tailwind-styled-v4 5.0.7 → 5.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +184 -410
  2. package/README.md +45 -15
  3. package/dist/cli.js +62 -52
  4. package/dist/cli.js.map +1 -1
  5. package/dist/cli.mjs +62 -52
  6. package/dist/cli.mjs.map +1 -1
  7. package/dist/compiler.d.mts +8 -3
  8. package/dist/compiler.d.ts +8 -3
  9. package/dist/compiler.js +214 -127
  10. package/dist/compiler.js.map +1 -1
  11. package/dist/compiler.mjs +195 -103
  12. package/dist/compiler.mjs.map +1 -1
  13. package/dist/engine.js +146 -66
  14. package/dist/engine.js.map +1 -1
  15. package/dist/engine.mjs +146 -66
  16. package/dist/engine.mjs.map +1 -1
  17. package/dist/index.d.mts +26 -8
  18. package/dist/index.d.ts +26 -8
  19. package/dist/index.js +72 -19
  20. package/dist/index.js.map +1 -1
  21. package/dist/index.mjs +72 -19
  22. package/dist/index.mjs.map +1 -1
  23. package/dist/next.d.mts +12 -40
  24. package/dist/next.d.ts +12 -40
  25. package/dist/next.js +27 -320
  26. package/dist/next.js.map +1 -1
  27. package/dist/next.mjs +27 -320
  28. package/dist/next.mjs.map +1 -1
  29. package/dist/turbopackLoader.js +137 -88
  30. package/dist/turbopackLoader.js.map +1 -1
  31. package/dist/turbopackLoader.mjs +137 -88
  32. package/dist/turbopackLoader.mjs.map +1 -1
  33. package/dist/tw.js +62 -52
  34. package/dist/tw.js.map +1 -1
  35. package/dist/tw.mjs +62 -52
  36. package/dist/tw.mjs.map +1 -1
  37. package/dist/vite.js +146 -66
  38. package/dist/vite.js.map +1 -1
  39. package/dist/vite.mjs +146 -66
  40. package/dist/vite.mjs.map +1 -1
  41. package/dist/webpackLoader.js +92 -83
  42. package/dist/webpackLoader.js.map +1 -1
  43. package/dist/webpackLoader.mjs +92 -83
  44. package/dist/webpackLoader.mjs.map +1 -1
  45. package/native/tailwind-styled-native.node +0 -0
  46. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"sources":["../packages/domain/shared/src/native-resolution.ts","../packages/domain/shared/src/index.ts","../packages/domain/compiler/src/nativeBridge.ts","../packages/domain/compiler/src/index.ts","../packages/presentation/next/src/turbopackLoader.ts"],"names":["fs","path","isBrowser","nodeModuleRef","getNodeModuleRef","getRequire","require"],"mappings":";;;;;;;;;;;;;AAUA,IAAM,SAAA,GAAY,OAAO,MAAA,KAAW,WAAA,IAAe,OAAO,QAAA,KAAa,WAAA;AAGvE,IAAI,aAAA,GAAqB,IAAA;AACzB,SAAS,gBAAA,GAAmB;AAC1B,EAAA,IAAI,WAAW,OAAO,IAAA;AACtB,EAAA,IAAI,aAAA,KAAkB,MAAM,OAAO,aAAA;AACnC,EAAA,IAAI;AACF,IAAA,MAAM,OAAO,OAAO,SAAA,KAAY,UAAA,GAAa,SAAA,CAAQ,QAAa,CAAA,GAAI,IAAA;AACtE,IAAA,aAAA,GAAgB,IAAA;AAChB,IAAA,OAAO,IAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,aAAA,GAAgB,IAAA;AAChB,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAEA,IAAI,OAAA,GAAe,IAAA;AACnB,IAAI,SAAA,GAAiB,IAAA;AAErB,IAAI,QAAA,GAAgB,IAAA;AAEpB,SAAS,SAAA,GAAY;AACnB,EAAA,IAAI,SAAA,EAAW,OAAO,EAAE,UAAA,EAAY,MAAM,KAAA,EAAM;AAChD,EAAA,MAAM,cAAc,gBAAA,EAAiB;AACrC,EAAA,IAAI,CAAC,WAAA,EAAa,OAAO,EAAE,UAAA,EAAY,MAAM,KAAA,EAAM;AACnD,EAAA,IAAI,CAAC,SAAS,OAAA,GAAU,WAAA,CAAY,cAAc,MAAA,CAAA,IAAA,CAAY,GAAG,EAAE,SAAS,CAAA;AAC5E,EAAA,OAAO,OAAA;AACT;AACA,SAAS,WAAA,GAAc;AACrB,EAAA,IA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,CAAA;AAEvD,EAAA,IAAI;AACF,IAAA,MAAM,SAAS,kBAAA,CAAmB;AAAA,MAChC,UAAU,IAAA,CAAK,YAAA;AAAA,MACf,MAAA,EAAQ,QAAA;AAAA,MACR,OAAA,EAAS;AAAA,KACV,CAAA;AAGD,IAAA,IAAI,CAAC,MAAA,CAAO,OAAA,IAAW,CAAC,MAAA,CAAO,IAAA,CAAK,QAAQ,OAAO,MAAA;AAGnD,IAAA,IAAI,MAAA,CAAO,OAAA,CAAQ,MAAA,GAAS,CAAA,EAAG;AAC7B,MAAA,mBAAA,CAAoB,IAAA,CAAK,YAAA,EAAc,MAAA,CAAO,OAAO,CAAA;AAGrD,MAAA,oBAAA,CAAqB,OAAA,CAAQ,YAAA,EAAc,IAAA,CAAK,YAAA,EAAc,OAAO,OAAO,CAAA;AAAA,IAC9E;AAGA,IAAA,IAAI,CAAC,SAAA,EAAW,OAAO,MAAA,CAAO,IAAA;AAG9B,IAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,IAAA,CAAK,OAAA,CAAQ,kDAAkD,EAAE,CAAA;AACtF,IAAA,OAAO,SAAA,GAAY,KAAA;AAAA,EACrB,SAAS,GAAA,EAAK;AAEZ,IAAA,MAAM,MAAM,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAC3D,IAAA,IAAI,KAAA,EAAO;AACT,MAAA,OAAA,CAAQ,IAAA,CAAK,CAAA,iCAAA,EAAoC,QAAQ,CAAA,EAAA,EAAK,GAAG,CAAA,CAAE,CAAA;AAAA,IACrE;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AACF","file":"turbopackLoader.mjs","sourcesContent":["/**\r\n * Prebuilt binary resolution untuk native NAPI bindings.\r\n * QA #1: Resolve native binary dari prebuilt packages atau local build.\r\n *\r\n * Prioritas:\r\n * 1. TW_NATIVE_PATH env var (explicit override)\r\n * 2. Prebuilt binary dari platform-specific npm package\r\n * 3. Local build dari source (developer mode)\r\n */\r\n\r\nconst isBrowser = typeof window !== \"undefined\" || typeof document !== \"undefined\"\r\n\r\n// ESM-safe require detection\r\nlet nodeModuleRef: any = null\r\nfunction getNodeModuleRef() {\r\n if (isBrowser) return null\r\n if (nodeModuleRef !== null) return nodeModuleRef\r\n try {\r\n const test = typeof require === 'function' ? require('node:module') : null\r\n nodeModuleRef = test\r\n return test\r\n } catch {\r\n nodeModuleRef = null\r\n return null\r\n }\r\n}\r\n\r\nlet _nodeFs: any = null\r\nlet _nodePath: any = null\r\nlet _nodeModule: any = null\r\nlet _require: any = null\r\n\r\nfunction getNodeFs() {\r\n if (isBrowser) return { existsSync: () => false }\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) return { existsSync: () => false }\r\n if (!_nodeFs) _nodeFs = nodeRequire.createRequire(import.meta.url)(\"node:fs\")\r\n return _nodeFs\r\n}\r\nfunction getNodePath() {\r\n if (isBrowser) return { resolve: () => \"\", dirname: \"\" }\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) return { resolve: () => \"\", dirname: \"\" }\r\n if (!_nodePath) _nodePath = nodeRequire.createRequire(import.meta.url)(\"node:path\")\r\n return _nodePath!\r\n}\r\nfunction getNodeModule() {\r\n if (isBrowser) return { createRequire: () => { throw new Error(\"node:module not available\") } }\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) return { createRequire: () => { throw new Error(\"require not available\") } }\r\n if (!_nodeModule) _nodeModule = nodeRequire\r\n return _nodeModule\r\n}\r\nfunction getRequire(_importMetaUrl: string) {\r\n if (isBrowser) return () => { throw new Error(\"node:module not available\") }\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) return () => { throw new Error(\"require not available\") }\r\n if (!_require) _require = nodeRequire.createRequire(_importMetaUrl)\r\n return _require\r\n}\r\n\r\nexport interface NativeResolutionResult {\r\n path: string | null\r\n source: \"env\" | \"prebuilt\" | \"local\" | \"not-found\"\r\n platform: string\r\n tried: string[]\r\n}\r\n\r\n/** Platform key → prebuilt npm package name */\r\nconst PLATFORM_MAP: Record<string, string[]> = {\r\n \"linux-x64\": [\"@tailwind-styled/native-linux-x64\"],\r\n \"linux-arm64\": [\"@tailwind-styled/native-linux-arm64\"],\r\n \"darwin-x64\": [\"@tailwind-styled/native-darwin-x64\"],\r\n \"darwin-arm64\": [\"@tailwind-styled/native-darwin-arm64\"],\r\n \"win32-x64\": [\"@tailwind-styled/native-win32-x64\"],\r\n \"win32-arm64\": [\"@tailwind-styled/native-win32-arm64\"],\r\n}\r\n\r\nfunction platformKey(): string {\r\n if (isBrowser) return \"browser\"\r\n return `${process.platform}-${process.arch}`\r\n}\r\n\r\n/**\r\n * Resolve native binary path dari semua sumber yang tersedia.\r\n *\r\n * @example\r\n * const result = resolveNativeBinary()\r\n * if (result.path) {\r\n * const binding = require(result.path)\r\n * } else {\r\n * throw new Error(\"Native binding not found — run npm run build:rust\")\r\n * }\r\n */\r\nexport function resolveNativeBinary(runtimeDir?: string): NativeResolutionResult {\r\n const platform = platformKey()\r\n const tried: string[] = []\r\n\r\n if (isBrowser) {\r\n return { path: null, source: \"not-found\", platform, tried: [\"not available in browser\"] }\r\n }\r\n\r\n const fs = getNodeFs()\r\n const path = getNodePath()\r\n const _req = getRequire(import.meta.url)\r\n\r\n // 1. Env var override\r\n const envPath = process.env.TW_NATIVE_PATH?.trim()\r\n if (envPath) {\r\n if (fs.existsSync(envPath)) {\r\n return { path: envPath, source: \"env\", platform, tried }\r\n }\r\n tried.push(`env:${envPath} (not found)`)\r\n }\r\n\r\n // 2. Skip jika disabled\r\n if (\r\n process.env.TWS_NO_NATIVE === \"1\" ||\r\n process.env.TWS_NO_RUST === \"1\" ||\r\n process.env.TWS_DISABLE_NATIVE === \"1\"\r\n ) {\r\n return { path: null, source: \"not-found\", platform, tried: [\"disabled by env\"] }\r\n }\r\n\r\n // 3. Prebuilt binary dari platform-specific npm package\r\n const prebuiltPkgs = PLATFORM_MAP[platform] ?? []\r\n for (const pkg of prebuiltPkgs) {\r\n try {\r\n const candidate = _req.resolve(`${pkg}/tailwind_styled_parser.node`)\r\n if (fs.existsSync(candidate)) {\r\n return { path: candidate, source: \"prebuilt\", platform, tried }\r\n }\r\n tried.push(`prebuilt:${pkg} (resolved but missing)`)\r\n } catch {\r\n tried.push(`prebuilt:${pkg} (not installed)`)\r\n }\r\n }\r\n\r\n // 4. Local build candidates\r\n const cwd = process.cwd()\r\n const base = runtimeDir ?? cwd\r\n const localCandidates = [\r\n path.resolve(base, \"tailwind_styled_parser.node\"),\r\n path.resolve(base, \"..\", \"tailwind_styled_parser.node\"),\r\n path.resolve(cwd, \"native\", \"tailwind_styled_parser.node\"),\r\n path.resolve(cwd, \"native\", \"target\", \"release\", \"tailwind_styled_parser.node\"),\r\n // napi-rs conventional output\r\n path.resolve(base, `tailwind_styled_parser.${platform}.node`),\r\n ]\r\n\r\n for (const candidate of localCandidates) {\r\n tried.push(`local:${candidate}`)\r\n if (fs.existsSync(candidate)) {\r\n return { path: candidate, source: \"local\", platform, tried }\r\n }\r\n }\r\n\r\n return { path: null, source: \"not-found\", platform, tried }\r\n}\r\n\r\n/**\r\n * Format human-readable error untuk \"binary not found\".\r\n */\r\nexport function formatNativeNotFoundError(result: NativeResolutionResult): string {\r\n const lines = [\r\n `[tailwind-styled] Native binding not found for ${result.platform}`,\r\n ``,\r\n `Tried:`,\r\n ...result.tried.map(t => ` - ${t}`),\r\n ``,\r\n `Solutions:`,\r\n ` 1. Build locally: npm run build:rust`,\r\n ` 2. Install prebuilt: npm install @tailwind-styled/native-${result.platform}`,\r\n ` 3. Override path: TW_NATIVE_PATH=/path/to/parser.node`,\r\n ` 4. Disable native: TWS_DISABLE_NATIVE=1 (slower, JS fallback)`,\r\n ]\r\n return lines.join(\"\\n\")\r\n}\r\n","const isBrowser = typeof window !== \"undefined\" || typeof document !== \"undefined\"\r\n\r\n// ESM-safe require detection\r\nlet nodeModuleRef: any = null\r\nfunction getNodeModuleRef() {\r\n if (isBrowser) return null\r\n if (nodeModuleRef !== null) return nodeModuleRef\r\n try {\r\n const test = typeof require === 'function' ? require('node:module') : null\r\n nodeModuleRef = test\r\n return test\r\n } catch {\r\n nodeModuleRef = null\r\n return null\r\n }\r\n}\r\n\r\nlet _nodeCrypto: any = null\r\nlet _nodeFs: any = null\r\nlet _nodeModule: any = null\r\nlet _nodePath: any = null\r\nlet _nodeUrl: any = null\r\n\r\nfunction getNodeCrypto() {\r\n if (isBrowser) throw new Error(\"node:crypto not available in browser\")\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) throw new Error(\"require not available\")\r\n if (!_nodeCrypto) _nodeCrypto = nodeRequire.createRequire(import.meta.url)(\"node:crypto\")\r\n return _nodeCrypto!\r\n}\r\nfunction getNodeFs() {\r\n if (isBrowser) throw new Error(\"node:fs not available in browser\")\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) throw new Error(\"require not available\")\r\n if (!_nodeFs) _nodeFs = nodeRequire.createRequire(import.meta.url)(\"node:fs\")\r\n return _nodeFs!\r\n}\r\nfunction getNodeModule() {\r\n if (isBrowser) throw new Error(\"node:module not available in browser\")\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) throw new Error(\"require not available\")\r\n if (!_nodeModule) _nodeModule = nodeRequire\r\n return _nodeModule!\r\n}\r\nfunction getNodePath() {\r\n if (isBrowser) throw new Error(\"node:path not available in browser\")\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) throw new Error(\"require not available\")\r\n if (!_nodePath) _nodePath = nodeRequire.createRequire(import.meta.url)(\"node:path\")\r\n return _nodePath!\r\n}\r\nfunction getNodeUrl() {\r\n if (isBrowser) throw new Error(\"node:url not available in browser\")\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) throw new Error(\"require not available\")\r\n if (!_nodeUrl) _nodeUrl = nodeRequire.createRequire(import.meta.url)(\"node:url\")\r\n return _nodeUrl!\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Types\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport type TokenMap = Record<string, string>\r\n\r\nexport type VariantValue = string | number | boolean | undefined\r\n\r\nexport type VariantProps = Record<string, VariantValue>\r\n\r\nexport type HtmlTagName = keyof HTMLElementTagNameMap\r\n\r\nexport type CompoundCondition = Record<string, string | number | boolean>\r\n\r\nexport type VariantMatrix = Record<string, Array<string | number | boolean>>\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Logging\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport interface Logger {\r\n warn(...args: unknown[]): void\r\n debug(...args: unknown[]): void\r\n error(...args: unknown[]): void\r\n log(...args: unknown[]): void\r\n}\r\n\r\nexport function createLogger(namespace: string): Logger {\r\n const prefix = `[${namespace}]`\r\n return {\r\n warn(...args: unknown[]) {\r\n process.stderr.write(`${prefix} ${args.map(a => typeof a === \"string\" ? a : String(a)).join(\" \")}\\n`)\r\n },\r\n debug(...args: unknown[]) {\r\n process.stderr.write(`${prefix} ${args.map(a => typeof a === \"string\" ? a : String(a)).join(\" \")}\\n`)\r\n },\r\n error(...args: unknown[]) {\r\n process.stderr.write(`${prefix} ${args.map(a => typeof a === \"string\" ? a : String(a)).join(\" \")}\\n`)\r\n },\r\n log(...args: unknown[]) {\r\n process.stderr.write(`${prefix} ${args.map(a => typeof a === \"string\" ? a : String(a)).join(\" \")}\\n`)\r\n },\r\n }\r\n}\r\n\r\nexport function createDebugLogger(namespace: string, label?: string): (msg: string) => void {\r\n const prefix = label ? `[${namespace}:${label}]` : `[${namespace}]`\r\n return (msg: string) => {\r\n if (process.env.DEBUG?.includes(namespace) || process.env.TW_DEBUG) {\r\n console.debug(prefix, msg)\r\n }\r\n }\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Error handling\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport type ErrorSource = \"rust\" | \"validation\" | \"compile\" | \"io\" | \"config\" | \"unknown\"\r\n\r\ntype ZodLikeIssue = {\r\n path?: readonly PropertyKey[]\r\n message?: string\r\n}\r\n\r\nfunction formatIssuePath(path?: readonly PropertyKey[]): string {\r\n if (!path || path.length === 0) return \"(root)\"\r\n return path\r\n .map((segment) =>\r\n typeof segment === \"symbol\" ? segment.description ?? segment.toString() : String(segment)\r\n )\r\n .join(\".\")\r\n}\r\n\r\nexport class TwError extends Error {\r\n /** @deprecated Gunakan source */\r\n public readonly domain: string\r\n public readonly source: ErrorSource\r\n public readonly code: string\r\n public readonly originalCause?: unknown\r\n\r\n constructor(domainOrSource: string, code: string, message: string, cause?: unknown) {\r\n super(message)\r\n this.name = \"TwError\"\r\n this.domain = domainOrSource\r\n this.source = domainOrSource as ErrorSource\r\n this.code = code\r\n this.originalCause = cause\r\n if (Error.captureStackTrace) Error.captureStackTrace(this, TwError)\r\n }\r\n\r\n static fromIo(code: string, message: string): TwError {\r\n return new TwError(\"io\", code, message)\r\n }\r\n\r\n static fromCompile(code: string, message: string): TwError {\r\n return new TwError(\"compile\", code, message)\r\n }\r\n\r\n static fromRust(err: { code?: string; message?: string } | Error | unknown): TwError {\r\n if (err instanceof TwError) return err\r\n if (err instanceof Error) return new TwError(\"rust\", \"RUST_ERROR\", err.message, err)\r\n if (err && typeof err === \"object\") {\r\n const e = err as { code?: string; message?: string }\r\n return new TwError(\"rust\", e.code ?? \"RUST_ERROR\", e.message ?? String(err), err)\r\n }\r\n return new TwError(\"rust\", \"RUST_ERROR\", String(err), err)\r\n }\r\n\r\n /** Buat TwError dari ZodError — dukung shape Zod v3 (`errors`) dan v4 (`issues`). */\r\n static fromZod(err: { issues?: ZodLikeIssue[]; errors?: ZodLikeIssue[] }): TwError {\r\n const first = err.issues?.[0] ?? err.errors?.[0]\r\n const path = formatIssuePath(first?.path)\r\n const message = first ? `${path}: ${first.message}` : \"Schema validation failed\"\r\n return new TwError(\"validation\", \"SCHEMA_VALIDATION_FAILED\", message, err)\r\n }\r\n\r\n static wrap(source: string, code: string, err: unknown): TwError {\r\n if (err instanceof TwError) return err\r\n if (err instanceof Error) return new TwError(source, code, err.message, err)\r\n return new TwError(source, code, String(err), err)\r\n }\r\n\r\n override toString(): string {\r\n return `TwError [${this.source}:${this.code}] ${this.message}`\r\n }\r\n\r\n toJSON(): { name: string; source: string; code: string; message: string } {\r\n return { name: this.name, source: this.source, code: this.code, message: this.message }\r\n }\r\n\r\n toCliMessage(): string {\r\n return `[${this.source.toUpperCase()}:${this.code}] ${this.message}`\r\n }\r\n}\r\n\r\nexport function wrapUnknownError(domain: string, code: string, error: unknown): TwError {\r\n return TwError.wrap(domain, code, error)\r\n}\r\n\r\nexport function isTwError(err: unknown): err is TwError {\r\n return err instanceof TwError\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Native binding resolution\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport interface LoadNativeBindingOptions<T> {\r\n runtimeDir: string\r\n candidates: string[]\r\n isValid: (module: unknown) => module is T\r\n invalidExportMessage: string\r\n}\r\n\r\nexport interface LoadNativeBindingResult<T> {\r\n binding: T | null\r\n loadErrors: Array<{ path: string; message: string }>\r\n loadedPath?: string\r\n}\r\n\r\nexport function loadNativeBinding<T>(options: LoadNativeBindingOptions<T>): LoadNativeBindingResult<T> {\r\n if (isBrowser) {\r\n return { binding: null, loadErrors: [{ path: \"\", message: \"Native bindings not available in browser\" }] }\r\n }\r\n \r\n const { runtimeDir, candidates, isValid } = options\r\n const loadErrors: Array<{ path: string; message: string }> = []\r\n const path = getNodePath()\r\n const fs = getNodeFs()\r\n\r\n for (const candidate of candidates) {\r\n const candidatePath = path.resolve(runtimeDir, candidate)\r\n try {\r\n if (!fs.existsSync(candidatePath) && !fs.existsSync(candidatePath + \".node\")) {\r\n continue\r\n }\r\n const mod = requireNativeModule(candidatePath)\r\n if (mod && isValid(mod)) {\r\n return { binding: mod, loadErrors, loadedPath: candidatePath }\r\n }\r\n loadErrors.push({ path: candidatePath, message: options.invalidExportMessage })\r\n } catch (e) {\r\n loadErrors.push({ path: candidatePath, message: e instanceof Error ? e.message : String(e) })\r\n }\r\n }\r\n\r\n return { binding: null, loadErrors }\r\n}\r\n\r\nfunction getRequire(): NodeRequire {\r\n if (isBrowser) return (() => { throw new Error(\"require not available in browser\") }) as unknown as NodeRequire\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) return (() => { throw new Error(\"require not available\") }) as unknown as NodeRequire\r\n return nodeRequire.createRequire(import.meta.url)\r\n}\r\n\r\nconst _require = getRequire()\r\n\r\nfunction requireNativeModule(path: string): unknown {\r\n return _require(path)\r\n}\r\n\r\nexport interface ResolveCandidatesOptions {\r\n runtimeDir: string\r\n envVarNames?: string[]\r\n includeDefaultCandidates?: boolean\r\n enforceNodeExtensionForEnvPath?: boolean\r\n}\r\n\r\nexport function resolveNativeBindingCandidates(options: ResolveCandidatesOptions): string[] {\r\n if (isBrowser) return []\r\n \r\n const { runtimeDir, envVarNames = [], includeDefaultCandidates = true, enforceNodeExtensionForEnvPath = false } = options\r\n const candidates: string[] = []\r\n const path = getNodePath()\r\n const fs = getNodeFs()\r\n\r\n for (const envVar of envVarNames) {\r\n const envPath = process.env[envVar]\r\n if (envPath) {\r\n if (enforceNodeExtensionForEnvPath && !envPath.endsWith(\".node\")) {\r\n candidates.push(envPath + \".node\")\r\n } else {\r\n candidates.push(envPath)\r\n }\r\n }\r\n }\r\n\r\n if (!includeDefaultCandidates) return candidates\r\n\r\n if (fs.existsSync(runtimeDir)) {\r\n try {\r\n const entries = fs.readdirSync(runtimeDir)\r\n for (const entry of entries) {\r\n if (entry.endsWith(\".node\")) {\r\n candidates.push(entry)\r\n }\r\n }\r\n } catch {\r\n // ignore read errors\r\n }\r\n }\r\n\r\n const platform = typeof process !== \"undefined\" ? process.platform : \"\"\r\n const ext = platform === \"win32\" ? \".dll\" : platform === \"darwin\" ? \".dylib\" : \".so\"\r\n const defaultBindingName = `tailwind_styled_parser${ext}`\r\n candidates.push(path.resolve(runtimeDir, \"..\", \"..\", \"..\", \"native\", defaultBindingName))\r\n candidates.push(path.resolve(runtimeDir, \"..\", \"..\", \"..\", \"..\", \"native\", defaultBindingName))\r\n candidates.push(path.resolve(process.cwd(), \"native\", defaultBindingName))\r\n\r\n return Array.from(new Set(candidates))\r\n}\r\n\r\nexport function resolveRuntimeDir(dir: string | undefined, importMetaUrl: string): string {\r\n if (isBrowser) return \"\"\r\n \r\n if (dir) return getNodePath().resolve(dir)\r\n try {\r\n return getNodeUrl().fileURLToPath(importMetaUrl)\r\n } catch {\r\n return process.cwd()\r\n }\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Hashing\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport function hashContent(content: string, algorithm: string = \"md5\", length?: number): string {\r\n if (isBrowser) {\r\n // Simple hash fallback for browser\r\n let hash = 0\r\n for (let i = 0; i < content.length; i++) {\r\n const char = content.charCodeAt(i)\r\n hash = ((hash << 5) - hash) + char\r\n hash = hash & hash\r\n }\r\n return Math.abs(hash).toString(16).slice(0, length ?? 8)\r\n }\r\n const hash = getNodeCrypto().createHash(algorithm).update(content).digest(\"hex\")\r\n return length ? hash.slice(0, length) : hash\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Error formatting\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport function formatErrorMessage(error: unknown): string {\r\n if (error instanceof TwError) return error.toString()\r\n if (error instanceof Error) return error.message\r\n return String(error)\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// LRU Cache\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport class LRUCache<K, V> {\r\n private capacity: number\r\n private cache: Map<K, V>\r\n\r\n constructor(capacity: number) {\r\n this.capacity = capacity\r\n this.cache = new Map()\r\n }\r\n\r\n get(key: K): V | undefined {\r\n if (!this.cache.has(key)) return undefined\r\n const value = this.cache.get(key)!\r\n this.cache.delete(key)\r\n this.cache.set(key, value)\r\n return value\r\n }\r\n\r\n set(key: K, value: V): void {\r\n if (this.cache.has(key)) {\r\n this.cache.delete(key)\r\n } else if (this.cache.size >= this.capacity) {\r\n const firstKey = this.cache.keys().next().value\r\n if (firstKey !== undefined) {\r\n this.cache.delete(firstKey)\r\n }\r\n }\r\n this.cache.set(key, value)\r\n }\r\n\r\n delete(key: K): boolean {\r\n return this.cache.delete(key)\r\n }\r\n\r\n has(key: K): boolean {\r\n return this.cache.has(key)\r\n }\r\n\r\n clear(): void {\r\n this.cache.clear()\r\n }\r\n\r\n entries(): IterableIterator<[K, V]> {\r\n return this.cache.entries()\r\n }\r\n\r\n get size(): number {\r\n return this.cache.size\r\n }\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Trace Utilities\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport type { TraceSnapshot, TraceSummary } from \"./trace\"\r\nexport {\r\n getHealthColor,\r\n getModeColor,\r\n formatMemory,\r\n formatDuration,\r\n calculateHealth,\r\n getBuildTimeColor,\r\n getMemoryColor,\r\n createTraceSnapshot,\r\n getPipelinePercentages,\r\n} from \"./trace\"\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Performance Telemetry\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\n\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Error Codes\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport type { ErrorCode } from \"./error-codes\"\r\nexport { ERROR_CODES, getSuggestion, formatErrorCode } from \"./error-codes\"\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Tailwind Compatibility\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport type { TailwindInfo } from \"./compatibility\"\r\nexport { detectTailwind, assertTailwindV4, getTailwindVersion, isTailwindV4 } from \"./compatibility\"\r\n\r\n// ── Native binding schemas (Zod boundary validation)\r\nexport {\r\n NativeScanFileSchema, NativeScanResultSchema,\r\n NativeAnalyzerReportSchema, NativeTransformResultSchema,\r\n NativeCssCompileResultSchema, NativeWatchResultSchema,\r\n NativeCacheEntrySchema, NativeCacheReadResultSchema,\r\n safeParseNative, parseNative,\r\n} from './native-schemas'\r\n\r\n// ── ESM-safe runtime helpers ──────────────────────────────────────────────\r\nexport {\r\n createEsmRequire,\r\n getDirname,\r\n getFilename,\r\n resolveFromRoot,\r\n tryRequire,\r\n resolveNativeNodePath,\r\n} from \"./esmHelpers\"\r\n\r\n// ── Performance telemetry ────────────────────────────────────────────────────\r\nexport {\r\n TelemetryCollector,\r\n getGlobalTelemetry,\r\n resetGlobalTelemetry,\r\n createBuildTimer,\r\n type BuildTelemetry,\r\n type TelemetrySummary,\r\n type BuildPhases,\r\n} from \"./telemetry\"\r\n\r\n// ── Config/JSON schema validation ─────────────────────────────────────────────\r\nexport {\r\n ScanCacheSchema,\r\n ScanCacheClassEntrySchema,\r\n TailwindConfigSchema,\r\n RegistryPluginEntrySchema,\r\n RegistryFileSchema,\r\n PackageJsonSchema,\r\n parseJsonWithSchema,\r\n parseJsonFileWithSchema,\r\n type ScanCache,\r\n type ScanCacheClassEntry,\r\n type TailwindConfig,\r\n type RegistryPluginEntry,\r\n type RegistryFile,\r\n type PackageJson,\r\n} from \"./configSchemas\"\r\n\r\n// ── Worker/bootstrap path resolution ─────────────────────────────────────────\r\nexport {\r\n resolveWorkerPath,\r\n resolveLoaderPath,\r\n type WorkerPathOptions,\r\n type WorkerPathResult,\r\n} from \"./workerResolver\"\r\n\r\n// ── Codegen helpers ───────────────────────────────────────────────────────────\r\nexport {\r\n generateComponentCode,\r\n generateStorybookStory,\r\n generateClassRenameCodemod,\r\n generateBarrelFile,\r\n type ComponentCodegenOptions,\r\n} from \"./codegen\"\r\n\r\n// ── Native binary resolution (QA #1) ─────────────────────────────────────────\r\nexport {\r\n resolveNativeBinary,\r\n formatNativeNotFoundError,\r\n type NativeResolutionResult,\r\n} from \"./native-resolution\"\r\n\r\n// ── Shared observability contract ────────────────────────────────────────────\r\nexport {\r\n createObservabilityClient,\r\n type ClassInspection,\r\n type ClassProperty,\r\n type ClassUsageLocation,\r\n type BuildTrace,\r\n type BuildPhaseTrace,\r\n type DashboardMetrics,\r\n type DashboardSummary,\r\n type ObservabilityClient,\r\n} from \"./observability\"\r\n","/**\r\n * tailwind-styled-v5 — Native Bridge Loader\r\n *\r\n * Uses @tailwind-styled/shared for native binding resolution.\r\n * All functions require native Rust binding - no JS fallback.\r\n */\r\n\r\nimport { resolveNativeBinary, resolveRuntimeDir } from \"@tailwind-styled/shared\"\r\nimport { createRequire } from \"node:module\"\r\n\r\nexport interface ComponentMetadata {\r\n component: string\r\n tag: string\r\n baseClass: string\r\n subComponents: Record<string, { tag?: string; class: string }>\r\n}\r\n\r\nexport interface NativeRscResult {\r\n isServer: boolean\r\n needsClientDirective: boolean\r\n clientReasons: string[]\r\n}\r\n\r\nconst log = (...args: unknown[]) => {\r\n if (process.env.DEBUG?.includes(\"compiler:native\")) {\r\n console.log(\"[compiler:native]\", ...args)\r\n }\r\n}\r\n\r\n// ── Type Exports ────────────────────────────────────────────────────────────────\r\n\r\nexport interface NativeBridge {\r\n // Core transform\r\n transformSource?: (source: string, opts?: Record<string, string>) => NativeTransformResult | null\r\n extractClassesFromSource?: (source: string) => string[]\r\n hasTwUsage?: (source: string) => boolean\r\n isAlreadyTransformed?: (source: string) => boolean\r\n // Class Extractor\r\n extractAllClasses?: (source: string) => string[]\r\n parseClasses?: (raw: string) => Array<{ raw: string; type: string }>\r\n // Application functions\r\n extractComponentUsage?: (source: string) => Array<{ component: string; propsJson: string }>\r\n normalizeAndDedupClasses?: (raw: string) => { normalized: string; duplicatesRemoved: number; uniqueCount: number }\r\n diffClassLists?: (previous: string[], current: string[]) => { added: string[]; removed: string[]; unchanged: string[]; hasChanges: boolean }\r\n batchExtractClasses?: (filePaths: string[]) => Array<{ file: string; classes: string[]; contentHash: string; ok: boolean; error?: string }>\r\n checkAgainstSafelist?: (classes: string[], safelist: string[]) => { matched: string[]; unmatched: string[]; safelistSize: number }\r\n // Batch 2\r\n hoistComponents?: (source: string) => { code: string; hoisted: string[]; warnings: string[] }\r\n compileVariantTable?: (configJson: string) => { id: string; tableJson: string; keys: string[]; defaultKey: string; combinations: number }\r\n classifyAndSortClasses?: (classes: string[]) => Array<{ className: string; bucket: string; sortOrder: number }>\r\n mergeCssDeclarations?: (cssChunks: string[]) => { declarationsJson: string; declarationString: string; count: number }\r\n analyzeClassUsage?: (classes: string[], scanResultJson: string, css: string) => Array<{ className: string; usageCount: number; filesJson: string; bundleSizeBytes: number; isDeadCode: boolean }>\r\n analyzeRsc?: (source: string, filename: string) => {\r\n isServer: boolean\r\n needsClientDirective: boolean\r\n clientReasons: string[]\r\n }\r\n analyzeClasses?: (\r\n filesJson: string,\r\n cwd: string,\r\n flags: number\r\n ) => {\r\n css?: string\r\n code: string\r\n classes: string[]\r\n changed: boolean\r\n rscJson?: string\r\n metadataJson?: string\r\n safelist?: string[]\r\n } | null\r\n // CSS compilation\r\n compileCss?: (classes: string[], prefix?: string | null) => { css: string; classes: string[] }\r\n compileCssLightning?: (classes: string[]) => string\r\n}\r\n\r\nexport interface NativeTransformResult {\r\n code: string\r\n classes: string[]\r\n changed: boolean\r\n rscJson?: string\r\n metadataJson?: string\r\n}\r\n\r\nexport interface ClassExtractResult {\r\n classes: string[]\r\n component_names: string[]\r\n has_tw_usage: boolean\r\n has_use_client: boolean\r\n imports: string[]\r\n}\r\n\r\nconst NATIVE_UNAVAILABLE_MESSAGE =\r\n \"[tailwind-styled/compiler v5] Native binding is required but not available.\\n\" +\r\n \"This package requires native Rust bindings. There is no JavaScript fallback.\\n\" +\r\n \"Please ensure:\\n\" +\r\n \" 1. The native module is properly installed\\n\" +\r\n \" 2. You have run: npm run build:rust (or use prebuilt binary)\\n\" +\r\n \"\\n\" +\r\n \"For help, see: https://tailwind-styled.dev/docs/install\"\r\n\r\n// ── Native Bridge - Factory Pattern\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nlet nativeBridge: NativeBridge | null = null\r\nlet bridgeLoadAttempted = false\r\nlet bridgeLoadError: Error | null = null\r\n\r\nconst isValidNativeBridge = (mod: unknown): mod is NativeBridge => {\r\n const m = mod as Partial<NativeBridge>\r\n return !!(\r\n typeof m.transformSource === \"function\" ||\r\n typeof m.extractAllClasses === \"function\" ||\r\n typeof m.hasTwUsage === \"function\"\r\n )\r\n}\r\n\r\nexport const getNativeBridge = (): NativeBridge => {\r\n if (nativeBridge) {\r\n return nativeBridge\r\n }\r\n\r\n if (bridgeLoadAttempted) {\r\n if (bridgeLoadError) {\r\n throw bridgeLoadError\r\n }\r\n throw new Error(NATIVE_UNAVAILABLE_MESSAGE)\r\n }\r\n\r\n bridgeLoadAttempted = true\r\n\r\n try {\r\n const runtimeDir = resolveRuntimeDir(undefined, import.meta.url)\r\n const require = createRequire(import.meta.url)\r\n \r\n // Use shared's native resolution\r\n const result = resolveNativeBinary(runtimeDir)\r\n\r\n if (result.path && result.path.endsWith(\".node\")) {\r\n try {\r\n const binding = require(result.path) as NativeBridge\r\n if (isValidNativeBridge(binding)) {\r\n nativeBridge = binding\r\n log(\"Native bridge loaded successfully from:\", result.path)\r\n return nativeBridge\r\n }\r\n } catch (e) {\r\n log(\"Failed to require native binding:\", e)\r\n }\r\n }\r\n\r\n throw new Error(`${NATIVE_UNAVAILABLE_MESSAGE}\\n\\nTried paths: ${result.tried.join(\"\\n\")}`)\r\n } catch (err) {\r\n bridgeLoadError = err instanceof Error ? err : new Error(String(err))\r\n log(\"Failed to load native bridge:\", bridgeLoadError.message)\r\n throw bridgeLoadError\r\n }\r\n}\r\n\r\nexport const resetNativeBridgeCache = (): void => {\r\n nativeBridge = null\r\n bridgeLoadAttempted = false\r\n bridgeLoadError = null\r\n log(\"Native bridge cache reset\")\r\n}\r\n\r\n// ── Adaptor for native results\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport const adaptNativeResult = (\r\n raw: NativeTransformResult\r\n): {\r\n code: string\r\n classes: string[]\r\n changed: boolean\r\n rsc?: NativeRscResult\r\n metadata?: ComponentMetadata[]\r\n} => {\r\n return {\r\n code: raw.code ?? \"\",\r\n classes: raw.classes ?? [],\r\n changed: raw.changed ?? false,\r\n rsc: raw.rscJson ? JSON.parse(raw.rscJson) : undefined,\r\n metadata: raw.metadataJson ? JSON.parse(raw.metadataJson) : undefined,\r\n }\r\n}\r\n","/**\r\n * tailwind-styled-v5 — Compiler Index\r\n * \r\n * All functions are backed by native Rust bindings.\r\n * No JavaScript fallback - native is required.\r\n */\r\n\r\nimport { getNativeBridge, resetNativeBridgeCache, adaptNativeResult, type NativeBridge, type NativeTransformResult, type ClassExtractResult, type ComponentMetadata, type NativeRscResult } from \"./nativeBridge\"\r\n\r\nexport { getNativeBridge, resetNativeBridgeCache, adaptNativeResult }\r\nexport type { NativeBridge, NativeTransformResult, ClassExtractResult, ComponentMetadata, NativeRscResult }\r\n\r\nexport type LoaderOutput = {\r\n code: string\r\n changed: boolean\r\n classes: string[]\r\n}\r\n\r\n// =============================================================================\r\n// CORE TRANSFORM FUNCTIONS\r\n// =============================================================================\r\n\r\nexport const transformSource = (source: string, opts?: Record<string, unknown>) => {\r\n const native = getNativeBridge()\r\n if (!native?.transformSource) {\r\n throw new Error(\"FATAL: Native binding 'transformSource' is required but not available.\")\r\n }\r\n const result = native.transformSource(source, opts as Record<string, string>)\r\n if (!result) {\r\n throw new Error(\"FATAL: transformSource returned null\")\r\n }\r\n return result\r\n}\r\n\r\nexport const hasTwUsage = (source: string): boolean => {\r\n const native = getNativeBridge()\r\n if (!native?.hasTwUsage) {\r\n throw new Error(\"FATAL: Native binding 'hasTwUsage' is required but not available.\")\r\n }\r\n return native.hasTwUsage(source)\r\n}\r\n\r\nexport const isAlreadyTransformed = (source: string): boolean => {\r\n const native = getNativeBridge()\r\n if (!native?.isAlreadyTransformed) {\r\n throw new Error(\"FATAL: Native binding 'isAlreadyTransformed' is required but not available.\")\r\n }\r\n return native.isAlreadyTransformed(source)\r\n}\r\n\r\nexport const shouldProcess = (source: string): boolean => {\r\n return hasTwUsage(source) && !isAlreadyTransformed(source)\r\n}\r\n\r\n// =============================================================================\r\n// CSS COMPILATION\r\n// =============================================================================\r\n\r\nexport const compileCssFromClasses = (classes: string[], prefix?: string | null) => {\r\n const native = getNativeBridge()\r\n if (!native?.transformSource) {\r\n throw new Error(\"FATAL: Native binding 'transformSource' is required but not available.\")\r\n }\r\n const result = native.transformSource(classes.join(\" \"), { prefix: prefix ?? \"\" })\r\n if (!result) {\r\n throw new Error(\"FATAL: transformSource returned null\")\r\n }\r\n return result\r\n}\r\n\r\nexport const buildStyleTag = (classes: string[]): string => {\r\n const result = compileCssFromClasses(classes)\r\n return result?.code ? `<style data-tailwind-styled>${result.code}</style>` : \"\"\r\n}\r\n\r\nexport const compileCssNative = (classes: string[], prefix: string | null = null) => {\r\n return compileCssFromClasses(classes, prefix)\r\n}\r\n\r\nexport const generateCssForClasses = async (\r\n classes: string[],\r\n _tailwindConfig?: Record<string, unknown>,\r\n _root?: string\r\n): Promise<string> => {\r\n const result = await compileCssFromClasses(classes)\r\n return result?.code || \"\"\r\n}\r\n\r\n// =============================================================================\r\n// CLASS EXTRACTION\r\n// =============================================================================\r\n\r\nexport const extractAllClasses = (source: string): string[] => {\r\n const native = getNativeBridge()\r\n if (!native?.extractAllClasses) {\r\n throw new Error(\"FATAL: Native binding 'extractAllClasses' is required but not available.\")\r\n }\r\n return native.extractAllClasses(source) || []\r\n}\r\n\r\nexport const extractClassesFromSource = (source: string): string => {\r\n const native = getNativeBridge()\r\n if (!native?.extractClassesFromSource) {\r\n throw new Error(\"FATAL: Native binding 'extractClassesFromSource' is required but not available.\")\r\n }\r\n const result = native.extractClassesFromSource(source)\r\n return Array.isArray(result) ? result.join(\" \") : String(result || \"\")\r\n}\r\n\r\nexport const astExtractClasses = (source: string, filename: string) => {\r\n const native = getNativeBridge()\r\n if (!native?.extractClassesFromSource) {\r\n throw new Error(\"FATAL: Native binding 'extractClassesFromSource' is required but not available.\")\r\n }\r\n return native.extractClassesFromSource(source) || []\r\n}\r\n\r\nexport const parseClasses = (raw: string): Array<{ raw: string; type: string }> => {\r\n const native = getNativeBridge()\r\n if (!native?.parseClasses) {\r\n // Fallback to JS implementation\r\n return parseClassesJs(raw)\r\n }\r\n return native.parseClasses(raw) || []\r\n}\r\n\r\nfunction parseClassesJs(raw: string): Array<{ raw: string; type: string }> {\r\n if (!raw || typeof raw !== \"string\") return []\r\n \r\n const classes = raw.split(/\\s+/).filter(Boolean)\r\n return classes.map((cls) => ({\r\n raw: cls,\r\n type: cls.includes(\":\") ? \"variant\" : cls.includes(\"/\") ? \"arbitrary\" : \"utility\",\r\n }))\r\n}\r\n\r\n// =============================================================================\r\n// CLASS NORMALIZATION & MERGING\r\n// =============================================================================\r\n\r\nexport const normalizeClasses = (raw: string): string => {\r\n const result = normalizeAndDedupClasses(raw)\r\n return result?.normalized || \"\"\r\n}\r\n\r\nexport const mergeClassesStatic = (classes: string): string => {\r\n const result = normalizeAndDedupClasses(classes)\r\n return result?.normalized || \"\"\r\n}\r\n\r\nfunction normalizeAndDedupClassesJs(raw: string): { normalized: string; duplicatesRemoved: number; uniqueCount: number } {\r\n const seen = new Set<string>()\r\n const result: string[] = []\r\n let duplicatesRemoved = 0\r\n\r\n for (const token of raw.split(/\\s+/)) {\r\n if (token.length === 0) continue\r\n if (seen.has(token)) {\r\n duplicatesRemoved++\r\n } else {\r\n seen.add(token)\r\n result.push(token)\r\n }\r\n }\r\n\r\n return {\r\n normalized: result.join(\" \"),\r\n duplicatesRemoved,\r\n uniqueCount: result.length,\r\n }\r\n}\r\n\r\nexport const normalizeAndDedupClasses = (raw: string) => {\r\n const native = getNativeBridge()\r\n if (!native?.normalizeAndDedupClasses) {\r\n // Fallback to JS implementation\r\n return normalizeAndDedupClassesJs(raw)\r\n }\r\n const result = native.normalizeAndDedupClasses(raw)\r\n return result || { normalized: \"\", duplicatesRemoved: 0, uniqueCount: 0 }\r\n}\r\n\r\n// =============================================================================\r\n// DEAD STYLE ELIMINATOR\r\n// =============================================================================\r\n\r\nexport const eliminateDeadCss = (css: string, deadClasses: Set<string>): string => {\r\n let result = css\r\n for (const dead of deadClasses) {\r\n result = result.replace(new RegExp(`\\\\.${dead.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}[^{]*\\\\{[^}]*\\\\}`, 'g'), '')\r\n }\r\n return result\r\n}\r\n\r\nexport const findDeadVariants = (variantConfig: Record<string, unknown>, usage: Record<string, Set<string>>) => {\r\n const unused: string[] = []\r\n const variants = variantConfig as Record<string, Record<string, string>>\r\n for (const [key, values] of Object.entries(variants)) {\r\n for (const [value] of Object.entries(values)) {\r\n const keyValue = `${key}:${value}`\r\n if (!usage[key]?.has(value)) {\r\n unused.push(keyValue)\r\n }\r\n }\r\n }\r\n return unused\r\n}\r\n\r\nexport const runElimination = (css: string, scanResult: unknown) => {\r\n const scanJson = JSON.stringify(scanResult)\r\n const classes = extractAllClasses(css)\r\n const usage = analyzeClassUsage(classes, scanJson, css) || []\r\n const deadClasses = new Set((usage as Array<{ isDeadCode: boolean; className: string }>).filter(u => u.isDeadCode).map(u => u.className))\r\n return eliminateDeadCss(css, deadClasses)\r\n}\r\n\r\nexport const optimizeCss = (css: string): string => {\r\n const classes = extractAllClasses(css)\r\n const usage = analyzeClassUsage(classes, \"[]\", css) || []\r\n const usedClasses = new Set((usage as Array<{ isDeadCode: boolean; className: string }>).filter(u => !u.isDeadCode).map(u => u.className))\r\n \r\n let result = css\r\n const classRegex = /\\.([a-zA-Z0-9_-]+)/g\r\n result = result.replace(classRegex, (match, className) => {\r\n return usedClasses.has(className) ? match : ''\r\n })\r\n \r\n result = result.replace(/[^{}]*\\{\\s*\\}/g, '')\r\n return result.trim()\r\n}\r\n\r\nexport const scanProjectUsage = (dirs: string[], cwd: string) => {\r\n const path = require('node:path')\r\n const files = dirs.map(dir => path.resolve(cwd, dir))\r\n const results = batchExtractClasses(files) || []\r\n \r\n const combined: Record<string, Record<string, Set<string>>> = {}\r\n for (const result of results) {\r\n if (result.ok && result.classes) {\r\n for (const cls of result.classes) {\r\n if (!combined[cls]) combined[cls] = {}\r\n combined[cls][result.file] = new Set([cls])\r\n }\r\n }\r\n }\r\n return combined\r\n}\r\n\r\n// =============================================================================\r\n// COMPONENT ANALYSIS\r\n// =============================================================================\r\n\r\nexport const extractComponentUsage = (source: string): Array<{ component: string; propsJson: string }> => {\r\n const native = getNativeBridge()\r\n if (!native?.extractComponentUsage) {\r\n throw new Error(\"FATAL: Native binding 'extractComponentUsage' is required but not available.\")\r\n }\r\n return native.extractComponentUsage(source) || []\r\n}\r\n\r\n// =============================================================================\r\n// DIFF & BATCH OPERATIONS\r\n// =============================================================================\r\n\r\nexport const diffClassLists = (previous: string[], current: string[]) => {\r\n const native = getNativeBridge()\r\n if (!native?.diffClassLists) {\r\n throw new Error(\"FATAL: Native binding 'diffClassLists' is required but not available.\")\r\n }\r\n return native.diffClassLists(previous, current) || { added: [], removed: [], unchanged: [], hasChanges: false }\r\n}\r\n\r\nexport const batchExtractClasses = (filePaths: string[]) => {\r\n const native = getNativeBridge()\r\n if (!native?.batchExtractClasses) {\r\n throw new Error(\"FATAL: Native binding 'batchExtractClasses' is required but not available.\")\r\n }\r\n return native.batchExtractClasses(filePaths) || []\r\n}\r\n\r\nexport const checkAgainstSafelist = (classes: string[], safelist: string[]) => {\r\n const native = getNativeBridge()\r\n if (!native?.checkAgainstSafelist) {\r\n throw new Error(\"FATAL: Native binding 'checkAgainstSafelist' is required but not available.\")\r\n }\r\n return native.checkAgainstSafelist(classes, safelist) || { matched: [], unmatched: [], safelistSize: 0 }\r\n}\r\n\r\n// =============================================================================\r\n// HOISTING\r\n// =============================================================================\r\n\r\nexport const hoistComponents = (source: string) => {\r\n const native = getNativeBridge()\r\n if (!native?.hoistComponents) {\r\n throw new Error(\"FATAL: Native binding 'hoistComponents' is required but not available.\")\r\n }\r\n return native.hoistComponents(source) || { code: source, hoisted: [], warnings: [] }\r\n}\r\n\r\n// =============================================================================\r\n// VARIANT COMPILATION\r\n// =============================================================================\r\n\r\nexport const compileVariantTable = (configJson: string) => {\r\n const native = getNativeBridge()\r\n if (!native?.compileVariantTable) {\r\n throw new Error(\"FATAL: Native binding 'compileVariantTable' is required but not available.\")\r\n }\r\n return native.compileVariantTable(configJson) || { id: \"\", tableJson: \"{}\", keys: [], defaultKey: \"\", combinations: 0 }\r\n}\r\n\r\nexport const compileVariants = (componentId: string, config: Record<string, unknown>) => {\r\n return compileVariantTable(JSON.stringify({ componentId, ...config }))\r\n}\r\n\r\n// =============================================================================\r\n// CSS ANALYSIS\r\n// =============================================================================\r\n\r\nexport const classifyAndSortClasses = (classes: string[]) => {\r\n const native = getNativeBridge()\r\n if (!native?.classifyAndSortClasses) {\r\n throw new Error(\"FATAL: Native binding 'classifyAndSortClasses' is required but not available.\")\r\n }\r\n return native.classifyAndSortClasses(classes) || []\r\n}\r\n\r\nexport const mergeCssDeclarations = (cssChunks: string[]) => {\r\n const native = getNativeBridge()\r\n if (!native?.mergeCssDeclarations) {\r\n throw new Error(\"FATAL: Native binding 'mergeCssDeclarations' is required but not available.\")\r\n }\r\n return native.mergeCssDeclarations(cssChunks) || { declarationsJson: \"{}\", declarationString: \"\", count: 0 }\r\n}\r\n\r\nexport const analyzeClassUsage = (classes: string[], scanResultJson: string, css: string) => {\r\n const native = getNativeBridge()\r\n if (!native?.analyzeClassUsage) {\r\n throw new Error(\"FATAL: Native binding 'analyzeClassUsage' is required but not available.\")\r\n }\r\n return native.analyzeClassUsage(classes, scanResultJson, css) || []\r\n}\r\n\r\n// =============================================================================\r\n// RSC ANALYSIS\r\n// =============================================================================\r\n\r\nexport const analyzeRsc = (source: string, filename: string) => {\r\n const native = getNativeBridge()\r\n if (!native?.analyzeRsc) {\r\n throw new Error(\"FATAL: Native binding 'analyzeRsc' is required but not available.\")\r\n }\r\n return native.analyzeRsc(source, filename) || { isServer: true, needsClientDirective: false, clientReasons: [] }\r\n}\r\n\r\nexport const analyzeFile = (source: string, filename: string) => {\r\n const rsc = analyzeRsc(source, filename)\r\n return {\r\n isServer: rsc?.isServer ?? true,\r\n needsClientDirective: rsc?.needsClientDirective ?? false,\r\n clientReasons: rsc?.clientReasons ?? [],\r\n interactiveClasses: [],\r\n canStaticResolveVariants: true,\r\n }\r\n}\r\n\r\nexport const analyzeVariantUsage = (source: string, componentName: string, variantKeys: string[]) => {\r\n const rsc = analyzeRsc(source, componentName)\r\n return { \r\n resolved: {} as Record<string, string>, \r\n dynamic: [] as string[] \r\n }\r\n}\r\n\r\nexport const injectClientDirective = (source: string): string => {\r\n if (!source.includes('\"use client\"') && !source.includes(\"'use client'\")) {\r\n return '\"use client\";\\n' + source\r\n }\r\n return source\r\n}\r\n\r\nexport const injectServerOnlyComment = (source: string): string => {\r\n return `/* @server-only */\\n${source}`\r\n}\r\n\r\n// =============================================================================\r\n// FULL ANALYSIS\r\n// =============================================================================\r\n\r\nexport const analyzeClasses = (filesJson: string, cwd: string, flags: number) => {\r\n const native = getNativeBridge()\r\n if (!native?.analyzeClasses) {\r\n throw new Error(\"FATAL: Native binding 'analyzeClasses' is required but not available.\")\r\n }\r\n return native.analyzeClasses(filesJson, cwd, flags)\r\n}\r\n\r\n// =============================================================================\r\n// SAFELIST\r\n// =============================================================================\r\n\r\nexport const generateSafelist = (scanDirs: string[], outputPath?: string, cwd?: string) => {\r\n const classes = scanProjectUsage(scanDirs, cwd || process.cwd())\r\n const allClasses = Object.keys(classes).sort()\r\n \r\n if (outputPath) {\r\n const fs = require('node:fs')\r\n fs.writeFileSync(outputPath, JSON.stringify(allClasses, null, 2))\r\n }\r\n \r\n return allClasses\r\n}\r\n\r\nexport const loadSafelist = (safelistPath: string): string[] => {\r\n const fs = require('node:fs')\r\n try {\r\n const content = fs.readFileSync(safelistPath, 'utf-8')\r\n return JSON.parse(content)\r\n } catch {\r\n return []\r\n }\r\n}\r\n\r\n// =============================================================================\r\n// CONFIG LOADING\r\n// =============================================================================\r\n\r\nexport const loadTailwindConfig = (cwd: string = process.cwd()) => {\r\n const fs = require('node:fs')\r\n const path = require('node:path')\r\n \r\n const configFiles = [\r\n 'tailwind.config.ts',\r\n 'tailwind.config.js',\r\n 'tailwind.config.mjs',\r\n 'tailwind.config.cjs',\r\n ]\r\n \r\n for (const file of configFiles) {\r\n const fullPath = path.join(cwd, file)\r\n if (fs.existsSync(fullPath)) {\r\n const mod = require(fullPath)\r\n return mod.default || mod\r\n }\r\n }\r\n \r\n return {}\r\n}\r\n\r\nexport const getContentPaths = (cwd: string = process.cwd()) => {\r\n const path = require('node:path')\r\n return {\r\n content: [\r\n path.join(cwd, 'src/**/*.{js,ts,jsx,tsx}'),\r\n path.join(cwd, 'app/**/*.{js,ts,jsx,tsx}'),\r\n path.join(cwd, 'pages/**/*.{js,ts,jsx,tsx}'),\r\n ],\r\n }\r\n}\r\n\r\n// =============================================================================\r\n// LOADER\r\n// =============================================================================\r\n\r\nexport const runLoaderTransform = (ctx: { filepath: string; source: string; options?: Record<string, unknown> }) => {\r\n const { filepath, source, options } = ctx\r\n const result = transformSource(source, { filename: filepath, ...options })\r\n return {\r\n code: result?.code || \"\",\r\n changed: result?.changed || false,\r\n classes: result?.classes || [],\r\n } as LoaderOutput\r\n}\r\n\r\nexport const shouldSkipFile = (filepath: string): boolean => {\r\n const SKIP_PATHS = ['node_modules', '.next', '.rspack-dist', '.turbo', 'dist/', 'out/']\r\n const skipExtensions = ['.css', '.json', '.md', '.txt', '.yaml', '.yml']\r\n \r\n for (const p of SKIP_PATHS) {\r\n if (filepath.includes(p)) return true\r\n }\r\n for (const ext of skipExtensions) {\r\n if (filepath.endsWith(ext)) return true\r\n }\r\n return false\r\n}\r\n\r\n// =============================================================================\r\n// ROUTE CSS COLLECTOR\r\n// =============================================================================\r\n\r\nexport const fileToRoute = (filepath: string): string | null => {\r\n const normalized = filepath.replace(/\\\\/g, '/')\r\n\r\n // Layout / loading / error — shared across all routes\r\n if (\r\n normalized.includes('/layout.') ||\r\n normalized.includes('/loading.') ||\r\n normalized.includes('/error.')\r\n ) {\r\n return '__global'\r\n }\r\n\r\n // App Router — /app/[...]/page.[tj]sx?\r\n const appPageMatch = normalized.match(/\\/app\\/(.+?)\\/page\\.[tj]sx?$/)\r\n if (appPageMatch) return `/${appPageMatch[1]}`\r\n\r\n const appRootPage = normalized.match(/\\/app\\/page\\.[tj]sx?$/)\r\n if (appRootPage) return '/'\r\n\r\n // Pages Router — /pages/[...].tsx (exclude _app, _document, _error, api/)\r\n const pagesMatch = normalized.match(/\\/pages\\/(.+?)\\.[tj]sx?$/)\r\n if (pagesMatch) {\r\n const pagePath = pagesMatch[1]\r\n if (pagePath.startsWith('_') || pagePath.startsWith('api/')) return '__global'\r\n // /pages/index → /, /pages/about → /about, /pages/blog/[slug] → /blog/[slug]\r\n return pagePath === 'index' ? '/' : `/${pagePath}`\r\n }\r\n\r\n return null\r\n}\r\n\r\nexport const getAllRoutes = (): string[] => {\r\n return Array.from(_routeClassMap.keys())\r\n}\r\n\r\n// In-memory route → classes map (populated by webpack/turbopack loader per file)\r\nconst _routeClassMap = new Map<string, Set<string>>()\r\n\r\nexport const getRouteClasses = (route: string): Set<string> => {\r\n return _routeClassMap.get(route) ?? new Set()\r\n}\r\n\r\nexport const getAllRouteClasses = (): Map<string, Set<string>> => {\r\n return new Map(_routeClassMap)\r\n}\r\n\r\nexport const registerFileClasses = (filepath: string, classes: string[]): void => {\r\n if (!classes.length) return\r\n const route = fileToRoute(filepath) ?? '__global'\r\n const existing = _routeClassMap.get(route) ?? new Set<string>()\r\n for (const cls of classes) existing.add(cls)\r\n _routeClassMap.set(route, existing)\r\n}\r\n\r\nexport const registerGlobalClasses = (classes: string[]): void => {\r\n if (!classes.length) return\r\n const existing = _routeClassMap.get('__global') ?? new Set<string>()\r\n for (const cls of classes) existing.add(cls)\r\n _routeClassMap.set('__global', existing)\r\n}\r\n\r\nexport const clearRouteClasses = (): void => {\r\n _routeClassMap.clear()\r\n}\r\n\r\n// =============================================================================\r\n// INCREMENTAL ENGINE\r\n// =============================================================================\r\n\r\nlet incrementalEngineInstance: unknown = null\r\n\r\nexport const getIncrementalEngine = () => {\r\n if (!incrementalEngineInstance) {\r\n incrementalEngineInstance = {\r\n compile: (source: string) => transformSource(source),\r\n }\r\n }\r\n return incrementalEngineInstance\r\n}\r\n\r\nexport const resetIncrementalEngine = () => {\r\n incrementalEngineInstance = null\r\n}\r\n\r\nexport const IncrementalEngine = class {\r\n compile(source: string) {\r\n return transformSource(source)\r\n }\r\n}\r\n\r\n// =============================================================================\r\n// STYLE BUCKET SYSTEM\r\n// =============================================================================\r\n\r\nlet bucketEngineInstance: unknown = null\r\n\r\nexport const getBucketEngine = () => {\r\n if (!bucketEngineInstance) {\r\n bucketEngineInstance = {\r\n add: (className: string) => className,\r\n get: (bucket: string) => [],\r\n }\r\n }\r\n return bucketEngineInstance\r\n}\r\n\r\nexport const resetBucketEngine = () => {\r\n bucketEngineInstance = null\r\n}\r\n\r\nexport const BucketEngine = class {\r\n add(className: string) {\r\n return className\r\n }\r\n}\r\n\r\nexport const classifyNode = (node: unknown): string => {\r\n return 'unknown'\r\n}\r\n\r\nexport const detectConflicts = (classes: string[]): string[] => {\r\n return []\r\n}\r\n\r\nexport const bucketSort = (classes: string[]): string[] => {\r\n return classes\r\n}","/**\r\n * tailwind-styled-v4 — Turbopack / Webpack Loader\r\n *\r\n * QA #7: Router-aware loader dengan:\r\n * - App Router vs Pages Router detection\r\n * - Directive preservation (use client / use server)\r\n * - Version-specific Next.js optimizations\r\n * - Source map passthrough\r\n * - Skip non-component files (node_modules, .d.ts, already transformed)\r\n */\r\n\r\nimport { runLoaderTransform, registerFileClasses } from \"@tailwind-styled/compiler/internal\"\r\nimport fs from \"node:fs\"\r\nimport path from \"node:path\"\r\n\r\nexport interface TurbopackContext {\r\n /** Absolute path ke file yang sedang di-transform */\r\n resourcePath: string\r\n /** Next.js version (jika di-inject oleh withTailwindStyled) */\r\n query?: Record<string, unknown>\r\n}\r\n\r\nexport interface TurbopackLoaderOptions {\r\n addDataAttr?: boolean | string\r\n autoClientBoundary?: boolean | string\r\n hoist?: boolean | string\r\n preserveImports?: boolean | string\r\n /** Debug mode — log transform details */\r\n debug?: boolean | string\r\n /** Explicit Next.js major version */\r\n nextMajor?: number | string\r\n /** Path ke safelist CSS file — di-inject oleh withTailwindStyled (dev only) */\r\n safelistPath?: string\r\n}\r\n\r\nfunction parseBool(val: boolean | string | undefined, fallback = false): boolean {\r\n if (typeof val === \"boolean\") return val\r\n if (typeof val === \"string\") return val === \"true\" || val === \"1\"\r\n return fallback\r\n}\r\n\r\nfunction parseNum(val: number | string | undefined): number | undefined {\r\n if (typeof val === \"number\") return val\r\n if (typeof val === \"string\") return parseInt(val, 10) || undefined\r\n return undefined\r\n}\r\n\r\nfunction detectRouter(resourcePath: string): \"app\" | \"pages\" | \"unknown\" {\r\n const normalized = resourcePath.replace(/\\\\/g, \"/\")\r\n if (/\\/app\\//.test(normalized)) return \"app\"\r\n if (/\\/pages\\//.test(normalized)) return \"pages\"\r\n return \"unknown\"\r\n}\r\n\r\nfunction isSkippable(resourcePath: string): boolean {\r\n const normalized = resourcePath.replace(/\\\\/g, \"/\")\r\n return (\r\n normalized.includes(\"/node_modules/\") ||\r\n normalized.endsWith(\".d.ts\") ||\r\n normalized.endsWith(\".d.mts\") ||\r\n normalized.endsWith(\".d.cts\") ||\r\n // Skip CSS/assets\r\n /\\.(css|scss|sass|less|svg|png|jpg|jpeg|gif|webp|ico|woff|woff2|ttf|eot)$/.test(normalized)\r\n )\r\n}\r\n\r\n/** Extract directive line dari source */\r\nfunction extractDirective(source: string): { directive: string; stripped: string } {\r\n const match = source.match(/^(\\s*[\"'](use client|use server)[\"']\\s*;?\\s*\\n?)/)\r\n if (!match) return { directive: \"\", stripped: source }\r\n const directive = match[1].trim().replace(/['\"]/g, '\"') + \"\\n\"\r\n const stripped = source.slice(match[0].length)\r\n return { directive, stripped }\r\n}\r\n\r\n\r\n// ─── Per-file safelist writer ─────────────────────────────────────────────────\r\n// Turbopack tidak punya afterCompile hook dan bisa spawn multiple workers.\r\n// Solusi: tiap file menulis file CSS-nya sendiri di .next/tw-classes/<hash>.css\r\n// Tailwind scan seluruh direktori via @source \".next/tw-classes/**\"\r\n// Tidak ada race condition karena tiap file punya output path unik.\r\n\r\nfunction getPerFileSafelistPath(safelistDir: string, resourcePath: string): string {\r\n // Buat nama file yang unik dan filesystem-safe dari resourcePath\r\n const normalized = resourcePath.replace(/\\\\/g, \"/\")\r\n const slug = normalized\r\n .replace(/^.*\\/src\\//, \"\") // strip path prefix sampai src/\r\n .replace(/\\.[tj]sx?$/, \"\") // strip extension\r\n .replace(/[^a-zA-Z0-9]/g, \"_\") // replace non-alphanumeric\r\n .slice(0, 80) // max length\r\n return path.join(safelistDir, `${slug}.css`)\r\n}\r\n\r\nfunction writePerFileSafelist(\r\n safelistPath: string | undefined,\r\n resourcePath: string,\r\n classes: string[]\r\n): void {\r\n if (!safelistPath || classes.length === 0) return\r\n try {\r\n // safelistPath = .next/tailwind-styled-safelist.css\r\n // safelistDir = .next/tw-classes/\r\n const safelistDir = path.join(path.dirname(safelistPath), \"tw-classes\")\r\n const outPath = getPerFileSafelistPath(safelistDir, resourcePath)\r\n\r\n if (!fs.existsSync(safelistDir)) fs.mkdirSync(safelistDir, { recursive: true })\r\n\r\n const sorted = [...new Set(classes)].sort()\r\n const css = [\r\n `/* tw-safelist: ${path.basename(resourcePath)} — auto-generated */`,\r\n \"@layer utilities {\",\r\n sorted.map((cls) => `.${cls.replace(/([^a-zA-Z0-9_-])/g, \"\\\\$1\")} {}`).join(\"\\n\"),\r\n \"}\",\r\n ].join(\"\\n\")\r\n\r\n fs.writeFileSync(outPath, css, \"utf-8\")\r\n } catch {\r\n // Non-fatal\r\n }\r\n}\r\n\r\n/**\r\n * Main loader function — compatible dengan Turbopack, Webpack 5, rspack.\r\n */\r\nexport default function turbopackLoader(\r\n this: TurbopackContext,\r\n source: string,\r\n options: TurbopackLoaderOptions = {}\r\n): string {\r\n // Skip files yang tidak perlu di-transform\r\n if (isSkippable(this.resourcePath)) return source\r\n\r\n // Detect router context\r\n const router = detectRouter(this.resourcePath)\r\n const nextMajor = parseNum(options.nextMajor)\r\n const debug = parseBool(options.debug)\r\n const filename = path.basename(this.resourcePath)\r\n\r\n // Build effective options berdasarkan router context\r\n const effective = {\r\n addDataAttr: parseBool(options.addDataAttr),\r\n // App Router: selalu auto-detect client boundary\r\n // Pages Router: opt-in via option\r\n autoClientBoundary: router === \"app\" ? true : parseBool(options.autoClientBoundary),\r\n // Hoist by default untuk semua contexts\r\n hoist: parseBool(options.hoist, true),\r\n // Pages Router: preserve imports (RSC tidak berlaku)\r\n preserveImports: router === \"pages\" ? true : parseBool(options.preserveImports, false),\r\n }\r\n\r\n if (debug) {\r\n console.debug(`[tw-loader] ${filename}: router=${router} nextMajor=${nextMajor ?? \"unknown\"}`)\r\n }\r\n\r\n // Preserve directive (use client / use server)\r\n const { directive, stripped } = extractDirective(source)\r\n\r\n try {\r\n const output = runLoaderTransform({\r\n filepath: this.resourcePath,\r\n source: stripped,\r\n options: effective,\r\n })\r\n\r\n // Tidak ada perubahan → return original (avoid unnecessary HMR)\r\n if (!output.changed && !output.code.length) return source\r\n\r\n // Register classes untuk route map (dipakai webpack dev plugin & build manifest)\r\n if (output.classes.length > 0) {\r\n registerFileClasses(this.resourcePath, output.classes)\r\n // Turbopack: tulis per-file safelist langsung dari loader.\r\n // Race-condition-safe karena tiap file punya output path unik.\r\n writePerFileSafelist(options.safelistPath, this.resourcePath, output.classes)\r\n }\r\n\r\n // Re-attach directive di depan\r\n if (!directive) return output.code\r\n\r\n // Strip any duplicate directives yang mungkin diinject oleh compiler\r\n const clean = output.code.replace(/^\\s*[\"'](use client|use server)[\"']\\s*;?\\s*\\n?/, \"\")\r\n return directive + clean\r\n } catch (err) {\r\n // Loader harus tidak pernah throw — return source asli dengan warning\r\n const msg = err instanceof Error ? err.message : String(err)\r\n if (debug) {\r\n console.warn(`[tw-loader] transform failed for ${filename}: ${msg}`)\r\n }\r\n return source\r\n }\r\n}"]}
1
+ {"version":3,"sources":["../packages/domain/shared/src/native-resolution.ts","../packages/domain/shared/src/index.ts","../packages/domain/compiler/src/nativeBridge.ts","../packages/domain/compiler/src/index.ts","../packages/presentation/next/src/turbopackLoader.ts"],"names":["fs","path","getNodeModuleRef","isBrowser","nodeModuleRef","getRequire","require"],"mappings":";;;;;;;;;;;;;;;;;AAcA,SAAS,gBAAA,GAAmB;AAC1B,EAAA,IAAI,WAAW,OAAO,IAAA;AACtB,EAAA,IAAI,aAAA,KAAkB,MAAM,OAAO,aAAA;AACnC,EAAA,IAAI;AACF,IAAA,MAAM,OAAO,OAAO,SAAA,KAAY,UAAA,GAAa,SAAA,CAAQ,QAAa,CAAA,GAAI,IAAA;AACtE,IAAA,aAAA,GAAgB,IAAA;AAChB,IAAA,OAAO,IAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,aAAA,GAAgB,IAAA;AAChB,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAOA,SAAS,SAAA,GAAY;AACnB,EAAA,IAAI,SAAA,EAAW,OAAO,EAAE,UAAA,EAAY,MAAM,KAAA,EAAM;AAChD,EAAA,MAAM,cAAc,gBAAA,EAAiB;AACrC,EAAA,IAAI,CAAC,WAAA,EAAa,OAAO,EAAE,UAAA,EAAY,MAAM,KAAA,EAAM;AACnD,EAAA,IAAI,CAAC,SAAS,OAAA,GAAU,WAAA,CAAY,cAAc,MAAA,CAAA,IAAA,CAAY,GAAG,EAAE,SAAS,CAAA;AAC5E,EAAA,OAAO,OAAA;AACT;AACA,SAAS,WAAA,GAAc;AACrB,EAAA,IAAI,WAAW,OAAO,EAAE,SAAS,MAAM,EAAA,EAAI,SAAS,EAAA,EAAG;AACvD,EAAA,MAAM,cAAc,gBAAA,EAAiB;AACrC,EAAA,IAAI,CAAC,aAAa,OAAO,EAAE,SAAS,MAAM,EAAA,EAAI,SAAS,EAAA,EAAG;AAC1D,EAAA,IAAI,C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AA,CAAmB;AAAA,MAChC,UAAU,IAAA,CAAK,YAAA;AAAA,MACf,MAAA,EAAQ,QAAA;AAAA,MACR,OAAA,EAAS;AAAA,KACV,CAAA;AAMD,IAAA,IAAI,CAAC,MAAA,CAAO,OAAA,EAAS,OAAO,MAAA;AAG5B,IAAA,IAAI,MAAA,CAAO,OAAA,CAAQ,MAAA,GAAS,CAAA,EAAG;AAC7B,MAAA,mBAAA,CAAoB,IAAA,CAAK,YAAA,EAAc,MAAA,CAAO,OAAO,CAAA;AAGrD,MAAA,oBAAA,CAAqB,OAAA,CAAQ,YAAA,EAAc,IAAA,CAAK,YAAA,EAAc,OAAO,OAAO,CAAA;AAAA,IAC9E;AAGA,IAAA,IAAI,CAAC,SAAA,EAAW,OAAO,MAAA,CAAO,IAAA;AAG9B,IAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,IAAA,CAAK,OAAA,CAAQ,kDAAkD,EAAE,CAAA;AACtF,IAAA,OAAO,SAAA,GAAY,KAAA;AAAA,EACrB,SAAS,GAAA,EAAK;AAEZ,IAAA,MAAM,MAAM,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAC3D,IAAA,IAAI,KAAA,EAAO;AACT,MAAA,OAAA,CAAQ,IAAA,CAAK,CAAA,iCAAA,EAAoC,QAAQ,CAAA,EAAA,EAAK,GAAG,CAAA,CAAE,CAAA;AAAA,IACrE;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AACF","file":"turbopackLoader.mjs","sourcesContent":["/**\r\n * Prebuilt binary resolution untuk native NAPI bindings.\r\n * QA #1: Resolve native binary dari prebuilt packages atau local build.\r\n *\r\n * Prioritas:\r\n * 1. TW_NATIVE_PATH env var (explicit override)\r\n * 2. Prebuilt binary dari platform-specific npm package\r\n * 3. Local build dari source (developer mode)\r\n */\r\n\r\nconst isBrowser = typeof window !== \"undefined\" || typeof document !== \"undefined\"\r\n\r\n// ESM-safe require detection\r\nlet nodeModuleRef: any = null\r\nfunction getNodeModuleRef() {\r\n if (isBrowser) return null\r\n if (nodeModuleRef !== null) return nodeModuleRef\r\n try {\r\n const test = typeof require === 'function' ? require('node:module') : null\r\n nodeModuleRef = test\r\n return test\r\n } catch {\r\n nodeModuleRef = null\r\n return null\r\n }\r\n}\r\n\r\nlet _nodeFs: any = null\r\nlet _nodePath: any = null\r\nlet _nodeModule: any = null\r\nlet _require: any = null\r\n\r\nfunction getNodeFs() {\r\n if (isBrowser) return { existsSync: () => false }\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) return { existsSync: () => false }\r\n if (!_nodeFs) _nodeFs = nodeRequire.createRequire(import.meta.url)(\"node:fs\")\r\n return _nodeFs\r\n}\r\nfunction getNodePath() {\r\n if (isBrowser) return { resolve: () => \"\", dirname: \"\" }\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) return { resolve: () => \"\", dirname: \"\" }\r\n if (!_nodePath) _nodePath = nodeRequire.createRequire(import.meta.url)(\"node:path\")\r\n return _nodePath!\r\n}\r\nfunction getNodeModule() {\r\n if (isBrowser) return { createRequire: () => { throw new Error(\"node:module not available\") } }\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) return { createRequire: () => { throw new Error(\"require not available\") } }\r\n if (!_nodeModule) _nodeModule = nodeRequire\r\n return _nodeModule\r\n}\r\nfunction getRequire(_importMetaUrl: string) {\r\n if (isBrowser) return () => { throw new Error(\"node:module not available\") }\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) return () => { throw new Error(\"require not available\") }\r\n if (!_require) _require = nodeRequire.createRequire(_importMetaUrl)\r\n return _require\r\n}\r\n\r\nexport interface NativeResolutionResult {\r\n path: string | null\r\n source: \"env\" | \"prebuilt\" | \"local\" | \"not-found\"\r\n platform: string\r\n tried: string[]\r\n}\r\n\r\n/** Platform key → prebuilt npm package name */\r\nconst PLATFORM_MAP: Record<string, string[]> = {\r\n \"linux-x64\": [\"@tailwind-styled/native-linux-x64\"],\r\n \"linux-arm64\": [\"@tailwind-styled/native-linux-arm64\"],\r\n \"darwin-x64\": [\"@tailwind-styled/native-darwin-x64\"],\r\n \"darwin-arm64\": [\"@tailwind-styled/native-darwin-arm64\"],\r\n \"win32-x64\": [\"@tailwind-styled/native-win32-x64\"],\r\n \"win32-arm64\": [\"@tailwind-styled/native-win32-arm64\"],\r\n}\r\n\r\nfunction platformKey(): string {\r\n if (isBrowser) return \"browser\"\r\n return `${process.platform}-${process.arch}`\r\n}\r\n\r\n/**\r\n * Resolve native binary path dari semua sumber yang tersedia.\r\n *\r\n * @example\r\n * const result = resolveNativeBinary()\r\n * if (result.path) {\r\n * const binding = require(result.path)\r\n * } else {\r\n * throw new Error(\"Native binding not found — run npm run build:rust\")\r\n * }\r\n */\r\nexport function resolveNativeBinary(runtimeDir?: string): NativeResolutionResult {\r\n const platform = platformKey()\r\n const tried: string[] = []\r\n\r\n if (isBrowser) {\r\n return { path: null, source: \"not-found\", platform, tried: [\"not available in browser\"] }\r\n }\r\n\r\n const fs = getNodeFs()\r\n const path = getNodePath()\r\n const _req = getRequire(import.meta.url)\r\n\r\n // 1. Env var override\r\n const envPath = process.env.TW_NATIVE_PATH?.trim()\r\n if (envPath) {\r\n if (fs.existsSync(envPath)) {\r\n return { path: envPath, source: \"env\", platform, tried }\r\n }\r\n tried.push(`env:${envPath} (not found)`)\r\n }\r\n\r\n // 2. Skip jika disabled\r\n if (\r\n process.env.TWS_NO_NATIVE === \"1\" ||\r\n process.env.TWS_NO_RUST === \"1\" ||\r\n process.env.TWS_DISABLE_NATIVE === \"1\"\r\n ) {\r\n return { path: null, source: \"not-found\", platform, tried: [\"disabled by env\"] }\r\n }\r\n\r\n // 3. Prebuilt binary dari platform-specific npm package\r\n const prebuiltPkgs = PLATFORM_MAP[platform] ?? []\r\n for (const pkg of prebuiltPkgs) {\r\n try {\r\n const candidate = _req.resolve(`${pkg}/tailwind_styled_parser.node`)\r\n if (fs.existsSync(candidate)) {\r\n return { path: candidate, source: \"prebuilt\", platform, tried }\r\n }\r\n tried.push(`prebuilt:${pkg} (resolved but missing)`)\r\n } catch {\r\n tried.push(`prebuilt:${pkg} (not installed)`)\r\n }\r\n }\r\n\r\n // 4. Local build candidates\r\n const cwd = process.cwd()\r\n const base = runtimeDir ?? cwd\r\n const localCandidates = [\r\n path.resolve(base, \"tailwind_styled_parser.node\"),\r\n path.resolve(base, \"..\", \"tailwind_styled_parser.node\"),\r\n path.resolve(cwd, \"native\", \"tailwind_styled_parser.node\"),\r\n path.resolve(cwd, \"native\", \"target\", \"release\", \"tailwind_styled_parser.node\"),\r\n // napi-rs conventional output\r\n path.resolve(base, `tailwind_styled_parser.${platform}.node`),\r\n ]\r\n\r\n for (const candidate of localCandidates) {\r\n tried.push(`local:${candidate}`)\r\n if (fs.existsSync(candidate)) {\r\n return { path: candidate, source: \"local\", platform, tried }\r\n }\r\n }\r\n\r\n return { path: null, source: \"not-found\", platform, tried }\r\n}\r\n\r\n/**\r\n * Format human-readable error untuk \"binary not found\".\r\n */\r\nexport function formatNativeNotFoundError(result: NativeResolutionResult): string {\r\n const lines = [\r\n `[tailwind-styled] Native binding not found for ${result.platform}`,\r\n ``,\r\n `Tried:`,\r\n ...result.tried.map(t => ` - ${t}`),\r\n ``,\r\n `Solutions:`,\r\n ` 1. Build locally: npm run build:rust`,\r\n ` 2. Install prebuilt: npm install @tailwind-styled/native-${result.platform}`,\r\n ` 3. Override path: TW_NATIVE_PATH=/path/to/parser.node`,\r\n ` 4. Disable native: TWS_DISABLE_NATIVE=1 (slower, JS fallback)`,\r\n ]\r\n return lines.join(\"\\n\")\r\n}\r\n","const isBrowser = typeof window !== \"undefined\" || typeof document !== \"undefined\"\r\n\r\n// ESM-safe require detection\r\nlet nodeModuleRef: any = null\r\nfunction getNodeModuleRef() {\r\n if (isBrowser) return null\r\n if (nodeModuleRef !== null) return nodeModuleRef\r\n try {\r\n const test = typeof require === 'function' ? require('node:module') : null\r\n nodeModuleRef = test\r\n return test\r\n } catch {\r\n nodeModuleRef = null\r\n return null\r\n }\r\n}\r\n\r\nlet _nodeCrypto: any = null\r\nlet _nodeFs: any = null\r\nlet _nodeModule: any = null\r\nlet _nodePath: any = null\r\nlet _nodeUrl: any = null\r\n\r\nfunction getNodeCrypto() {\r\n if (isBrowser) throw new Error(\"node:crypto not available in browser\")\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) throw new Error(\"require not available\")\r\n if (!_nodeCrypto) _nodeCrypto = nodeRequire.createRequire(import.meta.url)(\"node:crypto\")\r\n return _nodeCrypto!\r\n}\r\nfunction getNodeFs() {\r\n if (isBrowser) throw new Error(\"node:fs not available in browser\")\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) throw new Error(\"require not available\")\r\n if (!_nodeFs) _nodeFs = nodeRequire.createRequire(import.meta.url)(\"node:fs\")\r\n return _nodeFs!\r\n}\r\nfunction getNodeModule() {\r\n if (isBrowser) throw new Error(\"node:module not available in browser\")\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) throw new Error(\"require not available\")\r\n if (!_nodeModule) _nodeModule = nodeRequire\r\n return _nodeModule!\r\n}\r\nfunction getNodePath() {\r\n if (isBrowser) throw new Error(\"node:path not available in browser\")\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) throw new Error(\"require not available\")\r\n if (!_nodePath) _nodePath = nodeRequire.createRequire(import.meta.url)(\"node:path\")\r\n return _nodePath!\r\n}\r\nfunction getNodeUrl() {\r\n if (isBrowser) throw new Error(\"node:url not available in browser\")\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) throw new Error(\"require not available\")\r\n if (!_nodeUrl) _nodeUrl = nodeRequire.createRequire(import.meta.url)(\"node:url\")\r\n return _nodeUrl!\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Types\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport type TokenMap = Record<string, string>\r\n\r\nexport type VariantValue = string | number | boolean | undefined\r\n\r\nexport type VariantProps = Record<string, VariantValue>\r\n\r\nexport type HtmlTagName = keyof HTMLElementTagNameMap\r\n\r\nexport type CompoundCondition = Record<string, string | number | boolean>\r\n\r\nexport type VariantMatrix = Record<string, Array<string | number | boolean>>\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Logging\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport interface Logger {\r\n warn(...args: unknown[]): void\r\n debug(...args: unknown[]): void\r\n error(...args: unknown[]): void\r\n log(...args: unknown[]): void\r\n}\r\n\r\nexport function createLogger(namespace: string): Logger {\r\n const prefix = `[${namespace}]`\r\n return {\r\n warn(...args: unknown[]) {\r\n process.stderr.write(`${prefix} ${args.map(a => typeof a === \"string\" ? a : String(a)).join(\" \")}\\n`)\r\n },\r\n debug(...args: unknown[]) {\r\n process.stderr.write(`${prefix} ${args.map(a => typeof a === \"string\" ? a : String(a)).join(\" \")}\\n`)\r\n },\r\n error(...args: unknown[]) {\r\n process.stderr.write(`${prefix} ${args.map(a => typeof a === \"string\" ? a : String(a)).join(\" \")}\\n`)\r\n },\r\n log(...args: unknown[]) {\r\n process.stderr.write(`${prefix} ${args.map(a => typeof a === \"string\" ? a : String(a)).join(\" \")}\\n`)\r\n },\r\n }\r\n}\r\n\r\nexport function createDebugLogger(namespace: string, label?: string): (msg: string) => void {\r\n const prefix = label ? `[${namespace}:${label}]` : `[${namespace}]`\r\n return (msg: string) => {\r\n if (process.env.DEBUG?.includes(namespace) || process.env.TW_DEBUG) {\r\n console.debug(prefix, msg)\r\n }\r\n }\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Error handling\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport type ErrorSource = \"rust\" | \"validation\" | \"compile\" | \"io\" | \"config\" | \"unknown\"\r\n\r\ntype ZodLikeIssue = {\r\n path?: readonly PropertyKey[]\r\n message?: string\r\n}\r\n\r\nfunction formatIssuePath(path?: readonly PropertyKey[]): string {\r\n if (!path || path.length === 0) return \"(root)\"\r\n return path\r\n .map((segment) =>\r\n typeof segment === \"symbol\" ? segment.description ?? segment.toString() : String(segment)\r\n )\r\n .join(\".\")\r\n}\r\n\r\nexport class TwError extends Error {\r\n /** @deprecated Gunakan source */\r\n public readonly domain: string\r\n public readonly source: ErrorSource\r\n public readonly code: string\r\n public readonly originalCause?: unknown\r\n\r\n constructor(domainOrSource: string, code: string, message: string, cause?: unknown) {\r\n super(message)\r\n this.name = \"TwError\"\r\n this.domain = domainOrSource\r\n this.source = domainOrSource as ErrorSource\r\n this.code = code\r\n this.originalCause = cause\r\n if (Error.captureStackTrace) Error.captureStackTrace(this, TwError)\r\n }\r\n\r\n static fromIo(code: string, message: string): TwError {\r\n return new TwError(\"io\", code, message)\r\n }\r\n\r\n static fromCompile(code: string, message: string): TwError {\r\n return new TwError(\"compile\", code, message)\r\n }\r\n\r\n static fromRust(err: { code?: string; message?: string } | Error | unknown): TwError {\r\n if (err instanceof TwError) return err\r\n if (err instanceof Error) return new TwError(\"rust\", \"RUST_ERROR\", err.message, err)\r\n if (err && typeof err === \"object\") {\r\n const e = err as { code?: string; message?: string }\r\n return new TwError(\"rust\", e.code ?? \"RUST_ERROR\", e.message ?? String(err), err)\r\n }\r\n return new TwError(\"rust\", \"RUST_ERROR\", String(err), err)\r\n }\r\n\r\n /** Buat TwError dari ZodError — dukung shape Zod v3 (`errors`) dan v4 (`issues`). */\r\n static fromZod(err: { issues?: ZodLikeIssue[]; errors?: ZodLikeIssue[] }): TwError {\r\n const first = err.issues?.[0] ?? err.errors?.[0]\r\n const path = formatIssuePath(first?.path)\r\n const message = first ? `${path}: ${first.message}` : \"Schema validation failed\"\r\n return new TwError(\"validation\", \"SCHEMA_VALIDATION_FAILED\", message, err)\r\n }\r\n\r\n static wrap(source: string, code: string, err: unknown): TwError {\r\n if (err instanceof TwError) return err\r\n if (err instanceof Error) return new TwError(source, code, err.message, err)\r\n return new TwError(source, code, String(err), err)\r\n }\r\n\r\n override toString(): string {\r\n return `TwError [${this.source}:${this.code}] ${this.message}`\r\n }\r\n\r\n toJSON(): { name: string; source: string; code: string; message: string } {\r\n return { name: this.name, source: this.source, code: this.code, message: this.message }\r\n }\r\n\r\n toCliMessage(): string {\r\n return `[${this.source.toUpperCase()}:${this.code}] ${this.message}`\r\n }\r\n}\r\n\r\nexport function wrapUnknownError(domain: string, code: string, error: unknown): TwError {\r\n return TwError.wrap(domain, code, error)\r\n}\r\n\r\nexport function isTwError(err: unknown): err is TwError {\r\n return err instanceof TwError\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Native binding resolution\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport interface LoadNativeBindingOptions<T> {\r\n runtimeDir: string\r\n candidates: string[]\r\n isValid: (module: unknown) => module is T\r\n invalidExportMessage: string\r\n}\r\n\r\nexport interface LoadNativeBindingResult<T> {\r\n binding: T | null\r\n loadErrors: Array<{ path: string; message: string }>\r\n loadedPath?: string\r\n}\r\n\r\nexport function loadNativeBinding<T>(options: LoadNativeBindingOptions<T>): LoadNativeBindingResult<T> {\r\n if (isBrowser) {\r\n return { binding: null, loadErrors: [{ path: \"\", message: \"Native bindings not available in browser\" }] }\r\n }\r\n \r\n const { runtimeDir, candidates, isValid } = options\r\n const loadErrors: Array<{ path: string; message: string }> = []\r\n const path = getNodePath()\r\n const fs = getNodeFs()\r\n\r\n for (const candidate of candidates) {\r\n const candidatePath = path.resolve(runtimeDir, candidate)\r\n try {\r\n if (!fs.existsSync(candidatePath) && !fs.existsSync(candidatePath + \".node\")) {\r\n continue\r\n }\r\n const mod = requireNativeModule(candidatePath)\r\n if (mod && isValid(mod)) {\r\n return { binding: mod, loadErrors, loadedPath: candidatePath }\r\n }\r\n loadErrors.push({ path: candidatePath, message: options.invalidExportMessage })\r\n } catch (e) {\r\n loadErrors.push({ path: candidatePath, message: e instanceof Error ? e.message : String(e) })\r\n }\r\n }\r\n\r\n return { binding: null, loadErrors }\r\n}\r\n\r\nfunction getRequire(): NodeRequire {\r\n if (isBrowser) return (() => { throw new Error(\"require not available in browser\") }) as unknown as NodeRequire\r\n const nodeRequire = getNodeModuleRef()\r\n if (!nodeRequire) return (() => { throw new Error(\"require not available\") }) as unknown as NodeRequire\r\n return nodeRequire.createRequire(import.meta.url)\r\n}\r\n\r\nconst _require = getRequire()\r\n\r\nfunction requireNativeModule(path: string): unknown {\r\n return _require(path)\r\n}\r\n\r\nexport interface ResolveCandidatesOptions {\r\n runtimeDir: string\r\n envVarNames?: string[]\r\n includeDefaultCandidates?: boolean\r\n enforceNodeExtensionForEnvPath?: boolean\r\n}\r\n\r\nexport function resolveNativeBindingCandidates(options: ResolveCandidatesOptions): string[] {\r\n if (isBrowser) return []\r\n \r\n const { runtimeDir, envVarNames = [], includeDefaultCandidates = true, enforceNodeExtensionForEnvPath = false } = options\r\n const candidates: string[] = []\r\n const path = getNodePath()\r\n const fs = getNodeFs()\r\n\r\n for (const envVar of envVarNames) {\r\n const envPath = process.env[envVar]\r\n if (envPath) {\r\n if (enforceNodeExtensionForEnvPath && !envPath.endsWith(\".node\")) {\r\n candidates.push(envPath + \".node\")\r\n } else {\r\n candidates.push(envPath)\r\n }\r\n }\r\n }\r\n\r\n if (!includeDefaultCandidates) return candidates\r\n\r\n if (fs.existsSync(runtimeDir)) {\r\n try {\r\n const entries = fs.readdirSync(runtimeDir)\r\n for (const entry of entries) {\r\n if (entry.endsWith(\".node\")) {\r\n candidates.push(entry)\r\n }\r\n }\r\n } catch {\r\n // ignore read errors\r\n }\r\n }\r\n\r\n const platform = typeof process !== \"undefined\" ? process.platform : \"\"\r\n const ext = platform === \"win32\" ? \".dll\" : platform === \"darwin\" ? \".dylib\" : \".so\"\r\n const defaultBindingName = `tailwind_styled_parser${ext}`\r\n candidates.push(path.resolve(runtimeDir, \"..\", \"..\", \"..\", \"native\", defaultBindingName))\r\n candidates.push(path.resolve(runtimeDir, \"..\", \"..\", \"..\", \"..\", \"native\", defaultBindingName))\r\n candidates.push(path.resolve(process.cwd(), \"native\", defaultBindingName))\r\n\r\n return Array.from(new Set(candidates))\r\n}\r\n\r\nexport function resolveRuntimeDir(dir: string | undefined, importMetaUrl: string): string {\r\n if (isBrowser) return \"\"\r\n \r\n if (dir) return getNodePath().resolve(dir)\r\n try {\r\n return getNodeUrl().fileURLToPath(importMetaUrl)\r\n } catch {\r\n return process.cwd()\r\n }\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Hashing\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport function hashContent(content: string, algorithm: string = \"md5\", length?: number): string {\r\n if (isBrowser) {\r\n // Simple hash fallback for browser\r\n let hash = 0\r\n for (let i = 0; i < content.length; i++) {\r\n const char = content.charCodeAt(i)\r\n hash = ((hash << 5) - hash) + char\r\n hash = hash & hash\r\n }\r\n return Math.abs(hash).toString(16).slice(0, length ?? 8)\r\n }\r\n const hash = getNodeCrypto().createHash(algorithm).update(content).digest(\"hex\")\r\n return length ? hash.slice(0, length) : hash\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Error formatting\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport function formatErrorMessage(error: unknown): string {\r\n if (error instanceof TwError) return error.toString()\r\n if (error instanceof Error) return error.message\r\n return String(error)\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// LRU Cache\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport class LRUCache<K, V> {\r\n private capacity: number\r\n private cache: Map<K, V>\r\n\r\n constructor(capacity: number) {\r\n this.capacity = capacity\r\n this.cache = new Map()\r\n }\r\n\r\n get(key: K): V | undefined {\r\n if (!this.cache.has(key)) return undefined\r\n const value = this.cache.get(key)!\r\n this.cache.delete(key)\r\n this.cache.set(key, value)\r\n return value\r\n }\r\n\r\n set(key: K, value: V): void {\r\n if (this.cache.has(key)) {\r\n this.cache.delete(key)\r\n } else if (this.cache.size >= this.capacity) {\r\n const firstKey = this.cache.keys().next().value\r\n if (firstKey !== undefined) {\r\n this.cache.delete(firstKey)\r\n }\r\n }\r\n this.cache.set(key, value)\r\n }\r\n\r\n delete(key: K): boolean {\r\n return this.cache.delete(key)\r\n }\r\n\r\n has(key: K): boolean {\r\n return this.cache.has(key)\r\n }\r\n\r\n clear(): void {\r\n this.cache.clear()\r\n }\r\n\r\n entries(): IterableIterator<[K, V]> {\r\n return this.cache.entries()\r\n }\r\n\r\n get size(): number {\r\n return this.cache.size\r\n }\r\n}\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Trace Utilities\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport type { TraceSnapshot, TraceSummary } from \"./trace\"\r\nexport {\r\n getHealthColor,\r\n getModeColor,\r\n formatMemory,\r\n formatDuration,\r\n calculateHealth,\r\n getBuildTimeColor,\r\n getMemoryColor,\r\n createTraceSnapshot,\r\n getPipelinePercentages,\r\n} from \"./trace\"\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Performance Telemetry\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\n\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Error Codes\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport type { ErrorCode } from \"./error-codes\"\r\nexport { ERROR_CODES, getSuggestion, formatErrorCode } from \"./error-codes\"\r\n\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n// Tailwind Compatibility\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport type { TailwindInfo } from \"./compatibility\"\r\nexport { detectTailwind, assertTailwindV4, getTailwindVersion, isTailwindV4 } from \"./compatibility\"\r\n\r\n// ── Native binding schemas (Zod boundary validation)\r\nexport {\r\n NativeScanFileSchema, NativeScanResultSchema,\r\n NativeAnalyzerReportSchema, NativeTransformResultSchema,\r\n NativeCssCompileResultSchema, NativeWatchResultSchema,\r\n NativeCacheEntrySchema, NativeCacheReadResultSchema,\r\n safeParseNative, parseNative,\r\n} from './native-schemas'\r\n\r\n// ── ESM-safe runtime helpers ──────────────────────────────────────────────\r\nexport {\r\n createEsmRequire,\r\n getDirname,\r\n getFilename,\r\n resolveFromRoot,\r\n tryRequire,\r\n resolveNativeNodePath,\r\n} from \"./esmHelpers\"\r\n\r\n// ── Performance telemetry ────────────────────────────────────────────────────\r\nexport {\r\n TelemetryCollector,\r\n getGlobalTelemetry,\r\n resetGlobalTelemetry,\r\n createBuildTimer,\r\n type BuildTelemetry,\r\n type TelemetrySummary,\r\n type BuildPhases,\r\n} from \"./telemetry\"\r\n\r\n// ── Config/JSON schema validation ─────────────────────────────────────────────\r\nexport {\r\n ScanCacheSchema,\r\n ScanCacheClassEntrySchema,\r\n TailwindConfigSchema,\r\n RegistryPluginEntrySchema,\r\n RegistryFileSchema,\r\n PackageJsonSchema,\r\n parseJsonWithSchema,\r\n parseJsonFileWithSchema,\r\n type ScanCache,\r\n type ScanCacheClassEntry,\r\n type TailwindConfig,\r\n type RegistryPluginEntry,\r\n type RegistryFile,\r\n type PackageJson,\r\n} from \"./configSchemas\"\r\n\r\n// ── Worker/bootstrap path resolution ─────────────────────────────────────────\r\nexport {\r\n resolveWorkerPath,\r\n resolveLoaderPath,\r\n type WorkerPathOptions,\r\n type WorkerPathResult,\r\n} from \"./workerResolver\"\r\n\r\n// ── Codegen helpers ───────────────────────────────────────────────────────────\r\nexport {\r\n generateComponentCode,\r\n generateStorybookStory,\r\n generateClassRenameCodemod,\r\n generateBarrelFile,\r\n type ComponentCodegenOptions,\r\n} from \"./codegen\"\r\n\r\n// ── Native binary resolution (QA #1) ─────────────────────────────────────────\r\nexport {\r\n resolveNativeBinary,\r\n formatNativeNotFoundError,\r\n type NativeResolutionResult,\r\n} from \"./native-resolution\"\r\n\r\n// ── Shared observability contract ────────────────────────────────────────────\r\nexport {\r\n createObservabilityClient,\r\n type ClassInspection,\r\n type ClassProperty,\r\n type ClassUsageLocation,\r\n type BuildTrace,\r\n type BuildPhaseTrace,\r\n type DashboardMetrics,\r\n type DashboardSummary,\r\n type ObservabilityClient,\r\n} from \"./observability\"\r\n","/**\r\n * tailwind-styled-v5 — Native Bridge Loader\r\n *\r\n * Uses @tailwind-styled/shared for native binding resolution.\r\n * All functions require native Rust binding - no JS fallback.\r\n */\r\n\r\nimport { resolveNativeBinary, resolveRuntimeDir } from \"@tailwind-styled/shared\"\r\nimport { createRequire } from \"node:module\"\r\n\r\nexport interface ComponentMetadata {\r\n component: string\r\n tag: string\r\n baseClass: string\r\n subComponents: Record<string, { tag?: string; class: string }>\r\n}\r\n\r\nexport interface NativeRscResult {\r\n isServer: boolean\r\n needsClientDirective: boolean\r\n clientReasons: string[]\r\n}\r\n\r\nconst log = (...args: unknown[]) => {\r\n if (process.env.DEBUG?.includes(\"compiler:native\")) {\r\n console.log(\"[compiler:native]\", ...args)\r\n }\r\n}\r\n\r\n// ── Type Exports ────────────────────────────────────────────────────────────────\r\n\r\nexport interface NativeBridge {\r\n // Core transform\r\n transformSource?: (source: string, opts?: Record<string, string>) => NativeTransformResult | null\r\n extractClassesFromSource?: (source: string) => string[]\r\n hasTwUsage?: (source: string) => boolean\r\n isAlreadyTransformed?: (source: string) => boolean\r\n // Class Extractor\r\n extractAllClasses?: (source: string) => string[]\r\n parseClasses?: (raw: string) => Array<{ raw: string; type: string }>\r\n // Application functions\r\n extractComponentUsage?: (source: string) => Array<{ component: string; propsJson: string }>\r\n normalizeAndDedupClasses?: (raw: string) => { normalized: string; duplicatesRemoved: number; uniqueCount: number }\r\n diffClassLists?: (previous: string[], current: string[]) => { added: string[]; removed: string[]; unchanged: string[]; hasChanges: boolean }\r\n batchExtractClasses?: (filePaths: string[]) => Array<{ file: string; classes: string[]; contentHash: string; ok: boolean; error?: string }>\r\n checkAgainstSafelist?: (classes: string[], safelist: string[]) => { matched: string[]; unmatched: string[]; safelistSize: number }\r\n // Batch 2\r\n hoistComponents?: (source: string) => { code: string; hoisted: string[]; warnings: string[] }\r\n compileVariantTable?: (configJson: string) => { id: string; tableJson: string; keys: string[]; defaultKey: string; combinations: number }\r\n classifyAndSortClasses?: (classes: string[]) => Array<{ className: string; bucket: string; sortOrder: number }>\r\n mergeCssDeclarations?: (cssChunks: string[]) => { declarationsJson: string; declarationString: string; count: number }\r\n analyzeClassUsage?: (classes: string[], scanResultJson: string, css: string) => Array<{ className: string; usageCount: number; filesJson: string; bundleSizeBytes: number; isDeadCode: boolean }>\r\n analyzeRsc?: (source: string, filename: string) => {\r\n isServer: boolean\r\n needsClientDirective: boolean\r\n clientReasons: string[]\r\n }\r\n analyzeClasses?: (\r\n filesJson: string,\r\n cwd: string,\r\n flags: number\r\n ) => {\r\n css?: string\r\n code: string\r\n classes: string[]\r\n changed: boolean\r\n rscJson?: string\r\n metadataJson?: string\r\n safelist?: string[]\r\n } | null\r\n // CSS compilation\r\n compileCss?: (classes: string[], prefix?: string | null) => { css: string; classes: string[] }\r\n compileCssLightning?: (classes: string[]) => string\r\n /** Post-process raw Tailwind-generated CSS dengan LightningCSS di Rust */\r\n processTailwindCssLightning?: (css: string) => { css: string; size_bytes: number; resolved_classes: string[]; unknown_classes: string[] }\r\n}\r\n\r\nexport interface NativeTransformResult {\r\n code: string\r\n classes: string[]\r\n changed: boolean\r\n rscJson?: string\r\n metadataJson?: string\r\n}\r\n\r\nexport interface ClassExtractResult {\r\n classes: string[]\r\n component_names: string[]\r\n has_tw_usage: boolean\r\n has_use_client: boolean\r\n imports: string[]\r\n}\r\n\r\nconst NATIVE_UNAVAILABLE_MESSAGE =\r\n \"[tailwind-styled/compiler v5] Native binding is required but not available.\\n\" +\r\n \"This package requires native Rust bindings. There is no JavaScript fallback.\\n\" +\r\n \"Please ensure:\\n\" +\r\n \" 1. The native module is properly installed\\n\" +\r\n \" 2. You have run: npm run build:rust (or use prebuilt binary)\\n\" +\r\n \"\\n\" +\r\n \"For help, see: https://tailwind-styled.dev/docs/install\"\r\n\r\n// ── Native Bridge - Factory Pattern\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nlet nativeBridge: NativeBridge | null = null\r\nlet bridgeLoadAttempted = false\r\nlet bridgeLoadError: Error | null = null\r\n\r\nconst isValidNativeBridge = (mod: unknown): mod is NativeBridge => {\r\n const m = mod as Partial<NativeBridge>\r\n return !!(\r\n typeof m.transformSource === \"function\" ||\r\n typeof m.extractAllClasses === \"function\" ||\r\n typeof m.hasTwUsage === \"function\"\r\n )\r\n}\r\n\r\nexport const getNativeBridge = (): NativeBridge => {\r\n if (nativeBridge) {\r\n return nativeBridge\r\n }\r\n\r\n if (bridgeLoadAttempted) {\r\n if (bridgeLoadError) {\r\n throw bridgeLoadError\r\n }\r\n throw new Error(NATIVE_UNAVAILABLE_MESSAGE)\r\n }\r\n\r\n bridgeLoadAttempted = true\r\n\r\n try {\r\n const runtimeDir = resolveRuntimeDir(undefined, import.meta.url)\r\n const require = createRequire(import.meta.url)\r\n \r\n // Use shared's native resolution\r\n const result = resolveNativeBinary(runtimeDir)\r\n\r\n if (result.path && result.path.endsWith(\".node\")) {\r\n try {\r\n const binding = require(result.path) as NativeBridge\r\n if (isValidNativeBridge(binding)) {\r\n nativeBridge = binding\r\n log(\"Native bridge loaded successfully from:\", result.path)\r\n return nativeBridge\r\n }\r\n } catch (e) {\r\n log(\"Failed to require native binding:\", e)\r\n }\r\n }\r\n\r\n throw new Error(`${NATIVE_UNAVAILABLE_MESSAGE}\\n\\nTried paths: ${result.tried.join(\"\\n\")}`)\r\n } catch (err) {\r\n bridgeLoadError = err instanceof Error ? err : new Error(String(err))\r\n log(\"Failed to load native bridge:\", bridgeLoadError.message)\r\n throw bridgeLoadError\r\n }\r\n}\r\n\r\nexport const resetNativeBridgeCache = (): void => {\r\n nativeBridge = null\r\n bridgeLoadAttempted = false\r\n bridgeLoadError = null\r\n log(\"Native bridge cache reset\")\r\n}\r\n\r\n// ── Adaptor for native results\r\n// ─────────────────────────────────────────────────────────────────────────────\r\n\r\nexport const adaptNativeResult = (\r\n raw: NativeTransformResult\r\n): {\r\n code: string\r\n classes: string[]\r\n changed: boolean\r\n rsc?: NativeRscResult\r\n metadata?: ComponentMetadata[]\r\n} => {\r\n return {\r\n code: raw.code ?? \"\",\r\n classes: raw.classes ?? [],\r\n changed: raw.changed ?? false,\r\n rsc: raw.rscJson ? JSON.parse(raw.rscJson) : undefined,\r\n metadata: raw.metadataJson ? JSON.parse(raw.metadataJson) : undefined,\r\n }\r\n}\r\n\r\n// ── Eager init — load native bridge saat module dimuat, bukan saat request pertama\r\n// Mencegah crash di Turbopack dev mode karena lazy init mid-request\r\n// ─────────────────────────────────────────────────────────────────────────────\r\nif (typeof process !== \"undefined\" && !bridgeLoadAttempted) {\r\n try {\r\n getNativeBridge()\r\n } catch {\r\n // Sudah di-capture di bridgeLoadError — akan di-throw saat dipanggil pertama kali\r\n }\r\n}","/**\r\n * tailwind-styled-v5 — Compiler Index\r\n * \r\n * All functions are backed by native Rust bindings.\r\n * No JavaScript fallback - native is required.\r\n */\r\n\r\nimport { getNativeBridge, resetNativeBridgeCache, adaptNativeResult, type NativeBridge, type NativeTransformResult, type ClassExtractResult, type ComponentMetadata, type NativeRscResult } from \"./nativeBridge\"\r\n\r\nexport { getNativeBridge, resetNativeBridgeCache, adaptNativeResult }\r\nexport type { NativeBridge, NativeTransformResult, ClassExtractResult, ComponentMetadata, NativeRscResult }\r\n\r\nexport type LoaderOutput = {\r\n code: string\r\n changed: boolean\r\n classes: string[]\r\n}\r\n\r\n// =============================================================================\r\n// CORE TRANSFORM FUNCTIONS\r\n// =============================================================================\r\n\r\nexport const transformSource = (source: string, opts?: Record<string, unknown>) => {\r\n const native = getNativeBridge()\r\n if (!native?.transformSource) {\r\n throw new Error(\"FATAL: Native binding 'transformSource' is required but not available.\")\r\n }\r\n const result = native.transformSource(source, opts as Record<string, string>)\r\n if (!result) {\r\n throw new Error(\"FATAL: transformSource returned null\")\r\n }\r\n return result\r\n}\r\n\r\nexport const hasTwUsage = (source: string): boolean => {\r\n const native = getNativeBridge()\r\n if (!native?.hasTwUsage) {\r\n throw new Error(\"FATAL: Native binding 'hasTwUsage' is required but not available.\")\r\n }\r\n return native.hasTwUsage(source)\r\n}\r\n\r\nexport const isAlreadyTransformed = (source: string): boolean => {\r\n const native = getNativeBridge()\r\n if (!native?.isAlreadyTransformed) {\r\n throw new Error(\"FATAL: Native binding 'isAlreadyTransformed' is required but not available.\")\r\n }\r\n return native.isAlreadyTransformed(source)\r\n}\r\n\r\nexport const shouldProcess = (source: string): boolean => {\r\n return hasTwUsage(source) && !isAlreadyTransformed(source)\r\n}\r\n\r\n// =============================================================================\r\n// CSS COMPILATION\r\n// =============================================================================\r\n\r\nexport const compileCssFromClasses = (classes: string[], prefix?: string | null) => {\r\n const native = getNativeBridge()\r\n if (!native?.transformSource) {\r\n throw new Error(\"FATAL: Native binding 'transformSource' is required but not available.\")\r\n }\r\n const result = native.transformSource(classes.join(\" \"), { prefix: prefix ?? \"\" })\r\n if (!result) {\r\n throw new Error(\"FATAL: transformSource returned null\")\r\n }\r\n return result\r\n}\r\n\r\nexport const buildStyleTag = (classes: string[]): string => {\r\n const result = compileCssFromClasses(classes)\r\n return result?.code ? `<style data-tailwind-styled>${result.code}</style>` : \"\"\r\n}\r\n\r\nexport const compileCssNative = (classes: string[], prefix: string | null = null) => {\r\n return compileCssFromClasses(classes, prefix)\r\n}\r\n\r\nexport const generateCssForClasses = async (\r\n classes: string[],\r\n _tailwindConfig?: Record<string, unknown>,\r\n _root?: string\r\n): Promise<string> => {\r\n const { runCssPipeline } = await import(\"./tailwindEngine\")\r\n const result = await runCssPipeline(classes)\r\n return result.css\r\n}\r\n\r\n// =============================================================================\r\n// CLASS EXTRACTION\r\n// =============================================================================\r\n\r\nexport const extractAllClasses = (source: string): string[] => {\r\n const native = getNativeBridge()\r\n if (!native?.extractAllClasses) {\r\n throw new Error(\"FATAL: Native binding 'extractAllClasses' is required but not available.\")\r\n }\r\n return native.extractAllClasses(source) || []\r\n}\r\n\r\nexport const extractClassesFromSource = (source: string): string => {\r\n const native = getNativeBridge()\r\n if (!native?.extractClassesFromSource) {\r\n throw new Error(\"FATAL: Native binding 'extractClassesFromSource' is required but not available.\")\r\n }\r\n const result = native.extractClassesFromSource(source)\r\n return Array.isArray(result) ? result.join(\" \") : String(result || \"\")\r\n}\r\n\r\nexport const astExtractClasses = (source: string, filename: string) => {\r\n const native = getNativeBridge()\r\n if (!native?.extractClassesFromSource) {\r\n throw new Error(\"FATAL: Native binding 'extractClassesFromSource' is required but not available.\")\r\n }\r\n return native.extractClassesFromSource(source) || []\r\n}\r\n\r\nexport const parseClasses = (raw: string): Array<{ raw: string; type: string }> => {\r\n const native = getNativeBridge()\r\n if (!native?.parseClasses) {\r\n // Fallback to JS implementation\r\n return parseClassesJs(raw)\r\n }\r\n return native.parseClasses(raw) || []\r\n}\r\n\r\nfunction parseClassesJs(raw: string): Array<{ raw: string; type: string }> {\r\n if (!raw || typeof raw !== \"string\") return []\r\n \r\n const classes = raw.split(/\\s+/).filter(Boolean)\r\n return classes.map((cls) => ({\r\n raw: cls,\r\n type: cls.includes(\":\") ? \"variant\" : cls.includes(\"/\") ? \"arbitrary\" : \"utility\",\r\n }))\r\n}\r\n\r\n// =============================================================================\r\n// CLASS NORMALIZATION & MERGING\r\n// =============================================================================\r\n\r\nexport const normalizeClasses = (raw: string): string => {\r\n const result = normalizeAndDedupClasses(raw)\r\n return result?.normalized || \"\"\r\n}\r\n\r\nexport const mergeClassesStatic = (classes: string): string => {\r\n const result = normalizeAndDedupClasses(classes)\r\n return result?.normalized || \"\"\r\n}\r\n\r\nfunction normalizeAndDedupClassesJs(raw: string): { normalized: string; duplicatesRemoved: number; uniqueCount: number } {\r\n const seen = new Set<string>()\r\n const result: string[] = []\r\n let duplicatesRemoved = 0\r\n\r\n for (const token of raw.split(/\\s+/)) {\r\n if (token.length === 0) continue\r\n if (seen.has(token)) {\r\n duplicatesRemoved++\r\n } else {\r\n seen.add(token)\r\n result.push(token)\r\n }\r\n }\r\n\r\n return {\r\n normalized: result.join(\" \"),\r\n duplicatesRemoved,\r\n uniqueCount: result.length,\r\n }\r\n}\r\n\r\nexport const normalizeAndDedupClasses = (raw: string) => {\r\n const native = getNativeBridge()\r\n if (!native?.normalizeAndDedupClasses) {\r\n // Fallback to JS implementation\r\n return normalizeAndDedupClassesJs(raw)\r\n }\r\n const result = native.normalizeAndDedupClasses(raw)\r\n return result || { normalized: \"\", duplicatesRemoved: 0, uniqueCount: 0 }\r\n}\r\n\r\n// =============================================================================\r\n// DEAD STYLE ELIMINATOR\r\n// =============================================================================\r\n\r\nexport const eliminateDeadCss = (css: string, deadClasses: Set<string>): string => {\r\n let result = css\r\n for (const dead of deadClasses) {\r\n result = result.replace(new RegExp(`\\\\.${dead.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}[^{]*\\\\{[^}]*\\\\}`, 'g'), '')\r\n }\r\n return result\r\n}\r\n\r\nexport const findDeadVariants = (variantConfig: Record<string, unknown>, usage: Record<string, Set<string>>) => {\r\n const unused: string[] = []\r\n const variants = variantConfig as Record<string, Record<string, string>>\r\n for (const [key, values] of Object.entries(variants)) {\r\n for (const [value] of Object.entries(values)) {\r\n const keyValue = `${key}:${value}`\r\n if (!usage[key]?.has(value)) {\r\n unused.push(keyValue)\r\n }\r\n }\r\n }\r\n return unused\r\n}\r\n\r\nexport const runElimination = (css: string, scanResult: unknown) => {\r\n const scanJson = JSON.stringify(scanResult)\r\n const classes = extractAllClasses(css)\r\n const usage = analyzeClassUsage(classes, scanJson, css) || []\r\n const deadClasses = new Set((usage as Array<{ isDeadCode: boolean; className: string }>).filter(u => u.isDeadCode).map(u => u.className))\r\n return eliminateDeadCss(css, deadClasses)\r\n}\r\n\r\nexport const optimizeCss = (css: string): string => {\r\n const classes = extractAllClasses(css)\r\n const usage = analyzeClassUsage(classes, \"[]\", css) || []\r\n const usedClasses = new Set((usage as Array<{ isDeadCode: boolean; className: string }>).filter(u => !u.isDeadCode).map(u => u.className))\r\n \r\n let result = css\r\n const classRegex = /\\.([a-zA-Z0-9_-]+)/g\r\n result = result.replace(classRegex, (match, className) => {\r\n return usedClasses.has(className) ? match : ''\r\n })\r\n \r\n result = result.replace(/[^{}]*\\{\\s*\\}/g, '')\r\n return result.trim()\r\n}\r\n\r\nexport const scanProjectUsage = (dirs: string[], cwd: string) => {\r\n const path = require('node:path')\r\n const files = dirs.map(dir => path.resolve(cwd, dir))\r\n const results = batchExtractClasses(files) || []\r\n \r\n const combined: Record<string, Record<string, Set<string>>> = {}\r\n for (const result of results) {\r\n if (result.ok && result.classes) {\r\n for (const cls of result.classes) {\r\n if (!combined[cls]) combined[cls] = {}\r\n combined[cls][result.file] = new Set([cls])\r\n }\r\n }\r\n }\r\n return combined\r\n}\r\n\r\n// =============================================================================\r\n// COMPONENT ANALYSIS\r\n// =============================================================================\r\n\r\nexport const extractComponentUsage = (source: string): Array<{ component: string; propsJson: string }> => {\r\n const native = getNativeBridge()\r\n if (!native?.extractComponentUsage) {\r\n throw new Error(\"FATAL: Native binding 'extractComponentUsage' is required but not available.\")\r\n }\r\n return native.extractComponentUsage(source) || []\r\n}\r\n\r\n// =============================================================================\r\n// DIFF & BATCH OPERATIONS\r\n// =============================================================================\r\n\r\nexport const diffClassLists = (previous: string[], current: string[]) => {\r\n const native = getNativeBridge()\r\n if (!native?.diffClassLists) {\r\n throw new Error(\"FATAL: Native binding 'diffClassLists' is required but not available.\")\r\n }\r\n return native.diffClassLists(previous, current) || { added: [], removed: [], unchanged: [], hasChanges: false }\r\n}\r\n\r\nexport const batchExtractClasses = (filePaths: string[]) => {\r\n const native = getNativeBridge()\r\n if (!native?.batchExtractClasses) {\r\n throw new Error(\"FATAL: Native binding 'batchExtractClasses' is required but not available.\")\r\n }\r\n return native.batchExtractClasses(filePaths) || []\r\n}\r\n\r\nexport const checkAgainstSafelist = (classes: string[], safelist: string[]) => {\r\n const native = getNativeBridge()\r\n if (!native?.checkAgainstSafelist) {\r\n throw new Error(\"FATAL: Native binding 'checkAgainstSafelist' is required but not available.\")\r\n }\r\n return native.checkAgainstSafelist(classes, safelist) || { matched: [], unmatched: [], safelistSize: 0 }\r\n}\r\n\r\n// =============================================================================\r\n// HOISTING\r\n// =============================================================================\r\n\r\nexport const hoistComponents = (source: string) => {\r\n const native = getNativeBridge()\r\n if (!native?.hoistComponents) {\r\n throw new Error(\"FATAL: Native binding 'hoistComponents' is required but not available.\")\r\n }\r\n return native.hoistComponents(source) || { code: source, hoisted: [], warnings: [] }\r\n}\r\n\r\n// =============================================================================\r\n// VARIANT COMPILATION\r\n// =============================================================================\r\n\r\nexport const compileVariantTable = (configJson: string) => {\r\n const native = getNativeBridge()\r\n if (!native?.compileVariantTable) {\r\n throw new Error(\"FATAL: Native binding 'compileVariantTable' is required but not available.\")\r\n }\r\n return native.compileVariantTable(configJson) || { id: \"\", tableJson: \"{}\", keys: [], defaultKey: \"\", combinations: 0 }\r\n}\r\n\r\nexport const compileVariants = (componentId: string, config: Record<string, unknown>) => {\r\n return compileVariantTable(JSON.stringify({ componentId, ...config }))\r\n}\r\n\r\n// =============================================================================\r\n// CSS ANALYSIS\r\n// =============================================================================\r\n\r\nexport const classifyAndSortClasses = (classes: string[]) => {\r\n const native = getNativeBridge()\r\n if (!native?.classifyAndSortClasses) {\r\n throw new Error(\"FATAL: Native binding 'classifyAndSortClasses' is required but not available.\")\r\n }\r\n return native.classifyAndSortClasses(classes) || []\r\n}\r\n\r\nexport const mergeCssDeclarations = (cssChunks: string[]) => {\r\n const native = getNativeBridge()\r\n if (!native?.mergeCssDeclarations) {\r\n throw new Error(\"FATAL: Native binding 'mergeCssDeclarations' is required but not available.\")\r\n }\r\n return native.mergeCssDeclarations(cssChunks) || { declarationsJson: \"{}\", declarationString: \"\", count: 0 }\r\n}\r\n\r\nexport const analyzeClassUsage = (classes: string[], scanResultJson: string, css: string) => {\r\n const native = getNativeBridge()\r\n if (!native?.analyzeClassUsage) {\r\n throw new Error(\"FATAL: Native binding 'analyzeClassUsage' is required but not available.\")\r\n }\r\n return native.analyzeClassUsage(classes, scanResultJson, css) || []\r\n}\r\n\r\n// =============================================================================\r\n// RSC ANALYSIS\r\n// =============================================================================\r\n\r\nexport const analyzeRsc = (source: string, filename: string) => {\r\n const native = getNativeBridge()\r\n if (!native?.analyzeRsc) {\r\n throw new Error(\"FATAL: Native binding 'analyzeRsc' is required but not available.\")\r\n }\r\n return native.analyzeRsc(source, filename) || { isServer: true, needsClientDirective: false, clientReasons: [] }\r\n}\r\n\r\nexport const analyzeFile = (source: string, filename: string) => {\r\n const rsc = analyzeRsc(source, filename)\r\n return {\r\n isServer: rsc?.isServer ?? true,\r\n needsClientDirective: rsc?.needsClientDirective ?? false,\r\n clientReasons: rsc?.clientReasons ?? [],\r\n interactiveClasses: [],\r\n canStaticResolveVariants: true,\r\n }\r\n}\r\n\r\nexport const analyzeVariantUsage = (source: string, componentName: string, variantKeys: string[]) => {\r\n const rsc = analyzeRsc(source, componentName)\r\n return { \r\n resolved: {} as Record<string, string>, \r\n dynamic: [] as string[] \r\n }\r\n}\r\n\r\nexport const injectClientDirective = (source: string): string => {\r\n if (!source.includes('\"use client\"') && !source.includes(\"'use client'\")) {\r\n return '\"use client\";\\n' + source\r\n }\r\n return source\r\n}\r\n\r\nexport const injectServerOnlyComment = (source: string): string => {\r\n return `/* @server-only */\\n${source}`\r\n}\r\n\r\n// =============================================================================\r\n// FULL ANALYSIS\r\n// =============================================================================\r\n\r\nexport const analyzeClasses = (filesJson: string, cwd: string, flags: number) => {\r\n const native = getNativeBridge()\r\n if (!native?.analyzeClasses) {\r\n throw new Error(\"FATAL: Native binding 'analyzeClasses' is required but not available.\")\r\n }\r\n return native.analyzeClasses(filesJson, cwd, flags)\r\n}\r\n\r\n// =============================================================================\r\n// SAFELIST\r\n// =============================================================================\r\n\r\nexport const generateSafelist = (scanDirs: string[], outputPath?: string, cwd?: string) => {\r\n const classes = scanProjectUsage(scanDirs, cwd || process.cwd())\r\n const allClasses = Object.keys(classes).sort()\r\n \r\n if (outputPath) {\r\n const fs = require('node:fs')\r\n fs.writeFileSync(outputPath, JSON.stringify(allClasses, null, 2))\r\n }\r\n \r\n return allClasses\r\n}\r\n\r\nexport const loadSafelist = (safelistPath: string): string[] => {\r\n const fs = require('node:fs')\r\n try {\r\n const content = fs.readFileSync(safelistPath, 'utf-8')\r\n return JSON.parse(content)\r\n } catch {\r\n return []\r\n }\r\n}\r\n\r\n// =============================================================================\r\n// CONFIG LOADING\r\n// =============================================================================\r\n\r\nexport const loadTailwindConfig = (cwd: string = process.cwd()) => {\r\n const fs = require('node:fs')\r\n const path = require('node:path')\r\n \r\n const configFiles = [\r\n 'tailwind.config.ts',\r\n 'tailwind.config.js',\r\n 'tailwind.config.mjs',\r\n 'tailwind.config.cjs',\r\n ]\r\n \r\n for (const file of configFiles) {\r\n const fullPath = path.join(cwd, file)\r\n if (fs.existsSync(fullPath)) {\r\n const mod = require(fullPath)\r\n return mod.default || mod\r\n }\r\n }\r\n \r\n return {}\r\n}\r\n\r\nexport const getContentPaths = (cwd: string = process.cwd()) => {\r\n const path = require('node:path')\r\n return {\r\n content: [\r\n path.join(cwd, 'src/**/*.{js,ts,jsx,tsx}'),\r\n path.join(cwd, 'app/**/*.{js,ts,jsx,tsx}'),\r\n path.join(cwd, 'pages/**/*.{js,ts,jsx,tsx}'),\r\n ],\r\n }\r\n}\r\n\r\n// =============================================================================\r\n// LOADER\r\n// =============================================================================\r\n\r\nexport const runLoaderTransform = (ctx: { filepath: string; source: string; options?: Record<string, unknown> }) => {\r\n const { filepath, source, options } = ctx\r\n const result = transformSource(source, { filename: filepath, ...options })\r\n return {\r\n code: result?.code || \"\",\r\n changed: result?.changed || false,\r\n classes: result?.classes || [],\r\n } as LoaderOutput\r\n}\r\n\r\nexport const shouldSkipFile = (filepath: string): boolean => {\r\n const SKIP_PATHS = ['node_modules', '.next', '.rspack-dist', '.turbo', 'dist/', 'out/']\r\n const skipExtensions = ['.css', '.json', '.md', '.txt', '.yaml', '.yml']\r\n \r\n for (const p of SKIP_PATHS) {\r\n if (filepath.includes(p)) return true\r\n }\r\n for (const ext of skipExtensions) {\r\n if (filepath.endsWith(ext)) return true\r\n }\r\n return false\r\n}\r\n\r\n// =============================================================================\r\n// ROUTE CSS COLLECTOR\r\n// =============================================================================\r\n\r\nexport const fileToRoute = (filepath: string): string | null => {\r\n const normalized = filepath.replace(/\\\\/g, '/')\r\n \r\n if (normalized.includes('/layout.') || normalized.includes('/loading.') || normalized.includes('/error.')) {\r\n return '__global'\r\n }\r\n \r\n const pageMatch = normalized.match(/\\/app\\/(.+?)\\/page\\.[tj]sx?$/)\r\n if (pageMatch) return `/${pageMatch[1]}`\r\n \r\n const rootPage = normalized.match(/\\/app\\/page\\.[tj]sx?$/)\r\n if (rootPage) return '/'\r\n \r\n return null\r\n}\r\n\r\nexport const getAllRoutes = (): string[] => {\r\n return ['/', '__global']\r\n}\r\n\r\nexport const getRouteClasses = (route: string): Set<string> => {\r\n return new Set()\r\n}\r\n\r\nexport const registerFileClasses = (filepath: string, classes: string[]): void => {\r\n // Could be implemented with native\r\n}\r\n\r\nexport const registerGlobalClasses = (classes: string[]): void => {\r\n // Could be implemented with native\r\n}\r\n\r\n// =============================================================================\r\n// INCREMENTAL ENGINE\r\n// =============================================================================\r\n\r\nlet incrementalEngineInstance: unknown = null\r\n\r\nexport const getIncrementalEngine = () => {\r\n if (!incrementalEngineInstance) {\r\n incrementalEngineInstance = {\r\n compile: (source: string) => transformSource(source),\r\n }\r\n }\r\n return incrementalEngineInstance\r\n}\r\n\r\nexport const resetIncrementalEngine = () => {\r\n incrementalEngineInstance = null\r\n}\r\n\r\nexport const IncrementalEngine = class {\r\n compile(source: string) {\r\n return transformSource(source)\r\n }\r\n}\r\n\r\n// =============================================================================\r\n// STYLE BUCKET SYSTEM\r\n// =============================================================================\r\n\r\nlet bucketEngineInstance: unknown = null\r\n\r\nexport const getBucketEngine = () => {\r\n if (!bucketEngineInstance) {\r\n bucketEngineInstance = {\r\n add: (className: string) => className,\r\n get: (bucket: string) => [],\r\n }\r\n }\r\n return bucketEngineInstance\r\n}\r\n\r\nexport const resetBucketEngine = () => {\r\n bucketEngineInstance = null\r\n}\r\n\r\nexport const BucketEngine = class {\r\n add(className: string) {\r\n return className\r\n }\r\n}\r\n\r\nexport const classifyNode = (node: unknown): string => {\r\n return 'unknown'\r\n}\r\n\r\nexport const detectConflicts = (classes: string[]): string[] => {\r\n return []\r\n}\r\n\r\nexport const bucketSort = (classes: string[]): string[] => {\r\n return classes\r\n}","/**\r\n * tailwind-styled-v4 — Turbopack / Webpack Loader\r\n *\r\n * QA #7: Router-aware loader dengan:\r\n * - App Router vs Pages Router detection\r\n * - Directive preservation (use client / use server)\r\n * - Version-specific Next.js optimizations\r\n * - Source map passthrough\r\n * - Skip non-component files (node_modules, .d.ts, already transformed)\r\n */\r\n\r\nimport { runLoaderTransform, registerFileClasses } from \"@tailwind-styled/compiler/internal\"\r\nimport fs from \"node:fs\"\r\nimport path from \"node:path\"\r\n\r\nexport interface TurbopackContext {\r\n /** Absolute path ke file yang sedang di-transform */\r\n resourcePath: string\r\n /** Next.js version (jika di-inject oleh withTailwindStyled) */\r\n query?: Record<string, unknown>\r\n}\r\n\r\nexport interface TurbopackLoaderOptions {\r\n addDataAttr?: boolean | string\r\n autoClientBoundary?: boolean | string\r\n hoist?: boolean | string\r\n preserveImports?: boolean | string\r\n /** Debug mode — log transform details */\r\n debug?: boolean | string\r\n /** Explicit Next.js major version */\r\n nextMajor?: number | string\r\n /** Path ke safelist CSS file — di-inject oleh withTailwindStyled (dev only) */\r\n safelistPath?: string\r\n}\r\n\r\nfunction parseBool(val: boolean | string | undefined, fallback = false): boolean {\r\n if (typeof val === \"boolean\") return val\r\n if (typeof val === \"string\") return val === \"true\" || val === \"1\"\r\n return fallback\r\n}\r\n\r\nfunction parseNum(val: number | string | undefined): number | undefined {\r\n if (typeof val === \"number\") return val\r\n if (typeof val === \"string\") return parseInt(val, 10) || undefined\r\n return undefined\r\n}\r\n\r\nfunction detectRouter(resourcePath: string): \"app\" | \"pages\" | \"unknown\" {\r\n const normalized = resourcePath.replace(/\\\\/g, \"/\")\r\n if (/\\/app\\//.test(normalized)) return \"app\"\r\n if (/\\/pages\\//.test(normalized)) return \"pages\"\r\n return \"unknown\"\r\n}\r\n\r\n/**\r\n * Next.js App Router entry-point files yang TIDAK boleh diproses loader ini.\r\n *\r\n * Turbopack tidak support `exclude` di rule level seperti webpack, sehingga\r\n * *.tsx glob akan match layout.tsx, page.tsx, dll. Guard ini memastikan loader\r\n * skip file-file tersebut secara eksplisit — identik dengan NEXT_RSC_ENTRIES\r\n * di withTailwindStyled.ts yang hanya efektif untuk webpack path.\r\n *\r\n * Tanpa guard ini: loader menyentuh layout.tsx → Next.js/React Compiler\r\n * kehilangan sinyal pure RSC → locale injection dari Accept-Language header\r\n * (Next.js 16+) tidak konsisten antara SSR pass dan hydration pass →\r\n * hydration mismatch `lang=\"id\"` vs `lang=\"en\"`.\r\n */\r\nconst NEXT_RSC_ENTRIES =\r\n /(?:^|[\\\\/])(?:layout|page|loading|error|not-found|template|default)\\.[jt]sx?$/\r\n\r\nfunction isSkippable(resourcePath: string): boolean {\r\n const normalized = resourcePath.replace(/\\\\/g, \"/\")\r\n return (\r\n normalized.includes(\"/node_modules/\") ||\r\n normalized.endsWith(\".d.ts\") ||\r\n normalized.endsWith(\".d.mts\") ||\r\n normalized.endsWith(\".d.cts\") ||\r\n // Skip CSS/assets\r\n /\\.(css|scss|sass|less|svg|png|jpg|jpeg|gif|webp|ico|woff|woff2|ttf|eot)$/.test(normalized) ||\r\n // Skip Next.js RSC entry files — Turbopack tidak punya exclude di rule level,\r\n // jadi guard ini menggantikan NEXT_RSC_ENTRIES exclude yang ada di webpack path.\r\n NEXT_RSC_ENTRIES.test(normalized)\r\n )\r\n}\r\n\r\n/** Extract directive line dari source */\r\nfunction extractDirective(source: string): { directive: string; stripped: string } {\r\n const match = source.match(/^(\\s*[\"'](use client|use server)[\"']\\s*;?\\s*\\n?)/)\r\n if (!match) return { directive: \"\", stripped: source }\r\n const directive = match[1].trim().replace(/['\"]/g, '\"') + \"\\n\"\r\n const stripped = source.slice(match[0].length)\r\n return { directive, stripped }\r\n}\r\n\r\n\r\n// ─── Per-file safelist writer ─────────────────────────────────────────────────\r\n// Turbopack tidak punya afterCompile hook dan bisa spawn multiple workers.\r\n// Solusi: tiap file menulis file CSS-nya sendiri di .next/tw-classes/<slug>.css\r\n// Tailwind scan seluruh direktori via @source \".next/tw-classes/**\"\r\n// Tidak ada race condition karena tiap file punya output path unik.\r\n//\r\n// Stale file handling:\r\n// - Setiap dev server start, Next.js hapus .next/ → tw-classes/ otomatis hilang\r\n// - Setiap compile cycle, TwSafelistDevPlugin (webpack) clear tw-classes/\r\n// - Turbopack: pakai _cycle sentinel file — kalau cycle berubah, clear dulu\r\n\r\n// ─── Cycle ID ─────────────────────────────────────────────────────────────────\r\n// withTailwindStyled menulis _start.txt saat wrap() dipanggil (= saat next.config.ts\r\n// di-load, yaitu sekali per dev server start). Setiap compile cycle Turbopack,\r\n// loader baca _start.txt dan compare dengan _cycle.txt di tw-classes/:\r\n//\r\n// _start.txt = timestamp dev server start (ditulis withTailwindStyled)\r\n// _cycle.txt = timestamp cycle terakhir (ditulis loader pertama di tiap cycle)\r\n//\r\n// Kalau _cycle.txt != _start.txt → compile cycle baru → clear tw-classes/ dulu.\r\n// Ini solve masalah \"file yang dihapus tetap ada di safelist\" tanpa butuh hook.\r\n\r\nconst CYCLE_SENTINEL = \"_cycle.txt\"\r\nconst START_SENTINEL = \"_start.txt\"\r\n\r\n// Cached per worker instance — hindari readFileSync berulang di file yang sama\r\nconst _workerCache = new Map<string, string>()\r\n\r\nfunction getTwClassesDir(safelistPath: string): string {\r\n return path.join(path.dirname(safelistPath), \"tw-classes\")\r\n}\r\n\r\nfunction readSentinel(filePath: string): string {\r\n try { return fs.readFileSync(filePath, \"utf-8\").trim() } catch { return \"\" }\r\n}\r\n\r\nfunction clearAndMarkCycle(twClassesDir: string, startId: string): void {\r\n try {\r\n if (fs.existsSync(twClassesDir)) {\r\n for (const file of fs.readdirSync(twClassesDir)) {\r\n if (file === START_SENTINEL || file === \"_webpack-merged.css\") continue\r\n try { fs.unlinkSync(path.join(twClassesDir, file)) } catch { /* non-fatal */ }\r\n }\r\n } else {\r\n fs.mkdirSync(twClassesDir, { recursive: true })\r\n }\r\n fs.writeFileSync(path.join(twClassesDir, CYCLE_SENTINEL), startId, \"utf-8\")\r\n _workerCache.set(twClassesDir, startId)\r\n } catch { /* non-fatal */ }\r\n}\r\n\r\nfunction getPerFileSafelistPath(safelistDir: string, resourcePath: string): string {\r\n const normalized = resourcePath.replace(/\\\\/g, \"/\")\r\n const slug = normalized\r\n .replace(/^.*\\/src\\//, \"\")\r\n .replace(/\\.[tj]sx?$/, \"\")\r\n .replace(/[^a-zA-Z0-9]/g, \"_\")\r\n .slice(0, 80)\r\n return path.join(safelistDir, `${slug}.css`)\r\n}\r\n\r\nfunction writePerFileSafelist(\r\n safelistPath: string | undefined,\r\n resourcePath: string,\r\n classes: string[]\r\n): void {\r\n if (!safelistPath || classes.length === 0) return\r\n try {\r\n const twClassesDir = getTwClassesDir(safelistPath)\r\n\r\n // Baca start ID dari _start.txt (ditulis withTailwindStyled saat config load)\r\n const startId = readSentinel(path.join(twClassesDir, START_SENTINEL))\r\n\r\n // Compare dengan cycle ID terakhir — pakai in-memory cache dulu, fallback ke disk\r\n const cachedCycle = _workerCache.get(twClassesDir) ?? readSentinel(path.join(twClassesDir, CYCLE_SENTINEL))\r\n\r\n if (startId && cachedCycle !== startId) {\r\n // Compile cycle baru — clear tw-classes/ dan tulis _cycle.txt baru\r\n clearAndMarkCycle(twClassesDir, startId)\r\n } else if (!fs.existsSync(twClassesDir)) {\r\n fs.mkdirSync(twClassesDir, { recursive: true })\r\n }\r\n\r\n const outPath = getPerFileSafelistPath(twClassesDir, resourcePath)\r\n const sorted = [...new Set(classes)].sort()\r\n const css = [\r\n `/* tw-safelist: ${path.basename(resourcePath)} — auto-generated */`,\r\n \"@layer utilities {\",\r\n sorted.map((cls) => `.${cls.replace(/([^a-zA-Z0-9_-])/g, \"\\\\$1\")} {}`).join(\"\\n\"),\r\n \"}\",\r\n ].join(\"\\n\")\r\n\r\n // Skip write jika isi sama — avoid Tailwind re-scan yang tidak perlu\r\n try {\r\n if (fs.readFileSync(outPath, \"utf-8\") === css) return\r\n } catch { /* file belum ada, lanjut write */ }\r\n\r\n fs.writeFileSync(outPath, css, \"utf-8\")\r\n } catch {\r\n // Non-fatal\r\n }\r\n}\r\n\r\n/**\r\n * Main loader function — compatible dengan Turbopack, Webpack 5, rspack.\r\n */\r\nexport default function turbopackLoader(\r\n this: TurbopackContext,\r\n source: string,\r\n options: TurbopackLoaderOptions = {}\r\n): string {\r\n // Skip files yang tidak perlu di-transform\r\n if (isSkippable(this.resourcePath)) return source\r\n\r\n // Detect router context\r\n const router = detectRouter(this.resourcePath)\r\n const nextMajor = parseNum(options.nextMajor)\r\n const debug = parseBool(options.debug)\r\n const filename = path.basename(this.resourcePath)\r\n\r\n // Build effective options berdasarkan router context\r\n const effective = {\r\n addDataAttr: parseBool(options.addDataAttr),\r\n // App Router: selalu auto-detect client boundary\r\n // Pages Router: opt-in via option\r\n autoClientBoundary: router === \"app\" ? true : parseBool(options.autoClientBoundary),\r\n // Hoist by default untuk semua contexts\r\n hoist: parseBool(options.hoist, true),\r\n // Pages Router: preserve imports (RSC tidak berlaku)\r\n preserveImports: router === \"pages\" ? true : parseBool(options.preserveImports, false),\r\n }\r\n\r\n if (debug) {\r\n console.debug(`[tw-loader] ${filename}: router=${router} nextMajor=${nextMajor ?? \"unknown\"}`)\r\n }\r\n\r\n // Preserve directive (use client / use server)\r\n const { directive, stripped } = extractDirective(source)\r\n\r\n try {\r\n const output = runLoaderTransform({\r\n filepath: this.resourcePath,\r\n source: stripped,\r\n options: effective,\r\n })\r\n\r\n // Tidak ada perubahan — Rust kembalikan source asli (bukan string kosong).\r\n // Guard lama `!output.code.length` selalu false karena code = original source.\r\n // Fix: cukup cek changed flag saja; return source asli agar Next.js RSC boundary\r\n // tetap intact dan tidak ada interaksi dengan React Compiler locale detection.\r\n if (!output.changed) return source\r\n\r\n // Register classes untuk route map (dipakai webpack dev plugin & build manifest)\r\n if (output.classes.length > 0) {\r\n registerFileClasses(this.resourcePath, output.classes)\r\n // Turbopack: tulis per-file safelist langsung dari loader.\r\n // Race-condition-safe karena tiap file punya output path unik.\r\n writePerFileSafelist(options.safelistPath, this.resourcePath, output.classes)\r\n }\r\n\r\n // Re-attach directive di depan\r\n if (!directive) return output.code\r\n\r\n // Strip any duplicate directives yang mungkin diinject oleh compiler\r\n const clean = output.code.replace(/^\\s*[\"'](use client|use server)[\"']\\s*;?\\s*\\n?/, \"\")\r\n return directive + clean\r\n } catch (err) {\r\n // Loader harus tidak pernah throw — return source asli dengan warning\r\n const msg = err instanceof Error ? err.message : String(err)\r\n if (debug) {\r\n console.warn(`[tw-loader] transform failed for ${filename}: ${msg}`)\r\n }\r\n return source\r\n }\r\n}"]}
package/dist/tw.js CHANGED
@@ -5941,6 +5941,67 @@ var init_createApp = __esm({
5941
5941
  };
5942
5942
  }
5943
5943
  });
5944
+ var log3, NATIVE_UNAVAILABLE_MESSAGE, nativeBridge, bridgeLoadAttempted, bridgeLoadError, isValidNativeBridge, getNativeBridge;
5945
+ var init_nativeBridge = __esm({
5946
+ "packages/domain/compiler/src/nativeBridge.ts"() {
5947
+ init_src();
5948
+ log3 = (...args) => {
5949
+ if (process.env.DEBUG?.includes("compiler:native")) {
5950
+ console.log("[compiler:native]", ...args);
5951
+ }
5952
+ };
5953
+ NATIVE_UNAVAILABLE_MESSAGE = "[tailwind-styled/compiler v5] Native binding is required but not available.\nThis package requires native Rust bindings. There is no JavaScript fallback.\nPlease ensure:\n 1. The native module is properly installed\n 2. You have run: npm run build:rust (or use prebuilt binary)\n\nFor help, see: https://tailwind-styled.dev/docs/install";
5954
+ nativeBridge = null;
5955
+ bridgeLoadAttempted = false;
5956
+ bridgeLoadError = null;
5957
+ isValidNativeBridge = (mod) => {
5958
+ const m = mod;
5959
+ return !!(typeof m.transformSource === "function" || typeof m.extractAllClasses === "function" || typeof m.hasTwUsage === "function");
5960
+ };
5961
+ getNativeBridge = () => {
5962
+ if (nativeBridge) {
5963
+ return nativeBridge;
5964
+ }
5965
+ if (bridgeLoadAttempted) {
5966
+ if (bridgeLoadError) {
5967
+ throw bridgeLoadError;
5968
+ }
5969
+ throw new Error(NATIVE_UNAVAILABLE_MESSAGE);
5970
+ }
5971
+ bridgeLoadAttempted = true;
5972
+ try {
5973
+ const runtimeDir = resolveRuntimeDir(void 0, (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href)));
5974
+ const require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href)));
5975
+ const result = resolveNativeBinary(runtimeDir);
5976
+ if (result.path && result.path.endsWith(".node")) {
5977
+ try {
5978
+ const binding = require2(result.path);
5979
+ if (isValidNativeBridge(binding)) {
5980
+ nativeBridge = binding;
5981
+ log3("Native bridge loaded successfully from:", result.path);
5982
+ return nativeBridge;
5983
+ }
5984
+ } catch (e) {
5985
+ log3("Failed to require native binding:", e);
5986
+ }
5987
+ }
5988
+ throw new Error(`${NATIVE_UNAVAILABLE_MESSAGE}
5989
+
5990
+ Tried paths: ${result.tried.join("\n")}`);
5991
+ } catch (err) {
5992
+ bridgeLoadError = err instanceof Error ? err : new Error(String(err));
5993
+ log3("Failed to load native bridge:", bridgeLoadError.message);
5994
+ throw bridgeLoadError;
5995
+ }
5996
+ };
5997
+ if (typeof process !== "undefined" && !bridgeLoadAttempted) {
5998
+ try {
5999
+ getNativeBridge();
6000
+ } catch {
6001
+ }
6002
+ }
6003
+ }
6004
+ });
5944
6005
 
5945
6006
  // packages/infrastructure/cli/src/commands/program.ts
5946
6007
  init_esm();
@@ -9071,59 +9132,8 @@ var syncCommand = {
9071
9132
  var import_picocolors5 = __toESM(require_picocolors());
9072
9133
  init_errors();
9073
9134
 
9074
- // packages/domain/compiler/src/nativeBridge.ts
9075
- init_src();
9076
- var log3 = (...args) => {
9077
- if (process.env.DEBUG?.includes("compiler:native")) {
9078
- console.log("[compiler:native]", ...args);
9079
- }
9080
- };
9081
- var NATIVE_UNAVAILABLE_MESSAGE = "[tailwind-styled/compiler v5] Native binding is required but not available.\nThis package requires native Rust bindings. There is no JavaScript fallback.\nPlease ensure:\n 1. The native module is properly installed\n 2. You have run: npm run build:rust (or use prebuilt binary)\n\nFor help, see: https://tailwind-styled.dev/docs/install";
9082
- var nativeBridge = null;
9083
- var bridgeLoadAttempted = false;
9084
- var bridgeLoadError = null;
9085
- var isValidNativeBridge = (mod) => {
9086
- const m = mod;
9087
- return !!(typeof m.transformSource === "function" || typeof m.extractAllClasses === "function" || typeof m.hasTwUsage === "function");
9088
- };
9089
- var getNativeBridge = () => {
9090
- if (nativeBridge) {
9091
- return nativeBridge;
9092
- }
9093
- if (bridgeLoadAttempted) {
9094
- if (bridgeLoadError) {
9095
- throw bridgeLoadError;
9096
- }
9097
- throw new Error(NATIVE_UNAVAILABLE_MESSAGE);
9098
- }
9099
- bridgeLoadAttempted = true;
9100
- try {
9101
- const runtimeDir = resolveRuntimeDir(void 0, (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href)));
9102
- const require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href)));
9103
- const result = resolveNativeBinary(runtimeDir);
9104
- if (result.path && result.path.endsWith(".node")) {
9105
- try {
9106
- const binding = require2(result.path);
9107
- if (isValidNativeBridge(binding)) {
9108
- nativeBridge = binding;
9109
- log3("Native bridge loaded successfully from:", result.path);
9110
- return nativeBridge;
9111
- }
9112
- } catch (e) {
9113
- log3("Failed to require native binding:", e);
9114
- }
9115
- }
9116
- throw new Error(`${NATIVE_UNAVAILABLE_MESSAGE}
9117
-
9118
- Tried paths: ${result.tried.join("\n")}`);
9119
- } catch (err) {
9120
- bridgeLoadError = err instanceof Error ? err : new Error(String(err));
9121
- log3("Failed to load native bridge:", bridgeLoadError.message);
9122
- throw bridgeLoadError;
9123
- }
9124
- };
9125
-
9126
9135
  // packages/domain/compiler/src/index.ts
9136
+ init_nativeBridge();
9127
9137
  var compileCssFromClasses = (classes, prefix) => {
9128
9138
  const native = getNativeBridge();
9129
9139
  if (!native?.transformSource) {