cursedbelt-server 4.55.0 → 4.57.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.
@@ -50,8 +50,24 @@ export interface YtDownload {
50
50
  dir: string;
51
51
  dispose(): Promise<void>;
52
52
  }
53
- /** Fetch one video. `onProgress` gets the fraction of the file received, 0–1. */
54
- export type YtDlpFetch = (videoId: string, onProgress?: (fraction: number) => void) => Promise<YtDownload>;
53
+ /** What one call may add to the profile: a site that needs the owner's sign-in gets his cookies. */
54
+ interface YtDlpCallOptions {
55
+ /** A Netscape-format cookie jar yt-dlp reads (`--cookies`). The caller owns and removes it. */
56
+ cookiesFile?: string;
57
+ /**
58
+ * A RESUMABLE download: yt-dlp writes into this directory, which the CALLER owns — made if it is
59
+ * missing, kept with its `.part` files when the download fails, so the next call with the same
60
+ * directory continues where the bytes stopped instead of starting a 25 GB film again. The owner,
61
+ * 2026-10-29: *"if my internet was to go out … my downloads in process could be picked back up
62
+ * where they left off"* (forge task 4010). `dispose` still removes it once the file is had.
63
+ */
64
+ workDir?: string;
65
+ }
66
+ /**
67
+ * Fetch one video. `target` is a YouTube video id, or a page URL (`https://…`) of any site yt-dlp
68
+ * reads — Collections' pasted links (forge task 4003). `onProgress` gets the fraction received, 0–1.
69
+ */
70
+ export type YtDlpFetch = (target: string, onProgress?: (fraction: number) => void, options?: YtDlpCallOptions) => Promise<YtDownload>;
55
71
  /**
56
72
  * Why a download failed, sorted by what the owner can do about it.
57
73
  *
@@ -60,9 +76,11 @@ export type YtDlpFetch = (videoId: string, onProgress?: (fraction: number) => vo
60
76
  * · `blocked` — YouTube is refusing this Mac as a bot. Time fixes it, usually.
61
77
  * · `unavailable` — the video itself: private, deleted, region-locked, members-only.
62
78
  * · `too-big` — over the one-download ceiling.
79
+ * · `unsupported` — a pasted page URL yt-dlp has no reader for. Only a URL target gets it: for a
80
+ * YouTube id the same words mean YouTube moved, which `outdated` fixes.
63
81
  * · `failed` — anything else, with yt-dlp's own last error line.
64
82
  */
65
- export type YtDlpFailure = "missing" | "outdated" | "blocked" | "unavailable" | "too-big" | "failed";
83
+ export type YtDlpFailure = "missing" | "outdated" | "blocked" | "unavailable" | "too-big" | "unsupported" | "failed";
66
84
  export declare class YtDlpError extends Error {
67
85
  readonly kind: YtDlpFailure;
68
86
  constructor(message: string, kind: YtDlpFailure);
@@ -79,12 +97,14 @@ export declare const isFinalYtDlpFailure: (kind: YtDlpFailure) => boolean;
79
97
  export declare function parseYtProgress(line: string): number | null;
80
98
  /** The info JSON printed after the file is in place, or `null` for any other line. */
81
99
  export declare function parseYtInfo(line: string): YtInfo | null;
82
- /** Sort a failure by what can be done about it — see {@link YtDlpFailure}. */
83
- export declare function classifyYtDlpFailure(stderr: string): YtDlpFailure;
100
+ /** Sort a failure by what can be done about it — see {@link YtDlpFailure}. `target` is what was fetched. */
101
+ export declare function classifyYtDlpFailure(stderr: string, target?: string): YtDlpFailure;
84
102
  /** The arguments for one download. Exported so a test pins the flags that matter. */
85
- export declare function ytDlpArgs(videoId: string, outDir: string, profile: Pick<YtDlpProfile, "format" | "extraArgs" | "maxFilesize">, options?: {
103
+ export declare function ytDlpArgs(target: string, outDir: string, profile: Pick<YtDlpProfile, "format" | "extraArgs" | "maxFilesize">, options?: {
86
104
  cacheDir?: string;
87
105
  jsRuntime?: string;
106
+ cookiesFile?: string;
107
+ resumable?: boolean;
88
108
  }): string[];
89
109
  /** Run a program, handing each stdout line over as it arrives. Injected in tests. */
90
110
  export type RunLines = (binary: string, args: string[], onLine: (line: string) => void) => Promise<{
@@ -127,3 +147,4 @@ export interface YtDlpOptions {
127
147
  * and what it leaves as a sentence.
128
148
  */
129
149
  export declare function createYtDlp(options: YtDlpOptions): YtDlpFetch;
150
+ export {};
@@ -14,8 +14,13 @@
14
14
  * a track; Collections ingests a video), and any re-encode (only Collections has one, and only
15
15
  * when no H.264 stream exists).
16
16
  *
17
+ * A target is a YouTube video id or, since forge task 4003, any page URL yt-dlp reads — the
18
+ * links the owner pastes into Collections. A site that hides its videos behind a sign-in (eporner's
19
+ * age check) is handed the owner's own cookie jar per call; reading that jar is the app's business.
20
+ *
17
21
  * ── The file stays on disk ──────────────────────────────────────────────────────────────
18
- * A download resolves to a PATH inside a fresh temporary directory, and the caller disposes of
22
+ * A download resolves to a PATH inside a fresh temporary directory — or inside the caller's own
23
+ * `workDir`, which makes it resumable across failures (forge task 4010) — and the caller disposes of
19
24
  * it. A 1080p video is gigabytes, and reading it into memory to hand it over would make the
20
25
  * agent's footprint the size of the largest video in a playlist. Music, whose files are a few
21
26
  * MB, reads the bytes and disposes at once.
@@ -57,6 +62,19 @@ export function ytDlpPath(state) {
57
62
  export function ytDlpCacheDir(state) {
58
63
  return join(state, "cache", "yt-dlp");
59
64
  }
65
+ /** Is `target` a page URL rather than a YouTube video id? */
66
+ const isPageUrl = (target) => /^https?:\/\//i.test(target);
67
+ /** The site a target is on, as a sentence names it: `YouTube`, or the URL's host without `www.`. */
68
+ function siteOf(target) {
69
+ if (!isPageUrl(target))
70
+ return "YouTube";
71
+ try {
72
+ return new URL(target).hostname.replace(/^www\./i, "") || "that site";
73
+ }
74
+ catch {
75
+ return "that site";
76
+ }
77
+ }
60
78
  export class YtDlpError extends Error {
61
79
  kind;
62
80
  constructor(message, kind) {
@@ -66,7 +84,7 @@ export class YtDlpError extends Error {
66
84
  }
67
85
  }
68
86
  /** A failure no retry and no update can change — the video's own fault, or the ceiling. */
69
- export const isFinalYtDlpFailure = (kind) => kind === "unavailable" || kind === "too-big";
87
+ export const isFinalYtDlpFailure = (kind) => kind === "unavailable" || kind === "too-big" || kind === "unsupported";
70
88
  // ── Pure: reading what yt-dlp prints ───────────────────────────────────────────────────
71
89
  /**
72
90
  * One progress line, as a fraction — or `null` for any other line.
@@ -109,11 +127,14 @@ const UNAVAILABLE = /video unavailable|this video is unavailable|private video|h
109
127
  const BLOCKED = /confirm you.?re not a bot|sign in to confirm|too many requests|http error 429/i;
110
128
  const OUTDATED = /unable to extract|nsig|n challenge|signature (extraction|function)|precondition check failed|http error 403|requested format is not available|please report this issue|js challenge|player .*(response|js)|unsupported url|jsc/i;
111
129
  const TOO_BIG = /larger than max-filesize|max-filesize/i;
112
- /** Sort a failure by what can be done about it — see {@link YtDlpFailure}. */
113
- export function classifyYtDlpFailure(stderr) {
130
+ const UNSUPPORTED = /unsupported url/i;
131
+ /** Sort a failure by what can be done about it — see {@link YtDlpFailure}. `target` is what was fetched. */
132
+ export function classifyYtDlpFailure(stderr, target = "") {
114
133
  const line = lastYtDlpError(stderr);
115
134
  if (TOO_BIG.test(line))
116
135
  return "too-big";
136
+ if (isPageUrl(target) && UNSUPPORTED.test(line))
137
+ return "unsupported";
117
138
  if (UNAVAILABLE.test(line))
118
139
  return "unavailable";
119
140
  if (BLOCKED.test(line))
@@ -125,36 +146,42 @@ export function classifyYtDlpFailure(stderr) {
125
146
  /** The sentence a downloads table shows. Every kind that has a remedy NAMES it. */
126
147
  function describeYtDlpFailure(kind, detail, context) {
127
148
  const fix = context.fixCommand;
149
+ const site = context.site;
128
150
  switch (kind) {
129
151
  case "missing":
130
152
  return `yt-dlp is not installed on the Mac and installing it failed (${detail}). Run: ${fix}`;
131
153
  case "outdated":
132
- return (`yt-dlp could not read YouTube — it is out of date for a change YouTube made (${detail}). ` +
154
+ return (`yt-dlp could not read ${site} — it is out of date for a change ${site} made (${detail}). ` +
133
155
  (context.updated
134
156
  ? `The agent already updated it and it still fails, so the fix is not released yet; try again in a day, or run: ${fix}`
135
157
  : `Run: ${fix}`));
136
158
  case "blocked":
137
- return `YouTube is refusing this Mac's requests as a bot (${detail}). It usually lifts within hours — try again later. If it persists, update yt-dlp: ${fix}`;
159
+ return `${site} is refusing this Mac's requests as a bot (${detail}). It usually lifts within hours — try again later. If it persists, update yt-dlp: ${fix}`;
138
160
  case "unavailable":
139
- return `YouTube will not play this video to anyone signed out (${detail}), so there is nothing to download.`;
161
+ return `${site} will not play this video to anyone signed out (${detail}), so there is nothing to download.`;
162
+ case "unsupported":
163
+ return `yt-dlp has no reader for ${site} pages (${detail}), so that link cannot be downloaded.`;
140
164
  case "too-big":
141
165
  return `${context.profile.noun} is over this app's ${context.profile.maxFilesize}B ceiling for one download.`;
142
166
  default:
143
- return `yt-dlp failed: ${detail || "no reason given"}. If YouTube links keep failing, update it: ${fix}`;
167
+ return `yt-dlp failed: ${detail || "no reason given"}. If ${site} links keep failing, update it: ${fix}`;
144
168
  }
145
169
  }
146
170
  /** The arguments for one download. Exported so a test pins the flags that matter. */
147
- export function ytDlpArgs(videoId, outDir, profile, options = {}) {
171
+ export function ytDlpArgs(target, outDir, profile, options = {}) {
148
172
  return [
149
173
  ...(options.jsRuntime ? ["--js-runtimes", `bun:${options.jsRuntime}`] : []),
150
174
  ...(options.cacheDir ? ["--cache-dir", options.cacheDir] : []),
175
+ ...(options.cookiesFile ? ["--cookies", options.cookiesFile] : []),
151
176
  "--no-playlist",
152
177
  "-f",
153
178
  profile.format,
154
179
  ...(profile.extraArgs ?? []),
155
180
  "--max-filesize",
156
181
  profile.maxFilesize,
157
- "--no-part",
182
+ // Resumable: keep the `.part` and continue it. Otherwise no `.part` at all — a fresh directory
183
+ // per run has nothing to continue, and a half file there is only litter.
184
+ ...(options.resumable ? ["--continue"] : ["--no-part"]),
158
185
  "--no-mtime",
159
186
  "--no-colors",
160
187
  "--newline",
@@ -165,9 +192,11 @@ export function ytDlpArgs(videoId, outDir, profile, options = {}) {
165
192
  "--print",
166
193
  `after_move:${INFO_MARK}%()j`,
167
194
  "-o",
168
- join(outDir, "%(id)s.%(ext)s"),
195
+ // Resumable runs name the file for the directory, not the site's id: a signed URL resolved
196
+ // afresh on the next try can carry a different id, and a different name is a fresh download.
197
+ join(outDir, options.resumable ? "download.%(ext)s" : "%(id)s.%(ext)s"),
169
198
  "--",
170
- `https://www.youtube.com/watch?v=${videoId}`,
199
+ isPageUrl(target) ? target : `https://www.youtube.com/watch?v=${target}`,
171
200
  ];
172
201
  }
173
202
  const runLines = (binary, args, onLine) => new Promise((resolve, reject) => {
@@ -254,7 +283,7 @@ export function createYtDlp(options) {
254
283
  const label = options.label ?? "[yt-dlp]";
255
284
  const jsRuntime = options.jsRuntime ?? (process.versions.bun ? process.execPath : undefined);
256
285
  let lastUpdate = Number.NEGATIVE_INFINITY;
257
- const describe = (kind, detail, updated) => describeYtDlpFailure(kind, detail, { updated, fixCommand: options.fixCommand, profile: options.profile });
286
+ const describe = (kind, detail, updated, target) => describeYtDlpFailure(kind, detail, { updated, fixCommand: options.fixCommand, profile: options.profile, site: siteOf(target) });
258
287
  const ensureInstalled = async () => {
259
288
  if (await isFile(options.binary))
260
289
  return;
@@ -264,18 +293,23 @@ export function createYtDlp(options) {
264
293
  }
265
294
  catch (error) {
266
295
  const detail = error instanceof Error ? error.message : String(error);
267
- throw new YtDlpError(describe("missing", detail, false), "missing");
296
+ throw new YtDlpError(describe("missing", detail, false, ""), "missing");
268
297
  }
269
298
  };
270
299
  /** One yt-dlp run into a fresh directory. Throws a classified error on failure. */
271
- const attempt = async (videoId, onProgress) => {
272
- const dir = await mkdtemp(join(options.tmpRoot ?? tmpdir(), "ytdlp-"));
300
+ const attempt = async (target, onProgress, call = {}) => {
301
+ const resumable = call.workDir !== undefined;
302
+ const dir = call.workDir ?? (await mkdtemp(join(options.tmpRoot ?? tmpdir(), "ytdlp-")));
303
+ if (resumable)
304
+ await mkdir(dir, { recursive: true });
273
305
  const dispose = () => rm(dir, { recursive: true, force: true });
274
306
  try {
275
307
  let info = null;
276
- const { code, stderr } = await run(options.binary, ytDlpArgs(videoId, dir, options.profile, {
308
+ const { code, stderr } = await run(options.binary, ytDlpArgs(target, dir, options.profile, {
277
309
  ...(options.cacheDir ? { cacheDir: options.cacheDir } : {}),
278
310
  ...(jsRuntime ? { jsRuntime } : {}),
311
+ ...(call.cookiesFile ? { cookiesFile: call.cookiesFile } : {}),
312
+ ...(resumable ? { resumable } : {}),
279
313
  }), (line) => {
280
314
  const fraction = parseYtProgress(line);
281
315
  if (fraction !== null)
@@ -284,7 +318,7 @@ export function createYtDlp(options) {
284
318
  });
285
319
  const found = info;
286
320
  if (code !== 0 || !found?.filepath) {
287
- const kind = code === 0 ? "failed" : classifyYtDlpFailure(stderr);
321
+ const kind = code === 0 ? "failed" : classifyYtDlpFailure(stderr, target);
288
322
  throw new YtDlpError(code === 0 ? "yt-dlp finished without saying where the file went" : lastYtDlpError(stderr), kind);
289
323
  }
290
324
  if (!(await isFile(found.filepath)))
@@ -293,17 +327,19 @@ export function createYtDlp(options) {
293
327
  return { path: found.filepath, extension, info: found, dir, dispose };
294
328
  }
295
329
  catch (error) {
296
- await dispose();
330
+ // 🔴 A resumable directory is the caller's, and its `.part` is the whole point: keep it.
331
+ if (!resumable)
332
+ await dispose();
297
333
  throw error;
298
334
  }
299
335
  };
300
- return async (videoId, onProgress) => {
336
+ return async (target, onProgress, call) => {
301
337
  await ensureInstalled();
302
338
  let updated = false;
303
339
  let last = null;
304
340
  for (let tries = 1; tries <= ATTEMPTS + 1; tries++) {
305
341
  try {
306
- return await attempt(videoId, onProgress);
342
+ return await attempt(target, onProgress, call);
307
343
  }
308
344
  catch (error) {
309
345
  last =
@@ -329,6 +365,6 @@ export function createYtDlp(options) {
329
365
  }
330
366
  }
331
367
  const failure = last ?? new YtDlpError("no attempt ran", "failed");
332
- throw new YtDlpError(describe(failure.kind, failure.message, updated), failure.kind);
368
+ throw new YtDlpError(describe(failure.kind, failure.message, updated, target), failure.kind);
333
369
  };
334
370
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.55.0",
3
+ "version": "4.57.0",
4
4
  "license": "ISC",
5
5
  "type": "module",
6
6
  "description": "The app-facing Bun/Hono server tier of the cursedbelt split — storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",
@@ -417,7 +417,7 @@
417
417
  "@node-rs/argon2": "^2.0.2",
418
418
  "@types/bun": "^1.3.14",
419
419
  "@types/node": "^24",
420
- "cursedbelt": "^5.9.0",
420
+ "cursedbelt": "^5.99.6",
421
421
  "hono": "4.12.28",
422
422
  "kysely": "^0.28.17",
423
423
  "kysely-bun-sqlite": "^0.4.0",
@@ -516,11 +516,8 @@ END;`;
516
516
  const dir = scratch();
517
517
  const child = join(dir, 'big.js');
518
518
  writeFileSync(child, "process.stdout.write('[' + JSON.stringify('x'.repeat(2_000_000)) + ']'); process.exit(0);");
519
- const proc = Bun.spawn([process.execPath, child], { stdout: 'pipe' });
520
- const piped = (await new Response(proc.stdout).text()).length;
521
- await proc.exited;
522
- // The failure this exists for: if Bun ever stops cutting the pipe, this line says so.
523
- expect(piped).toBeLessThan(2_000_004);
519
+ // Bun ≤1.3 cut this pipe at a 64 KiB boundary; 1.4.3 delivers it whole (measured 2026-10-29),
520
+ // so the pipe's loss is no longer asserted — only that spawnToFile keeps every byte on any Bun.
524
521
  const r = spawnToFile([process.execPath, child]);
525
522
  expect(r.code).toBe(0);
526
523
  expect(r.stdout.length).toBe(2_000_004);
@@ -78,6 +78,14 @@ describe("reading what yt-dlp prints", () => {
78
78
  expect(ytDlpArgs("abc", "/out", AUDIO)).not.toContain("--merge-output-format");
79
79
  });
80
80
 
81
+ test("🔴 a pasted page URL is fetched as given, and a cookie jar rides along only when handed one", () => {
82
+ const page = "https://www.eporner.com/video-6t3XeYYVBvy/some-title/";
83
+ const args = ytDlpArgs(page, "/out", VIDEO, { cookiesFile: "/jar.txt" });
84
+ expect(args.at(-1)).toBe(page);
85
+ expect(args[args.indexOf("--cookies") + 1]).toBe("/jar.txt");
86
+ expect(ytDlpArgs("abc", "/out", VIDEO)).not.toContain("--cookies");
87
+ });
88
+
81
89
  test("the binary is one per generation, under its state root", () => {
82
90
  expect(ytDlpPath("/state")).toBe("/state/bin/yt-dlp");
83
91
  });
@@ -99,6 +107,16 @@ describe("sorting a failure by what fixes it", () => {
99
107
  });
100
108
  });
101
109
 
110
+ describe("a pasted link yt-dlp cannot read", () => {
111
+ const line = "ERROR: Unsupported URL: https://example.com/watch/1\n";
112
+ test("🔴 is final for a page URL — no retry or update gives yt-dlp a reader it lacks", () => {
113
+ expect(classifyYtDlpFailure(line, "https://example.com/watch/1")).toBe("unsupported");
114
+ });
115
+ test("but for a YouTube id it still reads as YouTube having moved", () => {
116
+ expect(classifyYtDlpFailure(line, "abc")).toBe("outdated");
117
+ });
118
+ });
119
+
102
120
  describe("the fetcher", () => {
103
121
  let dir: string;
104
122
  let binary: string;
@@ -169,6 +187,19 @@ describe("the fetcher", () => {
169
187
  expect((await readdir(dir)).filter((name) => name.startsWith("ytdlp-"))).toEqual([]);
170
188
  });
171
189
 
190
+ test("🔴 a resumable download keeps its directory and its partial bytes through a failure, and continues there", async () => {
191
+ const work = join(dir, "job-1");
192
+ await make(scripted("Connection reset by peer"))("abc", undefined, { workDir: work }).catch(() => undefined);
193
+ // The partial is where the next call looks — never deleted on a failure.
194
+ expect((await stat(work)).isDirectory()).toBe(true);
195
+ const args = runs.at(-1) as string[];
196
+ expect(args).toContain("--continue");
197
+ expect(args).not.toContain("--no-part");
198
+ expect(args[args.indexOf("-o") + 1]).toBe(join(work, "download.%(ext)s"));
199
+ // A non-resumable call is unchanged: no partial, a fresh directory, gone on failure.
200
+ expect(ytDlpArgs("abc", "/out", VIDEO)).toContain("--no-part");
201
+ });
202
+
172
203
  test("the ceiling sentence uses the profile's own noun and size", async () => {
173
204
  const failure = await make(scripted("File is larger than max-filesize (9 > 8). Aborting."), VIDEO)("abc").then(
174
205
  () => {
@@ -213,6 +244,21 @@ describe("the fetcher", () => {
213
244
  expect(second.message).toMatch(/Run: cd /);
214
245
  });
215
246
 
247
+ test("🔴 a URL target's cookie jar reaches yt-dlp, and its failure sentence names that site", async () => {
248
+ const page = "https://www.eporner.com/video-abc/t/";
249
+ const failure = await make(scripted("Unsupported URL: x"))(page, undefined, { cookiesFile: "/jar.txt" }).then(
250
+ () => {
251
+ throw new Error("expected a failure");
252
+ },
253
+ (e: unknown) => e as YtDlpError,
254
+ );
255
+ expect(runs[0]?.at(-1)).toBe(page);
256
+ expect(runs[0]).toContain("/jar.txt");
257
+ expect(failure.kind).toBe("unsupported");
258
+ expect(failure.message).toContain("eporner.com");
259
+ expect(runs).toHaveLength(1);
260
+ });
261
+
216
262
  test("a private video is not retried and not a reason to update", async () => {
217
263
  const failure = await make(scripted("[youtube] abc: Private video"))("abc").then(() => { throw new Error("expected a failure"); }, (e: unknown) => e as YtDlpError);
218
264
  expect(failure.kind).toBe("unavailable");
@@ -14,8 +14,13 @@
14
14
  * a track; Collections ingests a video), and any re-encode (only Collections has one, and only
15
15
  * when no H.264 stream exists).
16
16
  *
17
+ * A target is a YouTube video id or, since forge task 4003, any page URL yt-dlp reads — the
18
+ * links the owner pastes into Collections. A site that hides its videos behind a sign-in (eporner's
19
+ * age check) is handed the owner's own cookie jar per call; reading that jar is the app's business.
20
+ *
17
21
  * ── The file stays on disk ──────────────────────────────────────────────────────────────
18
- * A download resolves to a PATH inside a fresh temporary directory, and the caller disposes of
22
+ * A download resolves to a PATH inside a fresh temporary directory — or inside the caller's own
23
+ * `workDir`, which makes it resumable across failures (forge task 4010) — and the caller disposes of
19
24
  * it. A 1080p video is gigabytes, and reading it into memory to hand it over would make the
20
25
  * agent's footprint the size of the largest video in a playlist. Music, whose files are a few
21
26
  * MB, reads the bytes and disposes at once.
@@ -115,8 +120,42 @@ export interface YtDownload {
115
120
  dispose(): Promise<void>;
116
121
  }
117
122
 
118
- /** Fetch one video. `onProgress` gets the fraction of the file received, 0–1. */
119
- export type YtDlpFetch = (videoId: string, onProgress?: (fraction: number) => void) => Promise<YtDownload>;
123
+ /** What one call may add to the profile: a site that needs the owner's sign-in gets his cookies. */
124
+ interface YtDlpCallOptions {
125
+ /** A Netscape-format cookie jar yt-dlp reads (`--cookies`). The caller owns and removes it. */
126
+ cookiesFile?: string;
127
+ /**
128
+ * A RESUMABLE download: yt-dlp writes into this directory, which the CALLER owns — made if it is
129
+ * missing, kept with its `.part` files when the download fails, so the next call with the same
130
+ * directory continues where the bytes stopped instead of starting a 25 GB film again. The owner,
131
+ * 2026-10-29: *"if my internet was to go out … my downloads in process could be picked back up
132
+ * where they left off"* (forge task 4010). `dispose` still removes it once the file is had.
133
+ */
134
+ workDir?: string;
135
+ }
136
+
137
+ /**
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.
140
+ */
141
+ export type YtDlpFetch = (
142
+ target: string,
143
+ onProgress?: (fraction: number) => void,
144
+ options?: YtDlpCallOptions,
145
+ ) => Promise<YtDownload>;
146
+
147
+ /** Is `target` a page URL rather than a YouTube video id? */
148
+ const isPageUrl = (target: string): boolean => /^https?:\/\//i.test(target);
149
+
150
+ /** The site a target is on, as a sentence names it: `YouTube`, or the URL's host without `www.`. */
151
+ function siteOf(target: string): string {
152
+ if (!isPageUrl(target)) return "YouTube";
153
+ try {
154
+ return new URL(target).hostname.replace(/^www\./i, "") || "that site";
155
+ } catch {
156
+ return "that site";
157
+ }
158
+ }
120
159
 
121
160
  /**
122
161
  * Why a download failed, sorted by what the owner can do about it.
@@ -126,9 +165,11 @@ export type YtDlpFetch = (videoId: string, onProgress?: (fraction: number) => vo
126
165
  * · `blocked` — YouTube is refusing this Mac as a bot. Time fixes it, usually.
127
166
  * · `unavailable` — the video itself: private, deleted, region-locked, members-only.
128
167
  * · `too-big` — over the one-download ceiling.
168
+ * · `unsupported` — a pasted page URL yt-dlp has no reader for. Only a URL target gets it: for a
169
+ * YouTube id the same words mean YouTube moved, which `outdated` fixes.
129
170
  * · `failed` — anything else, with yt-dlp's own last error line.
130
171
  */
131
- export type YtDlpFailure = "missing" | "outdated" | "blocked" | "unavailable" | "too-big" | "failed";
172
+ export type YtDlpFailure = "missing" | "outdated" | "blocked" | "unavailable" | "too-big" | "unsupported" | "failed";
132
173
 
133
174
  export class YtDlpError extends Error {
134
175
  constructor(
@@ -141,7 +182,8 @@ export class YtDlpError extends Error {
141
182
  }
142
183
 
143
184
  /** A failure no retry and no update can change — the video's own fault, or the ceiling. */
144
- export const isFinalYtDlpFailure = (kind: YtDlpFailure): boolean => kind === "unavailable" || kind === "too-big";
185
+ export const isFinalYtDlpFailure = (kind: YtDlpFailure): boolean =>
186
+ kind === "unavailable" || kind === "too-big" || kind === "unsupported";
145
187
 
146
188
  // ── Pure: reading what yt-dlp prints ───────────────────────────────────────────────────
147
189
 
@@ -188,10 +230,13 @@ const OUTDATED =
188
230
  /unable to extract|nsig|n challenge|signature (extraction|function)|precondition check failed|http error 403|requested format is not available|please report this issue|js challenge|player .*(response|js)|unsupported url|jsc/i;
189
231
  const TOO_BIG = /larger than max-filesize|max-filesize/i;
190
232
 
191
- /** Sort a failure by what can be done about it — see {@link YtDlpFailure}. */
192
- export function classifyYtDlpFailure(stderr: string): YtDlpFailure {
233
+ const UNSUPPORTED = /unsupported url/i;
234
+
235
+ /** Sort a failure by what can be done about it — see {@link YtDlpFailure}. `target` is what was fetched. */
236
+ export function classifyYtDlpFailure(stderr: string, target = ""): YtDlpFailure {
193
237
  const line = lastYtDlpError(stderr);
194
238
  if (TOO_BIG.test(line)) return "too-big";
239
+ if (isPageUrl(target) && UNSUPPORTED.test(line)) return "unsupported";
195
240
  if (UNAVAILABLE.test(line)) return "unavailable";
196
241
  if (BLOCKED.test(line)) return "blocked";
197
242
  if (OUTDATED.test(line)) return "outdated";
@@ -202,47 +247,53 @@ export function classifyYtDlpFailure(stderr: string): YtDlpFailure {
202
247
  function describeYtDlpFailure(
203
248
  kind: YtDlpFailure,
204
249
  detail: string,
205
- context: { updated: boolean; fixCommand: string; profile: Pick<YtDlpProfile, "maxFilesize" | "noun"> },
250
+ context: { updated: boolean; fixCommand: string; profile: Pick<YtDlpProfile, "maxFilesize" | "noun">; site: string },
206
251
  ): string {
207
252
  const fix = context.fixCommand;
253
+ const site = context.site;
208
254
  switch (kind) {
209
255
  case "missing":
210
256
  return `yt-dlp is not installed on the Mac and installing it failed (${detail}). Run: ${fix}`;
211
257
  case "outdated":
212
258
  return (
213
- `yt-dlp could not read YouTube — it is out of date for a change YouTube made (${detail}). ` +
259
+ `yt-dlp could not read ${site} — it is out of date for a change ${site} made (${detail}). ` +
214
260
  (context.updated
215
261
  ? `The agent already updated it and it still fails, so the fix is not released yet; try again in a day, or run: ${fix}`
216
262
  : `Run: ${fix}`)
217
263
  );
218
264
  case "blocked":
219
- return `YouTube is refusing this Mac's requests as a bot (${detail}). It usually lifts within hours — try again later. If it persists, update yt-dlp: ${fix}`;
265
+ return `${site} is refusing this Mac's requests as a bot (${detail}). It usually lifts within hours — try again later. If it persists, update yt-dlp: ${fix}`;
220
266
  case "unavailable":
221
- return `YouTube will not play this video to anyone signed out (${detail}), so there is nothing to download.`;
267
+ return `${site} will not play this video to anyone signed out (${detail}), so there is nothing to download.`;
268
+ case "unsupported":
269
+ return `yt-dlp has no reader for ${site} pages (${detail}), so that link cannot be downloaded.`;
222
270
  case "too-big":
223
271
  return `${context.profile.noun} is over this app's ${context.profile.maxFilesize}B ceiling for one download.`;
224
272
  default:
225
- return `yt-dlp failed: ${detail || "no reason given"}. If YouTube links keep failing, update it: ${fix}`;
273
+ return `yt-dlp failed: ${detail || "no reason given"}. If ${site} links keep failing, update it: ${fix}`;
226
274
  }
227
275
  }
228
276
 
229
277
  /** The arguments for one download. Exported so a test pins the flags that matter. */
230
278
  export function ytDlpArgs(
231
- videoId: string,
279
+ target: string,
232
280
  outDir: string,
233
281
  profile: Pick<YtDlpProfile, "format" | "extraArgs" | "maxFilesize">,
234
- options: { cacheDir?: string; jsRuntime?: string } = {},
282
+ options: { cacheDir?: string; jsRuntime?: string; cookiesFile?: string; resumable?: boolean } = {},
235
283
  ): string[] {
236
284
  return [
237
285
  ...(options.jsRuntime ? ["--js-runtimes", `bun:${options.jsRuntime}`] : []),
238
286
  ...(options.cacheDir ? ["--cache-dir", options.cacheDir] : []),
287
+ ...(options.cookiesFile ? ["--cookies", options.cookiesFile] : []),
239
288
  "--no-playlist",
240
289
  "-f",
241
290
  profile.format,
242
291
  ...(profile.extraArgs ?? []),
243
292
  "--max-filesize",
244
293
  profile.maxFilesize,
245
- "--no-part",
294
+ // Resumable: keep the `.part` and continue it. Otherwise no `.part` at all — a fresh directory
295
+ // per run has nothing to continue, and a half file there is only litter.
296
+ ...(options.resumable ? ["--continue"] : ["--no-part"]),
246
297
  "--no-mtime",
247
298
  "--no-colors",
248
299
  "--newline",
@@ -253,9 +304,11 @@ export function ytDlpArgs(
253
304
  "--print",
254
305
  `after_move:${INFO_MARK}%()j`,
255
306
  "-o",
256
- join(outDir, "%(id)s.%(ext)s"),
307
+ // Resumable runs name the file for the directory, not the site's id: a signed URL resolved
308
+ // afresh on the next try can carry a different id, and a different name is a fresh download.
309
+ join(outDir, options.resumable ? "download.%(ext)s" : "%(id)s.%(ext)s"),
257
310
  "--",
258
- `https://www.youtube.com/watch?v=${videoId}`,
311
+ isPageUrl(target) ? target : `https://www.youtube.com/watch?v=${target}`,
259
312
  ];
260
313
  }
261
314
 
@@ -373,8 +426,8 @@ export function createYtDlp(options: YtDlpOptions): YtDlpFetch {
373
426
  const label = options.label ?? "[yt-dlp]";
374
427
  const jsRuntime = options.jsRuntime ?? (process.versions.bun ? process.execPath : undefined);
375
428
  let lastUpdate = Number.NEGATIVE_INFINITY;
376
- const describe = (kind: YtDlpFailure, detail: string, updated: boolean): string =>
377
- describeYtDlpFailure(kind, detail, { updated, fixCommand: options.fixCommand, profile: options.profile });
429
+ const describe = (kind: YtDlpFailure, detail: string, updated: boolean, target: string): string =>
430
+ describeYtDlpFailure(kind, detail, { updated, fixCommand: options.fixCommand, profile: options.profile, site: siteOf(target) });
378
431
 
379
432
  const ensureInstalled = async (): Promise<void> => {
380
433
  if (await isFile(options.binary)) return;
@@ -383,21 +436,25 @@ export function createYtDlp(options: YtDlpOptions): YtDlpFetch {
383
436
  await install(options.binary);
384
437
  } catch (error) {
385
438
  const detail = error instanceof Error ? error.message : String(error);
386
- throw new YtDlpError(describe("missing", detail, false), "missing");
439
+ throw new YtDlpError(describe("missing", detail, false, ""), "missing");
387
440
  }
388
441
  };
389
442
 
390
443
  /** One yt-dlp run into a fresh directory. Throws a classified error on failure. */
391
- const attempt = async (videoId: string, onProgress?: (fraction: number) => void): Promise<YtDownload> => {
392
- const dir = await mkdtemp(join(options.tmpRoot ?? tmpdir(), "ytdlp-"));
444
+ const attempt = async (target: string, onProgress?: (fraction: number) => void, call: YtDlpCallOptions = {}): Promise<YtDownload> => {
445
+ const resumable = call.workDir !== undefined;
446
+ const dir = call.workDir ?? (await mkdtemp(join(options.tmpRoot ?? tmpdir(), "ytdlp-")));
447
+ if (resumable) await mkdir(dir, { recursive: true });
393
448
  const dispose = () => rm(dir, { recursive: true, force: true });
394
449
  try {
395
450
  let info: YtInfo | null = null;
396
451
  const { code, stderr } = await run(
397
452
  options.binary,
398
- ytDlpArgs(videoId, dir, options.profile, {
453
+ ytDlpArgs(target, dir, options.profile, {
399
454
  ...(options.cacheDir ? { cacheDir: options.cacheDir } : {}),
400
455
  ...(jsRuntime ? { jsRuntime } : {}),
456
+ ...(call.cookiesFile ? { cookiesFile: call.cookiesFile } : {}),
457
+ ...(resumable ? { resumable } : {}),
401
458
  }),
402
459
  (line) => {
403
460
  const fraction = parseYtProgress(line);
@@ -407,25 +464,26 @@ export function createYtDlp(options: YtDlpOptions): YtDlpFetch {
407
464
  );
408
465
  const found = info as YtInfo | null;
409
466
  if (code !== 0 || !found?.filepath) {
410
- const kind = code === 0 ? "failed" : classifyYtDlpFailure(stderr);
467
+ const kind = code === 0 ? "failed" : classifyYtDlpFailure(stderr, target);
411
468
  throw new YtDlpError(code === 0 ? "yt-dlp finished without saying where the file went" : lastYtDlpError(stderr), kind);
412
469
  }
413
470
  if (!(await isFile(found.filepath))) throw new YtDlpError(`yt-dlp named ${found.filepath} and it is not there`, "failed");
414
471
  const extension = (found.ext || found.filepath.split(".").at(-1) || "bin").toLowerCase();
415
472
  return { path: found.filepath, extension, info: found, dir, dispose };
416
473
  } catch (error) {
417
- await dispose();
474
+ // 🔴 A resumable directory is the caller's, and its `.part` is the whole point: keep it.
475
+ if (!resumable) await dispose();
418
476
  throw error;
419
477
  }
420
478
  };
421
479
 
422
- return async (videoId, onProgress) => {
480
+ return async (target, onProgress, call) => {
423
481
  await ensureInstalled();
424
482
  let updated = false;
425
483
  let last: YtDlpError | null = null;
426
484
  for (let tries = 1; tries <= ATTEMPTS + 1; tries++) {
427
485
  try {
428
- return await attempt(videoId, onProgress);
486
+ return await attempt(target, onProgress, call);
429
487
  } catch (error) {
430
488
  last =
431
489
  error instanceof YtDlpError ? error : new YtDlpError(error instanceof Error ? error.message : String(error), "failed");
@@ -449,6 +507,6 @@ export function createYtDlp(options: YtDlpOptions): YtDlpFetch {
449
507
  }
450
508
  }
451
509
  const failure = last ?? new YtDlpError("no attempt ran", "failed");
452
- throw new YtDlpError(describe(failure.kind, failure.message, updated), failure.kind);
510
+ throw new YtDlpError(describe(failure.kind, failure.message, updated, target), failure.kind);
453
511
  };
454
512
  }