feat: docgen package (#8029)

This commit is contained in:
Noel
2022-06-07 10:51:33 +02:00
committed by GitHub
parent 5475767c2c
commit 8b979c0245
71 changed files with 1411 additions and 756 deletions

4
.github/labeler.yml vendored
View File

@@ -14,6 +14,10 @@ chore:
- packages/discord.js/* - packages/discord.js/*
- packages/discord.js/**/* - packages/discord.js/**/*
'packages:docgen':
- packages/docgen/*
- packages/docgen/**/*
'packages:proxy': 'packages:proxy':
- packages/proxy/* - packages/proxy/*
- packages/proxy/**/* - packages/proxy/**/*

2
.github/labels.yml vendored
View File

@@ -50,6 +50,8 @@
color: 'fbca04' color: 'fbca04'
- name: 'packages:discord.js' - name: 'packages:discord.js'
color: 'fbca04' color: 'fbca04'
- name: 'packages:docgen'
color: 'fbca04'
- name: 'packages:proxy' - name: 'packages:proxy'
color: 'fbca04' color: 'fbca04'
- name: 'packages:rest' - name: 'packages:rest'

8
.prettierignore Normal file
View File

@@ -0,0 +1,8 @@
**/CHANGELOG.md
**/.turbo
**/dist/
**/docs/**/*
**/!docs/index.yml
**/!docs/README.md
**/coverage/
**/LICENSE

View File

@@ -6,3 +6,4 @@ docs/**/*
!docs/index.yml !docs/index.yml
!docs/README.md !docs/README.md
coverage/ coverage/
tsup.config.*.mjs

View File

@@ -175,8 +175,7 @@
END OF TERMS AND CONDITIONS END OF TERMS AND CONDITIONS
Copyright 2021 Noel Buechler Copyright 2022 Noel Buechler
Copyright 2021 Vlad Frangu
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.

View File

@@ -6,3 +6,4 @@ docs/**/*
!docs/index.yml !docs/index.yml
!docs/README.md !docs/README.md
coverage/ coverage/
tsup.config.*.mjs

View File

@@ -6,3 +6,4 @@ docs/**/*
!docs/index.yml !docs/index.yml
!docs/README.md !docs/README.md
coverage/ coverage/
tsup.config.*.mjs

View File

@@ -175,8 +175,8 @@
END OF TERMS AND CONDITIONS END OF TERMS AND CONDITIONS
Copyright 2015 - 2021 Noel Buechler Copyright 2021 Noel Buechler
Copyright 2015 - 2021 Amish Shah Copyright 2015 Amish Shah
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.

View File

@@ -15,11 +15,13 @@ pids
.env .env
test/auth.json test/auth.json
test/auth.js test/auth.js
docs/deploy/deploy_key
docs/deploy/deploy_key.pub
deploy/deploy_key
deploy/deploy_key.pub
# Dist # Dist
dist/ dist/
docs/docs.json docs/**/*
!docs/index.json
# Miscellaneous
.tmp/
coverage/
tsconfig.tsbuildinfo

View File

@@ -6,3 +6,4 @@ docs/**/*
!docs/index.yml !docs/index.yml
!docs/README.md !docs/README.md
coverage/ coverage/
tsup.config.*.mjs

View File

@@ -175,8 +175,8 @@
END OF TERMS AND CONDITIONS END OF TERMS AND CONDITIONS
Copyright 2015 - 2021 Noel Buechler Copyright 2021 Noel Buechler
Copyright 2015 - 2021 Amish Shah Copyright 2015 Amish Shah
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.

View File

@@ -0,0 +1 @@
[{ "name": "General", "files": [{ "name": "Welcome", "id": "welcome", "path": "../../README.md" }] }]

View File

@@ -1,5 +0,0 @@
- name: General
files:
- name: Welcome
id: welcome
path: ../../README.md

View File

@@ -7,8 +7,8 @@
"test:typescript": "tsc --noEmit && tsd", "test:typescript": "tsc --noEmit && tsd",
"lint": "prettier --check . && eslint src && tslint typings/index.d.ts", "lint": "prettier --check . && eslint src && tslint typings/index.d.ts",
"format": "prettier --write . && eslint src --fix", "format": "prettier --write . && eslint src --fix",
"docs": "docgen --source ./src --custom ./docs/index.yml --root ../../ --output ./docs/docs.json", "docs": "docgen -i ./src/*.js ./src/**/*.js -c ./docs/index.json -r ../../ -o ./docs/docs.json",
"docs:test": "docgen --source ./src --custom ./docs/index.yml --root ../../", "docs:test": "docgen -i ./src/*.js ./src/**/*.js -c ./docs/index.json -r ../../",
"prepublishOnly": "yarn lint && yarn test", "prepublishOnly": "yarn lint && yarn test",
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/discord.js/*'", "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/discord.js/*'",
"release": "cliff-jumper --skip-tag --verbose" "release": "cliff-jumper --skip-tag --verbose"
@@ -61,7 +61,7 @@
"ws": "^8.7.0" "ws": "^8.7.0"
}, },
"devDependencies": { "devDependencies": {
"@discordjs/docgen": "^0.11.1", "@discordjs/docgen": "workspace:^",
"@favware/cliff-jumper": "^1.8.3", "@favware/cliff-jumper": "^1.8.3",
"@types/node": "^16.11.38", "@types/node": "^16.11.38",
"dtslint": "^4.2.1", "dtslint": "^4.2.1",

View File

@@ -0,0 +1,12 @@
{
"root": true,
"extends": "marine/prettier/node",
"parserOptions": {
"project": "./tsconfig.eslint.json",
"extraFileExtensions": [".mjs"]
},
"ignorePatterns": ["**/dist/*"],
"env": {
"jest": true
}
}

25
packages/docgen/.gitignore vendored Normal file
View File

@@ -0,0 +1,25 @@
# Packages
node_modules/
# Log files
logs/
*.log
npm-debug.log*
# Runtime data
pids
*.pid
*.seed
# Env
.env
# Dist
dist/
typings/
docs/**/*
# Miscellaneous
.tmp/
coverage/

View File

@@ -0,0 +1,9 @@
# Autogenerated
CHANGELOG.md
.turbo
dist/
docs/**/*
!docs/index.yml
!docs/README.md
coverage/
tsup.config.*.mjs

View File

@@ -0,0 +1,8 @@
{
"printWidth": 120,
"useTabs": true,
"singleQuote": true,
"quoteProps": "as-needed",
"trailingComma": "all",
"endOfLine": "lf"
}

191
packages/docgen/LICENSE Normal file
View File

@@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2022 Noel Buechler
Copyright 2015 Amish Shah
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

31
packages/docgen/README.md Normal file
View File

@@ -0,0 +1,31 @@
<div align="center">
<br />
<p>
<a href="https://discord.js.org"><img src="https://discord.js.org/static/logo.svg" width="546" alt="discord.js" /></a>
</p>
<br />
<p>
<a href="https://discord.gg/djs"><img src="https://img.shields.io/discord/222078108977594368?color=5865F2&logo=discord&logoColor=white" alt="Discord server" /></a>
<a href="https://github.com/discordjs/discord.js/actions"><img src="https://github.com/discordjs/discord.js/actions/workflows/test.yml/badge.svg" alt="Build status" /></a>
</p>
</div>
## Links
- [Website](https://discord.js.org/) ([source](https://github.com/discordjs/website))
- [Documentation](https://discord.js.org/#/docs)
- [Guide](https://discordjs.guide/) ([source](https://github.com/discordjs/guide))
See also the [Update Guide](https://discordjs.guide/additional-info/changes-in-v13.html), including updated and removed items in the library.
- [discord.js Discord server](https://discord.gg/djs)
- [Discord API Discord server](https://discord.gg/discord-api)
- [GitHub](https://github.com/discordjs/discord.js/tree/main/packages/scripts)
- [Related libraries](https://discord.com/developers/docs/topics/community-resources#libraries)
## Contributing
See [the contribution guide](https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md) if you'd like to submit a PR.
## Help
If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle
nudge in the right direction, please don't hesitate to join our official [discord.js Server](https://discord.gg/djs).

View File

@@ -0,0 +1,74 @@
{
"name": "@discordjs/docgen",
"version": "0.12.0-dev",
"description": "The docs.json generator for discord.js and its related projects",
"scripts": {
"build": "tsup",
"lint": "prettier --check . && eslint src --ext mjs,js,ts",
"format": "prettier --write . && eslint src --ext mjs,js,ts --fix",
"prepublishOnly": "yarn build && yarn lint && yarn test",
"changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/docgen/*'",
"release": "cliff-jumper"
},
"bin": "./dist/index.js",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
"import": "./dist/index.mjs",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"directories": {
"lib": "src"
},
"files": [
"dist"
],
"contributors": [
"Crawl <icrawltogo@gmail.com>",
"Amish Shah <amishshah.2k@gmail.com>",
"Schuyler Cebulskie <Gawdl3y@Gawdl3y.com>"
],
"license": "Apache-2.0",
"keywords": [
"documentation",
"docs",
"generator",
"docgen",
"docsgen",
"node",
"discordjs"
],
"repository": {
"type": "git",
"url": "https://github.com/discordjs/discord.js.git"
},
"bugs": {
"url": "https://github.com/discordjs/discord.js/issues"
},
"homepage": "https://discord.js.org",
"dependencies": {
"@discordjs/collection": "workspace:^",
"commander": "^9.3.0",
"jsdoc-to-markdown": "^7.1.1",
"tslib": "^2.4.0"
},
"devDependencies": {
"@favware/cliff-jumper": "^1.8.3",
"@types/jsdoc-to-markdown": "^7.0.3",
"@types/node": "^16.11.38",
"@typescript-eslint/eslint-plugin": "^5.27.1",
"@typescript-eslint/parser": "^5.27.1",
"eslint": "^8.17.0",
"eslint-config-marine": "^9.4.1",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-import": "^2.26.0",
"prettier": "^2.6.2",
"tsup": "^6.1.0",
"typescript": "^4.7.3"
},
"engines": {
"node": ">=16.9.0"
}
}

View File

@@ -0,0 +1,143 @@
import { join } from 'path';
import { Collection } from '@discordjs/collection';
import type { ChildTypes, Class, Config, CustomDocs, RootTypes } from './interfaces/index.js';
import { DocumentedClass } from './types/class.js';
import { DocumentedConstructor } from './types/constructor.js';
import { DocumentedEvent } from './types/event.js';
import { DocumentedExternal } from './types/external.js';
import { DocumentedInterface } from './types/interface.js';
import { DocumentedMember } from './types/member.js';
import { DocumentedMethod } from './types/method.js';
import { DocumentedTypeDef } from './types/typedef.js';
import packageFile from '../package.json';
export class Documentation {
public readonly classes = new Collection<string, DocumentedClass>();
public readonly functions = new Collection<string, DocumentedMethod>();
public readonly interfaces = new Collection<string, DocumentedInterface>();
public readonly typedefs = new Collection<string, DocumentedTypeDef>();
public readonly externals = new Collection<string, DocumentedExternal>();
public constructor(
data: RootTypes[],
private readonly config: Config,
private readonly custom?: Record<string, CustomDocs>,
) {
let items = data;
for (const item of items) {
switch (item.kind) {
case 'class': {
this.classes.set(item.name, new DocumentedClass(item, config));
items = items.filter((i) => i.longname !== item.longname);
break;
}
case 'function': {
if (item.scope === 'global' || !item.memberof) {
this.functions.set(item.name, new DocumentedMethod(item, config));
items = items.filter((i) => i.longname !== item.longname);
}
break;
}
case 'interface': {
this.interfaces.set(item.name, new DocumentedInterface(item as unknown as Class, config));
items = items.filter((i) => i.longname !== item.longname);
break;
}
case 'typedef': {
this.typedefs.set(item.name, new DocumentedTypeDef(item, config));
items = items.filter((i) => i.longname !== item.longname);
break;
}
case 'external': {
this.externals.set(item.name, new DocumentedExternal(item, config));
items = items.filter((i) => i.longname !== item.longname);
break;
}
default:
break;
}
}
this.parse(items as ChildTypes[]);
}
public parse(items: ChildTypes[]) {
for (const member of items) {
let item: DocumentedMethod | DocumentedConstructor | DocumentedMember | DocumentedEvent | null = null;
switch (member.kind) {
case 'constructor': {
item = new DocumentedConstructor(member, this.config);
break;
}
case 'function': {
item = new DocumentedMethod(member, this.config);
break;
}
case 'member': {
item = new DocumentedMember(member, this.config);
break;
}
case 'event': {
item = new DocumentedEvent(member, this.config);
break;
}
default: {
// @ts-expect-error
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
console.warn(`- Unknown documentation kind "${member.kind}" - \n${JSON.stringify(member)}\n`);
}
}
const parent = this.classes.get(member.memberof ?? '') ?? this.interfaces.get(member.memberof ?? '');
if (parent) {
if (item) {
parent.add(item);
} else {
console.warn(
`- Documentation item could not be constructed for "${member.name}" - \n${JSON.stringify(member)}\n`,
);
}
continue;
}
const info = [];
const name = (member.name || item?.data.name) ?? 'UNKNOWN';
const memberof = member.memberof ?? item?.data.memberof;
const meta =
member.kind === 'constructor'
? null
: { file: member.meta.filename, line: member.meta.lineno, path: member.meta.path };
if (memberof) info.push(`member of "${memberof}"`);
if (meta) info.push(`${join(meta.path, meta.file)}${meta.line ? `:${meta.line}` : ''}`);
console.warn(`- "${name}"${info.length ? ` (${info.join(', ')})` : ''} has no accessible parent.`);
if (!name && !info.length) console.warn('Raw object:', member);
}
}
public serialize() {
return {
meta: {
generator: packageFile.version,
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()),
custom: this.custom,
};
}
public static get FORMAT_VERSION() {
return 30;
}
}

View File

@@ -0,0 +1,88 @@
#!/usr/bin/env node
import { readFileSync, writeFileSync } from 'fs';
import { join, basename, extname, dirname, relative } from 'path';
import { createCommand } from 'commander';
import jsdoc2md from 'jsdoc-to-markdown';
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;
}
interface CustomFiles {
id?: string;
name: string;
path?: string;
files: {
id?: string;
name: string;
path: string;
}[];
}
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');
const program = command.parse(process.argv);
const options = program.opts<CLIOptions>();
console.log('Parsing JSDocs in source files...');
const 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, '/'),
};
}
}
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, options, custom);
if (options.output) {
console.log(`Writing to ${options.output}...`);
writeFileSync(options.output, JSON.stringify(docs.serialize()));
}
console.log('Done!');

View File

@@ -0,0 +1 @@
export type Access = 'public' | 'private' | 'protected';

View File

@@ -0,0 +1,3 @@
import type { Constructor, Event, Member, Method } from './index.js';
export type ChildTypes = Constructor | Member | Method | Event;

View File

@@ -0,0 +1,13 @@
import type { Access, Item, Meta, Scope } from './index.js';
export interface Class extends Item {
kind: 'class';
scope: Scope;
implements?: string[];
augments?: string[];
see?: string[];
access?: Access;
virtual?: boolean;
deprecated?: boolean | string;
meta: Meta;
}

View File

@@ -0,0 +1,3 @@
export interface Config {
root: string;
}

View File

@@ -0,0 +1,9 @@
import type { Access, Item, Param } from './index.js';
export interface Constructor extends Item {
kind: 'constructor';
memberof: string;
see?: string[];
access?: Access;
params?: Param[];
}

View File

@@ -0,0 +1,12 @@
export interface CustomDocs {
name?: string;
files: Record<
string,
{
name?: string;
type?: string;
content?: string;
path?: string;
}
>;
}

View File

@@ -0,0 +1,11 @@
import type { Item, Meta, Param, Scope } from './index.js';
export interface Event extends Item {
kind: 'event';
scope: Scope;
memberof: string;
see?: string[];
deprecated?: boolean | string;
params?: Param[];
meta: Meta;
}

View File

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

View File

@@ -0,0 +1,7 @@
import type { Item, Meta } from './index.js';
export interface External extends Item {
kind: 'external';
see?: string[];
meta: Meta;
}

View File

@@ -0,0 +1,21 @@
export * from './access.type.js';
export * from './childTypes.type';
export * from './class.interface.js';
export * from './config.interface.js';
export * from './constructor.interface.js';
export * from './customDocs.interface.js';
export * from './event.interface.js';
export * from './exception.interface.js';
export * from './external.interface.js';
export * from './interface.interface.js';
export * from './item.interface.js';
export * from './member.interface.js';
export * from './meta.interface.js';
export * from './method.interface.js';
export * from './param.interface.js';
export * from './return.interface.js';
export * from './rootTypes.type.js';
export * from './scope.type.js';
export * from './type.interface.js';
export * from './typedef.interface.js';
export * from './var-type.interface';

View File

@@ -0,0 +1,7 @@
import type { Class } from './index.js';
// @ts-expect-error
export interface Interface extends Class {
kind: 'interface';
classdesc: string;
}

View File

@@ -0,0 +1,8 @@
export interface Item {
id: string;
longname: string;
name: string;
kind: string;
description: string;
order: number;
}

View File

@@ -0,0 +1,17 @@
import type { Access, Item, Meta, Param, Scope, Type } from './index.js';
export interface Member extends Item {
kind: 'member';
see?: string[];
scope: Scope;
memberof: string;
type: Type;
access?: Access;
readonly?: boolean;
nullable?: boolean;
virtual?: boolean;
deprecated?: boolean | string;
default?: string;
properties?: Param[];
meta: Meta;
}

View File

@@ -0,0 +1,5 @@
export interface Meta {
lineno: number;
filename: string;
path: string;
}

View File

@@ -0,0 +1,22 @@
import type { Access, Exception, Item, Meta, Param, Return, Scope } from './index.js';
export interface Method extends Item {
kind: 'function';
see?: string[];
scope: Scope;
access?: Access;
inherits?: string;
inherited?: boolean;
implements?: string[];
examples?: string[];
virtual?: boolean;
deprecated?: boolean | string;
memberof?: string;
params?: Param[];
async?: boolean;
generator?: boolean;
fires?: string[];
returns?: Return[];
exceptions?: Exception[];
meta: Meta;
}

View File

@@ -0,0 +1,11 @@
import type { Type } from './index.js';
export interface Param {
type: Type;
description: string;
name: string;
optional?: boolean;
defaultvalue?: string;
variable?: string;
nullable?: boolean;
}

View File

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

View File

@@ -0,0 +1,3 @@
import type { Class, External, Interface, Method, Typedef } from './index.js';
export type RootTypes = Class | Method | Interface | Typedef | External;

View File

@@ -0,0 +1 @@
export type Scope = 'global' | 'instance' | 'static';

View File

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

View File

@@ -0,0 +1,14 @@
import type { Access, Item, Meta, Param, Return, Scope, Type } from './index.js';
export interface Typedef extends Item {
kind: 'typedef';
scope: Scope;
see?: string[];
access?: Access;
deprecated?: boolean | string;
type: Type;
properties?: Param[];
params?: Param[];
returns?: Return[];
meta: Meta;
}

View File

@@ -0,0 +1,6 @@
import type { Type } from './index.js';
export interface VarType extends Type {
description?: string;
nullable?: boolean;
}

View File

@@ -0,0 +1,76 @@
import { Collection } from '@discordjs/collection';
import { DocumentedConstructor } from './constructor.js';
import { DocumentedEvent } from './event.js';
import { DocumentedItemMeta } from './item-meta.js';
import { DocumentedItem } from './item.js';
import { DocumentedMember } from './member.js';
import { DocumentedMethod } from './method.js';
import { DocumentedVarType } from './var-type.js';
import type { Class, Config } from '../interfaces/index.js';
export class DocumentedClass extends DocumentedItem<Class> {
public readonly props = new Collection<string, DocumentedMember>();
public readonly methods = new Collection<string, DocumentedMethod>();
public readonly events = new Collection<string, DocumentedEvent>();
public construct: DocumentedConstructor | null = null;
public extends: DocumentedVarType | null = null;
public implements: DocumentedVarType | null = null;
public constructor(data: Class, config: Config) {
super(data, config);
if (data.augments) {
this.extends = new DocumentedVarType({ names: data.augments }, this.config);
}
if (data.implements) {
this.implements = new DocumentedVarType({ names: data.implements }, this.config);
}
}
public add(item: DocumentedConstructor | DocumentedMethod | DocumentedMember | DocumentedEvent) {
if (item instanceof DocumentedConstructor) {
if (this.construct) throw new Error(`Doc ${this.data.name} already has constructor`);
this.construct = item;
} else if (item instanceof DocumentedMethod) {
const prefix = item.data.scope === 'static' ? 's-' : '';
if (this.methods.has(prefix + item.data.name)) {
throw new Error(`Doc ${this.data.name} already has method ${item.data.name}`);
}
this.methods.set(prefix + item.data.name, item);
} else if (item instanceof DocumentedMember) {
if (this.props.has(item.data.name)) {
throw new Error(`Doc ${this.data.name} already has prop ${item.data.name}`);
}
this.props.set(item.data.name, item);
} else if (item instanceof DocumentedEvent) {
if (this.events.has(item.data.name)) {
throw new Error(`Doc ${this.data.name} already has event ${item.data.name}`);
}
this.events.set(item.data.name, item);
}
}
public override serializer() {
return {
name: this.data.name,
description: this.data.description,
see: this.data.see,
extends: this.extends?.serialize(),
implements: this.implements?.serialize(),
access: this.data.access,
abstract: this.data.virtual,
deprecated: this.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,
meta: new DocumentedItemMeta(this.data.meta, this.config).serialize(),
};
}
}

View File

@@ -0,0 +1,17 @@
import { DocumentedItem } from './item.js';
import { DocumentedParam } from './param.js';
import type { Constructor } from '../interfaces/index.js';
export class DocumentedConstructor extends DocumentedItem<Constructor> {
public override serializer() {
return {
name: this.data.name,
description: this.data.description,
see: this.data.see,
access: this.data.access,
params: this.data.params?.length
? this.data.params.map((p) => new DocumentedParam(p, this.config).serialize())
: undefined,
};
}
}

View File

@@ -0,0 +1,19 @@
import { DocumentedItemMeta } from './item-meta.js';
import { DocumentedItem } from './item.js';
import { DocumentedParam } from './param.js';
import type { Event } from '../interfaces/index.js';
export class DocumentedEvent extends DocumentedItem<Event> {
public override serializer() {
return {
name: this.data.name,
description: this.data.description,
see: this.data.see,
deprecated: this.data.deprecated,
params: this.data.params?.length
? this.data.params.map((p) => new DocumentedParam(p, this.config).serialize())
: undefined,
meta: new DocumentedItemMeta(this.data.meta, this.config).serialize(),
};
}
}

View File

@@ -0,0 +1,14 @@
import { DocumentedItemMeta } from './item-meta.js';
import { DocumentedItem } from './item.js';
import type { External } from '../interfaces/index.js';
export class DocumentedExternal extends DocumentedItem<External> {
public override serializer() {
return {
name: this.data.name,
description: this.data.description,
see: this.data.see,
meta: new DocumentedItemMeta(this.data.meta, this.config).serialize(),
};
}
}

View File

@@ -0,0 +1,11 @@
import { DocumentedClass } from './class.js';
import type { Interface } from '../interfaces/index.js';
export class DocumentedInterface extends DocumentedClass {
public override serializer() {
const data = this.data as unknown as Interface;
const serialized = super.serializer();
serialized.description = data.classdesc;
return serialized;
}
}

View File

@@ -0,0 +1,13 @@
import { relative } from 'path';
import { DocumentedItem } from './item.js';
import type { Meta } from '../interfaces/index.js';
export class DocumentedItemMeta extends DocumentedItem<Meta> {
public override serializer() {
return {
line: this.data.lineno,
file: this.data.filename,
path: relative(this.config.root, this.data.path).replace(/\\/g, '/'),
};
}
}

View File

@@ -0,0 +1,27 @@
import type { Config, Item } from '../interfaces/index.js';
export class DocumentedItem<T = Item> {
public constructor(public readonly data: T, public readonly config: Config) {}
public serialize() {
try {
return this.serializer();
} catch (err) {
const error = err as Error;
error.message = `Error while serializing ${this.detailedName()}: ${error.message}`;
throw error;
}
}
protected serializer() {
throw new Error("Method 'serializer()' must be implemented.");
}
private detailedName() {
const data = this.data as Item | undefined;
if (!data) return this.constructor.name;
if (data.id) return `${data.id} (${this.constructor.name})`;
if (data.name) return `${data.name} (${this.constructor.name})`;
return this.constructor.name;
}
}

View File

@@ -0,0 +1,44 @@
import { DocumentedItemMeta } from './item-meta.js';
import { DocumentedItem } from './item.js';
import { DocumentedParam } from './param.js';
import { DocumentedVarType } from './var-type.js';
import type { Member } from '../interfaces/index.js';
export class DocumentedMember extends DocumentedItem<Member> {
public override serializer() {
return {
name: this.data.name,
description: this.data.description,
see: this.data.see,
scope: this.data.scope,
access: this.data.access,
readonly: this.data.readonly,
nullable: this.data.nullable,
abstract: this.data.virtual,
deprecated: this.data.deprecated,
default: this.data.default,
type: new DocumentedVarType(this.data.type, this.config).serialize(),
props: this.data.properties?.length
? this.data.properties.map((p) => new DocumentedParam(p, this.config).serialize())
: undefined,
meta: new DocumentedItemMeta(this.data.meta, this.config).serialize(),
};
}
}
/*
{ id: 'Client#rest',
longname: 'Client#rest',
name: 'rest',
scope: 'instance',
kind: 'member',
description: 'The REST manager of the client',
memberof: 'Client',
type: { names: [ 'RESTManager' ] },
access: 'private',
meta:
{ lineno: 32,
filename: 'Client.js',
path: 'src/client' },
order: 11 }
*/

View File

@@ -0,0 +1,34 @@
import { DocumentedItemMeta } from './item-meta.js';
import { DocumentedItem } from './item.js';
import { DocumentedParam } from './param.js';
import { DocumentedVarType } from './var-type.js';
import type { Method } from '../interfaces/index.js';
export class DocumentedMethod extends DocumentedItem<Method> {
public override serializer() {
return {
name: this.data.name,
description: this.data.description,
see: this.data.see,
scope: this.data.scope,
access: this.data.access,
inherits: this.data.inherits,
inherited: this.data.inherited,
implements: this.data.implements,
examples: this.data.examples,
abstract: this.data.virtual && !this.data.inherited,
deprecated: this.data.deprecated,
emits: this.data.fires,
throws: this.data.exceptions,
params: this.data.params?.length
? this.data.params.map((p) => new DocumentedParam(p, this.config).serialize())
: undefined,
async: this.data.async,
generator: this.data.generator,
returns: this.data.returns?.length
? this.data.returns.map((p) => new DocumentedVarType(p, this.config).serialize())
: undefined,
meta: new DocumentedItemMeta(this.data.meta, this.config).serialize(),
};
}
}

View File

@@ -0,0 +1,17 @@
import { DocumentedItem } from './item.js';
import { DocumentedVarType } from './var-type.js';
import type { Param } from '../interfaces/index.js';
export class DocumentedParam extends DocumentedItem<Param> {
public override serializer() {
return {
name: this.data.name,
description: this.data.description,
optional: this.data.optional,
default: this.data.defaultvalue,
variable: this.data.variable,
nullable: this.data.nullable,
type: new DocumentedVarType(this.data.type, this.config).serialize(),
};
}
}

View File

@@ -0,0 +1,28 @@
import { DocumentedItemMeta } from './item-meta.js';
import { DocumentedItem } from './item.js';
import { DocumentedParam } from './param.js';
import { DocumentedVarType } from './var-type.js';
import type { Typedef } from '../interfaces/index.js';
export class DocumentedTypeDef extends DocumentedItem<Typedef> {
public override serializer() {
return {
name: this.data.name,
description: this.data.description,
see: this.data.see,
access: this.data.access,
deprecated: this.data.deprecated,
type: new DocumentedVarType(this.data.type, this.config).serialize(),
props: this.data.properties?.length
? this.data.properties.map((p) => new DocumentedParam(p, this.config).serialize())
: undefined,
params: this.data.params?.length
? this.data.params.map((p) => new DocumentedParam(p, this.config).serialize())
: undefined,
returns: this.data.returns?.length
? this.data.returns.map((p) => new DocumentedVarType(p, this.config).serialize())
: undefined,
meta: new DocumentedItemMeta(this.data.meta, this.config).serialize(),
};
}
}

View File

@@ -0,0 +1,34 @@
import { DocumentedItem } from './item.js';
import type { VarType } from '../interfaces/index.js';
export class DocumentedVarType extends DocumentedItem<VarType> {
public override serializer() {
const names = this.data.names?.map((name) => this.splitVarName(name));
if (!this.data.description && !this.data.nullable) {
return names;
}
return {
types: names,
description: this.data.description,
nullable: this.data.nullable,
};
}
private splitVarName(str: string) {
if (str === '*') return ['*'];
str = str.replace(/\./g, '');
const matches = str.match(/([\w*]+)([^\w*]+)/g);
const output = [];
if (matches) {
for (const match of matches) {
const groups = /([\w*]+)([^\w*]+)/.exec(match);
output.push([groups![1], groups![2]]);
}
} else {
output.push([str.match(/([\w*]+)/g)![0]]);
}
return output;
}
}

View File

@@ -0,0 +1,20 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"allowJs": true
},
"include": [
"**/*.ts",
"**/*.tsx",
"**/*.js",
"**/*.mjs",
"**/*.jsx",
"**/*.test.ts",
"**/*.test.js",
"**/*.test.mjs",
"**/*.spec.ts",
"**/*.spec.js",
"**/*.spec.mjs"
],
"exclude": []
}

View File

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

View File

@@ -0,0 +1,13 @@
import { defineConfig } from 'tsup';
export default defineConfig({
clean: true,
dts: true,
entryPoints: ['src/index.ts'],
format: ['esm', 'cjs'],
keepNames: true,
minify: false,
skipNodeModulesBundle: true,
sourcemap: true,
target: 'es2021',
});

View File

@@ -25,8 +25,3 @@ docs/**/*
.tmp/ .tmp/
coverage/ coverage/
tsconfig.tsbuildinfo tsconfig.tsbuildinfo
.turbo
# Yarn files
.yarn/install-state.gz
.yarn/build-state.yml

View File

@@ -6,3 +6,4 @@ docs/**/*
!docs/index.yml !docs/index.yml
!docs/README.md !docs/README.md
coverage/ coverage/
tsup.config.*.mjs

View File

@@ -25,8 +25,3 @@ docs/**/*
.tmp/ .tmp/
coverage/ coverage/
tsconfig.tsbuildinfo tsconfig.tsbuildinfo
.turbo
# Yarn files
.yarn/install-state.gz
.yarn/build-state.yml

View File

@@ -6,3 +6,4 @@ docs/**/*
!docs/index.yml !docs/index.yml
!docs/README.md !docs/README.md
coverage/ coverage/
tsup.config.*.mjs

View File

@@ -176,8 +176,8 @@
END OF TERMS AND CONDITIONS END OF TERMS AND CONDITIONS
Copyright 2021 Noel Buechler Copyright 2021 Noel Buechler
Copyright 2021 Antonio Román
Copyright 2021 Vlad Frangu Copyright 2021 Vlad Frangu
Copyright 2021 Antonio Román
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.

View File

@@ -19,10 +19,6 @@ dist/
typings/ typings/
docs/**/* docs/**/*
!docs/index.yml
!docs/README.md
!docs/examples/
!docs/examples/*.md
# Miscellaneous # Miscellaneous
.tmp/ .tmp/

View File

@@ -6,3 +6,4 @@ docs/**/*
!docs/index.yml !docs/index.yml
!docs/README.md !docs/README.md
coverage/ coverage/
tsup.config.*.mjs

View File

@@ -175,8 +175,7 @@
END OF TERMS AND CONDITIONS END OF TERMS AND CONDITIONS
Copyright 2021 Noel Buechler Copyright 2022 Noel Buechler
Copyright 2021 Vlad Frangu
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.

View File

@@ -6,3 +6,4 @@ docs/**/*
!docs/index.yml !docs/index.yml
!docs/README.md !docs/README.md
coverage/ coverage/
tsup.config.*.mjs

View File

@@ -175,7 +175,8 @@
END OF TERMS AND CONDITIONS END OF TERMS AND CONDITIONS
Copyright 2020-2021 Amish Shah Copyright 2022 Noel Buechler
Copyright 2020 Amish Shah
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.

945
yarn.lock

File diff suppressed because it is too large Load Diff