@boy-offi9-inc/tidepull 0.2.0-rc.1 → 0.3.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
@@ -37,14 +37,31 @@ await g.pull(url, { signal: ctl.signal }); // rejects with name === "Abor
37
37
 
38
38
  Cap the speed with `limitRate` (bytes per second, applied to each file): `g.download(info, { limitRate: 1_000_000 })`.
39
39
 
40
+ ### Playlists and feeds
41
+
42
+ RSS/Atom feeds with audio or video enclosures and `.m3u` files are playlists. Enable them with the opt-in `feeds` plugin and download every item with `pullAll`:
43
+
44
+ ```ts
45
+ import feeds from "@boy-offi9-inc/tidepull/feeds";
46
+ import { pullAll } from "@boy-offi9-inc/tidepull/playlist";
47
+
48
+ const g = createTidepull({ plugins: [feeds] });
49
+ const files = await pullAll(g, "https://example.com/podcast.rss", { items: "1-3,7", paths: "./out" });
50
+ // "01 - Episode title.mp3", "02 - ...": the number and the title come from the playlist
51
+ ```
52
+
53
+ `g.resolve(url)` returns an `Info` or a `Playlist` (`isPlaylist(x)` tells you which). `g.extract(url)` still returns a single `Info` and refuses a playlist with a clear error. A failing item is thrown by default; pass `onError` to report it and continue. Template fields for playlist items: `%(playlist)s`, `%(playlist_index)02d`, `%(playlist_count)s`, `%(playlist_id)s`.
54
+
40
55
  ## API (everything else is internal)
41
56
  | Export | Purpose |
42
57
  |---|---|
43
- | `createTidepull(opts?)` → `Tidepull` | `.extract(url)`, `.select(info, selector)`, `.download(info, opts)`, `.pull(url, opts)`, `.on(listener)`, `.use(plugin)`, `.extractors` |
58
+ | `createTidepull(opts?)` → `Tidepull` | `.extract(url)`, `.resolve(url)`, `.select(info, selector)`, `.download(info, opts)`, `.pull(url, opts)`, `.on(listener)`, `.use(plugin)`, `.extractors` |
44
59
  | `definePlugin`, `PLUGIN_API_VERSION` | write extractor plugins |
45
60
  | `@boy-offi9-inc/tidepull/dash` *(opt-in)* | DASH VOD: `createTidepull({ plugins: [dash] })` |
46
61
  | `@boy-offi9-inc/tidepull/loader` *(opt-in)* | `loadPlugins(paths)` / `loadPlugin(file)`: load plugins from disk |
47
62
  | `@boy-offi9-inc/tidepull/cookies` *(opt-in)* | `parseCookies`, `loadCookieFile`, `cookieJar`: `createTidepull({ http: { cookies: cookieJar(cookies) } })` |
63
+ | `@boy-offi9-inc/tidepull/feeds` *(opt-in)* | RSS/Atom feeds and `.m3u` files as playlists: `createTidepull({ plugins: [feeds] })`; also `parseFeed`, `parseM3u` |
64
+ | `@boy-offi9-inc/tidepull/playlist` *(opt-in)* | `pullAll`, `resolveItems`, `parseItems`, `playlistFields` |
48
65
  | `selectFormats`, `renderTemplate`, `parseHlsMaster/Media` | the building blocks, usable standalone |
49
66
  | `Http`, `TidepullError` | redirect-safe, header-scoped HTTP client; error type |
50
67
  | types | `Info`, `Format`, `Extractor`, `TidepullEvent`, `DownloadOptions`, `TidepullPlugin`, ... |
@@ -69,6 +86,8 @@ export default definePlugin({
69
86
  ```
70
87
  Plugins run before built-ins; the generic fallback is always last. From disk: `import { loadPlugins } from "@boy-offi9-inc/tidepull/loader"` (the CLI does this for you, and bundles DASH). A plugin targeting a different `apiVersion` is refused with a clear message instead of failing mysteriously. **Plugins execute with your privileges. Only load code you trust.** See `src/extractors/_template.ts`.
71
88
 
89
+ An extractor may instead return a `Playlist` (`{ kind: "playlist", id, title, extractor, webpage_url, entries: [{ url, title? }] }`) for a page that lists several items; each entry is then extracted on its own by the same extractors.
90
+
72
91
  ## CLI
73
92
  ```bash
74
93
  tidepull -F URL # list formats
@@ -78,10 +97,14 @@ tidepull -j URL | jq .formats # data on stdout, logs on std
78
97
  tidepull -a urls.txt --download-archive done.txt # batch input; skip what you already downloaded
79
98
  tidepull --limit-rate 1M URL # cap the speed (500K, 1.5M, ...)
80
99
  tidepull --cookies cookies.txt URL # use your own logged-in session
100
+ tidepull https://example.com/podcast.rss -P ~/Music # every item of a feed or .m3u playlist
101
+ tidepull --playlist-items 1-3,7 URL # only some items (-F lists a playlist's entries)
81
102
  ```
82
103
 
83
104
  **Cookies.** `--cookies FILE` reads a Netscape `cookies.txt` (the format browser extensions export). Each cookie is sent only to the host, path and scheme it was issued for. Keep the file private (`chmod 600`); you get a warning if other users can read it.
84
105
 
106
+ **Playlists.** A feed or `.m3u` URL downloads every item; `--playlist-items 1-3,7,10-` chooses some. Items are numbered in the file name (`01 - Title.mp3`). A failing item is reported and the rest continue (exit code 1). `-j` prints the playlist as one JSON object and `-F` lists its entries, without downloading.
107
+
85
108
  **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.
86
109
 
87
110
  **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.
@@ -93,6 +116,7 @@ From a clone, `node src/cli.ts <args>` runs the TypeScript source directly (Node
93
116
  **What Tidepull does**
94
117
  - Downloads direct media files, HLS (VOD, AES-128) and DASH (VOD) streams, and pages that embed them
95
118
  - Resumes interrupted downloads, caps speed, retries with backoff and cancels cleanly
119
+ - Downloads RSS/Atom feeds (audio and video enclosures) and `.m3u` files as playlists, with item selection and numbered file names
96
120
  - Merges separate video and audio, or remuxes, with ffmpeg
97
121
  - Selects formats (`bv*[height<=720]+ba/b`) and names files from templates
98
122
  - Uses your own cookies (`--cookies`) and headers, sending them only to the hosts they belong to
@@ -102,7 +126,7 @@ From a clone, `node src/cli.ts <args>` runs the TypeScript source directly (Node
102
126
  - No site-specific extractors are built in. Platforms such as YouTube hide their media behind scripts and tokens and need a plugin
103
127
  - No DRM: protected streams (Widevine, PlayReady, FairPlay, encrypted DASH) are not supported and will not be
104
128
  - No circumvention: it cannot get past logins, paywalls or geo-blocks. With `--cookies` it only fetches what your own session can already see
105
- - Not implemented yet: live streams, multi-period DASH (first period only), SAMPLE-AES, byte-range HLS/DASH, subtitles, playlists, a proxy option
129
+ - Not implemented yet: live streams, multi-period DASH (first period only), SAMPLE-AES, byte-range HLS/DASH, subtitles, playlists from video sites (they need a plugin), a proxy option
106
130
  - Cookies are read-only: `Set-Cookie` responses are not stored
107
131
 
108
132
  ### Details
@@ -113,7 +137,8 @@ From a clone, `node src/cli.ts <args>` runs the TypeScript source directly (Node
113
137
  | DASH VOD (`.mpd`), opt-in via `@boy-offi9-inc/tidepull/dash` (built into the CLI) | `SegmentTemplate` (`$Number%05d$`, `$Time$`, timelines, durations), `SegmentList`, single-file `SegmentBase`, nested `BaseURL`; encrypted (`ContentProtection`) representations are skipped, never decrypted |
114
138
  | Generic page extractor | `og:video`, `<video>/<source>`, bare media URLs in HTML/JSON |
115
139
  | Format selector | `b bv bv* ba ba* w wv wa`, `+` merge, `/` fallback, `()` groups, `[height<=720]` `[filesize<?50M]` `[ext=mp4]` |
116
- | Output templates | `%(title)s`, `%(x\|default)s`, `%(title).50s`, sanitized |
140
+ | Output templates | `%(title)s`, `%(x\|default)s`, `%(title).50s`, `%(n)02d`, sanitized |
141
+ | Playlists | RSS 2.0/1.0 and Atom feeds (`<enclosure>`, Atom enclosure links, Media RSS) and `.m3u` files; opt-in via `/feeds` (built into the CLI); entries are extracted one by one, in order |
117
142
  | Cookies | Netscape `cookies.txt`; matched by domain, path, `Secure` and expiry; re-evaluated on every redirect hop |
118
143
  | CLI conveniences | `-a` batch input, `--download-archive`, `--limit-rate`, `--config-location` |
119
144
  | Merge / remux | ffmpeg |
@@ -123,8 +148,11 @@ The core does only what every user needs: extract → select → download, event
123
148
 
124
149
  | Import | Files | Raw | Gzip | Minified (gzip) |
125
150
  |---|---|---|---|---|
126
- | `@boy-offi9-inc/tidepull` (core: direct, HLS, generic page, selector, templates, resume, merge) | 18 | 44.9 KB | 13.5 KB | 22 KB (9 KB) |
127
- | `@boy-offi9-inc/tidepull/dash` (adds XML + MPD parsing) | +6 | +14 KB | +4.7 KB | +7 KB (+3 KB) |
151
+ | `@boy-offi9-inc/tidepull` (core: direct, HLS, generic page, selector, templates, resume, merge, playlists contract) | 18 | 49.2 KB | 14.7 KB | 24 KB (9.8 KB) |
152
+ | `@boy-offi9-inc/tidepull/dash` (adds XML + MPD parsing) | +6 | +14 KB | +4.7 KB | +6.7 KB (+3.1 KB) |
153
+ | `@boy-offi9-inc/tidepull/feeds` (RSS/Atom + .m3u; shares the XML parser with dash) | +5 | +9 KB | +3.3 KB | +3.8 KB (+1.9 KB) |
154
+ | `@boy-offi9-inc/tidepull/playlist` (`pullAll`, item selection) | +1 | +3.9 KB | +1.5 KB | +1.9 KB (+1.0 KB) |
155
+ | `@boy-offi9-inc/tidepull/cookies` (cookies.txt) | +2 | +3.8 KB | +1.6 KB | +1.6 KB (+0.9 KB) |
128
156
  | `@boy-offi9-inc/tidepull/loader` (plugins from disk) | +3 | +4 KB | +1.7 KB | n/a (Node only) |
129
157
 
130
158
  `npm run size` fails the build if the core grows past its budget. CLI and terminal UI are not part of `import "@boy-offi9-inc/tidepull"`.
@@ -134,6 +162,7 @@ The core does only what every user needs: extract → select → download, event
134
162
  - **Redirect-safe HTTP.** Redirects are followed manually and headers are recomputed on every hop: secrets and per-request headers stay with their own host, non-http(s) targets are refused, loops are capped.
135
163
  - **Origin-scoped secrets.** Custom headers like `Authorization`, `Cookie` or API tokens (`--header` / `http.headers`) are sent only to the origins you pass to `extract()`/`pull()`, plus any `--header-host` / `http.headerHosts` patterns (`cdn.example.com`, `*.example.com`). `Referer`, `Origin`, `Accept*`, `User-Agent` and `Range` are never treated as secret. Using one `Tidepull` instance for several sites trusts all of them, so use one instance per credential. The low-level `Http` class (without `headerHosts`) sends headers to each request's start origin only.
136
164
  - **Per-host cookies.** `--cookies` sends each cookie only to the host, path and scheme it was issued for (`Secure` cookies never go over http). A cookie with a single-label domain such as `.com` is treated as host-only. Cookie values are never logged and never appear in `-j` output.
165
+ - **Untrusted playlist entries.** URLs found inside a feed or playlist are extracted with `trust: false`, so secret headers (`--header`) are never sent to hosts a feed names. Only the URL you gave is trusted.
137
166
  - Output filenames are built from sanitized fields only. Only `http(s)` URLs are accepted.
138
167
 
139
168
  ## Legal
@@ -33,6 +33,18 @@ export type TidepullEvent = {
33
33
  } | {
34
34
  type: "remux";
35
35
  output: string;
36
+ } | {
37
+ type: "playlist";
38
+ title: string;
39
+ count: number;
40
+ selected: number;
41
+ } | {
42
+ type: "item";
43
+ index: number;
44
+ position: number;
45
+ total: number;
46
+ url: string;
47
+ title?: string;
36
48
  } | {
37
49
  type: "done";
38
50
  file: string;
@@ -1,4 +1,4 @@
1
- import type { Ctx, Info } from "./types.js";
1
+ import type { Ctx, Info, Playlist } from "./types.js";
2
2
  export declare const DEFAULT_OUTPUT = "%(title)s [%(id)s].%(ext)s";
3
3
  export interface DownloadOptions {
4
4
  /** format selector, default "bv*+ba/b" */
@@ -21,7 +21,13 @@ export interface DownloadOptions {
21
21
  headers: Record<string, string>;
22
22
  /** maximum average download speed in bytes per second (applies to each file) */
23
23
  limitRate?: number;
24
+ /** extra output-template fields (playlist downloads set playlist, playlist_id, playlist_index, playlist_count) */
25
+ fields?: Record<string, string | number>;
24
26
  }
27
+ export declare const isPlaylist: (x: Info | Playlist) => x is Playlist;
28
+ /** Resolves a URL with the first matching extractor: a single item (Info) or a Playlist. */
29
+ export declare function resolveUrl(rawUrl: string, ctx: Ctx): Promise<Info | Playlist>;
30
+ /** Like resolveUrl, but a playlist is an error (callers that need one item). */
25
31
  export declare function extractInfo(rawUrl: string, ctx: Ctx): Promise<Info>;
26
32
  /** Selects formats per opts.format, downloads them, merges/remuxes with ffmpeg if needed. Returns the final file path. */
27
33
  export declare function downloadInfo(info: Info, opts: DownloadOptions, ctx: Ctx): Promise<string>;
@@ -7,7 +7,9 @@ import { Meter } from "./meter.js";
7
7
  import { selectFormats } from "./selector.js";
8
8
  import { renderTemplate } from "./template.js";
9
9
  export const DEFAULT_OUTPUT = "%(title)s [%(id)s].%(ext)s";
10
- export async function extractInfo(rawUrl, ctx) {
10
+ export const isPlaylist = (x) => x.kind === "playlist";
11
+ /** Resolves a URL with the first matching extractor: a single item (Info) or a Playlist. */
12
+ export async function resolveUrl(rawUrl, ctx) {
11
13
  let url;
12
14
  try {
13
15
  url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(rawUrl) ? rawUrl : `https://${rawUrl}`);
@@ -21,10 +23,22 @@ export async function extractInfo(rawUrl, ctx) {
21
23
  if (!ex)
22
24
  throw new TidepullError(`No extractor can handle ${url.href}`);
23
25
  ctx.emit({ type: "extract", extractor: ex.name, url: url.href });
24
- const info = await ex.extract(url, ctx);
25
- if (!info.formats?.length)
26
+ const result = await ex.extract(url, ctx);
27
+ if (isPlaylist(result)) {
28
+ if (!result.entries?.length)
29
+ throw new TidepullError(`Extractor "${ex.name}" returned an empty playlist`);
30
+ }
31
+ else if (!result.formats?.length)
26
32
  throw new TidepullError(`Extractor "${ex.name}" returned no formats`);
27
- return info;
33
+ return result;
34
+ }
35
+ /** Like resolveUrl, but a playlist is an error (callers that need one item). */
36
+ export async function extractInfo(rawUrl, ctx) {
37
+ const result = await resolveUrl(rawUrl, ctx);
38
+ if (isPlaylist(result)) {
39
+ throw new TidepullError(`${rawUrl} is a playlist (${result.entries.length} items); use resolve() or pullAll() from "playlist" to download its items`);
40
+ }
41
+ return result;
28
42
  }
29
43
  /** Drops undefined keys so events serialize cleanly. */
30
44
  const compact = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
@@ -42,13 +56,15 @@ export async function downloadInfo(info, opts, ctx) {
42
56
  const predictedExt = merging ? opts.mergeFormat : chosen[0].ext;
43
57
  const fields = {
44
58
  ...scalars(info),
59
+ ...opts.fields,
45
60
  ...scalars(chosen[0]),
46
61
  format_id: chosen.map((f) => f.format_id).join("+"),
47
62
  resolution: chosen[0].height ? `${chosen[0].width ?? "?"}x${chosen[0].height}` : "audio only",
48
63
  ext: predictedExt,
49
64
  };
50
- // Default name: just the title when it equals the id (direct files).
51
- const template = opts.output ?? (String(info.title) === String(info.id) ? "%(title)s.%(ext)s" : DEFAULT_OUTPUT);
65
+ // Default name: just the title when it equals the id (direct files); playlist items get their number in front.
66
+ const defaultName = String(info.title) === String(info.id) ? "%(title)s.%(ext)s" : DEFAULT_OUTPUT;
67
+ const template = opts.output ?? (opts.fields?.playlist_index !== undefined ? `%(playlist_index)02d - ${defaultName}` : defaultName);
52
68
  let target = path.resolve(opts.paths, renderTemplate(template, fields));
53
69
  await mkdir(path.dirname(target), { recursive: true });
54
70
  const exists = await stat(target).then(() => true, () => false);
@@ -1,3 +1,3 @@
1
- /** Output templates: "%(title)s [%(id)s].%(ext)s", "%(uploader|unknown)s", "%(title).50s". */
1
+ /** Output templates: "%(title)s [%(id)s].%(ext)s", "%(uploader|unknown)s", "%(title).50s", "%(playlist_index)02d". */
2
2
  export declare function sanitize(s: string): string;
3
3
  export declare function renderTemplate(tpl: string, fields: Record<string, unknown>): string;
@@ -1,4 +1,4 @@
1
- /** Output templates: "%(title)s [%(id)s].%(ext)s", "%(uploader|unknown)s", "%(title).50s". */
1
+ /** Output templates: "%(title)s [%(id)s].%(ext)s", "%(uploader|unknown)s", "%(title).50s", "%(playlist_index)02d". */
2
2
  export function sanitize(s) {
3
3
  const cleaned = s
4
4
  .replace(/[\\/:*?"<>|\x00-\x1f]/g, "_")
@@ -8,11 +8,16 @@ export function sanitize(s) {
8
8
  return (cleaned || "_").slice(0, 200);
9
9
  }
10
10
  export function renderTemplate(tpl, fields) {
11
- return tpl.replace(/%%|%\(([A-Za-z_]\w*)(?:\|([^)]*))?\)(?:\.(\d+))?s/g, (m, key, dflt, max) => {
11
+ return tpl.replace(/%%|%\(([A-Za-z_]\w*)(?:\|([^)]*))?\)(?:\.(\d+)s|(0?)(\d*)d|s)/g, (m, key, dflt, max, zero, width) => {
12
12
  if (m === "%%")
13
13
  return "%";
14
14
  const v = fields[key];
15
- let s = v === undefined || v === null || typeof v === "object" ? (dflt ?? "NA") : String(v);
15
+ const missing = v === undefined || v === null || typeof v === "object";
16
+ if (m.endsWith("d")) {
17
+ const n = Number(v);
18
+ return sanitize(missing || !Number.isFinite(n) ? (dflt ?? "NA") : String(Math.trunc(n)).padStart(Number(width) || 0, zero ? "0" : " "));
19
+ }
20
+ let s = missing ? (dflt ?? "NA") : String(v);
16
21
  if (max)
17
22
  s = s.slice(0, Number(max));
18
23
  return sanitize(s);
@@ -48,9 +48,23 @@ export interface Ctx {
48
48
  extractors: readonly Extractor[];
49
49
  signal?: AbortSignal;
50
50
  }
51
+ /** One item of a playlist. It is extracted on its own when it is downloaded. */
52
+ export interface PlaylistEntry {
53
+ url: string;
54
+ title?: string;
55
+ }
56
+ /** A list of items found at one URL (a feed, a playlist file). */
57
+ export interface Playlist {
58
+ kind: "playlist";
59
+ id: string;
60
+ title: string;
61
+ extractor: string;
62
+ webpage_url: string;
63
+ entries: PlaylistEntry[];
64
+ }
51
65
  /** The extractor contract. One file per site. */
52
66
  export interface Extractor {
53
67
  readonly name: string;
54
68
  suitable(url: URL): boolean;
55
- extract(url: URL, ctx: Ctx): Promise<Info>;
69
+ extract(url: URL, ctx: Ctx): Promise<Info | Playlist>;
56
70
  }
@@ -1,6 +1,10 @@
1
- import type { Ctx, Extractor, Info } from "../core/types.js";
1
+ import type { Ctx, Info } from "../core/types.js";
2
2
  import { parseMpd } from "./parse.js";
3
- export declare const dashExtractor: Extractor;
3
+ export declare const dashExtractor: {
4
+ name: string;
5
+ suitable: (url: URL) => boolean;
6
+ extract: (url: URL, ctx: Ctx) => Promise<Info>;
7
+ };
4
8
  export declare function extractDash(url: URL, ctx: Ctx): Promise<Info>;
5
9
  export { parseMpd };
6
10
  declare const _default: import("../plugins.js").TidepullPlugin;
@@ -1,3 +1,7 @@
1
- import type { Ctx, Extractor, Info } from "../core/types.js";
2
- export declare const directExtractor: Extractor;
1
+ import type { Ctx, Info } from "../core/types.js";
2
+ export declare const directExtractor: {
3
+ name: string;
4
+ suitable: (url: URL) => boolean;
5
+ extract: (url: URL, ctx: Ctx) => Promise<Info>;
6
+ };
3
7
  export declare function extractDirect(url: URL, ctx: Ctx): Promise<Info>;
@@ -1,10 +1,21 @@
1
1
  import { TidepullError, errMsg } from "../core/errors.js";
2
+ import { isPlaylist } from "../core/pipeline.js";
2
3
  import { extractDirect } from "./direct.js";
3
4
  import { extractHls } from "./hls.js";
4
5
  import { decodeEntities, extOf } from "./util.js";
5
6
  const MEDIA_CT = /^(video|audio)\//;
6
7
  const HLS_CT = /(mpegurl)/;
7
8
  const DASH_CT = /dash\+xml/;
9
+ const FEED_CT = /(rss|atom)\+xml/;
10
+ const EXT_BY_TYPE = {
11
+ "audio/mpeg": "mp3",
12
+ "audio/mp4": "m4a",
13
+ "audio/x-m4a": "m4a",
14
+ "audio/aac": "aac",
15
+ "audio/ogg": "ogg",
16
+ "video/quicktime": "mov",
17
+ "video/x-matroska": "mkv",
18
+ };
8
19
  function attrs(tag) {
9
20
  const out = {};
10
21
  const re = /([a-zA-Z:_-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
@@ -42,7 +53,10 @@ async function extractOne(u, ctx) {
42
53
  const ex = ctx.extractors.find((e) => e !== genericExtractor && e.suitable(u));
43
54
  if (!ex)
44
55
  throw new TidepullError(`no extractor for ${u.href}`);
45
- return ex.extract(u, ctx);
56
+ const result = await ex.extract(u, ctx);
57
+ if (isPlaylist(result))
58
+ throw new TidepullError(`${u.href} is a playlist, not a single media item`);
59
+ return result;
46
60
  }
47
61
  /** Fallback: look at the page itself (media content-type, og:video, <video>, bare media URLs). */
48
62
  export const genericExtractor = {
@@ -55,6 +69,13 @@ export const genericExtractor = {
55
69
  throw new TidepullError(`HTTP ${res.status} ${res.statusText} for ${url.href}`);
56
70
  }
57
71
  const ct = (res.headers.get("content-type") ?? "").toLowerCase();
72
+ if (FEED_CT.test(ct)) {
73
+ await res.body?.cancel();
74
+ const feeds = ctx.extractors.find((e) => e.name === "rss");
75
+ if (!feeds)
76
+ throw new TidepullError('This URL is a feed; enable feed support with: import feeds from "@boy-offi9-inc/tidepull/feeds"; createTidepull({ plugins: [feeds] })');
77
+ return feeds.extract(new URL(res.url || url.href), ctx);
78
+ }
58
79
  if (MEDIA_CT.test(ct) || HLS_CT.test(ct) || DASH_CT.test(ct)) {
59
80
  await res.body?.cancel();
60
81
  const u = new URL(res.url || url.href);
@@ -67,7 +88,10 @@ export const genericExtractor = {
67
88
  return dash.extract(u, ctx);
68
89
  }
69
90
  const info = await extractDirect(u, ctx);
70
- info.formats[0].ext = extOf(u.pathname) || ct.split("/")[1].split(";")[0];
91
+ const type = ct.split(";")[0].trim();
92
+ info.formats[0].ext = extOf(u.pathname) || EXT_BY_TYPE[type] || type.split("/")[1];
93
+ if (type.startsWith("audio/"))
94
+ info.formats[0].vcodec = "none";
71
95
  return info;
72
96
  }
73
97
  const html = await res.text();
@@ -1,3 +1,7 @@
1
- import type { Ctx, Extractor, Info } from "../core/types.js";
2
- export declare const hlsExtractor: Extractor;
1
+ import type { Ctx, Info } from "../core/types.js";
2
+ export declare const hlsExtractor: {
3
+ name: string;
4
+ suitable: (url: URL) => boolean;
5
+ extract: (url: URL, ctx: Ctx) => Promise<Info>;
6
+ };
3
7
  export declare function extractHls(url: URL, ctx: Ctx): Promise<Info>;
@@ -0,0 +1,21 @@
1
+ import type { Ctx, Playlist, PlaylistEntry } from "./core/types.js";
2
+ export interface ParsedList {
3
+ title: string;
4
+ entries: PlaylistEntry[];
5
+ }
6
+ /** Items with a media enclosure from an RSS 2.0, RSS 1.0 or Atom feed. URLs are resolved against `base`. */
7
+ export declare function parseFeed(text: string, base: string): ParsedList;
8
+ /** Entries of an .m3u playlist file (#EXTINF titles, #PLAYLIST name). Only http(s) URLs are kept. */
9
+ export declare function parseM3u(text: string, base: string): ParsedList;
10
+ export declare const rssExtractor: {
11
+ name: string;
12
+ suitable: (url: URL) => boolean;
13
+ extract(url: URL, ctx: Ctx): Promise<Playlist>;
14
+ };
15
+ export declare const m3uExtractor: {
16
+ name: string;
17
+ suitable: (url: URL) => boolean;
18
+ extract(url: URL, ctx: Ctx): Promise<Playlist>;
19
+ };
20
+ declare const _default: import("./plugins.js").TidepullPlugin;
21
+ export default _default;
package/dist/feeds.js ADDED
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Playlist sources (opt-in: "@boy-offi9-inc/tidepull/feeds"): RSS/Atom feeds with media enclosures, and .m3u playlist files.
3
+ * import feeds from "@boy-offi9-inc/tidepull/feeds";
4
+ * createTidepull({ plugins: [feeds] });
5
+ * Each media URL becomes one playlist entry, extracted on its own when it is downloaded.
6
+ */
7
+ import { TidepullError } from "./core/errors.js";
8
+ import { child, kids, parseXml } from "./dash/xml.js";
9
+ import { extOf, stem } from "./extractors/util.js";
10
+ import { definePlugin } from "./plugins.js";
11
+ const MAX_BYTES = 10 * 1024 * 1024;
12
+ const MAX_ENTRIES = 10_000;
13
+ const isMedia = (type) => !type || /^(audio|video)\//i.test(type) || /octet-stream/i.test(type);
14
+ /** The media URL of an RSS item or Atom entry: <enclosure>, an Atom rel="enclosure" link, or Media RSS <media:content>. */
15
+ function mediaUrl(item) {
16
+ const candidates = [
17
+ ...kids(item, "enclosure").map((e) => ({ url: e.attrs.url, type: e.attrs.type })),
18
+ ...kids(item, "link").filter((l) => l.attrs.rel === "enclosure").map((l) => ({ url: l.attrs.href, type: l.attrs.type })),
19
+ ...[...kids(item, "content"), ...kids(item, "group").flatMap((g) => kids(g, "content"))].map((c) => ({
20
+ url: c.attrs.url,
21
+ type: c.attrs.type ?? (c.attrs.medium ? `${c.attrs.medium}/` : undefined),
22
+ })),
23
+ ];
24
+ return candidates.find((c) => c.url && isMedia(c.type))?.url;
25
+ }
26
+ function toEntry(raw, title, base, seen) {
27
+ if (!raw)
28
+ return undefined;
29
+ let url;
30
+ try {
31
+ url = new URL(raw.trim(), base).href;
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ if (!/^https?:/.test(url) || seen.has(url))
37
+ return undefined;
38
+ seen.add(url);
39
+ return title ? { url, title } : { url };
40
+ }
41
+ /** Items with a media enclosure from an RSS 2.0, RSS 1.0 or Atom feed. URLs are resolved against `base`. */
42
+ export function parseFeed(text, base) {
43
+ const root = parseXml(text);
44
+ let title;
45
+ let items;
46
+ if (root.name === "rss" || root.name === "RDF") {
47
+ const channel = child(root, "channel") ?? root;
48
+ title = child(channel, "title")?.text ?? "";
49
+ items = [...kids(channel, "item"), ...kids(root, "item")];
50
+ }
51
+ else if (root.name === "feed") {
52
+ title = child(root, "title")?.text ?? "";
53
+ items = kids(root, "entry");
54
+ }
55
+ else
56
+ throw new TidepullError("Not an RSS or Atom feed");
57
+ const seen = new Set();
58
+ const entries = [];
59
+ for (const item of items) {
60
+ const entry = toEntry(mediaUrl(item), child(item, "title")?.text.trim(), base, seen);
61
+ if (entry)
62
+ entries.push(entry);
63
+ }
64
+ return { title: title.trim(), entries };
65
+ }
66
+ /** Entries of an .m3u playlist file (#EXTINF titles, #PLAYLIST name). Only http(s) URLs are kept. */
67
+ export function parseM3u(text, base) {
68
+ let title = "";
69
+ let pending;
70
+ const seen = new Set();
71
+ const entries = [];
72
+ for (const raw of text.split(/\r?\n/)) {
73
+ const line = raw.trim();
74
+ if (!line)
75
+ continue;
76
+ if (line.startsWith("#PLAYLIST:"))
77
+ title = line.slice("#PLAYLIST:".length).trim();
78
+ else if (line.startsWith("#EXTINF:"))
79
+ pending = line.includes(",") ? line.slice(line.indexOf(",") + 1).trim() || undefined : undefined;
80
+ else if (!line.startsWith("#")) {
81
+ const entry = toEntry(line, pending, base, seen);
82
+ if (entry)
83
+ entries.push(entry);
84
+ pending = undefined;
85
+ }
86
+ }
87
+ return { title, entries };
88
+ }
89
+ function playlist(extractor, url, parsed, ctx) {
90
+ if (!parsed.entries.length)
91
+ throw new TidepullError(`No media found in this ${extractor === "rss" ? "feed (needs audio or video enclosures)" : "playlist"}`);
92
+ if (parsed.entries.length > MAX_ENTRIES) {
93
+ ctx.log.warn(`Only the first ${MAX_ENTRIES} of ${parsed.entries.length} entries are used`);
94
+ parsed.entries.length = MAX_ENTRIES;
95
+ }
96
+ const id = stem(url.pathname) || url.hostname;
97
+ return { kind: "playlist", id, title: parsed.title || id, extractor, webpage_url: url.href, entries: parsed.entries };
98
+ }
99
+ export const rssExtractor = {
100
+ name: "rss",
101
+ suitable: (url) => /^(rss|atom|xml)$/.test(extOf(url.pathname)) || /(^|\/)(feed|rss|atom)(\.xml)?\/?$/i.test(url.pathname),
102
+ async extract(url, ctx) {
103
+ const { text, finalUrl } = await ctx.http.text(url.href);
104
+ if (text.length > MAX_BYTES)
105
+ throw new TidepullError("Feed is too large");
106
+ return playlist("rss", url, parseFeed(text, finalUrl), ctx);
107
+ },
108
+ };
109
+ export const m3uExtractor = {
110
+ name: "m3u",
111
+ suitable: (url) => extOf(url.pathname) === "m3u",
112
+ async extract(url, ctx) {
113
+ const { text, finalUrl } = await ctx.http.text(url.href);
114
+ if (text.length > MAX_BYTES)
115
+ throw new TidepullError("Playlist is too large");
116
+ return playlist("m3u", url, parseM3u(text, finalUrl), ctx);
117
+ },
118
+ };
119
+ export default definePlugin({ name: "feeds", apiVersion: 1, extractors: [rssExtractor, m3uExtractor] });
package/dist/index.d.ts CHANGED
@@ -3,9 +3,10 @@ export { Tidepull, createTidepull } from "./tidepull.js";
3
3
  export type { TidepullOptions, CallOptions, Listener } from "./tidepull.js";
4
4
  export { definePlugin, PLUGIN_API_VERSION } from "./plugins.js";
5
5
  export type { TidepullPlugin } from "./plugins.js";
6
- export type { Info, Format, Extractor, Ctx, Protocol } from "./core/types.js";
6
+ export type { Info, Format, Extractor, Ctx, Protocol, Playlist, PlaylistEntry } from "./core/types.js";
7
7
  export type { TidepullEvent, Log } from "./core/events.js";
8
8
  export type { DownloadOptions } from "./core/pipeline.js";
9
+ export { isPlaylist } from "./core/pipeline.js";
9
10
  export type { HttpOptions } from "./core/http.js";
10
11
  export { Http } from "./core/http.js";
11
12
  export { TidepullError } from "./core/errors.js";
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  /** Public library API. Everything not exported here is internal. */
2
2
  export { Tidepull, createTidepull } from "./tidepull.js";
3
3
  export { definePlugin, PLUGIN_API_VERSION } from "./plugins.js";
4
+ export { isPlaylist } from "./core/pipeline.js";
4
5
  export { Http } from "./core/http.js";
5
6
  export { TidepullError } from "./core/errors.js";
6
7
  export { selectFormats, DEFAULT_FORMAT } from "./core/selector.js";
package/dist/main.js CHANGED
@@ -2,8 +2,11 @@ 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 { isPlaylist } from "./core/pipeline.js";
5
6
  import { Archive, configArgs, parseRate, readUrlList } from "./cliutil.js";
6
7
  import { cookieJar, loadCookieFile } from "./cookies.js";
8
+ import feeds from "./feeds.js";
9
+ import { playlistFields, resolveItems } from "./playlist.js";
7
10
  import { createTidepull } from "./tidepull.js";
8
11
  import dash from "./dash/index.js";
9
12
  import { defaultPluginDir, loadPlugins } from "./loader.js";
@@ -19,7 +22,8 @@ Usage: tidepull [options] URL [URL...]
19
22
  Selection:
20
23
  -f, --format FORMAT Format selector (default: ${DEFAULT_FORMAT})
21
24
  e.g. "bv*[height<=720]+ba/b", "ba", "hls-1200"
22
- -F, --list-formats List available formats and exit
25
+ -F, --list-formats List available formats and exit (for a playlist: its entries)
26
+ --playlist-items SPEC Playlist items to download, e.g. 1-3,7,10- (default: all)
23
27
 
24
28
  Output:
25
29
  -o, --output TEMPLATE Output template (default: "%(title)s [%(id)s].%(ext)s",
@@ -92,6 +96,11 @@ function listFormats(info) {
92
96
  }
93
97
  return table(rows);
94
98
  }
99
+ function listEntries(p) {
100
+ const rows = [["#", "TITLE", "URL"]];
101
+ p.entries.forEach((e, i) => rows.push([String(i + 1), e.title ?? "", e.url]));
102
+ return table(rows);
103
+ }
95
104
  export async function main(argv) {
96
105
  let values;
97
106
  let positionals;
@@ -131,6 +140,7 @@ export async function main(argv) {
131
140
  cookies: { type: "string" },
132
141
  "config-location": { type: "string" },
133
142
  "no-config": { type: "boolean" },
143
+ "playlist-items": { type: "string" },
134
144
  "no-color": { type: "boolean" },
135
145
  help: { type: "boolean", short: "h" },
136
146
  version: { type: "boolean" },
@@ -212,7 +222,7 @@ export async function main(argv) {
212
222
  }
213
223
  const tp = createTidepull({
214
224
  http: { headers, headerHosts: values["header-host"] ?? [], userAgent: values["user-agent"], retries: num(values.retries, 3), cookies },
215
- plugins: [...plugins, dash],
225
+ plugins: [...plugins, dash, feeds],
216
226
  ffmpeg: values["ffmpeg-location"],
217
227
  });
218
228
  tp.on(values["progress-json"] ? jsonRenderer() : humanRenderer(log, { progress: !values["no-progress"] && !values.quiet }));
@@ -242,34 +252,67 @@ export async function main(argv) {
242
252
  const onSigint = () => ctl.abort();
243
253
  process.once("SIGINT", onSigint);
244
254
  let code = 0;
255
+ const report = (e, url) => {
256
+ log.error(errMsg(e));
257
+ if (values["progress-json"])
258
+ process.stdout.write(JSON.stringify({ type: "error", message: errMsg(e), url }) + "\n");
259
+ if (values.verbose && e instanceof Error && e.stack)
260
+ process.stderr.write(e.stack + "\n");
261
+ code = Math.max(code, e instanceof TidepullError ? e.exitCode : 1);
262
+ };
263
+ /** What to do with one extracted item: print info, list formats, print URLs, or download it. */
264
+ const handle = async (info, fields) => {
265
+ if (values["dump-json"])
266
+ process.stdout.write(JSON.stringify(info) + "\n");
267
+ else if (values["list-formats"]) {
268
+ log.tag("info", `Available formats for ${info.id}:`);
269
+ process.stdout.write(listFormats(info) + "\n");
270
+ }
271
+ else if (values["get-url"]) {
272
+ const chosen = tp.select(info, opts.format);
273
+ if (!chosen)
274
+ throw new TidepullError(`Requested format is not available: ${opts.format}`);
275
+ for (const f of chosen)
276
+ process.stdout.write(f.url + "\n");
277
+ }
278
+ else if (values.simulate) {
279
+ log.tag("info", `${info.title} (${info.formats.length} format(s))`);
280
+ }
281
+ else if (archive?.has(info)) {
282
+ log.tag("download", `${info.title}: already in the archive, skipping`);
283
+ }
284
+ else {
285
+ const file = await tp.download(info, { ...opts, fields, signal: ctl.signal });
286
+ archive?.add(info);
287
+ if (values["print-path"])
288
+ process.stdout.write(file + "\n");
289
+ }
290
+ };
245
291
  try {
246
292
  for (const url of urls) {
247
293
  try {
248
- const info = await tp.extract(url, { signal: ctl.signal });
249
- if (values["dump-json"])
250
- process.stdout.write(JSON.stringify(info) + "\n");
251
- else if (values["list-formats"]) {
252
- log.tag("info", `Available formats for ${info.id}:`);
253
- process.stdout.write(listFormats(info) + "\n");
254
- }
255
- else if (values["get-url"]) {
256
- const chosen = tp.select(info, opts.format);
257
- if (!chosen)
258
- throw new TidepullError(`Requested format is not available: ${opts.format}`);
259
- for (const f of chosen)
260
- process.stdout.write(f.url + "\n");
261
- }
262
- else if (values.simulate) {
263
- log.tag("info", `${info.title} (${info.formats.length} format(s))`);
264
- }
265
- else if (archive?.has(info)) {
266
- log.tag("download", `${info.title}: already in the archive, skipping`);
294
+ const resolved = await tp.resolve(url, { signal: ctl.signal });
295
+ if (isPlaylist(resolved) && (values["dump-json"] || values["list-formats"])) {
296
+ // listing a playlist needs no request per entry
297
+ if (values["dump-json"])
298
+ process.stdout.write(JSON.stringify(resolved) + "\n");
299
+ else {
300
+ log.tag("info", `${resolved.title}: ${resolved.entries.length} item(s)`);
301
+ process.stdout.write(listEntries(resolved) + "\n");
302
+ }
303
+ continue;
267
304
  }
268
- else {
269
- const file = await tp.download(info, { ...opts, signal: ctl.signal });
270
- archive?.add(info);
271
- if (values["print-path"])
272
- process.stdout.write(file + "\n");
305
+ for await (const item of resolveItems(tp, resolved, { signal: ctl.signal, items: values["playlist-items"] })) {
306
+ try {
307
+ if (item.error)
308
+ throw item.error;
309
+ await handle(item.info, playlistFields(item));
310
+ }
311
+ catch (e) {
312
+ if (ctl.signal.aborted)
313
+ throw e;
314
+ report(e, item.entry?.url ?? url);
315
+ }
273
316
  }
274
317
  }
275
318
  catch (e) {
@@ -281,12 +324,7 @@ export async function main(argv) {
281
324
  code = 130;
282
325
  break;
283
326
  }
284
- log.error(errMsg(e));
285
- if (values["progress-json"])
286
- process.stdout.write(JSON.stringify({ type: "error", message: errMsg(e), url }) + "\n");
287
- if (values.verbose && e instanceof Error && e.stack)
288
- process.stderr.write(e.stack + "\n");
289
- code = Math.max(code, e instanceof TidepullError ? e.exitCode : 1);
327
+ report(e, url);
290
328
  }
291
329
  }
292
330
  }
@@ -0,0 +1,40 @@
1
+ import { type DownloadOptions } from "./core/pipeline.js";
2
+ import type { Info, Playlist, PlaylistEntry } from "./core/types.js";
3
+ import type { CallOptions, Tidepull } from "./tidepull.js";
4
+ /** Item numbers from a spec like "1-3,7,10-" (1-based, in the order given, no duplicates). Empty spec selects everything. */
5
+ export declare function parseItems(spec: string | undefined, total: number): number[];
6
+ export interface PlaylistItem {
7
+ /** 1-based position in the playlist */
8
+ index: number;
9
+ /** 1-based position among the selected items */
10
+ position: number;
11
+ /** number of selected items */
12
+ total: number;
13
+ /** undefined when the URL was a single item */
14
+ playlist?: Playlist;
15
+ entry?: PlaylistEntry;
16
+ info?: Info;
17
+ /** why this entry could not be extracted */
18
+ error?: Error;
19
+ }
20
+ /**
21
+ * Template fields for an item: playlist, playlist_id, playlist_index, playlist_count. Empty for a single item.
22
+ * When the extractor's own title is just the id (a bare file name), the entry's title from the playlist is used instead.
23
+ */
24
+ export declare const playlistFields: (item: PlaylistItem) => Record<string, string | number>;
25
+ /**
26
+ * One item for a single URL, or one per selected entry of a playlist (extracted lazily, in order).
27
+ * An entry that fails to extract is reported on the item instead of ending the iteration.
28
+ * `source` may be a URL or an already resolved Info/Playlist.
29
+ */
30
+ export declare function resolveItems(tp: Tidepull, source: string | Info | Playlist, o?: CallOptions & {
31
+ items?: string;
32
+ }): AsyncGenerator<PlaylistItem>;
33
+ export interface PullAllOptions extends Partial<DownloadOptions>, CallOptions {
34
+ /** which playlist items to download, e.g. "1-3,7,10-" (default: all) */
35
+ items?: string;
36
+ /** called for an item that fails; without it the first failure is thrown */
37
+ onError?: (error: Error, item: PlaylistItem) => void;
38
+ }
39
+ /** Downloads a single item, or every selected entry of a playlist, and returns the files in order. */
40
+ export declare function pullAll(tp: Tidepull, source: string, o?: PullAllOptions): Promise<string[]>;
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Playlist helpers (opt-in: "@boy-offi9-inc/tidepull/playlist"): choose items and download every entry of a playlist.
3
+ * Entries are extracted one at a time with `trust: false`, so secret headers never go to hosts named inside a feed.
4
+ */
5
+ import { TidepullError } from "./core/errors.js";
6
+ import { isPlaylist } from "./core/pipeline.js";
7
+ /** Item numbers from a spec like "1-3,7,10-" (1-based, in the order given, no duplicates). Empty spec selects everything. */
8
+ export function parseItems(spec, total) {
9
+ if (!spec?.trim())
10
+ return Array.from({ length: total }, (_, i) => i + 1);
11
+ const out = [];
12
+ const seen = new Set();
13
+ for (const token of spec.split(",").map((s) => s.trim()).filter(Boolean)) {
14
+ const m = /^(\d*)-(\d*)$/.exec(token) ?? /^(\d+)$/.exec(token);
15
+ if (!m)
16
+ throw new TidepullError(`Invalid playlist items "${token}" (examples: 1-3,7,10-)`, 2);
17
+ const first = m[1] === "" ? 1 : Number(m[1]);
18
+ const last = m[2] === undefined ? first : m[2] === "" ? total : Number(m[2]);
19
+ if (first < 1)
20
+ throw new TidepullError(`Playlist items start at 1, got "${token}"`, 2);
21
+ for (let i = first; i <= Math.min(last, total); i++) {
22
+ if (!seen.has(i)) {
23
+ seen.add(i);
24
+ out.push(i);
25
+ }
26
+ }
27
+ }
28
+ return out;
29
+ }
30
+ /**
31
+ * Template fields for an item: playlist, playlist_id, playlist_index, playlist_count. Empty for a single item.
32
+ * When the extractor's own title is just the id (a bare file name), the entry's title from the playlist is used instead.
33
+ */
34
+ export const playlistFields = (item) => {
35
+ if (!item.playlist)
36
+ return {};
37
+ const fields = {
38
+ playlist: item.playlist.title,
39
+ playlist_id: item.playlist.id,
40
+ playlist_index: item.index,
41
+ playlist_count: item.playlist.entries.length,
42
+ };
43
+ if (item.entry?.title && item.info && item.info.title === item.info.id)
44
+ fields.title = item.entry.title;
45
+ return fields;
46
+ };
47
+ /**
48
+ * One item for a single URL, or one per selected entry of a playlist (extracted lazily, in order).
49
+ * An entry that fails to extract is reported on the item instead of ending the iteration.
50
+ * `source` may be a URL or an already resolved Info/Playlist.
51
+ */
52
+ export async function* resolveItems(tp, source, o = {}) {
53
+ const first = typeof source === "string" ? await tp.resolve(source, o) : source;
54
+ if (!isPlaylist(first)) {
55
+ yield { index: 1, position: 1, total: 1, info: first };
56
+ return;
57
+ }
58
+ const picked = parseItems(o.items, first.entries.length);
59
+ tp.emit({ type: "playlist", title: first.title, count: first.entries.length, selected: picked.length });
60
+ for (const [i, index] of picked.entries()) {
61
+ const entry = first.entries[index - 1];
62
+ const base = { index, position: i + 1, total: picked.length, playlist: first, entry };
63
+ tp.emit({ type: "item", index, position: i + 1, total: picked.length, url: entry.url, ...(entry.title ? { title: entry.title } : {}) });
64
+ try {
65
+ yield { ...base, info: await tp.extract(entry.url, { signal: o.signal, trust: false }) };
66
+ }
67
+ catch (e) {
68
+ if (o.signal?.aborted)
69
+ throw e;
70
+ yield { ...base, error: e };
71
+ }
72
+ }
73
+ }
74
+ /** Downloads a single item, or every selected entry of a playlist, and returns the files in order. */
75
+ export async function pullAll(tp, source, o = {}) {
76
+ const { items, onError, ...rest } = o;
77
+ const files = [];
78
+ for await (const item of resolveItems(tp, source, { items, signal: o.signal, trust: o.trust })) {
79
+ try {
80
+ if (item.error)
81
+ throw item.error;
82
+ files.push(await tp.download(item.info, { ...rest, fields: { ...rest.fields, ...playlistFields(item) } }));
83
+ }
84
+ catch (e) {
85
+ if (o.signal?.aborted || !onError)
86
+ throw e;
87
+ onError(e, item);
88
+ }
89
+ }
90
+ return files;
91
+ }
@@ -1,7 +1,7 @@
1
1
  import { type DownloadOptions } from "./core/pipeline.js";
2
2
  import { type TidepullEvent } from "./core/events.js";
3
3
  import { Http, type HttpOptions } from "./core/http.js";
4
- import type { Format, Info } from "./core/types.js";
4
+ import type { Format, Info, Playlist } from "./core/types.js";
5
5
  import type { TidepullPlugin } from "./plugins.js";
6
6
  export type Listener = (e: TidepullEvent) => void;
7
7
  export interface TidepullOptions {
@@ -13,6 +13,11 @@ export interface TidepullOptions {
13
13
  }
14
14
  export interface CallOptions {
15
15
  signal?: AbortSignal;
16
+ /**
17
+ * Let headers marked secret (Authorization, tokens) be sent to this URL's origin. Default true.
18
+ * Pass false for URLs found inside other documents, such as playlist entries.
19
+ */
20
+ trust?: boolean;
16
21
  }
17
22
  /**
18
23
  * The library entry point. No terminal I/O: everything observable goes through events.
@@ -35,9 +40,14 @@ export declare class Tidepull {
35
40
  get extractors(): string[];
36
41
  /** Register a plugin (takes priority over built-in extractors). */
37
42
  use(plugin: TidepullPlugin): this;
43
+ /** Publishes an event to the listeners. */
44
+ emit(e: TidepullEvent): void;
38
45
  private ctx;
39
46
  private guard;
47
+ private trustUrl;
40
48
  extract(url: string, o?: CallOptions): Promise<Info>;
49
+ /** Like extract(), but a playlist (feed, playlist file) comes back as a Playlist instead of an error. */
50
+ resolve(url: string, o?: CallOptions): Promise<Info | Playlist>;
41
51
  /** Which format(s) the selector picks (two or more means merge), or undefined if none match. */
42
52
  select(info: Info, selector?: string): Format[] | undefined;
43
53
  /** Downloads the selected format(s). Resolves to the final file path. */
package/dist/tidepull.js CHANGED
@@ -1,4 +1,4 @@
1
- import { downloadInfo, extractInfo } from "./core/pipeline.js";
1
+ import { downloadInfo, extractInfo, resolveUrl } from "./core/pipeline.js";
2
2
  import { abortError } from "./core/errors.js";
3
3
  import { makeLog } from "./core/events.js";
4
4
  import { Http } from "./core/http.js";
@@ -41,17 +41,19 @@ export class Tidepull {
41
41
  this.registry = buildRegistry(this.plugins);
42
42
  return this;
43
43
  }
44
- ctx(signal) {
45
- const emit = (e) => {
46
- for (const l of this.listeners) {
47
- try {
48
- l(e);
49
- }
50
- catch {
51
- /* listeners must not break the engine */
52
- }
44
+ /** Publishes an event to the listeners. */
45
+ emit(e) {
46
+ for (const l of this.listeners) {
47
+ try {
48
+ l(e);
53
49
  }
54
- };
50
+ catch {
51
+ /* listeners must not break the engine */
52
+ }
53
+ }
54
+ }
55
+ ctx(signal) {
56
+ const emit = (e) => this.emit(e);
55
57
  return { http: this.http.scoped(signal), emit, log: makeLog(emit), extractors: this.registry, signal };
56
58
  }
57
59
  async guard(signal, fn) {
@@ -64,15 +66,25 @@ export class Tidepull {
64
66
  throw e;
65
67
  }
66
68
  }
67
- extract(url, o = {}) {
69
+ trustUrl(url, o) {
70
+ if (o.trust === false)
71
+ return;
68
72
  try {
69
73
  this.http.trust(/^[a-z][a-z0-9+.-]*:\/\//i.test(url) ? url : `https://${url}`);
70
74
  }
71
75
  catch {
72
- /* invalid URL: extractInfo reports it */
76
+ /* invalid URL: the extraction step reports it */
73
77
  }
78
+ }
79
+ extract(url, o = {}) {
80
+ this.trustUrl(url, o);
74
81
  return this.guard(o.signal, () => extractInfo(url, this.ctx(o.signal)));
75
82
  }
83
+ /** Like extract(), but a playlist (feed, playlist file) comes back as a Playlist instead of an error. */
84
+ resolve(url, o = {}) {
85
+ this.trustUrl(url, o);
86
+ return this.guard(o.signal, () => resolveUrl(url, this.ctx(o.signal)));
87
+ }
76
88
  /** Which format(s) the selector picks (two or more means merge), or undefined if none match. */
77
89
  select(info, selector = DEFAULT_FORMAT) {
78
90
  return selectFormats(selector, info.formats);
package/dist/ui/render.js CHANGED
@@ -58,6 +58,12 @@ export function humanRenderer(log, o) {
58
58
  case "remux":
59
59
  log.tag("remux", `Remuxing to "${e.output}"`);
60
60
  break;
61
+ case "playlist":
62
+ log.tag("playlist", `${e.title}: ${e.selected} of ${e.count} item(s)`);
63
+ break;
64
+ case "item":
65
+ log.tag("item", `${e.position}/${e.total}${e.title ? ` ${e.title}` : ""}`);
66
+ break;
61
67
  case "done":
62
68
  log.tag("done", e.file);
63
69
  break;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boy-offi9-inc/tidepull",
3
- "version": "0.2.0-rc.1",
3
+ "version": "0.3.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",
@@ -25,7 +25,7 @@
25
25
  "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json && node scripts/fix-dts.mjs",
26
26
  "prepack": "npm run build",
27
27
  "prepublishOnly": "npm run typecheck && npm test",
28
- "size": "node scripts/size.mjs dist/index.js --budget=48"
28
+ "size": "node scripts/size.mjs dist/index.js --budget=50"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@types/node": "^22.0.0",
@@ -49,6 +49,14 @@
49
49
  "./cookies": {
50
50
  "types": "./dist/cookies.d.ts",
51
51
  "import": "./dist/cookies.js"
52
+ },
53
+ "./feeds": {
54
+ "types": "./dist/feeds.d.ts",
55
+ "import": "./dist/feeds.js"
56
+ },
57
+ "./playlist": {
58
+ "types": "./dist/playlist.d.ts",
59
+ "import": "./dist/playlist.js"
52
60
  }
53
61
  },
54
62
  "files": [