Compare commits

...

93 Commits

Author SHA1 Message Date
iCrawl
3621e5efbd chore(rest): release @discordjs/rest@1.1.0 2022-08-22 10:01:34 +02:00
iCrawl
d2f5b5b539 chore(ws): release @discordjs/ws@0.3.0 2022-08-22 09:57:26 +02:00
iCrawl
9ed11a4c19 chore: deps 2022-08-22 09:56:42 +02:00
Suneet Tipirneni
e42fd16369 feat(website): Show constructor information (#8540) 2022-08-22 09:45:53 +02:00
Jiralite
dd44e8b6ec fix(proxyRequests): Typo in error message (#8537)
fix(proxyRequests): typo in error message

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-08-21 20:39:40 +00:00
Synbulat Biishev
3bef9018c0 fix(GuildMemberManager): add() method throws an error (#8539)
* fix(GuildMemberManager): `add()` method throws an error

* chore: update comment
2022-08-21 20:32:56 +00:00
Jiralite
23a0b6ccf2 fix(Guild): Widget channel types and fixes (#8530)
fix: various widget fixes

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-08-21 09:28:31 +00:00
Jiralite
b3f7c32f7f types: Allow choice's value type to be strictly inferred (#8529)
* types: stricter types for choices in options

* test: add choice tests

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-08-20 20:29:16 +00:00
Jiralite
0dba8adbd2 types(GuildAuditLogs): Allow fetching to return all possible values (#8522)
types: allow everything to be returned upon fetching

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-08-20 19:03:36 +00:00
Jiralite
2b8074dd12 refactor(GuildAuditLogsEntry): Remove guild from application command permission update extra (#8520)
refactor(GuildAuditLogsEntry): remove guild extra

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-08-20 18:51:39 +00:00
InkoHX
16bbc8aa20 types: Correct EventEmitter.on (static) return type (#8524)
types: Correct EventEmitter.on (static) return type

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-08-20 18:45:56 +00:00
Jiralite
7a3d18dd6d types(GuildAuditLogs): Remove static Entry (#8521)
types(GuildAuditLogs): remove static `Entry`

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-08-20 18:34:32 +00:00
Jiralite
4882b17a77 types: Disallow some channel types from webhook creation (#8531)
types: disallow some channel types from webhook creation
2022-08-20 18:26:33 +00:00
Suneet Tipirneni
8028813825 feat(website): render @defaultValue blocks (#8527)
feat(website): render @defaultValue blocks
2022-08-19 18:24:55 +02:00
Suneet Tipirneni
47f2990b89 feat(website): show inherited members (#8526)
* feat(website): show inherited members

* fix: use passHref
2022-08-19 18:22:22 +02:00
Suneet Tipirneni
e475b63f25 feat(website): show descriptions for @typeParam blocks (#8523) 2022-08-19 10:55:43 +02:00
iCrawl
673262d38c feat: deprecation badges 2022-08-18 18:47:44 +02:00
Suneet Tipirneni
7f415a2502 feat(website): show parameter descriptions (#8519)
Co-authored-by: Noel <buechler.noel@outlook.com>
2022-08-18 18:38:27 +02:00
DD
cda3f005b1 feat(GuildMemberManager): addRole and removeRole (#8510)
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-08-18 10:58:35 +02:00
Synbulat Biishev
f9c25ddcfe feat: deprecate ActionRow.from() (#8504)
* feat: deprecate `ActionRow.from()`

* feat: deprecate `ActionRow.from()`

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-08-18 07:06:01 +00:00
iCrawl
74740260a7 ci: fix if statement, again 2022-08-17 23:51:07 +02:00
iCrawl
1008e3d4a7 ci: fix if check 2022-08-17 23:46:22 +02:00
iCrawl
17ab0e652c refactor: inline table of contents 2022-08-17 23:21:23 +02:00
Noel
872ce801a0 revert: "refactor(website): use mantine code blocks" (#8514) 2022-08-17 23:04:47 +02:00
Suneet Tipirneni
0bf3df30da refactor(website): use mantine code blocks (#8512) 2022-08-17 22:38:11 +02:00
iCrawl
20680efbc9 feat: more visibly annotate optionals 2022-08-17 22:16:22 +02:00
Jiralite
7701331b1c ci: Remove management of chore label (#8508)
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-08-17 20:12:54 +00:00
Suneet Tipirneni
0be85fd101 feat(website): render @deprecated and @remarks blocks (#8511) 2022-08-17 21:51:29 +02:00
iCrawl
e147c5bd64 fix: codelisting 2022-08-17 21:24:38 +02:00
iCrawl
2f1ec7401c feat: table of contents / method visibility / property modifiers 2022-08-17 21:12:09 +02:00
Suneet Tipirneni
0f83402985 refactor(website): adjust typography (#8503) 2022-08-17 10:17:09 +02:00
Parbez
d97cd936fd chore: bump vitest and add @vitest/coverage-c8 (#8507) 2022-08-17 09:44:21 +02:00
Jiralite
812f7f1ea8 types: Implement max/min values for autocomplete (#8498)
* types: implement max/min values for autocomplete

* refactor: deduplicate options

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-08-16 20:37:08 +00:00
Jiralite
7d2507279c docs(GuildAuditLogsEntry): Correct action wording (#8499)
docs(GuildAuditLogsEntry): fix `action` wording

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-08-16 20:30:07 +00:00
Rodry
c31a5cfcc8 types(ModalMessageModalSubmitInteraction): channelId is not nullable (#8496)
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-08-16 15:38:30 +00:00
DD
acdafe60c7 fix(WebSocketShard#destroy): wait for close and cleanup listeners (#8479)
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-08-16 15:33:00 +00:00
DD
4fd42528fe fix(WebSocketManager#connect): check if we have enough sessions (#8481)
* fix(WebSocketManager#connect): check if we have enough sessions

* fix: more useful error message

* fix: tests

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
2022-08-16 15:28:01 +00:00
ZyX
ebaf158006 types: change type of ApplicationCommandSubCommand.options (#8476)
* types: change type of ApplicationCommandSubCommand.options

* types: change type of ApplicationCommandSubCommand.options

* Update packages/discord.js/typings/index.d.ts

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>

Co-authored-by: Vlad Frangu <kingdgrizzle@gmail.com>
Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
2022-08-16 14:39:16 +00:00
Suneet Tipirneni
7116647947 feat(website): render tsdoc examples (#8494) 2022-08-16 16:33:49 +02:00
iCrawl
c99b808882 ci: fix workflow 2022-08-16 16:24:07 +02:00
iCrawl
a1dddd6b2c build: only build web on vercel 2022-08-16 16:07:08 +02:00
iCrawl
b3db9eef32 build: force a docs rebuild 2022-08-16 15:51:51 +02:00
iCrawl
501945215b ci: use concurrency 2022-08-16 11:00:17 +02:00
iCrawl
e82b2e49f5 fix: use correct env file 2022-08-15 19:17:41 +02:00
iCrawl
5f42b5af30 feat: fetch from local when developing or CI build 2022-08-15 19:13:01 +02:00
iCrawl
35e79b389d fix: correctly handle overflowing content 2022-08-15 18:35:34 +02:00
iCrawl
5dc7946df2 fix: properly render critical styles on the server 2022-08-15 18:23:10 +02:00
iCrawl
1e00f5789e chore: enable kodiak for auto merges 2022-08-15 16:56:30 +02:00
iCrawl
85cb0f25c7 build: run build with concurrency but everything else parallel 2022-08-15 16:16:12 +02:00
iCrawl
3cc893a282 build: enable parallel building for turbo 2022-08-15 16:12:45 +02:00
Marcus Otterström
fc99bf431a Specify time unit in awaitModalSubmit (#8484) 2022-08-15 16:07:03 +02:00
Noel
4ab1d09997 refactor: docs design (#8487) 2022-08-15 14:48:00 +02:00
iCrawl
d09ef1e425 build: switch back to turbo for speedz 2022-08-15 14:19:17 +02:00
iCrawl
d56590a11d chore: use external collection for docgen 2022-08-15 13:50:41 +02:00
iCrawl
c052f56f3e ci: fix typechecking in ci 2022-08-15 00:42:33 +02:00
iCrawl
cb856860b7 ci: install dev deps everywhere 2022-08-14 21:30:55 +02:00
iCrawl
4cf265c7c6 ci: exclude shared match 2022-08-14 21:21:17 +02:00
iCrawl
3ec7ef07a0 ci: correctly reference job 2022-08-14 21:17:12 +02:00
iCrawl
90e7aea443 ci: check for shared additionally to packages 2022-08-14 21:04:51 +02:00
iCrawl
1211c7fc10 ci: fix dependency 2022-08-14 20:12:58 +02:00
iCrawl
84a4b1f58a ci: only test run affected packages 2022-08-14 20:12:02 +02:00
iCrawl
193b252672 docs: fence examples in codeblocks 2022-08-14 19:25:25 +02:00
DD
bc06cc638d feat(WebSocketShard): support new resume url (#8480) 2022-08-14 12:01:35 +02:00
iCrawl
d08da8a212 refactor: properly handling spacing 2022-08-13 20:42:03 +02:00
iCrawl
5360099e5f build: don't build website on ci, let vercel handle it on changes 2022-08-13 20:14:28 +02:00
Suneet Tipirneni
fd4844ddb9 feat(website): add support for function overloads (#8474)
Co-authored-by: Noel <buechler.noel@outlook.com>
2022-08-13 20:14:23 +02:00
iCrawl
8e69efde04 feat(website): breadcrumbs layout 2022-08-12 17:04:12 +02:00
iCrawl
2447165c82 fix(website): accessibility 2022-08-12 17:03:04 +02:00
Jiralite
c97977a3e8 fix(Embed): Reference video in video (#8473) 2022-08-12 05:09:44 +02:00
iCrawl
7666a6c341 chore: update changelog 2022-08-10 20:56:22 +02:00
iCrawl
9d8966fe24 chore(discord.js): release discord.js@14.2.0 2022-08-10 20:50:57 +02:00
iCrawl
4d128acac5 chore: deps 2022-08-10 20:37:25 +02:00
iCrawl
831d6506cb chore: update changelog 2022-08-10 20:26:45 +02:00
RedGuy12
c5b96a185c types(Message): correct bulkDelete return type (#8465)
Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
Co-authored-by: Noel <buechler.noel@outlook.com>
2022-08-10 20:25:12 +02:00
Jiralite
afa27b15c5 fix(ThreadChannel): Handle possibly null parent (#8466) 2022-08-10 20:16:57 +02:00
iCrawl
4d7283933d chore: update changelog 2022-08-10 19:44:23 +02:00
Jan Parisek
452e94fd3e types: fix missing types for mentionable options (#8443)
Co-authored-by: A. Román <kyradiscord@gmail.com>
Co-authored-by: Noel <buechler.noel@outlook.com>
2022-08-10 18:33:52 +02:00
Jiralite
6c6fe74dd8 fix: Remove DM channels from Client#messageDeleteBulk's types (#8460) 2022-08-10 18:29:46 +02:00
A. Román
0e2a09571c fix(Transformers): do not transform Date objects (#8463) 2022-08-10 18:28:35 +02:00
Ryan Munro
0fab869e51 fix(ModalSubmitInteraction): allow deferUpdate (#8455) 2022-08-10 18:25:56 +02:00
advaith
64a4041a05 docs: change registration example to use global commands (#8454) 2022-08-10 18:25:31 +02:00
Jan Parisek
38275fc53d types(ApplicationCommandOption): add ApplicationCommandBooleanOption (#8434) 2022-08-10 18:24:50 +02:00
n1ck_pro
aac8acc22b fix(Guild): unable to fetch templates (#8420) 2022-08-08 11:11:10 +02:00
Ryan Munro
6ef4754d40 docs(Colors): provide enum descriptions (#8437) 2022-08-08 11:10:43 +02:00
Almeida
b8a31360a2 fix(MessageMentions): infinite loop in parsedUsers getter (#8430) 2022-08-08 11:10:32 +02:00
RedGuy12
5b053cf82e docs(AttachmentBuilder): fix #8407 (#8421)
Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
2022-08-08 11:06:11 +02:00
Synbulat Biishev
e72b986939 fix(DataResolver): make Buffer from string (#8416) 2022-08-08 11:05:56 +02:00
Jiralite
3a96ce7970 feat(Guild): Add max_video_channel_users (#8423) 2022-08-08 11:05:40 +02:00
SpaceEEC
359f688555 fix(WebSocketShard): always reconnect on disconnected with 1000 (#8405) 2022-08-01 13:24:25 +02:00
SpaceEEC
3161e1a1ac fix(WebSocketShard): emit errors directly instead of objects (#8406) 2022-08-01 13:24:09 +02:00
iCrawl
4d8361c711 build: fix building actions 2022-07-30 22:02:02 +02:00
iCrawl
d6e4d149fd chore(discord.js): release discord.js@14.1.2 2022-07-30 21:00:09 +02:00
DD
480c85c9c3 fix(errors): error codes (#8398) 2022-07-30 20:49:59 +02:00
166 changed files with 5672 additions and 4232 deletions

11
.github/.kodiak.toml vendored Normal file
View File

@@ -0,0 +1,11 @@
version = 1
[merge]
require_automerge_label = false
blocking_labels = ['blocked']
method = 'squash'
[merge.message]
title = 'pull_request_title'
strip_html_comments = true
include_coauthors = true

View File

@@ -1,13 +0,0 @@
#!/bin/bash
git diff HEAD^ HEAD --quiet .
if [[ "$VERCEL_GIT_COMMIT_REF" == "main" || $? -eq 1 ]]; then
# Proceed with the build
echo "✅ - Proceed"
exit 1;
else
# Don't build
echo "🛑 - Build cancelled"
exit 0;
fi

4
.github/labeler.yml vendored
View File

@@ -1,7 +1,3 @@
chore:
- any: ['*']
all: ['!packages/*', '!packages/**/*']
'packages:builders':
- packages/builders/*
- packages/builders/**/*

View File

@@ -3,8 +3,6 @@ on:
push:
branches:
- 'main'
- 'stable'
- '!docs'
tags:
- '**'
workflow_dispatch:
@@ -12,15 +10,28 @@ on:
ref:
description: 'The branch, tag or SHA to checkout'
required: true
ref_type:
type: choice
description: 'Branch or tag'
options:
- branch
- tag
required: true
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs:
build:
name: Build documentation
runs-on: ubuntu-latest
if: github.repository_owner == 'discordjs'
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
uses: actions/checkout@v3
@@ -32,7 +43,6 @@ jobs:
with:
node-version: 16
cache: 'yarn'
cache-dependency-path: yarn.lock
- name: Install dependencies
run: yarn --immutable
@@ -72,8 +82,10 @@ jobs:
package: ['builders', 'collection', 'discord.js', 'proxy', 'rest', 'voice', 'ws']
runs-on: ubuntu-latest
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
BRANCH_NAME: ${{ github.event.inputs.ref || needs.build.outputs.BRANCH_NAME }}
BRANCH_OR_TAG: ${{ needs.build.outputs.BRANCH_OR_TAG }}
BRANCH_OR_TAG: ${{ github.event.inputs.ref_type || needs.build.outputs.BRANCH_OR_TAG }}
SHA: ${{ needs.build.outputs.SHA }}
steps:
- name: Checkout repository
@@ -84,7 +96,6 @@ jobs:
with:
node-version: 16
cache: 'yarn'
cache-dependency-path: yarn.lock
- name: Install dependencies
run: yarn --immutable
@@ -112,14 +123,14 @@ jobs:
path: 'out'
- name: Extract package and semver from tag
if: ${{ github.event.inputs.ref || env.BRANCH_OR_TAG == 'tag' }}
if: ${{ github.event.inputs.ref_type == 'tag' || env.BRANCH_OR_TAG == 'tag' }}
id: extract-tag
uses: ./packages/actions/src/formatTag
with:
tag: ${{ env.BRANCH_NAME }}
- name: Move docs to correct directory
if: ${{ (github.event.inputs.ref || env.BRANCH_OR_TAG == 'tag') && matrix.package == steps.extract-tag.outputs.package }}
if: ${{ (github.event.inputs.ref_type == 'tag' || env.BRANCH_OR_TAG == 'tag') && matrix.package == steps.extract-tag.outputs.package }}
env:
PACKAGE: ${{ steps.extract-tag.outputs.package }}
SEMVER: ${{ steps.extract-tag.outputs.semver }}
@@ -131,7 +142,7 @@ jobs:
fi
- name: Move docs to correct directory
if: ${{ !github.event.inputs.ref && env.BRANCH_OR_TAG == 'branch' }}
if: ${{ github.event.inputs.ref_type == 'branch' || env.BRANCH_OR_TAG == 'branch' }}
env:
PACKAGE: ${{ matrix.package }}
run: |

View File

@@ -1,8 +1,8 @@
name: npm auto deprecate
on:
workflow_dispatch:
schedule:
- cron: '0 1 * * *'
workflow_dispatch:
jobs:
npm-auto-deprecate:
name: npm auto deprecate
@@ -17,7 +17,6 @@ jobs:
with:
node-version: 16
cache: 'yarn'
cache-dependency-path: yarn.lock
- name: Install dependencies
run: yarn --immutable

View File

@@ -1,8 +1,8 @@
name: Publish dev docker images
on:
workflow_dispatch:
schedule:
- cron: '0 */12 * * *'
workflow_dispatch:
jobs:
docker-publish:
name: Docker publish

View File

@@ -1,8 +1,8 @@
name: Publish dev
on:
workflow_dispatch:
schedule:
- cron: '0 */12 * * *'
workflow_dispatch:
jobs:
npm-publish:
name: npm publish
@@ -25,6 +25,9 @@ jobs:
- package: '@discordjs/ws'
folder: 'ws'
runs-on: ubuntu-latest
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
if: github.repository_owner == 'discordjs'
steps:
- name: Checkout repository
@@ -36,7 +39,6 @@ jobs:
node-version: 16
registry-url: https://registry.npmjs.org/
cache: 'yarn'
cache-dependency-path: yarn.lock
- name: Install dependencies
run: yarn --immutable

View File

@@ -1,9 +1,18 @@
name: Tests
on: [push, pull_request]
on:
push:
pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
cancel-in-progress: true
jobs:
tests:
name: Tests
runs-on: ubuntu-latest
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
NEXT_PUBLIC_LOCAL_DEV: true
steps:
- name: Checkout repository
uses: actions/checkout@v3
@@ -13,10 +22,9 @@ jobs:
with:
node-version: 16
cache: 'yarn'
cache-dependency-path: yarn.lock
- name: Install dependencies
run: yarn --immutable
run: yarn install --immutable
- name: Build dependencies
run: yarn build
@@ -28,5 +36,5 @@ jobs:
run: yarn test
- name: Upload Coverage
uses: ./packages/actions/src/uploadCoverage
if: github.repository_owner == 'discordjs'
uses: ./packages/actions/src/uploadCoverage

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"
"src/**.ts": "vitest related --run"
}

View File

@@ -1,36 +0,0 @@
diff --git a/dist/rollup-plugin-typescript2.cjs.js b/dist/rollup-plugin-typescript2.cjs.js
index 9ab972b041cc76f8f786d6a20f3efb53c364cad6..13e056a3c0971eb18b307d91fad096a9f3b9de79 100644
--- a/dist/rollup-plugin-typescript2.cjs.js
+++ b/dist/rollup-plugin-typescript2.cjs.js
@@ -29799,6 +29799,13 @@ const typescript = (options) => {
declarations[key] = { type: result.dts, map: result.dtsmap };
context.debug(() => `${safe.exports.blue("generated declarations")} for '${key}'`);
}
+ // if a user sets this compilerOption, they probably want another plugin (e.g. Babel, ESBuild) to transform their TS instead, while rpt2 just type-checks and/or outputs declarations
+ // note that result.code is non-existent if emitDeclarationOnly per https://github.com/ezolenko/rollup-plugin-typescript2/issues/268
+ if (parsedConfig.options.emitDeclarationOnly)
+ {
+ context.debug(() => `${blue("emitDeclarationOnly")} enabled, not transforming TS'`);
+ return undefined;
+ }
const transformResult = { code: result.code, map: { mappings: "" } };
if (result.map) {
if (pluginOptions.sourceMapCallback)
diff --git a/dist/rollup-plugin-typescript2.es.js b/dist/rollup-plugin-typescript2.es.js
index e43bf8f03bc6792b61d8352e04bb6466712426c2..420e8f0d0d109076bc72e9d60240077235a9ba11 100644
--- a/dist/rollup-plugin-typescript2.es.js
+++ b/dist/rollup-plugin-typescript2.es.js
@@ -29770,6 +29770,13 @@ const typescript = (options) => {
declarations[key] = { type: result.dts, map: result.dtsmap };
context.debug(() => `${safe.exports.blue("generated declarations")} for '${key}'`);
}
+ // if a user sets this compilerOption, they probably want another plugin (e.g. Babel, ESBuild) to transform their TS instead, while rpt2 just type-checks and/or outputs declarations
+ // note that result.code is non-existent if emitDeclarationOnly per https://github.com/ezolenko/rollup-plugin-typescript2/issues/268
+ if (parsedConfig.options.emitDeclarationOnly)
+ {
+ context.debug(() => `${blue("emitDeclarationOnly")} enabled, not transforming TS'`);
+ return undefined;
+ }
const transformResult = { code: result.code, map: { mappings: "" } };
if (result.map) {
if (pluginOptions.sourceMapCallback)

View File

@@ -72,7 +72,7 @@ const rest = new REST({ version: '10' }).setToken('token');
try {
console.log('Started refreshing application (/) commands.');
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID), { body: commands });
await rest.put(Routes.applicationCommands(CLIENT_ID), { body: commands });
console.log('Successfully reloaded application (/) commands.');
} catch (error) {

View File

@@ -1,5 +1,6 @@
import { relative, resolve } from 'node:path';
import glob from 'fast-glob';
import isCi from 'is-ci';
import typescript from 'rollup-plugin-typescript2';
import { defineBuildConfig, BuildEntry } from 'unbuild';
@@ -26,7 +27,7 @@ export function createUnbuildConfig({
preserveModules = true,
preserveModulesRoot = 'src',
declaration = true,
typeCheck = false,
typeCheck = isCi,
}: Partial<ConfigOptions> = {}) {
const files = glob
.sync('**', { cwd: 'src' })
@@ -45,6 +46,7 @@ export function createUnbuildConfig({
cjsBridge,
json: {
namedExports: false,
preferConst: true,
},
},

View File

@@ -4,13 +4,13 @@
"description": "A powerful library for interacting with the Discord API",
"private": true,
"scripts": {
"build": "yarn workspaces foreach --parallel --topological run build",
"test": "yarn workspaces foreach --parallel --topological run test",
"lint": "yarn workspaces foreach --parallel --topological run lint",
"format": "yarn workspaces foreach --parallel --topological run format",
"fmt": "yarn format",
"build": "turbo run build",
"test": "turbo run test --parallel",
"lint": "turbo run lint --parallel",
"format": "turbo run format --parallel",
"fmt": "turbo run format --parallel",
"postinstall": "is-ci || husky install",
"docs": "yarn workspaces foreach --parallel --topological run docs",
"docs": "turbo run docs --parallel",
"update": "yarn upgrade-interactive"
},
"contributors": [
@@ -39,25 +39,18 @@
"devDependencies": {
"@commitlint/cli": "^17.0.3",
"@commitlint/config-angular": "^17.0.3",
"@favware/cliff-jumper": "^1.8.5",
"@favware/npm-deprecate": "^1.0.4",
"@typescript-eslint/eslint-plugin": "^5.31.0",
"@typescript-eslint/parser": "^5.31.0",
"@favware/cliff-jumper": "^1.8.7",
"@favware/npm-deprecate": "^1.0.5",
"@types/is-ci": "^3.0.0",
"conventional-changelog-cli": "^2.2.2",
"eslint": "^8.20.0",
"eslint-config-marine": "^9.4.1",
"eslint-config-prettier": "^8.5.0",
"eslint-import-resolver-typescript": "^3.3.0",
"eslint-plugin-import": "^2.26.0",
"fast-glob": "^3.2.11",
"husky": "^8.0.1",
"is-ci": "^3.0.1",
"lint-staged": "^13.0.3",
"prettier": "^2.7.1",
"turbo": "^1.4.3",
"typescript": "^4.7.4"
},
"resolutions": {
"rollup-plugin-typescript2@0.32.1": "patch:rollup-plugin-typescript2@npm:0.32.1#.yarn/patches/rollup-plugin-typescript2-npm-0.32.1-b5887420f2.patch",
"@microsoft/tsdoc-config": "patch:@microsoft/tsdoc-config@npm:0.16.1#.yarn/patches/@microsoft-tsdoc-config-npm-0.16.1-81031b1bbf.patch"
},
"engines": {

View File

@@ -1,3 +1,11 @@
import { createUnbuildConfig } from '../../build.config';
export default createUnbuildConfig({ minify: true, emitCJS: false });
export default createUnbuildConfig({
entries: [
{ builder: 'rollup', input: 'src/index' },
{ builder: 'rollup', input: 'src/formatTag/index' },
],
preserveModules: false,
minify: true,
emitCJS: false,
});

View File

@@ -6,8 +6,8 @@
"scripts": {
"test": "vitest run",
"build": "unbuild",
"lint": "prettier --check . && eslint src __tests__ --ext mjs,js,ts",
"format": "prettier --write . && eslint src __tests__ --ext mjs,js,ts --fix",
"lint": "prettier --check . && TIMING=1 eslint src __tests__ --ext mjs,js,ts",
"format": "prettier --write . && TIMING=1 eslint src __tests__ --ext mjs,js,ts --fix",
"fmt": "yarn format"
},
"main": "./dist/index.mjs",
@@ -39,18 +39,24 @@
},
"homepage": "https://discord.js.org",
"dependencies": {
"@actions/core": "^1.9.0",
"@actions/core": "^1.9.1",
"tslib": "^2.4.0"
},
"devDependencies": {
"@types/node": "^16.11.46",
"c8": "^7.12.0",
"eslint": "^8.20.0",
"@types/node": "^16.11.52",
"@typescript-eslint/eslint-plugin": "^5.33.1",
"@typescript-eslint/parser": "^5.33.1",
"@vitest/coverage-c8": "^0.22.1",
"eslint": "^8.22.0",
"eslint-config-marine": "^9.4.1",
"eslint-config-prettier": "^8.5.0",
"eslint-import-resolver-typescript": "^3.4.2",
"eslint-plugin-import": "^2.26.0",
"prettier": "^2.7.1",
"rollup-plugin-typescript2": "0.32.1",
"rollup-plugin-typescript2": "^0.33.0",
"typescript": "^4.7.4",
"unbuild": "^0.7.6",
"vitest": "^0.19.1"
"unbuild": "^0.8.9",
"vitest": "^0.22.1"
},
"engines": {
"node": ">=16.9.0"

View File

@@ -11,4 +11,4 @@ outputs:
description: 'The semver string that was extracted from this tag'
runs:
using: node16
main: ../../dist/formatTag/index.mjs
main: ../../dist/index.mjs

View File

@@ -1,3 +1,7 @@
{
"extends": "../../.eslintrc.json"
"extends": "../../.eslintrc.json",
"plugins": ["eslint-plugin-tsdoc"],
"rules": {
"tsdoc/syntax": "warn"
}
}

View File

@@ -5,8 +5,8 @@
"scripts": {
"test": "vitest run",
"build": "unbuild",
"lint": "prettier --check . && eslint src __tests__ --ext mjs,js,ts",
"format": "prettier --write . && eslint src __tests__ --ext mjs,js,ts --fix",
"lint": "prettier --check . && TIMING=1 eslint src __tests__ --ext mjs,js,ts",
"format": "prettier --write . && TIMING=1 eslint src __tests__ --ext mjs,js,ts --fix",
"fmt": "yarn format",
"docs": "downlevel-dts . docs --to=3.7 && docgen -i src/index.ts -c docs/index.json -o docs/docs.json --typescript && api-extractor run --local",
"prepack": "yarn lint && yarn test && yarn build",
@@ -55,24 +55,31 @@
"homepage": "https://discord.js.org",
"dependencies": {
"@sapphire/shapeshift": "^3.5.1",
"discord-api-types": "^0.36.3",
"discord-api-types": "^0.37.3",
"fast-deep-equal": "^3.1.3",
"ts-mixer": "^6.0.1",
"tslib": "^2.4.0"
},
"devDependencies": {
"@discordjs/docgen": "workspace:^",
"@favware/cliff-jumper": "^1.8.5",
"@microsoft/api-extractor": "^7.28.6",
"@types/node": "^16.11.46",
"c8": "^7.12.0",
"@favware/cliff-jumper": "^1.8.7",
"@microsoft/api-extractor": "^7.29.3",
"@types/node": "^16.11.52",
"@typescript-eslint/eslint-plugin": "^5.33.1",
"@typescript-eslint/parser": "^5.33.1",
"@vitest/coverage-c8": "^0.22.1",
"downlevel-dts": "^0.10.0",
"eslint": "^8.20.0",
"eslint": "^8.22.0",
"eslint-config-marine": "^9.4.1",
"eslint-config-prettier": "^8.5.0",
"eslint-import-resolver-typescript": "^3.4.2",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-tsdoc": "^0.2.16",
"prettier": "^2.7.1",
"rollup-plugin-typescript2": "0.32.1",
"rollup-plugin-typescript2": "^0.33.0",
"typescript": "^4.7.4",
"unbuild": "^0.7.6",
"vitest": "^0.19.1"
"unbuild": "^0.8.9",
"vitest": "^0.22.1"
},
"engines": {
"node": ">=16.9.0"

View File

@@ -22,6 +22,8 @@ export type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalAction
/**
* Represents an action row component
*
* @typeParam T - The types of components this action row holds
*/
export class ActionRowBuilder<T extends AnyComponentBuilder> extends ComponentBuilder<
APIActionRowComponent<APIMessageActionRowComponent | APIModalActionRowComponent>
@@ -56,6 +58,9 @@ export class ActionRowBuilder<T extends AnyComponentBuilder> extends ComponentBu
return this;
}
/**
* {@inheritDoc ComponentBuilder.toJSON}
*/
public toJSON(): APIActionRowComponent<ReturnType<T['toJSON']>> {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return {

View File

@@ -10,6 +10,8 @@ export type AnyAPIActionRowComponent = APIActionRowComponentTypes | APIActionRow
/**
* Represents a discord component
*
* @typeParam DataType - The type of internal API data that is stored within the component
*/
export abstract class ComponentBuilder<
DataType extends Partial<APIBaseComponent<ComponentType>> = APIBaseComponent<ComponentType>,
@@ -20,6 +22,13 @@ export abstract class ComponentBuilder<
*/
public readonly data: Partial<DataType>;
/**
* Serializes this component to an API-compatible JSON object
*
* @remarks
* This method runs validations on the data before serializing it.
* As such, it may throw an error if the data is invalid.
*/
public abstract toJSON(): AnyAPIActionRowComponent;
public constructor(data: Partial<DataType>) {

View File

@@ -21,6 +21,35 @@ import { ComponentBuilder } from '../Component';
* Represents a button component
*/
export class ButtonBuilder extends ComponentBuilder<APIButtonComponent> {
/**
* Creates a new button from API data
* @param data - The API data to create this button with
*
* @example
* Creating a button from an API data object
* ```ts
* const button = new ButtonBuilder({
* style: 'primary',
* label: 'Click Me',
* emoji: {
* name: ':smile:',
* id: '12345678901234567890123456789012',
* },
* custom_id: '12345678901234567890123456789012',
* });
* ```
*
* @example
* Creating a button using setters and API data
* ```ts
* const button = new ButtonBuilder({
* style: 'primary',
* label: 'Click Me',
* })
* .setEmoji({ name: ':smile:', id: '12345678901234567890123456789012' })
* .setCustomId('12345678901234567890123456789012');
* ```
*/
public constructor(data?: Partial<APIButtonComponent>) {
super({ type: ComponentType.Button, ...data });
}
@@ -38,6 +67,10 @@ export class ButtonBuilder extends ComponentBuilder<APIButtonComponent> {
/**
* Sets the URL for this button
*
* @remarks
* This method is only available to buttons using the `Link` button style.
* Only three types of URL schemes are currently supported: `https://`, `http://` and `discord://`
*
* @param url - The URL to open when this button is clicked
*/
public setURL(url: string) {
@@ -48,6 +81,9 @@ export class ButtonBuilder extends ComponentBuilder<APIButtonComponent> {
/**
* Sets the custom id for this button
*
* @remarks
* This method is only applicable to buttons that are not using the `Link` button style.
*
* @param customId - The custom id to use for this button
*/
public setCustomId(customId: string) {
@@ -85,6 +121,9 @@ export class ButtonBuilder extends ComponentBuilder<APIButtonComponent> {
return this;
}
/**
* {@inheritDoc ComponentBuilder.toJSON}
*/
public toJSON(): APIButtonComponent {
validateRequiredButtonParameters(
this.data.style,

View File

@@ -116,6 +116,9 @@ export class SelectMenuBuilder extends ComponentBuilder<APISelectMenuComponent>
return this;
}
/**
* {@inheritDoc ComponentBuilder.toJSON}
*/
public toJSON(): APISelectMenuComponent {
validateRequiredSelectMenuParameters(this.options, this.data.custom_id);
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions

View File

@@ -1,4 +1,5 @@
import type { APIMessageComponentEmoji, APISelectMenuOption } from 'discord-api-types/v10';
import type { JSONEncodable } from '../../util/jsonEncodable';
import {
defaultValidator,
@@ -10,7 +11,7 @@ import {
/**
* Represents a option within a select menu component
*/
export class SelectMenuOptionBuilder {
export class SelectMenuOptionBuilder implements JSONEncodable<APISelectMenuOption> {
public constructor(public data: Partial<APISelectMenuOption> = {}) {}
/**
@@ -63,6 +64,9 @@ export class SelectMenuOptionBuilder {
return this;
}
/**
* {@inheritDoc ComponentBuilder.toJSON}
*/
public toJSON(): APISelectMenuOption {
validateRequiredSelectMenuOptionParameters(this.data.label, this.data.value);
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions

View File

@@ -10,11 +10,15 @@ import {
labelValidator,
textInputStyleValidator,
} from './Assertions';
import type { Equatable } from '../../util/equatable';
import { isJSONEncodable, type JSONEncodable } from '../../util/jsonEncodable';
import { customIdValidator } from '../Assertions';
import { ComponentBuilder } from '../Component';
export class TextInputBuilder extends ComponentBuilder<APITextInputComponent> {
export class TextInputBuilder
extends ComponentBuilder<APITextInputComponent>
implements Equatable<JSONEncodable<APITextInputComponent> | APITextInputComponent>
{
public constructor(data?: APITextInputComponent & { type?: ComponentType.TextInput }) {
super({ type: ComponentType.TextInput, ...data });
}
@@ -99,6 +103,9 @@ export class TextInputBuilder extends ComponentBuilder<APITextInputComponent> {
return this;
}
/**
* {@inheritDoc ComponentBuilder.toJSON}
*/
public toJSON(): APITextInputComponent {
validateRequiredParameters(this.data.custom_id, this.data.style, this.data.label);
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
@@ -107,6 +114,9 @@ export class TextInputBuilder extends ComponentBuilder<APITextInputComponent> {
} as APITextInputComponent;
}
/**
* {@inheritDoc Equatable.equals}
*/
public equals(other: JSONEncodable<APITextInputComponent> | APITextInputComponent): boolean {
if (isJSONEncodable(other)) {
return isEqual(other.toJSON(), this.data);

View File

@@ -35,7 +35,7 @@ export class ContextMenuCommandBuilder {
* Whether the command is enabled by default when the app is added to a guild
*
* @deprecated This property is deprecated and will be removed in the future.
* You should use `setDefaultMemberPermissions` or `setDMPermission` instead.
* You should use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.
*/
public readonly default_permission: boolean | undefined = undefined;
@@ -86,7 +86,7 @@ export class ContextMenuCommandBuilder {
* @param value - Whether or not to enable this command by default
*
* @see https://discord.com/developers/docs/interactions/application-commands#permissions
* @deprecated Use `setDefaultMemberPermissions` or `setDMPermission` instead.
* @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.
*/
public setDefaultPermission(value: boolean) {
// Assert the value matches the conditions

View File

@@ -70,6 +70,9 @@ export class ModalBuilder implements JSONEncodable<APIModalInteractionResponseCa
return this;
}
/**
* {@inheritDoc ComponentBuilder.toJSON}
*/
public toJSON(): APIModalInteractionResponseCallbackData {
validateRequiredParameters(this.data.custom_id, this.data.title, this.components);
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions

View File

@@ -49,7 +49,7 @@ export class SlashCommandBuilder {
* Whether the command is enabled by default when the app is added to a guild
*
* @deprecated This property is deprecated and will be removed in the future.
* You should use `setDefaultMemberPermissions` or `setDMPermission` instead.
* You should use {@link (SlashCommandBuilder:class).setDefaultMemberPermissions} or {@link (SlashCommandBuilder:class).setDMPermission} instead.
*/
public readonly default_permission: boolean | undefined = undefined;
@@ -89,7 +89,7 @@ export class SlashCommandBuilder {
* @param value - Whether or not to enable this command by default
*
* @see https://discord.com/developers/docs/interactions/application-commands#permissions
* @deprecated Use `setDefaultMemberPermissions` or `setDMPermission` instead.
* @deprecated Use {@link (SlashCommandBuilder:class).setDefaultMemberPermissions} or {@link (SlashCommandBuilder:class).setDMPermission} instead.
*/
public setDefaultPermission(value: boolean) {
// Assert the value matches the conditions

View File

@@ -14,6 +14,9 @@ export class SlashCommandIntegerOption
{
public readonly type = ApplicationCommandOptionType.Integer as const;
/**
* {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}
*/
public setMaxValue(max: number): this {
numberValidator.parse(max);
@@ -22,6 +25,9 @@ export class SlashCommandIntegerOption
return this;
}
/**
* {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}
*/
public setMinValue(min: number): this {
numberValidator.parse(min);

View File

@@ -14,6 +14,9 @@ export class SlashCommandNumberOption
{
public readonly type = ApplicationCommandOptionType.Number as const;
/**
* {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}
*/
public setMaxValue(max: number): this {
numberValidator.parse(max);
@@ -22,6 +25,9 @@ export class SlashCommandNumberOption
return this;
}
/**
* {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}
*/
public setMinValue(min: number): this {
numberValidator.parse(min);

View File

@@ -52,9 +52,31 @@ export class EmbedBuilder {
}
/**
* Adds fields to the embed (max 25)
* Appends fields to the embed
*
* @param fields The fields to add
* @remarks
* This method accepts either an array of fields or a variable number of field parameters.
* The maximum amount of fields that can be added is 25.
*
* @example
* Using an array
* ```ts
* const fields: APIEmbedField[] = ...;
* const embed = new EmbedBuilder()
* .addFields(fields);
* ```
*
* @example
* Using rest parameters (variadic)
* ```ts
* const embed = new EmbedBuilder()
* .addFields(
* { name: 'Field 1', value: 'Value 1' },
* { name: 'Field 2', value: 'Value 2' },
* );
* ```
*
* @param fields - The fields to add
*/
public addFields(...fields: RestOrArray<APIEmbedField>): this {
fields = normalizeArray(fields);
@@ -70,11 +92,37 @@ export class EmbedBuilder {
}
/**
* Removes, replaces, or inserts fields in the embed (max 25)
* Removes, replaces, or inserts fields in the embed.
*
* @param index The index to start at
* @param deleteCount The number of fields to remove
* @param fields The replacing field objects
* @remarks
* This method behaves similarly
* to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice}.
* The maximum amount of fields that can be added is 25.
*
* It's useful for modifying and adjusting order of the already-existing fields of an embed.
*
* @example
* Remove the first field
* ```ts
* embed.spliceFields(0, 1);
* ```
*
* @example
* Remove the first n fields
* ```ts
* const n = 4
* embed.spliceFields(0, n);
* ```
*
* @example
* Remove the last field
* ```ts
* embed.spliceFields(-1, 1);
* ```
*
* @param index - The index to start at
* @param deleteCount - The number of fields to remove
* @param fields - The replacing field objects
*/
public spliceFields(index: number, deleteCount: number, ...fields: APIEmbedField[]): this {
// Ensure adding these fields won't exceed the 25 field limit
@@ -88,8 +136,15 @@ export class EmbedBuilder {
}
/**
* Sets the embed's fields (max 25).
* @param fields The fields to set
* Sets the embed's fields
*
* @remarks
* This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically,
* it splices the entire array of fields, replacing them with the provided fields.
*
* You can set a maximum of 25 fields.
*
* @param fields - The fields to set
*/
public setFields(...fields: RestOrArray<APIEmbedField>) {
this.spliceFields(0, this.data.fields?.length ?? 0, ...normalizeArray(fields));
@@ -99,7 +154,7 @@ export class EmbedBuilder {
/**
* Sets the author of this embed
*
* @param options The options for the author
* @param options - The options for the author
*/
public setAuthor(options: EmbedAuthorOptions | null): this {
@@ -118,7 +173,7 @@ export class EmbedBuilder {
/**
* Sets the color of this embed
*
* @param color The color of the embed
* @param color - The color of the embed
*/
public setColor(color: number | RGBTuple | null): this {
// Data assertions
@@ -136,7 +191,7 @@ export class EmbedBuilder {
/**
* Sets the description of this embed
*
* @param description The description
* @param description - The description
*/
public setDescription(description: string | null): this {
// Data assertions
@@ -149,7 +204,7 @@ export class EmbedBuilder {
/**
* Sets the footer of this embed
*
* @param options The options for the footer
* @param options - The options for the footer
*/
public setFooter(options: EmbedFooterOptions | null): this {
if (options === null) {
@@ -167,7 +222,7 @@ export class EmbedBuilder {
/**
* Sets the image of this embed
*
* @param url The URL of the image
* @param url - The URL of the image
*/
public setImage(url: string | null): this {
// Data assertions
@@ -180,7 +235,7 @@ export class EmbedBuilder {
/**
* Sets the thumbnail of this embed
*
* @param url The URL of the thumbnail
* @param url - The URL of the thumbnail
*/
public setThumbnail(url: string | null): this {
// Data assertions
@@ -193,7 +248,7 @@ export class EmbedBuilder {
/**
* Sets the timestamp of this embed
*
* @param timestamp The timestamp or date
* @param timestamp - The timestamp or date
*/
public setTimestamp(timestamp: number | Date | null = Date.now()): this {
// Data assertions
@@ -206,7 +261,7 @@ export class EmbedBuilder {
/**
* Sets the title of this embed
*
* @param title The title
* @param title - The title
*/
public setTitle(title: string | null): this {
// Data assertions
@@ -219,7 +274,7 @@ export class EmbedBuilder {
/**
* Sets the URL of this embed
*
* @param url The URL
* @param url - The URL
*/
public setURL(url: string | null): this {
// Data assertions

View File

@@ -1,3 +1,9 @@
/**
* Represents a structure that can be checked against another
* given structure for equality
*
* @typeParam T - The type of object to compare the current object to
*/
export interface Equatable<T> {
/**
* Whether or not this is equal to another structure

View File

@@ -1,3 +1,8 @@
/**
* Represents an object capable of representing itself as a JSON object
*
* @typeParam T - The JSON type corresponding to {@link JSONEncodable.toJSON} outputs.
*/
export interface JSONEncodable<T> {
/**
* Transforms this object to its JSON format

View File

@@ -1,3 +1,7 @@
{
"extends": "../../.eslintrc.json"
"extends": "../../.eslintrc.json",
"plugins": ["eslint-plugin-tsdoc"],
"rules": {
"tsdoc/syntax": "warn"
}
}

View File

@@ -5,8 +5,8 @@
"scripts": {
"test": "vitest run",
"build": "unbuild",
"lint": "prettier --check . && eslint src __tests__ --ext mjs,js,ts",
"format": "prettier --write . && eslint src __tests__ --ext mjs,js,ts --fix",
"lint": "prettier --check . && TIMING=1 eslint src __tests__ --ext mjs,js,ts",
"format": "prettier --write . && TIMING=1 eslint src __tests__ --ext mjs,js,ts --fix",
"fmt": "yarn format",
"docs": "downlevel-dts . docs --to=3.7 && docgen -i src/index.ts -c docs/index.json -o docs/docs.json --typescript && api-extractor run --local",
"prepack": "yarn lint && yarn test && yarn build",
@@ -51,17 +51,24 @@
"homepage": "https://discord.js.org",
"devDependencies": {
"@discordjs/docgen": "workspace:^",
"@favware/cliff-jumper": "^1.8.5",
"@microsoft/api-extractor": "^7.28.6",
"@types/node": "^16.11.46",
"c8": "^7.12.0",
"@favware/cliff-jumper": "^1.8.7",
"@microsoft/api-extractor": "^7.29.3",
"@types/node": "^16.11.52",
"@typescript-eslint/eslint-plugin": "^5.33.1",
"@typescript-eslint/parser": "^5.33.1",
"@vitest/coverage-c8": "^0.22.1",
"downlevel-dts": "^0.10.0",
"eslint": "^8.20.0",
"eslint": "^8.22.0",
"eslint-config-marine": "^9.4.1",
"eslint-config-prettier": "^8.5.0",
"eslint-import-resolver-typescript": "^3.4.2",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-tsdoc": "^0.2.16",
"prettier": "^2.7.1",
"rollup-plugin-typescript2": "0.32.1",
"rollup-plugin-typescript2": "^0.33.0",
"typescript": "^4.7.4",
"unbuild": "^0.7.6",
"vitest": "^0.19.1"
"unbuild": "^0.8.9",
"vitest": "^0.22.1"
},
"engines": {
"node": ">=16.9.0"

View File

@@ -28,6 +28,9 @@ export interface Collection<K, V> extends Map<K, V> {
/**
* A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has
* an ID, for significantly improved performance and ease-of-use.
*
* @typeParam K - The key type this collection holds
* @typeParam V - The value type this collection holds
*/
export class Collection<K, V> extends Map<K, V> {
/**
@@ -37,7 +40,9 @@ export class Collection<K, V> extends Map<K, V> {
* @param defaultValueGenerator - A function that generates the default value
*
* @example
* ```ts
* collection.ensure(guildId, () => defaultGuildConfig);
* ```
*/
public ensure(key: K, defaultValueGenerator: (key: K, collection: this) => V): V {
if (this.has(key)) return this.get(key)!;
@@ -230,7 +235,9 @@ export class Collection<K, V> extends Map<K, V> {
* @param thisArg - Value to use as `this` when executing function
*
* @example
* ```ts
* collection.find(user => user.username === 'Bob');
* ```
*/
public find<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined;
public find(fn: (value: V, key: K, collection: this) => boolean): V | undefined;
@@ -257,7 +264,9 @@ export class Collection<K, V> extends Map<K, V> {
* @param thisArg - Value to use as `this` when executing function
*
* @example
* ```ts
* collection.findKey(user => user.username === 'Bob');
* ```
*/
public findKey<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined;
public findKey(fn: (value: V, key: K, collection: this) => boolean): K | undefined;
@@ -304,7 +313,9 @@ export class Collection<K, V> extends Map<K, V> {
* @param thisArg - Value to use as `this` when executing function
*
* @example
* ```ts
* collection.filter(user => user.username === 'Bob');
* ```
*/
public filter<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): Collection<K2, V>;
public filter<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): Collection<K, V2>;
@@ -336,7 +347,9 @@ export class Collection<K, V> extends Map<K, V> {
* @param thisArg - Value to use as `this` when executing function
*
* @example
* ```ts
* const [big, small] = collection.partition(guild => guild.memberCount > 250);
* ```
*/
public partition<K2 extends K>(
fn: (value: V, key: K, collection: this) => key is K2,
@@ -385,7 +398,9 @@ export class Collection<K, V> extends Map<K, V> {
* @param thisArg - Value to use as `this` when executing function
*
* @example
* ```ts
* collection.flatMap(guild => guild.members.cache);
* ```
*/
public flatMap<T>(fn: (value: V, key: K, collection: this) => Collection<K, T>): Collection<K, T>;
public flatMap<T, This>(
@@ -405,7 +420,9 @@ export class Collection<K, V> extends Map<K, V> {
* @param thisArg - Value to use as `this` when executing function
*
* @example
* ```ts
* collection.map(user => user.tag);
* ```
*/
public map<T>(fn: (value: V, key: K, collection: this) => T): T[];
public map<This, T>(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[];
@@ -429,7 +446,9 @@ export class Collection<K, V> extends Map<K, V> {
* @param thisArg - Value to use as `this` when executing function
*
* @example
* ```ts
* collection.mapValues(user => user.tag);
* ```
*/
public mapValues<T>(fn: (value: V, key: K, collection: this) => T): Collection<K, T>;
public mapValues<This, T>(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection<K, T>;
@@ -449,7 +468,9 @@ export class Collection<K, V> extends Map<K, V> {
* @param thisArg - Value to use as `this` when executing function
*
* @example
* ```ts
* collection.some(user => user.discriminator === '0000');
* ```
*/
public some(fn: (value: V, key: K, collection: this) => boolean): boolean;
public some<T>(fn: (this: T, value: V, key: K, collection: this) => boolean, thisArg: T): boolean;
@@ -470,7 +491,9 @@ export class Collection<K, V> extends Map<K, V> {
* @param thisArg - Value to use as `this` when executing function
*
* @example
* ```ts
* collection.every(user => !user.bot);
* ```
*/
public every<K2 extends K>(fn: (value: V, key: K, collection: this) => key is K2): this is Collection<K2, V>;
public every<V2 extends V>(fn: (value: V, key: K, collection: this) => value is V2): this is Collection<K, V2>;
@@ -502,7 +525,9 @@ export class Collection<K, V> extends Map<K, V> {
* @param initialValue - Starting value for the accumulator
*
* @example
* ```ts
* collection.reduce((acc, guild) => acc + guild.memberCount, 0);
* ```
*/
public reduce<T>(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T {
if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);
@@ -540,10 +565,12 @@ export class Collection<K, V> extends Map<K, V> {
* @param thisArg - Value to use as `this` when executing function
*
* @example
* ```ts
* collection
* .each(user => console.log(user.username))
* .filter(user => user.bot)
* .each(user => console.log(user.username));
* ```
*/
public each(fn: (value: V, key: K, collection: this) => void): this;
public each<T>(fn: (this: T, value: V, key: K, collection: this) => void, thisArg: T): this;
@@ -560,10 +587,12 @@ export class Collection<K, V> extends Map<K, V> {
* @param thisArg - Value to use as `this` when executing function
*
* @example
* ```ts
* collection
* .tap(coll => console.log(coll.size))
* .filter(user => user.bot)
* .tap(coll => console.log(coll.size))
* ```
*/
public tap(fn: (collection: this) => void): this;
public tap<T>(fn: (this: T, collection: this) => void, thisArg: T): this;
@@ -578,7 +607,9 @@ export class Collection<K, V> extends Map<K, V> {
* Creates an identical shallow copy of this collection.
*
* @example
* ```ts
* const newColl = someColl.clone();
* ```
*/
public clone(): Collection<K, V> {
return new this.constructor[Symbol.species](this);
@@ -590,7 +621,9 @@ export class Collection<K, V> extends Map<K, V> {
* @param collections - Collections to merge
*
* @example
* ```ts
* const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);
* ```
*/
public concat(...collections: ReadonlyCollection<K, V>[]) {
const newColl = this.clone();
@@ -631,7 +664,9 @@ export class Collection<K, V> extends Map<K, V> {
* If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.
*
* @example
* ```ts
* collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
* ```
*/
public sort(compareFunction: Comparator<K, V> = Collection.defaultSort) {
const entries = [...this.entries()];
@@ -686,6 +721,7 @@ export class Collection<K, V> extends Map<K, V> {
* @param whenInBoth - Function getting the result if the entry exists in both Collections
*
* @example
* ```ts
* // Sums up the entries in two collections.
* coll.merge(
* other,
@@ -693,8 +729,10 @@ export class Collection<K, V> extends Map<K, V> {
* y => ({ keep: true, value: y }),
* (x, y) => ({ keep: true, value: x + y }),
* );
* ```
*
* @example
* ```ts
* // Intersects two collections in a left-biased manner.
* coll.merge(
* other,
@@ -702,6 +740,7 @@ export class Collection<K, V> extends Map<K, V> {
* y => ({ keep: false }),
* (x, _) => ({ keep: true, value: x }),
* );
* ```
*/
public merge<T, R>(
other: ReadonlyCollection<K, T>,
@@ -739,7 +778,9 @@ export class Collection<K, V> extends Map<K, V> {
* according to the string conversion of each element.
*
* @example
* ```ts
* collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);
* ```
*/
public sorted(compareFunction: Comparator<K, V> = Collection.defaultSort) {
return new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk));
@@ -761,8 +802,10 @@ export class Collection<K, V> extends Map<K, V> {
* @param combine - Function to combine an existing entry with a new one
*
* @example
* ```ts
* Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y);
* // returns Collection { "a" => 3, "b" => 2 }
* ```
*/
public static combineEntries<K, V>(
entries: Iterable<[K, V]>,

View File

@@ -2,6 +2,44 @@
All notable changes to this project will be documented in this file.
# [14.2.0](https://github.com/discordjs/discord.js/compare/14.1.2...14.2.0) - (2022-08-10)
## Bug Fixes
- **ThreadChannel:** Handle possibly `null` parent (#8466) ([afa27b1](https://github.com/discordjs/discord.js/commit/afa27b15c5b92bc8d55b8285834d8e03f6692d06))
- Remove DM channels from `Client#messageDeleteBulk`'s types (#8460) ([6c6fe74](https://github.com/discordjs/discord.js/commit/6c6fe74dd84859c5319efa999404e8168f189710))
- **Transformers:** Do not transform `Date` objects (#8463) ([0e2a095](https://github.com/discordjs/discord.js/commit/0e2a09571c8e5ee61153b04e45334a226a1b4534))
- **ModalSubmitInteraction:** Allow deferUpdate (#8455) ([0fab869](https://github.com/discordjs/discord.js/commit/0fab869e5179dca7ddec75b5519615278e51ad82))
- **Guild:** Unable to fetch templates (#8420) ([aac8acc](https://github.com/discordjs/discord.js/commit/aac8acc22be7d7af99933ef099eca7deda43cb40))
- **MessageMentions:** Infinite loop in `parsedUsers` getter (#8430) ([b8a3136](https://github.com/discordjs/discord.js/commit/b8a31360a220e3d796f5381bd215d30a379ecb7c))
- **DataResolver:** Make `Buffer` from string (#8416) ([e72b986](https://github.com/discordjs/discord.js/commit/e72b986939e2958547c0e54d6d27472c8d111609))
## Documentation
- Change registration example to use global commands (#8454) ([64a4041](https://github.com/discordjs/discord.js/commit/64a4041a05e9514334a9f9e1f38a1ea18bb676d5))
- **Colors:** Provide enum descriptions (#8437) ([6ef4754](https://github.com/discordjs/discord.js/commit/6ef4754d40c5ec65715fc1e00e643c52fe0a6209))
- **AttachmentBuilder:** Fix #8407 (#8421) ([5b053cf](https://github.com/discordjs/discord.js/commit/5b053cf82ec2f2b717a490485af052dc956fe3c9))
## Features
- **Guild:** Add `max_video_channel_users` (#8423) ([3a96ce7](https://github.com/discordjs/discord.js/commit/3a96ce7970947f6268c21a1323d986aac8cb736d))
## Typings
- **Message:** Correct `bulkDelete` return type (#8465) ([c5b96a1](https://github.com/discordjs/discord.js/commit/c5b96a185cb8ba836b7cd10526c14059866f218f))
- Fix missing types for mentionable options (#8443) ([452e94f](https://github.com/discordjs/discord.js/commit/452e94fd3ecc12de9e3408982c5c7fd931bae634))
- **ApplicationCommandOption:** Add `ApplicationCommandBooleanOption` (#8434) ([38275fc](https://github.com/discordjs/discord.js/commit/38275fc53d633ce77ed2b142aff788dcbd4fad8c))
# [14.1.2](https://github.com/discordjs/discord.js/compare/14.1.1...14.1.2) - (2022-07-30)
## Bug Fixes
- **errors:** Error codes (#8398) ([480c85c](https://github.com/discordjs/discord.js/commit/480c85c9c3d129204b3399ed726a4e570e0b2852))
## Documentation
- **Embed:** Ensure height and width are numbers (#8396) ([fca3dad](https://github.com/discordjs/discord.js/commit/fca3dada2a565eecfc7e5275cc9317df1d261871))
# [14.1.0](https://github.com/discordjs/discord.js/compare/14.0.3...14.1.0) - (2022-07-29)
## Bug Fixes
@@ -57,7 +95,7 @@ All notable changes to this project will be documented in this file.
- 14.0.1 release bump, no new features.
# [14.0.0](https://github.com/discordjs/discord.js/compare/13.9.2...14.0.0) - (2022-07-17)
# [14.0.0](https://github.com/discordjs/discord.js/compare/13.10.2...14.0.0) - (2022-07-17)
## Bug Fixes
@@ -463,6 +501,24 @@ All notable changes to this project will be documented in this file.
- AssertType -> expectType ([3f36746](https://github.com/discordjs/discord.js/commit/3f36746561a40cd61a7cd2e054b7ef80d58fc707))
- Fix cache types resolving to `never` (#7164) ([c978dbb](https://github.com/discordjs/discord.js/commit/c978dbb6233bcd85408caf0bca7619c9c5d508f0))
# [13.10.2](https://github.com/discordjs/discord.js/compare/13.10.1...13.10.2) - (2022-08-10)
## Typings
- **Message:** Correct `bulkDelete` return type (v13) (#8469) ([03c59e3](https://github.com/discordjs/discord.js/commit/03c59e3a837edcaa428549c8387ef4d29e3ef6e4))
# [13.10.1](https://github.com/discordjs/discord.js/compare/13.10.0...13.10.1) - (2022-08-10)
## Bug Fixes
- **ThreadChannel:** Handle possibly `null` parent (v13) (#8467) ([2a46d9f](https://github.com/discordjs/discord.js/commit/2a46d9f58e4714c8580218a3459992bbfec2bcf7))
# [13.10.0](https://github.com/discordjs/discord.js/compare/13.9.2...13.10.0) - (2022-08-08)
## Features
- **Guild:** Add `max_video_channel_users` (v13) (#8424) ([ae43bca](https://github.com/discordjs/discord.js/commit/ae43bca8b0afd8b90db7a1d99f67205b29338c2d))
# [13.9.2](https://github.com/discordjs/discord.js/compare/13.9.1...13.9.2) - (2022-07-29)
## Bug Fixes

View File

@@ -71,7 +71,7 @@ const rest = new REST({ version: '10' }).setToken('token');
try {
console.log('Started refreshing application (/) commands.');
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID), { body: commands });
await rest.put(Routes.applicationCommands(CLIENT_ID), { body: commands });
console.log('Successfully reloaded application (/) commands.');
} catch (error) {

View File

@@ -1,6 +1,6 @@
{
"name": "discord.js",
"version": "14.1.1",
"version": "14.2.0",
"description": "A powerful library for interacting with the Discord API",
"scripts": {
"test": "yarn docs:test && yarn test:typescript",
@@ -54,19 +54,19 @@
"@discordjs/rest": "workspace:^",
"@sapphire/snowflake": "^3.2.2",
"@types/ws": "^8.5.3",
"discord-api-types": "^0.36.3",
"discord-api-types": "^0.37.3",
"fast-deep-equal": "^3.1.3",
"lodash.snakecase": "^4.1.1",
"tslib": "^2.4.0",
"undici": "^5.8.0",
"undici": "^5.9.1",
"ws": "^8.8.1"
},
"devDependencies": {
"@discordjs/docgen": "workspace:^",
"@favware/cliff-jumper": "^1.8.5",
"@types/node": "^16.11.46",
"@favware/cliff-jumper": "^1.8.7",
"@types/node": "^16.11.52",
"dtslint": "^4.2.1",
"eslint": "^8.20.0",
"eslint": "^8.22.0",
"jest": "^28.1.3",
"prettier": "^2.7.1",
"tsd": "^0.22.0",

View File

@@ -33,7 +33,7 @@ class MessageDeleteBulkAction extends Action {
* Emitted whenever messages are deleted in bulk.
* @event Client#messageDeleteBulk
* @param {Collection<Snowflake, Message>} messages The deleted messages, mapped by their id
* @param {TextBasedChannels} channel The channel that the messages were deleted in
* @param {GuildTextBasedChannel} channel The channel that the messages were deleted in
*/
if (messages.size > 0) client.emit(Events.MessageBulkDelete, messages, channel);
return { messages };

View File

@@ -3,7 +3,6 @@
// Heavily inspired by node's `internal/errors` module
const ErrorCodes = require('./ErrorCodes');
const Messages = require('./Messages');
const kCode = Symbol('code');
/**
* Extend an error of some sort into a DiscordjsError.
@@ -15,17 +14,13 @@ function makeDiscordjsError(Base) {
return class DiscordjsError extends Base {
constructor(code, ...args) {
super(message(code, args));
this[kCode] = code;
this.code = code;
Error.captureStackTrace?.(this, DiscordjsError);
}
get name() {
return `${super.name} [${this.code}]`;
}
get code() {
return ErrorCodes[this[kCode]];
}
};
}
@@ -37,9 +32,9 @@ function makeDiscordjsError(Base) {
* @ignore
*/
function message(code, args) {
if (typeof code !== 'number') throw new Error('Error code must be a valid DiscordjsErrorCodes');
if (!(code in ErrorCodes)) throw new Error('Error code must be a valid DiscordjsErrorCodes');
const msg = Messages[code];
if (!msg) throw new Error(`An invalid error code was used: ${code}.`);
if (!msg) throw new Error(`No message associated with error code: ${code}.`);
if (typeof msg === 'function') return msg(...args);
if (!args?.length) return msg;
args.unshift(msg);

View File

@@ -1,159 +1,152 @@
'use strict';
const { createEnum } = require('../util/Enums');
/**
* @typedef {Object} DiscordjsErrorCodes
* @property {number} ClientInvalidOption
* @property {number} ClientInvalidProvidedShards
* @property {number} ClientMissingIntents
* @property {number} ClientNotReady
* @property {'ClientInvalidOption'} ClientInvalidOption
* @property {'ClientInvalidProvidedShards'} ClientInvalidProvidedShards
* @property {'ClientMissingIntents'} ClientMissingIntents
* @property {'ClientNotReady'} ClientNotReady
* @property {number} TokenInvalid
* @property {number} TokenMissing
* @property {number} ApplicationCommandPermissionsTokenMissing
* @property {'TokenInvalid'} TokenInvalid
* @property {'TokenMissing'} TokenMissing
* @property {'ApplicationCommandPermissionsTokenMissing'} ApplicationCommandPermissionsTokenMissing
* @property {number} WSCloseRequested
* @property {number} WSConnectionExists
* @property {number} WSNotOpen
* @property {number} ManagerDestroyed
* @property {'WSCloseRequested'} WSCloseRequested
* @property {'WSConnectionExists'} WSConnectionExists
* @property {'WSNotOpen'} WSNotOpen
* @property {'ManagerDestroyed'} ManagerDestroyed
* @property {number} BitFieldInvalid
* @property {'BitFieldInvalid'} BitFieldInvalid
* @property {number} ShardingInvalid
* @property {number} ShardingRequired
* @property {number} InvalidIntents
* @property {number} DisallowedIntents
* @property {number} ShardingNoShards
* @property {number} ShardingInProcess
* @property {number} ShardingInvalidEvalBroadcast
* @property {number} ShardingShardNotFound
* @property {number} ShardingAlreadySpawned
* @property {number} ShardingProcessExists
* @property {number} ShardingWorkerExists
* @property {number} ShardingReadyTimeout
* @property {number} ShardingReadyDisconnected
* @property {number} ShardingReadyDied
* @property {number} ShardingNoChildExists
* @property {number} ShardingShardMiscalculation
* @property {'ShardingInvalid'} ShardingInvalid
* @property {'ShardingRequired'} ShardingRequired
* @property {'InvalidIntents'} InvalidIntents
* @property {'DisallowedIntents'} DisallowedIntents
* @property {'ShardingNoShards'} ShardingNoShards
* @property {'ShardingInProcess'} ShardingInProcess
* @property {'ShardingInvalidEvalBroadcast'} ShardingInvalidEvalBroadcast
* @property {'ShardingShardNotFound'} ShardingShardNotFound
* @property {'ShardingAlreadySpawned'} ShardingAlreadySpawned
* @property {'ShardingProcessExists'} ShardingProcessExists
* @property {'ShardingWorkerExists'} ShardingWorkerExists
* @property {'ShardingReadyTimeout'} ShardingReadyTimeout
* @property {'ShardingReadyDisconnected'} ShardingReadyDisconnected
* @property {'ShardingReadyDied'} ShardingReadyDied
* @property {'ShardingNoChildExists'} ShardingNoChildExists
* @property {'ShardingShardMiscalculation'} ShardingShardMiscalculation
* @property {number} ColorRange
* @property {number} ColorConvert
* @property {'ColorRange'} ColorRange
* @property {'ColorConvert'} ColorConvert
* @property {number} InviteOptionsMissingChannel
* @property {'InviteOptionsMissingChannel'} InviteOptionsMissingChannel
* @property {number} ButtonLabel
* @property {number} ButtonURL
* @property {number} ButtonCustomId
* @property {'ButtonLabel'} ButtonLabel
* @property {'ButtonURL'} ButtonURL
* @property {'ButtonCustomId'} ButtonCustomId
* @property {number} SelectMenuCustomId
* @property {number} SelectMenuPlaceholder
* @property {number} SelectOptionLabel
* @property {number} SelectOptionValue
* @property {number} SelectOptionDescription
* @property {'SelectMenuCustomId'} SelectMenuCustomId
* @property {'SelectMenuPlaceholder'} SelectMenuPlaceholder
* @property {'SelectOptionLabel'} SelectOptionLabel
* @property {'SelectOptionValue'} SelectOptionValue
* @property {'SelectOptionDescription'} SelectOptionDescription
* @property {number} InteractionCollectorError
* @property {'InteractionCollectorError'} InteractionCollectorError
* @property {number} FileNotFound
* @property {'FileNotFound'} FileNotFound
* @property {number} UserBannerNotFetched
* @property {number} UserNoDMChannel
* @property {'UserBannerNotFetched'} UserBannerNotFetched
* @property {'UserNoDMChannel'} UserNoDMChannel
* @property {number} VoiceNotStageChannel
* @property {'VoiceNotStageChannel'} VoiceNotStageChannel
* @property {number} VoiceStateNotOwn
* @property {number} VoiceStateInvalidType
* @property {'VoiceStateNotOwn'} VoiceStateNotOwn
* @property {'VoiceStateInvalidType'} VoiceStateInvalidType
* @property {number} ReqResourceType
* @property {'ReqResourceType'} ReqResourceType
* @property {number} ImageFormat
* @property {number} ImageSize
* @property {'ImageFormat'} ImageFormat
* @property {'ImageSize'} ImageSize
* @property {number} MessageBulkDeleteType
* @property {number} MessageNonceType
* @property {number} MessageContentType
* @property {'MessageBulkDeleteType'} MessageBulkDeleteType
* @property {'MessageNonceType'} MessageNonceType
* @property {'MessageContentType'} MessageContentType
* @property {number} SplitMaxLen
* @property {'SplitMaxLen'} SplitMaxLen
* @property {number} BanResolveId
* @property {number} FetchBanResolveId
* @property {'BanResolveId'} BanResolveId
* @property {'FetchBanResolveId'} FetchBanResolveId
* @property {number} PruneDaysType
* @property {'PruneDaysType'} PruneDaysType
* @property {number} GuildChannelResolve
* @property {number} GuildVoiceChannelResolve
* @property {number} GuildChannelOrphan
* @property {number} GuildChannelUnowned
* @property {number} GuildOwned
* @property {number} GuildMembersTimeout
* @property {number} GuildUncachedMe
* @property {number} ChannelNotCached
* @property {number} StageChannelResolve
* @property {number} GuildScheduledEventResolve
* @property {number} FetchOwnerId
* @property {'GuildChannelResolve'} GuildChannelResolve
* @property {'GuildVoiceChannelResolve'} GuildVoiceChannelResolve
* @property {'GuildChannelOrphan'} GuildChannelOrphan
* @property {'GuildChannelUnowned'} GuildChannelUnowned
* @property {'GuildOwned'} GuildOwned
* @property {'GuildMembersTimeout'} GuildMembersTimeout
* @property {'GuildUncachedMe'} GuildUncachedMe
* @property {'ChannelNotCached'} ChannelNotCached
* @property {'StageChannelResolve'} StageChannelResolve
* @property {'GuildScheduledEventResolve'} GuildScheduledEventResolve
* @property {'FetchOwnerId'} FetchOwnerId
* @property {number} InvalidType
* @property {number} InvalidElement
* @property {'InvalidType'} InvalidType
* @property {'InvalidElement'} InvalidElement
* @property {number} MessageThreadParent
* @property {number} MessageExistingThread
* @property {number} ThreadInvitableType
* @property {'MessageThreadParent'} MessageThreadParent
* @property {'MessageExistingThread'} MessageExistingThread
* @property {'ThreadInvitableType'} ThreadInvitableType
* @property {number} WebhookMessage
* @property {number} WebhookTokenUnavailable
* @property {number} WebhookURLInvalid
* @property {number} WebhookApplication
* @property {number} MessageReferenceMissing
* @property {'WebhookMessage'} WebhookMessage
* @property {'WebhookTokenUnavailable'} WebhookTokenUnavailable
* @property {'WebhookURLInvalid'} WebhookURLInvalid
* @property {'WebhookApplication'} WebhookApplication
* @property {'MessageReferenceMissing'} MessageReferenceMissing
* @property {number} EmojiType
* @property {number} EmojiManaged
* @property {number} MissingManageEmojisAndStickersPermission
* @property {number} NotGuildSticker
* @property {'EmojiType'} EmojiType
* @property {'EmojiManaged'} EmojiManaged
* @property {'MissingManageEmojisAndStickersPermission'} MissingManageEmojisAndStickersPermission
* @property {'NotGuildSticker'} NotGuildSticker
* @property {number} ReactionResolveUser
* @property {'ReactionResolveUser'} ReactionResolveUser
* @property {number} VanityURL
* @property {'VanityURL'} VanityURL
* @property {number} InviteResolveCode
* @property {'InviteResolveCode'} InviteResolveCode
* @property {number} InviteNotFound
* @property {'InviteNotFound'} InviteNotFound
* @property {number} DeleteGroupDMChannel
* @property {number} FetchGroupDMChannel
* @property {'DeleteGroupDMChannel'} DeleteGroupDMChannel
* @property {'FetchGroupDMChannel'} FetchGroupDMChannel
* @property {number} MemberFetchNonceLength
* @property {'MemberFetchNonceLength'} MemberFetchNonceLength
* @property {number} GlobalCommandPermissions
* @property {number} GuildUncachedEntityResolve
* @property {'GlobalCommandPermissions'} GlobalCommandPermissions
* @property {'GuildUncachedEntityResolve'} GuildUncachedEntityResolve
* @property {number} InteractionAlreadyReplied
* @property {number} InteractionNotReplied
* @property {number} InteractionEphemeralReplied
* @property {'InteractionAlreadyReplied'} InteractionAlreadyReplied
* @property {'InteractionNotReplied'} InteractionNotReplied
* @property {'InteractionEphemeralReplied'} InteractionEphemeralReplied
* @property {number} CommandInteractionOptionNotFound
* @property {number} CommandInteractionOptionType
* @property {number} CommandInteractionOptionEmpty
* @property {number} CommandInteractionOptionNoSubcommand
* @property {number} CommandInteractionOptionNoSubcommandGroup
* @property {number} AutocompleteInteractionOptionNoFocusedOption
* @property {'CommandInteractionOptionNotFound'} CommandInteractionOptionNotFound
* @property {'CommandInteractionOptionType'} CommandInteractionOptionType
* @property {'CommandInteractionOptionEmpty'} CommandInteractionOptionEmpty
* @property {'CommandInteractionOptionNoSubcommand'} CommandInteractionOptionNoSubcommand
* @property {'CommandInteractionOptionNoSubcommandGroup'} CommandInteractionOptionNoSubcommandGroup
* @property {'AutocompleteInteractionOptionNoFocusedOption'} AutocompleteInteractionOptionNoFocusedOption
* @property {number} ModalSubmitInteractionFieldNotFound
* @property {number} ModalSubmitInteractionFieldType
* @property {'ModalSubmitInteractionFieldNotFound'} ModalSubmitInteractionFieldNotFound
* @property {'ModalSubmitInteractionFieldType'} ModalSubmitInteractionFieldType
* @property {number} InvalidMissingScopes
* @property {'InvalidMissingScopes'} InvalidMissingScopes
* @property {number} NotImplemented
* @property {'NotImplemented'} NotImplemented
* @property {number} SweepFilterReturn
* @property {'SweepFilterReturn'} SweepFilterReturn
*/
// JSDoc for IntelliSense purposes
/**
* @type {DiscordjsErrorCodes}
* @ignore
*/
module.exports = createEnum([
const keys = [
'ClientInvalidOption',
'ClientInvalidProvidedShards',
'ClientMissingIntents',
@@ -295,4 +288,11 @@ module.exports = createEnum([
'NotImplemented',
'SweepFilterReturn',
]);
];
// JSDoc for IntelliSense purposes
/**
* @type {DiscordjsErrorCodes}
* @ignore
*/
module.exports = Object.fromEntries(keys.map(key => [key, key]));

View File

@@ -164,7 +164,7 @@ class GuildChannelManager extends CachedManager {
/**
* @typedef {ChannelWebhookCreateOptions} WebhookCreateOptions
* @property {GuildChannelResolvable} channel The channel to create the webhook for
* @property {TextChannel|NewsChannel|VoiceChannel|Snowflake} channel The channel to create the webhook for
*/
/**

View File

@@ -1,6 +1,5 @@
'use strict';
const { Buffer } = require('node:buffer');
const { setTimeout, clearTimeout } = require('node:timers');
const { Collection } = require('@discordjs/collection');
const { makeURLSearchParams } = require('@discordjs/rest');
@@ -128,8 +127,12 @@ class GuildMemberManager extends CachedManager {
resolvedOptions.roles = resolvedRoles;
}
const data = await this.client.rest.put(Routes.guildMember(this.guild.id, userId), { body: resolvedOptions });
// Data is an empty buffer if the member is already part of the guild.
return data instanceof Buffer ? (options.fetchWhenExisting === false ? null : this.fetch(userId)) : this._add(data);
// Data is an empty Uint8Array if the member is already part of the guild.
return data instanceof Uint8Array
? options.fetchWhenExisting === false
? null
: this.fetch(userId)
: this._add(data);
}
/**
@@ -441,6 +444,42 @@ class GuildMemberManager extends CachedManager {
return this.guild.bans.remove(user, reason);
}
/**
* Options used for adding or removing a role from a member.
* @typedef {Object} AddOrRemoveGuildMemberRoleOptions
* @property {GuildMemberResolvable} user The user to add/remove the role from
* @property {RoleResolvable} role The role to add/remove
* @property {string} [reason] Reason for adding/removing the role
*/
/**
* Adds a role to a member.
* @param {AddOrRemoveGuildMemberRoleOptions} options Options for adding the role
* @returns {Promise<GuildMember|User|Snowflake>}
*/
async addRole(options) {
const { user, role, reason } = options;
const userId = this.guild.members.resolveId(user);
const roleId = this.guild.roles.resolveId(role);
await this.client.rest.put(Routes.guildMemberRole(this.guild.id, userId, roleId), { reason });
return this.resolve(user) ?? this.client.users.resolve(user) ?? userId;
}
/**
* Removes a role from a member.
* @param {AddOrRemoveGuildMemberRoleOptions} options Options for removing the role
* @returns {Promise<GuildMember|User|Snowflake>}
*/
async removeRole(options) {
const { user, role, reason } = options;
const userId = this.guild.members.resolveId(user);
const roleId = this.guild.roles.resolveId(role);
await this.client.rest.delete(Routes.guildMemberRole(this.guild.id, userId, roleId), { reason });
return this.resolve(user) ?? this.client.users.resolve(user) ?? userId;
}
async _fetchSingle({ user, cache, force = false }) {
if (!force) {
const existing = this.cache.get(user);

View File

@@ -1,5 +1,6 @@
'use strict';
const { deprecate } = require('node:util');
const { isJSONEncodable } = require('@discordjs/builders');
const Component = require('./Component');
const { createComponent } = require('../util/Components');
@@ -24,6 +25,7 @@ class ActionRow extends Component {
* Creates a new action row builder from JSON data
* @param {JSONEncodable<APIActionRowComponent>|APIActionRowComponent} other The other data
* @returns {ActionRowBuilder}
* @deprecated Use {@link ActionRowBuilder.from()} instead.
*/
static from(other) {
if (isJSONEncodable(other)) {
@@ -41,4 +43,6 @@ class ActionRow extends Component {
}
}
ActionRow.from = deprecate(ActionRow.from, 'ActionRow.from() is deprecated. Use ActionRowBuilder.from() instead.');
module.exports = ActionRow;

View File

@@ -8,7 +8,7 @@ const { basename, flatten } = require('../util/Util');
class AttachmentBuilder {
/**
* @param {BufferResolvable|Stream} attachment The file
* @param {APIAttachment} [data] Extra data
* @param {AttachmentData} [data] Extra data
*/
constructor(attachment, data = {}) {
/**
@@ -108,3 +108,9 @@ module.exports = AttachmentBuilder;
* @external APIAttachment
* @see {@link https://discord.com/developers/docs/resources/channel#attachment-object}
*/
/**
* @typedef {Object} AttachmentData
* @property {string} [name] The name of the attachment
* @property {string} [description] The description of the attachment
*/

View File

@@ -115,10 +115,10 @@ class Embed {
get video() {
if (!this.data.video) return null;
return {
url: this.data.image.url,
proxyURL: this.data.image.proxy_url,
height: this.data.image.height,
width: this.data.image.width,
url: this.data.video.url,
proxyURL: this.data.video.proxy_url,
height: this.data.video.height,
width: this.data.video.width,
};
}

View File

@@ -216,6 +216,8 @@ class Guild extends AnonymousGuild {
* @type {?boolean}
*/
this.widgetEnabled = data.widget_enabled;
} else {
this.widgetEnabled ??= null;
}
if ('widget_channel_id' in data) {
@@ -224,6 +226,8 @@ class Guild extends AnonymousGuild {
* @type {?string}
*/
this.widgetChannelId = data.widget_channel_id;
} else {
this.widgetChannelId ??= null;
}
if ('explicit_content_filter' in data) {
@@ -287,6 +291,16 @@ class Guild extends AnonymousGuild {
this.maximumPresences ??= null;
}
if ('max_video_channel_users' in data) {
/**
* The maximum amount of users allowed in a video channel.
* @type {?number}
*/
this.maxVideoChannelUsers = data.max_video_channel_users;
} else {
this.maxVideoChannelUsers ??= null;
}
if ('approximate_member_count' in data) {
/**
* The approximate amount of members the guild has
@@ -479,7 +493,7 @@ class Guild extends AnonymousGuild {
/**
* Widget channel for this guild
* @type {?TextChannel}
* @type {?(TextChannel|NewsChannel|VoiceChannel|StageChannel)}
* @readonly
*/
get widgetChannel() {
@@ -550,7 +564,7 @@ class Guild extends AnonymousGuild {
* @returns {Promise<Collection<string, GuildTemplate>>}
*/
async fetchTemplates() {
const templates = await this.client.rest.get(Routes.guildTemplate(this.id));
const templates = await this.client.rest.get(Routes.guildTemplates(this.id));
return templates.reduce((col, data) => col.set(data.code, new GuildTemplate(this.client, data)), new Collection());
}
@@ -646,14 +660,14 @@ class Guild extends AnonymousGuild {
* Data for the Guild Widget Settings object
* @typedef {Object} GuildWidgetSettings
* @property {boolean} enabled Whether the widget is enabled
* @property {?GuildChannel} channel The widget invite channel
* @property {?(TextChannel|NewsChannel|VoiceChannel|StageChannel)} channel The widget invite channel
*/
/**
* The Guild Widget Settings object
* @typedef {Object} GuildWidgetSettingsData
* @property {boolean} enabled Whether the widget is enabled
* @property {?GuildChannelResolvable} channel The widget invite channel
* @property {?(TextChannel|NewsChannel|VoiceChannel|StageChannel|Snowflake)} channel The widget invite channel
*/
/**

View File

@@ -106,7 +106,7 @@ class GuildAuditLogsEntry {
this.actionType = GuildAuditLogsEntry.actionType(data.action_type);
/**
* Specific action type of this entry in its string presentation
* The type of action that occured.
* @type {AuditLogEvent}
*/
this.action = data.action_type;
@@ -220,7 +220,6 @@ class GuildAuditLogsEntry {
case AuditLogEvent.ApplicationCommandPermissionUpdate:
this.extra = {
applicationId: data.options.application_id,
guild: guild.client.guilds.cache.get(data.options.guild_id) ?? { id: data.options.guild_id },
};
break;

View File

@@ -48,6 +48,14 @@ class MessageMentions {
*/
static GlobalChannelsPattern = new RegExp(this.ChannelsPattern.source, 'g');
/**
* A global regular expression variant of {@link MessageMentions.UsersPattern}.
* @type {RegExp}
* @memberof MessageMentions
* @private
*/
static GlobalUsersPattern = new RegExp(this.UsersPattern.source, 'g');
constructor(message, users, roles, everyone, crosspostedChannels, repliedUser) {
/**
* The client the message is from
@@ -225,7 +233,7 @@ class MessageMentions {
if (this._parsedUsers) return this._parsedUsers;
this._parsedUsers = new Collection();
let matches;
while ((matches = this.constructor.UsersPattern.exec(this._content)) !== null) {
while ((matches = this.constructor.GlobalUsersPattern.exec(this._content)) !== null) {
const user = this.client.users.cache.get(matches[1]);
if (user) this._parsedUsers.set(user.id, user);
}

View File

@@ -283,10 +283,11 @@ class ThreadChannel extends BaseChannel {
* <info>This only works when the thread started from a message in the parent channel, otherwise the promise will
* reject. If you just need the id of that message, use {@link ThreadChannel#id} instead.</info>
* @param {BaseFetchOptions} [options] Additional options for this fetch
* @returns {Promise<Message>}
* @returns {Promise<Message|null>}
*/
fetchStarterMessage(options) {
return this.parent.messages.fetch({ message: this.id, ...options });
// eslint-disable-next-line require-await
async fetchStarterMessage(options) {
return this.parent?.messages.fetch({ message: this.id, ...options }) ?? null;
}
/**

View File

@@ -197,7 +197,7 @@ class InteractionResponses {
});
this.deferred = true;
return options.fetchReply ? this.fetchReply() : new InteractionResponse(this, this.message.interaction?.id);
return options.fetchReply ? this.fetchReply() : new InteractionResponse(this, this.message?.interaction?.id);
}
/**
@@ -255,7 +255,7 @@ class InteractionResponses {
* An object containing the same properties as {@link CollectorOptions}, but a few less:
* @typedef {Object} AwaitModalSubmitOptions
* @property {CollectorFilter} [filter] The filter applied to this collector
* @property {number} time Time to wait for an interaction before rejecting
* @property {number} time Time in milliseconds to wait for an interaction before rejecting
*/
/**

View File

@@ -283,7 +283,7 @@ class TextBasedChannel {
* @param {Collection<Snowflake, Message>|MessageResolvable[]|number} messages
* Messages or number of messages to delete
* @param {boolean} [filterOld=false] Filter messages to remove those which are older than two weeks automatically
* @returns {Promise<Collection<Snowflake, Message>>} Returns the deleted messages
* @returns {Promise<Collection<Snowflake, Message|undefined>>} Returns the deleted messages
* @example
* // Bulk delete messages
* channel.bulkDelete(5)

View File

@@ -2,36 +2,36 @@
/**
* @typedef {Object} Colors
* @property {number} Default
* @property {number} White
* @property {number} Aqua
* @property {number} Green
* @property {number} Blue
* @property {number} Yellow
* @property {number} Purple
* @property {number} LuminousVividPink
* @property {number} Fuchsia
* @property {number} Gold
* @property {number} Orange
* @property {number} Red
* @property {number} Grey
* @property {number} Navy
* @property {number} DarkAqua
* @property {number} DarkGreen
* @property {number} DarkBlue
* @property {number} DarkPurple
* @property {number} DarkVividPink
* @property {number} DarkGold
* @property {number} DarkOrange
* @property {number} DarkRed
* @property {number} DarkGrey
* @property {number} DarkerGrey
* @property {number} LightGrey
* @property {number} DarkNavy
* @property {number} Blurple
* @property {number} Greyple
* @property {number} DarkButNotBlack
* @property {number} NotQuiteBlack
* @property {number} Default 0x000000 | rgb(0,0,0)
* @property {number} White 0xFFFFFF | rgb(255,255,255)
* @property {number} Aqua 0x1ABC9C | rgb(26,188,156)
* @property {number} Green 0x57F287 | rgb(87,242,135)
* @property {number} Blue 0x3498DB | rgb(52,152,219)
* @property {number} Yellow 0xFEE75C | rgb(254,231,92)
* @property {number} Purple 0x9B59B6 | rgb(155,89,182)
* @property {number} LuminousVividPink 0xE91E63 | rgb(233,30,99)
* @property {number} Fuchsia 0xEB459E | rgb(235,69,158)
* @property {number} Gold 0xF1C40F | rgb(241,196,15)
* @property {number} Orange 0xE67E22 | rgb(230,126,34)
* @property {number} Red 0xED4245 | rgb(237,66,69)
* @property {number} Grey 0x95A5A6 | rgb(149,165,166)
* @property {number} Navy 0x34495E | rgb(52,73,94)
* @property {number} DarkAqua 0x11806A | rgb(17,128,106)
* @property {number} DarkGreen 0x1F8B4C | rgb(31,139,76)
* @property {number} DarkBlue 0x206694 | rgb(32,102,148)
* @property {number} DarkPurple 0x71368A | rgb(113,54,138)
* @property {number} DarkVividPink 0xAD1457 | rgb(173,20,87)
* @property {number} DarkGold 0xC27C0E | rgb(194,124,14)
* @property {number} DarkOrange 0xA84300 | rgb(168,67,0)
* @property {number} DarkRed 0x992D22 | rgb(153,45,34)
* @property {number} DarkGrey 0x979C9F | rgb(151,156,159)
* @property {number} DarkerGrey 0x7F8C8D | rgb(127,140,141)
* @property {number} LightGrey 0xBCC0C0 | rgb(188,192,192)
* @property {number} DarkNavy 0x2C3E50 | rgb(44,62,80)
* @property {number} Blurple 0x5865F2 | rgb(88,101,242)
* @property {number} Greyple 0x99AAb5 | rgb(153,170,181)
* @property {number} DarkButNotBlack 0x2C2F33 | rgb(44,47,51)
* @property {number} NotQuiteBlack 0x23272A | rgb(35,39,42)
*/
// JSDoc for IntelliSense purposes

View File

@@ -53,13 +53,19 @@ exports.NonSystemMessageTypes = [
];
/**
* The channels that are text-based.
* * DMChannel
* The guild channels that are text-based.
* * TextChannel
* * NewsChannel
* * ThreadChannel
* * VoiceChannel
* @typedef {DMChannel|TextChannel|NewsChannel|ThreadChannel|VoiceChannel} TextBasedChannels
* @typedef {TextChannel|NewsChannel|ThreadChannel|VoiceChannel} GuildTextBasedChannel
*/
/**
* The channels that are text-based.
* * DMChannel
* * GuildTextBasedChannel
* @typedef {DMChannel|GuildTextBasedChannel} TextBasedChannels
*/
/**

View File

@@ -116,7 +116,7 @@ class DataResolver extends null {
if (typeof resource[Symbol.asyncIterator] === 'function') {
const buffers = [];
for await (const data of resource) buffers.push(data);
for await (const data of resource) buffers.push(Buffer.from(data));
return { data: Buffer.concat(buffers) };
}

View File

@@ -9,6 +9,7 @@ const snakeCase = require('lodash.snakecase');
*/
function toSnakeCase(obj) {
if (typeof obj !== 'object' || !obj) return obj;
if (obj instanceof Date) return obj;
if (Array.isArray(obj)) return obj.map(toSnakeCase);
return Object.fromEntries(Object.entries(obj).map(([key, value]) => [snakeCase(key), toSnakeCase(value)]));
}

View File

@@ -192,7 +192,10 @@ declare module 'node:events' {
class EventEmitter {
// Add type overloads for client events.
public static once<K extends keyof ClientEvents>(eventEmitter: Client, eventName: K): Promise<ClientEvents[K]>;
public static on<K extends keyof ClientEvents>(eventEmitter: Client, eventName: K): AsyncIterator<ClientEvents[K]>;
public static on<K extends keyof ClientEvents>(
eventEmitter: Client,
eventName: K,
): AsyncIterableIterator<ClientEvents[K]>;
}
}
@@ -1083,6 +1086,7 @@ export class Guild extends AnonymousGuild {
public afkChannelId: Snowflake | null;
public afkTimeout: number;
public applicationId: Snowflake | null;
public maxVideoChannelUsers: number | null;
public approximateMemberCount: number | null;
public approximatePresenceCount: number | null;
public available: boolean;
@@ -1123,7 +1127,7 @@ export class Guild extends AnonymousGuild {
public vanityURLUses: number | null;
public get voiceAdapterCreator(): InternalDiscordGatewayAdapterCreator;
public voiceStates: VoiceStateManager;
public get widgetChannel(): TextChannel | null;
public get widgetChannel(): TextChannel | NewsChannel | VoiceBasedChannel | null;
public widgetChannelId: Snowflake | null;
public widgetEnabled: boolean | null;
public get maximumBitrate(): number;
@@ -1177,35 +1181,37 @@ export class Guild extends AnonymousGuild {
public toJSON(): unknown;
}
export class GuildAuditLogs<T extends GuildAuditLogsResolvable = null> {
export class GuildAuditLogs<T extends GuildAuditLogsResolvable = AuditLogEvent> {
private constructor(guild: Guild, data: RawGuildAuditLogData);
private applicationCommands: Collection<Snowflake, ApplicationCommand>;
private webhooks: Collection<Snowflake, Webhook>;
private integrations: Collection<Snowflake | string, Integration>;
private guildScheduledEvents: Collection<Snowflake, GuildScheduledEvent>;
public entries: Collection<Snowflake, GuildAuditLogsEntry<T>>;
public static Entry: typeof GuildAuditLogsEntry;
public toJSON(): unknown;
}
export class GuildAuditLogsEntry<
TAction extends GuildAuditLogsResolvable = null,
TAction extends GuildAuditLogsResolvable = AuditLogEvent,
TActionType extends GuildAuditLogsActionType = TAction extends keyof GuildAuditLogsTypes
? GuildAuditLogsTypes[TAction][1]
: 'All',
: GuildAuditLogsActionType,
TTargetType extends GuildAuditLogsTargetType = TAction extends keyof GuildAuditLogsTypes
? GuildAuditLogsTypes[TAction][0]
: 'Unknown',
: GuildAuditLogsTargetType,
TResolvedType = TAction extends null ? AuditLogEvent : TAction,
> {
private constructor(logs: GuildAuditLogs, guild: Guild, data: RawGuildAuditLogEntryData);
public static Targets: GuildAuditLogsTargets;
public action: TAction;
public action: TResolvedType;
public actionType: TActionType;
public changes: AuditLogChange[];
public get createdAt(): Date;
public get createdTimestamp(): number;
public executor: User | null;
public extra: TAction extends keyof GuildAuditLogsEntryExtraField ? GuildAuditLogsEntryExtraField[TAction] : null;
public extra: TResolvedType extends keyof GuildAuditLogsEntryExtraField
? GuildAuditLogsEntryExtraField[TResolvedType]
: null;
public id: Snowflake;
public reason: string | null;
public target: TTargetType extends keyof GuildAuditLogsEntryTargetField<TActionType>
@@ -1880,8 +1886,9 @@ export class MessageMentions {
public crosspostedChannels: Collection<Snowflake, CrosspostedChannel>;
public toJSON(): unknown;
public static ChannelsPattern: typeof FormattingPatterns.Channel;
private static GlobalChannelsPattern: RegExp;
private static GlobalUsersPattern: RegExp;
public static ChannelsPattern: typeof FormattingPatterns.Channel;
public static EveryonePattern: RegExp;
public static RolesPattern: typeof FormattingPatterns.Role;
public static UsersPattern: typeof FormattingPatterns.User;
@@ -1968,12 +1975,11 @@ export class ModalSubmitFields {
export interface ModalMessageModalSubmitInteraction<Cached extends CacheType = CacheType>
extends ModalSubmitInteraction<Cached> {
message: Message<BooleanCache<Cached>>;
channelId: Snowflake;
update(options: InteractionUpdateOptions & { fetchReply: true }): Promise<Message>;
update(
options: string | MessagePayload | InteractionUpdateOptions,
): Promise<InteractionResponse<BooleanCache<Cached>>>;
deferUpdate(options: InteractionDeferUpdateOptions & { fetchReply: true }): Promise<Message>;
deferUpdate(options?: InteractionDeferUpdateOptions): Promise<InteractionResponse<BooleanCache<Cached>>>;
inGuild(): this is ModalMessageModalSubmitInteraction<'raw' | 'cached'>;
inCachedGuild(): this is ModalMessageModalSubmitInteraction<'cached'>;
inRawGuild(): this is ModalMessageModalSubmitInteraction<'raw'>;
@@ -2004,6 +2010,8 @@ export class ModalSubmitInteraction<Cached extends CacheType = CacheType> extend
public deferReply(options?: InteractionDeferReplyOptions): Promise<InteractionResponse<BooleanCache<Cached>>>;
public fetchReply(): Promise<Message<BooleanCache<Cached>>>;
public followUp(options: string | MessagePayload | InteractionReplyOptions): Promise<Message<BooleanCache<Cached>>>;
public deferUpdate(options: InteractionDeferUpdateOptions & { fetchReply: true }): Promise<Message>;
public deferUpdate(options?: InteractionDeferUpdateOptions): Promise<InteractionResponse<BooleanCache<Cached>>>;
public inGuild(): this is ModalSubmitInteraction<'raw' | 'cached'>;
public inCachedGuild(): this is ModalSubmitInteraction<'cached'>;
public inRawGuild(): this is ModalSubmitInteraction<'raw'>;
@@ -2538,7 +2546,7 @@ export class ThreadChannel extends TextBasedChannelMixin(BaseChannel, ['fetchWeb
checkAdmin?: boolean,
): Readonly<PermissionsBitField> | null;
public fetchOwner(options?: BaseFetchOptions): Promise<ThreadMember | null>;
public fetchStarterMessage(options?: BaseFetchOptions): Promise<Message>;
public fetchStarterMessage(options?: BaseFetchOptions): Promise<Message | null>;
public setArchived(archived?: boolean, reason?: string): Promise<AnyThreadChannel>;
public setAutoArchiveDuration(
autoArchiveDuration: ThreadAutoArchiveDuration,
@@ -3021,152 +3029,152 @@ export const version: string;
//#region Errors
export enum DiscordjsErrorCodes {
ClientInvalidOption,
ClientInvalidProvidedShards,
ClientMissingIntents,
ClientNotReady,
ClientInvalidOption = 'ClientInvalidOption',
ClientInvalidProvidedShards = 'ClientInvalidProvidedShards',
ClientMissingIntents = 'ClientMissingIntents',
ClientNotReady = 'ClientNotReady',
TokenInvalid,
TokenMissing,
ApplicationCommandPermissionsTokenMissing,
TokenInvalid = 'TokenInvalid',
TokenMissing = 'TokenMissing',
ApplicationCommandPermissionsTokenMissing = 'ApplicationCommandPermissionsTokenMissing',
WSCloseRequested,
WSConnectionExists,
WSNotOpen,
ManagerDestroyed,
WSCloseRequested = 'WSCloseRequested',
WSConnectionExists = 'WSConnectionExists',
WSNotOpen = 'WSNotOpen',
ManagerDestroyed = 'ManagerDestroyed',
BitFieldInvalid,
BitFieldInvalid = 'BitFieldInvalid',
ShardingInvalid,
ShardingRequired,
InvalidIntents,
DisallowedIntents,
ShardingNoShards,
ShardingInProcess,
ShardingInvalidEvalBroadcast,
ShardingShardNotFound,
ShardingAlreadySpawned,
ShardingProcessExists,
ShardingWorkerExists,
ShardingReadyTimeout,
ShardingReadyDisconnected,
ShardingReadyDied,
ShardingNoChildExists,
ShardingShardMiscalculation,
ShardingInvalid = 'ShardingInvalid',
ShardingRequired = 'ShardingRequired',
InvalidIntents = 'InvalidIntents',
DisallowedIntents = 'DisallowedIntents',
ShardingNoShards = 'ShardingNoShards',
ShardingInProcess = 'ShardingInProcess',
ShardingInvalidEvalBroadcast = 'ShardingInvalidEvalBroadcast',
ShardingShardNotFound = 'ShardingShardNotFound',
ShardingAlreadySpawned = 'ShardingAlreadySpawned',
ShardingProcessExists = 'ShardingProcessExists',
ShardingWorkerExists = 'ShardingWorkerExists',
ShardingReadyTimeout = 'ShardingReadyTimeout',
ShardingReadyDisconnected = 'ShardingReadyDisconnected',
ShardingReadyDied = 'ShardingReadyDied',
ShardingNoChildExists = 'ShardingNoChildExists',
ShardingShardMiscalculation = 'ShardingShardMiscalculation',
ColorRange,
ColorConvert,
ColorRange = 'ColorRange',
ColorConvert = 'ColorConvert',
InviteOptionsMissingChannel,
InviteOptionsMissingChannel = 'InviteOptionsMissingChannel',
ButtonLabel,
ButtonURL,
ButtonCustomId,
ButtonLabel = 'ButtonLabel',
ButtonURL = 'ButtonURL',
ButtonCustomId = 'ButtonCustomId',
SelectMenuCustomId,
SelectMenuPlaceholder,
SelectOptionLabel,
SelectOptionValue,
SelectOptionDescription,
SelectMenuCustomId = 'SelectMenuCustomId',
SelectMenuPlaceholder = 'SelectMenuPlaceholder',
SelectOptionLabel = 'SelectOptionLabel',
SelectOptionValue = 'SelectOptionValue',
SelectOptionDescription = 'SelectOptionDescription',
InteractionCollectorError,
InteractionCollectorError = 'InteractionCollectorError',
FileNotFound,
FileNotFound = 'FileNotFound',
UserBannerNotFetched,
UserNoDMChannel,
UserBannerNotFetched = 'UserBannerNotFetched',
UserNoDMChannel = 'UserNoDMChannel',
VoiceNotStageChannel,
VoiceNotStageChannel = 'VoiceNotStageChannel',
VoiceStateNotOwn,
VoiceStateInvalidType,
VoiceStateNotOwn = 'VoiceStateNotOwn',
VoiceStateInvalidType = 'VoiceStateInvalidType',
ReqResourceType,
ReqResourceType = 'ReqResourceType',
ImageFormat,
ImageSize,
ImageFormat = 'ImageFormat',
ImageSize = 'ImageSize',
MessageBulkDeleteType,
MessageNonceType,
MessageContentType,
MessageBulkDeleteType = 'MessageBulkDeleteType',
MessageNonceType = 'MessageNonceType',
MessageContentType = 'MessageContentType',
SplitMaxLen,
SplitMaxLen = 'SplitMaxLen',
BanResolveId,
FetchBanResolveId,
BanResolveId = 'BanResolveId',
FetchBanResolveId = 'FetchBanResolveId',
PruneDaysType,
PruneDaysType = 'PruneDaysType',
GuildChannelResolve,
GuildVoiceChannelResolve,
GuildChannelOrphan,
GuildChannelUnowned,
GuildOwned,
GuildMembersTimeout,
GuildUncachedMe,
ChannelNotCached,
StageChannelResolve,
GuildScheduledEventResolve,
FetchOwnerId,
GuildChannelResolve = 'GuildChannelResolve',
GuildVoiceChannelResolve = 'GuildVoiceChannelResolve',
GuildChannelOrphan = 'GuildChannelOrphan',
GuildChannelUnowned = 'GuildChannelUnowned',
GuildOwned = 'GuildOwned',
GuildMembersTimeout = 'GuildMembersTimeout',
GuildUncachedMe = 'GuildUncachedMe',
ChannelNotCached = 'ChannelNotCached',
StageChannelResolve = 'StageChannelResolve',
GuildScheduledEventResolve = 'GuildScheduledEventResolve',
FetchOwnerId = 'FetchOwnerId',
InvalidType,
InvalidElement,
InvalidType = 'InvalidType',
InvalidElement = 'InvalidElement',
MessageThreadParent,
MessageExistingThread,
ThreadInvitableType,
MessageThreadParent = 'MessageThreadParent',
MessageExistingThread = 'MessageExistingThread',
ThreadInvitableType = 'ThreadInvitableType',
WebhookMessage,
WebhookTokenUnavailable,
WebhookURLInvalid,
WebhookApplication,
MessageReferenceMissing,
WebhookMessage = 'WebhookMessage',
WebhookTokenUnavailable = 'WebhookTokenUnavailable',
WebhookURLInvalid = 'WebhookURLInvalid',
WebhookApplication = 'WebhookApplication',
MessageReferenceMissing = 'MessageReferenceMissing',
EmojiType,
EmojiManaged,
MissingManageEmojisAndStickersPermission,
NotGuildSticker,
EmojiType = 'EmojiType',
EmojiManaged = 'EmojiManaged',
MissingManageEmojisAndStickersPermission = 'MissingManageEmojisAndStickersPermission',
NotGuildSticker = 'NotGuildSticker',
ReactionResolveUser,
ReactionResolveUser = 'ReactionResolveUser',
VanityURL,
VanityURL = 'VanityURL',
InviteResolveCode,
InviteResolveCode = 'InviteResolveCode',
InviteNotFound,
InviteNotFound = 'InviteNotFound',
DeleteGroupDMChannel,
FetchGroupDMChannel,
DeleteGroupDMChannel = 'DeleteGroupDMChannel',
FetchGroupDMChannel = 'FetchGroupDMChannel',
MemberFetchNonceLength,
MemberFetchNonceLength = 'MemberFetchNonceLength',
GlobalCommandPermissions,
GuildUncachedEntityResolve,
GlobalCommandPermissions = 'GlobalCommandPermissions',
GuildUncachedEntityResolve = 'GuildUncachedEntityResolve',
InteractionAlreadyReplied,
InteractionNotReplied,
InteractionEphemeralReplied,
InteractionAlreadyReplied = 'InteractionAlreadyReplied',
InteractionNotReplied = 'InteractionNotReplied',
InteractionEphemeralReplied = 'InteractionEphemeralReplied',
CommandInteractionOptionNotFound,
CommandInteractionOptionType,
CommandInteractionOptionEmpty,
CommandInteractionOptionNoSubcommand,
CommandInteractionOptionNoSubcommandGroup,
AutocompleteInteractionOptionNoFocusedOption,
CommandInteractionOptionNotFound = 'CommandInteractionOptionNotFound',
CommandInteractionOptionType = 'CommandInteractionOptionType',
CommandInteractionOptionEmpty = 'CommandInteractionOptionEmpty',
CommandInteractionOptionNoSubcommand = 'CommandInteractionOptionNoSubcommand',
CommandInteractionOptionNoSubcommandGroup = 'CommandInteractionOptionNoSubcommandGroup',
AutocompleteInteractionOptionNoFocusedOption = 'AutocompleteInteractionOptionNoFocusedOption',
ModalSubmitInteractionFieldNotFound,
ModalSubmitInteractionFieldType,
ModalSubmitInteractionFieldNotFound = 'ModalSubmitInteractionFieldNotFound',
ModalSubmitInteractionFieldType = 'ModalSubmitInteractionFieldType',
InvalidMissingScopes,
InvalidMissingScopes = 'InvalidMissingScopes',
NotImplemented,
NotImplemented = 'NotImplemented',
SweepFilterReturn,
SweepFilterReturn = 'SweepFilterReturn',
}
export interface DiscordjsErrorFields<Name extends string> {
readonly name: `${Name} [${keyof typeof DiscordjsErrorCodes}]`;
get code(): keyof typeof DiscordjsErrorCodes;
readonly name: `${Name} [${DiscordjsErrorCodes}]`;
get code(): DiscordjsErrorCodes;
}
export function DiscordjsErrorMixin<T, N extends string>(
@@ -3404,6 +3412,12 @@ export class GuildManager extends CachedManager<Snowflake, Guild, GuildResolvabl
public fetch(options?: FetchGuildsOptions): Promise<Collection<Snowflake, OAuth2Guild>>;
}
export interface AddOrRemoveGuildMemberRoleOptions {
user: GuildMemberResolvable;
role: RoleResolvable;
reason?: string;
}
export class GuildMemberManager extends CachedManager<Snowflake, GuildMember, GuildMemberResolvable> {
private constructor(guild: Guild, iterable?: Iterable<RawGuildMemberData>);
public guild: Guild;
@@ -3426,6 +3440,8 @@ export class GuildMemberManager extends CachedManager<Snowflake, GuildMember, Gu
public prune(options?: GuildPruneMembersOptions): Promise<number>;
public search(options: GuildSearchMembersOptions): Promise<Collection<Snowflake, GuildMember>>;
public unban(user: UserResolvable, reason?: string): Promise<User | null>;
public addRole(options: AddOrRemoveGuildMemberRoleOptions): Promise<GuildMember | User | Snowflake>;
public removeRole(options: AddOrRemoveGuildMemberRoleOptions): Promise<GuildMember | User | Snowflake>;
}
export class GuildBanManager extends CachedManager<Snowflake, GuildBan, GuildBanResolvable> {
@@ -3656,7 +3672,7 @@ export interface TextBasedChannelFields extends PartialTextBasedChannelFields {
bulkDelete(
messages: Collection<Snowflake, Message> | readonly MessageResolvable[] | number,
filterOld?: boolean,
): Promise<Collection<Snowflake, Message>>;
): Promise<Collection<Snowflake, Message | PartialMessage | undefined>>;
createMessageComponentCollector<T extends MessageComponentType>(
options?: MessageChannelCollectorOptionsParams<T, true>,
): InteractionCollector<MappedInteractionTypes[T]>;
@@ -3793,31 +3809,85 @@ export interface ApplicationCommandChannelOption extends BaseApplicationCommandO
channelTypes?: ChannelType[];
}
export interface ApplicationCommandRoleOptionData extends BaseApplicationCommandOptionsData {
type: ApplicationCommandOptionType.Role;
}
export interface ApplicationCommandRoleOption extends BaseApplicationCommandOptionsData {
type: ApplicationCommandOptionType.Role;
}
export interface ApplicationCommandUserOptionData extends BaseApplicationCommandOptionsData {
type: ApplicationCommandOptionType.User;
}
export interface ApplicationCommandUserOption extends BaseApplicationCommandOptionsData {
type: ApplicationCommandOptionType.User;
}
export interface ApplicationCommandMentionableOptionData extends BaseApplicationCommandOptionsData {
type: ApplicationCommandOptionType.Mentionable;
}
export interface ApplicationCommandMentionableOption extends BaseApplicationCommandOptionsData {
type: ApplicationCommandOptionType.Mentionable;
}
export interface ApplicationCommandAttachmentOption extends BaseApplicationCommandOptionsData {
type: ApplicationCommandOptionType.Attachment;
}
export interface ApplicationCommandAutocompleteOption extends Omit<BaseApplicationCommandOptionsData, 'autocomplete'> {
type:
| ApplicationCommandOptionType.String
| ApplicationCommandOptionType.Number
| ApplicationCommandOptionType.Integer;
export interface ApplicationCommandAutocompleteNumericOption
extends Omit<BaseApplicationCommandOptionsData, 'autocomplete'> {
type: CommandOptionNumericResolvableType;
minValue?: number;
maxValue?: number;
autocomplete: true;
}
export interface ApplicationCommandChoicesData extends Omit<BaseApplicationCommandOptionsData, 'autocomplete'> {
export interface ApplicationCommandAutocompleteStringOption
extends Omit<BaseApplicationCommandOptionsData, 'autocomplete'> {
type: ApplicationCommandOptionType.String;
minLength?: number;
maxLength?: number;
autocomplete: true;
}
export interface ApplicationCommandAutocompleteNumericOptionData
extends Omit<BaseApplicationCommandOptionsData, 'autocomplete'> {
type: CommandOptionNumericResolvableType;
minValue?: number;
min_value?: number;
maxValue?: number;
max_value?: number;
autocomplete: true;
}
export interface ApplicationCommandAutocompleteStringOptionData
extends Omit<BaseApplicationCommandOptionsData, 'autocomplete'> {
type: ApplicationCommandOptionType.String;
minLength?: number;
min_length?: number;
maxLength?: number;
max_length?: number;
autocomplete: true;
}
export interface ApplicationCommandChoicesData<Type extends string | number = string | number>
extends Omit<BaseApplicationCommandOptionsData, 'autocomplete'> {
type: CommandOptionChoiceResolvableType;
choices?: ApplicationCommandOptionChoiceData[];
choices?: ApplicationCommandOptionChoiceData<Type>[];
autocomplete?: false;
}
export interface ApplicationCommandChoicesOption extends Omit<BaseApplicationCommandOptionsData, 'autocomplete'> {
export interface ApplicationCommandChoicesOption<Type extends string | number = string | number>
extends Omit<BaseApplicationCommandOptionsData, 'autocomplete'> {
type: CommandOptionChoiceResolvableType;
choices?: ApplicationCommandOptionChoiceData[];
choices?: ApplicationCommandOptionChoiceData<Type>[];
autocomplete?: false;
}
export interface ApplicationCommandNumericOptionData extends ApplicationCommandChoicesData {
export interface ApplicationCommandNumericOptionData extends ApplicationCommandChoicesData<number> {
type: CommandOptionNumericResolvableType;
minValue?: number;
min_value?: number;
@@ -3825,7 +3895,7 @@ export interface ApplicationCommandNumericOptionData extends ApplicationCommandC
max_value?: number;
}
export interface ApplicationCommandStringOptionData extends ApplicationCommandChoicesData {
export interface ApplicationCommandStringOptionData extends ApplicationCommandChoicesData<string> {
type: ApplicationCommandOptionType.String;
minLength?: number;
min_length?: number;
@@ -3833,18 +3903,26 @@ export interface ApplicationCommandStringOptionData extends ApplicationCommandCh
max_length?: number;
}
export interface ApplicationCommandNumericOption extends ApplicationCommandChoicesOption {
export interface ApplicationCommandBooleanOptionData extends BaseApplicationCommandOptionsData {
type: ApplicationCommandOptionType.Boolean;
}
export interface ApplicationCommandNumericOption extends ApplicationCommandChoicesOption<number> {
type: CommandOptionNumericResolvableType;
minValue?: number;
maxValue?: number;
}
export interface ApplicationCommandStringOption extends ApplicationCommandChoicesOption {
export interface ApplicationCommandStringOption extends ApplicationCommandChoicesOption<string> {
type: ApplicationCommandOptionType.String;
minLength?: number;
maxLength?: number;
}
export interface ApplicationCommandBooleanOption extends BaseApplicationCommandOptionsData {
type: ApplicationCommandOptionType.Boolean;
}
export interface ApplicationCommandSubGroupData extends Omit<BaseApplicationCommandOptionsData, 'required'> {
type: ApplicationCommandOptionType.SubcommandGroup;
options?: ApplicationCommandSubCommandData[];
@@ -3857,19 +3935,12 @@ export interface ApplicationCommandSubGroup extends Omit<BaseApplicationCommandO
export interface ApplicationCommandSubCommandData extends Omit<BaseApplicationCommandOptionsData, 'required'> {
type: ApplicationCommandOptionType.Subcommand;
options?: (
| ApplicationCommandChoicesData
| ApplicationCommandNonOptionsData
| ApplicationCommandChannelOptionData
| ApplicationCommandAutocompleteOption
| ApplicationCommandNumericOptionData
| ApplicationCommandStringOptionData
)[];
options?: Exclude<ApplicationCommandOptionData, ApplicationCommandSubGroupData | ApplicationCommandSubCommandData>[];
}
export interface ApplicationCommandSubCommand extends Omit<BaseApplicationCommandOptionsData, 'required'> {
type: ApplicationCommandOptionType.Subcommand;
options?: (ApplicationCommandChoicesOption | ApplicationCommandNonOptions | ApplicationCommandChannelOption)[];
options?: Exclude<ApplicationCommandOption, ApplicationCommandSubGroup | ApplicationCommandSubCommand>[];
}
export interface ApplicationCommandNonOptionsData extends BaseApplicationCommandOptionsData {
@@ -3884,26 +3955,35 @@ export type ApplicationCommandOptionData =
| ApplicationCommandSubGroupData
| ApplicationCommandNonOptionsData
| ApplicationCommandChannelOptionData
| ApplicationCommandChoicesData
| ApplicationCommandAutocompleteOption
| ApplicationCommandAutocompleteNumericOptionData
| ApplicationCommandAutocompleteStringOptionData
| ApplicationCommandNumericOptionData
| ApplicationCommandStringOptionData
| ApplicationCommandRoleOptionData
| ApplicationCommandUserOptionData
| ApplicationCommandMentionableOptionData
| ApplicationCommandBooleanOptionData
| ApplicationCommandSubCommandData;
export type ApplicationCommandOption =
| ApplicationCommandSubGroup
| ApplicationCommandAutocompleteNumericOption
| ApplicationCommandAutocompleteStringOption
| ApplicationCommandNonOptions
| ApplicationCommandChannelOption
| ApplicationCommandChoicesOption
| ApplicationCommandNumericOption
| ApplicationCommandStringOption
| ApplicationCommandRoleOption
| ApplicationCommandUserOption
| ApplicationCommandMentionableOption
| ApplicationCommandBooleanOption
| ApplicationCommandAttachmentOption
| ApplicationCommandSubCommand;
export interface ApplicationCommandOptionChoiceData {
export interface ApplicationCommandOptionChoiceData<Value extends string | number = string | number> {
name: string;
nameLocalizations?: LocalizationMap;
value: string | number;
value: Value;
}
export interface ApplicationCommandPermissions {
@@ -4077,7 +4157,7 @@ export interface ChannelWebhookCreateOptions {
}
export interface WebhookCreateOptions extends ChannelWebhookCreateOptions {
channel: GuildChannelResolvable;
channel: TextChannel | NewsChannel | VoiceChannel | Snowflake;
}
export interface ClientEvents {
@@ -4121,7 +4201,7 @@ export interface ClientEvents {
reactions: Collection<string | Snowflake, MessageReaction>,
];
messageReactionRemoveEmoji: [reaction: MessageReaction | PartialMessageReaction];
messageDeleteBulk: [messages: Collection<Snowflake, Message | PartialMessage>, channel: TextBasedChannel];
messageDeleteBulk: [messages: Collection<Snowflake, Message | PartialMessage>, channel: GuildTextBasedChannel];
messageReactionAdd: [reaction: MessageReaction | PartialMessageReaction, user: User | PartialUser];
messageReactionRemove: [reaction: MessageReaction | PartialMessageReaction, user: User | PartialUser];
messageUpdate: [oldMessage: Message | PartialMessage, newMessage: Message | PartialMessage];
@@ -4658,7 +4738,7 @@ export interface GuildAuditLogsEntryExtraField {
[AuditLogEvent.StageInstanceCreate]: StageChannel | { id: Snowflake };
[AuditLogEvent.StageInstanceDelete]: StageChannel | { id: Snowflake };
[AuditLogEvent.StageInstanceUpdate]: StageChannel | { id: Snowflake };
[AuditLogEvent.ApplicationCommandPermissionUpdate]: { applicationId: Snowflake; guild: Guild | { id: Snowflake } };
[AuditLogEvent.ApplicationCommandPermissionUpdate]: { applicationId: Snowflake };
}
export interface GuildAuditLogsEntryTargetField<TActionType extends GuildAuditLogsActionType> {
@@ -4750,7 +4830,7 @@ export interface GuildCreateOptions {
export interface GuildWidgetSettings {
enabled: boolean;
channel: NonThreadGuildBasedChannel | null;
channel: TextChannel | NewsChannel | VoiceBasedChannel | null;
}
export interface GuildEditData {
@@ -4828,7 +4908,7 @@ export interface GuildPruneMembersOptions {
export interface GuildWidgetSettingsData {
enabled: boolean;
channel: GuildChannelResolvable | null;
channel: TextChannel | NewsChannel | VoiceBasedChannel | Snowflake | null;
}
export interface GuildSearchMembersOptions {

View File

@@ -134,6 +134,8 @@ import {
Webhook,
WebhookClient,
InteractionWebhook,
GuildAuditLogsActionType,
GuildAuditLogsTargetType,
} from '.';
import { expectAssignable, expectNotAssignable, expectNotType, expectType } from 'tsd';
import type { ContextMenuCommandBuilder, SlashCommandBuilder } from '@discordjs/builders';
@@ -1100,6 +1102,7 @@ expectAssignable<'death'>(ShardEvents.Death);
expectAssignable<1>(Status.Connecting);
declare const applicationCommandData: ApplicationCommandData;
declare const applicationCommandOptionData: ApplicationCommandOptionData;
declare const applicationCommandResolvable: ApplicationCommandResolvable;
declare const applicationCommandManager: ApplicationCommandManager;
{
@@ -1119,6 +1122,24 @@ declare const applicationCommandManager: ApplicationCommandManager;
expectType<Promise<Collection<Snowflake, ApplicationCommand>>>(
applicationCommandManager.set([applicationCommandData], '0'),
);
// Test inference of choice values.
if ('choices' in applicationCommandOptionData) {
if (applicationCommandOptionData.type === ApplicationCommandOptionType.String) {
expectType<string>(applicationCommandOptionData.choices[0]!.value);
expectNotType<number>(applicationCommandOptionData.choices[0]!.value);
}
if (applicationCommandOptionData.type === ApplicationCommandOptionType.Integer) {
expectType<number>(applicationCommandOptionData.choices[0]!.value);
expectNotType<string>(applicationCommandOptionData.choices[0]!.value);
}
if (applicationCommandOptionData.type === ApplicationCommandOptionType.Number) {
expectType<number>(applicationCommandOptionData.choices[0]!.value);
expectNotType<string>(applicationCommandOptionData.choices[0]!.value);
}
}
}
declare const applicationNonChoiceOptionData: ApplicationCommandOptionData & {
@@ -1533,7 +1554,7 @@ expectType<Promise<GuildAuditLogs<AuditLogEvent.IntegrationUpdate>>>(
);
expectType<Promise<GuildAuditLogs<null>>>(guild.fetchAuditLogs({ type: null }));
expectType<Promise<GuildAuditLogs<null>>>(guild.fetchAuditLogs());
expectType<Promise<GuildAuditLogs<AuditLogEvent>>>(guild.fetchAuditLogs());
expectType<Promise<GuildAuditLogsEntry<AuditLogEvent.MemberKick, 'Delete', 'User'> | undefined>>(
guild.fetchAuditLogs({ type: AuditLogEvent.MemberKick }).then(al => al.entries.first()),
@@ -1542,10 +1563,10 @@ expectAssignable<Promise<GuildAuditLogsEntry<AuditLogEvent.MemberKick, 'Delete',
guild.fetchAuditLogs({ type: AuditLogEvent.MemberKick }).then(al => al.entries.first()),
);
expectType<Promise<GuildAuditLogsEntry<null, 'All', 'Unknown'> | undefined>>(
expectType<Promise<GuildAuditLogsEntry<null, GuildAuditLogsActionType, GuildAuditLogsTargetType> | undefined>>(
guild.fetchAuditLogs({ type: null }).then(al => al.entries.first()),
);
expectType<Promise<GuildAuditLogsEntry<null, 'All', 'Unknown'> | undefined>>(
expectType<Promise<GuildAuditLogsEntry<null, GuildAuditLogsActionType, GuildAuditLogsTargetType> | undefined>>(
guild.fetchAuditLogs().then(al => al.entries.first()),
);

View File

@@ -1,3 +1,9 @@
import { createUnbuildConfig } from '../../build.config';
export default createUnbuildConfig({ minify: true, externals: ['package.cjs', 'package.mjs'] });
export default createUnbuildConfig({
entries: [
{ builder: 'rollup', input: 'src/index' },
{ builder: 'rollup', input: 'src/cli' },
],
minify: true,
});

View File

@@ -1,17 +1,17 @@
{
"name": "@discordjs/docgen",
"version": "0.12.0",
"version": "0.12.1",
"description": "The docs.json generator for discord.js and its related projects",
"scripts": {
"build": "unbuild",
"lint": "prettier --check . && eslint src --ext mjs,js,ts",
"format": "prettier --write . && eslint src --ext mjs,js,ts --fix",
"lint": "prettier --check . && TIMING=1 eslint src --ext mjs,js,ts",
"format": "prettier --write . && TIMING=1 eslint src --ext mjs,js,ts --fix",
"fmt": "yarn format",
"prepack": "yarn lint && yarn test && yarn build",
"prepack": "yarn format && yarn build",
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/docgen/*'",
"release": "cliff-jumper"
},
"bin": "./dist/index.cjs",
"bin": "./dist/cli.cjs",
"directories": {
"lib": "src"
},
@@ -42,23 +42,31 @@
},
"homepage": "https://discord.js.org",
"dependencies": {
"@discordjs/collection": "workspace:^",
"commander": "^9.4.0",
"jsdoc-to-markdown": "^7.1.1",
"tslib": "^2.4.0",
"typedoc": "^0.23.9"
"typedoc": "^0.23.10"
},
"devDependencies": {
"@favware/cliff-jumper": "^1.8.5",
"@favware/cliff-jumper": "^1.8.7",
"@types/jsdoc-to-markdown": "^7.0.3",
"@types/node": "^16.11.46",
"eslint": "^8.20.0",
"@types/node": "^16.11.52",
"@typescript-eslint/eslint-plugin": "^5.33.1",
"@typescript-eslint/parser": "^5.33.1",
"eslint": "^8.22.0",
"eslint-config-marine": "^9.4.1",
"eslint-config-prettier": "^8.5.0",
"eslint-import-resolver-typescript": "^3.4.2",
"eslint-plugin-import": "^2.26.0",
"prettier": "^2.7.1",
"rollup-plugin-typescript2": "0.32.1",
"rollup-plugin-typescript2": "^0.33.0",
"typescript": "^4.7.4",
"unbuild": "^0.7.6"
"unbuild": "^0.8.9"
},
"engines": {
"node": ">=16.9.0"
},
"publishConfig": {
"access": "public"
}
}

View File

@@ -0,0 +1,25 @@
#!/usr/bin/env node
import { createCommand } from 'commander';
import { build } from './index.js';
import packageFile from '../package.json';
export interface CLIOptions {
input: string[];
custom: string;
root: string;
output: string;
typescript: boolean;
}
const command = createCommand()
.version(packageFile.version)
.option('-i, --input <string...>', 'Source directories to parse JSDocs in')
.option('-c, --custom <string>', 'Custom docs definition file to use')
.option('-r, --root [string]', 'Root directory of the project', '.')
.option('-o, --output <string>', 'Path to output file')
.option('--typescript', '', false);
const program = command.parse(process.argv);
const options = program.opts<CLIOptions>();
build(options);

View File

@@ -1,5 +1,4 @@
import { dirname, join, relative } from 'node:path';
import { Collection } from '@discordjs/collection';
import type { DeclarationReflection } from 'typedoc';
import type { ChildTypes, Class, Config, CustomDocs, RootTypes } from './interfaces/index.js';
import { DocumentedClass } from './types/class.js';
@@ -13,15 +12,15 @@ import { DocumentedTypeDef } from './types/typedef.js';
import packageFile from '../package.json';
export class Documentation {
public readonly classes = new Collection<string, DocumentedClass>();
public readonly classes = new Map<string, DocumentedClass>();
public readonly functions = new Collection<string, DocumentedMethod>();
public readonly functions = new Map<string, DocumentedMethod>();
public readonly interfaces = new Collection<string, DocumentedInterface>();
public readonly interfaces = new Map<string, DocumentedInterface>();
public readonly typedefs = new Collection<string, DocumentedTypeDef>();
public readonly typedefs = new Map<string, DocumentedTypeDef>();
public readonly externals = new Collection<string, DocumentedExternal>();
public readonly externals = new Map<string, DocumentedExternal>();
public constructor(
data: RootTypes[] | DeclarationReflection[],
@@ -244,11 +243,11 @@ export class Documentation {
format: Documentation.FORMAT_VERSION,
date: Date.now(),
},
classes: this.classes.map((c) => c.serialize()),
functions: this.functions.map((f) => f.serialize()),
interfaces: this.interfaces.map((i) => i.serialize()),
typedefs: this.typedefs.map((t) => t.serialize()),
externals: this.externals.map((e) => e.serialize()),
classes: [...this.classes.values()].map((c) => c.serialize()),
functions: [...this.functions.values()].map((f) => f.serialize()),
interfaces: [...this.interfaces.values()].map((i) => i.serialize()),
typedefs: [...this.typedefs.values()].map((t) => t.serialize()),
externals: [...this.externals.values()].map((e) => e.serialize()),
custom: this.custom,
};
}

View File

@@ -1,20 +1,10 @@
#!/usr/bin/env node
import { readFileSync, writeFileSync } from 'node:fs';
import { join, basename, extname, dirname, relative } from 'node:path';
import { createCommand } from 'commander';
import { dirname, join, extname, basename, relative } from 'node:path';
import jsdoc2md from 'jsdoc-to-markdown';
import { Application, DeclarationReflection, TSConfigReader } from 'typedoc';
import { Documentation } from './documentation.js';
import type { ChildTypes, CustomDocs, RootTypes } from './interfaces/index.js';
import packageFile from '../package.json';
interface CLIOptions {
input: string[];
custom: string;
root: string;
output: string;
typescript: boolean;
}
import { type DeclarationReflection, Application, TSConfigReader } from 'typedoc';
import type { CLIOptions } from './cli';
import { Documentation } from './documentation';
import type { RootTypes, ChildTypes, CustomDocs } from './interfaces';
interface CustomFiles {
id?: string;
@@ -27,79 +17,70 @@ interface CustomFiles {
}[];
}
const command = createCommand()
.version(packageFile.version)
.option('-i, --input <string...>', 'Source directories to parse JSDocs in')
.option('-c, --custom <string>', 'Custom docs definition file to use')
.option('-r, --root [string]', 'Root directory of the project', '.')
.option('-o, --output <string>', 'Path to output file')
.option('--typescript', '', false);
const program = command.parse(process.argv);
const options = program.opts<CLIOptions>();
let data: (RootTypes & ChildTypes)[] | DeclarationReflection[] = [];
if (options.typescript) {
console.log('Parsing Typescript in source files...');
const app = new Application();
app.options.addReader(new TSConfigReader());
app.bootstrap({ entryPoints: options.input });
const project = app.convert();
if (project) {
// @ts-expect-error
data = app.serializer.toObject(project).children!;
console.log(`${data.length} items parsed.`);
}
} else {
console.log('Parsing JSDocs in source files...');
data = jsdoc2md.getTemplateDataSync({ files: options.input }) as (RootTypes & ChildTypes)[];
console.log(`${data.length} JSDoc items parsed.`);
}
const custom: Record<string, CustomDocs> = {};
if (options.custom) {
console.log('Loading custom docs files...');
const customDir = dirname(options.custom);
const file = readFileSync(options.custom, 'utf-8');
const data = JSON.parse(file) as CustomFiles[];
for (const category of data) {
const categoryId = category.id ?? category.name.toLowerCase();
const dir = join(customDir, category.path ?? categoryId);
custom[categoryId] = {
name: category.name || category.id!,
files: {},
};
for (const f of category.files) {
const fileRootPath = join(dir, f.path);
const extension = extname(f.path);
const fileId = f.id ?? basename(f.path, extension);
const fileData = readFileSync(fileRootPath, 'utf-8');
custom[categoryId]!.files[fileId] = {
name: f.name,
type: extension.toLowerCase().replace(/^\./, ''),
content: fileData,
path: relative(options.root, fileRootPath).replace(/\\/g, '/'),
};
export function build({ input, custom: customDocs, root, output, typescript }: CLIOptions) {
let data: (RootTypes & ChildTypes)[] | DeclarationReflection[] = [];
if (typescript) {
console.log('Parsing Typescript in source files...');
const app = new Application();
app.options.addReader(new TSConfigReader());
app.bootstrap({ entryPoints: input });
const project = app.convert();
if (project) {
// @ts-expect-error
data = app.serializer.toObject(project).children!;
console.log(`${data.length} items parsed.`);
}
} else {
console.log('Parsing JSDocs in source files...');
data = jsdoc2md.getTemplateDataSync({ files: input }) as (RootTypes & ChildTypes)[];
console.log(`${data.length} JSDoc items parsed.`);
}
const fileCount = Object.keys(custom)
.map((k) => Object.keys(custom[k]!))
.reduce((prev, c) => prev + c.length, 0);
const categoryCount = Object.keys(custom).length;
console.log(
`${fileCount} custom docs file${fileCount === 1 ? '' : 's'} in ` +
`${categoryCount} categor${categoryCount === 1 ? 'y' : 'ies'} loaded.`,
);
}
const custom: Record<string, CustomDocs> = {};
if (customDocs) {
console.log('Loading custom docs files...');
const customDir = dirname(customDocs);
const file = readFileSync(customDocs, 'utf-8');
const data = JSON.parse(file) as CustomFiles[];
console.log(`Serializing documentation with format version ${Documentation.FORMAT_VERSION}...`);
const docs = new Documentation(data, options, custom);
for (const category of data) {
const categoryId = category.id ?? category.name.toLowerCase();
const dir = join(customDir, category.path ?? categoryId);
custom[categoryId] = {
name: category.name || category.id!,
files: {},
};
if (options.output) {
console.log(`Writing to ${options.output}...`);
writeFileSync(options.output, JSON.stringify(docs.serialize()));
for (const f of category.files) {
const fileRootPath = join(dir, f.path);
const extension = extname(f.path);
const fileId = f.id ?? basename(f.path, extension);
const fileData = readFileSync(fileRootPath, 'utf-8');
custom[categoryId]!.files[fileId] = {
name: f.name,
type: extension.toLowerCase().replace(/^\./, ''),
content: fileData,
path: relative(root, fileRootPath).replace(/\\/g, '/'),
};
}
}
const fileCount = Object.keys(custom)
.map((k) => Object.keys(custom[k]!))
.reduce((prev, c) => prev + c.length, 0);
const categoryCount = Object.keys(custom).length;
console.log(
`${fileCount} custom docs file${fileCount === 1 ? '' : 's'} in ` +
`${categoryCount} categor${categoryCount === 1 ? 'y' : 'ies'} loaded.`,
);
}
console.log(`Serializing documentation with format version ${Documentation.FORMAT_VERSION}...`);
const docs = new Documentation(data, { input, custom: customDocs, root, output, typescript }, custom);
if (output) {
console.log(`Writing to ${output}...`);
writeFileSync(output, JSON.stringify(docs.serialize()));
}
console.log('Done!');
}
console.log('Done!');

View File

@@ -1,7 +1,7 @@
import type { Type } from './index.js';
export interface Return {
type: Type;
type: Required<Type>;
nullable?: boolean;
description?: string;
}

View File

@@ -1,3 +1,3 @@
export interface Type {
names?: string[];
names?: string[] | undefined;
}

View File

@@ -1,7 +1,7 @@
import type { Type } from './index.js';
export interface VarType extends Type {
type?: Required<Type>;
description?: string;
nullable?: boolean;
type?: Required<Type> | undefined;
description?: string | undefined;
nullable?: boolean | undefined;
}

View File

@@ -1,5 +1,4 @@
import { parse } from 'node:path';
import { Collection } from '@discordjs/collection';
import type { DeclarationReflection } from 'typedoc';
import { DocumentedConstructor } from './constructor.js';
import { DocumentedEvent } from './event.js';
@@ -12,11 +11,11 @@ import type { Class, Config } from '../interfaces/index.js';
import { parseType } from '../util/parseType.js';
export class DocumentedClass extends DocumentedItem<Class | DeclarationReflection> {
public readonly props = new Collection<string, DocumentedMember>();
public readonly props = new Map<string, DocumentedMember>();
public readonly methods = new Collection<string, DocumentedMethod>();
public readonly methods = new Map<string, DocumentedMethod>();
public readonly events = new Collection<string, DocumentedEvent>();
public readonly events = new Map<string, DocumentedEvent>();
public construct: DocumentedConstructor | null = null;
@@ -120,9 +119,9 @@ export class DocumentedClass extends DocumentedItem<Class | DeclarationReflectio
.trim() ?? true
: undefined,
construct: this.construct?.serialize(),
props: this.props.size ? this.props.map((p) => p.serialize()) : undefined,
methods: this.methods.size ? this.methods.map((m) => m.serialize()) : undefined,
events: this.events.size ? this.events.map((e) => e.serialize()) : undefined,
props: this.props.size ? [...this.props.values()].map((p) => p.serialize()) : undefined,
methods: this.methods.size ? [...this.methods.values()].map((m) => m.serialize()) : undefined,
events: this.events.size ? [...this.events.values()].map((e) => e.serialize()) : undefined,
meta,
};
}
@@ -138,9 +137,9 @@ export class DocumentedClass extends DocumentedItem<Class | DeclarationReflectio
abstract: data.virtual,
deprecated: data.deprecated,
construct: this.construct?.serialize(),
props: this.props.size ? this.props.map((p) => p.serialize()) : undefined,
methods: this.methods.size ? this.methods.map((m) => m.serialize()) : undefined,
events: this.events.size ? this.events.map((e) => e.serialize()) : undefined,
props: this.props.size ? [...this.props.values()].map((p) => p.serialize()) : undefined,
methods: this.methods.size ? [...this.methods.values()].map((m) => m.serialize()) : undefined,
events: this.events.size ? [...this.events.values()].map((e) => e.serialize()) : undefined,
meta: new DocumentedItemMeta(data.meta, this.config).serialize(),
};
}

View File

@@ -4,8 +4,8 @@
"description": "Lightweight HTTP proxy for Discord's API, brought to you as a container 📦",
"scripts": {
"build": "unbuild",
"lint": "prettier --check . && eslint src --ext mjs,js,ts",
"format": "prettier --write . && eslint src --ext mjs,js,ts --fix",
"lint": "prettier --check . && TIMING=1 eslint src --ext mjs,js,ts",
"format": "prettier --write . && TIMING=1 eslint src --ext mjs,js,ts --fix",
"fmt": "yarn format",
"prepack": "yarn lint && yarn test && yarn build",
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/proxy-container/*'"
@@ -49,12 +49,18 @@
"tslib": "^2.4.0"
},
"devDependencies": {
"@types/node": "^16.11.46",
"eslint": "^8.20.0",
"@types/node": "^16.11.52",
"@typescript-eslint/eslint-plugin": "^5.33.1",
"@typescript-eslint/parser": "^5.33.1",
"eslint": "^8.22.0",
"eslint-config-marine": "^9.4.1",
"eslint-config-prettier": "^8.5.0",
"eslint-import-resolver-typescript": "^3.4.2",
"eslint-plugin-import": "^2.26.0",
"prettier": "^2.7.1",
"rollup-plugin-typescript2": "0.32.1",
"rollup-plugin-typescript2": "^0.33.0",
"typescript": "^4.7.4",
"unbuild": "^0.7.6"
"unbuild": "^0.8.9"
},
"engines": {
"node": ">=16.9.0"

View File

@@ -1,3 +1,7 @@
{
"extends": "../../.eslintrc.json"
"extends": "../../.eslintrc.json",
"plugins": ["eslint-plugin-tsdoc"],
"rules": {
"tsdoc/syntax": "warn"
}
}

View File

@@ -5,8 +5,8 @@
"scripts": {
"test": "vitest run",
"build": "unbuild",
"lint": "prettier --check . && eslint src __tests__ --ext mjs,js,ts",
"format": "prettier --write . && eslint src __tests__ --ext mjs,js,ts --fix",
"lint": "prettier --check . && TIMING=1 eslint src __tests__ --ext mjs,js,ts",
"format": "prettier --write . && TIMING=1 eslint src __tests__ --ext mjs,js,ts --fix",
"fmt": "yarn format",
"docs": "downlevel-dts . docs --to=3.7 && docgen -i src/index.ts -c docs/index.json -o docs/docs.json --typescript && api-extractor run --local",
"prepack": "yarn lint && yarn test && yarn build",
@@ -56,23 +56,29 @@
"dependencies": {
"@discordjs/rest": "^1.0.0",
"tslib": "^2.4.0",
"undici": "^5.8.0"
"undici": "^5.9.1"
},
"devDependencies": {
"@discordjs/docgen": "workspace:^",
"@favware/cliff-jumper": "^1.8.5",
"@microsoft/api-extractor": "^7.28.6",
"@types/node": "^16.11.46",
"@favware/cliff-jumper": "^1.8.7",
"@microsoft/api-extractor": "^7.29.3",
"@types/node": "^16.11.52",
"@types/supertest": "^2.0.12",
"c8": "^7.12.0",
"@typescript-eslint/eslint-plugin": "^5.33.1",
"@typescript-eslint/parser": "^5.33.1",
"@vitest/coverage-c8": "^0.22.1",
"downlevel-dts": "^0.10.0",
"eslint": "^8.20.0",
"eslint": "^8.22.0",
"eslint-config-marine": "^9.4.1",
"eslint-config-prettier": "^8.5.0",
"eslint-import-resolver-typescript": "^3.4.2",
"eslint-plugin-import": "^2.26.0",
"prettier": "^2.7.1",
"rollup-plugin-typescript2": "0.32.1",
"rollup-plugin-typescript2": "^0.33.0",
"supertest": "^6.2.4",
"typescript": "^4.7.4",
"unbuild": "^0.7.6",
"vitest": "^0.19.1"
"unbuild": "^0.8.9",
"vitest": "^0.22.1"
},
"engines": {
"node": ">=16.9.0"

View File

@@ -19,7 +19,7 @@ export function proxyRequests(rest: REST): RequestHandler {
if (!method || !url) {
throw new TypeError(
'Invalid request. Missing method and/or url, implying that this is not a Server IncomingMesage',
'Invalid request. Missing method and/or url, implying that this is not a Server IncomingMessage',
);
}

View File

@@ -1,7 +1,4 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"exactOptionalPropertyTypes": false
},
"include": ["src/**/*.ts"]
}

View File

@@ -1,3 +1,7 @@
{
"extends": "../../.eslintrc.json"
"extends": "../../.eslintrc.json",
"plugins": ["eslint-plugin-tsdoc"],
"rules": {
"tsdoc/syntax": "warn"
}
}

View File

@@ -2,6 +2,18 @@
All notable changes to this project will be documented in this file.
# [@discordjs/rest@1.1.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@1.0.1...@discordjs/rest@1.1.0) - (2022-08-22)
## Features
- **website:** Show `constructor` information (#8540) ([e42fd16](https://github.com/discordjs/discord.js/commit/e42fd1636973b10dd7ed6fb4280ee1a4a8f82007))
- **website:** Render `@defaultValue` blocks (#8527) ([8028813](https://github.com/discordjs/discord.js/commit/8028813825e7708915ea892760c1003afd60df2f))
- **WebSocketShard:** Support new resume url (#8480) ([bc06cc6](https://github.com/discordjs/discord.js/commit/bc06cc638d2f57ab5c600e8cdb6afc8eb2180166))
## Refactor
- Docs design (#8487) ([4ab1d09](https://github.com/discordjs/discord.js/commit/4ab1d09997a18879a9eb9bda39df6f15aa22557e))
# [@discordjs/rest@0.6.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@0.5.0...@discordjs/rest@0.6.0) - (2022-07-17)
## Documentation

View File

@@ -1,12 +1,12 @@
{
"name": "@discordjs/rest",
"version": "1.0.1",
"version": "1.1.0",
"description": "The REST API for discord.js",
"scripts": {
"test": "vitest run",
"build": "unbuild",
"lint": "prettier --check . && eslint src __tests__ --ext mjs,js,ts",
"format": "prettier --write . && eslint src __tests__ --ext mjs,js,ts --fix",
"lint": "prettier --check . && TIMING=1 eslint src __tests__ --ext mjs,js,ts",
"format": "prettier --write . && TIMING=1 eslint src __tests__ --ext mjs,js,ts --fix",
"fmt": "yarn format",
"docs": "downlevel-dts . docs --to=3.7 && docgen -i src/index.ts -c docs/index.json -o docs/docs.json --typescript && api-extractor run --local",
"prepack": "yarn lint && yarn test && yarn build",
@@ -53,26 +53,33 @@
"homepage": "https://discord.js.org",
"dependencies": {
"@discordjs/collection": "workspace:^",
"@sapphire/async-queue": "^1.3.2",
"@sapphire/async-queue": "^1.5.0",
"@sapphire/snowflake": "^3.2.2",
"discord-api-types": "^0.36.3",
"file-type": "^17.1.4",
"discord-api-types": "^0.37.3",
"file-type": "^17.1.6",
"tslib": "^2.4.0",
"undici": "^5.8.0"
"undici": "^5.9.1"
},
"devDependencies": {
"@discordjs/docgen": "workspace:^",
"@favware/cliff-jumper": "^1.8.5",
"@microsoft/api-extractor": "^7.28.6",
"@types/node": "^16.11.46",
"c8": "^7.12.0",
"@favware/cliff-jumper": "^1.8.7",
"@microsoft/api-extractor": "^7.29.3",
"@types/node": "^16.11.52",
"@typescript-eslint/eslint-plugin": "^5.33.1",
"@typescript-eslint/parser": "^5.33.1",
"@vitest/coverage-c8": "^0.22.1",
"downlevel-dts": "^0.10.0",
"eslint": "^8.20.0",
"eslint": "^8.22.0",
"eslint-config-marine": "^9.4.1",
"eslint-config-prettier": "^8.5.0",
"eslint-import-resolver-typescript": "^3.4.2",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-tsdoc": "^0.2.16",
"prettier": "^2.7.1",
"rollup-plugin-typescript2": "0.32.1",
"rollup-plugin-typescript2": "^0.33.0",
"typescript": "^4.7.4",
"unbuild": "^0.7.6",
"vitest": "^0.19.1"
"unbuild": "^0.8.9",
"vitest": "^0.22.1"
},
"engines": {
"node": ">=16.9.0"

View File

@@ -15,7 +15,7 @@ export interface BaseImageURLOptions {
/**
* The extension to use for the image URL
*
* @default 'webp'
* @defaultValue `'webp'`
*/
extension?: ImageExtension;
/**
@@ -41,7 +41,7 @@ export interface MakeURLOptions {
/**
* The extension to use for the image URL
*
* @default 'webp'
* @defaultValue `'webp'`
*/
extension?: string | undefined;
/**

View File

@@ -25,45 +25,45 @@ export interface RESTOptions {
agent: Dispatcher;
/**
* The base api path, without version
* @default 'https://discord.com/api'
* @defaultValue `'https://discord.com/api'`
*/
api: string;
/**
* The authorization prefix to use for requests, useful if you want to use
* bearer tokens
*
* @default 'Bot'
* @defaultValue `'Bot'`
*/
authPrefix: 'Bot' | 'Bearer';
/**
* The cdn path
*
* @default 'https://cdn.discordapp.com'
* @defaultValue 'https://cdn.discordapp.com'
*/
cdn: string;
/**
* Additional headers to send for all API requests
*
* @default {}
* @defaultValue `{}`
*/
headers: Record<string, string>;
/**
* The number of invalid REST requests (those that return 401, 403, or 429) in a 10 minute window between emitted warnings (0 for no warnings).
* That is, if set to 500, warnings will be emitted at invalid request number 500, 1000, 1500, and so on.
*
* @default 0
* @defaultValue `0`
*/
invalidRequestWarningInterval: number;
/**
* How many requests to allow sending per second (Infinity for unlimited, 50 for the standard global limit used by Discord)
*
* @default 50
* @defaultValue `50`
*/
globalRequestsPerSecond: number;
/**
* The extra offset to add to rate limits in milliseconds
*
* @default 50
* @defaultValue `50`
*/
offset: number;
/**
@@ -72,50 +72,50 @@ export interface RESTOptions {
* (e.g. `/channels` to match any route starting with `/channels` such as `/channels/:id/messages`)
* for which to throw {@link RateLimitError}s. All other request routes will be queued normally
*
* @default null
* @defaultValue `null`
*/
rejectOnRateLimit: string[] | RateLimitQueueFilter | null;
/**
* The number of retries for errors with the 500 code, or errors
* that timeout
*
* @default 3
* @defaultValue `3`
*/
retries: number;
/**
* The time to wait in milliseconds before a request is aborted
*
* @default 15_000
* @defaultValue `15_000`
*/
timeout: number;
/**
* Extra information to add to the user agent
*
* @default `Node.js ${process.version}`
* @defaultValue `Node.js ${process.version}`
*/
userAgentAppendix: string;
/**
* The version of the API to use
*
* @default '10'
* @defaultValue `'10'`
*/
version: string;
/**
* The amount of time in milliseconds that passes between each hash sweep. (defaults to 4h)
*
* @default 14_400_000
* @defaultValue `14_400_000`
*/
hashSweepInterval: number;
/**
* The maximum amount of time a hash can exist in milliseconds without being hit with a request (defaults to 24h)
*
* @default 86_400_000
* @defaultValue `86_400_000`
*/
hashLifetime: number;
/**
* The amount of time in milliseconds that passes between each hash sweep. (defaults to 1h)
*
* @default 3_600_000
* @defaultValue `3_600_000`
*/
handlerSweepInterval: number;
}

View File

@@ -50,13 +50,13 @@ export interface RequestData {
/**
* If this request needs the `Authorization` header
*
* @default true
* @defaultValue `true`
*/
auth?: boolean;
/**
* The authorization prefix to use for this request, useful if you use this with bearer tokens
*
* @default 'Bot'
* @defaultValue `'Bot'`
*/
authPrefix?: 'Bot' | 'Bearer';
/**
@@ -65,7 +65,7 @@ export interface RequestData {
*/
body?: BodyInit | unknown;
/**
* The {@link https://undici.nodejs.org/#/docs/api/Agent Agent} to use for the request.
* The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} to use for the request.
*/
dispatcher?: Agent;
/**
@@ -92,7 +92,7 @@ export interface RequestData {
/**
* If this request should be versioned
*
* @default true
* @defaultValue `true`
*/
versioned?: boolean;
}
@@ -174,7 +174,7 @@ export interface RequestManager {
*/
export class RequestManager extends EventEmitter {
/**
* The {@link https://undici.nodejs.org/#/docs/api/Agent Agent} for all requests
* The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} for all requests
* performed by this manager.
*/
public agent: Dispatcher | null = null;
@@ -342,7 +342,7 @@ export class RequestManager extends EventEmitter {
* @param hash - The hash for the route
* @param majorParameter - The major parameter for this handler
*
* @private
* @internal
*/
private createHandler(hash: string, majorParameter: string) {
// Create the async request queue to handle requests
@@ -487,7 +487,7 @@ export class RequestManager extends EventEmitter {
* @param endpoint - The raw endpoint to generalize
* @param method - The HTTP method this endpoint is called without
*
* @private
* @internal
*/
private static generateRouteData(endpoint: RouteLike, method: RequestMethod): RouteData {
const majorIdMatch = /^\/(?:channels|guilds|webhooks)\/(\d{16,19})/.exec(endpoint);

View File

@@ -3,13 +3,27 @@ import type { RequestOptions } from '../REST';
import type { HandlerRequestData, RouteData } from '../RequestManager';
export interface IHandler {
/**
* Queues a request to be sent
*
* @param routeId - The generalized api route with literal ids for major parameters
* @param url - The url to do the request on
* @param options - All the information needed to make a request
* @param requestData - Extra data from the user's request needed for errors and additional processing
*/
queueRequest: (
routeId: RouteData,
url: string,
options: RequestOptions,
requestData: HandlerRequestData,
) => Promise<Dispatcher.ResponseData>;
/**
* If the bucket is currently inactive (no pending requests)
*/
// eslint-disable-next-line @typescript-eslint/method-signature-style -- This is meant to be a getter returning a bool
get inactive(): boolean;
/**
* The unique id of the handler
*/
readonly id: string;
}

View File

@@ -30,7 +30,7 @@ const enum QueueType {
*/
export class SequentialHandler implements IHandler {
/**
* The unique id of the handler
* {@inheritDoc IHandler.id}
*/
public readonly id: string;
@@ -87,7 +87,7 @@ export class SequentialHandler implements IHandler {
}
/**
* If the bucket is currently inactive (no pending requests)
* {@inheritDoc IHandler.inactive}
*/
public get inactive(): boolean {
return (
@@ -161,12 +161,7 @@ export class SequentialHandler implements IHandler {
}
/**
* Queues a request to be sent
*
* @param routeId - The generalized api route with literal ids for major parameters
* @param url - The url to do the request on
* @param options - All the information needed to make a request
* @param requestData - Extra data from the user's request needed for errors and additional processing
* {@inheritDoc IHandler.queueRequest}
*/
public async queueRequest(
routeId: RouteData,

View File

@@ -6,8 +6,8 @@
"scripts": {
"test": "vitest run",
"build": "unbuild",
"lint": "prettier --check . && eslint src --ext mjs,js,ts",
"format": "prettier --write . && eslint src --ext mjs,js,ts --fix",
"lint": "prettier --check . && TIMING=1 eslint src --ext mjs,js,ts",
"format": "prettier --write . && TIMING=1 eslint src --ext mjs,js,ts --fix",
"fmt": "yarn format"
},
"main": "./dist/index.cjs",
@@ -48,14 +48,20 @@
"tslib": "^2.4.0"
},
"devDependencies": {
"@types/node": "^16.11.46",
"c8": "^7.12.0",
"eslint": "^8.20.0",
"@types/node": "^16.11.52",
"@typescript-eslint/eslint-plugin": "^5.33.1",
"@typescript-eslint/parser": "^5.33.1",
"@vitest/coverage-c8": "^0.22.1",
"eslint": "^8.22.0",
"eslint-config-marine": "^9.4.1",
"eslint-config-prettier": "^8.5.0",
"eslint-import-resolver-typescript": "^3.4.2",
"eslint-plugin-import": "^2.26.0",
"prettier": "^2.7.1",
"rollup-plugin-typescript2": "0.32.1",
"rollup-plugin-typescript2": "^0.33.0",
"typescript": "^4.7.4",
"unbuild": "^0.7.6",
"vitest": "^0.19.1"
"unbuild": "^0.8.9",
"vitest": "^0.22.1"
},
"engines": {
"node": ">=16.9.0"

View File

@@ -1,5 +1,9 @@
{
"extends": "../../.eslintrc.json",
"plugins": ["eslint-plugin-tsdoc"],
"rules": {
"tsdoc/syntax": "warn"
},
"parserOptions": {
"project": "./tsconfig.eslint.json",
"extraFileExtensions": [".mjs"]

View File

@@ -5,8 +5,8 @@
"scripts": {
"build": "unbuild",
"test": "jest --coverage",
"lint": "prettier --check . && eslint src __tests__ --ext mjs,js,ts",
"format": "prettier --write . && eslint src __tests__ --ext mjs,js,ts --fix",
"lint": "prettier --check . && TIMING=1 eslint src __tests__ --ext mjs,js,ts",
"format": "prettier --write . && TIMING=1 eslint src __tests__ --ext mjs,js,ts --fix",
"fmt": "yarn format",
"docs": "downlevel-dts . docs --to=3.7 && docgen -i src/index.ts -c docs/index.json -o docs/docs.json --typescript && api-extractor run --local",
"prepack": "yarn lint && yarn test && yarn build",
@@ -53,31 +53,37 @@
"homepage": "https://discord.js.org",
"dependencies": {
"@types/ws": "^8.5.3",
"discord-api-types": "^0.36.3",
"discord-api-types": "^0.37.3",
"prism-media": "^1.3.4",
"tslib": "^2.4.0",
"ws": "^8.8.1"
},
"devDependencies": {
"@babel/core": "^7.18.9",
"@babel/preset-env": "^7.18.9",
"@babel/core": "^7.18.10",
"@babel/preset-env": "^7.18.10",
"@babel/preset-typescript": "^7.18.6",
"@discordjs/docgen": "workspace:^",
"@discordjs/scripts": "workspace:^",
"@favware/cliff-jumper": "^1.8.5",
"@microsoft/api-extractor": "^7.28.6",
"@types/jest": "^28.1.6",
"@types/node": "^16.11.46",
"@favware/cliff-jumper": "^1.8.7",
"@microsoft/api-extractor": "^7.29.3",
"@types/jest": "^28.1.7",
"@types/node": "^16.11.52",
"@typescript-eslint/eslint-plugin": "^5.33.1",
"@typescript-eslint/parser": "^5.33.1",
"downlevel-dts": "^0.10.0",
"eslint": "^8.20.0",
"eslint": "^8.22.0",
"eslint-config-marine": "^9.4.1",
"eslint-config-prettier": "^8.5.0",
"eslint-import-resolver-typescript": "^3.4.2",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-tsdoc": "^0.2.16",
"jest": "^28.1.3",
"jest-websocket-mock": "^2.3.0",
"jest-websocket-mock": "^2.4.0",
"mock-socket": "^9.1.5",
"prettier": "^2.7.1",
"rollup-plugin-typescript2": "0.32.1",
"rollup-plugin-typescript2": "^0.33.0",
"tweetnacl": "^1.0.3",
"typescript": "^4.7.4",
"unbuild": "^0.7.6"
"unbuild": "^0.8.9"
},
"engines": {
"node": ">=16.9.0"

View File

@@ -53,7 +53,7 @@ export enum VoiceConnectionStatus {
*/
export interface VoiceConnectionSignallingState {
status: VoiceConnectionStatus.Signalling;
subscription?: PlayerSubscription;
subscription?: PlayerSubscription | undefined;
adapter: DiscordGatewayAdapterImplementerMethods;
}
@@ -88,7 +88,7 @@ export enum VoiceConnectionDisconnectReason {
*/
export interface VoiceConnectionDisconnectedBaseState {
status: VoiceConnectionStatus.Disconnected;
subscription?: PlayerSubscription;
subscription?: PlayerSubscription | undefined;
adapter: DiscordGatewayAdapterImplementerMethods;
}
@@ -128,7 +128,7 @@ export type VoiceConnectionDisconnectedState =
export interface VoiceConnectionConnectingState {
status: VoiceConnectionStatus.Connecting;
networking: Networking;
subscription?: PlayerSubscription;
subscription?: PlayerSubscription | undefined;
adapter: DiscordGatewayAdapterImplementerMethods;
}
@@ -139,7 +139,7 @@ export interface VoiceConnectionConnectingState {
export interface VoiceConnectionReadyState {
status: VoiceConnectionStatus.Ready;
networking: Networking;
subscription?: PlayerSubscription;
subscription?: PlayerSubscription | undefined;
adapter: DiscordGatewayAdapterImplementerMethods;
}
@@ -165,22 +165,22 @@ export type VoiceConnectionState =
export interface VoiceConnection extends EventEmitter {
/**
* Emitted when there is an error emitted from the voice connection
* @event
* @eventProperty
*/
on(event: 'error', listener: (error: Error) => void): this;
/**
* Emitted debugging information about the voice connection
* @event
* @eventProperty
*/
on(event: 'debug', listener: (message: string) => void): this;
/**
* Emitted when the state of the voice connection changes
* @event
* @eventProperty
*/
on(event: 'stateChange', listener: (oldState: VoiceConnectionState, newState: VoiceConnectionState) => void): this;
/**
* Emitted when the state of the voice connection changes to a specific status
* @event
* @eventProperty
*/
on<T extends VoiceConnectionStatus>(
event: T,
@@ -688,7 +688,7 @@ export class VoiceConnection extends EventEmitter {
*
* @param subscription - The removed subscription
*/
private onSubscriptionRemoved(subscription: PlayerSubscription) {
protected onSubscriptionRemoved(subscription: PlayerSubscription) {
if (this.state.status !== VoiceConnectionStatus.Destroyed && this.state.subscription === subscription) {
this.state = {
...this.state,

View File

@@ -154,27 +154,27 @@ export type AudioPlayerState =
export interface AudioPlayer extends EventEmitter {
/**
* Emitted when there is an error emitted from the audio resource played by the audio player
* @event
* @eventProperty
*/
on(event: 'error', listener: (error: AudioPlayerError) => void): this;
/**
* Emitted debugging information about the audio player
* @event
* @eventProperty
*/
on(event: 'debug', listener: (message: string) => void): this;
/**
* Emitted when the state of the audio player changes
* @event
* @eventProperty
*/
on(event: 'stateChange', listener: (oldState: AudioPlayerState, newState: AudioPlayerState) => void): this;
/**
* Emitted when the audio player is subscribed to a voice connection
* @event
* @eventProperty
*/
on(event: 'subscribe' | 'unsubscribe', listener: (subscription: PlayerSubscription) => void): this;
/**
* Emitted when the status of state changes to a specific status
* @event
* @eventProperty
*/
on<T extends AudioPlayerStatus>(
event: T,

View File

@@ -13,6 +13,6 @@ export class AudioPlayerError extends Error {
super(error.message);
this.resource = resource;
this.name = error.name;
this.stack = error.stack;
this.stack = error.stack!;
}
}

View File

@@ -7,7 +7,7 @@ import { noop } from '../util/util';
/**
* Options that are set when creating a new audio resource.
*
* @template T - the type for the metadata (if any) of the audio resource
* @typeParam T - the type for the metadata (if any) of the audio resource
*/
export interface CreateAudioResourceOptions<T> {
/**
@@ -38,7 +38,7 @@ export interface CreateAudioResourceOptions<T> {
/**
* Represents an audio resource that can be played by an audio player.
*
* @template T - the type for the metadata (if any) of the audio resource
* @typeParam T - the type for the metadata (if any) of the audio resource
*/
export class AudioResource<T = unknown> {
/**
@@ -73,7 +73,7 @@ export class AudioResource<T = unknown> {
/**
* The audio player that the resource is subscribed to, if any.
*/
public audioPlayer?: AudioPlayer;
public audioPlayer?: AudioPlayer | undefined;
/**
* The playback duration of this audio resource, given in milliseconds.
@@ -204,7 +204,7 @@ export function inferStreamType(stream: Readable): {
* @param input - The resource to play
* @param options - Configurable options for creating the resource
*
* @template T - the type for the metadata (if any) of the audio resource
* @typeParam T - the type for the metadata (if any) of the audio resource
*/
export function createAudioResource<T>(
input: string | Readable,
@@ -228,7 +228,7 @@ export function createAudioResource<T>(
* @param input - The resource to play
* @param options - Configurable options for creating the resource
*
* @template T - the type for the metadata (if any) of the audio resource
* @typeParam T - the type for the metadata (if any) of the audio resource
*/
export function createAudioResource<T extends null | undefined>(
input: string | Readable,
@@ -248,7 +248,7 @@ export function createAudioResource<T extends null | undefined>(
* @param input - The resource to play
* @param options - Configurable options for creating the resource
*
* @template T - the type for the metadata (if any) of the audio resource
* @typeParam T - the type for the metadata (if any) of the audio resource
*/
export function createAudioResource<T>(
input: string | Readable,

View File

@@ -10,7 +10,7 @@ export interface CreateVoiceConnectionOptions {
* If true, debug messages will be enabled for the voice connection and its
* related components. Defaults to false.
*/
debug?: boolean;
debug?: boolean | undefined;
adapterCreator: DiscordGatewayAdapterCreator;
}

View File

@@ -81,7 +81,7 @@ export interface NetworkingReadyState {
udp: VoiceUDPSocket;
connectionOptions: ConnectionOptions;
connectionData: ConnectionData;
preparedPacket?: Buffer;
preparedPacket?: Buffer | undefined;
}
/**
@@ -94,7 +94,7 @@ export interface NetworkingResumingState {
udp: VoiceUDPSocket;
connectionOptions: ConnectionOptions;
connectionData: ConnectionData;
preparedPacket?: Buffer;
preparedPacket?: Buffer | undefined;
}
/**
@@ -155,7 +155,7 @@ export interface Networking extends EventEmitter {
/**
* Debug event for Networking.
*
* @event
* @eventProperty
*/
on(event: 'debug', listener: (message: string) => void): this;
on(event: 'error', listener: (error: Error) => void): this;

View File

@@ -10,13 +10,13 @@ export interface VoiceWebSocket extends EventEmitter {
/**
* Debug event for VoiceWebSocket.
*
* @event
* @eventProperty
*/
on(event: 'debug', listener: (message: string) => void): this;
/**
* Packet event.
*
* @event
* @eventProperty
*/
on(event: 'packet', listener: (packet: any) => void): this;
}

View File

@@ -4,13 +4,13 @@ import { EventEmitter } from 'node:events';
export interface SpeakingMap extends EventEmitter {
/**
* Emitted when a user starts speaking.
* @event
* @eventProperty
*/
on(event: 'start', listener: (userId: string) => void): this;
/**
* Emitted when a user ends speaking.
* @event
* @eventProperty
*/
on(event: 'end', listener: (userId: string) => void): this;
}

View File

@@ -1,7 +1,4 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"exactOptionalPropertyTypes": false
},
"include": ["src/**/*.ts"]
}

View File

@@ -0,0 +1 @@
NEXT_PUBLIC_LOCAL_DEV=true

View File

@@ -5,15 +5,16 @@
"private": true,
"scripts": {
"test": "vitest run",
"build": "yarn build:css && yarn build:next",
"build:local": "yarn run --top-level docs --force && yarn build:prod",
"build:prod": "yarn build:css && yarn build:next",
"build:next": "next build",
"build:css": "yarn generate:css",
"dev": "concurrently 'yarn dev:css' 'yarn dev:next'",
"dev": "yarn run --top-level docs && concurrently 'yarn dev:css' 'yarn dev:next'",
"dev:next": "next dev",
"dev:css": "yarn generate:css --watch",
"generate:css": "unocss 'src/**/*.tsx' --out-file ./src/styles/unocss.css",
"lint": "prettier --check . && eslint src --ext mjs,js,ts,tsx",
"format": "prettier --write . && eslint src --ext mjs,js,ts,tsx --fix"
"lint": "prettier --check . && TIMING=1 eslint src --ext mjs,js,ts,tsx",
"format": "prettier --write . && TIMING=1 eslint src --ext mjs,js,ts,tsx --fix"
},
"main": "./dist/index.js",
"module": "./dist/index.mjs",
@@ -47,12 +48,18 @@
},
"homepage": "https://discord.js.org",
"dependencies": {
"@microsoft/api-extractor-model": "^7.22.1",
"@emotion/react": "^11.10.0",
"@emotion/server": "^11.10.0",
"@mantine/core": "^5.2.0",
"@mantine/hooks": "^5.2.0",
"@mantine/next": "^5.2.0",
"@mantine/nprogress": "^5.2.0",
"@mantine/spotlight": "^5.2.0",
"@microsoft/api-extractor-model": "^7.23.1",
"@microsoft/tsdoc": "0.14.1",
"@microsoft/tsdoc-config": "0.16.1",
"@vscode/codicons": "^0.0.31",
"framer-motion": "^6.5.1",
"next": "^12.2.3",
"@vscode/codicons": "^0.0.32",
"next": "^12.2.5",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-icons": "^4.4.0",
@@ -60,37 +67,32 @@
"sharp": "^0.30.7"
},
"devDependencies": {
"@testing-library/cypress": "^8.0.3",
"@testing-library/dom": "^8.16.0",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^14.3.0",
"@types/node": "^16.11.46",
"@testing-library/user-event": "^14.4.3",
"@types/node": "^16.11.52",
"@types/react-dom": "^18.0.6",
"@types/react-syntax-highlighter": "^15.5.4",
"@typescript-eslint/eslint-plugin": "^5.31.0",
"@typescript-eslint/parser": "^5.31.0",
"@unocss/cli": "^0.44.7",
"@unocss/preset-web-fonts": "^0.44.7",
"@unocss/reset": "^0.44.7",
"@vitejs/plugin-react": "^2.0.0",
"c8": "^7.12.0",
"@typescript-eslint/eslint-plugin": "^5.33.1",
"@typescript-eslint/parser": "^5.33.1",
"@unocss/cli": "^0.45.9",
"@unocss/preset-web-fonts": "^0.45.9",
"@unocss/reset": "^0.45.9",
"@vitejs/plugin-react": "^2.0.1",
"@vitest/coverage-c8": "^0.22.1",
"concurrently": "^7.3.0",
"cypress": "^10.3.1",
"eslint": "^8.20.0",
"eslint": "^8.22.0",
"eslint-config-marine": "^9.4.1",
"eslint-config-prettier": "^8.5.0",
"eslint-import-resolver-typescript": "^3.3.0",
"eslint-import-resolver-typescript": "^3.4.2",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-react": "^7.30.1",
"eslint-plugin-react-hooks": "^4.6.0",
"happy-dom": "^6.0.4",
"msw": "^0.44.2",
"prettier": "^2.7.1",
"typescript": "^4.7.4",
"unocss": "^0.44.7",
"vercel": "^27.3.1",
"vitest": "^0.19.1"
"unocss": "^0.45.9",
"vercel": "^28.1.0",
"vitest": "^0.22.1"
},
"engines": {
"node": ">=16.9.0"

View File

@@ -0,0 +1,381 @@
import {
ApiModel,
ApiDeclaredItem,
ApiPropertyItem,
ApiMethod,
ApiParameterListMixin,
ApiTypeParameterListMixin,
ApiClass,
ApiFunction,
ApiItemKind,
ApiTypeAlias,
ApiEnum,
ApiInterface,
ApiMethodSignature,
ApiPropertySignature,
ApiVariable,
ApiItem,
ApiConstructor,
ApiItemContainerMixin,
} from '@microsoft/api-extractor-model';
import { generateTypeParamData } from './TypeParameterMixin';
import { Visibility } from './Visibility';
import { createCommentNode } from './comment';
import type { DocBlockJSON } from './comment/CommentBlock';
import type { AnyDocNodeJSON } from './comment/CommentNode';
import { DocNodeContainerJSON, nodeContainer } from './comment/CommentNodeContainer';
import {
generatePath,
genParameter,
genReference,
genToken,
resolveName,
TokenDocumentation,
} from '~/util/parse.server';
export interface ReferenceData {
name: string;
path: string;
}
export interface InheritanceData {
parentName: string;
path: string;
parentKey: string;
}
export interface ApiInheritableJSON {
inheritanceData: InheritanceData | null;
}
export interface ApiItemJSON {
kind: string;
name: string;
referenceData: ReferenceData;
excerpt: string;
excerptTokens: TokenDocumentation[];
remarks: DocNodeContainerJSON | null;
summary: DocNodeContainerJSON | null;
deprecated: DocNodeContainerJSON | null;
comment: AnyDocNodeJSON | null;
containerKey: string;
path: string[];
}
export interface ApiPropertyItemJSON extends ApiItemJSON, ApiInheritableJSON {
propertyTypeTokens: TokenDocumentation[];
readonly: boolean;
optional: boolean;
}
export interface ApiTypeParameterListJSON {
typeParameters: ApiTypeParameterJSON[];
}
export interface ApiTypeParameterJSON {
name: string;
constraintTokens: TokenDocumentation[];
defaultTokens: TokenDocumentation[];
optional: boolean;
commentBlock: DocBlockJSON | null;
}
export interface ApiParameterListJSON {
parameters: ApiParameterJSON[];
}
export interface ApiMethodSignatureJSON
extends ApiItemJSON,
ApiTypeParameterListJSON,
ApiParameterListJSON,
ApiInheritableJSON {
returnTypeTokens: TokenDocumentation[];
optional: boolean;
overloadIndex: number;
}
export interface ApiMethodJSON extends ApiMethodSignatureJSON {
static: boolean;
visibility: Visibility;
}
export interface ApiParameterJSON {
name: string;
isOptional: boolean;
tokens: TokenDocumentation[];
paramCommentBlock: DocBlockJSON | null;
}
export interface ApiClassJSON extends ApiItemJSON, ApiTypeParameterListJSON {
constructor: ApiConstructorJSON | null;
properties: ApiPropertyItemJSON[];
methods: ApiMethodJSON[];
extendsTokens: TokenDocumentation[];
implementsTokens: TokenDocumentation[][];
}
export interface ApiTypeAliasJSON extends ApiItemJSON, ApiTypeParameterListJSON {
typeTokens: TokenDocumentation[];
}
export interface EnumMemberData {
name: string;
initializerTokens: TokenDocumentation[];
summary: DocNodeContainerJSON | null;
}
export interface ApiEnumJSON extends ApiItemJSON {
members: EnumMemberData[];
}
export interface ApiInterfaceJSON extends ApiItemJSON, ApiTypeParameterListJSON {
properties: ApiPropertyItemJSON[];
methods: ApiMethodSignatureJSON[];
extendsTokens: TokenDocumentation[][] | null;
}
export interface ApiVariableJSON extends ApiItemJSON {
typeTokens: TokenDocumentation[];
readonly: boolean;
}
export interface ApiFunctionJSON extends ApiItemJSON, ApiTypeParameterListJSON, ApiParameterListJSON {
returnTypeTokens: TokenDocumentation[];
overloadIndex: number;
}
export interface ApiConstructorJSON extends ApiItemJSON, ApiParameterListJSON {
protected: boolean;
}
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export class ApiNodeJSONEncoder {
public static encode(model: ApiModel, node: ApiItem) {
if (!(node instanceof ApiDeclaredItem)) {
throw new Error(`Cannot serialize node of type ${node.kind}`);
}
switch (node.kind) {
case ApiItemKind.Class:
return this.encodeClass(model, node as ApiClass);
case ApiItemKind.Function:
return this.encodeFunction(model, node as ApiFunction);
case ApiItemKind.Interface:
return this.encodeInterface(model, node as ApiInterface);
case ApiItemKind.TypeAlias:
return this.encodeTypeAlias(model, node as ApiTypeAlias);
case ApiItemKind.Enum:
return this.encodeEnum(model, node as ApiEnum);
case ApiItemKind.Variable:
return this.encodeVariable(model, node as ApiVariable);
default:
throw new Error(`Unknown API item kind: ${node.kind}`);
}
}
public static encodeItem(model: ApiModel, item: ApiDeclaredItem): ApiItemJSON {
const path = [];
for (const _item of item.getHierarchy()) {
switch (_item.kind) {
case 'None':
case 'EntryPoint':
case 'Model':
break;
default:
path.push(resolveName(_item));
}
}
return {
kind: item.kind,
name: resolveName(item),
referenceData: genReference(item),
excerpt: item.excerpt.text,
excerptTokens: item.excerpt.spannedTokens.map((token) => genToken(model, token)),
remarks: item.tsdocComment?.remarksBlock
? (createCommentNode(item.tsdocComment.remarksBlock, model, item.parent) as DocNodeContainerJSON)
: null,
summary: item.tsdocComment?.summarySection
? (createCommentNode(item.tsdocComment.summarySection, model, item.parent) as DocNodeContainerJSON)
: null,
deprecated: item.tsdocComment?.deprecatedBlock
? (createCommentNode(item.tsdocComment.deprecatedBlock, model, item.parent) as DocNodeContainerJSON)
: null,
path,
containerKey: item.containerKey,
comment: item.tsdocComment ? createCommentNode(item.tsdocComment, model, item.parent) : null,
};
}
public static encodeParameterList(
model: ApiModel,
item: ApiParameterListMixin & ApiDeclaredItem,
): { parameters: ApiParameterJSON[] } {
return {
parameters: item.parameters.map((param) => genParameter(model, param)),
};
}
public static encodeTypeParameterList(model: ApiModel, item: ApiTypeParameterListMixin & ApiDeclaredItem) {
return {
typeParameters: item.typeParameters.map((param) => generateTypeParamData(model, param, item.parent)),
};
}
public static encodeProperty(
model: ApiModel,
item: ApiPropertyItem,
parent: ApiItemContainerMixin,
): ApiPropertyItemJSON {
return {
...this.encodeItem(model, item),
...this.encodeInheritanceData(item, parent),
propertyTypeTokens: item.propertyTypeExcerpt.spannedTokens.map((token) => genToken(model, token)),
readonly: item.isReadonly,
optional: item.isOptional,
};
}
public static encodeInheritanceData(item: ApiDeclaredItem, parent: ApiItemContainerMixin): ApiInheritableJSON {
return {
inheritanceData:
item.parent && item.parent.containerKey !== parent.containerKey
? {
parentKey: item.parent.containerKey,
parentName: item.parent.displayName,
path: generatePath(item.parent.getHierarchy()),
}
: null,
};
}
public static encodeFunction(model: ApiModel, item: ApiFunction) {
return {
...this.encodeItem(model, item),
...this.encodeParameterList(model, item),
...this.encodeTypeParameterList(model, item),
returnTypeTokens: item.returnTypeExcerpt.spannedTokens.map((token) => genToken(model, token)),
overloadIndex: item.overloadIndex,
};
}
public static encodeMethodSignature(
model: ApiModel,
item: ApiMethodSignature,
parent: ApiItemContainerMixin,
): ApiMethodSignatureJSON {
return {
...this.encodeFunction(model, item),
...this.encodeInheritanceData(item, parent),
optional: item.isOptional,
};
}
public static encodeMethod(model: ApiModel, item: ApiMethod, parent: ApiItemContainerMixin): ApiMethodJSON {
return {
...this.encodeMethodSignature(model, item, parent),
static: item.isStatic,
visibility: item.isProtected ? Visibility.Protected : Visibility.Public,
};
}
public static encodeClass(model: ApiModel, item: ApiClass): ApiClassJSON {
const extendsExcerpt = item.extendsType?.excerpt;
const methods: ApiMethodJSON[] = [];
const properties: ApiPropertyItemJSON[] = [];
let constructor: ApiConstructor | undefined;
for (const member of item.findMembersWithInheritance().items) {
switch (member.kind) {
case ApiItemKind.Method:
methods.push(this.encodeMethod(model, member as ApiMethod, item));
break;
case ApiItemKind.Property:
properties.push(this.encodeProperty(model, member as ApiPropertyItem, item));
break;
case ApiItemKind.Constructor:
constructor = member as ApiConstructor;
break;
default:
break;
}
}
return {
...this.encodeItem(model, item),
...this.encodeTypeParameterList(model, item),
constructor: constructor ? this.encodeConstructor(model, constructor) : null,
extendsTokens: extendsExcerpt ? extendsExcerpt.spannedTokens.map((token) => genToken(model, token)) : [],
implementsTokens: item.implementsTypes.map((excerpt) =>
excerpt.excerpt.spannedTokens.map((token) => genToken(model, token)),
),
methods,
properties,
};
}
public static encodeTypeAlias(model: ApiModel, item: ApiTypeAlias): ApiTypeAliasJSON {
return {
...this.encodeItem(model, item),
...this.encodeTypeParameterList(model, item),
typeTokens: item.typeExcerpt.spannedTokens.map((token) => genToken(model, token)),
};
}
public static encodeEnum(model: ApiModel, item: ApiEnum): ApiEnumJSON {
return {
...this.encodeItem(model, item),
members: item.members.map((member) => ({
name: member.name,
initializerTokens: member.initializerExcerpt?.spannedTokens.map((token) => genToken(model, token)) ?? [],
summary: member.tsdocComment ? nodeContainer(member.tsdocComment.summarySection, model, member) : null,
})),
};
}
public static encodeInterface(model: ApiModel, item: ApiInterface): ApiInterfaceJSON {
const methods: ApiMethodSignatureJSON[] = [];
const properties: ApiPropertyItemJSON[] = [];
for (const member of item.findMembersWithInheritance().items) {
switch (member.kind) {
case ApiItemKind.MethodSignature:
methods.push(this.encodeMethodSignature(model, member as ApiMethodSignature, item));
break;
case ApiItemKind.PropertySignature:
properties.push(this.encodeProperty(model, member as ApiPropertySignature, item));
break;
default:
break;
}
}
return {
...this.encodeItem(model, item),
...this.encodeTypeParameterList(model, item),
extendsTokens: item.extendsTypes.map((excerpt) =>
excerpt.excerpt.spannedTokens.map((token) => genToken(model, token)),
),
methods,
properties,
};
}
public static encodeVariable(model: ApiModel, item: ApiVariable): ApiVariableJSON {
return {
...this.encodeItem(model, item),
typeTokens: item.variableTypeExcerpt.spannedTokens.map((token) => genToken(model, token)),
readonly: item.isReadonly,
};
}
public static encodeConstructor(model: ApiModel, item: ApiConstructor): ApiConstructorJSON {
return {
...this.encodeItem(model, item),
...this.encodeParameterList(model, item),
protected: item.isProtected,
};
}
}

View File

@@ -1,55 +0,0 @@
import {
type ApiClass,
type ApiModel,
ApiItemKind,
type ApiMethod,
type ApiPropertyItem,
} from '@microsoft/api-extractor-model';
import { DocItem } from './DocItem';
import { DocMethod } from './DocMethod';
import { DocProperty } from './DocProperty';
import { TypeParameterMixin } from './TypeParameterMixin';
import { type TokenDocumentation, genToken } from '~/util/parse.server';
export class DocClass extends TypeParameterMixin(DocItem<ApiClass>) {
public readonly extendsTokens: TokenDocumentation[] | null;
public readonly implementsTokens: TokenDocumentation[][];
public readonly methods: DocMethod[] = [];
public readonly properties: DocProperty[] = [];
public constructor(model: ApiModel, item: ApiClass) {
super(model, item);
const extendsExcerpt = item.extendsType?.excerpt;
this.extendsTokens = extendsExcerpt
? extendsExcerpt.spannedTokens.map((token) => genToken(this.model, token))
: null;
this.implementsTokens = item.implementsTypes.map((excerpt) =>
excerpt.excerpt.spannedTokens.map((token) => genToken(this.model, token)),
);
for (const member of item.members) {
switch (member.kind) {
case ApiItemKind.Method:
this.methods.push(new DocMethod(this.model, member as ApiMethod));
break;
case ApiItemKind.Property:
this.properties.push(new DocProperty(this.model, member as ApiPropertyItem));
break;
default:
break;
}
}
}
public override toJSON() {
return {
...super.toJSON(),
extendsTokens: this.extendsTokens,
implementsTokens: this.implementsTokens,
methods: this.methods.map((method) => method.toJSON()),
properties: this.properties.map((prop) => prop.toJSON()),
};
}
}

View File

@@ -1,33 +0,0 @@
import type { ApiEnum, ApiModel } from '@microsoft/api-extractor-model';
import { DocItem } from './DocItem';
import { CommentNodeContainer } from './comment/CommentNodeContainer';
import { genToken, TokenDocumentation } from '~/util/parse.server';
export interface EnumMemberData {
name: string;
initializerTokens: TokenDocumentation[];
summary: ReturnType<DocItem['toJSON']>['summary'];
}
export class DocEnum extends DocItem<ApiEnum> {
public readonly members: EnumMemberData[] = [];
public constructor(model: ApiModel, item: ApiEnum) {
super(model, item);
this.members = item.members.map((member) => ({
name: member.name,
initializerTokens: member.initializerExcerpt?.spannedTokens.map((token) => genToken(this.model, token)) ?? [],
summary: member.tsdocComment
? new CommentNodeContainer(member.tsdocComment.summarySection, model, member).toJSON()
: null,
}));
}
public override toJSON() {
return {
...super.toJSON(),
members: this.members,
};
}
}

View File

@@ -1,26 +0,0 @@
import type { ApiFunction, ApiModel, ApiParameterListMixin } from '@microsoft/api-extractor-model';
import { DocItem } from './DocItem';
import { TypeParameterMixin } from './TypeParameterMixin';
import { type TokenDocumentation, genToken, genParameter, ParameterDocumentation } from '~/util/parse.server';
export class DocFunction extends TypeParameterMixin(DocItem<ApiFunction>) {
public readonly returnTypeTokens: TokenDocumentation[];
public readonly overloadIndex: number;
public readonly parameters: ParameterDocumentation[];
public constructor(model: ApiModel, item: ApiFunction) {
super(model, item);
this.returnTypeTokens = item.returnTypeExcerpt.spannedTokens.map((token) => genToken(this.model, token));
this.overloadIndex = item.overloadIndex;
this.parameters = (item as ApiParameterListMixin).parameters.map((param) => genParameter(this.model, param));
}
public override toJSON() {
return {
...super.toJSON(),
parameters: this.parameters,
returnTypeTokens: this.returnTypeTokens,
overloadIndex: this.overloadIndex,
};
}
}

View File

@@ -1,48 +0,0 @@
import { DocItem } from './DocItem';
import { DocMethodSignature } from './DocMethodSignature';
import { DocProperty } from './DocProperty';
import { TypeParameterMixin } from './TypeParameterMixin';
import {
ApiInterface,
ApiItemKind,
ApiMethodSignature,
ApiModel,
ApiPropertySignature,
} from '~/util/api-extractor.server';
import { type TokenDocumentation, genToken } from '~/util/parse.server';
export class DocInterface extends TypeParameterMixin(DocItem<ApiInterface>) {
public readonly extendsTokens: TokenDocumentation[][] | null;
public readonly methods: DocMethodSignature[] = [];
public readonly properties: DocProperty[] = [];
public constructor(model: ApiModel, item: ApiInterface) {
super(model, item);
this.extendsTokens = item.extendsTypes.map((excerpt) =>
excerpt.excerpt.spannedTokens.map((token) => genToken(this.model, token)),
);
for (const member of item.members) {
switch (member.kind) {
case ApiItemKind.MethodSignature:
this.methods.push(new DocMethodSignature(this.model, member as ApiMethodSignature));
break;
case ApiItemKind.PropertySignature:
this.properties.push(new DocProperty(this.model, member as ApiPropertySignature));
break;
default:
break;
}
}
}
public override toJSON() {
return {
...super.toJSON(),
extendsTokens: this.extendsTokens,
methods: this.methods.map((method) => method.toJSON()),
properties: this.properties.map((prop) => prop.toJSON()),
};
}
}

View File

@@ -1,46 +0,0 @@
import type { ApiModel, ApiDeclaredItem } from '@microsoft/api-extractor-model';
import { CommentNodeContainer } from './comment/CommentNodeContainer';
import type { ReferenceData } from '~/util/model.server';
import { resolveName, genReference, TokenDocumentation, genToken } from '~/util/parse.server';
export type DocItemConstructor<T = DocItem> = new (...args: any[]) => T;
export class DocItem<T extends ApiDeclaredItem = ApiDeclaredItem> {
public readonly item: T;
public readonly name: string;
public readonly referenceData: ReferenceData;
public readonly model: ApiModel;
public readonly excerpt: string;
public readonly excerptTokens: TokenDocumentation[] = [];
public readonly kind: string;
public readonly remarks: CommentNodeContainer | null;
public readonly summary: CommentNodeContainer | null;
public constructor(model: ApiModel, item: T) {
this.item = item;
this.kind = item.kind;
this.model = model;
this.name = resolveName(item);
this.referenceData = genReference(item);
this.excerpt = item.excerpt.text;
this.excerptTokens = item.excerpt.spannedTokens.map((token) => genToken(model, token));
this.remarks = item.tsdocComment?.remarksBlock
? new CommentNodeContainer(item.tsdocComment.remarksBlock.content, model, item.parent)
: null;
this.summary = item.tsdocComment?.summarySection
? new CommentNodeContainer(item.tsdocComment.summarySection, model, item.parent)
: null;
}
public toJSON() {
return {
name: this.name,
referenceData: this.referenceData,
summary: this.summary?.toJSON() ?? null,
excerpt: this.excerpt,
excerptTokens: this.excerptTokens,
kind: this.kind,
remarks: this.remarks?.toJSON() ?? null,
};
}
}

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