'use strict';

const fsp = require('node:fs/promises');
const kit = require('@nuxt/kit');
const defu = require('defu');
const kit$1 = require('nuxt-site-config/kit');
const pathe = require('pathe');
const pkgTypes = require('pkg-types');
const ufo = require('ufo');
const util = require('./util.cjs');
const node_fs = require('node:fs');
const devtoolsKit = require('@nuxt/devtools-kit');
const stdEnv = require('std-env');

var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }

const fsp__default = /*#__PURE__*/_interopDefaultCompat(fsp);

const DEVTOOLS_UI_ROUTE = "/__nuxt-robots";
const DEVTOOLS_UI_LOCAL_PORT = 3030;
function setupDevToolsUI(options, resolve, nuxt = kit.useNuxt()) {
  const clientPath = resolve("./client");
  const isProductionBuild = node_fs.existsSync(clientPath);
  if (isProductionBuild) {
    nuxt.hook("vite:serverCreated", async (server) => {
      const sirv = await import('sirv').then((r) => r.default || r);
      server.middlewares.use(
        DEVTOOLS_UI_ROUTE,
        sirv(clientPath, { dev: true, single: true })
      );
    });
  } else {
    nuxt.hook("vite:extendConfig", (config) => {
      config.server ??= {};
      config.server.proxy ??= {};
      config.server.proxy[DEVTOOLS_UI_ROUTE] = {
        target: `http://localhost:${DEVTOOLS_UI_LOCAL_PORT}${DEVTOOLS_UI_ROUTE}`,
        changeOrigin: true,
        followRedirects: true,
        rewrite: (path) => path.replace(DEVTOOLS_UI_ROUTE, "")
      };
    });
  }
  devtoolsKit.addCustomTab({
    name: "nuxt-robots",
    title: "Robots",
    icon: "carbon:bot",
    view: {
      type: "iframe",
      src: DEVTOOLS_UI_ROUTE
    }
  });
}

const autodetectableProviders = {
  azure_static: "azure",
  cloudflare_pages: "cloudflare-pages",
  netlify: "netlify",
  stormkit: "stormkit",
  vercel: "vercel",
  cleavr: "cleavr",
  stackblitz: "stackblitz"
};
const autodetectableStaticProviders = {
  netlify: "netlify-static",
  vercel: "vercel-static"
};
function detectTarget(options = {}) {
  return options?.static ? autodetectableStaticProviders[stdEnv.provider] : autodetectableProviders[stdEnv.provider];
}
function resolveNitroPreset(nitroConfig) {
  if (stdEnv.provider === "stackblitz" || stdEnv.provider === "codesandbox")
    return stdEnv.provider;
  let preset;
  if (nitroConfig && nitroConfig?.preset)
    preset = nitroConfig.preset;
  if (!preset)
    preset = stdEnv.env.NITRO_PRESET || detectTarget() || "node-server";
  return preset.replace("_", "-");
}
async function getNuxtModuleOptions(module, nuxt = kit.useNuxt()) {
  const moduleMeta = ({ name: module } ) || {};
  const { nuxtModule } = await kit.loadNuxtModuleInstance(module, nuxt);
  let moduleEntry;
  for (const m of nuxt.options.modules) {
    if (Array.isArray(m) && m.length >= 2) {
      const _module = m[0];
      const _moduleEntryName = typeof _module === "string" ? _module : (await _module.getMeta?.())?.name || "";
      if (_moduleEntryName === moduleMeta.name)
        moduleEntry = m;
    }
  }
  let inlineOptions = {};
  if (moduleEntry)
    inlineOptions = moduleEntry[1];
  if (nuxtModule.getOptions)
    return nuxtModule.getOptions(inlineOptions, nuxt);
  return inlineOptions;
}
function isNuxtGenerate(nuxt = kit.useNuxt()) {
  return nuxt.options.nitro.static || nuxt.options._generate || [
    "static",
    "github-pages"
  ].includes(resolveNitroPreset(nuxt.options.nitro));
}

const logger = kit.useLogger("@nuxt/robots");

function generatePathForI18nPages(localeCode, pageLocales, defaultLocale, strategy) {
  let path = pageLocales;
  switch (strategy) {
    case "prefix_except_default":
    case "prefix_and_default":
      path = localeCode === defaultLocale ? pageLocales : ufo.joinURL(localeCode, pageLocales);
      break;
    case "prefix":
      path = ufo.joinURL(localeCode, pageLocales);
      break;
  }
  return path;
}
function mapPathForI18nPages(path, autoI18n) {
  const pages = autoI18n.pages;
  if (!pages || !Object.keys(pages).length)
    return false;
  const withoutSlashes = ufo.withoutTrailingSlash(ufo.withoutLeadingSlash(path)).replace("/index", "");
  function resolveForAllLocales(pageName, pageLocales) {
    return autoI18n.locales.filter((l) => {
      if (l.code in pageLocales && pageLocales[l.code] === false)
        return false;
      if (autoI18n.strategy === "prefix_except_default" && l.code === autoI18n.defaultLocale)
        return false;
      return true;
    }).map((l) => {
      const localePath = l.code in pageLocales && pageLocales[l.code] !== false ? pageLocales[l.code] : `/${pageName}`;
      return ufo.withLeadingSlash(generatePathForI18nPages(l.code, localePath, autoI18n.defaultLocale, autoI18n.strategy));
    });
  }
  if (withoutSlashes in pages) {
    const pageLocales = pages[withoutSlashes];
    if (pageLocales)
      return resolveForAllLocales(withoutSlashes, pageLocales);
  }
  for (const [pageName, pageLocales] of Object.entries(pages)) {
    if (!pageLocales)
      continue;
    if (autoI18n.defaultLocale in pageLocales && pageLocales[autoI18n.defaultLocale] === path)
      return resolveForAllLocales(pageName, pageLocales);
  }
  return false;
}
function splitPathForI18nLocales(path, autoI18n) {
  const locales = autoI18n.strategy === "prefix_except_default" ? autoI18n.locales.filter((l) => l.code !== autoI18n.defaultLocale) : autoI18n.locales;
  if (!path || util.isInternalRoute(path))
    return path;
  const match = path.match(new RegExp(`^/(${locales.map((l) => l.code).join("|")})(.*)`));
  const locale = match?.[1];
  if (locale)
    return path;
  return [
    // always add the original route to avoid redirects
    path,
    ...locales.map((l) => `/${l.code}${path}`)
  ];
}
async function resolveI18nConfig() {
  let nuxtI18nConfig = {};
  let resolvedAutoI18n = false;
  let normalisedLocales = [];
  if (kit.hasNuxtModule("@nuxtjs/i18n")) {
    const i18nVersion = await kit.getNuxtModuleVersion("@nuxtjs/i18n");
    if (!await kit.hasNuxtModuleCompatibility("@nuxtjs/i18n", ">=8"))
      logger.warn(`You are using @nuxtjs/i18n v${i18nVersion}. For the best compatibility, please upgrade to @nuxtjs/i18n v8.0.0 or higher.`);
    nuxtI18nConfig = await getNuxtModuleOptions("@nuxtjs/i18n") || {};
    normalisedLocales = util.mergeOnKey((nuxtI18nConfig.locales || []).map((locale) => typeof locale === "string" ? { code: locale } : locale), "code");
    const usingI18nPages = Object.keys(nuxtI18nConfig.pages || {}).length;
    const hasI18nConfigForAlternatives = nuxtI18nConfig.differentDomains || usingI18nPages || nuxtI18nConfig.strategy !== "no_prefix" && nuxtI18nConfig.locales;
    if (hasI18nConfigForAlternatives) {
      resolvedAutoI18n = {
        differentDomains: nuxtI18nConfig.differentDomains,
        defaultLocale: nuxtI18nConfig.defaultLocale,
        locales: normalisedLocales,
        strategy: nuxtI18nConfig.strategy,
        pages: nuxtI18nConfig.pages
      };
    }
  }
  return resolvedAutoI18n;
}

function registerTypeTemplates({ nuxt }) {
  const isNuxt4 = Number(nuxt.options.future?.compatibilityVersion) === 4;
  const nitroModule = isNuxt4 ? "nitropack/types" : "nitropack";
  kit.addTypeTemplate({
    filename: "types/nuxt-robots-nuxt.d.ts",
    getContents: () => `// Generated by nuxt-robots
import type { RobotsValue } from '@nuxtjs/robots'

declare module '#app' {
  interface PageMeta {
    robots?: RobotsValue
  }
}

export {}
`
  }, {
    nuxt: true
  });
  kit.addTypeTemplate({
    filename: "types/nuxt-robots-nitro.d.ts",
    getContents: () => `// Generated by nuxt-robots
import type { HookRobotsConfigContext, HookRobotsTxtContext, RobotsValue, RobotsContext, PatternMapValue } from '@nuxtjs/robots'

declare module '${nitroModule}' {
  interface NitroApp {
    _robots: {
      ctx: HookRobotsConfigContext
      nuxtContentUrls?: Set<string>
    },
    _robotsRuleMatcher: (url: string) => any
    _robotsPatternMap?: Map<string, PatternMapValue>
  }
  interface NitroRouteRules {
    robots?: RobotsValue | {
      indexable: boolean
      rule: string
    }
  }
  interface NitroRouteConfig {
    robots?: RobotsValue | {
      indexable: boolean
      rule: string
    }
  }
  interface NitroRuntimeHooks {
    'robots:config': (ctx: HookRobotsConfigContext) => void | Promise<void>
    'robots:robots-txt': (ctx: HookRobotsTxtContext) => void | Promise<void>
  }
}

declare module 'h3' {
  interface H3EventContext {
    robots: RobotsContext
    robotsProduction?: RobotsContext
  }
}

export {}
`
  }, {
    nitro: true,
    nuxt: true
  });
}

const module$1 = kit.defineNuxtModule({
  meta: {
    name: "@nuxtjs/robots",
    compatibility: {
      nuxt: ">=3.6.1"
    },
    configKey: "robots"
  },
  moduleDependencies: {
    "@nuxtjs/i18n": {
      version: ">=8",
      optional: true
    },
    "nuxt-i18n-micro": {
      version: ">=1",
      optional: true
    },
    "nuxt-site-config": {
      version: ">=3"
    },
    "@nuxt/content": {
      version: ">=2",
      optional: true
    }
  },
  defaults: {
    enabled: true,
    credits: true,
    debug: false,
    allow: [],
    disallow: [],
    sitemap: [],
    groups: [],
    blockNonSeoBots: false,
    mergeWithRobotsTxtPath: true,
    header: true,
    metaTag: true,
    cacheControl: "max-age=14400, must-revalidate",
    robotsEnabledValue: util.ROBOT_DIRECTIVE_VALUES.enabled,
    robotsDisabledValue: util.ROBOT_DIRECTIVE_VALUES.disabled,
    disallowNonIndexableRoutes: false,
    robotsTxt: true,
    botDetection: true
  },
  async setup(config, nuxt) {
    const { resolve } = kit.createResolver((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('module.cjs', document.baseURI).href)));
    const { version } = await pkgTypes.readPackageJSON(resolve("../package.json"));
    logger.level = config.debug || nuxt.options.debug ? 4 : 3;
    if (config.enabled === false) {
      logger.debug("The module is disabled, skipping setup.");
      kit.addImports({ name: "useRobotsRule", from: resolve(`./runtime/app/composables/mock`) });
      kit.addImports({ name: "useBotDetection", from: resolve(`./runtime/app/composables/mock`) });
      nuxt.options.nitro = nuxt.options.nitro || {};
      nuxt.options.nitro.imports = nuxt.options.nitro.imports || {};
      nuxt.options.nitro.imports.presets = nuxt.options.nitro.imports.presets || [];
      nuxt.options.nitro.imports.presets.push({
        from: resolve("./runtime/server/mock-composables"),
        imports: [
          "getPathRobotConfig",
          "getSiteRobotConfig",
          "getBotDetection",
          "isBot",
          "getBotInfo"
        ]
      });
      nuxt.options.nitro.alias = nuxt.options.nitro.alias || {};
      nuxt.options.nitro.alias["#internal/nuxt-robots"] = resolve("./runtime/server/mock-composables");
      return;
    }
    nuxt.options.experimental.extraPageMetaExtractionKeys = nuxt.options.experimental.extraPageMetaExtractionKeys || [];
    if (!nuxt.options.experimental.extraPageMetaExtractionKeys.includes("robots"))
      nuxt.options.experimental.extraPageMetaExtractionKeys.push("robots");
    const pageMetaRobots = {};
    nuxt.hook("pages:resolved", (pages) => {
      for (const page of pages) {
        if (typeof page.meta?.robots !== "undefined")
          pageMetaRobots[page.path] = page.meta.robots;
      }
    });
    if (nuxt.options.app.baseURL?.length > 1 && config.robotsTxt) {
      logger.error(`You are not allowed to generate a robots.txt with a base URL, please set \`{ robots: { robotsTxt: false } }\` in your nuxt.config.`);
      config.robotsTxt = false;
    }
    const resolvedAutoI18n = typeof config.autoI18n === "boolean" ? false : config.autoI18n || await resolveI18nConfig();
    if (config.blockNonSeoBots) {
      config.groups.push({
        userAgent: util.NonHelpfulBots,
        comment: ["Block non helpful bots"],
        disallow: ["/"]
      });
    }
    if (config.blockAiBots) {
      config.groups.push({
        userAgent: util.AiBots,
        comment: ["Block AI Crawlers"],
        disallow: ["/"]
      });
    }
    await kit$1.installNuxtSiteConfig();
    if (config.metaTag)
      kit.addPlugin({ mode: "server", src: resolve("./runtime/app/plugins/robot-meta.server") });
    if (config.robotsTxt && config.mergeWithRobotsTxtPath !== false) {
      let usingRobotsTxtPath = "";
      let robotsTxt = false;
      const publicRobotsTxtPath = resolve(nuxt.options.rootDir, nuxt.options.dir.public, "robots.txt");
      const validPaths = [
        // public/robots.txt - This is the default, we need to move this to avoid issues
        publicRobotsTxtPath,
        // assets/robots.txt
        resolve(nuxt.options.rootDir, nuxt.options.dir.assets, "robots.txt"),
        // public/_robots.txt
        resolve(nuxt.options.rootDir, nuxt.options.dir.public, "_robots.txt"),
        // public/_robots.txt
        resolve(nuxt.options.rootDir, nuxt.options.dir.public, "_robots.txt"),
        // public/_dir/robots.txt
        resolve(nuxt.options.rootDir, nuxt.options.dir.public, "_dir", "robots.txt"),
        // pages/_dir/robots.txt
        resolve(nuxt.options.rootDir, nuxt.options.dir.pages, "_dir", "robots.txt"),
        // pages/robots.txt
        resolve(nuxt.options.rootDir, nuxt.options.dir.pages, "robots.txt"),
        // robots.txt
        resolve(nuxt.options.rootDir, "robots.txt")
      ];
      if (config.mergeWithRobotsTxtPath === true) {
        for (const path of validPaths) {
          robotsTxt = await fsp__default.readFile(path, { encoding: "utf-8" }).catch(() => false);
          if (robotsTxt) {
            usingRobotsTxtPath = path;
            break;
          }
        }
      } else {
        const customPath = resolve(nuxt.options.rootDir, config.mergeWithRobotsTxtPath);
        if (!await fsp__default.stat(customPath).catch(() => false)) {
          logger.error(`You provided an invalid \`mergeWithRobotsTxtPath\`, the file does not exist: ${customPath}.`);
        } else {
          usingRobotsTxtPath = customPath;
          robotsTxt = await fsp__default.readFile(customPath, { encoding: "utf-8" });
        }
      }
      if (typeof robotsTxt === "string") {
        const path = pathe.relative(nuxt.options.rootDir, usingRobotsTxtPath);
        logger.debug(`A robots.txt file was found at \`./${path}\`, merging config.`);
        const parsedRobotsTxt = util.parseRobotsTxt(robotsTxt);
        const { errors } = util.validateRobots(parsedRobotsTxt);
        if (errors.length > 0) {
          logger.error(`The \`./${path}\` file contains errors:`);
          for (const error of errors)
            logger.log(` - ${error}`);
          logger.log("");
        }
        const wildCardGroups = parsedRobotsTxt.groups.filter((group) => util.asArray(group.userAgent).includes("*"));
        if (wildCardGroups.some((group) => util.asArray(group.disallow).includes("/"))) {
          logger.warn(`The \`./${path}\` is blocking indexing for all environments.`);
          logger.info("It's recommended to use the `indexable` Site Config to toggle this instead.");
        }
        config.groups.push(...parsedRobotsTxt.groups);
        const host = parsedRobotsTxt.groups.map((g) => g.host).filter(Boolean)[0];
        if (host) {
          kit$1.updateSiteConfig({
            _context: usingRobotsTxtPath,
            url: host
          });
        }
        config.sitemap = [.../* @__PURE__ */ new Set([...util.asArray(config.sitemap), ...parsedRobotsTxt.sitemaps])];
        if (usingRobotsTxtPath === publicRobotsTxtPath) {
          await fsp__default.rename(usingRobotsTxtPath, resolve(nuxt.options.rootDir, nuxt.options.dir.public, "_robots.txt"));
          logger.warn("Your robots.txt file was moved to `./public/_robots.txt` to avoid conflicts.");
          const extraPaths = [];
          for (const path2 of validPaths) {
            if (path2 !== usingRobotsTxtPath)
              extraPaths.push(` - ./${pathe.relative(nuxt.options.rootDir, path2)}`);
          }
          logger.info(`The following paths are also valid for your robots.txt:
${extraPaths.join("\n")}
`);
        }
      }
    }
    const nitroPreset = resolveNitroPreset(nuxt.options.nitro);
    const usingNuxtContent = kit.hasNuxtModule("@nuxt/content");
    const isNuxtContentV3 = usingNuxtContent && await kit.hasNuxtModuleCompatibility("@nuxt/content", "^3");
    let isNuxtContentV2 = usingNuxtContent && await kit.hasNuxtModuleCompatibility("@nuxt/content", "^2");
    if (isNuxtContentV3) {
      if (nuxt.options._installedModules.some((m) => m.meta.name === "Content")) {
        logger.warn("You have loaded `@nuxt/content` before `@nuxtjs/robots`, this may cause issues with the integration. Please ensure `@nuxtjs/robots` is loaded first.");
      }
      nuxt.hooks.hook("content:file:afterParse", (ctx) => {
        if (typeof ctx.content.robots !== "undefined") {
          let rule = ctx.content.robots;
          if (typeof rule === "boolean") {
            rule = rule ? config.robotsEnabledValue : config.robotsDisabledValue;
          } else if (typeof rule === "object" && rule !== null) {
            const directives = [];
            for (const [key, value] of Object.entries(rule)) {
              if (value === false || value === null || value === void 0)
                continue;
              if (key in util.ROBOT_DIRECTIVE_VALUES && typeof value === "boolean" && value) {
                directives.push(util.ROBOT_DIRECTIVE_VALUES[key]);
              } else if (key === "max-image-preview" && typeof value === "string") {
                directives.push(util.formatMaxImagePreview(value));
              } else if (key === "max-snippet" && typeof value === "number") {
                directives.push(util.formatMaxSnippet(value));
              } else if (key === "max-video-preview" && typeof value === "number") {
                directives.push(util.formatMaxVideoPreview(value));
              }
            }
            rule = directives.join(", ") || config.robotsEnabledValue;
          }
          ctx.content.seo = ctx.content.seo || {};
          ctx.content.seo.robots = rule;
        }
      });
    } else if (isNuxtContentV2 && nitroPreset.startsWith("cloudflare")) {
      logger.warn("The Nuxt Robots, Nuxt Content integration does not work with CloudFlare yet, the integration will be disabled. Learn more at: https://nuxtseo.com/docs/robots/guides/content");
      isNuxtContentV2 = false;
    }
    nuxt.hook("nitro:build:public-assets", (nitro) => {
      nitro.hooks.hook("close", async () => {
        const outputPath = resolve(nitro.options.output.publicDir, "_robots.txt");
        if (await fsp__default.stat(outputPath).catch(() => false)) {
          await fsp__default.unlink(outputPath);
          logger.debug("Deleted _robots.txt from output");
        }
      });
    });
    nuxt.hook("modules:done", async () => {
      config.sitemap = util.asArray(config.sitemap);
      config.disallow = util.asArray(config.disallow);
      config.allow = util.asArray(config.allow);
      config.groups = config.groups.map(util.normalizeGroup);
      const existingGroup = config.groups.find((stack) => stack.userAgent.length === 1 && stack.userAgent[0] === "*");
      if (existingGroup) {
        existingGroup.disallow = [.../* @__PURE__ */ new Set([...existingGroup.disallow || [], ...config.disallow])];
        if (existingGroup.disallow.length > 1) {
          existingGroup.disallow = existingGroup.disallow.filter((disallow) => disallow !== "");
        }
        existingGroup.allow = [.../* @__PURE__ */ new Set([...existingGroup.allow || [], ...config.allow])];
      } else {
        config.groups.unshift({
          userAgent: ["*"],
          disallow: config.disallow.length > 0 ? config.disallow : [""],
          allow: config.allow
        });
      }
      await nuxt.hooks.callHook("robots:config", config);
      nuxt.options.routeRules = nuxt.options.routeRules || {};
      if (config.header) {
        const noIndexPaths = [ufo.withoutTrailingSlash(nuxt.options.app.buildAssetsDir), `${nuxt.options.app.buildAssetsDir}**`];
        for (const path of noIndexPaths) {
          nuxt.options.routeRules[path] = defu.defu({
            robots: "noindex"
          }, nuxt.options.routeRules[path]);
        }
        Object.entries(nuxt.options.routeRules).forEach(([route, rules]) => {
          const robotRule = util.normaliseRobotsRouteRule(rules);
          if (robotRule && !robotRule.allow && robotRule.rule) {
            nuxt.options.routeRules[route] = defu.defu({
              headers: {
                "X-Robots-Tag": robotRule.rule
              }
            }, nuxt.options.routeRules?.[route]);
          }
        });
      }
      const extraDisallows = /* @__PURE__ */ new Set();
      if (config.disallowNonIndexableRoutes) {
        Object.entries(nuxt.options.routeRules || {}).forEach(([route, rules]) => {
          const url = route.split("/").map((segment) => segment.startsWith(":") ? "*" : segment).join("/");
          const robotsRule = util.normaliseRobotsRouteRule(rules);
          if (robotsRule && !robotsRule.allow) {
            extraDisallows.add(url.replaceAll("**", "*"));
          }
        });
      }
      const firstGroup = config.groups.find((group) => group.userAgent.includes("*"));
      if (firstGroup)
        firstGroup.disallow = [.../* @__PURE__ */ new Set([...firstGroup.disallow || [], ...extraDisallows])];
      if (resolvedAutoI18n && resolvedAutoI18n.locales && resolvedAutoI18n.strategy !== "no_prefix") {
        const i18n = resolvedAutoI18n;
        for (const group of config.groups.filter((g) => !g._skipI18n)) {
          group.allow = util.asArray(group.allow || []).map((path) => {
            if (typeof path !== "string")
              return path;
            return mapPathForI18nPages(path, i18n) || splitPathForI18nLocales(path, i18n);
          }).flat();
          group.disallow = util.asArray(group.disallow || []).map((path) => {
            if (typeof path !== "string")
              return path;
            return mapPathForI18nPages(path, i18n) || splitPathForI18nLocales(path, i18n);
          }).flat();
        }
      }
      const groups = config.groups.map(util.normalizeGroup);
      const pathsToCheck = [
        ufo.withoutTrailingSlash(nuxt.options.app.buildAssetsDir),
        nuxt.options.app.buildAssetsDir,
        "/api",
        "/api/"
      ];
      for (const p of pathsToCheck) {
        if (groups.some((g) => g.disallow.includes(p))) {
          logger.warn(`You have disallowed robots accessing \`${ufo.withTrailingSlash(p)}**\`, this may prevent your site from being indexed correctly.`);
        }
      }
      const robotsRuntimeConfig = {
        version: version || "",
        isNuxtContentV2,
        debug: config.debug,
        credits: config.credits,
        groups,
        sitemap: config.sitemap,
        header: config.header,
        robotsEnabledValue: config.robotsEnabledValue,
        robotsDisabledValue: config.robotsDisabledValue,
        cacheControl: config.cacheControl ?? "max-age=14400, must-revalidate",
        botDetection: config.botDetection ?? true,
        pageMetaRobots
      };
      nuxt.options.runtimeConfig["nuxt-robots"] = robotsRuntimeConfig;
      nuxt.options.runtimeConfig.public["nuxt-robots"] = robotsRuntimeConfig;
    });
    registerTypeTemplates({ nuxt});
    const isFirebase = nitroPreset === "firebase";
    if ((isNuxtGenerate() || isFirebase) && config.robotsTxt) {
      nuxt.options.nitro.prerender = nuxt.options.nitro.prerender || {};
      nuxt.options.nitro.prerender.routes = nuxt.options.nitro.prerender.routes || [];
      nuxt.options.nitro.prerender.routes.push("/robots.txt");
      if (isFirebase)
        logger.info("Firebase does not support dynamic robots.txt files. Prerendering /robots.txt.");
    }
    kit.addImports({
      name: "useRobotsRule",
      from: resolve("./runtime/app/composables/useRobotsRule")
    });
    if (config.botDetection) {
      kit.addImports({
        name: "useBotDetection",
        from: resolve("./runtime/app/composables/useBotDetection")
      });
    } else {
      kit.addImports({
        name: "useBotDetection",
        from: resolve("./runtime/app/composables/mock")
      });
    }
    if (config.robotsTxt) {
      kit.addServerHandler({
        route: "/robots.txt",
        handler: resolve("./runtime/server/routes/robots-txt")
      });
    }
    kit.addServerHandler({
      middleware: true,
      handler: resolve("./runtime/server/middleware/injectContext")
    });
    kit.addServerPlugin(resolve("./runtime/server/plugins/initContext"));
    if (isNuxtContentV2) {
      kit.addServerHandler({
        route: "/__robots__/nuxt-content.json",
        handler: resolve("./runtime/server/routes/__robots__/nuxt-content-v2")
      });
    }
    if (config.debug || nuxt.options.dev) {
      kit.addServerHandler({
        route: "/__robots__/debug.json",
        handler: resolve("./runtime/server/routes/__robots__/debug")
      });
      kit.addServerHandler({
        route: "/__robots__/debug-path.json",
        handler: resolve("./runtime/server/routes/__robots__/debug-path")
      });
    }
    if (nuxt.options.dev)
      setupDevToolsUI(config, resolve);
    kit.addServerImportsDir(resolve("./runtime/server/composables"));
    if (!config.botDetection) {
      nuxt.options.nitro.imports = nuxt.options.nitro.imports || {};
      nuxt.options.nitro.imports.presets = nuxt.options.nitro.imports.presets || [];
      nuxt.options.nitro.imports.presets.push({
        from: resolve("./runtime/server/mock-composables"),
        imports: [
          "getBotDetection",
          "isBot",
          "getBotInfo"
        ]
      });
    }
    nuxt.options.nitro.alias = nuxt.options.nitro.alias || {};
    nuxt.options.nitro.alias["#internal/nuxt-simple-robots"] = resolve("./runtime/server/composables");
    nuxt.options.nitro.alias["#internal/nuxt-robots"] = resolve("./runtime/server/composables");
    nuxt.options.alias["#robots"] = resolve("./runtime");
  }
});

module.exports = module$1;
