@aethervtt/shard-testing 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Patrick Dias
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # @aethervtt/shard-testing
2
+
3
+ Part of [Shard](https://github.com/aethervtt/shard), a WebGPU-first 2D/3D game engine in TypeScript. See the repository for documentation.
@@ -0,0 +1,94 @@
1
+ import { type HeadlessProject } from '@aethervtt/shard-node';
2
+ import type { App } from '@aethervtt/shard-runtime';
3
+ export { describe, expect } from 'vitest';
4
+ type Json = Record<string, any>;
5
+ /**
6
+ * The game under test: a headless app with the project loaded, fixed timestep, fixed seed. Every
7
+ * method maps to a protocol call, so tests exercise the same surface agents use.
8
+ */
9
+ export declare class Game {
10
+ readonly project: HeadlessProject;
11
+ private nextId;
12
+ constructor(project: HeadlessProject);
13
+ get app(): App;
14
+ /** Any protocol method. Throws the ShardError on failure. */
15
+ call<T = Json>(method: string, params?: unknown): Promise<T>;
16
+ /** Loads a scene file, replacing the start scene. */
17
+ load(scenePath: string): Promise<void>;
18
+ /** Runs `frames` frames at the fixed timestep. */
19
+ step(frames?: number): Promise<void>;
20
+ /** A component's JSON value on the entity at `path` (or id), as the protocol would report it. */
21
+ get(entity: string | number, component: string): Json;
22
+ /** All components of an entity as JSON. */
23
+ entity(entity: string | number): Promise<Json>;
24
+ patch(entity: string | number, components: Json): Promise<void>;
25
+ readonly input: {
26
+ /** Holds an action (`"<map>.<action>"`) or key (`"KeyW"`) until released. */
27
+ hold: (name: string) => void;
28
+ release: (name: string) => void;
29
+ /** Press for one frame. */
30
+ press: (name: string) => Promise<void>;
31
+ };
32
+ /**
33
+ * Sounds started, stopped, and dropped (audio plugin) from frame `since`, as `audio.log` returns
34
+ * them: `{ frame, event, clip, entity, path, bus, position, gain, pan, reason }`.
35
+ */
36
+ audioLog(since?: number): Promise<Json[]>;
37
+ /** UI (ui plugin): read the HUD as data and press buttons by path, without pixel coordinates. */
38
+ readonly ui: {
39
+ /** `ui.describe`: every tree with rects, text, widget state, focus, and anchors. */
40
+ describe: () => Promise<Json>;
41
+ /** One node from `ui.describe` by scene path (or a unique suffix, like "fuel/label"). */
42
+ node: (path: string) => Promise<Json | undefined>;
43
+ /** Clicks a button or toggle (`ui.click`); step a frame for systems to see the UiClick. */
44
+ click: (path: string) => Promise<void>;
45
+ focus: (path: string | null) => Promise<void>;
46
+ };
47
+ /** Navigation (nav plugin): paths and agents as data. */
48
+ readonly nav: {
49
+ /** `nav.describe`: grids, navmeshes (tiles, last bake), and agents. */
50
+ describe: () => Promise<Json>;
51
+ /** `nav.path` between two world points: `{ status, length, corners }`. */
52
+ path: (from: [number, number, number], to: [number, number, number]) => Promise<{
53
+ status: 'complete' | 'partial' | 'none';
54
+ length: number;
55
+ corners: number[][];
56
+ }>;
57
+ /** One NavAgent from `nav.describe` by scene path (or a unique suffix): status, remaining, route. */
58
+ agent: (path: string) => Promise<Json | undefined>;
59
+ };
60
+ /** Saved games (save plugin): the same calls as save_game and load_game. */
61
+ readonly saves: {
62
+ /** Saves the game to a slot; returns `save.describe` of it. */
63
+ write: (slot: string, meta?: unknown) => Promise<Json>;
64
+ /** Loads a slot, or a save file (an edited fixture). Returns `{ scenes, spawned, warnings }`. */
65
+ load: (slot: string | Json) => Promise<Json>;
66
+ /** A slot's save as JSON, or without a slot the game as it would save now. */
67
+ read: (slot?: string) => Promise<Json>;
68
+ describe: (slot?: string) => Promise<Json>;
69
+ };
70
+ /** Settings resources (`engine/Settings` by default): read, or set and apply at once. */
71
+ readonly settings: {
72
+ get: (name?: string) => Promise<Json>;
73
+ set: (values: Json, name?: string) => Promise<Json>;
74
+ };
75
+ /** Switches the locale (`"pt-BR"`); keyed text updates on the next frame. */
76
+ locale(tag: string): Promise<void>;
77
+ /** Saves a PNG of a camera (default: the first) to `.shard/test-results/<name>`. Returns the path. */
78
+ screenshot(name: string, options?: {
79
+ camera?: string;
80
+ width?: number;
81
+ height?: number;
82
+ }): Promise<string>;
83
+ private inject;
84
+ private resolve;
85
+ }
86
+ /** A gameplay test. Each test gets a fresh game; the GPU is shared across a file. */
87
+ export declare function test(name: string, fn: (ctx: {
88
+ game: Game;
89
+ }) => Promise<void> | void, timeout?: number): void;
90
+ export declare namespace test {
91
+ var skip: (name: string, _fn: (ctx: {
92
+ game: Game;
93
+ }) => Promise<void> | void) => void;
94
+ }
package/dist/index.js ADDED
@@ -0,0 +1,209 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { findComponent, ShardError } from "@aethervtt/shard-core";
4
+ import { createNodeGpuContext } from "@aethervtt/shard-gpu/node";
5
+ import { openProject } from "@aethervtt/shard-node";
6
+ import { findEntityByPath } from "@aethervtt/shard-scene";
7
+ import { afterAll, test as vitestTest } from "vitest";
8
+ import { describe, expect } from "vitest";
9
+ class Game {
10
+ project;
11
+ nextId = 1;
12
+ constructor(project) {
13
+ this.project = project;
14
+ }
15
+ get app() {
16
+ return this.project.app;
17
+ }
18
+ /** Any protocol method. Throws the ShardError on failure. */
19
+ async call(method, params) {
20
+ const response = await this.project.server.handle({
21
+ jsonrpc: "2.0",
22
+ id: this.nextId++,
23
+ method,
24
+ params
25
+ });
26
+ if (response.error) {
27
+ const data = response.error.data;
28
+ throw new ShardError(data?.code ?? "testing/protocol", response.error.message, {
29
+ path: data?.path,
30
+ hint: data?.hint
31
+ });
32
+ }
33
+ return response.result;
34
+ }
35
+ /** Loads a scene file, replacing the start scene. */
36
+ async load(scenePath) {
37
+ for (const id of await this.call("app.describe").then((d) => d.scenes)) {
38
+ if (id !== scenePath)
39
+ await this.call("scene.load", { json: { version: 1, entities: [] }, id });
40
+ }
41
+ await this.call("scene.load", { file: scenePath, id: scenePath });
42
+ }
43
+ /** Runs `frames` frames at the fixed timestep. */
44
+ async step(frames = 1) {
45
+ await this.call("time.step", { frames });
46
+ }
47
+ /** A component's JSON value on the entity at `path` (or id), as the protocol would report it. */
48
+ get(entity, component) {
49
+ const world = this.app.world;
50
+ const e = this.resolve(entity);
51
+ const def = findComponent(component);
52
+ if (!def || !world.has(e, def)) throw missing(entity, component);
53
+ return def.serialize(world.get(e, def));
54
+ }
55
+ /** All components of an entity as JSON. */
56
+ async entity(entity) {
57
+ return (await this.call("entity.get", { entity })).components;
58
+ }
59
+ async patch(entity, components) {
60
+ await this.call("entity.patch", { entity, components });
61
+ }
62
+ input = {
63
+ /** Holds an action (`"<map>.<action>"`) or key (`"KeyW"`) until released. */
64
+ hold: (name) => this.inject(name, true),
65
+ release: (name) => this.inject(name, false),
66
+ /** Press for one frame. */
67
+ press: async (name) => {
68
+ this.inject(name, true);
69
+ await this.step(1);
70
+ this.inject(name, false);
71
+ }
72
+ };
73
+ /**
74
+ * Sounds started, stopped, and dropped (audio plugin) from frame `since`, as `audio.log` returns
75
+ * them: `{ frame, event, clip, entity, path, bus, position, gain, pan, reason }`.
76
+ */
77
+ async audioLog(since = 0) {
78
+ return (await this.call("audio.log", { since })).entries;
79
+ }
80
+ /** UI (ui plugin): read the HUD as data and press buttons by path, without pixel coordinates. */
81
+ ui = {
82
+ /** `ui.describe`: every tree with rects, text, widget state, focus, and anchors. */
83
+ describe: async () => this.call("ui.describe"),
84
+ /** One node from `ui.describe` by scene path (or a unique suffix, like "fuel/label"). */
85
+ node: async (path) => {
86
+ const d = await this.call("ui.describe");
87
+ const find = (n) => {
88
+ const p = n.path;
89
+ if (p === path || p?.endsWith(`/${path}`)) return n;
90
+ for (const c of n.children ?? []) {
91
+ const hit = find(c);
92
+ if (hit) return hit;
93
+ }
94
+ return void 0;
95
+ };
96
+ for (const r of d.roots) {
97
+ const hit = find(r.tree);
98
+ if (hit) return hit;
99
+ }
100
+ return void 0;
101
+ },
102
+ /** Clicks a button or toggle (`ui.click`); step a frame for systems to see the UiClick. */
103
+ click: async (path) => {
104
+ await this.call("ui.click", { entity: path });
105
+ },
106
+ focus: async (path) => {
107
+ await this.call("ui.focus", { entity: path });
108
+ }
109
+ };
110
+ /** Navigation (nav plugin): paths and agents as data. */
111
+ nav = {
112
+ /** `nav.describe`: grids, navmeshes (tiles, last bake), and agents. */
113
+ describe: async () => this.call("nav.describe"),
114
+ /** `nav.path` between two world points: `{ status, length, corners }`. */
115
+ path: async (from, to) => this.call("nav.path", { from, to }),
116
+ /** One NavAgent from `nav.describe` by scene path (or a unique suffix): status, remaining, route. */
117
+ agent: async (path) => {
118
+ const d = await this.call("nav.describe");
119
+ return d.agents.find((a) => a.path === path || a.path?.endsWith(`/${path}`));
120
+ }
121
+ };
122
+ /** Saved games (save plugin): the same calls as save_game and load_game. */
123
+ saves = {
124
+ /** Saves the game to a slot; returns `save.describe` of it. */
125
+ write: async (slot, meta) => this.call("save.write", meta === void 0 ? { slot } : { slot, meta }),
126
+ /** Loads a slot, or a save file (an edited fixture). Returns `{ scenes, spawned, warnings }`. */
127
+ load: async (slot) => this.call("save.load", typeof slot === "string" ? { slot } : { json: slot }),
128
+ /** A slot's save as JSON, or without a slot the game as it would save now. */
129
+ read: async (slot) => this.call("save.read", slot ? { slot } : {}),
130
+ describe: async (slot) => this.call("save.describe", slot ? { slot } : {})
131
+ };
132
+ /** Settings resources (`engine/Settings` by default): read, or set and apply at once. */
133
+ settings = {
134
+ get: async (name = "engine/Settings") => (await this.call("settings.get", { name })).settings[name],
135
+ set: async (values, name = "engine/Settings") => this.call("settings.set", { name, values })
136
+ };
137
+ /** Switches the locale (`"pt-BR"`); keyed text updates on the next frame. */
138
+ async locale(tag) {
139
+ await this.call("locale.set", { locale: tag });
140
+ }
141
+ /** Saves a PNG of a camera (default: the first) to `.shard/test-results/<name>`. Returns the path. */
142
+ async screenshot(name, options = {}) {
143
+ const shot = await this.call("render.capture", options);
144
+ const dir = join(this.project.root, ".shard", "test-results");
145
+ await mkdir(dir, { recursive: true });
146
+ const file = join(dir, name);
147
+ await writeFile(file, Buffer.from(shot.data, "base64"));
148
+ return file;
149
+ }
150
+ inject(name, pressed) {
151
+ const isAction = name.includes(".");
152
+ void this.call("input.inject", isAction ? { action: name, pressed } : { key: name, pressed });
153
+ }
154
+ resolve(entity) {
155
+ const world = this.app.world;
156
+ const e = typeof entity === "number" ? entity : findEntityByPath(world, entity);
157
+ if (e === void 0 || !world.isAlive(e)) {
158
+ throw new ShardError("testing/unknown-entity", `No entity ${JSON.stringify(entity)}`, {
159
+ hint: 'Use a scene path like "ship/camera" or an entity id.'
160
+ });
161
+ }
162
+ return e;
163
+ }
164
+ }
165
+ function missing(entity, component) {
166
+ return new ShardError(
167
+ "testing/missing-component",
168
+ `${JSON.stringify(entity)} has no "${component}"`
169
+ );
170
+ }
171
+ let sharedGpu;
172
+ const open = [];
173
+ afterAll(() => {
174
+ for (const p of open.splice(0)) p.close();
175
+ sharedGpu?.destroy();
176
+ sharedGpu = void 0;
177
+ });
178
+ function projectRoot() {
179
+ return process.env.SHARD_PROJECT_ROOT ?? process.cwd();
180
+ }
181
+ function test(name, fn, timeout = 3e4) {
182
+ vitestTest(
183
+ name,
184
+ async () => {
185
+ sharedGpu ??= await createNodeGpuContext();
186
+ const project = await openProject({
187
+ root: projectRoot(),
188
+ // Test files import project modules directly; the game must use the same instances.
189
+ code: "source",
190
+ gpu: sharedGpu,
191
+ width: 320,
192
+ height: 180
193
+ });
194
+ open.push(project);
195
+ await fn({ game: new Game(project) });
196
+ },
197
+ timeout
198
+ );
199
+ }
200
+ test.skip = (name, _fn) => {
201
+ vitestTest.skip(name, () => {
202
+ });
203
+ };
204
+ export {
205
+ Game,
206
+ describe,
207
+ expect,
208
+ test
209
+ };
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@aethervtt/shard-testing",
3
+ "version": "0.0.1",
4
+ "license": "MIT",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ }
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "LICENSE",
16
+ "README.md"
17
+ ],
18
+ "dependencies": {
19
+ "@aethervtt/shard-core": "0.0.1",
20
+ "@aethervtt/shard-gpu": "0.0.1",
21
+ "@aethervtt/shard-node": "0.0.1",
22
+ "@aethervtt/shard-protocol": "0.0.1",
23
+ "@aethervtt/shard-runtime": "0.0.1",
24
+ "vitest": "^5.0.1",
25
+ "@aethervtt/shard-scene": "0.0.1"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/aethervtt/shard.git",
30
+ "directory": "packages/testing"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public",
34
+ "provenance": true
35
+ },
36
+ "shard": {
37
+ "buildSha": "d6c5c6aef4675575c878b02cf2c8f738b4190229"
38
+ }
39
+ }