Compare commits

...

36 Commits

Author SHA1 Message Date
iCrawl
60c70389a4 chore(collection): release @discordjs/collection@1.2.0 2022-10-08 16:35:58 +02:00
iCrawl
f06d12fd73 chore(builders): release @discordjs/builders@1.3.0 2022-10-08 16:34:30 +02:00
iCrawl
dc31b76465 ci: update workflow for tags 2022-10-08 16:33:37 +02:00
iCrawl
ba90f14f9b feat: auto-link headings 2022-10-08 15:44:00 +02:00
iCrawl
7b76b0b7e7 fix: proper root margin values for intersection observer 2022-10-08 14:31:26 +02:00
iCrawl
63939f8219 feat: automatic hash for anchors on scroll 2022-10-08 14:04:00 +02:00
Suneet Tipirneni
33ec49d5bf feat(guide): add outline for pages (#8722)
Co-authored-by: iCrawl <buechler.noel@outlook.com>
2022-10-08 05:15:02 +02:00
Jeroen Claassens
d923d0ab96 build: switch to esbuild-plugin-version-injector for injecting version strings (#8723) 2022-10-08 02:54:45 +02:00
iCrawl
62332c2720 chore: deps 2022-10-07 20:26:45 +02:00
Parbez
7af3c3b6f1 fix: ws package.json path (#8720) 2022-10-07 19:42:04 +02:00
iCrawl
5730866073 feat: alert & discord components 2022-10-07 17:49:03 +02:00
Parbez
9f68d73706 fix: cliff.toml styling (#8716) 2022-10-07 13:57:48 +02:00
Noel
0ac3e766bd feat: web-components (#8715) 2022-10-07 06:56:13 +02:00
iCrawl
76a7021452 chore: deps 2022-10-07 02:49:44 +02:00
iCrawl
103cb16be0 refactor: improve deprecation block 2022-10-07 02:45:04 +02:00
iCrawl
baa6c69835 refactor: improve tips/warnings 2022-10-07 02:44:28 +02:00
Suneet Tipirneni
f85022162d feat(scripts): Add script to create a @discordjs package (#8711) 2022-10-07 02:38:58 +02:00
iCrawl
35bfba0c50 fix: info and caution components 2022-10-07 01:14:49 +02:00
iCrawl
ecfe4e3f1c fix: index page 2022-10-07 00:33:41 +02:00
Noel
2628659747 feat: astro guide (#8714) 2022-10-06 23:53:35 +02:00
ckohen
01d75c8b8b fix(Client): don't auth for webhook fetches with token (#8709)
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-10-06 19:43:00 +00:00
iCrawl
b64d657241 chore: removing building website from pre-commit 2022-10-06 12:36:26 +02:00
Almeida
7e51ea0ada chore(util): add missing cliff-jumper config file (#8707) 2022-10-06 12:11:19 +02:00
Almeida
aec44a0c93 refactor: rename Error to DiscordjsError internally (#8706)
* refactor: rename Error to DiscordjsError internally

* chore: remove globalThis usage

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-10-06 09:21:03 +00:00
iCrawl
e745b95677 chore: deps 2022-10-05 20:57:39 +02:00
Suneet Tipirneni
9effd82abe docs: fix AwaitMessageComponentOptions typedef (#8696)
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-10-05 20:41:36 +02:00
SpaceEEC
628759bcff feat(GuildChannelManager): allow creating channels with a default auto archive duration (#8693) 2022-10-05 20:41:15 +02:00
muchnameless
a306219673 fix: re-export util (#8699) 2022-10-05 20:40:50 +02:00
Suneet Tipirneni
c0f7a1a89a types(Message): remove & this from #inGuild typeguard (#8704) 2022-10-05 20:40:28 +02:00
Julian
a7eab50ee3 fix(WebSocketShard): add ready data parameter to ready event (#8705) 2022-10-05 20:39:05 +02:00
Jiralite
ace974fc1f fix: Throw discord.js errors correctly (#8697)
fix: import errors correctly

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-10-05 16:16:07 +00:00
iCrawl
d9137c3658 chore: deps 2022-10-04 01:10:35 +02:00
iCrawl
b7fadb350a fix: sidebar menu styling 2022-10-04 01:02:37 +02:00
iCrawl
1f944b889f feat: allow search by tags 2022-10-04 00:47:15 +02:00
iCrawl
b187a18e9c feat: properly build search indicies 2022-10-04 00:46:15 +02:00
iCrawl
0b8651cf85 chore: remove building package docs with old docgen 2022-10-03 14:32:40 +02:00
243 changed files with 9667 additions and 2928 deletions

View File

@@ -16,3 +16,14 @@ To get ready to work on the codebase, please do the following:
4. Code your heart out!
5. Run `yarn test` to run ESLint and ensure any JSDoc changes are valid
6. [Submit a pull request](https://github.com/discordjs/discord.js/compare) (Make sure you follow the [conventional commit format](https://github.com/discordjs/discord.js/blob/main/.github/COMMIT_CONVENTION.md))
## Adding new packages
If you'd like to create another package under the `@discordjs` organization run the following command:
```bash
yarn create-package <package-name> [package-description]
```
This will create new package directory under `packages/` with the required configuration files. You can
begin to make changes within the `src/` directory.

50
.github/labeler.yml vendored
View File

@@ -1,43 +1,39 @@
'packages:builders':
packages:builders:
- packages/builders/*
- packages/builders/**/*
'packages:collection':
packages:collection:
- packages/collection/*
- packages/collection/**/*
'packages:discord.js':
packages:discord.js:
- packages/discord.js/*
- packages/discord.js/**/*
'packages:docgen':
packages:docgen:
- packages/docgen/*
- packages/docgen/**/*
'packages:proxy':
packages:guide:
- packages/guide/*
- packages/guide/**/*
packages:proxy:
- packages/proxy/*
- packages/proxy/**/*
'packages:proxy-container':
packages:proxy-container:
- packages/proxy-container/*
- packages/proxy-container/**/*
'packages:rest':
packages:rest:
- packages/rest/*
- packages/rest/**/*
'packages:voice':
- packages/voice/*
- packages/voice/**/*
'packages:website':
- packages/website/*
- packages/website/**/*
'packages:ws':
- packages/ws/*
- packages/ws/**/*
'packages:util':
packages:util:
- packages/util/*
- packages/util/**/*
packages:voice:
- packages/voice/*
- packages/voice/**/*
packages:website:
- packages/website/*
- packages/website/**/*
packages/web-components:
- packages:web-components/*
- packages:web-components/**/*
packages:ws:
- packages/ws/*
- packages/ws/**/*

204
.github/labels.yml vendored
View File

@@ -1,104 +1,108 @@
- name: 'api changes'
- name: api changes
color: '5663e9'
- name: 'api support'
- name: api support
color: '5663e9'
- name: 'backlog'
color: '7ef7ef'
- name: 'blocked'
color: 'fc1423'
- name: 'bug'
color: 'd73a4a'
- name: 'caching'
color: '80c042'
- name: 'chore'
color: 'ffffff'
- name: 'ci'
color: '0075ca'
- name: 'dependencies'
color: '276bd1'
- name: 'discussion'
color: 'b6b1f9'
- name: 'discord'
- name: backlog
color: 7ef7ef
- name: blocked
color: fc1423
- name: bug
color: d73a4a
- name: caching
color: 80c042
- name: chore
color: ffffff
- name: ci
color: 0075ca
- name: dependencies
color: 276bd1
- name: discussion
color: b6b1f9
- name: discord
color: '5663e9'
- name: 'documentation'
color: '0075ca'
- name: 'duplicate'
color: 'cfd3d7'
- name: 'error handling'
color: '80c042'
- name: 'feature request'
color: 'fcf95a'
- name: 'gateway'
color: '80c042'
- name: 'good first issue'
color: '7057ff'
- name: 'has PR'
color: '4b1f8e'
- name: 'help wanted'
- name: documentation
color: 0075ca
- name: duplicate
color: cfd3d7
- name: error handling
color: 80c042
- name: feature request
color: fcf95a
- name: gateway
color: 80c042
- name: good first issue
color: 7057ff
- name: has PR
color: 4b1f8e
- name: help wanted
color: '008672'
- name: 'interactions'
color: '80c042'
- name: 'in progress'
color: 'ffccd7'
- name: 'in review'
color: 'aed5fc'
- name: 'invalid'
color: 'e4e669'
- name: 'need repro'
color: 'c66037'
- name: 'packages:builders'
color: 'fbca04'
- name: 'packages:collection'
color: 'fbca04'
- name: 'packages:discord.js'
color: 'fbca04'
- name: 'packages:docgen'
color: 'fbca04'
- name: 'packages:proxy'
color: 'fbca04'
- name: 'packages:proxy-container'
color: 'fbca04'
- name: 'packages:rest'
color: 'fbca04'
- name: 'packages:voice'
color: 'fbca04'
- name: 'packages:website'
color: 'fbca04'
- name: 'packages:ws'
color: 'fbca04'
- name: 'packages:util'
color: 'fbca04'
- name: 'performance'
color: '80c042'
- name: 'permissions'
color: '80c042'
- name: 'priority:high'
color: 'fc1423'
- name: 'question (please use Discord instead)'
color: 'd876e3'
- name: 'ratelimits'
color: '80c042'
- name: 'refactor'
color: '1d637f'
- name: 'regression'
color: 'ea8785'
- name: 'REST'
color: '80c042'
- name: 'semver:major'
color: 'c10f47'
- name: 'semver:minor'
color: 'e4f486'
- name: 'semver:patch'
color: 'e8be8b'
- name: 'sharding'
color: '80c042'
- name: 'tests'
color: 'f06dff'
- name: 'threads'
color: '80c042'
- name: 'typings'
color: '80c042'
- name: 'utility'
color: '80c042'
- name: 'wontfix'
color: 'ffffff'
- name: interactions
color: 80c042
- name: in progress
color: ffccd7
- name: in review
color: aed5fc
- name: invalid
color: e4e669
- name: need repro
color: c66037
- name: packages:builders
color: fbca04
- name: packages:collection
color: fbca04
- name: packages:discord.js
color: fbca04
- name: packages:docgen
color: fbca04
- name: packages:guide
color: fbca04
- name: packages:proxy
color: fbca04
- name: packages:proxy-container
color: fbca04
- name: packages:rest
color: fbca04
- name: packages:util
color: fbca04
- name: packages:voice
color: fbca04
- name: packages:website
color: fbca04
- name: packages:web-components
color: fbca04
- name: packages:ws
color: fbca04
- name: performance
color: 80c042
- name: permissions
color: 80c042
- name: priority:high
color: fc1423
- name: question (please use Discord instead)
color: d876e3
- name: ratelimits
color: 80c042
- name: refactor
color: 1d637f
- name: regression
color: ea8785
- name: REST
color: 80c042
- name: semver:major
color: c10f47
- name: semver:minor
color: e4f486
- name: semver:patch
color: e8be8b
- name: sharding
color: 80c042
- name: tests
color: f06dff
- name: threads
color: 80c042
- name: typings
color: 80c042
- name: utility
color: 80c042
- name: wontfix
color: ffffff

View File

@@ -27,10 +27,6 @@ jobs:
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
outputs:
BRANCH_NAME: ${{ steps.env.outputs.BRANCH_NAME }}
BRANCH_OR_TAG: ${{ steps.env.outputs.BRANCH_OR_TAG }}
SHA: ${{ steps.env.outputs.SHA }}
if: github.repository_owner == 'discordjs'
steps:
- name: Checkout repository
@@ -65,13 +61,6 @@ jobs:
name: api-extractor
path: packages/*/docs/docs.api.json
- name: Set outputs for upload job
id: env
run: |
echo "::set-output name=BRANCH_NAME::${GITHUB_REF_NAME}"
echo "::set-output name=BRANCH_OR_TAG::${GITHUB_REF_TYPE}"
echo "::set-output name=SHA::${GITHUB_SHA}"
upload:
name: Upload Documentation
needs: build
@@ -86,7 +75,6 @@ jobs:
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
BRANCH_NAME: ${{ github.event.inputs.ref || needs.build.outputs.BRANCH_NAME }}
BRANCH_OR_TAG: ${{ github.event.inputs.ref_type || needs.build.outputs.BRANCH_OR_TAG }}
SHA: ${{ needs.build.outputs.SHA }}
steps:
- name: Checkout repository
uses: actions/checkout@v3
@@ -123,33 +111,37 @@ jobs:
path: 'out'
- name: Extract package and semver from tag
if: ${{ env.BRANCH_OR_TAG == 'tag' }}
if: ${{ env.GITHUB_REF_TYPE == 'tag' }}
id: extract-tag
uses: ./packages/actions/src/formatTag
with:
tag: ${{ env.BRANCH_NAME }}
tag: ${{ env.GITHUB_REF_NAME }}
- name: Move docs to correct directory
if: ${{ env.BRANCH_OR_TAG == 'tag' && matrix.package == steps.extract-tag.outputs.package }}
if: ${{ env.GITHUB_REF_TYPE == 'tag' && matrix.package == steps.extract-tag.outputs.package }}
env:
PACKAGE: ${{ steps.extract-tag.outputs.package }}
SEMVER: ${{ steps.extract-tag.outputs.semver }}
run: |
mkdir -p out/${PACKAGE}
mv docs/${PACKAGE}/docs/docs.json out/${PACKAGE}/${SEMVER}.json
if [[ $PACKAGE == "discord.js" ]]; then
mv docs/${PACKAGE}/docs/docs.json out/${PACKAGE}/${SEMVER}.json
fi
if [[ $PACKAGE != "discord.js" ]]; then
mv docs/${PACKAGE}/docs/docs.api.json out/${PACKAGE}/${SEMVER}.api.json
fi
- name: Move docs to correct directory
if: ${{ env.BRANCH_OR_TAG == 'branch' }}
if: ${{ env.GITHUB_REF_TYPE == 'branch' }}
env:
PACKAGE: ${{ matrix.package }}
run: |
mkdir -p out/${PACKAGE}
mv docs/${PACKAGE}/docs/docs.json out/${PACKAGE}/${BRANCH_NAME}.json
if [[ $PACKAGE == "discord.js" ]]; then
mv docs/${PACKAGE}/docs/docs.json out/${PACKAGE}/${GITHUB_REF_NAME}.json
fi
if [[ $PACKAGE != "discord.js" ]]; then
mv docs/${PACKAGE}/docs/docs.api.json out/${PACKAGE}/${BRANCH_NAME}.api.json
mv docs/${PACKAGE}/docs/docs.api.json out/${PACKAGE}/${GITHUB_REF_NAME}.api.json
fi
- name: Commit and push
@@ -158,5 +150,5 @@ jobs:
git config user.name github-actions[bot]
git config user.email 41898282+github-actions[bot]@users.noreply.github.com
git add .
git commit -m "Docs build for ${BRANCH_OR_TAG} ${BRANCH_NAME}: ${SHA}" || true
git commit -m "Docs build for ${GITHUB_REF_TYPE} ${GITHUB_REF_NAME}: ${GITHUB_SHA}" || true
git push

View File

@@ -1,4 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
yarn build && yarn workspace @discordjs/website run build:local && yarn lint-staged
yarn build && yarn lint-staged

View File

@@ -1,5 +1,5 @@
{
"*": "prettier --ignore-unknown --write",
"{src/**,__tests__/**}.{mjs,js,ts}": "eslint --ext mjs,js,ts --fix",
"src/**.ts": "vitest related --run"
"{src/**,__tests__/**}.{mjs,js,cjs,ts,tsx,astro}": "eslint --ext .mjs,.js,.cjs,.ts,.tsx,.astro --fix",
"src/**.ts": "vitest related --run --config ./vitest.config.ts"
}

View File

@@ -8,6 +8,7 @@
"eamodio.gitlens",
"christian-kohler.npm-intellisense",
"christian-kohler.path-intellisense",
"antfu.unocss"
"antfu.unocss",
"astro-build.astro-vscode"
]
}

View File

@@ -1,11 +1,16 @@
{
"eslint.workingDirectories": [{ "pattern": "./packages/*" }],
"eslint.validate": ["javascript", "javascriptreact", "astro", "typescript", "typescriptreact"],
"prettier.documentSelectors": ["**/*.astro"],
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": true,
"source.organizeImports": false
},
"unocss.root": "./packages/website",
"files.associations": {
"*.mdx": "markdown"
},
"unocss.root": "./packages/web-components",
"typescript.tsdk": "node_modules/typescript/lib"
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

801
.yarn/releases/yarn-3.2.4.cjs vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -8,4 +8,4 @@ plugins:
- path: .yarn/plugins/@yarnpkg/plugin-version.cjs
spec: "@yarnpkg/plugin-version"
yarnPath: .yarn/releases/yarn-3.2.1.cjs
yarnPath: .yarn/releases/yarn-3.2.4.cjs

View File

@@ -11,7 +11,8 @@
"fmt": "turbo run format --parallel",
"postinstall": "is-ci || husky install",
"docs": "turbo run docs --parallel",
"update": "yarn upgrade-interactive"
"update": "yarn upgrade-interactive",
"create-package": "node packages/scripts/src/packageScript.mjs"
},
"contributors": [
"Crawl <icrawltogo@gmail.com>",
@@ -39,15 +40,15 @@
"devDependencies": {
"@commitlint/cli": "^17.1.2",
"@commitlint/config-angular": "^17.1.0",
"@favware/cliff-jumper": "^1.8.7",
"@favware/cliff-jumper": "^1.8.8",
"@favware/npm-deprecate": "^1.0.5",
"conventional-changelog-cli": "^2.2.2",
"husky": "^8.0.1",
"is-ci": "^3.0.1",
"lint-staged": "^13.0.3",
"tsup": "^6.2.3",
"turbo": "^1.5.3",
"typescript": "^4.8.3"
"turbo": "^1.5.5",
"typescript": "^4.8.4"
},
"resolutions": {
"@microsoft/tsdoc-config": "patch:@microsoft/tsdoc-config@npm:0.16.1#.yarn/patches/@microsoft-tsdoc-config-npm-0.16.1-81031b1bbf.patch"
@@ -58,5 +59,5 @@
"workspaces": [
"packages/*"
],
"packageManager": "yarn@3.2.1"
"packageManager": "yarn@3.2.4"
}

View File

@@ -6,8 +6,8 @@
"scripts": {
"test": "vitest run",
"build": "tsup",
"lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext mjs,js,ts",
"format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext mjs,js,ts --fix",
"lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts",
"format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix",
"fmt": "yarn format"
},
"main": "./dist/index.mjs",
@@ -39,19 +39,19 @@
},
"homepage": "https://discord.js.org",
"dependencies": {
"@actions/core": "^1.9.1",
"@actions/core": "^1.10.0",
"tslib": "^2.4.0"
},
"devDependencies": {
"@types/node": "^16.11.60",
"@vitest/coverage-c8": "^0.23.4",
"@types/node": "^16.11.64",
"@vitest/coverage-c8": "^0.24.0",
"cross-env": "^7.0.3",
"eslint": "^8.24.0",
"eslint-config-neon": "^0.1.33",
"eslint-config-neon": "^0.1.35",
"prettier": "^2.7.1",
"tsup": "^6.2.3",
"typescript": "^4.8.3",
"vitest": "^0.23.4"
"typescript": "^4.8.4",
"vitest": "^0.24.0"
},
"engines": {
"node": ">=16.9.0"

View File

@@ -5,8 +5,8 @@
"private": true,
"scripts": {
"build": "tsup",
"lint": "prettier --check . && cross-env TIMING=1 eslint src --ext mjs,js,ts",
"format": "prettier --write . && cross-env TIMING=1 eslint src --ext mjs,js,ts --fix",
"lint": "prettier --check . && cross-env TIMING=1 eslint src --ext .mjs,.js,.ts",
"format": "prettier --write . && cross-env TIMING=1 eslint src --ext .mjs,.js,.ts --fix",
"fmt": "yarn format"
},
"main": "./dist/index.js",
@@ -35,13 +35,13 @@
"@microsoft/tsdoc": "0.14.1"
},
"devDependencies": {
"@types/node": "^16.11.60",
"@types/node": "^16.11.64",
"cross-env": "^7.0.3",
"eslint": "^8.24.0",
"eslint-config-neon": "^0.1.33",
"eslint-config-neon": "^0.1.35",
"prettier": "^2.7.1",
"tsup": "^6.2.3",
"typescript": "^4.8.3"
"typescript": "^4.8.4"
},
"engines": {
"node": ">=16.9.0"

View File

@@ -2,6 +2,40 @@
All notable changes to this project will be documented in this file.
# [@discordjs/builders@1.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.2.0...@discordjs/builders@1.3.0) - (2022-10-08)
## Bug Fixes
- Allow adding forums to `channelTypes` (#8658) ([b1e190c](https://github.com/discordjs/discord.js/commit/b1e190c4f0773a1a739625f5b41026f593515370))
- **SlashCommandBuilder:** Missing methods in subcommand builder (#8583) ([1c5b78f](https://github.com/discordjs/discord.js/commit/1c5b78fd2130f09c951459cf4c2d637f46c3c2c9))
- Footer / sidebar / deprecation alert ([ba3e0ed](https://github.com/discordjs/discord.js/commit/ba3e0ed348258fe8e51eefb4aa7379a1230616a9))
## Documentation
- **builders/components:** Document constructors (#8636) ([8444576](https://github.com/discordjs/discord.js/commit/8444576f45da5fdddbf8ba2d91b4cb31a3b51c04))
- Change name (#8604) ([dd5a089](https://github.com/discordjs/discord.js/commit/dd5a08944c258a847fc4377f1d5e953264ab47d0))
- Use remarks instead of `Note` in descriptions (#8597) ([f3ce4a7](https://github.com/discordjs/discord.js/commit/f3ce4a75d0c4eafc89a1f0ce9f4964bcbcdae6da))
## Features
- Web-components (#8715) ([0ac3e76](https://github.com/discordjs/discord.js/commit/0ac3e766bd9dbdeb106483fa4bb085d74de346a2))
- Add `@discordjs/util` (#8591) ([b2ec865](https://github.com/discordjs/discord.js/commit/b2ec865765bf94181473864a627fb63ea8173fd3))
- Add `chatInputApplicationCommandMention` formatter (#8546) ([d08a57c](https://github.com/discordjs/discord.js/commit/d08a57cadd9d69a734077cc1902d931ab10336db))
## Refactor
- Replace usage of deprecated `ChannelType`s (#8625) ([669c3cd](https://github.com/discordjs/discord.js/commit/669c3cd2566eac68ef38ab522dd6378ba761e8b3))
- Website components (#8600) ([c334157](https://github.com/discordjs/discord.js/commit/c3341570d983aea9ecc419979d5a01de658c9d67))
- Use `eslint-config-neon` for packages. (#8579) ([edadb9f](https://github.com/discordjs/discord.js/commit/edadb9fe5dfd9ff51a3cfc9b25cb242d3f9f5241))
## Testing
- Rename incorrect test (#8596) ([ce991dd](https://github.com/discordjs/discord.js/commit/ce991dd1d883f6785b5f4b4b3ac80ef21cb304e7))
## Typings
- **interactions:** Fix `{Slash,ContextMenu}CommandBuilder#toJSON` (#8568) ([b7eb96d](https://github.com/discordjs/discord.js/commit/b7eb96d45670616521fbcca28a657793d91605c7))
# [@discordjs/builders@1.2.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.1.0...@discordjs/builders@1.2.0) - (2022-08-22)
## Features

View File

@@ -1,14 +1,14 @@
{
"name": "@discordjs/builders",
"version": "1.2.0",
"version": "1.3.0",
"description": "A set of builders that you can use when creating your bot",
"scripts": {
"test": "vitest run",
"build": "tsup",
"lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext mjs,js,ts",
"format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext mjs,js,ts --fix",
"lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts",
"format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix",
"fmt": "yarn format",
"docs": "downlevel-dts dist docs/dist --to=3.7 && docgen -i src/index.ts -c docs/index.json -o docs/docs.json --typescript && api-extractor run --local",
"docs": "downlevel-dts dist docs/dist --to=3.7 && api-extractor run --local",
"prepack": "yarn lint && yarn test && yarn build",
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/builders/*'",
"release": "cliff-jumper"
@@ -55,26 +55,26 @@
"homepage": "https://discord.js.org",
"dependencies": {
"@discordjs/util": "workspace:^",
"@sapphire/shapeshift": "^3.6.0",
"discord-api-types": "^0.37.11",
"@sapphire/shapeshift": "^3.7.0",
"discord-api-types": "^0.37.12",
"fast-deep-equal": "^3.1.3",
"ts-mixer": "^6.0.1",
"tslib": "^2.4.0"
},
"devDependencies": {
"@discordjs/docgen": "workspace:^",
"@favware/cliff-jumper": "^1.8.7",
"@microsoft/api-extractor": "^7.31.2",
"@types/node": "^16.11.60",
"@vitest/coverage-c8": "^0.23.4",
"@favware/cliff-jumper": "^1.8.8",
"@microsoft/api-extractor": "^7.32.0",
"@types/node": "^16.11.64",
"@vitest/coverage-c8": "^0.24.0",
"cross-env": "^7.0.3",
"downlevel-dts": "^0.10.1",
"esbuild-plugin-version-injector": "^1.0.0",
"eslint": "^8.24.0",
"eslint-config-neon": "^0.1.33",
"eslint-config-neon": "^0.1.35",
"prettier": "^2.7.1",
"tsup": "^6.2.3",
"typescript": "^4.8.3",
"vitest": "^0.23.4"
"typescript": "^4.8.4",
"vitest": "^0.24.0"
},
"engines": {
"node": ">=16.9.0"

View File

@@ -40,3 +40,12 @@ export * from './util/componentUtil.js';
export * from './util/normalizeArray.js';
export * from './util/validation.js';
export * from '@discordjs/util';
/**
* The [\@discordjs/builders](https://github.com/discordjs/discord.js/blob/main/packages/builders/#readme) version
* that you are currently using.
*
* Note to developers: This needs to explicitly be `string` so it is not typed as a "const string" that gets injected by esbuild
*/
// eslint-disable-next-line @typescript-eslint/no-inferrable-types
export const version: string = '[VI]{{inject}}[/VI]';

View File

@@ -1,3 +1,6 @@
import { esbuildPluginVersionInjector } from 'esbuild-plugin-version-injector';
import { createTsupConfig } from '../../tsup.config.js';
export default createTsupConfig();
export default createTsupConfig({
esbuildPlugins: [esbuildPluginVersionInjector()],
});

View File

@@ -2,6 +2,30 @@
All notable changes to this project will be documented in this file.
# [@discordjs/collection@1.2.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.1.0...@discordjs/collection@1.2.0) - (2022-10-08)
## Bug Fixes
- Footer / sidebar / deprecation alert ([ba3e0ed](https://github.com/discordjs/discord.js/commit/ba3e0ed348258fe8e51eefb4aa7379a1230616a9))
## Documentation
- Change name (#8604) ([dd5a089](https://github.com/discordjs/discord.js/commit/dd5a08944c258a847fc4377f1d5e953264ab47d0))
- Remove xml tag from collection#find (#8550) ([4032457](https://github.com/discordjs/discord.js/commit/40324574ebea9894cadcc967e0db0e4e21d62768))
## Features
- Web-components (#8715) ([0ac3e76](https://github.com/discordjs/discord.js/commit/0ac3e766bd9dbdeb106483fa4bb085d74de346a2))
## Refactor
- Website components (#8600) ([c334157](https://github.com/discordjs/discord.js/commit/c3341570d983aea9ecc419979d5a01de658c9d67))
- Use `eslint-config-neon` for packages. (#8579) ([edadb9f](https://github.com/discordjs/discord.js/commit/edadb9fe5dfd9ff51a3cfc9b25cb242d3f9f5241))
## Typings
- **Collection:** Make fn return type unknown (#8676) ([822b7f2](https://github.com/discordjs/discord.js/commit/822b7f234af053c8f917b0a998b82abfccd33801))
# [@discordjs/collection@1.1.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.0.1...@discordjs/collection@1.1.0) - (2022-08-22)
## Bug Fixes

View File

@@ -1,14 +1,14 @@
{
"name": "@discordjs/collection",
"version": "1.1.0",
"version": "1.2.0",
"description": "Utility data structure used in discord.js",
"scripts": {
"test": "vitest run",
"build": "tsup",
"lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext mjs,js,ts",
"format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext mjs,js,ts --fix",
"lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts",
"format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix",
"fmt": "yarn format",
"docs": "downlevel-dts dist docs/dist --to=3.7 && docgen -i src/index.ts -c docs/index.json -o docs/docs.json --typescript && api-extractor run --local",
"docs": "downlevel-dts dist docs/dist --to=3.7 && api-extractor run --local",
"prepack": "yarn lint && yarn test && yarn build",
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/collection/*'",
"release": "cliff-jumper"
@@ -50,19 +50,19 @@
},
"homepage": "https://discord.js.org",
"devDependencies": {
"@discordjs/docgen": "workspace:^",
"@favware/cliff-jumper": "^1.8.7",
"@microsoft/api-extractor": "^7.31.2",
"@types/node": "^16.11.60",
"@vitest/coverage-c8": "^0.23.4",
"@favware/cliff-jumper": "^1.8.8",
"@microsoft/api-extractor": "^7.32.0",
"@types/node": "^16.11.64",
"@vitest/coverage-c8": "^0.24.0",
"cross-env": "^7.0.3",
"downlevel-dts": "^0.10.1",
"esbuild-plugin-version-injector": "^1.0.0",
"eslint": "^8.24.0",
"eslint-config-neon": "^0.1.33",
"eslint-config-neon": "^0.1.35",
"prettier": "^2.7.1",
"tsup": "^6.2.3",
"typescript": "^4.8.3",
"vitest": "^0.23.4"
"typescript": "^4.8.4",
"vitest": "^0.24.0"
},
"engines": {
"node": ">=16.9.0"

View File

@@ -1 +1,10 @@
export * from './collection.js';
/**
* The [\@discordjs/collection](https://github.com/discordjs/discord.js/blob/main/packages/collection/#readme) version
* that you are currently using.
*
* Note to developers: This needs to explicitly be `string` so it is not typed as a "const string" that gets injected by esbuild
*/
// eslint-disable-next-line @typescript-eslint/no-inferrable-types
export const version: string = '[VI]{{inject}}[/VI]';

View File

@@ -1,3 +1,6 @@
import { esbuildPluginVersionInjector } from 'esbuild-plugin-version-injector';
import { createTsupConfig } from '../../tsup.config.js';
export default createTsupConfig();
export default createTsupConfig({
esbuildPlugins: [esbuildPluginVersionInjector()],
});

View File

@@ -55,24 +55,24 @@
"@discordjs/util": "workspace:^",
"@sapphire/snowflake": "^3.2.2",
"@types/ws": "^8.5.3",
"discord-api-types": "^0.37.11",
"discord-api-types": "^0.37.12",
"fast-deep-equal": "^3.1.3",
"lodash.snakecase": "^4.1.1",
"tslib": "^2.4.0",
"undici": "^5.10.0",
"undici": "^5.11.0",
"ws": "^8.9.0"
},
"devDependencies": {
"@discordjs/docgen": "workspace:^",
"@favware/cliff-jumper": "^1.8.7",
"@types/node": "^16.11.60",
"@favware/cliff-jumper": "^1.8.8",
"@types/node": "^16.11.64",
"dtslint": "^4.2.1",
"eslint": "^8.24.0",
"jest": "^29.0.3",
"jest": "^29.1.2",
"prettier": "^2.7.1",
"tsd": "^0.24.1",
"tslint": "^6.1.3",
"typescript": "^4.8.3"
"typescript": "^4.8.4"
},
"engines": {
"node": ">=16.9.0"

View File

@@ -2,7 +2,7 @@
const EventEmitter = require('node:events');
const { REST } = require('@discordjs/rest');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const Options = require('../util/Options');
const { mergeDefault, flatten } = require('../util/Util');
@@ -15,7 +15,7 @@ class BaseClient extends EventEmitter {
super({ captureRejections: true });
if (typeof options !== 'object' || options === null) {
throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
}
/**

View File

@@ -8,7 +8,7 @@ const BaseClient = require('./BaseClient');
const ActionsManager = require('./actions/ActionsManager');
const ClientVoiceManager = require('./voice/ClientVoiceManager');
const WebSocketManager = require('./websocket/WebSocketManager');
const { Error, TypeError, RangeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, DiscordjsRangeError, ErrorCodes } = require('../errors');
const BaseGuildEmojiManager = require('../managers/BaseGuildEmojiManager');
const ChannelManager = require('../managers/ChannelManager');
const GuildManager = require('../managers/GuildManager');
@@ -211,7 +211,7 @@ class Client extends BaseClient {
* client.login('my token');
*/
async login(token = this.token) {
if (!token || typeof token !== 'string') throw new Error(ErrorCodes.TokenInvalid);
if (!token || typeof token !== 'string') throw new DiscordjsError(ErrorCodes.TokenInvalid);
this.token = token = token.replace(/^(Bot|Bearer)\s*/i, '');
this.rest.setToken(token);
this.emit(
@@ -313,7 +313,7 @@ class Client extends BaseClient {
* .catch(console.error);
*/
async fetchWebhook(id, token) {
const data = await this.rest.get(Routes.webhook(id, token));
const data = await this.rest.get(Routes.webhook(id, token), { auth: typeof token === 'undefined' });
return new Webhook(this, { token, ...data });
}
@@ -366,7 +366,7 @@ class Client extends BaseClient {
*/
async fetchGuildPreview(guild) {
const id = this.guilds.resolveId(guild);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable');
const data = await this.rest.get(Routes.guildPreview(id));
return new GuildPreview(this, data);
}
@@ -378,7 +378,7 @@ class Client extends BaseClient {
*/
async fetchGuildWidget(guild) {
const id = this.guilds.resolveId(guild);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable');
const data = await this.rest.get(Routes.guildWidgetJSON(id));
return new Widget(this, data);
}
@@ -413,23 +413,23 @@ class Client extends BaseClient {
* console.log(`Generated bot invite link: ${link}`);
*/
generateInvite(options = {}) {
if (typeof options !== 'object') throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
if (!this.application) throw new Error(ErrorCodes.ClientNotReady, 'generate an invite link');
if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
if (!this.application) throw new DiscordjsError(ErrorCodes.ClientNotReady, 'generate an invite link');
const { scopes } = options;
if (typeof scopes === 'undefined') {
throw new TypeError(ErrorCodes.InvalidMissingScopes);
throw new DiscordjsTypeError(ErrorCodes.InvalidMissingScopes);
}
if (!Array.isArray(scopes)) {
throw new TypeError(ErrorCodes.InvalidType, 'scopes', 'Array of Invite Scopes', true);
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'scopes', 'Array of Invite Scopes', true);
}
if (!scopes.some(scope => [OAuth2Scopes.Bot, OAuth2Scopes.ApplicationsCommands].includes(scope))) {
throw new TypeError(ErrorCodes.InvalidMissingScopes);
throw new DiscordjsTypeError(ErrorCodes.InvalidMissingScopes);
}
const validScopes = Object.values(OAuth2Scopes);
const invalidScope = scopes.find(scope => !validScopes.includes(scope));
if (invalidScope) {
throw new TypeError(ErrorCodes.InvalidElement, 'Array', 'scopes', invalidScope);
throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'scopes', invalidScope);
}
const query = makeURLSearchParams({
@@ -445,7 +445,7 @@ class Client extends BaseClient {
if (options.guild) {
const guildId = this.guilds.resolveId(options.guild);
if (!guildId) throw new TypeError(ErrorCodes.InvalidType, 'options.guild', 'GuildResolvable');
if (!guildId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options.guild', 'GuildResolvable');
query.set('guild_id', guildId);
}
@@ -477,31 +477,31 @@ class Client extends BaseClient {
*/
_validateOptions(options = this.options) {
if (typeof options.intents === 'undefined') {
throw new TypeError(ErrorCodes.ClientMissingIntents);
throw new DiscordjsTypeError(ErrorCodes.ClientMissingIntents);
} else {
options.intents = IntentsBitField.resolve(options.intents);
}
if (typeof options.shardCount !== 'number' || isNaN(options.shardCount) || options.shardCount < 1) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'shardCount', 'a number greater than or equal to 1');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'shardCount', 'a number greater than or equal to 1');
}
if (options.shards && !(options.shards === 'auto' || Array.isArray(options.shards))) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'shards', "'auto', a number or array of numbers");
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'shards', "'auto', a number or array of numbers");
}
if (options.shards && !options.shards.length) throw new RangeError(ErrorCodes.ClientInvalidProvidedShards);
if (options.shards && !options.shards.length) throw new DiscordjsRangeError(ErrorCodes.ClientInvalidProvidedShards);
if (typeof options.makeCache !== 'function') {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'makeCache', 'a function');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'makeCache', 'a function');
}
if (typeof options.sweepers !== 'object' || options.sweepers === null) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'sweepers', 'an object');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'sweepers', 'an object');
}
if (!Array.isArray(options.partials)) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'partials', 'an Array');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'partials', 'an Array');
}
if (typeof options.waitGuildTimeout !== 'number' || isNaN(options.waitGuildTimeout)) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'waitGuildTimeout', 'a number');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'waitGuildTimeout', 'a number');
}
if (typeof options.failIfNotExists !== 'boolean') {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'failIfNotExists', 'a boolean');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'failIfNotExists', 'a boolean');
}
}
}

View File

@@ -1,7 +1,7 @@
'use strict';
const BaseClient = require('./BaseClient');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const Webhook = require('../structures/Webhook');
const { parseWebhookURL } = require('../util/Util');
@@ -48,7 +48,7 @@ class WebhookClient extends BaseClient {
if ('url' in data) {
const parsed = parseWebhookURL(data.url);
if (!parsed) {
throw new Error(ErrorCodes.WebhookURLInvalid);
throw new DiscordjsError(ErrorCodes.WebhookURLInvalid);
}
({ id, token } = parsed);

View File

@@ -7,7 +7,7 @@ const { Collection } = require('@discordjs/collection');
const { GatewayCloseCodes, GatewayDispatchEvents, Routes } = require('discord-api-types/v10');
const WebSocketShard = require('./WebSocketShard');
const PacketHandlers = require('./handlers');
const { Error, ErrorCodes } = require('../../errors');
const { DiscordjsError, ErrorCodes } = require('../../errors');
const Events = require('../../util/Events');
const Status = require('../../util/Status');
const WebSocketShardEvents = require('../../util/WebSocketShardEvents');
@@ -131,7 +131,7 @@ class WebSocketManager extends EventEmitter {
* @private
*/
async connect() {
const invalidToken = new Error(ErrorCodes.TokenInvalid);
const invalidToken = new DiscordjsError(ErrorCodes.TokenInvalid);
const {
url: gatewayURL,
shards: recommendedShards,
@@ -247,7 +247,7 @@ class WebSocketManager extends EventEmitter {
await shard.connect();
} catch (error) {
if (error?.code && error.code in unrecoverableErrorCodeMap) {
throw new Error(unrecoverableErrorCodeMap[error.code]);
throw new DiscordjsError(unrecoverableErrorCodeMap[error.code]);
// Undefined if session is invalid, error event for regular closes
} else if (!error || error.code) {
this.debug('Failed to connect to the gateway, requeueing...', shard);
@@ -320,7 +320,7 @@ class WebSocketManager extends EventEmitter {
destroy() {
if (this.destroyed) return;
// TODO: Make a util for getting a stack
this.debug(`Manager was destroyed. Called by:\n${new globalThis.Error().stack}`);
this.debug(`Manager was destroyed. Called by:\n${new Error().stack}`);
this.destroyed = true;
this.shardQueue.clear();
for (const shard of this.shards.values()) shard.destroy({ closeCode: 1_000, reset: true, emit: false, log: false });

View File

@@ -42,7 +42,7 @@ function message(code, args) {
}
module.exports = {
Error: makeDiscordjsError(Error),
TypeError: makeDiscordjsError(TypeError),
RangeError: makeDiscordjsError(RangeError),
DiscordjsError: makeDiscordjsError(Error),
DiscordjsTypeError: makeDiscordjsError(TypeError),
DiscordjsRangeError: makeDiscordjsError(RangeError),
};

View File

@@ -11,10 +11,9 @@ exports.ShardingManager = require('./sharding/ShardingManager');
exports.WebhookClient = require('./client/WebhookClient');
// Errors
const { Error, TypeError, RangeError } = require('./errors/DJSError');
exports.DiscordjsError = Error;
exports.DiscordjsTypeError = TypeError;
exports.DiscordjsRangeError = RangeError;
exports.DiscordjsError = require('./errors/DJSError').DiscordjsError;
exports.DiscordjsTypeError = require('./errors/DJSError').DiscordjsTypeError;
exports.DiscordjsRangeError = require('./errors/DJSError').DiscordjsRangeError;
exports.DiscordjsErrorCodes = require('./errors/ErrorCodes');
// Utilities
@@ -187,3 +186,4 @@ exports.WebSocket = require('./WebSocket');
__exportStar(require('discord-api-types/v10'), exports);
__exportStar(require('@discordjs/builders'), exports);
__exportStar(require('@discordjs/rest'), exports);
__exportStar(require('@discordjs/util'), exports);

View File

@@ -6,7 +6,7 @@ const { makeURLSearchParams } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v10');
const ApplicationCommandPermissionsManager = require('./ApplicationCommandPermissionsManager');
const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const ApplicationCommand = require('../structures/ApplicationCommand');
const PermissionsBitField = require('../util/PermissionsBitField');
@@ -193,7 +193,7 @@ class ApplicationCommandManager extends CachedManager {
*/
async edit(command, data, guildId) {
const id = this.resolveId(command);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');
const patched = await this.client.rest.patch(this.commandPath({ id, guildId }), {
body: this.constructor.transformCommand(data),
@@ -215,7 +215,7 @@ class ApplicationCommandManager extends CachedManager {
*/
async delete(command, guildId) {
const id = this.resolveId(command);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');
await this.client.rest.delete(this.commandPath({ id, guildId }));

View File

@@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection');
const { ApplicationCommandPermissionType, RESTJSONErrorCodes, Routes } = require('discord-api-types/v10');
const BaseManager = require('./BaseManager');
const { Error, TypeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');
/**
* Manages API methods for permissions of Application Commands.
@@ -153,12 +153,17 @@ class ApplicationCommandPermissionsManager extends BaseManager {
*/
async set({ guild, command, permissions, token } = {}) {
if (!token) {
throw new Error(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
throw new DiscordjsError(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
}
let { guildId, commandId } = this._validateOptions(guild, command);
if (!Array.isArray(permissions)) {
throw new TypeError(ErrorCodes.InvalidType, 'permissions', 'Array of ApplicationCommandPermissions', true);
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'permissions',
'Array of ApplicationCommandPermissions',
true,
);
}
if (!commandId) {
@@ -190,14 +195,19 @@ class ApplicationCommandPermissionsManager extends BaseManager {
*/
async add({ guild, command, permissions, token } = {}) {
if (!token) {
throw new Error(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
throw new DiscordjsError(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
}
let { guildId, commandId } = this._validateOptions(guild, command);
if (!commandId) {
commandId = this.client.user.id;
}
if (!Array.isArray(permissions)) {
throw new TypeError(ErrorCodes.InvalidType, 'permissions', 'Array of ApplicationCommandPermissions', true);
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'permissions',
'Array of ApplicationCommandPermissions',
true,
);
}
let existing = [];
@@ -262,7 +272,7 @@ class ApplicationCommandPermissionsManager extends BaseManager {
*/
async remove({ guild, command, users, roles, channels, token } = {}) {
if (!token) {
throw new Error(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
throw new DiscordjsError(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
}
let { guildId, commandId } = this._validateOptions(guild, command);
if (!commandId) {
@@ -270,14 +280,14 @@ class ApplicationCommandPermissionsManager extends BaseManager {
}
if (!users && !roles && !channels) {
throw new TypeError(ErrorCodes.InvalidType, 'users OR roles OR channels', 'Array or Resolvable', true);
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'users OR roles OR channels', 'Array or Resolvable', true);
}
let resolvedUserIds = [];
if (Array.isArray(users)) {
for (const user of users) {
const userId = this.client.users.resolveId(user);
if (!userId) throw new TypeError(ErrorCodes.InvalidElement, 'Array', 'users', user);
if (!userId) throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'users', user);
resolvedUserIds.push(userId);
}
}
@@ -289,9 +299,9 @@ class ApplicationCommandPermissionsManager extends BaseManager {
resolvedRoleIds.push(role);
continue;
}
if (!this.guild) throw new Error(ErrorCodes.GuildUncachedEntityResolve, 'roles');
if (!this.guild) throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'roles');
const roleId = this.guild.roles.resolveId(role);
if (!roleId) throw new TypeError(ErrorCodes.InvalidElement, 'Array', 'users', role);
if (!roleId) throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'users', role);
resolvedRoleIds.push(roleId);
}
}
@@ -303,9 +313,9 @@ class ApplicationCommandPermissionsManager extends BaseManager {
resolvedChannelIds.push(channel);
continue;
}
if (!this.guild) throw new Error(ErrorCodes.GuildUncachedEntityResolve, 'channels');
if (!this.guild) throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'channels');
const channelId = this.guild.channels.resolveId(channel);
if (!channelId) throw new TypeError(ErrorCodes.InvalidElement, 'Array', 'channels', channel);
if (!channelId) throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'channels', channel);
resolvedChannelIds.push(channelId);
}
}
@@ -353,10 +363,10 @@ class ApplicationCommandPermissionsManager extends BaseManager {
*/
async has({ guild, command, permissionId, permissionType }) {
const { guildId, commandId } = this._validateOptions(guild, command);
if (!commandId) throw new TypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');
if (!commandId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');
if (!permissionId) {
throw new TypeError(
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'permissionId',
'UserResolvable, RoleResolvable, ChannelResolvable, or Permission Constant',
@@ -366,14 +376,14 @@ class ApplicationCommandPermissionsManager extends BaseManager {
if (typeof permissionId !== 'string') {
resolvedId = this.client.users.resolveId(permissionId);
if (!resolvedId) {
if (!this.guild) throw new Error(ErrorCodes.GuildUncachedEntityResolve, 'roles');
if (!this.guild) throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'roles');
resolvedId = this.guild.roles.resolveId(permissionId);
}
if (!resolvedId) {
resolvedId = this.guild.channels.resolveId(permissionId);
}
if (!resolvedId) {
throw new TypeError(
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'permissionId',
'UserResolvable, RoleResolvable, ChannelResolvable, or Permission Constant',
@@ -394,7 +404,7 @@ class ApplicationCommandPermissionsManager extends BaseManager {
_validateOptions(guild, command) {
const guildId = this.guildId ?? this.client.guilds.resolveId(guild);
if (!guildId) throw new Error(ErrorCodes.GlobalCommandPermissions);
if (!guildId) throw new DiscordjsError(ErrorCodes.GlobalCommandPermissions);
let commandId = this.commandId;
if (command && !commandId) {
commandId = this.manager.resolveId?.(command);
@@ -403,7 +413,7 @@ class ApplicationCommandPermissionsManager extends BaseManager {
}
commandId ??= this.client.application?.commands.resolveId(command);
if (!commandId) {
throw new TypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable', true);
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable', true);
}
}
return { guildId, commandId };

View File

@@ -53,6 +53,8 @@ class CategoryChannelChildManager extends DataManager {
* @property {GuildForumTagData[]} [availableTags] The tags that can be used in this channel (forum only).
* @property {DefaultReactionEmoji} [defaultReactionEmoji]
* The emoji to show in the add reaction button on a thread in a guild forum channel.
* @property {ThreadAutoArchiveDuration} [defaultAutoArchiveDuration]
* The default auto archive duration for all new threads in this channel
* @property {SortOrderType} [defaultSortOrder] The default sort order mode used to order posts (forum only).
* @property {string} [reason] Reason for creating the new channel
*/

View File

@@ -1,7 +1,7 @@
'use strict';
const BaseManager = require('./BaseManager');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
/**
* Manages the API methods of a data model along with a collection of instances.
@@ -28,7 +28,7 @@ class DataManager extends BaseManager {
* @abstract
*/
get cache() {
throw new Error(ErrorCodes.NotImplemented, 'get cache', this.constructor.name);
throw new DiscordjsError(ErrorCodes.NotImplemented, 'get cache', this.constructor.name);
}
/**

View File

@@ -5,7 +5,7 @@ const { Collection } = require('@discordjs/collection');
const { makeURLSearchParams } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, Error, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, DiscordjsError, ErrorCodes } = require('../errors');
const GuildBan = require('../structures/GuildBan');
const { GuildMember } = require('../structures/GuildMember');
@@ -104,7 +104,7 @@ class GuildBanManager extends CachedManager {
if (resolvedUser) return this._fetchSingle({ user: resolvedUser, cache, force });
if (!before && !after && !limit && typeof cache === 'undefined') {
return Promise.reject(new Error(ErrorCodes.FetchBanResolveId));
return Promise.reject(new DiscordjsError(ErrorCodes.FetchBanResolveId));
}
return this._fetchMany(options);
@@ -152,9 +152,9 @@ class GuildBanManager extends CachedManager {
* .catch(console.error);
*/
async create(user, options = {}) {
if (typeof options !== 'object') throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
const id = this.client.users.resolveId(user);
if (!id) throw new Error(ErrorCodes.BanResolveId, true);
if (!id) throw new DiscordjsError(ErrorCodes.BanResolveId, true);
if (typeof options.deleteMessageDays !== 'undefined' && !deprecationEmittedForDeleteMessageDays) {
process.emitWarning(
@@ -195,7 +195,7 @@ class GuildBanManager extends CachedManager {
*/
async remove(user, reason) {
const id = this.client.users.resolveId(user);
if (!id) throw new Error(ErrorCodes.BanResolveId);
if (!id) throw new DiscordjsError(ErrorCodes.BanResolveId);
await this.client.rest.delete(Routes.guildBan(this.guild.id, id), { reason });
return this.client.users.resolve(user);
}

View File

@@ -5,7 +5,7 @@ const { Collection } = require('@discordjs/collection');
const { ChannelType, Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const GuildTextThreadManager = require('./GuildTextThreadManager');
const { Error, TypeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');
const GuildChannel = require('../structures/GuildChannel');
const PermissionOverwrites = require('../structures/PermissionOverwrites');
const ThreadChannel = require('../structures/ThreadChannel');
@@ -141,6 +141,7 @@ class GuildChannelManager extends CachedManager {
videoQualityMode,
availableTags,
defaultReactionEmoji,
defaultAutoArchiveDuration,
defaultSortOrder,
reason,
}) {
@@ -163,6 +164,7 @@ class GuildChannelManager extends CachedManager {
video_quality_mode: videoQualityMode,
available_tags: availableTags?.map(availableTag => transformGuildForumTag(availableTag)),
default_reaction_emoji: defaultReactionEmoji && transformGuildDefaultReaction(defaultReactionEmoji),
default_auto_archive_duration: defaultAutoArchiveDuration,
default_sort_order: defaultSortOrder,
},
reason,
@@ -193,7 +195,7 @@ class GuildChannelManager extends CachedManager {
*/
async createWebhook({ channel, name, avatar, reason }) {
const id = this.resolveId(channel);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
if (typeof avatar === 'string' && !avatar.startsWith('data:')) {
avatar = await DataResolver.resolveImage(avatar);
}
@@ -248,7 +250,7 @@ class GuildChannelManager extends CachedManager {
*/
async edit(channel, data) {
channel = this.resolve(channel);
if (!channel) throw new TypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
if (!channel) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
const parent = data.parent && this.client.channels.resolveId(data.parent);
@@ -314,7 +316,7 @@ class GuildChannelManager extends CachedManager {
*/
async setPosition(channel, position, { relative, reason } = {}) {
channel = this.resolve(channel);
if (!channel) throw new TypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
if (!channel) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
const updatedChannels = await setPosition(
channel,
position,
@@ -357,7 +359,7 @@ class GuildChannelManager extends CachedManager {
if (id) {
const data = await this.client.rest.get(Routes.channel(id));
// Since this is the guild manager, throw if on a different guild
if (this.guild.id !== data.guild_id) throw new Error(ErrorCodes.GuildChannelUnowned);
if (this.guild.id !== data.guild_id) throw new DiscordjsError(ErrorCodes.GuildChannelUnowned);
return this.client.channels._add(data, this.guild, { cache });
}
@@ -379,7 +381,7 @@ class GuildChannelManager extends CachedManager {
*/
async fetchWebhooks(channel) {
const id = this.resolveId(channel);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
const data = await this.client.rest.get(Routes.channelWebhooks(id));
return data.reduce((hooks, hook) => hooks.set(hook.id, new Webhook(this.client, hook)), new Collection());
}
@@ -453,7 +455,7 @@ class GuildChannelManager extends CachedManager {
*/
async delete(channel, reason) {
const id = this.resolveId(channel);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
await this.client.rest.delete(Routes.channel(id), { reason });
this.client.actions.ChannelDelete.handle({ id });
}

View File

@@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection');
const { Routes, PermissionFlagsBits } = require('discord-api-types/v10');
const BaseGuildEmojiManager = require('./BaseGuildEmojiManager');
const { Error, TypeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');
const DataResolver = require('../util/DataResolver');
/**
@@ -51,12 +51,12 @@ class GuildEmojiManager extends BaseGuildEmojiManager {
*/
async create({ attachment, name, roles, reason }) {
attachment = await DataResolver.resolveImage(attachment);
if (!attachment) throw new TypeError(ErrorCodes.ReqResourceType);
if (!attachment) throw new DiscordjsTypeError(ErrorCodes.ReqResourceType);
const body = { image: attachment, name };
if (roles) {
if (!Array.isArray(roles) && !(roles instanceof Collection)) {
throw new TypeError(
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'options.roles',
'Array or Collection of Roles or Snowflakes',
@@ -67,7 +67,7 @@ class GuildEmojiManager extends BaseGuildEmojiManager {
for (const role of roles.values()) {
const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) {
throw new TypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'options.roles', role);
throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'options.roles', role);
}
body.roles.push(resolvedRole);
}
@@ -117,7 +117,7 @@ class GuildEmojiManager extends BaseGuildEmojiManager {
*/
async delete(emoji, reason) {
const id = this.resolveId(emoji);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true);
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true);
await this.client.rest.delete(Routes.guildEmoji(this.guild.id, id), { reason });
}
@@ -129,7 +129,7 @@ class GuildEmojiManager extends BaseGuildEmojiManager {
*/
async edit(emoji, data) {
const id = this.resolveId(emoji);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true);
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true);
const roles = data.roles?.map(r => this.guild.roles.resolveId(r));
const newData = await this.client.rest.patch(Routes.guildEmoji(this.guild.id, id), {
body: {
@@ -154,15 +154,15 @@ class GuildEmojiManager extends BaseGuildEmojiManager {
*/
async fetchAuthor(emoji) {
emoji = this.resolve(emoji);
if (!emoji) throw new TypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true);
if (!emoji) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true);
if (emoji.managed) {
throw new Error(ErrorCodes.EmojiManaged);
throw new DiscordjsError(ErrorCodes.EmojiManaged);
}
const { me } = this.guild.members;
if (!me) throw new Error(ErrorCodes.GuildUncachedMe);
if (!me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe);
if (!me.permissions.has(PermissionFlagsBits.ManageEmojisAndStickers)) {
throw new Error(ErrorCodes.MissingManageEmojisAndStickersPermission, this.guild);
throw new DiscordjsError(ErrorCodes.MissingManageEmojisAndStickersPermission, this.guild);
}
const data = await this.client.rest.get(Routes.guildEmoji(this.guild.id, emoji.id));

View File

@@ -2,7 +2,7 @@
const { Collection } = require('@discordjs/collection');
const DataManager = require('./DataManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const { Role } = require('../structures/Role');
/**
@@ -46,7 +46,7 @@ class GuildEmojiRoleManager extends DataManager {
for (const role of roleOrRoles.values()) {
const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) {
return Promise.reject(new TypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role));
return Promise.reject(new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role));
}
resolvedRoles.push(resolvedRole);
}
@@ -67,7 +67,7 @@ class GuildEmojiRoleManager extends DataManager {
for (const role of roleOrRoles.values()) {
const roleId = this.guild.roles.resolveId(role);
if (!roleId) {
return Promise.reject(new TypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role));
return Promise.reject(new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role));
}
resolvedRoleIds.push(roleId);
}

View File

@@ -2,7 +2,7 @@
const { Routes } = require('discord-api-types/v10');
const ThreadManager = require('./ThreadManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const MessagePayload = require('../structures/MessagePayload');
/**
@@ -56,7 +56,7 @@ class GuildForumThreadManager extends ThreadManager {
appliedTags,
} = {}) {
if (!message) {
throw new TypeError(ErrorCodes.GuildForumMessageRequired);
throw new DiscordjsTypeError(ErrorCodes.GuildForumMessageRequired);
}
const { body, files } = await (message instanceof MessagePayload ? message : MessagePayload.create(this, message))

View File

@@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection');
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const Invite = require('../structures/Invite');
const DataResolver = require('../util/DataResolver');
@@ -123,18 +123,18 @@ class GuildInviteManager extends CachedManager {
if (!options) return this._fetchMany();
if (typeof options === 'string') {
const code = DataResolver.resolveInviteCode(options);
if (!code) return Promise.reject(new Error(ErrorCodes.InviteResolveCode));
if (!code) return Promise.reject(new DiscordjsError(ErrorCodes.InviteResolveCode));
return this._fetchSingle({ code, cache: true });
}
if (!options.code) {
if (options.channelId) {
const id = this.guild.channels.resolveId(options.channelId);
if (!id) return Promise.reject(new Error(ErrorCodes.GuildChannelResolve));
if (!id) return Promise.reject(new DiscordjsError(ErrorCodes.GuildChannelResolve));
return this._fetchChannelMany(id, options.cache);
}
if ('cache' in options) return this._fetchMany(options.cache);
return Promise.reject(new Error(ErrorCodes.InviteResolveCode));
return Promise.reject(new DiscordjsError(ErrorCodes.InviteResolveCode));
}
return this._fetchSingle({
...options,
@@ -150,7 +150,7 @@ class GuildInviteManager extends CachedManager {
const invites = await this._fetchMany(cache);
const invite = invites.get(code);
if (!invite) throw new Error(ErrorCodes.InviteNotFound);
if (!invite) throw new DiscordjsError(ErrorCodes.InviteNotFound);
return invite;
}
@@ -180,7 +180,7 @@ class GuildInviteManager extends CachedManager {
{ temporary, maxAge, maxUses, unique, targetUser, targetApplication, targetType, reason } = {},
) {
const id = this.guild.channels.resolveId(channel);
if (!id) throw new Error(ErrorCodes.GuildChannelResolve);
if (!id) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
const invite = await this.client.rest.post(Routes.channelInvites(id), {
body: {

View File

@@ -6,7 +6,7 @@ const { makeURLSearchParams } = require('@discordjs/rest');
const { DiscordSnowflake } = require('@sapphire/snowflake');
const { Routes, GatewayOpcodes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { Error, TypeError, RangeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, DiscordjsRangeError, ErrorCodes } = require('../errors');
const BaseGuildVoiceChannel = require('../structures/BaseGuildVoiceChannel');
const { GuildMember } = require('../structures/GuildMember');
const { Role } = require('../structures/Role');
@@ -96,7 +96,7 @@ class GuildMemberManager extends CachedManager {
*/
async add(user, options) {
const userId = this.client.users.resolveId(user);
if (!userId) throw new TypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable');
if (!userId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable');
if (!options.force) {
const cachedUser = this.cache.get(userId);
if (cachedUser) return cachedUser;
@@ -109,7 +109,7 @@ class GuildMemberManager extends CachedManager {
};
if (options.roles) {
if (!Array.isArray(options.roles) && !(options.roles instanceof Collection)) {
throw new TypeError(
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'options.roles',
'Array or Collection of Roles or Snowflakes',
@@ -120,7 +120,7 @@ class GuildMemberManager extends CachedManager {
for (const role of options.roles.values()) {
const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) {
throw new TypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'options.roles', role);
throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'options.roles', role);
}
resolvedRoles.push(resolvedRole);
}
@@ -291,12 +291,12 @@ class GuildMemberManager extends CachedManager {
*/
async edit(user, { reason, ...data }) {
const id = this.client.users.resolveId(user);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable');
if (data.channel) {
data.channel = this.guild.channels.resolve(data.channel);
if (!(data.channel instanceof BaseGuildVoiceChannel)) {
throw new Error(ErrorCodes.GuildVoiceChannelResolve);
throw new DiscordjsError(ErrorCodes.GuildVoiceChannelResolve);
}
data.channel_id = data.channel.id;
data.channel = undefined;
@@ -362,7 +362,7 @@ class GuildMemberManager extends CachedManager {
* .catch(console.error);
*/
async prune({ days, dry = false, count: compute_prune_count, roles = [], reason } = {}) {
if (typeof days !== 'number') throw new TypeError(ErrorCodes.PruneDaysType);
if (typeof days !== 'number') throw new DiscordjsTypeError(ErrorCodes.PruneDaysType);
const query = { days };
const resolvedRoles = [];
@@ -370,7 +370,7 @@ class GuildMemberManager extends CachedManager {
for (const role of roles) {
const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) {
throw new TypeError(ErrorCodes.InvalidElement, 'Array', 'options.roles', role);
throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'options.roles', role);
}
resolvedRoles.push(resolvedRole);
}
@@ -404,7 +404,7 @@ class GuildMemberManager extends CachedManager {
*/
async kick(user, reason) {
const id = this.client.users.resolveId(user);
if (!id) return Promise.reject(new TypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable'));
if (!id) return Promise.reject(new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable'));
await this.client.rest.delete(Routes.guildMember(this.guild.id, id), { reason });
@@ -500,7 +500,7 @@ class GuildMemberManager extends CachedManager {
} = {}) {
return new Promise((resolve, reject) => {
if (!query && !user_ids) query = '';
if (nonce.length > 32) throw new RangeError(ErrorCodes.MemberFetchNonceLength);
if (nonce.length > 32) throw new DiscordjsRangeError(ErrorCodes.MemberFetchNonceLength);
this.guild.shard.send({
op: GatewayOpcodes.RequestGuildMembers,
d: {
@@ -533,7 +533,7 @@ class GuildMemberManager extends CachedManager {
const timeout = setTimeout(() => {
this.client.removeListener(Events.GuildMembersChunk, handler);
this.client.decrementMaxListeners();
reject(new Error(ErrorCodes.GuildMembersTimeout));
reject(new DiscordjsError(ErrorCodes.GuildMembersTimeout));
}, time).unref();
this.client.incrementMaxListeners();
this.client.on(Events.GuildMembersChunk, handler);

View File

@@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection');
const { Routes } = require('discord-api-types/v10');
const DataManager = require('./DataManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const { Role } = require('../structures/Role');
/**
@@ -110,7 +110,9 @@ class GuildMemberRoleManager extends DataManager {
const resolvedRoles = [];
for (const role of roleOrRoles.values()) {
const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) throw new TypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role);
if (!resolvedRole) {
throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role);
}
resolvedRoles.push(resolvedRole);
}
@@ -119,7 +121,7 @@ class GuildMemberRoleManager extends DataManager {
} else {
roleOrRoles = this.guild.roles.resolveId(roleOrRoles);
if (roleOrRoles === null) {
throw new TypeError(
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'roles',
'Role, Snowflake or Array or Collection of Roles or Snowflakes',
@@ -145,7 +147,9 @@ class GuildMemberRoleManager extends DataManager {
const resolvedRoles = [];
for (const role of roleOrRoles.values()) {
const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) throw new TypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role);
if (!resolvedRole) {
throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role);
}
resolvedRoles.push(resolvedRole);
}
@@ -154,7 +158,7 @@ class GuildMemberRoleManager extends DataManager {
} else {
roleOrRoles = this.guild.roles.resolveId(roleOrRoles);
if (roleOrRoles === null) {
throw new TypeError(
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'roles',
'Role, Snowflake or Array or Collection of Roles or Snowflakes',

View File

@@ -4,7 +4,7 @@ const { Collection } = require('@discordjs/collection');
const { makeURLSearchParams } = require('@discordjs/rest');
const { GuildScheduledEventEntityType, Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, Error, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, DiscordjsError, ErrorCodes } = require('../errors');
const { GuildScheduledEvent } = require('../structures/GuildScheduledEvent');
const DataResolver = require('../util/DataResolver');
@@ -69,7 +69,7 @@ class GuildScheduledEventManager extends CachedManager {
* @returns {Promise<GuildScheduledEvent>}
*/
async create(options) {
if (typeof options !== 'object') throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
let {
privacyLevel,
entityType,
@@ -89,7 +89,7 @@ class GuildScheduledEventManager extends CachedManager {
entity_metadata = { location: entityMetadata?.location };
} else {
channel_id = this.guild.channels.resolveId(channel);
if (!channel_id) throw new Error(ErrorCodes.GuildVoiceChannelResolve);
if (!channel_id) throw new DiscordjsError(ErrorCodes.GuildVoiceChannelResolve);
entity_metadata = typeof entityMetadata === 'undefined' ? entityMetadata : null;
}
@@ -188,9 +188,9 @@ class GuildScheduledEventManager extends CachedManager {
*/
async edit(guildScheduledEvent, options) {
const guildScheduledEventId = this.resolveId(guildScheduledEvent);
if (!guildScheduledEventId) throw new Error(ErrorCodes.GuildScheduledEventResolve);
if (!guildScheduledEventId) throw new DiscordjsError(ErrorCodes.GuildScheduledEventResolve);
if (typeof options !== 'object') throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
let {
privacyLevel,
entityType,
@@ -238,7 +238,7 @@ class GuildScheduledEventManager extends CachedManager {
*/
async delete(guildScheduledEvent) {
const guildScheduledEventId = this.resolveId(guildScheduledEvent);
if (!guildScheduledEventId) throw new Error(ErrorCodes.GuildScheduledEventResolve);
if (!guildScheduledEventId) throw new DiscordjsError(ErrorCodes.GuildScheduledEventResolve);
await this.client.rest.delete(Routes.guildScheduledEvent(this.guild.id, guildScheduledEventId));
}
@@ -269,7 +269,7 @@ class GuildScheduledEventManager extends CachedManager {
*/
async fetchSubscribers(guildScheduledEvent, options = {}) {
const guildScheduledEventId = this.resolveId(guildScheduledEvent);
if (!guildScheduledEventId) throw new Error(ErrorCodes.GuildScheduledEventResolve);
if (!guildScheduledEventId) throw new DiscordjsError(ErrorCodes.GuildScheduledEventResolve);
const query = makeURLSearchParams({
limit: options.limit,

View File

@@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection');
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const MessagePayload = require('../structures/MessagePayload');
const { Sticker } = require('../structures/Sticker');
@@ -59,7 +59,7 @@ class GuildStickerManager extends CachedManager {
*/
async create({ file, name, tags, description, reason } = {}) {
const resolvedFile = await MessagePayload.resolveFile(file);
if (!resolvedFile) throw new TypeError(ErrorCodes.ReqResourceType);
if (!resolvedFile) throw new DiscordjsTypeError(ErrorCodes.ReqResourceType);
file = { ...resolvedFile, key: 'file' };
const body = { name, tags, description: description ?? '' };
@@ -106,7 +106,7 @@ class GuildStickerManager extends CachedManager {
*/
async edit(sticker, data = {}) {
const stickerId = this.resolveId(sticker);
if (!stickerId) throw new TypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
if (!stickerId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
const d = await this.client.rest.patch(Routes.guildSticker(this.guild.id, stickerId), {
body: data,
@@ -130,7 +130,7 @@ class GuildStickerManager extends CachedManager {
*/
async delete(sticker, reason) {
sticker = this.resolveId(sticker);
if (!sticker) throw new TypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
if (!sticker) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
await this.client.rest.delete(Routes.guildSticker(this.guild.id, sticker), { reason });
}
@@ -172,7 +172,7 @@ class GuildStickerManager extends CachedManager {
*/
async fetchUser(sticker) {
sticker = this.resolve(sticker);
if (!sticker) throw new TypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
if (!sticker) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
const data = await this.client.rest.get(Routes.guildSticker(this.guild.id, sticker.id));
sticker._patch(data);
return sticker.user;

View File

@@ -2,7 +2,7 @@
const { ChannelType, Routes } = require('discord-api-types/v10');
const ThreadManager = require('./ThreadManager');
const { ErrorCodes, TypeError } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
/**
* Manages API methods for {@link ThreadChannel} objects and stores their cache.
@@ -68,7 +68,7 @@ class GuildTextThreadManager extends ThreadManager {
let startMessageId;
if (startMessage) {
startMessageId = this.channel.messages.resolveId(startMessage);
if (!startMessageId) throw new TypeError(ErrorCodes.InvalidType, 'startMessage', 'MessageResolvable');
if (!startMessageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'startMessage', 'MessageResolvable');
} else if (this.channel.type !== ChannelType.GuildAnnouncement) {
resolvedType = type ?? resolvedType;
}

View File

@@ -4,7 +4,7 @@ const { Collection } = require('@discordjs/collection');
const { makeURLSearchParams } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const { Message } = require('../structures/Message');
const MessagePayload = require('../structures/MessagePayload');
const { resolvePartialEmoji } = require('../util/Util');
@@ -164,7 +164,7 @@ class MessageManager extends CachedManager {
*/
async edit(message, options) {
const messageId = this.resolveId(message);
if (!messageId) throw new TypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
if (!messageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
const { body, files } = await (options instanceof MessagePayload
? options
@@ -190,7 +190,7 @@ class MessageManager extends CachedManager {
*/
async crosspost(message) {
message = this.resolveId(message);
if (!message) throw new TypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
const data = await this.client.rest.post(Routes.channelMessageCrosspost(this.channel.id, message));
return this.cache.get(data.id) ?? this._add(data);
@@ -204,7 +204,7 @@ class MessageManager extends CachedManager {
*/
async pin(message, reason) {
message = this.resolveId(message);
if (!message) throw new TypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
await this.client.rest.put(Routes.channelPin(this.channel.id, message), { reason });
}
@@ -217,7 +217,7 @@ class MessageManager extends CachedManager {
*/
async unpin(message, reason) {
message = this.resolveId(message);
if (!message) throw new TypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
await this.client.rest.delete(Routes.channelPin(this.channel.id, message), { reason });
}
@@ -230,10 +230,10 @@ class MessageManager extends CachedManager {
*/
async react(message, emoji) {
message = this.resolveId(message);
if (!message) throw new TypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
emoji = resolvePartialEmoji(emoji);
if (!emoji) throw new TypeError(ErrorCodes.EmojiType, 'emoji', 'EmojiIdentifierResolvable');
if (!emoji) throw new DiscordjsTypeError(ErrorCodes.EmojiType, 'emoji', 'EmojiIdentifierResolvable');
const emojiId = emoji.id
? `${emoji.animated ? 'a:' : ''}${emoji.name}:${emoji.id}`
@@ -249,7 +249,7 @@ class MessageManager extends CachedManager {
*/
async delete(message) {
message = this.resolveId(message);
if (!message) throw new TypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
await this.client.rest.delete(Routes.channelMessage(this.channel.id, message));
}

View File

@@ -4,7 +4,7 @@ const process = require('node:process');
const { Collection } = require('@discordjs/collection');
const { OverwriteType, Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const PermissionOverwrites = require('../structures/PermissionOverwrites');
const { Role } = require('../structures/Role');
@@ -65,7 +65,12 @@ class PermissionOverwriteManager extends CachedManager {
set(overwrites, reason) {
if (!Array.isArray(overwrites) && !(overwrites instanceof Collection)) {
return Promise.reject(
new TypeError(ErrorCodes.InvalidType, 'overwrites', 'Array or Collection of Permission Overwrites', true),
new DiscordjsTypeError(
ErrorCodes.InvalidType,
'overwrites',
'Array or Collection of Permission Overwrites',
true,
),
);
}
return this.channel.edit({ permissionOverwrites: overwrites, reason });
@@ -93,7 +98,7 @@ class PermissionOverwriteManager extends CachedManager {
let { type, reason } = overwriteOptions;
if (typeof type !== 'number') {
userOrRole = this.channel.guild.roles.resolve(userOrRole) ?? this.client.users.resolve(userOrRole);
if (!userOrRole) throw new TypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role');
if (!userOrRole) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role');
type = userOrRole instanceof Role ? OverwriteType.Role : OverwriteType.Member;
}
@@ -153,7 +158,7 @@ class PermissionOverwriteManager extends CachedManager {
*/
async delete(userOrRole, reason) {
const userOrRoleId = this.channel.guild.roles.resolveId(userOrRole) ?? this.client.users.resolveId(userOrRole);
if (!userOrRoleId) throw new TypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role');
if (!userOrRoleId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role');
await this.client.rest.delete(Routes.channelPermission(this.channel.id, userOrRoleId), { reason });
return this.channel;

View File

@@ -4,7 +4,7 @@ const { Collection } = require('@discordjs/collection');
const { makeURLSearchParams } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const User = require('../structures/User');
/**
@@ -63,7 +63,7 @@ class ReactionUserManager extends CachedManager {
*/
async remove(user = this.client.user) {
const userId = this.client.users.resolveId(user);
if (!userId) throw new Error(ErrorCodes.ReactionResolveUser);
if (!userId) throw new DiscordjsError(ErrorCodes.ReactionResolveUser);
const message = this.reaction.message;
const route =
userId === this.client.user.id

View File

@@ -4,7 +4,7 @@ const process = require('node:process');
const { Collection } = require('@discordjs/collection');
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const { Role } = require('../structures/Role');
const DataResolver = require('../util/DataResolver');
const PermissionsBitField = require('../util/PermissionsBitField');
@@ -183,7 +183,7 @@ class RoleManager extends CachedManager {
*/
async edit(role, data) {
role = this.resolve(role);
if (!role) throw new TypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable');
if (!role) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable');
if (typeof data.position === 'number') {
await this.setPosition(role, data.position, { reason: data.reason });
@@ -244,7 +244,7 @@ class RoleManager extends CachedManager {
*/
async setPosition(role, position, { relative, reason } = {}) {
role = this.resolve(role);
if (!role) throw new TypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable');
if (!role) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable');
const updatedRoles = await setPosition(
role,
position,
@@ -303,7 +303,9 @@ class RoleManager extends CachedManager {
comparePositions(role1, role2) {
const resolvedRole1 = this.resolve(role1);
const resolvedRole2 = this.resolve(role2);
if (!resolvedRole1 || !resolvedRole2) throw new TypeError(ErrorCodes.InvalidType, 'role', 'Role nor a Snowflake');
if (!resolvedRole1 || !resolvedRole2) {
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'Role nor a Snowflake');
}
if (resolvedRole1.position === resolvedRole2.position) {
return Number(BigInt(resolvedRole2.id) - BigInt(resolvedRole1.id));

View File

@@ -2,7 +2,7 @@
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, Error, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, DiscordjsError, ErrorCodes } = require('../errors');
const { StageInstance } = require('../structures/StageInstance');
/**
@@ -57,8 +57,8 @@ class StageInstanceManager extends CachedManager {
*/
async create(channel, options) {
const channelId = this.guild.channels.resolveId(channel);
if (!channelId) throw new Error(ErrorCodes.StageChannelResolve);
if (typeof options !== 'object') throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
if (!channelId) throw new DiscordjsError(ErrorCodes.StageChannelResolve);
if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
let { topic, privacyLevel, sendStartNotification } = options;
const data = await this.client.rest.post(Routes.stageInstances(), {
@@ -86,7 +86,7 @@ class StageInstanceManager extends CachedManager {
*/
async fetch(channel, { cache = true, force = false } = {}) {
const channelId = this.guild.channels.resolveId(channel);
if (!channelId) throw new Error(ErrorCodes.StageChannelResolve);
if (!channelId) throw new DiscordjsError(ErrorCodes.StageChannelResolve);
if (!force) {
const existing = this.cache.find(stageInstance => stageInstance.channelId === channelId);
@@ -116,9 +116,9 @@ class StageInstanceManager extends CachedManager {
* .catch(console.error);
*/
async edit(channel, options) {
if (typeof options !== 'object') throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
const channelId = this.guild.channels.resolveId(channel);
if (!channelId) throw new Error(ErrorCodes.StageChannelResolve);
if (!channelId) throw new DiscordjsError(ErrorCodes.StageChannelResolve);
let { topic, privacyLevel } = options;
@@ -145,7 +145,7 @@ class StageInstanceManager extends CachedManager {
*/
async delete(channel) {
const channelId = this.guild.channels.resolveId(channel);
if (!channelId) throw new Error(ErrorCodes.StageChannelResolve);
if (!channelId) throw new DiscordjsError(ErrorCodes.StageChannelResolve);
await this.client.rest.delete(Routes.stageInstance(channelId));
}

View File

@@ -4,7 +4,7 @@ const { Collection } = require('@discordjs/collection');
const { makeURLSearchParams } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const ThreadChannel = require('../structures/ThreadChannel');
/**
@@ -162,7 +162,7 @@ class ThreadManager extends CachedManager {
query.set('before', timestamp);
}
} catch {
throw new TypeError(ErrorCodes.InvalidType, 'before', 'DateResolvable or ThreadChannelResolvable');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'before', 'DateResolvable or ThreadChannelResolvable');
}
}
}

View File

@@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection');
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const ThreadMember = require('../structures/ThreadMember');
/**
@@ -95,7 +95,7 @@ class ThreadMemberManager extends CachedManager {
*/
async add(member, reason) {
const id = member === '@me' ? member : this.client.users.resolveId(member);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'member', 'UserResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'member', 'UserResolvable');
await this.client.rest.put(Routes.threadMembers(this.thread.id, id), { reason });
return id;
}

View File

@@ -2,7 +2,7 @@
const { ChannelType, Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const { GuildMember } = require('../structures/GuildMember');
const { Message } = require('../structures/Message');
const ThreadMember = require('../structures/ThreadMember');
@@ -69,7 +69,7 @@ class UserManager extends CachedManager {
async deleteDM(user) {
const id = this.resolveId(user);
const dmChannel = this.dmChannel(id);
if (!dmChannel) throw new Error(ErrorCodes.UserNoDMChannel);
if (!dmChannel) throw new DiscordjsError(ErrorCodes.UserNoDMChannel);
await this.client.rest.delete(Routes.channel(dmChannel.id));
this.client.channels._remove(dmChannel.id);
return dmChannel;

View File

@@ -5,7 +5,7 @@ const path = require('node:path');
const process = require('node:process');
const { setTimeout, clearTimeout } = require('node:timers');
const { setTimeout: sleep } = require('node:timers/promises');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const ShardEvents = require('../util/ShardEvents');
const { makeError, makePlainError } = require('../util/Util');
let childProcess = null;
@@ -107,8 +107,8 @@ class Shard extends EventEmitter {
* @returns {Promise<ChildProcess>}
*/
spawn(timeout = 30_000) {
if (this.process) throw new Error(ErrorCodes.ShardingProcessExists, this.id);
if (this.worker) throw new Error(ErrorCodes.ShardingWorkerExists, this.id);
if (this.process) throw new DiscordjsError(ErrorCodes.ShardingProcessExists, this.id);
if (this.worker) throw new DiscordjsError(ErrorCodes.ShardingWorkerExists, this.id);
this._exitListener = this._handleExit.bind(this, undefined, timeout);
@@ -154,17 +154,17 @@ class Shard extends EventEmitter {
const onDisconnect = () => {
cleanup();
reject(new Error(ErrorCodes.ShardingReadyDisconnected, this.id));
reject(new DiscordjsError(ErrorCodes.ShardingReadyDisconnected, this.id));
};
const onDeath = () => {
cleanup();
reject(new Error(ErrorCodes.ShardingReadyDied, this.id));
reject(new DiscordjsError(ErrorCodes.ShardingReadyDied, this.id));
};
const onTimeout = () => {
cleanup();
reject(new Error(ErrorCodes.ShardingReadyTimeout, this.id));
reject(new DiscordjsError(ErrorCodes.ShardingReadyTimeout, this.id));
};
const spawnTimeoutTimer = setTimeout(onTimeout, timeout);
@@ -239,7 +239,9 @@ class Shard extends EventEmitter {
*/
fetchClientValue(prop) {
// Shard is dead (maybe respawning), don't cache anything and error immediately
if (!this.process && !this.worker) return Promise.reject(new Error(ErrorCodes.ShardingNoChildExists, this.id));
if (!this.process && !this.worker) {
return Promise.reject(new DiscordjsError(ErrorCodes.ShardingNoChildExists, this.id));
}
// Cached promise from previous call
if (this._fetches.has(prop)) return this._fetches.get(prop);
@@ -282,7 +284,9 @@ class Shard extends EventEmitter {
const _eval = typeof script === 'function' ? `(${script})(this, ${JSON.stringify(context)})` : script;
// Shard is dead (maybe respawning), don't cache anything and error immediately
if (!this.process && !this.worker) return Promise.reject(new Error(ErrorCodes.ShardingNoChildExists, this.id));
if (!this.process && !this.worker) {
return Promise.reject(new DiscordjsError(ErrorCodes.ShardingNoChildExists, this.id));
}
// Cached promise from previous call
if (this._evals.has(_eval)) return this._evals.get(_eval);

View File

@@ -1,7 +1,7 @@
'use strict';
const process = require('node:process');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');
const Events = require('../util/Events');
const { makeError, makePlainError } = require('../util/Util');
@@ -141,7 +141,7 @@ class ShardClientUtil {
return new Promise((resolve, reject) => {
const parent = this.parentPort ?? process;
if (typeof script !== 'function') {
reject(new TypeError(ErrorCodes.ShardingInvalidEvalBroadcast));
reject(new DiscordjsTypeError(ErrorCodes.ShardingInvalidEvalBroadcast));
return;
}
script = `(${script})(this, ${JSON.stringify(options.context)})`;
@@ -206,7 +206,7 @@ class ShardClientUtil {
*/
_respond(type, message) {
this.send(message).catch(err => {
const error = new globalThis.Error(`Error when sending ${type} response to master process: ${err.message}`);
const error = new Error(`Error when sending ${type} response to master process: ${err.message}`);
error.stack = err.stack;
/**
* Emitted when the client encounters an error.
@@ -246,7 +246,7 @@ class ShardClientUtil {
*/
static shardIdForGuildId(guildId, shardCount) {
const shard = Number(BigInt(guildId) >> 22n) % shardCount;
if (shard < 0) throw new Error(ErrorCodes.ShardingShardMiscalculation, shard, guildId, shardCount);
if (shard < 0) throw new DiscordjsError(ErrorCodes.ShardingShardMiscalculation, shard, guildId, shardCount);
return shard;
}

View File

@@ -7,7 +7,7 @@ const process = require('node:process');
const { setTimeout: sleep } = require('node:timers/promises');
const { Collection } = require('@discordjs/collection');
const Shard = require('./Shard');
const { Error, TypeError, RangeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, DiscordjsRangeError, ErrorCodes } = require('../errors');
const { mergeDefault, fetchRecommendedShardCount } = require('../util/Util');
/**
@@ -64,10 +64,10 @@ class ShardingManager extends EventEmitter {
* @type {string}
*/
this.file = file;
if (!file) throw new Error(ErrorCodes.ClientInvalidOption, 'File', 'specified.');
if (!file) throw new DiscordjsError(ErrorCodes.ClientInvalidOption, 'File', 'specified.');
if (!path.isAbsolute(file)) this.file = path.resolve(process.cwd(), file);
const stats = fs.statSync(this.file);
if (!stats.isFile()) throw new Error(ErrorCodes.ClientInvalidOption, 'File', 'a file');
if (!stats.isFile()) throw new DiscordjsError(ErrorCodes.ClientInvalidOption, 'File', 'a file');
/**
* List of shards this sharding manager spawns
@@ -76,18 +76,18 @@ class ShardingManager extends EventEmitter {
this.shardList = options.shardList ?? 'auto';
if (this.shardList !== 'auto') {
if (!Array.isArray(this.shardList)) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'shardList', 'an array.');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'shardList', 'an array.');
}
this.shardList = [...new Set(this.shardList)];
if (this.shardList.length < 1) {
throw new RangeError(ErrorCodes.ClientInvalidOption, 'shardList', 'at least 1 id.');
throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'shardList', 'at least 1 id.');
}
if (
this.shardList.some(
shardId => typeof shardId !== 'number' || isNaN(shardId) || !Number.isInteger(shardId) || shardId < 0,
)
) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'shardList', 'an array of positive integers.');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'shardList', 'an array of positive integers.');
}
}
@@ -98,13 +98,13 @@ class ShardingManager extends EventEmitter {
this.totalShards = options.totalShards || 'auto';
if (this.totalShards !== 'auto') {
if (typeof this.totalShards !== 'number' || isNaN(this.totalShards)) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'a number.');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'a number.');
}
if (this.totalShards < 1) {
throw new RangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'at least 1.');
throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'at least 1.');
}
if (!Number.isInteger(this.totalShards)) {
throw new RangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'an integer.');
throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'an integer.');
}
}
@@ -114,7 +114,7 @@ class ShardingManager extends EventEmitter {
*/
this.mode = options.mode;
if (this.mode !== 'process' && this.mode !== 'worker') {
throw new RangeError(ErrorCodes.ClientInvalidOption, 'Sharding mode', '"process" or "worker"');
throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'Sharding mode', '"process" or "worker"');
}
/**
@@ -190,16 +190,16 @@ class ShardingManager extends EventEmitter {
amount = await fetchRecommendedShardCount(this.token);
} else {
if (typeof amount !== 'number' || isNaN(amount)) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'a number.');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'a number.');
}
if (amount < 1) throw new RangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'at least 1.');
if (amount < 1) throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'at least 1.');
if (!Number.isInteger(amount)) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'an integer.');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'an integer.');
}
}
// Make sure this many shards haven't already been spawned
if (this.shards.size >= amount) throw new Error(ErrorCodes.ShardingAlreadySpawned, this.shards.size);
if (this.shards.size >= amount) throw new DiscordjsError(ErrorCodes.ShardingAlreadySpawned, this.shards.size);
if (this.shardList === 'auto' || this.totalShards === 'auto' || this.totalShards !== amount) {
this.shardList = [...Array(amount).keys()];
}
@@ -208,7 +208,7 @@ class ShardingManager extends EventEmitter {
}
if (this.shardList.some(shardId => shardId >= amount)) {
throw new RangeError(
throw new DiscordjsRangeError(
ErrorCodes.ClientInvalidOption,
'Amount of shards',
'bigger than the highest shardId in the shardList option.',
@@ -252,7 +252,9 @@ class ShardingManager extends EventEmitter {
* @returns {Promise<*|Array<*>>} Results of the script execution
*/
broadcastEval(script, options = {}) {
if (typeof script !== 'function') return Promise.reject(new TypeError(ErrorCodes.ShardingInvalidEvalBroadcast));
if (typeof script !== 'function') {
return Promise.reject(new DiscordjsTypeError(ErrorCodes.ShardingInvalidEvalBroadcast));
}
return this._performOnShards('eval', [`(${script})(this, ${JSON.stringify(options.context)})`], options.shard);
}
@@ -279,14 +281,16 @@ class ShardingManager extends EventEmitter {
* @private
*/
_performOnShards(method, args, shard) {
if (this.shards.size === 0) return Promise.reject(new Error(ErrorCodes.ShardingNoShards));
if (this.shards.size === 0) return Promise.reject(new DiscordjsError(ErrorCodes.ShardingNoShards));
if (typeof shard === 'number') {
if (this.shards.has(shard)) return this.shards.get(shard)[method](...args);
return Promise.reject(new Error(ErrorCodes.ShardingShardNotFound, shard));
return Promise.reject(new DiscordjsError(ErrorCodes.ShardingShardNotFound, shard));
}
if (this.shards.size !== this.shardList.length) return Promise.reject(new Error(ErrorCodes.ShardingInProcess));
if (this.shards.size !== this.shardList.length) {
return Promise.reject(new DiscordjsError(ErrorCodes.ShardingInProcess));
}
const promises = [];
for (const sh of this.shards.values()) promises.push(sh[method](...args));

View File

@@ -3,7 +3,7 @@
const { InteractionResponseType, Routes } = require('discord-api-types/v10');
const BaseInteraction = require('./BaseInteraction');
const CommandInteractionOptionResolver = require('./CommandInteractionOptionResolver');
const { ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
/**
* Represents an autocomplete interaction.
@@ -81,7 +81,7 @@ class AutocompleteInteraction extends BaseInteraction {
* .catch(console.error);
*/
async respond(options) {
if (this.responded) throw new Error(ErrorCodes.InteractionAlreadyReplied);
if (this.responded) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied);
await this.client.rest.post(Routes.interactionCallback(this.id, this.token), {
body: {

View File

@@ -2,7 +2,7 @@
const { GatewayOpcodes } = require('discord-api-types/v10');
const { Presence } = require('./Presence');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
/**
* Represents the client's presence.
@@ -49,7 +49,7 @@ class ClientPresence extends Presence {
if (activities?.length) {
for (const [i, activity] of activities.entries()) {
if (typeof activity.name !== 'string') {
throw new TypeError(ErrorCodes.InvalidType, `activities[${i}].name`, 'string');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, `activities[${i}].name`, 'string');
}
activity.type ??= 0;

View File

@@ -1,7 +1,7 @@
'use strict';
const { ApplicationCommandOptionType } = require('discord-api-types/v10');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
/**
* A resolver for command interaction options.
@@ -75,7 +75,7 @@ class CommandInteractionOptionResolver {
const option = this._hoistedOptions.find(opt => opt.name === name);
if (!option) {
if (required) {
throw new TypeError(ErrorCodes.CommandInteractionOptionNotFound, name);
throw new DiscordjsTypeError(ErrorCodes.CommandInteractionOptionNotFound, name);
}
return null;
}
@@ -96,9 +96,9 @@ class CommandInteractionOptionResolver {
if (!option) {
return null;
} else if (option.type !== type) {
throw new TypeError(ErrorCodes.CommandInteractionOptionType, name, option.type, type);
throw new DiscordjsTypeError(ErrorCodes.CommandInteractionOptionType, name, option.type, type);
} else if (required && properties.every(prop => option[prop] === null || typeof option[prop] === 'undefined')) {
throw new TypeError(ErrorCodes.CommandInteractionOptionEmpty, name, option.type);
throw new DiscordjsTypeError(ErrorCodes.CommandInteractionOptionEmpty, name, option.type);
}
return option;
}
@@ -110,7 +110,7 @@ class CommandInteractionOptionResolver {
*/
getSubcommand(required = true) {
if (required && !this._subcommand) {
throw new TypeError(ErrorCodes.CommandInteractionOptionNoSubcommand);
throw new DiscordjsTypeError(ErrorCodes.CommandInteractionOptionNoSubcommand);
}
return this._subcommand;
}
@@ -122,7 +122,7 @@ class CommandInteractionOptionResolver {
*/
getSubcommandGroup(required = false) {
if (required && !this._group) {
throw new TypeError(ErrorCodes.CommandInteractionOptionNoSubcommandGroup);
throw new DiscordjsTypeError(ErrorCodes.CommandInteractionOptionNoSubcommandGroup);
}
return this._group;
}
@@ -273,7 +273,7 @@ class CommandInteractionOptionResolver {
*/
getFocused(getFull = false) {
const focusedOption = this._hoistedOptions.find(option => option.focused);
if (!focusedOption) throw new TypeError(ErrorCodes.AutocompleteInteractionOptionNoFocusedOption);
if (!focusedOption) throw new DiscordjsTypeError(ErrorCodes.AutocompleteInteractionOptionNoFocusedOption);
return getFull ? focusedOption : focusedOption.value;
}
}

View File

@@ -11,7 +11,7 @@ const GuildTemplate = require('./GuildTemplate');
const Integration = require('./Integration');
const Webhook = require('./Webhook');
const WelcomeScreen = require('./WelcomeScreen');
const { Error, TypeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');
const GuildApplicationCommandManager = require('../managers/GuildApplicationCommandManager');
const GuildBanManager = require('../managers/GuildBanManager');
const GuildChannelManager = require('../managers/GuildChannelManager');
@@ -467,7 +467,7 @@ class Guild extends AnonymousGuild {
*/
async fetchOwner(options) {
if (!this.ownerId) {
throw new Error(ErrorCodes.FetchOwnerId);
throw new DiscordjsError(ErrorCodes.FetchOwnerId);
}
const member = await this.members.fetch({ ...options, user: this.ownerId });
return member;
@@ -618,7 +618,7 @@ class Guild extends AnonymousGuild {
*/
async fetchVanityData() {
if (!this.features.includes(GuildFeature.VanityURL)) {
throw new Error(ErrorCodes.VanityURL);
throw new DiscordjsError(ErrorCodes.VanityURL);
}
const data = await this.client.rest.get(Routes.guildVanityUrl(this.id));
this.vanityURLCode = data.code;
@@ -720,7 +720,7 @@ class Guild extends AnonymousGuild {
if (options.user) {
const id = this.client.users.resolveId(options.user);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable');
query.set('user_id', id);
}
@@ -1178,7 +1178,7 @@ class Guild extends AnonymousGuild {
* .catch(console.error);
*/
async leave() {
if (this.ownerId === this.client.user.id) throw new Error(ErrorCodes.GuildOwned);
if (this.ownerId === this.client.user.id) throw new DiscordjsError(ErrorCodes.GuildOwned);
await this.client.rest.delete(Routes.userGuild(this.id));
return this;
}

View File

@@ -2,7 +2,7 @@
const { PermissionFlagsBits } = require('discord-api-types/v10');
const { BaseChannel } = require('./BaseChannel');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const PermissionOverwriteManager = require('../managers/PermissionOverwriteManager');
const { VoiceBasedChannelTypes } = require('../util/Constants');
const PermissionsBitField = require('../util/PermissionsBitField');
@@ -250,7 +250,7 @@ class GuildChannel extends BaseChannel {
* @returns {Promise<GuildChannel>}
*/
lockPermissions() {
if (!this.parent) return Promise.reject(new Error(ErrorCodes.GuildChannelOrphan));
if (!this.parent) return Promise.reject(new DiscordjsError(ErrorCodes.GuildChannelOrphan));
const permissionOverwrites = this.parent.permissionOverwrites.cache.map(overwrite => overwrite.toJSON());
return this.edit({ permissionOverwrites });
}

View File

@@ -2,7 +2,7 @@
const { PermissionFlagsBits } = require('discord-api-types/v10');
const BaseGuildEmoji = require('./BaseGuildEmoji');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const GuildEmojiRoleManager = require('../managers/GuildEmojiRoleManager');
/**
@@ -55,7 +55,7 @@ class GuildEmoji extends BaseGuildEmoji {
* @readonly
*/
get deletable() {
if (!this.guild.members.me) throw new Error(ErrorCodes.GuildUncachedMe);
if (!this.guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe);
return !this.managed && this.guild.members.me.permissions.has(PermissionFlagsBits.ManageEmojisAndStickers);
}

View File

@@ -4,7 +4,7 @@ const { PermissionFlagsBits } = require('discord-api-types/v10');
const Base = require('./Base');
const VoiceState = require('./VoiceState');
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const GuildMemberRoleManager = require('../managers/GuildMemberRoleManager');
const PermissionsBitField = require('../util/PermissionsBitField');
@@ -248,7 +248,7 @@ class GuildMember extends Base {
if (this.user.id === this.guild.ownerId) return false;
if (this.user.id === this.client.user.id) return false;
if (this.client.user.id === this.guild.ownerId) return true;
if (!this.guild.members.me) throw new Error(ErrorCodes.GuildUncachedMe);
if (!this.guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe);
return this.guild.members.me.roles.highest.comparePositionTo(this.roles.highest) > 0;
}
@@ -258,7 +258,7 @@ class GuildMember extends Base {
* @readonly
*/
get kickable() {
if (!this.guild.members.me) throw new Error(ErrorCodes.GuildUncachedMe);
if (!this.guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe);
return this.manageable && this.guild.members.me.permissions.has(PermissionFlagsBits.KickMembers);
}
@@ -268,7 +268,7 @@ class GuildMember extends Base {
* @readonly
*/
get bannable() {
if (!this.guild.members.me) throw new Error(ErrorCodes.GuildUncachedMe);
if (!this.guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe);
return this.manageable && this.guild.members.me.permissions.has(PermissionFlagsBits.BanMembers);
}
@@ -301,7 +301,7 @@ class GuildMember extends Base {
*/
permissionsIn(channel) {
channel = this.guild.channels.resolve(channel);
if (!channel) throw new Error(ErrorCodes.GuildChannelResolve);
if (!channel) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
return channel.permissionsFor(this);
}

View File

@@ -3,7 +3,7 @@
const { DiscordSnowflake } = require('@sapphire/snowflake');
const { GuildScheduledEventStatus, GuildScheduledEventEntityType, RouteBases } = require('discord-api-types/v10');
const Base = require('./Base');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
/**
* Represents a scheduled event in a {@link Guild}.
@@ -254,9 +254,9 @@ class GuildScheduledEvent extends Base {
async createInviteURL(options) {
let channelId = this.channelId;
if (this.entityType === GuildScheduledEventEntityType.External) {
if (!options?.channel) throw new Error(ErrorCodes.InviteOptionsMissingChannel);
if (!options?.channel) throw new DiscordjsError(ErrorCodes.InviteOptionsMissingChannel);
channelId = this.guild.channels.resolveId(options.channel);
if (!channelId) throw new Error(ErrorCodes.GuildChannelResolve);
if (!channelId) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
}
const invite = await this.guild.invites.create(channelId, options);
return `${RouteBases.invite}/${invite.code}?event=${this.id}`;

View File

@@ -1,7 +1,7 @@
'use strict';
const { InteractionType } = require('discord-api-types/v10');
const { ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
/**
* Represents an interaction's response
@@ -34,7 +34,7 @@ class InteractionResponse {
collector.once('end', (interactions, reason) => {
const interaction = interactions.first();
if (interaction) resolve(interaction);
else reject(new Error(ErrorCodes.InteractionCollectorError, reason));
else reject(new DiscordjsError(ErrorCodes.InteractionCollectorError, reason));
});
});
}

View File

@@ -5,7 +5,7 @@ const Base = require('./Base');
const { GuildScheduledEvent } = require('./GuildScheduledEvent');
const IntegrationApplication = require('./IntegrationApplication');
const InviteStageInstance = require('./InviteStageInstance');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
/**
* Represents an invitation to a guild channel.
@@ -234,7 +234,7 @@ class Invite extends Base {
get deletable() {
const guild = this.guild;
if (!guild || !this.client.guilds.cache.has(guild.id)) return false;
if (!guild.members.me) throw new Error(ErrorCodes.GuildUncachedMe);
if (!guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe);
return Boolean(
this.channel?.permissionsFor(this.client.user).has(PermissionFlagsBits.ManageChannels, false) ||
guild.members.me.permissions.has(PermissionFlagsBits.ManageGuild),

View File

@@ -19,7 +19,7 @@ const Mentions = require('./MessageMentions');
const MessagePayload = require('./MessagePayload');
const ReactionCollector = require('./ReactionCollector');
const { Sticker } = require('./Sticker');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const ReactionManager = require('../managers/ReactionManager');
const { createComponent } = require('../util/Components');
const { NonSystemMessageTypes } = require('../util/Constants');
@@ -541,6 +541,9 @@ class Message extends Base {
* @property {CollectorFilter} [filter] The filter applied to this collector
* @property {number} [time] Time to wait for an interaction before rejecting
* @property {ComponentType} [componentType] The type of component interaction to collect
* @property {number} [idle] Time to wait without another message component interaction before ending the collector
* @property {boolean} [dispose] Whether to remove the message component interaction after collecting
* @property {InteractionResponse} [InteractionResponse] The interaction response to collect interactions from
*/
/**
@@ -562,7 +565,7 @@ class Message extends Base {
collector.once('end', (interactions, reason) => {
const interaction = interactions.first();
if (interaction) resolve(interaction);
else reject(new Error(ErrorCodes.InteractionCollectorError, reason));
else reject(new DiscordjsError(ErrorCodes.InteractionCollectorError, reason));
});
});
}
@@ -628,10 +631,10 @@ class Message extends Base {
* @returns {Promise<Message>}
*/
async fetchReference() {
if (!this.reference) throw new Error(ErrorCodes.MessageReferenceMissing);
if (!this.reference) throw new DiscordjsError(ErrorCodes.MessageReferenceMissing);
const { channelId, messageId } = this.reference;
const channel = this.client.channels.resolve(channelId);
if (!channel) throw new Error(ErrorCodes.GuildChannelResolve);
if (!channel) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
const message = await channel.messages.fetch(messageId);
return message;
}
@@ -666,7 +669,7 @@ class Message extends Base {
* .catch(console.error);
*/
edit(options) {
if (!this.channel) return Promise.reject(new Error(ErrorCodes.ChannelNotCached));
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached));
return this.channel.messages.edit(this, options);
}
@@ -682,7 +685,7 @@ class Message extends Base {
* }
*/
crosspost() {
if (!this.channel) return Promise.reject(new Error(ErrorCodes.ChannelNotCached));
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached));
return this.channel.messages.crosspost(this.id);
}
@@ -697,7 +700,7 @@ class Message extends Base {
* .catch(console.error)
*/
async pin(reason) {
if (!this.channel) throw new Error(ErrorCodes.ChannelNotCached);
if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
await this.channel.messages.pin(this.id, reason);
return this;
}
@@ -713,7 +716,7 @@ class Message extends Base {
* .catch(console.error)
*/
async unpin(reason) {
if (!this.channel) throw new Error(ErrorCodes.ChannelNotCached);
if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
await this.channel.messages.unpin(this.id, reason);
return this;
}
@@ -734,7 +737,7 @@ class Message extends Base {
* .catch(console.error);
*/
async react(emoji) {
if (!this.channel) throw new Error(ErrorCodes.ChannelNotCached);
if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
await this.channel.messages.react(this.id, emoji);
return this.client.actions.MessageReactionAdd.handle(
@@ -758,7 +761,7 @@ class Message extends Base {
* .catch(console.error);
*/
async delete() {
if (!this.channel) throw new Error(ErrorCodes.ChannelNotCached);
if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
await this.channel.messages.delete(this.id);
return this;
}
@@ -783,7 +786,7 @@ class Message extends Base {
* .catch(console.error);
*/
reply(options) {
if (!this.channel) return Promise.reject(new Error(ErrorCodes.ChannelNotCached));
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached));
let data;
if (options instanceof MessagePayload) {
@@ -816,11 +819,11 @@ class Message extends Base {
* @returns {Promise<ThreadChannel>}
*/
startThread(options = {}) {
if (!this.channel) return Promise.reject(new Error(ErrorCodes.ChannelNotCached));
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached));
if (![ChannelType.GuildText, ChannelType.GuildAnnouncement].includes(this.channel.type)) {
return Promise.reject(new Error(ErrorCodes.MessageThreadParent));
return Promise.reject(new DiscordjsError(ErrorCodes.MessageThreadParent));
}
if (this.hasThread) return Promise.reject(new Error(ErrorCodes.MessageExistingThread));
if (this.hasThread) return Promise.reject(new DiscordjsError(ErrorCodes.MessageExistingThread));
return this.channel.threads.create({ ...options, startMessage: this });
}
@@ -830,7 +833,7 @@ class Message extends Base {
* @returns {Promise<Message>}
*/
fetch(force = true) {
if (!this.channel) return Promise.reject(new Error(ErrorCodes.ChannelNotCached));
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached));
return this.channel.messages.fetch({ message: this.id, force });
}
@@ -839,8 +842,8 @@ class Message extends Base {
* @returns {Promise<?Webhook>}
*/
fetchWebhook() {
if (!this.webhookId) return Promise.reject(new Error(ErrorCodes.WebhookMessage));
if (this.webhookId === this.applicationId) return Promise.reject(new Error(ErrorCodes.WebhookApplication));
if (!this.webhookId) return Promise.reject(new DiscordjsError(ErrorCodes.WebhookMessage));
if (this.webhookId === this.applicationId) return Promise.reject(new DiscordjsError(ErrorCodes.WebhookApplication));
return this.client.fetchWebhook(this.webhookId);
}

View File

@@ -5,7 +5,7 @@ const { isJSONEncodable } = require('@discordjs/builders');
const { lazy } = require('@discordjs/util');
const { MessageFlags } = require('discord-api-types/v10');
const ActionRowBuilder = require('./ActionRowBuilder');
const { RangeError, ErrorCodes } = require('../errors');
const { DiscordjsRangeError, ErrorCodes } = require('../errors');
const DataResolver = require('../util/DataResolver');
const MessageFlagsBitField = require('../util/MessageFlagsBitField');
const { basename, verifyString } = require('../util/Util');
@@ -108,7 +108,7 @@ class MessagePayload {
if (this.options.content === null) {
content = '';
} else if (typeof this.options.content !== 'undefined') {
content = verifyString(this.options.content, RangeError, ErrorCodes.MessageContentType, true);
content = verifyString(this.options.content, DiscordjsRangeError, ErrorCodes.MessageContentType, true);
}
return content;
@@ -130,7 +130,7 @@ class MessagePayload {
if (typeof this.options.nonce !== 'undefined') {
nonce = this.options.nonce;
if (typeof nonce === 'number' ? !Number.isInteger(nonce) : typeof nonce !== 'string') {
throw new RangeError(ErrorCodes.MessageNonceType);
throw new DiscordjsRangeError(ErrorCodes.MessageNonceType);
}
}

View File

@@ -2,7 +2,7 @@
const { Collection } = require('@discordjs/collection');
const { ComponentType } = require('discord-api-types/v10');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
/**
* Represents the serialized fields from a modal submit interaction
@@ -33,10 +33,10 @@ class ModalSubmitFields {
*/
getField(customId, type) {
const field = this.fields.get(customId);
if (!field) throw new TypeError(ErrorCodes.ModalSubmitInteractionFieldNotFound, customId);
if (!field) throw new DiscordjsTypeError(ErrorCodes.ModalSubmitInteractionFieldNotFound, customId);
if (type !== undefined && type !== field.type) {
throw new TypeError(ErrorCodes.ModalSubmitInteractionFieldType, customId, field.type, type);
throw new DiscordjsTypeError(ErrorCodes.ModalSubmitInteractionFieldType, customId, field.type, type);
}
return field;

View File

@@ -2,7 +2,7 @@
const { Routes } = require('discord-api-types/v10');
const BaseGuildTextChannel = require('./BaseGuildTextChannel');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
/**
* Represents a guild news channel on Discord.
@@ -23,7 +23,7 @@ class NewsChannel extends BaseGuildTextChannel {
*/
async addFollower(channel, reason) {
const channelId = this.guild.channels.resolveId(channel);
if (!channelId) throw new Error(ErrorCodes.GuildChannelResolve);
if (!channelId) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
await this.client.rest.post(Routes.channelFollowers(this.id), { body: { webhook_channel_id: channelId }, reason });
return this;
}

View File

@@ -1,7 +1,7 @@
'use strict';
const { BaseChannel } = require('./BaseChannel');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
/**
* Represents a Partial Group DM Channel on Discord.
@@ -49,11 +49,11 @@ class PartialGroupDMChannel extends BaseChannel {
}
delete() {
return Promise.reject(new Error(ErrorCodes.DeleteGroupDMChannel));
return Promise.reject(new DiscordjsError(ErrorCodes.DeleteGroupDMChannel));
}
fetch() {
return Promise.reject(new Error(ErrorCodes.FetchGroupDMChannel));
return Promise.reject(new DiscordjsError(ErrorCodes.FetchGroupDMChannel));
}
}

View File

@@ -3,7 +3,7 @@
const { OverwriteType } = require('discord-api-types/v10');
const Base = require('./Base');
const { Role } = require('./Role');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const PermissionsBitField = require('../util/PermissionsBitField');
/**
@@ -181,7 +181,7 @@ class PermissionOverwrites extends Base {
}
const userOrRole = guild.roles.resolve(overwrite.id) ?? guild.client.users.resolve(overwrite.id);
if (!userOrRole) throw new TypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role');
if (!userOrRole) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role');
const type = userOrRole instanceof Role ? OverwriteType.Role : OverwriteType.Member;
return {

View File

@@ -3,7 +3,7 @@
const { DiscordSnowflake } = require('@sapphire/snowflake');
const { PermissionFlagsBits } = require('discord-api-types/v10');
const Base = require('./Base');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const PermissionsBitField = require('../util/PermissionsBitField');
/**
@@ -229,7 +229,7 @@ class Role extends Base {
*/
permissionsIn(channel, checkAdmin = true) {
channel = this.guild.channels.resolve(channel);
if (!channel) throw new Error(ErrorCodes.GuildChannelResolve);
if (!channel) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
return channel.rolePermissions(this, checkAdmin);
}

View File

@@ -3,7 +3,7 @@
const { DiscordSnowflake } = require('@sapphire/snowflake');
const { Routes, StickerFormatType } = require('discord-api-types/v10');
const Base = require('./Base');
const { ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
/**
* Represents a Sticker.
@@ -191,7 +191,7 @@ class Sticker extends Base {
*/
async fetchUser() {
if (this.partial) await this.fetch();
if (!this.guildId) throw new Error(ErrorCodes.NotGuildSticker);
if (!this.guildId) throw new DiscordjsError(ErrorCodes.NotGuildSticker);
return this.guild.stickers.fetchUser(this);
}

View File

@@ -3,7 +3,7 @@
const { ChannelType, PermissionFlagsBits, Routes } = require('discord-api-types/v10');
const { BaseChannel } = require('./BaseChannel');
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const { RangeError, ErrorCodes } = require('../errors');
const { DiscordjsRangeError, ErrorCodes } = require('../errors');
const MessageManager = require('../managers/MessageManager');
const ThreadMemberManager = require('../managers/ThreadMemberManager');
const ChannelFlagsBitField = require('../util/ChannelFlagsBitField');
@@ -400,7 +400,7 @@ class ThreadChannel extends BaseChannel {
*/
setInvitable(invitable = true, reason) {
if (this.type !== ChannelType.PrivateThread) {
return Promise.reject(new RangeError(ErrorCodes.ThreadInvitableType, this.type));
return Promise.reject(new DiscordjsRangeError(ErrorCodes.ThreadInvitableType, this.type));
}
return this.edit({ invitable, reason });
}

View File

@@ -2,7 +2,7 @@
const { ChannelType, Routes } = require('discord-api-types/v10');
const Base = require('./Base');
const { Error, TypeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');
/**
* Represents the voice state for a Guild Member.
@@ -220,20 +220,20 @@ class VoiceState extends Base {
* @returns {Promise<VoiceState>}
*/
async edit(data) {
if (this.channel?.type !== ChannelType.GuildStageVoice) throw new Error(ErrorCodes.VoiceNotStageChannel);
if (this.channel?.type !== ChannelType.GuildStageVoice) throw new DiscordjsError(ErrorCodes.VoiceNotStageChannel);
const target = this.client.user.id === this.id ? '@me' : this.id;
if (target !== '@me' && typeof data.requestToSpeak !== 'undefined') {
throw new Error(ErrorCodes.VoiceStateNotOwn);
throw new DiscordjsError(ErrorCodes.VoiceStateNotOwn);
}
if (!['boolean', 'undefined'].includes(typeof data.requestToSpeak)) {
throw new TypeError(ErrorCodes.VoiceStateInvalidType, 'requestToSpeak');
throw new DiscordjsTypeError(ErrorCodes.VoiceStateInvalidType, 'requestToSpeak');
}
if (!['boolean', 'undefined'].includes(typeof data.suppressed)) {
throw new TypeError(ErrorCodes.VoiceStateInvalidType, 'suppressed');
throw new DiscordjsTypeError(ErrorCodes.VoiceStateInvalidType, 'suppressed');
}
await this.client.rest.patch(Routes.guildVoiceState(this.guild.id, target), {

View File

@@ -5,7 +5,7 @@ const { lazy } = require('@discordjs/util');
const { DiscordSnowflake } = require('@sapphire/snowflake');
const { Routes, WebhookType } = require('discord-api-types/v10');
const MessagePayload = require('./MessagePayload');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const DataResolver = require('../util/DataResolver');
const getMessage = lazy(() => require('./Message').Message);
@@ -190,7 +190,7 @@ class Webhook {
* .catch(console.error);
*/
async send(options) {
if (!this.token) throw new Error(ErrorCodes.WebhookTokenUnavailable);
if (!this.token) throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable);
let messagePayload;
@@ -231,7 +231,7 @@ class Webhook {
* @see {@link https://api.slack.com/messaging/webhooks}
*/
async sendSlackMessage(body) {
if (!this.token) throw new Error(ErrorCodes.WebhookTokenUnavailable);
if (!this.token) throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable);
const data = await this.client.rest.post(Routes.webhookPlatform(this.id, this.token, 'slack'), {
query: makeURLSearchParams({ wait: true }),
@@ -287,7 +287,7 @@ class Webhook {
* @returns {Promise<Message>} Returns the message sent by this webhook
*/
async fetchMessage(message, { threadId } = {}) {
if (!this.token) throw new Error(ErrorCodes.WebhookTokenUnavailable);
if (!this.token) throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable);
const data = await this.client.rest.get(Routes.webhookMessage(this.id, this.token, message), {
query: threadId ? makeURLSearchParams({ thread_id: threadId }) : undefined,
@@ -308,7 +308,7 @@ class Webhook {
* @returns {Promise<Message>} Returns the message edited by this webhook
*/
async editMessage(message, options) {
if (!this.token) throw new Error(ErrorCodes.WebhookTokenUnavailable);
if (!this.token) throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable);
let messagePayload;
@@ -359,7 +359,7 @@ class Webhook {
* @returns {Promise<void>}
*/
async deleteMessage(message, threadId) {
if (!this.token) throw new Error(ErrorCodes.WebhookTokenUnavailable);
if (!this.token) throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable);
await this.client.rest.delete(
Routes.webhookMessage(this.id, this.token, typeof message === 'string' ? message : message.id),

View File

@@ -3,7 +3,7 @@
const EventEmitter = require('node:events');
const { setTimeout, clearTimeout } = require('node:timers');
const { Collection } = require('@discordjs/collection');
const { TypeError, ErrorCodes } = require('../../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../../errors');
const { flatten } = require('../../util/Util');
/**
@@ -87,7 +87,7 @@ class Collector extends EventEmitter {
this._endReason = null;
if (typeof this.filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'options.filter', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options.filter', 'function');
}
this.handleCollect = this.handleCollect.bind(this);

View File

@@ -2,7 +2,7 @@
const { isJSONEncodable } = require('@discordjs/builders');
const { InteractionResponseType, MessageFlags, Routes, InteractionType } = require('discord-api-types/v10');
const { Error, ErrorCodes } = require('../../errors');
const { DiscordjsError, ErrorCodes } = require('../../errors');
const InteractionCollector = require('../InteractionCollector');
const InteractionResponse = require('../InteractionResponse');
const MessagePayload = require('../MessagePayload');
@@ -64,7 +64,7 @@ class InteractionResponses {
* .catch(console.error);
*/
async deferReply(options = {}) {
if (this.deferred || this.replied) throw new Error(ErrorCodes.InteractionAlreadyReplied);
if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied);
this.ephemeral = options.ephemeral ?? false;
await this.client.rest.post(Routes.interactionCallback(this.id, this.token), {
body: {
@@ -99,7 +99,7 @@ class InteractionResponses {
* .catch(console.error);
*/
async reply(options) {
if (this.deferred || this.replied) throw new Error(ErrorCodes.InteractionAlreadyReplied);
if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied);
this.ephemeral = options.ephemeral ?? false;
let messagePayload;
@@ -147,7 +147,7 @@ class InteractionResponses {
* .catch(console.error);
*/
async editReply(options) {
if (!this.deferred && !this.replied) throw new Error(ErrorCodes.InteractionNotReplied);
if (!this.deferred && !this.replied) throw new DiscordjsError(ErrorCodes.InteractionNotReplied);
const message = await this.webhook.editMessage('@original', options);
this.replied = true;
return message;
@@ -164,7 +164,7 @@ class InteractionResponses {
* .catch(console.error);
*/
async deleteReply() {
if (this.ephemeral) throw new Error(ErrorCodes.InteractionEphemeralReplied);
if (this.ephemeral) throw new DiscordjsError(ErrorCodes.InteractionEphemeralReplied);
await this.webhook.deleteMessage('@original');
}
@@ -174,7 +174,7 @@ class InteractionResponses {
* @returns {Promise<Message>}
*/
followUp(options) {
if (!this.deferred && !this.replied) return Promise.reject(new Error(ErrorCodes.InteractionNotReplied));
if (!this.deferred && !this.replied) return Promise.reject(new DiscordjsError(ErrorCodes.InteractionNotReplied));
return this.webhook.send(options);
}
@@ -189,7 +189,7 @@ class InteractionResponses {
* .catch(console.error);
*/
async deferUpdate(options = {}) {
if (this.deferred || this.replied) throw new Error(ErrorCodes.InteractionAlreadyReplied);
if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied);
await this.client.rest.post(Routes.interactionCallback(this.id, this.token), {
body: {
type: InteractionResponseType.DeferredMessageUpdate,
@@ -215,7 +215,7 @@ class InteractionResponses {
* .catch(console.error);
*/
async update(options) {
if (this.deferred || this.replied) throw new Error(ErrorCodes.InteractionAlreadyReplied);
if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied);
let messagePayload;
if (options instanceof MessagePayload) messagePayload = options;
@@ -242,7 +242,7 @@ class InteractionResponses {
* @returns {Promise<void>}
*/
async showModal(modal) {
if (this.deferred || this.replied) throw new Error(ErrorCodes.InteractionAlreadyReplied);
if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied);
await this.client.rest.post(Routes.interactionCallback(this.id, this.token), {
body: {
type: InteractionResponseType.Modal,
@@ -272,14 +272,14 @@ class InteractionResponses {
* .catch(console.error);
*/
awaitModalSubmit(options) {
if (typeof options.time !== 'number') throw new Error(ErrorCodes.InvalidType, 'time', 'number');
if (typeof options.time !== 'number') throw new DiscordjsError(ErrorCodes.InvalidType, 'time', 'number');
const _options = { ...options, max: 1, interactionType: InteractionType.ModalSubmit };
return new Promise((resolve, reject) => {
const collector = new InteractionCollector(this.client, _options);
collector.once('end', (interactions, reason) => {
const interaction = interactions.first();
if (interaction) resolve(interaction);
else reject(new Error(ErrorCodes.InteractionCollectorError, reason));
else reject(new DiscordjsError(ErrorCodes.InteractionCollectorError, reason));
});
});
}

View File

@@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection');
const { DiscordSnowflake } = require('@sapphire/snowflake');
const { InteractionType, Routes } = require('discord-api-types/v10');
const { TypeError, Error, ErrorCodes } = require('../../errors');
const { DiscordjsTypeError, DiscordjsError, ErrorCodes } = require('../../errors');
const InteractionCollector = require('../InteractionCollector');
const MessageCollector = require('../MessageCollector');
const MessagePayload = require('../MessagePayload');
@@ -273,7 +273,7 @@ class TextBasedChannel {
collector.once('end', (interactions, reason) => {
const interaction = interactions.first();
if (interaction) resolve(interaction);
else reject(new Error(ErrorCodes.InteractionCollectorError, reason));
else reject(new DiscordjsError(ErrorCodes.InteractionCollectorError, reason));
});
});
}
@@ -326,7 +326,7 @@ class TextBasedChannel {
const msgs = await this.messages.fetch({ limit: messages });
return this.bulkDelete(msgs, filterOld);
}
throw new TypeError(ErrorCodes.MessageBulkDeleteType);
throw new DiscordjsTypeError(ErrorCodes.MessageBulkDeleteType);
}
/**

View File

@@ -1,6 +1,6 @@
'use strict';
const { RangeError, ErrorCodes } = require('../errors');
const { DiscordjsRangeError, ErrorCodes } = require('../errors');
/**
* Data structure that makes it easy to interact with a bitfield.
@@ -165,7 +165,7 @@ class BitField {
if (typeof this.Flags[bit] !== 'undefined') return this.Flags[bit];
if (!isNaN(bit)) return typeof DefaultBit === 'bigint' ? BigInt(bit) : Number(bit);
}
throw new RangeError(ErrorCodes.BitFieldInvalid, bit);
throw new DiscordjsRangeError(ErrorCodes.BitFieldInvalid, bit);
}
}

View File

@@ -4,7 +4,7 @@ const { Buffer } = require('node:buffer');
const fs = require('node:fs/promises');
const path = require('node:path');
const { fetch } = require('undici');
const { Error: DiscordError, TypeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');
const Invite = require('../structures/Invite');
/**
@@ -129,11 +129,11 @@ class DataResolver extends null {
const file = path.resolve(resource);
const stats = await fs.stat(file);
if (!stats.isFile()) throw new DiscordError(ErrorCodes.FileNotFound, file);
if (!stats.isFile()) throw new DiscordjsError(ErrorCodes.FileNotFound, file);
return { data: await fs.readFile(file) };
}
throw new TypeError(ErrorCodes.ReqResourceType);
throw new DiscordjsTypeError(ErrorCodes.ReqResourceType);
}
}

View File

@@ -1,7 +1,7 @@
'use strict';
const { Collection } = require('@discordjs/collection');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
/**
* Options for defining the behavior of a LimitedCollection
@@ -20,15 +20,15 @@ const { TypeError, ErrorCodes } = require('../errors');
class LimitedCollection extends Collection {
constructor(options = {}, iterable) {
if (typeof options !== 'object' || options === null) {
throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
}
const { maxSize = Infinity, keepOverLimit = null } = options;
if (typeof maxSize !== 'number') {
throw new TypeError(ErrorCodes.InvalidType, 'maxSize', 'number');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'maxSize', 'number');
}
if (keepOverLimit !== null && typeof keepOverLimit !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'keepOverLimit', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'keepOverLimit', 'function');
}
super(iterable);

View File

@@ -3,7 +3,7 @@
const { setInterval, clearInterval } = require('node:timers');
const { ThreadChannelTypes, SweeperKeys } = require('./Constants');
const Events = require('./Events');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
/**
* @typedef {Function} GlobalSweepFilter
@@ -131,7 +131,7 @@ class Sweepers {
*/
sweepMessages(filter) {
if (typeof filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'filter', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function');
}
let channels = 0;
let messages = 0;
@@ -162,7 +162,7 @@ class Sweepers {
*/
sweepReactions(filter) {
if (typeof filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'filter', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function');
}
let channels = 0;
let messages = 0;
@@ -210,7 +210,7 @@ class Sweepers {
*/
sweepThreadMembers(filter) {
if (typeof filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'filter', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function');
}
let threads = 0;
@@ -240,7 +240,7 @@ class Sweepers {
*/
sweepThreads(filter) {
if (typeof filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'filter', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function');
}
let threads = 0;
@@ -262,7 +262,7 @@ class Sweepers {
*/
sweepUsers(filter) {
if (typeof filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'filter', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function');
}
const users = this.client.users.cache.sweep(filter);
@@ -313,13 +313,13 @@ class Sweepers {
excludeFromSweep = () => false,
} = {}) {
if (typeof lifetime !== 'number') {
throw new TypeError(ErrorCodes.InvalidType, 'lifetime', 'number');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'lifetime', 'number');
}
if (typeof getComparisonTimestamp !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'getComparisonTimestamp', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'getComparisonTimestamp', 'function');
}
if (typeof excludeFromSweep !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'excludeFromSweep', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'excludeFromSweep', 'function');
}
return () => {
if (lifetime <= 0) return null;
@@ -391,7 +391,7 @@ class Sweepers {
*/
_sweepGuildDirectProp(key, filter, { emit = true, outputName } = {}) {
if (typeof filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'filter', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function');
}
let guilds = 0;
@@ -419,20 +419,20 @@ class Sweepers {
_validateProperties(key) {
const props = this.options[key];
if (typeof props !== 'object') {
throw new TypeError(ErrorCodes.InvalidType, `sweepers.${key}`, 'object', true);
throw new DiscordjsTypeError(ErrorCodes.InvalidType, `sweepers.${key}`, 'object', true);
}
if (typeof props.interval !== 'number') {
throw new TypeError(ErrorCodes.InvalidType, `sweepers.${key}.interval`, 'number');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, `sweepers.${key}.interval`, 'number');
}
// Invites, Messages, and Threads can be provided a lifetime parameter, which we use to generate the filter
if (['invites', 'messages', 'threads'].includes(key) && !('filter' in props)) {
if (typeof props.lifetime !== 'number') {
throw new TypeError(ErrorCodes.InvalidType, `sweepers.${key}.lifetime`, 'number');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, `sweepers.${key}.lifetime`, 'number');
}
return;
}
if (typeof props.filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, `sweepers.${key}.filter`, 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, `sweepers.${key}.filter`, 'function');
}
}
@@ -448,7 +448,7 @@ class Sweepers {
this.intervals[intervalKey] = setInterval(() => {
const sweepFn = opts.filter();
if (sweepFn === null) return;
if (typeof sweepFn !== 'function') throw new TypeError(ErrorCodes.SweepFilterReturn);
if (typeof sweepFn !== 'function') throw new DiscordjsTypeError(ErrorCodes.SweepFilterReturn);
this[sweepKey](sweepFn);
}, opts.interval * 1_000).unref();
}

View File

@@ -5,7 +5,7 @@ const { Collection } = require('@discordjs/collection');
const { ChannelType, RouteBases, Routes } = require('discord-api-types/v10');
const { fetch } = require('undici');
const Colors = require('./Colors');
const { Error: DiscordError, RangeError, TypeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsRangeError, DiscordjsTypeError, ErrorCodes } = require('../errors');
const isObject = d => typeof d === 'object' && d !== null;
/**
@@ -223,13 +223,13 @@ function escapeSpoiler(text) {
* @returns {Promise<number>} The recommended number of shards
*/
async function fetchRecommendedShardCount(token, { guildsPerShard = 1_000, multipleOf = 1 } = {}) {
if (!token) throw new DiscordError(ErrorCodes.TokenMissing);
if (!token) throw new DiscordjsError(ErrorCodes.TokenMissing);
const response = await fetch(RouteBases.api + Routes.gatewayBot(), {
method: 'GET',
headers: { Authorization: `Bot ${token.replace(/^Bot\s*/i, '')}` },
});
if (!response.ok) {
if (response.status === 401) throw new DiscordError(ErrorCodes.TokenInvalid);
if (response.status === 401) throw new DiscordjsError(ErrorCodes.TokenInvalid);
throw response;
}
const { shards } = await response.json();
@@ -413,8 +413,8 @@ function resolveColor(color) {
color = (color[0] << 16) + (color[1] << 8) + color[2];
}
if (color < 0 || color > 0xffffff) throw new RangeError(ErrorCodes.ColorRange);
else if (Number.isNaN(color)) throw new TypeError(ErrorCodes.ColorConvert);
if (color < 0 || color > 0xffffff) throw new DiscordjsRangeError(ErrorCodes.ColorRange);
else if (Number.isNaN(color)) throw new DiscordjsTypeError(ErrorCodes.ColorConvert);
return color;
}

View File

@@ -1750,7 +1750,7 @@ export class Message<InGuild extends boolean = boolean> extends Base {
public toJSON(): unknown;
public toString(): string;
public unpin(reason?: string): Promise<Message<InGuild>>;
public inGuild(): this is Message<true> & this;
public inGuild(): this is Message<true>;
}
export class AttachmentBuilder {
@@ -4252,6 +4252,7 @@ export interface CategoryCreateChannelOptions {
videoQualityMode?: VideoQualityMode;
availableTags?: GuildForumTagData[];
defaultReactionEmoji?: DefaultReactionEmoji;
defaultAutoArchiveDuration?: ThreadAutoArchiveDuration;
defaultSortOrder?: SortOrderType;
reason?: string;
}

View File

@@ -309,6 +309,11 @@ declare const assertIsMessage: (m: Promise<Message>) => void;
client.on('messageCreate', async message => {
const { client, channel } = message;
if (!message.inGuild() && message.partial) {
expectNotType<never>(message);
}
expectType<Client<true>>(client);
assertIsMessage(channel.send('string'));
assertIsMessage(channel.send({}));

View File

@@ -4,8 +4,8 @@
"description": "The docs.json generator for discord.js and its related projects",
"scripts": {
"build": "tsup",
"lint": "prettier --check . && cross-env TIMING=1 eslint src --ext mjs,js,ts",
"format": "prettier --write . && cross-env TIMING=1 eslint src --ext mjs,js,ts --fix",
"lint": "prettier --check . && cross-env TIMING=1 eslint src --ext .mjs,.js,.ts",
"format": "prettier --write . && cross-env TIMING=1 eslint src --ext .mjs,.js,.ts --fix",
"fmt": "yarn format",
"prepack": "yarn format && yarn build"
},
@@ -40,21 +40,21 @@
},
"homepage": "https://discord.js.org",
"dependencies": {
"commander": "^9.4.0",
"commander": "^9.4.1",
"jsdoc-to-markdown": "^7.1.1",
"tslib": "^2.4.0",
"typedoc": "^0.23.15"
},
"devDependencies": {
"@favware/cliff-jumper": "^1.8.7",
"@favware/cliff-jumper": "^1.8.8",
"@types/jsdoc-to-markdown": "^7.0.3",
"@types/node": "^16.11.60",
"@types/node": "^16.11.64",
"cross-env": "^7.0.3",
"eslint": "^8.24.0",
"eslint-config-neon": "^0.1.33",
"eslint-config-neon": "^0.1.35",
"prettier": "^2.7.1",
"tsup": "^6.2.3",
"typescript": "^4.8.3"
"typescript": "^4.8.4"
},
"engines": {
"node": ">=16.9.0"

View File

@@ -0,0 +1,11 @@
{
"extends": ["../../.eslintrc.json", "neon/react", "neon/astro", "neon/prettier"],
"settings": {
"react": {
"version": "detect"
}
},
"rules": {
"react/jsx-filename-extension": [1, { "extensions": [".tsx", ".astro"] }]
}
}

30
packages/guide/.gitignore vendored Normal file
View File

@@ -0,0 +1,30 @@
# Packages
node_modules/
# Log files
logs/
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# Env
.env
# Dist
dist/
typings/
.cache/
build/
api/
src/styles/unocss.css
.next/
# Miscellaneous
.tmp/
coverage/
.vercel
public/searchIndex

View File

@@ -0,0 +1 @@
module.exports = require('../../.lintstagedrc.json');

View File

@@ -0,0 +1,15 @@
# Autogenerated
CHANGELOG.md
.turbo
dist/
docs/**/*
!docs/index.yml
!docs/README.md
coverage/
.cache
build/
src/styles/unocss.css
api/
.next/
.vercel/
.cache/

View File

@@ -0,0 +1 @@
module.exports = require('../../.prettierrc.json');

View File

@@ -0,0 +1,105 @@
import { fileURLToPath, URL } from 'node:url';
import image from '@astrojs/image';
import mdx from '@astrojs/mdx';
import react from '@astrojs/react';
import { remarkCodeHike } from '@code-hike/mdx';
import { defineConfig } from 'astro/config';
import { toString } from 'hast-util-to-string';
import { h } from 'hastscript';
import { escape } from 'html-escaper';
import rehypeAutolinkHeadings from 'rehype-autolink-headings';
import rehypeSlug from 'rehype-slug';
import shikiThemeDarkPlus from 'shiki/themes/dark-plus.json' assert { type: 'json' };
import Unocss from 'unocss/astro';
const LinkIcon = h(
'svg',
{
width: '1rem',
height: '1rem',
viewBox: '0 0 24 24',
fill: 'none',
stroke: 'currentColor',
strokeWidth: '2',
strokeLinecap: 'round',
strokeLinejoin: 'round',
},
h('path', {
// eslint-disable-next-line id-length
d: 'M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71',
}),
h('path', {
// eslint-disable-next-line id-length
d: 'M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71',
}),
);
const createSROnlyLabel = (text: string) => {
const node = h('span.sr-only', `Section titled ${escape(text)}`);
node.properties!['is:raw'] = true;
return node;
};
export default defineConfig({
integrations: [
react(),
mdx(),
image({
serviceEntryPoint: '@astrojs/image/sharp',
}),
Unocss({
configFile: fileURLToPath(new URL('../ui/unocss.config.ts', import.meta.url)),
}),
],
markdown: {
remarkPlugins: [[remarkCodeHike, { autoImport: false, theme: shikiThemeDarkPlus, lineNumbers: true }]],
rehypePlugins: [
rehypeSlug,
[
rehypeAutolinkHeadings,
{
properties: {
class:
'relative inline-flex w-6 h-6 place-items-center place-content-center outline-0 text-black dark:text-white ml-2',
},
behavior: 'after',
group: ({ tagName }) =>
h('div', {
class: `[&>*]:inline-block [&>h1]:m-0 [&>h2]:m-0 [&>h3]:m-0 [&>h4]:m-0 level-${tagName}`,
tabIndex: -1,
}),
content: (heading) => [
h(
`span.anchor-icon`,
{
ariaHidden: 'true',
},
LinkIcon,
),
createSROnlyLabel(toString(heading)),
],
},
],
],
extendDefaultPlugins: true,
syntaxHighlight: false,
},
vite: {
resolve: {
alias: {
'ariakit/button': fileURLToPath(new URL('node_modules/ariakit/esm/button/index.js', import.meta.url)),
'ariakit/disclosure': fileURLToPath(new URL('node_modules/ariakit/esm/disclosure/index.js', import.meta.url)),
'ariakit-utils/dom': fileURLToPath(new URL('node_modules/ariakit-utils/esm/dom.js', import.meta.url)),
'ariakit-utils/events': fileURLToPath(new URL('node_modules/ariakit-utils/esm/events.js', import.meta.url)),
'ariakit-utils/focus': fileURLToPath(new URL('node_modules/ariakit-utils/esm/focus.js', import.meta.url)),
'ariakit-utils/hooks': fileURLToPath(new URL('node_modules/ariakit-utils/esm/hooks.js', import.meta.url)),
'ariakit-utils/misc': fileURLToPath(new URL('node_modules/ariakit-utils/esm/misc.js', import.meta.url)),
'ariakit-utils/platform': fileURLToPath(new URL('node_modules/ariakit-utils/esm/platform.js', import.meta.url)),
'ariakit-utils/system': fileURLToPath(new URL('node_modules/ariakit-utils/esm/system.js', import.meta.url)),
'react-icons/fi': fileURLToPath(new URL('node_modules/react-icons/fi/index.esm.js', import.meta.url)),
'react-icons/vsc': fileURLToPath(new URL('node_modules/react-icons/vsc/index.esm.js', import.meta.url)),
'react-use': fileURLToPath(new URL('node_modules/react-use/esm/index.js', import.meta.url)),
},
},
},
});

View File

@@ -0,0 +1,91 @@
{
"name": "@discordjs/guide",
"version": "0.1.0",
"description": "Imagine a guide... that explores the many possibilities for your discord.js bot",
"private": true,
"scripts": {
"test": "vitest run",
"build:prod": "yarn workspace @discordjs/ui run build && astro build",
"dev": "astro dev",
"preview": "astro preview",
"lint": "prettier --check . && cross-env TIMING=1 eslint src --ext .mjs,.js,.cjs,.ts,.tsx,.astro",
"format": "prettier --write . && cross-env TIMING=1 eslint src --ext .mjs,.js,.cjs,.ts,.tsx,.astro --fix"
},
"type": "module",
"contributors": [
"Crawl <icrawltogo@gmail.com>"
],
"license": "Apache-2.0",
"keywords": [
"discord",
"api",
"bot",
"client",
"node",
"discordapp",
"discordjs"
],
"repository": {
"type": "git",
"url": "https://github.com/discordjs/discord.js.git"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
},
"homepage": "https://discord.js.org",
"dependencies": {
"@astrojs/image": "^0.9.2",
"@astrojs/mdx": "^0.11.4",
"@astrojs/react": "^1.1.4",
"@code-hike/mdx": "^0.7.4",
"@discordjs/ui": "workspace:^",
"@vscode/codicons": "^0.0.32",
"ariakit": "^2.0.0-next.41",
"astro": "^1.4.6",
"cmdk": "^0.1.20",
"meilisearch": "^0.28.0",
"react": "^17.0.2",
"react-custom-scrollbars-2": "^4.5.0",
"react-dom": "^17.0.2",
"react-icons": "^4.4.0",
"react-syntax-highlighter": "^15.5.0",
"react-use": "^17.4.0",
"rehype-ignore": "^1.0.1",
"rehype-pretty-code": "^0.3.2",
"rehype-raw": "^6.1.1",
"sharp": "^0.31.1",
"shiki": "^0.11.1"
},
"devDependencies": {
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^14.4.3",
"@types/node": "^16.11.64",
"@types/react": "^17.0.50",
"@types/react-dom": "^17.0.17",
"@types/react-syntax-highlighter": "^15.5.5",
"@unocss/cli": "^0.45.26",
"@unocss/reset": "^0.45.26",
"@vitejs/plugin-react": "^2.1.0",
"@vitest/coverage-c8": "^0.24.0",
"concurrently": "^7.4.0",
"cross-env": "^7.0.3",
"eslint": "^8.24.0",
"eslint-config-neon": "^0.1.35",
"happy-dom": "^7.4.0",
"hast-util-to-string": "^2.0.0",
"hastscript": "^7.0.2",
"html-escaper": "^3.0.3",
"prettier": "^2.7.1",
"prettier-plugin-astro": "^0.5.5",
"prettier-plugin-tailwindcss": "^0.1.13",
"rehype-autolink-headings": "^6.1.1",
"rehype-slug": "^5.0.1",
"typescript": "^4.8.4",
"unocss": "^0.45.26",
"vercel": "^28.4.8",
"vitest": "^0.24.0"
},
"engines": {
"node": ">=16.9.0"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Some files were not shown because too many files have changed in this diff Show More