Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/docs/commands/dev.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ your project's package manager:
and the server restarts when the server build changes.

Open the URL that `nf start` prints, [http://localhost:3000](http://localhost:3000) by default.
Stop both with `Ctrl+C`.
Stop both with `Ctrl+C`. If one of them stops with an error, `nf dev` stops the other one and exits with
code 1.

## Usage

Expand Down
10 changes: 8 additions & 2 deletions docs/docs/commands/editor.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,23 @@ description: Start the NanoForge visual editor
## What it does

`nf editor` starts the NanoForge editor, a visual tool to build scenes, entities, components and
systems. It runs on your machine and you use it in the browser. It prints its URL:
systems. It runs on your machine and you use it in the browser. It prints its URL once the editor
answers:

```text
🔗 Editor running! Open it in your browser: http://localhost:5173
```

- **With a `[path]`**, it opens that project: the URL is `http://localhost:<port>/load?path=...`,
and the browser opens by default once the editor answers (it waits up to 30 seconds).
and the browser opens by default once the editor answers.
- **Without a path**, the editor shows its project list, and no browser opens unless you pass
`--open`.

If the editor stops with an error, `nf editor` prints `Editor failed!` and exits with code 1. If it
has not answered after 30 seconds, `nf editor` prints a warning with the URL and keeps running. If
a NanoForge editor already answers on the port, `nf editor` stops: open that one, or pass another
`--port`.

The editor can open projects only inside its root folder. The root is the `-d` folder, or the
parent folder of `[path]` when the project is outside of `-d`.

Expand Down
13 changes: 8 additions & 5 deletions docs/docs/commands/start.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ It reads environment variables from the shell and from the `.env` file of the `-
passes the `NANOFORGE_*` ones to the apps. See
[environment variables](../configuration/environment-variables).

`nf start` keeps running until you stop it with `Ctrl+C`. The [loader pages](/docs/loader/overview)
`nf start` keeps running until you stop it with `Ctrl+C`. If the client or the server stops with an error, `nf start`
stops the other one and exits with code 1. The [loader pages](/docs/loader/overview)
describe what runs in the browser and on the server.

## Usage
Expand Down Expand Up @@ -57,8 +58,9 @@ export default defineConfig({
});
```

Give **absolute paths**. The client loader runs from its own package folder, so a relative path
is not resolved from your project. `--cert` and `--key` win over the configuration. You can also put the game behind a reverse proxy
Relative paths work: `--cert` and `--key` are resolved from the current folder, `tls.cert` and
`tls.key` from the client app's folder. `nf start` checks that both files exist before it starts.
`--cert` and `--key` win over the configuration. You can also put the game behind a reverse proxy
that serves HTTPS.

## Peer-to-peer
Expand All @@ -78,7 +80,7 @@ nf start --port 8080
Serve over HTTPS:

```bash
nf start --cert "$PWD/certs/cert.pem" --key "$PWD/certs/key.pem"
nf start --cert certs/cert.pem --key certs/key.pem
```

Serve builds made in other folders:
Expand All @@ -93,7 +95,8 @@ nf start --client-dir build/client --server-dir build/server
a workspace whose `packages` match no app. Check the patterns.
- **`No certificate found for TLS.` / `No key found for TLS.`** You gave one of `--cert` and
`--key` (or `tls.enable: true` without both paths). Give both.
- **The client fails to start with `--cert` and `--key`.** Check that both paths are absolute.
- **`TLS file not found: <path>.`** The certificate or the key is not at that path. A flag is
relative to the current folder, a `tls` path to the client app's folder.
- **The page shows `Storage issue: The game must be hosted with SSL (HTTPS)...`.** You opened the
game on an address that isn't `localhost` over HTTP. Use HTTPS (see above).
- **`No build found at <folder>`.** The build folder doesn't exist, and `nf start` stops: run
Expand Down
8 changes: 4 additions & 4 deletions docs/docs/configuration/configuration-file.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,10 @@ export default defineConfig({ type: "lib" });

A `client` also has:

| Field | Type | Default | Description |
| ------ | --------------------------------------------------------------------- | ------------------- | --------------------------------------------------------------------------------------------------------- |
| `port` | `string` | `"3000"` | Port of the web page that `nf start` serves. `nf start --port` overrides it. |
| `tls` | `{ enable?: false }` or `{ enable: true, cert: string, key: string }` | `{ enable: false }` | Serve over HTTPS with this certificate and key. Use absolute paths. See [HTTPS](../commands/start#https). |
| Field | Type | Default | Description |
| ------ | --------------------------------------------------------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `port` | `string` | `"3000"` | Port of the web page that `nf start` serves. `nf start --port` overrides it. |
| `tls` | `{ enable?: false }` or `{ enable: true, cert: string, key: string }` | `{ enable: false }` | Serve over HTTPS with this certificate and key. A relative path is relative to the client app's folder. See [HTTPS](../commands/start#https). |

### Example

Expand Down
107 changes: 107 additions & 0 deletions src/action/abstract.action.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import { treeKill } from "@lib/tree-kill";

import { AbstractAction, type HandleResult } from "./abstract.action";

vi.mock("@lib/tree-kill", () => ({ treeKill: vi.fn().mockResolvedValue(undefined) }));

class ChildrenAction extends AbstractAction {
protected startMessage = "Start";
protected successMessage = "Done";
protected failureMessage = "Children failed!";

constructor(private readonly tasks: () => Promise<boolean>[]) {
super();
}

public handle(): Promise<HandleResult> {
return this.waitForChildren(this.tasks());
}
}

const never = () => new Promise<boolean>(() => undefined);

describe("AbstractAction with child processes", () => {
let exit: ReturnType<typeof vi.spyOn>;
let error: ReturnType<typeof vi.spyOn>;
let signalListeners: Map<string, () => void>;

beforeEach(() => {
vi.clearAllMocks();
exit = vi.spyOn(process, "exit").mockImplementation((() => undefined) as never);
error = vi.spyOn(console, "error").mockImplementation(() => undefined);
vi.spyOn(console, "info").mockImplementation(() => undefined);
signalListeners = new Map();
vi.spyOn(process, "once").mockImplementation(((event: string, listener: () => void) => {
signalListeners.set(event, listener);
return process;
}) as never);
});

afterEach(() => {
vi.restoreAllMocks();
});

it("stops the other children and exits 1 with the failure message when one fails", async () => {
await new ChildrenAction(() => [Promise.resolve(false), never()]).run();

expect(error).toHaveBeenCalledWith(expect.stringContaining("Children failed!"));
expect(treeKill).toHaveBeenCalledWith(process.pid, "SIGTERM");
expect(exit).toHaveBeenCalledWith(1);
});

it("prints the error of a child that rejects", async () => {
await new ChildrenAction(() => [
Promise.reject(new Error("exited with code 1")),
never(),
]).run();

expect(error).toHaveBeenCalledWith("exited with code 1");
expect(exit).toHaveBeenCalledWith(1);
});

it("prints the failure before stopping the process tree", async () => {
const order: string[] = [];
error.mockImplementation(() => order.push("print"));
vi.mocked(treeKill).mockImplementation(async () => {
order.push("kill");
});

await new ChildrenAction(() => [Promise.resolve(false)]).run();

expect(order.indexOf("print")).toBeLessThan(order.indexOf("kill"));
});

it("neither fails nor exits when every child ends cleanly", async () => {
await new ChildrenAction(() => [Promise.resolve(true), Promise.resolve(true)]).run();

expect(treeKill).not.toHaveBeenCalled();
expect(exit).not.toHaveBeenCalled();
});

it("leaves Ctrl+C to the signal handler: a child stopped by it is not a failure", async () => {
let stopChild: (ok: boolean) => void = () => undefined;
const run = new ChildrenAction(() => [
new Promise<boolean>((resolve) => (stopChild = resolve)),
]).run();

signalListeners.get("SIGINT")?.();
stopChild(false);
await run;

expect(treeKill).not.toHaveBeenCalled();
expect(exit).not.toHaveBeenCalled();
expect(error).not.toHaveBeenCalledWith(expect.stringContaining("Children failed!"));
});

it("prints no header when the child's own failure line already says it", async () => {
const action = new ChildrenAction(() => [Promise.resolve(false)]);
Object.assign(action, { childFailureMessage: "" });

await action.run();

expect(error).not.toHaveBeenCalledWith(expect.stringContaining("Children failed!"));
expect(exit).toHaveBeenCalledWith(1);
});
});
49 changes: 45 additions & 4 deletions src/action/abstract.action.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { red } from "ansis";

import { type Input } from "@lib/input";
import { treeKill } from "@lib/tree-kill";
import { Prefixes } from "@lib/ui";

import { handleActionError } from "@utils/errors";
import { getErrorMessage, handleActionError } from "@utils/errors";

const STOP_SIGNALS: NodeJS.Signals[] = ["SIGINT", "SIGTERM", "SIGHUP", "SIGQUIT", "SIGBREAK"];

export interface HandleResult {
success?: boolean;
Expand All @@ -13,6 +18,10 @@ export abstract class AbstractAction {
protected abstract startMessage: string;
protected abstract successMessage: string;
protected abstract failureMessage: string;
/** Printed when a child fails; empty when the child's own failure line says the same. */
protected childFailureMessage?: string;

private stopping = false;

public abstract handle(
args?: Input,
Expand All @@ -25,23 +34,39 @@ export abstract class AbstractAction {

try {
const result = await this.handle(args, options, extraFlags);
this.resolveResult(result);
await this.resolveResult(result);
} catch (error: unknown) {
handleActionError(this.failureMessage, error);
}
}

/**
* Keeps the command alive while the processes it started run. The first one that fails (resolves
* `false` or rejects) fails the command: the others are stopped and the CLI exits 1.
*/
protected waitForChildren(tasks: Promise<boolean>[]): Promise<HandleResult> {
// Ctrl+C stops the children too: nf.ts kills the tree then, it is not a failure.
for (const signal of STOP_SIGNALS) process.once(signal, () => (this.stopping = true));

return new Promise((resolve) => {
const fail = (error?: unknown) => resolve({ keepAlive: true, success: false, error });
for (const task of tasks) void task.then((ok) => (ok ? undefined : fail()), fail);
void Promise.allSettled(tasks).then(() => resolve({ keepAlive: true }));
});
}

private logStart(): void {
console.info();
console.info(`${Prefixes.INFO} ${this.startMessage}`);
console.info();
}

private resolveResult(result: HandleResult): void {
private async resolveResult(result: HandleResult): Promise<void> {
const success = result?.success !== false;
const keepAlive = result?.keepAlive === true;

if (keepAlive) return;
if (keepAlive && success) return;
if (keepAlive) return this.stopChildren(result.error);

console.info();

Expand All @@ -53,4 +78,20 @@ export abstract class AbstractAction {
if (this.successMessage) console.info(this.successMessage);
process.exit(0);
}

private async stopChildren(error: unknown): Promise<void> {
if (this.stopping) return;

// Printed first: on Windows, taskkill /T /F ends this process too.
console.error();
const header = this.childFailureMessage ?? this.failureMessage;
if (header) console.error(red(header));
const message = getErrorMessage(error);
if (message) console.error(message);

// shortcut: kills the CLI's whole process tree (itself last, exit 1 runs first), as the runner
// exposes no child to kill; kill only the children once the runner hands them out.
await treeKill(process.pid, "SIGTERM");
process.exit(1);
}
}
50 changes: 39 additions & 11 deletions src/action/actions/dev.action.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { resolve } from "path";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

import { type Input } from "@lib/input";
import { PackageManagerFactory } from "@lib/package-manager";
import { RunnerFactory } from "@lib/runner";

import { DevAction } from "./dev.action";

vi.mock("@lib/package-manager", () => ({
PackageManagerFactory: { find: vi.fn() },
vi.mock("@lib/runner", () => ({
RunnerFactory: { create: vi.fn() },
}));

const GAME = resolve("game");
Expand All @@ -16,18 +16,46 @@ const createInput = (entries: [string, any][]): Input =>
new Map(entries.map(([key, value]) => [key, { value }]));

describe("DevAction", () => {
const runDev = vi.fn().mockResolvedValue(true);
const run = vi.fn();

beforeEach(() => {
vi.clearAllMocks();
vi.mocked(PackageManagerFactory.find).mockResolvedValue({ runDev } as any);
run.mockResolvedValue(null);
vi.mocked(RunnerFactory.create).mockReturnValue({ run } as any);
vi.spyOn(process, "once").mockImplementation((() => process) as never);
});

it("runs build and start in watch mode with their output shown, not collected", async () => {
afterEach(() => {
vi.restoreAllMocks();
});

it("fails as soon as build or start fails, without waiting for the other", async () => {
run.mockImplementation(([command]: string[]) =>
command === "start"
? Promise.reject(new Error("exited with code 1"))
: new Promise(() => undefined),
);

await expect(
new DevAction().handle(new Map(), createInput([["directory", GAME]])),
).resolves.toMatchObject({ keepAlive: true, success: false });
});

it("runs the running CLI itself, never `<pm> exec nf`", async () => {
await new DevAction().handle(new Map(), createInput([["directory", GAME]]));

expect(RunnerFactory.create).toHaveBeenCalledWith(process.execPath, [process.argv[1]]);
expect(RunnerFactory.create).not.toHaveBeenCalledWith(
expect.stringMatching(/^(npm|pnpm|yarn|bun)$/),
expect.anything(),
);
});

it("runs build and start in watch mode in the project, with their output shown", async () => {
await new DevAction().handle(new Map(), createInput([["directory", GAME]]));

expect(runDev).toHaveBeenCalledWith(GAME, "nf", {}, ["build", "--watch"], false);
expect(runDev).toHaveBeenCalledWith(GAME, "nf", {}, ["start", "--watch"], false);
expect(run).toHaveBeenCalledWith(["build", "--watch"], { cwd: GAME });
expect(run).toHaveBeenCalledWith(["start", "--watch"], { cwd: GAME });
});

it("passes --editor to the build only", async () => {
Expand All @@ -39,7 +67,7 @@ describe("DevAction", () => {
]),
);

expect(runDev).toHaveBeenCalledWith(GAME, "nf", {}, ["build", "--watch", "--editor"], false);
expect(runDev).toHaveBeenCalledWith(GAME, "nf", {}, ["start", "--watch"], false);
expect(run).toHaveBeenCalledWith(["build", "--watch", "--editor"], { cwd: GAME });
expect(run).toHaveBeenCalledWith(["start", "--watch"], { cwd: GAME });
});
});
Loading
Loading