Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Manual

  1. Install installs the command on Linux, macOS and Windows and keeps it updated.
  2. Download posts saves a post, several posts, an account’s posts and your saved posts.
  3. Log in to Instagram saves the session that saved posts and comments need.
  4. Read a post’s comments prints a post’s comments and replies.
  5. Script the command covers --json, exit codes and the config directory.
  6. Serve is the JSON-lines protocol a desktop app drives the downloads through.
  7. Using the library explains resolve, the result, options and supported URL forms.
  8. Instagram explains post resolution, account and saved listing, comments and anonymous access.
  9. Facebook explains post resolution and page listing.
  10. Errors explains the exported error classes and their fields.
  11. Writing an extractor explains how to add a platform.
  12. Tests and cassettes explains replay, recording and snapshots.
  13. Live eval explains fixture output and live checks.
  14. Architecture maps the library’s source modules and request path.

Install

On Linux or macOS:

curl -fsSL https://downloader.rising.sh/install.sh | sh

On Windows, in PowerShell:

irm https://downloader.rising.sh/install.ps1 | iex

Then run downloader --version. The same command updates an installed copy.

What the script installs

With Node 22.13 or newer on your PATH, install.sh installs an 80 KB Node script. Otherwise it installs a standalone binary, about 100 MB because it carries the Bun runtime. install.ps1 always installs the standalone downloader.exe. Both scripts take the files from the newest downloader-cli release and check them against its SHA256SUMS before they install.

VariableEffect
DOWNLOADER_VERSIONInstalls a release such as 0.3.0 instead of the newest.
DOWNLOADER_BIN_DIRInstalls into this directory. Default: ~/.local/bin, or %LOCALAPPDATA%\downloader on Windows.
DOWNLOADER_BINARY1 installs the binary even when Node is present. Only install.sh reads it.
curl -fsSL https://downloader.rising.sh/install.sh | DOWNLOADER_VERSION=0.3.0 sh

install.sh prints a line when the install directory is not on your PATH. install.ps1 adds its directory to your user PATH; open a new terminal to pick it up.

Updates

Once a day, a run in a terminal asks GitHub for the newest downloader-cli release. When it is newer than the running version, the run ends with a notice and the command that installs it. The check gives up after 1.5 seconds, and runs with --json, --help or --version skip it. DOWNLOADER_NO_UPDATE_CHECK=1 turns it off.

Library

To resolve posts from your own code, install the library instead:

npm install @totallynotdavid/downloader

Download posts

Download a post

downloader https://youtu.be/dQw4w9WgXcQ -o videos

downloader <url> resolves the post and saves each media item into the directory given by -o, or the current directory. A file that already exists is skipped. A post the history records with its files still in that directory is skipped before any request; another directory gets a copy. A download is written to <name>.part and renamed when complete. A failed download keeps its .part, and the next run asks the server for the rest; a server that cannot send a range sends the whole file again. When the media host refuses an expired URL, the post is resolved once more. A download fails when the server sends nothing for 30 seconds.

Download several posts

downloader https://www.instagram.com/p/Df147tCiAyB/ https://youtu.be/dQw4w9WgXcQ
downloader - < urls.txt

Each URL is downloaded in turn. - reads URLs from stdin, one per line, and skips blank lines and lines that start with #. The first download starts before stdin ends.

A post that fails to resolve or download is reported, and the rest still download; the command then exits 1. A block, a rate limit or a refused session stops the run, since every later post would fail the same way.

Pick posts from an account

downloader @natgeo
downloader https://www.instagram.com/natgeo/
downloader https://www.facebook.com/natgeo

@user and an Instagram profile URL list an Instagram account. A Facebook page or profile URL lists that account: facebook.com/<name>, a tab such as /<name>/videos, /profile.php?id=<id> or /people/<name>/<id>. A post, photo or video URL downloads that post instead. Facebook lists only posts with a photo or video of their own; shares and text posts are left out.

In a terminal this opens a checkbox list of the newest posts. “Load more posts…” fetches the next page and keeps what is already checked. Only the checked posts are resolved and downloaded.

Without a terminal, or with --json, choose the posts with a flag:

FlagDownloads
--allEvery post.
--limit <n>The newest n posts.
--pick <list>Posts by number, as --list prints them: 1,3,5-8.
--listNothing. Prints the newest posts with their numbers and exits.

The command fails with a usage error when none of them is given and no picker can open.

--type and --author narrow the listing before any of these apply, so --list numbers, --pick and --limit count only matching posts. --type takes photo, video or album; an album holding a video is still an album. --author takes account names, with or without @. Both take a comma list. A filter that matches rarely reads many pages before the first post shows.

downloader https://www.instagram.com/<you>/saved/ --all --type video
downloader https://www.instagram.com/<you>/saved/ --list --author natgeo,nasa

--all and --limit download each page of posts as it arrives, so the first files land before the account is fully listed. A failed post is handled as in Download several posts.

Download your saved posts

downloader https://www.instagram.com/<you>/saved/all-posts/ --all -o saved

instagram.com/<you>/saved/ and its all-posts tab list the posts the account saved, newest save first, with the same picker and flags as an account. Only the account itself can see them, so this target uses the saved session from the first request and fails with not_logged_in without one; see Log in. A URL that names a different account than the session fails with login_required. The saved feed already holds each post’s media, so a saved post downloads without a second request.

downloader https://www.instagram.com/<you>/saved/<name>/<id>/ --all -o trips

A named collection lists only its posts. Open the collection on the Saved page in the browser and copy its URL: the URL ends in the collection’s ID.

Keep post metadata

downloader @natgeo --limit 5 --metadata -o natgeo

--metadata appends one JSON line per downloaded post to posts.jsonl in the output directory. A line holds url, author, platform, description (the caption), timestamp in Unix seconds, the counts the platform returned (likes, comments, views, shares, reposts), files and saved_at. Counts change over time, and saved_at dates them. A post already in the download history is skipped and writes no line. get and account listings take the flag.

Log in to Instagram

downloader login

The command prints where to find the sessionid cookie, reads it from a hidden prompt, checks it with Instagram and saves it. Other inputs:

downloader login --browser firefox
downloader login --cookies cookies.txt
pbpaste | downloader login

--browser reads the Instagram cookies from a browser signed in to instagram.com: firefox, chrome, chromium, brave or edge. When several profiles are signed in, the one whose cookies changed last wins. Firefox works on every system. Chromium browsers work on Linux and macOS: on Linux the password comes from the keyring through secret-tool, on macOS from the Keychain, which may ask for permission. On Windows they encrypt cookies with a key only the browser can read, so use Firefox or --cookies there.

--cookies reads a Netscape cookies.txt or a JSON export from a browser extension. Piped input is the sessionid value.

Requests go out without the session first, and Facebook requests never use it. The saved session is used only when Instagram refuses an anonymous request, which happens on blocked networks and for private accounts. Saved posts and comments always use it. When Instagram refuses the saved session as well, the command fails with session_refused; run downloader login again. Treat the session as a password: anyone who holds it can act as the account.

downloader whoami prints the account of the saved session. downloader logout deletes it.

Read a post’s comments

downloader comments https://www.instagram.com/p/Df147tCiAyB/
downloader comments https://www.instagram.com/p/Df147tCiAyB/ --replies --json > comments.json

comments prints one line per comment, @author: text. Instagram shows comments only to a signed-in viewer, so the command uses the saved session and fails with not_logged_in without one. See Log in.

FlagEffect
--repliesReads the replies to each comment and indents them under it.
--limit <n>Stops after n top-level comments.

With --json, data holds the comments in the same order, each with id, author, text, timestamp, likes, replies and, for a reply, parent.

Script the command

downloader @natgeo --list --json

Progress, prompts and errors go to stderr. Data goes to stdout: the post list of --list, the account of whoami. --json prints one envelope on stdout and turns prompts off:

{ "ok": true, "data": [], "meta": {} }
{ "ok": false, "error": { "code": "not_logged_in", "message": "No Instagram session is saved", "hint": "Run downloader login." } }

For several URLs and for an account, meta.failed lists each post that failed with its url, code and message. For an account, meta.user names the account and meta.platform is instagram or facebook.

An error names the host that failed, never the full URL: media URLs carry signed tokens. A site that wants a signed-in user fails with login_required, and one that refuses the request fails with refused.

NO_COLOR turns colors off. --debug, or DOWNLOADER_DEBUG=1, prints each request as method, host, path, status and time, without the query string. A prompt opens only when stdin and stderr are terminals and CI is unset.

Exit codes

CodeMeaning
0Success.
1A request failed: network, block, missing post, parse error.
2Usage error or unsupported URL.
130The prompt was cancelled.

Config directory

The tool keeps config.json, auth.json and history.jsonl in $XDG_CONFIG_HOME/downloader, which defaults to ~/.config/downloader, or %APPDATA%\downloader on Windows. DOWNLOADER_CONFIG_DIR overrides the path. auth.json holds the session with mode 0600. history.jsonl holds one line per downloaded post: its URL, its files and the time.

Serve

downloader serve

serve answers JSON-line requests on stdin and writes replies and events on stdout, one JSON object per line. A desktop app runs it as a child process and drives the downloads through it. It exits when stdin closes and every request has answered. Diagnostics go to stderr.

> {"id":1,"method":"resolve","params":{"url":"https://www.instagram.com/p/Df147tCiAyB/"}}
< {"event":"ready","data":{"protocol":1}}
< {"id":1,"ok":true,"data":{"url":"…","platform":"instagram","items":[…]}}

Messages

The first line out is {"event":"ready","data":{"protocol":1}}. A client refuses a server whose protocol number it does not know.

A request is {id, method, params}. The id is any JSON value the client picks and comes back on the reply. Requests run concurrently, so replies arrive in the order they finish.

A reply is {id, ok: true, data} or {id, ok: false, error: {code, message}}. The codes are the ones --json prints (see Script the command), plus bad_request for a line that is not JSON (its id is null) and no_method for an unknown method.

An event is {event, data}.

Methods

MethodParamsData
resolve{url}{url, platform, items: [{type, url, filename}]}
list{target}{listing, name, platform, posts, more}
more{listing}{posts, more}
download{url, folder}{url, files, skipped}
history{limit?}[{url, files, at}], newest first, 100 by default
session{}the saved account, "" without a name, or null
login{pasted}{username}
logout{}null

list takes the same targets as the command line: @user, an Instagram profile URL or a Facebook page URL. It returns the first page and a listing number; more returns the next page of that listing. Each post carries saved, true when the history holds it with its files on disk.

download saves one post into folder, which must be an absolute path. It answers when the post is saved. Downloads run one at a time in the order they arrive. A post the history holds with its files in that folder is skipped before any request, and the reply says skipped: true. Each saved post is added to the history the command line reads.

login takes a pasted sessionid or cookie export, checks it with Instagram and saves it where downloader login does.

Events

progress reports bytes of one file of a download:

{
  "event": "progress",
  "data": {
    "id": 3,
    "filename": "Df147tCiAyB.jpg",
    "received": 40960,
    "total": 182044
  }
}

id is the download request’s id. total is absent when the site does not send a length.

Using the library

resolve(url, options?) returns direct media URLs, the headers needed to fetch them, and metadata for one public post. It does not download the media.

import { resolve } from "@totallynotdavid/downloader";

const result = await resolve("https://www.instagram.com/p/DcepzLhTqxC/");
console.log(result.meta.author, result.urls.length);

The result

The public types are declared in src/types.ts.

type MediaResult = {
  urls: MediaItem[];
  headers: Record<string, string>;
  meta: {
    title: string;
    author: string;
    platform: string;
    description?: string;
    thumbnail?: string;
    views?: number;
    likes?: number;
    comments?: number;
    shares?: number;
    reposts?: number;
    timestamp?: number;
  };
};

type MediaItem = {
  type: "image" | "video" | "audio";
  url: string;
  filename: string;
};

title, author, and platform are always present. Other metadata fields are present only when the platform returns them. timestamp is Unix time in seconds. filename is a suggested name, not a guarantee about the media format.

A post can return more than one item. Galleries and carousels return one item per image. Facebook can return separate video and audio items. YouTube can return separate video-only and audio-only items when no single stream has the best video quality. Reddit returns separate video and audio items when its embed page lists no combined MP4.

A Reddit post that links to another supported site returns that site’s result.

Download the media

Pass result.headers to each media request. Request YouTube media in Range chunks of at most 10 MiB: its media server sends about 30 KB/s for a request without a Range header or with a larger range.

import { writeFile } from "node:fs/promises";
import { resolve } from "@totallynotdavid/downloader";

const result = await resolve("https://www.instagram.com/p/DcepzLhTqxC/");

for (const item of result.urls) {
  const response = await fetch(item.url, { headers: result.headers });
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${item.url}`);
  await writeFile(item.filename, Buffer.from(await response.arrayBuffer()));
}

Options

await resolve(url, {
  timeout: 15_000,
  headers: { "Accept-Language": "es-PE" },
});
OptionMeaning
timeoutMilliseconds allowed for each request. The default is 10,000. YouTube uses 15,000 for its requests when no value is supplied.
headersAdditional request headers. Extractors that require an app-specific user agent may override it.
cookiesCookies by name. Only Instagram reads them, and only when they hold a sessionid. See Instagram.

Some posts require several requests. timeout applies to each request, not to the complete resolve call.

Supported URLs

The router removes a leading www. and matches the remaining hostname. It also accepts any Pinterest subdomain. Other hostnames must match the table.

PlatformHostnamesURL examples
Instagraminstagram.com/p/<code>/, /reel/<code>/, /tv/<code>/
TikToktiktok.com, vm., vt./@user/video/<id>, /@user/photo/<id>, or a share link
Twitter/Xtwitter.com, x.com/<user>/status/<id>
YouTubeyoutube.com, youtu.be/watch?v=<id>, /shorts/<id>, /embed/<id>, or a youtu.be/<id> URL
Redditreddit.com, redd.it/r/<sub>/comments/<id>/, /r/<sub>/s/<token>, /gallery/<id>, or a redd.it/<id> URL
Facebookfacebook.com, m., web., fb.com, fb.watchA post, photo, or video URL; see Facebook
Imgurimgur.com, i.imgur.comAn image, album, or gallery URL
Pinterestpinterest.com, *.pinterest.com/pin/<id>/ or /pin/<slug>--<id>/

resolve accepts a post URL, not an account URL. Use listInstagramPosts for Instagram accounts and listFacebookPosts for Facebook pages and profiles.

Request failures

The call can reject with a TypeError for an invalid URL, or with one of the exported error classes. See Errors for handling them.

Instagram

The package has three Instagram entry points. resolve returns media for one post. listInstagramPosts returns a page of an account’s posts. getInstagramViewer checks a session. The first two use Instagram’s logged-out web endpoint and require no login. With a sessionid cookie they sign in instead; see Signed-in requests.

Resolve a post

resolve accepts /p/<code>/, /reel/<code>/, and /tv/<code>/ URLs.

import { resolve } from "@totallynotdavid/downloader";

const result = await resolve("https://www.instagram.com/p/DcepzLhTqxC/");

The result contains the post’s media at the first available full-resolution candidate. A carousel has one item per child. result.headers contains the User-Agent and Referer needed when fetching Instagram media.

An account URL or a URL without one of the supported post paths rejects with a ParseError.

List an account’s posts

import { listInstagramPosts } from "@totallynotdavid/downloader";

const first = await listInstagramPosts("uni_oficial");
for (const post of first.posts) {
  console.log(post.shortcode, post.type, post.author);
}

if (first.cursor) {
  const next = await listInstagramPosts("uni_oficial", {
    cursor: first.cursor,
  });
}

listInstagramPosts(username, options?) returns up to 12 posts in grid order. The result type is exported from the package root:

type ListPostsOptions = ResolveOptions & {
  cursor?: string;
  detail?: boolean;
};

type Post = {
  shortcode: string;
  url: string;
  author: string;
  caption?: string;
  type: "image" | "video" | "carousel";
  thumbnail: string;
  media?: MediaItem[];
  timestamp?: number;
  likes?: number;
  comments?: number;
  views?: number;
  resolved?: MediaResult;
};

type PostPage = {
  posts: Post[];
  cursor?: string;
};

Username and cursor

A leading @ is optional. The username that remains must match [A-Za-z0-9._]{1,30}. Invalid usernames and malformed cursors reject before a request.

Pass cursor unchanged to fetch the next page. It is absent on the last page. A cursor works only in the mode that returned it: a signed-out cursor with a sessionid, or a signed-in cursor without one, rejects with a ParseError. An unknown account rejects with a NetworkError whose statusCode is 404. An account with no posts returns { posts: [] }.

url is an Instagram reel URL for reels and a post URL for other items. author is the first author returned for that grid item, so a collab post can belong to another account. caption is absent when the post has no caption. thumbnail is the cover image URL. likes, comments and views are present when the listing returns them; views is the play count. resolved is the MediaResult that resolve(url) would return, set when the listing already holds the full media, so a caller can download the post without resolving it again.

Detail

The regular account response contains no media URLs or timestamp. Set detail: true to fill media with the same items returned by resolve and to fill timestamp with Unix seconds. This adds one request per post. A failure rejects the whole page.

List saved posts

const page = await listInstagramSaved("me", { cookies, cursor, detail });

listInstagramSaved lists the posts the session’s account saved, newest save first, 21 to a page, through GET /api/v1/feed/saved/posts/?max_id=<cursor>. It returns the same PostPage as listInstagramPosts. Only the account itself can see its saved posts, so a sessionid is required: without one it rejects with a BlockedError before any request. The first page checks the username against the session’s viewer and rejects with a NetworkError whose statusCode is 401 when they differ. The feed returns full media nodes, so every post with media carries resolved and detail: true costs no extra request. The feed gives no comment count, so comments is absent.

const page = await listInstagramSaved("me", { cookies, collection: "179" });

collection lists one named collection instead, through GET /api/v1/feed/collection/<id>/posts/?max_id=<cursor>, 12 to a page, with the same checks and post shape. The ID is the number that ends the collection’s URL, instagram.com/<you>/saved/<name>/<id>/; an ID that is not a number rejects with a ParseError before any request.

List comments

const page = await listInstagramComments(url, { cookies, cursor });
const replies = await listInstagramReplies(url, comment.id, {
  cookies,
  cursor,
});

listInstagramComments lists a post’s top-level comments, 15 to a page, through GET /api/v1/media/<id>/comments/?min_id=<cursor>. Instagram answers this endpoint only for a signed-in viewer, so a sessionid is required: without one it rejects with a BlockedError before any request. A URL without a post shortcode rejects with a ParseError. A page holds comments and, while more remain, the cursor for the next page.

Each Comment holds id, author (the username), text, timestamp in Unix seconds, likes and replies, the reply count. listInstagramReplies lists the replies to one comment through GET /api/v1/media/<id>/comments/<comment id>/child_comments/?min_id=<cursor>, about 9 to a page, with the same checks. A reply carries parent, the ID of the comment it answers.

Anonymous access

Instagram can block anonymous requests from datacenter IPs. A block is reported as BlockedError; retrying from the same IP rarely helps.

The library uses the runtime’s global fetch. Configure a residential proxy in the runtime when it supports proxy environment variables. Node 24 or later requires NODE_USE_ENV_PROXY=1 for that configuration.

See Errors for all Instagram block cases.

Signed-in requests

A blocked IP or a private account needs a session. Pass the browser’s Instagram cookies as cookies; the sessionid cookie alone is enough. The other cookie the API needs, ds_user_id, is read from the start of the sessionid.

import {
  getInstagramViewer,
  listInstagramPosts,
  resolve,
} from "@totallynotdavid/downloader";

const cookies = { sessionid: process.env.IG_SESSIONID ?? "" };

const viewer = await getInstagramViewer({ cookies });
console.log(`signed in as @${viewer.username}`);

const page = await listInstagramPosts("natgeo", { cookies, detail: true });
const post = await resolve(page.posts[0].url, { cookies });

getInstagramViewer(options) returns { id, username } for the session. It makes one request and is the cheapest way to check that a session still works.

Signed in, listInstagramPosts reads the account’s grid the way the web app does, and detail: true adds no request because the signed-in grid already carries the media. resolve reads the post from the v1 media API.

A session that is missing, signed out or expired rejects with a BlockedError. Its statusCode is 401, or the redirect status when Instagram sends the request to the login page. Treat a session as a password: anyone who holds the sessionid can act as the account.

Facebook

resolve returns media for one Facebook post, photo or video. listFacebookPosts returns a page of a page’s or profile’s public posts. Both read the public web pages and send no cookies.

Resolve a post

resolve fetches the page at the URL and reads the post it shows. It accepts facebook.com, m.facebook.com, web.facebook.com, fb.com and fb.watch URLs. The tests cover these forms:

  • A post: /<page>/posts/<id>
  • A photo: /photo/?fbid=<id>
  • A video: /watch/?v=<id>
import { resolve } from "@totallynotdavid/downloader";

const result = await resolve(
  "https://www.facebook.com/1551UNMSM/posts/1582271390604244",
);

A post with several photos is a carousel with one item per photo. The post page embeds only the first few; the rest come from the post’s media set page and one page per photo, so a 10-photo post costs about 7 requests.

A share link (/share/p/…, /share/v/…) answers with a login page and rejects with a NetworkError of status 401. Open the link in a browser and pass the address it lands on. A deleted or private post rejects with status 404.

List an account’s posts

import { listFacebookPosts } from "@totallynotdavid/downloader";

const first = await listFacebookPosts("1551UNMSM");
for (const post of first.posts) {
  console.log(post.type, post.url, post.caption);
}

if (first.cursor) {
  const next = await listFacebookPosts("1551UNMSM", { cursor: first.cursor });
}

listFacebookPosts(account, options?) returns posts newest first in the Post and PostPage shapes described in Instagram. The account is one of:

  • a page name such as 1551UNMSM, or a numeric profile ID
  • a profile URL: https://www.facebook.com/1551UNMSM, a tab such as /1551UNMSM/videos, /profile.php?id=<id>, or /people/<name>/<id>

Each Post.url is an address resolve accepts. A carousel links to its post, a photo to /photo/?fbid=, and a video to /watch/?v=. Post.shortcode is the post ID.

A page holds up to 12 posts. The timeline returns 3 stories per request, so a page costs up to 4 requests, plus one for the profile on the first page. Stories without a photo or video of their own, such as shares and text posts, are left out, so a page can hold fewer than 12. The cursor has the form <user id>:<timeline cursor>; pass it back unchanged.

Errors

CaseError
A malformed account or cursorParseError, before any request
An account shown only to signed-in usersNetworkError with status 401
An unknown accountNetworkError with status 404
A timeline error or unexpected replyParseError

Errors

resolve, listInstagramPosts and listFacebookPosts can reject with one of the four error classes exported from the package root. Their implementations are in src/errors.ts.

Error
├── PlatformNotSupportedError
├── NetworkError            statusCode?: number
│   └── BlockedError
└── ParseError              platform: string
ClassMeaningExtra field
PlatformNotSupportedErrorNo extractor matches the URL hostname.
NetworkErrorA request failed or the target was not found.statusCode?: number
BlockedErrorInstagram refused the request or the session.statusCode?: number
ParseErrorThe URL or response could not be interpreted.platform: string

BlockedError extends NetworkError. Check it before NetworkError when the response matters.

A string that is not a URL rejects with the TypeError thrown by new URL. The library does not wrap that error.

Network errors

NetworkError.statusCode is set when the server answered with a non-2xx status. A timeout uses status 408. A failure before a response, such as a DNS error, has no status. Instagram uses status 404 for a missing post or account.

Instagram uses BlockedError for redirects to login, login-required responses, rate limits, and posts hidden from logged-out visitors. With cookies, it also reports a missing, signed-out or expired session. Other platforms report an HTTP refusal as NetworkError.

Parse errors

ParseError.message starts with [<platform>], and platform contains that platform name. An extractor uses it when the URL lacks an identifier, the response has an unexpected shape, or no media is available. YouTube also uses it when the video is not playable.

Handling errors

import {
  resolve,
  BlockedError,
  NetworkError,
  ParseError,
  PlatformNotSupportedError,
} from "@totallynotdavid/downloader";

try {
  await resolve(url);
} catch (error) {
  if (error instanceof PlatformNotSupportedError) {
    console.error(`Unsupported platform: ${error.message}`);
  } else if (error instanceof BlockedError) {
    // Change the runtime's network path or stop retrying.
  } else if (error instanceof NetworkError) {
    // Inspect error.statusCode when it is present.
  } else if (error instanceof ParseError) {
    // The post is unusable, or the extractor needs an update.
  } else {
    throw error;
  }
}

Writing an extractor

An extractor turns one platform’s post URL into a MediaResult. Each platform has a module in src/extractors/, and src/router.ts selects one by hostname.

resolve(url) -> route(url) -> extractor(url, options) -> MediaResult

Add an extractor

  1. Create src/extractors/<platform>.ts.
  2. Register each supported hostname in src/router.ts.
  3. Add fixtures and cassettes. See Tests and cassettes.
  4. Add the URL forms to Using the library.

Extractor shape

An extractor default-exports a function that accepts the URL and ResolveOptions.

import { http_get } from "../http.ts";
import { NetworkError, ParseError } from "../errors.ts";
import type { MediaResult, ResolveOptions } from "../types.ts";

export default async function resolve(
  url: string,
  options: ResolveOptions,
): Promise<MediaResult> {
  const id = url.match(/\/post\/(\d+)/)?.[1];
  if (!id) throw new ParseError("Could not parse post id", "example");

  try {
    const response = await http_get(
      `https://api.example.com/posts/${id}`,
      options,
    );
    const data = (await response.json()) as {
      video_url?: string;
      title?: string;
      author?: string;
    };

    if (!data.video_url) throw new ParseError("No media found", "example");

    return {
      urls: [
        { type: "video", url: data.video_url, filename: `example-${id}.mp4` },
      ],
      headers: {},
      meta: {
        title: data.title || "Example post",
        author: data.author || "Unknown",
        platform: "example",
      },
    };
  } catch (error: unknown) {
    if (error instanceof NetworkError || error instanceof ParseError) {
      throw error;
    }
    const message = error instanceof Error ? error.message : "Unknown error";
    throw new ParseError(message, "example");
  }
}

Register the extractor with the hostname written without www.. The router removes that prefix before it looks up the hostname.

import example from "./extractors/example.ts";

const EXTRACTORS = new Map<string, ExtractorFn>([
  // ...
  ["example.com", example],
  ["ex.am", example],
]);

Contracts

  • Use http_get and http_post from src/http.ts. Pass options through so the caller’s timeout and headers apply.
  • Throw ParseError with the platform name when the URL or response is not usable. Rethrow NetworkError and ParseError; wrap other errors in a ParseError.
  • Put CDN request headers in result.headers. Use {} when no headers are required.
  • Use <platform>-<id>.<ext> filenames. Add -1, -2 for additional media, and -video or -audio for separate tracks. Facebook uses the fb- prefix.
  • Assign optional metadata only when the platform returned a value. The exactOptionalPropertyTypes setting does not allow undefined values in optional fields.
  • Keep platform extractors independent. The Instagram modules share their GraphQL client and media parser.

Code style is in Contributing.

Tests and cassettes

The replay tests run every extractor against recorded responses. bun run test does not contact a platform. Recording is the separate workflow that refreshes those responses from live platforms.

tests/fixtures.ts -> runner -> transport -> cassette -> snapshot

Commands

Run these in packages/core.

CommandPurpose
bun run testReplay cassettes and assert snapshots.
bun run test:updateAccept intended snapshot changes.
bun run record [platform]Refresh cassettes from a live platform.
bun run eval [platform]Print fixture results. See Live eval.
bun run eval:liveCheck the Instagram fixtures against the live site. See Live eval.

The optional platform filters for record and eval match the keys in tests/fixtures.ts. The test command runs the files in tests/replay/.

Review a parser change

  1. Change the extractor.
  2. Run bun run test.
  3. Read the snapshot diff.
  4. If the change is intended, run bun run test:update.

The snapshot is the review artifact. Replay separates a parser change from a platform response change.

Fixtures

tests/fixtures.ts holds two fixture sets:

  • SAMPLES maps each platform to named post URLs.
  • ACCOUNTS maps Instagram accounts to page counts and optional detail mode.

Add a post to SAMPLES, or an account to ACCOUNTS, before recording it. Then run bun run record <platform>, inspect the result with bun run eval <platform>, and run bun run test:update when the snapshot is correct.

Replay transport

tests/support/transport.ts replaces globalThis.fetch in replay and record modes.

extractor -> src/http.ts -> fetch -> transport
                                     |- replay: read a cassette, no network
                                     |- record: fetch live data, write a cassette

A cassette is tests/cassettes/<host>/<method>-<hash>.json.gz. The hash uses the method, URL, and request body, so changing a request body misses the old cassette. Replay returns a synthetic 504 for a missing cassette instead of fetching it.

Recording drops Set-Cookie. Snapshots remove query strings so signed CDN parameters do not create noise.

Record

Recording requires either EVAL_PROXY_URL or Geonode credentials. The first matching setting wins:

SettingEffect
EVAL_PROXY_URL=http://user:pass@host:portUse that proxy.
EVAL_PROXY_URL=directRecord without a proxy when the host has a clean residential IP.
GEONODE_USERNAME and GEONODE_PASSWORDUse the Geonode residential gateway.

The record script loads a repository-root .env file. It chooses one sticky residential exit for the process. Reddit is recorded directly because it answers the residential exits with 403.

Without a proxy setting, recording stops before its first request:

$ bun run record
error: GEONODE_USERNAME is required for this command. Set it in .env or the environment.

Inspect a cassette

A cassette is gzipped JSON. The response body is base64 in body_b64.

zcat tests/cassettes/api.vxtwitter.com/GET-56a35b1c45644f82.json.gz \
  | jq -r .body_b64 | base64 -d | jq '{tweetID, mediaURLs}'

Live eval

scripts/eval.ts runs the fixtures and prints each result. Replay is the default. The --live flag sends requests to platforms.

CommandMode
bun run eval [platform]Replays committed cassettes without network access.
bun run eval:liveRuns the Instagram fixtures against the live site.

Output

Each post fixture prints a status, item count, item types, elapsed time, and metadata.

OK   instagram/single_image              1[image] 241ms
     title=¡Continuamos con la segunda charla d... author=gft.unmsm ...

Each account fixture prints its page sizes and then one line per post.

OK   instagram/images                   gft.unmsm 12 posts, more 1335ms
     DcepzLhTqxC  image    gft.unmsm        2026-08-25T21:56:15.000Z media=1 ¡Continuamos con la segunda charla d

A failed fixture prints FAIL, the error class, and its message.

FAIL instagram/video_reel               NetworkError: Unable to connect. Is the computer able to access the url? []

Exit status

Replay eval always exits 0, so inspect its FAIL lines. Live eval exits 1 when one or more fixtures fail and prints the count of failed checks.

Check Instagram queries

Instagram can retire the persisted query IDs used by the library. A retired ID causes a ParseError that says the query ID may be stale. Run bun run eval:live to check the post and account fixtures against Instagram.

The live check does not configure a proxy. From a datacenter IP, a BlockedError means the network path was refused, not that the query IDs are stale. Configure the runtime’s proxy as described in Instagram, or run the check from a residential connection.

The check makes one request per post fixture. An account fixture with detail: true adds one request per listed post. CI does not run this live check.

Architecture

The package accepts a public post URL and returns a normalized MediaResult. Paths are relative to packages/core. The public entry points are exported from src/index.ts.

Request path

resolve(url, options)
  -> route(url)
  -> platform extractor
  -> http_get/http_post
  -> global fetch
  -> MediaResult

src/resolve.ts selects an extractor through src/router.ts. The router removes a leading www. and matches the hostname. Pinterest also accepts subdomains. An unmatched hostname produces PlatformNotSupportedError.

The extractor parses the platform response into the common types in src/types.ts. src/http.ts supplies default request headers, applies the per-request timeout, and turns failed HTTP responses into NetworkError.

Source map

PathResponsibility
src/index.tsPublic functions, types, and error exports.
src/resolve.tsResolves one post through the router.
src/router.tsMaps supported hostnames to extractors.
src/http.tsGET and POST wrappers around fetch.
src/errors.tsPublic error classes.
src/types.tsPublic result, media, and Instagram listing types.
src/extractors/*.tsPlatform-specific URL parsing, requests, and response mapping.
scripts/eval.tsPrints fixture results for local inspection.
tests/fixtures.tsPost and account inputs used by replay tests and eval.
tests/support/transport.tsReplays or records HTTP responses for tests.
tests/replay/Behavioral tests for extractors, Instagram listing, and recording.

Instagram listing

src/extractors/instagram-posts.ts uses the Instagram extractor’s shared media lookup for detail: true. It validates the username before the first request, returns pages of up to 12 posts, and uses the returned cursor for later pages.

src/extractors/instagram-session.ts holds the signed-in path. It reads the request tokens and the viewer from the signed-in home page, builds the cookie and same-origin headers, and reads a post from the v1 media API. The listing and the post extractor switch to it when the options carry a sessionid cookie.

Build boundary

bunup.config.ts builds src/index.ts into dist/index.js and dist/index.d.ts. The package publishes dist, readme.md, and LICENSE, as declared in package.json.