import WarpError from "./errors/WarpError.js";
export default class WarpWorldlineCoordinate {
    kind = 'worldline-coordinate';
    worldlineName;
    checkpointSha;
    frontierEntries;
    _createWorldline;
    constructor(options) {
        assertFrontier(options.frontier);
        assertWorldlineFactory(options.createWorldline);
        assertNonEmpty(options.worldlineName, 'worldlineName');
        assertNonEmpty(options.checkpointSha, 'checkpointSha');
        this.worldlineName = options.worldlineName;
        this.checkpointSha = options.checkpointSha;
        this.frontierEntries = freezeFrontier(options.frontier);
        this._createWorldline = options.createWorldline;
        Object.freeze(this);
    }
    frontier() {
        return new Map(this.frontierEntries.map((entry) => [entry.writerId, entry.patchSha]));
    }
    source() {
        return {
            kind: 'coordinate',
            frontier: this.frontier(),
            checkpointSha: this.checkpointSha,
        };
    }
    optic() {
        return this._createWorldline({ source: this.source() }).optic();
    }
}
function freezeFrontier(frontier) {
    return Object.freeze([...frontier.entries()]
        .sort(([left], [right]) => left.localeCompare(right))
        .map(([writerId, patchSha]) => {
        assertNonEmpty(writerId, 'writerId');
        assertNonEmpty(patchSha, 'patchSha');
        return Object.freeze({ writerId, patchSha });
    }));
}
function assertFrontier(frontier) {
    if (!(frontier instanceof Map)) {
        throw new WarpError('WarpWorldline coordinate requires a frontier Map', 'E_WARP_WORLDLINE_COORDINATE', { context: { field: 'frontier' } });
    }
}
function assertWorldlineFactory(createWorldline) {
    if (typeof createWorldline !== 'function') {
        throw new WarpError('WarpWorldline coordinate requires a worldline factory', 'E_WARP_WORLDLINE_COORDINATE', { context: { field: 'createWorldline' } });
    }
}
function assertNonEmpty(value, field) {
    if (typeof value !== 'string' || value.trim().length === 0) {
        throw new WarpError('WarpWorldline coordinate requires non-empty identity fields', 'E_WARP_WORLDLINE_COORDINATE', { context: { field } });
    }
}
