Skip to content
Merged
12 changes: 6 additions & 6 deletions docs/docs/schematics/component.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ schematics @nanoforge-dev/schematics:component --part=client --name=health

## Options

| Option | Type | Default | Description |
| ----------- | ---------------------- | --------- | ------------------------------------------------------------------------------------ |
| `name` | `string` | `example` | Component name. `health` gives the class `HealthComponent` in `health.component.ts`. |
| `part` | `"client" \| "server"` | required | Required, but the generated file is the same for both. |
| `directory` | `string` | `.` | Folder to write to. |
| `language` | `"ts" \| "js"` | `ts` | `.ts` or `.js` file. |
| Option | Type | Default | Description |
| ----------- | ---------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `name` | `string` | `example` | Component name: a letter, then letters, digits, `-` or `_`. `health` gives the class `HealthComponent` in `health.component.ts`. |
| `part` | `"client" \| "server"` | required | Required, but the generated file is the same for both. |
| `directory` | `string` | `.` | Folder to write to. |
| `language` | `"ts" \| "js"` | `ts` | `.ts` or `.js` file. |

## Generated file

Expand Down
40 changes: 16 additions & 24 deletions docs/docs/schematics/system.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ schematics @nanoforge-dev/schematics:system --part=client --name=movement

## Options

| Option | Type | Default | Description |
| ----------- | ---------------------- | --------- | ------------------------------------------------------------------------------------ |
| `name` | `string` | `example` | System name. `movement` gives the function `movementSystem` in `movement.system.ts`. |
| `part` | `"client" \| "server"` | required | Required. Only the JS file uses it, in a JSDoc comment. |
| `directory` | `string` | `.` | Folder to write to. |
| `language` | `"ts" \| "js"` | `ts` | `.ts` or `.js` file. |
| Option | Type | Default | Description |
| ----------- | ---------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `name` | `string` | `example` | System name: a letter, then letters, digits, `-` or `_`. `movement` gives the function `movementSystem` in `movement.system.ts`. |
| `part` | `"client" \| "server"` | required | Required. Only the JS file uses it, in a JSDoc comment. |
| `directory` | `string` | `.` | Folder to write to. |
| `language` | `"ts" \| "js"` | `ts` | `.ts` or `.js` file. |

## Generated file

Expand All @@ -32,21 +32,14 @@ schematics @nanoforge-dev/schematics:system --part=client --name=movement
import { type Context } from "@nanoforge-dev/common";
import { type EditorSystemManifest, type Registry } from "@nanoforge-dev/ecs";

import { ExampleComponent } from "../components/example.component";
// Position2D comes with every new project: replace it with the components this system works on.
import { Position2D } from "../components/position-2d.component";

export const movementSystem = (registry: Registry, ctx: Context) => {
const entities = registry.getZipper([ExampleComponent]);
const entities = registry.getZipper([Position2D]);

entities.forEach((entity) => {
if (entity.ExampleComponent.paramA === "end") {
ctx.app.setIsRunning(false);
return;
}

if (entity.ExampleComponent.paramB === 0) entity.ExampleComponent.paramA = "end";

if (entity.ExampleComponent.paramB >= 0)
entity.ExampleComponent.paramB = entity.ExampleComponent.paramB - 1;
entities.forEach(({ Position2D }) => {
if (Position2D.x > 1000) ctx.app.requestStop();
});
};

Expand All @@ -56,15 +49,14 @@ export default movementSystem.name;
// * Required for the editor to display the system and generate code
export const EDITOR_SYSTEM_MANIFEST: EditorSystemManifest = {
name: "movement",
description:
"This system end the game when paramB reaches 0 for any entity with ExampleComponent",
dependencies: ["ExampleComponent"],
description: "This system ends the game once an entity with Position2D goes past x = 1000",
dependencies: ["Position2D"],
};
```

The example system works on `ExampleComponent`, imported from `../components/example.component`.
That file exists only if you created a component named `example`. Replace it with your own
components.
The example system works on `Position2D`, imported from `../components/position-2d.component`,
which `nf new` creates in every app. The import assumes the default `src/systems` and
`src/components` folders. Replace it with your own components.

## System signature

Expand Down
4 changes: 2 additions & 2 deletions docs/guides/components-and-systems.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ them from the registry.
```

It writes `src/systems/regen.system.ts`, with a `regenSystem` function. It imports
`ExampleComponent` from `../components/example.component`, a file `nf new` doesn't create:
replace that import and `ExampleComponent` with your component:
`Position2D` from `../components/position-2d.component`, which every new project has:
replace that import and `Position2D` with your component:

```ts src/systems/regen.system.ts
import type { Context } from "@nanoforge-dev/common";
Expand Down
11 changes: 11 additions & 0 deletions libs/schematics/e2e/component.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,17 @@ describe("component schematic", () => {
});
});

describe("name validation", () => {
it.each(["2d sprite", "my component", "-component", ""])(
"should reject %j, which gives no identifier",
async (name) => {
await expect(runner.runSchematic("component", { name, part: "client" })).rejects.toThrow(
/pattern/,
);
},
);
});

describe("custom directory", () => {
it("should generate file in the specified directory", async () => {
const tree = await runner.runSchematic("component", {
Expand Down
55 changes: 53 additions & 2 deletions libs/schematics/e2e/project.test.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { SchematicTestRunner, type UnitTestTree } from "@angular-devkit/schematics/testing";
import { EOL } from "node:os";
import { resolve } from "node:path";
import { beforeAll, describe, expect, it } from "vitest";
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";

const collectionPath = resolve(__dirname, "../dist/collection.json");

// The factory resolves real registry versions (respecting a 48h trust
// window) for standalone projects, so we can't assert an exact pinned
// number here — only that a registry-resolved value or a workspace-linking
// protocol came back.
// Includes semver-range fallbacks (e.g. "^2") so this still passes when the
// Includes semver-range fallbacks (e.g. "^3") so this still passes when the
// registry is unreachable and the fetcher falls back to its default.
const RESOLVED_VERSION = /^(\d+\.\d+\.\d+|workspace:\*|\*|latest|\^\d+(\.\d+){0,2})$/;

Expand Down Expand Up @@ -76,6 +76,14 @@ describe("project schematic", () => {
expect(content).not.toContain("ctx.libs");
});

it("should only pass the defined props to new Circle, for exactOptionalPropertyTypes", () => {
const content = tree.readContent(
"/apps/client/src/components/drawable-circle-2d.component.ts",
);
expect(content).toMatch(/new Circle\(\s*definedProps\(\{/);
expect(content).toContain("value !== undefined");
});

it("should not generate Dockerfile or init functions by default", () => {
expect(tree.files).not.toContain("/apps/client/Dockerfile");
expect(tree.files).not.toContain("/apps/client/.dockerignore");
Expand Down Expand Up @@ -352,6 +360,20 @@ describe("project schematic", () => {
expect(tree.files).toContain("/js-apps/client/jsconfig.json");
expect(tree.files).not.toContain("/js-apps/client/tsconfig.json");
});

it("should enable esModuleInterop in a standalone jsconfig.json, like the tsconfig.json", async () => {
const standalone = await runner.runSchematic("project", {
part: "client",
workspaceName: "js-standalone-workspace",
directory: "js-standalone-apps/client",
language: "js",
workspace: false,
});
const jsconfig = JSON.parse(
standalone.readContent("/js-standalone-apps/client/jsconfig.json"),
);
expect(jsconfig.compilerOptions.esModuleInterop).toBe(true);
});
});

describe("@nanoforge-dev/ecs and @nanoforge-dev/network version resolution", () => {
Expand Down Expand Up @@ -386,6 +408,35 @@ describe("project schematic", () => {
});
});

describe("when the registry lookup fails", () => {
afterEach(() => {
vi.unstubAllGlobals();
});

it.each(["client", "server"] as const)(
"falls back to the engine 3 range for every %s engine package",
async (part) => {
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("network down")));
const tree = await runner.runSchematic("project", {
part,
workspaceName: `offline-${part}-workspace`,
directory: `offline-${part}-apps/${part}`,
workspace: false,
hasServer: true,
});
const packageJson = JSON.parse(
tree.readContent(`/offline-${part}-apps/${part}/package.json`),
);
const engineDeps = Object.entries({
...packageJson.dependencies,
...packageJson.devDependencies,
}).filter(([name]) => name.startsWith("@nanoforge-dev/") && name !== "@nanoforge-dev/cli");
expect(engineDeps.length).toBeGreaterThan(0);
for (const [, version] of engineDeps) expect(version).toBe("^3");
},
);
});

describe("packageManager (Corepack) field", () => {
it("is never set on a generated project's package.json", async () => {
const tree = await runner.runSchematic("project", {
Expand Down
29 changes: 29 additions & 0 deletions libs/schematics/e2e/system.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,15 @@ describe("system schematic", () => {
expect(content).toContain("export const EDITOR_SYSTEM_MANIFEST");
expect(content).toContain('name: "mySystem"');
});

it("should only use a component and an AppContext method that exist in a new project", () => {
const content = tree.readContent("/my-app/my-system.system.ts");
expect(content).toContain('from "../components/position-2d.component"');
expect(content).toContain('dependencies: ["Position2D"]');
expect(content).toContain("ctx.app.requestStop()");
expect(content).not.toContain("ExampleComponent");
expect(content).not.toContain("setIsRunning");
});
});

describe("TypeScript system for server part", () => {
Expand Down Expand Up @@ -101,6 +110,15 @@ describe("system schematic", () => {
expect(content).toContain("export const EDITOR_SYSTEM_MANIFEST");
expect(content).toContain('name: "mySystem"');
});

it("should only use a component and an AppContext method that exist in a new project", () => {
const content = tree.readContent("/my-app/my-system.system.js");
expect(content).toContain('from "../components/position-2d.component"');
expect(content).toContain('dependencies: ["Position2D"]');
expect(content).toContain("ctx.app.requestStop()");
expect(content).not.toContain("ExampleComponent");
expect(content).not.toContain("setIsRunning");
});
});

describe("name formatting", () => {
Expand Down Expand Up @@ -141,6 +159,17 @@ describe("system schematic", () => {
});
});

describe("name validation", () => {
it.each(["2d sprite", "my system", "-system", ""])(
"should reject %j, which gives no identifier",
async (name) => {
await expect(runner.runSchematic("system", { name, part: "client" })).rejects.toThrow(
/pattern/,
);
},
);
});

describe("custom directory", () => {
it("should generate file in the specified directory", async () => {
const tree = await runner.runSchematic("system", {
Expand Down
20 changes: 19 additions & 1 deletion libs/schematics/e2e/workspace.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { SchematicTestRunner, type UnitTestTree } from "@angular-devkit/schematics/testing";
import { EOL } from "node:os";
import { resolve } from "node:path";
import { beforeAll, describe, expect, it } from "vitest";
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";

const collectionPath = resolve(__dirname, "../dist/collection.json");

Expand Down Expand Up @@ -111,6 +111,11 @@ describe("workspace schematic", () => {
expect(tree.files).not.toContain("/js-workspace/nanoforge.config.ts");
});

it("should enable esModuleInterop in jsconfig.json, like the tsconfig.json", () => {
const jsconfig = JSON.parse(tree.readContent("/js-workspace/jsconfig.json"));
expect(jsconfig.compilerOptions.esModuleInterop).toBe(true);
});

it("has the same package.json shape as the TypeScript workspace, minus typescript itself", () => {
const packageJson = JSON.parse(tree.readContent("/js-workspace/package.json"));
expect(packageJson.devDependencies["typescript"]).toBeUndefined();
Expand All @@ -132,6 +137,19 @@ describe("workspace schematic", () => {
});
});

describe("when the registry lookup fails", () => {
afterEach(() => {
vi.unstubAllGlobals();
});

it("falls back to the engine 3 range for @nanoforge-dev/config", async () => {
vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("network down")));
const tree = await runner.runSchematic("workspace", { name: "offline-workspace" });
const packageJson = JSON.parse(tree.readContent("/offline-workspace/package.json"));
expect(packageJson.devDependencies["@nanoforge-dev/config"]).toBe("^3");
});
});

describe("with custom directory", () => {
it("should generate files in the specified directory", async () => {
const tree = await runner.runSchematic("workspace", {
Expand Down
5 changes: 3 additions & 2 deletions libs/schematics/src/defaults.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
export const DEFAULT_APP_NAME = "nanoforge-app";
export const DEFAULT_LANGUAGE = "ts";
export const DEFAULT_PACKAGE_MANAGER = "npm";
export const DEFAULT_NANOFORGE_DEPENDENCY_VERSION = "^2";
export const DEFAULT_ENGINE_VERSION = "^2";
/** Fallbacks used when an engine package lookup fails: keep them on the engine major the templates are written for. */
export const DEFAULT_NANOFORGE_DEPENDENCY_VERSION = "^3";
export const DEFAULT_ENGINE_VERSION = "^3";

/** Fallback used when the registry lookup for `@nanoforge-dev/cli` fails. */
export const DEFAULT_CLI_DEPENDENCY_VERSION = "latest";
Expand Down
3 changes: 2 additions & 1 deletion libs/schematics/src/libs/component/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"properties": {
"name": {
"type": "string",
"description": "Component name",
"description": "Component name: a letter, then letters, digits, \"-\" or \"_\"",
"pattern": "^[A-Za-z][A-Za-z0-9_-]*$",
"default": "example"
},
"directory": {
Expand Down
2 changes: 1 addition & 1 deletion libs/schematics/src/libs/project/files/js/jsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"resolvePackageJsonImports": true,

"allowSyntheticDefaultImports": true,
"esModuleInterop": false,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@ import type { NfFile } from "@nanoforge-dev/common";
import type { EditorComponentManifest } from "@nanoforge-dev/ecs";
import { Circle, type Layer } from "@nanoforge-dev/graphics-2d";

// Drops the props left undefined, which `exactOptionalPropertyTypes` (strict projects) rejects.
const definedProps = <T extends object>(props: T) =>
Object.fromEntries(Object.entries(props).filter(([, value]) => value !== undefined)) as {
[K in keyof T]: Exclude<T[K], undefined>;
};

export class DrawableCircle2D {
public readonly name: string = this.constructor.name;
shape: Circle;
Expand Down Expand Up @@ -29,31 +35,33 @@ export class DrawableCircle2D {
fillPatternRotation?: number,
fillPatternRepeat?: string,
) {
this.shape = new Circle({
radius,
visible,
id,
opacity,
scaleX,
scaleY,
skewX,
skewY,
rotation,
offsetX,
offsetY,
fill: fillColor,
fillPatternImage: _fillPatternImage
? Object.assign(new Image(), { src: _fillPatternImage.path })
: undefined,
fillPatternX,
fillPatternY,
fillPatternOffsetX,
fillPatternOffsetY,
fillPatternScaleX,
fillPatternScaleY,
fillPatternRotation,
fillPatternRepeat,
});
this.shape = new Circle(
definedProps({
radius,
visible,
id,
opacity,
scaleX,
scaleY,
skewX,
skewY,
rotation,
offsetX,
offsetY,
fill: fillColor,
fillPatternImage: _fillPatternImage
? Object.assign(new Image(), { src: _fillPatternImage.path })
: undefined,
fillPatternX,
fillPatternY,
fillPatternOffsetX,
fillPatternOffsetY,
fillPatternScaleX,
fillPatternScaleY,
fillPatternRotation,
fillPatternRepeat,
}),
);
}

get radius() {
Expand Down
Loading