"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var heap_exports = {};
__export(heap_exports, {
  HeapDumpSet: () => HeapDumpSet
});
module.exports = __toCommonJS(heap_exports);
var import_api = require("@memlab/api");
var import_core = __toESM(require("@memlab/core"), 1);
var import_js_tools = require("@nacho-iot/js-tools");
var import_memlab = __toESM(require("memlab"), 1);
var import_promises = require("node:fs/promises");
var import_node_path = require("node:path");
var import_node_v8 = require("node:v8");
var import_runner = require("../runner.js");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import_api.config.externalLeakFilter = {
  leakFilter(_node) {
    return true;
  },
  retainerReferenceFilter(edge, _snapshot, isReferenceUsedByDefault) {
    switch (edge.name_or_index) {
      case "MatterHooks":
      case "MockLogger":
      case "MockTime":
      case "MochaReporter":
      case "mocha":
      case "#wrapPrefix":
      case "#dumps":
      case "_playwrightInstance":
      case "logs":
        return false;
    }
    return isReferenceUsedByDefault;
  }
};
let skipNextConsoleNewline = false;
Object.defineProperties(import_core.default.info, {
  outStream: {
    value: {
      write(payload) {
        payload = payload.toString();
        if (payload === "\x1B[K" || payload === "\x1B[F") {
          skipNextConsoleNewline = true;
          return;
        }
        payload = payload.trimEnd();
        for (const line of payload.toString().split("\n")) {
          if (skipNextConsoleNewline) {
            skipNextConsoleNewline = false;
            if (line === "") {
              continue;
            }
          }
          MockLogger.injectExternalMessage("MEMLAB", line);
        }
      }
    }
  }
});
class HeapDumpSet {
  #dir;
  #startedAt = /* @__PURE__ */ new Date();
  #dumps = {};
  #nextId = 1;
  constructor(name) {
    this.#dir = import_runner.TestRunner.current.pkg.resolve(`build/heaps/${name}-${this.#startedAt.toISOString()}`);
  }
  get(name) {
    const path = this.#dumps[name];
    if (path === void 0) {
      throw new Error(`No dump named "${name}"`);
    }
    return path;
  }
  async create(name = "dump") {
    await import_runner.TestRunner.current.progress.subtask(`heap dump ${name}`, async () => {
      if (!(0, import_js_tools.isDirectory)(this.#dir)) {
        await (0, import_promises.mkdir)(this.#dir, { recursive: true });
      }
      const path = (0, import_node_path.join)(
        this.#dir,
        `${(this.#nextId++).toString().padStart(2, "0")}-${name}-${Date.now() - this.#startedAt.getTime()}.heapsnapshot`
      );
      (0, import_node_v8.writeHeapSnapshot)(path);
      this.#dumps[name] = path;
    });
  }
  async findLeaks() {
    const paths = Object.values(this.#dumps);
    if (paths.length !== 3) {
      throw new Error("Leak analysis requires three heap dumps: baseline, target and final");
    }
    let result = [];
    await import_runner.TestRunner.current.progress.subtask("analyzing leaks", async () => {
      const snapshots = import_memlab.default.SnapshotResultReader.fromSnapshots(paths[0], paths[1], paths[2]);
      result = await (0, import_api.findLeaks)(snapshots);
    });
    return result;
  }
}
//# sourceMappingURL=heap.js.map
