import { basename, extname, join, resolve } from "../../../../pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs";
import { fileURLToPath, findExportNames, resolvePath } from "../../../../mlly@1.8.1/node_modules/mlly/dist/index.mjs";
import { MagicString } from "../../../../magic-string@0.30.21/node_modules/magic-string/dist/magic-string.es.mjs";
import { camelCase, titleCase } from "../../../../scule@1.3.0/node_modules/scule/dist/index.mjs";
import { readPackageJSON } from "../../../../pkg-types@2.3.0/node_modules/pkg-types/dist/index.mjs";
import { image, link, render } from "../../../../mdbox@0.1.1/node_modules/mdbox/dist/index.mjs";
import { destr } from "../../../../destr@2.0.5/node_modules/destr/dist/index.mjs";
import { promises } from "node:fs";
import { readFile, readdir, stat } from "node:fs/promises";
import { defu as defu$1 } from "defu";

//#region ../../node_modules/.pnpm/automd@0.4.3_patch_hash=5b5d5334735dce5e1ae79d8924a5aa49e4139453056613d618786b961793a42b_magicast@0.5.2/node_modules/automd/dist/index.mjs
function defineGenerator(generator) {
	return generator;
}
function resolvePath$1(path, { url, dir }) {
	if (path.startsWith("/")) return join(dir, path);
	return url ? fileURLToPath(new URL(path, url)) : resolve(dir, path);
}
async function getPkg(dir, input = {}) {
	const pkg = await readPackageJSON(dir).catch(() => void 0);
	return defu$1({
		name: input.name,
		version: typeof input.version === "string" ? input.version : void 0,
		github: input.github || input.gh
	}, {
		name: pkg?.name,
		version: pkg?.version,
		github: _getGitRepo(pkg?.repository)
	}, {
		name: process.env.npm_package_name,
		version: process.env.npm_package_version
	});
}
function _getGitRepo(repo) {
	const url = typeof repo === "string" ? repo : repo?.url;
	if (!url || typeof url !== "string") return;
	const match = /(?:https:\/\/github\.com\/|gh:|github:|)([\w-]+)\/([\w-]+)/.exec(url);
	if (match && match[1] && match[2]) return `${match[1]}/${match[2]}`;
}
const jsdocs = defineGenerator({
	name: "jsdocs",
	async generate({ config, args, url }) {
		const { loadSchema } = await import("../../../../untyped@2.0.0/node_modules/untyped/dist/loader/loader.mjs");
		return { contents: _render(await loadSchema(resolvePath$1(args.src, {
			url,
			dir: config.dir
		}), { jiti: {
			fsCache: false,
			moduleCache: false
		} }), args, Number.parseInt(args.headingLevel) || 2).join("\n").replace(/\n{3,}/g, "\n\n") };
	}
});
function _render(schema, opts, headingLevel) {
	const sections = Object.create(null);
	for (const [key, keySchema] of Object.entries(schema.properties || {})) {
		const section = _renderSection(key, keySchema, opts, headingLevel + 1);
		if (!section) continue;
		sections[section.group] = sections[section.group] || [];
		sections[section.group].push([section.heading, section.lines]);
	}
	const lines = [];
	const sortedGroups = Object.keys(sections).sort((a, b) => {
		if (a === "") return 1;
		if (b === "") return -1;
		return a.localeCompare(b);
	});
	for (const group of sortedGroups) {
		if (group) lines.push(`\n${"#".repeat(headingLevel)} ${titleCase(group)}\n`);
		const sortedSections = sections[group].sort((a, b) => a[0].localeCompare(b[0]));
		for (const section of sortedSections) {
			const heading = `\n${"#".repeat(headingLevel + 1)} ${section[0]}\n`;
			lines.push(heading, ...section[1]);
		}
	}
	return lines;
}
function _renderSection(key, schema, opts, headingLevel) {
	const tags = _parseTags(schema.tags);
	if (tags.some((t) => t.tag === "@deprecated" || t.tag === "@internal")) return;
	const group = tags.find((t) => t.tag === "@group")?.contents || opts.defaultGroup || "";
	if (opts.group && (typeof opts.group === "string" ? group !== opts.group : !opts.group.includes(group))) return;
	let heading = `\`${key}\``;
	const lines = [];
	if (schema.type === "function") heading = `\`${_generateFunctionSig(key, schema)}\``;
	else if (schema.type !== "object") {
		lines.push(`- **Type**: \`${schema.markdownType || schema.tsType || schema.type}\``);
		if ("default" in schema) lines.push(`- **Default**: \`${JSON.stringify(schema.default)}\``);
		lines.push("");
	}
	lines.push(..._renderBody(schema));
	for (const tag of tags) if (tag.tag === "@example") {
		const codeBlock = tag.contents.startsWith("`") ? tag.contents : `\`\`\`ts\n${tag.contents}\n\`\`\``;
		lines.push("", "**Example:**", "", codeBlock);
	}
	if (schema.type === "object") lines.push(..._render(schema, opts, headingLevel));
	return {
		heading,
		lines,
		group
	};
}
function _renderBody(schema) {
	const lines = [];
	if (schema.title) lines.push(schema.title.trim());
	if (schema.title && schema.description) lines.push("");
	if (schema.description) lines.push(...schema.description.split("\n").map((line) => line.trim()).join("\n\n").split("\n"));
	return lines;
}
function _parseTags(lines = []) {
	const parsedTags = [];
	let tag = "";
	let contentLines = [];
	for (const line of lines.join("\n").split("\n")) if (line.startsWith("@")) {
		if (tag) parsedTags.push({
			tag,
			contents: contentLines.join("\n")
		});
		const [_tag, ...rest] = line.split(" ");
		tag = _tag;
		contentLines = rest;
	} else contentLines.push(line);
	if (tag) parsedTags.push({
		tag,
		contents: contentLines.join("\n")
	});
	return parsedTags;
}
function _generateFunctionSig(name, meta) {
	return `${name}(${(meta.args || []).map((arg) => {
		let str = arg.name;
		if (arg.optional) str += "?";
		const tsType = _simpleArgType(arg.tsType);
		if (tsType) str += `: ${tsType}`;
		return str;
	}).join(", ")})`;
}
function _simpleArgType(tsType = "") {
	return tsType.split(/\s*\|\s*/).filter((t) => t && t !== "object" && t.startsWith("{")).map((ot) => ot.split(/\s*[,;]\s*/g).map((p) => p.replaceAll(/\s*:\s*(string|boolean|number)/g, "")).join(", ")).join(" | ");
}
const badgeTypes = {
	npmVersion: {
		name: "npm version",
		to: "https://npmjs.com/package/{name}"
	},
	npmDownloads: {
		name: "npm downloads",
		to: "https://npm.chart.dev/{name}"
	},
	bundlephobia: {
		name: "bundle size",
		to: "https://bundlephobia.com/package/{name}"
	},
	bundlejs: {
		name: "bundle size",
		to: "https://bundlejs.com/?q={name}"
	},
	packagephobia: {
		name: "install size",
		to: "https://packagephobia.com/result?p={name}"
	},
	codecov: {
		name: "codecov",
		to: "https://codecov.io/gh/{github}"
	},
	license: {
		name: "license",
		to: "https://github.com/{github}/blob/{licenseBranch}/LICENSE"
	}
};
const badgeProviders = {
	shields: {
		npmVersion: "https://img.shields.io/npm/v/{name}",
		npmDownloads: "https://img.shields.io/npm/dm/{name}",
		bundlephobia: "https://img.shields.io/bundlephobia/minzip/{name}",
		packagephobia: "https://badgen.net/packagephobia/install/{name}",
		bundlejs: "https://img.shields.io/bundlejs/size/{name}",
		codecov: "https://img.shields.io/codecov/c/gh/{github}",
		license: "https://img.shields.io/github/license/{github}"
	},
	badgen: {
		npmVersion: "https://flat.badgen.net/npm/v/{name}",
		npmDownloads: "https://flat.badgen.net/npm/dm/{name}",
		bundlephobia: "https://flat.badgen.net/bundlephobia/minzip/{name}",
		bundlejs: false,
		packagephobia: "https://flat.badgen.net/packagephobia/install/{name}",
		codecov: "https://flat.badgen.net/codecov/c/github/{github}",
		license: "https://flat.badgen.net/github/license/{github}"
	},
	badgenClassic: {
		npmVersion: "https://badgen.net/npm/v/{name}",
		npmDownloads: "https://badgen.net/npm/dm/{name}",
		bundlephobia: "https://badgen.net/bundlephobia/minzip/{name}",
		bundlejs: false,
		packagephobia: "https://badgen.net/packagephobia/install/{name}",
		codecov: "https://badgen.net/codecov/c/github/{github}",
		license: "https://badgen.net/github/license/{github}"
	}
};
const badges = defineGenerator({
	name: "badges",
	async generate({ config, args }) {
		const pkg = await getPkg(config.dir, args);
		const ctx = {
			name: pkg.name,
			github: pkg.github,
			licenseBranch: "main",
			...args
		};
		const fillStr = (str) => str.replace(/{(\w+)}/g, (_, key) => ctx[key] || "");
		const provider = badgeProviders[args.provider] || badgeProviders.shields;
		const providerParams = Object.entries({
			color: args.color,
			labelColor: args.labelColor,
			...args.styleParams
		}).filter(([, value]) => value).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&");
		const badges$1 = {
			npmVersion: {
				enabled: ctx.name && args.npmVersion !== false,
				...badgeTypes.npmVersion
			},
			npmDownloads: {
				enabled: ctx.name && args.npmDownloads !== false,
				...badgeTypes.npmDownloads
			},
			bundlephobia: {
				enabled: args.bundlephobia && ctx.name,
				...badgeTypes.bundlephobia
			},
			bundlejs: {
				enabled: args.bundlejs && ctx.name,
				...badgeTypes.bundlejs
			},
			packagephobia: {
				enabled: args.packagephobia && ctx.name,
				...badgeTypes.packagephobia
			},
			codecov: {
				enabled: args.codecov && ctx.github,
				...badgeTypes.codecov
			},
			license: {
				enabled: args.license && ctx.github,
				...badgeTypes.license
			}
		};
		const md = [];
		for (const [badgeType, badge] of Object.entries(badges$1)) {
			if (!badge.enabled || !provider[badgeType]) continue;
			const to = fillStr(badge.to);
			const imgURL = fillStr(provider[badgeType]) + (providerParams ? `?${providerParams}` : "");
			md.push(link(to, image(imgURL, badge.name)));
		}
		return { contents: md.join("\n") };
	}
});
const INSTALL_COMMANDS = [
	["npm", "install"],
	["yarn", "add"],
	["pnpm", "add"],
	["bun", "install"],
	[
		"deno",
		"install",
		" --dev",
		"npm:"
	]
];
const NYPM_COMMAND = ["npx nypm", "install"];
const RUN_COMMANDS = [
	["npm", "npx "],
	["pnpm", "pnpm dlx "],
	["bun", "bunx "],
	["deno", "deno run -A npm:"]
];
const pmInstall = defineGenerator({
	name: "pm-install",
	async generate({ config, args }) {
		const { name, version } = await getPkg(config.dir, args);
		if (!name) return { contents: "<!-- package name is unspecified -->" };
		let versionSuffix = "";
		if (args.version) versionSuffix = typeof args.version === "string" ? `@${args.version}` : `@^${version}`;
		const contents = (args.auto === false ? INSTALL_COMMANDS : [NYPM_COMMAND, ...INSTALL_COMMANDS]).map(([cmd, install, dev = " -D", pkgPrefix = ""]) => `# ${cmd.includes("nypm") ? "✨ Auto-detect" : cmd}\n${cmd} ${install}${args.dev ? dev : args.global ? "g" : ""} ${pkgPrefix}${name}${versionSuffix}`);
		if ((args.separate ?? false) === false) return { contents: render.codeBlock(contents.join("\n\n"), "sh") };
		return { contents: contents.map((cmd) => render.codeBlock(cmd, "sh")).join("\n\n") };
	}
});
const pmX = defineGenerator({
	name: "pm-x",
	async generate({ config, args }) {
		const { name, version } = await getPkg(config.dir, args);
		if (!name) return { contents: "<!-- package name is unspecified -->" };
		let versionSuffix = "";
		if (args.version) versionSuffix = typeof args.version === "string" ? `@${args.version}` : `@${version}`;
		const contents = RUN_COMMANDS.map(([pm, cmd]) => `# ${pm}\n${cmd}${name}${versionSuffix}${args.args ? ` ${args.args}` : ""}`);
		if ((args.separate ?? false) === false) return { contents: render.codeBlock(contents.join("\n\n"), "sh") };
		return { contents: contents.map((cmd) => render.codeBlock(cmd, "sh")).join("\n\n") };
	}
});
const fetch = defineGenerator({
	name: "fetch",
	async generate({ args }) {
		const { $fetch } = await import("../../../../ofetch@1.5.1/node_modules/ofetch/dist/node.mjs");
		let url = args.url;
		if (!url) throw new Error("URL is required!");
		if (url.startsWith("gh:")) url = `https://raw.githubusercontent.com/${url.slice(3)}`;
		return { contents: await $fetch(url) };
	}
});
const DEFAULT_CDN = "https://esm.sh/";
const jsimport = defineGenerator({
	name: "jsimport",
	async generate({ config, args }) {
		const { name } = await getPkg(config.dir, args);
		const importPath = name + (args.path || "");
		const importNames = [].concat(args.import, args.imports).filter(Boolean).flatMap((i) => i.split(/\s*,\s*/));
		if (args.src) {
			const exportNames = findExportNames(await readFile(await resolvePath(args.src, { url: config.dir }), "utf8"));
			if (exportNames && exportNames.length > 0) importNames.push(...exportNames);
		}
		const lines = [];
		const fmtImports = importNames.length > 1 ? `\n${importNames.map((i) => "  " + i + ",").join("\n")}\n` : importNames[0] && ` ${importNames[0]} ` || "";
		const formatMultiLine = (str) => {
			return str.length > (args.printWidth || 80) ? str : str.replace(/\n/g, "").replace(/,\s*}/, "}").replace(/(\w)}/, "$1 }").replace(/\s+/g, " ");
		};
		if (args.esm !== false) {
			const code = formatMultiLine(`import {${fmtImports}} from "${importPath}";`);
			lines.push("**ESM** (Node.js, Bun, Deno)", render.codeBlock(code, "js"));
		}
		if (args.cjs) {
			const code = formatMultiLine(`const {${fmtImports}} = require("${importPath}");`);
			lines.push("**CommonJS** (Legacy Node.js)", render.codeBlock(code, "js"));
		}
		if (args.cdn) {
			const code = formatMultiLine(`import {${fmtImports}} from "${typeof args.cdn === "string" ? args.cdn : DEFAULT_CDN}${importPath}";`);
			lines.push("**CDN** (Deno and Browsers)", render.codeBlock(code, "js"));
		}
		return { contents: lines.join("\n\n") };
	}
});
const withAutomd = defineGenerator({
	name: "with-automd",
	generate({ args }) {
		const lastUpdate = args.lastUpdate ? ` (last updated: ${typeof args.lastUpdate === "string" ? args.lastUpdate : (/* @__PURE__ */ new Date()).toDateString()})` : "";
		const emoji = args.emoji === false ? "" : "🤖 ";
		const lines = [];
		if (args.separator !== false) lines.push("---", "");
		lines.push(`_${emoji}auto updated with [automd](https://automd.unjs.io)${lastUpdate}_`);
		return { contents: lines.join("\n") };
	}
});
const file = defineGenerator({
	name: "file",
	async generate({ args, config, url }) {
		const fullPath = resolvePath$1(args.src, {
			url,
			dir: config.dir
		});
		let contents = await readFile(fullPath, "utf8");
		if (!args.noTrim) contents = contents.trim();
		if (args.lines) {
			const groups = /^(?<startLine>\d+)?:(?<endLine>\d+)?$/.exec(args.lines)?.groups;
			if (!groups) throw new Error("invalid lines format");
			const lines = contents.split("\n");
			const startLine = Number(groups.startLine) || 1;
			const endLine = Number(groups.endLine) || lines.length;
			if (startLine < 1) throw new Error("first line's index can not be smaller than 1");
			contents = lines.slice(startLine - 1, endLine).join("\n");
		}
		if (args.code) contents = render.codeBlock(contents, args.lang || extname(fullPath).slice(1), { ext: args.name === false ? void 0 : typeof args.name === "string" ? args.name : `[${basename(fullPath)}]` });
		return { contents };
	}
});
const PROVIDERS = {
	CONTRIB_ROCKS: "contrib.rocks",
	MARKUPGO: "markupgo"
};
const contributors = defineGenerator({
	name: "contributors",
	async generate({ config, args }) {
		const { github } = await getPkg(config.dir, args);
		const provider = args.provider || PROVIDERS.CONTRIB_ROCKS;
		if (!github) throw new Error("`github` is required!");
		const lines = [];
		if (typeof args.license === "string") lines.push(`Published under the [${args.license.toUpperCase()}](https://github.com/${github}/blob/main/LICENSE) license.`);
		let madeBy = `[community](https://github.com/${github}/graphs/contributors) 💛`;
		if (typeof args.author === "string") {
			const authors = args.author.split(",").map((author) => author.trim()).map((user) => `[@${user}](https://github.com/${user})`).join(", ");
			if (authors.length > 0) madeBy = `${authors} and ${madeBy}`;
		}
		lines.push(`Made by ${madeBy}`);
		if (provider === PROVIDERS.MARKUPGO) {
			const params = [];
			args = {
				circleSize: "64",
				center: "true",
				...args
			};
			if (Number(args.max) >= 0) params.push(["count", args.max]);
			if (Number(args.width)) params.push(["width", args.width]);
			if (Number(args.circleSize)) params.push(["circleSize", args.circleSize]);
			if (Number(args.circleRadius)) params.push(["circleRadius", args.circleRadius]);
			if (Number(args.circleSpacing)) params.push(["circleSpacing", args.circleSpacing]);
			if (args.center) params.push(["center", Boolean(args.center).toString()]);
			if (!args.markupGoLogo) params.push(["removeLogo", "true"]);
			if (args.anon) params.push(["anon", Boolean(args.anon).toString()]);
			let paramsStr = params.map(([k, v]) => `${k}=${v}`).join("&");
			paramsStr = paramsStr ? `?${paramsStr}` : "";
			lines.push(`<br><br>`, `<a href="https://github.com/${github}/graphs/contributors">`, `<img src="https://markupgo.com/github/${github}/contributors${paramsStr}" />`, `</a>`);
		} else {
			const params = [["repo", github]];
			if (args.max) params.push(["max", args.max]);
			if (args.anon) params.push(["anon", args.anon]);
			const paramsStr = params.map(([k, v]) => `${k}=${v}`).join("&");
			lines.push(`<br><br>`, `<a href="https://github.com/${github}/graphs/contributors">`, `<img src="https://contrib.rocks/image?${paramsStr}" />`, `</a>`);
		}
		return { contents: lines.join("\n") };
	}
});
const DEFAULT_IGNORE = [
	"node_modules",
	".git",
	".DS_Store",
	".nuxt",
	".output",
	".nitro",
	"dist",
	"coverage",
	".cache",
	".turbo"
];
async function parseGitignore(dir) {
	try {
		return (await readFile(join(dir, ".gitignore"), "utf8")).split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#"));
	} catch {
		return [];
	}
}
function shouldIgnore(name, ignorePatterns, defaultIgnore) {
	const allPatterns = [...defaultIgnore, ...ignorePatterns];
	for (const pattern of allPatterns) {
		if (name === pattern.replace(/^\//, "").replace(/\/$/, "")) return true;
		if (pattern.startsWith("*") && name.endsWith(pattern.slice(1))) return true;
		if (pattern.endsWith("*") && name.startsWith(pattern.slice(0, -1))) return true;
	}
	return false;
}
async function buildTree(dir, ignorePatterns, maxDepth, currentDepth = 0) {
	if (maxDepth > 0 && currentDepth >= maxDepth) return [];
	const entries = await readdir(dir);
	const result = [];
	for (const entry of entries) {
		if (shouldIgnore(entry, ignorePatterns, DEFAULT_IGNORE)) continue;
		const fullPath = join(dir, entry);
		const isDirectory = (await stat(fullPath)).isDirectory();
		const treeEntry = {
			name: entry,
			isDirectory
		};
		if (isDirectory) treeEntry.children = await buildTree(fullPath, ignorePatterns, maxDepth, currentDepth + 1);
		result.push(treeEntry);
	}
	result.sort((a, b) => {
		if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1;
		return a.name.localeCompare(b.name);
	});
	return result;
}
function renderTree(entries, isLast = []) {
	const lines = [];
	for (let i = 0; i < entries.length; i++) {
		const entry = entries[i];
		const isLastEntry = i === entries.length - 1;
		let linePrefix = "";
		for (const element_ of isLast) linePrefix += element_ ? "    " : "│   ";
		const connector = isLastEntry ? "└── " : "├── ";
		const suffix = entry.isDirectory ? "/" : "";
		lines.push(`${linePrefix}${connector}${entry.name}${suffix}`);
		if (entry.children && entry.children.length > 0) {
			const childLines = renderTree(entry.children, [...isLast, isLastEntry]);
			lines.push(...childLines);
		}
	}
	return lines;
}
const dirTree = defineGenerator({
	name: "dir-tree",
	async generate({ args, config, url }) {
		const srcPath = args.src || ".";
		const fullPath = resolvePath$1(srcPath, {
			url,
			dir: config.dir
		});
		if (!(await stat(fullPath)).isDirectory()) throw new Error(`Path "${srcPath}" is not a directory`);
		const userIgnore = args.ignore ? String(args.ignore).split(",").map((s) => s.trim()) : [];
		return { contents: "```\n" + renderTree(await buildTree(fullPath, [...await parseGitignore(fullPath), ...userIgnore], args.maxDepth ? Number(args.maxDepth) : 0)).join("\n") + "\n```" };
	}
});
var generators_default = {
	jsdocs,
	badges,
	"pm-i": pmInstall,
	"pm-install": pmInstall,
	"pm-x": pmX,
	fetch,
	file,
	jsimport,
	"with-automd": withAutomd,
	contributors,
	"dir-tree": dirTree
};
function findBlocks(md, config = {}) {
	const blocks = [];
	for (const match of md.matchAll(new RegExp(`^(?<open><!--\\s*(${config.prefix.join("|")}):(?<generator>.+?)\\s+(?<args>.*?)\\s*-->)(?<contents>.+?)(?<close>^<!--\\s*\\/(${config.prefix.join("|")})\\s*-->)`, "gimsu"))) {
		if (match.index === void 0 || !match.groups) continue;
		const start = match.index + match.groups.open.length || 0;
		const end = start + match.groups.contents.length;
		blocks.push({
			generator: match.groups.generator,
			rawArgs: match.groups.args,
			contents: match.groups.contents,
			loc: {
				start,
				end
			},
			_loc: {
				start: match.index,
				end: match.index + match[0].length
			}
		});
	}
	return blocks;
}
function containsAutomd(md, config = {}) {
	return new RegExp(`^<!--\\s*(${config.prefix.join("|")}):`, "gimsu").test(md);
}
function parseRawArgs(rawArgs) {
	const args = Object.create(null);
	for (const part of rawArgs.split(/\s+/)) {
		const [_key, value] = part.split("=");
		const key = _key && camelCase(_key);
		if (key && value) args[key] = destr(value);
		else if (part.startsWith("no-")) args[part.slice(3)] = false;
		else args[part] = true;
	}
	return args;
}
const RESOLVED_CONFIG_SYMBOL = Symbol("automdConfig");
function resolveConfig(config) {
	if (config && RESOLVED_CONFIG_SYMBOL in config) return config;
	const _config = {
		dir: ".",
		input: "README.md",
		generators: {},
		[RESOLVED_CONFIG_SYMBOL]: true,
		...config
	};
	_config.prefix = _config.prefix || [];
	if (typeof _config.prefix === "string") _config.prefix = [_config.prefix];
	if (!_config.prefix.includes("automd")) _config.prefix.push("automd");
	if (!_config.prefix.includes("powerlines")) _config.prefix.push("powerlines");
	_config.dir = resolve(_config.dir);
	_config.input = (Array.isArray(_config.input) ? _config.input : [_config.input]).filter(Boolean);
	return _config;
}
async function loadConfig(dir = ".", overrides) {
	const { loadConfig: loadConfig$1 } = await import("c12");
	dir = resolve(dir);
	const { config } = await loadConfig$1({
		cwd: dir,
		name: "automd",
		dotenv: true,
		overrides,
		defaults: {
			ignore: [
				"**/node_modules",
				"**/dist",
				"**/.*"
			],
			dir
		}
	});
	return resolveConfig(config);
}
async function transform(contents, _config, url) {
	const start = performance.now();
	const config = resolveConfig(_config);
	const editor = new MagicString(contents);
	const updates = [];
	const generators = {
		...generators_default,
		...config.generators
	};
	const blocks = findBlocks(contents, config);
	for (const block of blocks) {
		const result = await _transformBlock(block, config, generators, url);
		if (result.unwrap) editor.overwrite(block._loc.start, block._loc.end, `${result.contents.trim()}`);
		else editor.overwrite(block.loc.start, block.loc.end, `\n\n${result.contents.trim()}\n\n`);
		updates.push({
			block,
			result
		});
	}
	const hasChanged = editor.hasChanged();
	const hasIssues = updates.some((u) => u.result.issues?.filter(Boolean).length);
	const time = performance.now() - start;
	return {
		hasChanged,
		hasIssues,
		contents: hasChanged ? editor.toString() : contents,
		updates,
		time
	};
}
async function _transformBlock(block, config, generators, url) {
	const args = parseRawArgs(block.rawArgs);
	const generator = generators[block.generator];
	if (!generator) {
		const suggestions = (await import("../../../../didyoumean2@7.0.4/node_modules/didyoumean2/dist/index.mjs").then((r) => r.default || r))(block.generator, Object.keys(generators));
		const error = `Unknown generator:\`${block.generator}\`.${suggestions ? ` Did you mean "generator:\`${suggestions}\`"?` : ""}`;
		return {
			contents: `<!-- ⚠️  ${error} -->`,
			issues: [error]
		};
	}
	const context = {
		args,
		config,
		block,
		transform: (contents) => transform(contents, config, url),
		url
	};
	try {
		const result = await generator.generate(context);
		if (!result.unwrap && containsAutomd(result.contents, config)) result.unwrap = true;
		if (result.unwrap) {
			const nestedRes = await context.transform(result.contents);
			result.contents = nestedRes.contents;
			if (nestedRes.hasIssues) result.issues = [...result.issues || [], ...nestedRes.updates.flatMap((u) => u.result.issues || [])].filter(Boolean);
		}
		return result;
	} catch (error) {
		return {
			contents: `<!-- ⚠️  (${block.generator}) ${error.message || error} -->`,
			issues: [error]
		};
	}
}

//#endregion
export { loadConfig, resolveConfig, transform };
//# sourceMappingURL=index.mjs.map