1
0
Fork 0

Compare commits

...

4 Commits

Author SHA1 Message Date
Pabloader 8b93a732a7 Add linter 2026-04-29 09:28:17 +00:00
Pabloader b866e0a5de RPG engine improvements: caching, cloning, versioning, query overloads
- Condition parse cache: each unique string parsed once (Map<string, ParsedCondition>)
- executeAction: throw on missing type/malformed action/missing action; warn-only on
  destroyed entity (legitimate mid-flight case)
- World.query() overloads for 2 and 3 component types: query(A, B) → [Entity, A, B]
- World.once()/off() consistency: #onceWrappers map lets off(event, original) correctly
  remove handlers registered via once()
- World.cloneEntity(source, newId?): deep-clones all components via structuredClone,
  onAdd() fires normally on the new entity
- isEntityContext() type guard alongside isEvalContext()
- Inventory.getVariables() cache: invalidated on add()/remove()
- QuestLog.getVariables() cache: invalidated on any status transition or _advance()
- QuestLog.entries() explicit Generator return type
- Variables JSDoc: clarifies when to use Variables vs typed Component<TState>
- @component({ name?, version? }) object overload in registry
- registerMigration(name, from, to, fn): chained migrations run automatically on
  deserialize when saved version < current version
- Serialization wire format: ComponentData carries version, WorldData carries
  schemaVersion; mismatched schemaVersion throws a descriptive error

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-29 09:28:05 +00:00
Pabloader 066271205a QoL Improvements for actions and context 2026-04-29 08:16:18 +00:00
Pabloader 9bec7701e0 Serialization 2026-04-29 07:28:16 +00:00
14 changed files with 632 additions and 226 deletions

View File

@ -11,6 +11,7 @@
"backend:dev": "bun --hot backend/src/index.ts",
"register": "bun backend/src/register.ts",
"login": "bun backend/src/login.ts",
"lint": "bun tsc --noEmit --skipLibCheck",
"docker:build": "docker build -t git.pabloader.ru/pabloid/tsgames:latest backend/",
"docker:push": "docker push git.pabloader.ru/pabloid/tsgames:latest",
"docker:update": "docker service update --force --image git.pabloader.ru/pabloid/tsgames:latest tsgames_backend",

View File

@ -1,49 +1,53 @@
import type { InventorySlotInput, RPGVariables, SlotId } from "../types";
import { action } from "../utils/decorators";
import { Component, type EvalContext } from "../core/world";
import { component } from "../core/registry";
import { Stackable, Usable } from "./item";
import { resolveVariables } from "../utils/variables";
interface SlotEntry {
readonly slotId: SlotId;
readonly limit: number | undefined;
state: { itemId: string; amount: number } | null;
interface SlotRecord {
slotId: SlotId;
limit: number | undefined;
contents: { itemId: string; amount: number } | null;
}
interface SlotUpdateArgs {
itemId: string;
amount: number;
slotId?: SlotId;
interface InventoryState {
slots: SlotRecord[];
}
export class Inventory extends Component {
private readonly slots: Map<SlotId, SlotEntry>;
@component
export class Inventory extends Component<InventoryState> {
#cachedVars: RPGVariables | null = null;
constructor(slotDefs: Array<InventorySlotInput>) {
super();
this.slots = new Map(
slotDefs.map(def => {
super({
slots: slotDefs.map(def => {
const slotId = typeof def === 'object' ? def.slotId : def;
const limit = typeof def === 'object' ? def.limit : undefined;
return [slotId, { slotId, limit, state: null }];
})
);
return { slotId, limit, contents: null };
}),
});
}
private slotCapFor(slot: SlotEntry, itemId: string): number {
#slot(slotId: SlotId): SlotRecord | undefined {
return this.state.slots.find(s => s.slotId === slotId);
}
#capFor(slot: SlotRecord, itemId: string): number {
const limitCap = slot.limit ?? Infinity;
const stackable = this.entity.world.getEntity(itemId)?.get(Stackable);
const stackCap = stackable ? stackable.maxStack : 1;
return Math.min(limitCap, stackCap);
}
private slotRoomFor(slot: SlotEntry, itemId: string): number {
if (slot.state !== null && slot.state.itemId !== itemId) return 0;
return this.slotCapFor(slot, itemId) - (slot.state?.amount ?? 0);
#roomFor(slot: SlotRecord, itemId: string): number {
if (slot.contents !== null && slot.contents.itemId !== itemId) return 0;
return this.#capFor(slot, itemId) - (slot.contents?.amount ?? 0);
}
@action
add({ itemId, amount, slotId }: SlotUpdateArgs): boolean {
add({ itemId, amount, slotId }: { itemId: string; amount: number; slotId?: SlotId }): boolean {
this.#cachedVars = null;
if (amount < 0) return false;
if (amount === 0) return true;
@ -53,19 +57,19 @@ export class Inventory extends Component {
}
if (slotId !== undefined) {
const slot = this.slots.get(slotId);
const slot = this.#slot(slotId);
if (!slot) return false;
if (this.slotRoomFor(slot, itemId) < amount) return false;
slot.state = { itemId, amount: (slot.state?.amount ?? 0) + amount };
if (this.#roomFor(slot, itemId) < amount) return false;
slot.contents = { itemId, amount: (slot.contents?.amount ?? 0) + amount };
this.emit('add', { itemId, amount, slotIds: [slotId] });
return true;
}
// Two-phase: pre-check then apply
let remaining = amount;
for (const slot of this.slots.values()) {
if (slot.state === null || slot.state.itemId === itemId) {
remaining -= Math.min(this.slotRoomFor(slot, itemId), remaining);
for (const slot of this.state.slots) {
if (slot.contents === null || slot.contents.itemId === itemId) {
remaining -= Math.min(this.#roomFor(slot, itemId), remaining);
if (remaining === 0) break;
}
}
@ -74,24 +78,24 @@ export class Inventory extends Component {
// Apply — fill existing slots for this item first, then empty ones
remaining = amount;
const slotIds: SlotId[] = [];
for (const [id, slot] of this.slots) {
if (slot.state?.itemId === itemId) {
const take = Math.min(this.slotRoomFor(slot, itemId), remaining);
slot.state.amount += take;
for (const slot of this.state.slots) {
if (slot.contents?.itemId === itemId) {
const take = Math.min(this.#roomFor(slot, itemId), remaining);
slot.contents.amount += take;
remaining -= take;
slotIds.push(id);
slotIds.push(slot.slotId);
if (remaining === 0) {
this.emit('add', { itemId, amount, slotIds });
return true;
}
}
}
for (const [id, slot] of this.slots) {
if (slot.state === null) {
const take = Math.min(this.slotCapFor(slot, itemId), remaining);
slot.state = { itemId, amount: take };
for (const slot of this.state.slots) {
if (slot.contents === null) {
const take = Math.min(this.#capFor(slot, itemId), remaining);
slot.contents = { itemId, amount: take };
remaining -= take;
slotIds.push(id);
slotIds.push(slot.slotId);
if (remaining === 0) {
this.emit('add', { itemId, amount, slotIds });
return true;
@ -103,16 +107,17 @@ export class Inventory extends Component {
}
@action
remove({ itemId, amount, slotId }: SlotUpdateArgs): boolean {
remove({ itemId, amount, slotId }: { itemId: string; amount: number; slotId?: SlotId }): boolean {
this.#cachedVars = null;
if (amount < 0) return false;
if (amount === 0) return true;
if (slotId !== undefined) {
const slot = this.slots.get(slotId);
if (!slot || slot.state?.itemId !== itemId) return false;
if (slot.state.amount < amount) return false;
slot.state.amount -= amount;
if (slot.state.amount === 0) slot.state = null;
const slot = this.#slot(slotId);
if (!slot || slot.contents?.itemId !== itemId) return false;
if (slot.contents.amount < amount) return false;
slot.contents.amount -= amount;
if (slot.contents.amount === 0) slot.contents = null;
this.emit('remove', { itemId, amount, slotIds: [slotId] });
return true;
}
@ -121,13 +126,13 @@ export class Inventory extends Component {
let remaining = amount;
const slotIds: SlotId[] = [];
for (const [id, slot] of this.slots) {
if (slot.state?.itemId === itemId) {
const take = Math.min(slot.state.amount, remaining);
slot.state.amount -= take;
if (slot.state.amount === 0) slot.state = null;
for (const slot of this.state.slots) {
if (slot.contents?.itemId === itemId) {
const take = Math.min(slot.contents.amount, remaining);
slot.contents.amount -= take;
if (slot.contents.amount === 0) slot.contents = null;
remaining -= take;
slotIds.push(id);
slotIds.push(slot.slotId);
if (remaining === 0) {
this.emit('remove', { itemId, amount, slotIds });
return true;
@ -170,27 +175,29 @@ export class Inventory extends Component {
getAmount(itemId: string, slotId?: SlotId): number {
if (slotId !== undefined) {
const slot = this.slots.get(slotId);
return slot?.state?.itemId === itemId ? slot.state.amount : 0;
const slot = this.#slot(slotId);
return slot?.contents?.itemId === itemId ? slot.contents.amount : 0;
}
let total = 0;
for (const slot of this.slots.values()) {
if (slot.state?.itemId === itemId) total += slot.state.amount;
for (const slot of this.state.slots) {
if (slot.contents?.itemId === itemId) total += slot.contents.amount;
}
return total;
}
getItems(): Map<string, number> {
const result = new Map<string, number>();
for (const slot of this.slots.values()) {
if (slot.state) {
result.set(slot.state.itemId, (result.get(slot.state.itemId) ?? 0) + slot.state.amount);
for (const slot of this.state.slots) {
if (slot.contents) {
const { itemId, amount } = slot.contents;
result.set(itemId, (result.get(itemId) ?? 0) + amount);
}
}
return result;
}
override getVariables(): RPGVariables {
if (this.#cachedVars) return this.#cachedVars;
const result: RPGVariables = {};
for (const [itemId, amount] of this.getItems()) {
result[itemId] = amount;
@ -201,6 +208,7 @@ export class Inventory extends Component {
}
}
}
this.#cachedVars = result;
return result;
}
}

View File

@ -1,37 +1,55 @@
import { Component, type EvalContext, type World } from "../core/world";
import { component } from "../core/registry";
import type { RPGAction } from "../types";
import { action, variable } from "../utils/decorators";
import { executeAction } from "../utils/variables";
export class Item extends Component {
constructor(
readonly name: string,
readonly description: string = '',
) {
super();
}
interface ItemState {
name: string;
description: string;
}
export class Stackable extends Component {
@variable readonly maxStack: number;
@component
export class Item extends Component<ItemState> {
constructor(name: string, description = '') {
super({ name, description });
}
get name(): string { return this.state.name; }
get description(): string { return this.state.description; }
}
interface StackableState {
maxStack: number;
}
@component
export class Stackable extends Component<StackableState> {
constructor(maxStack: number) {
super();
this.maxStack = maxStack;
super({ maxStack });
}
@variable get maxStack(): number { return this.state.maxStack; }
}
export class Usable extends Component {
@variable readonly consumeOnUse: boolean;
constructor(private readonly actions: RPGAction[], consumeOnUse = true) {
super();
this.consumeOnUse = consumeOnUse;
interface UsableState {
actions: RPGAction[];
consumeOnUse: boolean;
}
@component
export class Usable extends Component<UsableState> {
constructor(actions: RPGAction[], consumeOnUse = true) {
super({ actions, consumeOnUse });
}
@variable get consumeOnUse(): boolean { return this.state.consumeOnUse; }
@action
async use(arg?: EvalContext, ctx?: EvalContext): Promise<void> {
ctx = arg ?? ctx ?? this.context;
if (!ctx) return;
for (const action of this.actions) {
for (const action of this.state.actions) {
await executeAction(action, ctx);
}
}

View File

@ -1,4 +1,5 @@
import { Component, type EvalContext } from "../core/world";
import { component } from "../core/registry";
import { isQuest, type Quest, type QuestStage, type RPGVariables } from "../types";
import { evaluateCondition } from "../utils/conditions";
@ -14,29 +15,49 @@ export interface QuestEntry {
state: QuestRuntimeState;
}
export class QuestLog extends Component {
readonly #quests = new Map<string, QuestEntry>();
interface QuestLogState {
quests: Record<string, Quest>;
runtimeStates: Record<string, QuestRuntimeState>;
}
@component
export class QuestLog extends Component<QuestLogState> {
#cachedVars: RPGVariables | null = null;
constructor(quests: Quest[] = []) {
const questsRecord: Record<string, Quest> = {};
const runtimeStates: Record<string, QuestRuntimeState> = {};
for (const q of quests) {
questsRecord[q.id] = q;
runtimeStates[q.id] = { status: 'inactive', stageIndex: 0 };
}
super({ quests: questsRecord, runtimeStates });
}
addQuest(quest: Quest): void {
if (this.#quests.has(quest.id)) {
if (this.state.quests[quest.id]) {
console.warn(`[QuestLog] quest '${quest.id}' is already registered, ignoring duplicate`);
return;
}
this.#quests.set(quest.id, { quest, state: { status: 'inactive', stageIndex: 0 } });
this.state.quests[quest.id] = quest;
this.state.runtimeStates[quest.id] = { status: 'inactive', stageIndex: 0 };
}
#invalidate() { this.#cachedVars = null; }
#transition(op: string, questId: string, from: QuestStatus, to: QuestStatus, event: string): boolean {
const entry = this.#quests.get(questId);
if (!entry) {
const runtimeState = this.state.runtimeStates[questId];
if (!runtimeState) {
console.warn(`[QuestLog] ${op}: quest '${questId}' is not registered`);
return false;
}
if (entry.state.status !== from) {
console.warn(`[QuestLog] ${op}: quest '${questId}' cannot transition from status '${entry.state.status}'`);
if (runtimeState.status !== from) {
console.warn(`[QuestLog] ${op}: quest '${questId}' cannot transition from status '${runtimeState.status}'`);
return false;
}
entry.state.status = to;
if (to === 'active' || to === 'inactive') entry.state.stageIndex = 0;
runtimeState.status = to;
if (to === 'active' || to === 'inactive') runtimeState.stageIndex = 0;
this.#invalidate();
this.emit(event, { questId });
return true;
}
@ -58,21 +79,21 @@ export class QuestLog extends Component {
}
getState(questId: string): QuestRuntimeState | undefined {
return this.#quests.get(questId)?.state;
return this.state.runtimeStates[questId];
}
isAvailable(questId: string, ctx: EvalContext): boolean {
const entry = this.#quests.get(questId);
if (!entry) return false;
const { quest } = entry;
const quest = this.state.quests[questId];
if (!quest) return false;
if (!quest.conditions?.length) return true;
return quest.conditions.every(c => evaluateCondition(c, ctx));
}
getStage(questId: string): QuestStage | undefined {
const entry = this.#quests.get(questId);
if (!entry || entry.state.status !== 'active') return undefined;
return entry.quest.stages[entry.state.stageIndex];
const quest = this.state.quests[questId];
const runtimeState = this.state.runtimeStates[questId];
if (!quest || runtimeState?.status !== 'active') return undefined;
return quest.stages[runtimeState.stageIndex];
}
getObjectiveProgress(
@ -89,31 +110,33 @@ export class QuestLog extends Component {
}
/** @internal used by QuestSystem */
entries(): IterableIterator<[string, QuestEntry]> {
return this.#quests.entries();
*entries(): Generator<[string, QuestEntry], void, unknown> {
for (const [id, quest] of Object.entries(this.state.quests)) {
yield [id, { quest, state: this.state.runtimeStates[id]! }];
}
}
/** @internal called by QuestSystem after stage actions complete */
_advance(questId: string): void {
const entry = this.#quests.get(questId);
if (!entry) return;
const { quest, state } = entry;
if (state.stageIndex + 1 < quest.stages.length) {
state.stageIndex++;
this.emit('stage', { questId, index: state.stageIndex, stage: quest.stages[state.stageIndex] });
const quest = this.state.quests[questId];
const runtimeState = this.state.runtimeStates[questId];
if (!quest || !runtimeState) return;
this.#invalidate();
if (runtimeState.stageIndex + 1 < quest.stages.length) {
runtimeState.stageIndex++;
this.emit('stage', { questId, index: runtimeState.stageIndex, stage: quest.stages[runtimeState.stageIndex] });
} else {
state.status = 'completed';
runtimeState.status = 'completed';
this.emit('completed', { questId });
}
}
override getActions() {
const result = { ...super.getActions() };
for (const questId of this.#quests.keys()) {
const entry = this.#quests.get(questId)!;
if (entry.state.status === 'inactive') {
for (const [questId, runtimeState] of Object.entries(this.state.runtimeStates)) {
if (runtimeState.status === 'inactive') {
result[`${questId}.start`] = this.start.bind(this, questId);
} else if (entry.state.status === 'active') {
} else if (runtimeState.status === 'active') {
result[`${questId}.complete`] = this.complete.bind(this, questId);
result[`${questId}.fail`] = this.fail.bind(this, questId);
result[`${questId}.abandon`] = this.abandon.bind(this, questId);
@ -123,11 +146,13 @@ export class QuestLog extends Component {
}
override getVariables(): RPGVariables {
if (this.#cachedVars) return this.#cachedVars;
const result: RPGVariables = {};
for (const [questId, { state }] of this.#quests) {
result[`${questId}.status`] = state.status;
result[`${questId}.stage`] = state.stageIndex;
for (const [questId, runtimeState] of Object.entries(this.state.runtimeStates)) {
result[`${questId}.status`] = runtimeState.status;
result[`${questId}.stage`] = runtimeState.stageIndex;
}
this.#cachedVars = result;
return result;
}
}
@ -141,8 +166,9 @@ export namespace Quests {
for (const stage of quest.stages) {
for (const action of stage.actions) {
if (!actionSet.has(action.type)) {
errors.push(`stage '${stage.id}': unknown action type '${action.type}'`);
const type = typeof action === 'string' ? action : action.type;
if (!actionSet.has(type)) {
errors.push(`stage '${stage.id}': unknown action type '${type}'`);
}
}
}

View File

@ -1,43 +1,49 @@
import { action, variable } from "../utils/decorators";
import { Component } from "../core/world";
import { component } from "../core/registry";
export class Stat extends Component {
@variable('.') private value: number;
@variable private max: number | undefined;
@variable private min: number | undefined;
interface StatState {
value: number;
max: number | undefined;
min: number | undefined;
}
@component
export class Stat extends Component<StatState> {
constructor(value: number, max?: number, min?: number) {
super();
this.value = value;
this.max = max;
this.min = min;
super({ value, max, min });
}
@variable('.') get value(): number { return this.state.value; }
@variable get max(): number | undefined { return this.state.max; }
@variable get min(): number | undefined { return this.state.min; }
@action
update(amount: number) {
this.set(this.value + amount);
this.set(this.state.value + amount);
}
@action
set(value: number) {
const prev = this.value;
this.value = value;
if (this.min != null) {
this.value = Math.max(this.min, this.value);
const prev = this.state.value;
this.state.value = value;
if (this.state.min != null) {
this.state.value = Math.max(this.state.min, this.state.value);
}
if (this.max != null) {
this.value = Math.min(this.value, this.max);
if (this.state.max != null) {
this.state.value = Math.min(this.state.value, this.state.max);
}
if (prev !== this.value) {
this.emit('set', { prev, value: this.value });
if (prev !== this.state.value) {
this.emit('set', { prev, value: this.state.value });
}
}
get current(): number {
return this.value;
return this.state.value;
}
}
@component
export class Health extends Stat {
constructor(value: number, max?: number, min = 0) {
super(value, max, min);
@ -48,4 +54,4 @@ export class Health extends Stat {
this.set(0);
this.emit('killed');
}
}
}

View File

@ -1,43 +1,58 @@
import type { RPGVariables } from "../types";
import { action } from "../utils/decorators";
import { Component } from "../core/world";
import { component } from "../core/registry";
interface Var {
key: string;
value: RPGVariables[string];
}
export class Variables extends Component {
private readonly variables: RPGVariables = {};
interface VariablesState {
vars: RPGVariables;
}
/**
* Generic runtime key-value store set by dialog actions, quest scripts, and game events
* values whose keys are only known at runtime or come from data files.
*
* Prefer a typed `Component<TState>` when the shape is fixed at compile time
* (e.g. health, stats, slot definitions).
*/
@component
export class Variables extends Component<VariablesState> {
constructor() {
super({ vars: {} });
}
override getVariables() {
return this.variables;
return this.state.vars;
}
@action
set({ key, value }: Var) {
const prev = this.variables[key];
this.variables[key] = value;
const prev = this.state.vars[key];
this.state.vars[key] = value;
this.emit('set', { key, value, prev });
return this.variables;
return this.state.vars;
}
@action
unset(key: string) {
const prev = this.variables[key];
delete this.variables[key];
const prev = this.state.vars[key];
delete this.state.vars[key];
this.emit('unset', { key, prev });
return this.variables;
return this.state.vars;
}
@action
increment({ key, value }: Var) {
const currentValue = this.variables[key] ?? 0;
const currentValue = this.state.vars[key] ?? 0;
if (typeof currentValue === 'number' && typeof value === 'number') {
this.set({ key, value: currentValue + value });
} else {
console.warn(`[Variables] increment failed: ${key} is not a number`);
}
return this.variables;
return this.state.vars;
}
}

View File

@ -0,0 +1,100 @@
import type { Component } from './world';
type ComponentConstructor = abstract new (...args: any[]) => Component<any>;
type MigrationFn = (state: Record<string, unknown>) => Record<string, unknown>;
interface ComponentMeta {
ctor: ComponentConstructor;
version: number;
}
interface MigrationEntry {
toVersion: number;
fn: MigrationFn;
}
const registry = new Map<string, ComponentMeta>();
const reverseRegistry = new Map<ComponentConstructor, string>();
/** migrations[name][fromVersion] → { toVersion, fn } */
const migrations = new Map<string, Map<number, MigrationEntry>>();
function register(name: string, ctor: ComponentConstructor, version: number): void {
registry.set(name, { ctor, version });
reverseRegistry.set(ctor, name);
}
export function getComponentMeta(name: string): ComponentMeta | undefined {
return registry.get(name);
}
export function getComponentName(ctor: Function): string | undefined {
return reverseRegistry.get(ctor as ComponentConstructor);
}
/**
* Register a migration that upgrades component state from `fromVersion` to `toVersion`.
* Migrations are chained automatically: registering 01 and 12 handles saves at version 0.
*/
export function registerMigration(
name: string,
fromVersion: number,
toVersion: number,
fn: MigrationFn,
): void {
if (!migrations.has(name)) migrations.set(name, new Map());
migrations.get(name)!.set(fromVersion, { toVersion, fn });
}
/**
* Apply all registered migrations to bring `state` from `fromVersion` up to the current
* registered version. Returns the migrated state (may be the same object if no migrations ran).
*/
export function migrateState(
name: string,
state: Record<string, unknown>,
fromVersion: number,
): Record<string, unknown> {
const meta = registry.get(name);
if (!meta) return state;
const chain = migrations.get(name);
if (!chain) return state;
let current = fromVersion;
let s = state;
while (current < meta.version) {
const entry = chain.get(current);
if (!entry) throw new Error(
`[registry] No migration for '${name}' from version ${current} to ${meta.version}. ` +
`Register one with registerMigration('${name}', ${current}, ...).`
);
s = entry.fn(s);
current = entry.toVersion;
}
return s;
}
interface ComponentOptions {
name?: string;
version?: number;
}
type ComponentDecorator = (target: ComponentConstructor, ctx: ClassDecoratorContext) => void;
export function component(target: ComponentConstructor, ctx: ClassDecoratorContext): void;
export function component(name: string): ComponentDecorator;
export function component(options: ComponentOptions): ComponentDecorator;
export function component(
nameOrTargetOrOptions: string | ComponentConstructor | ComponentOptions,
ctx?: ClassDecoratorContext,
): void | ComponentDecorator {
if (typeof nameOrTargetOrOptions === 'string') {
const name = nameOrTargetOrOptions;
return (target: ComponentConstructor) => register(name, target, 0);
}
if (typeof nameOrTargetOrOptions === 'object') {
const { name, version = 0 } = nameOrTargetOrOptions;
return (target: ComponentConstructor, ctx: ClassDecoratorContext) =>
register(name ?? String(ctx.name), target, version);
}
// Used as bare @component
register(String(ctx!.name), nameOrTargetOrOptions, 0);
}

View File

@ -0,0 +1,127 @@
import { World, Entity, Component, COMPONENT_STATE, WORLD_ENTITY_COUNTER } from './world';
import { getComponentMeta, getComponentName, migrateState } from './registry';
/** Increment this when the WorldData/EntityData structure itself changes incompatibly. */
const SCHEMA_VERSION = 1;
interface ComponentData {
type: 'component';
name: string;
key: string;
version: number;
state: unknown;
}
interface EntityData {
type: 'entity';
id: string;
components: ComponentData[];
}
interface WorldData {
type: 'world';
schemaVersion: number;
globals: Record<string, string | number | boolean | undefined>;
entityCounter: number;
entities: EntityData[];
}
type AnyData = ComponentData | EntityData | WorldData;
function serializeComponent(component: Component<any>): ComponentData {
const name = getComponentName(component.constructor);
if (!name) {
throw new Error(
`Component '${component.constructor.name}' is not registered. ` +
`Add @component to the class declaration.`
);
}
const meta = getComponentMeta(name)!;
return { type: 'component', name, key: component.key, version: meta.version, state: component[COMPONENT_STATE]() };
}
function serializeEntity(entity: Entity): EntityData {
const components: ComponentData[] = [];
for (const [, component] of entity) {
components.push(serializeComponent(component));
}
return { type: 'entity', id: entity.id, components };
}
function serializeWorld(world: World): WorldData {
const entities: EntityData[] = [];
for (const entity of world) {
entities.push(serializeEntity(entity));
}
return {
type: 'world',
schemaVersion: SCHEMA_VERSION,
globals: { ...world.globals },
entityCounter: world[WORLD_ENTITY_COUNTER],
entities,
};
}
function deserializeComponent(data: ComponentData): Component<any> {
const meta = getComponentMeta(data.name);
if (!meta) {
throw new Error(`Unknown component '${data.name}'. Ensure it is imported so @component runs.`);
}
const savedVersion = data.version ?? 0;
const state = savedVersion < meta.version
? migrateState(data.name, data.state as Record<string, unknown>, savedVersion)
: data.state;
// Bypass constructor: create a bare instance and restore state directly.
// Safe because constructors must only call super(state) — all initialization
// logic goes in onAdd(), which entity.add() calls after this.
const instance = Object.create(meta.ctor.prototype) as Component<any>;
(instance as unknown as { state: unknown }).state = state;
return instance;
}
function deserializeEntity(data: EntityData, world: World): Entity {
const entity = world.createEntity(data.id);
for (const componentData of data.components) {
entity.add(componentData.key, deserializeComponent(componentData));
}
return entity;
}
function deserializeWorld(data: WorldData): World {
if (data.schemaVersion !== SCHEMA_VERSION) {
throw new Error(
`Unsupported save format: schema version ${data.schemaVersion}, ` +
`expected ${SCHEMA_VERSION}. The save file is incompatible with this version of the engine.`
);
}
const world = new World();
Object.assign(world.globals, data.globals);
world[WORLD_ENTITY_COUNTER] = data.entityCounter;
for (const entityData of data.entities) {
deserializeEntity(entityData, world);
}
return world;
}
export namespace Serialization {
export function serialize(x: World | Entity | Component<any>): string {
if (x instanceof World) return JSON.stringify(serializeWorld(x));
if (x instanceof Entity) return JSON.stringify(serializeEntity(x));
return JSON.stringify(serializeComponent(x));
}
export function deserialize(s: string): World | Entity | Component<any> {
const data = JSON.parse(s) as AnyData;
switch (data.type) {
case 'world': return deserializeWorld(data);
case 'entity': {
const world = new World();
return deserializeEntity(data, world);
}
case 'component': return deserializeComponent(data);
default: throw new Error(`Unknown serialized type: '${(data as AnyData).type}'`);
}
}
}

View File

@ -15,14 +15,28 @@ type EntityEventHandler = <T>(event: EntityEvent<T>) => void;
type WorldEventHandler = <T>(event: WorldEvent<T>) => void;
export interface EvalContext {
self: Entity;
self: Entity | World;
world: World;
}
export abstract class Component {
/** Symbol used by Serialization to read component state. */
export const COMPONENT_STATE = Symbol('rpg.component.state');
/** Symbol used by Serialization to access World's entity counter. */
export const WORLD_ENTITY_COUNTER = Symbol('rpg.world.entityCounter');
export abstract class Component<TState = Record<string, unknown>> {
entity!: Entity;
key!: string;
protected state: TState;
constructor(state: TState) {
this.state = state;
}
[COMPONENT_STATE](): TState { return this.state; }
protected emit(event: string, data?: unknown): void {
this.entity.emit(`${this.key}.${event}`, data);
}
@ -81,7 +95,7 @@ export class Entity {
return { self: this, world: this.world };
}
add<T extends Component>(key: string, component: T): T {
add<T extends Component<any>>(key: string, component: T): T {
const existing = this.#components.get(key);
if (existing) existing.onRemove();
component.entity = this;
@ -91,10 +105,10 @@ export class Entity {
return component;
}
get<T extends Component>(key: string): T | undefined;
get<T extends Component>(ctor: Class<T>): T | undefined;
get<T extends Component>(ctor: Class<T>, key: string): T | undefined;
get<T extends Component>(ctorOrKey: Class<T> | string, key?: string): T | undefined {
get<T extends Component<any>>(key: string): T | undefined;
get<T extends Component<any>>(ctor: Class<T>): T | undefined;
get<T extends Component<any>>(ctor: Class<T>, key: string): T | undefined;
get<T extends Component<any>>(ctorOrKey: Class<T> | string, key?: string): T | undefined {
if (typeof ctorOrKey === 'string') {
return this.#components.get(ctorOrKey) as T | undefined;
}
@ -109,9 +123,9 @@ export class Entity {
}
has(key: string): boolean;
has<T extends Component>(ctor: Class<T>): boolean;
has<T extends Component>(ctor: Class<T>, key: string): boolean;
has<T extends Component>(ctorOrKey: Class<T> | string, key?: string): boolean {
has<T extends Component<any>>(ctor: Class<T>): boolean;
has<T extends Component<any>>(ctor: Class<T>, key: string): boolean;
has<T extends Component<any>>(ctorOrKey: Class<T> | string, key?: string): boolean {
if (typeof ctorOrKey === 'string') return this.#components.has(ctorOrKey);
if (key !== undefined) return this.#components.get(key) instanceof ctorOrKey;
for (const c of this.#components.values()) {
@ -121,9 +135,9 @@ export class Entity {
}
remove(key: string): void;
remove<T extends Component>(ctor: Class<T>): void;
remove<T extends Component>(ctor: Class<T>, key: string): void;
remove<T extends Component>(ctorOrKey: Class<T> | string, key?: string): void {
remove<T extends Component<any>>(ctor: Class<T>): void;
remove<T extends Component<any>>(ctor: Class<T>, key: string): void;
remove<T extends Component<any>>(ctorOrKey: Class<T> | string, key?: string): void {
if (typeof ctorOrKey === 'string') {
this.#removeByKey(ctorOrKey);
return;
@ -166,12 +180,12 @@ export class Entity {
this.world.destroyEntity(this);
}
/** @internal used by World.query and resolveVariables */
/** @internal */
[Symbol.iterator](): IterableIterator<[string, Component]> {
return this.#components.entries();
}
/** @internal called by World.destroyEntity */
/** @internal */
_destroy(): void {
for (const c of this.#components.values()) c.onRemove();
this.#components.clear();
@ -185,11 +199,33 @@ export class World {
readonly #entities = new Map<string, Entity>();
readonly #handlers = new Map<string, Set<EntityEventHandler>>();
readonly #globalHandlers = new Map<string, Set<WorldEventHandler>>();
readonly #onceWrappers = new Map<Function, Function>();
readonly #systems: System[] = [];
#entityCounter = 0;
get [WORLD_ENTITY_COUNTER](): number { return this.#entityCounter; }
set [WORLD_ENTITY_COUNTER](n: number) { this.#entityCounter = n; }
get id() { return 'world'; }
get context(): EvalContext {
return { self: this, world: this };
}
/**
* Create a new entity and add it to the world.
*
* @param id - How the entity ID is determined:
* - Omitted auto-generated: `entity_1`, `entity_2`,
* - Plain string used as-is: `createEntity('player')` `'player'`
* - Template with `*` `*` is replaced by the auto-incremented counter:
* `createEntity('enemy_*')` `'enemy_1'`, `'enemy_2'`,
* @throws If an entity with the resolved ID already exists.
*/
createEntity(id?: string): Entity {
const entityId = id ?? `entity_${++this.#entityCounter}`;
const entityId = id == null
? `entity_${++this.#entityCounter}`
: id.includes('*') ? id.replace('*', String(++this.#entityCounter)) : id;
if (this.#entities.has(entityId)) throw new Error(`Entity '${entityId}' already exists`);
const entity = new Entity(entityId, this);
this.#entities.set(entityId, entity);
@ -208,13 +244,39 @@ export class World {
}
}
*query<T extends Component>(ctor: Class<T>): Generator<[Entity, string, T]> {
for (const entity of this.#entities.values()) {
for (const [key, component] of entity) {
if (component instanceof ctor) {
yield [entity, key, component as T]
/**
* Create a new entity whose components are deep copies of `source`'s components.
* The clone is immediately live in the world and `onAdd()` fires for each component.
* @param source - Entity to clone.
* @param newId - ID for the clone; follows the same rules as {@link createEntity}.
*/
cloneEntity(source: Entity, newId?: string): Entity {
const target = this.createEntity(newId);
for (const [key, component] of source) {
const clone = Object.create(component.constructor.prototype) as Component<any>;
(clone as unknown as { state: unknown }).state = structuredClone(component[COMPONENT_STATE]());
target.add(key, clone);
}
return target;
}
query<T extends Component<any>>(ctor: Class<T>): Generator<[Entity, string, T]>;
query<A extends Component<any>, B extends Component<any>>(ctorA: Class<A>, ctorB: Class<B>): Generator<[Entity, A, B]>;
query<A extends Component<any>, B extends Component<any>, C extends Component<any>>(ctorA: Class<A>, ctorB: Class<B>, ctorC: Class<C>): Generator<[Entity, A, B, C]>;
*query(...ctors: Class<Component<any>>[]): Generator<unknown[]> {
const entities = this.#entities;
if (ctors.length === 1) {
const ctor = ctors[0];
for (const entity of entities.values()) {
for (const [key, component] of entity) {
if (component instanceof ctor) yield [entity, key, component];
}
}
} else {
for (const entity of entities.values()) {
const components = ctors.map(ctor => entity.get(ctor));
if (components.every(c => c !== undefined)) yield [entity, ...components];
}
}
}
@ -238,11 +300,7 @@ export class World {
emit(entityId: string, event: string, data?: unknown): void {
const entity = this.getEntity(entityId);
if (!entity) return;
this.#handlers.get(`${entityId}\0${event}`)?.forEach(h => h({
target: entity,
data,
}));
this.#handlers.get(`${entityId}\0${event}`)?.forEach(h => h({ target: entity, data }));
}
emitGlobal(event: string, data?: unknown): void {
@ -262,9 +320,13 @@ export class World {
off(entityId: string, event: string, handler: EntityEventHandler): void;
off(arg1: string, arg2: WorldEventHandler | string, arg3?: EntityEventHandler): void {
if (typeof arg2 === 'string') {
this.#handlers.get(`${arg1}\0${arg2}`)?.delete(arg3!);
const handler = (this.#onceWrappers.get(arg3!) ?? arg3!) as EntityEventHandler;
this.#handlers.get(`${arg1}\0${arg2}`)?.delete(handler);
this.#onceWrappers.delete(arg3!);
} else {
this.#globalHandlers.get(arg1)?.delete(arg2);
const handler = (this.#onceWrappers.get(arg2) ?? arg2) as WorldEventHandler;
this.#globalHandlers.get(arg1)?.delete(handler);
this.#onceWrappers.delete(arg2);
}
}
@ -272,17 +334,24 @@ export class World {
once(entityId: string, event: string, handler: EntityEventHandler): () => void;
once(arg1: string, arg2: WorldEventHandler | string, arg3?: EntityEventHandler): () => void {
if (typeof arg2 === 'string') {
const wrapped: EntityEventHandler = data => { unsub(); arg3!(data); };
const original = arg3!;
const wrapped: EntityEventHandler = data => { this.#onceWrappers.delete(original); unsub(); original(data); };
this.#onceWrappers.set(original, wrapped);
const unsub = this.on(arg1, arg2, wrapped);
return unsub;
return () => { this.#onceWrappers.delete(original); unsub(); };
}
const h = arg2;
const wrapped: WorldEventHandler = data => { unsub(); h(data); };
const original = arg2;
const wrapped: WorldEventHandler = data => { this.#onceWrappers.delete(original); unsub(); original(data); };
this.#onceWrappers.set(original, wrapped);
const unsub = this.on(arg1, wrapped);
return unsub;
return () => { this.#onceWrappers.delete(original); unsub(); };
}
#addHandler<T extends WorldEventHandler | EntityEventHandler>(map: Map<string, Set<T>>, key: string, handler: T): () => void {
#addHandler<T extends WorldEventHandler | EntityEventHandler>(
map: Map<string, Set<T>>,
key: string,
handler: T,
): () => void {
if (!map.has(key)) map.set(key, new Set());
map.get(key)!.add(handler);
return () => map.get(key)?.delete(handler);
@ -295,6 +364,14 @@ export class World {
export function isEvalContext(v: unknown): v is EvalContext {
return typeof v === 'object' && v != null
&& (v as EvalContext).self instanceof Entity
&& (
(v as EvalContext).self instanceof Entity
|| (v as EvalContext).self instanceof World
)
&& (v as EvalContext).world instanceof World;
}
/** Narrows an {@link EvalContext} to one where `self` is an `Entity`, not a `World`. */
export function isEntityContext(ctx: EvalContext): ctx is { self: Entity; world: World } {
return ctx.self instanceof Entity;
}

View File

@ -46,7 +46,7 @@ export namespace Dialogs {
const actions = new Set<string>();
for (const node of dialog.nodes) {
for (const action of node.actions ?? []) {
actions.add(action.type);
actions.add(typeof action === 'string' ? action : action.type);
}
}
return Array.from(actions);
@ -76,8 +76,9 @@ export namespace Dialogs {
errors.push(`node '${node.id}': nextNodeId '${node.nextNodeId}' does not match any node id`);
for (const action of node.actions ?? []) {
if (!actionSet.has(action.type)) {
errors.push(`node '${node.id}': unknown action type '${action.type}'`);
const type = typeof action === 'string' ? action : action.type;
if (!actionSet.has(type)) {
errors.push(`node '${node.id}': unknown action type '${type}'`);
}
}
@ -238,7 +239,9 @@ export class DialogEngine {
if (isEvalContext(this.options)) {
await executeAction(action, this.options);
} else {
await this.options.actions[action.type]?.(action.arg);
const type = typeof action === 'string' ? action: action.type;
const arg = typeof action === 'string' ? undefined : action.arg;
await this.options.actions[type]?.(arg);
}
}

View File

@ -3,10 +3,13 @@ import type { EvalContext } from './core/world';
// ── Shared ────────────────────────────────────────────────────────────────────
const RPGActionScheme = Type.Object({
type: Type.String(),
arg: Type.Optional(Type.Any()),
});
const RPGActionScheme = Type.Union([
Type.Object({
type: Type.String(),
arg: Type.Optional(Type.Any()),
}),
Type.String(),
]);
export type RPGCondition = string;
export type RPGVariables = Record<string, string | number | boolean | undefined>;

View File

@ -12,33 +12,47 @@ export interface ParsedCondition {
value?: ConditionValue;
}
const parseCache = new Map<string, ParsedCondition>();
export function parseCondition(s: RPGCondition): ParsedCondition {
const cached = parseCache.get(s);
if (cached) return cached;
let result: ParsedCondition;
// ~variable — falsy check, nothing else allowed
if (s.startsWith('~') && !s.includes(' '))
return { variable: s.slice(1), negate: true };
if (s.startsWith('~') && !s.includes(' ')) {
result = { variable: s.slice(1), negate: true };
} else {
const spaceIdx = s.indexOf(' ');
if (spaceIdx === -1) {
result = { variable: s, negate: false };
} else {
const variable = s.slice(0, spaceIdx);
const rest = s.slice(spaceIdx + 1).trim();
const spaceIdx = s.indexOf(' ');
if (spaceIdx === -1)
return { variable: s, negate: false };
if (rest === 'null') {
result = { variable, negate: false, operator: 'null' };
} else if (rest === '~null') {
result = { variable, negate: false, operator: '~null' };
} else {
const opMatch = rest.match(/^(==|!=|>=|<=|>|<)\s*(.+)$/);
if (!opMatch) throw new Error(`Invalid condition: "${s}"`);
const variable = s.slice(0, spaceIdx);
const rest = s.slice(spaceIdx + 1).trim();
const [, operator, rawValue] = opMatch;
let value: ConditionValue;
if (rawValue === 'null') value = null;
else if (rawValue === 'true') value = true;
else if (rawValue === 'false') value = false;
else if (!isNaN(Number(rawValue))) value = Number(rawValue);
else value = rawValue.replace(/^['"]|['"]$/g, '');
if (rest === 'null') return { variable, negate: false, operator: 'null' };
if (rest === '~null') return { variable, negate: false, operator: '~null' };
result = { variable, negate: false, operator: operator as ConditionOperator, value };
}
}
}
const opMatch = rest.match(/^(==|!=|>=|<=|>|<)\s*(.+)$/);
if (!opMatch) throw new Error(`Invalid condition: "${s}"`);
const [, operator, rawValue] = opMatch;
let value: ConditionValue;
if (rawValue === 'null') value = null;
else if (rawValue === 'true') value = true;
else if (rawValue === 'false') value = false;
else if (!isNaN(Number(rawValue))) value = Number(rawValue);
else value = rawValue.replace(/^['"]|['"]$/g, '');
return { variable, negate: false, operator: operator as ConditionOperator, value };
parseCache.set(s, result);
return result;
}
function evalParsed({ negate, operator, value }: ParsedCondition, val: RPGVariables[string]): boolean {

View File

@ -1,19 +1,17 @@
import type { RPGAction, RPGActions, RPGVariables } from "../types";
import { World } from "../core/world";
import { isEvalContext, World } from "../core/world";
import type { EvalContext, Entity } from "../core/world";
export function resolveVariables(entity: Entity): RPGVariables;
export function resolveVariables(world: World): RPGVariables;
export function resolveVariables(entityOrWorld: Entity | World): RPGVariables {
export function resolveVariables(target: Entity | World): RPGVariables {
const result: RPGVariables = {};
if (entityOrWorld instanceof World) {
for (const entity of entityOrWorld) {
if (target instanceof World) {
for (const entity of target) {
for (const [key, value] of Object.entries(resolveVariables(entity))) {
result[`${entity.id}.${key}`] = value;
}
}
} else {
for (const [key, component] of entityOrWorld) {
for (const [key, component] of target) {
for (const [varKey, value] of Object.entries(component.getVariables())) {
if (value != null) {
if (varKey && varKey !== '.') {
@ -49,18 +47,16 @@ export function resolveVariable(name: string, ctx: EvalContext): RPGVariables[st
// bare name → self entity
return resolveVariables(ctx.self)[name];
}
export function resolveActions(entity: Entity): RPGActions;
export function resolveActions(world: World): RPGActions;
export function resolveActions(entityOrWorld: Entity | World): RPGActions {
export function resolveActions(target: Entity | World): RPGActions {
const result: RPGActions = {};
if (entityOrWorld instanceof World) {
for (const entity of entityOrWorld) {
if (target instanceof World) {
for (const entity of target) {
for (const [key, value] of Object.entries(resolveActions(entity))) {
result[`${entity.id}.${key}`] = value;
}
}
} else {
for (const [key, component] of entityOrWorld) {
for (const [key, component] of target) {
for (const [actionKey, fn] of Object.entries(component.getActions())) {
result[`${key}.${actionKey}`] = fn;
}
@ -69,7 +65,20 @@ export function resolveActions(entityOrWorld: Entity | World): RPGActions {
return result;
}
export async function executeAction(action: RPGAction, ctx: EvalContext): Promise<unknown> {
interface Contextable {
readonly context: EvalContext;
}
export async function executeAction(action: RPGAction, ctx: EvalContext | Contextable): Promise<unknown> {
if (typeof action === 'string') {
action = { type: action };
}
if ('context' in ctx) {
ctx = ctx.context;
}
if (!action.type) {
throw new TypeError(`[executeAction] action object is missing a 'type' property`);
}
let entity = ctx.self;
let actionType = action.type;
@ -77,12 +86,12 @@ export async function executeAction(action: RPGAction, ctx: EvalContext): Promis
if (action.type.startsWith('@')) {
const dotIdx = action.type.indexOf('.', 1);
if (dotIdx === -1) {
console.warn(`[executeAction] malformed cross-entity action '${action.type}': missing '.' after entity id`);
return;
throw new Error(`[executeAction] malformed cross-entity action '${action.type}': missing '.' after entity id`);
}
const entityId = action.type.slice(1, dotIdx);
const found = ctx.world.getEntity(entityId);
if (!found) {
// Entity may have been destroyed legitimately — warn and skip rather than throw.
console.warn(`[executeAction] entity '${entityId}' not found (action '${action.type}')`);
return;
}
@ -92,8 +101,7 @@ export async function executeAction(action: RPGAction, ctx: EvalContext): Promis
const actions = resolveActions(entity);
if (!(actionType in actions)) {
console.warn(`[executeAction] action '${actionType}' not found on entity '${entity.id}'`);
return;
throw new Error(`[executeAction] action '${actionType}' not found on entity '${entity instanceof World ? 'world' : entity.id}'`);
}
return actions[actionType](action.arg, ctx);
}

View File

@ -6,6 +6,7 @@ import { QuestLog } from "@common/rpg/components/questLog";
import { QuestSystem } from "@common/rpg/systems/questSystem";
import { Items } from "@common/rpg/components/item";
import { resolveVariables, resolveActions, executeAction } from "@common/rpg/utils/variables";
import { Serialization } from "@common/rpg/core/serialization";
export default async function main() {
const world = new World();
@ -18,15 +19,12 @@ export default async function main() {
player.add('inventory', new Inventory(['head', 'legs']));
player.add('health', new Health(100, 100));
player.add('vars', new Variables());
player.add('quests', new QuestLog());
const quests = player.get(QuestLog)!;
quests.addQuest({
player.add('quests', new QuestLog([{
id: 'test',
description: 'Test quest',
title: 'Test',
stages: [],
});
}]));
console.log(resolveVariables(world));
@ -36,8 +34,10 @@ export default async function main() {
const vars = player.get(Variables)!;
vars.set({ key: 'test', value: 'test' });
await executeAction({ type: 'inventory.add', arg: { itemId: 'boots', amount: 2 } }, player.context);
await executeAction({ type: 'inventory.add', arg: { itemId: 'boots', amount: 2 } }, player);
await executeAction('player.quests.test.start', world);
console.log(resolveActions(world));
console.log(resolveVariables(world));
console.log(Serialization.serialize(world));
}