import { ValidationError } from "../core/index.js";
import {} from "./Component.js";
import {} from "./Entity.js";
import { World } from "./World.js";
export function serializeWorld(world) {
    const entities = world.entities.entities().map((entity) => {
        const components = {};
        for (const type of world.registry.list()) {
            const value = world.components.get(entity, type.ctor);
            if (value)
                components[type.name] = type.schema.serialize ? type.schema.serialize(value) : structuredClone(value);
        }
        return { id: entity.id, generation: entity.generation, components };
    });
    return { version: 1, entities };
}
export function deserializeWorld(serialized, componentTypes) {
    if (serialized.version !== 1)
        throw new ValidationError("ECS_VERSION", `Unsupported ECS version: ${serialized.version}`);
    const world = new World();
    for (const type of componentTypes)
        world.registerComponent(type);
    const remap = new Map();
    for (const serializedEntity of serialized.entities) {
        const entity = world.createEntity();
        remap.set(`${serializedEntity.id}:${serializedEntity.generation}`, entity);
        for (const [name, data] of Object.entries(serializedEntity.components)) {
            const type = world.registry.getByName(name);
            if (!type)
                throw new ValidationError("ECS_DESERIALIZE_COMPONENT", `Missing component type during ECS deserialize: ${name}`);
            const component = type.schema.deserialize ? type.schema.deserialize(data) : data;
            world.add(entity, type.ctor, component);
        }
    }
    return { world, remap };
}
//# sourceMappingURL=ECSSerializer.js.map