import { isJsonObject, jsonClone } from './hub/types/json.js';
import { cloneRuntimeMetadataWithNative, ensureRuntimeMetadataCarrierWithNative, readRuntimeMetadataWithNative } from '../router/virtual-router/engine-selection/native-shared-conversion-semantics.js';
export function readRuntimeMetadata(carrier) {
    if (!carrier || typeof carrier !== 'object') {
        return undefined;
    }
    const candidate = readRuntimeMetadataWithNative(carrier);
    return candidate && isJsonObject(candidate) ? candidate : undefined;
}
export function ensureRuntimeMetadata(carrier) {
    if (!carrier || typeof carrier !== 'object') {
        throw new Error('ensureRuntimeMetadata requires object carrier');
    }
    const nextCarrier = ensureRuntimeMetadataCarrierWithNative(carrier);
    for (const key of Object.keys(carrier)) {
        if (!Object.prototype.hasOwnProperty.call(nextCarrier, key)) {
            delete carrier[key];
        }
    }
    Object.assign(carrier, nextCarrier);
    const existing = carrier.__rt;
    if (existing && isJsonObject(existing)) {
        return existing;
    }
    carrier.__rt = {};
    return carrier.__rt;
}
export function cloneRuntimeMetadata(carrier) {
    const rt = cloneRuntimeMetadataWithNative(carrier);
    return rt && isJsonObject(rt) ? jsonClone(rt) : undefined;
}
