@zfadhli/tokrec 0.15.2 → 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/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
package/dist/io/http.mjs
CHANGED
|
@@ -32,7 +32,21 @@ async function createHttpClient(config) {
|
|
|
32
32
|
"https://webcast.tiktok.com",
|
|
33
33
|
"https://m.tiktok.com"
|
|
34
34
|
]) for (const [name, value] of Object.entries(config.cookies)) session.setCookie(name, value, domain);
|
|
35
|
-
const
|
|
35
|
+
const minIntervalMs = config.ratePerSecond ? 1e3 / config.ratePerSecond : 0;
|
|
36
|
+
let lastTokenTime = 0;
|
|
37
|
+
/** Wait for the next rate-limit token, abort-aware so a stop does not wait one out. */
|
|
38
|
+
async function waitForToken(signal) {
|
|
39
|
+
if (minIntervalMs <= 0 || signal.aborted) return;
|
|
40
|
+
const waitTime = Math.max(0, lastTokenTime + minIntervalMs - Date.now());
|
|
41
|
+
if (waitTime > 0) await new Promise((resolve) => {
|
|
42
|
+
const timer = setTimeout(resolve, waitTime);
|
|
43
|
+
signal.addEventListener("abort", () => {
|
|
44
|
+
clearTimeout(timer);
|
|
45
|
+
resolve();
|
|
46
|
+
}, { once: true });
|
|
47
|
+
});
|
|
48
|
+
lastTokenTime = Date.now();
|
|
49
|
+
}
|
|
36
50
|
async function rateLimitedFetch(url, options, external) {
|
|
37
51
|
const controller = new AbortController();
|
|
38
52
|
const onAbort = () => controller.abort(external?.reason);
|
|
@@ -40,7 +54,7 @@ async function createHttpClient(config) {
|
|
|
40
54
|
else external?.addEventListener("abort", onAbort, { once: true });
|
|
41
55
|
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
42
56
|
try {
|
|
43
|
-
await
|
|
57
|
+
await waitForToken(controller.signal);
|
|
44
58
|
return await session.fetch(url, {
|
|
45
59
|
method: options?.method,
|
|
46
60
|
body: options?.body,
|
|
@@ -70,28 +84,6 @@ async function createHttpClient(config) {
|
|
|
70
84
|
}
|
|
71
85
|
};
|
|
72
86
|
}
|
|
73
|
-
/**
|
|
74
|
-
* Token bucket: a minimum interval between requests. `0` or less is unlimited.
|
|
75
|
-
* Abort-aware, so a stop does not wait out a pending token.
|
|
76
|
-
*/
|
|
77
|
-
function createRateLimiter(tokensPerSecond) {
|
|
78
|
-
if (tokensPerSecond <= 0) return { acquire: async () => {} };
|
|
79
|
-
const MIN_INTERVAL_MS = 1e3 / tokensPerSecond;
|
|
80
|
-
let lastTokenTime = 0;
|
|
81
|
-
return { async acquire(signal) {
|
|
82
|
-
if (signal?.aborted) return;
|
|
83
|
-
const now = Date.now();
|
|
84
|
-
const waitTime = Math.max(0, lastTokenTime + MIN_INTERVAL_MS - now);
|
|
85
|
-
if (waitTime > 0) await new Promise((resolve) => {
|
|
86
|
-
const timer = setTimeout(resolve, waitTime);
|
|
87
|
-
if (signal) signal.addEventListener("abort", () => {
|
|
88
|
-
clearTimeout(timer);
|
|
89
|
-
resolve();
|
|
90
|
-
}, { once: true });
|
|
91
|
-
});
|
|
92
|
-
lastTokenTime = Date.now();
|
|
93
|
-
} };
|
|
94
|
-
}
|
|
95
87
|
//#endregion
|
|
96
88
|
export { createHttpClient };
|
|
97
89
|
|
package/dist/io/http.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.mjs","names":[],"sources":["../../src/io/http.ts"],"sourcesContent":["/**\n * HTTP — the transport layer in one file: the wreq-js session (TLS fingerprint\n * impersonation, cookie jar, proxy) and the token-bucket rate limiter that\n * keeps polling from tripping TikTok's WAF.\n *\n * This file owns the `HttpClient` contract: it is the seam every adapter and\n * `test/utils/mock-http.ts` implement. There is no second definition.\n */\n\nimport { createSession, type Session } from \"wreq-js\"\nimport type { RecorderConfig } from \"../app/config\"\n\n// BodyInit is only available inside declare module \"bun\" in bun-types, not as a global\n// under the ES2022 lib. We explicitly import it to keep core/ focused on ES2022.\nexport type HttpBody = import(\"bun\").BodyInit\n\nexport interface HttpClient {\n get: (url: string, signal?: AbortSignal) => Promise<Response>\n post: (\n url: string,\n body?: HttpBody,\n headers?: Record<string, string>,\n signal?: AbortSignal,\n ) => Promise<Response>\n close: () => Promise<void>\n}\n\nconst REQUEST_TIMEOUT_MS = 15_000\n\n/** Standard browser headers to avoid TikTok WAF detection. */\nconst BROWSER_HEADERS: Record<string, string> = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:149.0) Gecko/20100101 Firefox/149.0\",\n Accept: \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\",\n \"Accept-Language\": \"en-US,en;q=0.5\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"Sec-Fetch-Dest\": \"document\",\n \"Sec-Fetch-Mode\": \"navigate\",\n \"Sec-Fetch-Site\": \"none\",\n \"Sec-Fetch-User\": \"?1\",\n}\n\nexport async function createHttpClient(config: RecorderConfig): Promise<HttpClient> {\n const session: Session = await createSession({\n browser: \"firefox_149\",\n os: \"windows\",\n proxy: config.proxy,\n })\n\n // Seed cookies into the session jar so all subsequent requests are authenticated.\n // NOTE: Using a Cookie header does NOT populate wreq-js's cookie jar —\n // we must use session.setCookie() instead.\n // Seed for all TikTok domains since cookies may not propagate across\n // subdomains automatically in wreq-js's cookie jar.\n if (config.cookies && \"sessionid_ss\" in config.cookies) {\n const domains = [\"https://www.tiktok.com\", \"https://webcast.tiktok.com\", \"https://m.tiktok.com\"]\n for (const domain of domains) {\n for (const [name, value] of Object.entries(config.cookies)) {\n session.setCookie(name, value, domain)\n }\n }\n }\n\n const
|
|
1
|
+
{"version":3,"file":"http.mjs","names":[],"sources":["../../src/io/http.ts"],"sourcesContent":["/**\n * HTTP — the transport layer in one file: the wreq-js session (TLS fingerprint\n * impersonation, cookie jar, proxy) and the token-bucket rate limiter that\n * keeps polling from tripping TikTok's WAF.\n *\n * This file owns the `HttpClient` contract: it is the seam every adapter and\n * `test/utils/mock-http.ts` implement. There is no second definition.\n */\n\nimport { createSession, type Session } from \"wreq-js\"\nimport type { RecorderConfig } from \"../app/config\"\n\n// BodyInit is only available inside declare module \"bun\" in bun-types, not as a global\n// under the ES2022 lib. We explicitly import it to keep core/ focused on ES2022.\nexport type HttpBody = import(\"bun\").BodyInit\n\nexport interface HttpClient {\n get: (url: string, signal?: AbortSignal) => Promise<Response>\n post: (\n url: string,\n body?: HttpBody,\n headers?: Record<string, string>,\n signal?: AbortSignal,\n ) => Promise<Response>\n close: () => Promise<void>\n}\n\nconst REQUEST_TIMEOUT_MS = 15_000\n\n/** Standard browser headers to avoid TikTok WAF detection. */\nconst BROWSER_HEADERS: Record<string, string> = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:149.0) Gecko/20100101 Firefox/149.0\",\n Accept: \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\",\n \"Accept-Language\": \"en-US,en;q=0.5\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"Sec-Fetch-Dest\": \"document\",\n \"Sec-Fetch-Mode\": \"navigate\",\n \"Sec-Fetch-Site\": \"none\",\n \"Sec-Fetch-User\": \"?1\",\n}\n\nexport async function createHttpClient(config: RecorderConfig): Promise<HttpClient> {\n const session: Session = await createSession({\n browser: \"firefox_149\",\n os: \"windows\",\n proxy: config.proxy,\n })\n\n // Seed cookies into the session jar so all subsequent requests are authenticated.\n // NOTE: Using a Cookie header does NOT populate wreq-js's cookie jar —\n // we must use session.setCookie() instead.\n // Seed for all TikTok domains since cookies may not propagate across\n // subdomains automatically in wreq-js's cookie jar.\n if (config.cookies && \"sessionid_ss\" in config.cookies) {\n const domains = [\"https://www.tiktok.com\", \"https://webcast.tiktok.com\", \"https://m.tiktok.com\"]\n for (const domain of domains) {\n for (const [name, value] of Object.entries(config.cookies)) {\n session.setCookie(name, value, domain)\n }\n }\n }\n\n // Token bucket: a minimum interval between requests. `0` or less is unlimited.\n const minIntervalMs = config.ratePerSecond ? 1000 / config.ratePerSecond : 0\n let lastTokenTime = 0\n\n /** Wait for the next rate-limit token, abort-aware so a stop does not wait one out. */\n async function waitForToken(signal: AbortSignal): Promise<void> {\n if (minIntervalMs <= 0 || signal.aborted) return\n const waitTime = Math.max(0, lastTokenTime + minIntervalMs - Date.now())\n if (waitTime > 0) {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, waitTime)\n signal.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer)\n resolve()\n },\n { once: true },\n )\n })\n }\n lastTokenTime = Date.now()\n }\n\n async function rateLimitedFetch(\n url: string,\n options?: { method?: string; body?: unknown; headers?: Record<string, string> },\n external?: AbortSignal,\n ): Promise<Response> {\n const controller = new AbortController()\n const onAbort = () => controller.abort(external?.reason)\n if (external?.aborted) controller.abort(external.reason)\n else external?.addEventListener(\"abort\", onAbort, { once: true })\n const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)\n try {\n await waitForToken(controller.signal)\n const res = await session.fetch(url, {\n method: options?.method,\n body: options?.body as never,\n headers: {\n ...BROWSER_HEADERS,\n ...options?.headers,\n },\n signal: controller.signal,\n })\n // SAFETY: wreq-js returns its own Response-compatible object; the port only\n // needs the standard `status`, `ok`, and `text()` surface.\n return res as unknown as Response\n } finally {\n clearTimeout(timeout)\n external?.removeEventListener(\"abort\", onAbort)\n }\n }\n\n return {\n get: async (url: string, signal?: AbortSignal) => rateLimitedFetch(url, undefined, signal),\n post: async (\n url: string,\n body?: HttpBody,\n headers?: Record<string, string>,\n signal?: AbortSignal,\n ) =>\n rateLimitedFetch(\n url,\n {\n method: \"POST\",\n body: body as never,\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n ...headers,\n },\n },\n signal,\n ),\n close: async () => {\n await session.close()\n },\n }\n}\n"],"mappings":";;;;;;;;;;AA2BA,MAAM,qBAAqB;;AAG3B,MAAM,kBAA0C;CAC9C,cAAc;CACd,QAAQ;CACR,mBAAmB;CACnB,mBAAmB;CACnB,6BAA6B;CAC7B,kBAAkB;CAClB,kBAAkB;CAClB,kBAAkB;CAClB,kBAAkB;AACpB;AAEA,eAAsB,iBAAiB,QAA6C;CAClF,MAAM,UAAmB,MAAM,cAAc;EAC3C,SAAS;EACT,IAAI;EACJ,OAAO,OAAO;CAChB,CAAC;CAOD,IAAI,OAAO,WAAW,kBAAkB,OAAO,SAE7C,KAAK,MAAM,UAAU;EADJ;EAA0B;EAA8B;CAC9C,GACzB,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,OAAO,OAAO,GACvD,QAAQ,UAAU,MAAM,OAAO,MAAM;CAM3C,MAAM,gBAAgB,OAAO,gBAAgB,MAAO,OAAO,gBAAgB;CAC3E,IAAI,gBAAgB;;CAGpB,eAAe,aAAa,QAAoC;EAC9D,IAAI,iBAAiB,KAAK,OAAO,SAAS;EAC1C,MAAM,WAAW,KAAK,IAAI,GAAG,gBAAgB,gBAAgB,KAAK,IAAI,CAAC;EACvE,IAAI,WAAW,GACb,MAAM,IAAI,SAAe,YAAY;GACnC,MAAM,QAAQ,WAAW,SAAS,QAAQ;GAC1C,OAAO,iBACL,eACM;IACJ,aAAa,KAAK;IAClB,QAAQ;GACV,GACA,EAAE,MAAM,KAAK,CACf;EACF,CAAC;EAEH,gBAAgB,KAAK,IAAI;CAC3B;CAEA,eAAe,iBACb,KACA,SACA,UACmB;EACnB,MAAM,aAAa,IAAI,gBAAgB;EACvC,MAAM,gBAAgB,WAAW,MAAM,UAAU,MAAM;EACvD,IAAI,UAAU,SAAS,WAAW,MAAM,SAAS,MAAM;OAClD,UAAU,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EAChE,MAAM,UAAU,iBAAiB,WAAW,MAAM,GAAG,kBAAkB;EACvE,IAAI;GACF,MAAM,aAAa,WAAW,MAAM;GAYpC,OAAO,MAXW,QAAQ,MAAM,KAAK;IACnC,QAAQ,SAAS;IACjB,MAAM,SAAS;IACf,SAAS;KACP,GAAG;KACH,GAAG,SAAS;IACd;IACA,QAAQ,WAAW;GACrB,CAAC;EAIH,UAAU;GACR,aAAa,OAAO;GACpB,UAAU,oBAAoB,SAAS,OAAO;EAChD;CACF;CAEA,OAAO;EACL,KAAK,OAAO,KAAa,WAAyB,iBAAiB,KAAK,KAAA,GAAW,MAAM;EACzF,MAAM,OACJ,KACA,MACA,SACA,WAEA,iBACE,KACA;GACE,QAAQ;GACF;GACN,SAAS;IACP,gBAAgB;IAChB,GAAG;GACL;EACF,GACA,MACF;EACF,OAAO,YAAY;GACjB,MAAM,QAAQ,MAAM;EACtB;CACF;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { TikTokError } from "../../core/errors.mjs";
|
|
2
|
-
import { findFfmpegPath, pipeFfmpegSegment } from "./ffmpeg.mjs";
|
|
3
2
|
import { bytesToHuman, formatDuration, formatFilename } from "../../core/format.mjs";
|
|
3
|
+
import { findFfmpegPath, pipeFfmpegSegment } from "./ffmpeg.mjs";
|
|
4
4
|
import { createWriteStream, mkdirSync, statSync } from "node:fs";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
//#region src/io/media/download.ts
|
package/dist/io/media/ffmpeg.mjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import { TikTokError } from "../../core/errors.mjs";
|
|
2
|
-
import { statSync } from "node:fs";
|
|
2
|
+
import { statSync, unlinkSync } from "node:fs";
|
|
3
3
|
import { spawn } from "node:child_process";
|
|
4
4
|
import { execa } from "execa";
|
|
5
5
|
//#region src/io/media/ffmpeg.ts
|
|
6
6
|
/**
|
|
7
7
|
* FFmpeg — the single home for process invocation.
|
|
8
8
|
*
|
|
9
|
-
* Two
|
|
10
|
-
* capture)
|
|
11
|
-
*
|
|
12
|
-
* PATH lookup.
|
|
9
|
+
* Two entry points: `pipeFfmpegSegment` streams stdout into a `WriteStream`
|
|
10
|
+
* (live capture) and `createMediaConverter` builds the remux/segment capability
|
|
11
|
+
* the job consumes. Locating the binary lives here too, so no caller
|
|
12
|
+
* reimplements a PATH lookup.
|
|
13
13
|
*/
|
|
14
14
|
/** Kill FFmpeg if no output is received within this window after spawn. */
|
|
15
15
|
const FFMPEG_STARTUP_TIMEOUT = 3e4;
|
|
@@ -46,6 +46,52 @@ async function runFfmpeg(args, signal) {
|
|
|
46
46
|
throw new TikTokError("ffmpeg-error", `FFmpeg failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
47
47
|
}
|
|
48
48
|
}
|
|
49
|
+
function createMediaConverter(logger, signal) {
|
|
50
|
+
async function convert(input) {
|
|
51
|
+
const output = input.replace(/\.(flv|ts)$/i, ".mp4");
|
|
52
|
+
logger?.info(`Converting: ${input} → ${output}`);
|
|
53
|
+
await runFfmpeg([
|
|
54
|
+
"-i",
|
|
55
|
+
input,
|
|
56
|
+
"-c",
|
|
57
|
+
"copy",
|
|
58
|
+
"-y",
|
|
59
|
+
output
|
|
60
|
+
], signal);
|
|
61
|
+
try {
|
|
62
|
+
unlinkSync(input);
|
|
63
|
+
logger?.info(`Deleted original: ${input}`);
|
|
64
|
+
} catch {
|
|
65
|
+
logger?.warn(`Could not delete original: ${input}`);
|
|
66
|
+
}
|
|
67
|
+
return output;
|
|
68
|
+
}
|
|
69
|
+
async function segment(input, segmentSeconds, outputPattern) {
|
|
70
|
+
return runFfmpeg([
|
|
71
|
+
"-i",
|
|
72
|
+
input,
|
|
73
|
+
"-c",
|
|
74
|
+
"copy",
|
|
75
|
+
"-f",
|
|
76
|
+
"segment",
|
|
77
|
+
"-segment_time",
|
|
78
|
+
String(segmentSeconds),
|
|
79
|
+
"-reset_timestamps",
|
|
80
|
+
"1",
|
|
81
|
+
"-segment_start_number",
|
|
82
|
+
"1",
|
|
83
|
+
"-segment_list",
|
|
84
|
+
"pipe:1",
|
|
85
|
+
"-segment_list_type",
|
|
86
|
+
"csv",
|
|
87
|
+
outputPattern
|
|
88
|
+
], signal);
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
convert,
|
|
92
|
+
segment
|
|
93
|
+
};
|
|
94
|
+
}
|
|
49
95
|
/**
|
|
50
96
|
* Build FFmpeg HTTP option arguments for cookies and headers.
|
|
51
97
|
* TikTok's CDN requires session cookies and a Referer to serve the stream.
|
|
@@ -151,6 +197,6 @@ async function pipeFfmpegSegment(ffmpegPath, url, writer, signal, maxDuration, c
|
|
|
151
197
|
});
|
|
152
198
|
}
|
|
153
199
|
//#endregion
|
|
154
|
-
export { findFfmpegPath, pipeFfmpegSegment
|
|
200
|
+
export { createMediaConverter, findFfmpegPath, pipeFfmpegSegment };
|
|
155
201
|
|
|
156
202
|
//# sourceMappingURL=ffmpeg.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ffmpeg.mjs","names":[],"sources":["../../../src/io/media/ffmpeg.ts"],"sourcesContent":["/**\n * FFmpeg — the single home for process invocation.\n *\n * Two modes: `pipeFfmpegSegment` streams stdout into a `WriteStream` (live\n * capture), `runFfmpeg` runs to completion and returns stdout (remux,\n * segment). Locating the binary lives here too, so no caller reimplements a\n * PATH lookup.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\"\nimport type { WriteStream } from \"node:fs\"\nimport { statSync } from \"node:fs\"\nimport { execa } from \"execa\"\nimport { TikTokError } from \"../../core/errors\"\n\n/** Kill FFmpeg if no output is received within this window after spawn. */\nexport const FFMPEG_STARTUP_TIMEOUT = 30_000\n\n/** Find the FFmpeg binary via `Bun.which()` or a PATH search. */\nexport function findFfmpegPath(): string | null {\n const bunWhich = (globalThis as { Bun?: { which?: (cmd: string) => string | null } }).Bun?.which\n if (typeof bunWhich === \"function\") {\n return (bunWhich(\"ffmpeg\") as string) ?? null\n }\n const paths = process.env.PATH?.split(\":\") ?? []\n for (const dir of paths) {\n try {\n const full = `${dir}/ffmpeg`\n statSync(full)\n return full\n } catch {\n // not found in this directory\n }\n }\n return null\n}\n\n/**\n * Run FFmpeg to completion and return stdout — for output that is a file\n * rather than a pipe (the segment muxer's `-segment_list pipe:1`).\n */\nexport async function runFfmpeg(args: string[], signal?: AbortSignal): Promise<string> {\n const ffmpegPath = findFfmpegPath()\n if (!ffmpegPath) {\n throw new TikTokError(\n \"ffmpeg-not-found\",\n \"FFmpeg not found. Install it:\\n\" +\n \" Linux: apt install ffmpeg / brew install ffmpeg / pacman -S ffmpeg\\n\" +\n \" macOS: brew install ffmpeg\\n\" +\n \" Windows: choco install ffmpeg\",\n )\n }\n try {\n const result = await execa(ffmpegPath, args, {\n cancelSignal: signal,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n return result.stdout ?? \"\"\n } catch (err: unknown) {\n if (signal?.aborted) {\n throw new TikTokError(\"aborted\", \"Aborted by user\")\n }\n const message = err instanceof Error ? err.message : String(err)\n throw new TikTokError(\"ffmpeg-error\", `FFmpeg failed: ${message}`)\n }\n}\n\n/**\n * Build FFmpeg HTTP option arguments for cookies and headers.\n * TikTok's CDN requires session cookies and a Referer to serve the stream.\n */\nfunction buildHttpArgs(cookies?: Record<string, string>): string[] {\n const args: string[] = []\n\n // ponytail: user-agent header, CDNs tend to be picky\n args.push(\n \"-user_agent\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:149.0) Gecko/20100101 Firefox/149.0\",\n )\n args.push(\"-headers\", \"Referer: https://www.tiktok.com/\\r\\n\")\n\n if (cookies && Object.keys(cookies).length > 0) {\n const cookieStr = Object.entries(cookies)\n .map(([k, v]) => `${k}=${v}`)\n .join(\"\\r\\n\")\n args.push(\"-cookies\", cookieStr)\n }\n\n return args\n}\n\n/** Standard FFmpeg reconnect + mpegts pipe arguments. */\nconst FFMPEG_BASE_ARGS = [\n \"-reconnect\",\n \"1\",\n \"-reconnect_at_eof\",\n \"1\",\n \"-reconnect_streamed\",\n \"1\",\n \"-reconnect_delay_max\",\n \"5\",\n \"-c\",\n \"copy\",\n \"-f\",\n \"mpegts\",\n \"pipe:1\",\n]\n\n/**\n * Spawn an FFmpeg process to download from `url` and pipe its stdout to\n * `writer` with backpressure handling.\n *\n * Uses child_process.spawn directly (not execa) because execa v9 defaults\n * to encoding stdout as UTF-8, which corrupts binary MPEG-TS data.\n */\nexport async function pipeFfmpegSegment(\n ffmpegPath: string,\n url: string,\n writer: WriteStream,\n signal: AbortSignal,\n maxDuration?: number,\n cookies?: Record<string, string>,\n): Promise<void> {\n const durationArgs = maxDuration ? [\"-t\", String(maxDuration)] : []\n const httpArgs = buildHttpArgs(cookies)\n // ponytail: input options (-headers, -cookies, -user_agent) must come before -i\n const args = [...httpArgs, \"-i\", url, ...durationArgs, ...FFMPEG_BASE_ARGS]\n const proc: ChildProcess = spawn(ffmpegPath, args, {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n\n let stderr = \"\"\n let firstDataTimer: ReturnType<typeof setTimeout> | null = null\n\n const clearStartupTimer = () => {\n if (firstDataTimer) {\n clearTimeout(firstDataTimer)\n firstDataTimer = null\n }\n }\n\n // Forward abort signal to process\n const onAbort = () => {\n if (!proc.killed) proc.kill(\"SIGTERM\")\n }\n signal.addEventListener(\"abort\", onAbort, { once: true })\n\n proc.stderr?.on(\"data\", (chunk: Buffer) => {\n clearStartupTimer()\n stderr += chunk.toString()\n if (stderr.length > 10000) stderr = stderr.slice(-5000)\n })\n\n proc.stdout?.on(\"data\", (chunk: Buffer) => {\n clearStartupTimer()\n const canContinue = writer.write(chunk)\n if (!canContinue) {\n proc.stdout?.pause()\n writer.once(\"drain\", () => proc.stdout?.resume())\n }\n })\n\n await new Promise<void>((resolve, reject) => {\n firstDataTimer = setTimeout(() => {\n if (!proc.killed) {\n proc.kill(\"SIGTERM\")\n setTimeout(() => {\n if (!proc.killed) proc.kill(\"SIGKILL\")\n }, 2000)\n }\n reject(\n new TikTokError(\n \"ffmpeg-error\",\n `FFmpeg startup timed out after ${FFMPEG_STARTUP_TIMEOUT / 1000}s\\n${stderr.slice(-500)}`,\n ),\n )\n }, FFMPEG_STARTUP_TIMEOUT)\n\n proc.on(\"close\", (code) => {\n clearStartupTimer()\n signal.removeEventListener(\"abort\", onAbort)\n if (signal.aborted) {\n resolve()\n return\n }\n if (code === 0 || code === null) {\n resolve()\n return\n }\n reject(\n new TikTokError(\"ffmpeg-error\", `FFmpeg exited with code ${code}\\n${stderr.slice(-500)}`),\n )\n })\n\n proc.on(\"error\", (err) => {\n clearStartupTimer()\n signal.removeEventListener(\"abort\", onAbort)\n reject(err)\n })\n })\n}\n"],"mappings":";;;;;;;;;;;;;;AAgBA,MAAa,yBAAyB;;AAGtC,SAAgB,iBAAgC;CAC9C,MAAM,WAAY,WAAoE,KAAK;CAC3F,IAAI,OAAO,aAAa,YACtB,OAAQ,SAAS,QAAQ,KAAgB;CAE3C,MAAM,QAAQ,QAAQ,IAAI,MAAM,MAAM,GAAG,KAAK,CAAC;CAC/C,KAAK,MAAM,OAAO,OAChB,IAAI;EACF,MAAM,OAAO,GAAG,IAAI;EACpB,SAAS,IAAI;EACb,OAAO;CACT,QAAQ,CAER;CAEF,OAAO;AACT;;;;;AAMA,eAAsB,UAAU,MAAgB,QAAuC;CACrF,MAAM,aAAa,eAAe;CAClC,IAAI,CAAC,YACH,MAAM,IAAI,YACR,oBACA,sKAIF;CAEF,IAAI;EAKF,QAAO,MAJc,MAAM,YAAY,MAAM;GAC3C,cAAc;GACd,OAAO;IAAC;IAAU;IAAQ;GAAM;EAClC,CAAC,EAAA,CACa,UAAU;CAC1B,SAAS,KAAc;EACrB,IAAI,QAAQ,SACV,MAAM,IAAI,YAAY,WAAW,iBAAiB;EAGpD,MAAM,IA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EACzC,kBAAkB;EAElB,IAAI,CADgB,OAAO,MAAM,KAClB,GAAG;GAChB,KAAK,QAAQ,MAAM;GACnB,OAAO,KAAK,eAAe,KAAK,QAAQ,OAAO,CAAC;EAClD;CACF,CAAC;CAED,MAAM,IAAI,SAAe,SAAS,WAAW;EAC3C,iBAAiB,iBAAiB;GAChC,IAAI,CAAC,KAAK,QAAQ;IAChB,KAAK,KAAK,SAAS;IACnB,iBAAiB;KACf,IAAI,CAAC,KAAK,QAAQ,KAAK,KAAK,SAAS;IACvC,GAAG,GAAI;GACT;GACA,OACE,IAAI,YACF,gBACA,kCAAkC,yBAAyB,IAAK,KAAK,OAAO,MAAM,IAAI,GACxF,CACF;EACF,GAAG,sBAAsB;EAEzB,KAAK,GAAG,UAAU,SAAS;GACzB,kBAAkB;GAClB,OAAO,oBAAoB,SAAS,OAAO;GAC3C,IAAI,OAAO,SAAS;IAClB,QAAQ;IACR;GACF;GACA,IAAI,SAAS,KAAK,SAAS,MAAM;IAC/B,QAAQ;IACR;GACF;GACA,OACE,IAAI,YAAY,gBAAgB,2BAA2B,KAAK,IAAI,OAAO,MAAM,IAAI,GAAG,CAC1F;EACF,CAAC;EAED,KAAK,GAAG,UAAU,QAAQ;GACxB,kBAAkB;GAClB,OAAO,oBAAoB,SAAS,OAAO;GAC3C,OAAO,GAAG;EACZ,CAAC;CACH,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"ffmpeg.mjs","names":[],"sources":["../../../src/io/media/ffmpeg.ts"],"sourcesContent":["/**\n * FFmpeg — the single home for process invocation.\n *\n * Two entry points: `pipeFfmpegSegment` streams stdout into a `WriteStream`\n * (live capture) and `createMediaConverter` builds the remux/segment capability\n * the job consumes. Locating the binary lives here too, so no caller\n * reimplements a PATH lookup.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\"\nimport type { WriteStream } from \"node:fs\"\nimport { statSync, unlinkSync } from \"node:fs\"\nimport { execa } from \"execa\"\nimport { TikTokError } from \"../../core/errors\"\nimport type { Logger } from \"../../core/log\"\n\n/** Kill FFmpeg if no output is received within this window after spawn. */\nconst FFMPEG_STARTUP_TIMEOUT = 30_000\n\n/** Find the FFmpeg binary via `Bun.which()` or a PATH search. */\nexport function findFfmpegPath(): string | null {\n const bunWhich = (globalThis as { Bun?: { which?: (cmd: string) => string | null } }).Bun?.which\n if (typeof bunWhich === \"function\") {\n return (bunWhich(\"ffmpeg\") as string) ?? null\n }\n const paths = process.env.PATH?.split(\":\") ?? []\n for (const dir of paths) {\n try {\n const full = `${dir}/ffmpeg`\n statSync(full)\n return full\n } catch {\n // not found in this directory\n }\n }\n return null\n}\n\n/**\n * Run FFmpeg to completion and return stdout — for output that is a file\n * rather than a pipe (the segment muxer's `-segment_list pipe:1`).\n */\nasync function runFfmpeg(args: string[], signal?: AbortSignal): Promise<string> {\n const ffmpegPath = findFfmpegPath()\n if (!ffmpegPath) {\n throw new TikTokError(\n \"ffmpeg-not-found\",\n \"FFmpeg not found. Install it:\\n\" +\n \" Linux: apt install ffmpeg / brew install ffmpeg / pacman -S ffmpeg\\n\" +\n \" macOS: brew install ffmpeg\\n\" +\n \" Windows: choco install ffmpeg\",\n )\n }\n try {\n const result = await execa(ffmpegPath, args, {\n cancelSignal: signal,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n return result.stdout ?? \"\"\n } catch (err: unknown) {\n if (signal?.aborted) {\n throw new TikTokError(\"aborted\", \"Aborted by user\")\n }\n const message = err instanceof Error ? err.message : String(err)\n throw new TikTokError(\"ffmpeg-error\", `FFmpeg failed: ${message}`)\n }\n}\n\n/** The media-processing capability `RecordingJob` depends on. */\nexport interface MediaConverter {\n /** Convert a TS file to MP4 (stream copy). Deletes the original on success. */\n convert: (input: string) => Promise<string>\n /** Split a file into `<name>_partN.mp4`; returns FFmpeg's CSV segment listing. */\n segment: (input: string, segmentSeconds: number, outputPattern: string) => Promise<string>\n}\n\nexport function createMediaConverter(logger?: Logger, signal?: AbortSignal): MediaConverter {\n async function convert(input: string): Promise<string> {\n const output = input.replace(/\\.(flv|ts)$/i, \".mp4\")\n logger?.info(`Converting: ${input} → ${output}`)\n\n await runFfmpeg([\"-i\", input, \"-c\", \"copy\", \"-y\", output], signal)\n\n try {\n unlinkSync(input)\n logger?.info(`Deleted original: ${input}`)\n } catch {\n logger?.warn(`Could not delete original: ${input}`)\n }\n\n return output\n }\n\n async function segment(\n input: string,\n segmentSeconds: number,\n outputPattern: string,\n ): Promise<string> {\n return runFfmpeg(\n [\n \"-i\",\n input,\n \"-c\",\n \"copy\",\n \"-f\",\n \"segment\",\n \"-segment_time\",\n String(segmentSeconds),\n \"-reset_timestamps\",\n \"1\",\n \"-segment_start_number\",\n \"1\",\n \"-segment_list\",\n \"pipe:1\",\n \"-segment_list_type\",\n \"csv\",\n outputPattern,\n ],\n signal,\n )\n }\n\n return { convert, segment }\n}\n\n/**\n * Build FFmpeg HTTP option arguments for cookies and headers.\n * TikTok's CDN requires session cookies and a Referer to serve the stream.\n */\nfunction buildHttpArgs(cookies?: Record<string, string>): string[] {\n const args: string[] = []\n\n // ponytail: user-agent header, CDNs tend to be picky\n args.push(\n \"-user_agent\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:149.0) Gecko/20100101 Firefox/149.0\",\n )\n args.push(\"-headers\", \"Referer: https://www.tiktok.com/\\r\\n\")\n\n if (cookies && Object.keys(cookies).length > 0) {\n const cookieStr = Object.entries(cookies)\n .map(([k, v]) => `${k}=${v}`)\n .join(\"\\r\\n\")\n args.push(\"-cookies\", cookieStr)\n }\n\n return args\n}\n\n/** Standard FFmpeg reconnect + mpegts pipe arguments. */\nconst FFMPEG_BASE_ARGS = [\n \"-reconnect\",\n \"1\",\n \"-reconnect_at_eof\",\n \"1\",\n \"-reconnect_streamed\",\n \"1\",\n \"-reconnect_delay_max\",\n \"5\",\n \"-c\",\n \"copy\",\n \"-f\",\n \"mpegts\",\n \"pipe:1\",\n]\n\n/**\n * Spawn an FFmpeg process to download from `url` and pipe its stdout to\n * `writer` with backpressure handling.\n *\n * Uses child_process.spawn directly (not execa) because execa v9 defaults\n * to encoding stdout as UTF-8, which corrupts binary MPEG-TS data.\n */\nexport async function pipeFfmpegSegment(\n ffmpegPath: string,\n url: string,\n writer: WriteStream,\n signal: AbortSignal,\n maxDuration?: number,\n cookies?: Record<string, string>,\n): Promise<void> {\n const durationArgs = maxDuration ? [\"-t\", String(maxDuration)] : []\n const httpArgs = buildHttpArgs(cookies)\n // ponytail: input options (-headers, -cookies, -user_agent) must come before -i\n const args = [...httpArgs, \"-i\", url, ...durationArgs, ...FFMPEG_BASE_ARGS]\n const proc: ChildProcess = spawn(ffmpegPath, args, {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n\n let stderr = \"\"\n let firstDataTimer: ReturnType<typeof setTimeout> | null = null\n\n const clearStartupTimer = () => {\n if (firstDataTimer) {\n clearTimeout(firstDataTimer)\n firstDataTimer = null\n }\n }\n\n // Forward abort signal to process\n const onAbort = () => {\n if (!proc.killed) proc.kill(\"SIGTERM\")\n }\n signal.addEventListener(\"abort\", onAbort, { once: true })\n\n proc.stderr?.on(\"data\", (chunk: Buffer) => {\n clearStartupTimer()\n stderr += chunk.toString()\n if (stderr.length > 10000) stderr = stderr.slice(-5000)\n })\n\n proc.stdout?.on(\"data\", (chunk: Buffer) => {\n clearStartupTimer()\n const canContinue = writer.write(chunk)\n if (!canContinue) {\n proc.stdout?.pause()\n writer.once(\"drain\", () => proc.stdout?.resume())\n }\n })\n\n await new Promise<void>((resolve, reject) => {\n firstDataTimer = setTimeout(() => {\n if (!proc.killed) {\n proc.kill(\"SIGTERM\")\n setTimeout(() => {\n if (!proc.killed) proc.kill(\"SIGKILL\")\n }, 2000)\n }\n reject(\n new TikTokError(\n \"ffmpeg-error\",\n `FFmpeg startup timed out after ${FFMPEG_STARTUP_TIMEOUT / 1000}s\\n${stderr.slice(-500)}`,\n ),\n )\n }, FFMPEG_STARTUP_TIMEOUT)\n\n proc.on(\"close\", (code) => {\n clearStartupTimer()\n signal.removeEventListener(\"abort\", onAbort)\n if (signal.aborted) {\n resolve()\n return\n }\n if (code === 0 || code === null) {\n resolve()\n return\n }\n reject(\n new TikTokError(\"ffmpeg-error\", `FFmpeg exited with code ${code}\\n${stderr.slice(-500)}`),\n )\n })\n\n proc.on(\"error\", (err) => {\n clearStartupTimer()\n signal.removeEventListener(\"abort\", onAbort)\n reject(err)\n })\n })\n}\n"],"mappings":";;;;;;;;;;;;;;AAiBA,MAAM,yBAAyB;;AAG/B,SAAgB,iBAAgC;CAC9C,MAAM,WAAY,WAAoE,KAAK;CAC3F,IAAI,OAAO,aAAa,YACtB,OAAQ,SAAS,QAAQ,KAAgB;CAE3C,MAAM,QAAQ,QAAQ,IAAI,MAAM,MAAM,GAAG,KAAK,CAAC;CAC/C,KAAK,MAAM,OAAO,OAChB,IAAI;EACF,MAAM,OAAO,GAAG,IAAI;EACpB,SAAS,IAAI;EACb,OAAO;CACT,QAAQ,CAER;CAEF,OAAO;AACT;;;;;AAMA,eAAe,UAAU,MAAgB,QAAuC;CAC9E,MAAM,aAAa,eAAe;CAClC,IAAI,CAAC,YACH,MAAM,IAAI,YACR,oBACA,sKAIF;CAEF,IAAI;EAKF,QAAO,MAJc,MAAM,YAAY,MAAM;GAC3C,cAAc;GACd,OAAO;IAAC;IAAU;IAAQ;GAAM;EAClC,CAAC,EAAA,CACa,UAAU;CAC1B,SAAS,KAAc;EACrB,IAAI,QAAQ,SACV,MAAM,IAAI,YAAY,WAAW,iBAAiB;EAGpD,MAAM,IAAI,YAAY,gBAAgB,kBADtB,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,GACE;CACnE;AACF;AAUA,SAAgB,qBAAqB,QAAiB,QAAsC;CAC1F,eAAe,QAAQ,OAAgC;EACrD,MAAM,SAAS,MAAM,QAAQ,gBAAgB,MAAM;EACnD,QAAQ,KAAK,eAAe,MAAM,KAAK,QAAQ;EAE/C,MAAM,UAAU;GAAC;GAAM;GAAO;GAAM;GAAQ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createProfileSource()
|
|
21
21
|
];
|
|
22
|
-
async function ensureCache(user) {
|
|
23
|
-
if (cached && cachedUser === user) return cached;
|
|
24
|
-
cached = await resolveVerdict(user);
|
|
25
|
-
cachedUser = user;
|
|
26
|
-
return cached;
|
|
27
|
-
}
|
|
28
|
-
function invalidateCache() {
|
|
29
|
-
cached = null;
|
|
30
|
-
cachedUser = "";
|
|
31
|
-
}
|
|
32
22
|
return {
|
|
33
|
-
invalidateCache
|
|
23
|
+
invalidateCache() {
|
|
24
|
+
cached = null;
|
|
25
|
+
cachedUser = "";
|
|
26
|
+
},
|
|
34
27
|
async getVerdict(user) {
|
|
35
|
-
|
|
28
|
+
if (!cached || cachedUser !== user) {
|
|
29
|
+
cached = await resolveVerdict(user);
|
|
30
|
+
cachedUser = user;
|
|
31
|
+
}
|
|
32
|
+
return cached;
|
|
36
33
|
},
|
|
37
34
|
async isRoomAlive(roomId) {
|
|
38
35
|
if (cached?.room && String(cached.room.id) === String(roomId)) return isLiveReason(cached.reason);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.mjs","names":[],"sources":["../../../src/io/tiktok/client.ts"],"sourcesContent":["/**\n * TikTok API — resolves room IDs, live status, and stream URLs.\n *\n * `createTikTokClient` is a thin orchestrator: per-
|
|
1
|
+
{"version":3,"file":"client.mjs","names":[],"sources":["../../../src/io/tiktok/client.ts"],"sourcesContent":["/**\n * TikTok API — resolves room IDs, live status, and stream URLs.\n *\n * `createTikTokClient` is a thin orchestrator: per-tick cache, cache\n * invalidation, and `discover()` over sources returning `Candidate`s. The chain\n * turns failures into evidence instead of aborting. `getVerdict` is the only\n * public verdict surface.\n *\n * All public methods share a per-tick cache so the page is fetched at most once\n * per poll cycle. The optional `signal` aborts in-flight HTTP requests.\n */\n\nimport type { Logger } from \"../../core/log\"\nimport { isLiveReason, type Verdict, verdictOf } from \"../../core/verdict\"\nimport type { HttpClient } from \"../http\"\nimport { type DiscoverySource, discover, type ResolveContext } from \"./discovery/chain\"\nimport { createApiLiveSource, createProfileSource } from \"./discovery/fallback\"\nimport { createPageSource } from \"./discovery/page\"\nimport { createPageFetcher } from \"./page\"\nimport { createWebcastApi } from \"./webcast\"\n\nexport interface TikTokClient {\n /** Check if a room is currently live. */\n isRoomAlive(roomId: string): Promise<boolean>\n /** Get the best-quality FLV stream URL for a room. Returns null on failure. */\n getLiveUrl(roomId: string): Promise<string | null>\n /** Full per-tick verdict with reason, refs, evidence trail, and failure. */\n getVerdict(user: string): Promise<Verdict>\n /** Invalidate per-tick cache (call at start of each poll tick). */\n invalidateCache(): void\n}\n\nexport function createTikTokClient(\n http: HttpClient,\n logger?: Logger,\n showDebug?: boolean,\n signal?: AbortSignal,\n): TikTokClient {\n // Debug logging helper — writes to stderr only when --debug is passed.\n const debug = (msg: string) => {\n logger?.debug(msg)\n if (showDebug) process.stderr.write(`[API_DEBUG] ${msg}\\n`)\n }\n let cached: Verdict | null = null\n let cachedUser = \"\"\n const webcast = createWebcastApi(http, debug, signal)\n const tryFetchPage = createPageFetcher(http, debug, signal)\n const sources: DiscoverySource[] = [\n createPageSource(),\n createApiLiveSource(),\n createProfileSource(),\n ]\n\n return {\n invalidateCache() {\n cached = null\n cachedUser = \"\"\n },\n\n async getVerdict(user: string): Promise<Verdict> {\n if (!cached || cachedUser !== user) {\n cached = await resolveVerdict(user)\n cachedUser = user\n }\n return cached\n },\n\n async isRoomAlive(roomId: string): Promise<boolean> {\n if (cached?.room && String(cached.room.id) === String(roomId)) {\n return isLiveReason(cached.reason)\n }\n // Use the lightweight check_alive endpoint instead of re-fetching\n // the full room/info response.\n return webcast.fetchCheckAlive(roomId)\n },\n\n async getLiveUrl(roomId: string): Promise<string | null> {\n if (cached?.room && String(cached.room.id) === String(roomId) && cached.stream) {\n return cached.stream.url\n }\n // Room ID, not a username: never route this through the user cache.\n const res = await webcast.fetchStreamUrlFromApi(roomId)\n return res.ok ? res.value : null\n },\n }\n\n // ─── Internal: discovery chain → one verdict ───\n\n async function resolveVerdict(user: string): Promise<Verdict> {\n const ctx: ResolveContext = { user, http, debug, fetchPage: tryFetchPage, webcast }\n const { candidate, evidence } = await discover(sources, ctx)\n switch (candidate.kind) {\n case \"room\":\n return verdictOf({ room: candidate.room, stream: candidate.stream, evidence })\n case \"denied\":\n return verdictOf({ room: candidate.room, denied: true, evidence })\n case \"failed\":\n return verdictOf({ failure: candidate.error, evidence })\n case \"miss\":\n return verdictOf({ evidence })\n }\n }\n}\n"],"mappings":";;;;;;;AAgCA,SAAgB,mBACd,MACA,QACA,WACA,QACc;CAEd,MAAM,SAAS,QAAgB;EAC7B,QAAQ,MAAM,GAAG;EACjB,IAAI,WAAW,QAAQ,OAAO,MAAM,eAAe,IAAI,GAAG;CAC5D;CACA,IAAI,SAAyB;CAC7B,IAAI,aAAa;CACjB,MAAM,UAAU,iBAAiB,MAAM,OAAO,MAAM;CACpD,MAAM,eAAe,kBAAkB,MAAM,OAAO,MAAM;CAC1D,MAAM,UAA6B;EACjC,iBAAiB;EACjB,oBAAoB;EACpB,oBAAoB;CACtB;CAEA,OAAO;EACL,kBAAkB;GAChB,SAAS;GACT,aAAa;EACf;EAEA,MAAM,WAAW,MAAgC;GAC/C,IAAI,CAAC,UAAU,eAAe,MAAM;IAClC,SAAS,MAAM,eAAe,IAAI;IAClC,aAAa;GACf;GACA,OAAO;EACT;EAEA,MAAM,YAAY,QAAkC;GAClD,IAAI,QAAQ,QAAQ,OAAO,OAAO,KAAK,EAAE,MAAM,OAAO,MAAM,GAC1D,OAAO,aAAa,OAAO,MAAM;GAInC,OAAO,QAAQ,gBAAgB,MAAM;EACvC;EAEA,MAAM,WAAW,QAAwC;GACvD,IAAI,QAAQ,QAAQ,OAAO,OAAO,KAAK,EAAE,MAAM,OAAO,MAAM,KAAK,OAAO,QACtE,OAAO,OAAO,OAAO;GAGvB,MAAM,MAAM,MAAM,QAAQ,sBAAsB,MAAM;GACtD,OAAO,IAAI,KAAK,IAAI,QAAQ;EAC9B;CACF;CAIA,eAAe,eAAe,MAAgC;EAE5D,MAAM,EAAE,WAAW,aAAa,MAAM,SAAS,SAAS;GAD1B;GAAM;GAAM;GAAO,WAAW;GAAc;EAChB,CAAC;EAC3D,QAAQ,UAAU,MAAlB;GACE,KAAK,QACH,OAAO,UAAU;IAAE,MAAM,UAAU;IAAM,QAAQ,UAAU;IAAQ;GAAS,CAAC;GAC/E,KAAK,UACH,OAAO,UAAU;IAAE,MAAM,UAAU;IAAM,QAAQ;IAAM;GAAS,CAAC;GACnE,KAAK,UACH,OAAO,UAAU;IAAE,SAAS,UAAU;IAAO;GAAS,CAAC;GACzD,KAAK,QACH,OAAO,UAAU,EAAE,SAAS,CAAC;EACjC;CACF;AACF"}
|
|
@@ -65,13 +65,14 @@ async function refused(ctx, roomId, title, source) {
|
|
|
65
65
|
};
|
|
66
66
|
}
|
|
67
67
|
function outcomeOf(candidate) {
|
|
68
|
-
|
|
69
|
-
case "room": return "hit";
|
|
70
|
-
case "denied": return "denied";
|
|
71
|
-
case "failed": return "error";
|
|
72
|
-
case "miss": return "miss";
|
|
73
|
-
}
|
|
68
|
+
return OUTCOME[candidate.kind];
|
|
74
69
|
}
|
|
70
|
+
const OUTCOME = {
|
|
71
|
+
room: "hit",
|
|
72
|
+
denied: "denied",
|
|
73
|
+
failed: "error",
|
|
74
|
+
miss: "miss"
|
|
75
|
+
};
|
|
75
76
|
/**
|
|
76
77
|
* Run discovery sources in order. A throw — sync or async — becomes a
|
|
77
78
|
* `failed` candidate and the chain continues: the `probe.ts:154` dead end,
|
|
@@ -85,17 +86,13 @@ async function discover(sources, ctx) {
|
|
|
85
86
|
note: "no sources configured"
|
|
86
87
|
};
|
|
87
88
|
for (const source of sources) {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
error: error instanceof Error ? error : new Error(String(error))
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
})();
|
|
89
|
+
let candidate;
|
|
90
|
+
try {
|
|
91
|
+
candidate = await source.find(ctx);
|
|
92
|
+
} catch (error) {
|
|
93
|
+
ctx.debug(`discover: ${source.id} threw — ${error instanceof Error ? error.message : error}`);
|
|
94
|
+
candidate = failed(error);
|
|
95
|
+
}
|
|
99
96
|
evidence.push({
|
|
100
97
|
source: candidate.kind === "room" || candidate.kind === "denied" ? candidate.source : source.id,
|
|
101
98
|
outcome: outcomeOf(candidate)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chain.mjs","names":[],"sources":["../../../../src/io/tiktok/discovery/chain.ts"],"sourcesContent":["/**\n * Discovery chain — one idea in one file: a source reports facts, the chain\n * turns every outcome (including a throw) into evidence, and the first room or\n * gate refusal ends it.\n
|
|
1
|
+
{"version":3,"file":"chain.mjs","names":[],"sources":["../../../../src/io/tiktok/discovery/chain.ts"],"sourcesContent":["/**\n * Discovery chain — one idea in one file: a source reports facts, the chain\n * turns every outcome (including a throw) into evidence, and the first room or\n * gate refusal ends it.\n */\n\nimport type { Evidence, EvidenceOutcome, RoomRef, SourceId, StreamRef } from \"../../../core/verdict\"\nimport type { HttpClient } from \"../../http\"\nimport type { WebcastReader } from \"../webcast\"\n\n/**\n * What one discovery source found. `room`/`denied` end the chain; `miss` and\n * `failed` let the next source try — a throw is evidence, never a dead end.\n */\nexport type Candidate =\n | { kind: \"room\"; room: RoomRef; stream: StreamRef | null; source: SourceId }\n | { kind: \"denied\"; room: RoomRef; code: number; source: SourceId }\n | { kind: \"miss\"; note: string }\n | { kind: \"failed\"; error: Error }\n\nexport interface ResolveContext {\n user: string\n http: HttpClient\n debug: (msg: string) => void\n fetchPage: (user: string, path: string) => Promise<{ html: string; baseUrl: string } | null>\n webcast: WebcastReader\n}\n\nexport interface DiscoverySource {\n readonly id: \"page\" | \"api-live\" | \"profile\"\n find(ctx: ResolveContext): Promise<Candidate>\n}\n\n// ─── candidate constructors ────────────────────────────────\n\n/** Nothing found here — let the next source try. */\nexport function miss(note: string): Candidate {\n return { kind: \"miss\", note }\n}\n\n/** A transport/parse failure. The chain keeps going; it only wins over a miss. */\nexport function failed(error: unknown): Candidate {\n return { kind: \"failed\", error: error instanceof Error ? error : new Error(String(error)) }\n}\n\n/**\n * Room live with a stream URL. Uses `knownUrl` when the page already carried\n * it; otherwise asks the Webcast API. A 4003110 refusal becomes `denied`.\n */\nexport async function withStream(\n ctx: ResolveContext,\n room: RoomRef,\n source: SourceId,\n knownUrl: string | null,\n): Promise<Candidate> {\n if (knownUrl) return { kind: \"room\", room, stream: { url: knownUrl }, source }\n const res = await ctx.webcast.fetchStreamUrlFromApi(room.id)\n if (res.ok) {\n return { kind: \"room\", room, stream: res.value ? { url: res.value } : null, source }\n }\n if (res.statusCode === 4003110) return refused(ctx, room.id, room.title, source)\n return { kind: \"room\", room, stream: null, source }\n}\n\n/** Authoritative room/info lookup: the single 4003110 consumer for room IDs. */\nexport async function fromRoomInfo(\n ctx: ResolveContext,\n roomId: string,\n source: SourceId,\n): Promise<Candidate> {\n const res = await ctx.webcast.roomInfo(roomId)\n if (res.ok) {\n if (!res.value) return miss(`room/info returned no data for ${roomId}`)\n return { kind: \"room\", room: res.value.room, stream: res.value.stream, source }\n }\n if (res.statusCode === 4003110) return refused(ctx, roomId, null, source)\n if (res.statusCode === 0) return failed(new Error(`room/info transport failure for ${roomId}`))\n return miss(`room/info HTTP ${res.statusCode} for ${roomId}`)\n}\n\n/** Gate refusal: check_alive decides whether the room is live (restricted) or offline. */\nexport async function refused(\n ctx: ResolveContext,\n roomId: string,\n title: string | null,\n source: SourceId,\n): Promise<Candidate> {\n const room = await ctx.webcast.refusedRoom(roomId, title)\n return { kind: \"denied\", room, code: 4003110, source }\n}\n\n// ─── runner ────────────────────────────────────────────────\n\nfunction outcomeOf(candidate: Candidate): EvidenceOutcome {\n return OUTCOME[candidate.kind]\n}\n\nconst OUTCOME = {\n room: \"hit\",\n denied: \"denied\",\n failed: \"error\",\n miss: \"miss\",\n} satisfies Record<Candidate[\"kind\"], EvidenceOutcome>\n\n/**\n * Run discovery sources in order. A throw — sync or async — becomes a\n * `failed` candidate and the chain continues: the `probe.ts:154` dead end,\n * inverted. A room or a gate refusal ends the chain; the first failure\n * outranks a later miss.\n */\nexport async function discover(\n sources: readonly DiscoverySource[],\n ctx: ResolveContext,\n): Promise<{ candidate: Candidate; evidence: Evidence[] }> {\n const evidence: Evidence[] = []\n let best: Candidate = { kind: \"miss\", note: \"no sources configured\" }\n\n for (const source of sources) {\n let candidate: Candidate\n try {\n candidate = await source.find(ctx)\n } catch (error) {\n ctx.debug(`discover: ${source.id} threw — ${error instanceof Error ? error.message : error}`)\n candidate = failed(error)\n }\n evidence.push({\n source:\n candidate.kind === \"room\" || candidate.kind === \"denied\" ? candidate.source : source.id,\n outcome: outcomeOf(candidate),\n })\n if (candidate.kind === \"room\" || candidate.kind === \"denied\") return { candidate, evidence }\n // First failure is the root cause; a later failure must not overwrite it.\n if (candidate.kind === \"failed\" && best.kind !== \"failed\") best = candidate\n }\n\n return { candidate: best, evidence }\n}\n"],"mappings":";;AAoCA,SAAgB,KAAK,MAAyB;CAC5C,OAAO;EAAE,MAAM;EAAQ;CAAK;AAC9B;;AAGA,SAAgB,OAAO,OAA2B;CAChD,OAAO;EAAE,MAAM;EAAU,OAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;CAAE;AAC5F;;;;;AAMA,eAAsB,WACpB,KACA,MACA,QACA,UACoB;CACpB,IAAI,UAAU,OAAO;EAAE,MAAM;EAAQ;EAAM,QAAQ,EAAE,KAAK,SAAS;EAAG;CAAO;CAC7E,MAAM,MAAM,MAAM,IAAI,QAAQ,sBAAsB,KAAK,EAAE;CAC3D,IAAI,IAAI,IACN,OAAO;EAAE,MAAM;EAAQ;EAAM,QAAQ,IAAI,QAAQ,EAAE,KAAK,IAAI,MAAM,IAAI;EAAM;CAAO;CAErF,IAAI,IAAI,eAAe,SAAS,OAAO,QAAQ,KAAK,KAAK,IAAI,KAAK,O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SAAS,UAAU,SAAS;EAC9B,CAAC;EACD,IAAI,UAAU,SAAS,UAAU,UAAU,SAAS,UAAU,OAAO;GAAE;GAAW;EAAS;EAE3F,IAAI,UAAU,SAAS,YAAY,KAAK,SAAS,UAAU,OAAO;CACpE;CAEA,OAAO;EAAE,WAAW;EAAM;CAAS;AACrC"}
|
|
@@ -10,61 +10,48 @@ function createPageSource() {
|
|
|
10
10
|
return {
|
|
11
11
|
id: "page",
|
|
12
12
|
async find(ctx) {
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
const page = await ctx.fetchPage(ctx.user, "/live");
|
|
14
|
+
const html = page?.html ?? "";
|
|
15
|
+
ctx.debug(page ? `fetchLiveInfo: /live returned ${html.length} bytes (${page.baseUrl})` : "fetchLiveInfo: all domains blocked for /live page");
|
|
15
16
|
let failure = null;
|
|
16
|
-
const
|
|
17
|
+
const attempt = async (pending) => {
|
|
18
|
+
const candidate = await pending;
|
|
17
19
|
if (candidate.kind === "room" || candidate.kind === "denied") return candidate;
|
|
18
20
|
if (candidate.kind === "failed") failure ??= candidate;
|
|
19
21
|
return null;
|
|
20
22
|
};
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
}
|
|
49
|
-
if (userInfo?.roomId) {
|
|
50
|
-
const roomId = String(userInfo.roomId);
|
|
51
|
-
ctx.debug(`fetchLiveInfo: userInfo fallback — roomId=${roomId}, querying Webcast API`);
|
|
52
|
-
const found = take(await fromRoomInfo(ctx, roomId, "room-info"));
|
|
53
|
-
ctx.debug(`fetchLiveInfo: Webcast API ${found ? "returned room info" : "returned null"}`);
|
|
54
|
-
if (found) return found;
|
|
55
|
-
}
|
|
56
|
-
ctx.debug("fetchLiveInfo: trying legacy fallback (UserModule)");
|
|
57
|
-
const legacy = take(await sigiLegacy(sigi, ctx));
|
|
58
|
-
ctx.debug(`fetchLiveInfo: legacy fallback ${legacy ? "succeeded" : "returned null"}`);
|
|
59
|
-
if (legacy) return legacy;
|
|
60
|
-
}
|
|
23
|
+
const sigi = page ? extractSigiState(html) : null;
|
|
24
|
+
ctx.debug(`fetchLiveInfo: SIGI_STATE ${sigi ? "found" : "not found"}`);
|
|
25
|
+
const liveRoom = sigi?.LiveRoom?.liveRoomUserInfo?.liveRoom;
|
|
26
|
+
const roomId = sigi?.LiveRoom?.liveRoomUserInfo?.user?.roomId;
|
|
27
|
+
const id = roomId ? String(roomId) : null;
|
|
28
|
+
if (liveRoom && id) {
|
|
29
|
+
const room = {
|
|
30
|
+
id,
|
|
31
|
+
title: liveRoom.title ?? null,
|
|
32
|
+
live: liveRoom.status === 2
|
|
33
|
+
};
|
|
34
|
+
ctx.debug(`fetchLiveInfo: primary path — roomId=${room.id}, live=${room.live}`);
|
|
35
|
+
if (!room.live) return {
|
|
36
|
+
kind: "room",
|
|
37
|
+
room,
|
|
38
|
+
stream: null,
|
|
39
|
+
source: "sigi"
|
|
40
|
+
};
|
|
41
|
+
return withStream(ctx, room, "sigi", extractStreamUrlFast(liveRoom) ?? findStreamUrlRecursively(sigi));
|
|
42
|
+
}
|
|
43
|
+
if (id) {
|
|
44
|
+
const found = await attempt(fromRoomInfo(ctx, id, "room-info"));
|
|
45
|
+
if (found) return found;
|
|
46
|
+
}
|
|
47
|
+
if (sigi) {
|
|
48
|
+
const found = await attempt(sigiLegacy(sigi, ctx));
|
|
49
|
+
if (found) return found;
|
|
61
50
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
const found = take(await fromRoomInfo(ctx, roomId, "room-info"));
|
|
67
|
-
ctx.debug(`fetchLiveInfo: universal data Webcast API ${found ? "succeeded" : "returned null"}`);
|
|
51
|
+
const universalRoomId = extractUserFromUniversalData(html).roomId;
|
|
52
|
+
ctx.debug(`fetchLiveInfo: universal data roomId=${universalRoomId ?? "null"}`);
|
|
53
|
+
if (universalRoomId) {
|
|
54
|
+
const found = await attempt(fromRoomInfo(ctx, universalRoomId, "room-info"));
|
|
68
55
|
if (found) return found;
|
|
69
56
|
}
|
|
70
57
|
return failure ?? miss("page: no room id");
|
|
@@ -79,9 +66,8 @@ function createPageSource() {
|
|
|
79
66
|
*/
|
|
80
67
|
async function sigiLegacy(sigi, ctx) {
|
|
81
68
|
const isLive = sigi.LiveRoom?.liveRoomStatus === 2;
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
if (userModule?.roomId) roomId = typeof userModule.roomId === "object" ? String(userModule.roomId.id ?? "") : String(userModule.roomId);
|
|
69
|
+
const raw = (sigi.UserModule?.users?.[ctx.user])?.roomId;
|
|
70
|
+
const roomId = raw ? String(typeof raw === "object" ? raw.id ?? "" : raw) : "";
|
|
85
71
|
if (!roomId) return miss("sigi-legacy: no roomId");
|
|
86
72
|
const room = {
|
|
87
73
|
id: roomId,
|
|
@@ -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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