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 N
} from "./chunk-QRMCI4IG.js";
import {
  e as P
} from "./chunk-JNV2AX5Q.js";
import {
  b as A
} from "./chunk-OHF3P2FE.js";
import {
  a as M
} from "./chunk-5G5PMXGR.js";
import {
  a as W
} from "./chunk-E3SD6WWV.js";
import {
  a as p,
  f as d
} from "./chunk-HRN2KQZP.js";

// src/core-server/utils/server-statics.ts
var g = d(W(), 1), O = d(N(), 1), S = d(M(), 1);
import { existsSync as k, statSync as C } from "node:fs";
import { readFile as L, stat as _ } from "node:fs/promises";
import { basename as w, isAbsolute as D, join as $, posix as H, resolve as v, sep as U, win32 as B } from "node:path";
import { getDirectoryFromWorkingDir as G, resolvePathInStorybookCache as Y } from "storybook/internal/common";
import { logger as T, once as j } from "storybook/internal/node-logger";
var V = Y("", "ignored-sub").split("ignored-sub")[0], y = /* @__PURE__ */ new Map(), x = /* @__PURE__ */ p(async (e) => {
  if (y.has(e))
    return y.get(e);
  {
    let [o, i] = await Promise.all([L(e, "utf-8"), _(e)]), s = { data: o, mtime: i.mtimeMs };
    return y.set(e, s), s;
  }
}, "readFileOnce"), z = $(
  P("storybook"),
  "/assets/browser/favicon-wrapper.svg"
), J = /* @__PURE__ */ p((e) => {
  let [, o, i, s] = e?.match(/(<svg[^>]*>)(.*?)(<\/svg>)/s) ?? [];
  if (!o || !i || !s)
    return e;
  let n, t, r = o.replace(/width=["']([^"']*)["']/g, (c, l) => (n = parseFloat(l), 'width="32px"')).replace(/height=["']([^"']*)["']/g, (c, l) => (t = parseFloat(l), 'height="32px"'));
  return !/viewBox=["'][^"']*["']/.test(r) && n && t && (r = r.replace(/>$/, ` viewBox="0 0 ${n} ${t}">`)), r = r.replace(/preserveAspectRatio=["'][^"']*["']/g, "").replace(/>$/, ' preserveAspectRatio="xMidYMid meet">'), r + i + s;
}, "prepareNestedSvg");
async function me(e, o) {
  let i = await o.presets.apply("staticDirs") ?? [], s = await o.presets.apply("favicon"), n = v(s, ".."), t = w(s);
  e.use(`/${t}`, async (r, a, c) => {
    let l = r.query.status;
    if (l && t.endsWith(".svg") && ["active", "critical", "negative", "positive", "warning"].includes(l)) {
      let [u, m] = await Promise.all([
        x($(n, t)),
        x(z)
      ]).catch((f) => (f instanceof Error && j.warn(`Failed to read favicon: ${f.message}`), [null, null]));
      if (u && m) {
        let f = m.data.replace('<g id="mask"', `<g mask="url(#${l}-mask)"`).replace('<use id="status"', `<use href="#${l}"`).replace('<use id="icon" />', J(u.data));
        a.setHeader("Content-Type", "image/svg+xml"), a.setHeader("ETag", `"${m.mtime}-${u.mtime}"`), a.end(f);
        return;
      }
    }
    return r.url = `/${t}`, h(n)(r, a, c);
  }), i.map((r) => {
    try {
      let { staticDir: a, staticPath: c, targetEndpoint: l } = Q(r, o.configDir);
      if (!l.startsWith("/sb-") && !a.startsWith(V) && T.info(
        `=> Serving static files from ${g.default.cyan(a)} at ${g.default.cyan(l)}`
      ), k(c) && C(c).isFile()) {
        let u = v(c, ".."), m = w(c);
        e.use(l, (f, I, F) => {
          f.url = `/${m}`, h(u)(f, I, F);
        });
      } else
        e.use(l, h(c));
    } catch (a) {
      a instanceof Error && T.warn(a.message);
    }
  });
}
p(me, "useStatics");
var h = /* @__PURE__ */ p((e, o = {}) => (i, s, n) => {
  let t = i._parsedUrl, r = n ? () => {
    i._parsedUrl = t, n();
  } : void 0;
  (0, O.default)(e, { dev: !0, etag: !0, extensions: [], ...o })(i, s, r);
}, "sirvWorkaround"), K = /* @__PURE__ */ p((e) => {
  let o = e.lastIndexOf(":"), s = B.isAbsolute(e) && o === 1, n = o !== -1 && !s ? o : e.length, [t, r] = [e.slice(0, n), e.slice(n + 1)], a = D(t) ? t : `./${t}`, c = v(a);
  if (!k(c))
    throw new Error(
      S.dedent`
        Failed to load static files, no such directory: ${g.default.cyan(c)}
        Make sure this directory exists.
      `
    );
  let m = (r || (C(c).isFile() ? w(c) : "/")).split(U).join(H.sep).replace(/^\/?/, "./"), f = m.substring(1);
  return { staticDir: a, staticPath: c, targetDir: m, targetEndpoint: f };
}, "parseStaticDir"), Q = /* @__PURE__ */ p((e, o) => {
  let i = typeof e == "string" ? e : `${e.from}:${e.to}`, s = D(i) ? i : G({ configDir: o, workingDir: process.cwd(), directory: i });
  return K(s);
}, "mapStaticDir");

// src/core-server/withTelemetry.ts
var R = d(A(), 1);
import { HandledError as X, cache as b, loadAllPresets as Z } from "storybook/internal/common";
import { logger as q } from "storybook/internal/node-logger";
import { getPrecedingUpgrade as ee, oneWayHash as re, telemetry as E } from "storybook/internal/telemetry";
var te = /* @__PURE__ */ p(async () => {
  if (process.env.CI || !process.stdout.isTTY)
    return;
  let { enableCrashReports: e } = await (0, R.default)({
    type: "confirm",
    name: "enableCrashReports",
    message: "Would you like to help improve Storybook by sending anonymous crash reports?",
    initial: !0
  });
  return await b.set("enableCrashReports", e), e;
}, "promptCrashReports");
async function oe({
  cliOptions: e,
  presetOptions: o,
  skipPrompt: i
}) {
  if (e.disableTelemetry)
    return "none";
  if (!o)
    return "full";
  let n = await (await Z(o)).apply("core");
  if (n?.enableCrashReports !== void 0)
    return n.enableCrashReports ? "full" : "error";
  if (n?.disableTelemetry)
    return "none";
  let t = await b.get("enableCrashReports") ?? await b.get("enableCrashreports");
  if (t !== void 0)
    return t ? "full" : "error";
  if (i)
    return "error";
  let r = await te();
  return r !== void 0 ? r ? "full" : "error" : "full";
}
p(oe, "getErrorLevel");
async function se(e, o, i) {
  try {
    let s = "error";
    try {
      s = await oe(i);
    } catch {
    }
    if (s !== "none") {
      let n = await ee(), t = e, r;
      "message" in t ? r = t.message ? re(t.message) : "EMPTY_MESSAGE" : r = "NO_MESSAGE";
      let { code: a, name: c, category: l } = t;
      await E(
        "error",
        {
          code: a,
          name: c,
          category: l,
          eventType: o,
          precedingUpgrade: n,
          error: s === "full" ? t : void 0,
          errorHash: r,
          // if we ever end up sending a non-error instance, we'd like to know
          isErrorInstance: t instanceof Error
        },
        {
          immediate: !0,
          configDir: i.cliOptions.configDir || i.presetOptions?.configDir,
          enableCrashReports: s === "full"
        }
      );
    }
  } catch {
  }
}
p(se, "sendTelemetryError");
async function we(e, o, i) {
  let s = !(o.cliOptions.disableTelemetry || o.cliOptions.test === !0), n = !1;
  async function t() {
    n = !0, s && await E("canceled", { eventType: e }, { stripMetadata: !0, immediate: !0 }), process.exit(0);
  }
  p(t, "cancelTelemetry"), e === "init" && process.on("SIGINT", t), s && E("boot", { eventType: e }, { stripMetadata: !0 });
  try {
    return await i();
  } catch (r) {
    if (n)
      return;
    if (!(r instanceof X)) {
      let { printError: a = q.error } = o;
      a(r);
    }
    throw s && await se(r, e, o), r;
  } finally {
    process.off("SIGINT", t);
  }
}
p(we, "withTelemetry");

export {
  me as a,
  K as b,
  Q as c,
  oe as d,
  se as e,
  we as f
};
