Compare commits

...
76 Commits
Author SHA1 Message Date
fraujulian 2e67987a44 docs: document Node 24 and lifecycle behavior
Build Validation / build (push) Failing after 33s
2026-08-24 14:13:55 +02:00
fraujulian 9d2d629a3e fix(voice): harden connection and playback lifecycle 2026-08-24 14:13:14 +02:00
fraujulian f48424e198 fix(ffmpeg): make process shutdown race-safe 2026-08-24 14:12:40 +02:00
fraujulian d750e5fe3f build(tooling): modernize Node and TypeScript setup 2026-08-24 14:12:04 +02:00
fraujulian 58d77b9771 refactor(errors): use native error causes 2026-08-24 14:11:23 +02:00
fraujulian 5fe9285bcb style(prettier): enforce LF line endings 2026-08-24 14:10:19 +02:00
fraujulian 0ec0479c4f ci(node): use Node.js 24 2026-08-24 14:09:44 +02:00
fraujulian 814ceb97e2 chore(gitea): remove unused issue templates 2026-08-24 14:09:05 +02:00
fraujulian 1a95376401 chore: add funding configuration 2026-07-27 15:59:54 +02:00
fraujulian f731845ea8 ci: migrate GitHub contributions to Gitea
Build Validation / build (push) Successful in 1m2s
2026-07-27 15:54:46 +02:00
fraujulian 40404781a9 docs: replace GitHub references with Gitea
Build Validation / build (push) Successful in 57s
2026-07-22 22:43:05 +02:00
fraujulian be478902db chore(package): update repository URLs 2026-07-22 22:43:04 +02:00
fraujulian 8c842b15a2 chore(package): exclude Gitea metadata 2026-07-22 22:43:02 +02:00
fraujulian 60a607a39b ci(gitea): migrate release workflow 2026-07-22 22:43:01 +02:00
fraujulian 4a23b46e54 ci(gitea): migrate validation workflow 2026-07-22 22:42:59 +02:00
fraujulian 641065dc58 chore(gitea): remove GitHub-only metadata 2026-07-22 22:42:58 +02:00
fraujulian 0b30982f04 chore(gitea): migrate issue templates 2026-07-22 22:41:53 +02:00
fraujulian b17ff5b52e Merge pull request #76 from FrauJulian/dependabot/npm_and_yarn/types/node-26.0.1
Bump @types/node from 26.0.0 to 26.0.1
2026-07-14 23:32:59 +02:00
fraujulian 16c153cfa7 Merge pull request #77 from FrauJulian/dependabot/npm_and_yarn/eslint-plugin-n-18.2.1
Bump eslint-plugin-n from 18.1.0 to 18.2.1
2026-07-14 23:32:40 +02:00
fraujulian 7050c608bc Merge pull request #81 from FrauJulian/dependabot/npm_and_yarn/prettier-3.9.4
Bump prettier from 3.8.4 to 3.9.4
2026-07-14 23:32:11 +02:00
fraujulian b2e1850df0 Merge pull request #82 from FrauJulian/dependabot/npm_and_yarn/typescript-eslint/parser-8.62.1
Bump @typescript-eslint/parser from 8.62.0 to 8.62.1
2026-07-14 23:31:53 +02:00
dependabot[bot] 03aacbdba6 Bump @typescript-eslint/parser from 8.62.0 to 8.62.1
Bumps [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser) from 8.62.0 to 8.62.1.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.62.1/packages/parser)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/parser"
  dependency-version: 8.62.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-30 13:33:31 +00:00
dependabot[bot] 6e64248a5b Bump prettier from 3.8.4 to 3.9.4
Bumps [prettier](https://github.com/prettier/prettier) from 3.8.4 to 3.9.4.
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.8.4...3.9.4)

---
updated-dependencies:
- dependency-name: prettier
  dependency-version: 3.9.4
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-30 13:33:17 +00:00
dependabot[bot] abc6a19cca Bump eslint-plugin-n from 18.1.0 to 18.2.1
Bumps [eslint-plugin-n](https://github.com/eslint-community/eslint-plugin-n) from 18.1.0 to 18.2.1.
- [Release notes](https://github.com/eslint-community/eslint-plugin-n/releases)
- [Changelog](https://github.com/eslint-community/eslint-plugin-n/blob/master/CHANGELOG.md)
- [Commits](https://github.com/eslint-community/eslint-plugin-n/compare/v18.1.0...v18.2.1)

---
updated-dependencies:
- dependency-name: eslint-plugin-n
  dependency-version: 18.2.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-26 13:33:32 +00:00
dependabot[bot] 7b24d7de6f Bump @types/node from 26.0.0 to 26.0.1
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 26.0.0 to 26.0.1.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 26.0.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-25 13:34:10 +00:00
fraujulian 74b45b7460 Merge pull request #73 from FrauJulian/dependabot/npm_and_yarn/typescript-eslint/eslint-plugin-8.62.0
Bump @typescript-eslint/eslint-plugin from 8.61.1 to 8.62.0
2026-06-24 08:42:08 +02:00
fraujulian 9ce21ec9ca Merge pull request #74 from FrauJulian/dependabot/npm_and_yarn/typescript-eslint/parser-8.62.0
Bump @typescript-eslint/parser from 8.61.1 to 8.62.0
2026-06-24 08:41:47 +02:00
dependabot[bot] f625f27599 Bump @typescript-eslint/parser from 8.61.1 to 8.62.0
Bumps [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser) from 8.61.1 to 8.62.0.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.62.0/packages/parser)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/parser"
  dependency-version: 8.62.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-23 13:34:08 +00:00
dependabot[bot] 298633267e Bump @typescript-eslint/eslint-plugin from 8.61.1 to 8.62.0
Bumps [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/eslint-plugin) from 8.61.1 to 8.62.0.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.62.0/packages/eslint-plugin)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/eslint-plugin"
  dependency-version: 8.62.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-23 13:33:55 +00:00
fraujulian f73213964b chore: update dependencies 2026-06-22 12:52:25 +02:00
fraujulian 60871ccd60 improve: docs 2026-06-22 12:51:46 +02:00
fraujulian 1f55657390 Merge pull request #72 from FrauJulian/66-67-68-69-70-71-multiple-bugs
improvements and bug fixes
2026-06-22 12:43:27 +02:00
fraujulian b4e92b9b7b improve: tests 2026-06-22 12:40:00 +02:00
fraujulian 215d67ce89 Reject non-finite volume values 2026-06-22 12:20:41 +02:00
fraujulian b29fda5ae9 Clean up failed voice connections 2026-06-22 12:18:35 +02:00
fraujulian d10dae1b53 Surface ffmpeg startup failures 2026-06-22 12:16:21 +02:00
fraujulian 1a77896c32 Add failed connection startup regression test 2026-06-22 12:12:48 +02:00
fraujulian a811feaede Handle renewal restart failures 2026-06-22 12:09:21 +02:00
fraujulian 24bbfc354f chore: updated issue templates 2026-06-22 11:37:05 +02:00
fraujulian faa48a0264 chore: update dependencies 2026-06-15 15:47:16 +02:00
fraujulian 9f4f70dcc0 fix: place version 2026-05-26 17:48:08 +02:00
fraujulian 907985b54e chore: added publish task 2026-05-26 17:44:18 +02:00
fraujulian 9998447c65 chore: updated ignore files 2026-05-26 17:43:58 +02:00
fraujulian e8fba67a1a chore(docs): updated md files 2026-05-26 17:41:05 +02:00
fraujulian b34afa0d8b chore: updated and improved dependencies 2026-05-26 17:33:56 +02:00
fraujulian 7f2eeaefb0 improve: tests 2026-05-26 17:33:11 +02:00
fraujulian 0fd3a41f1c chore: versioning 2026-05-26 17:10:26 +02:00
fraujulian 51d738a442 fix: rollout 2026-05-23 21:17:49 +02:00
fraujulian db7de9c04d fix: rollout 2026-05-23 21:12:11 +02:00
fraujulian eaf86f948b fix: rollout 2026-05-23 20:13:04 +02:00
fraujulian d4f92e1eac fix: rollout 2026-05-23 20:02:53 +02:00
fraujulian 9eace0838b fix: rollout 2026-05-23 19:56:12 +02:00
fraujulian 5cc7127a5a chore: updated dependencies 2026-05-23 19:48:54 +02:00
fraujulian 7923b917d8 chore: updated dependencies 2026-05-23 19:44:52 +02:00
fraujulian 78cbf3f233 refactor: husky 2026-05-23 19:38:05 +02:00
fraujulian 4cc9774ff5 feat: github release task 2026-05-23 19:37:12 +02:00
fraujulian 6962d87f24 feat & improvements & refactor: new structure, better garbage collection, better docs, better performance, added tests 2026-05-23 19:26:59 +02:00
fraujulian 966db49e37 Add LICENSE file 2026-05-23 19:07:24 +02:00
fraujulian 707822e43d Merge pull request #31 from FrauJulian/dependabot/npm_and_yarn/typescript-eslint/parser-8.50.1
Bump @typescript-eslint/parser from 8.50.0 to 8.50.1
2025-12-23 22:45:21 +01:00
fraujulian 29f51c5ff0 Merge pull request #32 from FrauJulian/dependabot/npm_and_yarn/typescript-eslint/eslint-plugin-8.50.1
Bump @typescript-eslint/eslint-plugin from 8.50.0 to 8.50.1
2025-12-23 22:45:14 +01:00
dependabot[bot] ee676212ab Bump @typescript-eslint/eslint-plugin from 8.50.0 to 8.50.1
Bumps [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/eslint-plugin) from 8.50.0 to 8.50.1.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.50.1/packages/eslint-plugin)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/eslint-plugin"
  dependency-version: 8.50.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-12-23 13:20:33 +00:00
dependabot[bot] 5496514dab Bump @typescript-eslint/parser from 8.50.0 to 8.50.1
Bumps [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser) from 8.50.0 to 8.50.1.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.50.1/packages/parser)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/parser"
  dependency-version: 8.50.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-12-23 13:20:21 +00:00
fraujulian 1e08cddc61 Merge pull request #30 from FrauJulian/dependabot/npm_and_yarn/types/node-25.0.3
Bump @types/node from 25.0.2 to 25.0.3
2025-12-18 08:00:19 +01:00
dependabot[bot] d07efd73a5 Bump @types/node from 25.0.2 to 25.0.3
Bumps [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) from 25.0.2 to 25.0.3.
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

---
updated-dependencies:
- dependency-name: "@types/node"
  dependency-version: 25.0.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-12-17 13:25:52 +00:00
fraujulian 4447437fd2 Update README for clarity and formatting 2025-12-17 08:20:50 +01:00
fraujulian 199f9f84c5 Merge pull request #29 from FrauJulian/20-gigantic-update
Gigantic Update - A lot bug fixes and refactorings.
2025-12-16 16:05:24 +01:00
Lechner Julian - FrauJulian 78bc4b4f24 eslint changes; 2025-12-16 16:02:07 +01:00
Lechner Julian - FrauJulian b0dc3ba52b Added issue templates; Removed packet managers, switched to npm; Fixed a lot of Bugs; Added new Versioning; Added types and reworked docs; Refactored project structure; 2025-12-16 16:01:33 +01:00
fraujulian 431c720162 Create SECURITY.md 2025-12-16 12:02:18 +01:00
fraujulian 309eb75716 Configure Dependabot for npm and daily updates 2025-12-16 11:58:05 +01:00
Lechner Julian - FrauJulian ba9709ddd1 Updated types 2025-10-10 18:48:22 +02:00
fraujulian bac8b41cb9 Merge pull request #19 from FrauJulian/fraujulian
Updated types;
2025-10-10 18:30:25 +02:00
Lechner Julian - FrauJulian ecc3189054 Updated pre-commit 2025-10-10 18:29:28 +02:00
Lechner Julian - FrauJulian 96ee35c1e4 Updated typing export/import; 2025-10-10 18:27:43 +02:00
Lechner Julian - FrauJulian f712ea73d7 Merge remote-tracking branch 'origin/fraujulian' into fraujulian 2025-10-10 18:26:30 +02:00
Lechner Julian - FrauJulian 21d8894629 Updated typing export/import; 2025-10-10 18:25:24 +02:00
41 changed files with 14270 additions and 22476 deletions
+9
View File
@@ -0,0 +1,9 @@
*.ts text eol=crlf linguist-language=TypeScript
*.tsx text eol=crlf linguist-language=TypeScript
*.mts text eol=crlf linguist-language=TypeScript
*.cts text eol=crlf linguist-language=TypeScript
*.js text eol=crlf linguist-language=JavaScript
*.jsx text eol=crlf linguist-language=JavaScript
*.mjs text eol=crlf linguist-language=JavaScript
*.cjs text eol=crlf linguist-language=JavaScript
+21
View File
@@ -0,0 +1,21 @@
name: 🐛 Bug
description: Report a bug or unexpected behavior
title: '🐛 [BUG]: '
body:
- type: textarea
id: information
attributes:
label: Description
description: Provide all information.
placeholder: 'What happened? What did you expect to happen?'
validations:
required: false
- type: textarea
id: criteria
attributes:
label: Acceptance Criteria
description: What are the expectations?
placeholder: 'How do you want it implemented? How should it be tested?'
validations:
required: false
+1
View File
@@ -0,0 +1 @@
blank_issues_enabled: false
+21
View File
@@ -0,0 +1,21 @@
name: 💡 Enhancement
description: Suggest a new feature
title: '💡 [Enhancement]: '
body:
- type: textarea
id: information
attributes:
label: Description
description: Provide all information.
placeholder: 'What happened? What did you expect to happen?'
validations:
required: false
- type: textarea
id: criteria
attributes:
label: Acceptance Criteria
description: What are the expectations?
placeholder: 'How do you want it implemented? How should it be tested?'
validations:
required: false
+21
View File
@@ -0,0 +1,21 @@
name: ⚙️ Improvement
description: Suggest an improvement to existing functionality
title: '⚙️ [Improvement]: '
body:
- type: textarea
id: information
attributes:
label: Description
description: Provide all information.
placeholder: 'What happened? What did you expect to happen?'
validations:
required: false
- type: textarea
id: criteria
attributes:
label: Acceptance Criteria
description: What are the expectations?
placeholder: 'How do you want it implemented? How should it be tested?'
validations:
required: false
+102
View File
@@ -0,0 +1,102 @@
name: Release and Deploy Build
on:
workflow_dispatch:
permissions:
contents: write
env:
VERSION_MAJOR: '1'
VERSION_MINOR: '1'
VERSION_PATCH: ${{ gitea.run_number }}
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
with:
fetch-depth: 0
fetch-tags: true
- name: Use NodeJS 24
uses: actions/setup-node@v6
with:
node-version: '24'
registry-url: 'https://registry.npmjs.org'
package-manager-cache: false
- name: Install Dependencies
run: npm ci
- name: Set Release Version
id: version
run: npm run version:place
- name: Export Release Version
id: release_version
run: |
package_version="$(node -p "require('./package.json').version")"
echo "tag=${package_version}" >> "$GITEA_OUTPUT"
- name: Run Build
run: npm run build
- name: Publish Library
run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Create Gitea release
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_API_URL: ${{ gitea.api_url }}
GITEA_REPOSITORY: ${{ gitea.repository }}
GITEA_SERVER_URL: ${{ gitea.server_url }}
GITEA_SHA: ${{ gitea.sha }}
RELEASE_TAG: v${{ steps.release_version.outputs.tag }}
run: |
git fetch --force --tags
releases_url="${GITEA_API_URL}/repos/${GITEA_REPOSITORY}/releases"
previous_tag="$(curl --fail --silent --show-error --header "Authorization: token ${GITEA_TOKEN}" "${releases_url}?limit=50" | jq -r --arg tag "$RELEASE_TAG" '[.[] | select(.draft == false and .tag_name != $tag)][0].tag_name // empty')"
if [ -n "$previous_tag" ]; then
if git rev-parse --verify --quiet "${previous_tag}^{commit}" >/dev/null; then
commit_messages="$(git log --reverse --format='- %s' "${previous_tag}..${GITEA_SHA}")"
else
commit_messages="$(git log --reverse --format='- %s' "${GITEA_SHA}")"
fi
full_changelog="${GITEA_SERVER_URL}/${GITEA_REPOSITORY}/compare/${previous_tag}...${RELEASE_TAG}"
else
commit_messages="$(git log --reverse --format='- %s' "${GITEA_SHA}")"
full_changelog=""
fi
if [ -z "$commit_messages" ]; then
commit_messages='- No commits since the previous release'
fi
{
echo '## Changes'
echo
printf '%s\n' "$commit_messages"
echo
if [ -n "$full_changelog" ]; then
echo "**Full Changelog**: ${full_changelog}"
fi
} > release-notes.md
jq -n --arg tag "$RELEASE_TAG" --arg target "$GITEA_SHA" --rawfile body release-notes.md \
'{tag_name: $tag, target_commitish: $target, name: $tag, body: $body, draft: false, prerelease: false}' > release.json
release_id="$(curl --silent --header "Authorization: token ${GITEA_TOKEN}" "${releases_url}/tags/${RELEASE_TAG}" | jq -r '.id // empty')"
if [ -n "$release_id" ]; then
curl --fail-with-body --request PATCH --header "Authorization: token ${GITEA_TOKEN}" --header 'Content-Type: application/json' --data @release.json "${releases_url}/${release_id}"
else
curl --fail-with-body --request POST --header "Authorization: token ${GITEA_TOKEN}" --header 'Content-Type: application/json' --data @release.json "$releases_url"
fi
+30
View File
@@ -0,0 +1,30 @@
name: Build Validation
on:
workflow_dispatch:
push:
branches:
- main
pull_request:
types: [opened, synchronize, reopened]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: use NodeJS 24
uses: actions/setup-node@v4
with:
node-version: '24'
- name: Install Dependencies
run: npm ci
- name: Run Checks
run: npm run check
- name: Run Build
run: npm run build
-39
View File
@@ -1,39 +0,0 @@
name: Build Rollout
on:
workflow_dispatch:
permissions:
id-token: write
contents: read
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: use NodeJS v22.12.0
uses: actions/setup-node@v4
with:
node-version: '22.12.0'
registry-url: 'https://registry.npmjs.org'
always-auth: true
- name: Create .npmrc
run: echo "//registry.npmjs.org/:_authToken=\${NPM_TOKEN}" > ~/.npmrc
env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
- name: Install Dependencies
run: npm install
- name: run Rollout Build
run: npm run build
- name: Publish Library
run: npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
-23
View File
@@ -1,23 +0,0 @@
name: Build Validation
on:
pull_request:
types: [opened, synchronize, reopened]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: use NodeJS v22.16.0
uses: actions/setup-node@v4
with:
node-version: '22.16.0'
- name: Install Dependencies
run: npm install
- name: run Rollout Build
run: npm run build
+106
View File
@@ -0,0 +1,106 @@
name: Redirect contributions to Gitea
on:
issues:
types: [opened, reopened]
pull_request_target:
types: [opened, reopened]
permissions:
issues: write
pull-requests: write
concurrency:
group: migrate-${{ github.event_name }}-${{ github.event.issue.number || github.event.pull_request.number }}
env:
GITEA_API_URL: https://git.lechner-systems.at/api/v1
GITEA_REPOSITORY: FrauJulian/Discord-Audio-Stream
jobs:
migrate-issue:
if: github.event_name == 'issues'
runs-on: ubuntu-latest
steps:
- name: Migrate issue and close
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: |
set -euo pipefail
number="$(jq -r '.issue.number' "$GITHUB_EVENT_PATH")"
title="$(jq -r '.issue.title' "$GITHUB_EVENT_PATH")"
body="$(jq -r '.issue.body // ""' "$GITHUB_EVENT_PATH")"
author="$(jq -r '.issue.user.login' "$GITHUB_EVENT_PATH")"
source_url="$(jq -r '.issue.html_url' "$GITHUB_EVENT_PATH")"
github_api="${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}"
migrated_url="$(
curl --fail --silent --show-error \
--header "Authorization: Bearer ${GITHUB_TOKEN}" \
--header "Accept: application/vnd.github+json" \
"${github_api}/issues/${number}/comments?per_page=100" |
jq -r '[.[] | select(.user.login == "github-actions[bot]" and (.body | startswith("Migrated to Gitea: ")))] | first | .body // "" | sub("^Migrated to Gitea: "; "")'
)"
if [ -z "$migrated_url" ]; then
migrated_body="${body}
---
Originally opened by @${author} on GitHub: ${source_url}"
jq -n \
--arg title "$title" \
--arg body "$migrated_body" \
'{title: $title, body: $body}' > gitea-request.json
curl --fail-with-body \
--request POST \
--header "Authorization: token ${GITEA_TOKEN}" \
--header "Content-Type: application/json" \
--data @gitea-request.json \
"${GITEA_API_URL}/repos/${GITEA_REPOSITORY}/issues" > gitea-response.json
migrated_url="$(jq -r '.html_url' gitea-response.json)"
jq -n --arg body "Migrated to Gitea: ${migrated_url}" '{body: $body}' > github-comment.json
curl --fail-with-body \
--request POST \
--header "Authorization: Bearer ${GITHUB_TOKEN}" \
--header "Content-Type: application/json" \
--data @github-comment.json \
"${github_api}/issues/${number}/comments"
fi
curl --fail-with-body \
--request PATCH \
--header "Authorization: Bearer ${GITHUB_TOKEN}" \
--header "Content-Type: application/json" \
--data '{"state":"closed","state_reason":"not_planned"}' \
"${github_api}/issues/${number}"
redirect-pull-request:
if: github.event_name == 'pull_request_target'
runs-on: ubuntu-latest
steps:
- name: Redirect pull request and close
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
number="$(jq -r '.pull_request.number' "$GITHUB_EVENT_PATH")"
github_api="${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}"
curl --fail-with-body \
--request POST \
--header "Authorization: Bearer ${GITHUB_TOKEN}" \
--header "Content-Type: application/json" \
--data '{"body":"Please open the Pull Request on Gitea"}' \
"${github_api}/issues/${number}/comments"
curl --fail-with-body \
--request PATCH \
--header "Authorization: Bearer ${GITHUB_TOKEN}" \
--header "Content-Type: application/json" \
--data '{"state":"closed"}' \
"${github_api}/pulls/${number}"
+13 -4
View File
@@ -1,4 +1,13 @@
.idea .idea/
.git .vscode/
node_modules node_modules/
dist dist/
coverage/
.npm/
.eslintcache
*.log
*.tsbuildinfo
.DS_Store
Thumbs.db
+1 -2
View File
@@ -1,3 +1,2 @@
#!/usr/bin/env sh #!/usr/bin/env sh
npm run format || exit 1 npm run check || exit 1
npm run lint:fix || exit 1
+28 -5
View File
@@ -1,10 +1,33 @@
.idea .gitea
.git .git
.github
.idea
.vscode
dist
node_modules
coverage
.npm
.husky
src
set-version.js
README.md
SECURITY.md
CODEOWNERS
.gitignore .gitignore
.npmignore .npmignore
node_modules .prettierignore
src .prettierrc
README.md .gitattributes
tsconfig.json tsconfig.json
tsconfig.eslint.json
tsup.config.ts tsup.config.ts
eslint.config.cjs
eslint.config.typeaware.cjs
package-lock.json
jest.config.cjs
tests
+9
View File
@@ -0,0 +1,9 @@
node_modules/
dist/
coverage/
.git/
.idea/
.vscode/
package-lock.json
+11 -11
View File
@@ -1,13 +1,13 @@
{ {
"printWidth": 140, "printWidth": 120,
"tabWidth": 2, "tabWidth": 4,
"useTabs": false, "useTabs": false,
"singleQuote": true, "singleQuote": true,
"trailingComma": "all", "trailingComma": "all",
"semi": true, "semi": true,
"arrowParens": "always", "arrowParens": "always",
"bracketSpacing": true, "bracketSpacing": true,
"bracketSameLine": false, "bracketSameLine": false,
"quoteProps": "as-needed", "quoteProps": "as-needed",
"endOfLine": "crlf" "endOfLine": "lf"
} }
+577 -420
View File
File diff suppressed because it is too large Load Diff
+187 -90
View File
@@ -1,120 +1,217 @@
# Discord Audio Stream # Discord Audio Stream
[![npm](https://img.shields.io/npm/dw/discord-audio-stream)](http://npmjs.org/package/discord-audio-stream) [![npm](https://img.shields.io/npm/dw/discord-audio-stream)](http://npmjs.org/package/discord-audio-stream)
![GitHub package.json version](https://img.shields.io/github/package-json/v/FrauJulian/discord-audio-stream) ![latest release](https://img.shields.io/gitea/v/release/FrauJulian/Discord-Audio-Stream?gitea_url=https%3A%2F%2Fgit.lechner-systems.at&color=blue)
![GitHub Repo stars](https://img.shields.io/github/stars/FrauJulian/discord-audio-stream?style=social) ![Gitea Repo stars](https://img.shields.io/gitea/stars/FrauJulian/Discord-Audio-Stream?gitea_url=https%3A%2F%2Fgit.lechner-systems.at&style=social)
**This module is designed to work with [discord.js/voice](https://www.npmjs.com/package/@discordjs/voice) v0.18. This `discord-audio-stream` is a small TypeScript library for managed Discord voice playback through
package doesn't support older `@discordjs/voice` and ffmpeg.
versions!**
## 👋 Support It manages the Discord voice connection, ffmpeg process, raw PCM audio resource, optional renewal, and cleanup. Keep one
`AudioManager` per guild, usually in a `Map<string, AudioManager>`, and call `dispose()` when that manager will not be
reused.
Please create an [issue](https://github.com/FrauJulian/DiscordAudioStreamNPM/issues) on github or write [ ## Support
`fraujulian`](https://discord.com/users/860206216893693973) on discord!
## 📝 Usage Create an [issue](https://git.lechner-systems.at/FrauJulian/Discord-Audio-Stream/issues) on Gitea or contact
[`fraujulian`](https://discord.com/users/860206216893693973) on Discord.
### Install ## Installation
> **Supported package managers:** npm, yarn, pnpm, bun Node.js `24.x` is required.
#### Recommended:
```bash ```bash
npm install discord-audio-stream @snazzah/davey @discordjs/opus npm install discord-audio-stream @discordjs/voice @discordjs/opus
yarn add discord-audio-stream @snazzah/davey @discordjs/opus
pnpm add discord-audio-stream @snazzah/davey @discordjs/opus
bun add discord-audio-stream @snazzah/davey @discordjs/opus
``` ```
You need `@snazzah/davey` and one of the encryption libraries to run this package! Use `opusscript@^0.0.8` only as a slower JavaScript fallback when `@discordjs/opus` cannot be installed.
**Encryption Libraries (npm install):** `ffmpeg` must be available either on the host PATH or through the optional `ffmpeg-static` package:
> You only need to install one of these libraries if your system does not support `aes-256-gcm` (verify by running ```bash
> `require('node:crypto').getCiphers().includes('aes-256-gcm')`). npm install ffmpeg-static
- `sodium-native`
- `sodium`
- `@stablelib/xchacha20poly1305`
- `@noble/ciphers`
- `libsodium-wrappers`
**Opus Libraries (npm install):**
- `@discordjs/opus`
- `opusscript`
**FFmpeg:**
- [`FFmpeg`](https://ffmpeg.org/) (installed and added to environment)
- `ffmpeg-static`
### Create Instance
```js
let audioManager = new AudioManager();
``` ```
or (with parameters) Use `ffmpeg.mode: 'native'` for PATH-based ffmpeg and `ffmpeg.mode: 'static'` for `ffmpeg-static`.
```js ## Basic Usage
let audioManager = new AudioManager(
{ ```ts
VoiceChannelId: 0, //voice channel id where to play music import { AudioManager } from 'discord-audio-stream';
GuildId: 0, //guild id
VoiceAdapter: 0, //guild VoiceAdapter const manager = new AudioManager({
}, connection: {
{ guildId: guild.id,
ResourceType: '', //resource type like link or file channelId: voiceChannel.id,
Resource: '', //auto play link or file name adapterCreator: guild.voiceAdapterCreator,
}, },
); source: {
type: 'url',
url: 'https://example.com/live-stream.mp3',
},
ffmpeg: {
mode: 'native',
},
});
await manager.start();
``` ```
### Properties of the AudioManager For a file source:
#### Properties ```ts
manager.setSource({
type: 'file',
path: 'audio/intro.mp3',
});
| Callable with | Type | Description | await manager.start();
| ----------------- | ---------------------------- | ----------------------------------------------- | ```
| `VoiceConnection` | **VoiceConnection** | VoiceConnection instance from discord.js/voice. |
| `AudioPlayer` | **AudioPlayer** | AudioPlayer instance from discord.js/voice. |
| `AudioResource` | **AudioResource** | AudioResource instance from discord.js/voice. |
| `ConnectionData` | **VoiceConnectionDataModel** | Global variable for connection data. |
| `AudioData` | **AudioDataModel** | Global variable for audio data. |
#### Methods Relative file paths are resolved from `process.cwd()`. URL sources are validated before playback starts.
| Callable with | Parameters | Return type | Description | | For large bots, queue many simultaneous starts so the host does not spawn too many ffmpeg processes in the same tick.
| ------------------------------ | ------------------------------------------------------- | ----------- | ------------------------------------------------------------- | -------------------------------------- |
| `OverrideVoiceConnectionData` | `connectionData` (type of **VoiceConnectionDataModel**) | void | Method to override global connectionData variable. | |
| `OverrideVoiceAudioDataModel` | `audioData` (type of **VoiceAudioDataModel**) | void | Method to override global audioData variable. | |
| `OverrideRenewInMs` | `renewInMs` (type of int, default value is 5400000) | void | Method to override global renewInMs variable. | |
| `CreateConnection` | `isRenew` (type of boolean, default value is false) | void | Method to join the voice connection. | |
| `PlayAudioOnConnection` | | void | Method to play audio on the existing voice connection. | |
| `PauseAudio` | | void | Method to pause the audio. | |
| `ResumeAudio` | | void | Method to resume the audio. | |
| `StopAudioOnConnection` | | void | Method to stop the audio without destroying voice connection. | |
| `CreateConnectionAndPlayAudio` | | void | Method to join the voice connection and play audio. | |
| `DestroyConnection` | | void | Method to destroy the voice connection. | |
| `Dispose` | | void | Dispose all data in object. | |
| `SetVolume` | `volume` (type of number, 0 - 100 percent) | void | Method to set the audio volume. | Method to set the volume of the audio. |
| `SetMaxListeners` | `maxListeners` (type of number) | void | Method to set the max listeners of the audio stream. | |
##### Types History ## Lifecycle
- [**VoiceConnection** by discord.js/voice](https://github.com/discordjs/discord.js/blob/main/packages/voice/src/VoiceConnection.ts#L166) ```ts
- [**AudioPlayer** by discord.js/voice](https://github.com/discordjs/discord.js/blob/main/packages/voice/src/audio/AudioPlayer.ts#L155) manager.setConnection(connectionOptions);
- [**AudioResource** by discord.js/voice](https://github.com/discordjs/discord.js/blob/main/packages/voice/src/audio/AudioResource.ts#L44) manager.setSource(source);
- [**VoiceConnectionDataModel** by discord-audio-stream](https://github.com/FrauJulian/Discord-Audio-Stream/blob/main/src/Models/VoiceConnectionDataModel.d.ts#L3)
- [**VoiceAudioDataModel** by discord-audio-stream](https://github.com/FrauJulian/Discord-Audio-Stream/blob/main/src/Models/VoiceAudioDataModel.d.ts#L1)
## 📋 Contributors: await manager.start(); // connect() + play()
manager.pause();
manager.resume();
await manager.stop(); // stops playback and destroys the voice connection
manager.dispose(); // final cleanup; the manager cannot be reused
```
~ [**FrauJulian - Julian Lechner**](https://fraujulian.xyz/). `connect()` joins the configured voice channel. `play(source?)` starts playback on an existing connection. Use `start()`
when you want both.
## 🤝 Enjoy the package? For scoped playback, `AudioManager` supports explicit resource management:
Give it a star ⭐ on [github](https://github.com/FrauJulian/discord-audio-stream)! ```ts
{
using manager = new AudioManager(options);
await manager.start();
} // disposed automatically
```
## API
```ts
type AudioManagerOptions = {
ffmpeg?: {
mode?: 'native' | 'static';
executablePath?: string;
inputArgs?: readonly string[];
outputArgs?: readonly string[];
};
connection?: {
guildId: string;
channelId: string;
adapterCreator: DiscordGatewayAdapterCreator;
};
source?: { type: 'url'; url: string } | { type: 'file'; path: string };
renewIntervalMs?: number | false;
connectTimeoutMs?: number;
onError?: (error: Error) => void;
volume?: {
enabled?: boolean;
initialPercent?: number;
};
};
```
### Defaults
| Option | Default |
| ------------------ | ---------- |
| `ffmpeg.mode` | `'native'` |
| `connectTimeoutMs` | `20_000` |
| `renewIntervalMs` | `false` |
| `volume.enabled` | `false` |
### Methods
| Method | Description |
| ------------------------ | ---------------------------------------------------------------------------------- |
| `setConnection(options)` | Replaces the voice connection target. |
| `setSource(source)` | Replaces the audio source. |
| `connect()` | Joins the configured Discord voice channel. |
| `play(source?)` | Starts playback on an existing connection. |
| `start()` | Connects and starts playback. |
| `pause()` | Pauses active playback. |
| `resume()` | Resumes paused playback. |
| `stop()` | Stops playback, clears renewal, and destroys the voice connection. |
| `setVolume(percent)` | Sets volume from `0` to `100`; requires `volume.enabled: true`. |
| `dispose()` | Idempotently releases timers, ffmpeg, streams, player state, and voice connection. |
| `[Symbol.dispose]()` | Enables automatic cleanup with TypeScript's `using` declaration. |
### State
```ts
manager.state; // 'idle' | 'connecting' | 'ready' | 'playing' | 'paused' | 'stopped' | 'disposed'
manager.isPlaying;
manager.isConnected;
```
## Audio Options
Inline volume has runtime cost in `@discordjs/voice`, so it is disabled by default.
```ts
const manager = new AudioManager({
connection,
source,
volume: {
enabled: true,
initialPercent: 50,
},
});
await manager.start();
manager.setVolume(25);
```
Calling `setVolume()` without `volume.enabled: true` throws `AudioManagerStateError`.
Default ffmpeg output is raw Discord-compatible PCM: `s16le`, `48000 Hz`, `2 channels`.
You can override ffmpeg arguments through `ffmpeg.inputArgs` and `ffmpeg.outputArgs`. When you override them, you are
responsible for keeping the output compatible with `StreamType.Raw`.
Connection renewal is disabled by default because `@discordjs/voice` handles recoverable disconnects. Set
`renewIntervalMs` only when an application has a measured need for periodic restarts. `stop()` and `dispose()` always
clear the renewal timer.
## Errors
The package exports these error classes:
- `AudioManagerError`
- `AudioManagerConfigError`
- `AudioManagerStateError`
- `FfmpegProcessError`
Configuration problems, such as a missing source or invalid URL, throw `AudioManagerConfigError`. Invalid lifecycle
operations, such as calling `pause()` while nothing is playing, throw `AudioManagerStateError`.
Use `onError` to observe asynchronous audio player and voice connection errors. The manager cleans up failed playback
and unrecoverable connections before invoking the callback.
## Development
```bash
npm ci
npm run check
npm run build
```
## Contributors
~ [**FrauJulian - Julian Lechner**](https://fraujulian.xyz/) - CODEOWNER
## Enjoy the package?
Give it a star on [Gitea](https://git.lechner-systems.at/FrauJulian/Discord-Audio-Stream)!
+55
View File
@@ -0,0 +1,55 @@
# Security Policy
## Supported Versions
Security fixes are provided for the latest published release line.
| Version | Supported |
| ----------------------------------------- | --------- |
| Latest release | Yes |
| Older releases | No |
| Unreleased local forks or modified builds | No |
If a vulnerability is fixed, the fix will generally be released only for the current supported version unless a backport is clearly necessary.
## Reporting a Vulnerability
Do not open a public Gitea issue for security vulnerabilities.
Report vulnerabilities privately by email to `fraujulian@lechner.top`.
Please include:
- A clear description of the issue and the expected security impact.
- Affected package version or commit, Node.js version, and runtime environment.
- Reproduction steps, proof of concept, or a minimal example.
- Any relevant logs, stack traces, or dependency details.
- Whether you believe the issue is already publicly known.
## What To Expect
- Initial acknowledgement is targeted within 7 days.
- After triage, you may be asked for more detail or validation.
- If the report is accepted, a fix will be prepared and released as soon as reasonably possible.
- Coordinated disclosure is preferred. Please wait for a fix or explicit approval before publishing details.
- If the report is out of scope or not reproducible, you will be told why.
## Scope
This policy covers vulnerabilities in the published `discord-audio-stream` package itself.
Examples that may be in scope:
- Input handling issues that could cause unsafe process execution behavior.
- Vulnerabilities caused by package logic, lifecycle management, or exposed API behavior.
- Security-relevant documentation mistakes that would realistically lead users into unsafe deployment.
Examples that are usually out of scope:
- Vulnerabilities in third-party dependencies that are not introduced by this package.
- Misconfiguration in a consuming bot, Discord server, host OS, or infrastructure.
- Denial of service caused solely by unsupported environments or intentionally extreme workloads.
## Disclosure
When a report is confirmed, the goal is to publish a fix and then disclose the issue responsibly through the repository release notes, commit history, or an advisory, depending on severity and impact.
-1269
View File
File diff suppressed because it is too large Load Diff
+92 -83
View File
@@ -1,101 +1,110 @@
/** @type {import('eslint').Linter.FlatConfig[]} */ /** @type {import('eslint').Linter.FlatConfig[]} */
const prettierConfig = require('eslint-config-prettier/flat');
const config = [ const config = [
// Globale Ignores (ersetzt .eslintignore) {
{ ignores: ['coverage/', 'dist/', 'node_modules/'],
ignores: ['dist/', 'node_modules/'],
},
// Haupt-Setup für TS/JS-Dateien
{
files: ['**/*.{ts,tsx,js,cjs,mjs}'],
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module', // du schreibst TS mit ES-Imports; Laufzeit ist CJS nach Transpile
parser: require('@typescript-eslint/parser'),
parserOptions: {
// schnelles Profil: kein Type-Checker, nur Syntax-Linting
ecmaFeatures: {},
},
}, },
plugins: { {
'@typescript-eslint': require('@typescript-eslint/eslint-plugin'), files: ['**/*.{ts,tsx,js,cjs,mjs}'],
import: require('eslint-plugin-import'),
promise: require('eslint-plugin-promise'),
'unused-imports': require('eslint-plugin-unused-imports'),
n: require('eslint-plugin-n'),
},
rules: { languageOptions: {
/* Basis */ ecmaVersion: 'latest',
'no-debugger': 'warn', sourceType: 'module',
parser: require('@typescript-eslint/parser'),
/* TypeScript */ parserOptions: {
'@typescript-eslint/consistent-type-imports': ['warn', { prefer: 'type-imports' }], ecmaFeatures: {},
'@typescript-eslint/no-unused-vars': 'off', // schneller über unused-imports },
'unused-imports/no-unused-imports': 'warn',
'unused-imports/no-unused-vars': [
'warn',
{
vars: 'all',
varsIgnorePattern: '^_',
args: 'after-used',
argsIgnorePattern: '^_',
}, },
],
'@typescript-eslint/no-explicit-any': 'off', // pragmatisch für großen Bot
/* Imports */ plugins: {
'import/first': 'error', '@typescript-eslint': require('@typescript-eslint/eslint-plugin'),
'import/no-duplicates': 'error', import: require('eslint-plugin-import'),
'import/newline-after-import': 'warn', promise: require('eslint-plugin-promise'),
'import/no-extraneous-dependencies': [ 'unused-imports': require('eslint-plugin-unused-imports'),
'error', n: require('eslint-plugin-n'),
{
devDependencies: [
'**/*.config.{js,cjs,mjs,ts}',
'**/scripts/**',
'**/*.test.{ts,js}',
'**/Testing.{ts,js}',
'**/.eslintrc.{js,cjs}',
],
}, },
],
/* Node (wir kompilieren TS → CJS; ES-Syntax erlauben) */ rules: {
'n/no-missing-import': 'off', // TypeScript-Resolver übernimmt /* Base */
'n/no-unsupported-features/es-syntax': 'off', 'no-debugger': 'warn',
/* Promises (Discord-/DB-/HTTP-Logik) */ /* TypeScript */
'promise/catch-or-return': 'warn', '@typescript-eslint/consistent-type-imports': ['warn', { prefer: 'type-imports' }],
'promise/always-return': 'off', '@typescript-eslint/no-unused-vars': 'off',
'unused-imports/no-unused-imports': 'warn',
'unused-imports/no-unused-vars': [
'warn',
{ vars: 'all', varsIgnorePattern: '^_', args: 'after-used', argsIgnorePattern: '^_' },
],
'@typescript-eslint/no-explicit-any': 'error',
/* bewusste „Fire-and-forget“-Promises mit `void` */ /* Imports */
'no-void': ['warn', { allowAsStatement: true }], 'import/first': 'error',
}, 'import/no-duplicates': 'error',
'import/newline-after-import': 'warn',
'import/no-extraneous-dependencies': [
'error',
{
devDependencies: [
'**/*.config*.{js,cjs,mjs,ts}',
'**/scripts/**',
'**/*.test.{ts,js}',
'**/Testing.{ts,js}',
'**/.eslintrc.{js,cjs}',
],
},
],
settings: { /* Node */
'import/resolver': { 'n/no-missing-import': 'off',
typescript: { 'n/no-unsupported-features/es-syntax': 'off',
alwaysTryTypes: true,
// nutzt automatisch deine tsconfig-Pfade /* Promis */
'promise/catch-or-return': 'warn',
'promise/always-return': 'off',
/* „Fire-and-forget“-Promises `void` */
'no-void': ['warn', { allowAsStatement: true }],
}, },
node: true,
},
},
},
// Reine JS/CJS-Skripte (Build/Hooks) dürfen require/exporte nutzen settings: {
{ 'import/resolver': {
files: ['**/*.{js,cjs}'], typescript: {
languageOptions: { alwaysTryTypes: true,
sourceType: 'script', },
node: true,
},
},
}, },
rules: {
'n/global-require': 'off', {
files: ['**/*.{ts,tsx}'],
languageOptions: {
parserOptions: {
project: ['./tsconfig.eslint.json'],
tsconfigRootDir: __dirname,
},
},
rules: {
'@typescript-eslint/no-floating-promises': 'error',
'@typescript-eslint/no-misused-promises': ['error', { checksVoidReturn: false }],
'@typescript-eslint/no-unsafe-assignment': 'error',
'@typescript-eslint/no-unsafe-member-access': 'error',
'@typescript-eslint/no-unsafe-argument': 'error',
},
},
{
files: ['**/*.{js,cjs}'],
languageOptions: {
sourceType: 'script',
},
rules: {
'n/global-require': 'off',
},
}, },
},
]; ];
module.exports = config; module.exports = [...config, prettierConfig];
-25
View File
@@ -1,25 +0,0 @@
/** @type {import('eslint').Linter.FlatConfig[]} */
const base = require('./eslint.config.cjs');
const typeAwareLayer = {
files: ['**/*.{ts,tsx}'],
languageOptions: {
parser: require('@typescript-eslint/parser'),
parserOptions: {
project: ['./tsconfig.eslint.json'],
tsconfigRootDir: __dirname,
},
},
plugins: {
'@typescript-eslint': require('@typescript-eslint/eslint-plugin'),
},
rules: {
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-misused-promises': ['warn', { checksVoidReturn: false }],
'@typescript-eslint/no-unsafe-assignment': 'warn',
'@typescript-eslint/no-unsafe-member-access': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
},
};
module.exports = [...base, typeAwareLayer];
+15
View File
@@ -0,0 +1,15 @@
/** @type {import('jest').Config} */
module.exports = {
clearMocks: true,
moduleFileExtensions: ['ts', 'js', 'json'],
testEnvironment: 'node',
testMatch: ['<rootDir>/tests/**/*.test.ts'],
transform: {
'^.+\\.ts$': [
'ts-jest',
{
tsconfig: '<rootDir>/tsconfig.test.json',
},
],
},
};
+10835 -9853
View File
File diff suppressed because it is too large Load Diff
+118 -88
View File
@@ -1,91 +1,121 @@
{ {
"name": "discord-audio-stream", "$schema": "https://json.schemastore.org/package.json",
"version": "0.6.17", "name": "discord-audio-stream",
"license": "LGPL-2.1-only", "version": "x.x.x",
"description": "NodeJS library to make stream any audio on discord easier.", "license": "LGPL-3.0-only",
"exports": { "description": "A small Discord voice audio streaming library with managed ffmpeg playback.",
".": { "exports": {
"require": { ".": {
"types": "./dist/index.d.ts", "require": {
"default": "./dist/index.js" "types": "./dist/index.d.ts",
}, "default": "./dist/index.js"
"import": { },
"types": "./dist/index.d.mts", "import": {
"default": "./dist/index.mjs" "types": "./dist/index.d.mts",
} "default": "./dist/index.mjs"
} }
}, }
"main": "./dist/index.js", },
"module": "./dist/index.mjs", "main": "./dist/index.js",
"types": "./dist/index.d.ts", "module": "./dist/index.mjs",
"files": [ "types": "./dist/index.d.ts",
"dist" "files": [
], "dist"
"directories": {
"lib": "src"
},
"scripts": {
"lint": "eslint . --ext .ts,.tsx,.js,.cjs,.mjs",
"lint:fix": "eslint . --ext .ts,.tsx,.js,.cjs,.mjs --fix",
"lint:types": "eslint . --config eslint.config.typeaware.cjs --ext .ts,.tsx",
"format": "prettier --write .",
"format:check": "prettier --check .",
"update:dependencies": "npx npm-check-updates --upgrade && pnpm install && bun install && npm install && yarn install && echo PLEASE delete your node_modules directory and install again with your package manager.",
"update:version": "npm version patch --no-git-tag-version",
"clean:dist": "del-cli dist",
"build": "npm run clean:dist && npm run update:version && tsup",
"prepare": "husky"
},
"repository": "https://github.com/FrauJulian/Discord-Audio-Stream",
"bugs": "https://github.com/FrauJulian/Discord-Audio-Stream/issues",
"funding": "https://ko-fi.com/FrauJulian",
"keywords": [
"discordjs",
"discord.js",
"discordjs/voice",
"audio",
"voice"
],
"contributors": [
"FrauJulian - Lechner Julian <fraujulian@lechner.top>"
],
"lint-staged": {
"*.{ts,tsx,js,cjs,mjs}": [
"eslint --fix",
"prettier --write"
], ],
"*.{json,md,yml,yaml}": [ "sideEffects": false,
"prettier --write" "scripts": {
] "version:place": "node set-version.js set-ci-version",
}, "version:check": "node set-version.js check-placeholder",
"dependencies": { "version:fix": "node set-version.js fix-placeholder",
"@discordjs/voice": "^0.19.0", "lint": "eslint . --ext .ts,.tsx,.js,.cjs,.mjs",
"@typescript-eslint/eslint-plugin": "^8.46.0", "lint:fix": "eslint . --ext .ts,.tsx,.js,.cjs,.mjs --fix",
"@typescript-eslint/parser": "^8.46.0" "format": "prettier --write .",
}, "format:check": "prettier --check .",
"devDependencies": { "typecheck": "tsc --noEmit --declaration --isolatedDeclarations",
"@types/ejs": "^3.1.5", "test": "jest --runInBand",
"@types/node": "^24.7.1", "check": "npm run version:check && npm run format:check && npm run lint && npm run typecheck && npm run test",
"del-cli": "^7.0.0", "fix": "npm run version:fix && npm run format && npm run lint:fix",
"eslint": "^9.37.0", "build": "tsup",
"eslint-config-prettier": "^10.1.8", "prepare": "husky"
"eslint-import-resolver-typescript": "^4.4.4", },
"eslint-plugin-import": "^2.32.0", "repository": {
"eslint-plugin-n": "^17.23.1", "type": "git",
"eslint-plugin-promise": "^7.2.1", "url": "git+https://git.lechner-systems.at/FrauJulian/Discord-Audio-Stream.git"
"eslint-plugin-unused-imports": "^4.2.0", },
"husky": "^9.1.7", "bugs": "https://git.lechner-systems.at/FrauJulian/Discord-Audio-Stream/issues",
"npm-check-updates": "^19.0.0", "funding": "https://ko-fi.com/FrauJulian",
"prettier": "^3.6.2", "keywords": [
"ts-jest": "^29.4.5", "discord",
"tsup": "^8.5.0", "discord.js",
"typescript": "^5.9.3" "audio",
}, "voice",
"engines": { "streaming",
"node": ">=18" "discordjs/voice",
}, "music",
"private": false, "24/7"
"publishConfig": { ],
"access": "public" "contributors": [
} "Julian Lechner - FrauJulian <fraujulian@lechner.top>"
],
"lint-staged": {
"*.{ts,tsx,js,cjs,mjs}": [
"eslint --fix",
"prettier --write"
],
"*.{json,md,yml,yaml}": [
"prettier --write"
]
},
"devDependencies": {
"@discordjs/opus": "^0.10.0",
"@jest/globals": "^30.4.1",
"@types/ejs": "^3.1.5",
"@types/node": "^24.0.0",
"@typescript-eslint/eslint-plugin": "^8.67.0",
"@typescript-eslint/parser": "^8.67.0",
"eslint": "^9.39.5",
"eslint-config-prettier": "^10.1.8",
"eslint-import-resolver-typescript": "^4.4.5",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-n": "^18.3.0",
"eslint-plugin-promise": "^7.3.0",
"eslint-plugin-unused-imports": "^4.4.1",
"husky": "^9.1.7",
"jest": "^30.4.2",
"prettier": "^3.9.6",
"ts-jest": "^29.4.12",
"tsup": "^8.5.1",
"@typescript/native": "npm:typescript@^7.0.2",
"typescript": "npm:@typescript/typescript6@^6.0.2"
},
"peerDependencies": {
"@discordjs/opus": "^0.10.0",
"@discordjs/voice": "^0.19.2",
"ffmpeg-static": "^5.3.0",
"opusscript": "^0.0.8"
},
"peerDependenciesMeta": {
"@discordjs/opus": {
"optional": true
},
"ffmpeg-static": {
"optional": true
},
"opusscript": {
"optional": true
}
},
"overrides": {
"@discordjs/node-pre-gyp": {
"tar": "^7.5.22"
},
"esbuild": "^0.28.2"
},
"engines": {
"node": "24.x"
},
"private": false,
"publishConfig": {
"access": "public"
}
} }
-5870
View File
File diff suppressed because it is too large Load Diff
-3
View File
@@ -1,3 +0,0 @@
ignoredBuiltDependencies:
- esbuild
- unrs-resolver
+103
View File
@@ -0,0 +1,103 @@
const fs = require('fs');
const lockFilePath = 'package-lock.json';
const packageFilePath = 'package.json';
const placeholderVersion = 'x.x.x';
const command = process.argv[2];
function readJson(path) {
return JSON.parse(fs.readFileSync(path, 'utf8').toString());
}
function writeJson(path, value, spaces) {
fs.writeFileSync(path, `${JSON.stringify(value, null, spaces)}\n`);
}
function getLockFile() {
if (!fs.existsSync(lockFilePath)) {
return null;
}
return readJson(lockFilePath);
}
function writeVersions(version) {
const pkg = readJson(packageFilePath);
pkg.version = version;
writeJson(packageFilePath, pkg, 2);
const lock = getLockFile();
if (lock) {
lock.version = version;
if (lock.packages?.['']) {
lock.packages[''].version = version;
}
writeJson(lockFilePath, lock, 4);
}
}
function checkPlaceholder() {
const pkg = readJson(packageFilePath);
const lock = getLockFile();
const errors = [];
if (pkg.version !== placeholderVersion) {
errors.push(`package.json version must be "${placeholderVersion}", got "${pkg.version}"`);
}
if (lock && lock.version !== placeholderVersion) {
errors.push(`package-lock.json version must be "${placeholderVersion}", got "${lock.version}"`);
}
if (lock?.packages?.[''] && lock.packages[''].version !== placeholderVersion) {
errors.push(
`package-lock.json packages[""] version must be "${placeholderVersion}", got "${lock.packages[''].version}"`,
);
}
if (errors.length > 0) {
for (const error of errors) {
console.error(error);
}
process.exit(1);
}
console.log(`Version placeholder validated: ${placeholderVersion}`);
}
function fixPlaceholder() {
writeVersions(placeholderVersion);
console.log(`Version placeholder set to: ${placeholderVersion}`);
}
function getCiVersion() {
const major = process.env.VERSION_MAJOR;
const minor = process.env.VERSION_MINOR;
const patch = process.env.VERSION_PATCH;
const segments = { major, minor, patch };
for (const [name, value] of Object.entries(segments)) {
if (!/^\d+$/.test(value ?? '')) {
console.error(`Missing or invalid ${name} version segment: "${value ?? ''}"`);
process.exit(1);
}
}
return `${major}.${minor}.${patch}`;
}
if (command === 'check-placeholder') {
checkPlaceholder();
} else if (command === 'fix-placeholder') {
fixPlaceholder();
} else if (command === 'set-ci-version') {
const ciVersion = getCiVersion();
writeVersions(ciVersion);
console.log(`CI version set to: ${ciVersion}`);
} else {
console.error('Invalid command. Use one of: check-placeholder, fix-placeholder, set-ci-version');
process.exit(1);
}
+419 -153
View File
@@ -1,159 +1,425 @@
import type { AudioPlayer, AudioResource, VoiceConnection } from '@discordjs/voice'; import type { AudioPlayer, AudioResource, VoiceConnection } from '@discordjs/voice';
import { createAudioPlayer, createAudioResource, joinVoiceChannel } from '@discordjs/voice'; import {
import { join } from 'node:path'; createAudioPlayer,
import type { VoiceAudioDataModel, VoiceConnectionDataModel } from './index.d'; createAudioResource,
entersState,
joinVoiceChannel,
AudioPlayerStatus,
NoSubscriberBehavior,
StreamType,
VoiceConnectionStatus,
} from '@discordjs/voice';
import { isAbsolute, resolve } from 'node:path';
export default class AudioManager { import { AudioManagerConfigError, AudioManagerStateError } from './errors';
public VoiceConnection?: VoiceConnection; import { startFfmpeg, type FfmpegProcessHandle } from './ffmpeg';
public AudioPlayer?: AudioPlayer; import type {
public AudioResource?: AudioResource; AudioManagerOptions,
AudioSource,
PlaybackState,
ResolvedAudioSource,
VoiceConnectionOptions,
} from './types';
protected IsActive?: boolean; const DEFAULT_CONNECT_TIMEOUT_MS = 20_000;
protected IsAudioPlaying?: boolean; const DISCONNECT_RECOVERY_TIMEOUT_MS = 5_000;
const MAX_TIMER_DELAY_MS = 2_147_483_647;
protected ConnectionData?: VoiceConnectionDataModel; function assertValidTimerDelay(value: number, optionName: string): void {
protected AudioData?: VoiceAudioDataModel; if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TIMER_DELAY_MS) {
throw new AudioManagerConfigError(
private TimeoutHandle?: NodeJS.Timeout; `${optionName} must be an integer between 1 and ${MAX_TIMER_DELAY_MS} milliseconds.`,
private RenewInMs?: number; );
}
constructor(connectionData?: VoiceConnectionDataModel, audioData?: VoiceAudioDataModel, renewInMs = 5400000) { }
this.RenewInMs = renewInMs;
this.ConnectionData = connectionData; function assertValidVolumePercent(value: number): void {
this.AudioData = audioData; if (!Number.isFinite(value) || value < 0 || value > 100) {
} throw new AudioManagerConfigError('Volume must be between 0 and 100 percent.');
}
public OverrideRenewInMs(renewInMs: number = 5400000): void { }
this.RenewInMs = renewInMs;
} export default class AudioManager implements Disposable {
private readonly audioPlayer: AudioPlayer;
public OverrideVoiceConnectionData(connectionData: VoiceConnectionDataModel): void {
this.ConnectionData = connectionData; private connection: VoiceConnection | undefined;
} private resource: AudioResource | undefined;
private ffmpeg: FfmpegProcessHandle | undefined;
public OverrideVoiceAudioDataModel(audioData: VoiceAudioDataModel): void { private connectAttempt: AbortController | undefined;
this.AudioData = audioData; private renewTimer: NodeJS.Timeout | undefined;
} private playbackState: PlaybackState = 'idle';
private connectionOptions: VoiceConnectionOptions | undefined;
public CreateConnection(isRenew: boolean = false): void { private audioSource: AudioSource | undefined;
this.CheckIfNull(this.ConnectionData); private readonly options: Required<Pick<AudioManagerOptions, 'connectTimeoutMs'>> &
Omit<AudioManagerOptions, 'connectTimeoutMs'>;
if (!isRenew) {
if (this.IsActive) { public constructor(options: AudioManagerOptions = {}) {
this.DestroyConnection(false); const connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
} else { assertValidTimerDelay(connectTimeoutMs, 'connectTimeoutMs');
this.IsActive = true;
} if (typeof options.renewIntervalMs === 'number') {
assertValidTimerDelay(options.renewIntervalMs, 'renewIntervalMs');
}
if (options.volume?.initialPercent !== undefined) {
if (options.volume.enabled !== true) {
throw new AudioManagerConfigError('volume.initialPercent requires volume.enabled to be true.');
}
assertValidVolumePercent(options.volume.initialPercent);
}
this.options = {
...options,
connectTimeoutMs,
};
this.connectionOptions = options.connection;
this.audioSource = options.source;
this.audioPlayer = createAudioPlayer({
behaviors: {
noSubscriber: NoSubscriberBehavior.Play,
},
});
this.audioPlayer.on('error', (error) => {
this.finishPlayback(error.resource);
this.reportError(error);
});
this.audioPlayer.on(AudioPlayerStatus.Idle, (oldState) => {
if ('resource' in oldState) {
this.finishPlayback(oldState.resource);
}
});
}
public get state(): PlaybackState {
return this.playbackState;
}
public get isPlaying(): boolean {
return this.playbackState === 'playing';
}
public get isConnected(): boolean {
return this.connection?.state.status === VoiceConnectionStatus.Ready;
}
public setConnection(options: VoiceConnectionOptions): void {
this.assertNotDisposed();
this.connectionOptions = options;
}
public setSource(source: AudioSource): void {
this.assertNotDisposed();
this.audioSource = source;
}
public async connect(): Promise<void> {
this.assertNotDisposed();
if (!this.connectionOptions) {
throw new AudioManagerConfigError('Voice connection options are required before connecting.');
}
this.cancelConnectAttempt();
const attempt = new AbortController();
this.connectAttempt = attempt;
this.clearRenewTimer();
this.playbackState = 'connecting';
const previousConnection = this.connection;
this.connection = undefined;
let connection: VoiceConnection | undefined;
try {
previousConnection?.destroy();
connection = joinVoiceChannel({
guildId: this.connectionOptions.guildId,
channelId: this.connectionOptions.channelId,
adapterCreator: this.connectionOptions.adapterCreator,
});
this.connection = connection;
this.observeConnection(connection);
connection.subscribe(this.audioPlayer);
await entersState(
connection,
VoiceConnectionStatus.Ready,
AbortSignal.any([attempt.signal, AbortSignal.timeout(this.options.connectTimeoutMs)]),
);
} catch (error) {
if (this.connectAttempt !== attempt) {
throw new AudioManagerStateError('Voice connection was stopped before it became ready.', {
cause: error,
});
}
this.connectAttempt = undefined;
if (connection && connection.state.status !== VoiceConnectionStatus.Destroyed) {
connection.destroy();
}
if (this.connection === connection) {
this.connection = undefined;
}
this.playbackState = 'stopped';
throw error;
}
if (this.connectAttempt !== attempt || this.connection !== connection) {
throw new AudioManagerStateError('Voice connection was stopped before it became ready.');
}
this.connectAttempt = undefined;
this.playbackState = 'ready';
this.scheduleRenewal();
}
public async play(source?: AudioSource): Promise<void> {
this.assertNotDisposed();
if (source) {
this.setSource(source);
}
if (!this.isConnected) {
throw new AudioManagerStateError('A voice connection is required before audio can be played.');
}
const resolvedSource = this.resolveSource();
this.stopCurrentPlayback();
this.ffmpeg = startFfmpeg(resolvedSource.input, this.options.ffmpeg);
const ffmpeg = this.ffmpeg;
try {
await ffmpeg.ready;
if (this.ffmpeg !== ffmpeg) {
throw new AudioManagerStateError('Playback was stopped before ffmpeg became ready.');
}
this.resource = createAudioResource(ffmpeg.process.stdout, {
inputType: StreamType.Raw,
inlineVolume: this.options.volume?.enabled === true,
});
} catch (error) {
if (this.ffmpeg !== ffmpeg) {
throw error instanceof AudioManagerStateError
? error
: new AudioManagerStateError('Playback was stopped before ffmpeg became ready.', {
cause: error,
});
}
this.stopCurrentPlayback();
throw error;
}
try {
if (this.options.volume?.enabled === true && this.options.volume.initialPercent !== undefined) {
this.setVolume(this.options.volume.initialPercent);
}
this.audioPlayer.play(this.resource);
this.playbackState = 'playing';
} catch (error) {
this.stopCurrentPlayback();
this.playbackState = 'ready';
throw error;
}
}
public async start(): Promise<void> {
await this.connect();
await this.play();
}
public pause(): void {
this.assertNotDisposed();
if (this.playbackState !== 'playing') {
throw new AudioManagerStateError('Audio can only be paused while it is playing.');
}
this.audioPlayer.pause();
this.playbackState = 'paused';
}
public resume(): void {
this.assertNotDisposed();
if (this.playbackState !== 'paused') {
throw new AudioManagerStateError('Audio can only be resumed while it is paused.');
}
this.audioPlayer.unpause();
this.playbackState = 'playing';
}
public async stop(): Promise<void> {
if (this.playbackState === 'disposed') {
return;
}
this.cancelConnectAttempt();
this.clearRenewTimer();
this.stopCurrentPlayback();
this.audioPlayer.stop(true);
this.connection?.disconnect();
this.connection?.destroy();
this.connection = undefined;
this.playbackState = 'stopped';
}
public setVolume(volumeInPercent: number): void {
this.assertNotDisposed();
if (this.options.volume?.enabled !== true) {
throw new AudioManagerStateError('Volume control requires volume.enabled to be true.');
}
assertValidVolumePercent(volumeInPercent);
if (!this.resource?.volume) {
throw new AudioManagerStateError('No audio resource with volume control is currently active.');
}
this.resource.volume.setVolume(volumeInPercent / 100);
}
public dispose(): void {
if (this.playbackState === 'disposed') {
return;
}
this.cancelConnectAttempt();
this.clearRenewTimer();
this.stopCurrentPlayback();
this.audioPlayer.stop(true);
this.connection?.destroy();
this.connection = undefined;
this.connectionOptions = undefined;
this.audioSource = undefined;
this.playbackState = 'disposed';
}
public [Symbol.dispose](): void {
this.dispose();
}
private resolveSource(): ResolvedAudioSource {
if (!this.audioSource) {
throw new AudioManagerConfigError('Audio source is required before playback can start.');
}
if (this.audioSource.type === 'url') {
try {
return {
input: new URL(this.audioSource.url).toString(),
source: this.audioSource,
};
} catch (error) {
throw new AudioManagerConfigError('Invalid audio source URL.', { cause: error });
}
}
return {
input: isAbsolute(this.audioSource.path)
? this.audioSource.path
: resolve(process.cwd(), this.audioSource.path),
source: this.audioSource,
};
}
private scheduleRenewal(): void {
const renewIntervalMs = this.options.renewIntervalMs;
if (renewIntervalMs === undefined || renewIntervalMs === false) {
return;
}
this.renewTimer = setTimeout(() => {
void this.start().catch((error: unknown) => {
if (this.playbackState === 'disposed') {
return;
}
this.clearRenewTimer();
this.stopCurrentPlayback();
this.audioPlayer.stop(true);
this.connection?.disconnect();
this.connection?.destroy();
this.connection = undefined;
this.playbackState = 'stopped';
this.reportError(error);
});
}, renewIntervalMs);
if (typeof this.renewTimer.unref === 'function') {
this.renewTimer.unref();
}
}
private observeConnection(connection: VoiceConnection): void {
connection.on('error', (error) => {
this.reportError(error);
});
connection.on(VoiceConnectionStatus.Disconnected, () => this.handleDisconnectedConnection(connection));
}
private async handleDisconnectedConnection(connection: VoiceConnection): Promise<void> {
try {
await Promise.race([
entersState(connection, VoiceConnectionStatus.Signalling, DISCONNECT_RECOVERY_TIMEOUT_MS),
entersState(connection, VoiceConnectionStatus.Connecting, DISCONNECT_RECOVERY_TIMEOUT_MS),
]);
} catch (error) {
if (this.connection !== connection) {
return;
}
this.clearRenewTimer();
this.stopCurrentPlayback();
this.audioPlayer.stop(true);
this.connection = undefined;
if (connection.state.status !== VoiceConnectionStatus.Destroyed) {
connection.destroy();
}
this.playbackState = 'stopped';
this.reportError(error);
}
}
private finishPlayback(resource: AudioResource): void {
if (this.resource !== resource) {
return;
}
this.stopCurrentPlayback();
if (this.playbackState !== 'disposed') {
this.playbackState = this.isConnected ? 'ready' : 'stopped';
}
}
private reportError(error: unknown): void {
this.options.onError?.(error instanceof Error ? error : new Error(String(error)));
}
private clearRenewTimer(): void {
if (this.renewTimer) {
clearTimeout(this.renewTimer);
this.renewTimer = undefined;
}
}
private cancelConnectAttempt(): void {
this.connectAttempt?.abort();
this.connectAttempt = undefined;
}
private stopCurrentPlayback(): void {
this.resource?.playStream.destroy();
this.resource = undefined;
this.ffmpeg?.stop();
this.ffmpeg = undefined;
}
private assertNotDisposed(): void {
if (this.playbackState === 'disposed') {
throw new AudioManagerStateError('AudioManager has been disposed.');
}
} }
this.VoiceConnection = joinVoiceChannel({
channelId: this.ConnectionData!.VoiceChannelId.toString(),
guildId: this.ConnectionData!.GuildId.toString(),
adapterCreator: this.ConnectionData!.VoiceAdapter,
});
this.TimeoutHandle = setTimeout((): void => {
this.DestroyConnection(false);
if (this.IsActive) {
this.CreateConnection(true);
if (this.IsAudioPlaying) {
this.PlayAudioOnConnection();
}
}
}, this.RenewInMs);
}
public PlayAudioOnConnection(): void {
this.CheckIfNull(this.AudioData);
if (this.AudioData!.ResourceType === 'File') {
this.AudioResource = createAudioResource(join(__dirname, this.AudioData!.Resource), { inlineVolume: true });
} else if (this.AudioData!.ResourceType === 'Link') {
this.AudioResource = createAudioResource(this.AudioData!.Resource, { inlineVolume: true });
} else {
throw new Error('Invalid resource type.');
}
this.AudioPlayer = createAudioPlayer();
this.AudioPlayer.play(this.AudioResource);
this.VoiceConnection!.subscribe(this.AudioPlayer!);
this.IsAudioPlaying = true;
}
public StopAudioOnConnection(): void {
if (this.IsAudioPlaying) {
this.DestroyConnection(false);
this.CreateConnection();
} else {
throw new Error('Audio is not playing.');
}
}
public PauseAudio(): void {
if (this.IsAudioPlaying) {
this.AudioPlayer!.pause();
this.IsAudioPlaying = false;
} else {
throw new TypeError('Audio is not playing.');
}
}
public ResumeAudio(): void {
if (!this.IsAudioPlaying) {
this.AudioPlayer!.unpause();
this.IsAudioPlaying = true;
} else {
throw new TypeError('Audio is playing.');
}
}
public CreateConnectionAndPlayAudio(): void {
this.CreateConnection();
this.PlayAudioOnConnection();
}
public DestroyConnection(resetValidationParameters: boolean = true): void {
if (this.CheckIfNull(this.VoiceConnection)) return;
this.VoiceConnection!.destroy();
if (resetValidationParameters) {
this.IsActive = false;
this.IsAudioPlaying = false;
}
}
public SetMaxListeners(maxListeners: number): void {
if (this.CheckIfNull(this.VoiceConnection)) return;
this.VoiceConnection!.setMaxListeners(maxListeners);
}
public SetVolume(volumeInPercent: number): void {
if (volumeInPercent < 0 || volumeInPercent > 100) throw new Error('Volume must be between 0 and 100.');
if (this.CheckIfNull(this.VoiceConnection)) return;
this.AudioResource!.volume!.setVolume(volumeInPercent / 100);
}
public Dispose(): void {
this.VoiceConnection = undefined;
this.AudioPlayer = undefined;
this.AudioResource = undefined;
this.IsActive = undefined;
this.IsAudioPlaying = undefined;
this.ConnectionData = undefined;
this.AudioData = undefined;
this.TimeoutHandle = undefined;
this.RenewInMs = undefined;
}
private CheckIfNull<T>(value: T | null): boolean {
if (value === null) {
throw new Error(`${value} cannot be null in this case.`);
}
return true;
}
} }
+16
View File
@@ -0,0 +1,16 @@
export class AudioManagerError extends Error {
public constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = new.target.name;
}
}
export class AudioManagerConfigError extends AudioManagerError {}
export class AudioManagerStateError extends AudioManagerError {}
export class FfmpegProcessError extends AudioManagerError {
public constructor(message: string, cause?: unknown) {
super(message, cause === undefined ? undefined : { cause });
}
}
+169
View File
@@ -0,0 +1,169 @@
import { spawn } from 'node:child_process';
import type { ChildProcessByStdio } from 'node:child_process';
import { createRequire } from 'node:module';
import type { Readable } from 'node:stream';
import { AudioManagerConfigError, FfmpegProcessError } from './errors';
import type { FfmpegOptions } from './types';
const requireFromCurrentModule = createRequire(__filename);
const DEFAULT_INPUT_ARGS = ['-hide_banner', '-loglevel', 'error', '-nostdin'] as const;
const DEFAULT_OUTPUT_ARGS = ['-vn', '-f', 's16le', '-ar', '48000', '-ac', '2', 'pipe:1'] as const;
const FORCE_KILL_TIMEOUT_MS = 2_000;
const STDERR_TAIL_BYTES = 4_096;
export type FfmpegProcessHandle = {
readonly process: ChildProcessByStdio<null, Readable, Readable>;
readonly ready: Promise<void>;
stop(): void;
};
export function resolveFfmpegExecutable(options: FfmpegOptions = {}): string {
if (options.executablePath?.trim()) {
return options.executablePath;
}
if ((options.mode ?? 'native') === 'native') {
return 'ffmpeg';
}
try {
const executable = requireFromCurrentModule('ffmpeg-static') as unknown;
if (typeof executable === 'string' && executable.length > 0) {
return executable;
}
} catch (error) {
throw new AudioManagerConfigError(
'Unable to resolve ffmpeg-static. Install it or pass ffmpeg.executablePath.',
{ cause: error },
);
}
throw new AudioManagerConfigError('ffmpeg-static did not expose an executable path.');
}
export function startFfmpeg(input: string, options: FfmpegOptions = {}): FfmpegProcessHandle {
const executable = resolveFfmpegExecutable(options);
const args = [
...(options.inputArgs ?? DEFAULT_INPUT_ARGS),
'-i',
input,
...(options.outputArgs ?? DEFAULT_OUTPUT_ARGS),
];
const childProcess = spawn(executable, args, { stdio: ['ignore', 'pipe', 'pipe'] });
const abortController = new AbortController();
const ready = waitForFfmpegOutput(childProcess, abortController.signal);
childProcess.stderr.resume();
return {
process: childProcess,
ready,
stop: (): void => {
stopProcess(childProcess, abortController);
},
};
}
function waitForFfmpegOutput(
childProcess: ChildProcessByStdio<null, Readable, Readable>,
signal: AbortSignal,
): Promise<void> {
const { promise, resolve, reject } = Promise.withResolvers<void>();
let stderrTail = '';
let settled = false;
const appendStderr = (chunk: Buffer | string): void => {
stderrTail = (stderrTail + String(chunk)).slice(-STDERR_TAIL_BYTES);
};
const cleanup = (): void => {
childProcess.off('exit', onExit);
childProcess.stdout.off('readable', onReadable);
childProcess.stderr.off('data', appendStderr);
signal.removeEventListener('abort', onAbort);
};
const settle = (complete: () => void): void => {
if (settled) {
return;
}
settled = true;
cleanup();
complete();
};
const fail = (message: string, cause?: unknown): void => {
settle(() => reject(new FfmpegProcessError(addStderrTail(message, stderrTail), cause)));
};
const onError = (error: Error): void => {
if (!settled) {
fail(`Unable to start ffmpeg. Cause: ${error.message}`, error);
}
};
const onExit = (code: number | null, exitSignal: NodeJS.Signals | null): void => {
fail(`ffmpeg exited before producing audio. Exit code: ${code ?? 'none'}, signal: ${exitSignal ?? 'none'}.`);
};
const onReadable = (): void => {
settle(() => resolve());
};
const onAbort = (): void => {
const reason: unknown = signal.reason;
settle(() =>
reject(
reason instanceof Error
? reason
: new FfmpegProcessError('ffmpeg was stopped before producing audio.', reason),
),
);
};
childProcess.stderr.on('data', appendStderr);
childProcess.on('error', onError);
childProcess.once('exit', onExit);
childProcess.stdout.once('readable', onReadable);
signal.addEventListener('abort', onAbort, { once: true });
return promise;
}
function addStderrTail(message: string, stderrTail: string): string {
const trimmedTail = stderrTail.trim();
return trimmedTail ? `${message} stderr: ${trimmedTail}` : message;
}
function stopProcess(
childProcess: ChildProcessByStdio<null, Readable, Readable>,
abortController: AbortController,
): void {
if (abortController.signal.aborted) {
return;
}
abortController.abort(new FfmpegProcessError('ffmpeg was stopped before producing audio.'));
childProcess.stdout.destroy();
childProcess.stderr.destroy();
if (childProcess.exitCode !== null || childProcess.signalCode !== null) {
return;
}
childProcess.kill('SIGTERM');
const forceKillTimeout = setTimeout(() => {
if (childProcess.exitCode === null && childProcess.signalCode === null) {
childProcess.kill('SIGKILL');
}
}, FORCE_KILL_TIMEOUT_MS);
childProcess.once('close', () => clearTimeout(forceKillTimeout));
forceKillTimeout.unref();
}
-32
View File
@@ -1,32 +0,0 @@
import type { DiscordGatewayAdapterCreator } from '@discordjs/voice';
export type VoiceConnectionDataModel = {
/**
* The ID of the voice channel to connect to.
*/
VoiceChannelId: string;
/**
* The Id of the guild (server) to connect to.
*/
GuildId: string;
/**
* The adapter creator for the voice connection.
* Can be archived by the guild instance via the voiceAdapterCreator property.
*/
VoiceAdapter: DiscordGatewayAdapterCreator;
};
export type VoiceAudioDataModel = {
/**
* The unique identifier for the audio resource.
*/
ResourceType: 'Link' | 'File';
/**
* The URL or file path of the audio resource.
* any is to be assumed to require(filepath)
*/
Resource: string | any;
};
+10
View File
@@ -1 +1,11 @@
export { default as AudioManager } from './audio-manager'; export { default as AudioManager } from './audio-manager';
export { AudioManagerConfigError, AudioManagerError, AudioManagerStateError, FfmpegProcessError } from './errors';
export type {
AudioManagerOptions,
AudioSource,
FfmpegMode,
FfmpegOptions,
PlaybackState,
VoiceConnectionOptions,
VolumeOptions,
} from './types';
+183
View File
@@ -0,0 +1,183 @@
import type { DiscordGatewayAdapterCreator } from '@discordjs/voice';
/**
* Strategy used to resolve the ffmpeg executable.
*
* - `native` uses the `ffmpeg` binary available on the host PATH.
* - `static` resolves the optional `ffmpeg-static` package.
*/
export type FfmpegMode = 'native' | 'static';
/**
* Audio input consumed by ffmpeg.
*
* URL sources are validated through the built-in `URL` constructor before playback starts.
* File sources may be absolute or relative; relative paths are resolved from `process.cwd()`.
*/
export type AudioSource =
| {
/**
* Marks this source as a remote URL.
*/
type: 'url';
/**
* Fully qualified audio URL passed to ffmpeg.
*/
url: string;
}
| {
/**
* Marks this source as a local file path.
*/
type: 'file';
/**
* Absolute file path or path relative to `process.cwd()`.
*/
path: string;
};
/**
* Discord voice channel connection settings.
*/
export type VoiceConnectionOptions = {
/**
* Discord guild/server ID.
*/
guildId: string;
/**
* Discord voice channel ID where audio should be played.
*/
channelId: string;
/**
* Discord voice adapter creator, usually `guild.voiceAdapterCreator` from discord.js.
*/
adapterCreator: DiscordGatewayAdapterCreator;
};
/**
* Public playback lifecycle state exposed by `AudioManager.state`.
*/
export type PlaybackState = 'idle' | 'connecting' | 'ready' | 'playing' | 'paused' | 'stopped' | 'disposed';
/**
* ffmpeg executable and argument configuration.
*/
export type FfmpegOptions = {
/**
* ffmpeg resolution mode.
*
* @defaultValue `'native'`
*/
mode?: FfmpegMode;
/**
* Explicit ffmpeg executable path.
*
* When provided, this value takes precedence over `mode`.
*/
executablePath?: string;
/**
* Arguments placed before `-i <source>`.
*
* Override only when you need full control over ffmpeg input behavior.
*/
inputArgs?: readonly string[];
/**
* Arguments placed after `-i <source>`.
*
* If overridden, the output must remain compatible with `StreamType.Raw`.
*/
outputArgs?: readonly string[];
};
/**
* Optional inline volume control settings.
*/
export type VolumeOptions = {
/**
* Enables Discord voice inline volume support.
*
* Disabled by default because inline volume has runtime overhead.
*
* @defaultValue `false`
*/
enabled?: boolean;
/**
* Initial volume percentage applied when playback starts.
*
* Requires `enabled: true`.
*/
initialPercent?: number;
};
/**
* Constructor options for `AudioManager`.
*/
export type AudioManagerOptions = {
/**
* ffmpeg executable and argument configuration.
*/
ffmpeg?: FfmpegOptions;
/**
* Initial Discord voice connection settings.
*
* May also be supplied later through `setConnection()`.
*/
connection?: VoiceConnectionOptions;
/**
* Initial audio source.
*
* May also be supplied later through `setSource()` or `play(source)`.
*/
source?: AudioSource;
/**
* Milliseconds after which the manager reconnects and restarts playback.
*
* Renewal is disabled unless an interval is provided.
*
* @defaultValue `false`
*/
renewIntervalMs?: number | false;
/**
* Maximum milliseconds to wait for the Discord voice connection to become ready.
*
* @defaultValue `20_000`
*/
connectTimeoutMs?: number;
/**
* Receives asynchronous audio player and voice connection errors.
*/
onError?: (error: Error) => void;
/**
* Optional inline volume configuration.
*/
volume?: VolumeOptions;
};
/**
* Internal normalized audio source passed to ffmpeg.
*/
export type ResolvedAudioSource = {
/**
* Validated URL or absolute file path passed as ffmpeg input.
*/
input: string;
/**
* Original source configuration.
*/
source: AudioSource;
};
+826
View File
@@ -0,0 +1,826 @@
import { jest, describe, beforeEach, afterEach, it, expect } from '@jest/globals';
import {
AudioPlayerStatus,
createAudioPlayer,
createAudioResource,
entersState,
joinVoiceChannel,
VoiceConnectionStatus,
} from '@discordjs/voice';
import { resolve } from 'node:path';
import { PassThrough } from 'node:stream';
import AudioManager from '../src/audio-manager';
import { AudioManagerConfigError, AudioManagerStateError, FfmpegProcessError } from '../src';
import { startFfmpeg } from '../src/ffmpeg';
import type { FfmpegProcessHandle } from '../src/ffmpeg';
import type { AudioSource, VoiceConnectionOptions } from '../src';
import type { VoiceConnection } from '@discordjs/voice';
type MockListener = (...args: unknown[]) => unknown;
const audioPlayerListeners = new Map<string, MockListener>();
const connectionListeners = new Map<string, MockListener>();
const secondConnectionListeners = new Map<string, MockListener>();
const mockAudioPlayer = {
on: jest.fn((event: string, listener: MockListener) => {
audioPlayerListeners.set(event, listener);
return mockAudioPlayer;
}),
play: jest.fn(),
pause: jest.fn(),
unpause: jest.fn(),
stop: jest.fn(),
};
const mockConnection = {
state: { status: 'ready' },
on: jest.fn((event: string, listener: MockListener) => {
connectionListeners.set(event, listener);
return mockConnection;
}),
subscribe: jest.fn(),
disconnect: jest.fn(),
destroy: jest.fn(),
};
const mockSecondConnection = {
state: { status: 'ready' },
on: jest.fn((event: string, listener: MockListener) => {
secondConnectionListeners.set(event, listener);
return mockSecondConnection;
}),
subscribe: jest.fn(),
disconnect: jest.fn(),
destroy: jest.fn(),
};
const mockVoiceConnection = mockConnection as unknown as VoiceConnection;
const mockSecondVoiceConnection = mockSecondConnection as unknown as VoiceConnection;
const mockAudioResource = {
playStream: {
destroy: jest.fn(),
},
volume: {
setVolume: jest.fn(),
},
};
const mockFfmpegHandle: FfmpegProcessHandle = {
process: {
stdout: new PassThrough(),
} as unknown as FfmpegProcessHandle['process'],
ready: Promise.resolve(),
stop: jest.fn(),
};
jest.mock('@discordjs/voice', () => ({
AudioPlayerStatus: {
Idle: 'idle',
},
NoSubscriberBehavior: {
Play: 'play',
},
StreamType: {
Raw: 'raw',
},
VoiceConnectionStatus: {
Connecting: 'connecting',
Destroyed: 'destroyed',
Disconnected: 'disconnected',
Ready: 'ready',
Signalling: 'signalling',
},
createAudioPlayer: jest.fn(() => mockAudioPlayer),
createAudioResource: jest.fn(() => mockAudioResource),
entersState: jest.fn(() => Promise.resolve(mockVoiceConnection)),
joinVoiceChannel: jest.fn(() => mockVoiceConnection),
}));
jest.mock('../src/ffmpeg', () => ({
startFfmpeg: jest.fn(() => mockFfmpegHandle),
}));
const connectionOptions: VoiceConnectionOptions = {
guildId: 'guild-id',
channelId: 'channel-id',
adapterCreator: jest.fn() as unknown as VoiceConnectionOptions['adapterCreator'],
};
const liveStreamSource: AudioSource = {
type: 'url',
url: 'https://synradiode.stream.laut.fm/synradiode',
};
const fileSourcePath = 'tests/audio.mp3';
const resolvedFileSourcePath = resolve(process.cwd(), fileSourcePath);
type MockedEntersStateReturn = ReturnType<typeof entersState>;
function createMockFfmpegHandle(): FfmpegProcessHandle {
return {
process: {
stdout: new PassThrough(),
} as unknown as FfmpegProcessHandle['process'],
ready: Promise.resolve(),
stop: jest.fn(),
};
}
function listenerFor(listeners: Map<string, MockListener>, event: string): MockListener {
const listener = listeners.get(event);
if (!listener) {
throw new Error(`No listener registered for ${event}.`);
}
return listener;
}
describe('AudioManager', () => {
beforeEach(() => {
jest.clearAllMocks();
audioPlayerListeners.clear();
connectionListeners.clear();
secondConnectionListeners.clear();
mockConnection.state.status = VoiceConnectionStatus.Ready;
mockSecondConnection.state.status = VoiceConnectionStatus.Ready;
});
afterEach(() => {
jest.useRealTimers();
});
it('requires connection options before connecting', async () => {
const manager = new AudioManager({ renewIntervalMs: false });
await expect(manager.connect()).rejects.toThrow(AudioManagerConfigError);
});
it('connects and starts playback with resolved URL source', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
await manager.start();
expect(manager.state).toBe('playing');
expect(manager.isConnected).toBe(true);
expect(manager.isPlaying).toBe(true);
expect(mockConnection.subscribe).toHaveBeenCalledWith(mockAudioPlayer);
expect(startFfmpeg).toHaveBeenCalledWith('https://synradiode.stream.laut.fm/synradiode', undefined);
expect(mockAudioPlayer.play).toHaveBeenCalledWith(mockAudioResource);
});
it('does not schedule connection renewal by default', async () => {
jest.useFakeTimers();
const manager = new AudioManager({ connection: connectionOptions });
await manager.connect();
expect(jest.getTimerCount()).toBe(0);
manager.dispose();
});
it('reports voice connection errors without interrupting playback', async () => {
const connectionError = new Error('voice connection failed');
const onError = jest.fn();
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
onError,
});
await manager.start();
listenerFor(connectionListeners, 'error')(connectionError);
expect(onError).toHaveBeenCalledWith(connectionError);
expect(manager.state).toBe('playing');
});
it('keeps playback while a disconnected voice connection recovers', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
await manager.start();
await listenerFor(connectionListeners, VoiceConnectionStatus.Disconnected)();
expect(entersState).toHaveBeenCalledWith(mockVoiceConnection, VoiceConnectionStatus.Signalling, 5_000);
expect(entersState).toHaveBeenCalledWith(mockVoiceConnection, VoiceConnectionStatus.Connecting, 5_000);
expect(mockConnection.destroy).not.toHaveBeenCalled();
expect(manager.state).toBe('playing');
});
it('stops playback after an unrecoverable voice disconnect', async () => {
const disconnectError = new Error('voice connection did not recover');
const onError = jest.fn();
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
onError,
});
await manager.start();
jest.mocked(entersState).mockRejectedValueOnce(disconnectError).mockRejectedValueOnce(disconnectError);
mockConnection.state.status = VoiceConnectionStatus.Disconnected;
await listenerFor(connectionListeners, VoiceConnectionStatus.Disconnected)();
expect(mockFfmpegHandle.stop).toHaveBeenCalledTimes(1);
expect(mockAudioPlayer.stop).toHaveBeenCalledWith(true);
expect(mockConnection.destroy).toHaveBeenCalledTimes(1);
expect(onError).toHaveBeenCalledWith(disconnectError);
expect(manager.state).toBe('stopped');
expect(manager.isConnected).toBe(false);
});
it('cleans up when connection startup fails', async () => {
jest.useFakeTimers();
const manager = new AudioManager({
connection: connectionOptions,
renewIntervalMs: 10_000,
});
jest.mocked(entersState).mockRejectedValueOnce(new Error('voice connection timeout'));
await expect(manager.connect()).rejects.toThrow('voice connection timeout');
expect(manager.state).toBe('stopped');
expect(manager.isConnected).toBe(false);
expect(mockConnection.subscribe).toHaveBeenCalledWith(mockAudioPlayer);
expect(mockConnection.destroy).toHaveBeenCalledTimes(1);
expect(jest.getTimerCount()).toBe(0);
});
it('restores the stopped state when voice setup throws synchronously', async () => {
const connectionError = new Error('voice setup failed');
jest.mocked(joinVoiceChannel).mockImplementationOnce(() => {
throw connectionError;
});
const manager = new AudioManager({ connection: connectionOptions, renewIntervalMs: false });
await expect(manager.connect()).rejects.toBe(connectionError);
expect(manager.state).toBe('stopped');
expect(manager.isConnected).toBe(false);
});
it('does not become ready when stopped during connection startup', async () => {
jest.useFakeTimers();
const ready = Promise.withResolvers<VoiceConnection>();
jest.mocked(entersState).mockReturnValueOnce(ready.promise as unknown as MockedEntersStateReturn);
const manager = new AudioManager({
connection: connectionOptions,
renewIntervalMs: 10_000,
});
const connectPromise = manager.connect();
await manager.stop();
ready.resolve(mockVoiceConnection);
await expect(connectPromise).rejects.toThrow(AudioManagerStateError);
expect(manager.state).toBe('stopped');
expect(manager.isConnected).toBe(false);
expect(jest.getTimerCount()).toBe(0);
});
it('keeps the latest connection when a stale connection attempt rejects', async () => {
const firstReady = Promise.withResolvers<VoiceConnection>();
const secondReady = Promise.withResolvers<VoiceConnection>();
jest.mocked(joinVoiceChannel)
.mockReturnValueOnce(mockVoiceConnection)
.mockReturnValueOnce(mockSecondVoiceConnection);
jest.mocked(entersState)
.mockReturnValueOnce(firstReady.promise as unknown as MockedEntersStateReturn)
.mockReturnValueOnce(secondReady.promise as unknown as MockedEntersStateReturn);
const manager = new AudioManager({
connection: connectionOptions,
renewIntervalMs: false,
});
const firstConnect = manager.connect();
const secondConnect = manager.connect();
firstReady.reject(new Error('stale connection failed'));
secondReady.resolve(mockSecondVoiceConnection);
await expect(firstConnect).rejects.toThrow(AudioManagerStateError);
await expect(secondConnect).resolves.toBeUndefined();
expect(manager.state).toBe('ready');
expect(manager.isConnected).toBe(true);
expect(mockConnection.destroy).toHaveBeenCalledTimes(1);
expect(mockSecondConnection.destroy).not.toHaveBeenCalled();
});
it('does not become ready when disposed during connection startup', async () => {
const ready = Promise.withResolvers<VoiceConnection>();
jest.mocked(entersState).mockReturnValueOnce(ready.promise as unknown as MockedEntersStateReturn);
const manager = new AudioManager({
connection: connectionOptions,
renewIntervalMs: false,
});
const connectPromise = manager.connect();
manager.dispose();
ready.reject(new Error('disposed connection failed'));
await expect(connectPromise).rejects.toThrow(AudioManagerStateError);
expect(manager.state).toBe('disposed');
expect(manager.isConnected).toBe(false);
expect(mockConnection.destroy).toHaveBeenCalledTimes(1);
});
it('starts playback with the committed mp3 test file', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: {
type: 'file',
path: fileSourcePath,
},
renewIntervalMs: false,
});
await manager.start();
expect(startFfmpeg).toHaveBeenCalledWith(resolvedFileSourcePath, undefined);
expect(mockAudioPlayer.play).toHaveBeenCalledWith(mockAudioResource);
});
it('accepts the live stream URL as a valid source', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
await manager.connect();
await manager.play();
expect(startFfmpeg).toHaveBeenCalledWith('https://synradiode.stream.laut.fm/synradiode', undefined);
});
it('plays a source passed directly to play()', async () => {
const manager = new AudioManager({
connection: connectionOptions,
renewIntervalMs: false,
});
await manager.connect();
await manager.play({
type: 'file',
path: fileSourcePath,
});
expect(startFfmpeg).toHaveBeenCalledWith(resolvedFileSourcePath, undefined);
expect(manager.state).toBe('playing');
});
it('does not report playback when ffmpeg startup fails', async () => {
const startupError = new FfmpegProcessError('Unable to start ffmpeg.');
jest.mocked(startFfmpeg).mockReturnValueOnce({
...mockFfmpegHandle,
ready: Promise.reject(startupError),
});
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
await manager.connect();
await expect(manager.play()).rejects.toBe(startupError);
expect(manager.state).toBe('ready');
expect(mockAudioPlayer.play).not.toHaveBeenCalled();
expect(mockFfmpegHandle.stop).toHaveBeenCalledTimes(1);
});
it('cleans up when audio resource creation fails', async () => {
const resourceError = new Error('resource failed');
jest.mocked(createAudioResource).mockImplementationOnce(() => {
throw resourceError;
});
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
await manager.connect();
await expect(manager.play()).rejects.toBe(resourceError);
expect(manager.state).toBe('ready');
expect(mockFfmpegHandle.stop).toHaveBeenCalledTimes(1);
expect(mockAudioPlayer.play).not.toHaveBeenCalled();
});
it('cleans up when the audio player rejects playback', async () => {
const playerError = new Error('player failed');
mockAudioPlayer.play.mockImplementationOnce(() => {
throw playerError;
});
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
await manager.connect();
await expect(manager.play()).rejects.toBe(playerError);
expect(manager.state).toBe('ready');
expect(mockFfmpegHandle.stop).toHaveBeenCalledTimes(1);
expect(mockAudioResource.playStream.destroy).toHaveBeenCalledTimes(1);
});
it('cleans up and reports asynchronous audio player errors', async () => {
const playerError = Object.assign(new Error('audio stream failed'), { resource: mockAudioResource });
const onError = jest.fn();
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
onError,
});
await manager.start();
listenerFor(audioPlayerListeners, 'error')(playerError);
expect(mockFfmpegHandle.stop).toHaveBeenCalledTimes(1);
expect(mockAudioResource.playStream.destroy).toHaveBeenCalledTimes(1);
expect(onError).toHaveBeenCalledWith(playerError);
expect(manager.state).toBe('ready');
expect(manager.isPlaying).toBe(false);
});
it('returns to ready when the current audio resource becomes idle', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
await manager.start();
listenerFor(audioPlayerListeners, AudioPlayerStatus.Idle)({ resource: mockAudioResource });
expect(mockFfmpegHandle.stop).toHaveBeenCalledTimes(1);
expect(mockAudioResource.playStream.destroy).toHaveBeenCalledTimes(1);
expect(manager.state).toBe('ready');
expect(manager.isPlaying).toBe(false);
});
it('does not report playback when stopped before ffmpeg is ready', async () => {
const ready = Promise.withResolvers<void>();
jest.mocked(startFfmpeg).mockReturnValueOnce({
...mockFfmpegHandle,
ready: ready.promise,
});
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
await manager.connect();
const playPromise = manager.play();
await manager.stop();
ready.resolve();
await expect(playPromise).rejects.toThrow(AudioManagerStateError);
expect(manager.state).toBe('stopped');
expect(mockAudioPlayer.play).not.toHaveBeenCalled();
});
it('does not report playback when disposed before ffmpeg is ready', async () => {
const ready = Promise.withResolvers<void>();
jest.mocked(startFfmpeg).mockReturnValueOnce({
...mockFfmpegHandle,
ready: ready.promise,
});
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
await manager.connect();
const playPromise = manager.play();
manager.dispose();
ready.resolve();
await expect(playPromise).rejects.toThrow(AudioManagerStateError);
expect(manager.state).toBe('disposed');
expect(mockAudioPlayer.play).not.toHaveBeenCalled();
});
it('keeps only the latest concurrent playback', async () => {
const firstReady = Promise.withResolvers<void>();
const firstHandle = {
...createMockFfmpegHandle(),
ready: firstReady.promise,
};
const secondHandle = createMockFfmpegHandle();
jest.mocked(startFfmpeg).mockReturnValueOnce(firstHandle).mockReturnValueOnce(secondHandle);
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
await manager.connect();
const firstPlay = manager.play();
const secondPlay = manager.play({ type: 'file', path: fileSourcePath });
firstReady.resolve();
await expect(firstPlay).rejects.toThrow(AudioManagerStateError);
await expect(secondPlay).resolves.toBeUndefined();
expect(manager.state).toBe('playing');
expect(mockAudioPlayer.play).toHaveBeenCalledTimes(1);
expect(firstHandle.stop).toHaveBeenCalledTimes(1);
expect(secondHandle.stop).not.toHaveBeenCalled();
});
it('replaces active playback when a new source is played', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
await manager.start();
await manager.play({
type: 'file',
path: fileSourcePath,
});
expect(mockFfmpegHandle.stop).toHaveBeenCalledTimes(1);
expect(mockAudioResource.playStream.destroy).toHaveBeenCalledTimes(1);
expect(startFfmpeg).toHaveBeenLastCalledWith(resolvedFileSourcePath, undefined);
});
it('requires an active connection before play()', async () => {
const manager = new AudioManager({
source: liveStreamSource,
renewIntervalMs: false,
});
await expect(manager.play()).rejects.toThrow(AudioManagerStateError);
});
it('requires a source before play()', async () => {
const manager = new AudioManager({
connection: connectionOptions,
renewIntervalMs: false,
});
await manager.connect();
await expect(manager.play()).rejects.toThrow(AudioManagerConfigError);
});
it('rejects invalid URL sources', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: {
type: 'url',
url: 'not a url',
},
renewIntervalMs: false,
});
await manager.connect();
await expect(manager.play()).rejects.toThrow(AudioManagerConfigError);
});
it('applies initial volume only when volume support is enabled', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
volume: {
enabled: true,
initialPercent: 35,
},
});
await manager.start();
expect(mockAudioResource.volume.setVolume).toHaveBeenCalledWith(0.35);
});
it('rejects invalid initial volume before allocating audio resources', () => {
expect(
() =>
new AudioManager({
volume: {
enabled: true,
initialPercent: 101,
},
}),
).toThrow(AudioManagerConfigError);
expect(
() =>
new AudioManager({
volume: {
enabled: false,
initialPercent: 50,
},
}),
).toThrow(AudioManagerConfigError);
expect(createAudioPlayer).not.toHaveBeenCalled();
expect(createAudioResource).not.toHaveBeenCalled();
expect(startFfmpeg).not.toHaveBeenCalled();
});
it('rejects timer delays that Node.js cannot schedule safely', () => {
expect(() => new AudioManager({ connectTimeoutMs: 0 })).toThrow(AudioManagerConfigError);
expect(() => new AudioManager({ renewIntervalMs: 2_147_483_648 })).toThrow(AudioManagerConfigError);
});
it('rejects volume changes when inline volume is disabled', () => {
const manager = new AudioManager({ renewIntervalMs: false });
expect(() => manager.setVolume(50)).toThrow(AudioManagerStateError);
});
it('rejects invalid volume percentages', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
volume: {
enabled: true,
},
});
await manager.start();
expect(() => manager.setVolume(-1)).toThrow(AudioManagerConfigError);
expect(() => manager.setVolume(101)).toThrow(AudioManagerConfigError);
expect(() => manager.setVolume(Number.NaN)).toThrow(AudioManagerConfigError);
expect(() => manager.setVolume(Number.POSITIVE_INFINITY)).toThrow(AudioManagerConfigError);
expect(() => manager.setVolume(Number.NEGATIVE_INFINITY)).toThrow(AudioManagerConfigError);
expect(() => manager.setVolume(0)).not.toThrow();
expect(() => manager.setVolume(42)).not.toThrow();
expect(() => manager.setVolume(100)).not.toThrow();
});
it('rejects volume changes before any resource exists', () => {
const manager = new AudioManager({
renewIntervalMs: false,
volume: {
enabled: true,
},
});
expect(() => manager.setVolume(50)).toThrow(AudioManagerStateError);
});
it('pauses and resumes only from valid playback states', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
expect(() => manager.pause()).toThrow(AudioManagerStateError);
await manager.start();
manager.pause();
manager.resume();
expect(mockAudioPlayer.pause).toHaveBeenCalledTimes(1);
expect(mockAudioPlayer.unpause).toHaveBeenCalledTimes(1);
expect(manager.state).toBe('playing');
});
it('stops playback and voice resources idempotently', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
await manager.start();
await manager.stop();
await manager.stop();
expect(mockFfmpegHandle.stop).toHaveBeenCalledTimes(1);
expect(mockAudioResource.playStream.destroy).toHaveBeenCalledTimes(1);
expect(mockConnection.destroy).toHaveBeenCalled();
expect(manager.state).toBe('stopped');
});
it('rejects pause and resume after stop', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
await manager.start();
await manager.stop();
expect(() => manager.pause()).toThrow(AudioManagerStateError);
expect(() => manager.resume()).toThrow(AudioManagerStateError);
});
it('restarts playback when the renewal timer fires', async () => {
jest.useFakeTimers();
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: 10_000,
});
const startSpy = jest.spyOn(manager, 'start').mockResolvedValue(undefined);
await manager.connect();
jest.advanceTimersByTime(10_000);
await Promise.resolve();
expect(startSpy).toHaveBeenCalledTimes(1);
});
it('cleans up when renewal restart fails', async () => {
jest.useFakeTimers();
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: 10_000,
});
const startSpy = jest.spyOn(manager, 'start').mockRejectedValue(new Error('renewal failed'));
await manager.connect();
jest.advanceTimersByTime(10_000);
await Promise.resolve();
expect(startSpy).toHaveBeenCalledTimes(1);
expect(mockAudioPlayer.stop).toHaveBeenCalledWith(true);
expect(mockConnection.destroy).toHaveBeenCalled();
expect(manager.state).toBe('stopped');
expect(jest.getTimerCount()).toBe(0);
});
it('clears existing renewal timer before reconnecting', async () => {
jest.useFakeTimers();
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: 10_000,
});
await manager.connect();
await manager.connect();
expect(jest.getTimerCount()).toBe(1);
manager.dispose();
expect(jest.getTimerCount()).toBe(0);
});
it('blocks source and connection changes after disposal', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
manager.dispose();
expect(() => manager.setSource(liveStreamSource)).toThrow(AudioManagerStateError);
expect(() => manager.setConnection(connectionOptions)).toThrow(AudioManagerStateError);
});
it('supports explicit resource management', () => {
const manager = (() => {
using disposableManager = new AudioManager({ renewIntervalMs: false });
return disposableManager;
})();
expect(manager.state).toBe('disposed');
});
it('prevents use after disposal', async () => {
const manager = new AudioManager({
connection: connectionOptions,
source: liveStreamSource,
renewIntervalMs: false,
});
await manager.start();
manager.dispose();
expect(() => manager.pause()).toThrow(AudioManagerStateError);
expect(manager.state).toBe('disposed');
});
});
BIN
View File
Binary file not shown.
+246
View File
@@ -0,0 +1,246 @@
import { jest, describe, beforeEach, afterEach, it, expect } from '@jest/globals';
import { spawn } from 'node:child_process';
import type { ChildProcess } from 'node:child_process';
import { FfmpegProcessError } from '../src';
import { resolveFfmpegExecutable, startFfmpeg } from '../src/ffmpeg';
jest.mock('node:child_process', () => ({
spawn: jest.fn(),
}));
const mockSpawn = jest.mocked(spawn);
type MockChildProcess = {
stdout: {
destroy: jest.Mock;
once: jest.Mock;
off: jest.Mock;
};
stderr: {
destroy: jest.Mock;
on: jest.Mock;
off: jest.Mock;
resume: jest.Mock;
};
on: jest.Mock;
once: jest.Mock;
off: jest.Mock;
kill: jest.Mock;
killed: boolean;
exitCode: number | null;
signalCode: NodeJS.Signals | null;
};
function createMockChildProcess(): MockChildProcess {
return {
stdout: {
destroy: jest.fn(),
once: jest.fn(),
off: jest.fn(),
},
stderr: {
destroy: jest.fn(),
on: jest.fn(),
off: jest.fn(),
resume: jest.fn(),
},
on: jest.fn(),
once: jest.fn(),
off: jest.fn(),
kill: jest.fn(),
killed: false,
exitCode: null,
signalCode: null,
};
}
function mockSpawnReturn(childProcess: MockChildProcess): void {
mockSpawn.mockReturnValue(childProcess as unknown as ChildProcess);
}
function getProcessHandler(childProcess: MockChildProcess, eventName: string): (...args: unknown[]) => void {
return childProcess.once.mock.calls.find(([event]) => event === eventName)?.[1] as (...args: unknown[]) => void;
}
function getPersistentProcessHandler(childProcess: MockChildProcess, eventName: string): (...args: unknown[]) => void {
return childProcess.on.mock.calls.find(([event]) => event === eventName)?.[1] as (...args: unknown[]) => void;
}
function getStdoutHandler(childProcess: MockChildProcess, eventName: string): (...args: unknown[]) => void {
return childProcess.stdout.once.mock.calls.find(([event]) => event === eventName)?.[1] as (
...args: unknown[]
) => void;
}
function getStderrHandler(childProcess: MockChildProcess, eventName: string): (...args: unknown[]) => void {
return childProcess.stderr.on.mock.calls.find(([event]) => event === eventName)?.[1] as (
...args: unknown[]
) => void;
}
describe('ffmpeg helpers', () => {
beforeEach(() => {
jest.clearAllMocks();
});
afterEach(() => {
jest.useRealTimers();
});
it('prefers an explicit executable path', () => {
expect(resolveFfmpegExecutable({ executablePath: '/custom/ffmpeg' })).toBe('/custom/ffmpeg');
});
it('uses the native ffmpeg binary by default', () => {
expect(resolveFfmpegExecutable()).toBe('ffmpeg');
expect(resolveFfmpegExecutable({ mode: 'native' })).toBe('ffmpeg');
});
it('spawns ffmpeg with the default argument set', () => {
const childProcess = createMockChildProcess();
mockSpawnReturn(childProcess);
startFfmpeg('https://synradiode.stream.laut.fm/synradiode');
expect(mockSpawn).toHaveBeenCalledWith(
'ffmpeg',
[
'-hide_banner',
'-loglevel',
'error',
'-nostdin',
'-i',
'https://synradiode.stream.laut.fm/synradiode',
'-vn',
'-f',
's16le',
'-ar',
'48000',
'-ac',
'2',
'pipe:1',
],
{ stdio: ['ignore', 'pipe', 'pipe'] },
);
expect(childProcess.on).toHaveBeenCalledWith('error', expect.any(Function));
expect(childProcess.once).toHaveBeenCalledWith('exit', expect.any(Function));
expect(childProcess.stdout.once).toHaveBeenCalledWith('readable', expect.any(Function));
expect(childProcess.stderr.on).toHaveBeenCalledWith('data', expect.any(Function));
expect(childProcess.stderr.resume).toHaveBeenCalledTimes(1);
});
it('rejects readiness when ffmpeg startup emits an error', async () => {
const childProcess = createMockChildProcess();
mockSpawnReturn(childProcess);
const handle = startFfmpeg('tests/audio.mp3');
const errorHandler = getPersistentProcessHandler(childProcess, 'error');
const spawnError = new Error('spawn ENOENT');
errorHandler(spawnError);
await expect(handle.ready).rejects.toMatchObject({
cause: spawnError,
message: expect.stringContaining('spawn ENOENT'),
name: FfmpegProcessError.name,
});
});
it('includes stderr when ffmpeg exits before producing audio', async () => {
const childProcess = createMockChildProcess();
mockSpawnReturn(childProcess);
const handle = startFfmpeg('tests/audio.mp3');
const stderrHandler = getStderrHandler(childProcess, 'data');
const exitHandler = getProcessHandler(childProcess, 'exit');
stderrHandler('invalid input');
exitHandler(1, null);
await expect(handle.ready).rejects.toThrow('invalid input');
});
it('keeps the useful tail of long ffmpeg stderr output', async () => {
const childProcess = createMockChildProcess();
mockSpawnReturn(childProcess);
const handle = startFfmpeg('tests/audio.mp3');
const stderrHandler = getStderrHandler(childProcess, 'data');
const exitHandler = getProcessHandler(childProcess, 'exit');
stderrHandler(`${'x'.repeat(5_000)}final diagnostic`);
exitHandler(1, null);
await expect(handle.ready).rejects.toThrow('final diagnostic');
});
it('keeps readiness resolved when ffmpeg exits after producing audio', async () => {
const childProcess = createMockChildProcess();
mockSpawnReturn(childProcess);
const handle = startFfmpeg('tests/audio.mp3');
const readableHandler = getStdoutHandler(childProcess, 'readable');
const exitHandler = getProcessHandler(childProcess, 'exit');
const errorHandler = getPersistentProcessHandler(childProcess, 'error');
readableHandler();
errorHandler(new Error('late process error'));
exitHandler(1, null);
await expect(handle.ready).resolves.toBeUndefined();
});
it('uses custom executable and argument overrides when provided', () => {
const childProcess = createMockChildProcess();
mockSpawnReturn(childProcess);
startFfmpeg('tests/audio.mp3', {
executablePath: '/custom/ffmpeg',
inputArgs: ['-re'],
outputArgs: ['-f', 'wav', 'pipe:1'],
});
expect(mockSpawn).toHaveBeenCalledWith(
'/custom/ffmpeg',
['-re', '-i', 'tests/audio.mp3', '-f', 'wav', 'pipe:1'],
{ stdio: ['ignore', 'pipe', 'pipe'] },
);
});
it('stops a running child process and schedules a force kill fallback', async () => {
jest.useFakeTimers();
const childProcess = createMockChildProcess();
childProcess.kill.mockImplementation(() => {
childProcess.killed = true;
return true;
});
mockSpawnReturn(childProcess);
const handle = startFfmpeg('tests/audio.mp3');
const readyExpectation = expect(handle.ready).rejects.toThrow('stopped before producing audio');
handle.stop();
await readyExpectation;
expect(childProcess.stdout.destroy).toHaveBeenCalledTimes(1);
expect(childProcess.stderr.destroy).toHaveBeenCalledTimes(1);
expect(childProcess.kill).toHaveBeenCalledWith('SIGTERM');
jest.advanceTimersByTime(2_000);
expect(childProcess.kill).toHaveBeenNthCalledWith(2, 'SIGKILL');
});
it('does not signal a process that already exited', async () => {
const childProcess = createMockChildProcess();
childProcess.exitCode = 0;
mockSpawnReturn(childProcess);
const handle = startFfmpeg('tests/audio.mp3');
const readyExpectation = expect(handle.ready).rejects.toThrow('stopped before producing audio');
handle.stop();
await readyExpectation;
expect(childProcess.kill).not.toHaveBeenCalled();
});
});
+5 -2
View File
@@ -1,4 +1,7 @@
{ {
"extends": "./tsconfig.json", "extends": "./tsconfig.json",
"include": ["src/**/*.ts"] "compilerOptions": {
"skipLibCheck": true
},
"include": ["src/**/*.ts", "tests/**/*.ts", "tsup.config.ts"]
} }
+22 -18
View File
@@ -1,20 +1,24 @@
{ {
"compilerOptions": { "compilerOptions": {
"strict": true, "target": "ES2024",
"allowJs": false, "lib": ["ES2024"],
"noImplicitAny": true, "module": "Node20",
"esModuleInterop": true, "types": [],
"strictNullChecks": true, "rootDir": "./",
"target": "ES2022", "outDir": "./dist",
"moduleResolution": "Node", "esModuleInterop": true,
"module": "CommonJS", "forceConsistentCasingInFileNames": true,
"declaration": true, "strict": true,
"isolatedModules": true, "isolatedModules": true,
"noEmit": true, "erasableSyntaxOnly": true,
"outDir": "dist", "noUnusedLocals": true,
"types": ["node"], "noUnusedParameters": true,
"typeRoots": ["node_modules/@types"] "noImplicitReturns": true,
}, "noUncheckedIndexedAccess": true,
"include": ["src"], "exactOptionalPropertyTypes": true,
"exclude": ["node_modules"] "noFallthroughCasesInSwitch": true,
"noEmitOnError": true
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
} }
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./dist-test",
"skipLibCheck": true
},
"include": ["src/**/*.ts", "tests/**/*.ts", "tsup.config.ts"]
}
+11 -6
View File
@@ -1,10 +1,15 @@
import { defineConfig } from 'tsup'; import { defineConfig } from 'tsup';
export default defineConfig({ export default defineConfig({
format: ['cjs', 'esm'], format: ['cjs', 'esm'],
entry: ['./src/index.ts'], entry: ['./src/index.ts'],
dts: true, dts: {
shims: true, compilerOptions: {
skipNodeModulesBundle: true, // tsup's declaration bundler still sets the removed baseUrl option internally.
clean: true, ignoreDeprecations: '6.0',
},
},
shims: true,
skipNodeModulesBundle: true,
clean: true,
}); });
-4480
View File
File diff suppressed because it is too large Load Diff