@wolfstar/cli 2.3.0 → 2.3.1-next-20261005132902

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.
@@ -6,6 +6,14 @@ import { resolveSync } from "mlly";
6
6
  import { startTunnel } from "untun";
7
7
 
8
8
  //#region src/dev/tunnel.ts
9
+ const SIGNALS = [
10
+ "SIGINT",
11
+ "SIGTERM",
12
+ "SIGHUP"
13
+ ];
14
+ function isCloudflaredExit(reason) {
15
+ return reason instanceof Error && reason.message.startsWith("cloudflared exited (");
16
+ }
9
17
  /**
10
18
  * Exposes the bot's interactions endpoint publicly while `stars dev` runs.
11
19
  *
@@ -20,6 +28,7 @@ var Tunnel = class extends EventEmitter {
20
28
  #state = "off";
21
29
  #url = null;
22
30
  #wanted = false;
31
+ #rejectionGuard = null;
23
32
  constructor(config, options = {}) {
24
33
  super();
25
34
  this.config = config;
@@ -58,7 +67,12 @@ var Tunnel = class extends EventEmitter {
58
67
  const tunnel = this.#tunnel;
59
68
  this.#tunnel = null;
60
69
  this.#setState("off", null);
61
- if (tunnel) await tunnel.close();
70
+ if (!tunnel) return;
71
+ try {
72
+ await tunnel.close();
73
+ } finally {
74
+ this.#releaseRejectionGuard();
75
+ }
62
76
  }
63
77
  async #useConfiguredUrl(tunnel) {
64
78
  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"}`);
@@ -72,29 +86,76 @@ var Tunnel = class extends EventEmitter {
72
86
  return null;
73
87
  }
74
88
  this.emit("log", "info", "Opening a cloudflared quick tunnel…");
89
+ this.#installRejectionGuard();
75
90
  try {
76
- const tunnel = await this.#startTunnel({
77
- url: target,
78
- acceptCloudflareNotice: true
79
- });
91
+ const tunnel = await this.#startWithoutSignalHandlers(target);
80
92
  if (!this.#wanted) {
81
93
  await tunnel?.close();
94
+ this.#releaseRejectionGuard();
82
95
  return null;
83
96
  }
84
97
  if (!tunnel) {
85
98
  this.emit("log", "error", "cloudflared setup was cancelled");
86
99
  this.#setState("failed", null);
100
+ this.#releaseRejectionGuard();
87
101
  return null;
88
102
  }
89
103
  this.#tunnel = tunnel;
90
104
  return await tunnel.getURL();
91
105
  } catch (error) {
106
+ this.#releaseRejectionGuard();
107
+ if (!this.#wanted) return null;
92
108
  this.emit("log", "error", `cloudflared failed: ${error instanceof Error ? error.message : String(error)}`);
93
109
  this.#setState("failed", null);
94
110
  return null;
95
111
  }
96
112
  }
97
113
  /**
114
+ * `untun` adds its own `SIGINT`/`SIGTERM`/`SIGHUP` listeners that call `process.exit()` once cloudflared is closed,
115
+ * which races `stars dev`'s graceful shutdown (it closes the tunnel through {@link close} anyway), so they are removed.
116
+ */
117
+ async #startWithoutSignalHandlers(target) {
118
+ const before = SIGNALS.map((signal) => new Set(process.listeners(signal)));
119
+ try {
120
+ return await this.#startTunnel({
121
+ url: target,
122
+ acceptCloudflareNotice: true
123
+ });
124
+ } finally {
125
+ SIGNALS.forEach((signal, index) => {
126
+ for (const listener of process.listeners(signal)) if (!before[index].has(listener)) process.off(signal, listener);
127
+ });
128
+ }
129
+ }
130
+ /**
131
+ * `untun` rejects a promise per connection when cloudflared exits and never handles it (and its location pattern
132
+ * does not match lowercase codes such as `mxp03`, so that promise is never settled before), which Node reports as an
133
+ * unhandled rejection that ends the process, whenever the tunnel closes. The guard swallows that one error for as
134
+ * long as this tunnel exists; anything else it sees is thrown again, as if it was not installed.
135
+ */
136
+ #installRejectionGuard() {
137
+ if (this.#rejectionGuard) return;
138
+ const guard = (reason) => {
139
+ if (!isCloudflaredExit(reason)) {
140
+ if (process.listeners("unhandledRejection").length === 1) throw reason;
141
+ return;
142
+ }
143
+ if (this.#state !== "up" || !this.#wanted) return;
144
+ this.#tunnel = null;
145
+ this.emit("log", "error", `cloudflared stopped unexpectedly: ${reason.message}`);
146
+ this.#setState("failed", null);
147
+ this.#releaseRejectionGuard();
148
+ };
149
+ this.#rejectionGuard = guard;
150
+ process.on("unhandledRejection", guard);
151
+ }
152
+ /** Node reports an unhandled rejection after the microtasks that follow it, so the guard has to outlive them. */
153
+ #releaseRejectionGuard() {
154
+ const guard = this.#rejectionGuard;
155
+ this.#rejectionGuard = null;
156
+ if (guard) setImmediate(() => process.off("unhandledRejection", guard));
157
+ }
158
+ /**
98
159
  * Points the Discord application's interactions endpoint at the tunnel. Discord validates the endpoint with a
99
160
  * signed ping before accepting it, so the bot has to be up already — this runs after the first successful build.
100
161
  */
@@ -407,4 +468,4 @@ function isAtLeast(version, minimum) {
407
468
 
408
469
  //#endregion
409
470
  export { isAtLeast as a, endpointUrl as c, bridgeImportArgs as i, readDiscordCredentials as l, CLI_SOURCE as n, parseBridgeMessage as o, DUMP_ENV as r, Tunnel as s, BRIDGE_FRAMEWORK_VERSION as t };
410
- //# sourceMappingURL=bridge-BvkmlAOZ.js.map
471
+ //# sourceMappingURL=bridge-BegCt_n2.js.map
@@ -0,0 +1 @@
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,IA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C,CAAC,KAAK,CAAC;CAC/G,QAAQ;EACP,OAAO,CAAC;CACT;CAEA,OAAO,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"}
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as runMain } from "./run-DMM2YlP3.js";
2
+ import { t as runMain } from "./run-CHqwvZXf.js";
3
3
 
4
4
  //#region src/cli.ts
5
5
  await runMain();
@@ -2,7 +2,7 @@ import { i as shouldUseColor } from "./output-mode-Bp7Da8vJ.js";
2
2
  import { t as cliDiagnostics } from "./diagnostics-BysbNnPD.js";
3
3
  import { c as moduleImportArgs, d as resolveCwd, n as loadProject, r as withProjectEnv, s as envImportArgs, t as applyEnvOptions, u as projectArgs } from "./hooks-Cy6F2bhH.js";
4
4
  import { i as matchesDeployed, n as diffCommands, t as describeCommand } from "./command-diff-BK912Hjc.js";
5
- import { i as bridgeImportArgs, l as readDiscordCredentials, o as parseBridgeMessage, r as DUMP_ENV, t as BRIDGE_FRAMEWORK_VERSION } from "./bridge-BvkmlAOZ.js";
5
+ import { i as bridgeImportArgs, l as readDiscordCredentials, o as parseBridgeMessage, r as DUMP_ENV, t as BRIDGE_FRAMEWORK_VERSION } from "./bridge-BegCt_n2.js";
6
6
  import { defineCommand } from "citty";
7
7
  import { existsSync } from "node:fs";
8
8
  import { displayPath } from "@wolfstar/schema";
@@ -545,4 +545,4 @@ var commands_default = defineCommand({
545
545
 
546
546
  //#endregion
547
547
  export { commands_default as default };
548
- //# sourceMappingURL=commands-DVC7ky6f.js.map
548
+ //# sourceMappingURL=commands-Bh0K9iWX.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"commands-DVC7ky6f.js","names":[],"sources":["../src/utils/discord.ts","../src/utils/local-commands.ts","../src/utils/prompts.ts","../src/commands/commands.ts"],"sourcesContent":["import type { ResolvedStarsConfig } from '@wolfstar/schema';\nimport { cliDiagnostics } from './diagnostics.js';\nimport { readDiscordCredentials } from '../dev/tunnel.js';\n\nconst API = 'https://discord.com/api/v10';\n\nexport interface ApplicationCommand {\n\tid: string;\n\tapplication_id: string;\n\tname: string;\n\tdescription?: string;\n\ttype?: number;\n\tguild_id?: string;\n\tversion?: string;\n}\n\nexport interface DiscordClient {\n\tapplicationId: string;\n\tlistCommands(guildId: string | null): Promise<ApplicationCommand[]>;\n\tdeleteCommand(guildId: string | null, commandId: string): Promise<void>;\n\t/** Replaces every command of the scope with `commands` (Discord's bulk overwrite): what is not listed is deleted. */\n\tputCommands(guildId: string | null, commands: readonly object[]): Promise<ApplicationCommand[]>;\n}\n\nexport const COMMAND_TYPE_NAMES: Record<number, string> = { 1: 'chat input', 2: 'user', 3: 'message' };\n\n/**\n * A minimal Discord REST client for what `stars commands` manages. The credentials come from the environment or the\n * project's `.env`, the same place the bot reads them from once it starts.\n */\nexport function createDiscordClient(config: ResolvedStarsConfig, env: NodeJS.ProcessEnv = process.env): DiscordClient {\n\tconst credentials = readDiscordCredentials(config, env);\n\tif (!credentials) {\n\t\tthrow cliDiagnostics.DISCORD_TOKEN_MISSING({});\n\t}\n\n\tif (!credentials.applicationId) {\n\t\tthrow cliDiagnostics.DISCORD_APPLICATION_ID_MISSING({});\n\t}\n\n\tconst applicationId = credentials.applicationId;\n\tconst scope = (guildId: string | null) =>\n\t\tguildId ? `/applications/${applicationId}/guilds/${guildId}/commands` : `/applications/${applicationId}/commands`;\n\n\tconst request = async (method: string, path: string, payload?: unknown): Promise<unknown> => {\n\t\tconst response = await fetch(`${API}${path}`, {\n\t\t\tmethod,\n\t\t\theaders: { authorization: `Bot ${credentials.token}`, ...(payload === undefined ? {} : { 'content-type': 'application/json' }) },\n\t\t\t...(payload === undefined ? {} : { body: JSON.stringify(payload) }),\n\t\t\tsignal: AbortSignal.timeout(15_000)\n\t\t});\n\n\t\tif (response.status === 204) return null;\n\n\t\tconst body: unknown = await response.json().catch(() => null);\n\t\tif (!response.ok) {\n\t\t\tconst detail = typeof body === 'object' && body !== null && 'message' in body ? String((body as { message: unknown }).message) : '';\n\t\t\tthrow cliDiagnostics.DISCORD_REQUEST_FAILED({ status: response.status, detail });\n\t\t}\n\n\t\treturn body;\n\t};\n\n\treturn {\n\t\tapplicationId,\n\t\tasync listCommands(guildId) {\n\t\t\tconst body = await request('GET', scope(guildId));\n\t\t\treturn Array.isArray(body) ? (body as ApplicationCommand[]) : [];\n\t\t},\n\t\tasync deleteCommand(guildId, commandId) {\n\t\t\tawait request('DELETE', `${scope(guildId)}/${commandId}`);\n\t\t},\n\t\tasync putCommands(guildId, commands) {\n\t\t\tconst body = await request('PUT', scope(guildId), commands);\n\t\t\treturn Array.isArray(body) ? (body as ApplicationCommand[]) : [];\n\t\t}\n\t};\n}\n","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","import type { Diagnostic } from 'nostics';\nimport type { ApplicationCommand } from './discord.js';\nimport { cliDiagnostics } from './diagnostics.js';\n\nexport interface CommandsPrompt {\n\t/** Asks which of the deployed commands to delete. Returns the chosen ids. */\n\tpick(commands: readonly ApplicationCommand[], scope: string): Promise<string[]>;\n\t/** Final go/no-go before anything is deleted. */\n\tconfirm(message: string): Promise<boolean>;\n}\n\n/**\n * The interactive wizard behind `stars commands clean`: a checklist of what Discord has deployed, then a\n * confirmation, so a destructive cleanup is never one keystroke away. `@clack/prompts` is loaded lazily — the\n * non-interactive paths (`--yes`, `--json`, CI) never pay for it.\n */\nexport function createClackPrompt(): CommandsPrompt {\n\treturn {\n\t\tasync pick(commands, scope) {\n\t\t\tconst { isCancel, multiselect } = await import('@clack/prompts');\n\t\t\tconst answer = await multiselect({\n\t\t\t\tmessage: `Which commands should be deleted from ${scope}?`,\n\t\t\t\toptions: commands.map((command) => ({\n\t\t\t\t\tvalue: command.id,\n\t\t\t\t\tlabel: command.name,\n\t\t\t\t\thint: [describeType(command), command.id].filter(Boolean).join(' · ')\n\t\t\t\t})),\n\t\t\t\trequired: false\n\t\t\t});\n\n\t\t\tif (isCancel(answer)) throw aborted();\n\t\t\treturn answer as string[];\n\t\t},\n\t\tasync confirm(message) {\n\t\t\tconst { confirm, isCancel } = await import('@clack/prompts');\n\t\t\tconst answer = await confirm({ message, initialValue: false });\n\n\t\t\tif (isCancel(answer)) throw aborted();\n\t\t\treturn Boolean(answer);\n\t\t}\n\t};\n}\n\nfunction describeType(command: ApplicationCommand): string {\n\tswitch (command.type) {\n\t\tcase 2:\n\t\t\treturn 'user';\n\t\tcase 3:\n\t\t\treturn 'message';\n\t\tdefault:\n\t\t\treturn 'chat input';\n\t}\n}\n\nfunction aborted(): Diagnostic {\n\treturn cliDiagnostics.ABORTED({});\n}\n","import { applyEnvOptions, loadProject, withProjectEnv } from '../utils/hooks.js';\nimport { defineCommand } from 'citty';\nimport { createColors } from 'colorette';\nimport type { Diagnostic } from 'nostics';\nimport type { ResolvedStarsConfig } from '@wolfstar/schema';\nimport type { CommandData, CommandSnapshot } from '../dev/bridge.js';\nimport { describeCommand, diffCommands, matchesDeployed, type CommandChange } from '../utils/command-diff.js';\nimport { COMMAND_TYPE_NAMES, createDiscordClient, type ApplicationCommand, type DiscordClient } from '../utils/discord.js';\nimport { cliDiagnostics } from '../utils/diagnostics.js';\nimport { readLocalCommands } from '../utils/local-commands.js';\nimport { shouldUseColor } from '../utils/output-mode.js';\nimport { createClackPrompt, type CommandsPrompt } from '../utils/prompts.js';\nimport { projectArgs, resolveCwd, type ProjectArgs } from '../utils/args.js';\n\nexport interface CommandsTaskOptions extends ProjectArgs {\n\t/** A guild id to work on the guild-scoped commands instead of the global ones. */\n\tguild?: string;\n\tjson?: boolean;\n\tstdout?: NodeJS.WritableStream;\n\t/** Overrides the client, for tests. */\n\tclient?: DiscordClient;\n}\n\nexport interface CommandsCleanOptions extends CommandsTaskOptions {\n\t/** Names to delete; without any, the wizard asks which of the deployed commands to remove. */\n\tnames?: string[];\n\t/** Deletes without asking. Required in a non-interactive terminal. */\n\tyes?: boolean;\n\tstdin?: NodeJS.ReadableStream & { isTTY?: boolean };\n\t/** Overrides the interactive wizard, for tests. */\n\tprompt?: CommandsPrompt;\n}\n\nexport interface CommandsDiffOptions extends CommandsTaskOptions {\n\t/** Fails when the deployed commands differ, for CI. */\n\tcheck?: boolean;\n\t/** Overrides the commands read from the built bot, for tests. */\n\tlocal?: CommandSnapshot;\n}\n\nexport interface CommandsDeployOptions extends CommandsDiffOptions {\n\t/** Deploys without asking. Required in a non-interactive terminal. */\n\tyes?: boolean;\n\tstdin?: NodeJS.ReadableStream & { isTTY?: boolean };\n\t/** Overrides the confirmation, for tests. */\n\tprompt?: Pick<CommandsPrompt, 'confirm'>;\n}\n\n/**\n * Lists the application commands Discord currently has deployed, which is not necessarily what the project would\n * register today: renamed and removed commands stay until something deletes them.\n */\nexport async function runCommandsList(options: CommandsTaskOptions): Promise<void> {\n\tconst stdout = options.stdout ?? process.stdout;\n\tconst colors = createColors({ useColor: shouldUseColor() && !options.json });\n\tconst { client, guild } = await connect(options);\n\tconst commands = await client.listCommands(guild);\n\n\tif (options.json) {\n\t\tstdout.write(`${JSON.stringify({ applicationId: client.applicationId, guildId: guild, commands }, null, 2)}\\n`);\n\t\treturn;\n\t}\n\n\tif (commands.length === 0) {\n\t\tstdout.write(`${colors.dim('stars')} no ${guild ? `commands in guild ${guild}` : 'global commands'} are deployed\\n`);\n\t\treturn;\n\t}\n\n\tstdout.write(`${colors.dim('stars')} ${commands.length} ${guild ? `command(s) in guild ${guild}` : 'global command(s)'}\\n`);\n\tfor (const command of commands) stdout.write(` ${colors.bold(describeName(command))} ${colors.dim(command.id)}\\n`);\n}\n\n/**\n * Deletes deployed application commands. Discord keeps whatever was registered last, so this is the way to clear\n * commands a project no longer defines (or a whole guild's test deployment).\n */\nexport async function runCommandsClean(options: CommandsCleanOptions): Promise<void> {\n\tconst stdout = options.stdout ?? process.stdout;\n\tconst colors = createColors({ useColor: shouldUseColor() && !options.json });\n\tconst { client, guild } = await connect(options);\n\tconst deployed = await client.listCommands(guild);\n\tconst wanted = options.names?.filter((name) => name.length > 0) ?? [];\n\n\tconst missing = wanted.filter((name) => !deployed.some((command) => command.name === name));\n\tif (missing.length > 0) {\n\t\tthrow cliDiagnostics.COMMAND_NOT_FOUND({ names: missing.join(', ') });\n\t}\n\n\tif (deployed.length === 0) {\n\t\tif (options.json) stdout.write(`${JSON.stringify({ deleted: [] }, null, 2)}\\n`);\n\t\telse stdout.write(`${colors.dim('stars')} nothing to delete\\n`);\n\t\treturn;\n\t}\n\n\tconst scope = guild ? `guild ${guild}` : 'the global scope';\n\tconst targets = await selectTargets(options, deployed, wanted, scope, stdout, colors);\n\tif (targets.length === 0) {\n\t\tif (options.json) stdout.write(`${JSON.stringify({ deleted: [] }, null, 2)}\\n`);\n\t\telse stdout.write(`${colors.dim('stars')} nothing to delete\\n`);\n\t\treturn;\n\t}\n\n\tfor (const command of targets) {\n\t\tawait client.deleteCommand(guild, command.id);\n\t\tif (!options.json) stdout.write(`${colors.dim('stars')} ${colors.red('deleted')} ${describeName(command)}\\n`);\n\t}\n\n\tif (options.json) stdout.write(`${JSON.stringify({ deleted: targets.map((command) => ({ id: command.id, name: command.name })) }, null, 2)}\\n`);\n}\n\nconst SYMBOLS = { added: '+', removed: '-', changed: '~' } as const;\n\n/**\n * What a deploy of `guild` (or the global scope) would change: the commands the project defines for it against the\n * ones Discord has. A command is `changed` when the project's definition no longer matches (see `matchesDeployed`).\n */\nasync function compare(options: CommandsDiffOptions): Promise<{\n\tclient: DiscordClient;\n\tguild: string | null;\n\tlocal: CommandData[];\n\tchanges: CommandChange[];\n}> {\n\tconst project = await loadProject({ cwd: resolveCwd(options), configFile: options.config });\n\t// What the bot is started with: `env:options` (and varlock) may pick other env files than the defaults.\n\tconst config = withProjectEnv(await applyEnvOptions(project.config, project.hooks));\n\tconst { client, guild } = connectTo(config, options);\n\tconst snapshot = options.local ?? (await readLocalCommands(config));\n\tconst local = guild === null ? snapshot.global : (snapshot.guilds[guild] ?? []);\n\tconst deployed = (await client.listCommands(guild)) as unknown as CommandData[];\n\t// Seen from Discord: what a deploy would add to, change in and remove from the deployed commands.\n\treturn { client, guild, local, changes: diffCommands(deployed, local, guild, (old, next) => matchesDeployed(next, old)) };\n}\n\nfunction writeChanges(stdout: NodeJS.WritableStream, colors: ReturnType<typeof createColors>, changes: readonly CommandChange[]): void {\n\tconst paint = { added: colors.green, removed: colors.red, changed: colors.yellow };\n\tfor (const change of changes) {\n\t\tstdout.write(\n\t\t\t` ${paint[change.kind](`${SYMBOLS[change.kind]} ${describeCommand({ ...change, guild: null })}`)} ${colors.dim(change.kind)}\\n`\n\t\t);\n\t}\n}\n\n/**\n * Compares the commands the project defines with the ones Discord has deployed, without changing anything: what\n * `stars commands deploy` would do. `--check` makes a difference an error, for CI.\n */\nexport async function runCommandsDiff(options: CommandsDiffOptions): Promise<void> {\n\tconst stdout = options.stdout ?? process.stdout;\n\tconst colors = createColors({ useColor: shouldUseColor() && !options.json });\n\tconst { client, guild, changes } = await compare(options);\n\n\tif (options.json) {\n\t\tstdout.write(`${JSON.stringify({ applicationId: client.applicationId, guildId: guild, changes }, null, 2)}\\n`);\n\t} else if (changes.length === 0) {\n\t\tstdout.write(`${colors.dim('stars')} ${guild ? `guild ${guild}` : 'the global scope'} is up to date\\n`);\n\t} else {\n\t\tstdout.write(`${colors.dim('stars')} ${changes.length} difference(s) in ${guild ? `guild ${guild}` : 'the global scope'}\\n`);\n\t\twriteChanges(stdout, colors, changes);\n\t}\n\n\tif (options.check && changes.length > 0) throw cliDiagnostics.COMMANDS_DIFFER({ count: changes.length });\n}\n\n/**\n * Deploys the commands the project defines to Discord with a bulk overwrite: a deployed command the project no\n * longer defines is deleted. It shows what will change and asks first; scripts pass `--yes`.\n */\nexport async function runCommandsDeploy(options: CommandsDeployOptions): Promise<void> {\n\tconst stdout = options.stdout ?? process.stdout;\n\tconst colors = createColors({ useColor: shouldUseColor() && !options.json });\n\tconst { client, guild, local, changes } = await compare(options);\n\tconst scope = guild ? `guild ${guild}` : 'the global scope';\n\n\tif (changes.length === 0) {\n\t\tif (options.json) stdout.write(`${JSON.stringify({ applicationId: client.applicationId, guildId: guild, deployed: 0, changes }, null, 2)}\\n`);\n\t\telse stdout.write(`${colors.dim('stars')} ${scope} is up to date, nothing to deploy\\n`);\n\t\treturn;\n\t}\n\n\tif (!options.json) {\n\t\tstdout.write(`${colors.dim('stars')} deploying to ${scope}\\n`);\n\t\twriteChanges(stdout, colors, changes);\n\t}\n\n\tif (!options.yes) {\n\t\tconst stdin = options.stdin ?? process.stdin;\n\t\t// `--json` owns stdout: a question printed there would end up in front of the document.\n\t\tif (!options.prompt && (!stdin.isTTY || options.json)) throw cliDiagnostics.DEPLOY_CONFIRMATION_REQUIRED({});\n\t\tconst prompt = options.prompt ?? createClackPrompt();\n\t\tif (!(await prompt.confirm(`Overwrite the commands of ${scope} with the ${local.length} the project defines?`))) {\n\t\t\tthrow cliDiagnostics.ABORTED({});\n\t\t}\n\t}\n\n\tconst deployed = await client.putCommands(guild, local);\n\tif (options.json) {\n\t\tstdout.write(`${JSON.stringify({ applicationId: client.applicationId, guildId: guild, deployed: deployed.length, changes }, null, 2)}\\n`);\n\t} else {\n\t\tstdout.write(`${colors.dim('stars')} ${colors.green('deployed')} ${deployed.length} command(s) to ${scope}\\n`);\n\t}\n}\n\n/**\n * Works out what to delete: `--name` (and `--yes`) keep the command scriptable, while a bare `stars commands clean`\n * on a terminal runs the wizard — a checklist of what Discord has deployed, then a confirmation.\n */\nasync function selectTargets(\n\toptions: CommandsCleanOptions,\n\tdeployed: ApplicationCommand[],\n\twanted: string[],\n\tscope: string,\n\tstdout: NodeJS.WritableStream,\n\tcolors: ReturnType<typeof createColors>\n): Promise<ApplicationCommand[]> {\n\tif (wanted.length > 0) {\n\t\tconst named = deployed.filter((command) => wanted.includes(command.name));\n\t\tif (options.yes) return named;\n\n\t\tawait confirmOrThrow(options, stdout, colors, `delete ${colors.bold(String(named.length))} command(s) from ${scope}?`);\n\t\treturn named;\n\t}\n\n\tif (options.yes) return deployed;\n\n\tconst stdin = options.stdin ?? process.stdin;\n\tif (!options.prompt && !stdin.isTTY) throw confirmationRequired();\n\n\tconst prompt = options.prompt ?? createClackPrompt();\n\tconst chosen = new Set(await prompt.pick(deployed, scope));\n\tconst targets = deployed.filter((command) => chosen.has(command.id));\n\tif (targets.length === 0) return [];\n\n\tconst names = targets.map((command) => command.name).join(', ');\n\tif (!(await prompt.confirm(`Delete ${targets.length} command(s) from ${scope}: ${names}?`))) {\n\t\tthrow cliDiagnostics.ABORTED({});\n\t}\n\n\treturn targets;\n}\n\nasync function connect(options: CommandsTaskOptions): Promise<{ client: DiscordClient; guild: string | null }> {\n\tconst { config } = await loadProject({ cwd: resolveCwd(options), configFile: options.config });\n\treturn connectTo(config, options);\n}\n\nfunction connectTo(config: ResolvedStarsConfig, options: CommandsTaskOptions): { client: DiscordClient; guild: string | null } {\n\treturn { client: options.client ?? createDiscordClient(config), guild: options.guild ?? null };\n}\n\nfunction describeName(command: ApplicationCommand): string {\n\tconst type = command.type && command.type !== 1 ? ` (${COMMAND_TYPE_NAMES[command.type] ?? `type ${command.type}`})` : '';\n\treturn `${command.name}${type}`;\n}\n\n/**\n * Deleting deployed commands is not reversible, so a terminal run asks first; scripts pass `--yes`.\n */\nasync function confirmOrThrow(\n\toptions: CommandsCleanOptions,\n\tstdout: NodeJS.WritableStream,\n\tcolors: ReturnType<typeof createColors>,\n\tquestion: string\n): Promise<void> {\n\tif (options.prompt) {\n\t\tif (await options.prompt.confirm(question)) return;\n\t\tthrow cliDiagnostics.ABORTED({});\n\t}\n\n\tconst stdin = options.stdin ?? process.stdin;\n\tif (!stdin.isTTY) throw confirmationRequired();\n\n\tstdout.write(`${colors.dim('stars')} ${question} [y/N] `);\n\treturn new Promise((resolve, reject) => {\n\t\tstdin.setEncoding?.('utf-8');\n\t\tstdin.once('data', (chunk: string) => {\n\t\t\tstdin.pause?.();\n\t\t\tconst answer = chunk.trim().toLowerCase();\n\t\t\tif (answer === 'y' || answer === 'yes') resolve();\n\t\t\telse reject(cliDiagnostics.ABORTED({}));\n\t\t});\n\t\tstdin.resume?.();\n\t});\n}\n\nfunction confirmationRequired(): Diagnostic {\n\treturn cliDiagnostics.CONFIRMATION_REQUIRED({});\n}\n\nconst scopeArgs = {\n\t...projectArgs,\n\tguild: {\n\t\ttype: 'string',\n\t\tdescription: 'Work on a guild’s commands instead of the global ones'\n\t},\n\tjson: {\n\t\ttype: 'boolean',\n\t\tdescription: 'Print machine-readable JSON',\n\t\tdefault: false\n\t}\n} as const;\n\nconst list = defineCommand({\n\tmeta: { name: 'list', description: 'List the application commands Discord has deployed' },\n\targs: scopeArgs,\n\tasync run({ args }) {\n\t\tawait runCommandsList({ config: args.config, cwd: args.cwd, guild: args.guild, json: args.json });\n\t}\n});\n\nconst clean = defineCommand({\n\tmeta: { name: 'clean', description: 'Delete deployed application commands (all of them, or the named ones)' },\n\targs: {\n\t\t...scopeArgs,\n\t\tname: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Only delete the command with this name (repeatable)'\n\t\t},\n\t\tyes: {\n\t\t\ttype: 'boolean',\n\t\t\talias: 'y',\n\t\t\tdescription: 'Delete without asking for a confirmation',\n\t\t\tdefault: false\n\t\t}\n\t},\n\tasync run({ args }) {\n\t\tconst names = Array.isArray(args.name) ? args.name : args.name ? [args.name] : [];\n\t\tawait runCommandsClean({ config: args.config, cwd: args.cwd, guild: args.guild, json: args.json, names, yes: args.yes });\n\t}\n});\n\nconst diff = defineCommand({\n\tmeta: { name: 'diff', description: 'Compare the commands the built bot defines with the ones Discord has deployed' },\n\targs: {\n\t\t...scopeArgs,\n\t\tcheck: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Fail when the deployed commands differ, for CI',\n\t\t\tdefault: false\n\t\t}\n\t},\n\tasync run({ args }) {\n\t\tawait runCommandsDiff({ config: args.config, cwd: args.cwd, guild: args.guild, json: args.json, check: args.check });\n\t}\n});\n\nconst deploy = defineCommand({\n\tmeta: { name: 'deploy', description: 'Deploy the commands the built bot defines, replacing the deployed ones' },\n\targs: {\n\t\t...scopeArgs,\n\t\tyes: {\n\t\t\ttype: 'boolean',\n\t\t\talias: 'y',\n\t\t\tdescription: 'Deploy without asking for a confirmation',\n\t\t\tdefault: false\n\t\t}\n\t},\n\tasync run({ args }) {\n\t\tawait runCommandsDeploy({ config: args.config, cwd: args.cwd, guild: args.guild, json: args.json, yes: args.yes });\n\t}\n});\n\nconst SUBCOMMANDS = ['list', 'clean', 'diff', 'deploy'];\n\nexport default defineCommand({\n\tmeta: {\n\t\tname: 'commands',\n\t\tdescription: 'Inspect, compare, deploy and clean the application commands deployed to Discord'\n\t},\n\tsubCommands: { list, clean, diff, deploy },\n\targs: scopeArgs,\n\tasync run({ args, rawArgs }) {\n\t\t// `stars commands` with no subcommand lists, the way `git branch` does.\n\t\tif (rawArgs.some((argument) => SUBCOMMANDS.includes(argument))) return;\n\n\t\tawait runCommandsList({ config: args.config, cwd: args.cwd, guild: args.guild, json: args.json });\n\t}\n});\n"],"mappings":";;;;;;;;;;;;AAIA,MAAM,MAAM;AAoBZ,MAAa,qBAA6C;CAAE,GAAG;CAAc,GAAG;CAAQ,GAAG;AAAU;;;;;AA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AAU,aAAa;CAAyE;CAC9G,MAAM;EACL,GAAG;EACH,KAAK;GACJ,MAAM;GACN,OAAO;GACP,aAAa;GACb,SAAS;EACV;CACD;CACA,MAAM,IAAI,EAAE,QAAQ;EACnB,MAAM,kBAAkB;GAAE,QAAQ,KAAK;GAAQ,KAAK,KAAK;GAAK,OAAO,KAAK;GAAO,MAAM,KAAK;GAAM,KAAK,KAAK;EAAI,CAAC;CAClH;AACD,CAAC;AAED,MAAM,cAAc;CAAC;CAAQ;CAAS;CAAQ;AAAQ;AAEtD,uBAAe,cAAc;CAC5B,MAAM;EACL,MAAM;EACN,aAAa;CACd;CACA,aAAa;EAAE;EAAM;EAAO;EAAM;CAAO;CACzC,MAAM;CACN,MAAM,IAAI,EAAE,MAAM,WAAW;EAE5B,IAAI,QAAQ,MAAM,aAAa,YAAY,SAAS,QAAQ,CAAC,GAAG;EAEhE,MAAM,gBAAgB;GAAE,QAAQ,KAAK;GAAQ,KAAK,KAAK;GAAK,OAAO,KAAK;GAAO,MAAM,KAAK;EAAK,CAAC;CACjG;AACD,CAAC"}
1
+ {"version":3,"file":"commands-Bh0K9iWX.js","names":[],"sources":["../src/utils/discord.ts","../src/utils/local-commands.ts","../src/utils/prompts.ts","../src/commands/commands.ts"],"sourcesContent":["import type { ResolvedStarsConfig } from '@wolfstar/schema';\nimport { cliDiagnostics } from './diagnostics.js';\nimport { readDiscordCredentials } from '../dev/tunnel.js';\n\nconst API = 'https://discord.com/api/v10';\n\nexport interface ApplicationCommand {\n\tid: string;\n\tapplication_id: string;\n\tname: string;\n\tdescription?: string;\n\ttype?: number;\n\tguild_id?: string;\n\tversion?: string;\n}\n\nexport interface DiscordClient {\n\tapplicationId: string;\n\tlistCommands(guildId: string | null): Promise<ApplicationCommand[]>;\n\tdeleteCommand(guildId: string | null, commandId: string): Promise<void>;\n\t/** Replaces every command of the scope with `commands` (Discord's bulk overwrite): what is not listed is deleted. */\n\tputCommands(guildId: string | null, commands: readonly object[]): Promise<ApplicationCommand[]>;\n}\n\nexport const COMMAND_TYPE_NAMES: Record<number, string> = { 1: 'chat input', 2: 'user', 3: 'message' };\n\n/**\n * A minimal Discord REST client for what `stars commands` manages. The credentials come from the environment or the\n * project's `.env`, the same place the bot reads them from once it starts.\n */\nexport function createDiscordClient(config: ResolvedStarsConfig, env: NodeJS.ProcessEnv = process.env): DiscordClient {\n\tconst credentials = readDiscordCredentials(config, env);\n\tif (!credentials) {\n\t\tthrow cliDiagnostics.DISCORD_TOKEN_MISSING({});\n\t}\n\n\tif (!credentials.applicationId) {\n\t\tthrow cliDiagnostics.DISCORD_APPLICATION_ID_MISSING({});\n\t}\n\n\tconst applicationId = credentials.applicationId;\n\tconst scope = (guildId: string | null) =>\n\t\tguildId ? `/applications/${applicationId}/guilds/${guildId}/commands` : `/applications/${applicationId}/commands`;\n\n\tconst request = async (method: string, path: string, payload?: unknown): Promise<unknown> => {\n\t\tconst response = await fetch(`${API}${path}`, {\n\t\t\tmethod,\n\t\t\theaders: { authorization: `Bot ${credentials.token}`, ...(payload === undefined ? {} : { 'content-type': 'application/json' }) },\n\t\t\t...(payload === undefined ? {} : { body: JSON.stringify(payload) }),\n\t\t\tsignal: AbortSignal.timeout(15_000)\n\t\t});\n\n\t\tif (response.status === 204) return null;\n\n\t\tconst body: unknown = await response.json().catch(() => null);\n\t\tif (!response.ok) {\n\t\t\tconst detail = typeof body === 'object' && body !== null && 'message' in body ? String((body as { message: unknown }).message) : '';\n\t\t\tthrow cliDiagnostics.DISCORD_REQUEST_FAILED({ status: response.status, detail });\n\t\t}\n\n\t\treturn body;\n\t};\n\n\treturn {\n\t\tapplicationId,\n\t\tasync listCommands(guildId) {\n\t\t\tconst body = await request('GET', scope(guildId));\n\t\t\treturn Array.isArray(body) ? (body as ApplicationCommand[]) : [];\n\t\t},\n\t\tasync deleteCommand(guildId, commandId) {\n\t\t\tawait request('DELETE', `${scope(guildId)}/${commandId}`);\n\t\t},\n\t\tasync putCommands(guildId, commands) {\n\t\t\tconst body = await request('PUT', scope(guildId), commands);\n\t\t\treturn Array.isArray(body) ? (body as ApplicationCommand[]) : [];\n\t\t}\n\t};\n}\n","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","import type { Diagnostic } from 'nostics';\nimport type { ApplicationCommand } from './discord.js';\nimport { cliDiagnostics } from './diagnostics.js';\n\nexport interface CommandsPrompt {\n\t/** Asks which of the deployed commands to delete. Returns the chosen ids. */\n\tpick(commands: readonly ApplicationCommand[], scope: string): Promise<string[]>;\n\t/** Final go/no-go before anything is deleted. */\n\tconfirm(message: string): Promise<boolean>;\n}\n\n/**\n * The interactive wizard behind `stars commands clean`: a checklist of what Discord has deployed, then a\n * confirmation, so a destructive cleanup is never one keystroke away. `@clack/prompts` is loaded lazily — the\n * non-interactive paths (`--yes`, `--json`, CI) never pay for it.\n */\nexport function createClackPrompt(): CommandsPrompt {\n\treturn {\n\t\tasync pick(commands, scope) {\n\t\t\tconst { isCancel, multiselect } = await import('@clack/prompts');\n\t\t\tconst answer = await multiselect({\n\t\t\t\tmessage: `Which commands should be deleted from ${scope}?`,\n\t\t\t\toptions: commands.map((command) => ({\n\t\t\t\t\tvalue: command.id,\n\t\t\t\t\tlabel: command.name,\n\t\t\t\t\thint: [describeType(command), command.id].filter(Boolean).join(' · ')\n\t\t\t\t})),\n\t\t\t\trequired: false\n\t\t\t});\n\n\t\t\tif (isCancel(answer)) throw aborted();\n\t\t\treturn answer as string[];\n\t\t},\n\t\tasync confirm(message) {\n\t\t\tconst { confirm, isCancel } = await import('@clack/prompts');\n\t\t\tconst answer = await confirm({ message, initialValue: false });\n\n\t\t\tif (isCancel(answer)) throw aborted();\n\t\t\treturn Boolean(answer);\n\t\t}\n\t};\n}\n\nfunction describeType(command: ApplicationCommand): string {\n\tswitch (command.type) {\n\t\tcase 2:\n\t\t\treturn 'user';\n\t\tcase 3:\n\t\t\treturn 'message';\n\t\tdefault:\n\t\t\treturn 'chat input';\n\t}\n}\n\nfunction aborted(): Diagnostic {\n\treturn cliDiagnostics.ABORTED({});\n}\n","import { applyEnvOptions, loadProject, withProjectEnv } from '../utils/hooks.js';\nimport { defineCommand } from 'citty';\nimport { createColors } from 'colorette';\nimport type { Diagnostic } from 'nostics';\nimport type { ResolvedStarsConfig } from '@wolfstar/schema';\nimport type { CommandData, CommandSnapshot } from '../dev/bridge.js';\nimport { describeCommand, diffCommands, matchesDeployed, type CommandChange } from '../utils/command-diff.js';\nimport { COMMAND_TYPE_NAMES, createDiscordClient, type ApplicationCommand, type DiscordClient } from '../utils/discord.js';\nimport { cliDiagnostics } from '../utils/diagnostics.js';\nimport { readLocalCommands } from '../utils/local-commands.js';\nimport { shouldUseColor } from '../utils/output-mode.js';\nimport { createClackPrompt, type CommandsPrompt } from '../utils/prompts.js';\nimport { projectArgs, resolveCwd, type ProjectArgs } from '../utils/args.js';\n\nexport interface CommandsTaskOptions extends ProjectArgs {\n\t/** A guild id to work on the guild-scoped commands instead of the global ones. */\n\tguild?: string;\n\tjson?: boolean;\n\tstdout?: NodeJS.WritableStream;\n\t/** Overrides the client, for tests. */\n\tclient?: DiscordClient;\n}\n\nexport interface CommandsCleanOptions extends CommandsTaskOptions {\n\t/** Names to delete; without any, the wizard asks which of the deployed commands to remove. */\n\tnames?: string[];\n\t/** Deletes without asking. Required in a non-interactive terminal. */\n\tyes?: boolean;\n\tstdin?: NodeJS.ReadableStream & { isTTY?: boolean };\n\t/** Overrides the interactive wizard, for tests. */\n\tprompt?: CommandsPrompt;\n}\n\nexport interface CommandsDiffOptions extends CommandsTaskOptions {\n\t/** Fails when the deployed commands differ, for CI. */\n\tcheck?: boolean;\n\t/** Overrides the commands read from the built bot, for tests. */\n\tlocal?: CommandSnapshot;\n}\n\nexport interface CommandsDeployOptions extends CommandsDiffOptions {\n\t/** Deploys without asking. Required in a non-interactive terminal. */\n\tyes?: boolean;\n\tstdin?: NodeJS.ReadableStream & { isTTY?: boolean };\n\t/** Overrides the confirmation, for tests. */\n\tprompt?: Pick<CommandsPrompt, 'confirm'>;\n}\n\n/**\n * Lists the application commands Discord currently has deployed, which is not necessarily what the project would\n * register today: renamed and removed commands stay until something deletes them.\n */\nexport async function runCommandsList(options: CommandsTaskOptions): Promise<void> {\n\tconst stdout = options.stdout ?? process.stdout;\n\tconst colors = createColors({ useColor: shouldUseColor() && !options.json });\n\tconst { client, guild } = await connect(options);\n\tconst commands = await client.listCommands(guild);\n\n\tif (options.json) {\n\t\tstdout.write(`${JSON.stringify({ applicationId: client.applicationId, guildId: guild, commands }, null, 2)}\\n`);\n\t\treturn;\n\t}\n\n\tif (commands.length === 0) {\n\t\tstdout.write(`${colors.dim('stars')} no ${guild ? `commands in guild ${guild}` : 'global commands'} are deployed\\n`);\n\t\treturn;\n\t}\n\n\tstdout.write(`${colors.dim('stars')} ${commands.length} ${guild ? `command(s) in guild ${guild}` : 'global command(s)'}\\n`);\n\tfor (const command of commands) stdout.write(` ${colors.bold(describeName(command))} ${colors.dim(command.id)}\\n`);\n}\n\n/**\n * Deletes deployed application commands. Discord keeps whatever was registered last, so this is the way to clear\n * commands a project no longer defines (or a whole guild's test deployment).\n */\nexport async function runCommandsClean(options: CommandsCleanOptions): Promise<void> {\n\tconst stdout = options.stdout ?? process.stdout;\n\tconst colors = createColors({ useColor: shouldUseColor() && !options.json });\n\tconst { client, guild } = await connect(options);\n\tconst deployed = await client.listCommands(guild);\n\tconst wanted = options.names?.filter((name) => name.length > 0) ?? [];\n\n\tconst missing = wanted.filter((name) => !deployed.some((command) => command.name === name));\n\tif (missing.length > 0) {\n\t\tthrow cliDiagnostics.COMMAND_NOT_FOUND({ names: missing.join(', ') });\n\t}\n\n\tif (deployed.length === 0) {\n\t\tif (options.json) stdout.write(`${JSON.stringify({ deleted: [] }, null, 2)}\\n`);\n\t\telse stdout.write(`${colors.dim('stars')} nothing to delete\\n`);\n\t\treturn;\n\t}\n\n\tconst scope = guild ? `guild ${guild}` : 'the global scope';\n\tconst targets = await selectTargets(options, deployed, wanted, scope, stdout, colors);\n\tif (targets.length === 0) {\n\t\tif (options.json) stdout.write(`${JSON.stringify({ deleted: [] }, null, 2)}\\n`);\n\t\telse stdout.write(`${colors.dim('stars')} nothing to delete\\n`);\n\t\treturn;\n\t}\n\n\tfor (const command of targets) {\n\t\tawait client.deleteCommand(guild, command.id);\n\t\tif (!options.json) stdout.write(`${colors.dim('stars')} ${colors.red('deleted')} ${describeName(command)}\\n`);\n\t}\n\n\tif (options.json) stdout.write(`${JSON.stringify({ deleted: targets.map((command) => ({ id: command.id, name: command.name })) }, null, 2)}\\n`);\n}\n\nconst SYMBOLS = { added: '+', removed: '-', changed: '~' } as const;\n\n/**\n * What a deploy of `guild` (or the global scope) would change: the commands the project defines for it against the\n * ones Discord has. A command is `changed` when the project's definition no longer matches (see `matchesDeployed`).\n */\nasync function compare(options: CommandsDiffOptions): Promise<{\n\tclient: DiscordClient;\n\tguild: string | null;\n\tlocal: CommandData[];\n\tchanges: CommandChange[];\n}> {\n\tconst project = await loadProject({ cwd: resolveCwd(options), configFile: options.config });\n\t// What the bot is started with: `env:options` (and varlock) may pick other env files than the defaults.\n\tconst config = withProjectEnv(await applyEnvOptions(project.config, project.hooks));\n\tconst { client, guild } = connectTo(config, options);\n\tconst snapshot = options.local ?? (await readLocalCommands(config));\n\tconst local = guild === null ? snapshot.global : (snapshot.guilds[guild] ?? []);\n\tconst deployed = (await client.listCommands(guild)) as unknown as CommandData[];\n\t// Seen from Discord: what a deploy would add to, change in and remove from the deployed commands.\n\treturn { client, guild, local, changes: diffCommands(deployed, local, guild, (old, next) => matchesDeployed(next, old)) };\n}\n\nfunction writeChanges(stdout: NodeJS.WritableStream, colors: ReturnType<typeof createColors>, changes: readonly CommandChange[]): void {\n\tconst paint = { added: colors.green, removed: colors.red, changed: colors.yellow };\n\tfor (const change of changes) {\n\t\tstdout.write(\n\t\t\t` ${paint[change.kind](`${SYMBOLS[change.kind]} ${describeCommand({ ...change, guild: null })}`)} ${colors.dim(change.kind)}\\n`\n\t\t);\n\t}\n}\n\n/**\n * Compares the commands the project defines with the ones Discord has deployed, without changing anything: what\n * `stars commands deploy` would do. `--check` makes a difference an error, for CI.\n */\nexport async function runCommandsDiff(options: CommandsDiffOptions): Promise<void> {\n\tconst stdout = options.stdout ?? process.stdout;\n\tconst colors = createColors({ useColor: shouldUseColor() && !options.json });\n\tconst { client, guild, changes } = await compare(options);\n\n\tif (options.json) {\n\t\tstdout.write(`${JSON.stringify({ applicationId: client.applicationId, guildId: guild, changes }, null, 2)}\\n`);\n\t} else if (changes.length === 0) {\n\t\tstdout.write(`${colors.dim('stars')} ${guild ? `guild ${guild}` : 'the global scope'} is up to date\\n`);\n\t} else {\n\t\tstdout.write(`${colors.dim('stars')} ${changes.length} difference(s) in ${guild ? `guild ${guild}` : 'the global scope'}\\n`);\n\t\twriteChanges(stdout, colors, changes);\n\t}\n\n\tif (options.check && changes.length > 0) throw cliDiagnostics.COMMANDS_DIFFER({ count: changes.length });\n}\n\n/**\n * Deploys the commands the project defines to Discord with a bulk overwrite: a deployed command the project no\n * longer defines is deleted. It shows what will change and asks first; scripts pass `--yes`.\n */\nexport async function runCommandsDeploy(options: CommandsDeployOptions): Promise<void> {\n\tconst stdout = options.stdout ?? process.stdout;\n\tconst colors = createColors({ useColor: shouldUseColor() && !options.json });\n\tconst { client, guild, local, changes } = await compare(options);\n\tconst scope = guild ? `guild ${guild}` : 'the global scope';\n\n\tif (changes.length === 0) {\n\t\tif (options.json) stdout.write(`${JSON.stringify({ applicationId: client.applicationId, guildId: guild, deployed: 0, changes }, null, 2)}\\n`);\n\t\telse stdout.write(`${colors.dim('stars')} ${scope} is up to date, nothing to deploy\\n`);\n\t\treturn;\n\t}\n\n\tif (!options.json) {\n\t\tstdout.write(`${colors.dim('stars')} deploying to ${scope}\\n`);\n\t\twriteChanges(stdout, colors, changes);\n\t}\n\n\tif (!options.yes) {\n\t\tconst stdin = options.stdin ?? process.stdin;\n\t\t// `--json` owns stdout: a question printed there would end up in front of the document.\n\t\tif (!options.prompt && (!stdin.isTTY || options.json)) throw cliDiagnostics.DEPLOY_CONFIRMATION_REQUIRED({});\n\t\tconst prompt = options.prompt ?? createClackPrompt();\n\t\tif (!(await prompt.confirm(`Overwrite the commands of ${scope} with the ${local.length} the project defines?`))) {\n\t\t\tthrow cliDiagnostics.ABORTED({});\n\t\t}\n\t}\n\n\tconst deployed = await client.putCommands(guild, local);\n\tif (options.json) {\n\t\tstdout.write(`${JSON.stringify({ applicationId: client.applicationId, guildId: guild, deployed: deployed.length, changes }, null, 2)}\\n`);\n\t} else {\n\t\tstdout.write(`${colors.dim('stars')} ${colors.green('deployed')} ${deployed.length} command(s) to ${scope}\\n`);\n\t}\n}\n\n/**\n * Works out what to delete: `--name` (and `--yes`) keep the command scriptable, while a bare `stars commands clean`\n * on a terminal runs the wizard — a checklist of what Discord has deployed, then a confirmation.\n */\nasync function selectTargets(\n\toptions: CommandsCleanOptions,\n\tdeployed: ApplicationCommand[],\n\twanted: string[],\n\tscope: string,\n\tstdout: NodeJS.WritableStream,\n\tcolors: ReturnType<typeof createColors>\n): Promise<ApplicationCommand[]> {\n\tif (wanted.length > 0) {\n\t\tconst named = deployed.filter((command) => wanted.includes(command.name));\n\t\tif (options.yes) return named;\n\n\t\tawait confirmOrThrow(options, stdout, colors, `delete ${colors.bold(String(named.length))} command(s) from ${scope}?`);\n\t\treturn named;\n\t}\n\n\tif (options.yes) return deployed;\n\n\tconst stdin = options.stdin ?? process.stdin;\n\tif (!options.prompt && !stdin.isTTY) throw confirmationRequired();\n\n\tconst prompt = options.prompt ?? createClackPrompt();\n\tconst chosen = new Set(await prompt.pick(deployed, scope));\n\tconst targets = deployed.filter((command) => chosen.has(command.id));\n\tif (targets.length === 0) return [];\n\n\tconst names = targets.map((command) => command.name).join(', ');\n\tif (!(await prompt.confirm(`Delete ${targets.length} command(s) from ${scope}: ${names}?`))) {\n\t\tthrow cliDiagnostics.ABORTED({});\n\t}\n\n\treturn targets;\n}\n\nasync function connect(options: CommandsTaskOptions): Promise<{ client: DiscordClient; guild: string | null }> {\n\tconst { config } = await loadProject({ cwd: resolveCwd(options), configFile: options.config });\n\treturn connectTo(config, options);\n}\n\nfunction connectTo(config: ResolvedStarsConfig, options: CommandsTaskOptions): { client: DiscordClient; guild: string | null } {\n\treturn { client: options.client ?? createDiscordClient(config), guild: options.guild ?? null };\n}\n\nfunction describeName(command: ApplicationCommand): string {\n\tconst type = command.type && command.type !== 1 ? ` (${COMMAND_TYPE_NAMES[command.type] ?? `type ${command.type}`})` : '';\n\treturn `${command.name}${type}`;\n}\n\n/**\n * Deleting deployed commands is not reversible, so a terminal run asks first; scripts pass `--yes`.\n */\nasync function confirmOrThrow(\n\toptions: CommandsCleanOptions,\n\tstdout: NodeJS.WritableStream,\n\tcolors: ReturnType<typeof createColors>,\n\tquestion: string\n): Promise<void> {\n\tif (options.prompt) {\n\t\tif (await options.prompt.confirm(question)) return;\n\t\tthrow cliDiagnostics.ABORTED({});\n\t}\n\n\tconst stdin = options.stdin ?? process.stdin;\n\tif (!stdin.isTTY) throw confirmationRequired();\n\n\tstdout.write(`${colors.dim('stars')} ${question} [y/N] `);\n\treturn new Promise((resolve, reject) => {\n\t\tstdin.setEncoding?.('utf-8');\n\t\tstdin.once('data', (chunk: string) => {\n\t\t\tstdin.pause?.();\n\t\t\tconst answer = chunk.trim().toLowerCase();\n\t\t\tif (answer === 'y' || answer === 'yes') resolve();\n\t\t\telse reject(cliDiagnostics.ABORTED({}));\n\t\t});\n\t\tstdin.resume?.();\n\t});\n}\n\nfunction confirmationRequired(): Diagnostic {\n\treturn cliDiagnostics.CONFIRMATION_REQUIRED({});\n}\n\nconst scopeArgs = {\n\t...projectArgs,\n\tguild: {\n\t\ttype: 'string',\n\t\tdescription: 'Work on a guild’s commands instead of the global ones'\n\t},\n\tjson: {\n\t\ttype: 'boolean',\n\t\tdescription: 'Print machine-readable JSON',\n\t\tdefault: false\n\t}\n} as const;\n\nconst list = defineCommand({\n\tmeta: { name: 'list', description: 'List the application commands Discord has deployed' },\n\targs: scopeArgs,\n\tasync run({ args }) {\n\t\tawait runCommandsList({ config: args.config, cwd: args.cwd, guild: args.guild, json: args.json });\n\t}\n});\n\nconst clean = defineCommand({\n\tmeta: { name: 'clean', description: 'Delete deployed application commands (all of them, or the named ones)' },\n\targs: {\n\t\t...scopeArgs,\n\t\tname: {\n\t\t\ttype: 'string',\n\t\t\tdescription: 'Only delete the command with this name (repeatable)'\n\t\t},\n\t\tyes: {\n\t\t\ttype: 'boolean',\n\t\t\talias: 'y',\n\t\t\tdescription: 'Delete without asking for a confirmation',\n\t\t\tdefault: false\n\t\t}\n\t},\n\tasync run({ args }) {\n\t\tconst names = Array.isArray(args.name) ? args.name : args.name ? [args.name] : [];\n\t\tawait runCommandsClean({ config: args.config, cwd: args.cwd, guild: args.guild, json: args.json, names, yes: args.yes });\n\t}\n});\n\nconst diff = defineCommand({\n\tmeta: { name: 'diff', description: 'Compare the commands the built bot defines with the ones Discord has deployed' },\n\targs: {\n\t\t...scopeArgs,\n\t\tcheck: {\n\t\t\ttype: 'boolean',\n\t\t\tdescription: 'Fail when the deployed commands differ, for CI',\n\t\t\tdefault: false\n\t\t}\n\t},\n\tasync run({ args }) {\n\t\tawait runCommandsDiff({ config: args.config, cwd: args.cwd, guild: args.guild, json: args.json, check: args.check });\n\t}\n});\n\nconst deploy = defineCommand({\n\tmeta: { name: 'deploy', description: 'Deploy the commands the built bot defines, replacing the deployed ones' },\n\targs: {\n\t\t...scopeArgs,\n\t\tyes: {\n\t\t\ttype: 'boolean',\n\t\t\talias: 'y',\n\t\t\tdescription: 'Deploy without asking for a confirmation',\n\t\t\tdefault: false\n\t\t}\n\t},\n\tasync run({ args }) {\n\t\tawait runCommandsDeploy({ config: args.config, cwd: args.cwd, guild: args.guild, json: args.json, yes: args.yes });\n\t}\n});\n\nconst SUBCOMMANDS = ['list', 'clean', 'diff', 'deploy'];\n\nexport default defineCommand({\n\tmeta: {\n\t\tname: 'commands',\n\t\tdescription: 'Inspect, compare, deploy and clean the application commands deployed to Discord'\n\t},\n\tsubCommands: { list, clean, diff, deploy },\n\targs: scopeArgs,\n\tasync run({ args, rawArgs }) {\n\t\t// `stars commands` with no subcommand lists, the way `git branch` does.\n\t\tif (rawArgs.some((argument) => SUBCOMMANDS.includes(argument))) return;\n\n\t\tawait runCommandsList({ config: args.config, cwd: args.cwd, guild: args.guild, json: args.json });\n\t}\n});\n"],"mappings":";;;;;;;;;;;;AAIA,MAAM,MAAM;AAoBZ,MAAa,qBAA6C;CAAE,GAAG;CAAc,GAAG;CAAQ,GAAG;AAAU;;;;;AAMrG,SAAgB,oBAAoB,QAA6B,MAAyB,QAAQ,KAAoB;CACrH,MAAM,cAAc,uBAAuB,QAAQ,GAAG;CACtD,IAAI,CAAC,aACJ,MAAM,eAAe,sBAAsB,CAAC,CAAC;CAG9C,IAAI,CAAC,YAAY,eAChB,MAAM,eAAe,+BAA+B,CAAC,CAAC;CAGvD,MAAM,gBAAgB,YAAY;CAClC,MAAM,SAAS,YACd,UAAU,iBAAiB,cAAc,UAAU,QAAQ,aAAa,iBAAiB,cAAc;CAExG,MAAM,UAAU,OAAO,QAAgB,MAAc,YAAwC;EAC5F,MAAM,WAAW,MAAM,MAAM,GAAG,MAAM,QAAQ;GAC7C;GACA,SAAS;IAAE,eAAe,OAAO,YAAY;IAAS,GAAI,YAAY,SAAY,CAAC,IAAI,EAAE,gBAAgB,mBAAmB;GAAG;GAC/H,GAAI,YAAY,SAAY,CAAC,IAAI,EAAE,MAAM,KAAK,UAAU,OAAO,EAAE;GACjE,QAAQ,YAAY,QAAQ,IAAM;EACnC,CAAC;EAED,IAAI,SAAS,WAAW,KAAK,OAAO;EAEpC,MAAM,OAAgB,MAAM,SAAS,KAAK,CAAC,CAAC,YAAY,IAAI;EAC5D,IAAI,CAAC,SAAS,IAAI;GACjB,MAAM,SAAS,O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
2
  const commands = {
3
- dev: () => import("./dev-oPPVR7d_.js").then((module) => module.default),
3
+ dev: () => import("./dev-Owu3e3AO.js").then((module) => module.default),
4
4
  build: () => import("./build-DJcc95Yq.js").then((module) => module.default),
5
5
  info: () => import("./info-CKJVMWIT.js").then((module) => module.default),
6
6
  codegen: () => import("./codegen-aJSyPz-J.js").then((module) => module.default),
7
7
  prepare: () => import("./prepare-BM93i3Rm.js").then((module) => module.default),
8
- commands: () => import("./commands-DVC7ky6f.js").then((module) => module.default),
9
- doctor: () => import("./doctor-DkVUwgDd.js").then((module) => module.default),
10
- completions: () => import("./completions-D2KYtrrv.js").then((module) => module.default)
8
+ commands: () => import("./commands-Bh0K9iWX.js").then((module) => module.default),
9
+ doctor: () => import("./doctor-DEtAAknK.js").then((module) => module.default),
10
+ completions: () => import("./completions-DMPlZ0S1.js").then((module) => module.default)
11
11
  };
12
12
 
13
13
  //#endregion
14
14
  export { commands as t };
15
- //# sourceMappingURL=commands-Clpbqq3K.js.map
15
+ //# sourceMappingURL=commands-CSB-pjgs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"commands-Clpbqq3K.js","names":[],"sources":["../src/commands/index.ts"],"sourcesContent":["import type { CommandDef } from 'citty';\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\nexport const commands: Record<string, () => Promise<AnyCommand>> = {\n\tdev: () => import('./dev.js').then((module) => module.default),\n\tbuild: () => import('./build.js').then((module) => module.default),\n\tinfo: () => import('./info.js').then((module) => module.default),\n\tcodegen: () => import('./codegen.js').then((module) => module.default),\n\tprepare: () => import('./prepare.js').then((module) => module.default),\n\tcommands: () => import('./commands.js').then((module) => module.default),\n\tdoctor: () => import('./doctor.js').then((module) => module.default),\n\tcompletions: () => import('./completions.js').then((module) => module.default)\n};\n"],"mappings":";AAMA,MAAa,WAAsD;CAClE,WAAW,OAAO,oBAAW,CAAC,MAAM,WAAW,OAAO,OAAO;CAC7D,aAAa,OAAO,sBAAa,CAAC,MAAM,WAAW,OAAO,OAAO;CACjE,YAAY,OAAO,qBAAY,CAAC,MAAM,WAAW,OAAO,OAAO;CAC/D,eAAe,OAAO,wBAAe,CAAC,MAAM,WAAW,OAAO,OAAO;CACrE,eAAe,OAAO,wBAAe,CAAC,MAAM,WAAW,OAAO,OAAO;CACrE,gBAAgB,OAAO,yBAAgB,CAAC,MAAM,WAAW,OAAO,OAAO;CACvE,cAAc,OAAO,uBAAc,CAAC,MAAM,WAAW,OAAO,OAAO;CACnE,mBAAmB,OAAO,4BAAmB,CAAC,MAAM,WAAW,OAAO,OAAO;AAC9E"}
1
+ {"version":3,"file":"commands-CSB-pjgs.js","names":[],"sources":["../src/commands/index.ts"],"sourcesContent":["import type { CommandDef } from 'citty';\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\nexport const commands: Record<string, () => Promise<AnyCommand>> = {\n\tdev: () => import('./dev.js').then((module) => module.default),\n\tbuild: () => import('./build.js').then((module) => module.default),\n\tinfo: () => import('./info.js').then((module) => module.default),\n\tcodegen: () => import('./codegen.js').then((module) => module.default),\n\tprepare: () => import('./prepare.js').then((module) => module.default),\n\tcommands: () => import('./commands.js').then((module) => module.default),\n\tdoctor: () => import('./doctor.js').then((module) => module.default),\n\tcompletions: () => import('./completions.js').then((module) => module.default)\n};\n"],"mappings":";AAMA,MAAa,WAAsD;CAClE,WAAW,OAAO,oBAAW,CAAC,MAAM,WAAW,OAAO,OAAO;CAC7D,aAAa,OAAO,sBAAa,CAAC,MAAM,WAAW,OAAO,OAAO;CACjE,YAAY,OAAO,qBAAY,CAAC,MAAM,WAAW,OAAO,OAAO;CAC/D,eAAe,OAAO,wBAAe,CAAC,MAAM,WAAW,OAAO,OAAO;CACrE,eAAe,OAAO,wBAAe,CAAC,MAAM,WAAW,OAAO,OAAO;CACrE,gBAAgB,OAAO,yBAAgB,CAAC,MAAM,WAAW,OAAO,OAAO;CACvE,cAAc,OAAO,uBAAc,CAAC,MAAM,WAAW,OAAO,OAAO;CACnE,mBAAmB,OAAO,4BAAmB,CAAC,MAAM,WAAW,OAAO,OAAO;AAC9E"}
@@ -138,7 +138,7 @@ function generateCompletions(shell, commands) {
138
138
  return GENERATORS[shell](commands);
139
139
  }
140
140
  async function runCompletions(options) {
141
- const { commands } = await import("./commands-CIPWQtF0.js");
141
+ const { commands } = await import("./commands-BlDTDvFO.js");
142
142
  (options.stdout ?? process.stdout).write(generateCompletions(options.shell, await describeCommands(commands)));
143
143
  }
144
144
  var completions_default = defineCommand({
@@ -158,4 +158,4 @@ var completions_default = defineCommand({
158
158
 
159
159
  //#endregion
160
160
  export { completions_default as default };
161
- //# sourceMappingURL=completions-D2KYtrrv.js.map
161
+ //# sourceMappingURL=completions-DMPlZ0S1.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"completions-D2KYtrrv.js","names":[],"sources":["../src/commands/completions.ts"],"sourcesContent":["import { defineCommand, type ArgsDef, type CommandDef } from 'citty';\nimport { cliDiagnostics } from '../utils/diagnostics.js';\n\n// citty types each command by its own arguments; the tree only needs the erased form.\n// oxlint-disable-next-line typescript/no-explicit-any\ntype AnyCommand = CommandDef<any>;\n\nexport interface CompletionFlag {\n\tname: string;\n\tdescription: string;\n\t/** Short forms, without the dash (`c` for `-c`). */\n\taliases: string[];\n\t/** A boolean that is on by default also has a `--no-<name>` form. */\n\tnegatable: boolean;\n}\n\nexport interface CompletionCommand {\n\tname: string;\n\tdescription: string;\n\tflags: CompletionFlag[];\n\tsubcommands: CompletionCommand[];\n}\n\nexport const SHELLS = ['bash', 'zsh', 'fish'] as const;\nexport type Shell = (typeof SHELLS)[number];\n\nasync function resolve<T>(value: T | Promise<T> | (() => T | Promise<T>) | undefined): Promise<T | undefined> {\n\treturn typeof value === 'function' ? (value as () => T | Promise<T>)() : value;\n}\n\n/** Walks the commands the CLI registers, so the completions never drift from what `--help` prints. */\nexport async function describeCommands(commands: Record<string, () => Promise<AnyCommand>>): Promise<CompletionCommand[]> {\n\tconst describe = async (name: string, command: AnyCommand): Promise<CompletionCommand> => {\n\t\tconst meta = (await resolve(command.meta)) ?? {};\n\t\tconst args = ((await resolve(command.args)) ?? {}) as ArgsDef;\n\t\tconst children = ((await resolve(command.subCommands)) ?? {}) as Record<string, AnyCommand | (() => Promise<AnyCommand>)>;\n\t\treturn {\n\t\t\tname,\n\t\t\tdescription: meta.description ?? '',\n\t\t\tflags: Object.entries(args)\n\t\t\t\t.filter(([, arg]) => arg.type !== 'positional')\n\t\t\t\t.map(([flag, arg]) => ({\n\t\t\t\t\tname: flag,\n\t\t\t\t\tdescription: arg.description ?? '',\n\t\t\t\t\taliases: [(arg as { alias?: string | string[] }).alias ?? []].flat(),\n\t\t\t\t\tnegatable: arg.type === 'boolean' && arg.default === true\n\t\t\t\t})),\n\t\t\tsubcommands: await Promise.all(Object.entries(children).map(async ([child, value]) => describe(child, (await resolve(value))!)))\n\t\t};\n\t};\n\n\treturn Promise.all(Object.entries(commands).map(async ([name, load]) => describe(name, await load())));\n}\n\n/** Every spelling of a flag: `--name`, `--no-name` when it can be switched off, and its short forms. */\nconst spellings = (flag: CompletionFlag) => [\n\t`--${flag.name}`,\n\t...(flag.negatable ? [`--no-${flag.name}`] : []),\n\t...flag.aliases.map((alias) => (alias.length === 1 ? `-${alias}` : `--${alias}`))\n];\n\nconst flagsOf = (command: CompletionCommand) => [...command.flags.flatMap(spellings), '--help'].join(' ');\n\nfunction bash(commands: readonly CompletionCommand[]): string {\n\tconst cases = commands.map((command) => {\n\t\tif (command.subcommands.length === 0) return `\\t\\t${command.name}) words=\"${flagsOf(command)}\" ;;`;\n\t\tconst nested = command.subcommands.map((child) => `\\t\\t\\t\\t${child.name}) words=\"${flagsOf(child)}\" ;;`).join('\\n');\n\t\treturn [\n\t\t\t`\\t\\t${command.name})`,\n\t\t\t// The subcommand is the first of its names after the command: options of the parent may come before it.\n\t\t\t'\\t\\t\\tsub=\"\"',\n\t\t\t'\\t\\t\\tfor ((i = 2; i < COMP_CWORD; i++)); do',\n\t\t\t`\\t\\t\\t\\tcase \"\\${COMP_WORDS[i]}\" in ${command.subcommands.map((child) => child.name).join('|')}) sub=\"\\${COMP_WORDS[i]}\"; break ;; esac`,\n\t\t\t'\\t\\t\\tdone',\n\t\t\t'\\t\\t\\tcase \"$sub\" in',\n\t\t\tnested,\n\t\t\t`\\t\\t\\t\\t*) words=\"${command.subcommands.map((child) => child.name).join(' ')} ${flagsOf(command)}\" ;;`,\n\t\t\t'\\t\\t\\tesac ;;'\n\t\t].join('\\n');\n\t});\n\n\treturn `# stars completions for bash. Load them with: eval \"$(stars completions bash)\"\n_stars() {\n\tlocal cur words sub i\n\tcur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n\tif [ \"$COMP_CWORD\" -eq 1 ]; then\n\t\twords=\"${commands.map((command) => command.name).join(' ')} --help --version\"\n\telse\n\t\tcase \"\\${COMP_WORDS[1]}\" in\n${cases.join('\\n')}\n\t\t\t*) words=\"\" ;;\n\t\tesac\n\tfi\n\tCOMPREPLY=($(compgen -W \"$words\" -- \"$cur\"))\n}\ncomplete -o default -F _stars stars\n`;\n}\n\nconst quote = (text: string) => `'${text.replaceAll(\"'\", \"'\\\\''\")}'`;\n/** A zsh `_describe` entry: the colon separates the value from its description, so one in the text is escaped. */\nconst described = (name: string, description: string) => quote(`${name}:${description.replaceAll(':', '\\\\:')}`);\n\nfunction zsh(commands: readonly CompletionCommand[]): string {\n\tconst flags = (command: CompletionCommand) =>\n\t\t[\n\t\t\t...command.flags.flatMap((flag) => spellings(flag).map((spelling) => described(spelling, flag.description))),\n\t\t\tdescribed('--help', 'Show the usage')\n\t\t].join(' ');\n\tconst cases = commands.map((command) => {\n\t\tif (command.subcommands.length === 0) return `\\t\\t${command.name}) items=(${flags(command)}) ;;`;\n\t\tconst nested = command.subcommands.map((child) => `\\t\\t\\t\\t${child.name}) items=(${flags(child)}) ;;`).join('\\n');\n\t\tconst children = command.subcommands.map((child) => described(child.name, child.description)).join(' ');\n\t\treturn [\n\t\t\t`\\t\\t${command.name})`,\n\t\t\t'\\t\\t\\tsub=\"\"',\n\t\t\t'\\t\\t\\tfor word in ${words[3,CURRENT-1]}; do',\n\t\t\t`\\t\\t\\t\\tcase \"$word\" in ${command.subcommands.map((child) => child.name).join('|')}) sub=\"$word\"; break ;; esac`,\n\t\t\t'\\t\\t\\tdone',\n\t\t\t'\\t\\t\\tcase \"$sub\" in',\n\t\t\tnested,\n\t\t\t`\\t\\t\\t\\t*) items=(${children} ${flags(command)}) ;;`,\n\t\t\t'\\t\\t\\tesac ;;'\n\t\t].join('\\n');\n\t});\n\n\treturn `#compdef stars\n# stars completions for zsh. Load them with: eval \"$(stars completions zsh)\"\n_stars() {\n\tlocal -a items\n\tlocal sub word\n\tif (( CURRENT == 2 )); then\n\t\titems=(${commands.map((command) => described(command.name, command.description)).join(' ')})\n\telse\n\t\tcase \"$words[2]\" in\n${cases.join('\\n')}\n\t\tesac\n\tfi\n\t_describe 'stars' items\n}\ncompdef _stars stars\n`;\n}\n\nfunction fishFlag(condition: string, flag: CompletionFlag): string[] {\n\tconst short = flag.aliases\n\t\t.filter((alias) => alias.length === 1)\n\t\t.map((alias) => ` -s ${alias}`)\n\t\t.join('');\n\tconst line = (name: string) => `complete -c stars -n \"${condition}\" -l ${name}${name === flag.name ? short : ''} -d ${quote(flag.description)}`;\n\treturn [line(flag.name), ...(flag.negatable ? [line(`no-${flag.name}`)] : [])];\n}\n\nfunction fish(commands: readonly CompletionCommand[]): string {\n\tconst lines = ['# stars completions for fish. Load them with: stars completions fish | source', 'complete -c stars -f'];\n\tconst names = commands.map((command) => command.name).join(' ');\n\tfor (const command of commands) {\n\t\tlines.push(`complete -c stars -n \"not __fish_seen_subcommand_from ${names}\" -a ${command.name} -d ${quote(command.description)}`);\n\t\tconst children = command.subcommands.map((child) => child.name).join(' ');\n\t\tfor (const flag of command.flags) lines.push(...fishFlag(`__fish_seen_subcommand_from ${command.name}`, flag));\n\n\t\tfor (const child of command.subcommands) {\n\t\t\tlines.push(\n\t\t\t\t`complete -c stars -n \"__fish_seen_subcommand_from ${command.name}; and not __fish_seen_subcommand_from ${children}\" -a ${child.name} -d ${quote(child.description)}`\n\t\t\t);\n\t\t\tfor (const flag of child.flags.filter((candidate) => !command.flags.some((own) => own.name === candidate.name))) {\n\t\t\t\tlines.push(...fishFlag(`__fish_seen_subcommand_from ${command.name}; and __fish_seen_subcommand_from ${child.name}`, flag));\n\t\t\t}\n\t\t}\n\t}\n\n\treturn `${lines.join('\\n')}\\n`;\n}\n\nconst GENERATORS: Record<Shell, (commands: readonly CompletionCommand[]) => string> = { bash, zsh, fish };\n\n/** The completion script of a shell, for the given commands. */\nexport function generateCompletions(shell: string, commands: readonly CompletionCommand[]): string {\n\tif (!(SHELLS as readonly string[]).includes(shell)) throw cliDiagnostics.UNKNOWN_SHELL({ shell });\n\treturn GENERATORS[shell as Shell](commands);\n}\n\nexport interface CompletionsOptions {\n\tshell: string;\n\tstdout?: NodeJS.WritableStream;\n}\n\nexport async function runCompletions(options: CompletionsOptions): Promise<void> {\n\t// Imported here: the registry imports this module, as it does every command.\n\tconst { commands } = await import('./index.js');\n\t(options.stdout ?? process.stdout).write(generateCompletions(options.shell, await describeCommands(commands)));\n}\n\nexport default defineCommand({\n\tmeta: {\n\t\tname: 'completions',\n\t\tdescription: 'Print the shell completion script for bash, zsh or fish'\n\t},\n\targs: {\n\t\tshell: {\n\t\t\ttype: 'positional',\n\t\t\tdescription: `The shell to print completions for: ${SHELLS.join(', ')}`,\n\t\t\trequired: true\n\t\t}\n\t},\n\tasync run({ args }) {\n\t\tawait runCompletions({ shell: args.shell });\n\t}\n});\n"],"mappings":";;;;AAuBA,MAAa,SAAS;CAAC;CAAQ;CAAO;AAAM;AAG5C,eAAe,QAAW,OAAoF;CAC7G,OAAO,OAAO,UAAU,aAAc,MAA+B,IAAI;AAC1E;;AAGA,eAAsB,iBAAiB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,+BAA+B,QAAQ,QAAQ,IAAI,CAAC;EAE7G,KAAK,MAAM,SAAS,QAAQ,aAAa;GACxC,MAAM,KACL,qDAAqD,QAAQ,KAAK,wCAAwC,SAAS,OAAO,MAAM,KAAK,MAAM,MAAM,MAAM,WAAW,GACnK;GACA,KAAK,MAAM,QAAQ,MAAM,MAAM,QAAQ,cAAc,CAAC,QAAQ,MAAM,MAAM,QAAQ,IAAI,SAAS,UAAU,IAAI,CAAC,GAC7G,MAAM,KAAK,GAAG,SAAS,+BAA+B,QAAQ,KAAK,oCAAoC,MAAM,QAAQ,IAAI,CAAC;EAE5H;CACD;CAEA,OAAO,GAAG,MAAM,KAAK,IAAI,EAAE;AAC5B;AAEA,MAAM,aAAgF;CAAE;CAAM;CAAK;AAAK;;AAGxG,SAAgB,oBAAoB,OAAe,UAAgD;CAClG,IAAI,CAAE,OAA6B,SAAS,KAAK,GAAG,MAAM,eAAe,cAAc,EAAE,MAAM,CAAC;CAChG,OAAO,WAAW,MAAe,CAAC,QAAQ;AAC3C;AAOA,eAAsB,eAAe,SAA4C;CAEhF,MAAM,EAAE,aAAa,MAAM,OAAO;CAClC,CAAC,QAAQ,UAAU,QAAQ,OAAM,CAAE,MAAM,oBAAoB,QAAQ,OAAO,MAAM,iBAAiB,QAAQ,CAAC,CAAC;AAC9G;AAEA,0BAAe,cAAc;CAC5B,MAAM;EACL,MAAM;EACN,aAAa;CACd;CACA,MAAM,EACL,OAAO;EACN,MAAM;EACN,aAAa,uCAAuC,OAAO,KAAK,IAAI;EACpE,UAAU;CACX,EACD;CACA,MAAM,IAAI,EAAE,QAAQ;EACnB,MAAM,eAAe,EAAE,OAAO,KAAK,MAAM,CAAC;CAC3C;AACD,CAAC"}
1
+ {"version":3,"file":"completions-DMPlZ0S1.js","names":[],"sources":["../src/commands/completions.ts"],"sourcesContent":["import { defineCommand, type ArgsDef, type CommandDef } from 'citty';\nimport { cliDiagnostics } from '../utils/diagnostics.js';\n\n// citty types each command by its own arguments; the tree only needs the erased form.\n// oxlint-disable-next-line typescript/no-explicit-any\ntype AnyCommand = CommandDef<any>;\n\nexport interface CompletionFlag {\n\tname: string;\n\tdescription: string;\n\t/** Short forms, without the dash (`c` for `-c`). */\n\taliases: string[];\n\t/** A boolean that is on by default also has a `--no-<name>` form. */\n\tnegatable: boolean;\n}\n\nexport interface CompletionCommand {\n\tname: string;\n\tdescription: string;\n\tflags: CompletionFlag[];\n\tsubcommands: CompletionCommand[];\n}\n\nexport const SHELLS = ['bash', 'zsh', 'fish'] as const;\nexport type Shell = (typeof SHELLS)[number];\n\nasync function resolve<T>(value: T | Promise<T> | (() => T | Promise<T>) | undefined): Promise<T | undefined> {\n\treturn typeof value === 'function' ? (value as () => T | Promise<T>)() : value;\n}\n\n/** Walks the commands the CLI registers, so the completions never drift from what `--help` prints. */\nexport async function describeCommands(commands: Record<string, () => Promise<AnyCommand>>): Promise<CompletionCommand[]> {\n\tconst describe = async (name: string, command: AnyCommand): Promise<CompletionCommand> => {\n\t\tconst meta = (await resolve(command.meta)) ?? {};\n\t\tconst args = ((await resolve(command.args)) ?? {}) as ArgsDef;\n\t\tconst children = ((await resolve(command.subCommands)) ?? {}) as Record<string, AnyCommand | (() => Promise<AnyCommand>)>;\n\t\treturn {\n\t\t\tname,\n\t\t\tdescription: meta.description ?? '',\n\t\t\tflags: Object.entries(args)\n\t\t\t\t.filter(([, arg]) => arg.type !== 'positional')\n\t\t\t\t.map(([flag, arg]) => ({\n\t\t\t\t\tname: flag,\n\t\t\t\t\tdescription: arg.description ?? '',\n\t\t\t\t\taliases: [(arg as { alias?: string | string[] }).alias ?? []].flat(),\n\t\t\t\t\tnegatable: arg.type === 'boolean' && arg.default === true\n\t\t\t\t})),\n\t\t\tsubcommands: await Promise.all(Object.entries(children).map(async ([child, value]) => describe(child, (await resolve(value))!)))\n\t\t};\n\t};\n\n\treturn Promise.all(Object.entries(commands).map(async ([name, load]) => describe(name, await load())));\n}\n\n/** Every spelling of a flag: `--name`, `--no-name` when it can be switched off, and its short forms. */\nconst spellings = (flag: CompletionFlag) => [\n\t`--${flag.name}`,\n\t...(flag.negatable ? [`--no-${flag.name}`] : []),\n\t...flag.aliases.map((alias) => (alias.length === 1 ? `-${alias}` : `--${alias}`))\n];\n\nconst flagsOf = (command: CompletionCommand) => [...command.flags.flatMap(spellings), '--help'].join(' ');\n\nfunction bash(commands: readonly CompletionCommand[]): string {\n\tconst cases = commands.map((command) => {\n\t\tif (command.subcommands.length === 0) return `\\t\\t${command.name}) words=\"${flagsOf(command)}\" ;;`;\n\t\tconst nested = command.subcommands.map((child) => `\\t\\t\\t\\t${child.name}) words=\"${flagsOf(child)}\" ;;`).join('\\n');\n\t\treturn [\n\t\t\t`\\t\\t${command.name})`,\n\t\t\t// The subcommand is the first of its names after the command: options of the parent may come before it.\n\t\t\t'\\t\\t\\tsub=\"\"',\n\t\t\t'\\t\\t\\tfor ((i = 2; i < COMP_CWORD; i++)); do',\n\t\t\t`\\t\\t\\t\\tcase \"\\${COMP_WORDS[i]}\" in ${command.subcommands.map((child) => child.name).join('|')}) sub=\"\\${COMP_WORDS[i]}\"; break ;; esac`,\n\t\t\t'\\t\\t\\tdone',\n\t\t\t'\\t\\t\\tcase \"$sub\" in',\n\t\t\tnested,\n\t\t\t`\\t\\t\\t\\t*) words=\"${command.subcommands.map((child) => child.name).join(' ')} ${flagsOf(command)}\" ;;`,\n\t\t\t'\\t\\t\\tesac ;;'\n\t\t].join('\\n');\n\t});\n\n\treturn `# stars completions for bash. Load them with: eval \"$(stars completions bash)\"\n_stars() {\n\tlocal cur words sub i\n\tcur=\"\\${COMP_WORDS[COMP_CWORD]}\"\n\tif [ \"$COMP_CWORD\" -eq 1 ]; then\n\t\twords=\"${commands.map((command) => command.name).join(' ')} --help --version\"\n\telse\n\t\tcase \"\\${COMP_WORDS[1]}\" in\n${cases.join('\\n')}\n\t\t\t*) words=\"\" ;;\n\t\tesac\n\tfi\n\tCOMPREPLY=($(compgen -W \"$words\" -- \"$cur\"))\n}\ncomplete -o default -F _stars stars\n`;\n}\n\nconst quote = (text: string) => `'${text.replaceAll(\"'\", \"'\\\\''\")}'`;\n/** A zsh `_describe` entry: the colon separates the value from its description, so one in the text is escaped. */\nconst described = (name: string, description: string) => quote(`${name}:${description.replaceAll(':', '\\\\:')}`);\n\nfunction zsh(commands: readonly CompletionCommand[]): string {\n\tconst flags = (command: CompletionCommand) =>\n\t\t[\n\t\t\t...command.flags.flatMap((flag) => spellings(flag).map((spelling) => described(spelling, flag.description))),\n\t\t\tdescribed('--help', 'Show the usage')\n\t\t].join(' ');\n\tconst cases = commands.map((command) => {\n\t\tif (command.subcommands.length === 0) return `\\t\\t${command.name}) items=(${flags(command)}) ;;`;\n\t\tconst nested = command.subcommands.map((child) => `\\t\\t\\t\\t${child.name}) items=(${flags(child)}) ;;`).join('\\n');\n\t\tconst children = command.subcommands.map((child) => described(child.name, child.description)).join(' ');\n\t\treturn [\n\t\t\t`\\t\\t${command.name})`,\n\t\t\t'\\t\\t\\tsub=\"\"',\n\t\t\t'\\t\\t\\tfor word in ${words[3,CURRENT-1]}; do',\n\t\t\t`\\t\\t\\t\\tcase \"$word\" in ${command.subcommands.map((child) => child.name).join('|')}) sub=\"$word\"; break ;; esac`,\n\t\t\t'\\t\\t\\tdone',\n\t\t\t'\\t\\t\\tcase \"$sub\" in',\n\t\t\tnested,\n\t\t\t`\\t\\t\\t\\t*) items=(${children} ${flags(command)}) ;;`,\n\t\t\t'\\t\\t\\tesac ;;'\n\t\t].join('\\n');\n\t});\n\n\treturn `#compdef stars\n# stars completions for zsh. Load them with: eval \"$(stars completions zsh)\"\n_stars() {\n\tlocal -a items\n\tlocal sub word\n\tif (( CURRENT == 2 )); then\n\t\titems=(${commands.map((command) => described(command.name, command.description)).join(' ')})\n\telse\n\t\tcase \"$words[2]\" in\n${cases.join('\\n')}\n\t\tesac\n\tfi\n\t_describe 'stars' items\n}\ncompdef _stars stars\n`;\n}\n\nfunction fishFlag(condition: string, flag: CompletionFlag): string[] {\n\tconst short = flag.aliases\n\t\t.filter((alias) => alias.length === 1)\n\t\t.map((alias) => ` -s ${alias}`)\n\t\t.join('');\n\tconst line = (name: string) => `complete -c stars -n \"${condition}\" -l ${name}${name === flag.name ? short : ''} -d ${quote(flag.description)}`;\n\treturn [line(flag.name), ...(flag.negatable ? [line(`no-${flag.name}`)] : [])];\n}\n\nfunction fish(commands: readonly CompletionCommand[]): string {\n\tconst lines = ['# stars completions for fish. Load them with: stars completions fish | source', 'complete -c stars -f'];\n\tconst names = commands.map((command) => command.name).join(' ');\n\tfor (const command of commands) {\n\t\tlines.push(`complete -c stars -n \"not __fish_seen_subcommand_from ${names}\" -a ${command.name} -d ${quote(command.description)}`);\n\t\tconst children = command.subcommands.map((child) => child.name).join(' ');\n\t\tfor (const flag of command.flags) lines.push(...fishFlag(`__fish_seen_subcommand_from ${command.name}`, flag));\n\n\t\tfor (const child of command.subcommands) {\n\t\t\tlines.push(\n\t\t\t\t`complete -c stars -n \"__fish_seen_subcommand_from ${command.name}; and not __fish_seen_subcommand_from ${children}\" -a ${child.name} -d ${quote(child.description)}`\n\t\t\t);\n\t\t\tfor (const flag of child.flags.filter((candidate) => !command.flags.some((own) => own.name === candidate.name))) {\n\t\t\t\tlines.push(...fishFlag(`__fish_seen_subcommand_from ${command.name}; and __fish_seen_subcommand_from ${child.name}`, flag));\n\t\t\t}\n\t\t}\n\t}\n\n\treturn `${lines.join('\\n')}\\n`;\n}\n\nconst GENERATORS: Record<Shell, (commands: readonly CompletionCommand[]) => string> = { bash, zsh, fish };\n\n/** The completion script of a shell, for the given commands. */\nexport function generateCompletions(shell: string, commands: readonly CompletionCommand[]): string {\n\tif (!(SHELLS as readonly string[]).includes(shell)) throw cliDiagnostics.UNKNOWN_SHELL({ shell });\n\treturn GENERATORS[shell as Shell](commands);\n}\n\nexport interface CompletionsOptions {\n\tshell: string;\n\tstdout?: NodeJS.WritableStream;\n}\n\nexport async function runCompletions(options: CompletionsOptions): Promise<void> {\n\t// Imported here: the registry imports this module, as it does every command.\n\tconst { commands } = await import('./index.js');\n\t(options.stdout ?? process.stdout).write(generateCompletions(options.shell, await describeCommands(commands)));\n}\n\nexport default defineCommand({\n\tmeta: {\n\t\tname: 'completions',\n\t\tdescription: 'Print the shell completion script for bash, zsh or fish'\n\t},\n\targs: {\n\t\tshell: {\n\t\t\ttype: 'positional',\n\t\t\tdescription: `The shell to print completions for: ${SHELLS.join(', ')}`,\n\t\t\trequired: true\n\t\t}\n\t},\n\tasync run({ args }) {\n\t\tawait runCompletions({ shell: args.shell });\n\t}\n});\n"],"mappings":";;;;AAuBA,MAAa,SAAS;CAAC;CAAQ;CAAO;AAAM;AAG5C,eAAe,QAAW,OAAoF;CAC7G,OAAO,OAAO,UAAU,aAAc,MAA+B,IAAI;AAC1E;;AAGA,eAAsB,iBAAiB,UAAmF;CACzH,MAAM,WAAW,OAAO,MAAc,YAAoD;EACzF,MAAM,OAAQ,MAAM,QAAQ,QAAQ,IAAI,KAAM,CAAC;EAC/C,MAAM,OAAS,MAAM,QAAQ,QAAQ,IAAI,KAAM,CAAC;EAChD,MAAM,WAAa,MAAM,QAAQ,QAAQ,WAAW,KAAM,CAAC;EAC3D,OAAO;GACN;GACA,aAAa,KAAK,eAAe;GACjC,OAAO,OAAO,QAAQ,IAAI,CAAC,CACzB,QAAQ,GAAG,SAAS,IAAI,SAAS,YAAY,CAAC,CAC9C,KAAK,CAAC,MAAM,UAAU;IACtB,MAAM;IACN,aAAa,IAAI,eAAe;IAChC,SAAS,CAAE,IAAsC,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK;IACnE,WAAW,IAAI,SAAS,aAAa,IAAI,YAAY;GACtD,EAAE;GACH,aAAa,MAAM,QAAQ,IAAI,OAAO,QAAQ,QAAQ,CAAC,CAAC,IAAI,OAAO,CAAC,OAAO,WAAW,SAAS,OAAQ,MAAM,QAAQ,KAAK,CAAG,CAAC,CAAC;EAChI;CACD;CAEA,OAAO,QAAQ,IAAI,OAAO,QAAQ,Q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,UAAU,QAAQ,OAAM,CAAE,MAAM,oBAAoB,QAAQ,OAAO,MAAM,iBAAiB,QAAQ,CAAC,CAAC;AAC9G;AAEA,0BAAe,cAAc;CAC5B,MAAM;EACL,MAAM;EACN,aAAa;CACd;CACA,MAAM,EACL,OAAO;EACN,MAAM;EACN,aAAa,uCAAuC,OAAO,KAAK,IAAI;EACpE,UAAU;CACX,EACD;CACA,MAAM,IAAI,EAAE,QAAQ;EACnB,MAAM,eAAe,EAAE,OAAO,KAAK,MAAM,CAAC;CAC3C;AACD,CAAC"}
@@ -8,7 +8,7 @@ import { n as createBuilder, t as Locales } from "./locales-BJAP4HYf.js";
8
8
  import { c as moduleImportArgs, d as resolveCwd, l as collectFlag, n as loadProject, r as withProjectEnv, s as envImportArgs, t as applyEnvOptions, u as projectArgs } from "./hooks-Cy6F2bhH.js";
9
9
  import { n as reportWarnings, t as prepareProject } from "./_shared-BIQK0Bhm.js";
10
10
  import { r as diffSnapshots, t as describeCommand } from "./command-diff-BK912Hjc.js";
11
- import { i as bridgeImportArgs, n as CLI_SOURCE, o as parseBridgeMessage, s as Tunnel } from "./bridge-BvkmlAOZ.js";
11
+ import { i as bridgeImportArgs, n as CLI_SOURCE, o as parseBridgeMessage, s as Tunnel } from "./bridge-BegCt_n2.js";
12
12
  import { a as initialLogView, s as isLogLevel, x as classifyAppLine, y as LogBuffer } from "./log-view-B7uJEnMR.js";
13
13
  import { defineCommand } from "citty";
14
14
  import { createWriteStream, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
@@ -1166,4 +1166,4 @@ var dev_default = defineCommand({
1166
1166
 
1167
1167
  //#endregion
1168
1168
  export { dev_default as default };
1169
- //# sourceMappingURL=dev-oPPVR7d_.js.map
1169
+ //# sourceMappingURL=dev-Owu3e3AO.js.map