{"version":3,"sources":["../node_modules/tsup/assets/esm_shims.js","../packages/domain/shared/src/native-resolution.ts","../packages/domain/shared/src/index.ts","../packages/domain/compiler/src/nativeBridge.ts","../packages/domain/compiler/src/compiler/index.ts","../packages/domain/compiler/src/parser/index.ts","../packages/domain/compiler/src/analyzer/index.ts","../packages/domain/compiler/src/cache/index.ts","../packages/domain/compiler/src/redis/index.ts","../packages/domain/compiler/src/watch/index.ts","../packages/domain/compiler/src/routeGraph.ts","../packages/domain/compiler/src/semanticComponentAnalyzer.ts","../packages/domain/compiler/src/typeGeneratorFromMetadata.ts","../packages/domain/compiler/src/typeGenerationPlugin.ts","../packages/domain/compiler/src/index.ts","../src/umbrella/atomic.ts","../packages/domain/atomic/src/index.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * Prebuilt binary resolution untuk native NAPI bindings.\n * QA #1: Resolve native binary dari prebuilt packages atau local build.\n *\n * Prioritas:\n * 1. TW_NATIVE_PATH env var (explicit override)\n * 2. Prebuilt binary dari platform-specific npm package\n * 3. Local build dari source (developer mode)\n */\n\nimport { createRequire } from \"node:module\"\nimport * as fs from \"node:fs\"\nimport * as path from \"node:path\"\n\nconst isBrowser = typeof window !== \"undefined\" || typeof document !== \"undefined\"\n\n// ESM-safe require — works in both ESM and CJS contexts.\n// Ref: Node.js docs — module.createRequire(filename) hanya terima:\n//   - file URL object, file URL string, atau absolute path string.\n// \"file://unknown\" crash karena bukan URL valid — gunakan process.cwd() sebagai fallback.\n// Ref: https://nodejs.org/api/module.html#modulecreaterequirefilename\nfunction _safeCreateRequire(): NodeRequire {\n  // ESM context: import.meta.url selalu absolute file URL yang valid\n  if (typeof import.meta !== \"undefined\" && import.meta.url && !import.meta.url.includes(\"unknown\")) {\n    return createRequire(import.meta.url)\n  }\n  // CJS context: __filename adalah absolute path yang valid\n  if (typeof __filename !== \"undefined\") {\n    return createRequire(__filename)\n  }\n  // Fallback: process.cwd() mengembalikan absolute path (Node.js docs — process.cwd())\n  return createRequire(new URL(`file://${process.cwd()}/`).href)\n}\n\nconst _require = _safeCreateRequire()\n\nexport interface NativeResolutionResult {\n  path: string | null\n  source: \"env\" | \"prebuilt\" | \"local\" | \"not-found\"\n  platform: string\n  tried: string[]\n}\n\n/** Platform key → prebuilt npm package name */\nconst PLATFORM_MAP: Record<string, string[]> = {\n  \"linux-x64\":    [\"@tailwind-styled/native-linux-x64-gnu\", \"@tailwind-styled/native-linux-x64\"],\n  \"linux-arm64\":  [\"@tailwind-styled/native-linux-arm64-gnu\", \"@tailwind-styled/native-linux-arm64\"],\n  \"darwin-x64\":   [\"@tailwind-styled/native-darwin-x64\"],\n  \"darwin-arm64\": [\"@tailwind-styled/native-darwin-arm64\"],\n  \"win32-x64\":    [\"@tailwind-styled/native-win32-x64-msvc\", \"@tailwind-styled/native-win32-x64\"],\n  \"win32-arm64\":  [\"@tailwind-styled/native-win32-arm64-msvc\", \"@tailwind-styled/native-win32-arm64\"],\n}\n\nfunction platformKey(): string {\n  if (isBrowser) return \"browser\"\n  return `${process.platform}-${process.arch}`\n}\n\n/**\n * Resolve native binary path dari semua sumber yang tersedia.\n *\n * @example\n * const result = resolveNativeBinary()\n * if (result.path) {\n *   const binding = require(result.path)\n * } else {\n *   throw new Error(\"Native binding not found — run npm run build:rust\")\n * }\n */\nexport function resolveNativeBinary(runtimeDir?: string): NativeResolutionResult {\n  const platform = platformKey()\n  const tried: string[] = []\n\n  if (isBrowser) {\n    return { path: null, source: \"not-found\", platform, tried: [\"not available in browser\"] }\n  }\n\n  // 0. Disabled flag — always short-circuit before any I/O\n  // TWS_NO_NATIVE adalah nama canonical; TWS_DISABLE_NATIVE diterima untuk backward compat\n  if (process.env.TWS_NO_NATIVE === \"1\" || process.env.TWS_DISABLE_NATIVE === \"1\") {\n    return { path: null, source: \"not-found\", platform, tried: [] }\n  }\n\n  // 1. Env var override\n  const envPath = process.env.TW_NATIVE_PATH?.trim()\n  if (envPath) {\n    if (fs.existsSync(envPath)) {\n      return { path: envPath, source: \"env\", platform, tried }\n    }\n    tried.push(`env:${envPath} (not found)`)\n  }\n\n  // 2. Prebuilt binary dari platform-specific npm package\n  const prebuiltPkgs = PLATFORM_MAP[platform] ?? []\n  for (const pkg of prebuiltPkgs) {\n    try {\n      const candidate = _require.resolve(`${pkg}/tailwind_styled_parser.node`)\n      if (fs.existsSync(candidate)) {\n        return { path: candidate, source: \"prebuilt\", platform, tried }\n      }\n      tried.push(`prebuilt:${pkg} (resolved but missing)`)\n    } catch {\n      tried.push(`prebuilt:${pkg} (not installed)`)\n    }\n  }\n\n  // 2b. .node file bundled inside this package itself (via \"files\": [\"native/*.node\"])\n  //     Covers the case where user installs tailwind-styled-v4 directly from npm\n  //     and the .node file lands at node_modules/tailwind-styled-v4/native/*.node\n  const napiPlatform = platform === \"linux-x64\" ? \"linux-x64-gnu\"\n    : platform === \"linux-arm64\" ? \"linux-arm64-gnu\"\n    : platform\n  const BINARY_NAMES_SELF = [\"tailwind-styled-native\", \"tailwind_styled_parser\"]\n  if (runtimeDir) {\n    // runtimeDir is typically dist/ — go up to package root, then into native/\n    for (const depth of [\"..\", path.join(\"..\", \"..\"), path.join(\"..\", \"..\", \"..\")]) {\n      const pkgRoot = path.resolve(runtimeDir, depth)\n      for (const bin of BINARY_NAMES_SELF) {\n        for (const suffix of [\"\", `.${platform}`, `.${napiPlatform}`]) {\n          const candidate = path.resolve(pkgRoot, \"native\", `${bin}${suffix}.node`)\n          tried.push(`self-bundled:${candidate}`)\n          if (fs.existsSync(candidate)) {\n            return { path: candidate, source: \"prebuilt\", platform, tried }\n          }\n        }\n      }\n    }\n  }\n\n  // 3. Local build candidates\n  const cwd = process.cwd()\n  const base = runtimeDir ?? cwd\n  // napi-rs naming: platform key may have -gnu suffix on Linux (already computed above)\n\n  // Both possible binary names:\n  // - \"tailwind_styled_parser\" (old hardcoded name in resolvers)\n  // - \"tailwind-styled-native\" (actual binaryName in native/package.json)\n  const BINARY_NAMES = [\"tailwind-styled-native\", \"tailwind_styled_parser\"]\n\n  const localCandidates: string[] = []\n\n  for (const bin of BINARY_NAMES) {\n    localCandidates.push(path.resolve(base, `${bin}.node`))\n    localCandidates.push(path.resolve(base, \"..\", `${bin}.node`))\n    localCandidates.push(path.resolve(base, `${bin}.${platform}.node`))\n    localCandidates.push(path.resolve(base, `${bin}.${napiPlatform}.node`))\n  }\n\n  // Walk up from cwd AND base to find repo root native/ dir\n  // Needed when npm workspaces sets cwd to the package subdir\n  for (const startDir of [cwd, base]) {\n    let dir = startDir\n    for (let i = 0; i < 6; i++) {\n      const nativeDir = path.resolve(dir, \"native\")\n      for (const bin of BINARY_NAMES) {\n        localCandidates.push(path.resolve(nativeDir, `${bin}.node`))\n        localCandidates.push(path.resolve(nativeDir, `${bin}.${platform}.node`))\n        localCandidates.push(path.resolve(nativeDir, `${bin}.${napiPlatform}.node`))\n        localCandidates.push(path.resolve(nativeDir, \"target\", \"release\", `${bin}.node`))\n      }\n      const parent = path.resolve(dir, \"..\")\n      if (parent === dir) break\n      dir = parent\n    }\n  }\n\n  for (const candidate of localCandidates) {\n    tried.push(`local:${candidate}`)\n    if (fs.existsSync(candidate)) {\n      return { path: candidate, source: \"local\", platform, tried }\n    }\n  }\n\n  return { path: null, source: \"not-found\", platform, tried }\n}\n\n/**\n * Format human-readable error untuk \"binary not found\".\n */\nexport function formatNativeNotFoundError(result: NativeResolutionResult): string {\n  const lines = [\n    `[tailwind-styled] Native binding not found for ${result.platform}`,\n    ``,\n    `Tried:`,\n    ...result.tried.map(t => `  - ${t}`),\n    ``,\n    `Solutions:`,\n    `  1. Build locally:     npm run build:rust`,\n    `  2. Install prebuilt:  npm install @tailwind-styled/native-${result.platform}`,\n    `  3. Override path:     TW_NATIVE_PATH=/path/to/parser.node`,\n  ]\n  return lines.join(\"\\n\")\n}","import { createHash } from \"node:crypto\"\nimport fs from \"node:fs\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport { createRequire } from \"node:module\"\n\n// Native-only: Node.js is always available. No browser fallback.\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Types\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type TokenMap = Record<string, string>\n\nexport type VariantValue = string | number | boolean | undefined\n\nexport type VariantProps = Record<string, VariantValue>\n\nexport type HtmlTagName = keyof HTMLElementTagNameMap\n\nexport type CompoundCondition = Record<string, string | number | boolean>\n\nexport type VariantMatrix = Record<string, Array<string | number | boolean>>\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Logging\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface Logger {\n  warn(...args: unknown[]): void\n  debug(...args: unknown[]): void\n  error(...args: unknown[]): void\n  log(...args: unknown[]): void\n}\n\nexport function createLogger(namespace: string): Logger {\n  const prefix = `[${namespace}]`\n  return {\n    warn(...args: unknown[]) {\n      process.stderr.write(`${prefix} ${args.map(a => typeof a === \"string\" ? a : String(a)).join(\" \")}\\n`)\n    },\n    debug(...args: unknown[]) {\n      process.stderr.write(`${prefix} ${args.map(a => typeof a === \"string\" ? a : String(a)).join(\" \")}\\n`)\n    },\n    error(...args: unknown[]) {\n      process.stderr.write(`${prefix} ${args.map(a => typeof a === \"string\" ? a : String(a)).join(\" \")}\\n`)\n    },\n    log(...args: unknown[]) {\n      process.stderr.write(`${prefix} ${args.map(a => typeof a === \"string\" ? a : String(a)).join(\" \")}\\n`)\n    },\n  }\n}\n\nexport function createDebugLogger(namespace: string, label?: string): (msg: string) => void {\n  const prefix = label ? `[${namespace}:${label}]` : `[${namespace}]`\n  return (msg: string) => {\n    if (process.env.DEBUG?.includes(namespace) || process.env.TW_DEBUG) {\n      console.debug(prefix, msg)\n    }\n  }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Error handling\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type ErrorSource = \"rust\" | \"validation\" | \"compile\" | \"io\" | \"config\" | \"unknown\"\n\ntype ZodLikeIssue = {\n  path?: readonly PropertyKey[]\n  message?: string\n}\n\nfunction formatIssuePath(path?: readonly PropertyKey[]): string {\n  if (!path || path.length === 0) return \"(root)\"\n  return path\n    .map((segment) =>\n      typeof segment === \"symbol\" ? segment.description ?? segment.toString() : String(segment)\n    )\n    .join(\".\")\n}\n\nexport class TwError extends Error {\n  /** @deprecated Gunakan source */\n  public readonly domain: string\n  public readonly source: ErrorSource\n  public readonly code: string\n  public readonly originalCause?: unknown\n\n  constructor(domainOrSource: string, code: string, message: string, cause?: unknown) {\n    super(message)\n    this.name = \"TwError\"\n    this.domain = domainOrSource\n    this.source = domainOrSource as ErrorSource\n    this.code = code\n    this.originalCause = cause\n    if (Error.captureStackTrace) Error.captureStackTrace(this, TwError)\n  }\n\n  static fromIo(code: string, message: string): TwError {\n    return new TwError(\"io\", code, message)\n  }\n\n  static fromCompile(code: string, message: string): TwError {\n    return new TwError(\"compile\", code, message)\n  }\n\n  static fromRust(err: { code?: string; message?: string } | Error | unknown): TwError {\n    if (err instanceof TwError) return err\n    if (err instanceof Error) return new TwError(\"rust\", \"RUST_ERROR\", err.message, err)\n    if (err && typeof err === \"object\") {\n      const e = err as { code?: string; message?: string }\n      return new TwError(\"rust\", e.code ?? \"RUST_ERROR\", e.message ?? String(err), err)\n    }\n    return new TwError(\"rust\", \"RUST_ERROR\", String(err), err)\n  }\n\n  /** Buat TwError dari ZodError — dukung shape Zod v3 (`errors`) dan v4 (`issues`). */\n  static fromZod(err: { issues?: ZodLikeIssue[]; errors?: ZodLikeIssue[] }): TwError {\n    const first = err.issues?.[0] ?? err.errors?.[0]\n    const path = formatIssuePath(first?.path)\n    const message = first ? `${path}: ${first.message}` : \"Schema validation failed\"\n    return new TwError(\"validation\", \"SCHEMA_VALIDATION_FAILED\", message, err)\n  }\n\n  static wrap(source: string, code: string, err: unknown): TwError {\n    if (err instanceof TwError) return err\n    if (err instanceof Error) return new TwError(source, code, err.message, err)\n    return new TwError(source, code, String(err), err)\n  }\n\n  override toString(): string {\n    return `TwError [${this.source}:${this.code}] ${this.message}`\n  }\n\n  toJSON(): { name: string; source: string; code: string; message: string } {\n    return { name: this.name, source: this.source, code: this.code, message: this.message }\n  }\n\n  toCliMessage(): string {\n    return `[${this.source.toUpperCase()}:${this.code}] ${this.message}`\n  }\n}\n\nexport function wrapUnknownError(domain: string, code: string, error: unknown): TwError {\n  return TwError.wrap(domain, code, error)\n}\n\nexport function isTwError(err: unknown): err is TwError {\n  return err instanceof TwError\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Native binding resolution\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport interface LoadNativeBindingOptions<T> {\n  runtimeDir: string\n  candidates: string[]\n  isValid: (module: unknown) => module is T\n  invalidExportMessage: string\n}\n\nexport interface LoadNativeBindingResult<T> {\n  binding: T | null\n  loadErrors: Array<{ path: string; message: string }>\n  loadedPath?: string\n}\n\nexport function loadNativeBinding<T>(options: LoadNativeBindingOptions<T>): LoadNativeBindingResult<T> {\n  const { runtimeDir, candidates, isValid } = options\n  const loadErrors: Array<{ path: string; message: string }> = []\n\n  for (const candidate of candidates) {\n    const candidatePath = path.resolve(runtimeDir, candidate)\n    try {\n      if (!fs.existsSync(candidatePath) && !fs.existsSync(candidatePath + \".node\")) {\n        continue\n      }\n      const mod = requireNativeModule(candidatePath)\n      if (mod && isValid(mod)) {\n        return { binding: mod, loadErrors, loadedPath: candidatePath }\n      }\n      loadErrors.push({ path: candidatePath, message: options.invalidExportMessage })\n    } catch (e) {\n      loadErrors.push({ path: candidatePath, message: e instanceof Error ? e.message : String(e) })\n    }\n  }\n\n  return { binding: null, loadErrors }\n}\n\nconst _require = createRequire(\n  typeof __filename !== \"undefined\"\n    ? `file://${__filename}`\n    : (import.meta.url ?? \"file://unknown\")\n)\n\nfunction requireNativeModule(p: string): unknown {\n  return _require(p)\n}\n\nexport interface ResolveCandidatesOptions {\n  runtimeDir?: string\n  envVarNames?: string[]\n  includeDefaultCandidates?: boolean\n  enforceNodeExtensionForEnvPath?: boolean\n  /** @deprecated — ignored, kept for backward compat */\n  packageName?: string\n}\n\nexport function resolveNativeBindingCandidates(options: ResolveCandidatesOptions): string[] {\n  const {\n    envVarNames = [\"TW_NATIVE_PATH\", \"TWS_NATIVE_PATH\"],\n    includeDefaultCandidates = true,\n    enforceNodeExtensionForEnvPath = false,\n  } = options\n  // Default ke cwd kalau runtimeDir tidak disediakan\n  const runtimeDir = options.runtimeDir || process.cwd()\n  const candidates: string[] = []\n\n  for (const envVar of envVarNames) {\n    const envPath = process.env[envVar]\n    if (envPath) {\n      candidates.push(enforceNodeExtensionForEnvPath && !envPath.endsWith(\".node\") ? envPath + \".node\" : envPath)\n    }\n  }\n\n  if (!includeDefaultCandidates) return candidates\n\n  if (fs.existsSync(runtimeDir)) {\n    try {\n      for (const entry of fs.readdirSync(runtimeDir)) {\n        if (entry.endsWith(\".node\")) candidates.push(entry)\n      }\n    } catch { /* ignore read errors */ }\n  }\n\n  const BINARY_NAMES = [\"tailwind-styled-native\", \"tailwind_styled_parser\"]\n  const napiPlatform = process.platform === \"linux\" && process.arch === \"x64\" ? \"linux-x64-gnu\"\n    : process.platform === \"linux\" && process.arch === \"arm64\" ? \"linux-arm64-gnu\"\n      : `${process.platform}-${process.arch}`\n\n  for (const bin of BINARY_NAMES) {\n    candidates.push(path.resolve(runtimeDir, `${bin}.node`))\n    candidates.push(path.resolve(runtimeDir, `${bin}.${napiPlatform}.node`))\n    // 1 level: dist/ → package-root/native/ (published npm package)\n    candidates.push(path.resolve(runtimeDir, \"..\", \"native\", `${bin}.node`))\n    candidates.push(path.resolve(runtimeDir, \"..\", \"native\", `${bin}.${napiPlatform}.node`))\n    // cwd fallback (user project root)\n    candidates.push(path.resolve(process.cwd(), \"native\", `${bin}.node`))\n    candidates.push(path.resolve(process.cwd(), \"native\", `${bin}.${napiPlatform}.node`))\n    // 4 level: dist/ → package/ → domain/ → packages/ → repo-root/ (monorepo dev)\n    candidates.push(path.resolve(runtimeDir, \"..\", \"..\", \"..\", \"..\", \"native\", `${bin}.node`))\n    candidates.push(path.resolve(runtimeDir, \"..\", \"..\", \"..\", \"..\", \"native\", `${bin}.${napiPlatform}.node`))\n    // 3 level fallback\n    candidates.push(path.resolve(runtimeDir, \"..\", \"..\", \"..\", \"native\", `${bin}.node`))\n  }\n\n  return Array.from(new Set(candidates))\n}\n\nexport function resolveRuntimeDir(dir: string | undefined, importMetaUrl: string): string {\n  if (dir) return path.resolve(dir)\n  try {\n    return path.dirname(fileURLToPath(importMetaUrl))\n  } catch {\n    return process.cwd()\n  }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Hashing\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport function hashContent(content: string, algorithm: string = \"md5\", length?: number): string {\n  const hash = createHash(algorithm).update(content).digest(\"hex\")\n  return length ? hash.slice(0, length) : hash\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Error formatting\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport function formatErrorMessage(error: unknown): string {\n  if (error instanceof TwError) return error.toString()\n  if (error instanceof Error) return error.message\n  return String(error)\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// LRU Cache\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport class LRUCache<K, V> {\n  private capacity: number\n  private cache: Map<K, V>\n\n  constructor(capacity: number) {\n    this.capacity = capacity\n    this.cache = new Map()\n  }\n\n  get(key: K): V | undefined {\n    if (!this.cache.has(key)) return undefined\n    const value = this.cache.get(key)!\n    this.cache.delete(key)\n    this.cache.set(key, value)\n    return value\n  }\n\n  set(key: K, value: V): void {\n    if (this.cache.has(key)) {\n      this.cache.delete(key)\n    } else if (this.cache.size >= this.capacity) {\n      const firstKey = this.cache.keys().next().value\n      if (firstKey !== undefined) {\n        this.cache.delete(firstKey)\n      }\n    }\n    this.cache.set(key, value)\n  }\n\n  delete(key: K): boolean {\n    return this.cache.delete(key)\n  }\n\n  has(key: K): boolean {\n    return this.cache.has(key)\n  }\n\n  clear(): void {\n    this.cache.clear()\n  }\n\n  entries(): IterableIterator<[K, V]> {\n    return this.cache.entries()\n  }\n\n  get size(): number {\n    return this.cache.size\n  }\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Trace Utilities\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type { TraceSnapshot, TraceSummary } from \"./trace\"\nexport {\n  getHealthColor,\n  getModeColor,\n  formatMemory,\n  formatDuration,\n  calculateHealth,\n  getBuildTimeColor,\n  getMemoryColor,\n  createTraceSnapshot,\n  getPipelinePercentages,\n} from \"./trace\"\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Performance Telemetry\n// ─────────────────────────────────────────────────────────────────────────────\n\n\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Error Codes\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type { ErrorCode } from \"./error-codes\"\nexport { ERROR_CODES, getSuggestion, formatErrorCode } from \"./error-codes\"\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Tailwind Compatibility\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type { TailwindInfo } from \"./compatibility\"\nexport { detectTailwind, assertTailwindV4, getTailwindVersion, isTailwindV4 } from \"./compatibility\"\n\n// ── Native binding schemas (Zod boundary validation)\nexport {\n  NativeScanFileSchema, NativeScanResultSchema,\n  NativeAnalyzerReportSchema, NativeTransformResultSchema,\n  NativeCssCompileResultSchema, NativeWatchResultSchema,\n  NativeCacheEntrySchema, NativeCacheReadResultSchema,\n  safeParseNative, parseNative,\n} from './native-schemas'\n\n// ── ESM-safe runtime helpers ──────────────────────────────────────────────\nexport {\n  createEsmRequire,\n  getDirname,\n  getFilename,\n  resolveFromRoot,\n  tryRequire,\n  resolveNativeNodePath,\n} from \"./esmHelpers\"\n\n// ── Performance telemetry ────────────────────────────────────────────────────\nexport {\n  TelemetryCollector,\n  getGlobalTelemetry,\n  resetGlobalTelemetry,\n  createBuildTimer,\n  type BuildTelemetry,\n  type TelemetrySummary,\n  type BuildPhases,\n} from \"./telemetry\"\n\n// ── Config/JSON schema validation ─────────────────────────────────────────────\nexport {\n  ScanCacheSchema,\n  ScanCacheClassEntrySchema,\n  TailwindConfigSchema,\n  RegistryPluginEntrySchema,\n  RegistryFileSchema,\n  PackageJsonSchema,\n  parseJsonWithSchema,\n  parseJsonFileWithSchema,\n  type ScanCache,\n  type ScanCacheClassEntry,\n  type TailwindConfig,\n  type RegistryPluginEntry,\n  type RegistryFile,\n  type PackageJson,\n} from \"./configSchemas\"\n\n// ── Worker/bootstrap path resolution ─────────────────────────────────────────\nexport {\n  resolveWorkerPath,\n  resolveLoaderPath,\n  type WorkerPathOptions,\n  type WorkerPathResult,\n} from \"./workerResolver\"\n\n// ── Codegen helpers ───────────────────────────────────────────────────────────\nexport {\n  generateComponentCode,\n  generateStorybookStory,\n  generateClassRenameCodemod,\n  generateBarrelFile,\n  type ComponentCodegenOptions,\n} from \"./codegen\"\n\n// ── Native binary resolution (QA #1) ─────────────────────────────────────────\nexport {\n  resolveNativeBinary,\n  formatNativeNotFoundError,\n  type NativeResolutionResult,\n} from \"./native-resolution\"\n\n// ── Shared observability contract ────────────────────────────────────────────\nexport {\n  createObservabilityClient,\n  type ClassInspection,\n  type ClassProperty,\n  type ClassUsageLocation,\n  type BuildTrace,\n  type BuildPhaseTrace,\n  type DashboardMetrics,\n  type DashboardSummary,\n  type ObservabilityClient,\n} from \"./observability\"\n\nexport {\n  TW_STATE_STATIC_FILENAME,\n  extractStaticStateCss,\n  appendStaticStateCssToSafelist,\n  type TwStateConfigEntry,\n  type StaticStateCssInput,\n  type GeneratedStateRule,\n  type StaticStateExtractionResult,\n} from \"./staticStateExtractor\"\nexport { setGlobalLogFile } from \"./logger\"","/**\n * tailwind-styled-v5 — Native Bridge Loader\n *\n * Uses @tailwind-styled/shared for native binding resolution.\n * All functions require native Rust binding - no JS fallback.\n */\n\nimport { resolveNativeBinary, resolveRuntimeDir } from \"@tailwind-styled/shared\"\n\n// require() is safe here — tsup banner injects CJS-compatible require into ESM output.\n// See tsup.config.ts esbuildOptions banner for how this is set up.\nconst _loadNative = (path: string): unknown => require(path)\n\nexport interface ComponentMetadata {\n  component: string\n  tag: string\n  baseClass: string\n  subComponents: Record<string, { tag?: string; class: string }>\n}\n\nexport interface NativeRscResult {\n  isServer: boolean\n  needsClientDirective: boolean\n  clientReasons: string[]\n}\n\nconst log = (...args: unknown[]) => {\n  if (process.env.DEBUG?.includes(\"compiler:native\")) {\n    console.log(\"[compiler:native]\", ...args)\n  }\n}\n\n// ── Structured Type Definitions ─────────────────────────────────────────────\n\nexport interface ScanWorkspaceResult {\n  files: string[]\n  total_files: number\n  classes: string[]\n  unique_classes: number\n  duration_ms: number\n  errors: string[]\n}\n\nexport interface ScanFileResult {\n  file: string\n  classes: string[]\n  class_count: number\n  has_tw_usage: boolean\n  size_bytes: number\n  duration_ms: number\n}\n\nexport interface BatchExtractResult {\n  file: string\n  classes: string[]\n  contentHash: string\n  ok: boolean\n  error?: string\n}\n\nexport interface SafelistCheckResult {\n  matched: string[]\n  unmatched: string[]\n  safelistSize: number\n}\n\nexport interface PrefilterFileResult {\n  file: string\n  has_tw_usage: boolean\n  duration_ms: number\n  size_bytes: number\n  status: \"processed\" | \"skipped\" | \"error\"\n  error?: string\n}\n\nexport interface DeadCodeResult {\n  deadInCss: string[]\n  deadInSource: string[]\n  liveClasses: string[]\n  totalCssClasses: number\n  totalSourceClasses: number\n}\n\nexport interface ProcessedCssResult {\n  css: string\n  size_bytes: number\n  resolved_classes: string[]\n  unknown_classes: string[]\n}\n\nexport interface ContainerConfig {\n  tag: string\n  containerJson: string\n  containerName?: string\n  breakpoints: Array<{ key: string; classes: string }>\n}\n\nexport interface HoistResult {\n  code: string\n  hoisted: string[]\n  warnings: string[]\n}\n\nexport interface VariantTableResult {\n  id: string\n  tableJson: string\n  keys: string[]\n  defaultKey: string\n  combinations: number\n}\n\nexport interface ClassifyResult {\n  className: string\n  bucket: string\n  sortOrder: number\n}\n\nexport interface MergeResult {\n  declarationsJson: string\n  declarationString: string\n  count: number\n}\n\nexport interface ClassUsageItem {\n  className: string\n  usageCount: number\n  filesJson: string\n  bundleSizeBytes: number\n  isDeadCode: boolean\n}\n\nexport interface StateCssConfig {\n  tag: string\n  componentName: string\n  statesJson: string\n  sourceFile: string\n}\n\nexport interface GeneratedStateCss {\n  selector: string\n  declarations: string\n  cssRule: string\n  componentName: string\n  stateName: string\n}\n\n// ── Type Exports ────────────────────────────────────────────────────────────────\n\nexport interface NativeBridge {\n  // CSS Compiler - New Rust implementation\n  generateCssNative?: (classes: string[], theme_json: string) => string\n  getCacheStats?: () => [number, number]\n  clearThemeCache?: () => void\n  // Core transform\n  transformSource?: (source: string, opts?: Record<string, string>) => NativeTransformResult | null\n  extractClassesFromSource?: (source: string) => string[]\n  hasTwUsage?: (source: string) => boolean\n  isAlreadyTransformed?: (source: string) => boolean\n  // Phase 5: Scanner functions (snake_case from Rust)\n  scan_workspace?: (root: string, extensions?: string[]) => ScanWorkspaceResult\n  extract_classes_from_source?: (source: string) => string[]\n  batch_extract_classes?: (filePaths: string[]) => BatchExtractResult[]\n  check_against_safelist?: (classes: string[], safelist: string[]) => SafelistCheckResult\n  scan_file?: (filePath: string) => ScanFileResult\n  collect_files?: (root: string, extensions?: string[]) => string[]\n  walk_and_prefilter_source_files?: (root: string, extensions?: string[]) => PrefilterFileResult[]\n  generate_sub_component_types?: (root: string, outputPath?: string) => string\n  // Class Extractor\n  extractAllClasses?: (source: string) => string[]\n  parseClasses?: (raw: string) => Array<{ raw: string; type: string }>\n  // Application functions\n  extractComponentUsage?: (source: string) => Array<{ component: string; propsJson: string }>\n  normalizeAndDedupClasses?: (raw: string) => { normalized: string; duplicatesRemoved: number; uniqueCount: number }\n  diffClassLists?: (previous: string[], current: string[]) => { added: string[]; removed: string[]; unchanged: string[]; hasChanges: boolean }\n  batchExtractClasses?: (filePaths: string[]) => Array<{ file: string; classes: string[]; contentHash: string; ok: boolean; error?: string }>\n  checkAgainstSafelist?: (classes: string[], safelist: string[]) => { matched: string[]; unmatched: string[]; safelistSize: number }\n  // Batch 2\n  hoistComponents?: (source: string) => HoistResult\n  compileVariantTable?: (configJson: string) => VariantTableResult\n  classifyAndSortClasses?: (classes: string[]) => ClassifyResult[]\n  mergeCssDeclarations?: (cssChunks: string[]) => MergeResult\n  analyzeClassUsage?: (classes: string[], scanResultJson: string, css: string) => ClassUsageItem[]\n  analyzeRsc?: (source: string, filename: string) => {\n    isServer: boolean\n    needsClientDirective: boolean\n    clientReasons: string[]\n  }\n  analyzeClasses?: (\n    filesJson: string,\n    cwd: string,\n    flags: number\n  ) => {\n    css?: string\n    code: string\n    classes: string[]\n    changed: boolean\n    rscJson?: string\n    metadataJson?: string\n    safelist?: string[]\n  } | null\n  // CSS compilation\n  compileCss?: (classes: string[], prefix?: string | null) => { css: string; classes: string[] }\n  compileCssLightning?: (classes: string[]) => string\n  /** Post-process raw Tailwind-generated CSS dengan LightningCSS di Rust */\n  detectDeadCode?: (scanResultJson: string, css: string) => DeadCodeResult\n  processTailwindCssLightning?: (css: string) => ProcessedCssResult\n  processTailwindCssWithTargets?: (css: string, targets: string | null) => { css: string; size_bytes: number }\n  // Atomic CSS (atomic.rs)\n  parseAtomicClass?: (twClass: string) => string | null\n  generateAtomicCss?: (rulesJson: string) => string\n  toAtomicClasses?: (twClasses: string) => string\n  clearAtomicRegistry?: () => void\n  atomicRegistrySize?: () => number\n  // Impact analysis (impact_analysis.rs)\n  calculateImpact?: (impactJson: string) => string\n  calculateRisk?: (className: string, totalComponents: number) => string\n  calculateSavings?: (bundleSizeBytes: number, componentCount: number) => number\n  // Static state CSS pre-generation (state_css.rs)\n  extractTwStateConfigs?: (source: string, filename: string) => StateCssConfig[]\n  generateStaticStateCss?: (inputs: Array<{\n    tag: string\n    componentName: string\n    statesJson: string\n  }>, resolvedCss: string | null) => GeneratedStateCss[]\n  extractAndGenerateStateCss?: (source: string, filename: string) => GeneratedStateCss[]\n  /**\n   * Convert layout/utility class string ke CSS declarations.\n   * Dipakai oleh extractContainerCssFromSource sebagai Rust-accelerated fallback.\n   */\n  layoutClassesToCss?: (classes: string) => string\n  /**\n   * Hash string dengan algoritma tertentu, return n karakter pertama.\n   * Dipakai untuk generate deterministic container CSS IDs.\n   */\n  hashContent?: (input: string, algo: string, length: number) => string\n  /** Hapus dead CSS selectors + minify via Lightning CSS. */\n  eliminateDeadCss?: (css: string, deadClasses: string[]) => string\n  /** Dead code detection + strip + Lightning CSS minify dalam satu call. */\n  optimizeCss?: (css: string) => string\n  /** Extract tw container configs dari source untuk static @container CSS generation. */\n  extractTwContainerConfigs?: (source: string) => Array<{\n    tag: string\n    containerJson: string\n    containerName?: string\n    breakpoints: Array<{ key: string; classes: string }>\n  }>\n  \n  // Phase 5.1: Cache Management (9 functions)\n  get_cache_statistics?: () => string  // Returns JSON\n  clear_all_caches?: () => void\n  clear_parse_cache?: () => void\n  clear_resolve_cache?: () => void\n  clear_compile_cache?: () => void\n  clear_css_gen_cache?: () => void\n  get_cache_optimization_hints?: (hit_rate_percent: number, memory_used_mb: number) => string  // Returns JSON\n  estimate_optimal_cache_config_native?: (total_budget_mb: number, workload_type: string) => string  // Returns JSON\n  cache_read?: (cache_path: string) => { entries_json: string }\n  cache_write?: (cache_path: string, entries: Array<{ file: string; content_hash: string; classes: string[]; mtime_ms: number; size_bytes: number }>) => boolean\n  cache_priority?: (mtime_ms: number, size_bytes: number, hit_count: number) => number\n  \n  // Phase 5.1: Theme Resolution Extended (7 functions)\n  resolve_variants?: (configJson: string) => string  // Returns JSON\n  validate_variant_config?: (configJson: string) => string  // Returns JSON\n  resolve_cascade?: (baseThemeJson: string, overridesJson: string) => string  // Returns JSON\n  resolve_class_names?: (classNames: string[], themeJson: string) => string  // Returns JSON\n  resolve_conflict_group?: (groupName: string, themeJson: string) => string  // Returns JSON\n  resolve_theme_value?: (keyPath: string, themeJson: string) => string | null\n  resolve_simple_variants?: (configJson: string) => string  // Returns JSON\n  \n  // Phase 5.1: Streaming & Incremental Processing (8 functions)\n  process_file_change?: (fileChangeJson: string) => string  // Returns JSON\n  compute_incremental_diff?: (oldScanJson: string, newScanJson: string) => string  // Returns JSON\n  create_fingerprint?: (filePath: string, fileContent: string) => string  // Returns JSON\n  inject_state_hash?: (css: string, stateHash: string) => string  // Returns JSON\n  prune_stale_entries?: (maxAgeSeconds: number, maxEntries: number) => string  // Returns JSON\n  rebuild_workspace_result?: (rootDir: string, extensions?: string[]) => string  // Returns JSON\n  scan_file_native?: (filePath: string, fileContent: string) => string  // Returns JSON\n  scan_files_batch_native?: (filesJson: string) => string  // Returns JSON\n  \n  // Phase 5.2: CSS Compilation (12 functions)\n  generate_css?: (rule_json: string, minify?: boolean | null) => string\n  generate_css_batch?: (rules_json: string, minify?: boolean | null) => string\n  compile_class?: (input: string) => string  // Returns JSON\n  compile_classes?: (inputs: string[]) => string  // Returns JSON\n  compile_to_css?: (input: string, minify: boolean) => string\n  compile_to_css_batch?: (inputs: string[], minify: boolean) => string\n  minify_css?: (css: string) => string\n  compile_animation?: (animationName: string, from: string, to: string) => string  // Returns JSON\n  compile_keyframes?: (name: string, stopsJson: string) => string  // Returns JSON\n  compile_theme?: (tokensJson: string, themeName: string, prefix: string) => string  // Returns JSON\n  tw_merge?: (classString: string) => string\n  tw_merge_many?: (classStrings: string[]) => string\n  tw_merge_with_separator?: (classString: string, options: Record<string, unknown>) => string\n  tw_merge_many_with_separator?: (classStrings: string[], options: Record<string, unknown>) => string\n  tw_merge_raw?: (classLists: string[]) => string\n  \n  // Phase 5.2: ID Registry (16 functions)\n  id_registry_create?: () => number\n  id_registry_generate?: (handle: number, name: string) => number\n  id_registry_lookup?: (handle: number, name: string) => number\n  id_registry_next?: (handle: number) => number\n  id_registry_destroy?: (handle: number) => void\n  id_registry_reset?: (handle: number) => void\n  id_registry_snapshot?: (handle: number) => string  // Returns JSON\n  id_registry_active_count?: () => number\n  register_property_name?: (propertyName: string) => number\n  register_value_name?: (valueName: string) => number\n  property_id_to_string?: (propertyId: number) => string\n  value_id_to_string?: (valueId: number) => string\n  reverse_lookup_property?: (propertyId: number) => string\n  reverse_lookup_value?: (valueId: number) => string\n  id_registry_export?: (handle: number) => string\n  id_registry_import?: (importedData: string) => number\n  \n  // Phase 5.3: Redis Integration (40 functions)\n  redis_ping?: () => string\n  redis_get?: (key: string) => string\n  redis_set?: (key: string, value: string, ttl_seconds?: number) => string\n  redis_delete?: (key: string) => number\n  redis_exists?: (key: string) => number\n  redis_mget?: (keys: string[]) => string  // Returns JSON\n  redis_mset?: (pairs: Array<[string, string]>) => string\n  redis_flush_db?: () => number\n  redis_flush_all?: () => number\n  redis_pool_connect?: (host: string, port: number, pool_size?: number) => string\n  redis_pool_stats?: () => string  // Returns JSON\n  redis_pool_reconnect?: () => string\n  redis_enable_cluster?: (initial_nodes: string[]) => string  // Returns JSON\n  redis_disable_cluster?: () => string\n  redis_cluster_status?: () => string  // Returns JSON\n  redis_subscribe?: (channel: string) => string\n  redis_publish?: (channel: string, message: string) => number\n  redis_expiration_set?: (key: string, ttl_seconds: number) => number\n  redis_expiration_get?: (key: string) => string  // Returns JSON\n  redis_info?: () => string\n  redis_monitor?: () => string\n  redis_cache_size?: () => number\n  redis_cache_key_count?: () => number\n  redis_cache_clear?: () => number\n  redis_cache_hit_rate?: () => number\n  redis_enable_persistence?: (mode: string) => string\n  redis_disable_persistence?: () => string\n  redis_snapshot?: () => string\n  redis_memory_stats?: () => string\n  redis_optimize_memory?: () => number\n  redis_set_eviction_policy?: (policy: string) => string\n  redis_get_eviction_policy?: () => string\n  redis_replicate?: (target_host: string, target_port: number) => number\n  redis_replication_status?: () => string\n  redis_cache_sync?: (peers: string[]) => number\n  redis_enable_cache_warming?: (key_pattern: string) => string\n  redis_disable_cache_warming?: () => string\n  redis_diagnose?: () => string\n  \n  // Phase 5.4: Watch System & File Monitoring (20 functions)\n  start_watch?: (root_path: string, patterns?: string[]) => number\n  poll_watch_events?: (handle: number, timeout_ms?: number) => string  // Returns JSON\n  stop_watch?: (handle: number) => number\n  watch_add_pattern?: (handle: number, pattern: string) => string\n  watch_remove_pattern?: (handle: number, pattern: string) => string\n  watch_get_active_handles?: () => string  // Returns JSON\n  watch_clear_all?: () => number\n  watch_event_type_to_string?: (event_type_code: number) => string\n  is_watch_running?: (handle: number) => boolean\n  get_watch_stats?: () => string  // Returns JSON\n  watch_pause?: (handle: number) => string\n  watch_resume?: (handle: number) => string\n  scan_cache_optimizations?: () => string  // Returns JSON\n  get_plugin_hooks?: () => string  // Returns JSON\n  register_plugin_hook?: (hook_name: string, handler_id: string) => string\n  unregister_plugin_hook?: (hook_name: string, handler_id: string) => string\n  emit_plugin_hook?: (hook_name: string, data_json: string) => string\n  get_compilation_metrics?: () => string  // Returns JSON\n  reset_compilation_metrics?: () => string\n  validate_css_output?: (css: string) => string  // Returns JSON\n  get_compiler_diagnostics?: () => string  // Returns JSON\n\n  // ── Cache Management (napi_bridge_cache.rs) ────────────────────────────────\n  configureCacheBackend?: (configJson: string) => string\n  getRecommendedCacheConfig?: (workloadType: string) => string\n  clearAllCachesNapi?: () => void\n  clearResolveCacheNapi?: () => void\n  clearCompileCacheNapi?: () => void\n  clearCssGenCacheNapi?: () => void\n  getResolverPoolStats?: () => string\n  clearResolverPool?: () => string\n  resolveColorCached?: (themeId: number, color: string, configJson: string) => string\n  resolveSpacingCached?: (themeId: number, spacing: string, configJson: string) => string\n  resolveFontSizeCached?: (themeId: number, size: string, configJson: string) => string\n  resetResolverPoolStats?: () => void\n  getCacheOptimizationHints?: () => string\n  estimateStreamingBatchSize?: (targetMemoryMb: number) => string\n\n  // ── Parsing (napi_bridge_parsing.rs) ──────────────────────────────────────\n  parseClass?: (input: string) => string\n  compileClassNapi?: (input: string) => string\n  getParseStats?: () => string\n  clearParseCacheNapi?: () => void\n\n  // ── Theme Parsing (napi_bridge_theme_parsing.rs) ───────────────────────────\n  parseColorsNapi?: (colorsJson: string) => string | Record<string, string>\n  parseSpacingNapi?: (spacingJson: string) => string | Record<string, string>\n  parseTransformNapi?: (transformJson: string) => string | Record<string, string>\n  normalizeColorNapi?: (color: string, opacity: string) => string\n  sanitizeColorNapi?: (color: string) => string\n  splitRgbaNapi?: (color: string) => string | { r: number; g: number; b: number; a: number }\n  validateColorsNapi?: (colorsJson: string) => boolean\n  validateBreakpointsNapi?: (breakpointsJson: string) => boolean\n  runHealthCheck?: () => void\n\n  // ── Watch (napi_bridge_watch.rs) ───────────────────────────────────────────\n  watchFiles?: (rootDir: string, optionsJson?: string | null) => string\n  stopWatching?: (handleId: number) => string\n  getWatchEvents?: (handleId: number, maxEvents?: number | null) => string\n  getWatchPerformance?: () => string\n  clearWatchStats?: () => string\n  getActiveWatches?: () => number\n  setWatchMetrics?: (metricName: string, value: string) => string\n  setWatchAggregation?: (aggregationType: string) => string\n\n  // ── Week 6 Optimization (week6_api.rs) ────────────────────────────────────\n  getOptimizationRecommendations?: (hitRate: number, memoryMb: number, classCount: number) => string\n  estimateOptimalBatchSize?: (totalClasses: number, memoryAvailableMb: number) => number\n  predictMemoryUsage?: (uniqueClasses: number, avgClassSizeBytes: number) => number\n  recommendCachingStrategy?: (isSsr: boolean, memoryConstraintMb: number) => string\n  benchmarkStreamingVsBuffered?: (classCount: number) => string\n  getWeek6OptimizationStatus?: () => string\n\n  // ── Analysis & Memory Profiling (napi_bridge_analysis.rs) ──────────────────\n  getWeek6FeaturesStatus?: () => string\n  getMemoryStatsNative?: () => string\n  getMemoryRecommendationsNative?: () => string\n  estimateOptimalCacheConfigNative?: (workloadType: string, expectedEntries: number) => string\n  resetMemoryStats?: () => void\n\n  // ── Scan Cache (scan_cache_api.rs) ────────────────────────────────────────\n  scanCacheGet?: (filePath: string, contentHash: string) => string[] | null\n  scanCachePut?: (filePath: string, contentHash: string, classes: string[], mtimeMs: number, size: number) => void\n  scanCacheInvalidate?: (filePath: string) => void\n  scanCacheStats?: () => { size: number }\n\n  // ── Missing Theme, Redis, and Utility Functions ──────────────────────────\n  resolveColor?: (color: string) => string\n  resolveSpacing?: (spacing: string) => string\n  resolveFontSize?: (size: string) => string\n  resolveBreakpoint?: (breakpoint: string) => string\n  redisExpire?: (key: string, ttlSeconds: number) => string\n  redisTtl?: (key: string) => string\n  redisGetConfig?: () => string\n  redisShutdown?: () => string\n  redisSyncNodes?: () => string\n  resetCacheStats?: () => void\n}\n\nexport interface NativeTransformResult {\n  code: string\n  classes: string[]\n  changed: boolean\n  rscJson?: string\n  metadataJson?: string\n}\n\nexport interface ClassExtractResult {\n  classes: string[]\n  component_names: string[]\n  has_tw_usage: boolean\n  has_use_client: boolean\n  imports: string[]\n}\n\nconst NATIVE_UNAVAILABLE_MESSAGE =\n  \"[tailwind-styled/compiler v5] Native binding is required but not available.\\n\" +\n  \"This package requires native Rust bindings. There is no JavaScript fallback.\\n\" +\n  \"Please ensure:\\n\" +\n  \"  1. The native module is properly installed\\n\" +\n  \"  2. You have run: npm run build:rust (or use prebuilt binary)\\n\" +\n  \"\\n\" +\n  \"For help, see: https://tailwind-styled.dev/docs/install\"\n\n// ── Native Bridge - Factory Pattern\n// ─────────────────────────────────────────────────────────────────────────────\n\nlet nativeBridge: NativeBridge | null = null\nlet bridgeLoadAttempted = false\nlet bridgeLoadError: Error | null = null\n\nconst isValidNativeBridge = (mod: unknown): mod is NativeBridge => {\n  const m = mod as Partial<NativeBridge>\n  return !!(\n    typeof m.transformSource === \"function\" ||\n    typeof m.extractAllClasses === \"function\" ||\n    typeof m.hasTwUsage === \"function\"\n  )\n}\n\nexport const getNativeBridge = (): NativeBridge => {\n  if (nativeBridge) {\n    return nativeBridge\n  }\n\n  if (bridgeLoadAttempted) {\n    if (bridgeLoadError) {\n      throw bridgeLoadError\n    }\n    throw new Error(NATIVE_UNAVAILABLE_MESSAGE)\n  }\n\n  bridgeLoadAttempted = true\n\n  try {\n    const runtimeDir = resolveRuntimeDir(undefined, import.meta.url)\n    \n    // Use shared's native resolution\n    const result = resolveNativeBinary(runtimeDir)\n\n    if (result.path && result.path.endsWith(\".node\")) {\n      try {\n        const binding = _loadNative(result.path) as NativeBridge\n        if (isValidNativeBridge(binding)) {\n          const toCamelCase = (str: string): string => {\n            return str.replace(/_([a-z0-9])/g, (_, g) => g.toUpperCase())\n          }\n          nativeBridge = new Proxy(binding, {\n            get(target, prop) {\n              if (typeof prop === \"string\") {\n                if (prop in target) {\n                  return target[prop as keyof typeof target]\n                }\n                const camelKey = toCamelCase(prop)\n                if (camelKey in target) {\n                  const val = target[camelKey as keyof typeof target]\n                  if (typeof val === \"function\") {\n                    return (val as Function).bind(target)\n                  }\n                  return val\n                }\n                const napiKey = `${camelKey}Napi`\n                if (napiKey in target) {\n                  const val = target[napiKey as keyof typeof target]\n                  if (typeof val === \"function\") {\n                    return (val as Function).bind(target)\n                  }\n                  return val\n                }\n                const napiInnerKey = `${camelKey}NapiInner`\n                if (napiInnerKey in target) {\n                  const val = target[napiInnerKey as keyof typeof target]\n                  if (typeof val === \"function\") {\n                    return (val as Function).bind(target)\n                  }\n                  return val\n                }\n              }\n              return target[prop as keyof typeof target]\n            }\n          }) as NativeBridge\n          log(\"Native bridge loaded successfully and proxy-wrapped from:\", result.path)\n          return nativeBridge\n        }\n      } catch (e) {\n        log(\"Failed to require native binding:\", e)\n      }\n    }\n\n    throw new Error(`${NATIVE_UNAVAILABLE_MESSAGE}\\n\\nTried paths: ${result.tried.join(\"\\n\")}`)\n  } catch (err) {\n    bridgeLoadError = err instanceof Error ? err : new Error(String(err))\n    log(\"Failed to load native bridge:\", bridgeLoadError.message)\n    throw bridgeLoadError\n  }\n}\n\nexport const resetNativeBridgeCache = (): void => {\n  nativeBridge = null\n  bridgeLoadAttempted = false\n  bridgeLoadError = null\n  log(\"Native bridge cache reset\")\n}\n\n// ── Adaptor for native results\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport const adaptNativeResult = (\n  raw: NativeTransformResult\n): {\n  code: string\n  classes: string[]\n  changed: boolean\n  rsc?: NativeRscResult\n  metadata?: ComponentMetadata[]\n} => {\n  return {\n    code: raw.code ?? \"\",\n    classes: raw.classes ?? [],\n    changed: raw.changed ?? false,\n    rsc: raw.rscJson ? JSON.parse(raw.rscJson) : undefined,\n    metadata: raw.metadataJson ? JSON.parse(raw.metadataJson) : undefined,\n  }\n}\n\n// ── Eager init — load native bridge saat module dimuat, bukan saat request pertama\n// Mencegah crash di Turbopack dev mode karena lazy init mid-request\n// ─────────────────────────────────────────────────────────────────────────────\nif (typeof process !== \"undefined\" && !bridgeLoadAttempted) {\n  try {\n    getNativeBridge()\n  } catch {\n    // Sudah di-capture di bridgeLoadError — akan di-throw saat dipanggil pertama kali\n  }\n}\n\n// ── Re-export all 63 wrapper functions from nativeBridgeWrappers\n// These provide complete type safety, error handling, and JSDoc documentation\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport {\n  // Redis Cache Functions (40)\n  redis_pool_connect,\n  redis_pool_stats,\n  redis_pool_reconnect,\n  redis_ping,\n  redis_get,\n  redis_set,\n  redis_delete,\n  redis_exists,\n  redis_mget,\n  redis_mset,\n  redis_flush_db,\n  redis_flush_all,\n  redis_cache_size,\n  redis_cache_key_count,\n  redis_cache_clear,\n  redis_cache_hit_rate,\n  redis_info,\n  redis_monitor,\n  redis_enable_cluster,\n  redis_disable_cluster,\n  redis_cluster_status,\n  redis_expiration_set,\n  redis_expiration_get,\n  redis_subscribe,\n  redis_publish,\n  redis_enable_persistence,\n  redis_disable_persistence,\n  redis_snapshot,\n  redis_replicate,\n  redis_replication_status,\n  redis_enable_cache_warming,\n  redis_disable_cache_warming,\n  redis_cache_sync,\n  redis_set_eviction_policy,\n  redis_get_eviction_policy,\n  redis_memory_stats,\n  redis_optimize_memory,\n  redis_diagnose,\n  // Watch System Functions (20)\n  start_watch,\n  poll_watch_events,\n  stop_watch,\n  watch_add_pattern,\n  watch_remove_pattern,\n  watch_pause,\n  watch_resume,\n  is_watch_running,\n  get_watch_stats,\n  watch_get_active_handles,\n  watch_clear_all,\n  register_plugin_hook,\n  unregister_plugin_hook,\n  emit_plugin_hook,\n  get_plugin_hooks,\n  // ID Registry Functions (16)\n  id_registry_create,\n  id_registry_generate,\n  id_registry_lookup,\n  id_registry_next,\n  id_registry_destroy,\n  id_registry_reset,\n  id_registry_snapshot,\n  id_registry_active_count,\n  register_property_name,\n  register_value_name,\n  property_id_to_string,\n  value_id_to_string,\n  reverse_lookup_property,\n  reverse_lookup_value,\n  id_registry_export,\n  id_registry_import,\n  // Incremental Compilation Functions (8)\n  process_file_change,\n  compute_incremental_diff,\n  create_fingerprint,\n  inject_state_hash,\n  prune_stale_entries,\n  rebuild_workspace_result,\n  scan_files_batch_native,\n  // Theme Resolution Functions (7)\n  resolve_variants,\n  validate_variant_config,\n  resolve_cascade,\n  resolve_class_names,\n  resolve_conflict_group,\n  resolve_theme_value,\n  resolve_simple_variants,\n  generate_css,\n  generate_css_batch,\n  resolve_color_cached,\n  resolve_spacing_cached,\n  resolve_font_size_cached,\n  reset_resolver_pool_stats,\n  get_week6_features_status,\n  get_memory_stats_native,\n  get_memory_recommendations_native,\n  estimate_optimal_cache_config_native,\n  reset_memory_stats,\n} from \"./nativeBridgeWrappers\"","/**\n * Compiler Sub-entry Point\n * \n * Exports CSS generation and compilation functionality.\n * - CSS generation with caching\n * - Compilation of classes to CSS\n * - ID registry management\n * - Streaming and incremental processing\n */\n\nexport {\n  generateCssNative,\n  getCacheStats,\n  clearThemeCache,\n  resetCacheStats,\n} from './cssGeneratorNative'\n\nexport {\n  compileCssNative2,\n  compileCssLightning,\n  extractTwStateConfigsNative,\n  generateStaticStateCssNative,\n  extractAndGenerateStateCssNative,\n  layoutClassesToCss,\n  hashContent,\n  extractTwContainerConfigs,\n  parseAtomicClass,\n  generateAtomicCss,\n  toAtomicClasses,\n  clearAtomicRegistry,\n  atomicRegistrySize,\n  type ContainerConfig,\n  type StateCssConfig,\n  type GeneratedStateCss,\n} from './compilationNative'\n\nexport {\n  generateCss,\n  generateCssBatch,\n  compileClass,\n  compileClasses,\n  compileToCss,\n  compileToCssBatch,\n  minifyCss,\n  compileAnimation,\n  compileKeyframes,\n  compileTheme,\n  twMerge,\n  twMergeMany,\n  twMergeWithSeparator,\n  twMergeManyWithSeparator,\n  twMergeRaw,\n  type CompiledCssRule,\n  type CompiledAnimation,\n  type CompiledTheme,\n  type CssCompileResult,\n  type TwMergeOptions,\n} from './cssCompilationNative'\n\nexport {\n  idRegistryCreate,\n  idRegistryGenerate,\n  idRegistryLookup,\n  idRegistryNext,\n  idRegistryDestroy,\n  idRegistryReset,\n  idRegistrySnapshot,\n  idRegistryActiveCount,\n  registerPropertyName,\n  registerValueName,\n  propertyIdToString,\n  valueIdToString,\n  reverseLookupProperty,\n  reverseLookupValue,\n  idRegistryExport,\n  idRegistryImport,\n  type RegistrySnapshot,\n} from './idRegistryNative'\n\nexport {\n  processFileChange,\n  computeIncrementalDiff,\n  createFingerprint,\n  injectStateHash,\n  pruneStaleCacheEntries,\n  rebuildWorkspaceResult,\n  scanFileNative,\n  scanFilesBatchNative,\n  type FileChangeEvent,\n  type ProcessedFileChange,\n  type FileDiff,\n  type FileFingerprint,\n  type IncrementalDiffResult,\n  type StateInjectionResult,\n  type PruneResult,\n  type RebuildWorkspaceResult,\n} from './streamingNative'\n\nexport { runCssPipeline } from './tailwindEngine'\n","/**\n * Parser Sub-entry Point\n * \n * Exports class parsing and extraction functionality.\n * - Tailwind class parsing\n * - Class extraction from source\n * - Class normalization and deduplication\n * - Component analysis\n */\n\nimport { getNativeBridge } from '../nativeBridge'\n\n// ============================================================================\n// PARSING FUNCTIONS\n// ============================================================================\n\nexport const parseClasses = (raw: string): Array<{ raw: string; type: string }> => {\n  const native = getNativeBridge()\n  if (!native?.parseClasses) {\n    throw new Error('FATAL: Native binding \\'parseClasses\\' is required but not available.')\n  }\n  return native.parseClasses(raw) || []\n}\n\nexport const parseClass = (input: string): Record<string, unknown> => {\n  const native = getNativeBridge()\n  if (!native?.parseClass) {\n    throw new Error('FATAL: Native binding \\'parseClass\\' is required but not available.')\n  }\n  const result = native.parseClass(input)\n  return typeof result === 'string' ? JSON.parse(result) : result\n}\n\n// ============================================================================\n// CLASS EXTRACTION\n// ============================================================================\n\nexport const extractAllClasses = (source: string): string[] => {\n  const native = getNativeBridge()\n  if (!native?.extractAllClasses) {\n    throw new Error('FATAL: Native binding \\'extractAllClasses\\' is required but not available.')\n  }\n  return native.extractAllClasses(source) || []\n}\n\nexport const extractClassesFromSource = (source: string): string => {\n  const native = getNativeBridge()\n  if (!native?.extractClassesFromSource) {\n    throw new Error('FATAL: Native binding \\'extractClassesFromSource\\' is required but not available.')\n  }\n  const result = native.extractClassesFromSource(source)\n  return Array.isArray(result) ? result.join(' ') : String(result || '')\n}\n\nexport const astExtractClasses = (source: string, _filename: string) => {\n  const native = getNativeBridge()\n  if (!native?.extractClassesFromSource) {\n    throw new Error('FATAL: Native binding \\'extractClassesFromSource\\' is required but not available.')\n  }\n  return native.extractClassesFromSource(source) || []\n}\n\n// ============================================================================\n// CLASS NORMALIZATION & MERGING\n// ============================================================================\n\nexport const normalizeClasses = (raw: string): string => {\n  const result = normalizeAndDedupClasses(raw)\n  return result?.normalized || ''\n}\n\nexport const mergeClassesStatic = (classes: string): string => {\n  const result = normalizeAndDedupClasses(classes)\n  return result?.normalized || ''\n}\n\nexport const normalizeAndDedupClasses = (raw: string) => {\n  const native = getNativeBridge()\n  if (!native?.normalizeAndDedupClasses) {\n    throw new Error('FATAL: Native binding \\'normalizeAndDedupClasses\\' is required but not available.')\n  }\n  const result = native.normalizeAndDedupClasses(raw)\n  return result || { normalized: '', duplicatesRemoved: 0, uniqueCount: 0 }\n}\n\n// ============================================================================\n// COMPONENT ANALYSIS\n// ============================================================================\n\nexport const extractComponentUsage = (source: string): Array<{ component: string; propsJson: string }> => {\n  const native = getNativeBridge()\n  if (!native?.extractComponentUsage) {\n    throw new Error('FATAL: Native binding \\'extractComponentUsage\\' is required but not available.')\n  }\n  return native.extractComponentUsage(source) || []\n}\n\n// ============================================================================\n// BATCH OPERATIONS\n// ============================================================================\n\nexport const batchExtractClasses = (filePaths: string[]) => {\n  const native = getNativeBridge()\n  if (!native?.batchExtractClasses) {\n    throw new Error('FATAL: Native binding \\'batchExtractClasses\\' is required but not available.')\n  }\n  return native.batchExtractClasses(filePaths) || []\n}\n\nexport const checkAgainstSafelist = (classes: string[], safelist: string[]) => {\n  const native = getNativeBridge()\n  if (!native?.checkAgainstSafelist) {\n    throw new Error('FATAL: Native binding \\'checkAgainstSafelist\\' is required but not available.')\n  }\n  return native.checkAgainstSafelist(classes, safelist) || { matched: [], unmatched: [], safelistSize: 0 }\n}\n\n// ============================================================================\n// DIFF & MERGING\n// ============================================================================\n\nexport const diffClassLists = (previous: string[], current: string[]) => {\n  const native = getNativeBridge()\n  if (!native?.diffClassLists) {\n    throw new Error('FATAL: Native binding \\'diffClassLists\\' is required but not available.')\n  }\n  return native.diffClassLists(previous, current) || { added: [], removed: [], unchanged: [], hasChanges: false }\n}\n\n// Re-export types if any\nexport type { ClassExtractResult, ComponentMetadata } from '../nativeBridge'\n","/**\n * Analyzer Sub-entry Point\n * \n * Exports analysis and optimization functionality.\n * - CSS and class analysis\n * - Dead code detection\n * - Theme resolution and validation\n * - Code classification and optimization\n */\n\nexport {\n  detectDeadCode,\n  analyzeClassUsageNative,\n  analyzeClassesNative,\n  analyzeRscNative,\n  optimizeCssNative,\n  processTailwindCssLightning,\n  eliminateDeadCssNative,\n  hoistComponentsNative,\n  compileVariantTableNative,\n  classifyAndSortClassesNative,\n  mergeCssDeclarationsNative,\n  getWeek6FeaturesStatus,\n  getMemoryStatsNative,\n  getMemoryRecommendationsNative,\n  estimateOptimalCacheConfigNative,\n  resetMemoryStats,\n  type DeadCodeResult,\n  type ClassUsageItem,\n  type ProcessedCssResult,\n  type HoistResult,\n  type VariantTableResult,\n  type ClassifyResult,\n  type MergeResult,\n  type MemoryStats,\n  type MemoryRecommendations,\n  type OptimalCacheConfigAnalysis,\n  type Week6FeaturesStatus,\n} from './analyzerNative'\n\nexport {\n  resolveVariants,\n  validateThemeConfig,\n  resolveCascade,\n  resolveClassNames,\n  resolveConflictGroup,\n  resolveThemeValue,\n  resolveSimpleVariants,\n  type ThemeValidationResult,\n  type ResolvedVariantConfig,\n  type ThemeCascadeResult,\n  type ResolvedClassName,\n  type ConflictGroupInfo,\n} from './themeResolutionNative'\n\nexport {\n  scanWorkspace,\n  extractClassesFromSourceNative,\n  batchExtractClassesNative,\n  checkAgainstSafelistNative,\n  scanFile,\n  collectFiles,\n  walkAndPrefilterSourceFiles,\n  generateSubComponentTypes,\n  type ScanWorkspaceResult,\n  type ScanFileResult,\n  type BatchExtractResult,\n  type SafelistCheckResult,\n  type PrefilterFileResult,\n} from './scannerNative'\n","/**\n * Cache Sub-entry Point\n * \n * Exports cache management functionality.\n * - Cache statistics retrieval\n * - Cache clearing operations\n * - Cache optimization\n * - Cache configuration\n */\n\nexport {\n  getCacheStatistics,\n  clearAllCaches,\n  clearParseCache,\n  clearResolveCache,\n  clearCompileCache,\n  clearCssGenCache,\n  getCacheOptimizationHints,\n  estimateOptimalCacheConfig,\n  cacheRead,\n  cacheWrite,\n  cachePriority,\n  getResolverPoolStats,\n  clearResolverPool,\n  resolveColorCached,\n  resolveSpacingCached,\n  resolveFontSizeCached,\n  resetResolverPoolStats,\n  type CacheOptimizationHints,\n  type OptimalCacheConfig,\n  type CacheStatistics,\n  type ResolverPoolStatsResult,\n} from './cacheNative'\n","/**\n * Redis Sub-entry Point\n * \n * Exports Redis and distributed cache functionality.\n * - Redis operations (get, set, delete, etc.)\n * - Redis pool management\n * - Cluster management\n * - Cache synchronization\n * - Persistence management\n */\n\nexport {\n  redisPing,\n  redisGet,\n  redisSet,\n  redisDelete,\n  redisExists,\n  redisMget,\n  redisMset,\n  redisFlushDb,\n  redisFlushAll,\n  redisPoolConnect,\n  redisPoolStats,\n  redisPoolReconnect,\n  redisEnableCluster,\n  redisDisableCluster,\n  redisClusterStatus,\n  redisSubscribe,\n  redisPublish,\n  redisExpirationSet,\n  redisExpirationGet,\n  redisInfo,\n  redisMonitor,\n  redisCacheSize,\n  redisCacheKeyCount,\n  redisCacheClear,\n  redisCacheHitRate,\n  redisEnablePersistence,\n  redisDisablePersistence,\n  redisSnapshot,\n  redisMemoryStats,\n  redisOptimizeMemory,\n  redisSetEvictionPolicy,\n  redisGetEvictionPolicy,\n  redisReplicate,\n  redisReplicationStatus,\n  redisCacheSync,\n  redisEnableCacheWarming,\n  redisDisableCacheWarming,\n  redisDiagnose,\n  type RedisCacheConfig,\n  type RedisPoolStats,\n  type RedisClusterNode,\n  type RedisClusterStatus,\n  type KeyExpiration,\n  type PubSubMessage,\n  type PoolInfo,\n} from './redisNative'\n","/**\n * Watch Sub-entry Point\n * \n * Exports file watching and compilation monitoring functionality.\n * - File system watching\n * - Watch event polling and management\n * - Watch statistics\n * - Plugin hooks\n * - Compilation metrics\n */\n\nexport {\n  startWatch,\n  pollWatchEvents,\n  stopWatch,\n  watchAddPattern,\n  watchRemovePattern,\n  watchGetActiveHandles,\n  watchClearAll,\n  watchEventTypeToString,\n  isWatchRunning,\n  getWatchStats,\n  watchPause,\n  watchResume,\n  scanCacheOptimizations,\n  getPluginHooks,\n  registerPluginHook,\n  unregisterPluginHook,\n  emitPluginHook,\n  getCompilationMetrics,\n  resetCompilationMetrics,\n  validateCssOutput,\n  getCompilerDiagnostics,\n  type WatchEvent,\n  type WatchHandle,\n  type WatchStats,\n} from './watchSystemNative'\n","/**\n * tailwind-styled-v4 — Route class attribution via static import graph\n *\n * Per-route CSS splitting yang sesungguhnya: bukan cuma \"semua classes jadi\n * satu bucket __global\", tapi exclusive-per-route classes vs shared classes.\n *\n * KENAPA INI BISA DIBANGUN SEKARANG (sebelumnya ditandai \"butuh import-graph\n * tracing yang belum ada\"): scanWorkspace() Rust SUDAH balikin classes\n * per-file (ScannedFile { file, classes, hash }) — yang belum ada cuma\n * relasi \"file A import file B\"-nya. Itu yang dibangun di sini, di sisi TS,\n * pakai static regex-based import extractor + resolusi tsconfig `paths`.\n * Tidak perlu native binding baru / rebuild Rust.\n *\n * ALGORITMA:\n *   1. Build adjacency list (file -> Set<file yang di-import>), regex-based,\n *      dibatasi ke file yang ada di dalam srcDir saja (bare/node_modules\n *      imports diabaikan — di luar scope atribusi route).\n *   2. Entry point per route = file yang match `app/.../page.{tsx,ts,jsx,js}`\n *      (sama heuristik dengan fileToRoute() di index.ts).\n *   3. BFS dari tiap entry -> reachable file set untuk route itu.\n *   4. Reverse: untuk tiap file, hitung berapa route yang bisa menjangkaunya.\n *      - Tepat 1 route -> classes file itu eksklusif ke route tersebut.\n *      - 0 atau 2+ route (termasuk layout/loading/error/template/\n *        not-found/default, dan file yang gak ke-reach sama sekali —\n *        misal dead code atau import yang gak ke-detect static parser\n *        ini, contoh: import dinamis berbasis variable) -> fallback ke\n *        \"__global\". Default selalu aman (gak pernah salah atribusi ke\n *        route yang salah), cuma bisa under-split di dynamic-import edge\n *        case.\n *\n * KETERBATASAN YANG DISADARI (belum di-handle, scope sengaja dibatasi):\n *   - Nested layout HARUSNYA cuma global utk subtree-nya (bukan whole app),\n *     tapi di sini SEMUA layout/loading/error/template selalu -> __global.\n *     Konservatif (over-share ke global), tidak pernah salah, tapi belum\n *     \"true\" subtree-scoped splitting.\n *   - Dynamic import dengan path non-literal (`import(someVar)`) tidak bisa\n *     di-resolve static parser ini — file tujuan jadi unreachable -> jatuh\n *     ke __global (aman, tapi gak ke-split).\n *   - Hanya resolve alias dari tsconfig.json/jsconfig.json root project\n *     (compilerOptions.paths + baseUrl). Alias yang didefinisikan di tempat\n *     lain (custom resolver webpack/turbopack) tidak ke-detect.\n */\n\nimport fs from \"node:fs\"\nimport path from \"node:path\"\n\nexport interface ScannedFileInput {\n  file: string\n  classes: string[]\n}\n\nexport interface RouteClassBuckets {\n  /** route path (\"/\", \"/docs\", \"/blog/[slug]\", ...) -> classes eksklusif route itu */\n  routes: Map<string, Set<string>>\n  /** classes shared 2+ route, layout/loading/error/template, atau unresolved */\n  global: Set<string>\n}\n\nconst CODE_EXTENSIONS = [\".tsx\", \".ts\", \".jsx\", \".js\", \".mjs\", \".cjs\"]\nconst SHARED_SEGMENT_RE = /(?:^|[\\\\/])(layout|loading|error|template|not-found|default)\\.(?:tsx|ts|jsx|js)$/\nconst PAGE_RE = /(?:^|[\\\\/])app[\\\\/](.*?)[\\\\/]page\\.(?:tsx|ts|jsx|js)$/\nconst ROOT_PAGE_RE = /(?:^|[\\\\/])app[\\\\/]page\\.(?:tsx|ts|jsx|js)$/\n\n/** Derive route path dari path file page.tsx App Router. Sama heuristik dengan fileToRoute() di index.ts. */\nfunction deriveRouteFromPageFile(normalizedFile: string): string | null {\n  const rootMatch = normalizedFile.match(ROOT_PAGE_RE)\n  if (rootMatch) return \"/\"\n  const match = normalizedFile.match(PAGE_RE)\n  if (!match) return null\n  // Strip Next.js route group segments seperti \"(marketing)\" — tidak masuk URL.\n  const segments = match[1]!.split(\"/\").filter((s) => !(s.startsWith(\"(\") && s.endsWith(\")\")))\n  return `/${segments.join(\"/\")}`\n}\n\ninterface TsconfigAliasInfo {\n  baseDir: string\n  paths: Array<{ prefix: string; targets: string[] }>\n}\n\n/**\n * Strip // dan /* *\\/ comment dari tsconfig.json/jsconfig.json, TANPA merusak\n * string literal. Naive `input.replace(/\\/\\*...*\\//, \"\")` salah: tsconfig\n * path alias umum kayak \"@/*\" mengandung literal \"/*\", dan glob pattern di\n * \"include\" kayak \"**\\/*.ts\" mengandung literal \"*\\/\" — regex buta bakal\n * ngira itu comment delimiter dan makan sebagian JSON di antaranya, bikin\n * parse error. Tokenizer ini lacak in-string state (termasuk escape \\\") jadi\n * cuma strip comment yang BENERAN di luar string.\n */\nfunction stripJsonComments(input: string): string {\n  let out = \"\"\n  let i = 0\n  let inString = false\n  let stringChar = \"\"\n  while (i < input.length) {\n    const ch = input[i]!\n    if (inString) {\n      out += ch\n      if (ch === \"\\\\\" && i + 1 < input.length) {\n        out += input[i + 1]\n        i += 2\n        continue\n      }\n      if (ch === stringChar) inString = false\n      i++\n      continue\n    }\n    if (ch === '\"' || ch === \"'\") {\n      inString = true\n      stringChar = ch\n      out += ch\n      i++\n      continue\n    }\n    if (ch === \"/\" && input[i + 1] === \"/\") {\n      while (i < input.length && input[i] !== \"\\n\") i++\n      continue\n    }\n    if (ch === \"/\" && input[i + 1] === \"*\") {\n      i += 2\n      while (i < input.length && !(input[i] === \"*\" && input[i + 1] === \"/\")) i++\n      i += 2\n      continue\n    }\n    out += ch\n    i++\n  }\n  return out\n}\n\nfunction loadTsconfigAliases(root: string): TsconfigAliasInfo | null {\n  for (const candidate of [\"tsconfig.json\", \"jsconfig.json\"]) {\n    const configPath = path.join(root, candidate)\n    if (!fs.existsSync(configPath)) continue\n    try {\n      const raw = stripJsonComments(fs.readFileSync(configPath, \"utf-8\"))\n      const parsed = JSON.parse(raw) as {\n        compilerOptions?: { baseUrl?: string; paths?: Record<string, string[]> }\n      }\n      const co = parsed.compilerOptions\n      if (!co?.paths) continue\n      const baseDir = path.join(root, co.baseUrl ?? \".\")\n      const paths = Object.entries(co.paths).map(([prefix, targets]) => ({\n        prefix: prefix.replace(/\\*$/, \"\"),\n        targets: targets.map((t) => t.replace(/\\*$/, \"\")),\n      }))\n      return { baseDir, paths }\n    } catch {\n      // Tsconfig korup/gak valid JSON — skip, fallback ke relative-only.\n      continue\n    }\n  }\n  return null\n}\n\n/** Resolve satu module specifier ke absolute file path, atau null kalau gak bisa/di luar scope. */\nfunction resolveSpecifier(\n  specifier: string,\n  fromFile: string,\n  aliasInfo: TsconfigAliasInfo | null\n): string | null {\n  let candidate: string | null = null\n\n  if (specifier.startsWith(\".\")) {\n    candidate = path.resolve(path.dirname(fromFile), specifier)\n  } else if (aliasInfo) {\n    for (const { prefix, targets } of aliasInfo.paths) {\n      if (specifier.startsWith(prefix)) {\n        const rest = specifier.slice(prefix.length)\n        candidate = path.join(aliasInfo.baseDir, targets[0] ?? \"\", rest)\n        break\n      }\n    }\n  }\n\n  if (!candidate) return null // bare specifier (node_modules/framework) — di luar scope\n\n  // Asset non-kode (css, image, dll) — bukan node graph, biarin gak ke-resolve.\n  if (/\\.(css|scss|sass|less|svg|png|jpe?g|gif|webp|json|woff2?|ttf|eot)$/i.test(candidate)) return null\n\n  if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) return candidate\n  for (const ext of CODE_EXTENSIONS) {\n    if (fs.existsSync(candidate + ext)) return candidate + ext\n  }\n  for (const ext of CODE_EXTENSIONS) {\n    const indexPath = path.join(candidate, `index${ext}`)\n    if (fs.existsSync(indexPath)) return indexPath\n  }\n  return null\n}\n\nconst IMPORT_FROM_RE = /(?:import|export)(?:[^'\"`;]*?)from\\s+[\"']([^\"']+)[\"']/g\nconst SIDE_EFFECT_IMPORT_RE = /^\\s*import\\s+[\"']([^\"']+)[\"']/gm\nconst DYNAMIC_IMPORT_RE = /\\bimport\\s*\\(\\s*[\"']([^\"']+)[\"']\\s*\\)/g\n\nfunction extractImportSpecifiers(source: string): string[] {\n  const specs = new Set<string>()\n  for (const re of [IMPORT_FROM_RE, SIDE_EFFECT_IMPORT_RE, DYNAMIC_IMPORT_RE]) {\n    re.lastIndex = 0\n    let m: RegExpExecArray | null\n    while ((m = re.exec(source))) {\n      if (m[1]) specs.add(m[1])\n    }\n  }\n  return [...specs]\n}\n\n/**\n * Build route -> exclusive-classes map + global fallback bucket, dari hasil\n * scanWorkspace() (files[].classes) plus static import graph antar file.\n */\nexport function buildRouteClassBuckets(root: string, srcDir: string, files: ScannedFileInput[]): RouteClassBuckets {\n  const aliasInfo = loadTsconfigAliases(root)\n  const classesByFile = new Map<string, string[]>()\n  const adjacency = new Map<string, Set<string>>()\n\n  for (const f of files) {\n    const normalized = path.normalize(f.file)\n    classesByFile.set(normalized, f.classes)\n    if (!adjacency.has(normalized)) adjacency.set(normalized, new Set())\n  }\n\n  for (const f of files) {\n    const normalized = path.normalize(f.file)\n    let source: string\n    try {\n      source = fs.readFileSync(normalized, \"utf-8\")\n    } catch {\n      continue // file mungkin udah kehapus/HMR race — skip, classes-nya tetap masuk ke __global lewat fallback unreachable\n    }\n    const edges = adjacency.get(normalized)!\n    for (const spec of extractImportSpecifiers(source)) {\n      const resolved = resolveSpecifier(spec, normalized, aliasInfo)\n      if (resolved && classesByFile.has(resolved)) edges.add(resolved)\n    }\n  }\n\n  // Entry point per route.\n  const routeEntries: Array<{ route: string; file: string }> = []\n  for (const f of files) {\n    const normalized = path.normalize(f.file).replace(/\\\\/g, \"/\")\n    const route = deriveRouteFromPageFile(normalized)\n    if (route) routeEntries.push({ route, file: path.normalize(f.file) })\n  }\n\n  // BFS per route -> set file yang reachable.\n  const reachableByRoute = new Map<string, Set<string>>()\n  for (const { route, file } of routeEntries) {\n    const visited = new Set<string>()\n    const queue = [file]\n    while (queue.length > 0) {\n      const current = queue.shift()!\n      if (visited.has(current)) continue\n      visited.add(current)\n      for (const next of adjacency.get(current) ?? []) {\n        if (!visited.has(next)) queue.push(next)\n      }\n    }\n    reachableByRoute.set(route, visited)\n  }\n\n  // Reverse: file -> routes yang menjangkaunya.\n  const routesByFile = new Map<string, Set<string>>()\n  for (const [route, fileSet] of reachableByRoute) {\n    for (const file of fileSet) {\n      if (!routesByFile.has(file)) routesByFile.set(file, new Set())\n      routesByFile.get(file)!.add(route)\n    }\n  }\n\n  const result: RouteClassBuckets = { routes: new Map(), global: new Set() }\n  for (const [file, classes] of classesByFile) {\n    const normalizedSlash = file.replace(/\\\\/g, \"/\")\n    const isSharedSegment = SHARED_SEGMENT_RE.test(normalizedSlash)\n    const reachingRoutes = isSharedSegment ? new Set<string>() : routesByFile.get(file)\n\n    if (!isSharedSegment && reachingRoutes && reachingRoutes.size === 1) {\n      const [route] = reachingRoutes\n      if (!result.routes.has(route!)) result.routes.set(route!, new Set())\n      const bucket = result.routes.get(route!)!\n      for (const cls of classes) bucket.add(cls)\n    } else {\n      for (const cls of classes) result.global.add(cls)\n    }\n  }\n\n  return result\n}\n\n/** Slugify route path jadi nama file CSS yang aman. \"/\" -> \"root\", \"/blog/[slug]\" -> \"blog__slug_\". */\nexport function routeToCssFilename(route: string): string {\n  const slug = route\n    .replace(/^\\/+/, \"\")\n    .replace(/[^a-zA-Z0-9_-]+/g, \"_\")\n    .replace(/^_+|_+$/g, \"\")\n  return `route_${slug || \"root\"}.css`\n}\n","/**\n * Semantic Component Analyzer\n * \n * Build-time analyzer untuk extract component metadata (@semantic, @aria, @state)\n * dari component config dan determine semantic intent.\n */\n\n/**\n * Semantic intent type - represents semantic meaning ng component\n */\nexport type SemanticIntent =\n    | 'button'\n    | 'link'\n    | 'navigation'\n    | 'heading'\n    | 'paragraph'\n    | 'list'\n    | 'input'\n    | 'form'\n    | 'dialog'\n    | 'alert'\n    | 'tab'\n    | 'checkbox'\n    | 'radio'\n    | 'select'\n    | 'custom'\n\n/**\n * Semantic metadata annotations\n */\nexport interface SemanticMetadata {\n    /**\n     * Semantic intent ng component (e.g., \"button\", \"link\")\n     * Guides ARIA role assignment at build-time\n     */\n    '@semantic'?: SemanticIntent\n\n    /**\n     * Explicit ARIA attributes to inject\n     */\n    '@aria'?: Record<string, string>\n\n    /**\n     * State-to-ARIA property mappings\n     * e.g., { checked: \"aria-checked\", disabled: \"aria-disabled\" }\n     */\n    '@state'?: Record<string, string>\n\n    /**\n     * Custom semantic mappings\n     */\n    [key: string]: unknown\n}\n\n/**\n * Component config type - basic shape\n */\nexport interface ComponentConfig {\n    tag?: string\n    variants?: Record<string, unknown>\n    defaultVariants?: Record<string, unknown>\n    [key: string]: unknown\n}\n\n/**\n * Analysis result from semantic analyzer\n */\nexport interface SemanticAnalysisResult {\n    componentName: string\n    tag: string\n    semantic: SemanticIntent\n    metadata: SemanticMetadata\n    ariaRole?: string\n    stateProperties: Map<string, string>\n}\n\n/**\n * Infer semantic intent from HTML tag\n */\nfunction inferSemanticFromTag(tag: string): SemanticIntent {\n    const tagLower = tag.toLowerCase()\n\n    const semanticMap: Record<string, SemanticIntent> = {\n        'button': 'button',\n        'a': 'link',\n        'nav': 'navigation',\n        'h1': 'heading',\n        'h2': 'heading',\n        'h3': 'heading',\n        'h4': 'heading',\n        'h5': 'heading',\n        'h6': 'heading',\n        'p': 'paragraph',\n        'ul': 'list',\n        'ol': 'list',\n        'input': 'input',\n        'form': 'form',\n        'dialog': 'dialog',\n        'select': 'select',\n        'textarea': 'input',\n    }\n\n    return semanticMap[tagLower] ?? 'custom'\n}\n\n/**\n * Extract semantic metadata from component config\n * Looks for @semantic, @aria, @state annotations\n */\nexport function extractSemanticMetadata(config: ComponentConfig): SemanticMetadata {\n    const metadata: SemanticMetadata = {}\n\n    // Extract prefixed fields (@semantic, @aria, @state)\n    for (const [key, value] of Object.entries(config)) {\n        if (key.startsWith('@')) {\n            metadata[key] = value\n        }\n    }\n\n    return metadata\n}\n\n/**\n * Analyze component config untuk determine semantic intent\n * Priority: explicit @semantic > tag-based inference\n */\nexport function analyzeComponentSemantics(\n    componentName: string,\n    config: ComponentConfig\n): SemanticAnalysisResult {\n    // Extract metadata\n    const metadata = extractSemanticMetadata(config)\n\n    // Get HTML tag (default: div)\n    const tag = config.tag ?? 'div'\n\n    // Determine semantic intent\n    let semantic = inferSemanticFromTag(tag)\n    if (metadata['@semantic']) {\n        semantic = metadata['@semantic'] as SemanticIntent\n    }\n\n    // Convert state mappings to Map\n    const stateProperties = new Map<string, string>()\n    if (metadata['@state']) {\n        for (const [key, value] of Object.entries(metadata['@state'])) {\n            if (typeof value === 'string') {\n                stateProperties.set(key, value)\n            }\n        }\n    }\n\n    return {\n        componentName,\n        tag,\n        semantic,\n        metadata,\n        stateProperties,\n    }\n}\n\n/**\n * Get ARIA role from semantic intent\n * Used by ARIA injection plugin at build-time\n */\nexport function getAriaRoleForSemantic(semantic: SemanticIntent): string | undefined {\n    const roleMap: Record<SemanticIntent, string | undefined> = {\n        'button': 'button',\n        'link': 'link',\n        'navigation': 'navigation',\n        'heading': 'heading',\n        'paragraph': undefined, // paragraph tidak perlu explicit role\n        'list': 'list',\n        'input': 'textbox',\n        'form': 'form',\n        'dialog': 'dialog',\n        'alert': 'alert',\n        'tab': 'tab',\n        'checkbox': 'checkbox',\n        'radio': 'radio',\n        'select': 'listbox',\n        'custom': undefined,\n    }\n\n    return roleMap[semantic]\n}\n\n/**\n * Batch analyze multiple components\n * Returns map of componentName → SemanticAnalysisResult\n */\nexport function analyzeComponentBatch(\n    components: Map<string, ComponentConfig>\n): Map<string, SemanticAnalysisResult> {\n    const results = new Map<string, SemanticAnalysisResult>()\n\n    for (const [name, config] of components) {\n        const analysis = analyzeComponentSemantics(name, config)\n        results.set(name, analysis)\n    }\n\n    return results\n}\n\n/**\n * Validate semantic metadata untuk consistency\n * Returns array of validation issues (empty = valid)\n */\nexport function validateSemanticMetadata(metadata: SemanticMetadata): string[] {\n    const issues: string[] = []\n\n    // Validate @semantic value\n    const validSemantics: SemanticIntent[] = [\n        'button', 'link', 'navigation', 'heading', 'paragraph', 'list',\n        'input', 'form', 'dialog', 'alert', 'tab', 'checkbox', 'radio', 'select', 'custom'\n    ]\n\n    if (metadata['@semantic'] && !validSemantics.includes(metadata['@semantic'] as SemanticIntent)) {\n        issues.push(`Invalid @semantic value: ${metadata['@semantic']}`)\n    }\n\n    // Validate @aria object\n    if (metadata['@aria']) {\n        if (typeof metadata['@aria'] !== 'object' || Array.isArray(metadata['@aria'])) {\n            issues.push('@aria must be object')\n        }\n    }\n\n    // Validate @state object\n    if (metadata['@state']) {\n        if (typeof metadata['@state'] !== 'object' || Array.isArray(metadata['@state'])) {\n            issues.push('@state must be object')\n        }\n\n        // Validate that values are string (ARIA property names)\n        for (const [key, value] of Object.entries(metadata['@state'] as Record<string, unknown>)) {\n            if (typeof value !== 'string') {\n                issues.push(`@state.${key} must be string (ARIA property name)`)\n            }\n        }\n    }\n\n    return issues\n}\n","/**\n * Type Stub Generator\n * \n * Build-time generator untuk create TypeScript .d.ts files dari semantic metadata.\n * Generates type stubs dengan semantic information untuk better IDE intellisense.\n */\n\nimport type { SemanticAnalysisResult, SemanticIntent } from './semanticComponentAnalyzer'\n\n/**\n * TypeScript interface definition untuk generated type\n */\nexport interface GeneratedTypeDefinition {\n    interfaceName: string\n    extendsFrom: string\n    properties: Map<string, TypeProperty>\n    jsDocComment?: string\n}\n\n/**\n * Individual property definition\n */\nexport interface TypeProperty {\n    name: string\n    type: string\n    description?: string\n    optional?: boolean\n}\n\n/**\n * Generate JSDoc comment dari semantic analysis\n */\nfunction generateJsDocFromSemantic(analysis: SemanticAnalysisResult): string {\n    const lines: string[] = [\n        '/**',\n        ` * ${analysis.componentName}`,\n        ` * `,\n        ` * Semantic intent: ${analysis.semantic}`,\n        ` * Tag: ${analysis.tag}`,\n    ]\n\n    if (analysis.metadata['@aria']) {\n        lines.push(` * ARIA: auto-injected dari semantic metadata`)\n    }\n\n    if (analysis.stateProperties.size > 0) {\n        const states = Array.from(analysis.stateProperties.entries())\n            .map(([k, v]) => `${k} → ${v}`)\n            .join(', ')\n        lines.push(` * State mappings: ${states}`)\n    }\n\n    lines.push(' */')\n    return lines.join('\\n')\n}\n\n/**\n * Get base type untuk component props\n * Depends on semantic intent dan HTML tag\n */\nfunction getBaseComponentType(analysis: SemanticAnalysisResult): string {\n    const tag = analysis.tag.toLowerCase()\n\n    // React.ComponentPropsWithoutRef untuk specific tags\n    const tagMap: Record<string, string> = {\n        'button': 'React.ButtonHTMLAttributes<HTMLButtonElement>',\n        'a': 'React.AnchorHTMLAttributes<HTMLAnchorElement>',\n        'input': 'React.InputHTMLAttributes<HTMLInputElement>',\n        'textarea': 'React.TextareaHTMLAttributes<HTMLTextAreaElement>',\n        'select': 'React.SelectHTMLAttributes<HTMLSelectElement>',\n        'form': 'React.FormHTMLAttributes<HTMLFormElement>',\n        'div': 'React.HTMLAttributes<HTMLDivElement>',\n        'span': 'React.HTMLAttributes<HTMLSpanElement>',\n        'nav': 'React.HTMLAttributes<HTMLElement>',\n        'dialog': 'React.DialogHTMLAttributes<HTMLDialogElement>',\n    }\n\n    return tagMap[tag] ?? 'React.HTMLAttributes<HTMLElement>'\n}\n\n/**\n * Generate state properties dari semantic metadata\n */\nfunction generateStateProperties(analysis: SemanticAnalysisResult): Map<string, TypeProperty> {\n    const props = new Map<string, TypeProperty>()\n\n    // Add state properties\n    for (const [stateName, ariaProp] of analysis.stateProperties) {\n        props.set(stateName, {\n            name: stateName,\n            type: 'boolean | undefined',\n            description: `State mapped to ARIA property: ${ariaProp}`,\n            optional: true,\n        })\n    }\n\n    return props\n}\n\n/**\n * Generate .d.ts interface definition\n */\nexport function generateTypeDefinition(\n    analysis: SemanticAnalysisResult,\n    componentName: string\n): GeneratedTypeDefinition {\n    const interfaceName = `${componentName}Props`\n    const baseType = getBaseComponentType(analysis)\n    const stateProps = generateStateProperties(analysis)\n\n    return {\n        interfaceName,\n        extendsFrom: baseType,\n        properties: stateProps,\n        jsDocComment: generateJsDocFromSemantic(analysis),\n    }\n}\n\n/**\n * Render TypeScript interface code\n */\nexport function renderTypeDefinition(def: GeneratedTypeDefinition): string {\n    const lines: string[] = []\n\n    if (def.jsDocComment) {\n        lines.push(def.jsDocComment)\n    }\n\n    lines.push(`export interface ${def.interfaceName} extends ${def.extendsFrom} {`)\n\n    // Add documented state properties\n    for (const prop of def.properties.values()) {\n        const optional = prop.optional ? '?' : ''\n\n        if (prop.description) {\n            lines.push(`  /** ${prop.description} */`)\n        }\n\n        lines.push(`  ${prop.name}${optional}: ${prop.type}`)\n    }\n\n    lines.push('}')\n\n    return lines.join('\\n')\n}\n\n/**\n * Generate complete .d.ts file content\n * Includes imports, interfaces, exports\n */\nexport function generateTypeStubFile(\n    analyses: Map<string, SemanticAnalysisResult>,\n    packageName: string = 'tailwind-styled'\n): string {\n    const lines: string[] = [\n        '/**',\n        ` * Auto-generated type definitions dari semantic component metadata`,\n        ` * Generated at build-time dari @semantic, @aria, @state annotations`,\n        ` * Package: ${packageName}`,\n        ` */`,\n        '',\n        \"import type * as React from 'react'\",\n        '',\n    ]\n\n    // Generate interface untuk setiap component\n    const interfaces: string[] = []\n\n    for (const [name, analysis] of analyses) {\n        const def = generateTypeDefinition(analysis, name)\n        interfaces.push(renderTypeDefinition(def))\n    }\n\n    lines.push(interfaces.join('\\n\\n'))\n    lines.push('')\n\n    // Generate namespace export\n    lines.push('export namespace Components {')\n    for (const analysis of analyses.values()) {\n        lines.push(`  export type ${analysis.componentName}Props = ${analysis.componentName}Props`)\n    }\n    lines.push('}')\n    lines.push('')\n\n    return lines.join('\\n')\n}\n\n/**\n * Write type stub file ke disk\n * Handles both ESM dan CJS output paths\n */\nexport interface TypeStubOutput {\n    filePath: string\n    content: string\n    format: 'esm' | 'cjs' | 'dts'\n}\n\n/**\n * Generate output paths untuk type stubs\n */\nexport function generateTypeStubOutputPaths(\n    outputDir: string,\n    packageName: string\n): TypeStubOutput[] {\n    return [\n        {\n            filePath: `${outputDir}/${packageName}.d.ts`,\n            content: '', // Will be set by caller\n            format: 'dts',\n        },\n    ]\n}\n\n/**\n * Batch generate type definitions dari multiple analyses\n */\nexport function generateTypeDefinitionsBatch(\n    analyses: Map<string, SemanticAnalysisResult>\n): Map<string, string> {\n    const results = new Map<string, string>()\n\n    for (const [name, analysis] of analyses) {\n        const def = generateTypeDefinition(analysis, name)\n        const code = renderTypeDefinition(def)\n        results.set(name, code)\n    }\n\n    return results\n}\n\n/**\n * Combine multiple type definitions into single file\n */\nexport function combineTypeDefinitions(\n    definitions: Map<string, string>,\n    packageName: string = 'tailwind-styled'\n): string {\n    const lines: string[] = [\n        '/**',\n        ` * Auto-generated type definitions dari semantic component metadata`,\n        ` * Generated at build-time dari @semantic, @aria, @state annotations`,\n        ` * Package: ${packageName}`,\n        ' */',\n        '',\n        \"import type * as React from 'react'\",\n        '',\n    ]\n\n    // Add all type definitions\n    const defs = Array.from(definitions.values())\n    lines.push(defs.join('\\n\\n'))\n\n    return lines.join('\\n')\n}\n","/**\n * Type Generation Plugin untuk tsup/build pipeline\n * \n * Integration point untuk run semantic analyzer + type generator\n * sebagai part dari build process.\n * \n * Usage di tsup.config.ts:\n * ```\n * import { createTypeGenerationPlugin } from './src/typeGenerationPlugin'\n * \n * export default defineConfig({\n *   plugins: [createTypeGenerationPlugin()],\n *   ...\n * })\n * ```\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport type { Plugin } from 'esbuild'\n\nimport {\n    analyzeComponentBatch,\n    type ComponentConfig,\n} from './semanticComponentAnalyzer'\nimport {\n    generateTypeStubFile,\n} from './typeGeneratorFromMetadata'\n\n/**\n * Options untuk type generation plugin\n */\nexport interface TypeGenerationPluginOptions {\n    /**\n     * Directory dimana akan output .d.ts files\n     * Default: './dist/types'\n     */\n    outputDir?: string\n\n    /**\n     * Package name untuk generated header\n     * Default: 'tailwind-styled'\n     */\n    packageName?: string\n\n    /**\n     * Enable logging\n     * Default: false\n     */\n    verbose?: boolean\n\n    /**\n     * Source file path untuk component registry\n     * Jika tidak provided, akan skip type generation\n     */\n    componentRegistryPath?: string\n}\n\n/**\n * Create tsup plugin untuk type generation\n * Runs at build-time to generate .d.ts files dari semantic metadata\n */\nexport function createTypeGenerationPlugin(options: TypeGenerationPluginOptions = {}): Plugin {\n    const {\n        outputDir = './dist/types',\n        packageName = 'tailwind-styled',\n        verbose = false,\n        componentRegistryPath,\n    } = options\n\n    return {\n        name: 'type-generation',\n\n        async setup(build) {\n            // This plugin uses esbuild setup hook\n            // For actual type generation, use onEnd callback if available\n            if (verbose) {\n                console.log('[type-generation] Plugin loaded')\n            }\n        },\n    }\n}\n\n/**\n * Load component registry dari file\n * Expected format: JSON with component configs\n */\nfunction loadComponentRegistry(filePath: string): Map<string, ComponentConfig> {\n    const registry = new Map<string, ComponentConfig>()\n\n    if (!fs.existsSync(filePath)) {\n        console.warn(`[type-generation] Component registry not found: ${filePath}`)\n        return registry\n    }\n\n    try {\n        const content = fs.readFileSync(filePath, 'utf8')\n        const data = JSON.parse(content)\n\n        // Expect format: { components: { name: config, ... } } atau direct object\n        const components = data.components ?? data\n\n        for (const [name, config] of Object.entries(components)) {\n            if (typeof config === 'object' && config !== null) {\n                registry.set(name, config as ComponentConfig)\n            }\n        }\n    } catch (error) {\n        console.warn(`[type-generation] Failed to load registry from ${filePath}:`, error)\n    }\n\n    return registry\n}\n\n/**\n * Standalone function untuk generate types from components\n * Useful untuk scripts atau CLI\n */\nexport async function generateTypesFromComponents(\n    components: Map<string, ComponentConfig>,\n    outputPath: string,\n    packageName: string = 'tailwind-styled'\n): Promise<void> {\n    if (components.size === 0) {\n        console.warn('No components provided')\n        return\n    }\n\n    // Analyze components\n    const analyses = analyzeComponentBatch(components)\n\n    // Generate type stubs\n    const typeContent = generateTypeStubFile(analyses, packageName)\n\n    // Ensure output directory exists\n    const dir = path.dirname(outputPath)\n    if (!fs.existsSync(dir)) {\n        fs.mkdirSync(dir, { recursive: true })\n    }\n\n    // Write file\n    fs.writeFileSync(outputPath, typeContent, 'utf8')\n\n    console.log(`Generated type stubs → ${outputPath} (${components.size} components)`)\n}","/**\n * tailwind-styled-v5 — Compiler Main Entry Point\n * \n * Re-exports all sub-entry points for backward compatibility.\n * For better tree-shaking, import from specific sub-entries:\n * - '@tailwind-styled/compiler/compiler' - CSS generation and compilation\n * - '@tailwind-styled/compiler/parser' - Class parsing and extraction\n * - '@tailwind-styled/compiler/analyzer' - Analysis and optimization\n * - '@tailwind-styled/compiler/cache' - Cache management\n * - '@tailwind-styled/compiler/redis' - Redis and distributed cache\n * - '@tailwind-styled/compiler/watch' - File watching and monitoring\n */\n\nimport fs from \"node:fs\"\nimport path from \"node:path\"\nimport { createRequire } from \"node:module\"\n\nconst _require = createRequire(\n  typeof require !== \"undefined\"\n    ? (typeof __filename !== \"undefined\" ? `file://${__filename}` : \"file://unknown\")\n    : import.meta.url\n)\n\nimport { getNativeBridge, resetNativeBridgeCache, adaptNativeResult, type NativeBridge, type NativeTransformResult, type ClassExtractResult, type ComponentMetadata, type NativeRscResult } from \"./nativeBridge\"\n\nexport { getNativeBridge, resetNativeBridgeCache, adaptNativeResult }\nexport type { NativeBridge, NativeTransformResult, ClassExtractResult, ComponentMetadata, NativeRscResult }\n\n// ═══════════════════════════════════════════════════════════════════════════\n// RE-EXPORT ALL SUB-ENTRIES FOR BACKWARD COMPATIBILITY\n// ═══════════════════════════════════════════════════════════════════════════\n\n// Compiler sub-entry - CSS generation, compilation, ID registry, streaming\nexport * from './compiler'\n\n// Parser sub-entry - Class parsing and extraction\nexport * from './parser'\n\n// Analyzer sub-entry - Analysis, optimization, theme resolution\nexport * from './analyzer'\n\n// Cache sub-entry - Cache management\nexport * from './cache'\n\n// Redis sub-entry - Redis and distributed cache\nexport * from './redis'\n\n// Watch sub-entry - File watching and monitoring\nexport * from './watch'\n\n// Route graph - static import-graph based per-route class attribution\nexport * from './routeGraph'\n\n// Semantic components - Type inference dan metadata analysis (Build-time)\nexport * from './semanticComponentAnalyzer'\nexport * from './typeGeneratorFromMetadata'\nexport * from './typeGenerationPlugin'\n\n// ═══════════════════════════════════════════════════════════════════════════\n// PURE RUST SYNC API (v5.0.19+) — NO FALLBACK\n// ═══════════════════════════════════════════════════════════════════════════\n// These are the ONLY scanning/generation paths for production builds\n// All must go through native Rust module — fail-fast if unavailable\n\n// ═══════════════════════════════════════════════════════════════════════════\n// TRANSFORM & CORE FUNCTIONS\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const transformSource = (source: string, opts?: Record<string, unknown>) => {\n  const native = getNativeBridge()\n  if (!native?.transformSource) {\n    throw new Error(\"FATAL: Native binding 'transformSource' is required but not available.\")\n  }\n  const stringOpts = opts\n    ? Object.fromEntries(Object.entries(opts).map(([k, v]) => [k, String(v)]))\n    : undefined\n  const result = native.transformSource(source, stringOpts as Record<string, string>)\n  if (!result) {\n    throw new Error(\"FATAL: transformSource returned null\")\n  }\n  return result\n}\n\nexport const hasTwUsage = (source: string): boolean => {\n  const native = getNativeBridge()\n  if (!native?.hasTwUsage) {\n    throw new Error(\"FATAL: Native binding 'hasTwUsage' is required but not available.\")\n  }\n  return native.hasTwUsage(source)\n}\n\nexport const isAlreadyTransformed = (source: string): boolean => {\n  const native = getNativeBridge()\n  if (!native?.isAlreadyTransformed) {\n    throw new Error(\"FATAL: Native binding 'isAlreadyTransformed' is required but not available.\")\n  }\n  return native.isAlreadyTransformed(source)\n}\n\nexport const shouldProcess = (source: string): boolean => {\n  return hasTwUsage(source) && !isAlreadyTransformed(source)\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// ADDITIONAL UTILITIES\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const compileCssFromClasses = (classes: string[], prefix?: string | null) => {\n  const native = getNativeBridge()\n  if (!native?.transformSource) {\n    throw new Error(\"FATAL: Native binding 'transformSource' is required but not available.\")\n  }\n  const result = native.transformSource(classes.join(\" \"), { prefix: prefix ?? \"\" })\n  if (!result) {\n    throw new Error(\"FATAL: transformSource returned null\")\n  }\n  return result\n}\n\nexport const buildStyleTag = (classes: string[]): string => {\n  const result = compileCssFromClasses(classes)\n  return result?.code ? `<style data-tailwind-styled>${result.code}</style>` : \"\"\n}\n\nexport const generateCssForClasses = async (\n  classes: string[],\n  _tailwindConfig?: Record<string, unknown>,\n  root?: string,\n  cssEntryContent?: string,\n  minify = false\n): Promise<string> => {\n  try {\n    const { runCssPipeline } = await import(\"./compiler/tailwindEngine\")\n    const result = await runCssPipeline(classes, cssEntryContent, root, minify)\n    return result.css\n  } catch {\n    // Fallback if import fails\n    const native = getNativeBridge()\n    if (!native?.transformSource) {\n      throw new Error(\"FATAL: Native binding 'transformSource' is required but not available.\")\n    }\n    const result = native.transformSource(classes.join(\" \"), {})\n    return result?.code || \"\"\n  }\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// DEAD STYLE ELIMINATION\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const eliminateDeadCss = (css: string, deadClasses: Set<string>): string => {\n  const native = getNativeBridge()\n  if (!native?.eliminateDeadCss) {\n    throw new Error(\"FATAL: Native binding 'eliminateDeadCss' is required but not available.\")\n  }\n  return native.eliminateDeadCss(css, Array.from(deadClasses)) as string\n}\n\nexport const findDeadVariants = (\n  variantConfig: Record<string, unknown> | Array<{ name: string; variants: Record<string, Record<string, string>>; defaultVariants?: Record<string, string> }>,\n  usage: Record<string, Set<string>>\n) => {\n  const unused: string[] = []\n\n  const configs = Array.isArray(variantConfig)\n    ? variantConfig\n    : [{ name: \"__root__\", variants: variantConfig as Record<string, Record<string, string>> }]\n\n  for (const component of configs) {\n    const componentUsage = usage[component.name] ?? new Set<string>()\n    const variants = component.variants as Record<string, Record<string, string>>\n    for (const [key, values] of Object.entries(variants)) {\n      for (const [value] of Object.entries(values)) {\n        if (!componentUsage.has(`${key}:${value}`)) {\n          unused.push(`${component.name !== \"__root__\" ? `${component.name}/` : \"\"}${key}:${value}`)\n        }\n      }\n    }\n  }\n\n  return { unusedCount: unused.length, unused }\n}\n\nexport const runElimination = (css: string, scanResult: unknown): string => {\n  const native = getNativeBridge()\n  if (!native?.detectDeadCode) {\n    throw new Error(\"FATAL: Native binding 'detectDeadCode' is required but not available.\")\n  }\n  const dead = native.detectDeadCode(JSON.stringify(scanResult), css) as { deadInCss: string[] }\n  return eliminateDeadCss(css, new Set(dead.deadInCss ?? []))\n}\n\nexport const scanProjectUsage = (dirs: string[], cwd: string) => {\n  // Import locally to avoid circular dependency\n  const { batchExtractClasses } = _require('./parser')\n  const files = dirs.map(dir => path.resolve(cwd, dir))\n  const results = batchExtractClasses(files) || []\n\n  const combined: Record<string, Record<string, Set<string>>> = {}\n  for (const result of results) {\n    if (result.ok && result.classes) {\n      for (const cls of result.classes) {\n        if (!combined[cls]) combined[cls] = {}\n        combined[cls][result.file] = new Set([cls])\n      }\n    }\n  }\n  return combined\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// CONFIG & UTILITIES\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const generateSafelist = (scanDirs: string[], outputPath?: string, cwd?: string) => {\n  const classes = scanProjectUsage(scanDirs, cwd || process.cwd())\n  const allClasses = Object.keys(classes).sort()\n  if (outputPath) {\n    fs.writeFileSync(outputPath, JSON.stringify(allClasses, null, 2))\n  }\n  return allClasses\n}\n\nexport const loadSafelist = (safelistPath: string): string[] => {\n  try {\n    const content = fs.readFileSync(safelistPath, \"utf-8\")\n    return JSON.parse(content)\n  } catch {\n    return []\n  }\n}\n\nexport const loadTailwindConfig = (cwd: string = process.cwd()) => {\n  const configFiles = [\n    \"tailwind.config.ts\",\n    \"tailwind.config.js\",\n    \"tailwind.config.mjs\",\n    \"tailwind.config.cjs\",\n  ]\n  for (const file of configFiles) {\n    const fullPath = path.join(cwd, file)\n    if (fs.existsSync(fullPath)) {\n      const mod = require(fullPath) as { default?: unknown }\n      return mod.default || mod\n    }\n  }\n  return {}\n}\n\nexport const getContentPaths = (cwd: string = process.cwd()) => {\n  return {\n    content: [\n      path.join(cwd, \"src/**/*.{js,ts,jsx,tsx}\"),\n      path.join(cwd, \"app/**/*.{js,ts,jsx,tsx}\"),\n      path.join(cwd, \"pages/**/*.{js,ts,jsx,tsx}\"),\n    ],\n  }\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// CONTAINER CSS EXTRACTION\n// ═══════════════════════════════════════════════════════════════════════════\n\nfunction _layoutClassesToCss(classes: string): string {\n  const native = getNativeBridge()\n  if (!native?.layoutClassesToCss) {\n    throw new Error(\"FATAL: Native binding 'layoutClassesToCss' is required but not available.\")\n  }\n  return native.layoutClassesToCss(classes)\n}\n\nfunction _hashContainer(tag: string, containerJson: string, name?: string): string {\n  const sortedKey = tag + (name ?? \"\") + containerJson\n  const native = getNativeBridge()\n  if (!native?.hashContent) {\n    throw new Error(\"FATAL: Native binding 'hashContent' is required but not available.\")\n  }\n  return `tw-cq-${native.hashContent(sortedKey, \"fnv\", 6)}`\n}\n\nconst _CONTAINER_BREAKPOINTS: Record<string, string> = {\n  xs: \"240px\",\n  sm: \"320px\",\n  md: \"640px\",\n  lg: \"1024px\",\n  xl: \"1280px\",\n  \"2xl\": \"1536px\",\n}\n\nexport function extractContainerCssFromSource(source: string): string {\n  const native = getNativeBridge()\n  if (!native?.extractTwContainerConfigs) {\n    throw new Error(\"FATAL: Native binding 'extractTwContainerConfigs' is required but not available.\")\n  }\n\n  const configs = native.extractTwContainerConfigs(source) as Array<{\n    tag: string\n    containerJson: string\n    containerName?: string\n    breakpoints: Array<{ key: string; classes: string }>\n  }>\n\n  const rules: string[] = []\n  for (const cfg of configs) {\n    const id = _hashContainer(cfg.tag, cfg.containerJson, cfg.containerName)\n    for (const { key, classes } of cfg.breakpoints) {\n      const minWidth = _CONTAINER_BREAKPOINTS[key] ?? key\n      const css = _layoutClassesToCss(classes)\n      if (!css) continue\n      const query = cfg.containerName\n        ? `@container ${cfg.containerName} (min-width: ${minWidth})`\n        : `@container (min-width: ${minWidth})`\n      rules.push(`${query}{.${id}{${css}}}`)\n    }\n  }\n  return rules.join(\"\\n\")\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// LOADER INTERFACE\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport type LoaderOutput = {\n  code: string\n  changed: boolean\n  classes: string[]\n  staticCss?: string\n  rsc?: { isServer?: boolean; needsClientDirective?: boolean; clientReasons?: string[] }\n  engine?: string\n}\n\nexport const runLoaderTransform = (ctx: { filepath: string; source: string; options?: Record<string, unknown> }) => {\n  const { filepath, source, options } = ctx\n  const result = transformSource(source, { filename: filepath, ...options })\n\n  let staticCss: string | undefined\n  try {\n    const cssChunks: string[] = []\n\n    const stateRules = extractAndGenerateStateCss(source, filepath)\n    if (stateRules.length > 0) {\n      // Filter out unresolved rules: when Rust can't resolve a Tailwind class,\n      // `declarations` contains the raw class name (e.g. \"w-full\") instead of\n      // a real CSS declaration (e.g. \"width: 100%\"). Real declarations always\n      // contain \":\". Emitting unresolved rules causes Tailwind v4 PostCSS to\n      // throw \"CssSyntaxError: Invalid declaration: `w-full`\".\n      // Mirror of the identical guard in staticStateExtractor.ts.\n      const resolvedRules = stateRules.filter((r) => {\n        const decl = r.declarations.trim()\n        return decl.length === 0 || decl.includes(\":\")\n      })\n      if (resolvedRules.length > 0) {\n        cssChunks.push(resolvedRules.map((r) => r.cssRule).join(\"\\n\"))\n      }\n    }\n\n    const containerCss = extractContainerCssFromSource(source)\n    if (containerCss) cssChunks.push(containerCss)\n\n    const combined = cssChunks.join(\"\\n\").trim()\n    if (combined) staticCss = combined\n  } catch (err) {\n    // Non-fatal — static CSS extraction failure should not break transform pipeline.\n    console.debug(\"Static CSS extraction warning:\", err)\n  }\n\n  return {\n    code: result?.code || \"\",\n    changed: result?.changed || false,\n    classes: result?.classes || [],\n    staticCss,\n  } as LoaderOutput\n}\n\nexport const shouldSkipFile = (filepath: string): boolean => {\n  const SKIP_PATHS = [\"node_modules\", \".next\", \".rspack-dist\", \".turbo\", \"dist/\", \"out/\"]\n  const skipExtensions = [\".css\", \".json\", \".md\", \".txt\", \".yaml\", \".yml\"]\n  for (const p of SKIP_PATHS) {\n    if (filepath.includes(p)) return true\n  }\n  for (const ext of skipExtensions) {\n    if (filepath.endsWith(ext)) return true\n  }\n  return false\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// ROUTE MANAGEMENT\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const fileToRoute = (filepath: string): string | null => {\n  const normalized = filepath.replace(/\\\\/g, \"/\")\n  if (normalized.includes(\"/layout.\") || normalized.includes(\"/loading.\") || normalized.includes(\"/error.\")) {\n    return \"__global\"\n  }\n  const pageMatch = normalized.match(/(?:^|\\/)app\\/(.+?)\\/page\\.[tj]sx?$/)\n  if (pageMatch) return `/${pageMatch[1]}`\n  const rootPage = normalized.match(/(?:^|\\/)app\\/page\\.[tj]sx?$/)\n  if (rootPage) return \"/\"\n  return null\n}\n\nexport const getAllRoutes = (): string[] => {\n  const native = getNativeBridge()\n  if (!native?.analyzeClasses) {\n    throw new Error(\"FATAL: Native binding 'analyzeClasses' is required but not available.\")\n  }\n  return [\"/\", \"__global\"]\n}\n\n// ── Route/class registry (FIX) ──────────────────────────────────────────────\n// Sebelumnya getRouteClasses/registerFileClasses/registerGlobalClasses adalah\n// no-op stubs (params di-prefix underscore, body kosong) — akibatnya\n// TwCssInjector SELALU gagal nemu manifest CSS walau \"routeCss: true\" sudah\n// diset di withTailwindStyled(...), karena memang tidak ada satu pun kode\n// yang pernah menulis isi map ini. webpackLoader.ts/turbopackLoader.ts sudah\n// benar memanggil registerFileClasses(filepath, output.classes) per file,\n// tapi panggilan itu jatuh ke lubang hitam.\n//\n// Map ini di-key per filepath (bukan per route langsung) — sama pola dengan\n// _fileStaticCssMap di staticCssWebpackPlugin.ts — supaya file yang\n// diedit/dihapus saat HMR gak nyisain stale classes dari versi lama file\n// tersebut. getRouteClasses() menghitung ulang dari scratch tiap dipanggil\n// dengan mem-bucket lewat fileToRoute(); ini O(files) per call, yang cukup\n// murah untuk ukuran project tipikal dan menghindari kelas bug \"double\n// counting\" kalau dihitung incremental.\nconst _fileClassesMap = new Map<string, Set<string>>()\nconst _globalClasses = new Set<string>()\n\nexport const getRouteClasses = (route: string): Set<string> => {\n  const result = new Set<string>()\n  for (const [filepath, classes] of _fileClassesMap) {\n    const fileRoute = fileToRoute(filepath) ?? \"__global\"\n    if (fileRoute === route) {\n      for (const cls of classes) result.add(cls)\n    }\n  }\n  return result\n}\n\n/**\n * Semua classes yang ke-register dari semua file + registerGlobalClasses(),\n * tanpa peduli route. TIDAK dipakai untuk manifest per-route (lihat\n * withTailwindStyled.ts — manifest ditulis dari `result.files` hasil\n * scanWorkspace() + buildRouteClassBuckets() di ./routeGraph.ts, karena\n * registry ini baru ke-isi progresif saat bundler benar-benar meng-compile\n * file, sementara manifest ditulis di config-eval time, sebelum itu).\n * getRouteClasses()/fileToRoute() di bawah juga TIDAK dipakai jalur itu —\n * cuma mengenali page.tsx/layout.tsx/loading.tsx/error.tsx secara langsung,\n * gak ngikutin import transitif. Per-route splitting yang sesungguhnya\n * (import-graph tracing: file mana di-import transitif oleh route mana)\n * sudah ada — lihat ./routeGraph.ts (buildRouteClassBuckets), dipanggil\n * dari withTailwindStyled.ts, bukan dari registry/fungsi di bawah ini.\n * Fungsi-fungsi di bawah dipertahankan untuk konsumer lain (CLI `tw split`,\n * dll) yang mungkin masih bergantung pada registry incremental ini.\n */\nexport const getAllRegisteredClasses = (): Set<string> => {\n  const result = new Set<string>(_globalClasses)\n  for (const classes of _fileClassesMap.values()) {\n    for (const cls of classes) result.add(cls)\n  }\n  return result\n}\n\n/** Dipanggil oleh webpackLoader.ts/turbopackLoader.ts setiap file di-transform. */\nexport const registerFileClasses = (filepath: string, classes: string[]): void => {\n  if (!classes || classes.length === 0) {\n    _fileClassesMap.delete(filepath)\n    return\n  }\n  _fileClassesMap.set(filepath, new Set(classes))\n}\n\nexport const registerGlobalClasses = (classes: string[]): void => {\n  for (const cls of classes) _globalClasses.add(cls)\n}\n\n/** Reset registry — dipakai test, atau awal compilation run kalau perlu state bersih. */\nexport const resetRouteClassRegistry = (): void => {\n  _fileClassesMap.clear()\n  _globalClasses.clear()\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// INCREMENTAL ENGINE\n// ═══════════════════════════════════════════════════════════════════════════\n\nlet _incrementalEngineInstance: InstanceType<typeof IncrementalEngine> | null = null\n\nexport const getIncrementalEngine = () => {\n  if (!_incrementalEngineInstance) {\n    _incrementalEngineInstance = new IncrementalEngine()\n  }\n  return _incrementalEngineInstance\n}\n\nexport const resetIncrementalEngine = (): void => {\n  _incrementalEngineInstance = null\n}\n\nexport class IncrementalEngine {\n  compile(source: string) {\n    return transformSource(source)\n  }\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// STYLE BUCKET SYSTEM\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const getBucketEngine = () => {\n  const native = getNativeBridge()\n  if (!native?.classifyAndSortClasses) {\n    throw new Error(\"FATAL: Native binding 'classifyAndSortClasses' is required but not available.\")\n  }\n  return {\n    add: (className: string) => className,\n    get: (_bucket: string): string[] => [],\n  }\n}\n\nexport const resetBucketEngine = (): void => { }\n\nexport class BucketEngine {\n  add(className: string) { return className }\n}\n\nexport const classifyNode = (_node: unknown): string => {\n  const native = getNativeBridge()\n  if (!native?.classifyAndSortClasses) {\n    throw new Error(\"FATAL: Native binding 'classifyAndSortClasses' is required but not available.\")\n  }\n  return \"unknown\"\n}\n\nexport const detectConflicts = (_classes: string[]): string[] => {\n  const native = getNativeBridge()\n  if (!native?.analyzeClassUsage) {\n    throw new Error(\"FATAL: Native binding 'analyzeClassUsage' is required but not available.\")\n  }\n  return []\n}\n\nexport const bucketSort = (classes: string[]): string[] => {\n  const native = getNativeBridge()\n  if (!native?.classifyAndSortClasses) {\n    throw new Error(\"FATAL: Native binding 'classifyAndSortClasses' is required but not available.\")\n  }\n  const sorted = native.classifyAndSortClasses(classes)\n  return sorted.map((c) => (c as { raw?: string }).raw ?? (c as unknown as string))\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// RSC & FILE ANALYSIS CONTINUED\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const analyzeFile = (source: string, filename: string) => {\n  const native = getNativeBridge()\n  if (!native?.analyzeRsc) {\n    throw new Error(\"FATAL: Native binding 'analyzeRsc' is required but not available.\")\n  }\n  const rsc = native.analyzeRsc(source, filename)\n  return {\n    isServer: rsc?.isServer ?? true,\n    needsClientDirective: rsc?.needsClientDirective ?? false,\n    clientReasons: rsc?.clientReasons ?? [],\n    interactiveClasses: [],\n    canStaticResolveVariants: true,\n  }\n}\n\nexport const analyzeVariantUsage = (_source: string, _componentName: string, _variantKeys: string[]) => {\n  return { resolved: {} as Record<string, string>, dynamic: [] as string[] }\n}\n\nexport const injectClientDirective = (source: string): string => {\n  if (!source.includes('\"use client\"') && !source.includes(\"'use client'\")) {\n    return '\"use client\";\\n' + source\n  }\n  return source\n}\n\nexport const injectServerOnlyComment = (source: string): string => {\n  return `/* @server-only */\\n${source}`\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// FULL ANALYSIS\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport const analyzeClasses = (filesJson: string, cwd: string, flags: number) => {\n  const native = getNativeBridge()\n  if (!native?.analyzeClasses) {\n    throw new Error(\"FATAL: Native binding 'analyzeClasses' is required but not available.\")\n  }\n  return native.analyzeClasses(filesJson, cwd, flags)\n}\n\n// ═══════════════════════════════════════════════════════════════════════════\n// STATE CSS PRE-GENERATION\n// ═══════════════════════════════════════════════════════════════════════════\n\nexport interface TwStateConfigEntry {\n  tag: string\n  componentName: string\n  statesJson: string\n  sourceFile: string\n}\n\nexport interface StaticStateCssInput {\n  tag: string\n  componentName: string\n  statesJson: string\n}\n\nexport interface GeneratedStateRule {\n  selector: string\n  declarations: string\n  cssRule: string\n  componentName: string\n  stateName: string\n}\n\nexport const extractTwStateConfigs = (source: string, filename: string): TwStateConfigEntry[] => {\n  const native = getNativeBridge()\n  if (!native?.extractTwStateConfigs) {\n    throw new Error(\"FATAL: Native binding 'extractTwStateConfigs' is required but not available.\")\n  }\n  return native.extractTwStateConfigs(source, filename)\n}\n\nexport const generateStaticStateCss = (\n  entries: TwStateConfigEntry[],\n  resolvedCssOrThemeConfig?: string | Record<string, unknown>\n): GeneratedStateRule[] => {\n  const native = getNativeBridge()\n  if (!native?.generateStaticStateCss) {\n    throw new Error(\"FATAL: Native binding 'generateStaticStateCss' is required but not available.\")\n  }\n  // Normalize: resolvedCssOrThemeConfig bisa string (resolvedCss) atau object (legacy themeConfig)\n  const resolvedCss = typeof resolvedCssOrThemeConfig === \"string\" ? resolvedCssOrThemeConfig : null\n  const inputs = entries.map((e) => ({\n    tag: e.tag,\n    componentName: e.componentName,\n    statesJson: e.statesJson,\n  }))\n  return native.generateStaticStateCss(inputs, resolvedCss) as GeneratedStateRule[]\n}\n\nexport const extractAndGenerateStateCss = (source: string, filename: string): GeneratedStateRule[] => {\n  const native = getNativeBridge()\n  if (!native?.extractAndGenerateStateCss) {\n    // Fallback: extract lalu generate secara terpisah\n    const entries = extractTwStateConfigs(source, filename)\n    return generateStaticStateCss(entries)\n  }\n  return native.extractAndGenerateStateCss(source, filename) as GeneratedStateRule[]\n}\n","export * from \"@tailwind-styled/atomic\"\n","/**\n * tailwind-styled-v4 — Atomic CSS\n *\n * JS layer: thin wrapper, re-export types, expose registry diagnostics.\n * Rust layer: parseAtomicClass, generateAtomicCss, toAtomicClasses, registry.\n *\n * Removed from JS: TW_PROPERTY_MAP, sizeValue, textSize, fontWeight,\n * leadingValue, roundedValue, sanitizeClassName, REGISTRY Map.\n */\n\nimport { getNativeBridge } from \"@tailwind-styled/compiler\"\n\nexport interface AtomicRule {\n  twClass: string\n  atomicName: string\n  property: string\n  value: string\n  modifier?: string\n}\n\ntype AtomicNativeBridge = Required<Pick<ReturnType<typeof getNativeBridge>,\n  \"parseAtomicClass\" | \"generateAtomicCss\" | \"toAtomicClasses\" | \"clearAtomicRegistry\" | \"atomicRegistrySize\"\n>>\n\nfunction getNative(): AtomicNativeBridge {\n  const native = getNativeBridge()\n  if (\n    !native?.parseAtomicClass ||\n    !native?.generateAtomicCss ||\n    !native?.toAtomicClasses\n  ) {\n    throw new Error(\n      \"FATAL: Native bindings 'parseAtomicClass', 'generateAtomicCss', 'toAtomicClasses' are required.\\n\" +\n      \"Build the native Rust module: npm run build:rust\"\n    )\n  }\n  return native as AtomicNativeBridge\n}\n\n/**\n * Parse a single Tailwind class into an AtomicRule.\n * Returns null if the class prefix is not in the atomic property map.\n *\n * Rust: parse_atomic_class(tw_class: String) -> Option<String>\n */\nconst _parseAtomicCache = new Map<string, AtomicRule>()\n\nexport function parseAtomicClass(twClass: string): AtomicRule | null {\n  const cached = _parseAtomicCache.get(twClass)\n  if (cached !== undefined) return cached\n  const native = getNative()\n  const json = native.parseAtomicClass(twClass)\n  if (!json) return null\n  const result = JSON.parse(json) as AtomicRule\n  _parseAtomicCache.set(twClass, result)\n  return result\n}\n\n/**\n * Generate CSS string from an array of AtomicRules.\n *\n * Rust: generate_atomic_css(rules_json: String) -> String\n */\nexport function generateAtomicCss(rules: AtomicRule[]): string {\n  const native = getNative()\n  return native.generateAtomicCss(JSON.stringify(rules))\n}\n\n/**\n * Convert a space-separated Tailwind class string to atomic equivalents.\n *\n * Rust: to_atomic_classes(tw_classes: String) -> String (JSON)\n */\nexport function toAtomicClasses(twClasses: string): {\n  atomicClasses: string\n  rules: AtomicRule[]\n  unknownClasses: string[]\n} {\n  const native = getNative()\n  return JSON.parse(native.toAtomicClasses(twClasses)) as {\n    atomicClasses: string\n    rules: AtomicRule[]\n    unknownClasses: string[]\n  }\n}\n\nexport function getAtomicRegistry(): { size: number } {\n  const native = getNativeBridge()\n  if (!native?.atomicRegistrySize) {\n    throw new Error(\"FATAL: Native binding 'atomicRegistrySize' is required but not available.\")\n  }\n  return { size: native.atomicRegistrySize() }\n}\n\nexport function clearAtomicRegistry(): void {\n  const native = getNativeBridge()\n  if (!native?.clearAtomicRegistry) {\n    throw new Error(\"FATAL: Native binding 'clearAtomicRegistry' is required but not available.\")\n  }\n  native.clearAtomicRegistry()\n}"],"mappings":";;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B,IAIM,aAIO;AARb;AAAA;AAAA;AAIA,IAAM,cAAc,MAAM,cAAc,YAAY,GAAG;AAIhD,IAAM,aAA6B,4BAAY;AAAA;AAAA;;;ACEtD,SAAS,qBAAqB;AAC9B,YAAY,QAAQ;AACpB,YAAYA,WAAU;AAStB,SAAS,qBAAkC;AAEzC,MAAI,OAAO,gBAAgB,eAAe,YAAY,OAAO,CAAC,YAAY,IAAI,SAAS,SAAS,GAAG;AACjG,WAAO,cAAc,YAAY,GAAG;AAAA,EACtC;AAEA,MAAI,OAAO,eAAe,aAAa;AACrC,WAAO,cAAc,UAAU;AAAA,EACjC;AAEA,SAAO,cAAc,IAAI,IAAI,UAAU,QAAQ,IAAI,CAAC,GAAG,EAAE,IAAI;AAC/D;AAqBA,SAAS,cAAsB;AAC7B,MAAI,UAAW,QAAO;AACtB,SAAO,GAAG,QAAQ,QAAQ,IAAI,QAAQ,IAAI;AAC5C;AAaO,SAAS,oBAAoB,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O,SAAS,gBAAgB,WAI9B;AACA,QAAM,SAAS,UAAU;AACzB,SAAO,KAAK,MAAM,OAAO,gBAAgB,SAAS,CAAC;AAKrD;AAEO,SAAS,oBAAsC;AACpD,QAAM,SAAS,gBAAgB;AAC/B,MAAI,CAAC,QAAQ,oBAAoB;AAC/B,UAAM,IAAI,MAAM,2EAA2E;AAAA,EAC7F;AACA,SAAO,EAAE,MAAM,OAAO,mBAAmB,EAAE;AAC7C;AAEO,SAAS,sBAA4B;AAC1C,QAAM,SAAS,gBAAgB;AAC/B,MAAI,CAAC,QAAQ,qBAAqB;AAChC,UAAM,IAAI,MAAM,4EAA4E;AAAA,EAC9F;AACA,SAAO,oBAAoB;AAC7B;","names":["path","fs","path","fileURLToPath","createRequire","_require","path","fs","path","fs","path","fs","path","createRequire","_require","init_src","init_src"]}