@dev-pi2pie/word-counter 0.1.5-canary.5 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/bin.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bin.mjs","names":["isRecord","ensureObject","stripInlineComment","resolvePath","pc","pc","resolveLatinHintRules","HARD_BOUNDARY_REGEX","LATIN_PROMOTION_BREAK_REGEX","findLastLatinPromotionBreakIndex","mergeAdjacentChunks","getNonWordTotal","collectNonWordsAggregate","normalizeText","buildPerKeyItems","wordCounter","buildSingleItem","sumTotals","wordCounter","resolvePath","resolvePath","emitConfigNotes","pc","resolvePath","pc","wordCounter","wordCounter","wordCounter","pc","relative","relativePath","pc","wordCounter","pc"],"sources":["../../src/cli/config/schema.ts","../../src/cli/config/discover.ts","../../src/cli/config/apply.ts","../../src/cli/total-of.ts","../../src/cli/config/errors.ts","../../src/cli/config/normalize.ts","../../src/cli/config/env.ts","../../src/cli/config/merge.ts","../../src/cli/config/jsonc.ts","../../src/cli/config/toml-tokens.ts","../../src/cli/config/toml.ts","../../src/cli/config/parse.ts","../../src/cli/config/resolve.ts","../../src/cli/config/sources.ts","../../src/cli/debug/channel.ts","../../node_modules/picocolors/picocolors.js","../../src/cli/program/version-embedded.ts","../../src/cli/batch/jobs/limits.ts","../../src/cli/batch/jobs/load-count-worker.ts","../../src/cli/doctor/checks.ts","../../src/cli/doctor/render.ts","../../src/cli/doctor/run.ts","../../src/markdown/toml/arrays.ts","../../src/markdown/toml/keys.ts","../../src/markdown/toml/strings.ts","../../src/markdown/toml/values.ts","../../src/markdown/toml/parse-frontmatter.ts","../../src/markdown/parse-markdown.ts","../../src/wc/segmenter.ts","../../src/utils/append-all.ts","../../src/wc/non-words.ts","../../src/wc/analyze.ts","../../src/wc/mode.ts","../../src/wc/latin-hints.ts","../../src/wc/locale-detect.ts","../../src/wc/segment.ts","../../src/wc/wc.ts","../../src/wc/index.ts","../../src/markdown/section-count.ts","../../src/detector/debug.ts","../../src/detector/inspect-helpers.ts","../../src/detector/none.ts","../../src/detector/result-builder.ts","../../src/detector/sections.ts","../../src/detector/policy.ts","../../src/detector/wasm-inspect.ts","../../src/detector/whatlang-map.ts","../../src/detector/wasm-presegment.ts","../../src/detector/whatlang-wasm.ts","../../src/detector/wasm-engine.ts","../../src/detector/wasm-resolution.ts","../../src/detector/wasm-windows.ts","../../src/detector/wasm.ts","../../src/detector/inspect.ts","../../src/detector/index.ts","../../src/cli/path/filter.ts","../../src/cli/path/load.ts","../../src/cli/path/resolve-debug.ts","../../src/cli/path/resolve-directory.ts","../../src/cli/path/resolve.ts","../../src/cli/runtime/options.ts","../../src/cli/inspect/input.ts","../../src/cli/inspect/render.ts","../../src/cli/inspect/batch.ts","../../src/cli/inspect/help.ts","../../src/cli/inspect/parse.ts","../../src/cli/inspect/single.ts","../../src/cli/inspect/run.ts","../../src/cli/program/options.ts","../../src/cli/program/version.ts","../../src/cli/batch/aggregate-compact.ts","../../src/cli/batch/aggregate-word-counter.ts","../../src/cli/batch/aggregate-sections.ts","../../src/cli/batch/aggregate.ts","../../src/cli/batch/jobs/queue.ts","../../src/cli/batch/jobs/read-input.ts","../../src/cli/batch/jobs/load-count.ts","../../src/cli/batch/jobs/render.ts","../../src/cli/progress/reporter.ts","../../src/cli/batch/run.ts","../../src/cli/batch/jobs/strategy.ts","../../src/cli/output/debug-json.ts","../../src/utils/show-singular-or-plural-word.ts","../../src/cli/output/render.ts","../../src/cli/output/normalize-base.ts","../../src/cli/runtime/batch.ts","../../src/cli/runtime/input.ts","../../src/cli/runtime/single.ts","../../src/command.ts","../../src/bin.ts"],"sourcesContent":["import type { DetectorContentGateMode, DetectorMode } from \"../../detector\";\nimport type { TotalOfPart } from \"../total-of\";\nimport type { PathMode } from \"../types\";\nimport type { ConfigFormat, ConfigLogLevel, ConfigLogVerbosity, ConfigProgressMode } from \"./types\";\n\nexport const CONFIG_FILE_BASENAME = \"wc-intl-seg.config\";\nexport const CONFIG_FORMAT_PRIORITY: readonly ConfigFormat[] = [\"toml\", \"jsonc\", \"json\"];\nexport const CONFIG_FILENAMES = CONFIG_FORMAT_PRIORITY.map(\n (format) => `${CONFIG_FILE_BASENAME}.${format}`,\n);\n\nexport const CONFIG_DETECTOR_VALUES: readonly DetectorMode[] = [\"regex\", \"wasm\"];\nexport const CONFIG_CONTENT_GATE_MODE_VALUES: readonly DetectorContentGateMode[] = [\n \"default\",\n \"strict\",\n \"loose\",\n \"off\",\n];\nexport const CONFIG_PATH_MODE_VALUES: readonly PathMode[] = [\"auto\", \"manual\"];\nexport const CONFIG_PROGRESS_MODE_VALUES: readonly ConfigProgressMode[] = [\"auto\", \"on\", \"off\"];\nexport const CONFIG_LOG_LEVEL_VALUES: readonly ConfigLogLevel[] = [\"info\", \"debug\"];\nexport const CONFIG_LOG_VERBOSITY_VALUES: readonly ConfigLogVerbosity[] = [\"compact\", \"verbose\"];\n\nexport const CONFIG_TOTAL_OF_VALUES: readonly TotalOfPart[] = [\n \"words\",\n \"emoji\",\n \"symbols\",\n \"punctuation\",\n \"whitespace\",\n];\n","import { stat } from \"node:fs/promises\";\nimport { join, win32 } from \"node:path\";\nimport { CONFIG_FILE_BASENAME, CONFIG_FILENAMES, CONFIG_FORMAT_PRIORITY } from \"./schema\";\nimport type {\n ConfigDiscoveryResult,\n ConfigFormat,\n ConfigScope,\n DiscoverConfigOptions,\n DiscoveredConfigFile,\n ResolveConfigDirectoryOptions,\n} from \"./types\";\n\ntype UserConfigDirectoryCandidate = {\n directory: string;\n kind: \"primary\" | \"legacy-macos\" | \"legacy-windows\";\n};\n\nasync function fileExists(path: string): Promise<boolean> {\n try {\n const metadata = await stat(path);\n return metadata.isFile();\n } catch {\n return false;\n }\n}\n\nfunction createIgnoredSiblingNote(\n scope: ConfigScope,\n selectedPath: string,\n ignoredSiblingPaths: string[],\n): string | undefined {\n if (ignoredSiblingPaths.length === 0) {\n return undefined;\n }\n\n return [\n `Using ${scope} config file \"${selectedPath}\".`,\n `Ignoring lower-priority sibling config files: ${ignoredSiblingPaths.join(\", \")}.`,\n ].join(\" \");\n}\n\nexport function resolveUserConfigDirectory(\n options: ResolveConfigDirectoryOptions = {},\n): string | undefined {\n return resolveUserConfigDirectories(options)[0]?.directory;\n}\n\nfunction resolveUserConfigDirectories(\n options: ResolveConfigDirectoryOptions = {},\n): UserConfigDirectoryCandidate[] {\n const platform = options.platform ?? process.platform;\n const env = options.env ?? process.env;\n const homeDir = env.HOME ?? env.USERPROFILE;\n\n if (platform === \"win32\") {\n const candidates: UserConfigDirectoryCandidate[] = [];\n if (homeDir) {\n candidates.push({\n directory: win32.join(homeDir, \".config\"),\n kind: \"primary\",\n });\n }\n if (env.APPDATA) {\n candidates.push({\n directory: env.APPDATA,\n kind: \"legacy-windows\",\n });\n }\n return candidates;\n }\n\n if (platform === \"darwin\") {\n const candidates: UserConfigDirectoryCandidate[] = [];\n if (env.XDG_CONFIG_HOME) {\n candidates.push({\n directory: env.XDG_CONFIG_HOME,\n kind: \"primary\",\n });\n }\n if (homeDir) {\n candidates.push({\n directory: join(homeDir, \".config\"),\n kind: \"primary\",\n });\n candidates.push({\n directory: join(homeDir, \"Library\", \"Application Support\"),\n kind: \"legacy-macos\",\n });\n }\n return candidates;\n }\n\n const directory = env.XDG_CONFIG_HOME ?? (homeDir ? join(homeDir, \".config\") : undefined);\n return directory\n ? [\n {\n directory,\n kind: \"primary\",\n },\n ]\n : [];\n}\n\nexport async function discoverConfigFileInDirectory(\n directory: string,\n scope: ConfigScope,\n): Promise<DiscoveredConfigFile | undefined> {\n const existing: Array<{ format: ConfigFormat; path: string }> = [];\n\n for (const format of CONFIG_FORMAT_PRIORITY) {\n const path = join(directory, `${CONFIG_FILE_BASENAME}.${format}`);\n if (await fileExists(path)) {\n existing.push({ format, path });\n }\n }\n\n if (existing.length === 0) {\n return undefined;\n }\n\n const selected = existing[0]!;\n const ignoredSiblingPaths = existing.slice(1).map((item) => item.path);\n const note = createIgnoredSiblingNote(scope, selected.path, ignoredSiblingPaths);\n\n return {\n scope,\n directory,\n path: selected.path,\n format: selected.format,\n ignoredSiblingPaths,\n notes: note ? [note] : [],\n };\n}\n\nexport async function discoverConfigFiles(\n options: DiscoverConfigOptions = {},\n): Promise<ConfigDiscoveryResult> {\n const cwd = options.cwd ?? process.cwd();\n const userDirectories = resolveUserConfigDirectories(options);\n\n const currentWorkingDirectory = await discoverConfigFileInDirectory(cwd, \"cwd\");\n let user: DiscoveredConfigFile | undefined;\n const discoveredFallbackUsers: DiscoveredConfigFile[] = [];\n\n for (const candidate of userDirectories) {\n const discovered = await discoverConfigFileInDirectory(candidate.directory, \"user\");\n if (!discovered) {\n continue;\n }\n\n if (!user) {\n user = discovered;\n if (candidate.kind === \"legacy-macos\") {\n user.notes.push(\n `Using legacy macOS user config location \"${discovered.directory}\". Migrate this config to \"${resolveUserConfigDirectory(options)}\" to follow the current default path.`,\n );\n }\n if (candidate.kind === \"legacy-windows\") {\n user.notes.push(\n `Using legacy Windows user config location \"${discovered.directory}\". Migrate this config to \"${resolveUserConfigDirectory(options)}\" to follow the current default path.`,\n );\n }\n continue;\n }\n\n discoveredFallbackUsers.push(discovered);\n }\n\n if (user) {\n for (const fallback of discoveredFallbackUsers) {\n user.notes.push(\n `Ignoring fallback user config file \"${fallback.path}\" because a higher-priority user config file was found at \"${user.path}\".`,\n );\n }\n }\n\n return {\n ...(user ? { user } : {}),\n ...(currentWorkingDirectory ? { cwd: currentWorkingDirectory } : {}),\n };\n}\n\nexport { CONFIG_FILENAMES };\n","import type { CliActionOptions } from \"../runtime/types\";\nimport type { ParsedInspectInvocation } from \"../inspect/types\";\nimport type { WordCounterConfig } from \"./types\";\n\nexport type CountCliSources = {\n detector: boolean;\n contentGate: boolean;\n pathMode: boolean;\n recursive: boolean;\n includeExt: boolean;\n excludeExt: boolean;\n totalOf: boolean;\n debug: boolean;\n verbose: boolean;\n debugReport: boolean;\n debugReportTee: boolean;\n progress: boolean;\n quietSkips: boolean;\n};\n\nfunction withConfigQuietSkips(\n currentQuietSkips: boolean | undefined,\n skippedFiles: boolean | undefined,\n): boolean | undefined {\n if (skippedFiles === undefined) {\n return currentQuietSkips;\n }\n\n return skippedFiles ? false : true;\n}\n\nexport function applyConfigToCountOptions(\n options: CliActionOptions,\n config: WordCounterConfig,\n sources: CountCliSources,\n): CliActionOptions {\n const next: CliActionOptions = { ...options };\n\n if (!sources.detector && config.detector !== undefined) {\n next.detector = config.detector;\n }\n\n if (!sources.contentGate && config.contentGate?.mode !== undefined) {\n next.contentGate = config.contentGate.mode;\n }\n\n if (!sources.pathMode && config.path?.mode !== undefined) {\n next.pathMode = config.path.mode;\n }\n\n if (!sources.recursive && config.path?.recursive !== undefined) {\n next.recursive = config.path.recursive;\n }\n\n next.pathDetectBinary = config.path?.detectBinary ?? next.pathDetectBinary ?? true;\n\n if (!sources.includeExt && config.path?.includeExtensions !== undefined) {\n next.includeExt = [...config.path.includeExtensions];\n }\n\n if (!sources.excludeExt && config.path?.excludeExtensions !== undefined) {\n next.excludeExt = [...config.path.excludeExtensions];\n }\n\n if (!sources.totalOf && config.output?.totalOf !== undefined) {\n next.totalOf = [...config.output.totalOf];\n }\n\n if (!sources.debug && config.logging?.level !== undefined) {\n next.debug = config.logging.level === \"debug\";\n }\n\n const debugEnabled = next.debug === true;\n\n if (debugEnabled && !sources.verbose && config.logging?.verbosity !== undefined) {\n next.verbose = config.logging.verbosity === \"verbose\";\n }\n\n if (debugEnabled && !sources.debugReport && config.reporting?.debugReport?.path !== undefined) {\n next.debugReport = config.reporting.debugReport.path;\n }\n\n const debugReportEnabled = next.debugReport !== undefined && next.debugReport !== false;\n\n if (\n debugEnabled &&\n debugReportEnabled &&\n !sources.debugReportTee &&\n config.reporting?.debugReport?.tee !== undefined\n ) {\n next.debugReportTee = config.reporting.debugReport.tee;\n }\n\n if (!sources.progress && config.progress?.mode !== undefined) {\n next.progressMode = config.progress.mode;\n }\n\n if (!sources.quietSkips) {\n next.quietSkips = withConfigQuietSkips(next.quietSkips, config.reporting?.skippedFiles);\n }\n\n return next;\n}\n\nexport function applyConfigToInspectInvocation(\n validated: ParsedInspectInvocation,\n config: WordCounterConfig,\n): ParsedInspectInvocation {\n const next: ParsedInspectInvocation = {\n ...validated,\n includeExt: [...validated.includeExt],\n excludeExt: [...validated.excludeExt],\n sources: { ...validated.sources },\n };\n\n const detectorFromConfig = config.inspect?.detector ?? config.detector;\n if (!next.sources.detector && detectorFromConfig !== undefined) {\n next.detector = detectorFromConfig;\n }\n\n const contentGateFromConfig = config.inspect?.contentGate?.mode ?? config.contentGate?.mode;\n if (!next.sources.contentGate && contentGateFromConfig !== undefined) {\n next.contentGateMode = contentGateFromConfig;\n }\n\n if (!next.sources.pathMode && config.path?.mode !== undefined) {\n next.pathMode = config.path.mode;\n }\n\n if (!next.sources.recursive && config.path?.recursive !== undefined) {\n next.recursive = config.path.recursive;\n }\n\n next.pathDetectBinary = config.path?.detectBinary ?? next.pathDetectBinary ?? true;\n\n if (!next.sources.includeExt && config.path?.includeExtensions !== undefined) {\n next.includeExt = [...config.path.includeExtensions];\n }\n\n if (!next.sources.excludeExt && config.path?.excludeExtensions !== undefined) {\n next.excludeExt = [...config.path.excludeExtensions];\n }\n\n return next;\n}\n","import type { SectionedResult } from \"../markdown\";\nimport type { NonWordCollection, WordCounterResult } from \"../wc\";\n\nexport const TOTAL_OF_PARTS = Object.freeze([\n \"words\",\n \"emoji\",\n \"symbols\",\n \"punctuation\",\n \"whitespace\",\n] as const);\n\nexport type TotalOfPart = (typeof TOTAL_OF_PARTS)[number];\n\nexport type TotalOfOverride = {\n parts: TotalOfPart[];\n total: number;\n};\n\ntype TotalOfCounts = Record<TotalOfPart, number>;\n\nconst TOTAL_OF_PART_ALIASES: Record<string, TotalOfPart> = {\n word: \"words\",\n words: \"words\",\n emoji: \"emoji\",\n emojis: \"emoji\",\n symbol: \"symbols\",\n symbols: \"symbols\",\n punction: \"punctuation\",\n punctuation: \"punctuation\",\n whitespace: \"whitespace\",\n};\n\nfunction createTotalOfCounts(): TotalOfCounts {\n return {\n words: 0,\n emoji: 0,\n symbols: 0,\n punctuation: 0,\n whitespace: 0,\n };\n}\n\nfunction collectNonWordCounts(\n target: TotalOfCounts,\n nonWords: NonWordCollection | undefined,\n): void {\n if (!nonWords) {\n return;\n }\n\n target.emoji += nonWords.counts.emoji;\n target.symbols += nonWords.counts.symbols;\n target.punctuation += nonWords.counts.punctuation;\n target.whitespace += nonWords.counts.whitespace ?? 0;\n}\n\nfunction collectFromWordCounterResult(result: WordCounterResult): TotalOfCounts {\n const counts = createTotalOfCounts();\n counts.words += result.counts?.words ?? result.total;\n\n if (result.breakdown.mode === \"collector\") {\n collectNonWordCounts(counts, result.breakdown.nonWords);\n return counts;\n }\n\n for (const item of result.breakdown.items) {\n collectNonWordCounts(counts, item.nonWords);\n }\n\n return counts;\n}\n\nfunction collectTotalOfCounts(result: WordCounterResult | SectionedResult): TotalOfCounts {\n if (!(\"section\" in result)) {\n return collectFromWordCounterResult(result);\n }\n\n const counts = createTotalOfCounts();\n for (const item of result.items) {\n const itemCounts = collectFromWordCounterResult(item.result);\n for (const part of TOTAL_OF_PARTS) {\n counts[part] += itemCounts[part];\n }\n }\n return counts;\n}\n\nfunction parseTotalOfToken(token: string): TotalOfPart {\n const normalized = token.trim().toLowerCase();\n const canonical = TOTAL_OF_PART_ALIASES[normalized];\n if (canonical) {\n return canonical;\n }\n throw new Error(`Invalid --total-of part: ${token}. Allowed: ${TOTAL_OF_PARTS.join(\", \")}.`);\n}\n\nexport function parseTotalOfOption(value: string): TotalOfPart[] {\n const rawTokens = value\n .split(\",\")\n .map((token) => token.trim())\n .filter((token) => token.length > 0);\n\n if (rawTokens.length === 0) {\n throw new Error(\n `Invalid --total-of value: \"${value}\". Use comma-separated parts from: ${TOTAL_OF_PARTS.join(\", \")}.`,\n );\n }\n\n const parts: TotalOfPart[] = [];\n const seen = new Set<TotalOfPart>();\n for (const token of rawTokens) {\n const parsed = parseTotalOfToken(token);\n if (seen.has(parsed)) {\n continue;\n }\n seen.add(parsed);\n parts.push(parsed);\n }\n\n return parts;\n}\n\nexport function requiresNonWordCollection(parts: readonly TotalOfPart[] | undefined): boolean {\n if (!parts || parts.length === 0) {\n return false;\n }\n return parts.some((part) => part !== \"words\");\n}\n\nexport function requiresWhitespaceCollection(parts: readonly TotalOfPart[] | undefined): boolean {\n if (!parts || parts.length === 0) {\n return false;\n }\n return parts.includes(\"whitespace\");\n}\n\nexport function resolveTotalOfOverride(\n result: WordCounterResult | SectionedResult,\n parts: readonly TotalOfPart[] | undefined,\n): TotalOfOverride | undefined {\n if (!parts || parts.length === 0) {\n return undefined;\n }\n\n const counts = collectTotalOfCounts(result);\n let total = 0;\n for (const part of parts) {\n total += counts[part];\n }\n\n return {\n parts: [...parts],\n total,\n };\n}\n\nexport function formatTotalOfParts(parts: readonly TotalOfPart[]): string {\n return parts.join(\", \");\n}\n","import type { ConfigFormat } from \"./types\";\n\nexport class ConfigValidationError extends Error {\n readonly sourceLabel: string;\n readonly path: string[];\n\n constructor(sourceLabel: string, path: string[], message: string) {\n const suffix = path.length > 0 ? ` at \"${path.join(\".\")}\"` : \"\";\n super(`Invalid config in ${sourceLabel}${suffix}: ${message}`);\n this.name = \"ConfigValidationError\";\n this.sourceLabel = sourceLabel;\n this.path = [...path];\n }\n}\n\nexport class ConfigParseError extends Error {\n readonly sourceLabel: string;\n readonly format: ConfigFormat;\n\n constructor(sourceLabel: string, format: ConfigFormat, message: string) {\n super(`Invalid ${format.toUpperCase()} config in ${sourceLabel}: ${message}`);\n this.name = \"ConfigParseError\";\n this.sourceLabel = sourceLabel;\n this.format = format;\n }\n}\n","import type { DetectorContentGateMode, DetectorMode } from \"../../detector\";\nimport type { TotalOfPart } from \"../total-of\";\nimport type { PathMode } from \"../types\";\nimport { ConfigValidationError } from \"./errors\";\nimport {\n CONFIG_CONTENT_GATE_MODE_VALUES,\n CONFIG_DETECTOR_VALUES,\n CONFIG_LOG_LEVEL_VALUES,\n CONFIG_LOG_VERBOSITY_VALUES,\n CONFIG_PATH_MODE_VALUES,\n CONFIG_PROGRESS_MODE_VALUES,\n CONFIG_TOTAL_OF_VALUES,\n} from \"./schema\";\nimport type {\n ConfigLogLevel,\n ConfigLogVerbosity,\n ConfigProgressMode,\n WordCounterConfig,\n} from \"./types\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction createConfigError(sourceLabel: string, path: string[], message: string): Error {\n return new ConfigValidationError(sourceLabel, path, message);\n}\n\nfunction ensureObject(\n value: unknown,\n sourceLabel: string,\n path: string[],\n): Record<string, unknown> | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!isRecord(value)) {\n throw createConfigError(sourceLabel, path, \"expected an object.\");\n }\n\n return value;\n}\n\nfunction rejectUnknownKeys(\n value: Record<string, unknown>,\n allowedKeys: readonly string[],\n sourceLabel: string,\n path: string[],\n): void {\n for (const key of Object.keys(value)) {\n if (!allowedKeys.includes(key)) {\n throw createConfigError(sourceLabel, [...path, key], \"unknown key.\");\n }\n }\n}\n\nfunction parseBoolean(value: unknown, sourceLabel: string, path: string[]): boolean | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (typeof value !== \"boolean\") {\n throw createConfigError(sourceLabel, path, \"expected a boolean.\");\n }\n\n return value;\n}\n\nfunction parseString(value: unknown, sourceLabel: string, path: string[]): string | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (typeof value !== \"string\") {\n throw createConfigError(sourceLabel, path, \"expected a string.\");\n }\n\n return value;\n}\n\nfunction parseStringArray(\n value: unknown,\n sourceLabel: string,\n path: string[],\n): string[] | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!Array.isArray(value) || value.some((item) => typeof item !== \"string\")) {\n throw createConfigError(sourceLabel, path, \"expected an array of strings.\");\n }\n\n return [...value];\n}\n\nfunction parseEnum<T extends string>(\n value: unknown,\n allowedValues: readonly T[],\n sourceLabel: string,\n path: string[],\n): T | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (typeof value !== \"string\" || !allowedValues.includes(value as T)) {\n throw createConfigError(\n sourceLabel,\n path,\n `expected one of: ${allowedValues.map((item) => `\"${item}\"`).join(\", \")}.`,\n );\n }\n\n return value as T;\n}\n\nfunction parseTotalOf(\n value: unknown,\n sourceLabel: string,\n path: string[],\n): TotalOfPart[] | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!Array.isArray(value) || value.some((item) => typeof item !== \"string\")) {\n throw createConfigError(sourceLabel, path, \"expected an array of strings.\");\n }\n\n const parts: TotalOfPart[] = [];\n for (const item of value) {\n const parsed = parseEnum(item, CONFIG_TOTAL_OF_VALUES, sourceLabel, path);\n if (parsed && !parts.includes(parsed)) {\n parts.push(parsed);\n }\n }\n\n return parts;\n}\n\nfunction normalizeInspectConfig(value: unknown, sourceLabel: string): WordCounterConfig[\"inspect\"] {\n const section = ensureObject(value, sourceLabel, [\"inspect\"]);\n if (!section) {\n return undefined;\n }\n\n rejectUnknownKeys(section, [\"detector\", \"contentGate\"], sourceLabel, [\"inspect\"]);\n\n const detector = parseEnum<DetectorMode>(section.detector, CONFIG_DETECTOR_VALUES, sourceLabel, [\n \"inspect\",\n \"detector\",\n ]);\n const contentGateSection = ensureObject(section.contentGate, sourceLabel, [\n \"inspect\",\n \"contentGate\",\n ]);\n if (contentGateSection) {\n rejectUnknownKeys(contentGateSection, [\"mode\"], sourceLabel, [\"inspect\", \"contentGate\"]);\n }\n const mode = parseEnum<DetectorContentGateMode>(\n contentGateSection?.mode,\n CONFIG_CONTENT_GATE_MODE_VALUES,\n sourceLabel,\n [\"inspect\", \"contentGate\", \"mode\"],\n );\n\n const normalized: NonNullable<WordCounterConfig[\"inspect\"]> = {};\n if (detector !== undefined) {\n normalized.detector = detector;\n }\n if (mode !== undefined) {\n normalized.contentGate = { mode };\n }\n\n return Object.keys(normalized).length > 0 ? normalized : undefined;\n}\n\nfunction normalizeContentGateConfig(\n value: unknown,\n sourceLabel: string,\n): WordCounterConfig[\"contentGate\"] {\n const section = ensureObject(value, sourceLabel, [\"contentGate\"]);\n if (!section) {\n return undefined;\n }\n\n rejectUnknownKeys(section, [\"mode\"], sourceLabel, [\"contentGate\"]);\n\n const mode = parseEnum<DetectorContentGateMode>(\n section.mode,\n CONFIG_CONTENT_GATE_MODE_VALUES,\n sourceLabel,\n [\"contentGate\", \"mode\"],\n );\n\n return mode === undefined ? undefined : { mode };\n}\n\nfunction normalizePathConfig(value: unknown, sourceLabel: string): WordCounterConfig[\"path\"] {\n const section = ensureObject(value, sourceLabel, [\"path\"]);\n if (!section) {\n return undefined;\n }\n\n rejectUnknownKeys(\n section,\n [\"mode\", \"recursive\", \"includeExtensions\", \"excludeExtensions\", \"detectBinary\"],\n sourceLabel,\n [\"path\"],\n );\n\n const mode = parseEnum<PathMode>(section.mode, CONFIG_PATH_MODE_VALUES, sourceLabel, [\n \"path\",\n \"mode\",\n ]);\n const recursive = parseBoolean(section.recursive, sourceLabel, [\"path\", \"recursive\"]);\n const includeExtensions = parseStringArray(section.includeExtensions, sourceLabel, [\n \"path\",\n \"includeExtensions\",\n ]);\n const excludeExtensions = parseStringArray(section.excludeExtensions, sourceLabel, [\n \"path\",\n \"excludeExtensions\",\n ]);\n const detectBinary = parseBoolean(section.detectBinary, sourceLabel, [\"path\", \"detectBinary\"]);\n\n const normalized: NonNullable<WordCounterConfig[\"path\"]> = {};\n if (mode !== undefined) {\n normalized.mode = mode;\n }\n if (recursive !== undefined) {\n normalized.recursive = recursive;\n }\n if (includeExtensions !== undefined) {\n normalized.includeExtensions = includeExtensions;\n }\n if (excludeExtensions !== undefined) {\n normalized.excludeExtensions = excludeExtensions;\n }\n if (detectBinary !== undefined) {\n normalized.detectBinary = detectBinary;\n }\n\n return Object.keys(normalized).length > 0 ? normalized : undefined;\n}\n\nfunction normalizeProgressConfig(\n value: unknown,\n sourceLabel: string,\n): WordCounterConfig[\"progress\"] {\n const section = ensureObject(value, sourceLabel, [\"progress\"]);\n if (!section) {\n return undefined;\n }\n\n rejectUnknownKeys(section, [\"mode\"], sourceLabel, [\"progress\"]);\n\n const mode = parseEnum<ConfigProgressMode>(\n section.mode,\n CONFIG_PROGRESS_MODE_VALUES,\n sourceLabel,\n [\"progress\", \"mode\"],\n );\n\n return mode === undefined ? undefined : { mode };\n}\n\nfunction normalizeOutputConfig(value: unknown, sourceLabel: string): WordCounterConfig[\"output\"] {\n const section = ensureObject(value, sourceLabel, [\"output\"]);\n if (!section) {\n return undefined;\n }\n\n rejectUnknownKeys(section, [\"totalOf\"], sourceLabel, [\"output\"]);\n\n const totalOf = parseTotalOf(section.totalOf, sourceLabel, [\"output\", \"totalOf\"]);\n return totalOf === undefined ? undefined : { totalOf };\n}\n\nfunction normalizeReportingConfig(\n value: unknown,\n sourceLabel: string,\n): WordCounterConfig[\"reporting\"] {\n const section = ensureObject(value, sourceLabel, [\"reporting\"]);\n if (!section) {\n return undefined;\n }\n\n rejectUnknownKeys(section, [\"skippedFiles\", \"debugReport\"], sourceLabel, [\"reporting\"]);\n\n const skippedFiles = parseBoolean(section.skippedFiles, sourceLabel, [\n \"reporting\",\n \"skippedFiles\",\n ]);\n\n const debugReportSection = ensureObject(section.debugReport, sourceLabel, [\n \"reporting\",\n \"debugReport\",\n ]);\n if (debugReportSection) {\n rejectUnknownKeys(debugReportSection, [\"path\", \"tee\"], sourceLabel, [\n \"reporting\",\n \"debugReport\",\n ]);\n }\n\n const path = parseString(debugReportSection?.path, sourceLabel, [\n \"reporting\",\n \"debugReport\",\n \"path\",\n ]);\n const tee = parseBoolean(debugReportSection?.tee, sourceLabel, [\n \"reporting\",\n \"debugReport\",\n \"tee\",\n ]);\n\n const normalized: NonNullable<WordCounterConfig[\"reporting\"]> = {};\n if (skippedFiles !== undefined) {\n normalized.skippedFiles = skippedFiles;\n }\n if (path !== undefined || tee !== undefined) {\n normalized.debugReport = {};\n if (path !== undefined) {\n normalized.debugReport.path = path;\n }\n if (tee !== undefined) {\n normalized.debugReport.tee = tee;\n }\n }\n\n return Object.keys(normalized).length > 0 ? normalized : undefined;\n}\n\nfunction normalizeLoggingConfig(value: unknown, sourceLabel: string): WordCounterConfig[\"logging\"] {\n const section = ensureObject(value, sourceLabel, [\"logging\"]);\n if (!section) {\n return undefined;\n }\n\n rejectUnknownKeys(section, [\"level\", \"verbosity\"], sourceLabel, [\"logging\"]);\n\n const level = parseEnum<ConfigLogLevel>(section.level, CONFIG_LOG_LEVEL_VALUES, sourceLabel, [\n \"logging\",\n \"level\",\n ]);\n const verbosity = parseEnum<ConfigLogVerbosity>(\n section.verbosity,\n CONFIG_LOG_VERBOSITY_VALUES,\n sourceLabel,\n [\"logging\", \"verbosity\"],\n );\n\n const normalized: NonNullable<WordCounterConfig[\"logging\"]> = {};\n if (level !== undefined) {\n normalized.level = level;\n }\n if (verbosity !== undefined) {\n normalized.verbosity = verbosity;\n }\n\n return Object.keys(normalized).length > 0 ? normalized : undefined;\n}\n\nexport function normalizeWordCounterConfig(value: unknown, sourceLabel: string): WordCounterConfig {\n const root = ensureObject(value, sourceLabel, []);\n if (!root) {\n throw createConfigError(sourceLabel, [], \"expected a root object.\");\n }\n\n rejectUnknownKeys(\n root,\n [\"detector\", \"contentGate\", \"inspect\", \"path\", \"progress\", \"output\", \"reporting\", \"logging\"],\n sourceLabel,\n [],\n );\n\n const detector = parseEnum<DetectorMode>(root.detector, CONFIG_DETECTOR_VALUES, sourceLabel, [\n \"detector\",\n ]);\n const contentGate = normalizeContentGateConfig(root.contentGate, sourceLabel);\n const inspect = normalizeInspectConfig(root.inspect, sourceLabel);\n const path = normalizePathConfig(root.path, sourceLabel);\n const progress = normalizeProgressConfig(root.progress, sourceLabel);\n const output = normalizeOutputConfig(root.output, sourceLabel);\n const reporting = normalizeReportingConfig(root.reporting, sourceLabel);\n const logging = normalizeLoggingConfig(root.logging, sourceLabel);\n\n const normalized: WordCounterConfig = {};\n if (detector !== undefined) {\n normalized.detector = detector;\n }\n if (contentGate !== undefined) {\n normalized.contentGate = contentGate;\n }\n if (inspect !== undefined) {\n normalized.inspect = inspect;\n }\n if (path !== undefined) {\n normalized.path = path;\n }\n if (progress !== undefined) {\n normalized.progress = progress;\n }\n if (output !== undefined) {\n normalized.output = output;\n }\n if (reporting !== undefined) {\n normalized.reporting = reporting;\n }\n if (logging !== undefined) {\n normalized.logging = logging;\n }\n\n return normalized;\n}\n","import { parseTotalOfOption } from \"../total-of\";\nimport { normalizeWordCounterConfig } from \"./normalize\";\nimport type { WordCounterConfig } from \"./types\";\n\nfunction parseBooleanEnv(name: string, value: string | undefined): boolean | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n const normalized = value.trim().toLowerCase();\n if (normalized === \"1\" || normalized === \"true\" || normalized === \"yes\" || normalized === \"on\") {\n return true;\n }\n if (normalized === \"0\" || normalized === \"false\" || normalized === \"no\" || normalized === \"off\") {\n return false;\n }\n\n throw new Error(`Invalid value for ${name}: ${value}`);\n}\n\nfunction parseCommaSeparatedEnv(value: string | undefined): string[] | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n const tokens = value\n .split(\",\")\n .map((token) => token.trim())\n .filter((token) => token.length > 0);\n\n return tokens.length > 0 ? tokens : [];\n}\n\ntype ConfigPath = NonNullable<WordCounterConfig[\"path\"]>;\ntype ConfigProgress = NonNullable<WordCounterConfig[\"progress\"]>;\ntype ConfigLogging = NonNullable<WordCounterConfig[\"logging\"]>;\n\nexport function resolveEnvConfig(env: NodeJS.ProcessEnv = process.env): WordCounterConfig {\n const pathMode = env.WORD_COUNTER_PATH_MODE;\n const recursive = parseBooleanEnv(\"WORD_COUNTER_RECURSIVE\", env.WORD_COUNTER_RECURSIVE);\n const includeExtensions = parseCommaSeparatedEnv(env.WORD_COUNTER_INCLUDE_EXT);\n const excludeExtensions = parseCommaSeparatedEnv(env.WORD_COUNTER_EXCLUDE_EXT);\n const skippedFiles = parseBooleanEnv(\"WORD_COUNTER_REPORT_SKIPS\", env.WORD_COUNTER_REPORT_SKIPS);\n const totalOfRaw = env.WORD_COUNTER_TOTAL_OF;\n const contentGateMode = env.WORD_COUNTER_CONTENT_GATE;\n const progressMode = env.WORD_COUNTER_PROGRESS;\n const logLevel = env.WORD_COUNTER_LOG_LEVEL;\n const logVerbosity = env.WORD_COUNTER_LOG_VERBOSITY;\n const debugReportPath = env.WORD_COUNTER_DEBUG_REPORT;\n const debugReportTee = parseBooleanEnv(\n \"WORD_COUNTER_DEBUG_REPORT_TEE\",\n env.WORD_COUNTER_DEBUG_REPORT_TEE,\n );\n\n const config: WordCounterConfig = {};\n\n if (\n pathMode !== undefined ||\n recursive !== undefined ||\n includeExtensions !== undefined ||\n excludeExtensions !== undefined\n ) {\n config.path = {};\n if (pathMode !== undefined) {\n config.path.mode = pathMode as ConfigPath[\"mode\"];\n }\n if (recursive !== undefined) {\n config.path.recursive = recursive;\n }\n if (includeExtensions !== undefined) {\n config.path.includeExtensions = includeExtensions;\n }\n if (excludeExtensions !== undefined) {\n config.path.excludeExtensions = excludeExtensions;\n }\n }\n\n if (progressMode !== undefined) {\n config.progress = {\n mode: progressMode as ConfigProgress[\"mode\"],\n };\n }\n\n if (totalOfRaw !== undefined) {\n config.output = {\n totalOf: parseTotalOfOption(totalOfRaw),\n };\n }\n\n if (contentGateMode !== undefined) {\n config.contentGate = {\n mode: contentGateMode as NonNullable<WordCounterConfig[\"contentGate\"]>[\"mode\"],\n };\n config.inspect = {\n ...(config.inspect ?? {}),\n contentGate: {\n mode: contentGateMode as NonNullable<\n NonNullable<WordCounterConfig[\"inspect\"]>[\"contentGate\"]\n >[\"mode\"],\n },\n };\n }\n\n if (skippedFiles !== undefined || debugReportPath !== undefined || debugReportTee !== undefined) {\n config.reporting = {};\n if (skippedFiles !== undefined) {\n config.reporting.skippedFiles = skippedFiles;\n }\n if (debugReportPath !== undefined || debugReportTee !== undefined) {\n config.reporting.debugReport = {};\n if (debugReportPath !== undefined) {\n config.reporting.debugReport.path = debugReportPath;\n }\n if (debugReportTee !== undefined) {\n config.reporting.debugReport.tee = debugReportTee;\n }\n }\n }\n\n if (logLevel !== undefined || logVerbosity !== undefined) {\n config.logging = {};\n if (logLevel !== undefined) {\n config.logging.level = logLevel as ConfigLogging[\"level\"];\n }\n if (logVerbosity !== undefined) {\n config.logging.verbosity = logVerbosity as ConfigLogging[\"verbosity\"];\n }\n }\n\n return normalizeWordCounterConfig(config, \"environment variables\");\n}\n","import type { WordCounterConfig } from \"./types\";\n\nfunction mergeSection<T extends Record<string, unknown> | undefined>(\n base: T,\n override: T,\n): T | undefined {\n if (!base) {\n return override ? ({ ...override } as T) : undefined;\n }\n if (!override) {\n return { ...base } as T;\n }\n return { ...base, ...override } as T;\n}\n\nfunction mergeNestedSection<T extends Record<string, unknown> | undefined>(\n base: T,\n override: T,\n nestedKey: string,\n): T | undefined {\n const merged = mergeSection(base, override);\n if (!merged) {\n return undefined;\n }\n\n const baseRecord = base as Record<string, unknown> | undefined;\n const overrideRecord = override as Record<string, unknown> | undefined;\n const baseNested = baseRecord?.[nestedKey];\n const overrideNested = overrideRecord?.[nestedKey];\n if (\n typeof baseNested === \"object\" &&\n baseNested !== null &&\n typeof overrideNested === \"object\" &&\n overrideNested !== null\n ) {\n return {\n ...merged,\n [nestedKey]: {\n ...(baseNested as Record<string, unknown>),\n ...(overrideNested as Record<string, unknown>),\n },\n } as T;\n }\n\n return merged;\n}\n\nexport function mergeWordCounterConfig(\n base: WordCounterConfig,\n override: WordCounterConfig,\n): WordCounterConfig {\n return {\n ...base,\n ...override,\n ...(base.inspect || override.inspect\n ? {\n inspect: mergeSection(base.inspect, override.inspect),\n }\n : {}),\n ...(base.path || override.path\n ? {\n path: mergeSection(base.path, override.path),\n }\n : {}),\n ...(base.progress || override.progress\n ? {\n progress: mergeSection(base.progress, override.progress),\n }\n : {}),\n ...(base.output || override.output\n ? {\n output: mergeSection(base.output, override.output),\n }\n : {}),\n ...(base.reporting || override.reporting\n ? {\n reporting: mergeNestedSection(base.reporting, override.reporting, \"debugReport\"),\n }\n : {}),\n ...(base.logging || override.logging\n ? {\n logging: mergeSection(base.logging, override.logging),\n }\n : {}),\n };\n}\n","function isEscaped(text: string, index: number): boolean {\n let backslashCount = 0;\n for (let cursor = index - 1; cursor >= 0 && text[cursor] === \"\\\\\"; cursor -= 1) {\n backslashCount += 1;\n }\n return backslashCount % 2 === 1;\n}\n\nexport function stripJsonComments(text: string): string {\n let result = \"\";\n let inString = false;\n let inLineComment = false;\n let inBlockComment = false;\n\n for (let index = 0; index < text.length; index += 1) {\n const current = text[index] ?? \"\";\n const next = text[index + 1] ?? \"\";\n\n if (inLineComment) {\n if (current === \"\\n\") {\n inLineComment = false;\n result += current;\n }\n continue;\n }\n\n if (inBlockComment) {\n if (current === \"*\" && next === \"/\") {\n inBlockComment = false;\n index += 1;\n }\n continue;\n }\n\n if (inString) {\n result += current;\n if (current === '\"' && !isEscaped(text, index)) {\n inString = false;\n }\n continue;\n }\n\n if (current === '\"') {\n inString = true;\n result += current;\n continue;\n }\n\n if (current === \"/\" && next === \"/\") {\n inLineComment = true;\n index += 1;\n continue;\n }\n\n if (current === \"/\" && next === \"*\") {\n inBlockComment = true;\n index += 1;\n continue;\n }\n\n result += current;\n }\n\n if (inBlockComment) {\n throw new Error(\"Unterminated block comment in JSONC config.\");\n }\n\n return result;\n}\n","export type TomlLineToken =\n | {\n kind: \"table\";\n path: string[];\n rawLine: string;\n }\n | {\n kind: \"assignment\";\n keyPath: string[];\n rawValue: string;\n rawLine: string;\n };\n\nfunction stripInlineComment(line: string): string {\n let inSingle = false;\n let inDouble = false;\n\n for (let index = 0; index < line.length; index += 1) {\n const current = line[index] ?? \"\";\n const previous = line[index - 1] ?? \"\";\n\n if (current === \"'\" && !inDouble) {\n inSingle = !inSingle;\n continue;\n }\n\n if (current === '\"' && !inSingle && previous !== \"\\\\\") {\n inDouble = !inDouble;\n continue;\n }\n\n if (current === \"#\" && !inSingle && !inDouble) {\n return line.slice(0, index);\n }\n }\n\n return line;\n}\n\nfunction splitPath(path: string, rawLine: string): string[] {\n const parts = path.split(\".\").map((part) => part.trim());\n if (parts.some((part) => part.length === 0)) {\n throw new Error(`Invalid TOML key: ${rawLine}`);\n }\n return parts;\n}\n\nfunction tokenizeTomlLine(rawLine: string, currentTable: string[]): TomlLineToken | undefined {\n const line = stripInlineComment(rawLine).trim();\n if (!line) {\n return undefined;\n }\n\n const tableMatch = line.match(/^\\[([A-Za-z0-9_.-]+)]$/);\n if (tableMatch) {\n return {\n kind: \"table\",\n path: splitPath(tableMatch[1] ?? \"\", rawLine),\n rawLine,\n };\n }\n\n const separatorIndex = line.indexOf(\"=\");\n if (separatorIndex <= 0) {\n throw new Error(`Invalid TOML assignment: ${rawLine}`);\n }\n\n const rawKey = line.slice(0, separatorIndex).trim();\n const rawValue = line.slice(separatorIndex + 1).trim();\n if (!rawKey || !rawValue) {\n throw new Error(`Invalid TOML assignment: ${rawLine}`);\n }\n\n return {\n kind: \"assignment\",\n keyPath: [...currentTable, ...splitPath(rawKey, rawLine)],\n rawValue,\n rawLine,\n };\n}\n\nexport function tokenizeTomlConfig(text: string): TomlLineToken[] {\n const tokens: TomlLineToken[] = [];\n let currentTable: string[] = [];\n\n for (const rawLine of text.split(/\\r?\\n/)) {\n const token = tokenizeTomlLine(rawLine, currentTable);\n if (!token) {\n continue;\n }\n\n if (token.kind === \"table\") {\n currentTable = token.path;\n tokens.push(token);\n continue;\n }\n\n tokens.push(token);\n }\n\n return tokens;\n}\n","import { tokenizeTomlConfig } from \"./toml-tokens\";\n\ntype TomlPrimitive = string | boolean;\ntype TomlValue = TomlPrimitive | TomlPrimitive[];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseTomlString(rawValue: string): string {\n if (rawValue.length < 2) {\n throw new Error(`Invalid TOML string value: ${rawValue}`);\n }\n\n const quote = rawValue[0];\n const inner = rawValue.slice(1, -1);\n if (quote === \"'\") {\n return inner;\n }\n\n return inner.replace(/\\\\([\"\\\\bfnrt])/g, (_match, escaped: string) => {\n switch (escaped) {\n case '\"':\n return '\"';\n case \"\\\\\":\n return \"\\\\\";\n case \"b\":\n return \"\\b\";\n case \"f\":\n return \"\\f\";\n case \"n\":\n return \"\\n\";\n case \"r\":\n return \"\\r\";\n case \"t\":\n return \"\\t\";\n default:\n return escaped;\n }\n });\n}\n\nfunction splitTomlArrayItems(rawValue: string): string[] {\n const items: string[] = [];\n let buffer = \"\";\n let inSingle = false;\n let inDouble = false;\n\n for (let index = 0; index < rawValue.length; index += 1) {\n const current = rawValue[index] ?? \"\";\n const previous = rawValue[index - 1] ?? \"\";\n\n if (current === \"'\" && !inDouble) {\n inSingle = !inSingle;\n buffer += current;\n continue;\n }\n\n if (current === '\"' && !inSingle && previous !== \"\\\\\") {\n inDouble = !inDouble;\n buffer += current;\n continue;\n }\n\n if (current === \",\" && !inSingle && !inDouble) {\n items.push(buffer.trim());\n buffer = \"\";\n continue;\n }\n\n buffer += current;\n }\n\n if (buffer.trim().length > 0) {\n items.push(buffer.trim());\n }\n\n return items;\n}\n\nfunction parseTomlValue(rawValue: string): TomlValue {\n const trimmed = rawValue.trim();\n if (trimmed === \"true\") {\n return true;\n }\n if (trimmed === \"false\") {\n return false;\n }\n\n if (\n (trimmed.startsWith('\"') && trimmed.endsWith('\"')) ||\n (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\"))\n ) {\n return parseTomlString(trimmed);\n }\n\n if (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) {\n const inner = trimmed.slice(1, -1).trim();\n if (inner.length === 0) {\n return [];\n }\n return splitTomlArrayItems(inner).map((item) => {\n const parsed = parseTomlValue(item);\n if (Array.isArray(parsed)) {\n throw new Error(`Nested TOML arrays are not supported: ${rawValue}`);\n }\n return parsed;\n });\n }\n\n throw new Error(`Unsupported TOML value: ${rawValue}`);\n}\n\nfunction ensureObject(parent: Record<string, unknown>, key: string): Record<string, unknown> {\n const existing = parent[key];\n if (existing === undefined) {\n const next: Record<string, unknown> = {};\n parent[key] = next;\n return next;\n }\n\n if (!isRecord(existing)) {\n throw new Error(`Cannot redefine non-table key as table: ${key}`);\n }\n\n return existing;\n}\n\nfunction setNestedValue(root: Record<string, unknown>, keyPath: string[], value: TomlValue): void {\n let target = root;\n for (let index = 0; index < keyPath.length - 1; index += 1) {\n target = ensureObject(target, keyPath[index] ?? \"\");\n }\n\n const leafKey = keyPath[keyPath.length - 1] ?? \"\";\n if (leafKey in target) {\n throw new Error(`Duplicate TOML key: ${keyPath.join(\".\")}`);\n }\n target[leafKey] = value;\n}\n\nexport function parseTomlConfig(text: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const token of tokenizeTomlConfig(text)) {\n if (token.kind === \"table\") {\n let tableTarget = result;\n for (const part of token.path) {\n tableTarget = ensureObject(tableTarget, part);\n }\n continue;\n }\n\n setNestedValue(result, token.keyPath, parseTomlValue(token.rawValue));\n }\n\n return result;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { ConfigParseError, ConfigValidationError } from \"./errors\";\nimport { stripJsonComments } from \"./jsonc\";\nimport { normalizeWordCounterConfig } from \"./normalize\";\nimport { parseTomlConfig } from \"./toml\";\nimport type { ConfigFormat, ParsedConfigFile, WordCounterConfig } from \"./types\";\n\nfunction parseJsonConfig(text: string, sourceLabel: string, format: \"json\" | \"jsonc\"): unknown {\n try {\n return JSON.parse(text);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ConfigParseError(sourceLabel, format, message);\n }\n}\n\nexport function parseConfigText(\n text: string,\n format: ConfigFormat,\n sourceLabel: string,\n): WordCounterConfig {\n let parsed: unknown;\n\n if (format === \"json\") {\n parsed = parseJsonConfig(text, sourceLabel, \"json\");\n } else if (format === \"jsonc\") {\n try {\n parsed = parseJsonConfig(stripJsonComments(text), sourceLabel, \"jsonc\");\n } catch (error) {\n if (error instanceof ConfigParseError) {\n throw error;\n }\n const message = error instanceof Error ? error.message : String(error);\n throw new ConfigParseError(sourceLabel, \"jsonc\", message);\n }\n } else {\n try {\n parsed = parseTomlConfig(text);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ConfigParseError(sourceLabel, \"toml\", message);\n }\n }\n\n try {\n return normalizeWordCounterConfig(parsed, sourceLabel);\n } catch (error) {\n if (error instanceof ConfigValidationError) {\n throw error;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n throw new ConfigParseError(sourceLabel, format, message);\n }\n}\n\nexport async function loadConfigFile(\n path: string,\n format: ConfigFormat,\n): Promise<ParsedConfigFile> {\n let text: string;\n try {\n text = await readFile(path, \"utf8\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to read config file (${path}): ${message}`);\n }\n\n return {\n format,\n path,\n config: parseConfigText(text, format, path),\n };\n}\n","import { loadConfigFile } from \"./parse\";\nimport { discoverConfigFiles } from \"./discover\";\nimport { resolveEnvConfig } from \"./env\";\nimport { mergeWordCounterConfig } from \"./merge\";\nimport type { DiscoverConfigOptions, ParsedConfigFile, WordCounterConfig } from \"./types\";\n\nexport type ResolvedWordCounterConfig = {\n config: WordCounterConfig;\n files: ParsedConfigFile[];\n notes: string[];\n};\n\nexport async function resolveWordCounterConfig(\n options: DiscoverConfigOptions = {},\n): Promise<ResolvedWordCounterConfig> {\n const discovered = await discoverConfigFiles(options);\n const filesToLoad = [discovered.user, discovered.cwd].filter((item) => item !== undefined);\n const loadedFiles = await Promise.all(\n filesToLoad.map(async (item) => {\n const loaded = await loadConfigFile(item.path, item.format);\n return {\n ...loaded,\n notes: item.notes,\n };\n }),\n );\n\n let config: WordCounterConfig = {};\n const files: ParsedConfigFile[] = [];\n const notes: string[] = [];\n\n for (const loaded of loadedFiles) {\n config = mergeWordCounterConfig(config, loaded.config);\n files.push({\n path: loaded.path,\n format: loaded.format,\n config: loaded.config,\n });\n notes.push(...loaded.notes);\n }\n\n config = mergeWordCounterConfig(config, resolveEnvConfig(options.env));\n\n return {\n config,\n files,\n notes,\n };\n}\n","import type { Command } from \"commander\";\nimport type { ConfigProgressMode } from \"./types\";\nimport type { CliActionOptions } from \"../runtime/types\";\nimport type { CountCliSources } from \"./apply\";\n\nfunction isCliOptionSource(program: Command, optionName: string): boolean {\n return program.getOptionValueSource(optionName) === \"cli\";\n}\n\nexport function deriveCountCliSources(program: Command): CountCliSources {\n return {\n detector: isCliOptionSource(program, \"detector\"),\n contentGate: isCliOptionSource(program, \"contentGate\"),\n pathMode: isCliOptionSource(program, \"pathMode\"),\n recursive: isCliOptionSource(program, \"recursive\"),\n includeExt: isCliOptionSource(program, \"includeExt\"),\n excludeExt: isCliOptionSource(program, \"excludeExt\"),\n totalOf: isCliOptionSource(program, \"totalOf\"),\n debug: isCliOptionSource(program, \"debug\"),\n verbose: isCliOptionSource(program, \"verbose\"),\n debugReport: isCliOptionSource(program, \"debugReport\"),\n debugReportTee:\n isCliOptionSource(program, \"debugReportTee\") || isCliOptionSource(program, \"debugTee\"),\n progress: isCliOptionSource(program, \"progress\"),\n quietSkips: isCliOptionSource(program, \"quietSkips\"),\n };\n}\n\nexport function deriveInitialCountProgressMode(\n program: Command,\n rawProgressValue: boolean,\n): ConfigProgressMode {\n if (!isCliOptionSource(program, \"progress\")) {\n return \"auto\";\n }\n\n return rawProgressValue ? \"on\" : \"off\";\n}\n","import { closeSync, createWriteStream, existsSync, mkdirSync, openSync, statSync } from \"node:fs\";\nimport { basename, dirname, extname, join, resolve as resolvePath } from \"node:path\";\n\ntype DebugDetails = Record<string, unknown>;\nexport type DebugVerbosity = \"compact\" | \"verbose\";\nexport type DebugEventScope = \"run\" | \"file\";\nconst DEBUG_EVENT_SCHEMA_VERSION = 1;\n\nexport type DebugEventOptions = {\n verbosity?: DebugVerbosity;\n scope?: DebugEventScope;\n};\n\ntype DebugReportOptions = {\n path?: string;\n tee: boolean;\n cwd?: string;\n autogeneratedNamePrefix?: string;\n};\n\nexport type CreateDebugChannelOptions = {\n enabled: boolean;\n verbosity?: DebugVerbosity;\n report?: DebugReportOptions;\n now?: () => Date;\n pid?: number;\n};\n\nexport type DebugChannel = {\n enabled: boolean;\n verbosity: DebugVerbosity;\n reportPath?: string;\n emit: (event: string, details?: DebugDetails, options?: DebugEventOptions) => void;\n close: () => Promise<void>;\n};\n\ntype DebugSink = {\n write: (line: string) => void;\n close: () => Promise<void>;\n};\n\nconst NOOP_CLOSE = async (): Promise<void> => {\n return;\n};\n\nfunction shouldEmitAtVerbosity(\n channelVerbosity: DebugVerbosity,\n eventVerbosity: DebugVerbosity,\n): boolean {\n return channelVerbosity === \"verbose\" || eventVerbosity === \"compact\";\n}\n\nfunction formatTimestampPart(value: number): string {\n return String(value).padStart(2, \"0\");\n}\n\nfunction formatDebugReportTimestamp(now: Date): string {\n return [\n `${now.getUTCFullYear()}${formatTimestampPart(now.getUTCMonth() + 1)}${formatTimestampPart(now.getUTCDate())}`,\n `${formatTimestampPart(now.getUTCHours())}${formatTimestampPart(now.getUTCMinutes())}${formatTimestampPart(now.getUTCSeconds())}`,\n ].join(\"-\");\n}\n\nfunction buildRunId(now: Date, pid: number): string {\n return `wc-debug-${now.getTime()}-${pid}`;\n}\n\nfunction inferEventTopic(event: string): string {\n const topic = event.split(\".\")[0]?.trim();\n return topic && topic.length > 0 ? topic : \"runtime\";\n}\n\nconst FILE_SCOPED_EVENT_PATTERNS = [\n /^batch\\.skips\\.item$/,\n /^path\\.resolve\\.input$/,\n /^path\\.resolve\\.skip$/,\n /^path\\.resolve\\.(filter|regex)\\.excluded$/,\n /^path\\.resolve\\.expand\\.include$/,\n /^path\\.resolve\\.dedupe\\.(accept|duplicate)$/,\n];\n\nfunction inferEventScope(event: string): DebugEventScope {\n return FILE_SCOPED_EVENT_PATTERNS.some((pattern) => pattern.test(event)) ? \"file\" : \"run\";\n}\n\nfunction withCollisionSuffix(pathValue: string, sequence: number): string {\n if (sequence <= 0) {\n return pathValue;\n }\n\n const extension = extname(pathValue);\n const baseName = basename(pathValue, extension);\n const parent = dirname(pathValue);\n return join(parent, `${baseName}-${sequence}${extension}`);\n}\n\nfunction resolveReportPath(report: DebugReportOptions, now: Date, pid: number): string {\n const cwd = report.cwd ?? process.cwd();\n const autogeneratedNamePrefix = report.autogeneratedNamePrefix ?? \"wc-debug\";\n const defaultName = `${autogeneratedNamePrefix}-${formatDebugReportTimestamp(now)}-utc-${pid}.jsonl`;\n const explicitPathValue = typeof report.path === \"string\" ? report.path : undefined;\n const explicitPath = explicitPathValue !== undefined;\n const basePath = resolvePath(cwd, explicitPathValue ?? defaultName);\n mkdirSync(dirname(basePath), { recursive: true });\n\n if (explicitPath) {\n if (existsSync(basePath) && statSync(basePath).isDirectory()) {\n throw new Error(`debug report path must be a file: ${basePath}`);\n }\n return basePath;\n }\n\n let candidate = basePath;\n let sequence = 0;\n while (existsSync(candidate)) {\n sequence += 1;\n candidate = withCollisionSuffix(basePath, sequence);\n }\n\n return candidate;\n}\n\nfunction createTerminalSink(): DebugSink {\n return {\n write(line) {\n console.error(`[debug] ${line}`);\n },\n close: NOOP_CLOSE,\n };\n}\n\nfunction createFileSink(pathValue: string): DebugSink {\n try {\n const fd = openSync(pathValue, \"a\");\n closeSync(fd);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`debug report path is not writable: ${pathValue} (${message})`);\n }\n\n const stream = createWriteStream(pathValue, { flags: \"a\", encoding: \"utf8\" });\n let streamError: Error | undefined;\n stream.on(\"error\", (error) => {\n streamError = error;\n });\n\n return {\n write(line) {\n if (streamError || stream.destroyed) {\n return;\n }\n stream.write(`${line}\\n`);\n },\n close() {\n if (streamError || stream.destroyed || stream.writableEnded) {\n return Promise.resolve();\n }\n\n return new Promise<void>((resolve) => {\n stream.end(() => {\n resolve();\n });\n });\n },\n };\n}\n\nexport function createDebugChannel(options: CreateDebugChannelOptions): DebugChannel {\n if (!options.enabled) {\n return {\n enabled: false,\n verbosity: options.verbosity ?? \"compact\",\n emit() {\n return;\n },\n close: NOOP_CLOSE,\n };\n }\n\n const verbosity = options.verbosity ?? \"compact\";\n const sinks: DebugSink[] = [];\n let reportPath: string | undefined;\n const channelNow = options.now?.() ?? new Date();\n const channelPid = options.pid ?? process.pid;\n const runId = buildRunId(channelNow, channelPid);\n\n if (options.report) {\n reportPath = resolveReportPath(options.report, channelNow, channelPid);\n sinks.push(createFileSink(reportPath));\n\n if (options.report.tee) {\n sinks.push(createTerminalSink());\n }\n } else {\n sinks.push(createTerminalSink());\n }\n\n return {\n enabled: true,\n verbosity,\n reportPath,\n emit(event, details = {}, eventOptions = {}) {\n const eventVerbosity = eventOptions.verbosity ?? \"compact\";\n if (!shouldEmitAtVerbosity(verbosity, eventVerbosity)) {\n return;\n }\n\n const timestamp = (options.now?.() ?? new Date()).toISOString();\n const payload = JSON.stringify({\n schemaVersion: DEBUG_EVENT_SCHEMA_VERSION,\n timestamp,\n runId,\n topic: inferEventTopic(event),\n scope: eventOptions.scope ?? inferEventScope(event),\n event,\n verbosity: eventVerbosity,\n ...details,\n });\n for (const sink of sinks) {\n sink.write(payload);\n }\n },\n async close() {\n for (const sink of sinks) {\n await sink.close();\n }\n },\n };\n}\n","let p = process || {}, argv = p.argv || [], env = p.env || {}\nlet isColorSupported =\n\t!(!!env.NO_COLOR || argv.includes(\"--no-color\")) &&\n\t(!!env.FORCE_COLOR || argv.includes(\"--color\") || p.platform === \"win32\" || ((p.stdout || {}).isTTY && env.TERM !== \"dumb\") || !!env.CI)\n\nlet formatter = (open, close, replace = open) =>\n\tinput => {\n\t\tlet string = \"\" + input, index = string.indexOf(close, open.length)\n\t\treturn ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close\n\t}\n\nlet replaceClose = (string, close, replace, index) => {\n\tlet result = \"\", cursor = 0\n\tdo {\n\t\tresult += string.substring(cursor, index) + replace\n\t\tcursor = index + close.length\n\t\tindex = string.indexOf(close, cursor)\n\t} while (~index)\n\treturn result + string.substring(cursor)\n}\n\nlet createColors = (enabled = isColorSupported) => {\n\tlet f = enabled ? formatter : () => String\n\treturn {\n\t\tisColorSupported: enabled,\n\t\treset: f(\"\\x1b[0m\", \"\\x1b[0m\"),\n\t\tbold: f(\"\\x1b[1m\", \"\\x1b[22m\", \"\\x1b[22m\\x1b[1m\"),\n\t\tdim: f(\"\\x1b[2m\", \"\\x1b[22m\", \"\\x1b[22m\\x1b[2m\"),\n\t\titalic: f(\"\\x1b[3m\", \"\\x1b[23m\"),\n\t\tunderline: f(\"\\x1b[4m\", \"\\x1b[24m\"),\n\t\tinverse: f(\"\\x1b[7m\", \"\\x1b[27m\"),\n\t\thidden: f(\"\\x1b[8m\", \"\\x1b[28m\"),\n\t\tstrikethrough: f(\"\\x1b[9m\", \"\\x1b[29m\"),\n\n\t\tblack: f(\"\\x1b[30m\", \"\\x1b[39m\"),\n\t\tred: f(\"\\x1b[31m\", \"\\x1b[39m\"),\n\t\tgreen: f(\"\\x1b[32m\", \"\\x1b[39m\"),\n\t\tyellow: f(\"\\x1b[33m\", \"\\x1b[39m\"),\n\t\tblue: f(\"\\x1b[34m\", \"\\x1b[39m\"),\n\t\tmagenta: f(\"\\x1b[35m\", \"\\x1b[39m\"),\n\t\tcyan: f(\"\\x1b[36m\", \"\\x1b[39m\"),\n\t\twhite: f(\"\\x1b[37m\", \"\\x1b[39m\"),\n\t\tgray: f(\"\\x1b[90m\", \"\\x1b[39m\"),\n\n\t\tbgBlack: f(\"\\x1b[40m\", \"\\x1b[49m\"),\n\t\tbgRed: f(\"\\x1b[41m\", \"\\x1b[49m\"),\n\t\tbgGreen: f(\"\\x1b[42m\", \"\\x1b[49m\"),\n\t\tbgYellow: f(\"\\x1b[43m\", \"\\x1b[49m\"),\n\t\tbgBlue: f(\"\\x1b[44m\", \"\\x1b[49m\"),\n\t\tbgMagenta: f(\"\\x1b[45m\", \"\\x1b[49m\"),\n\t\tbgCyan: f(\"\\x1b[46m\", \"\\x1b[49m\"),\n\t\tbgWhite: f(\"\\x1b[47m\", \"\\x1b[49m\"),\n\n\t\tblackBright: f(\"\\x1b[90m\", \"\\x1b[39m\"),\n\t\tredBright: f(\"\\x1b[91m\", \"\\x1b[39m\"),\n\t\tgreenBright: f(\"\\x1b[92m\", \"\\x1b[39m\"),\n\t\tyellowBright: f(\"\\x1b[93m\", \"\\x1b[39m\"),\n\t\tblueBright: f(\"\\x1b[94m\", \"\\x1b[39m\"),\n\t\tmagentaBright: f(\"\\x1b[95m\", \"\\x1b[39m\"),\n\t\tcyanBright: f(\"\\x1b[96m\", \"\\x1b[39m\"),\n\t\twhiteBright: f(\"\\x1b[97m\", \"\\x1b[39m\"),\n\n\t\tbgBlackBright: f(\"\\x1b[100m\", \"\\x1b[49m\"),\n\t\tbgRedBright: f(\"\\x1b[101m\", \"\\x1b[49m\"),\n\t\tbgGreenBright: f(\"\\x1b[102m\", \"\\x1b[49m\"),\n\t\tbgYellowBright: f(\"\\x1b[103m\", \"\\x1b[49m\"),\n\t\tbgBlueBright: f(\"\\x1b[104m\", \"\\x1b[49m\"),\n\t\tbgMagentaBright: f(\"\\x1b[105m\", \"\\x1b[49m\"),\n\t\tbgCyanBright: f(\"\\x1b[106m\", \"\\x1b[49m\"),\n\t\tbgWhiteBright: f(\"\\x1b[107m\", \"\\x1b[49m\"),\n\t}\n}\n\nmodule.exports = createColors()\nmodule.exports.createColors = createColors\n","// This file is generated by scripts/generate-embedded-version.mjs.\n// Do not edit manually.\nexport const EMBEDDED_PACKAGE_VERSION = \"0.1.5-canary.5\";\n","import os from \"node:os\";\nimport type { BatchJobsLimit } from \"./types\";\n\nconst DEFAULT_UV_THREADPOOL_SIZE = 4;\n\nfunction parsePositiveInteger(value: string | undefined): number | undefined {\n if (!value) {\n return undefined;\n }\n\n const parsed = Number.parseInt(value, 10);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n return undefined;\n }\n\n return parsed;\n}\n\nexport function resolveBatchJobsLimit(env: NodeJS.ProcessEnv = process.env): BatchJobsLimit {\n const cpuLimit = Math.max(1, os.availableParallelism());\n const uvThreadpool = parsePositiveInteger(env.UV_THREADPOOL_SIZE) ?? DEFAULT_UV_THREADPOOL_SIZE;\n const ioLimit = Math.max(1, uvThreadpool * 2);\n const suggestedMaxJobs = Math.max(1, Math.min(cpuLimit, ioLimit));\n\n return {\n suggestedMaxJobs,\n cpuLimit,\n uvThreadpool,\n ioLimit,\n };\n}\n\nexport function clampRequestedJobs(requestedJobs: number, limits: BatchJobsLimit): number {\n return Math.max(1, Math.min(requestedJobs, limits.suggestedMaxJobs));\n}\n\nexport function formatJobsAdvisoryWarning(\n requestedJobs: number,\n effectiveJobs: number,\n limits: BatchJobsLimit,\n): string {\n return [\n `Warning: requested --jobs=${requestedJobs} exceeds suggested host limit (${limits.suggestedMaxJobs}).`,\n `Running with --jobs=${effectiveJobs} as a safety cap.`,\n `Host limits: cpuLimit=${limits.cpuLimit}, uvThreadpool=${limits.uvThreadpool}, ioLimit=${limits.ioLimit}.`,\n ].join(\" \");\n}\n\nexport function isResourceLimitError(error: unknown): error is NodeJS.ErrnoException {\n if (typeof error !== \"object\" || error === null) {\n return false;\n }\n\n const code = \"code\" in error ? error.code : undefined;\n return code === \"EMFILE\" || code === \"ENFILE\";\n}\n\nexport function createResourceLimitError(\n path: string,\n error: unknown,\n requestedJobs: number,\n limits: BatchJobsLimit,\n): Error {\n const message = error instanceof Error ? error.message : String(error);\n const code =\n typeof error === \"object\" && error !== null && \"code\" in error ? String(error.code) : \"UNKNOWN\";\n\n return new Error(\n [\n `Resource limit reached while processing: ${path} (${code}: ${message}).`,\n `Requested --jobs=${requestedJobs}; suggested host limit is ${limits.suggestedMaxJobs}.`,\n \"Reduce --jobs or raise OS file descriptor limits before retrying.\",\n ].join(\" \"),\n );\n}\n","import { createResourceLimitError, resolveBatchJobsLimit } from \"./limits\";\nimport type { CountBatchWithJobsOptions, CountBatchWithJobsResult } from \"./types\";\n\nexport class WorkerRouteUnavailableError extends Error {}\n\nexport type WorkerRoutePreflight = {\n workerThreadsAvailable: boolean;\n workerRouteDisabledByEnv: boolean;\n disableWorkerJobsEnv: string | null;\n workerPoolModuleLoadable: boolean;\n workerEntryFound: boolean;\n};\n\nasync function resolveWorkerThreadsAvailability(): Promise<boolean> {\n try {\n const workerThreads = await import(\"node:worker_threads\");\n return typeof workerThreads.Worker === \"function\";\n } catch {\n return false;\n }\n}\n\nfunction isFallbackFriendlyWorkerError(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) {\n return false;\n }\n\n const code = \"code\" in error ? String(error.code) : \"\";\n if (\n code === \"ERR_WORKER_PATH\" ||\n code === \"ERR_WORKER_UNSUPPORTED_EXTENSION\" ||\n code === \"ERR_UNKNOWN_FILE_EXTENSION\" ||\n code === \"ERR_MODULE_NOT_FOUND\"\n ) {\n return true;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n return message.includes(\"Unknown file extension\") || message.includes(\"Cannot find module\");\n}\n\nexport async function resolveWorkerRoutePreflight(\n env: NodeJS.ProcessEnv = process.env,\n): Promise<WorkerRoutePreflight> {\n const disableWorkerJobsEnv = env.WORD_COUNTER_DISABLE_WORKER_JOBS ?? null;\n const workerRouteDisabledByEnv = disableWorkerJobsEnv === \"1\";\n const workerThreadsAvailable = await resolveWorkerThreadsAvailability();\n\n try {\n const workerPoolModule = await import(\"./worker-pool\");\n return {\n workerThreadsAvailable,\n workerRouteDisabledByEnv,\n disableWorkerJobsEnv,\n workerPoolModuleLoadable: true,\n workerEntryFound: workerPoolModule.resolveWorkerEntryUrl() !== null,\n };\n } catch {\n return {\n workerThreadsAvailable,\n workerRouteDisabledByEnv,\n disableWorkerJobsEnv,\n workerPoolModuleLoadable: false,\n workerEntryFound: false,\n };\n }\n}\n\nexport async function countBatchInputsWithWorkerJobs(\n filePaths: string[],\n options: CountBatchWithJobsOptions,\n): Promise<CountBatchWithJobsResult> {\n const workerRouteDisabled = process.env.WORD_COUNTER_DISABLE_WORKER_JOBS === \"1\";\n if (workerRouteDisabled) {\n throw new WorkerRouteUnavailableError(\"Worker route disabled by environment.\");\n }\n\n let workerPoolModule: Awaited<typeof import(\"./worker-pool\")>;\n try {\n workerPoolModule = await import(\"./worker-pool\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new WorkerRouteUnavailableError(`Worker route unavailable: ${message}`);\n }\n\n try {\n return await workerPoolModule.countBatchInputsWithWorkerPool({\n filePaths,\n jobs: options.jobs,\n section: options.section,\n detectorMode: options.detectorMode ?? \"regex\",\n wcOptions: options.wcOptions,\n detectBinary: options.detectBinary ?? true,\n preserveCollectorSegments: options.preserveCollectorSegments,\n detectorEvidence: options.detectorEvidence,\n debugVerbosity: options.debugVerbosity,\n onFileProcessed: options.onFileProcessed,\n onDetectorDebugEvent: options.onDetectorDebugEvent,\n debugEnabled: options.onDetectorDebugEvent !== undefined,\n });\n } catch (error) {\n if (error instanceof workerPoolModule.WorkerPoolTaskFatalError) {\n if (error.code === \"EMFILE\" || error.code === \"ENFILE\") {\n throw createResourceLimitError(\n error.path,\n { code: error.code, message: error.message },\n options.jobs,\n resolveBatchJobsLimit(),\n );\n }\n throw new Error(error.message);\n }\n\n if (\n error instanceof workerPoolModule.WorkerPoolUnavailableError ||\n isFallbackFriendlyWorkerError(error)\n ) {\n const message = error instanceof Error ? error.message : String(error);\n throw new WorkerRouteUnavailableError(`Worker route unavailable: ${message}`);\n }\n\n throw error;\n }\n}\n","import { EMBEDDED_PACKAGE_VERSION } from \"../program/version-embedded\";\nimport { resolveBatchJobsLimit } from \"../batch/jobs/limits\";\nimport { resolveWorkerRoutePreflight } from \"../batch/jobs/load-count-worker\";\nimport type {\n DoctorBuildChannel,\n DoctorReport,\n DoctorRuntimeOverrides,\n DoctorSegmenterHealth,\n DoctorStatus,\n DoctorRuntimeSummary,\n} from \"./types\";\n\nconst REQUIRED_NODE_RANGE = \">=22.18.0\";\nconst REQUIRED_NODE_VERSION = {\n major: 22,\n minor: 18,\n patch: 0,\n} as const;\nconst SAMPLE_TEXT = \"Hello 世界\";\n\nfunction normalizePackageVersion(value: string | undefined): string {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : \"0.0.0\";\n}\n\nfunction deriveBuildChannel(packageVersion: string): DoctorBuildChannel {\n const prereleaseMatch = /(?:^|[.-])(alpha|beta|rc|canary)(?:[.-]|$)/i.exec(packageVersion);\n if (!prereleaseMatch) {\n return \"stable\";\n }\n\n const channel = prereleaseMatch[1]?.toLowerCase();\n if (channel === \"alpha\" || channel === \"beta\" || channel === \"rc\" || channel === \"canary\") {\n return channel;\n }\n\n return \"stable\";\n}\n\nfunction parseNodeVersion(version: string): {\n major: number;\n minor: number;\n patch: number;\n} | null {\n const match = /^v?(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?(?:[-+].*)?$/.exec(version.trim());\n if (!match) {\n return null;\n }\n\n const major = Number.parseInt(match[1] ?? \"\", 10);\n const minor = Number.parseInt(match[2] ?? \"0\", 10);\n const patch = Number.parseInt(match[3] ?? \"0\", 10);\n\n if (!Number.isFinite(major) || !Number.isFinite(minor) || !Number.isFinite(patch)) {\n return null;\n }\n\n return { major, minor, patch };\n}\n\nfunction meetsRequiredNodeVersion(version: {\n major: number;\n minor: number;\n patch: number;\n} | null): boolean {\n if (!version) {\n return false;\n }\n\n if (version.major !== REQUIRED_NODE_VERSION.major) {\n return version.major > REQUIRED_NODE_VERSION.major;\n }\n if (version.minor !== REQUIRED_NODE_VERSION.minor) {\n return version.minor > REQUIRED_NODE_VERSION.minor;\n }\n return version.patch >= REQUIRED_NODE_VERSION.patch;\n}\n\nfunction resolveRuntimeSummary(overrides: DoctorRuntimeOverrides = {}): DoctorRuntimeSummary {\n const packageVersion = normalizePackageVersion(\n overrides.packageVersion ?? EMBEDDED_PACKAGE_VERSION,\n );\n const nodeVersion = overrides.nodeVersion ?? process.version;\n const parsedNodeVersion = parseNodeVersion(nodeVersion);\n\n return {\n packageVersion,\n buildChannel: deriveBuildChannel(packageVersion),\n requiredNodeRange: REQUIRED_NODE_RANGE,\n nodeVersion,\n meetsProjectRequirement: meetsRequiredNodeVersion(parsedNodeVersion),\n platform: overrides.platform ?? process.platform,\n arch: overrides.arch ?? process.arch,\n };\n}\n\nfunction resolveSegmenterHealth(overrides: DoctorRuntimeOverrides = {}): DoctorSegmenterHealth {\n const intlLike = overrides.intl ?? Intl;\n const Segmenter = intlLike.Segmenter;\n const available = typeof Segmenter === \"function\";\n\n let wordGranularity = false;\n let graphemeGranularity = false;\n let sampleWordSegmentation = false;\n\n if (!available) {\n return {\n available,\n wordGranularity,\n graphemeGranularity,\n sampleWordSegmentation,\n };\n }\n\n try {\n const wordSegmenter = new Segmenter(\"en\", { granularity: \"word\" });\n wordGranularity = true;\n for (const _segment of wordSegmenter.segment(SAMPLE_TEXT)) {\n sampleWordSegmentation = true;\n break;\n }\n } catch {\n wordGranularity = false;\n sampleWordSegmentation = false;\n }\n\n try {\n new Segmenter(\"en\", { granularity: \"grapheme\" });\n graphemeGranularity = true;\n } catch {\n graphemeGranularity = false;\n }\n\n return {\n available,\n wordGranularity,\n graphemeGranularity,\n sampleWordSegmentation,\n };\n}\n\nfunction collectWarnings(\n runtime: DoctorRuntimeSummary,\n segmenter: DoctorSegmenterHealth,\n workerRoute: Awaited<ReturnType<typeof resolveWorkerRoutePreflight>>,\n): string[] {\n const warnings: string[] = [];\n\n if (!runtime.meetsProjectRequirement) {\n warnings.push(\n `Node.js ${runtime.nodeVersion} is outside the supported range ${runtime.requiredNodeRange}.`,\n );\n }\n\n if (!segmenter.available) {\n warnings.push(\"Intl.Segmenter is unavailable.\");\n } else {\n if (!segmenter.wordGranularity) {\n warnings.push(\"Intl.Segmenter word granularity is unusable.\");\n }\n if (!segmenter.graphemeGranularity) {\n warnings.push(\"Intl.Segmenter grapheme granularity is unusable.\");\n }\n if (!segmenter.sampleWordSegmentation) {\n warnings.push(\"Intl.Segmenter sample segmentation failed.\");\n }\n }\n\n if (!workerRoute.workerThreadsAvailable) {\n warnings.push(\"Worker threads are unavailable on this runtime.\");\n }\n if (workerRoute.workerRouteDisabledByEnv) {\n warnings.push(\"Worker route is disabled by environment.\");\n }\n if (!workerRoute.workerPoolModuleLoadable) {\n warnings.push(\"Worker route preflight failed: worker-pool module could not be loaded.\");\n } else if (!workerRoute.workerEntryFound) {\n warnings.push(\"Worker route preflight failed: count-worker entry file was not found.\");\n }\n\n return warnings;\n}\n\nfunction resolveStatus(segmenter: DoctorSegmenterHealth, warnings: string[]): DoctorStatus {\n const hardFailure =\n !segmenter.available ||\n !segmenter.wordGranularity ||\n !segmenter.graphemeGranularity ||\n !segmenter.sampleWordSegmentation;\n\n if (hardFailure) {\n return \"fail\";\n }\n\n if (warnings.length > 0) {\n return \"warn\";\n }\n\n return \"ok\";\n}\n\nexport async function createDoctorReport(\n overrides: DoctorRuntimeOverrides = {},\n): Promise<DoctorReport> {\n const runtime = resolveRuntimeSummary(overrides);\n const segmenter = resolveSegmenterHealth(overrides);\n const env = overrides.env ?? process.env;\n const jobs = resolveBatchJobsLimit(env);\n const workerRoute = await resolveWorkerRoutePreflight(env);\n const warnings = collectWarnings(runtime, segmenter, workerRoute);\n\n return {\n status: resolveStatus(segmenter, warnings),\n runtime,\n segmenter,\n jobs,\n workerRoute,\n warnings,\n };\n}\n\nexport { REQUIRED_NODE_RANGE };\n","import pc from \"picocolors\";\nimport type { DoctorOutputFormat, DoctorReport, DoctorStatus } from \"./types\";\n\ntype RenderDoctorReportOptions = {\n format: DoctorOutputFormat;\n pretty: boolean;\n};\n\nfunction colorStatus(status: DoctorStatus): string {\n if (status === \"ok\") {\n return pc.green(pc.bold(status));\n }\n if (status === \"warn\") {\n return pc.yellow(pc.bold(status));\n }\n return pc.red(pc.bold(status));\n}\n\nfunction renderSection(title: string, lines: string[]): void {\n console.log(pc.bold(title));\n for (const line of lines) {\n console.log(`- ${line}`);\n }\n console.log(\"\");\n}\n\nfunction colorBoolean(value: boolean, yes = \"yes\", no = \"no\"): string {\n return value ? pc.green(yes) : pc.red(no);\n}\n\nfunction colorNumber(value: number): string {\n return pc.yellow(String(value));\n}\n\nfunction colorStatusWord(value: boolean): string {\n return value ? pc.green(\"ok\") : pc.red(\"fail\");\n}\n\nfunction renderStandardDoctorReport(report: DoctorReport): void {\n console.log(`Doctor: ${colorStatus(report.status)}`);\n console.log(\"\");\n\n renderSection(\"Runtime\", [\n `package: ${report.runtime.packageVersion} (${report.runtime.buildChannel})`,\n `node: ${report.runtime.nodeVersion} (supported: ${colorBoolean(\n report.runtime.meetsProjectRequirement,\n )}; required ${report.runtime.requiredNodeRange})`,\n `platform: ${report.runtime.platform} ${report.runtime.arch}`,\n ]);\n\n renderSection(\"Segmenter\", [\n `Intl.Segmenter: ${colorBoolean(report.segmenter.available, \"available\", \"missing\")}`,\n `word granularity: ${colorStatusWord(report.segmenter.wordGranularity)}`,\n `grapheme granularity: ${colorStatusWord(report.segmenter.graphemeGranularity)}`,\n `sample segmentation: ${colorStatusWord(report.segmenter.sampleWordSegmentation)}`,\n ]);\n\n renderSection(\"Batch jobs\", [\n `cpuLimit: ${colorNumber(report.jobs.cpuLimit)}`,\n `uvThreadpool: ${colorNumber(report.jobs.uvThreadpool)}`,\n `ioLimit: ${colorNumber(report.jobs.ioLimit)}`,\n `suggestedMaxJobs: ${colorNumber(report.jobs.suggestedMaxJobs)}`,\n ]);\n\n renderSection(\"Worker route\", [\n `worker threads: ${colorBoolean(report.workerRoute.workerThreadsAvailable, \"available\", \"missing\")}`,\n `disabled by env: ${colorBoolean(report.workerRoute.workerRouteDisabledByEnv)}`,\n `disableWorkerJobsEnv: ${report.workerRoute.disableWorkerJobsEnv ?? \"null\"}`,\n `worker pool module: ${colorBoolean(report.workerRoute.workerPoolModuleLoadable, \"loadable\", \"missing\")}`,\n `worker entry: ${colorBoolean(report.workerRoute.workerEntryFound, \"found\", \"missing\")}`,\n ]);\n\n if (report.warnings.length > 0) {\n console.log(pc.bold(\"Warnings\"));\n for (const warning of report.warnings) {\n console.log(pc.yellow(`- ${warning}`));\n }\n }\n}\n\nexport function renderDoctorReport(report: DoctorReport, options: RenderDoctorReportOptions): void {\n if (options.format === \"json\") {\n console.log(JSON.stringify(report, null, options.pretty ? 2 : 0));\n return;\n }\n\n renderStandardDoctorReport(report);\n}\n","import pc from \"picocolors\";\nimport { createDoctorReport } from \"./checks\";\nimport { renderDoctorReport } from \"./render\";\nimport type { DoctorOutputFormat, DoctorRuntimeOverrides } from \"./types\";\n\ntype ExecuteDoctorCommandOptions = {\n argv: string[];\n runtime?: DoctorRuntimeOverrides;\n};\n\ntype ValidDoctorInvocation =\n | {\n ok: true;\n format: DoctorOutputFormat;\n pretty: boolean;\n }\n | {\n ok: true;\n help: true;\n }\n | {\n ok: false;\n message: string;\n };\n\nconst DOCTOR_HELP_LINES = [\n \"Usage: word-counter doctor [options]\",\n \"\",\n \"report runtime diagnostics for this host\",\n \"\",\n \"Options:\",\n \" --format <format> doctor output format (json)\",\n \" --pretty pretty print doctor JSON output (default: false)\",\n \" -h, --help display help for command\",\n];\n\nfunction parseDoctorFormat(rawValue: string | undefined): DoctorOutputFormat | null {\n if (rawValue === undefined) {\n return \"standard\";\n }\n if (rawValue === \"json\") {\n return \"json\";\n }\n return null;\n}\n\nfunction validateDoctorInvocation(argv: string[]): ValidDoctorInvocation {\n const doctorIndex = argv.findIndex((token, index) => index >= 2 && token === \"doctor\");\n const tokens = doctorIndex >= 0 ? argv.slice(doctorIndex + 1) : [];\n let expectsFormatValue = false;\n let format: DoctorOutputFormat = \"standard\";\n let pretty = false;\n\n for (const token of tokens) {\n if (token === \"-h\" || token === \"--help\") {\n return {\n ok: true,\n help: true,\n };\n }\n\n if (expectsFormatValue) {\n const parsedFormat = parseDoctorFormat(token);\n if (parsedFormat === null) {\n return {\n ok: false,\n message: \"`doctor` only supports default text output or `--format json`.\",\n };\n }\n format = parsedFormat;\n expectsFormatValue = false;\n continue;\n }\n\n if (token === \"--\") {\n return {\n ok: false,\n message: \"`doctor` does not accept positional inputs.\",\n };\n }\n\n if (token === \"--format\") {\n expectsFormatValue = true;\n continue;\n }\n\n if (token.startsWith(\"--format=\")) {\n const rawValue = token.slice(\"--format=\".length);\n if (rawValue.length === 0) {\n return {\n ok: false,\n message: \"`--format` requires a value.\",\n };\n }\n const parsedFormat = parseDoctorFormat(rawValue);\n if (parsedFormat === null) {\n return {\n ok: false,\n message: \"`doctor` only supports default text output or `--format json`.\",\n };\n }\n format = parsedFormat;\n continue;\n }\n\n if (token === \"--pretty\") {\n pretty = true;\n continue;\n }\n\n if (token.startsWith(\"-\")) {\n return {\n ok: false,\n message: `\\`${token}\\` is not supported by \\`doctor\\`.`,\n };\n }\n\n return {\n ok: false,\n message: \"`doctor` does not accept positional inputs.\",\n };\n }\n\n if (expectsFormatValue) {\n return {\n ok: false,\n message: \"`--format` requires a value.\",\n };\n }\n\n if (pretty && format !== \"json\") {\n return {\n ok: false,\n message: \"`--pretty` requires `--format json`.\",\n };\n }\n\n return {\n ok: true,\n format,\n pretty,\n };\n}\n\nexport function isExplicitDoctorInvocation(argv: string[]): boolean {\n if (argv[2] !== \"doctor\") {\n return false;\n }\n\n const trailingTokens = argv.slice(3);\n if (trailingTokens.length === 0) {\n return true;\n }\n\n return trailingTokens.some((token) => token === \"--\" || token.startsWith(\"-\"));\n}\n\nfunction printDoctorHelp(): void {\n for (const line of DOCTOR_HELP_LINES) {\n console.log(line);\n }\n}\n\nexport async function executeDoctorCommand({\n argv,\n runtime,\n}: ExecuteDoctorCommandOptions): Promise<void> {\n const validated = validateDoctorInvocation(argv);\n if (!validated.ok) {\n console.error(pc.red(`error: ${validated.message}`));\n process.exitCode = 1;\n return;\n }\n\n if (\"help\" in validated) {\n printDoctorHelp();\n process.exitCode = 0;\n return;\n }\n\n const report = await createDoctorReport(runtime);\n renderDoctorReport(report, {\n format: validated.format,\n pretty: validated.pretty,\n });\n process.exitCode = report.status === \"fail\" ? 2 : 0;\n}\n","export function ensureArrayContainer(\n result: Record<string, unknown>,\n key: string,\n): Record<string, unknown>[] {\n const existing = result[key];\n if (Array.isArray(existing)) {\n return existing as Record<string, unknown>[];\n }\n const list: Record<string, unknown>[] = [];\n result[key] = list;\n return list;\n}\n\nexport function flattenArrayTables(result: Record<string, unknown>): void {\n for (const [key, value] of Object.entries(result)) {\n if (!Array.isArray(value)) {\n continue;\n }\n const flattened = value\n .map((entry) =>\n Object.entries(entry)\n .map(([entryKey, entryValue]) => `${entryKey}=${entryValue}`)\n .join(\", \"),\n )\n .join(\" | \");\n result[key] = flattened;\n }\n}\n","function stripKeyQuotes(key: string): string {\n const trimmed = key.trim();\n if (\n (trimmed.startsWith('\"') && trimmed.endsWith('\"')) ||\n (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\"))\n ) {\n return trimmed.slice(1, -1);\n }\n return trimmed;\n}\n\nexport function normalizeKeyPath(key: string): string | null {\n const trimmed = key.trim();\n if (!trimmed) {\n return null;\n }\n\n if (\n (trimmed.startsWith('\"') && trimmed.endsWith('\"')) ||\n (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\"))\n ) {\n const unquoted = stripKeyQuotes(trimmed);\n return unquoted ? unquoted : null;\n }\n\n const segments = trimmed.split(\".\").map((segment) => segment.trim());\n if (segments.some((segment) => !segment)) {\n return null;\n }\n return segments.join(\".\");\n}\n","export function stripInlineComment(line: string): string {\n let inString: \"single\" | \"double\" | null = null;\n let escaped = false;\n\n for (let i = 0; i < line.length; i += 1) {\n const char = line[i] ?? \"\";\n\n if (inString) {\n if (escaped) {\n escaped = false;\n continue;\n }\n\n if (char === \"\\\\\" && inString === \"double\") {\n escaped = true;\n continue;\n }\n\n if (inString === \"double\" && char === '\"') {\n inString = null;\n continue;\n }\n\n if (inString === \"single\" && char === \"'\") {\n inString = null;\n continue;\n }\n\n continue;\n }\n\n if (char === '\"') {\n inString = \"double\";\n continue;\n }\n\n if (char === \"'\") {\n inString = \"single\";\n continue;\n }\n\n if (char === \"#\") {\n return line.slice(0, i).trimEnd();\n }\n }\n\n return line;\n}\n\nfunction unescapeBasic(input: string): string {\n return input\n .replace(/\\\\\\\\/g, \"\\\\\")\n .replace(/\\\\\"/g, '\"')\n .replace(/\\\\n/g, \"\\n\")\n .replace(/\\\\t/g, \"\\t\")\n .replace(/\\\\r/g, \"\\r\");\n}\n\nexport function parseStringLiteral(value: string): string | null {\n if (value.startsWith('\"\"\"') && value.endsWith('\"\"\"')) {\n const inner = value.slice(3, -3);\n return unescapeBasic(inner);\n }\n\n if (value.startsWith(\"'''\") && value.endsWith(\"'''\")) {\n return value.slice(3, -3);\n }\n\n if (value.startsWith('\"') && value.endsWith('\"')) {\n return unescapeBasic(value.slice(1, -1));\n }\n\n if (value.startsWith(\"'\") && value.endsWith(\"'\")) {\n return value.slice(1, -1);\n }\n\n return null;\n}\n","import { normalizeKeyPath } from \"./keys\";\nimport { parseStringLiteral } from \"./strings\";\nimport type { TomlValue } from \"./types\";\n\nfunction parsePrimitive(raw: string): string | number | boolean | null {\n const value = raw.trim();\n if (!value) {\n return null;\n }\n\n const stringLiteral = parseStringLiteral(value);\n if (stringLiteral !== null) {\n return stringLiteral;\n }\n\n if (value === \"true\") {\n return true;\n }\n\n if (value === \"false\") {\n return false;\n }\n\n if (/^[+-]?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/.test(value)) {\n return Number(value);\n }\n\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(value)) {\n return value;\n }\n\n return value;\n}\n\nfunction parseArray(raw: string): Array<string | number | boolean> | null {\n const value = raw.trim();\n if (!value.startsWith(\"[\") || !value.endsWith(\"]\")) {\n return null;\n }\n\n const inner = value.slice(1, -1).trim();\n if (!inner) {\n return [];\n }\n\n const items: Array<string | number | boolean> = [];\n let current = \"\";\n let inString: \"single\" | \"double\" | null = null;\n let escaped = false;\n\n for (let i = 0; i < inner.length; i += 1) {\n const char = inner[i] ?? \"\";\n\n if (inString) {\n current += char;\n if (escaped) {\n escaped = false;\n continue;\n }\n\n if (char === \"\\\\\" && inString === \"double\") {\n escaped = true;\n continue;\n }\n\n if (inString === \"double\" && char === '\"') {\n inString = null;\n } else if (inString === \"single\" && char === \"'\") {\n inString = null;\n }\n continue;\n }\n\n if (char === '\"') {\n inString = \"double\";\n current += char;\n continue;\n }\n\n if (char === \"'\") {\n inString = \"single\";\n current += char;\n continue;\n }\n\n if (char === \",\") {\n const item = parsePrimitive(current);\n if (item === null) {\n return null;\n }\n items.push(item);\n current = \"\";\n continue;\n }\n\n current += char;\n }\n\n const finalItem = parsePrimitive(current);\n if (finalItem === null) {\n return null;\n }\n items.push(finalItem);\n\n return items;\n}\n\nfunction parseInlineTable(raw: string): Record<string, TomlValue> | null {\n const trimmed = raw.trim();\n if (!trimmed.startsWith(\"{\") || !trimmed.endsWith(\"}\")) {\n return null;\n }\n\n const inner = trimmed.slice(1, -1).trim();\n if (!inner) {\n return {};\n }\n\n const pairs: string[] = [];\n let current = \"\";\n let inString: \"single\" | \"double\" | null = null;\n let escaped = false;\n let bracketDepth = 0;\n let braceDepth = 0;\n\n for (let i = 0; i < inner.length; i += 1) {\n const char = inner[i] ?? \"\";\n\n if (inString) {\n current += char;\n if (escaped) {\n escaped = false;\n continue;\n }\n\n if (char === \"\\\\\" && inString === \"double\") {\n escaped = true;\n continue;\n }\n\n if (inString === \"double\" && char === '\"') {\n inString = null;\n } else if (inString === \"single\" && char === \"'\") {\n inString = null;\n }\n continue;\n }\n\n if (char === '\"') {\n inString = \"double\";\n current += char;\n continue;\n }\n\n if (char === \"'\") {\n inString = \"single\";\n current += char;\n continue;\n }\n\n if (char === \"[\") {\n bracketDepth += 1;\n current += char;\n continue;\n }\n\n if (char === \"]\") {\n if (bracketDepth > 0) {\n bracketDepth -= 1;\n }\n current += char;\n continue;\n }\n\n if (char === \"{\") {\n braceDepth += 1;\n current += char;\n continue;\n }\n\n if (char === \"}\") {\n if (braceDepth > 0) {\n braceDepth -= 1;\n }\n current += char;\n continue;\n }\n\n if (char === \",\" && bracketDepth === 0 && braceDepth === 0) {\n pairs.push(current);\n current = \"\";\n continue;\n }\n\n current += char;\n }\n\n if (current.trim()) {\n pairs.push(current);\n }\n\n const output: Record<string, TomlValue> = {};\n for (const pair of pairs) {\n const separatorIndex = pair.indexOf(\"=\");\n if (separatorIndex === -1) {\n return null;\n }\n const key = normalizeKeyPath(pair.slice(0, separatorIndex));\n if (!key) {\n return null;\n }\n const valueRaw = pair.slice(separatorIndex + 1).trim();\n if (!valueRaw) {\n return null;\n }\n if (valueRaw.startsWith(\"{\")) {\n return null;\n }\n const normalized = normalizeValue(valueRaw);\n if (normalized === null) {\n return null;\n }\n if (typeof normalized === \"object\" && !Array.isArray(normalized)) {\n return null;\n }\n output[key] = normalized;\n }\n\n return output;\n}\n\nexport function normalizeValue(value: string): TomlValue | null {\n if (!value) {\n return null;\n }\n\n const trimmed = value.trim();\n if (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\")) {\n return parseInlineTable(trimmed);\n }\n\n const array = parseArray(trimmed);\n if (array) {\n return array;\n }\n\n if (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) {\n return null;\n }\n\n return parsePrimitive(trimmed);\n}\n\nexport function toPlainText(value: unknown): string {\n if (value == null) {\n return \"\";\n }\n if (Array.isArray(value)) {\n return value.map((item) => String(item)).join(\", \");\n }\n return String(value);\n}\n","import { ensureArrayContainer, flattenArrayTables } from \"./arrays\";\nimport { normalizeKeyPath } from \"./keys\";\nimport { stripInlineComment } from \"./strings\";\nimport { normalizeValue, toPlainText } from \"./values\";\n\nexport function parseTomlFrontmatter(frontmatter: string): Record<string, unknown> | null {\n const result: Record<string, unknown> = {};\n const lines = frontmatter.split(\"\\n\");\n let tablePrefix = \"\";\n let tableTarget: Record<string, unknown> | null = null;\n let tablePrefixInList = false;\n\n for (let index = 0; index < lines.length; index += 1) {\n const rawLine = lines[index] ?? \"\";\n const trimmedLine = rawLine.trim();\n if (!trimmedLine || trimmedLine.startsWith(\"#\")) {\n continue;\n }\n\n if (trimmedLine.startsWith(\"[[\")) {\n const match = trimmedLine.match(/^\\[\\[([^\\]]+)]]$/);\n if (!match) {\n return null;\n }\n const normalizedTable = normalizeKeyPath(match[1] ?? \"\");\n if (!normalizedTable) {\n return null;\n }\n const list = ensureArrayContainer(result, normalizedTable);\n const newEntry: Record<string, unknown> = {};\n list.push(newEntry);\n tableTarget = newEntry;\n tablePrefix = normalizedTable;\n tablePrefixInList = true;\n continue;\n }\n\n const tableMatch = trimmedLine.match(/^\\[([^\\]]+)]$/);\n if (tableMatch) {\n const normalizedTable = normalizeKeyPath(tableMatch[1] ?? \"\");\n if (!normalizedTable) {\n return null;\n }\n tablePrefix = normalizedTable;\n tablePrefixInList = false;\n tableTarget = null;\n continue;\n }\n\n const lineForParsing = /(\"\"\"|''')/.test(rawLine) ? rawLine : stripInlineComment(rawLine);\n const separatorIndex = lineForParsing.indexOf(\"=\");\n if (separatorIndex === -1) {\n return null;\n }\n\n const keyRaw = lineForParsing.slice(0, separatorIndex);\n const key = normalizeKeyPath(keyRaw);\n let valueRaw = lineForParsing.slice(separatorIndex + 1).trim();\n if (!key) {\n return null;\n }\n\n const tripleDelimiter = valueRaw.startsWith('\"\"\"')\n ? '\"\"\"'\n : valueRaw.startsWith(\"'''\")\n ? \"'''\"\n : null;\n if (tripleDelimiter) {\n const closingIndex = valueRaw.indexOf(tripleDelimiter, tripleDelimiter.length);\n if (closingIndex !== -1) {\n const after = valueRaw.slice(closingIndex + tripleDelimiter.length);\n const strippedAfter = stripInlineComment(after);\n valueRaw = `${valueRaw.slice(0, closingIndex + tripleDelimiter.length)}${strippedAfter}`;\n } else {\n const delimiter = tripleDelimiter;\n let combined = valueRaw;\n let closed = false;\n while (index + 1 < lines.length) {\n index += 1;\n const nextLine = lines[index] ?? \"\";\n combined += `\\n${nextLine}`;\n if (new RegExp(`${delimiter}\\\\s*$`).test(nextLine)) {\n closed = true;\n break;\n }\n }\n if (!closed) {\n return null;\n }\n valueRaw = combined;\n }\n }\n\n const normalized = normalizeValue(valueRaw);\n if (normalized === null) {\n return null;\n }\n\n const fullKey = tablePrefix ? `${tablePrefix}.${key}` : key;\n if (typeof normalized === \"object\" && !Array.isArray(normalized)) {\n for (const [inlineKey, inlineValue] of Object.entries(normalized)) {\n const entryKey = tablePrefixInList ? `${key}.${inlineKey}` : `${fullKey}.${inlineKey}`;\n if (tablePrefixInList && tableTarget) {\n tableTarget[entryKey] = toPlainText(inlineValue);\n } else {\n result[entryKey] = toPlainText(inlineValue);\n }\n }\n continue;\n }\n\n if (tablePrefixInList && tableTarget) {\n tableTarget[key] = toPlainText(normalized);\n continue;\n }\n\n result[fullKey] = toPlainText(normalized);\n }\n\n flattenArrayTables(result);\n\n return result;\n}\n","import { parseDocument } from \"yaml\";\nimport { parseTomlFrontmatter } from \"./toml-simple\";\nimport type { FrontmatterType, ParsedMarkdown } from \"./types\";\n\nconst FENCE_TO_TYPE: Record<string, FrontmatterType> = {\n \"---\": \"yaml\",\n \"+++\": \"toml\",\n \";;;\": \"json\",\n};\n\nfunction normalizeNewlines(input: string): string {\n return input.replace(/\\r\\n/g, \"\\n\");\n}\n\nfunction stripBom(line: string): string {\n return line.startsWith(\"\\uFEFF\") ? line.slice(1) : line;\n}\n\nfunction getFenceType(line: string): FrontmatterType | null {\n const match = line.match(/^[\\t ]*(---|\\+\\+\\+|;;;)[\\t ]*$/);\n if (!match) {\n return null;\n }\n return FENCE_TO_TYPE[match[1] ?? \"\"] ?? null;\n}\n\nfunction parseFrontmatter(\n frontmatter: string,\n type: FrontmatterType | null,\n): Record<string, unknown> | null {\n if (!type) {\n return null;\n }\n\n if (type === \"json\") {\n try {\n return JSON.parse(frontmatter) as Record<string, unknown>;\n } catch {\n return null;\n }\n }\n\n if (type === \"yaml\") {\n const doc = parseDocument(frontmatter, { prettyErrors: false });\n if (doc.errors.length > 0) {\n return null;\n }\n const data = doc.toJSON();\n if (!data || typeof data !== \"object\" || Array.isArray(data)) {\n return null;\n }\n return data as Record<string, unknown>;\n }\n\n if (type === \"toml\") {\n return parseTomlFrontmatter(frontmatter);\n }\n\n return null;\n}\n\nfunction extractJsonBlock(\n text: string,\n startIndex: number,\n): { jsonText: string; endIndex: number } | null {\n let depth = 0;\n let inString = false;\n let escaped = false;\n\n for (let i = startIndex; i < text.length; i += 1) {\n const char = text[i] ?? \"\";\n\n if (inString) {\n if (escaped) {\n escaped = false;\n continue;\n }\n\n if (char === \"\\\\\") {\n escaped = true;\n continue;\n }\n\n if (char === '\"') {\n inString = false;\n }\n\n continue;\n }\n\n if (char === '\"') {\n inString = true;\n continue;\n }\n\n if (char === \"{\") {\n depth += 1;\n continue;\n }\n\n if (char === \"}\") {\n depth -= 1;\n if (depth === 0) {\n const jsonText = text.slice(startIndex, i + 1);\n return { jsonText, endIndex: i };\n }\n }\n }\n\n return null;\n}\n\nexport function parseMarkdown(input: string): ParsedMarkdown {\n const normalized = normalizeNewlines(input);\n const lines = normalized.split(\"\\n\");\n if (lines.length === 0) {\n return { frontmatter: null, content: normalized, data: null, frontmatterType: null };\n }\n\n lines[0] = stripBom(lines[0] ?? \"\");\n const normalizedWithoutBom = lines.join(\"\\n\");\n\n const openingType = getFenceType(lines[0] ?? \"\");\n if (!openingType) {\n const leadingWhitespace = normalizedWithoutBom.match(/^[\\t \\n]*/)?.[0] ?? \"\";\n const jsonStart = leadingWhitespace.length;\n if (normalizedWithoutBom[jsonStart] !== \"{\") {\n return {\n frontmatter: null,\n content: normalizedWithoutBom,\n data: null,\n frontmatterType: null,\n };\n }\n\n const jsonBlock = extractJsonBlock(normalizedWithoutBom, jsonStart);\n if (!jsonBlock) {\n return {\n frontmatter: null,\n content: normalizedWithoutBom,\n data: null,\n frontmatterType: null,\n };\n }\n\n const frontmatter = jsonBlock.jsonText;\n let content = normalizedWithoutBom.slice(jsonBlock.endIndex + 1);\n if (content.startsWith(\"\\n\")) {\n content = content.slice(1);\n }\n const data = parseFrontmatter(frontmatter, \"json\");\n if (!data) {\n return {\n frontmatter: null,\n content: normalizedWithoutBom,\n data: null,\n frontmatterType: null,\n };\n }\n\n return {\n frontmatter,\n content,\n data,\n frontmatterType: \"json\",\n };\n }\n\n let closingIndex = -1;\n for (let i = 1; i < lines.length; i += 1) {\n if (getFenceType(lines[i] ?? \"\") === openingType) {\n closingIndex = i;\n break;\n }\n }\n\n if (closingIndex === -1) {\n return { frontmatter: null, content: normalizedWithoutBom, data: null, frontmatterType: null };\n }\n\n const frontmatter = lines.slice(1, closingIndex).join(\"\\n\");\n const content = lines.slice(closingIndex + 1).join(\"\\n\");\n const data = parseFrontmatter(frontmatter, openingType);\n\n return {\n frontmatter,\n content,\n data,\n frontmatterType: openingType,\n };\n}\n","const segmenterCache = new Map<string, Intl.Segmenter>();\nconst graphemeSegmenterCache = new Map<string, Intl.Segmenter>();\n\nexport function getSegmenter(locale: string): Intl.Segmenter {\n const cached = segmenterCache.get(locale);\n if (cached) {\n return cached;\n }\n const segmenter = new Intl.Segmenter(locale, { granularity: \"word\" });\n segmenterCache.set(locale, segmenter);\n return segmenter;\n}\n\nexport function getGraphemeSegmenter(locale: string): Intl.Segmenter {\n const cached = graphemeSegmenterCache.get(locale);\n if (cached) {\n return cached;\n }\n const segmenter = new Intl.Segmenter(locale, { granularity: \"grapheme\" });\n graphemeSegmenterCache.set(locale, segmenter);\n return segmenter;\n}\n\nfunction supportsSegmenter(): boolean {\n return typeof Intl !== \"undefined\" && typeof Intl.Segmenter === \"function\";\n}\n\nexport function countWordsForLocale(text: string, locale: string): number {\n const segmenter = getSegmenter(locale);\n let count = 0;\n for (const segment of segmenter.segment(text)) {\n if (segment.isWordLike) {\n count++;\n }\n }\n return count;\n}\n\nexport function countCharsForLocale(text: string, locale: string): number {\n if (!supportsSegmenter()) {\n return Array.from(text).length;\n }\n const segmenter = getGraphemeSegmenter(locale);\n let count = 0;\n for (const _segment of segmenter.segment(text)) {\n count++;\n }\n return count;\n}\n","export function appendAll<T>(target: T[], source: readonly T[]): void {\n for (const item of source) {\n target.push(item);\n }\n}\n","import type { NonWordCollection, WhitespaceCounts } from \"./types\";\nimport { appendAll } from \"../utils/append-all\";\n\nconst emojiRegex = /(?:\\p{Extended_Pictographic}|\\p{Emoji_Presentation})/u;\nconst emojiPresentationRegex = /\\p{Emoji_Presentation}/u;\nconst keycapEmojiRegex = /[0-9#*]\\uFE0F?\\u20E3/u;\nconst symbolRegex = /\\p{S}/u;\nconst punctuationRegex = /\\p{P}/u;\nconst whitespaceRegex = /\\s/u;\nconst newlineChars = new Set([\"\\n\", \"\\r\", \"\\u2028\", \"\\u2029\"]);\n\nexport function createNonWordCollection(): NonWordCollection {\n return {\n emoji: [],\n symbols: [],\n punctuation: [],\n counts: {\n emoji: 0,\n symbols: 0,\n punctuation: 0,\n },\n };\n}\n\nexport function addNonWord(\n collection: NonWordCollection,\n category: \"emoji\" | \"symbol\" | \"punctuation\",\n segment: string,\n): void {\n if (category === \"emoji\") {\n collection.emoji.push(segment);\n collection.counts.emoji += 1;\n return;\n }\n if (category === \"symbol\") {\n collection.symbols.push(segment);\n collection.counts.symbols += 1;\n return;\n }\n collection.punctuation.push(segment);\n collection.counts.punctuation += 1;\n}\n\nexport function addWhitespace(collection: NonWordCollection, segment: string): number {\n let whitespace = collection.whitespace;\n let count = 0;\n for (const char of segment) {\n if (char === \" \") {\n whitespace = whitespace ?? createWhitespaceCounts();\n whitespace.spaces += 1;\n count += 1;\n continue;\n }\n if (char === \"\\t\") {\n whitespace = whitespace ?? createWhitespaceCounts();\n whitespace.tabs += 1;\n count += 1;\n continue;\n }\n if (newlineChars.has(char)) {\n whitespace = whitespace ?? createWhitespaceCounts();\n whitespace.newlines += 1;\n count += 1;\n continue;\n }\n if (whitespaceRegex.test(char)) {\n whitespace = whitespace ?? createWhitespaceCounts();\n whitespace.other += 1;\n count += 1;\n }\n }\n\n if (count > 0) {\n collection.whitespace = whitespace ?? createWhitespaceCounts();\n collection.counts.whitespace = (collection.counts.whitespace ?? 0) + count;\n }\n\n return count;\n}\n\nexport function classifyNonWordSegment(segment: string): \"emoji\" | \"symbol\" | \"punctuation\" | null {\n const hasEmojiVariationSelector = segment.includes(\"\\uFE0F\");\n if (\n keycapEmojiRegex.test(segment) ||\n emojiPresentationRegex.test(segment) ||\n (hasEmojiVariationSelector && emojiRegex.test(segment))\n ) {\n return \"emoji\";\n }\n if (symbolRegex.test(segment)) {\n return \"symbol\";\n }\n if (punctuationRegex.test(segment)) {\n return \"punctuation\";\n }\n return null;\n}\n\nexport function mergeNonWordCollections(\n target: NonWordCollection,\n source: NonWordCollection,\n): NonWordCollection {\n if (source.counts.emoji > 0) {\n appendAll(target.emoji, source.emoji);\n target.counts.emoji += source.counts.emoji;\n }\n if (source.counts.symbols > 0) {\n appendAll(target.symbols, source.symbols);\n target.counts.symbols += source.counts.symbols;\n }\n if (source.counts.punctuation > 0) {\n appendAll(target.punctuation, source.punctuation);\n target.counts.punctuation += source.counts.punctuation;\n }\n if (source.counts.whitespace && source.counts.whitespace > 0 && source.whitespace) {\n const whitespace = target.whitespace ?? createWhitespaceCounts();\n whitespace.spaces += source.whitespace.spaces;\n whitespace.tabs += source.whitespace.tabs;\n whitespace.newlines += source.whitespace.newlines;\n whitespace.other += source.whitespace.other;\n target.whitespace = whitespace;\n target.counts.whitespace = (target.counts.whitespace ?? 0) + source.counts.whitespace;\n }\n return target;\n}\n\nfunction createWhitespaceCounts(): WhitespaceCounts {\n return { spaces: 0, tabs: 0, newlines: 0, other: 0 };\n}\n","import { countCharsForLocale, getSegmenter } from \"./segmenter\";\nimport {\n addNonWord,\n addWhitespace,\n classifyNonWordSegment,\n createNonWordCollection,\n mergeNonWordCollections,\n} from \"./non-words\";\nimport { appendAll } from \"../utils/append-all\";\nimport type {\n CharCollectorBreakdown,\n ChunkAnalysis,\n CollectorBreakdown,\n LocaleChunk,\n NonWordCollection,\n} from \"./types\";\n\ntype CharAnalysis = LocaleChunk & { chars: number; nonWords?: NonWordCollection };\ntype CharChunkAnalysis = CharAnalysis & { wordChars: number; nonWordChars: number };\n\nexport function analyzeChunk(\n chunk: LocaleChunk,\n collectNonWords?: boolean,\n includeWhitespace?: boolean,\n): ChunkAnalysis {\n const segmenter = getSegmenter(chunk.locale);\n const segments: string[] = [];\n const nonWords: NonWordCollection | null = collectNonWords ? createNonWordCollection() : null;\n for (const part of segmenter.segment(chunk.text)) {\n if (part.isWordLike) {\n segments.push(part.segment);\n } else if (collectNonWords && nonWords) {\n if (includeWhitespace) {\n addWhitespace(nonWords, part.segment);\n }\n const category = classifyNonWordSegment(part.segment);\n if (category) {\n addNonWord(nonWords, category, part.segment);\n }\n }\n }\n return {\n locale: chunk.locale,\n text: chunk.text,\n segments,\n words: segments.length,\n nonWords: nonWords ?? undefined,\n };\n}\n\nexport function analyzeCharChunk(\n chunk: LocaleChunk,\n collectNonWords?: boolean,\n includeWhitespace?: boolean,\n): CharChunkAnalysis {\n const segmenter = getSegmenter(chunk.locale);\n const nonWords: NonWordCollection | null = collectNonWords ? createNonWordCollection() : null;\n let chars = 0;\n let wordChars = 0;\n let nonWordChars = 0;\n\n for (const part of segmenter.segment(chunk.text)) {\n if (part.isWordLike) {\n const count = countCharsForLocale(part.segment, chunk.locale);\n chars += count;\n wordChars += count;\n continue;\n }\n\n if (collectNonWords && nonWords) {\n let whitespaceCount = 0;\n if (includeWhitespace) {\n whitespaceCount = addWhitespace(nonWords, part.segment);\n }\n const category = classifyNonWordSegment(part.segment);\n if (category) {\n addNonWord(nonWords, category, part.segment);\n }\n if (category || whitespaceCount > 0) {\n const count = countCharsForLocale(part.segment, chunk.locale);\n chars += count;\n nonWordChars += count;\n }\n }\n }\n\n return {\n locale: chunk.locale,\n text: chunk.text,\n chars,\n wordChars,\n nonWordChars,\n nonWords: nonWords ?? undefined,\n };\n}\n\nexport function aggregateCharsByLocale(\n chunks: CharChunkAnalysis[],\n): Array<CharCollectorBreakdown & { wordChars: number; nonWordChars: number }> {\n const order: string[] = [];\n const map = new Map<\n string,\n CharCollectorBreakdown & { wordChars: number; nonWordChars: number }\n >();\n\n for (const chunk of chunks) {\n const existing = map.get(chunk.locale);\n if (existing) {\n existing.chars += chunk.chars;\n existing.wordChars += chunk.wordChars;\n existing.nonWordChars += chunk.nonWordChars;\n if (chunk.nonWords) {\n if (!existing.nonWords) {\n existing.nonWords = createNonWordCollection();\n }\n mergeNonWordCollections(existing.nonWords, chunk.nonWords);\n }\n continue;\n }\n\n order.push(chunk.locale);\n map.set(chunk.locale, {\n locale: chunk.locale,\n chars: chunk.chars,\n wordChars: chunk.wordChars,\n nonWordChars: chunk.nonWordChars,\n nonWords: chunk.nonWords\n ? mergeNonWordCollections(createNonWordCollection(), chunk.nonWords)\n : undefined,\n });\n }\n\n return order.map((locale) => map.get(locale)!);\n}\n\nexport function aggregateByLocale(chunks: ChunkAnalysis[]): CollectorBreakdown[] {\n const order: string[] = [];\n const map = new Map<string, CollectorBreakdown>();\n\n for (const chunk of chunks) {\n const existing = map.get(chunk.locale);\n if (existing) {\n existing.words += chunk.words;\n appendAll(existing.segments, chunk.segments);\n continue;\n }\n\n order.push(chunk.locale);\n map.set(chunk.locale, {\n locale: chunk.locale,\n words: chunk.words,\n segments: [...chunk.segments],\n });\n }\n\n return order.map((locale) => map.get(locale)!);\n}\n","import type { WordCounterMode } from \"./types\";\n\nconst MODE_ALIASES: Record<string, WordCounterMode> = {\n chunk: \"chunk\",\n chunks: \"chunk\",\n segments: \"segments\",\n segment: \"segments\",\n seg: \"segments\",\n collector: \"collector\",\n collect: \"collector\",\n colle: \"collector\",\n char: \"char\",\n chars: \"char\",\n character: \"char\",\n characters: \"char\",\n \"char-collector\": \"char-collector\",\n};\n\nconst CHAR_MODE_ALIASES = new Set([\"char\", \"chars\", \"character\", \"characters\"]);\nconst COLLECTOR_MODE_ALIASES = new Set([\"collector\", \"collect\", \"colle\", \"col\"]);\n\nfunction collapseSeparators(value: string): string {\n return value.replace(/[-_\\s]+/g, \"\");\n}\n\nfunction isComposedCharCollectorFromTokens(value: string): boolean {\n const tokens = value\n .split(/[-_\\s]+/)\n .map((token) => token.trim())\n .filter((token) => token.length > 0);\n if (tokens.length < 2) {\n return false;\n }\n\n let hasCharAlias = false;\n let hasCollectorAlias = false;\n for (const token of tokens) {\n if (CHAR_MODE_ALIASES.has(token)) {\n hasCharAlias = true;\n continue;\n }\n if (COLLECTOR_MODE_ALIASES.has(token)) {\n hasCollectorAlias = true;\n continue;\n }\n return false;\n }\n\n return hasCharAlias && hasCollectorAlias;\n}\n\nfunction isComposedCharCollectorCompact(value: string): boolean {\n for (const charAlias of CHAR_MODE_ALIASES) {\n for (const collectorAlias of COLLECTOR_MODE_ALIASES) {\n if (value === `${charAlias}${collectorAlias}` || value === `${collectorAlias}${charAlias}`) {\n return true;\n }\n }\n }\n return false;\n}\n\nexport function normalizeMode(input?: string | null): WordCounterMode | null {\n if (!input) {\n return null;\n }\n const normalized = input.trim().toLowerCase();\n const direct = MODE_ALIASES[normalized];\n if (direct) {\n return direct;\n }\n\n if (isComposedCharCollectorFromTokens(normalized)) {\n return \"char-collector\";\n }\n\n const compact = collapseSeparators(normalized);\n if (isComposedCharCollectorCompact(compact)) {\n return \"char-collector\";\n }\n\n return MODE_ALIASES[compact] ?? null;\n}\n\nexport function resolveMode(\n input?: string | null,\n fallback: WordCounterMode = \"chunk\",\n): WordCounterMode {\n return normalizeMode(input) ?? fallback;\n}\n","import type { LatinHintRule } from \"./types\";\n\nconst DEFAULT_LATIN_HINT_RULES_SOURCE = [\n { tag: \"de\", pattern: \"[äöüÄÖÜß]\" },\n { tag: \"es\", pattern: \"[ñÑ¿¡]\" },\n { tag: \"pt\", pattern: \"[ãõÃÕ]\" },\n { tag: \"fr\", pattern: \"[œŒæÆ]\" },\n { tag: \"pl\", pattern: \"[ąćęłńśźżĄĆĘŁŃŚŹŻ]\" },\n { tag: \"tr\", pattern: \"[ıİğĞşŞ]\" },\n { tag: \"ro\", pattern: \"[ăĂâÂîÎșȘțȚ]\" },\n { tag: \"hu\", pattern: \"[őŐűŰ]\" },\n { tag: \"is\", pattern: \"[ðÐþÞ]\" },\n] satisfies LatinHintRule[];\n\nexport const DEFAULT_LATIN_HINT_RULES: ReadonlyArray<Readonly<LatinHintRule>> = Object.freeze(\n DEFAULT_LATIN_HINT_RULES_SOURCE.map((rule) => Object.freeze({ ...rule })),\n);\n","import type { LatinHintRule } from \"./types\";\nimport { DEFAULT_LATIN_HINT_RULES } from \"./latin-hints\";\n\nexport const DEFAULT_LOCALE = \"und-Latn\";\nexport const DEFAULT_HAN_TAG = \"und-Hani\";\n\nconst MAX_LATIN_HINT_PATTERN_LENGTH = 256;\n\nexport interface LocaleDetectOptions {\n latinLanguageHint?: string;\n latinTagHint?: string;\n latinLocaleHint?: string;\n latinHintRules?: LatinHintRule[];\n useDefaultLatinHints?: boolean;\n hanLanguageHint?: string;\n hanTagHint?: string;\n}\n\ntype ResolvedLatinHintRule = {\n tag: string;\n pattern: RegExp;\n priority: number;\n order: number;\n};\n\nexport type LocaleDetectContext = {\n latinHint?: string;\n hanHint?: string;\n latinHintRules: ResolvedLatinHintRule[];\n latinLocales: Set<string>;\n};\n\nexport type LocaleDetectTraceSource = \"script\" | \"hint\" | \"fallback\";\nexport type LocaleDetectTrace = {\n locale: string | null;\n source?: LocaleDetectTraceSource;\n reason?: string;\n};\n\nconst regex = {\n hiragana: /\\p{Script=Hiragana}/u,\n katakana: /\\p{Script=Katakana}/u,\n hangul: /\\p{Script=Hangul}/u,\n han: /\\p{Script=Han}/u,\n latin: /\\p{Script=Latin}/u,\n arabic: /\\p{Script=Arabic}/u,\n cyrillic: /\\p{Script=Cyrillic}/u,\n devanagari: /\\p{Script=Devanagari}/u,\n thai: /\\p{Script=Thai}/u,\n};\n\nconst defaultLatinLocales = new Set<string>([\n DEFAULT_LOCALE,\n ...DEFAULT_LATIN_HINT_RULES.map((hint) => hint.tag),\n]);\n\nexport function isLatinLocale(locale: string, context?: LocaleDetectContext): boolean {\n if (context) {\n return context.latinLocales.has(locale);\n }\n return defaultLatinLocales.has(locale);\n}\n\nfunction resolveLatinHint(options: LocaleDetectOptions): string | undefined {\n const latinTagHint = options.latinTagHint?.trim();\n if (latinTagHint) {\n return latinTagHint;\n }\n\n const latinLanguageHint = options.latinLanguageHint?.trim();\n if (latinLanguageHint) {\n return latinLanguageHint;\n }\n\n const latinLocaleHint = options.latinLocaleHint?.trim();\n if (latinLocaleHint) {\n return latinLocaleHint;\n }\n\n return undefined;\n}\n\nfunction resolveHanHint(options: LocaleDetectOptions): string | undefined {\n const hanTagHint = options.hanTagHint?.trim();\n if (hanTagHint) {\n return hanTagHint;\n }\n\n const hanLanguageHint = options.hanLanguageHint?.trim();\n if (hanLanguageHint) {\n return hanLanguageHint;\n }\n\n return undefined;\n}\n\nfunction compileLatinHintPattern(pattern: string | RegExp, label: string): RegExp {\n const source = typeof pattern === \"string\" ? pattern : pattern.source;\n const hasUnicodeMode =\n typeof pattern !== \"string\" && (pattern.flags.includes(\"u\") || pattern.flags.includes(\"v\"));\n const flags =\n typeof pattern === \"string\" ? \"u\" : hasUnicodeMode ? pattern.flags : `${pattern.flags}u`;\n if (source.length === 0) {\n throw new Error(`${label}: pattern must not be empty.`);\n }\n if (source.length > MAX_LATIN_HINT_PATTERN_LENGTH) {\n throw new Error(\n `${label}: pattern must be at most ${MAX_LATIN_HINT_PATTERN_LENGTH} characters.`,\n );\n }\n try {\n return new RegExp(source, flags);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`${label}: invalid Unicode regex pattern (${message}).`);\n }\n}\n\nfunction normalizeLatinHintPriority(priority: unknown, label: string): number {\n if (priority === undefined) {\n return 0;\n }\n if (typeof priority !== \"number\" || !Number.isFinite(priority)) {\n throw new Error(`${label}: priority must be a finite number when provided.`);\n }\n return priority;\n}\n\nfunction compileLatinHintRule(\n rule: Readonly<LatinHintRule>,\n order: number,\n label: string,\n): ResolvedLatinHintRule {\n const tag = typeof rule.tag === \"string\" ? rule.tag.trim() : \"\";\n if (!tag) {\n throw new Error(`${label}: tag must be a non-empty string.`);\n }\n const pattern = compileLatinHintPattern(rule.pattern, label);\n const priority = normalizeLatinHintPriority(rule.priority, label);\n return {\n tag,\n pattern,\n priority,\n order,\n };\n}\n\nfunction resolveLatinHintRules(options: LocaleDetectOptions): ResolvedLatinHintRule[] {\n const useDefaultLatinHints = options.useDefaultLatinHints !== false;\n const customRules = options.latinHintRules ?? [];\n const combinedRules: Array<{ rule: Readonly<LatinHintRule>; label: string }> = [];\n\n for (let index = 0; index < customRules.length; index += 1) {\n const rule = customRules[index];\n if (!rule) {\n continue;\n }\n combinedRules.push({\n rule,\n label: `Invalid custom Latin hint rule at index ${index}`,\n });\n }\n\n if (useDefaultLatinHints) {\n for (let index = 0; index < DEFAULT_LATIN_HINT_RULES.length; index += 1) {\n const rule = DEFAULT_LATIN_HINT_RULES[index];\n if (!rule) {\n continue;\n }\n combinedRules.push({\n rule,\n label: `Invalid default Latin hint rule at index ${index}`,\n });\n }\n }\n\n const resolvedRules = combinedRules.map((entry, index) =>\n compileLatinHintRule(entry.rule, index, entry.label),\n );\n\n resolvedRules.sort((left, right) => {\n if (left.priority !== right.priority) {\n return right.priority - left.priority;\n }\n return left.order - right.order;\n });\n\n return resolvedRules;\n}\n\nexport function resolveLocaleDetectContext(options: LocaleDetectOptions = {}): LocaleDetectContext {\n const latinHint = resolveLatinHint(options);\n const latinHintRules = resolveLatinHintRules(options);\n const latinLocales = new Set<string>([DEFAULT_LOCALE]);\n for (const rule of latinHintRules) {\n latinLocales.add(rule.tag);\n }\n if (latinHint) {\n latinLocales.add(latinHint);\n }\n\n return {\n latinHint,\n hanHint: resolveHanHint(options),\n latinHintRules,\n latinLocales,\n };\n}\n\nfunction detectLatinLocale(char: string, context: LocaleDetectContext): string {\n for (const hint of context.latinHintRules) {\n hint.pattern.lastIndex = 0;\n if (hint.pattern.test(char)) {\n return hint.tag;\n }\n }\n return DEFAULT_LOCALE;\n}\n\nexport function detectLocaleForCharTrace(\n char: string,\n previousLocale?: string | null,\n options: LocaleDetectOptions = {},\n context: LocaleDetectContext = resolveLocaleDetectContext(options),\n allowLatinLocaleCarry = true,\n allowJapaneseHanCarry = true,\n): LocaleDetectTrace {\n if (regex.hiragana.test(char) || regex.katakana.test(char)) {\n return {\n locale: \"ja\",\n source: \"script\",\n reason: \"hiragana-katakana\",\n };\n }\n if (regex.hangul.test(char)) {\n return {\n locale: \"ko\",\n source: \"script\",\n reason: \"hangul\",\n };\n }\n if (regex.arabic.test(char)) {\n return {\n locale: \"ar\",\n source: \"script\",\n reason: \"arabic\",\n };\n }\n if (regex.cyrillic.test(char)) {\n return {\n locale: \"ru\",\n source: \"script\",\n reason: \"cyrillic\",\n };\n }\n if (regex.devanagari.test(char)) {\n return {\n locale: \"hi\",\n source: \"script\",\n reason: \"devanagari\",\n };\n }\n if (regex.thai.test(char)) {\n return {\n locale: \"th\",\n source: \"script\",\n reason: \"thai\",\n };\n }\n\n if (regex.han.test(char)) {\n if (allowJapaneseHanCarry && previousLocale && previousLocale.startsWith(\"ja\")) {\n return {\n locale: previousLocale,\n source: \"script\",\n reason: \"japanese-han-carry\",\n };\n }\n if (context.hanHint) {\n return {\n locale: context.hanHint,\n source: \"hint\",\n reason: \"explicit-han-hint\",\n };\n }\n return {\n locale: DEFAULT_HAN_TAG,\n source: \"fallback\",\n reason:\n previousLocale && previousLocale.startsWith(\"ja\") && !allowJapaneseHanCarry\n ? \"han-fallback-after-boundary\"\n : \"han-fallback\",\n };\n }\n\n if (regex.latin.test(char)) {\n const hintedLocale = detectLatinLocale(char, context);\n if (hintedLocale !== DEFAULT_LOCALE) {\n return {\n locale: hintedLocale,\n source: \"hint\",\n reason: \"latin-hint-rule\",\n };\n }\n if (\n allowLatinLocaleCarry &&\n previousLocale &&\n isLatinLocale(previousLocale, context) &&\n previousLocale !== DEFAULT_LOCALE\n ) {\n return {\n locale: previousLocale,\n source: \"hint\",\n reason: \"latin-locale-carry\",\n };\n }\n if (context.latinHint) {\n return {\n locale: context.latinHint,\n source: \"hint\",\n reason: \"explicit-latin-hint\",\n };\n }\n return {\n locale: DEFAULT_LOCALE,\n source: \"fallback\",\n reason: \"latin-fallback\",\n };\n }\n\n return {\n locale: null,\n };\n}\n\nexport function detectLocaleForChar(\n char: string,\n previousLocale?: string | null,\n options: LocaleDetectOptions = {},\n context: LocaleDetectContext = resolveLocaleDetectContext(options),\n allowLatinLocaleCarry = true,\n allowJapaneseHanCarry = true,\n): string | null {\n return detectLocaleForCharTrace(\n char,\n previousLocale,\n options,\n context,\n allowLatinLocaleCarry,\n allowJapaneseHanCarry,\n ).locale;\n}\n","import {\n DEFAULT_LOCALE,\n detectLocaleForChar,\n isLatinLocale,\n resolveLocaleDetectContext,\n type LocaleDetectOptions,\n} from \"./locale-detect\";\nimport type { LocaleChunk } from \"./types\";\n\nconst HARD_BOUNDARY_REGEX = /[\\r\\n,.!?;:,、。!?;:.。、]/u;\nconst LATIN_PROMOTION_BREAK_REGEX = /[\\s,.!?;:,、。!?;:.。、]/u;\n\nexport function segmentTextByLocale(\n text: string,\n options: LocaleDetectOptions = {},\n): LocaleChunk[] {\n const context = resolveLocaleDetectContext(options);\n const chunks: LocaleChunk[] = [];\n // Keep currentLocale as a non-null string to simplify type-narrowing.\n let currentLocale: string = DEFAULT_LOCALE;\n let buffer = \"\";\n let bufferHasScript = false;\n let sawCarryBoundary = false;\n\n const updateCarryBoundaryState = (detected: string | null, char: string): void => {\n if (detected !== null) {\n sawCarryBoundary = false;\n return;\n }\n if (HARD_BOUNDARY_REGEX.test(char)) {\n sawCarryBoundary = true;\n }\n };\n\n for (const char of text) {\n const detected = detectLocaleForChar(\n char,\n currentLocale,\n options,\n context,\n !sawCarryBoundary,\n !sawCarryBoundary,\n );\n const targetLocale = detected ?? currentLocale;\n\n // If buffer is empty, this is the first character for a new chunk.\n if (buffer === \"\") {\n currentLocale = targetLocale;\n buffer = char;\n bufferHasScript = detected !== null;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n if (detected !== null && !bufferHasScript) {\n currentLocale = targetLocale;\n buffer += char;\n bufferHasScript = true;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n if (targetLocale !== currentLocale && detected !== null) {\n if (currentLocale === DEFAULT_LOCALE && isLatinLocale(targetLocale, context)) {\n const promotionBreakIndex = findLastLatinPromotionBreakIndex(buffer);\n if (promotionBreakIndex === -1) {\n currentLocale = targetLocale;\n buffer += char;\n bufferHasScript = true;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n const prefix = buffer.slice(0, promotionBreakIndex + 1);\n const suffix = buffer.slice(promotionBreakIndex + 1);\n if (prefix.length > 0) {\n chunks.push({ locale: currentLocale, text: prefix });\n }\n currentLocale = targetLocale;\n buffer = `${suffix}${char}`;\n bufferHasScript = true;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n // currentLocale is guaranteed to be a string here.\n chunks.push({ locale: currentLocale, text: buffer });\n currentLocale = targetLocale;\n buffer = char;\n bufferHasScript = true;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n buffer += char;\n if (detected !== null) {\n bufferHasScript = true;\n }\n updateCarryBoundaryState(detected, char);\n }\n\n if (buffer.length > 0) {\n chunks.push({ locale: currentLocale, text: buffer });\n }\n\n return mergeAdjacentChunks(chunks);\n}\n\nfunction findLastLatinPromotionBreakIndex(buffer: string): number {\n for (let index = buffer.length - 1; index >= 0; index -= 1) {\n const char = buffer[index];\n if (!char) {\n continue;\n }\n if (LATIN_PROMOTION_BREAK_REGEX.test(char)) {\n return index;\n }\n }\n return -1;\n}\n\nfunction mergeAdjacentChunks(chunks: LocaleChunk[]): LocaleChunk[] {\n if (chunks.length === 0) {\n return chunks;\n }\n\n const merged: LocaleChunk[] = [];\n // We already returned for empty arrays above, so the first element is present.\n let last = chunks[0]!;\n\n for (let i = 1; i < chunks.length; i++) {\n const chunk = chunks[i]!;\n if (chunk.locale === last.locale) {\n last = { locale: last.locale, text: last.text + chunk.text };\n } else {\n merged.push(last);\n last = chunk;\n }\n }\n\n merged.push(last);\n return merged;\n}\n","import {\n analyzeCharChunk,\n analyzeChunk,\n aggregateByLocale,\n aggregateCharsByLocale,\n} from \"./analyze\";\nimport { resolveMode } from \"./mode\";\nimport { segmentTextByLocale } from \"./segment\";\nimport { countCharsForLocale, countWordsForLocale } from \"./segmenter\";\nimport { createNonWordCollection, mergeNonWordCollections } from \"./non-words\";\nimport type {\n CharBreakdown,\n CharCollectorBreakdown,\n ChunkBreakdown,\n ChunkWithSegments,\n NonWordCollection,\n WordCounterMode,\n WordCounterOptions,\n WordCounterResult,\n} from \"./types\";\n\nexport type {\n LatinHintRule,\n NonWordCollection,\n WordCounterMode,\n WordCounterOptions,\n WordCounterResult,\n WordCounterBreakdown,\n} from \"./types\";\n\nexport { countCharsForLocale, countWordsForLocale, segmentTextByLocale };\nexport { DEFAULT_LATIN_HINT_RULES } from \"./latin-hints\";\n\nexport function wordCounter(text: string, options: WordCounterOptions = {}): WordCounterResult {\n const mode: WordCounterMode = resolveMode(options.mode, \"chunk\");\n const collectNonWords = Boolean(options.nonWords);\n const includeWhitespace = Boolean(options.includeWhitespace);\n const chunks = segmentTextByLocale(text, {\n latinLanguageHint: options.latinLanguageHint,\n latinTagHint: options.latinTagHint,\n latinLocaleHint: options.latinLocaleHint,\n latinHintRules: options.latinHintRules,\n useDefaultLatinHints: options.useDefaultLatinHints,\n hanLanguageHint: options.hanLanguageHint,\n hanTagHint: options.hanTagHint,\n });\n\n if (mode === \"char\" || mode === \"char-collector\") {\n const analyzed = chunks.map((chunk) =>\n analyzeCharChunk(chunk, collectNonWords, includeWhitespace),\n );\n const total = analyzed.reduce((sum, chunk) => sum + chunk.chars, 0);\n const counts = collectNonWords\n ? {\n words: analyzed.reduce((sum, chunk) => sum + chunk.wordChars, 0),\n nonWords: analyzed.reduce((sum, chunk) => sum + chunk.nonWordChars, 0),\n total,\n }\n : undefined;\n\n if (mode === \"char\") {\n const items: CharBreakdown[] = analyzed.map((chunk) => ({\n locale: chunk.locale,\n text: chunk.text,\n chars: chunk.chars,\n nonWords: chunk.nonWords,\n }));\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n },\n };\n }\n\n const aggregated = aggregateCharsByLocale(analyzed);\n const items: CharCollectorBreakdown[] = aggregated.map((chunk) => ({\n locale: chunk.locale,\n chars: chunk.chars,\n nonWords: chunk.nonWords,\n }));\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n },\n };\n }\n\n const analyzed = chunks.map((chunk) => analyzeChunk(chunk, collectNonWords, includeWhitespace));\n const wordsTotal = analyzed.reduce((sum, chunk) => sum + chunk.words, 0);\n const nonWordsTotal = collectNonWords\n ? analyzed.reduce((sum, chunk) => {\n if (!chunk.nonWords) {\n return sum;\n }\n return sum + getNonWordTotal(chunk.nonWords);\n }, 0)\n : 0;\n const total = analyzed.reduce((sum, chunk) => {\n let chunkTotal = chunk.words;\n if (collectNonWords && chunk.nonWords) {\n chunkTotal += getNonWordTotal(chunk.nonWords);\n }\n return sum + chunkTotal;\n }, 0);\n\n const counts = collectNonWords\n ? { words: wordsTotal, nonWords: nonWordsTotal, total }\n : undefined;\n\n if (mode === \"segments\") {\n const items: ChunkWithSegments[] = analyzed.map((chunk) => ({\n locale: chunk.locale,\n text: chunk.text,\n words: chunk.words,\n segments: chunk.segments,\n nonWords: chunk.nonWords,\n }));\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n },\n };\n }\n\n if (mode === \"collector\") {\n const items = aggregateByLocale(analyzed);\n const nonWords = collectNonWordsAggregate(analyzed, collectNonWords);\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n nonWords,\n },\n };\n }\n\n const items: ChunkBreakdown[] = analyzed.map((chunk) => ({\n locale: chunk.locale,\n text: chunk.text,\n words: chunk.words,\n nonWords: chunk.nonWords,\n }));\n\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n },\n };\n}\n\nfunction getNonWordTotal(nonWords: NonWordCollection): number {\n return (\n nonWords.counts.emoji +\n nonWords.counts.symbols +\n nonWords.counts.punctuation +\n (nonWords.counts.whitespace ?? 0)\n );\n}\n\nfunction collectNonWordsAggregate(\n analyzed: Array<{ nonWords?: NonWordCollection }>,\n enabled: boolean,\n): NonWordCollection | undefined {\n if (!enabled) {\n return undefined;\n }\n const collection = createNonWordCollection();\n for (const chunk of analyzed) {\n if (!chunk.nonWords) {\n continue;\n }\n mergeNonWordCollections(collection, chunk.nonWords);\n }\n return collection;\n}\n","import { wordCounter } from \"./wc\";\n\nexport default wordCounter;\nexport { countCharsForLocale, countWordsForLocale, segmentTextByLocale } from \"./wc\";\nexport { DEFAULT_LATIN_HINT_RULES } from \"./wc\";\nexport type {\n LatinHintRule,\n NonWordCollection,\n WordCounterMode,\n WordCounterOptions,\n WordCounterResult,\n WordCounterBreakdown,\n} from \"./wc\";\n","import type { WordCounterMode, WordCounterOptions, WordCounterResult } from \"../wc/types\";\nimport wordCounter from \"../wc\";\nimport { parseMarkdown } from \"./parse-markdown\";\nimport type { SectionMode, SectionedResult } from \"./types\";\n\nfunction normalizeText(value: unknown): string {\n if (value == null) {\n return \"\";\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nfunction buildPerKeyItems(\n data: Record<string, unknown> | null,\n mode: WordCounterMode,\n options: WordCounterOptions,\n): Array<{ name: string; source: \"frontmatter\"; result: WordCounterResult }> {\n if (!data || typeof data !== \"object\" || Array.isArray(data)) {\n return [];\n }\n\n return Object.entries(data).map(([key, value]) => {\n const valueText = normalizeText(value);\n const text = valueText ? `${key}: ${valueText}` : key;\n return {\n name: key,\n source: \"frontmatter\",\n result: wordCounter(text, options),\n };\n });\n}\n\nfunction buildSingleItem(\n name: string,\n text: string,\n mode: WordCounterMode,\n options: WordCounterOptions,\n source: \"frontmatter\" | \"content\",\n) {\n return [{ name, source, result: wordCounter(text, options) }];\n}\n\nfunction sumTotals(items: Array<{ result: WordCounterResult }>): number {\n return items.reduce((sum, item) => sum + item.result.total, 0);\n}\n\nexport function countSections(\n input: string,\n section: SectionMode,\n options: WordCounterOptions = {},\n): SectionedResult {\n const mode: WordCounterMode = options.mode ?? \"chunk\";\n if (section === \"all\") {\n const result = wordCounter(input, options);\n return {\n section,\n total: result.total,\n frontmatterType: null,\n items: [{ name: \"all\", source: \"content\", result }],\n };\n }\n\n const parsed = parseMarkdown(input);\n const frontmatterText = parsed.frontmatter ?? \"\";\n const contentText = parsed.content ?? \"\";\n\n let items: Array<{ name: string; source: \"frontmatter\" | \"content\"; result: WordCounterResult }> =\n [];\n\n if (section === \"frontmatter\") {\n items = buildSingleItem(\"frontmatter\", frontmatterText, mode, options, \"frontmatter\");\n } else if (section === \"content\") {\n items = buildSingleItem(\"content\", contentText, mode, options, \"content\");\n } else if (section === \"split\") {\n items = [\n ...buildSingleItem(\"frontmatter\", frontmatterText, mode, options, \"frontmatter\"),\n ...buildSingleItem(\"content\", contentText, mode, options, \"content\"),\n ];\n } else if (section === \"per-key\") {\n items = buildPerKeyItems(parsed.data, mode, options);\n } else if (section === \"split-per-key\") {\n items = [\n ...buildPerKeyItems(parsed.data, mode, options),\n ...buildSingleItem(\"content\", contentText, mode, options, \"content\"),\n ];\n }\n\n return {\n section,\n total: sumTotals(items),\n frontmatterType: parsed.frontmatterType,\n items,\n };\n}\n","import type { SectionMode } from \"../markdown\";\nimport { DEFAULT_HAN_TAG, DEFAULT_LOCALE } from \"../wc/locale-detect\";\nimport type { WordCounterMode } from \"../wc/types\";\nimport type { DetectorRouteTag } from \"./policy\";\nimport type { DetectorMode } from \"./types\";\n\nexport type DetectorDebugVerbosity = \"compact\" | \"verbose\";\nexport const DETECTOR_EVIDENCE_PREVIEW_LIMIT = 160;\n\nexport type DetectorEvidenceConfig = {\n verbosity: DetectorDebugVerbosity;\n mode: WordCounterMode;\n section: SectionMode;\n};\n\nexport type DetectorDebugSummary = {\n mode: DetectorMode;\n engine: \"none\" | \"whatlang-wasm\";\n windowsTotal: number;\n accepted: number;\n fallback: number;\n routes: {\n latin: number;\n han: number;\n };\n acceptancePaths: {\n reliable: number;\n corroborated: number;\n };\n fallbackReasons: {\n notEligible: number;\n noCandidate: number;\n belowThreshold: number;\n qualityGate: number;\n corroborationUnreliable: number;\n };\n};\n\nexport type DetectorDebugContext = {\n emit?: (\n event: string,\n details?: Record<string, unknown>,\n options?: { verbosity?: DetectorDebugVerbosity },\n ) => void;\n summary?: DetectorDebugSummary;\n evidence?: DetectorEvidenceConfig;\n};\n\nexport type DetectorFallbackReason =\n | \"notEligible\"\n | \"noCandidate\"\n | \"belowThreshold\"\n | \"qualityGate\"\n | \"corroborationUnreliable\";\n\nexport function createDetectorDebugSummary(\n mode: DetectorMode,\n engine: DetectorDebugSummary[\"engine\"] = mode === \"wasm\" ? \"whatlang-wasm\" : \"none\",\n): DetectorDebugSummary {\n return {\n mode,\n engine,\n windowsTotal: 0,\n accepted: 0,\n fallback: 0,\n routes: {\n latin: 0,\n han: 0,\n },\n acceptancePaths: {\n reliable: 0,\n corroborated: 0,\n },\n fallbackReasons: {\n notEligible: 0,\n noCandidate: 0,\n belowThreshold: 0,\n qualityGate: 0,\n corroborationUnreliable: 0,\n },\n };\n}\n\nexport function mergeDetectorDebugSummaries(\n summaries: Array<DetectorDebugSummary | undefined>,\n): DetectorDebugSummary | undefined {\n const present = summaries.filter(\n (summary): summary is DetectorDebugSummary => summary !== undefined,\n );\n if (present.length === 0) {\n return undefined;\n }\n\n const first = present[0]!;\n const merged = createDetectorDebugSummary(first.mode, first.engine);\n for (const summary of present) {\n merged.windowsTotal += summary.windowsTotal;\n merged.accepted += summary.accepted;\n merged.fallback += summary.fallback;\n merged.routes.latin += summary.routes.latin;\n merged.routes.han += summary.routes.han;\n merged.acceptancePaths.reliable += summary.acceptancePaths.reliable;\n merged.acceptancePaths.corroborated += summary.acceptancePaths.corroborated;\n merged.fallbackReasons.notEligible += summary.fallbackReasons.notEligible;\n merged.fallbackReasons.noCandidate += summary.fallbackReasons.noCandidate;\n merged.fallbackReasons.belowThreshold += summary.fallbackReasons.belowThreshold;\n merged.fallbackReasons.qualityGate += summary.fallbackReasons.qualityGate;\n merged.fallbackReasons.corroborationUnreliable +=\n summary.fallbackReasons.corroborationUnreliable;\n }\n\n return merged;\n}\n\nexport function recordDetectorWindow(\n summary: DetectorDebugSummary | undefined,\n routeTag: DetectorRouteTag,\n): void {\n if (!summary) {\n return;\n }\n\n summary.windowsTotal += 1;\n if (routeTag === DEFAULT_LOCALE) {\n summary.routes.latin += 1;\n return;\n }\n if (routeTag === DEFAULT_HAN_TAG) {\n summary.routes.han += 1;\n }\n}\n\nexport function recordDetectorAccepted(\n summary: DetectorDebugSummary | undefined,\n path: \"reliable\" | \"corroborated\",\n): void {\n if (!summary) {\n return;\n }\n\n summary.accepted += 1;\n if (path === \"reliable\") {\n summary.acceptancePaths.reliable += 1;\n return;\n }\n\n summary.acceptancePaths.corroborated += 1;\n}\n\nexport function recordDetectorFallback(\n summary: DetectorDebugSummary | undefined,\n reason: DetectorFallbackReason,\n): void {\n if (!summary) {\n return;\n }\n\n summary.fallback += 1;\n summary.fallbackReasons[reason] += 1;\n}\n\nexport function createDetectorEvidencePreview(text: string): {\n preview: string;\n truncated: boolean;\n} {\n const collapsed = text.replace(/\\s+/gu, \" \").trim();\n const codePoints = Array.from(collapsed);\n if (codePoints.length <= DETECTOR_EVIDENCE_PREVIEW_LIMIT) {\n return {\n preview: collapsed,\n truncated: false,\n };\n }\n\n return {\n preview: codePoints.slice(0, DETECTOR_EVIDENCE_PREVIEW_LIMIT).join(\"\"),\n truncated: true,\n };\n}\n","import {\n DEFAULT_LOCALE,\n detectLocaleForCharTrace,\n isLatinLocale,\n resolveLocaleDetectContext,\n type LocaleDetectContext,\n type LocaleDetectOptions,\n type LocaleDetectTraceSource,\n} from \"../wc/locale-detect\";\nimport type { LocaleChunk } from \"../wc/types\";\nimport { createDetectorEvidencePreview, DETECTOR_EVIDENCE_PREVIEW_LIMIT } from \"./debug\";\nimport type {\n DetectorInspectChunk,\n DetectorInspectInput,\n DetectorInspectInputOptions,\n} from \"./inspect-types\";\n\nconst HARD_BOUNDARY_REGEX = /[\\r\\n,.!?;:,、。!?;:.。、]/u;\nconst LATIN_PROMOTION_BREAK_REGEX = /[\\s,.!?;:,、。!?;:.。、]/u;\n\nexport type TracedLocaleChunk = LocaleChunk & {\n source: \"script\" | \"hint\" | \"fallback\";\n reason?: string;\n};\n\nfunction findLastLatinPromotionBreakIndex(buffer: string): number {\n for (let index = buffer.length - 1; index >= 0; index -= 1) {\n const char = buffer[index];\n if (!char) {\n continue;\n }\n if (LATIN_PROMOTION_BREAK_REGEX.test(char)) {\n return index;\n }\n }\n return -1;\n}\n\nfunction mergeAdjacentTracedChunks(chunks: TracedLocaleChunk[]): TracedLocaleChunk[] {\n if (chunks.length === 0) {\n return chunks;\n }\n\n const merged: TracedLocaleChunk[] = [];\n let last = chunks[0]!;\n\n for (let index = 1; index < chunks.length; index += 1) {\n const chunk = chunks[index]!;\n if (chunk.locale === last.locale) {\n last = {\n ...last,\n text: last.text + chunk.text,\n };\n continue;\n }\n merged.push(last);\n last = chunk;\n }\n\n merged.push(last);\n return merged;\n}\n\nexport function segmentTextByLocaleWithTrace(\n text: string,\n options: LocaleDetectOptions = {},\n): TracedLocaleChunk[] {\n const context: LocaleDetectContext = resolveLocaleDetectContext(options);\n const chunks: TracedLocaleChunk[] = [];\n let currentLocale = DEFAULT_LOCALE;\n let currentSource: LocaleDetectTraceSource = \"fallback\";\n let currentReason = \"latin-fallback\";\n let buffer = \"\";\n let bufferHasScript = false;\n let sawCarryBoundary = false;\n\n const updateCarryBoundaryState = (detected: string | null, char: string): void => {\n if (detected !== null) {\n sawCarryBoundary = false;\n return;\n }\n if (HARD_BOUNDARY_REGEX.test(char)) {\n sawCarryBoundary = true;\n }\n };\n\n const pushChunk = (\n locale: string,\n textValue: string,\n source: LocaleDetectTraceSource,\n reason?: string,\n ) => {\n if (textValue.length === 0) {\n return;\n }\n chunks.push({\n locale,\n text: textValue,\n source,\n ...(reason ? { reason } : {}),\n });\n };\n\n for (const char of text) {\n const trace = detectLocaleForCharTrace(\n char,\n currentLocale,\n options,\n context,\n !sawCarryBoundary,\n !sawCarryBoundary,\n );\n const detected = trace.locale;\n const targetLocale = detected ?? currentLocale;\n\n if (buffer === \"\") {\n currentLocale = targetLocale;\n currentSource = trace.source ?? \"fallback\";\n currentReason = trace.reason ?? currentReason;\n buffer = char;\n bufferHasScript = detected !== null;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n if (detected !== null && !bufferHasScript) {\n currentLocale = targetLocale;\n currentSource = trace.source ?? currentSource;\n currentReason = trace.reason ?? currentReason;\n buffer += char;\n bufferHasScript = true;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n if (targetLocale !== currentLocale && detected !== null) {\n if (currentLocale === DEFAULT_LOCALE && isLatinLocale(targetLocale, context)) {\n const promotionBreakIndex = findLastLatinPromotionBreakIndex(buffer);\n if (promotionBreakIndex === -1) {\n currentLocale = targetLocale;\n currentSource = trace.source ?? currentSource;\n currentReason = trace.reason ?? currentReason;\n buffer += char;\n bufferHasScript = true;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n const prefix = buffer.slice(0, promotionBreakIndex + 1);\n const suffix = buffer.slice(promotionBreakIndex + 1);\n pushChunk(currentLocale, prefix, currentSource, currentReason);\n currentLocale = targetLocale;\n currentSource = trace.source ?? currentSource;\n currentReason = trace.reason ?? currentReason;\n buffer = `${suffix}${char}`;\n bufferHasScript = true;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n pushChunk(currentLocale, buffer, currentSource, currentReason);\n currentLocale = targetLocale;\n currentSource = trace.source ?? \"fallback\";\n currentReason = trace.reason ?? currentReason;\n buffer = char;\n bufferHasScript = true;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n buffer += char;\n if (detected !== null) {\n bufferHasScript = true;\n }\n updateCarryBoundaryState(detected, char);\n }\n\n pushChunk(currentLocale, buffer, currentSource, currentReason);\n return mergeAdjacentTracedChunks(chunks);\n}\n\nexport function createInspectInput(\n text: string,\n inputOptions: DetectorInspectInputOptions | undefined,\n): DetectorInspectInput {\n const preview = createDetectorEvidencePreview(text);\n return {\n sourceType: inputOptions?.sourceType ?? \"inline\",\n ...(inputOptions?.path ? { path: inputOptions.path } : {}),\n textLength: text.length,\n textPreview: preview.preview,\n textPreviewTruncated: preview.truncated,\n };\n}\n\nexport function createInspectChunk(\n index: number,\n chunk: LocaleChunk,\n extras?: Pick<DetectorInspectChunk, \"source\" | \"reason\">,\n): DetectorInspectChunk {\n const preview = createDetectorEvidencePreview(chunk.text);\n return {\n index,\n locale: chunk.locale,\n textPreview: preview.preview,\n textPreviewTruncated: preview.truncated,\n ...(extras?.source ? { source: extras.source } : {}),\n ...(extras?.reason ? { reason: extras.reason } : {}),\n };\n}\n\nexport function createInspectPreview(text: string): {\n textPreview: string;\n textPreviewTruncated: boolean;\n} {\n const preview = createDetectorEvidencePreview(text);\n return {\n textPreview: preview.preview,\n textPreviewTruncated: preview.truncated,\n };\n}\n\nexport { DETECTOR_EVIDENCE_PREVIEW_LIMIT as DETECTOR_INSPECT_PREVIEW_LIMIT };\n","import { countSections } from \"../markdown\";\nimport wordCounter, { segmentTextByLocale } from \"../wc\";\nimport {\n createInspectChunk,\n createInspectInput,\n segmentTextByLocaleWithTrace,\n} from \"./inspect-helpers\";\nimport type { DetectorInspectOptions, DetectorInspectResult } from \"./inspect-types\";\nimport type {\n DetectorCountSectionsOptions,\n DetectorLocaleOptions,\n DetectorWordCounterOptions,\n} from \"./types\";\n\nexport async function segmentTextByLocaleWithRegexDetector(\n text: string,\n options: DetectorLocaleOptions = {},\n) {\n return segmentTextByLocale(text, options);\n}\n\nexport async function wordCounterWithRegexDetector(\n text: string,\n options: DetectorWordCounterOptions = {},\n) {\n return wordCounter(text, options);\n}\n\nexport async function countSectionsWithRegexDetector(\n input: string,\n section: Parameters<typeof countSections>[1],\n options: DetectorCountSectionsOptions = {},\n) {\n return countSections(input, section, options);\n}\n\nexport async function inspectTextWithRegexDetector(\n text: string,\n options: DetectorInspectOptions = {},\n): Promise<DetectorInspectResult> {\n if (text.trim().length === 0) {\n return {\n schemaVersion: 1,\n kind: \"detector-inspect\",\n view: \"pipeline\",\n detector: \"regex\",\n input: createInspectInput(text, options.input),\n chunks: [],\n decision: {\n kind: \"empty\",\n notes: [\"No detector-eligible content was present.\"],\n },\n resolvedChunks: [],\n };\n }\n\n const chunks = segmentTextByLocaleWithTrace(text, options);\n\n return {\n schemaVersion: 1,\n kind: \"detector-inspect\",\n view: \"pipeline\",\n detector: \"regex\",\n input: createInspectInput(text, options.input),\n chunks: chunks.map((chunk, index) =>\n createInspectChunk(index, chunk, {\n source: chunk.source,\n reason: chunk.reason,\n }),\n ),\n decision: {\n kind: \"deterministic\",\n notes: [\n \"Regex inspection does not use detector windows or engine confidence.\",\n \"Final locales come directly from script detection, hint rules, and fallback rules.\",\n ],\n },\n resolvedChunks: chunks.map((chunk, index) => createInspectChunk(index, chunk)),\n };\n}\n","import {\n analyzeCharChunk,\n analyzeChunk,\n aggregateByLocale,\n aggregateCharsByLocale,\n} from \"../wc/analyze\";\nimport { resolveMode } from \"../wc/mode\";\nimport { createNonWordCollection, mergeNonWordCollections } from \"../wc/non-words\";\nimport type {\n CharBreakdown,\n CharCollectorBreakdown,\n ChunkBreakdown,\n ChunkWithSegments,\n LocaleChunk,\n NonWordCollection,\n WordCounterMode,\n WordCounterOptions,\n WordCounterResult,\n} from \"../wc/types\";\n\nfunction getNonWordTotal(nonWords: NonWordCollection): number {\n return (\n nonWords.counts.emoji +\n nonWords.counts.symbols +\n nonWords.counts.punctuation +\n (nonWords.counts.whitespace ?? 0)\n );\n}\n\nfunction collectNonWordsAggregate(\n analyzed: Array<{ nonWords?: NonWordCollection }>,\n enabled: boolean,\n): NonWordCollection | undefined {\n if (!enabled) {\n return undefined;\n }\n const collection = createNonWordCollection();\n for (const chunk of analyzed) {\n if (!chunk.nonWords) {\n continue;\n }\n mergeNonWordCollections(collection, chunk.nonWords);\n }\n return collection;\n}\n\nexport function buildWordCounterResultFromChunks(\n chunks: LocaleChunk[],\n options: WordCounterOptions = {},\n): WordCounterResult {\n const mode: WordCounterMode = resolveMode(options.mode, \"chunk\");\n const collectNonWords = Boolean(options.nonWords);\n const includeWhitespace = Boolean(options.includeWhitespace);\n\n if (mode === \"char\" || mode === \"char-collector\") {\n const analyzed = chunks.map((chunk) =>\n analyzeCharChunk(chunk, collectNonWords, includeWhitespace),\n );\n const total = analyzed.reduce((sum, chunk) => sum + chunk.chars, 0);\n const counts = collectNonWords\n ? {\n words: analyzed.reduce((sum, chunk) => sum + chunk.wordChars, 0),\n nonWords: analyzed.reduce((sum, chunk) => sum + chunk.nonWordChars, 0),\n total,\n }\n : undefined;\n\n if (mode === \"char\") {\n const items: CharBreakdown[] = analyzed.map((chunk) => ({\n locale: chunk.locale,\n text: chunk.text,\n chars: chunk.chars,\n nonWords: chunk.nonWords,\n }));\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n },\n };\n }\n\n const aggregated = aggregateCharsByLocale(analyzed);\n const items: CharCollectorBreakdown[] = aggregated.map((chunk) => ({\n locale: chunk.locale,\n chars: chunk.chars,\n nonWords: chunk.nonWords,\n }));\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n },\n };\n }\n\n const analyzed = chunks.map((chunk) => analyzeChunk(chunk, collectNonWords, includeWhitespace));\n const wordsTotal = analyzed.reduce((sum, chunk) => sum + chunk.words, 0);\n const nonWordsTotal = collectNonWords\n ? analyzed.reduce((sum, chunk) => {\n if (!chunk.nonWords) {\n return sum;\n }\n return sum + getNonWordTotal(chunk.nonWords);\n }, 0)\n : 0;\n const total = analyzed.reduce((sum, chunk) => {\n let chunkTotal = chunk.words;\n if (collectNonWords && chunk.nonWords) {\n chunkTotal += getNonWordTotal(chunk.nonWords);\n }\n return sum + chunkTotal;\n }, 0);\n\n const counts = collectNonWords\n ? { words: wordsTotal, nonWords: nonWordsTotal, total }\n : undefined;\n\n if (mode === \"segments\") {\n const items: ChunkWithSegments[] = analyzed.map((chunk) => ({\n locale: chunk.locale,\n text: chunk.text,\n words: chunk.words,\n segments: chunk.segments,\n nonWords: chunk.nonWords,\n }));\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n },\n };\n }\n\n if (mode === \"collector\") {\n const items = aggregateByLocale(analyzed);\n const nonWords = collectNonWordsAggregate(analyzed, collectNonWords);\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n nonWords,\n },\n };\n }\n\n const items: ChunkBreakdown[] = analyzed.map((chunk) => ({\n locale: chunk.locale,\n text: chunk.text,\n words: chunk.words,\n nonWords: chunk.nonWords,\n }));\n\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n },\n };\n}\n","import { parseMarkdown } from \"../markdown\";\nimport type { SectionMode, SectionedResult } from \"../markdown\";\nimport type { WordCounterResult } from \"../wc/types\";\nimport type { DetectorCountSectionsOptions } from \"./types\";\nimport { wordCounterWithDetector } from \"./index\";\n\nfunction normalizeText(value: unknown): string {\n if (value == null) {\n return \"\";\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nasync function buildPerKeyItems(\n data: Record<string, unknown> | null,\n options: DetectorCountSectionsOptions,\n): Promise<Array<{ name: string; source: \"frontmatter\"; result: WordCounterResult }>> {\n if (!data || typeof data !== \"object\" || Array.isArray(data)) {\n return [];\n }\n\n return Promise.all(\n Object.entries(data).map(async ([key, value]) => {\n const valueText = normalizeText(value);\n const text = valueText ? `${key}: ${valueText}` : key;\n return {\n name: key,\n source: \"frontmatter\" as const,\n result: await wordCounterWithDetector(text, options),\n };\n }),\n );\n}\n\nasync function buildSingleItem(\n name: string,\n text: string,\n options: DetectorCountSectionsOptions,\n source: \"frontmatter\" | \"content\",\n): Promise<Array<{ name: string; source: \"frontmatter\" | \"content\"; result: WordCounterResult }>> {\n return [{ name, source, result: await wordCounterWithDetector(text, options) }];\n}\n\nfunction sumTotals(items: Array<{ result: WordCounterResult }>): number {\n return items.reduce((sum, item) => sum + item.result.total, 0);\n}\n\nexport async function countSectionsWithResolvedDetector(\n input: string,\n section: SectionMode,\n options: DetectorCountSectionsOptions = {},\n): Promise<SectionedResult> {\n if (section === \"all\") {\n const result = await wordCounterWithDetector(input, options);\n return {\n section,\n total: result.total,\n frontmatterType: null,\n items: [{ name: \"all\", source: \"content\", result }],\n };\n }\n\n const parsed = parseMarkdown(input);\n const frontmatterText = parsed.frontmatter ?? \"\";\n const contentText = parsed.content ?? \"\";\n\n let items: Array<{ name: string; source: \"frontmatter\" | \"content\"; result: WordCounterResult }> =\n [];\n\n if (section === \"frontmatter\") {\n items = await buildSingleItem(\"frontmatter\", frontmatterText, options, \"frontmatter\");\n } else if (section === \"content\") {\n items = await buildSingleItem(\"content\", contentText, options, \"content\");\n } else if (section === \"split\") {\n items = [\n ...(await buildSingleItem(\"frontmatter\", frontmatterText, options, \"frontmatter\")),\n ...(await buildSingleItem(\"content\", contentText, options, \"content\")),\n ];\n } else if (section === \"per-key\") {\n items = await buildPerKeyItems(parsed.data, options);\n } else if (section === \"split-per-key\") {\n items = [\n ...(await buildPerKeyItems(parsed.data, options)),\n ...(await buildSingleItem(\"content\", contentText, options, \"content\")),\n ];\n }\n\n return {\n section,\n total: sumTotals(items),\n frontmatterType: parsed.frontmatterType,\n items,\n };\n}\n","import { DEFAULT_HAN_TAG, DEFAULT_LOCALE } from \"../wc/locale-detect\";\nimport type { LocaleChunk } from \"../wc/types\";\nimport type { DetectorContentGateMode, DetectorResult } from \"./types\";\n\nexport const LATIN_WASM_MIN_SCRIPT_CHARS = 24;\nexport const HANI_WASM_MIN_SCRIPT_CHARS = 12;\nexport const LATIN_WASM_MIN_CONFIDENCE = 0.75;\nexport const HANI_WASM_MIN_CONFIDENCE = 0.9;\nexport const LATIN_WASM_CORROBORATED_MIN_CONFIDENCE = 0.7;\nconst LATIN_WASM_STRICT_MIN_SCRIPT_CHARS = 30;\nconst LATIN_WASM_LOOSE_MIN_SCRIPT_CHARS = 20;\nconst HANI_WASM_STRICT_MIN_SCRIPT_CHARS = 16;\nconst HANI_WASM_LOOSE_MIN_FOCUS_HAN_CHARS = 4;\n\nconst LATIN_SCRIPT_REGEX = /\\p{Script=Latin}/u;\nconst HAN_SCRIPT_REGEX = /\\p{Script=Han}/u;\nconst HANI_DIAGNOSTIC_SCRIPT_REGEX = /[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}]/u;\nconst LATIN_WORD_REGEX = /\\p{Script=Latin}+/gu;\nconst WHITESPACE_REGEX = /\\s/u;\nconst JAPANESE_CONTEXT_LOCALE = \"ja\";\n\nexport type DetectorRouteTag = typeof DEFAULT_LOCALE | typeof DEFAULT_HAN_TAG;\nexport type DetectorContentGatePolicy = \"latinProse\" | \"none\";\nexport type DetectorDiagnosticTextSource = \"focus\" | \"borrowed-context\";\n\nexport type DetectorWindow = {\n routeTag: DetectorRouteTag;\n startIndex: number;\n endIndex: number;\n text: string;\n};\n\nexport type DetectorBorrowedContext = {\n leftChunkIndex?: number;\n rightChunkIndex?: number;\n};\n\nexport type DetectorDiagnosticSample = {\n focusText: string;\n text: string;\n normalizedText: string;\n normalizedApplied: boolean;\n textSource: DetectorDiagnosticTextSource;\n borrowedContext?: DetectorBorrowedContext;\n};\n\nexport type DetectorEligibilityResult = {\n scriptChars: number;\n minScriptChars: number;\n passed: boolean;\n};\n\nexport type DetectorContentGateResult = {\n applied: boolean;\n passed: boolean;\n policy: DetectorContentGatePolicy;\n mode: DetectorContentGateMode;\n};\n\nexport type DetectorCorroboratedAcceptance =\n | {\n accepted: true;\n confidence: number;\n hasReliableCorroboration: true;\n }\n | {\n accepted: false;\n confidence: number;\n hasReliableCorroboration: boolean;\n reason: \"mismatch\" | \"belowThreshold\" | \"unreliable\";\n };\n\nexport type DetectorRoutePolicy = {\n routeTag: DetectorRouteTag;\n eligibility: {\n evaluate: (\n sample: DetectorDiagnosticSample,\n mode?: DetectorContentGateMode,\n ) => DetectorEligibilityResult;\n };\n buildDiagnosticSample: (\n window: DetectorWindow,\n chunks: LocaleChunk[],\n ) => DetectorDiagnosticSample;\n evaluateContentGate: (\n sample: DetectorDiagnosticSample,\n mode?: DetectorContentGateMode,\n ) => DetectorContentGateResult;\n accept: (candidate: DetectorResult) => boolean;\n acceptCorroborated?: (\n raw: DetectorResult,\n normalized: DetectorResult,\n ) => DetectorCorroboratedAcceptance;\n fallbackTag: string;\n};\n\nfunction countMatchingChars(text: string, matcher: RegExp): number {\n let count = 0;\n for (const char of text) {\n if (matcher.test(char)) {\n count += 1;\n }\n }\n return count;\n}\n\nfunction getSampleScriptMatcher(routeTag: DetectorRouteTag): RegExp {\n return routeTag === DEFAULT_HAN_TAG ? HAN_SCRIPT_REGEX : LATIN_SCRIPT_REGEX;\n}\n\nfunction getEligibilityScriptMatcher(routeTag: DetectorRouteTag): RegExp {\n return routeTag === DEFAULT_HAN_TAG ? HANI_DIAGNOSTIC_SCRIPT_REGEX : LATIN_SCRIPT_REGEX;\n}\n\nfunction normalizeSampleText(text: string, routeTag: DetectorRouteTag): string {\n const matcher = getSampleScriptMatcher(routeTag);\n return [...text]\n .map((char) => {\n if (matcher.test(char) || WHITESPACE_REGEX.test(char)) {\n return char;\n }\n return \" \";\n })\n .join(\"\")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nfunction buildFocusOnlyDiagnosticSample(window: DetectorWindow): DetectorDiagnosticSample {\n const normalizedText = normalizeSampleText(window.text, window.routeTag);\n return {\n focusText: window.text,\n text: window.text,\n normalizedText,\n normalizedApplied: normalizedText !== window.text,\n textSource: \"focus\",\n };\n}\n\nfunction buildHaniDiagnosticSample(\n window: DetectorWindow,\n chunks: LocaleChunk[],\n): DetectorDiagnosticSample {\n const borrowedContext: DetectorBorrowedContext = {};\n const sampleParts: string[] = [];\n\n const leftChunk = chunks[window.startIndex - 1];\n if (leftChunk?.locale === JAPANESE_CONTEXT_LOCALE) {\n borrowedContext.leftChunkIndex = window.startIndex - 1;\n sampleParts.push(leftChunk.text);\n }\n\n sampleParts.push(window.text);\n\n const rightChunk = chunks[window.endIndex + 1];\n if (rightChunk?.locale === JAPANESE_CONTEXT_LOCALE) {\n borrowedContext.rightChunkIndex = window.endIndex + 1;\n sampleParts.push(rightChunk.text);\n }\n\n const text = sampleParts.join(\"\");\n const normalizedText = normalizeSampleText(text, window.routeTag);\n const borrowed =\n borrowedContext.leftChunkIndex !== undefined || borrowedContext.rightChunkIndex !== undefined;\n\n return {\n focusText: window.text,\n text,\n normalizedText,\n normalizedApplied: normalizedText !== text,\n textSource: borrowed ? \"borrowed-context\" : \"focus\",\n ...(borrowed ? { borrowedContext } : {}),\n };\n}\n\nfunction countLatinWords(text: string): number {\n return text.match(LATIN_WORD_REGEX)?.length ?? 0;\n}\n\nfunction isTechnicalLikeLatinLine(line: string, latinWords: number): boolean {\n const trimmed = line.trim();\n if (!trimmed) {\n return false;\n }\n\n if (/^[>#$]/u.test(trimmed)) {\n return true;\n }\n\n if (/(^|\\s)--[a-z0-9][a-z0-9-]*/iu.test(trimmed)) {\n return true;\n }\n\n if (/`[^`]+`/u.test(trimmed)) {\n return true;\n }\n\n if (/(^|[\\s\"'`])(?:\\.{0,2}\\/|\\/)?[\\w./-]+\\.[a-z0-9]{1,6}(?=$|[\\s\"'`])/iu.test(trimmed)) {\n return true;\n }\n\n if (/^[-*\\d.)\\s]*[\\p{L}\\p{N}_.-]+:\\s+\\S/iu.test(trimmed) && latinWords <= 8) {\n return true;\n }\n\n return false;\n}\n\nfunction shouldTreatLatinProseBlockAsSentenceLike(\n latinWords: number,\n lineCount: number,\n hasSentencePunctuation: boolean,\n): boolean {\n if (latinWords < 4) {\n return false;\n }\n\n if (hasSentencePunctuation) {\n return true;\n }\n\n return lineCount <= 1 ? latinWords >= 5 : latinWords >= 8;\n}\n\nfunction evaluateLatinContentGate(\n text: string,\n normalizedSample: string,\n mode: Exclude<DetectorContentGateMode, \"off\">,\n): DetectorContentGateResult {\n const minNormalizedLatinWords = mode === \"strict\" ? 5 : 4;\n const minProseWords = mode === \"strict\" ? 5 : mode === \"loose\" ? 3 : 4;\n const technicalWordSlack = mode === \"loose\" ? 2 : 0;\n const normalizedLatinWords = countLatinWords(normalizedSample);\n if (normalizedLatinWords < minNormalizedLatinWords) {\n return {\n applied: true,\n passed: false,\n policy: \"latinProse\",\n mode,\n };\n }\n\n let proseWords = 0;\n let technicalWords = 0;\n let proseBlockWords = 0;\n let proseBlockLines = 0;\n let proseBlockHasSentencePunctuation = false;\n\n const flushProseBlock = () => {\n if (\n shouldTreatLatinProseBlockAsSentenceLike(\n proseBlockWords,\n proseBlockLines,\n proseBlockHasSentencePunctuation,\n )\n ) {\n proseWords += proseBlockWords;\n }\n\n proseBlockWords = 0;\n proseBlockLines = 0;\n proseBlockHasSentencePunctuation = false;\n };\n\n for (const rawLine of text.split(/\\r?\\n/u)) {\n const line = rawLine.trim();\n if (!line || line === \"---\" || line === \"```\") {\n flushProseBlock();\n continue;\n }\n\n const latinWords = countLatinWords(line);\n if (latinWords === 0) {\n continue;\n }\n\n const technicalLike = isTechnicalLikeLatinLine(line, latinWords);\n if (technicalLike) {\n flushProseBlock();\n technicalWords += latinWords;\n continue;\n }\n\n proseBlockWords += latinWords;\n proseBlockLines += 1;\n proseBlockHasSentencePunctuation ||= /[.!?]/u.test(line);\n }\n\n flushProseBlock();\n return {\n applied: true,\n passed: proseWords >= minProseWords && proseWords + technicalWordSlack >= technicalWords,\n policy: \"latinProse\",\n mode,\n };\n}\n\nfunction evaluateEligibility(\n sample: DetectorDiagnosticSample,\n routeTag: DetectorRouteTag,\n minScriptChars: number,\n): DetectorEligibilityResult {\n const scriptChars = countMatchingChars(sample.text, getEligibilityScriptMatcher(routeTag));\n return {\n scriptChars,\n minScriptChars,\n passed: scriptChars >= minScriptChars,\n };\n}\n\nfunction getLatinEligibilityMinScriptChars(mode: DetectorContentGateMode = \"default\"): number {\n if (mode === \"strict\") {\n return LATIN_WASM_STRICT_MIN_SCRIPT_CHARS;\n }\n\n if (mode === \"loose\") {\n return LATIN_WASM_LOOSE_MIN_SCRIPT_CHARS;\n }\n\n return LATIN_WASM_MIN_SCRIPT_CHARS;\n}\n\nfunction evaluateHaniEligibility(\n sample: DetectorDiagnosticSample,\n mode: DetectorContentGateMode = \"default\",\n): DetectorEligibilityResult {\n if (mode === \"loose\") {\n const scriptChars = countMatchingChars(sample.focusText, HAN_SCRIPT_REGEX);\n return {\n scriptChars,\n minScriptChars: HANI_WASM_LOOSE_MIN_FOCUS_HAN_CHARS,\n passed: scriptChars >= HANI_WASM_LOOSE_MIN_FOCUS_HAN_CHARS,\n };\n }\n\n const minScriptChars =\n mode === \"strict\" ? HANI_WASM_STRICT_MIN_SCRIPT_CHARS : HANI_WASM_MIN_SCRIPT_CHARS;\n return evaluateEligibility(sample, DEFAULT_HAN_TAG, minScriptChars);\n}\n\nfunction shouldAcceptCandidate(\n confidence: number | undefined,\n reliable: boolean | undefined,\n minConfidence: number,\n): boolean {\n if (reliable !== true) {\n return false;\n }\n\n if (confidence === undefined) {\n return false;\n }\n\n return confidence >= minConfidence;\n}\n\nfunction evaluateLatinCorroboratedAcceptance(\n raw: DetectorResult,\n normalized: DetectorResult,\n): DetectorCorroboratedAcceptance {\n if (raw.tag !== normalized.tag) {\n return {\n accepted: false,\n confidence: Math.max(raw.confidence ?? 0, normalized.confidence ?? 0),\n hasReliableCorroboration: raw.reliable === true || normalized.reliable === true,\n reason: \"mismatch\",\n };\n }\n\n const confidence = Math.max(raw.confidence ?? 0, normalized.confidence ?? 0);\n const hasReliableCorroboration = raw.reliable === true || normalized.reliable === true;\n\n if (!hasReliableCorroboration && confidence >= LATIN_WASM_CORROBORATED_MIN_CONFIDENCE) {\n return {\n accepted: false,\n confidence,\n hasReliableCorroboration,\n reason: \"unreliable\",\n };\n }\n\n if (confidence < LATIN_WASM_CORROBORATED_MIN_CONFIDENCE) {\n return {\n accepted: false,\n confidence,\n hasReliableCorroboration,\n reason: \"belowThreshold\",\n };\n }\n\n if (!hasReliableCorroboration) {\n return {\n accepted: false,\n confidence,\n hasReliableCorroboration,\n reason: \"unreliable\",\n };\n }\n\n return {\n accepted: true,\n confidence,\n hasReliableCorroboration: true,\n };\n}\n\nfunction createLatinRoutePolicy(): DetectorRoutePolicy {\n return {\n routeTag: DEFAULT_LOCALE,\n eligibility: {\n evaluate(sample, mode = \"default\") {\n return evaluateEligibility(sample, DEFAULT_LOCALE, getLatinEligibilityMinScriptChars(mode));\n },\n },\n buildDiagnosticSample(window) {\n return buildFocusOnlyDiagnosticSample(window);\n },\n evaluateContentGate(sample, mode = \"default\") {\n if (mode === \"off\") {\n return {\n applied: false,\n passed: true,\n policy: \"none\",\n mode,\n };\n }\n\n return evaluateLatinContentGate(sample.text, sample.normalizedText, mode);\n },\n accept(candidate) {\n return shouldAcceptCandidate(\n candidate.confidence,\n candidate.reliable,\n LATIN_WASM_MIN_CONFIDENCE,\n );\n },\n acceptCorroborated(raw, normalized) {\n return evaluateLatinCorroboratedAcceptance(raw, normalized);\n },\n fallbackTag: DEFAULT_LOCALE,\n };\n}\n\nfunction createHaniRoutePolicy(): DetectorRoutePolicy {\n return {\n routeTag: DEFAULT_HAN_TAG,\n eligibility: {\n evaluate(sample, mode = \"default\") {\n return evaluateHaniEligibility(sample, mode);\n },\n },\n buildDiagnosticSample(window, chunks) {\n return buildHaniDiagnosticSample(window, chunks);\n },\n evaluateContentGate(_sample, mode = \"default\") {\n return {\n applied: false,\n passed: true,\n policy: \"none\",\n mode,\n };\n },\n accept(candidate) {\n return shouldAcceptCandidate(\n candidate.confidence,\n candidate.reliable,\n HANI_WASM_MIN_CONFIDENCE,\n );\n },\n fallbackTag: DEFAULT_HAN_TAG,\n };\n}\n\nexport const DETECTOR_ROUTE_POLICIES: Record<DetectorRouteTag, DetectorRoutePolicy> = {\n [DEFAULT_LOCALE]: createLatinRoutePolicy(),\n [DEFAULT_HAN_TAG]: createHaniRoutePolicy(),\n};\n\nexport function isAmbiguousDetectorRoute(locale: string): locale is DetectorRouteTag {\n return locale === DEFAULT_LOCALE || locale === DEFAULT_HAN_TAG;\n}\n\nexport function countScriptBearingCharsForRoute(text: string, routeTag: DetectorRouteTag): number {\n return countMatchingChars(text, getEligibilityScriptMatcher(routeTag));\n}\n\nexport function normalizeDetectorSampleForRoute(text: string, routeTag: DetectorRouteTag): string {\n return normalizeSampleText(text, routeTag);\n}\n","import { DETECTOR_ROUTE_POLICIES, type DetectorWindow } from \"./policy\";\nimport {\n createInspectChunk,\n createInspectPreview,\n type TracedLocaleChunk,\n} from \"./inspect-helpers\";\nimport type { DetectorInspectResult, DetectorInspectWindow } from \"./inspect-types\";\nimport type { ResolvedDetectorWindow } from \"./wasm-resolution\";\nimport type { ExecutedEngineSample } from \"./wasm-engine\";\n\nfunction buildInspectSample(\n sample:\n | ResolvedDetectorWindow[\"sample\"]\n | {\n text: string;\n normalizedText: string;\n normalizedApplied: boolean;\n textSource: \"focus\" | \"borrowed-context\";\n borrowedContext?: ResolvedDetectorWindow[\"sample\"][\"borrowedContext\"];\n },\n) {\n return {\n text: sample.text,\n textLength: sample.text.length,\n normalizedText: sample.normalizedText,\n normalizedApplied: sample.normalizedApplied,\n textSource: sample.textSource,\n ...(sample.borrowedContext ? { borrowedContext: sample.borrowedContext } : {}),\n };\n}\n\nexport function buildEmptyEngineInspectResult(\n input: DetectorInspectResult[\"input\"],\n): DetectorInspectResult {\n return {\n schemaVersion: 1,\n kind: \"detector-inspect\",\n view: \"engine\",\n detector: \"wasm\",\n input,\n sample: {\n text: \"\",\n textLength: 0,\n normalizedText: \"\",\n normalizedApplied: false,\n textSource: \"focus\",\n },\n decision: {\n kind: \"empty\",\n notes: [\"No detector-eligible content was present.\"],\n },\n };\n}\n\nexport async function buildEngineInspectResult(\n input: DetectorInspectResult[\"input\"],\n window: DetectorWindow,\n chunks: Array<{ locale: string; text: string }>,\n executeEngine: (\n sample: ReturnType<\n (typeof DETECTOR_ROUTE_POLICIES)[typeof window.routeTag][\"buildDiagnosticSample\"]\n >,\n routeTag: typeof window.routeTag,\n ) => Promise<ExecutedEngineSample>,\n): Promise<DetectorInspectResult> {\n const sample = DETECTOR_ROUTE_POLICIES[window.routeTag].buildDiagnosticSample(window, chunks);\n const { rawResult, rawRemapped, normalizedResult, normalizedRemapped } = await executeEngine(\n sample,\n window.routeTag,\n );\n\n if (!rawResult) {\n return {\n schemaVersion: 1,\n kind: \"detector-inspect\",\n view: \"engine\",\n detector: \"wasm\",\n input,\n routeTag: window.routeTag,\n sample: buildInspectSample(sample),\n };\n }\n\n return {\n schemaVersion: 1,\n kind: \"detector-inspect\",\n view: \"engine\",\n detector: \"wasm\",\n input,\n routeTag: window.routeTag,\n sample: buildInspectSample(sample),\n engine: {\n name: \"whatlang-wasm\",\n raw: rawResult,\n ...(normalizedResult ? { normalized: normalizedResult } : {}),\n remapped: {\n rawTag: rawRemapped?.tag ?? null,\n normalizedTag: normalizedRemapped?.tag ?? null,\n },\n },\n };\n}\n\nexport function buildEmptyPipelineInspectResult(\n input: DetectorInspectResult[\"input\"],\n): DetectorInspectResult {\n return {\n schemaVersion: 1,\n kind: \"detector-inspect\",\n view: \"pipeline\",\n detector: \"wasm\",\n input,\n chunks: [],\n windows: [],\n decision: {\n kind: \"empty\",\n notes: [\"No detector-eligible content was present.\"],\n },\n resolvedChunks: [],\n };\n}\n\nexport function buildPipelineInspectResult(\n input: DetectorInspectResult[\"input\"],\n tracedChunks: TracedLocaleChunk[],\n resolvedWindows: Array<ResolvedDetectorWindow & { window: DetectorWindow; windowIndex: number }>,\n finalResolved: Array<{ locale: string; text: string }>,\n): DetectorInspectResult {\n return {\n schemaVersion: 1,\n kind: \"detector-inspect\",\n view: \"pipeline\",\n detector: \"wasm\",\n input,\n chunks: tracedChunks.map((chunk, index) =>\n createInspectChunk(index, chunk, {\n source: chunk.source,\n }),\n ),\n windows: resolvedWindows.map(\n ({\n window,\n windowIndex,\n sample,\n eligibility,\n contentGate,\n engineExecuted,\n engineReason,\n decision,\n }) => {\n const focusPreview = createInspectPreview(sample.focusText);\n const samplePreview = createInspectPreview(sample.text);\n const normalizedPreview = createInspectPreview(sample.normalizedText);\n const inspectWindow: DetectorInspectWindow = {\n windowIndex,\n routeTag: window.routeTag,\n chunkRange: {\n start: window.startIndex,\n end: window.endIndex,\n },\n focusTextPreview: focusPreview.textPreview,\n focusTextPreviewTruncated: focusPreview.textPreviewTruncated,\n diagnosticSample: {\n textPreview: samplePreview.textPreview,\n textPreviewTruncated: samplePreview.textPreviewTruncated,\n normalizedTextPreview: normalizedPreview.textPreview,\n normalizedTextPreviewTruncated: normalizedPreview.textPreviewTruncated,\n normalizedApplied: sample.normalizedApplied,\n ...(sample.borrowedContext ? { borrowedContext: sample.borrowedContext } : {}),\n },\n eligibility,\n contentGate,\n engine: {\n executed: engineExecuted,\n ...(engineReason ? { reason: engineReason } : {}),\n },\n decision,\n };\n return inspectWindow;\n },\n ),\n resolvedChunks: finalResolved.map((chunk, index) => createInspectChunk(index, chunk)),\n };\n}\n","import { DEFAULT_HAN_TAG, DEFAULT_LOCALE } from \"../wc/locale-detect\";\nimport type { DetectorRouteTag } from \"./policy\";\nimport type { DetectorResult } from \"./types\";\n\nexport interface WhatlangWasmResult {\n lang: string;\n script: string;\n confidence: number;\n reliable: boolean;\n}\n\nconst LATIN_LANGUAGE_TAGS: Record<string, string> = {\n cat: \"ca\",\n ces: \"cs\",\n dan: \"da\",\n deu: \"de\",\n eng: \"en\",\n fin: \"fi\",\n fra: \"fr\",\n hun: \"hu\",\n ita: \"it\",\n lat: \"la\",\n nld: \"nl\",\n pol: \"pl\",\n por: \"pt\",\n ron: \"ro\",\n spa: \"es\",\n swe: \"sv\",\n tur: \"tr\",\n};\n\nconst HANI_LANGUAGE_TAGS: Record<string, string> = {\n cmn: \"zh\",\n jpn: \"ja\",\n};\n\nfunction hasSupportedScript(result: WhatlangWasmResult, routeTag: DetectorRouteTag): boolean {\n if (routeTag === DEFAULT_LOCALE) {\n return result.script === \"Latin\";\n }\n\n if (result.lang === \"cmn\") {\n return result.script === \"Mandarin\";\n }\n\n if (result.lang === \"jpn\") {\n return (\n result.script === \"Mandarin\" || result.script === \"Hiragana\" || result.script === \"Katakana\"\n );\n }\n\n return false;\n}\n\nfunction remapLanguageTag(lang: string, routeTag: DetectorRouteTag): string | undefined {\n if (routeTag === DEFAULT_LOCALE) {\n return LATIN_LANGUAGE_TAGS[lang];\n }\n\n return HANI_LANGUAGE_TAGS[lang];\n}\n\nexport function remapWhatlangResult(\n result: WhatlangWasmResult,\n routeTag: DetectorRouteTag,\n): DetectorResult | null {\n if (!hasSupportedScript(result, routeTag)) {\n return null;\n }\n\n const tag = remapLanguageTag(result.lang, routeTag);\n if (!tag) {\n return null;\n }\n\n return {\n tag,\n confidence: result.confidence,\n reliable: result.reliable,\n source: \"wasm\",\n };\n}\n\nexport function getDetectorFallbackTag(routeTag: DetectorRouteTag): string {\n return routeTag === DEFAULT_HAN_TAG ? DEFAULT_HAN_TAG : DEFAULT_LOCALE;\n}\n","import { segmentTextByLocale } from \"../wc\";\nimport { DEFAULT_LOCALE } from \"../wc/locale-detect\";\nimport type { LocaleChunk } from \"../wc/types\";\nimport { getDetectorFallbackTag } from \"./whatlang-map\";\nimport type { DetectorLocaleOptions } from \"./types\";\nimport type { DetectorWindow } from \"./policy\";\n\nexport function createDeferredLatinPreSegmentOptions(\n options: DetectorLocaleOptions,\n): DetectorLocaleOptions {\n return {\n ...options,\n latinLanguageHint: undefined,\n latinTagHint: undefined,\n latinLocaleHint: undefined,\n latinHintRules: undefined,\n useDefaultLatinHints: false,\n };\n}\n\nfunction createRuleOnlyLatinOptions(options: DetectorLocaleOptions): DetectorLocaleOptions {\n return {\n ...options,\n latinLanguageHint: undefined,\n latinTagHint: undefined,\n latinLocaleHint: undefined,\n };\n}\n\nfunction mergeAdjacentChunks(chunks: LocaleChunk[]): LocaleChunk[] {\n if (chunks.length === 0) {\n return chunks;\n }\n\n const merged: LocaleChunk[] = [];\n let last = chunks[0]!;\n\n for (let index = 1; index < chunks.length; index += 1) {\n const chunk = chunks[index]!;\n if (chunk.locale === last.locale) {\n last = {\n locale: last.locale,\n text: last.text + chunk.text,\n };\n continue;\n }\n merged.push(last);\n last = chunk;\n }\n\n merged.push(last);\n return merged;\n}\n\nexport function reapplyDeferredLatinFallback(\n chunks: LocaleChunk[],\n options: DetectorLocaleOptions,\n): LocaleChunk[] {\n const relabeled: LocaleChunk[] = [];\n\n for (const chunk of chunks) {\n if (chunk.locale !== DEFAULT_LOCALE) {\n relabeled.push(chunk);\n continue;\n }\n\n relabeled.push(...segmentTextByLocale(chunk.text, options));\n }\n\n return mergeAdjacentChunks(relabeled);\n}\n\nexport function reapplyResolvedLatinHintRules(\n resolvedChunks: LocaleChunk[],\n originalChunks: LocaleChunk[],\n options: DetectorLocaleOptions,\n): LocaleChunk[] {\n const relabeled: LocaleChunk[] = [];\n const ruleOnlyOptions = createRuleOnlyLatinOptions(options);\n\n for (let index = 0; index < resolvedChunks.length; index += 1) {\n const chunk = resolvedChunks[index];\n const originalChunk = originalChunks[index];\n if (!chunk || !originalChunk) {\n continue;\n }\n\n if (originalChunk.locale !== DEFAULT_LOCALE || chunk.locale === DEFAULT_LOCALE) {\n relabeled.push(chunk);\n continue;\n }\n\n const hintedChunks = segmentTextByLocale(chunk.text, ruleOnlyOptions).map((hintedChunk) => ({\n locale: hintedChunk.locale === DEFAULT_LOCALE ? chunk.locale : hintedChunk.locale,\n text: hintedChunk.text,\n }));\n relabeled.push(...hintedChunks);\n }\n\n return mergeAdjacentChunks(relabeled);\n}\n\nexport function resolveFallbackDebugOutcome(\n window: DetectorWindow,\n options: DetectorLocaleOptions,\n): {\n finalTag: string;\n finalLocales?: string[];\n} {\n const fallbackTag = getDetectorFallbackTag(window.routeTag);\n if (window.routeTag !== DEFAULT_LOCALE) {\n return { finalTag: fallbackTag };\n }\n\n const relabeled = reapplyDeferredLatinFallback(\n [\n {\n locale: fallbackTag,\n text: window.text,\n },\n ],\n options,\n );\n const finalLocales = relabeled.map((chunk) => chunk.locale);\n if (finalLocales.length === 1) {\n return {\n finalTag: finalLocales[0]!,\n };\n }\n\n return finalLocales.length > 1\n ? {\n finalTag: fallbackTag,\n finalLocales,\n }\n : {\n finalTag: fallbackTag,\n };\n}\n","import { existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { createRequire } from \"node:module\";\nimport { fileURLToPath } from \"node:url\";\nimport type { DetectorRouteTag } from \"./policy\";\nimport type { WhatlangWasmResult } from \"./whatlang-map\";\n\nconst GENERATED_FOLDER_NAME = \"wasm-language-detector\";\nconst GENERATED_MODULE_FILE = \"language_detector.js\";\nconst MAX_SEARCH_DEPTH = 8;\nconst requireFromHere = createRequire(import.meta.url);\n\nexport const WASM_DETECTOR_RUNTIME_UNAVAILABLE_MESSAGE =\n \"WASM detector runtime is unavailable. Run `bun run build:wasm` to generate it.\";\n\ntype WhatlangWasmModule = {\n detect_language: (text: string, routeTag: string) => WhatlangWasmResult | null;\n};\n\nlet modulePromise: Promise<WhatlangWasmModule> | null = null;\n\nfunction resolveCandidateModulePaths(): string[] {\n const moduleDir = dirname(fileURLToPath(import.meta.url));\n const candidates = new Set<string>();\n let currentDir = moduleDir;\n\n for (let depth = 0; depth < MAX_SEARCH_DEPTH; depth += 1) {\n candidates.add(join(currentDir, GENERATED_FOLDER_NAME, GENERATED_MODULE_FILE));\n candidates.add(join(currentDir, \"generated\", GENERATED_FOLDER_NAME, GENERATED_MODULE_FILE));\n\n const parentDir = dirname(currentDir);\n if (parentDir === currentDir) {\n break;\n }\n currentDir = parentDir;\n }\n\n return [...candidates];\n}\n\nfunction resolveWhatlangWasmModulePath(): string {\n for (const candidate of resolveCandidateModulePaths()) {\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n\n throw new Error(WASM_DETECTOR_RUNTIME_UNAVAILABLE_MESSAGE);\n}\n\nasync function loadWhatlangWasmModule(): Promise<WhatlangWasmModule> {\n if (!modulePromise) {\n modulePromise = (async () => {\n const modulePath = resolveWhatlangWasmModulePath();\n return requireFromHere(modulePath) as WhatlangWasmModule;\n })();\n }\n\n return modulePromise;\n}\n\nexport async function detectWithWhatlangWasm(\n text: string,\n routeTag: DetectorRouteTag,\n): Promise<WhatlangWasmResult | null> {\n const wasmModule = await loadWhatlangWasmModule();\n return wasmModule.detect_language(text, routeTag);\n}\n","import type { DetectorDiagnosticSample, DetectorRouteTag } from \"./policy\";\nimport { remapWhatlangResult } from \"./whatlang-map\";\nimport { detectWithWhatlangWasm } from \"./whatlang-wasm\";\nimport type { DetectorResult } from \"./types\";\n\nexport type ExecutedEngineSample = {\n rawResult: Awaited<ReturnType<typeof detectWithWhatlangWasm>> | null;\n rawRemapped: DetectorResult | null;\n normalizedResult: Awaited<ReturnType<typeof detectWithWhatlangWasm>> | null;\n normalizedRemapped: DetectorResult | null;\n};\n\nexport function buildEvidenceSample(\n result: Awaited<ReturnType<typeof detectWithWhatlangWasm>> | null,\n remappedTag: string | null,\n) {\n return {\n lang: result?.lang ?? null,\n script: result?.script ?? null,\n confidence: result?.confidence ?? null,\n reliable: result?.reliable ?? null,\n remappedTag,\n };\n}\n\nexport async function executeEngineSample(\n sample: DetectorDiagnosticSample,\n routeTag: DetectorRouteTag,\n): Promise<ExecutedEngineSample> {\n const rawResult = await detectWithWhatlangWasm(sample.text, routeTag);\n const rawRemapped = rawResult ? remapWhatlangResult(rawResult, routeTag) : null;\n const normalizedResult =\n sample.normalizedApplied && sample.normalizedText.length > 0\n ? await detectWithWhatlangWasm(sample.normalizedText, routeTag)\n : null;\n const normalizedRemapped = normalizedResult\n ? remapWhatlangResult(normalizedResult, routeTag)\n : null;\n\n return {\n rawResult,\n rawRemapped,\n normalizedResult,\n normalizedRemapped,\n };\n}\n","import {\n createDetectorEvidencePreview,\n recordDetectorAccepted,\n recordDetectorFallback,\n recordDetectorWindow,\n type DetectorFallbackReason,\n} from \"./debug\";\nimport {\n DETECTOR_ROUTE_POLICIES,\n type DetectorContentGateResult,\n type DetectorDiagnosticSample,\n type DetectorEligibilityResult,\n type DetectorWindow,\n} from \"./policy\";\nimport type { LocaleChunk } from \"../wc/types\";\nimport { getDetectorFallbackTag } from \"./whatlang-map\";\nimport type { DetectorLocaleOptions } from \"./types\";\nimport { buildEvidenceSample, executeEngineSample } from \"./wasm-engine\";\nimport { resolveFallbackDebugOutcome } from \"./wasm-presegment\";\n\nexport type ResolvedDetectorWindow = {\n resolvedLocale: string;\n sample: DetectorDiagnosticSample;\n eligibility: DetectorEligibilityResult;\n contentGate: DetectorContentGateResult;\n engineExecuted: boolean;\n engineReason?: \"notEligible\";\n rawResult: Awaited<ReturnType<typeof executeEngineSample>>[\"rawResult\"];\n rawRemappedTag: string | null;\n normalizedResult: Awaited<ReturnType<typeof executeEngineSample>>[\"normalizedResult\"];\n normalizedRemappedTag: string | null;\n decision: {\n accepted: boolean;\n path: \"reliable\" | \"corroborated\" | null;\n finalTag: string;\n finalLocales?: string[];\n fallbackReason: DetectorFallbackReason | null;\n };\n};\n\nfunction emitDetectorWindowEvidence({\n window,\n windowIndex,\n sample,\n eligibility,\n contentGate,\n rawResult,\n rawRemappedTag,\n normalizedResult,\n normalizedRemappedTag,\n decision,\n debug,\n}: {\n window: DetectorWindow;\n windowIndex: number;\n sample: DetectorDiagnosticSample;\n eligibility: DetectorEligibilityResult;\n contentGate: DetectorContentGateResult;\n rawResult: ResolvedDetectorWindow[\"rawResult\"];\n rawRemappedTag: string | null;\n normalizedResult: ResolvedDetectorWindow[\"normalizedResult\"];\n normalizedRemappedTag: string | null;\n decision: ResolvedDetectorWindow[\"decision\"];\n debug?: DetectorLocaleOptions[\"detectorDebug\"];\n}): void {\n const evidence = debug?.evidence;\n if (!evidence || !debug.emit) {\n return;\n }\n\n const baseDetails = {\n engine: \"whatlang-wasm\",\n routeTag: window.routeTag,\n windowIndex,\n startIndex: window.startIndex,\n endIndex: window.endIndex,\n mode: evidence.mode,\n section: evidence.section,\n textLength: sample.text.length,\n focusTextLength: sample.focusText.length,\n normalizedLength: sample.normalizedText.length,\n normalizedApplied: sample.normalizedApplied,\n textSource: sample.textSource,\n scriptChars: eligibility.scriptChars,\n minScriptChars: eligibility.minScriptChars,\n eligible: eligibility.passed,\n contentGate,\n qualityGate: contentGate.passed,\n raw: buildEvidenceSample(rawResult, rawRemappedTag),\n normalized: buildEvidenceSample(normalizedResult, normalizedRemappedTag),\n decision,\n ...(sample.borrowedContext ? { borrowedContext: sample.borrowedContext } : {}),\n };\n\n if (evidence.verbosity === \"verbose\") {\n debug.emit(\n \"detector.window.evidence\",\n {\n ...baseDetails,\n text: sample.text,\n normalizedText: sample.normalizedText,\n },\n { verbosity: \"verbose\" },\n );\n return;\n }\n\n const textPreview = createDetectorEvidencePreview(sample.text);\n const normalizedPreview = createDetectorEvidencePreview(sample.normalizedText);\n debug.emit(\n \"detector.window.evidence\",\n {\n ...baseDetails,\n textPreview: textPreview.preview,\n textPreviewTruncated: textPreview.truncated,\n normalizedPreview: normalizedPreview.preview,\n normalizedPreviewTruncated: normalizedPreview.truncated,\n },\n { verbosity: \"compact\" },\n );\n}\n\nexport async function resolveWindowLocale(\n window: DetectorWindow,\n windowIndex: number,\n chunks: LocaleChunk[],\n options: DetectorLocaleOptions,\n debug?: DetectorLocaleOptions[\"detectorDebug\"],\n): Promise<ResolvedDetectorWindow> {\n const routePolicy = DETECTOR_ROUTE_POLICIES[window.routeTag];\n const sample = routePolicy.buildDiagnosticSample(window, chunks);\n const configuredMode = options.contentGate?.mode;\n const eligibility = routePolicy.eligibility.evaluate(sample, configuredMode);\n const contentGate = routePolicy.evaluateContentGate(sample, configuredMode);\n\n recordDetectorWindow(debug?.summary, window.routeTag);\n debug?.emit?.(\n \"detector.window.start\",\n {\n routeTag: window.routeTag,\n startIndex: window.startIndex,\n endIndex: window.endIndex,\n textLength: window.text.length,\n sampleTextLength: sample.text.length,\n textSource: sample.textSource,\n ...(sample.borrowedContext ? { borrowedContext: sample.borrowedContext } : {}),\n },\n { verbosity: \"verbose\" },\n );\n\n if (!eligibility.passed) {\n recordDetectorFallback(debug?.summary, \"notEligible\");\n const fallbackDebugOutcome = resolveFallbackDebugOutcome(window, options);\n const resolution: ResolvedDetectorWindow = {\n resolvedLocale: getDetectorFallbackTag(window.routeTag),\n sample,\n eligibility,\n contentGate,\n engineExecuted: false,\n engineReason: \"notEligible\",\n rawResult: null,\n rawRemappedTag: null,\n normalizedResult: null,\n normalizedRemappedTag: null,\n decision: {\n accepted: false,\n path: null,\n finalTag: fallbackDebugOutcome.finalTag,\n ...(fallbackDebugOutcome.finalLocales\n ? { finalLocales: fallbackDebugOutcome.finalLocales }\n : {}),\n fallbackReason: \"notEligible\",\n },\n };\n emitDetectorWindowEvidence({\n window,\n windowIndex,\n sample: resolution.sample,\n eligibility: resolution.eligibility,\n contentGate: resolution.contentGate,\n rawResult: resolution.rawResult,\n rawRemappedTag: resolution.rawRemappedTag,\n normalizedResult: resolution.normalizedResult,\n normalizedRemappedTag: resolution.normalizedRemappedTag,\n decision: resolution.decision,\n debug,\n });\n debug?.emit?.(\"detector.window.fallback\", {\n routeTag: window.routeTag,\n finalTag: fallbackDebugOutcome.finalTag,\n ...(fallbackDebugOutcome.finalLocales\n ? { finalLocales: fallbackDebugOutcome.finalLocales }\n : {}),\n reason: \"notEligible\",\n });\n return resolution;\n }\n\n const { rawResult, rawRemapped, normalizedResult, normalizedRemapped } =\n await executeEngineSample(sample, window.routeTag);\n debug?.emit?.(\n \"detector.window.sample\",\n {\n routeTag: window.routeTag,\n normalizedApplied: sample.normalizedApplied,\n normalizedLength: sample.normalizedText.length,\n textSource: sample.textSource,\n contentGate,\n qualityGate: contentGate.passed,\n rawTag: rawRemapped?.tag ?? null,\n rawConfidence: rawRemapped?.confidence ?? null,\n rawReliable: rawRemapped?.reliable ?? null,\n ...(sample.borrowedContext ? { borrowedContext: sample.borrowedContext } : {}),\n },\n { verbosity: \"verbose\" },\n );\n debug?.emit?.(\n \"detector.window.candidates\",\n {\n routeTag: window.routeTag,\n normalizedTag: normalizedRemapped?.tag ?? null,\n normalizedConfidence: normalizedRemapped?.confidence ?? null,\n normalizedReliable: normalizedRemapped?.reliable ?? null,\n },\n { verbosity: \"verbose\" },\n );\n\n const candidates = [rawRemapped, normalizedRemapped].filter((value) => value !== null);\n if (candidates.length === 0) {\n recordDetectorFallback(debug?.summary, \"noCandidate\");\n const fallbackDebugOutcome = resolveFallbackDebugOutcome(window, options);\n const resolution: ResolvedDetectorWindow = {\n resolvedLocale: getDetectorFallbackTag(window.routeTag),\n sample,\n eligibility,\n contentGate,\n engineExecuted: true,\n rawResult,\n rawRemappedTag: rawRemapped?.tag ?? null,\n normalizedResult,\n normalizedRemappedTag: normalizedRemapped?.tag ?? null,\n decision: {\n accepted: false,\n path: null,\n finalTag: fallbackDebugOutcome.finalTag,\n ...(fallbackDebugOutcome.finalLocales\n ? { finalLocales: fallbackDebugOutcome.finalLocales }\n : {}),\n fallbackReason: \"noCandidate\",\n },\n };\n emitDetectorWindowEvidence({\n window,\n windowIndex,\n sample: resolution.sample,\n eligibility: resolution.eligibility,\n contentGate: resolution.contentGate,\n rawResult: resolution.rawResult,\n rawRemappedTag: resolution.rawRemappedTag,\n normalizedResult: resolution.normalizedResult,\n normalizedRemappedTag: resolution.normalizedRemappedTag,\n decision: resolution.decision,\n debug,\n });\n debug?.emit?.(\"detector.window.fallback\", {\n routeTag: window.routeTag,\n finalTag: fallbackDebugOutcome.finalTag,\n ...(fallbackDebugOutcome.finalLocales\n ? { finalLocales: fallbackDebugOutcome.finalLocales }\n : {}),\n reason: \"noCandidate\",\n });\n return resolution;\n }\n\n const strongestCandidate = candidates.reduce((best, current) => {\n if (!best) {\n return current;\n }\n return (current.confidence ?? 0) > (best.confidence ?? 0) ? current : best;\n }, candidates[0]);\n\n if (strongestCandidate && contentGate.passed && routePolicy.accept(strongestCandidate)) {\n recordDetectorAccepted(debug?.summary, \"reliable\");\n const resolution: ResolvedDetectorWindow = {\n resolvedLocale: strongestCandidate.tag,\n sample,\n eligibility,\n contentGate,\n engineExecuted: true,\n rawResult,\n rawRemappedTag: rawRemapped?.tag ?? null,\n normalizedResult,\n normalizedRemappedTag: normalizedRemapped?.tag ?? null,\n decision: {\n accepted: true,\n path: \"reliable\",\n finalTag: strongestCandidate.tag,\n fallbackReason: null,\n },\n };\n emitDetectorWindowEvidence({\n window,\n windowIndex,\n sample: resolution.sample,\n eligibility: resolution.eligibility,\n contentGate: resolution.contentGate,\n rawResult: resolution.rawResult,\n rawRemappedTag: resolution.rawRemappedTag,\n normalizedResult: resolution.normalizedResult,\n normalizedRemappedTag: resolution.normalizedRemappedTag,\n decision: resolution.decision,\n debug,\n });\n debug?.emit?.(\"detector.window.accepted\", {\n routeTag: window.routeTag,\n finalTag: strongestCandidate.tag,\n acceptancePath: \"reliable\",\n confidence: strongestCandidate.confidence ?? null,\n reliable: strongestCandidate.reliable ?? null,\n });\n return resolution;\n }\n\n if (contentGate.passed && routePolicy.acceptCorroborated && rawRemapped && normalizedRemapped) {\n const corroborated = routePolicy.acceptCorroborated(rawRemapped, normalizedRemapped);\n if (corroborated.accepted) {\n recordDetectorAccepted(debug?.summary, \"corroborated\");\n const resolution: ResolvedDetectorWindow = {\n resolvedLocale: rawRemapped.tag,\n sample,\n eligibility,\n contentGate,\n engineExecuted: true,\n rawResult,\n rawRemappedTag: rawRemapped.tag,\n normalizedResult,\n normalizedRemappedTag: normalizedRemapped.tag,\n decision: {\n accepted: true,\n path: \"corroborated\",\n finalTag: rawRemapped.tag,\n fallbackReason: null,\n },\n };\n emitDetectorWindowEvidence({\n window,\n windowIndex,\n sample: resolution.sample,\n eligibility: resolution.eligibility,\n contentGate: resolution.contentGate,\n rawResult: resolution.rawResult,\n rawRemappedTag: resolution.rawRemappedTag,\n normalizedResult: resolution.normalizedResult,\n normalizedRemappedTag: resolution.normalizedRemappedTag,\n decision: resolution.decision,\n debug,\n });\n debug?.emit?.(\"detector.window.accepted\", {\n routeTag: window.routeTag,\n finalTag: rawRemapped.tag,\n acceptancePath: \"corroborated\",\n confidence: corroborated.confidence,\n reliable: corroborated.hasReliableCorroboration,\n });\n return resolution;\n }\n\n if (corroborated.reason === \"unreliable\") {\n recordDetectorFallback(debug?.summary, \"corroborationUnreliable\");\n const fallbackDebugOutcome = resolveFallbackDebugOutcome(window, options);\n const resolution: ResolvedDetectorWindow = {\n resolvedLocale: getDetectorFallbackTag(window.routeTag),\n sample,\n eligibility,\n contentGate,\n engineExecuted: true,\n rawResult,\n rawRemappedTag: rawRemapped.tag,\n normalizedResult,\n normalizedRemappedTag: normalizedRemapped.tag,\n decision: {\n accepted: false,\n path: null,\n finalTag: fallbackDebugOutcome.finalTag,\n ...(fallbackDebugOutcome.finalLocales\n ? { finalLocales: fallbackDebugOutcome.finalLocales }\n : {}),\n fallbackReason: \"corroborationUnreliable\",\n },\n };\n emitDetectorWindowEvidence({\n window,\n windowIndex,\n sample: resolution.sample,\n eligibility: resolution.eligibility,\n contentGate: resolution.contentGate,\n rawResult: resolution.rawResult,\n rawRemappedTag: resolution.rawRemappedTag,\n normalizedResult: resolution.normalizedResult,\n normalizedRemappedTag: resolution.normalizedRemappedTag,\n decision: resolution.decision,\n debug,\n });\n debug?.emit?.(\"detector.window.fallback\", {\n routeTag: window.routeTag,\n finalTag: fallbackDebugOutcome.finalTag,\n ...(fallbackDebugOutcome.finalLocales\n ? { finalLocales: fallbackDebugOutcome.finalLocales }\n : {}),\n reason: \"corroborationUnreliable\",\n });\n return resolution;\n }\n }\n\n const fallbackReason = contentGate.passed ? \"belowThreshold\" : \"qualityGate\";\n recordDetectorFallback(debug?.summary, fallbackReason);\n const fallbackDebugOutcome = resolveFallbackDebugOutcome(window, options);\n const resolution: ResolvedDetectorWindow = {\n resolvedLocale: getDetectorFallbackTag(window.routeTag),\n sample,\n eligibility,\n contentGate,\n engineExecuted: true,\n rawResult,\n rawRemappedTag: rawRemapped?.tag ?? null,\n normalizedResult,\n normalizedRemappedTag: normalizedRemapped?.tag ?? null,\n decision: {\n accepted: false,\n path: null,\n finalTag: fallbackDebugOutcome.finalTag,\n ...(fallbackDebugOutcome.finalLocales\n ? { finalLocales: fallbackDebugOutcome.finalLocales }\n : {}),\n fallbackReason,\n },\n };\n emitDetectorWindowEvidence({\n window,\n windowIndex,\n sample: resolution.sample,\n eligibility: resolution.eligibility,\n contentGate: resolution.contentGate,\n rawResult: resolution.rawResult,\n rawRemappedTag: resolution.rawRemappedTag,\n normalizedResult: resolution.normalizedResult,\n normalizedRemappedTag: resolution.normalizedRemappedTag,\n decision: resolution.decision,\n debug,\n });\n debug?.emit?.(\"detector.window.fallback\", {\n routeTag: window.routeTag,\n finalTag: fallbackDebugOutcome.finalTag,\n ...(fallbackDebugOutcome.finalLocales\n ? { finalLocales: fallbackDebugOutcome.finalLocales }\n : {}),\n reason: fallbackReason,\n });\n return resolution;\n}\n","import type { LocaleChunk } from \"../wc/types\";\nimport { isAmbiguousDetectorRoute, type DetectorWindow } from \"./policy\";\n\nexport function buildDetectorWindows(chunks: LocaleChunk[]): DetectorWindow[] {\n const windows: DetectorWindow[] = [];\n\n for (let index = 0; index < chunks.length; index += 1) {\n const chunk = chunks[index];\n if (!chunk || !isAmbiguousDetectorRoute(chunk.locale)) {\n continue;\n }\n\n const previousWindow = windows[windows.length - 1];\n if (\n previousWindow &&\n previousWindow.routeTag === chunk.locale &&\n previousWindow.endIndex === index - 1\n ) {\n previousWindow.endIndex = index;\n previousWindow.text += chunk.text;\n continue;\n }\n\n windows.push({\n routeTag: chunk.locale,\n startIndex: index,\n endIndex: index,\n text: chunk.text,\n });\n }\n\n return windows;\n}\n","import { segmentTextByLocale } from \"../wc\";\nimport { resolveLocaleDetectContext } from \"../wc/locale-detect\";\nimport { buildWordCounterResultFromChunks } from \"./result-builder\";\nimport { countSectionsWithResolvedDetector } from \"./sections\";\nimport { type DetectorWindow } from \"./policy\";\nimport { createInspectInput, segmentTextByLocaleWithTrace } from \"./inspect-helpers\";\nimport type { DetectorInspectOptions, DetectorInspectResult } from \"./inspect-types\";\nimport {\n buildEmptyEngineInspectResult,\n buildEmptyPipelineInspectResult,\n buildEngineInspectResult,\n buildPipelineInspectResult,\n} from \"./wasm-inspect\";\nimport {\n createDeferredLatinPreSegmentOptions,\n reapplyDeferredLatinFallback,\n reapplyResolvedLatinHintRules,\n} from \"./wasm-presegment\";\nimport { executeEngineSample } from \"./wasm-engine\";\nimport { resolveWindowLocale, type ResolvedDetectorWindow } from \"./wasm-resolution\";\nimport { buildDetectorWindows } from \"./wasm-windows\";\nimport { WASM_DETECTOR_RUNTIME_UNAVAILABLE_MESSAGE } from \"./whatlang-wasm\";\nimport type {\n DetectorCountSectionsOptions,\n DetectorLocaleOptions,\n DetectorWordCounterOptions,\n} from \"./types\";\n\nexport { WASM_DETECTOR_RUNTIME_UNAVAILABLE_MESSAGE };\n\nexport async function segmentTextByLocaleWithWasmDetector(\n text: string,\n options: DetectorLocaleOptions = {},\n) {\n // Validate the original hint configuration up front even though Latin hinting\n // is deferred until after detector routing in WASM mode.\n resolveLocaleDetectContext(options);\n\n const chunks = segmentTextByLocale(text, createDeferredLatinPreSegmentOptions(options));\n const resolved = [...chunks];\n const windows = buildDetectorWindows(chunks);\n\n for (const [windowIndex, window] of windows.entries()) {\n const resolution = await resolveWindowLocale(\n window,\n windowIndex,\n chunks,\n options,\n options.detectorDebug,\n );\n for (let index = window.startIndex; index <= window.endIndex; index += 1) {\n const chunk = resolved[index];\n if (!chunk) {\n continue;\n }\n resolved[index] = {\n ...chunk,\n locale: resolution.resolvedLocale,\n };\n }\n }\n\n options.detectorDebug?.emit?.(\"detector.summary\", options.detectorDebug.summary, {\n verbosity: \"compact\",\n });\n const hintRelabeled = reapplyResolvedLatinHintRules(resolved, chunks, options);\n return reapplyDeferredLatinFallback(hintRelabeled, options);\n}\n\nexport async function wordCounterWithWasmDetector(\n text: string,\n options: DetectorWordCounterOptions = {},\n) {\n const chunks = await segmentTextByLocaleWithWasmDetector(text, options);\n return buildWordCounterResultFromChunks(chunks, options);\n}\n\nexport async function countSectionsWithWasmDetector(\n input: string,\n section: Parameters<typeof countSectionsWithResolvedDetector>[1],\n options: DetectorCountSectionsOptions = {},\n) {\n return countSectionsWithResolvedDetector(input, section, options);\n}\n\nexport async function inspectTextWithWasmDetector(\n text: string,\n options: DetectorInspectOptions = {},\n): Promise<DetectorInspectResult> {\n const input = createInspectInput(text, options.input);\n const tracedChunks = segmentTextByLocaleWithTrace(\n text,\n createDeferredLatinPreSegmentOptions(options),\n );\n const chunks = tracedChunks.map(({ locale, text: chunkText }) => ({\n locale,\n text: chunkText,\n }));\n const windows = buildDetectorWindows(chunks);\n\n if (options.view === \"engine\") {\n if (windows.length === 0) {\n return buildEmptyEngineInspectResult(input);\n }\n\n const window = windows[0]!;\n return buildEngineInspectResult(input, window, chunks, executeEngineSample);\n }\n\n if (text.trim().length === 0) {\n return buildEmptyPipelineInspectResult(input);\n }\n\n const resolved = [...chunks];\n const resolvedWindows: Array<\n ResolvedDetectorWindow & { window: DetectorWindow; windowIndex: number }\n > = [];\n\n for (const [windowIndex, window] of windows.entries()) {\n const resolution = await resolveWindowLocale(window, windowIndex, chunks, options);\n resolvedWindows.push({\n ...resolution,\n window,\n windowIndex,\n });\n for (let index = window.startIndex; index <= window.endIndex; index += 1) {\n const chunk = resolved[index];\n if (!chunk) {\n continue;\n }\n resolved[index] = {\n ...chunk,\n locale: resolution.resolvedLocale,\n };\n }\n }\n\n const hintRelabeled = reapplyResolvedLatinHintRules(resolved, chunks, options);\n const finalResolved = reapplyDeferredLatinFallback(hintRelabeled, options);\n\n return buildPipelineInspectResult(input, tracedChunks, resolvedWindows, finalResolved);\n}\n","import { inspectTextWithRegexDetector } from \"./none\";\nimport type { DetectorInspectOptions, DetectorInspectResult } from \"./inspect-types\";\nimport type { DetectorMode } from \"./types\";\nimport { inspectTextWithWasmDetector } from \"./wasm\";\n\nfunction resolveInspectDetectorMode(\n mode: DetectorMode | undefined,\n view: DetectorInspectOptions[\"view\"],\n): DetectorMode {\n if (mode) {\n return mode;\n }\n\n void view;\n return \"wasm\";\n}\n\nexport async function inspectTextWithDetector(\n text: string,\n options: DetectorInspectOptions = {},\n): Promise<DetectorInspectResult> {\n const view = options.view ?? \"pipeline\";\n const detector = resolveInspectDetectorMode(options.detector, view);\n\n if (detector === \"regex\" && view === \"engine\") {\n throw new Error('`view: \"engine\"` requires `detector: \"wasm\"`.');\n }\n\n if (detector === \"regex\") {\n return inspectTextWithRegexDetector(text, {\n ...options,\n detector,\n view: \"pipeline\",\n });\n }\n\n return inspectTextWithWasmDetector(text, {\n ...options,\n detector,\n view,\n });\n}\n","import type { SectionMode } from \"../markdown\";\nimport type { LocaleChunk } from \"../wc/types\";\nimport {\n countSectionsWithRegexDetector,\n inspectTextWithRegexDetector,\n segmentTextByLocaleWithRegexDetector,\n wordCounterWithRegexDetector,\n} from \"./none\";\nimport {\n countSectionsWithWasmDetector,\n inspectTextWithWasmDetector,\n segmentTextByLocaleWithWasmDetector,\n WASM_DETECTOR_RUNTIME_UNAVAILABLE_MESSAGE,\n wordCounterWithWasmDetector,\n} from \"./wasm\";\nimport { inspectTextWithDetector } from \"./inspect\";\nimport { createDetectorDebugSummary, mergeDetectorDebugSummaries } from \"./debug\";\nimport type {\n DetectorContentGateMode,\n DetectorContentGateOptions,\n DetectorCountSectionsOptions,\n DetectorLocaleOptions,\n DetectorMode,\n DetectorResult,\n DetectorSource,\n DetectorWordCounterOptions,\n} from \"./types\";\n\nexport type {\n DetectorContentGateMode,\n DetectorContentGateOptions,\n DetectorCountSections,\n DetectorCountSectionsOptions,\n DetectorCountResult,\n DetectorLocaleOptions,\n DetectorMode,\n DetectorResult,\n DetectorRuntimeOptions,\n DetectorSource,\n DetectorWordCounterOptions,\n} from \"./types\";\nexport type {\n DetectorInspectChunk,\n DetectorInspectDecision,\n DetectorInspectEngine,\n DetectorInspectEngineRaw,\n DetectorInspectEngineResult,\n DetectorInspectInput,\n DetectorInspectInputOptions,\n DetectorInspectInputSourceType,\n DetectorInspectKind,\n DetectorInspectOptions,\n DetectorInspectPipelineResult,\n DetectorInspectResult,\n DetectorInspectSample,\n DetectorInspectSchemaVersion,\n DetectorInspectView,\n DetectorInspectWindow,\n} from \"./inspect-types\";\nexport type {\n DetectorDebugContext,\n DetectorDebugSummary,\n DetectorDebugVerbosity,\n DetectorEvidenceConfig,\n DetectorFallbackReason,\n} from \"./debug\";\n\nexport const DETECTOR_MODES: DetectorMode[] = [\"regex\", \"wasm\"];\nexport const DEFAULT_DETECTOR_MODE: DetectorMode = \"regex\";\n\nexport function resolveDetectorMode(mode?: DetectorMode): DetectorMode {\n return mode ?? DEFAULT_DETECTOR_MODE;\n}\n\nexport function assertDetectorModeImplemented(mode?: DetectorMode): void {\n void mode;\n}\n\nexport async function segmentTextByLocaleWithDetector(\n text: string,\n options: DetectorLocaleOptions = {},\n): Promise<LocaleChunk[]> {\n const mode = resolveDetectorMode(options.detector);\n if (mode === \"wasm\") {\n return segmentTextByLocaleWithWasmDetector(text, options);\n }\n return segmentTextByLocaleWithRegexDetector(text, options);\n}\n\nexport async function wordCounterWithDetector(\n text: string,\n options: DetectorWordCounterOptions = {},\n) {\n const mode = resolveDetectorMode(options.detector);\n if (mode === \"wasm\") {\n return wordCounterWithWasmDetector(text, options);\n }\n return wordCounterWithRegexDetector(text, options);\n}\n\nexport async function countSectionsWithDetector(\n input: string,\n section: SectionMode,\n options: DetectorCountSectionsOptions = {},\n) {\n const mode = resolveDetectorMode(options.detector);\n if (mode === \"wasm\") {\n return countSectionsWithWasmDetector(input, section, options);\n }\n return countSectionsWithRegexDetector(input, section, options);\n}\n\nexport const DETECTOR_SOURCES: DetectorSource[] = [\"script\", \"hint\", \"wasm\"];\nexport const DEFAULT_DETECTOR_RESULT_SOURCE: DetectorSource = \"script\";\nexport { WASM_DETECTOR_RUNTIME_UNAVAILABLE_MESSAGE };\nexport {\n createDetectorDebugSummary,\n inspectTextWithDetector,\n inspectTextWithRegexDetector,\n inspectTextWithWasmDetector,\n mergeDetectorDebugSummaries,\n};\n\nexport function createDetectorResult(\n tag: string,\n source: DetectorSource = DEFAULT_DETECTOR_RESULT_SOURCE,\n confidence?: number,\n reliable?: boolean,\n): DetectorResult {\n return {\n tag,\n source,\n ...(confidence === undefined ? {} : { confidence }),\n ...(reliable === undefined ? {} : { reliable }),\n };\n}\n","import { extname, relative, sep } from \"node:path\";\n\nexport type DirectoryExtensionFilter = {\n includeExtensions: Set<string>;\n excludeExtensions: Set<string>;\n effectiveIncludeExtensions: Set<string>;\n};\n\nexport type DirectoryRegexFilter = {\n sourcePattern: string | undefined;\n regex: RegExp | undefined;\n};\n\nexport const DEFAULT_INCLUDE_EXTENSIONS = Object.freeze([\n \".md\",\n \".markdown\",\n \".mdx\",\n \".mdc\",\n \".txt\",\n]);\n\nexport function collectExtensionOption(value: string, previous: string[] = []): string[] {\n return [...previous, value];\n}\n\nexport function normalizeExtensionToken(value: string): string | null {\n const trimmed = value.trim().toLowerCase();\n if (!trimmed) {\n return null;\n }\n\n const normalized = trimmed.startsWith(\".\") ? trimmed : `.${trimmed}`;\n if (normalized === \".\") {\n return null;\n }\n\n return normalized;\n}\n\nfunction parseExtensionValues(values: string[] | undefined): Set<string> {\n const parsed = new Set<string>();\n if (!values || values.length === 0) {\n return parsed;\n }\n\n for (const value of values) {\n for (const token of value.split(\",\")) {\n const normalized = normalizeExtensionToken(token);\n if (!normalized) {\n continue;\n }\n parsed.add(normalized);\n }\n }\n\n return parsed;\n}\n\nexport function buildDirectoryExtensionFilter(\n includeValues: string[] | undefined,\n excludeValues: string[] | undefined,\n): DirectoryExtensionFilter {\n const includeFromFlags = parseExtensionValues(includeValues);\n const excludeExtensions = parseExtensionValues(excludeValues);\n\n const includeExtensions =\n includeFromFlags.size > 0 ? includeFromFlags : new Set(DEFAULT_INCLUDE_EXTENSIONS);\n\n const effectiveIncludeExtensions = new Set<string>();\n for (const extension of includeExtensions) {\n if (excludeExtensions.has(extension)) {\n continue;\n }\n effectiveIncludeExtensions.add(extension);\n }\n\n return {\n includeExtensions,\n excludeExtensions,\n effectiveIncludeExtensions,\n };\n}\n\nexport function shouldIncludeFromDirectory(\n filePath: string,\n filter: DirectoryExtensionFilter,\n): boolean {\n const extension = extname(filePath).toLowerCase();\n return filter.effectiveIncludeExtensions.has(extension);\n}\n\nexport function buildDirectoryRegexFilter(pattern: string | undefined): DirectoryRegexFilter {\n if (pattern === undefined) {\n return { sourcePattern: undefined, regex: undefined };\n }\n\n if (pattern.trim().length === 0) {\n return { sourcePattern: pattern, regex: undefined };\n }\n\n try {\n return { sourcePattern: pattern, regex: new RegExp(pattern) };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Invalid --regex pattern: ${message}`);\n }\n}\n\nexport function toDirectoryRelativePath(rootPath: string, filePath: string): string {\n const relativePath = relative(rootPath, filePath);\n if (sep === \"/\") {\n return relativePath;\n }\n return relativePath.split(sep).join(\"/\");\n}\n\nexport function shouldIncludeFromDirectoryRegex(\n relativePath: string,\n filter: DirectoryRegexFilter,\n): boolean {\n if (!filter.regex) {\n return true;\n }\n\n return filter.regex.test(relativePath);\n}\n","import { readFile } from \"node:fs/promises\";\nimport type { BatchFileInput, BatchSkip } from \"../types\";\n\nexport function isProbablyBinary(buffer: Buffer): boolean {\n if (buffer.length === 0) {\n return false;\n }\n\n const sampleSize = Math.min(buffer.length, 1024);\n let suspicious = 0;\n\n for (let index = 0; index < sampleSize; index += 1) {\n const byte = buffer[index] ?? 0;\n\n if (byte === 0) {\n return true;\n }\n\n if (byte === 9 || byte === 10 || byte === 13) {\n continue;\n }\n\n if (byte >= 32 && byte <= 126) {\n continue;\n }\n\n if (byte >= 128) {\n continue;\n }\n\n suspicious += 1;\n }\n\n return suspicious / sampleSize > 0.3;\n}\n\nexport async function loadBatchInputs(\n filePaths: string[],\n): Promise<{ files: BatchFileInput[]; skipped: BatchSkip[] }> {\n const files: BatchFileInput[] = [];\n const skipped: BatchSkip[] = [];\n\n for (const filePath of filePaths) {\n let buffer: Buffer;\n try {\n buffer = await readFile(filePath);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n skipped.push({ path: filePath, reason: `not readable: ${message}` });\n continue;\n }\n\n if (isProbablyBinary(buffer)) {\n skipped.push({ path: filePath, reason: \"binary file\" });\n continue;\n }\n\n files.push({\n path: filePath,\n content: buffer.toString(\"utf8\"),\n });\n }\n\n return { files, skipped };\n}\n","import type { DebugChannel } from \"../debug/channel\";\nimport type { PathResolveDebugStats } from \"./resolve-types\";\n\nconst NOOP_DEBUG_CHANNEL = {\n enabled: false,\n verbosity: \"compact\",\n emit() {\n return;\n },\n close: async () => {\n return;\n },\n} satisfies DebugChannel;\n\nexport function resolvePathDebugChannel(debug?: DebugChannel): DebugChannel {\n return debug ?? NOOP_DEBUG_CHANNEL;\n}\n\nexport function createPathResolveDebugStats(): PathResolveDebugStats {\n return {\n dedupeAccepted: 0,\n dedupeDuplicates: 0,\n filterExcluded: 0,\n regexExcluded: 0,\n directoryIncluded: 0,\n };\n}\n\nexport function emitPathResolveSummaries(\n debug: DebugChannel,\n stats: PathResolveDebugStats,\n files: number,\n skipped: number,\n): void {\n debug.emit(\"path.resolve.filter.summary\", {\n excluded: stats.filterExcluded + stats.regexExcluded,\n extensionExcluded: stats.filterExcluded,\n regexExcluded: stats.regexExcluded,\n included: stats.directoryIncluded,\n });\n debug.emit(\"path.resolve.dedupe.summary\", {\n accepted: stats.dedupeAccepted,\n duplicates: stats.dedupeDuplicates,\n });\n debug.emit(\"path.resolve.complete\", {\n files,\n skipped,\n ordering: \"absolute-path-ascending\",\n });\n}\n","import { type Dirent } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { resolve as resolvePath } from \"node:path\";\nimport { appendAll } from \"../../utils/append-all\";\nimport type { DebugChannel } from \"../debug/channel\";\nimport type { BatchResolvedSkip } from \"../types\";\nimport {\n shouldIncludeFromDirectory,\n shouldIncludeFromDirectoryRegex,\n toDirectoryRelativePath,\n} from \"./filter\";\nimport type { ExpandDirectoryOptions, PathResolveDebugStats } from \"./resolve-types\";\n\nexport async function expandDirectory(\n { rootPath, directoryPath, recursive, extensionFilter, regexFilter }: ExpandDirectoryOptions,\n skipped: BatchResolvedSkip[],\n recordRegexExcluded: (filePath: string) => boolean,\n debug: DebugChannel,\n stats: PathResolveDebugStats,\n): Promise<string[]> {\n let entries: Dirent[];\n try {\n entries = await readdir(directoryPath, { withFileTypes: true, encoding: \"utf8\" });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n skipped.push({\n path: directoryPath,\n reason: `directory read failed: ${message}`,\n source: \"directory\",\n });\n debug.emit(\"path.resolve.expand.read_failed\", {\n directory: directoryPath,\n reason: `directory read failed: ${message}`,\n });\n return [];\n }\n\n const sortedEntries = entries.slice().sort((left, right) => left.name.localeCompare(right.name));\n const files: string[] = [];\n debug.emit(\"path.resolve.expand.start\", {\n directory: directoryPath,\n entries: sortedEntries.length,\n recursive,\n });\n\n for (const entry of sortedEntries) {\n const entryPath = resolvePath(directoryPath, entry.name);\n\n if (entry.isFile()) {\n if (!shouldIncludeFromDirectory(entryPath, extensionFilter)) {\n skipped.push({ path: entryPath, reason: \"extension excluded\", source: \"directory\" });\n debug.emit(\n \"path.resolve.filter.excluded\",\n {\n path: entryPath,\n reason: \"extension excluded\",\n },\n { verbosity: \"verbose\" },\n );\n stats.filterExcluded += 1;\n continue;\n }\n\n const relativePath = toDirectoryRelativePath(rootPath, entryPath);\n if (!shouldIncludeFromDirectoryRegex(relativePath, regexFilter)) {\n if (recordRegexExcluded(entryPath)) {\n debug.emit(\n \"path.resolve.regex.excluded\",\n {\n path: entryPath,\n relativePath,\n pattern: regexFilter.sourcePattern,\n reason: \"regex excluded\",\n },\n { verbosity: \"verbose\" },\n );\n stats.regexExcluded += 1;\n }\n continue;\n }\n\n files.push(entryPath);\n stats.directoryIncluded += 1;\n debug.emit(\n \"path.resolve.expand.include\",\n {\n path: entryPath,\n source: \"directory\",\n },\n { verbosity: \"verbose\" },\n );\n continue;\n }\n\n if (!entry.isDirectory() || !recursive) {\n continue;\n }\n\n const nestedFiles = await expandDirectory(\n {\n rootPath,\n directoryPath: entryPath,\n recursive,\n extensionFilter,\n regexFilter,\n },\n skipped,\n recordRegexExcluded,\n debug,\n stats,\n );\n appendAll(files, nestedFiles);\n }\n\n debug.emit(\"path.resolve.expand.complete\", {\n directory: directoryPath,\n files: files.length,\n });\n\n return files;\n}\n","import { stat } from \"node:fs/promises\";\nimport { resolve as resolvePath } from \"node:path\";\nimport type { BatchResolvedFile, BatchResolvedSkip, BatchSkip } from \"../types\";\nimport {\n buildDirectoryRegexFilter,\n buildDirectoryExtensionFilter,\n type DirectoryRegexFilter,\n} from \"./filter\";\nimport {\n createPathResolveDebugStats,\n emitPathResolveSummaries,\n resolvePathDebugChannel,\n} from \"./resolve-debug\";\nimport { expandDirectory } from \"./resolve-directory\";\nimport type { PathResolveDebugStats, ResolveBatchFilePathOptions } from \"./resolve-types\";\n\nexport async function resolveBatchFileEntries(\n pathInputs: string[],\n options: ResolveBatchFilePathOptions,\n): Promise<{ files: BatchResolvedFile[]; skipped: BatchResolvedSkip[] }> {\n const skipped: BatchResolvedSkip[] = [];\n const regexExcludedPaths = new Set<string>();\n const resolvedFiles = new Map<string, BatchResolvedFile>();\n const stats: PathResolveDebugStats = createPathResolveDebugStats();\n const extensionFilter =\n options.extensionFilter ?? buildDirectoryExtensionFilter(undefined, undefined);\n let regexFilter: DirectoryRegexFilter | undefined;\n const debug = resolvePathDebugChannel(options.debug);\n\n debug.emit(\"path.resolve.inputs\", {\n inputs: pathInputs.length,\n pathMode: options.pathMode,\n recursive: options.recursive,\n hasRegex: Boolean(options.directoryRegexPattern),\n });\n\n const addResolvedFile = (\n filePath: string,\n details: { source: \"direct\" | \"directory\"; input: string },\n ): void => {\n regexExcludedPaths.delete(filePath);\n\n const existing = resolvedFiles.get(filePath);\n if (existing) {\n if (existing.source === \"directory\" && details.source === \"direct\") {\n resolvedFiles.set(filePath, {\n path: filePath,\n source: \"direct\",\n });\n }\n stats.dedupeDuplicates += 1;\n debug.emit(\n \"path.resolve.dedupe.duplicate\",\n {\n path: filePath,\n source: details.source,\n input: details.input,\n },\n { verbosity: \"verbose\" },\n );\n return;\n }\n\n resolvedFiles.set(filePath, {\n path: filePath,\n source: details.source,\n });\n stats.dedupeAccepted += 1;\n debug.emit(\n \"path.resolve.dedupe.accept\",\n {\n path: filePath,\n source: details.source,\n input: details.input,\n },\n { verbosity: \"verbose\" },\n );\n };\n\n const getRegexFilter = (): DirectoryRegexFilter => {\n if (!regexFilter) {\n regexFilter = buildDirectoryRegexFilter(options.directoryRegexPattern);\n }\n return regexFilter;\n };\n\n const recordRegexExcluded = (filePath: string): boolean => {\n if (resolvedFiles.has(filePath)) {\n return false;\n }\n\n regexExcludedPaths.add(filePath);\n return true;\n };\n\n for (const rawPath of pathInputs) {\n const targetPath = resolvePath(rawPath);\n debug.emit(\"path.resolve.input\", {\n rawPath,\n resolvedPath: targetPath,\n });\n let metadata: Awaited<ReturnType<typeof stat>>;\n\n try {\n metadata = await stat(targetPath);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n skipped.push({ path: targetPath, reason: `not readable: ${message}`, source: \"direct\" });\n debug.emit(\"path.resolve.skip\", {\n path: targetPath,\n reason: `not readable: ${message}`,\n });\n continue;\n }\n\n if (metadata.isDirectory() && options.pathMode === \"auto\") {\n const effectiveRegexFilter = getRegexFilter();\n debug.emit(\"path.resolve.root.expand\", {\n root: targetPath,\n recursive: options.recursive,\n regex: effectiveRegexFilter.sourcePattern ?? null,\n });\n const files = await expandDirectory(\n {\n rootPath: targetPath,\n directoryPath: targetPath,\n recursive: options.recursive,\n extensionFilter,\n regexFilter: effectiveRegexFilter,\n },\n skipped,\n recordRegexExcluded,\n debug,\n stats,\n );\n for (const file of files) {\n addResolvedFile(file, { source: \"directory\", input: targetPath });\n }\n continue;\n }\n\n if (!metadata.isFile()) {\n skipped.push({ path: targetPath, reason: \"not a regular file\", source: \"direct\" });\n debug.emit(\"path.resolve.skip\", {\n path: targetPath,\n reason: \"not a regular file\",\n });\n continue;\n }\n\n addResolvedFile(targetPath, { source: \"direct\", input: targetPath });\n }\n\n for (const path of regexExcludedPaths) {\n skipped.push({ path, reason: \"regex excluded\", source: \"directory\" });\n }\n\n const files = [...resolvedFiles.values()].sort((left, right) =>\n left.path.localeCompare(right.path),\n );\n emitPathResolveSummaries(debug, stats, files.length, skipped.length);\n\n return { files, skipped };\n}\n\nexport async function resolveBatchFilePaths(\n pathInputs: string[],\n options: ResolveBatchFilePathOptions,\n): Promise<{ files: string[]; skipped: BatchSkip[] }> {\n const resolved = await resolveBatchFileEntries(pathInputs, options);\n return {\n files: resolved.files.map((file) => file.path),\n skipped: resolved.skipped.map(({ path, reason }) => ({ path, reason })),\n };\n}\n","import { readFileSync } from \"node:fs\";\nimport { requiresNonWordCollection, requiresWhitespaceCollection } from \"../total-of\";\nimport type { BatchScope } from \"../types\";\nimport type { LatinHintRule } from \"../../wc\";\nimport type { CliActionOptions, ResolvedCountRunOptions } from \"./types\";\n\nexport function hasPathInput(pathValues: string[] | undefined): pathValues is string[] {\n return Array.isArray(pathValues) && pathValues.length > 0;\n}\n\nfunction countLongOptionOccurrences(argv: string[], optionName: string): number {\n let count = 0;\n for (let index = 2; index < argv.length; index += 1) {\n const token = argv[index];\n if (!token) {\n continue;\n }\n if (token === \"--\") {\n break;\n }\n\n if (token === optionName) {\n count += 1;\n // Consume the next token as this option's value so literal values like\n // \"--regex=foo\" are not misread as a second option occurrence.\n index += 1;\n continue;\n }\n\n if (token.startsWith(`${optionName}=`)) {\n count += 1;\n continue;\n }\n }\n\n return count;\n}\n\nexport function validateSingleRegexOptionUsage(argv: string[]): void {\n if (countLongOptionOccurrences(argv, \"--regex\") > 1) {\n throw new Error(\"`--regex` can only be provided once.\");\n }\n}\n\nexport function validateStandalonePrintJobsLimitUsage(argv: string[]): void {\n const tokens = argv.slice(2).filter((token) => token.length > 0);\n if (tokens.length !== 1 || tokens[0] !== \"--print-jobs-limit\") {\n throw new Error(\"`--print-jobs-limit` must be used alone.\");\n }\n}\n\nexport function resolveBatchScope(argv: string[]): BatchScope {\n let scope: BatchScope = \"merged\";\n for (const token of argv) {\n if (token === \"--merged\") {\n scope = \"merged\";\n continue;\n }\n\n if (token === \"--per-file\") {\n scope = \"per-file\";\n }\n }\n\n return scope;\n}\n\nexport function resolveDebugReportPathOption(\n rawValue: string | boolean | undefined,\n): string | undefined {\n if (rawValue === undefined || rawValue === false) {\n return undefined;\n }\n\n if (typeof rawValue === \"string\") {\n return rawValue;\n }\n\n return undefined;\n}\n\nexport function parseInlineLatinHintRule(value: string): LatinHintRule {\n const separatorIndex = value.indexOf(\"=\");\n if (separatorIndex <= 0) {\n throw new Error(\"`--latin-hint` must use `<tag>=<pattern>` format.\");\n }\n\n const tag = value.slice(0, separatorIndex).trim();\n const pattern = value.slice(separatorIndex + 1);\n\n if (!tag) {\n throw new Error(\"`--latin-hint` tag must be non-empty.\");\n }\n\n if (!pattern) {\n throw new Error(\"`--latin-hint` pattern must be non-empty.\");\n }\n\n return { tag, pattern };\n}\n\nfunction parseLatinHintsFileRule(value: unknown, index: number, sourcePath: string): LatinHintRule {\n if (typeof value !== \"object\" || value === null) {\n throw new Error(`Invalid Latin hint rule at ${sourcePath}#${index}: rule must be an object.`);\n }\n\n const tag = \"tag\" in value ? value.tag : undefined;\n const pattern = \"pattern\" in value ? value.pattern : undefined;\n const priority = \"priority\" in value ? value.priority : undefined;\n\n if (typeof tag !== \"string\" || tag.trim().length === 0) {\n throw new Error(\n `Invalid Latin hint rule at ${sourcePath}#${index}: tag must be a non-empty string.`,\n );\n }\n\n if (typeof pattern !== \"string\") {\n throw new Error(`Invalid Latin hint rule at ${sourcePath}#${index}: pattern must be a string.`);\n }\n\n if (priority !== undefined && (typeof priority !== \"number\" || !Number.isFinite(priority))) {\n throw new Error(\n `Invalid Latin hint rule at ${sourcePath}#${index}: priority must be a finite number.`,\n );\n }\n\n return {\n tag,\n pattern,\n ...(priority !== undefined ? { priority } : {}),\n };\n}\n\nfunction parseLatinHintsFile(path: string): LatinHintRule[] {\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to read Latin hint file (${path}): ${message}`);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Invalid JSON in Latin hint file (${path}): ${message}`);\n }\n\n if (!Array.isArray(parsed)) {\n throw new Error(`Latin hint file (${path}) must contain a JSON array.`);\n }\n\n return parsed.map((rule, index) => parseLatinHintsFileRule(rule, index, path));\n}\n\nfunction resolveLatinHintRules(options: CliActionOptions): LatinHintRule[] | undefined {\n const inlineRules = (options.latinHint ?? []).map((value) => parseInlineLatinHintRule(value));\n const fileRules =\n typeof options.latinHintsFile === \"string\" && options.latinHintsFile.length > 0\n ? parseLatinHintsFile(options.latinHintsFile)\n : [];\n\n const mergedRules = [...inlineRules, ...fileRules];\n if (mergedRules.length === 0) {\n return undefined;\n }\n\n return mergedRules;\n}\n\nexport function resolveCountRunOptions(options: CliActionOptions): ResolvedCountRunOptions {\n const useSection = options.section !== \"all\";\n const detectorMode = options.detector ?? \"regex\";\n const totalOfParts = options.totalOf;\n const requestedNonWords = Boolean(options.nonWords || options.includeWhitespace || options.misc);\n const collectNonWordsForOverride = requiresNonWordCollection(totalOfParts);\n const collectWhitespaceForOverride = requiresWhitespaceCollection(totalOfParts);\n const enableNonWords = Boolean(\n options.nonWords || options.includeWhitespace || options.misc || collectNonWordsForOverride,\n );\n const enableWhitespace = Boolean(\n options.includeWhitespace || options.misc || collectWhitespaceForOverride,\n );\n const shouldNormalizeBaseOutput = !requestedNonWords && enableNonWords;\n\n return {\n useSection,\n detectorMode,\n totalOfParts,\n requestedNonWords,\n shouldNormalizeBaseOutput,\n wcOptions: {\n detector: detectorMode,\n contentGate:\n options.contentGate === undefined\n ? undefined\n : {\n mode: options.contentGate,\n },\n mode: options.mode,\n latinLanguageHint: options.latinLanguage,\n latinTagHint: options.latinTag,\n latinLocaleHint: options.latinLocale,\n latinHintRules: resolveLatinHintRules(options),\n useDefaultLatinHints: options.defaultLatinHints !== false,\n hanLanguageHint: options.hanLanguage,\n hanTagHint: options.hanTag,\n nonWords: enableNonWords,\n includeWhitespace: enableWhitespace,\n },\n };\n}\n\nexport function formatInputReadError(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n return `Failed to read input: ${message}`;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { parseMarkdown } from \"../../markdown\";\nimport { buildDirectoryExtensionFilter } from \"../path/filter\";\nimport { isProbablyBinary } from \"../path/load\";\nimport { resolveBatchFileEntries } from \"../path/resolve\";\nimport { formatInputReadError } from \"../runtime/options\";\nimport type { BatchSkip, PathMode } from \"../types\";\nimport type { InspectLoadedPathInput, InspectSectionMode, InspectSingleInput } from \"./types\";\n\nexport function selectInspectText(input: string, section: InspectSectionMode): string {\n if (section === \"all\") {\n return input;\n }\n\n const parsed = parseMarkdown(input);\n if (section === \"frontmatter\") {\n return parsed.frontmatter ?? \"\";\n }\n\n return parsed.content;\n}\n\nexport async function loadSingleInspectInput(\n path: string | undefined,\n textTokens: string[],\n section: InspectSectionMode,\n detectBinary = true,\n): Promise<InspectSingleInput> {\n if (path) {\n try {\n const buffer = await readFile(path);\n if (detectBinary && isProbablyBinary(buffer)) {\n throw new Error(\"binary file\");\n }\n return {\n text: selectInspectText(buffer.toString(\"utf8\"), section),\n sourceType: \"path\",\n path,\n };\n } catch (error) {\n if (error instanceof Error && error.message === \"binary file\") {\n throw error;\n }\n throw new Error(formatInputReadError(error));\n }\n }\n\n return {\n text: selectInspectText(textTokens.join(\" \"), section),\n sourceType: \"inline\",\n };\n}\n\nexport async function loadInspectBatchInputs(\n pathInputs: string[],\n options: {\n pathMode: PathMode;\n pathDetectBinary: boolean;\n recursive: boolean;\n includeExt: string[];\n excludeExt: string[];\n regex?: string;\n },\n): Promise<{\n files: InspectLoadedPathInput[];\n skipped: BatchSkip[];\n failures: BatchSkip[];\n}> {\n const resolved = await resolveBatchFileEntries(pathInputs, {\n pathMode: options.pathMode,\n recursive: options.recursive,\n extensionFilter: buildDirectoryExtensionFilter(options.includeExt, options.excludeExt),\n ...(options.regex !== undefined ? { directoryRegexPattern: options.regex } : {}),\n });\n\n const skipped: BatchSkip[] = [];\n const failures: BatchSkip[] = [];\n for (const skip of resolved.skipped) {\n if (skip.source === \"direct\") {\n failures.push({ path: skip.path, reason: skip.reason });\n continue;\n }\n skipped.push({ path: skip.path, reason: skip.reason });\n }\n\n const files: InspectLoadedPathInput[] = [];\n for (const entry of resolved.files) {\n let buffer: Buffer;\n try {\n buffer = await readFile(entry.path);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (entry.source === \"direct\") {\n failures.push({ path: entry.path, reason: `not readable: ${message}` });\n } else {\n skipped.push({ path: entry.path, reason: `not readable: ${message}` });\n }\n continue;\n }\n\n if (options.pathDetectBinary && isProbablyBinary(buffer)) {\n if (entry.source === \"direct\") {\n failures.push({ path: entry.path, reason: \"binary file\" });\n } else {\n skipped.push({ path: entry.path, reason: \"binary file\" });\n }\n continue;\n }\n\n files.push({\n path: entry.path,\n source: entry.source,\n text: buffer.toString(\"utf8\"),\n });\n }\n\n skipped.sort((left, right) => left.path.localeCompare(right.path));\n failures.sort((left, right) => left.path.localeCompare(right.path));\n\n return { files, skipped, failures };\n}\n","import { createInspectPreview } from \"../../detector/inspect-helpers\";\nimport type { DetectorInspectResult } from \"../../detector/inspect-types\";\nimport type { InspectBatchJsonPayload } from \"./types\";\n\nexport function buildInspectStandardLines(\n result: DetectorInspectResult,\n options: { includeTitle?: boolean } = {},\n): string[] {\n const includeTitle = options.includeTitle !== false;\n const lines: string[] = [];\n\n if (includeTitle) {\n lines.push(\"Detector inspect\");\n lines.push(`View: ${result.view}`);\n lines.push(`Detector: ${result.detector}`);\n lines.push(\"\");\n }\n\n lines.push(\"Input\");\n lines.push(`Source: ${result.input.sourceType}`);\n if (result.input.path) {\n lines.push(`Path: ${result.input.path}`);\n }\n lines.push(`Text length: ${result.input.textLength}`);\n\n if (result.view === \"engine\") {\n const samplePreview = createInspectPreview(result.sample.text);\n const normalizedPreview = createInspectPreview(result.sample.normalizedText);\n\n lines.push(\"\");\n lines.push(\"Sample\");\n lines.push(`Text source: ${result.sample.textSource}`);\n lines.push(`Sample text preview: ${JSON.stringify(samplePreview.textPreview)}`);\n lines.push(`Sample text truncated: ${samplePreview.textPreviewTruncated}`);\n lines.push(`Normalized text preview: ${JSON.stringify(normalizedPreview.textPreview)}`);\n lines.push(`Normalized text truncated: ${normalizedPreview.textPreviewTruncated}`);\n if (result.sample.borrowedContext) {\n lines.push(`Borrowed context: ${JSON.stringify(result.sample.borrowedContext)}`);\n }\n if (result.routeTag) {\n lines.push(`Route tag: ${result.routeTag}`);\n }\n if (result.engine) {\n lines.push(\"\");\n lines.push(\"Engine\");\n lines.push(\n `Raw: ${result.engine.raw.lang}/${result.engine.raw.script} confidence=${result.engine.raw.confidence} reliable=${result.engine.raw.reliable}`,\n );\n if (result.engine.normalized) {\n lines.push(\n `Normalized: ${result.engine.normalized.lang}/${result.engine.normalized.script} confidence=${result.engine.normalized.confidence} reliable=${result.engine.normalized.reliable}`,\n );\n }\n lines.push(\n `Remap: raw=${result.engine.remapped.rawTag ?? \"null\"} normalized=${result.engine.remapped.normalizedTag ?? \"null\"}`,\n );\n } else if (result.decision?.kind === \"empty\") {\n lines.push(\"\");\n lines.push(`Decision: ${result.decision.notes.join(\" \")}`);\n }\n return lines;\n }\n\n lines.push(\"\");\n lines.push(\"Chunks\");\n if (result.chunks.length === 0) {\n lines.push(\"(none)\");\n } else {\n for (const chunk of result.chunks) {\n const source = chunk.source ? ` | ${chunk.source}` : \"\";\n const reason = chunk.reason ? ` | ${chunk.reason}` : \"\";\n lines.push(\n `[${chunk.index}] ${chunk.locale}${source}${reason} | ${JSON.stringify(chunk.textPreview)}`,\n );\n }\n }\n\n if (result.windows) {\n for (const window of result.windows) {\n lines.push(\"\");\n lines.push(`Window ${window.windowIndex}`);\n lines.push(`Route: ${window.routeTag}`);\n lines.push(`Chunk range: ${window.chunkRange.start}-${window.chunkRange.end}`);\n lines.push(`Focus: ${JSON.stringify(window.focusTextPreview)}`);\n if (window.diagnosticSample.borrowedContext) {\n lines.push(`Borrowed context: ${JSON.stringify(window.diagnosticSample.borrowedContext)}`);\n }\n lines.push(`Sample: ${JSON.stringify(window.diagnosticSample.textPreview)}`);\n lines.push(\n `Normalized sample: ${JSON.stringify(window.diagnosticSample.normalizedTextPreview)}`,\n );\n lines.push(\n `Eligibility: ${window.eligibility.scriptChars}/${window.eligibility.minScriptChars} passed=${window.eligibility.passed}`,\n );\n lines.push(\n `Content gate: mode=${window.contentGate.mode} policy=${window.contentGate.policy} applied=${window.contentGate.applied} passed=${window.contentGate.passed}`,\n );\n lines.push(\n `Engine: ${window.engine.executed ? \"executed\" : `skipped (${window.engine.reason ?? \"unknown\"})`}`,\n );\n lines.push(\n `Decision: accepted=${window.decision.accepted} path=${window.decision.path ?? \"null\"} final=${window.decision.finalTag} fallback=${window.decision.fallbackReason ?? \"null\"}`,\n );\n }\n }\n\n if (result.decision && \"kind\" in result.decision) {\n lines.push(\"\");\n lines.push(`Decision: ${result.decision.kind}`);\n lines.push(result.decision.notes.join(\" \"));\n }\n\n lines.push(\"\");\n lines.push(\"Resolved\");\n if (result.resolvedChunks.length === 0) {\n lines.push(\"(none)\");\n return lines;\n }\n for (const chunk of result.resolvedChunks) {\n lines.push(`[${chunk.index}] ${chunk.locale} | ${JSON.stringify(chunk.textPreview)}`);\n }\n\n return lines;\n}\n\nexport function buildInspectBatchStandardLines(payload: InspectBatchJsonPayload): string[] {\n const lines: string[] = [\n \"Detector inspect batch\",\n `View: ${payload.view}`,\n `Detector: ${payload.detector}`,\n `Section: ${payload.section}`,\n `Requested inputs: ${payload.summary.requestedInputs}`,\n `Summary: ${payload.summary.succeeded} succeeded, ${payload.summary.skipped} skipped, ${payload.summary.failed} failed`,\n ];\n\n for (const file of payload.files) {\n lines.push(\"\");\n lines.push(`File: ${file.path}`);\n lines.push(...buildInspectStandardLines(file.result, { includeTitle: false }));\n }\n\n if (payload.skipped.length > 0) {\n lines.push(\"\");\n lines.push(\"Skipped\");\n for (const item of payload.skipped) {\n lines.push(`${item.path} | ${item.reason}`);\n }\n }\n\n if (payload.failures.length > 0) {\n lines.push(\"\");\n lines.push(\"Failures\");\n for (const item of payload.failures) {\n lines.push(`${item.path} | ${item.reason}`);\n }\n }\n\n return lines;\n}\n\nexport function printLines(lines: string[]): void {\n for (const line of lines) {\n console.log(line);\n }\n}\n","import { inspectTextWithDetector } from \"../../detector\";\nimport type { BatchSkip } from \"../types\";\nimport { selectInspectText } from \"./input\";\nimport { buildInspectBatchStandardLines, printLines } from \"./render\";\nimport type {\n InspectBatchJsonPayload,\n InspectLoadedPathInput,\n ParsedInspectInvocation,\n} from \"./types\";\n\nexport function buildInspectBatchJsonPayload(\n validated: ParsedInspectInvocation,\n files: Array<{ path: string; result: Awaited<ReturnType<typeof inspectTextWithDetector>> }>,\n skipped: BatchSkip[],\n failures: BatchSkip[],\n): InspectBatchJsonPayload {\n return {\n schemaVersion: 1,\n kind: \"detector-inspect-batch\",\n detector: validated.detector,\n view: validated.view,\n section: validated.section,\n summary: {\n requestedInputs: validated.paths.length,\n succeeded: files.length,\n skipped: skipped.length,\n failed: failures.length,\n },\n files,\n skipped,\n failures,\n };\n}\n\nexport async function runInspectBatch(\n validated: ParsedInspectInvocation,\n loaded: {\n files: InspectLoadedPathInput[];\n skipped: BatchSkip[];\n failures: BatchSkip[];\n },\n): Promise<void> {\n const batchFiles: Array<{\n path: string;\n result: Awaited<ReturnType<typeof inspectTextWithDetector>>;\n }> = [];\n for (const file of loaded.files) {\n const result = await inspectTextWithDetector(selectInspectText(file.text, validated.section), {\n detector: validated.detector,\n contentGate: {\n mode: validated.contentGateMode,\n },\n view: validated.view,\n input: {\n sourceType: \"path\",\n path: file.path,\n },\n });\n batchFiles.push({\n path: file.path,\n result,\n });\n }\n\n const payload = buildInspectBatchJsonPayload(\n validated,\n batchFiles,\n loaded.skipped,\n loaded.failures,\n );\n if (validated.format === \"json\") {\n console.log(JSON.stringify(payload, null, validated.pretty ? 2 : 0));\n } else {\n printLines(buildInspectBatchStandardLines(payload));\n }\n\n process.exitCode = payload.failures.length > 0 || payload.files.length === 0 ? 1 : 0;\n}\n","const INSPECT_HELP_LINES = [\n \"Usage: word-counter inspect [options] [text...]\",\n \"\",\n \"inspect detector behavior without count output\",\n \"\",\n \"Options:\",\n \" -d, --detector <mode> inspect detector mode (wasm, regex) (default: regex)\",\n \" --content-gate <mode> content gate mode (default, strict, loose, off) (default: default)\",\n \" --view <view> inspect view (pipeline, engine) (default: pipeline)\",\n \" -f, --format <format> inspect output format (standard, json) (default: standard)\",\n \" --pretty pretty print inspect JSON output\",\n \" --section <section> inspect section selector (all, frontmatter, content) (default: all)\",\n \" --path-mode <mode> path resolution mode for --path inputs (auto, manual) (default: auto)\",\n \" --recursive enable recursive directory traversal for --path directories\",\n \" --no-recursive disable recursive directory traversal for --path directories\",\n \" --include-ext <exts> comma-separated extensions to include during directory scanning\",\n \" --exclude-ext <exts> comma-separated extensions to exclude during directory scanning\",\n \" --regex <pattern> regex filter for directory-expanded paths\",\n \" -p, --path <path> inspect text from file or directory inputs\",\n \" -h, --help display help for command\",\n];\n\nexport function printInspectHelp(): void {\n for (const line of INSPECT_HELP_LINES) {\n console.log(line);\n }\n}\n","import type { DetectorInspectView } from \"../../detector/inspect-types\";\nimport type { DetectorContentGateMode } from \"../../detector\";\nimport type { PathMode } from \"../types\";\nimport type {\n InspectDetectorMode,\n InspectOutputFormat,\n InspectSectionMode,\n ValidInspectInvocation,\n} from \"./types\";\n\nfunction parseDetector(rawValue: string | undefined): InspectDetectorMode | null {\n if (rawValue === undefined) {\n return \"regex\";\n }\n if (rawValue === \"wasm\" || rawValue === \"regex\") {\n return rawValue;\n }\n return null;\n}\n\nfunction parseView(rawValue: string | undefined): DetectorInspectView | null {\n if (rawValue === undefined) {\n return \"pipeline\";\n }\n if (rawValue === \"pipeline\" || rawValue === \"engine\") {\n return rawValue;\n }\n return null;\n}\n\nfunction parseFormat(rawValue: string | undefined): InspectOutputFormat | null {\n if (rawValue === undefined) {\n return \"standard\";\n }\n if (rawValue === \"standard\" || rawValue === \"json\") {\n return rawValue;\n }\n return null;\n}\n\nfunction parseContentGateMode(rawValue: string | undefined): DetectorContentGateMode | null {\n if (rawValue === undefined) {\n return \"default\";\n }\n if (\n rawValue === \"default\" ||\n rawValue === \"strict\" ||\n rawValue === \"loose\" ||\n rawValue === \"off\"\n ) {\n return rawValue;\n }\n return null;\n}\n\nfunction parsePathMode(rawValue: string | undefined): PathMode | null {\n if (rawValue === undefined) {\n return \"auto\";\n }\n if (rawValue === \"auto\" || rawValue === \"manual\") {\n return rawValue;\n }\n return null;\n}\n\nfunction isSupportedInspectSectionMode(value: string): value is InspectSectionMode {\n return value === \"all\" || value === \"frontmatter\" || value === \"content\";\n}\n\nexport function validateInspectInvocation(argv: string[]): ValidInspectInvocation {\n const inspectIndex = argv.findIndex((token, index) => index >= 2 && token === \"inspect\");\n const tokens = inspectIndex >= 0 ? argv.slice(inspectIndex + 1) : [];\n let detector: InspectDetectorMode = \"regex\";\n let contentGateMode: DetectorContentGateMode = \"default\";\n let view: DetectorInspectView = \"pipeline\";\n let format: InspectOutputFormat = \"standard\";\n let pretty = false;\n let section: InspectSectionMode = \"all\";\n let pathMode: PathMode = \"auto\";\n let recursive = true;\n const paths: string[] = [];\n const includeExt: string[] = [];\n const excludeExt: string[] = [];\n let regex: string | undefined;\n const textTokens: string[] = [];\n const sources = {\n detector: false,\n contentGate: false,\n pathMode: false,\n recursive: false,\n includeExt: false,\n excludeExt: false,\n };\n let expects:\n | \"detector\"\n | \"view\"\n | \"contentGate\"\n | \"format\"\n | \"section\"\n | \"pathMode\"\n | \"path\"\n | \"includeExt\"\n | \"excludeExt\"\n | \"regex\"\n | null = null;\n let positionalMode = false;\n\n const consumeValue = (\n kind:\n | \"detector\"\n | \"view\"\n | \"contentGate\"\n | \"format\"\n | \"section\"\n | \"pathMode\"\n | \"path\"\n | \"includeExt\"\n | \"excludeExt\"\n | \"regex\",\n value: string,\n ): string | null => {\n if (kind === \"detector\") {\n const parsed = parseDetector(value);\n if (parsed === null) {\n return \"`--detector` must be `wasm` or `regex`.\";\n }\n detector = parsed;\n sources.detector = true;\n return null;\n }\n\n if (kind === \"view\") {\n const parsed = parseView(value);\n if (parsed === null) {\n return \"`--view` must be `pipeline` or `engine`.\";\n }\n view = parsed;\n return null;\n }\n\n if (kind === \"contentGate\") {\n const parsed = parseContentGateMode(value);\n if (parsed === null) {\n return \"`--content-gate` must be `default`, `strict`, `loose`, or `off`.\";\n }\n contentGateMode = parsed;\n sources.contentGate = true;\n return null;\n }\n\n if (kind === \"format\") {\n if (value === \"raw\") {\n return \"`inspect` does not support `--format raw`.\";\n }\n const parsed = parseFormat(value);\n if (parsed === null) {\n return \"`--format` must be `standard` or `json`.\";\n }\n format = parsed;\n return null;\n }\n\n if (kind === \"section\") {\n if (!isSupportedInspectSectionMode(value)) {\n return \"`inspect` supports `--section all`, `frontmatter`, or `content`.\";\n }\n section = value;\n return null;\n }\n\n if (kind === \"pathMode\") {\n const parsed = parsePathMode(value);\n if (parsed === null) {\n return \"`--path-mode` must be `auto` or `manual`.\";\n }\n pathMode = parsed;\n sources.pathMode = true;\n return null;\n }\n\n if (kind === \"path\") {\n paths.push(value);\n return null;\n }\n\n if (kind === \"includeExt\") {\n includeExt.push(value);\n sources.includeExt = true;\n return null;\n }\n\n if (kind === \"excludeExt\") {\n excludeExt.push(value);\n sources.excludeExt = true;\n return null;\n }\n\n if (regex !== undefined) {\n return \"`--regex` can only be provided once.\";\n }\n regex = value;\n return null;\n };\n\n for (const token of tokens) {\n if (token === \"-h\" || token === \"--help\") {\n return { ok: true, help: true };\n }\n\n if (expects) {\n const error = consumeValue(expects, token);\n if (error) {\n return { ok: false, message: error };\n }\n expects = null;\n continue;\n }\n\n if (positionalMode) {\n textTokens.push(token);\n continue;\n }\n\n if (token === \"--\") {\n positionalMode = true;\n continue;\n }\n\n if (token === \"--recursive\") {\n recursive = true;\n sources.recursive = true;\n continue;\n }\n\n if (token === \"--no-recursive\") {\n recursive = false;\n sources.recursive = true;\n continue;\n }\n\n if (token === \"--pretty\") {\n pretty = true;\n continue;\n }\n\n if (\n token === \"--detector\" ||\n token === \"-d\" ||\n token === \"--content-gate\" ||\n token === \"--view\" ||\n token === \"--format\" ||\n token === \"-f\" ||\n token === \"--section\" ||\n token === \"--path-mode\" ||\n token === \"--path\" ||\n token === \"-p\" ||\n token === \"--include-ext\" ||\n token === \"--exclude-ext\" ||\n token === \"--regex\"\n ) {\n expects =\n token === \"-p\"\n ? \"path\"\n : token === \"-d\"\n ? \"detector\"\n : token === \"--content-gate\"\n ? \"contentGate\"\n : token === \"-f\"\n ? \"format\"\n : token === \"--path-mode\"\n ? \"pathMode\"\n : token === \"--include-ext\"\n ? \"includeExt\"\n : token === \"--exclude-ext\"\n ? \"excludeExt\"\n : (token.slice(2) as\n | \"detector\"\n | \"view\"\n | \"format\"\n | \"section\"\n | \"path\"\n | \"regex\");\n continue;\n }\n\n if (\n token.startsWith(\"--detector=\") ||\n token.startsWith(\"--content-gate=\") ||\n token.startsWith(\"--view=\") ||\n token.startsWith(\"--format=\") ||\n token.startsWith(\"--section=\") ||\n token.startsWith(\"--path-mode=\") ||\n token.startsWith(\"--path=\") ||\n token.startsWith(\"--include-ext=\") ||\n token.startsWith(\"--exclude-ext=\") ||\n token.startsWith(\"--regex=\")\n ) {\n const separatorIndex = token.indexOf(\"=\");\n const optionName = token.slice(2, separatorIndex);\n const value = token.slice(separatorIndex + 1);\n if (value.length === 0) {\n return {\n ok: false,\n message: `\\`--${optionName}\\` requires a value.`,\n };\n }\n\n const normalizedOption =\n optionName === \"path-mode\"\n ? \"pathMode\"\n : optionName === \"include-ext\"\n ? \"includeExt\"\n : optionName === \"exclude-ext\"\n ? \"excludeExt\"\n : (optionName as\n | \"detector\"\n | \"content-gate\"\n | \"view\"\n | \"format\"\n | \"section\"\n | \"path\"\n | \"regex\");\n const normalizedNamedOption =\n normalizedOption === \"content-gate\" ? \"contentGate\" : normalizedOption;\n\n const error = consumeValue(\n normalizedNamedOption as\n | \"detector\"\n | \"contentGate\"\n | \"view\"\n | \"format\"\n | \"section\"\n | \"path\"\n | \"regex\"\n | \"pathMode\"\n | \"includeExt\"\n | \"excludeExt\",\n value,\n );\n if (error) {\n return { ok: false, message: error };\n }\n continue;\n }\n\n if (token.startsWith(\"-\")) {\n return {\n ok: false,\n message: `\\`${token}\\` is not supported by \\`inspect\\`.`,\n };\n }\n\n textTokens.push(token);\n }\n\n if (expects) {\n const optionName =\n expects === \"pathMode\"\n ? \"path-mode\"\n : expects === \"contentGate\"\n ? \"content-gate\"\n : expects === \"includeExt\"\n ? \"include-ext\"\n : expects === \"excludeExt\"\n ? \"exclude-ext\"\n : expects;\n return {\n ok: false,\n message: `\\`--${optionName}\\` requires a value.`,\n };\n }\n\n if (paths.length > 0 && textTokens.length > 0) {\n return {\n ok: false,\n message: \"`inspect` accepts either positional text or --path inputs, not both.\",\n };\n }\n\n if (paths.length === 0 && textTokens.length === 0) {\n return {\n ok: false,\n message: \"No inspect input provided. Pass text or use --path.\",\n };\n }\n\n return {\n ok: true,\n detector,\n contentGateMode,\n view,\n format,\n pretty,\n section,\n pathMode,\n pathDetectBinary: true,\n recursive,\n includeExt,\n excludeExt,\n ...(regex !== undefined ? { regex } : {}),\n paths,\n textTokens,\n sources,\n };\n}\n","import { inspectTextWithDetector } from \"../../detector\";\nimport { buildInspectStandardLines, printLines } from \"./render\";\nimport type { InspectSingleInput, ParsedInspectInvocation } from \"./types\";\n\nexport async function runSingleInspect(\n validated: ParsedInspectInvocation,\n input: InspectSingleInput,\n): Promise<void> {\n const result = await inspectTextWithDetector(input.text, {\n detector: validated.detector,\n contentGate: {\n mode: validated.contentGateMode,\n },\n view: validated.view,\n input: {\n sourceType: input.sourceType,\n ...(input.path ? { path: input.path } : {}),\n },\n });\n\n if (validated.format === \"json\") {\n console.log(JSON.stringify(result, null, validated.pretty ? 2 : 0));\n process.exitCode = 0;\n return;\n }\n\n printLines(buildInspectStandardLines(result));\n process.exitCode = 0;\n}\n","import { applyConfigToInspectInvocation, resolveWordCounterConfig } from \"../config\";\nimport pc from \"picocolors\";\nimport { runInspectBatch } from \"./batch\";\nimport { printInspectHelp } from \"./help\";\nimport { loadInspectBatchInputs, loadSingleInspectInput, selectInspectText } from \"./input\";\nimport { validateInspectInvocation } from \"./parse\";\nimport { runSingleInspect } from \"./single\";\nimport type { ExecuteInspectCommandOptions } from \"./types\";\n\nexport function isExplicitInspectInvocation(argv: string[]): boolean {\n return argv[2] === \"inspect\";\n}\n\nfunction emitConfigNotes(notes: string[]): void {\n for (const note of notes) {\n const warningLine = note.startsWith(\"Warning:\") ? note : `Warning: ${note}`;\n console.error(pc.yellow(warningLine));\n }\n}\n\nexport async function executeInspectCommand({\n argv,\n runtime,\n}: ExecuteInspectCommandOptions): Promise<void> {\n const parsed = validateInspectInvocation(argv);\n if (!parsed.ok) {\n console.error(pc.red(`error: ${parsed.message}`));\n process.exitCode = 1;\n return;\n }\n\n if (parsed.help) {\n printInspectHelp();\n process.exitCode = 0;\n return;\n }\n\n let validated = parsed;\n\n try {\n const resolvedConfig = await resolveWordCounterConfig({\n env: runtime?.env,\n cwd: runtime?.cwd,\n });\n validated = applyConfigToInspectInvocation(validated, resolvedConfig.config);\n emitConfigNotes(resolvedConfig.notes);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(pc.red(`error: ${message}`));\n process.exitCode = 1;\n return;\n }\n\n if (validated.view === \"engine\" && validated.detector === \"regex\") {\n console.error(pc.red(\"error: `--view engine` requires `--detector wasm`.\"));\n process.exitCode = 1;\n return;\n }\n\n try {\n if (validated.paths.length === 0) {\n const input = await loadSingleInspectInput(\n undefined,\n validated.textTokens,\n validated.section,\n );\n await runSingleInspect(validated, input);\n return;\n }\n\n const loaded = await loadInspectBatchInputs(validated.paths, {\n pathMode: validated.pathMode,\n pathDetectBinary: validated.pathDetectBinary,\n recursive: validated.recursive,\n includeExt: validated.includeExt,\n excludeExt: validated.excludeExt,\n ...(validated.regex !== undefined ? { regex: validated.regex } : {}),\n });\n\n const directSinglePath =\n validated.paths.length === 1 &&\n loaded.files.length === 1 &&\n loaded.skipped.length === 0 &&\n loaded.failures.length === 0 &&\n loaded.files[0]?.source === \"direct\";\n\n if (directSinglePath) {\n const file = loaded.files[0];\n if (!file) {\n throw new Error(\"Missing inspect file input.\");\n }\n await runSingleInspect(validated, {\n text: selectInspectText(file.text, validated.section),\n sourceType: \"path\",\n path: file.path,\n });\n return;\n }\n\n await runInspectBatch(validated, loaded);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(pc.red(`error: ${message}`));\n process.exitCode = 1;\n }\n}\n","import { Command, Option } from \"commander\";\nimport type { SectionMode } from \"../../markdown\";\nimport { collectExtensionOption } from \"../path/filter\";\nimport { parseTotalOfOption } from \"../total-of\";\nimport type { PathMode } from \"../types\";\nimport type { OutputFormat } from \"../runtime/types\";\nimport type { DetectorContentGateMode, DetectorMode } from \"../../detector\";\nimport type { WordCounterMode } from \"../../wc\";\n\nconst MODE_CHOICES: WordCounterMode[] = [\n \"chunk\",\n \"segments\",\n \"collector\",\n \"char\",\n \"char-collector\",\n];\nconst DETECTOR_CHOICES: DetectorMode[] = [\"regex\", \"wasm\"];\nconst CONTENT_GATE_CHOICES: DetectorContentGateMode[] = [\"default\", \"strict\", \"loose\", \"off\"];\nconst FORMAT_CHOICES: OutputFormat[] = [\"standard\", \"raw\", \"json\"];\nconst SECTION_CHOICES: SectionMode[] = [\n \"all\",\n \"split\",\n \"frontmatter\",\n \"content\",\n \"per-key\",\n \"split-per-key\",\n];\nconst PATH_MODE_CHOICES: PathMode[] = [\"auto\", \"manual\"];\n\nfunction collectPathValue(value: string, previous: string[] = []): string[] {\n return [...previous, value];\n}\n\nfunction collectLatinHintValue(value: string, previous: string[] = []): string[] {\n return [...previous, value];\n}\n\nfunction parseJobsOption(value: string): number {\n if (!/^\\d+$/.test(value)) {\n throw new Error(\"`--jobs` must be an integer >= 1.\");\n }\n\n const parsed = Number.parseInt(value, 10);\n if (!Number.isSafeInteger(parsed) || parsed < 1) {\n throw new Error(\"`--jobs` must be an integer >= 1.\");\n }\n\n return parsed;\n}\n\nexport function configureProgramOptions(\n program: Command,\n parseMode: (value: string) => WordCounterMode,\n): void {\n program\n .addOption(\n new Option(\"-m, --mode <mode>\", \"breakdown mode\")\n .choices(MODE_CHOICES)\n .argParser(parseMode)\n .default(\"chunk\"),\n )\n .addOption(\n new Option(\"-f, --format <format>\", \"output format\")\n .choices(FORMAT_CHOICES)\n .default(\"standard\"),\n )\n .addOption(\n new Option(\"--section <section>\", \"document section mode\")\n .choices(SECTION_CHOICES)\n .default(\"all\"),\n )\n .addOption(\n new Option(\"-d, --detector <mode>\", \"locale detector mode\")\n .choices(DETECTOR_CHOICES)\n .default(\"regex\"),\n )\n .addOption(\n new Option(\n \"--content-gate <mode>\",\n \"detector content gate policy mode (default, strict, loose, off)\",\n ).choices(CONTENT_GATE_CHOICES),\n )\n .addOption(\n new Option(\n \"--path-mode <mode>\",\n \"path resolution mode: auto (default) expands directories; manual treats --path values as literal files\",\n )\n .choices(PATH_MODE_CHOICES)\n .default(\"auto\"),\n )\n .option(\"--latin-language <language>\", \"hint a language tag for Latin script text\")\n .option(\"--latin-tag <tag>\", \"hint a BCP 47 tag for Latin script text\")\n .option(\"--latin-locale <locale>\", \"legacy alias of --latin-language\")\n .option(\n \"--latin-hint <tag>=<pattern>\",\n \"add a custom Latin hint rule (repeatable)\",\n collectLatinHintValue,\n [],\n )\n .option(\"--latin-hints-file <path>\", \"load custom Latin hint rules from a JSON file\")\n .option(\"--no-default-latin-hints\", \"disable built-in Latin hint rules\")\n .option(\"--han-language <language>\", \"hint a language tag for Han script text\")\n .option(\"--han-tag <tag>\", \"hint a BCP 47 tag for Han script text\")\n .option(\"--non-words\", \"collect emoji, symbols, and punctuation (excludes whitespace)\")\n .option(\n \"--include-whitespace\",\n \"include whitespace counts (implies --non-words; same as --misc)\",\n )\n .option(\"--misc\", \"collect non-words plus whitespace (alias for --include-whitespace)\")\n .option(\n \"--total-of <parts>\",\n \"override total composition (comma-separated): words,emoji,symbols,punctuation,whitespace\",\n parseTotalOfOption,\n )\n .option(\"--pretty\", \"pretty print JSON output\", false)\n .option(\"--debug\", \"enable debug diagnostics on stderr\")\n .option(\"--verbose\", \"emit verbose per-file debug diagnostics (requires --debug)\")\n .option(\n \"--detector-evidence\",\n \"emit per-window detector evidence on the debug stream (requires --debug and --detector wasm)\",\n )\n .option(\"--debug-report [path]\", \"write debug diagnostics to a report file\")\n .option(\"--debug-report-tee\", \"mirror debug diagnostics to both report file and stderr\")\n .option(\"--debug-tee\", \"alias of --debug-report-tee\")\n .option(\"--merged\", \"show merged aggregate output (default)\")\n .option(\"--per-file\", \"show per-file output plus merged summary\")\n .option(\n \"--jobs <n>\",\n \"batch jobs in --path mode (1=async main-thread, >1=worker load+count)\",\n parseJobsOption,\n 1,\n )\n .option(\"--print-jobs-limit\", \"print host jobs-limit JSON and exit (must be used alone)\")\n .option(\"--progress\", \"enable batch progress indicator\")\n .option(\"--no-progress\", \"disable batch progress indicator\")\n .option(\"--keep-progress\", \"keep final batch progress line visible in standard mode\")\n .option(\"--recursive\", \"enable recursive directory traversal\")\n .option(\"--no-recursive\", \"disable recursive directory traversal\")\n .option(\"--quiet-warnings\", \"suppress non-fatal warning diagnostics\")\n .option(\"--quiet-skips\", \"suppress debug skip output and per-file json skipped field\")\n .option(\n \"--include-ext <exts>\",\n \"comma-separated extensions to include during directory scanning\",\n collectExtensionOption,\n [],\n )\n .option(\n \"--exclude-ext <exts>\",\n \"comma-separated extensions to exclude during directory scanning\",\n collectExtensionOption,\n [],\n )\n .option(\n \"--regex <pattern>\",\n \"regex filter for directory-scanned paths (applies to --path directories only)\",\n )\n .option(\n \"-p, --path <path>\",\n \"read input from file or directory (directories expand in auto mode by default)\",\n collectPathValue,\n [],\n )\n .argument(\"[text...]\", \"text to count\")\n .showHelpAfterError();\n}\n","import { readFileSync } from \"node:fs\";\nimport { dirname, join, resolve as resolvePath } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport pc from \"picocolors\";\nimport { EMBEDDED_PACKAGE_VERSION } from \"./version-embedded\";\n\nfunction* candidateSearchRoots(): Generator<string> {\n yield dirname(fileURLToPath(import.meta.url));\n\n const argvPath = process.argv[1];\n if (typeof argvPath === \"string\" && argvPath.length > 0) {\n yield dirname(resolvePath(argvPath));\n }\n\n yield process.cwd();\n}\n\nfunction* walkUpDirectories(start: string, maxLevels: number): Generator<string> {\n let current = start;\n for (let depth = 0; depth < maxLevels; depth += 1) {\n yield current;\n const parent = dirname(current);\n if (parent === current) {\n break;\n }\n current = parent;\n }\n}\n\nfunction resolveVersionFromPath(start: string, maxLevels: number): string | null {\n for (const directory of walkUpDirectories(start, maxLevels)) {\n try {\n const raw = readFileSync(join(directory, \"package.json\"), \"utf8\");\n const data = JSON.parse(raw) as { version?: string };\n if (data.version) {\n return data.version;\n }\n } catch {\n // Try parent directories.\n }\n }\n return null;\n}\n\nfunction normalizeVersion(value: string | null | undefined): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n const trimmed = value.trim();\n if (!trimmed) {\n return null;\n }\n\n return trimmed;\n}\n\ntype ResolvePackageVersionOptions = {\n embeddedVersion?: string | null;\n candidateRoots?: string[];\n maxLevels?: number;\n resolveFromPath?: (start: string, maxLevels: number) => string | null;\n};\n\nexport function resolvePackageVersion(options: ResolvePackageVersionOptions = {}): string {\n const embeddedVersion = normalizeVersion(options.embeddedVersion ?? EMBEDDED_PACKAGE_VERSION);\n if (embeddedVersion) {\n return embeddedVersion;\n }\n\n const maxLevels = options.maxLevels ?? 8;\n const resolveFromPath = options.resolveFromPath ?? resolveVersionFromPath;\n const roots = options.candidateRoots ?? [...candidateSearchRoots()];\n const seen = new Set<string>();\n for (const root of roots) {\n if (seen.has(root)) {\n continue;\n }\n seen.add(root);\n const version = normalizeVersion(resolveFromPath(root, maxLevels));\n if (version) {\n return version;\n }\n }\n\n return \"0.0.0\";\n}\n\nexport function getFormattedVersionLabel(): string {\n const version = resolvePackageVersion();\n\n return pc.bgBlack(pc.bold(pc.italic(` word-counter ${pc.cyanBright(`ver.${version}`)} `)));\n}\n","import type { SectionedResult } from \"../../markdown\";\nimport type { WordCounterResult } from \"../../wc\";\n\nfunction stripCollectorSegmentsFromWordCounterResult(result: WordCounterResult): void {\n if (result.breakdown.mode !== \"collector\") {\n return;\n }\n\n for (const item of result.breakdown.items) {\n item.segments = [];\n }\n}\n\nfunction stripCollectorSegmentsFromSectionedResult(result: SectionedResult): void {\n for (const item of result.items) {\n stripCollectorSegmentsFromWordCounterResult(item.result);\n }\n}\n\nexport function compactCollectorSegmentsInCountResult(\n result: WordCounterResult | SectionedResult,\n): void {\n if (\"section\" in result) {\n stripCollectorSegmentsFromSectionedResult(result);\n return;\n }\n\n stripCollectorSegmentsFromWordCounterResult(result);\n}\n","import { appendAll } from \"../../utils/append-all\";\nimport wordCounter, { type NonWordCollection, type WordCounterResult } from \"../../wc\";\nimport { createNonWordCollection, mergeNonWordCollections } from \"../../wc/non-words\";\n\nexport function mergeWordCounterResult(\n left: WordCounterResult,\n right: WordCounterResult,\n preserveCollectorSegments: boolean,\n): WordCounterResult {\n if (left.breakdown.mode !== right.breakdown.mode) {\n throw new Error(\"Cannot merge different breakdown modes.\");\n }\n\n const total = left.total + right.total;\n const counts =\n left.counts || right.counts\n ? {\n words: (left.counts?.words ?? 0) + (right.counts?.words ?? 0),\n nonWords: (left.counts?.nonWords ?? 0) + (right.counts?.nonWords ?? 0),\n total: (left.counts?.total ?? 0) + (right.counts?.total ?? 0),\n }\n : undefined;\n\n if (left.breakdown.mode === \"chunk\" && right.breakdown.mode === \"chunk\") {\n return {\n total,\n counts,\n breakdown: {\n mode: \"chunk\",\n items: [...left.breakdown.items, ...right.breakdown.items],\n },\n };\n }\n\n if (left.breakdown.mode === \"segments\" && right.breakdown.mode === \"segments\") {\n return {\n total,\n counts,\n breakdown: {\n mode: \"segments\",\n items: [...left.breakdown.items, ...right.breakdown.items],\n },\n };\n }\n\n if (left.breakdown.mode === \"char\" && right.breakdown.mode === \"char\") {\n return {\n total,\n counts,\n breakdown: {\n mode: \"char\",\n items: [...left.breakdown.items, ...right.breakdown.items],\n },\n };\n }\n\n if (left.breakdown.mode === \"char-collector\" && right.breakdown.mode === \"char-collector\") {\n const localeOrder: string[] = [];\n const mergedByLocale = new Map<\n string,\n {\n locale: string;\n chars: number;\n nonWords?: NonWordCollection;\n }\n >();\n\n const addItems = (items: typeof left.breakdown.items): void => {\n for (const item of items) {\n const existing = mergedByLocale.get(item.locale);\n if (existing) {\n existing.chars += item.chars;\n if (item.nonWords) {\n if (!existing.nonWords) {\n existing.nonWords = createNonWordCollection();\n }\n mergeNonWordCollections(existing.nonWords, item.nonWords);\n }\n continue;\n }\n\n localeOrder.push(item.locale);\n mergedByLocale.set(item.locale, {\n locale: item.locale,\n chars: item.chars,\n nonWords: item.nonWords\n ? mergeNonWordCollections(createNonWordCollection(), item.nonWords)\n : undefined,\n });\n }\n };\n\n addItems(left.breakdown.items);\n addItems(right.breakdown.items);\n\n return {\n total,\n counts,\n breakdown: {\n mode: \"char-collector\",\n items: localeOrder.map((locale) => {\n const value = mergedByLocale.get(locale);\n if (!value) {\n throw new Error(`Missing char-collector entry for locale: ${locale}`);\n }\n return value;\n }),\n },\n };\n }\n\n if (left.breakdown.mode === \"collector\" && right.breakdown.mode === \"collector\") {\n const localeOrder: string[] = [];\n const mergedByLocale = new Map<\n string,\n {\n locale: string;\n words: number;\n segments: string[];\n }\n >();\n\n const addItems = (items: typeof left.breakdown.items): void => {\n for (const item of items) {\n const existing = mergedByLocale.get(item.locale);\n if (existing) {\n existing.words += item.words;\n if (preserveCollectorSegments) {\n appendAll(existing.segments, item.segments);\n }\n continue;\n }\n\n localeOrder.push(item.locale);\n mergedByLocale.set(item.locale, {\n locale: item.locale,\n words: item.words,\n segments: preserveCollectorSegments ? [...item.segments] : [],\n });\n }\n };\n\n addItems(left.breakdown.items);\n addItems(right.breakdown.items);\n\n let mergedNonWords: NonWordCollection | undefined;\n if (left.breakdown.nonWords || right.breakdown.nonWords) {\n mergedNonWords = createNonWordCollection();\n if (left.breakdown.nonWords) {\n mergeNonWordCollections(mergedNonWords, left.breakdown.nonWords);\n }\n if (right.breakdown.nonWords) {\n mergeNonWordCollections(mergedNonWords, right.breakdown.nonWords);\n }\n }\n\n return {\n total,\n counts,\n breakdown: {\n mode: \"collector\",\n items: localeOrder.map((locale) => {\n const value = mergedByLocale.get(locale);\n if (!value) {\n throw new Error(`Missing collector entry for locale: ${locale}`);\n }\n return value;\n }),\n nonWords: mergedNonWords,\n },\n };\n }\n\n return {\n total,\n counts,\n breakdown: left.breakdown,\n };\n}\n\nexport function aggregateWordCounterResults(\n results: WordCounterResult[],\n preserveCollectorSegments: boolean,\n): WordCounterResult {\n if (results.length === 0) {\n return wordCounter(\"\", { mode: \"chunk\" });\n }\n\n const first = results[0];\n if (!first) {\n return wordCounter(\"\", { mode: \"chunk\" });\n }\n\n let aggregate = first;\n for (let index = 1; index < results.length; index += 1) {\n const current = results[index];\n if (!current) {\n continue;\n }\n aggregate = mergeWordCounterResult(aggregate, current, preserveCollectorSegments);\n }\n\n return aggregate;\n}\n","import type { SectionedResult } from \"../../markdown\";\nimport { aggregateWordCounterResults } from \"./aggregate-word-counter\";\n\nfunction buildSectionKey(name: string, source: \"frontmatter\" | \"content\"): string {\n return `${source}:${name}`;\n}\n\nexport function aggregateSectionedResults(\n results: SectionedResult[],\n preserveCollectorSegments: boolean,\n): SectionedResult {\n if (results.length === 0) {\n return {\n section: \"all\",\n total: 0,\n frontmatterType: null,\n items: [],\n };\n }\n\n const section = results[0]?.section ?? \"all\";\n const grouped = new Map<\n string,\n {\n name: string;\n source: \"frontmatter\" | \"content\";\n items: ReturnType<typeof aggregateWordCounterResults>[];\n }\n >();\n let total = 0;\n let frontmatterType = results[0]?.frontmatterType ?? null;\n\n for (const result of results) {\n total += result.total;\n\n if (result.section !== section) {\n throw new Error(\"Cannot aggregate section results with different section modes.\");\n }\n\n if (frontmatterType !== result.frontmatterType) {\n frontmatterType = null;\n }\n\n for (const item of result.items) {\n const key = buildSectionKey(item.name, item.source);\n const existing = grouped.get(key);\n if (!existing) {\n grouped.set(key, {\n name: item.name,\n source: item.source,\n items: [item.result],\n });\n continue;\n }\n\n existing.items.push(item.result);\n }\n }\n\n const sourceOrder = new Map<\"frontmatter\" | \"content\", number>([\n [\"frontmatter\", 0],\n [\"content\", 1],\n ]);\n\n const items = [...grouped.values()]\n .sort((left, right) => {\n const sourceDiff = (sourceOrder.get(left.source) ?? 0) - (sourceOrder.get(right.source) ?? 0);\n if (sourceDiff !== 0) {\n return sourceDiff;\n }\n return left.name.localeCompare(right.name);\n })\n .map((entry) => ({\n name: entry.name,\n source: entry.source,\n result: aggregateWordCounterResults(entry.items, preserveCollectorSegments),\n }));\n\n return {\n section,\n total,\n frontmatterType,\n items,\n };\n}\n","import { countSections } from \"../../markdown\";\nimport type { SectionMode, SectionedResult } from \"../../markdown\";\nimport wordCounter, { type WordCounterResult } from \"../../wc\";\nimport type { BatchFileInput, BatchFileResult, BatchSummary } from \"../types\";\nimport type { BatchProgressSnapshot } from \"../progress/reporter\";\nimport { compactCollectorSegmentsInCountResult } from \"./aggregate-compact\";\nimport { aggregateSectionedResults } from \"./aggregate-sections\";\nimport { aggregateWordCounterResults } from \"./aggregate-word-counter\";\n\ntype BuildBatchSummaryOptions = {\n onFileCounted?: (snapshot: BatchProgressSnapshot) => void;\n onFinalizeStart?: () => void;\n preserveCollectorSegments?: boolean;\n};\n\ntype FinalizeBatchSummaryFromFileResultsOptions = {\n onFinalizeStart?: () => void;\n preserveCollectorSegments?: boolean;\n};\n\nexport { compactCollectorSegmentsInCountResult } from \"./aggregate-compact\";\n\nexport async function buildBatchSummary(\n inputs: BatchFileInput[],\n section: SectionMode,\n wcOptions: Parameters<typeof wordCounter>[1],\n options: BuildBatchSummaryOptions = {},\n): Promise<BatchSummary> {\n const preserveCollectorSegments = options.preserveCollectorSegments ?? true;\n const files: BatchFileResult[] = [];\n\n for (const input of inputs) {\n const result =\n section === \"all\"\n ? wordCounter(input.content, wcOptions)\n : countSections(input.content, section, wcOptions);\n\n if (!preserveCollectorSegments) {\n compactCollectorSegmentsInCountResult(result);\n }\n\n files.push({\n path: input.path,\n result,\n });\n\n options.onFileCounted?.({\n completed: files.length,\n total: inputs.length,\n });\n }\n\n return finalizeBatchSummaryFromFileResults(files, section, wcOptions, {\n onFinalizeStart: options.onFinalizeStart,\n preserveCollectorSegments: options.preserveCollectorSegments,\n });\n}\n\nexport function finalizeBatchSummaryFromFileResults(\n files: BatchFileResult[],\n section: SectionMode,\n wcOptions: Parameters<typeof wordCounter>[1],\n options: FinalizeBatchSummaryFromFileResultsOptions = {},\n): BatchSummary {\n const preserveCollectorSegments = options.preserveCollectorSegments ?? true;\n if (!preserveCollectorSegments) {\n for (const file of files) {\n compactCollectorSegmentsInCountResult(file.result);\n }\n }\n\n options.onFinalizeStart?.();\n if (files.length === 0) {\n return {\n files,\n skipped: [],\n aggregate:\n section === \"all\"\n ? wordCounter(\"\", wcOptions)\n : {\n section,\n total: 0,\n frontmatterType: null,\n items: [],\n },\n };\n }\n\n const aggregate =\n section === \"all\"\n ? aggregateWordCounterResults(\n files.map((file) => file.result as WordCounterResult),\n preserveCollectorSegments,\n )\n : aggregateSectionedResults(\n files.map((file) => file.result as SectionedResult),\n preserveCollectorSegments,\n );\n\n return {\n files,\n skipped: [],\n aggregate,\n };\n}\n","export async function runBoundedQueue<T>(\n total: number,\n requestedJobs: number,\n worker: (index: number) => Promise<T>,\n): Promise<T[]> {\n if (total === 0) {\n return [];\n }\n\n const safeRequestedJobs = Number.isFinite(requestedJobs) ? Math.floor(requestedJobs) : 1;\n const concurrency = Math.max(1, Math.min(total, safeRequestedJobs));\n const results: Array<T | undefined> = Array.from({ length: total });\n let nextIndex = 0;\n\n const runWorker = async (): Promise<void> => {\n while (true) {\n const current = nextIndex;\n nextIndex += 1;\n if (current >= total) {\n return;\n }\n\n results[current] = await worker(current);\n }\n };\n\n await Promise.all(Array.from({ length: concurrency }, () => runWorker()));\n if (results.some((result) => result === undefined)) {\n throw new Error(\"Bounded queue completed with missing results.\");\n }\n return results as T[];\n}\n","import { readFile } from \"node:fs/promises\";\nimport { isProbablyBinary } from \"../../path/load\";\nimport { createResourceLimitError, isResourceLimitError } from \"./limits\";\nimport type { BatchJobsLimit } from \"./types\";\n\nexport type ReadBatchInputResult =\n | {\n type: \"file\";\n path: string;\n content: string;\n }\n | {\n type: \"skip\";\n path: string;\n reason: string;\n };\n\ntype ReadBatchInputOptions = {\n requestedJobs: number;\n limits: BatchJobsLimit;\n detectBinary: boolean;\n};\n\nexport async function readBatchInput(\n path: string | undefined,\n options: ReadBatchInputOptions,\n): Promise<ReadBatchInputResult> {\n if (!path) {\n return {\n type: \"skip\",\n path: \"\",\n reason: \"not readable: missing path\",\n };\n }\n\n let buffer: Buffer;\n try {\n buffer = await readFile(path);\n } catch (error) {\n if (isResourceLimitError(error)) {\n throw createResourceLimitError(path, error, options.requestedJobs, options.limits);\n }\n\n const message = error instanceof Error ? error.message : String(error);\n return {\n type: \"skip\",\n path,\n reason: `not readable: ${message}`,\n };\n }\n\n if (options.detectBinary && isProbablyBinary(buffer)) {\n return {\n type: \"skip\",\n path,\n reason: \"binary file\",\n };\n }\n\n return {\n type: \"file\",\n path,\n content: buffer.toString(\"utf8\"),\n };\n}\n","import { countSections } from \"../../../markdown\";\nimport { countSectionsWithDetector, wordCounterWithDetector } from \"../../../detector\";\nimport wordCounter from \"../../../wc\";\nimport { compactCollectorSegmentsInCountResult } from \"../aggregate\";\nimport { resolveBatchJobsLimit } from \"./limits\";\nimport { runBoundedQueue } from \"./queue\";\nimport { readBatchInput } from \"./read-input\";\nimport type { CountBatchWithJobsOptions, CountBatchWithJobsResult } from \"./types\";\n\ntype CountBatchEntry =\n | {\n type: \"file\";\n file: CountBatchWithJobsResult[\"files\"][number];\n }\n | {\n type: \"skip\";\n skip: CountBatchWithJobsResult[\"skipped\"][number];\n };\n\nexport async function countBatchInputsWithJobs(\n filePaths: string[],\n options: CountBatchWithJobsOptions,\n): Promise<CountBatchWithJobsResult> {\n const detectorMode = options.detectorMode ?? \"regex\";\n const limits = resolveBatchJobsLimit();\n const total = filePaths.length;\n let completed = 0;\n\n const entries = await runBoundedQueue(filePaths.length, options.jobs, async (index) => {\n const loaded = await readBatchInput(filePaths[index], {\n requestedJobs: options.jobs,\n limits,\n detectBinary: options.detectBinary ?? true,\n });\n if (loaded.type === \"skip\") {\n completed += 1;\n options.onFileProcessed?.({ completed, total });\n return {\n type: \"skip\",\n skip: { path: loaded.path, reason: loaded.reason },\n } satisfies CountBatchEntry;\n }\n\n const detectorDebug =\n detectorMode === \"wasm\"\n ? options.createDetectorDebugContext?.({ path: loaded.path })\n : undefined;\n const result =\n detectorMode === \"regex\"\n ? options.section === \"all\"\n ? wordCounter(loaded.content, options.wcOptions)\n : countSections(loaded.content, options.section, options.wcOptions)\n : options.section === \"all\"\n ? await wordCounterWithDetector(loaded.content, {\n ...options.wcOptions,\n detector: detectorMode,\n detectorDebug,\n })\n : await countSectionsWithDetector(loaded.content, options.section, {\n ...options.wcOptions,\n detector: detectorMode,\n detectorDebug,\n });\n\n if (!options.preserveCollectorSegments) {\n compactCollectorSegmentsInCountResult(result);\n }\n\n completed += 1;\n options.onFileProcessed?.({ completed, total });\n return {\n type: \"file\",\n file: {\n path: loaded.path,\n result,\n ...(detectorDebug?.summary ? { debug: { detector: detectorDebug.summary } } : {}),\n },\n } satisfies CountBatchEntry;\n });\n\n const files: CountBatchWithJobsResult[\"files\"] = [];\n const skipped: CountBatchWithJobsResult[\"skipped\"] = [];\n for (const entry of entries) {\n if (entry.type === \"file\") {\n files.push(entry.file);\n continue;\n }\n skipped.push(entry.skip);\n }\n\n return { files, skipped };\n}\n","import type { SectionMode } from \"../../../markdown\";\nimport type wordCounter from \"../../../wc\";\nimport { finalizeBatchSummaryFromFileResults } from \"../aggregate\";\nimport type { BatchFileResult, BatchSummary } from \"../../types\";\n\ntype FinalizeBatchJobsSummaryOptions = {\n onFinalizeStart?: () => void;\n preserveCollectorSegments?: boolean;\n};\n\nexport function finalizeBatchJobsSummary(\n files: BatchFileResult[],\n section: SectionMode,\n wcOptions: Parameters<typeof wordCounter>[1],\n options: FinalizeBatchJobsSummaryOptions = {},\n): BatchSummary {\n return finalizeBatchSummaryFromFileResults(files, section, wcOptions, {\n onFinalizeStart: options.onFinalizeStart,\n preserveCollectorSegments: options.preserveCollectorSegments,\n });\n}\n","export type ProgressOutputStream = {\n isTTY?: boolean;\n write: (chunk: string) => unknown;\n};\n\nexport type BatchProgressSnapshot = {\n completed: number;\n total: number;\n};\n\nexport type BatchProgressReporter = {\n enabled: boolean;\n start: (total: number, startedAtMs?: number) => void;\n advance: (snapshot: BatchProgressSnapshot) => void;\n startFinalizing: () => void;\n finish: () => void;\n};\n\ntype BatchProgressReporterOptions = {\n enabled: boolean;\n stream: ProgressOutputStream;\n clearOnFinish?: boolean;\n};\n\nconst PROGRESS_BAR_WIDTH = 20;\nconst FILLED_BAR_CHAR = \"█\";\nconst EMPTY_BAR_CHAR = \"░\";\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction buildProgressBar(completed: number, total: number): string {\n const safeTotal = Math.max(total, 1);\n const ratio = clamp(completed / safeTotal, 0, 1);\n const filled =\n completed >= safeTotal ? PROGRESS_BAR_WIDTH : Math.floor(ratio * PROGRESS_BAR_WIDTH);\n const empty = PROGRESS_BAR_WIDTH - filled;\n return `${FILLED_BAR_CHAR.repeat(filled)}${EMPTY_BAR_CHAR.repeat(empty)}`;\n}\n\nfunction formatElapsed(startedAtMs: number): string {\n const elapsedMs = Date.now() - startedAtMs;\n const totalSeconds = Math.max(0, Math.floor(elapsedMs / 1000));\n const minutes = Math.floor(totalSeconds / 60);\n const seconds = totalSeconds % 60;\n const tenths = Math.floor((Math.max(0, elapsedMs) % 1000) / 100);\n return `${String(minutes).padStart(2, \"0\")}:${String(seconds).padStart(2, \"0\")}.${tenths}`;\n}\n\nfunction buildProgressLine(completed: number, total: number, startedAtMs: number): string {\n const safeTotal = Math.max(total, 1);\n const percent = completed >= safeTotal ? 100 : Math.floor((completed / safeTotal) * 100);\n const bar = buildProgressBar(completed, safeTotal);\n const percentText = `${String(percent).padStart(3, \" \")}%`;\n const completedText = String(completed).padStart(String(safeTotal).length, \" \");\n const elapsed = formatElapsed(startedAtMs);\n return `Counting files [${bar}] ${percentText} ${completedText}/${safeTotal} elapsed ${elapsed}`;\n}\n\nfunction buildFinalizingLine(startedAtMs: number): string {\n const elapsed = formatElapsed(startedAtMs);\n return `Finalizing aggregate... elapsed ${elapsed}`;\n}\n\nexport function createBatchProgressReporter(\n options: BatchProgressReporterOptions,\n): BatchProgressReporter {\n const enabled = options.enabled;\n const isTTY = Boolean(options.stream.isTTY);\n const clearOnFinish = options.clearOnFinish ?? true;\n let active = false;\n let total = 0;\n let lastLineLength = 0;\n let startedAtMs = 0;\n let lastRenderedPercent = -1;\n let finalizingStarted = false;\n\n const writeTTYLine = (line: string): void => {\n const trailingPadding =\n lastLineLength > line.length ? \" \".repeat(lastLineLength - line.length) : \"\";\n options.stream.write(`\\r${line}${trailingPadding}`);\n lastLineLength = line.length;\n };\n\n const render = (completed: number): void => {\n const line = buildProgressLine(completed, total, startedAtMs);\n const safeTotal = Math.max(total, 1);\n const percent = completed >= safeTotal ? 100 : Math.floor((completed / safeTotal) * 100);\n if (!isTTY && percent === lastRenderedPercent && completed < safeTotal) {\n return;\n }\n\n lastRenderedPercent = percent;\n\n if (isTTY) {\n writeTTYLine(line);\n return;\n }\n\n lastLineLength = line.length;\n options.stream.write(`${line}\\n`);\n };\n\n const clearLine = (): void => {\n if (lastLineLength === 0) {\n return;\n }\n options.stream.write(`\\r${\" \".repeat(lastLineLength)}\\r`);\n lastLineLength = 0;\n };\n\n return {\n enabled,\n start(nextTotal, nextStartedAtMs) {\n if (!enabled || nextTotal <= 1) {\n return;\n }\n\n total = nextTotal;\n active = true;\n startedAtMs = nextStartedAtMs ?? Date.now();\n lastRenderedPercent = -1;\n finalizingStarted = false;\n render(0);\n },\n advance(snapshot) {\n if (!active) {\n return;\n }\n\n render(snapshot.completed);\n },\n startFinalizing() {\n if (!active || finalizingStarted) {\n return;\n }\n\n finalizingStarted = true;\n const line = buildFinalizingLine(startedAtMs);\n if (isTTY) {\n if (!clearOnFinish) {\n options.stream.write(`\\n${line}`);\n lastLineLength = line.length;\n return;\n }\n writeTTYLine(line);\n return;\n }\n\n lastLineLength = line.length;\n options.stream.write(`${line}\\n`);\n },\n finish() {\n if (!active) {\n return;\n }\n\n if (isTTY) {\n if (clearOnFinish) {\n clearLine();\n } else {\n options.stream.write(\"\\n\");\n }\n }\n active = false;\n },\n };\n}\n","import type { SectionMode } from \"../../markdown\";\nimport type { DetectorWordCounterOptions } from \"../../detector\";\nimport { createDetectorDebugSummary } from \"../../detector/debug\";\nimport { appendAll } from \"../../utils/append-all\";\nimport type { DebugChannel, DebugEventOptions } from \"../debug/channel\";\nimport { countBatchInputsWithJobs } from \"./jobs/load-count\";\nimport {\n WorkerRouteUnavailableError,\n countBatchInputsWithWorkerJobs,\n} from \"./jobs/load-count-worker\";\nimport { finalizeBatchJobsSummary } from \"./jobs/render\";\nimport type { BatchJobsStrategy } from \"./jobs/types\";\nimport { type DirectoryExtensionFilter } from \"../path/filter\";\nimport { resolveBatchFilePaths } from \"../path/resolve\";\nimport { type BatchProgressReporter } from \"../progress/reporter\";\nimport type { BatchOptions, BatchSummary } from \"../types\";\n\ntype RunBatchCountOptions = {\n pathInputs: string[];\n batchOptions: BatchOptions;\n extensionFilter: DirectoryExtensionFilter;\n detectBinary: boolean;\n section: SectionMode;\n wcOptions: DetectorWordCounterOptions;\n preserveCollectorSegments: boolean;\n detectorEvidence: boolean;\n debug: DebugChannel;\n progressReporter: BatchProgressReporter;\n jobs: number;\n jobsStrategy: BatchJobsStrategy;\n emitWarning?: (message: string) => void;\n};\n\nexport async function runBatchCount(options: RunBatchCountOptions): Promise<BatchSummary> {\n const detectorEvidence = options.detectorEvidence\n ? {\n verbosity: options.debug.verbosity,\n mode: options.wcOptions.mode ?? \"chunk\",\n section: options.section,\n }\n : undefined;\n const createFileDetectorDebugContext = ({ path }: { path: string }) =>\n options.debug.enabled && options.wcOptions.detector === \"wasm\"\n ? {\n emit: (\n event: string,\n details?: Record<string, unknown>,\n eventOptions?: DebugEventOptions,\n ) =>\n options.debug.emit(\n event,\n {\n path,\n ...details,\n },\n {\n ...eventOptions,\n scope: \"file\",\n },\n ),\n summary: createDetectorDebugSummary(\"wasm\"),\n ...(detectorEvidence ? { evidence: detectorEvidence } : {}),\n }\n : undefined;\n const emitWorkerDetectorDebugEvent = options.debug.enabled\n ? (event: string, details?: Record<string, unknown>, eventOptions?: DebugEventOptions) => {\n options.debug.emit(event, details, {\n ...eventOptions,\n scope: \"file\",\n });\n }\n : undefined;\n const batchStartedAtMs = Date.now();\n const resolveStartedAtMs = Date.now();\n\n options.debug.emit(\"batch.resolve.start\", {\n inputs: options.pathInputs.length,\n pathMode: options.batchOptions.pathMode,\n recursive: options.batchOptions.recursive,\n });\n\n const resolved = await resolveBatchFilePaths(options.pathInputs, {\n pathMode: options.batchOptions.pathMode,\n recursive: options.batchOptions.recursive,\n extensionFilter: options.extensionFilter,\n directoryRegexPattern: options.batchOptions.directoryRegexPattern,\n debug: options.debug,\n });\n const resolveElapsedMs = Date.now() - resolveStartedAtMs;\n options.debug.emit(\"batch.resolve.complete\", {\n files: resolved.files.length,\n skipped: resolved.skipped.length,\n elapsedMs: resolveElapsedMs,\n });\n options.debug.emit(\"batch.stage.timing\", {\n stage: \"resolve\",\n elapsedMs: resolveElapsedMs,\n });\n\n options.debug.emit(\"batch.jobs.strategy\", {\n strategy: options.jobsStrategy,\n jobs: options.jobs,\n });\n\n let summary: BatchSummary;\n let routeSkips: BatchSummary[\"skipped\"] = [];\n options.debug.emit(\"batch.load.start\", {\n files: resolved.files.length,\n jobs: options.jobs,\n strategy: options.jobsStrategy,\n });\n options.debug.emit(\"batch.load.complete\", {\n files: 0,\n skipped: 0,\n elapsedMs: 0,\n strategy: options.jobsStrategy,\n });\n options.debug.emit(\"batch.stage.timing\", {\n stage: \"load\",\n elapsedMs: 0,\n });\n\n const progressEnabled = options.progressReporter.enabled && resolved.files.length > 1;\n options.debug.emit(\"batch.progress.start\", {\n enabled: progressEnabled,\n total: resolved.files.length,\n });\n\n if (progressEnabled) {\n options.progressReporter.start(resolved.files.length, batchStartedAtMs);\n }\n\n const countStartedAtMs = Date.now();\n let finalizeStartedAtMs: number | null = null;\n let emittedCountTiming = false;\n try {\n let counted: Awaited<ReturnType<typeof countBatchInputsWithJobs>>;\n if (options.jobs > 1) {\n try {\n counted = await countBatchInputsWithWorkerJobs(resolved.files, {\n jobs: options.jobs,\n section: options.section,\n detectorMode: options.wcOptions.detector ?? \"regex\",\n wcOptions: options.wcOptions,\n detectBinary: options.detectBinary,\n preserveCollectorSegments: options.preserveCollectorSegments,\n detectorEvidence: options.detectorEvidence,\n debugVerbosity: options.debug.verbosity,\n onDetectorDebugEvent: emitWorkerDetectorDebugEvent,\n onFileProcessed: (snapshot) => {\n if (progressEnabled) {\n options.progressReporter.advance(snapshot);\n }\n },\n });\n options.debug.emit(\"batch.jobs.executor\", {\n strategy: options.jobsStrategy,\n executor: \"worker-pool\",\n jobs: options.jobs,\n });\n } catch (error) {\n if (!(error instanceof WorkerRouteUnavailableError)) {\n throw error;\n }\n\n options.emitWarning?.(\n `Worker executor unavailable; falling back to async load+count. (${error.message})`,\n );\n options.debug.emit(\"batch.jobs.executor\", {\n strategy: options.jobsStrategy,\n executor: \"async-fallback\",\n reason: error.message,\n jobs: options.jobs,\n });\n counted = await countBatchInputsWithJobs(resolved.files, {\n jobs: options.jobs,\n section: options.section,\n detectorMode: options.wcOptions.detector ?? \"regex\",\n wcOptions: options.wcOptions,\n detectBinary: options.detectBinary,\n preserveCollectorSegments: options.preserveCollectorSegments,\n detectorEvidence: options.detectorEvidence,\n debugVerbosity: options.debug.verbosity,\n createDetectorDebugContext: createFileDetectorDebugContext,\n onFileProcessed: (snapshot) => {\n if (progressEnabled) {\n options.progressReporter.advance(snapshot);\n }\n },\n });\n }\n } else {\n counted = await countBatchInputsWithJobs(resolved.files, {\n jobs: options.jobs,\n section: options.section,\n detectorMode: options.wcOptions.detector ?? \"regex\",\n wcOptions: options.wcOptions,\n detectBinary: options.detectBinary,\n preserveCollectorSegments: options.preserveCollectorSegments,\n detectorEvidence: options.detectorEvidence,\n debugVerbosity: options.debug.verbosity,\n createDetectorDebugContext: createFileDetectorDebugContext,\n onFileProcessed: (snapshot) => {\n if (progressEnabled) {\n options.progressReporter.advance(snapshot);\n }\n },\n });\n options.debug.emit(\"batch.jobs.executor\", {\n strategy: options.jobsStrategy,\n executor: \"async-main\",\n jobs: options.jobs,\n });\n }\n\n routeSkips = counted.skipped;\n summary = finalizeBatchJobsSummary(counted.files, options.section, options.wcOptions, {\n onFinalizeStart: () => {\n finalizeStartedAtMs = Date.now();\n if (progressEnabled) {\n options.progressReporter.startFinalizing();\n }\n\n const countElapsedMs = finalizeStartedAtMs - countStartedAtMs;\n options.debug.emit(\"batch.stage.timing\", {\n stage: \"count\",\n elapsedMs: countElapsedMs,\n });\n emittedCountTiming = true;\n },\n preserveCollectorSegments: options.preserveCollectorSegments,\n });\n } finally {\n if (progressEnabled) {\n options.progressReporter.finish();\n }\n options.debug.emit(\"batch.progress.complete\", {\n enabled: progressEnabled,\n total: resolved.files.length,\n });\n }\n\n if (!emittedCountTiming) {\n const countElapsedMs = Date.now() - countStartedAtMs;\n options.debug.emit(\"batch.stage.timing\", {\n stage: \"count\",\n elapsedMs: countElapsedMs,\n });\n }\n\n const finalizeElapsedMs = finalizeStartedAtMs === null ? 0 : Date.now() - finalizeStartedAtMs;\n options.debug.emit(\"batch.stage.timing\", {\n stage: \"finalize\",\n elapsedMs: finalizeElapsedMs,\n });\n\n appendAll(summary.skipped, resolved.skipped);\n appendAll(summary.skipped, routeSkips);\n options.debug.emit(\"batch.aggregate.complete\", {\n files: summary.files.length,\n skipped: summary.skipped.length,\n total: summary.aggregate.total,\n });\n\n return summary;\n}\n","import type { BatchJobsStrategy } from \"./types\";\n\nexport function resolveBatchJobsStrategy(_jobs: number): BatchJobsStrategy {\n return \"load-count\";\n}\n","import type { DetectorDebugSummary } from \"../../detector/debug\";\nimport type { BatchSkip } from \"../types\";\n\ntype DebugSection = {\n skipped?: BatchSkip[];\n detector?: DetectorDebugSummary;\n};\n\nexport function buildDebugSection(input: DebugSection): DebugSection | undefined {\n const output: DebugSection = {};\n\n if (input.skipped && input.skipped.length > 0) {\n output.skipped = input.skipped;\n }\n\n if (input.detector) {\n output.detector = input.detector;\n }\n\n return Object.keys(output).length > 0 ? output : undefined;\n}\n","export function showSingularOrPluralWord(count: number, word: string): string {\n return `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n}\n","import { relative as relativePath } from \"node:path\";\nimport type { SectionMode, SectionedResult } from \"../../markdown\";\nimport { showSingularOrPluralWord } from \"../../utils\";\nimport type { NonWordCollection, WordCounterMode, WordCounterResult } from \"../../wc\";\nimport { formatTotalOfParts, type TotalOfOverride } from \"../total-of\";\nimport type { BatchSkip, BatchSummary } from \"../types\";\nimport pc from \"picocolors\";\n\ntype CountUnit = \"word\" | \"character\";\n\ntype CountBreakdownItem = {\n locale: string;\n count: number;\n nonWords?: NonWordCollection;\n};\n\nexport type TotalLabels = {\n overall: string;\n section: string;\n};\n\nfunction getCountUnit(mode: WordCounterMode): CountUnit {\n return mode === \"char\" || mode === \"char-collector\" ? \"character\" : \"word\";\n}\n\nexport function getTotalLabels(mode: WordCounterMode, includeNonWords: boolean): TotalLabels {\n const unit = mode === \"char\" || mode === \"char-collector\" ? \"characters\" : \"words\";\n if (includeNonWords) {\n return { overall: \"Total count\", section: \"total count\" };\n }\n return { overall: `Total ${unit}`, section: `total ${unit}` };\n}\n\nfunction hasNonWords(nonWords: NonWordCollection): boolean {\n const whitespaceCount = nonWords.counts.whitespace ?? 0;\n return (\n nonWords.counts.emoji > 0 ||\n nonWords.counts.symbols > 0 ||\n nonWords.counts.punctuation > 0 ||\n whitespaceCount > 0\n );\n}\n\nfunction renderNonWords(nonWords: NonWordCollection | undefined, verbose: boolean): void {\n if (!nonWords || !hasNonWords(nonWords)) {\n return;\n }\n\n if (verbose) {\n const whitespace = nonWords.whitespace\n ? ` whitespace=${JSON.stringify(nonWords.whitespace)}`\n : \"\";\n console.log(\n pc.yellow(\n `Non-words: emoji=${JSON.stringify(nonWords.emoji)} symbols=${JSON.stringify(\n nonWords.symbols,\n )} punctuation=${JSON.stringify(nonWords.punctuation)}${whitespace}`,\n ),\n );\n return;\n }\n\n const whitespaceCount = nonWords.counts.whitespace ?? 0;\n const whitespaceLabel = whitespaceCount > 0 ? `, whitespace ${whitespaceCount}` : \"\";\n console.log(\n pc.yellow(\n `Non-words: emoji ${nonWords.counts.emoji}, symbols ${nonWords.counts.symbols}, punctuation ${nonWords.counts.punctuation}${whitespaceLabel}`,\n ),\n );\n}\n\nfunction renderCountBreakdown(items: CountBreakdownItem[], unit: CountUnit): void {\n for (const item of items) {\n console.log(`Locale ${item.locale}: ${showSingularOrPluralWord(item.count, unit)}`);\n renderNonWords(item.nonWords, false);\n }\n}\n\nfunction renderSegmentBreakdown(\n items: Array<{ locale: string; words: number; segments: string[]; nonWords?: NonWordCollection }>,\n): void {\n for (const item of items) {\n console.log(\n `Locale ${item.locale}: ${JSON.stringify(item.segments)} (${showSingularOrPluralWord(item.words, \"word\")})`,\n );\n renderNonWords(item.nonWords, true);\n }\n}\n\nfunction renderCollectorBreakdown(items: Array<{ locale: string; words: number }>): void {\n for (const item of items) {\n console.log(`Locale ${item.locale}: ${showSingularOrPluralWord(item.words, \"word\")}`);\n }\n}\n\nfunction renderTotalOfOverride(baseTotal: number, override: TotalOfOverride | undefined): void {\n if (!override || override.total === baseTotal) {\n return;\n }\n\n console.log(`Total-of (override: ${formatTotalOfParts(override.parts)}): ${override.total}`);\n}\n\nexport function renderStandardResult(\n result: WordCounterResult,\n totalLabel: string,\n totalOfOverride?: TotalOfOverride,\n): void {\n console.log(`${totalLabel}: ${result.total}`);\n renderTotalOfOverride(result.total, totalOfOverride);\n\n if (result.breakdown.mode === \"segments\") {\n renderSegmentBreakdown(result.breakdown.items);\n return;\n }\n\n if (result.breakdown.mode === \"collector\") {\n renderCollectorBreakdown(result.breakdown.items);\n renderNonWords(result.breakdown.nonWords, false);\n return;\n }\n\n if (result.breakdown.mode === \"char\" || result.breakdown.mode === \"char-collector\") {\n renderCountBreakdown(\n result.breakdown.items.map((item) => ({\n locale: item.locale,\n count: item.chars,\n nonWords: item.nonWords,\n })),\n getCountUnit(result.breakdown.mode),\n );\n return;\n }\n\n renderCountBreakdown(\n result.breakdown.items.map((item) => ({\n locale: item.locale,\n count: item.words,\n nonWords: item.nonWords,\n })),\n getCountUnit(result.breakdown.mode),\n );\n}\n\nfunction buildSectionLabel(\n sectionName: string,\n sectionMode: SectionMode,\n source: \"frontmatter\" | \"content\",\n totalLabel: string,\n): string {\n if (sectionMode === \"frontmatter\") {\n return `[Frontmatter] (${totalLabel})`;\n }\n\n if (sectionMode === \"content\") {\n return `[Content] (${totalLabel})`;\n }\n\n if (sectionMode === \"split\") {\n return source === \"frontmatter\" ? `[Frontmatter] (${totalLabel})` : `[Content] (${totalLabel})`;\n }\n\n if (sectionMode === \"per-key\") {\n return `[Frontmatter] ${sectionName} (${totalLabel})`;\n }\n\n if (sectionMode === \"split-per-key\") {\n return source === \"content\"\n ? `[Content] (${totalLabel})`\n : `[Frontmatter] ${sectionName} (${totalLabel})`;\n }\n\n return `[Section] ${sectionName} (${totalLabel})`;\n}\n\nexport function renderStandardSectionedResult(\n result: SectionedResult,\n labels: TotalLabels,\n totalOfOverride?: TotalOfOverride,\n): void {\n console.log(`${labels.overall}: ${result.total}`);\n renderTotalOfOverride(result.total, totalOfOverride);\n\n for (const item of result.items) {\n const label = buildSectionLabel(item.name, result.section, item.source, labels.section);\n const unit = getCountUnit(item.result.breakdown.mode);\n console.log(pc.cyan(pc.bold(`${label}: ${showSingularOrPluralWord(item.result.total, unit)}`)));\n\n if (item.result.breakdown.mode === \"segments\") {\n renderSegmentBreakdown(item.result.breakdown.items);\n continue;\n }\n\n if (item.result.breakdown.mode === \"collector\") {\n renderCollectorBreakdown(item.result.breakdown.items);\n renderNonWords(item.result.breakdown.nonWords, false);\n continue;\n }\n\n if (item.result.breakdown.mode === \"char\" || item.result.breakdown.mode === \"char-collector\") {\n renderCountBreakdown(\n item.result.breakdown.items.map((chunk) => ({\n locale: chunk.locale,\n count: chunk.chars,\n nonWords: chunk.nonWords,\n })),\n unit,\n );\n continue;\n }\n\n renderCountBreakdown(\n item.result.breakdown.items.map((chunk) => ({\n locale: chunk.locale,\n count: chunk.words,\n nonWords: chunk.nonWords,\n })),\n unit,\n );\n }\n}\n\nexport function isSectionedResult(\n result: WordCounterResult | SectionedResult,\n): result is SectionedResult {\n return \"section\" in result;\n}\n\nfunction toDisplayPath(inputPath: string): string {\n const relative = relativePath(process.cwd(), inputPath);\n if (relative && !relative.startsWith(\"..\")) {\n return relative || \".\";\n }\n return inputPath;\n}\n\nexport function reportSkipped(skipped: BatchSkip[]): void {\n if (skipped.length === 0) {\n return;\n }\n\n console.error(pc.yellow(`Skipped ${skipped.length} path(s):`));\n for (const item of skipped) {\n console.error(pc.yellow(`- ${toDisplayPath(item.path)} (${item.reason})`));\n }\n}\n\nexport function renderPerFileStandard(\n summary: BatchSummary,\n labels: TotalLabels,\n resolveTotalOfOverride?: (\n result: WordCounterResult | SectionedResult,\n ) => TotalOfOverride | undefined,\n): void {\n for (const file of summary.files) {\n console.log(pc.bold(`[File] ${toDisplayPath(file.path)}`));\n if (isSectionedResult(file.result)) {\n renderStandardSectionedResult(file.result, labels, resolveTotalOfOverride?.(file.result));\n continue;\n }\n\n renderStandardResult(file.result, labels.overall, resolveTotalOfOverride?.(file.result));\n }\n\n console.log(pc.bold(`[Merged] ${summary.files.length} file(s)`));\n if (isSectionedResult(summary.aggregate)) {\n renderStandardSectionedResult(\n summary.aggregate,\n labels,\n resolveTotalOfOverride?.(summary.aggregate),\n );\n return;\n }\n\n renderStandardResult(\n summary.aggregate,\n labels.overall,\n resolveTotalOfOverride?.(summary.aggregate),\n );\n}\n","import type { SectionedResult } from \"../../markdown\";\nimport type { BatchSummary } from \"../types\";\nimport type { WordCounterResult } from \"../../wc\";\n\nfunction normalizeWordCounterResultBase(result: WordCounterResult): WordCounterResult {\n result.total = result.counts?.words ?? result.total;\n delete result.counts;\n\n if (result.breakdown.mode === \"collector\") {\n delete result.breakdown.nonWords;\n return result;\n }\n\n if (result.breakdown.mode === \"char\" || result.breakdown.mode === \"char-collector\") {\n for (const item of result.breakdown.items) {\n const nonWordCount =\n (item.nonWords?.counts.emoji ?? 0) +\n (item.nonWords?.counts.symbols ?? 0) +\n (item.nonWords?.counts.punctuation ?? 0) +\n (item.nonWords?.counts.whitespace ?? 0);\n item.chars = Math.max(0, item.chars - nonWordCount);\n delete item.nonWords;\n }\n return result;\n }\n\n for (const item of result.breakdown.items) {\n delete item.nonWords;\n }\n\n return result;\n}\n\nfunction normalizeSectionedResultBase(result: SectionedResult): SectionedResult {\n let total = 0;\n for (const item of result.items) {\n normalizeWordCounterResultBase(item.result);\n total += item.result.total;\n }\n result.total = total;\n return result;\n}\n\nexport function normalizeResultBase(\n result: WordCounterResult | SectionedResult,\n): WordCounterResult | SectionedResult {\n if (\"section\" in result) {\n return normalizeSectionedResultBase(result);\n }\n return normalizeWordCounterResultBase(result);\n}\n\nexport function normalizeBatchSummaryBase(summary: BatchSummary): BatchSummary {\n for (const file of summary.files) {\n normalizeResultBase(file.result);\n }\n normalizeResultBase(summary.aggregate);\n return summary;\n}\n","import type { SectionedResult } from \"../../markdown\";\nimport { mergeDetectorDebugSummaries } from \"../../detector/debug\";\nimport { runBatchCount } from \"../batch/run\";\nimport {\n clampRequestedJobs,\n formatJobsAdvisoryWarning,\n resolveBatchJobsLimit,\n} from \"../batch/jobs/limits\";\nimport { resolveBatchJobsStrategy } from \"../batch/jobs/strategy\";\nimport type { DebugChannel } from \"../debug/channel\";\nimport { buildDebugSection } from \"../output/debug-json\";\nimport {\n getTotalLabels,\n isSectionedResult,\n renderPerFileStandard,\n renderStandardResult,\n renderStandardSectionedResult,\n reportSkipped,\n} from \"../output/render\";\nimport { normalizeBatchSummaryBase } from \"../output/normalize-base\";\nimport { buildDirectoryExtensionFilter } from \"../path/filter\";\nimport { createBatchProgressReporter } from \"../progress/reporter\";\nimport { resolveTotalOfOverride, type TotalOfOverride } from \"../total-of\";\nimport type { BatchOptions } from \"../types\";\nimport type { WordCounterResult } from \"../../wc\";\nimport { resolveBatchScope } from \"./options\";\nimport type { CliActionOptions, ResolvedCountRunOptions, RunCliOptions } from \"./types\";\nimport pc from \"picocolors\";\n\ntype ExecuteBatchCountOptions = {\n argv: string[];\n options: CliActionOptions;\n runtime: RunCliOptions;\n resolved: ResolvedCountRunOptions;\n debug: DebugChannel;\n teeEnabled: boolean;\n};\n\nexport async function executeBatchCount({\n argv,\n options,\n runtime,\n resolved,\n debug,\n teeEnabled,\n}: ExecuteBatchCountOptions): Promise<void> {\n const warningsEnabled = !options.quietWarnings;\n const emitWarning = (message: string): void => {\n if (!warningsEnabled) {\n return;\n }\n const warningLine = message.startsWith(\"Warning:\") ? message : `Warning: ${message}`;\n console.error(pc.yellow(warningLine));\n };\n\n const batchOptions: BatchOptions = {\n scope: resolveBatchScope(argv),\n pathMode: options.pathMode,\n recursive: options.recursive,\n quietSkips: Boolean(options.quietSkips),\n directoryRegexPattern: options.regex,\n };\n\n const extensionFilter = buildDirectoryExtensionFilter(options.includeExt, options.excludeExt);\n const requestedJobs = options.jobs;\n const jobsLimit = resolveBatchJobsLimit();\n const jobs = clampRequestedJobs(requestedJobs, jobsLimit);\n if (requestedJobs > jobsLimit.suggestedMaxJobs) {\n emitWarning(formatJobsAdvisoryWarning(requestedJobs, jobs, jobsLimit));\n }\n const jobsStrategy = resolveBatchJobsStrategy(jobs);\n\n const debugEnabled = Boolean(options.debug);\n const mirrorDebugToTerminal = debugEnabled && (!debug.reportPath || teeEnabled);\n const summary = await runBatchCount({\n pathInputs: options.path ?? [],\n batchOptions,\n extensionFilter,\n detectBinary: options.pathDetectBinary,\n section: options.section,\n wcOptions: resolved.wcOptions,\n preserveCollectorSegments: options.format === \"json\",\n detectorEvidence: Boolean(options.detectorEvidence),\n debug,\n progressReporter: createBatchProgressReporter({\n enabled: options.format === \"standard\" && options.progressMode !== \"off\",\n stream: runtime.stderr ?? process.stderr,\n clearOnFinish: !(mirrorDebugToTerminal || options.keepProgress),\n }),\n jobs,\n jobsStrategy,\n emitWarning,\n });\n\n const showSkipDiagnostics = debugEnabled && !batchOptions.quietSkips;\n const showSkipItems = showSkipDiagnostics && Boolean(options.verbose);\n debug.emit(\"batch.skips.policy\", {\n enabled: showSkipDiagnostics,\n items: showSkipItems,\n quietSkips: batchOptions.quietSkips,\n });\n if (showSkipDiagnostics) {\n debug.emit(\"batch.skips.report\", {\n count: summary.skipped.length,\n });\n if (showSkipItems) {\n for (const skip of summary.skipped) {\n debug.emit(\n \"batch.skips.item\",\n {\n path: skip.path,\n reason: skip.reason,\n },\n { verbosity: \"verbose\" },\n );\n }\n }\n\n if (mirrorDebugToTerminal) {\n reportSkipped(summary.skipped);\n }\n }\n\n if (summary.files.length === 0) {\n throw new Error(\"No readable text-like inputs were found from --path.\");\n }\n\n let aggregateTotalOfOverride: TotalOfOverride | undefined;\n let totalOfOverridesByResult: WeakMap<object, TotalOfOverride> | undefined;\n if (resolved.totalOfParts && resolved.totalOfParts.length > 0) {\n totalOfOverridesByResult = new WeakMap<object, TotalOfOverride>();\n const aggregateOverride = resolveTotalOfOverride(summary.aggregate, resolved.totalOfParts);\n if (aggregateOverride) {\n totalOfOverridesByResult.set(summary.aggregate as object, aggregateOverride);\n aggregateTotalOfOverride = aggregateOverride;\n }\n\n for (const file of summary.files) {\n const fileOverride = resolveTotalOfOverride(file.result, resolved.totalOfParts);\n if (!fileOverride) {\n continue;\n }\n totalOfOverridesByResult.set(file.result as object, fileOverride);\n }\n } else {\n aggregateTotalOfOverride = resolveTotalOfOverride(summary.aggregate, resolved.totalOfParts);\n }\n\n if (resolved.shouldNormalizeBaseOutput) {\n normalizeBatchSummaryBase(summary);\n }\n\n if (!aggregateTotalOfOverride && totalOfOverridesByResult) {\n aggregateTotalOfOverride = totalOfOverridesByResult.get(summary.aggregate as object);\n }\n\n if (options.format === \"raw\") {\n console.log(aggregateTotalOfOverride?.total ?? summary.aggregate.total);\n return;\n }\n\n if (options.format === \"json\") {\n const spacing = options.pretty ? 2 : 0;\n const aggregateDetectorDebug = mergeDetectorDebugSummaries(\n summary.files.map((file) => file.debug?.detector),\n );\n\n if (batchOptions.scope === \"per-file\") {\n const skipped = showSkipDiagnostics ? summary.skipped : undefined;\n const fileEntries = summary.files.map((file) => {\n const base = {\n path: file.path,\n result: file.result,\n ...(options.debug && file.debug\n ? { debug: buildDebugSection({ detector: file.debug.detector }) }\n : {}),\n };\n\n if (!resolved.totalOfParts || resolved.totalOfParts.length === 0) {\n return base;\n }\n\n const fileOverride =\n totalOfOverridesByResult?.get(file.result as object) ??\n resolveTotalOfOverride(file.result, resolved.totalOfParts);\n if (!fileOverride) {\n return base;\n }\n\n return {\n ...base,\n meta: {\n totalOf: fileOverride.parts,\n totalOfOverride: fileOverride.total,\n },\n };\n });\n const meta =\n resolved.totalOfParts && resolved.totalOfParts.length > 0\n ? {\n totalOf: resolved.totalOfParts,\n aggregateTotalOfOverride: aggregateTotalOfOverride?.total ?? summary.aggregate.total,\n }\n : undefined;\n const payload = {\n scope: \"per-file\",\n files: fileEntries,\n ...(skipped ? { skipped } : {}),\n ...(options.debug\n ? {\n debug: buildDebugSection({\n skipped,\n detector: aggregateDetectorDebug,\n }),\n }\n : {}),\n aggregate: summary.aggregate,\n ...(meta ? { meta } : {}),\n };\n console.log(JSON.stringify(payload, null, spacing));\n return;\n }\n\n if (!aggregateTotalOfOverride) {\n console.log(\n JSON.stringify(\n {\n ...summary.aggregate,\n ...(options.debug\n ? {\n debug: buildDebugSection({\n detector: aggregateDetectorDebug,\n }),\n }\n : {}),\n },\n null,\n spacing,\n ),\n );\n return;\n }\n console.log(\n JSON.stringify(\n {\n ...summary.aggregate,\n meta: {\n totalOf: aggregateTotalOfOverride.parts,\n totalOfOverride: aggregateTotalOfOverride.total,\n },\n ...(options.debug\n ? {\n debug: buildDebugSection({\n detector: aggregateDetectorDebug,\n }),\n }\n : {}),\n },\n null,\n spacing,\n ),\n );\n return;\n }\n\n const labels = getTotalLabels(options.mode, resolved.requestedNonWords);\n const totalOfResolver =\n resolved.totalOfParts && resolved.totalOfParts.length > 0\n ? (result: WordCounterResult | SectionedResult) =>\n totalOfOverridesByResult?.get(result as object) ??\n resolveTotalOfOverride(result, resolved.totalOfParts)\n : undefined;\n\n if (batchOptions.scope === \"per-file\") {\n renderPerFileStandard(summary, labels, totalOfResolver);\n return;\n }\n\n if (isSectionedResult(summary.aggregate)) {\n renderStandardSectionedResult(summary.aggregate, labels, aggregateTotalOfOverride);\n return;\n }\n\n renderStandardResult(summary.aggregate, labels.overall, aggregateTotalOfOverride);\n}\n","async function readStdin(): Promise<string> {\n if (process.stdin.isTTY) {\n return \"\";\n }\n\n return new Promise<string>((resolve, reject) => {\n const chunks: string[] = [];\n process.stdin.setEncoding(\"utf8\");\n process.stdin.on(\"data\", (chunk) => chunks.push(String(chunk)));\n process.stdin.on(\"end\", () => resolve(chunks.join(\"\")));\n process.stdin.on(\"error\", (error) => reject(error));\n process.stdin.resume();\n });\n}\n\nexport async function resolveInput(textTokens: string[]): Promise<string> {\n if (textTokens.length > 0) {\n return textTokens.join(\" \");\n }\n\n return readStdin();\n}\n","import type { SectionedResult } from \"../../markdown\";\nimport { buildDebugSection } from \"../output/debug-json\";\nimport { countSections } from \"../../markdown\";\nimport { countSectionsWithDetector, wordCounterWithDetector } from \"../../detector\";\nimport { createDetectorDebugSummary } from \"../../detector/debug\";\nimport {\n getTotalLabels,\n isSectionedResult,\n renderStandardResult,\n renderStandardSectionedResult,\n} from \"../output/render\";\nimport { normalizeResultBase } from \"../output/normalize-base\";\nimport { resolveTotalOfOverride } from \"../total-of\";\nimport wordCounter, { type WordCounterResult } from \"../../wc\";\nimport { resolveInput } from \"./input\";\nimport { formatInputReadError } from \"./options\";\nimport type { DebugChannel } from \"../debug/channel\";\nimport type { CliActionOptions, ResolvedCountRunOptions } from \"./types\";\n\ntype ExecuteSingleCountOptions = {\n textTokens: string[];\n options: CliActionOptions;\n resolved: ResolvedCountRunOptions;\n debug: DebugChannel;\n};\n\nexport async function executeSingleCount({\n textTokens,\n options,\n resolved,\n debug,\n}: ExecuteSingleCountOptions): Promise<void> {\n debug.emit(\"runtime.single.start\", {\n detectorMode: resolved.detectorMode,\n format: options.format,\n section: options.section,\n });\n\n let input: string;\n try {\n input = await resolveInput(textTokens);\n } catch (error) {\n throw new Error(formatInputReadError(error));\n }\n\n const trimmed = input.trim();\n if (!trimmed) {\n throw new Error(\"No input provided. Pass text, pipe stdin, or use --path.\");\n }\n\n const detectorDebugSummary =\n resolved.detectorMode === \"wasm\"\n ? createDetectorDebugSummary(resolved.detectorMode)\n : undefined;\n const detectorDebug =\n detectorDebugSummary && debug.enabled\n ? {\n emit: debug.emit,\n summary: detectorDebugSummary,\n ...(options.detectorEvidence\n ? {\n evidence: {\n verbosity: debug.verbosity,\n mode: resolved.wcOptions.mode ?? \"chunk\",\n section: options.section,\n },\n }\n : {}),\n }\n : undefined;\n\n const result: WordCounterResult | SectionedResult = resolved.useSection\n ? resolved.detectorMode === \"regex\"\n ? countSections(trimmed, options.section, resolved.wcOptions)\n : await countSectionsWithDetector(trimmed, options.section, {\n ...resolved.wcOptions,\n detector: resolved.detectorMode,\n detectorDebug,\n })\n : resolved.detectorMode === \"regex\"\n ? wordCounter(trimmed, resolved.wcOptions)\n : await wordCounterWithDetector(trimmed, {\n ...resolved.wcOptions,\n detector: resolved.detectorMode,\n detectorDebug,\n });\n const totalOfOverride = resolveTotalOfOverride(result, resolved.totalOfParts);\n const displayResult = resolved.shouldNormalizeBaseOutput ? normalizeResultBase(result) : result;\n\n debug.emit(\"runtime.single.complete\", {\n detectorMode: resolved.detectorMode,\n sectioned: resolved.useSection,\n total: displayResult.total,\n });\n\n if (options.format === \"raw\") {\n console.log(totalOfOverride?.total ?? displayResult.total);\n return;\n }\n\n if (options.format === \"json\") {\n const spacing = options.pretty ? 2 : 0;\n const debugSection =\n options.debug && detectorDebugSummary && detectorDebugSummary.windowsTotal > 0\n ? buildDebugSection({ detector: detectorDebugSummary })\n : undefined;\n if (!totalOfOverride && !debugSection) {\n console.log(JSON.stringify(displayResult, null, spacing));\n return;\n }\n console.log(\n JSON.stringify(\n {\n ...displayResult,\n ...(totalOfOverride\n ? {\n meta: {\n totalOf: totalOfOverride.parts,\n totalOfOverride: totalOfOverride.total,\n },\n }\n : {}),\n ...(debugSection ? { debug: debugSection } : {}),\n },\n null,\n spacing,\n ),\n );\n return;\n }\n\n const labels = getTotalLabels(options.mode, resolved.requestedNonWords);\n if (isSectionedResult(displayResult)) {\n renderStandardSectionedResult(displayResult, labels, totalOfOverride);\n return;\n }\n\n renderStandardResult(displayResult, labels.overall, totalOfOverride);\n}\n","import { Command } from \"commander\";\nimport {\n applyConfigToCountOptions,\n deriveCountCliSources,\n deriveInitialCountProgressMode,\n resolveWordCounterConfig,\n} from \"./cli/config\";\nimport { createDebugChannel } from \"./cli/debug/channel\";\nimport { executeDoctorCommand, isExplicitDoctorInvocation } from \"./cli/doctor/run\";\nimport { executeInspectCommand, isExplicitInspectInvocation } from \"./cli/inspect/run\";\nimport { configureProgramOptions } from \"./cli/program/options\";\nimport { getFormattedVersionLabel } from \"./cli/program/version\";\nimport { resolveBatchJobsLimit } from \"./cli/batch/jobs/limits\";\nimport { executeBatchCount } from \"./cli/runtime/batch\";\nimport { WASM_DETECTOR_RUNTIME_UNAVAILABLE_MESSAGE } from \"./detector\";\nimport {\n hasPathInput,\n resolveCountRunOptions,\n resolveDebugReportPathOption,\n validateStandalonePrintJobsLimitUsage,\n validateSingleRegexOptionUsage,\n} from \"./cli/runtime/options\";\nimport { executeSingleCount } from \"./cli/runtime/single\";\nimport type { CliActionOptions, RunCliOptions } from \"./cli/runtime/types\";\nimport type { WordCounterMode } from \"./wc\";\nimport { normalizeMode } from \"./wc/mode\";\nimport pc from \"picocolors\";\n\nfunction emitConfigNotes(notes: string[]): void {\n for (const note of notes) {\n const warningLine = note.startsWith(\"Warning:\") ? note : `Warning: ${note}`;\n console.error(pc.yellow(warningLine));\n }\n}\n\nexport async function runCli(\n argv: string[] = process.argv,\n runtime: RunCliOptions = {},\n): Promise<void> {\n if (isExplicitDoctorInvocation(argv)) {\n await executeDoctorCommand({\n argv,\n runtime: runtime.doctor,\n });\n return;\n }\n\n if (isExplicitInspectInvocation(argv)) {\n await executeInspectCommand({ argv, runtime });\n return;\n }\n\n const program = new Command();\n const parseMode = (value: string): WordCounterMode => {\n const normalized = normalizeMode(value);\n if (!normalized) {\n throw new Error(`Invalid mode: ${value}`);\n }\n return normalized;\n };\n\n program\n .name(\"word-counter\")\n .description(\"Locale-aware word counting powered by Intl.Segmenter.\")\n .version(getFormattedVersionLabel(), \"-v, --version\", \"output the version number\")\n .addHelpText(\n \"after\",\n \"\\nCommands:\\n inspect [options] [text...] inspect detector behavior without count output\\n doctor [options] report runtime diagnostics for this host\",\n );\n\n configureProgramOptions(program, parseMode);\n\n program.action(\n async (textTokens: string[], rawOptions: CliActionOptions & { progress: boolean }) => {\n if (rawOptions.printJobsLimit) {\n try {\n validateStandalonePrintJobsLimitUsage(argv);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n program.error(pc.red(message));\n return;\n }\n\n console.log(JSON.stringify(resolveBatchJobsLimit()));\n return;\n }\n\n let options: CliActionOptions = {\n ...rawOptions,\n pathDetectBinary: rawOptions.pathDetectBinary ?? true,\n progressMode: deriveInitialCountProgressMode(program, rawOptions.progress),\n };\n\n try {\n const resolvedConfig = await resolveWordCounterConfig({\n env: runtime.env,\n cwd: runtime.cwd,\n });\n options = applyConfigToCountOptions(\n options,\n resolvedConfig.config,\n deriveCountCliSources(program),\n );\n if (!options.quietWarnings) {\n emitConfigNotes(resolvedConfig.notes);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n program.error(pc.red(message));\n return;\n }\n\n const debugEnabled = Boolean(options.debug);\n const debugReportPath = resolveDebugReportPathOption(options.debugReport);\n const debugReportEnabled = options.debugReport !== undefined && options.debugReport !== false;\n\n if (options.verbose && !debugEnabled) {\n program.error(pc.red(\"`--verbose` requires `--debug`.\"));\n return;\n }\n\n if (options.detectorEvidence && !debugEnabled) {\n program.error(pc.red(\"`--detector-evidence` requires `--debug`.\"));\n return;\n }\n\n if (options.detectorEvidence && options.detector !== \"wasm\") {\n program.error(pc.red(\"`--detector-evidence` requires `--detector wasm`.\"));\n return;\n }\n\n if (debugReportEnabled && !debugEnabled) {\n program.error(pc.red(\"`--debug-report` requires `--debug`.\"));\n return;\n }\n\n const teeEnabled = Boolean(options.debugReportTee || options.debugTee);\n\n if (teeEnabled && !debugReportEnabled) {\n program.error(\n pc.red(\"`--debug-report-tee` (alias: `--debug-tee`) requires `--debug-report`.\"),\n );\n return;\n }\n\n try {\n validateSingleRegexOptionUsage(argv);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n program.error(pc.red(message));\n return;\n }\n\n let debug;\n try {\n debug = createDebugChannel({\n enabled: debugEnabled,\n verbosity: options.verbose ? \"verbose\" : \"compact\",\n report: debugReportEnabled\n ? {\n path: debugReportPath,\n tee: teeEnabled,\n autogeneratedNamePrefix: options.detectorEvidence\n ? \"wc-detector-evidence\"\n : \"wc-debug\",\n }\n : undefined,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n program.error(pc.red(`Failed to initialize debug diagnostics: ${message}`));\n return;\n }\n\n try {\n const resolved = resolveCountRunOptions(options);\n if (hasPathInput(options.path)) {\n await executeBatchCount({\n argv,\n options,\n runtime,\n resolved,\n debug,\n teeEnabled,\n });\n return;\n }\n\n await executeSingleCount({\n textTokens,\n options,\n resolved,\n debug,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (message === \"No input provided. Pass text, pipe stdin, or use --path.\") {\n program.error(pc.red(message));\n return;\n }\n if (message === \"No readable text-like inputs were found from --path.\") {\n program.error(pc.red(message));\n return;\n }\n if (message === WASM_DETECTOR_RUNTIME_UNAVAILABLE_MESSAGE) {\n console.error(pc.red(message));\n process.exitCode = 1;\n return;\n }\n program.error(message);\n } finally {\n await debug.close();\n }\n },\n );\n\n await program.parseAsync(argv);\n if (process.exitCode === undefined) {\n process.exitCode = 0;\n }\n}\n\nexport { buildBatchSummary } from \"./cli/batch/aggregate\";\nexport { loadBatchInputs } from \"./cli/path/load\";\nexport { resolveBatchFilePaths } from \"./cli/path/resolve\";\n","import { runCli } from \"./command\";\n\nrunCli().catch((error) => {\n const message = error instanceof Error ? error.message : String(error);\n console.error(\"Failed to run CLI:\", message);\n process.exitCode = 1;\n});\n"],"x_google_ignoreList":[15],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAa,uBAAuB;AACpC,MAAa,yBAAkD;CAAC;CAAQ;CAAS;CAAO;AACxD,uBAAuB,KACpD,WAAW,GAAG,qBAAqB,GAAG,SACxC;AAED,MAAa,yBAAkD,CAAC,SAAS,OAAO;AAChF,MAAa,kCAAsE;CACjF;CACA;CACA;CACA;CACD;AACD,MAAa,0BAA+C,CAAC,QAAQ,SAAS;AAC9E,MAAa,8BAA6D;CAAC;CAAQ;CAAM;CAAM;AAC/F,MAAa,0BAAqD,CAAC,QAAQ,QAAQ;AACnF,MAAa,8B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OAAO,UAAU;CACxB,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AACtE,SAAQ,MAAM,sBAAsB,QAAQ;AAC5C,SAAQ,WAAW;EACnB"}
|
|
1
|
+
{"version":3,"file":"bin.mjs","names":["isRecord","ensureObject","stripInlineComment","resolvePath","pc","pc","resolveLatinHintRules","HARD_BOUNDARY_REGEX","LATIN_PROMOTION_BREAK_REGEX","findLastLatinPromotionBreakIndex","mergeAdjacentChunks","getNonWordTotal","collectNonWordsAggregate","normalizeText","buildPerKeyItems","wordCounter","buildSingleItem","sumTotals","wordCounter","resolvePath","resolvePath","emitConfigNotes","pc","resolvePath","pc","wordCounter","wordCounter","wordCounter","pc","relative","relativePath","pc","wordCounter","pc"],"sources":["../../src/cli/config/schema.ts","../../src/cli/config/discover.ts","../../src/cli/config/apply.ts","../../src/cli/total-of.ts","../../src/cli/config/errors.ts","../../src/cli/config/normalize.ts","../../src/cli/config/env.ts","../../src/cli/config/merge.ts","../../src/cli/config/jsonc.ts","../../src/cli/config/toml-tokens.ts","../../src/cli/config/toml.ts","../../src/cli/config/parse.ts","../../src/cli/config/resolve.ts","../../src/cli/config/sources.ts","../../src/cli/debug/channel.ts","../../node_modules/picocolors/picocolors.js","../../src/cli/program/version-embedded.ts","../../src/cli/batch/jobs/limits.ts","../../src/cli/batch/jobs/load-count-worker.ts","../../src/cli/doctor/checks.ts","../../src/cli/doctor/render.ts","../../src/cli/doctor/run.ts","../../src/markdown/toml/arrays.ts","../../src/markdown/toml/keys.ts","../../src/markdown/toml/strings.ts","../../src/markdown/toml/values.ts","../../src/markdown/toml/parse-frontmatter.ts","../../src/markdown/parse-markdown.ts","../../src/wc/segmenter.ts","../../src/utils/append-all.ts","../../src/wc/non-words.ts","../../src/wc/analyze.ts","../../src/wc/mode.ts","../../src/wc/latin-hints.ts","../../src/wc/locale-detect.ts","../../src/wc/segment.ts","../../src/wc/wc.ts","../../src/wc/index.ts","../../src/markdown/section-count.ts","../../src/detector/debug.ts","../../src/detector/inspect-helpers.ts","../../src/detector/none.ts","../../src/detector/result-builder.ts","../../src/detector/sections.ts","../../src/detector/policy.ts","../../src/detector/wasm-inspect.ts","../../src/detector/whatlang-map.ts","../../src/detector/wasm-presegment.ts","../../src/detector/whatlang-wasm.ts","../../src/detector/wasm-engine.ts","../../src/detector/wasm-resolution.ts","../../src/detector/wasm-windows.ts","../../src/detector/wasm.ts","../../src/detector/inspect.ts","../../src/detector/index.ts","../../src/cli/path/filter.ts","../../src/cli/path/load.ts","../../src/cli/path/resolve-debug.ts","../../src/cli/path/resolve-directory.ts","../../src/cli/path/resolve.ts","../../src/cli/runtime/options.ts","../../src/cli/inspect/input.ts","../../src/cli/inspect/render.ts","../../src/cli/inspect/batch.ts","../../src/cli/inspect/help.ts","../../src/cli/inspect/parse.ts","../../src/cli/inspect/single.ts","../../src/cli/inspect/run.ts","../../src/cli/program/options.ts","../../src/cli/program/version.ts","../../src/cli/batch/aggregate-compact.ts","../../src/cli/batch/aggregate-word-counter.ts","../../src/cli/batch/aggregate-sections.ts","../../src/cli/batch/aggregate.ts","../../src/cli/batch/jobs/queue.ts","../../src/cli/batch/jobs/read-input.ts","../../src/cli/batch/jobs/load-count.ts","../../src/cli/batch/jobs/render.ts","../../src/cli/progress/reporter.ts","../../src/cli/batch/run.ts","../../src/cli/batch/jobs/strategy.ts","../../src/cli/output/debug-json.ts","../../src/utils/show-singular-or-plural-word.ts","../../src/cli/output/render.ts","../../src/cli/output/normalize-base.ts","../../src/cli/runtime/batch.ts","../../src/cli/runtime/input.ts","../../src/cli/runtime/single.ts","../../src/command.ts","../../src/bin.ts"],"sourcesContent":["import type { DetectorContentGateMode, DetectorMode } from \"../../detector\";\nimport type { TotalOfPart } from \"../total-of\";\nimport type { PathMode } from \"../types\";\nimport type { ConfigFormat, ConfigLogLevel, ConfigLogVerbosity, ConfigProgressMode } from \"./types\";\n\nexport const CONFIG_FILE_BASENAME = \"wc-intl-seg.config\";\nexport const CONFIG_FORMAT_PRIORITY: readonly ConfigFormat[] = [\"toml\", \"jsonc\", \"json\"];\nexport const CONFIG_FILENAMES = CONFIG_FORMAT_PRIORITY.map(\n (format) => `${CONFIG_FILE_BASENAME}.${format}`,\n);\n\nexport const CONFIG_DETECTOR_VALUES: readonly DetectorMode[] = [\"regex\", \"wasm\"];\nexport const CONFIG_CONTENT_GATE_MODE_VALUES: readonly DetectorContentGateMode[] = [\n \"default\",\n \"strict\",\n \"loose\",\n \"off\",\n];\nexport const CONFIG_PATH_MODE_VALUES: readonly PathMode[] = [\"auto\", \"manual\"];\nexport const CONFIG_PROGRESS_MODE_VALUES: readonly ConfigProgressMode[] = [\"auto\", \"on\", \"off\"];\nexport const CONFIG_LOG_LEVEL_VALUES: readonly ConfigLogLevel[] = [\"info\", \"debug\"];\nexport const CONFIG_LOG_VERBOSITY_VALUES: readonly ConfigLogVerbosity[] = [\"compact\", \"verbose\"];\n\nexport const CONFIG_TOTAL_OF_VALUES: readonly TotalOfPart[] = [\n \"words\",\n \"emoji\",\n \"symbols\",\n \"punctuation\",\n \"whitespace\",\n];\n","import { stat } from \"node:fs/promises\";\nimport { join, win32 } from \"node:path\";\nimport { CONFIG_FILE_BASENAME, CONFIG_FILENAMES, CONFIG_FORMAT_PRIORITY } from \"./schema\";\nimport type {\n ConfigDiscoveryResult,\n ConfigFormat,\n ConfigScope,\n DiscoverConfigOptions,\n DiscoveredConfigFile,\n ResolveConfigDirectoryOptions,\n} from \"./types\";\n\ntype UserConfigDirectoryCandidate = {\n directory: string;\n kind: \"primary\" | \"legacy-macos\" | \"legacy-windows\";\n};\n\nasync function fileExists(path: string): Promise<boolean> {\n try {\n const metadata = await stat(path);\n return metadata.isFile();\n } catch {\n return false;\n }\n}\n\nfunction createIgnoredSiblingNote(\n scope: ConfigScope,\n selectedPath: string,\n ignoredSiblingPaths: string[],\n): string | undefined {\n if (ignoredSiblingPaths.length === 0) {\n return undefined;\n }\n\n return [\n `Using ${scope} config file \"${selectedPath}\".`,\n `Ignoring lower-priority sibling config files: ${ignoredSiblingPaths.join(\", \")}.`,\n ].join(\" \");\n}\n\nexport function resolveUserConfigDirectory(\n options: ResolveConfigDirectoryOptions = {},\n): string | undefined {\n return resolveUserConfigDirectories(options)[0]?.directory;\n}\n\nfunction resolveUserConfigDirectories(\n options: ResolveConfigDirectoryOptions = {},\n): UserConfigDirectoryCandidate[] {\n const platform = options.platform ?? process.platform;\n const env = options.env ?? process.env;\n const homeDir = env.HOME ?? env.USERPROFILE;\n\n if (platform === \"win32\") {\n const candidates: UserConfigDirectoryCandidate[] = [];\n if (homeDir) {\n candidates.push({\n directory: win32.join(homeDir, \".config\"),\n kind: \"primary\",\n });\n }\n if (env.APPDATA) {\n candidates.push({\n directory: env.APPDATA,\n kind: \"legacy-windows\",\n });\n }\n return candidates;\n }\n\n if (platform === \"darwin\") {\n const candidates: UserConfigDirectoryCandidate[] = [];\n if (env.XDG_CONFIG_HOME) {\n candidates.push({\n directory: env.XDG_CONFIG_HOME,\n kind: \"primary\",\n });\n }\n if (homeDir) {\n candidates.push({\n directory: join(homeDir, \".config\"),\n kind: \"primary\",\n });\n candidates.push({\n directory: join(homeDir, \"Library\", \"Application Support\"),\n kind: \"legacy-macos\",\n });\n }\n return candidates;\n }\n\n const directory = env.XDG_CONFIG_HOME ?? (homeDir ? join(homeDir, \".config\") : undefined);\n return directory\n ? [\n {\n directory,\n kind: \"primary\",\n },\n ]\n : [];\n}\n\nexport async function discoverConfigFileInDirectory(\n directory: string,\n scope: ConfigScope,\n): Promise<DiscoveredConfigFile | undefined> {\n const existing: Array<{ format: ConfigFormat; path: string }> = [];\n\n for (const format of CONFIG_FORMAT_PRIORITY) {\n const path = join(directory, `${CONFIG_FILE_BASENAME}.${format}`);\n if (await fileExists(path)) {\n existing.push({ format, path });\n }\n }\n\n if (existing.length === 0) {\n return undefined;\n }\n\n const selected = existing[0]!;\n const ignoredSiblingPaths = existing.slice(1).map((item) => item.path);\n const note = createIgnoredSiblingNote(scope, selected.path, ignoredSiblingPaths);\n\n return {\n scope,\n directory,\n path: selected.path,\n format: selected.format,\n ignoredSiblingPaths,\n notes: note ? [note] : [],\n };\n}\n\nexport async function discoverConfigFiles(\n options: DiscoverConfigOptions = {},\n): Promise<ConfigDiscoveryResult> {\n const cwd = options.cwd ?? process.cwd();\n const userDirectories = resolveUserConfigDirectories(options);\n\n const currentWorkingDirectory = await discoverConfigFileInDirectory(cwd, \"cwd\");\n let user: DiscoveredConfigFile | undefined;\n const discoveredFallbackUsers: DiscoveredConfigFile[] = [];\n\n for (const candidate of userDirectories) {\n const discovered = await discoverConfigFileInDirectory(candidate.directory, \"user\");\n if (!discovered) {\n continue;\n }\n\n if (!user) {\n user = discovered;\n if (candidate.kind === \"legacy-macos\") {\n user.notes.push(\n `Using legacy macOS user config location \"${discovered.directory}\". Migrate this config to \"${resolveUserConfigDirectory(options)}\" to follow the current default path.`,\n );\n }\n if (candidate.kind === \"legacy-windows\") {\n user.notes.push(\n `Using legacy Windows user config location \"${discovered.directory}\". Migrate this config to \"${resolveUserConfigDirectory(options)}\" to follow the current default path.`,\n );\n }\n continue;\n }\n\n discoveredFallbackUsers.push(discovered);\n }\n\n if (user) {\n for (const fallback of discoveredFallbackUsers) {\n user.notes.push(\n `Ignoring fallback user config file \"${fallback.path}\" because a higher-priority user config file was found at \"${user.path}\".`,\n );\n }\n }\n\n return {\n ...(user ? { user } : {}),\n ...(currentWorkingDirectory ? { cwd: currentWorkingDirectory } : {}),\n };\n}\n\nexport { CONFIG_FILENAMES };\n","import type { CliActionOptions } from \"../runtime/types\";\nimport type { ParsedInspectInvocation } from \"../inspect/types\";\nimport type { WordCounterConfig } from \"./types\";\n\nexport type CountCliSources = {\n detector: boolean;\n contentGate: boolean;\n pathMode: boolean;\n recursive: boolean;\n includeExt: boolean;\n excludeExt: boolean;\n totalOf: boolean;\n debug: boolean;\n verbose: boolean;\n debugReport: boolean;\n debugReportTee: boolean;\n progress: boolean;\n quietSkips: boolean;\n};\n\nfunction withConfigQuietSkips(\n currentQuietSkips: boolean | undefined,\n skippedFiles: boolean | undefined,\n): boolean | undefined {\n if (skippedFiles === undefined) {\n return currentQuietSkips;\n }\n\n return skippedFiles ? false : true;\n}\n\nexport function applyConfigToCountOptions(\n options: CliActionOptions,\n config: WordCounterConfig,\n sources: CountCliSources,\n): CliActionOptions {\n const next: CliActionOptions = { ...options };\n\n if (!sources.detector && config.detector !== undefined) {\n next.detector = config.detector;\n }\n\n if (!sources.contentGate && config.contentGate?.mode !== undefined) {\n next.contentGate = config.contentGate.mode;\n }\n\n if (!sources.pathMode && config.path?.mode !== undefined) {\n next.pathMode = config.path.mode;\n }\n\n if (!sources.recursive && config.path?.recursive !== undefined) {\n next.recursive = config.path.recursive;\n }\n\n next.pathDetectBinary = config.path?.detectBinary ?? next.pathDetectBinary ?? true;\n\n if (!sources.includeExt && config.path?.includeExtensions !== undefined) {\n next.includeExt = [...config.path.includeExtensions];\n }\n\n if (!sources.excludeExt && config.path?.excludeExtensions !== undefined) {\n next.excludeExt = [...config.path.excludeExtensions];\n }\n\n if (!sources.totalOf && config.output?.totalOf !== undefined) {\n next.totalOf = [...config.output.totalOf];\n }\n\n if (!sources.debug && config.logging?.level !== undefined) {\n next.debug = config.logging.level === \"debug\";\n }\n\n const debugEnabled = next.debug === true;\n\n if (debugEnabled && !sources.verbose && config.logging?.verbosity !== undefined) {\n next.verbose = config.logging.verbosity === \"verbose\";\n }\n\n if (debugEnabled && !sources.debugReport && config.reporting?.debugReport?.path !== undefined) {\n next.debugReport = config.reporting.debugReport.path;\n }\n\n const debugReportEnabled = next.debugReport !== undefined && next.debugReport !== false;\n\n if (\n debugEnabled &&\n debugReportEnabled &&\n !sources.debugReportTee &&\n config.reporting?.debugReport?.tee !== undefined\n ) {\n next.debugReportTee = config.reporting.debugReport.tee;\n }\n\n if (!sources.progress && config.progress?.mode !== undefined) {\n next.progressMode = config.progress.mode;\n }\n\n if (!sources.quietSkips) {\n next.quietSkips = withConfigQuietSkips(next.quietSkips, config.reporting?.skippedFiles);\n }\n\n return next;\n}\n\nexport function applyConfigToInspectInvocation(\n validated: ParsedInspectInvocation,\n config: WordCounterConfig,\n): ParsedInspectInvocation {\n const next: ParsedInspectInvocation = {\n ...validated,\n includeExt: [...validated.includeExt],\n excludeExt: [...validated.excludeExt],\n sources: { ...validated.sources },\n };\n\n const detectorFromConfig = config.inspect?.detector ?? config.detector;\n if (!next.sources.detector && detectorFromConfig !== undefined) {\n next.detector = detectorFromConfig;\n }\n\n const contentGateFromConfig = config.inspect?.contentGate?.mode ?? config.contentGate?.mode;\n if (!next.sources.contentGate && contentGateFromConfig !== undefined) {\n next.contentGateMode = contentGateFromConfig;\n }\n\n if (!next.sources.pathMode && config.path?.mode !== undefined) {\n next.pathMode = config.path.mode;\n }\n\n if (!next.sources.recursive && config.path?.recursive !== undefined) {\n next.recursive = config.path.recursive;\n }\n\n next.pathDetectBinary = config.path?.detectBinary ?? next.pathDetectBinary ?? true;\n\n if (!next.sources.includeExt && config.path?.includeExtensions !== undefined) {\n next.includeExt = [...config.path.includeExtensions];\n }\n\n if (!next.sources.excludeExt && config.path?.excludeExtensions !== undefined) {\n next.excludeExt = [...config.path.excludeExtensions];\n }\n\n return next;\n}\n","import type { SectionedResult } from \"../markdown\";\nimport type { NonWordCollection, WordCounterResult } from \"../wc\";\n\nexport const TOTAL_OF_PARTS = Object.freeze([\n \"words\",\n \"emoji\",\n \"symbols\",\n \"punctuation\",\n \"whitespace\",\n] as const);\n\nexport type TotalOfPart = (typeof TOTAL_OF_PARTS)[number];\n\nexport type TotalOfOverride = {\n parts: TotalOfPart[];\n total: number;\n};\n\ntype TotalOfCounts = Record<TotalOfPart, number>;\n\nconst TOTAL_OF_PART_ALIASES: Record<string, TotalOfPart> = {\n word: \"words\",\n words: \"words\",\n emoji: \"emoji\",\n emojis: \"emoji\",\n symbol: \"symbols\",\n symbols: \"symbols\",\n punction: \"punctuation\",\n punctuation: \"punctuation\",\n whitespace: \"whitespace\",\n};\n\nfunction createTotalOfCounts(): TotalOfCounts {\n return {\n words: 0,\n emoji: 0,\n symbols: 0,\n punctuation: 0,\n whitespace: 0,\n };\n}\n\nfunction collectNonWordCounts(\n target: TotalOfCounts,\n nonWords: NonWordCollection | undefined,\n): void {\n if (!nonWords) {\n return;\n }\n\n target.emoji += nonWords.counts.emoji;\n target.symbols += nonWords.counts.symbols;\n target.punctuation += nonWords.counts.punctuation;\n target.whitespace += nonWords.counts.whitespace ?? 0;\n}\n\nfunction collectFromWordCounterResult(result: WordCounterResult): TotalOfCounts {\n const counts = createTotalOfCounts();\n counts.words += result.counts?.words ?? result.total;\n\n if (result.breakdown.mode === \"collector\") {\n collectNonWordCounts(counts, result.breakdown.nonWords);\n return counts;\n }\n\n for (const item of result.breakdown.items) {\n collectNonWordCounts(counts, item.nonWords);\n }\n\n return counts;\n}\n\nfunction collectTotalOfCounts(result: WordCounterResult | SectionedResult): TotalOfCounts {\n if (!(\"section\" in result)) {\n return collectFromWordCounterResult(result);\n }\n\n const counts = createTotalOfCounts();\n for (const item of result.items) {\n const itemCounts = collectFromWordCounterResult(item.result);\n for (const part of TOTAL_OF_PARTS) {\n counts[part] += itemCounts[part];\n }\n }\n return counts;\n}\n\nfunction parseTotalOfToken(token: string): TotalOfPart {\n const normalized = token.trim().toLowerCase();\n const canonical = TOTAL_OF_PART_ALIASES[normalized];\n if (canonical) {\n return canonical;\n }\n throw new Error(`Invalid --total-of part: ${token}. Allowed: ${TOTAL_OF_PARTS.join(\", \")}.`);\n}\n\nexport function parseTotalOfOption(value: string): TotalOfPart[] {\n const rawTokens = value\n .split(\",\")\n .map((token) => token.trim())\n .filter((token) => token.length > 0);\n\n if (rawTokens.length === 0) {\n throw new Error(\n `Invalid --total-of value: \"${value}\". Use comma-separated parts from: ${TOTAL_OF_PARTS.join(\", \")}.`,\n );\n }\n\n const parts: TotalOfPart[] = [];\n const seen = new Set<TotalOfPart>();\n for (const token of rawTokens) {\n const parsed = parseTotalOfToken(token);\n if (seen.has(parsed)) {\n continue;\n }\n seen.add(parsed);\n parts.push(parsed);\n }\n\n return parts;\n}\n\nexport function requiresNonWordCollection(parts: readonly TotalOfPart[] | undefined): boolean {\n if (!parts || parts.length === 0) {\n return false;\n }\n return parts.some((part) => part !== \"words\");\n}\n\nexport function requiresWhitespaceCollection(parts: readonly TotalOfPart[] | undefined): boolean {\n if (!parts || parts.length === 0) {\n return false;\n }\n return parts.includes(\"whitespace\");\n}\n\nexport function resolveTotalOfOverride(\n result: WordCounterResult | SectionedResult,\n parts: readonly TotalOfPart[] | undefined,\n): TotalOfOverride | undefined {\n if (!parts || parts.length === 0) {\n return undefined;\n }\n\n const counts = collectTotalOfCounts(result);\n let total = 0;\n for (const part of parts) {\n total += counts[part];\n }\n\n return {\n parts: [...parts],\n total,\n };\n}\n\nexport function formatTotalOfParts(parts: readonly TotalOfPart[]): string {\n return parts.join(\", \");\n}\n","import type { ConfigFormat } from \"./types\";\n\nexport class ConfigValidationError extends Error {\n readonly sourceLabel: string;\n readonly path: string[];\n\n constructor(sourceLabel: string, path: string[], message: string) {\n const suffix = path.length > 0 ? ` at \"${path.join(\".\")}\"` : \"\";\n super(`Invalid config in ${sourceLabel}${suffix}: ${message}`);\n this.name = \"ConfigValidationError\";\n this.sourceLabel = sourceLabel;\n this.path = [...path];\n }\n}\n\nexport class ConfigParseError extends Error {\n readonly sourceLabel: string;\n readonly format: ConfigFormat;\n\n constructor(sourceLabel: string, format: ConfigFormat, message: string) {\n super(`Invalid ${format.toUpperCase()} config in ${sourceLabel}: ${message}`);\n this.name = \"ConfigParseError\";\n this.sourceLabel = sourceLabel;\n this.format = format;\n }\n}\n","import type { DetectorContentGateMode, DetectorMode } from \"../../detector\";\nimport type { TotalOfPart } from \"../total-of\";\nimport type { PathMode } from \"../types\";\nimport { ConfigValidationError } from \"./errors\";\nimport {\n CONFIG_CONTENT_GATE_MODE_VALUES,\n CONFIG_DETECTOR_VALUES,\n CONFIG_LOG_LEVEL_VALUES,\n CONFIG_LOG_VERBOSITY_VALUES,\n CONFIG_PATH_MODE_VALUES,\n CONFIG_PROGRESS_MODE_VALUES,\n CONFIG_TOTAL_OF_VALUES,\n} from \"./schema\";\nimport type {\n ConfigLogLevel,\n ConfigLogVerbosity,\n ConfigProgressMode,\n WordCounterConfig,\n} from \"./types\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction createConfigError(sourceLabel: string, path: string[], message: string): Error {\n return new ConfigValidationError(sourceLabel, path, message);\n}\n\nfunction ensureObject(\n value: unknown,\n sourceLabel: string,\n path: string[],\n): Record<string, unknown> | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!isRecord(value)) {\n throw createConfigError(sourceLabel, path, \"expected an object.\");\n }\n\n return value;\n}\n\nfunction rejectUnknownKeys(\n value: Record<string, unknown>,\n allowedKeys: readonly string[],\n sourceLabel: string,\n path: string[],\n): void {\n for (const key of Object.keys(value)) {\n if (!allowedKeys.includes(key)) {\n throw createConfigError(sourceLabel, [...path, key], \"unknown key.\");\n }\n }\n}\n\nfunction parseBoolean(value: unknown, sourceLabel: string, path: string[]): boolean | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (typeof value !== \"boolean\") {\n throw createConfigError(sourceLabel, path, \"expected a boolean.\");\n }\n\n return value;\n}\n\nfunction parseString(value: unknown, sourceLabel: string, path: string[]): string | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (typeof value !== \"string\") {\n throw createConfigError(sourceLabel, path, \"expected a string.\");\n }\n\n return value;\n}\n\nfunction parseStringArray(\n value: unknown,\n sourceLabel: string,\n path: string[],\n): string[] | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!Array.isArray(value) || value.some((item) => typeof item !== \"string\")) {\n throw createConfigError(sourceLabel, path, \"expected an array of strings.\");\n }\n\n return [...value];\n}\n\nfunction parseEnum<T extends string>(\n value: unknown,\n allowedValues: readonly T[],\n sourceLabel: string,\n path: string[],\n): T | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (typeof value !== \"string\" || !allowedValues.includes(value as T)) {\n throw createConfigError(\n sourceLabel,\n path,\n `expected one of: ${allowedValues.map((item) => `\"${item}\"`).join(\", \")}.`,\n );\n }\n\n return value as T;\n}\n\nfunction parseTotalOf(\n value: unknown,\n sourceLabel: string,\n path: string[],\n): TotalOfPart[] | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!Array.isArray(value) || value.some((item) => typeof item !== \"string\")) {\n throw createConfigError(sourceLabel, path, \"expected an array of strings.\");\n }\n\n const parts: TotalOfPart[] = [];\n for (const item of value) {\n const parsed = parseEnum(item, CONFIG_TOTAL_OF_VALUES, sourceLabel, path);\n if (parsed && !parts.includes(parsed)) {\n parts.push(parsed);\n }\n }\n\n return parts;\n}\n\nfunction normalizeInspectConfig(value: unknown, sourceLabel: string): WordCounterConfig[\"inspect\"] {\n const section = ensureObject(value, sourceLabel, [\"inspect\"]);\n if (!section) {\n return undefined;\n }\n\n rejectUnknownKeys(section, [\"detector\", \"contentGate\"], sourceLabel, [\"inspect\"]);\n\n const detector = parseEnum<DetectorMode>(section.detector, CONFIG_DETECTOR_VALUES, sourceLabel, [\n \"inspect\",\n \"detector\",\n ]);\n const contentGateSection = ensureObject(section.contentGate, sourceLabel, [\n \"inspect\",\n \"contentGate\",\n ]);\n if (contentGateSection) {\n rejectUnknownKeys(contentGateSection, [\"mode\"], sourceLabel, [\"inspect\", \"contentGate\"]);\n }\n const mode = parseEnum<DetectorContentGateMode>(\n contentGateSection?.mode,\n CONFIG_CONTENT_GATE_MODE_VALUES,\n sourceLabel,\n [\"inspect\", \"contentGate\", \"mode\"],\n );\n\n const normalized: NonNullable<WordCounterConfig[\"inspect\"]> = {};\n if (detector !== undefined) {\n normalized.detector = detector;\n }\n if (mode !== undefined) {\n normalized.contentGate = { mode };\n }\n\n return Object.keys(normalized).length > 0 ? normalized : undefined;\n}\n\nfunction normalizeContentGateConfig(\n value: unknown,\n sourceLabel: string,\n): WordCounterConfig[\"contentGate\"] {\n const section = ensureObject(value, sourceLabel, [\"contentGate\"]);\n if (!section) {\n return undefined;\n }\n\n rejectUnknownKeys(section, [\"mode\"], sourceLabel, [\"contentGate\"]);\n\n const mode = parseEnum<DetectorContentGateMode>(\n section.mode,\n CONFIG_CONTENT_GATE_MODE_VALUES,\n sourceLabel,\n [\"contentGate\", \"mode\"],\n );\n\n return mode === undefined ? undefined : { mode };\n}\n\nfunction normalizePathConfig(value: unknown, sourceLabel: string): WordCounterConfig[\"path\"] {\n const section = ensureObject(value, sourceLabel, [\"path\"]);\n if (!section) {\n return undefined;\n }\n\n rejectUnknownKeys(\n section,\n [\"mode\", \"recursive\", \"includeExtensions\", \"excludeExtensions\", \"detectBinary\"],\n sourceLabel,\n [\"path\"],\n );\n\n const mode = parseEnum<PathMode>(section.mode, CONFIG_PATH_MODE_VALUES, sourceLabel, [\n \"path\",\n \"mode\",\n ]);\n const recursive = parseBoolean(section.recursive, sourceLabel, [\"path\", \"recursive\"]);\n const includeExtensions = parseStringArray(section.includeExtensions, sourceLabel, [\n \"path\",\n \"includeExtensions\",\n ]);\n const excludeExtensions = parseStringArray(section.excludeExtensions, sourceLabel, [\n \"path\",\n \"excludeExtensions\",\n ]);\n const detectBinary = parseBoolean(section.detectBinary, sourceLabel, [\"path\", \"detectBinary\"]);\n\n const normalized: NonNullable<WordCounterConfig[\"path\"]> = {};\n if (mode !== undefined) {\n normalized.mode = mode;\n }\n if (recursive !== undefined) {\n normalized.recursive = recursive;\n }\n if (includeExtensions !== undefined) {\n normalized.includeExtensions = includeExtensions;\n }\n if (excludeExtensions !== undefined) {\n normalized.excludeExtensions = excludeExtensions;\n }\n if (detectBinary !== undefined) {\n normalized.detectBinary = detectBinary;\n }\n\n return Object.keys(normalized).length > 0 ? normalized : undefined;\n}\n\nfunction normalizeProgressConfig(\n value: unknown,\n sourceLabel: string,\n): WordCounterConfig[\"progress\"] {\n const section = ensureObject(value, sourceLabel, [\"progress\"]);\n if (!section) {\n return undefined;\n }\n\n rejectUnknownKeys(section, [\"mode\"], sourceLabel, [\"progress\"]);\n\n const mode = parseEnum<ConfigProgressMode>(\n section.mode,\n CONFIG_PROGRESS_MODE_VALUES,\n sourceLabel,\n [\"progress\", \"mode\"],\n );\n\n return mode === undefined ? undefined : { mode };\n}\n\nfunction normalizeOutputConfig(value: unknown, sourceLabel: string): WordCounterConfig[\"output\"] {\n const section = ensureObject(value, sourceLabel, [\"output\"]);\n if (!section) {\n return undefined;\n }\n\n rejectUnknownKeys(section, [\"totalOf\"], sourceLabel, [\"output\"]);\n\n const totalOf = parseTotalOf(section.totalOf, sourceLabel, [\"output\", \"totalOf\"]);\n return totalOf === undefined ? undefined : { totalOf };\n}\n\nfunction normalizeReportingConfig(\n value: unknown,\n sourceLabel: string,\n): WordCounterConfig[\"reporting\"] {\n const section = ensureObject(value, sourceLabel, [\"reporting\"]);\n if (!section) {\n return undefined;\n }\n\n rejectUnknownKeys(section, [\"skippedFiles\", \"debugReport\"], sourceLabel, [\"reporting\"]);\n\n const skippedFiles = parseBoolean(section.skippedFiles, sourceLabel, [\n \"reporting\",\n \"skippedFiles\",\n ]);\n\n const debugReportSection = ensureObject(section.debugReport, sourceLabel, [\n \"reporting\",\n \"debugReport\",\n ]);\n if (debugReportSection) {\n rejectUnknownKeys(debugReportSection, [\"path\", \"tee\"], sourceLabel, [\n \"reporting\",\n \"debugReport\",\n ]);\n }\n\n const path = parseString(debugReportSection?.path, sourceLabel, [\n \"reporting\",\n \"debugReport\",\n \"path\",\n ]);\n const tee = parseBoolean(debugReportSection?.tee, sourceLabel, [\n \"reporting\",\n \"debugReport\",\n \"tee\",\n ]);\n\n const normalized: NonNullable<WordCounterConfig[\"reporting\"]> = {};\n if (skippedFiles !== undefined) {\n normalized.skippedFiles = skippedFiles;\n }\n if (path !== undefined || tee !== undefined) {\n normalized.debugReport = {};\n if (path !== undefined) {\n normalized.debugReport.path = path;\n }\n if (tee !== undefined) {\n normalized.debugReport.tee = tee;\n }\n }\n\n return Object.keys(normalized).length > 0 ? normalized : undefined;\n}\n\nfunction normalizeLoggingConfig(value: unknown, sourceLabel: string): WordCounterConfig[\"logging\"] {\n const section = ensureObject(value, sourceLabel, [\"logging\"]);\n if (!section) {\n return undefined;\n }\n\n rejectUnknownKeys(section, [\"level\", \"verbosity\"], sourceLabel, [\"logging\"]);\n\n const level = parseEnum<ConfigLogLevel>(section.level, CONFIG_LOG_LEVEL_VALUES, sourceLabel, [\n \"logging\",\n \"level\",\n ]);\n const verbosity = parseEnum<ConfigLogVerbosity>(\n section.verbosity,\n CONFIG_LOG_VERBOSITY_VALUES,\n sourceLabel,\n [\"logging\", \"verbosity\"],\n );\n\n const normalized: NonNullable<WordCounterConfig[\"logging\"]> = {};\n if (level !== undefined) {\n normalized.level = level;\n }\n if (verbosity !== undefined) {\n normalized.verbosity = verbosity;\n }\n\n return Object.keys(normalized).length > 0 ? normalized : undefined;\n}\n\nexport function normalizeWordCounterConfig(value: unknown, sourceLabel: string): WordCounterConfig {\n const root = ensureObject(value, sourceLabel, []);\n if (!root) {\n throw createConfigError(sourceLabel, [], \"expected a root object.\");\n }\n\n rejectUnknownKeys(\n root,\n [\"detector\", \"contentGate\", \"inspect\", \"path\", \"progress\", \"output\", \"reporting\", \"logging\"],\n sourceLabel,\n [],\n );\n\n const detector = parseEnum<DetectorMode>(root.detector, CONFIG_DETECTOR_VALUES, sourceLabel, [\n \"detector\",\n ]);\n const contentGate = normalizeContentGateConfig(root.contentGate, sourceLabel);\n const inspect = normalizeInspectConfig(root.inspect, sourceLabel);\n const path = normalizePathConfig(root.path, sourceLabel);\n const progress = normalizeProgressConfig(root.progress, sourceLabel);\n const output = normalizeOutputConfig(root.output, sourceLabel);\n const reporting = normalizeReportingConfig(root.reporting, sourceLabel);\n const logging = normalizeLoggingConfig(root.logging, sourceLabel);\n\n const normalized: WordCounterConfig = {};\n if (detector !== undefined) {\n normalized.detector = detector;\n }\n if (contentGate !== undefined) {\n normalized.contentGate = contentGate;\n }\n if (inspect !== undefined) {\n normalized.inspect = inspect;\n }\n if (path !== undefined) {\n normalized.path = path;\n }\n if (progress !== undefined) {\n normalized.progress = progress;\n }\n if (output !== undefined) {\n normalized.output = output;\n }\n if (reporting !== undefined) {\n normalized.reporting = reporting;\n }\n if (logging !== undefined) {\n normalized.logging = logging;\n }\n\n return normalized;\n}\n","import { parseTotalOfOption } from \"../total-of\";\nimport { normalizeWordCounterConfig } from \"./normalize\";\nimport type { WordCounterConfig } from \"./types\";\n\nfunction parseBooleanEnv(name: string, value: string | undefined): boolean | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n const normalized = value.trim().toLowerCase();\n if (normalized === \"1\" || normalized === \"true\" || normalized === \"yes\" || normalized === \"on\") {\n return true;\n }\n if (normalized === \"0\" || normalized === \"false\" || normalized === \"no\" || normalized === \"off\") {\n return false;\n }\n\n throw new Error(`Invalid value for ${name}: ${value}`);\n}\n\nfunction parseCommaSeparatedEnv(value: string | undefined): string[] | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n const tokens = value\n .split(\",\")\n .map((token) => token.trim())\n .filter((token) => token.length > 0);\n\n return tokens.length > 0 ? tokens : [];\n}\n\ntype ConfigPath = NonNullable<WordCounterConfig[\"path\"]>;\ntype ConfigProgress = NonNullable<WordCounterConfig[\"progress\"]>;\ntype ConfigLogging = NonNullable<WordCounterConfig[\"logging\"]>;\n\nexport function resolveEnvConfig(env: NodeJS.ProcessEnv = process.env): WordCounterConfig {\n const pathMode = env.WORD_COUNTER_PATH_MODE;\n const recursive = parseBooleanEnv(\"WORD_COUNTER_RECURSIVE\", env.WORD_COUNTER_RECURSIVE);\n const includeExtensions = parseCommaSeparatedEnv(env.WORD_COUNTER_INCLUDE_EXT);\n const excludeExtensions = parseCommaSeparatedEnv(env.WORD_COUNTER_EXCLUDE_EXT);\n const skippedFiles = parseBooleanEnv(\"WORD_COUNTER_REPORT_SKIPS\", env.WORD_COUNTER_REPORT_SKIPS);\n const totalOfRaw = env.WORD_COUNTER_TOTAL_OF;\n const contentGateMode = env.WORD_COUNTER_CONTENT_GATE;\n const progressMode = env.WORD_COUNTER_PROGRESS;\n const logLevel = env.WORD_COUNTER_LOG_LEVEL;\n const logVerbosity = env.WORD_COUNTER_LOG_VERBOSITY;\n const debugReportPath = env.WORD_COUNTER_DEBUG_REPORT;\n const debugReportTee = parseBooleanEnv(\n \"WORD_COUNTER_DEBUG_REPORT_TEE\",\n env.WORD_COUNTER_DEBUG_REPORT_TEE,\n );\n\n const config: WordCounterConfig = {};\n\n if (\n pathMode !== undefined ||\n recursive !== undefined ||\n includeExtensions !== undefined ||\n excludeExtensions !== undefined\n ) {\n config.path = {};\n if (pathMode !== undefined) {\n config.path.mode = pathMode as ConfigPath[\"mode\"];\n }\n if (recursive !== undefined) {\n config.path.recursive = recursive;\n }\n if (includeExtensions !== undefined) {\n config.path.includeExtensions = includeExtensions;\n }\n if (excludeExtensions !== undefined) {\n config.path.excludeExtensions = excludeExtensions;\n }\n }\n\n if (progressMode !== undefined) {\n config.progress = {\n mode: progressMode as ConfigProgress[\"mode\"],\n };\n }\n\n if (totalOfRaw !== undefined) {\n config.output = {\n totalOf: parseTotalOfOption(totalOfRaw),\n };\n }\n\n if (contentGateMode !== undefined) {\n config.contentGate = {\n mode: contentGateMode as NonNullable<WordCounterConfig[\"contentGate\"]>[\"mode\"],\n };\n config.inspect = {\n ...config.inspect,\n contentGate: {\n mode: contentGateMode as NonNullable<\n NonNullable<WordCounterConfig[\"inspect\"]>[\"contentGate\"]\n >[\"mode\"],\n },\n };\n }\n\n if (skippedFiles !== undefined || debugReportPath !== undefined || debugReportTee !== undefined) {\n config.reporting = {};\n if (skippedFiles !== undefined) {\n config.reporting.skippedFiles = skippedFiles;\n }\n if (debugReportPath !== undefined || debugReportTee !== undefined) {\n config.reporting.debugReport = {};\n if (debugReportPath !== undefined) {\n config.reporting.debugReport.path = debugReportPath;\n }\n if (debugReportTee !== undefined) {\n config.reporting.debugReport.tee = debugReportTee;\n }\n }\n }\n\n if (logLevel !== undefined || logVerbosity !== undefined) {\n config.logging = {};\n if (logLevel !== undefined) {\n config.logging.level = logLevel as ConfigLogging[\"level\"];\n }\n if (logVerbosity !== undefined) {\n config.logging.verbosity = logVerbosity as ConfigLogging[\"verbosity\"];\n }\n }\n\n return normalizeWordCounterConfig(config, \"environment variables\");\n}\n","import type { WordCounterConfig } from \"./types\";\n\nfunction mergeSection<T extends Record<string, unknown> | undefined>(\n base: T,\n override: T,\n): T | undefined {\n if (!base) {\n return override ? ({ ...override } as T) : undefined;\n }\n if (!override) {\n return { ...base } as T;\n }\n return { ...base, ...override } as T;\n}\n\nfunction mergeNestedSection<T extends Record<string, unknown> | undefined>(\n base: T,\n override: T,\n nestedKey: string,\n): T | undefined {\n const merged = mergeSection(base, override);\n if (!merged) {\n return undefined;\n }\n\n const baseRecord = base as Record<string, unknown> | undefined;\n const overrideRecord = override as Record<string, unknown> | undefined;\n const baseNested = baseRecord?.[nestedKey];\n const overrideNested = overrideRecord?.[nestedKey];\n if (\n typeof baseNested === \"object\" &&\n baseNested !== null &&\n typeof overrideNested === \"object\" &&\n overrideNested !== null\n ) {\n return {\n ...merged,\n [nestedKey]: {\n ...(baseNested as Record<string, unknown>),\n ...(overrideNested as Record<string, unknown>),\n },\n } as T;\n }\n\n return merged;\n}\n\nexport function mergeWordCounterConfig(\n base: WordCounterConfig,\n override: WordCounterConfig,\n): WordCounterConfig {\n return {\n ...base,\n ...override,\n ...(base.inspect || override.inspect\n ? {\n inspect: mergeSection(base.inspect, override.inspect),\n }\n : {}),\n ...(base.path || override.path\n ? {\n path: mergeSection(base.path, override.path),\n }\n : {}),\n ...(base.progress || override.progress\n ? {\n progress: mergeSection(base.progress, override.progress),\n }\n : {}),\n ...(base.output || override.output\n ? {\n output: mergeSection(base.output, override.output),\n }\n : {}),\n ...(base.reporting || override.reporting\n ? {\n reporting: mergeNestedSection(base.reporting, override.reporting, \"debugReport\"),\n }\n : {}),\n ...(base.logging || override.logging\n ? {\n logging: mergeSection(base.logging, override.logging),\n }\n : {}),\n };\n}\n","function isEscaped(text: string, index: number): boolean {\n let backslashCount = 0;\n for (let cursor = index - 1; cursor >= 0 && text[cursor] === \"\\\\\"; cursor -= 1) {\n backslashCount += 1;\n }\n return backslashCount % 2 === 1;\n}\n\nexport function stripJsonComments(text: string): string {\n let result = \"\";\n let inString = false;\n let inLineComment = false;\n let inBlockComment = false;\n\n for (let index = 0; index < text.length; index += 1) {\n const current = text[index] ?? \"\";\n const next = text[index + 1] ?? \"\";\n\n if (inLineComment) {\n if (current === \"\\n\") {\n inLineComment = false;\n result += current;\n }\n continue;\n }\n\n if (inBlockComment) {\n if (current === \"*\" && next === \"/\") {\n inBlockComment = false;\n index += 1;\n }\n continue;\n }\n\n if (inString) {\n result += current;\n if (current === '\"' && !isEscaped(text, index)) {\n inString = false;\n }\n continue;\n }\n\n if (current === '\"') {\n inString = true;\n result += current;\n continue;\n }\n\n if (current === \"/\" && next === \"/\") {\n inLineComment = true;\n index += 1;\n continue;\n }\n\n if (current === \"/\" && next === \"*\") {\n inBlockComment = true;\n index += 1;\n continue;\n }\n\n result += current;\n }\n\n if (inBlockComment) {\n throw new Error(\"Unterminated block comment in JSONC config.\");\n }\n\n return result;\n}\n","export type TomlLineToken =\n | {\n kind: \"table\";\n path: string[];\n rawLine: string;\n }\n | {\n kind: \"assignment\";\n keyPath: string[];\n rawValue: string;\n rawLine: string;\n };\n\nfunction stripInlineComment(line: string): string {\n let inSingle = false;\n let inDouble = false;\n\n for (let index = 0; index < line.length; index += 1) {\n const current = line[index] ?? \"\";\n const previous = line[index - 1] ?? \"\";\n\n if (current === \"'\" && !inDouble) {\n inSingle = !inSingle;\n continue;\n }\n\n if (current === '\"' && !inSingle && previous !== \"\\\\\") {\n inDouble = !inDouble;\n continue;\n }\n\n if (current === \"#\" && !inSingle && !inDouble) {\n return line.slice(0, index);\n }\n }\n\n return line;\n}\n\nfunction splitPath(path: string, rawLine: string): string[] {\n const parts = path.split(\".\").map((part) => part.trim());\n if (parts.some((part) => part.length === 0)) {\n throw new Error(`Invalid TOML key: ${rawLine}`);\n }\n return parts;\n}\n\nfunction tokenizeTomlLine(rawLine: string, currentTable: string[]): TomlLineToken | undefined {\n const line = stripInlineComment(rawLine).trim();\n if (!line) {\n return undefined;\n }\n\n const tableMatch = line.match(/^\\[([A-Za-z0-9_.-]+)]$/);\n if (tableMatch) {\n return {\n kind: \"table\",\n path: splitPath(tableMatch[1] ?? \"\", rawLine),\n rawLine,\n };\n }\n\n const separatorIndex = line.indexOf(\"=\");\n if (separatorIndex <= 0) {\n throw new Error(`Invalid TOML assignment: ${rawLine}`);\n }\n\n const rawKey = line.slice(0, separatorIndex).trim();\n const rawValue = line.slice(separatorIndex + 1).trim();\n if (!rawKey || !rawValue) {\n throw new Error(`Invalid TOML assignment: ${rawLine}`);\n }\n\n return {\n kind: \"assignment\",\n keyPath: [...currentTable, ...splitPath(rawKey, rawLine)],\n rawValue,\n rawLine,\n };\n}\n\nexport function tokenizeTomlConfig(text: string): TomlLineToken[] {\n const tokens: TomlLineToken[] = [];\n let currentTable: string[] = [];\n\n for (const rawLine of text.split(/\\r?\\n/)) {\n const token = tokenizeTomlLine(rawLine, currentTable);\n if (!token) {\n continue;\n }\n\n if (token.kind === \"table\") {\n currentTable = token.path;\n tokens.push(token);\n continue;\n }\n\n tokens.push(token);\n }\n\n return tokens;\n}\n","import { tokenizeTomlConfig } from \"./toml-tokens\";\n\ntype TomlPrimitive = string | boolean;\ntype TomlValue = TomlPrimitive | TomlPrimitive[];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseTomlString(rawValue: string): string {\n if (rawValue.length < 2) {\n throw new Error(`Invalid TOML string value: ${rawValue}`);\n }\n\n const quote = rawValue[0];\n const inner = rawValue.slice(1, -1);\n if (quote === \"'\") {\n return inner;\n }\n\n return inner.replace(/\\\\([\"\\\\bfnrt])/g, (_match, escaped: string) => {\n switch (escaped) {\n case '\"':\n return '\"';\n case \"\\\\\":\n return \"\\\\\";\n case \"b\":\n return \"\\b\";\n case \"f\":\n return \"\\f\";\n case \"n\":\n return \"\\n\";\n case \"r\":\n return \"\\r\";\n case \"t\":\n return \"\\t\";\n default:\n return escaped;\n }\n });\n}\n\nfunction splitTomlArrayItems(rawValue: string): string[] {\n const items: string[] = [];\n let buffer = \"\";\n let inSingle = false;\n let inDouble = false;\n\n for (let index = 0; index < rawValue.length; index += 1) {\n const current = rawValue[index] ?? \"\";\n const previous = rawValue[index - 1] ?? \"\";\n\n if (current === \"'\" && !inDouble) {\n inSingle = !inSingle;\n buffer += current;\n continue;\n }\n\n if (current === '\"' && !inSingle && previous !== \"\\\\\") {\n inDouble = !inDouble;\n buffer += current;\n continue;\n }\n\n if (current === \",\" && !inSingle && !inDouble) {\n items.push(buffer.trim());\n buffer = \"\";\n continue;\n }\n\n buffer += current;\n }\n\n if (buffer.trim().length > 0) {\n items.push(buffer.trim());\n }\n\n return items;\n}\n\nfunction parseTomlValue(rawValue: string): TomlValue {\n const trimmed = rawValue.trim();\n if (trimmed === \"true\") {\n return true;\n }\n if (trimmed === \"false\") {\n return false;\n }\n\n if (\n (trimmed.startsWith('\"') && trimmed.endsWith('\"')) ||\n (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\"))\n ) {\n return parseTomlString(trimmed);\n }\n\n if (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) {\n const inner = trimmed.slice(1, -1).trim();\n if (inner.length === 0) {\n return [];\n }\n return splitTomlArrayItems(inner).map((item) => {\n const parsed = parseTomlValue(item);\n if (Array.isArray(parsed)) {\n throw new Error(`Nested TOML arrays are not supported: ${rawValue}`);\n }\n return parsed;\n });\n }\n\n throw new Error(`Unsupported TOML value: ${rawValue}`);\n}\n\nfunction ensureObject(parent: Record<string, unknown>, key: string): Record<string, unknown> {\n const existing = parent[key];\n if (existing === undefined) {\n const next: Record<string, unknown> = {};\n parent[key] = next;\n return next;\n }\n\n if (!isRecord(existing)) {\n throw new Error(`Cannot redefine non-table key as table: ${key}`);\n }\n\n return existing;\n}\n\nfunction setNestedValue(root: Record<string, unknown>, keyPath: string[], value: TomlValue): void {\n let target = root;\n for (let index = 0; index < keyPath.length - 1; index += 1) {\n target = ensureObject(target, keyPath[index] ?? \"\");\n }\n\n const leafKey = keyPath[keyPath.length - 1] ?? \"\";\n if (leafKey in target) {\n throw new Error(`Duplicate TOML key: ${keyPath.join(\".\")}`);\n }\n target[leafKey] = value;\n}\n\nexport function parseTomlConfig(text: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const token of tokenizeTomlConfig(text)) {\n if (token.kind === \"table\") {\n let tableTarget = result;\n for (const part of token.path) {\n tableTarget = ensureObject(tableTarget, part);\n }\n continue;\n }\n\n setNestedValue(result, token.keyPath, parseTomlValue(token.rawValue));\n }\n\n return result;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { ConfigParseError, ConfigValidationError } from \"./errors\";\nimport { stripJsonComments } from \"./jsonc\";\nimport { normalizeWordCounterConfig } from \"./normalize\";\nimport { parseTomlConfig } from \"./toml\";\nimport type { ConfigFormat, ParsedConfigFile, WordCounterConfig } from \"./types\";\n\nfunction parseJsonConfig(text: string, sourceLabel: string, format: \"json\" | \"jsonc\"): unknown {\n try {\n return JSON.parse(text);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ConfigParseError(sourceLabel, format, message);\n }\n}\n\nexport function parseConfigText(\n text: string,\n format: ConfigFormat,\n sourceLabel: string,\n): WordCounterConfig {\n let parsed: unknown;\n\n if (format === \"json\") {\n parsed = parseJsonConfig(text, sourceLabel, \"json\");\n } else if (format === \"jsonc\") {\n try {\n parsed = parseJsonConfig(stripJsonComments(text), sourceLabel, \"jsonc\");\n } catch (error) {\n if (error instanceof ConfigParseError) {\n throw error;\n }\n const message = error instanceof Error ? error.message : String(error);\n throw new ConfigParseError(sourceLabel, \"jsonc\", message);\n }\n } else {\n try {\n parsed = parseTomlConfig(text);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ConfigParseError(sourceLabel, \"toml\", message);\n }\n }\n\n try {\n return normalizeWordCounterConfig(parsed, sourceLabel);\n } catch (error) {\n if (error instanceof ConfigValidationError) {\n throw error;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n throw new ConfigParseError(sourceLabel, format, message);\n }\n}\n\nexport async function loadConfigFile(\n path: string,\n format: ConfigFormat,\n): Promise<ParsedConfigFile> {\n let text: string;\n try {\n text = await readFile(path, \"utf8\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to read config file (${path}): ${message}`);\n }\n\n return {\n format,\n path,\n config: parseConfigText(text, format, path),\n };\n}\n","import { loadConfigFile } from \"./parse\";\nimport { discoverConfigFiles } from \"./discover\";\nimport { resolveEnvConfig } from \"./env\";\nimport { mergeWordCounterConfig } from \"./merge\";\nimport type { DiscoverConfigOptions, ParsedConfigFile, WordCounterConfig } from \"./types\";\n\nexport type ResolvedWordCounterConfig = {\n config: WordCounterConfig;\n files: ParsedConfigFile[];\n notes: string[];\n};\n\nexport async function resolveWordCounterConfig(\n options: DiscoverConfigOptions = {},\n): Promise<ResolvedWordCounterConfig> {\n const discovered = await discoverConfigFiles(options);\n const filesToLoad = [discovered.user, discovered.cwd].filter((item) => item !== undefined);\n const loadedFiles = await Promise.all(\n filesToLoad.map(async (item) => {\n const loaded = await loadConfigFile(item.path, item.format);\n return {\n ...loaded,\n notes: item.notes,\n };\n }),\n );\n\n let config: WordCounterConfig = {};\n const files: ParsedConfigFile[] = [];\n const notes: string[] = [];\n\n for (const loaded of loadedFiles) {\n config = mergeWordCounterConfig(config, loaded.config);\n files.push({\n path: loaded.path,\n format: loaded.format,\n config: loaded.config,\n });\n notes.push(...loaded.notes);\n }\n\n config = mergeWordCounterConfig(config, resolveEnvConfig(options.env));\n\n return {\n config,\n files,\n notes,\n };\n}\n","import type { Command } from \"commander\";\nimport type { ConfigProgressMode } from \"./types\";\nimport type { CountCliSources } from \"./apply\";\n\nfunction isCliOptionSource(program: Command, optionName: string): boolean {\n return program.getOptionValueSource(optionName) === \"cli\";\n}\n\nexport function deriveCountCliSources(program: Command): CountCliSources {\n return {\n detector: isCliOptionSource(program, \"detector\"),\n contentGate: isCliOptionSource(program, \"contentGate\"),\n pathMode: isCliOptionSource(program, \"pathMode\"),\n recursive: isCliOptionSource(program, \"recursive\"),\n includeExt: isCliOptionSource(program, \"includeExt\"),\n excludeExt: isCliOptionSource(program, \"excludeExt\"),\n totalOf: isCliOptionSource(program, \"totalOf\"),\n debug: isCliOptionSource(program, \"debug\"),\n verbose: isCliOptionSource(program, \"verbose\"),\n debugReport: isCliOptionSource(program, \"debugReport\"),\n debugReportTee:\n isCliOptionSource(program, \"debugReportTee\") || isCliOptionSource(program, \"debugTee\"),\n progress: isCliOptionSource(program, \"progress\"),\n quietSkips: isCliOptionSource(program, \"quietSkips\"),\n };\n}\n\nexport function deriveInitialCountProgressMode(\n program: Command,\n rawProgressValue: boolean,\n): ConfigProgressMode {\n if (!isCliOptionSource(program, \"progress\")) {\n return \"auto\";\n }\n\n return rawProgressValue ? \"on\" : \"off\";\n}\n","import { closeSync, createWriteStream, existsSync, mkdirSync, openSync, statSync } from \"node:fs\";\nimport { basename, dirname, extname, join, resolve as resolvePath } from \"node:path\";\n\ntype DebugDetails = Record<string, unknown>;\nexport type DebugVerbosity = \"compact\" | \"verbose\";\nexport type DebugEventScope = \"run\" | \"file\";\nconst DEBUG_EVENT_SCHEMA_VERSION = 1;\n\nexport type DebugEventOptions = {\n verbosity?: DebugVerbosity;\n scope?: DebugEventScope;\n};\n\ntype DebugReportOptions = {\n path?: string;\n tee: boolean;\n cwd?: string;\n autogeneratedNamePrefix?: string;\n};\n\nexport type CreateDebugChannelOptions = {\n enabled: boolean;\n verbosity?: DebugVerbosity;\n report?: DebugReportOptions;\n now?: () => Date;\n pid?: number;\n};\n\nexport type DebugChannel = {\n enabled: boolean;\n verbosity: DebugVerbosity;\n reportPath?: string;\n emit: (event: string, details?: DebugDetails, options?: DebugEventOptions) => void;\n close: () => Promise<void>;\n};\n\ntype DebugSink = {\n write: (line: string) => void;\n close: () => Promise<void>;\n};\n\nconst NOOP_CLOSE = async (): Promise<void> => {\n return;\n};\n\nfunction shouldEmitAtVerbosity(\n channelVerbosity: DebugVerbosity,\n eventVerbosity: DebugVerbosity,\n): boolean {\n return channelVerbosity === \"verbose\" || eventVerbosity === \"compact\";\n}\n\nfunction formatTimestampPart(value: number): string {\n return String(value).padStart(2, \"0\");\n}\n\nfunction formatDebugReportTimestamp(now: Date): string {\n return [\n `${now.getUTCFullYear()}${formatTimestampPart(now.getUTCMonth() + 1)}${formatTimestampPart(now.getUTCDate())}`,\n `${formatTimestampPart(now.getUTCHours())}${formatTimestampPart(now.getUTCMinutes())}${formatTimestampPart(now.getUTCSeconds())}`,\n ].join(\"-\");\n}\n\nfunction buildRunId(now: Date, pid: number): string {\n return `wc-debug-${now.getTime()}-${pid}`;\n}\n\nfunction inferEventTopic(event: string): string {\n const topic = event.split(\".\")[0]?.trim();\n return topic && topic.length > 0 ? topic : \"runtime\";\n}\n\nconst FILE_SCOPED_EVENT_PATTERNS = [\n /^batch\\.skips\\.item$/,\n /^path\\.resolve\\.input$/,\n /^path\\.resolve\\.skip$/,\n /^path\\.resolve\\.(filter|regex)\\.excluded$/,\n /^path\\.resolve\\.expand\\.include$/,\n /^path\\.resolve\\.dedupe\\.(accept|duplicate)$/,\n];\n\nfunction inferEventScope(event: string): DebugEventScope {\n return FILE_SCOPED_EVENT_PATTERNS.some((pattern) => pattern.test(event)) ? \"file\" : \"run\";\n}\n\nfunction withCollisionSuffix(pathValue: string, sequence: number): string {\n if (sequence <= 0) {\n return pathValue;\n }\n\n const extension = extname(pathValue);\n const baseName = basename(pathValue, extension);\n const parent = dirname(pathValue);\n return join(parent, `${baseName}-${sequence}${extension}`);\n}\n\nfunction resolveReportPath(report: DebugReportOptions, now: Date, pid: number): string {\n const cwd = report.cwd ?? process.cwd();\n const autogeneratedNamePrefix = report.autogeneratedNamePrefix ?? \"wc-debug\";\n const defaultName = `${autogeneratedNamePrefix}-${formatDebugReportTimestamp(now)}-utc-${pid}.jsonl`;\n const explicitPathValue = typeof report.path === \"string\" ? report.path : undefined;\n const explicitPath = explicitPathValue !== undefined;\n const basePath = resolvePath(cwd, explicitPathValue ?? defaultName);\n mkdirSync(dirname(basePath), { recursive: true });\n\n if (explicitPath) {\n if (existsSync(basePath) && statSync(basePath).isDirectory()) {\n throw new Error(`debug report path must be a file: ${basePath}`);\n }\n return basePath;\n }\n\n let candidate = basePath;\n let sequence = 0;\n while (existsSync(candidate)) {\n sequence += 1;\n candidate = withCollisionSuffix(basePath, sequence);\n }\n\n return candidate;\n}\n\nfunction createTerminalSink(): DebugSink {\n return {\n write(line) {\n console.error(`[debug] ${line}`);\n },\n close: NOOP_CLOSE,\n };\n}\n\nfunction createFileSink(pathValue: string): DebugSink {\n try {\n const fd = openSync(pathValue, \"a\");\n closeSync(fd);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`debug report path is not writable: ${pathValue} (${message})`);\n }\n\n const stream = createWriteStream(pathValue, { flags: \"a\", encoding: \"utf8\" });\n let streamError: Error | undefined;\n stream.on(\"error\", (error) => {\n streamError = error;\n });\n\n return {\n write(line) {\n if (streamError || stream.destroyed) {\n return;\n }\n stream.write(`${line}\\n`);\n },\n close() {\n if (streamError || stream.destroyed || stream.writableEnded) {\n return Promise.resolve();\n }\n\n return new Promise<void>((resolve) => {\n stream.end(() => {\n resolve();\n });\n });\n },\n };\n}\n\nexport function createDebugChannel(options: CreateDebugChannelOptions): DebugChannel {\n if (!options.enabled) {\n return {\n enabled: false,\n verbosity: options.verbosity ?? \"compact\",\n emit() {\n return;\n },\n close: NOOP_CLOSE,\n };\n }\n\n const verbosity = options.verbosity ?? \"compact\";\n const sinks: DebugSink[] = [];\n let reportPath: string | undefined;\n const channelNow = options.now?.() ?? new Date();\n const channelPid = options.pid ?? process.pid;\n const runId = buildRunId(channelNow, channelPid);\n\n if (options.report) {\n reportPath = resolveReportPath(options.report, channelNow, channelPid);\n sinks.push(createFileSink(reportPath));\n\n if (options.report.tee) {\n sinks.push(createTerminalSink());\n }\n } else {\n sinks.push(createTerminalSink());\n }\n\n return {\n enabled: true,\n verbosity,\n reportPath,\n emit(event, details = {}, eventOptions = {}) {\n const eventVerbosity = eventOptions.verbosity ?? \"compact\";\n if (!shouldEmitAtVerbosity(verbosity, eventVerbosity)) {\n return;\n }\n\n const timestamp = (options.now?.() ?? new Date()).toISOString();\n const payload = JSON.stringify({\n schemaVersion: DEBUG_EVENT_SCHEMA_VERSION,\n timestamp,\n runId,\n topic: inferEventTopic(event),\n scope: eventOptions.scope ?? inferEventScope(event),\n event,\n verbosity: eventVerbosity,\n ...details,\n });\n for (const sink of sinks) {\n sink.write(payload);\n }\n },\n async close() {\n for (const sink of sinks) {\n await sink.close();\n }\n },\n };\n}\n","let p = process || {}, argv = p.argv || [], env = p.env || {}\nlet isColorSupported =\n\t!(!!env.NO_COLOR || argv.includes(\"--no-color\")) &&\n\t(!!env.FORCE_COLOR || argv.includes(\"--color\") || p.platform === \"win32\" || ((p.stdout || {}).isTTY && env.TERM !== \"dumb\") || !!env.CI)\n\nlet formatter = (open, close, replace = open) =>\n\tinput => {\n\t\tlet string = \"\" + input, index = string.indexOf(close, open.length)\n\t\treturn ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close\n\t}\n\nlet replaceClose = (string, close, replace, index) => {\n\tlet result = \"\", cursor = 0\n\tdo {\n\t\tresult += string.substring(cursor, index) + replace\n\t\tcursor = index + close.length\n\t\tindex = string.indexOf(close, cursor)\n\t} while (~index)\n\treturn result + string.substring(cursor)\n}\n\nlet createColors = (enabled = isColorSupported) => {\n\tlet f = enabled ? formatter : () => String\n\treturn {\n\t\tisColorSupported: enabled,\n\t\treset: f(\"\\x1b[0m\", \"\\x1b[0m\"),\n\t\tbold: f(\"\\x1b[1m\", \"\\x1b[22m\", \"\\x1b[22m\\x1b[1m\"),\n\t\tdim: f(\"\\x1b[2m\", \"\\x1b[22m\", \"\\x1b[22m\\x1b[2m\"),\n\t\titalic: f(\"\\x1b[3m\", \"\\x1b[23m\"),\n\t\tunderline: f(\"\\x1b[4m\", \"\\x1b[24m\"),\n\t\tinverse: f(\"\\x1b[7m\", \"\\x1b[27m\"),\n\t\thidden: f(\"\\x1b[8m\", \"\\x1b[28m\"),\n\t\tstrikethrough: f(\"\\x1b[9m\", \"\\x1b[29m\"),\n\n\t\tblack: f(\"\\x1b[30m\", \"\\x1b[39m\"),\n\t\tred: f(\"\\x1b[31m\", \"\\x1b[39m\"),\n\t\tgreen: f(\"\\x1b[32m\", \"\\x1b[39m\"),\n\t\tyellow: f(\"\\x1b[33m\", \"\\x1b[39m\"),\n\t\tblue: f(\"\\x1b[34m\", \"\\x1b[39m\"),\n\t\tmagenta: f(\"\\x1b[35m\", \"\\x1b[39m\"),\n\t\tcyan: f(\"\\x1b[36m\", \"\\x1b[39m\"),\n\t\twhite: f(\"\\x1b[37m\", \"\\x1b[39m\"),\n\t\tgray: f(\"\\x1b[90m\", \"\\x1b[39m\"),\n\n\t\tbgBlack: f(\"\\x1b[40m\", \"\\x1b[49m\"),\n\t\tbgRed: f(\"\\x1b[41m\", \"\\x1b[49m\"),\n\t\tbgGreen: f(\"\\x1b[42m\", \"\\x1b[49m\"),\n\t\tbgYellow: f(\"\\x1b[43m\", \"\\x1b[49m\"),\n\t\tbgBlue: f(\"\\x1b[44m\", \"\\x1b[49m\"),\n\t\tbgMagenta: f(\"\\x1b[45m\", \"\\x1b[49m\"),\n\t\tbgCyan: f(\"\\x1b[46m\", \"\\x1b[49m\"),\n\t\tbgWhite: f(\"\\x1b[47m\", \"\\x1b[49m\"),\n\n\t\tblackBright: f(\"\\x1b[90m\", \"\\x1b[39m\"),\n\t\tredBright: f(\"\\x1b[91m\", \"\\x1b[39m\"),\n\t\tgreenBright: f(\"\\x1b[92m\", \"\\x1b[39m\"),\n\t\tyellowBright: f(\"\\x1b[93m\", \"\\x1b[39m\"),\n\t\tblueBright: f(\"\\x1b[94m\", \"\\x1b[39m\"),\n\t\tmagentaBright: f(\"\\x1b[95m\", \"\\x1b[39m\"),\n\t\tcyanBright: f(\"\\x1b[96m\", \"\\x1b[39m\"),\n\t\twhiteBright: f(\"\\x1b[97m\", \"\\x1b[39m\"),\n\n\t\tbgBlackBright: f(\"\\x1b[100m\", \"\\x1b[49m\"),\n\t\tbgRedBright: f(\"\\x1b[101m\", \"\\x1b[49m\"),\n\t\tbgGreenBright: f(\"\\x1b[102m\", \"\\x1b[49m\"),\n\t\tbgYellowBright: f(\"\\x1b[103m\", \"\\x1b[49m\"),\n\t\tbgBlueBright: f(\"\\x1b[104m\", \"\\x1b[49m\"),\n\t\tbgMagentaBright: f(\"\\x1b[105m\", \"\\x1b[49m\"),\n\t\tbgCyanBright: f(\"\\x1b[106m\", \"\\x1b[49m\"),\n\t\tbgWhiteBright: f(\"\\x1b[107m\", \"\\x1b[49m\"),\n\t}\n}\n\nmodule.exports = createColors()\nmodule.exports.createColors = createColors\n","// This file is generated by scripts/generate-embedded-version.mjs.\n// Do not edit manually.\nexport const EMBEDDED_PACKAGE_VERSION = \"0.1.5\";\n","import os from \"node:os\";\nimport type { BatchJobsLimit } from \"./types\";\n\nconst DEFAULT_UV_THREADPOOL_SIZE = 4;\n\nfunction parsePositiveInteger(value: string | undefined): number | undefined {\n if (!value) {\n return undefined;\n }\n\n const parsed = Number.parseInt(value, 10);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n return undefined;\n }\n\n return parsed;\n}\n\nexport function resolveBatchJobsLimit(env: NodeJS.ProcessEnv = process.env): BatchJobsLimit {\n const cpuLimit = Math.max(1, os.availableParallelism());\n const uvThreadpool = parsePositiveInteger(env.UV_THREADPOOL_SIZE) ?? DEFAULT_UV_THREADPOOL_SIZE;\n const ioLimit = Math.max(1, uvThreadpool * 2);\n const suggestedMaxJobs = Math.max(1, Math.min(cpuLimit, ioLimit));\n\n return {\n suggestedMaxJobs,\n cpuLimit,\n uvThreadpool,\n ioLimit,\n };\n}\n\nexport function clampRequestedJobs(requestedJobs: number, limits: BatchJobsLimit): number {\n return Math.max(1, Math.min(requestedJobs, limits.suggestedMaxJobs));\n}\n\nexport function formatJobsAdvisoryWarning(\n requestedJobs: number,\n effectiveJobs: number,\n limits: BatchJobsLimit,\n): string {\n return [\n `Warning: requested --jobs=${requestedJobs} exceeds suggested host limit (${limits.suggestedMaxJobs}).`,\n `Running with --jobs=${effectiveJobs} as a safety cap.`,\n `Host limits: cpuLimit=${limits.cpuLimit}, uvThreadpool=${limits.uvThreadpool}, ioLimit=${limits.ioLimit}.`,\n ].join(\" \");\n}\n\nexport function isResourceLimitError(error: unknown): error is NodeJS.ErrnoException {\n if (typeof error !== \"object\" || error === null) {\n return false;\n }\n\n const code = \"code\" in error ? error.code : undefined;\n return code === \"EMFILE\" || code === \"ENFILE\";\n}\n\nexport function createResourceLimitError(\n path: string,\n error: unknown,\n requestedJobs: number,\n limits: BatchJobsLimit,\n): Error {\n const message = error instanceof Error ? error.message : String(error);\n const code =\n typeof error === \"object\" && error !== null && \"code\" in error ? String(error.code) : \"UNKNOWN\";\n\n return new Error(\n [\n `Resource limit reached while processing: ${path} (${code}: ${message}).`,\n `Requested --jobs=${requestedJobs}; suggested host limit is ${limits.suggestedMaxJobs}.`,\n \"Reduce --jobs or raise OS file descriptor limits before retrying.\",\n ].join(\" \"),\n );\n}\n","import { createResourceLimitError, resolveBatchJobsLimit } from \"./limits\";\nimport type { CountBatchWithJobsOptions, CountBatchWithJobsResult } from \"./types\";\n\nexport class WorkerRouteUnavailableError extends Error {}\n\nexport type WorkerRoutePreflight = {\n workerThreadsAvailable: boolean;\n workerRouteDisabledByEnv: boolean;\n disableWorkerJobsEnv: string | null;\n workerPoolModuleLoadable: boolean;\n workerEntryFound: boolean;\n};\n\nasync function resolveWorkerThreadsAvailability(): Promise<boolean> {\n try {\n const workerThreads = await import(\"node:worker_threads\");\n return typeof workerThreads.Worker === \"function\";\n } catch {\n return false;\n }\n}\n\nfunction isFallbackFriendlyWorkerError(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) {\n return false;\n }\n\n const code = \"code\" in error ? String(error.code) : \"\";\n if (\n code === \"ERR_WORKER_PATH\" ||\n code === \"ERR_WORKER_UNSUPPORTED_EXTENSION\" ||\n code === \"ERR_UNKNOWN_FILE_EXTENSION\" ||\n code === \"ERR_MODULE_NOT_FOUND\"\n ) {\n return true;\n }\n\n const message = error instanceof Error ? error.message : String(error);\n return message.includes(\"Unknown file extension\") || message.includes(\"Cannot find module\");\n}\n\nexport async function resolveWorkerRoutePreflight(\n env: NodeJS.ProcessEnv = process.env,\n): Promise<WorkerRoutePreflight> {\n const disableWorkerJobsEnv = env.WORD_COUNTER_DISABLE_WORKER_JOBS ?? null;\n const workerRouteDisabledByEnv = disableWorkerJobsEnv === \"1\";\n const workerThreadsAvailable = await resolveWorkerThreadsAvailability();\n\n try {\n const workerPoolModule = await import(\"./worker-pool\");\n return {\n workerThreadsAvailable,\n workerRouteDisabledByEnv,\n disableWorkerJobsEnv,\n workerPoolModuleLoadable: true,\n workerEntryFound: workerPoolModule.resolveWorkerEntryUrl() !== null,\n };\n } catch {\n return {\n workerThreadsAvailable,\n workerRouteDisabledByEnv,\n disableWorkerJobsEnv,\n workerPoolModuleLoadable: false,\n workerEntryFound: false,\n };\n }\n}\n\nexport async function countBatchInputsWithWorkerJobs(\n filePaths: string[],\n options: CountBatchWithJobsOptions,\n): Promise<CountBatchWithJobsResult> {\n const workerRouteDisabled = process.env.WORD_COUNTER_DISABLE_WORKER_JOBS === \"1\";\n if (workerRouteDisabled) {\n throw new WorkerRouteUnavailableError(\"Worker route disabled by environment.\");\n }\n\n let workerPoolModule: Awaited<typeof import(\"./worker-pool\")>;\n try {\n workerPoolModule = await import(\"./worker-pool\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new WorkerRouteUnavailableError(`Worker route unavailable: ${message}`);\n }\n\n try {\n return await workerPoolModule.countBatchInputsWithWorkerPool({\n filePaths,\n jobs: options.jobs,\n section: options.section,\n detectorMode: options.detectorMode ?? \"regex\",\n wcOptions: options.wcOptions,\n detectBinary: options.detectBinary ?? true,\n preserveCollectorSegments: options.preserveCollectorSegments,\n detectorEvidence: options.detectorEvidence,\n debugVerbosity: options.debugVerbosity,\n onFileProcessed: options.onFileProcessed,\n onDetectorDebugEvent: options.onDetectorDebugEvent,\n debugEnabled: options.onDetectorDebugEvent !== undefined,\n });\n } catch (error) {\n if (error instanceof workerPoolModule.WorkerPoolTaskFatalError) {\n if (error.code === \"EMFILE\" || error.code === \"ENFILE\") {\n throw createResourceLimitError(\n error.path,\n { code: error.code, message: error.message },\n options.jobs,\n resolveBatchJobsLimit(),\n );\n }\n throw new Error(error.message);\n }\n\n if (\n error instanceof workerPoolModule.WorkerPoolUnavailableError ||\n isFallbackFriendlyWorkerError(error)\n ) {\n const message = error instanceof Error ? error.message : String(error);\n throw new WorkerRouteUnavailableError(`Worker route unavailable: ${message}`);\n }\n\n throw error;\n }\n}\n","import { EMBEDDED_PACKAGE_VERSION } from \"../program/version-embedded\";\nimport { resolveBatchJobsLimit } from \"../batch/jobs/limits\";\nimport { resolveWorkerRoutePreflight } from \"../batch/jobs/load-count-worker\";\nimport type {\n DoctorBuildChannel,\n DoctorReport,\n DoctorRuntimeOverrides,\n DoctorSegmenterHealth,\n DoctorStatus,\n DoctorRuntimeSummary,\n} from \"./types\";\n\nconst REQUIRED_NODE_RANGE = \">=22.18.0\";\nconst REQUIRED_NODE_VERSION = {\n major: 22,\n minor: 18,\n patch: 0,\n} as const;\nconst SAMPLE_TEXT = \"Hello 世界\";\n\nfunction normalizePackageVersion(value: string | undefined): string {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : \"0.0.0\";\n}\n\nfunction deriveBuildChannel(packageVersion: string): DoctorBuildChannel {\n const prereleaseMatch = /(?:^|[.-])(alpha|beta|rc|canary)(?:[.-]|$)/i.exec(packageVersion);\n if (!prereleaseMatch) {\n return \"stable\";\n }\n\n const channel = prereleaseMatch[1]?.toLowerCase();\n if (channel === \"alpha\" || channel === \"beta\" || channel === \"rc\" || channel === \"canary\") {\n return channel;\n }\n\n return \"stable\";\n}\n\nfunction parseNodeVersion(version: string): {\n major: number;\n minor: number;\n patch: number;\n} | null {\n const match = /^v?(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?(?:[-+].*)?$/.exec(version.trim());\n if (!match) {\n return null;\n }\n\n const major = Number.parseInt(match[1] ?? \"\", 10);\n const minor = Number.parseInt(match[2] ?? \"0\", 10);\n const patch = Number.parseInt(match[3] ?? \"0\", 10);\n\n if (!Number.isFinite(major) || !Number.isFinite(minor) || !Number.isFinite(patch)) {\n return null;\n }\n\n return { major, minor, patch };\n}\n\nfunction meetsRequiredNodeVersion(\n version: {\n major: number;\n minor: number;\n patch: number;\n } | null,\n): boolean {\n if (!version) {\n return false;\n }\n\n if (version.major !== REQUIRED_NODE_VERSION.major) {\n return version.major > REQUIRED_NODE_VERSION.major;\n }\n if (version.minor !== REQUIRED_NODE_VERSION.minor) {\n return version.minor > REQUIRED_NODE_VERSION.minor;\n }\n return version.patch >= REQUIRED_NODE_VERSION.patch;\n}\n\nfunction resolveRuntimeSummary(overrides: DoctorRuntimeOverrides = {}): DoctorRuntimeSummary {\n const packageVersion = normalizePackageVersion(\n overrides.packageVersion ?? EMBEDDED_PACKAGE_VERSION,\n );\n const nodeVersion = overrides.nodeVersion ?? process.version;\n const parsedNodeVersion = parseNodeVersion(nodeVersion);\n\n return {\n packageVersion,\n buildChannel: deriveBuildChannel(packageVersion),\n requiredNodeRange: REQUIRED_NODE_RANGE,\n nodeVersion,\n meetsProjectRequirement: meetsRequiredNodeVersion(parsedNodeVersion),\n platform: overrides.platform ?? process.platform,\n arch: overrides.arch ?? process.arch,\n };\n}\n\nfunction resolveSegmenterHealth(overrides: DoctorRuntimeOverrides = {}): DoctorSegmenterHealth {\n const intlLike = overrides.intl ?? Intl;\n const Segmenter = intlLike.Segmenter;\n const available = typeof Segmenter === \"function\";\n\n let wordGranularity = false;\n let graphemeGranularity = false;\n let sampleWordSegmentation = false;\n\n if (!available) {\n return {\n available,\n wordGranularity,\n graphemeGranularity,\n sampleWordSegmentation,\n };\n }\n\n try {\n const wordSegmenter = new Segmenter(\"en\", { granularity: \"word\" });\n wordGranularity = true;\n for (const _segment of wordSegmenter.segment(SAMPLE_TEXT)) {\n sampleWordSegmentation = true;\n break;\n }\n } catch {\n wordGranularity = false;\n sampleWordSegmentation = false;\n }\n\n try {\n new Segmenter(\"en\", { granularity: \"grapheme\" });\n graphemeGranularity = true;\n } catch {\n graphemeGranularity = false;\n }\n\n return {\n available,\n wordGranularity,\n graphemeGranularity,\n sampleWordSegmentation,\n };\n}\n\nfunction collectWarnings(\n runtime: DoctorRuntimeSummary,\n segmenter: DoctorSegmenterHealth,\n workerRoute: Awaited<ReturnType<typeof resolveWorkerRoutePreflight>>,\n): string[] {\n const warnings: string[] = [];\n\n if (!runtime.meetsProjectRequirement) {\n warnings.push(\n `Node.js ${runtime.nodeVersion} is outside the supported range ${runtime.requiredNodeRange}.`,\n );\n }\n\n if (!segmenter.available) {\n warnings.push(\"Intl.Segmenter is unavailable.\");\n } else {\n if (!segmenter.wordGranularity) {\n warnings.push(\"Intl.Segmenter word granularity is unusable.\");\n }\n if (!segmenter.graphemeGranularity) {\n warnings.push(\"Intl.Segmenter grapheme granularity is unusable.\");\n }\n if (!segmenter.sampleWordSegmentation) {\n warnings.push(\"Intl.Segmenter sample segmentation failed.\");\n }\n }\n\n if (!workerRoute.workerThreadsAvailable) {\n warnings.push(\"Worker threads are unavailable on this runtime.\");\n }\n if (workerRoute.workerRouteDisabledByEnv) {\n warnings.push(\"Worker route is disabled by environment.\");\n }\n if (!workerRoute.workerPoolModuleLoadable) {\n warnings.push(\"Worker route preflight failed: worker-pool module could not be loaded.\");\n } else if (!workerRoute.workerEntryFound) {\n warnings.push(\"Worker route preflight failed: count-worker entry file was not found.\");\n }\n\n return warnings;\n}\n\nfunction resolveStatus(segmenter: DoctorSegmenterHealth, warnings: string[]): DoctorStatus {\n const hardFailure =\n !segmenter.available ||\n !segmenter.wordGranularity ||\n !segmenter.graphemeGranularity ||\n !segmenter.sampleWordSegmentation;\n\n if (hardFailure) {\n return \"fail\";\n }\n\n if (warnings.length > 0) {\n return \"warn\";\n }\n\n return \"ok\";\n}\n\nexport async function createDoctorReport(\n overrides: DoctorRuntimeOverrides = {},\n): Promise<DoctorReport> {\n const runtime = resolveRuntimeSummary(overrides);\n const segmenter = resolveSegmenterHealth(overrides);\n const env = overrides.env ?? process.env;\n const jobs = resolveBatchJobsLimit(env);\n const workerRoute = await resolveWorkerRoutePreflight(env);\n const warnings = collectWarnings(runtime, segmenter, workerRoute);\n\n return {\n status: resolveStatus(segmenter, warnings),\n runtime,\n segmenter,\n jobs,\n workerRoute,\n warnings,\n };\n}\n\nexport { REQUIRED_NODE_RANGE };\n","import pc from \"picocolors\";\nimport type { DoctorOutputFormat, DoctorReport, DoctorStatus } from \"./types\";\n\ntype RenderDoctorReportOptions = {\n format: DoctorOutputFormat;\n pretty: boolean;\n};\n\nfunction colorStatus(status: DoctorStatus): string {\n if (status === \"ok\") {\n return pc.green(pc.bold(status));\n }\n if (status === \"warn\") {\n return pc.yellow(pc.bold(status));\n }\n return pc.red(pc.bold(status));\n}\n\nfunction renderSection(title: string, lines: string[]): void {\n console.log(pc.bold(title));\n for (const line of lines) {\n console.log(`- ${line}`);\n }\n console.log(\"\");\n}\n\nfunction colorBoolean(value: boolean, yes = \"yes\", no = \"no\"): string {\n return value ? pc.green(yes) : pc.red(no);\n}\n\nfunction colorNumber(value: number): string {\n return pc.yellow(String(value));\n}\n\nfunction colorStatusWord(value: boolean): string {\n return value ? pc.green(\"ok\") : pc.red(\"fail\");\n}\n\nfunction renderStandardDoctorReport(report: DoctorReport): void {\n console.log(`Doctor: ${colorStatus(report.status)}`);\n console.log(\"\");\n\n renderSection(\"Runtime\", [\n `package: ${report.runtime.packageVersion} (${report.runtime.buildChannel})`,\n `node: ${report.runtime.nodeVersion} (supported: ${colorBoolean(\n report.runtime.meetsProjectRequirement,\n )}; required ${report.runtime.requiredNodeRange})`,\n `platform: ${report.runtime.platform} ${report.runtime.arch}`,\n ]);\n\n renderSection(\"Segmenter\", [\n `Intl.Segmenter: ${colorBoolean(report.segmenter.available, \"available\", \"missing\")}`,\n `word granularity: ${colorStatusWord(report.segmenter.wordGranularity)}`,\n `grapheme granularity: ${colorStatusWord(report.segmenter.graphemeGranularity)}`,\n `sample segmentation: ${colorStatusWord(report.segmenter.sampleWordSegmentation)}`,\n ]);\n\n renderSection(\"Batch jobs\", [\n `cpuLimit: ${colorNumber(report.jobs.cpuLimit)}`,\n `uvThreadpool: ${colorNumber(report.jobs.uvThreadpool)}`,\n `ioLimit: ${colorNumber(report.jobs.ioLimit)}`,\n `suggestedMaxJobs: ${colorNumber(report.jobs.suggestedMaxJobs)}`,\n ]);\n\n renderSection(\"Worker route\", [\n `worker threads: ${colorBoolean(report.workerRoute.workerThreadsAvailable, \"available\", \"missing\")}`,\n `disabled by env: ${colorBoolean(report.workerRoute.workerRouteDisabledByEnv)}`,\n `disableWorkerJobsEnv: ${report.workerRoute.disableWorkerJobsEnv ?? \"null\"}`,\n `worker pool module: ${colorBoolean(report.workerRoute.workerPoolModuleLoadable, \"loadable\", \"missing\")}`,\n `worker entry: ${colorBoolean(report.workerRoute.workerEntryFound, \"found\", \"missing\")}`,\n ]);\n\n if (report.warnings.length > 0) {\n console.log(pc.bold(\"Warnings\"));\n for (const warning of report.warnings) {\n console.log(pc.yellow(`- ${warning}`));\n }\n }\n}\n\nexport function renderDoctorReport(report: DoctorReport, options: RenderDoctorReportOptions): void {\n if (options.format === \"json\") {\n console.log(JSON.stringify(report, null, options.pretty ? 2 : 0));\n return;\n }\n\n renderStandardDoctorReport(report);\n}\n","import pc from \"picocolors\";\nimport { createDoctorReport } from \"./checks\";\nimport { renderDoctorReport } from \"./render\";\nimport type { DoctorOutputFormat, DoctorRuntimeOverrides } from \"./types\";\n\ntype ExecuteDoctorCommandOptions = {\n argv: string[];\n runtime?: DoctorRuntimeOverrides;\n};\n\ntype ValidDoctorInvocation =\n | {\n ok: true;\n format: DoctorOutputFormat;\n pretty: boolean;\n }\n | {\n ok: true;\n help: true;\n }\n | {\n ok: false;\n message: string;\n };\n\nconst DOCTOR_HELP_LINES = [\n \"Usage: word-counter doctor [options]\",\n \"\",\n \"report runtime diagnostics for this host\",\n \"\",\n \"Options:\",\n \" --format <format> doctor output format (json)\",\n \" --pretty pretty print doctor JSON output (default: false)\",\n \" -h, --help display help for command\",\n];\n\nfunction parseDoctorFormat(rawValue: string | undefined): DoctorOutputFormat | null {\n if (rawValue === undefined) {\n return \"standard\";\n }\n if (rawValue === \"json\") {\n return \"json\";\n }\n return null;\n}\n\nfunction validateDoctorInvocation(argv: string[]): ValidDoctorInvocation {\n const doctorIndex = argv.findIndex((token, index) => index >= 2 && token === \"doctor\");\n const tokens = doctorIndex >= 0 ? argv.slice(doctorIndex + 1) : [];\n let expectsFormatValue = false;\n let format: DoctorOutputFormat = \"standard\";\n let pretty = false;\n\n for (const token of tokens) {\n if (token === \"-h\" || token === \"--help\") {\n return {\n ok: true,\n help: true,\n };\n }\n\n if (expectsFormatValue) {\n const parsedFormat = parseDoctorFormat(token);\n if (parsedFormat === null) {\n return {\n ok: false,\n message: \"`doctor` only supports default text output or `--format json`.\",\n };\n }\n format = parsedFormat;\n expectsFormatValue = false;\n continue;\n }\n\n if (token === \"--\") {\n return {\n ok: false,\n message: \"`doctor` does not accept positional inputs.\",\n };\n }\n\n if (token === \"--format\") {\n expectsFormatValue = true;\n continue;\n }\n\n if (token.startsWith(\"--format=\")) {\n const rawValue = token.slice(\"--format=\".length);\n if (rawValue.length === 0) {\n return {\n ok: false,\n message: \"`--format` requires a value.\",\n };\n }\n const parsedFormat = parseDoctorFormat(rawValue);\n if (parsedFormat === null) {\n return {\n ok: false,\n message: \"`doctor` only supports default text output or `--format json`.\",\n };\n }\n format = parsedFormat;\n continue;\n }\n\n if (token === \"--pretty\") {\n pretty = true;\n continue;\n }\n\n if (token.startsWith(\"-\")) {\n return {\n ok: false,\n message: `\\`${token}\\` is not supported by \\`doctor\\`.`,\n };\n }\n\n return {\n ok: false,\n message: \"`doctor` does not accept positional inputs.\",\n };\n }\n\n if (expectsFormatValue) {\n return {\n ok: false,\n message: \"`--format` requires a value.\",\n };\n }\n\n if (pretty && format !== \"json\") {\n return {\n ok: false,\n message: \"`--pretty` requires `--format json`.\",\n };\n }\n\n return {\n ok: true,\n format,\n pretty,\n };\n}\n\nexport function isExplicitDoctorInvocation(argv: string[]): boolean {\n if (argv[2] !== \"doctor\") {\n return false;\n }\n\n const trailingTokens = argv.slice(3);\n if (trailingTokens.length === 0) {\n return true;\n }\n\n return trailingTokens.some((token) => token === \"--\" || token.startsWith(\"-\"));\n}\n\nfunction printDoctorHelp(): void {\n for (const line of DOCTOR_HELP_LINES) {\n console.log(line);\n }\n}\n\nexport async function executeDoctorCommand({\n argv,\n runtime,\n}: ExecuteDoctorCommandOptions): Promise<void> {\n const validated = validateDoctorInvocation(argv);\n if (!validated.ok) {\n console.error(pc.red(`error: ${validated.message}`));\n process.exitCode = 1;\n return;\n }\n\n if (\"help\" in validated) {\n printDoctorHelp();\n process.exitCode = 0;\n return;\n }\n\n const report = await createDoctorReport(runtime);\n renderDoctorReport(report, {\n format: validated.format,\n pretty: validated.pretty,\n });\n process.exitCode = report.status === \"fail\" ? 2 : 0;\n}\n","export function ensureArrayContainer(\n result: Record<string, unknown>,\n key: string,\n): Record<string, unknown>[] {\n const existing = result[key];\n if (Array.isArray(existing)) {\n return existing as Record<string, unknown>[];\n }\n const list: Record<string, unknown>[] = [];\n result[key] = list;\n return list;\n}\n\nexport function flattenArrayTables(result: Record<string, unknown>): void {\n for (const [key, value] of Object.entries(result)) {\n if (!Array.isArray(value)) {\n continue;\n }\n const flattened = value\n .map((entry) =>\n Object.entries(entry)\n .map(([entryKey, entryValue]) => `${entryKey}=${entryValue}`)\n .join(\", \"),\n )\n .join(\" | \");\n result[key] = flattened;\n }\n}\n","function stripKeyQuotes(key: string): string {\n const trimmed = key.trim();\n if (\n (trimmed.startsWith('\"') && trimmed.endsWith('\"')) ||\n (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\"))\n ) {\n return trimmed.slice(1, -1);\n }\n return trimmed;\n}\n\nexport function normalizeKeyPath(key: string): string | null {\n const trimmed = key.trim();\n if (!trimmed) {\n return null;\n }\n\n if (\n (trimmed.startsWith('\"') && trimmed.endsWith('\"')) ||\n (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\"))\n ) {\n const unquoted = stripKeyQuotes(trimmed);\n return unquoted ? unquoted : null;\n }\n\n const segments = trimmed.split(\".\").map((segment) => segment.trim());\n if (segments.some((segment) => !segment)) {\n return null;\n }\n return segments.join(\".\");\n}\n","export function stripInlineComment(line: string): string {\n let inString: \"single\" | \"double\" | null = null;\n let escaped = false;\n\n for (let i = 0; i < line.length; i += 1) {\n const char = line[i] ?? \"\";\n\n if (inString) {\n if (escaped) {\n escaped = false;\n continue;\n }\n\n if (char === \"\\\\\" && inString === \"double\") {\n escaped = true;\n continue;\n }\n\n if (inString === \"double\" && char === '\"') {\n inString = null;\n continue;\n }\n\n if (inString === \"single\" && char === \"'\") {\n inString = null;\n continue;\n }\n\n continue;\n }\n\n if (char === '\"') {\n inString = \"double\";\n continue;\n }\n\n if (char === \"'\") {\n inString = \"single\";\n continue;\n }\n\n if (char === \"#\") {\n return line.slice(0, i).trimEnd();\n }\n }\n\n return line;\n}\n\nfunction unescapeBasic(input: string): string {\n return input\n .replace(/\\\\\\\\/g, \"\\\\\")\n .replace(/\\\\\"/g, '\"')\n .replace(/\\\\n/g, \"\\n\")\n .replace(/\\\\t/g, \"\\t\")\n .replace(/\\\\r/g, \"\\r\");\n}\n\nexport function parseStringLiteral(value: string): string | null {\n if (value.startsWith('\"\"\"') && value.endsWith('\"\"\"')) {\n const inner = value.slice(3, -3);\n return unescapeBasic(inner);\n }\n\n if (value.startsWith(\"'''\") && value.endsWith(\"'''\")) {\n return value.slice(3, -3);\n }\n\n if (value.startsWith('\"') && value.endsWith('\"')) {\n return unescapeBasic(value.slice(1, -1));\n }\n\n if (value.startsWith(\"'\") && value.endsWith(\"'\")) {\n return value.slice(1, -1);\n }\n\n return null;\n}\n","import { normalizeKeyPath } from \"./keys\";\nimport { parseStringLiteral } from \"./strings\";\nimport type { TomlValue } from \"./types\";\n\nfunction parsePrimitive(raw: string): string | number | boolean | null {\n const value = raw.trim();\n if (!value) {\n return null;\n }\n\n const stringLiteral = parseStringLiteral(value);\n if (stringLiteral !== null) {\n return stringLiteral;\n }\n\n if (value === \"true\") {\n return true;\n }\n\n if (value === \"false\") {\n return false;\n }\n\n if (/^[+-]?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/.test(value)) {\n return Number(value);\n }\n\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(value)) {\n return value;\n }\n\n return value;\n}\n\nfunction parseArray(raw: string): Array<string | number | boolean> | null {\n const value = raw.trim();\n if (!value.startsWith(\"[\") || !value.endsWith(\"]\")) {\n return null;\n }\n\n const inner = value.slice(1, -1).trim();\n if (!inner) {\n return [];\n }\n\n const items: Array<string | number | boolean> = [];\n let current = \"\";\n let inString: \"single\" | \"double\" | null = null;\n let escaped = false;\n\n for (let i = 0; i < inner.length; i += 1) {\n const char = inner[i] ?? \"\";\n\n if (inString) {\n current += char;\n if (escaped) {\n escaped = false;\n continue;\n }\n\n if (char === \"\\\\\" && inString === \"double\") {\n escaped = true;\n continue;\n }\n\n if (inString === \"double\" && char === '\"') {\n inString = null;\n } else if (inString === \"single\" && char === \"'\") {\n inString = null;\n }\n continue;\n }\n\n if (char === '\"') {\n inString = \"double\";\n current += char;\n continue;\n }\n\n if (char === \"'\") {\n inString = \"single\";\n current += char;\n continue;\n }\n\n if (char === \",\") {\n const item = parsePrimitive(current);\n if (item === null) {\n return null;\n }\n items.push(item);\n current = \"\";\n continue;\n }\n\n current += char;\n }\n\n const finalItem = parsePrimitive(current);\n if (finalItem === null) {\n return null;\n }\n items.push(finalItem);\n\n return items;\n}\n\nfunction parseInlineTable(raw: string): Record<string, TomlValue> | null {\n const trimmed = raw.trim();\n if (!trimmed.startsWith(\"{\") || !trimmed.endsWith(\"}\")) {\n return null;\n }\n\n const inner = trimmed.slice(1, -1).trim();\n if (!inner) {\n return {};\n }\n\n const pairs: string[] = [];\n let current = \"\";\n let inString: \"single\" | \"double\" | null = null;\n let escaped = false;\n let bracketDepth = 0;\n let braceDepth = 0;\n\n for (let i = 0; i < inner.length; i += 1) {\n const char = inner[i] ?? \"\";\n\n if (inString) {\n current += char;\n if (escaped) {\n escaped = false;\n continue;\n }\n\n if (char === \"\\\\\" && inString === \"double\") {\n escaped = true;\n continue;\n }\n\n if (inString === \"double\" && char === '\"') {\n inString = null;\n } else if (inString === \"single\" && char === \"'\") {\n inString = null;\n }\n continue;\n }\n\n if (char === '\"') {\n inString = \"double\";\n current += char;\n continue;\n }\n\n if (char === \"'\") {\n inString = \"single\";\n current += char;\n continue;\n }\n\n if (char === \"[\") {\n bracketDepth += 1;\n current += char;\n continue;\n }\n\n if (char === \"]\") {\n if (bracketDepth > 0) {\n bracketDepth -= 1;\n }\n current += char;\n continue;\n }\n\n if (char === \"{\") {\n braceDepth += 1;\n current += char;\n continue;\n }\n\n if (char === \"}\") {\n if (braceDepth > 0) {\n braceDepth -= 1;\n }\n current += char;\n continue;\n }\n\n if (char === \",\" && bracketDepth === 0 && braceDepth === 0) {\n pairs.push(current);\n current = \"\";\n continue;\n }\n\n current += char;\n }\n\n if (current.trim()) {\n pairs.push(current);\n }\n\n const output: Record<string, TomlValue> = {};\n for (const pair of pairs) {\n const separatorIndex = pair.indexOf(\"=\");\n if (separatorIndex === -1) {\n return null;\n }\n const key = normalizeKeyPath(pair.slice(0, separatorIndex));\n if (!key) {\n return null;\n }\n const valueRaw = pair.slice(separatorIndex + 1).trim();\n if (!valueRaw) {\n return null;\n }\n if (valueRaw.startsWith(\"{\")) {\n return null;\n }\n const normalized = normalizeValue(valueRaw);\n if (normalized === null) {\n return null;\n }\n if (typeof normalized === \"object\" && !Array.isArray(normalized)) {\n return null;\n }\n output[key] = normalized;\n }\n\n return output;\n}\n\nexport function normalizeValue(value: string): TomlValue | null {\n if (!value) {\n return null;\n }\n\n const trimmed = value.trim();\n if (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\")) {\n return parseInlineTable(trimmed);\n }\n\n const array = parseArray(trimmed);\n if (array) {\n return array;\n }\n\n if (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) {\n return null;\n }\n\n return parsePrimitive(trimmed);\n}\n\nexport function toPlainText(value: unknown): string {\n if (value == null) {\n return \"\";\n }\n if (Array.isArray(value)) {\n return value.map((item) => String(item)).join(\", \");\n }\n return String(value);\n}\n","import { ensureArrayContainer, flattenArrayTables } from \"./arrays\";\nimport { normalizeKeyPath } from \"./keys\";\nimport { stripInlineComment } from \"./strings\";\nimport { normalizeValue, toPlainText } from \"./values\";\n\nexport function parseTomlFrontmatter(frontmatter: string): Record<string, unknown> | null {\n const result: Record<string, unknown> = {};\n const lines = frontmatter.split(\"\\n\");\n let tablePrefix = \"\";\n let tableTarget: Record<string, unknown> | null = null;\n let tablePrefixInList = false;\n\n for (let index = 0; index < lines.length; index += 1) {\n const rawLine = lines[index] ?? \"\";\n const trimmedLine = rawLine.trim();\n if (!trimmedLine || trimmedLine.startsWith(\"#\")) {\n continue;\n }\n\n if (trimmedLine.startsWith(\"[[\")) {\n const match = trimmedLine.match(/^\\[\\[([^\\]]+)]]$/);\n if (!match) {\n return null;\n }\n const normalizedTable = normalizeKeyPath(match[1] ?? \"\");\n if (!normalizedTable) {\n return null;\n }\n const list = ensureArrayContainer(result, normalizedTable);\n const newEntry: Record<string, unknown> = {};\n list.push(newEntry);\n tableTarget = newEntry;\n tablePrefix = normalizedTable;\n tablePrefixInList = true;\n continue;\n }\n\n const tableMatch = trimmedLine.match(/^\\[([^\\]]+)]$/);\n if (tableMatch) {\n const normalizedTable = normalizeKeyPath(tableMatch[1] ?? \"\");\n if (!normalizedTable) {\n return null;\n }\n tablePrefix = normalizedTable;\n tablePrefixInList = false;\n tableTarget = null;\n continue;\n }\n\n const lineForParsing = /(\"\"\"|''')/.test(rawLine) ? rawLine : stripInlineComment(rawLine);\n const separatorIndex = lineForParsing.indexOf(\"=\");\n if (separatorIndex === -1) {\n return null;\n }\n\n const keyRaw = lineForParsing.slice(0, separatorIndex);\n const key = normalizeKeyPath(keyRaw);\n let valueRaw = lineForParsing.slice(separatorIndex + 1).trim();\n if (!key) {\n return null;\n }\n\n const tripleDelimiter = valueRaw.startsWith('\"\"\"')\n ? '\"\"\"'\n : valueRaw.startsWith(\"'''\")\n ? \"'''\"\n : null;\n if (tripleDelimiter) {\n const closingIndex = valueRaw.indexOf(tripleDelimiter, tripleDelimiter.length);\n if (closingIndex !== -1) {\n const after = valueRaw.slice(closingIndex + tripleDelimiter.length);\n const strippedAfter = stripInlineComment(after);\n valueRaw = `${valueRaw.slice(0, closingIndex + tripleDelimiter.length)}${strippedAfter}`;\n } else {\n const delimiter = tripleDelimiter;\n let combined = valueRaw;\n let closed = false;\n while (index + 1 < lines.length) {\n index += 1;\n const nextLine = lines[index] ?? \"\";\n combined += `\\n${nextLine}`;\n if (new RegExp(`${delimiter}\\\\s*$`).test(nextLine)) {\n closed = true;\n break;\n }\n }\n if (!closed) {\n return null;\n }\n valueRaw = combined;\n }\n }\n\n const normalized = normalizeValue(valueRaw);\n if (normalized === null) {\n return null;\n }\n\n const fullKey = tablePrefix ? `${tablePrefix}.${key}` : key;\n if (typeof normalized === \"object\" && !Array.isArray(normalized)) {\n for (const [inlineKey, inlineValue] of Object.entries(normalized)) {\n const entryKey = tablePrefixInList ? `${key}.${inlineKey}` : `${fullKey}.${inlineKey}`;\n if (tablePrefixInList && tableTarget) {\n tableTarget[entryKey] = toPlainText(inlineValue);\n } else {\n result[entryKey] = toPlainText(inlineValue);\n }\n }\n continue;\n }\n\n if (tablePrefixInList && tableTarget) {\n tableTarget[key] = toPlainText(normalized);\n continue;\n }\n\n result[fullKey] = toPlainText(normalized);\n }\n\n flattenArrayTables(result);\n\n return result;\n}\n","import { parseDocument } from \"yaml\";\nimport { parseTomlFrontmatter } from \"./toml-simple\";\nimport type { FrontmatterType, ParsedMarkdown } from \"./types\";\n\nconst FENCE_TO_TYPE: Record<string, FrontmatterType> = {\n \"---\": \"yaml\",\n \"+++\": \"toml\",\n \";;;\": \"json\",\n};\n\nfunction normalizeNewlines(input: string): string {\n return input.replace(/\\r\\n/g, \"\\n\");\n}\n\nfunction stripBom(line: string): string {\n return line.startsWith(\"\\uFEFF\") ? line.slice(1) : line;\n}\n\nfunction getFenceType(line: string): FrontmatterType | null {\n const match = line.match(/^[\\t ]*(---|\\+\\+\\+|;;;)[\\t ]*$/);\n if (!match) {\n return null;\n }\n return FENCE_TO_TYPE[match[1] ?? \"\"] ?? null;\n}\n\nfunction parseFrontmatter(\n frontmatter: string,\n type: FrontmatterType | null,\n): Record<string, unknown> | null {\n if (!type) {\n return null;\n }\n\n if (type === \"json\") {\n try {\n return JSON.parse(frontmatter) as Record<string, unknown>;\n } catch {\n return null;\n }\n }\n\n if (type === \"yaml\") {\n const doc = parseDocument(frontmatter, { prettyErrors: false });\n if (doc.errors.length > 0) {\n return null;\n }\n const data = doc.toJSON();\n if (!data || typeof data !== \"object\" || Array.isArray(data)) {\n return null;\n }\n return data as Record<string, unknown>;\n }\n\n if (type === \"toml\") {\n return parseTomlFrontmatter(frontmatter);\n }\n\n return null;\n}\n\nfunction extractJsonBlock(\n text: string,\n startIndex: number,\n): { jsonText: string; endIndex: number } | null {\n let depth = 0;\n let inString = false;\n let escaped = false;\n\n for (let i = startIndex; i < text.length; i += 1) {\n const char = text[i] ?? \"\";\n\n if (inString) {\n if (escaped) {\n escaped = false;\n continue;\n }\n\n if (char === \"\\\\\") {\n escaped = true;\n continue;\n }\n\n if (char === '\"') {\n inString = false;\n }\n\n continue;\n }\n\n if (char === '\"') {\n inString = true;\n continue;\n }\n\n if (char === \"{\") {\n depth += 1;\n continue;\n }\n\n if (char === \"}\") {\n depth -= 1;\n if (depth === 0) {\n const jsonText = text.slice(startIndex, i + 1);\n return { jsonText, endIndex: i };\n }\n }\n }\n\n return null;\n}\n\nexport function parseMarkdown(input: string): ParsedMarkdown {\n const normalized = normalizeNewlines(input);\n const lines = normalized.split(\"\\n\");\n if (lines.length === 0) {\n return { frontmatter: null, content: normalized, data: null, frontmatterType: null };\n }\n\n lines[0] = stripBom(lines[0] ?? \"\");\n const normalizedWithoutBom = lines.join(\"\\n\");\n\n const openingType = getFenceType(lines[0] ?? \"\");\n if (!openingType) {\n const leadingWhitespace = normalizedWithoutBom.match(/^[\\t \\n]*/)?.[0] ?? \"\";\n const jsonStart = leadingWhitespace.length;\n if (normalizedWithoutBom[jsonStart] !== \"{\") {\n return {\n frontmatter: null,\n content: normalizedWithoutBom,\n data: null,\n frontmatterType: null,\n };\n }\n\n const jsonBlock = extractJsonBlock(normalizedWithoutBom, jsonStart);\n if (!jsonBlock) {\n return {\n frontmatter: null,\n content: normalizedWithoutBom,\n data: null,\n frontmatterType: null,\n };\n }\n\n const frontmatter = jsonBlock.jsonText;\n let content = normalizedWithoutBom.slice(jsonBlock.endIndex + 1);\n if (content.startsWith(\"\\n\")) {\n content = content.slice(1);\n }\n const data = parseFrontmatter(frontmatter, \"json\");\n if (!data) {\n return {\n frontmatter: null,\n content: normalizedWithoutBom,\n data: null,\n frontmatterType: null,\n };\n }\n\n return {\n frontmatter,\n content,\n data,\n frontmatterType: \"json\",\n };\n }\n\n let closingIndex = -1;\n for (let i = 1; i < lines.length; i += 1) {\n if (getFenceType(lines[i] ?? \"\") === openingType) {\n closingIndex = i;\n break;\n }\n }\n\n if (closingIndex === -1) {\n return { frontmatter: null, content: normalizedWithoutBom, data: null, frontmatterType: null };\n }\n\n const frontmatter = lines.slice(1, closingIndex).join(\"\\n\");\n const content = lines.slice(closingIndex + 1).join(\"\\n\");\n const data = parseFrontmatter(frontmatter, openingType);\n\n return {\n frontmatter,\n content,\n data,\n frontmatterType: openingType,\n };\n}\n","const segmenterCache = new Map<string, Intl.Segmenter>();\nconst graphemeSegmenterCache = new Map<string, Intl.Segmenter>();\n\nexport function getSegmenter(locale: string): Intl.Segmenter {\n const cached = segmenterCache.get(locale);\n if (cached) {\n return cached;\n }\n const segmenter = new Intl.Segmenter(locale, { granularity: \"word\" });\n segmenterCache.set(locale, segmenter);\n return segmenter;\n}\n\nexport function getGraphemeSegmenter(locale: string): Intl.Segmenter {\n const cached = graphemeSegmenterCache.get(locale);\n if (cached) {\n return cached;\n }\n const segmenter = new Intl.Segmenter(locale, { granularity: \"grapheme\" });\n graphemeSegmenterCache.set(locale, segmenter);\n return segmenter;\n}\n\nfunction supportsSegmenter(): boolean {\n return typeof Intl !== \"undefined\" && typeof Intl.Segmenter === \"function\";\n}\n\nexport function countWordsForLocale(text: string, locale: string): number {\n const segmenter = getSegmenter(locale);\n let count = 0;\n for (const segment of segmenter.segment(text)) {\n if (segment.isWordLike) {\n count++;\n }\n }\n return count;\n}\n\nexport function countCharsForLocale(text: string, locale: string): number {\n if (!supportsSegmenter()) {\n return Array.from(text).length;\n }\n const segmenter = getGraphemeSegmenter(locale);\n let count = 0;\n for (const _segment of segmenter.segment(text)) {\n count++;\n }\n return count;\n}\n","export function appendAll<T>(target: T[], source: readonly T[]): void {\n for (const item of source) {\n target.push(item);\n }\n}\n","import type { NonWordCollection, WhitespaceCounts } from \"./types\";\nimport { appendAll } from \"../utils/append-all\";\n\nconst emojiRegex = /(?:\\p{Extended_Pictographic}|\\p{Emoji_Presentation})/u;\nconst emojiPresentationRegex = /\\p{Emoji_Presentation}/u;\nconst keycapEmojiRegex = /[0-9#*]\\uFE0F?\\u20E3/u;\nconst symbolRegex = /\\p{S}/u;\nconst punctuationRegex = /\\p{P}/u;\nconst whitespaceRegex = /\\s/u;\nconst newlineChars = new Set([\"\\n\", \"\\r\", \"\\u2028\", \"\\u2029\"]);\n\nexport function createNonWordCollection(): NonWordCollection {\n return {\n emoji: [],\n symbols: [],\n punctuation: [],\n counts: {\n emoji: 0,\n symbols: 0,\n punctuation: 0,\n },\n };\n}\n\nexport function addNonWord(\n collection: NonWordCollection,\n category: \"emoji\" | \"symbol\" | \"punctuation\",\n segment: string,\n): void {\n if (category === \"emoji\") {\n collection.emoji.push(segment);\n collection.counts.emoji += 1;\n return;\n }\n if (category === \"symbol\") {\n collection.symbols.push(segment);\n collection.counts.symbols += 1;\n return;\n }\n collection.punctuation.push(segment);\n collection.counts.punctuation += 1;\n}\n\nexport function addWhitespace(collection: NonWordCollection, segment: string): number {\n let whitespace = collection.whitespace;\n let count = 0;\n for (const char of segment) {\n if (char === \" \") {\n whitespace = whitespace ?? createWhitespaceCounts();\n whitespace.spaces += 1;\n count += 1;\n continue;\n }\n if (char === \"\\t\") {\n whitespace = whitespace ?? createWhitespaceCounts();\n whitespace.tabs += 1;\n count += 1;\n continue;\n }\n if (newlineChars.has(char)) {\n whitespace = whitespace ?? createWhitespaceCounts();\n whitespace.newlines += 1;\n count += 1;\n continue;\n }\n if (whitespaceRegex.test(char)) {\n whitespace = whitespace ?? createWhitespaceCounts();\n whitespace.other += 1;\n count += 1;\n }\n }\n\n if (count > 0) {\n collection.whitespace = whitespace ?? createWhitespaceCounts();\n collection.counts.whitespace = (collection.counts.whitespace ?? 0) + count;\n }\n\n return count;\n}\n\nexport function classifyNonWordSegment(segment: string): \"emoji\" | \"symbol\" | \"punctuation\" | null {\n const hasEmojiVariationSelector = segment.includes(\"\\uFE0F\");\n if (\n keycapEmojiRegex.test(segment) ||\n emojiPresentationRegex.test(segment) ||\n (hasEmojiVariationSelector && emojiRegex.test(segment))\n ) {\n return \"emoji\";\n }\n if (symbolRegex.test(segment)) {\n return \"symbol\";\n }\n if (punctuationRegex.test(segment)) {\n return \"punctuation\";\n }\n return null;\n}\n\nexport function mergeNonWordCollections(\n target: NonWordCollection,\n source: NonWordCollection,\n): NonWordCollection {\n if (source.counts.emoji > 0) {\n appendAll(target.emoji, source.emoji);\n target.counts.emoji += source.counts.emoji;\n }\n if (source.counts.symbols > 0) {\n appendAll(target.symbols, source.symbols);\n target.counts.symbols += source.counts.symbols;\n }\n if (source.counts.punctuation > 0) {\n appendAll(target.punctuation, source.punctuation);\n target.counts.punctuation += source.counts.punctuation;\n }\n if (source.counts.whitespace && source.counts.whitespace > 0 && source.whitespace) {\n const whitespace = target.whitespace ?? createWhitespaceCounts();\n whitespace.spaces += source.whitespace.spaces;\n whitespace.tabs += source.whitespace.tabs;\n whitespace.newlines += source.whitespace.newlines;\n whitespace.other += source.whitespace.other;\n target.whitespace = whitespace;\n target.counts.whitespace = (target.counts.whitespace ?? 0) + source.counts.whitespace;\n }\n return target;\n}\n\nfunction createWhitespaceCounts(): WhitespaceCounts {\n return { spaces: 0, tabs: 0, newlines: 0, other: 0 };\n}\n","import { countCharsForLocale, getSegmenter } from \"./segmenter\";\nimport {\n addNonWord,\n addWhitespace,\n classifyNonWordSegment,\n createNonWordCollection,\n mergeNonWordCollections,\n} from \"./non-words\";\nimport { appendAll } from \"../utils/append-all\";\nimport type {\n CharCollectorBreakdown,\n ChunkAnalysis,\n CollectorBreakdown,\n LocaleChunk,\n NonWordCollection,\n} from \"./types\";\n\ntype CharAnalysis = LocaleChunk & { chars: number; nonWords?: NonWordCollection };\ntype CharChunkAnalysis = CharAnalysis & { wordChars: number; nonWordChars: number };\n\nexport function analyzeChunk(\n chunk: LocaleChunk,\n collectNonWords?: boolean,\n includeWhitespace?: boolean,\n): ChunkAnalysis {\n const segmenter = getSegmenter(chunk.locale);\n const segments: string[] = [];\n const nonWords: NonWordCollection | null = collectNonWords ? createNonWordCollection() : null;\n for (const part of segmenter.segment(chunk.text)) {\n if (part.isWordLike) {\n segments.push(part.segment);\n } else if (collectNonWords && nonWords) {\n if (includeWhitespace) {\n addWhitespace(nonWords, part.segment);\n }\n const category = classifyNonWordSegment(part.segment);\n if (category) {\n addNonWord(nonWords, category, part.segment);\n }\n }\n }\n return {\n locale: chunk.locale,\n text: chunk.text,\n segments,\n words: segments.length,\n nonWords: nonWords ?? undefined,\n };\n}\n\nexport function analyzeCharChunk(\n chunk: LocaleChunk,\n collectNonWords?: boolean,\n includeWhitespace?: boolean,\n): CharChunkAnalysis {\n const segmenter = getSegmenter(chunk.locale);\n const nonWords: NonWordCollection | null = collectNonWords ? createNonWordCollection() : null;\n let chars = 0;\n let wordChars = 0;\n let nonWordChars = 0;\n\n for (const part of segmenter.segment(chunk.text)) {\n if (part.isWordLike) {\n const count = countCharsForLocale(part.segment, chunk.locale);\n chars += count;\n wordChars += count;\n continue;\n }\n\n if (collectNonWords && nonWords) {\n let whitespaceCount = 0;\n if (includeWhitespace) {\n whitespaceCount = addWhitespace(nonWords, part.segment);\n }\n const category = classifyNonWordSegment(part.segment);\n if (category) {\n addNonWord(nonWords, category, part.segment);\n }\n if (category || whitespaceCount > 0) {\n const count = countCharsForLocale(part.segment, chunk.locale);\n chars += count;\n nonWordChars += count;\n }\n }\n }\n\n return {\n locale: chunk.locale,\n text: chunk.text,\n chars,\n wordChars,\n nonWordChars,\n nonWords: nonWords ?? undefined,\n };\n}\n\nexport function aggregateCharsByLocale(\n chunks: CharChunkAnalysis[],\n): Array<CharCollectorBreakdown & { wordChars: number; nonWordChars: number }> {\n const order: string[] = [];\n const map = new Map<\n string,\n CharCollectorBreakdown & { wordChars: number; nonWordChars: number }\n >();\n\n for (const chunk of chunks) {\n const existing = map.get(chunk.locale);\n if (existing) {\n existing.chars += chunk.chars;\n existing.wordChars += chunk.wordChars;\n existing.nonWordChars += chunk.nonWordChars;\n if (chunk.nonWords) {\n if (!existing.nonWords) {\n existing.nonWords = createNonWordCollection();\n }\n mergeNonWordCollections(existing.nonWords, chunk.nonWords);\n }\n continue;\n }\n\n order.push(chunk.locale);\n map.set(chunk.locale, {\n locale: chunk.locale,\n chars: chunk.chars,\n wordChars: chunk.wordChars,\n nonWordChars: chunk.nonWordChars,\n nonWords: chunk.nonWords\n ? mergeNonWordCollections(createNonWordCollection(), chunk.nonWords)\n : undefined,\n });\n }\n\n return order.map((locale) => map.get(locale)!);\n}\n\nexport function aggregateByLocale(chunks: ChunkAnalysis[]): CollectorBreakdown[] {\n const order: string[] = [];\n const map = new Map<string, CollectorBreakdown>();\n\n for (const chunk of chunks) {\n const existing = map.get(chunk.locale);\n if (existing) {\n existing.words += chunk.words;\n appendAll(existing.segments, chunk.segments);\n continue;\n }\n\n order.push(chunk.locale);\n map.set(chunk.locale, {\n locale: chunk.locale,\n words: chunk.words,\n segments: [...chunk.segments],\n });\n }\n\n return order.map((locale) => map.get(locale)!);\n}\n","import type { WordCounterMode } from \"./types\";\n\nconst MODE_ALIASES: Record<string, WordCounterMode> = {\n chunk: \"chunk\",\n chunks: \"chunk\",\n segments: \"segments\",\n segment: \"segments\",\n seg: \"segments\",\n collector: \"collector\",\n collect: \"collector\",\n colle: \"collector\",\n char: \"char\",\n chars: \"char\",\n character: \"char\",\n characters: \"char\",\n \"char-collector\": \"char-collector\",\n};\n\nconst CHAR_MODE_ALIASES = new Set([\"char\", \"chars\", \"character\", \"characters\"]);\nconst COLLECTOR_MODE_ALIASES = new Set([\"collector\", \"collect\", \"colle\", \"col\"]);\n\nfunction collapseSeparators(value: string): string {\n return value.replace(/[-_\\s]+/g, \"\");\n}\n\nfunction isComposedCharCollectorFromTokens(value: string): boolean {\n const tokens = value\n .split(/[-_\\s]+/)\n .map((token) => token.trim())\n .filter((token) => token.length > 0);\n if (tokens.length < 2) {\n return false;\n }\n\n let hasCharAlias = false;\n let hasCollectorAlias = false;\n for (const token of tokens) {\n if (CHAR_MODE_ALIASES.has(token)) {\n hasCharAlias = true;\n continue;\n }\n if (COLLECTOR_MODE_ALIASES.has(token)) {\n hasCollectorAlias = true;\n continue;\n }\n return false;\n }\n\n return hasCharAlias && hasCollectorAlias;\n}\n\nfunction isComposedCharCollectorCompact(value: string): boolean {\n for (const charAlias of CHAR_MODE_ALIASES) {\n for (const collectorAlias of COLLECTOR_MODE_ALIASES) {\n if (value === `${charAlias}${collectorAlias}` || value === `${collectorAlias}${charAlias}`) {\n return true;\n }\n }\n }\n return false;\n}\n\nexport function normalizeMode(input?: string | null): WordCounterMode | null {\n if (!input) {\n return null;\n }\n const normalized = input.trim().toLowerCase();\n const direct = MODE_ALIASES[normalized];\n if (direct) {\n return direct;\n }\n\n if (isComposedCharCollectorFromTokens(normalized)) {\n return \"char-collector\";\n }\n\n const compact = collapseSeparators(normalized);\n if (isComposedCharCollectorCompact(compact)) {\n return \"char-collector\";\n }\n\n return MODE_ALIASES[compact] ?? null;\n}\n\nexport function resolveMode(\n input?: string | null,\n fallback: WordCounterMode = \"chunk\",\n): WordCounterMode {\n return normalizeMode(input) ?? fallback;\n}\n","import type { LatinHintRule } from \"./types\";\n\nconst DEFAULT_LATIN_HINT_RULES_SOURCE = [\n { tag: \"de\", pattern: \"[äöüÄÖÜß]\" },\n { tag: \"es\", pattern: \"[ñÑ¿¡]\" },\n { tag: \"pt\", pattern: \"[ãõÃÕ]\" },\n { tag: \"fr\", pattern: \"[œŒæÆ]\" },\n { tag: \"pl\", pattern: \"[ąćęłńśźżĄĆĘŁŃŚŹŻ]\" },\n { tag: \"tr\", pattern: \"[ıİğĞşŞ]\" },\n { tag: \"ro\", pattern: \"[ăĂâÂîÎșȘțȚ]\" },\n { tag: \"hu\", pattern: \"[őŐűŰ]\" },\n { tag: \"is\", pattern: \"[ðÐþÞ]\" },\n] satisfies LatinHintRule[];\n\nexport const DEFAULT_LATIN_HINT_RULES: ReadonlyArray<Readonly<LatinHintRule>> = Object.freeze(\n DEFAULT_LATIN_HINT_RULES_SOURCE.map((rule) => Object.freeze({ ...rule })),\n);\n","import type { LatinHintRule } from \"./types\";\nimport { DEFAULT_LATIN_HINT_RULES } from \"./latin-hints\";\n\nexport const DEFAULT_LOCALE = \"und-Latn\";\nexport const DEFAULT_HAN_TAG = \"und-Hani\";\n\nconst MAX_LATIN_HINT_PATTERN_LENGTH = 256;\n\nexport interface LocaleDetectOptions {\n latinLanguageHint?: string;\n latinTagHint?: string;\n latinLocaleHint?: string;\n latinHintRules?: LatinHintRule[];\n useDefaultLatinHints?: boolean;\n hanLanguageHint?: string;\n hanTagHint?: string;\n}\n\ntype ResolvedLatinHintRule = {\n tag: string;\n pattern: RegExp;\n priority: number;\n order: number;\n};\n\nexport type LocaleDetectContext = {\n latinHint?: string;\n hanHint?: string;\n latinHintRules: ResolvedLatinHintRule[];\n latinLocales: Set<string>;\n};\n\nexport type LocaleDetectTraceSource = \"script\" | \"hint\" | \"fallback\";\nexport type LocaleDetectTrace = {\n locale: string | null;\n source?: LocaleDetectTraceSource;\n reason?: string;\n};\n\nconst regex = {\n hiragana: /\\p{Script=Hiragana}/u,\n katakana: /\\p{Script=Katakana}/u,\n hangul: /\\p{Script=Hangul}/u,\n han: /\\p{Script=Han}/u,\n latin: /\\p{Script=Latin}/u,\n arabic: /\\p{Script=Arabic}/u,\n cyrillic: /\\p{Script=Cyrillic}/u,\n devanagari: /\\p{Script=Devanagari}/u,\n thai: /\\p{Script=Thai}/u,\n};\n\nconst defaultLatinLocales = new Set<string>([\n DEFAULT_LOCALE,\n ...DEFAULT_LATIN_HINT_RULES.map((hint) => hint.tag),\n]);\n\nexport function isLatinLocale(locale: string, context?: LocaleDetectContext): boolean {\n if (context) {\n return context.latinLocales.has(locale);\n }\n return defaultLatinLocales.has(locale);\n}\n\nfunction resolveLatinHint(options: LocaleDetectOptions): string | undefined {\n const latinTagHint = options.latinTagHint?.trim();\n if (latinTagHint) {\n return latinTagHint;\n }\n\n const latinLanguageHint = options.latinLanguageHint?.trim();\n if (latinLanguageHint) {\n return latinLanguageHint;\n }\n\n const latinLocaleHint = options.latinLocaleHint?.trim();\n if (latinLocaleHint) {\n return latinLocaleHint;\n }\n\n return undefined;\n}\n\nfunction resolveHanHint(options: LocaleDetectOptions): string | undefined {\n const hanTagHint = options.hanTagHint?.trim();\n if (hanTagHint) {\n return hanTagHint;\n }\n\n const hanLanguageHint = options.hanLanguageHint?.trim();\n if (hanLanguageHint) {\n return hanLanguageHint;\n }\n\n return undefined;\n}\n\nfunction compileLatinHintPattern(pattern: string | RegExp, label: string): RegExp {\n const source = typeof pattern === \"string\" ? pattern : pattern.source;\n const hasUnicodeMode =\n typeof pattern !== \"string\" && (pattern.flags.includes(\"u\") || pattern.flags.includes(\"v\"));\n const flags =\n typeof pattern === \"string\" ? \"u\" : hasUnicodeMode ? pattern.flags : `${pattern.flags}u`;\n if (source.length === 0) {\n throw new Error(`${label}: pattern must not be empty.`);\n }\n if (source.length > MAX_LATIN_HINT_PATTERN_LENGTH) {\n throw new Error(\n `${label}: pattern must be at most ${MAX_LATIN_HINT_PATTERN_LENGTH} characters.`,\n );\n }\n try {\n return new RegExp(source, flags);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`${label}: invalid Unicode regex pattern (${message}).`);\n }\n}\n\nfunction normalizeLatinHintPriority(priority: unknown, label: string): number {\n if (priority === undefined) {\n return 0;\n }\n if (typeof priority !== \"number\" || !Number.isFinite(priority)) {\n throw new Error(`${label}: priority must be a finite number when provided.`);\n }\n return priority;\n}\n\nfunction compileLatinHintRule(\n rule: Readonly<LatinHintRule>,\n order: number,\n label: string,\n): ResolvedLatinHintRule {\n const tag = typeof rule.tag === \"string\" ? rule.tag.trim() : \"\";\n if (!tag) {\n throw new Error(`${label}: tag must be a non-empty string.`);\n }\n const pattern = compileLatinHintPattern(rule.pattern, label);\n const priority = normalizeLatinHintPriority(rule.priority, label);\n return {\n tag,\n pattern,\n priority,\n order,\n };\n}\n\nfunction resolveLatinHintRules(options: LocaleDetectOptions): ResolvedLatinHintRule[] {\n const useDefaultLatinHints = options.useDefaultLatinHints !== false;\n const customRules = options.latinHintRules ?? [];\n const combinedRules: Array<{ rule: Readonly<LatinHintRule>; label: string }> = [];\n\n for (let index = 0; index < customRules.length; index += 1) {\n const rule = customRules[index];\n if (!rule) {\n continue;\n }\n combinedRules.push({\n rule,\n label: `Invalid custom Latin hint rule at index ${index}`,\n });\n }\n\n if (useDefaultLatinHints) {\n for (let index = 0; index < DEFAULT_LATIN_HINT_RULES.length; index += 1) {\n const rule = DEFAULT_LATIN_HINT_RULES[index];\n if (!rule) {\n continue;\n }\n combinedRules.push({\n rule,\n label: `Invalid default Latin hint rule at index ${index}`,\n });\n }\n }\n\n const resolvedRules = combinedRules.map((entry, index) =>\n compileLatinHintRule(entry.rule, index, entry.label),\n );\n\n resolvedRules.sort((left, right) => {\n if (left.priority !== right.priority) {\n return right.priority - left.priority;\n }\n return left.order - right.order;\n });\n\n return resolvedRules;\n}\n\nexport function resolveLocaleDetectContext(options: LocaleDetectOptions = {}): LocaleDetectContext {\n const latinHint = resolveLatinHint(options);\n const latinHintRules = resolveLatinHintRules(options);\n const latinLocales = new Set<string>([DEFAULT_LOCALE]);\n for (const rule of latinHintRules) {\n latinLocales.add(rule.tag);\n }\n if (latinHint) {\n latinLocales.add(latinHint);\n }\n\n return {\n latinHint,\n hanHint: resolveHanHint(options),\n latinHintRules,\n latinLocales,\n };\n}\n\nfunction detectLatinLocale(char: string, context: LocaleDetectContext): string {\n for (const hint of context.latinHintRules) {\n hint.pattern.lastIndex = 0;\n if (hint.pattern.test(char)) {\n return hint.tag;\n }\n }\n return DEFAULT_LOCALE;\n}\n\nexport function detectLocaleForCharTrace(\n char: string,\n previousLocale?: string | null,\n options: LocaleDetectOptions = {},\n context: LocaleDetectContext = resolveLocaleDetectContext(options),\n allowLatinLocaleCarry = true,\n allowJapaneseHanCarry = true,\n): LocaleDetectTrace {\n if (regex.hiragana.test(char) || regex.katakana.test(char)) {\n return {\n locale: \"ja\",\n source: \"script\",\n reason: \"hiragana-katakana\",\n };\n }\n if (regex.hangul.test(char)) {\n return {\n locale: \"ko\",\n source: \"script\",\n reason: \"hangul\",\n };\n }\n if (regex.arabic.test(char)) {\n return {\n locale: \"ar\",\n source: \"script\",\n reason: \"arabic\",\n };\n }\n if (regex.cyrillic.test(char)) {\n return {\n locale: \"ru\",\n source: \"script\",\n reason: \"cyrillic\",\n };\n }\n if (regex.devanagari.test(char)) {\n return {\n locale: \"hi\",\n source: \"script\",\n reason: \"devanagari\",\n };\n }\n if (regex.thai.test(char)) {\n return {\n locale: \"th\",\n source: \"script\",\n reason: \"thai\",\n };\n }\n\n if (regex.han.test(char)) {\n if (allowJapaneseHanCarry && previousLocale && previousLocale.startsWith(\"ja\")) {\n return {\n locale: previousLocale,\n source: \"script\",\n reason: \"japanese-han-carry\",\n };\n }\n if (context.hanHint) {\n return {\n locale: context.hanHint,\n source: \"hint\",\n reason: \"explicit-han-hint\",\n };\n }\n return {\n locale: DEFAULT_HAN_TAG,\n source: \"fallback\",\n reason:\n previousLocale && previousLocale.startsWith(\"ja\") && !allowJapaneseHanCarry\n ? \"han-fallback-after-boundary\"\n : \"han-fallback\",\n };\n }\n\n if (regex.latin.test(char)) {\n const hintedLocale = detectLatinLocale(char, context);\n if (hintedLocale !== DEFAULT_LOCALE) {\n return {\n locale: hintedLocale,\n source: \"hint\",\n reason: \"latin-hint-rule\",\n };\n }\n if (\n allowLatinLocaleCarry &&\n previousLocale &&\n isLatinLocale(previousLocale, context) &&\n previousLocale !== DEFAULT_LOCALE\n ) {\n return {\n locale: previousLocale,\n source: \"hint\",\n reason: \"latin-locale-carry\",\n };\n }\n if (context.latinHint) {\n return {\n locale: context.latinHint,\n source: \"hint\",\n reason: \"explicit-latin-hint\",\n };\n }\n return {\n locale: DEFAULT_LOCALE,\n source: \"fallback\",\n reason: \"latin-fallback\",\n };\n }\n\n return {\n locale: null,\n };\n}\n\nexport function detectLocaleForChar(\n char: string,\n previousLocale?: string | null,\n options: LocaleDetectOptions = {},\n context: LocaleDetectContext = resolveLocaleDetectContext(options),\n allowLatinLocaleCarry = true,\n allowJapaneseHanCarry = true,\n): string | null {\n return detectLocaleForCharTrace(\n char,\n previousLocale,\n options,\n context,\n allowLatinLocaleCarry,\n allowJapaneseHanCarry,\n ).locale;\n}\n","import {\n DEFAULT_LOCALE,\n detectLocaleForChar,\n isLatinLocale,\n resolveLocaleDetectContext,\n type LocaleDetectOptions,\n} from \"./locale-detect\";\nimport type { LocaleChunk } from \"./types\";\n\nconst HARD_BOUNDARY_REGEX = /[\\r\\n,.!?;:,、。!?;:.。、]/u;\nconst LATIN_PROMOTION_BREAK_REGEX = /[\\s,.!?;:,、。!?;:.。、]/u;\n\nexport function segmentTextByLocale(\n text: string,\n options: LocaleDetectOptions = {},\n): LocaleChunk[] {\n const context = resolveLocaleDetectContext(options);\n const chunks: LocaleChunk[] = [];\n // Keep currentLocale as a non-null string to simplify type-narrowing.\n let currentLocale: string = DEFAULT_LOCALE;\n let buffer = \"\";\n let bufferHasScript = false;\n let sawCarryBoundary = false;\n\n const updateCarryBoundaryState = (detected: string | null, char: string): void => {\n if (detected !== null) {\n sawCarryBoundary = false;\n return;\n }\n if (HARD_BOUNDARY_REGEX.test(char)) {\n sawCarryBoundary = true;\n }\n };\n\n for (const char of text) {\n const detected = detectLocaleForChar(\n char,\n currentLocale,\n options,\n context,\n !sawCarryBoundary,\n !sawCarryBoundary,\n );\n const targetLocale = detected ?? currentLocale;\n\n // If buffer is empty, this is the first character for a new chunk.\n if (buffer === \"\") {\n currentLocale = targetLocale;\n buffer = char;\n bufferHasScript = detected !== null;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n if (detected !== null && !bufferHasScript) {\n currentLocale = targetLocale;\n buffer += char;\n bufferHasScript = true;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n if (targetLocale !== currentLocale && detected !== null) {\n if (currentLocale === DEFAULT_LOCALE && isLatinLocale(targetLocale, context)) {\n const promotionBreakIndex = findLastLatinPromotionBreakIndex(buffer);\n if (promotionBreakIndex === -1) {\n currentLocale = targetLocale;\n buffer += char;\n bufferHasScript = true;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n const prefix = buffer.slice(0, promotionBreakIndex + 1);\n const suffix = buffer.slice(promotionBreakIndex + 1);\n if (prefix.length > 0) {\n chunks.push({ locale: currentLocale, text: prefix });\n }\n currentLocale = targetLocale;\n buffer = `${suffix}${char}`;\n bufferHasScript = true;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n // currentLocale is guaranteed to be a string here.\n chunks.push({ locale: currentLocale, text: buffer });\n currentLocale = targetLocale;\n buffer = char;\n bufferHasScript = true;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n buffer += char;\n if (detected !== null) {\n bufferHasScript = true;\n }\n updateCarryBoundaryState(detected, char);\n }\n\n if (buffer.length > 0) {\n chunks.push({ locale: currentLocale, text: buffer });\n }\n\n return mergeAdjacentChunks(chunks);\n}\n\nfunction findLastLatinPromotionBreakIndex(buffer: string): number {\n for (let index = buffer.length - 1; index >= 0; index -= 1) {\n const char = buffer[index];\n if (!char) {\n continue;\n }\n if (LATIN_PROMOTION_BREAK_REGEX.test(char)) {\n return index;\n }\n }\n return -1;\n}\n\nfunction mergeAdjacentChunks(chunks: LocaleChunk[]): LocaleChunk[] {\n if (chunks.length === 0) {\n return chunks;\n }\n\n const merged: LocaleChunk[] = [];\n // We already returned for empty arrays above, so the first element is present.\n let last = chunks[0]!;\n\n for (let i = 1; i < chunks.length; i++) {\n const chunk = chunks[i]!;\n if (chunk.locale === last.locale) {\n last = { locale: last.locale, text: last.text + chunk.text };\n } else {\n merged.push(last);\n last = chunk;\n }\n }\n\n merged.push(last);\n return merged;\n}\n","import {\n analyzeCharChunk,\n analyzeChunk,\n aggregateByLocale,\n aggregateCharsByLocale,\n} from \"./analyze\";\nimport { resolveMode } from \"./mode\";\nimport { segmentTextByLocale } from \"./segment\";\nimport { countCharsForLocale, countWordsForLocale } from \"./segmenter\";\nimport { createNonWordCollection, mergeNonWordCollections } from \"./non-words\";\nimport type {\n CharBreakdown,\n CharCollectorBreakdown,\n ChunkBreakdown,\n ChunkWithSegments,\n NonWordCollection,\n WordCounterMode,\n WordCounterOptions,\n WordCounterResult,\n} from \"./types\";\n\nexport type {\n LatinHintRule,\n NonWordCollection,\n WordCounterMode,\n WordCounterOptions,\n WordCounterResult,\n WordCounterBreakdown,\n} from \"./types\";\n\nexport { countCharsForLocale, countWordsForLocale, segmentTextByLocale };\nexport { DEFAULT_LATIN_HINT_RULES } from \"./latin-hints\";\n\nexport function wordCounter(text: string, options: WordCounterOptions = {}): WordCounterResult {\n const mode: WordCounterMode = resolveMode(options.mode, \"chunk\");\n const collectNonWords = Boolean(options.nonWords);\n const includeWhitespace = Boolean(options.includeWhitespace);\n const chunks = segmentTextByLocale(text, {\n latinLanguageHint: options.latinLanguageHint,\n latinTagHint: options.latinTagHint,\n latinLocaleHint: options.latinLocaleHint,\n latinHintRules: options.latinHintRules,\n useDefaultLatinHints: options.useDefaultLatinHints,\n hanLanguageHint: options.hanLanguageHint,\n hanTagHint: options.hanTagHint,\n });\n\n if (mode === \"char\" || mode === \"char-collector\") {\n const analyzed = chunks.map((chunk) =>\n analyzeCharChunk(chunk, collectNonWords, includeWhitespace),\n );\n const total = analyzed.reduce((sum, chunk) => sum + chunk.chars, 0);\n const counts = collectNonWords\n ? {\n words: analyzed.reduce((sum, chunk) => sum + chunk.wordChars, 0),\n nonWords: analyzed.reduce((sum, chunk) => sum + chunk.nonWordChars, 0),\n total,\n }\n : undefined;\n\n if (mode === \"char\") {\n const items: CharBreakdown[] = analyzed.map((chunk) => ({\n locale: chunk.locale,\n text: chunk.text,\n chars: chunk.chars,\n nonWords: chunk.nonWords,\n }));\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n },\n };\n }\n\n const aggregated = aggregateCharsByLocale(analyzed);\n const items: CharCollectorBreakdown[] = aggregated.map((chunk) => ({\n locale: chunk.locale,\n chars: chunk.chars,\n nonWords: chunk.nonWords,\n }));\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n },\n };\n }\n\n const analyzed = chunks.map((chunk) => analyzeChunk(chunk, collectNonWords, includeWhitespace));\n const wordsTotal = analyzed.reduce((sum, chunk) => sum + chunk.words, 0);\n const nonWordsTotal = collectNonWords\n ? analyzed.reduce((sum, chunk) => {\n if (!chunk.nonWords) {\n return sum;\n }\n return sum + getNonWordTotal(chunk.nonWords);\n }, 0)\n : 0;\n const total = analyzed.reduce((sum, chunk) => {\n let chunkTotal = chunk.words;\n if (collectNonWords && chunk.nonWords) {\n chunkTotal += getNonWordTotal(chunk.nonWords);\n }\n return sum + chunkTotal;\n }, 0);\n\n const counts = collectNonWords\n ? { words: wordsTotal, nonWords: nonWordsTotal, total }\n : undefined;\n\n if (mode === \"segments\") {\n const items: ChunkWithSegments[] = analyzed.map((chunk) => ({\n locale: chunk.locale,\n text: chunk.text,\n words: chunk.words,\n segments: chunk.segments,\n nonWords: chunk.nonWords,\n }));\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n },\n };\n }\n\n if (mode === \"collector\") {\n const items = aggregateByLocale(analyzed);\n const nonWords = collectNonWordsAggregate(analyzed, collectNonWords);\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n nonWords,\n },\n };\n }\n\n const items: ChunkBreakdown[] = analyzed.map((chunk) => ({\n locale: chunk.locale,\n text: chunk.text,\n words: chunk.words,\n nonWords: chunk.nonWords,\n }));\n\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n },\n };\n}\n\nfunction getNonWordTotal(nonWords: NonWordCollection): number {\n return (\n nonWords.counts.emoji +\n nonWords.counts.symbols +\n nonWords.counts.punctuation +\n (nonWords.counts.whitespace ?? 0)\n );\n}\n\nfunction collectNonWordsAggregate(\n analyzed: Array<{ nonWords?: NonWordCollection }>,\n enabled: boolean,\n): NonWordCollection | undefined {\n if (!enabled) {\n return undefined;\n }\n const collection = createNonWordCollection();\n for (const chunk of analyzed) {\n if (!chunk.nonWords) {\n continue;\n }\n mergeNonWordCollections(collection, chunk.nonWords);\n }\n return collection;\n}\n","import { wordCounter } from \"./wc\";\n\nexport default wordCounter;\nexport { countCharsForLocale, countWordsForLocale, segmentTextByLocale } from \"./wc\";\nexport { DEFAULT_LATIN_HINT_RULES } from \"./wc\";\nexport type {\n LatinHintRule,\n NonWordCollection,\n WordCounterMode,\n WordCounterOptions,\n WordCounterResult,\n WordCounterBreakdown,\n} from \"./wc\";\n","import type { WordCounterMode, WordCounterOptions, WordCounterResult } from \"../wc/types\";\nimport wordCounter from \"../wc\";\nimport { parseMarkdown } from \"./parse-markdown\";\nimport type { SectionMode, SectionedResult } from \"./types\";\n\nfunction normalizeText(value: unknown): string {\n if (value == null) {\n return \"\";\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nfunction buildPerKeyItems(\n data: Record<string, unknown> | null,\n mode: WordCounterMode,\n options: WordCounterOptions,\n): Array<{ name: string; source: \"frontmatter\"; result: WordCounterResult }> {\n if (!data || typeof data !== \"object\" || Array.isArray(data)) {\n return [];\n }\n\n return Object.entries(data).map(([key, value]) => {\n const valueText = normalizeText(value);\n const text = valueText ? `${key}: ${valueText}` : key;\n return {\n name: key,\n source: \"frontmatter\",\n result: wordCounter(text, options),\n };\n });\n}\n\nfunction buildSingleItem(\n name: string,\n text: string,\n mode: WordCounterMode,\n options: WordCounterOptions,\n source: \"frontmatter\" | \"content\",\n) {\n return [{ name, source, result: wordCounter(text, options) }];\n}\n\nfunction sumTotals(items: Array<{ result: WordCounterResult }>): number {\n return items.reduce((sum, item) => sum + item.result.total, 0);\n}\n\nexport function countSections(\n input: string,\n section: SectionMode,\n options: WordCounterOptions = {},\n): SectionedResult {\n const mode: WordCounterMode = options.mode ?? \"chunk\";\n if (section === \"all\") {\n const result = wordCounter(input, options);\n return {\n section,\n total: result.total,\n frontmatterType: null,\n items: [{ name: \"all\", source: \"content\", result }],\n };\n }\n\n const parsed = parseMarkdown(input);\n const frontmatterText = parsed.frontmatter ?? \"\";\n const contentText = parsed.content ?? \"\";\n\n let items: Array<{ name: string; source: \"frontmatter\" | \"content\"; result: WordCounterResult }> =\n [];\n\n if (section === \"frontmatter\") {\n items = buildSingleItem(\"frontmatter\", frontmatterText, mode, options, \"frontmatter\");\n } else if (section === \"content\") {\n items = buildSingleItem(\"content\", contentText, mode, options, \"content\");\n } else if (section === \"split\") {\n items = [\n ...buildSingleItem(\"frontmatter\", frontmatterText, mode, options, \"frontmatter\"),\n ...buildSingleItem(\"content\", contentText, mode, options, \"content\"),\n ];\n } else if (section === \"per-key\") {\n items = buildPerKeyItems(parsed.data, mode, options);\n } else if (section === \"split-per-key\") {\n items = [\n ...buildPerKeyItems(parsed.data, mode, options),\n ...buildSingleItem(\"content\", contentText, mode, options, \"content\"),\n ];\n }\n\n return {\n section,\n total: sumTotals(items),\n frontmatterType: parsed.frontmatterType,\n items,\n };\n}\n","import type { SectionMode } from \"../markdown\";\nimport { DEFAULT_HAN_TAG, DEFAULT_LOCALE } from \"../wc/locale-detect\";\nimport type { WordCounterMode } from \"../wc/types\";\nimport type { DetectorRouteTag } from \"./policy\";\nimport type { DetectorMode } from \"./types\";\n\nexport type DetectorDebugVerbosity = \"compact\" | \"verbose\";\nexport const DETECTOR_EVIDENCE_PREVIEW_LIMIT = 160;\n\nexport type DetectorEvidenceConfig = {\n verbosity: DetectorDebugVerbosity;\n mode: WordCounterMode;\n section: SectionMode;\n};\n\nexport type DetectorDebugSummary = {\n mode: DetectorMode;\n engine: \"none\" | \"whatlang-wasm\";\n windowsTotal: number;\n accepted: number;\n fallback: number;\n routes: {\n latin: number;\n han: number;\n };\n acceptancePaths: {\n reliable: number;\n corroborated: number;\n };\n fallbackReasons: {\n notEligible: number;\n noCandidate: number;\n belowThreshold: number;\n qualityGate: number;\n corroborationUnreliable: number;\n };\n};\n\nexport type DetectorDebugContext = {\n emit?: (\n event: string,\n details?: Record<string, unknown>,\n options?: { verbosity?: DetectorDebugVerbosity },\n ) => void;\n summary?: DetectorDebugSummary;\n evidence?: DetectorEvidenceConfig;\n};\n\nexport type DetectorFallbackReason =\n | \"notEligible\"\n | \"noCandidate\"\n | \"belowThreshold\"\n | \"qualityGate\"\n | \"corroborationUnreliable\";\n\nexport function createDetectorDebugSummary(\n mode: DetectorMode,\n engine: DetectorDebugSummary[\"engine\"] = mode === \"wasm\" ? \"whatlang-wasm\" : \"none\",\n): DetectorDebugSummary {\n return {\n mode,\n engine,\n windowsTotal: 0,\n accepted: 0,\n fallback: 0,\n routes: {\n latin: 0,\n han: 0,\n },\n acceptancePaths: {\n reliable: 0,\n corroborated: 0,\n },\n fallbackReasons: {\n notEligible: 0,\n noCandidate: 0,\n belowThreshold: 0,\n qualityGate: 0,\n corroborationUnreliable: 0,\n },\n };\n}\n\nexport function mergeDetectorDebugSummaries(\n summaries: Array<DetectorDebugSummary | undefined>,\n): DetectorDebugSummary | undefined {\n const present = summaries.filter(\n (summary): summary is DetectorDebugSummary => summary !== undefined,\n );\n if (present.length === 0) {\n return undefined;\n }\n\n const first = present[0]!;\n const merged = createDetectorDebugSummary(first.mode, first.engine);\n for (const summary of present) {\n merged.windowsTotal += summary.windowsTotal;\n merged.accepted += summary.accepted;\n merged.fallback += summary.fallback;\n merged.routes.latin += summary.routes.latin;\n merged.routes.han += summary.routes.han;\n merged.acceptancePaths.reliable += summary.acceptancePaths.reliable;\n merged.acceptancePaths.corroborated += summary.acceptancePaths.corroborated;\n merged.fallbackReasons.notEligible += summary.fallbackReasons.notEligible;\n merged.fallbackReasons.noCandidate += summary.fallbackReasons.noCandidate;\n merged.fallbackReasons.belowThreshold += summary.fallbackReasons.belowThreshold;\n merged.fallbackReasons.qualityGate += summary.fallbackReasons.qualityGate;\n merged.fallbackReasons.corroborationUnreliable +=\n summary.fallbackReasons.corroborationUnreliable;\n }\n\n return merged;\n}\n\nexport function recordDetectorWindow(\n summary: DetectorDebugSummary | undefined,\n routeTag: DetectorRouteTag,\n): void {\n if (!summary) {\n return;\n }\n\n summary.windowsTotal += 1;\n if (routeTag === DEFAULT_LOCALE) {\n summary.routes.latin += 1;\n return;\n }\n if (routeTag === DEFAULT_HAN_TAG) {\n summary.routes.han += 1;\n }\n}\n\nexport function recordDetectorAccepted(\n summary: DetectorDebugSummary | undefined,\n path: \"reliable\" | \"corroborated\",\n): void {\n if (!summary) {\n return;\n }\n\n summary.accepted += 1;\n if (path === \"reliable\") {\n summary.acceptancePaths.reliable += 1;\n return;\n }\n\n summary.acceptancePaths.corroborated += 1;\n}\n\nexport function recordDetectorFallback(\n summary: DetectorDebugSummary | undefined,\n reason: DetectorFallbackReason,\n): void {\n if (!summary) {\n return;\n }\n\n summary.fallback += 1;\n summary.fallbackReasons[reason] += 1;\n}\n\nexport function createDetectorEvidencePreview(text: string): {\n preview: string;\n truncated: boolean;\n} {\n const collapsed = text.replace(/\\s+/gu, \" \").trim();\n const codePoints = Array.from(collapsed);\n if (codePoints.length <= DETECTOR_EVIDENCE_PREVIEW_LIMIT) {\n return {\n preview: collapsed,\n truncated: false,\n };\n }\n\n return {\n preview: codePoints.slice(0, DETECTOR_EVIDENCE_PREVIEW_LIMIT).join(\"\"),\n truncated: true,\n };\n}\n","import {\n DEFAULT_LOCALE,\n detectLocaleForCharTrace,\n isLatinLocale,\n resolveLocaleDetectContext,\n type LocaleDetectContext,\n type LocaleDetectOptions,\n type LocaleDetectTraceSource,\n} from \"../wc/locale-detect\";\nimport type { LocaleChunk } from \"../wc/types\";\nimport { createDetectorEvidencePreview, DETECTOR_EVIDENCE_PREVIEW_LIMIT } from \"./debug\";\nimport type {\n DetectorInspectChunk,\n DetectorInspectInput,\n DetectorInspectInputOptions,\n} from \"./inspect-types\";\n\nconst HARD_BOUNDARY_REGEX = /[\\r\\n,.!?;:,、。!?;:.。、]/u;\nconst LATIN_PROMOTION_BREAK_REGEX = /[\\s,.!?;:,、。!?;:.。、]/u;\n\nexport type TracedLocaleChunk = LocaleChunk & {\n source: \"script\" | \"hint\" | \"fallback\";\n reason?: string;\n};\n\nfunction findLastLatinPromotionBreakIndex(buffer: string): number {\n for (let index = buffer.length - 1; index >= 0; index -= 1) {\n const char = buffer[index];\n if (!char) {\n continue;\n }\n if (LATIN_PROMOTION_BREAK_REGEX.test(char)) {\n return index;\n }\n }\n return -1;\n}\n\nfunction mergeAdjacentTracedChunks(chunks: TracedLocaleChunk[]): TracedLocaleChunk[] {\n if (chunks.length === 0) {\n return chunks;\n }\n\n const merged: TracedLocaleChunk[] = [];\n let last = chunks[0]!;\n\n for (let index = 1; index < chunks.length; index += 1) {\n const chunk = chunks[index]!;\n if (chunk.locale === last.locale) {\n last = {\n ...last,\n text: last.text + chunk.text,\n };\n continue;\n }\n merged.push(last);\n last = chunk;\n }\n\n merged.push(last);\n return merged;\n}\n\nexport function segmentTextByLocaleWithTrace(\n text: string,\n options: LocaleDetectOptions = {},\n): TracedLocaleChunk[] {\n const context: LocaleDetectContext = resolveLocaleDetectContext(options);\n const chunks: TracedLocaleChunk[] = [];\n let currentLocale = DEFAULT_LOCALE;\n let currentSource: LocaleDetectTraceSource = \"fallback\";\n let currentReason = \"latin-fallback\";\n let buffer = \"\";\n let bufferHasScript = false;\n let sawCarryBoundary = false;\n\n const updateCarryBoundaryState = (detected: string | null, char: string): void => {\n if (detected !== null) {\n sawCarryBoundary = false;\n return;\n }\n if (HARD_BOUNDARY_REGEX.test(char)) {\n sawCarryBoundary = true;\n }\n };\n\n const pushChunk = (\n locale: string,\n textValue: string,\n source: LocaleDetectTraceSource,\n reason?: string,\n ) => {\n if (textValue.length === 0) {\n return;\n }\n chunks.push({\n locale,\n text: textValue,\n source,\n ...(reason ? { reason } : {}),\n });\n };\n\n for (const char of text) {\n const trace = detectLocaleForCharTrace(\n char,\n currentLocale,\n options,\n context,\n !sawCarryBoundary,\n !sawCarryBoundary,\n );\n const detected = trace.locale;\n const targetLocale = detected ?? currentLocale;\n\n if (buffer === \"\") {\n currentLocale = targetLocale;\n currentSource = trace.source ?? \"fallback\";\n currentReason = trace.reason ?? currentReason;\n buffer = char;\n bufferHasScript = detected !== null;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n if (detected !== null && !bufferHasScript) {\n currentLocale = targetLocale;\n currentSource = trace.source ?? currentSource;\n currentReason = trace.reason ?? currentReason;\n buffer += char;\n bufferHasScript = true;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n if (targetLocale !== currentLocale && detected !== null) {\n if (currentLocale === DEFAULT_LOCALE && isLatinLocale(targetLocale, context)) {\n const promotionBreakIndex = findLastLatinPromotionBreakIndex(buffer);\n if (promotionBreakIndex === -1) {\n currentLocale = targetLocale;\n currentSource = trace.source ?? currentSource;\n currentReason = trace.reason ?? currentReason;\n buffer += char;\n bufferHasScript = true;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n const prefix = buffer.slice(0, promotionBreakIndex + 1);\n const suffix = buffer.slice(promotionBreakIndex + 1);\n pushChunk(currentLocale, prefix, currentSource, currentReason);\n currentLocale = targetLocale;\n currentSource = trace.source ?? currentSource;\n currentReason = trace.reason ?? currentReason;\n buffer = `${suffix}${char}`;\n bufferHasScript = true;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n pushChunk(currentLocale, buffer, currentSource, currentReason);\n currentLocale = targetLocale;\n currentSource = trace.source ?? \"fallback\";\n currentReason = trace.reason ?? currentReason;\n buffer = char;\n bufferHasScript = true;\n updateCarryBoundaryState(detected, char);\n continue;\n }\n\n buffer += char;\n if (detected !== null) {\n bufferHasScript = true;\n }\n updateCarryBoundaryState(detected, char);\n }\n\n pushChunk(currentLocale, buffer, currentSource, currentReason);\n return mergeAdjacentTracedChunks(chunks);\n}\n\nexport function createInspectInput(\n text: string,\n inputOptions: DetectorInspectInputOptions | undefined,\n): DetectorInspectInput {\n const preview = createDetectorEvidencePreview(text);\n return {\n sourceType: inputOptions?.sourceType ?? \"inline\",\n ...(inputOptions?.path ? { path: inputOptions.path } : {}),\n textLength: text.length,\n textPreview: preview.preview,\n textPreviewTruncated: preview.truncated,\n };\n}\n\nexport function createInspectChunk(\n index: number,\n chunk: LocaleChunk,\n extras?: Pick<DetectorInspectChunk, \"source\" | \"reason\">,\n): DetectorInspectChunk {\n const preview = createDetectorEvidencePreview(chunk.text);\n return {\n index,\n locale: chunk.locale,\n textPreview: preview.preview,\n textPreviewTruncated: preview.truncated,\n ...(extras?.source ? { source: extras.source } : {}),\n ...(extras?.reason ? { reason: extras.reason } : {}),\n };\n}\n\nexport function createInspectPreview(text: string): {\n textPreview: string;\n textPreviewTruncated: boolean;\n} {\n const preview = createDetectorEvidencePreview(text);\n return {\n textPreview: preview.preview,\n textPreviewTruncated: preview.truncated,\n };\n}\n\nexport { DETECTOR_EVIDENCE_PREVIEW_LIMIT as DETECTOR_INSPECT_PREVIEW_LIMIT };\n","import { countSections } from \"../markdown\";\nimport wordCounter, { segmentTextByLocale } from \"../wc\";\nimport {\n createInspectChunk,\n createInspectInput,\n segmentTextByLocaleWithTrace,\n} from \"./inspect-helpers\";\nimport type { DetectorInspectOptions, DetectorInspectResult } from \"./inspect-types\";\nimport type {\n DetectorCountSectionsOptions,\n DetectorLocaleOptions,\n DetectorWordCounterOptions,\n} from \"./types\";\n\nexport async function segmentTextByLocaleWithRegexDetector(\n text: string,\n options: DetectorLocaleOptions = {},\n) {\n return segmentTextByLocale(text, options);\n}\n\nexport async function wordCounterWithRegexDetector(\n text: string,\n options: DetectorWordCounterOptions = {},\n) {\n return wordCounter(text, options);\n}\n\nexport async function countSectionsWithRegexDetector(\n input: string,\n section: Parameters<typeof countSections>[1],\n options: DetectorCountSectionsOptions = {},\n) {\n return countSections(input, section, options);\n}\n\nexport async function inspectTextWithRegexDetector(\n text: string,\n options: DetectorInspectOptions = {},\n): Promise<DetectorInspectResult> {\n if (text.trim().length === 0) {\n return {\n schemaVersion: 1,\n kind: \"detector-inspect\",\n view: \"pipeline\",\n detector: \"regex\",\n input: createInspectInput(text, options.input),\n chunks: [],\n decision: {\n kind: \"empty\",\n notes: [\"No detector-eligible content was present.\"],\n },\n resolvedChunks: [],\n };\n }\n\n const chunks = segmentTextByLocaleWithTrace(text, options);\n\n return {\n schemaVersion: 1,\n kind: \"detector-inspect\",\n view: \"pipeline\",\n detector: \"regex\",\n input: createInspectInput(text, options.input),\n chunks: chunks.map((chunk, index) =>\n createInspectChunk(index, chunk, {\n source: chunk.source,\n reason: chunk.reason,\n }),\n ),\n decision: {\n kind: \"deterministic\",\n notes: [\n \"Regex inspection does not use detector windows or engine confidence.\",\n \"Final locales come directly from script detection, hint rules, and fallback rules.\",\n ],\n },\n resolvedChunks: chunks.map((chunk, index) => createInspectChunk(index, chunk)),\n };\n}\n","import {\n analyzeCharChunk,\n analyzeChunk,\n aggregateByLocale,\n aggregateCharsByLocale,\n} from \"../wc/analyze\";\nimport { resolveMode } from \"../wc/mode\";\nimport { createNonWordCollection, mergeNonWordCollections } from \"../wc/non-words\";\nimport type {\n CharBreakdown,\n CharCollectorBreakdown,\n ChunkBreakdown,\n ChunkWithSegments,\n LocaleChunk,\n NonWordCollection,\n WordCounterMode,\n WordCounterOptions,\n WordCounterResult,\n} from \"../wc/types\";\n\nfunction getNonWordTotal(nonWords: NonWordCollection): number {\n return (\n nonWords.counts.emoji +\n nonWords.counts.symbols +\n nonWords.counts.punctuation +\n (nonWords.counts.whitespace ?? 0)\n );\n}\n\nfunction collectNonWordsAggregate(\n analyzed: Array<{ nonWords?: NonWordCollection }>,\n enabled: boolean,\n): NonWordCollection | undefined {\n if (!enabled) {\n return undefined;\n }\n const collection = createNonWordCollection();\n for (const chunk of analyzed) {\n if (!chunk.nonWords) {\n continue;\n }\n mergeNonWordCollections(collection, chunk.nonWords);\n }\n return collection;\n}\n\nexport function buildWordCounterResultFromChunks(\n chunks: LocaleChunk[],\n options: WordCounterOptions = {},\n): WordCounterResult {\n const mode: WordCounterMode = resolveMode(options.mode, \"chunk\");\n const collectNonWords = Boolean(options.nonWords);\n const includeWhitespace = Boolean(options.includeWhitespace);\n\n if (mode === \"char\" || mode === \"char-collector\") {\n const analyzed = chunks.map((chunk) =>\n analyzeCharChunk(chunk, collectNonWords, includeWhitespace),\n );\n const total = analyzed.reduce((sum, chunk) => sum + chunk.chars, 0);\n const counts = collectNonWords\n ? {\n words: analyzed.reduce((sum, chunk) => sum + chunk.wordChars, 0),\n nonWords: analyzed.reduce((sum, chunk) => sum + chunk.nonWordChars, 0),\n total,\n }\n : undefined;\n\n if (mode === \"char\") {\n const items: CharBreakdown[] = analyzed.map((chunk) => ({\n locale: chunk.locale,\n text: chunk.text,\n chars: chunk.chars,\n nonWords: chunk.nonWords,\n }));\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n },\n };\n }\n\n const aggregated = aggregateCharsByLocale(analyzed);\n const items: CharCollectorBreakdown[] = aggregated.map((chunk) => ({\n locale: chunk.locale,\n chars: chunk.chars,\n nonWords: chunk.nonWords,\n }));\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n },\n };\n }\n\n const analyzed = chunks.map((chunk) => analyzeChunk(chunk, collectNonWords, includeWhitespace));\n const wordsTotal = analyzed.reduce((sum, chunk) => sum + chunk.words, 0);\n const nonWordsTotal = collectNonWords\n ? analyzed.reduce((sum, chunk) => {\n if (!chunk.nonWords) {\n return sum;\n }\n return sum + getNonWordTotal(chunk.nonWords);\n }, 0)\n : 0;\n const total = analyzed.reduce((sum, chunk) => {\n let chunkTotal = chunk.words;\n if (collectNonWords && chunk.nonWords) {\n chunkTotal += getNonWordTotal(chunk.nonWords);\n }\n return sum + chunkTotal;\n }, 0);\n\n const counts = collectNonWords\n ? { words: wordsTotal, nonWords: nonWordsTotal, total }\n : undefined;\n\n if (mode === \"segments\") {\n const items: ChunkWithSegments[] = analyzed.map((chunk) => ({\n locale: chunk.locale,\n text: chunk.text,\n words: chunk.words,\n segments: chunk.segments,\n nonWords: chunk.nonWords,\n }));\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n },\n };\n }\n\n if (mode === \"collector\") {\n const items = aggregateByLocale(analyzed);\n const nonWords = collectNonWordsAggregate(analyzed, collectNonWords);\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n nonWords,\n },\n };\n }\n\n const items: ChunkBreakdown[] = analyzed.map((chunk) => ({\n locale: chunk.locale,\n text: chunk.text,\n words: chunk.words,\n nonWords: chunk.nonWords,\n }));\n\n return {\n total,\n counts,\n breakdown: {\n mode,\n items,\n },\n };\n}\n","import { parseMarkdown } from \"../markdown\";\nimport type { SectionMode, SectionedResult } from \"../markdown\";\nimport type { WordCounterResult } from \"../wc/types\";\nimport type { DetectorCountSectionsOptions } from \"./types\";\nimport { wordCounterWithDetector } from \"./index\";\n\nfunction normalizeText(value: unknown): string {\n if (value == null) {\n return \"\";\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nasync function buildPerKeyItems(\n data: Record<string, unknown> | null,\n options: DetectorCountSectionsOptions,\n): Promise<Array<{ name: string; source: \"frontmatter\"; result: WordCounterResult }>> {\n if (!data || typeof data !== \"object\" || Array.isArray(data)) {\n return [];\n }\n\n return Promise.all(\n Object.entries(data).map(async ([key, value]) => {\n const valueText = normalizeText(value);\n const text = valueText ? `${key}: ${valueText}` : key;\n return {\n name: key,\n source: \"frontmatter\" as const,\n result: await wordCounterWithDetector(text, options),\n };\n }),\n );\n}\n\nasync function buildSingleItem(\n name: string,\n text: string,\n options: DetectorCountSectionsOptions,\n source: \"frontmatter\" | \"content\",\n): Promise<Array<{ name: string; source: \"frontmatter\" | \"content\"; result: WordCounterResult }>> {\n return [{ name, source, result: await wordCounterWithDetector(text, options) }];\n}\n\nfunction sumTotals(items: Array<{ result: WordCounterResult }>): number {\n return items.reduce((sum, item) => sum + item.result.total, 0);\n}\n\nexport async function countSectionsWithResolvedDetector(\n input: string,\n section: SectionMode,\n options: DetectorCountSectionsOptions = {},\n): Promise<SectionedResult> {\n if (section === \"all\") {\n const result = await wordCounterWithDetector(input, options);\n return {\n section,\n total: result.total,\n frontmatterType: null,\n items: [{ name: \"all\", source: \"content\", result }],\n };\n }\n\n const parsed = parseMarkdown(input);\n const frontmatterText = parsed.frontmatter ?? \"\";\n const contentText = parsed.content ?? \"\";\n\n let items: Array<{ name: string; source: \"frontmatter\" | \"content\"; result: WordCounterResult }> =\n [];\n\n if (section === \"frontmatter\") {\n items = await buildSingleItem(\"frontmatter\", frontmatterText, options, \"frontmatter\");\n } else if (section === \"content\") {\n items = await buildSingleItem(\"content\", contentText, options, \"content\");\n } else if (section === \"split\") {\n items = [\n ...(await buildSingleItem(\"frontmatter\", frontmatterText, options, \"frontmatter\")),\n ...(await buildSingleItem(\"content\", contentText, options, \"content\")),\n ];\n } else if (section === \"per-key\") {\n items = await buildPerKeyItems(parsed.data, options);\n } else if (section === \"split-per-key\") {\n items = [\n ...(await buildPerKeyItems(parsed.data, options)),\n ...(await buildSingleItem(\"content\", contentText, options, \"content\")),\n ];\n }\n\n return {\n section,\n total: sumTotals(items),\n frontmatterType: parsed.frontmatterType,\n items,\n };\n}\n","import { DEFAULT_HAN_TAG, DEFAULT_LOCALE } from \"../wc/locale-detect\";\nimport type { LocaleChunk } from \"../wc/types\";\nimport type { DetectorContentGateMode, DetectorResult } from \"./types\";\n\nexport const LATIN_WASM_MIN_SCRIPT_CHARS = 24;\nexport const HANI_WASM_MIN_SCRIPT_CHARS = 12;\nexport const LATIN_WASM_MIN_CONFIDENCE = 0.75;\nexport const HANI_WASM_MIN_CONFIDENCE = 0.9;\nexport const LATIN_WASM_CORROBORATED_MIN_CONFIDENCE = 0.7;\nconst LATIN_WASM_STRICT_MIN_SCRIPT_CHARS = 30;\nconst LATIN_WASM_LOOSE_MIN_SCRIPT_CHARS = 20;\nconst HANI_WASM_STRICT_MIN_SCRIPT_CHARS = 16;\nconst HANI_WASM_LOOSE_MIN_FOCUS_HAN_CHARS = 4;\n\nconst LATIN_SCRIPT_REGEX = /\\p{Script=Latin}/u;\nconst HAN_SCRIPT_REGEX = /\\p{Script=Han}/u;\nconst HANI_DIAGNOSTIC_SCRIPT_REGEX = /[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}]/u;\nconst LATIN_WORD_REGEX = /\\p{Script=Latin}+/gu;\nconst WHITESPACE_REGEX = /\\s/u;\nconst JAPANESE_CONTEXT_LOCALE = \"ja\";\n\nexport type DetectorRouteTag = typeof DEFAULT_LOCALE | typeof DEFAULT_HAN_TAG;\nexport type DetectorContentGatePolicy = \"latinProse\" | \"none\";\nexport type DetectorDiagnosticTextSource = \"focus\" | \"borrowed-context\";\n\nexport type DetectorWindow = {\n routeTag: DetectorRouteTag;\n startIndex: number;\n endIndex: number;\n text: string;\n};\n\nexport type DetectorBorrowedContext = {\n leftChunkIndex?: number;\n rightChunkIndex?: number;\n};\n\nexport type DetectorDiagnosticSample = {\n focusText: string;\n text: string;\n normalizedText: string;\n normalizedApplied: boolean;\n textSource: DetectorDiagnosticTextSource;\n borrowedContext?: DetectorBorrowedContext;\n};\n\nexport type DetectorEligibilityResult = {\n scriptChars: number;\n minScriptChars: number;\n passed: boolean;\n};\n\nexport type DetectorContentGateResult = {\n applied: boolean;\n passed: boolean;\n policy: DetectorContentGatePolicy;\n mode: DetectorContentGateMode;\n};\n\nexport type DetectorCorroboratedAcceptance =\n | {\n accepted: true;\n confidence: number;\n hasReliableCorroboration: true;\n }\n | {\n accepted: false;\n confidence: number;\n hasReliableCorroboration: boolean;\n reason: \"mismatch\" | \"belowThreshold\" | \"unreliable\";\n };\n\nexport type DetectorRoutePolicy = {\n routeTag: DetectorRouteTag;\n eligibility: {\n evaluate: (\n sample: DetectorDiagnosticSample,\n mode?: DetectorContentGateMode,\n ) => DetectorEligibilityResult;\n };\n buildDiagnosticSample: (\n window: DetectorWindow,\n chunks: LocaleChunk[],\n ) => DetectorDiagnosticSample;\n evaluateContentGate: (\n sample: DetectorDiagnosticSample,\n mode?: DetectorContentGateMode,\n ) => DetectorContentGateResult;\n accept: (candidate: DetectorResult) => boolean;\n acceptCorroborated?: (\n raw: DetectorResult,\n normalized: DetectorResult,\n ) => DetectorCorroboratedAcceptance;\n fallbackTag: string;\n};\n\nfunction countMatchingChars(text: string, matcher: RegExp): number {\n let count = 0;\n for (const char of text) {\n if (matcher.test(char)) {\n count += 1;\n }\n }\n return count;\n}\n\nfunction getSampleScriptMatcher(routeTag: DetectorRouteTag): RegExp {\n return routeTag === DEFAULT_HAN_TAG ? HAN_SCRIPT_REGEX : LATIN_SCRIPT_REGEX;\n}\n\nfunction getEligibilityScriptMatcher(routeTag: DetectorRouteTag): RegExp {\n return routeTag === DEFAULT_HAN_TAG ? HANI_DIAGNOSTIC_SCRIPT_REGEX : LATIN_SCRIPT_REGEX;\n}\n\nfunction normalizeSampleText(text: string, routeTag: DetectorRouteTag): string {\n const matcher = getSampleScriptMatcher(routeTag);\n return [...text]\n .map((char) => {\n if (matcher.test(char) || WHITESPACE_REGEX.test(char)) {\n return char;\n }\n return \" \";\n })\n .join(\"\")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nfunction buildFocusOnlyDiagnosticSample(window: DetectorWindow): DetectorDiagnosticSample {\n const normalizedText = normalizeSampleText(window.text, window.routeTag);\n return {\n focusText: window.text,\n text: window.text,\n normalizedText,\n normalizedApplied: normalizedText !== window.text,\n textSource: \"focus\",\n };\n}\n\nfunction buildHaniDiagnosticSample(\n window: DetectorWindow,\n chunks: LocaleChunk[],\n): DetectorDiagnosticSample {\n const borrowedContext: DetectorBorrowedContext = {};\n const sampleParts: string[] = [];\n\n const leftChunk = chunks[window.startIndex - 1];\n if (leftChunk?.locale === JAPANESE_CONTEXT_LOCALE) {\n borrowedContext.leftChunkIndex = window.startIndex - 1;\n sampleParts.push(leftChunk.text);\n }\n\n sampleParts.push(window.text);\n\n const rightChunk = chunks[window.endIndex + 1];\n if (rightChunk?.locale === JAPANESE_CONTEXT_LOCALE) {\n borrowedContext.rightChunkIndex = window.endIndex + 1;\n sampleParts.push(rightChunk.text);\n }\n\n const text = sampleParts.join(\"\");\n const normalizedText = normalizeSampleText(text, window.routeTag);\n const borrowed =\n borrowedContext.leftChunkIndex !== undefined || borrowedContext.rightChunkIndex !== undefined;\n\n return {\n focusText: window.text,\n text,\n normalizedText,\n normalizedApplied: normalizedText !== text,\n textSource: borrowed ? \"borrowed-context\" : \"focus\",\n ...(borrowed ? { borrowedContext } : {}),\n };\n}\n\nfunction countLatinWords(text: string): number {\n return text.match(LATIN_WORD_REGEX)?.length ?? 0;\n}\n\nfunction isTechnicalLikeLatinLine(line: string, latinWords: number): boolean {\n const trimmed = line.trim();\n if (!trimmed) {\n return false;\n }\n\n if (/^[>#$]/u.test(trimmed)) {\n return true;\n }\n\n if (/(^|\\s)--[a-z0-9][a-z0-9-]*/iu.test(trimmed)) {\n return true;\n }\n\n if (/`[^`]+`/u.test(trimmed)) {\n return true;\n }\n\n if (/(^|[\\s\"'`])(?:\\.{0,2}\\/|\\/)?[\\w./-]+\\.[a-z0-9]{1,6}(?=$|[\\s\"'`])/iu.test(trimmed)) {\n return true;\n }\n\n if (/^[-*\\d.)\\s]*[\\p{L}\\p{N}_.-]+:\\s+\\S/iu.test(trimmed) && latinWords <= 8) {\n return true;\n }\n\n return false;\n}\n\nfunction shouldTreatLatinProseBlockAsSentenceLike(\n latinWords: number,\n lineCount: number,\n hasSentencePunctuation: boolean,\n): boolean {\n if (latinWords < 4) {\n return false;\n }\n\n if (hasSentencePunctuation) {\n return true;\n }\n\n return lineCount <= 1 ? latinWords >= 5 : latinWords >= 8;\n}\n\nfunction evaluateLatinContentGate(\n text: string,\n normalizedSample: string,\n mode: Exclude<DetectorContentGateMode, \"off\">,\n): DetectorContentGateResult {\n const minNormalizedLatinWords = mode === \"strict\" ? 5 : 4;\n const minProseWords = mode === \"strict\" ? 5 : mode === \"loose\" ? 3 : 4;\n const technicalWordSlack = mode === \"loose\" ? 2 : 0;\n const normalizedLatinWords = countLatinWords(normalizedSample);\n if (normalizedLatinWords < minNormalizedLatinWords) {\n return {\n applied: true,\n passed: false,\n policy: \"latinProse\",\n mode,\n };\n }\n\n let proseWords = 0;\n let technicalWords = 0;\n let proseBlockWords = 0;\n let proseBlockLines = 0;\n let proseBlockHasSentencePunctuation = false;\n\n const flushProseBlock = () => {\n if (\n shouldTreatLatinProseBlockAsSentenceLike(\n proseBlockWords,\n proseBlockLines,\n proseBlockHasSentencePunctuation,\n )\n ) {\n proseWords += proseBlockWords;\n }\n\n proseBlockWords = 0;\n proseBlockLines = 0;\n proseBlockHasSentencePunctuation = false;\n };\n\n for (const rawLine of text.split(/\\r?\\n/u)) {\n const line = rawLine.trim();\n if (!line || line === \"---\" || line === \"```\") {\n flushProseBlock();\n continue;\n }\n\n const latinWords = countLatinWords(line);\n if (latinWords === 0) {\n continue;\n }\n\n const technicalLike = isTechnicalLikeLatinLine(line, latinWords);\n if (technicalLike) {\n flushProseBlock();\n technicalWords += latinWords;\n continue;\n }\n\n proseBlockWords += latinWords;\n proseBlockLines += 1;\n proseBlockHasSentencePunctuation ||= /[.!?]/u.test(line);\n }\n\n flushProseBlock();\n return {\n applied: true,\n passed: proseWords >= minProseWords && proseWords + technicalWordSlack >= technicalWords,\n policy: \"latinProse\",\n mode,\n };\n}\n\nfunction evaluateEligibility(\n sample: DetectorDiagnosticSample,\n routeTag: DetectorRouteTag,\n minScriptChars: number,\n): DetectorEligibilityResult {\n const scriptChars = countMatchingChars(sample.text, getEligibilityScriptMatcher(routeTag));\n return {\n scriptChars,\n minScriptChars,\n passed: scriptChars >= minScriptChars,\n };\n}\n\nfunction getLatinEligibilityMinScriptChars(mode: DetectorContentGateMode = \"default\"): number {\n if (mode === \"strict\") {\n return LATIN_WASM_STRICT_MIN_SCRIPT_CHARS;\n }\n\n if (mode === \"loose\") {\n return LATIN_WASM_LOOSE_MIN_SCRIPT_CHARS;\n }\n\n return LATIN_WASM_MIN_SCRIPT_CHARS;\n}\n\nfunction evaluateHaniEligibility(\n sample: DetectorDiagnosticSample,\n mode: DetectorContentGateMode = \"default\",\n): DetectorEligibilityResult {\n if (mode === \"loose\") {\n const scriptChars = countMatchingChars(sample.focusText, HAN_SCRIPT_REGEX);\n return {\n scriptChars,\n minScriptChars: HANI_WASM_LOOSE_MIN_FOCUS_HAN_CHARS,\n passed: scriptChars >= HANI_WASM_LOOSE_MIN_FOCUS_HAN_CHARS,\n };\n }\n\n const minScriptChars =\n mode === \"strict\" ? HANI_WASM_STRICT_MIN_SCRIPT_CHARS : HANI_WASM_MIN_SCRIPT_CHARS;\n return evaluateEligibility(sample, DEFAULT_HAN_TAG, minScriptChars);\n}\n\nfunction shouldAcceptCandidate(\n confidence: number | undefined,\n reliable: boolean | undefined,\n minConfidence: number,\n): boolean {\n if (reliable !== true) {\n return false;\n }\n\n if (confidence === undefined) {\n return false;\n }\n\n return confidence >= minConfidence;\n}\n\nfunction evaluateLatinCorroboratedAcceptance(\n raw: DetectorResult,\n normalized: DetectorResult,\n): DetectorCorroboratedAcceptance {\n if (raw.tag !== normalized.tag) {\n return {\n accepted: false,\n confidence: Math.max(raw.confidence ?? 0, normalized.confidence ?? 0),\n hasReliableCorroboration: raw.reliable === true || normalized.reliable === true,\n reason: \"mismatch\",\n };\n }\n\n const confidence = Math.max(raw.confidence ?? 0, normalized.confidence ?? 0);\n const hasReliableCorroboration = raw.reliable === true || normalized.reliable === true;\n\n if (!hasReliableCorroboration && confidence >= LATIN_WASM_CORROBORATED_MIN_CONFIDENCE) {\n return {\n accepted: false,\n confidence,\n hasReliableCorroboration,\n reason: \"unreliable\",\n };\n }\n\n if (confidence < LATIN_WASM_CORROBORATED_MIN_CONFIDENCE) {\n return {\n accepted: false,\n confidence,\n hasReliableCorroboration,\n reason: \"belowThreshold\",\n };\n }\n\n if (!hasReliableCorroboration) {\n return {\n accepted: false,\n confidence,\n hasReliableCorroboration,\n reason: \"unreliable\",\n };\n }\n\n return {\n accepted: true,\n confidence,\n hasReliableCorroboration: true,\n };\n}\n\nfunction createLatinRoutePolicy(): DetectorRoutePolicy {\n return {\n routeTag: DEFAULT_LOCALE,\n eligibility: {\n evaluate(sample, mode = \"default\") {\n return evaluateEligibility(sample, DEFAULT_LOCALE, getLatinEligibilityMinScriptChars(mode));\n },\n },\n buildDiagnosticSample(window) {\n return buildFocusOnlyDiagnosticSample(window);\n },\n evaluateContentGate(sample, mode = \"default\") {\n if (mode === \"off\") {\n return {\n applied: false,\n passed: true,\n policy: \"none\",\n mode,\n };\n }\n\n return evaluateLatinContentGate(sample.text, sample.normalizedText, mode);\n },\n accept(candidate) {\n return shouldAcceptCandidate(\n candidate.confidence,\n candidate.reliable,\n LATIN_WASM_MIN_CONFIDENCE,\n );\n },\n acceptCorroborated(raw, normalized) {\n return evaluateLatinCorroboratedAcceptance(raw, normalized);\n },\n fallbackTag: DEFAULT_LOCALE,\n };\n}\n\nfunction createHaniRoutePolicy(): DetectorRoutePolicy {\n return {\n routeTag: DEFAULT_HAN_TAG,\n eligibility: {\n evaluate(sample, mode = \"default\") {\n return evaluateHaniEligibility(sample, mode);\n },\n },\n buildDiagnosticSample(window, chunks) {\n return buildHaniDiagnosticSample(window, chunks);\n },\n evaluateContentGate(_sample, mode = \"default\") {\n return {\n applied: false,\n passed: true,\n policy: \"none\",\n mode,\n };\n },\n accept(candidate) {\n return shouldAcceptCandidate(\n candidate.confidence,\n candidate.reliable,\n HANI_WASM_MIN_CONFIDENCE,\n );\n },\n fallbackTag: DEFAULT_HAN_TAG,\n };\n}\n\nexport const DETECTOR_ROUTE_POLICIES: Record<DetectorRouteTag, DetectorRoutePolicy> = {\n [DEFAULT_LOCALE]: createLatinRoutePolicy(),\n [DEFAULT_HAN_TAG]: createHaniRoutePolicy(),\n};\n\nexport function isAmbiguousDetectorRoute(locale: string): locale is DetectorRouteTag {\n return locale === DEFAULT_LOCALE || locale === DEFAULT_HAN_TAG;\n}\n\nexport function countScriptBearingCharsForRoute(text: string, routeTag: DetectorRouteTag): number {\n return countMatchingChars(text, getEligibilityScriptMatcher(routeTag));\n}\n\nexport function normalizeDetectorSampleForRoute(text: string, routeTag: DetectorRouteTag): string {\n return normalizeSampleText(text, routeTag);\n}\n","import { DETECTOR_ROUTE_POLICIES, type DetectorWindow } from \"./policy\";\nimport {\n createInspectChunk,\n createInspectPreview,\n type TracedLocaleChunk,\n} from \"./inspect-helpers\";\nimport type { DetectorInspectResult, DetectorInspectWindow } from \"./inspect-types\";\nimport type { ResolvedDetectorWindow } from \"./wasm-resolution\";\nimport type { ExecutedEngineSample } from \"./wasm-engine\";\n\nfunction buildInspectSample(\n sample:\n | ResolvedDetectorWindow[\"sample\"]\n | {\n text: string;\n normalizedText: string;\n normalizedApplied: boolean;\n textSource: \"focus\" | \"borrowed-context\";\n borrowedContext?: ResolvedDetectorWindow[\"sample\"][\"borrowedContext\"];\n },\n) {\n return {\n text: sample.text,\n textLength: sample.text.length,\n normalizedText: sample.normalizedText,\n normalizedApplied: sample.normalizedApplied,\n textSource: sample.textSource,\n ...(sample.borrowedContext ? { borrowedContext: sample.borrowedContext } : {}),\n };\n}\n\nexport function buildEmptyEngineInspectResult(\n input: DetectorInspectResult[\"input\"],\n): DetectorInspectResult {\n return {\n schemaVersion: 1,\n kind: \"detector-inspect\",\n view: \"engine\",\n detector: \"wasm\",\n input,\n sample: {\n text: \"\",\n textLength: 0,\n normalizedText: \"\",\n normalizedApplied: false,\n textSource: \"focus\",\n },\n decision: {\n kind: \"empty\",\n notes: [\"No detector-eligible content was present.\"],\n },\n };\n}\n\nexport async function buildEngineInspectResult(\n input: DetectorInspectResult[\"input\"],\n window: DetectorWindow,\n chunks: Array<{ locale: string; text: string }>,\n executeEngine: (\n sample: ReturnType<\n (typeof DETECTOR_ROUTE_POLICIES)[typeof window.routeTag][\"buildDiagnosticSample\"]\n >,\n routeTag: typeof window.routeTag,\n ) => Promise<ExecutedEngineSample>,\n): Promise<DetectorInspectResult> {\n const sample = DETECTOR_ROUTE_POLICIES[window.routeTag].buildDiagnosticSample(window, chunks);\n const { rawResult, rawRemapped, normalizedResult, normalizedRemapped } = await executeEngine(\n sample,\n window.routeTag,\n );\n\n if (!rawResult) {\n return {\n schemaVersion: 1,\n kind: \"detector-inspect\",\n view: \"engine\",\n detector: \"wasm\",\n input,\n routeTag: window.routeTag,\n sample: buildInspectSample(sample),\n };\n }\n\n return {\n schemaVersion: 1,\n kind: \"detector-inspect\",\n view: \"engine\",\n detector: \"wasm\",\n input,\n routeTag: window.routeTag,\n sample: buildInspectSample(sample),\n engine: {\n name: \"whatlang-wasm\",\n raw: rawResult,\n ...(normalizedResult ? { normalized: normalizedResult } : {}),\n remapped: {\n rawTag: rawRemapped?.tag ?? null,\n normalizedTag: normalizedRemapped?.tag ?? null,\n },\n },\n };\n}\n\nexport function buildEmptyPipelineInspectResult(\n input: DetectorInspectResult[\"input\"],\n): DetectorInspectResult {\n return {\n schemaVersion: 1,\n kind: \"detector-inspect\",\n view: \"pipeline\",\n detector: \"wasm\",\n input,\n chunks: [],\n windows: [],\n decision: {\n kind: \"empty\",\n notes: [\"No detector-eligible content was present.\"],\n },\n resolvedChunks: [],\n };\n}\n\nexport function buildPipelineInspectResult(\n input: DetectorInspectResult[\"input\"],\n tracedChunks: TracedLocaleChunk[],\n resolvedWindows: Array<ResolvedDetectorWindow & { window: DetectorWindow; windowIndex: number }>,\n finalResolved: Array<{ locale: string; text: string }>,\n): DetectorInspectResult {\n return {\n schemaVersion: 1,\n kind: \"detector-inspect\",\n view: \"pipeline\",\n detector: \"wasm\",\n input,\n chunks: tracedChunks.map((chunk, index) =>\n createInspectChunk(index, chunk, {\n source: chunk.source,\n }),\n ),\n windows: resolvedWindows.map(\n ({\n window,\n windowIndex,\n sample,\n eligibility,\n contentGate,\n engineExecuted,\n engineReason,\n decision,\n }) => {\n const focusPreview = createInspectPreview(sample.focusText);\n const samplePreview = createInspectPreview(sample.text);\n const normalizedPreview = createInspectPreview(sample.normalizedText);\n const inspectWindow: DetectorInspectWindow = {\n windowIndex,\n routeTag: window.routeTag,\n chunkRange: {\n start: window.startIndex,\n end: window.endIndex,\n },\n focusTextPreview: focusPreview.textPreview,\n focusTextPreviewTruncated: focusPreview.textPreviewTruncated,\n diagnosticSample: {\n textPreview: samplePreview.textPreview,\n textPreviewTruncated: samplePreview.textPreviewTruncated,\n normalizedTextPreview: normalizedPreview.textPreview,\n normalizedTextPreviewTruncated: normalizedPreview.textPreviewTruncated,\n normalizedApplied: sample.normalizedApplied,\n ...(sample.borrowedContext ? { borrowedContext: sample.borrowedContext } : {}),\n },\n eligibility,\n contentGate,\n engine: {\n executed: engineExecuted,\n ...(engineReason ? { reason: engineReason } : {}),\n },\n decision,\n };\n return inspectWindow;\n },\n ),\n resolvedChunks: finalResolved.map((chunk, index) => createInspectChunk(index, chunk)),\n };\n}\n","import { DEFAULT_HAN_TAG, DEFAULT_LOCALE } from \"../wc/locale-detect\";\nimport type { DetectorRouteTag } from \"./policy\";\nimport type { DetectorResult } from \"./types\";\n\nexport interface WhatlangWasmResult {\n lang: string;\n script: string;\n confidence: number;\n reliable: boolean;\n}\n\nconst LATIN_LANGUAGE_TAGS: Record<string, string> = {\n cat: \"ca\",\n ces: \"cs\",\n dan: \"da\",\n deu: \"de\",\n eng: \"en\",\n fin: \"fi\",\n fra: \"fr\",\n hun: \"hu\",\n ita: \"it\",\n lat: \"la\",\n nld: \"nl\",\n pol: \"pl\",\n por: \"pt\",\n ron: \"ro\",\n spa: \"es\",\n swe: \"sv\",\n tur: \"tr\",\n};\n\nconst HANI_LANGUAGE_TAGS: Record<string, string> = {\n cmn: \"zh\",\n jpn: \"ja\",\n};\n\nfunction hasSupportedScript(result: WhatlangWasmResult, routeTag: DetectorRouteTag): boolean {\n if (routeTag === DEFAULT_LOCALE) {\n return result.script === \"Latin\";\n }\n\n if (result.lang === \"cmn\") {\n return result.script === \"Mandarin\";\n }\n\n if (result.lang === \"jpn\") {\n return (\n result.script === \"Mandarin\" || result.script === \"Hiragana\" || result.script === \"Katakana\"\n );\n }\n\n return false;\n}\n\nfunction remapLanguageTag(lang: string, routeTag: DetectorRouteTag): string | undefined {\n if (routeTag === DEFAULT_LOCALE) {\n return LATIN_LANGUAGE_TAGS[lang];\n }\n\n return HANI_LANGUAGE_TAGS[lang];\n}\n\nexport function remapWhatlangResult(\n result: WhatlangWasmResult,\n routeTag: DetectorRouteTag,\n): DetectorResult | null {\n if (!hasSupportedScript(result, routeTag)) {\n return null;\n }\n\n const tag = remapLanguageTag(result.lang, routeTag);\n if (!tag) {\n return null;\n }\n\n return {\n tag,\n confidence: result.confidence,\n reliable: result.reliable,\n source: \"wasm\",\n };\n}\n\nexport function getDetectorFallbackTag(routeTag: DetectorRouteTag): string {\n return routeTag === DEFAULT_HAN_TAG ? DEFAULT_HAN_TAG : DEFAULT_LOCALE;\n}\n","import { segmentTextByLocale } from \"../wc\";\nimport { DEFAULT_LOCALE } from \"../wc/locale-detect\";\nimport type { LocaleChunk } from \"../wc/types\";\nimport { getDetectorFallbackTag } from \"./whatlang-map\";\nimport type { DetectorLocaleOptions } from \"./types\";\nimport type { DetectorWindow } from \"./policy\";\n\nexport function createDeferredLatinPreSegmentOptions(\n options: DetectorLocaleOptions,\n): DetectorLocaleOptions {\n return {\n ...options,\n latinLanguageHint: undefined,\n latinTagHint: undefined,\n latinLocaleHint: undefined,\n latinHintRules: undefined,\n useDefaultLatinHints: false,\n };\n}\n\nfunction createRuleOnlyLatinOptions(options: DetectorLocaleOptions): DetectorLocaleOptions {\n return {\n ...options,\n latinLanguageHint: undefined,\n latinTagHint: undefined,\n latinLocaleHint: undefined,\n };\n}\n\nfunction mergeAdjacentChunks(chunks: LocaleChunk[]): LocaleChunk[] {\n if (chunks.length === 0) {\n return chunks;\n }\n\n const merged: LocaleChunk[] = [];\n let last = chunks[0]!;\n\n for (let index = 1; index < chunks.length; index += 1) {\n const chunk = chunks[index]!;\n if (chunk.locale === last.locale) {\n last = {\n locale: last.locale,\n text: last.text + chunk.text,\n };\n continue;\n }\n merged.push(last);\n last = chunk;\n }\n\n merged.push(last);\n return merged;\n}\n\nexport function reapplyDeferredLatinFallback(\n chunks: LocaleChunk[],\n options: DetectorLocaleOptions,\n): LocaleChunk[] {\n const relabeled: LocaleChunk[] = [];\n\n for (const chunk of chunks) {\n if (chunk.locale !== DEFAULT_LOCALE) {\n relabeled.push(chunk);\n continue;\n }\n\n relabeled.push(...segmentTextByLocale(chunk.text, options));\n }\n\n return mergeAdjacentChunks(relabeled);\n}\n\nexport function reapplyResolvedLatinHintRules(\n resolvedChunks: LocaleChunk[],\n originalChunks: LocaleChunk[],\n options: DetectorLocaleOptions,\n): LocaleChunk[] {\n const relabeled: LocaleChunk[] = [];\n const ruleOnlyOptions = createRuleOnlyLatinOptions(options);\n\n for (let index = 0; index < resolvedChunks.length; index += 1) {\n const chunk = resolvedChunks[index];\n const originalChunk = originalChunks[index];\n if (!chunk || !originalChunk) {\n continue;\n }\n\n if (originalChunk.locale !== DEFAULT_LOCALE || chunk.locale === DEFAULT_LOCALE) {\n relabeled.push(chunk);\n continue;\n }\n\n const hintedChunks = segmentTextByLocale(chunk.text, ruleOnlyOptions).map((hintedChunk) => ({\n locale: hintedChunk.locale === DEFAULT_LOCALE ? chunk.locale : hintedChunk.locale,\n text: hintedChunk.text,\n }));\n relabeled.push(...hintedChunks);\n }\n\n return mergeAdjacentChunks(relabeled);\n}\n\nexport function resolveFallbackDebugOutcome(\n window: DetectorWindow,\n options: DetectorLocaleOptions,\n): {\n finalTag: string;\n finalLocales?: string[];\n} {\n const fallbackTag = getDetectorFallbackTag(window.routeTag);\n if (window.routeTag !== DEFAULT_LOCALE) {\n return { finalTag: fallbackTag };\n }\n\n const relabeled = reapplyDeferredLatinFallback(\n [\n {\n locale: fallbackTag,\n text: window.text,\n },\n ],\n options,\n );\n const finalLocales = relabeled.map((chunk) => chunk.locale);\n if (finalLocales.length === 1) {\n return {\n finalTag: finalLocales[0]!,\n };\n }\n\n return finalLocales.length > 1\n ? {\n finalTag: fallbackTag,\n finalLocales,\n }\n : {\n finalTag: fallbackTag,\n };\n}\n","import { existsSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { createRequire } from \"node:module\";\nimport { fileURLToPath } from \"node:url\";\nimport type { DetectorRouteTag } from \"./policy\";\nimport type { WhatlangWasmResult } from \"./whatlang-map\";\n\nconst GENERATED_FOLDER_NAME = \"wasm-language-detector\";\nconst GENERATED_MODULE_FILE = \"language_detector.js\";\nconst MAX_SEARCH_DEPTH = 8;\nconst requireFromHere = createRequire(import.meta.url);\n\nexport const WASM_DETECTOR_RUNTIME_UNAVAILABLE_MESSAGE =\n \"WASM detector runtime is unavailable. Run `bun run build:wasm` to generate it.\";\n\ntype WhatlangWasmModule = {\n detect_language: (text: string, routeTag: string) => WhatlangWasmResult | null;\n};\n\nlet modulePromise: Promise<WhatlangWasmModule> | null = null;\n\nfunction resolveCandidateModulePaths(): string[] {\n const moduleDir = dirname(fileURLToPath(import.meta.url));\n const candidates = new Set<string>();\n let currentDir = moduleDir;\n\n for (let depth = 0; depth < MAX_SEARCH_DEPTH; depth += 1) {\n candidates.add(join(currentDir, GENERATED_FOLDER_NAME, GENERATED_MODULE_FILE));\n candidates.add(join(currentDir, \"generated\", GENERATED_FOLDER_NAME, GENERATED_MODULE_FILE));\n\n const parentDir = dirname(currentDir);\n if (parentDir === currentDir) {\n break;\n }\n currentDir = parentDir;\n }\n\n return [...candidates];\n}\n\nfunction resolveWhatlangWasmModulePath(): string {\n for (const candidate of resolveCandidateModulePaths()) {\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n\n throw new Error(WASM_DETECTOR_RUNTIME_UNAVAILABLE_MESSAGE);\n}\n\nasync function loadWhatlangWasmModule(): Promise<WhatlangWasmModule> {\n if (!modulePromise) {\n modulePromise = (async () => {\n const modulePath = resolveWhatlangWasmModulePath();\n return requireFromHere(modulePath) as WhatlangWasmModule;\n })();\n }\n\n return modulePromise;\n}\n\nexport async function detectWithWhatlangWasm(\n text: string,\n routeTag: DetectorRouteTag,\n): Promise<WhatlangWasmResult | null> {\n const wasmModule = await loadWhatlangWasmModule();\n return wasmModule.detect_language(text, routeTag);\n}\n","import type { DetectorDiagnosticSample, DetectorRouteTag } from \"./policy\";\nimport { remapWhatlangResult } from \"./whatlang-map\";\nimport { detectWithWhatlangWasm } from \"./whatlang-wasm\";\nimport type { DetectorResult } from \"./types\";\n\nexport type ExecutedEngineSample = {\n rawResult: Awaited<ReturnType<typeof detectWithWhatlangWasm>> | null;\n rawRemapped: DetectorResult | null;\n normalizedResult: Awaited<ReturnType<typeof detectWithWhatlangWasm>> | null;\n normalizedRemapped: DetectorResult | null;\n};\n\nexport function buildEvidenceSample(\n result: Awaited<ReturnType<typeof detectWithWhatlangWasm>> | null,\n remappedTag: string | null,\n) {\n return {\n lang: result?.lang ?? null,\n script: result?.script ?? null,\n confidence: result?.confidence ?? null,\n reliable: result?.reliable ?? null,\n remappedTag,\n };\n}\n\nexport async function executeEngineSample(\n sample: DetectorDiagnosticSample,\n routeTag: DetectorRouteTag,\n): Promise<ExecutedEngineSample> {\n const rawResult = await detectWithWhatlangWasm(sample.text, routeTag);\n const rawRemapped = rawResult ? remapWhatlangResult(rawResult, routeTag) : null;\n const normalizedResult =\n sample.normalizedApplied && sample.normalizedText.length > 0\n ? await detectWithWhatlangWasm(sample.normalizedText, routeTag)\n : null;\n const normalizedRemapped = normalizedResult\n ? remapWhatlangResult(normalizedResult, routeTag)\n : null;\n\n return {\n rawResult,\n rawRemapped,\n normalizedResult,\n normalizedRemapped,\n };\n}\n","import {\n createDetectorEvidencePreview,\n recordDetectorAccepted,\n recordDetectorFallback,\n recordDetectorWindow,\n type DetectorFallbackReason,\n} from \"./debug\";\nimport {\n DETECTOR_ROUTE_POLICIES,\n type DetectorContentGateResult,\n type DetectorDiagnosticSample,\n type DetectorEligibilityResult,\n type DetectorWindow,\n} from \"./policy\";\nimport type { LocaleChunk } from \"../wc/types\";\nimport { getDetectorFallbackTag } from \"./whatlang-map\";\nimport type { DetectorLocaleOptions } from \"./types\";\nimport { buildEvidenceSample, executeEngineSample } from \"./wasm-engine\";\nimport { resolveFallbackDebugOutcome } from \"./wasm-presegment\";\n\nexport type ResolvedDetectorWindow = {\n resolvedLocale: string;\n sample: DetectorDiagnosticSample;\n eligibility: DetectorEligibilityResult;\n contentGate: DetectorContentGateResult;\n engineExecuted: boolean;\n engineReason?: \"notEligible\";\n rawResult: Awaited<ReturnType<typeof executeEngineSample>>[\"rawResult\"];\n rawRemappedTag: string | null;\n normalizedResult: Awaited<ReturnType<typeof executeEngineSample>>[\"normalizedResult\"];\n normalizedRemappedTag: string | null;\n decision: {\n accepted: boolean;\n path: \"reliable\" | \"corroborated\" | null;\n finalTag: string;\n finalLocales?: string[];\n fallbackReason: DetectorFallbackReason | null;\n };\n};\n\nfunction emitDetectorWindowEvidence({\n window,\n windowIndex,\n sample,\n eligibility,\n contentGate,\n rawResult,\n rawRemappedTag,\n normalizedResult,\n normalizedRemappedTag,\n decision,\n debug,\n}: {\n window: DetectorWindow;\n windowIndex: number;\n sample: DetectorDiagnosticSample;\n eligibility: DetectorEligibilityResult;\n contentGate: DetectorContentGateResult;\n rawResult: ResolvedDetectorWindow[\"rawResult\"];\n rawRemappedTag: string | null;\n normalizedResult: ResolvedDetectorWindow[\"normalizedResult\"];\n normalizedRemappedTag: string | null;\n decision: ResolvedDetectorWindow[\"decision\"];\n debug?: DetectorLocaleOptions[\"detectorDebug\"];\n}): void {\n const evidence = debug?.evidence;\n if (!evidence || !debug.emit) {\n return;\n }\n\n const baseDetails = {\n engine: \"whatlang-wasm\",\n routeTag: window.routeTag,\n windowIndex,\n startIndex: window.startIndex,\n endIndex: window.endIndex,\n mode: evidence.mode,\n section: evidence.section,\n textLength: sample.text.length,\n focusTextLength: sample.focusText.length,\n normalizedLength: sample.normalizedText.length,\n normalizedApplied: sample.normalizedApplied,\n textSource: sample.textSource,\n scriptChars: eligibility.scriptChars,\n minScriptChars: eligibility.minScriptChars,\n eligible: eligibility.passed,\n contentGate,\n qualityGate: contentGate.passed,\n raw: buildEvidenceSample(rawResult, rawRemappedTag),\n normalized: buildEvidenceSample(normalizedResult, normalizedRemappedTag),\n decision,\n ...(sample.borrowedContext ? { borrowedContext: sample.borrowedContext } : {}),\n };\n\n if (evidence.verbosity === \"verbose\") {\n debug.emit(\n \"detector.window.evidence\",\n {\n ...baseDetails,\n text: sample.text,\n normalizedText: sample.normalizedText,\n },\n { verbosity: \"verbose\" },\n );\n return;\n }\n\n const textPreview = createDetectorEvidencePreview(sample.text);\n const normalizedPreview = createDetectorEvidencePreview(sample.normalizedText);\n debug.emit(\n \"detector.window.evidence\",\n {\n ...baseDetails,\n textPreview: textPreview.preview,\n textPreviewTruncated: textPreview.truncated,\n normalizedPreview: normalizedPreview.preview,\n normalizedPreviewTruncated: normalizedPreview.truncated,\n },\n { verbosity: \"compact\" },\n );\n}\n\nexport async function resolveWindowLocale(\n window: DetectorWindow,\n windowIndex: number,\n chunks: LocaleChunk[],\n options: DetectorLocaleOptions,\n debug?: DetectorLocaleOptions[\"detectorDebug\"],\n): Promise<ResolvedDetectorWindow> {\n const routePolicy = DETECTOR_ROUTE_POLICIES[window.routeTag];\n const sample = routePolicy.buildDiagnosticSample(window, chunks);\n const configuredMode = options.contentGate?.mode;\n const eligibility = routePolicy.eligibility.evaluate(sample, configuredMode);\n const contentGate = routePolicy.evaluateContentGate(sample, configuredMode);\n\n recordDetectorWindow(debug?.summary, window.routeTag);\n debug?.emit?.(\n \"detector.window.start\",\n {\n routeTag: window.routeTag,\n startIndex: window.startIndex,\n endIndex: window.endIndex,\n textLength: window.text.length,\n sampleTextLength: sample.text.length,\n textSource: sample.textSource,\n ...(sample.borrowedContext ? { borrowedContext: sample.borrowedContext } : {}),\n },\n { verbosity: \"verbose\" },\n );\n\n if (!eligibility.passed) {\n recordDetectorFallback(debug?.summary, \"notEligible\");\n const fallbackDebugOutcome = resolveFallbackDebugOutcome(window, options);\n const resolution: ResolvedDetectorWindow = {\n resolvedLocale: getDetectorFallbackTag(window.routeTag),\n sample,\n eligibility,\n contentGate,\n engineExecuted: false,\n engineReason: \"notEligible\",\n rawResult: null,\n rawRemappedTag: null,\n normalizedResult: null,\n normalizedRemappedTag: null,\n decision: {\n accepted: false,\n path: null,\n finalTag: fallbackDebugOutcome.finalTag,\n ...(fallbackDebugOutcome.finalLocales\n ? { finalLocales: fallbackDebugOutcome.finalLocales }\n : {}),\n fallbackReason: \"notEligible\",\n },\n };\n emitDetectorWindowEvidence({\n window,\n windowIndex,\n sample: resolution.sample,\n eligibility: resolution.eligibility,\n contentGate: resolution.contentGate,\n rawResult: resolution.rawResult,\n rawRemappedTag: resolution.rawRemappedTag,\n normalizedResult: resolution.normalizedResult,\n normalizedRemappedTag: resolution.normalizedRemappedTag,\n decision: resolution.decision,\n debug,\n });\n debug?.emit?.(\"detector.window.fallback\", {\n routeTag: window.routeTag,\n finalTag: fallbackDebugOutcome.finalTag,\n ...(fallbackDebugOutcome.finalLocales\n ? { finalLocales: fallbackDebugOutcome.finalLocales }\n : {}),\n reason: \"notEligible\",\n });\n return resolution;\n }\n\n const { rawResult, rawRemapped, normalizedResult, normalizedRemapped } =\n await executeEngineSample(sample, window.routeTag);\n debug?.emit?.(\n \"detector.window.sample\",\n {\n routeTag: window.routeTag,\n normalizedApplied: sample.normalizedApplied,\n normalizedLength: sample.normalizedText.length,\n textSource: sample.textSource,\n contentGate,\n qualityGate: contentGate.passed,\n rawTag: rawRemapped?.tag ?? null,\n rawConfidence: rawRemapped?.confidence ?? null,\n rawReliable: rawRemapped?.reliable ?? null,\n ...(sample.borrowedContext ? { borrowedContext: sample.borrowedContext } : {}),\n },\n { verbosity: \"verbose\" },\n );\n debug?.emit?.(\n \"detector.window.candidates\",\n {\n routeTag: window.routeTag,\n normalizedTag: normalizedRemapped?.tag ?? null,\n normalizedConfidence: normalizedRemapped?.confidence ?? null,\n normalizedReliable: normalizedRemapped?.reliable ?? null,\n },\n { verbosity: \"verbose\" },\n );\n\n const candidates = [rawRemapped, normalizedRemapped].filter((value) => value !== null);\n if (candidates.length === 0) {\n recordDetectorFallback(debug?.summary, \"noCandidate\");\n const fallbackDebugOutcome = resolveFallbackDebugOutcome(window, options);\n const resolution: ResolvedDetectorWindow = {\n resolvedLocale: getDetectorFallbackTag(window.routeTag),\n sample,\n eligibility,\n contentGate,\n engineExecuted: true,\n rawResult,\n rawRemappedTag: rawRemapped?.tag ?? null,\n normalizedResult,\n normalizedRemappedTag: normalizedRemapped?.tag ?? null,\n decision: {\n accepted: false,\n path: null,\n finalTag: fallbackDebugOutcome.finalTag,\n ...(fallbackDebugOutcome.finalLocales\n ? { finalLocales: fallbackDebugOutcome.finalLocales }\n : {}),\n fallbackReason: \"noCandidate\",\n },\n };\n emitDetectorWindowEvidence({\n window,\n windowIndex,\n sample: resolution.sample,\n eligibility: resolution.eligibility,\n contentGate: resolution.contentGate,\n rawResult: resolution.rawResult,\n rawRemappedTag: resolution.rawRemappedTag,\n normalizedResult: resolution.normalizedResult,\n normalizedRemappedTag: resolution.normalizedRemappedTag,\n decision: resolution.decision,\n debug,\n });\n debug?.emit?.(\"detector.window.fallback\", {\n routeTag: window.routeTag,\n finalTag: fallbackDebugOutcome.finalTag,\n ...(fallbackDebugOutcome.finalLocales\n ? { finalLocales: fallbackDebugOutcome.finalLocales }\n : {}),\n reason: \"noCandidate\",\n });\n return resolution;\n }\n\n const strongestCandidate = candidates.reduce((best, current) => {\n if (!best) {\n return current;\n }\n return (current.confidence ?? 0) > (best.confidence ?? 0) ? current : best;\n }, candidates[0]);\n\n if (strongestCandidate && contentGate.passed && routePolicy.accept(strongestCandidate)) {\n recordDetectorAccepted(debug?.summary, \"reliable\");\n const resolution: ResolvedDetectorWindow = {\n resolvedLocale: strongestCandidate.tag,\n sample,\n eligibility,\n contentGate,\n engineExecuted: true,\n rawResult,\n rawRemappedTag: rawRemapped?.tag ?? null,\n normalizedResult,\n normalizedRemappedTag: normalizedRemapped?.tag ?? null,\n decision: {\n accepted: true,\n path: \"reliable\",\n finalTag: strongestCandidate.tag,\n fallbackReason: null,\n },\n };\n emitDetectorWindowEvidence({\n window,\n windowIndex,\n sample: resolution.sample,\n eligibility: resolution.eligibility,\n contentGate: resolution.contentGate,\n rawResult: resolution.rawResult,\n rawRemappedTag: resolution.rawRemappedTag,\n normalizedResult: resolution.normalizedResult,\n normalizedRemappedTag: resolution.normalizedRemappedTag,\n decision: resolution.decision,\n debug,\n });\n debug?.emit?.(\"detector.window.accepted\", {\n routeTag: window.routeTag,\n finalTag: strongestCandidate.tag,\n acceptancePath: \"reliable\",\n confidence: strongestCandidate.confidence ?? null,\n reliable: strongestCandidate.reliable ?? null,\n });\n return resolution;\n }\n\n if (contentGate.passed && routePolicy.acceptCorroborated && rawRemapped && normalizedRemapped) {\n const corroborated = routePolicy.acceptCorroborated(rawRemapped, normalizedRemapped);\n if (corroborated.accepted) {\n recordDetectorAccepted(debug?.summary, \"corroborated\");\n const resolution: ResolvedDetectorWindow = {\n resolvedLocale: rawRemapped.tag,\n sample,\n eligibility,\n contentGate,\n engineExecuted: true,\n rawResult,\n rawRemappedTag: rawRemapped.tag,\n normalizedResult,\n normalizedRemappedTag: normalizedRemapped.tag,\n decision: {\n accepted: true,\n path: \"corroborated\",\n finalTag: rawRemapped.tag,\n fallbackReason: null,\n },\n };\n emitDetectorWindowEvidence({\n window,\n windowIndex,\n sample: resolution.sample,\n eligibility: resolution.eligibility,\n contentGate: resolution.contentGate,\n rawResult: resolution.rawResult,\n rawRemappedTag: resolution.rawRemappedTag,\n normalizedResult: resolution.normalizedResult,\n normalizedRemappedTag: resolution.normalizedRemappedTag,\n decision: resolution.decision,\n debug,\n });\n debug?.emit?.(\"detector.window.accepted\", {\n routeTag: window.routeTag,\n finalTag: rawRemapped.tag,\n acceptancePath: \"corroborated\",\n confidence: corroborated.confidence,\n reliable: corroborated.hasReliableCorroboration,\n });\n return resolution;\n }\n\n if (corroborated.reason === \"unreliable\") {\n recordDetectorFallback(debug?.summary, \"corroborationUnreliable\");\n const fallbackDebugOutcome = resolveFallbackDebugOutcome(window, options);\n const resolution: ResolvedDetectorWindow = {\n resolvedLocale: getDetectorFallbackTag(window.routeTag),\n sample,\n eligibility,\n contentGate,\n engineExecuted: true,\n rawResult,\n rawRemappedTag: rawRemapped.tag,\n normalizedResult,\n normalizedRemappedTag: normalizedRemapped.tag,\n decision: {\n accepted: false,\n path: null,\n finalTag: fallbackDebugOutcome.finalTag,\n ...(fallbackDebugOutcome.finalLocales\n ? { finalLocales: fallbackDebugOutcome.finalLocales }\n : {}),\n fallbackReason: \"corroborationUnreliable\",\n },\n };\n emitDetectorWindowEvidence({\n window,\n windowIndex,\n sample: resolution.sample,\n eligibility: resolution.eligibility,\n contentGate: resolution.contentGate,\n rawResult: resolution.rawResult,\n rawRemappedTag: resolution.rawRemappedTag,\n normalizedResult: resolution.normalizedResult,\n normalizedRemappedTag: resolution.normalizedRemappedTag,\n decision: resolution.decision,\n debug,\n });\n debug?.emit?.(\"detector.window.fallback\", {\n routeTag: window.routeTag,\n finalTag: fallbackDebugOutcome.finalTag,\n ...(fallbackDebugOutcome.finalLocales\n ? { finalLocales: fallbackDebugOutcome.finalLocales }\n : {}),\n reason: \"corroborationUnreliable\",\n });\n return resolution;\n }\n }\n\n const fallbackReason = contentGate.passed ? \"belowThreshold\" : \"qualityGate\";\n recordDetectorFallback(debug?.summary, fallbackReason);\n const fallbackDebugOutcome = resolveFallbackDebugOutcome(window, options);\n const resolution: ResolvedDetectorWindow = {\n resolvedLocale: getDetectorFallbackTag(window.routeTag),\n sample,\n eligibility,\n contentGate,\n engineExecuted: true,\n rawResult,\n rawRemappedTag: rawRemapped?.tag ?? null,\n normalizedResult,\n normalizedRemappedTag: normalizedRemapped?.tag ?? null,\n decision: {\n accepted: false,\n path: null,\n finalTag: fallbackDebugOutcome.finalTag,\n ...(fallbackDebugOutcome.finalLocales\n ? { finalLocales: fallbackDebugOutcome.finalLocales }\n : {}),\n fallbackReason,\n },\n };\n emitDetectorWindowEvidence({\n window,\n windowIndex,\n sample: resolution.sample,\n eligibility: resolution.eligibility,\n contentGate: resolution.contentGate,\n rawResult: resolution.rawResult,\n rawRemappedTag: resolution.rawRemappedTag,\n normalizedResult: resolution.normalizedResult,\n normalizedRemappedTag: resolution.normalizedRemappedTag,\n decision: resolution.decision,\n debug,\n });\n debug?.emit?.(\"detector.window.fallback\", {\n routeTag: window.routeTag,\n finalTag: fallbackDebugOutcome.finalTag,\n ...(fallbackDebugOutcome.finalLocales\n ? { finalLocales: fallbackDebugOutcome.finalLocales }\n : {}),\n reason: fallbackReason,\n });\n return resolution;\n}\n","import type { LocaleChunk } from \"../wc/types\";\nimport { isAmbiguousDetectorRoute, type DetectorWindow } from \"./policy\";\n\nexport function buildDetectorWindows(chunks: LocaleChunk[]): DetectorWindow[] {\n const windows: DetectorWindow[] = [];\n\n for (let index = 0; index < chunks.length; index += 1) {\n const chunk = chunks[index];\n if (!chunk || !isAmbiguousDetectorRoute(chunk.locale)) {\n continue;\n }\n\n const previousWindow = windows[windows.length - 1];\n if (\n previousWindow &&\n previousWindow.routeTag === chunk.locale &&\n previousWindow.endIndex === index - 1\n ) {\n previousWindow.endIndex = index;\n previousWindow.text += chunk.text;\n continue;\n }\n\n windows.push({\n routeTag: chunk.locale,\n startIndex: index,\n endIndex: index,\n text: chunk.text,\n });\n }\n\n return windows;\n}\n","import { segmentTextByLocale } from \"../wc\";\nimport { resolveLocaleDetectContext } from \"../wc/locale-detect\";\nimport { buildWordCounterResultFromChunks } from \"./result-builder\";\nimport { countSectionsWithResolvedDetector } from \"./sections\";\nimport { type DetectorWindow } from \"./policy\";\nimport { createInspectInput, segmentTextByLocaleWithTrace } from \"./inspect-helpers\";\nimport type { DetectorInspectOptions, DetectorInspectResult } from \"./inspect-types\";\nimport {\n buildEmptyEngineInspectResult,\n buildEmptyPipelineInspectResult,\n buildEngineInspectResult,\n buildPipelineInspectResult,\n} from \"./wasm-inspect\";\nimport {\n createDeferredLatinPreSegmentOptions,\n reapplyDeferredLatinFallback,\n reapplyResolvedLatinHintRules,\n} from \"./wasm-presegment\";\nimport { executeEngineSample } from \"./wasm-engine\";\nimport { resolveWindowLocale, type ResolvedDetectorWindow } from \"./wasm-resolution\";\nimport { buildDetectorWindows } from \"./wasm-windows\";\nimport { WASM_DETECTOR_RUNTIME_UNAVAILABLE_MESSAGE } from \"./whatlang-wasm\";\nimport type {\n DetectorCountSectionsOptions,\n DetectorLocaleOptions,\n DetectorWordCounterOptions,\n} from \"./types\";\n\nexport { WASM_DETECTOR_RUNTIME_UNAVAILABLE_MESSAGE };\n\nexport async function segmentTextByLocaleWithWasmDetector(\n text: string,\n options: DetectorLocaleOptions = {},\n) {\n // Validate the original hint configuration up front even though Latin hinting\n // is deferred until after detector routing in WASM mode.\n resolveLocaleDetectContext(options);\n\n const chunks = segmentTextByLocale(text, createDeferredLatinPreSegmentOptions(options));\n const resolved = [...chunks];\n const windows = buildDetectorWindows(chunks);\n\n for (const [windowIndex, window] of windows.entries()) {\n const resolution = await resolveWindowLocale(\n window,\n windowIndex,\n chunks,\n options,\n options.detectorDebug,\n );\n for (let index = window.startIndex; index <= window.endIndex; index += 1) {\n const chunk = resolved[index];\n if (!chunk) {\n continue;\n }\n resolved[index] = {\n ...chunk,\n locale: resolution.resolvedLocale,\n };\n }\n }\n\n options.detectorDebug?.emit?.(\"detector.summary\", options.detectorDebug.summary, {\n verbosity: \"compact\",\n });\n const hintRelabeled = reapplyResolvedLatinHintRules(resolved, chunks, options);\n return reapplyDeferredLatinFallback(hintRelabeled, options);\n}\n\nexport async function wordCounterWithWasmDetector(\n text: string,\n options: DetectorWordCounterOptions = {},\n) {\n const chunks = await segmentTextByLocaleWithWasmDetector(text, options);\n return buildWordCounterResultFromChunks(chunks, options);\n}\n\nexport async function countSectionsWithWasmDetector(\n input: string,\n section: Parameters<typeof countSectionsWithResolvedDetector>[1],\n options: DetectorCountSectionsOptions = {},\n) {\n return countSectionsWithResolvedDetector(input, section, options);\n}\n\nexport async function inspectTextWithWasmDetector(\n text: string,\n options: DetectorInspectOptions = {},\n): Promise<DetectorInspectResult> {\n const input = createInspectInput(text, options.input);\n const tracedChunks = segmentTextByLocaleWithTrace(\n text,\n createDeferredLatinPreSegmentOptions(options),\n );\n const chunks = tracedChunks.map(({ locale, text: chunkText }) => ({\n locale,\n text: chunkText,\n }));\n const windows = buildDetectorWindows(chunks);\n\n if (options.view === \"engine\") {\n if (windows.length === 0) {\n return buildEmptyEngineInspectResult(input);\n }\n\n const window = windows[0]!;\n return buildEngineInspectResult(input, window, chunks, executeEngineSample);\n }\n\n if (text.trim().length === 0) {\n return buildEmptyPipelineInspectResult(input);\n }\n\n const resolved = [...chunks];\n const resolvedWindows: Array<\n ResolvedDetectorWindow & { window: DetectorWindow; windowIndex: number }\n > = [];\n\n for (const [windowIndex, window] of windows.entries()) {\n const resolution = await resolveWindowLocale(window, windowIndex, chunks, options);\n resolvedWindows.push({\n ...resolution,\n window,\n windowIndex,\n });\n for (let index = window.startIndex; index <= window.endIndex; index += 1) {\n const chunk = resolved[index];\n if (!chunk) {\n continue;\n }\n resolved[index] = {\n ...chunk,\n locale: resolution.resolvedLocale,\n };\n }\n }\n\n const hintRelabeled = reapplyResolvedLatinHintRules(resolved, chunks, options);\n const finalResolved = reapplyDeferredLatinFallback(hintRelabeled, options);\n\n return buildPipelineInspectResult(input, tracedChunks, resolvedWindows, finalResolved);\n}\n","import { inspectTextWithRegexDetector } from \"./none\";\nimport type { DetectorInspectOptions, DetectorInspectResult } from \"./inspect-types\";\nimport type { DetectorMode } from \"./types\";\nimport { inspectTextWithWasmDetector } from \"./wasm\";\n\nfunction resolveInspectDetectorMode(\n mode: DetectorMode | undefined,\n view: DetectorInspectOptions[\"view\"],\n): DetectorMode {\n if (mode) {\n return mode;\n }\n\n void view;\n return \"wasm\";\n}\n\nexport async function inspectTextWithDetector(\n text: string,\n options: DetectorInspectOptions = {},\n): Promise<DetectorInspectResult> {\n const view = options.view ?? \"pipeline\";\n const detector = resolveInspectDetectorMode(options.detector, view);\n\n if (detector === \"regex\" && view === \"engine\") {\n throw new Error('`view: \"engine\"` requires `detector: \"wasm\"`.');\n }\n\n if (detector === \"regex\") {\n return inspectTextWithRegexDetector(text, {\n ...options,\n detector,\n view: \"pipeline\",\n });\n }\n\n return inspectTextWithWasmDetector(text, {\n ...options,\n detector,\n view,\n });\n}\n","import type { SectionMode } from \"../markdown\";\nimport type { LocaleChunk } from \"../wc/types\";\nimport {\n countSectionsWithRegexDetector,\n inspectTextWithRegexDetector,\n segmentTextByLocaleWithRegexDetector,\n wordCounterWithRegexDetector,\n} from \"./none\";\nimport {\n countSectionsWithWasmDetector,\n inspectTextWithWasmDetector,\n segmentTextByLocaleWithWasmDetector,\n WASM_DETECTOR_RUNTIME_UNAVAILABLE_MESSAGE,\n wordCounterWithWasmDetector,\n} from \"./wasm\";\nimport { inspectTextWithDetector } from \"./inspect\";\nimport { createDetectorDebugSummary, mergeDetectorDebugSummaries } from \"./debug\";\nimport type {\n DetectorContentGateMode,\n DetectorContentGateOptions,\n DetectorCountSectionsOptions,\n DetectorLocaleOptions,\n DetectorMode,\n DetectorResult,\n DetectorSource,\n DetectorWordCounterOptions,\n} from \"./types\";\n\nexport type {\n DetectorContentGateMode,\n DetectorContentGateOptions,\n DetectorCountSections,\n DetectorCountSectionsOptions,\n DetectorCountResult,\n DetectorLocaleOptions,\n DetectorMode,\n DetectorResult,\n DetectorRuntimeOptions,\n DetectorSource,\n DetectorWordCounterOptions,\n} from \"./types\";\nexport type {\n DetectorInspectChunk,\n DetectorInspectDecision,\n DetectorInspectEngine,\n DetectorInspectEngineRaw,\n DetectorInspectEngineResult,\n DetectorInspectInput,\n DetectorInspectInputOptions,\n DetectorInspectInputSourceType,\n DetectorInspectKind,\n DetectorInspectOptions,\n DetectorInspectPipelineResult,\n DetectorInspectResult,\n DetectorInspectSample,\n DetectorInspectSchemaVersion,\n DetectorInspectView,\n DetectorInspectWindow,\n} from \"./inspect-types\";\nexport type {\n DetectorDebugContext,\n DetectorDebugSummary,\n DetectorDebugVerbosity,\n DetectorEvidenceConfig,\n DetectorFallbackReason,\n} from \"./debug\";\n\nexport const DETECTOR_MODES: DetectorMode[] = [\"regex\", \"wasm\"];\nexport const DEFAULT_DETECTOR_MODE: DetectorMode = \"regex\";\n\nexport function resolveDetectorMode(mode?: DetectorMode): DetectorMode {\n return mode ?? DEFAULT_DETECTOR_MODE;\n}\n\nexport function assertDetectorModeImplemented(mode?: DetectorMode): void {\n void mode;\n}\n\nexport async function segmentTextByLocaleWithDetector(\n text: string,\n options: DetectorLocaleOptions = {},\n): Promise<LocaleChunk[]> {\n const mode = resolveDetectorMode(options.detector);\n if (mode === \"wasm\") {\n return segmentTextByLocaleWithWasmDetector(text, options);\n }\n return segmentTextByLocaleWithRegexDetector(text, options);\n}\n\nexport async function wordCounterWithDetector(\n text: string,\n options: DetectorWordCounterOptions = {},\n) {\n const mode = resolveDetectorMode(options.detector);\n if (mode === \"wasm\") {\n return wordCounterWithWasmDetector(text, options);\n }\n return wordCounterWithRegexDetector(text, options);\n}\n\nexport async function countSectionsWithDetector(\n input: string,\n section: SectionMode,\n options: DetectorCountSectionsOptions = {},\n) {\n const mode = resolveDetectorMode(options.detector);\n if (mode === \"wasm\") {\n return countSectionsWithWasmDetector(input, section, options);\n }\n return countSectionsWithRegexDetector(input, section, options);\n}\n\nexport const DETECTOR_SOURCES: DetectorSource[] = [\"script\", \"hint\", \"wasm\"];\nexport const DEFAULT_DETECTOR_RESULT_SOURCE: DetectorSource = \"script\";\nexport { WASM_DETECTOR_RUNTIME_UNAVAILABLE_MESSAGE };\nexport {\n createDetectorDebugSummary,\n inspectTextWithDetector,\n inspectTextWithRegexDetector,\n inspectTextWithWasmDetector,\n mergeDetectorDebugSummaries,\n};\n\nexport function createDetectorResult(\n tag: string,\n source: DetectorSource = DEFAULT_DETECTOR_RESULT_SOURCE,\n confidence?: number,\n reliable?: boolean,\n): DetectorResult {\n return {\n tag,\n source,\n ...(confidence === undefined ? {} : { confidence }),\n ...(reliable === undefined ? {} : { reliable }),\n };\n}\n","import { extname, relative, sep } from \"node:path\";\n\nexport type DirectoryExtensionFilter = {\n includeExtensions: Set<string>;\n excludeExtensions: Set<string>;\n effectiveIncludeExtensions: Set<string>;\n};\n\nexport type DirectoryRegexFilter = {\n sourcePattern: string | undefined;\n regex: RegExp | undefined;\n};\n\nexport const DEFAULT_INCLUDE_EXTENSIONS = Object.freeze([\n \".md\",\n \".markdown\",\n \".mdx\",\n \".mdc\",\n \".txt\",\n]);\n\nexport function collectExtensionOption(value: string, previous: string[] = []): string[] {\n return [...previous, value];\n}\n\nexport function normalizeExtensionToken(value: string): string | null {\n const trimmed = value.trim().toLowerCase();\n if (!trimmed) {\n return null;\n }\n\n const normalized = trimmed.startsWith(\".\") ? trimmed : `.${trimmed}`;\n if (normalized === \".\") {\n return null;\n }\n\n return normalized;\n}\n\nfunction parseExtensionValues(values: string[] | undefined): Set<string> {\n const parsed = new Set<string>();\n if (!values || values.length === 0) {\n return parsed;\n }\n\n for (const value of values) {\n for (const token of value.split(\",\")) {\n const normalized = normalizeExtensionToken(token);\n if (!normalized) {\n continue;\n }\n parsed.add(normalized);\n }\n }\n\n return parsed;\n}\n\nexport function buildDirectoryExtensionFilter(\n includeValues: string[] | undefined,\n excludeValues: string[] | undefined,\n): DirectoryExtensionFilter {\n const includeFromFlags = parseExtensionValues(includeValues);\n const excludeExtensions = parseExtensionValues(excludeValues);\n\n const includeExtensions =\n includeFromFlags.size > 0 ? includeFromFlags : new Set(DEFAULT_INCLUDE_EXTENSIONS);\n\n const effectiveIncludeExtensions = new Set<string>();\n for (const extension of includeExtensions) {\n if (excludeExtensions.has(extension)) {\n continue;\n }\n effectiveIncludeExtensions.add(extension);\n }\n\n return {\n includeExtensions,\n excludeExtensions,\n effectiveIncludeExtensions,\n };\n}\n\nexport function shouldIncludeFromDirectory(\n filePath: string,\n filter: DirectoryExtensionFilter,\n): boolean {\n const extension = extname(filePath).toLowerCase();\n return filter.effectiveIncludeExtensions.has(extension);\n}\n\nexport function buildDirectoryRegexFilter(pattern: string | undefined): DirectoryRegexFilter {\n if (pattern === undefined) {\n return { sourcePattern: undefined, regex: undefined };\n }\n\n if (pattern.trim().length === 0) {\n return { sourcePattern: pattern, regex: undefined };\n }\n\n try {\n return { sourcePattern: pattern, regex: new RegExp(pattern) };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Invalid --regex pattern: ${message}`);\n }\n}\n\nexport function toDirectoryRelativePath(rootPath: string, filePath: string): string {\n const relativePath = relative(rootPath, filePath);\n if (sep === \"/\") {\n return relativePath;\n }\n return relativePath.split(sep).join(\"/\");\n}\n\nexport function shouldIncludeFromDirectoryRegex(\n relativePath: string,\n filter: DirectoryRegexFilter,\n): boolean {\n if (!filter.regex) {\n return true;\n }\n\n return filter.regex.test(relativePath);\n}\n","import { readFile } from \"node:fs/promises\";\nimport type { BatchFileInput, BatchSkip } from \"../types\";\n\nexport function isProbablyBinary(buffer: Buffer): boolean {\n if (buffer.length === 0) {\n return false;\n }\n\n const sampleSize = Math.min(buffer.length, 1024);\n let suspicious = 0;\n\n for (let index = 0; index < sampleSize; index += 1) {\n const byte = buffer[index] ?? 0;\n\n if (byte === 0) {\n return true;\n }\n\n if (byte === 9 || byte === 10 || byte === 13) {\n continue;\n }\n\n if (byte >= 32 && byte <= 126) {\n continue;\n }\n\n if (byte >= 128) {\n continue;\n }\n\n suspicious += 1;\n }\n\n return suspicious / sampleSize > 0.3;\n}\n\nexport async function loadBatchInputs(\n filePaths: string[],\n): Promise<{ files: BatchFileInput[]; skipped: BatchSkip[] }> {\n const files: BatchFileInput[] = [];\n const skipped: BatchSkip[] = [];\n\n for (const filePath of filePaths) {\n let buffer: Buffer;\n try {\n buffer = await readFile(filePath);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n skipped.push({ path: filePath, reason: `not readable: ${message}` });\n continue;\n }\n\n if (isProbablyBinary(buffer)) {\n skipped.push({ path: filePath, reason: \"binary file\" });\n continue;\n }\n\n files.push({\n path: filePath,\n content: buffer.toString(\"utf8\"),\n });\n }\n\n return { files, skipped };\n}\n","import type { DebugChannel } from \"../debug/channel\";\nimport type { PathResolveDebugStats } from \"./resolve-types\";\n\nconst NOOP_DEBUG_CHANNEL = {\n enabled: false,\n verbosity: \"compact\",\n emit() {\n return;\n },\n close: async () => {\n return;\n },\n} satisfies DebugChannel;\n\nexport function resolvePathDebugChannel(debug?: DebugChannel): DebugChannel {\n return debug ?? NOOP_DEBUG_CHANNEL;\n}\n\nexport function createPathResolveDebugStats(): PathResolveDebugStats {\n return {\n dedupeAccepted: 0,\n dedupeDuplicates: 0,\n filterExcluded: 0,\n regexExcluded: 0,\n directoryIncluded: 0,\n };\n}\n\nexport function emitPathResolveSummaries(\n debug: DebugChannel,\n stats: PathResolveDebugStats,\n files: number,\n skipped: number,\n): void {\n debug.emit(\"path.resolve.filter.summary\", {\n excluded: stats.filterExcluded + stats.regexExcluded,\n extensionExcluded: stats.filterExcluded,\n regexExcluded: stats.regexExcluded,\n included: stats.directoryIncluded,\n });\n debug.emit(\"path.resolve.dedupe.summary\", {\n accepted: stats.dedupeAccepted,\n duplicates: stats.dedupeDuplicates,\n });\n debug.emit(\"path.resolve.complete\", {\n files,\n skipped,\n ordering: \"absolute-path-ascending\",\n });\n}\n","import { type Dirent } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { resolve as resolvePath } from \"node:path\";\nimport { appendAll } from \"../../utils/append-all\";\nimport type { DebugChannel } from \"../debug/channel\";\nimport type { BatchResolvedSkip } from \"../types\";\nimport {\n shouldIncludeFromDirectory,\n shouldIncludeFromDirectoryRegex,\n toDirectoryRelativePath,\n} from \"./filter\";\nimport type { ExpandDirectoryOptions, PathResolveDebugStats } from \"./resolve-types\";\n\nexport async function expandDirectory(\n { rootPath, directoryPath, recursive, extensionFilter, regexFilter }: ExpandDirectoryOptions,\n skipped: BatchResolvedSkip[],\n recordRegexExcluded: (filePath: string) => boolean,\n debug: DebugChannel,\n stats: PathResolveDebugStats,\n): Promise<string[]> {\n let entries: Dirent[];\n try {\n entries = await readdir(directoryPath, { withFileTypes: true, encoding: \"utf8\" });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n skipped.push({\n path: directoryPath,\n reason: `directory read failed: ${message}`,\n source: \"directory\",\n });\n debug.emit(\"path.resolve.expand.read_failed\", {\n directory: directoryPath,\n reason: `directory read failed: ${message}`,\n });\n return [];\n }\n\n const sortedEntries = entries.slice().sort((left, right) => left.name.localeCompare(right.name));\n const files: string[] = [];\n debug.emit(\"path.resolve.expand.start\", {\n directory: directoryPath,\n entries: sortedEntries.length,\n recursive,\n });\n\n for (const entry of sortedEntries) {\n const entryPath = resolvePath(directoryPath, entry.name);\n\n if (entry.isFile()) {\n if (!shouldIncludeFromDirectory(entryPath, extensionFilter)) {\n skipped.push({ path: entryPath, reason: \"extension excluded\", source: \"directory\" });\n debug.emit(\n \"path.resolve.filter.excluded\",\n {\n path: entryPath,\n reason: \"extension excluded\",\n },\n { verbosity: \"verbose\" },\n );\n stats.filterExcluded += 1;\n continue;\n }\n\n const relativePath = toDirectoryRelativePath(rootPath, entryPath);\n if (!shouldIncludeFromDirectoryRegex(relativePath, regexFilter)) {\n if (recordRegexExcluded(entryPath)) {\n debug.emit(\n \"path.resolve.regex.excluded\",\n {\n path: entryPath,\n relativePath,\n pattern: regexFilter.sourcePattern,\n reason: \"regex excluded\",\n },\n { verbosity: \"verbose\" },\n );\n stats.regexExcluded += 1;\n }\n continue;\n }\n\n files.push(entryPath);\n stats.directoryIncluded += 1;\n debug.emit(\n \"path.resolve.expand.include\",\n {\n path: entryPath,\n source: \"directory\",\n },\n { verbosity: \"verbose\" },\n );\n continue;\n }\n\n if (!entry.isDirectory() || !recursive) {\n continue;\n }\n\n const nestedFiles = await expandDirectory(\n {\n rootPath,\n directoryPath: entryPath,\n recursive,\n extensionFilter,\n regexFilter,\n },\n skipped,\n recordRegexExcluded,\n debug,\n stats,\n );\n appendAll(files, nestedFiles);\n }\n\n debug.emit(\"path.resolve.expand.complete\", {\n directory: directoryPath,\n files: files.length,\n });\n\n return files;\n}\n","import { stat } from \"node:fs/promises\";\nimport { resolve as resolvePath } from \"node:path\";\nimport type { BatchResolvedFile, BatchResolvedSkip, BatchSkip } from \"../types\";\nimport {\n buildDirectoryRegexFilter,\n buildDirectoryExtensionFilter,\n type DirectoryRegexFilter,\n} from \"./filter\";\nimport {\n createPathResolveDebugStats,\n emitPathResolveSummaries,\n resolvePathDebugChannel,\n} from \"./resolve-debug\";\nimport { expandDirectory } from \"./resolve-directory\";\nimport type { PathResolveDebugStats, ResolveBatchFilePathOptions } from \"./resolve-types\";\n\nexport async function resolveBatchFileEntries(\n pathInputs: string[],\n options: ResolveBatchFilePathOptions,\n): Promise<{ files: BatchResolvedFile[]; skipped: BatchResolvedSkip[] }> {\n const skipped: BatchResolvedSkip[] = [];\n const regexExcludedPaths = new Set<string>();\n const resolvedFiles = new Map<string, BatchResolvedFile>();\n const stats: PathResolveDebugStats = createPathResolveDebugStats();\n const extensionFilter =\n options.extensionFilter ?? buildDirectoryExtensionFilter(undefined, undefined);\n let regexFilter: DirectoryRegexFilter | undefined;\n const debug = resolvePathDebugChannel(options.debug);\n\n debug.emit(\"path.resolve.inputs\", {\n inputs: pathInputs.length,\n pathMode: options.pathMode,\n recursive: options.recursive,\n hasRegex: Boolean(options.directoryRegexPattern),\n });\n\n const addResolvedFile = (\n filePath: string,\n details: { source: \"direct\" | \"directory\"; input: string },\n ): void => {\n regexExcludedPaths.delete(filePath);\n\n const existing = resolvedFiles.get(filePath);\n if (existing) {\n if (existing.source === \"directory\" && details.source === \"direct\") {\n resolvedFiles.set(filePath, {\n path: filePath,\n source: \"direct\",\n });\n }\n stats.dedupeDuplicates += 1;\n debug.emit(\n \"path.resolve.dedupe.duplicate\",\n {\n path: filePath,\n source: details.source,\n input: details.input,\n },\n { verbosity: \"verbose\" },\n );\n return;\n }\n\n resolvedFiles.set(filePath, {\n path: filePath,\n source: details.source,\n });\n stats.dedupeAccepted += 1;\n debug.emit(\n \"path.resolve.dedupe.accept\",\n {\n path: filePath,\n source: details.source,\n input: details.input,\n },\n { verbosity: \"verbose\" },\n );\n };\n\n const getRegexFilter = (): DirectoryRegexFilter => {\n if (!regexFilter) {\n regexFilter = buildDirectoryRegexFilter(options.directoryRegexPattern);\n }\n return regexFilter;\n };\n\n const recordRegexExcluded = (filePath: string): boolean => {\n if (resolvedFiles.has(filePath)) {\n return false;\n }\n\n regexExcludedPaths.add(filePath);\n return true;\n };\n\n for (const rawPath of pathInputs) {\n const targetPath = resolvePath(rawPath);\n debug.emit(\"path.resolve.input\", {\n rawPath,\n resolvedPath: targetPath,\n });\n let metadata: Awaited<ReturnType<typeof stat>>;\n\n try {\n metadata = await stat(targetPath);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n skipped.push({ path: targetPath, reason: `not readable: ${message}`, source: \"direct\" });\n debug.emit(\"path.resolve.skip\", {\n path: targetPath,\n reason: `not readable: ${message}`,\n });\n continue;\n }\n\n if (metadata.isDirectory() && options.pathMode === \"auto\") {\n const effectiveRegexFilter = getRegexFilter();\n debug.emit(\"path.resolve.root.expand\", {\n root: targetPath,\n recursive: options.recursive,\n regex: effectiveRegexFilter.sourcePattern ?? null,\n });\n const files = await expandDirectory(\n {\n rootPath: targetPath,\n directoryPath: targetPath,\n recursive: options.recursive,\n extensionFilter,\n regexFilter: effectiveRegexFilter,\n },\n skipped,\n recordRegexExcluded,\n debug,\n stats,\n );\n for (const file of files) {\n addResolvedFile(file, { source: \"directory\", input: targetPath });\n }\n continue;\n }\n\n if (!metadata.isFile()) {\n skipped.push({ path: targetPath, reason: \"not a regular file\", source: \"direct\" });\n debug.emit(\"path.resolve.skip\", {\n path: targetPath,\n reason: \"not a regular file\",\n });\n continue;\n }\n\n addResolvedFile(targetPath, { source: \"direct\", input: targetPath });\n }\n\n for (const path of regexExcludedPaths) {\n skipped.push({ path, reason: \"regex excluded\", source: \"directory\" });\n }\n\n const files = [...resolvedFiles.values()].sort((left, right) =>\n left.path.localeCompare(right.path),\n );\n emitPathResolveSummaries(debug, stats, files.length, skipped.length);\n\n return { files, skipped };\n}\n\nexport async function resolveBatchFilePaths(\n pathInputs: string[],\n options: ResolveBatchFilePathOptions,\n): Promise<{ files: string[]; skipped: BatchSkip[] }> {\n const resolved = await resolveBatchFileEntries(pathInputs, options);\n return {\n files: resolved.files.map((file) => file.path),\n skipped: resolved.skipped.map(({ path, reason }) => ({ path, reason })),\n };\n}\n","import { readFileSync } from \"node:fs\";\nimport { requiresNonWordCollection, requiresWhitespaceCollection } from \"../total-of\";\nimport type { BatchScope } from \"../types\";\nimport type { LatinHintRule } from \"../../wc\";\nimport type { CliActionOptions, ResolvedCountRunOptions } from \"./types\";\n\nexport function hasPathInput(pathValues: string[] | undefined): pathValues is string[] {\n return Array.isArray(pathValues) && pathValues.length > 0;\n}\n\nfunction countLongOptionOccurrences(argv: string[], optionName: string): number {\n let count = 0;\n for (let index = 2; index < argv.length; index += 1) {\n const token = argv[index];\n if (!token) {\n continue;\n }\n if (token === \"--\") {\n break;\n }\n\n if (token === optionName) {\n count += 1;\n // Consume the next token as this option's value so literal values like\n // \"--regex=foo\" are not misread as a second option occurrence.\n index += 1;\n continue;\n }\n\n if (token.startsWith(`${optionName}=`)) {\n count += 1;\n continue;\n }\n }\n\n return count;\n}\n\nexport function validateSingleRegexOptionUsage(argv: string[]): void {\n if (countLongOptionOccurrences(argv, \"--regex\") > 1) {\n throw new Error(\"`--regex` can only be provided once.\");\n }\n}\n\nexport function validateStandalonePrintJobsLimitUsage(argv: string[]): void {\n const tokens = argv.slice(2).filter((token) => token.length > 0);\n if (tokens.length !== 1 || tokens[0] !== \"--print-jobs-limit\") {\n throw new Error(\"`--print-jobs-limit` must be used alone.\");\n }\n}\n\nexport function resolveBatchScope(argv: string[]): BatchScope {\n let scope: BatchScope = \"merged\";\n for (const token of argv) {\n if (token === \"--merged\") {\n scope = \"merged\";\n continue;\n }\n\n if (token === \"--per-file\") {\n scope = \"per-file\";\n }\n }\n\n return scope;\n}\n\nexport function resolveDebugReportPathOption(\n rawValue: string | boolean | undefined,\n): string | undefined {\n if (rawValue === undefined || rawValue === false) {\n return undefined;\n }\n\n if (typeof rawValue === \"string\") {\n return rawValue;\n }\n\n return undefined;\n}\n\nexport function parseInlineLatinHintRule(value: string): LatinHintRule {\n const separatorIndex = value.indexOf(\"=\");\n if (separatorIndex <= 0) {\n throw new Error(\"`--latin-hint` must use `<tag>=<pattern>` format.\");\n }\n\n const tag = value.slice(0, separatorIndex).trim();\n const pattern = value.slice(separatorIndex + 1);\n\n if (!tag) {\n throw new Error(\"`--latin-hint` tag must be non-empty.\");\n }\n\n if (!pattern) {\n throw new Error(\"`--latin-hint` pattern must be non-empty.\");\n }\n\n return { tag, pattern };\n}\n\nfunction parseLatinHintsFileRule(value: unknown, index: number, sourcePath: string): LatinHintRule {\n if (typeof value !== \"object\" || value === null) {\n throw new Error(`Invalid Latin hint rule at ${sourcePath}#${index}: rule must be an object.`);\n }\n\n const tag = \"tag\" in value ? value.tag : undefined;\n const pattern = \"pattern\" in value ? value.pattern : undefined;\n const priority = \"priority\" in value ? value.priority : undefined;\n\n if (typeof tag !== \"string\" || tag.trim().length === 0) {\n throw new Error(\n `Invalid Latin hint rule at ${sourcePath}#${index}: tag must be a non-empty string.`,\n );\n }\n\n if (typeof pattern !== \"string\") {\n throw new Error(`Invalid Latin hint rule at ${sourcePath}#${index}: pattern must be a string.`);\n }\n\n if (priority !== undefined && (typeof priority !== \"number\" || !Number.isFinite(priority))) {\n throw new Error(\n `Invalid Latin hint rule at ${sourcePath}#${index}: priority must be a finite number.`,\n );\n }\n\n return {\n tag,\n pattern,\n ...(priority !== undefined ? { priority } : {}),\n };\n}\n\nfunction parseLatinHintsFile(path: string): LatinHintRule[] {\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Failed to read Latin hint file (${path}): ${message}`);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Invalid JSON in Latin hint file (${path}): ${message}`);\n }\n\n if (!Array.isArray(parsed)) {\n throw new Error(`Latin hint file (${path}) must contain a JSON array.`);\n }\n\n return parsed.map((rule, index) => parseLatinHintsFileRule(rule, index, path));\n}\n\nfunction resolveLatinHintRules(options: CliActionOptions): LatinHintRule[] | undefined {\n const inlineRules = (options.latinHint ?? []).map((value) => parseInlineLatinHintRule(value));\n const fileRules =\n typeof options.latinHintsFile === \"string\" && options.latinHintsFile.length > 0\n ? parseLatinHintsFile(options.latinHintsFile)\n : [];\n\n const mergedRules = [...inlineRules, ...fileRules];\n if (mergedRules.length === 0) {\n return undefined;\n }\n\n return mergedRules;\n}\n\nexport function resolveCountRunOptions(options: CliActionOptions): ResolvedCountRunOptions {\n const useSection = options.section !== \"all\";\n const detectorMode = options.detector ?? \"regex\";\n const totalOfParts = options.totalOf;\n const requestedNonWords = Boolean(options.nonWords || options.includeWhitespace || options.misc);\n const collectNonWordsForOverride = requiresNonWordCollection(totalOfParts);\n const collectWhitespaceForOverride = requiresWhitespaceCollection(totalOfParts);\n const enableNonWords = Boolean(\n options.nonWords || options.includeWhitespace || options.misc || collectNonWordsForOverride,\n );\n const enableWhitespace = Boolean(\n options.includeWhitespace || options.misc || collectWhitespaceForOverride,\n );\n const shouldNormalizeBaseOutput = !requestedNonWords && enableNonWords;\n\n return {\n useSection,\n detectorMode,\n totalOfParts,\n requestedNonWords,\n shouldNormalizeBaseOutput,\n wcOptions: {\n detector: detectorMode,\n contentGate:\n options.contentGate === undefined\n ? undefined\n : {\n mode: options.contentGate,\n },\n mode: options.mode,\n latinLanguageHint: options.latinLanguage,\n latinTagHint: options.latinTag,\n latinLocaleHint: options.latinLocale,\n latinHintRules: resolveLatinHintRules(options),\n useDefaultLatinHints: options.defaultLatinHints !== false,\n hanLanguageHint: options.hanLanguage,\n hanTagHint: options.hanTag,\n nonWords: enableNonWords,\n includeWhitespace: enableWhitespace,\n },\n };\n}\n\nexport function formatInputReadError(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n return `Failed to read input: ${message}`;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { parseMarkdown } from \"../../markdown\";\nimport { buildDirectoryExtensionFilter } from \"../path/filter\";\nimport { isProbablyBinary } from \"../path/load\";\nimport { resolveBatchFileEntries } from \"../path/resolve\";\nimport { formatInputReadError } from \"../runtime/options\";\nimport type { BatchSkip, PathMode } from \"../types\";\nimport type { InspectLoadedPathInput, InspectSectionMode, InspectSingleInput } from \"./types\";\n\nexport function selectInspectText(input: string, section: InspectSectionMode): string {\n if (section === \"all\") {\n return input;\n }\n\n const parsed = parseMarkdown(input);\n if (section === \"frontmatter\") {\n return parsed.frontmatter ?? \"\";\n }\n\n return parsed.content;\n}\n\nexport async function loadSingleInspectInput(\n path: string | undefined,\n textTokens: string[],\n section: InspectSectionMode,\n detectBinary = true,\n): Promise<InspectSingleInput> {\n if (path) {\n try {\n const buffer = await readFile(path);\n if (detectBinary && isProbablyBinary(buffer)) {\n throw new Error(\"binary file\");\n }\n return {\n text: selectInspectText(buffer.toString(\"utf8\"), section),\n sourceType: \"path\",\n path,\n };\n } catch (error) {\n if (error instanceof Error && error.message === \"binary file\") {\n throw error;\n }\n throw new Error(formatInputReadError(error));\n }\n }\n\n return {\n text: selectInspectText(textTokens.join(\" \"), section),\n sourceType: \"inline\",\n };\n}\n\nexport async function loadInspectBatchInputs(\n pathInputs: string[],\n options: {\n pathMode: PathMode;\n pathDetectBinary: boolean;\n recursive: boolean;\n includeExt: string[];\n excludeExt: string[];\n regex?: string;\n },\n): Promise<{\n files: InspectLoadedPathInput[];\n skipped: BatchSkip[];\n failures: BatchSkip[];\n}> {\n const resolved = await resolveBatchFileEntries(pathInputs, {\n pathMode: options.pathMode,\n recursive: options.recursive,\n extensionFilter: buildDirectoryExtensionFilter(options.includeExt, options.excludeExt),\n ...(options.regex !== undefined ? { directoryRegexPattern: options.regex } : {}),\n });\n\n const skipped: BatchSkip[] = [];\n const failures: BatchSkip[] = [];\n for (const skip of resolved.skipped) {\n if (skip.source === \"direct\") {\n failures.push({ path: skip.path, reason: skip.reason });\n continue;\n }\n skipped.push({ path: skip.path, reason: skip.reason });\n }\n\n const files: InspectLoadedPathInput[] = [];\n for (const entry of resolved.files) {\n let buffer: Buffer;\n try {\n buffer = await readFile(entry.path);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (entry.source === \"direct\") {\n failures.push({ path: entry.path, reason: `not readable: ${message}` });\n } else {\n skipped.push({ path: entry.path, reason: `not readable: ${message}` });\n }\n continue;\n }\n\n if (options.pathDetectBinary && isProbablyBinary(buffer)) {\n if (entry.source === \"direct\") {\n failures.push({ path: entry.path, reason: \"binary file\" });\n } else {\n skipped.push({ path: entry.path, reason: \"binary file\" });\n }\n continue;\n }\n\n files.push({\n path: entry.path,\n source: entry.source,\n text: buffer.toString(\"utf8\"),\n });\n }\n\n skipped.sort((left, right) => left.path.localeCompare(right.path));\n failures.sort((left, right) => left.path.localeCompare(right.path));\n\n return { files, skipped, failures };\n}\n","import { createInspectPreview } from \"../../detector/inspect-helpers\";\nimport type { DetectorInspectResult } from \"../../detector/inspect-types\";\nimport type { InspectBatchJsonPayload } from \"./types\";\n\nexport function buildInspectStandardLines(\n result: DetectorInspectResult,\n options: { includeTitle?: boolean } = {},\n): string[] {\n const includeTitle = options.includeTitle !== false;\n const lines: string[] = [];\n\n if (includeTitle) {\n lines.push(\"Detector inspect\");\n lines.push(`View: ${result.view}`);\n lines.push(`Detector: ${result.detector}`);\n lines.push(\"\");\n }\n\n lines.push(\"Input\");\n lines.push(`Source: ${result.input.sourceType}`);\n if (result.input.path) {\n lines.push(`Path: ${result.input.path}`);\n }\n lines.push(`Text length: ${result.input.textLength}`);\n\n if (result.view === \"engine\") {\n const samplePreview = createInspectPreview(result.sample.text);\n const normalizedPreview = createInspectPreview(result.sample.normalizedText);\n\n lines.push(\"\");\n lines.push(\"Sample\");\n lines.push(`Text source: ${result.sample.textSource}`);\n lines.push(`Sample text preview: ${JSON.stringify(samplePreview.textPreview)}`);\n lines.push(`Sample text truncated: ${samplePreview.textPreviewTruncated}`);\n lines.push(`Normalized text preview: ${JSON.stringify(normalizedPreview.textPreview)}`);\n lines.push(`Normalized text truncated: ${normalizedPreview.textPreviewTruncated}`);\n if (result.sample.borrowedContext) {\n lines.push(`Borrowed context: ${JSON.stringify(result.sample.borrowedContext)}`);\n }\n if (result.routeTag) {\n lines.push(`Route tag: ${result.routeTag}`);\n }\n if (result.engine) {\n lines.push(\"\");\n lines.push(\"Engine\");\n lines.push(\n `Raw: ${result.engine.raw.lang}/${result.engine.raw.script} confidence=${result.engine.raw.confidence} reliable=${result.engine.raw.reliable}`,\n );\n if (result.engine.normalized) {\n lines.push(\n `Normalized: ${result.engine.normalized.lang}/${result.engine.normalized.script} confidence=${result.engine.normalized.confidence} reliable=${result.engine.normalized.reliable}`,\n );\n }\n lines.push(\n `Remap: raw=${result.engine.remapped.rawTag ?? \"null\"} normalized=${result.engine.remapped.normalizedTag ?? \"null\"}`,\n );\n } else if (result.decision?.kind === \"empty\") {\n lines.push(\"\");\n lines.push(`Decision: ${result.decision.notes.join(\" \")}`);\n }\n return lines;\n }\n\n lines.push(\"\");\n lines.push(\"Chunks\");\n if (result.chunks.length === 0) {\n lines.push(\"(none)\");\n } else {\n for (const chunk of result.chunks) {\n const source = chunk.source ? ` | ${chunk.source}` : \"\";\n const reason = chunk.reason ? ` | ${chunk.reason}` : \"\";\n lines.push(\n `[${chunk.index}] ${chunk.locale}${source}${reason} | ${JSON.stringify(chunk.textPreview)}`,\n );\n }\n }\n\n if (result.windows) {\n for (const window of result.windows) {\n lines.push(\"\");\n lines.push(`Window ${window.windowIndex}`);\n lines.push(`Route: ${window.routeTag}`);\n lines.push(`Chunk range: ${window.chunkRange.start}-${window.chunkRange.end}`);\n lines.push(`Focus: ${JSON.stringify(window.focusTextPreview)}`);\n if (window.diagnosticSample.borrowedContext) {\n lines.push(`Borrowed context: ${JSON.stringify(window.diagnosticSample.borrowedContext)}`);\n }\n lines.push(`Sample: ${JSON.stringify(window.diagnosticSample.textPreview)}`);\n lines.push(\n `Normalized sample: ${JSON.stringify(window.diagnosticSample.normalizedTextPreview)}`,\n );\n lines.push(\n `Eligibility: ${window.eligibility.scriptChars}/${window.eligibility.minScriptChars} passed=${window.eligibility.passed}`,\n );\n lines.push(\n `Content gate: mode=${window.contentGate.mode} policy=${window.contentGate.policy} applied=${window.contentGate.applied} passed=${window.contentGate.passed}`,\n );\n lines.push(\n `Engine: ${window.engine.executed ? \"executed\" : `skipped (${window.engine.reason ?? \"unknown\"})`}`,\n );\n lines.push(\n `Decision: accepted=${window.decision.accepted} path=${window.decision.path ?? \"null\"} final=${window.decision.finalTag} fallback=${window.decision.fallbackReason ?? \"null\"}`,\n );\n }\n }\n\n if (result.decision && \"kind\" in result.decision) {\n lines.push(\"\");\n lines.push(`Decision: ${result.decision.kind}`);\n lines.push(result.decision.notes.join(\" \"));\n }\n\n lines.push(\"\");\n lines.push(\"Resolved\");\n if (result.resolvedChunks.length === 0) {\n lines.push(\"(none)\");\n return lines;\n }\n for (const chunk of result.resolvedChunks) {\n lines.push(`[${chunk.index}] ${chunk.locale} | ${JSON.stringify(chunk.textPreview)}`);\n }\n\n return lines;\n}\n\nexport function buildInspectBatchStandardLines(payload: InspectBatchJsonPayload): string[] {\n const lines: string[] = [\n \"Detector inspect batch\",\n `View: ${payload.view}`,\n `Detector: ${payload.detector}`,\n `Section: ${payload.section}`,\n `Requested inputs: ${payload.summary.requestedInputs}`,\n `Summary: ${payload.summary.succeeded} succeeded, ${payload.summary.skipped} skipped, ${payload.summary.failed} failed`,\n ];\n\n for (const file of payload.files) {\n lines.push(\"\");\n lines.push(`File: ${file.path}`);\n lines.push(...buildInspectStandardLines(file.result, { includeTitle: false }));\n }\n\n if (payload.skipped.length > 0) {\n lines.push(\"\");\n lines.push(\"Skipped\");\n for (const item of payload.skipped) {\n lines.push(`${item.path} | ${item.reason}`);\n }\n }\n\n if (payload.failures.length > 0) {\n lines.push(\"\");\n lines.push(\"Failures\");\n for (const item of payload.failures) {\n lines.push(`${item.path} | ${item.reason}`);\n }\n }\n\n return lines;\n}\n\nexport function printLines(lines: string[]): void {\n for (const line of lines) {\n console.log(line);\n }\n}\n","import { inspectTextWithDetector } from \"../../detector\";\nimport type { BatchSkip } from \"../types\";\nimport { selectInspectText } from \"./input\";\nimport { buildInspectBatchStandardLines, printLines } from \"./render\";\nimport type {\n InspectBatchJsonPayload,\n InspectLoadedPathInput,\n ParsedInspectInvocation,\n} from \"./types\";\n\nexport function buildInspectBatchJsonPayload(\n validated: ParsedInspectInvocation,\n files: Array<{ path: string; result: Awaited<ReturnType<typeof inspectTextWithDetector>> }>,\n skipped: BatchSkip[],\n failures: BatchSkip[],\n): InspectBatchJsonPayload {\n return {\n schemaVersion: 1,\n kind: \"detector-inspect-batch\",\n detector: validated.detector,\n view: validated.view,\n section: validated.section,\n summary: {\n requestedInputs: validated.paths.length,\n succeeded: files.length,\n skipped: skipped.length,\n failed: failures.length,\n },\n files,\n skipped,\n failures,\n };\n}\n\nexport async function runInspectBatch(\n validated: ParsedInspectInvocation,\n loaded: {\n files: InspectLoadedPathInput[];\n skipped: BatchSkip[];\n failures: BatchSkip[];\n },\n): Promise<void> {\n const batchFiles: Array<{\n path: string;\n result: Awaited<ReturnType<typeof inspectTextWithDetector>>;\n }> = [];\n for (const file of loaded.files) {\n const result = await inspectTextWithDetector(selectInspectText(file.text, validated.section), {\n detector: validated.detector,\n contentGate: {\n mode: validated.contentGateMode,\n },\n view: validated.view,\n input: {\n sourceType: \"path\",\n path: file.path,\n },\n });\n batchFiles.push({\n path: file.path,\n result,\n });\n }\n\n const payload = buildInspectBatchJsonPayload(\n validated,\n batchFiles,\n loaded.skipped,\n loaded.failures,\n );\n if (validated.format === \"json\") {\n console.log(JSON.stringify(payload, null, validated.pretty ? 2 : 0));\n } else {\n printLines(buildInspectBatchStandardLines(payload));\n }\n\n process.exitCode = payload.failures.length > 0 || payload.files.length === 0 ? 1 : 0;\n}\n","const INSPECT_HELP_LINES = [\n \"Usage: word-counter inspect [options] [text...]\",\n \"\",\n \"inspect detector behavior without count output\",\n \"\",\n \"Options:\",\n \" -d, --detector <mode> inspect detector mode (wasm, regex) (default: regex)\",\n \" --content-gate <mode> content gate mode (default, strict, loose, off) (default: default)\",\n \" --view <view> inspect view (pipeline, engine) (default: pipeline)\",\n \" -f, --format <format> inspect output format (standard, json) (default: standard)\",\n \" --pretty pretty print inspect JSON output\",\n \" --section <section> inspect section selector (all, frontmatter, content) (default: all)\",\n \" --path-mode <mode> path resolution mode for --path inputs (auto, manual) (default: auto)\",\n \" --recursive enable recursive directory traversal for --path directories\",\n \" --no-recursive disable recursive directory traversal for --path directories\",\n \" --include-ext <exts> comma-separated extensions to include during directory scanning\",\n \" --exclude-ext <exts> comma-separated extensions to exclude during directory scanning\",\n \" --regex <pattern> regex filter for directory-expanded paths\",\n \" -p, --path <path> inspect text from file or directory inputs\",\n \" -h, --help display help for command\",\n];\n\nexport function printInspectHelp(): void {\n for (const line of INSPECT_HELP_LINES) {\n console.log(line);\n }\n}\n","import type { DetectorInspectView } from \"../../detector/inspect-types\";\nimport type { DetectorContentGateMode } from \"../../detector\";\nimport type { PathMode } from \"../types\";\nimport type {\n InspectDetectorMode,\n InspectOutputFormat,\n InspectSectionMode,\n ValidInspectInvocation,\n} from \"./types\";\n\nfunction parseDetector(rawValue: string | undefined): InspectDetectorMode | null {\n if (rawValue === undefined) {\n return \"regex\";\n }\n if (rawValue === \"wasm\" || rawValue === \"regex\") {\n return rawValue;\n }\n return null;\n}\n\nfunction parseView(rawValue: string | undefined): DetectorInspectView | null {\n if (rawValue === undefined) {\n return \"pipeline\";\n }\n if (rawValue === \"pipeline\" || rawValue === \"engine\") {\n return rawValue;\n }\n return null;\n}\n\nfunction parseFormat(rawValue: string | undefined): InspectOutputFormat | null {\n if (rawValue === undefined) {\n return \"standard\";\n }\n if (rawValue === \"standard\" || rawValue === \"json\") {\n return rawValue;\n }\n return null;\n}\n\nfunction parseContentGateMode(rawValue: string | undefined): DetectorContentGateMode | null {\n if (rawValue === undefined) {\n return \"default\";\n }\n if (\n rawValue === \"default\" ||\n rawValue === \"strict\" ||\n rawValue === \"loose\" ||\n rawValue === \"off\"\n ) {\n return rawValue;\n }\n return null;\n}\n\nfunction parsePathMode(rawValue: string | undefined): PathMode | null {\n if (rawValue === undefined) {\n return \"auto\";\n }\n if (rawValue === \"auto\" || rawValue === \"manual\") {\n return rawValue;\n }\n return null;\n}\n\nfunction isSupportedInspectSectionMode(value: string): value is InspectSectionMode {\n return value === \"all\" || value === \"frontmatter\" || value === \"content\";\n}\n\nexport function validateInspectInvocation(argv: string[]): ValidInspectInvocation {\n const inspectIndex = argv.findIndex((token, index) => index >= 2 && token === \"inspect\");\n const tokens = inspectIndex >= 0 ? argv.slice(inspectIndex + 1) : [];\n let detector: InspectDetectorMode = \"regex\";\n let contentGateMode: DetectorContentGateMode = \"default\";\n let view: DetectorInspectView = \"pipeline\";\n let format: InspectOutputFormat = \"standard\";\n let pretty = false;\n let section: InspectSectionMode = \"all\";\n let pathMode: PathMode = \"auto\";\n let recursive = true;\n const paths: string[] = [];\n const includeExt: string[] = [];\n const excludeExt: string[] = [];\n let regex: string | undefined;\n const textTokens: string[] = [];\n const sources = {\n detector: false,\n contentGate: false,\n pathMode: false,\n recursive: false,\n includeExt: false,\n excludeExt: false,\n };\n let expects:\n | \"detector\"\n | \"view\"\n | \"contentGate\"\n | \"format\"\n | \"section\"\n | \"pathMode\"\n | \"path\"\n | \"includeExt\"\n | \"excludeExt\"\n | \"regex\"\n | null = null;\n let positionalMode = false;\n\n const consumeValue = (\n kind:\n | \"detector\"\n | \"view\"\n | \"contentGate\"\n | \"format\"\n | \"section\"\n | \"pathMode\"\n | \"path\"\n | \"includeExt\"\n | \"excludeExt\"\n | \"regex\",\n value: string,\n ): string | null => {\n if (kind === \"detector\") {\n const parsed = parseDetector(value);\n if (parsed === null) {\n return \"`--detector` must be `wasm` or `regex`.\";\n }\n detector = parsed;\n sources.detector = true;\n return null;\n }\n\n if (kind === \"view\") {\n const parsed = parseView(value);\n if (parsed === null) {\n return \"`--view` must be `pipeline` or `engine`.\";\n }\n view = parsed;\n return null;\n }\n\n if (kind === \"contentGate\") {\n const parsed = parseContentGateMode(value);\n if (parsed === null) {\n return \"`--content-gate` must be `default`, `strict`, `loose`, or `off`.\";\n }\n contentGateMode = parsed;\n sources.contentGate = true;\n return null;\n }\n\n if (kind === \"format\") {\n if (value === \"raw\") {\n return \"`inspect` does not support `--format raw`.\";\n }\n const parsed = parseFormat(value);\n if (parsed === null) {\n return \"`--format` must be `standard` or `json`.\";\n }\n format = parsed;\n return null;\n }\n\n if (kind === \"section\") {\n if (!isSupportedInspectSectionMode(value)) {\n return \"`inspect` supports `--section all`, `frontmatter`, or `content`.\";\n }\n section = value;\n return null;\n }\n\n if (kind === \"pathMode\") {\n const parsed = parsePathMode(value);\n if (parsed === null) {\n return \"`--path-mode` must be `auto` or `manual`.\";\n }\n pathMode = parsed;\n sources.pathMode = true;\n return null;\n }\n\n if (kind === \"path\") {\n paths.push(value);\n return null;\n }\n\n if (kind === \"includeExt\") {\n includeExt.push(value);\n sources.includeExt = true;\n return null;\n }\n\n if (kind === \"excludeExt\") {\n excludeExt.push(value);\n sources.excludeExt = true;\n return null;\n }\n\n if (regex !== undefined) {\n return \"`--regex` can only be provided once.\";\n }\n regex = value;\n return null;\n };\n\n for (const token of tokens) {\n if (token === \"-h\" || token === \"--help\") {\n return { ok: true, help: true };\n }\n\n if (expects) {\n const error = consumeValue(expects, token);\n if (error) {\n return { ok: false, message: error };\n }\n expects = null;\n continue;\n }\n\n if (positionalMode) {\n textTokens.push(token);\n continue;\n }\n\n if (token === \"--\") {\n positionalMode = true;\n continue;\n }\n\n if (token === \"--recursive\") {\n recursive = true;\n sources.recursive = true;\n continue;\n }\n\n if (token === \"--no-recursive\") {\n recursive = false;\n sources.recursive = true;\n continue;\n }\n\n if (token === \"--pretty\") {\n pretty = true;\n continue;\n }\n\n if (\n token === \"--detector\" ||\n token === \"-d\" ||\n token === \"--content-gate\" ||\n token === \"--view\" ||\n token === \"--format\" ||\n token === \"-f\" ||\n token === \"--section\" ||\n token === \"--path-mode\" ||\n token === \"--path\" ||\n token === \"-p\" ||\n token === \"--include-ext\" ||\n token === \"--exclude-ext\" ||\n token === \"--regex\"\n ) {\n expects =\n token === \"-p\"\n ? \"path\"\n : token === \"-d\"\n ? \"detector\"\n : token === \"--content-gate\"\n ? \"contentGate\"\n : token === \"-f\"\n ? \"format\"\n : token === \"--path-mode\"\n ? \"pathMode\"\n : token === \"--include-ext\"\n ? \"includeExt\"\n : token === \"--exclude-ext\"\n ? \"excludeExt\"\n : (token.slice(2) as\n | \"detector\"\n | \"view\"\n | \"format\"\n | \"section\"\n | \"path\"\n | \"regex\");\n continue;\n }\n\n if (\n token.startsWith(\"--detector=\") ||\n token.startsWith(\"--content-gate=\") ||\n token.startsWith(\"--view=\") ||\n token.startsWith(\"--format=\") ||\n token.startsWith(\"--section=\") ||\n token.startsWith(\"--path-mode=\") ||\n token.startsWith(\"--path=\") ||\n token.startsWith(\"--include-ext=\") ||\n token.startsWith(\"--exclude-ext=\") ||\n token.startsWith(\"--regex=\")\n ) {\n const separatorIndex = token.indexOf(\"=\");\n const optionName = token.slice(2, separatorIndex);\n const value = token.slice(separatorIndex + 1);\n if (value.length === 0) {\n return {\n ok: false,\n message: `\\`--${optionName}\\` requires a value.`,\n };\n }\n\n const normalizedOption =\n optionName === \"path-mode\"\n ? \"pathMode\"\n : optionName === \"include-ext\"\n ? \"includeExt\"\n : optionName === \"exclude-ext\"\n ? \"excludeExt\"\n : (optionName as\n | \"detector\"\n | \"content-gate\"\n | \"view\"\n | \"format\"\n | \"section\"\n | \"path\"\n | \"regex\");\n const normalizedNamedOption =\n normalizedOption === \"content-gate\" ? \"contentGate\" : normalizedOption;\n\n const error = consumeValue(\n normalizedNamedOption as\n | \"detector\"\n | \"contentGate\"\n | \"view\"\n | \"format\"\n | \"section\"\n | \"path\"\n | \"regex\"\n | \"pathMode\"\n | \"includeExt\"\n | \"excludeExt\",\n value,\n );\n if (error) {\n return { ok: false, message: error };\n }\n continue;\n }\n\n if (token.startsWith(\"-\")) {\n return {\n ok: false,\n message: `\\`${token}\\` is not supported by \\`inspect\\`.`,\n };\n }\n\n textTokens.push(token);\n }\n\n if (expects) {\n const optionName =\n expects === \"pathMode\"\n ? \"path-mode\"\n : expects === \"contentGate\"\n ? \"content-gate\"\n : expects === \"includeExt\"\n ? \"include-ext\"\n : expects === \"excludeExt\"\n ? \"exclude-ext\"\n : expects;\n return {\n ok: false,\n message: `\\`--${optionName}\\` requires a value.`,\n };\n }\n\n if (paths.length > 0 && textTokens.length > 0) {\n return {\n ok: false,\n message: \"`inspect` accepts either positional text or --path inputs, not both.\",\n };\n }\n\n if (paths.length === 0 && textTokens.length === 0) {\n return {\n ok: false,\n message: \"No inspect input provided. Pass text or use --path.\",\n };\n }\n\n return {\n ok: true,\n detector,\n contentGateMode,\n view,\n format,\n pretty,\n section,\n pathMode,\n pathDetectBinary: true,\n recursive,\n includeExt,\n excludeExt,\n ...(regex !== undefined ? { regex } : {}),\n paths,\n textTokens,\n sources,\n };\n}\n","import { inspectTextWithDetector } from \"../../detector\";\nimport { buildInspectStandardLines, printLines } from \"./render\";\nimport type { InspectSingleInput, ParsedInspectInvocation } from \"./types\";\n\nexport async function runSingleInspect(\n validated: ParsedInspectInvocation,\n input: InspectSingleInput,\n): Promise<void> {\n const result = await inspectTextWithDetector(input.text, {\n detector: validated.detector,\n contentGate: {\n mode: validated.contentGateMode,\n },\n view: validated.view,\n input: {\n sourceType: input.sourceType,\n ...(input.path ? { path: input.path } : {}),\n },\n });\n\n if (validated.format === \"json\") {\n console.log(JSON.stringify(result, null, validated.pretty ? 2 : 0));\n process.exitCode = 0;\n return;\n }\n\n printLines(buildInspectStandardLines(result));\n process.exitCode = 0;\n}\n","import { applyConfigToInspectInvocation, resolveWordCounterConfig } from \"../config\";\nimport pc from \"picocolors\";\nimport { runInspectBatch } from \"./batch\";\nimport { printInspectHelp } from \"./help\";\nimport { loadInspectBatchInputs, loadSingleInspectInput, selectInspectText } from \"./input\";\nimport { validateInspectInvocation } from \"./parse\";\nimport { runSingleInspect } from \"./single\";\nimport type { ExecuteInspectCommandOptions } from \"./types\";\n\nexport function isExplicitInspectInvocation(argv: string[]): boolean {\n return argv[2] === \"inspect\";\n}\n\nfunction emitConfigNotes(notes: string[]): void {\n for (const note of notes) {\n const warningLine = note.startsWith(\"Warning:\") ? note : `Warning: ${note}`;\n console.error(pc.yellow(warningLine));\n }\n}\n\nexport async function executeInspectCommand({\n argv,\n runtime,\n}: ExecuteInspectCommandOptions): Promise<void> {\n const parsed = validateInspectInvocation(argv);\n if (!parsed.ok) {\n console.error(pc.red(`error: ${parsed.message}`));\n process.exitCode = 1;\n return;\n }\n\n if (parsed.help) {\n printInspectHelp();\n process.exitCode = 0;\n return;\n }\n\n let validated = parsed;\n\n try {\n const resolvedConfig = await resolveWordCounterConfig({\n env: runtime?.env,\n cwd: runtime?.cwd,\n });\n validated = applyConfigToInspectInvocation(validated, resolvedConfig.config);\n emitConfigNotes(resolvedConfig.notes);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(pc.red(`error: ${message}`));\n process.exitCode = 1;\n return;\n }\n\n if (validated.view === \"engine\" && validated.detector === \"regex\") {\n console.error(pc.red(\"error: `--view engine` requires `--detector wasm`.\"));\n process.exitCode = 1;\n return;\n }\n\n try {\n if (validated.paths.length === 0) {\n const input = await loadSingleInspectInput(\n undefined,\n validated.textTokens,\n validated.section,\n );\n await runSingleInspect(validated, input);\n return;\n }\n\n const loaded = await loadInspectBatchInputs(validated.paths, {\n pathMode: validated.pathMode,\n pathDetectBinary: validated.pathDetectBinary,\n recursive: validated.recursive,\n includeExt: validated.includeExt,\n excludeExt: validated.excludeExt,\n ...(validated.regex !== undefined ? { regex: validated.regex } : {}),\n });\n\n const directSinglePath =\n validated.paths.length === 1 &&\n loaded.files.length === 1 &&\n loaded.skipped.length === 0 &&\n loaded.failures.length === 0 &&\n loaded.files[0]?.source === \"direct\";\n\n if (directSinglePath) {\n const file = loaded.files[0];\n if (!file) {\n throw new Error(\"Missing inspect file input.\");\n }\n await runSingleInspect(validated, {\n text: selectInspectText(file.text, validated.section),\n sourceType: \"path\",\n path: file.path,\n });\n return;\n }\n\n await runInspectBatch(validated, loaded);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.error(pc.red(`error: ${message}`));\n process.exitCode = 1;\n }\n}\n","import { Command, Option } from \"commander\";\nimport type { SectionMode } from \"../../markdown\";\nimport { collectExtensionOption } from \"../path/filter\";\nimport { parseTotalOfOption } from \"../total-of\";\nimport type { PathMode } from \"../types\";\nimport type { OutputFormat } from \"../runtime/types\";\nimport type { DetectorContentGateMode, DetectorMode } from \"../../detector\";\nimport type { WordCounterMode } from \"../../wc\";\n\nconst MODE_CHOICES: WordCounterMode[] = [\n \"chunk\",\n \"segments\",\n \"collector\",\n \"char\",\n \"char-collector\",\n];\nconst DETECTOR_CHOICES: DetectorMode[] = [\"regex\", \"wasm\"];\nconst CONTENT_GATE_CHOICES: DetectorContentGateMode[] = [\"default\", \"strict\", \"loose\", \"off\"];\nconst FORMAT_CHOICES: OutputFormat[] = [\"standard\", \"raw\", \"json\"];\nconst SECTION_CHOICES: SectionMode[] = [\n \"all\",\n \"split\",\n \"frontmatter\",\n \"content\",\n \"per-key\",\n \"split-per-key\",\n];\nconst PATH_MODE_CHOICES: PathMode[] = [\"auto\", \"manual\"];\n\nfunction collectPathValue(value: string, previous: string[] = []): string[] {\n return [...previous, value];\n}\n\nfunction collectLatinHintValue(value: string, previous: string[] = []): string[] {\n return [...previous, value];\n}\n\nfunction parseJobsOption(value: string): number {\n if (!/^\\d+$/.test(value)) {\n throw new Error(\"`--jobs` must be an integer >= 1.\");\n }\n\n const parsed = Number.parseInt(value, 10);\n if (!Number.isSafeInteger(parsed) || parsed < 1) {\n throw new Error(\"`--jobs` must be an integer >= 1.\");\n }\n\n return parsed;\n}\n\nexport function configureProgramOptions(\n program: Command,\n parseMode: (value: string) => WordCounterMode,\n): void {\n program\n .addOption(\n new Option(\"-m, --mode <mode>\", \"breakdown mode\")\n .choices(MODE_CHOICES)\n .argParser(parseMode)\n .default(\"chunk\"),\n )\n .addOption(\n new Option(\"-f, --format <format>\", \"output format\")\n .choices(FORMAT_CHOICES)\n .default(\"standard\"),\n )\n .addOption(\n new Option(\"--section <section>\", \"document section mode\")\n .choices(SECTION_CHOICES)\n .default(\"all\"),\n )\n .addOption(\n new Option(\"-d, --detector <mode>\", \"locale detector mode\")\n .choices(DETECTOR_CHOICES)\n .default(\"regex\"),\n )\n .addOption(\n new Option(\n \"--content-gate <mode>\",\n \"detector content gate policy mode (default, strict, loose, off)\",\n ).choices(CONTENT_GATE_CHOICES),\n )\n .addOption(\n new Option(\n \"--path-mode <mode>\",\n \"path resolution mode: auto (default) expands directories; manual treats --path values as literal files\",\n )\n .choices(PATH_MODE_CHOICES)\n .default(\"auto\"),\n )\n .option(\"--latin-language <language>\", \"hint a language tag for Latin script text\")\n .option(\"--latin-tag <tag>\", \"hint a BCP 47 tag for Latin script text\")\n .option(\"--latin-locale <locale>\", \"legacy alias of --latin-language\")\n .option(\n \"--latin-hint <tag>=<pattern>\",\n \"add a custom Latin hint rule (repeatable)\",\n collectLatinHintValue,\n [],\n )\n .option(\"--latin-hints-file <path>\", \"load custom Latin hint rules from a JSON file\")\n .option(\"--no-default-latin-hints\", \"disable built-in Latin hint rules\")\n .option(\"--han-language <language>\", \"hint a language tag for Han script text\")\n .option(\"--han-tag <tag>\", \"hint a BCP 47 tag for Han script text\")\n .option(\"--non-words\", \"collect emoji, symbols, and punctuation (excludes whitespace)\")\n .option(\n \"--include-whitespace\",\n \"include whitespace counts (implies --non-words; same as --misc)\",\n )\n .option(\"--misc\", \"collect non-words plus whitespace (alias for --include-whitespace)\")\n .option(\n \"--total-of <parts>\",\n \"override total composition (comma-separated): words,emoji,symbols,punctuation,whitespace\",\n parseTotalOfOption,\n )\n .option(\"--pretty\", \"pretty print JSON output\", false)\n .option(\"--debug\", \"enable debug diagnostics on stderr\")\n .option(\"--verbose\", \"emit verbose per-file debug diagnostics (requires --debug)\")\n .option(\n \"--detector-evidence\",\n \"emit per-window detector evidence on the debug stream (requires --debug and --detector wasm)\",\n )\n .option(\"--debug-report [path]\", \"write debug diagnostics to a report file\")\n .option(\"--debug-report-tee\", \"mirror debug diagnostics to both report file and stderr\")\n .option(\"--debug-tee\", \"alias of --debug-report-tee\")\n .option(\"--merged\", \"show merged aggregate output (default)\")\n .option(\"--per-file\", \"show per-file output plus merged summary\")\n .option(\n \"--jobs <n>\",\n \"batch jobs in --path mode (1=async main-thread, >1=worker load+count)\",\n parseJobsOption,\n 1,\n )\n .option(\"--print-jobs-limit\", \"print host jobs-limit JSON and exit (must be used alone)\")\n .option(\"--progress\", \"enable batch progress indicator\")\n .option(\"--no-progress\", \"disable batch progress indicator\")\n .option(\"--keep-progress\", \"keep final batch progress line visible in standard mode\")\n .option(\"--recursive\", \"enable recursive directory traversal\")\n .option(\"--no-recursive\", \"disable recursive directory traversal\")\n .option(\"--quiet-warnings\", \"suppress non-fatal warning diagnostics\")\n .option(\"--quiet-skips\", \"suppress debug skip output and per-file json skipped field\")\n .option(\n \"--include-ext <exts>\",\n \"comma-separated extensions to include during directory scanning\",\n collectExtensionOption,\n [],\n )\n .option(\n \"--exclude-ext <exts>\",\n \"comma-separated extensions to exclude during directory scanning\",\n collectExtensionOption,\n [],\n )\n .option(\n \"--regex <pattern>\",\n \"regex filter for directory-scanned paths (applies to --path directories only)\",\n )\n .option(\n \"-p, --path <path>\",\n \"read input from file or directory (directories expand in auto mode by default)\",\n collectPathValue,\n [],\n )\n .argument(\"[text...]\", \"text to count\")\n .showHelpAfterError();\n}\n","import { readFileSync } from \"node:fs\";\nimport { dirname, join, resolve as resolvePath } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport pc from \"picocolors\";\nimport { EMBEDDED_PACKAGE_VERSION } from \"./version-embedded\";\n\nfunction* candidateSearchRoots(): Generator<string> {\n yield dirname(fileURLToPath(import.meta.url));\n\n const argvPath = process.argv[1];\n if (typeof argvPath === \"string\" && argvPath.length > 0) {\n yield dirname(resolvePath(argvPath));\n }\n\n yield process.cwd();\n}\n\nfunction* walkUpDirectories(start: string, maxLevels: number): Generator<string> {\n let current = start;\n for (let depth = 0; depth < maxLevels; depth += 1) {\n yield current;\n const parent = dirname(current);\n if (parent === current) {\n break;\n }\n current = parent;\n }\n}\n\nfunction resolveVersionFromPath(start: string, maxLevels: number): string | null {\n for (const directory of walkUpDirectories(start, maxLevels)) {\n try {\n const raw = readFileSync(join(directory, \"package.json\"), \"utf8\");\n const data = JSON.parse(raw) as { version?: string };\n if (data.version) {\n return data.version;\n }\n } catch {\n // Try parent directories.\n }\n }\n return null;\n}\n\nfunction normalizeVersion(value: string | null | undefined): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n const trimmed = value.trim();\n if (!trimmed) {\n return null;\n }\n\n return trimmed;\n}\n\ntype ResolvePackageVersionOptions = {\n embeddedVersion?: string | null;\n candidateRoots?: string[];\n maxLevels?: number;\n resolveFromPath?: (start: string, maxLevels: number) => string | null;\n};\n\nexport function resolvePackageVersion(options: ResolvePackageVersionOptions = {}): string {\n const embeddedVersion = normalizeVersion(options.embeddedVersion ?? EMBEDDED_PACKAGE_VERSION);\n if (embeddedVersion) {\n return embeddedVersion;\n }\n\n const maxLevels = options.maxLevels ?? 8;\n const resolveFromPath = options.resolveFromPath ?? resolveVersionFromPath;\n const roots = options.candidateRoots ?? [...candidateSearchRoots()];\n const seen = new Set<string>();\n for (const root of roots) {\n if (seen.has(root)) {\n continue;\n }\n seen.add(root);\n const version = normalizeVersion(resolveFromPath(root, maxLevels));\n if (version) {\n return version;\n }\n }\n\n return \"0.0.0\";\n}\n\nexport function getFormattedVersionLabel(): string {\n const version = resolvePackageVersion();\n\n return pc.bgBlack(pc.bold(pc.italic(` word-counter ${pc.cyanBright(`ver.${version}`)} `)));\n}\n","import type { SectionedResult } from \"../../markdown\";\nimport type { WordCounterResult } from \"../../wc\";\n\nfunction stripCollectorSegmentsFromWordCounterResult(result: WordCounterResult): void {\n if (result.breakdown.mode !== \"collector\") {\n return;\n }\n\n for (const item of result.breakdown.items) {\n item.segments = [];\n }\n}\n\nfunction stripCollectorSegmentsFromSectionedResult(result: SectionedResult): void {\n for (const item of result.items) {\n stripCollectorSegmentsFromWordCounterResult(item.result);\n }\n}\n\nexport function compactCollectorSegmentsInCountResult(\n result: WordCounterResult | SectionedResult,\n): void {\n if (\"section\" in result) {\n stripCollectorSegmentsFromSectionedResult(result);\n return;\n }\n\n stripCollectorSegmentsFromWordCounterResult(result);\n}\n","import { appendAll } from \"../../utils/append-all\";\nimport wordCounter, { type NonWordCollection, type WordCounterResult } from \"../../wc\";\nimport { createNonWordCollection, mergeNonWordCollections } from \"../../wc/non-words\";\n\nexport function mergeWordCounterResult(\n left: WordCounterResult,\n right: WordCounterResult,\n preserveCollectorSegments: boolean,\n): WordCounterResult {\n if (left.breakdown.mode !== right.breakdown.mode) {\n throw new Error(\"Cannot merge different breakdown modes.\");\n }\n\n const total = left.total + right.total;\n const counts =\n left.counts || right.counts\n ? {\n words: (left.counts?.words ?? 0) + (right.counts?.words ?? 0),\n nonWords: (left.counts?.nonWords ?? 0) + (right.counts?.nonWords ?? 0),\n total: (left.counts?.total ?? 0) + (right.counts?.total ?? 0),\n }\n : undefined;\n\n if (left.breakdown.mode === \"chunk\" && right.breakdown.mode === \"chunk\") {\n return {\n total,\n counts,\n breakdown: {\n mode: \"chunk\",\n items: [...left.breakdown.items, ...right.breakdown.items],\n },\n };\n }\n\n if (left.breakdown.mode === \"segments\" && right.breakdown.mode === \"segments\") {\n return {\n total,\n counts,\n breakdown: {\n mode: \"segments\",\n items: [...left.breakdown.items, ...right.breakdown.items],\n },\n };\n }\n\n if (left.breakdown.mode === \"char\" && right.breakdown.mode === \"char\") {\n return {\n total,\n counts,\n breakdown: {\n mode: \"char\",\n items: [...left.breakdown.items, ...right.breakdown.items],\n },\n };\n }\n\n if (left.breakdown.mode === \"char-collector\" && right.breakdown.mode === \"char-collector\") {\n const localeOrder: string[] = [];\n const mergedByLocale = new Map<\n string,\n {\n locale: string;\n chars: number;\n nonWords?: NonWordCollection;\n }\n >();\n\n const addItems = (items: typeof left.breakdown.items): void => {\n for (const item of items) {\n const existing = mergedByLocale.get(item.locale);\n if (existing) {\n existing.chars += item.chars;\n if (item.nonWords) {\n if (!existing.nonWords) {\n existing.nonWords = createNonWordCollection();\n }\n mergeNonWordCollections(existing.nonWords, item.nonWords);\n }\n continue;\n }\n\n localeOrder.push(item.locale);\n mergedByLocale.set(item.locale, {\n locale: item.locale,\n chars: item.chars,\n nonWords: item.nonWords\n ? mergeNonWordCollections(createNonWordCollection(), item.nonWords)\n : undefined,\n });\n }\n };\n\n addItems(left.breakdown.items);\n addItems(right.breakdown.items);\n\n return {\n total,\n counts,\n breakdown: {\n mode: \"char-collector\",\n items: localeOrder.map((locale) => {\n const value = mergedByLocale.get(locale);\n if (!value) {\n throw new Error(`Missing char-collector entry for locale: ${locale}`);\n }\n return value;\n }),\n },\n };\n }\n\n if (left.breakdown.mode === \"collector\" && right.breakdown.mode === \"collector\") {\n const localeOrder: string[] = [];\n const mergedByLocale = new Map<\n string,\n {\n locale: string;\n words: number;\n segments: string[];\n }\n >();\n\n const addItems = (items: typeof left.breakdown.items): void => {\n for (const item of items) {\n const existing = mergedByLocale.get(item.locale);\n if (existing) {\n existing.words += item.words;\n if (preserveCollectorSegments) {\n appendAll(existing.segments, item.segments);\n }\n continue;\n }\n\n localeOrder.push(item.locale);\n mergedByLocale.set(item.locale, {\n locale: item.locale,\n words: item.words,\n segments: preserveCollectorSegments ? [...item.segments] : [],\n });\n }\n };\n\n addItems(left.breakdown.items);\n addItems(right.breakdown.items);\n\n let mergedNonWords: NonWordCollection | undefined;\n if (left.breakdown.nonWords || right.breakdown.nonWords) {\n mergedNonWords = createNonWordCollection();\n if (left.breakdown.nonWords) {\n mergeNonWordCollections(mergedNonWords, left.breakdown.nonWords);\n }\n if (right.breakdown.nonWords) {\n mergeNonWordCollections(mergedNonWords, right.breakdown.nonWords);\n }\n }\n\n return {\n total,\n counts,\n breakdown: {\n mode: \"collector\",\n items: localeOrder.map((locale) => {\n const value = mergedByLocale.get(locale);\n if (!value) {\n throw new Error(`Missing collector entry for locale: ${locale}`);\n }\n return value;\n }),\n nonWords: mergedNonWords,\n },\n };\n }\n\n return {\n total,\n counts,\n breakdown: left.breakdown,\n };\n}\n\nexport function aggregateWordCounterResults(\n results: WordCounterResult[],\n preserveCollectorSegments: boolean,\n): WordCounterResult {\n if (results.length === 0) {\n return wordCounter(\"\", { mode: \"chunk\" });\n }\n\n const first = results[0];\n if (!first) {\n return wordCounter(\"\", { mode: \"chunk\" });\n }\n\n let aggregate = first;\n for (let index = 1; index < results.length; index += 1) {\n const current = results[index];\n if (!current) {\n continue;\n }\n aggregate = mergeWordCounterResult(aggregate, current, preserveCollectorSegments);\n }\n\n return aggregate;\n}\n","import type { SectionedResult } from \"../../markdown\";\nimport { aggregateWordCounterResults } from \"./aggregate-word-counter\";\n\nfunction buildSectionKey(name: string, source: \"frontmatter\" | \"content\"): string {\n return `${source}:${name}`;\n}\n\nexport function aggregateSectionedResults(\n results: SectionedResult[],\n preserveCollectorSegments: boolean,\n): SectionedResult {\n if (results.length === 0) {\n return {\n section: \"all\",\n total: 0,\n frontmatterType: null,\n items: [],\n };\n }\n\n const section = results[0]?.section ?? \"all\";\n const grouped = new Map<\n string,\n {\n name: string;\n source: \"frontmatter\" | \"content\";\n items: ReturnType<typeof aggregateWordCounterResults>[];\n }\n >();\n let total = 0;\n let frontmatterType = results[0]?.frontmatterType ?? null;\n\n for (const result of results) {\n total += result.total;\n\n if (result.section !== section) {\n throw new Error(\"Cannot aggregate section results with different section modes.\");\n }\n\n if (frontmatterType !== result.frontmatterType) {\n frontmatterType = null;\n }\n\n for (const item of result.items) {\n const key = buildSectionKey(item.name, item.source);\n const existing = grouped.get(key);\n if (!existing) {\n grouped.set(key, {\n name: item.name,\n source: item.source,\n items: [item.result],\n });\n continue;\n }\n\n existing.items.push(item.result);\n }\n }\n\n const sourceOrder = new Map<\"frontmatter\" | \"content\", number>([\n [\"frontmatter\", 0],\n [\"content\", 1],\n ]);\n\n const items = [...grouped.values()]\n .sort((left, right) => {\n const sourceDiff = (sourceOrder.get(left.source) ?? 0) - (sourceOrder.get(right.source) ?? 0);\n if (sourceDiff !== 0) {\n return sourceDiff;\n }\n return left.name.localeCompare(right.name);\n })\n .map((entry) => ({\n name: entry.name,\n source: entry.source,\n result: aggregateWordCounterResults(entry.items, preserveCollectorSegments),\n }));\n\n return {\n section,\n total,\n frontmatterType,\n items,\n };\n}\n","import { countSections } from \"../../markdown\";\nimport type { SectionMode, SectionedResult } from \"../../markdown\";\nimport wordCounter, { type WordCounterResult } from \"../../wc\";\nimport type { BatchFileInput, BatchFileResult, BatchSummary } from \"../types\";\nimport type { BatchProgressSnapshot } from \"../progress/reporter\";\nimport { compactCollectorSegmentsInCountResult } from \"./aggregate-compact\";\nimport { aggregateSectionedResults } from \"./aggregate-sections\";\nimport { aggregateWordCounterResults } from \"./aggregate-word-counter\";\n\ntype BuildBatchSummaryOptions = {\n onFileCounted?: (snapshot: BatchProgressSnapshot) => void;\n onFinalizeStart?: () => void;\n preserveCollectorSegments?: boolean;\n};\n\ntype FinalizeBatchSummaryFromFileResultsOptions = {\n onFinalizeStart?: () => void;\n preserveCollectorSegments?: boolean;\n};\n\nexport { compactCollectorSegmentsInCountResult } from \"./aggregate-compact\";\n\nexport async function buildBatchSummary(\n inputs: BatchFileInput[],\n section: SectionMode,\n wcOptions: Parameters<typeof wordCounter>[1],\n options: BuildBatchSummaryOptions = {},\n): Promise<BatchSummary> {\n const preserveCollectorSegments = options.preserveCollectorSegments ?? true;\n const files: BatchFileResult[] = [];\n\n for (const input of inputs) {\n const result =\n section === \"all\"\n ? wordCounter(input.content, wcOptions)\n : countSections(input.content, section, wcOptions);\n\n if (!preserveCollectorSegments) {\n compactCollectorSegmentsInCountResult(result);\n }\n\n files.push({\n path: input.path,\n result,\n });\n\n options.onFileCounted?.({\n completed: files.length,\n total: inputs.length,\n });\n }\n\n return finalizeBatchSummaryFromFileResults(files, section, wcOptions, {\n onFinalizeStart: options.onFinalizeStart,\n preserveCollectorSegments: options.preserveCollectorSegments,\n });\n}\n\nexport function finalizeBatchSummaryFromFileResults(\n files: BatchFileResult[],\n section: SectionMode,\n wcOptions: Parameters<typeof wordCounter>[1],\n options: FinalizeBatchSummaryFromFileResultsOptions = {},\n): BatchSummary {\n const preserveCollectorSegments = options.preserveCollectorSegments ?? true;\n if (!preserveCollectorSegments) {\n for (const file of files) {\n compactCollectorSegmentsInCountResult(file.result);\n }\n }\n\n options.onFinalizeStart?.();\n if (files.length === 0) {\n return {\n files,\n skipped: [],\n aggregate:\n section === \"all\"\n ? wordCounter(\"\", wcOptions)\n : {\n section,\n total: 0,\n frontmatterType: null,\n items: [],\n },\n };\n }\n\n const aggregate =\n section === \"all\"\n ? aggregateWordCounterResults(\n files.map((file) => file.result as WordCounterResult),\n preserveCollectorSegments,\n )\n : aggregateSectionedResults(\n files.map((file) => file.result as SectionedResult),\n preserveCollectorSegments,\n );\n\n return {\n files,\n skipped: [],\n aggregate,\n };\n}\n","export async function runBoundedQueue<T>(\n total: number,\n requestedJobs: number,\n worker: (index: number) => Promise<T>,\n): Promise<T[]> {\n if (total === 0) {\n return [];\n }\n\n const safeRequestedJobs = Number.isFinite(requestedJobs) ? Math.floor(requestedJobs) : 1;\n const concurrency = Math.max(1, Math.min(total, safeRequestedJobs));\n const results: Array<T | undefined> = Array.from({ length: total });\n let nextIndex = 0;\n\n const runWorker = async (): Promise<void> => {\n while (true) {\n const current = nextIndex;\n nextIndex += 1;\n if (current >= total) {\n return;\n }\n\n results[current] = await worker(current);\n }\n };\n\n await Promise.all(Array.from({ length: concurrency }, () => runWorker()));\n if (results.some((result) => result === undefined)) {\n throw new Error(\"Bounded queue completed with missing results.\");\n }\n return results as T[];\n}\n","import { readFile } from \"node:fs/promises\";\nimport { isProbablyBinary } from \"../../path/load\";\nimport { createResourceLimitError, isResourceLimitError } from \"./limits\";\nimport type { BatchJobsLimit } from \"./types\";\n\nexport type ReadBatchInputResult =\n | {\n type: \"file\";\n path: string;\n content: string;\n }\n | {\n type: \"skip\";\n path: string;\n reason: string;\n };\n\ntype ReadBatchInputOptions = {\n requestedJobs: number;\n limits: BatchJobsLimit;\n detectBinary: boolean;\n};\n\nexport async function readBatchInput(\n path: string | undefined,\n options: ReadBatchInputOptions,\n): Promise<ReadBatchInputResult> {\n if (!path) {\n return {\n type: \"skip\",\n path: \"\",\n reason: \"not readable: missing path\",\n };\n }\n\n let buffer: Buffer;\n try {\n buffer = await readFile(path);\n } catch (error) {\n if (isResourceLimitError(error)) {\n throw createResourceLimitError(path, error, options.requestedJobs, options.limits);\n }\n\n const message = error instanceof Error ? error.message : String(error);\n return {\n type: \"skip\",\n path,\n reason: `not readable: ${message}`,\n };\n }\n\n if (options.detectBinary && isProbablyBinary(buffer)) {\n return {\n type: \"skip\",\n path,\n reason: \"binary file\",\n };\n }\n\n return {\n type: \"file\",\n path,\n content: buffer.toString(\"utf8\"),\n };\n}\n","import { countSections } from \"../../../markdown\";\nimport { countSectionsWithDetector, wordCounterWithDetector } from \"../../../detector\";\nimport wordCounter from \"../../../wc\";\nimport { compactCollectorSegmentsInCountResult } from \"../aggregate\";\nimport { resolveBatchJobsLimit } from \"./limits\";\nimport { runBoundedQueue } from \"./queue\";\nimport { readBatchInput } from \"./read-input\";\nimport type { CountBatchWithJobsOptions, CountBatchWithJobsResult } from \"./types\";\n\ntype CountBatchEntry =\n | {\n type: \"file\";\n file: CountBatchWithJobsResult[\"files\"][number];\n }\n | {\n type: \"skip\";\n skip: CountBatchWithJobsResult[\"skipped\"][number];\n };\n\nexport async function countBatchInputsWithJobs(\n filePaths: string[],\n options: CountBatchWithJobsOptions,\n): Promise<CountBatchWithJobsResult> {\n const detectorMode = options.detectorMode ?? \"regex\";\n const limits = resolveBatchJobsLimit();\n const total = filePaths.length;\n let completed = 0;\n\n const entries = await runBoundedQueue(filePaths.length, options.jobs, async (index) => {\n const loaded = await readBatchInput(filePaths[index], {\n requestedJobs: options.jobs,\n limits,\n detectBinary: options.detectBinary ?? true,\n });\n if (loaded.type === \"skip\") {\n completed += 1;\n options.onFileProcessed?.({ completed, total });\n return {\n type: \"skip\",\n skip: { path: loaded.path, reason: loaded.reason },\n } satisfies CountBatchEntry;\n }\n\n const detectorDebug =\n detectorMode === \"wasm\"\n ? options.createDetectorDebugContext?.({ path: loaded.path })\n : undefined;\n const result =\n detectorMode === \"regex\"\n ? options.section === \"all\"\n ? wordCounter(loaded.content, options.wcOptions)\n : countSections(loaded.content, options.section, options.wcOptions)\n : options.section === \"all\"\n ? await wordCounterWithDetector(loaded.content, {\n ...options.wcOptions,\n detector: detectorMode,\n detectorDebug,\n })\n : await countSectionsWithDetector(loaded.content, options.section, {\n ...options.wcOptions,\n detector: detectorMode,\n detectorDebug,\n });\n\n if (!options.preserveCollectorSegments) {\n compactCollectorSegmentsInCountResult(result);\n }\n\n completed += 1;\n options.onFileProcessed?.({ completed, total });\n return {\n type: \"file\",\n file: {\n path: loaded.path,\n result,\n ...(detectorDebug?.summary ? { debug: { detector: detectorDebug.summary } } : {}),\n },\n } satisfies CountBatchEntry;\n });\n\n const files: CountBatchWithJobsResult[\"files\"] = [];\n const skipped: CountBatchWithJobsResult[\"skipped\"] = [];\n for (const entry of entries) {\n if (entry.type === \"file\") {\n files.push(entry.file);\n continue;\n }\n skipped.push(entry.skip);\n }\n\n return { files, skipped };\n}\n","import type { SectionMode } from \"../../../markdown\";\nimport type wordCounter from \"../../../wc\";\nimport { finalizeBatchSummaryFromFileResults } from \"../aggregate\";\nimport type { BatchFileResult, BatchSummary } from \"../../types\";\n\ntype FinalizeBatchJobsSummaryOptions = {\n onFinalizeStart?: () => void;\n preserveCollectorSegments?: boolean;\n};\n\nexport function finalizeBatchJobsSummary(\n files: BatchFileResult[],\n section: SectionMode,\n wcOptions: Parameters<typeof wordCounter>[1],\n options: FinalizeBatchJobsSummaryOptions = {},\n): BatchSummary {\n return finalizeBatchSummaryFromFileResults(files, section, wcOptions, {\n onFinalizeStart: options.onFinalizeStart,\n preserveCollectorSegments: options.preserveCollectorSegments,\n });\n}\n","export type ProgressOutputStream = {\n isTTY?: boolean;\n write: (chunk: string) => unknown;\n};\n\nexport type BatchProgressSnapshot = {\n completed: number;\n total: number;\n};\n\nexport type BatchProgressReporter = {\n enabled: boolean;\n start: (total: number, startedAtMs?: number) => void;\n advance: (snapshot: BatchProgressSnapshot) => void;\n startFinalizing: () => void;\n finish: () => void;\n};\n\ntype BatchProgressReporterOptions = {\n enabled: boolean;\n stream: ProgressOutputStream;\n clearOnFinish?: boolean;\n};\n\nconst PROGRESS_BAR_WIDTH = 20;\nconst FILLED_BAR_CHAR = \"█\";\nconst EMPTY_BAR_CHAR = \"░\";\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction buildProgressBar(completed: number, total: number): string {\n const safeTotal = Math.max(total, 1);\n const ratio = clamp(completed / safeTotal, 0, 1);\n const filled =\n completed >= safeTotal ? PROGRESS_BAR_WIDTH : Math.floor(ratio * PROGRESS_BAR_WIDTH);\n const empty = PROGRESS_BAR_WIDTH - filled;\n return `${FILLED_BAR_CHAR.repeat(filled)}${EMPTY_BAR_CHAR.repeat(empty)}`;\n}\n\nfunction formatElapsed(startedAtMs: number): string {\n const elapsedMs = Date.now() - startedAtMs;\n const totalSeconds = Math.max(0, Math.floor(elapsedMs / 1000));\n const minutes = Math.floor(totalSeconds / 60);\n const seconds = totalSeconds % 60;\n const tenths = Math.floor((Math.max(0, elapsedMs) % 1000) / 100);\n return `${String(minutes).padStart(2, \"0\")}:${String(seconds).padStart(2, \"0\")}.${tenths}`;\n}\n\nfunction buildProgressLine(completed: number, total: number, startedAtMs: number): string {\n const safeTotal = Math.max(total, 1);\n const percent = completed >= safeTotal ? 100 : Math.floor((completed / safeTotal) * 100);\n const bar = buildProgressBar(completed, safeTotal);\n const percentText = `${String(percent).padStart(3, \" \")}%`;\n const completedText = String(completed).padStart(String(safeTotal).length, \" \");\n const elapsed = formatElapsed(startedAtMs);\n return `Counting files [${bar}] ${percentText} ${completedText}/${safeTotal} elapsed ${elapsed}`;\n}\n\nfunction buildFinalizingLine(startedAtMs: number): string {\n const elapsed = formatElapsed(startedAtMs);\n return `Finalizing aggregate... elapsed ${elapsed}`;\n}\n\nexport function createBatchProgressReporter(\n options: BatchProgressReporterOptions,\n): BatchProgressReporter {\n const enabled = options.enabled;\n const isTTY = Boolean(options.stream.isTTY);\n const clearOnFinish = options.clearOnFinish ?? true;\n let active = false;\n let total = 0;\n let lastLineLength = 0;\n let startedAtMs = 0;\n let lastRenderedPercent = -1;\n let finalizingStarted = false;\n\n const writeTTYLine = (line: string): void => {\n const trailingPadding =\n lastLineLength > line.length ? \" \".repeat(lastLineLength - line.length) : \"\";\n options.stream.write(`\\r${line}${trailingPadding}`);\n lastLineLength = line.length;\n };\n\n const render = (completed: number): void => {\n const line = buildProgressLine(completed, total, startedAtMs);\n const safeTotal = Math.max(total, 1);\n const percent = completed >= safeTotal ? 100 : Math.floor((completed / safeTotal) * 100);\n if (!isTTY && percent === lastRenderedPercent && completed < safeTotal) {\n return;\n }\n\n lastRenderedPercent = percent;\n\n if (isTTY) {\n writeTTYLine(line);\n return;\n }\n\n lastLineLength = line.length;\n options.stream.write(`${line}\\n`);\n };\n\n const clearLine = (): void => {\n if (lastLineLength === 0) {\n return;\n }\n options.stream.write(`\\r${\" \".repeat(lastLineLength)}\\r`);\n lastLineLength = 0;\n };\n\n return {\n enabled,\n start(nextTotal, nextStartedAtMs) {\n if (!enabled || nextTotal <= 1) {\n return;\n }\n\n total = nextTotal;\n active = true;\n startedAtMs = nextStartedAtMs ?? Date.now();\n lastRenderedPercent = -1;\n finalizingStarted = false;\n render(0);\n },\n advance(snapshot) {\n if (!active) {\n return;\n }\n\n render(snapshot.completed);\n },\n startFinalizing() {\n if (!active || finalizingStarted) {\n return;\n }\n\n finalizingStarted = true;\n const line = buildFinalizingLine(startedAtMs);\n if (isTTY) {\n if (!clearOnFinish) {\n options.stream.write(`\\n${line}`);\n lastLineLength = line.length;\n return;\n }\n writeTTYLine(line);\n return;\n }\n\n lastLineLength = line.length;\n options.stream.write(`${line}\\n`);\n },\n finish() {\n if (!active) {\n return;\n }\n\n if (isTTY) {\n if (clearOnFinish) {\n clearLine();\n } else {\n options.stream.write(\"\\n\");\n }\n }\n active = false;\n },\n };\n}\n","import type { SectionMode } from \"../../markdown\";\nimport type { DetectorWordCounterOptions } from \"../../detector\";\nimport { createDetectorDebugSummary } from \"../../detector/debug\";\nimport { appendAll } from \"../../utils/append-all\";\nimport type { DebugChannel, DebugEventOptions } from \"../debug/channel\";\nimport { countBatchInputsWithJobs } from \"./jobs/load-count\";\nimport {\n WorkerRouteUnavailableError,\n countBatchInputsWithWorkerJobs,\n} from \"./jobs/load-count-worker\";\nimport { finalizeBatchJobsSummary } from \"./jobs/render\";\nimport type { BatchJobsStrategy } from \"./jobs/types\";\nimport { type DirectoryExtensionFilter } from \"../path/filter\";\nimport { resolveBatchFilePaths } from \"../path/resolve\";\nimport { type BatchProgressReporter } from \"../progress/reporter\";\nimport type { BatchOptions, BatchSummary } from \"../types\";\n\ntype RunBatchCountOptions = {\n pathInputs: string[];\n batchOptions: BatchOptions;\n extensionFilter: DirectoryExtensionFilter;\n detectBinary: boolean;\n section: SectionMode;\n wcOptions: DetectorWordCounterOptions;\n preserveCollectorSegments: boolean;\n detectorEvidence: boolean;\n debug: DebugChannel;\n progressReporter: BatchProgressReporter;\n jobs: number;\n jobsStrategy: BatchJobsStrategy;\n emitWarning?: (message: string) => void;\n};\n\nexport async function runBatchCount(options: RunBatchCountOptions): Promise<BatchSummary> {\n const detectorEvidence = options.detectorEvidence\n ? {\n verbosity: options.debug.verbosity,\n mode: options.wcOptions.mode ?? \"chunk\",\n section: options.section,\n }\n : undefined;\n const createFileDetectorDebugContext = ({ path }: { path: string }) =>\n options.debug.enabled && options.wcOptions.detector === \"wasm\"\n ? {\n emit: (\n event: string,\n details?: Record<string, unknown>,\n eventOptions?: DebugEventOptions,\n ) =>\n options.debug.emit(\n event,\n {\n path,\n ...details,\n },\n {\n ...eventOptions,\n scope: \"file\",\n },\n ),\n summary: createDetectorDebugSummary(\"wasm\"),\n ...(detectorEvidence ? { evidence: detectorEvidence } : {}),\n }\n : undefined;\n const emitWorkerDetectorDebugEvent = options.debug.enabled\n ? (event: string, details?: Record<string, unknown>, eventOptions?: DebugEventOptions) => {\n options.debug.emit(event, details, {\n ...eventOptions,\n scope: \"file\",\n });\n }\n : undefined;\n const batchStartedAtMs = Date.now();\n const resolveStartedAtMs = Date.now();\n\n options.debug.emit(\"batch.resolve.start\", {\n inputs: options.pathInputs.length,\n pathMode: options.batchOptions.pathMode,\n recursive: options.batchOptions.recursive,\n });\n\n const resolved = await resolveBatchFilePaths(options.pathInputs, {\n pathMode: options.batchOptions.pathMode,\n recursive: options.batchOptions.recursive,\n extensionFilter: options.extensionFilter,\n directoryRegexPattern: options.batchOptions.directoryRegexPattern,\n debug: options.debug,\n });\n const resolveElapsedMs = Date.now() - resolveStartedAtMs;\n options.debug.emit(\"batch.resolve.complete\", {\n files: resolved.files.length,\n skipped: resolved.skipped.length,\n elapsedMs: resolveElapsedMs,\n });\n options.debug.emit(\"batch.stage.timing\", {\n stage: \"resolve\",\n elapsedMs: resolveElapsedMs,\n });\n\n options.debug.emit(\"batch.jobs.strategy\", {\n strategy: options.jobsStrategy,\n jobs: options.jobs,\n });\n\n let summary: BatchSummary;\n let routeSkips: BatchSummary[\"skipped\"] = [];\n options.debug.emit(\"batch.load.start\", {\n files: resolved.files.length,\n jobs: options.jobs,\n strategy: options.jobsStrategy,\n });\n options.debug.emit(\"batch.load.complete\", {\n files: 0,\n skipped: 0,\n elapsedMs: 0,\n strategy: options.jobsStrategy,\n });\n options.debug.emit(\"batch.stage.timing\", {\n stage: \"load\",\n elapsedMs: 0,\n });\n\n const progressEnabled = options.progressReporter.enabled && resolved.files.length > 1;\n options.debug.emit(\"batch.progress.start\", {\n enabled: progressEnabled,\n total: resolved.files.length,\n });\n\n if (progressEnabled) {\n options.progressReporter.start(resolved.files.length, batchStartedAtMs);\n }\n\n const countStartedAtMs = Date.now();\n let finalizeStartedAtMs: number | null = null;\n let emittedCountTiming = false;\n try {\n let counted: Awaited<ReturnType<typeof countBatchInputsWithJobs>>;\n if (options.jobs > 1) {\n try {\n counted = await countBatchInputsWithWorkerJobs(resolved.files, {\n jobs: options.jobs,\n section: options.section,\n detectorMode: options.wcOptions.detector ?? \"regex\",\n wcOptions: options.wcOptions,\n detectBinary: options.detectBinary,\n preserveCollectorSegments: options.preserveCollectorSegments,\n detectorEvidence: options.detectorEvidence,\n debugVerbosity: options.debug.verbosity,\n onDetectorDebugEvent: emitWorkerDetectorDebugEvent,\n onFileProcessed: (snapshot) => {\n if (progressEnabled) {\n options.progressReporter.advance(snapshot);\n }\n },\n });\n options.debug.emit(\"batch.jobs.executor\", {\n strategy: options.jobsStrategy,\n executor: \"worker-pool\",\n jobs: options.jobs,\n });\n } catch (error) {\n if (!(error instanceof WorkerRouteUnavailableError)) {\n throw error;\n }\n\n options.emitWarning?.(\n `Worker executor unavailable; falling back to async load+count. (${error.message})`,\n );\n options.debug.emit(\"batch.jobs.executor\", {\n strategy: options.jobsStrategy,\n executor: \"async-fallback\",\n reason: error.message,\n jobs: options.jobs,\n });\n counted = await countBatchInputsWithJobs(resolved.files, {\n jobs: options.jobs,\n section: options.section,\n detectorMode: options.wcOptions.detector ?? \"regex\",\n wcOptions: options.wcOptions,\n detectBinary: options.detectBinary,\n preserveCollectorSegments: options.preserveCollectorSegments,\n detectorEvidence: options.detectorEvidence,\n debugVerbosity: options.debug.verbosity,\n createDetectorDebugContext: createFileDetectorDebugContext,\n onFileProcessed: (snapshot) => {\n if (progressEnabled) {\n options.progressReporter.advance(snapshot);\n }\n },\n });\n }\n } else {\n counted = await countBatchInputsWithJobs(resolved.files, {\n jobs: options.jobs,\n section: options.section,\n detectorMode: options.wcOptions.detector ?? \"regex\",\n wcOptions: options.wcOptions,\n detectBinary: options.detectBinary,\n preserveCollectorSegments: options.preserveCollectorSegments,\n detectorEvidence: options.detectorEvidence,\n debugVerbosity: options.debug.verbosity,\n createDetectorDebugContext: createFileDetectorDebugContext,\n onFileProcessed: (snapshot) => {\n if (progressEnabled) {\n options.progressReporter.advance(snapshot);\n }\n },\n });\n options.debug.emit(\"batch.jobs.executor\", {\n strategy: options.jobsStrategy,\n executor: \"async-main\",\n jobs: options.jobs,\n });\n }\n\n routeSkips = counted.skipped;\n summary = finalizeBatchJobsSummary(counted.files, options.section, options.wcOptions, {\n onFinalizeStart: () => {\n finalizeStartedAtMs = Date.now();\n if (progressEnabled) {\n options.progressReporter.startFinalizing();\n }\n\n const countElapsedMs = finalizeStartedAtMs - countStartedAtMs;\n options.debug.emit(\"batch.stage.timing\", {\n stage: \"count\",\n elapsedMs: countElapsedMs,\n });\n emittedCountTiming = true;\n },\n preserveCollectorSegments: options.preserveCollectorSegments,\n });\n } finally {\n if (progressEnabled) {\n options.progressReporter.finish();\n }\n options.debug.emit(\"batch.progress.complete\", {\n enabled: progressEnabled,\n total: resolved.files.length,\n });\n }\n\n if (!emittedCountTiming) {\n const countElapsedMs = Date.now() - countStartedAtMs;\n options.debug.emit(\"batch.stage.timing\", {\n stage: \"count\",\n elapsedMs: countElapsedMs,\n });\n }\n\n const finalizeElapsedMs = finalizeStartedAtMs === null ? 0 : Date.now() - finalizeStartedAtMs;\n options.debug.emit(\"batch.stage.timing\", {\n stage: \"finalize\",\n elapsedMs: finalizeElapsedMs,\n });\n\n appendAll(summary.skipped, resolved.skipped);\n appendAll(summary.skipped, routeSkips);\n options.debug.emit(\"batch.aggregate.complete\", {\n files: summary.files.length,\n skipped: summary.skipped.length,\n total: summary.aggregate.total,\n });\n\n return summary;\n}\n","import type { BatchJobsStrategy } from \"./types\";\n\nexport function resolveBatchJobsStrategy(_jobs: number): BatchJobsStrategy {\n return \"load-count\";\n}\n","import type { DetectorDebugSummary } from \"../../detector/debug\";\nimport type { BatchSkip } from \"../types\";\n\ntype DebugSection = {\n skipped?: BatchSkip[];\n detector?: DetectorDebugSummary;\n};\n\nexport function buildDebugSection(input: DebugSection): DebugSection | undefined {\n const output: DebugSection = {};\n\n if (input.skipped && input.skipped.length > 0) {\n output.skipped = input.skipped;\n }\n\n if (input.detector) {\n output.detector = input.detector;\n }\n\n return Object.keys(output).length > 0 ? output : undefined;\n}\n","export function showSingularOrPluralWord(count: number, word: string): string {\n return `${count} ${word}${count === 1 ? \"\" : \"s\"}`;\n}\n","import { relative as relativePath } from \"node:path\";\nimport type { SectionMode, SectionedResult } from \"../../markdown\";\nimport { showSingularOrPluralWord } from \"../../utils\";\nimport type { NonWordCollection, WordCounterMode, WordCounterResult } from \"../../wc\";\nimport { formatTotalOfParts, type TotalOfOverride } from \"../total-of\";\nimport type { BatchSkip, BatchSummary } from \"../types\";\nimport pc from \"picocolors\";\n\ntype CountUnit = \"word\" | \"character\";\n\ntype CountBreakdownItem = {\n locale: string;\n count: number;\n nonWords?: NonWordCollection;\n};\n\nexport type TotalLabels = {\n overall: string;\n section: string;\n};\n\nfunction getCountUnit(mode: WordCounterMode): CountUnit {\n return mode === \"char\" || mode === \"char-collector\" ? \"character\" : \"word\";\n}\n\nexport function getTotalLabels(mode: WordCounterMode, includeNonWords: boolean): TotalLabels {\n const unit = mode === \"char\" || mode === \"char-collector\" ? \"characters\" : \"words\";\n if (includeNonWords) {\n return { overall: \"Total count\", section: \"total count\" };\n }\n return { overall: `Total ${unit}`, section: `total ${unit}` };\n}\n\nfunction hasNonWords(nonWords: NonWordCollection): boolean {\n const whitespaceCount = nonWords.counts.whitespace ?? 0;\n return (\n nonWords.counts.emoji > 0 ||\n nonWords.counts.symbols > 0 ||\n nonWords.counts.punctuation > 0 ||\n whitespaceCount > 0\n );\n}\n\nfunction renderNonWords(nonWords: NonWordCollection | undefined, verbose: boolean): void {\n if (!nonWords || !hasNonWords(nonWords)) {\n return;\n }\n\n if (verbose) {\n const whitespace = nonWords.whitespace\n ? ` whitespace=${JSON.stringify(nonWords.whitespace)}`\n : \"\";\n console.log(\n pc.yellow(\n `Non-words: emoji=${JSON.stringify(nonWords.emoji)} symbols=${JSON.stringify(\n nonWords.symbols,\n )} punctuation=${JSON.stringify(nonWords.punctuation)}${whitespace}`,\n ),\n );\n return;\n }\n\n const whitespaceCount = nonWords.counts.whitespace ?? 0;\n const whitespaceLabel = whitespaceCount > 0 ? `, whitespace ${whitespaceCount}` : \"\";\n console.log(\n pc.yellow(\n `Non-words: emoji ${nonWords.counts.emoji}, symbols ${nonWords.counts.symbols}, punctuation ${nonWords.counts.punctuation}${whitespaceLabel}`,\n ),\n );\n}\n\nfunction renderCountBreakdown(items: CountBreakdownItem[], unit: CountUnit): void {\n for (const item of items) {\n console.log(`Locale ${item.locale}: ${showSingularOrPluralWord(item.count, unit)}`);\n renderNonWords(item.nonWords, false);\n }\n}\n\nfunction renderSegmentBreakdown(\n items: Array<{ locale: string; words: number; segments: string[]; nonWords?: NonWordCollection }>,\n): void {\n for (const item of items) {\n console.log(\n `Locale ${item.locale}: ${JSON.stringify(item.segments)} (${showSingularOrPluralWord(item.words, \"word\")})`,\n );\n renderNonWords(item.nonWords, true);\n }\n}\n\nfunction renderCollectorBreakdown(items: Array<{ locale: string; words: number }>): void {\n for (const item of items) {\n console.log(`Locale ${item.locale}: ${showSingularOrPluralWord(item.words, \"word\")}`);\n }\n}\n\nfunction renderTotalOfOverride(baseTotal: number, override: TotalOfOverride | undefined): void {\n if (!override || override.total === baseTotal) {\n return;\n }\n\n console.log(`Total-of (override: ${formatTotalOfParts(override.parts)}): ${override.total}`);\n}\n\nexport function renderStandardResult(\n result: WordCounterResult,\n totalLabel: string,\n totalOfOverride?: TotalOfOverride,\n): void {\n console.log(`${totalLabel}: ${result.total}`);\n renderTotalOfOverride(result.total, totalOfOverride);\n\n if (result.breakdown.mode === \"segments\") {\n renderSegmentBreakdown(result.breakdown.items);\n return;\n }\n\n if (result.breakdown.mode === \"collector\") {\n renderCollectorBreakdown(result.breakdown.items);\n renderNonWords(result.breakdown.nonWords, false);\n return;\n }\n\n if (result.breakdown.mode === \"char\" || result.breakdown.mode === \"char-collector\") {\n renderCountBreakdown(\n result.breakdown.items.map((item) => ({\n locale: item.locale,\n count: item.chars,\n nonWords: item.nonWords,\n })),\n getCountUnit(result.breakdown.mode),\n );\n return;\n }\n\n renderCountBreakdown(\n result.breakdown.items.map((item) => ({\n locale: item.locale,\n count: item.words,\n nonWords: item.nonWords,\n })),\n getCountUnit(result.breakdown.mode),\n );\n}\n\nfunction buildSectionLabel(\n sectionName: string,\n sectionMode: SectionMode,\n source: \"frontmatter\" | \"content\",\n totalLabel: string,\n): string {\n if (sectionMode === \"frontmatter\") {\n return `[Frontmatter] (${totalLabel})`;\n }\n\n if (sectionMode === \"content\") {\n return `[Content] (${totalLabel})`;\n }\n\n if (sectionMode === \"split\") {\n return source === \"frontmatter\" ? `[Frontmatter] (${totalLabel})` : `[Content] (${totalLabel})`;\n }\n\n if (sectionMode === \"per-key\") {\n return `[Frontmatter] ${sectionName} (${totalLabel})`;\n }\n\n if (sectionMode === \"split-per-key\") {\n return source === \"content\"\n ? `[Content] (${totalLabel})`\n : `[Frontmatter] ${sectionName} (${totalLabel})`;\n }\n\n return `[Section] ${sectionName} (${totalLabel})`;\n}\n\nexport function renderStandardSectionedResult(\n result: SectionedResult,\n labels: TotalLabels,\n totalOfOverride?: TotalOfOverride,\n): void {\n console.log(`${labels.overall}: ${result.total}`);\n renderTotalOfOverride(result.total, totalOfOverride);\n\n for (const item of result.items) {\n const label = buildSectionLabel(item.name, result.section, item.source, labels.section);\n const unit = getCountUnit(item.result.breakdown.mode);\n console.log(pc.cyan(pc.bold(`${label}: ${showSingularOrPluralWord(item.result.total, unit)}`)));\n\n if (item.result.breakdown.mode === \"segments\") {\n renderSegmentBreakdown(item.result.breakdown.items);\n continue;\n }\n\n if (item.result.breakdown.mode === \"collector\") {\n renderCollectorBreakdown(item.result.breakdown.items);\n renderNonWords(item.result.breakdown.nonWords, false);\n continue;\n }\n\n if (item.result.breakdown.mode === \"char\" || item.result.breakdown.mode === \"char-collector\") {\n renderCountBreakdown(\n item.result.breakdown.items.map((chunk) => ({\n locale: chunk.locale,\n count: chunk.chars,\n nonWords: chunk.nonWords,\n })),\n unit,\n );\n continue;\n }\n\n renderCountBreakdown(\n item.result.breakdown.items.map((chunk) => ({\n locale: chunk.locale,\n count: chunk.words,\n nonWords: chunk.nonWords,\n })),\n unit,\n );\n }\n}\n\nexport function isSectionedResult(\n result: WordCounterResult | SectionedResult,\n): result is SectionedResult {\n return \"section\" in result;\n}\n\nfunction toDisplayPath(inputPath: string): string {\n const relative = relativePath(process.cwd(), inputPath);\n if (relative && !relative.startsWith(\"..\")) {\n return relative || \".\";\n }\n return inputPath;\n}\n\nexport function reportSkipped(skipped: BatchSkip[]): void {\n if (skipped.length === 0) {\n return;\n }\n\n console.error(pc.yellow(`Skipped ${skipped.length} path(s):`));\n for (const item of skipped) {\n console.error(pc.yellow(`- ${toDisplayPath(item.path)} (${item.reason})`));\n }\n}\n\nexport function renderPerFileStandard(\n summary: BatchSummary,\n labels: TotalLabels,\n resolveTotalOfOverride?: (\n result: WordCounterResult | SectionedResult,\n ) => TotalOfOverride | undefined,\n): void {\n for (const file of summary.files) {\n console.log(pc.bold(`[File] ${toDisplayPath(file.path)}`));\n if (isSectionedResult(file.result)) {\n renderStandardSectionedResult(file.result, labels, resolveTotalOfOverride?.(file.result));\n continue;\n }\n\n renderStandardResult(file.result, labels.overall, resolveTotalOfOverride?.(file.result));\n }\n\n console.log(pc.bold(`[Merged] ${summary.files.length} file(s)`));\n if (isSectionedResult(summary.aggregate)) {\n renderStandardSectionedResult(\n summary.aggregate,\n labels,\n resolveTotalOfOverride?.(summary.aggregate),\n );\n return;\n }\n\n renderStandardResult(\n summary.aggregate,\n labels.overall,\n resolveTotalOfOverride?.(summary.aggregate),\n );\n}\n","import type { SectionedResult } from \"../../markdown\";\nimport type { BatchSummary } from \"../types\";\nimport type { WordCounterResult } from \"../../wc\";\n\nfunction normalizeWordCounterResultBase(result: WordCounterResult): WordCounterResult {\n result.total = result.counts?.words ?? result.total;\n delete result.counts;\n\n if (result.breakdown.mode === \"collector\") {\n delete result.breakdown.nonWords;\n return result;\n }\n\n if (result.breakdown.mode === \"char\" || result.breakdown.mode === \"char-collector\") {\n for (const item of result.breakdown.items) {\n const nonWordCount =\n (item.nonWords?.counts.emoji ?? 0) +\n (item.nonWords?.counts.symbols ?? 0) +\n (item.nonWords?.counts.punctuation ?? 0) +\n (item.nonWords?.counts.whitespace ?? 0);\n item.chars = Math.max(0, item.chars - nonWordCount);\n delete item.nonWords;\n }\n return result;\n }\n\n for (const item of result.breakdown.items) {\n delete item.nonWords;\n }\n\n return result;\n}\n\nfunction normalizeSectionedResultBase(result: SectionedResult): SectionedResult {\n let total = 0;\n for (const item of result.items) {\n normalizeWordCounterResultBase(item.result);\n total += item.result.total;\n }\n result.total = total;\n return result;\n}\n\nexport function normalizeResultBase(\n result: WordCounterResult | SectionedResult,\n): WordCounterResult | SectionedResult {\n if (\"section\" in result) {\n return normalizeSectionedResultBase(result);\n }\n return normalizeWordCounterResultBase(result);\n}\n\nexport function normalizeBatchSummaryBase(summary: BatchSummary): BatchSummary {\n for (const file of summary.files) {\n normalizeResultBase(file.result);\n }\n normalizeResultBase(summary.aggregate);\n return summary;\n}\n","import type { SectionedResult } from \"../../markdown\";\nimport { mergeDetectorDebugSummaries } from \"../../detector/debug\";\nimport { runBatchCount } from \"../batch/run\";\nimport {\n clampRequestedJobs,\n formatJobsAdvisoryWarning,\n resolveBatchJobsLimit,\n} from \"../batch/jobs/limits\";\nimport { resolveBatchJobsStrategy } from \"../batch/jobs/strategy\";\nimport type { DebugChannel } from \"../debug/channel\";\nimport { buildDebugSection } from \"../output/debug-json\";\nimport {\n getTotalLabels,\n isSectionedResult,\n renderPerFileStandard,\n renderStandardResult,\n renderStandardSectionedResult,\n reportSkipped,\n} from \"../output/render\";\nimport { normalizeBatchSummaryBase } from \"../output/normalize-base\";\nimport { buildDirectoryExtensionFilter } from \"../path/filter\";\nimport { createBatchProgressReporter } from \"../progress/reporter\";\nimport { resolveTotalOfOverride, type TotalOfOverride } from \"../total-of\";\nimport type { BatchOptions } from \"../types\";\nimport type { WordCounterResult } from \"../../wc\";\nimport { resolveBatchScope } from \"./options\";\nimport type { CliActionOptions, ResolvedCountRunOptions, RunCliOptions } from \"./types\";\nimport pc from \"picocolors\";\n\ntype ExecuteBatchCountOptions = {\n argv: string[];\n options: CliActionOptions;\n runtime: RunCliOptions;\n resolved: ResolvedCountRunOptions;\n debug: DebugChannel;\n teeEnabled: boolean;\n};\n\nexport async function executeBatchCount({\n argv,\n options,\n runtime,\n resolved,\n debug,\n teeEnabled,\n}: ExecuteBatchCountOptions): Promise<void> {\n const warningsEnabled = !options.quietWarnings;\n const emitWarning = (message: string): void => {\n if (!warningsEnabled) {\n return;\n }\n const warningLine = message.startsWith(\"Warning:\") ? message : `Warning: ${message}`;\n console.error(pc.yellow(warningLine));\n };\n\n const batchOptions: BatchOptions = {\n scope: resolveBatchScope(argv),\n pathMode: options.pathMode,\n recursive: options.recursive,\n quietSkips: Boolean(options.quietSkips),\n directoryRegexPattern: options.regex,\n };\n\n const extensionFilter = buildDirectoryExtensionFilter(options.includeExt, options.excludeExt);\n const requestedJobs = options.jobs;\n const jobsLimit = resolveBatchJobsLimit();\n const jobs = clampRequestedJobs(requestedJobs, jobsLimit);\n if (requestedJobs > jobsLimit.suggestedMaxJobs) {\n emitWarning(formatJobsAdvisoryWarning(requestedJobs, jobs, jobsLimit));\n }\n const jobsStrategy = resolveBatchJobsStrategy(jobs);\n\n const debugEnabled = Boolean(options.debug);\n const mirrorDebugToTerminal = debugEnabled && (!debug.reportPath || teeEnabled);\n const summary = await runBatchCount({\n pathInputs: options.path ?? [],\n batchOptions,\n extensionFilter,\n detectBinary: options.pathDetectBinary,\n section: options.section,\n wcOptions: resolved.wcOptions,\n preserveCollectorSegments: options.format === \"json\",\n detectorEvidence: Boolean(options.detectorEvidence),\n debug,\n progressReporter: createBatchProgressReporter({\n enabled: options.format === \"standard\" && options.progressMode !== \"off\",\n stream: runtime.stderr ?? process.stderr,\n clearOnFinish: !(mirrorDebugToTerminal || options.keepProgress),\n }),\n jobs,\n jobsStrategy,\n emitWarning,\n });\n\n const showSkipDiagnostics = debugEnabled && !batchOptions.quietSkips;\n const showSkipItems = showSkipDiagnostics && Boolean(options.verbose);\n debug.emit(\"batch.skips.policy\", {\n enabled: showSkipDiagnostics,\n items: showSkipItems,\n quietSkips: batchOptions.quietSkips,\n });\n if (showSkipDiagnostics) {\n debug.emit(\"batch.skips.report\", {\n count: summary.skipped.length,\n });\n if (showSkipItems) {\n for (const skip of summary.skipped) {\n debug.emit(\n \"batch.skips.item\",\n {\n path: skip.path,\n reason: skip.reason,\n },\n { verbosity: \"verbose\" },\n );\n }\n }\n\n if (mirrorDebugToTerminal) {\n reportSkipped(summary.skipped);\n }\n }\n\n if (summary.files.length === 0) {\n throw new Error(\"No readable text-like inputs were found from --path.\");\n }\n\n let aggregateTotalOfOverride: TotalOfOverride | undefined;\n let totalOfOverridesByResult: WeakMap<object, TotalOfOverride> | undefined;\n if (resolved.totalOfParts && resolved.totalOfParts.length > 0) {\n totalOfOverridesByResult = new WeakMap<object, TotalOfOverride>();\n const aggregateOverride = resolveTotalOfOverride(summary.aggregate, resolved.totalOfParts);\n if (aggregateOverride) {\n totalOfOverridesByResult.set(summary.aggregate as object, aggregateOverride);\n aggregateTotalOfOverride = aggregateOverride;\n }\n\n for (const file of summary.files) {\n const fileOverride = resolveTotalOfOverride(file.result, resolved.totalOfParts);\n if (!fileOverride) {\n continue;\n }\n totalOfOverridesByResult.set(file.result as object, fileOverride);\n }\n } else {\n aggregateTotalOfOverride = resolveTotalOfOverride(summary.aggregate, resolved.totalOfParts);\n }\n\n if (resolved.shouldNormalizeBaseOutput) {\n normalizeBatchSummaryBase(summary);\n }\n\n if (!aggregateTotalOfOverride && totalOfOverridesByResult) {\n aggregateTotalOfOverride = totalOfOverridesByResult.get(summary.aggregate as object);\n }\n\n if (options.format === \"raw\") {\n console.log(aggregateTotalOfOverride?.total ?? summary.aggregate.total);\n return;\n }\n\n if (options.format === \"json\") {\n const spacing = options.pretty ? 2 : 0;\n const aggregateDetectorDebug = mergeDetectorDebugSummaries(\n summary.files.map((file) => file.debug?.detector),\n );\n\n if (batchOptions.scope === \"per-file\") {\n const skipped = showSkipDiagnostics ? summary.skipped : undefined;\n const fileEntries = summary.files.map((file) => {\n const base = {\n path: file.path,\n result: file.result,\n ...(options.debug && file.debug\n ? { debug: buildDebugSection({ detector: file.debug.detector }) }\n : {}),\n };\n\n if (!resolved.totalOfParts || resolved.totalOfParts.length === 0) {\n return base;\n }\n\n const fileOverride =\n totalOfOverridesByResult?.get(file.result as object) ??\n resolveTotalOfOverride(file.result, resolved.totalOfParts);\n if (!fileOverride) {\n return base;\n }\n\n return {\n ...base,\n meta: {\n totalOf: fileOverride.parts,\n totalOfOverride: fileOverride.total,\n },\n };\n });\n const meta =\n resolved.totalOfParts && resolved.totalOfParts.length > 0\n ? {\n totalOf: resolved.totalOfParts,\n aggregateTotalOfOverride: aggregateTotalOfOverride?.total ?? summary.aggregate.total,\n }\n : undefined;\n const payload = {\n scope: \"per-file\",\n files: fileEntries,\n ...(skipped ? { skipped } : {}),\n ...(options.debug\n ? {\n debug: buildDebugSection({\n skipped,\n detector: aggregateDetectorDebug,\n }),\n }\n : {}),\n aggregate: summary.aggregate,\n ...(meta ? { meta } : {}),\n };\n console.log(JSON.stringify(payload, null, spacing));\n return;\n }\n\n if (!aggregateTotalOfOverride) {\n console.log(\n JSON.stringify(\n {\n ...summary.aggregate,\n ...(options.debug\n ? {\n debug: buildDebugSection({\n detector: aggregateDetectorDebug,\n }),\n }\n : {}),\n },\n null,\n spacing,\n ),\n );\n return;\n }\n console.log(\n JSON.stringify(\n {\n ...summary.aggregate,\n meta: {\n totalOf: aggregateTotalOfOverride.parts,\n totalOfOverride: aggregateTotalOfOverride.total,\n },\n ...(options.debug\n ? {\n debug: buildDebugSection({\n detector: aggregateDetectorDebug,\n }),\n }\n : {}),\n },\n null,\n spacing,\n ),\n );\n return;\n }\n\n const labels = getTotalLabels(options.mode, resolved.requestedNonWords);\n const totalOfResolver =\n resolved.totalOfParts && resolved.totalOfParts.length > 0\n ? (result: WordCounterResult | SectionedResult) =>\n totalOfOverridesByResult?.get(result as object) ??\n resolveTotalOfOverride(result, resolved.totalOfParts)\n : undefined;\n\n if (batchOptions.scope === \"per-file\") {\n renderPerFileStandard(summary, labels, totalOfResolver);\n return;\n }\n\n if (isSectionedResult(summary.aggregate)) {\n renderStandardSectionedResult(summary.aggregate, labels, aggregateTotalOfOverride);\n return;\n }\n\n renderStandardResult(summary.aggregate, labels.overall, aggregateTotalOfOverride);\n}\n","async function readStdin(): Promise<string> {\n if (process.stdin.isTTY) {\n return \"\";\n }\n\n return new Promise<string>((resolve, reject) => {\n const chunks: string[] = [];\n process.stdin.setEncoding(\"utf8\");\n process.stdin.on(\"data\", (chunk) => chunks.push(String(chunk)));\n process.stdin.on(\"end\", () => resolve(chunks.join(\"\")));\n process.stdin.on(\"error\", (error) => reject(error));\n process.stdin.resume();\n });\n}\n\nexport async function resolveInput(textTokens: string[]): Promise<string> {\n if (textTokens.length > 0) {\n return textTokens.join(\" \");\n }\n\n return readStdin();\n}\n","import type { SectionedResult } from \"../../markdown\";\nimport { buildDebugSection } from \"../output/debug-json\";\nimport { countSections } from \"../../markdown\";\nimport { countSectionsWithDetector, wordCounterWithDetector } from \"../../detector\";\nimport { createDetectorDebugSummary } from \"../../detector/debug\";\nimport {\n getTotalLabels,\n isSectionedResult,\n renderStandardResult,\n renderStandardSectionedResult,\n} from \"../output/render\";\nimport { normalizeResultBase } from \"../output/normalize-base\";\nimport { resolveTotalOfOverride } from \"../total-of\";\nimport wordCounter, { type WordCounterResult } from \"../../wc\";\nimport { resolveInput } from \"./input\";\nimport { formatInputReadError } from \"./options\";\nimport type { DebugChannel } from \"../debug/channel\";\nimport type { CliActionOptions, ResolvedCountRunOptions } from \"./types\";\n\ntype ExecuteSingleCountOptions = {\n textTokens: string[];\n options: CliActionOptions;\n resolved: ResolvedCountRunOptions;\n debug: DebugChannel;\n};\n\nexport async function executeSingleCount({\n textTokens,\n options,\n resolved,\n debug,\n}: ExecuteSingleCountOptions): Promise<void> {\n debug.emit(\"runtime.single.start\", {\n detectorMode: resolved.detectorMode,\n format: options.format,\n section: options.section,\n });\n\n let input: string;\n try {\n input = await resolveInput(textTokens);\n } catch (error) {\n throw new Error(formatInputReadError(error));\n }\n\n const trimmed = input.trim();\n if (!trimmed) {\n throw new Error(\"No input provided. Pass text, pipe stdin, or use --path.\");\n }\n\n const detectorDebugSummary =\n resolved.detectorMode === \"wasm\"\n ? createDetectorDebugSummary(resolved.detectorMode)\n : undefined;\n const detectorDebug =\n detectorDebugSummary && debug.enabled\n ? {\n emit: debug.emit,\n summary: detectorDebugSummary,\n ...(options.detectorEvidence\n ? {\n evidence: {\n verbosity: debug.verbosity,\n mode: resolved.wcOptions.mode ?? \"chunk\",\n section: options.section,\n },\n }\n : {}),\n }\n : undefined;\n\n const result: WordCounterResult | SectionedResult = resolved.useSection\n ? resolved.detectorMode === \"regex\"\n ? countSections(trimmed, options.section, resolved.wcOptions)\n : await countSectionsWithDetector(trimmed, options.section, {\n ...resolved.wcOptions,\n detector: resolved.detectorMode,\n detectorDebug,\n })\n : resolved.detectorMode === \"regex\"\n ? wordCounter(trimmed, resolved.wcOptions)\n : await wordCounterWithDetector(trimmed, {\n ...resolved.wcOptions,\n detector: resolved.detectorMode,\n detectorDebug,\n });\n const totalOfOverride = resolveTotalOfOverride(result, resolved.totalOfParts);\n const displayResult = resolved.shouldNormalizeBaseOutput ? normalizeResultBase(result) : result;\n\n debug.emit(\"runtime.single.complete\", {\n detectorMode: resolved.detectorMode,\n sectioned: resolved.useSection,\n total: displayResult.total,\n });\n\n if (options.format === \"raw\") {\n console.log(totalOfOverride?.total ?? displayResult.total);\n return;\n }\n\n if (options.format === \"json\") {\n const spacing = options.pretty ? 2 : 0;\n const debugSection =\n options.debug && detectorDebugSummary && detectorDebugSummary.windowsTotal > 0\n ? buildDebugSection({ detector: detectorDebugSummary })\n : undefined;\n if (!totalOfOverride && !debugSection) {\n console.log(JSON.stringify(displayResult, null, spacing));\n return;\n }\n console.log(\n JSON.stringify(\n {\n ...displayResult,\n ...(totalOfOverride\n ? {\n meta: {\n totalOf: totalOfOverride.parts,\n totalOfOverride: totalOfOverride.total,\n },\n }\n : {}),\n ...(debugSection ? { debug: debugSection } : {}),\n },\n null,\n spacing,\n ),\n );\n return;\n }\n\n const labels = getTotalLabels(options.mode, resolved.requestedNonWords);\n if (isSectionedResult(displayResult)) {\n renderStandardSectionedResult(displayResult, labels, totalOfOverride);\n return;\n }\n\n renderStandardResult(displayResult, labels.overall, totalOfOverride);\n}\n","import { Command } from \"commander\";\nimport {\n applyConfigToCountOptions,\n deriveCountCliSources,\n deriveInitialCountProgressMode,\n resolveWordCounterConfig,\n} from \"./cli/config\";\nimport { createDebugChannel } from \"./cli/debug/channel\";\nimport { executeDoctorCommand, isExplicitDoctorInvocation } from \"./cli/doctor/run\";\nimport { executeInspectCommand, isExplicitInspectInvocation } from \"./cli/inspect/run\";\nimport { configureProgramOptions } from \"./cli/program/options\";\nimport { getFormattedVersionLabel } from \"./cli/program/version\";\nimport { resolveBatchJobsLimit } from \"./cli/batch/jobs/limits\";\nimport { executeBatchCount } from \"./cli/runtime/batch\";\nimport { WASM_DETECTOR_RUNTIME_UNAVAILABLE_MESSAGE } from \"./detector\";\nimport {\n hasPathInput,\n resolveCountRunOptions,\n resolveDebugReportPathOption,\n validateStandalonePrintJobsLimitUsage,\n validateSingleRegexOptionUsage,\n} from \"./cli/runtime/options\";\nimport { executeSingleCount } from \"./cli/runtime/single\";\nimport type { CliActionOptions, RunCliOptions } from \"./cli/runtime/types\";\nimport type { WordCounterMode } from \"./wc\";\nimport { normalizeMode } from \"./wc/mode\";\nimport pc from \"picocolors\";\n\nfunction emitConfigNotes(notes: string[]): void {\n for (const note of notes) {\n const warningLine = note.startsWith(\"Warning:\") ? note : `Warning: ${note}`;\n console.error(pc.yellow(warningLine));\n }\n}\n\nexport async function runCli(\n argv: string[] = process.argv,\n runtime: RunCliOptions = {},\n): Promise<void> {\n if (isExplicitDoctorInvocation(argv)) {\n await executeDoctorCommand({\n argv,\n runtime: runtime.doctor,\n });\n return;\n }\n\n if (isExplicitInspectInvocation(argv)) {\n await executeInspectCommand({ argv, runtime });\n return;\n }\n\n const program = new Command();\n const parseMode = (value: string): WordCounterMode => {\n const normalized = normalizeMode(value);\n if (!normalized) {\n throw new Error(`Invalid mode: ${value}`);\n }\n return normalized;\n };\n\n program\n .name(\"word-counter\")\n .description(\"Locale-aware word counting powered by Intl.Segmenter.\")\n .version(getFormattedVersionLabel(), \"-v, --version\", \"output the version number\")\n .addHelpText(\n \"after\",\n \"\\nCommands:\\n inspect [options] [text...] inspect detector behavior without count output\\n doctor [options] report runtime diagnostics for this host\",\n );\n\n configureProgramOptions(program, parseMode);\n\n program.action(\n async (textTokens: string[], rawOptions: CliActionOptions & { progress: boolean }) => {\n if (rawOptions.printJobsLimit) {\n try {\n validateStandalonePrintJobsLimitUsage(argv);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n program.error(pc.red(message));\n return;\n }\n\n console.log(JSON.stringify(resolveBatchJobsLimit()));\n return;\n }\n\n let options: CliActionOptions = {\n ...rawOptions,\n pathDetectBinary: rawOptions.pathDetectBinary ?? true,\n progressMode: deriveInitialCountProgressMode(program, rawOptions.progress),\n };\n\n try {\n const resolvedConfig = await resolveWordCounterConfig({\n env: runtime.env,\n cwd: runtime.cwd,\n });\n options = applyConfigToCountOptions(\n options,\n resolvedConfig.config,\n deriveCountCliSources(program),\n );\n if (!options.quietWarnings) {\n emitConfigNotes(resolvedConfig.notes);\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n program.error(pc.red(message));\n return;\n }\n\n const debugEnabled = Boolean(options.debug);\n const debugReportPath = resolveDebugReportPathOption(options.debugReport);\n const debugReportEnabled = options.debugReport !== undefined && options.debugReport !== false;\n\n if (options.verbose && !debugEnabled) {\n program.error(pc.red(\"`--verbose` requires `--debug`.\"));\n return;\n }\n\n if (options.detectorEvidence && !debugEnabled) {\n program.error(pc.red(\"`--detector-evidence` requires `--debug`.\"));\n return;\n }\n\n if (options.detectorEvidence && options.detector !== \"wasm\") {\n program.error(pc.red(\"`--detector-evidence` requires `--detector wasm`.\"));\n return;\n }\n\n if (debugReportEnabled && !debugEnabled) {\n program.error(pc.red(\"`--debug-report` requires `--debug`.\"));\n return;\n }\n\n const teeEnabled = Boolean(options.debugReportTee || options.debugTee);\n\n if (teeEnabled && !debugReportEnabled) {\n program.error(\n pc.red(\"`--debug-report-tee` (alias: `--debug-tee`) requires `--debug-report`.\"),\n );\n return;\n }\n\n try {\n validateSingleRegexOptionUsage(argv);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n program.error(pc.red(message));\n return;\n }\n\n let debug;\n try {\n debug = createDebugChannel({\n enabled: debugEnabled,\n verbosity: options.verbose ? \"verbose\" : \"compact\",\n report: debugReportEnabled\n ? {\n path: debugReportPath,\n tee: teeEnabled,\n autogeneratedNamePrefix: options.detectorEvidence\n ? \"wc-detector-evidence\"\n : \"wc-debug\",\n }\n : undefined,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n program.error(pc.red(`Failed to initialize debug diagnostics: ${message}`));\n return;\n }\n\n try {\n const resolved = resolveCountRunOptions(options);\n if (hasPathInput(options.path)) {\n await executeBatchCount({\n argv,\n options,\n runtime,\n resolved,\n debug,\n teeEnabled,\n });\n return;\n }\n\n await executeSingleCount({\n textTokens,\n options,\n resolved,\n debug,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (message === \"No input provided. Pass text, pipe stdin, or use --path.\") {\n program.error(pc.red(message));\n return;\n }\n if (message === \"No readable text-like inputs were found from --path.\") {\n program.error(pc.red(message));\n return;\n }\n if (message === WASM_DETECTOR_RUNTIME_UNAVAILABLE_MESSAGE) {\n console.error(pc.red(message));\n process.exitCode = 1;\n return;\n }\n program.error(message);\n } finally {\n await debug.close();\n }\n },\n );\n\n await program.parseAsync(argv);\n if (process.exitCode === undefined) {\n process.exitCode = 0;\n }\n}\n\nexport { buildBatchSummary } from \"./cli/batch/aggregate\";\nexport { loadBatchInputs } from \"./cli/path/load\";\nexport { resolveBatchFilePaths } from \"./cli/path/resolve\";\n","import { runCli } from \"./command\";\n\nrunCli().catch((error) => {\n const message = error instanceof Error ? error.message : String(error);\n console.error(\"Failed to run CLI:\", message);\n process.exitCode = 1;\n});\n"],"x_google_ignoreList":[15],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAa,uBAAuB;AACpC,MAAa,yBAAkD;CAAC;CAAQ;CAAS;CAAO;AACxD,uBAAuB,KACpD,WAAW,GAAG,qBAAqB,GAAG,SACxC;AAED,MAAa,yBAAkD,CAAC,SAAS,OAAO;AAChF,MAAa,kCAAsE;CACjF;CACA;CACA;CACA;CACD;AACD,MAAa,0BAA+C,CAAC,QAAQ,SAAS;AAC9E,MAAa,8BAA6D;CAAC;CAAQ;CAAM;CAAM;AAC/F,MAAa,0BAAqD,CAAC,QAAQ,QAAQ;AACnF,MAAa,8BAA6D,CAAC,WAAW,UAAU;AAEhG,MAAa,yBAAiD;CAC5D;CACA;CACA;CACA;CACA;CAC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