/**
 * SyncBridge — wraps a mog SDK object's internal compute bridge to
 * expose Yrs CRDT sync primitives as binary (Uint8Array) operations.
 *
 * This is the ONLY file that touches mog SDK internals for CRDT sync.
 * If the mog team later exposes a public network sync API, swap this file.
 *
 * Internal access paths (both lead to the same ComputeBridge):
 *   HeadlessEngine → .lifecycle.computeBridge
 *   Workbook (WorkbookImpl) → .ctx.computeBridge
 */
// ── Native addon loader ────────────────────────────────────────────────
import { createRequire } from 'node:module';
const PLATFORM_PACKAGES = {
    darwin: { arm64: '@mog-sdk/darwin-arm64', x64: '@mog-sdk/darwin-x64' },
    linux: { x64: '@mog-sdk/linux-x64-gnu', arm64: '@mog-sdk/linux-arm64-gnu' },
    win32: { x64: '@mog-sdk/win32-x64-msvc' }
};
let _cachedAddon;
/**
 * Load the platform-native compute addon.
 * Same resolution as @mog-sdk/node's internal tryLoadNapiAddon.
 *
 * Uses createRequire anchored to @mog-sdk/node's package location so
 * pnpm's symlinked node_modules resolves the platform package correctly.
 */
function loadNativeAddon() {
    if (_cachedAddon)
        return _cachedAddon;
    // Resolve the SDK's main entry, then create require from its directory.
    // This ensures pnpm's symlinked deps (@mog-sdk/darwin-arm64 etc.) are findable.
    const req = createRequire(import.meta.url);
    const sdkEntry = req.resolve('@mog-sdk/node');
    const sdkReq = createRequire(sdkEntry);
    const pkg = PLATFORM_PACKAGES[process.platform]?.[process.arch];
    if (!pkg)
        throw new Error(`Unsupported platform: ${process.platform}/${process.arch}`);
    _cachedAddon = sdkReq(pkg);
    return _cachedAddon;
}
/**
 * Try to extract the compute bridge from various mog SDK object types.
 * Returns null if the object doesn't expose a compute bridge.
 */
function extractComputeBridge(obj) {
    // Path 1: HeadlessEngine → .lifecycle.computeBridge
    const fromEngine = obj?.lifecycle?.computeBridge;
    if (fromEngine && typeof fromEngine.syncStateVector === 'function') {
        return fromEngine;
    }
    // Path 2: Workbook (WorkbookImpl) → .ctx.computeBridge
    const fromWorkbook = obj?.ctx?.computeBridge;
    if (fromWorkbook && typeof fromWorkbook.syncStateVector === 'function') {
        return fromWorkbook;
    }
    return null;
}
// ── SyncBridge ─────────────────────────────────────────────────────────
export class SyncBridge {
    bridge;
    /**
     * @param engineOrWorkbook - A mog HeadlessEngine or Workbook instance.
     *   At runtime, both expose a compute bridge via internal properties.
     */
    constructor(engineOrWorkbook) {
        const bridge = extractComputeBridge(engineOrWorkbook);
        if (!bridge) {
            throw new Error('SyncBridge: object does not expose a compute bridge with sync methods');
        }
        this.bridge = bridge;
    }
    /** Full Yrs document state as binary — used for initial sync to server. */
    async getFullState() {
        const nums = await this.bridge.core.syncFullState();
        return new Uint8Array(nums);
    }
    /** Local Yrs state vector — used in state-vector exchange protocol. */
    async getStateVector() {
        const nums = await this.bridge.syncStateVector();
        return new Uint8Array(nums);
    }
    /** Compute diff that would bring a remote (with given state vector) up to date. */
    async computeDiff(remoteSv) {
        const nums = await this.bridge.syncDiff(Array.from(remoteSv));
        return new Uint8Array(nums);
    }
    /** Apply a remote Yrs update to the local engine. */
    async applyUpdate(update) {
        await this.bridge.syncApply(Array.from(update));
    }
    // ── Static helpers ───────────────────────────────────────────────────
    /**
     * Convert raw Yrs state bytes into a WorkbookSnapshot JSON string.
     * Uses the NAPI addon's `yrs_state_to_snapshot_json` function.
     */
    static snapshotFromState(state) {
        const addon = loadNativeAddon();
        const fn = addon.yrs_state_to_snapshot_json;
        if (typeof fn !== 'function') {
            throw new Error('SyncBridge: yrs_state_to_snapshot_json not found on NAPI addon');
        }
        return fn(Buffer.from(state));
    }
    /** Return the native compute addon (for createHeadlessEngine's computeAddon param). */
    static getNativeAddon() {
        return loadNativeAddon();
    }
}
//# sourceMappingURL=sync-bridge.js.map