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 {
  b as X,
  e as q
} from "../../_node-chunks/chunk-KEDHCFPX.js";
import "../../_node-chunks/chunk-QRMCI4IG.js";
import {
  a as L
} from "../../_node-chunks/chunk-64SXAXSR.js";
import {
  a as T,
  e as h
} from "../../_node-chunks/chunk-JNV2AX5Q.js";
import "../../_node-chunks/chunk-OHF3P2FE.js";
import {
  o as Q
} from "../../_node-chunks/chunk-X4DZG7WK.js";
import {
  a as $
} from "../../_node-chunks/chunk-5G5PMXGR.js";
import "../../_node-chunks/chunk-E3SD6WWV.js";
import {
  a as i,
  f as k
} from "../../_node-chunks/chunk-HRN2KQZP.js";

// src/core-server/presets/common-preset.ts
import { existsSync as Fe } from "node:fs";
import { readFile as wt } from "node:fs/promises";
import { isAbsolute as Et, join as G } from "node:path";
import {
  JsPackageManagerFactory as bt,
  getDirectoryFromWorkingDir as ht,
  getPreviewBodyTemplate as Ct,
  getPreviewHeadTemplate as Rt,
  loadEnvs as Pt,
  removeAddon as ve
} from "storybook/internal/common";
import { readCsf as Nt } from "storybook/internal/csf-tools";
import { logger as vt } from "storybook/internal/node-logger";
import { telemetry as Ft } from "storybook/internal/telemetry";
var Oe = k($(), 1);

// src/core-server/server-channel/create-new-story-channel.ts
import { existsSync as je } from "node:fs";
import { writeFile as Ae } from "node:fs/promises";
import { relative as ce } from "node:path";
import { getStoryId as We } from "storybook/internal/common";
import {
  CREATE_NEW_STORYFILE_REQUEST as Le,
  CREATE_NEW_STORYFILE_RESPONSE as V
} from "storybook/internal/core-events";
import { telemetry as z } from "storybook/internal/telemetry";

// src/core-server/utils/get-new-story-file.ts
import { existsSync as _ } from "node:fs";
import { readFile as De } from "node:fs/promises";
import { basename as ie, dirname as se, extname as ne, join as C } from "node:path";
import {
  extractProperFrameworkName as ke,
  findConfigFile as $e,
  getFrameworkName as _e,
  getProjectRoot as U
} from "storybook/internal/common";
import { isCsfFactoryPreview as Ie } from "storybook/internal/csf-tools";

// src/core-server/utils/new-story-templates/csf-factory-template.ts
var Z = k($(), 1);

// src/core-server/utils/get-component-variable-name.ts
var F = /* @__PURE__ */ i(async (e) => (await import("../../_node-chunks/camelcase-AZ53QZ6T.js")).default(e.replace(/^[^a-zA-Z_$]*/, ""), { pascalCase: !0 }).replace(/[^a-zA-Z_$]+/, ""), "getComponentVariableName");

// src/core-server/utils/new-story-templates/csf-factory-template.ts
async function K(e) {
  let t = e.componentIsDefaultExport ? await F(e.basenameWithoutExtension) : e.componentExportName, o = e.componentIsDefaultExport ? `import ${t} from './${e.basenameWithoutExtension}';` : `import { ${t} } from './${e.basenameWithoutExtension}';`;
  return Z.dedent`
  ${"import preview from '#.storybook/preview';"}
  
  ${o}

  const meta = preview.meta({
    component: ${t},
  });
  
  export const ${e.exportedStoryName} = meta.story({});
  `;
}
i(K, "getCsfFactoryTemplateForNewStoryFile");

// src/core-server/utils/new-story-templates/javascript.ts
var ee = k($(), 1);
async function te(e) {
  let t = e.componentIsDefaultExport ? await F(e.basenameWithoutExtension) : e.componentExportName, o = e.componentIsDefaultExport ? `import ${t} from './${e.basenameWithoutExtension}';` : `import { ${t} } from './${e.basenameWithoutExtension}';`;
  return ee.dedent`
  ${o}

  const meta = {
    component: ${t},
  };
  
  export default meta;
  
  export const ${e.exportedStoryName} = {};
  `;
}
i(te, "getJavaScriptTemplateForNewStoryFile");

// src/core-server/utils/new-story-templates/typescript.ts
var re = k($(), 1);
async function oe(e) {
  let t = e.componentIsDefaultExport ? await F(e.basenameWithoutExtension) : e.componentExportName, o = e.componentIsDefaultExport ? `import ${t} from './${e.basenameWithoutExtension}'` : `import { ${t} } from './${e.basenameWithoutExtension}'`;
  return re.dedent`
  import type { Meta, StoryObj } from '${e.frameworkPackage}';

  ${o};

  const meta = {
    component: ${t},
  } satisfies Meta<typeof ${t}>;

  export default meta;

  type Story = StoryObj<typeof meta>;

  export const ${e.exportedStoryName}: Story = {};
  `;
}
i(oe, "getTypeScriptTemplateForNewStoryFile");

// src/core-server/utils/get-new-story-file.ts
async function ae({
  componentFilePath: e,
  componentExportName: t,
  componentIsDefaultExport: o,
  componentExportCount: r
}, n) {
  let s = await _e(n), c = ke(s), p = ie(e), a = ne(e), m = p.replace(a, ""), l = se(e), { storyFileName: y, isTypescript: d, storyFileExtension: S } = M(e), u = `${y}.${S}`, R = `${m}.${t}.stories.${S}`, P = "Default", D = !1;
  try {
    let N = $e("preview", n.configDir);
    if (N) {
      let W = await De(N, "utf-8");
      D = Ie(Q(W));
    }
  } catch {
  }
  let O = "";
  return D ? O = await K({
    basenameWithoutExtension: m,
    componentExportName: t,
    componentIsDefaultExport: o,
    exportedStoryName: P
  }) : O = d && s ? await oe({
    basenameWithoutExtension: m,
    componentExportName: t,
    componentIsDefaultExport: o,
    frameworkPackage: c,
    exportedStoryName: P
  }) : await te({
    basenameWithoutExtension: m,
    componentExportName: t,
    componentIsDefaultExport: o,
    exportedStoryName: P
  }), { storyFilePath: H(C(U(), l), y) && r > 1 ? C(U(), l, R) : C(U(), l, u), exportedStoryName: P, storyFileContent: O, dirname: se };
}
i(ae, "getNewStoryFile");
var M = /* @__PURE__ */ i((e) => {
  let t = /\.(ts|tsx|mts|cts)$/.test(e), o = ie(e), r = ne(e), n = o.replace(r, ""), s = t ? "tsx" : "jsx";
  return {
    storyFileName: `${n}.stories`,
    storyFileExtension: s,
    isTypescript: t
  };
}, "getStoryMetadata"), H = /* @__PURE__ */ i((e, t) => _(C(e, `${t}.ts`)) || _(C(e, `${t}.tsx`)) || _(C(e, `${t}.js`)) || _(C(e, `${t}.jsx`)), "doesStoryFileExist");

// src/core-server/server-channel/create-new-story-channel.ts
function pe(e, t, o) {
  return e.on(
    Le,
    async (r) => {
      try {
        let { storyFilePath: n, exportedStoryName: s, storyFileContent: c } = await ae(
          r.payload,
          t
        ), p = ce(process.cwd(), n), { storyId: a, kind: m } = await We({ storyFilePath: n, exportedStoryName: s }, t);
        if (je(n)) {
          e.emit(V, {
            success: !1,
            id: r.id,
            payload: {
              type: "STORY_FILE_EXISTS",
              kind: m
            },
            error: `A story file already exists at ${p}`
          }), o.disableTelemetry || z("create-new-story-file", {
            success: !1,
            error: "STORY_FILE_EXISTS"
          });
          return;
        }
        await Ae(n, c, "utf-8"), e.emit(V, {
          success: !0,
          id: r.id,
          payload: {
            storyId: a,
            storyFilePath: ce(process.cwd(), n),
            exportedStoryName: s
          },
          error: null
        }), o.disableTelemetry || z("create-new-story-file", {
          success: !0
        });
      } catch (n) {
        e.emit(V, {
          success: !1,
          id: r.id,
          error: n?.message
        }), o.disableTelemetry || await z("create-new-story-file", {
          success: !1,
          error: n
        });
      }
    }
  ), e;
}
i(pe, "initCreateNewStoryChannel");

// src/core-server/server-channel/file-search-channel.ts
import { readFile as He } from "node:fs/promises";
import { dirname as Ve, join as B } from "node:path";
import {
  extractProperRendererNameFromFramework as ze,
  getFrameworkName as Be,
  getProjectRoot as j
} from "storybook/internal/common";
import {
  FILE_COMPONENT_SEARCH_REQUEST as Ye,
  FILE_COMPONENT_SEARCH_RESPONSE as fe
} from "storybook/internal/core-events";
import { telemetry as Y } from "storybook/internal/telemetry";

// src/core-server/utils/parser/generic-parser.ts
import { parser as qe, types as x } from "storybook/internal/babel";
var I = class {
  static {
    i(this, "GenericParser");
  }
  /**
   * Parse the content of a file and return the exports
   *
   * @param content The content of the file
   * @returns The exports of the file
   */
  async parse(t) {
    let o = qe.parse(t, {
      allowImportExportEverywhere: !0,
      allowAwaitOutsideFunction: !0,
      allowNewTargetOutsideFunction: !0,
      allowReturnOutsideFunction: !0,
      allowUndeclaredExports: !0,
      plugins: [
        // Language features
        "typescript",
        "jsx",
        // Latest ECMAScript features
        "asyncGenerators",
        "bigInt",
        "classProperties",
        "classPrivateProperties",
        "classPrivateMethods",
        "classStaticBlock",
        "dynamicImport",
        "exportNamespaceFrom",
        "logicalAssignment",
        "moduleStringNames",
        "nullishCoalescingOperator",
        "numericSeparator",
        "objectRestSpread",
        "optionalCatchBinding",
        "optionalChaining",
        "privateIn",
        "regexpUnicodeSets",
        "topLevelAwait",
        // ECMAScript proposals
        "asyncDoExpressions",
        "decimal",
        "decorators",
        "decoratorAutoAccessors",
        "deferredImportEvaluation",
        "destructuringPrivate",
        "doExpressions",
        "explicitResourceManagement",
        "exportDefaultFrom",
        "functionBind",
        "functionSent",
        "importAttributes",
        "importReflection",
        "moduleBlocks",
        "partialApplication",
        "recordAndTuple",
        "sourcePhaseImports",
        "throwExpressions"
      ]
    }), r = [];
    return o.program.body.forEach(/* @__PURE__ */ i(function(s) {
      x.isExportNamedDeclaration(s) ? (x.isFunctionDeclaration(s.declaration) && x.isIdentifier(s.declaration.id) && r.push({
        name: s.declaration.id.name,
        default: !1
      }), x.isClassDeclaration(s.declaration) && x.isIdentifier(s.declaration.id) && r.push({
        name: s.declaration.id.name,
        default: !1
      }), s.declaration === null && s.specifiers.length > 0 && s.specifiers.forEach((c) => {
        x.isExportSpecifier(c) && x.isIdentifier(c.exported) && r.push({
          name: c.exported.name,
          default: !1
        });
      }), x.isVariableDeclaration(s.declaration) && s.declaration.declarations.forEach((c) => {
        x.isVariableDeclarator(c) && x.isIdentifier(c.id) && r.push({
          name: c.id.name,
          default: !1
        });
      })) : x.isExportDefaultDeclaration(s) && r.push({
        name: "default",
        default: !0
      });
    }, "traverse")), { exports: r };
  }
};

// src/core-server/utils/parser/index.ts
function me(e) {
  return new I();
}
i(me, "getParser");

// src/core-server/utils/search-files.ts
var Ue = ["js", "mjs", "cjs", "jsx", "mts", "ts", "tsx", "cts"], Me = [
  "**/node_modules/**",
  "**/*.spec.*",
  "**/*.test.*",
  "**/*.stories.*",
  "**/storybook-static/**"
];
async function le({
  searchQuery: e,
  cwd: t,
  ignoredFiles: o = Me,
  fileExtensions: r = Ue
}) {
  let { globby: n, isDynamicPattern: s } = await import("../../_node-chunks/globby-OFXSUYQS.js"), c = s(e, { cwd: t }), a = /(\.[a-z]+)$/i.test(e), m = `{${r.join(",")}}`, l = c ? e : a ? [`**/*${e}*`, `**/*${e}*/**`] : [
    `**/*${e}*.${m}`,
    `**/*${e}*/**/*.${m}`
  ];
  return (await n(l, {
    ignore: o,
    gitignore: !0,
    caseSensitiveMatch: !1,
    cwd: t,
    objectMode: !0
  })).map((d) => d.path).filter((d) => r.some((S) => d.endsWith(`.${S}`)));
}
i(le, "searchFiles");

// src/core-server/server-channel/file-search-channel.ts
async function ye(e, t, o) {
  return e.on(
    Ye,
    async (r) => {
      let n = r.id;
      try {
        if (!n)
          return;
        let s = await Be(t), c = await ze(
          s
        ), a = (await le({
          searchQuery: n,
          cwd: j()
        })).map(async (m) => {
          let l = me(c);
          try {
            let y = await He(B(j(), m), "utf-8"), { storyFileName: d } = M(B(j(), m)), S = Ve(m), u = H(B(j(), S), d), R = await l.parse(y);
            return {
              filepath: m,
              exportedComponents: R.exports,
              storyFileExists: u
            };
          } catch (y) {
            return o.disableTelemetry || Y("create-new-story-file-search", {
              success: !1,
              error: `Could not parse file: ${y}`
            }), {
              filepath: m,
              storyFileExists: !1,
              exportedComponents: null
            };
          }
        });
        o.disableTelemetry || Y("create-new-story-file-search", {
          success: !0,
          payload: {
            fileCount: a.length
          }
        }), e.emit(fe, {
          success: !0,
          id: n,
          payload: {
            files: await Promise.all(a)
          },
          error: null
        });
      } catch (s) {
        e.emit(fe, {
          success: !1,
          id: n ?? "",
          error: `An error occurred while searching for components in the project.
${s?.message}`
        }), o.disableTelemetry || Y("create-new-story-file-search", {
          success: !1,
          error: `An error occured while searching for components: ${s}`
        });
      }
    }
  ), e;
}
i(ye, "initFileSearchChannel");

// src/core-server/utils/constants.ts
var ue = [
  {
    from: T(h("storybook"), "assets/browser"),
    to: "/sb-common-assets"
  }
], de = T(h("storybook"), "assets/browser/favicon.svg");

// src/core-server/utils/save-story/save-story.ts
import { writeFile as Xe } from "node:fs/promises";
import { basename as Qe, join as Ze } from "node:path";
import { formatFileContent as Ke } from "storybook/internal/common";
import {
  SAVE_STORY_REQUEST as et,
  SAVE_STORY_RESPONSE as we,
  STORY_RENDERED as Ee
} from "storybook/internal/core-events";
import { storyNameFromExport as be, toId as tt } from "storybook/internal/csf";
import { printCsf as rt, readCsf as ot } from "storybook/internal/csf-tools";
import { logger as st } from "storybook/internal/node-logger";
import { isExampleStoryId as it, telemetry as he } from "storybook/internal/telemetry";

// src/core-server/utils/save-story/duplicate-story-with-new-name.ts
import { types as E, traverse as ge } from "storybook/internal/babel";

// src/core-server/utils/save-story/utils.ts
var g = class extends Error {
  static {
    i(this, "SaveStoryError");
  }
};

// src/core-server/utils/save-story/duplicate-story-with-new-name.ts
var xe = /* @__PURE__ */ i((e, t, o) => {
  let r = e._storyExports[t], n = E.cloneNode(r);
  if (!n)
    throw new g("cannot clone Node");
  let s = !1;
  if (ge(n, {
    Identifier(p) {
      s || p.node.name === t && (s = !0, p.node.name = o);
    },
    ObjectProperty(p) {
      let a = p.get("key");
      a.isIdentifier() && a.node.name === "args" && p.remove();
    },
    noScope: !0
  }), !(E.isCallExpression(n.init) && E.isMemberExpression(n.init.callee) && E.isIdentifier(n.init.callee.property) && n.init.callee.property.name === "story") && (E.isArrowFunctionExpression(n.init) || E.isCallExpression(n.init)))
    throw new g("Creating a new story based on a CSF2 story is not supported");
  return ge(e._ast, {
    Program(p) {
      p.pushContainer(
        "body",
        E.exportNamedDeclaration(E.variableDeclaration("const", [n]))
      );
    }
  }), n;
}, "duplicateStoryWithNewName");

// src/core-server/utils/save-story/update-args-in-csf-file.ts
import { types as f, traverse as Ge } from "storybook/internal/babel";

// src/core-server/utils/save-story/valueToAST.ts
import { parser as Je, types as w } from "storybook/internal/babel";
function A(e) {
  if (e === null)
    return w.nullLiteral();
  switch (typeof e) {
    case "function":
      return Je.parse(e.toString(), {
        allowReturnOutsideFunction: !0,
        allowSuperOutsideMethod: !0
      }).program.body[0]?.expression;
    case "number":
      return w.numericLiteral(e);
    case "string":
      return w.stringLiteral(e);
    case "boolean":
      return w.booleanLiteral(e);
    case "undefined":
      return w.identifier("undefined");
    default:
      return Array.isArray(e) ? w.arrayExpression(e.map(A)) : w.objectExpression(
        Object.keys(e).filter((o) => typeof e[o] < "u").map((o) => {
          let r = e[o];
          return w.objectProperty(w.stringLiteral(o), A(r));
        })
      );
  }
}
i(A, "valueToAST");

// src/core-server/utils/save-story/update-args-in-csf-file.ts
var Se = /* @__PURE__ */ i(async (e, t) => {
  let o = !1, r = Object.fromEntries(
    Object.entries(t).map(([s, c]) => [s, A(c)])
  );
  if (!(f.isCallExpression(e) && f.isMemberExpression(e.callee) && f.isIdentifier(e.callee.property) && e.callee.property.name === "story") && (f.isArrowFunctionExpression(e) || f.isCallExpression(e)))
    throw new g("Updating a CSF2 story is not supported");
  if (f.isObjectExpression(e)) {
    let s = e.properties, c = s.find((p) => {
      if (f.isObjectProperty(p)) {
        let a = p.key;
        return f.isIdentifier(a) && a.name === "args";
      }
      return !1;
    });
    if (c) {
      if (f.isObjectProperty(c)) {
        let p = c.value;
        if (f.isObjectExpression(p)) {
          p.properties.forEach((m) => {
            if (f.isObjectProperty(m)) {
              let l = m.key;
              f.isIdentifier(l) && l.name in r && (m.value = r[l.name], delete r[l.name]);
            }
          });
          let a = Object.entries(r);
          Object.keys(r).length && a.forEach(([m, l]) => {
            p.properties.push(f.objectProperty(f.identifier(m), l));
          });
        }
      }
    } else
      s.unshift(
        f.objectProperty(
          f.identifier("args"),
          f.objectExpression(
            Object.entries(r).map(([p, a]) => f.objectProperty(f.identifier(p), a))
          )
        )
      );
    return;
  }
  Ge(e, {
    ObjectExpression(s) {
      if (o)
        return;
      o = !0;
      let p = s.get("properties").find((a) => {
        if (a.isObjectProperty()) {
          let m = a.get("key");
          return m.isIdentifier() && m.node.name === "args";
        }
        return !1;
      });
      if (p) {
        if (p.isObjectProperty()) {
          let a = p.get("value");
          if (a.isObjectExpression()) {
            a.traverse({
              ObjectProperty(l) {
                let y = l.get("key");
                y.isIdentifier() && y.node.name in r && (l.get("value").replaceWith(r[y.node.name]), delete r[y.node.name]);
              },
              noScope: !0
            });
            let m = Object.entries(r);
            Object.keys(r).length && m.forEach(([l, y]) => {
              a.pushContainer("properties", f.objectProperty(f.identifier(l), y));
            });
          }
        }
      } else
        s.unshiftContainer(
          "properties",
          f.objectProperty(
            f.identifier("args"),
            f.objectExpression(
              Object.entries(r).map(([a, m]) => f.objectProperty(f.identifier(a), m))
            )
          )
        );
    },
    noScope: !0
  });
}, "updateArgsInCsfFile");

// src/core-server/utils/save-story/save-story.ts
var nt = /* @__PURE__ */ i((e) => JSON.parse(e, (t, o) => o === "__sb_empty_function_arg__" ? () => {
} : o), "parseArgs"), at = /* @__PURE__ */ i((e, t) => {
  let o = "([\\s\\S])", r = "(\\r\\n|\\r|\\n)", n = r + "};" + r, s = new RegExp(
    // Looks for an export by the given name, considers the first closing brace on its own line
    // to be the end of the story definition.
    `^(?<before>${o}*)(?<story>export const ${t} =${o}+?${n})(?<after>${o}*)$`
  ), { before: c, story: p, after: a } = e.match(s)?.groups || {};
  return p ? c + p.replaceAll(/(\r\n|\r|\n)(\r\n|\r|\n)([ \t]*[a-z0-9_]+): /gi, "$2$3:") + a : e;
}, "removeExtraNewlines");
function Ce(e, t, o) {
  e.on(et, async ({ id: r, payload: n }) => {
    let { csfId: s, importPath: c, args: p, name: a } = n, m, l, y, d, S;
    try {
      y = Qe(c), d = Ze(process.cwd(), c);
      let u = await ot(d, {
        makeTitle: /* @__PURE__ */ i((v) => v || "myTitle", "makeTitle")
      }), R = u.parse(), P = Object.entries(R._stories), [D, O] = s.split("--");
      l = a && be(a), m = l && tt(D, l);
      let [b] = P.find(([v, Te]) => Te.id.endsWith(`--${O}`)) || [];
      if (!b)
        throw new g("Source story not found.");
      if (a && u.getStoryExport(a))
        throw new g("Story already exists.");
      S = be(b), await Se(
        a ? xe(R, b, a) : u.getStoryExport(b),
        p ? nt(p) : {}
      );
      let N = await Ke(
        d,
        at(rt(u).code, a || b)
      );
      await Promise.all([
        new Promise((v) => {
          e.on(Ee, v), setTimeout(() => v(e.off(Ee, v)), 3e3);
        }),
        Xe(d, N)
      ]), e.emit(we, {
        id: r,
        success: !0,
        payload: {
          csfId: s,
          newStoryId: m,
          newStoryName: l,
          newStoryExportName: a,
          sourceFileContent: N,
          sourceFileName: y,
          sourceStoryName: S,
          sourceStoryExportName: b
        },
        error: null
      });
      let W = it(m ?? s);
      !o.disableTelemetry && !W && await he("save-story", {
        action: a ? "createStory" : "updateStory",
        success: !0
      });
    } catch (u) {
      e.emit(we, {
        id: r,
        success: !1,
        error: u instanceof g ? u.message : "Unknown error"
      }), st.error(
        `Error writing to ${d}:
${u.stack || u.message || u.toString()}`
      ), !o.disableTelemetry && !(u instanceof g) && await he("save-story", {
        action: a ? "createStory" : "updateStory",
        success: !1,
        error: u
      });
    }
  });
}
i(Ce, "initializeSaveStory");

// src/core-server/utils/whats-new.ts
import { writeFile as ct } from "node:fs/promises";
import { findConfigFile as pt, loadMainConfig as mt } from "storybook/internal/common";
import {
  REQUEST_WHATS_NEW_DATA as lt,
  RESULT_WHATS_NEW_DATA as Re,
  SET_WHATS_NEW_CACHE as ft,
  TELEMETRY_ERROR as yt,
  TOGGLE_WHATS_NEW_NOTIFICATIONS as ut
} from "storybook/internal/core-events";
import { printConfig as dt, readConfig as gt } from "storybook/internal/csf-tools";
import { logger as Pe } from "storybook/internal/node-logger";
import { telemetry as xt } from "storybook/internal/telemetry";
var J = "whats-new-cache", St = "https://storybook.js.org/whats-new/v1";
function Ne(e, t, o) {
  e.on(ft, async (r) => {
    let n = await t.cache.get(J).catch((s) => (Pe.verbose(s), {}));
    await t.cache.set(J, { ...n, ...r });
  }), e.on(lt, async () => {
    try {
      let r = await fetch(St).then(async (a) => {
        if (a.ok)
          return a.json();
        throw a;
      }), s = (await mt({ configDir: t.configDir })).core?.disableWhatsNewNotifications === !0, c = await t.cache.get(J) ?? {}, p = {
        ...r,
        status: "SUCCESS",
        postIsRead: r.url === c.lastReadPost,
        showNotification: r.url !== c.lastDismissedPost && r.url !== c.lastReadPost,
        disableWhatsNewNotifications: s
      };
      e.emit(Re, { data: p });
    } catch (r) {
      Pe.verbose(r instanceof Error ? r.message : String(r)), e.emit(Re, {
        data: { status: "ERROR" }
      });
    }
  }), e.on(
    ut,
    async ({ disableWhatsNewNotifications: r }) => {
      let n = o.disableTelemetry !== !0;
      try {
        let s = pt("main", t.configDir);
        L(s, `unable to find Storybook main file in ${t.configDir}`);
        let c = await gt(s);
        if (!c._exportsObject)
          throw new Error(
            "Unable to parse Storybook main file while trying to read 'core' property"
          );
        c.setFieldValue(["core", "disableWhatsNewNotifications"], r), await ct(s, dt(c).code), n && await xt("core-config", { disableWhatsNewNotifications: r });
      } catch (s) {
        L(s instanceof Error), n && await q(s, "core-config", {
          cliOptions: t,
          presetOptions: { ...t, corePresets: [], overridePresets: [] },
          skipPrompt: !0
        });
      }
    }
  ), e.on(yt, async (r) => {
    o.disableTelemetry !== !0 && await q(r, "browser", {
      cliOptions: t,
      presetOptions: { ...t, corePresets: [], overridePresets: [] },
      skipPrompt: !0
    });
  });
}
i(Ne, "initializeWhatsNew");

// src/core-server/presets/common-preset.ts
var Ot = /* @__PURE__ */ i((e, t = {}) => Object.entries(t).reduce((o, [r, n]) => o.replace(new RegExp(`%${r}%`, "g"), n), e), "interpolate"), Oo = /* @__PURE__ */ i(async (e = []) => [
  ...ue,
  ...e
], "staticDirs"), To = /* @__PURE__ */ i(async (e, t) => {
  if (e)
    return e;
  let o = await t.presets.apply("staticDirs"), n = (o ? o.map((s) => typeof s == "string" ? s : `${s.from}:${s.to}`) : []).map((s) => {
    let c = [], p = o && !Et(s) ? ht({
      configDir: t.configDir,
      workingDir: process.cwd(),
      directory: s
    }) : s, { staticPath: a, targetEndpoint: m } = X(p);
    return ["/favicon.svg", "/favicon.ico"].includes(m) && c.push(a), m === "/" && (c.push(G(a, "favicon.svg")), c.push(G(a, "favicon.ico"))), c.filter((l) => Fe(l));
  }).reduce((s, c) => s.concat(c), []);
  return n.length > 1 && vt.warn(Oe.dedent`
      Looks like multiple favicons were detected. Using the first one.

      ${n.join(", ")}
    `), n[0] || de;
}, "favicon"), Do = /* @__PURE__ */ i(async (e, t) => {
  let { presets: o } = t, r = await o.apply("babelDefault", {}, t) ?? {};
  return {
    ...r,
    // This override makes sure that we will never transpile babel further down then the browsers that storybook supports.
    // This is needed to support the mount property of the context described here:
    // https://storybook.js.org/docs/writing-tests/interaction-testing#run-code-before-each-test
    overrides: [
      ...r?.overrides ?? [],
      {
        include: /\.(story|stories)\.[cm]?[jt]sx?$/,
        presets: [
          [
            "@babel/preset-env",
            {
              bugfixes: !0,
              targets: {
                // This is the same browser supports that we use to bundle our manager and preview code.
                chrome: 100,
                safari: 15,
                firefox: 91
              }
            }
          ]
        ]
      }
    ]
  };
}, "babel"), ko = /* @__PURE__ */ i((e, t) => e || t.packageJson?.name || !1, "title"), $o = /* @__PURE__ */ i((e, t) => e || t.loglevel || "info", "logLevel"), _o = /* @__PURE__ */ i(async (e, { configDir: t, presets: o }) => {
  let r = await o.apply("env");
  return Rt(t, r);
}, "previewHead"), Io = /* @__PURE__ */ i(async () => Pt({ production: !0 }).raw, "env"), jo = /* @__PURE__ */ i(async (e, { configDir: t, presets: o }) => {
  let r = await o.apply("env");
  return Ct(t, r);
}, "previewBody"), Ao = /* @__PURE__ */ i(() => ({
  check: !1,
  // 'react-docgen' faster than `react-docgen-typescript` but produces lower quality results
  reactDocgen: "react-docgen",
  reactDocgenTypescriptOptions: {
    shouldExtractLiteralValuesFromEnum: !0,
    shouldRemoveUndefinedFromOptional: !0,
    propFilter: /* @__PURE__ */ i((e) => e.parent ? !/node_modules/.test(e.parent.fileName) : !0, "propFilter"),
    // NOTE: this default cannot be changed
    savePropValueAsString: !0
  }
}), "typescript"), Tt = /* @__PURE__ */ i((e) => {
  if (e !== void 0) {
    if (e.toUpperCase() === "FALSE")
      return !1;
    if (e.toUpperCase() === "TRUE" || typeof e == "string")
      return !0;
  }
}, "optionalEnvToBoolean"), Wo = /* @__PURE__ */ i((e, t) => {
  let o = ve, r = bt.getPackageManager({
    configDir: t.configDir
  });
  return t.disableTelemetry || (o = /* @__PURE__ */ i(async (n, s) => (await Ft("remove", { addon: n, source: "api" }), ve(n, { ...s, packageManager: r })), "removeAddon")), { ...e, removeAddon: o };
}, "experimental_serverAPI"), Lo = /* @__PURE__ */ i(async (e, t) => ({
  ...e,
  disableTelemetry: t.disableTelemetry === !0,
  enableCrashReports: t.enableCrashReports || Tt(process.env.STORYBOOK_ENABLE_CRASH_REPORTS)
}), "core"), qo = /* @__PURE__ */ i(async (e) => ({
  ...e,
  argTypeTargetsV7: !0,
  legacyDecoratorFileOrder: !1,
  disallowImplicitActionsInRenderV8: !0,
  viewport: !0,
  highlight: !0,
  controls: !0,
  interactions: !0,
  actions: !0,
  backgrounds: !0,
  outline: !0,
  measure: !0
}), "features"), Dt = {
  test: /(stories|story)\.(m?js|ts)x?$/,
  createIndex: /* @__PURE__ */ i(async (e, t) => (await Nt(e, t)).parse().indexInputs, "createIndex")
}, Uo = /* @__PURE__ */ i((e) => [Dt].concat(e || []), "experimental_indexers"), Mo = /* @__PURE__ */ i(async (e, t) => {
  let o = await t.presets.apply("framework");
  return typeof o == "string" ? {} : typeof o > "u" ? null : o.options;
}, "frameworkOptions"), Ho = /* @__PURE__ */ i(async (e, t) => {
  let o = G(t.configDir, "manager-head.html");
  if (Fe(o)) {
    let r = wt(o, { encoding: "utf8" }), n = t.presets.apply("env");
    return Ot(await r, await n);
  }
  return "";
}, "managerHead"), Vo = /* @__PURE__ */ i(async (e, t) => {
  let o = await t.presets.apply("core");
  return Ne(e, t, o), Ce(e, t, o), ye(e, t, o), pe(e, t, o), e;
}, "experimental_serverChannel"), zo = /* @__PURE__ */ i(async (e) => {
  try {
    return {
      ...e,
      react: h("react"),
      reactDom: h("react-dom")
    };
  } catch {
    return e;
  }
}, "resolvedReact"), Bo = /* @__PURE__ */ i(async (e) => ({
  ...e,
  "dev-only": { excludeFromDocsStories: !0 },
  "docs-only": { excludeFromSidebar: !0 },
  "test-only": { excludeFromSidebar: !0, excludeFromDocsStories: !0 }
}), "tags"), Yo = /* @__PURE__ */ i(async (e) => [
  T(h("storybook"), "dist/core-server/presets/common-manager.js"),
  ...e || []
], "managerEntries");
export {
  Do as babel,
  Lo as core,
  Dt as csfIndexer,
  Io as env,
  Uo as experimental_indexers,
  Wo as experimental_serverAPI,
  Vo as experimental_serverChannel,
  To as favicon,
  qo as features,
  Mo as frameworkOptions,
  $o as logLevel,
  Yo as managerEntries,
  Ho as managerHead,
  jo as previewBody,
  _o as previewHead,
  zo as resolvedReact,
  Oo as staticDirs,
  Bo as tags,
  ko as title,
  Ao as typescript
};
