import { d as EMPTY_DATA_URI } from "./constants-DgZl8nng.js";
import { C as pathEquals, S as pathContains, a as cwd, j as toError, t as DetailError, w as prettifySchemaError, x as parseJsonc, z as Logger } from "./util-CsmUMRtR.js";
import { E as VivliostyleInlineConfig, T as VivliostyleConfigSchema } from "./schema-DFj2EinN.js";
import { createRequire } from "node:module";
import * as v from "valibot";
import upath from "upath";
import fs from "node:fs";
import { cyan, underline } from "yoctocolors";
import { pathToFileURL } from "node:url";
import terminalLink from "terminal-link";
import { glob } from "tinyglobby";
import { copy } from "fs-extra/esm";
import picomatch from "picomatch";
//#region src/commands/cli-flags.ts
function createParserProgram({ setupProgram, parseArgs }) {
	return (argv) => {
		const program = setupProgram();
		program.parse(argv);
		let options = program.opts();
		options = parseArgs?.(options, program.args ?? []) ?? options;
		options = warnDeprecatedFlags(options);
		return v.parse(VivliostyleInlineConfig, options);
	};
}
function setupConfigFromFlags(flags) {
	if (!flags.input) {
		if (flags.enableViewerStartPage) return {
			tasks: [{ entry: [] }],
			inlineOptions: { input: {
				format: "webbook",
				entry: EMPTY_DATA_URI
			} }
		};
		throw new Error("No input is set. Please set an appropriate entry or a Vivliostyle config file.");
	}
	return {
		tasks: [{ entry: [] }],
		inlineOptions: { ...flags }
	};
}
function warnDeprecatedFlags(options) {
	return { ...options };
}
//#endregion
//#region src/config/load.ts
const require = createRequire(import.meta.url);
function locateVivliostyleConfig({ config, cwd: cwd$1 = cwd }) {
	if (config) return upath.resolve(cwd$1, config);
	return [
		".js",
		".mjs",
		".cjs",
		".ts",
		".mts",
		".cts",
		".json"
	].map((ext) => upath.join(cwd$1, `vivliostyle.config${ext}`)).find((p) => fs.existsSync(p));
}
async function loadVivliostyleConfig({ config, configData, cwd: cwd$2 }) {
	if (configData) return v.parse(VivliostyleConfigSchema, configData);
	const absPath = locateVivliostyleConfig({
		config,
		cwd: cwd$2
	});
	if (!absPath) return;
	let parsedConfig;
	let jsonRaw;
	try {
		if (upath.extname(absPath) === ".json") {
			jsonRaw = fs.readFileSync(absPath, "utf8");
			parsedConfig = parseJsonc(jsonRaw);
		} else {
			Reflect.deleteProperty(require.cache, require.resolve(absPath));
			const url = pathToFileURL(absPath);
			url.search = `version=${Date.now()}`;
			parsedConfig = (await import(
				/* @vite-ignore */
				url.href
)).default;
			jsonRaw = JSON.stringify(parsedConfig, null, 2);
		}
	} catch (error) {
		const thrownError = toError(error);
		throw new DetailError(`An error occurred on loading a config file: ${absPath}`, thrownError.stack ?? thrownError.message);
	}
	const result = v.safeParse(VivliostyleConfigSchema, parsedConfig);
	if (result.success) {
		const { tasks, inlineOptions } = result.output;
		return {
			tasks,
			inlineOptions: {
				...inlineOptions,
				cwd: cwd$2 ?? cwd,
				config: absPath
			}
		};
	}
	const errorString = prettifySchemaError(jsonRaw, result.issues);
	throw new DetailError(`Validation of vivliostyle config failed. Please check the schema: ${config}`, errorString);
}
function warnDeprecatedConfig(config) {
	if (config.tasks.some((task) => task.includeAssets)) Logger.logWarn("'includeAssets' property of Vivliostyle config was deprecated and will be removed in a future release. Please use 'copyAsset.includes' property instead.");
	if (config.tasks.some((task) => task.tocTitle)) Logger.logWarn("'tocTitle' property of Vivliostyle config was deprecated and will be removed in a future release. Please use 'toc.title' property instead.");
	if (config.tasks.some((task) => task.http)) Logger.logWarn("'http' property of Vivliostyle config was deprecated and will be removed in a future release. This option is enabled by default, and the file protocol is no longer supported.");
	if (config.tasks.some((task) => task.pressReady !== void 0)) Logger.logWarn("'pressReady' property of Vivliostyle config was deprecated and will be removed in a future release. Please use 'pdfPostprocess.preflight: \"press-ready\"' property instead.");
	if (config.tasks.some((task) => task.output && [task.output].flat().some((o) => o.preflight))) Logger.logWarn("'preflight' property of output config was deprecated and will be removed in a future release. Please use 'pdfPostprocess.preflight' property instead.");
	if (config.tasks.some((task) => task.output && [task.output].flat().some((o) => o.preflightOption))) Logger.logWarn("'preflightOption' property of output config was deprecated and will be removed in a future release. Please use 'pdfPostprocess.preflightOption' property instead.");
	if (config.inlineOptions.renderMode === "docker" || config.tasks.some((task) => task.output && [task.output].flat().some((o) => o.renderMode === "docker"))) {
		const issueUrl = "https://github.com/vivliostyle/vivliostyle-cli/issues/823";
		const issueLinkText = underline(issueUrl);
		const issueLink = terminalLink(issueLinkText, issueUrl, { fallback: () => issueLinkText });
		Logger.logWarn(`'renderMode: docker' option was deprecated and may be removed in a future major release.\n${cyan(`     See ${issueLink} for details and to share your feedback.`)}`);
	}
}
//#endregion
//#region \0@oxc-project+runtime@0.137.0/helpers/esm/usingCtx.js
function _usingCtx() {
	var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
		var n = Error();
		return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
	}, e = {}, n = [];
	function using(r, e) {
		if (null != e) {
			if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
			if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
			if (void 0 === o && (o = e[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
			if ("function" != typeof o) throw new TypeError("Object is not disposable.");
			t && (o = function o() {
				try {
					t.call(e);
				} catch (r) {
					return Promise.reject(r);
				}
			}), n.push({
				v: e,
				d: o,
				a: r
			});
		} else r && n.push({
			d: e,
			a: r
		});
		return e;
	}
	return {
		e,
		u: using.bind(null, !1),
		a: using.bind(null, !0),
		d: function d() {
			var o, t = this.e, s = 0;
			function next() {
				for (; o = n.pop();) try {
					if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
					if (o.d) {
						var r = o.d.call(o.v);
						if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
					} else s |= 1;
				} catch (r) {
					return err(r);
				}
				if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
				if (t !== e) throw t;
			}
			function err(n) {
				return t = t !== e ? new r(n, t) : n, next();
			}
			return next();
		}
	};
}
//#endregion
//#region src/processor/asset.ts
var GlobMatcher = class {
	#matchers;
	constructor(matcherConfig) {
		this.matcherConfig = matcherConfig;
		this.#matchers = matcherConfig.map(({ patterns, ...options }) => picomatch(patterns, options));
	}
	match(test) {
		return this.#matchers.some((matcher) => matcher(test));
	}
	async glob(globOptions = {}) {
		return new Set((await Promise.all(this.matcherConfig.map((config) => glob({
			...config,
			...globOptions
		})))).flat());
	}
};
function getIgnoreThemeDirectoryPatterns({ themesDir, cwd }) {
	return pathContains(cwd, themesDir) ? [`${upath.relative(cwd, themesDir)}/node_modules/*/example`, `${upath.relative(cwd, themesDir)}/node_modules/*/*/example`] : [];
}
function getIgnoreAssetPatterns({ outputs, entries, cwd }) {
	return [...outputs.flatMap(({ format, path: p }) => pathContains(cwd, p) ? format === "webpub" ? upath.join(upath.relative(cwd, p), "**") : upath.relative(cwd, p) : []), ...entries.flatMap(({ template }) => {
		return template?.type === "file" && pathContains(cwd, template.pathname) ? upath.relative(cwd, template.pathname) : [];
	})];
}
function getWebPubResourceMatcher({ outputs, themesDir, entries, cwd, manifestPath, copyAsset: { fileExtensions }, additionalPatterns = [] }) {
	return new GlobMatcher([{
		patterns: [
			`**/${upath.relative(cwd, manifestPath)}`,
			"**/*.{html,htm,xhtml,xht}",
			`**/*.{${fileExtensions.join(",")}}`,
			...additionalPatterns
		],
		ignore: [
			...getIgnoreAssetPatterns({
				cwd,
				outputs,
				entries
			}),
			...getIgnoreThemeDirectoryPatterns({
				cwd,
				themesDir
			}),
			"node_modules/**",
			"**/.!(vs-*)/**"
		],
		dot: true,
		cwd
	}]);
}
function getAssetMatcher({ copyAsset: { fileExtensions, includes, excludes }, outputs, themesDir, entries, cwd, ignore = [] }) {
	const ignorePatterns = [
		...ignore,
		...excludes,
		...getIgnoreAssetPatterns({
			outputs,
			entries,
			cwd
		})
	];
	return new GlobMatcher([{
		patterns: fileExtensions.map((ext) => `**/*.${ext}`),
		ignore: [
			"**/node_modules/**",
			...ignorePatterns,
			...getIgnoreThemeDirectoryPatterns({
				themesDir,
				cwd
			})
		],
		cwd
	}, {
		patterns: includes,
		ignore: ignorePatterns,
		cwd
	}]);
}
async function copyAssets({ entryContextDir, workspaceDir, copyAsset, outputs, themesDir, entries }) {
	if (pathEquals(entryContextDir, workspaceDir)) return;
	const relWorkspaceDir = upath.relative(entryContextDir, workspaceDir);
	const assets = await getAssetMatcher({
		copyAsset,
		cwd: entryContextDir,
		outputs,
		themesDir,
		entries,
		ignore: relWorkspaceDir ? [upath.join(relWorkspaceDir, "**")] : []
	}).glob({ followSymbolicLinks: true });
	Logger.debug("assets", assets);
	for (const asset of assets) {
		const target = upath.join(workspaceDir, asset);
		fs.mkdirSync(upath.dirname(target), { recursive: true });
		await copy(upath.resolve(entryContextDir, asset), target);
	}
}
//#endregion
export { _usingCtx as a, warnDeprecatedConfig as c, getWebPubResourceMatcher as i, createParserProgram as l, copyAssets as n, loadVivliostyleConfig as o, getAssetMatcher as r, locateVivliostyleConfig as s, GlobMatcher as t, setupConfigFromFlags as u };

//# sourceMappingURL=asset-DBj3nifv.js.map