18 Commits

Author SHA1 Message Date
Jacob Nguyen
715f373dea fix sern build option 2024-04-11 18:17:28 -05:00
Jacob Nguyen
504331d7ca user install work? 2024-04-10 21:23:48 -05:00
Jacob Nguyen
44e5dd3845 the readme was kinda vague (#133) 2024-03-19 12:41:41 -05:00
github-actions[bot]
9f9a2aaca7 chore(main): release 1.2.1 (#132)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-02-07 22:09:32 -06:00
Jacob Nguyen
d1832e44ce fix: better error messages for publish 2024-02-07 22:04:05 -06:00
Jacob Nguyen
e55ceedadd refactor: error json inspecter 2024-02-07 21:49:09 -06:00
github-actions[bot]
6bb212a3be chore(main): release 1.2.0 (#131)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-01-29 00:38:02 -06:00
Jacob Nguyen
2d6e65a1e6 feat: make application id optional, thanks @trueharuu (#130)
make application id optional, thanks @trueharuu
2024-01-29 09:56:24 +05:30
github-actions[bot]
eb53ecb638 chore(main): release 1.1.0 (#129)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2024-01-27 23:50:17 -06:00
Jacob Nguyen
303ac0280c feat: command clear (#128) 2024-01-28 10:59:37 +05:30
github-actions[bot]
3f994d6948 chore(main): release 1.0.3 (#127)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-12-25 19:26:01 -06:00
Jacob Nguyen
a5cb66828e fix: intellisense for esm build ts (#126)
* fix: broken link and refactor
2023-12-25 11:47:46 -06:00
github-actions[bot]
667d0c1b89 chore(main): release 1.0.2 (#125)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2023-11-04 16:20:29 -05:00
Jacob Nguyen
5dbf2a87dc fix: better error handling 2023-11-04 16:14:00 -05:00
a309c085e9 chore: build docs rephrasing (#118)
Co-authored-by: Jacob Nguyen <76754747+jacoobes@users.noreply.github.com>
2023-10-18 13:39:58 -05:00
f1d7d6c911 fix: build mkdir errors (#122)
Co-authored-by: Jacob Nguyen <76754747+jacoobes@users.noreply.github.com>
2023-10-18 13:27:58 -05:00
Jacob Nguyen
4ec96dbe17 Update continuous-integration.yml 2023-10-18 13:18:29 -05:00
Peter-MJ-Parker
3970cc6911 chore: fix grammar in error message (#123) 2023-10-13 22:53:19 +05:30
15 changed files with 226 additions and 85 deletions

View File

@@ -11,25 +11,25 @@ on:
- main
jobs:
Lint:
name: Linting
runs-on: ubuntu-latest
# Lint:
# name: Linting
# runs-on: ubuntu-latest
steps:
- name: Check out Git repository
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3
# steps:
# - name: Check out Git repository
# uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3
- name: Set up Node.js
uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c # v3
with:
node-version: 17
# - name: Set up Node.js
# uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c # v3
# with:
# node-version: 17
# Prettier must be in `package.json`
- name: Install Node.js dependencies
run: npm i
# - name: Install Node.js dependencies
# run: npm i
- name: Run Prettier
run: npm run format
# - name: Run Prettier
# run: npm run format
Test:
name: Testing

View File

@@ -2,6 +2,42 @@
All notable changes to this project will be documented in this file.
## [1.2.1](https://github.com/sern-handler/cli/compare/v1.2.0...v1.2.1) (2024-02-08)
### Bug Fixes
* better error messages for publish ([d1832e4](https://github.com/sern-handler/cli/commit/d1832e44ce1b10aeb5b9dc902b7d35ab51c41ff3))
## [1.2.0](https://github.com/sern-handler/cli/compare/v1.1.0...v1.2.0) (2024-01-29)
### Features
* make application id optional, thanks [@trueharuu](https://github.com/trueharuu) ([#130](https://github.com/sern-handler/cli/issues/130)) ([2d6e65a](https://github.com/sern-handler/cli/commit/2d6e65a1e6073f605aab192b8cea33037a04af2c))
## [1.1.0](https://github.com/sern-handler/cli/compare/v1.0.3...v1.1.0) (2024-01-28)
### Features
* command clear ([#128](https://github.com/sern-handler/cli/issues/128)) ([303ac02](https://github.com/sern-handler/cli/commit/303ac0280c7c7c55f2670d49c9685b911670bc05))
## [1.0.3](https://github.com/sern-handler/cli/compare/v1.0.2...v1.0.3) (2023-12-25)
### Bug Fixes
* intellisense for esm build ts ([#126](https://github.com/sern-handler/cli/issues/126)) ([a5cb668](https://github.com/sern-handler/cli/commit/a5cb66828eae47d3eac5b86c7e67c01dbed500d5))
## [1.0.2](https://github.com/sern-handler/cli/compare/v1.0.1...v1.0.2) (2023-11-04)
### Bug Fixes
* better error handling ([5dbf2a8](https://github.com/sern-handler/cli/commit/5dbf2a87dcb0001993fe126d9002bc82c8108e24))
* build mkdir errors ([#122](https://github.com/sern-handler/cli/issues/122)) ([f1d7d6c](https://github.com/sern-handler/cli/commit/f1d7d6c911bc54ed3ca3e39eefbc7de6ee33b10d))
## [1.0.1](https://github.com/sern-handler/cli/compare/v1.0.0...v1.0.1) (2023-10-05)

View File

@@ -3,11 +3,11 @@
</div>
# Features
😁 **User Friendly** <br>
💦 **Simple** <br>
🌱 **Efficient** <br>
💪 **Powerful** <br>
- Manage discord application commands from the command line.
- Install plugins from the community.
- Really fast startup times (I think).
- Deploy with premade docker configurations.
- Inhouse build tool based on esbuild built for sern applications, nearly **zero** config.
## Installation

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "@sern/cli",
"version": "1.0.1",
"version": "1.2.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@sern/cli",
"version": "1.0.1",
"version": "1.2.1",
"license": "MIT",
"dependencies": {
"@esbuild-kit/cjs-loader": "^2.4.2",

View File

@@ -1,6 +1,6 @@
{
"name": "@sern/cli",
"version": "1.0.1",
"version": "1.2.1",
"description": "Official CLI for @sern/handler",
"exports": "./dist/index.js",
"bin": {

View File

@@ -54,19 +54,23 @@ export async function build(options: Record<string, any>) {
}
const sernConfig = await getConfig();
let buildConfig: Partial<BuildOptions> = {};
const entryPoints = await glob(`./src/**/*{${validExtensions.join(',')}}`, {
//for some reason, my ignore glob wasn't registering correctly'
ignore: {
ignored: (p) => p.name.endsWith('.d.ts'),
},
});
const buildConfigPath = resolve(options.project ?? 'sern.build.js');
const resolveBuildConfig = (path: string|undefined, language: string) => {
if(language === 'javascript') {
return path ?? resolve('jsconfig.json')
}
return path ?? resolve('tsconfig.json')
}
const defaultBuildConfig = {
defineVersion: true,
format: options.format ?? 'esm',
@@ -76,28 +80,23 @@ export async function build(options: Record<string, any>) {
env: options.env ?? resolve('.env'),
};
if (pathExistsSync(buildConfigPath)) {
try {
buildConfig = {
...defaultBuildConfig,
...(await import('file:///' + buildConfigPath)).default,
};
} catch (e) {
console.log(e);
process.exit(1);
}
} else {
//throwable, buildConfigPath may not exist
buildConfig = {
...defaultBuildConfig,
...(await import('file:///' + buildConfigPath)).default,
};
} else {
buildConfig = defaultBuildConfig;
console.log('No build config found, defaulting');
}
let env = {} as Record<string, string>;
configDotenv({ path: buildConfig.env, processEnv: env });
if (env.MODE && !env.NODE_ENV) {
const modeButNotNodeEnvExists = env.MODE && !env.NODE_ENV;
if (modeButNotNodeEnvExists) {
console.warn('Use NODE_ENV instead of MODE');
console.warn('MODE has no effect.');
console.warn(`https://nodejs.dev/en/learn/nodejs-the-difference-between-development-and-production/`);
console.warn(`https://nodejs.org/en/learn/getting-started/nodejs-the-difference-between-development-and-production`);
}
if (env.NODE_ENV) {
@@ -110,7 +109,7 @@ export async function build(options: Record<string, any>) {
try {
let config = require(buildConfig.tsconfig!);
config.extends && console.warn("Please ensure to extend the generated tsconfig")
config.extends && console.warn("Extend the generated tsconfig")
} catch(e) {
console.warn("no tsconfig / jsconfig found");
console.warn(`Please create a ${sernConfig.language === 'javascript' ? 'jsconfig.json' : 'tsconfig.json' }`);
@@ -130,15 +129,15 @@ export async function build(options: Record<string, any>) {
console.log(' ', magentaBright('env'), buildConfig.env);
const sernDir = resolve('.sern'),
genDir = resolve(sernDir, 'generated'),
ambientFilePath = resolve(sernDir, 'ambient.d.ts'),
packageJsonPath = resolve('package.json'),
sernTsConfigPath = resolve(sernDir, 'tsconfig.json'),
packageJson = () => require(packageJsonPath);
genDir = resolve(sernDir, 'generated'),
ambientFilePath = resolve(sernDir, 'ambient.d.ts'),
packageJsonPath = resolve('package.json'),
sernTsConfigPath = resolve(sernDir, 'tsconfig.json'),
packageJson = () => require(packageJsonPath);
if (!(await pathExists(genDir))) {
console.log('Making .sern/generated dir, does not exist');
await mkdir(genDir);
await mkdir(genDir, { recursive: true });
}
try {

View File

@@ -0,0 +1,60 @@
import * as Rest from '../rest.js'
import assert from 'node:assert'
import dotenv from 'dotenv'
import ora from 'ora';
import type { CommandData, GuildId } from '../utilities/types.js';
import { readFileSync, writeFile } from 'node:fs'
import { resolve } from 'node:path'
import prompts from 'prompts';
const getConfirmation = (args: Record<string,any> ) => {
if(args.yes) {
return args.yes
} else {
return prompts({
type: 'confirm',
name: 'confirmation',
message: 'Are you sure you want to delete ALL your application commands?',
initial: true
}, { onCancel: () => (console.log("Cancelled operation ( ̄┰ ̄*)"), process.exit(1)) })
.then(response => response.confirmation);
}
}
export async function commandClear(args: Record<string,any>) {
dotenv.configDotenv({ path: args.env || resolve('.env') })
const token = process.env.token || process.env.DISCORD_TOKEN;
assert(token, 'Could not find a token for this bot in .env or commandline. Do you have DISCORD_TOKEN in env?');
const confirmation = await getConfirmation(args);
if (confirmation) {
const spin = ora({
text: `Deleting ALL application commands...`,
spinner: 'aesthetic',
}).start();
const rest = await Rest.create(token);
let guildCommands: Record<GuildId, CommandData[]>
try {
guildCommands = JSON.parse(readFileSync('.sern/command-data-remote.json', 'utf-8'))
await rest.updateGlobal([]);
delete guildCommands.global
for (const guildId in guildCommands) {
await rest.putGuildCommands(guildId, []);
}
writeFile('.sern/command-data-remote.json', "{}", (err) => {
if(err) {
spin.fail("Error happened while writing to json:");
console.error(err)
process.exit(1)
}
})
spin.succeed();
} catch(e) {
spin.fail("Something went wrong. ");
throw e;
}
} else {
console.log('Operation canceled. ( ̄┰ ̄*)');
}
}

View File

@@ -14,9 +14,11 @@ export function list() {
const globalCommands = commands.global;
delete commands.global;
console.log(bold('Global Commands'));
for (const command of globalCommands) log(command);
if(globalCommands) {
console.log(bold('Global Commands'));
for (const command of globalCommands) log(command);
}
console.log('\t');
for (const guildId in commands) {

View File

@@ -15,7 +15,7 @@ export async function publish(commandDir: string | undefined, args: Partial<Publ
args.import ??= [];
args.token && console.info('Token passed through command line');
args.applicationId && console.info('applicationId passed through command line');
args.applicationId && console.info(magentaBright('WARNING')+ ' This option is deprecated. Do not pass applicationId through command line');
commandDir && console.info('Publishing with override path: ', commandDir);
const dotenvLocation = new URL('../node_modules/dotenv/config.js', rootPath),

View File

@@ -10,7 +10,8 @@ import { once } from 'node:events';
import * as Rest from './rest';
import type { sernConfig } from './utilities/getConfig';
import type { PublishableData, PublishableModule, Typeable } from './create-publish.d.ts';
import { cyanBright, greenBright, redBright } from 'colorette';
import { cyanBright, greenBright, magentaBright, redBright } from 'colorette';
import { inspect } from 'node:util'
import ora from 'ora';
async function deriveFileInfo(dir: string, file: string) {
@@ -143,6 +144,7 @@ const serialize = (permissions: unknown) => {
const makePublishData = ({ commandModule, config }: Record<string, Record<string, unknown>>) => {
const applicationType = intoApplicationType(commandModule.type as number);
console.log(config)
return {
data: {
name: commandModule.name as string,
@@ -152,6 +154,19 @@ const makePublishData = ({ commandModule, config }: Record<string, Record<string
options: optionsTransformer((commandModule?.options ?? []) as Typeable[]),
dm_permission: config?.dmPermission,
default_member_permissions: serialize(config?.defaultMemberPermissions),
//@ts-ignore
integration_types: (config?.integrationTypes ?? ['Guild']).map(
(s: string) => {
if(s === "Guild") {
return 0
} else if (s == "User") {
return 1
} else {
throw Error("IntegrationType is not one of Guild or User");
}
}),
//@ts-ignore
contexts: config?.contexts ? config.contexts : undefined
},
config,
};
@@ -163,13 +178,13 @@ const publishableData = modules.map(makePublishData),
appid = process.env.applicationId || process.env.APPLICATION_ID;
assert(token, 'Could not find a token for this bot in .env or commandline. Do you have DISCORD_TOKEN in env?');
assert(appid, 'Could not find an application id for this bot in .env or commandline. Do you have APPLICATION_ID in env?');
appid && console.warn(`${magentaBright('WARNING')}: APPLICATION_ID is not necessary anymore`);
// partition globally published and guilded commands
const [globalCommands, guildedCommands] = publishableData.reduce(
([globals, guilded], module) => {
const isPublishableGlobally = !module.config || !Array.isArray(module.config.guildIds);
const isPublishableGlobally = !Array.isArray(module.config?.guildIds);
if (isPublishableGlobally) {
console.log(module)
return [[module, ...globals], guilded];
}
return [globals, [module, ...guilded]];
@@ -181,7 +196,7 @@ const spin = ora(`Publishing ${cyanBright('Global')} commands`);
globalCommands.length && spin.start();
const rest = Rest.create(appid, token);
const rest = await Rest.create(token);
const res = await rest.updateGlobal(globalCommands);
let globalCommandsResponse: unknown;
@@ -189,25 +204,32 @@ let globalCommandsResponse: unknown;
if (res.ok) {
globalCommands.length && spin.succeed(`All ${cyanBright('Global')} commands published`);
globalCommandsResponse = await res.json();
console.log(globalCommandsResponse)
} else {
spin.fail(`Failed to publish global commands [Code: ${redBright(res.status)}]`);
let err: Error
console.error("Status Text ", res.statusText);
switch(res.status) {
case 400 :
throw Error("400: Ensure your commands have proper fields and data with left nothing out");
case 404 :
case 400 : {
const validation_errors = await res.json()
console.error('errors:', inspect(validation_errors, { depth: Infinity }));
console.error("Modules with validation errors:"
+ inspect(Object.keys(validation_errors.errors).map(idx => globalCommands[idx as any])))
throw Error("400: Ensure your commands have proper fields and data with nothing left out");
}
case 404 : {
console.error('errors:', inspect(await res.json(), { depth: Infinity }));
throw Error("Forbidden 404. Is you application id and/or token correct?")
case 429:
throw Error('Chill out homie, too many requests')
}
case 429: {
console.error('errors:', inspect(await res.json(), { depth: Infinity }));
err = Error('Chill out homie, too many requests')
} break;
default: {
console.error('errors:', inspect(await res.json(), { depth: Infinity }));
throw Error(res.status.toString() + " error")
}
}
console.error(
'errors:',
await res.json().then((res) => {
const errors = Object.values(res.errors);
// @ts-ignore
return errors.map((err) => err?.name?._errors);
})
);
console.error(res.statusText);
}
function associateGuildIdsWithData(data: PublishableModule[]): Map<string, PublishableData[]> {
@@ -246,12 +268,21 @@ for (const [guildId, array] of guildCommandMap.entries()) {
} else {
spin.fail(`[${redBright(guildId)}] Failed to update commands for guild, Reason: ${result.message}`);
switch(response.status) {
case 400 :
throw Error("400: Ensure your commands have proper fields and data and left nothing out");
case 404 :
case 400 : {
console.error(inspect(result, { depth: Infinity }))
console.error("Modules with validation errors:"
+ inspect(Object.keys(result.errors).map(idx => array[idx as any])))
throw Error("400: Ensure your commands have proper fields and data and nothing left out");
}
case 404 : {
console.error(inspect(result, { depth: Infinity }))
throw Error("Forbidden 404. Is you application id and/or token correct?")
case 429:
}
case 429: {
console.error(inspect(result, { depth: Infinity }))
throw Error('Chill out homie, too many requests')
}
}
}
}

View File

@@ -39,24 +39,26 @@ program //
.description('New way to manage your slash commands')
.option('-W --suppress-warnings', 'suppress experimental warning')
.option('-i, --import [scriptPath...]', 'Prerequire a script to load into publisher')
.option('-t, --token [token]')
.option('--appId [applicationId]')
.option('-e --env', 'path to .env file')
.argument('[path]', 'path with respect to current working directory that will locate all published files')
.action(async (...args) => importDynamic('publish.js').then((m) => m.publish(...args)))
)
.addCommand(
).addCommand(
new Command('list') //
.description('List all slash commands')
.action(async (...args) => importDynamic('list.js').then((m) => m.list(...args)))
);
.action(async (...args) => importDynamic('list.js').then((m) => m.list(...args))))
.addCommand(
new Command('clear')
.description('Clear and reset commands-data-remote.json and the api')
.option('-y, --yes', "Say yes to all prompts")
.option('-e, --env [path]', "Supply a path to a .env")
.action(async (...args) => importDynamic('command-clear.js').then((m) => m.commandClear(...args))));
program
.command('build')
.description('Build your bot')
.option('-f --format [fmt]', 'The module system of your application. `cjs` or `esm`', 'esm')
.option('-m --mode [mode]', 'the mode for sern to build in. `production` or `development`', 'development')
.option('-W --suppress-warnings', 'suppress experimental warning')
.option('-p --project [filePath]', 'build with this sern.build file')
.option('-p --project [filePath]', 'build with the provided sern.build file')
.option('-e --env', 'path to .env file')
.option('--tsconfig [filePath]', 'Use this tsconfig')
.action(async (...args) => importDynamic('build.js').then((m) => m.build(...args)));

View File

@@ -11,12 +11,22 @@ const publishablesIntoJson = (ps: PublishableModule[]) =>
4
);
export const create = (appid: string, token: string) => {
const globalURL = new URL(`${appid}/commands`, baseURL);
export const create = async (token: string) => {
const headers = {
Authorization: 'Bot ' + token,
'Content-Type': 'application/json',
};
let me;
let appid: string;
try {
me = await fetch(new URL('@me', baseURL), { headers }).then(res => res.json());
appid = me.id;
} catch(e) {
console.log("Something went wrong while trying to fetch your application:");
throw e;
}
const globalURL = new URL(`${appid}/commands`, baseURL);
return {
updateGlobal: (commands: PublishableModule[]) =>
fetch(globalURL, {

View File

@@ -13,7 +13,7 @@ export interface sernConfig {
export interface TheoreticalEnv {
DISCORD_TOKEN: string;
APPLICATION_ID: string;
APPLICATION_ID?: string;
MODE: 'PROD' | 'DEV';
[name: string]: string;
}

View File

@@ -11,7 +11,6 @@ export async function getConfig(): Promise<sernConfig> {
return output;
}
export interface sernConfig {
language: 'typescript' | 'javascript';
defaultPrefix?: string;
@@ -20,5 +19,4 @@ export interface sernConfig {
commands: string;
events?: string;
};
buildPath: string;
}

View File

@@ -6,9 +6,9 @@ const processEnvType = (env: NodeJS.ProcessEnv) => {
const envBuilder = new StringWriter();
for (const key of entries) {
envBuilder.tab();
envBuilder.tab();
envBuilder.envField(key);
envBuilder.tab()
.tab()
.envField(key);
}
return envBuilder.build();
};
@@ -40,6 +40,8 @@ const writeTsConfig = async (format: 'cjs' | 'esm', configPath: string, fw: File
const target = format === 'esm' ? { target: 'esnext' } : {};
const sernTsConfig = {
compilerOptions: {
//module determines top level await. CJS doesn't have that abliity afaik
module: format === 'cjs' ? 'node' : 'esnext',
moduleResolution: 'node',
strict: true,
skipLibCheck: true,
@@ -69,6 +71,7 @@ class StringWriter {
return this;
}
envField(key: string) {
//if env field has space or parens, wrap key in ""
if (/\s|\(|\)/g.test(key)) {
this.fileString += `"${key}": string`;
} else {