@zfadhli/tokrec 0.15.0 → 0.16.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.
- package/README.md +126 -0
- package/dist/app/config.mjs.map +1 -1
- package/dist/app/job.mjs +39 -17
- package/dist/app/job.mjs.map +1 -1
- package/dist/app/logger.mjs +8 -16
- package/dist/app/logger.mjs.map +1 -1
- package/dist/app/loop.mjs +6 -3
- package/dist/app/loop.mjs.map +1 -1
- package/dist/app/recorder.d.mts.map +1 -1
- package/dist/app/recorder.mjs +25 -29
- package/dist/app/recorder.mjs.map +1 -1
- package/dist/core/plan.mjs.map +1 -1
- package/dist/core/verdict.d.mts +1 -1
- package/dist/core/verdict.mjs.map +1 -1
- package/dist/io/http.mjs +16 -24
- package/dist/io/http.mjs.map +1 -1
- package/dist/io/media/download.mjs +1 -1
- package/dist/io/media/ffmpeg.mjs +52 -6
- package/dist/io/media/ffmpeg.mjs.map +1 -1
- package/dist/io/tiktok/client.mjs +9 -12
- package/dist/io/tiktok/client.mjs.map +1 -1
- package/dist/io/tiktok/discovery/chain.mjs +14 -17
- package/dist/io/tiktok/discovery/chain.mjs.map +1 -1
- package/dist/io/tiktok/discovery/page.mjs +38 -52
- package/dist/io/tiktok/discovery/page.mjs.map +1 -1
- package/dist/io/tiktok/parse.mjs +24 -31
- package/dist/io/tiktok/parse.mjs.map +1 -1
- package/dist/io/tiktok/webcast.mjs +15 -29
- package/dist/io/tiktok/webcast.mjs.map +1 -1
- package/package.json +1 -1
- package/src/app/config.ts +5 -19
- package/src/app/job.ts +61 -27
- package/src/app/logger.ts +9 -23
- package/src/app/loop.ts +12 -11
- package/src/app/recorder.ts +44 -47
- package/src/core/plan.ts +1 -1
- package/src/core/verdict.ts +1 -1
- package/src/index.ts +1 -1
- package/src/io/http.ts +24 -49
- package/src/io/media/ffmpeg.ts +65 -7
- package/src/io/tiktok/client.ts +13 -24
- package/src/io/tiktok/discovery/chain.ts +15 -24
- package/src/io/tiktok/discovery/page.ts +51 -90
- package/src/io/tiktok/parse.ts +38 -48
- package/src/io/tiktok/webcast.ts +30 -41
- package/dist/app/abort.mjs +0 -14
- package/dist/app/abort.mjs.map +0 -1
- package/dist/app/events.mjs +0 -36
- package/dist/app/events.mjs.map +0 -1
- package/dist/io/media/convert.mjs +0 -60
- package/dist/io/media/convert.mjs.map +0 -1
- package/dist/io/media/normalize.mjs +0 -32
- package/dist/io/media/normalize.mjs.map +0 -1
- package/src/app/abort.ts +0 -18
- package/src/app/events.ts +0 -46
- package/src/io/media/convert.ts +0 -69
- package/src/io/media/normalize.ts +0 -64
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"page.mjs","names":[],"sources":["../../../../src/io/tiktok/discovery/page.ts"],"sourcesContent":["import type { RoomRef } from \"../../../core/verdict\"\nimport type { SigiState } from \"../parse\"\nimport {\n extractSigiState,\n extractStreamUrlFast,\n extractUserFromUniversalData,\n findStreamUrlRecursively,\n} from \"../parse\"\nimport
|
|
1
|
+
{"version":3,"file":"page.mjs","names":[],"sources":["../../../../src/io/tiktok/discovery/page.ts"],"sourcesContent":["import type { RoomRef } from \"../../../core/verdict\"\nimport type { SigiState } from \"../parse\"\nimport {\n extractSigiState,\n extractStreamUrlFast,\n extractUserFromUniversalData,\n findStreamUrlRecursively,\n} from \"../parse\"\nimport type { Candidate, DiscoverySource, ResolveContext } from \"./chain\"\nimport { fromRoomInfo, miss, withStream } from \"./chain\"\n\n/**\n * Page source: server-rendered SIGI_STATE first, then the async-loaded legacy\n * module, then `__UNIVERSAL_DATA_FOR_REHYDRATION__`. Throws propagate to the\n * chain, which records them and moves on — never a dead end.\n */\nexport function createPageSource(): DiscoverySource {\n return {\n id: \"page\",\n async find(ctx: ResolveContext): Promise<Candidate> {\n const page = await ctx.fetchPage(ctx.user, \"/live\")\n const html = page?.html ?? \"\"\n ctx.debug(\n page\n ? `fetchLiveInfo: /live returned ${html.length} bytes (${page.baseUrl})`\n : \"fetchLiveInfo: all domains blocked for /live page\",\n )\n\n // A `failed` sub-step is not terminal: later paths still get their chance.\n // It is returned only if nothing else hit.\n let failure: Extract<Candidate, { kind: \"failed\" }> | null = null\n const attempt = async (pending: Promise<Candidate>): Promise<Candidate | null> => {\n const candidate = await pending\n if (candidate.kind === \"room\" || candidate.kind === \"denied\") return candidate\n if (candidate.kind === \"failed\") failure ??= candidate\n return null\n }\n\n const sigi: SigiState | null = page ? extractSigiState(html) : null\n ctx.debug(`fetchLiveInfo: SIGI_STATE ${sigi ? \"found\" : \"not found\"}`)\n const liveRoom = sigi?.LiveRoom?.liveRoomUserInfo?.liveRoom\n const roomId = sigi?.LiveRoom?.liveRoomUserInfo?.user?.roomId\n const id = roomId ? String(roomId) : null\n\n // 1. Server-rendered liveRoom wins — no extra request needed.\n if (liveRoom && id) {\n const room: RoomRef = {\n id,\n title: liveRoom.title ?? null,\n live: liveRoom.status === 2, // 2 = live, 4 = offline\n }\n ctx.debug(`fetchLiveInfo: primary path — roomId=${room.id}, live=${room.live}`)\n if (!room.live) return { kind: \"room\", room, stream: null, source: \"sigi\" }\n const knownUrl = extractStreamUrlFast(liveRoom) ?? findStreamUrlRecursively(sigi)\n return withStream(ctx, room, \"sigi\", knownUrl)\n }\n\n // 2. roomId present but liveRoom async-loaded: the Webcast API is authoritative.\n if (id) {\n const found = await attempt(fromRoomInfo(ctx, id, \"room-info\"))\n if (found) return found\n }\n\n // 3. Legacy async-loaded SIGI_STATE.\n if (sigi) {\n const found = await attempt(sigiLegacy(sigi, ctx))\n if (found) return found\n }\n\n // 4. Universal data — SIGI_STATE's successor, from the already-fetched page.\n const universalRoomId = extractUserFromUniversalData(html).roomId\n ctx.debug(`fetchLiveInfo: universal data roomId=${universalRoomId ?? \"null\"}`)\n if (universalRoomId) {\n const found = await attempt(fromRoomInfo(ctx, universalRoomId, \"room-info\"))\n if (found) return found\n }\n\n return failure ?? miss(\"page: no room id\")\n },\n }\n}\n\n/**\n * Secondary live-info extraction when SIGI_STATE's LiveRoom data is\n * async-loaded. Uses LiveRoom.liveRoomStatus for the live flag and\n * UserModule.users[user].roomId for the room ID. Stream URL comes from the\n * Webcast API (room/info/) as a final fallback.\n */\nasync function sigiLegacy(sigi: SigiState, ctx: ResolveContext): Promise<Candidate> {\n const isLive = sigi.LiveRoom?.liveRoomStatus === 2 // 2 = live\n\n // UserModule is usually populated even when LiveRoom is not.\n const owner = sigi.UserModule?.users?.[ctx.user]\n const raw = owner?.roomId\n const roomId = raw ? String(typeof raw === \"object\" ? (raw.id ?? \"\") : raw) : \"\"\n\n // No roomId available — treat as offline (room/enter was unreliable).\n if (!roomId) return miss(\"sigi-legacy: no roomId\")\n\n const room: RoomRef = { id: roomId, title: null, live: isLive }\n if (!isLive) return { kind: \"room\", room, stream: null, source: \"sigi\" }\n return withStream(ctx, room, \"sigi\", null)\n}\n"],"mappings":";;;;;;;;AAgBA,SAAgB,mBAAoC;CAClD,OAAO;EACL,IAAI;EACJ,MAAM,KAAK,KAAyC;GAClD,MAAM,OAAO,MAAM,IAAI,UAAU,IAAI,MAAM,OAAO;GAClD,MAAM,OAAO,MAAM,QAAQ;GAC3B,IAAI,MACF,OACI,iCAAiC,KAAK,OAAO,UAAU,KAAK,QAAQ,KACpE,mDACN;GAIA,IAAI,UAAyD;GAC7D,MAAM,UAAU,OAAO,YAA2D;IAChF,MAAM,YAAY,MAAM;IACxB,IAAI,UAAU,SAAS,UAAU,UAAU,SAAS,UAAU,OAAO;IACrE,IAAI,UAAU,SAAS,UAAU,YAAY;IAC7C,OAAO;GACT;GAEA,MAAM,OAAyB,OAAO,iBAAiB,IAAI,IAAI;GAC/D,IAAI,MAAM,6BAA6B,OAAO,UAAU,aAAa;GACrE,MAAM,WAAW,MAAM,UAAU,kBAAkB;GACnD,MAAM,SAAS,MAAM,UAAU,kBAAkB,MAAM;GACvD,MAAM,KAAK,SAAS,OAAO,MAAM,IAAI;GAGrC,IAAI,YAAY,IAAI;IAClB,MAAM,OAAgB;KACpB;KACA,OAAO,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
CHANGED
|
@@ -1,9 +1,7 @@
|
|
|
1
1
|
//#region src/io/tiktok/parse.ts
|
|
2
|
-
/**
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
function extractSigiState(html) {
|
|
6
|
-
const match = html.match(/<script\s+id="SIGI_STATE"\s+type="application\/json">(.*?)<\/script>/);
|
|
2
|
+
/** Pull a `<script id="…" type="application/json">` block out of the page. */
|
|
3
|
+
function embeddedJson(html, marker) {
|
|
4
|
+
const match = html.match(marker);
|
|
7
5
|
if (!match?.[1]) return null;
|
|
8
6
|
try {
|
|
9
7
|
return JSON.parse(match[1]);
|
|
@@ -12,6 +10,12 @@ function extractSigiState(html) {
|
|
|
12
10
|
}
|
|
13
11
|
}
|
|
14
12
|
/**
|
|
13
|
+
* @public Exported for testing.
|
|
14
|
+
*/
|
|
15
|
+
function extractSigiState(html) {
|
|
16
|
+
return embeddedJson(html, /<script\s+id="SIGI_STATE"\s+type="application\/json">(.*?)<\/script>/);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
15
19
|
* Extract the numeric user ID and optional room ID from TikTok's new
|
|
16
20
|
* page structure (__UNIVERSAL_DATA_FOR_REHYDRATION__).
|
|
17
21
|
*
|
|
@@ -25,24 +29,16 @@ function extractSigiState(html) {
|
|
|
25
29
|
* @public Exported for testing and fixture capture.
|
|
26
30
|
*/
|
|
27
31
|
function extractUserFromUniversalData(html) {
|
|
28
|
-
const
|
|
29
|
-
if (!
|
|
32
|
+
const data = embeddedJson(html, /<script\s+id="__UNIVERSAL_DATA_FOR_REHYDRATION__"\s+type="application\/json">(.*?)<\/script>/);
|
|
33
|
+
if (!data) return {
|
|
30
34
|
userId: null,
|
|
31
35
|
roomId: null
|
|
32
36
|
};
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
roomId: user?.roomId ? String(user.roomId) : null
|
|
39
|
-
};
|
|
40
|
-
} catch {
|
|
41
|
-
return {
|
|
42
|
-
userId: null,
|
|
43
|
-
roomId: null
|
|
44
|
-
};
|
|
45
|
-
}
|
|
37
|
+
const user = (data.__DEFAULT_SCOPE__ ?? data)["webapp.user-detail"]?.userInfo?.user;
|
|
38
|
+
return {
|
|
39
|
+
userId: user?.id ? String(user.id) : null,
|
|
40
|
+
roomId: user?.roomId ? String(user.roomId) : null
|
|
41
|
+
};
|
|
46
42
|
}
|
|
47
43
|
/**
|
|
48
44
|
* Fast-path: extract stream URL from the known SIGI_STATE location.
|
|
@@ -54,7 +50,7 @@ function extractStreamUrlFast(liveRoom) {
|
|
|
54
50
|
try {
|
|
55
51
|
const raw = liveRoom?.streamData?.pull_data?.stream_data;
|
|
56
52
|
if (!raw) return null;
|
|
57
|
-
const data = JSON.parse(raw)
|
|
53
|
+
const data = JSON.parse(raw).data;
|
|
58
54
|
if (!data) return null;
|
|
59
55
|
for (const q of [
|
|
60
56
|
"origin",
|
|
@@ -82,13 +78,13 @@ function extractStreamUrlFast(liveRoom) {
|
|
|
82
78
|
* Inspired by PR #430 (Michele0303/tiktok-live-recorder).
|
|
83
79
|
*/
|
|
84
80
|
function findStreamUrlRecursively(obj) {
|
|
85
|
-
|
|
86
|
-
|
|
81
|
+
let flv = null;
|
|
82
|
+
let hls = null;
|
|
87
83
|
function walk(value) {
|
|
88
84
|
if (typeof value === "string") {
|
|
89
|
-
if (
|
|
90
|
-
if (value.includes(".flv"))
|
|
91
|
-
else
|
|
85
|
+
if (value.startsWith("http://") || value.startsWith("https://")) {
|
|
86
|
+
if (value.includes(".flv")) flv ??= value;
|
|
87
|
+
else if (value.includes(".m3u8")) hls ??= value;
|
|
92
88
|
return;
|
|
93
89
|
}
|
|
94
90
|
if (value.startsWith("{") || value.startsWith("[")) try {
|
|
@@ -96,13 +92,10 @@ function findStreamUrlRecursively(obj) {
|
|
|
96
92
|
} catch {}
|
|
97
93
|
return;
|
|
98
94
|
}
|
|
99
|
-
if (value && typeof value === "object")
|
|
100
|
-
else for (const val of Object.values(value)) walk(val);
|
|
95
|
+
if (value && typeof value === "object") for (const val of Object.values(value)) walk(val);
|
|
101
96
|
}
|
|
102
97
|
walk(obj);
|
|
103
|
-
|
|
104
|
-
if (m3u8Urls.length > 0) return m3u8Urls[0];
|
|
105
|
-
return null;
|
|
98
|
+
return flv ?? hls;
|
|
106
99
|
}
|
|
107
100
|
//#endregion
|
|
108
101
|
export { extractSigiState, extractStreamUrlFast, extractUserFromUniversalData, findStreamUrlRecursively };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"parse.mjs","names":[],"sources":["../../../src/io/tiktok/parse.ts"],"sourcesContent":["export interface SigiState {\n LiveRoom?: {\n liveRoomStatus?: number\n liveRoomUserInfo?: {\n user?: {\n id?: string | number\n roomId?: string | number\n }\n liveRoom?: {\n status?: number // 2 = live, 4 = offline\n title?: string\n startTime?: number\n streamData?: {\n pull_data?: {\n stream_data?: string // JSON string with FLV/HLS URLs\n }\n }\n }\n }\n }\n UserModule?: {\n users?: {\n [username: string]: {\n id?: string // numeric user ID\n uniqueId?: string\n roomId?: string | { id: string }\n }\n }\n }\n}\n\n// ─── HTML parsing ──────────────────────────────────────────\n\n
|
|
1
|
+
{"version":3,"file":"parse.mjs","names":[],"sources":["../../../src/io/tiktok/parse.ts"],"sourcesContent":["export interface SigiState {\n LiveRoom?: {\n liveRoomStatus?: number\n liveRoomUserInfo?: {\n user?: {\n id?: string | number\n roomId?: string | number\n }\n liveRoom?: {\n status?: number // 2 = live, 4 = offline\n title?: string\n startTime?: number\n streamData?: {\n pull_data?: {\n stream_data?: string // JSON string with FLV/HLS URLs\n }\n }\n }\n }\n }\n UserModule?: {\n users?: {\n [username: string]: {\n id?: string // numeric user ID\n uniqueId?: string\n roomId?: string | { id: string }\n }\n }\n }\n}\n\n// ─── HTML parsing ──────────────────────────────────────────\n\n/** Pull a `<script id=\"…\" type=\"application/json\">` block out of the page. */\nfunction embeddedJson(html: string, marker: RegExp): Record<string, unknown> | null {\n const match = html.match(marker)\n if (!match?.[1]) return null\n try {\n return JSON.parse(match[1]) as Record<string, unknown>\n } catch {\n return null\n }\n}\n\n/**\n * @public Exported for testing.\n */\nexport function extractSigiState(html: string): SigiState | null {\n return embeddedJson(\n html,\n /<script\\s+id=\"SIGI_STATE\"\\s+type=\"application\\/json\">(.*?)<\\/script>/,\n ) as SigiState | null\n}\n\n/**\n * Extract the numeric user ID and optional room ID from TikTok's new\n * page structure (__UNIVERSAL_DATA_FOR_REHYDRATION__).\n *\n * The profile page (/@user) includes \"webapp.user-detail\" which\n * contains the user's numeric ID. When the user is live, the roomId\n * is also embedded here.\n *\n * Returns { userId, roomId } where userId is always set when the data\n * is found, and roomId is set only when the user is currently live.\n *\n * @public Exported for testing and fixture capture.\n */\nexport function extractUserFromUniversalData(html: string): {\n userId: string | null\n roomId: string | null\n} {\n const data = embeddedJson(\n html,\n /<script\\s+id=\"__UNIVERSAL_DATA_FOR_REHYDRATION__\"\\s+type=\"application\\/json\">(.*?)<\\/script>/,\n )\n if (!data) return { userId: null, roomId: null }\n const scope = (data.__DEFAULT_SCOPE__ ?? data) as Record<string, unknown>\n const userDetail = scope[\"webapp.user-detail\"] as\n | { userInfo?: { user?: { id?: unknown; roomId?: unknown } } }\n | undefined\n const user = userDetail?.userInfo?.user\n return {\n userId: user?.id ? String(user.id) : null,\n roomId: user?.roomId ? String(user.roomId) : null,\n }\n}\n\n// ─── Stream URL extraction ─────────────────────────────────\n\n/**\n * Fast-path: extract stream URL from the known SIGI_STATE location.\n * This covers ~95% of cases without needing a full recursive search.\n *\n * Prefers FLV (lower latency) over HLS/other protocols.\n */\nexport function extractStreamUrlFast(\n liveRoom: NonNullable<NonNullable<SigiState[\"LiveRoom\"]>[\"liveRoomUserInfo\"]>[\"liveRoom\"],\n): string | null {\n try {\n const raw = liveRoom?.streamData?.pull_data?.stream_data\n if (!raw) return null\n const parsed = JSON.parse(raw) as {\n data?: Record<string, { main?: { flv?: string; hls?: string } }>\n }\n const data = parsed.data\n if (!data) return null\n\n // Try all known quality keys, preferring higher quality.\n // FLV is preferred (lower latency); HLS is the fallback.\n const qualities = [\"origin\", \"fhd\", \"uhd\", \"hd\", \"sd\", \"ld\"]\n for (const q of qualities) {\n const entry = data[q]\n // Prefer FLV over HLS when both are available\n const url = entry?.main?.flv ?? entry?.main?.hls\n if (url) return url\n }\n return null\n } catch {\n return null\n }\n}\n\n/**\n * Brute-force recursive search for a stream URL anywhere in a JSON value.\n * Survives TikTok changing key names or nesting structure.\n *\n * Prefers FLV over HLS when both are present in the response.\n *\n * Inspired by PR #430 (Michele0303/tiktok-live-recorder).\n */\nexport function findStreamUrlRecursively(obj: unknown): string | null {\n // First FLV wins; HLS is only a fallback.\n let flv: string | null = null\n let hls: string | null = null\n\n function walk(value: unknown): void {\n if (typeof value === \"string\") {\n if (value.startsWith(\"http://\") || value.startsWith(\"https://\")) {\n if (value.includes(\".flv\")) flv ??= value\n else if (value.includes(\".m3u8\")) hls ??= value\n return\n }\n // JSON-encoded string — parse and recurse\n if (value.startsWith(\"{\") || value.startsWith(\"[\")) {\n try {\n walk(JSON.parse(value))\n } catch {\n // skip\n }\n }\n return\n }\n\n if (value && typeof value === \"object\") {\n for (const val of Object.values(value as Record<string, unknown>)) walk(val)\n }\n }\n\n walk(obj)\n return flv ?? hls\n}\n"],"mappings":";;AAkCA,SAAS,aAAa,MAAc,QAAgD;CAClF,MAAM,QAAQ,KAAK,MAAM,MAAM;CAC/B,IAAI,CAAC,QAAQ,IAAI,OAAO;CACxB,IAAI;EACF,OAAO,KAAK,MAAM,MAAM,EAAE;CAC5B,QAAQ;EACN,OAAO;CACT;AACF;;;;AAKA,SAAgB,iBAAiB,MAAgC;CAC/D,OAAO,aACL,MACA,sEACF;AACF;;;;;;;;;;;;;;AAeA,SAAgB,6BAA6B,MAG3C;CACA,MAAM,OAAO,aACX,MACA,8FACF;CACA,IAAI,CAAC,MAAM,OAAO;EAAE,QAAQ;EAAM,QAAQ;CAAK;CAK/C,MAAM,QAJS,KAAK,qBAAqB,KAAA,CA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4
4
|
function createWebcastApi(http, debug, signal) {
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* instead of being collapsed into null; callers map failures.
|
|
10
|
-
* The caller provides an extractor for the response data.
|
|
6
|
+
* GET → JSON with the contract every Webcast call shares: gate refusals
|
|
7
|
+
* (status_code 4003110) and transport failures come back as `{ ok: false }`
|
|
8
|
+
* instead of collapsing into null. `statusCode: 0` = threw before a status.
|
|
11
9
|
*/
|
|
12
|
-
async function
|
|
10
|
+
async function fetchJson(url, label, extract) {
|
|
13
11
|
try {
|
|
14
|
-
const url = `${WEBCAST_BASE}/webcast/room/info/?aid=1988&room_id=${roomId}&type=live`;
|
|
15
12
|
const res = await http.get(url, signal);
|
|
16
|
-
debug(
|
|
13
|
+
debug(`${label} status=${res.status}, ok=${res.ok}`);
|
|
17
14
|
if (!res.ok) return {
|
|
18
15
|
ok: false,
|
|
19
16
|
statusCode: res.status,
|
|
20
17
|
body: ""
|
|
21
18
|
};
|
|
22
19
|
const text = await res.text();
|
|
23
|
-
debug(
|
|
20
|
+
debug(`${label} returned ${text.length} bytes`);
|
|
24
21
|
if (text.length === 0) return {
|
|
25
22
|
ok: true,
|
|
26
23
|
value: null
|
|
@@ -43,32 +40,21 @@ function createWebcastApi(http, debug, signal) {
|
|
|
43
40
|
};
|
|
44
41
|
}
|
|
45
42
|
}
|
|
43
|
+
async function fetchFromRoomApi(roomId, extract) {
|
|
44
|
+
return fetchJson(`${WEBCAST_BASE}/webcast/room/info/?aid=1988&room_id=${roomId}&type=live`, `fetchFromRoomApi: roomId=${roomId}`, extract);
|
|
45
|
+
}
|
|
46
46
|
/**
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
* This is faster and cheaper than fetching the full room/info response.
|
|
51
|
-
* Returns `true` if the room is live, `false` otherwise (including errors).
|
|
47
|
+
* Lightweight liveness probe: cheaper than the full room/info response.
|
|
48
|
+
* Failures read as `false`.
|
|
52
49
|
*
|
|
53
50
|
* Endpoint: /webcast/room/check_alive/?aid=1988®ion=CH&room_ids={id}&user_is_login=true
|
|
54
51
|
* Response: { "data": [{ "alive": true/false, "room_id": "..." }] }
|
|
55
52
|
*/
|
|
56
53
|
async function fetchCheckAlive(roomId) {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
if (!res.ok) return false;
|
|
62
|
-
const text = await res.text();
|
|
63
|
-
debug(`fetchCheckAlive: roomId=${roomId} returned ${text.length} bytes`);
|
|
64
|
-
if (text.length === 0) return false;
|
|
65
|
-
const alive = (JSON.parse(text)?.data)?.[0]?.alive === true;
|
|
66
|
-
debug(`fetchCheckAlive: roomId=${roomId} alive=${alive}`);
|
|
67
|
-
return alive;
|
|
68
|
-
} catch (err) {
|
|
69
|
-
debug(`fetchCheckAlive: roomId=${roomId} error — ${err instanceof Error ? err.message : String(err)}`);
|
|
70
|
-
return false;
|
|
71
|
-
}
|
|
54
|
+
const res = await fetchJson(`${WEBCAST_BASE}/webcast/room/check_alive/?aid=1988®ion=CH&room_ids=${roomId}&user_is_login=true`, `fetchCheckAlive: roomId=${roomId}`, (data) => data.data?.[0]?.alive === true);
|
|
55
|
+
const alive = res.ok && res.value === true;
|
|
56
|
+
debug(`fetchCheckAlive: roomId=${roomId} alive=${alive}`);
|
|
57
|
+
return alive;
|
|
72
58
|
}
|
|
73
59
|
/**
|
|
74
60
|
* Resolve a 4003110 room-gate refusal via check_alive: the room is live
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webcast.mjs","names":[],"sources":["../../../src/io/tiktok/webcast.ts"],"sourcesContent":["import type { RoomRef, StreamRef } from \"../../core/verdict\"\nimport type { HttpClient } from \"../http\"\nimport { findStreamUrlRecursively } from \"./parse\"\n\nconst WEBCAST_BASE = \"https://webcast.tiktok.com\"\n\n/**\n * Discriminated room/info result: refusals (notably status_code 4003110)\n * and transport failures surface as `{ ok: false }` instead of null.\n * `statusCode: 0` means the request threw before a status was read.\n */\nexport type RoomApiResult<T> =\n | { ok: true; value: T | null }\n | { ok: false; statusCode: number; body: string }\n\n/** Authoritative room/info facts: the room plus its stream URL when present. */\nexport interface RoomFacts {\n readonly room: RoomRef\n readonly stream: StreamRef | null\n}\n\n/** What discovery sources consume. `createWebcastApi` is the only implementation. */\nexport interface WebcastReader {\n fetchFromRoomApi: <T>(\n roomId: string,\n extract: (data: Record<string, unknown>) => T | null,\n ) => Promise<RoomApiResult<T>>\n fetchCheckAlive: (roomId: string) => Promise<boolean>\n fetchStreamUrlFromApi: (roomId: string) => Promise<RoomApiResult<string>>\n /** room/info as domain facts; 4003110 comes back as `{ ok: false }`. */\n roomInfo: (roomId: string) => Promise<RoomApiResult<RoomFacts>>\n /** Resolve a 4003110 refusal: alive → restricted candidate, else offline. */\n refusedRoom: (roomId: string, title: string | null) => Promise<RoomRef>\n}\n\nexport function createWebcastApi(\n http: HttpClient,\n debug: (msg: string) => void,\n signal?: AbortSignal,\n): WebcastReader {\n /**\n *
|
|
1
|
+
{"version":3,"file":"webcast.mjs","names":[],"sources":["../../../src/io/tiktok/webcast.ts"],"sourcesContent":["import type { RoomRef, StreamRef } from \"../../core/verdict\"\nimport type { HttpClient } from \"../http\"\nimport { findStreamUrlRecursively } from \"./parse\"\n\nconst WEBCAST_BASE = \"https://webcast.tiktok.com\"\n\n/**\n * Discriminated room/info result: refusals (notably status_code 4003110)\n * and transport failures surface as `{ ok: false }` instead of null.\n * `statusCode: 0` means the request threw before a status was read.\n */\nexport type RoomApiResult<T> =\n | { ok: true; value: T | null }\n | { ok: false; statusCode: number; body: string }\n\n/** Authoritative room/info facts: the room plus its stream URL when present. */\nexport interface RoomFacts {\n readonly room: RoomRef\n readonly stream: StreamRef | null\n}\n\n/** What discovery sources consume. `createWebcastApi` is the only implementation. */\nexport interface WebcastReader {\n fetchFromRoomApi: <T>(\n roomId: string,\n extract: (data: Record<string, unknown>) => T | null,\n ) => Promise<RoomApiResult<T>>\n fetchCheckAlive: (roomId: string) => Promise<boolean>\n fetchStreamUrlFromApi: (roomId: string) => Promise<RoomApiResult<string>>\n /** room/info as domain facts; 4003110 comes back as `{ ok: false }`. */\n roomInfo: (roomId: string) => Promise<RoomApiResult<RoomFacts>>\n /** Resolve a 4003110 refusal: alive → restricted candidate, else offline. */\n refusedRoom: (roomId: string, title: string | null) => Promise<RoomRef>\n}\n\nexport function createWebcastApi(\n http: HttpClient,\n debug: (msg: string) => void,\n signal?: AbortSignal,\n): WebcastReader {\n /**\n * GET → JSON with the contract every Webcast call shares: gate refusals\n * (status_code 4003110) and transport failures come back as `{ ok: false }`\n * instead of collapsing into null. `statusCode: 0` = threw before a status.\n */\n async function fetchJson<T>(\n url: string,\n label: string,\n extract: (data: Record<string, unknown>) => T | null,\n ): Promise<RoomApiResult<T>> {\n try {\n const res = await http.get(url, signal)\n debug(`${label} status=${res.status}, ok=${res.ok}`)\n if (!res.ok) return { ok: false, statusCode: res.status, body: \"\" }\n\n const text = await res.text()\n debug(`${label} returned ${text.length} bytes`)\n if (text.length === 0) return { ok: true, value: null }\n\n const data = JSON.parse(text) as Record<string, unknown>\n // status_code 4003110 = age-protected/restricted room: report it\n if (data.status_code === 4003110) return { ok: false, statusCode: 4003110, body: text }\n\n return { ok: true, value: extract(data) }\n } catch {\n return { ok: false, statusCode: 0, body: \"\" }\n }\n }\n\n async function fetchFromRoomApi<T>(\n roomId: string,\n extract: (data: Record<string, unknown>) => T | null,\n ): Promise<RoomApiResult<T>> {\n return fetchJson(\n `${WEBCAST_BASE}/webcast/room/info/?aid=1988&room_id=${roomId}&type=live`,\n `fetchFromRoomApi: roomId=${roomId}`,\n extract,\n )\n }\n\n /**\n * Lightweight liveness probe: cheaper than the full room/info response.\n * Failures read as `false`.\n *\n * Endpoint: /webcast/room/check_alive/?aid=1988®ion=CH&room_ids={id}&user_is_login=true\n * Response: { \"data\": [{ \"alive\": true/false, \"room_id\": \"...\" }] }\n */\n async function fetchCheckAlive(roomId: string): Promise<boolean> {\n const res = await fetchJson(\n `${WEBCAST_BASE}/webcast/room/check_alive/?aid=1988®ion=CH&room_ids=${roomId}&user_is_login=true`,\n `fetchCheckAlive: roomId=${roomId}`,\n (data) => (data.data as Array<{ alive?: boolean }> | undefined)?.[0]?.alive === true,\n )\n const alive = res.ok && res.value === true\n debug(`fetchCheckAlive: roomId=${roomId} alive=${alive}`)\n return alive\n }\n\n /**\n * Resolve a 4003110 room-gate refusal via check_alive: the room is live\n * (restricted) when alive, offline otherwise. Single home for this mapping.\n */\n async function refusedRoom(roomId: string, title: string | null): Promise<RoomRef> {\n debug(`refusedRoom: room/info refused roomId=${roomId} (status_code 4003110)`)\n const live = await fetchCheckAlive(roomId)\n return { id: roomId, title, live }\n }\n\n /**\n * Fetch room/info as domain facts. Requires a known roomId. A 4003110\n * refusal stays `{ ok: false, statusCode: 4003110 }` for the caller to map\n * via `refusedRoom`.\n */\n async function roomInfo(roomId: string): Promise<RoomApiResult<RoomFacts>> {\n const res = await fetchFromRoomApi<Record<string, unknown>>(\n roomId,\n (data) => (data as { data?: Record<string, unknown> }).data ?? null,\n )\n if (!res.ok) return res\n const roomData = res.value\n if (!roomData) return { ok: true, value: null }\n\n const title = (roomData.title as string | undefined) ?? null\n const streamUrl = findStreamUrlRecursively(roomData)\n return {\n ok: true,\n value: {\n room: { id: roomId, title, live: (roomData.status ?? 4) === 2 },\n stream: streamUrl ? { url: streamUrl } : null,\n },\n }\n }\n\n /**\n * Fetch stream URL from the Webcast API.\n * Covers cases where SIGI_STATE doesn't include stream data.\n * Refusals (4003110) and transport failures are reported so callers\n * can distinguish restricted rooms from missing URLs.\n */\n async function fetchStreamUrlFromApi(roomId: string): Promise<RoomApiResult<string>> {\n return fetchFromRoomApi(roomId, (data) => findStreamUrlRecursively(data))\n }\n\n return {\n fetchFromRoomApi,\n fetchCheckAlive,\n fetchStreamUrlFromApi,\n roomInfo,\n refusedRoom,\n }\n}\n"],"mappings":";;AAIA,MAAM,eAAe;AA+BrB,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M,MAAM,MAAM,iBAChB,SACC,SAAU,KAA4C,QAAQ,IACjE;EACA,IAAI,CAAC,IAAI,IAAI,OAAO;EACpB,MAAM,WAAW,IAAI;EACrB,IAAI,CAAC,UAAU,OAAO;GAAE,IAAI;GAAM,OAAO;EAAK;EAE9C,MAAM,QAAS,SAAS,SAAgC;EACxD,MAAM,YAAY,yBAAyB,QAAQ;EACnD,OAAO;GACL,IAAI;GACJ,OAAO;IACL,MAAM;KAAE,IAAI;KAAQ;KAAO,OAAO,SAAS,UAAU,OAAO;IAAE;IAC9D,QAAQ,YAAY,EAAE,KAAK,UAAU,IAAI;GAC3C;EACF;CACF;;;;;;;CAQA,eAAe,sBAAsB,QAAgD;EACnF,OAAO,iBAAiB,SAAS,SAAS,yBAAyB,IAAI,CAAC;CAC1E;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;CACF;AACF"}
|
package/package.json
CHANGED
package/src/app/config.ts
CHANGED
|
@@ -16,7 +16,7 @@ export type CookieAuth = Record<string, string>
|
|
|
16
16
|
export type LogLevel = "debug" | "info" | "warn" | "error"
|
|
17
17
|
|
|
18
18
|
/**
|
|
19
|
-
* Machine-readable reason for a LIVE status verdict — lives in `
|
|
19
|
+
* Machine-readable reason for a LIVE status verdict — lives in `core/verdict.ts`.
|
|
20
20
|
*/
|
|
21
21
|
export type { LiveReason } from "../core/verdict"
|
|
22
22
|
|
|
@@ -124,24 +124,10 @@ export interface RecorderEventHandler {
|
|
|
124
124
|
}
|
|
125
125
|
|
|
126
126
|
/** A `RecorderConfig` with every default applied — what the recorder runs on. */
|
|
127
|
-
export
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
duration: number
|
|
132
|
-
proxy?: string
|
|
133
|
-
cookiesPath?: string
|
|
134
|
-
cookies?: CookieAuth
|
|
135
|
-
logLevel: LogLevel
|
|
136
|
-
logConsole: boolean
|
|
137
|
-
segmentMinutes: number
|
|
138
|
-
normalizeAudio: boolean
|
|
139
|
-
normalizeLoudness: number
|
|
140
|
-
normalizeCodec?: string
|
|
141
|
-
normalizeBitrate?: string
|
|
142
|
-
ratePerSecond: number
|
|
143
|
-
debug: boolean
|
|
144
|
-
}
|
|
127
|
+
export type ResolvedConfig = Required<
|
|
128
|
+
Omit<RecorderConfig, "proxy" | "cookies" | "cookiesPath" | "normalizeCodec" | "normalizeBitrate">
|
|
129
|
+
> &
|
|
130
|
+
Pick<RecorderConfig, "proxy" | "cookies" | "cookiesPath" | "normalizeCodec" | "normalizeBitrate">
|
|
145
131
|
|
|
146
132
|
/** Apply defaults once, at the entry point; nothing downstream re-reads `??`. */
|
|
147
133
|
export function resolveConfig(config: RecorderConfig): ResolvedConfig {
|
package/src/app/job.ts
CHANGED
|
@@ -5,11 +5,11 @@
|
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
import { statSync, unlinkSync, utimesSync } from "node:fs"
|
|
8
|
-
import { join, parse } from "node:path"
|
|
8
|
+
import { isAbsolute, join, parse } from "node:path"
|
|
9
|
+
import { type NormalizeOptions, type NormalizeResult, normalizeFile } from "peaknorm"
|
|
9
10
|
import { TikTokError } from "../core/errors"
|
|
10
11
|
import type { Logger } from "../core/log"
|
|
11
|
-
import type {
|
|
12
|
-
import type { AudioNormalizer } from "../io/media/normalize"
|
|
12
|
+
import type { MediaConverter } from "../io/media/ffmpeg"
|
|
13
13
|
import type {
|
|
14
14
|
ProgressEvent,
|
|
15
15
|
RecordEvent,
|
|
@@ -25,10 +25,16 @@ export interface RecordingJob {
|
|
|
25
25
|
|
|
26
26
|
export interface RecordingJobDeps {
|
|
27
27
|
result: RecordedFile
|
|
28
|
-
cfg: Pick<
|
|
28
|
+
cfg: Pick<
|
|
29
|
+
RecorderConfig,
|
|
30
|
+
| "segmentMinutes"
|
|
31
|
+
| "normalizeAudio"
|
|
32
|
+
| "normalizeLoudness"
|
|
33
|
+
| "normalizeCodec"
|
|
34
|
+
| "normalizeBitrate"
|
|
35
|
+
>
|
|
29
36
|
logger: Logger
|
|
30
|
-
converter:
|
|
31
|
-
audioNormalizer: AudioNormalizer | null
|
|
37
|
+
converter: MediaConverter
|
|
32
38
|
signal: AbortSignal
|
|
33
39
|
emitRecord: (event: RecordEvent) => void
|
|
34
40
|
emitProgress: (event: ProgressEvent) => void
|
|
@@ -75,12 +81,11 @@ async function run(deps: RecordingJobDeps): Promise<RecordedFile[]> {
|
|
|
75
81
|
async function segment(deps: RecordingJobDeps): Promise<RecordedFile[]> {
|
|
76
82
|
const { result, cfg, logger, signal } = deps
|
|
77
83
|
const parsed = parse(result.file)
|
|
78
|
-
const
|
|
84
|
+
const segmentMinutes = cfg.segmentMinutes ?? 20
|
|
85
|
+
const segmentTime = Math.max(1, segmentMinutes * 60)
|
|
79
86
|
const outputPattern = join(parsed.dir, `${parsed.name}_part%d.mp4`)
|
|
80
87
|
|
|
81
|
-
logger.info(
|
|
82
|
-
`Segmenting: ${parsed.base} → ${parsed.name}_partN.mp4 (${cfg.segmentMinutes ?? 20} min each)`,
|
|
83
|
-
)
|
|
88
|
+
logger.info(`Segmenting: ${parsed.base} → ${parsed.name}_partN.mp4 (${segmentMinutes} min each)`)
|
|
84
89
|
deps.setState({ state: "segmenting" })
|
|
85
90
|
deps.emitRecord({
|
|
86
91
|
phase: "segment",
|
|
@@ -100,7 +105,7 @@ async function segment(deps: RecordingJobDeps): Promise<RecordedFile[]> {
|
|
|
100
105
|
return convert(deps)
|
|
101
106
|
}
|
|
102
107
|
|
|
103
|
-
const segments = parseSegmentList(listing, segmentTime)
|
|
108
|
+
const segments = parseSegmentList(listing, segmentTime, parsed.dir)
|
|
104
109
|
if (segments.length === 0) {
|
|
105
110
|
logger.warn("Segmenting produced no files — falling back to whole-file conversion")
|
|
106
111
|
return convert(deps)
|
|
@@ -109,13 +114,6 @@ async function segment(deps: RecordingJobDeps): Promise<RecordedFile[]> {
|
|
|
109
114
|
const fileMtimeMs = statSync(result.file).mtimeMs
|
|
110
115
|
const recStartMs = fileMtimeMs - result.duration * 1000
|
|
111
116
|
|
|
112
|
-
try {
|
|
113
|
-
unlinkSync(result.file)
|
|
114
|
-
logger.info(`Deleted original: ${parsed.base}`)
|
|
115
|
-
} catch {
|
|
116
|
-
logger.warn(`Could not delete original: ${parsed.base}`)
|
|
117
|
-
}
|
|
118
|
-
|
|
119
117
|
const files: RecordedFile[] = []
|
|
120
118
|
for (let i = 0; i < segments.length; i++) {
|
|
121
119
|
const seg = segments[i]
|
|
@@ -141,10 +139,17 @@ async function segment(deps: RecordingJobDeps): Promise<RecordedFile[]> {
|
|
|
141
139
|
|
|
142
140
|
deps.emitRecord({ phase: "segment", status: "end", segments: files.length })
|
|
143
141
|
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
142
|
+
// Only now that every part is on disk and readable is the crash-safe source
|
|
143
|
+
// expendable; an earlier unlink loses the recording if a part stat fails.
|
|
144
|
+
try {
|
|
145
|
+
unlinkSync(result.file)
|
|
146
|
+
logger.info(`Deleted original: ${parsed.base}`)
|
|
147
|
+
} catch {
|
|
148
|
+
logger.warn(`Could not delete original: ${parsed.base}`)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
for (const recorded of files) {
|
|
152
|
+
await normalize(deps, recorded.file)
|
|
148
153
|
}
|
|
149
154
|
|
|
150
155
|
deps.setState({
|
|
@@ -174,7 +179,7 @@ async function convert(deps: RecordingJobDeps): Promise<RecordedFile[]> {
|
|
|
174
179
|
}
|
|
175
180
|
deps.emitRecord({ phase: "end", ...recorded })
|
|
176
181
|
|
|
177
|
-
|
|
182
|
+
await normalize(deps, mp4File)
|
|
178
183
|
|
|
179
184
|
deps.emitRecord({
|
|
180
185
|
phase: "convert",
|
|
@@ -188,10 +193,32 @@ async function convert(deps: RecordingJobDeps): Promise<RecordedFile[]> {
|
|
|
188
193
|
}
|
|
189
194
|
|
|
190
195
|
async function normalize(deps: RecordingJobDeps, file: string): Promise<void> {
|
|
191
|
-
|
|
196
|
+
const { cfg, logger, signal } = deps
|
|
197
|
+
if (!cfg.normalizeAudio || signal.aborted) return
|
|
192
198
|
deps.emitRecord({ phase: "normalize", status: "start", file })
|
|
199
|
+
logger.info(`Normalizing audio: ${file}`)
|
|
193
200
|
try {
|
|
194
|
-
const
|
|
201
|
+
const opts: NormalizeOptions = {
|
|
202
|
+
loudness: cfg.normalizeLoudness ?? -14,
|
|
203
|
+
backup: false,
|
|
204
|
+
// Post-processing outlives a user stop only until POST_REMUX_GRACE_MS;
|
|
205
|
+
// forwarding the signal is what lets that cap bound a loudnorm pass.
|
|
206
|
+
signal,
|
|
207
|
+
onFileProgress: (f, percent, phase) =>
|
|
208
|
+
deps.emitProgress({
|
|
209
|
+
kind: "normalize",
|
|
210
|
+
file: f,
|
|
211
|
+
percent,
|
|
212
|
+
phase: phase as "analyzing" | "normalizing",
|
|
213
|
+
}),
|
|
214
|
+
}
|
|
215
|
+
if (cfg.normalizeCodec !== undefined) opts.audioCodec = cfg.normalizeCodec
|
|
216
|
+
if (cfg.normalizeBitrate !== undefined) opts.audioBitrate = cfg.normalizeBitrate
|
|
217
|
+
const result: NormalizeResult = await normalizeFile(file, opts)
|
|
218
|
+
// peaknorm resolves (not rejects) when its signal aborts, leaving the file
|
|
219
|
+
// untouched — so an abort must not be reported as a completed normalize.
|
|
220
|
+
if (signal.aborted) return
|
|
221
|
+
logger.info(`Audio normalized: ${result.output}`)
|
|
195
222
|
deps.emitRecord({
|
|
196
223
|
phase: "normalize",
|
|
197
224
|
status: "done",
|
|
@@ -199,7 +226,10 @@ async function normalize(deps: RecordingJobDeps, file: string): Promise<void> {
|
|
|
199
226
|
output: result.output,
|
|
200
227
|
})
|
|
201
228
|
} catch (err) {
|
|
229
|
+
// A stop-time abort is not a normalization failure — say nothing.
|
|
230
|
+
if (signal.aborted) return
|
|
202
231
|
const message = err instanceof Error ? err.message : String(err)
|
|
232
|
+
logger.error(`Audio normalization failed: ${message}`)
|
|
203
233
|
deps.emitRecord({
|
|
204
234
|
phase: "normalize",
|
|
205
235
|
status: "error",
|
|
@@ -212,14 +242,18 @@ async function normalize(deps: RecordingJobDeps, file: string): Promise<void> {
|
|
|
212
242
|
function parseSegmentList(
|
|
213
243
|
listing: string,
|
|
214
244
|
fallbackDuration: number,
|
|
245
|
+
dir: string,
|
|
215
246
|
): { file: string; duration: number }[] {
|
|
216
247
|
return listing
|
|
217
248
|
.split("\n")
|
|
218
249
|
.map((line) => line.trim())
|
|
219
250
|
.filter((line) => line.length > 0)
|
|
220
251
|
.flatMap((line) => {
|
|
221
|
-
const [
|
|
222
|
-
if (!
|
|
252
|
+
const [name, start, end] = line.split(",").map((field) => field.replace(/^"|"$/g, ""))
|
|
253
|
+
if (!name) return []
|
|
254
|
+
// ffmpeg lists segment basenames even when handed an absolute pattern,
|
|
255
|
+
// so resolve against the directory the recording lives in.
|
|
256
|
+
const file = isAbsolute(name) ? name : join(dir, name)
|
|
223
257
|
const duration = Number(end) - Number(start)
|
|
224
258
|
return [
|
|
225
259
|
{ file, duration: Number.isFinite(duration) && duration > 0 ? duration : fallbackDuration },
|
package/src/app/logger.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Logger — rotating file + console with levels.
|
|
3
|
-
* Zero-dependency minimal implementation (~60 lines).
|
|
4
3
|
*/
|
|
5
4
|
|
|
6
5
|
import { appendFileSync, existsSync, mkdirSync, renameSync, statSync, writeFileSync } from "node:fs"
|
|
@@ -96,18 +95,12 @@ export function createLogger(opts: {
|
|
|
96
95
|
const ts = new Date().toISOString()
|
|
97
96
|
const suffix = args.length > 0 ? ` ${args.map((a) => String(a)).join(" ")}` : ""
|
|
98
97
|
const line = `[${ts}] [${level.toUpperCase()}] ${msg}${suffix}`
|
|
99
|
-
const formatted = `[${ts}] [${level.toUpperCase()}] ${msg}${suffix}`
|
|
100
98
|
|
|
101
|
-
// Console (optional — can be suppressed for file-only logging)
|
|
102
99
|
if (showConsole) {
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
} else {
|
|
106
|
-
process.stdout.write(`${LEVEL_COLORS[level]}${formatted}${RESET}\n`)
|
|
107
|
-
}
|
|
100
|
+
const sink = level === "error" ? process.stderr : process.stdout
|
|
101
|
+
sink.write(`${LEVEL_COLORS[level]}${line}${RESET}\n`)
|
|
108
102
|
}
|
|
109
103
|
|
|
110
|
-
// File
|
|
111
104
|
try {
|
|
112
105
|
rotateIfNeeded()
|
|
113
106
|
appendFileSync(logFile, `${line}\n`, "utf-8")
|
|
@@ -116,18 +109,11 @@ export function createLogger(opts: {
|
|
|
116
109
|
}
|
|
117
110
|
}
|
|
118
111
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
warn: (msg, ...args) => {
|
|
127
|
-
if (LEVEL_ORDER.warn >= LEVEL_ORDER[level]) write("warn", msg, args)
|
|
128
|
-
},
|
|
129
|
-
error: (msg, ...args) => {
|
|
130
|
-
if (LEVEL_ORDER.error >= LEVEL_ORDER[level]) write("error", msg, args)
|
|
131
|
-
},
|
|
132
|
-
}
|
|
112
|
+
const log =
|
|
113
|
+
(lvl: LogLevel) =>
|
|
114
|
+
(msg: string, ...args: unknown[]): void => {
|
|
115
|
+
if (LEVEL_ORDER[lvl] >= LEVEL_ORDER[level]) write(lvl, msg, args)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return { debug: log("debug"), info: log("info"), warn: log("warn"), error: log("error") }
|
|
133
119
|
}
|
package/src/app/loop.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Polling monitor — calls a tick function on a configurable interval.
|
|
3
3
|
* Fires the first tick immediately, then every N minutes.
|
|
4
4
|
*
|
|
5
|
-
* One external `AbortSignal` (the
|
|
5
|
+
* One external `AbortSignal` (the recorder's scope) interrupts both the
|
|
6
6
|
* sleep and any in-flight tick; there is no private controller.
|
|
7
7
|
*/
|
|
8
8
|
|
|
@@ -15,17 +15,18 @@ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
|
15
15
|
resolve()
|
|
16
16
|
return
|
|
17
17
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
{ once: true },
|
|
27
|
-
)
|
|
18
|
+
|
|
19
|
+
let timer: ReturnType<typeof setTimeout>
|
|
20
|
+
// One exit path: clear the timer, drop the listener, resolve. Without the
|
|
21
|
+
// removal a long-lived signal accumulates one listener per poll interval.
|
|
22
|
+
const done = (): void => {
|
|
23
|
+
clearTimeout(timer)
|
|
24
|
+
signal?.removeEventListener("abort", done)
|
|
25
|
+
resolve()
|
|
28
26
|
}
|
|
27
|
+
|
|
28
|
+
timer = setTimeout(done, ms)
|
|
29
|
+
signal?.addEventListener("abort", done, { once: true })
|
|
29
30
|
})
|
|
30
31
|
}
|
|
31
32
|
|