import { normalizedUnionType } from "../types/type-ops.js";
export const getCurrentTypeForDecl = (declId, ctx) => ctx.typeEnv?.get(declId.id) ?? ctx.typeSystem.typeOfValueRead(declId);
export const getReadableMemberTypeForNarrowing = (type, propertyName, ctx) => {
    if (type.kind === "objectType") {
        const member = type.members.find((candidate) => candidate.kind === "propertySignature" &&
            candidate.name === propertyName);
        return member?.kind === "propertySignature" ? member.type : undefined;
    }
    if (type.kind === "referenceType" &&
        type.structuralMembers &&
        type.structuralMembers.length > 0) {
        const member = type.structuralMembers.find((candidate) => candidate.kind === "propertySignature" &&
            candidate.name === propertyName);
        return member?.kind === "propertySignature" ? member.type : undefined;
    }
    const memberType = ctx.typeSystem.typeOfMember(type, {
        kind: "byName",
        name: propertyName,
    });
    return memberType.kind === "unknownType" ? undefined : memberType;
};
const collectPropertyNarrowingCandidates = (currentType, ctx) => {
    const expanded = ctx.typeSystem.collectNarrowingCandidates(currentType);
    return expanded.length > 0 ? expanded : [currentType];
};
export const narrowTypeByPropertyPresence = (currentType, propertyName, wantPresent, ctx) => {
    const kept = collectPropertyNarrowingCandidates(currentType, ctx).filter((member) => {
        const hasMember = member !== undefined &&
            getReadableMemberTypeForNarrowing(member, propertyName, ctx) !==
                undefined;
        return hasMember === wantPresent;
    });
    if (kept.length === 0)
        return undefined;
    if (kept.length === 1)
        return kept[0];
    return normalizedUnionType(kept);
};
export const narrowTypeByPropertyTruthiness = (currentType, propertyName, wantTruthy, ctx) => {
    const kept = collectPropertyNarrowingCandidates(currentType, ctx).filter((member) => {
        if (!member)
            return false;
        const memberType = getReadableMemberTypeForNarrowing(member, propertyName, ctx);
        if (!memberType || memberType.kind !== "literalType") {
            return false;
        }
        return wantTruthy
            ? memberType.value === true
            : memberType.value === false;
    });
    if (kept.length === 0)
        return undefined;
    if (kept.length === 1)
        return kept[0];
    return normalizedUnionType(kept);
};
//# sourceMappingURL=narrowing-property-helpers.js.map