var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __using = (stack, value, async) => {
  if (value != null) {
    if (typeof value !== "object" && typeof value !== "function") __typeError("Object expected");
    var dispose, inner;
    if (async) dispose = value[__knownSymbol("asyncDispose")];
    if (dispose === void 0) {
      dispose = value[__knownSymbol("dispose")];
      if (async) inner = dispose;
    }
    if (typeof dispose !== "function") __typeError("Object not disposable");
    if (inner) dispose = function() {
      try {
        inner.call(this);
      } catch (e) {
        return Promise.reject(e);
      }
    };
    stack.push([async, dispose, value]);
  } else if (async) {
    stack.push([async]);
  }
  return value;
};
var __callDispose = (stack, error, hasError) => {
  var E = typeof SuppressedError === "function" ? SuppressedError : function(e, s, m, _) {
    return _ = Error(m), _.name = "SuppressedError", _.error = e, _.suppressed = s, _;
  };
  var fail = (e) => error = hasError ? new E(e, error, "An error was suppressed during disposal") : (hasError = true, e);
  var next = (it) => {
    while (it = stack.pop()) {
      try {
        var result = it[1] && it[1].call(it[2]);
        if (it[0]) return Promise.resolve(result).then(next, (e) => (fail(e), next()));
      } catch (e) {
        fail(e);
      }
    }
    if (hasError) throw error;
  };
  return next();
};
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import {
  AsyncCache,
  describeList,
  Diagnostic,
  DnsMessageType,
  DnsMessageTypeFlag,
  DnsRecordType,
  Instant,
  isDeepEqual,
  Lifetime,
  Logger,
  MatterAggregateError,
  Millis,
  Minutes,
  ObserverGroup,
  Time
} from "@matter/general";
const logger = Logger.get("MdnsServer");
const RESPONDER_NAMES_OWNER = "mdns-responder";
const QUESTION_SUPPRESSION_WINDOW = Millis(999);
class MdnsServer {
  #lifetime;
  #observers = new ObserverGroup();
  #recordsGenerator = /* @__PURE__ */ new Map();
  #records = new AsyncCache(
    "MDNS discovery",
    async (multicastInterface) => {
      const byService = /* @__PURE__ */ new Map();
      const ownedNames = /* @__PURE__ */ new Set();
      const addrs = await this.network.getIpMac(multicastInterface);
      if (addrs === void 0) {
        return { byService, ownedNames };
      }
      for (const [service, generator] of this.#recordsGenerator) {
        const records = generator(multicastInterface, addrs);
        byService.set(service, records);
        for (const record of records) {
          ownedNames.add(record.name.toLowerCase());
        }
      }
      this.#registerResponderNames(ownedNames);
      return { byService, ownedNames };
    },
    Minutes(15)
  );
  // Union of advertised names across interfaces, fed to the socket so it keeps queries for our records (notably
  // bare-hostname A/AAAA queries, which carry no service-type label) before decoding.  Reset when records change.
  #responderNames = /* @__PURE__ */ new Set();
  #recordLastSentAsMulticastAnswer = /* @__PURE__ */ new Map();
  #truncatedQueryCache = /* @__PURE__ */ new Map();
  /** RFC 6762 §7.3 - Tracks recently answered queries for duplicate suppression */
  #recentlyAnsweredQueries = /* @__PURE__ */ new Map();
  #socket;
  constructor(socket, lifetime = Lifetime.process) {
    this.#socket = socket;
    this.#lifetime = lifetime.join("mdns server");
    this.#observers.on(this.#socket.receipt, this.#handleMessage.bind(this));
  }
  get network() {
    return this.#socket.network;
  }
  get supportsIpv4() {
    return this.#socket.supportsIpv4;
  }
  buildDnsRecordKey(record, netInterface, unicastTarget) {
    return `${record.name.toLowerCase()}-${record.recordClass}-${record.recordType}-${netInterface}-${unicastTarget}`;
  }
  async #handleMessage(incomingMessage) {
    var _stack = [];
    try {
      const _processing = __using(_stack, this.#lifetime.join("processing message"));
      const { byService, ownedNames } = await this.#records.get(incomingMessage.sourceIntf);
      if (byService.size === 0) {
        return;
      }
      const message = this.#prepareMessage(incomingMessage);
      if (message === void 0) {
        return;
      }
      const { sourceIntf, sourceIp, transactionId, queries, answers: knownAnswers } = message;
      if (!queries.some((q) => ownedNames.has(q.name.toLowerCase()))) {
        return;
      }
      let sentPreviousPacket = false;
      for (const portRecords of byService.values()) {
        let answers = queries.flatMap((query) => this.#queryRecords(query, portRecords));
        if (answers.length === 0) continue;
        let additionalRecords = queries.find(
          (query) => query.recordType !== DnsRecordType.A && query.recordType !== DnsRecordType.AAAA
        ) !== void 0 ? portRecords.filter((record) => !answers.includes(record) && record.recordType !== DnsRecordType.PTR) : [];
        if (knownAnswers.length > 0) {
          for (const knownAnswersRecord of knownAnswers) {
            answers = answers.filter((record) => !this.#suppressedByKnownAnswer(record, knownAnswersRecord));
            if (answers.length === 0) break;
          }
          if (answers.length === 0) continue;
          if (additionalRecords.length > 0) {
            for (const knownAnswersRecord of knownAnswers) {
              additionalRecords = additionalRecords.filter(
                (record) => !this.#suppressedByKnownAnswer(record, knownAnswersRecord)
              );
            }
          }
        }
        const now = Time.nowMs;
        let uniCastResponse = queries.filter((query) => !query.uniCastResponse).length === 0;
        const answersTimeSinceLastSent = answers.map((answer) => ({
          timeSinceLastMultiCast: Millis(
            now - (this.#recordLastSentAsMulticastAnswer.get(this.buildDnsRecordKey(answer, sourceIntf)) ?? 0)
          ),
          ttl: answer.ttl
        }));
        if (uniCastResponse && answersTimeSinceLastSent.some(({ timeSinceLastMultiCast, ttl }) => timeSinceLastMultiCast > ttl / 4)) {
          uniCastResponse = false;
        }
        if (!uniCastResponse) {
          answers = answers.filter(
            // The last time sent as multicast was more than 900 ms ago
            (_2, index) => answersTimeSinceLastSent[index].timeSinceLastMultiCast >= Millis(900)
          );
          if (answers.length === 0) continue;
          if (this.#shouldSuppressResponse(queries, knownAnswers, sourceIntf, answers)) {
            continue;
          }
          answers.forEach(
            (answer) => this.#recordLastSentAsMulticastAnswer.set(this.buildDnsRecordKey(answer, sourceIntf), now)
          );
        }
        if (sentPreviousPacket) {
          await Time.sleep("MDNS delay", Millis(20 + Math.floor(Math.random() * 100)));
        }
        this.#socket.send(
          {
            messageType: DnsMessageType.Response,
            transactionId,
            answers,
            additionalRecords
          },
          sourceIntf,
          uniCastResponse ? sourceIp : void 0
        ).catch((error) => {
          logger.warn(`Failed to send mDNS response to ${sourceIp}`, error);
        });
        sentPreviousPacket = true;
      }
    } catch (_) {
      var _error = _, _hasError = true;
    } finally {
      __callDispose(_stack, _error, _hasError);
    }
  }
  async #announceRecordsForInterface(netInterface, records) {
    await this.#socket.send(
      {
        messageType: DnsMessageType.Response,
        answers: records
      },
      netInterface
    );
  }
  async broadcast(...services) {
    var _stack = [];
    try {
      const _broadcasting = __using(_stack, this.#lifetime.join("broadcasting", Diagnostic.strong(describeList("and", ...services))));
      await MatterAggregateError.allSettled(
        (await this.#getMulticastInterfacesForAnnounce()).map(async ({ name: netInterface }) => {
          const { byService } = await this.#records.get(netInterface);
          let sentPreviousPacket = false;
          for (const [service, serviceRecords] of byService) {
            if (services.length && !services.includes(service)) continue;
            if (sentPreviousPacket) {
              await Time.sleep("MDNS delay", Millis(20 + Math.floor(Math.random() * 100)));
            }
            await this.#announceRecordsForInterface(netInterface, serviceRecords);
            sentPreviousPacket = true;
          }
        }),
        "Error announcing MDNS messages"
      ).catch((error) => logger.error("Error announcing MDNS messages", error));
    } catch (_) {
      var _error = _, _hasError = true;
    } finally {
      __callDispose(_stack, _error, _hasError);
    }
  }
  async expireAnnouncements(...services) {
    var _stack = [];
    try {
      const _expiring = __using(_stack, this.#lifetime.join("expiring", Diagnostic.strong(describeList("and", ...services))));
      await MatterAggregateError.allSettled(
        this.#records.keys().map(async (netInterface) => {
          const { byService } = await this.#records.get(netInterface);
          let sentPreviousPacket = false;
          for (const [service, serviceRecords] of byService) {
            if (services.length && !services.includes(service)) continue;
            serviceRecords.forEach((record) => {
              record.ttl = Instant;
            });
            if (sentPreviousPacket) {
              await Time.sleep("MDNS delay", Millis(20 + Math.floor(Math.random() * 100)));
            }
            await this.#announceRecordsForInterface(netInterface, serviceRecords);
            this.#recordsGenerator.delete(service);
            sentPreviousPacket = true;
          }
        }),
        "Error happened when expiring MDNS announcements"
      ).catch((error) => logger.warn("Error happened when expiring MDNS announcements", error));
      await this.#resetServices();
    } catch (_) {
      var _error = _, _hasError = true;
    } finally {
      __callDispose(_stack, _error, _hasError);
    }
  }
  async setRecordsGenerator(service, generator) {
    this.#recordsGenerator.set(service, generator);
    await this.#resetServices();
  }
  async #resetServices() {
    await this.#records.clear();
    this.#recordLastSentAsMulticastAnswer.clear();
    this.#recentlyAnsweredQueries.clear();
    this.#responderNames.clear();
  }
  // Accumulate the union of advertised names across interfaces; re-register only when it grows.  Stale entries from a
  // vanished interface are at worst extra keeps and are cleared on the next #resetServices.
  #registerResponderNames(ownedNames) {
    let changed = false;
    for (const name of ownedNames) {
      if (!this.#responderNames.has(name)) {
        this.#responderNames.add(name);
        changed = true;
      }
    }
    if (changed) {
      this.#socket.registerRelevantNames(RESPONDER_NAMES_OWNER, this.#responderNames);
    }
  }
  async close() {
    var _stack = [];
    try {
      const _closing = __using(_stack, this.#lifetime.closing());
      this.#observers.close();
      this.#socket.unregisterRelevantNames(RESPONDER_NAMES_OWNER);
      await this.#records.close();
      for (const { timer } of this.#truncatedQueryCache.values()) {
        timer.stop();
      }
      this.#truncatedQueryCache.clear();
      this.#recordLastSentAsMulticastAnswer.clear();
      this.#recentlyAnsweredQueries.clear();
    } catch (_) {
      var _error = _, _hasError = true;
    } finally {
      __callDispose(_stack, _error, _hasError);
    }
  }
  #getMulticastInterfacesForAnnounce() {
    const { netInterface } = this.#socket;
    return netInterface === void 0 ? this.network.getNetInterfaces() : [{ name: netInterface }];
  }
  #suppressedByKnownAnswer(record, knownAnswer) {
    const lcName = knownAnswer.name.toLowerCase();
    if (record.name.toLowerCase() !== lcName) return false;
    return isDeepEqual({ ...record, name: lcName }, { ...knownAnswer, name: lcName }, true);
  }
  #queryRecords({ name, recordType }, records) {
    const queryName = name.toLowerCase();
    if (recordType === DnsRecordType.ANY) {
      return records.filter((record) => record.name.toLowerCase() === queryName);
    } else {
      return records.filter(
        (record) => record.name.toLowerCase() === queryName && record.recordType === recordType
      );
    }
  }
  /**
   * RFC 6762 §7.3 - Checks if we should suppress a response because another responder
   * has recently answered the same question with answers that cover what we'd send.
   * Also, lazily cleans up expired entries from the cache.
   */
  #shouldSuppressResponse(queries, knownAnswers, sourceIntf, answers) {
    const now = Time.nowMs;
    for (const [key, entry] of this.#recentlyAnsweredQueries) {
      if (now - entry.timestamp >= QUESTION_SUPPRESSION_WINDOW) {
        this.#recentlyAnsweredQueries.delete(key);
      }
    }
    const queryKey = queries.map((q) => `${q.name.toLowerCase()}-${q.recordType}`).sort().join("|") + `-${sourceIntf}`;
    const cached = this.#recentlyAnsweredQueries.get(queryKey);
    if (cached && now - cached.timestamp < QUESTION_SUPPRESSION_WINDOW) {
      const answerHashes = answers.map((a) => this.buildDnsRecordKey(a, sourceIntf));
      const allAnswersKnown = answerHashes.every((h) => cached.knownAnswerHashes.has(h));
      if (allAnswersKnown) {
        return true;
      }
    }
    const knownAnswerHashes = /* @__PURE__ */ new Set();
    for (const answer of knownAnswers) {
      knownAnswerHashes.add(this.buildDnsRecordKey(answer, sourceIntf));
    }
    for (const answer of answers) {
      knownAnswerHashes.add(this.buildDnsRecordKey(answer, sourceIntf));
    }
    this.#recentlyAnsweredQueries.set(queryKey, {
      knownAnswerHashes,
      timestamp: now
    });
    return false;
  }
  async #processTruncatedQuery(key) {
    const { message, timer } = this.#truncatedQueryCache.get(key) ?? {};
    this.#truncatedQueryCache.delete(key);
    timer?.stop();
    if (message) {
      if (message.queries.length === 0) {
        return;
      }
      message.messageType &= ~DnsMessageTypeFlag.TC;
      await this.#handleMessage(message);
    }
  }
  /**
   * Delays processing of truncated messages to allow combining multiple parts or combines them if possible
   */
  #prepareMessage(newMessage) {
    const { messageType, transactionId, sourceIntf, sourceIp } = newMessage;
    if (!DnsMessageType.isQuery(messageType)) {
      return;
    }
    const key = `${transactionId}-${sourceIntf}-${sourceIp}`;
    const { message: existingMessage, timer } = this.#truncatedQueryCache.get(key) ?? {};
    this.#truncatedQueryCache.delete(key);
    timer?.stop();
    const message = existingMessage ? {
      ...existingMessage,
      queries: [...existingMessage.queries, ...newMessage.queries],
      answers: [...existingMessage.answers, ...newMessage.answers],
      additionalRecords: [...existingMessage.additionalRecords, ...newMessage.additionalRecords],
      messageType: newMessage.messageType
      // Keep TC flag as is from the latest message
    } : newMessage;
    if ((messageType & DnsMessageTypeFlag.TC) === 0) {
      if (message.queries.length === 0) {
        return;
      }
      return message;
    }
    this.#truncatedQueryCache.set(key, {
      message,
      timer: Time.getTimer(
        `Truncated MDNS message ${key}`,
        Millis(400 + Math.floor(Math.random() * 100)),
        () => this.#processTruncatedQuery(key)
      ).start()
    });
  }
}
export {
  MdnsServer,
  QUESTION_SUPPRESSION_WINDOW
};
//# sourceMappingURL=MdnsServer.js.map
