From 12ed997149c8eee1f47ef5040ab56cca1ea8cb52 Mon Sep 17 00:00:00 2001 From: dbjpanda Date: Tue, 13 Oct 2026 02:05:56 +0530 Subject: [PATCH 1/2] feat(cli): dev --run shows the backend and the app in tabs; init asks for a project name - concile dev --run opens a tab per process (mprocs) in a terminal; plain prefixed lines in CI, agents and pipes - the app waits for the backend; @concile/vite proxies to a running backend via CONCILE_DEV_BACKEND - React + Vite starter runs concile dev --run vite; init starts an existing app's dev script next to the backend - init asks for a project name on one line and no longer lists other folders - boxed brand banner; SQLite ExperimentalWarning hidden - scripts/try-local.sh tests init with locally packed packages - docs and site: npx concile init is the start command --- .changeset/dev-tabs.md | 6 + .changeset/init-project-name.md | 5 + README.md | 8 +- bun.lock | 4 + docs/core-concepts/cli.mdx | 20 +++ docs/deploy/local-dev.mdx | 4 +- docs/deploy/vite-plugin.mdx | 32 +++- docs/get-started/quickstart.mdx | 17 +- packages/cli/package.json | 6 +- packages/cli/src/bin.ts | 10 ++ packages/cli/src/cli.ts | 14 +- packages/cli/src/dev-tabs.ts | 101 +++++++++++ packages/cli/src/init/apply.ts | 37 +++- packages/cli/src/init/banner.ts | 158 ++++++++++++------ packages/cli/src/init/command.ts | 91 +++++----- packages/cli/src/init/detect.ts | 9 - packages/cli/src/init/prompts.ts | 62 ++++--- packages/cli/templates/vite/package.json | 2 +- packages/cli/test/dev-tabs.test.ts | 53 ++++++ packages/cli/test/init/banner.test.ts | 75 ++++++--- packages/cli/test/init/command.test.ts | 101 +++++++---- packages/cli/test/init/detect.test.ts | 12 +- packages/cli/test/init/local-packages.test.ts | 39 +++++ packages/cli/test/init/prompts.test.ts | 4 +- packages/cli/test/init/templates.test.ts | 4 +- packages/vite/README.md | 2 +- packages/vite/src/index.ts | 6 +- packages/vite/test/plugin.test.ts | 15 ++ scripts/try-local.sh | 46 +++++ www/app/(home)/Hero.tsx | 4 +- www/app/(home)/page.tsx | 2 +- www/components/brand-poster.tsx | 2 +- 32 files changed, 720 insertions(+), 231 deletions(-) create mode 100644 .changeset/dev-tabs.md create mode 100644 .changeset/init-project-name.md create mode 100644 packages/cli/src/dev-tabs.ts create mode 100644 packages/cli/test/dev-tabs.test.ts create mode 100644 packages/cli/test/init/local-packages.test.ts create mode 100755 scripts/try-local.sh diff --git a/.changeset/dev-tabs.md b/.changeset/dev-tabs.md new file mode 100644 index 00000000..7ae521ed --- /dev/null +++ b/.changeset/dev-tabs.md @@ -0,0 +1,6 @@ +--- +"@concile/cli": patch +"@concile/vite": patch +--- + +`concile dev --run ""` shows the backend and your app in separate tabs, so each one's output and URL stay apart. The app starts once the backend is up. The React + Vite starter now runs `concile dev --run vite`, and the `@concile/vite` plugin proxies to that backend instead of starting a second one. `concile init` in an existing app starts its own dev script next to the backend. Without a terminal, or with `CONCILE_TABS=0`, output stays as prefixed lines. The SQLite ExperimentalWarning no longer prints. diff --git a/.changeset/init-project-name.md b/.changeset/init-project-name.md new file mode 100644 index 00000000..4171382c --- /dev/null +++ b/.changeset/init-project-name.md @@ -0,0 +1,5 @@ +--- +"@concile/cli": patch +--- + +`concile init` asks for a project name on one line, like create-convex, with an editable default. `.` uses the current folder when it is empty. It no longer lists other folders. The banner is redrawn in the brand style. diff --git a/README.md b/README.md index 4f46dab1..7275a554 100644 --- a/README.md +++ b/README.md @@ -75,13 +75,15 @@ You didn't have to write a websocket server. You didn't write a REST endpoint. Y npx concile init ``` -Run it in an empty folder to get a starter app, or inside the app you already have. It asks a couple of quick questions, shows every file it will add, and changes nothing until you say yes. Want a new folder? Run `npx concile init my-app`. Then: +Run it in an existing app, and it configures Concile there. Run it in an empty directory, and it prompts for a project name to set up a starter app. Type `.` at that prompt to use the current directory. It lists every file it will touch and waits for your confirmation before writing anything. Then start the dev environment: ```bash -npx concile dev +npm run dev ``` -Got a starter app? Run `npm run dev` instead. It starts the app and the backend together. Open it in two browser tabs (http://localhost:5173 for React + Vite, http://localhost:3001 for Next.js). Type in one. It shows up in the other. +Your app and the backend boot together in separate terminal tabs. Open http://localhost:5173 for React + Vite, or http://localhost:3001 for Next.js, across two browser windows. Type a message in one window, and it appears in the other. + +Adding Concile to an existing project? Run `npx concile dev --run "npm run dev"` to spin up your dev script alongside the backend. If you only need the backend running, use `npx concile dev`. Need the flags for scripts or CI? Run `npx concile init --yes`, or see `npx concile init --help`. diff --git a/bun.lock b/bun.lock index ecb87f14..72ccf4fd 100644 --- a/bun.lock +++ b/bun.lock @@ -418,6 +418,7 @@ "concile": "./dist/bin.js", }, "dependencies": { + "@clack/core": "^1.5.1", "@clack/prompts": "^1.8.1", "@concile/admin": "workspace:*", "@concile/blobstore": "workspace:*", @@ -444,6 +445,7 @@ "@concile/values": "workspace:*", "esbuild": "^0.27.0", "magicast": "^0.5.5", + "mprocs": "0.9.6", "ws": "^8.18.0", }, "devDependencies": { @@ -1925,6 +1927,8 @@ "mlly": ["mlly@1.8.2", "", { "dependencies": { "acorn": "^8.16.0", "pathe": "^2.0.3", "pkg-types": "^1.3.1", "ufo": "^1.6.3" } }, "sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA=="], + "mprocs": ["mprocs@0.9.6", "", { "bin": { "mprocs": "cli.js" } }, "sha512-sEwB5XD3/rReB47h0YbN2L5fXOLcMjF8sOEDTMr/daCLyVZfU4CegbanxO0ybiaFx0MQ/nV7yzOHmprmy2Wq9w=="], + "mri": ["mri@1.2.0", "", {}, "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA=="], "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], diff --git a/docs/core-concepts/cli.mdx b/docs/core-concepts/cli.mdx index 3308d75a..18bfaadc 100644 --- a/docs/core-concepts/cli.mdx +++ b/docs/core-concepts/cli.mdx @@ -59,12 +59,32 @@ concile dev | `--storage-bucket ` | `CONCILE_STORAGE_BUCKET` env, else unset (filesystem) | Select the S3-compatible file-storage backend, see [File storage](/docs/core-concepts/file-storage) | | `--storage-endpoint ` | `CONCILE_STORAGE_ENDPOINT` env, else unset | S3-compatible endpoint (MinIO, R2, …) | | `--web ` | unset | Serve a static web UI directory at the site root, alongside the API | +| `--run ""` | unset | Start your frontend dev command next to the backend, see [Run your app alongside](#run-your-app-alongside) | +| `--no-ui` | unset | Plain output: no terminal dashboard and no `--run` tabs | The database and storage settings fall back to the same environment variables under `dev` as under `serve`: `CONCILE_DATABASE_URL`, `CONCILE_STORAGE_BUCKET`, and `CONCILE_STORAGE_ENDPOINT` (plus the rest of the `CONCILE_STORAGE_*` family) all work, with the flag winning when both are set. Both commands resolve storage through the same boot path. +### Run your app alongside + +Pass `--run ""` to launch your frontend dev server alongside the backend from a single command: + +```bash +concile dev --run "npm run dev" +``` + +The app waits to launch until the backend starts listening, avoiding port conflicts. Concile also +exposes the backend URL to your app through `CONCILE_DEV_BACKEND`. In an interactive terminal, the +app and backend run in dedicated tabs. Press `j` and `k` to cycle through tabs, `r` to restart the +active process, and `q` to quit both. In non-interactive environments like CI, under coding agents, +or when piping stdout, the tab interface is disabled. Logs from the app stream inline with an `app +│` prefix. Pass `--no-ui` or set `CONCILE_TABS=0` to force this view in a regular terminal. + +Both starter templates rely on this pattern. The React + Vite starter runs `concile dev --run vite` +inside `npm run dev`, while the Next.js starter runs `concile dev --run "next dev -p 3001"`. + ### Admin key handling `dev` reads `CONCILE_ADMIN_KEY` if set (blank/whitespace-only counts as unset, with a warning). If diff --git a/docs/deploy/local-dev.mdx b/docs/deploy/local-dev.mdx index 8c3059da..5e89efbd 100644 --- a/docs/deploy/local-dev.mdx +++ b/docs/deploy/local-dev.mdx @@ -66,8 +66,8 @@ Here is a look at every flag `concile dev` accepts: | `--database-url ` | unset | Takes a `postgres://` or `postgresql://` connection string. When this is set, concile uses Postgres instead of SQLite; see [Postgres](/docs/deploy/postgres) for more. It can also be read from `CONCILE_DATABASE_URL`, though the flag takes priority. | | `--storage-bucket ` | unset | Selects the S3-compatible file storage backend (using a bucket name). If left unset, it uses local filesystem storage under `/storage`. It can also be read from `CONCILE_STORAGE_BUCKET`. | | `--storage-endpoint ` | unset | Sets an S3-compatible endpoint (like MinIO, R2, etc.), which only matters if you also use `--storage-bucket`. It can also be read from `CONCILE_STORAGE_ENDPOINT`. | -| `--run ""` | unset | Starts your frontend dev command next to the backend, so one command runs both. For example `--run "next dev -p 3001"`. Its output shows with an `app │` prefix, and it stops when `concile dev` stops. The Next.js starter's `npm run dev` uses this. | -| `--no-ui` | unset | Turns off the full-screen terminal dashboard (Bun only) and prints plain lines. `--run` turns it off too. | +| `--run ""` | unset | Starts your frontend dev command next to the backend, so one command runs both. For example `--run "next dev -p 3001"`. The app starts once the backend is up. In a terminal, each one gets its own tab: `j`/`k` switch, `r` restarts, `q` quits both. In CI, agents and pipes, or with `CONCILE_TABS=0`, the app's lines show with an `app │` prefix instead. Both starters' `npm run dev` use this. | +| `--no-ui` | unset | Turns off the full-screen terminal dashboard (Bun only) and the `--run` tabs, and prints plain lines. | A CLI flag will always override its environment variable equivalent if both are set. diff --git a/docs/deploy/vite-plugin.mdx b/docs/deploy/vite-plugin.mdx index 3b8ebb4c..dc61ad5f 100644 --- a/docs/deploy/vite-plugin.mdx +++ b/docs/deploy/vite-plugin.mdx @@ -79,6 +79,14 @@ That's the entire configuration. You do not need to add any options. npx vite ``` + + +If you run `concile dev --run vite`, the backend is already active in its own tab. The plugin reads +`CONCILE_DEV_BACKEND` and routes requests to that existing instance instead of booting a new one. +The React + Vite starter uses this setup out of the box. + + + The backend starts up right along with the dev server. You will see its log lines appear in the same terminal, prefixed with `[concile]`. Open your app at the Vite URL, and you'll find the engine's surfaces are there too, all on the very same origin: @@ -180,49 +188,57 @@ are specific to one mode and simply ignored by the other. type: '"proxy" | "embed"', default: '"proxy"', description: - 'How the backend runs alongside Vite. "proxy" spawns concile dev as a child and proxies to it; "embed" boots the engine inside Vite\'s own process.', + 'How the backend runs alongside Vite. "proxy" spawns concile dev as a child and proxies to +it; "embed" boots the engine inside Vite\'s own process.', }, functionsDir: { type: "string", default: '"concile"', description: - "Where your schema and functions live, relative to the Vite root. Passed to the backend as --dir. Shared by both modes.", + "Where your schema and functions live, relative to the Vite root. Passed to the backend as +--dir. Shared by both modes.", }, port: { type: "number", default: "an OS-assigned free port", description: - "Proxy mode only: the port the spawned concile dev listens on (the browser never sees it; everything goes through Vite's port).", + "Proxy mode only: the port the spawned concile dev listens on (the browser never sees it; +everything goes through Vite's port).", }, command: { type: "string", default: 'local node_modules/.bin/concile, else "npx concile"', description: - "Proxy mode only: how to invoke the CLI. A whitespace-split command string, e.g. \"bun concile\".", + "Proxy mode only: how to invoke the CLI. A whitespace-split command string, e.g. \"bun +concile\".", }, args: { type: "string[]", default: "[]", description: - 'Proxy mode only: extra flags appended to concile dev, e.g. ["--database-url", "postgres://..."].', + 'Proxy mode only: extra flags appended to concile dev, e.g. ["--database-url", +"postgres://..."].', }, dataPath: { type: "string", default: "/.concile/dev.db", description: - "Embed mode only: the SQLite database file for the in-process engine, resolved against the Vite root.", + "Embed mode only: the SQLite database file for the in-process engine, resolved against the +Vite root.", }, databaseUrl: { type: "string", default: "unset (SQLite)", description: - "Embed mode only: a postgres:// connection string. When set, the in-process engine uses Postgres instead of SQLite.", + "Embed mode only: a postgres:// connection string. When set, the in-process engine uses +Postgres instead of SQLite.", }, adminKey: { type: "string", default: "a per-run ephemeral key", description: - "Embed mode only: the admin key protecting the in-process engine's /_admin API and dashboard.", + "Embed mode only: the admin key protecting the in-process engine's /_admin API and +dashboard.", }, }} /> diff --git a/docs/get-started/quickstart.mdx b/docs/get-started/quickstart.mdx index 65b718db..249f6325 100644 --- a/docs/get-started/quickstart.mdx +++ b/docs/get-started/quickstart.mdx @@ -26,9 +26,10 @@ npx concile init my-app cd my-app ``` -`init` creates the folder and a `concile/` directory with a sample `messages` table, query and -mutation. It also installs the packages. Already have an app? Run `npx concile init` inside it -instead. To see every option, run `npx concile init --help`. +`init` generates the project folder, sets up a `concile/` directory with a sample `messages` schema, +query, and mutation, and installs dependencies. In an empty folder, run `npx concile init` without a +name, and it prompts you for one. Type `.` to use that folder. Working in an existing project? Run +`npx concile init` directly in that repo. Run `npx concile init --help` to view all available flags. @@ -36,7 +37,8 @@ instead. To see every option, run `npx concile init --help`. ## Define a schema -`init` already wrote `concile/schema.ts`. Here is what is in it. It lists your tables and the shape of each row: +`init` already wrote `concile/schema.ts`. Here is what is in it. It lists your tables and the shape +of each row: ```ts title="concile/schema.ts" import { defineSchema, defineTable, v } from "@concile/values"; @@ -107,9 +109,10 @@ admin key → 3q2xN7vRkYw8pTzL5mA9cB1dE6fGhJ0u The admin key is a fresh random value on each run (unless you set `CONCILE_ADMIN_KEY` yourself). Yours will differ. -Did `init` give you a starter app? Run `npm run dev` instead. It starts the app and the backend -together. Then open it in two browser tabs: http://localhost:5173 for React + Vite, -http://localhost:3001 for Next.js. +If you generated a starter app with `init`, run `npm run dev`. This boots both your app and the +backend in separate terminal tabs. Use `j` and `k` to toggle between tabs, and hit `q` to shut down +both processes. Next, open your app across two browser windows: http://localhost:5173 for React + +Vite, or http://localhost:3001 for Next.js. diff --git a/packages/cli/package.json b/packages/cli/package.json index ca1aeabf..184dc6b2 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -38,6 +38,7 @@ "clean": "rm -rf dist .turbo" }, "dependencies": { + "@clack/core": "^1.5.1", "@clack/prompts": "^1.8.1", "@concile/admin": "workspace:*", "@concile/blobstore": "workspace:*", @@ -45,6 +46,7 @@ "@concile/blobstore-s3": "workspace:*", "@concile/codegen": "workspace:*", "@concile/component": "workspace:*", + "@concile/dashboard": "workspace:*", "@concile/deploy": "workspace:*", "@concile/docstore": "workspace:*", "@concile/docstore-postgres": "workspace:*", @@ -63,8 +65,8 @@ "@concile/values": "workspace:*", "esbuild": "^0.27.0", "magicast": "^0.5.5", - "ws": "^8.18.0", - "@concile/dashboard": "workspace:*" + "mprocs": "0.9.6", + "ws": "^8.18.0" }, "devDependencies": { "@electric-sql/pglite": "^0.2.17", diff --git a/packages/cli/src/bin.ts b/packages/cli/src/bin.ts index b25dd4f2..bbc026ba 100644 --- a/packages/cli/src/bin.ts +++ b/packages/cli/src/bin.ts @@ -1,6 +1,16 @@ #!/usr/bin/env node import { runCli } from "./cli"; +// node:sqlite prints an ExperimentalWarning on every start. It says nothing users can act on, so +// it is dropped; every other warning still shows. +const emitWarning = process.emitWarning.bind(process); +process.emitWarning = ((warning: string | Error, ...rest: unknown[]) => { + const message = typeof warning === "string" ? warning : warning.message; + const type = typeof rest[0] === "string" ? rest[0] : (rest[0] as { type?: string } | undefined)?.type; + if (type === "ExperimentalWarning" && message.includes("SQLite")) return; + return (emitWarning as (...a: unknown[]) => void)(warning, ...rest); +}) as typeof process.emitWarning; + runCli(process.argv.slice(2)) .then((code) => process.exit(code)) .catch((e) => { diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index ccb624d2..2d385383 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -25,6 +25,7 @@ import { fleetCommand } from "./fleet"; import { objectstoreCommand } from "./objectstore"; import { loadEnvFiles } from "./env-files"; import { runAlongside } from "./run-alongside"; +import { afterBackend, backendUrl, BACKEND_ENV, mprocsBinary, runInTabs, wantTabs } from "./dev-tabs"; function parseFlags(args: string[]): DevOptions { const out: DevOptions = {}; @@ -46,6 +47,15 @@ function parseFlags(args: string[]): DevOptions { export async function devCommand(args: string[]): Promise { const flags = parseFlags(args); + // --run in a real terminal: the backend and the app each get a tab. This process only hosts them. + if (flags.run && wantTabs({ noUi: flags.noUi, env: process.env, stdinTTY: Boolean(process.stdin.isTTY), stdoutTTY: Boolean(process.stdout.isTTY) })) { + const binary = mprocsBinary(); + if (binary) { + const { port, ip } = resolveDevOptions(flags); + const devArgs = args.filter((a, i) => a !== "--run" && args[i - 1] !== "--run"); + return runInTabs(binary, { devArgs, run: flags.run, cwd: process.cwd(), url: backendUrl(ip, port) }); + } + } // Before anything reads the environment: .env.local, then .env, never overriding a set variable. loadEnvFiles(flags.functionsDir ? dirname(resolve(process.cwd(), flags.functionsDir)) : process.cwd()); const { functionsDir, projectRoot } = await resolveFunctionsDir(flags.functionsDir, process.cwd()); @@ -113,7 +123,7 @@ export async function devCommand(args: string[]): Promise { // --run: the frontend dev server, started after the backend is listening so it can connect at once. if (flags.run) { - const app = runAlongside(flags.run, { cwd: projectRoot, write: (l) => process.stdout.write(l) }); + const app = runAlongside(flags.run, { cwd: projectRoot, write: (l) => process.stdout.write(l), env: { [BACKEND_ENV]: backendUrl(opts.ip, opts.port) } }); void app.exited.then((code) => process.stdout.write(`app exited (code ${code}). The backend keeps running.\n`)); for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"] as const) { process.once(sig, () => { @@ -311,6 +321,8 @@ export async function runCli(argv: string[]): Promise { } case "dev": return devCommand(rest); + case "__after-backend": // internal: the app tab of `dev --run` + return afterBackend(rest); case "serve": return serveCommand(rest); case "deploy": diff --git a/packages/cli/src/dev-tabs.ts b/packages/cli/src/dev-tabs.ts new file mode 100644 index 00000000..808bc26f --- /dev/null +++ b/packages/cli/src/dev-tabs.ts @@ -0,0 +1,101 @@ +/** + * `concile dev --run ""` in a real terminal: the backend and the app each get their own tab + * (mprocs, a terminal UI for running several processes). Each tab shows one process's own output, + * so it is always clear which URL belongs to which server. Without a terminal (CI, agents, pipes) + * the caller keeps the plain prefixed output instead. + */ +import { spawn } from "node:child_process"; +import { createRequire } from "node:module"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { createConnection } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { isAgent } from "./init/flags"; + +/** Env var the app process gets: where the backend listens. @concile/vite proxies to it instead of starting its own. */ +export const BACKEND_ENV = "CONCILE_DEV_BACKEND"; + +/** The mprocs binary, or null when the package or this platform's build is missing. */ +export function mprocsBinary(): string | null { + try { + return createRequire(import.meta.url)("mprocs") as string; + } catch { + return null; + } +} + +export function wantTabs(o: { noUi?: boolean; env: NodeJS.ProcessEnv; stdinTTY: boolean; stdoutTTY: boolean }): boolean { + if (o.noUi || o.env.CONCILE_TABS === "0" || o.env.CI) return false; + if (isAgent(o.env)) return false; + return o.stdinTTY && o.stdoutTTY; +} + +/** The URL the app reaches the backend on. A wildcard bind is still reached through loopback. */ +export function backendUrl(ip: string, port: number): string { + const host = ip === "0.0.0.0" || ip === "::" ? "127.0.0.1" : ip.includes(":") ? `[${ip}]` : ip; + return `http://${host}:${port}`; +} + +/** @internal exported for tests. The mprocs config: the backend tab, then the app tab. */ +export function tabsConfig(o: { devArgs: string[]; run: string; cwd: string; url: string }): object { + const bin = fileURLToPath(new URL("./bin.js", import.meta.url)); + return { + proc_list_title: "concile dev", + procs: { + concile: { cmd: [process.execPath, bin, "dev", "--no-ui", ...o.devArgs], cwd: o.cwd }, + // The app waits for the backend, so it can connect at once and never takes the backend's port. + app: { cmd: [process.execPath, bin, "__after-backend", o.url, o.run], cwd: o.cwd, env: { [BACKEND_ENV]: o.url } }, + }, + }; +} + +/** Runs both processes in tabs and returns when the user quits. */ +export function runInTabs(binary: string, o: { devArgs: string[]; run: string; cwd: string; url: string }): Promise { + const dir = mkdtempSync(join(tmpdir(), "concile-tabs-")); + const config = join(dir, "mprocs.yaml"); // JSON is valid YAML + writeFileSync(config, JSON.stringify(tabsConfig(o))); + return new Promise((resolve) => { + const child = spawn(binary, ["--config", config], { stdio: "inherit", cwd: o.cwd }); + child.on("error", () => resolve(1)); + child.on("exit", (code) => resolve(code ?? 0)); + }); +} + +function portOpen(host: string, port: number): Promise { + return new Promise((resolve) => { + const s = createConnection({ host, port }); + s.once("connect", () => { s.destroy(); resolve(true); }); + s.once("error", () => resolve(false)); + }); +} + +/** + * `concile __after-backend ` (internal, the app tab): waits until the backend + * listens, then runs the app command in this terminal. After a minute it starts the app anyway. + */ +export async function afterBackend(args: string[], opts: { timeoutMs?: number; write?: (s: string) => void } = {}): Promise { + const [url, command] = args; + if (!url || !command) return 2; + const write = opts.write ?? ((s: string) => process.stdout.write(s)); + const { hostname, port } = new URL(url); + const host = hostname.replace(/^\[|\]$/g, ""); + const deadline = Date.now() + (opts.timeoutMs ?? 60_000); + let said = false; + while (!(await portOpen(host, Number(port)))) { + if (Date.now() > deadline) { + write(`The backend is not up yet. Starting the app anyway.\n`); + break; + } + if (!said) write(`Waiting for the backend on ${url}…\n`); + said = true; + await new Promise((r) => setTimeout(r, 200)); + } + return new Promise((resolve) => { + const child = spawn(command, { shell: true, stdio: "inherit" }); + const forward = (sig: NodeJS.Signals) => child.kill(sig); + for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"] as const) process.on(sig, forward); + child.on("error", (e) => { write(`Could not start "${command}": ${e.message}\n`); resolve(1); }); + child.on("exit", (code, signal) => resolve(code ?? (signal ? 1 : 0))); + }); +} diff --git a/packages/cli/src/init/apply.ts b/packages/cli/src/init/apply.ts index afaf36d9..15d9ac00 100644 --- a/packages/cli/src/init/apply.ts +++ b/packages/cli/src/init/apply.ts @@ -156,7 +156,9 @@ const INSTALL_ARGS: Record string[]> = { */ export function pinPackages(packages: string[], version: string = CLI_VERSION): string[] { if (!/^\d+\.\d+\.\d+/.test(version)) return packages; - return packages.map((p) => (p === "concile" || p.startsWith("@concile/") ? `${p}@^${version}` : p)); + // A package that already names its version or file (name@spec) is left as it is. + const bare = (p: string) => !p.slice(1).includes("@"); + return packages.map((p) => ((p === "concile" || p.startsWith("@concile/")) && bare(p) ? `${p}@^${version}` : p)); } /** @@ -188,6 +190,33 @@ export function runCommand(cmd: string, args: string[], cwd: string): Promise; + const specs: Record = Object.fromEntries(Object.entries(manifest).map(([name, file]) => [name, `file:${file}`])); + const pkgPath = join(cwd, "package.json"); + const pkg = JSON.parse(readFileSync(pkgPath, "utf8")) as Record | unknown>; + // Direct packages become file dependencies (npm rejects an override on a direct dependency)... + const deps = { ...(pkg.dependencies as Record) }; + const rest: string[] = []; + for (const p of packages) { + if (specs[p]) deps[p] = specs[p]; + else rest.push(p); + } + pkg.dependencies = deps; + // ...and everything they pull in transitively comes from the same files through overrides. + const indirect = Object.fromEntries(Object.entries(specs).filter(([name]) => !(name in deps))); + if (pm === "pnpm") pkg.pnpm = { ...(pkg.pnpm as object), overrides: { ...((pkg.pnpm as { overrides?: object })?.overrides), ...indirect } }; + else if (pm === "yarn") pkg.resolutions = { ...(pkg.resolutions as object), ...indirect }; + else pkg.overrides = { ...(pkg.overrides as object), ...indirect }; + writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n"); + return rest; +} + export function defaultApplyDeps(): ApplyDeps { const here = dirname(fileURLToPath(import.meta.url)); // dist/bin.js and dist/index.js sit in dist/; templates ship beside dist/. @@ -195,6 +224,12 @@ export function defaultApplyDeps(): ApplyDeps { return { templatesDir, async install(pm, packages, full, cwd) { + const local = process.env.CONCILE_LOCAL_PACKAGES; + if (local) { + // The local packages are now in package.json, so a full install picks them up. + packages = useLocalPackages(cwd, pm, packages, local); + full = true; + } for (const args of installCommands(pm, packages, full)) await runCommand(pm, args, cwd); }, async codegen(functionsDir) { diff --git a/packages/cli/src/init/banner.ts b/packages/cli/src/init/banner.ts index cad67a95..0e7483ac 100644 --- a/packages/cli/src/init/banner.ts +++ b/packages/cli/src/init/banner.ts @@ -2,76 +2,124 @@ import { BRAND_RGB, rgb, type ColorLevel } from "../ui"; export interface BannerOptions { columns: number; level: ColorLevel; unicode: boolean; version: string } -// The logo mark from www/public/brand/concile-mark.svg on its 8-unit grid. `▓▓` is the single -// violet cell; `▪` are the small dissolving cells. -const MARK = [ - " ████████▪ ", - " ██████████▪ ▪ ", - "████ ▪ ▪ ", - "████ ▓▓", - "████ ▪ ▪ ", - " ██████████▪ ▪ ", - " ████████▪ ", -]; -// First animation frame: the violet cell two columns out, "arriving". -const MARK_ARRIVING = MARK.map((l, i) => (i === 3 ? "████ " : l)); -const ARRIVING_CELL_ROW = 3; +// The display wordmark, copied from www/components/brand-grid.ts (keep them in step): the name +// in the mark's own cells, lowercase, with the dot of the i as the one violet cell. The brand uses +// it stand-alone for hero moments, so the banner shows it without the mark. +const GLYPHS: Record = { + c: ["", "", ".XXX", "X...", "X...", "X...", ".XXX"], + o: ["", "", ".XX.", "X..X", "X..X", "X..X", ".XX."], + n: ["", "", "XXX.", "X..X", "X..X", "X..X", "X..X"], + i: ["V", "", "X", "X", "X", "X", "X"], + l: ["X", "X", "X", "X", "X", "X", "X"], + e: ["", "", ".XX.", "X..X", "XXXX", "X...", ".XXX"], +}; + +/** "concile" on one 7-row grid, one blank column between letters. */ +function wordRows(): string[] { + const rows = Array.from({ length: 7 }, () => ""); + [..."concile"].forEach((ch, n) => { + const g = GLYPHS[ch]!; + const w = Math.max(...g.map((r) => r.length)); + for (let r = 0; r < 7; r++) rows[r] += (n ? "." : "") + (g[r] ?? "").padEnd(w, "."); + }); + return rows; +} +const WORD_ROWS = wordRows(); + +// First animation frame: the i without its dot. The violet cell then drops into place. +const WORD_ARRIVING = WORD_ROWS.map((r, i) => (i === 0 ? r.replace("V", ".") : r)); -const WORD = [ - " ██████╗ ██████╗ ███╗ ██╗ ██████╗██╗██╗ ███████╗", - "██╔════╝██╔═══██╗████╗ ██║██╔════╝██║██║ ██╔════╝", - "██║ ██║ ██║██╔██╗ ██║██║ ██║██║ █████╗ ", - "██║ ██║ ██║██║╚██╗██║██║ ██║██║ ██╔══╝ ", - "╚██████╗╚██████╔╝██║ ╚████║╚██████╗██║███████╗███████╗", - " ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚═╝╚══════╝╚══════╝", -]; /** - * Wordmark rows, light to dark. Mid greys only: they must read on a dark terminal and on a white one - * (macOS Terminal's default). At 256 colours these land on cube greys 175 and 135, never near-white. - * @internal exported for tests. + * One brand cell is half a character cell: two grid rows share a line through ▀ ▄ █. A cell is + * about as wide as it is tall, so the letters keep their shape at 4 lines high. Plain cells use the + * terminal's own foreground (right on dark and light themes) and V is brand violet. Where two + * kinds would share a character, V wins. */ -export const GREYS = [175, 160, 145, 130, 115, 100]; -const WIDE = 2 + MARK[0]!.length + 3 + WORD[0]!.length; // 75 (2 + 16 + 3 + 54) +function render(rows: string[], level: ColorLevel): string[] { + const violet = rgb(level, ...BRAND_RGB); + const kind = (c: string | undefined) => (c === "X" ? "x" : c === "V" ? "v" : null); + const paint = (k: string, s: string) => (k === "v" ? violet(s) : s); + const out: string[] = []; + for (let r = 0; r < rows.length; r += 2) { + const top = rows[r]!; + const bottom = rows[r + 1] ?? ""; + let line = ""; + for (let c = 0; c < top.length; c++) { + const t = kind(top[c]); + const b = kind(bottom[c]); + if (!t && !b) line += " "; + else if (t === b) line += paint(t!, "█"); + else if (t === "v" || (t && !b)) line += paint(t!, "▀"); + else line += paint(b!, "▄"); + } + out.push(line); + } + return out; +} + +const TAGLINE = "the reactive backend you self-host"; +const DOCS = "concile.dev/docs"; +/** Columns the wordmark needs. @internal exported for tests. */ +export const WIDE = 2 + WORD_ROWS[0]!.length; + +/** The right-hand column of the boxed banner, one line per wordmark row. */ +function infoLines(o: BannerOptions): string[] { + const dim = (s: string) => (o.level === 0 ? s : `\x1b[2m${s}\x1b[22m`); + const bold = (s: string) => (o.level === 0 ? s : `\x1b[1m${s}\x1b[22m`); + return [ + `${bold("concile init")} ${dim(`v${o.version}`)}`, + dim(TAGLINE), + `${dim("docs")} ${DOCS}`, + dim("nothing changes until you say yes"), + ]; +} +const INFO_W = Math.max(TAGLINE.length, "concile init v0.00.00".length, `docs ${DOCS}`.length, "nothing changes until you say yes".length); +// │ 2 wordmark 2 │ 2 info 2 │ +const INNER_LEFT = 2 + WORD_ROWS[0]!.length + 2; +const INNER_RIGHT = 2 + INFO_W + 2; +/** Columns the boxed banner needs. @internal exported for tests. */ +export const BOXED = 1 + INNER_LEFT + 1 + INNER_RIGHT + 1; export function plainBannerLine(version: string): string { return `concile init v${version}`; } -function paintMark(line: string, level: ColorLevel): string { - const violet = rgb(level, ...BRAND_RGB); - return line.replace("▓▓", violet("██")); +const visible = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, "").length; +const padTo = (s: string, w: number) => s + " ".repeat(Math.max(0, w - visible(s))); + +/** + * One wide box: the wordmark on the left, a separator, the essentials on the right. The + * border and the secondary text are dim, so the violet dot of the i stays the one accent. + */ +function boxed(word: string[], o: BannerOptions): string[] { + const dim = (s: string) => (o.level === 0 ? s : `\x1b[2m${s}\x1b[22m`); + const info = infoLines(o); + const bar = dim("│"); + const row = (left: string, right: string) => `${bar}${padTo(left, INNER_LEFT)}${bar}${padTo(right, INNER_RIGHT)}${bar}`; + // Starts in column 0, the column of the prompts' vertical bar below it. + return [ + dim(`╭${"─".repeat(INNER_LEFT)}┬${"─".repeat(INNER_RIGHT)}╮`), + row("", ""), + ...word.map((l, i) => row(` ${l}`, ` ${info[i] ?? ""}`)), + row("", ""), + dim(`╰${"─".repeat(INNER_LEFT)}┴${"─".repeat(INNER_RIGHT)}╯`), + ]; } -function frame(mark: string[], o: BannerOptions, extraCell: boolean): string { - const violet = rgb(o.level, ...BRAND_RGB); +function frame(word: string[], o: BannerOptions): string { const dim = (s: string) => (o.level === 0 ? s : `\x1b[2m${s}\x1b[22m`); - const tagline = ` ${dim(`the reactive backend you self-host · v${o.version}`)}`; - const rows: string[] = [""]; - if (o.columns >= WIDE) { - for (let i = 0; i < mark.length; i++) { - let m = paintMark(mark[i] ?? "", o.level); - if (extraCell && i === ARRIVING_CELL_ROW) m = `${m}${violet("██")}`; - const w = i === 0 ? "" : WORD[i - 1] ?? ""; - const g = GREYS[i - 1] ?? 100; - const pad = extraCell && i === ARRIVING_CELL_ROW ? " " : " "; - rows.push(` ${m}${w ? pad + rgb(o.level, g, g, g)(w) : ""}`.replace(/\s+$/, "")); - } - } else { - for (let i = 0; i < mark.length; i++) { - let m = paintMark(mark[i] ?? "", o.level); - if (extraCell && i === ARRIVING_CELL_ROW) m = `${m}${violet("██")}`; - rows.push(` ${m}`.replace(/\s+$/, "")); - } - rows.push("", ` ${violet("concile")}`); - } - rows.push("", tagline, ""); - return rows.join("\n"); + if (o.columns >= BOXED) return ["", ...boxed(render(word, o.level), o), ""].join("\n"); + const lines: string[] = [""]; + if (o.columns >= WIDE) for (const l of render(word, o.level)) lines.push(` ${l}`.replace(/\s+$/, "")); + else lines.push(` ${rgb(o.level, ...BRAND_RGB)("concile")}`); + lines.push("", ` ${dim(`${TAGLINE} · v${o.version}`)}`, ""); + return lines.join("\n"); } export function bannerFrames(o: BannerOptions): string[] { if (!o.unicode) return [["", " concile", ` the reactive backend you self-host - v${o.version}`, ""].join("\n")]; - if (o.level === 0) return [frame(MARK, o, false)]; - return [frame(MARK_ARRIVING, o, true), frame(MARK, o, false)]; + if (o.level === 0 || o.columns < WIDE) return [frame(WORD_ROWS, o)]; + return [frame(WORD_ARRIVING, o), frame(WORD_ROWS, o)]; } export async function showBanner(o: BannerOptions, write: (s: string) => void, animate: boolean): Promise { diff --git a/packages/cli/src/init/command.ts b/packages/cli/src/init/command.ts index 8fb3b7c2..e6dc30b8 100644 --- a/packages/cli/src/init/command.ts +++ b/packages/cli/src/init/command.ts @@ -1,7 +1,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs"; -import { isAbsolute, join, relative, resolve } from "node:path"; +import { basename, isAbsolute, join, relative, resolve } from "node:path"; import { CLI_VERSION } from "../version"; -import { childProjects, compareVersions, detect, freeFolderName, type PackageManager, type ProjectInfo } from "./detect"; +import { compareVersions, detect, freeFolderName, type PackageManager, type ProjectInfo } from "./detect"; import { loadConfig } from "../load-config"; import { planInit, previewLines, fsView, type Action, type Answers } from "./plan"; import { ApplyError, applyPlan, defaultApplyDeps, type ApplyDeps, type ApplyResult } from "./apply"; @@ -19,7 +19,8 @@ export interface InitDeps { prompter: Prompter | null; apply: ApplyDeps; /** Starts the dev server. `script` set: run the project's dev script (a starter: backend + app). */ - startDev: (root: string, script?: { pm: PackageManager }) => Promise; + /** Starts development: the package's own dev script, `concile dev --run `, or `concile dev` alone. */ + startDev: (root: string, how?: DevStart["how"]) => Promise; /** Runs `concile migrate` on a Convex project at `root`. */ migrate: (root: string) => Promise; nodeVersion?: string; @@ -34,9 +35,9 @@ function defaults(): InitDeps { write: (s) => process.stdout.write(s), prompter: null, apply: defaultApplyDeps(), - startDev: async (root, script) => { - if (script) { - const [cmd, ...rest] = RUN_DEV[script.pm].split(" "); + startDev: async (root, how) => { + if (how && "script" in how) { + const [cmd, ...rest] = RUN_DEV[how.script].split(" "); const { spawn } = await import("node:child_process"); const child = spawn(cmd!, rest, { cwd: root, stdio: "inherit", shell: process.platform === "win32" }); return new Promise((done) => { @@ -47,7 +48,7 @@ function defaults(): InitDeps { process.chdir(root); // Dynamic import: cli.ts imports this file. const { devCommand } = await import("../cli"); - return devCommand([]); + return devCommand(how ? ["--run", how.run] : []); }, migrate: async (root) => { // Dynamic import keeps init/* free of a static cycle through cli.ts. @@ -115,14 +116,27 @@ function installHint(pm: PackageManager, packages: string[]): string { return `Packages were not installed. Install them, then run: npx concile codegen\n ${pm} ${verb} ${packages.join(" ")}`; } -/** For an existing app: how to start the frontend and the backend with one command. */ -function oneCommandTip(framework: string, pm: PackageManager): string | null { - if (framework === "vite") { - return `To start the backend with vite too: ${pm === "npm" ? "npm install -D" : `${pm} add -D`} @concile/vite, add concile() from "@concile/vite" to the plugins in vite.config, and set VITE_CONCILE_URL=ws://localhost:5173/api/sync in .env.local.`; - } - if (framework === "next") return `To start both with one command: npx concile dev --run "next dev -p 3001"`; - if (framework === "sveltekit" || framework === "astro") return `To start both with one command: npx concile dev --run "${RUN_DEV[pm]}"`; - return null; +export interface DevStart { + /** What the user types to start developing. */ + command: string; + /** How init starts it: the package's dev script, the app's dev script next to `concile dev`, or the backend alone. */ + how?: { script: PackageManager } | { run: string }; +} + +/** + * One command starts the app and the backend. A starter's dev script already does both. An existing + * app keeps its package.json as it is: `concile dev --run` starts its own dev script next to the + * backend. A dev script that already runs concile is used as it is. + * @internal exported for tests. + */ +export function devStart(root: string, pm: PackageManager, starter: boolean): DevStart { + const script = RUN_DEV[pm]; + if (starter) return { command: script, how: { script: pm } }; + let dev: unknown; + try { dev = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).scripts?.dev; } catch { dev = undefined; } + if (typeof dev !== "string") return { command: "npx concile dev" }; + if (/\bconcile\b/.test(dev)) return { command: script, how: { script: pm } }; + return { command: `npx concile dev --run "${script}"`, how: { run: script } }; } /** Quotes a path for a copy-pasteable command when it holds spaces or shell characters. */ @@ -180,27 +194,27 @@ async function runInit(args: string[], d: InitDeps, nested: boolean): Promise relative(d.cwd, resolve(root, dir)) || "."; - if (interactive) { - let dir: string; - try { - dir = await ui.askLoose(projects, suggested, (name) => existsSync(resolve(root, name))); - } catch (e) { - if (e instanceof Cancelled) return 0; - throw e; - } + // No package.json here. Like create-next-app and create-convex, ask for a folder name and never go + // looking through other folders: an existing project is set up by running init inside it. + // An empty folder may also take the app itself ("."); a folder with other files may not. + const suggested = freeFolderName(root); + const at = (dir: string) => relative(d.cwd, resolve(root, dir)) || "."; + if (info.kind === "loose" && !interactive) { + return stop(`${basename(root)}/ has no package.json, so it is not a project.\nTo start a new app: npx concile init ${shellArg(at(suggested))}\nTo set up an existing project, run npx concile init inside it.`, { suggested }); + } + // Without flags, agents and CI set up an empty folder right where they are. + if (interactive && (info.kind === "loose" || (info.kind === "empty" && flags.folder === null && !nested))) { + let dir: string; + try { + dir = await ui.askWhere(basename(root), suggested, info.kind === "empty", (name) => existsSync(resolve(root, name))); + } catch (e) { + if (e instanceof Cancelled) return 0; + throw e; + } + if (dir !== ".") { const rest = flags.folder === null ? args : args.filter((a) => a !== flags.folder); return runInit([at(dir), ...rest], { ...d, prompter: ui }, true); } - const lines = [ - ...projects.map((p) => `To set up ${p}: npx concile init ${shellArg(at(p))}`), - `To start a new app: npx concile init ${shellArg(at(suggested))}`, - ]; - return stop(`This folder has files but no package.json, so it doesn't look like a project.\n${lines.join("\n")}`, { projects, suggested }); } if (info.kind === "convex") { if (!interactive) return stop("This looks like a Convex project. Move it to Concile with: npx concile migrate"); @@ -324,7 +338,8 @@ async function runInit(args: string[], d: InitDeps, nested: boolean): Promise f.id === (answers.starter && answers.starter !== "none" ? answers.starter : info.framework)); const cd = flags.folder ? `cd ${flags.folder} && ` : ""; const starter = actions.find((a) => a.kind === "copyTemplate"); - const runDev = starter ? `${cd}${RUN_DEV[info.packageManager]}` : `${cd}npx concile dev`; + const dev = devStart(root, info.packageManager, Boolean(starter)); + const runDev = `${cd}${dev.command}`; if (flags.json) { d.write(JSON.stringify({ ok: true, root, answers: redactAnswers(answers), done: result.done, manual: result.manual, next: notInstalled ?? runDev })); return 0; @@ -340,15 +355,15 @@ async function runInit(args: string[], d: InitDeps, nested: boolean): Promise IGNORED.has(e) || IGNORED_PREFIXES.some((re) => re.test(e)); -/** Direct subfolders of `root` that hold a package.json: the projects a loose folder can point to. */ -export function childProjects(root: string): string[] { - if (!existsSync(root)) return []; - return readdirSync(root, { withFileTypes: true }) - .filter((e) => e.isDirectory() && !e.name.startsWith(".") && e.name !== "node_modules" && existsSync(join(root, e.name, "package.json"))) - .map((e) => e.name) - .sort(); -} - /** `base`, or `base-2`, `base-3`... : the first name that does not exist yet in `root`. */ export function freeFolderName(root: string, base = "my-app"): string { for (let n = 1; ; n++) { diff --git a/packages/cli/src/init/prompts.ts b/packages/cli/src/init/prompts.ts index a40a51f3..20de2cea 100644 --- a/packages/cli/src/init/prompts.ts +++ b/packages/cli/src/init/prompts.ts @@ -1,4 +1,5 @@ import * as p from "@clack/prompts"; +import { TextPrompt } from "@clack/core"; import { COMPONENTS, type ComponentId, type StarterId } from "./registry"; import { detectColorLevel, supportsUnicode } from "../ui"; import { plainBannerLine, showBanner } from "./banner"; @@ -13,8 +14,8 @@ export interface Prompter { confirmApply(lines: string[]): Promise; askStartDev(): Promise; askMigrate(): Promise; - /** A folder with files but no package.json: set up a project inside it, or create a new app folder. */ - askLoose(projects: string[], suggested: string, taken: (name: string) => boolean): Promise; + /** Where a new app goes: a folder name, or "." for this folder when `here` allows it. */ + askWhere(folder: string, suggested: string, here: boolean, taken: (name: string) => boolean): Promise; info(msg: string): void; warn(msg: string): void; step(msg: string): { done(msg: string): void; fail(msg: string): void }; @@ -59,6 +60,11 @@ export function clackPrompter( const term = { env: io.env, isTTY: io.isTTY, platform: io.platform }; const level = detectColorLevel(term, { honorForce: true }); const dim = (s: string) => (level === 0 ? s : `\x1b[2m${s}\x1b[22m`); + const paint = (code: string, s: string) => (level === 0 ? s : `\x1b[${code}m${s}\x1b[0m`); + // clack's own symbols, so the one hand-drawn prompt matches the rest. + const ui = supportsUnicode(term) + ? { bar: "│", end: "└", active: "◆", done: "◇", error: "▲", cancel: "■" } + : { bar: "|", end: "—", active: "*", done: "o", error: "x", cancel: "x" }; return { async intro() { // No colour (NO_COLOR, TERM=dumb): one plain line instead of the logo (spec section 4, Banner). @@ -129,30 +135,32 @@ export function clackPrompter( async askMigrate() { return check(await p.confirm({ message: "This looks like a Convex project. Run `concile migrate` now?", initialValue: true })); }, - async askLoose(projects, suggested, taken) { - const NEW = "\0new"; - if (projects.length) { - const pick = check( - await p.select({ - message: "This folder is not a project. What should get Concile?", - options: [...projects.map((d) => ({ value: d, label: `${d}/`, hint: "existing project" })), { value: NEW, label: "A new app in a new folder" }], - }), - ); - if (pick !== NEW) return pick; - } - return check( - await p.text({ - message: "Name the new app folder", - initialValue: suggested, - validate: (v) => { - const name = (v ?? "").trim(); - if (!name) return "Type a folder name."; - if (/[\\/]/.test(name)) return "Use a plain folder name, without slashes."; - if (taken(name)) return `${name} already exists. Pick another name.`; - return undefined; - }, - }), - ).trim(); + async askWhere(folder, suggested, here, taken) { + // One line, like create-convex: "Project name › my-app". The suggestion is real, editable text + // (Backspace works), dim until changed. clack's text() puts the input on its own line, so this draws its own. + const label = here ? `Project name ${dim("(. for this folder)")}` : "Project name"; + const prompt = new TextPrompt({ + initialValue: suggested, + validate: (v) => { + const name = (v ?? "").trim(); + if (!name) return "Type a folder name."; + if (name === ".") return here ? undefined : `${folder}/ already has files. Pick a new folder name.`; + if (/[\\/]/.test(name)) return "Use a plain folder name, without slashes."; + if (taken(name)) return `${name} already exists. Pick another name, or run init inside it.`; + return undefined; + }, + render() { + const input = this.userInput === suggested ? `${dim(suggested)}${paint("7", " ")}` : this.userInputWithCursor; + const line = (sym: string, value: string) => `${dim(ui.bar)}\n${sym} ${label} ${dim("›")} ${value}`; + switch (this.state) { + case "submit": return line(paint("32", ui.done), dim(this.value ?? "")); + case "cancel": return `${line(paint("31", ui.cancel), paint("9;2", this.userInput))}\n${dim(ui.bar)}`; + case "error": return `${line(paint("33", ui.error), input)}\n${paint("33", ui.end)} ${paint("33", this.error)}\n`; + default: return `${line(paint("36", ui.active), input)}\n${paint("36", ui.end)}\n`; + } + }, + }); + return String(check(await prompt.prompt())).trim(); }, info: (m) => p.log.info(m), warn: (m) => p.log.warn(m), @@ -180,7 +188,7 @@ export function plainPrompter(write: (s: string) => void): Prompter { askDb: never, askStartDev: never, askMigrate: never, - askLoose: never, + askWhere: never, async confirmApply() { return true; }, diff --git a/packages/cli/templates/vite/package.json b/packages/cli/templates/vite/package.json index b89f6078..e20beac6 100644 --- a/packages/cli/templates/vite/package.json +++ b/packages/cli/templates/vite/package.json @@ -2,7 +2,7 @@ "name": "concile-app", "private": true, "type": "module", - "scripts": { "dev": "vite", "build": "vite build" }, + "scripts": { "dev": "concile dev --run vite", "build": "vite build" }, "dependencies": { "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", "@vitejs/plugin-react": "^5.0.0", "typescript": "^5.7.2", "vite": "^7.0.0" } } diff --git a/packages/cli/test/dev-tabs.test.ts b/packages/cli/test/dev-tabs.test.ts new file mode 100644 index 00000000..1a90ab6f --- /dev/null +++ b/packages/cli/test/dev-tabs.test.ts @@ -0,0 +1,53 @@ +import { describe, it, expect } from "vitest"; +import { createServer } from "node:net"; +import { afterBackend, backendUrl, mprocsBinary, tabsConfig, wantTabs } from "../src/dev-tabs"; + +describe("dev tabs", () => { + const tty = { env: {}, stdinTTY: true, stdoutTTY: true }; + it("uses tabs only in a real terminal, never for CI, agents, --no-ui or CONCILE_TABS=0", () => { + expect(wantTabs(tty)).toBe(true); + expect(wantTabs({ ...tty, stdoutTTY: false })).toBe(false); + expect(wantTabs({ ...tty, noUi: true })).toBe(false); + expect(wantTabs({ ...tty, env: { CI: "1" } })).toBe(false); + expect(wantTabs({ ...tty, env: { CLAUDECODE: "1" } })).toBe(false); + expect(wantTabs({ ...tty, env: { CONCILE_TABS: "0" } })).toBe(false); + }); + + it("the app reaches a wildcard bind through loopback", () => { + expect(backendUrl("0.0.0.0", 3000)).toBe("http://127.0.0.1:3000"); + expect(backendUrl("127.0.0.1", 4000)).toBe("http://127.0.0.1:4000"); + expect(backendUrl("::1", 3000)).toBe("http://[::1]:3000"); + }); + + it("one tab runs the backend without its own UI, the other waits for it and runs the app", () => { + const cfg = tabsConfig({ devArgs: ["--port", "4000"], run: "vite", cwd: "/app", url: "http://127.0.0.1:4000" }) as { + procs: Record }>; + }; + expect(Object.keys(cfg.procs)).toEqual(["concile", "app"]); + expect(cfg.procs.concile!.cmd.slice(2)).toEqual(["dev", "--no-ui", "--port", "4000"]); + expect(cfg.procs.app!.cmd.slice(2)).toEqual(["__after-backend", "http://127.0.0.1:4000", "vite"]); + expect(cfg.procs.app!.env).toEqual({ CONCILE_DEV_BACKEND: "http://127.0.0.1:4000" }); + }); + + it("ships the mprocs binary for this platform", () => { + expect(mprocsBinary()).toMatch(/mprocs/); + }); + + it("the app starts only once the backend listens", async () => { + const server = createServer(); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + const port = (server.address() as { port: number }).port; + const out: string[] = []; + const code = await afterBackend([`http://127.0.0.1:${port}`, "exit 3"], { write: (s) => out.push(s) }); + server.close(); + expect(code).toBe(3); + expect(out).toEqual([]); // already listening: no waiting message + }); + + it("starts the app anyway when the backend never comes up", async () => { + const out: string[] = []; + const code = await afterBackend(["http://127.0.0.1:1", "exit 0"], { timeoutMs: 300, write: (s) => out.push(s) }); + expect(code).toBe(0); + expect(out.join("")).toContain("Starting the app anyway"); + }); +}); diff --git a/packages/cli/test/init/banner.test.ts b/packages/cli/test/init/banner.test.ts index 4150f555..ce4211e2 100644 --- a/packages/cli/test/init/banner.test.ts +++ b/packages/cli/test/init/banner.test.ts @@ -1,22 +1,58 @@ import { describe, it, expect } from "vitest"; -import { bannerFrames, plainBannerLine, showBanner, GREYS } from "../../src/init/banner"; +import { bannerFrames, plainBannerLine, showBanner, WIDE, BOXED } from "../../src/init/banner"; const strip = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, ""); const final = (o: Parameters[0]) => { const f = bannerFrames(o); return f[f.length - 1]!; }; +const VIOLET = "\x1b[38;2;139;108;240m"; describe("banner", () => { - it("wide terminals show mark and wordmark side by side, each line within the width", () => { - const out = strip(final({ columns: 80, level: 3, unicode: true, version: "0.2.0" })); - expect(out).toContain("██████╗ ██████╗ ███╗"); - expect(out).toContain("the reactive backend you self-host · v0.2.0"); - for (const line of out.split("\n")) expect(line.length).toBeLessThanOrEqual(80); + it("wide terminals: one box from column 0, wordmark | the essentials", () => { + const out = strip(final({ columns: 100, level: 3, unicode: true, version: "0.2.0" })); + const lines = out.split("\n").filter(Boolean); + expect(lines).toHaveLength(8); // borders, a padding row above and below, 4 wordmark rows + // Column 0, where the prompts' vertical bar is. + expect(lines[0]).toMatch(/^╭─+┬─+╮$/); + expect(lines.at(-1)).toMatch(/^╰─+┴─+╯$/); + expect(lines[1]).toMatch(/^│ +│ +│$/); + expect(lines[2]).toContain("│ concile init v0.2.0"); + expect(lines[3]).toContain("│ ▄▀▀▀ ▄▀▀▄ █▀▀▄ ▄▀▀▀ █ █ ▄▀▀▄ │ the reactive backend you self-host"); + expect(lines[4]).toContain("docs concile.dev/docs"); + expect(lines[5]).toContain("nothing changes until you say yes"); + // A clean grid: every line the same width, the separator in the same column. + expect(new Set(lines.map((l) => l.length)).size).toBe(1); + const sep = lines[0]!.indexOf("┬"); + expect(lines.at(-1)!.indexOf("┴")).toBe(sep); + for (const l of lines.slice(1, -1)) expect(l[sep]).toBe("│"); + expect(lines[0]!.length).toBe(BOXED); + expect(BOXED).toBeLessThanOrEqual(80); }); - it("narrow terminals show the mark and a small name, no wordmark", () => { + it("medium terminals: the wordmark alone, 4 lines tall, version on the tagline", () => { const out = strip(final({ columns: 60, level: 3, unicode: true, version: "0.2.0" })); - expect(out).not.toContain("███╗"); + expect(out).not.toContain("╭"); + expect(out.split("\n").slice(1, 5)[2]).toBe(" █ █ █ █ █ █ █ █ █▀▀▀"); + expect(out).toContain("the reactive backend you self-host · v0.2.0"); + expect(WIDE).toBe(30); // was 75 columns with the mark and block letters + }); + + it("the one violet cell is the dot of the i", () => { + const out = final({ columns: 80, level: 3, unicode: true, version: "0.2.0" }); + expect(out.split(VIOLET).length - 1).toBe(1); + expect(out).toContain(`${VIOLET}▀`); + }); + + it("plain cells use the terminal's own colour, so it reads on dark and light themes", () => { + const out = final({ columns: 80, level: 3, unicode: true, version: "0.2.0" }); + const colours = [...out.matchAll(/\x1b\[38;[^m]*m/g)].map((m) => m[0]); + expect(new Set(colours)).toEqual(new Set([VIOLET])); + }); + + it("terminals narrower than the wordmark get the name as text, without animation", () => { + const o = { columns: 25, level: 3 as const, unicode: true, version: "0.2.0" }; + const out = strip(final(o)); + expect(out).not.toContain("█"); expect(out).toContain("concile"); - for (const line of out.split("\n")) expect(line.length).toBeLessThanOrEqual(60); + expect(bannerFrames(o)).toHaveLength(1); }); it("level 0 output has no escape codes", () => { @@ -29,10 +65,15 @@ describe("banner", () => { expect(out).toContain("concile"); }); - it("animation: two frames, the violet cell starts out of place", () => { + it("animation: the i's violet dot drops in; nothing else changes", () => { const f = bannerFrames({ columns: 80, level: 3, unicode: true, version: "0.2.0" }); expect(f.length).toBe(2); - expect(strip(f[0]!)).not.toBe(strip(f[1]!)); + expect(f[0]).not.toContain(VIOLET); + expect(f[1]).toContain(VIOLET); + const a = strip(f[0]!).split("\n"); + const b = strip(f[1]!).split("\n"); + expect(a.length).toBe(b.length); + expect(a.filter((l, i) => l !== b[i])).toHaveLength(1); // only the line with the dot }); it("plain line for agents and CI", () => { @@ -52,16 +93,4 @@ describe("banner", () => { await showBanner(o, (s) => writes.push(s), false); expect(writes).toEqual([final(o) + "\n"]); }); - it("wordmark greys read on light and dark backgrounds (no near-white, no near-black)", () => { - for (const g of GREYS) { - expect(g).toBeGreaterThanOrEqual(90); - expect(g).toBeLessThanOrEqual(180); - } - const out = final({ columns: 80, level: 2, unicode: true, version: "0.2.0" }); - const codes = [...out.matchAll(/\x1b\[38;5;(\d+)m/g)].map((m) => Number(m[1])); - const cube = [0, 95, 135, 175, 215, 255]; - const greys = codes.filter((c) => c >= 16 && c <= 231).map((c) => { const n = c - 16; return [cube[Math.floor(n / 36)]!, cube[Math.floor(n / 6) % 6]!, cube[n % 6]!]; }).filter(([r, g, b]) => r === g && g === b); - expect(greys.length).toBeGreaterThanOrEqual(6); - for (const [v] of greys) expect(v).toBeLessThanOrEqual(175); - }); }); diff --git a/packages/cli/test/init/command.test.ts b/packages/cli/test/init/command.test.ts index 9e8c7832..1f2b7ac5 100644 --- a/packages/cli/test/init/command.test.ts +++ b/packages/cli/test/init/command.test.ts @@ -1,8 +1,8 @@ import { describe, it, expect } from "vitest"; import { mkdtempSync, writeFileSync, existsSync, readFileSync, readdirSync, mkdirSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { initCommand, addCommand } from "../../src/init/command"; +import { basename, join } from "node:path"; +import { initCommand, addCommand, devStart } from "../../src/init/command"; import { dirname } from "node:path"; import { fileURLToPath } from "node:url"; import type { ApplyDeps } from "../../src/init/apply"; @@ -61,7 +61,7 @@ describe("initCommand (non-interactive)", () => { expect(readdirSync(root)).toEqual(["notes.txt"]); }); - it("loose folder holding a project: points at it and never suggests a taken name", async () => { + it("loose folder: never lists other folders, suggests a free name", async () => { const root = mkdtempSync(join(tmpdir(), "cmd3b-")); mkdirSync(join(root, "my-app")); writeFileSync(join(root, "my-app", "package.json"), "{}"); @@ -69,46 +69,59 @@ describe("initCommand (non-interactive)", () => { const out: string[] = []; expect(await initCommand([], deps(root, out))).toBe(1); const text = out.join(""); - expect(text).toContain("To set up my-app: npx concile init my-app"); expect(text).toContain("To start a new app: npx concile init my-app-2"); + expect(text).toContain("run npx concile init inside it"); + expect(text).not.toContain("To set up my-app"); }); - it("loose folder, interactive: picking a child project runs init inside it", async () => { - const root = mkdtempSync(join(tmpdir(), "cmd3c-")); - mkdirSync(join(root, "web")); - writeFileSync(join(root, "web", "package.json"), JSON.stringify({ name: "web", devDependencies: { vite: "6" } })); - writeFileSync(join(root, "notes.txt"), "hi"); - let asked: { projects: string[]; suggested: string } | null = null; - const ui = { - ...plainPrompter(() => {}), - askLoose: async (projects: string[], suggested: string) => { asked = { projects, suggested }; return "web"; }, - askRecommended: async () => true, - askStartDev: async () => false, - }; - const d = { ...deps(root, []), stdinTTY: true, stdoutTTY: true, prompter: ui }; - expect(await initCommand(["--no-install"], d)).toBe(0); - expect(asked).toEqual({ projects: ["web"], suggested: "my-app" }); - expect(existsSync(join(root, "web", "concile.config.ts"))).toBe(true); - expect(existsSync(join(root, "concile.config.ts"))).toBe(false); + const answers = (where: string, seen: { suggested: string; here: boolean }[] = []) => ({ + ...plainPrompter(() => {}), + askWhere: async (_folder: string, suggested: string, here: boolean) => { seen.push({ suggested, here }); return where; }, + askRecommended: async () => false, + askStarter: async () => "none" as const, + askComponents: async () => [], + askDb: async () => ({ db: "sqlite" as const, url: null }), + askStartDev: async () => false, }); - it("loose folder, interactive: a new name creates the app in that folder", async () => { + it("loose folder, interactive: the app goes into a new folder", async () => { const root = mkdtempSync(join(tmpdir(), "cmd3d-")); writeFileSync(join(root, "notes.txt"), "hi"); - const ui = { - ...plainPrompter(() => {}), - askLoose: async () => "fresh", - askRecommended: async () => false, - askStarter: async () => "none" as const, - askComponents: async () => [], - askDb: async () => ({ db: "sqlite" as const, url: null }), - askStartDev: async () => false, - }; - const d = { ...deps(root, []), stdinTTY: true, stdoutTTY: true, prompter: ui }; + const seen: { suggested: string; here: boolean }[] = []; + const d = { ...deps(root, []), stdinTTY: true, stdoutTTY: true, prompter: answers("fresh", seen) }; expect(await initCommand(["--no-install"], d)).toBe(0); + expect(seen).toEqual([{ suggested: "my-app", here: false }]); expect(existsSync(join(root, "fresh", "concile", "schema.ts"))).toBe(true); }); + it("empty folder, interactive: asks once, and '.' sets up right here", async () => { + const root = mkdtempSync(join(tmpdir(), "cmd3e-")); + const seen: { suggested: string; here: boolean }[] = []; + const d = { ...deps(root, []), stdinTTY: true, stdoutTTY: true, prompter: answers(".", seen) }; + expect(await initCommand(["--no-install"], d)).toBe(0); + expect(seen).toEqual([{ suggested: "my-app", here: true }]); + expect(existsSync(join(root, "concile", "schema.ts"))).toBe(true); + }); + + it("empty folder, interactive: a name creates that folder and does not ask again", async () => { + const root = mkdtempSync(join(tmpdir(), "cmd3f-")); + const seen: { suggested: string; here: boolean }[] = []; + const d = { ...deps(root, []), stdinTTY: true, stdoutTTY: true, prompter: answers("shop", seen) }; + expect(await initCommand(["--no-install"], d)).toBe(0); + expect(seen).toHaveLength(1); + expect(existsSync(join(root, "shop", "concile", "schema.ts"))).toBe(true); + expect(existsSync(join(root, "concile"))).toBe(false); + }); + + it("a folder named on the command line is not asked about", async () => { + const root = mkdtempSync(join(tmpdir(), "cmd3g-")); + const seen: { suggested: string; here: boolean }[] = []; + const d = { ...deps(root, []), stdinTTY: true, stdoutTTY: true, prompter: answers("x", seen) }; + expect(await initCommand(["named", "--no-install"], d)).toBe(0); + expect(seen).toHaveLength(0); + expect(existsSync(join(root, "named", "concile", "schema.ts"))).toBe(true); + }); + it("Convex project points to concile migrate and changes nothing", async () => { const root = mkdtempSync(join(tmpdir(), "cmd4-")); writeFileSync(join(root, "package.json"), "{}"); @@ -330,8 +343,8 @@ describe("final fix wave", () => { const tpl = mkdtempSync(join(tmpdir(), "fw-tpl-")); for (const t of ["vite", "next"]) { mkdirSync(join(tpl, t)); writeFileSync(join(tpl, t, "package.json"), "{}"); } for (const [starter, pm, line] of [ - ["vite", "npm", "npm run dev starts the app and the backend together. Open http://localhost:5173 in two tabs."], - ["next", "pnpm", "pnpm dev starts the app and the backend together. Open http://localhost:3001 in two tabs."], + ["vite", "npm", "npm run dev starts the app and the backend together. Open http://localhost:5173 in two browser windows to see live updates."], + ["next", "pnpm", "pnpm dev starts the app and the backend together. Open http://localhost:3001 in two browser windows to see live updates."], ] as const) { const root = mkdtempSync(join(tmpdir(), "fw-start-")); const out: string[] = []; @@ -399,3 +412,23 @@ describe("final fix wave", () => { expect(src).toContain('await import("./init/command")'); }); }); + +describe("devStart", () => { + const app = (pkg: object) => { + const root = mkdtempSync(join(tmpdir(), "devstart-")); + writeFileSync(join(root, "package.json"), JSON.stringify(pkg)); + return root; + }; + it("a starter runs its own dev script, which starts both", () => { + expect(devStart(app({}), "pnpm", true)).toEqual({ command: "pnpm dev", how: { script: "pnpm" } }); + }); + it("an existing app keeps its dev script and gets the backend next to it", () => { + expect(devStart(app({ scripts: { dev: "next dev" } }), "npm", false)).toEqual({ command: 'npx concile dev --run "npm run dev"', how: { run: "npm run dev" } }); + }); + it("a dev script that already runs concile is used as it is", () => { + expect(devStart(app({ scripts: { dev: 'concile dev --run "vite"' } }), "bun", false)).toEqual({ command: "bun run dev", how: { script: "bun" } }); + }); + it("no dev script: the backend alone", () => { + expect(devStart(app({}), "npm", false)).toEqual({ command: "npx concile dev" }); + }); +}); diff --git a/packages/cli/test/init/detect.test.ts b/packages/cli/test/init/detect.test.ts index f820dfa0..789288ef 100644 --- a/packages/cli/test/init/detect.test.ts +++ b/packages/cli/test/init/detect.test.ts @@ -3,7 +3,7 @@ import { spawnSync } from "node:child_process"; import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; -import { detect, compareVersions, packageNameFor, childProjects, freeFolderName } from "../../src/init/detect"; +import { detect, compareVersions, packageNameFor, freeFolderName } from "../../src/init/detect"; function project(files: Record): string { const root = mkdtempSync(join(tmpdir(), "detect-")); @@ -111,15 +111,7 @@ describe("packageNameFor", () => { }); }); -describe("loose folder helpers", () => { - it("childProjects lists subfolders with a package.json, skipping dot folders and node_modules", () => { - const root = mkdtempSync(join(tmpdir(), "child-")); - for (const d of ["b-app", "a-app", "node_modules", ".hidden", "plain"]) mkdirSync(join(root, d)); - for (const d of ["b-app", "a-app", "node_modules", ".hidden"]) writeFileSync(join(root, d, "package.json"), "{}"); - expect(childProjects(root)).toEqual(["a-app", "b-app"]); - expect(childProjects(join(root, "missing"))).toEqual([]); - }); - +describe("freeFolderName", () => { it("freeFolderName skips names that exist", () => { const root = mkdtempSync(join(tmpdir(), "free-")); expect(freeFolderName(root)).toBe("my-app"); diff --git a/packages/cli/test/init/local-packages.test.ts b/packages/cli/test/init/local-packages.test.ts new file mode 100644 index 00000000..b43a58b5 --- /dev/null +++ b/packages/cli/test/init/local-packages.test.ts @@ -0,0 +1,39 @@ +import { describe, it, expect } from "vitest"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { pinPackages, useLocalPackages } from "../../src/init/apply"; + +function setup() { + const dir = mkdtempSync(join(tmpdir(), "local-pkgs-")); + writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "app", overrides: { left: "1" } })); + const manifest = join(dir, "manifest.json"); + writeFileSync(manifest, JSON.stringify({ concile: "/t/concile.tgz", "@concile/cli": "/t/cli.tgz" })); + return { dir, manifest }; +} + +describe("useLocalPackages (CONCILE_LOCAL_PACKAGES, contributors only)", () => { + it("npm/bun: direct packages become file dependencies, the rest go into overrides", () => { + const { dir, manifest } = setup(); + expect(useLocalPackages(dir, "npm", ["concile", "react"], manifest)).toEqual(["react"]); + const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + expect(pkg.dependencies).toEqual({ concile: "file:/t/concile.tgz" }); + // npm rejects an override on a direct dependency, so concile is not overridden. + expect(pkg.overrides).toEqual({ left: "1", "@concile/cli": "file:/t/cli.tgz" }); + }); + + it("pnpm uses pnpm.overrides, yarn uses resolutions", () => { + const a = setup(); + useLocalPackages(a.dir, "pnpm", [], a.manifest); + expect(JSON.parse(readFileSync(join(a.dir, "package.json"), "utf8")).pnpm.overrides["@concile/cli"]).toBe("file:/t/cli.tgz"); + const b = setup(); + useLocalPackages(b.dir, "yarn", [], b.manifest); + expect(JSON.parse(readFileSync(join(b.dir, "package.json"), "utf8")).resolutions["@concile/cli"]).toBe("file:/t/cli.tgz"); + }); + + it("pinPackages leaves a package that already names its spec alone", () => { + expect(pinPackages(["concile@file:/t/c.tgz", "@concile/cli@file:/t/x.tgz", "@concile/auth", "react"], "0.2.1")).toEqual([ + "concile@file:/t/c.tgz", "@concile/cli@file:/t/x.tgz", "@concile/auth@^0.2.1", "react", + ]); + }); +}); diff --git a/packages/cli/test/init/prompts.test.ts b/packages/cli/test/init/prompts.test.ts index 30012537..8a1f9ce9 100644 --- a/packages/cli/test/init/prompts.test.ts +++ b/packages/cli/test/init/prompts.test.ts @@ -14,10 +14,10 @@ describe("clackPrompter intro", () => { await clackPrompter("1.2.3", term({ TERM: "dumb" }, out)).intro(); expect(out.join("")).toBe("concile init v1.2.3\n"); }); - it("shows the logo banner with colour", async () => { + it("shows the wordmark banner with colour", async () => { const out: string[] = []; await clackPrompter("1.2.3", term({ TERM: "xterm-256color", COLORTERM: "truecolor" }, out)).intro(); - expect(out.join("")).toContain("██"); + expect(out.join("")).toContain("█▀▀▄"); // the n of the pixel wordmark expect(out.join("")).toContain("v1.2.3"); }); }); diff --git a/packages/cli/test/init/templates.test.ts b/packages/cli/test/init/templates.test.ts index 4f4da30e..0eb80574 100644 --- a/packages/cli/test/init/templates.test.ts +++ b/packages/cli/test/init/templates.test.ts @@ -44,9 +44,9 @@ describe("templates", () => { expect(pj.type).toBe("module"); }); - it("vite: the @concile/vite plugin starts the backend with vite, and the client defaults to the page's address", () => { + it("vite: concile dev runs the backend and vite in tabs, the plugin proxies to it, and the client uses the page's address", () => { expect(readFileSync(join(tpl, "vite", "vite.config.ts"), "utf8")).toMatch(/plugins: \[react\(\), concile\(\)\]/); - expect(JSON.parse(readFileSync(join(tpl, "vite", "package.json"), "utf8")).scripts.dev).toBe("vite"); + expect(JSON.parse(readFileSync(join(tpl, "vite", "package.json"), "utf8")).scripts.dev).toBe("concile dev --run vite"); expect(readFileSync(join(tpl, "vite", "src", "main.tsx"), "utf8")).toContain("${location.host}/api/sync"); }); }); diff --git a/packages/vite/README.md b/packages/vite/README.md index 1fb77bf0..baec7721 100644 --- a/packages/vite/README.md +++ b/packages/vite/README.md @@ -20,7 +20,7 @@ export default defineConfig({ }); ``` -Run `vite` and the plugin brings the backend up alongside the dev server. `/api` (including the `/api/sync` WebSocket), `/_dashboard`, and `/_admin` are served from the same origin as your app. +Run `vite` and the plugin brings the backend up alongside the dev server. Under `concile dev --run vite`, the backend is already running in its own tab, so the plugin only proxies to it. `/api` (including the `/api/sync` WebSocket), `/_dashboard`, and `/_admin` are served from the same origin as your app. ## Modes diff --git a/packages/vite/src/index.ts b/packages/vite/src/index.ts index 17e44428..b772b3c7 100644 --- a/packages/vite/src/index.ts +++ b/packages/vite/src/index.ts @@ -71,11 +71,14 @@ export function concile(options: ConcileVitePluginOptions = {}): Plugin { function proxyPlugin(options: ConcileVitePluginOptions): Plugin { let port: number; let backend: Backend | undefined; + // `concile dev --run vite` already runs the backend (in its own tab) and says where. Then this + // plugin only proxies to it and starts nothing. + const running = process.env.CONCILE_DEV_BACKEND; return { name: "concile", async config() { port = options.port ?? (await freePort()); - const target = `http://127.0.0.1:${port}`; + const target = running ?? `http://127.0.0.1:${port}`; return { server: { proxy: { @@ -87,6 +90,7 @@ function proxyPlugin(options: ConcileVitePluginOptions): Plugin { }; }, async configureServer(server) { + if (running) return; const root = server.config.root; const cli = resolveCli(root, options.command); const args = buildDevArgs(cli.baseArgs, port, options.functionsDir ?? DEFAULT_FUNCTIONS_DIR, options.args ?? []); diff --git a/packages/vite/test/plugin.test.ts b/packages/vite/test/plugin.test.ts index f71edde0..b10297e4 100644 --- a/packages/vite/test/plugin.test.ts +++ b/packages/vite/test/plugin.test.ts @@ -20,6 +20,21 @@ describe("concile() plugin — config hook", () => { expect(Object.keys(proxy).sort()).toEqual(["/_admin", "/_dashboard", "/api"]); }); + it("under `concile dev --run`, proxies to the running backend and starts none", async () => { + process.env.CONCILE_DEV_BACKEND = "http://127.0.0.1:3999"; + try { + const plugin = concile(); + const cfg = (await (plugin.config as (c: unknown, e: unknown) => unknown)({}, { command: "serve" })) as { + server: { proxy: Record }; + }; + expect(cfg.server.proxy["/api"]!.target).toBe("http://127.0.0.1:3999"); + // A server without config or httpServer would throw if the hook tried to spawn the backend. + await expect((plugin.configureServer as (s: unknown) => unknown)({})).resolves.toBeUndefined(); + } finally { + delete process.env.CONCILE_DEV_BACKEND; + } + }); + it("has the plugin name and a configureServer hook", () => { const plugin = concile(); expect(plugin.name).toBe("concile"); diff --git a/scripts/try-local.sh b/scripts/try-local.sh new file mode 100755 index 00000000..90b9b068 --- /dev/null +++ b/scripts/try-local.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# Try `concile init` from this checkout, exactly as a user would, without publishing anything. +# +# Builds the workspace, packs every publishable package the way the release does (`bun pm pack`), +# then runs this checkout's `concile init` in the current folder. CONCILE_LOCAL_PACKAGES makes +# init install those packed files instead of the npm versions, so `concile dev` and the starters +# afterwards run your local code too. +# +# Usage (from the folder you want to test in): +# /path/to/concile/scripts/try-local.sh [init args] e.g. ... try-local.sh my-app +# SKIP_BUILD=1 ...try-local.sh reuse the last build and tarballs +set -euo pipefail + +REPO="$(cd "$(dirname "$0")/.." && pwd)" +OUT="${TMPDIR:-/tmp}/concile-local" +PACKS="$OUT/tarballs" +MANIFEST="$OUT/manifest.json" + +if [ -z "${SKIP_BUILD:-}" ] || [ ! -f "$MANIFEST" ]; then + echo "Building the workspace (log: $OUT/build.log)..." + mkdir -p "$OUT" + (cd "$REPO" && bun run build) >"$OUT/build.log" 2>&1 || { echo "Build failed. See $OUT/build.log"; exit 1; } + + echo "Packing packages..." + rm -rf "$PACKS" && mkdir -p "$PACKS" + while IFS= read -r dir; do + (cd "$REPO/$dir" && bun pm pack --destination "$PACKS" --quiet >/dev/null) + done < <(cd "$REPO" && node -e 'import("./scripts/list-publishable.mjs").then(m => { for (const p of m.publishablePackages()) console.log(p.dir) })') + + # name -> tarball path, read from each tarball's own package.json. + node - "$PACKS" >"$MANIFEST" <<'EOF' +const { readdirSync } = require("node:fs"); +const { join } = require("node:path"); +const { execFileSync } = require("node:child_process"); +const dir = process.argv[2]; +const out = {}; +for (const f of readdirSync(dir).filter((f) => f.endsWith(".tgz"))) { + const path = join(dir, f); + out[JSON.parse(execFileSync("tar", ["-xOzf", path, "package/package.json"], { encoding: "utf8" })).name] = path; +} +process.stdout.write(JSON.stringify(out, null, 2) + "\n"); +EOF + echo "Packed $(ls "$PACKS"/*.tgz | wc -l | tr -d ' ') packages." +fi + +CONCILE_LOCAL_PACKAGES="$MANIFEST" exec node "$REPO/packages/cli/dist/bin.js" init "$@" diff --git a/www/app/(home)/Hero.tsx b/www/app/(home)/Hero.tsx index b8dc85e0..9733f57a 100644 --- a/www/app/(home)/Hero.tsx +++ b/www/app/(home)/Hero.tsx @@ -39,12 +39,12 @@ export function Hero() { is decoration, not content: a screen reader should hear the command, not the dollar sign. */} - npm i concile && npx concile dev + npx concile init