import CJS_COMPAT_NODE_URL_2pwcsqiof3u from 'node:url';
import CJS_COMPAT_NODE_PATH_2pwcsqiof3u from 'node:path';
import CJS_COMPAT_NODE_MODULE_2pwcsqiof3u from "node:module";

var __filename = CJS_COMPAT_NODE_URL_2pwcsqiof3u.fileURLToPath(import.meta.url);
var __dirname = CJS_COMPAT_NODE_PATH_2pwcsqiof3u.dirname(__filename);
var require = CJS_COMPAT_NODE_MODULE_2pwcsqiof3u.createRequire(import.meta.url);

// ------------------------------------------------------------
// end of CJS compatibility banner, injected by Storybook's esbuild configuration
// ------------------------------------------------------------
import {
  require_build
} from "./chunk-OW2CVULD.js";
import {
  StorybookError
} from "./chunk-MBETX7JF.js";
import {
  up
} from "./chunk-BNCI7WUG.js";
import {
  resolvePackageDir
} from "./chunk-S2YTODOS.js";
import {
  relative
} from "./chunk-5T6DBXTM.js";
import {
  loadConfig,
  printConfig
} from "./chunk-EOEHGEPZ.js";
import {
  require_dist
} from "./chunk-PSC66KMF.js";
import {
  require_picocolors
} from "./chunk-SBH7AZWY.js";
import {
  __toESM
} from "./chunk-MN2VDHJD.js";

// src/core-server/utils/server-statics.ts
import { existsSync, statSync } from "node:fs";
import { readFile, stat } from "node:fs/promises";
import { basename, isAbsolute, join, posix, resolve, sep, win32 } from "node:path";
import {
  getDirectoryFromWorkingDir,
  getProjectRoot,
  resolvePathInStorybookCache
} from "storybook/internal/common";
import { CLI_COLORS, logger, once } from "storybook/internal/node-logger";
var import_picocolors = __toESM(require_picocolors(), 1), import_sirv = __toESM(require_build(), 1), import_ts_dedent = __toESM(require_dist(), 1);
var cacheDir = resolvePathInStorybookCache("", "ignored-sub").split("ignored-sub")[0], files = /* @__PURE__ */ new Map(), readFileOnce = async (path) => {
  if (files.has(path))
    return files.get(path);
  {
    let [data, stats] = await Promise.all([readFile(path, "utf-8"), stat(path)]), result = { data, mtime: stats.mtimeMs };
    return files.set(path, result), result;
  }
}, faviconWrapperPath = join(
  resolvePackageDir("storybook"),
  "/assets/browser/favicon-wrapper.svg"
), prepareNestedSvg = (svg) => {
  let [, openingTag, contents, closingTag] = svg?.match(/(<svg[^>]*>)(.*?)(<\/svg>)/s) ?? [];
  if (!openingTag || !contents || !closingTag)
    return svg;
  let width, height, modifiedTag = openingTag.replace(/width=["']([^"']*)["']/g, (_, value) => (width = parseFloat(value), 'width="32px"')).replace(/height=["']([^"']*)["']/g, (_, value) => (height = parseFloat(value), 'height="32px"'));
  return !/viewBox=["'][^"']*["']/.test(modifiedTag) && width && height && (modifiedTag = modifiedTag.replace(/>$/, ` viewBox="0 0 ${width} ${height}">`)), modifiedTag = modifiedTag.replace(/preserveAspectRatio=["'][^"']*["']/g, "").replace(/>$/, ' preserveAspectRatio="xMidYMid meet">'), modifiedTag + contents + closingTag;
};
async function useStatics(app, options) {
  let staticDirs = await options.presets.apply("staticDirs") ?? [], faviconPath = await options.presets.apply("favicon"), faviconDir = resolve(faviconPath, ".."), faviconFile = basename(faviconPath);
  app.use(`/${faviconFile}`, async (req, res, next) => {
    let status = req.query.status;
    if (status && faviconFile.endsWith(".svg") && ["active", "critical", "negative", "positive", "warning"].includes(status)) {
      let [faviconInfo, faviconWrapperInfo] = await Promise.all([
        readFileOnce(join(faviconDir, faviconFile)),
        readFileOnce(faviconWrapperPath)
      ]).catch((e) => (e instanceof Error && once.warn(`Failed to read favicon: ${e.message}`), [null, null]));
      if (faviconInfo && faviconWrapperInfo) {
        let svg = faviconWrapperInfo.data.replace('<g id="mask"', `<g mask="url(#${status}-mask)"`).replace('<use id="status"', `<use href="#${status}"`).replace('<use id="icon" />', prepareNestedSvg(faviconInfo.data));
        res.setHeader("Content-Type", "image/svg+xml"), res.setHeader("ETag", `"${faviconWrapperInfo.mtime}-${faviconInfo.mtime}"`), res.end(svg);
        return;
      }
    }
    return req.url = `/${faviconFile}`, sirvWorkaround(faviconDir)(req, res, next);
  }), staticDirs.map((dir) => {
    try {
      let { staticDir, staticPath, targetEndpoint } = mapStaticDir(dir, options.configDir);
      if (!targetEndpoint.startsWith("/sb-") && !staticDir.startsWith(cacheDir)) {
        let relativeStaticDir = relative(getProjectRoot(), staticDir);
        logger.debug(
          `Serving static files from ${CLI_COLORS.info(relativeStaticDir)} at ${CLI_COLORS.info(targetEndpoint)}`
        );
      }
      if (existsSync(staticPath) && statSync(staticPath).isFile()) {
        let staticPathDir = resolve(staticPath, ".."), staticPathFile = basename(staticPath);
        app.use(targetEndpoint, (req, res, next) => {
          req.url = `/${staticPathFile}`, sirvWorkaround(staticPathDir)(req, res, next);
        });
      } else
        app.use(targetEndpoint, sirvWorkaround(staticPath));
    } catch (e) {
      e instanceof Error && logger.warn(e.message);
    }
  });
}
var sirvWorkaround = (dir, opts = {}) => (req, res, next) => {
  let originalParsedUrl = req._parsedUrl, maybeNext = next ? () => {
    req._parsedUrl = originalParsedUrl, next();
  } : void 0;
  (0, import_sirv.default)(dir, { dev: !0, etag: !0, extensions: [], ...opts })(req, res, maybeNext);
}, parseStaticDir = (arg) => {
  let lastColonIndex = arg.lastIndexOf(":"), isWindowsRawDirOnly = win32.isAbsolute(arg) && lastColonIndex === 1, splitIndex = lastColonIndex !== -1 && !isWindowsRawDirOnly ? lastColonIndex : arg.length, [from, to] = [arg.slice(0, splitIndex), arg.slice(splitIndex + 1)], staticDir = isAbsolute(from) ? from : `./${from}`, staticPath = resolve(staticDir);
  if (!existsSync(staticPath))
    throw new Error(
      import_ts_dedent.dedent`
        Failed to load static files, no such directory: ${import_picocolors.default.cyan(staticPath)}
        Make sure this directory exists.
      `
    );
  let targetDir = (to || (statSync(staticPath).isFile() ? basename(staticPath) : "/")).split(sep).join(posix.sep).replace(/^\/?/, "./"), targetEndpoint = targetDir.substring(1);
  return { staticDir, staticPath, targetDir, targetEndpoint };
}, mapStaticDir = (staticDir, configDir) => {
  let specifier = typeof staticDir == "string" ? staticDir : `${staticDir.from}:${staticDir.to}`, normalizedDir = isAbsolute(specifier) ? specifier : getDirectoryFromWorkingDir({ configDir, workingDir: process.cwd(), directory: specifier });
  return parseStaticDir(normalizedDir);
};

// src/core-server/withTelemetry.ts
import { HandledError, cache, isCI, loadAllPresets } from "storybook/internal/common";
import { logger as logger2, prompt } from "storybook/internal/node-logger";
import {
  ErrorCollector,
  getPrecedingUpgrade,
  oneWayHash,
  telemetry
} from "storybook/internal/telemetry";
var promptCrashReports = async () => {
  if (isCI() || !process.stdout.isTTY)
    return;
  let enableCrashReports = await prompt.confirm({
    message: "Would you like to send anonymous crash reports to improve Storybook and fix bugs faster?",
    initialValue: !0
  });
  return await cache.set("enableCrashReports", enableCrashReports), enableCrashReports;
};
async function getErrorLevel({
  cliOptions,
  presetOptions,
  skipPrompt
}) {
  if (cliOptions.disableTelemetry)
    return "none";
  if (!presetOptions)
    return "error";
  let core = await (await loadAllPresets(presetOptions)).apply("core");
  if (core?.enableCrashReports !== void 0)
    return core.enableCrashReports ? "full" : "error";
  if (core?.disableTelemetry)
    return "none";
  let valueFromCache = await cache.get("enableCrashReports") ?? await cache.get("enableCrashreports");
  if (valueFromCache !== void 0)
    return valueFromCache ? "full" : "error";
  if (skipPrompt)
    return "error";
  let valueFromPrompt = await promptCrashReports();
  return valueFromPrompt !== void 0 ? valueFromPrompt ? "full" : "error" : "full";
}
async function sendTelemetryError(_error, eventType, options, blocking = !0, parent) {
  try {
    let errorLevel = "error";
    try {
      errorLevel = await getErrorLevel(options);
    } catch {
    }
    if (errorLevel !== "none") {
      let precedingUpgrade = await getPrecedingUpgrade(), error = _error, errorHash;
      "message" in error ? errorHash = error.message ? oneWayHash(error.message) : "EMPTY_MESSAGE" : errorHash = "NO_MESSAGE";
      let { code, name, category } = error;
      if (await telemetry(
        "error",
        {
          code,
          name,
          category,
          eventType,
          blocking,
          precedingUpgrade,
          error: errorLevel === "full" ? error : void 0,
          errorHash,
          // if we ever end up sending a non-error instance, we'd like to know
          isErrorInstance: error instanceof Error,
          // Include parent error information if this is a sub-error
          ...parent ? { parent: parent.fullErrorCode } : {}
        },
        {
          immediate: !0,
          configDir: options.cliOptions.configDir || options.presetOptions?.configDir,
          enableCrashReports: errorLevel === "full"
        }
      ), error && "subErrors" in error && error.subErrors.length > 0)
        for (let subError of error.subErrors)
          await sendTelemetryError(subError, eventType, options, blocking, error);
    }
  } catch {
  }
}
function isTelemetryEnabled(options) {
  return !(options.cliOptions.disableTelemetry || options.cliOptions.test === !0);
}
async function withTelemetry(eventType, options, run) {
  let enableTelemetry = isTelemetryEnabled(options), canceled = !1;
  async function cancelTelemetry() {
    canceled = !0, enableTelemetry && await telemetry("canceled", { eventType }, { stripMetadata: !0, immediate: !0 }), process.exit(0);
  }
  eventType === "init" && process.on("SIGINT", cancelTelemetry), enableTelemetry && telemetry("boot", { eventType }, { stripMetadata: !0 });
  try {
    return await run();
  } catch (error) {
    if (canceled)
      return;
    if (!(error instanceof HandledError || error instanceof StorybookError && error.isHandledError)) {
      let { printError = logger2.error } = options;
      printError(error);
    }
    throw enableTelemetry && await sendTelemetryError(error, eventType, options), error;
  } finally {
    if (enableTelemetry) {
      let errors = ErrorCollector.getErrors();
      for (let error of errors)
        await sendTelemetryError(error, eventType, options, !1);
      process.off("SIGINT", cancelTelemetry);
    }
  }
}

// src/core-server/utils/generate-story.ts
import { existsSync as existsSync3 } from "node:fs";
import { writeFile } from "node:fs/promises";
import { relative as relative3 } from "node:path";
import { getStoryId } from "storybook/internal/common";

// src/core-server/utils/get-new-story-file.ts
import { existsSync as existsSync2 } from "node:fs";
import { readFile as readFile2 } from "node:fs/promises";
import { basename as basename2, dirname as dirname2, extname, join as join2, relative as relative2 } from "node:path";
import { types as t, traverse } from "storybook/internal/babel";
import {
  extractFrameworkPackageName,
  findConfigFile,
  formatFileContent,
  getFrameworkName,
  getProjectRoot as getProjectRoot2
} from "storybook/internal/common";
import { isCsfFactoryPreview } from "storybook/internal/csf-tools";
import { logger as logger3 } from "storybook/internal/node-logger";

// src/core-server/utils/get-dummy-props-for-args.ts
var STORYBOOK_FN_PLACEHOLDER = "[[STORYBOOK_FN_PLACEHOLDER]]";
function generateDummyPropsFromArgTypes(argTypes) {
  let required = {}, optional = {};
  for (let [propName, argType] of Object.entries(argTypes)) {
    let isRequired = argType.type && typeof argType.type == "object" && argType.type.required, dummyValue;
    if (typeof argType.type == "string") {
      let sbType = { name: argType.type };
      dummyValue = generateDummyValueFromSBType(sbType, propName);
    } else argType.type && typeof argType.type == "object" ? dummyValue = generateDummyValueFromSBType(argType.type, propName) : dummyValue = void 0;
    isRequired ? required[propName] = dummyValue : optional[propName] = dummyValue;
  }
  return { required, optional };
}
function tokenize(name) {
  return name ? name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_\-]+/g, " ").split(" ").map((t2) => t2.toLowerCase()).filter(Boolean) : [];
}
function hasAny(tokens, set) {
  return tokens.some((t2) => set.has(t2));
}
var URL_TOKENS = /* @__PURE__ */ new Set(["url", "href", "link"]), IMAGE_TOKENS = /* @__PURE__ */ new Set(["image", "img", "photo", "avatar", "logo"]), EMAIL_TOKENS = /* @__PURE__ */ new Set(["email", "e-mail", "mail"]), PHONE_TOKENS = /* @__PURE__ */ new Set(["phone", "tel", "telephone", "mobile", "cell"]), COLOR_TOKENS = /* @__PURE__ */ new Set(["color", "background", "bg"]), DATE_TOKENS = /* @__PURE__ */ new Set(["date", "at", "time", "timestamp"]), NEGATIVE_IMAGE_TOKENS = /* @__PURE__ */ new Set([
  "size",
  "width",
  "height",
  "ratio",
  "count",
  "status",
  "loading",
  "config",
  "options",
  "variant"
]);
function getMostLikelyTypeFromTokens(tokens) {
  let score = {};
  for (let token of tokens)
    IMAGE_TOKENS.has(token) && (score.image = (score.image ?? 0) + 3), URL_TOKENS.has(token) && (score.url = (score.url ?? 0) + 2), EMAIL_TOKENS.has(token) && (score.email = (score.email ?? 0) + 3), PHONE_TOKENS.has(token) && (score.phone = (score.phone ?? 0) + 3);
  hasAny(tokens, NEGATIVE_IMAGE_TOKENS) && (score.image = (score.image ?? 0) - 4);
  let best = null, bestScore = 0;
  for (let [kind, value] of Object.entries(score))
    value > bestScore && (bestScore = value, best = kind);
  return best;
}
function normalizeStringLiteral(value) {
  return typeof value != "string" ? value : value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'") ? value.slice(1, -1) : value;
}
function generateDummyValueFromSBType(sbType, propName) {
  switch (sbType.name) {
    case "boolean":
      return !0;
    case "number":
      return 42;
    case "string": {
      let name = propName ?? "", tokens = tokenize(name);
      if (hasAny(tokens, COLOR_TOKENS))
        return "#ff0000";
      if (hasAny(tokens, DATE_TOKENS))
        return "2025-01-01";
      switch (getMostLikelyTypeFromTokens(tokens)) {
        case "image":
          return "https://placehold.co/600x400?text=Storybook";
        case "url":
          return "https://example.com";
        case "email":
          return "storybook@example.com";
        case "phone":
          return "1234567890";
        default:
          return name ?? "Hello world";
      }
    }
    case "date":
      return /* @__PURE__ */ new Date("2025-01-01");
    case "node":
      return propName ?? "Hello world";
    case "function":
      return STORYBOOK_FN_PLACEHOLDER;
    case "literal":
      return normalizeStringLiteral(sbType.value);
    case "object": {
      let result = {};
      for (let [key, valueType] of Object.entries(sbType.value))
        result[key] = generateDummyValueFromSBType(valueType, key);
      return result;
    }
    case "union": {
      if (!sbType.value?.length)
        return "";
      let literalType = sbType.value.find((t2) => t2.name === "literal");
      return literalType?.name === "literal" ? normalizeStringLiteral(literalType.value) : generateDummyValueFromSBType(sbType.value[0], propName);
    }
    case "array":
      return sbType.value.name === "other" ? [] : [generateDummyValueFromSBType(sbType.value, propName)];
    case "tuple":
      return sbType.value.map((el) => generateDummyValueFromSBType(el));
    case "enum":
      return sbType.value[0] ?? propName;
    case "intersection": {
      let objectTypes = sbType.value.filter((t2) => t2.name === "object");
      if (objectTypes.length > 0) {
        let result = {};
        return objectTypes.forEach((objType) => {
          objType.name === "object" && Object.entries(objType.value).forEach(([key, type]) => {
            result[key] = generateDummyValueFromSBType(type, key);
          });
        }), result;
      }
      return {};
    }
    case "other": {
      let value = sbType.value;
      return value?.startsWith("React") || value?.includes("Event") || value?.includes("Element") ? STORYBOOK_FN_PLACEHOLDER : value === "null" ? null : value === "void" || value === "undefined" ? void 0 : value ?? propName;
    }
  }
}

// src/core-server/utils/new-story-templates/csf-factory-template.ts
var import_ts_dedent2 = __toESM(require_dist(), 1);

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

// src/core-server/utils/new-story-templates/csf-factory-template.ts
async function getCsfFactoryTemplateForNewStoryFile(data) {
  let importName = data.componentIsDefaultExport ? await getComponentVariableName(data.basenameWithoutExtension) : data.componentExportName, importStatement = data.componentIsDefaultExport ? `import ${importName} from './${data.basenameWithoutExtension}';` : `import { ${importName} } from './${data.basenameWithoutExtension}';`, previewImport = data.previewImportPath ? `import preview from '${data.previewImportPath}';` : "import preview from '#.storybook/preview';", argsString = data.args && Object.keys(data.args).length > 0 ? `{ args: ${JSON.stringify(data.args, null, 2)} }` : "{}", tagsString = data.tags && Array.isArray(data.tags) && data.tags.length > 0 ? `tags: ${JSON.stringify(data.tags)},` : "";
  return import_ts_dedent2.dedent`
  ${previewImport}

  ${importStatement}

  const meta = preview.meta({
    component: ${importName},
    ${tagsString}
  });

  export const ${data.exportedStoryName} = meta.story(${argsString});
  `;
}

// src/core-server/utils/new-story-templates/javascript.ts
var import_ts_dedent3 = __toESM(require_dist(), 1);
async function getJavaScriptTemplateForNewStoryFile(data) {
  let importName = data.componentIsDefaultExport ? await getComponentVariableName(data.basenameWithoutExtension) : data.componentExportName, importStatement = data.componentIsDefaultExport ? `import ${importName} from './${data.basenameWithoutExtension}';` : `import { ${importName} } from './${data.basenameWithoutExtension}';`, hasArgs = !!(data.args && Object.keys(data.args).length > 0), argsString = hasArgs ? `args: ${JSON.stringify(data.args, null, 2)},` : "", tagsString = data.tags && Array.isArray(data.tags) && data.tags.length > 0 ? `tags: ${JSON.stringify(data.tags)},` : "", storyExport = hasArgs ? import_ts_dedent3.dedent`
      export const ${data.exportedStoryName} = {
        ${argsString}
      };
      ` : `export const ${data.exportedStoryName} = {};`;
  return import_ts_dedent3.dedent`
  ${importStatement}

  const meta = {
    component: ${importName},
    ${tagsString}
  };

  export default meta;

  ${storyExport}
  `;
}

// src/core-server/utils/new-story-templates/typescript.ts
var import_ts_dedent4 = __toESM(require_dist(), 1);
async function getTypeScriptTemplateForNewStoryFile(data) {
  let importName = data.componentIsDefaultExport ? await getComponentVariableName(data.basenameWithoutExtension) : data.componentExportName, importStatement = data.componentIsDefaultExport ? `import ${importName} from './${data.basenameWithoutExtension}'` : `import { ${importName} } from './${data.basenameWithoutExtension}'`, hasArgs = !!(data.args && Object.keys(data.args).length > 0), argsString = hasArgs ? `args: ${JSON.stringify(data.args, null, 2)},` : "", storyExport = hasArgs ? import_ts_dedent4.dedent`
      export const ${data.exportedStoryName}: Story = {
        ${argsString}
      };
      ` : `export const ${data.exportedStoryName}: Story = {};`, tagsString = data.tags && Array.isArray(data.tags) && data.tags.length > 0 ? `tags: ${JSON.stringify(data.tags)},` : "";
  return import_ts_dedent4.dedent`
  import type { Meta, StoryObj } from '${data.frameworkPackage}';

  ${importStatement};

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

  export default meta;

  type Story = StoryObj<typeof meta>;

  ${storyExport}
  `;
}

// src/core-server/utils/get-new-story-file.ts
async function getNewStoryFile({
  componentFilePath,
  componentExportName,
  componentIsDefaultExport,
  componentExportCount,
  tags
}, options) {
  let frameworkPackageName = await getFrameworkName(options), sanitizedFrameworkPackageName = extractFrameworkPackageName(frameworkPackageName), base = basename2(componentFilePath), extension = extname(componentFilePath), basenameWithoutExtension = base.replace(extension, ""), dir = dirname2(componentFilePath), projectRoot = getProjectRoot2(), relativeDir = dir.startsWith(projectRoot) ? relative2(projectRoot, dir) : dir, { storyFileName, isTypescript, storyFileExtension } = getStoryMetadata(componentFilePath), storyFileNameWithExtension = `${storyFileName}.${storyFileExtension}`, alternativeStoryFileNameWithExtension = `${basenameWithoutExtension}.${componentExportName}.stories.${storyFileExtension}`, exportedStoryName = "Default", useCsfFactory = !1, previewConfigPath;
  try {
    let previewConfig = findConfigFile("preview", options.configDir);
    if (previewConfig) {
      let previewContent = await readFile2(previewConfig, "utf-8");
      useCsfFactory = isCsfFactoryPreview(loadConfig(previewContent)), previewConfigPath = previewConfig;
    }
  } catch {
  }
  let args;
  try {
    let argTypes = await options.presets.apply("experimental_getArgTypesData", null, {
      ...options,
      componentFilePath,
      componentExportName
    });
    if (logger3.debug(`Extracted argTypes for ${componentExportName}: ${JSON.stringify(argTypes)}`), argTypes) {
      let { required } = generateDummyPropsFromArgTypes(argTypes);
      Object.keys(required).length > 0 && (args = required, logger3.debug(
        `Generated mocked props using ArgTypes for ${componentExportName}: ${JSON.stringify(args)}`
      ));
    }
  } catch (error) {
    logger3.debug(`Could not generate mocked props for ${componentExportName}: ${error}`);
  }
  let storyFileContent = "";
  if (useCsfFactory) {
    let previewImportPath;
    if (previewConfigPath && !await checkForImportsMap(options.configDir)) {
      let storyFilePath2 = join2(projectRoot, relativeDir), pathWithoutExt = relative2(storyFilePath2, previewConfigPath).replace(/\.(ts|js|mts|cts|tsx|jsx)$/, "");
      previewImportPath = pathWithoutExt.startsWith(".") ? pathWithoutExt : `./${pathWithoutExt}`;
    }
    storyFileContent = await getCsfFactoryTemplateForNewStoryFile({
      basenameWithoutExtension,
      componentExportName,
      componentIsDefaultExport,
      exportedStoryName,
      previewImportPath,
      args,
      tags
    });
  } else
    storyFileContent = isTypescript && frameworkPackageName ? await getTypeScriptTemplateForNewStoryFile({
      basenameWithoutExtension,
      componentExportName,
      componentIsDefaultExport,
      frameworkPackage: sanitizedFrameworkPackageName,
      exportedStoryName,
      args,
      tags
    }) : await getJavaScriptTemplateForNewStoryFile({
      basenameWithoutExtension,
      componentExportName,
      componentIsDefaultExport,
      exportedStoryName,
      args,
      tags
    });
  storyFileContent = replaceArgsPlaceholders(storyFileContent);
  let storyFilePath = doesStoryFileExist(join2(projectRoot, relativeDir), storyFileName) && componentExportCount > 1 ? join2(projectRoot, relativeDir, alternativeStoryFileNameWithExtension) : join2(projectRoot, relativeDir, storyFileNameWithExtension), formattedStoryFileContent = await formatFileContent(storyFilePath, storyFileContent);
  return {
    storyFilePath,
    exportedStoryName,
    storyFileContent: formattedStoryFileContent,
    dirname: dir,
    alreadyContainsArgs: !!args
  };
}
var getStoryMetadata = (componentFilePath) => {
  let isTypescript = /\.(ts|tsx|mts|cts)$/.test(componentFilePath), base = basename2(componentFilePath), extension = extname(componentFilePath), basenameWithoutExtension = base.replace(extension, ""), storyFileExtension = isTypescript ? "tsx" : "jsx";
  return {
    storyFileName: `${basenameWithoutExtension}.stories`,
    storyFileExtension,
    isTypescript
  };
}, doesStoryFileExist = (parentFolder, storyFileName) => existsSync2(join2(parentFolder, `${storyFileName}.ts`)) || existsSync2(join2(parentFolder, `${storyFileName}.tsx`)) || existsSync2(join2(parentFolder, `${storyFileName}.js`)) || existsSync2(join2(parentFolder, `${storyFileName}.jsx`));
async function checkForImportsMap(configDir) {
  try {
    for (let directory of up(configDir, { last: getProjectRoot2() })) {
      let packageJsonPath = join2(directory, "package.json");
      if (existsSync2(packageJsonPath)) {
        let packageJsonContent = await readFile2(packageJsonPath, "utf-8");
        if (JSON.parse(packageJsonContent).imports)
          return !0;
      }
    }
    return !1;
  } catch {
    return !1;
  }
}
function replaceArgsPlaceholders(storyFileContent) {
  if (!storyFileContent.includes(STORYBOOK_FN_PLACEHOLDER))
    return storyFileContent;
  let storyFile = loadConfig(storyFileContent).parse(), needsFnImport = !1;
  return traverse(storyFile._ast, {
    StringLiteral(path) {
      path.node.value === STORYBOOK_FN_PLACEHOLDER && (needsFnImport = !0, path.replaceWith(t.callExpression(t.identifier("fn"), [])));
    }
  }), needsFnImport && storyFile.setImport(["fn"], "storybook/test"), printConfig(storyFile).code;
}

// src/core-server/utils/generate-story.ts
async function generateStoryFile(payload, options, generateOptions = {}) {
  let { checkFileExists = !0 } = generateOptions;
  try {
    let { storyFilePath, exportedStoryName, storyFileContent, alreadyContainsArgs } = await getNewStoryFile(payload, options), relativeStoryFilePath = relative3(process.cwd(), storyFilePath), { storyId, kind } = await getStoryId({ storyFilePath, exportedStoryName }, options);
    return checkFileExists && existsSync3(storyFilePath) ? {
      success: !1,
      kind,
      storyFilePath: relativeStoryFilePath,
      error: `A story file already exists at ${relativeStoryFilePath}`,
      errorType: "STORY_FILE_EXISTS"
    } : (await writeFile(storyFilePath, storyFileContent, "utf-8"), {
      success: !0,
      storyId,
      kind,
      storyFilePath: relativeStoryFilePath,
      exportedStoryName,
      alreadyContainsArgs
    });
  } catch (e) {
    return {
      success: !1,
      error: e?.message || "Unknown error occurred",
      errorType: "UNKNOWN"
    };
  }
}

// ../../node_modules/es-toolkit/dist/function/debounce.mjs
function debounce(func, debounceMs, { signal, edges } = {}) {
  let pendingThis, pendingArgs = null, leading = edges != null && edges.includes("leading"), trailing = edges == null || edges.includes("trailing"), invoke = () => {
    pendingArgs !== null && (func.apply(pendingThis, pendingArgs), pendingThis = void 0, pendingArgs = null);
  }, onTimerEnd = () => {
    trailing && invoke(), cancel();
  }, timeoutId = null, schedule = () => {
    timeoutId != null && clearTimeout(timeoutId), timeoutId = setTimeout(() => {
      timeoutId = null, onTimerEnd();
    }, debounceMs);
  }, cancelTimer = () => {
    timeoutId !== null && (clearTimeout(timeoutId), timeoutId = null);
  }, cancel = () => {
    cancelTimer(), pendingThis = void 0, pendingArgs = null;
  }, flush = () => {
    invoke();
  }, debounced = function(...args) {
    if (signal?.aborted)
      return;
    pendingThis = this, pendingArgs = args;
    let isFirstCall = timeoutId == null;
    schedule(), leading && isFirstCall && invoke();
  };
  return debounced.schedule = schedule, debounced.cancel = cancel, debounced.flush = flush, signal?.addEventListener("abort", cancel, { once: !0 }), debounced;
}

// ../../node_modules/es-toolkit/dist/function/throttle.mjs
function throttle(func, throttleMs, { signal, edges = ["leading", "trailing"] } = {}) {
  let pendingAt = null, debounced = debounce(function(...args) {
    pendingAt = Date.now(), func.apply(this, args);
  }, throttleMs, { signal, edges }), throttled = function(...args) {
    if (pendingAt == null && (pendingAt = Date.now()), Date.now() - pendingAt >= throttleMs) {
      pendingAt = Date.now(), func.apply(this, args), debounced.cancel(), debounced.schedule();
      return;
    }
    debounced.apply(this, args);
  };
  return throttled.cancel = debounced.cancel, throttled.flush = debounced.flush, throttled;
}

// ../../node_modules/es-toolkit/dist/function/partial.mjs
function partial(func, ...partialArgs) {
  return partialImpl(func, placeholderSymbol, ...partialArgs);
}
function partialImpl(func, placeholder, ...partialArgs) {
  let partialed = function(...providedArgs) {
    let providedArgsIndex = 0, substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg), remainingArgs = providedArgs.slice(providedArgsIndex);
    return func.apply(this, substitutedArgs.concat(remainingArgs));
  };
  return func.prototype && (partialed.prototype = Object.create(func.prototype)), partialed;
}
var placeholderSymbol = Symbol("partial.placeholder");
partial.placeholder = placeholderSymbol;

// ../../node_modules/es-toolkit/dist/function/partialRight.mjs
function partialRight(func, ...partialArgs) {
  return partialRightImpl(func, placeholderSymbol2, ...partialArgs);
}
function partialRightImpl(func, placeholder, ...partialArgs) {
  let partialedRight = function(...providedArgs) {
    let placeholderLength = partialArgs.filter((arg) => arg === placeholder).length, rangeLength = Math.max(providedArgs.length - placeholderLength, 0), remainingArgs = providedArgs.slice(0, rangeLength), providedArgsIndex = rangeLength, substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
    return func.apply(this, remainingArgs.concat(substitutedArgs));
  };
  return func.prototype && (partialedRight.prototype = Object.create(func.prototype)), partialedRight;
}
var placeholderSymbol2 = Symbol("partialRight.placeholder");
partialRight.placeholder = placeholderSymbol2;

// ../../node_modules/es-toolkit/dist/function/retry.mjs
var DEFAULT_RETRIES = Number.POSITIVE_INFINITY;

export {
  useStatics,
  parseStaticDir,
  mapStaticDir,
  debounce,
  throttle,
  getErrorLevel,
  sendTelemetryError,
  isTelemetryEnabled,
  withTelemetry,
  getStoryMetadata,
  doesStoryFileExist,
  generateStoryFile
};
