import CJS_COMPAT_NODE_URL from 'node:url';
import CJS_COMPAT_NODE_PATH from 'node:path';
import CJS_COMPAT_NODE_MODULE from "node:module";

const __filename = CJS_COMPAT_NODE_URL.fileURLToPath(import.meta.url);
const __dirname = CJS_COMPAT_NODE_PATH.dirname(__filename);
const require = CJS_COMPAT_NODE_MODULE.createRequire(import.meta.url);
// ------------------------------------------------------------
// end of CJS compatibility banner, injected by Storybook's esbuild configuration
// ------------------------------------------------------------
import {
  a as j
} from "../_node-chunks/chunk-3BAQCC32.js";
import {
  j as ce,
  k as pe
} from "../_node-chunks/chunk-ENXVT5W6.js";
import "../_node-chunks/chunk-MES5DXOO.js";
import "../_node-chunks/chunk-FKZAYFJ3.js";
import {
  a as ie
} from "../_node-chunks/chunk-GXVMKGDT.js";
import "../_node-chunks/chunk-PIBCS5TU.js";
import {
  d as re
} from "../_node-chunks/chunk-XP4ZNFE5.js";
import "../_node-chunks/chunk-JLZG7VUL.js";
import {
  c as ae
} from "../_node-chunks/chunk-HFHLCGZP.js";
import "../_node-chunks/chunk-4Y3IMN4V.js";
import "../_node-chunks/chunk-3KW7Q6W3.js";
import "../_node-chunks/chunk-64SXAXSR.js";
import {
  a as oe
} from "../_node-chunks/chunk-JNV2AX5Q.js";
import "../_node-chunks/chunk-OHF3P2FE.js";
import "../_node-chunks/chunk-G3SRPRRF.js";
import {
  a as se
} from "../_node-chunks/chunk-WBEMC3FF.js";
import "../_node-chunks/chunk-5G5PMXGR.js";
import {
  a as et
} from "../_node-chunks/chunk-E3SD6WWV.js";
import {
  a as r,
  b as te,
  d as Xe,
  f as ne
} from "../_node-chunks/chunk-HRN2KQZP.js";

// ../node_modules/fetch-retry/index.js
var Je = Xe((Vr, Fe) => {
  "use strict";
  Fe.exports = function(e, t) {
    if (t = t || {}, typeof e != "function")
      throw new k("fetch must be a function");
    if (typeof t != "object")
      throw new k("defaults must be an object");
    if (t.retries !== void 0 && !J(t.retries))
      throw new k("retries must be a positive integer");
    if (t.retryDelay !== void 0 && !J(t.retryDelay) && typeof t.retryDelay != "function")
      throw new k("retryDelay must be a positive integer or a function returning a positive integer");
    if (t.retryOn !== void 0 && !Array.isArray(t.retryOn) && typeof t.retryOn != "function")
      throw new k("retryOn property expects an array or function");
    var n = {
      retries: 3,
      retryDelay: 1e3,
      retryOn: []
    };
    return t = Object.assign(n, t), /* @__PURE__ */ r(function(s, a) {
      var c = t.retries, p = t.retryDelay, l = t.retryOn;
      if (a && a.retries !== void 0)
        if (J(a.retries))
          c = a.retries;
        else
          throw new k("retries must be a positive integer");
      if (a && a.retryDelay !== void 0)
        if (J(a.retryDelay) || typeof a.retryDelay == "function")
          p = a.retryDelay;
        else
          throw new k("retryDelay must be a positive integer or a function returning a positive integer");
      if (a && a.retryOn)
        if (Array.isArray(a.retryOn) || typeof a.retryOn == "function")
          l = a.retryOn;
        else
          throw new k("retryOn property expects an array or function");
      return new Promise(function(g, d) {
        var P = /* @__PURE__ */ r(function(u) {
          var v = typeof Request < "u" && s instanceof Request ? s.clone() : s;
          e(v, a).then(function(m) {
            if (Array.isArray(l) && l.indexOf(m.status) === -1)
              g(m);
            else if (typeof l == "function")
              try {
                return Promise.resolve(l(u, null, m)).then(function(y) {
                  y ? w(u, null, m) : g(m);
                }).catch(d);
              } catch (y) {
                d(y);
              }
            else
              u < c ? w(u, null, m) : g(m);
          }).catch(function(m) {
            if (typeof l == "function")
              try {
                Promise.resolve(l(u, m, null)).then(function(y) {
                  y ? w(u, m, null) : d(m);
                }).catch(function(y) {
                  d(y);
                });
              } catch (y) {
                d(y);
              }
            else u < c ? w(u, m, null) : d(m);
          });
        }, "wrappedFetch");
        function w(u, v, m) {
          var y = typeof p == "function" ? p(u, v, m) : p;
          setTimeout(function() {
            P(++u);
          }, y);
        }
        r(w, "retry"), P(0);
      });
    }, "fetchRetry");
  };
  function J(e) {
    return Number.isInteger(e) && e >= 0;
  }
  r(J, "isPositiveInteger");
  function k(e) {
    this.name = "ArgumentError", this.message = e;
  }
  r(k, "ArgumentError");
});

// src/telemetry/index.ts
import { logger as qe } from "storybook/internal/node-logger";

// src/telemetry/notify.ts
var me = ne(et(), 1);
import { cache as le } from "storybook/internal/common";
import { CLI_COLORS as tt, logger as A } from "storybook/internal/node-logger";
var ue = "telemetry-notification-date", fe = /* @__PURE__ */ r(async () => {
  await le.get(ue, null) || (le.set(ue, Date.now()), A.log(
    `${tt.info("Attention:")} Storybook now collects completely anonymous telemetry regarding usage. This information is used to shape Storybook's roadmap and prioritize features.`
  ), A.log(
    "You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:"
  ), A.log(me.default.cyan("https://storybook.js.org/telemetry")), A.log(""));
}, "notify");

// src/telemetry/sanitize.ts
import ge from "node:path";
function de(e) {
  return e.replace(/[-[/{}()*+?.\\^$|]/g, "\\$&");
}
r(de, "regexpEscape");
function ye(e = "") {
  return e.replace(/\u001B\[[0-9;]*m/g, "");
}
r(ye, "removeAnsiEscapeCodes");
function T(e, t = ge.sep) {
  if (!e)
    return e;
  let n = process.cwd().split(t);
  for (; n.length > 1; ) {
    let o = n.join(t), s = new RegExp(de(o), "gi");
    e = e.replace(s, "$SNIP");
    let a = n.join(t + t), c = new RegExp(de(a), "gi");
    e = e.replace(c, "$SNIP"), n.pop();
  }
  return e;
}
r(T, "cleanPaths");
function C(e, t = ge.sep) {
  try {
    e = {
      ...JSON.parse(JSON.stringify(e)),
      message: ye(e.message),
      stack: ye(e.stack),
      cause: e.cause,
      name: e.name
    };
    let n = T(JSON.stringify(e), t);
    return JSON.parse(n);
  } catch (n) {
    return `Sanitization error: ${n?.message}`;
  }
}
r(C, "sanitizeError");

// src/telemetry/storybook-metadata.ts
import { dirname as Rt } from "node:path";
import {
  getProjectRoot as Nt,
  getStorybookConfiguration as It,
  getStorybookInfo as _t,
  loadMainConfig as Ft,
  versions as Jt
} from "storybook/internal/common";
import { readConfig as Lt } from "storybook/internal/csf-tools";

// ../node_modules/walk-up-path/dist/mjs/index.js
import { dirname as nt, resolve as rt } from "path";
var ke = /* @__PURE__ */ r(function* (e) {
  for (e = rt(e); e; ) {
    yield e;
    let t = nt(e);
    if (t === e)
      break;
    e = t;
  }
}, "walkUp");

// ../node_modules/fd-package-json/dist/esm/main.js
import { resolve as ot } from "node:path";
import { stat as at, readFile as st } from "node:fs/promises";
async function it(e) {
  try {
    return (await at(e)).isFile();
  } catch {
    return !1;
  }
}
r(it, "fileExists");
async function W(e) {
  for (let t of ke(e)) {
    let n = ot(t, "package.json");
    if (await it(n))
      return n;
  }
  return null;
}
r(W, "findPackagePath");
async function be(e) {
  let t = await W(e);
  if (!t)
    return null;
  try {
    let n = await st(t, { encoding: "utf8" });
    return JSON.parse(n);
  } catch {
    return null;
  }
}
r(be, "findPackage");

// ../node_modules/package-manager-detector/dist/commands.mjs
function we(e) {
  return (t) => t.length > 1 ? [e, "run", t[0], "--", ...t.slice(1)] : [e, "run", t[0]];
}
r(we, "npmRun");
function ct() {
  return (e) => ["deno", "run", `npm:${e[0]}`, ...e.slice(1)];
}
r(ct, "denoExecute");
var pt = {
  agent: ["npm", 0],
  run: we("npm"),
  install: ["npm", "i", 0],
  frozen: ["npm", "ci", 0],
  global: ["npm", "i", "-g", 0],
  add: ["npm", "i", 0],
  upgrade: ["npm", "update", 0],
  "upgrade-interactive": null,
  execute: ["npx", 0],
  "execute-local": ["npx", 0],
  uninstall: ["npm", "uninstall", 0],
  global_uninstall: ["npm", "uninstall", "-g", 0]
}, ve = {
  agent: ["yarn", 0],
  run: ["yarn", "run", 0],
  install: ["yarn", "install", 0],
  frozen: ["yarn", "install", "--frozen-lockfile", 0],
  global: ["yarn", "global", "add", 0],
  add: ["yarn", "add", 0],
  upgrade: ["yarn", "upgrade", 0],
  "upgrade-interactive": ["yarn", "upgrade-interactive", 0],
  execute: ["npx", 0],
  "execute-local": ["yarn", "exec", 0],
  uninstall: ["yarn", "remove", 0],
  global_uninstall: ["yarn", "global", "remove", 0]
}, lt = {
  ...ve,
  frozen: ["yarn", "install", "--immutable", 0],
  upgrade: ["yarn", "up", 0],
  "upgrade-interactive": ["yarn", "up", "-i", 0],
  execute: ["yarn", "dlx", 0],
  "execute-local": ["yarn", "exec", 0],
  // Yarn 2+ removed 'global', see https://github.com/yarnpkg/berry/issues/821
  global: ["npm", "i", "-g", 0],
  global_uninstall: ["npm", "uninstall", "-g", 0]
}, he = {
  agent: ["pnpm", 0],
  run: ["pnpm", "run", 0],
  install: ["pnpm", "i", 0],
  frozen: ["pnpm", "i", "--frozen-lockfile", 0],
  global: ["pnpm", "add", "-g", 0],
  add: ["pnpm", "add", 0],
  upgrade: ["pnpm", "update", 0],
  "upgrade-interactive": ["pnpm", "update", "-i", 0],
  execute: ["pnpm", "dlx", 0],
  "execute-local": ["pnpm", "exec", 0],
  uninstall: ["pnpm", "remove", 0],
  global_uninstall: ["pnpm", "remove", "--global", 0]
}, ut = {
  agent: ["bun", 0],
  run: ["bun", "run", 0],
  install: ["bun", "install", 0],
  frozen: ["bun", "install", "--frozen-lockfile", 0],
  global: ["bun", "add", "-g", 0],
  add: ["bun", "add", 0],
  upgrade: ["bun", "update", 0],
  "upgrade-interactive": ["bun", "update", 0],
  execute: ["bun", "x", 0],
  "execute-local": ["bun", "x", 0],
  uninstall: ["bun", "remove", 0],
  global_uninstall: ["bun", "remove", "-g", 0]
}, mt = {
  agent: ["deno", 0],
  run: ["deno", "task", 0],
  install: ["deno", "install", 0],
  frozen: ["deno", "install", "--frozen", 0],
  global: ["deno", "install", "-g", 0],
  add: ["deno", "add", 0],
  upgrade: ["deno", "outdated", "--update", 0],
  "upgrade-interactive": ["deno", "outdated", "--update", 0],
  execute: ct(),
  "execute-local": ["deno", "task", "--eval", 0],
  uninstall: ["deno", "remove", 0],
  global_uninstall: ["deno", "uninstall", "-g", 0]
}, ft = {
  npm: pt,
  yarn: ve,
  "yarn@berry": lt,
  pnpm: he,
  // pnpm v6.x or below
  "pnpm@6": {
    ...he,
    run: we("pnpm")
  },
  bun: ut,
  deno: mt
};

// ../node_modules/package-manager-detector/dist/constants.mjs
var V = [
  "npm",
  "yarn",
  "yarn@berry",
  "pnpm",
  "pnpm@6",
  "bun",
  "deno"
], M = {
  "bun.lock": "bun",
  "bun.lockb": "bun",
  "deno.lock": "deno",
  "pnpm-lock.yaml": "pnpm",
  "pnpm-workspace.yaml": "pnpm",
  "yarn.lock": "yarn",
  "package-lock.json": "npm",
  "npm-shrinkwrap.json": "npm"
}, R = {
  "node_modules/.deno/": "deno",
  "node_modules/.pnpm/": "pnpm",
  "node_modules/.yarn-state.yml": "yarn",
  // yarn v2+ (node-modules)
  "node_modules/.yarn_integrity": "yarn",
  // yarn v1
  "node_modules/.package-lock.json": "npm",
  ".pnp.cjs": "yarn",
  // yarn v3+ (pnp)
  ".pnp.js": "yarn",
  // yarn v2 (pnp)
  "bun.lock": "bun",
  "bun.lockb": "bun"
};

// ../node_modules/package-manager-detector/dist/detect.mjs
import Pe from "node:fs/promises";
import b from "node:path";
import dt from "node:process";
async function $(e, t) {
  try {
    let n = await Pe.stat(e);
    return t === "file" ? n.isFile() : n.isDirectory();
  } catch {
    return !1;
  }
}
r($, "pathExists");
function* yt(e = dt.cwd()) {
  let t = b.resolve(e), { root: n } = b.parse(t);
  for (; t && t !== n; )
    yield t, t = b.dirname(t);
}
r(yt, "lookup");
async function xe(e, t) {
  return !e || !$(e, "file") ? null : await kt(e, t);
}
r(xe, "parsePackageJson");
async function z(e = {}) {
  let { cwd: t, strategies: n = ["lockfile", "packageManager-field", "devEngines-field"], onUnknown: o } = e;
  for (let s of yt(t))
    for (let a of n)
      switch (a) {
        case "lockfile": {
          for (let c of Object.keys(M))
            if (await $(b.join(s, c), "file")) {
              let p = M[c], l = await xe(b.join(s, "package.json"), o);
              return l || { name: p, agent: p };
            }
          break;
        }
        case "packageManager-field":
        case "devEngines-field": {
          let c = await xe(b.join(s, "package.json"), o);
          if (c)
            return c;
          break;
        }
        case "install-metadata": {
          for (let c of Object.keys(R)) {
            let p = c.endsWith("/") ? "dir" : "file";
            if (await $(b.join(s, c), p)) {
              let l = R[c], g = l === "yarn" ? bt(c) ? "yarn" : "yarn@berry" : l;
              return { name: l, agent: g };
            }
          }
          break;
        }
      }
  return null;
}
r(z, "detect");
function gt(e) {
  let t = /* @__PURE__ */ r((n) => n?.match(/\d+(\.\d+){0,2}/)?.[0] ?? n, "handelVer");
  if (typeof e.packageManager == "string") {
    let [n, o] = e.packageManager.replace(/^\^/, "").split("@");
    return { name: n, ver: t(o) };
  }
  if (typeof e.devEngines?.packageManager?.name == "string")
    return {
      name: e.devEngines.packageManager.name,
      ver: t(e.devEngines.packageManager.version)
    };
}
r(gt, "getNameAndVer");
async function kt(e, t) {
  try {
    let n = JSON.parse(await Pe.readFile(e, "utf8")), o, s = gt(n);
    if (s) {
      let a = s.name, c = s.ver, p = c;
      return a === "yarn" && c && Number.parseInt(c) > 1 ? (o = "yarn@berry", p = "berry", { name: a, agent: o, version: p }) : a === "pnpm" && c && Number.parseInt(c) < 7 ? (o = "pnpm@6", { name: a, agent: o, version: p }) : V.includes(a) ? (o = a, { name: a, agent: o, version: p }) : t?.(n.packageManager) ?? null;
    }
  } catch {
  }
  return null;
}
r(kt, "handlePackageManager");
function bt(e) {
  return e.endsWith(".yarn_integrity");
}
r(bt, "isMetadataYarnClassic");

// src/telemetry/get-application-file-count.ts
import { sep as wt } from "node:path";

// src/telemetry/exec-command-count-lines.ts
import { createInterface as ht } from "node:readline";
async function N(e, t) {
  let n = re(e, { shell: !0, buffer: !1, ...t });
  if (!n.stdout)
    throw new Error("Unexpected missing stdout");
  let o = 0, s = ht(n.stdout);
  return s.on("line", () => {
    o += 1;
  }), await n, s.close(), o;
}
r(N, "execCommandCountLines");

// src/telemetry/run-telemetry-operation.ts
var Se = ce({
  basePath: pe("telemetry"),
  ns: "storybook",
  ttl: 24 * 60 * 60 * 1e3
  // 24h
}), I = /* @__PURE__ */ r(async (e, t) => {
  let n = await Se.get(e);
  return n === void 0 && (n = await t(), n !== void 0 && await Se.set(e, n)), n;
}, "runTelemetryOperation");

// src/telemetry/get-application-file-count.ts
var vt = ["page", "screen"], xt = ["js", "jsx", "ts", "tsx"], Pt = /* @__PURE__ */ r(async (e) => {
  let n = vt.flatMap((o) => [
    o,
    [o[0].toUpperCase(), ...o.slice(1)].join("")
  ]).flatMap(
    (o) => xt.map((s) => `"${e}${wt}*${o}*.${s}"`)
  );
  try {
    let o = `git ls-files -- ${n.join(" ")}`;
    return await N(o);
  } catch {
    return;
  }
}, "getApplicationFilesCountUncached"), Te = /* @__PURE__ */ r(async (e) => I(
  "applicationFiles",
  async () => Pt(e)
), "getApplicationFileCount");

// src/telemetry/get-chromatic-version.ts
function Ee(e) {
  let t = e.dependencies?.chromatic || e.devDependencies?.chromatic || e.peerDependencies?.chromatic;
  return t || (e.scripts && Object.values(e.scripts).find((n) => n?.match(/chromatic/)) ? "latest" : void 0);
}
r(Ee, "getChromaticVersionSpecifier");

// src/telemetry/get-framework-info.ts
import { normalize as Tt } from "node:path";
import { frameworkPackages as Et } from "storybook/internal/common";

// src/telemetry/package-json.ts
import { fileURLToPath as St } from "node:url";
var B = /* @__PURE__ */ r(async (e) => {
  let t = Object.keys(e);
  return Promise.all(t.map(_));
}, "getActualPackageVersions"), _ = /* @__PURE__ */ r(async (e) => {
  try {
    let t = await G(e);
    return {
      name: t?.name || e,
      version: t?.version || null
    };
  } catch {
    return {
      name: e,
      version: null
    };
  }
}, "getActualPackageVersion"), G = /* @__PURE__ */ r(async (e) => {
  try {
    let t = await ae("package.json", {
      cwd: St(import.meta.resolve(e, process.cwd()))
    });
    t || (t = import.meta.resolve(
      oe(e, "package.json"),
      process.cwd()
    ));
    let { default: n } = await import(t, {
      with: { type: "json" }
    });
    return n;
  } catch {
    return;
  }
}, "getActualPackageJson");

// src/telemetry/get-framework-info.ts
var Ot = [
  "html",
  "react",
  "svelte",
  "vue3",
  "preact",
  "server",
  "vue",
  "web-components",
  "angular",
  "ember"
], Dt = ["builder-webpack5", "builder-vite"];
function Oe(e, t) {
  let { name: n = "", version: o, dependencies: s, devDependencies: a, peerDependencies: c } = e, p = {
    // We include the framework itself because it may be a renderer too (e.g. angular)
    [n]: o,
    ...s,
    ...a,
    ...c
  };
  return t.map((l) => `@storybook/${l}`).find((l) => p[l]);
}
r(Oe, "findMatchingPackage");
var jt = /* @__PURE__ */ r((e) => {
  let t = Tt(e).replace(new RegExp(/\\/, "g"), "/");
  return Object.keys(Et).find((o) => t.endsWith(o)) || T(e).replace(/.*node_modules[\\/]/, "");
}, "getFrameworkPackageName");
async function De(e) {
  if (!e?.framework)
    return {};
  let t = typeof e.framework == "string" ? e.framework : e.framework?.name;
  if (!t)
    return {};
  let n = await G(t);
  if (!n)
    return {};
  let o = Oe(n, Dt), s = Oe(n, Ot), a = jt(t), c = typeof e.framework == "object" ? e.framework.options : {};
  return {
    framework: {
      name: a,
      options: c
    },
    builder: o,
    renderer: s
  };
}
r(De, "getFrameworkInfo");

// src/telemetry/get-has-router-package.ts
var At = /* @__PURE__ */ new Set([
  "react-router",
  "react-router-dom",
  "remix",
  "@tanstack/react-router",
  "expo-router",
  "@reach/router",
  "react-easy-router",
  "@remix-run/router",
  "wouter",
  "wouter-preact",
  "preact-router",
  "vue-router",
  "unplugin-vue-router",
  "@angular/router",
  "@solidjs/router",
  // metaframeworks that imply routing
  "next",
  "react-scripts",
  "gatsby",
  "nuxt",
  "@sveltejs/kit"
]);
function je(e) {
  return Object.keys(e?.dependencies ?? {}).some(
    (t) => At.has(t)
  );
}
r(je, "getHasRouterPackage");

// src/telemetry/get-monorepo-type.ts
import { existsSync as Ae, readFileSync as Ct } from "node:fs";
import { join as Y } from "node:path";
import { getProjectRoot as H } from "storybook/internal/common";
var Ce = {
  Nx: "nx.json",
  Turborepo: "turbo.json",
  Lerna: "lerna.json",
  Rush: "rush.json",
  Lage: "lage.config.json"
}, Me = /* @__PURE__ */ r(() => {
  let t = Object.keys(Ce).find((o) => {
    let s = Y(H(), Ce[o]);
    return Ae(s);
  });
  if (t)
    return t;
  if (!Ae(Y(H(), "package.json")))
    return;
  if (JSON.parse(
    Ct(Y(H(), "package.json"), { encoding: "utf8" })
  )?.workspaces)
    return "Workspaces";
}, "getMonorepoType");

// src/telemetry/get-portable-stories-usage.ts
var Mt = /* @__PURE__ */ r(async (e) => {
  try {
    let t = "git grep -l composeStor" + (e ? ` -- ${e}` : "");
    return await N(t);
  } catch (t) {
    return t.exitCode === 1 ? 0 : void 0;
  }
}, "getPortableStoriesFileCountUncached"), Re = /* @__PURE__ */ r(async (e) => I(
  "portableStories",
  async () => Mt(e)
), "getPortableStoriesFileCount");

// src/telemetry/storybook-metadata.ts
var Ne = {
  next: "Next",
  "react-scripts": "CRA",
  gatsby: "Gatsby",
  "@nuxtjs/storybook": "nuxt",
  "@nrwl/storybook": "nx",
  "@vue/cli-service": "vue-cli",
  "@sveltejs/kit": "sveltekit"
}, Ie = /* @__PURE__ */ r((e) => T(e).replace(/\/dist\/.*/, "").replace(/\.[mc]?[tj]?s[x]?$/, "").replace(/\/register$/, "").replace(/\/manager$/, "").replace(/\/preset$/, ""), "sanitizeAddonName"), Ut = /* @__PURE__ */ r(async ({
  packageJsonPath: e,
  packageJson: t,
  mainConfig: n,
  configDir: o
}) => {
  let s = await ie(), a = {
    generatedAt: (/* @__PURE__ */ new Date()).getTime(),
    userSince: s.value.userSince,
    hasCustomBabel: !1,
    hasCustomWebpack: !1,
    hasStaticDirs: !1,
    hasStorybookEslint: !1,
    refCount: 0
  }, c = {
    ...t?.dependencies,
    ...t?.devDependencies,
    ...t?.peerDependencies
  }, p = Object.keys(c).find((i) => !!Ne[i]);
  if (p) {
    let { version: i } = await _(p);
    a.metaFramework = {
      name: Ne[p],
      packageName: p,
      version: i || "unknown"
    };
  }
  let l = [
    "playwright",
    "vitest",
    "jest",
    "cypress",
    "nightwatch",
    "webdriver",
    "@web/test-runner",
    "puppeteer",
    "karma",
    "jasmine",
    "chai",
    "testing-library",
    "@ngneat/spectator",
    "wdio",
    "msw",
    "miragejs",
    "sinon",
    "chromatic"
  ], g = Object.keys(c).filter(
    (i) => l.find((f) => i.includes(f))
  );
  a.testPackages = Object.fromEntries(
    await Promise.all(
      g.map(async (i) => [i, (await _(i))?.version])
    )
  ), a.hasRouterPackage = je(t);
  let d = Me();
  d && (a.monorepo = d);
  try {
    let i = await z({ cwd: Nt() });
    i && (a.packageManager = {
      type: i.name,
      version: i.version,
      agent: i.agent
    });
  } catch {
  }
  let P = c.typescript ? "typescript" : "javascript";
  if (!n)
    return {
      ...a,
      storybookVersionSpecifier: Jt.storybook,
      language: P
    };
  a.hasCustomBabel = !!n.babel, a.hasCustomWebpack = !!n.webpackFinal, a.hasStaticDirs = !!n.staticDirs, typeof n.typescript == "object" && (a.typescriptOptions = n.typescript);
  let w = await De(n);
  typeof n.refs == "object" && (a.refCount = Object.keys(n.refs).length), typeof n.features == "object" && (a.features = n.features);
  let u = {};
  n.addons && n.addons.forEach((i) => {
    let f, D;
    typeof i == "string" ? f = Ie(i) : (i.name.includes("addon-essentials") && (D = i.options), f = Ie(i.name)), u[f] = {
      options: D,
      version: void 0
    };
  });
  let v = Ee(t);
  v && (u.chromatic = {
    version: void 0,
    versionSpecifier: v,
    options: void 0
  }), (await B(u)).forEach(({ name: i, version: f }) => {
    u[i] = u[i] || {
      name: i,
      version: f
    }, u[i].version = f || void 0;
  });
  let y = Object.keys(u), S = Object.keys(c).filter((i) => i.includes("storybook") && !y.includes(i)).reduce((i, f) => ({
    ...i,
    [f]: { version: void 0 }
  }), {});
  (await B(S)).forEach(({ name: i, version: f }) => {
    S[i] = S[i] || {
      name: i,
      version: f
    }, S[i].version = f || void 0;
  });
  let Ke = !!c["eslint-plugin-storybook"], ee = await _t(o);
  try {
    let { previewConfigPath: i } = ee;
    if (i) {
      let f = await Lt(i), D = !!(f.getFieldNode(["globals"]) || f.getFieldNode(["globalTypes"]));
      a.preview = { ...a.preview, usesGlobals: D };
    }
  } catch {
  }
  let Ze = await Re(), Qe = await Te(Rt(e));
  return {
    ...a,
    ...w,
    portableStoriesFileCount: Ze,
    applicationFileCount: Qe,
    storybookVersion: j,
    storybookVersionSpecifier: ee.version,
    language: P,
    storybookPackages: S,
    addons: u,
    hasStorybookEslint: Ke
  };
}, "computeStorybookMetadata");
async function Wt() {
  let e = await W(process.cwd());
  return e ? {
    packageJsonPath: e,
    packageJson: await be(e) || {}
  } : {
    packageJsonPath: process.cwd(),
    packageJson: {}
  };
}
r(Wt, "getPackageJsonDetails");
var F, _e = /* @__PURE__ */ r(async (e) => {
  if (F)
    return F;
  let { packageJson: t, packageJsonPath: n } = await Wt(), o = (e || It(
    String(t?.scripts?.storybook || ""),
    "-c",
    "--config-dir"
  )) ?? ".storybook", s = await Ft({ configDir: o }).catch(() => {
  });
  return F = await Ut({
    mainConfig: s,
    packageJson: t,
    packageJsonPath: n,
    configDir: o
  }), F;
}, "getStorybookMetadata");

// src/telemetry/telemetry.ts
var Ye = ne(Je(), 1);
import { readFileSync as nn } from "node:fs";
import * as Ge from "node:os";

// ../node_modules/nanoid/index.js
import { randomFillSync as Ue } from "crypto";

// ../node_modules/nanoid/url-alphabet/index.js
var Le = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";

// ../node_modules/nanoid/index.js
var Vt = 128, h, x, $t = /* @__PURE__ */ r((e) => {
  !h || h.length < e ? (h = Buffer.allocUnsafe(e * Vt), Ue(h), x = 0) : x + e > h.length && (Ue(h), x = 0), x += e;
}, "fillPool");
var E = /* @__PURE__ */ r((e = 21) => {
  $t(e -= 0);
  let t = "";
  for (let n = x - e; n < x; n++)
    t += Le[h[n] & 63];
  return t;
}, "nanoid");

// src/telemetry/anonymous-id.ts
import { relative as Bt } from "node:path";
import { getProjectRoot as Gt } from "storybook/internal/common";
import { execSync as Yt } from "child_process";

// src/telemetry/one-way-hash.ts
import { createHash as zt } from "crypto";
var q = /* @__PURE__ */ r((e) => {
  let t = zt("sha256");
  return t.update("storybook-telemetry-salt"), t.update(e), t.digest("hex");
}, "oneWayHash");

// src/telemetry/anonymous-id.ts
function Ht(e) {
  let o = e.trim().replace(/#.*$/, "").replace(/^.*@/, "").replace(/^.*\/\//, "");
  return (o.endsWith(".git") ? o : `${o}.git`).replace(":", "/");
}
r(Ht, "normalizeGitUrl");
function qt(e, t) {
  return `${Ht(e)}${se(t)}`;
}
r(qt, "unhashedProjectId");
var L, We = /* @__PURE__ */ r(() => {
  if (L)
    return L;
  try {
    let e = Bt(Gt(), process.cwd()), t = Yt("git config --local --get remote.origin.url", {
      timeout: 1e3,
      stdio: "pipe"
    });
    L = q(qt(String(t), e));
  } catch {
  }
  return L;
}, "getAnonymousProjectId");

// src/telemetry/event-cache.ts
import { cache as Z } from "storybook/internal/common";
var K = Promise.resolve(), Kt = /* @__PURE__ */ r(async (e, t) => {
  let n = await Z.get("lastEvents") || {};
  n[e] = { body: t, timestamp: Date.now() }, await Z.set("lastEvents", n);
}, "setHelper"), $e = /* @__PURE__ */ r(async (e, t) => (await K, K = Kt(e, t), K), "set");
var Zt = /* @__PURE__ */ r((e) => {
  let { body: t, timestamp: n } = e;
  return {
    timestamp: n,
    eventType: t?.eventType,
    eventId: t?.eventId,
    sessionId: t?.sessionId
  };
}, "upgradeFields"), Qt = ["init", "upgrade"], Xt = ["build", "dev", "error"], Ve = /* @__PURE__ */ r((e, t) => {
  let n = t.map((o) => e?.[o]).filter(Boolean).sort((o, s) => s.timestamp - o.timestamp);
  return n.length > 0 ? n[0] : void 0;
}, "lastEvent"), en = /* @__PURE__ */ r(async (e = void 0) => {
  let t = e || await Z.get("lastEvents") || {}, n = Ve(t, Qt), o = Ve(t, Xt);
  if (n)
    return !o?.timestamp || n.timestamp > o.timestamp ? Zt(n) : void 0;
}, "getPrecedingUpgrade");

// src/telemetry/fetch.ts
var ze = global.fetch;

// src/telemetry/session-id.ts
import { cache as Be } from "storybook/internal/common";
var tn = 1e3 * 60 * 60 * 2, O;
var Q = /* @__PURE__ */ r(async () => {
  let e = Date.now();
  if (!O) {
    let t = await Be.get("session");
    t && t.lastUsed >= e - tn ? O = t.id : O = E();
  }
  return await Be.set("session", { id: O, lastUsed: e }), O;
}, "getSessionId");

// src/telemetry/telemetry.ts
var rn = (0, Ye.default)(ze), on = process.env.STORYBOOK_TELEMETRY_URL || "https://storybook.js.org/event-log", U = [], an = /* @__PURE__ */ r((e, t) => {
  X[e] = t;
}, "addToGlobalContext"), sn = /* @__PURE__ */ r(() => {
  try {
    let e = Ge.platform();
    return e === "win32" ? "Windows" : e === "darwin" ? "macOS" : e === "linux" ? "Linux" : `Other: ${e}`;
  } catch {
    return "Unknown";
  }
}, "getOperatingSystem"), X = {
  inCI: !!process.env.CI,
  isTTY: process.stdout.isTTY,
  platform: sn(),
  nodeVersion: process.versions.node,
  storybookVersion: pn()
}, cn = /* @__PURE__ */ r(async (e, t, n) => {
  let { eventType: o, payload: s, metadata: a, ...c } = e, p = await Q(), l = E(), g = { ...c, eventType: o, eventId: l, sessionId: p, metadata: a, payload: s, context: t };
  return rn(on, {
    method: "post",
    body: JSON.stringify(g),
    headers: { "Content-Type": "application/json" },
    retries: 3,
    retryOn: [503, 504],
    retryDelay: /* @__PURE__ */ r((d) => 2 ** d * (typeof n?.retryDelay == "number" && !Number.isNaN(n?.retryDelay) ? n.retryDelay : 1e3), "retryDelay")
  });
}, "prepareRequest");
function pn() {
  try {
    return JSON.parse(nn(te.resolve("storybook/package.json"), "utf8")).version;
  } catch {
    return j;
  }
}
r(pn, "getVersionNumber");
async function He(e, t = { retryDelay: 1e3, immediate: !1 }) {
  let { eventType: n, payload: o, metadata: s, ...a } = e, c = t.stripMetadata ? X : {
    ...X,
    anonymousId: We()
  }, p;
  try {
    p = cn(e, c, t), U.push(p), t.immediate ? await Promise.all(U) : await p;
    let l = await Q(), g = E(), d = { ...a, eventType: n, eventId: g, sessionId: l, metadata: s, payload: o, context: c };
    await $e(n, d);
  } catch {
  } finally {
    U = U.filter((l) => l !== p);
  }
}
r(He, "sendTelemetry");

// src/telemetry/index.ts
var Do = /* @__PURE__ */ r((e) => e.startsWith("example-button--") || e.startsWith("example-header--") || e.startsWith("example-page--"), "isExampleStoryId"), jo = /* @__PURE__ */ r(async (e, t = {}, n = {}) => {
  e !== "boot" && n.notify !== !1 && await fe();
  let o = {
    eventType: e,
    payload: t
  };
  try {
    n?.stripMetadata || (o.metadata = await _e(n?.configDir));
  } catch (s) {
    o.payload.metadataErrorMessage = C(s).message, n?.enableCrashReports && (o.payload.metadataError = C(s));
  } finally {
    let { error: s } = o.payload;
    s && (o.payload.error = C(s)), (!o.payload.error || n?.enableCrashReports) && (process.env?.STORYBOOK_TELEMETRY_DEBUG && (qe.info(`
[telemetry]`), qe.info(JSON.stringify(o, null, 2))), await He(o, n));
  }
}, "telemetry");
export {
  an as addToGlobalContext,
  T as cleanPaths,
  Ut as computeStorybookMetadata,
  en as getPrecedingUpgrade,
  _e as getStorybookMetadata,
  Do as isExampleStoryId,
  Ne as metaFrameworks,
  q as oneWayHash,
  ye as removeAnsiEscapeCodes,
  Ie as sanitizeAddonName,
  C as sanitizeError,
  jo as telemetry
};
