@secret-momo/utils 1.6.0 → 1.7.2
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/download/aria2.d.ts +1 -1
- package/lib/download/aria2.js +1 -1
- package/lib/download/index.d.ts +2 -2
- package/lib/download/index.js +1 -1
- package/lib/env.d.ts +8 -0
- package/lib/env.js +1 -1
- package/lib/fetch.d.ts +1 -1
- package/lib/fetch.js +1 -1
- package/lib/index.js +1 -1
- package/lib/url.js +1 -1
- package/package.json +15 -10
package/lib/download/aria2.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { DownloadOptions, DownloadResult } from './types';
|
|
|
4
4
|
*
|
|
5
5
|
* 下载前会检查本机是否安装 `aria2c`;若不存在会抛出异常,并提示通过
|
|
6
6
|
* `brew install aria2` 安装。下载时使用 `aria2c -x8 -s8 -k1M` 参数;如提供
|
|
7
|
-
* referer
|
|
7
|
+
* referer,则将其用于 HEAD 探测和 aria2c 下载,并根据 URL 或响应 `Content-Type` 推断视频扩展名。
|
|
8
8
|
*
|
|
9
9
|
* @param options 下载配置
|
|
10
10
|
* @param options.url 视频资源 URL
|
package/lib/download/aria2.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdirSync as
|
|
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};
|
package/lib/download/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export { aria2DownloadVideo };
|
|
|
4
4
|
/**
|
|
5
5
|
* 下载视频资源到指定目录。
|
|
6
6
|
*
|
|
7
|
-
* 会根据 URL 或响应 `Content-Type`
|
|
7
|
+
* 会根据 URL 或响应 `Content-Type` 推断视频扩展名,并用 UUID 生成文件名。
|
|
8
8
|
* 下载成功时返回保存后的文件路径;下载失败时记录日志并返回 `null`。
|
|
9
9
|
*
|
|
10
10
|
* @param options 下载配置
|
|
@@ -16,7 +16,7 @@ export declare function downloadVideo({ url, dir }: DownloadOptions): Promise<st
|
|
|
16
16
|
/**
|
|
17
17
|
* 下载图片资源到指定目录。
|
|
18
18
|
*
|
|
19
|
-
* 会根据 URL 或响应 `Content-Type`
|
|
19
|
+
* 会根据 URL 或响应 `Content-Type` 推断图片扩展名,并用 UUID 生成文件名。
|
|
20
20
|
* 下载成功时返回保存后的文件路径;下载失败时记录日志并返回 `null`。
|
|
21
21
|
*
|
|
22
22
|
* @param options 下载配置
|
package/lib/download/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mkdirSync as
|
|
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
CHANGED
|
@@ -1 +1,9 @@
|
|
|
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;
|
|
1
9
|
export declare function getNodeName(): string;
|
package/lib/env.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execSync as
|
|
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
CHANGED
|
@@ -5,7 +5,7 @@ export declare const mobileUserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5
|
|
|
5
5
|
* - 最多重试 `MAX_RETRIES` 次(默认 5 次),总尝试次数为 `MAX_RETRIES + 1`。
|
|
6
6
|
* - 仅在可重试异常(如超时、连接重置、网络错误)时重试。
|
|
7
7
|
* - 重试间隔采用指数退避:`2^attempt` 秒,即 `1s, 2s, 4s, 8s, 16s`。
|
|
8
|
-
* -
|
|
8
|
+
* - 若有效请求信号已中止(优先使用 `init.signal`,否则使用 `Request.signal`),则不会重试。
|
|
9
9
|
*/
|
|
10
10
|
export declare function fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
|
|
11
11
|
export declare function fetchText(input: string | URL | Request, init?: RequestInit): Promise<string>;
|
package/lib/fetch.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{logger as
|
|
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/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{downloadImage as r,downloadVideo as t}from"./download/index.js";import{dateTimeToNow as f,dateToNow as a,timestampToDate as d,yesterdayDate as p}from"./date-time.js";import{getNodeName as
|
|
1
|
+
import{downloadImage as r,downloadVideo as t}from"./download/index.js";import{dateTimeToNow as f,dateToNow as a,timestampToDate as d,yesterdayDate as p}from"./date-time.js";import{findRepoRoot as i,getNodeName as l}from"./env.js";import{fetch as g,fetchHtml as s,fetchJson as c,fetchText as u,mobileUserAgent as w,userAgent as T}from"./fetch.js";import{fileSize as N}from"./file.js";import{fixed2 as D,fixed4 as R,toPercentage as v}from"./num.js";import{logger as I}from"./pino.js";import{sleep as U,sleep_random as V}from"./sleep.js";import{genId as z,uuidv4 as H}from"./uuid.js";import{getRedirectUrl as Q,removeQueryParams as S}from"./url.js";import{aria2DownloadVideo as j}from"./download/aria2.js";import{default as q}from"pino";export{j as aria2DownloadVideo,f as dateTimeToNow,a as dateToNow,r as downloadImage,t as downloadVideo,g as fetch,s as fetchHtml,c as fetchJson,u as fetchText,N as fileSize,i as findRepoRoot,D as fixed2,R as fixed4,z as genId,l as getNodeName,Q as getRedirectUrl,I as logger,w as mobileUserAgent,q as pino,S as removeQueryParams,U as sleep,V as sleep_random,d as timestampToDate,v as toPercentage,T as userAgent,H as uuidv4,p as yesterdayDate};
|
package/lib/url.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{fetch as
|
|
1
|
+
import{fetch as n,userAgent as a}from"./fetch.js";function s(e){const t=e.split("?")[0]??e;return t.endsWith("/")?t.slice(0,-1):t}async function c(e){const t=await n(e,{method:"GET",redirect:"manual",headers:{"User-Agent":a}});try{if(t.status>=300&&t.status<400){const r=t.headers.get("location");return r?new URL(r,e).href:e}return e}finally{await t.body?.cancel().catch(()=>{})}}export{c as getRedirectUrl,s as removeQueryParams};
|
package/package.json
CHANGED
|
@@ -1,13 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@secret-momo/utils",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.2",
|
|
4
4
|
"module": "src/index.ts",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
7
7
|
"node": "24.19.0"
|
|
8
8
|
},
|
|
9
9
|
"publishConfig": {
|
|
10
|
-
"access": "public"
|
|
10
|
+
"access": "public",
|
|
11
|
+
"registry": "https://registry.npmjs.org/"
|
|
12
|
+
},
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/secretmomo/utils.git"
|
|
11
16
|
},
|
|
12
17
|
"files": [
|
|
13
18
|
"lib"
|
|
@@ -30,27 +35,27 @@
|
|
|
30
35
|
]
|
|
31
36
|
},
|
|
32
37
|
"scripts": {
|
|
33
|
-
"postinstall": "bun outdated",
|
|
34
38
|
"prepublishOnly": "bun run build",
|
|
35
|
-
"build": "rm -rf lib && rollup -c && tsc -p tsconfig.build.json"
|
|
39
|
+
"build": "rm -rf lib && rollup -c && tsc -p tsconfig.build.json",
|
|
40
|
+
"typecheck": "tsc --noEmit"
|
|
36
41
|
},
|
|
37
42
|
"devDependencies": {
|
|
38
43
|
"@eslint/config-helpers": "0.7.0",
|
|
39
44
|
"@eslint/js": "10.0.1",
|
|
40
|
-
"@types/bun": "1.4.
|
|
41
|
-
"eslint": "10.
|
|
45
|
+
"@types/bun": "1.4.2",
|
|
46
|
+
"eslint": "10.11.0",
|
|
42
47
|
"eslint-plugin-import-x": "4.17.1",
|
|
43
48
|
"eslint-plugin-react": "7.37.5",
|
|
44
49
|
"eslint-plugin-react-hooks": "7.1.1",
|
|
45
50
|
"eslint-plugin-unused-imports": "4.4.1",
|
|
46
51
|
"husky": "9.1.7",
|
|
47
52
|
"jiti": "2.7.0",
|
|
48
|
-
"lint-staged": "17.
|
|
49
|
-
"prettier": "3.9.
|
|
50
|
-
"rollup": "4.63.
|
|
53
|
+
"lint-staged": "17.5.1",
|
|
54
|
+
"prettier": "3.9.8",
|
|
55
|
+
"rollup": "4.63.4",
|
|
51
56
|
"rollup-plugin-esbuild": "6.2.1",
|
|
52
57
|
"typescript": "6.0.3",
|
|
53
|
-
"typescript-eslint": "8.
|
|
58
|
+
"typescript-eslint": "8.70.0"
|
|
54
59
|
},
|
|
55
60
|
"dependencies": {
|
|
56
61
|
"dayjs": "1.11.23",
|