@secret-momo/utils 1.9.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 +33 -48
  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
@@ -0,0 +1,8 @@
1
+ export function createLogs(client) {
2
+ return {
3
+ stream: (options = {}) => client.response('GET', '/logs', {
4
+ ...options,
5
+ query: { level: options.level, format: options.structured ? 'structured' : undefined },
6
+ }),
7
+ };
8
+ }
@@ -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 MihomoMemoryModule {
4
4
  /** GET `/memory`:获取实时内存占用 HTTP 流,数据包含 `inuse` 和固定为 0 的 `oslimit`(单位:字节)。 */
5
5
  stream(options?: MihomoRequestOptions): Promise<Response>;
@@ -0,0 +1,3 @@
1
+ export function createMemory(client) {
2
+ return { stream: (options) => client.response('GET', '/memory', options) };
3
+ }
@@ -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 MihomoProxiesModule {
4
4
  /** GET `/proxies`:获取所有代理及策略组;以名称为键,包含类型、可用性与延迟历史等信息。 */
5
5
  list(options?: MihomoRequestOptions): Promise<Record<string, MihomoProxy>>;
@@ -0,0 +1,17 @@
1
+ import { encodePathSegment } from './client.js';
2
+ export function createProxies(client) {
3
+ return {
4
+ list: async (options) => (await client.json('GET', '/proxies', options))
5
+ .proxies,
6
+ get: (name, options) => client.json('GET', `/proxies/${encodePathSegment(name)}`, options),
7
+ select: (groupName, proxyName, options) => client.empty('PUT', `/proxies/${encodePathSegment(groupName)}`, {
8
+ ...options,
9
+ body: { name: proxyName },
10
+ }),
11
+ clearFixed: (name, options) => client.empty('DELETE', `/proxies/${encodePathSegment(name)}`, options),
12
+ delay: (name, options) => client.json('GET', `/proxies/${encodePathSegment(name)}/delay`, {
13
+ ...options,
14
+ query: { url: options.url, timeout: options.timeout, expected: options.expected },
15
+ }),
16
+ };
17
+ }
@@ -1,5 +1,5 @@
1
- import { type MihomoClient } from './client';
2
- import type { MihomoDelayOptions, MihomoProxy, MihomoProxyProvider, MihomoRequestOptions } from './types';
1
+ import { type MihomoClient } from './client.js';
2
+ import type { MihomoDelayOptions, MihomoProxy, MihomoProxyProvider, MihomoRequestOptions } from './types.js';
3
3
  export interface MihomoProxyProvidersModule {
4
4
  /** GET `/providers/proxies`:获取全部代理集合及其元信息和代理列表。 */
5
5
  list(options?: MihomoRequestOptions): Promise<Record<string, MihomoProxyProvider>>;
@@ -0,0 +1,15 @@
1
+ import { encodePathSegment } from './client.js';
2
+ export function createProxyProviders(client) {
3
+ const providerPath = (name) => `/providers/proxies/${encodePathSegment(name)}`;
4
+ return {
5
+ list: async (options) => (await client.json('GET', '/providers/proxies', options)).providers,
6
+ get: (name, options) => client.json('GET', providerPath(name), options),
7
+ update: (name, options) => client.empty('PUT', providerPath(name), options),
8
+ healthcheck: (name, options) => client.empty('GET', `${providerPath(name)}/healthcheck`, options),
9
+ getProxy: (provider, name, options) => client.json('GET', `${providerPath(provider)}/${encodePathSegment(name)}`, options),
10
+ healthcheckProxy: (provider, name, options) => client.json('GET', `${providerPath(provider)}/${encodePathSegment(name)}/healthcheck`, {
11
+ ...options,
12
+ query: { url: options.url, timeout: options.timeout },
13
+ }),
14
+ };
15
+ }
@@ -1,5 +1,5 @@
1
- import { type MihomoClient } from './client';
2
- import type { MihomoRequestOptions, MihomoRuleProvider } from './types';
1
+ import { type MihomoClient } from './client.js';
2
+ import type { MihomoRequestOptions, MihomoRuleProvider } from './types.js';
3
3
  export interface MihomoRuleProvidersModule {
4
4
  /** GET `/providers/rules`:获取全部规则集合,并以集合名称为键返回。 */
5
5
  list(options?: MihomoRequestOptions): Promise<Record<string, MihomoRuleProvider>>;
@@ -0,0 +1,7 @@
1
+ import { encodePathSegment } from './client.js';
2
+ export function createRuleProviders(client) {
3
+ return {
4
+ list: async (options) => (await client.json('GET', '/providers/rules', options)).providers,
5
+ update: (name, options) => client.empty('PUT', `/providers/rules/${encodePathSegment(name)}`, options),
6
+ };
7
+ }
@@ -1,5 +1,5 @@
1
- import type { MihomoClient } from './client';
2
- import type { MihomoRequestOptions, MihomoRule } from './types';
1
+ import type { MihomoClient } from './client.js';
2
+ import type { MihomoRequestOptions, MihomoRule } from './types.js';
3
3
  export interface MihomoRulesModule {
4
4
  /** GET `/rules`:获取规则数组,包括索引、类型、匹配内容、目标代理和命中统计。 */
5
5
  list(options?: MihomoRequestOptions): Promise<MihomoRule[]>;
@@ -0,0 +1,6 @@
1
+ export function createRules(client) {
2
+ return {
3
+ list: async (options) => (await client.json('GET', '/rules', options)).rules,
4
+ setDisabled: (values, options) => client.empty('PATCH', '/rules/disable', { ...options, body: values }),
5
+ };
6
+ }
@@ -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 MihomoStorageModule {
4
4
  /** GET `/storage/:key`:读取指定 key 的 JSON 值;不存在时返回 `null`。 */
5
5
  get<T = unknown>(key: string, options?: MihomoRequestOptions): Promise<T | null>;
@@ -0,0 +1,9 @@
1
+ import { encodePathSegment } from './client.js';
2
+ export function createStorage(client) {
3
+ const path = (key) => `/storage/${encodePathSegment(key)}`;
4
+ return {
5
+ get: (key, options) => client.json('GET', path(key), options),
6
+ set: (key, value, options) => client.empty('PUT', path(key), { ...options, body: value }),
7
+ delete: (key, options) => client.empty('DELETE', path(key), options),
8
+ };
9
+ }
@@ -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 MihomoTrafficModule {
4
4
  /** GET `/traffic`:获取实时流量 HTTP 流;数据含每秒 up/down 及累计 upTotal/downTotal(单位:字节)。 */
5
5
  stream(options?: MihomoRequestOptions): Promise<Response>;
@@ -0,0 +1,3 @@
1
+ export function createTraffic(client) {
2
+ return { stream: (options) => client.response('GET', '/traffic', options) };
3
+ }
@@ -1,15 +1,16 @@
1
- /** Options accepted by every mihomo API method. */
1
+ /** 所有 mihomo API 方法通用的请求选项。 */
2
2
  export interface MihomoRequestOptions {
3
3
  signal?: AbortSignal | null;
4
4
  headers?: RequestInit['headers'];
5
5
  }
6
6
  export interface MihomoOptions {
7
- /** External controller address. Defaults to `http://127.0.0.1:9090`. */
7
+ /** external-controller 地址,默认为 `http://127.0.0.1:9090`。 */
8
8
  baseUrl?: string | URL;
9
- /** The `secret` configured for mihomo's external controller. */
9
+ /** mihomo external-controller 配置中的 secret。 */
10
10
  secret?: string;
11
11
  }
12
- export type MihomoMode = 'rule' | 'global' | 'direct' | string;
12
+ /** 提示常见模式,同时允许内核扩展的其他字符串。 */
13
+ export type MihomoMode = 'rule' | 'global' | 'direct' | (string & {});
13
14
  export type MihomoLogLevel = 'info' | 'warning' | 'error' | 'debug';
14
15
  export interface MihomoVersion {
15
16
  meta: boolean;
@@ -0,0 +1 @@
1
+ export {};
@@ -1,5 +1,5 @@
1
- import type { MihomoClient } from './client';
2
- import type { MihomoPathPayload, MihomoRequestOptions, MihomoUpgradeResult } from './types';
1
+ import type { MihomoClient } from './client.js';
2
+ import type { MihomoPathPayload, MihomoRequestOptions, MihomoUpgradeResult } from './types.js';
3
3
  export interface MihomoUpgradeModule {
4
4
  /** POST `/upgrade`:更新 mihomo 内核;可用 `channel` 指定通道、`force` 强制更新,成功返回 `{ status: 'ok' }`。 */
5
5
  core(payload?: MihomoPathPayload, options?: MihomoRequestOptions & {
@@ -0,0 +1,11 @@
1
+ export function createUpgrade(client) {
2
+ return {
3
+ core: (payload, options = {}) => client.json('POST', '/upgrade', {
4
+ ...options,
5
+ body: payload,
6
+ query: { channel: options.channel, force: options.force },
7
+ }),
8
+ ui: (options) => client.json('POST', '/upgrade/ui', options),
9
+ geo: (payload, options) => client.empty('POST', '/upgrade/geo', { ...options, body: payload }),
10
+ };
11
+ }
@@ -1,5 +1,5 @@
1
- import type { MihomoClient } from './client';
2
- import type { MihomoRequestOptions, MihomoVersion } from './types';
1
+ import type { MihomoClient } from './client.js';
2
+ import type { MihomoRequestOptions, MihomoVersion } from './types.js';
3
3
  export interface MihomoVersionModule {
4
4
  /** GET `/version`:获取 mihomo 版本号,以及是否为 Meta 版本的标识。 */
5
5
  get(options?: MihomoRequestOptions): Promise<MihomoVersion>;
@@ -0,0 +1,3 @@
1
+ export function createVersion(client) {
2
+ return { get: (options) => client.json('GET', '/version', options) };
3
+ }
@@ -1,4 +1,6 @@
1
+ /** 使用原生 toFixed 舍入二进制浮点值,不保证十进制中点的精确四舍五入。 */
1
2
  export declare function fixed2(n: number): number;
3
+ /** 使用原生 toFixed 保留四位小数后转换为数字。 */
2
4
  export declare function fixed4(n: number): number;
3
5
  /**
4
6
  * 将数字转为百分比字符串,如:12.34%
package/dist/num.js ADDED
@@ -0,0 +1,19 @@
1
+ /** 使用原生 toFixed 舍入二进制浮点值,不保证十进制中点的精确四舍五入。 */
2
+ export function fixed2(n) {
3
+ return Number(n.toFixed(2));
4
+ }
5
+ /** 使用原生 toFixed 保留四位小数后转换为数字。 */
6
+ export function fixed4(n) {
7
+ return Number(n.toFixed(4));
8
+ }
9
+ /**
10
+ * 将数字转为百分比字符串,如:12.34%
11
+ *
12
+ * @param n 数字,如:0.1234
13
+ * @returns 百分比字符串,如:12.34%
14
+ */
15
+ export function toPercentage(n) {
16
+ if (n === undefined)
17
+ return '-';
18
+ return `${fixed2(n * 100)}%`;
19
+ }
package/dist/pino.js ADDED
@@ -0,0 +1,13 @@
1
+ import pino from 'pino';
2
+ const logger = pino({
3
+ level: 'info',
4
+ transport: {
5
+ target: 'pino-pretty',
6
+ options: {
7
+ colorize: true,
8
+ translateTime: 'SYS:yyyy-mm-dd HH:MM:ss', // 使用系统时间,默认按 UTC 显示时间。
9
+ ignore: 'pid,hostname',
10
+ },
11
+ },
12
+ });
13
+ export { pino, logger };
@@ -0,0 +1,19 @@
1
+ import { isIP } from 'node:net';
2
+ /**
3
+ * 获取当前电脑访问互联网时使用的公网出网 IP 地址。
4
+ */
5
+ export async function getPublicIp() {
6
+ const response = await globalThis.fetch('https://api.ipify.org?format=json', {
7
+ headers: { Accept: 'application/json' },
8
+ });
9
+ if (!response.ok) {
10
+ // 错误响应体无人消费;取消它,且不让清理异常覆盖 HTTP 状态错误。
11
+ await response.body?.cancel().catch(() => { });
12
+ throw new Error(`Failed to get public IP: ${response.status} ${response.statusText}`);
13
+ }
14
+ const body = (await response.json());
15
+ if (!body || typeof body.ip !== 'string' || isIP(body.ip) === 0) {
16
+ throw new TypeError('Public IP service returned an invalid response');
17
+ }
18
+ return body.ip;
19
+ }
@@ -0,0 +1,3 @@
1
+ /** 等待指定时长;可通过 signal 取消并以 signal.reason 拒绝。 */
2
+ export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
3
+ export declare function sleep_random(): Promise<void>;
package/dist/sleep.js ADDED
@@ -0,0 +1,21 @@
1
+ /** 等待指定时长;可通过 signal 取消并以 signal.reason 拒绝。 */
2
+ export function sleep(ms, signal) {
3
+ return new Promise((resolve, reject) => {
4
+ if (signal?.aborted) {
5
+ reject(signal.reason);
6
+ return;
7
+ }
8
+ const onAbort = () => {
9
+ clearTimeout(timer);
10
+ reject(signal?.reason);
11
+ };
12
+ const timer = setTimeout(() => {
13
+ signal?.removeEventListener('abort', onAbort);
14
+ resolve();
15
+ }, ms);
16
+ signal?.addEventListener('abort', onAbort, { once: true });
17
+ });
18
+ }
19
+ export function sleep_random() {
20
+ return sleep(Math.floor(Math.random() * 500) + 750);
21
+ }
@@ -1,5 +1,5 @@
1
1
  /**
2
- * 移除 url 中的 query 参数,并去掉末尾的 /
2
+ * 移除 query 参数与路径末尾一个 /,保留 fragment,支持相对地址。
3
3
  */
4
4
  export declare function removeQueryParams(url: string): string;
5
5
  export declare function getRedirectUrl(url: string): Promise<string>;
package/dist/url.js ADDED
@@ -0,0 +1,29 @@
1
+ import { fetch } from './fetch.js';
2
+ /**
3
+ * 移除 query 参数与路径末尾一个 /,保留 fragment,支持相对地址。
4
+ */
5
+ export function removeQueryParams(url) {
6
+ const hashIndex = url.indexOf('#');
7
+ const prefix = hashIndex === -1 ? url : url.slice(0, hashIndex);
8
+ const fragment = hashIndex === -1 ? '' : url.slice(hashIndex);
9
+ const queryIndex = prefix.indexOf('?');
10
+ const pathname = queryIndex === -1 ? prefix : prefix.slice(0, queryIndex);
11
+ return (pathname.endsWith('/') ? pathname.slice(0, -1) : pathname) + fragment;
12
+ }
13
+ export async function getRedirectUrl(url) {
14
+ const res = await fetch(url, {
15
+ redirect: 'manual',
16
+ });
17
+ try {
18
+ // 仅处理 Fetch 定义的重定向状态,排除缓存验证等其他 3xx 状态。
19
+ if ([301, 302, 303, 307, 308].includes(res.status)) {
20
+ const location = res.headers.get('location');
21
+ return location ? new URL(location, url).href : url;
22
+ }
23
+ return url;
24
+ }
25
+ finally {
26
+ // 只需响应头;清理失败不能覆盖结果或 URL 解析错误。
27
+ await res.body?.cancel().catch(() => { });
28
+ }
29
+ }
@@ -1,2 +1,3 @@
1
+ /** 生成 0–65536 位字母数字 ID;长度必须为整数,遵循 Web Crypto 单次取样上限。 */
1
2
  export declare function genId(len?: number): string;
2
3
  export declare function uuidv4(): `${string}-${string}-${string}-${string}-${string}`;
package/dist/uuid.js ADDED
@@ -0,0 +1,16 @@
1
+ /** 生成 0–65536 位字母数字 ID;长度必须为整数,遵循 Web Crypto 单次取样上限。 */
2
+ export function genId(len = 10) {
3
+ if (!Number.isInteger(len) || len < 0 || len > 65536) {
4
+ throw new RangeError('len 必须是 0 到 65536 之间的整数');
5
+ }
6
+ const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
7
+ let result = '';
8
+ const bytes = crypto.getRandomValues(new Uint8Array(len));
9
+ for (let i = 0; i < len; i++) {
10
+ result += chars[bytes[i] % chars.length];
11
+ }
12
+ return result;
13
+ }
14
+ export function uuidv4() {
15
+ return crypto.randomUUID();
16
+ }
package/package.json CHANGED
@@ -1,65 +1,50 @@
1
1
  {
2
2
  "name": "@secret-momo/utils",
3
- "version": "1.9.0",
4
- "module": "src/index.ts",
3
+ "version": "2.0.0",
4
+ "description": "常用工具函数、资源下载和 Mihomo API 客户端。",
5
5
  "type": "module",
6
- "engines": {
7
- "node": "24.19.0"
8
- },
9
- "publishConfig": {
10
- "access": "public",
11
- "registry": "https://registry.npmjs.org/"
12
- },
6
+ "license": "MIT",
13
7
  "repository": {
14
8
  "type": "git",
15
- "url": "git+https://github.com/secretmomo/utils.git"
9
+ "url": "git+https://github.com/secretmomo/npm-packages.git",
10
+ "directory": "packages/utils"
16
11
  },
17
- "files": [
18
- "lib"
19
- ],
20
- "main": "./lib/index.js",
21
- "types": "./lib/index.d.ts",
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
22
14
  "exports": {
23
15
  ".": {
24
- "types": "./lib/index.d.ts",
25
- "import": "./lib/index.js"
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
+ },
19
+ "./fetch": {
20
+ "types": "./dist/fetch.d.ts",
21
+ "import": "./dist/fetch.js"
22
+ },
23
+ "./pino": {
24
+ "types": "./dist/pino.d.ts",
25
+ "import": "./dist/pino.js"
26
26
  }
27
27
  },
28
- "lint-staged": {
29
- "*.{ts,tsx,js,jsx}": [
30
- "bunx eslint --fix",
31
- "bunx prettier --write"
32
- ],
33
- "*.{json,md}": [
34
- "bunx prettier --write"
35
- ]
36
- },
37
- "scripts": {
38
- "prepublishOnly": "bun run build",
39
- "build": "rm -rf lib && rollup -c && tsc -p tsconfig.build.json",
40
- "typecheck": "tsc --noEmit"
28
+ "files": [
29
+ "dist"
30
+ ],
31
+ "engines": {
32
+ "node": ">=26"
41
33
  },
42
- "devDependencies": {
43
- "@eslint/config-helpers": "0.7.0",
44
- "@eslint/js": "10.0.1",
45
- "@types/bun": "1.4.2",
46
- "eslint": "10.12.0",
47
- "eslint-plugin-import-x": "4.17.1",
48
- "eslint-plugin-react": "7.37.5",
49
- "eslint-plugin-react-hooks": "7.1.1",
50
- "eslint-plugin-unused-imports": "4.4.1",
51
- "husky": "9.1.7",
52
- "jiti": "2.7.0",
53
- "lint-staged": "17.6.0",
54
- "prettier": "3.9.9",
55
- "rollup": "4.64.1",
56
- "rollup-plugin-esbuild": "6.2.1",
57
- "typescript": "6.0.3",
58
- "typescript-eslint": "8.71.1"
34
+ "publishConfig": {
35
+ "access": "public",
36
+ "registry": "https://registry.npmjs.org/"
59
37
  },
60
38
  "dependencies": {
39
+ "@types/node": "26.6.6",
61
40
  "dayjs": "1.11.23",
62
41
  "pino": "10.4.0",
63
42
  "pino-pretty": "13.2.0"
43
+ },
44
+ "scripts": {
45
+ "build": "tsc -p tsconfig.build.json",
46
+ "typecheck": "tsc -p tsconfig.json --noEmit",
47
+ "test": "vitest run --config ../../vitest.config.mts",
48
+ "test:runtime": "node --test tests/runtime.test.mjs"
64
49
  }
65
- }
50
+ }
package/lib/date-time.js DELETED
@@ -1 +0,0 @@
1
- import r from"dayjs";function Y(t="YYYY-MM-DD HH:mm:ss"){return r().format(t)}function e(t="YYYY-MM-DD"){return r().format(t)}function a(t="YYYY-MM-DD"){return r().subtract(1,"day").format(t)}function n(t,o="YYYY-MM-DD"){return r(t).format(o)}export{Y as dateTimeToNow,e as dateToNow,n as timestampToDate,a as yesterdayDate};
@@ -1 +0,0 @@
1
- import{mkdirSync as f,existsSync as m}from"node:fs";import{rm as l}from"node:fs/promises";import{join as d,basename as p}from"node:path";import{execFile as w}from"node:child_process";import{promisify as E}from"node:util";import{uuidv4 as h}from"../uuid.js";import{fetch as y}from"../fetch.js";import{logger as D}from"../pino.js";import{pickVideoExtension as g}from"./extension.js";import{fileSize as F}from"../file.js";const n=E(w),c=D.child({name:"aria2DownloadVideo"});async function S(r,a){const i=[r,`${r}.aria2`].filter(t=>!a.has(t)),e=(await Promise.allSettled(i.map(t=>l(t,{force:!0})))).flatMap(t=>t.status==="rejected"?[t.reason]:[]);e.length>0&&c.error(new AggregateError(e,"\u6E05\u7406 aria2 \u4E0B\u8F7D\u4E2D\u95F4\u4EA7\u7269\u5931\u8D25"))}async function x(){try{await n("aria2c",["--version"])}catch(r){throw r.code==="ENOENT"?new Error("\u672A\u627E\u5230 aria2c \u547D\u4EE4\u884C\u5DE5\u5177\uFF0C\u8BF7\u5148\u4F7F\u7528 brew install aria2 \u5B89\u88C5\u3002",{cause:r}):r}}async function A(r,a){try{return(await y(r,{method:"HEAD",...a?{headers:{Referer:a}}:{}})).headers.get("content-type")}catch{return null}}async function $({url:r,dir:a,referer:i}){await x();let e;const t=new Set;try{f(a,{recursive:!0});const o=g(r,await A(r,i));e=d(a,`${h()}.${o}`);for(const u of[e,`${e}.aria2`])m(u)&&t.add(u);const s=["-x8","-s8","-k1M","--auto-file-renaming=false",...i?["--referer",i]:[],"-d",a,"-o",p(e),r];return await n("aria2c",s),{isSuccess:!0,filePath:e,fileSize:await F(e)}}catch(o){return e&&await S(e,t),c.error(o),{isSuccess:!1,error:o}}}export{$ as aria2DownloadVideo};
@@ -1 +0,0 @@
1
- const a=new Set(["mp4","webm","mov","m4v","mkv","avi","ogv"]),v=new Set(["jpg","jpeg","png","gif","webp","svg","bmp","avif","ico"]),r={"video/mp4":"mp4","video/webm":"webm","video/quicktime":"mov","video/x-m4v":"m4v","video/x-matroska":"mkv","video/x-msvideo":"avi","video/ogg":"ogv"},c={"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/x-ms-bmp":"bmp","image/avif":"avif","image/x-icon":"ico"};function g(e,i){try{const{pathname:m}=new URL(e),n=m.split("/").pop()??"",o=/\.([a-zA-Z0-9]+)$/.exec(n);if(!o?.[1])return null;const t=o[1].toLowerCase();return i.has(t)?t:null}catch{return null}}function p(e,i){if(!e)return null;const m=e.split(";")[0]?.trim().toLowerCase()??"";return i[m]??null}function s(e,i){return g(e,a)??p(i,r)??"mp4"}function u(e,i){const m=g(e,v);if(m==="jpeg")return"jpg";const n=p(i,c);return m??n??"jpg"}export{u as pickImageExtension,s as pickVideoExtension};
@@ -1 +0,0 @@
1
- import{mkdirSync as c,createWriteStream as d}from"node:fs";import{rm as h}from"node:fs/promises";import{join as m}from"node:path";import{Readable as l}from"node:stream";import{pipeline as f}from"node:stream/promises";import{fetch as s}from"../fetch.js";import{uuidv4 as w}from"../uuid.js";import{pickImageExtension as u,pickVideoExtension as y}from"./extension.js";import{logger as n}from"../pino.js";import{aria2DownloadVideo as z}from"./aria2.js";import{fileSize as b}from"../file.js";async function p(e,a){if(e)try{await h(e,{force:!0})}catch(t){n.child({name:a,filePath:e}).error(t,"Failed to remove partial download")}}async function g({url:e,dir:a}){let t;try{c(a,{recursive:!0});const o=await s(e);if(!o.ok)throw await o.body?.cancel().catch(()=>{}),new Error(`Download failed: HTTP ${o.status}`);if(!o.body)throw new Error("Response has no body");const i=y(e,o.headers.get("content-type")),r=m(a,`${w()}.${i}`);return await f(l.fromWeb(o.body),d(r).once("open",()=>{t=r})),r}catch(o){return n.child({name:"downloadVideo"}).error(o),await p(t,"downloadVideo"),null}}async function E({url:e,dir:a}){let t;try{c(a,{recursive:!0});const o=await s(e);if(!o.ok)throw await o.body?.cancel().catch(()=>{}),new Error(`Download failed: HTTP ${o.status}`);if(!o.body)throw new Error("Response has no body");const i=u(e,o.headers.get("content-type")),r=m(a,`${w()}.${i}`);return await f(l.fromWeb(o.body),d(r).once("open",()=>{t=r})),{isSuccess:!0,filePath:r,fileSize:await b(r)}}catch(o){return n.child({name:"downloadImage"}).error(o),await p(t,"downloadImage"),{isSuccess:!1,error:o}}}export{z as aria2DownloadVideo,E as downloadImage,g as downloadVideo};
package/lib/env.d.ts DELETED
@@ -1,9 +0,0 @@
1
- /**
2
- * 从指定目录开始向上查找仓库根目录。
3
- *
4
- * `.git` 适用于常规 Git 仓库,`bun.lock` 和声明了 `workspaces` 的
5
- * `package.json` 则用于识别未携带 Git 元数据的 Bun/monorepo 工作区。
6
- * 搜索会优先返回离 `from` 最近的匹配目录。
7
- */
8
- export declare function findRepoRoot(from: string): string;
9
- export declare function getNodeName(): string;
package/lib/env.js DELETED
@@ -1 +0,0 @@
1
- import{execSync as c}from"node:child_process";import{existsSync as i,readFileSync as a}from"node:fs";import{join as u,dirname as l}from"node:path";function p(r){let e=r;for(;;){if(i(u(e,".git"))||i(u(e,"bun.lock")))return e;const n=u(e,"package.json");if(i(n)&&JSON.parse(a(n,"utf8")).workspaces)return e;const o=l(e);if(o===e)break;e=o}throw new Error("\u672A\u627E\u5230\u4ED3\u5E93\u6839\u76EE\u5F55\uFF08\u7F3A\u5C11 .git / bun.lock / \u542B workspaces \u7684 package.json\uFF09")}let t=null;function m(){if(t)return t;try{const r=c("system_profiler SPHardwareDataType",{encoding:"utf-8",stdio:["pipe","pipe","ignore"]}),e=n=>{const o=new RegExp(`${n}:\\s+(.+)`);return r.match(o)?.[1]?.trim()??null};return t={modelName:e("Model Name"),modelIdentifier:e("Model Identifier"),chip:e("Chip")||e("Processor Name"),raw:r},t}catch{return{modelName:null,modelIdentifier:null,chip:null,raw:""}}}function s(){const{modelName:r,chip:e}=m();return`${r}(${e})`}export{p as findRepoRoot,s as getNodeName};
package/lib/fetch.d.ts DELETED
@@ -1,13 +0,0 @@
1
- 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";
2
- 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";
3
- /**
4
- * 对 `globalThis.fetch` 的轻量封装:
5
- * - 最多重试 `MAX_RETRIES` 次(默认 5 次),总尝试次数为 `MAX_RETRIES + 1`。
6
- * - 仅在可重试异常(如超时、连接重置、网络错误)时重试。
7
- * - 重试间隔采用指数退避:`2^attempt` 秒,即 `1s, 2s, 4s, 8s, 16s`。
8
- * - 若有效请求信号已中止(优先使用 `init.signal`,否则使用 `Request.signal`),则不会重试。
9
- */
10
- export declare function fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
11
- export declare function fetchText(input: string | URL | Request, init?: RequestInit): Promise<string>;
12
- export declare function fetchHtml(input: string | URL | Request, init?: RequestInit): Promise<string>;
13
- export declare function fetchJson(input: string | URL | Request, init?: RequestInit): Promise<unknown>;
package/lib/fetch.js DELETED
@@ -1 +0,0 @@
1
- import{logger as F}from"./pino.js";import{sleep as w}from"./sleep.js";const a=5,h="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",S="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";function m(e){return e instanceof Request?e.url:e.toString()}function u(e,t,o){const r=new Headers(t?.headers??(e instanceof Request?e.headers:void 0));return new Headers(o).forEach((n,c)=>{r.has(c)||r.set(c,n)}),{...t,headers:r}}function p(e){try{return new URL(e).origin}catch{return e}}function C(e){return p(e)+"/"}function x(e){const t=e,o=t?.name??"Error",r=t?.message??String(e),n=t?.cause?.code?` [code=${String(t.cause.code)}]`:"";return`${o}: ${r}${n}`}function A(e,t){if(t?.aborted)return!1;const o=e,r=(o?.message??String(e)).toLowerCase(),n=String(o?.cause?.code??"").toLowerCase(),c=["network","socket","econnreset","econnrefused","etimedout","timeout","failed to fetch","unable to connect","certificate","unknown cert","ssl","tls"].some(i=>r.includes(i)),s=["econnreset","econnrefused","etimedout"].some(i=>n===i);return o?.name==="TimeoutError"||o?.name==="AbortError"||c||s}async function l(e,t){const o=t?.signal!==void 0?t.signal??void 0:e instanceof Request?e.signal:void 0,r=m(e);t=u(e,t,{"Accept-Language":"zh-CN,zh;q=0.9,en;q=0.8",Referer:C(r),"User-Agent":h});for(let n=0;n<=a;n++)try{return await globalThis.fetch(e,t)}catch(c){if(!(n<a&&A(c,o)))throw c;const s=a+1,i=n+1,f=Math.pow(2,n),g=a-n-1;F.warn(`\u8BF7\u6C42\u5931\u8D25\uFF0C\u7B2C ${i}/${s} \u6B21\u5C1D\u8BD5\uFF0C${f}s \u540E\u91CD\u8BD5\uFF08\u5269\u4F59 ${g} \u6B21\uFF09\uFF1A${r}\uFF1B\u9519\u8BEF\uFF1A${x(c)}`),await w(1e3*f)}throw new Error("Unexpected fetch retry failure")}async function d(e,t){return(await l(e,t)).text()}async function y(e,t){return t=u(e,t,{Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8","Cache-Control":"no-cache","Content-Type":"text/html",Pragma:"no-cache","Upgrade-Insecure-Requests":"1","Sec-Fetch-Site":"none","Sec-Fetch-Mode":"navigate","Sec-Fetch-User":"?1","Sec-Fetch-Dest":"document"}),await d(e,t)}async function b(e,t){return t=u(e,t,{Accept:"application/json, text/plain, */*",Connection:"keep-alive","Content-Type":"application/json",Origin:p(m(e)),"Sec-Fetch-Site":"same-site","Sec-Fetch-Mode":"cors","Sec-Fetch-Dest":"empty"}),(await l(e,t)).json()}export{l as fetch,y as fetchHtml,b as fetchJson,d as fetchText,S as mobileUserAgent,h as userAgent};
package/lib/file.js DELETED
@@ -1 +0,0 @@
1
- import{statSync as r}from"node:fs";const n=["B","KB","MB","GB","TB"];function i(t){if(t<1024)return`${t}B`;const o=Math.min(Math.floor(Math.log(t)/Math.log(1024)),n.length-1);return`${(t/1024**o).toFixed(2)}${n[o]}`}async function e(t){const{size:o}=r(t);return i(o)}export{e as fileSize};
package/lib/index.d.ts DELETED
@@ -1,12 +0,0 @@
1
- export * from './download';
2
- export * from './date-time';
3
- export * from './env';
4
- export * from './fetch';
5
- export * from './file';
6
- export * from './num';
7
- export * from './pino';
8
- export * from './public-ip';
9
- export * from './sleep';
10
- export * from './uuid';
11
- export * from './url';
12
- export * from './mihomo';
package/lib/index.js DELETED
@@ -1 +0,0 @@
1
- import{downloadImage as r,downloadVideo as t}from"./download/index.js";import{dateTimeToNow as f,dateToNow as p,timestampToDate as a,yesterdayDate as d}from"./date-time.js";import{findRepoRoot as x,getNodeName as l}from"./env.js";import{fetch as g,fetchHtml as s,fetchJson as c,fetchText as h,mobileUserAgent as u,userAgent as w}from"./fetch.js";import{fileSize as N}from"./file.js";import{fixed2 as D,fixed4 as I,toPercentage as M}from"./num.js";import{logger as R}from"./pino.js";import{getPublicIp as v}from"./public-ip.js";import{sleep as H,sleep_random as U}from"./sleep.js";import{genId as z,uuidv4 as C}from"./uuid.js";import{getRedirectUrl as J,removeQueryParams as Q}from"./url.js";import{createMihomo as _}from"./mihomo/index.js";import{MihomoClient as k,MihomoHttpError as q}from"./mihomo/client.js";import{aria2DownloadVideo as F}from"./download/aria2.js";import{default as K}from"pino";export{k as MihomoClient,q as MihomoHttpError,F as aria2DownloadVideo,_ as createMihomo,f as dateTimeToNow,p as dateToNow,r as downloadImage,t as downloadVideo,g as fetch,s as fetchHtml,c as fetchJson,h as fetchText,N as fileSize,x as findRepoRoot,D as fixed2,I as fixed4,z as genId,l as getNodeName,v as getPublicIp,J as getRedirectUrl,R as logger,u as mobileUserAgent,K as pino,Q as removeQueryParams,H as sleep,U as sleep_random,a as timestampToDate,M as toPercentage,w as userAgent,C as uuidv4,d as yesterdayDate};
@@ -1 +0,0 @@
1
- function h(c){return{flushFakeIp:e=>c.empty("POST","/cache/fakeip/flush",e),flushDns:e=>c.empty("POST","/cache/dns/flush",e)}}export{h as createCache};
@@ -1,25 +0,0 @@
1
- import type { MihomoOptions, MihomoRequestOptions } from './types';
2
- export declare class MihomoHttpError extends Error {
3
- readonly response: Response;
4
- readonly body: string;
5
- constructor(response: Response, body: string);
6
- }
7
- export declare class MihomoClient {
8
- private readonly baseUrl;
9
- private readonly secret?;
10
- constructor(options: MihomoOptions);
11
- url(path: string, query?: Record<string, string | number | boolean | undefined>): string;
12
- response(method: string, path: string, options?: MihomoRequestOptions & {
13
- body?: unknown;
14
- query?: Record<string, string | number | boolean | undefined>;
15
- }): Promise<Response>;
16
- json<T>(method: string, path: string, options?: MihomoRequestOptions & {
17
- body?: unknown;
18
- query?: Record<string, string | number | boolean | undefined>;
19
- }): Promise<T>;
20
- empty(method: string, path: string, options?: MihomoRequestOptions & {
21
- body?: unknown;
22
- query?: Record<string, string | number | boolean | undefined>;
23
- }): Promise<void>;
24
- }
25
- export declare function encodePathSegment(value: string): string;
@@ -1 +0,0 @@
1
- class a extends Error{constructor(t,s){super(`Mihomo request failed: ${t.status} ${t.statusText}`),this.response=t,this.body=s,this.name="MihomoHttpError"}response;body}class h{baseUrl;secret;constructor(t){const s=new URL(t.baseUrl?.toString()??"http://127.0.0.1:9090");s.search="",s.hash="";const e=s.toString().replace(/\/+$/,"");this.baseUrl=e,this.secret=t.secret}url(t,s){const e=new URL(`${this.baseUrl}${t}`);for(const[r,o]of Object.entries(s??{}))o!==void 0&&e.searchParams.set(r,String(o));return e.toString()}async response(t,s,e={}){const r=new Headers(e.headers);this.secret&&!r.has("Authorization")&&r.set("Authorization",`Bearer ${this.secret}`);let o;e.body!==void 0&&(o=JSON.stringify(e.body),r.has("Content-Type")||r.set("Content-Type","application/json"));const n=await globalThis.fetch(this.url(s,e.query),{method:t,headers:r,body:o,signal:e.signal??void 0});if(!n.ok)throw new a(n,await n.text());return n}async json(t,s,e){return(await this.response(t,s,e)).json()}async empty(t,s,e){await this.response(t,s,e)}}function c(i){return encodeURIComponent(i)}export{h as MihomoClient,a as MihomoHttpError,c as encodePathSegment};
@@ -1 +0,0 @@
1
- function r(t){return{get:e=>t.json("GET","/configs",e),reload:(e,o={})=>t.empty("PUT","/configs",{...o,body:e,query:{force:o.force}}),patch:(e,o)=>t.empty("PATCH","/configs",{...o,body:e}),updateGeo:(e,o)=>t.empty("POST","/configs/geo",{...o,body:e}),restart:(e,o)=>t.empty("POST","/restart",{...o,body:e})}}export{r as createConfigs};
@@ -1 +0,0 @@
1
- import{encodePathSegment as o}from"./client.js";function c(e){return{list:(n={})=>e.json("GET","/connections",{...n,query:{interval:n.interval}}),closeAll:n=>e.empty("DELETE","/connections",n),close:(n,t)=>e.empty("DELETE",`/connections/${o(n)}`,t)}}export{c as createConnections};
@@ -1 +0,0 @@
1
- function p(e){return{gc:r=>e.empty("PUT","/debug/gc",r),pprofUrl:()=>e.url("/debug/pprof")}}export{p as createDebug};
package/lib/mihomo/dns.js DELETED
@@ -1 +0,0 @@
1
- function u(e){return{query:(n,r,t)=>e.json("GET","/dns/query",{...t,query:{name:n,type:r}})}}export{u as createDns};
@@ -1 +0,0 @@
1
- import{encodePathSegment as o}from"./client.js";function u(r){return{list:async t=>(await r.json("GET","/group",t)).proxies,get:(t,e)=>r.json("GET",`/group/${o(t)}`,e),delay:(t,e)=>r.json("GET",`/group/${o(t)}/delay`,{...e,query:{url:e.url,timeout:e.timeout,expected:e.expected}})}}export{u as createGroups};