cursedbelt-server 4.58.0 → 4.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/server/engagement/api.d.ts +6 -0
  2. package/dist/server/engagement/api.js +3 -0
  3. package/dist/server/engagement/d1.d.ts +7 -0
  4. package/dist/server/engagement/d1.js +4 -0
  5. package/dist/server/engagement/events.d.ts +26 -0
  6. package/dist/server/engagement/events.js +52 -0
  7. package/dist/server/engagement/policy.d.ts +2 -1
  8. package/dist/server/engagement/policy.js +11 -3
  9. package/dist/server/events/actions.d.ts +46 -0
  10. package/dist/server/events/actions.js +62 -0
  11. package/dist/server/events/actor.d.ts +19 -0
  12. package/dist/server/events/actor.js +30 -0
  13. package/dist/server/events/gauge.d.ts +21 -0
  14. package/dist/server/events/gauge.js +60 -0
  15. package/dist/server/events/index.d.ts +14 -0
  16. package/dist/server/events/index.js +14 -0
  17. package/dist/server/events/point.d.ts +77 -0
  18. package/dist/server/events/point.js +149 -0
  19. package/dist/server/events/sink.d.ts +97 -0
  20. package/dist/server/events/sink.js +113 -0
  21. package/dist/server/events/views.d.ts +24 -0
  22. package/dist/server/events/views.js +41 -0
  23. package/dist/server/youtube/ytdlp.d.ts +14 -4
  24. package/dist/server/youtube/ytdlp.js +11 -4
  25. package/package.json +8 -2
  26. package/src/server/bench/cpuBudget.spec.ts +12 -8
  27. package/src/server/engagement/api.ts +8 -0
  28. package/src/server/engagement/d1.ts +9 -0
  29. package/src/server/engagement/engagement.spec.ts +15 -1
  30. package/src/server/engagement/events.ts +79 -0
  31. package/src/server/engagement/policy.ts +10 -3
  32. package/src/server/events/actions.spec.ts +126 -0
  33. package/src/server/events/actions.ts +113 -0
  34. package/src/server/events/actor.ts +34 -0
  35. package/src/server/events/gauge.spec.ts +75 -0
  36. package/src/server/events/gauge.ts +81 -0
  37. package/src/server/events/index.ts +47 -0
  38. package/src/server/events/point.spec.ts +145 -0
  39. package/src/server/events/point.ts +197 -0
  40. package/src/server/events/sink.spec.ts +289 -0
  41. package/src/server/events/sink.ts +221 -0
  42. package/src/server/events/views.ts +62 -0
  43. package/src/server/telemetryIsWorkerSafe.spec.ts +23 -0
  44. package/src/server/youtube/ytdlp.spec.ts +14 -2
  45. package/src/server/youtube/ytdlp.ts +25 -7
@@ -0,0 +1,221 @@
1
+ /**
2
+ * `createEventSink(binding, options)` — the one seam an app records user events through.
3
+ *
4
+ * ```ts
5
+ * const events = createEventSink(env.EVENTS, { app: "music", salt: env.EVENTS_SALT, build: env.MUSIC_BUILD_COMMIT,
6
+ * defer: (work) => ctx.waitUntil(work) });
7
+ * events.record(c.req.raw, { kind: "action", name: "file.upload", place: "upload", purpose: "upload",
8
+ * actor: { id: user.email, owner: user.isOwner }, status: 200, ms, bytes });
9
+ * ```
10
+ *
11
+ * `record` is synchronous, never throws, and is never awaited by a caller: a known actor writes
12
+ * at once; an anonymous one hashes first (Web Crypto is async) and writes when the digest lands,
13
+ * which `defer` (a Worker's `ctx.waitUntil`) keeps alive past the response. A write that fails is
14
+ * counted nowhere else — the schema's "a failure must never reach the user".
15
+ *
16
+ * What the request supplies, and the body never does: the address and User-Agent (the anonymous
17
+ * hash, the device, the bot verdict), `request.cf.country`, the Referer HOST for a public view,
18
+ * and whether an Access service token (`cf-access-client-id`) — a deploy smoke — sent it.
19
+ */
20
+ import type { AnalyticsEngineDataset } from "../metrics/telemetrySink.js";
21
+ import { anonymousActor } from "./actor.js";
22
+ import {
23
+ type ActorKind,
24
+ type EventKind,
25
+ type EventOutcome,
26
+ type EventPoint,
27
+ type EventPurpose,
28
+ type EventVia,
29
+ classifyDevice,
30
+ isBotUserAgent,
31
+ outcomeOf,
32
+ referrerHost,
33
+ toEventPoint,
34
+ } from "./point.js";
35
+
36
+ /** The `EVENTS` binding — the same shape as the `AE` binding `requestLogger` writes to. */
37
+ export type EventsDataset = AnalyticsEngineDataset;
38
+
39
+ /** Who did it, as far as the app knows. Absent or `id: null` → the anonymous hash. */
40
+ export interface EventActor {
41
+ /** The stable id the app already uses for the person — the email `requestLogger` writes. */
42
+ id?: string | null;
43
+ /** Human-readable: the display name or email. Default: the id. */
44
+ label?: string | null;
45
+ /** The app owner's own account (`SsoUser.isOwner`). */
46
+ owner?: boolean;
47
+ /** Said outright — `agent` for a bearer/service token, `smoke` for a deploy identity — else resolved. */
48
+ kind?: ActorKind;
49
+ }
50
+
51
+ export interface EventFields {
52
+ kind: EventKind;
53
+ name: string;
54
+ /** The page/view it happened on (a view's own name for a `view`). */
55
+ place?: string;
56
+ purpose: EventPurpose;
57
+ /** Default `web`. */
58
+ via?: EventVia;
59
+ actor?: EventActor | null;
60
+ tenant?: string;
61
+ /** The response status, read as the outcome (`outcomeOf`) unless `outcome` is given. */
62
+ status?: number;
63
+ outcome?: EventOutcome;
64
+ ms?: number;
65
+ bytes?: number;
66
+ value?: number;
67
+ /** A PUBLIC page's view: the Referer host is recorded. Never for anything behind a session. */
68
+ public?: boolean;
69
+ /** Overrides the sink's build stamp for this one point. */
70
+ build?: string;
71
+ }
72
+
73
+ export interface EventSinkOptions {
74
+ /** The registry id — `music`, `family`, `patterns`. */
75
+ app: string;
76
+ /** `EVENTS_SALT`; absent → `LOCAL_EVENTS_SALT` (local dev), and the write still happens. */
77
+ salt?: string | null;
78
+ /** The deploy's build stamp (`<APP>_BUILD_COMMIT`), for blob16. */
79
+ build?: string | null;
80
+ /** Accounts whose activity is a deploy smoke or stage walk. Default: `smoke@auth.local`. */
81
+ smokeAccounts?: readonly string[];
82
+ /** Keeps the anonymous hash's write alive past the response — a Worker's `ctx.waitUntil`. */
83
+ defer?: (work: Promise<unknown>) => void;
84
+ now?: () => number;
85
+ }
86
+
87
+ export interface EventSink {
88
+ /** False when no binding was passed: every `record` is then a no-op. */
89
+ readonly bound: boolean;
90
+ /** Record one event. Synchronous, never throws, never awaited. */
91
+ record(request: Request | null | undefined, fields: EventFields): void;
92
+ }
93
+
94
+ /** The stage walk's account (`apps/auth-stage/scripts/accessWalk.ts` → `SMOKE_ACCOUNT`). */
95
+ export const DEFAULT_SMOKE_ACCOUNTS: readonly string[] = ["smoke@auth.local"];
96
+
97
+ /**
98
+ * The stage registry's seeded accounts (`apps/auth-stage/scripts/seed.ts`): `stage-owner@` and
99
+ * `stage-user-<i>-<seed>@cursedalchemy.com`, which every app's stage walk signs in as. They exist on
100
+ * no production registry, so a point they make is a walk's — `smoke`, never a person.
101
+ */
102
+ const STAGE_SEED_ACCOUNT = /^stage-(?:owner|user-\d+-[0-9a-f]+)@cursedalchemy\.com$/;
103
+
104
+ /** Is this actor id a deploy smoke's or a stage walk's? `smokeAccounts` adds an app's own. */
105
+ export function isSmokeAccount(id: string, smokeAccounts: readonly string[] = DEFAULT_SMOKE_ACCOUNTS): boolean {
106
+ const lower = id.trim().toLowerCase();
107
+ if (lower === "") return false;
108
+ return STAGE_SEED_ACCOUNT.test(lower) || smokeAccounts.some((account) => account.toLowerCase() === lower);
109
+ }
110
+
111
+ /** What one request says about its sender — everything the point takes from headers. */
112
+ export interface RequestFacts {
113
+ ip: string;
114
+ userAgent: string;
115
+ country: string;
116
+ referrer: string;
117
+ /** An Access service token sent it — the deploy smokes' identity. */
118
+ serviceToken: boolean;
119
+ }
120
+
121
+ export function requestFacts(request: Request | null | undefined): RequestFacts {
122
+ if (!request) return { ip: "", userAgent: "", country: "", referrer: "", serviceToken: false };
123
+ const headers = request.headers;
124
+ const forwarded = headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "";
125
+ const cf = (request as { cf?: { country?: unknown } }).cf;
126
+ return {
127
+ ip: headers.get("cf-connecting-ip")?.trim() || forwarded,
128
+ userAgent: headers.get("user-agent") ?? "",
129
+ country: typeof cf?.country === "string" ? cf.country : "",
130
+ referrer: referrerHost(headers.get("referer")),
131
+ serviceToken: headers.has("cf-access-client-id"),
132
+ };
133
+ }
134
+
135
+ /** The schema's actorKind rule, as one pure decision — `sink.spec.ts` pins each branch. */
136
+ export function resolveActorKind(input: {
137
+ actor: EventActor | null | undefined;
138
+ facts: Pick<RequestFacts, "userAgent" | "serviceToken">;
139
+ smokeAccounts: readonly string[];
140
+ }): ActorKind {
141
+ const { actor, facts } = input;
142
+ if (actor?.kind) return actor.kind;
143
+ const id = actor?.id?.trim().toLowerCase() ?? "";
144
+ if (isSmokeAccount(id, input.smokeAccounts)) return "smoke";
145
+ if (facts.serviceToken) return "smoke";
146
+ if (isBotUserAgent(facts.userAgent)) return "bot";
147
+ if (id) return actor?.owner ? "owner" : "user";
148
+ return "anon";
149
+ }
150
+
151
+ export function createEventSink(binding: EventsDataset | null | undefined, options: EventSinkOptions): EventSink {
152
+ const now = options.now ?? (() => Date.now());
153
+ const smokeAccounts = options.smokeAccounts ?? DEFAULT_SMOKE_ACCOUNTS;
154
+ const build = options.build ?? "";
155
+
156
+ const write = (point: EventPoint): void => {
157
+ try {
158
+ binding?.writeDataPoint(toEventPoint(point));
159
+ } catch (error) {
160
+ console.warn(`[events] a ${point.kind}:${point.name} point was not written: ${String(error)}`);
161
+ }
162
+ };
163
+
164
+ return {
165
+ bound: !!binding,
166
+ record(request, fields) {
167
+ if (!binding) return;
168
+ try {
169
+ const facts = requestFacts(request);
170
+ const actorKind = resolveActorKind({ actor: fields.actor, facts, smokeAccounts });
171
+ const id = fields.actor?.id?.trim() ?? "";
172
+ const base: Omit<EventPoint, "actor"> = {
173
+ app: options.app,
174
+ kind: fields.kind,
175
+ name: fields.name,
176
+ place: fields.place ?? "",
177
+ actorKind,
178
+ actorLabel: id ? (fields.actor?.label ?? id) : "",
179
+ tenant: fields.tenant ?? "",
180
+ via: fields.via ?? "web",
181
+ purpose: fields.purpose,
182
+ device: classifyDevice(facts.userAgent),
183
+ country: facts.country,
184
+ outcome: fields.outcome ?? outcomeOf(fields.status),
185
+ referrer: fields.public && fields.kind === "view" ? facts.referrer : "",
186
+ build: fields.build ?? build,
187
+ ms: fields.ms ?? 0,
188
+ bytes: fields.bytes ?? 0,
189
+ value: fields.value ?? 0,
190
+ };
191
+ if (id) {
192
+ write({ ...base, actor: id });
193
+ return;
194
+ }
195
+ // Machine traffic with no address at all (a cron, a gauge) has no identity to hash.
196
+ if (!facts.ip && !facts.userAgent) {
197
+ write({ ...base, actor: "" });
198
+ return;
199
+ }
200
+ const pending = anonymousActor({ ip: facts.ip, userAgent: facts.userAgent, salt: options.salt, now: now() })
201
+ .then((actor) => write({ ...base, actor }))
202
+ .catch((error: unknown) => {
203
+ console.warn(`[events] a ${fields.kind}:${fields.name} point was not written: ${String(error)}`);
204
+ });
205
+ options.defer?.(pending);
206
+ } catch (error) {
207
+ console.warn(`[events] a ${fields.kind}:${fields.name} point was not written: ${String(error)}`);
208
+ }
209
+ },
210
+ };
211
+ }
212
+
213
+ /** One event through a throwaway sink — for a caller with no sink to keep. */
214
+ export function recordEvent(
215
+ binding: EventsDataset | null | undefined,
216
+ request: Request | null | undefined,
217
+ fields: EventFields,
218
+ options: EventSinkOptions,
219
+ ): void {
220
+ createEventSink(binding, options).record(request, fields);
221
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * A server-side `view` for a public page: the schema's rule for prerendered and shell pages —
3
+ * record in the Worker's fetch path on an HTML navigation (GET, `Accept` includes `text/html`,
4
+ * status 200, not `/assets/*`, not `/api/*`, not `/healthz`, not a file), with the anonymous
5
+ * hashed actor or the session's, and the Referer HOST.
6
+ */
7
+ import type { EventActor, EventFields, EventSink } from "./sink.js";
8
+
9
+ export interface HtmlNavigation {
10
+ /** The route PATTERN recorded as the view's name — never the concrete path. */
11
+ route: string;
12
+ }
13
+
14
+ const NEVER_A_VIEW = /^\/(api\/|assets\/|healthz$|\.well-known\/|_)/;
15
+
16
+ /**
17
+ * The view this request is, or null when it is not an HTML navigation. `routeOf` maps the path to
18
+ * a pattern (`/` → `"/"`, `/docs/abc` → `"/docs/:id"`); the default keeps `/` and collapses every
19
+ * other path to its first segment (`/sign-in/anything` → `/sign-in`).
20
+ */
21
+ export function htmlNavigationOf(
22
+ request: Request,
23
+ status: number,
24
+ routeOf: (pathname: string) => string | null = firstSegment,
25
+ ): HtmlNavigation | null {
26
+ if (request.method !== "GET" || status !== 200) return null;
27
+ if (!(request.headers.get("accept") ?? "").includes("text/html")) return null;
28
+ const pathname = new URL(request.url).pathname;
29
+ if (NEVER_A_VIEW.test(pathname)) return null;
30
+ // A file (`/favicon.ico`, `/manifest.webmanifest`) is never a page.
31
+ if (pathname.slice(pathname.lastIndexOf("/") + 1).includes(".")) return null;
32
+ const route = routeOf(pathname);
33
+ return route ? { route } : null;
34
+ }
35
+
36
+ function firstSegment(pathname: string): string {
37
+ const first = pathname.split("/").filter(Boolean)[0];
38
+ return first ? `/${first}` : "/";
39
+ }
40
+
41
+ /** Record the view an HTML navigation is, when it is one. Returns whether it was. */
42
+ export function recordHtmlView(
43
+ events: EventSink,
44
+ request: Request,
45
+ status: number,
46
+ fields: { purpose: EventFields["purpose"]; actor?: EventActor | null; public?: boolean; tenant?: string },
47
+ routeOf?: (pathname: string) => string | null,
48
+ ): boolean {
49
+ const navigation = htmlNavigationOf(request, status, routeOf);
50
+ if (!navigation) return false;
51
+ events.record(request, {
52
+ kind: "view",
53
+ name: navigation.route,
54
+ place: navigation.route,
55
+ purpose: fields.purpose,
56
+ actor: fields.actor ?? null,
57
+ public: fields.public ?? true,
58
+ ...(fields.tenant ? { tenant: fields.tenant } : {}),
59
+ status,
60
+ });
61
+ return true;
62
+ }
@@ -98,6 +98,26 @@ describe('cursedbelt-server/telemetry', () => {
98
98
  });
99
99
  });
100
100
 
101
+ describe('🔴 cursedbelt-server/events — a Worker writes user events through it', () => {
102
+ test('reaches no `bun:` module at runtime — the sink, the point and the hash are all in the graph', () => {
103
+ const { files, bunImports } = runtimeGraph(join(import.meta.dir, 'events', 'index.ts'));
104
+ expect(bunImports).toEqual([]);
105
+ for (const file of ['events/sink.ts', 'events/point.ts', 'events/actor.ts', 'events/views.ts', 'events/actions.ts', 'events/gauge.ts', 'metrics/normalizeRoute.ts']) {
106
+ expect({ file, reached: files.some((f) => f.endsWith(file)) }).toEqual({ file, reached: true });
107
+ }
108
+ // The sink types its binding from the telemetry sink but never runs it: `metricsBuffer` stays out.
109
+ expect(files.some((f) => f.endsWith('metricsBuffer.ts'))).toBe(false);
110
+ });
111
+
112
+ test("its export map's `import` is the real module, not the Bun-only refusal", () => {
113
+ const pkg = JSON.parse(readFileSync(join(import.meta.dir, '..', '..', 'package.json'), 'utf8')) as {
114
+ exports: Record<string, { import?: string; source?: string }>;
115
+ };
116
+ expect(pkg.exports['./events']?.import).toBe('./dist/server/events/index.js');
117
+ expect(pkg.exports['./events']?.source).toBe('./src/server/events/index.ts');
118
+ });
119
+ });
120
+
101
121
  describe('🔴 cursedbelt-server/engagement/d1 — a Worker mounts it (task 2096)', () => {
102
122
  test('reaches no `bun:` module at runtime — not the store, not the Bun-only barrel', () => {
103
123
  const { files, bunImports } = runtimeGraph(join(import.meta.dir, 'engagement', 'd1.ts'));
@@ -105,6 +125,9 @@ describe('🔴 cursedbelt-server/engagement/d1 — a Worker mounts it (task 2096
105
125
  // Not vacuous: the policy and the manifest rule are both in the graph, and the store is not.
106
126
  expect(files.some((f) => f.endsWith('engagement/policy.ts'))).toBe(true);
107
127
  expect(files.some((f) => f.endsWith('engagement/manifestPlaces.ts'))).toBe(true);
128
+ // The user-event dual-write (4.60.0) rides along; it only TYPES the sink, so the sink stays out.
129
+ expect(files.some((f) => f.endsWith('engagement/events.ts'))).toBe(true);
130
+ expect(files.some((f) => f.endsWith('events/sink.ts'))).toBe(false);
108
131
  expect(files.some((f) => f.endsWith('engagement/store.ts'))).toBe(false);
109
132
  });
110
133
 
@@ -17,6 +17,7 @@ import {
17
17
  installOrUpdateYtDlp,
18
18
  parseYtInfo,
19
19
  parseYtProgress,
20
+ parseYtSample,
20
21
  type RunLines,
21
22
  YtDlpError,
22
23
  type YtDlpProfile,
@@ -52,6 +53,12 @@ describe("reading what yt-dlp prints", () => {
52
53
  expect(parseYtProgress("ytprogress 50 NA NA")).toBeNull();
53
54
  });
54
55
 
56
+ test("the line's speed and size come along, and NA is absent rather than a number", () => {
57
+ expect(parseYtSample("ytprogress 2551 10202 NA 1048576.5")).toEqual({ bytesPerSecond: 1048576.5, totalBytes: 10202 });
58
+ expect(parseYtSample("ytprogress 50 NA 200 NA")).toEqual({ totalBytes: 200 });
59
+ expect(parseYtSample("ytprogress 50 NA NA NA")).toEqual({});
60
+ });
61
+
55
62
  test("yt-dlp's own chatter is not progress", () => {
56
63
  expect(parseYtProgress("[download] 41.1% of 9.73MiB")).toBeNull();
57
64
  expect(parseYtInfo("[info] aqz: Downloading 1 format(s): 251")).toBeNull();
@@ -146,7 +153,7 @@ describe("the fetcher", () => {
146
153
  const out = args[args.indexOf("-o") + 1] as string;
147
154
  const file = out.replace("%(id)s.%(ext)s", "abc.webm");
148
155
  await writeFile(file, new Uint8Array([0x1a, 0x45, 0xdf, 0xa3, 1, 2, 3]));
149
- onLine("ytprogress 1 4 NA");
156
+ onLine("ytprogress 1 4 NA 512.5");
150
157
  onLine("[download] 100%");
151
158
  onLine(`ytinfo ${JSON.stringify({ id: "abc", title: "T", ext: "webm", filepath: file })}`);
152
159
  return { code: 0, stderr: "" };
@@ -171,11 +178,16 @@ describe("the fetcher", () => {
171
178
 
172
179
  test("a download hands back the file, the extension and the info, and reports progress", async () => {
173
180
  const fractions: number[] = [];
174
- const audio = await make(scripted("ok"))("abc", (f) => fractions.push(f));
181
+ const samples: unknown[] = [];
182
+ const audio = await make(scripted("ok"))("abc", (f, sample) => {
183
+ fractions.push(f);
184
+ samples.push(sample);
185
+ });
175
186
  expect(audio.extension).toBe("webm");
176
187
  expect(audio.info.title).toBe("T");
177
188
  expect(new Uint8Array(await readFile(audio.path)).slice(0, 4)).toEqual(new Uint8Array([0x1a, 0x45, 0xdf, 0xa3]));
178
189
  expect(fractions).toEqual([0.25]);
190
+ expect(samples).toEqual([{ bytesPerSecond: 512.5, totalBytes: 4 }]);
179
191
  expect(installs).toBe(0);
180
192
  // 🔴 The file is the caller's until it disposes — then it and its directory are gone.
181
193
  await audio.dispose();
@@ -136,14 +136,24 @@ interface YtDlpCallOptions {
136
136
 
137
137
  /**
138
138
  * Fetch one video. `target` is a YouTube video id, or a page URL (`https://…`) of any site yt-dlp
139
- * reads — Collections' pasted links (forge task 4003). `onProgress` gets the fraction received, 0–1.
139
+ * reads — Collections' pasted links (forge task 4003). `onProgress` gets the fraction received, 0–1,
140
+ * and what the same line said about the speed and the size.
140
141
  */
141
142
  export type YtDlpFetch = (
142
143
  target: string,
143
- onProgress?: (fraction: number) => void,
144
+ onProgress?: YtProgress,
144
145
  options?: YtDlpCallOptions,
145
146
  ) => Promise<YtDownload>;
146
147
 
148
+ /** How a download is going, beyond its fraction. A field yt-dlp does not know is absent. */
149
+ export interface YtProgressSample {
150
+ bytesPerSecond?: number;
151
+ /** The exact size, or yt-dlp's estimate of it when the stream has no `content-length`. */
152
+ totalBytes?: number;
153
+ }
154
+
155
+ export type YtProgress = (fraction: number, sample?: YtProgressSample) => void;
156
+
147
157
  /** Is `target` a page URL rather than a YouTube video id? */
148
158
  const isPageUrl = (target: string): boolean => /^https?:\/\//i.test(target);
149
159
 
@@ -190,8 +200,8 @@ export const isFinalYtDlpFailure = (kind: YtDlpFailure): boolean =>
190
200
  /**
191
201
  * One progress line, as a fraction — or `null` for any other line.
192
202
  *
193
- * The template prints `downloaded total estimate`, and yt-dlp writes `NA` for a field it does
194
- * not know. The exact total wins; the estimate is what a stream without a `content-length`
203
+ * The template prints `downloaded total estimate speed`, and yt-dlp writes `NA` for a field it
204
+ * does not know. The exact total wins; the estimate is what a stream without a `content-length`
195
205
  * has. With neither there is no honest fraction, so none is claimed.
196
206
  */
197
207
  export function parseYtProgress(line: string): number | null {
@@ -202,6 +212,14 @@ export function parseYtProgress(line: string): number | null {
202
212
  return Math.min(Math.max((downloaded as number) / (whole as number), 0), 1);
203
213
  }
204
214
 
215
+ /** The speed and size on a progress line {@link parseYtProgress} read. `NA` is an absent field. */
216
+ export function parseYtSample(line: string): YtProgressSample {
217
+ const [, total, estimate, speed] = line.slice(PROGRESS_MARK.length).trim().split(/\s+/).map(Number);
218
+ const known = (n: number | undefined): n is number => Number.isFinite(n) && (n as number) > 0;
219
+ const totalBytes = known(total) ? total : estimate;
220
+ return { ...(known(speed) ? { bytesPerSecond: speed } : {}), ...(known(totalBytes) ? { totalBytes } : {}) };
221
+ }
222
+
205
223
  /** The info JSON printed after the file is in place, or `null` for any other line. */
206
224
  export function parseYtInfo(line: string): YtInfo | null {
207
225
  if (!line.startsWith(INFO_MARK)) return null;
@@ -300,7 +318,7 @@ export function ytDlpArgs(
300
318
  // `--print` implies `--quiet`, which would swallow the progress lines — hence `--progress`.
301
319
  "--progress",
302
320
  "--progress-template",
303
- `download:${PROGRESS_MARK}%(progress.downloaded_bytes)s %(progress.total_bytes)s %(progress.total_bytes_estimate)s`,
321
+ `download:${PROGRESS_MARK}%(progress.downloaded_bytes)s %(progress.total_bytes)s %(progress.total_bytes_estimate)s %(progress.speed)s`,
304
322
  "--print",
305
323
  `after_move:${INFO_MARK}%()j`,
306
324
  "-o",
@@ -441,7 +459,7 @@ export function createYtDlp(options: YtDlpOptions): YtDlpFetch {
441
459
  };
442
460
 
443
461
  /** One yt-dlp run into a fresh directory. Throws a classified error on failure. */
444
- const attempt = async (target: string, onProgress?: (fraction: number) => void, call: YtDlpCallOptions = {}): Promise<YtDownload> => {
462
+ const attempt = async (target: string, onProgress?: YtProgress, call: YtDlpCallOptions = {}): Promise<YtDownload> => {
445
463
  const resumable = call.workDir !== undefined;
446
464
  const dir = call.workDir ?? (await mkdtemp(join(options.tmpRoot ?? tmpdir(), "ytdlp-")));
447
465
  if (resumable) await mkdir(dir, { recursive: true });
@@ -458,7 +476,7 @@ export function createYtDlp(options: YtDlpOptions): YtDlpFetch {
458
476
  }),
459
477
  (line) => {
460
478
  const fraction = parseYtProgress(line);
461
- if (fraction !== null) onProgress?.(fraction);
479
+ if (fraction !== null) onProgress?.(fraction, parseYtSample(line));
462
480
  info = parseYtInfo(line) ?? info;
463
481
  },
464
482
  );