@wolfstar/create-http-framework 2.0.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2022 Wolfstar Project
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,69 @@
1
+ # `@wolfstar/create-http-framework`
2
+
3
+ A CLI scaffolding tool for creating new [WolfStar HTTP Framework](https://github.com/wolfstar-project/stars-components/tree/main/packages/http-framework) bot projects.
4
+
5
+ ## Usage
6
+
7
+ ```bash
8
+ npm create @wolfstar/http-framework@latest my-discord-bot
9
+ # or
10
+ pnpm create @wolfstar/http-framework my-discord-bot
11
+ # or
12
+ yarn create @wolfstar/http-framework my-discord-bot
13
+ # or
14
+ bun create @wolfstar/http-framework my-discord-bot
15
+ ```
16
+
17
+ The CLI will guide you through the following prompts:
18
+
19
+ - **Project name** — an npm-compatible name for your bot
20
+ - **Package manager** — npm, yarn, pnpm, or bun
21
+ - **Language** — TypeScript or JavaScript
22
+ - **Build tool** — tsdown, TypeScript 6, or the TypeScript 7 release candidate
23
+ - **Linter and formatter** — Oxlint / ESLint and Oxfmt / Prettier
24
+ - **Port** — the port the HTTP server will listen on (default: `3000`)
25
+ - **i18n support** — optionally add `@wolfstar/http-framework-i18n`
26
+ - **Auto-install** — install dependencies immediately after scaffolding
27
+
28
+ ## Options
29
+
30
+ | Flag | Alias | Description |
31
+ | ---------------------------- | ----- | ----------------------------------------------------------- |
32
+ | `--overwrite` | | Overwrite the target directory if it already exists |
33
+ | `--no-interactive` | | Skip all prompts and use defaults / flags |
34
+ | `--interactive` | `-i` | Force interactive prompts even when an AI agent is detected |
35
+ | `--package-manager <pm>` | | Choose npm, yarn, pnpm, or bun |
36
+ | `--language <lang>` | | Choose TypeScript (`ts`) or JavaScript (`js`) |
37
+ | `--build <tool>` | | Choose `tsc6`, `tsc7`, or `tsdown` for TypeScript |
38
+ | `--lint <linter>` | | Choose `none`, `eslint`, or `oxlint` |
39
+ | `--format <formatter>` | | Choose `none`, `prettier`, or `oxfmt` |
40
+ | `--port <number>` | | Set the HTTP port (default: `3000`) |
41
+ | `--i18n` / `--no-i18n` | | Enable or disable i18n support |
42
+ | `--install` / `--no-install` | | Enable or disable dependency installation |
43
+ | `--help` | `-h` | Print usage and exit |
44
+
45
+ ## Non-interactive / AI agent mode
46
+
47
+ When the CLI detects an AI agent is running it (via [`@vercel/detect-agent`](https://www.npmjs.com/package/@vercel/detect-agent)), it automatically enters non-interactive mode, equivalent to passing `--no-interactive`. A project name argument is required in this mode:
48
+
49
+ ```bash
50
+ create-http-framework my-discord-bot --no-interactive
51
+ ```
52
+
53
+ ## Generated project structure
54
+
55
+ ```
56
+ my-discord-bot/
57
+ ├── src/
58
+ │ ├── commands/
59
+ │ │ └── ping.ts # Example ping command
60
+ │ └── index.ts # Entry point — starts the HTTP server
61
+ ├── .env # Environment variables (DISCORD_TOKEN, DISCORD_PUBLIC_KEY)
62
+ ├── .gitignore
63
+ ├── package.json
64
+ └── tsconfig.json
65
+ ```
66
+
67
+ ## Requirements
68
+
69
+ - Node.js `>=20`
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import { determineAgent } from "@vercel/detect-agent";
4
4
  import mri from "mri";
5
5
  import { dirname, join, relative, resolve } from "node:path";
6
6
  import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
7
- import { execFileSync } from "node:child_process";
7
+ import spawn from "cross-spawn";
8
8
  import { resolveCommand } from "package-manager-detector/commands";
9
9
  import { detect } from "package-manager-detector/detect";
10
10
  import Handlebars from "handlebars";
@@ -33,6 +33,37 @@ function writeFile(filePath, content) {
33
33
  writeFileSync(filePath, content, "utf-8");
34
34
  }
35
35
 
36
+ //#endregion
37
+ //#region src/tools/options.ts
38
+ const PACKAGE_MANAGERS = [
39
+ "npm",
40
+ "yarn",
41
+ "pnpm",
42
+ "bun"
43
+ ];
44
+ const LANGUAGES = ["ts", "js"];
45
+ const BUILD_TOOLS = [
46
+ "tsc6",
47
+ "tsc7",
48
+ "tsdown"
49
+ ];
50
+ const LINTERS = [
51
+ "none",
52
+ "eslint",
53
+ "oxlint"
54
+ ];
55
+ const FORMATTERS = [
56
+ "none",
57
+ "prettier",
58
+ "oxfmt"
59
+ ];
60
+ /**
61
+ * TypeScript 7.0 (the native compiler) ships under the main `typescript` package on the `rc`
62
+ * dist-tag. We pin it exactly because it is a prerelease (the old separate `@typescript/native-preview`
63
+ * package only has dev builds).
64
+ */
65
+ const TYPESCRIPT_RC_VERSION = "7.0.1-rc";
66
+
36
67
  //#endregion
37
68
  //#region src/tools/npmHelpers.ts
38
69
  async function fetchVersion(packageName) {
@@ -40,25 +71,47 @@ async function fetchVersion(packageName) {
40
71
  if (!response.ok) throw new Error(`Failed to resolve latest version for ${packageName}: ${response.status} ${response.statusText}`);
41
72
  return (await response.json()).version;
42
73
  }
43
- async function fetchDependencyVersions() {
44
- const [httpFramework, httpFrameworkI18n, discordApiTypes, typescript, tsNode, typesNode, discordJsBuilders] = await Promise.all([
45
- fetchVersion("@wolfstar/http-framework"),
46
- fetchVersion("@wolfstar/http-framework-i18n"),
47
- fetchVersion("discord-api-types"),
48
- fetchVersion("typescript"),
49
- fetchVersion("ts-node"),
50
- fetchVersion("@types/node"),
51
- fetchVersion("@discordjs/builders")
74
+ /**
75
+ * Resolves the latest versions of only the packages required by the chosen selections.
76
+ * `ts-node` is intentionally never included. TypeScript 7.0 (tsc7) is pinned to the rc instead
77
+ * of being fetched, because `typescript@latest` resolves to the 6.x line.
78
+ */
79
+ async function fetchDependencyVersions(selections) {
80
+ const names = /* @__PURE__ */ new Set([
81
+ "@wolfstar/http-framework",
82
+ "discord-api-types",
83
+ "@discordjs/builders"
52
84
  ]);
53
- return {
54
- httpFramework,
55
- httpFrameworkI18n,
56
- discordApiTypes,
57
- typescript,
58
- tsNode,
59
- typesNode,
60
- discordJsBuilders
61
- };
85
+ if (selections.i18n) names.add("@wolfstar/http-framework-i18n");
86
+ if (selections.language === "ts") {
87
+ names.add("@types/node");
88
+ switch (selections.buildTool) {
89
+ case "tsc6":
90
+ names.add("typescript").add("tsc-watch");
91
+ break;
92
+ case "tsc7":
93
+ names.add("tsc-watch");
94
+ break;
95
+ case "tsdown":
96
+ names.add("tsdown").add("typescript");
97
+ break;
98
+ }
99
+ }
100
+ if (selections.linter === "eslint") {
101
+ names.add("eslint");
102
+ names.add(selections.language === "ts" ? "typescript-eslint" : "@eslint/js");
103
+ }
104
+ if (selections.linter === "oxlint") names.add("oxlint");
105
+ if (selections.formatter === "prettier") names.add("prettier");
106
+ if (selections.formatter === "oxfmt") names.add("oxfmt");
107
+ const list = [...names];
108
+ const resolved = await Promise.all(list.map(fetchVersion));
109
+ const versions = {};
110
+ list.forEach((name, index) => {
111
+ versions[name] = resolved[index];
112
+ });
113
+ if (selections.language === "ts" && selections.buildTool === "tsc7") versions["typescript"] = TYPESCRIPT_RC_VERSION;
114
+ return versions;
62
115
  }
63
116
 
64
117
  //#endregion
@@ -79,21 +132,274 @@ async function detectPackageManager() {
79
132
  }
80
133
  return "npm";
81
134
  }
135
+ function quoteToken(token) {
136
+ return /\s/.test(token) ? `"${token}"` : token;
137
+ }
138
+ /**
139
+ * Builds the correct "run a script" command string for the given package manager, e.g.
140
+ * `npm run build` / `pnpm run build`. Extra args are forwarded the way each manager expects
141
+ * (npm inserts the `--` separator automatically), and tokens containing spaces are quoted so
142
+ * nested commands (`--onSuccess "pnpm run start"`) survive being placed in a package.json script.
143
+ */
144
+ function getRunScript(pm, script, args = []) {
145
+ const resolved = resolveCommand(pm, "run", [script, ...args]);
146
+ if (!resolved) throw new Error(`Could not resolve run command for ${pm}`);
147
+ return [resolved.command, ...resolved.args].map(quoteToken).join(" ");
148
+ }
149
+ /** Returns the install command string for the given package manager, e.g. `pnpm install`. */
150
+ function getInstallScript(pm) {
151
+ const resolved = resolveCommand(pm, "install", []);
152
+ if (!resolved) throw new Error(`Could not resolve install command for ${pm}`);
153
+ return [resolved.command, ...resolved.args].map(quoteToken).join(" ");
154
+ }
82
155
  async function installDependencies(pm, dir) {
83
156
  const agent = (await detect({ cwd: process.cwd() }))?.agent ?? pm;
84
157
  const resolved = resolveCommand(agent, "install", []);
85
158
  if (!resolved) throw new Error(`Could not resolve install command for ${agent}`);
86
- execFileSync(resolved.command, resolved.args, {
159
+ const result = spawn.sync(resolved.command, resolved.args, {
160
+ cwd: dir,
161
+ stdio: process.env["DEBUG"] ? "inherit" : "pipe"
162
+ });
163
+ if (result.error) throw result.error;
164
+ if (result.status !== 0) throw new Error(`Dependency installation failed with exit code ${result.status ?? "unknown"}`);
165
+ }
166
+ /** Runs an arbitrary command in `dir` via cross-spawn (used for the post-scaffold formatter pass). */
167
+ function runCommand(command, args, dir) {
168
+ const result = spawn.sync(command, args, {
87
169
  cwd: dir,
88
170
  stdio: process.env["DEBUG"] ? "inherit" : "pipe"
89
171
  });
172
+ if (result.error) throw result.error;
173
+ if (result.status !== 0) throw new Error(`Command "${command}" failed with exit code ${result.status ?? "unknown"}`);
174
+ }
175
+
176
+ //#endregion
177
+ //#region src/tools/projectFiles.ts
178
+ const caret = (version) => `^${version}`;
179
+ function sortKeys(record) {
180
+ return Object.fromEntries(Object.entries(record).sort(([a], [b]) => a.localeCompare(b)));
181
+ }
182
+ function json(value) {
183
+ return `${JSON.stringify(value, null, " ")}\n`;
184
+ }
185
+ function buildScripts(ctx) {
186
+ const { packageManager: pm, buildTool } = ctx;
187
+ const start = "node dist/index.js";
188
+ let scripts;
189
+ if (ctx.language === "js") scripts = {
190
+ start: "node src/index.js",
191
+ dev: "node --watch src/index.js"
192
+ };
193
+ else if (buildTool === "tsdown") scripts = {
194
+ build: "tsdown",
195
+ dev: getRunScript(pm, "build", ["--onSuccess", getRunScript(pm, "start")]),
196
+ watch: getRunScript(pm, "build", ["--watch"]),
197
+ "watch:start": getRunScript(pm, "build", [
198
+ "--watch",
199
+ "--onSuccess",
200
+ getRunScript(pm, "start")
201
+ ]),
202
+ start
203
+ };
204
+ else scripts = {
205
+ build: "tsc -b src",
206
+ dev: `${getRunScript(pm, "build")} && ${getRunScript(pm, "start")}`,
207
+ watch: "tsc -b src -w",
208
+ "watch:start": `tsc-watch -b src --onSuccess "${getRunScript(pm, "start")}"`,
209
+ start
210
+ };
211
+ if (ctx.linter === "oxlint") {
212
+ scripts["lint"] = "oxlint src";
213
+ scripts["lint:fix"] = "oxlint --fix src";
214
+ } else if (ctx.linter === "eslint") {
215
+ scripts["lint"] = "eslint src";
216
+ scripts["lint:fix"] = "eslint src --fix";
217
+ }
218
+ if (ctx.formatter === "oxfmt") {
219
+ scripts["format"] = "oxfmt --write src";
220
+ scripts["format:check"] = "oxfmt --check src";
221
+ } else if (ctx.formatter === "prettier") {
222
+ scripts["format"] = "prettier --write src";
223
+ scripts["format:check"] = "prettier --check src";
224
+ }
225
+ return scripts;
226
+ }
227
+ function buildDependencies(ctx) {
228
+ const v = ctx.versions;
229
+ const dependencies = {
230
+ "@discordjs/builders": caret(v["@discordjs/builders"]),
231
+ "@wolfstar/http-framework": caret(v["@wolfstar/http-framework"]),
232
+ "discord-api-types": caret(v["discord-api-types"])
233
+ };
234
+ if (ctx.i18n) dependencies["@wolfstar/http-framework-i18n"] = caret(v["@wolfstar/http-framework-i18n"]);
235
+ return sortKeys(dependencies);
236
+ }
237
+ function buildDevDependencies(ctx) {
238
+ const v = ctx.versions;
239
+ const dev = {};
240
+ if (ctx.language === "ts") {
241
+ dev["@types/node"] = caret(v["@types/node"]);
242
+ switch (ctx.buildTool) {
243
+ case "tsc6":
244
+ dev["typescript"] = caret(v["typescript"]);
245
+ dev["tsc-watch"] = caret(v["tsc-watch"]);
246
+ break;
247
+ case "tsc7":
248
+ dev["typescript"] = v["typescript"];
249
+ dev["tsc-watch"] = caret(v["tsc-watch"]);
250
+ break;
251
+ case "tsdown":
252
+ dev["tsdown"] = caret(v["tsdown"]);
253
+ dev["typescript"] = caret(v["typescript"]);
254
+ break;
255
+ }
256
+ }
257
+ if (ctx.linter === "eslint") {
258
+ dev["eslint"] = caret(v["eslint"]);
259
+ if (ctx.language === "ts") dev["typescript-eslint"] = caret(v["typescript-eslint"]);
260
+ else dev["@eslint/js"] = caret(v["@eslint/js"]);
261
+ } else if (ctx.linter === "oxlint") dev["oxlint"] = caret(v["oxlint"]);
262
+ if (ctx.formatter === "prettier") dev["prettier"] = caret(v["prettier"]);
263
+ else if (ctx.formatter === "oxfmt") dev["oxfmt"] = caret(v["oxfmt"]);
264
+ return sortKeys(dev);
265
+ }
266
+ function packageJson(ctx) {
267
+ const devDependencies = buildDevDependencies(ctx);
268
+ return json({
269
+ name: ctx.name,
270
+ version: "1.0.0",
271
+ description: "A Discord HTTP bot built with `@wolfstar/http-framework`",
272
+ type: "module",
273
+ scripts: buildScripts(ctx),
274
+ dependencies: buildDependencies(ctx),
275
+ ...Object.keys(devDependencies).length > 0 ? { devDependencies } : {},
276
+ engines: { node: ">=20" }
277
+ });
278
+ }
279
+ const sharedCompilerOptions = {
280
+ target: "ES2022",
281
+ module: "Node16",
282
+ moduleResolution: "Node16",
283
+ strict: true,
284
+ esModuleInterop: true,
285
+ skipLibCheck: true,
286
+ declaration: true,
287
+ declarationMap: true,
288
+ sourceMap: true,
289
+ experimentalDecorators: true,
290
+ emitDecoratorMetadata: true
291
+ };
292
+ /** Writes the tsconfig(s). The tsc branches use a composite build so `tsc -b src` resolves `src/tsconfig.json`. */
293
+ function writeTsconfig(targetDir, ctx) {
294
+ if (ctx.language === "js") return;
295
+ if (ctx.buildTool === "tsdown") {
296
+ writeFile(join(targetDir, "tsconfig.json"), json({
297
+ compilerOptions: {
298
+ ...sharedCompilerOptions,
299
+ outDir: "./dist",
300
+ rootDir: "./src"
301
+ },
302
+ include: ["src/**/*.ts"],
303
+ exclude: ["node_modules", "dist"]
304
+ }));
305
+ return;
306
+ }
307
+ writeFile(join(targetDir, "tsconfig.json"), json({
308
+ files: [],
309
+ references: [{ path: "./src" }]
310
+ }));
311
+ writeFile(join(targetDir, "src", "tsconfig.json"), json({
312
+ compilerOptions: {
313
+ ...sharedCompilerOptions,
314
+ rootDir: ".",
315
+ outDir: "../dist",
316
+ composite: true,
317
+ tsBuildInfoFile: "../dist/tsconfig.tsbuildinfo"
318
+ },
319
+ include: ["**/*.ts"]
320
+ }));
321
+ }
322
+ function writeBuildConfig(targetDir, ctx) {
323
+ if (ctx.language === "js" || ctx.buildTool !== "tsdown") return;
324
+ const content = [
325
+ "import { defineConfig } from 'tsdown';",
326
+ "",
327
+ "export default defineConfig({",
328
+ " entry: ['src/**/*.ts'],",
329
+ " format: ['esm'],",
330
+ " target: 'node20',",
331
+ " // Mirror the src/ structure so the framework can load command pieces from dist/commands at runtime.",
332
+ " unbundle: true,",
333
+ " // Emit dist/index.js so the shared `start` script (node dist/index.js) works.",
334
+ " outExtensions: () => ({ js: '.js' }),",
335
+ " clean: true,",
336
+ " sourcemap: true",
337
+ "});",
338
+ ""
339
+ ].join("\n");
340
+ writeFile(join(targetDir, "tsdown.config.ts"), content);
341
+ }
342
+ function writeLinterConfig(targetDir, ctx) {
343
+ if (ctx.linter === "oxlint") writeFile(join(targetDir, ".oxlintrc.json"), json({
344
+ $schema: "./node_modules/oxlint/configuration_schema.json",
345
+ ...ctx.language === "ts" ? { plugins: ["typescript"] } : {},
346
+ categories: {
347
+ correctness: "error",
348
+ suspicious: "warn"
349
+ },
350
+ ignorePatterns: ["dist/**", "node_modules/**"]
351
+ }));
352
+ else if (ctx.linter === "eslint") {
353
+ const content = ctx.language === "ts" ? [
354
+ "import tseslint from 'typescript-eslint';",
355
+ "",
356
+ "export default tseslint.config(",
357
+ " { ignores: ['dist/**'] },",
358
+ " ...tseslint.configs.recommended",
359
+ ");",
360
+ ""
361
+ ].join("\n") : [
362
+ "import js from '@eslint/js';",
363
+ "",
364
+ "export default [",
365
+ " { ignores: ['dist/**'] },",
366
+ " js.configs.recommended",
367
+ "];",
368
+ ""
369
+ ].join("\n");
370
+ writeFile(join(targetDir, "eslint.config.mjs"), content);
371
+ }
372
+ }
373
+ function writeFormatterConfig(targetDir, ctx) {
374
+ if (ctx.formatter === "oxfmt") writeFile(join(targetDir, ".oxfmtrc.json"), json({
375
+ $schema: "./node_modules/oxfmt/configuration_schema.json",
376
+ useTabs: true,
377
+ tabWidth: 4,
378
+ printWidth: 150,
379
+ singleQuote: true,
380
+ trailingComma: "none",
381
+ semi: true,
382
+ endOfLine: "lf"
383
+ }));
384
+ else if (ctx.formatter === "prettier") writeFile(join(targetDir, ".prettierrc.json"), json({
385
+ useTabs: true,
386
+ tabWidth: 4,
387
+ printWidth: 150,
388
+ singleQuote: true,
389
+ trailingComma: "none"
390
+ }));
391
+ }
392
+ /** Generates every config-style file in code so the output is always valid, formatted JSON/TS. */
393
+ function writeProjectFiles(targetDir, ctx) {
394
+ writeFile(join(targetDir, "package.json"), packageJson(ctx));
395
+ writeTsconfig(targetDir, ctx);
396
+ writeBuildConfig(targetDir, ctx);
397
+ writeLinterConfig(targetDir, ctx);
398
+ writeFormatterConfig(targetDir, ctx);
90
399
  }
91
400
 
92
401
  //#endregion
93
402
  //#region src/tools/templateProcessor.ts
94
- Handlebars.registerHelper("eq", (a, b) => a === b);
95
- Handlebars.registerHelper("or", (...args) => args.slice(0, -1).some(Boolean));
96
- Handlebars.registerHelper("and", (...args) => args.slice(0, -1).every(Boolean));
97
403
  const templateDir = join(fileURLToPath(import.meta.url), "../..", "template");
98
404
  function walkDir(dir) {
99
405
  const entries = readdirSync(dir);
@@ -109,6 +415,8 @@ function processTemplate(outputDir, context) {
109
415
  const allFiles = walkDir(templateDir);
110
416
  for (const absoluteSource of allFiles) {
111
417
  const relativePath = relative(templateDir, absoluteSource);
418
+ if (context.language === "js" && relativePath.endsWith(".ts.hbs")) continue;
419
+ if (context.language === "ts" && relativePath.endsWith(".js.hbs")) continue;
112
420
  const rawContent = readFileSync(absoluteSource, "utf-8");
113
421
  const isHandlebars = relativePath.endsWith(".hbs");
114
422
  writeFile(join(outputDir, isHandlebars ? relativePath.slice(0, -4) : relativePath), isHandlebars ? Handlebars.compile(rawContent)(context) : rawContent);
@@ -128,27 +436,46 @@ function printHelp() {
128
436
  Usage: create-http-framework [project-name] [options]
129
437
 
130
438
  Options:
131
- --overwrite Overwrite target directory if it already exists
132
- --yes, -y Skip prompts and use defaults (port 3000, no i18n, auto-install)
133
- --interactive, -i Force interactive prompts even when an AI agent is detected
134
- --help, -h Print this message and exit
439
+ --overwrite Overwrite target directory if it already exists
440
+ --no-interactive Skip all prompts and use defaults / flags
441
+ --interactive, -i Force interactive prompts even when an AI agent is detected
442
+ --package-manager <pm> npm | yarn | pnpm | bun (defaults to the detected one)
443
+ --language <lang> ts | js (default: ts)
444
+ --build <tool> tsc6 | tsc7 | tsdown — TypeScript only (default: tsdown)
445
+ --lint <linter> none | eslint | oxlint (default: oxlint)
446
+ --format <formatter> none | prettier | oxfmt (default: oxfmt)
447
+ --port <number> HTTP port (default: 3000)
448
+ --i18n / --no-i18n Toggle @wolfstar/http-framework-i18n (default: off)
449
+ --install / --no-install Toggle dependency installation (default: on)
450
+ --help, -h Print this message and exit
135
451
 
136
452
  `);
137
453
  process.exit(0);
138
454
  }
455
+ function parseEnum(value, allowed, label) {
456
+ if (value === void 0) return void 0;
457
+ if (!allowed.includes(value)) {
458
+ cancel(`Invalid ${label} "${value}". Expected one of: ${allowed.join(", ")}.`);
459
+ process.exit(1);
460
+ }
461
+ return value;
462
+ }
139
463
  async function main() {
140
464
  const argv = mri(process.argv.slice(2), {
141
- boolean: [
142
- "overwrite",
143
- "yes",
144
- "help",
145
- "interactive"
465
+ boolean: ["overwrite", "help"],
466
+ string: [
467
+ "package-manager",
468
+ "language",
469
+ "build",
470
+ "lint",
471
+ "format",
472
+ "port"
146
473
  ],
147
474
  alias: {
148
- y: "yes",
149
475
  h: "help",
150
476
  i: "interactive"
151
- }
477
+ },
478
+ default: { install: true }
152
479
  });
153
480
  if (argv["help"]) {
154
481
  printHelp();
@@ -156,16 +483,23 @@ async function main() {
156
483
  }
157
484
  const argProjectName = argv._[0];
158
485
  const flagOverwrite = argv["overwrite"];
159
- const flagYes = argv["yes"];
160
486
  const flagInteractive = argv["interactive"];
487
+ const cliPackageManager = parseEnum(argv["package-manager"], PACKAGE_MANAGERS, "--package-manager");
488
+ const cliLanguage = parseEnum(argv["language"], LANGUAGES, "--language");
489
+ const cliBuild = parseEnum(argv["build"], BUILD_TOOLS, "--build");
490
+ const cliLint = parseEnum(argv["lint"], LINTERS, "--lint");
491
+ const cliFormat = parseEnum(argv["format"], FORMATTERS, "--format");
492
+ const cliPort = argv["port"];
493
+ const cliI18n = argv["i18n"];
494
+ const cliInstall = argv["install"];
161
495
  const { isAgent, agent } = await determineAgent();
162
- const agentMode = isAgent && !flagInteractive;
163
- const effectiveYes = flagYes || agentMode;
496
+ const agentMode = isAgent && flagInteractive !== true;
497
+ const nonInteractive = flagInteractive === false || agentMode;
164
498
  intro("Welcome to the WolfStar HTTP Framework!");
165
- if (agentMode && !flagYes) log.info(`AI agent detected (${agent.name}) — running in non-interactive mode`);
166
- const packageManager = await detectPackageManager();
499
+ if (agentMode && flagInteractive !== false) log.info(`AI agent detected (${agent.name}) — running in non-interactive mode`);
500
+ const detectedPackageManager = await detectPackageManager();
167
501
  let projectName;
168
- if (effectiveYes) {
502
+ if (nonInteractive) {
169
503
  if (!argProjectName) {
170
504
  cancel("A project name argument is required in non-interactive mode.");
171
505
  process.exit(1);
@@ -193,9 +527,26 @@ async function main() {
193
527
  }
194
528
  projectName = nameResult;
195
529
  }
530
+ let packageManager;
531
+ if (nonInteractive) packageManager = cliPackageManager ?? detectedPackageManager;
532
+ else {
533
+ const pmResult = await select({
534
+ message: "Which package manager would you like to use?",
535
+ options: PACKAGE_MANAGERS.map((pm) => ({
536
+ value: pm,
537
+ label: pm
538
+ })),
539
+ initialValue: PACKAGE_MANAGERS.includes(detectedPackageManager) ? detectedPackageManager : "npm"
540
+ });
541
+ if (isCancel(pmResult)) {
542
+ cancel("Operation cancelled.");
543
+ process.exit(0);
544
+ }
545
+ packageManager = pmResult;
546
+ }
196
547
  const targetDir = resolve(projectName);
197
548
  if (directoryExists(targetDir) && !isEmpty(targetDir)) if (flagOverwrite) emptyDir(targetDir);
198
- else if (effectiveYes) {
549
+ else if (nonInteractive) {
199
550
  cancel(`"${projectName}" already exists. Use --overwrite to overwrite it.`);
200
551
  process.exit(1);
201
552
  } else {
@@ -216,8 +567,13 @@ async function main() {
216
567
  emptyDir(targetDir);
217
568
  }
218
569
  let port;
219
- if (effectiveYes) port = 3e3;
220
- else {
570
+ if (nonInteractive) {
571
+ port = cliPort === void 0 ? 3e3 : Number(cliPort);
572
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
573
+ cancel("Provide a valid --port between 1 and 65535.");
574
+ process.exit(1);
575
+ }
576
+ } else {
221
577
  const portResult = await text({
222
578
  message: "Which port should the HTTP server listen on?",
223
579
  placeholder: "3000",
@@ -233,8 +589,110 @@ async function main() {
233
589
  }
234
590
  port = Number(portResult);
235
591
  }
592
+ let language;
593
+ if (nonInteractive) language = cliLanguage ?? "ts";
594
+ else {
595
+ const languageResult = await select({
596
+ message: "Which language would you like to use?",
597
+ options: [{
598
+ value: "ts",
599
+ label: "TypeScript"
600
+ }, {
601
+ value: "js",
602
+ label: "JavaScript"
603
+ }],
604
+ initialValue: "ts"
605
+ });
606
+ if (isCancel(languageResult)) {
607
+ cancel("Operation cancelled.");
608
+ process.exit(0);
609
+ }
610
+ language = languageResult;
611
+ }
612
+ let buildTool = "tsdown";
613
+ if (cliBuild !== void 0 && language === "js") log.warn("--build only applies to TypeScript projects and will be ignored.");
614
+ if (language === "ts") if (nonInteractive) buildTool = cliBuild ?? "tsdown";
615
+ else {
616
+ const buildResult = await select({
617
+ message: "Which build tool would you like to use?",
618
+ options: [
619
+ {
620
+ value: "tsdown",
621
+ label: "tsdown (bundler)"
622
+ },
623
+ {
624
+ value: "tsc6",
625
+ label: "TypeScript 6.0 (tsc)"
626
+ },
627
+ {
628
+ value: "tsc7",
629
+ label: "TypeScript 7.0 rc (tsc)"
630
+ }
631
+ ],
632
+ initialValue: "tsdown"
633
+ });
634
+ if (isCancel(buildResult)) {
635
+ cancel("Operation cancelled.");
636
+ process.exit(0);
637
+ }
638
+ buildTool = buildResult;
639
+ }
640
+ let linter;
641
+ if (nonInteractive) linter = cliLint ?? "oxlint";
642
+ else {
643
+ const lintResult = await select({
644
+ message: "Which linter would you like to use?",
645
+ options: [
646
+ {
647
+ value: "oxlint",
648
+ label: "oxlint"
649
+ },
650
+ {
651
+ value: "eslint",
652
+ label: "ESLint"
653
+ },
654
+ {
655
+ value: "none",
656
+ label: "None"
657
+ }
658
+ ],
659
+ initialValue: "oxlint"
660
+ });
661
+ if (isCancel(lintResult)) {
662
+ cancel("Operation cancelled.");
663
+ process.exit(0);
664
+ }
665
+ linter = lintResult;
666
+ }
667
+ let formatter;
668
+ if (nonInteractive) formatter = cliFormat ?? "oxfmt";
669
+ else {
670
+ const formatResult = await select({
671
+ message: "Which formatter would you like to use?",
672
+ options: [
673
+ {
674
+ value: "oxfmt",
675
+ label: "oxfmt"
676
+ },
677
+ {
678
+ value: "prettier",
679
+ label: "Prettier"
680
+ },
681
+ {
682
+ value: "none",
683
+ label: "None"
684
+ }
685
+ ],
686
+ initialValue: "oxfmt"
687
+ });
688
+ if (isCancel(formatResult)) {
689
+ cancel("Operation cancelled.");
690
+ process.exit(0);
691
+ }
692
+ formatter = formatResult;
693
+ }
236
694
  let wantsI18n;
237
- if (effectiveYes) wantsI18n = false;
695
+ if (nonInteractive) wantsI18n = cliI18n ?? false;
238
696
  else {
239
697
  const i18nResult = await confirm({
240
698
  message: "Would you like to add i18n support? (@wolfstar/http-framework-i18n)",
@@ -247,7 +705,7 @@ async function main() {
247
705
  wantsI18n = Boolean(i18nResult);
248
706
  }
249
707
  let wantsInstall;
250
- if (effectiveYes) wantsInstall = true;
708
+ if (nonInteractive) wantsInstall = cliInstall;
251
709
  else {
252
710
  const installResult = await confirm({
253
711
  message: `Would you like to automatically install dependencies with ${packageManager}?`,
@@ -261,24 +719,58 @@ async function main() {
261
719
  }
262
720
  const s = spinner();
263
721
  s.start("Fetching latest dependency versions...");
264
- const versions = await fetchDependencyVersions();
722
+ const versions = await fetchDependencyVersions({
723
+ i18n: wantsI18n,
724
+ language,
725
+ buildTool,
726
+ linter,
727
+ formatter
728
+ });
265
729
  s.stop("Versions fetched.");
266
730
  s.start("Generating project files...");
267
731
  processTemplate(targetDir, {
732
+ name: projectName,
733
+ port,
734
+ language
735
+ });
736
+ writeProjectFiles(targetDir, {
268
737
  name: projectName,
269
738
  port,
270
739
  i18n: wantsI18n,
271
740
  packageManager,
272
- todaysDate: (/* @__PURE__ */ new Date()).toISOString().split("T")[0],
741
+ language,
742
+ buildTool,
743
+ linter,
744
+ formatter,
273
745
  versions
274
746
  });
275
747
  s.stop("Project files generated.");
748
+ if (formatter !== "none") try {
749
+ s.start("Formatting project files...");
750
+ if (formatter === "oxfmt") runCommand("npx", [
751
+ "--yes",
752
+ "oxfmt",
753
+ "--write",
754
+ "."
755
+ ], targetDir);
756
+ else runCommand("npx", [
757
+ "--yes",
758
+ "prettier",
759
+ "--write",
760
+ ".",
761
+ "--log-level",
762
+ "warn"
763
+ ], targetDir);
764
+ s.stop("Project files formatted.");
765
+ } catch {
766
+ s.stop("Skipped formatting (formatter not available yet — it will run after install).");
767
+ }
276
768
  if (wantsInstall) {
277
769
  s.start(`Installing dependencies with ${packageManager}...`);
278
770
  await installDependencies(packageManager, targetDir);
279
771
  s.stop("Dependencies installed.");
280
772
  }
281
- outro(`Done! To get started:\n\n cd ${projectName}\n${wantsInstall ? "" : ` ${packageManager} install\n`} ${packageManager} run dev`);
773
+ outro(`Done! To get started:\n\n cd ${projectName}\n${wantsInstall ? "" : ` ${getInstallScript(packageManager)}\n`} ${getRunScript(packageManager, "dev")}`);
282
774
  }
283
775
  main().catch((error) => {
284
776
  cancel(error instanceof Error ? error.message : String(error));
package/package.json CHANGED
@@ -1,58 +1,59 @@
1
1
  {
2
- "name": "@wolfstar/create-http-framework",
3
- "version": "2.0.1",
4
- "description": "Create a new WolfStar HTTP Framework bot project",
5
- "keywords": [
6
- "cli",
7
- "create",
8
- "discord",
9
- "http",
10
- "scaffold",
11
- "wolfstar"
12
- ],
13
- "homepage": "https://github.com/wolfstar-project/stars-components/tree/main/packages/create-http-framework",
14
- "bugs": {
15
- "url": "https://github.com/wolfstar-project/stars-components/issues"
16
- },
17
- "license": "Apache-2.0",
18
- "author": "@wolfstar",
19
- "repository": {
20
- "type": "git",
21
- "url": "git+https://github.com/wolfstar-project/stars-components.git",
22
- "directory": "packages/create-http-framework"
23
- },
24
- "bin": {
25
- "create-http-framework": "./dist/index.js"
26
- },
27
- "files": [
28
- "dist/",
29
- "template/"
30
- ],
31
- "type": "module",
32
- "publishConfig": {
33
- "access": "public"
34
- },
35
- "scripts": {
36
- "build": "tsdown --config-loader unrun",
37
- "typecheck": "tsc -p ../../tsconfig.json",
38
- "lint": "oxlint src --fix",
39
- "prepack": "pnpm run build"
40
- },
41
- "dependencies": {
42
- "@clack/prompts": "^1.6.0",
43
- "@vercel/detect-agent": "^1.2.3",
44
- "handlebars": "^4.7.9",
45
- "mri": "^1.2.0",
46
- "package-manager-detector": "^1.6.0"
47
- },
48
- "devDependencies": {
49
- "@types/handlebars": "^4.1.0",
50
- "@types/mri": "^1.2.0",
51
- "@types/node": "22.15.21",
52
- "tsdown": "^0.22.3",
53
- "typescript": "~5.8.3"
54
- },
55
- "engines": {
56
- "node": ">=20"
57
- }
58
- }
2
+ "name": "@wolfstar/create-http-framework",
3
+ "version": "2.1.0",
4
+ "description": "Create a new WolfStar HTTP Framework bot project",
5
+ "keywords": [
6
+ "cli",
7
+ "create",
8
+ "discord",
9
+ "http",
10
+ "scaffold",
11
+ "wolfstar"
12
+ ],
13
+ "homepage": "https://github.com/wolfstar-project/stars-components/tree/main/packages/create-http-framework",
14
+ "bugs": {
15
+ "url": "https://github.com/wolfstar-project/stars-components/issues"
16
+ },
17
+ "license": "Apache-2.0",
18
+ "author": "@wolfstar",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/wolfstar-project/stars-components.git",
22
+ "directory": "packages/create-http-framework"
23
+ },
24
+ "bin": {
25
+ "create-http-framework": "./dist/index.js"
26
+ },
27
+ "files": [
28
+ "dist/",
29
+ "template/"
30
+ ],
31
+ "type": "module",
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "dependencies": {
36
+ "@clack/prompts": "^1.7.0",
37
+ "@vercel/detect-agent": "^1.2.3",
38
+ "cross-spawn": "^7.0.6",
39
+ "handlebars": "^4.7.9",
40
+ "mri": "^1.2.0",
41
+ "package-manager-detector": "^1.7.0"
42
+ },
43
+ "devDependencies": {
44
+ "@types/cross-spawn": "^6.0.6",
45
+ "@types/handlebars": "^4.1.0",
46
+ "@types/mri": "^1.2.0",
47
+ "@types/node": "22.15.21",
48
+ "tsdown": "^0.22.3",
49
+ "typescript": "~5.8.3"
50
+ },
51
+ "engines": {
52
+ "node": ">=20"
53
+ },
54
+ "scripts": {
55
+ "build": "tsdown --config-loader unrun",
56
+ "typecheck": "tsc -p ../../tsconfig.json",
57
+ "lint": "oxlint src --fix"
58
+ }
59
+ }
package/template/.env.hbs CHANGED
@@ -1 +1,4 @@
1
- DISCORD_TOKEN=your_bot_token_here DISCORD_PUBLIC_KEY=your_public_key_here DISCORD_CLIENT_ID=your_client_id_here HTTP_POST_PATH=/
1
+ DISCORD_TOKEN=your_bot_token_here
2
+ DISCORD_PUBLIC_KEY=your_public_key_here
3
+ DISCORD_CLIENT_ID=your_client_id_here
4
+ HTTP_POST_PATH=/
@@ -1 +1,4 @@
1
- node_modules/ dist/ .env *.js.map
1
+ node_modules/
2
+ dist/
3
+ .env
4
+ *.js.map
@@ -0,0 +1,12 @@
1
+ import { Command } from '@wolfstar/http-framework';
2
+ import { MessageFlags } from 'discord-api-types/v10';
3
+
4
+ export class PingCommand extends Command {
5
+ chatInputRun(interaction) {
6
+ return interaction.reply({ content: 'Pong!', flags: MessageFlags.Ephemeral });
7
+ }
8
+
9
+ static builder = (builder) => builder
10
+ .setName('ping')
11
+ .setDescription('Replies with pong!')
12
+ }
@@ -1,5 +1,13 @@
1
- import { Command } from '@wolfstar/http-framework'; import { SlashCommandBuilder } from '@discordjs/builders'; import { MessageFlags } from
2
- 'discord-api-types/v10'; export class PingCommand extends Command { public constructor(context: Command.LoaderContext) { super(context, { name:
3
- 'ping', description: 'Replies with pong!' }); } public override chatInputRun(interaction: Command.ChatInputInteraction) { return interaction.reply({
4
- content: 'Pong!', flags: MessageFlags.Ephemeral }); } public static readonly builder = new SlashCommandBuilder() .setName('ping')
5
- .setDescription('Replies with pong!'); }
1
+ import { Command, RegisterCommand } from '@wolfstar/http-framework';
2
+ import { MessageFlags } from 'discord-api-types/v10';
3
+
4
+ @RegisterCommand((builder) =>
5
+ builder //
6
+ .setName('ping')
7
+ .setDescription('Replies with pong!')
8
+ )
9
+ export class PingCommand extends Command {
10
+ public override chatInputRun(interaction: Command.ChatInputInteraction) {
11
+ return interaction.reply({ content: 'Pong!', flags: MessageFlags.Ephemeral });
12
+ }
13
+ }
@@ -0,0 +1,10 @@
1
+ import { dirname, join } from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { Client } from '@wolfstar/http-framework';
4
+
5
+ const client = new Client();
6
+
7
+ await client.load({ baseUserDirectory: join(dirname(fileURLToPath(import.meta.url)), 'commands') });
8
+ await client.listen({ port: {{port}} });
9
+
10
+ console.log('Bot is running on port {{port}}');
@@ -1,5 +1,10 @@
1
- import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { Client } from '@wolfstar/http-framework'; const client =
2
- new Client(); await client.load({ baseUserDirectory: join(dirname(fileURLToPath(import.meta.url)), 'commands') }); await client.listen({ port:
3
- {{port}}
4
- }); console.log('Bot is running on port
5
- {{port}}');
1
+ import { dirname, join } from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { Client } from '@wolfstar/http-framework';
4
+
5
+ const client = new Client();
6
+
7
+ await client.load({ baseUserDirectory: join(dirname(fileURLToPath(import.meta.url)), 'commands') });
8
+ await client.listen({ port: {{port}} });
9
+
10
+ console.log('Bot is running on port {{port}}');
@@ -1,7 +0,0 @@
1
- { "name": "{{name}}", "version": "1.0.0", "description": "A Discord HTTP bot built with `@wolfstar/http-framework`", "author": "`@wolfstar`",
2
- "repository": { "url": "https://github.com/yourusername/your-repo.git" }, "bugs": { "url": "https://github.com/yourusername/your-repo/issues" },
3
- "homepage": "https://github.com/yourusername/your-repo#readme", "keywords": ["discord", "bot", "http", "wolfstar"], "type": "module", "scripts": {
4
- "build": "tsc", "dev": "node --watch --loader ts-node/esm src/index.ts", "start": "node dist/index.js" }, "dependencies": { "@discordjs/builders": "^{{versions.discordJsBuilders}}",
5
- "@wolfstar/http-framework": "^{{versions.httpFramework}}"{{#if i18n}}, "@wolfstar/http-framework-i18n": "^{{versions.httpFrameworkI18n}}"{{/if}},
6
- "discord-api-types": "^{{versions.discordApiTypes}}" }, "devDependencies": { "@types/node": "^{{versions.typesNode}}", "ts-node": "^{{versions.tsNode}}",
7
- "typescript": "^{{versions.typescript}}" }, "engines": { "node": ">=20" } }
@@ -1,3 +0,0 @@
1
- { "compilerOptions": { "target": "ES2022", "module": "Node16", "moduleResolution": "Node16", "outDir": "./dist", "rootDir": "./src", "strict": true,
2
- "esModuleInterop": true, "skipLibCheck": true, "declaration": true, "declarationMap": true, "sourceMap": true, "experimentalDecorators": true,
3
- "emitDecoratorMetadata": true }, "include": ["src/**/*.ts"], "exclude": ["node_modules", "dist"] }