@boy-offi9-inc/tidepull 0.1.0-rc.1 → 0.2.0-rc.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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Tidepull contributors
3
+ Copyright (c) 2026 Boy Offi9 Inc
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -35,6 +35,8 @@ setTimeout(() => ctl.abort(), 5000);
35
35
  await g.pull(url, { signal: ctl.signal }); // rejects with name === "AbortError"
36
36
  ```
37
37
 
38
+ Cap the speed with `limitRate` (bytes per second, applied to each file): `g.download(info, { limitRate: 1_000_000 })`.
39
+
38
40
  ## API (everything else is internal)
39
41
  | Export | Purpose |
40
42
  |---|---|
@@ -72,7 +74,14 @@ tidepull -F URL # list formats
72
74
  tidepull -f "bv*[height<=720]+ba/b" URL # select + merge (needs ffmpeg)
73
75
  tidepull -o "%(title).60s [%(id)s].%(ext)s" -P ~/Videos URL
74
76
  tidepull -j URL | jq .formats # data on stdout, logs on stderr
77
+ tidepull -a urls.txt --download-archive done.txt # batch input; skip what you already downloaded
78
+ tidepull --limit-rate 1M URL # cap the speed (500K, 1.5M, ...)
75
79
  ```
80
+
81
+ **Batch and archive.** `-a FILE` reads one URL per line (`#` starts a comment, `-` reads stdin). `--download-archive FILE` records each finished item and skips it on later runs.
82
+
83
+ **Config file.** Defaults go in `~/.config/tidepull/config` (or `--config-location FILE`): one or more options per line, `#` for comments, for example `-P ~/Videos` and `--limit-rate 2M`. Options on the command line win; `--no-config` ignores the file.
84
+
76
85
  From a clone, `node src/cli.ts <args>` runs the TypeScript source directly (Node >= 22.18); `npm run build` emits JS + `.d.ts`.
77
86
 
78
87
  ## What works today
@@ -0,0 +1,22 @@
1
+ import type { Info } from "./core/types.js";
2
+ /** "500K", "1.5M", "2G" or plain bytes per second. */
3
+ export declare function parseRate(s: string): number;
4
+ /** Splits a config line into arguments. Supports 'single' and "double" quotes and \" inside double quotes. */
5
+ export declare function splitArgs(line: string): string[];
6
+ /** One URL per line; blank lines and lines starting with # are ignored. "-" reads stdin. */
7
+ export declare function readUrlList(file: string): string[];
8
+ export declare function defaultConfigPath(env?: NodeJS.ProcessEnv): string;
9
+ /**
10
+ * Arguments from the config file: one or more options per line, # starts a comment.
11
+ * Placed before the command line so the command line wins. Returns [] when disabled or absent.
12
+ */
13
+ export declare function configArgs(argv: string[], env?: NodeJS.ProcessEnv): string[];
14
+ /** Remembers finished downloads so later runs skip them. One key per line. */
15
+ export declare class Archive {
16
+ private file;
17
+ private keys;
18
+ constructor(file: string);
19
+ static key(info: Info): string;
20
+ has(info: Info): boolean;
21
+ add(info: Info): void;
22
+ }
@@ -0,0 +1,115 @@
1
+ /** CLI-only helpers: config file, batch input, download archive, rate parsing. Not part of the library entry point. */
2
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { TidepullError, errMsg } from "./core/errors.js";
6
+ /** "500K", "1.5M", "2G" or plain bytes per second. */
7
+ export function parseRate(s) {
8
+ const m = /^(\d+(?:\.\d+)?)([KMG])?$/i.exec(s.trim());
9
+ if (!m || !(Number(m[1]) > 0))
10
+ throw new TidepullError(`Invalid rate "${s}" (examples: 500K, 1.5M)`, 2);
11
+ const mult = { K: 1024, M: 1024 ** 2, G: 1024 ** 3 }[(m[2] ?? "").toUpperCase()] ?? 1;
12
+ return Math.round(Number(m[1]) * mult);
13
+ }
14
+ /** Splits a config line into arguments. Supports 'single' and "double" quotes and \" inside double quotes. */
15
+ export function splitArgs(line) {
16
+ const out = [];
17
+ let cur = "";
18
+ let quote = "";
19
+ let started = false;
20
+ for (let i = 0; i < line.length; i++) {
21
+ const c = line[i];
22
+ if (quote) {
23
+ if (c === quote)
24
+ quote = "";
25
+ else if (c === "\\" && quote === '"' && i + 1 < line.length)
26
+ cur += line[++i];
27
+ else
28
+ cur += c;
29
+ }
30
+ else if (c === '"' || c === "'") {
31
+ quote = c;
32
+ started = true;
33
+ }
34
+ else if (/\s/.test(c)) {
35
+ if (cur || started)
36
+ out.push(cur);
37
+ cur = "";
38
+ started = false;
39
+ }
40
+ else
41
+ cur += c;
42
+ }
43
+ if (quote)
44
+ throw new TidepullError(`Unterminated quote in: ${line}`, 2);
45
+ if (cur || started)
46
+ out.push(cur);
47
+ return out;
48
+ }
49
+ /** One URL per line; blank lines and lines starting with # are ignored. "-" reads stdin. */
50
+ export function readUrlList(file) {
51
+ let text;
52
+ try {
53
+ text = readFileSync(file === "-" ? 0 : file, "utf8");
54
+ }
55
+ catch (e) {
56
+ throw new TidepullError(`Cannot read batch file ${file}: ${errMsg(e)}`, 2);
57
+ }
58
+ return text.split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith("#"));
59
+ }
60
+ export function defaultConfigPath(env = process.env) {
61
+ return path.join(env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config"), "tidepull", "config");
62
+ }
63
+ /**
64
+ * Arguments from the config file: one or more options per line, # starts a comment.
65
+ * Placed before the command line so the command line wins. Returns [] when disabled or absent.
66
+ */
67
+ export function configArgs(argv, env = process.env) {
68
+ if (argv.includes("--no-config"))
69
+ return [];
70
+ const at = argv.findIndex((a) => a === "--config-location" || a.startsWith("--config-location="));
71
+ let file;
72
+ if (at >= 0) {
73
+ const a = argv[at];
74
+ file = a.includes("=") ? a.slice(a.indexOf("=") + 1) : argv[at + 1];
75
+ if (!file || !existsSync(file))
76
+ throw new TidepullError(`Config file not found: ${file ?? "(no path given)"}`, 2);
77
+ }
78
+ else if (existsSync(defaultConfigPath(env)))
79
+ file = defaultConfigPath(env);
80
+ if (!file)
81
+ return [];
82
+ const out = [];
83
+ for (const raw of readFileSync(file, "utf8").split(/\r?\n/)) {
84
+ const line = raw.trim();
85
+ if (line && !line.startsWith("#"))
86
+ out.push(...splitArgs(line));
87
+ }
88
+ return out;
89
+ }
90
+ /** Extractors whose ids are not globally unique (a file name, a playlist path): key them by URL instead. */
91
+ const BY_URL = new Set(["direct", "hls", "dash", "generic"]);
92
+ /** Remembers finished downloads so later runs skip them. One key per line. */
93
+ export class Archive {
94
+ file;
95
+ keys;
96
+ constructor(file) {
97
+ this.file = file;
98
+ const lines = existsSync(file) ? readFileSync(file, "utf8").split(/\r?\n/) : [];
99
+ this.keys = new Set(lines.map((l) => l.trim()).filter(Boolean));
100
+ }
101
+ static key(info) {
102
+ return `${info.extractor} ${BY_URL.has(info.extractor) ? info.webpage_url : info.id}`;
103
+ }
104
+ has(info) {
105
+ return this.keys.has(Archive.key(info));
106
+ }
107
+ add(info) {
108
+ const key = Archive.key(info);
109
+ if (this.keys.has(key))
110
+ return;
111
+ mkdirSync(path.dirname(path.resolve(this.file)), { recursive: true });
112
+ appendFileSync(this.file, key + "\n");
113
+ this.keys.add(key);
114
+ }
115
+ }
@@ -6,10 +6,19 @@ export interface Progress {
6
6
  /** total is a guess (HLS: extrapolated from finished segments) */
7
7
  estimated?: boolean;
8
8
  }
9
+ /** Caps average throughput at `rate` bytes per second by delaying callers. */
10
+ export declare class RateLimiter {
11
+ private rate;
12
+ private start;
13
+ private sent;
14
+ constructor(rate: number);
15
+ take(bytes: number, signal?: AbortSignal): Promise<void>;
16
+ }
9
17
  export interface DownloadOpts {
10
18
  http: Http;
11
19
  headers?: Record<string, string>;
12
20
  signal?: AbortSignal;
21
+ limiter?: RateLimiter;
13
22
  onProgress: (p: Progress) => void;
14
23
  }
15
24
  /** Plain HTTP download. Resumes from `<dest>.part` with Range requests. */
@@ -1,10 +1,26 @@
1
1
  import { createDecipheriv } from "node:crypto";
2
2
  import { createWriteStream } from "node:fs";
3
3
  import { rename, rm, stat } from "node:fs/promises";
4
+ import { setTimeout as sleep } from "node:timers/promises";
4
5
  import { Readable, Transform } from "node:stream";
5
6
  import { pipeline } from "node:stream/promises";
6
7
  import { TidepullError } from "./errors.js";
7
8
  import { isMasterPlaylist, parseMedia } from "./hls.js";
9
+ /** Caps average throughput at `rate` bytes per second by delaying callers. */
10
+ export class RateLimiter {
11
+ rate;
12
+ start = Date.now();
13
+ sent = 0;
14
+ constructor(rate) {
15
+ this.rate = rate;
16
+ }
17
+ async take(bytes, signal) {
18
+ this.sent += bytes;
19
+ const wait = this.start + (this.sent / this.rate) * 1000 - Date.now();
20
+ if (wait > 0)
21
+ await sleep(wait, undefined, { signal });
22
+ }
23
+ }
8
24
  /** Plain HTTP download. Resumes from `<dest>.part` with Range requests. */
9
25
  export async function downloadHttp(url, dest, o) {
10
26
  const part = dest + ".part";
@@ -52,7 +68,19 @@ export async function downloadHttp(url, dest, o) {
52
68
  cb(null, chunk);
53
69
  },
54
70
  });
55
- await pipeline(Readable.fromWeb(res.body), counter, createWriteStream(part, { flags: append ? "a" : "w" }), { signal: o.signal });
71
+ const limiter = o.limiter;
72
+ const throttle = new Transform({
73
+ async transform(chunk, _enc, cb) {
74
+ try {
75
+ await limiter?.take(chunk.length, o.signal);
76
+ cb(null, chunk);
77
+ }
78
+ catch (e) {
79
+ cb(e);
80
+ }
81
+ },
82
+ });
83
+ await pipeline(Readable.fromWeb(res.body), throttle, counter, createWriteStream(part, { flags: append ? "a" : "w" }), { signal: o.signal });
56
84
  if (total !== undefined && done !== total) {
57
85
  throw new TidepullError(`Incomplete download (${done}/${total} bytes). Re-run to resume.`);
58
86
  }
@@ -126,6 +154,7 @@ export async function downloadSegments(segments, dest, o) {
126
154
  lastMap = map;
127
155
  ext = "mp4";
128
156
  }
157
+ await o.limiter?.take(buf.length, o.signal);
129
158
  await write(buf);
130
159
  bytes += buf.length;
131
160
  if (next < n)
package/dist/core/http.js CHANGED
@@ -18,7 +18,7 @@ export class Http {
18
18
  defaultSignal;
19
19
  constructor(o = {}) {
20
20
  this.headers = {
21
- "User-Agent": o.userAgent ?? "Mozilla/5.0 (compatible; tidepull/0.1)",
21
+ "User-Agent": o.userAgent ?? "Mozilla/5.0 (compatible; tidepull)",
22
22
  "Accept-Language": "en-US,en;q=0.9",
23
23
  };
24
24
  this.secret = {};
@@ -19,6 +19,8 @@ export interface DownloadOptions {
19
19
  ffmpeg?: string;
20
20
  /** extra request headers for the media downloads */
21
21
  headers: Record<string, string>;
22
+ /** maximum average download speed in bytes per second (applies to each file) */
23
+ limitRate?: number;
22
24
  }
23
25
  export declare function extractInfo(rawUrl: string, ctx: Ctx): Promise<Info>;
24
26
  /** Selects formats per opts.format, downloads them, merges/remuxes with ffmpeg if needed. Returns the final file path. */
@@ -1,6 +1,6 @@
1
1
  import { mkdir, rename, rm, stat } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { downloadDash, downloadHls, downloadHttp } from "./downloader.js";
3
+ import { downloadDash, downloadHls, downloadHttp, RateLimiter } from "./downloader.js";
4
4
  import { TidepullError } from "./errors.js";
5
5
  import { findFfmpeg, mergeStreams, remux } from "./ffmpeg.js";
6
6
  import { Meter } from "./meter.js";
@@ -73,7 +73,8 @@ export async function downloadInfo(info, opts, ctx) {
73
73
  const eta = speed && p.total ? (p.total - p.downloaded) / speed : undefined;
74
74
  ctx.emit(compact({ type: "progress", format_id: f.format_id, ...p, speed, eta }));
75
75
  };
76
- const common = { http: ctx.http, headers: { ...f.http_headers, ...opts.headers }, signal: ctx.signal, onProgress };
76
+ const limiter = opts.limitRate ? new RateLimiter(opts.limitRate) : undefined;
77
+ const common = { http: ctx.http, headers: { ...f.http_headers, ...opts.headers }, signal: ctx.signal, limiter, onProgress };
77
78
  let ext = f.ext;
78
79
  if (f.protocol === "hls")
79
80
  ({ ext } = await downloadHls(f.url, dest, { ...common, concurrency: opts.concurrency }));
package/dist/main.js CHANGED
@@ -2,6 +2,7 @@ import { parseArgs } from "node:util";
2
2
  import { DEFAULT_FORMAT, selectFormats } from "./core/selector.js";
3
3
  import { TidepullError, errMsg } from "./core/errors.js";
4
4
  import { existsSync, readFileSync } from "node:fs";
5
+ import { Archive, configArgs, parseRate, readUrlList } from "./cliutil.js";
5
6
  import { createTidepull } from "./tidepull.js";
6
7
  import dash from "./dash/index.js";
7
8
  import { defaultPluginDir, loadPlugins } from "./loader.js";
@@ -40,7 +41,16 @@ Plugins:
40
41
  --plugin PATH Load a plugin file or directory (repeatable). Plugins run with your privileges!
41
42
  --no-plugins Skip auto-loading ~/.config/tidepull/plugins (or $TIDEPULL_PLUGIN_DIR)
42
43
 
44
+ Input:
45
+ -a, --batch-file FILE Read URLs from FILE, one per line ("-" = stdin, # starts a comment)
46
+ --download-archive FILE Skip items listed in FILE; record new ones after downloading
47
+
48
+ Config:
49
+ --config-location FILE Read options from FILE (default: ~/.config/tidepull/config)
50
+ --no-config Do not read a config file
51
+
43
52
  Network:
53
+ --limit-rate RATE Maximum download speed per file, e.g. 500K or 1.5M
44
54
  -N, --concurrent-fragments N HLS segments fetched in parallel (default: 4)
45
55
  -R, --retries N Retries per request (default: 3)
46
56
  --header "Name: value" Extra request header (repeatable). Secret-looking headers (Authorization,
@@ -85,7 +95,7 @@ export async function main(argv) {
85
95
  let positionals;
86
96
  function parse() {
87
97
  return parseArgs({
88
- args: argv,
98
+ args,
89
99
  allowPositionals: true,
90
100
  options: {
91
101
  format: { type: "string", short: "f" },
@@ -113,12 +123,25 @@ export async function main(argv) {
113
123
  "progress-json": { type: "boolean" },
114
124
  plugin: { type: "string", multiple: true },
115
125
  "no-plugins": { type: "boolean" },
126
+ "batch-file": { type: "string", short: "a" },
127
+ "download-archive": { type: "string" },
128
+ "limit-rate": { type: "string" },
129
+ "config-location": { type: "string" },
130
+ "no-config": { type: "boolean" },
116
131
  "no-color": { type: "boolean" },
117
132
  help: { type: "boolean", short: "h" },
118
133
  version: { type: "boolean" },
119
134
  },
120
135
  });
121
136
  }
137
+ let args = argv;
138
+ try {
139
+ args = [...configArgs(argv), ...argv];
140
+ }
141
+ catch (e) {
142
+ process.stderr.write(`ERROR: ${errMsg(e)}\n`);
143
+ return e instanceof TidepullError ? e.exitCode : 2;
144
+ }
122
145
  try {
123
146
  ({ values, positionals } = parse());
124
147
  }
@@ -135,7 +158,22 @@ export async function main(argv) {
135
158
  verbose: values.verbose,
136
159
  color: !values["no-color"] && shouldUseColor(),
137
160
  });
138
- if (!positionals.length && !values["list-extractors"]) {
161
+ const urls = [...positionals];
162
+ let limitRate;
163
+ let archive;
164
+ try {
165
+ if (values["batch-file"])
166
+ urls.push(...readUrlList(values["batch-file"]));
167
+ if (values["limit-rate"])
168
+ limitRate = parseRate(values["limit-rate"]);
169
+ if (values["download-archive"])
170
+ archive = new Archive(values["download-archive"]);
171
+ }
172
+ catch (e) {
173
+ log.error(errMsg(e));
174
+ return e instanceof TidepullError ? e.exitCode : 1;
175
+ }
176
+ if (!urls.length && !values["list-extractors"]) {
139
177
  log.error("You must provide at least one URL. Try 'tidepull --help'.");
140
178
  return 2;
141
179
  }
@@ -184,6 +222,7 @@ export async function main(argv) {
184
222
  mergeFormat: values["merge-output-format"],
185
223
  remuxVideo: values["remux-video"],
186
224
  headers,
225
+ limitRate,
187
226
  };
188
227
  for (const k of Object.keys(opts))
189
228
  if (opts[k] === undefined)
@@ -194,7 +233,7 @@ export async function main(argv) {
194
233
  process.once("SIGINT", onSigint);
195
234
  let code = 0;
196
235
  try {
197
- for (const url of positionals) {
236
+ for (const url of urls) {
198
237
  try {
199
238
  const info = await tp.extract(url, { signal: ctl.signal });
200
239
  if (values["dump-json"])
@@ -213,8 +252,12 @@ export async function main(argv) {
213
252
  else if (values.simulate) {
214
253
  log.tag("info", `${info.title} (${info.formats.length} format(s))`);
215
254
  }
255
+ else if (archive?.has(info)) {
256
+ log.tag("download", `${info.title}: already in the archive, skipping`);
257
+ }
216
258
  else {
217
259
  const file = await tp.download(info, { ...opts, signal: ctl.signal });
260
+ archive?.add(info);
218
261
  if (values["print-path"])
219
262
  process.stdout.write(file + "\n");
220
263
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boy-offi9-inc/tidepull",
3
- "version": "0.1.0-rc.1",
3
+ "version": "0.2.0-rc.0",
4
4
  "description": "A minimal, from-scratch media downloader library: extractor plugins, yt-dlp-style format selection, resumable downloads.",
5
5
  "type": "module",
6
6
  "license": "MIT",