tailwind-styled-v4 5.0.8 → 5.0.10

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 (140) hide show
  1. package/CHANGELOG.md +204 -416
  2. package/README.md +45 -15
  3. package/dist/{analyzeWorkspace-DuJKh7Ty.d.mts → analyzeWorkspace-BS5O4rhC.d.mts} +47 -2
  4. package/dist/{analyzeWorkspace-Ct_NTAWt.d.ts → analyzeWorkspace-DDOQdzzI.d.ts} +47 -2
  5. package/dist/analyzer.d.mts +5 -3
  6. package/dist/analyzer.d.ts +5 -3
  7. package/dist/analyzer.js +563 -468
  8. package/dist/analyzer.js.map +1 -1
  9. package/dist/analyzer.mjs +562 -467
  10. package/dist/analyzer.mjs.map +1 -1
  11. package/dist/animate.d.mts +4 -7
  12. package/dist/animate.d.ts +4 -7
  13. package/dist/animate.js +171 -265
  14. package/dist/animate.js.map +1 -1
  15. package/dist/animate.mjs +165 -264
  16. package/dist/animate.mjs.map +1 -1
  17. package/dist/atomic.d.mts +22 -1
  18. package/dist/atomic.d.ts +22 -1
  19. package/dist/atomic.js +221 -165
  20. package/dist/atomic.js.map +1 -1
  21. package/dist/atomic.mjs +200 -165
  22. package/dist/atomic.mjs.map +1 -1
  23. package/dist/cli.d.mts +60 -1
  24. package/dist/cli.d.ts +60 -1
  25. package/dist/cli.js +1261 -1517
  26. package/dist/cli.js.map +1 -1
  27. package/dist/cli.mjs +1238 -1513
  28. package/dist/cli.mjs.map +1 -1
  29. package/dist/compiler.d.mts +38 -7
  30. package/dist/compiler.d.ts +38 -7
  31. package/dist/compiler.js +174 -197
  32. package/dist/compiler.js.map +1 -1
  33. package/dist/compiler.mjs +151 -194
  34. package/dist/compiler.mjs.map +1 -1
  35. package/dist/devtools.js +7 -31
  36. package/dist/devtools.js.map +1 -1
  37. package/dist/devtools.mjs +7 -31
  38. package/dist/devtools.mjs.map +1 -1
  39. package/dist/engine.d.mts +134 -63
  40. package/dist/engine.d.ts +134 -63
  41. package/dist/engine.js +2863 -2482
  42. package/dist/engine.js.map +1 -1
  43. package/dist/engine.mjs +2852 -2485
  44. package/dist/engine.mjs.map +1 -1
  45. package/dist/{index-eWAocnD2.d.mts → index-NDINUhLN.d.mts} +3 -1
  46. package/dist/{index-eWAocnD2.d.ts → index-NDINUhLN.d.ts} +3 -1
  47. package/dist/index.d.mts +63 -32
  48. package/dist/index.d.ts +63 -32
  49. package/dist/index.js +335 -169
  50. package/dist/index.js.map +1 -1
  51. package/dist/index.mjs +315 -169
  52. package/dist/index.mjs.map +1 -1
  53. package/dist/{liveTokenEngine-DSUk88P6.d.ts → liveTokenEngine-CN9ian1R.d.ts} +1 -1
  54. package/dist/{liveTokenEngine-CX5_0c4q.d.mts → liveTokenEngine-DKoWRtqH.d.mts} +1 -1
  55. package/dist/next.d.mts +10 -4
  56. package/dist/next.d.ts +10 -4
  57. package/dist/next.js +32 -45
  58. package/dist/next.js.map +1 -1
  59. package/dist/next.mjs +30 -43
  60. package/dist/next.mjs.map +1 -1
  61. package/dist/plugin-api.d.mts +8 -2
  62. package/dist/plugin-api.d.ts +8 -2
  63. package/dist/plugin-api.js +14 -2
  64. package/dist/plugin-api.js.map +1 -1
  65. package/dist/plugin-api.mjs +14 -3
  66. package/dist/plugin-api.mjs.map +1 -1
  67. package/dist/plugin-registry.js +51 -11
  68. package/dist/plugin-registry.js.map +1 -1
  69. package/dist/plugin-registry.mjs +51 -11
  70. package/dist/plugin-registry.mjs.map +1 -1
  71. package/dist/plugin.d.mts +5 -7
  72. package/dist/plugin.d.ts +5 -7
  73. package/dist/plugin.js +16 -15
  74. package/dist/plugin.js.map +1 -1
  75. package/dist/plugin.mjs +16 -16
  76. package/dist/plugin.mjs.map +1 -1
  77. package/dist/rspack.js +17 -38
  78. package/dist/rspack.js.map +1 -1
  79. package/dist/rspack.mjs +15 -36
  80. package/dist/rspack.mjs.map +1 -1
  81. package/dist/runtime.d.mts +2 -2
  82. package/dist/runtime.d.ts +2 -2
  83. package/dist/scanner.d.mts +10 -1
  84. package/dist/scanner.d.ts +10 -1
  85. package/dist/scanner.js +298 -124
  86. package/dist/scanner.js.map +1 -1
  87. package/dist/scanner.mjs +296 -124
  88. package/dist/scanner.mjs.map +1 -1
  89. package/dist/shared.d.mts +1 -1
  90. package/dist/shared.d.ts +1 -1
  91. package/dist/shared.js +104 -176
  92. package/dist/shared.js.map +1 -1
  93. package/dist/shared.mjs +85 -176
  94. package/dist/shared.mjs.map +1 -1
  95. package/dist/storybook-addon.d.mts +1 -1
  96. package/dist/storybook-addon.d.ts +1 -1
  97. package/dist/svelte.d.mts +1 -1
  98. package/dist/svelte.d.ts +1 -1
  99. package/dist/svelte.js +166 -3
  100. package/dist/svelte.js.map +1 -1
  101. package/dist/svelte.mjs +143 -1
  102. package/dist/svelte.mjs.map +1 -1
  103. package/dist/syntax.js +21 -21
  104. package/dist/syntax.js.map +1 -1
  105. package/dist/syntax.mjs +21 -21
  106. package/dist/syntax.mjs.map +1 -1
  107. package/dist/testing.js +9 -1
  108. package/dist/testing.js.map +1 -1
  109. package/dist/testing.mjs +9 -1
  110. package/dist/testing.mjs.map +1 -1
  111. package/dist/theme.d.mts +2 -2
  112. package/dist/theme.d.ts +2 -2
  113. package/dist/theme.js +40 -112
  114. package/dist/theme.js.map +1 -1
  115. package/dist/theme.mjs +37 -110
  116. package/dist/theme.mjs.map +1 -1
  117. package/dist/turbopackLoader.js +84 -126
  118. package/dist/turbopackLoader.js.map +1 -1
  119. package/dist/turbopackLoader.mjs +68 -124
  120. package/dist/turbopackLoader.mjs.map +1 -1
  121. package/dist/tw.js +1256 -1517
  122. package/dist/tw.js.map +1 -1
  123. package/dist/tw.mjs +1236 -1513
  124. package/dist/tw.mjs.map +1 -1
  125. package/dist/vite.js +1783 -823
  126. package/dist/vite.js.map +1 -1
  127. package/dist/vite.mjs +1767 -821
  128. package/dist/vite.mjs.map +1 -1
  129. package/dist/vue.d.mts +1 -1
  130. package/dist/vue.d.ts +1 -1
  131. package/dist/vue.js +165 -4
  132. package/dist/vue.js.map +1 -1
  133. package/dist/vue.mjs +141 -1
  134. package/dist/vue.mjs.map +1 -1
  135. package/dist/webpackLoader.js +69 -108
  136. package/dist/webpackLoader.js.map +1 -1
  137. package/dist/webpackLoader.mjs +49 -104
  138. package/dist/webpackLoader.mjs.map +1 -1
  139. package/native/tailwind-styled-native.node +0 -0
  140. package/package.json +22 -24
package/dist/tw.js CHANGED
@@ -1,13 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- var path3 = require('path');
5
- var url = require('url');
6
- var zod = require('zod');
7
- var fs8 = require('fs');
8
4
  var module$1 = require('module');
5
+ var fs11 = require('fs');
6
+ var path6 = require('path');
7
+ require('crypto');
8
+ var url = require('url');
9
9
  var worker_threads = require('worker_threads');
10
- var fs4 = require('fs/promises');
10
+ var os = require('os');
11
+ var zod = require('zod');
12
+ var fs7 = require('fs/promises');
11
13
  var prompts = require('@clack/prompts');
12
14
  var util = require('util');
13
15
  var child_process = require('child_process');
@@ -15,9 +17,27 @@ var child_process = require('child_process');
15
17
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
16
18
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
17
19
 
18
- var path3__default = /*#__PURE__*/_interopDefault(path3);
19
- var fs8__default = /*#__PURE__*/_interopDefault(fs8);
20
- var fs4__default = /*#__PURE__*/_interopDefault(fs4);
20
+ function _interopNamespace(e) {
21
+ if (e && e.__esModule) return e;
22
+ var n = Object.create(null);
23
+ if (e) {
24
+ Object.keys(e).forEach(function (k) {
25
+ if (k !== 'default') {
26
+ var d = Object.getOwnPropertyDescriptor(e, k);
27
+ Object.defineProperty(n, k, d.get ? d : {
28
+ enumerable: true,
29
+ get: function () { return e[k]; }
30
+ });
31
+ }
32
+ });
33
+ }
34
+ n.default = e;
35
+ return Object.freeze(n);
36
+ }
37
+
38
+ var fs11__namespace = /*#__PURE__*/_interopNamespace(fs11);
39
+ var path6__namespace = /*#__PURE__*/_interopNamespace(path6);
40
+ var fs7__default = /*#__PURE__*/_interopDefault(fs7);
21
41
 
22
42
  /* tailwind-styled-v4 v5.0.4 | MIT | https://github.com/dictionar32/tailwind-styled-v4 */
23
43
  var __create = Object.create;
@@ -993,8 +1013,8 @@ var require_command = __commonJS({
993
1013
  "packages/infrastructure/cli/node_modules/commander/lib/command.js"(exports$1) {
994
1014
  var EventEmitter = __require("events").EventEmitter;
995
1015
  var childProcess = __require("child_process");
996
- var path26 = __require("path");
997
- var fs12 = __require("fs");
1016
+ var path29 = __require("path");
1017
+ var fs15 = __require("fs");
998
1018
  var process2 = __require("process");
999
1019
  var { Argument: Argument2, humanReadableArgName } = require_argument();
1000
1020
  var { CommanderError: CommanderError2 } = require_error();
@@ -1925,11 +1945,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
1925
1945
  let launchWithNode = false;
1926
1946
  const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1927
1947
  function findFile(baseDir, baseName) {
1928
- const localBin = path26.resolve(baseDir, baseName);
1929
- if (fs12.existsSync(localBin)) return localBin;
1930
- if (sourceExt.includes(path26.extname(baseName))) return void 0;
1948
+ const localBin = path29.resolve(baseDir, baseName);
1949
+ if (fs15.existsSync(localBin)) return localBin;
1950
+ if (sourceExt.includes(path29.extname(baseName))) return void 0;
1931
1951
  const foundExt = sourceExt.find(
1932
- (ext) => fs12.existsSync(`${localBin}${ext}`)
1952
+ (ext) => fs15.existsSync(`${localBin}${ext}`)
1933
1953
  );
1934
1954
  if (foundExt) return `${localBin}${foundExt}`;
1935
1955
  return void 0;
@@ -1941,21 +1961,21 @@ Expecting one of '${allowedValues.join("', '")}'`);
1941
1961
  if (this._scriptPath) {
1942
1962
  let resolvedScriptPath;
1943
1963
  try {
1944
- resolvedScriptPath = fs12.realpathSync(this._scriptPath);
1964
+ resolvedScriptPath = fs15.realpathSync(this._scriptPath);
1945
1965
  } catch (err) {
1946
1966
  resolvedScriptPath = this._scriptPath;
1947
1967
  }
1948
- executableDir = path26.resolve(
1949
- path26.dirname(resolvedScriptPath),
1968
+ executableDir = path29.resolve(
1969
+ path29.dirname(resolvedScriptPath),
1950
1970
  executableDir
1951
1971
  );
1952
1972
  }
1953
1973
  if (executableDir) {
1954
1974
  let localFile = findFile(executableDir, executableFile);
1955
1975
  if (!localFile && !subcommand._executableFile && this._scriptPath) {
1956
- const legacyName = path26.basename(
1976
+ const legacyName = path29.basename(
1957
1977
  this._scriptPath,
1958
- path26.extname(this._scriptPath)
1978
+ path29.extname(this._scriptPath)
1959
1979
  );
1960
1980
  if (legacyName !== this._name) {
1961
1981
  localFile = findFile(
@@ -1966,7 +1986,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
1966
1986
  }
1967
1987
  executableFile = localFile || executableFile;
1968
1988
  }
1969
- launchWithNode = sourceExt.includes(path26.extname(executableFile));
1989
+ launchWithNode = sourceExt.includes(path29.extname(executableFile));
1970
1990
  let proc;
1971
1991
  if (process2.platform !== "win32") {
1972
1992
  if (launchWithNode) {
@@ -2806,7 +2826,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2806
2826
  * @return {Command}
2807
2827
  */
2808
2828
  nameFromFilename(filename) {
2809
- this._name = path26.basename(filename, path26.extname(filename));
2829
+ this._name = path29.basename(filename, path29.extname(filename));
2810
2830
  return this;
2811
2831
  }
2812
2832
  /**
@@ -2820,9 +2840,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
2820
2840
  * @param {string} [path]
2821
2841
  * @return {(string|null|Command)}
2822
2842
  */
2823
- executableDir(path27) {
2824
- if (path27 === void 0) return this._executableDir;
2825
- this._executableDir = path27;
2843
+ executableDir(path30) {
2844
+ if (path30 === void 0) return this._executableDir;
2845
+ this._executableDir = path30;
2826
2846
  return this;
2827
2847
  }
2828
2848
  /**
@@ -3162,45 +3182,6 @@ var init_esmHelpers = __esm({
3162
3182
  _nodeUrl = null;
3163
3183
  }
3164
3184
  });
3165
-
3166
- // packages/domain/shared/src/native-resolution.ts
3167
- function getNodeModuleRef2() {
3168
- if (isBrowser2) return null;
3169
- if (nodeModuleRef2 !== null) return nodeModuleRef2;
3170
- try {
3171
- const test = typeof __require === "function" ? __require("module") : null;
3172
- nodeModuleRef2 = test;
3173
- return test;
3174
- } catch {
3175
- nodeModuleRef2 = null;
3176
- return null;
3177
- }
3178
- }
3179
- function getNodeFs() {
3180
- if (isBrowser2) return { existsSync: () => false };
3181
- const nodeRequire = getNodeModuleRef2();
3182
- if (!nodeRequire) return { existsSync: () => false };
3183
- if (!_nodeFs) _nodeFs = nodeRequire.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href)))("node:fs");
3184
- return _nodeFs;
3185
- }
3186
- function getNodePath2() {
3187
- if (isBrowser2) return { resolve: () => "", dirname: "" };
3188
- const nodeRequire = getNodeModuleRef2();
3189
- if (!nodeRequire) return { resolve: () => "", dirname: "" };
3190
- if (!_nodePath2) _nodePath2 = nodeRequire.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href)))("node:path");
3191
- return _nodePath2;
3192
- }
3193
- function getRequire(_importMetaUrl) {
3194
- if (isBrowser2) return () => {
3195
- throw new Error("node:module not available");
3196
- };
3197
- const nodeRequire = getNodeModuleRef2();
3198
- if (!nodeRequire) return () => {
3199
- throw new Error("require not available");
3200
- };
3201
- if (!_require) _require = nodeRequire.createRequire(_importMetaUrl);
3202
- return _require;
3203
- }
3204
3185
  function platformKey() {
3205
3186
  if (isBrowser2) return "browser";
3206
3187
  return `${process.platform}-${process.arch}`;
@@ -3211,24 +3192,21 @@ function resolveNativeBinary(runtimeDir) {
3211
3192
  if (isBrowser2) {
3212
3193
  return { path: null, source: "not-found", platform, tried: ["not available in browser"] };
3213
3194
  }
3214
- const fs12 = getNodeFs();
3215
- const path26 = getNodePath2();
3216
- const _req = getRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href)));
3195
+ if (process.env.TWS_DISABLE_NATIVE === "1") {
3196
+ return { path: null, source: "not-found", platform, tried: [] };
3197
+ }
3217
3198
  const envPath = process.env.TW_NATIVE_PATH?.trim();
3218
3199
  if (envPath) {
3219
- if (fs12.existsSync(envPath)) {
3200
+ if (fs11__namespace.existsSync(envPath)) {
3220
3201
  return { path: envPath, source: "env", platform, tried };
3221
3202
  }
3222
3203
  tried.push(`env:${envPath} (not found)`);
3223
3204
  }
3224
- if (process.env.TWS_NO_NATIVE === "1" || process.env.TWS_NO_RUST === "1" || process.env.TWS_DISABLE_NATIVE === "1") {
3225
- return { path: null, source: "not-found", platform, tried: ["disabled by env"] };
3226
- }
3227
3205
  const prebuiltPkgs = PLATFORM_MAP[platform] ?? [];
3228
3206
  for (const pkg of prebuiltPkgs) {
3229
3207
  try {
3230
- const candidate = _req.resolve(`${pkg}/tailwind_styled_parser.node`);
3231
- if (fs12.existsSync(candidate)) {
3208
+ const candidate = _require.resolve(`${pkg}/tailwind_styled_parser.node`);
3209
+ if (fs11__namespace.existsSync(candidate)) {
3232
3210
  return { path: candidate, source: "prebuilt", platform, tried };
3233
3211
  }
3234
3212
  tried.push(`prebuilt:${pkg} (resolved but missing)`);
@@ -3238,30 +3216,43 @@ function resolveNativeBinary(runtimeDir) {
3238
3216
  }
3239
3217
  const cwd2 = process.cwd();
3240
3218
  const base = runtimeDir ?? cwd2;
3241
- const localCandidates = [
3242
- path26.resolve(base, "tailwind_styled_parser.node"),
3243
- path26.resolve(base, "..", "tailwind_styled_parser.node"),
3244
- path26.resolve(cwd2, "native", "tailwind_styled_parser.node"),
3245
- path26.resolve(cwd2, "native", "target", "release", "tailwind_styled_parser.node"),
3246
- // napi-rs conventional output
3247
- path26.resolve(base, `tailwind_styled_parser.${platform}.node`)
3248
- ];
3219
+ const napiPlatform = platform === "linux-x64" ? "linux-x64-gnu" : platform === "linux-arm64" ? "linux-arm64-gnu" : platform;
3220
+ const BINARY_NAMES = ["tailwind-styled-native", "tailwind_styled_parser"];
3221
+ const localCandidates = [];
3222
+ for (const bin of BINARY_NAMES) {
3223
+ localCandidates.push(path6__namespace.resolve(base, `${bin}.node`));
3224
+ localCandidates.push(path6__namespace.resolve(base, "..", `${bin}.node`));
3225
+ localCandidates.push(path6__namespace.resolve(base, `${bin}.${platform}.node`));
3226
+ localCandidates.push(path6__namespace.resolve(base, `${bin}.${napiPlatform}.node`));
3227
+ }
3228
+ for (const startDir of [cwd2, base]) {
3229
+ let dir = startDir;
3230
+ for (let i = 0; i < 6; i++) {
3231
+ const nativeDir = path6__namespace.resolve(dir, "native");
3232
+ for (const bin of BINARY_NAMES) {
3233
+ localCandidates.push(path6__namespace.resolve(nativeDir, `${bin}.node`));
3234
+ localCandidates.push(path6__namespace.resolve(nativeDir, `${bin}.${platform}.node`));
3235
+ localCandidates.push(path6__namespace.resolve(nativeDir, `${bin}.${napiPlatform}.node`));
3236
+ localCandidates.push(path6__namespace.resolve(nativeDir, "target", "release", `${bin}.node`));
3237
+ }
3238
+ const parent = path6__namespace.resolve(dir, "..");
3239
+ if (parent === dir) break;
3240
+ dir = parent;
3241
+ }
3242
+ }
3249
3243
  for (const candidate of localCandidates) {
3250
3244
  tried.push(`local:${candidate}`);
3251
- if (fs12.existsSync(candidate)) {
3245
+ if (fs11__namespace.existsSync(candidate)) {
3252
3246
  return { path: candidate, source: "local", platform, tried };
3253
3247
  }
3254
3248
  }
3255
3249
  return { path: null, source: "not-found", platform, tried };
3256
3250
  }
3257
- var isBrowser2, nodeModuleRef2, _nodeFs, _nodePath2, _require, PLATFORM_MAP;
3251
+ var isBrowser2, _require, PLATFORM_MAP;
3258
3252
  var init_native_resolution = __esm({
3259
3253
  "packages/domain/shared/src/native-resolution.ts"() {
3260
3254
  isBrowser2 = typeof window !== "undefined" || typeof document !== "undefined";
3261
- nodeModuleRef2 = null;
3262
- _nodeFs = null;
3263
- _nodePath2 = null;
3264
- _require = null;
3255
+ _require = typeof __require !== "undefined" ? __require : 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)));
3265
3256
  PLATFORM_MAP = {
3266
3257
  "linux-x64": ["@tailwind-styled/native-linux-x64"],
3267
3258
  "linux-arm64": ["@tailwind-styled/native-linux-arm64"],
@@ -3272,41 +3263,6 @@ var init_native_resolution = __esm({
3272
3263
  };
3273
3264
  }
3274
3265
  });
3275
-
3276
- // packages/domain/shared/src/index.ts
3277
- function getNodeModuleRef3() {
3278
- if (isBrowser3) return null;
3279
- if (nodeModuleRef3 !== null) return nodeModuleRef3;
3280
- try {
3281
- const test = typeof __require === "function" ? __require("module") : null;
3282
- nodeModuleRef3 = test;
3283
- return test;
3284
- } catch {
3285
- nodeModuleRef3 = null;
3286
- return null;
3287
- }
3288
- }
3289
- function getNodeFs2() {
3290
- if (isBrowser3) throw new Error("node:fs not available in browser");
3291
- const nodeRequire = getNodeModuleRef3();
3292
- if (!nodeRequire) throw new Error("require not available");
3293
- if (!_nodeFs2) _nodeFs2 = nodeRequire.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href)))("node:fs");
3294
- return _nodeFs2;
3295
- }
3296
- function getNodePath3() {
3297
- if (isBrowser3) throw new Error("node:path not available in browser");
3298
- const nodeRequire = getNodeModuleRef3();
3299
- if (!nodeRequire) throw new Error("require not available");
3300
- if (!_nodePath3) _nodePath3 = nodeRequire.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href)))("node:path");
3301
- return _nodePath3;
3302
- }
3303
- function getNodeUrl2() {
3304
- if (isBrowser3) throw new Error("node:url not available in browser");
3305
- const nodeRequire = getNodeModuleRef3();
3306
- if (!nodeRequire) throw new Error("require not available");
3307
- if (!_nodeUrl2) _nodeUrl2 = nodeRequire.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href)))("node:url");
3308
- return _nodeUrl2;
3309
- }
3310
3266
  function createLogger(namespace) {
3311
3267
  const prefix = `[${namespace}]`;
3312
3268
  return {
@@ -3336,9 +3292,9 @@ function createDebugLogger(namespace, label) {
3336
3292
  }
3337
3293
  };
3338
3294
  }
3339
- function formatIssuePath(path26) {
3340
- if (!path26 || path26.length === 0) return "(root)";
3341
- return path26.map(
3295
+ function formatIssuePath(path29) {
3296
+ if (!path29 || path29.length === 0) return "(root)";
3297
+ return path29.map(
3342
3298
  (segment) => typeof segment === "symbol" ? segment.description ?? segment.toString() : String(segment)
3343
3299
  ).join(".");
3344
3300
  }
@@ -3346,17 +3302,12 @@ function wrapUnknownError(domain, code, error) {
3346
3302
  return TwError.wrap(domain, code, error);
3347
3303
  }
3348
3304
  function loadNativeBinding(options) {
3349
- if (isBrowser3) {
3350
- return { binding: null, loadErrors: [{ path: "", message: "Native bindings not available in browser" }] };
3351
- }
3352
3305
  const { runtimeDir, candidates, isValid } = options;
3353
3306
  const loadErrors = [];
3354
- const path26 = getNodePath3();
3355
- const fs12 = getNodeFs2();
3356
3307
  for (const candidate of candidates) {
3357
- const candidatePath = path26.resolve(runtimeDir, candidate);
3308
+ const candidatePath = path6__namespace.default.resolve(runtimeDir, candidate);
3358
3309
  try {
3359
- if (!fs12.existsSync(candidatePath) && !fs12.existsSync(candidatePath + ".node")) {
3310
+ if (!fs11__namespace.default.existsSync(candidatePath) && !fs11__namespace.default.existsSync(candidatePath + ".node")) {
3360
3311
  continue;
3361
3312
  }
3362
3313
  const mod = requireNativeModule(candidatePath);
@@ -3370,74 +3321,58 @@ function loadNativeBinding(options) {
3370
3321
  }
3371
3322
  return { binding: null, loadErrors };
3372
3323
  }
3373
- function getRequire2() {
3374
- if (isBrowser3) return (() => {
3375
- throw new Error("require not available in browser");
3376
- });
3377
- const nodeRequire = getNodeModuleRef3();
3378
- if (!nodeRequire) return (() => {
3379
- throw new Error("require not available");
3380
- });
3381
- return nodeRequire.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href)));
3382
- }
3383
- function requireNativeModule(path26) {
3384
- return _require2(path26);
3324
+ function requireNativeModule(p) {
3325
+ return _require2(p);
3385
3326
  }
3386
3327
  function resolveNativeBindingCandidates(options) {
3387
- if (isBrowser3) return [];
3388
- const { runtimeDir, envVarNames = [], includeDefaultCandidates = true, enforceNodeExtensionForEnvPath = false } = options;
3328
+ const {
3329
+ envVarNames = ["TW_NATIVE_PATH", "TWS_NATIVE_PATH"],
3330
+ includeDefaultCandidates = true,
3331
+ enforceNodeExtensionForEnvPath = false
3332
+ } = options;
3333
+ const runtimeDir = options.runtimeDir || process.cwd();
3389
3334
  const candidates = [];
3390
- const path26 = getNodePath3();
3391
- const fs12 = getNodeFs2();
3392
3335
  for (const envVar of envVarNames) {
3393
3336
  const envPath = process.env[envVar];
3394
3337
  if (envPath) {
3395
- if (enforceNodeExtensionForEnvPath && !envPath.endsWith(".node")) {
3396
- candidates.push(envPath + ".node");
3397
- } else {
3398
- candidates.push(envPath);
3399
- }
3338
+ candidates.push(enforceNodeExtensionForEnvPath && !envPath.endsWith(".node") ? envPath + ".node" : envPath);
3400
3339
  }
3401
3340
  }
3402
3341
  if (!includeDefaultCandidates) return candidates;
3403
- if (fs12.existsSync(runtimeDir)) {
3342
+ if (fs11__namespace.default.existsSync(runtimeDir)) {
3404
3343
  try {
3405
- const entries = fs12.readdirSync(runtimeDir);
3406
- for (const entry of entries) {
3407
- if (entry.endsWith(".node")) {
3408
- candidates.push(entry);
3409
- }
3344
+ for (const entry of fs11__namespace.default.readdirSync(runtimeDir)) {
3345
+ if (entry.endsWith(".node")) candidates.push(entry);
3410
3346
  }
3411
3347
  } catch {
3412
3348
  }
3413
3349
  }
3414
- const platform = typeof process !== "undefined" ? process.platform : "";
3415
- const ext = platform === "win32" ? ".dll" : platform === "darwin" ? ".dylib" : ".so";
3416
- const defaultBindingName = `tailwind_styled_parser${ext}`;
3417
- candidates.push(path26.resolve(runtimeDir, "..", "..", "..", "native", defaultBindingName));
3418
- candidates.push(path26.resolve(runtimeDir, "..", "..", "..", "..", "native", defaultBindingName));
3419
- candidates.push(path26.resolve(process.cwd(), "native", defaultBindingName));
3350
+ const BINARY_NAMES = ["tailwind-styled-native", "tailwind_styled_parser"];
3351
+ const napiPlatform = process.platform === "linux" && process.arch === "x64" ? "linux-x64-gnu" : process.platform === "linux" && process.arch === "arm64" ? "linux-arm64-gnu" : `${process.platform}-${process.arch}`;
3352
+ for (const bin of BINARY_NAMES) {
3353
+ candidates.push(path6__namespace.default.resolve(runtimeDir, `${bin}.node`));
3354
+ candidates.push(path6__namespace.default.resolve(runtimeDir, `${bin}.${napiPlatform}.node`));
3355
+ candidates.push(path6__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", `${bin}.node`));
3356
+ candidates.push(path6__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", `${bin}.${napiPlatform}.node`));
3357
+ candidates.push(path6__namespace.default.resolve(runtimeDir, "..", "..", "..", "native", `${bin}.node`));
3358
+ candidates.push(path6__namespace.default.resolve(process.cwd(), "native", `${bin}.node`));
3359
+ candidates.push(path6__namespace.default.resolve(process.cwd(), "native", `${bin}.${napiPlatform}.node`));
3360
+ }
3420
3361
  return Array.from(new Set(candidates));
3421
3362
  }
3422
3363
  function resolveRuntimeDir(dir, importMetaUrl) {
3423
- if (isBrowser3) return "";
3424
- if (dir) return getNodePath3().resolve(dir);
3364
+ if (dir) return path6__namespace.default.resolve(dir);
3425
3365
  try {
3426
- return getNodeUrl2().fileURLToPath(importMetaUrl);
3366
+ return path6__namespace.default.dirname(url.fileURLToPath(importMetaUrl));
3427
3367
  } catch {
3428
3368
  return process.cwd();
3429
3369
  }
3430
3370
  }
3431
- var isBrowser3, nodeModuleRef3, _nodeFs2, _nodePath3, _nodeUrl2, TwError, _require2;
3371
+ var TwError, _require2;
3432
3372
  var init_src = __esm({
3433
3373
  "packages/domain/shared/src/index.ts"() {
3434
3374
  init_esmHelpers();
3435
3375
  init_native_resolution();
3436
- isBrowser3 = typeof window !== "undefined" || typeof document !== "undefined";
3437
- nodeModuleRef3 = null;
3438
- _nodeFs2 = null;
3439
- _nodePath3 = null;
3440
- _nodeUrl2 = null;
3441
3376
  TwError = class _TwError extends Error {
3442
3377
  /** @deprecated Gunakan source */
3443
3378
  domain;
@@ -3471,8 +3406,8 @@ var init_src = __esm({
3471
3406
  /** Buat TwError dari ZodError — dukung shape Zod v3 (`errors`) dan v4 (`issues`). */
3472
3407
  static fromZod(err) {
3473
3408
  const first = err.issues?.[0] ?? err.errors?.[0];
3474
- const path26 = formatIssuePath(first?.path);
3475
- const message = first ? `${path26}: ${first.message}` : "Schema validation failed";
3409
+ const path29 = formatIssuePath(first?.path);
3410
+ const message = first ? `${path29}: ${first.message}` : "Schema validation failed";
3476
3411
  return new _TwError("validation", "SCHEMA_VALIDATION_FAILED", message, err);
3477
3412
  }
3478
3413
  static wrap(source, code, err) {
@@ -3490,21 +3425,33 @@ var init_src = __esm({
3490
3425
  return `[${this.source.toUpperCase()}:${this.code}] ${this.message}`;
3491
3426
  }
3492
3427
  };
3493
- _require2 = getRequire2();
3428
+ _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)));
3494
3429
  }
3495
3430
  });
3496
3431
 
3497
3432
  // packages/domain/scanner/src/native-bridge.ts
3498
3433
  var native_bridge_exports = {};
3499
3434
  __export(native_bridge_exports, {
3435
+ batchExtractClassesNative: () => batchExtractClassesNative,
3500
3436
  cachePriorityNative: () => cachePriorityNative,
3501
3437
  cacheReadNative: () => cacheReadNative,
3502
3438
  cacheWriteNative: () => cacheWriteNative,
3439
+ collectFilesNative: () => collectFilesNative,
3440
+ computeCacheStatsNative: () => computeCacheStatsNative,
3503
3441
  extractClassesNative: () => extractClassesNative,
3442
+ generateSubComponentTypesNative: () => generateSubComponentTypesNative,
3504
3443
  hasNativeScannerBinding: () => hasNativeScannerBinding,
3505
3444
  hashContentNative: () => hashContentNative,
3506
3445
  isRustCacheAvailable: () => isRustCacheAvailable,
3446
+ pruneStaleEntriesNative: () => pruneStaleEntriesNative,
3447
+ rebuildWorkspaceResultNative: () => rebuildWorkspaceResultNative,
3507
3448
  resetScannerBridgeCache: () => resetScannerBridgeCache,
3449
+ scanCacheGet: () => scanCacheGet,
3450
+ scanCacheInvalidate: () => scanCacheInvalidate,
3451
+ scanCachePut: () => scanCachePut,
3452
+ scanCacheStats: () => scanCacheStats,
3453
+ scanFileNative: () => scanFileNative,
3454
+ scanFilesBatchNative: () => scanFilesBatchNative,
3508
3455
  scanWorkspaceNative: () => scanWorkspaceNative
3509
3456
  });
3510
3457
  function getDirname2() {
@@ -3512,7 +3459,7 @@ function getDirname2() {
3512
3459
  return __dirname;
3513
3460
  }
3514
3461
  if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href)) }) !== "undefined" && (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href))) {
3515
- return path3__default.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href))));
3462
+ return path6__namespace.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href))));
3516
3463
  }
3517
3464
  return process.cwd();
3518
3465
  }
@@ -3593,6 +3540,95 @@ function cachePriorityNative(mtimeMs, size, cachedMtimeMs, cachedSize, cachedHit
3593
3540
  }
3594
3541
  return result;
3595
3542
  }
3543
+ function batchExtractClassesNative(filePaths) {
3544
+ const binding = scannerGetBinding();
3545
+ if (!binding.batchExtractClasses) {
3546
+ throw new Error("FATAL: Native binding 'batchExtractClasses' is required but not available.");
3547
+ }
3548
+ return binding.batchExtractClasses(filePaths) ?? [];
3549
+ }
3550
+ function scanCacheGet(filePath, contentHash) {
3551
+ const binding = scannerGetBinding();
3552
+ if (!binding.scanCacheGet) {
3553
+ throw new Error("FATAL: Native binding 'scanCacheGet' is required but not available.");
3554
+ }
3555
+ return binding.scanCacheGet(filePath, contentHash) ?? null;
3556
+ }
3557
+ function scanCachePut(filePath, contentHash, classes, mtimeMs, size) {
3558
+ const binding = scannerGetBinding();
3559
+ if (!binding.scanCachePut) {
3560
+ throw new Error("FATAL: Native binding 'scanCachePut' is required but not available.");
3561
+ }
3562
+ binding.scanCachePut(filePath, contentHash, classes, mtimeMs, size);
3563
+ }
3564
+ function scanCacheInvalidate(filePath) {
3565
+ const binding = scannerGetBinding();
3566
+ if (!binding.scanCacheInvalidate) {
3567
+ throw new Error("FATAL: Native binding 'scanCacheInvalidate' is required but not available.");
3568
+ }
3569
+ binding.scanCacheInvalidate(filePath);
3570
+ }
3571
+ function scanCacheStats() {
3572
+ const binding = scannerGetBinding();
3573
+ if (!binding.scanCacheStats) {
3574
+ throw new Error("FATAL: Native binding 'scanCacheStats' is required but not available.");
3575
+ }
3576
+ return binding.scanCacheStats();
3577
+ }
3578
+ function scanFileNative(filePath) {
3579
+ const binding = scannerGetBinding();
3580
+ if (!binding.scanFile) {
3581
+ throw new Error("FATAL: Native binding 'scanFile' is required but not available.");
3582
+ }
3583
+ return binding.scanFile(filePath);
3584
+ }
3585
+ function collectFilesNative(root, extensions, ignoreDirs) {
3586
+ const binding = scannerGetBinding();
3587
+ if (!binding.collectFiles) return null;
3588
+ return binding.collectFiles(root, extensions, ignoreDirs);
3589
+ }
3590
+ function scanFilesBatchNative(filePaths) {
3591
+ const binding = scannerGetBinding();
3592
+ if (!binding.scanFilesBatch) {
3593
+ return filePaths.map((fp) => {
3594
+ try {
3595
+ const r = binding.scanFile?.(fp);
3596
+ return r ? { file: r.file, classes: r.classes, hash: r.hash ?? "" } : { file: fp, classes: [], hash: "" };
3597
+ } catch {
3598
+ return { file: fp, classes: [], hash: "" };
3599
+ }
3600
+ });
3601
+ }
3602
+ return binding.scanFilesBatch(filePaths);
3603
+ }
3604
+ function generateSubComponentTypesNative(root, outputPath) {
3605
+ const binding = scannerGetBinding();
3606
+ if (!binding.generateSubComponentTypes) return null;
3607
+ return binding.generateSubComponentTypes(root, outputPath ?? null);
3608
+ }
3609
+ function pruneStaleEntriesNative(entries, maxAgeMs, checkExists) {
3610
+ const binding = scannerGetBinding();
3611
+ if (!binding.pruneStaleEntries) return null;
3612
+ return binding.pruneStaleEntries(
3613
+ entries.map((e) => ({ file: e.file, lastSeenMs: e.lastSeenMs ?? 0 })),
3614
+ maxAgeMs ?? null,
3615
+ checkExists ?? null
3616
+ );
3617
+ }
3618
+ function rebuildWorkspaceResultNative(files) {
3619
+ const binding = scannerBridgeLoader.get();
3620
+ if (!binding?.rebuildWorkspaceResult) return null;
3621
+ try {
3622
+ return binding.rebuildWorkspaceResult(files);
3623
+ } catch {
3624
+ return null;
3625
+ }
3626
+ }
3627
+ function computeCacheStatsNative(filesClasses, sizes, top) {
3628
+ const binding = scannerGetBinding();
3629
+ if (!binding.computeCacheStats) return null;
3630
+ return binding.computeCacheStats(filesClasses, sizes, top ?? null);
3631
+ }
3596
3632
  var log, isValidScannerBinding, createScannerBridgeLoader, scannerBridgeLoader, scannerGetBinding, resetScannerBridgeCache;
3597
3633
  var init_native_bridge = __esm({
3598
3634
  "packages/domain/scanner/src/native-bridge.ts"() {
@@ -3677,8 +3713,8 @@ var init_native_bridge = __esm({
3677
3713
  }
3678
3714
  });
3679
3715
  function defaultCachePath(rootDir, cacheDir) {
3680
- const dir = cacheDir ? path3__default.default.resolve(rootDir, cacheDir) : path3__default.default.join(process.cwd(), ".cache", "tailwind-styled");
3681
- return path3__default.default.join(dir, "scanner-cache.json");
3716
+ const dir = cacheDir ? path6__namespace.default.resolve(rootDir, cacheDir) : path6__namespace.default.join(process.cwd(), ".cache", "tailwind-styled");
3717
+ return path6__namespace.default.join(dir, "scanner-cache.json");
3682
3718
  }
3683
3719
  function readCache(rootDir, cacheDir) {
3684
3720
  const cachePath = defaultCachePath(rootDir, cacheDir);
@@ -3719,16 +3755,117 @@ var init_cache_native = __esm({
3719
3755
  init_native_bridge();
3720
3756
  }
3721
3757
  });
3758
+ function collectFiles(rootDir, extensions, ignoreDirs) {
3759
+ const native = collectFilesNative(rootDir, extensions, ignoreDirs);
3760
+ if (native !== null) return native;
3761
+ const files = [];
3762
+ function walk(dir) {
3763
+ let entries;
3764
+ try {
3765
+ entries = fs11__namespace.default.readdirSync(dir, { withFileTypes: true });
3766
+ } catch {
3767
+ return;
3768
+ }
3769
+ for (const entry of entries) {
3770
+ const fullPath = path6__namespace.default.join(dir, entry.name);
3771
+ const rel = path6__namespace.default.relative(rootDir, fullPath);
3772
+ if (entry.isDirectory()) {
3773
+ const ignored = ignoreDirs.some((d) => entry.name === d || rel.startsWith(d + path6__namespace.default.sep));
3774
+ if (!ignored) walk(fullPath);
3775
+ } else if (isScannableFile(entry.name, extensions)) {
3776
+ files.push(fullPath);
3777
+ }
3778
+ }
3779
+ }
3780
+ walk(rootDir);
3781
+ return files;
3782
+ }
3783
+ function mergeResults(batchResults) {
3784
+ const files = batchResults.map((r) => ({
3785
+ file: r.file,
3786
+ classes: r.classes,
3787
+ hash: r.content_hash
3788
+ }));
3789
+ const native = rebuildWorkspaceResultNative(files);
3790
+ if (native) return native;
3791
+ const unique = new Set(files.flatMap((f) => f.classes));
3792
+ return { files, totalFiles: files.length, uniqueClasses: Array.from(unique).sort() };
3793
+ }
3794
+ function runChunkInWorker(filePaths) {
3795
+ return new Promise((resolve2, reject) => {
3796
+ const worker = new worker_threads.Worker(_workerFilename, {
3797
+ workerData: { filePaths }
3798
+ });
3799
+ worker.once("message", (payload) => {
3800
+ if (payload.ok) {
3801
+ resolve2(payload.results);
3802
+ } else {
3803
+ reject(new Error(payload.error ?? "parallel-scanner worker failed"));
3804
+ }
3805
+ });
3806
+ worker.once("error", reject);
3807
+ worker.once("exit", (code) => {
3808
+ if (code !== 0) reject(new Error(`parallel-scanner worker exited with code ${code}`));
3809
+ });
3810
+ });
3811
+ }
3812
+ async function scanWorkspaceParallel(rootDir, options = {}) {
3813
+ const {
3814
+ extensions = DEFAULT_EXTENSIONS,
3815
+ ignoreDirs = DEFAULT_IGNORES,
3816
+ maxWorkers = Math.max(1, os.availableParallelism() - 1),
3817
+ chunkSize = DEFAULT_CHUNK_SIZE
3818
+ } = options;
3819
+ const files = collectFiles(path6__namespace.default.resolve(rootDir), extensions, ignoreDirs);
3820
+ if (files.length < PARALLEL_THRESHOLD) {
3821
+ return mergeResults(batchExtractClassesNative(files));
3822
+ }
3823
+ const chunks = [];
3824
+ for (let i = 0; i < files.length; i += chunkSize) {
3825
+ chunks.push(files.slice(i, i + chunkSize));
3826
+ }
3827
+ const allResults = [];
3828
+ for (let i = 0; i < chunks.length; i += maxWorkers) {
3829
+ const batch = chunks.slice(i, i + maxWorkers);
3830
+ const batchResults = await Promise.all(batch.map(runChunkInWorker));
3831
+ allResults.push(...batchResults.flat());
3832
+ }
3833
+ return mergeResults(allResults);
3834
+ }
3835
+ var PARALLEL_THRESHOLD, DEFAULT_CHUNK_SIZE, _workerFilename;
3836
+ var init_parallel_scanner = __esm({
3837
+ "packages/domain/scanner/src/parallel-scanner.ts"() {
3838
+ init_src2();
3839
+ init_native_bridge();
3840
+ PARALLEL_THRESHOLD = 50;
3841
+ DEFAULT_CHUNK_SIZE = 150;
3842
+ if (!worker_threads.isMainThread && worker_threads.parentPort) {
3843
+ const { filePaths } = worker_threads.workerData;
3844
+ try {
3845
+ const results = batchExtractClassesNative(filePaths);
3846
+ const msg = { ok: true, results };
3847
+ worker_threads.parentPort.postMessage(msg);
3848
+ } catch (error) {
3849
+ const msg = {
3850
+ ok: false,
3851
+ error: error instanceof Error ? error.message : String(error)
3852
+ };
3853
+ worker_threads.parentPort.postMessage(msg);
3854
+ }
3855
+ }
3856
+ _workerFilename = typeof __filename !== "undefined" ? __filename : url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href)));
3857
+ }
3858
+ });
3722
3859
  var formatIssuePath2, formatIssues, parseWithSchema, NonNegativeIntegerSchema, ScanWorkspaceOptionsSchema, ScanFileResultSchema, ScanWorkspaceResultSchema, ScannerWorkerSuccessMessageSchema, ScannerWorkerErrorMessageSchema, ScannerWorkerMessageSchema, parseScanWorkspaceOptions, parseScanWorkspaceResult, parseScannerWorkerMessage;
3723
3860
  var init_schemas = __esm({
3724
3861
  "packages/domain/scanner/src/schemas.ts"() {
3725
3862
  init_src();
3726
- formatIssuePath2 = (path26) => path26.length > 0 ? path26.map(
3863
+ formatIssuePath2 = (path29) => path29.length > 0 ? path29.map(
3727
3864
  (segment) => typeof segment === "symbol" ? segment.description ?? segment.toString() : String(segment)
3728
3865
  ).join(".") : "<root>";
3729
3866
  formatIssues = (error) => error.issues.map((issue) => {
3730
- const path26 = formatIssuePath2(issue.path);
3731
- return `${path26}: ${issue.message}`;
3867
+ const path29 = formatIssuePath2(issue.path);
3868
+ return `${path29}: ${issue.message}`;
3732
3869
  }).join("; ");
3733
3870
  parseWithSchema = (schema, data, label) => {
3734
3871
  const parsed = schema.safeParse(data);
@@ -3783,12 +3920,29 @@ var init_schemas = __esm({
3783
3920
  parseScannerWorkerMessage = (message) => parseWithSchema(ScannerWorkerMessageSchema, message, "scanner worker message is invalid");
3784
3921
  }
3785
3922
  });
3923
+
3924
+ // packages/domain/scanner/src/index.ts
3925
+ var src_exports = {};
3926
+ __export(src_exports, {
3927
+ DEFAULT_EXTENSIONS: () => DEFAULT_EXTENSIONS,
3928
+ DEFAULT_IGNORES: () => DEFAULT_IGNORES,
3929
+ batchExtractClassesNative: () => batchExtractClassesNative,
3930
+ extractClassesNative: () => extractClassesNative,
3931
+ isScannableFile: () => isScannableFile,
3932
+ parseScanWorkspaceOptions: () => parseScanWorkspaceOptions,
3933
+ parseScanWorkspaceResult: () => parseScanWorkspaceResult,
3934
+ parseScannerWorkerMessage: () => parseScannerWorkerMessage,
3935
+ scanFile: () => scanFile,
3936
+ scanSource: () => scanSource,
3937
+ scanWorkspace: () => scanWorkspace,
3938
+ scanWorkspaceAsync: () => scanWorkspaceAsync
3939
+ });
3786
3940
  function getRuntimeDir() {
3787
3941
  if (typeof __dirname !== "undefined" && __dirname.length > 0) {
3788
3942
  return __dirname;
3789
3943
  }
3790
3944
  if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href)) }) !== "undefined" && (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href))) {
3791
- return path3__default.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href))));
3945
+ return path6__namespace.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href))));
3792
3946
  }
3793
3947
  return process.cwd();
3794
3948
  }
@@ -3798,17 +3952,17 @@ function resolveScannerWorkerModulePath() {
3798
3952
  return __dirname;
3799
3953
  }
3800
3954
  if (typeof ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href)) }) !== "undefined" && (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href))) {
3801
- return path3__default.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href))));
3955
+ return path6__namespace.default.dirname(url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href))));
3802
3956
  }
3803
3957
  return process.cwd();
3804
3958
  })();
3805
3959
  const candidates = [
3806
- path3__default.default.resolve(runtimeDir, "worker.cjs"),
3807
- path3__default.default.resolve(runtimeDir, "worker.js"),
3808
- path3__default.default.resolve(runtimeDir, "worker.ts")
3960
+ path6__namespace.default.resolve(runtimeDir, "worker.cjs"),
3961
+ path6__namespace.default.resolve(runtimeDir, "worker.js"),
3962
+ path6__namespace.default.resolve(runtimeDir, "worker.ts")
3809
3963
  ];
3810
3964
  for (const candidate of candidates) {
3811
- if (fs8__default.default.existsSync(candidate)) return candidate;
3965
+ if (fs11__namespace.default.existsSync(candidate)) return candidate;
3812
3966
  }
3813
3967
  return null;
3814
3968
  }
@@ -3818,7 +3972,7 @@ function scanWorkspaceInWorker(rootDir, options) {
3818
3972
  if (!modulePath) {
3819
3973
  return Promise.reject(new Error("scanner worker module path could not be resolved"));
3820
3974
  }
3821
- return new Promise((resolve, reject) => {
3975
+ return new Promise((resolve2, reject) => {
3822
3976
  const settleState = { settled: false };
3823
3977
  const worker = new worker_threads.Worker(modulePath, { workerData: { rootDir, options: normalizedOptions } });
3824
3978
  const timeout = setTimeout(() => {
@@ -3838,7 +3992,7 @@ function scanWorkspaceInWorker(rootDir, options) {
3838
3992
  const message = parseScannerWorkerMessage(payload);
3839
3993
  finish(() => {
3840
3994
  if (message?.ok) {
3841
- resolve(parseScanWorkspaceResult(message.result));
3995
+ resolve2(parseScanWorkspaceResult(message.result));
3842
3996
  return;
3843
3997
  }
3844
3998
  reject(new Error(message?.error ?? "scanner worker failed without an error message"));
@@ -3865,19 +4019,19 @@ function collectCandidates(rootDir, ignoreDirectories, extensionSet) {
3865
4019
  if (!currentDir) continue;
3866
4020
  const entries = (() => {
3867
4021
  try {
3868
- return fs8__default.default.readdirSync(currentDir, { withFileTypes: true });
4022
+ return fs11__namespace.default.readdirSync(currentDir, { withFileTypes: true });
3869
4023
  } catch {
3870
4024
  return [];
3871
4025
  }
3872
4026
  })();
3873
4027
  for (const entry of entries) {
3874
- const fullPath = path3__default.default.join(currentDir, entry.name);
4028
+ const fullPath = path6__namespace.default.join(currentDir, entry.name);
3875
4029
  if (entry.isDirectory()) {
3876
4030
  if (!ignoreDirectories.has(entry.name)) directories.push(fullPath);
3877
4031
  continue;
3878
4032
  }
3879
4033
  if (!entry.isFile()) continue;
3880
- if (!extensionSet.has(path3__default.default.extname(entry.name))) continue;
4034
+ if (!extensionSet.has(path6__namespace.default.extname(entry.name))) continue;
3881
4035
  candidates.push(fullPath);
3882
4036
  }
3883
4037
  }
@@ -3891,9 +4045,12 @@ function toCacheSize(size) {
3891
4045
  function scanSource(source) {
3892
4046
  const nativeBinding = nativeParserLoader.get();
3893
4047
  if (nativeBinding?.extractClassesFromSource) {
3894
- const classes = nativeBinding.extractClassesFromSource(source);
3895
- if (Array.isArray(classes)) {
3896
- return Array.from(new Set(classes.filter(Boolean)));
4048
+ const result = nativeBinding.extractClassesFromSource(source);
4049
+ if (Array.isArray(result)) {
4050
+ return Array.from(new Set(result.filter(Boolean)));
4051
+ }
4052
+ if (result !== null && result !== void 0 && Array.isArray(result.classes)) {
4053
+ return Array.from(new Set(result.classes.filter(Boolean)));
3897
4054
  }
3898
4055
  }
3899
4056
  throw new Error(
@@ -3901,15 +4058,18 @@ function scanSource(source) {
3901
4058
  );
3902
4059
  }
3903
4060
  function isScannableFile(filePath, includeExtensions = DEFAULT_EXTENSIONS) {
3904
- return includeExtensions.includes(path3__default.default.extname(filePath));
4061
+ return includeExtensions.includes(path6__namespace.default.extname(filePath));
3905
4062
  }
3906
4063
  function scanFile(filePath) {
3907
- const source = fs8__default.default.readFileSync(filePath, "utf8");
3908
- const hash = hashContentNative(source) ?? void 0;
4064
+ const { scanFileNative: scanFileNative2 } = (init_native_bridge(), __toCommonJS(native_bridge_exports));
4065
+ const result = scanFileNative2(filePath);
4066
+ if (!result.ok) {
4067
+ throw new Error(`scanFile failed for ${filePath}: ${result.error ?? "unknown error"}`);
4068
+ }
3909
4069
  return {
3910
- file: filePath,
3911
- classes: scanSource(source),
3912
- ...hash ? { hash } : {}
4070
+ file: result.file,
4071
+ classes: result.classes,
4072
+ ...result.hash ? { hash: result.hash } : {}
3913
4073
  };
3914
4074
  }
3915
4075
  function scanWorkspace(rootDir, options = {}) {
@@ -3958,7 +4118,7 @@ function scanWorkspace(rootDir, options = {}) {
3958
4118
  for (const filePath of candidates) {
3959
4119
  const stat = (() => {
3960
4120
  try {
3961
- return fs8__default.default.statSync(filePath);
4121
+ return fs11__namespace.default.statSync(filePath);
3962
4122
  } catch {
3963
4123
  return null;
3964
4124
  }
@@ -3984,7 +4144,7 @@ function scanWorkspace(rootDir, options = {}) {
3984
4144
  for (const { filePath, stat, size, cached } of ranked) {
3985
4145
  const content = (() => {
3986
4146
  try {
3987
- return fs8__default.default.readFileSync(filePath, "utf8");
4147
+ return fs11__namespace.default.readFileSync(filePath, "utf8");
3988
4148
  } catch {
3989
4149
  return null;
3990
4150
  }
@@ -4046,14 +4206,21 @@ function scanWorkspace(rootDir, options = {}) {
4046
4206
  }
4047
4207
  async function scanWorkspaceAsync(rootDir, options = {}) {
4048
4208
  const normalizedOptions = parseScanWorkspaceOptions(options);
4049
- if (process.env.TWS_DISABLE_SCANNER_WORKER === "1") {
4050
- return scanWorkspace(rootDir, normalizedOptions);
4209
+ try {
4210
+ return await scanWorkspaceParallel(rootDir, {
4211
+ extensions: normalizedOptions.includeExtensions,
4212
+ ignoreDirs: normalizedOptions.ignoreDirectories
4213
+ });
4214
+ } catch (parallelError) {
4215
+ log2.debug(
4216
+ `parallel scan failed, retrying with single worker: ${parallelError instanceof Error ? parallelError.message : String(parallelError)}`
4217
+ );
4051
4218
  }
4052
4219
  try {
4053
4220
  return await scanWorkspaceInWorker(rootDir, normalizedOptions);
4054
4221
  } catch (error) {
4055
4222
  log2.debug(
4056
- `worker scan failed, falling back to sync scanner: ${error instanceof Error ? error.message : String(error)}`
4223
+ `worker scan failed, retrying with sync native scanner: ${error instanceof Error ? error.message : String(error)}`
4057
4224
  );
4058
4225
  return scanWorkspace(rootDir, normalizedOptions);
4059
4226
  }
@@ -4064,7 +4231,10 @@ var init_src2 = __esm({
4064
4231
  init_src();
4065
4232
  init_cache_native();
4066
4233
  init_native_bridge();
4234
+ init_parallel_scanner();
4067
4235
  init_schemas();
4236
+ init_schemas();
4237
+ init_native_bridge();
4068
4238
  log2 = createLogger("scanner");
4069
4239
  SCAN_WORKER_TIMEOUT_MS = 12e4;
4070
4240
  createNativeParserLoader = () => {
@@ -4078,12 +4248,25 @@ var init_src2 = __esm({
4078
4248
  const loadNativeParserBinding = () => {
4079
4249
  if (_state.binding !== void 0) return _state.binding;
4080
4250
  const runtimeDir = getRuntimeDir();
4081
- const req = module$1.createRequire(path3__default.default.join(runtimeDir, "noop.cjs"));
4251
+ const req = module$1.createRequire(path6__namespace.default.join(runtimeDir, "noop.cjs"));
4082
4252
  const candidates = [
4083
- path3__default.default.resolve(process.cwd(), "native/tailwind_styled_parser.node"),
4084
- path3__default.default.resolve(process.cwd(), "native/build/Release/tailwind_styled_parser.node"),
4085
- path3__default.default.resolve(runtimeDir, "..", "..", "..", "native", "tailwind_styled_parser.node"),
4086
- path3__default.default.resolve(
4253
+ // ── binaryName baru: tailwind-styled-native (napi-rs naming) ──
4254
+ // cwd = repo root saat run dari root, atau package dir saat workspaces
4255
+ path6__namespace.default.resolve(process.cwd(), "native", "tailwind-styled-native.node"),
4256
+ path6__namespace.default.resolve(process.cwd(), "native", `tailwind-styled-native.${process.platform}-${process.arch}.node`),
4257
+ path6__namespace.default.resolve(process.cwd(), "native", `tailwind-styled-native.${process.platform}-${process.arch}-gnu.node`),
4258
+ // runtimeDir = dist/ → naik 4 level ke repo root
4259
+ path6__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", "tailwind-styled-native.node"),
4260
+ path6__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", `tailwind-styled-native.${process.platform}-${process.arch}-gnu.node`),
4261
+ // 3 level fallback (jika package di-nest lebih dangkal)
4262
+ path6__namespace.default.resolve(runtimeDir, "..", "..", "..", "native", "tailwind-styled-native.node"),
4263
+ path6__namespace.default.resolve(runtimeDir, "..", "..", "..", "native", `tailwind-styled-native.${process.platform}-${process.arch}-gnu.node`),
4264
+ // ── binaryName lama: tailwind_styled_parser (backward compat) ──
4265
+ path6__namespace.default.resolve(process.cwd(), "native/tailwind_styled_parser.node"),
4266
+ path6__namespace.default.resolve(process.cwd(), "native/build/Release/tailwind_styled_parser.node"),
4267
+ path6__namespace.default.resolve(runtimeDir, "..", "..", "..", "..", "native", "tailwind_styled_parser.node"),
4268
+ path6__namespace.default.resolve(runtimeDir, "..", "..", "..", "native", "tailwind_styled_parser.node"),
4269
+ path6__namespace.default.resolve(
4087
4270
  runtimeDir,
4088
4271
  "..",
4089
4272
  "..",
@@ -4095,7 +4278,7 @@ var init_src2 = __esm({
4095
4278
  )
4096
4279
  ];
4097
4280
  for (const fullPath of candidates) {
4098
- if (!fs8__default.default.existsSync(fullPath)) continue;
4281
+ if (!fs11__namespace.default.existsSync(fullPath)) continue;
4099
4282
  try {
4100
4283
  const required = req(fullPath);
4101
4284
  if (required && (typeof required.extractClassesFromSource === "function" || typeof required.parseClasses === "function" || typeof required.parse_classes === "function")) {
@@ -4137,7 +4320,7 @@ function isRecord(value) {
4137
4320
  }
4138
4321
  async function pathExists(filePath) {
4139
4322
  try {
4140
- await fs8__default.default.promises.access(filePath, fs8__default.default.constants.F_OK);
4323
+ await fs11__namespace.default.promises.access(filePath, fs11__namespace.default.constants.F_OK);
4141
4324
  return true;
4142
4325
  } catch {
4143
4326
  return false;
@@ -4163,6 +4346,9 @@ var init_utils = __esm({
4163
4346
  });
4164
4347
 
4165
4348
  // packages/domain/analyzer/src/binding.ts
4349
+ async function getNativeBinding() {
4350
+ return analyzerBindingLoader.get();
4351
+ }
4166
4352
  async function requireNativeBinding() {
4167
4353
  const binding = await analyzerBindingLoader.get();
4168
4354
  if (binding?.analyzeClasses) return binding;
@@ -4255,7 +4441,7 @@ var formatIssuePath3, isPlainObject, formatIssues2, parseWithSchema2, CountSchem
4255
4441
  var init_schemas2 = __esm({
4256
4442
  "packages/domain/analyzer/src/schemas.ts"() {
4257
4443
  init_src();
4258
- formatIssuePath3 = (path26) => path26.length > 0 ? path26.map(
4444
+ formatIssuePath3 = (path29) => path29.length > 0 ? path29.map(
4259
4445
  (segment) => typeof segment === "symbol" ? segment.description ?? segment.toString() : String(segment)
4260
4446
  ).join(".") : "<root>";
4261
4447
  isPlainObject = (value) => {
@@ -4264,8 +4450,8 @@ var init_schemas2 = __esm({
4264
4450
  return proto === Object.prototype || proto === null;
4265
4451
  };
4266
4452
  formatIssues2 = (error) => error.issues.map((issue) => {
4267
- const path26 = formatIssuePath3(issue.path);
4268
- return `${path26}: ${issue.message}`;
4453
+ const path29 = formatIssuePath3(issue.path);
4454
+ return `${path29}: ${issue.message}`;
4269
4455
  }).join("; ");
4270
4456
  parseWithSchema2 = (schema, data, label) => {
4271
4457
  const parsed = schema.safeParse(data);
@@ -4361,117 +4547,12 @@ var init_schemas2 = __esm({
4361
4547
  parseClassToCssOptions = (options) => parseWithSchema2(ClassToCssOptionsSchema, options ?? {}, "classToCss options are invalid");
4362
4548
  }
4363
4549
  });
4364
- var SUPPORTED_TAILWIND_CONFIG_EXTENSIONS, KNOWN_UTILITY_PREFIXES, tailwindConfigCache, splitVariantAndBase, isArbitraryUtility, resolveConflictGroup, detectConflicts, isSupportedTailwindConfigPath, resolveTailwindConfigPath, collectSafelistFromConfig, collectCustomUtilities, collectSafelistFromSource, loadTailwindConfig, utilityPrefix, isKnownTailwindClass, buildSemanticReport;
4550
+ var SUPPORTED_TAILWIND_CONFIG_EXTENSIONS, tailwindConfigCache, splitVariantAndBase, isArbitraryUtility, resolveConflictGroup, detectConflicts, isSupportedTailwindConfigPath, resolveTailwindConfigPath, collectSafelistFromConfig, collectCustomUtilities, collectSafelistFromSource, loadTailwindConfig, utilityPrefix, buildSemanticReport;
4365
4551
  var init_semantic = __esm({
4366
4552
  "packages/domain/analyzer/src/semantic.ts"() {
4553
+ init_binding();
4367
4554
  init_utils();
4368
4555
  SUPPORTED_TAILWIND_CONFIG_EXTENSIONS = /* @__PURE__ */ new Set([".ts", ".js", ".cjs", ".mjs"]);
4369
- KNOWN_UTILITY_PREFIXES = /* @__PURE__ */ new Set([
4370
- "absolute",
4371
- "align",
4372
- "animate",
4373
- "arbitrary",
4374
- "aspect",
4375
- "backdrop",
4376
- "basis",
4377
- "bg",
4378
- "block",
4379
- "border",
4380
- "bottom",
4381
- "col",
4382
- "container",
4383
- "contents",
4384
- "cursor",
4385
- "dark",
4386
- "display",
4387
- "divide",
4388
- "fill",
4389
- "fixed",
4390
- "flex",
4391
- "float",
4392
- "font",
4393
- "from",
4394
- "gap",
4395
- "grid",
4396
- "grow",
4397
- "h",
4398
- "hidden",
4399
- "inset",
4400
- "inline",
4401
- "isolate",
4402
- "items",
4403
- "justify",
4404
- "left",
4405
- "leading",
4406
- "line",
4407
- "list",
4408
- "m",
4409
- "max-h",
4410
- "max-w",
4411
- "mb",
4412
- "min-h",
4413
- "min-w",
4414
- "ml",
4415
- "mr",
4416
- "mt",
4417
- "mx",
4418
- "my",
4419
- "object",
4420
- "opacity",
4421
- "order",
4422
- "origin",
4423
- "outline",
4424
- "overflow",
4425
- "overscroll",
4426
- "p",
4427
- "pb",
4428
- "pe",
4429
- "perspective",
4430
- "place",
4431
- "pl",
4432
- "pointer",
4433
- "position",
4434
- "pr",
4435
- "ps",
4436
- "pt",
4437
- "px",
4438
- "py",
4439
- "relative",
4440
- "right",
4441
- "ring",
4442
- "rotate",
4443
- "rounded",
4444
- "row",
4445
- "scale",
4446
- "shadow",
4447
- "shrink",
4448
- "size",
4449
- "skew",
4450
- "snap",
4451
- "space-x",
4452
- "space-y",
4453
- "sr",
4454
- "start",
4455
- "static",
4456
- "sticky",
4457
- "stroke",
4458
- "table",
4459
- "text",
4460
- "to",
4461
- "top",
4462
- "touch",
4463
- "tracking",
4464
- "transform",
4465
- "transition",
4466
- "translate",
4467
- "truncate",
4468
- "underline",
4469
- "via",
4470
- "visible",
4471
- "w",
4472
- "whitespace",
4473
- "z"
4474
- ]);
4475
4556
  tailwindConfigCache = /* @__PURE__ */ new Map();
4476
4557
  splitVariantAndBase = (className) => {
4477
4558
  const parts = className.split(":");
@@ -4501,48 +4582,28 @@ var init_semantic = __esm({
4501
4582
  if (base.startsWith("m-") || base.startsWith("mx-") || base.startsWith("my-")) return "margin";
4502
4583
  return null;
4503
4584
  };
4504
- detectConflicts = (usages) => {
4505
- const buckets = /* @__PURE__ */ new Map();
4506
- for (const usage of usages) {
4507
- const { variantKey, base } = splitVariantAndBase(usage.name);
4508
- const group = resolveConflictGroup(base);
4509
- if (!group) continue;
4510
- const key = `${variantKey}::${group}`;
4511
- const bucket = buckets.get(key) ?? {
4512
- variantKey,
4513
- group,
4514
- classes: /* @__PURE__ */ new Set()
4515
- };
4516
- bucket.classes.add(usage.name);
4517
- buckets.set(key, bucket);
4518
- }
4519
- const conflicts = [];
4520
- const conflictedClassNames = /* @__PURE__ */ new Set();
4521
- for (const bucket of buckets.values()) {
4522
- if (bucket.classes.size <= 1) continue;
4523
- const classes = Array.from(bucket.classes).sort();
4524
- for (const className of classes) conflictedClassNames.add(className);
4525
- const variantLabel = bucket.variantKey.length > 0 ? bucket.variantKey : "base";
4526
- conflicts.push({
4527
- className: bucket.group,
4528
- variants: bucket.variantKey.length > 0 ? bucket.variantKey.split(":") : [],
4529
- classes,
4530
- message: `Multiple ${bucket.group} utilities detected for "${variantLabel}".`
4531
- });
4585
+ detectConflicts = async (usages) => {
4586
+ const native = await getNativeBinding();
4587
+ if (!native?.detectClassConflicts) {
4588
+ throw new Error("FATAL: Native binding 'detectClassConflicts' is required but not available.");
4532
4589
  }
4533
- conflicts.sort((left, right) => {
4534
- if (right.classes.length !== left.classes.length)
4535
- return right.classes.length - left.classes.length;
4536
- return left.className.localeCompare(right.className);
4537
- });
4538
- return { conflicts, conflictedClassNames };
4590
+ const result = native.detectClassConflicts(JSON.stringify(usages.map((u) => ({ name: u.name, count: u.count }))));
4591
+ return {
4592
+ conflicts: result.conflicts.map((c) => ({
4593
+ className: c.group,
4594
+ variants: c.variantKey.length > 0 ? c.variantKey.split(":") : [],
4595
+ classes: c.classes,
4596
+ message: c.message
4597
+ })),
4598
+ conflictedClassNames: new Set(result.conflictedClassNames)
4599
+ };
4539
4600
  };
4540
4601
  isSupportedTailwindConfigPath = (configPath) => {
4541
- return SUPPORTED_TAILWIND_CONFIG_EXTENSIONS.has(path3__default.default.extname(configPath).toLowerCase());
4602
+ return SUPPORTED_TAILWIND_CONFIG_EXTENSIONS.has(path6__namespace.default.extname(configPath).toLowerCase());
4542
4603
  };
4543
4604
  resolveTailwindConfigPath = async (root, explicitPath) => {
4544
4605
  if (explicitPath) {
4545
- const resolved = path3__default.default.resolve(root, explicitPath);
4606
+ const resolved = path6__namespace.default.resolve(root, explicitPath);
4546
4607
  if (!await pathExists(resolved)) return null;
4547
4608
  return resolved;
4548
4609
  }
@@ -4553,7 +4614,7 @@ var init_semantic = __esm({
4553
4614
  "tailwind.config.mjs"
4554
4615
  ];
4555
4616
  for (const candidate of candidates) {
4556
- const fullPath = path3__default.default.resolve(root, candidate);
4617
+ const fullPath = path6__namespace.default.resolve(root, candidate);
4557
4618
  if (await pathExists(fullPath)) return fullPath;
4558
4619
  }
4559
4620
  return null;
@@ -4607,15 +4668,19 @@ var init_semantic = __esm({
4607
4668
  return out;
4608
4669
  };
4609
4670
  collectSafelistFromSource = async (configPath) => {
4610
- const source = await fs8__default.default.promises.readFile(configPath, "utf8");
4611
- const safelistBlock = source.match(/safelist\s*:\s*\[([\s\S]*?)\]/m)?.[1];
4612
- if (!safelistBlock) return [];
4613
- const out = /* @__PURE__ */ new Set();
4614
- for (const token of safelistBlock.matchAll(/["'`]([^"'`]+)["'`]/g)) {
4671
+ const source = await fs11__namespace.default.promises.readFile(configPath, "utf8");
4672
+ const { extractClassesNative: extractClassesNative2 } = await Promise.resolve().then(() => (init_src2(), src_exports));
4673
+ const allTokens = extractClassesNative2(source);
4674
+ const hasSafelist = source.includes("safelist");
4675
+ if (!hasSafelist) return [];
4676
+ const safelistMatch = source.match(/safelist\s*:\s*\[([\s\S]*?)\]/m)?.[1];
4677
+ if (!safelistMatch) return [];
4678
+ const safelistSet = /* @__PURE__ */ new Set();
4679
+ for (const token of safelistMatch.matchAll(/["'`]([^"'`]+)["'`]/g)) {
4615
4680
  const value = token[1].trim();
4616
- if (value.length > 0) out.add(value);
4681
+ if (value.length > 0) safelistSet.add(value);
4617
4682
  }
4618
- return Array.from(out);
4683
+ return allTokens.filter((t) => safelistSet.has(t));
4619
4684
  };
4620
4685
  loadTailwindConfig = async (root, semanticOption) => {
4621
4686
  const startMs = Date.now();
@@ -4630,7 +4695,7 @@ var init_semantic = __esm({
4630
4695
  customUtilities: /* @__PURE__ */ new Set()
4631
4696
  };
4632
4697
  }
4633
- const configStat = await fs8__default.default.promises.stat(configPath).catch(() => null);
4698
+ const configStat = await fs11__namespace.default.promises.stat(configPath).catch(() => null);
4634
4699
  if (configStat) {
4635
4700
  const cached = tailwindConfigCache.get(configPath);
4636
4701
  if (cached && cached.mtimeMs === configStat.mtimeMs && cached.size === configStat.size) {
@@ -4716,21 +4781,27 @@ var init_semantic = __esm({
4716
4781
  if (hyphen < 0) return normalized;
4717
4782
  return normalized.slice(0, hyphen);
4718
4783
  };
4719
- isKnownTailwindClass = (className, safelist, customUtilities) => {
4720
- if (safelist.has(className) || customUtilities.has(className)) return true;
4721
- const { base } = splitVariantAndBase(className);
4722
- if (customUtilities.has(base)) return true;
4723
- const prefix = utilityPrefix(base);
4724
- return KNOWN_UTILITY_PREFIXES.has(prefix);
4725
- };
4726
4784
  buildSemanticReport = async (usages, root, semanticOption) => {
4727
4785
  const loadedConfig = await loadTailwindConfig(root, semanticOption);
4728
4786
  const safelist = loadedConfig?.safelist ?? /* @__PURE__ */ new Set();
4729
4787
  const customUtilities = loadedConfig?.customUtilities ?? /* @__PURE__ */ new Set();
4730
4788
  const usageNames = new Set(usages.map((usage) => usage.name));
4731
4789
  const unusedClasses = Array.from(safelist).filter((className) => !usageNames.has(className)).sort().map((className) => ({ name: className, count: 0, isUnused: true }));
4732
- const unknownClasses = usages.filter((usage) => !isKnownTailwindClass(usage.name, safelist, customUtilities)).map((usage) => ({ ...usage, isUnused: true }));
4733
- const { conflicts } = detectConflicts(usages);
4790
+ const native = await getNativeBinding();
4791
+ if (!native?.classifyKnownClasses) {
4792
+ throw new Error("FATAL: Native binding 'classifyKnownClasses' is required but not available.");
4793
+ }
4794
+ const classNames = usages.map((u) => u.name);
4795
+ const results = native.classifyKnownClasses(
4796
+ classNames,
4797
+ Array.from(safelist),
4798
+ Array.from(customUtilities)
4799
+ );
4800
+ const unknownSet = new Set(
4801
+ results.filter((r) => !r.isKnown).map((r) => r.className)
4802
+ );
4803
+ const unknownClasses = usages.filter((usage) => unknownSet.has(usage.name)).map((usage) => ({ ...usage, isUnused: true }));
4804
+ const { conflicts } = await detectConflicts(usages);
4734
4805
  return {
4735
4806
  unusedClasses,
4736
4807
  unknownClasses,
@@ -4766,13 +4837,17 @@ function normalizeScan(scan, includeClass) {
4766
4837
  uniqueClasses: Array.from(unique).sort()
4767
4838
  };
4768
4839
  }
4769
- function collectClassCounts(scan) {
4770
- const counts = /* @__PURE__ */ new Map();
4771
- for (const file of scan.files) {
4772
- for (const className of file.classes) {
4773
- counts.set(className, (counts.get(className) ?? 0) + 1);
4774
- }
4840
+ async function collectClassCounts(scan) {
4841
+ const native = await requireNativeBinding();
4842
+ if (!native?.collectClassCounts) {
4843
+ throw new Error("FATAL: Native binding 'collectClassCounts' is required but not available.");
4775
4844
  }
4845
+ const filesJson = JSON.stringify(
4846
+ scan.files.map((f) => ({ file: f.file ?? "", classes: f.classes }))
4847
+ );
4848
+ const result = native.collectClassCounts(filesJson);
4849
+ const counts = /* @__PURE__ */ new Map();
4850
+ for (const entry of result) counts.set(entry.name, entry.count);
4776
4851
  return counts;
4777
4852
  }
4778
4853
  function buildClassUsage(counts) {
@@ -4781,29 +4856,24 @@ function buildClassUsage(counts) {
4781
4856
  return left.name.localeCompare(right.name);
4782
4857
  });
4783
4858
  }
4784
- function buildDistribution(usages) {
4785
- const distribution = {
4786
- "1": 0,
4787
- "2-3": 0,
4788
- "4-7": 0,
4789
- "8+": 0
4790
- };
4791
- for (const usage of usages) {
4792
- if (usage.count === 1) {
4793
- distribution["1"] += 1;
4794
- } else if (usage.count <= 3) {
4795
- distribution["2-3"] += 1;
4796
- } else if (usage.count <= 7) {
4797
- distribution["4-7"] += 1;
4798
- } else {
4799
- distribution["8+"] += 1;
4800
- }
4859
+ async function buildDistribution(usages, native) {
4860
+ const binding = native ?? await requireNativeBinding();
4861
+ if (!binding?.buildDistribution) {
4862
+ throw new Error("FATAL: Native binding 'buildDistribution' is required but not available.");
4801
4863
  }
4802
- return distribution;
4864
+ const result = binding.buildDistribution(
4865
+ JSON.stringify(usages.map((u) => ({ name: u.name, count: u.count })))
4866
+ );
4867
+ return {
4868
+ "1": result.once,
4869
+ "2-3": result.few,
4870
+ "4-7": result.moderate,
4871
+ "8+": result.frequent
4872
+ };
4803
4873
  }
4804
4874
  async function analyzeWorkspace(root, options = {}) {
4805
4875
  const startedAtMs = Date.now();
4806
- const resolvedRoot = path3__default.default.resolve(root);
4876
+ const resolvedRoot = path6__namespace.default.resolve(root);
4807
4877
  const normalizedOptions = parseAnalyzerOptions(options);
4808
4878
  const scan = await (async () => {
4809
4879
  const scanStartedAtMs = Date.now();
@@ -4847,7 +4917,7 @@ async function analyzeWorkspace(root, options = {}) {
4847
4917
  );
4848
4918
  }
4849
4919
  })();
4850
- const counts = collectClassCounts(normalizedScan);
4920
+ const counts = await collectClassCounts(normalizedScan);
4851
4921
  const baseAll = buildClassUsage(counts);
4852
4922
  const { all, semanticReport } = await (async () => {
4853
4923
  if (!normalizedOptions.semantic) {
@@ -4873,13 +4943,19 @@ async function analyzeWorkspace(root, options = {}) {
4873
4943
  );
4874
4944
  }
4875
4945
  })();
4876
- const top = all.slice(0, topLimit);
4877
- const frequent = all.filter((usage) => usage.count >= frequentThreshold).slice(0, topLimit);
4878
- const unique = all.filter((usage) => usage.count === 1);
4879
- const totalClassOccurrences = all.reduce((sum, usage) => sum + usage.count, 0);
4946
+ const classStatsNative = binding?.computeClassStats?.(
4947
+ JSON.stringify(all),
4948
+ topLimit,
4949
+ frequentThreshold
4950
+ );
4951
+ const top = classStatsNative ? JSON.parse(classStatsNative.topJson) : all.slice(0, topLimit);
4952
+ const frequent = classStatsNative ? JSON.parse(classStatsNative.frequentJson) : all.filter((usage) => usage.count >= frequentThreshold).slice(0, topLimit);
4953
+ const unique = classStatsNative ? JSON.parse(classStatsNative.uniqueJson) : all.filter((usage) => usage.count === 1);
4954
+ const totalClassOccurrences = classStatsNative ? classStatsNative.totalClassOccurrences : all.reduce((sum, usage) => sum + usage.count, 0);
4880
4955
  debugLog(
4881
4956
  `analyzeWorkspace completed in ${Date.now() - startedAtMs}ms (files=${normalizedScan.totalFiles}, uniqueClasses=${all.length})`
4882
4957
  );
4958
+ const distribution = await buildDistribution(all, binding);
4883
4959
  return {
4884
4960
  root: nativeReport.root || resolvedRoot,
4885
4961
  totalFiles: nativeReport.totalFiles,
@@ -4890,8 +4966,10 @@ async function analyzeWorkspace(root, options = {}) {
4890
4966
  top,
4891
4967
  frequent,
4892
4968
  unique,
4893
- distribution: buildDistribution(all)
4969
+ distribution
4894
4970
  },
4971
+ // topClasses — alias for classStats.top (test contract & backward compat)
4972
+ topClasses: top,
4895
4973
  safelist: all.map((usage) => usage.name),
4896
4974
  ...semanticReport ? { semantic: semanticReport } : {}
4897
4975
  };
@@ -4913,8 +4991,11 @@ var init_classToCss = __esm({
4913
4991
  init_binding();
4914
4992
  init_schemas2();
4915
4993
  init_utils();
4916
- normalizeClassInput = (input) => {
4994
+ normalizeClassInput = (input, _binding) => {
4917
4995
  if (typeof input === "string") {
4996
+ if (_binding?.normalizeClassInput) {
4997
+ return _binding.normalizeClassInput(input);
4998
+ }
4918
4999
  return input.split(/\s+/).map((item) => item.trim()).filter((item) => item.length > 0);
4919
5000
  }
4920
5001
  if (!Array.isArray(input)) {
@@ -4936,27 +5017,26 @@ var init_classToCss = __esm({
4936
5017
  const prefix = parsed.prefix ?? null;
4937
5018
  return { prefix, strict };
4938
5019
  };
4939
- mergeDeclarationMap = (target, css) => {
4940
- for (const ruleMatch of css.matchAll(/\{([^}]*)\}/g)) {
4941
- const body = ruleMatch[1];
4942
- for (const raw of body.split(";")) {
4943
- const declaration = raw.trim();
4944
- if (declaration.length === 0) continue;
4945
- const colonIndex = declaration.indexOf(":");
4946
- if (colonIndex <= 0) continue;
4947
- const property = declaration.slice(0, colonIndex).trim();
4948
- const value = declaration.slice(colonIndex + 1).trim();
4949
- if (property.length === 0 || value.length === 0) continue;
4950
- if (target.has(property)) target.delete(property);
4951
- target.set(property, value);
4952
- }
5020
+ mergeDeclarationMap = (target, css, binding) => {
5021
+ if (!binding.parseCssRules) {
5022
+ throw new Error("FATAL: Native binding 'parseCssRules' is required but not available.");
5023
+ }
5024
+ const rules = binding.parseCssRules(css);
5025
+ for (const rule of rules) {
5026
+ if (target.has(rule.property)) target.delete(rule.property);
5027
+ target.set(rule.property, rule.isImportant ? `${rule.value} !important` : rule.value);
4953
5028
  }
4954
5029
  };
4955
- declarationMapToString = (declarationMap) => {
4956
- return Array.from(declarationMap.entries()).map(([property, value]) => `${property}: ${value}`).join("; ");
5030
+ declarationMapToString = (declarationMap, binding) => {
5031
+ const entries = Array.from(declarationMap.entries()).map(([property, value]) => ({ property, value }));
5032
+ if (binding?.declarationMapToString) {
5033
+ return binding.declarationMapToString(entries);
5034
+ }
5035
+ return entries.map(({ property, value }) => `${property}: ${value}`).join("; ");
4957
5036
  };
4958
5037
  classToCss = async (input, options = {}) => {
4959
- const inputClasses = normalizeClassInput(input);
5038
+ const binding = await requireNativeCssCompiler();
5039
+ const inputClasses = normalizeClassInput(input, binding);
4960
5040
  const normalizedOptions = normalizeClassToCssOptions(options);
4961
5041
  if (inputClasses.length === 0) {
4962
5042
  return {
@@ -4968,7 +5048,6 @@ var init_classToCss = __esm({
4968
5048
  sizeBytes: 0
4969
5049
  };
4970
5050
  }
4971
- const binding = await requireNativeCssCompiler();
4972
5051
  const prefix = normalizedOptions.prefix;
4973
5052
  const results = await Promise.all(
4974
5053
  inputClasses.map(async (className) => {
@@ -5001,7 +5080,7 @@ var init_classToCss = __esm({
5001
5080
  const sizeBytes = results.reduce((sum, r) => sum + r.sizeBytes, 0);
5002
5081
  const declarationMap = /* @__PURE__ */ new Map();
5003
5082
  for (const result of results) {
5004
- mergeDeclarationMap(declarationMap, result.css);
5083
+ mergeDeclarationMap(declarationMap, result.css, binding);
5005
5084
  }
5006
5085
  const uniqueUnknown = Array.from(new Set(unknownClasses));
5007
5086
  if (normalizedOptions.strict && uniqueUnknown.length > 0) {
@@ -5010,7 +5089,7 @@ var init_classToCss = __esm({
5010
5089
  return {
5011
5090
  inputClasses,
5012
5091
  css: cssChunks.filter((chunk) => chunk.length > 0).join("\n"),
5013
- declarations: declarationMapToString(declarationMap),
5092
+ declarations: declarationMapToString(declarationMap, binding),
5014
5093
  resolvedClasses: Array.from(new Set(resolvedClasses)),
5015
5094
  unknownClasses: uniqueUnknown,
5016
5095
  sizeBytes
@@ -5020,8 +5099,8 @@ var init_classToCss = __esm({
5020
5099
  });
5021
5100
 
5022
5101
  // packages/domain/analyzer/src/index.ts
5023
- var src_exports = {};
5024
- __export(src_exports, {
5102
+ var src_exports2 = {};
5103
+ __export(src_exports2, {
5025
5104
  __internal: () => __internal,
5026
5105
  analyzeWorkspace: () => analyzeWorkspace,
5027
5106
  classToCss: () => classToCss
@@ -5049,7 +5128,7 @@ var init_src3 = __esm({
5049
5128
  });
5050
5129
  async function pathExists2(filePath) {
5051
5130
  try {
5052
- await fs4__default.default.access(filePath);
5131
+ await fs7__default.default.access(filePath);
5053
5132
  return true;
5054
5133
  } catch {
5055
5134
  return false;
@@ -5057,7 +5136,7 @@ async function pathExists2(filePath) {
5057
5136
  }
5058
5137
  async function readFileSafe(filePath) {
5059
5138
  try {
5060
- return await fs4__default.default.readFile(filePath, "utf8");
5139
+ return await fs7__default.default.readFile(filePath, "utf8");
5061
5140
  } catch {
5062
5141
  return null;
5063
5142
  }
@@ -5076,8 +5155,8 @@ async function writeFileSafe(filePath, content, options = {}) {
5076
5155
  options.onDryRun?.(`write ${filePath}`);
5077
5156
  return;
5078
5157
  }
5079
- await fs4__default.default.mkdir(path3__default.default.dirname(filePath), { recursive: true });
5080
- await fs4__default.default.writeFile(filePath, content, "utf8");
5158
+ await fs7__default.default.mkdir(path6__namespace.default.dirname(filePath), { recursive: true });
5159
+ await fs7__default.default.writeFile(filePath, content, "utf8");
5081
5160
  }
5082
5161
  async function ensureFileSafe(filePath, content, options = {}) {
5083
5162
  if (await pathExists2(filePath)) return "skipped";
@@ -5365,11 +5444,11 @@ var init_args = __esm({
5365
5444
  });
5366
5445
  function runtimeDirFromImportMeta(importMetaUrl) {
5367
5446
  const filename = url.fileURLToPath(importMetaUrl);
5368
- return path3__default.default.dirname(filename);
5447
+ return path6__namespace.default.dirname(filename);
5369
5448
  }
5370
5449
  async function resolveMonorepoPath(runtimeDir, relativeToRepoRoot) {
5371
- const fromRuntime = path3__default.default.resolve(runtimeDir, "..", "..", "..", relativeToRepoRoot);
5372
- const fromCwd = path3__default.default.resolve(process.cwd(), relativeToRepoRoot);
5450
+ const fromRuntime = path6__namespace.default.resolve(runtimeDir, "..", "..", "..", relativeToRepoRoot);
5451
+ const fromCwd = path6__namespace.default.resolve(process.cwd(), relativeToRepoRoot);
5373
5452
  return await pathExists2(fromRuntime) ? fromRuntime : fromCwd;
5374
5453
  }
5375
5454
  async function firstExistingPath(paths) {
@@ -5445,7 +5524,8 @@ async function runCliMain(options) {
5445
5524
  await program2.parseAsync(argv);
5446
5525
  } catch (error) {
5447
5526
  const isHelpError = isHelpExit(error);
5448
- if (isHelpError) return;
5527
+ const isVersionError = isVersionExit(error);
5528
+ if (isHelpError || isVersionError) return;
5449
5529
  const normalized = normalizeCliError(error);
5450
5530
  const isJson = input.json;
5451
5531
  if (isJson) {
@@ -5460,7 +5540,7 @@ async function runCliMain(options) {
5460
5540
  process.exitCode = errorExitCode(normalized);
5461
5541
  }
5462
5542
  }
5463
- var isCommanderLikeError, isHelpExit, normalizeCliError, findCommandByPath, resolveCommandHelp, resolveHelpPath, walkCommands;
5543
+ var isCommanderLikeError, isHelpExit, isVersionExit, normalizeCliError, findCommandByPath, resolveCommandHelp, resolveHelpPath, walkCommands;
5464
5544
  var init_runtime = __esm({
5465
5545
  "packages/infrastructure/cli/src/utils/runtime.ts"() {
5466
5546
  init_args();
@@ -5473,6 +5553,9 @@ var init_runtime = __esm({
5473
5553
  isHelpExit = (error) => {
5474
5554
  return isCommanderLikeError(error) && error.code === "commander.helpDisplayed";
5475
5555
  };
5556
+ isVersionExit = (error) => {
5557
+ return isCommanderLikeError(error) && error.code === "commander.version";
5558
+ };
5476
5559
  normalizeCliError = (error) => {
5477
5560
  if (!isCommanderLikeError(error)) return error;
5478
5561
  if (!error.code?.startsWith("commander.")) return error;
@@ -5553,7 +5636,7 @@ async function resolveCreateInput(options) {
5553
5636
  return { name: resolvedName, template: templateValue };
5554
5637
  }
5555
5638
  async function writeProjectFile(context, relativePath, content) {
5556
- const filePath = path3__default.default.join(context.projectDir, relativePath);
5639
+ const filePath = path6__namespace.default.join(context.projectDir, relativePath);
5557
5640
  await writeFileSafe(filePath, content, { dryRun: context.dryRun });
5558
5641
  context.writtenFiles.push(relativePath.replaceAll("\\", "/"));
5559
5642
  }
@@ -5672,7 +5755,6 @@ async function createViteVueApp(context) {
5672
5755
  scripts: { dev: "vite", build: "vite build", preview: "vite preview" },
5673
5756
  dependencies: {
5674
5757
  vue: "^3.4.0",
5675
- "tailwind-merge": "^3.5.0",
5676
5758
  "tailwind-styled-v4/vue": "^5.0.0"
5677
5759
  },
5678
5760
  devDependencies: {
@@ -5769,7 +5851,7 @@ async function createViteSvelteApp(context) {
5769
5851
  private: true,
5770
5852
  type: "module",
5771
5853
  scripts: { dev: "vite", build: "vite build", preview: "vite preview" },
5772
- dependencies: { "tailwind-merge": "^3.5.0", "tailwind-styled-v4/svelte": "^5.0.0" },
5854
+ dependencies: { "tailwind-styled-v4/svelte": "^5.0.0" },
5773
5855
  devDependencies: {
5774
5856
  svelte: "^5.0.0",
5775
5857
  "@sveltejs/vite-plugin-svelte": "^3.0.0",
@@ -5870,7 +5952,7 @@ async function createSimpleApp(context) {
5870
5952
  }
5871
5953
  async function createProject(options, output) {
5872
5954
  const { name, template } = await resolveCreateInput(options);
5873
- const projectDir = path3__default.default.resolve(process.cwd(), name);
5955
+ const projectDir = path6__namespace.default.resolve(process.cwd(), name);
5874
5956
  if (await pathExists2(projectDir)) {
5875
5957
  throw new CliUsageError(`Directory ${name} already exists.`);
5876
5958
  }
@@ -5941,10 +6023,13 @@ var init_createApp = __esm({
5941
6023
  };
5942
6024
  }
5943
6025
  });
5944
- var log3, NATIVE_UNAVAILABLE_MESSAGE, nativeBridge, bridgeLoadAttempted, bridgeLoadError, isValidNativeBridge, getNativeBridge;
6026
+
6027
+ // packages/domain/compiler/src/nativeBridge.ts
6028
+ var _loadNative, log3, NATIVE_UNAVAILABLE_MESSAGE, nativeBridge, bridgeLoadAttempted, bridgeLoadError, isValidNativeBridge, getNativeBridge;
5945
6029
  var init_nativeBridge = __esm({
5946
6030
  "packages/domain/compiler/src/nativeBridge.ts"() {
5947
6031
  init_src();
6032
+ _loadNative = (path29) => __require(path29);
5948
6033
  log3 = (...args) => {
5949
6034
  if (process.env.DEBUG?.includes("compiler:native")) {
5950
6035
  console.log("[compiler:native]", ...args);
@@ -5971,11 +6056,10 @@ var init_nativeBridge = __esm({
5971
6056
  bridgeLoadAttempted = true;
5972
6057
  try {
5973
6058
  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
6059
  const result = resolveNativeBinary(runtimeDir);
5976
6060
  if (result.path && result.path.endsWith(".node")) {
5977
6061
  try {
5978
- const binding = require2(result.path);
6062
+ const binding = _loadNative(result.path);
5979
6063
  if (isValidNativeBridge(binding)) {
5980
6064
  nativeBridge = binding;
5981
6065
  log3("Native bridge loaded successfully from:", result.path);
@@ -6010,7 +6094,7 @@ init_esm();
6010
6094
  init_errors();
6011
6095
  async function loadAnalyzerModule() {
6012
6096
  try {
6013
- const mod = await Promise.resolve().then(() => (init_src3(), src_exports));
6097
+ const mod = await Promise.resolve().then(() => (init_src3(), src_exports2));
6014
6098
  if (typeof mod.analyzeWorkspace !== "function") {
6015
6099
  throw new Error("analyzeWorkspace export not found");
6016
6100
  }
@@ -6077,7 +6161,7 @@ async function runAnalyzeCli(args) {
6077
6161
  verbose: process.env.TWS_VERBOSE === "1" || process.env.VERBOSE === "1"
6078
6162
  });
6079
6163
  const dirArg = parsed.positionals[0] ?? ".";
6080
- const dir = path3__default.default.resolve(process.cwd(), dirArg);
6164
+ const dir = path6__namespace.default.resolve(process.cwd(), dirArg);
6081
6165
  if (!await pathExists2(dir)) {
6082
6166
  throw new CliUsageError(`Directory not found: ${dir}`);
6083
6167
  }
@@ -6133,7 +6217,7 @@ async function runExtractCli(args) {
6133
6217
  const parsedMin = parseInt(minRaw, 10);
6134
6218
  const minCount = Number.isFinite(parsedMin) && parsedMin > 0 ? parsedMin : 2;
6135
6219
  const dirArg = parsed.positionals[0] ?? ".";
6136
- const dir = path3__default.default.resolve(process.cwd(), dirArg);
6220
+ const dir = path6__namespace.default.resolve(process.cwd(), dirArg);
6137
6221
  if (!await pathExists2(dir)) {
6138
6222
  throw new CliUsageError(`Directory not found: ${dir}`);
6139
6223
  }
@@ -6206,15 +6290,15 @@ async function runInitCli(rawArgs) {
6206
6290
  verbose: process.env.TWS_VERBOSE === "1" || process.env.VERBOSE === "1"
6207
6291
  });
6208
6292
  const target = rawArgs.find((arg) => !arg.startsWith("-")) ?? ".";
6209
- const root = path3__default.default.resolve(process.cwd(), target);
6293
+ const root = path6__namespace.default.resolve(process.cwd(), target);
6210
6294
  const report = { created: [], skipped: [] };
6211
6295
  await ensureFile(
6212
- path3__default.default.join(root, "src", "tailwind.css"),
6296
+ path6__namespace.default.join(root, "src", "tailwind.css"),
6213
6297
  '@import "tailwindcss";\n\n@theme {\n --color-primary: #3b82f6;\n --spacing-section: 3rem;\n}\n',
6214
6298
  report
6215
6299
  );
6216
6300
  await ensureFile(
6217
- path3__default.default.join(root, "tailwind-styled.config.json"),
6301
+ path6__namespace.default.join(root, "tailwind-styled.config.json"),
6218
6302
  `${JSON.stringify(
6219
6303
  {
6220
6304
  version: 1,
@@ -6233,12 +6317,12 @@ async function runInitCli(rawArgs) {
6233
6317
  output.writeText("\nInit complete");
6234
6318
  output.writeText(`Created: ${report.created.length}`);
6235
6319
  for (const filePath of report.created) {
6236
- output.writeText(` + ${path3__default.default.relative(root, filePath)}`);
6320
+ output.writeText(` + ${path6__namespace.default.relative(root, filePath)}`);
6237
6321
  }
6238
6322
  if (report.skipped.length > 0) {
6239
6323
  output.writeText(`Skipped: ${report.skipped.length}`);
6240
6324
  for (const filePath of report.skipped) {
6241
- output.writeText(` - ${path3__default.default.relative(root, filePath)} (exists)`);
6325
+ output.writeText(` - ${path6__namespace.default.relative(root, filePath)} (exists)`);
6242
6326
  }
6243
6327
  }
6244
6328
  }
@@ -6299,15 +6383,15 @@ async function findSourceFiles(dir) {
6299
6383
  const out = [];
6300
6384
  async function walk(currentDir) {
6301
6385
  if (!await pathExists2(currentDir)) return;
6302
- const entries = await fs4__default.default.readdir(currentDir, { withFileTypes: true });
6386
+ const entries = await fs7__default.default.readdir(currentDir, { withFileTypes: true });
6303
6387
  for (const entry of entries) {
6304
- const fullPath = path3__default.default.join(currentDir, entry.name);
6388
+ const fullPath = path6__namespace.default.join(currentDir, entry.name);
6305
6389
  if (entry.isDirectory()) {
6306
6390
  if (IGNORED_DIRS.has(entry.name)) continue;
6307
6391
  await walk(fullPath);
6308
6392
  continue;
6309
6393
  }
6310
- if (SOURCE_EXTENSIONS.has(path3__default.default.extname(entry.name))) {
6394
+ if (SOURCE_EXTENSIONS.has(path6__namespace.default.extname(entry.name))) {
6311
6395
  out.push(fullPath);
6312
6396
  }
6313
6397
  }
@@ -6328,7 +6412,7 @@ function migrateSource(source, options) {
6328
6412
  return { output, classRenames: 0, importRenames };
6329
6413
  }
6330
6414
  async function migrateConfig(root, dryRun) {
6331
- const cssPath = path3__default.default.join(root, "src", "tailwind.css");
6415
+ const cssPath = path6__namespace.default.join(root, "src", "tailwind.css");
6332
6416
  if (await pathExists2(cssPath)) return 0;
6333
6417
  await writeFileSafe(cssPath, DEFAULT_TAILWIND_CSS, { dryRun });
6334
6418
  return 1;
@@ -6341,7 +6425,7 @@ async function runMigrateCli(rawArgs) {
6341
6425
  verbose: process.env.TWS_VERBOSE === "1" || process.env.VERBOSE === "1"
6342
6426
  });
6343
6427
  const target = firstPositional(rawArgs) ?? ".";
6344
- const root = path3__default.default.resolve(process.cwd(), target);
6428
+ const root = path6__namespace.default.resolve(process.cwd(), target);
6345
6429
  const dryRunFlag = hasFlag("dry-run", rawArgs);
6346
6430
  const wizardOptions = hasFlag("wizard", rawArgs) ? await runMigrationWizard() : null;
6347
6431
  const { dryRun, includeConfig, includeClasses, includeImports } = wizardOptions ? {
@@ -6365,12 +6449,12 @@ async function runMigrateCli(rawArgs) {
6365
6449
  report.configWrites += await migrateConfig(root, dryRun);
6366
6450
  }
6367
6451
  for (const filePath of files) {
6368
- const source = await fs4__default.default.readFile(filePath, "utf8");
6452
+ const source = await fs7__default.default.readFile(filePath, "utf8");
6369
6453
  const migrated = migrateSource(source, { includeImports, includeClasses });
6370
6454
  if (migrated.output !== source) {
6371
6455
  report.updatedFiles++;
6372
6456
  if (!dryRun) {
6373
- await fs4__default.default.writeFile(filePath, migrated.output, "utf8");
6457
+ await fs7__default.default.writeFile(filePath, migrated.output, "utf8");
6374
6458
  }
6375
6459
  }
6376
6460
  report.classRenames += migrated.classRenames;
@@ -6434,10 +6518,10 @@ function buildClassNames(files, uniqueClasses) {
6434
6518
  });
6435
6519
  }
6436
6520
  function writeScanCache(root, cacheData) {
6437
- const cacheDir = path3__default.default.join(root, ".tailwind-styled");
6438
- const cachePath = path3__default.default.join(cacheDir, "scan-cache.json");
6439
- fs8__default.default.mkdirSync(cacheDir, { recursive: true });
6440
- fs8__default.default.writeFileSync(cachePath, JSON.stringify(cacheData, null, 2), "utf-8");
6521
+ const cacheDir = path6__namespace.default.join(root, ".tailwind-styled");
6522
+ const cachePath = path6__namespace.default.join(cacheDir, "scan-cache.json");
6523
+ fs11__namespace.default.mkdirSync(cacheDir, { recursive: true });
6524
+ fs11__namespace.default.writeFileSync(cachePath, JSON.stringify(cacheData, null, 2), "utf-8");
6441
6525
  return cachePath;
6442
6526
  }
6443
6527
  async function runScanCli(rawArgs) {
@@ -6449,7 +6533,7 @@ async function runScanCli(rawArgs) {
6449
6533
  debug: process.env.TWS_DEBUG === "1" || process.env.DEBUG === "1",
6450
6534
  verbose: process.env.TWS_VERBOSE === "1" || process.env.VERBOSE === "1"
6451
6535
  });
6452
- const root = path3__default.default.resolve(process.cwd(), target);
6536
+ const root = path6__namespace.default.resolve(process.cwd(), target);
6453
6537
  const spinner = output.spinner();
6454
6538
  spinner.start(`Scanning ${root}`);
6455
6539
  const scanned = await scanWorkspaceAsync(root);
@@ -6739,7 +6823,7 @@ var writeVerboseLine = (binary, args) => {
6739
6823
  console.error(` [verbose] $ ${formatCommand(binary, args)}`);
6740
6824
  };
6741
6825
  var runCommand = async (binary, args, options = {}) => {
6742
- return new Promise((resolve, reject) => {
6826
+ return new Promise((resolve2, reject) => {
6743
6827
  if (isVerboseEnabled(options)) {
6744
6828
  writeVerboseLine(binary, args);
6745
6829
  }
@@ -6766,7 +6850,7 @@ var runCommand = async (binary, args, options = {}) => {
6766
6850
  );
6767
6851
  return;
6768
6852
  }
6769
- resolve(exitCode);
6853
+ resolve2(exitCode);
6770
6854
  });
6771
6855
  });
6772
6856
  };
@@ -6795,7 +6879,7 @@ var formatCommandFailureOutput = (stdout, stderr) => {
6795
6879
  return "Command failed with no output.";
6796
6880
  };
6797
6881
  var runCommandCapture = async (binary, args, options = {}) => {
6798
- return new Promise((resolve, reject) => {
6882
+ return new Promise((resolve2, reject) => {
6799
6883
  if (isVerboseEnabled(options)) {
6800
6884
  writeVerboseLine(binary, args);
6801
6885
  }
@@ -6838,7 +6922,7 @@ ${formatCommandFailureOutput(stdout, stderr)}`,
6838
6922
  );
6839
6923
  return;
6840
6924
  }
6841
- resolve({
6925
+ resolve2({
6842
6926
  exitCode,
6843
6927
  stdout,
6844
6928
  stderr
@@ -6876,12 +6960,12 @@ function configureSetupFlags(rawArgs) {
6876
6960
  };
6877
6961
  }
6878
6962
  async function readPackageJson(cwd2) {
6879
- return readJsonSafe(path3__default.default.join(cwd2, "package.json"));
6963
+ return readJsonSafe(path6__namespace.default.join(cwd2, "package.json"));
6880
6964
  }
6881
6965
  async function detectPm(cwd2) {
6882
- if (await pathExists2(path3__default.default.join(cwd2, "bun.lockb"))) return "bun";
6883
- if (await pathExists2(path3__default.default.join(cwd2, "pnpm-lock.yaml"))) return "pnpm";
6884
- if (await pathExists2(path3__default.default.join(cwd2, "yarn.lock"))) return "yarn";
6966
+ if (await pathExists2(path6__namespace.default.join(cwd2, "bun.lockb"))) return "bun";
6967
+ if (await pathExists2(path6__namespace.default.join(cwd2, "pnpm-lock.yaml"))) return "pnpm";
6968
+ if (await pathExists2(path6__namespace.default.join(cwd2, "yarn.lock"))) return "yarn";
6885
6969
  return "npm";
6886
6970
  }
6887
6971
  async function detectBundler(cwd2) {
@@ -6902,7 +6986,7 @@ async function alreadyInstalled(cwd2, pkgName) {
6902
6986
  }
6903
6987
  async function findExisting(cwd2, names) {
6904
6988
  for (const name of names) {
6905
- const resolved = path3__default.default.join(cwd2, name);
6989
+ const resolved = path6__namespace.default.join(cwd2, name);
6906
6990
  if (await pathExists2(resolved)) return resolved;
6907
6991
  }
6908
6992
  return null;
@@ -7042,16 +7126,10 @@ var runSetupCli = async (rawArgs) => {
7042
7126
  output.writeText(import_picocolors3.default.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));
7043
7127
  output.writeText("");
7044
7128
  output.writeText(import_picocolors3.default.bold(" [1/4]") + import_picocolors3.default.cyan(" packages"));
7045
- const [hasCorePkg, hasMergePkg] = await Promise.all([
7046
- alreadyInstalled(cwd, "tailwind-styled-v4"),
7047
- alreadyInstalled(cwd, "tailwind-merge")
7048
- ]);
7049
- const toInstall = [
7050
- hasCorePkg ? null : "tailwind-styled-v4",
7051
- hasMergePkg ? null : "tailwind-merge"
7052
- ].filter(Boolean);
7129
+ const hasCorePkg = await alreadyInstalled(cwd, "tailwind-styled-v4");
7130
+ const toInstall = hasCorePkg ? [] : ["tailwind-styled-v4"];
7053
7131
  if (toInstall.length > 0) await installPackages(cwd, pm, toInstall, false, setupFlags, logger);
7054
- else logger.skip("tailwind-styled-v4 + tailwind-merge sudah terpasang");
7132
+ else logger.skip("tailwind-styled-v4 sudah terpasang");
7055
7133
  output.writeText("\n" + import_picocolors3.default.bold(" [2/4]") + import_picocolors3.default.cyan(" bundler config"));
7056
7134
  const bundlerConfigMap = {
7057
7135
  next: {
@@ -7074,7 +7152,7 @@ var runSetupCli = async (rawArgs) => {
7074
7152
  if (bundlerConfig) {
7075
7153
  const cfg = await findExisting(cwd, bundlerConfig.files);
7076
7154
  if (cfg)
7077
- await patchFileWithDryRun(cfg, bundlerConfig.patcher, path3__default.default.basename(cfg), setupFlags, logger);
7155
+ await patchFileWithDryRun(cfg, bundlerConfig.patcher, path6__namespace.default.basename(cfg), setupFlags, logger);
7078
7156
  else logger.warn(bundlerConfig.warnMsg);
7079
7157
  } else {
7080
7158
  logger.skip("React tanpa bundler - tidak ada bundler config yang di-patch");
@@ -7093,8 +7171,8 @@ var runSetupCli = async (rawArgs) => {
7093
7171
  if (cssFile) {
7094
7172
  await patchFileWithDryRun(
7095
7173
  cssFile,
7096
- (src) => patchTailwindCss(src, bundler, path3__default.default.relative(cwd, cssFile), cwd),
7097
- path3__default.default.relative(cwd, cssFile),
7174
+ (src) => patchTailwindCss(src, bundler, path6__namespace.default.relative(cwd, cssFile), cwd),
7175
+ path6__namespace.default.relative(cwd, cssFile),
7098
7176
  setupFlags,
7099
7177
  logger
7100
7178
  );
@@ -7102,7 +7180,7 @@ var runSetupCli = async (rawArgs) => {
7102
7180
  logger.warn('CSS entry tidak ditemukan \u2014 tambahkan @import "tailwindcss" manual ke globals.css');
7103
7181
  }
7104
7182
  output.writeText("\n" + import_picocolors3.default.bold(" [4/4]") + import_picocolors3.default.cyan(" tsconfig.json"));
7105
- const tsCfg = path3__default.default.join(cwd, "tsconfig.json");
7183
+ const tsCfg = path6__namespace.default.join(cwd, "tsconfig.json");
7106
7184
  const hasTsConfig = await findExisting(cwd, ["tsconfig.json"]);
7107
7185
  if (hasTsConfig) {
7108
7186
  await patchFileWithDryRun(tsCfg, patchTsConfig, "tsconfig.json", setupFlags, logger);
@@ -7168,7 +7246,7 @@ async function runStatsCli(args) {
7168
7246
  verbose: process.env.TWS_VERBOSE === "1" || process.env.VERBOSE === "1"
7169
7247
  });
7170
7248
  const dirArg = parsed.positionals[0] ?? ".";
7171
- const dir = path3__default.default.resolve(process.cwd(), dirArg);
7249
+ const dir = path6__namespace.default.resolve(process.cwd(), dirArg);
7172
7250
  if (!await pathExists2(dir)) {
7173
7251
  throw new CliUsageError(`Directory not found: ${dir}`);
7174
7252
  }
@@ -7222,13 +7300,13 @@ async function runStatsCli(args) {
7222
7300
  init_runtime();
7223
7301
  function collectTsFiles(dir, extensions) {
7224
7302
  const files = [];
7225
- const entries = fs8.readdirSync(dir, { withFileTypes: true });
7303
+ const entries = fs11.readdirSync(dir, { withFileTypes: true });
7226
7304
  for (const entry of entries) {
7227
- const full = path3.join(dir, entry.name);
7305
+ const full = path6.join(dir, entry.name);
7228
7306
  if (entry.isDirectory()) {
7229
7307
  if (entry.name === "node_modules" || entry.name === "dist" || entry.name === ".next") continue;
7230
7308
  files.push(...collectTsFiles(full, extensions));
7231
- } else if (extensions.has(path3.extname(entry.name))) {
7309
+ } else if (extensions.has(path6.extname(entry.name))) {
7232
7310
  files.push(full);
7233
7311
  }
7234
7312
  }
@@ -7305,7 +7383,7 @@ async function runBoundaryCli(args, context) {
7305
7383
  for (const file of files) {
7306
7384
  let source;
7307
7385
  try {
7308
- source = fs8.readFileSync(file, "utf8");
7386
+ source = fs11.readFileSync(file, "utf8");
7309
7387
  } catch {
7310
7388
  continue;
7311
7389
  }
@@ -7380,7 +7458,7 @@ function enumerateVariantProps(matrix) {
7380
7458
  }
7381
7459
  async function resolveScript(context, relativeToRepoRoot) {
7382
7460
  const fromRuntime = await resolveMonorepoPath(context.runtimeDir, relativeToRepoRoot);
7383
- const fromCwd = path3__default.default.resolve(process.cwd(), relativeToRepoRoot);
7461
+ const fromCwd = path6__namespace.default.resolve(process.cwd(), relativeToRepoRoot);
7384
7462
  const resolved = await firstExistingPath([fromRuntime, fromCwd]);
7385
7463
  if (!resolved) {
7386
7464
  throw new CliUsageError(`Required script not found: ${relativeToRepoRoot}`);
@@ -7394,13 +7472,13 @@ async function loadRegistry(context) {
7394
7472
  );
7395
7473
  const candidates = [
7396
7474
  runtimeRegistryPath,
7397
- path3__default.default.resolve(process.cwd(), "packages/domain/plugin-registry/registry.json")
7475
+ path6__namespace.default.resolve(process.cwd(), "packages/domain/plugin-registry/registry.json")
7398
7476
  ];
7399
7477
  const registryPath = await firstExistingPath(candidates);
7400
7478
  if (!registryPath) {
7401
7479
  throw new CliUsageError("Plugin registry file not found.");
7402
7480
  }
7403
- const raw = await fs4__default.default.readFile(registryPath, "utf8");
7481
+ const raw = await fs7__default.default.readFile(registryPath, "utf8");
7404
7482
  const data = JSON.parse(raw);
7405
7483
  return [
7406
7484
  ...data.official.map((item) => ({ ...item, official: true })),
@@ -7450,7 +7528,7 @@ init_json();
7450
7528
  var postJson = async (url, body, token) => {
7451
7529
  const { default: https } = await import('https');
7452
7530
  const { default: http } = await import('http');
7453
- return new Promise((resolve, reject) => {
7531
+ return new Promise((resolve2, reject) => {
7454
7532
  const client = url.protocol === "https:" ? https : http;
7455
7533
  const req = client.request(
7456
7534
  url,
@@ -7468,9 +7546,9 @@ var postJson = async (url, body, token) => {
7468
7546
  res.on("end", () => {
7469
7547
  const raw = Buffer.concat(chunks).toString("utf8");
7470
7548
  try {
7471
- resolve({ status: res.statusCode, body: JSON.parse(raw) });
7549
+ resolve2({ status: res.statusCode, body: JSON.parse(raw) });
7472
7550
  } catch {
7473
- resolve({ status: res.statusCode, body: raw });
7551
+ resolve2({ status: res.statusCode, body: raw });
7474
7552
  }
7475
7553
  });
7476
7554
  }
@@ -7499,7 +7577,7 @@ var deployCommand = {
7499
7577
  const version = typeof parsed.values.version === "string" ? parsed.values.version : "0.1.0";
7500
7578
  const tag = typeof parsed.values.tag === "string" ? parsed.values.tag : "latest";
7501
7579
  const registryUrl = typeof parsed.values.registry === "string" ? parsed.values.registry : process.env.TW_REGISTRY_URL ?? null;
7502
- const pkgPath = path3__default.default.join(process.cwd(), "package.json");
7580
+ const pkgPath = path6__namespace.default.join(process.cwd(), "package.json");
7503
7581
  if (!await pathExists2(pkgPath)) {
7504
7582
  throw new CliUsageError("[tw deploy] No package.json found in current directory");
7505
7583
  }
@@ -7534,10 +7612,10 @@ var deployCommand = {
7534
7612
  }
7535
7613
  return;
7536
7614
  }
7537
- const cacheDir = path3__default.default.join(process.cwd(), ".tw-cache");
7538
- await fs4__default.default.mkdir(cacheDir, { recursive: true });
7539
- await fs4__default.default.writeFile(
7540
- path3__default.default.join(cacheDir, "deploy-manifest.json"),
7615
+ const cacheDir = path6__namespace.default.join(process.cwd(), ".tw-cache");
7616
+ await fs7__default.default.mkdir(cacheDir, { recursive: true });
7617
+ await fs7__default.default.writeFile(
7618
+ path6__namespace.default.join(cacheDir, "deploy-manifest.json"),
7541
7619
  JSON.stringify(manifest, null, 2)
7542
7620
  );
7543
7621
  if (!registryUrl) {
@@ -7637,24 +7715,24 @@ function addIssue(issues, severity, type, message, suggestion, location) {
7637
7715
  issues.push({ severity, type, message, suggestion, location });
7638
7716
  }
7639
7717
  function readJsonFile(filePath) {
7640
- if (!fs8__default.default.existsSync(filePath)) return null;
7718
+ if (!fs11__namespace.default.existsSync(filePath)) return null;
7641
7719
  try {
7642
- return JSON.parse(fs8__default.default.readFileSync(filePath, "utf8"));
7720
+ return JSON.parse(fs11__namespace.default.readFileSync(filePath, "utf8"));
7643
7721
  } catch {
7644
7722
  return null;
7645
7723
  }
7646
7724
  }
7647
7725
  function findWorkspacePackageJsonFiles(root) {
7648
- const packagesDir = path3__default.default.join(root, "packages");
7649
- if (!fs8__default.default.existsSync(packagesDir)) return [];
7650
- return fs8__default.default.readdirSync(packagesDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => path3__default.default.join(packagesDir, entry.name, "package.json")).filter((filePath) => fs8__default.default.existsSync(filePath));
7726
+ const packagesDir = path6__namespace.default.join(root, "packages");
7727
+ if (!fs11__namespace.default.existsSync(packagesDir)) return [];
7728
+ return fs11__namespace.default.readdirSync(packagesDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => path6__namespace.default.join(packagesDir, entry.name, "package.json")).filter((filePath) => fs11__namespace.default.existsSync(filePath));
7651
7729
  }
7652
7730
  function findFiles(dir, ext) {
7653
7731
  const files = [];
7654
7732
  try {
7655
- const entries = fs8__default.default.readdirSync(dir, { withFileTypes: true });
7733
+ const entries = fs11__namespace.default.readdirSync(dir, { withFileTypes: true });
7656
7734
  for (const entry of entries) {
7657
- const fullPath = path3__default.default.join(dir, entry.name);
7735
+ const fullPath = path6__namespace.default.join(dir, entry.name);
7658
7736
  if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules") {
7659
7737
  files.push(...findFiles(fullPath, ext));
7660
7738
  } else if (entry.isFile() && entry.name.endsWith(ext)) {
@@ -7667,7 +7745,7 @@ function findFiles(dir, ext) {
7667
7745
  return files;
7668
7746
  }
7669
7747
  function runWorkspaceDiagnostics(root, issues, checks) {
7670
- const rootPackageJsonPath = path3__default.default.join(root, "package.json");
7748
+ const rootPackageJsonPath = path6__namespace.default.join(root, "package.json");
7671
7749
  const rootPackageJson = readJsonFile(rootPackageJsonPath);
7672
7750
  if (!rootPackageJson) {
7673
7751
  addCheck(
@@ -7720,7 +7798,7 @@ function runWorkspaceDiagnostics(root, issues, checks) {
7720
7798
  const scripts = typeof manifest.scripts === "object" && manifest.scripts !== null ? manifest.scripts : {};
7721
7799
  const missing = requiredScripts.filter((name) => typeof scripts[name] !== "string");
7722
7800
  if (missing.length === 0) return [];
7723
- const packageName = typeof manifest.name === "string" && manifest.name.length > 0 ? manifest.name : path3__default.default.basename(path3__default.default.dirname(filePath));
7801
+ const packageName = typeof manifest.name === "string" && manifest.name.length > 0 ? manifest.name : path6__namespace.default.basename(path6__namespace.default.dirname(filePath));
7724
7802
  return [{ packageName, missing }];
7725
7803
  });
7726
7804
  if (missingScripts.length === 0) {
@@ -7755,7 +7833,7 @@ function runWorkspaceDiagnostics(root, issues, checks) {
7755
7833
  );
7756
7834
  }
7757
7835
  function runTailwindProjectDiagnostics(root, issues, checks) {
7758
- const packageJsonPath = path3__default.default.join(root, "package.json");
7836
+ const packageJsonPath = path6__namespace.default.join(root, "package.json");
7759
7837
  const packageJson = readJsonFile(packageJsonPath);
7760
7838
  if (!packageJson) {
7761
7839
  addCheck(
@@ -7814,7 +7892,7 @@ function runTailwindProjectDiagnostics(root, issues, checks) {
7814
7892
  const cssFiles = findFiles(root, ".css");
7815
7893
  const hasTailwindImport = cssFiles.slice(0, 10).some((filePath) => {
7816
7894
  try {
7817
- const content = fs8__default.default.readFileSync(filePath, "utf8");
7895
+ const content = fs11__namespace.default.readFileSync(filePath, "utf8");
7818
7896
  return content.includes("@tailwind") || content.includes('@import "tailwindcss"');
7819
7897
  } catch {
7820
7898
  return false;
@@ -7838,7 +7916,7 @@ function runTailwindProjectDiagnostics(root, issues, checks) {
7838
7916
  );
7839
7917
  }
7840
7918
  const configFiles = ["tailwind.config.js", "tailwind.config.ts", "tailwind.config.mjs"];
7841
- const hasConfig = configFiles.some((name) => fs8__default.default.existsSync(path3__default.default.join(root, name)));
7919
+ const hasConfig = configFiles.some((name) => fs11__namespace.default.existsSync(path6__namespace.default.join(root, name)));
7842
7920
  addCheck(
7843
7921
  checks,
7844
7922
  "tailwind",
@@ -7847,7 +7925,7 @@ function runTailwindProjectDiagnostics(root, issues, checks) {
7847
7925
  "info",
7848
7926
  hasConfig ? "Tailwind config file detected." : "No tailwind.config file found."
7849
7927
  );
7850
- const tsconfig = readJsonFile(path3__default.default.join(root, "tsconfig.json"));
7928
+ const tsconfig = readJsonFile(path6__namespace.default.join(root, "tsconfig.json"));
7851
7929
  const jsx = tsconfig?.compilerOptions?.jsx;
7852
7930
  addCheck(
7853
7931
  checks,
@@ -8013,7 +8091,7 @@ async function runAnalysisDiagnostics(root, issues, checks, verbose) {
8013
8091
  }
8014
8092
  }
8015
8093
  var runDiagnostics = async (options = {}) => {
8016
- const root = path3__default.default.resolve(options.root ?? process.cwd());
8094
+ const root = path6__namespace.default.resolve(options.root ?? process.cwd());
8017
8095
  const includes = parseIncludes(options.include);
8018
8096
  const issues = [];
8019
8097
  const checks = [];
@@ -8163,7 +8241,7 @@ var shareCommand = {
8163
8241
  name: "share",
8164
8242
  async run(args, context) {
8165
8243
  const name = args.find((arg) => !arg.startsWith("-")) ?? "component-name";
8166
- const manifestPath = path3__default.default.join(process.cwd(), ".tw-cache", "deploy-manifest.json");
8244
+ const manifestPath = path6__namespace.default.join(process.cwd(), ".tw-cache", "deploy-manifest.json");
8167
8245
  const defaultManifest = {
8168
8246
  name,
8169
8247
  version: "0.1.0"
@@ -8249,14 +8327,14 @@ var isVersionOutdated = (currentVersion, latestVersion) => {
8249
8327
  };
8250
8328
  var resolveCurrentCliVersion = async (context) => {
8251
8329
  const candidates = [
8252
- path3__default.default.resolve(context.runtimeDir, "..", "package.json"),
8253
- path3__default.default.resolve(process.cwd(), "packages", "cli", "package.json"),
8254
- path3__default.default.resolve(process.cwd(), "package.json")
8330
+ path6__namespace.default.resolve(context.runtimeDir, "..", "package.json"),
8331
+ path6__namespace.default.resolve(process.cwd(), "packages", "cli", "package.json"),
8332
+ path6__namespace.default.resolve(process.cwd(), "package.json")
8255
8333
  ];
8256
8334
  for (const candidate of candidates) {
8257
8335
  if (!await pathExists2(candidate)) continue;
8258
8336
  const pkg = await readJsonSafe(candidate);
8259
- const isCliPackage = pkg?.version && (pkg.name === CLI_PACKAGE_NAME || candidate.includes(`${path3__default.default.sep}packages${path3__default.default.sep}cli${path3__default.default.sep}`));
8337
+ const isCliPackage = pkg?.version && (pkg.name === CLI_PACKAGE_NAME || candidate.includes(`${path6__namespace.default.sep}packages${path6__namespace.default.sep}cli${path6__namespace.default.sep}`));
8260
8338
  if (isCliPackage) return pkg.version ?? "0.0.0";
8261
8339
  }
8262
8340
  return "0.0.0";
@@ -8529,7 +8607,7 @@ function resolveCliEntry(scriptPath) {
8529
8607
  async function hasTailwindCssImport(cwd2) {
8530
8608
  const cssFiles = ["src/app/globals.css", "src/index.css", "src/style.css", "app/globals.css"];
8531
8609
  for (const file of cssFiles) {
8532
- const raw = await readFileSafe(path3__default.default.join(cwd2, file));
8610
+ const raw = await readFileSafe(path6__namespace.default.join(cwd2, file));
8533
8611
  if (raw?.includes("tailwindcss")) return true;
8534
8612
  }
8535
8613
  return false;
@@ -8545,7 +8623,7 @@ async function hasSafelistSource(cwd2) {
8545
8623
  "app/globals.css"
8546
8624
  ];
8547
8625
  for (const file of cssFiles) {
8548
- const raw = await readFileSafe(path3__default.default.join(cwd2, file));
8626
+ const raw = await readFileSafe(path6__namespace.default.join(cwd2, file));
8549
8627
  if (raw === null) continue;
8550
8628
  if (raw.includes("tw-classes")) return { found: true, cssFile: file };
8551
8629
  if (raw.includes("tailwindcss")) return { found: false, cssFile: file };
@@ -8553,8 +8631,8 @@ async function hasSafelistSource(cwd2) {
8553
8631
  return { found: false, cssFile: null };
8554
8632
  }
8555
8633
  async function applyTailwindInit(cwd2) {
8556
- await ensureFileSafe(path3__default.default.join(cwd2, "src", "tailwind.css"), DEFAULT_TAILWIND_CSS2);
8557
- await ensureFileSafe(path3__default.default.join(cwd2, "tailwind-styled.config.json"), DEFAULT_TW_CONFIG);
8634
+ await ensureFileSafe(path6__namespace.default.join(cwd2, "src", "tailwind.css"), DEFAULT_TAILWIND_CSS2);
8635
+ await ensureFileSafe(path6__namespace.default.join(cwd2, "tailwind-styled.config.json"), DEFAULT_TW_CONFIG);
8558
8636
  }
8559
8637
  function check(results, id, label, pass, message, fix) {
8560
8638
  results.push({ id, label, pass, message, fix });
@@ -8576,7 +8654,7 @@ async function runPreflightCli(rawArgs) {
8576
8654
  node.major >= 20 ? `Node ${node.full} OK` : `Node ${node.full} - requires >=20. Download: https://nodejs.org`,
8577
8655
  node.major < 20 ? "Install Node.js 20 LTS or newer from https://nodejs.org" : void 0
8578
8656
  );
8579
- const pkg = await readJsonSafe(path3__default.default.join(cwd2, "package.json"));
8657
+ const pkg = await readJsonSafe(path6__namespace.default.join(cwd2, "package.json"));
8580
8658
  check(
8581
8659
  results,
8582
8660
  "package-json",
@@ -8607,19 +8685,10 @@ async function runPreflightCli(rawArgs) {
8607
8685
  hasBundler ? `${bundlerName} detected OK` : "No supported bundler (Vite/Next.js/Rspack) found",
8608
8686
  "Install a bundler: npm install vite @vitejs/plugin-react OR npx create-next-app"
8609
8687
  );
8610
- const hasMerge = pkgHasDep(pkg, "tailwind-merge");
8611
- check(
8612
- results,
8613
- "tailwind-merge",
8614
- "tailwind-merge installed",
8615
- hasMerge,
8616
- hasMerge ? "tailwind-merge found OK" : "Missing peer dep - run: npm install tailwind-merge",
8617
- "npm install tailwind-merge"
8618
- );
8619
8688
  }
8620
8689
  const twConfigFiles = ["tailwind.config.ts", "tailwind.config.js", "tailwind.config.mjs"];
8621
8690
  const twConfigChecks = await Promise.all(
8622
- twConfigFiles.map(async (file) => ({ file, exists: await pathExists2(path3__default.default.join(cwd2, file)) }))
8691
+ twConfigFiles.map(async (file) => ({ file, exists: await pathExists2(path6__namespace.default.join(cwd2, file)) }))
8623
8692
  );
8624
8693
  const foundTwConfig = twConfigChecks.find((item) => item.exists)?.file ?? null;
8625
8694
  const hasCssConfig = await hasTailwindCssImport(cwd2);
@@ -8631,7 +8700,7 @@ async function runPreflightCli(rawArgs) {
8631
8700
  foundTwConfig ? `${foundTwConfig} found OK` : hasCssConfig ? "@import tailwindcss found in CSS OK" : "No Tailwind config found - run: tw init",
8632
8701
  "tw init"
8633
8702
  );
8634
- const oldConfig = await readJsonSafe(path3__default.default.join(cwd2, "tailwind.config.js")) ?? await readJsonSafe(path3__default.default.join(cwd2, "tailwind.config.ts"));
8703
+ const oldConfig = await readJsonSafe(path6__namespace.default.join(cwd2, "tailwind.config.js")) ?? await readJsonSafe(path6__namespace.default.join(cwd2, "tailwind.config.ts"));
8635
8704
  if (oldConfig) {
8636
8705
  const hasOldJit = oldConfig.mode === "jit";
8637
8706
  const hasOldPurge = "purge" in oldConfig;
@@ -8645,7 +8714,7 @@ async function runPreflightCli(rawArgs) {
8645
8714
  "Run: tw migrate --dry-run to see migration steps"
8646
8715
  );
8647
8716
  }
8648
- const hasTsConfig = await pathExists2(path3__default.default.join(cwd2, "tsconfig.json"));
8717
+ const hasTsConfig = await pathExists2(path6__namespace.default.join(cwd2, "tsconfig.json"));
8649
8718
  check(
8650
8719
  results,
8651
8720
  "typescript",
@@ -9039,7 +9108,7 @@ var storybookCommand = {
9039
9108
  context.output.writeText(
9040
9109
  `[tw storybook] Tip: use --variants='{"size":["sm","lg"]}' to enumerate variant combinations`
9041
9110
  );
9042
- const localBin = path3__default.default.join(
9111
+ const localBin = path6__namespace.default.join(
9043
9112
  process.cwd(),
9044
9113
  "node_modules",
9045
9114
  ".bin",
@@ -9236,418 +9305,269 @@ function getNativeEngineBinding() {
9236
9305
  // packages/domain/engine/src/bundleAnalyzer.ts
9237
9306
  var BundleAnalyzer = class {
9238
9307
  analyzeClass(className, scanResult, css) {
9239
- if (!className || className.trim() === "") {
9240
- throw new Error("Class name cannot be empty");
9241
- }
9242
- if (!scanResult) {
9243
- throw new Error("Scan result is required for analysis");
9308
+ if (!className || className.trim() === "") throw new Error("Class name cannot be empty");
9309
+ if (!scanResult) throw new Error("Scan result is required for analysis");
9310
+ if (typeof css !== "string") throw new Error("CSS string is required for analysis");
9311
+ const normalizedClass = className.startsWith(".") ? className.slice(1) : className;
9312
+ const native = getNativeEngineBinding();
9313
+ if (!native.analyzeClassUsage) {
9314
+ throw new Error("FATAL: Native binding 'analyzeClassUsage' is required but not available.");
9244
9315
  }
9245
- if (typeof css !== "string") {
9246
- throw new Error("CSS string is required for analysis");
9316
+ if (!native.buildDependencyChain) {
9317
+ throw new Error("FATAL: Native binding 'buildDependencyChain' is required but not available.");
9247
9318
  }
9248
- const normalizedClass = className.startsWith(".") ? className.slice(1) : className;
9249
- const usageCount = this.countClassUsage(normalizedClass, scanResult);
9250
- const files = this.getFilesUsingClass(normalizedClass, scanResult);
9251
- const bundleSize = this.calculateBundleContribution(normalizedClass, css);
9252
- const variantChains = this.extractVariantChains(normalizedClass, css);
9253
- const dependencies = this.extractDependencies(normalizedClass, css);
9254
- const isDeadCode = this.checkIsDeadCode(normalizedClass, scanResult, css);
9319
+ const results = native.analyzeClassUsage(
9320
+ [normalizedClass],
9321
+ JSON.stringify(scanResult),
9322
+ css
9323
+ );
9324
+ const info = results[0];
9325
+ const files = info ? JSON.parse(info.filesJson).map((f) => ({ file: f, line: 1, column: 1 })) : [];
9326
+ const dependencies = native.buildDependencyChain(normalizedClass);
9255
9327
  return {
9256
9328
  className: normalizedClass,
9257
- totalUsage: usageCount,
9329
+ totalUsage: info?.usageCount ?? 0,
9258
9330
  files,
9259
- bundleSizeBytes: bundleSize,
9260
- variantChains,
9261
- isDeadCode,
9331
+ bundleSizeBytes: info?.bundleSizeBytes ?? 0,
9332
+ variantChains: [],
9333
+ isDeadCode: info?.isDeadCode ?? true,
9262
9334
  dependencies
9263
9335
  };
9264
9336
  }
9265
9337
  analyzeAll(scanResult, css) {
9266
- if (!scanResult) {
9267
- throw new Error("Scan result is required for analysis");
9268
- }
9269
- if (typeof css !== "string") {
9270
- throw new Error("CSS string is required for analysis");
9271
- }
9272
- const results = /* @__PURE__ */ new Map();
9273
- const allClasses = new Set(scanResult.uniqueClasses);
9274
- const cssClasses = this.extractClassesFromCss(css);
9275
- for (const cssClass of cssClasses) {
9276
- allClasses.add(cssClass);
9277
- }
9278
- for (const className of allClasses) {
9279
- try {
9280
- const result = this.analyzeClass(className, scanResult, css);
9281
- results.set(className, result);
9282
- } catch (error) {
9283
- console.warn(`Failed to analyze class "${className}":`, error);
9284
- }
9338
+ if (!scanResult) throw new Error("Scan result is required for analysis");
9339
+ if (typeof css !== "string") throw new Error("CSS string is required for analysis");
9340
+ const native = getNativeEngineBinding();
9341
+ if (!native.analyzeClassUsage) {
9342
+ throw new Error("FATAL: Native binding 'analyzeClassUsage' is required but not available.");
9343
+ }
9344
+ if (!native.buildDependencyChain) {
9345
+ throw new Error("FATAL: Native binding 'buildDependencyChain' is required but not available.");
9346
+ }
9347
+ const allClasses = Array.from(/* @__PURE__ */ new Set([
9348
+ ...scanResult.uniqueClasses,
9349
+ ...native.extractAllClasses ? native.extractAllClasses(css) : []
9350
+ ]));
9351
+ const results = native.analyzeClassUsage(
9352
+ allClasses,
9353
+ JSON.stringify(scanResult),
9354
+ css
9355
+ );
9356
+ const map = /* @__PURE__ */ new Map();
9357
+ for (const info of results) {
9358
+ const files = JSON.parse(info.filesJson).map((f) => ({
9359
+ file: f,
9360
+ line: 1,
9361
+ column: 1
9362
+ }));
9363
+ const dependencies = native.buildDependencyChain ? native.buildDependencyChain(info.className) : [];
9364
+ map.set(info.className, {
9365
+ className: info.className,
9366
+ totalUsage: info.usageCount,
9367
+ files,
9368
+ bundleSizeBytes: info.bundleSizeBytes,
9369
+ variantChains: [],
9370
+ isDeadCode: info.isDeadCode,
9371
+ dependencies
9372
+ });
9285
9373
  }
9286
- return results;
9374
+ return map;
9287
9375
  }
9288
9376
  calculateBundleContribution(className, css) {
9289
9377
  if (!className || className.trim() === "") throw new Error("Class name cannot be empty");
9290
9378
  if (typeof css !== "string") throw new Error("CSS string is required");
9291
- try {
9292
- const native = (() => {
9293
- try {
9294
- return getNativeEngineBinding();
9295
- } catch {
9296
- return null;
9297
- }
9298
- })();
9299
- if (native?.calculateBundleContributionsNative) {
9300
- const r = native.calculateBundleContributionsNative([className], css);
9301
- return r?.[0]?.sizeBytes ?? 0;
9302
- }
9303
- } catch (err) {
9379
+ const native = getNativeEngineBinding();
9380
+ if (!native.calculateBundleContributions) {
9381
+ throw new Error("FATAL: Native binding 'calculateBundleContributions' is required but not available.");
9304
9382
  }
9305
- const normalizedClass = className.startsWith(".") ? className.slice(1) : className;
9306
- const escapedClass = normalizedClass.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9307
- const selectorPattern = new RegExp(`\\.${escapedClass}([\\s:{]|$)`, "g");
9308
- if (!css.match(selectorPattern)) return 0;
9309
- const classSelector = `.${normalizedClass}`;
9310
- return css.split("\n").filter((l) => l.includes(classSelector)).reduce((sum, l) => {
9311
- const s = l.indexOf("{");
9312
- return s !== -1 ? sum + l.substring(s).length + 1 : sum;
9313
- }, 0);
9383
+ const r = native.calculateBundleContributions([className], css);
9384
+ return r?.[0]?.sizeBytes ?? 0;
9314
9385
  }
9315
9386
  detectDeadCode(scanResult, css) {
9316
9387
  if (!scanResult) throw new Error("Scan result is required for dead code detection");
9317
9388
  if (typeof css !== "string") throw new Error("CSS string is required for dead code detection");
9318
- try {
9319
- const native = (() => {
9320
- try {
9321
- return getNativeEngineBinding();
9322
- } catch {
9323
- return null;
9324
- }
9325
- })();
9326
- if (native?.detectDeadCodeNative) {
9327
- const r = native.detectDeadCodeNative(JSON.stringify(scanResult), css);
9328
- return r?.deadInCss ?? [];
9329
- }
9330
- } catch (err) {
9331
- }
9332
- const cssClasses = this.extractClassesFromCss(css);
9333
- const usedClasses = new Set(scanResult.uniqueClasses);
9334
- return cssClasses.filter((c) => !usedClasses.has(c));
9335
- }
9336
- countClassUsage(className, scanResult) {
9337
- const normalizedClass = className.startsWith(".") ? className.slice(1) : className;
9338
- const count = scanResult.files.reduce((sum, file) => {
9339
- return sum + file.classes.filter((fileClass) => {
9340
- const normalizedFileClass = fileClass.startsWith(".") ? fileClass.slice(1) : fileClass;
9341
- return normalizedFileClass === normalizedClass;
9342
- }).length;
9343
- }, 0);
9344
- return count;
9345
- }
9346
- getFilesUsingClass(className, scanResult) {
9347
- const files = [];
9348
- const normalizedClass = className.startsWith(".") ? className.slice(1) : className;
9349
- for (const file of scanResult.files) {
9350
- for (const fileClass of file.classes) {
9351
- const normalizedFileClass = fileClass.startsWith(".") ? fileClass.slice(1) : fileClass;
9352
- if (normalizedFileClass === normalizedClass) {
9353
- files.push({
9354
- file: file.file,
9355
- line: 1,
9356
- column: 1
9357
- });
9358
- break;
9359
- }
9360
- }
9361
- }
9362
- return files;
9363
- }
9364
- extractVariantChains(className, css) {
9365
- const normalizedClass = className.startsWith(".") ? className.slice(1) : className;
9366
- const variantChains = [];
9367
- const escapedClass = normalizedClass.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9368
- const variantPattern = new RegExp(`([\\w-]+:${escapedClass}|${escapedClass})`, "g");
9369
- const lines = css.split("\n");
9370
- for (const line of lines) {
9371
- const matches = line.match(variantPattern);
9372
- if (matches) {
9373
- for (const match of matches) {
9374
- if (match.includes(":")) {
9375
- variantChains.push(match);
9376
- }
9377
- }
9378
- }
9379
- }
9380
- return [...new Set(variantChains)];
9381
- }
9382
- extractDependencies(className, _css) {
9383
- const normalizedClass = className.startsWith(".") ? className.slice(1) : className;
9384
- const parts = normalizedClass.split(":");
9385
- const dependencies = parts.slice(0, -1).map((_, i) => parts.slice(0, i + 1).join(":"));
9386
- return dependencies;
9387
- }
9388
- checkIsDeadCode(className, scanResult, css) {
9389
- const normalizedClass = className.startsWith(".") ? className.slice(1) : className;
9390
- const cssClasses = this.extractClassesFromCss(css);
9391
- if (!cssClasses.includes(normalizedClass)) {
9392
- return true;
9393
- }
9394
- const usageCount = this.countClassUsage(normalizedClass, scanResult);
9395
- return usageCount === 0;
9396
- }
9397
- extractClassesFromCss(css) {
9398
- const classes = [];
9399
- const classPattern = /\.([a-zA-Z0-9_-]+(?::[a-zA-Z0-9_-]+)*)/g;
9400
- for (const match of css.matchAll(classPattern)) {
9401
- const className = match[1];
9402
- if (!classes.includes(className)) {
9403
- classes.push(className);
9404
- }
9389
+ const native = getNativeEngineBinding();
9390
+ if (!native.detectDeadCode) {
9391
+ throw new Error("FATAL: Native binding 'detectDeadCode' is required but not available.");
9405
9392
  }
9406
- return classes;
9393
+ const r = native.detectDeadCode(JSON.stringify(scanResult), css);
9394
+ return r?.deadInCss ?? [];
9407
9395
  }
9408
9396
  };
9409
9397
 
9410
9398
  // packages/domain/engine/src/impactTracker.ts
9411
9399
  var ImpactTracker = class {
9412
9400
  bundleAnalyzer;
9413
- criticalPatterns = [
9414
- "fixed",
9415
- "absolute",
9416
- "sticky",
9417
- "z-50",
9418
- "z-index",
9419
- "top-0",
9420
- "right-0",
9421
- "bottom-0",
9422
- "left-0",
9423
- "w-full",
9424
- "h-full",
9425
- "min-h-screen",
9426
- "flex",
9427
- "grid",
9428
- "block",
9429
- "inline",
9430
- "hidden",
9431
- "visible",
9432
- "opacity",
9433
- "pointer-events",
9434
- "cursor"
9435
- ];
9436
9401
  constructor() {
9437
9402
  this.bundleAnalyzer = new BundleAnalyzer();
9438
9403
  }
9439
- /**
9440
- * Analisis impact sebuah class menggunakan BundleAnalyzer untuk dapat
9441
- * data akurat tentang bundle size contribution.
9442
- *
9443
- * @param className - Tailwind class yang ingin dianalisis
9444
- * @param scanResult - Hasil scan workspace
9445
- * @param css - CSS string dari build output (opsional — jika tidak ada, gunakan estimasi)
9446
- */
9447
9404
  analyzeWithBundle(className, scanResult, css = "") {
9448
9405
  const normalizedClass = className.startsWith(".") ? className.slice(1) : className;
9449
- let bundleAnalysis = null;
9450
- try {
9451
- if (scanResult && css) {
9452
- bundleAnalysis = this.bundleAnalyzer.analyzeClass(normalizedClass, scanResult, css);
9453
- }
9454
- } catch {
9455
- }
9456
- const resolvedBundleAnalysis = bundleAnalysis ?? (() => {
9457
- const usedIn = (scanResult?.files ?? []).filter(
9458
- (f) => f.classes?.includes(normalizedClass)
9459
- );
9460
- return {
9461
- className: normalizedClass,
9462
- totalUsage: usedIn.length,
9463
- files: usedIn.map((f) => ({
9464
- file: f.file,
9465
- line: 1,
9466
- column: 1
9467
- })),
9468
- bundleSizeBytes: 0,
9469
- variantChains: [],
9470
- isDeadCode: usedIn.length === 0,
9471
- dependencies: []
9472
- };
9473
- })();
9474
- return this.calculateImpact(normalizedClass, resolvedBundleAnalysis, scanResult);
9406
+ const native = getNativeEngineBinding();
9407
+ if (!native?.calculateImpactScores) {
9408
+ throw new Error("FATAL: Native binding 'calculateImpactScores' is required but not available.");
9409
+ }
9410
+ const scores = native.calculateImpactScores(
9411
+ [normalizedClass],
9412
+ JSON.stringify(scanResult),
9413
+ css,
9414
+ 0.6,
9415
+ 0.4
9416
+ );
9417
+ const score = scores[0];
9418
+ const bundleAnalysis = {
9419
+ className: normalizedClass,
9420
+ totalUsage: score?.usageCount ?? 0,
9421
+ files: [],
9422
+ bundleSizeBytes: score?.sizeBytes ?? 0,
9423
+ variantChains: [],
9424
+ isDeadCode: (score?.usageCount ?? 0) === 0,
9425
+ dependencies: []
9426
+ };
9427
+ return this.calculateImpact(normalizedClass, bundleAnalysis, scanResult, score);
9475
9428
  }
9476
- /**
9477
- * Analisis semua class dalam workspace sekaligus.
9478
- */
9479
9429
  analyzeAll(scanResult, css = "") {
9480
- const results = /* @__PURE__ */ new Map();
9430
+ const native = getNativeEngineBinding();
9431
+ if (!native?.calculateImpactScores) {
9432
+ throw new Error("FATAL: Native binding 'calculateImpactScores' is required but not available.");
9433
+ }
9481
9434
  const classes = scanResult?.uniqueClasses ?? [];
9435
+ const scores = native.calculateImpactScores(
9436
+ classes,
9437
+ JSON.stringify(scanResult),
9438
+ css,
9439
+ 0.6,
9440
+ 0.4
9441
+ );
9442
+ const scoreMap = new Map(scores.map((s) => [s.className, s]));
9443
+ const results = /* @__PURE__ */ new Map();
9482
9444
  for (const cls of classes) {
9483
- try {
9484
- results.set(cls, this.analyzeWithBundle(cls, scanResult, css));
9485
- } catch {
9486
- }
9445
+ const score = scoreMap.get(cls);
9446
+ const bundleAnalysis = {
9447
+ className: cls,
9448
+ totalUsage: score?.usageCount ?? 0,
9449
+ files: [],
9450
+ bundleSizeBytes: score?.sizeBytes ?? 0,
9451
+ variantChains: [],
9452
+ isDeadCode: (score?.usageCount ?? 0) === 0,
9453
+ dependencies: []
9454
+ };
9455
+ results.set(cls, this.calculateImpact(cls, bundleAnalysis, scanResult, score));
9487
9456
  }
9488
9457
  return results;
9489
9458
  }
9490
- calculateImpact(className, bundleAnalysis, scanResult) {
9491
- if (!className || className.trim() === "") {
9492
- return this.createEmptyReport(className);
9493
- }
9494
- if (!bundleAnalysis) {
9495
- return this.createEmptyReport(className);
9496
- }
9459
+ calculateImpact(className, bundleAnalysis, scanResult, nativeScore) {
9460
+ if (!className || className.trim() === "") return this.createEmptyReport(className);
9461
+ if (!bundleAnalysis) return this.createEmptyReport(className);
9497
9462
  const normalizedClass = className.startsWith(".") ? className.slice(1) : className;
9498
- const affectedComponents = this.findAffectedComponents(normalizedClass, scanResult);
9499
- const directUsage = affectedComponents.filter((c) => c.usageType === "direct").length;
9500
- const indirectUsage = affectedComponents.filter((c) => c.usageType !== "direct").length;
9501
- const totalComponents = affectedComponents.length;
9463
+ const totalComponents = nativeScore?.usageCount ?? bundleAnalysis.totalUsage ?? 0;
9464
+ const directUsage = totalComponents;
9465
+ const indirectUsage = 0;
9502
9466
  const bundleSizeBytes = bundleAnalysis.bundleSizeBytes || 0;
9503
- const estimatedSavings = this.calculateSavings(bundleSizeBytes, totalComponents);
9504
- const impactReport = {
9505
- className: normalizedClass,
9506
- totalComponents,
9507
- directUsage,
9508
- indirectUsage,
9509
- bundleSizeBytes,
9510
- estimatedSavings,
9511
- riskLevel: "low",
9512
- suggestions: []
9513
- };
9514
- impactReport.riskLevel = this.calculateRisk(normalizedClass, impactReport);
9515
- impactReport.suggestions = this.generateSuggestions(normalizedClass, impactReport);
9516
- return impactReport;
9467
+ const native = getNativeEngineBinding();
9468
+ if (native?.computeImpactMetadata) {
9469
+ const impactJson = JSON.stringify({
9470
+ className: normalizedClass,
9471
+ totalComponents,
9472
+ indirectUsage,
9473
+ bundleSizeBytes
9474
+ });
9475
+ const result = JSON.parse(native.computeImpactMetadata(normalizedClass, impactJson));
9476
+ return {
9477
+ className: normalizedClass,
9478
+ totalComponents,
9479
+ directUsage,
9480
+ indirectUsage,
9481
+ bundleSizeBytes,
9482
+ estimatedSavings: result.estimatedSavings,
9483
+ riskLevel: result.riskLevel,
9484
+ suggestions: result.suggestions
9485
+ };
9486
+ }
9487
+ if (native?.calculateImpact) {
9488
+ const impactJson = JSON.stringify({
9489
+ className: normalizedClass,
9490
+ totalComponents,
9491
+ indirectUsage,
9492
+ bundleSizeBytes
9493
+ });
9494
+ const result = JSON.parse(native.calculateImpact(impactJson));
9495
+ return {
9496
+ className: normalizedClass,
9497
+ totalComponents,
9498
+ directUsage,
9499
+ indirectUsage,
9500
+ bundleSizeBytes,
9501
+ estimatedSavings: result.estimatedSavings,
9502
+ riskLevel: result.riskLevel,
9503
+ suggestions: result.suggestions
9504
+ };
9505
+ }
9506
+ throw new Error("FATAL: Native binding 'computeImpactMetadata' or 'calculateImpact' is required but not available.");
9517
9507
  }
9518
9508
  findAffectedComponents(className, scanResult) {
9519
- const components = [];
9520
- if (!className || className.trim() === "") {
9521
- return components;
9522
- }
9523
- if (!scanResult || !Array.isArray(scanResult.files)) {
9524
- return components;
9509
+ if (!className || !scanResult) return [];
9510
+ const native = getNativeEngineBinding();
9511
+ if (!native?.calculateImpactScores) {
9512
+ throw new Error("FATAL: Native binding 'calculateImpactScores' is required but not available.");
9525
9513
  }
9526
9514
  const normalizedClass = className.startsWith(".") ? className.slice(1) : className;
9527
- const classParts = normalizedClass.split(":");
9515
+ const scores = native.calculateImpactScores(
9516
+ [normalizedClass],
9517
+ JSON.stringify(scanResult),
9518
+ "",
9519
+ 1,
9520
+ 0
9521
+ );
9522
+ if (!scores[0]?.usageCount) return [];
9523
+ const components = [];
9528
9524
  for (const file of scanResult.files) {
9529
- if (!file || !file.file) continue;
9530
- const filePath = file.file;
9531
- const classes = file.classes || [];
9532
- const variants = file.variants || [];
9533
- for (const [i, fileClass] of classes.entries()) {
9534
- if (!fileClass) continue;
9535
- const normalizedFileClass = fileClass.startsWith(".") ? fileClass.slice(1) : fileClass;
9536
- if (normalizedFileClass === normalizedClass) {
9537
- components.push({
9538
- file: filePath,
9539
- line: file.lineNumbers?.[i] || 1,
9540
- column: file.columnNumbers?.[i] || 1,
9541
- usageType: "direct"
9542
- });
9543
- } else if (normalizedFileClass.includes(normalizedClass)) {
9544
- const variant = classParts.length > 1 ? classParts[0] : void 0;
9545
- components.push({
9546
- file: filePath,
9547
- line: file.lineNumbers?.[i] || 1,
9548
- column: file.columnNumbers?.[i] || 1,
9549
- usageType: "variant",
9550
- variant
9551
- });
9552
- }
9553
- }
9554
- for (const [i, variant] of variants.entries()) {
9555
- if (!variant) continue;
9556
- if (variant.includes(normalizedClass)) {
9557
- const baseClass = variant.split(":").pop();
9558
- if (baseClass === normalizedClass) {
9559
- components.push({
9560
- file: filePath,
9561
- line: file.lineNumbers?.[i] || 1,
9562
- column: file.columnNumbers?.[i] || 1,
9563
- usageType: "variant",
9564
- variant: variant.split(":")[0]
9565
- });
9566
- }
9567
- }
9568
- }
9525
+ if (!file.classes?.includes(normalizedClass)) continue;
9526
+ components.push({
9527
+ file: file.file,
9528
+ line: 1,
9529
+ column: 1,
9530
+ usageType: "direct"
9531
+ });
9569
9532
  }
9570
9533
  return components;
9571
9534
  }
9572
- calculateRisk(className, impact) {
9573
- if (!className || className.trim() === "") {
9574
- return "low";
9575
- }
9576
- if (!impact) {
9577
- return "low";
9578
- }
9579
- const normalizedClass = className.startsWith(".") ? className.slice(1) : className;
9580
- if (impact.totalComponents > 10) {
9581
- return "high";
9582
- }
9583
- if (this.isCriticalClass(normalizedClass)) {
9584
- return "high";
9585
- }
9586
- if (impact.totalComponents >= 5 && impact.totalComponents <= 10) {
9587
- return "medium";
9535
+ /**
9536
+ * Cek apakah sebuah class dianggap "critical" (tidak boleh dihapus).
9537
+ *
9538
+ * Native: Rust `is_critical_class()` — O(n) pattern match di CRITICAL_PATTERNS.
9539
+ * Lebih cepat dari regex JS untuk daftar panjang karena no backtracking.
9540
+ *
9541
+ * @example
9542
+ * tracker.isCriticalClass("sr-only") // true
9543
+ * tracker.isCriticalClass("hidden") // true
9544
+ * tracker.isCriticalClass("bg-red-500") // false
9545
+ */
9546
+ isCriticalClass(className) {
9547
+ const native = getNativeEngineBinding();
9548
+ if (native?.isCriticalClass) {
9549
+ return native.isCriticalClass(className);
9588
9550
  }
9589
- return "low";
9551
+ return false;
9590
9552
  }
9591
- generateSuggestions(className, impact) {
9592
- const suggestions = [];
9593
- if (!className || className.trim() === "") {
9594
- return suggestions;
9595
- }
9596
- if (!impact) {
9597
- return suggestions;
9598
- }
9599
- const normalizedClass = className.startsWith(".") ? className.slice(1) : className;
9600
- if (impact.riskLevel === "high") {
9601
- if (impact.totalComponents > 10) {
9602
- suggestions.push(
9603
- `This class is used in ${impact.totalComponents} components. Consider creating a utility component instead.`
9604
- );
9605
- }
9606
- if (this.isCriticalClass(normalizedClass)) {
9607
- suggestions.push(
9608
- "This is a critical positioning/display class. Review all usages before removal."
9609
- );
9610
- }
9611
- suggestions.push("Manual code review recommended before removing this class.");
9612
- } else if (impact.riskLevel === "medium") {
9613
- suggestions.push(
9614
- `This class is used in ${impact.totalComponents} components. Test each component after removal.`
9615
- );
9616
- if (impact.indirectUsage > 0) {
9617
- suggestions.push("Check for indirect usages via variants before removing.");
9618
- }
9619
- } else {
9620
- if (impact.totalComponents > 0) {
9621
- suggestions.push("Low risk: class is used in fewer than 5 components.");
9622
- } else {
9623
- suggestions.push("This class appears to be unused. Consider removing it.");
9624
- }
9625
- }
9626
- if (impact.estimatedSavings > 0) {
9627
- suggestions.push(`Estimated bundle size savings: ~${impact.estimatedSavings} bytes.`);
9628
- }
9629
- if (impact.bundleSizeBytes > 100) {
9630
- suggestions.push(
9631
- "This class has significant CSS bundle contribution. Removal will improve load times."
9632
- );
9553
+ /**
9554
+ * Generate human-readable suggestions berdasarkan impact analysis.
9555
+ *
9556
+ * Native: `generate_suggestions()` di Rust — pattern matching di CRITICAL_PATTERNS
9557
+ * + threshold-based risk categories.
9558
+ *
9559
+ * Biasanya dipanggil setelah `calculateImpact` yang sudah set riskLevel.
9560
+ */
9561
+ generateSuggestions(className, report) {
9562
+ const native = getNativeEngineBinding();
9563
+ if (native?.generateSuggestions) {
9564
+ return native.generateSuggestions(className, JSON.stringify(report));
9633
9565
  }
9634
- return suggestions;
9635
- }
9636
- isCriticalClass(className) {
9637
- const normalized = className.startsWith(".") ? className.slice(1) : className;
9638
- return this.criticalPatterns.some(
9639
- (pattern) => normalized === pattern || normalized.startsWith(`${pattern}:`)
9640
- );
9641
- }
9642
- calculateSavings(bundleSize, componentCount) {
9643
- const baseSavings = bundleSize;
9644
- const componentOverhead = componentCount * 50;
9645
- return Math.max(0, baseSavings - componentOverhead);
9566
+ return [];
9646
9567
  }
9647
9568
  createEmptyReport(className) {
9648
- const normalizedClass = className?.startsWith(".") ? className.slice(1) : className || "";
9649
9569
  return {
9650
- className: normalizedClass,
9570
+ className: className?.startsWith(".") ? className.slice(1) : className || "",
9651
9571
  totalComponents: 0,
9652
9572
  directUsage: 0,
9653
9573
  indirectUsage: 0,
@@ -9669,6 +9589,15 @@ var RuleId = class {
9669
9589
  return `R${this.value}`;
9670
9590
  }
9671
9591
  };
9592
+ var SelectorId = class {
9593
+ constructor(value) {
9594
+ this.value = value;
9595
+ }
9596
+ value;
9597
+ toString() {
9598
+ return `S${this.value}`;
9599
+ }
9600
+ };
9672
9601
  var VariantChainId = class {
9673
9602
  constructor(value) {
9674
9603
  this.value = value;
@@ -9726,322 +9655,308 @@ var ConditionId = class {
9726
9655
  return `C${this.value}`;
9727
9656
  }
9728
9657
  };
9729
- var propertyNames = /* @__PURE__ */ new Map();
9730
- var valueNames = /* @__PURE__ */ new Map();
9658
+ var CascadeResolutionId = class {
9659
+ constructor(value) {
9660
+ this.value = value;
9661
+ }
9662
+ value;
9663
+ toString() {
9664
+ return `R${this.value}`;
9665
+ }
9666
+ };
9667
+ var _propertyNamesFallback = /* @__PURE__ */ new Map();
9668
+ var _valueNamesFallback = /* @__PURE__ */ new Map();
9669
+ function registerPropertyName(id, name) {
9670
+ const native = getNativeEngineBinding();
9671
+ if (native?.registerPropertyName) {
9672
+ native.registerPropertyName(id.value, name);
9673
+ return;
9674
+ }
9675
+ _propertyNamesFallback.set(id.value, name);
9676
+ }
9677
+ function registerValueName(id, name) {
9678
+ const native = getNativeEngineBinding();
9679
+ if (native?.registerValueName) {
9680
+ native.registerValueName(id.value, name);
9681
+ return;
9682
+ }
9683
+ _valueNamesFallback.set(id.value, name);
9684
+ }
9731
9685
  function propertyIdToString(id) {
9732
- return propertyNames.get(id.value) ?? `P${id.value}`;
9686
+ const native = getNativeEngineBinding();
9687
+ if (native?.propertyIdToString) {
9688
+ return native.propertyIdToString(id.value);
9689
+ }
9690
+ return _propertyNamesFallback.get(id.value) ?? `P${id.value}`;
9733
9691
  }
9734
9692
  function valueIdToString(id) {
9735
- return valueNames.get(id.value) ?? `V${id.value}`;
9736
- }
9737
- function createFingerprint(parts) {
9693
+ const native = getNativeEngineBinding();
9694
+ if (native?.valueIdToString) {
9695
+ return native.valueIdToString(id.value);
9696
+ }
9697
+ return _valueNamesFallback.get(id.value) ?? `V${id.value}`;
9698
+ }
9699
+ var CascadeStage = /* @__PURE__ */ ((CascadeStage2) => {
9700
+ CascadeStage2[CascadeStage2["Origin"] = 0] = "Origin";
9701
+ CascadeStage2[CascadeStage2["Layer"] = 1] = "Layer";
9702
+ CascadeStage2[CascadeStage2["Importance"] = 2] = "Importance";
9703
+ CascadeStage2[CascadeStage2["Specificity"] = 3] = "Specificity";
9704
+ CascadeStage2[CascadeStage2["Order"] = 4] = "Order";
9705
+ return CascadeStage2;
9706
+ })(CascadeStage || {});
9707
+ function createFingerprintFallback(parts) {
9738
9708
  const hash = parts.reduce(
9739
9709
  (acc, part) => part.split("").reduce((h, char) => (h << 5) - h + char.charCodeAt(0) & h, acc),
9740
9710
  0
9741
9711
  );
9742
9712
  return Math.abs(hash).toString(36);
9743
9713
  }
9714
+ function createFingerprint(parts) {
9715
+ const native = getNativeEngineBinding();
9716
+ if (native?.createFingerprint) {
9717
+ return native.createFingerprint(parts);
9718
+ }
9719
+ return createFingerprintFallback(parts);
9720
+ }
9744
9721
 
9745
9722
  // packages/domain/engine/src/reverseLookup.ts
9746
- var ReverseLookup = class _ReverseLookup {
9747
- parsedCache = /* @__PURE__ */ new Map();
9748
- static MAX_CACHE_SIZE = 1e3;
9749
- /** Jumlah karakter total yang disimpan di cache (approx) */
9750
- cacheSizeBytes = 0;
9751
- static MAX_CACHE_BYTES = 10 * 1024 * 1024;
9752
- // 10MB
9753
- parseCSS(css) {
9754
- const cached = this.parsedCache.get(css);
9755
- if (cached) {
9756
- return cached;
9757
- }
9758
- try {
9759
- const native = (() => {
9760
- try {
9761
- return getNativeEngineBinding();
9762
- } catch {
9763
- return null;
9764
- }
9765
- })();
9766
- if (native?.parseCssRulesNative) {
9767
- const raw = native.parseCssRulesNative(css);
9768
- const rules2 = (raw ?? []).map((r) => ({
9769
- className: r.className,
9770
- property: r.property,
9771
- value: r.value,
9772
- specificity: r.specificity,
9773
- source: { file: "", line: 0, column: 0 },
9774
- isImportant: r.isImportant,
9775
- variants: r.variants,
9776
- isOverride: false
9777
- }));
9778
- this.pruneCache();
9779
- this.parsedCache.set(css, rules2);
9780
- return rules2;
9781
- }
9782
- } catch {
9783
- }
9784
- const rules = [];
9785
- const classMap = /* @__PURE__ */ new Map();
9786
- const selectorRegex = /\.([a-zA-Z_][a-zA-Z0-9_-]*)/g;
9787
- const propertyRegex = /([a-zA-Z-]+)\s*:\s*([^;]+)/g;
9788
- const importantRegex = /!important\s*;?\s*$/;
9789
- const lines = css.split("\n");
9790
- const columnState = { offset: 0 };
9791
- for (const [i, line] of lines.entries()) {
9792
- const lineEnd = columnState.offset + line.length + 1;
9793
- for (const match of line.matchAll(selectorRegex)) {
9794
- const className = match[1];
9795
- const selectorStart = match.index;
9796
- const lineColumn = selectorStart + 1;
9797
- if (!classMap.has(className)) {
9798
- classMap.set(className, /* @__PURE__ */ new Map());
9799
- }
9800
- const braceMatch = css.indexOf("{", lineEnd - 1);
9801
- if (braceMatch !== -1) {
9802
- const closingBraceMatch = this.findClosingBrace(css, braceMatch);
9803
- const ruleContent = css.substring(braceMatch + 1, closingBraceMatch);
9804
- const variants = [];
9805
- const variantMatch = className.match(/^(.+?)(?::([a-zA-Z0-9_-]+))?$/);
9806
- if (variantMatch?.[2]) {
9807
- variants.push(variantMatch[2]);
9808
- }
9809
- const specificity = this.calculateSpecificity(className);
9810
- const source = {
9811
- file: "inline",
9812
- line: i + 1,
9813
- column: lineColumn
9814
- };
9815
- for (const propMatch of ruleContent.matchAll(propertyRegex)) {
9816
- const property = propMatch[1].trim();
9817
- const rawValue = propMatch[2].trim();
9818
- const isImportant = importantRegex.test(rawValue);
9819
- const value = isImportant ? rawValue.replace(importantRegex, "").trim() : rawValue;
9820
- const rule = {
9821
- className,
9822
- property,
9823
- value,
9824
- specificity,
9825
- source,
9826
- isImportant,
9827
- variants,
9828
- isOverride: false
9829
- };
9830
- rules.push(rule);
9831
- const classRules = classMap.get(className);
9832
- const existingProp = classRules.get(property);
9833
- if (existingProp) {
9834
- rule.isOverride = true;
9835
- }
9836
- classRules.set(property, rule);
9837
- }
9838
- }
9839
- }
9840
- columnState.offset = lineEnd;
9841
- }
9842
- this.pruneCache();
9843
- this.parsedCache.set(css, rules);
9844
- return rules;
9723
+ function getNative() {
9724
+ const native = getNativeEngineBinding();
9725
+ if (!native?.reverseLookupFromCss || !native?.reverseLookupByProperty || !native?.reverseLookupFindDependents) {
9726
+ throw new Error(
9727
+ "FATAL: Native bindings 'reverseLookupFromCss', 'reverseLookupByProperty', 'reverseLookupFindDependents' are required but not available.\nBuild the native Rust module: npm run build:rust"
9728
+ );
9845
9729
  }
9846
- findClosingBrace(css, start) {
9847
- let depth = 1;
9848
- for (let pos = start + 1; pos < css.length; pos++) {
9849
- const char = css[pos];
9850
- if (char === "{") depth++;
9851
- else if (char === "}") {
9852
- depth--;
9853
- if (depth === 0) return pos;
9854
- }
9855
- }
9856
- return css.length;
9730
+ return native;
9731
+ }
9732
+ function normaliseNativeResults(raw) {
9733
+ return raw.map((r) => ({
9734
+ property: r.property,
9735
+ value: r.value,
9736
+ usedInClasses: r.usedInClasses.map((u) => ({
9737
+ className: u.className,
9738
+ source: { file: "", line: 0, column: 0 },
9739
+ specificity: u.specificity,
9740
+ isOverride: u.isOverride,
9741
+ variants: u.variants
9742
+ }))
9743
+ }));
9744
+ }
9745
+ var ReverseLookup = class {
9746
+ fromCSS(cssProperty, cssValue, css) {
9747
+ if (!css || !cssProperty) return [];
9748
+ return normaliseNativeResults(getNative().reverseLookupFromCss(css, cssProperty, cssValue));
9857
9749
  }
9858
- calculateSpecificity(className) {
9859
- const pseudoClasses = className.match(/:[a-zA-Z-]+/g) || [];
9860
- const attributes = className.match(/\[[^\]]+\]/g) || [];
9861
- const pseudoElements = className.match(/::[a-zA-Z-]+/g) || [];
9862
- return 1 + pseudoClasses.length * 10 + attributes.length * 10 + pseudoElements.length * 100;
9750
+ findByProperty(property, css) {
9751
+ if (!css || !property) return [];
9752
+ return normaliseNativeResults(getNative().reverseLookupByProperty(css, property));
9863
9753
  }
9864
- fromCSS(cssProperty, cssValue, css) {
9865
- if (!css || !cssProperty) {
9866
- return [];
9867
- }
9868
- const rules = this.parseCSS(css);
9869
- const normalizedProperty = cssProperty.toLowerCase();
9870
- const normalizedValue = cssValue.toLowerCase().trim();
9871
- const usages = [];
9872
- for (const rule of rules) {
9873
- if (rule.property.toLowerCase() !== normalizedProperty) {
9874
- continue;
9875
- }
9876
- const ruleValueLower = rule.value.toLowerCase().trim();
9877
- if (ruleValueLower !== normalizedValue && !ruleValueLower.includes(normalizedValue)) {
9878
- continue;
9879
- }
9880
- usages.push({
9881
- className: rule.className,
9882
- source: rule.source,
9883
- specificity: rule.specificity,
9884
- isOverride: rule.isOverride || false,
9885
- variants: rule.variants
9886
- });
9887
- }
9888
- if (usages.length === 0) {
9889
- return [];
9890
- }
9891
- return [{ property: normalizedProperty, value: cssValue, usedInClasses: usages }];
9754
+ findDependents(className, css) {
9755
+ if (!css || !className) return [];
9756
+ return getNative().reverseLookupFindDependents(css, className);
9892
9757
  }
9893
9758
  fromBundle(className, css) {
9894
- if (!css || !className) {
9895
- return [];
9759
+ if (!css || !className) return [];
9760
+ const native = getNativeEngineBinding();
9761
+ if (!native?.parseCssRules) {
9762
+ throw new Error("FATAL: Native binding 'parseCssRules' is required but not available.");
9896
9763
  }
9897
- const rules = this.parseCSS(css);
9764
+ const raw = native.parseCssRules(css);
9898
9765
  const results = [];
9899
- for (const rule of rules) {
9900
- if (rule.className === className || rule.className.startsWith(`${className}:`)) {
9901
- const ruleIR = {
9902
- id: { value: results.length },
9903
- selector: { value: 0 },
9904
- variantChain: { value: 0 },
9905
- property: { value: 0 },
9906
- value: { value: 0 },
9907
- origin: 2,
9908
- importance: rule.isImportant ? 1 : 0,
9909
- layer: null,
9910
- layerOrder: 0,
9911
- specificity: rule.specificity,
9912
- condition: null,
9913
- conditionResult: 0,
9914
- insertionOrder: results.length,
9915
- fingerprint: "",
9916
- source: rule.source
9917
- };
9918
- results.push(ruleIR);
9919
- }
9766
+ for (const rule of raw ?? []) {
9767
+ if (rule.className !== className && !rule.className.startsWith(`${className}:`)) continue;
9768
+ results.push({
9769
+ id: { value: results.length },
9770
+ selector: { value: 0 },
9771
+ variantChain: { value: 0 },
9772
+ property: { value: 0 },
9773
+ value: { value: 0 },
9774
+ origin: 2,
9775
+ importance: rule.isImportant ? 1 : 0,
9776
+ layer: null,
9777
+ layerOrder: 0,
9778
+ specificity: rule.specificity,
9779
+ condition: null,
9780
+ conditionResult: 0,
9781
+ insertionOrder: results.length,
9782
+ fingerprint: "",
9783
+ source: { file: "", line: 0, column: 0 }
9784
+ });
9920
9785
  }
9921
9786
  return results;
9922
9787
  }
9923
- findDependents(className, css) {
9924
- if (!css || !className) {
9925
- return [];
9926
- }
9927
- const rules = this.parseCSS(css);
9928
- const dependents = /* @__PURE__ */ new Set();
9929
- const classParts = className.split(":");
9930
- const baseClass = classParts[0];
9931
- for (const rule of rules) {
9932
- const ruleBaseClass = rule.className.split(":")[0];
9933
- if (ruleBaseClass === baseClass && rule.className !== className) {
9934
- dependents.add(rule.className);
9935
- }
9936
- if (rule.className.includes(baseClass) && rule.className !== className) {
9937
- const isVariant = rule.className.includes(":");
9938
- if (isVariant && !rule.className.startsWith(`${className}:`)) {
9939
- dependents.add(rule.className);
9940
- }
9941
- }
9942
- }
9943
- return Array.from(dependents);
9788
+ clearCache() {
9789
+ getNativeEngineBinding()?.reverseLookupClearCache?.();
9944
9790
  }
9945
- findByProperty(property, css) {
9946
- if (!css || !property) {
9947
- return [];
9948
- }
9949
- const rules = this.parseCSS(css);
9950
- const normalizedProperty = property.toLowerCase();
9951
- const valueMap = /* @__PURE__ */ new Map();
9952
- for (const rule of rules) {
9953
- if (rule.property.toLowerCase() !== normalizedProperty) {
9954
- continue;
9955
- }
9956
- const classUsage = {
9957
- className: rule.className,
9958
- source: rule.source,
9959
- specificity: rule.specificity,
9960
- isOverride: rule.isOverride || false,
9961
- variants: rule.variants
9962
- };
9963
- let usages = valueMap.get(rule.value);
9964
- if (!usages) {
9965
- usages = [];
9966
- valueMap.set(rule.value, usages);
9967
- }
9968
- usages.push(classUsage);
9969
- }
9970
- const results = [];
9971
- for (const [value, usedInClasses] of valueMap) {
9972
- results.push({ property: normalizedProperty, value, usedInClasses });
9973
- }
9974
- return results;
9791
+ get cacheSize() {
9792
+ return getNativeEngineBinding()?.reverseLookupCacheSize?.() ?? 0;
9793
+ }
9794
+ };
9795
+
9796
+ // packages/domain/engine/src/resolver.ts
9797
+ function toNativeInput(rule) {
9798
+ return {
9799
+ id: rule.id.value,
9800
+ property: rule.property.value,
9801
+ origin: rule.origin,
9802
+ importance: rule.importance,
9803
+ layerOrder: rule.layerOrder,
9804
+ specificity: rule.specificity,
9805
+ conditionResult: rule.conditionResult,
9806
+ insertionOrder: rule.insertionOrder
9807
+ };
9808
+ }
9809
+ function callResolveCascade(rules) {
9810
+ const native = getNativeEngineBinding();
9811
+ if (!native.resolveCascade) {
9812
+ throw new Error(
9813
+ "FATAL: Native binding 'resolveCascade' is required but not available.\nThis function requires native Rust bindings.\n\nResolution steps:\n1. Build the native Rust module: npm run build:rust"
9814
+ );
9815
+ }
9816
+ const json = JSON.stringify(rules.map(toNativeInput));
9817
+ return JSON.parse(native.resolveCascade(json));
9818
+ }
9819
+ function buildResolutionsMap(nativeResult, rules, styleGraph) {
9820
+ const propertyIdMap = /* @__PURE__ */ new Map();
9821
+ for (const rule of rules) {
9822
+ if (!propertyIdMap.has(rule.property.value)) {
9823
+ propertyIdMap.set(rule.property.value, rule.property);
9824
+ }
9825
+ }
9826
+ const resolvedProperties = /* @__PURE__ */ new Map();
9827
+ for (const res of nativeResult.resolutions) {
9828
+ const propertyId = propertyIdMap.get(res.propertyId);
9829
+ if (!propertyId) continue;
9830
+ const winner = { value: res.winnerId };
9831
+ const losers = res.loserIds.map((v) => ({ value: v }));
9832
+ const existing = styleGraph.ruleConflicts.get(winner) ?? [];
9833
+ styleGraph.ruleConflicts.set(winner, [...existing, ...losers.filter((l) => !existing.some((e) => e.value === l.value))]);
9834
+ resolvedProperties.set(propertyId, {
9835
+ id: new CascadeResolutionId(res.id),
9836
+ property: propertyId,
9837
+ winner,
9838
+ losers,
9839
+ reason: { causes: res.causes, finalDecision: res.finalDecision },
9840
+ stage: res.stage
9841
+ });
9842
+ }
9843
+ return resolvedProperties;
9844
+ }
9845
+ var CascadeResolver = class {
9846
+ rules = /* @__PURE__ */ new Map();
9847
+ classRules = /* @__PURE__ */ new Map();
9848
+ styleGraph = { ruleConflicts: /* @__PURE__ */ new Map() };
9849
+ addRule(rule) {
9850
+ this.rules.set(rule.id, rule);
9851
+ }
9852
+ addRules(rules) {
9853
+ for (const rule of rules) this.addRule(rule);
9854
+ }
9855
+ registerClass(className, ruleIds) {
9856
+ this.classRules.set(className, ruleIds);
9857
+ }
9858
+ getRule(ruleId) {
9859
+ return this.rules.get(ruleId);
9860
+ }
9861
+ getClassRules(className) {
9862
+ return this.classRules.get(className);
9863
+ }
9864
+ getStyleGraph() {
9865
+ return this.styleGraph;
9975
9866
  }
9976
9867
  /**
9977
- * Kosongkan seluruh parsed cache.
9978
- * Panggil ini saat CSS berubah (watch mode) atau saat memory pressure.
9868
+ * Resolve cascade for a specific class.
9869
+ * Delegates sort + winner selection to Rust.
9979
9870
  */
9980
- clearCache() {
9981
- this.parsedCache.clear();
9982
- this.cacheSizeBytes = 0;
9871
+ resolveByClassName(className) {
9872
+ const ruleIds = this.classRules.get(className);
9873
+ if (!ruleIds || ruleIds.length === 0) return null;
9874
+ const classRules = ruleIds.map((id) => this.rules.get(id)).filter((r) => r !== void 0);
9875
+ if (classRules.length === 0) return null;
9876
+ const nativeResult = callResolveCascade(classRules);
9877
+ return { resolvedProperties: buildResolutionsMap(nativeResult, classRules, this.styleGraph) };
9983
9878
  }
9984
9879
  /**
9985
- * Hapus entri cache lama sampai di bawah threshold.
9986
- * Dipakai oleh parseCSS secara internal.
9880
+ * Resolve cascade for all rules.
9881
+ * Delegates sort + winner selection to Rust.
9987
9882
  */
9988
- pruneCache() {
9989
- while ((this.parsedCache.size >= _ReverseLookup.MAX_CACHE_SIZE || this.cacheSizeBytes >= _ReverseLookup.MAX_CACHE_BYTES) && this.parsedCache.size > 0) {
9990
- const firstKey = this.parsedCache.keys().next().value;
9991
- if (firstKey === void 0) break;
9992
- const removed = this.parsedCache.get(firstKey);
9993
- this.parsedCache.delete(firstKey);
9994
- this.cacheSizeBytes -= firstKey.length + (removed?.length ?? 0) * 100;
9995
- if (this.cacheSizeBytes < 0) this.cacheSizeBytes = 0;
9996
- }
9883
+ resolveAllProperties() {
9884
+ const allRules = Array.from(this.rules.values());
9885
+ if (allRules.length === 0) return /* @__PURE__ */ new Map();
9886
+ const nativeResult = callResolveCascade(allRules);
9887
+ return buildResolutionsMap(nativeResult, allRules, this.styleGraph);
9997
9888
  }
9998
- /** Cache size untuk observability/diagnostics */
9999
- get cacheSize() {
10000
- return this.parsedCache.size;
9889
+ /**
9890
+ * Resolve cascade for a specific set of rule IDs.
9891
+ */
9892
+ resolveForClass(classRuleIds) {
9893
+ const classRules = classRuleIds.map((id) => this.rules.get(id)).filter((r) => r !== void 0);
9894
+ if (classRules.length === 0) return /* @__PURE__ */ new Map();
9895
+ const nativeResult = callResolveCascade(classRules);
9896
+ return buildResolutionsMap(nativeResult, classRules, this.styleGraph);
9897
+ }
9898
+ /**
9899
+ * Resolve cascade for a single property bucket.
9900
+ */
9901
+ resolveProperty(property) {
9902
+ const bucketRuleIds = Array.from(this.rules.values()).filter((r) => r.property.value === property.value);
9903
+ if (bucketRuleIds.length === 0) return null;
9904
+ const nativeResult = callResolveCascade(bucketRuleIds);
9905
+ const resolved = buildResolutionsMap(nativeResult, bucketRuleIds, this.styleGraph);
9906
+ return resolved.get(property) ?? null;
9907
+ }
9908
+ getResolution(_id) {
9909
+ return void 0;
10001
9910
  }
10002
9911
  };
10003
9912
 
10004
- // packages/infrastructure/cli/src/utils/traceService.ts
10005
- init_src2();
10006
- init_src();
10007
- var createIdGenerator = () => {
10008
- const _counters = {
10009
- ruleId: 0,
10010
- selectorId: 0,
10011
- propertyId: 0,
10012
- valueId: 0,
10013
- layerId: 0,
10014
- conditionId: 0,
10015
- insertionOrder: 0
10016
- };
10017
- const generateRuleId = () => new RuleId(_counters.ruleId++);
10018
- const generateSelectorId = () => new RuleId(_counters.selectorId++);
10019
- const generatePropertyId = (propertyName) => new PropertyId(_counters.propertyId++, propertyName);
10020
- const generateValueId = (valueName) => new ValueId(_counters.valueId++, valueName);
10021
- const generateLayerId = () => new LayerId(_counters.layerId++);
10022
- const generateConditionId = () => new ConditionId(_counters.conditionId++);
10023
- const getNextInsertionOrder = () => _counters.insertionOrder++;
10024
- const reset = () => {
10025
- _counters.ruleId = 0;
10026
- _counters.selectorId = 0;
10027
- _counters.propertyId = 0;
10028
- _counters.valueId = 0;
10029
- _counters.layerId = 0;
10030
- _counters.conditionId = 0;
10031
- _counters.insertionOrder = 0;
9913
+ // packages/domain/engine/src/cssToIr.ts
9914
+ function createIdGenerator() {
9915
+ const state = {
9916
+ ruleIdCounter: 0,
9917
+ selectorIdCounter: 0,
9918
+ propertyIdCounter: 0,
9919
+ valueIdCounter: 0,
9920
+ layerIdCounter: 0,
9921
+ conditionIdCounter: 0,
9922
+ insertionOrderCounter: 0
10032
9923
  };
10033
9924
  return {
10034
- generateRuleId,
10035
- generateSelectorId,
10036
- generatePropertyId,
10037
- generateValueId,
10038
- generateLayerId,
10039
- generateConditionId,
10040
- getNextInsertionOrder,
10041
- reset
9925
+ generateRuleId: () => new RuleId(state.ruleIdCounter++),
9926
+ generateSelectorId: () => new SelectorId(state.selectorIdCounter++),
9927
+ generatePropertyId: (name) => {
9928
+ const id = new PropertyId(state.propertyIdCounter++);
9929
+ registerPropertyName(id, name);
9930
+ return id;
9931
+ },
9932
+ generateValueId: (name) => {
9933
+ const id = new ValueId(state.valueIdCounter++);
9934
+ registerValueName(id, name);
9935
+ return id;
9936
+ },
9937
+ generateLayerId: () => new LayerId(state.layerIdCounter++),
9938
+ generateConditionId: () => new ConditionId(state.conditionIdCounter++),
9939
+ getNextInsertionOrder: () => state.insertionOrderCounter++,
9940
+ reset: () => {
9941
+ state.ruleIdCounter = 0;
9942
+ state.selectorIdCounter = 0;
9943
+ state.propertyIdCounter = 0;
9944
+ state.valueIdCounter = 0;
9945
+ state.layerIdCounter = 0;
9946
+ state.conditionIdCounter = 0;
9947
+ state.insertionOrderCounter = 0;
9948
+ }
10042
9949
  };
10043
- };
10044
- var idGenerator = createIdGenerator();
9950
+ }
9951
+ var _defaultIdGen = createIdGenerator();
9952
+ var generateRuleId = () => _defaultIdGen.generateRuleId();
9953
+ var generateSelectorId = () => _defaultIdGen.generateSelectorId();
9954
+ var generatePropertyId = (name) => _defaultIdGen.generatePropertyId(name);
9955
+ var generateValueId = (name) => _defaultIdGen.generateValueId(name);
9956
+ var generateLayerId = () => _defaultIdGen.generateLayerId();
9957
+ var generateConditionId = () => _defaultIdGen.generateConditionId();
9958
+ var getNextInsertionOrder = () => _defaultIdGen.getNextInsertionOrder();
9959
+ var resetIdGenerator = () => _defaultIdGen.reset();
10045
9960
  var layerMap = /* @__PURE__ */ new Map();
10046
9961
  var layerOrderMap = /* @__PURE__ */ new Map();
10047
9962
  var LAYER_ORDER = {
@@ -10053,109 +9968,41 @@ var LAYER_ORDER = {
10053
9968
  function getOrCreateLayerId(layerName) {
10054
9969
  const existing = layerMap.get(layerName);
10055
9970
  if (existing) return existing;
10056
- const order = LAYER_ORDER[layerName] ?? 4;
10057
- const layerId = idGenerator.generateLayerId();
9971
+ const layerId = generateLayerId();
10058
9972
  layerMap.set(layerName, layerId);
10059
- layerOrderMap.set(layerName, order);
9973
+ layerOrderMap.set(layerName, LAYER_ORDER[layerName] ?? 4);
10060
9974
  return layerId;
10061
9975
  }
10062
- function calculateSpecificity(selector) {
10063
- const classCount = selector.className.split(":").length * 10;
10064
- const pseudoCount = selector.pseudoClasses.length * 10;
10065
- const mediaCount = selector.mediaQuery ? 1e3 : 0;
10066
- return classCount + pseudoCount + mediaCount;
10067
- }
10068
- function parseSelector(selectorText) {
10069
- const mediaMatch = selectorText.match(/^@media[^{]+\{(.+)$/);
10070
- const mediaQuery = mediaMatch ? mediaMatch[0] : null;
10071
- const baseClass = (mediaMatch ? mediaMatch[1].trim() : selectorText).startsWith(".") ? (mediaMatch ? mediaMatch[1].trim() : selectorText).slice(1) : mediaMatch ? mediaMatch[1].trim() : selectorText;
10072
- const escapedColon = /\\:/g;
10073
- const baseClassClean = baseClass.startsWith(".") ? baseClass.slice(1) : baseClass;
10074
- const baseClassFinal = baseClassClean.replace(escapedColon, "\u200B").split(":")[0].replace(/\u200B/g, ":");
10075
- const variantRegex = /^(hover|focus|active|visited|checked|disabled|required|optional|first|last|odd|even|before|after|placeholder|file|selection|backdrop|group|peer)/i;
10076
- const pseudoRegex = /^:([a-zA-Z-]+)$/;
10077
- const parts = baseClassFinal.split(":").slice(1);
10078
- const { variants, pseudoClasses } = parts.reduce(
10079
- (acc, part) => {
10080
- const normalized = `:${part}`;
10081
- if (variantRegex.test(part)) {
10082
- acc.variants.push(part);
10083
- } else if (pseudoRegex.test(normalized)) {
10084
- acc.pseudoClasses.push(normalized);
10085
- } else {
10086
- acc.variants.push(part);
10087
- }
10088
- return acc;
10089
- },
10090
- { variants: [], pseudoClasses: [] }
10091
- );
10092
- return {
10093
- className: baseClassFinal,
10094
- variants,
10095
- pseudoClasses,
10096
- mediaQuery
10097
- };
10098
- }
10099
- function parseDeclaration(block) {
10100
- const declarations = [];
10101
- for (const match of block.matchAll(/([a-zA-Z-]+)\s*:\s*([^;!]+)(!important)?/g)) {
10102
- const property = match[1].trim();
10103
- const value = match[2].trim();
10104
- const important = match[3] !== void 0;
10105
- declarations.push({ property, value, important });
10106
- }
10107
- return declarations;
10108
- }
10109
- function parseRules(css) {
10110
- const rules = [];
10111
- for (const match of css.matchAll(/([^{}]+)\s*\{([^{}]*)\}/g)) {
10112
- const selectorText = match[1].trim();
10113
- const declarationBlock = match[2].trim();
10114
- if (selectorText.startsWith("@")) {
10115
- continue;
10116
- }
10117
- const parsedSelector = parseSelector(selectorText);
10118
- const declarations = parseDeclaration(declarationBlock);
10119
- for (const decl of declarations) {
10120
- rules.push({
10121
- selector: parsedSelector,
10122
- property: decl.property,
10123
- value: decl.value,
10124
- important: decl.important
10125
- });
10126
- }
10127
- }
10128
- return rules;
10129
- }
10130
- function detectLayerFromSelector(className) {
10131
- const layerPrefixes = ["tw-", "tailwind-"];
10132
- for (const prefix of layerPrefixes) {
10133
- if (className.startsWith(prefix)) {
10134
- return "tailwind";
10135
- }
10136
- }
9976
+ function detectLayerFromClassName(className) {
9977
+ if (className.startsWith("tw-") || className.startsWith("tailwind-")) return "tailwind";
10137
9978
  return null;
10138
9979
  }
10139
- function parseCssToIr(css, prefix = "") {
10140
- idGenerator.reset();
9980
+ function parseCssToIr(css, options = {}) {
9981
+ resetIdGenerator();
10141
9982
  layerMap.clear();
10142
9983
  layerOrderMap.clear();
9984
+ const native = getNativeEngineBinding();
9985
+ if (!native?.parseCssRules) {
9986
+ throw new Error("FATAL: Native binding 'parseCssRules' is required but not available.");
9987
+ }
9988
+ const prefix = options.prefix ?? "";
10143
9989
  const rules = [];
10144
9990
  const classToRuleIds = /* @__PURE__ */ new Map();
10145
- const parsedRules = parseRules(css);
10146
- for (const parsedRule of parsedRules) {
10147
- const className = prefix + parsedRule.selector.className;
10148
- const specificity = calculateSpecificity(parsedRule.selector);
10149
- const layerName = detectLayerFromSelector(className);
9991
+ const parsed = native.parseCssRules(css);
9992
+ for (const r of parsed) {
9993
+ const className = prefix + r.className;
9994
+ r.variants.length > 0;
9995
+ const layerName = detectLayerFromClassName(className);
10150
9996
  const layer = layerName ? getOrCreateLayerId(layerName) : null;
10151
9997
  const layerOrder = layerName ? layerOrderMap.get(layerName) ?? 4 : 4;
10152
- const selectorId = idGenerator.generateSelectorId();
10153
- const propertyId = idGenerator.generatePropertyId(parsedRule.property);
10154
- const valueId = idGenerator.generateValueId(parsedRule.value);
10155
- const conditionId = parsedRule.selector.mediaQuery ? idGenerator.generateConditionId() : null;
10156
- const conditionResult = parsedRule.selector.mediaQuery ? 2 /* Unknown */ : 2 /* Unknown */;
10157
- const fingerprint = createFingerprint([className, parsedRule.property, parsedRule.value]);
10158
- const ruleId = idGenerator.generateRuleId();
9998
+ const selectorId = generateSelectorId();
9999
+ const propertyId = generatePropertyId(r.property);
10000
+ const valueId = generateValueId(r.value);
10001
+ const hasMedia = r.variants.some((v) => v.startsWith("@") || v === "dark" || v === "print");
10002
+ const conditionId = hasMedia ? generateConditionId() : null;
10003
+ const conditionResult = hasMedia ? 2 /* Unknown */ : 2 /* Unknown */;
10004
+ const ruleId = generateRuleId();
10005
+ const fingerprint = createFingerprint([className, r.property, r.value]);
10159
10006
  const rule = {
10160
10007
  id: ruleId,
10161
10008
  selector: selectorId,
@@ -10163,117 +10010,58 @@ function parseCssToIr(css, prefix = "") {
10163
10010
  property: propertyId,
10164
10011
  value: valueId,
10165
10012
  origin: 2 /* AuthorNormal */,
10166
- importance: parsedRule.important ? 1 /* Important */ : 0 /* Normal */,
10013
+ importance: r.isImportant ? 1 /* Important */ : 0 /* Normal */,
10167
10014
  layer,
10168
10015
  layerOrder,
10169
- specificity,
10016
+ specificity: r.specificity,
10017
+ // from native — no JS recalculation
10170
10018
  condition: conditionId,
10171
10019
  conditionResult,
10172
- insertionOrder: idGenerator.getNextInsertionOrder(),
10020
+ insertionOrder: getNextInsertionOrder(),
10173
10021
  fingerprint,
10174
- source: {
10175
- file: "",
10176
- line: 1,
10177
- column: 1
10178
- }
10022
+ source: { file: "", line: 1, column: 1 }
10179
10023
  };
10180
10024
  rules.push(rule);
10181
- const existingRuleIds = classToRuleIds.get(className) || [];
10182
- existingRuleIds.push(ruleId);
10183
- classToRuleIds.set(className, existingRuleIds);
10025
+ const existing = classToRuleIds.get(className) ?? [];
10026
+ existing.push(ruleId);
10027
+ classToRuleIds.set(className, existing);
10184
10028
  }
10185
10029
  return { rules, classToRuleIds };
10186
10030
  }
10187
- var CascadeResolver = class {
10188
- propertyBuckets = /* @__PURE__ */ new Map();
10189
- rules = /* @__PURE__ */ new Map();
10190
- classRules = /* @__PURE__ */ new Map();
10191
- addRule(rule) {
10192
- this.rules.set(rule.id, rule);
10193
- const property = rule.property;
10194
- const existingBucket = this.propertyBuckets.get(property);
10195
- if (!existingBucket) {
10196
- this.propertyBuckets.set(property, {
10197
- property,
10198
- rules: [rule.id]
10199
- });
10200
- } else {
10201
- this.propertyBuckets.set(property, {
10202
- ...existingBucket,
10203
- rules: [...existingBucket.rules, rule.id]
10204
- });
10205
- }
10206
- }
10207
- addRules(rules) {
10208
- for (const rule of rules) {
10209
- this.addRule(rule);
10210
- }
10211
- }
10212
- getRule(ruleId) {
10213
- return this.rules.get(ruleId);
10214
- }
10215
- registerClass(className, ruleIds) {
10216
- this.classRules.set(className, ruleIds);
10217
- }
10218
- getClassRules(className) {
10219
- return this.classRules.get(className);
10220
- }
10221
- resolveByClassName(className) {
10222
- const ruleIds = this.classRules.get(className);
10223
- if (!ruleIds) {
10224
- return null;
10225
- }
10226
- const classRules = [];
10227
- for (const ruleId of ruleIds) {
10228
- const rule = this.rules.get(ruleId);
10229
- if (rule) {
10230
- classRules.push(rule);
10231
- }
10232
- }
10233
- const propertyMap = /* @__PURE__ */ new Map();
10234
- for (const rule of classRules) {
10235
- const existing = propertyMap.get(rule.property) || [];
10236
- existing.push(rule);
10237
- propertyMap.set(rule.property, existing);
10238
- }
10239
- const resolved = /* @__PURE__ */ new Map();
10240
- for (const [property, rules] of propertyMap) {
10241
- if (rules.length > 0) {
10242
- const activeRules = rules.filter((r) => r.conditionResult !== 1 /* Inactive */);
10243
- if (activeRules.length > 0) {
10244
- activeRules.sort((a, b) => {
10245
- const originDiff = b.origin - a.origin;
10246
- if (originDiff !== 0) return originDiff;
10247
- const layerDiff = b.layerOrder - a.layerOrder;
10248
- if (layerDiff !== 0) return layerDiff;
10249
- const importanceDiff = b.importance - a.importance;
10250
- if (importanceDiff !== 0) return importanceDiff;
10251
- const specificityDiff = b.specificity - a.specificity;
10252
- if (specificityDiff !== 0) return specificityDiff;
10253
- return b.insertionOrder - a.insertionOrder;
10254
- });
10255
- const winner = activeRules[0];
10256
- resolved.set(property, { winner: winner.id });
10257
- }
10258
- }
10259
- }
10260
- return { resolvedProperties: resolved };
10261
- }
10262
- };
10263
- function trace(className, resolver) {
10264
- const provenance = {
10031
+
10032
+ // packages/domain/engine/src/trace.ts
10033
+ function buildProvenanceChain(className) {
10034
+ return {
10035
+ className,
10265
10036
  source: { file: "", line: 0, column: 0 },
10266
10037
  variants: /* @__PURE__ */ new Map(),
10267
10038
  rules: /* @__PURE__ */ new Map()
10268
10039
  };
10040
+ }
10041
+ function formatCause(c) {
10042
+ switch (c.type) {
10043
+ case "LowerOrigin":
10044
+ return "lower origin";
10045
+ case "LowerLayer":
10046
+ return "lower layer";
10047
+ case "LowerImportance":
10048
+ return "lower importance";
10049
+ case "LowerSpecificity":
10050
+ return `specificity ${c.delta}`;
10051
+ case "EarlierOrder":
10052
+ return `earlier order ${c.delta}`;
10053
+ case "InactiveCondition":
10054
+ return "inactive condition";
10055
+ }
10056
+ }
10057
+ function trace(className, resolver) {
10058
+ const provenance = buildProvenanceChain(className);
10269
10059
  const classRuleIds = resolver.getClassRules(className);
10270
10060
  const allRules = [];
10271
10061
  if (classRuleIds) {
10272
10062
  for (const ruleId of classRuleIds) {
10273
10063
  const rule = resolver.getRule(ruleId);
10274
- if (rule) {
10275
- allRules.push(rule);
10276
- }
10064
+ if (rule) allRules.push(rule);
10277
10065
  }
10278
10066
  }
10279
10067
  for (const rules of provenance.rules.values()) {
@@ -10282,57 +10070,49 @@ function trace(className, resolver) {
10282
10070
  const rulesByProperty = /* @__PURE__ */ new Map();
10283
10071
  for (const rule of allRules) {
10284
10072
  const propKey = rule.property.toString();
10285
- if (!rulesByProperty.has(propKey)) {
10286
- rulesByProperty.set(propKey, []);
10287
- }
10288
- rulesByProperty.get(propKey).push(rule);
10073
+ const bucket = rulesByProperty.get(propKey) ?? [];
10074
+ bucket.push(rule);
10075
+ rulesByProperty.set(propKey, bucket);
10289
10076
  }
10077
+ const resolved = resolver.resolveByClassName(className);
10290
10078
  const ruleTraces = [];
10291
10079
  const conflictTraces = [];
10292
- for (const [property, rules] of rulesByProperty) {
10293
- if (rules.length === 0) continue;
10294
- const activeRules = rules.filter((r) => r.conditionResult !== 1 /* Inactive */);
10295
- if (activeRules.length === 0) continue;
10296
- activeRules.sort((a, b) => {
10297
- const originDiff = b.origin - a.origin;
10298
- if (originDiff !== 0) return originDiff;
10299
- const layerDiff = b.layerOrder - a.layerOrder;
10300
- if (layerDiff !== 0) return layerDiff;
10301
- const importanceDiff = b.importance - a.importance;
10302
- if (importanceDiff !== 0) return importanceDiff;
10303
- const specificityDiff = b.specificity - a.specificity;
10304
- if (specificityDiff !== 0) return specificityDiff;
10305
- return b.insertionOrder - a.insertionOrder;
10306
- });
10307
- const winnerRule = activeRules[0];
10308
- const losers = activeRules.slice(1);
10309
- ruleTraces.push({
10310
- property,
10311
- value: winnerRule.value.toString(),
10312
- applied: true,
10313
- reason: null,
10314
- source: winnerRule.source,
10315
- specificity: winnerRule.specificity
10316
- });
10317
- for (const loserRule of losers) {
10318
- ruleTraces.push({
10319
- property,
10320
- value: loserRule.value.toString(),
10321
- applied: false,
10322
- reason: "lower specificity",
10323
- source: loserRule.source,
10324
- specificity: loserRule.specificity
10325
- });
10326
- conflictTraces.push({
10327
- property,
10328
- winner: winnerRule.value.toString(),
10329
- loser: loserRule.value.toString(),
10330
- stage: "Specificity",
10331
- causes: ["lower specificity"]
10332
- });
10080
+ if (resolved) {
10081
+ for (const [propId, resolution] of resolved.resolvedProperties) {
10082
+ const property = propId.toString();
10083
+ const rules = rulesByProperty.get(property) ?? [];
10084
+ const winnerRule = rules.find((r) => r.id.value === resolution.winner.value);
10085
+ if (winnerRule) {
10086
+ ruleTraces.push({
10087
+ property,
10088
+ value: winnerRule.value.toString(),
10089
+ applied: true,
10090
+ reason: null,
10091
+ source: winnerRule.source,
10092
+ specificity: winnerRule.specificity
10093
+ });
10094
+ }
10095
+ for (const loserId of resolution.losers) {
10096
+ const loserRule = rules.find((r) => r.id.value === loserId.value);
10097
+ if (!loserRule) continue;
10098
+ ruleTraces.push({
10099
+ property,
10100
+ value: loserRule.value.toString(),
10101
+ applied: false,
10102
+ reason: resolution.reason.finalDecision,
10103
+ source: loserRule.source,
10104
+ specificity: loserRule.specificity
10105
+ });
10106
+ conflictTraces.push({
10107
+ property,
10108
+ winner: winnerRule?.value.toString() ?? "",
10109
+ loser: loserRule.value.toString(),
10110
+ stage: CascadeStage[resolution.stage],
10111
+ causes: resolution.reason.causes.map(formatCause)
10112
+ });
10113
+ }
10333
10114
  }
10334
10115
  }
10335
- const resolved = resolver.resolveByClassName(className);
10336
10116
  const finalStyle = [];
10337
10117
  if (resolved) {
10338
10118
  for (const [propId, resolution] of resolved.resolvedProperties) {
@@ -10352,6 +10132,30 @@ function trace(className, resolver) {
10352
10132
  finalStyle
10353
10133
  };
10354
10134
  }
10135
+
10136
+ // packages/infrastructure/cli/src/utils/traceService.ts
10137
+ init_src2();
10138
+ init_src();
10139
+ function safeToString(value) {
10140
+ if (value === null || value === void 0) return "";
10141
+ if (typeof value === "string") return value;
10142
+ if (typeof value === "number") return String(value);
10143
+ if (typeof value === "object") {
10144
+ const obj = value;
10145
+ if (typeof obj.name === "string" && obj.name.length > 0) return obj.name;
10146
+ if (obj.value !== void 0) return String(obj.value);
10147
+ const toStr = obj.toString;
10148
+ if (typeof toStr === "function") {
10149
+ try {
10150
+ const result = toStr.call(value);
10151
+ if (typeof result === "string" && result !== "[object Object]") return result;
10152
+ } catch {
10153
+ }
10154
+ }
10155
+ return "?";
10156
+ }
10157
+ return String(value);
10158
+ }
10355
10159
  async function traceClass(className, options) {
10356
10160
  const root = options?.root ?? process.cwd();
10357
10161
  const scanResult = await scanWorkspace(root, {
@@ -10385,53 +10189,16 @@ async function traceClass(className, options) {
10385
10189
  const { rules, classToRuleIds } = parseCssToIr(cssResult.code);
10386
10190
  const ruleIds = classToRuleIds.get(className);
10387
10191
  if (!ruleIds || ruleIds.length === 0) {
10388
- throw TwError.fromCompile("TRACE_NO_RULES_FOUND", `No rules found for class "${className}" after parsing CSS.`);
10192
+ throw TwError.fromCompile(
10193
+ "TRACE_NO_RULES_FOUND",
10194
+ `No rules found for class "${className}" after parsing CSS.`
10195
+ );
10389
10196
  }
10390
10197
  const resolver = new CascadeResolver();
10391
10198
  resolver.addRules(rules);
10392
10199
  resolver.registerClass(className, ruleIds);
10393
- const engineTraceResult = trace(className, resolver);
10394
- return convertTraceResult(engineTraceResult);
10395
- }
10396
- function safeToString(value) {
10397
- if (value === null || value === void 0) return "";
10398
- if (typeof value === "string") return String(value);
10399
- if (typeof value === "number") return String(value);
10400
- if (typeof value === "boolean") return String(value);
10401
- if (typeof value === "object" && value !== null) {
10402
- const obj = value;
10403
- const name = obj.name;
10404
- if (typeof name === "string" && name.length > 0) {
10405
- return name;
10406
- }
10407
- const objValue = obj.value;
10408
- if (objValue !== void 0) {
10409
- return String(objValue);
10410
- }
10411
- const objValueOf = obj.valueOf;
10412
- if (typeof objValueOf === "function") {
10413
- try {
10414
- const vo = objValueOf.call(value);
10415
- if (vo !== value) return String(vo);
10416
- } catch {
10417
- }
10418
- }
10419
- const toStr = obj.toString;
10420
- if (typeof toStr === "function") {
10421
- try {
10422
- const result = toStr.call(value);
10423
- if (typeof result === "string" && result !== "[object Object]") {
10424
- return result;
10425
- }
10426
- } catch {
10427
- }
10428
- }
10429
- return "?";
10430
- }
10431
- return String(value);
10432
- }
10433
- function convertTraceResult(engineResult) {
10434
- return {
10200
+ const engineResult = trace(className, resolver);
10201
+ const result = {
10435
10202
  class: safeToString(engineResult.class),
10436
10203
  definedAt: {
10437
10204
  file: safeToString(engineResult.definedAt.file),
@@ -10443,7 +10210,8 @@ function convertTraceResult(engineResult) {
10443
10210
  value: safeToString(v.value),
10444
10211
  source: {
10445
10212
  file: safeToString(v.source?.file ?? ""),
10446
- line: Number(v.source?.line ?? 0)
10213
+ line: Number(v.source?.line ?? 0),
10214
+ column: Number(v.source?.column ?? 0)
10447
10215
  }
10448
10216
  })),
10449
10217
  rules: engineResult.rules.map((r) => ({
@@ -10453,7 +10221,8 @@ function convertTraceResult(engineResult) {
10453
10221
  reason: r.reason ? safeToString(r.reason) : null,
10454
10222
  source: {
10455
10223
  file: safeToString(r.source?.file ?? ""),
10456
- line: Number(r.source?.line ?? 0)
10224
+ line: Number(r.source?.line ?? 0),
10225
+ column: Number(r.source?.column ?? 0)
10457
10226
  },
10458
10227
  specificity: Number(r.specificity ?? 0)
10459
10228
  })),
@@ -10462,17 +10231,18 @@ function convertTraceResult(engineResult) {
10462
10231
  winner: safeToString(c.winner),
10463
10232
  loser: safeToString(c.loser),
10464
10233
  stage: safeToString(c.stage),
10465
- causes: c.causes?.map(safeToString) ?? []
10234
+ causes: (c.causes ?? []).map(safeToString)
10466
10235
  })),
10467
10236
  finalStyle: engineResult.finalStyle.map((f) => ({
10468
10237
  property: safeToString(f.property),
10469
10238
  value: safeToString(f.value)
10470
10239
  }))
10471
10240
  };
10241
+ return result;
10472
10242
  }
10473
10243
  init_src2();
10474
10244
  function toRelativePath(root, value) {
10475
- const relative = path3__default.default.relative(root, value);
10245
+ const relative = path6__namespace.default.relative(root, value);
10476
10246
  return relative.length > 0 ? relative : ".";
10477
10247
  }
10478
10248
  function uniqueSorted(values) {
@@ -10541,7 +10311,7 @@ function tryCompileClasses(classes) {
10541
10311
  }
10542
10312
  }
10543
10313
  function traceSingleFile(filePath, root) {
10544
- const source = fs8__default.default.readFileSync(filePath, "utf8");
10314
+ const source = fs11__namespace.default.readFileSync(filePath, "utf8");
10545
10315
  const classes = uniqueSorted(scanSource(source));
10546
10316
  const imports = extractImports(source);
10547
10317
  const compiled = tryCompileClasses(classes);
@@ -10572,7 +10342,7 @@ function traceDirectory(targetDir, root) {
10572
10342
  const imports = [];
10573
10343
  const importKeys = /* @__PURE__ */ new Set();
10574
10344
  const files = scanResult.files.filter((entry) => isScannableFile(entry.file, DEFAULT_EXTENSIONS)).map((entry) => {
10575
- const source = fs8__default.default.readFileSync(entry.file, "utf8");
10345
+ const source = fs11__namespace.default.readFileSync(entry.file, "utf8");
10576
10346
  const fileImports = extractImports(source);
10577
10347
  for (const fileImport of fileImports) {
10578
10348
  const key = `${fileImport.kind}:${fileImport.source}`;
@@ -10603,12 +10373,12 @@ function traceDirectory(targetDir, root) {
10603
10373
  };
10604
10374
  }
10605
10375
  async function traceTarget(target, options = {}) {
10606
- const root = path3__default.default.resolve(options.root ?? process.cwd());
10607
- const resolvedTarget = path3__default.default.resolve(root, target);
10608
- if (!fs8__default.default.existsSync(resolvedTarget)) {
10376
+ const root = path6__namespace.default.resolve(options.root ?? process.cwd());
10377
+ const resolvedTarget = path6__namespace.default.resolve(root, target);
10378
+ if (!fs11__namespace.default.existsSync(resolvedTarget)) {
10609
10379
  throw new Error(`Trace target not found: ${resolvedTarget}`);
10610
10380
  }
10611
- const stat = fs8__default.default.statSync(resolvedTarget);
10381
+ const stat = fs11__namespace.default.statSync(resolvedTarget);
10612
10382
  if (stat.isDirectory()) {
10613
10383
  return traceDirectory(resolvedTarget, root);
10614
10384
  }
@@ -10777,7 +10547,7 @@ async function runGenerateTypesCli(rawArgs) {
10777
10547
  const logger = createCliLogger({ output });
10778
10548
  const cwd2 = process.cwd();
10779
10549
  const outFile = rawArgs.find((a) => a.startsWith("--out="))?.slice(6) ?? "src/types/tailwind-styled.d.ts";
10780
- const outPath = path3__default.default.resolve(cwd2, outFile);
10550
+ const outPath = path6__namespace.default.resolve(cwd2, outFile);
10781
10551
  output.writeText("");
10782
10552
  output.writeText(import_picocolors6.default.bold(import_picocolors6.default.cyan(" \u25C6 tw generate-types")));
10783
10553
  output.writeText(import_picocolors6.default.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));
@@ -10791,12 +10561,11 @@ async function runGenerateTypesCli(rawArgs) {
10791
10561
  throw new Error("Native binding 'generateSubComponentTypes' tidak tersedia \u2014 pastikan build:rust sudah dijalankan");
10792
10562
  }
10793
10563
  result = binding.generateSubComponentTypes(cwd2, outPath);
10564
+ if (!result) throw new Error("generateSubComponentTypes mengembalikan null");
10794
10565
  spinner.stop(`Scanned ${result.filesScanned} files`);
10795
10566
  } catch (err) {
10796
10567
  spinner.error("Scan gagal");
10797
- logger.warn(err instanceof Error ? err.message : String(err));
10798
- output.writeText(import_picocolors6.default.dim(" \u2192 fallback ke JS scanner..."));
10799
- result = await fallbackJsScan(cwd2);
10568
+ throw err instanceof Error ? err : new Error(String(err));
10800
10569
  }
10801
10570
  if (!result) {
10802
10571
  logger.warn("Tidak ada hasil scan");
@@ -10814,12 +10583,12 @@ async function runGenerateTypesCli(rawArgs) {
10814
10583
  }
10815
10584
  output.writeText("");
10816
10585
  output.writeText(import_picocolors6.default.bold(" [2/2]") + import_picocolors6.default.cyan(" generate .d.ts"));
10817
- const outDir = path3__default.default.dirname(outPath);
10818
- if (!fs8__default.default.existsSync(outDir)) {
10819
- fs8__default.default.mkdirSync(outDir, { recursive: true });
10586
+ const outDir = path6__namespace.default.dirname(outPath);
10587
+ if (!fs11__namespace.default.existsSync(outDir)) {
10588
+ fs11__namespace.default.mkdirSync(outDir, { recursive: true });
10820
10589
  }
10821
- fs8__default.default.writeFileSync(outPath, result.dtsContent, "utf-8");
10822
- logger.ok(path3__default.default.relative(cwd2, outPath));
10590
+ fs11__namespace.default.writeFileSync(outPath, result.dtsContent, "utf-8");
10591
+ logger.ok(path6__namespace.default.relative(cwd2, outPath));
10823
10592
  output.writeText("");
10824
10593
  output.writeText(import_picocolors6.default.dim(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));
10825
10594
  output.writeText(import_picocolors6.default.bold(import_picocolors6.default.green(" \u2713 types generated")));
@@ -10830,11 +10599,11 @@ async function runGenerateTypesCli(rawArgs) {
10830
10599
  }
10831
10600
  async function loadNativeBinding2(cwd2) {
10832
10601
  const candidates = [
10833
- path3__default.default.join(cwd2, "native", "tailwind-styled-native.node"),
10834
- path3__default.default.join(cwd2, "node_modules", "tailwind-styled-v4", "native", "tailwind-styled-native.node")
10602
+ path6__namespace.default.join(cwd2, "native", "tailwind-styled-native.node"),
10603
+ path6__namespace.default.join(cwd2, "node_modules", "tailwind-styled-v4", "native", "tailwind-styled-native.node")
10835
10604
  ];
10836
10605
  for (const candidate of candidates) {
10837
- if (fs8__default.default.existsSync(candidate)) {
10606
+ if (fs11__namespace.default.existsSync(candidate)) {
10838
10607
  try {
10839
10608
  return __require(candidate);
10840
10609
  } catch {
@@ -10843,42 +10612,6 @@ async function loadNativeBinding2(cwd2) {
10843
10612
  }
10844
10613
  return null;
10845
10614
  }
10846
- async function fallbackJsScan(cwd2, outPath) {
10847
- const { execSync } = await import('child_process');
10848
- const registerRe = /registerSubComponent\s*\(\s*\{[^}]*name\s*:\s*["']([a-zA-Z][a-zA-Z0-9_-]*)["']/g;
10849
- const withSubRe = /\.withSub\s*<\s*([^>]+)\s*>/g;
10850
- const literalRe = /["']([a-zA-Z][a-zA-Z0-9_-]*)["']/g;
10851
- const names = /* @__PURE__ */ new Set();
10852
- let filesScanned = 0;
10853
- try {
10854
- const files = execSync(
10855
- `find . -name "*.tsx" -o -name "*.ts" -o -name "*.jsx" -o -name "*.js" | grep -v node_modules | grep -v .next | grep -v dist`,
10856
- { cwd: cwd2, encoding: "utf-8" }
10857
- ).trim().split("\n").filter(Boolean);
10858
- for (const file of files) {
10859
- try {
10860
- const source = fs8__default.default.readFileSync(path3__default.default.join(cwd2, file), "utf-8");
10861
- filesScanned++;
10862
- for (const m of source.matchAll(registerRe)) names.add(m[1]);
10863
- for (const m of source.matchAll(withSubRe)) {
10864
- for (const lit of m[1].matchAll(literalRe)) names.add(lit[1]);
10865
- }
10866
- } catch {
10867
- }
10868
- }
10869
- } catch {
10870
- }
10871
- const sorted = [...names].sort();
10872
- const union = sorted.map((n) => `"${n}"`).join(" | ") || "never";
10873
- const dtsContent = `// AUTO-GENERATED by tailwind-styled-v4 (JS fallback)
10874
- // DO NOT EDIT \u2014 Run: npx tw generate-types to regenerate
10875
-
10876
- declare module "tailwind-styled-v4" {
10877
- export type DetectedSubComponents = ${union}
10878
- }
10879
- `;
10880
- return { names: sorted, dtsContent, filesScanned };
10881
- }
10882
10615
 
10883
10616
  // packages/infrastructure/cli/src/commands/why.ts
10884
10617
  init_errors();
@@ -10929,7 +10662,7 @@ async function whyClass(className, options) {
10929
10662
  for (const file of scanResult.files) {
10930
10663
  const source = (() => {
10931
10664
  try {
10932
- return fs8__default.default.readFileSync(file.file, "utf8");
10665
+ return fs11__namespace.default.readFileSync(file.file, "utf8");
10933
10666
  } catch {
10934
10667
  return "";
10935
10668
  }
@@ -10943,7 +10676,7 @@ async function whyClass(className, options) {
10943
10676
  className
10944
10677
  ]);
10945
10678
  usedIn.push({
10946
- file: path3__default.default.relative(root, file.file) || path3__default.default.basename(file.file),
10679
+ file: path6__namespace.default.relative(root, file.file) || path6__namespace.default.basename(file.file),
10947
10680
  line: location.line,
10948
10681
  column: location.column,
10949
10682
  usage: normalizeScannedClass(fileClass)
@@ -11109,7 +10842,7 @@ function buildMainProgram(context) {
11109
10842
  new Map(miscCommands.map((command) => [command.name, command]));
11110
10843
  const scriptByName = new Map(scriptCommands.map((command) => [command.name, command]));
11111
10844
  const program2 = new Command("tw");
11112
- program2.name("tw").description("tailwind-styled-v4 CLI").option("--json", "Output strict JSON envelope").option("--debug", "Include stack traces for errors").option("--verbose", "Verbose runtime logs");
10845
+ program2.name("tw").description("tailwind-styled-v4 CLI").version("5.0.4", "--version", "Output the current version").option("--json", "Output strict JSON envelope").option("--debug", "Include stack traces for errors").option("--verbose", "Verbose runtime logs");
11113
10846
  program2.command("setup").description("Auto-setup project").option("--yes", "Skip prompts").option("--next", "Force Next.js").option("--vite", "Force Vite").option("--rspack", "Force Rspack").option("--react", "Force React").option("--dry-run", "Preview changes").option("--skip-install", "Skip package install").action(async (...actionArgs) => {
11114
10847
  const options = actionCommand(actionArgs).opts();
11115
10848
  const args = [];
@@ -11398,12 +11131,18 @@ function buildMainProgram(context) {
11398
11131
 
11399
11132
  // packages/infrastructure/cli/src/index.ts
11400
11133
  init_runtime();
11134
+ init_args();
11135
+ init_args();
11136
+ init_output();
11401
11137
  async function main2() {
11402
11138
  await runCliMain({
11403
11139
  importMetaUrl: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href)),
11404
11140
  buildProgram: buildMainProgram
11405
11141
  });
11406
11142
  }
11407
- main2();
11143
+ var __filename2 = url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('tw.js', document.baseURI).href)));
11144
+ if (process.argv[1] === __filename2) {
11145
+ main2();
11146
+ }
11408
11147
  //# sourceMappingURL=tw.js.map
11409
11148
  //# sourceMappingURL=tw.js.map