Full Code of imputnet/cobalt for AI

main a62d73499348 cached
413 files
1.0 MB
272.4k tokens
270 symbols
1 requests
Download .txt
Showing preview only (1,156K chars total). Download the full file or copy to clipboard to get everything.
Repository: imputnet/cobalt
Branch: main
Commit: a62d73499348
Files: 413
Total size: 1.0 MB

Directory structure:
gitextract_xvmn6t33/

├── .deepsource.toml
├── .dockerignore
├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug-main-instance.yml
│   │   ├── bug-report.yml
│   │   ├── config.yml
│   │   ├── feature-request.yml
│   │   ├── hosting-help.yml
│   │   └── service-request.yml
│   ├── test.sh
│   └── workflows/
│       ├── codeql.yml
│       ├── docker-develop.yml
│       ├── docker-staging.yml
│       ├── docker.yml
│       ├── fast-forward.yml
│       ├── test-services.yml
│       └── test.yml
├── .gitignore
├── CONTRIBUTING.md
├── Dockerfile
├── LICENSE
├── README.md
├── api/
│   ├── LICENSE
│   ├── README.md
│   ├── package.json
│   └── src/
│       ├── cobalt.js
│       ├── config.js
│       ├── core/
│       │   ├── api.js
│       │   ├── env.js
│       │   └── itunnel.js
│       ├── misc/
│       │   ├── cluster.js
│       │   ├── console-text.js
│       │   ├── crypto.js
│       │   ├── file-watcher.js
│       │   ├── language-codes.js
│       │   ├── load-from-fs.js
│       │   ├── randomize-ciphers.js
│       │   ├── run-test.js
│       │   └── utils.js
│       ├── processing/
│       │   ├── cookie/
│       │   │   ├── cookie.js
│       │   │   └── manager.js
│       │   ├── create-filename.js
│       │   ├── helpers/
│       │   │   └── youtube-session.js
│       │   ├── match-action.js
│       │   ├── match.js
│       │   ├── request.js
│       │   ├── schema.js
│       │   ├── service-alias.js
│       │   ├── service-config.js
│       │   ├── service-patterns.js
│       │   ├── services/
│       │   │   ├── bilibili.js
│       │   │   ├── bluesky.js
│       │   │   ├── dailymotion.js
│       │   │   ├── facebook.js
│       │   │   ├── instagram.js
│       │   │   ├── loom.js
│       │   │   ├── newgrounds.js
│       │   │   ├── ok.js
│       │   │   ├── pinterest.js
│       │   │   ├── reddit.js
│       │   │   ├── rutube.js
│       │   │   ├── snapchat.js
│       │   │   ├── soundcloud.js
│       │   │   ├── streamable.js
│       │   │   ├── tiktok.js
│       │   │   ├── tumblr.js
│       │   │   ├── twitch.js
│       │   │   ├── twitter.js
│       │   │   ├── vimeo.js
│       │   │   ├── vk.js
│       │   │   ├── xiaohongshu.js
│       │   │   └── youtube.js
│       │   └── url.js
│       ├── security/
│       │   ├── api-keys.js
│       │   ├── jwt.js
│       │   ├── secrets.js
│       │   └── turnstile.js
│       ├── store/
│       │   ├── base-store.js
│       │   ├── memory-store.js
│       │   ├── redis-ratelimit.js
│       │   ├── redis-store.js
│       │   └── store.js
│       ├── stream/
│       │   ├── ffmpeg.js
│       │   ├── internal-hls.js
│       │   ├── internal.js
│       │   ├── manage.js
│       │   ├── proxy.js
│       │   ├── shared.js
│       │   └── stream.js
│       └── util/
│           ├── generate-jwt-secret.js
│           ├── test.js
│           └── tests/
│               ├── bilibili.json
│               ├── bsky.json
│               ├── dailymotion.json
│               ├── facebook.json
│               ├── instagram.json
│               ├── loom.json
│               ├── newgrounds.json
│               ├── ok.json
│               ├── pinterest.json
│               ├── reddit.json
│               ├── rutube.json
│               ├── snapchat.json
│               ├── soundcloud.json
│               ├── streamable.json
│               ├── tiktok.json
│               ├── tumblr.json
│               ├── twitch.json
│               ├── twitter.json
│               ├── vimeo.json
│               ├── vk.json
│               ├── xiaohongshu.json
│               └── youtube.json
├── docs/
│   ├── api-env-variables.md
│   ├── api.md
│   ├── examples/
│   │   ├── cookies.example.json
│   │   └── docker-compose.example.yml
│   ├── protect-an-instance.md
│   └── run-an-instance.md
├── package.json
├── packages/
│   ├── api-client/
│   │   ├── .gitignore
│   │   ├── .prettierignore
│   │   ├── .prettierrc
│   │   ├── LICENSE
│   │   ├── package.json
│   │   └── tsconfig.json
│   └── version-info/
│       ├── index.d.ts
│       ├── index.js
│       └── package.json
├── pnpm-workspace.yaml
└── web/
    ├── .gitignore
    ├── .npmrc
    ├── LICENSE
    ├── README.md
    ├── changelogs/
    │   ├── 10.0.md
    │   ├── 10.1.md
    │   ├── 10.3.md
    │   ├── 10.5.md
    │   ├── 11.0.md
    │   ├── 11.2.md
    │   ├── 2.0.md
    │   ├── 2.2.5.md
    │   ├── 2.2.6.md
    │   ├── 2.2.8.md
    │   ├── 2.2.9.md
    │   ├── 2.2.md
    │   ├── 3.0.md
    │   ├── 3.1.md
    │   ├── 3.2.md
    │   ├── 3.4.md
    │   ├── 3.5.2.md
    │   ├── 3.5.4.md
    │   ├── 3.5.md
    │   ├── 3.6.3.md
    │   ├── 3.6.md
    │   ├── 3.7.md
    │   ├── 4.0.md
    │   ├── 4.1.md
    │   ├── 4.2.md
    │   ├── 4.3.2.md
    │   ├── 4.3.md
    │   ├── 4.4.md
    │   ├── 4.5.md
    │   ├── 4.6.md
    │   ├── 4.7.md
    │   ├── 4.8.md
    │   ├── 5.0.md
    │   ├── 5.1.md
    │   ├── 5.2.md
    │   ├── 5.3.md
    │   ├── 5.4.md
    │   ├── 6.0.md
    │   ├── 6.2.md
    │   ├── 7.0.md
    │   ├── 7.1.md
    │   ├── 7.11.md
    │   ├── 7.13.md
    │   ├── 7.14.md
    │   ├── 7.3.md
    │   ├── 7.4.md
    │   ├── 7.5.md
    │   ├── 7.6.md
    │   ├── 7.7.md
    │   ├── 7.8.md
    │   └── 7.9.md
    ├── eslint.config.js
    ├── i18n/
    │   ├── en/
    │   │   ├── a11y/
    │   │   │   ├── dialog.json
    │   │   │   ├── donate.json
    │   │   │   ├── general.json
    │   │   │   ├── queue.json
    │   │   │   ├── save.json
    │   │   │   └── tabs.json
    │   │   ├── about/
    │   │   │   ├── credits.md
    │   │   │   ├── general.md
    │   │   │   ├── privacy.md
    │   │   │   └── terms.md
    │   │   ├── about.json
    │   │   ├── button.json
    │   │   ├── dialog.json
    │   │   ├── donate.json
    │   │   ├── error/
    │   │   │   ├── api.json
    │   │   │   └── queue.json
    │   │   ├── error.json
    │   │   ├── general.json
    │   │   ├── notification.json
    │   │   ├── queue.json
    │   │   ├── receiver.json
    │   │   ├── remux.json
    │   │   ├── save.json
    │   │   ├── settings.json
    │   │   ├── tabs.json
    │   │   └── updates.json
    │   ├── languages.json
    │   └── ru/
    │       ├── a11y/
    │       │   ├── dialog.json
    │       │   ├── donate.json
    │       │   ├── general.json
    │       │   ├── queue.json
    │       │   ├── save.json
    │       │   └── tabs.json
    │       ├── about/
    │       │   ├── credits.md
    │       │   ├── general.md
    │       │   ├── privacy.md
    │       │   └── terms.md
    │       ├── about.json
    │       ├── button.json
    │       ├── dialog.json
    │       ├── donate.json
    │       ├── error/
    │       │   ├── api.json
    │       │   └── queue.json
    │       ├── error.json
    │       ├── general.json
    │       ├── notification.json
    │       ├── queue.json
    │       ├── receiver.json
    │       ├── remux.json
    │       ├── save.json
    │       ├── settings.json
    │       ├── tabs.json
    │       └── updates.json
    ├── package.json
    ├── src/
    │   ├── app.css
    │   ├── app.d.ts
    │   ├── app.html
    │   ├── components/
    │   │   ├── about/
    │   │   │   └── AboutSupport.svelte
    │   │   ├── buttons/
    │   │   │   ├── ActionButton.svelte
    │   │   │   ├── SettingsButton.svelte
    │   │   │   ├── SettingsToggle.svelte
    │   │   │   ├── Switcher.svelte
    │   │   │   └── VerticalActionButton.svelte
    │   │   ├── changelog/
    │   │   │   ├── ChangelogEntry.svelte
    │   │   │   └── ChangelogEntryWrapper.svelte
    │   │   ├── dialog/
    │   │   │   ├── DialogBackdropClose.svelte
    │   │   │   ├── DialogButton.svelte
    │   │   │   ├── DialogButtons.svelte
    │   │   │   ├── DialogContainer.svelte
    │   │   │   ├── DialogHolder.svelte
    │   │   │   ├── NoScriptDialog.svelte
    │   │   │   ├── PickerDialog.svelte
    │   │   │   ├── PickerItem.svelte
    │   │   │   ├── SavingDialog.svelte
    │   │   │   ├── SavingTutorial.svelte
    │   │   │   └── SmallDialog.svelte
    │   │   ├── donate/
    │   │   │   ├── DonateAltItem.svelte
    │   │   │   ├── DonateBanner.svelte
    │   │   │   ├── DonateCardContainer.svelte
    │   │   │   ├── DonateOptionsCard.svelte
    │   │   │   ├── DonateShareCard.svelte
    │   │   │   └── DonationOption.svelte
    │   │   ├── icons/
    │   │   │   ├── Clipboard.svelte
    │   │   │   ├── Cobalt.svelte
    │   │   │   ├── CobaltQR.svelte
    │   │   │   ├── CobaltSticker.svelte
    │   │   │   ├── Imput.svelte
    │   │   │   ├── Music.svelte
    │   │   │   ├── Mute.svelte
    │   │   │   └── Sparkles.svelte
    │   │   ├── misc/
    │   │   │   ├── AboutPageWrapper.svelte
    │   │   │   ├── BetaTesters.svelte
    │   │   │   ├── BulletExplain.svelte
    │   │   │   ├── CopyIcon.svelte
    │   │   │   ├── DropReceiver.svelte
    │   │   │   ├── FileReceiver.svelte
    │   │   │   ├── Meowbalt.svelte
    │   │   │   ├── NotchSticker.svelte
    │   │   │   ├── OuterLink.svelte
    │   │   │   ├── Placeholder.svelte
    │   │   │   ├── PopoverContainer.svelte
    │   │   │   ├── SectionHeading.svelte
    │   │   │   ├── Skeleton.svelte
    │   │   │   ├── Toggle.svelte
    │   │   │   ├── Turnstile.svelte
    │   │   │   └── UpdateNotification.svelte
    │   │   ├── queue/
    │   │   │   ├── ProcessingQueue.svelte
    │   │   │   ├── ProcessingQueueItem.svelte
    │   │   │   ├── ProcessingQueueStub.svelte
    │   │   │   ├── ProcessingStatus.svelte
    │   │   │   └── ProgressBar.svelte
    │   │   ├── save/
    │   │   │   ├── CaptchaTooltip.svelte
    │   │   │   ├── Omnibox.svelte
    │   │   │   ├── OmniboxIcon.svelte
    │   │   │   ├── SupportedServices.svelte
    │   │   │   └── buttons/
    │   │   │       ├── ClearButton.svelte
    │   │   │       └── DownloadButton.svelte
    │   │   ├── settings/
    │   │   │   ├── ClearStorageButton.svelte
    │   │   │   ├── DataSettingsButton.svelte
    │   │   │   ├── FilenamePreview.svelte
    │   │   │   ├── ManageSettings.svelte
    │   │   │   ├── ResetSettingsButton.svelte
    │   │   │   ├── SettingsCategory.svelte
    │   │   │   ├── SettingsDropdown.svelte
    │   │   │   └── SettingsInput.svelte
    │   │   ├── sidebar/
    │   │   │   ├── CobaltLogo.svelte
    │   │   │   ├── Sidebar.svelte
    │   │   │   └── SidebarTab.svelte
    │   │   └── subnav/
    │   │       ├── PageNav.svelte
    │   │       ├── PageNavSection.svelte
    │   │       └── PageNavTab.svelte
    │   ├── fonts/
    │   │   └── noto-mono-cobalt.css
    │   ├── lib/
    │   │   ├── api/
    │   │   │   ├── api-url.ts
    │   │   │   ├── api.ts
    │   │   │   ├── safety-warning.ts
    │   │   │   ├── saving-handler.ts
    │   │   │   ├── server-info.ts
    │   │   │   ├── session.ts
    │   │   │   └── turnstile.ts
    │   │   ├── changelogs.ts
    │   │   ├── clipboard.ts
    │   │   ├── device.ts
    │   │   ├── download.ts
    │   │   ├── env.ts
    │   │   ├── haptics.ts
    │   │   ├── i18n/
    │   │   │   ├── locale.ts
    │   │   │   └── translations.ts
    │   │   ├── libav.ts
    │   │   ├── polyfills/
    │   │   │   ├── abortsignal-timeout.ts
    │   │   │   └── user-activation.ts
    │   │   ├── polyfills.ts
    │   │   ├── settings/
    │   │   │   ├── audio-sub-language.ts
    │   │   │   ├── defaults.ts
    │   │   │   ├── lazy-get.ts
    │   │   │   ├── migrate-v7.ts
    │   │   │   ├── migrate.ts
    │   │   │   └── validate.ts
    │   │   ├── state/
    │   │   │   ├── dialogs.ts
    │   │   │   ├── omnibox.ts
    │   │   │   ├── queue-visibility.ts
    │   │   │   ├── server-info.ts
    │   │   │   ├── settings.ts
    │   │   │   ├── task-manager/
    │   │   │   │   ├── current-tasks.ts
    │   │   │   │   └── queue.ts
    │   │   │   ├── theme.ts
    │   │   │   └── turnstile.ts
    │   │   ├── storage/
    │   │   │   ├── index.ts
    │   │   │   ├── memory.ts
    │   │   │   ├── opfs.ts
    │   │   │   └── storage.ts
    │   │   ├── subnav.ts
    │   │   ├── task-manager/
    │   │   │   ├── queue.ts
    │   │   │   ├── run-worker.ts
    │   │   │   ├── runners/
    │   │   │   │   ├── fetch.ts
    │   │   │   │   └── ffmpeg.ts
    │   │   │   ├── scheduler.ts
    │   │   │   └── workers/
    │   │   │       ├── fetch.ts
    │   │   │       └── ffmpeg.ts
    │   │   ├── types/
    │   │   │   ├── api.ts
    │   │   │   ├── changelogs.ts
    │   │   │   ├── dialog.ts
    │   │   │   ├── generic.ts
    │   │   │   ├── i18n.ts
    │   │   │   ├── libav.ts
    │   │   │   ├── meowbalt.ts
    │   │   │   ├── omnibox.ts
    │   │   │   ├── queue.ts
    │   │   │   ├── settings/
    │   │   │   │   ├── v2.ts
    │   │   │   │   ├── v3.ts
    │   │   │   │   ├── v4.ts
    │   │   │   │   ├── v5.ts
    │   │   │   │   └── v6.ts
    │   │   │   ├── settings.ts
    │   │   │   ├── task-manager.ts
    │   │   │   └── workers.ts
    │   │   ├── util.ts
    │   │   └── version.ts
    │   └── routes/
    │       ├── +error.svelte
    │       ├── +layout.svelte
    │       ├── +layout.ts
    │       ├── +page.svelte
    │       ├── _headers/
    │       │   └── +server.ts
    │       ├── about/
    │       │   ├── +layout.svelte
    │       │   ├── +page.svelte
    │       │   ├── [page]/
    │       │   │   ├── +page.svelte
    │       │   │   └── +page.ts
    │       │   └── community/
    │       │       └── +page.svelte
    │       ├── donate/
    │       │   └── +page.svelte
    │       ├── remux/
    │       │   └── +page.svelte
    │       ├── settings/
    │       │   ├── +layout.svelte
    │       │   ├── +page.svelte
    │       │   ├── accessibility/
    │       │   │   └── +page.svelte
    │       │   ├── advanced/
    │       │   │   └── +page.svelte
    │       │   ├── appearance/
    │       │   │   └── +page.svelte
    │       │   ├── audio/
    │       │   │   └── +page.svelte
    │       │   ├── debug/
    │       │   │   └── +page.svelte
    │       │   ├── instances/
    │       │   │   └── +page.svelte
    │       │   ├── local/
    │       │   │   └── +page.svelte
    │       │   ├── metadata/
    │       │   │   └── +page.svelte
    │       │   ├── privacy/
    │       │   │   └── +page.svelte
    │       │   └── video/
    │       │       └── +page.svelte
    │       ├── updates/
    │       │   └── +page.svelte
    │       └── version.json/
    │           └── +server.ts
    ├── static/
    │   └── manifest.json
    ├── svelte.config.js
    ├── tsconfig.json
    ├── vite.config.ts
    └── wrangler.jsonc

================================================
FILE CONTENTS
================================================

================================================
FILE: .deepsource.toml
================================================
version = 1

[[analyzers]]
name = "javascript"

  [analyzers.meta]
  environment = ["nodejs"]

================================================
FILE: .dockerignore
================================================
# OS directory info files
.DS_Store
desktop.ini

# node
node_modules

# static build
build

# secrets
.env
.env.*
!.env.example
cookies.json

# docker
docker-compose.yml

# ide
.vscode


================================================
FILE: .github/ISSUE_TEMPLATE/bug-main-instance.yml
================================================
name: main instance bug report
description: "report an issue with cobalt.tools or api.cobalt.tools"
labels: ["main instance issue"]
body:
  - type: textarea
    id: bug-description
    attributes:
      label: bug description
      description: "clear and concise description of what the issue is."
    validations:
      required: true
  - type: textarea
    id: repro-steps
    attributes:
      label: reproduction steps
      description: steps to reproduce the described behavior.
      placeholder: |
        1. go to '...'
        2. click on '....'
        3. download [media type] from [service]
        4. see error
    validations:
      required: true
  - type: textarea
    id: screenshots
    attributes:
      label: screenshots
      description: if applicable, add screenshots or screen recordings to support your explanation.
  - type: textarea
    id: links
    attributes:
      label: links
      description: if applicable, add links that cause the issue. more = better.
      render: shell
  - type: input
    id: platform
    attributes:
      label: platform information
      description: "the operating system, browser and their versions where you encounter the issue"
      placeholder: safari 7 on mac os x 10.8
    validations:
      required: true
  - type: textarea
    id: more-context
    attributes:
      label: additional context
      description: add any other context about the problem here if applicable.

================================================
FILE: .github/ISSUE_TEMPLATE/bug-report.yml
================================================
name: bug report
description: report a global issue with the cobalt codebase
labels: ["bug"]
body:
  - type: textarea
    id: bug-description
    attributes:
      label: bug description
      description: "clear and concise description of what the issue is."
    validations:
      required: true
  - type: textarea
    id: repro-steps
    attributes:
      label: reproduction steps
      description: steps to reproduce the described behavior.
      placeholder: |
        1. go to '...'
        2. click on '....'
        3. download [media type] from [service]
        4. see error
    validations:
      required: true
  - type: textarea
    id: screenshots
    attributes:
      label: screenshots
      description: if applicable, add screenshots or screen recordings to support your explanation.
  - type: textarea
    id: links
    attributes:
      label: links
      description: if applicable, add links that cause the issue. more = better.
      render: shell
  - type: input
    id: platform
    attributes:
      label: platform information
      description: "the operating system, browser and their versions where you encounter the issue"
      placeholder: safari 7 on mac os x 10.8
    validations:
      required: true
  - type: textarea
    id: more-context
    attributes:
      label: additional context
      description: add any other context about the problem here if applicable.

================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: false
contact_links:
  - name: discord community
    url: https://discord.gg/pQPt8HBUPu
    about: |
      ask questions and discuss cobalt with others at any time.
      usually faster responses as more people are there to help.

================================================
FILE: .github/ISSUE_TEMPLATE/feature-request.yml
================================================
name: feature request
description: suggest a feature for cobalt
labels: ["feature request"]
body:
  - type: markdown
    attributes:
      value: |
        thanks for taking the time to make a feature request!
        before you start, please make to read the "adding features or support for services" section of
        our [contributor guidelines](https://github.com/imputnet/cobalt/blob/main/CONTRIBUTING.md#adding-features-or-support-for-services) to make sure your request is a good fit for cobalt.
  - type: textarea
    id: feat-description
    attributes:
      label: describe the feature you'd like to see
      description: "clear and concise description of the feature you want to see in cobalt."
    validations:
      required: true
  - type: textarea
    id: more-context
    attributes:
      label: additional context
      description: add any other context about the problem here if applicable.

================================================
FILE: .github/ISSUE_TEMPLATE/hosting-help.yml
================================================
name: instance hosting help
description: ask any question regarding cobalt instance hosting
labels: ["instance hosting help"]
body:
  - type: textarea
    id: problem-description
    attributes:
      label: problem description
      description: |
        describe what issue you're having, clearly and concisely.
        support your description with screenshots/links/etc when needed.
    validations:
      required: true
  - type: textarea
    id: configuration
    attributes:
      label: your instance configuration
      description: |
        if applicable, add or describe your instance configuration (e.g. compose file) or any changes you made to it.
        please **do not share senstive information** such as secret keys or the contents of your cookies file!
      render: shell

================================================
FILE: .github/ISSUE_TEMPLATE/service-request.yml
================================================
name: service request
description: "request service support in cobalt"
title: "add support for [service name]"
labels: ["service request"]
body:
  - type: markdown
    attributes:
      value: |
        thanks for taking the time to make a service request!
        before you start, please make to read the "adding features or support for services" section of
        our [contributor guidelines](https://github.com/imputnet/cobalt/blob/main/CONTRIBUTING.md#adding-features-or-support-for-services) to make sure your request is a good fit for cobalt.
  - type: input
    id: service-name
    attributes:
      label: service name
    validations:
      required: true
  - type: textarea
    id: service-description
    attributes:
      label: service description
      description: a brief description of what the service is and/or what it provides
    validations:
      required: true
  - type: textarea
    id: link-samples
    attributes:
      label: link samples
      description: |
        list of links that cobalt should recognize.
        could be regular video link, shared video link, mobile video link, shortened link, etc.
      render: shell
    validations:
      required: true
  - type: textarea
    id: more-context
    attributes:
      label: additional context
      description: any additional context or screenshots should go here.


================================================
FILE: .github/test.sh
================================================
#!/bin/bash
set -e

# thx: https://stackoverflow.com/a/27601038
waitport() {
    ATTEMPTS=50
    while [ $((ATTEMPTS-=1)) -gt 0 ] && ! nc -z localhost $1; do   
        sleep 0.1
    done

    [ "$ATTEMPTS" != 0 ] || exit 1
}

test_api() {
    waitport 3000
    curl -m 3 http://localhost:3000/
    API_RESPONSE=$(curl -m 10 http://localhost:3000/ \
         -X POST \
         -H "Accept: application/json" \
         -H "Content-Type: application/json" \
         -d '{"url":"https://garfield-69.tumblr.com/post/696499862852780032","alwaysProxy":true}')

    echo "API_RESPONSE=$API_RESPONSE"
    STATUS=$(echo "$API_RESPONSE" | jq -r .status)
    STREAM_URL=$(echo "$API_RESPONSE" | jq -r .url)
    [ "$STATUS" = tunnel ] || exit 1;
    S=$(curl -I -m 10 "$STREAM_URL")

    CONTENT_LENGTH=$(echo "$S" \
                        | grep -i content-length \
                        | cut -d' ' -f2 \
                        | tr -d '\r')

    echo "$CONTENT_LENGTH"
    [ "$CONTENT_LENGTH" = 0 ] && exit 1
    if [ "$CONTENT_LENGTH" -lt 512 ]; then
        exit 1
    fi
}

setup_api() {
    export API_PORT=3000
    export API_URL=http://localhost:3000
    timeout 10 pnpm run --prefix api start &
    API_PID=$!
}

setup_web() {
    pnpm run --prefix web check
    pnpm run --prefix web build
}

cd "$(git rev-parse --show-toplevel)"
pnpm install --frozen-lockfile

if [ "$1" = "api" ]; then
    setup_api
    test_api
    [ "$API_PID" != "" ] \
        && kill "$API_PID"
elif [ "$1" = "web" ]; then
    setup_web
else
    echo "usage: $0 <api/web>" >&2
    exit 1
fi

wait || exit $?


================================================
FILE: .github/workflows/codeql.yml
================================================
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"

on:
  push:
    branches:
      - '**'
  pull_request:
    branches: [ "main", "7" ]
  schedule:
    - cron: '33 7 * * 5'

jobs:
  analyze:
    name: Analyze (${{ matrix.language }})
    # Runner size impacts CodeQL analysis time. To learn more, please see:
    #   - https://gh.io/recommended-hardware-resources-for-running-codeql
    #   - https://gh.io/supported-runners-and-hardware-resources
    #   - https://gh.io/using-larger-runners (GitHub.com only)
    # Consider using larger runners or machines with greater resources for possible analysis time improvements.
    runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
    permissions:
      # required for all workflows
      security-events: write

      # required to fetch internal or private CodeQL packs
      packages: read

      # only required for workflows in private repositories
      actions: read
      contents: read

    strategy:
      fail-fast: false
      matrix:
        include:
        - language: javascript-typescript
          build-mode: none
        # CodeQL supports the following values keywords for 'language': 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift'
        # Use `c-cpp` to analyze code written in C, C++ or both
        # Use 'java-kotlin' to analyze code written in Java, Kotlin or both
        # Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
        # To learn more about changing the languages that are analyzed or customizing the build mode for your analysis,
        # see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning.
        # If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how
        # your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
    steps:
    - name: Checkout repository
      uses: actions/checkout@v4

    # Initializes the CodeQL tools for scanning.
    - name: Initialize CodeQL
      uses: github/codeql-action/init@v3
      with:
        languages: ${{ matrix.language }}
        build-mode: ${{ matrix.build-mode }}
        # If you wish to specify custom queries, you can do so here or in a config file.
        # By default, queries listed here will override any specified in a config file.
        # Prefix the list here with "+" to use these queries and those in the config file.

        # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
        # queries: security-extended,security-and-quality

    # If the analyze step fails for one of the languages you are analyzing with
    # "We were unable to automatically build your code", modify the matrix above
    # to set the build mode to "manual" for that language. Then modify this step
    # to build your code.
    # ℹ️ Command-line programs to run using the OS shell.
    # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
    - if: matrix.build-mode == 'manual'
      shell: bash
      run: |
        echo 'If you are using a "manual" build mode for one or more of the' \
          'languages you are analyzing, replace this with the commands to build' \
          'your code, for example:'
        echo '  make bootstrap'
        echo '  make release'
        exit 1

    - name: Perform CodeQL Analysis
      uses: github/codeql-action/analyze@v3
      with:
        category: "/language:${{matrix.language}}"


================================================
FILE: .github/workflows/docker-develop.yml
================================================
name: Build development Docker image

on:
  workflow_dispatch:

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build-and-push-image:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Get release metadata
        id: release-meta
        run: |
            version=$(cat package.json | jq -r .version)
            echo "commit_short=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
            echo "version=$version" >> $GITHUB_OUTPUT
            echo "major_version=$(echo "$version" | cut -d. -f1)" >> $GITHUB_OUTPUT
      - name: Extract metadata (tags, labels) for Docker
        id: meta
        uses: docker/metadata-action@v5
        with:
          tags: type=raw,value=develop
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

      - name: Build and push Docker image
        uses: docker/build-push-action@v6
        with:
          context: .
          platforms: linux/amd64
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max


================================================
FILE: .github/workflows/docker-staging.yml
================================================
name: Build staging Docker image

on:
  workflow_dispatch:

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build-and-push-image:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Get release metadata
        id: release-meta
        run: |
            version=$(cat package.json | jq -r .version)
            echo "commit_short=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
            echo "version=$version" >> $GITHUB_OUTPUT
            echo "major_version=$(echo "$version" | cut -d. -f1)" >> $GITHUB_OUTPUT
      - name: Extract metadata (tags, labels) for Docker
        id: meta
        uses: docker/metadata-action@v5
        with:
          tags: type=raw,value=staging
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

      - name: Build and push Docker image
        uses: docker/build-push-action@v6
        with:
          context: .
          platforms: linux/amd64
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max


================================================
FILE: .github/workflows/docker.yml
================================================
name: Build release Docker image

on:
  workflow_dispatch:

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build-and-push-image:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to the Container registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Get release metadata
        id: release-meta
        run: |
            version=$(cat api/package.json | jq -r .version)
            echo "commit_short=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
            echo "version=$version" >> $GITHUB_OUTPUT
            echo "major_version=$(echo "$version" | cut -d. -f1)" >> $GITHUB_OUTPUT
      - name: Extract metadata (tags, labels) for Docker
        id: meta
        uses: docker/metadata-action@v5
        with:
          tags: |
            type=raw,value=latest
            type=raw,value=${{ steps.release-meta.outputs.version }}
            type=raw,value=${{ steps.release-meta.outputs.major_version }}
            type=raw,value=${{ steps.release-meta.outputs.version }}-${{ steps.release-meta.outputs.commit_short }}
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

      - name: Build and push Docker image
        uses: docker/build-push-action@v6
        with:
          context: .
          platforms: linux/amd64,linux/arm64
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max


================================================
FILE: .github/workflows/fast-forward.yml
================================================
name: fast-forward
on:
  issue_comment:
    types: [created, edited]
jobs:
  fast-forward:
    # Only run if the comment contains the /fast-forward command.
    if: ${{ contains(github.event.comment.body, '/fast-forward')
            && github.event.issue.pull_request }}
    runs-on: ubuntu-latest

    permissions:
      contents: write
      pull-requests: write
      issues: write

    steps:
      - name: Fast forwarding
        uses: sequoia-pgp/fast-forward@v1
        with:
          merge: true
          comment: 'on-error'

================================================
FILE: .github/workflows/test-services.yml
================================================
name: Run service tests

on:
  pull_request:
  push:
    paths:
      - api/**
      - packages/**

jobs:
  check-services:
    name: test service functionality
    runs-on: ubuntu-latest
    outputs:
      services: ${{ steps.checkServices.outputs.service_list }}
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
      - id: checkServices
        run: pnpm i --frozen-lockfile && echo "service_list=$(node api/src/util/test get-services)" >> "$GITHUB_OUTPUT"

  test-services:
    needs: check-services
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        service: ${{ fromJson(needs.check-services.outputs.services) }}
    name: "test service: ${{ matrix.service }}"
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
      - run: pnpm i --frozen-lockfile
      - run: node api/src/util/test run-tests-for ${{ matrix.service }}
        env:
          HTTP_PROXY: ${{ secrets.API_EXTERNAL_PROXY }}
          TEST_IGNORE_SERVICES: ${{ vars.TEST_IGNORE_SERVICES }}


================================================
FILE: .github/workflows/test.yml
================================================
name: Run tests

on:
  pull_request:
  push:

jobs:
  check-lockfile:
    name: check lockfile correctness
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
      - name: Check that lockfile does not need an update
        run: pnpm install --frozen-lockfile

  test-web:
    name: web sanity check
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 'lts/*'
      - uses: pnpm/action-setup@v4
      - run: .github/test.sh web
        env:
          WEB_DEFAULT_API: https://api.dummy.example/

  test-api:
    name: api sanity check
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
      - run: .github/test.sh api


================================================
FILE: .gitignore
================================================
# OS directory info files
.DS_Store
desktop.ini

# node
node_modules

# static build
build

# secrets
.env
.env.*
!.env.example
cookies.json
keys.json

# docker
docker-compose.yml

# ide
.vscode


================================================
FILE: CONTRIBUTING.md
================================================
# contributing to cobalt
if you're reading this, you are probably interested in contributing to cobalt, which we are very thankful for :3

this document serves as a guide to help you make contributions that we can merge into the cobalt codebase.

## translations
we are currently accepting translations via the [i18n platform](https://i18n.imput.net).

thank you for showing interest in making cobalt more accessible around the world, we really appreciate it! here are some guidelines for how a cobalt translation should look:

- cobalt's writing style is informal. please do not use formal language, unless there is no other way to express the same idea of the original text in your language.
- all cobalt text is written in lowercase. this is a stylistic choice, please do not capitalize translated sentences.
- do not translate the name "cobalt", or "imput"
- you can translate "meowbalt" into whatever your language's equivalent of _meow_ is (e.g. _miaubalt_ in German)
- **please don't translate cobalt into languages which you are not experienced in.** we can use google translate ourselves, but we would prefer cobalt to be translated by humans, not computers.

if your language does not exist on the translation platform yet, you can request to add it by adding it to any of cobalt's components (e.g. [here](https://i18n.imput.net/projects/cobalt/about/)).

before translating a piece of text, check that no one has made a translation yet. pending translations are displayed in the **Suggestions** tab on the translate page. if someone already made a suggestion, and you think it's correct, you can upvote it! this helps us distinguish that a translation is correct.

if no one has submitted a translation, or the submitted translation seems wrong to you, you can submit your translation by clicking the **Suggest** button for each individual string, which sends it off for human review. we will then check it to to ensure no malicious translations are submitted, and add it to cobalt.

if any translation string's meaning seems unclear to you, please leave a comment on the *Comments* tab, and we will either add an explanation or a screenshot.

## adding features or support for services
before putting in the effort to implement a feature, it's worth considering whether it would be appropriate to add it to cobalt. the cobalt api is built to assist people **only with downloading freely accessible content**. other functionality, such as:
- downloading paid / not publicly accessible content
- downloading content protected by DRM
- scraping unrelated information & exposing it outside of file metadata

will not be reviewed or merged.

if you plan on adding a feature or support for a service, but are unsure whether it would be appropriate, it's best to open an issue and discuss it beforehand.

## git
when contributing code to cobalt, there are a few guidelines in place to ensure that the code history is readable and comprehensible.

### clean commit messages
internally, we use a format similar to [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/) - the first part signifies which part of the code you are changing (the *scope*), and the second part explains the change. for inspiration on how to write appropriate commit titles, you can take a look at the [commit history](https://github.com/imputnet/cobalt/commits/).

the scope is not strictly defined, you can write whatever you find most fitting for the particular change. suppose you are changing a small part of a more significant part of the codebase. in that case, you can specify both the larger and smaller scopes in the commit message for clarity (e.g., if you were changing something in internal streams, the commit could be something like `api/stream: fix object not being handled properly`).

if you think a change deserves further explanation, we encourage you to write a short explanation in the commit message ([example](https://github.com/imputnet/cobalt/commit/31be60484de8eaf63bba8a4f508e16438aa7ba6e)), which will save both you and us time having to enquire about the change, and you explaining the reason behind it.

if your contribution has uninformative commit titles, you may be asked to interactively rebase your branch and amend each commit to include a meaningful title.

### clean commit history
if your branch is out of date and/or has some merge conflicts with the `current` branch, you should **rebase** it instead of merging. this prevents meaningless merge commits from being included in your branch, which would then end up in the cobalt git history.

if you find a mistake or bug in your code before it's merged or reviewed, instead of making a brand new commit to fix it, it would be preferable to amend that specific commit where the mistake was first introduced. this also helps us easily revert a commit if we discover that it introduced a bug or some unwanted behavior.
- if the commit you are fixing is the latest one, you can add your files to staging and then use `git commit --amend` to apply the change.
- if the commit is somewhere deeper in your branch, you can use `git commit --fixup=HASH`, where *`HASH`* is the commit you are fixing.
    - afterward, you must interactively rebase your branch with `git rebase -i current --autosquash`.
      this will open up an editor, but you don't need to do anything else except save the file and exit.
- once you do either of these things, you will need to do a **force push** to your branch with `git push --force-with-lease`.


================================================
FILE: Dockerfile
================================================
FROM node:24-alpine AS base
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"

FROM base AS build
WORKDIR /app
COPY . /app

RUN corepack enable
RUN apk add --no-cache python3 alpine-sdk

RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
    pnpm install --prod --frozen-lockfile

RUN pnpm deploy --filter=@imput/cobalt-api --prod /prod/api

FROM base AS api
WORKDIR /app

COPY --from=build --chown=node:node /prod/api /app
COPY --from=build --chown=node:node /app/.git /app/.git

USER node

EXPOSE 9000
CMD [ "node", "src/cobalt" ]


================================================
FILE: LICENSE
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time.  Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    save what you love with cobalt.
    Copyright (C) 2024 imput

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.


================================================
FILE: README.md
================================================
<div align="center">
    <br/>
    <p>
        <img src="web/static/favicon.png" title="cobalt" alt="cobalt logo" width="100" />
    </p>
    <p>
        best way to save what you love
        <br/>
        <a href="https://cobalt.tools">
            cobalt.tools
        </a>
    </p>
    <p>
        <a href="https://discord.gg/pQPt8HBUPu">
            💬 community discord server
        </a>
        <br/>
        <a href="https://x.com/justusecobalt">
            🐦 twitter
        </a>
        <a href="https://bsky.app/profile/cobalt.tools">
            🦋 bluesky
        </a>
    </p>
    <br/>
</div>

cobalt is a media downloader that doesn't piss you off. it's friendly, efficient, and doesn't have ads, trackers, paywalls or other nonsense.

paste the link, get the file, move on. that simple, just how it should be.

### cobalt monorepo
this monorepo includes source code for api, frontend, and related packages:
- [api tree & readme](/api/)
- [web tree & readme](/web/)
- [packages tree](/packages/)

it also includes documentation in the [docs tree](/docs/):
- [how to run a cobalt instance](/docs/run-an-instance.md)
- [how to protect a cobalt instance](/docs/protect-an-instance.md)
- [cobalt api instance environment variables](/docs/api-env-variables.md)
- [cobalt api documentation](/docs/api.md)

### ethics
cobalt is a tool that makes downloading public content easier. it takes **zero liability**.
the end user is responsible for what they download, how they use and distribute that content.
cobalt never caches any content, it [works like a fancy proxy](/api/src/stream/).

cobalt is in no way a piracy tool and cannot be used as such.
it can only download free & publicly accessible content.
same content can be downloaded via dev tools of any modern web browser.

### contributing
if you're considering contributing to cobalt, first of all, thank you! check the [contribution guidelines here](/CONTRIBUTING.md) before getting started, they'll help you do your best right away.

### thank you
cobalt is sponsored by [royalehosting.net](https://royalehosting.net/?partner=cobalt). a part of our infrastructure is hosted on their network. we really appreciate their kindness and support!

### licenses
for relevant licensing information, see the [api](api/README.md) and [web](web/README.md) READMEs.
unless specified otherwise, the remainder of this repository is licensed under [AGPL-3.0](LICENSE).


================================================
FILE: api/LICENSE
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU Affero General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time.  Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    save what you love with cobalt.
    Copyright (C) 2024 imput

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.


================================================
FILE: api/README.md
================================================
# cobalt api
this directory includes the source code for cobalt api. it's made with [express.js](https://www.npmjs.com/package/express) and love!

## running your own instance
if you want to run your own instance for whatever purpose, [follow this guide](/docs/run-an-instance.md).
we recommend to use docker compose unless you intend to run cobalt for developing/debugging purposes.

## accessing the api
there is currently no publicly available pre-hosted api.
we recommend [deploying your own instance](/docs/run-an-instance.md) if you wish to use the cobalt api.

you can read [the api documentation here](/docs/api.md).

## supported services
this list is not final and keeps expanding over time!
if the desired service isn't supported yet, feel free to create an appropriate issue (or a pull request 👀).

| service           | video + audio | only audio | only video | metadata | rich file names |
| :--------         | :-----------: | :--------: | :--------: | :------: | :-------------: |
| bilibili          | ✅            | ✅         | ✅         | ➖         | ➖              |
| bluesky           | ✅            | ✅         | ✅         | ➖         | ➖              |
| dailymotion       | ✅            | ✅         | ✅         | ✅         | ✅              |
| instagram         | ✅            | ✅         | ✅         | ➖         | ➖              |
| facebook          | ✅            | ❌         | ✅         | ➖         | ➖              |
| loom              | ✅            | ❌         | ✅         | ✅         | ➖              |
| newgrounds        | ✅            | ✅         | ✅         | ✅         | ✅              |
| ok.ru             | ✅            | ❌         | ✅         | ✅         | ✅              |
| pinterest         | ✅            | ✅         | ✅         | ➖         | ➖              |
| reddit            | ✅            | ✅         | ✅         | ❌         | ❌              |
| rutube            | ✅            | ✅         | ✅         | ✅         | ✅              |
| snapchat          | ✅            | ✅         | ✅         | ➖         | ➖              |
| soundcloud        | ➖            | ✅         | ➖         | ✅         | ✅              |
| streamable        | ✅            | ✅         | ✅         | ➖         | ➖              |
| tiktok            | ✅            | ✅         | ✅         | ❌         | ❌              |
| tumblr            | ✅            | ✅         | ✅         | ➖         | ➖              |
| twitch clips      | ✅            | ✅         | ✅         | ✅         | ✅              |
| twitter/x         | ✅            | ✅         | ✅         | ➖         | ➖              |
| vimeo             | ✅            | ✅         | ✅         | ✅         | ✅              |
| vk videos & clips | ✅            | ❌         | ✅         | ✅         | ✅              |
| xiaohongshu       | ✅            | ✅         | ✅         | ➖         | ➖              |
| youtube           | ✅            | ✅         | ✅         | ✅         | ✅              |

| emoji   | meaning                 |
| :-----: | :---------------------- |
| ✅      | supported               |
| ➖      | unreasonable/impossible |
| ❌      | not supported           |

### additional notes or features (per service)
| service    | notes or features                                                                                                    |
| :--------  | :-----                                                                                                               |
| instagram  | supports reels, photos, and videos. lets you pick what to save from multi-media posts.                               |
| facebook   | supports public accessible videos content only.                                                                      |
| pinterest  | supports photos, gifs, videos and stories.                                                                           |
| reddit     | supports gifs and videos.                                                                                            |
| snapchat   | supports spotlights and stories. lets you pick what to save from stories.                                            |
| rutube     | supports yappy & private links.                                                                                      |
| soundcloud | supports private links.                                                                                              |
| tiktok     | supports videos with or without watermark, images from slideshow without watermark, and full (original) audios.      |
| twitter/x  | lets you pick what to save from multi-media posts. may not be 100% reliable due to current management.               |
| vimeo      | audio downloads are only available for dash.                                                                         |
| youtube    | supports videos, music, and shorts. 8K, 4K, HDR, VR, and high FPS videos. rich metadata & dubs. h264/av1/vp9 codecs. |

## license
cobalt api code is licensed under [AGPL-3.0](LICENSE).

this license allows you to modify, distribute and use the code for any purpose
as long as you:
- give appropriate credit to the original repo when using or modifying any parts of the code,
- provide a link to the license and indicate if changes to the code were made, and
- release the code under the **same license**

## open source acknowledgements
### ffmpeg
cobalt relies on ffmpeg for muxing and encoding media files. ffmpeg is absolutely spectacular and we're privileged to have the ability to use it for free, just like anyone else. we believe it should be way more recognized.

you can [support ffmpeg here](https://ffmpeg.org/donations.html)!

### youtube.js
cobalt relies on **[youtube.js](https://github.com/LuanRT/YouTube.js)** for interacting with youtube's innertube api, it wouldn't have been possible without this package.

you can support the developer via various methods listed on their github page!
(linked above)

### many others
cobalt-api also depends on:

- **[content-disposition-header](https://www.npmjs.com/package/content-disposition-header)** to simplify the provision of `content-disposition` headers.
- **[cors](https://www.npmjs.com/package/cors)** to manage cross-origin resource sharing within expressjs.
- **[dotenv](https://www.npmjs.com/package/dotenv)** to load environment variables from the `.env` file.
- **[express](https://www.npmjs.com/package/express)** as the backbone of cobalt servers.
- **[express-rate-limit](https://www.npmjs.com/package/express-rate-limit)** to rate limit api endpoints.
- **[ffmpeg-static](https://www.npmjs.com/package/ffmpeg-static)** to get binaries for ffmpeg depending on the platform.
- **[hls-parser](https://www.npmjs.com/package/hls-parser)** to parse HLS playlists according to spec (very impressive stuff).
- **[ipaddr.js](https://www.npmjs.com/package/ipaddr.js)** to parse ip addresses (used for rate limiting).
- **[nanoid](https://www.npmjs.com/package/nanoid)** to generate unique identifiers for each requested tunnel.
- **[set-cookie-parser](https://www.npmjs.com/package/set-cookie-parser)** to parse cookies that cobalt receives from certain services.
- **[undici](https://www.npmjs.com/package/undici)** for making http requests.
- **[url-pattern](https://www.npmjs.com/package/url-pattern)** to match provided links with supported patterns.
- **[zod](https://www.npmjs.com/package/zod)** to lock down the api request schema.
- **[@datastructures-js/priority-queue](https://www.npmjs.com/package/@datastructures-js/priority-queue)** for sorting stream caches for future clean up (without redis).
- **[@imput/psl](https://www.npmjs.com/package/@imput/psl)** as the domain name parser, our fork of [psl](https://www.npmjs.com/package/psl).

...and many other packages that these packages rely on.


================================================
FILE: api/package.json
================================================
{
    "name": "@imput/cobalt-api",
    "description": "save what you love",
    "version": "11.5",
    "author": "imput",
    "exports": "./src/cobalt.js",
    "type": "module",
    "engines": {
        "node": ">=18"
    },
    "scripts": {
        "start": "node src/cobalt",
        "test": "node src/util/test",
        "token:jwt": "node src/util/generate-jwt-secret"
    },
    "repository": {
        "type": "git",
        "url": "git+https://github.com/imputnet/cobalt.git"
    },
    "license": "AGPL-3.0",
    "bugs": {
        "url": "https://github.com/imputnet/cobalt/issues"
    },
    "homepage": "https://github.com/imputnet/cobalt#readme",
    "dependencies": {
        "@datastructures-js/priority-queue": "^6.3.1",
        "@imput/psl": "^2.0.4",
        "@imput/version-info": "workspace:^",
        "content-disposition-header": "0.6.0",
        "cors": "^2.8.5",
        "dotenv": "^16.0.1",
        "express": "^4.21.2",
        "express-rate-limit": "^7.4.1",
        "ffmpeg-static": "^5.1.0",
        "hls-parser": "^0.10.7",
        "ipaddr.js": "2.2.0",
        "mime": "^4.0.4",
        "nanoid": "^5.0.9",
        "set-cookie-parser": "2.6.0",
        "undici": "^6.21.3",
        "url-pattern": "1.0.3",
        "youtubei.js": "15.1.1",
        "zod": "^3.23.8"
    },
    "optionalDependencies": {
        "freebind": "^0.2.2",
        "rate-limit-redis": "^4.2.0",
        "redis": "^4.7.0"
    }
}


================================================
FILE: api/src/cobalt.js
================================================
import "dotenv/config";

import express from "express";
import cluster from "node:cluster";

import path from "path";
import { fileURLToPath } from "url";

import { env, isCluster } from "./config.js"
import { Red } from "./misc/console-text.js";
import { initCluster } from "./misc/cluster.js";
import { setupEnvWatcher } from "./core/env.js";

const app = express();

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename).slice(0, -4);

app.disable("x-powered-by");

if (env.apiURL) {
    const { runAPI } = await import("./core/api.js");

    if (isCluster) {
       await initCluster();
    }

    if (env.envFile) {
        setupEnvWatcher();
    }

    runAPI(express, app, __dirname, cluster.isPrimary);
} else {
    console.log(
        Red("API_URL env variable is missing, cobalt api can't start.")
    )
}


================================================
FILE: api/src/config.js
================================================
import { getVersion } from "@imput/version-info";
import { loadEnvs, validateEnvs } from "./core/env.js";

const version = await getVersion();

const canonicalEnv = Object.freeze(structuredClone(process.env));
const env = loadEnvs();

const genericUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36";
const cobaltUserAgent = `cobalt/${version} (+https://github.com/imputnet/cobalt)`;

export const setTunnelPort = (port) => env.tunnelPort = port;
export const isCluster = env.instanceCount > 1;
export const updateEnv = (newEnv) => {
    const changes = [];

    // tunnelPort is special and needs to get carried over here
    newEnv.tunnelPort = env.tunnelPort;

    for (const key in env) {
        if (key === 'subscribe') {
            continue;
        }

        if (String(env[key]) !== String(newEnv[key])) {
            changes.push(key);
        }
        env[key] = newEnv[key];
    }

    return changes;
}

await validateEnvs(env);

export {
    env,
    canonicalEnv,
    genericUserAgent,
    cobaltUserAgent,
}


================================================
FILE: api/src/core/api.js
================================================
import cors from "cors";
import http from "node:http";
import rateLimit from "express-rate-limit";
import { setGlobalDispatcher, EnvHttpProxyAgent } from "undici";
import { getCommit, getBranch, getRemote, getVersion } from "@imput/version-info";

import jwt from "../security/jwt.js";
import stream from "../stream/stream.js";
import match from "../processing/match.js";

import { env } from "../config.js";
import { extract } from "../processing/url.js";
import { Bright, Cyan } from "../misc/console-text.js";
import { hashHmac } from "../security/secrets.js";
import { createStore } from "../store/redis-ratelimit.js";
import { randomizeCiphers } from "../misc/randomize-ciphers.js";
import { verifyTurnstileToken } from "../security/turnstile.js";
import { friendlyServiceName } from "../processing/service-alias.js";
import { verifyStream } from "../stream/manage.js";
import { createResponse, normalizeRequest, getIP } from "../processing/request.js";
import { setupTunnelHandler } from "./itunnel.js";

import * as APIKeys from "../security/api-keys.js";
import * as Cookies from "../processing/cookie/manager.js";
import * as YouTubeSession from "../processing/helpers/youtube-session.js";

const git = {
    branch: await getBranch(),
    commit: await getCommit(),
    remote: await getRemote(),
}

const version = await getVersion();

const acceptRegex = /^application\/json(; charset=utf-8)?$/;

const corsConfig = env.corsWildcard ? {} : {
    origin: env.corsURL,
    optionsSuccessStatus: 200
}

const fail = (res, code, context) => {
    const { status, body } = createResponse("error", { code, context });
    res.status(status).json(body);
}

export const runAPI = async (express, app, __dirname, isPrimary = true) => {
    const startTime = new Date();
    const startTimestamp = startTime.getTime();

    const getServerInfo = () => {
        return JSON.stringify({
            cobalt: {
                version: version,
                url: env.apiURL,
                startTime: `${startTimestamp}`,
                turnstileSitekey: env.sessionEnabled ? env.turnstileSitekey : undefined,
                services: [...env.enabledServices].map(e => {
                    return friendlyServiceName(e);
                }),
            },
            git,
        });
    }

    const serverInfo = getServerInfo();

    const handleRateExceeded = (_, res) => {
        const { body } = createResponse("error", {
            code: "error.api.rate_exceeded",
            context: {
                limit: env.rateLimitWindow
            }
        });
        return res.status(429).json(body);
    };

    const keyGenerator = (req) => hashHmac(getIP(req), 'rate').toString('base64url');

    const sessionLimiter = rateLimit({
        windowMs: env.sessionRateLimitWindow * 1000,
        limit: env.sessionRateLimit,
        standardHeaders: 'draft-6',
        legacyHeaders: false,
        keyGenerator,
        store: await createStore('session'),
        handler: handleRateExceeded
    });

    const apiLimiter = rateLimit({
        windowMs: env.rateLimitWindow * 1000,
        limit: (req) => req.rateLimitMax || env.rateLimitMax,
        standardHeaders: 'draft-6',
        legacyHeaders: false,
        keyGenerator: req => req.rateLimitKey || keyGenerator(req),
        store: await createStore('api'),
        handler: handleRateExceeded
    });

    const apiTunnelLimiter = rateLimit({
        windowMs: env.tunnelRateLimitWindow * 1000,
        limit: env.tunnelRateLimitMax,
        standardHeaders: 'draft-6',
        legacyHeaders: false,
        keyGenerator: req => keyGenerator(req),
        store: await createStore('tunnel'),
        handler: (_, res) => {
            return res.sendStatus(429);
        }
    });

    app.set('trust proxy', ['loopback', 'uniquelocal']);

    app.use('/', cors({
        methods: ['GET', 'POST'],
        exposedHeaders: [
            'Ratelimit-Limit',
            'Ratelimit-Policy',
            'Ratelimit-Remaining',
            'Ratelimit-Reset'
        ],
        ...corsConfig,
    }));

    app.post('/', (req, res, next) => {
        if (!acceptRegex.test(req.header('Accept'))) {
            return fail(res, "error.api.header.accept");
        }
        if (!acceptRegex.test(req.header('Content-Type'))) {
            return fail(res, "error.api.header.content_type");
        }
        next();
    });

    app.post('/', (req, res, next) => {
        if (!env.apiKeyURL) {
            return next();
        }

        const { success, error } = APIKeys.validateAuthorization(req);
        if (!success) {
            // We call next() here if either if:
            // a) we have user sessions enabled, meaning the request
            //    will still need a Bearer token to not be rejected, or
            // b) we do not require the user to be authenticated, and
            //    so they can just make the request with the regular
            //    rate limit configuration;
            // otherwise, we reject the request.
            if (
                (env.sessionEnabled || !env.authRequired)
                && ['missing', 'not_api_key'].includes(error)
            ) {
                return next();
            }

            return fail(res, `error.api.auth.key.${error}`);
        }

        req.authType = "key";
        return next();
    });

    app.post('/', (req, res, next) => {
        if (!env.sessionEnabled || req.rateLimitKey) {
            return next();
        }

        try {
            const authorization = req.header("Authorization");
            if (!authorization) {
                return fail(res, "error.api.auth.jwt.missing");
            }

            if (authorization.length >= 256) {
                return fail(res, "error.api.auth.jwt.invalid");
            }

            const [ type, token, ...rest ] = authorization.split(" ");
            if (!token || type.toLowerCase() !== 'bearer' || rest.length) {
                return fail(res, "error.api.auth.jwt.invalid");
            }

            if (!jwt.verify(token, getIP(req, 32))) {
                return fail(res, "error.api.auth.jwt.invalid");
            }

            req.rateLimitKey = hashHmac(token, 'rate');
            req.authType = "session";
        } catch {
            return fail(res, "error.api.generic");
        }
        next();
    });

    app.post('/', apiLimiter);
    app.use('/', express.json({ limit: 1024 }));

    app.use('/', (err, _, res, next) => {
        if (err) {
            const { status, body } = createResponse("error", {
                code: "error.api.invalid_body",
            });
            return res.status(status).json(body);
        }

        next();
    });

    app.post("/session", sessionLimiter, async (req, res) => {
        if (!env.sessionEnabled) {
            return fail(res, "error.api.auth.not_configured")
        }

        const turnstileResponse = req.header("cf-turnstile-response");

        if (!turnstileResponse) {
            return fail(res, "error.api.auth.turnstile.missing");
        }

        const turnstileResult = await verifyTurnstileToken(
            turnstileResponse,
            req.ip
        );

        if (!turnstileResult) {
            return fail(res, "error.api.auth.turnstile.invalid");
        }

        try {
            res.json(jwt.generate(getIP(req, 32)));
        } catch {
            return fail(res, "error.api.generic");
        }
    });

    app.post('/', async (req, res) => {
        const request = req.body;

        if (!request.url) {
            return fail(res, "error.api.link.missing");
        }

        const { success, data: normalizedRequest } = await normalizeRequest(request);
        if (!success) {
            return fail(res, "error.api.invalid_body");
        }

        const parsed = extract(
            normalizedRequest.url,
            APIKeys.getAllowedServices(req.rateLimitKey),
        );

        if (!parsed) {
            return fail(res, "error.api.link.invalid");
        }

        if ("error" in parsed) {
            let context;
            if (parsed?.context) {
                context = parsed.context;
            }
            return fail(res, `error.api.${parsed.error}`, context);
        }

        try {
            const result = await match({
                host: parsed.host,
                patternMatch: parsed.patternMatch,
                params: normalizedRequest,
                authType: req.authType ?? "none",
            });

            res.status(result.status).json(result.body);
        } catch {
            fail(res, "error.api.generic");
        }
    });

    app.use('/tunnel', cors({
        methods: ['GET'],
        exposedHeaders: [
            'Estimated-Content-Length',
            'Content-Disposition'
        ],
        ...corsConfig,
    }));

    app.get('/tunnel', apiTunnelLimiter, async (req, res) => {
        const id = String(req.query.id);
        const exp = String(req.query.exp);
        const sig = String(req.query.sig);
        const sec = String(req.query.sec);
        const iv = String(req.query.iv);

        const checkQueries = id && exp && sig && sec && iv;
        const checkBaseLength = id.length === 21 && exp.length === 13;
        const checkSafeLength = sig.length === 43 && sec.length === 43 && iv.length === 22;

        if (!checkQueries || !checkBaseLength || !checkSafeLength) {
            return res.status(400).end();
        }

        if (req.query.p) {
            return res.status(200).end();
        }

        const streamInfo = await verifyStream(id, sig, exp, sec, iv);
        if (!streamInfo?.service) {
            return res.status(streamInfo.status).end();
        }

        if (streamInfo.type === 'proxy') {
            streamInfo.range = req.headers['range'];
        }

        return stream(res, streamInfo);
    });

    app.get('/', (_, res) => {
        res.type('json');
        res.status(200).send(env.envFile ? getServerInfo() : serverInfo);
    })

    app.get('/favicon.ico', (req, res) => {
        res.status(404).end();
    })

    app.get('/*', (req, res) => {
        res.redirect('/');
    })

    // handle all express errors
    app.use((_, __, res, ___) => {
        return fail(res, "error.api.generic");
    })

    randomizeCiphers();
    setInterval(randomizeCiphers, 1000 * 60 * 30); // shuffle ciphers every 30 minutes

    env.subscribe(['externalProxy', 'httpProxyValues'], () => {
        // TODO: remove env.externalProxy in a future version
        const options = {};
        if (env.externalProxy) {
            options.httpProxy = env.externalProxy;
        }

        setGlobalDispatcher(
            new EnvHttpProxyAgent(options)
        );
    });

    http.createServer(app).listen({
        port: env.apiPort,
        host: env.listenAddress,
        reusePort: env.instanceCount > 1 || undefined
    }, () => {
        if (isPrimary) {
            console.log(`\n` +
                Bright(Cyan("cobalt ")) + Bright("API ^ω^") + "\n" +

                "~~~~~~\n" +
                Bright("version: ") + version + "\n" +
                Bright("commit: ") + git.commit + "\n" +
                Bright("branch: ") + git.branch + "\n" +
                Bright("remote: ") + git.remote + "\n" +
                Bright("start time: ") + startTime.toUTCString() + "\n" +
                "~~~~~~\n" +

                Bright("url: ") + Bright(Cyan(env.apiURL)) + "\n" +
                Bright("port: ") + env.apiPort + "\n"
            );
        }

        if (env.apiKeyURL) {
            APIKeys.setup(env.apiKeyURL);
        }

        if (env.cookiePath) {
            Cookies.setup(env.cookiePath);
        }

        if (env.ytSessionServer) {
            YouTubeSession.setup();
        }
    });

    setupTunnelHandler();
}


================================================
FILE: api/src/core/env.js
================================================
import { Constants } from "youtubei.js";
import { services } from "../processing/service-config.js";
import { updateEnv, canonicalEnv, env as currentEnv } from "../config.js";

import { FileWatcher } from "../misc/file-watcher.js";
import { isURL } from "../misc/utils.js";
import * as cluster from "../misc/cluster.js";
import { Green, Yellow } from "../misc/console-text.js";

const forceLocalProcessingOptions = ["never", "session", "always"];
const youtubeHlsOptions = ["never", "key", "always"];

const httpProxyVariables = ["NO_PROXY", "HTTP_PROXY", "HTTPS_PROXY"].flatMap(
    k => [ k, k.toLowerCase() ]
);

const changeCallbacks = {};

const onEnvChanged = (changes) => {
    for (const key of changes) {
        if (changeCallbacks[key]) {
            changeCallbacks[key].map(fn => {
                try { fn() } catch {}
            });
        }
    }
}

const subscribe = (keys, fn) => {
    keys = [keys].flat();

    for (const key of keys) {
        if (key in currentEnv && key !== 'subscribe') {
            changeCallbacks[key] ??= [];
            changeCallbacks[key].push(fn);
            fn();
        } else throw `invalid env key ${key}`;
    }
}

export const loadEnvs = (env = process.env) => {
    const allServices = new Set(Object.keys(services));
    const disabledServices = env.DISABLED_SERVICES?.split(',') || [];
    const enabledServices = new Set(Object.keys(services).filter(e => {
        if (!disabledServices.includes(e)) {
            return e;
        }
    }));

    // we need to copy the proxy envs (HTTP_PROXY, HTTPS_PROXY)
    // back into process.env, so that EnvHttpProxyAgent can pick
    // them up later
    for (const key of httpProxyVariables) {
        const value = env[key] ?? canonicalEnv[key];
        if (value !== undefined) {
            process.env[key] = env[key];
        } else {
            delete process.env[key];
        }
    }

    return {
        apiURL: env.API_URL || '',
        apiPort: env.API_PORT || 9000,
        tunnelPort: env.API_PORT || 9000,

        listenAddress: env.API_LISTEN_ADDRESS,
        freebindCIDR: process.platform === 'linux' && env.FREEBIND_CIDR,

        corsWildcard: env.CORS_WILDCARD !== '0',
        corsURL: env.CORS_URL,

        cookiePath: env.COOKIE_PATH,

        rateLimitWindow: (env.RATELIMIT_WINDOW && parseInt(env.RATELIMIT_WINDOW)) || 60,
        rateLimitMax: (env.RATELIMIT_MAX && parseInt(env.RATELIMIT_MAX)) || 20,

        tunnelRateLimitWindow: (env.TUNNEL_RATELIMIT_WINDOW && parseInt(env.TUNNEL_RATELIMIT_WINDOW)) || 60,
        tunnelRateLimitMax: (env.TUNNEL_RATELIMIT_MAX && parseInt(env.TUNNEL_RATELIMIT_MAX)) || 40,

        sessionRateLimitWindow: (env.SESSION_RATELIMIT_WINDOW && parseInt(env.SESSION_RATELIMIT_WINDOW)) || 60,
        sessionRateLimit:
            // backwards compatibility with SESSION_RATELIMIT
            // till next major due to an error in docs
            (env.SESSION_RATELIMIT_MAX && parseInt(env.SESSION_RATELIMIT_MAX))
            || (env.SESSION_RATELIMIT && parseInt(env.SESSION_RATELIMIT))
            || 10,

        durationLimit: (env.DURATION_LIMIT && parseInt(env.DURATION_LIMIT)) || 10800,
        streamLifespan: (env.TUNNEL_LIFESPAN && parseInt(env.TUNNEL_LIFESPAN)) || 90,

        processingPriority: process.platform !== 'win32'
            && env.PROCESSING_PRIORITY
            && parseInt(env.PROCESSING_PRIORITY),

        externalProxy: env.API_EXTERNAL_PROXY,

        // used only for comparing against old values when envs are being updated
        httpProxyValues: httpProxyVariables.map(k => String(env[k])).join(''),

        turnstileSitekey: env.TURNSTILE_SITEKEY,
        turnstileSecret: env.TURNSTILE_SECRET,
        jwtSecret: env.JWT_SECRET,
        jwtLifetime: env.JWT_EXPIRY || 120,

        sessionEnabled: env.TURNSTILE_SITEKEY
                            && env.TURNSTILE_SECRET
                            && env.JWT_SECRET,

        apiKeyURL: env.API_KEY_URL && new URL(env.API_KEY_URL),
        authRequired: env.API_AUTH_REQUIRED === '1',
        redisURL: env.API_REDIS_URL,
        instanceCount: (env.API_INSTANCE_COUNT && parseInt(env.API_INSTANCE_COUNT)) || 1,
        keyReloadInterval: 900,

        allServices,
        enabledServices,

        customInnertubeClient: env.CUSTOM_INNERTUBE_CLIENT,
        ytSessionServer: env.YOUTUBE_SESSION_SERVER,
        ytSessionReloadInterval: 300,
        ytSessionInnertubeClient: env.YOUTUBE_SESSION_INNERTUBE_CLIENT,
        ytAllowBetterAudio: env.YOUTUBE_ALLOW_BETTER_AUDIO !== "0",

        // "never" | "session" | "always"
        forceLocalProcessing: env.FORCE_LOCAL_PROCESSING ?? "never",

        // "never" | "key" | "always"
        enableDeprecatedYoutubeHls: env.ENABLE_DEPRECATED_YOUTUBE_HLS ?? "never",

        envFile: env.API_ENV_FILE,
        envRemoteReloadInterval: 300,

        subscribe,
    };
}

let loggedProxyWarning = false;

export const validateEnvs = async (env) => {
    if (env.sessionEnabled && env.jwtSecret.length < 16) {
        throw new Error("JWT_SECRET env is too short (must be at least 16 characters long)");
    }

    if (env.instanceCount > 1 && !env.redisURL) {
        throw new Error("API_REDIS_URL is required when API_INSTANCE_COUNT is >= 2");
    } else if (env.instanceCount > 1 && !await cluster.supportsReusePort()) {
        console.error('API_INSTANCE_COUNT is not supported in your environment. to use this env, your node.js');
        console.error('version must be >= 23.1.0, and you must be running a recent enough version of linux');
        console.error('(or other OS that supports it). for more info, see `reusePort` option on');
        console.error('https://nodejs.org/api/net.html#serverlistenoptions-callback');
        throw new Error('SO_REUSEPORT is not supported');
    }

    if (env.customInnertubeClient && !Constants.SUPPORTED_CLIENTS.includes(env.customInnertubeClient)) {
        console.error("CUSTOM_INNERTUBE_CLIENT is invalid. Provided client is not supported.");
        console.error(`Supported clients are: ${Constants.SUPPORTED_CLIENTS.join(', ')}\n`);
        throw new Error("Invalid CUSTOM_INNERTUBE_CLIENT");
    }

    if (env.forceLocalProcessing && !forceLocalProcessingOptions.includes(env.forceLocalProcessing)) {
        console.error("FORCE_LOCAL_PROCESSING is invalid.");
        console.error(`Supported options are are: ${forceLocalProcessingOptions.join(', ')}\n`);
        throw new Error("Invalid FORCE_LOCAL_PROCESSING");
    }

    if (env.enableDeprecatedYoutubeHls && !youtubeHlsOptions.includes(env.enableDeprecatedYoutubeHls)) {
        console.error("ENABLE_DEPRECATED_YOUTUBE_HLS is invalid.");
        console.error(`Supported options are are: ${youtubeHlsOptions.join(', ')}\n`);
        throw new Error("Invalid ENABLE_DEPRECATED_YOUTUBE_HLS");
    }

    if (env.externalProxy && env.freebindCIDR) {
        throw new Error('freebind is not available when external proxy is enabled')
    }

    if (env.externalProxy && !loggedProxyWarning) {
        console.error('API_EXTERNAL_PROXY is deprecated and will be removed in a future release.');
        console.error('Use HTTP_PROXY or HTTPS_PROXY instead.');
        console.error('You can read more about the new proxy variables in docs/api-env-variables.md\n');

        // prevent the warning from being printed on every env validation
        loggedProxyWarning = true;
    }

    return env;
}

const reloadEnvs = async (contents) => {
    const newEnvs = {};
    const resolvedContents = await contents;

    for (let line of resolvedContents.split('\n')) {
        line = line.trim();
        if (line === '') {
            continue;
        }

        let [ key, value ] = line.split(/=(.+)?/);
        if (key) {
            if (value.match(/^['"]/) && value.match(/['"]$/)) {
                value = JSON.parse(value);
            }

            newEnvs[key] = value || '';
        }
    }

    const candidate = {
        ...canonicalEnv,
        ...newEnvs,
    };

    const parsed = await validateEnvs(
        loadEnvs(candidate)
    );

    cluster.broadcast({ env_update: resolvedContents });
    return updateEnv(parsed);
}

const wrapReload = (contents) => {
    reloadEnvs(contents)
    .then(changes => {
        if (changes.length === 0) {
            return;
        }

        onEnvChanged(changes);

        console.log(`${Green('[✓]')} envs reloaded successfully!`);
        for (const key of changes) {
            const value = currentEnv[key];
            const isSecret = key.toLowerCase().includes('apikey')
                          || key.toLowerCase().includes('secret')
                          || key === 'httpProxyValues';

            if (!value) {
                console.log(`    removed: ${key}`);
            } else {
                console.log(`    changed: ${key} -> ${isSecret ? '***' : value}`);
            }
        }
    })
    .catch((e) => {
        console.error(`${Yellow('[!]')} Failed reloading environment variables at ${new Date().toISOString()}.`);
        console.error('Error:', e);
    });
}

let watcher;
const setupWatcherFromFile = (path) => {
    const load = () => wrapReload(watcher.read());

    if (isURL(path)) {
        watcher = FileWatcher.fromFileProtocol(path);
    } else {
        watcher = new FileWatcher({ path });
    }

    watcher.on('file-updated', load);
    load();
}

const setupWatcherFromFetch = (url) => {
    const load = () => wrapReload(fetch(url).then(r => r.text()));
    setInterval(load, currentEnv.envRemoteReloadInterval);
    load();
}

export const setupEnvWatcher = () => {
    if (cluster.isPrimary) {
        const envFile = currentEnv.envFile;
        const isFile = !isURL(envFile)
                       || new URL(envFile).protocol === 'file:';

        if (isFile) {
            setupWatcherFromFile(envFile);
        } else {
            setupWatcherFromFetch(envFile);
        }
    } else if (cluster.isWorker) {
        process.on('message', (message) => {
            if ('env_update' in message) {
                reloadEnvs(message.env_update);
            }
        });
    }
}


================================================
FILE: api/src/core/itunnel.js
================================================
import stream from "../stream/stream.js";
import { getInternalTunnel } from "../stream/manage.js";
import { setTunnelPort } from "../config.js";
import { Green } from "../misc/console-text.js";
import express from "express";

const validateTunnel = (req, res) => {
    if (!req.ip.endsWith('127.0.0.1')) {
        res.sendStatus(403);
        return;
    }

    if (String(req.query.id).length !== 21) {
        res.sendStatus(400);
        return;
    }

    const streamInfo = getInternalTunnel(req.query.id);
    if (!streamInfo) {
        res.sendStatus(404);
        return;
    }

    return streamInfo;
}

const streamTunnel = (req, res) => {
    const streamInfo = validateTunnel(req, res);
    if (!streamInfo) {
        return;
    }

    streamInfo.headers = new Map([
        ...(streamInfo.headers || []),
        ...Object.entries(req.headers)
    ]);

    return stream(res, { type: 'internal', data: streamInfo });
}

export const setupTunnelHandler = () => {
    const tunnelHandler = express();

    tunnelHandler.get('/itunnel', streamTunnel);

    // fallback
    tunnelHandler.use((_, res) => res.sendStatus(400));
    // error handler
    tunnelHandler.use((_, __, res, ____) => res.socket.end());


    const server = tunnelHandler.listen({
        port: 0,
        host: '127.0.0.1',
        exclusive: true
    }, () => {
        const { port } = server.address();
        console.log(`${Green('[✓]')} internal tunnel handler running on 127.0.0.1:${port}`);
        setTunnelPort(port);
    });
}


================================================
FILE: api/src/misc/cluster.js
================================================
import cluster from "node:cluster";
import net from "node:net";
import { syncSecrets } from "../security/secrets.js";
import { env, isCluster } from "../config.js";

export { isPrimary, isWorker } from "node:cluster";

export const supportsReusePort = async () => {
    try {
        await new Promise((resolve, reject) => {
            const server = net.createServer().listen({ port: 0, reusePort: true });
            server.on('listening', () => server.close(resolve));
            server.on('error', (err) => (server.close(), reject(err)));
        });

        const [major, minor] = process.versions.node.split('.').map(Number);
        return major > 23 || (major === 23 && minor >= 1);
    } catch {
        return false;
    }
}

export const initCluster = async () => {
    if (cluster.isPrimary) {
        for (let i = 1; i < env.instanceCount; ++i) {
            cluster.fork();
        }
    }

    await syncSecrets();
}

export const broadcast = (message) => {
    if (!isCluster || !cluster.isPrimary || !cluster.workers) {
        return;
    }

    for (const worker of Object.values(cluster.workers)) {
        worker.send(message);
    }
}

export const send = (message) => {
    if (!isCluster) {
        return;
    }

    if (cluster.isPrimary) {
        return broadcast(message);
    } else {
        return process.send(message);
    }
}

export const waitFor = (key) => {
    return new Promise(resolve => {
        const listener = (message) => {
            if (key in message) {
                process.off('message', listener);
                return resolve(message);
            }
        }

        process.on('message', listener);
    });
}

export const mainOnMessage = (cb) => {
    for (const worker of Object.values(cluster.workers)) {
        worker.on('message', cb);
    }
}


================================================
FILE: api/src/misc/console-text.js
================================================
const ANSI = {
    RESET: "\x1b[0m",
    BRIGHT: "\x1b[1m",
    RED: "\x1b[31m",
    GREEN: "\x1b[32m",
    CYAN: "\x1b[36m",
    YELLOW: "\x1b[93m"
}

function wrap(color, text) {
    if (!ANSI[color.toUpperCase()]) {
        throw "invalid color";
    }

    return ANSI[color.toUpperCase()] + text + ANSI.RESET;
}

export function Bright(text) {
    return wrap('bright', text);
}

export function Red(text) {
    return wrap('red', text);
}

export function Green(text) {
    return wrap('green', text);
}

export function Cyan(text) {
    return wrap('cyan', text);
}

export function Yellow(text) {
    return wrap('yellow', text);
}


================================================
FILE: api/src/misc/crypto.js
================================================
import { createCipheriv, createDecipheriv } from "crypto";

const algorithm = "aes256";

export function encryptStream(plaintext, iv, secret) {
    const buff = Buffer.from(JSON.stringify(plaintext));
    const key = Buffer.from(secret, "base64url");
    const cipher = createCipheriv(algorithm, key, Buffer.from(iv, "base64url"));

    return Buffer.concat([ cipher.update(buff), cipher.final() ])
}

export function decryptStream(ciphertext, iv, secret) {
    const buff = Buffer.from(ciphertext);
    const key = Buffer.from(secret, "base64url");
    const decipher = createDecipheriv(algorithm, key, Buffer.from(iv, "base64url"));

    return Buffer.concat([ decipher.update(buff), decipher.final() ])
}


================================================
FILE: api/src/misc/file-watcher.js
================================================
import { EventEmitter } from 'node:events';
import * as fs from 'node:fs/promises';

export class FileWatcher extends EventEmitter {
    #path;
    #hasWatcher = false;
    #lastChange = new Date().getTime();

    constructor({ path, ...rest }) {
        super(rest);
        this.#path = path;
    }

    async #setupWatcher() {
        if (this.#hasWatcher)
            return;

        this.#hasWatcher = true;
        const watcher = fs.watch(this.#path);
        for await (const _ of watcher) {
            if (new Date() - this.#lastChange > 50) {
                this.emit('file-updated');
                this.#lastChange = new Date().getTime();
            }
        }
    }

    read() {
        this.#setupWatcher();
        return fs.readFile(this.#path, 'utf8');
    }

    static fromFileProtocol(url_) {
        const url = new URL(url_);
        if (url.protocol !== 'file:') {
            return;
        }

        const pathname = url.pathname === '/' ? '' : url.pathname;
        const file_path = decodeURIComponent(url.host + pathname);
        return new this({ path: file_path });
    }
}


================================================
FILE: api/src/misc/language-codes.js
================================================
// converted from this file https://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
const iso639_1to2 = {
    'aa': 'aar', 'ab': 'abk', 'af': 'afr', 'ak': 'aka', 'sq': 'sqi',
    'am': 'amh', 'ar': 'ara', 'an': 'arg', 'hy': 'hye', 'as': 'asm',
    'av': 'ava', 'ae': 'ave', 'ay': 'aym', 'az': 'aze', 'ba': 'bak',
    'bm': 'bam', 'eu': 'eus', 'be': 'bel', 'bn': 'ben', 'bi': 'bis',
    'bs': 'bos', 'br': 'bre', 'bg': 'bul', 'my': 'mya', 'ca': 'cat',
    'ch': 'cha', 'ce': 'che', 'zh': 'zho', 'cu': 'chu', 'cv': 'chv',
    'kw': 'cor', 'co': 'cos', 'cr': 'cre', 'cs': 'ces', 'da': 'dan',
    'dv': 'div', 'nl': 'nld', 'dz': 'dzo', 'en': 'eng', 'eo': 'epo',
    'et': 'est', 'ee': 'ewe', 'fo': 'fao', 'fj': 'fij', 'fi': 'fin',
    'fr': 'fra', 'fy': 'fry', 'ff': 'ful', 'ka': 'kat', 'de': 'deu',
    'gd': 'gla', 'ga': 'gle', 'gl': 'glg', 'gv': 'glv', 'el': 'ell',
    'gn': 'grn', 'gu': 'guj', 'ht': 'hat', 'ha': 'hau', 'he': 'heb',
    'hz': 'her', 'hi': 'hin', 'ho': 'hmo', 'hr': 'hrv', 'hu': 'hun',
    'ig': 'ibo', 'is': 'isl', 'io': 'ido', 'ii': 'iii', 'iu': 'iku',
    'ie': 'ile', 'ia': 'ina', 'id': 'ind', 'ik': 'ipk', 'it': 'ita',
    'jv': 'jav', 'ja': 'jpn', 'kl': 'kal', 'kn': 'kan', 'ks': 'kas',
    'kr': 'kau', 'kk': 'kaz', 'km': 'khm', 'ki': 'kik', 'rw': 'kin',
    'ky': 'kir', 'kv': 'kom', 'kg': 'kon', 'ko': 'kor', 'kj': 'kua',
    'ku': 'kur', 'lo': 'lao', 'la': 'lat', 'lv': 'lav', 'li': 'lim',
    'ln': 'lin', 'lt': 'lit', 'lb': 'ltz', 'lu': 'lub', 'lg': 'lug',
    'mk': 'mkd', 'mh': 'mah', 'ml': 'mal', 'mi': 'mri', 'mr': 'mar',
    'ms': 'msa', 'mg': 'mlg', 'mt': 'mlt', 'mn': 'mon', 'na': 'nau',
    'nv': 'nav', 'nr': 'nbl', 'nd': 'nde', 'ng': 'ndo', 'ne': 'nep',
    'nn': 'nno', 'nb': 'nob', 'no': 'nor', 'ny': 'nya', 'oc': 'oci',
    'oj': 'oji', 'or': 'ori', 'om': 'orm', 'os': 'oss', 'pa': 'pan',
    'fa': 'fas', 'pi': 'pli', 'pl': 'pol', 'pt': 'por', 'ps': 'pus',
    'qu': 'que', 'rm': 'roh', 'ro': 'ron', 'rn': 'run', 'ru': 'rus',
    'sg': 'sag', 'sa': 'san', 'si': 'sin', 'sk': 'slk', 'sl': 'slv',
    'se': 'sme', 'sm': 'smo', 'sn': 'sna', 'sd': 'snd', 'so': 'som',
    'st': 'sot', 'es': 'spa', 'sc': 'srd', 'sr': 'srp', 'ss': 'ssw',
    'su': 'sun', 'sw': 'swa', 'sv': 'swe', 'ty': 'tah', 'ta': 'tam',
    'tt': 'tat', 'te': 'tel', 'tg': 'tgk', 'tl': 'tgl', 'th': 'tha',
    'bo': 'bod', 'ti': 'tir', 'to': 'ton', 'tn': 'tsn', 'ts': 'tso',
    'tk': 'tuk', 'tr': 'tur', 'tw': 'twi', 'ug': 'uig', 'uk': 'ukr',
    'ur': 'urd', 'uz': 'uzb', 've': 'ven', 'vi': 'vie', 'vo': 'vol',
    'cy': 'cym', 'wa': 'wln', 'wo': 'wol', 'xh': 'xho', 'yi': 'yid',
    'yo': 'yor', 'za': 'zha', 'zu': 'zul',
}

const iso639_2to1 = Object.fromEntries(
    Object.entries(iso639_1to2).map(([k, v]) => [v, k])
);

const maps = {
    2: iso639_1to2,
    3: iso639_2to1,
}

export const convertLanguageCode = (code) => {
    code = code?.split("-")[0]?.split("_")[0] || "";
    return maps[code.length]?.[code.toLowerCase()] || null;
}


================================================
FILE: api/src/misc/load-from-fs.js
================================================
import * as fs from "fs";
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const root = join(
    dirname(fileURLToPath(import.meta.url)),
    '../../'
);

export function loadFile(path) {
    return fs.readFileSync(join(root, path), 'utf-8')
}

export function loadJSON(path) {
    try {
        return JSON.parse(loadFile(path))
    } catch {
        return false
    }
}


================================================
FILE: api/src/misc/randomize-ciphers.js
================================================
import tls from 'node:tls';
import { randomBytes } from 'node:crypto';

const ORIGINAL_CIPHERS = tls.DEFAULT_CIPHERS;

// How many ciphers from the top of the list to shuffle.
// The remaining ciphers are left in the original order.
const TOP_N_SHUFFLE = 8;

// Modified variation of https://stackoverflow.com/a/12646864
const shuffleArray = (array) => {
    for (let i = array.length - 1; i > 0; i--) {
        const j = randomBytes(4).readUint32LE() % array.length;
        [array[i], array[j]] = [array[j], array[i]];
    }

    return array;
}

export const randomizeCiphers = () => {
    do {
        const cipherList = ORIGINAL_CIPHERS.split(':');
        const shuffled = shuffleArray(cipherList.slice(0, TOP_N_SHUFFLE));
        const retained = cipherList.slice(TOP_N_SHUFFLE);

        tls.DEFAULT_CIPHERS = [ ...shuffled, ...retained ].join(':');
    } while (tls.DEFAULT_CIPHERS === ORIGINAL_CIPHERS);
}


================================================
FILE: api/src/misc/run-test.js
================================================
import { normalizeRequest } from "../processing/request.js";
import match from "../processing/match.js";
import { extract } from "../processing/url.js";

export async function runTest(url, params, expect) {
    const { success, data: normalized } = await normalizeRequest({ url, ...params });
    if (!success) {
        throw "invalid request";
    }

    const parsed = extract(normalized.url);
    if (parsed === null) {
        throw `invalid url: ${normalized.url}`;
    }

    const result = await match({
        host: parsed.host,
        patternMatch: parsed.patternMatch,
        params: normalized,
    });

    let error = [];
    if (expect.status !== result.body.status) {
        const detail = `${expect.status} (expected) != ${result.body.status} (actual)`;
        error.push(`status mismatch: ${detail}`);

        if (result.body.status === 'error') {
            error.push(`error code: ${result.body?.error?.code}`);
        }
    }

    if (expect.errorCode && expect.errorCode !== result.body?.error?.code) {
        const detail = `${expect.errorCode} (expected) != ${result.body.error.code} (actual)`
        error.push(`error mismatch: ${detail}`);
    }

    if (expect.code !== result.status) {
        const detail = `${expect.code} (expected) != ${result.status} (actual)`;
        error.push(`status code mismatch: ${detail}`);
    }

    if (error.length) {
        if (result.body.text) {
            error.push(`error message: ${result.body.text}`);
        }

        throw error.join('\n');
    }

    if (result.body.status === 'tunnel') {
        // TODO: stream testing
    }
}


================================================
FILE: api/src/misc/utils.js
================================================
import { request } from "undici";
const redirectStatuses = new Set([301, 302, 303, 307, 308]);

export async function getRedirectingURL(url, dispatcher, headers) {
    const params = {
        dispatcher,
        method: 'HEAD',
        headers,
        redirect: 'manual'
    };
    const getParams = {
        ...params,
        method: 'GET',
    };

    const callback = (r) => {
        if (redirectStatuses.has(r.statusCode) && r.headers['location']) {
            return r.headers['location'];
        }
    }

    /*
        try request() with HEAD & GET,
        then do the same with fetch
        (fetch is required for shortened reddit links)
    */

    let location = await request(url, params)
        .then(callback).catch(() => null);

    location ??= await request(url, getParams)
        .then(callback).catch(() => null);

    location ??= await fetch(url, params)
        .then(callback).catch(() => null);

    location ??= await fetch(url, getParams)
        .then(callback).catch(() => null);

    return location;
}

export function merge(a, b) {
    for (const k of Object.keys(b)) {
        if (Array.isArray(b[k])) {
            a[k] = [...(a[k] ?? []), ...b[k]];
        } else if (typeof b[k] === 'object') {
            a[k] = merge(a[k], b[k]);
        } else {
            a[k] = b[k];
        }
    }

    return a;
}

export function splitFilenameExtension(filename) {
    const parts = filename.split('.');
    const ext = parts.pop();

    if (!parts.length) {
        return [ ext, "" ]
    } else {
        return [ parts.join('.'), ext ]
    }
}

export function zip(a, b) {
    return a.map((value, i) => [ value, b[i] ]);
}

export function isURL(input) {
    try {
        new URL(input);
        return true;
    } catch {
        return false;
    }
}


================================================
FILE: api/src/processing/cookie/cookie.js
================================================
import { strict as assert } from 'node:assert';

export default class Cookie {
    constructor(input) {
        assert(typeof input === 'object');
        this._values = {};

        for (const [ k, v ] of Object.entries(input))
            this.set(k, v);
    }

    set(key, value) {
        const old = this._values[key];
        if (old === value)
            return false;

        this._values[key] = value;
        return true;
    }

    unset(keys) {
        for (const key of keys) delete this._values[key]
    }

    static fromString(str) {
        const obj = {};

        str.split('; ').forEach(cookie => {
            const key = cookie.split('=')[0];
            const value = cookie.split('=').splice(1).join('=');
            obj[key] = value
        })

        return new Cookie(obj)
    }

    toString() {
        return Object.entries(this._values).map(([ name, value ]) => `${name}=${value}`).join('; ')
    }

    toJSON() {
        return this.toString()
    }

    values() {
        return Object.freeze({ ...this._values })
    }
}


================================================
FILE: api/src/processing/cookie/manager.js
================================================
import Cookie from './cookie.js';

import { readFile, writeFile } from 'fs/promises';
import { Red, Green, Yellow } from '../../misc/console-text.js';
import { parse as parseSetCookie, splitCookiesString } from 'set-cookie-parser';
import * as cluster from '../../misc/cluster.js';
import { isCluster } from '../../config.js';

const WRITE_INTERVAL = 60000;
const VALID_SERVICES = new Set([
    'instagram',
    'instagram_bearer',
    'reddit',
    'twitter',
    'youtube',
    'vimeo_bearer',
]);

const invalidCookies = {};
let cookies = {}, dirty = false, intervalId;

function writeChanges(cookiePath) {
    if (!dirty) return;
    dirty = false;

    const cookieData = JSON.stringify({ ...cookies, ...invalidCookies }, null, 4);
    writeFile(cookiePath, cookieData).catch((e) => {
        console.warn(`${Yellow('[!]')} failed writing updated cookies to storage`);
        console.warn(e);
        clearInterval(intervalId);
        intervalId = null;
    })
}

const setupMain = async (cookiePath) => {
    try {
        cookies = await readFile(cookiePath, 'utf8');
        cookies = JSON.parse(cookies);
        for (const serviceName in cookies) {
            if (!VALID_SERVICES.has(serviceName)) {
                console.warn(`${Yellow('[!]')} ignoring unknown service in cookie file: ${serviceName}`);
            } else if (!Array.isArray(cookies[serviceName])) {
                console.warn(`${Yellow('[!]')} ${serviceName} in cookies file is not an array, ignoring it`);
            } else if (cookies[serviceName].some(c => typeof c !== 'string')) {
                console.warn(`${Yellow('[!]')} some cookie for ${serviceName} contains non-string value in cookies file`);
            } else continue;

            invalidCookies[serviceName] = cookies[serviceName];
            delete cookies[serviceName];
        }

        if (!intervalId) {
            intervalId = setInterval(() => writeChanges(cookiePath), WRITE_INTERVAL);
        }

        cluster.broadcast({ cookies });

        console.log(`${Green('[✓]')} cookies loaded successfully!`);
    } catch (e) {
        console.error(`${Yellow('[!]')} failed to load cookies.`);
        console.error('error:', e);
    }
}

const setupWorker = async () => {
    cookies = (await cluster.waitFor('cookies')).cookies;
}

export const loadFromFile = async (path) => {
    if (cluster.isPrimary) {
        await setupMain(path);
    } else if (cluster.isWorker) {
        await setupWorker();
    }

    dirty = false;
}

export const setup = async (path) => {
    await loadFromFile(path);

    if (isCluster) {
        const messageHandler = (message) => {
            if ('cookieUpdate' in message) {
                const { cookieUpdate } = message;

                if (cluster.isPrimary) {
                    dirty = true;
                    cluster.broadcast({ cookieUpdate });
                }

                const { service, idx, cookie } = cookieUpdate;
                cookies[service][idx] = cookie;
            }
        }

        if (cluster.isPrimary) {
            cluster.mainOnMessage(messageHandler);
        } else {
            process.on('message', messageHandler);
        }
    }
}

export function getCookie(service) {
    if (!VALID_SERVICES.has(service)) {
        console.error(
            `${Red('[!]')} ${service} not in allowed services list for cookies.`
            + ' if adding a new cookie type, include it there.'
        );
        return;
    }

    if (!cookies[service] || !cookies[service].length) return;

    const idx = Math.floor(Math.random() * cookies[service].length);

    const cookie = cookies[service][idx];
    if (typeof cookie === 'string') {
        cookies[service][idx] = Cookie.fromString(cookie);
    }

    cookies[service][idx].meta = { service, idx };
    return cookies[service][idx];
}

export function updateCookieValues(cookie, values) {
    let changed = false;

    for (const [ key, value ] of Object.entries(values)) {
        changed = cookie.set(key, value) || changed;
    }

    if (changed && cookie.meta) {
        dirty = true;
        if (isCluster) {
            const message = { cookieUpdate: { ...cookie.meta, cookie } };
            cluster.send(message);
        }
    }

    return changed;
}

export function updateCookie(cookie, headers) {
    if (!cookie) return;

    const parsed = parseSetCookie(
        splitCookiesString(headers.get('set-cookie')),
        { decodeValues: false }
    ), values = {}

    cookie.unset(parsed.filter(c => c.expires < new Date()).map(c => c.name));
    parsed.filter(c => !c.expires || c.expires > new Date()).forEach(c => values[c.name] = c.value);

    updateCookieValues(cookie, values);
}


================================================
FILE: api/src/processing/create-filename.js
================================================
// characters that are disallowed on windows:
// https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions
const characterMap = {
    '<':  '<',
    '>':  '>',
    ':':  ':',
    '"':  '"',
    '/':  '/',
    '\\': '\',
    '|': '|',
    '?': '?',
    '*': '*'
};

export const sanitizeString = (string) => {
    // remove any potential control characters the string might contain
    string = string.replace(/[\u0000-\u001F\u007F-\u009F]/g, "");

    for (const [ char, replacement ] of Object.entries(characterMap)) {
        string = string.replaceAll(char, replacement);
    }

    return string;
}

export default (f, style, isAudioOnly, isAudioMuted) => {
    let filename = '';

    let infoBase = [f.service, f.id];
    let classicTags = [...infoBase];
    let basicTags = [];

    let title = sanitizeString(f.title);

    if (f.author) {
        title += ` - ${sanitizeString(f.author)}`;
    }

    if (f.resolution) {
        classicTags.push(f.resolution);
    }

    if (f.qualityLabel) {
        basicTags.push(f.qualityLabel);
    }

    if (f.youtubeFormat) {
        classicTags.push(f.youtubeFormat);
        basicTags.push(f.youtubeFormat);
    }

    if (isAudioMuted) {
        classicTags.push("mute");
        basicTags.push("mute");
    } else if (f.youtubeDubName) {
        classicTags.push(f.youtubeDubName);
        basicTags.push(f.youtubeDubName);
    }

    switch (style) {
        default:
        case "classic":
            if (isAudioOnly) {
                if (f.youtubeDubName) {
                    infoBase.push(f.youtubeDubName);
                }
                return `${infoBase.join("_")}_audio`;
            }
            filename = classicTags.join("_");
            break;
        case "basic":
            if (isAudioOnly) return title;
            filename = `${title} (${basicTags.join(", ")})`;
            break;
        case "pretty":
            if (isAudioOnly) return `${title} (${infoBase[0]})`;
            filename = `${title} (${[...basicTags, infoBase[0]].join(", ")})`;
            break;
        case "nerdy":
            if (isAudioOnly) return `${title} (${infoBase.join(", ")})`;
            filename = `${title} (${basicTags.concat(infoBase).join(", ")})`;
            break;
    }
    return `${filename}.${f.extension}`;
}


================================================
FILE: api/src/processing/helpers/youtube-session.js
================================================
import * as cluster from "../../misc/cluster.js";

import { Agent } from "undici";
import { env } from "../../config.js";
import { Green, Yellow } from "../../misc/console-text.js";

const defaultAgent = new Agent();

let session;

const validateSession = (sessionResponse) => {
    if (!sessionResponse.potoken) {
        throw "no poToken in session response";
    }

    if (!sessionResponse.visitor_data) {
        throw "no visitor_data in session response";
    }

    if (!sessionResponse.updated) {
        throw "no last update timestamp in session response";
    }

    // https://github.com/iv-org/youtube-trusted-session-generator/blob/c2dfe3f/potoken_generator/main.py#L25
    if (sessionResponse.potoken.length < 160) {
        console.error(`${Yellow('[!]')} poToken is too short and might not work (${new Date().toISOString()})`);
    }
}

const updateSession = (newSession) => {
    session = newSession;
}

const loadSession = async () => {
    const sessionServerUrl = new URL(env.ytSessionServer);
    sessionServerUrl.pathname = "/token";

    const newSession = await fetch(
        sessionServerUrl,
        { dispatcher: defaultAgent }
    ).then(a => a.json());

    validateSession(newSession);

    if (!session || session.updated < newSession?.updated) {
        cluster.broadcast({ youtube_session: newSession });
        updateSession(newSession);
    }
}

const wrapLoad = (initial = false) => {
    loadSession()
    .then(() => {
        if (initial) {
            console.log(`${Green('[✓]')} poToken & visitor_data loaded successfully!`);
        }
    })
    .catch((e) => {
        console.error(`${Yellow('[!]')} Failed loading poToken & visitor_data at ${new Date().toISOString()}.`);
        console.error('Error:', e);
    })
}

export const getYouTubeSession = () => {
    return session;
}

export const setup = () => {
    if (cluster.isPrimary) {
        wrapLoad(true);
        if (env.ytSessionReloadInterval > 0) {
            setInterval(wrapLoad, env.ytSessionReloadInterval * 1000);
        }
    } else if (cluster.isWorker) {
        process.on('message', (message) => {
            if ('youtube_session' in message) {
                updateSession(message.youtube_session);
            }
        });
    }
}


================================================
FILE: api/src/processing/match-action.js
================================================
import createFilename from "./create-filename.js";

import { createResponse } from "./request.js";
import { audioIgnore } from "./service-config.js";
import { createStream } from "../stream/manage.js";
import { splitFilenameExtension } from "../misc/utils.js";
import { convertLanguageCode } from "../misc/language-codes.js";

const extraProcessingTypes = new Set(["merge", "remux", "mute", "audio", "gif"]);

export default function({
    r,
    host,
    audioFormat,
    isAudioOnly,
    isAudioMuted,
    disableMetadata,
    filenameStyle,
    convertGif,
    requestIP,
    audioBitrate,
    alwaysProxy,
    localProcessing,
}) {
    let action,
        responseType = "tunnel",
        defaultParams = {
            url: r.urls,
            headers: r.headers,
            service: host,
            filename: r.filenameAttributes ?
                    createFilename(r.filenameAttributes, filenameStyle, isAudioOnly, isAudioMuted) : r.filename,
            fileMetadata: !disableMetadata ? r.fileMetadata : false,
            requestIP,
            originalRequest: r.originalRequest,
            subtitles: r.subtitles,
            cover: !disableMetadata ? r.cover : false,
            cropCover: !disableMetadata ? r.cropCover : false,
        },
        params = {};

    if (r.isPhoto) action = "photo";
    else if (r.picker) action = "picker"
    else if (r.isGif && convertGif) action = "gif";
    else if (isAudioOnly) action = "audio";
    else if (isAudioMuted) action = "muteVideo";
    else if (r.isHLS) action = "hls";
    else action = "video";

    if (action === "picker" || action === "audio") {
        if (!r.filenameAttributes) defaultParams.filename = r.audioFilename;
        defaultParams.audioFormat = audioFormat;
    }

    if (action === "muteVideo" && isAudioMuted && !r.filenameAttributes) {
        const [ name, ext ] = splitFilenameExtension(r.filename);
        defaultParams.filename = `${name}_mute.${ext}`;
    } else if (action === "gif") {
        const [ name ] = splitFilenameExtension(r.filename);
        defaultParams.filename = `${name}.gif`;
    }

    switch (action) {
        default:
            return createResponse("error", {
                code: "error.api.fetch.empty"
            });

        case "photo":
            params = { type: "proxy" };
            break;

        case "gif":
            params = { type: "gif" };
            break;

        case "hls":
            params = {
                type: Array.isArray(r.urls) ? "merge" : "remux",
                isHLS: true,
            }
            break;

        case "muteVideo":
            let muteType = "mute";
            if (Array.isArray(r.urls) && !r.isHLS) {
                muteType = "proxy";
            }
            params = {
                type: muteType,
                url: Array.isArray(r.urls) ? r.urls[0] : r.urls,
                isHLS: r.isHLS
            }
            if (host === "reddit" && r.typeId === "redirect") {
                responseType = "redirect";
            }
            break;

        case "picker":
            responseType = "picker";
            switch (host) {
                case "instagram":
                case "twitter":
                case "snapchat":
                case "bsky":
                case "xiaohongshu":
                    params = { picker: r.picker };
                    break;

                case "tiktok":
                    let audioStreamType = "audio";
                    if (r.bestAudio === "mp3" && audioFormat === "best") {
                        audioFormat = "mp3";
                        audioStreamType = "proxy"
                    }
                    params = {
                        picker: r.picker,
                        url: createStream({
                            service: "tiktok",
                            type: audioStreamType,
                            url: r.urls,
                            headers: r.headers,
                            filename: `${r.audioFilename}.${audioFormat}`,
                            isAudioOnly: true,
                            audioFormat,
                            audioBitrate
                        })
                    }
                    break;
            }
            break;

        case "video":
            switch (host) {
                case "bilibili":
                    params = { type: "merge" };
                    break;

                case "youtube":
                    params = { type: r.type };
                    break;

                case "reddit":
                    responseType = r.typeId;
                    params = { type: r.type };
                    break;

                case "vimeo":
                    if (Array.isArray(r.urls)) {
                        params = { type: "merge" };
                    } else if (r.subtitles) {
                        params = { type: "remux" };
                    } else {
                        responseType = "redirect";
                    }
                    break;

                case "twitter":
                    if (r.type === "remux") {
                        params = { type: r.type };
                    } else {
                        responseType = "redirect";
                    }
                    break;

                case "loom":
                    if (r.subtitles) {
                        params = { type: "remux" };
                    } else {
                        responseType = "redirect";
                    }
                    break;

                case "vk":
                case "tiktok":
                    params = {
                        type: r.subtitles ? "remux" : "proxy"
                    };
                    break;

                case "ok":
                case "xiaohongshu":
                case "newgrounds":
                    params = { type: "proxy" };
                    break;

                case "facebook":
                case "instagram":
                case "tumblr":
                case "pinterest":
                case "streamable":
                case "snapchat":
                case "twitch":
                    responseType = "redirect";
                    break;
            }
            break;

        case "audio":
            if (audioIgnore.has(host) || (host === "reddit" && r.typeId === "redirect")) {
                return createResponse("error", {
                    code: "error.api.service.audio_not_supported"
                })
            }

            let processType = "audio";
            let copy = false;

            if (audioFormat === "best") {
                const serviceBestAudio = r.bestAudio;

                if (serviceBestAudio) {
                    audioFormat = serviceBestAudio;
                    processType = "proxy";

                    if (host === "soundcloud") {
                        processType = "audio";
                        copy = true;
                    }
                } else {
                    audioFormat = "m4a";
                    copy = true;
                }
            }

            if (r.isHLS || host === "vimeo") {
                copy = false;
                processType = "audio";
            }

            params = {
                type: processType,
                url: Array.isArray(r.urls) ? r.urls[1] : r.urls,

                audioBitrate,
                audioCopy: copy,
                audioFormat,

                isHLS: r.isHLS,
            }
            break;
    }

    if (defaultParams.filename && (action === "picker" || action === "audio")) {
        defaultParams.filename += `.${audioFormat}`;
    }

    // alwaysProxy is set to true in match.js if localProcessing is forced
    if (alwaysProxy && responseType === "redirect") {
        responseType = "tunnel";
        params.type = "proxy";
    }

    // TODO: add support for HLS
    // (very painful)
    if (!params.isHLS && responseType !== "picker") {
        const isPreferredWithExtra =
            localProcessing === "preferred" && extraProcessingTypes.has(params.type);

        if (localProcessing === "forced" || isPreferredWithExtra) {
            responseType = "local-processing";
        }
    }

    // extractors usually return ISO 639-1 language codes,
    // but video players expect ISO 639-2, so we convert them here
    const sublanguage = defaultParams.fileMetadata?.sublanguage;
    if (sublanguage && sublanguage.length !== 3) {
        const code = convertLanguageCode(sublanguage);
        if (code) {
            defaultParams.fileMetadata.sublanguage = code;
        } else {
            // if a language code couldn't be converted,
            // then we don't want it at all
            delete defaultParams.fileMetadata.sublanguage;
        }
    }

    return createResponse(
        responseType,
        { ...defaultParams, ...params }
    );
}


================================================
FILE: api/src/processing/match.js
================================================
import { strict as assert } from "node:assert";

import { env } from "../config.js";
import { createResponse } from "../processing/request.js";

import { testers } from "./service-patterns.js";
import matchAction from "./match-action.js";

import { friendlyServiceName } from "./service-alias.js";

import bilibili from "./services/bilibili.js";
import reddit from "./services/reddit.js";
import twitter from "./services/twitter.js";
import youtube from "./services/youtube.js";
import vk from "./services/vk.js";
import ok from "./services/ok.js";
import tiktok from "./services/tiktok.js";
import tumblr from "./services/tumblr.js";
import vimeo from "./services/vimeo.js";
import soundcloud from "./services/soundcloud.js";
import instagram from "./services/instagram.js";
import pinterest from "./services/pinterest.js";
import streamable from "./services/streamable.js";
import twitch from "./services/twitch.js";
import rutube from "./services/rutube.js";
import dailymotion from "./services/dailymotion.js";
import snapchat from "./services/snapchat.js";
import loom from "./services/loom.js";
import facebook from "./services/facebook.js";
import bluesky from "./services/bluesky.js";
import xiaohongshu from "./services/xiaohongshu.js";
import newgrounds from "./services/newgrounds.js";

let freebind;

export default async function({ host, patternMatch, params, authType }) {
    const { url } = params;
    assert(url instanceof URL);
    let dispatcher, requestIP;

    if (env.freebindCIDR) {
        if (!freebind) {
            freebind = await import('freebind');
        }

        requestIP = freebind.ip.random(env.freebindCIDR);
        dispatcher = freebind.dispatcherFromIP(requestIP, { strict: false });
    }

    try {
        let r,
            isAudioOnly = params.downloadMode === "audio",
            isAudioMuted = params.downloadMode === "mute";

        if (!testers[host]) {
            return createResponse("error", {
                code: "error.api.service.unsupported"
            });
        }
        if (!(testers[host](patternMatch))) {
            return createResponse("error", {
                code: "error.api.link.unsupported",
                context: {
                    service: friendlyServiceName(host),
                }
            });
        }

        // youtubeHLS will be fully removed in the future
        let youtubeHLS = params.youtubeHLS;
        const hlsEnv = env.enableDeprecatedYoutubeHls;

        if (hlsEnv === "never" || (hlsEnv === "key" && authType !== "key")) {
            youtubeHLS = false;
        }

        const subtitleLang =
            params.subtitleLang !== "none" ? params.subtitleLang : undefined;

        switch (host) {
            case "twitter":
                r = await twitter({
                    id: patternMatch.id,
                    index: patternMatch.index - 1,
                    toGif: !!params.convertGif,
                    alwaysProxy: params.alwaysProxy,
                    dispatcher,
                    subtitleLang
                });
                break;

            case "vk":
                r = await vk({
                    ownerId: patternMatch.ownerId,
                    videoId: patternMatch.videoId,
                    accessKey: patternMatch.accessKey,
                    quality: params.videoQuality,
                    subtitleLang,
                });
                break;

            case "ok":
                r = await ok({
                    id: patternMatch.id,
                    quality: params.videoQuality
                });
                break;

            case "bilibili":
                r = await bilibili(patternMatch);
                break;

            case "youtube":
                let fetchInfo = {
                    dispatcher,
                    id: patternMatch.id.slice(0, 11),
                    quality: params.videoQuality,
                    codec: params.youtubeVideoCodec,
                    container: params.youtubeVideoContainer,
                    isAudioOnly,
                    isAudioMuted,
                    dubLang: params.youtubeDubLang,
                    youtubeHLS,
                    subtitleLang,
                }

                if (url.hostname === "music.youtube.com" || isAudioOnly) {
                    fetchInfo.quality = "1080";
                    fetchInfo.codec = "vp9";
                    fetchInfo.isAudioOnly = true;
                    fetchInfo.isAudioMuted = false;

                    if (env.ytAllowBetterAudio && params.youtubeBetterAudio) {
                        fetchInfo.quality = "max";
                    }
                }

                r = await youtube(fetchInfo);
                break;

            case "reddit":
                r = await reddit({
                    ...patternMatch,
                    dispatcher,
                });
                break;

            case "tiktok":
                r = await tiktok({
                    postId: patternMatch.postId,
                    shortLink: patternMatch.shortLink,
                    fullAudio: params.tiktokFullAudio,
                    isAudioOnly,
                    h265: params.allowH265,
                    alwaysProxy: params.alwaysProxy,
                    subtitleLang,
                });
                break;

            case "tumblr":
                r = await tumblr({
                    id: patternMatch.id,
                    user: patternMatch.user,
                    url
                });
                break;

            case "vimeo":
                r = await vimeo({
                    id: patternMatch.id.slice(0, 11),
                    password: patternMatch.password,
                    quality: params.videoQuality,
                    isAudioOnly,
                    subtitleLang,
                });
                break;

            case "soundcloud":
                isAudioOnly = true;
                isAudioMuted = false;
                r = await soundcloud({
                    ...patternMatch,
                    format: params.audioFormat,
                });
                break;

            case "instagram":
                r = await instagram({
                    ...patternMatch,
                    quality: params.videoQuality,
                    alwaysProxy: params.alwaysProxy,
                    dispatcher
                })
                break;

            case "pinterest":
                r = await pinterest({
                    id: patternMatch.id,
                    shortLink: patternMatch.shortLink || false
                });
                break;

            case "streamable":
                r = await streamable({
                    id: patternMatch.id,
                    quality: params.videoQuality,
                    isAudioOnly,
                });
                break;

            case "twitch":
                r = await twitch({
                    clipId: patternMatch.clip || false,
                    quality: params.videoQuality,
                    isAudioOnly,
                });
                break;

            case "rutube":
                r = await rutube({
                    id: patternMatch.id,
                    yappyId: patternMatch.yappyId,
                    key: patternMatch.key,
                    quality: params.videoQuality,
                    isAudioOnly,
                    subtitleLang,
                });
                break;

            case "dailymotion":
                r = await dailymotion(patternMatch);
                break;

            case "snapchat":
                r = await snapchat({
                    ...patternMatch,
                    alwaysProxy: params.alwaysProxy,
                });
                break;

            case "loom":
                r = await loom({
                    id: patternMatch.id,
                    subtitleLang,
                });
                break;

            case "facebook":
                r = await facebook({
                    ...patternMatch,
                    dispatcher
                });
                break;

            case "bsky":
                r = await bluesky({
                    ...patternMatch,
                    alwaysProxy: params.alwaysProxy,
                    dispatcher
                });
                break;

            case "xiaohongshu":
                r = await xiaohongshu({
                    ...patternMatch,
                    h265: params.allowH265,
                    isAudioOnly,
                    dispatcher,
                });
                break;

            case "newgrounds":
                r = await newgrounds({
                    ...patternMatch,
                    quality: params.videoQuality,
                });
                break;

            default:
                return createResponse("error", {
                    code: "error.api.service.unsupported"
                });
        }

        if (r.isAudioOnly) {
            isAudioOnly = true;
            isAudioMuted = false;
        }

        if (r.error && r.critical) {
            return createResponse("critical", {
                code: `error.api.${r.error}`,
            })
        }

        if (r.error) {
            let context;
            switch(r.error) {
                case "content.too_long":
                    context = {
                        limit: parseFloat((env.durationLimit / 60).toFixed(2)),
                    }
                    break;

                case "fetch.fail":
                case "fetch.rate":
                case "fetch.critical":
                case "link.unsupported":
                case "content.video.unavailable":
                    context = {
                        service: friendlyServiceName(host),
                    }
                    break;
            }

            return createResponse("error", {
                code: `error.api.${r.error}`,
                context,
            })
        }

        let localProcessing = params.localProcessing;
        const lpEnv = env.forceLocalProcessing;
        const shouldForceLocal = lpEnv === "always" || (lpEnv === "session" && authType === "session");
        const localDisabled = (!localProcessing || localProcessing === "disabled");

        if (shouldForceLocal && localDisabled) {
            localProcessing = "preferred";
        }

        return matchAction({
            r,
            host,
            audioFormat: params.audioFormat,
            isAudioOnly,
            isAudioMuted,
            disableMetadata: params.disableMetadata,
            filenameStyle: params.filenameStyle,
            convertGif: params.convertGif,
            requestIP,
            audioBitrate: params.audioBitrate,
            alwaysProxy: params.alwaysProxy || localProcessing === "forced",
            localProcessing,
        })
    } catch {
        return createResponse("error", {
            code: "error.api.fetch.critical",
            context: {
                service: friendlyServiceName(host),
            }
        })
    }
}


================================================
FILE: api/src/processing/request.js
================================================
import mime from "mime";
import ipaddr from "ipaddr.js";

import { apiSchema } from "./schema.js";
import { createProxyTunnels, createStream } from "../stream/manage.js";

export function createResponse(responseType, responseData) {
    const internalError = (code) => {
        return {
            status: 500,
            body: {
                status: "error",
                error: {
                    code: code || "error.api.fetch.critical.core",
                },
                critical: true
            }
        }
    }

    try {
        let status = 200,
            response = {};

        if (responseType === "error") {
            status = 400;
        }

        switch (responseType) {
            case "error":
                response = {
                    error: {
                        code: responseData?.code,
                        context: responseData?.context,
                    }
                }
                break;

            case "redirect":
                response = {
                    url: responseData?.url,
                    filename: responseData?.filename
                }
                break;

            case "tunnel":
                response = {
                    url: createStream(responseData),
                    filename: responseData?.filename
                }
                break;

            case "local-processing":
                response = {
                    type: responseData?.type,
                    service: responseData?.service,
                    tunnel: createProxyTunnels(responseData),

                    output: {
                        type: mime.getType(responseData?.filename) || undefined,
                        filename: responseData?.filename,
                        metadata: responseData?.fileMetadata || undefined,
                        subtitles: !!responseData?.subtitles || undefined,
                    },

                    audio: {
                        copy: responseData?.audioCopy,
                        format: responseData?.audioFormat,
                        bitrate: responseData?.audioBitrate,
                        cover: !!responseData?.cover || undefined,
                        cropCover: !!responseData?.cropCover || undefined,
                    },

                    isHLS: responseData?.isHLS,
                }

                if (!response.audio.format) {
                    if (response.type === "audio") {
                        // audio response without a format is invalid
                        return internalError();
                    }
                    delete response.audio;
                }

                if (!response.output.type || !response.output.filename) {
                    // response without a type or filename is invalid
                    return internalError();
                }
                break;

            case "picker":
                response = {
                    picker: responseData?.picker,
                    audio: responseData?.url,
                    audioFilename: responseData?.filename
                }
                break;

            case "critical":
                return internalError(responseData?.code);

            default:
                throw "unreachable"
        }

        return {
            status,
            body: {
                status: responseType,
                ...response
            }
        }
    } catch {
        return internalError();
    }
}

export function normalizeRequest(request) {
    // TODO: remove after backwards compatibility period
    if ("localProcessing" in request && typeof request.localProcessing === "boolean") {
        request.localProcessing = request.localProcessing ? "preferred" : "disabled";
    }

    return apiSchema.safeParseAsync(request).catch(() => (
        { success: false }
    ));
}

export function getIP(req, prefix = 56) {
    const strippedIP = req.ip.replace(/^::ffff:/, '');
    const ip = ipaddr.parse(strippedIP);
    if (ip.kind() === 'ipv4') {
        return strippedIP;
    }

    const v6Bytes = ip.toByteArray();
          v6Bytes.fill(0, prefix / 8);

    return ipaddr.fromByteArray(v6Bytes).toString();
}


================================================
FILE: api/src/processing/schema.js
================================================
import { z } from "zod";
import { normalizeURL } from "./url.js";

export const apiSchema = z.object({
    url: z.string()
          .min(1)
          .transform(url => normalizeURL(url)),

    audioBitrate: z.enum(
        ["320", "256", "128", "96", "64", "8"]
    ).default("128"),

    audioFormat: z.enum(
        ["best", "mp3", "ogg", "wav", "opus"]
    ).default("mp3"),

    downloadMode: z.enum(
        ["auto", "audio", "mute"]
    ).default("auto"),

    filenameStyle: z.enum(
        ["classic", "pretty", "basic", "nerdy"]
    ).default("basic"),

    youtubeVideoCodec: z.enum(
        ["h264", "av1", "vp9"]
    ).default("h264"),

    youtubeVideoContainer: z.enum(
        ["auto", "mp4", "webm", "mkv"]
    ).default("auto"),

    videoQuality: z.enum(
        ["max", "4320", "2160", "1440", "1080", "720", "480", "360", "240", "144"]
    ).default("1080"),

    localProcessing: z.enum(
        ["disabled", "preferred", "forced"]
    ).default("disabled"),

    youtubeDubLang: z.string()
                     .min(2)
                     .max(8)
                     .regex(/^[0-9a-zA-Z\-]+$/)
                     .optional(),

    subtitleLang: z.string()
                     .min(2)
                     .max(8)
                     .regex(/^[0-9a-zA-Z\-]+$/)
                     .optional(),

    disableMetadata: z.boolean().default(false),

    allowH265: z.boolean().default(false),
    convertGif: z.boolean().default(true),
    tiktokFullAudio: z.boolean().default(false),

    alwaysProxy: z.boolean().default(false),

    youtubeHLS: z.boolean().default(false),
    youtubeBetterAudio: z.boolean().default(false),
})
.strict();


================================================
FILE: api/src/processing/service-alias.js
================================================
const friendlyNames = {
    bsky: "bluesky",
    twitch: "twitch clips"
}

export const friendlyServiceName = (service) => {
    if (service in friendlyNames) {
        return friendlyNames[service];
    }
    return service;
}


================================================
FILE: api/src/processing/service-config.js
================================================
import UrlPattern from "url-pattern";

export const audioIgnore = new Set(["vk", "ok", "loom"]);
export const hlsExceptions = new Set(["dailymotion", "vimeo", "rutube", "bsky", "youtube"]);

export const services = {
    bilibili: {
        patterns: [
            "video/:comId",
            "video/:comId?p=:partId",
            "_shortLink/:comShortLink",
            "_tv/:lang/video/:tvId",
            "_tv/video/:tvId"
        ],
        subdomains: ["m"],
    },
    bsky: {
        patterns: [
            "profile/:user/post/:post"
        ],
        tld: "app",
    },
    dailymotion: {
        patterns: ["video/:id"],
    },
    facebook: {
        patterns: [
            "_shortLink/:shortLink",
            ":username/videos/:caption/:id",
            ":username/videos/:id",
            "reel/:id",
            "share/:shareType/:id"
        ],
        subdomains: ["web", "m"],
        altDomains: ["fb.watch"],
    },
    instagram: {
        patterns: [
            "p/:postId",
            "tv/:postId",
            "reel/:postId",
            "reels/:postId",
            "stories/:username/:storyId",

            /*
                share & username links use the same url pattern,
                so we test the share pattern first, cuz id type is different.
                however, if someone has the "share" username and the user
                somehow gets a link of this ancient style, it's joever.
            */

            "share/:shareId",
            "share/p/:shareId",
            "share/reel/:shareId",

            ":username/p/:postId",
            ":username/reel/:postId",
        ],
        altDomains: ["ddinstagram.com"],
    },
    loom: {
        patterns: ["share/:id", "embed/:id"],
    },
    ok: {
        patterns: [
            "video/:id",
            "videoembed/:id"
        ],
        tld: "ru",
    },
    pinterest: {
        patterns: [
            "pin/:id",
            "pin/:id/:garbage",
            "url_shortener/:shortLink"
        ],
    },
    newgrounds: {
        patterns: [
            "portal/view/:id",
            "audio/listen/:audioId",
        ]
    },
    reddit: {
        patterns: [
            "comments/:id",

            "r/:sub/comments/:id",
            "r/:sub/comments/:id/:title",
            "r/:sub/comments/:id/comment/:commentId",

            "user/:user/comments/:id",
            "user/:user/comments/:id/:title",
            "user/:user/comments/:id/comment/:commentId",

            "r/u_:user/comments/:id",
            "r/u_:user/comments/:id/:title",
            "r/u_:user/comments/:id/comment/:commentId",

            "r/:sub/s/:shareId",

            "video/:shortId",
        ],
        subdomains: "*",
    },
    rutube: {
        patterns: [
            "video/:id",
            "play/embed/:id",
            "shorts/:id",
            "yappy/:yappyId",
            "video/private/:id?p=:key",
            "video/private/:id"
        ],
        tld: "ru",
    },
    snapchat: {
        patterns: [
            ":shortLink",
            "spotlight/:spotlightId",
            "add/:username/:storyId",
            "u/:username/:storyId",
            "add/:username",
            "u/:username",
            "t/:shortLink",
            "o/:spotlightId",
        ],
        subdomains: ["t", "story"],
    },
    soundcloud: {
        patterns: [
            ":author/:song/s-:accessKey",
            ":author/:song",
            ":shortLink"
        ],
        subdomains: ["on", "m"],
    },
    streamable: {
        patterns: [
            ":id",
            "o/:id",
            "e/:id",
            "s/:id"
        ],
    },
    tiktok: {
        patterns: [
            ":user/video/:postId",
            "i18n/share/video/:postId",
            ":shortLink",
            "t/:shortLink",
            ":user/photo/:postId",
            "v/:postId.html"
        ],
        subdomains: ["vt", "vm", "m", "t", "pro"],
    },
    tumblr: {
        patterns: [
            "post/:id",
            "blog/view/:user/:id",
            ":user/:id",
            ":user/:id/:trackingId"
        ],
        subdomains: "*",
    },
    twitch: {
        patterns: [":channel/clip/:clip"],
        tld: "tv",
        subdomains: ["clips", "www", "m"],
    },
    twitter: {
        patterns: [
            ":user/status/:id",
            ":user/status/:id/video/:index",
            ":user/status/:id/photo/:index",
            ":user/status/:id/mediaviewer",
            ":user/status/:id/mediaViewer",
            "i/bookmarks?post_id=:id"
        ],
        subdomains: ["mobile"],
        altDomains: ["x.com", "vxtwitter.com", "fixvx.com"],
    },
    vimeo: {
        patterns: [
            ":id",
            "video/:id",
            ":id/:password",
            "/channels/:user/:id",
            "groups/:groupId/videos/:id"
        ],
        subdomains: ["player"],
    },
    vk: {
        patterns: [
            "video:ownerId_:videoId",
            "clip:ownerId_:videoId",
            "video:ownerId_:videoId_:accessKey",
            "clip:ownerId_:videoId_:accessKey",

            // links with a duplicate author id and/or zipper query param
            "clips:duplicateId",
            "videos:duplicateId",
            "search/video"
        ],
        subdomains: ["m"],
        altDomains: ["vkvideo.ru", "vk.ru"],
    },
    xiaohongshu: {
        patterns: [
            "explore/:id?xsec_token=:token",
            "discovery/item/:id?xsec_token=:token",
            ":shareType/:shareId",
        ],
        altDomains: ["xhslink.com"],
    },
    youtube: {
        patterns: [
            "watch?v=:id",
            "embed/:id",
            "watch/:id",
            "v/:id"
        ],
        subdomains: ["music", "m"],
    }
}

Object.values(services).forEach(service => {
    service.patterns = service.patterns.map(
        pattern => new UrlPattern(pattern, {
            segmentValueCharset: UrlPattern.defaultOptions.segmentValueCharset + '@\\.:'
        })
    )
})


================================================
FILE: api/src/processing/service-patterns.js
================================================
export const testers = {
    "bilibili": pattern =>
        (pattern.comId?.length <= 12 && pattern.partId?.length <= 3) ||
        (pattern.comId?.length <= 12 && !pattern.partId) ||
        pattern.comShortLink?.length <= 16 ||
        pattern.tvId?.length <= 24,

    "bsky": pattern =>
        pattern.user?.length <= 128 && pattern.post?.length <= 128,

    "dailymotion": pattern => pattern.id?.length <= 32,

    "facebook": pattern =>
        pattern.shortLink?.length <= 11 ||
        pattern.username?.length <= 30 ||
        pattern.caption?.length <= 255 ||
        pattern.id?.length <= 20 && !pattern.shareType ||
        pattern.id?.length <= 20 && pattern.shareType?.length === 1,

    "instagram": pattern =>
        pattern.postId?.length <= 48 ||
        pattern.shareId?.length <= 16 ||
        (pattern.username?.length <= 30 && pattern.storyId?.length <= 24),

    "loom": pattern =>
        pattern.id?.length <= 32,

    "newgrounds": pattern =>
        pattern.id?.length <= 12 ||
        pattern.audioId?.length <= 12,

    "ok": pattern =>
        pattern.id?.length <= 16,

    "pinterest": pattern =>
        pattern.id?.length <= 128 ||
        pattern.shortLink?.length <= 32,

    "reddit": pattern =>
        pattern.id?.length <= 16 && !pattern.sub && !pattern.user ||
        (pattern.sub?.length <= 22 && pattern.id?.length <= 16) ||
        (pattern.user?.length <= 22 && pattern.id?.length <= 16) ||
        (pattern.sub?.length <= 22 && pattern.shareId?.length <= 16) ||
        (pattern.shortId?.length <= 16),

    "rutube": pattern =>
        (pattern.id?.length === 32 && pattern.key?.length <= 32) ||
        pattern.id?.length === 32 ||
        pattern.yappyId?.length === 32,

    "snapchat": pattern =>
        (pattern.username?.length <= 32 && (!pattern.storyId || pattern.storyId?.length <= 255)) ||
        pattern.spotlightId?.length <= 255 ||
        pattern.shortLink?.length <= 16,

    "soundcloud": pattern =>
        (pattern.author?.length <= 255 && pattern.song?.length <= 255) ||
        pattern.shortLink?.length <= 32,

    "streamable": pattern =>
        pattern.id?.length <= 6,

    "tiktok": pattern =>
        pattern.postId?.length <= 21 ||
        pattern.shortLink?.length <= 21,

    "tumblr": pattern =>
        pattern.id?.length < 21 ||
        (pattern.id?.length < 21 && pattern.user?.length <= 32),

    "twitch": pattern =>
        pattern.channel && pattern.clip?.length <= 100,

    "twitter": pattern =>
        pattern.id?.length < 20,

    "vimeo": pattern =>
        pattern.id?.length <= 11 && (!pattern.password || pattern.password.length < 16),

    "vk": pattern =>
        (pattern.ownerId?.length <= 10 && pattern.videoId?.length <= 10) ||
        (pattern.ownerId?.length <= 10 && pattern.videoId?.length <= 10 && pattern.videoId?.accessKey <= 18),

    "xiaohongshu": pattern =>
        pattern.id?.length <= 24 && pattern.token?.length <= 64 ||
        pattern.shareId?.length <= 24 && pattern.shareType?.length === 1,

    "youtube": pattern =>
        pattern.id?.length <= 11,
}


================================================
FILE: api/src/processing/services/bilibili.js
================================================
import { genericUserAgent, env } from "../../config.js";
import { resolveRedirectingURL } from "../url.js";

// TO-DO: higher quality downloads (currently requires an account)

function getBest(content) {
    return content?.filter(v => v.baseUrl || v.url)
                .map(v => (v.baseUrl = v.baseUrl || v.url, v))
                .reduce((a, b) => a?.bandwidth > b?.bandwidth ? a : b);
}

function extractBestQuality(dashData) {
    const bestVideo = getBest(dashData.video),
          bestAudio = getBest(dashData.audio);

    if (!bestVideo || !bestAudio) return [];
    return [ bestVideo, bestAudio ];
}

async function com_download(id, partId) {
    const url = new URL(`https://bilibili.com/video/${id}`);

    if (partId) {
        url.searchParams.set('p', partId);
    }

    const html = await fetch(url, {
        headers: {
            "user-agent": genericUserAgent
        }
    })
    .then(r => r.text())
    .catch(() => {});

    if (!html) {
        return { error: "fetch.fail" }
    }

    if (!(html.includes('<script>window.__playinfo__=') && html.includes('"video_codecid"'))) {
        return { error: "fetch.empty" };
    }

    const streamData = JSON.parse(
        html.split('<script>window.__playinfo__=')[1].split('</script>')[0]
    );

    if (streamData.data.timelength > env.durationLimit * 1000) {
        return { error: "content.too_long" };
    }

    const [ video, audio ] = extractBestQuality(streamData.data.dash);
    if (!video || !audio) {
        return { error: "fetch.empty" };
    }

    let filenameBase = `bilibili_${id}`;
    if (partId) {
        filenameBase += `_${partId}`;
    }

    return {
        urls: [video.baseUrl, audio.baseUrl],
        audioFilename: `${filenameBase}_audio`,
        filename: `${filenameBase}_${video.width}x${video.height}.mp4`,
    };
}

async function tv_download(id) {
    const url = new URL(
        'https://api.bilibili.tv/intl/gateway/web/playurl'
        + '?s_locale=en_US&platform=web&qn=64&type=0&device=wap'
        + '&tf=0&spm_id=bstar-web.ugc-video-detail.0.0&from_spm_id='
    );

    url.searchParams.set('aid', id);

    const { data } = await fetch(url).then(a => a.json());
    if (!data?.playurl?.video) {
        return { error: "fetch.empty" };
    }

    const [ video, audio ] = extractBestQuality({
        video: data.playurl.video.map(s => s.video_resource)
                                 .filter(s => s.codecs.includes('avc1')),
        audio: data.playurl.audio_resource
    });

    if (!video || !audio) {
        return { error: "fetch.empty" };
    }

    if (video.duration > env.durationLimit * 1000) {
        return { error: "content.too_long" };
    }

    return {
        urls: [video.url, audio.url],
        audioFilename: `bilibili_tv_${id}_audio`,
        filename: `bilibili_tv_${id}.mp4`
    };
}

export default async function({ comId, tvId, comShortLink, partId }) {
    if (comShortLink) {
        const patternMatch = await resolveRedirectingURL(`https://b23.tv/${comShortLink}`);
        comId = patternMatch?.comId;
    }

    if (comId) {
        return com_download(comId, partId);
    } else if (tvId) {
        return tv_download(tvId);
    }

    return { error: "fetch.fail" };
}


================================================
FILE: api/src/processing/services/bluesky.js
================================================
import HLS from "hls-parser";
import { cobaltUserAgent } from "../../config.js";
import { createStream } from "../../stream/manage.js";

const extractV
Download .txt
gitextract_xvmn6t33/

├── .deepsource.toml
├── .dockerignore
├── .github/
│   ├── ISSUE_TEMPLATE/
│   │   ├── bug-main-instance.yml
│   │   ├── bug-report.yml
│   │   ├── config.yml
│   │   ├── feature-request.yml
│   │   ├── hosting-help.yml
│   │   └── service-request.yml
│   ├── test.sh
│   └── workflows/
│       ├── codeql.yml
│       ├── docker-develop.yml
│       ├── docker-staging.yml
│       ├── docker.yml
│       ├── fast-forward.yml
│       ├── test-services.yml
│       └── test.yml
├── .gitignore
├── CONTRIBUTING.md
├── Dockerfile
├── LICENSE
├── README.md
├── api/
│   ├── LICENSE
│   ├── README.md
│   ├── package.json
│   └── src/
│       ├── cobalt.js
│       ├── config.js
│       ├── core/
│       │   ├── api.js
│       │   ├── env.js
│       │   └── itunnel.js
│       ├── misc/
│       │   ├── cluster.js
│       │   ├── console-text.js
│       │   ├── crypto.js
│       │   ├── file-watcher.js
│       │   ├── language-codes.js
│       │   ├── load-from-fs.js
│       │   ├── randomize-ciphers.js
│       │   ├── run-test.js
│       │   └── utils.js
│       ├── processing/
│       │   ├── cookie/
│       │   │   ├── cookie.js
│       │   │   └── manager.js
│       │   ├── create-filename.js
│       │   ├── helpers/
│       │   │   └── youtube-session.js
│       │   ├── match-action.js
│       │   ├── match.js
│       │   ├── request.js
│       │   ├── schema.js
│       │   ├── service-alias.js
│       │   ├── service-config.js
│       │   ├── service-patterns.js
│       │   ├── services/
│       │   │   ├── bilibili.js
│       │   │   ├── bluesky.js
│       │   │   ├── dailymotion.js
│       │   │   ├── facebook.js
│       │   │   ├── instagram.js
│       │   │   ├── loom.js
│       │   │   ├── newgrounds.js
│       │   │   ├── ok.js
│       │   │   ├── pinterest.js
│       │   │   ├── reddit.js
│       │   │   ├── rutube.js
│       │   │   ├── snapchat.js
│       │   │   ├── soundcloud.js
│       │   │   ├── streamable.js
│       │   │   ├── tiktok.js
│       │   │   ├── tumblr.js
│       │   │   ├── twitch.js
│       │   │   ├── twitter.js
│       │   │   ├── vimeo.js
│       │   │   ├── vk.js
│       │   │   ├── xiaohongshu.js
│       │   │   └── youtube.js
│       │   └── url.js
│       ├── security/
│       │   ├── api-keys.js
│       │   ├── jwt.js
│       │   ├── secrets.js
│       │   └── turnstile.js
│       ├── store/
│       │   ├── base-store.js
│       │   ├── memory-store.js
│       │   ├── redis-ratelimit.js
│       │   ├── redis-store.js
│       │   └── store.js
│       ├── stream/
│       │   ├── ffmpeg.js
│       │   ├── internal-hls.js
│       │   ├── internal.js
│       │   ├── manage.js
│       │   ├── proxy.js
│       │   ├── shared.js
│       │   └── stream.js
│       └── util/
│           ├── generate-jwt-secret.js
│           ├── test.js
│           └── tests/
│               ├── bilibili.json
│               ├── bsky.json
│               ├── dailymotion.json
│               ├── facebook.json
│               ├── instagram.json
│               ├── loom.json
│               ├── newgrounds.json
│               ├── ok.json
│               ├── pinterest.json
│               ├── reddit.json
│               ├── rutube.json
│               ├── snapchat.json
│               ├── soundcloud.json
│               ├── streamable.json
│               ├── tiktok.json
│               ├── tumblr.json
│               ├── twitch.json
│               ├── twitter.json
│               ├── vimeo.json
│               ├── vk.json
│               ├── xiaohongshu.json
│               └── youtube.json
├── docs/
│   ├── api-env-variables.md
│   ├── api.md
│   ├── examples/
│   │   ├── cookies.example.json
│   │   └── docker-compose.example.yml
│   ├── protect-an-instance.md
│   └── run-an-instance.md
├── package.json
├── packages/
│   ├── api-client/
│   │   ├── .gitignore
│   │   ├── .prettierignore
│   │   ├── .prettierrc
│   │   ├── LICENSE
│   │   ├── package.json
│   │   └── tsconfig.json
│   └── version-info/
│       ├── index.d.ts
│       ├── index.js
│       └── package.json
├── pnpm-workspace.yaml
└── web/
    ├── .gitignore
    ├── .npmrc
    ├── LICENSE
    ├── README.md
    ├── changelogs/
    │   ├── 10.0.md
    │   ├── 10.1.md
    │   ├── 10.3.md
    │   ├── 10.5.md
    │   ├── 11.0.md
    │   ├── 11.2.md
    │   ├── 2.0.md
    │   ├── 2.2.5.md
    │   ├── 2.2.6.md
    │   ├── 2.2.8.md
    │   ├── 2.2.9.md
    │   ├── 2.2.md
    │   ├── 3.0.md
    │   ├── 3.1.md
    │   ├── 3.2.md
    │   ├── 3.4.md
    │   ├── 3.5.2.md
    │   ├── 3.5.4.md
    │   ├── 3.5.md
    │   ├── 3.6.3.md
    │   ├── 3.6.md
    │   ├── 3.7.md
    │   ├── 4.0.md
    │   ├── 4.1.md
    │   ├── 4.2.md
    │   ├── 4.3.2.md
    │   ├── 4.3.md
    │   ├── 4.4.md
    │   ├── 4.5.md
    │   ├── 4.6.md
    │   ├── 4.7.md
    │   ├── 4.8.md
    │   ├── 5.0.md
    │   ├── 5.1.md
    │   ├── 5.2.md
    │   ├── 5.3.md
    │   ├── 5.4.md
    │   ├── 6.0.md
    │   ├── 6.2.md
    │   ├── 7.0.md
    │   ├── 7.1.md
    │   ├── 7.11.md
    │   ├── 7.13.md
    │   ├── 7.14.md
    │   ├── 7.3.md
    │   ├── 7.4.md
    │   ├── 7.5.md
    │   ├── 7.6.md
    │   ├── 7.7.md
    │   ├── 7.8.md
    │   └── 7.9.md
    ├── eslint.config.js
    ├── i18n/
    │   ├── en/
    │   │   ├── a11y/
    │   │   │   ├── dialog.json
    │   │   │   ├── donate.json
    │   │   │   ├── general.json
    │   │   │   ├── queue.json
    │   │   │   ├── save.json
    │   │   │   └── tabs.json
    │   │   ├── about/
    │   │   │   ├── credits.md
    │   │   │   ├── general.md
    │   │   │   ├── privacy.md
    │   │   │   └── terms.md
    │   │   ├── about.json
    │   │   ├── button.json
    │   │   ├── dialog.json
    │   │   ├── donate.json
    │   │   ├── error/
    │   │   │   ├── api.json
    │   │   │   └── queue.json
    │   │   ├── error.json
    │   │   ├── general.json
    │   │   ├── notification.json
    │   │   ├── queue.json
    │   │   ├── receiver.json
    │   │   ├── remux.json
    │   │   ├── save.json
    │   │   ├── settings.json
    │   │   ├── tabs.json
    │   │   └── updates.json
    │   ├── languages.json
    │   └── ru/
    │       ├── a11y/
    │       │   ├── dialog.json
    │       │   ├── donate.json
    │       │   ├── general.json
    │       │   ├── queue.json
    │       │   ├── save.json
    │       │   └── tabs.json
    │       ├── about/
    │       │   ├── credits.md
    │       │   ├── general.md
    │       │   ├── privacy.md
    │       │   └── terms.md
    │       ├── about.json
    │       ├── button.json
    │       ├── dialog.json
    │       ├── donate.json
    │       ├── error/
    │       │   ├── api.json
    │       │   └── queue.json
    │       ├── error.json
    │       ├── general.json
    │       ├── notification.json
    │       ├── queue.json
    │       ├── receiver.json
    │       ├── remux.json
    │       ├── save.json
    │       ├── settings.json
    │       ├── tabs.json
    │       └── updates.json
    ├── package.json
    ├── src/
    │   ├── app.css
    │   ├── app.d.ts
    │   ├── app.html
    │   ├── components/
    │   │   ├── about/
    │   │   │   └── AboutSupport.svelte
    │   │   ├── buttons/
    │   │   │   ├── ActionButton.svelte
    │   │   │   ├── SettingsButton.svelte
    │   │   │   ├── SettingsToggle.svelte
    │   │   │   ├── Switcher.svelte
    │   │   │   └── VerticalActionButton.svelte
    │   │   ├── changelog/
    │   │   │   ├── ChangelogEntry.svelte
    │   │   │   └── ChangelogEntryWrapper.svelte
    │   │   ├── dialog/
    │   │   │   ├── DialogBackdropClose.svelte
    │   │   │   ├── DialogButton.svelte
    │   │   │   ├── DialogButtons.svelte
    │   │   │   ├── DialogContainer.svelte
    │   │   │   ├── DialogHolder.svelte
    │   │   │   ├── NoScriptDialog.svelte
    │   │   │   ├── PickerDialog.svelte
    │   │   │   ├── PickerItem.svelte
    │   │   │   ├── SavingDialog.svelte
    │   │   │   ├── SavingTutorial.svelte
    │   │   │   └── SmallDialog.svelte
    │   │   ├── donate/
    │   │   │   ├── DonateAltItem.svelte
    │   │   │   ├── DonateBanner.svelte
    │   │   │   ├── DonateCardContainer.svelte
    │   │   │   ├── DonateOptionsCard.svelte
    │   │   │   ├── DonateShareCard.svelte
    │   │   │   └── DonationOption.svelte
    │   │   ├── icons/
    │   │   │   ├── Clipboard.svelte
    │   │   │   ├── Cobalt.svelte
    │   │   │   ├── CobaltQR.svelte
    │   │   │   ├── CobaltSticker.svelte
    │   │   │   ├── Imput.svelte
    │   │   │   ├── Music.svelte
    │   │   │   ├── Mute.svelte
    │   │   │   └── Sparkles.svelte
    │   │   ├── misc/
    │   │   │   ├── AboutPageWrapper.svelte
    │   │   │   ├── BetaTesters.svelte
    │   │   │   ├── BulletExplain.svelte
    │   │   │   ├── CopyIcon.svelte
    │   │   │   ├── DropReceiver.svelte
    │   │   │   ├── FileReceiver.svelte
    │   │   │   ├── Meowbalt.svelte
    │   │   │   ├── NotchSticker.svelte
    │   │   │   ├── OuterLink.svelte
    │   │   │   ├── Placeholder.svelte
    │   │   │   ├── PopoverContainer.svelte
    │   │   │   ├── SectionHeading.svelte
    │   │   │   ├── Skeleton.svelte
    │   │   │   ├── Toggle.svelte
    │   │   │   ├── Turnstile.svelte
    │   │   │   └── UpdateNotification.svelte
    │   │   ├── queue/
    │   │   │   ├── ProcessingQueue.svelte
    │   │   │   ├── ProcessingQueueItem.svelte
    │   │   │   ├── ProcessingQueueStub.svelte
    │   │   │   ├── ProcessingStatus.svelte
    │   │   │   └── ProgressBar.svelte
    │   │   ├── save/
    │   │   │   ├── CaptchaTooltip.svelte
    │   │   │   ├── Omnibox.svelte
    │   │   │   ├── OmniboxIcon.svelte
    │   │   │   ├── SupportedServices.svelte
    │   │   │   └── buttons/
    │   │   │       ├── ClearButton.svelte
    │   │   │       └── DownloadButton.svelte
    │   │   ├── settings/
    │   │   │   ├── ClearStorageButton.svelte
    │   │   │   ├── DataSettingsButton.svelte
    │   │   │   ├── FilenamePreview.svelte
    │   │   │   ├── ManageSettings.svelte
    │   │   │   ├── ResetSettingsButton.svelte
    │   │   │   ├── SettingsCategory.svelte
    │   │   │   ├── SettingsDropdown.svelte
    │   │   │   └── SettingsInput.svelte
    │   │   ├── sidebar/
    │   │   │   ├── CobaltLogo.svelte
    │   │   │   ├── Sidebar.svelte
    │   │   │   └── SidebarTab.svelte
    │   │   └── subnav/
    │   │       ├── PageNav.svelte
    │   │       ├── PageNavSection.svelte
    │   │       └── PageNavTab.svelte
    │   ├── fonts/
    │   │   └── noto-mono-cobalt.css
    │   ├── lib/
    │   │   ├── api/
    │   │   │   ├── api-url.ts
    │   │   │   ├── api.ts
    │   │   │   ├── safety-warning.ts
    │   │   │   ├── saving-handler.ts
    │   │   │   ├── server-info.ts
    │   │   │   ├── session.ts
    │   │   │   └── turnstile.ts
    │   │   ├── changelogs.ts
    │   │   ├── clipboard.ts
    │   │   ├── device.ts
    │   │   ├── download.ts
    │   │   ├── env.ts
    │   │   ├── haptics.ts
    │   │   ├── i18n/
    │   │   │   ├── locale.ts
    │   │   │   └── translations.ts
    │   │   ├── libav.ts
    │   │   ├── polyfills/
    │   │   │   ├── abortsignal-timeout.ts
    │   │   │   └── user-activation.ts
    │   │   ├── polyfills.ts
    │   │   ├── settings/
    │   │   │   ├── audio-sub-language.ts
    │   │   │   ├── defaults.ts
    │   │   │   ├── lazy-get.ts
    │   │   │   ├── migrate-v7.ts
    │   │   │   ├── migrate.ts
    │   │   │   └── validate.ts
    │   │   ├── state/
    │   │   │   ├── dialogs.ts
    │   │   │   ├── omnibox.ts
    │   │   │   ├── queue-visibility.ts
    │   │   │   ├── server-info.ts
    │   │   │   ├── settings.ts
    │   │   │   ├── task-manager/
    │   │   │   │   ├── current-tasks.ts
    │   │   │   │   └── queue.ts
    │   │   │   ├── theme.ts
    │   │   │   └── turnstile.ts
    │   │   ├── storage/
    │   │   │   ├── index.ts
    │   │   │   ├── memory.ts
    │   │   │   ├── opfs.ts
    │   │   │   └── storage.ts
    │   │   ├── subnav.ts
    │   │   ├── task-manager/
    │   │   │   ├── queue.ts
    │   │   │   ├── run-worker.ts
    │   │   │   ├── runners/
    │   │   │   │   ├── fetch.ts
    │   │   │   │   └── ffmpeg.ts
    │   │   │   ├── scheduler.ts
    │   │   │   └── workers/
    │   │   │       ├── fetch.ts
    │   │   │       └── ffmpeg.ts
    │   │   ├── types/
    │   │   │   ├── api.ts
    │   │   │   ├── changelogs.ts
    │   │   │   ├── dialog.ts
    │   │   │   ├── generic.ts
    │   │   │   ├── i18n.ts
    │   │   │   ├── libav.ts
    │   │   │   ├── meowbalt.ts
    │   │   │   ├── omnibox.ts
    │   │   │   ├── queue.ts
    │   │   │   ├── settings/
    │   │   │   │   ├── v2.ts
    │   │   │   │   ├── v3.ts
    │   │   │   │   ├── v4.ts
    │   │   │   │   ├── v5.ts
    │   │   │   │   └── v6.ts
    │   │   │   ├── settings.ts
    │   │   │   ├── task-manager.ts
    │   │   │   └── workers.ts
    │   │   ├── util.ts
    │   │   └── version.ts
    │   └── routes/
    │       ├── +error.svelte
    │       ├── +layout.svelte
    │       ├── +layout.ts
    │       ├── +page.svelte
    │       ├── _headers/
    │       │   └── +server.ts
    │       ├── about/
    │       │   ├── +layout.svelte
    │       │   ├── +page.svelte
    │       │   ├── [page]/
    │       │   │   ├── +page.svelte
    │       │   │   └── +page.ts
    │       │   └── community/
    │       │       └── +page.svelte
    │       ├── donate/
    │       │   └── +page.svelte
    │       ├── remux/
    │       │   └── +page.svelte
    │       ├── settings/
    │       │   ├── +layout.svelte
    │       │   ├── +page.svelte
    │       │   ├── accessibility/
    │       │   │   └── +page.svelte
    │       │   ├── advanced/
    │       │   │   └── +page.svelte
    │       │   ├── appearance/
    │       │   │   └── +page.svelte
    │       │   ├── audio/
    │       │   │   └── +page.svelte
    │       │   ├── debug/
    │       │   │   └── +page.svelte
    │       │   ├── instances/
    │       │   │   └── +page.svelte
    │       │   ├── local/
    │       │   │   └── +page.svelte
    │       │   ├── metadata/
    │       │   │   └── +page.svelte
    │       │   ├── privacy/
    │       │   │   └── +page.svelte
    │       │   └── video/
    │       │       └── +page.svelte
    │       ├── updates/
    │       │   └── +page.svelte
    │       └── version.json/
    │           └── +server.ts
    ├── static/
    │   └── manifest.json
    ├── svelte.config.js
    ├── tsconfig.json
    ├── vite.config.ts
    └── wrangler.jsonc
Download .txt
SYMBOL INDEX (270 symbols across 71 files)

FILE: api/src/misc/console-text.js
  constant ANSI (line 1) | const ANSI = {
  function wrap (line 10) | function wrap(color, text) {
  function Bright (line 18) | function Bright(text) {
  function Red (line 22) | function Red(text) {
  function Green (line 26) | function Green(text) {
  function Cyan (line 30) | function Cyan(text) {
  function Yellow (line 34) | function Yellow(text) {

FILE: api/src/misc/crypto.js
  function encryptStream (line 5) | function encryptStream(plaintext, iv, secret) {
  function decryptStream (line 13) | function decryptStream(ciphertext, iv, secret) {

FILE: api/src/misc/file-watcher.js
  class FileWatcher (line 4) | class FileWatcher extends EventEmitter {
    method constructor (line 9) | constructor({ path, ...rest }) {
    method #setupWatcher (line 14) | async #setupWatcher() {
    method read (line 28) | read() {
    method fromFileProtocol (line 33) | static fromFileProtocol(url_) {

FILE: api/src/misc/load-from-fs.js
  function loadFile (line 10) | function loadFile(path) {
  function loadJSON (line 14) | function loadJSON(path) {

FILE: api/src/misc/randomize-ciphers.js
  constant ORIGINAL_CIPHERS (line 4) | const ORIGINAL_CIPHERS = tls.DEFAULT_CIPHERS;
  constant TOP_N_SHUFFLE (line 8) | const TOP_N_SHUFFLE = 8;

FILE: api/src/misc/run-test.js
  function runTest (line 5) | async function runTest(url, params, expect) {

FILE: api/src/misc/utils.js
  function getRedirectingURL (line 4) | async function getRedirectingURL(url, dispatcher, headers) {
  function merge (line 43) | function merge(a, b) {
  function splitFilenameExtension (line 57) | function splitFilenameExtension(filename) {
  function zip (line 68) | function zip(a, b) {
  function isURL (line 72) | function isURL(input) {

FILE: api/src/processing/cookie/cookie.js
  class Cookie (line 3) | class Cookie {
    method constructor (line 4) | constructor(input) {
    method set (line 12) | set(key, value) {
    method unset (line 21) | unset(keys) {
    method fromString (line 25) | static fromString(str) {
    method toString (line 37) | toString() {
    method toJSON (line 41) | toJSON() {
    method values (line 45) | values() {

FILE: api/src/processing/cookie/manager.js
  constant WRITE_INTERVAL (line 9) | const WRITE_INTERVAL = 60000;
  constant VALID_SERVICES (line 10) | const VALID_SERVICES = new Set([
  function writeChanges (line 22) | function writeChanges(cookiePath) {
  function getCookie (line 105) | function getCookie(service) {
  function updateCookieValues (line 127) | function updateCookieValues(cookie, values) {
  function updateCookie (line 145) | function updateCookie(cookie, headers) {

FILE: api/src/processing/request.js
  function createResponse (line 7) | function createResponse(responseType, responseData) {
  function normalizeRequest (line 118) | function normalizeRequest(request) {
  function getIP (line 129) | function getIP(req, prefix = 56) {

FILE: api/src/processing/services/bilibili.js
  function getBest (line 6) | function getBest(content) {
  function extractBestQuality (line 12) | function extractBestQuality(dashData) {
  function com_download (line 20) | async function com_download(id, partId) {
  function tv_download (line 68) | async function tv_download(id) {

FILE: api/src/processing/services/dailymotion.js
  function getExp (line 6) | function getExp(token) {

FILE: api/src/processing/services/instagram.js
  function instagram (line 58) | function instagram(obj) {

FILE: api/src/processing/services/loom.js
  function fromTranscodedURL (line 12) | async function fromTranscodedURL(id) {
  function fromRawURL (line 31) | async function fromRawURL(id) {
  function getTranscript (line 53) | async function getTranscript(id) {

FILE: api/src/processing/services/reddit.js
  function getAccessToken (line 5) | async function getAccessToken() {

FILE: api/src/processing/services/rutube.js
  function requestJSON (line 4) | async function requestJSON(url) {

FILE: api/src/processing/services/snapchat.js
  constant SPOTLIGHT_VIDEO_REGEX (line 5) | const SPOTLIGHT_VIDEO_REGEX = /<link data-react-helmet="true" rel="prelo...
  constant NEXT_DATA_REGEX (line 6) | const NEXT_DATA_REGEX = /<script id="__NEXT_DATA__" type="application\/j...
  function getSpotlight (line 8) | async function getSpotlight(id) {
  function getStory (line 28) | async function getStory(username, storyId, alwaysProxy) {

FILE: api/src/processing/services/soundcloud.js
  function findClientID (line 9) | async function findClientID() {

FILE: api/src/processing/services/tumblr.js
  constant API_KEY (line 3) | const API_KEY = 'jrsCWX1XDuVxAFO4GkK147syAoN8BJZ5voz8tS80bPcj26Vc5Z';
  constant API_BASE (line 4) | const API_BASE = 'https://api-http2.tumblr.com';
  function request (line 6) | function request(domain, id) {

FILE: api/src/processing/services/twitter.js
  constant TWITTER_EPOCH (line 22) | const TWITTER_EPOCH = 1288834974657n;
  function needsFixing (line 26) | function needsFixing(media) {
  function bestQuality (line 39) | function bestQuality(arr) {

FILE: api/src/processing/services/youtube.js
  constant PLAYER_REFRESH_PERIOD (line 10) | const PLAYER_REFRESH_PERIOD = 1000 * 60 * 15;

FILE: api/src/processing/url.js
  function aliasURL (line 9) | function aliasURL(url) {
  function cleanURL (line 125) | function cleanURL(url) {
  function getHostIfValid (line 180) | function getHostIfValid(url) {
  function normalizeURL (line 195) | function normalizeURL(url) {
  function extract (line 203) | function extract(url, enabledServices = env.enabledServices) {
  function resolveRedirectingURL (line 246) | async function resolveRedirectingURL(url, dispatcher, headers) {

FILE: api/src/security/api-keys.js
  constant UUID_REGEX (line 14) | const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-...
  constant ALLOWED_KEYS (line 18) | const ALLOWED_KEYS = new Set(['name', 'ips', 'userAgents', 'limit', 'all...

FILE: api/src/store/base-store.js
  class Store (line 3) | class Store {
    method constructor (line 6) | constructor(name) {
    method _has (line 16) | async _has(_key) { await Promise.reject("needs implementation"); }
    method has (line 17) | has(key) {
    method _get (line 25) | async _get(_key) { await Promise.reject("needs implementation"); }
    method get (line 26) | async get(key) {
    method _set (line 38) | async _set(_key, _val, _exp_sec = -1) { await Promise.reject("needs im...
    method set (line 39) | set(key, val, exp_sec = -1) {

FILE: api/src/store/memory-store.js
  constant MIN_THRESHOLD_MS (line 6) | const MIN_THRESHOLD_MS = 2500;
  class MemoryStore (line 8) | class MemoryStore extends Store {
    method constructor (line 13) | constructor(name) {
    method _has (line 17) | _has(key) {
    method _get (line 21) | _get(key) {
    method _set (line 27) | _set(key, val, exp_sec = -1) {
    method #reschedule (line 43) | #reschedule() {
    method #sweepNow (line 67) | #sweepNow() {

FILE: api/src/store/redis-store.js
  class RedisStore (line 5) | class RedisStore extends Store {
    method constructor (line 11) | constructor(name) {
    method #keyOf (line 16) | #keyOf(key) {
    method _has (line 20) | async _has(key) {
    method _get (line 26) | async _get(key) {
    method _set (line 45) | async _set(key, val, exp_sec = -1) {

FILE: api/src/stream/internal-hls.js
  function getURL (line 5) | function getURL(url) {
  function transformObject (line 13) | function transformObject(streamInfo, hlsObject) {
  function transformMasterPlaylist (line 36) | function transformMasterPlaylist(streamInfo, hlsPlaylist) {
  function transformMediaPlaylist (line 50) | function transformMediaPlaylist(streamInfo, hlsPlaylist) {
  constant HLS_MIME_TYPES (line 57) | const HLS_MIME_TYPES = ["application/vnd.apple.mpegurl", "audio/mpegurl"...
  function isHlsResponse (line 59) | function isHlsResponse(req, streamInfo) {
  function handleHlsPlaylist (line 66) | async function handleHlsPlaylist(streamInfo, req, res) {
  function getSegmentSize (line 79) | async function getSegmentSize(url, config) {
  function probeInternalHLSTunnel (line 101) | async function probeInternalHLSTunnel(streamInfo) {

FILE: api/src/stream/internal.js
  constant CHUNK_SIZE (line 6) | const CHUNK_SIZE = BigInt(8e6);
  function handleChunkedStream (line 53) | async function handleChunkedStream(streamInfo, res) {
  function handleGenericStream (line 105) | async function handleGenericStream(streamInfo, res) {
  function internalStream (line 146) | function internalStream(streamInfo, res) {
  function probeInternalTunnel (line 158) | async function probeInternalTunnel(streamInfo) {

FILE: api/src/stream/manage.js
  function createStream (line 21) | function createStream(obj) {
  function createProxyTunnels (line 76) | function createProxyTunnels(info) {
  function getInternalTunnel (line 125) | function getInternalTunnel(id) {
  function getInternalTunnelFromURL (line 129) | function getInternalTunnelFromURL(url) {
  function createInternalStream (line 139) | function createInternalStream(url, obj = {}, isSubtitles) {
  function getInternalTunnelId (line 186) | function getInternalTunnelId(url) {
  function destroyInternalStream (line 195) | function destroyInternalStream(url) {
  function wrapStream (line 259) | function wrapStream(streamInfo) {
  function verifyStream (line 287) | async function verifyStream(id, hmac, exp, secret, iv) {

FILE: api/src/stream/shared.js
  function closeRequest (line 28) | function closeRequest(controller) {
  function closeResponse (line 32) | function closeResponse(res) {
  function getHeaders (line 40) | function getHeaders(service) {
  function pipe (line 46) | function pipe(from, to, done) {
  function estimateTunnelLength (line 56) | async function estimateTunnelLength(streamInfo, multiplier = 1.1) {
  function estimateAudioMultiplier (line 81) | function estimateAudioMultiplier(streamInfo) {

FILE: web/src/app.d.ts
  class Comp (line 6) | class Comp extends SvelteComponentDev {

FILE: web/src/lib/api/saving-handler.ts
  type SavingHandlerArgs (line 15) | type SavingHandlerArgs = {

FILE: web/src/lib/api/server-info.ts
  type CobaltServerInfoCache (line 9) | type CobaltServerInfoCache = {

FILE: web/src/lib/changelogs.ts
  function getVersionFromPath (line 3) | function getVersionFromPath(path: string) {
  function getAllChangelogs (line 7) | function getAllChangelogs() {

FILE: web/src/lib/download.ts
  type DownloadFileParams (line 12) | type DownloadFileParams = {
  type SavingDialogParams (line 18) | type SavingDialogParams = {

FILE: web/src/lib/libav.ts
  class LibAVWrapper (line 8) | class LibAVWrapper {
    method constructor (line 13) | constructor(onProgress?: FFmpegProgressCallback) {
    method init (line 19) | init(options?: LibAV.LibAVOpts) {
    method terminate (line 40) | async terminate() {
    method probe (line 47) | async probe(blob: Blob) {
    method render (line 73) | async render({ files, output, args }: RenderParams) {
    method #emitProgress (line 137) | #emitProgress(data: Uint8Array | Int8Array) {

FILE: web/src/lib/settings/audio-sub-language.ts
  type YoutubeDubLang (line 30) | type YoutubeDubLang = typeof youtubeDubLanguages[number];
  type SubtitleLang (line 31) | type SubtitleLang = typeof subtitleLanguages[number];
  type TranslationFunction (line 33) | type TranslationFunction = FromReadable<typeof translation>;

FILE: web/src/lib/settings/lazy-get.ts
  function lazySettingGetter (line 4) | function lazySettingGetter(settings: CobaltSettings) {

FILE: web/src/lib/settings/migrate-v7.ts
  type LegacySwitchers (line 23) | type LegacySwitchers = keyof typeof oldSwitcherValues;
  type LegacyCheckboxes (line 24) | type LegacyCheckboxes = typeof oldCheckboxes[number];
  type SwitcherOptions (line 49) | type SwitcherOptions = typeof oldSwitcherValues[T][number];

FILE: web/src/lib/settings/migrate.ts
  type Migrator (line 12) | type Migrator = (s: AllPartialSettingsWithSchema) => AllPartialSettingsW...

FILE: web/src/lib/settings/validate.ts
  function validateTypes (line 14) | function validateTypes(input: unknown, reference = defaultSettings as un...
  function validateLiteral (line 56) | function validateLiteral(value: Optional<string>, allowed: readonly stri...
  function validateLiterals (line 60) | function validateLiterals(literals: [Optional<string>, readonly string[]...
  function validateSettings (line 70) | function validateSettings(settings: PartialSettings) {

FILE: web/src/lib/state/dialogs.ts
  function createDialog (line 11) | function createDialog(newData: DialogInfo) {
  function killDialog (line 18) | function killDialog() {

FILE: web/src/lib/state/settings.ts
  function updateSetting (line 69) | function updateSetting(partial: PartialSettings) {
  function resetSettings (line 84) | function resetSettings() {

FILE: web/src/lib/state/task-manager/current-tasks.ts
  function addWorkerToQueue (line 9) | function addWorkerToQueue(workerId: string, item: CobaltCurrentTaskItem) {
  function removeWorkerFromQueue (line 16) | function removeWorkerFromQueue(id: string) {
  function updateWorkerProgress (line 23) | function updateWorkerProgress(workerId: string, progress: CobaltWorkerPr...
  function clearCurrentTasks (line 30) | function clearCurrentTasks() {

FILE: web/src/lib/state/task-manager/queue.ts
  function addItem (line 29) | function addItem(item: CobaltQueueItem) {
  function itemError (line 38) | function itemError(id: UUID, workerId: UUID, error: string) {
  function itemDone (line 56) | function itemDone(id: UUID, file: File) {
  function pipelineTaskDone (line 73) | function pipelineTaskDone(id: UUID, workerId: UUID, file: File) {
  function itemRunning (line 88) | function itemRunning(id: UUID) {
  function removeItem (line 103) | function removeItem(id: UUID) {
  function clearQueue (line 119) | function clearQueue() {

FILE: web/src/lib/state/theme.ts
  type Theme (line 7) | type Theme = typeof themeOptions[number];

FILE: web/src/lib/storage/index.ts
  function init (line 5) | async function init(expectedSize?: number): Promise<AbstractStorage> {
  function retype (line 17) | function retype(file: File, type: string) {

FILE: web/src/lib/storage/memory.ts
  class MemoryStorage (line 4) | class MemoryStorage extends AbstractStorage {
    method constructor (line 9) | constructor(chunkSize: number) {
    method init (line 14) | static async init(expectedSize: number) {
    method res (line 33) | async res() {
    method #expand (line 55) | #expand(size: number) {
    method write (line 61) | async write(data: Uint8Array | Int8Array, pos: number) {
    method destroy (line 85) | async destroy() {
    method isAvailable (line 89) | static async isAvailable() {

FILE: web/src/lib/storage/opfs.ts
  constant COBALT_PROCESSING_DIR (line 4) | const COBALT_PROCESSING_DIR = "cobalt-processing-data";
  class OPFSStorage (line 6) | class OPFSStorage extends AbstractStorage {
    method constructor (line 13) | constructor(root: FileSystemDirectoryHandle, handle: FileSystemFileHan...
    method init (line 20) | static async init() {
    method res (line 29) | async res() {
    method write (line 36) | async write(data: Uint8Array | Int8Array, offset: number) {
    method destroy (line 40) | async destroy() {
    method #computeIsAvailable (line 44) | static async #computeIsAvailable() {
    method isAvailable (line 73) | static async isAvailable() {

FILE: web/src/lib/storage/storage.ts
  method init (line 2) | static init(_expected_size: number): Promise<AbstractStorage> {
  method isAvailable (line 6) | static async isAvailable(): Promise<boolean> {

FILE: web/src/lib/types/api.ts
  type CobaltResponseType (line 3) | enum CobaltResponseType {
  type CobaltErrorResponse (line 11) | type CobaltErrorResponse = {
  type CobaltPartialURLResponse (line 22) | type CobaltPartialURLResponse = {
  type CobaltPickerResponse (line 27) | type CobaltPickerResponse = {
  type CobaltRedirectResponse (line 38) | type CobaltRedirectResponse = {
  type CobaltTunnelResponse (line 42) | type CobaltTunnelResponse = {
  type CobaltFileMetadata (line 59) | type CobaltFileMetadata = Record<
  type CobaltLocalProcessingType (line 63) | type CobaltLocalProcessingType = 'merge' | 'mute' | 'audio' | 'gif' | 'r...
  type CobaltLocalProcessingResponse (line 65) | type CobaltLocalProcessingResponse = {
  type CobaltFileUrlType (line 90) | type CobaltFileUrlType = "redirect" | "tunnel";
  type CobaltSession (line 92) | type CobaltSession = {
  type CobaltServerInfo (line 97) | type CobaltServerInfo = {
  type CobaltSaveRequestBody (line 115) | type CobaltSaveRequestBody =
  type CobaltSessionResponse (line 118) | type CobaltSessionResponse = CobaltSession | CobaltErrorResponse;
  type CobaltServerInfoResponse (line 119) | type CobaltServerInfoResponse = CobaltServerInfo | CobaltErrorResponse;
  type CobaltAPIResponse (line 121) | type CobaltAPIResponse = CobaltErrorResponse

FILE: web/src/lib/types/changelogs.ts
  type ChangelogMetadata (line 1) | interface ChangelogMetadata {
  type MarkdownMetadata (line 10) | interface MarkdownMetadata {
  type ChangelogImport (line 14) | type ChangelogImport = {

FILE: web/src/lib/types/dialog.ts
  type DialogButton (line 4) | type DialogButton = {
  type SmallDialogIcons (line 13) | type SmallDialogIcons = "warn-red";
  type DialogPickerItem (line 15) | type DialogPickerItem = {
  type Dialog (line 21) | type Dialog = {
  type SmallDialog (line 26) | type SmallDialog = Dialog & {
  type PickerDialog (line 37) | type PickerDialog = Dialog & {
  type SavingDialog (line 43) | type SavingDialog = Dialog & {
  type DialogInfo (line 51) | type DialogInfo = SmallDialog | PickerDialog | SavingDialog;

FILE: web/src/lib/types/generic.ts
  type RecursivePartial (line 5) | type RecursivePartial<Type> = {
  type DefaultImport (line 12) | type DefaultImport<T> = () => Promise<{ default: T }>;
  type Optional (line 13) | type Optional<T> = T | undefined;
  type Writeable (line 14) | type Writeable<T> = { -readonly [P in keyof T]: T[P] };
  type FromReadable (line 15) | type FromReadable<T> = T extends Readable<infer U> ? U : never;

FILE: web/src/lib/types/i18n.ts
  type LanguageCode (line 3) | type LanguageCode = string;
  type KeyPath (line 4) | type KeyPath = string;
  type GenericImport (line 6) | type GenericImport = DefaultImport<unknown>;
  type LocalizationContent (line 7) | type LocalizationContent = Record<string, string>;
  type StructuredLocfileInfo (line 8) | type StructuredLocfileInfo = Record<

FILE: web/src/lib/types/libav.ts
  type FileInfo (line 1) | type FileInfo = {
  type RenderParams (line 6) | type RenderParams = {
  type FFmpegProgressStatus (line 12) | type FFmpegProgressStatus = "continue" | "end" | "unknown";
  type FFmpegProgressEvent (line 13) | type FFmpegProgressEvent = {
  type FFmpegProgressCallback (line 24) | type FFmpegProgressCallback = (info: FFmpegProgressEvent) => void;

FILE: web/src/lib/types/meowbalt.ts
  type MeowbaltEmotions (line 1) | type MeowbaltEmotions = "smile" | "error" | "question" | "think" | "fast";

FILE: web/src/lib/types/omnibox.ts
  type CobaltDownloadButtonState (line 1) | type CobaltDownloadButtonState = "idle" | "think" | "check" | "done" | "...

FILE: web/src/lib/types/queue.ts
  type UUID (line 4) | type UUID = string;
  type CobaltQueueBaseItem (line 6) | type CobaltQueueBaseItem = {
  type CobaltQueueItemWaiting (line 16) | type CobaltQueueItemWaiting = CobaltQueueBaseItem & {
  type CobaltQueueItemRunning (line 20) | type CobaltQueueItemRunning = CobaltQueueBaseItem & {
  type CobaltQueueItemDone (line 25) | type CobaltQueueItemDone = CobaltQueueBaseItem & {
  type CobaltQueueItemError (line 30) | type CobaltQueueItemError = CobaltQueueBaseItem & {
  type CobaltQueueItem (line 35) | type CobaltQueueItem = CobaltQueueItemWaiting
  type CobaltQueue (line 40) | type CobaltQueue = {

FILE: web/src/lib/types/settings.ts
  type CobaltSettings (line 14) | type CobaltSettings = CobaltSettingsV6;
  type AnyCobaltSettings (line 16) | type AnyCobaltSettings = CobaltSettingsV5 | CobaltSettingsV4 | CobaltSet...
  type PartialSettings (line 18) | type PartialSettings = RecursivePartial<CobaltSettings>;
  type AllPartialSettingsWithSchema (line 20) | type AllPartialSettingsWithSchema = RecursivePartial<AnyCobaltSettings> ...
  type DownloadModeOption (line 22) | type DownloadModeOption = CobaltSettings['save']['downloadMode'];

FILE: web/src/lib/types/settings/v2.ts
  type CobaltSettingsAppearance (line 12) | type CobaltSettingsAppearance = {
  type CobaltSettingsAdvanced (line 20) | type CobaltSettingsAdvanced = {
  type CobaltSettingsPrivacy (line 24) | type CobaltSettingsPrivacy = {
  type CobaltSettingsProcessing (line 29) | type CobaltSettingsProcessing = {
  type CobaltSettingsSaveV2 (line 37) | type CobaltSettingsSaveV2 = {
  type CobaltSettingsV2 (line 53) | type CobaltSettingsV2 = {

FILE: web/src/lib/types/settings/v3.ts
  type CobaltSettingsV3 (line 4) | type CobaltSettingsV3 = Omit<CobaltSettingsV2, 'schemaVersion' | 'save'>...

FILE: web/src/lib/types/settings/v4.ts
  type CobaltSettingsV4 (line 3) | type CobaltSettingsV4 = Omit<CobaltSettingsV3, 'schemaVersion' | 'proces...

FILE: web/src/lib/types/settings/v5.ts
  type CobaltSettingsV5 (line 3) | type CobaltSettingsV5 = Omit<CobaltSettingsV4, 'schemaVersion' | 'advanc...

FILE: web/src/lib/types/settings/v6.ts
  type CobaltSettingsV6 (line 7) | type CobaltSettingsV6 = Omit<CobaltSettingsV5, 'schemaVersion' | 'save'>...

FILE: web/src/lib/types/task-manager.ts
  type CobaltCurrentTaskItem (line 4) | type CobaltCurrentTaskItem = {
  type CobaltCurrentTasks (line 10) | type CobaltCurrentTasks = {

FILE: web/src/lib/types/workers.ts
  type CobaltPipelineResultFileType (line 6) | type CobaltPipelineResultFileType = typeof resultFileTypes[number];
  type CobaltWorkerProgress (line 8) | type CobaltWorkerProgress = {
  type CobaltFFmpegWorkerArgs (line 14) | type CobaltFFmpegWorkerArgs = {
  type CobaltPipelineItemBase (line 20) | type CobaltPipelineItemBase = {
  type CobaltRemuxPipelineItem (line 26) | type CobaltRemuxPipelineItem = CobaltPipelineItemBase & {
  type CobaltEncodePipelineItem (line 31) | type CobaltEncodePipelineItem = CobaltPipelineItemBase & {
  type CobaltFetchPipelineItem (line 36) | type CobaltFetchPipelineItem = CobaltPipelineItemBase & {
  type CobaltPipelineItem (line 41) | type CobaltPipelineItem = CobaltEncodePipelineItem

FILE: web/src/lib/version.ts
  type VersionResponse (line 5) | type VersionResponse = {

FILE: web/src/routes/_headers/+server.ts
  function GET (line 1) | function GET() {

FILE: web/src/routes/version.json/+server.ts
  function GET (line 4) | async function GET() {

FILE: web/vite.config.ts
  method configureServer (line 17) | configureServer(server) {
  method configureServer (line 56) | configureServer(server) {
  method writeBundle (line 67) | async writeBundle(bundle) {
  method config (line 82) | config() {
Condensed preview — 413 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,159K chars).
[
  {
    "path": ".deepsource.toml",
    "chars": 93,
    "preview": "version = 1\n\n[[analyzers]]\nname = \"javascript\"\n\n  [analyzers.meta]\n  environment = [\"nodejs\"]"
  },
  {
    "path": ".dockerignore",
    "chars": 185,
    "preview": "# OS directory info files\n.DS_Store\ndesktop.ini\n\n# node\nnode_modules\n\n# static build\nbuild\n\n# secrets\n.env\n.env.*\n!.env."
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug-main-instance.yml",
    "chars": 1445,
    "preview": "name: main instance bug report\ndescription: \"report an issue with cobalt.tools or api.cobalt.tools\"\nlabels: [\"main insta"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug-report.yml",
    "chars": 1406,
    "preview": "name: bug report\ndescription: report a global issue with the cobalt codebase\nlabels: [\"bug\"]\nbody:\n  - type: textarea\n  "
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "chars": 251,
    "preview": "blank_issues_enabled: false\ncontact_links:\n  - name: discord community\n    url: https://discord.gg/pQPt8HBUPu\n    about:"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature-request.yml",
    "chars": 913,
    "preview": "name: feature request\ndescription: suggest a feature for cobalt\nlabels: [\"feature request\"]\nbody:\n  - type: markdown\n   "
  },
  {
    "path": ".github/ISSUE_TEMPLATE/hosting-help.yml",
    "chars": 793,
    "preview": "name: instance hosting help\ndescription: ask any question regarding cobalt instance hosting\nlabels: [\"instance hosting h"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/service-request.yml",
    "chars": 1358,
    "preview": "name: service request\ndescription: \"request service support in cobalt\"\ntitle: \"add support for [service name]\"\nlabels: ["
  },
  {
    "path": ".github/test.sh",
    "chars": 1588,
    "preview": "#!/bin/bash\nset -e\n\n# thx: https://stackoverflow.com/a/27601038\nwaitport() {\n    ATTEMPTS=50\n    while [ $((ATTEMPTS-=1)"
  },
  {
    "path": ".github/workflows/codeql.yml",
    "chars": 4307,
    "preview": "# For most projects, this workflow file will not need changing; you simply need\n# to commit it to your repository.\n#\n# Y"
  },
  {
    "path": ".github/workflows/docker-develop.yml",
    "chars": 1619,
    "preview": "name: Build development Docker image\n\non:\n  workflow_dispatch:\n\nenv:\n  REGISTRY: ghcr.io\n  IMAGE_NAME: ${{ github.reposi"
  },
  {
    "path": ".github/workflows/docker-staging.yml",
    "chars": 1615,
    "preview": "name: Build staging Docker image\n\non:\n  workflow_dispatch:\n\nenv:\n  REGISTRY: ghcr.io\n  IMAGE_NAME: ${{ github.repository"
  },
  {
    "path": ".github/workflows/docker.yml",
    "chars": 1904,
    "preview": "name: Build release Docker image\n\non:\n  workflow_dispatch:\n\nenv:\n  REGISTRY: ghcr.io\n  IMAGE_NAME: ${{ github.repository"
  },
  {
    "path": ".github/workflows/fast-forward.yml",
    "chars": 535,
    "preview": "name: fast-forward\non:\n  issue_comment:\n    types: [created, edited]\njobs:\n  fast-forward:\n    # Only run if the comment"
  },
  {
    "path": ".github/workflows/test-services.yml",
    "chars": 1057,
    "preview": "name: Run service tests\n\non:\n  pull_request:\n  push:\n    paths:\n      - api/**\n      - packages/**\n\njobs:\n  check-servic"
  },
  {
    "path": ".github/workflows/test.yml",
    "chars": 825,
    "preview": "name: Run tests\n\non:\n  pull_request:\n  push:\n\njobs:\n  check-lockfile:\n    name: check lockfile correctness\n    runs-on: "
  },
  {
    "path": ".gitignore",
    "chars": 195,
    "preview": "# OS directory info files\n.DS_Store\ndesktop.ini\n\n# node\nnode_modules\n\n# static build\nbuild\n\n# secrets\n.env\n.env.*\n!.env."
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 5510,
    "preview": "# contributing to cobalt\nif you're reading this, you are probably interested in contributing to cobalt, which we are ver"
  },
  {
    "path": "Dockerfile",
    "chars": 534,
    "preview": "FROM node:24-alpine AS base\nENV PNPM_HOME=\"/pnpm\"\nENV PATH=\"$PNPM_HOME:$PATH\"\n\nFROM base AS build\nWORKDIR /app\nCOPY . /a"
  },
  {
    "path": "LICENSE",
    "chars": 34469,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "README.md",
    "chars": 2423,
    "preview": "<div align=\"center\">\n    <br/>\n    <p>\n        <img src=\"web/static/favicon.png\" title=\"cobalt\" alt=\"cobalt logo\" width="
  },
  {
    "path": "api/LICENSE",
    "chars": 34469,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "api/README.md",
    "chars": 7810,
    "preview": "# cobalt api\nthis directory includes the source code for cobalt api. it's made with [express.js](https://www.npmjs.com/p"
  },
  {
    "path": "api/package.json",
    "chars": 1433,
    "preview": "{\n    \"name\": \"@imput/cobalt-api\",\n    \"description\": \"save what you love\",\n    \"version\": \"11.5\",\n    \"author\": \"imput\""
  },
  {
    "path": "api/src/cobalt.js",
    "chars": 857,
    "preview": "import \"dotenv/config\";\n\nimport express from \"express\";\nimport cluster from \"node:cluster\";\n\nimport path from \"path\";\nim"
  },
  {
    "path": "api/src/config.js",
    "chars": 1101,
    "preview": "import { getVersion } from \"@imput/version-info\";\nimport { loadEnvs, validateEnvs } from \"./core/env.js\";\n\nconst version"
  },
  {
    "path": "api/src/core/api.js",
    "chars": 11823,
    "preview": "import cors from \"cors\";\nimport http from \"node:http\";\nimport rateLimit from \"express-rate-limit\";\nimport { setGlobalDis"
  },
  {
    "path": "api/src/core/env.js",
    "chars": 10125,
    "preview": "import { Constants } from \"youtubei.js\";\nimport { services } from \"../processing/service-config.js\";\nimport { updateEnv,"
  },
  {
    "path": "api/src/core/itunnel.js",
    "chars": 1522,
    "preview": "import stream from \"../stream/stream.js\";\nimport { getInternalTunnel } from \"../stream/manage.js\";\nimport { setTunnelPor"
  },
  {
    "path": "api/src/misc/cluster.js",
    "chars": 1818,
    "preview": "import cluster from \"node:cluster\";\nimport net from \"node:net\";\nimport { syncSecrets } from \"../security/secrets.js\";\nim"
  },
  {
    "path": "api/src/misc/console-text.js",
    "chars": 640,
    "preview": "const ANSI = {\n    RESET: \"\\x1b[0m\",\n    BRIGHT: \"\\x1b[1m\",\n    RED: \"\\x1b[31m\",\n    GREEN: \"\\x1b[32m\",\n    CYAN: \"\\x1b["
  },
  {
    "path": "api/src/misc/crypto.js",
    "chars": 708,
    "preview": "import { createCipheriv, createDecipheriv } from \"crypto\";\n\nconst algorithm = \"aes256\";\n\nexport function encryptStream(p"
  },
  {
    "path": "api/src/misc/file-watcher.js",
    "chars": 1114,
    "preview": "import { EventEmitter } from 'node:events';\nimport * as fs from 'node:fs/promises';\n\nexport class FileWatcher extends Ev"
  },
  {
    "path": "api/src/misc/language-codes.js",
    "chars": 2959,
    "preview": "// converted from this file https://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt\nconst iso639_1to2 = {\n    'aa': '"
  },
  {
    "path": "api/src/misc/load-from-fs.js",
    "chars": 411,
    "preview": "import * as fs from \"fs\";\nimport { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst ro"
  },
  {
    "path": "api/src/misc/randomize-ciphers.js",
    "chars": 916,
    "preview": "import tls from 'node:tls';\nimport { randomBytes } from 'node:crypto';\n\nconst ORIGINAL_CIPHERS = tls.DEFAULT_CIPHERS;\n\n/"
  },
  {
    "path": "api/src/misc/run-test.js",
    "chars": 1618,
    "preview": "import { normalizeRequest } from \"../processing/request.js\";\nimport match from \"../processing/match.js\";\nimport { extrac"
  },
  {
    "path": "api/src/misc/utils.js",
    "chars": 1798,
    "preview": "import { request } from \"undici\";\nconst redirectStatuses = new Set([301, 302, 303, 307, 308]);\n\nexport async function ge"
  },
  {
    "path": "api/src/processing/cookie/cookie.js",
    "chars": 1062,
    "preview": "import { strict as assert } from 'node:assert';\n\nexport default class Cookie {\n    constructor(input) {\n        assert(t"
  },
  {
    "path": "api/src/processing/cookie/manager.js",
    "chars": 4704,
    "preview": "import Cookie from './cookie.js';\n\nimport { readFile, writeFile } from 'fs/promises';\nimport { Red, Green, Yellow } from"
  },
  {
    "path": "api/src/processing/create-filename.js",
    "chars": 2325,
    "preview": "// characters that are disallowed on windows:\n// https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#na"
  },
  {
    "path": "api/src/processing/helpers/youtube-session.js",
    "chars": 2262,
    "preview": "import * as cluster from \"../../misc/cluster.js\";\n\nimport { Agent } from \"undici\";\nimport { env } from \"../../config.js\""
  },
  {
    "path": "api/src/processing/match-action.js",
    "chars": 8921,
    "preview": "import createFilename from \"./create-filename.js\";\n\nimport { createResponse } from \"./request.js\";\nimport { audioIgnore "
  },
  {
    "path": "api/src/processing/match.js",
    "chars": 11147,
    "preview": "import { strict as assert } from \"node:assert\";\n\nimport { env } from \"../config.js\";\nimport { createResponse } from \"../"
  },
  {
    "path": "api/src/processing/request.js",
    "chars": 4231,
    "preview": "import mime from \"mime\";\nimport ipaddr from \"ipaddr.js\";\n\nimport { apiSchema } from \"./schema.js\";\nimport { createProxyT"
  },
  {
    "path": "api/src/processing/schema.js",
    "chars": 1666,
    "preview": "import { z } from \"zod\";\nimport { normalizeURL } from \"./url.js\";\n\nexport const apiSchema = z.object({\n    url: z.string"
  },
  {
    "path": "api/src/processing/service-alias.js",
    "chars": 228,
    "preview": "const friendlyNames = {\n    bsky: \"bluesky\",\n    twitch: \"twitch clips\"\n}\n\nexport const friendlyServiceName = (service) "
  },
  {
    "path": "api/src/processing/service-config.js",
    "chars": 6003,
    "preview": "import UrlPattern from \"url-pattern\";\n\nexport const audioIgnore = new Set([\"vk\", \"ok\", \"loom\"]);\nexport const hlsExcepti"
  },
  {
    "path": "api/src/processing/service-patterns.js",
    "chars": 3077,
    "preview": "export const testers = {\n    \"bilibili\": pattern =>\n        (pattern.comId?.length <= 12 && pattern.partId?.length <= 3)"
  },
  {
    "path": "api/src/processing/services/bilibili.js",
    "chars": 3237,
    "preview": "import { genericUserAgent, env } from \"../../config.js\";\nimport { resolveRedirectingURL } from \"../url.js\";\n\n// TO-DO: h"
  },
  {
    "path": "api/src/processing/services/bluesky.js",
    "chars": 4359,
    "preview": "import HLS from \"hls-parser\";\nimport { cobaltUserAgent } from \"../../config.js\";\nimport { createStream } from \"../../str"
  },
  {
    "path": "api/src/processing/services/dailymotion.js",
    "chars": 3588,
    "preview": "import HLSParser from \"hls-parser\";\nimport { env } from \"../../config.js\";\n\nlet _token;\n\nfunction getExp(token) {\n    re"
  },
  {
    "path": "api/src/processing/services/facebook.js",
    "chars": 1848,
    "preview": "import { genericUserAgent } from \"../../config.js\";\n\nconst headers = {\n    'User-Agent': genericUserAgent,\n    'Accept':"
  },
  {
    "path": "api/src/processing/services/instagram.js",
    "chars": 19451,
    "preview": "import { randomBytes } from \"node:crypto\";\nimport { resolveRedirectingURL } from \"../url.js\";\nimport { genericUserAgent "
  },
  {
    "path": "api/src/processing/services/loom.js",
    "chars": 3158,
    "preview": "import { genericUserAgent } from \"../../config.js\";\n\nconst craftHeaders = id => ({\n    \"user-agent\": genericUserAgent,\n "
  },
  {
    "path": "api/src/processing/services/newgrounds.js",
    "chars": 2893,
    "preview": "import { genericUserAgent } from \"../../config.js\";\n\nconst getVideo = async ({ id, quality }) => {\n    const json = awai"
  },
  {
    "path": "api/src/processing/services/ok.js",
    "chars": 1876,
    "preview": "import { genericUserAgent, env } from \"../../config.js\";\n\nconst resolutions = {\n    \"ultra\": \"2160\",\n    \"quad\": \"1440\","
  },
  {
    "path": "api/src/processing/services/pinterest.js",
    "chars": 1684,
    "preview": "import { genericUserAgent } from \"../../config.js\";\nimport { resolveRedirectingURL } from \"../url.js\";\n\nconst videoRegex"
  },
  {
    "path": "api/src/processing/services/reddit.js",
    "chars": 4660,
    "preview": "import { resolveRedirectingURL } from \"../url.js\";\nimport { genericUserAgent, env } from \"../../config.js\";\nimport { get"
  },
  {
    "path": "api/src/processing/services/rutube.js",
    "chars": 2922,
    "preview": "import HLS from \"hls-parser\";\nimport { env } from \"../../config.js\";\n\nasync function requestJSON(url) {\n    try {\n      "
  },
  {
    "path": "api/src/processing/services/snapchat.js",
    "chars": 3991,
    "preview": "import { resolveRedirectingURL } from \"../url.js\";\nimport { genericUserAgent } from \"../../config.js\";\nimport { createSt"
  },
  {
    "path": "api/src/processing/services/soundcloud.js",
    "chars": 4867,
    "preview": "import { env } from \"../../config.js\";\nimport { resolveRedirectingURL } from \"../url.js\";\n\nconst cachedID = {\n    versio"
  },
  {
    "path": "api/src/processing/services/streamable.js",
    "chars": 732,
    "preview": "export default async function(obj) {\n    let video = await fetch(`https://api.streamable.com/videos/${obj.id}`)\n        "
  },
  {
    "path": "api/src/processing/services/tiktok.js",
    "chars": 5068,
    "preview": "import Cookie from \"../cookie/cookie.js\";\n\nimport { extract, normalizeURL } from \"../url.js\";\nimport { genericUserAgent "
  },
  {
    "path": "api/src/processing/services/tumblr.js",
    "chars": 2435,
    "preview": "import psl from \"@imput/psl\";\n\nconst API_KEY = 'jrsCWX1XDuVxAFO4GkK147syAoN8BJZ5voz8tS80bPcj26Vc5Z';\nconst API_BASE = 'h"
  },
  {
    "path": "api/src/processing/services/twitch.js",
    "chars": 2989,
    "preview": "import { env } from \"../../config.js\";\n\nconst gqlURL = \"https://gql.twitch.tv/gql\";\nconst clientIdHead = { \"client-id\": "
  },
  {
    "path": "api/src/processing/services/twitter.js",
    "chars": 14128,
    "preview": "import HLS from \"hls-parser\";\nimport { genericUserAgent } from \"../../config.js\";\nimport { createStream } from \"../../st"
  },
  {
    "path": "api/src/processing/services/vimeo.js",
    "chars": 6986,
    "preview": "import HLS from \"hls-parser\";\nimport { env } from \"../../config.js\";\nimport { merge } from '../../misc/utils.js';\nimport"
  },
  {
    "path": "api/src/processing/services/vk.js",
    "chars": 4446,
    "preview": "import { env } from \"../../config.js\";\n\nconst resolutions = [\"2160\", \"1440\", \"1080\", \"720\", \"480\", \"360\", \"240\", \"144\"];"
  },
  {
    "path": "api/src/processing/services/xiaohongshu.js",
    "chars": 3039,
    "preview": "import { resolveRedirectingURL } from \"../url.js\";\nimport { genericUserAgent } from \"../../config.js\";\nimport { createSt"
  },
  {
    "path": "api/src/processing/services/youtube.js",
    "chars": 18250,
    "preview": "import HLS from \"hls-parser\";\n\nimport { fetch } from \"undici\";\nimport { Innertube, Session } from \"youtubei.js\";\n\nimport"
  },
  {
    "path": "api/src/processing/url.js",
    "chars": 7657,
    "preview": "import psl from \"@imput/psl\";\nimport { strict as assert } from \"node:assert\";\n\nimport { env } from \"../config.js\";\nimpor"
  },
  {
    "path": "api/src/security/api-keys.js",
    "chars": 7849,
    "preview": "import { env } from \"../config.js\";\nimport { Green, Yellow } from \"../misc/console-text.js\";\nimport ip from \"ipaddr.js\";"
  },
  {
    "path": "api/src/security/jwt.js",
    "chars": 1542,
    "preview": "import { nanoid } from \"nanoid\";\nimport { createHmac } from \"crypto\";\n\nimport { env } from \"../config.js\";\n\nconst toBase"
  },
  {
    "path": "api/src/security/secrets.js",
    "chars": 1726,
    "preview": "import cluster from \"node:cluster\";\nimport { createHmac, randomBytes } from \"node:crypto\";\n\nconst generateSalt = () => {"
  },
  {
    "path": "api/src/security/turnstile.js",
    "chars": 542,
    "preview": "import { env } from \"../config.js\";\n\nexport const verifyTurnstileToken = async (turnstileResponse, ip) => {\n    const re"
  },
  {
    "path": "api/src/store/base-store.js",
    "chars": 1066,
    "preview": "const _stores = new Set();\n\nexport class Store {\n    id;\n\n    constructor(name) {\n        name = name.toUpperCase();\n\n  "
  },
  {
    "path": "api/src/store/memory-store.js",
    "chars": 2012,
    "preview": "import { MinPriorityQueue } from '@datastructures-js/priority-queue';\nimport { Store } from './base-store.js';\n\n// minim"
  },
  {
    "path": "api/src/store/redis-ratelimit.js",
    "chars": 500,
    "preview": "import { env } from \"../config.js\";\n\nlet client, redis, redisLimiter;\n\nexport const createStore = async (name) => {\n    "
  },
  {
    "path": "api/src/store/redis-store.js",
    "chars": 1413,
    "preview": "import { commandOptions, createClient } from \"redis\";\nimport { env } from \"../config.js\";\nimport { Store } from \"./base-"
  },
  {
    "path": "api/src/store/store.js",
    "chars": 211,
    "preview": "import { env } from '../config.js';\n\nlet _export;\nif (env.redisURL) {\n    _export = await import('./redis-store.js');\n} "
  },
  {
    "path": "api/src/stream/ffmpeg.js",
    "chars": 5621,
    "preview": "import ffmpeg from \"ffmpeg-static\";\nimport { spawn } from \"child_process\";\nimport { create as contentDisposition } from "
  },
  {
    "path": "api/src/stream/internal-hls.js",
    "chars": 4425,
    "preview": "import HLS from \"hls-parser\";\nimport { createInternalStream } from \"./manage.js\";\nimport { request } from \"undici\";\n\nfun"
  },
  {
    "path": "api/src/stream/internal.js",
    "chars": 5626,
    "preview": "import { request } from \"undici\";\nimport { Readable } from \"node:stream\";\nimport { closeRequest, getHeaders, pipe } from"
  },
  {
    "path": "api/src/stream/manage.js",
    "chars": 8065,
    "preview": "import Store from \"../store/store.js\";\n\nimport { nanoid } from \"nanoid\";\nimport { randomBytes } from \"crypto\";\nimport { "
  },
  {
    "path": "api/src/stream/proxy.js",
    "chars": 1376,
    "preview": "import { Agent, request } from \"undici\";\nimport { create as contentDisposition } from \"content-disposition-header\";\n\nimp"
  },
  {
    "path": "api/src/stream/shared.js",
    "chars": 2248,
    "preview": "import { genericUserAgent } from \"../config.js\";\nimport { vkClientAgent } from \"../processing/services/vk.js\";\nimport { "
  },
  {
    "path": "api/src/stream/stream.js",
    "chars": 842,
    "preview": "import proxy from \"./proxy.js\";\nimport ffmpeg from \"./ffmpeg.js\";\n\nimport { closeResponse } from \"./shared.js\";\nimport {"
  },
  {
    "path": "api/src/util/generate-jwt-secret.js",
    "chars": 587,
    "preview": "// run with `pnpm -r token:jwt`\n\nconst makeSecureString = (length = 64) => {\n    const alphabet = 'abcdefghijklmnopqrstu"
  },
  {
    "path": "api/src/util/test.js",
    "chars": 4229,
    "preview": "import path from \"node:path\";\n\nimport { env } from \"../config.js\";\nimport { runTest } from \"../misc/run-test.js\";\nimport"
  },
  {
    "path": "api/src/util/tests/bilibili.json",
    "chars": 1696,
    "preview": "[\n    {\n        \"name\": \"1080p video\",\n        \"url\": \"https://www.bilibili.com/video/BV18i4y1m7xV/\",\n        \"params\": "
  },
  {
    "path": "api/src/util/tests/bsky.json",
    "chars": 2616,
    "preview": "[\n    {\n        \"name\": \"horizontal video\",\n        \"url\": \"https://bsky.app/profile/did:plc:oisofpd7lj26yvgiivf3lxsi/po"
  },
  {
    "path": "api/src/util/tests/dailymotion.json",
    "chars": 663,
    "preview": "[\n    {\n        \"name\": \"regular video\",\n        \"url\": \"https://www.dailymotion.com/video/x8t1eho\",\n        \"params\": {"
  },
  {
    "path": "api/src/util/tests/facebook.json",
    "chars": 1672,
    "preview": "[\n    {\n        \"name\": \"direct video with username and id\",\n        \"url\": \"https://web.facebook.com/100071784061914/vi"
  },
  {
    "path": "api/src/util/tests/instagram.json",
    "chars": 3407,
    "preview": "[\n    {\n        \"name\": \"single photo post\",\n        \"url\": \"https://www.instagram.com/p/DFx6KVduFWy/\",\n        \"params\""
  },
  {
    "path": "api/src/util/tests/loom.json",
    "chars": 1636,
    "preview": "[\n    {\n        \"name\": \"1080p video\",\n        \"url\": \"https://www.loom.com/share/d165fd054a294d8a8587807bcc50c885\",\n   "
  },
  {
    "path": "api/src/util/tests/newgrounds.json",
    "chars": 994,
    "preview": "[\n    {\n        \"name\": \"regular video\",\n        \"url\": \"https://www.newgrounds.com/portal/view/938050\",\n        \"params"
  },
  {
    "path": "api/src/util/tests/ok.json",
    "chars": 210,
    "preview": "[\n    {\n        \"name\": \"regular video\",\n        \"url\": \"https://ok.ru/video/7204071410346\",\n        \"params\": {},\n     "
  },
  {
    "path": "api/src/util/tests/pinterest.json",
    "chars": 2471,
    "preview": "[\n    {\n        \"name\": \"regular video\",\n        \"url\": \"https://www.pinterest.com/pin/70437485604616/\",\n        \"params"
  },
  {
    "path": "api/src/util/tests/reddit.json",
    "chars": 2430,
    "preview": "[\n    {\n        \"name\": \"video with audio\",\n        \"url\": \"https://www.reddit.com/r/TikTokCringe/comments/wup1fg/id_be_"
  },
  {
    "path": "api/src/util/tests/rutube.json",
    "chars": 2595,
    "preview": "[\n    {\n        \"name\": \"regular video\",\n        \"url\": \"https://rutube.ru/video/b2f6c27649907c2fde0af411b03825eb/\",\n   "
  },
  {
    "path": "api/src/util/tests/snapchat.json",
    "chars": 694,
    "preview": "[\n    {\n        \"name\": \"spotlight\",\n        \"url\": \"https://www.snapchat.com/spotlight/W7_EDlXWTBiXAEEniNoMPwAAYdWxucG9"
  },
  {
    "path": "api/src/util/tests/soundcloud.json",
    "chars": 2909,
    "preview": "[\n    {\n        \"name\": \"public song (best)\",\n        \"url\": \"https://soundcloud.com/l2share77/loona-butterfly?utm_sourc"
  },
  {
    "path": "api/src/util/tests/streamable.json",
    "chars": 1148,
    "preview": "[\n    {\n        \"name\": \"regular video\",\n        \"url\": \"https://streamable.com/p9cln4\",\n        \"params\": {},\n        \""
  },
  {
    "path": "api/src/util/tests/tiktok.json",
    "chars": 1165,
    "preview": "[\n    {\n        \"name\": \"long link video\",\n        \"url\": \"https://www.tiktok.com/@fatfatmillycat/video/7195741644585454"
  },
  {
    "path": "api/src/util/tests/tumblr.json",
    "chars": 1304,
    "preview": "[\n    {\n        \"name\": \"at.tumblr link\",\n        \"url\": \"https://at.tumblr.com/music/704177038274281472/n7x7pr7x4w2b\",\n"
  },
  {
    "path": "api/src/util/tests/twitch.json",
    "chars": 1125,
    "preview": "[\n    {\n        \"name\": \"clip\",\n        \"url\": \"https://twitch.tv/rtgame/clip/TubularInventiveSardineCorgiDerp-PM47mJQQ2"
  },
  {
    "path": "api/src/util/tests/twitter.json",
    "chars": 6247,
    "preview": "[\n    {\n        \"name\": \"regular video\",\n        \"url\": \"https://twitter.com/X/status/1697304622749086011\",\n        \"par"
  },
  {
    "path": "api/src/util/tests/vimeo.json",
    "chars": 1471,
    "preview": "[\n    {\n        \"name\": \"4k progressive\",\n        \"url\": \"https://vimeo.com/288386543\",\n        \"params\": {\n            "
  },
  {
    "path": "api/src/util/tests/vk.json",
    "chars": 1955,
    "preview": "[\n    {\n        \"name\": \"clip, defaults\",\n        \"url\": \"https://vk.com/clip-57274055_456239788\",\n        \"params\": {},"
  },
  {
    "path": "api/src/util/tests/xiaohongshu.json",
    "chars": 1838,
    "preview": "[\n    {\n        \"name\": \"video (might have expired)\",\n        \"url\": \"https://www.xiaohongshu.com/explore/685e63e1000000"
  },
  {
    "path": "api/src/util/tests/youtube.json",
    "chars": 6437,
    "preview": "[\n    {\n        \"name\": \"4k video (h264, 1440)\",\n        \"url\": \"https://www.youtube.com/watch?v=vPwaXytZcgI\",\n        \""
  },
  {
    "path": "docs/api-env-variables.md",
    "chars": 12639,
    "preview": "# cobalt api instance environment variables\nyou can customize your processing instance's behavior using these environmen"
  },
  {
    "path": "docs/api.md",
    "chars": 14494,
    "preview": "# cobalt api documentation\nmethods, acceptable values, headers, responses and everything else related to making and pars"
  },
  {
    "path": "docs/examples/cookies.example.json",
    "chars": 571,
    "preview": "{\n    \"instagram\": [\n        \"mid=<replace>; ig_did=<with>; csrftoken=<your>; ds_user_id=<own>; sessionid=<cookies>\"\n   "
  },
  {
    "path": "docs/examples/docker-compose.example.yml",
    "chars": 1875,
    "preview": "services:\n    cobalt:\n        image: ghcr.io/imputnet/cobalt:11\n\n        init: true\n        read_only: true\n        rest"
  },
  {
    "path": "docs/protect-an-instance.md",
    "chars": 8163,
    "preview": "# how to protect your cobalt instance\nif you keep getting a ton of unknown traffic that hurts the performance of your in"
  },
  {
    "path": "docs/run-an-instance.md",
    "chars": 2750,
    "preview": "# how to run a cobalt instance\nthis tutorial will help you run your own cobalt processing instance. if your instance is "
  },
  {
    "path": "package.json",
    "chars": 106,
    "preview": "{\n    \"name\": \"cobalt\",\n    \"packageManager\": \"pnpm@9.6.0\",\n    \"engines\": {\n        \"pnpm\": \">=9\"\n    }\n}"
  },
  {
    "path": "packages/api-client/.gitignore",
    "chars": 5,
    "preview": "dist\n"
  },
  {
    "path": "packages/api-client/.prettierignore",
    "chars": 25,
    "preview": "# Ignore artifacts:\ndist\n"
  },
  {
    "path": "packages/api-client/.prettierrc",
    "chars": 104,
    "preview": "{\n    \"tabWidth\": 4,\n    \"singleQuote\": true,\n    \"trailingComma\": \"none\",\n    \"arrowParens\": \"avoid\"\n}\n"
  },
  {
    "path": "packages/api-client/LICENSE",
    "chars": 1061,
    "preview": "MIT License\n\nCopyright (c) 2024 imput\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof t"
  },
  {
    "path": "packages/api-client/package.json",
    "chars": 329,
    "preview": "{\n    \"name\": \"@imput/cobalt-client\",\n    \"version\": \"0.0.1\",\n    \"description\": \"\",\n    \"main\": \"index.js\",\n    \"script"
  },
  {
    "path": "packages/api-client/tsconfig.json",
    "chars": 344,
    "preview": "{\n    \"include\": [\"src\"],\n    \"compilerOptions\": {\n        \"target\": \"es2016\",\n        \"module\": \"commonjs\",\n        \"ro"
  },
  {
    "path": "packages/version-info/index.d.ts",
    "chars": 266,
    "preview": "declare module \"@imput/version-info\" {\n    export function getCommit(): Promise<string | undefined>;\n    export function"
  },
  {
    "path": "packages/version-info/index.js",
    "chars": 1906,
    "preview": "import { existsSync }  from 'node:fs';\nimport { join, parse } from 'node:path';\nimport { cwd }         from 'node:proces"
  },
  {
    "path": "packages/version-info/package.json",
    "chars": 539,
    "preview": "{\n    \"name\": \"@imput/version-info\",\n    \"version\": \"1.0.1\",\n    \"description\": \"helper package for cobalt that provides"
  },
  {
    "path": "pnpm-workspace.yaml",
    "chars": 53,
    "preview": "packages:\n    - \"api\"\n    - \"web\"\n    - \"packages/*\"\n"
  },
  {
    "path": "web/.gitignore",
    "chars": 100,
    "preview": "# builds\n/build\n/.svelte-kit\n/package\n\n# vite\nvite.config.js.timestamp-*\nvite.config.ts.timestamp-*\n"
  },
  {
    "path": "web/.npmrc",
    "chars": 19,
    "preview": "engine-strict=true\n"
  },
  {
    "path": "web/LICENSE",
    "chars": 20844,
    "preview": "Attribution-NonCommercial-ShareAlike 4.0 International\n\n================================================================"
  },
  {
    "path": "web/README.md",
    "chars": 5459,
    "preview": "# cobalt web\nthe cobalt frontend is a static web app built with\n[sveltekit](https://kit.svelte.dev/) + [vite](https://vi"
  },
  {
    "path": "web/changelogs/10.0.md",
    "chars": 4815,
    "preview": "---\ntitle: \"cobalt, reborn\"\ndate: \"9 Sept, 2024\"\nbanner:\n    file: \"cobalt10.webp\"\n    alt: \"meowth plush staring into a"
  },
  {
    "path": "web/changelogs/10.1.md",
    "chars": 3620,
    "preview": "---\ntitle: \"squashing bugs, improving security and ux\"\ndate: \"1 Oct, 2024\"\nbanner:\n    file: \"meowth101hammer.webp\"\n    "
  },
  {
    "path": "web/changelogs/10.3.md",
    "chars": 6967,
    "preview": "---\ntitle: \"fastest cobalt yet, new youtube features, translation platform, and a lot more\"\ndate: \"4 Nov, 2024\"\nbanner:\n"
  },
  {
    "path": "web/changelogs/10.5.md",
    "chars": 7175,
    "preview": "---\ntitle: \"merry christmas and happy new year!\"\ndate: \"23 Dec, 2024\"\nbanner:\n    file: \"newyear2025.webp\"\n    alt: \"meo"
  },
  {
    "path": "web/changelogs/11.0.md",
    "chars": 12576,
    "preview": "---\ntitle: \"local media processing, better performance, and a lot of polish\"\ndate: \"29 May, 2025\"\nbanner:\n    file: \"meo"
  },
  {
    "path": "web/changelogs/11.2.md",
    "chars": 6228,
    "preview": "---\ntitle: \"local processing for everyone, subtitles, audio covers, and more\"\ndate: \"30 June, 2025\"\nbanner:\n    file: \"m"
  },
  {
    "path": "web/changelogs/2.0.md",
    "chars": 696,
    "preview": "---\ntitle: \"everything is new!\"\ndate: \"Jun 28, 2022\"\n---\n\n- added support for: bilibili.com, youtube, youtube music, red"
  },
  {
    "path": "web/changelogs/2.2.5.md",
    "chars": 805,
    "preview": "---\ntitle: \"remade localization system once again\"\ndate: \"Jul 24, 2022\"\n---\n\n- new localization system: fast, dynamic, w"
  },
  {
    "path": "web/changelogs/2.2.6.md",
    "chars": 394,
    "preview": "---\ntitle: \"tiktok is back!\"\ndate: \"Jul 28, 2022\"\n---\n\n- added support for tiktok (images won't work, they're only acces"
  },
  {
    "path": "web/changelogs/2.2.8.md",
    "chars": 203,
    "preview": "---\ntitle: \"faster and more accessible\"\ndate: \"Jul 30, 2022\"\n---\n\n- spanish localization by @adrigoomy\n- cobalt should l"
  },
  {
    "path": "web/changelogs/2.2.9.md",
    "chars": 264,
    "preview": "---\ntitle: \"fixes\"\ndate: \"Aug 6, 2022\"\n---\n\n- fixed neighbor quality picking for youtube videos\n- webm is now default fo"
  },
  {
    "path": "web/changelogs/2.2.md",
    "chars": 654,
    "preview": "---\ntitle: \"beginning of 2.2\"\ndate: \"Jul 13, 2022\"\n---\n\n- added download popup to solve the issue with downloads on ios\n"
  },
  {
    "path": "web/changelogs/3.0.md",
    "chars": 2830,
    "preview": "---\ntitle: \"everything what you've been waiting for. welcome to cobalt 3.0 :)\"\ndate: \"Aug 12, 2022\"\n---\n\nfollow cobalt's"
  },
  {
    "path": "web/changelogs/3.1.md",
    "chars": 511,
    "preview": "---\ntitle: small quality of life improvements\ndate: \"Aug 16, 2022\"\n---\n\n- tiktok videos can now be downloaded without wa"
  },
  {
    "path": "web/changelogs/3.2.md",
    "chars": 461,
    "preview": "---\ntitle: ukrainian localization and new error popup\ndate: \"Aug 19, 2022\"\n---\n\n- added ukrainian localization (thanks t"
  },
  {
    "path": "web/changelogs/3.4.md",
    "chars": 873,
    "preview": "---\ntitle: tiktok images and better localization\ndate: \"Sep 3, 2022\"\n---\n\n- added ability to save images from tiktok con"
  },
  {
    "path": "web/changelogs/3.5.2.md",
    "chars": 1024,
    "preview": "---\ntitle: \"vk clips support, improved changelog system, and less bugs\"\ndate: \"Sep 11, 2022\"\n---\nnew features:\n- added s"
  },
  {
    "path": "web/changelogs/3.5.4.md",
    "chars": 230,
    "preview": "---\ntitle: \"tiktok support is back :D\"\ndate: \"Sep 21, 2022\"\n---\nyou can download videos, sounds, and images from tiktok "
  },
  {
    "path": "web/changelogs/3.5.md",
    "chars": 1783,
    "preview": "---\ntitle: \"ui revamp and usability improvements\"\ndate: \"Sep 8, 2022\"\n---\nnew features:\n- cobalt now lets you paste the "
  },
  {
    "path": "web/changelogs/3.6.3.md",
    "chars": 697,
    "preview": "---\ntitle: \"less disturbance\"\ndate: \"Oct 5, 2022\"\n---\nchangelog popup no longer annoys you after a major update! this ac"
  },
  {
    "path": "web/changelogs/3.6.md",
    "chars": 601,
    "preview": "---\ntitle: \"improvements all around!\"\ndate: \"Sep 28, 2022\"\n---\n- download mode switcher is moving places, it's now right"
  },
  {
    "path": "web/changelogs/3.7.md",
    "chars": 1254,
    "preview": "---\ntitle: \"support for multi media tweets is here!\"\ndate: \"Oct 9, 2022\"\n---\ncobalt now lets you save any of the videos "
  },
  {
    "path": "web/changelogs/4.0.md",
    "chars": 1561,
    "preview": "---\ntitle: \"better and faster than ever\"\ndate: \"Oct 24, 2022\"\n---\nthis update has a ton of improvements and new features"
  },
  {
    "path": "web/changelogs/4.1.md",
    "chars": 531,
    "preview": "---\ntitle: \"better tiktok image downloads\"\ndate: \"Oct 27, 2022\"\n---\nhere's what's up:\n- tiktok images are saved as .jpeg"
  },
  {
    "path": "web/changelogs/4.2.md",
    "chars": 709,
    "preview": "---\ntitle: \"optimized quality picking and 8k video support\"\ndate: \"Nov 4, 2022\"\n---\n- this update fixes quality picking "
  },
  {
    "path": "web/changelogs/4.3.2.md",
    "chars": 662,
    "preview": "---\ntitle: \"twitter improvements & changelog overhaul\"\ndate: \"Nov 15, 2022\"\n---\n- you can download explicit content from"
  },
  {
    "path": "web/changelogs/4.3.md",
    "chars": 1908,
    "preview": "---\ntitle: \"developers, developers, developers, developers\"\ndate: \"Nov 12, 2022\"\nbanner:\n    file: \"developers.webp\"\n   "
  },
  {
    "path": "web/changelogs/4.4.md",
    "chars": 602,
    "preview": "---\ntitle: \"over 1 million monthly requests. thank you.\"\ndate: \"Nov 20, 2022\"\nbanner:\n    file: \"onemillionr.webp\"\n    a"
  },
  {
    "path": "web/changelogs/4.5.md",
    "chars": 2423,
    "preview": "---\ntitle: \"better, faster, stronger, stable\"\ndate: \"Dec 6, 2022\"\nbanner:\n    file: \"meowthstrong.webp\"\n    alt: \"meowth"
  },
  {
    "path": "web/changelogs/4.6.md",
    "chars": 1389,
    "preview": "---\ntitle: \"mute videos and proper soundcloud support\"\ndate: \"Dec 17, 2022\"\nbanner:\n    file: \"shutup.webp\"\n    alt: \"a "
  },
  {
    "path": "web/changelogs/4.7.md",
    "chars": 2044,
    "preview": "---\ntitle: \"we're better together! thank you for bug reports.\"\ndate: \"Jan 13, 2023\"\nbanner:\n    file: \"bettertogether.we"
  },
  {
    "path": "web/changelogs/4.8.md",
    "chars": 1649,
    "preview": "---\ntitle: \"prettier than ever\"\ndate: \"Jan 29, 2023\"\nbanner:\n    file: \"catmakeup.webp\"\n    alt: \"a cat being brushed wi"
  },
  {
    "path": "web/changelogs/5.0.md",
    "chars": 2229,
    "preview": "---\ntitle: \"it's all about attention to detail!\"\ndate: \"Feb 13, 2023\"\nbanner:\n    file: \"valentines.webp\"\n    alt: \"rela"
  },
  {
    "path": "web/changelogs/5.1.md",
    "chars": 3246,
    "preview": "---\ntitle: \"the evil has been defeated\"\ndate: \"Feb 26, 2023\"\nbanner:\n    file: \"happymeowth.webp\"\n    alt: \"meowth jumpi"
  },
  {
    "path": "web/changelogs/5.2.md",
    "chars": 3385,
    "preview": "---\ntitle: \"fastest one in the game\"\ndate: \"Mar 24, 2023\"\nbanner:\n    file: \"catspeed.webp\"\n    alt: \"a cat running very"
  },
  {
    "path": "web/changelogs/5.3.md",
    "chars": 989,
    "preview": "---\ntitle: \"better looks, better feel\"\ndate: \"Apr 3, 2023\"\nbanner:\n    file: \"cattired.webp\"\n    alt: \"a cat laying on a"
  },
  {
    "path": "web/changelogs/5.4.md",
    "chars": 2265,
    "preview": "---\ntitle: \"instagram support, docker, and more!\"\ndate: \"Apr 24, 2023\"\nbanner:\n    file: \"catphonestand.webp\"\n    alt: \""
  },
  {
    "path": "web/changelogs/6.0.md",
    "chars": 3998,
    "preview": "---\ntitle: \"better reliability, new infrastructure, pinterest support, and way more!\"\ndate: \"June 7, 2023\"\nbanner:\n    f"
  },
  {
    "path": "web/changelogs/6.2.md",
    "chars": 1182,
    "preview": "---\ntitle: \"all network issues have been fixed!\"\ndate: \"June 27 2023\"\nbanner:\n    file: \"meowthhammer.webp\"\n    alt: \"me"
  },
  {
    "path": "web/changelogs/7.0.md",
    "chars": 4895,
    "preview": "---\ntitle: \"biggest ui refresh yet!\"\ndate: \"August 15, 2023\"\nbanner:\n    file: \"meowthcooking.webp\"\n    alt: \"meowth han"
  },
  {
    "path": "web/changelogs/7.1.md",
    "chars": 1257,
    "preview": "---\ntitle: \"instagram, streamable, video metadata, and more!\"\ndate: \"August 20, 2023\"\nbanner:\n    file: \"meowthproductio"
  },
  {
    "path": "web/changelogs/7.11.md",
    "chars": 2515,
    "preview": "---\ntitle: \"cache encryption, meowbalt, dailymotion, bilibili, and much more!\"\ndate: \"March 6, 2024\"\nbanner:\n    file: \""
  },
  {
    "path": "web/changelogs/7.13.md",
    "chars": 3850,
    "preview": "---\ntitle: \"better ux, improvements for youtube, twitter, tiktok, instagram, and more!\"\ndate: \"May 5, 2024\"\nbanner:\n    "
  },
  {
    "path": "web/changelogs/7.14.md",
    "chars": 3502,
    "preview": "---\ntitle: \"now helping over 1 million people monthly\"\ndate: \"May 17, 2024\"\nbanner:\n    file: \"millionusers.webp\"\n    al"
  },
  {
    "path": "web/changelogs/7.3.md",
    "chars": 1365,
    "preview": "---\ntitle: \"extended video length limit, metadata toggle, ui improvements, and more!\"\ndate: \"September 6, 2023\"\nbanner:\n"
  },
  {
    "path": "web/changelogs/7.4.md",
    "chars": 2423,
    "preview": "---\ntitle: \"new domain, what's coming in future, bug fixes, and more!\"\ndate: \"September 9, 2023\"\nbanner:\n    file: \"newd"
  },
  {
    "path": "web/changelogs/7.5.md",
    "chars": 1258,
    "preview": "---\ntitle: \"support for twitch clips and rutube!\"\ndate: \"September 16, 2023\"\nbanner:\n    file: \"twitchupdate.webp\"\n    a"
  },
  {
    "path": "web/changelogs/7.6.md",
    "chars": 1978,
    "preview": "---\ntitle: \"customizable file names, instagram stories, and first cobalt sponsor!\"\ndate: \"October 15, 2023\"\nbanner:\n    "
  },
  {
    "path": "web/changelogs/7.7.md",
    "chars": 1075,
    "preview": "---\ntitle: \"bugfixes and better downloads!\"\ndate: \"December 2, 2023\"\nbanner:\n    file: \"meowthpolishegg.webp\"\n    alt: \""
  },
  {
    "path": "web/changelogs/7.8.md",
    "chars": 1649,
    "preview": "---\ntitle: \"new years clean up! bug fixes and fresh look for the home page\"\ndate: \"December 25, 2023\"\nbanner:\n    file: "
  },
  {
    "path": "web/changelogs/7.9.md",
    "chars": 2001,
    "preview": "---\ntitle: \"twitter gifs, pinterest, ok.ru, and more!\"\ndate: \"January 17, 2024\"\nbanner:\n    file: \"meowthball.webp\"\n    "
  },
  {
    "path": "web/eslint.config.js",
    "chars": 194,
    "preview": "// @ts-check\n\nimport eslint from '@eslint/js';\nimport tseslint from 'typescript-eslint';\n\nexport default tseslint.config"
  },
  {
    "path": "web/i18n/en/a11y/dialog.json",
    "chars": 131,
    "preview": "{\n    \"picker.item.photo\": \"photo thumbnail\",\n    \"picker.item.video\": \"video thumbnail\",\n    \"picker.item.gif\": \"gif th"
  },
  {
    "path": "web/i18n/en/a11y/donate.json",
    "chars": 120,
    "preview": "{\n    \"share.qr.expand\": \"qr code. press to expand.\",\n    \"share.qr.collapse\": \"expanded qr code. press to collapse.\"\n}\n"
  },
  {
    "path": "web/i18n/en/a11y/general.json",
    "chars": 26,
    "preview": "{\n    \"back\": \"go back\"\n}\n"
  },
  {
    "path": "web/i18n/en/a11y/queue.json",
    "chars": 173,
    "preview": "{\n    \"status.default\": \"processing queue\",\n    \"status.completed\": \"processing queue. all tasks are completed.\",\n    \"s"
  },
  {
    "path": "web/i18n/en/a11y/save.json",
    "chars": 468,
    "preview": "{\n    \"link_area\": \"link input area\",\n    \"link_area.turnstile\": \"link input area. checking if you're not a robot.\",\n   "
  },
  {
    "path": "web/i18n/en/a11y/tabs.json",
    "chars": 34,
    "preview": "{\n    \"tab_panel\": \"tabs panel\"\n}\n"
  },
  {
    "path": "web/i18n/en/about/credits.md",
    "chars": 2908,
    "preview": "<script lang=\"ts\">\n    import { contacts, docs, partners } from \"$lib/env\";\n    import { t } from \"$lib/i18n/translation"
  },
  {
    "path": "web/i18n/en/about/general.md",
    "chars": 2781,
    "preview": "<script lang=\"ts\">\n    import { t } from \"$lib/i18n/translations\";\n    import { contacts, docs } from \"$lib/env\";\n\n    i"
  },
  {
    "path": "web/i18n/en/about/privacy.md",
    "chars": 4261,
    "preview": "<script lang=\"ts\">\n    import env from \"$lib/env\";\n    import { t } from \"$lib/i18n/translations\";\n\n    import SectionHe"
  },
  {
    "path": "web/i18n/en/about/terms.md",
    "chars": 2077,
    "preview": "<script lang=\"ts\">\n    import { t } from \"$lib/i18n/translations\";\n    import SectionHeading from \"$components/misc/Sect"
  },
  {
    "path": "web/i18n/en/about.json",
    "chars": 1735,
    "preview": "{\n    \"page.general\": \"what's cobalt?\",\n\n    \"page.community\": \"community & support\",\n\n    \"page.privacy\": \"privacy poli"
  },
  {
    "path": "web/i18n/en/button.json",
    "chars": 707,
    "preview": "{\n    \"gotit\": \"got it\",\n    \"cancel\": \"cancel\",\n    \"reset\": \"reset\",\n    \"done\": \"done\",\n    \"download.audio\": \"downlo"
  },
  {
    "path": "web/i18n/en/dialog.json",
    "chars": 2107,
    "preview": "{\n    \"reset_settings.title\": \"reset all settings?\",\n    \"reset_settings.body\": \"are you sure you want to reset all sett"
  },
  {
    "path": "web/i18n/en/donate.json",
    "chars": 1894,
    "preview": "{\n    \"banner.title\": \"Support a safe\\nand open Internet\",\n    \"banner.subtitle\": \"donate to imput or share the\\njoy of "
  },
  {
    "path": "web/i18n/en/error/api.json",
    "chars": 7191,
    "preview": "{\n    \"auth.jwt.missing\": \"couldn't authenticate with the processing instance because the access token is missing. try a"
  }
]

// ... and 213 more files (download for full content)

About this extraction

This page contains the full source code of the imputnet/cobalt GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 413 files (1.0 MB), approximately 272.4k tokens, and a symbol index with 270 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!