mirror of
https://github.com/stack-auth/stack.git
synced 2026-06-21 21:09:49 +08:00
## What & why
Re-running `stack dev` / `hexclave dev` now picks up the **latest
published dashboard without reinstalling the CLI**.
In the RDE, the dashboard is a Next.js standalone build **bundled into
the `@hexclave/cli` npm tarball** — so a dashboard change only reaches a
user when they get a newer CLI *version*. This PR closes that gap for
the recommended `stack dev` flow.
## How it works
1. **npx self-re-exec** — at the top of the `dev` action, the CLI checks
npm for a newer `@hexclave/cli`. If found, it re-execs `npx --yes -p
@hexclave/cli@<latest> stack dev <your args>` (with a loop guard) and
exits with the child's code. The running code — and the dashboard
bundled in that tarball — is now the latest; the user's installed
devDependency is untouched. npx caches per version, so steady-state runs
are fast.
2. **Dashboard version handshake** (the necessary second half) — `stack
dev` keeps a **detached background dashboard** alive across runs and
reuses it by default, which would otherwise silently defeat the update.
The now-latest process compares the running dashboard's version
(persisted in dev-env state) against its own and **kills + restarts**
the stale one (SIGTERM → wait → SIGKILL) so the new dashboard actually
binds `:26700`. Equal/older/unknown versions are reused exactly as
before.
## Safety / opt-outs
- Skipped for the re-exec'd child (`STACK_CLI_SKIP_AUTO_UPDATE`, loop
guard), when the user opts out (`STACK_CLI_NO_AUTO_UPDATE` /
`--no-auto-update`), and in CI (`CI`).
- Registry lookup is TTL-cached in dev-env state with a short timeout
and is **offline-safe** — any failure (no network, no npx) falls through
to the installed CLI.
- `isVersionNewer` never downgrades and returns false for unparseable
versions.
## Changes
- **`packages/stack-cli/src/lib/self-update.ts`** (new) —
`maybeReexecToLatest()`, `resolveLatestVersion()`, `isVersionNewer()`,
`buildNpxInvocation()`.
- **`packages/stack-cli/src/commands/dev.ts`** — re-exec wiring,
`killLocalDashboard()`, version handshake, `--no-auto-update` flag,
version stamp on the recorded dashboard process.
- **`packages/stack-cli/src/lib/dev-env-state.ts`** —
`localDashboard.version` + `cliUpdateCheck` cache helpers.
- Tests: new `self-update.test.ts` + additions to
`dev-env-state.test.ts`.
## Verification
- `pnpm --filter @hexclave/cli run lint` ✅
- `pnpm --filter @hexclave/cli run typecheck` ✅
- `pnpm --filter @hexclave/cli run test` ✅ (132 passed)
## Prerequisite
Relies on `@hexclave/cli` being published to npm with the `latest`
dist-tag tracking releases — otherwise the check is a no-op (which is
safe).
<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
`hexclave dev` now re-execs via `npx` to run the latest `@hexclave/cli`,
so the bundled RDE dashboard stays current without reinstalling. It
reuses the running dashboard and only restarts it when the current CLI
is strictly newer.
- **New Features**
- Auto-update: always re-execs `npx --yes --min-release-age=0 -p
@hexclave/cli@latest hexclave dev ...`; runs in CI; opt out with
`--no-auto-update` or `STACK_CLI_NO_AUTO_UPDATE=1`.
- Per-port dashboard version handshake: records the CLI version per port
and restarts only when strictly newer; otherwise reuses it (respects
`NEXT_PUBLIC_HEXCLAVE_LOCAL_DASHBOARD_PORT`).
- **Bug Fixes**
- Safer restarts: after SIGTERM, wait for the port to free instead of
pid probes; bail on ESRCH/EPERM; only SIGKILL if the port still answers.
- Robust execution: ship a single `hexclave` bin (fixes `pnpx`/`pnpm
dlx`), forward SIGINT/SIGTERM to children, validate per-port dashboard
state, update help/messages to `hexclave`, and make Windows re-exec
reliable (`npx.cmd` with shell and argv quoting).
<sup>Written for commit 80c9b30a5c.
Summary will update on new commits.</sup>
<a
href="https://cubic.dev/pr/hexclave/hexclave/pull/1521?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **New Features**
* CLI can auto-check and re-exec to a pinned newer release (opt-out:
--no-auto-update).
* Local dashboard startup is version-aware and only restarts when the
CLI is strictly newer.
* Improved child-process signal forwarding for cleaner shutdowns.
* **Tests**
* Expanded unit tests covering dev workflow, self-update, package
metadata, persistence, and dashboard lifecycle.
* **Bug Fixes**
* Updated user-facing CLI messaging to use "hexclave" command names.
* **Chores**
* Removed legacy docs workspace entry.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: Konstantin Wohlwend <n2d4xc@gmail.com>
97 lines
4.0 KiB
TypeScript
97 lines
4.0 KiB
TypeScript
import { Command } from "commander";
|
|
import { isProjectAuthWithRefreshToken, resolveAuth, resolveLocalEmulatorAuth, type ProjectAuthWithRefreshToken } from "../lib/auth.js";
|
|
import { lookupLocalEmulatorProjectIdByPath } from "../lib/local-emulator-client.js";
|
|
import { getAdminProject } from "../lib/app.js";
|
|
import { CliError } from "../lib/errors.js";
|
|
import { resolveConfigFilePathOption } from "../lib/config-file-path.js";
|
|
|
|
function getErrorMessage(err: unknown): string {
|
|
if (err instanceof Error) {
|
|
return err.message;
|
|
}
|
|
if (typeof err === "string") {
|
|
return err;
|
|
}
|
|
try {
|
|
return JSON.stringify(err);
|
|
} catch {
|
|
return String(err);
|
|
}
|
|
}
|
|
|
|
export type ExecTargetOpts = {
|
|
cloudProjectId?: string,
|
|
configFile?: string,
|
|
};
|
|
|
|
export type ExecTarget =
|
|
| { kind: "cloud", projectId: string }
|
|
| { kind: "config", configFile: string };
|
|
|
|
// Validate that exactly one of --cloud-project-id / --config-file was provided
|
|
// and return a tagged target. Both branches are mutually exclusive; passing
|
|
// neither (or both) is rejected so the user has to make the cloud-vs-local
|
|
// choice explicit at every invocation.
|
|
export function parseExecTarget(opts: ExecTargetOpts): ExecTarget {
|
|
const hasCloud = opts.cloudProjectId != null && opts.cloudProjectId !== "";
|
|
const hasConfig = opts.configFile != null && opts.configFile !== "";
|
|
if (hasCloud && hasConfig) {
|
|
throw new CliError("Pass either --cloud-project-id or --config-file, not both.");
|
|
}
|
|
if (!hasCloud && !hasConfig) {
|
|
throw new CliError("Specify a target: pass --cloud-project-id <id> for the Hexclave cloud API, or --config-file <path> for the development environment.");
|
|
}
|
|
if (hasCloud) {
|
|
return { kind: "cloud", projectId: opts.cloudProjectId as string };
|
|
}
|
|
return { kind: "config", configFile: opts.configFile as string };
|
|
}
|
|
|
|
export function registerExecCommand(program: Command) {
|
|
program
|
|
.command("exec [javascript]")
|
|
.description("Execute JavaScript with a pre-configured StackServerApp as `hexclaveServerApp`. Pass --cloud-project-id <id> for the cloud API, or --config-file <path> for the development environment.")
|
|
.option("--cloud-project-id <id>", "Cloud project ID to run against (use --config-file instead for the development environment)")
|
|
.option("--config-file <path>", "Path to a development-environment stack.config.ts (use --cloud-project-id instead for the cloud API)")
|
|
.addHelpText("after", "\nFor available API methods, see: https://docs.hexclave.com/sdk/overview")
|
|
.action(async (javascript: string | undefined, opts: ExecTargetOpts) => {
|
|
if (javascript === undefined) {
|
|
throw new CliError("Missing JavaScript argument. Use `hexclave exec \"<javascript>\"` or `hexclave exec --help`.");
|
|
}
|
|
|
|
const target = parseExecTarget(opts);
|
|
let auth: ProjectAuthWithRefreshToken;
|
|
if (target.kind === "cloud") {
|
|
const cloudAuth = resolveAuth(target.projectId);
|
|
if (!isProjectAuthWithRefreshToken(cloudAuth)) {
|
|
throw new CliError("`hexclave exec --cloud-project-id` requires `hexclave login`. Remove STACK_SECRET_SERVER_KEY and try again.");
|
|
}
|
|
auth = cloudAuth;
|
|
} else {
|
|
const absPath = resolveConfigFilePathOption(target.configFile, { mustExist: true });
|
|
const projectId = await lookupLocalEmulatorProjectIdByPath(absPath);
|
|
auth = await resolveLocalEmulatorAuth(projectId);
|
|
}
|
|
const project = await getAdminProject(auth);
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
|
const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
|
|
let fn;
|
|
try {
|
|
fn = new AsyncFunction("hexclaveServerApp", javascript);
|
|
} catch (err: unknown) {
|
|
throw new CliError(`Syntax error in exec code: ${getErrorMessage(err)}`);
|
|
}
|
|
let result;
|
|
try {
|
|
result = await fn(project.app);
|
|
} catch (err: unknown) {
|
|
throw new CliError(`Exec error: ${getErrorMessage(err)}`);
|
|
}
|
|
|
|
if (result !== undefined) {
|
|
console.log(JSON.stringify(result, null, 2));
|
|
}
|
|
});
|
|
}
|