@wolfstar/cli 2.3.1 → 2.4.0-next-20261006112342

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.
Files changed (34) hide show
  1. package/README.md +43 -1
  2. package/dist/{bridge-BegCt_n2.js → bridge-B5BP6eXj.js} +2 -235
  3. package/dist/bridge-B5BP6eXj.js.map +1 -0
  4. package/dist/cli.js +1 -1
  5. package/dist/codegen-CF6o8v6A.js +262 -0
  6. package/dist/codegen-CF6o8v6A.js.map +1 -0
  7. package/dist/commands-C_B9ENxc.js +15 -0
  8. package/dist/{commands-CSB-pjgs.js.map → commands-C_B9ENxc.js.map} +1 -1
  9. package/dist/commands-DY-hEtQy.js +3 -0
  10. package/dist/{commands-Bh0K9iWX.js → commands-nGd6jExv.js} +4 -92
  11. package/dist/commands-nGd6jExv.js.map +1 -0
  12. package/dist/{completions-DMPlZ0S1.js → completions-CBQHiSnE.js} +2 -2
  13. package/dist/{completions-DMPlZ0S1.js.map → completions-CBQHiSnE.js.map} +1 -1
  14. package/dist/{dev-Owu3e3AO.js → dev-D9MAtiCk.js} +3 -2
  15. package/dist/{dev-Owu3e3AO.js.map → dev-D9MAtiCk.js.map} +1 -1
  16. package/dist/{doctor-DEtAAknK.js → doctor-DYAdmZZq.js} +3 -2
  17. package/dist/{doctor-DEtAAknK.js.map → doctor-DYAdmZZq.js.map} +1 -1
  18. package/dist/index.js +1 -1
  19. package/dist/{info-CKJVMWIT.js → info-CTUGxaHN.js} +2 -2
  20. package/dist/info-CTUGxaHN.js.map +1 -0
  21. package/dist/local-commands-DG_a4XE9.js +95 -0
  22. package/dist/local-commands-DG_a4XE9.js.map +1 -0
  23. package/dist/{run-CHqwvZXf.js → run-CjI3xBby.js} +2 -2
  24. package/dist/{run-CHqwvZXf.js.map → run-CjI3xBby.js.map} +1 -1
  25. package/dist/tunnel-C3bk4dq_.js +236 -0
  26. package/dist/tunnel-C3bk4dq_.js.map +1 -0
  27. package/package.json +5 -5
  28. package/dist/bridge-BegCt_n2.js.map +0 -1
  29. package/dist/codegen-aJSyPz-J.js +0 -124
  30. package/dist/codegen-aJSyPz-J.js.map +0 -1
  31. package/dist/commands-Bh0K9iWX.js.map +0 -1
  32. package/dist/commands-BlDTDvFO.js +0 -3
  33. package/dist/commands-CSB-pjgs.js +0 -15
  34. package/dist/info-CKJVMWIT.js.map +0 -1
@@ -0,0 +1,95 @@
1
+ import { t as cliDiagnostics } from "./diagnostics-BysbNnPD.js";
2
+ import { c as moduleImportArgs, s as envImportArgs } from "./hooks-Cy6F2bhH.js";
3
+ import { i as bridgeImportArgs, o as parseBridgeMessage, r as DUMP_ENV, t as BRIDGE_FRAMEWORK_VERSION } from "./bridge-B5BP6eXj.js";
4
+ import { existsSync } from "node:fs";
5
+ import { displayPath } from "@wolfstar/schema";
6
+ import { spawn } from "node:child_process";
7
+
8
+ //#region src/utils/local-commands.ts
9
+ /**
10
+ * The application commands the project defines, as the bot itself would register them.
11
+ *
12
+ * Commands are declared with builders and decorators that only exist once the bot's modules ran, so nothing short of
13
+ * running them knows the answer. This starts the built bot with the dev bridge in its "dump" mode: it loads its
14
+ * pieces, reports its registry over IPC and exits before it listens or talks to Discord.
15
+ *
16
+ * It is a plain start of the bot, not a `stars dev` session: `STARS_DEV` is not set, so commands a project only
17
+ * registers while developing are not part of what `stars commands deploy` deploys.
18
+ */
19
+ async function readLocalCommands(config, options = {}) {
20
+ if (!existsSync(config.build.output)) throw cliDiagnostics.LOCAL_COMMANDS_UNAVAILABLE({
21
+ reason: `${displayPath(config.root, config.build.output)} does not exist`,
22
+ fix: "Run `stars build` first: the commands are read from the built bot."
23
+ });
24
+ const bridge = bridgeImportArgs(config);
25
+ if (bridge.length === 0) throw cliDiagnostics.LOCAL_COMMANDS_UNAVAILABLE({
26
+ reason: `@wolfstar/http-framework ${BRIDGE_FRAMEWORK_VERSION} or later is not installed in ${config.root}`,
27
+ fix: `Install @wolfstar/http-framework@^${BRIDGE_FRAMEWORK_VERSION} in the project.`
28
+ });
29
+ const child = spawn(process.execPath, [
30
+ ...envImportArgs(config),
31
+ ...moduleImportArgs(config),
32
+ ...bridge,
33
+ ...config.dev.nodeArgs,
34
+ config.build.output,
35
+ ...config.dev.args
36
+ ], {
37
+ cwd: config.root,
38
+ env: {
39
+ ...process.env,
40
+ ...config.dev.env,
41
+ NODE_ENV: process.env.NODE_ENV ?? "development",
42
+ [DUMP_ENV]: "1"
43
+ },
44
+ stdio: [
45
+ "ignore",
46
+ "ignore",
47
+ "pipe",
48
+ "ipc"
49
+ ],
50
+ windowsHide: true
51
+ });
52
+ return new Promise((resolve, reject) => {
53
+ let stderr = "";
54
+ let settled = false;
55
+ const finish = (action) => {
56
+ if (settled) return;
57
+ settled = true;
58
+ clearTimeout(timer);
59
+ action();
60
+ };
61
+ const unavailable = (reason) => cliDiagnostics.LOCAL_COMMANDS_UNAVAILABLE({
62
+ reason,
63
+ fix: "Check that the bot starts with `stars dev`: it has to construct its `Client` and call `client.load()`."
64
+ });
65
+ const timer = setTimeout(() => {
66
+ child.kill("SIGKILL");
67
+ finish(() => reject(unavailable("the bot did not load its commands in time")));
68
+ }, options.timeout ?? 3e4);
69
+ child.stderr?.on("data", (chunk) => stderr = `${stderr}${chunk.toString()}`.slice(-2e3));
70
+ let snapshot = null;
71
+ child.on("message", (message) => {
72
+ const parsed = parseBridgeMessage(message);
73
+ if (parsed?.type !== "commands" || snapshot !== null) return;
74
+ snapshot = {
75
+ global: parsed.global,
76
+ guilds: parsed.guilds
77
+ };
78
+ setTimeout(() => child.kill("SIGKILL"), 2e3).unref();
79
+ });
80
+ child.once("error", (error) => finish(() => reject(unavailable(error.message))));
81
+ child.once("exit", (code) => {
82
+ if (snapshot !== null) {
83
+ const commands = snapshot;
84
+ finish(() => resolve(commands));
85
+ return;
86
+ }
87
+ const detail = stderr.trim().split("\n").at(-1);
88
+ finish(() => reject(unavailable(`the bot exited with code ${code} before loading its commands${detail ? ` (${detail})` : ""}`)));
89
+ });
90
+ });
91
+ }
92
+
93
+ //#endregion
94
+ export { readLocalCommands as t };
95
+ //# sourceMappingURL=local-commands-DG_a4XE9.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"local-commands-DG_a4XE9.js","names":[],"sources":["../src/utils/local-commands.ts"],"sourcesContent":["import type { ResolvedStarsConfig } from '@wolfstar/schema';\nimport { displayPath } from '@wolfstar/schema';\nimport { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { BRIDGE_FRAMEWORK_VERSION, bridgeImportArgs, DUMP_ENV, parseBridgeMessage, type CommandSnapshot } from '../dev/bridge.js';\nimport { cliDiagnostics } from './diagnostics.js';\nimport { envImportArgs, moduleImportArgs } from './env-import.js';\n\nexport interface ReadLocalCommandsOptions {\n\t/** Milliseconds the bot gets to load its pieces. */\n\ttimeout?: number;\n}\n\n/**\n * The application commands the project defines, as the bot itself would register them.\n *\n * Commands are declared with builders and decorators that only exist once the bot's modules ran, so nothing short of\n * running them knows the answer. This starts the built bot with the dev bridge in its \"dump\" mode: it loads its\n * pieces, reports its registry over IPC and exits before it listens or talks to Discord.\n *\n * It is a plain start of the bot, not a `stars dev` session: `STARS_DEV` is not set, so commands a project only\n * registers while developing are not part of what `stars commands deploy` deploys.\n */\nexport async function readLocalCommands(config: ResolvedStarsConfig, options: ReadLocalCommandsOptions = {}): Promise<CommandSnapshot> {\n\tif (!existsSync(config.build.output)) {\n\t\tthrow cliDiagnostics.LOCAL_COMMANDS_UNAVAILABLE({\n\t\t\treason: `${displayPath(config.root, config.build.output)} does not exist`,\n\t\t\tfix: 'Run `stars build` first: the commands are read from the built bot.'\n\t\t});\n\t}\n\n\tconst bridge = bridgeImportArgs(config);\n\tif (bridge.length === 0) {\n\t\tthrow cliDiagnostics.LOCAL_COMMANDS_UNAVAILABLE({\n\t\t\treason: `@wolfstar/http-framework ${BRIDGE_FRAMEWORK_VERSION} or later is not installed in ${config.root}`,\n\t\t\tfix: `Install @wolfstar/http-framework@^${BRIDGE_FRAMEWORK_VERSION} in the project.`\n\t\t});\n\t}\n\n\tconst child = spawn(\n\t\tprocess.execPath,\n\t\t[...envImportArgs(config), ...moduleImportArgs(config), ...bridge, ...config.dev.nodeArgs, config.build.output, ...config.dev.args],\n\t\t{\n\t\t\tcwd: config.root,\n\t\t\t// The environment the commands are read under is the caller's: `NODE_ENV=production stars commands deploy`\n\t\t\t// deploys what a production start registers. Unset, it is development, like the project's env files.\n\t\t\tenv: { ...process.env, ...config.dev.env, NODE_ENV: process.env.NODE_ENV ?? 'development', [DUMP_ENV]: '1' },\n\t\t\tstdio: ['ignore', 'ignore', 'pipe', 'ipc'],\n\t\t\twindowsHide: true\n\t\t}\n\t);\n\n\treturn new Promise<CommandSnapshot>((resolve, reject) => {\n\t\tlet stderr = '';\n\t\tlet settled = false;\n\t\tconst finish = (action: () => void) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tclearTimeout(timer);\n\t\t\taction();\n\t\t};\n\t\tconst unavailable = (reason: string) =>\n\t\t\tcliDiagnostics.LOCAL_COMMANDS_UNAVAILABLE({\n\t\t\t\treason,\n\t\t\t\tfix: 'Check that the bot starts with `stars dev`: it has to construct its `Client` and call `client.load()`.'\n\t\t\t});\n\n\t\tconst timer = setTimeout(() => {\n\t\t\tchild.kill('SIGKILL');\n\t\t\tfinish(() => reject(unavailable('the bot did not load its commands in time')));\n\t\t}, options.timeout ?? 30_000);\n\n\t\tchild.stderr?.on('data', (chunk: Buffer) => (stderr = `${stderr}${chunk.toString()}`.slice(-2000)));\n\t\tlet snapshot: CommandSnapshot | null = null;\n\t\tchild.on('message', (message) => {\n\t\t\tconst parsed = parseBridgeMessage(message);\n\t\t\tif (parsed?.type !== 'commands' || snapshot !== null) return;\n\t\t\tsnapshot = { global: parsed.global, guilds: parsed.guilds };\n\t\t\t// The bot exits on its own once the message is flushed. The answer waits for that: until then the process\n\t\t\t// still holds the project directory (its working directory), which Windows refuses to let go of.\n\t\t\tsetTimeout(() => child.kill('SIGKILL'), 2000).unref();\n\t\t});\n\t\tchild.once('error', (error) => finish(() => reject(unavailable(error.message))));\n\t\tchild.once('exit', (code) => {\n\t\t\tif (snapshot !== null) {\n\t\t\t\tconst commands = snapshot;\n\t\t\t\tfinish(() => resolve(commands));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst detail = stderr.trim().split('\\n').at(-1);\n\t\t\tfinish(() => reject(unavailable(`the bot exited with code ${code} before loading its commands${detail ? ` (${detail})` : ''}`)));\n\t\t});\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuBA,eAAsB,kBAAkB,QAA6B,UAAoC,CAAC,GAA6B;CACtI,IAAI,CAAC,WAAW,OAAO,MAAM,MAAM,GAClC,MAAM,eAAe,2BAA2B;EAC/C,QAAQ,GAAG,YAAY,OAAO,MAAM,OAAO,MAAM,MAAM,EAAE;EACzD,KAAK;CACN,CAAC;CAGF,MAAM,SAAS,iBAAiB,MAAM;CACtC,IAAI,OAAO,WAAW,GACrB,MAAM,eAAe,2BAA2B;EAC/C,QAAQ,4BAA4B,yBAAyB,gCAAgC,OAAO;EACpG,KAAK,qCAAqC,yBAAyB;CACpE,CAAC;CAGF,MAAM,QAAQ,MACb,QAAQ,UACR;EAAC,GAAG,cAAc,MAAM;EAAG,GAAG,iBAAiB,MAAM;EAAG,GAAG;EAAQ,GAAG,OAAO,IAAI;EAAU,OAAO,MAAM;EAAQ,GAAG,OAAO,IAAI;CAAI,GAClI;EACC,KAAK,OAAO;EAGZ,KAAK;GAAE,GAAG,QAAQ;GAAK,GAAG,OAAO,IAAI;GAAK,UAAU,QAAQ,IAAI,YAAY;IAAgB,WAAW;EAAI;EAC3G,OAAO;GAAC;GAAU;GAAU;GAAQ;EAAK;EACzC,aAAa;CACd,CACD;CAEA,OAAO,IAAI,SAA0B,SAAS,WAAW;EACxD,IAAI,SAAS;EACb,IAAI,UAAU;EACd,MAAM,UAAU,WAAuB;GACtC,IAAI,SAAS;GACb,UAAU;GACV,aAAa,KAAK;GAClB,OAAO;EACR;EACA,MAAM,eAAe,WACpB,eAAe,2BAA2B;GACzC;GACA,KAAK;EACN,CAAC;EAEF,MAAM,QAAQ,iBAAiB;GAC9B,MAAM,KAAK,SAAS;GACpB,aAAa,OAAO,YAAY,2CAA2C,CAAC,CAAC;EAC9E,GAAG,QAAQ,WAAW,GAAM;EAE5B,MAAM,QAAQ,GAAG,SAAS,UAAmB,SAAS,GAAG,SAAS,MAAM,SAAS,IAAI,MAAM,IAAK,CAAE;EAClG,IAAI,WAAmC;EACvC,MAAM,GAAG,YAAY,YAAY;GAChC,MAAM,SAAS,mBAAmB,OAAO;GACzC,IAAI,QAAQ,SAAS,cAAc,aAAa,MAAM;GACtD,WAAW;IAAE,QAAQ,OAAO;IAAQ,QAAQ,OAAO;GAAO;GAG1D,iBAAiB,MAAM,KAAK,SAAS,GAAG,GAAI,CAAC,CAAC,MAAM;EACrD,CAAC;EACD,MAAM,KAAK,UAAU,UAAU,aAAa,OAAO,YAAY,MAAM,OAAO,CAAC,CAAC,CAAC;EAC/E,MAAM,KAAK,SAAS,SAAS;GAC5B,IAAI,aAAa,MAAM;IACtB,MAAM,WAAW;IACjB,aAAa,QAAQ,QAAQ,CAAC;IAC9B;GACD;GAEA,MAAM,SAAS,OAAO,KAAK,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,GAAG,EAAE;GAC9C,aAAa,OAAO,YAAY,4BAA4B,KAAK,8BAA8B,SAAS,KAAK,OAAO,KAAK,IAAI,CAAC,CAAC;EAChI,CAAC;CACF,CAAC;AACF"}
@@ -1,4 +1,4 @@
1
- import { t as commands } from "./commands-CSB-pjgs.js";
1
+ import { t as commands } from "./commands-C_B9ENxc.js";
2
2
  import { t as readOwnPackageJson } from "./version-BzclCE19.js";
3
3
  import { n as exitCodeOf, r as formatError } from "./errors-COFWKKKw.js";
4
4
  import { defineCommand, renderUsage, runCommand } from "citty";
@@ -52,4 +52,4 @@ async function runMain(argv = process.argv.slice(2)) {
52
52
 
53
53
  //#endregion
54
54
  export { runMain as t };
55
- //# sourceMappingURL=run-CHqwvZXf.js.map
55
+ //# sourceMappingURL=run-CjI3xBby.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-CHqwvZXf.js","names":["_runCommand"],"sources":["../src/main.ts","../src/run.ts"],"sourcesContent":["import { defineCommand, type CommandDef } from 'citty';\nimport { commands } from './commands/index.js';\nimport { readOwnPackageJson } from './utils/version.js';\n\n// citty types each command by its own arguments; the registry needs the erased form.\n// oxlint-disable-next-line typescript/no-explicit-any\ntype AnyCommand = CommandDef<any>;\n\nconst packageJson = readOwnPackageJson();\n\nexport const main = defineCommand({\n\tmeta: {\n\t\tname: 'stars',\n\t\tversion: packageJson.version,\n\t\tdescription: packageJson.description\n\t},\n\tsubCommands: commands\n}) as AnyCommand;\n","import { renderUsage, runCommand as _runCommand, type CommandDef } from 'citty';\nimport process from 'node:process';\nimport { commands } from './commands/index.js';\nimport { main } from './main.js';\nimport { exitCodeOf, formatError } from './utils/errors.js';\nimport { readOwnPackageJson } from './utils/version.js';\n\n// citty types each command by its own arguments; the registry needs the erased form.\n// oxlint-disable-next-line typescript/no-explicit-any\ntype AnyCommand = CommandDef<any>;\n\n/**\n * Walks the command names of `stars <command> [<subcommand>] --help` so nested commands (`stars commands clean`)\n * render their own usage instead of their parent's.\n */\nasync function resolveHelpTarget(names: string[]): Promise<AnyCommand | null> {\n\tconst [first, ...rest] = names;\n\tif (!first || !Object.hasOwn(commands, first)) return null;\n\n\tlet command = await commands[first]!();\n\tfor (const name of rest) {\n\t\tconst resolved = typeof command.subCommands === 'function' ? await command.subCommands() : await command.subCommands;\n\t\tconst child: unknown = (resolved as Record<string, unknown> | undefined)?.[name];\n\t\tif (!child) break;\n\t\tcommand = (typeof child === 'function' ? await child() : child) as AnyCommand;\n\t}\n\n\treturn command;\n}\n\nexport async function runMain(argv: string[] = process.argv.slice(2)): Promise<void> {\n\tif (argv.includes('--version') || argv.includes('-V')) {\n\t\tconsole.log(readOwnPackageJson().version);\n\t\tprocess.exit(0);\n\t}\n\n\tif (argv.length === 0 || argv.includes('--help') || argv.includes('-h')) {\n\t\t// citty's showUsage logs through consola, which is muted in some environments; render and print directly.\n\t\tconst command = await resolveHelpTarget(argv.filter((argument) => !argument.startsWith('-')));\n\t\tconsole.log(await (command ? renderUsage(command, main) : renderUsage(main)));\n\t\tprocess.exit(0);\n\t}\n\n\ttry {\n\t\tawait _runCommand(main, { rawArgs: argv });\n\t} catch (error) {\n\t\tconsole.error(await formatError(error));\n\t\tprocess.exit(exitCodeOf(error));\n\t}\n}\n"],"mappings":";;;;;;;AAQA,MAAM,cAAc,mBAAmB;AAEvC,MAAa,OAAO,cAAc;CACjC,MAAM;EACL,MAAM;EACN,SAAS,YAAY;EACrB,aAAa,YAAY;CAC1B;CACA,aAAa;AACd,CAAC;;;;;;;;ACFD,eAAe,kBAAkB,OAA6C;CAC7E,MAAM,CAAC,OAAO,GAAG,QAAQ;CACzB,IAAI,CAAC,SAAS,CAAC,OAAO,OAAO,UAAU,KAAK,GAAG,OAAO;CAEtD,IAAI,UAAU,MAAM,SAAS,MAAM,CAAE;CACrC,KAAK,MAAM,QAAQ,MAAM;EAExB,MAAM,SADW,OAAO,QAAQ,gBAAgB,aAAa,MAAM,QAAQ,YAAY,IAAI,MAAM,QAAQ,YACzE,GAA2C;EAC3E,IAAI,CAAC,OAAO;EACZ,UAAW,OAAO,UAAU,aAAa,MAAM,MAAM,IAAI;CAC1D;CAEA,OAAO;AACR;AAEA,eAAsB,QAAQ,OAAiB,QAAQ,KAAK,MAAM,CAAC,GAAkB;CACpF,IAAI,KAAK,SAAS,WAAW,KAAK,KAAK,SAAS,IAAI,GAAG;EACtD,QAAQ,IAAI,mBAAmB,CAAC,CAAC,OAAO;EACxC,QAAQ,KAAK,CAAC;CACf;CAEA,IAAI,KAAK,WAAW,KAAK,KAAK,SAAS,QAAQ,KAAK,KAAK,SAAS,IAAI,GAAG;EAExE,MAAM,UAAU,MAAM,kBAAkB,KAAK,QAAQ,aAAa,CAAC,SAAS,WAAW,GAAG,CAAC,CAAC;EAC5F,QAAQ,IAAI,OAAO,UAAU,YAAY,SAAS,IAAI,IAAI,YAAY,IAAI,EAAE;EAC5E,QAAQ,KAAK,CAAC;CACf;CAEA,IAAI;EACH,MAAMA,WAAY,MAAM,EAAE,SAAS,KAAK,CAAC;CAC1C,SAAS,OAAO;EACf,QAAQ,MAAM,MAAM,YAAY,KAAK,CAAC;EACtC,QAAQ,KAAK,WAAW,KAAK,CAAC;CAC/B;AACD"}
1
+ {"version":3,"file":"run-CjI3xBby.js","names":["_runCommand"],"sources":["../src/main.ts","../src/run.ts"],"sourcesContent":["import { defineCommand, type CommandDef } from 'citty';\nimport { commands } from './commands/index.js';\nimport { readOwnPackageJson } from './utils/version.js';\n\n// citty types each command by its own arguments; the registry needs the erased form.\n// oxlint-disable-next-line typescript/no-explicit-any\ntype AnyCommand = CommandDef<any>;\n\nconst packageJson = readOwnPackageJson();\n\nexport const main = defineCommand({\n\tmeta: {\n\t\tname: 'stars',\n\t\tversion: packageJson.version,\n\t\tdescription: packageJson.description\n\t},\n\tsubCommands: commands\n}) as AnyCommand;\n","import { renderUsage, runCommand as _runCommand, type CommandDef } from 'citty';\nimport process from 'node:process';\nimport { commands } from './commands/index.js';\nimport { main } from './main.js';\nimport { exitCodeOf, formatError } from './utils/errors.js';\nimport { readOwnPackageJson } from './utils/version.js';\n\n// citty types each command by its own arguments; the registry needs the erased form.\n// oxlint-disable-next-line typescript/no-explicit-any\ntype AnyCommand = CommandDef<any>;\n\n/**\n * Walks the command names of `stars <command> [<subcommand>] --help` so nested commands (`stars commands clean`)\n * render their own usage instead of their parent's.\n */\nasync function resolveHelpTarget(names: string[]): Promise<AnyCommand | null> {\n\tconst [first, ...rest] = names;\n\tif (!first || !Object.hasOwn(commands, first)) return null;\n\n\tlet command = await commands[first]!();\n\tfor (const name of rest) {\n\t\tconst resolved = typeof command.subCommands === 'function' ? await command.subCommands() : await command.subCommands;\n\t\tconst child: unknown = (resolved as Record<string, unknown> | undefined)?.[name];\n\t\tif (!child) break;\n\t\tcommand = (typeof child === 'function' ? await child() : child) as AnyCommand;\n\t}\n\n\treturn command;\n}\n\nexport async function runMain(argv: string[] = process.argv.slice(2)): Promise<void> {\n\tif (argv.includes('--version') || argv.includes('-V')) {\n\t\tconsole.log(readOwnPackageJson().version);\n\t\tprocess.exit(0);\n\t}\n\n\tif (argv.length === 0 || argv.includes('--help') || argv.includes('-h')) {\n\t\t// citty's showUsage logs through consola, which is muted in some environments; render and print directly.\n\t\tconst command = await resolveHelpTarget(argv.filter((argument) => !argument.startsWith('-')));\n\t\tconsole.log(await (command ? renderUsage(command, main) : renderUsage(main)));\n\t\tprocess.exit(0);\n\t}\n\n\ttry {\n\t\tawait _runCommand(main, { rawArgs: argv });\n\t} catch (error) {\n\t\tconsole.error(await formatError(error));\n\t\tprocess.exit(exitCodeOf(error));\n\t}\n}\n"],"mappings":";;;;;;;AAQA,MAAM,cAAc,mBAAmB;AAEvC,MAAa,OAAO,cAAc;CACjC,MAAM;EACL,MAAM;EACN,SAAS,YAAY;EACrB,aAAa,YAAY;CAC1B;CACA,aAAa;AACd,CAAC;;;;;;;;ACFD,eAAe,kBAAkB,OAA6C;CAC7E,MAAM,CAAC,OAAO,GAAG,QAAQ;CACzB,IAAI,CAAC,SAAS,CAAC,OAAO,OAAO,UAAU,KAAK,GAAG,OAAO;CAEtD,IAAI,UAAU,MAAM,SAAS,MAAM,CAAE;CACrC,KAAK,MAAM,QAAQ,MAAM;EAExB,MAAM,SADW,OAAO,QAAQ,gBAAgB,aAAa,MAAM,QAAQ,YAAY,IAAI,MAAM,QAAQ,YACzE,GAA2C;EAC3E,IAAI,CAAC,OAAO;EACZ,UAAW,OAAO,UAAU,aAAa,MAAM,MAAM,IAAI;CAC1D;CAEA,OAAO;AACR;AAEA,eAAsB,QAAQ,OAAiB,QAAQ,KAAK,MAAM,CAAC,GAAkB;CACpF,IAAI,KAAK,SAAS,WAAW,KAAK,KAAK,SAAS,IAAI,GAAG;EACtD,QAAQ,IAAI,mBAAmB,CAAC,CAAC,OAAO;EACxC,QAAQ,KAAK,CAAC;CACf;CAEA,IAAI,KAAK,WAAW,KAAK,KAAK,SAAS,QAAQ,KAAK,KAAK,SAAS,IAAI,GAAG;EAExE,MAAM,UAAU,MAAM,kBAAkB,KAAK,QAAQ,aAAa,CAAC,SAAS,WAAW,GAAG,CAAC,CAAC;EAC5F,QAAQ,IAAI,OAAO,UAAU,YAAY,SAAS,IAAI,IAAI,YAAY,IAAI,EAAE;EAC5E,QAAQ,KAAK,CAAC;CACf;CAEA,IAAI;EACH,MAAMA,WAAY,MAAM,EAAE,SAAS,KAAK,CAAC;CAC1C,SAAS,OAAO;EACf,QAAQ,MAAM,MAAM,YAAY,KAAK,CAAC;EACtC,QAAQ,KAAK,WAAW,KAAK,CAAC;CAC/B;AACD"}
@@ -0,0 +1,236 @@
1
+ import { i as readProjectEnv } from "./hooks-Cy6F2bhH.js";
2
+ import { EventEmitter } from "node:events";
3
+ import { startTunnel } from "untun";
4
+
5
+ //#region src/dev/tunnel.ts
6
+ const SIGNALS = [
7
+ "SIGINT",
8
+ "SIGTERM",
9
+ "SIGHUP"
10
+ ];
11
+ function isCloudflaredExit(reason) {
12
+ return reason instanceof Error && reason.message.startsWith("cloudflared exited (");
13
+ }
14
+ /**
15
+ * Exposes the bot's interactions endpoint publicly while `stars dev` runs.
16
+ *
17
+ * `dev.tunnel: true` opens a `cloudflared` quick tunnel via `untun` (it changes on every run); a configured https
18
+ * URL is only probed, since the user already serves it. Writing the URL to the Discord application is opt-in
19
+ * through `dev.tunnel.updateEndpoint`, because it edits a live application.
20
+ */
21
+ var Tunnel = class extends EventEmitter {
22
+ config;
23
+ #startTunnel;
24
+ #tunnel = null;
25
+ #state = "off";
26
+ #url = null;
27
+ #wanted = false;
28
+ #rejectionGuard = null;
29
+ constructor(config, options = {}) {
30
+ super();
31
+ this.config = config;
32
+ this.#startTunnel = options.startTunnel ?? startTunnel;
33
+ }
34
+ get state() {
35
+ return this.#state;
36
+ }
37
+ /** The public URL of the interactions endpoint, `null` until the tunnel is up. */
38
+ get url() {
39
+ return this.#url;
40
+ }
41
+ async start(forceQuick = false) {
42
+ if (this.#state === "starting" || this.#state === "up") return;
43
+ const configured = this.config.dev.tunnel;
44
+ const tunnel = forceQuick && configured.mode === "off" ? {
45
+ mode: "quick",
46
+ path: "/",
47
+ updateEndpoint: false
48
+ } : configured;
49
+ if (tunnel.mode === "off") return;
50
+ this.#wanted = true;
51
+ this.#setState("starting", null);
52
+ const url = tunnel.mode === "url" ? await this.#useConfiguredUrl(tunnel) : await this.#openQuickTunnel();
53
+ if (!url || !this.#wanted) return;
54
+ this.#setState("up", endpointUrl(url, tunnel.path));
55
+ this.emit("log", "success", `Tunnel ready at ${this.#url}`);
56
+ if (tunnel.updateEndpoint) await this.#updateInteractionsEndpoint(this.#url);
57
+ }
58
+ /** Toggles the configured tunnel, opening a quick tunnel when the project did not configure one. */
59
+ toggle() {
60
+ return this.#state === "starting" || this.#state === "up" ? this.close() : this.start(true);
61
+ }
62
+ async close() {
63
+ this.#wanted = false;
64
+ const tunnel = this.#tunnel;
65
+ this.#tunnel = null;
66
+ this.#setState("off", null);
67
+ if (!tunnel) return;
68
+ try {
69
+ await tunnel.close();
70
+ } finally {
71
+ this.#releaseRejectionGuard();
72
+ }
73
+ }
74
+ async #useConfiguredUrl(tunnel) {
75
+ if (!await probe(endpointUrl(tunnel.url, tunnel.path))) this.emit("log", "warn", `${tunnel.url} did not answer; make sure it forwards to ${this.config.dev.url ?? "the bot"}`);
76
+ return tunnel.url;
77
+ }
78
+ async #openQuickTunnel() {
79
+ const target = this.config.dev.url;
80
+ if (!target) {
81
+ this.emit("log", "error", "A quick tunnel needs `dev.url` to know what to forward to");
82
+ this.#setState("failed", null);
83
+ return null;
84
+ }
85
+ this.emit("log", "info", "Opening a cloudflared quick tunnel…");
86
+ this.#installRejectionGuard();
87
+ try {
88
+ const tunnel = await this.#startWithoutSignalHandlers(target);
89
+ if (!this.#wanted) {
90
+ await tunnel?.close();
91
+ this.#releaseRejectionGuard();
92
+ return null;
93
+ }
94
+ if (!tunnel) {
95
+ this.emit("log", "error", "cloudflared setup was cancelled");
96
+ this.#setState("failed", null);
97
+ this.#releaseRejectionGuard();
98
+ return null;
99
+ }
100
+ this.#tunnel = tunnel;
101
+ return await tunnel.getURL();
102
+ } catch (error) {
103
+ this.#releaseRejectionGuard();
104
+ if (!this.#wanted) return null;
105
+ this.emit("log", "error", `cloudflared failed: ${error instanceof Error ? error.message : String(error)}`);
106
+ this.#setState("failed", null);
107
+ return null;
108
+ }
109
+ }
110
+ /**
111
+ * `untun` adds its own `SIGINT`/`SIGTERM`/`SIGHUP` listeners that call `process.exit()` once cloudflared is closed,
112
+ * which races `stars dev`'s graceful shutdown (it closes the tunnel through {@link close} anyway), so they are removed.
113
+ */
114
+ async #startWithoutSignalHandlers(target) {
115
+ const before = SIGNALS.map((signal) => new Set(process.listeners(signal)));
116
+ try {
117
+ return await this.#startTunnel({
118
+ url: target,
119
+ acceptCloudflareNotice: true
120
+ });
121
+ } finally {
122
+ SIGNALS.forEach((signal, index) => {
123
+ for (const listener of process.listeners(signal)) if (!before[index].has(listener)) process.off(signal, listener);
124
+ });
125
+ }
126
+ }
127
+ /**
128
+ * `untun` rejects a promise per connection when cloudflared exits and never handles it (and its location pattern
129
+ * does not match lowercase codes such as `mxp03`, so that promise is never settled before), which Node reports as an
130
+ * unhandled rejection that ends the process, whenever the tunnel closes. The guard swallows that one error for as
131
+ * long as this tunnel exists; anything else it sees is thrown again, as if it was not installed.
132
+ */
133
+ #installRejectionGuard() {
134
+ if (this.#rejectionGuard) return;
135
+ const guard = (reason) => {
136
+ if (!isCloudflaredExit(reason)) {
137
+ if (process.listeners("unhandledRejection").length === 1) throw reason;
138
+ return;
139
+ }
140
+ if (this.#state !== "up" || !this.#wanted) return;
141
+ this.#tunnel = null;
142
+ this.emit("log", "error", `cloudflared stopped unexpectedly: ${reason.message}`);
143
+ this.#setState("failed", null);
144
+ this.#releaseRejectionGuard();
145
+ };
146
+ this.#rejectionGuard = guard;
147
+ process.on("unhandledRejection", guard);
148
+ }
149
+ /** Node reports an unhandled rejection after the microtasks that follow it, so the guard has to outlive them. */
150
+ #releaseRejectionGuard() {
151
+ const guard = this.#rejectionGuard;
152
+ this.#rejectionGuard = null;
153
+ if (guard) setImmediate(() => process.off("unhandledRejection", guard));
154
+ }
155
+ /**
156
+ * Points the Discord application's interactions endpoint at the tunnel. Discord validates the endpoint with a
157
+ * signed ping before accepting it, so the bot has to be up already — this runs after the first successful build.
158
+ */
159
+ async #updateInteractionsEndpoint(url) {
160
+ const credentials = readDiscordCredentials(this.config);
161
+ if (!credentials) {
162
+ this.emit("log", "warn", "Skipped the interactions endpoint update: DISCORD_TOKEN is not set");
163
+ return;
164
+ }
165
+ try {
166
+ const response = await fetch("https://discord.com/api/v10/applications/@me", {
167
+ method: "PATCH",
168
+ headers: {
169
+ authorization: `Bot ${credentials.token}`,
170
+ "content-type": "application/json"
171
+ },
172
+ body: JSON.stringify({ interactions_endpoint_url: url }),
173
+ signal: AbortSignal.timeout(1e4)
174
+ });
175
+ if (response.ok) this.emit("log", "success", `Interactions endpoint set to ${url}`);
176
+ else this.emit("log", "error", `Discord rejected the interactions endpoint (${response.status}): ${(await response.text()).slice(0, 300)}`);
177
+ } catch (error) {
178
+ this.emit("log", "error", `Failed to update the interactions endpoint: ${error instanceof Error ? error.message : String(error)}`);
179
+ }
180
+ }
181
+ #setState(state, url) {
182
+ this.#state = state;
183
+ this.#url = url;
184
+ this.emit("state", state, url);
185
+ }
186
+ };
187
+ /**
188
+ * Joins the tunnel's origin with the path the interactions endpoint is served on.
189
+ */
190
+ function endpointUrl(origin, path) {
191
+ return path === "/" ? origin : new URL(path, origin.endsWith("/") ? origin : `${origin}/`).href;
192
+ }
193
+ async function probe(url) {
194
+ try {
195
+ return (await fetch(url, {
196
+ method: "HEAD",
197
+ signal: AbortSignal.timeout(5e3)
198
+ })).status < 500;
199
+ } catch {
200
+ return false;
201
+ }
202
+ }
203
+ /**
204
+ * Reads the Discord credentials the CLI needs from the environment, falling back to the project's `.env` files the
205
+ * way the bot itself does once it starts.
206
+ */
207
+ function readDiscordCredentials(config, env = process.env) {
208
+ const fromFiles = readProjectEnvFilesCached(config);
209
+ const read = (...keys) => {
210
+ for (const key of keys) {
211
+ const value = config.dev.env[key] ?? env[key] ?? fromFiles[key];
212
+ if (value) return value;
213
+ }
214
+ return null;
215
+ };
216
+ const token = read("DISCORD_TOKEN", "TOKEN");
217
+ if (!token) return null;
218
+ return {
219
+ token,
220
+ applicationId: read("DISCORD_APPLICATION_ID", "APPLICATION_ID", "DISCORD_CLIENT_ID", "CLIENT_ID")
221
+ };
222
+ }
223
+ let envFileCache = null;
224
+ /** The variables the bot loads (see {@link readProjectEnv}), once per project and `env` options. */
225
+ function readProjectEnvFilesCached(config) {
226
+ const key = JSON.stringify([config.root, config.env.options]);
227
+ if (envFileCache?.key !== key) envFileCache = {
228
+ key,
229
+ values: readProjectEnv(config)
230
+ };
231
+ return envFileCache.values;
232
+ }
233
+
234
+ //#endregion
235
+ export { endpointUrl as n, readDiscordCredentials as r, Tunnel as t };
236
+ //# sourceMappingURL=tunnel-C3bk4dq_.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tunnel-C3bk4dq_.js","names":[],"sources":["../src/dev/tunnel.ts"],"sourcesContent":["import type { ResolvedStarsConfig, ResolvedTunnelConfig } from '@wolfstar/schema';\nimport { readProjectEnv } from '../utils/project-env.js';\nimport { EventEmitter } from 'node:events';\nimport { startTunnel, type Tunnel as UntunTunnel } from 'untun';\nimport type { LogLevel } from '../utils/log-buffer.js';\n\nexport type TunnelState = 'off' | 'starting' | 'up' | 'failed';\n\nconst SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const;\n\nfunction isCloudflaredExit(reason: unknown): reason is Error {\n\treturn reason instanceof Error && reason.message.startsWith('cloudflared exited (');\n}\n\nexport interface TunnelEvents {\n\tlog: [level: LogLevel, text: string];\n\tstate: [state: TunnelState, url: string | null];\n}\n\nexport interface TunnelOptions {\n\t/** Override for tests. */\n\tstartTunnel?: typeof startTunnel;\n}\n\n/**\n * Exposes the bot's interactions endpoint publicly while `stars dev` runs.\n *\n * `dev.tunnel: true` opens a `cloudflared` quick tunnel via `untun` (it changes on every run); a configured https\n * URL is only probed, since the user already serves it. Writing the URL to the Discord application is opt-in\n * through `dev.tunnel.updateEndpoint`, because it edits a live application.\n */\nexport class Tunnel extends EventEmitter<TunnelEvents> {\n\t#startTunnel: typeof startTunnel;\n\t#tunnel: UntunTunnel | null = null;\n\t#state: TunnelState = 'off';\n\t#url: string | null = null;\n\t#wanted = false;\n\t#rejectionGuard: ((reason: unknown) => void) | null = null;\n\n\tpublic constructor(\n\t\tprivate readonly config: ResolvedStarsConfig,\n\t\toptions: TunnelOptions = {}\n\t) {\n\t\tsuper();\n\t\tthis.#startTunnel = options.startTunnel ?? startTunnel;\n\t}\n\n\tpublic get state(): TunnelState {\n\t\treturn this.#state;\n\t}\n\n\t/** The public URL of the interactions endpoint, `null` until the tunnel is up. */\n\tpublic get url(): string | null {\n\t\treturn this.#url;\n\t}\n\n\tpublic async start(forceQuick = false): Promise<void> {\n\t\tif (this.#state === 'starting' || this.#state === 'up') return;\n\t\tconst configured = this.config.dev.tunnel;\n\t\tconst tunnel: ResolvedTunnelConfig =\n\t\t\tforceQuick && configured.mode === 'off' ? { mode: 'quick', path: '/', updateEndpoint: false } : configured;\n\t\tif (tunnel.mode === 'off') return;\n\n\t\tthis.#wanted = true;\n\t\tthis.#setState('starting', null);\n\t\tconst url = tunnel.mode === 'url' ? await this.#useConfiguredUrl(tunnel) : await this.#openQuickTunnel();\n\t\tif (!url || !this.#wanted) return;\n\n\t\tthis.#setState('up', endpointUrl(url, tunnel.path));\n\t\tthis.emit('log', 'success', `Tunnel ready at ${this.#url}`);\n\t\tif (tunnel.updateEndpoint) await this.#updateInteractionsEndpoint(this.#url!);\n\t}\n\n\t/** Toggles the configured tunnel, opening a quick tunnel when the project did not configure one. */\n\tpublic toggle(): Promise<void> {\n\t\treturn this.#state === 'starting' || this.#state === 'up' ? this.close() : this.start(true);\n\t}\n\n\tpublic async close(): Promise<void> {\n\t\tthis.#wanted = false;\n\t\tconst tunnel = this.#tunnel;\n\t\tthis.#tunnel = null;\n\t\tthis.#setState('off', null);\n\t\t// Without a tunnel, `#openQuickTunnel` is still waiting for one and closes it (then releases the guard) when it arrives.\n\t\tif (!tunnel) return;\n\t\ttry {\n\t\t\tawait tunnel.close();\n\t\t} finally {\n\t\t\tthis.#releaseRejectionGuard();\n\t\t}\n\t}\n\n\tasync #useConfiguredUrl(tunnel: Extract<ResolvedTunnelConfig, { mode: 'url' }>): Promise<string | null> {\n\t\tconst reachable = await probe(endpointUrl(tunnel.url, tunnel.path));\n\t\tif (!reachable) {\n\t\t\tthis.emit('log', 'warn', `${tunnel.url} did not answer; make sure it forwards to ${this.config.dev.url ?? 'the bot'}`);\n\t\t}\n\n\t\treturn tunnel.url;\n\t}\n\n\tasync #openQuickTunnel(): Promise<string | null> {\n\t\tconst target = this.config.dev.url;\n\t\tif (!target) {\n\t\t\tthis.emit('log', 'error', 'A quick tunnel needs `dev.url` to know what to forward to');\n\t\t\tthis.#setState('failed', null);\n\t\t\treturn null;\n\t\t}\n\n\t\tthis.emit('log', 'info', 'Opening a cloudflared quick tunnel…');\n\t\tthis.#installRejectionGuard();\n\n\t\ttry {\n\t\t\tconst tunnel = await this.#startWithoutSignalHandlers(target);\n\t\t\tif (!this.#wanted) {\n\t\t\t\tawait tunnel?.close();\n\t\t\t\tthis.#releaseRejectionGuard();\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!tunnel) {\n\t\t\t\tthis.emit('log', 'error', 'cloudflared setup was cancelled');\n\t\t\t\tthis.#setState('failed', null);\n\t\t\t\tthis.#releaseRejectionGuard();\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tthis.#tunnel = tunnel;\n\t\t\treturn await tunnel.getURL();\n\t\t} catch (error) {\n\t\t\tthis.#releaseRejectionGuard();\n\t\t\t// Closing the tunnel makes cloudflared exit, which `untun` reports as a failure: that is not one.\n\t\t\tif (!this.#wanted) return null;\n\t\t\tthis.emit('log', 'error', `cloudflared failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\tthis.#setState('failed', null);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * `untun` adds its own `SIGINT`/`SIGTERM`/`SIGHUP` listeners that call `process.exit()` once cloudflared is closed,\n\t * which races `stars dev`'s graceful shutdown (it closes the tunnel through {@link close} anyway), so they are removed.\n\t */\n\tasync #startWithoutSignalHandlers(target: string): Promise<UntunTunnel | undefined> {\n\t\tconst before = SIGNALS.map((signal) => new Set(process.listeners(signal)));\n\t\ttry {\n\t\t\treturn await this.#startTunnel({ url: target, acceptCloudflareNotice: true });\n\t\t} finally {\n\t\t\tSIGNALS.forEach((signal, index) => {\n\t\t\t\tfor (const listener of process.listeners(signal)) {\n\t\t\t\t\tif (!before[index]!.has(listener)) process.off(signal, listener);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * `untun` rejects a promise per connection when cloudflared exits and never handles it (and its location pattern\n\t * does not match lowercase codes such as `mxp03`, so that promise is never settled before), which Node reports as an\n\t * unhandled rejection that ends the process, whenever the tunnel closes. The guard swallows that one error for as\n\t * long as this tunnel exists; anything else it sees is thrown again, as if it was not installed.\n\t */\n\t#installRejectionGuard(): void {\n\t\tif (this.#rejectionGuard) return;\n\n\t\tconst guard = (reason: unknown): void => {\n\t\t\tif (!isCloudflaredExit(reason)) {\n\t\t\t\t// The guard is the only listener, so without this the rejection would be ignored instead of ending the process.\n\t\t\t\tif (process.listeners('unhandledRejection').length === 1) throw reason;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (this.#state !== 'up' || !this.#wanted) return;\n\t\t\tthis.#tunnel = null;\n\t\t\tthis.emit('log', 'error', `cloudflared stopped unexpectedly: ${reason.message}`);\n\t\t\tthis.#setState('failed', null);\n\t\t\tthis.#releaseRejectionGuard();\n\t\t};\n\n\t\tthis.#rejectionGuard = guard;\n\t\tprocess.on('unhandledRejection', guard);\n\t}\n\n\t/** Node reports an unhandled rejection after the microtasks that follow it, so the guard has to outlive them. */\n\t#releaseRejectionGuard(): void {\n\t\tconst guard = this.#rejectionGuard;\n\t\tthis.#rejectionGuard = null;\n\t\tif (guard) setImmediate(() => process.off('unhandledRejection', guard));\n\t}\n\n\t/**\n\t * Points the Discord application's interactions endpoint at the tunnel. Discord validates the endpoint with a\n\t * signed ping before accepting it, so the bot has to be up already — this runs after the first successful build.\n\t */\n\tasync #updateInteractionsEndpoint(url: string): Promise<void> {\n\t\tconst credentials = readDiscordCredentials(this.config);\n\t\tif (!credentials) {\n\t\t\tthis.emit('log', 'warn', 'Skipped the interactions endpoint update: DISCORD_TOKEN is not set');\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tconst response = await fetch('https://discord.com/api/v10/applications/@me', {\n\t\t\t\tmethod: 'PATCH',\n\t\t\t\theaders: { authorization: `Bot ${credentials.token}`, 'content-type': 'application/json' },\n\t\t\t\tbody: JSON.stringify({ interactions_endpoint_url: url }),\n\t\t\t\tsignal: AbortSignal.timeout(10_000)\n\t\t\t});\n\n\t\t\tif (response.ok) this.emit('log', 'success', `Interactions endpoint set to ${url}`);\n\t\t\telse\n\t\t\t\tthis.emit(\n\t\t\t\t\t'log',\n\t\t\t\t\t'error',\n\t\t\t\t\t`Discord rejected the interactions endpoint (${response.status}): ${(await response.text()).slice(0, 300)}`\n\t\t\t\t);\n\t\t} catch (error) {\n\t\t\tthis.emit('log', 'error', `Failed to update the interactions endpoint: ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\t}\n\n\t#setState(state: TunnelState, url: string | null): void {\n\t\tthis.#state = state;\n\t\tthis.#url = url;\n\t\tthis.emit('state', state, url);\n\t}\n}\n\n/**\n * Joins the tunnel's origin with the path the interactions endpoint is served on.\n */\nexport function endpointUrl(origin: string, path: string): string {\n\treturn path === '/' ? origin : new URL(path, origin.endsWith('/') ? origin : `${origin}/`).href;\n}\n\nasync function probe(url: string): Promise<boolean> {\n\ttry {\n\t\tconst response = await fetch(url, { method: 'HEAD', signal: AbortSignal.timeout(5000) });\n\t\treturn response.status < 500;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport interface DiscordCredentials {\n\ttoken: string;\n\tapplicationId: string | null;\n}\n\n/**\n * Reads the Discord credentials the CLI needs from the environment, falling back to the project's `.env` files the\n * way the bot itself does once it starts.\n */\nexport function readDiscordCredentials(config: ResolvedStarsConfig, env: NodeJS.ProcessEnv = process.env): DiscordCredentials | null {\n\tconst fromFiles = readProjectEnvFilesCached(config);\n\tconst read = (...keys: string[]): string | null => {\n\t\tfor (const key of keys) {\n\t\t\tconst value = config.dev.env[key] ?? env[key] ?? fromFiles[key];\n\t\t\tif (value) return value;\n\t\t}\n\t\treturn null;\n\t};\n\n\tconst token = read('DISCORD_TOKEN', 'TOKEN');\n\tif (!token) return null;\n\n\treturn { token, applicationId: read('DISCORD_APPLICATION_ID', 'APPLICATION_ID', 'DISCORD_CLIENT_ID', 'CLIENT_ID') };\n}\n\nlet envFileCache: { key: string; values: Record<string, string> } | null = null;\n\n/** The variables the bot loads (see {@link readProjectEnv}), once per project and `env` options. */\nfunction readProjectEnvFilesCached(config: ResolvedStarsConfig): Record<string, string> {\n\tconst key = JSON.stringify([config.root, config.env.options]);\n\tif (envFileCache?.key !== key) envFileCache = { key, values: readProjectEnv(config) };\n\treturn envFileCache.values;\n}\n"],"mappings":";;;;;AAQA,MAAM,UAAU;CAAC;CAAU;CAAW;AAAQ;AAE9C,SAAS,kBAAkB,QAAkC;CAC5D,OAAO,kBAAkB,SAAS,OAAO,QAAQ,WAAW,sBAAsB;AACnF;;;;;;;;AAmBA,IAAa,SAAb,cAA4B,aAA2B;CASpC;CARlB;CACA,UAA8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",
4
4
  "description": "The stars command line interface for @wolfstar/http-framework projects: typed configuration, dev server, build and project info",
5
5
  "keywords": [
6
6
  "api",
@@ -56,10 +56,10 @@
56
56
  "dependencies": {
57
57
  "@clack/prompts": "^1.8.1",
58
58
  "@sapphire/ts-config": "^5.0.3",
59
- "@wolfstar/kit": "^0.1.1",
60
- "@wolfstar/nitro-server": "^0.2.6",
61
- "@wolfstar/schema": "^0.6.0",
62
- "@wolfstar/vite-server": "^0.4.1",
59
+ "@wolfstar/kit": "^0.1.2-next-20261006112342",
60
+ "@wolfstar/nitro-server": "^0.2.7-next-20261006112342",
61
+ "@wolfstar/schema": "^0.7.0-next-20261006112342",
62
+ "@wolfstar/vite-server": "^0.4.2-next-20261006112342",
63
63
  "chokidar": "^5.0.0",
64
64
  "citty": "^0.2.2",
65
65
  "colorette": "^2.0.20",
@@ -1 +0,0 @@
1
- {"version":3,"file":"bridge-BegCt_n2.js","names":[],"sources":["../src/dev/tunnel.ts","../src/dev/bridge.ts"],"sourcesContent":["import type { ResolvedStarsConfig, ResolvedTunnelConfig } from '@wolfstar/schema';\nimport { readProjectEnv } from '../utils/project-env.js';\nimport { EventEmitter } from 'node:events';\nimport { startTunnel, type Tunnel as UntunTunnel } from 'untun';\nimport type { LogLevel } from '../utils/log-buffer.js';\n\nexport type TunnelState = 'off' | 'starting' | 'up' | 'failed';\n\nconst SIGNALS = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const;\n\nfunction isCloudflaredExit(reason: unknown): reason is Error {\n\treturn reason instanceof Error && reason.message.startsWith('cloudflared exited (');\n}\n\nexport interface TunnelEvents {\n\tlog: [level: LogLevel, text: string];\n\tstate: [state: TunnelState, url: string | null];\n}\n\nexport interface TunnelOptions {\n\t/** Override for tests. */\n\tstartTunnel?: typeof startTunnel;\n}\n\n/**\n * Exposes the bot's interactions endpoint publicly while `stars dev` runs.\n *\n * `dev.tunnel: true` opens a `cloudflared` quick tunnel via `untun` (it changes on every run); a configured https\n * URL is only probed, since the user already serves it. Writing the URL to the Discord application is opt-in\n * through `dev.tunnel.updateEndpoint`, because it edits a live application.\n */\nexport class Tunnel extends EventEmitter<TunnelEvents> {\n\t#startTunnel: typeof startTunnel;\n\t#tunnel: UntunTunnel | null = null;\n\t#state: TunnelState = 'off';\n\t#url: string | null = null;\n\t#wanted = false;\n\t#rejectionGuard: ((reason: unknown) => void) | null = null;\n\n\tpublic constructor(\n\t\tprivate readonly config: ResolvedStarsConfig,\n\t\toptions: TunnelOptions = {}\n\t) {\n\t\tsuper();\n\t\tthis.#startTunnel = options.startTunnel ?? startTunnel;\n\t}\n\n\tpublic get state(): TunnelState {\n\t\treturn this.#state;\n\t}\n\n\t/** The public URL of the interactions endpoint, `null` until the tunnel is up. */\n\tpublic get url(): string | null {\n\t\treturn this.#url;\n\t}\n\n\tpublic async start(forceQuick = false): Promise<void> {\n\t\tif (this.#state === 'starting' || this.#state === 'up') return;\n\t\tconst configured = this.config.dev.tunnel;\n\t\tconst tunnel: ResolvedTunnelConfig =\n\t\t\tforceQuick && configured.mode === 'off' ? { mode: 'quick', path: '/', updateEndpoint: false } : configured;\n\t\tif (tunnel.mode === 'off') return;\n\n\t\tthis.#wanted = true;\n\t\tthis.#setState('starting', null);\n\t\tconst url = tunnel.mode === 'url' ? await this.#useConfiguredUrl(tunnel) : await this.#openQuickTunnel();\n\t\tif (!url || !this.#wanted) return;\n\n\t\tthis.#setState('up', endpointUrl(url, tunnel.path));\n\t\tthis.emit('log', 'success', `Tunnel ready at ${this.#url}`);\n\t\tif (tunnel.updateEndpoint) await this.#updateInteractionsEndpoint(this.#url!);\n\t}\n\n\t/** Toggles the configured tunnel, opening a quick tunnel when the project did not configure one. */\n\tpublic toggle(): Promise<void> {\n\t\treturn this.#state === 'starting' || this.#state === 'up' ? this.close() : this.start(true);\n\t}\n\n\tpublic async close(): Promise<void> {\n\t\tthis.#wanted = false;\n\t\tconst tunnel = this.#tunnel;\n\t\tthis.#tunnel = null;\n\t\tthis.#setState('off', null);\n\t\t// Without a tunnel, `#openQuickTunnel` is still waiting for one and closes it (then releases the guard) when it arrives.\n\t\tif (!tunnel) return;\n\t\ttry {\n\t\t\tawait tunnel.close();\n\t\t} finally {\n\t\t\tthis.#releaseRejectionGuard();\n\t\t}\n\t}\n\n\tasync #useConfiguredUrl(tunnel: Extract<ResolvedTunnelConfig, { mode: 'url' }>): Promise<string | null> {\n\t\tconst reachable = await probe(endpointUrl(tunnel.url, tunnel.path));\n\t\tif (!reachable) {\n\t\t\tthis.emit('log', 'warn', `${tunnel.url} did not answer; make sure it forwards to ${this.config.dev.url ?? 'the bot'}`);\n\t\t}\n\n\t\treturn tunnel.url;\n\t}\n\n\tasync #openQuickTunnel(): Promise<string | null> {\n\t\tconst target = this.config.dev.url;\n\t\tif (!target) {\n\t\t\tthis.emit('log', 'error', 'A quick tunnel needs `dev.url` to know what to forward to');\n\t\t\tthis.#setState('failed', null);\n\t\t\treturn null;\n\t\t}\n\n\t\tthis.emit('log', 'info', 'Opening a cloudflared quick tunnel…');\n\t\tthis.#installRejectionGuard();\n\n\t\ttry {\n\t\t\tconst tunnel = await this.#startWithoutSignalHandlers(target);\n\t\t\tif (!this.#wanted) {\n\t\t\t\tawait tunnel?.close();\n\t\t\t\tthis.#releaseRejectionGuard();\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!tunnel) {\n\t\t\t\tthis.emit('log', 'error', 'cloudflared setup was cancelled');\n\t\t\t\tthis.#setState('failed', null);\n\t\t\t\tthis.#releaseRejectionGuard();\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tthis.#tunnel = tunnel;\n\t\t\treturn await tunnel.getURL();\n\t\t} catch (error) {\n\t\t\tthis.#releaseRejectionGuard();\n\t\t\t// Closing the tunnel makes cloudflared exit, which `untun` reports as a failure: that is not one.\n\t\t\tif (!this.#wanted) return null;\n\t\t\tthis.emit('log', 'error', `cloudflared failed: ${error instanceof Error ? error.message : String(error)}`);\n\t\t\tthis.#setState('failed', null);\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * `untun` adds its own `SIGINT`/`SIGTERM`/`SIGHUP` listeners that call `process.exit()` once cloudflared is closed,\n\t * which races `stars dev`'s graceful shutdown (it closes the tunnel through {@link close} anyway), so they are removed.\n\t */\n\tasync #startWithoutSignalHandlers(target: string): Promise<UntunTunnel | undefined> {\n\t\tconst before = SIGNALS.map((signal) => new Set(process.listeners(signal)));\n\t\ttry {\n\t\t\treturn await this.#startTunnel({ url: target, acceptCloudflareNotice: true });\n\t\t} finally {\n\t\t\tSIGNALS.forEach((signal, index) => {\n\t\t\t\tfor (const listener of process.listeners(signal)) {\n\t\t\t\t\tif (!before[index]!.has(listener)) process.off(signal, listener);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * `untun` rejects a promise per connection when cloudflared exits and never handles it (and its location pattern\n\t * does not match lowercase codes such as `mxp03`, so that promise is never settled before), which Node reports as an\n\t * unhandled rejection that ends the process, whenever the tunnel closes. The guard swallows that one error for as\n\t * long as this tunnel exists; anything else it sees is thrown again, as if it was not installed.\n\t */\n\t#installRejectionGuard(): void {\n\t\tif (this.#rejectionGuard) return;\n\n\t\tconst guard = (reason: unknown): void => {\n\t\t\tif (!isCloudflaredExit(reason)) {\n\t\t\t\t// The guard is the only listener, so without this the rejection would be ignored instead of ending the process.\n\t\t\t\tif (process.listeners('unhandledRejection').length === 1) throw reason;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (this.#state !== 'up' || !this.#wanted) return;\n\t\t\tthis.#tunnel = null;\n\t\t\tthis.emit('log', 'error', `cloudflared stopped unexpectedly: ${reason.message}`);\n\t\t\tthis.#setState('failed', null);\n\t\t\tthis.#releaseRejectionGuard();\n\t\t};\n\n\t\tthis.#rejectionGuard = guard;\n\t\tprocess.on('unhandledRejection', guard);\n\t}\n\n\t/** Node reports an unhandled rejection after the microtasks that follow it, so the guard has to outlive them. */\n\t#releaseRejectionGuard(): void {\n\t\tconst guard = this.#rejectionGuard;\n\t\tthis.#rejectionGuard = null;\n\t\tif (guard) setImmediate(() => process.off('unhandledRejection', guard));\n\t}\n\n\t/**\n\t * Points the Discord application's interactions endpoint at the tunnel. Discord validates the endpoint with a\n\t * signed ping before accepting it, so the bot has to be up already — this runs after the first successful build.\n\t */\n\tasync #updateInteractionsEndpoint(url: string): Promise<void> {\n\t\tconst credentials = readDiscordCredentials(this.config);\n\t\tif (!credentials) {\n\t\t\tthis.emit('log', 'warn', 'Skipped the interactions endpoint update: DISCORD_TOKEN is not set');\n\t\t\treturn;\n\t\t}\n\n\t\ttry {\n\t\t\tconst response = await fetch('https://discord.com/api/v10/applications/@me', {\n\t\t\t\tmethod: 'PATCH',\n\t\t\t\theaders: { authorization: `Bot ${credentials.token}`, 'content-type': 'application/json' },\n\t\t\t\tbody: JSON.stringify({ interactions_endpoint_url: url }),\n\t\t\t\tsignal: AbortSignal.timeout(10_000)\n\t\t\t});\n\n\t\t\tif (response.ok) this.emit('log', 'success', `Interactions endpoint set to ${url}`);\n\t\t\telse\n\t\t\t\tthis.emit(\n\t\t\t\t\t'log',\n\t\t\t\t\t'error',\n\t\t\t\t\t`Discord rejected the interactions endpoint (${response.status}): ${(await response.text()).slice(0, 300)}`\n\t\t\t\t);\n\t\t} catch (error) {\n\t\t\tthis.emit('log', 'error', `Failed to update the interactions endpoint: ${error instanceof Error ? error.message : String(error)}`);\n\t\t}\n\t}\n\n\t#setState(state: TunnelState, url: string | null): void {\n\t\tthis.#state = state;\n\t\tthis.#url = url;\n\t\tthis.emit('state', state, url);\n\t}\n}\n\n/**\n * Joins the tunnel's origin with the path the interactions endpoint is served on.\n */\nexport function endpointUrl(origin: string, path: string): string {\n\treturn path === '/' ? origin : new URL(path, origin.endsWith('/') ? origin : `${origin}/`).href;\n}\n\nasync function probe(url: string): Promise<boolean> {\n\ttry {\n\t\tconst response = await fetch(url, { method: 'HEAD', signal: AbortSignal.timeout(5000) });\n\t\treturn response.status < 500;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport interface DiscordCredentials {\n\ttoken: string;\n\tapplicationId: string | null;\n}\n\n/**\n * Reads the Discord credentials the CLI needs from the environment, falling back to the project's `.env` files the\n * way the bot itself does once it starts.\n */\nexport function readDiscordCredentials(config: ResolvedStarsConfig, env: NodeJS.ProcessEnv = process.env): DiscordCredentials | null {\n\tconst fromFiles = readProjectEnvFilesCached(config);\n\tconst read = (...keys: string[]): string | null => {\n\t\tfor (const key of keys) {\n\t\t\tconst value = config.dev.env[key] ?? env[key] ?? fromFiles[key];\n\t\t\tif (value) return value;\n\t\t}\n\t\treturn null;\n\t};\n\n\tconst token = read('DISCORD_TOKEN', 'TOKEN');\n\tif (!token) return null;\n\n\treturn { token, applicationId: read('DISCORD_APPLICATION_ID', 'APPLICATION_ID', 'DISCORD_CLIENT_ID', 'CLIENT_ID') };\n}\n\nlet envFileCache: { key: string; values: Record<string, string> } | null = null;\n\n/** The variables the bot loads (see {@link readProjectEnv}), once per project and `env` options. */\nfunction readProjectEnvFilesCached(config: ResolvedStarsConfig): Record<string, string> {\n\tconst key = JSON.stringify([config.root, config.env.options]);\n\tif (envFileCache?.key !== key) envFileCache = { key, values: readProjectEnv(config) };\n\treturn envFileCache.values;\n}\n","import type { ResolvedStarsConfig } from '@wolfstar/schema';\nimport { resolveSync } from 'mlly';\nimport { pathToFileURL } from 'node:url';\nimport { findInstalledVersion } from '../utils/project.js';\n\n/** Marks a message of the bridge, so a bot using the IPC channel for something else is left alone. */\nexport const BRIDGE_SOURCE = 'stars:bridge';\n/** Marks a message `stars dev` sends to the bot. */\nexport const CLI_SOURCE = 'stars:cli';\n/** Set on a bot started only to report the commands it registers (see `readLocalCommands`). */\nexport const DUMP_ENV = 'STARS_COMMANDS_DUMP';\n/** The first `@wolfstar/http-framework` with object plugins (`Client.use({ name, postListen })`), which the bridge is. */\nexport const BRIDGE_FRAMEWORK_VERSION = '6.1.0';\n\n/** An application command as the bot would register it: the JSON body Discord receives. */\nexport interface CommandData {\n\tname: string;\n\ttype?: number;\n\t[key: string]: unknown;\n}\n\nexport interface CommandSnapshot {\n\tglobal: CommandData[];\n\t/** Guild-restricted commands, by guild id. */\n\tguilds: Record<string, CommandData[]>;\n}\n\nexport interface BridgeError {\n\tmessage: string;\n\t/** The first stack frames, without the message line. */\n\tstack: string[];\n}\n\n/**\n * What the bot tells `stars dev` over the IPC channel. The bot's stdout only carries text a level is guessed for; this\n * is everything the dev UI shows that happens inside the bot: hot reloads, requests, dispatches, its commands.\n */\nexport type BridgeMessage =\n\t| { type: 'ready'; clientId: string; port: number | null }\n\t| { type: 'pieces'; store: string; pieces: { name: string; path: string }[] }\n\t| { type: 'hmr'; event: 'start'; paths: string[] }\n\t| { type: 'hmr'; event: 'stop' }\n\t| { type: 'hmr'; event: 'reloaded' | 'loaded' | 'unloaded'; store: string; names: string[]; path: string }\n\t| ({ type: 'hmr'; event: 'error'; path: string } & BridgeError)\n\t| ({ type: 'commands' } & CommandSnapshot)\n\t| { type: 'dispatch'; phase: 'run'; route: string; piece: string }\n\t| { type: 'dispatch'; phase: 'success'; route: string; piece: string; ms: number | null }\n\t| { type: 'dispatch'; phase: 'error'; route: string; piece: string; ms: number | null; error: BridgeError }\n\t| { type: 'request'; method: string; path: string; status: number; ms: number }\n\t| { type: 'refreshed'; ok: true; global: number; guilds: number; cleared: number }\n\t| ({ type: 'refreshed'; ok: false } & BridgeError)\n\t/** A line on a channel of the sender's choice: how a plugin gets its own channel in the dev UI. */\n\t| { type: 'log'; channel: string; level: string; text: string; detail?: string[] };\n\n/** What the CLI asks of the bot. `clearGuilds` are guilds whose last command was removed: nothing registers them any more. */\nexport interface RefreshRequest {\n\tsource: typeof CLI_SOURCE;\n\ttype: 'commands:refresh';\n\tclearGuilds: string[];\n}\n\ntype Loose = Record<string, any>;\n\nconst isString = (value: unknown): value is string => typeof value === 'string';\nconst isNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);\nconst isStrings = (value: unknown): value is string[] => Array.isArray(value) && value.every(isString);\nconst isRecord = (value: unknown): value is Loose => value !== null && typeof value === 'object' && !Array.isArray(value);\nconst isCommands = (value: unknown): boolean => Array.isArray(value) && value.every((command) => isRecord(command) && isString(command.name));\nconst isError = (value: Loose): boolean => isString(value.message) && isStrings(value.stack);\n\n/** The shape each message must have. A plugin can send `log`, so nothing here is taken on trust. */\nconst SHAPES: Record<BridgeMessage['type'], (message: Loose) => boolean> = {\n\tready: (message) => isString(message.clientId) && (message.port === null || isNumber(message.port)),\n\tpieces: (message) =>\n\t\tisString(message.store) &&\n\t\tArray.isArray(message.pieces) &&\n\t\tmessage.pieces.every((piece: unknown) => isRecord(piece) && isString(piece.name) && isString(piece.path)),\n\thmr: (message) => {\n\t\tswitch (message.event) {\n\t\t\tcase 'start':\n\t\t\t\treturn isStrings(message.paths);\n\t\t\tcase 'stop':\n\t\t\t\treturn true;\n\t\t\tcase 'error':\n\t\t\t\treturn isString(message.path) && isError(message);\n\t\t\tcase 'reloaded':\n\t\t\tcase 'loaded':\n\t\t\tcase 'unloaded':\n\t\t\t\treturn isString(message.store) && isStrings(message.names) && isString(message.path);\n\t\t\tdefault:\n\t\t\t\treturn false;\n\t\t}\n\t},\n\tcommands: (message) => isCommands(message.global) && isRecord(message.guilds) && Object.values(message.guilds).every(isCommands),\n\tdispatch: (message) => {\n\t\tif (!isString(message.route) || !isString(message.piece)) return false;\n\t\tif (message.phase === 'run') return true;\n\t\tif (message.ms !== null && !isNumber(message.ms)) return false;\n\t\treturn message.phase === 'success' || (message.phase === 'error' && isRecord(message.error) && isError(message.error));\n\t},\n\trequest: (message) => isString(message.method) && isString(message.path) && isNumber(message.status) && isNumber(message.ms),\n\trefreshed: (message) =>\n\t\tmessage.ok === true\n\t\t\t? isNumber(message.global) && isNumber(message.guilds) && isNumber(message.cleared)\n\t\t\t: message.ok === false && isError(message),\n\tlog: (message) =>\n\t\tisString(message.channel) &&\n\t\tmessage.channel.length > 0 &&\n\t\tisString(message.level) &&\n\t\tisString(message.text) &&\n\t\t(message.detail === undefined || isStrings(message.detail))\n};\n\n/**\n * Narrows an IPC message to one of the bridge's, `null` for anything else the bot sends and for a bridge message that\n * does not have the shape of its type.\n */\nexport function parseBridgeMessage(value: unknown): BridgeMessage | null {\n\tif (!isRecord(value) || value.source !== BRIDGE_SOURCE || !isString(value.type) || !Object.hasOwn(SHAPES, value.type)) return null;\n\treturn SHAPES[value.type as BridgeMessage['type']](value) ? (value as BridgeMessage) : null;\n}\n\n/**\n * The source of the bridge: a module preloaded into the bot (`node --import`) that registers a plugin on the bot's own\n * `Client` and reports what happens there with `process.send`. It never writes to stdout, and does nothing when the\n * process has no IPC channel, so it is inert outside `stars dev`.\n *\n * It only uses what `@wolfstar/http-framework` already exposes — the client's events, its registry and its stores —\n * which is what keeps `@wolfstar/cli` free of a dependency on the framework: `framework` is the project's own copy.\n */\nexport function bridgeModuleSource(framework: string): string {\n\treturn `import { Client, container } from ${JSON.stringify(framework)};\n\nif (typeof process.send === 'function') {\n\tconst send = (type, data) => {\n\t\ttry {\n\t\t\tprocess.send({ source: ${JSON.stringify(BRIDGE_SOURCE)}, type, ...data });\n\t\t} catch {}\n\t};\n\tconst describe = (error) => ({\n\t\tmessage: error instanceof Error ? error.message : String(error),\n\t\tstack:\n\t\t\terror instanceof Error && typeof error.stack === 'string'\n\t\t\t\t? error.stack.split('\\\\n').slice(1, 6).map((line) => line.trim())\n\t\t\t\t: []\n\t});\n\tconst commandRoute = (context) => {\n\t\tconst data = context.interaction.data ?? {};\n\t\tconst kind = context.interaction.type === 4 ? 'autocomplete' : data.type === 2 ? 'user' : data.type === 3 ? 'message' : 'slash';\n\t\tlet name = String(data.name ?? 'unknown');\n\t\tlet options = data.options;\n\t\twhile (Array.isArray(options) && options.length === 1 && (options[0].type === 1 || options[0].type === 2)) {\n\t\t\tname += ' ' + options[0].name;\n\t\t\toptions = options[0].options;\n\t\t}\n\t\treturn kind + ':' + name;\n\t};\n\tconst handlerRoute = (context) => (context.interaction.type === 5 ? 'modal' : 'component') + ':' + context.handler.name;\n\tconst commandsOf = (client) => {\n\t\tconst guilds = {};\n\t\tfor (const [id, commands] of client.registry.getLoadedGuildCommands()) guilds[id] = commands;\n\t\treturn { global: client.registry.getLoadedGlobalCommands(), guilds };\n\t};\n\tconst snapshot = (client) => {\n\t\ttry {\n\t\t\tsend('commands', commandsOf(client));\n\t\t} catch {}\n\t};\n\n\ttry {\n\t\tClient.use({\n\t\t\tname: 'stars:dev-bridge',\n\t\t\tenforce: 'post',\n\t\t\tpostInitialization(client) {\n\t\t\t\tif (process.env[${JSON.stringify(DUMP_ENV)}] === '1') {\n\t\t\t\t\t// \\`stars commands diff\\` only wants to know what the bot would register: once its pieces are loaded\n\t\t\t\t\t// it has the answer, and exits before it listens or talks to Discord.\n\t\t\t\t\tconst load = client.load.bind(client);\n\t\t\t\t\tclient.load = async (...args) => {\n\t\t\t\t\t\tawait load(...args);\n\t\t\t\t\t\tprocess.send({ source: ${JSON.stringify(BRIDGE_SOURCE)}, type: 'commands', ...commandsOf(client) }, () => process.exit(0));\n\t\t\t\t\t\tawait new Promise(() => {});\n\t\t\t\t\t};\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst started = new WeakMap();\n\t\t\t\tconst track = (prefix, route, pieceOf) => {\n\t\t\t\t\tclient.on(prefix + 'Run', (context) => {\n\t\t\t\t\t\tstarted.set(context.interaction, performance.now());\n\t\t\t\t\t\tsend('dispatch', { phase: 'run', route: route(context), piece: pieceOf(context).name });\n\t\t\t\t\t});\n\t\t\t\t\tconst done = (phase) => (first, second) => {\n\t\t\t\t\t\tconst context = phase === 'error' ? second : first;\n\t\t\t\t\t\tconst at = started.get(context.interaction);\n\t\t\t\t\t\tsend('dispatch', {\n\t\t\t\t\t\t\tphase,\n\t\t\t\t\t\t\troute: route(context),\n\t\t\t\t\t\t\tpiece: pieceOf(context).name,\n\t\t\t\t\t\t\tms: at === undefined ? null : Math.round(performance.now() - at),\n\t\t\t\t\t\t\t...(phase === 'error' ? { error: describe(first) } : {})\n\t\t\t\t\t\t});\n\t\t\t\t\t};\n\t\t\t\t\tclient.on(prefix + 'Success', done('success'));\n\t\t\t\t\tclient.on(prefix + 'Error', done('error'));\n\t\t\t\t};\n\t\t\t\ttrack('command', commandRoute, (context) => context.command);\n\t\t\t\ttrack('autocomplete', commandRoute, (context) => context.command);\n\t\t\t\ttrack('interactionHandler', handlerRoute, (context) => context.handler);\n\n\t\t\t\tconst changed = (event) => (pieces, path) => {\n\t\t\t\t\tconst list = Array.isArray(pieces) ? pieces : [pieces];\n\t\t\t\t\tconst store = list[0]?.store?.name ?? 'pieces';\n\t\t\t\t\tsend('hmr', { event, path, store, names: list.map((piece) => piece.name) });\n\t\t\t\t\tif (store === 'commands') snapshot(client);\n\t\t\t\t};\n\t\t\t\tclient.on('hmrStart', (paths) => send('hmr', { event: 'start', paths }));\n\t\t\t\tclient.on('hmrStop', () => send('hmr', { event: 'stop' }));\n\t\t\t\tclient.on('hmrPieceReloaded', changed('reloaded'));\n\t\t\t\tclient.on('hmrPiecesLoaded', changed('loaded'));\n\t\t\t\tclient.on('hmrPieceUnloaded', changed('unloaded'));\n\t\t\t\tclient.on('hmrError', (error, path) => send('hmr', { event: 'error', path, ...describe(error) }));\n\t\t\t},\n\t\t\tpostListen(client) {\n\t\t\t\tif (process.env[${JSON.stringify(DUMP_ENV)}] === '1') return;\n\t\t\t\tconst server = client.server;\n\t\t\t\tserver?.on?.('request', (request, response) => {\n\t\t\t\t\tconst at = performance.now();\n\t\t\t\t\tresponse.once('finish', () =>\n\t\t\t\t\t\tsend('request', {\n\t\t\t\t\t\t\tmethod: String(request.method),\n\t\t\t\t\t\t\tpath: String(request.url),\n\t\t\t\t\t\t\tstatus: response.statusCode,\n\t\t\t\t\t\t\tms: Math.round(performance.now() - at)\n\t\t\t\t\t\t})\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t\tfor (const store of container.stores.values()) {\n\t\t\t\t\tsend('pieces', {\n\t\t\t\t\t\tstore: store.name,\n\t\t\t\t\t\tpieces: [...store.values()].map((piece) => ({ name: piece.name, path: piece.location.full }))\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tsnapshot(client);\n\t\t\t\tconst address = server?.address?.();\n\t\t\t\tsend('ready', { clientId: client.id, port: address !== null && typeof address === 'object' ? address.port : null });\n\t\t\t}\n\t\t});\n\n\t\tprocess.on('message', (message) => {\n\t\t\tif (message === null || typeof message !== 'object' || message.source !== ${JSON.stringify(CLI_SOURCE)}) return;\n\t\t\tif (message.type !== 'commands:refresh') return;\n\t\t\tPromise.resolve()\n\t\t\t\t.then(async () => {\n\t\t\t\t\tconst client = container.client;\n\t\t\t\t\tconst global = await client.registry.pushGlobalCommands();\n\t\t\t\t\tconst guilds = await client.registry.pushGuildRestrictedCommands();\n\t\t\t\t\tconst failed = guilds.find((result) => result.status === 'rejected');\n\t\t\t\t\tif (failed) throw failed.reason;\n\t\t\t\t\t// A guild that lost its last command is no longer in the registry, so nothing above overwrote it.\n\t\t\t\t\tconst clear = Array.isArray(message.clearGuilds) ? message.clearGuilds.filter((id) => typeof id === 'string') : [];\n\t\t\t\t\tfor (const id of clear) {\n\t\t\t\t\t\tawait container.rest.put('/applications/' + client.id + '/guilds/' + id + '/commands', { body: [] });\n\t\t\t\t\t}\n\t\t\t\t\tsend('refreshed', { ok: true, global: global.length, guilds: guilds.length, cleared: clear.length });\n\t\t\t\t})\n\t\t\t\t.catch((error) => send('refreshed', { ok: false, ...describe(error) }));\n\t\t});\n\t\t// Listening for messages keeps the channel, and with it the process, alive: a bot that is done must still exit.\n\t\tprocess.channel?.unref?.();\n\t} catch {}\n}\n`;\n}\n\n/**\n * `node` arguments that preload the bridge into the bot. Nothing is preloaded when the project's framework cannot be\n * resolved or predates object plugins: `stars dev` then shows what the bot prints, as it did before the bridge.\n *\n * The framework is resolved from the project with the `import` condition, the way `moduleImportArgs` does, so the\n * plugin lands on the `Client` the bot constructs. A build that bundles the framework into its output (Vite, Nitro)\n * has its own copy, which the preload cannot reach: the bridge stays silent there too.\n */\nexport function bridgeImportArgs(config: ResolvedStarsConfig): string[] {\n\tconst version = findInstalledVersion(config.root, '@wolfstar/http-framework');\n\tif (version === null || !isAtLeast(version, BRIDGE_FRAMEWORK_VERSION)) return [];\n\n\tlet framework: string;\n\ttry {\n\t\tframework = resolveSync('@wolfstar/http-framework', { url: pathToFileURL(`${config.root}/package.json`).href });\n\t} catch {\n\t\treturn [];\n\t}\n\n\treturn ['--import', `data:text/javascript,${encodeURIComponent(bridgeModuleSource(framework))}`];\n}\n\n/** Compares the `major.minor.patch` of two versions; a prerelease counts as its release. */\nexport function isAtLeast(version: string, minimum: string): boolean {\n\tconst parse = (value: string) =>\n\t\tvalue\n\t\t\t.split('-', 1)[0]!\n\t\t\t.split('.')\n\t\t\t.map((part) => Number.parseInt(part, 10) || 0);\n\tconst [a, b] = [parse(version), parse(minimum)];\n\tfor (let index = 0; index < 3; index++) {\n\t\tconst difference = (a[index] ?? 0) - (b[index] ?? 0);\n\t\tif (difference !== 0) return difference > 0;\n\t}\n\n\treturn true;\n}\n"],"mappings":";;;;;;;;AAQA,MAAM,UAAU;CAAC;CAAU;CAAW;AAAQ;AAE9C,SAAS,kBAAkB,QAAkC;CAC5D,OAAO,kBAAkB,SAAS,OAAO,QAAQ,WAAW,sBAAsB;AACnF;;;;;;;;AAmBA,IAAa,SAAb,cAA4B,aAA2B;CASpC;CARlB;CACA,UAA8B;CAC9B,SAAsB;CACtB,OAAsB;CACtB,UAAU;CACV,kBAAsD;CAEtD,AAAO,YACN,AAAiB,QACjB,UAAyB,CAAC,GACzB;EACD,MAAM;EAHW;EAIjB,KAAK,eAAe,QAAQ,eAAe;CAC5C;CAEA,IAAW,QAAqB;EAC/B,OAAO,KAAK;CACb;;CAGA,IAAW,MAAqB;EAC/B,OAAO,KAAK;CACb;CAEA,MAAa,MAAM,aAAa,OAAsB;EACrD,IAAI,KAAK,WAAW,cAAc,KAAK,WAAW,MAAM;EACxD,MAAM,aAAa,KAAK,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AAO,CAAC,YAAY,wBAAwB,mBAAmB,mBAAmB,SAAS,CAAC,GAAG;AAChG;;AAGA,SAAgB,UAAU,SAAiB,SAA0B;CACpE,MAAM,SAAS,UACd,MACE,MAAM,KAAK,CAAC,CAAC,CAAC,EAAE,CAChB,MAAM,GAAG,CAAC,CACV,KAAK,SAAS,OAAO,SAAS,MAAM,EAAE,KAAK,CAAC;CAC/C,MAAM,CAAC,GAAG,KAAK,CAAC,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC;CAC9C,KAAK,IAAI,QAAQ,GAAG,QAAQ,GAAG,SAAS;EACvC,MAAM,cAAc,EAAE,UAAU,MAAM,EAAE,UAAU;EAClD,IAAI,eAAe,GAAG,OAAO,aAAa;CAC3C;CAEA,OAAO;AACR"}
@@ -1,124 +0,0 @@
1
- import { i as shouldUseColor } from "./output-mode-Bp7Da8vJ.js";
2
- import { t as cliDiagnostics } from "./diagnostics-BysbNnPD.js";
3
- import { i as resolveFromProject } from "./project-zlQStwsf.js";
4
- import { d as resolveCwd, n as loadProject, u as projectArgs } from "./hooks-Cy6F2bhH.js";
5
- import { defineCommand } from "citty";
6
- import { join } from "node:path";
7
- import { displayPath } from "@wolfstar/schema";
8
- import { createColors } from "colorette";
9
- import { tmpdir } from "node:os";
10
- import { spawn } from "node:child_process";
11
- import { mkdtemp, readFile, rm } from "node:fs/promises";
12
-
13
- //#region src/commands/codegen.ts
14
- async function runCodegen(options) {
15
- const stdout = options.stdout ?? process.stdout;
16
- const colors = createColors({ useColor: shouldUseColor() && !options.json });
17
- const { config } = await loadProject({
18
- cwd: resolveCwd(options),
19
- configFile: options.config
20
- });
21
- const results = [];
22
- if (config.codegen.i18n) results.push(await runI18n(config, Boolean(options.check)));
23
- if (options.json) stdout.write(`${JSON.stringify({
24
- check: Boolean(options.check),
25
- results
26
- }, null, 2)}\n`);
27
- else if (results.length === 0) stdout.write(`${colors.dim("stars")} nothing to generate (no code generators are configured)\n`);
28
- else for (const result of results) {
29
- const paint = result.status === "outdated" ? colors.red : colors.green;
30
- stdout.write(`${colors.dim("stars")} ${result.generator}: ${paint(result.status)} ${displayPath(config.root, result.output)}\n`);
31
- }
32
- if (results.some((result) => result.status === "outdated")) throw cliDiagnostics.CODEGEN_OUTDATED({});
33
- }
34
- async function runI18n(config, check) {
35
- const { locales, output } = config.codegen.i18n;
36
- const cli = resolveFromProject(config.root, "@wolfstar/i18next-type-generator");
37
- if (!cli) throw cliDiagnostics.DEPENDENCY_MISSING({
38
- name: "@wolfstar/i18next-type-generator",
39
- root: config.root,
40
- hint: "Install it with `pnpm add -D @wolfstar/i18next-type-generator`, or set `codegen.i18n` to false."
41
- });
42
- if (!check) {
43
- await generate(config.root, cli, locales, output);
44
- return {
45
- generator: "i18n",
46
- output,
47
- status: "written"
48
- };
49
- }
50
- const directory = await mkdtemp(join(tmpdir(), "stars-codegen-"));
51
- try {
52
- const candidate = join(directory, "i18next.d.ts");
53
- await generate(config.root, cli, locales, candidate);
54
- const [expected, actual] = await Promise.all([readFile(candidate, "utf-8"), readFile(output, "utf-8").catch(() => null)]);
55
- return {
56
- generator: "i18n",
57
- output,
58
- status: expected === actual ? "up-to-date" : "outdated"
59
- };
60
- } finally {
61
- await rm(directory, {
62
- recursive: true,
63
- force: true
64
- });
65
- }
66
- }
67
- function generate(root, cli, locales, output) {
68
- return new Promise((resolve, reject) => {
69
- const child = spawn(process.execPath, [
70
- cli,
71
- locales,
72
- output
73
- ], {
74
- cwd: root,
75
- stdio: [
76
- "ignore",
77
- "ignore",
78
- "pipe"
79
- ],
80
- windowsHide: true
81
- });
82
- let stderr = "";
83
- child.stderr?.on("data", (chunk) => stderr += chunk.toString());
84
- child.once("error", reject);
85
- child.once("exit", (code) => {
86
- if (code === 0) resolve();
87
- else reject(cliDiagnostics.CODEGEN_FAILED({
88
- code,
89
- stderr: stderr.trim()
90
- }));
91
- });
92
- });
93
- }
94
- var codegen_default = defineCommand({
95
- meta: {
96
- name: "codegen",
97
- description: "Run the configured code generators (i18next types)"
98
- },
99
- args: {
100
- ...projectArgs,
101
- check: {
102
- type: "boolean",
103
- description: "Fail when the generated files are out of date instead of writing them",
104
- default: false
105
- },
106
- json: {
107
- type: "boolean",
108
- description: "Print machine-readable JSON",
109
- default: false
110
- }
111
- },
112
- async run({ args }) {
113
- await runCodegen({
114
- config: args.config,
115
- cwd: args.cwd,
116
- check: args.check,
117
- json: args.json
118
- });
119
- }
120
- });
121
-
122
- //#endregion
123
- export { codegen_default as default };
124
- //# sourceMappingURL=codegen-aJSyPz-J.js.map