@salty-css/core 0.2.1 → 0.2.2-refactor-vite-8.4

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 (304) hide show
  1. package/dist/astro-component-Ov1RH0CO.js +4 -0
  2. package/dist/astro-component-r0qEcF1p.cjs +14 -0
  3. package/{bin → dist/bin}/bin-util.d.ts +1 -0
  4. package/dist/bin/bin-util.d.ts.map +1 -0
  5. package/{bin → dist/bin}/commands/build.d.ts +1 -0
  6. package/dist/bin/commands/build.d.ts.map +1 -0
  7. package/{bin → dist/bin}/commands/generate.d.ts +1 -0
  8. package/dist/bin/commands/generate.d.ts.map +1 -0
  9. package/{bin → dist/bin}/commands/init.d.ts +1 -0
  10. package/dist/bin/commands/init.d.ts.map +1 -0
  11. package/{bin → dist/bin}/commands/update.d.ts +1 -0
  12. package/dist/bin/commands/update.d.ts.map +1 -0
  13. package/{bin → dist/bin}/commands/version.d.ts +1 -0
  14. package/dist/bin/commands/version.d.ts.map +1 -0
  15. package/{bin → dist/bin}/confirm-install.d.ts +1 -0
  16. package/dist/bin/confirm-install.d.ts.map +1 -0
  17. package/{bin → dist/bin}/context.d.ts +1 -0
  18. package/dist/bin/context.d.ts.map +1 -0
  19. package/{bin → dist/bin}/detection/css-file.d.ts +1 -0
  20. package/dist/bin/detection/css-file.d.ts.map +1 -0
  21. package/{bin → dist/bin}/frameworks/astro.d.ts +1 -0
  22. package/dist/bin/frameworks/astro.d.ts.map +1 -0
  23. package/{bin → dist/bin}/frameworks/index.d.ts +1 -0
  24. package/dist/bin/frameworks/index.d.ts.map +1 -0
  25. package/{bin → dist/bin}/frameworks/react.d.ts +1 -0
  26. package/dist/bin/frameworks/react.d.ts.map +1 -0
  27. package/{bin → dist/bin}/frameworks/types.d.ts +1 -0
  28. package/dist/bin/frameworks/types.d.ts.map +1 -0
  29. package/dist/bin/index.cjs +2 -0
  30. package/dist/bin/index.d.ts +3 -0
  31. package/dist/bin/index.d.ts.map +1 -0
  32. package/dist/bin/index.js +5 -0
  33. package/{bin → dist/bin}/integrations/astro.d.ts +1 -0
  34. package/dist/bin/integrations/astro.d.ts.map +1 -0
  35. package/{bin → dist/bin}/integrations/eslint.d.ts +1 -0
  36. package/dist/bin/integrations/eslint.d.ts.map +1 -0
  37. package/{bin → dist/bin}/integrations/index.d.ts +1 -0
  38. package/dist/bin/integrations/index.d.ts.map +1 -0
  39. package/{bin → dist/bin}/integrations/next.d.ts +1 -0
  40. package/dist/bin/integrations/next.d.ts.map +1 -0
  41. package/{bin → dist/bin}/integrations/types.d.ts +1 -0
  42. package/dist/bin/integrations/types.d.ts.map +1 -0
  43. package/{bin → dist/bin}/integrations/vite.d.ts +1 -0
  44. package/dist/bin/integrations/vite.d.ts.map +1 -0
  45. package/{bin → dist/bin}/logger.d.ts +1 -0
  46. package/dist/bin/logger.d.ts.map +1 -0
  47. package/dist/bin/main.cjs +1 -0
  48. package/{bin → dist/bin}/main.d.ts +1 -0
  49. package/dist/bin/main.d.ts.map +1 -0
  50. package/dist/bin/main.js +2 -0
  51. package/{bin → dist/bin}/package-json.d.ts +1 -0
  52. package/dist/bin/package-json.d.ts.map +1 -0
  53. package/{bin → dist/bin}/path-defaults.d.ts +1 -0
  54. package/dist/bin/path-defaults.d.ts.map +1 -0
  55. package/{bin → dist/bin}/prettier.d.ts +1 -0
  56. package/dist/bin/prettier.d.ts.map +1 -0
  57. package/{bin → dist/bin}/saltyrc.d.ts +1 -0
  58. package/dist/bin/saltyrc.d.ts.map +1 -0
  59. package/dist/bin/templates.d.ts +15 -0
  60. package/dist/bin/templates.d.ts.map +1 -0
  61. package/dist/chunk-CMqjfN_6.cjs +1 -0
  62. package/dist/compiler/get-files.cjs +1 -0
  63. package/{compiler → dist/compiler}/get-files.d.ts +1 -0
  64. package/dist/compiler/get-files.d.ts.map +1 -0
  65. package/dist/compiler/get-files.js +15 -0
  66. package/dist/compiler/get-function-range.cjs +1 -0
  67. package/{compiler → dist/compiler}/get-function-range.d.ts +1 -0
  68. package/dist/compiler/get-function-range.d.ts.map +1 -0
  69. package/dist/compiler/get-function-range.js +17 -0
  70. package/dist/compiler/helpers.cjs +1 -0
  71. package/{compiler → dist/compiler}/helpers.d.ts +1 -0
  72. package/dist/compiler/helpers.d.ts.map +1 -0
  73. package/dist/compiler/helpers.js +24 -0
  74. package/{compiler → dist/compiler}/resolve-import.d.ts +1 -0
  75. package/dist/compiler/resolve-import.d.ts.map +1 -0
  76. package/dist/compiler/salty-compiler.cjs +1 -0
  77. package/{compiler → dist/compiler}/salty-compiler.d.ts +1 -0
  78. package/dist/compiler/salty-compiler.d.ts.map +1 -0
  79. package/dist/compiler/salty-compiler.js +2 -0
  80. package/{config → dist/config}/define-config.d.ts +1 -0
  81. package/dist/config/define-config.d.ts.map +1 -0
  82. package/dist/config/index.cjs +1 -0
  83. package/{config → dist/config}/index.d.ts +1 -0
  84. package/dist/config/index.d.ts.map +1 -0
  85. package/dist/config/index.js +5 -0
  86. package/dist/css/index.cjs +1 -0
  87. package/{css → dist/css}/index.d.ts +1 -0
  88. package/dist/css/index.d.ts.map +1 -0
  89. package/dist/css/index.js +5 -0
  90. package/dist/css/keyframes.cjs +1 -0
  91. package/{css → dist/css}/keyframes.d.ts +1 -0
  92. package/dist/css/keyframes.d.ts.map +1 -0
  93. package/dist/css/keyframes.js +30 -0
  94. package/dist/css/media.cjs +1 -0
  95. package/{css → dist/css}/media.d.ts +1 -0
  96. package/dist/css/media.d.ts.map +1 -0
  97. package/dist/css/media.js +84 -0
  98. package/dist/css/merge.cjs +1 -0
  99. package/{css → dist/css}/merge.d.ts +1 -0
  100. package/dist/css/merge.d.ts.map +1 -0
  101. package/dist/css/merge.js +20 -0
  102. package/dist/css/token.cjs +1 -0
  103. package/{css → dist/css}/token.d.ts +1 -0
  104. package/dist/css/token.d.ts.map +1 -0
  105. package/dist/css/token.js +4 -0
  106. package/{factories → dist/factories}/define-font.d.ts +1 -0
  107. package/dist/factories/define-font.d.ts.map +1 -0
  108. package/{factories → dist/factories}/define-global-styles.d.ts +1 -0
  109. package/dist/factories/define-global-styles.d.ts.map +1 -0
  110. package/{factories → dist/factories}/define-import.d.ts +1 -0
  111. package/dist/factories/define-import.d.ts.map +1 -0
  112. package/{factories → dist/factories}/define-media-query.d.ts +1 -0
  113. package/dist/factories/define-media-query.d.ts.map +1 -0
  114. package/{factories → dist/factories}/define-templates.d.ts +1 -0
  115. package/dist/factories/define-templates.d.ts.map +1 -0
  116. package/{factories → dist/factories}/define-variables.d.ts +1 -0
  117. package/dist/factories/define-variables.d.ts.map +1 -0
  118. package/dist/factories/index.cjs +1 -0
  119. package/{factories → dist/factories}/index.d.ts +1 -0
  120. package/dist/factories/index.d.ts.map +1 -0
  121. package/dist/factories/index.js +149 -0
  122. package/{generators → dist/generators}/class-name-generator.d.ts +1 -0
  123. package/dist/generators/class-name-generator.d.ts.map +1 -0
  124. package/dist/generators/index.cjs +1 -0
  125. package/{generators → dist/generators}/index.d.ts +1 -0
  126. package/dist/generators/index.d.ts.map +1 -0
  127. package/dist/generators/index.js +2 -0
  128. package/{generators → dist/generators}/styled-generator.d.ts +1 -0
  129. package/dist/generators/styled-generator.d.ts.map +1 -0
  130. package/{generators → dist/generators}/styles-generator.d.ts +1 -0
  131. package/dist/generators/styles-generator.d.ts.map +1 -0
  132. package/dist/generators-CrK45F8i.js +112 -0
  133. package/dist/generators-eEKEtyAm.cjs +1 -0
  134. package/{helpers → dist/helpers}/color.d.ts +1 -0
  135. package/dist/helpers/color.d.ts.map +1 -0
  136. package/dist/helpers/index.cjs +1 -0
  137. package/{helpers → dist/helpers}/index.d.ts +1 -0
  138. package/dist/helpers/index.d.ts.map +1 -0
  139. package/dist/helpers/index.js +33 -0
  140. package/{helpers → dist/helpers}/viewport-clamp.d.ts +1 -0
  141. package/dist/helpers/viewport-clamp.d.ts.map +1 -0
  142. package/dist/instances/classname-instance.cjs +1 -0
  143. package/{instances → dist/instances}/classname-instance.d.ts +1 -0
  144. package/dist/instances/classname-instance.d.ts.map +1 -0
  145. package/dist/instances/classname-instance.js +18 -0
  146. package/dist/main-DGpSu6zK.js +545 -0
  147. package/dist/main-LnoqOq21.cjs +11 -0
  148. package/dist/maybe.d.ts +2 -0
  149. package/dist/maybe.d.ts.map +1 -0
  150. package/dist/parse-styles-2rwbF9j_.cjs +3 -0
  151. package/dist/parse-styles-Bz0otiZ-.js +336 -0
  152. package/dist/parsers/index.cjs +3 -0
  153. package/{parsers → dist/parsers}/index.d.ts +1 -0
  154. package/dist/parsers/index.d.ts.map +1 -0
  155. package/dist/parsers/index.js +79 -0
  156. package/{parsers → dist/parsers}/parse-modifiers.d.ts +1 -0
  157. package/dist/parsers/parse-modifiers.d.ts.map +1 -0
  158. package/{parsers → dist/parsers}/parse-styles.d.ts +1 -0
  159. package/dist/parsers/parse-styles.d.ts.map +1 -0
  160. package/{parsers → dist/parsers}/parse-templates.d.ts +1 -0
  161. package/dist/parsers/parse-templates.d.ts.map +1 -0
  162. package/{parsers → dist/parsers}/parse-tokens.d.ts +1 -0
  163. package/dist/parsers/parse-tokens.d.ts.map +1 -0
  164. package/{parsers → dist/parsers}/parser-regexes.d.ts +1 -0
  165. package/dist/parsers/parser-regexes.d.ts.map +1 -0
  166. package/{parsers → dist/parsers}/parser-types.d.ts +1 -0
  167. package/dist/parsers/parser-types.d.ts.map +1 -0
  168. package/{parsers → dist/parsers}/property-name-check.d.ts +1 -0
  169. package/dist/parsers/property-name-check.d.ts.map +1 -0
  170. package/{parsers → dist/parsers}/resolve-template-variants.d.ts +1 -0
  171. package/dist/parsers/resolve-template-variants.d.ts.map +1 -0
  172. package/{parsers → dist/parsers}/strict.d.ts +1 -0
  173. package/dist/parsers/strict.d.ts.map +1 -0
  174. package/{parsers → dist/parsers}/unit-check.d.ts +1 -0
  175. package/dist/parsers/unit-check.d.ts.map +1 -0
  176. package/dist/runtime/index.cjs +2 -0
  177. package/{runtime → dist/runtime}/index.d.ts +1 -0
  178. package/dist/runtime/index.d.ts.map +1 -0
  179. package/dist/runtime/index.js +20 -0
  180. package/dist/salty-compiler-Bvd0OKHz.cjs +33 -0
  181. package/dist/salty-compiler-CvQ-rsex.js +484 -0
  182. package/dist/salty.config-B0ZiRpHR.cjs +7 -0
  183. package/dist/salty.config-DWF4i7K0.js +4 -0
  184. package/dist/server/index.cjs +1 -0
  185. package/dist/server/index.d.ts +2 -0
  186. package/dist/server/index.d.ts.map +1 -0
  187. package/dist/server/index.js +12 -0
  188. package/{server → dist/server}/should-restart.d.ts +1 -0
  189. package/dist/server/should-restart.d.ts.map +1 -0
  190. package/{styled-file-Cda3EeR6.js → dist/styled-file-BCbAEzBB.cjs} +2 -5
  191. package/dist/styled-file-C_4eLAdV.js +4 -0
  192. package/dist/styled-file-DQHLzmuL.js +4 -0
  193. package/{styled-file-DLcgYmGN.js → dist/styled-file-DorArlCk.cjs} +2 -5
  194. package/{templates → dist/templates}/salty-reset.d.ts +1 -0
  195. package/dist/templates/salty-reset.d.ts.map +1 -0
  196. package/dist/templates-BGHLaAOm.cjs +1 -0
  197. package/dist/templates-DWWLjEiU.js +4 -0
  198. package/{types → dist/types}/cli-types.d.ts +1 -0
  199. package/dist/types/cli-types.d.ts.map +1 -0
  200. package/{types → dist/types}/config-types.d.ts +1 -0
  201. package/dist/types/config-types.d.ts.map +1 -0
  202. package/{types → dist/types}/font-types.d.ts +1 -0
  203. package/dist/types/font-types.d.ts.map +1 -0
  204. package/dist/types/index.cjs +0 -0
  205. package/{types → dist/types}/index.d.ts +1 -0
  206. package/dist/types/index.d.ts.map +1 -0
  207. package/dist/types/index.js +0 -0
  208. package/{types → dist/types}/util-types.d.ts +1 -0
  209. package/dist/types/util-types.d.ts.map +1 -0
  210. package/{util → dist/util}/camel-case.d.ts +1 -0
  211. package/dist/util/camel-case.d.ts.map +1 -0
  212. package/{util → dist/util}/dash-case.d.ts +1 -0
  213. package/dist/util/dash-case.d.ts.map +1 -0
  214. package/{util → dist/util}/dot-case.d.ts +1 -0
  215. package/dist/util/dot-case.d.ts.map +1 -0
  216. package/{util → dist/util}/glob-match.d.ts +1 -0
  217. package/dist/util/glob-match.d.ts.map +1 -0
  218. package/dist/util/index.cjs +1 -0
  219. package/{util → dist/util}/index.d.ts +1 -0
  220. package/dist/util/index.d.ts.map +1 -0
  221. package/dist/util/index.js +72 -0
  222. package/{util → dist/util}/module-type.d.ts +1 -0
  223. package/dist/util/module-type.d.ts.map +1 -0
  224. package/{util → dist/util}/pascal-case.d.ts +1 -0
  225. package/dist/util/pascal-case.d.ts.map +1 -0
  226. package/{util → dist/util}/to-hash.d.ts +1 -0
  227. package/dist/util/to-hash.d.ts.map +1 -0
  228. package/dist/vanilla-file-BEqMIe-6.js +4 -0
  229. package/{vanilla-file-1kOqbCIM.js → dist/vanilla-file-Z3VsOa_U.cjs} +2 -5
  230. package/dist/viewport-clamp-CHOyzt37.cjs +1 -0
  231. package/dist/viewport-clamp-CRtzRvJ3.js +7 -0
  232. package/package.json +67 -64
  233. package/README.md +0 -535
  234. package/astro-component-5hrNTCJ5.js +0 -4
  235. package/astro-component-Dj3enX6K.cjs +0 -4
  236. package/bin/index.cjs +0 -4
  237. package/bin/index.d.ts +0 -2
  238. package/bin/index.js +0 -3
  239. package/bin/main.cjs +0 -783
  240. package/bin/main.js +0 -782
  241. package/bin/templates.d.ts +0 -14
  242. package/class-name-generator-BcbeZdcV.cjs +0 -88
  243. package/class-name-generator-DJ27JHW_.js +0 -89
  244. package/compiler/get-files.cjs +0 -25
  245. package/compiler/get-files.js +0 -25
  246. package/compiler/get-function-range.cjs +0 -22
  247. package/compiler/get-function-range.js +0 -22
  248. package/compiler/helpers.cjs +0 -34
  249. package/compiler/helpers.js +0 -33
  250. package/compiler/salty-compiler.cjs +0 -845
  251. package/compiler/salty-compiler.js +0 -827
  252. package/config/index.cjs +0 -20
  253. package/config/index.js +0 -20
  254. package/css/index.cjs +0 -12
  255. package/css/index.js +0 -12
  256. package/css/keyframes.cjs +0 -49
  257. package/css/keyframes.js +0 -49
  258. package/css/media.cjs +0 -93
  259. package/css/media.js +0 -93
  260. package/css/merge.cjs +0 -20
  261. package/css/merge.js +0 -20
  262. package/css/token.cjs +0 -4
  263. package/css/token.js +0 -4
  264. package/define-templates-CVhhgPnd.js +0 -60
  265. package/define-templates-Deq1aCbN.cjs +0 -59
  266. package/factories/index.cjs +0 -177
  267. package/factories/index.js +0 -177
  268. package/generators/index.cjs +0 -58
  269. package/generators/index.js +0 -59
  270. package/glob-match-C28iYp1A.js +0 -74
  271. package/glob-match-CT1uFlp-.cjs +0 -73
  272. package/helpers/index.cjs +0 -53
  273. package/helpers/index.js +0 -53
  274. package/index-ByR0nfaf.cjs +0 -4
  275. package/index-DKz1QXqs.js +0 -4
  276. package/instances/classname-instance.cjs +0 -31
  277. package/instances/classname-instance.js +0 -31
  278. package/parse-styles-BlUpavVg.js +0 -521
  279. package/parse-styles-DWT4tDyS.cjs +0 -520
  280. package/parsers/index.cjs +0 -147
  281. package/parsers/index.js +0 -148
  282. package/pascal-case-By_l58S-.cjs +0 -7
  283. package/pascal-case-F3Usi5Wf.js +0 -8
  284. package/runtime/index.cjs +0 -24
  285. package/runtime/index.js +0 -24
  286. package/salty.config-DogY_sSQ.cjs +0 -4
  287. package/salty.config-GV37Q-D2.js +0 -4
  288. package/server/index.cjs +0 -4
  289. package/server/index.d.ts +0 -1
  290. package/server/index.js +0 -4
  291. package/should-restart-CQsyHls3.cjs +0 -17
  292. package/should-restart-CXIO0jxY.js +0 -18
  293. package/styled-file-BzmB9_Ez.cjs +0 -12
  294. package/styled-file-CPd_rTW2.cjs +0 -11
  295. package/to-hash-DSoCPs8D.js +0 -33
  296. package/to-hash-DT2ImSPA.cjs +0 -32
  297. package/types/index.cjs +0 -1
  298. package/types/index.js +0 -1
  299. package/util/index.cjs +0 -18
  300. package/util/index.js +0 -18
  301. package/vanilla-file-r0fp2q_m.cjs +0 -18
  302. package/viewport-clamp-CEmzmcSj.cjs +0 -10
  303. package/viewport-clamp-K553uXu3.js +0 -11
  304. /package/{.saltyrc.schema.json → dist/.saltyrc.schema.json} +0 -0
@@ -1,827 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
- import * as esbuild from "esbuild";
5
- import { resolve, dirname, relative, join, basename, parse } from "path";
6
- import { createLogger, transports, format } from "winston";
7
- import { readFile } from "fs/promises";
8
- import { existsSync, mkdirSync, copyFileSync, readFileSync, statSync, readdirSync, writeFileSync } from "fs";
9
- import { execSync } from "child_process";
10
- import { isSaltyFile, resolveExportValue, saltyFileExtensions } from "./helpers.js";
11
- import { t as toHash, d as dashCase } from "../to-hash-DSoCPs8D.js";
12
- import { n as normalizePath, i as isPathAllowed } from "../glob-match-C28iYp1A.js";
13
- import { d as defineTemplates } from "../define-templates-CVhhgPnd.js";
14
- import { createRequire } from "module";
15
- import { p as parseAndJoinStyles, c as parseVariableTokens } from "../parse-styles-BlUpavVg.js";
16
- import { mergeObjects, mergeFactories } from "../css/merge.js";
17
- import { getPackageJson } from "./get-files.js";
18
- import { parseTemplates, getTemplateTypes, getTemplateVariantMaps } from "../parsers/index.js";
19
- import console from "console";
20
- const logger = createLogger({
21
- level: "debug",
22
- format: format.combine(format.colorize(), format.cli()),
23
- transports: [new transports.Console({})]
24
- });
25
- const logError = (message) => {
26
- logger.error(message);
27
- };
28
- const EXTERNAL_URL = /^(?:[a-z][a-z0-9+.-]*:)?\/\//i;
29
- const normaliseSpec = (spec) => {
30
- if (typeof spec === "string") return { url: spec };
31
- return spec;
32
- };
33
- const ensureRelativePrefix = (path) => {
34
- if (path.startsWith(".") || path.startsWith("/")) return path;
35
- return `./${path}`;
36
- };
37
- const toPosix = (path) => path.split("\\").join("/");
38
- const defaultResolveModule = (specifier, sourceFile) => {
39
- return createRequire(sourceFile).resolve(specifier);
40
- };
41
- const defaultCopyAsset = (from, to) => {
42
- const dir = dirname(to);
43
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
44
- copyFileSync(from, to);
45
- };
46
- const buildRule = (url, { media, supports }) => {
47
- let rule = `@import url('${url}')`;
48
- if (supports) rule += ` supports(${supports})`;
49
- if (media) rule += ` ${media}`;
50
- return `${rule};`;
51
- };
52
- const resolveImport = (spec, sourceFile, destDir, options = {}) => {
53
- const opts = normaliseSpec(spec);
54
- const { url } = opts;
55
- const resolveModule = options.resolveModule ?? defaultResolveModule;
56
- const copyAsset = options.copyAsset ?? defaultCopyAsset;
57
- if (EXTERNAL_URL.test(url)) {
58
- return { rule: buildRule(url, opts) };
59
- }
60
- if (url.startsWith("/")) {
61
- return { rule: buildRule(url, opts) };
62
- }
63
- if (url.startsWith("./") || url.startsWith("../")) {
64
- const absolute2 = resolve(dirname(sourceFile), url);
65
- const fromImportsFile = relative(join(destDir, "css"), absolute2);
66
- return { rule: buildRule(ensureRelativePrefix(toPosix(fromImportsFile)), opts) };
67
- }
68
- const specifier = url.startsWith("~") ? url.slice(1) : url;
69
- const absolute = resolveModule(specifier, sourceFile);
70
- const hash = toHash(absolute, 6);
71
- const fileName = `${hash}-${basename(absolute)}`;
72
- const destPath = join(destDir, "imports", fileName);
73
- copyAsset(absolute, destPath);
74
- return { rule: buildRule(`../imports/${fileName}`, opts) };
75
- };
76
- const readPackageJsonModule = async (dirname2) => {
77
- const packageJsonContent = await getPackageJson(dirname2);
78
- if (!packageJsonContent) return void 0;
79
- return packageJsonContent.type;
80
- };
81
- let cachedModuleType;
82
- const detectCurrentModuleType = async (dirname2) => {
83
- if (cachedModuleType) return cachedModuleType;
84
- const packageJsonModule = await readPackageJsonModule(dirname2);
85
- if (packageJsonModule === "module") cachedModuleType = "esm";
86
- else if (packageJsonModule === "commonjs") cachedModuleType = "cjs";
87
- else if (import.meta.url.endsWith(".cjs")) cachedModuleType = "cjs";
88
- return cachedModuleType || "esm";
89
- };
90
- function dotCase(str) {
91
- if (!str) return "";
92
- if (typeof str !== "string") return dotCase(String(str));
93
- return str.replace(/[^\d\w]/g, ".");
94
- }
95
- const saltyReset = {
96
- /** Set box model to border-box */
97
- "*, *::before, *::after": {
98
- boxSizing: "border-box"
99
- },
100
- /** Remove default margin and padding */
101
- "*": {
102
- margin: 0
103
- },
104
- /** Remove adjust font properties */
105
- html: {
106
- lineHeight: 1.15,
107
- textSizeAdjust: "100%",
108
- WebkitFontSmoothing: "antialiased"
109
- },
110
- /** Make media elements responsive */
111
- "img, picture, video, canvas, svg": {
112
- display: "block",
113
- maxWidth: "100%"
114
- },
115
- /** Avoid overflow of text */
116
- "p, h1, h2, h3, h4, h5, h6": {
117
- overflowWrap: "break-word"
118
- },
119
- /** Improve text wrapping */
120
- p: {
121
- textWrap: "pretty"
122
- },
123
- "h1, h2, h3, h4, h5, h6": {
124
- textWrap: "balance"
125
- },
126
- /** Improve link color */
127
- a: {
128
- color: "currentColor"
129
- },
130
- /** Improve button line height */
131
- button: {
132
- lineHeight: "1em",
133
- color: "currentColor"
134
- },
135
- /** Improve form elements */
136
- "input, optgroup, select, textarea": {
137
- fontFamily: "inherit",
138
- fontSize: "100%",
139
- lineHeight: "1.15em"
140
- }
141
- };
142
- class SaltyCompiler {
143
- constructor(projectRootDir, options = {}) {
144
- __publicField(this, "importFile", (path) => {
145
- const now = Date.now();
146
- return import(
147
- /* @vite-ignore */
148
- `${path}?t=${now}`
149
- );
150
- });
151
- __publicField(this, "cache", {
152
- rcFile: null,
153
- destDir: null,
154
- externalModules: []
155
- });
156
- /**
157
- * Locate and read the .saltyrc.json file starting from the current directory and moving up the directory tree.
158
- * Caches the result to avoid redundant file reads.
159
- */
160
- __publicField(this, "readRCFile", async (currentDir = this.projectRootDir) => {
161
- if (this.cache.rcFile) return this.cache.rcFile;
162
- if (currentDir === "/") throw new Error("Could not find .saltyrc.json file");
163
- const rcPath = join(currentDir, ".saltyrc.json");
164
- const rcContent = await readFile(rcPath, "utf-8").then(JSON.parse).catch(() => void 0);
165
- if (!rcContent) return this.readRCFile(join(currentDir, ".."));
166
- this.cache.rcFile = rcContent;
167
- return rcContent;
168
- });
169
- /**
170
- * Get the project configuration from the .saltyrc.json file based on the current directory.
171
- * If no specific project configuration is found, it falls back to the default project.
172
- */
173
- __publicField(this, "getRCProjectConfig", async (dirname2) => {
174
- var _a, _b;
175
- const rcFile = await this.readRCFile(dirname2);
176
- const projectConfig = (_a = rcFile.projects) == null ? void 0 : _a.find((project) => dirname2.endsWith(project.dir || ""));
177
- if (!projectConfig) return (_b = rcFile.projects) == null ? void 0 : _b.find((project) => project.dir === rcFile.defaultProject);
178
- return projectConfig;
179
- });
180
- /**
181
- * Read the optional `include` / `exclude` glob filters for the current project from
182
- * `.saltyrc.json`. Used to scope which files the compiler discovers and watches.
183
- */
184
- __publicField(this, "getPathFilter", async () => {
185
- const projectConfig = await this.getRCProjectConfig(this.projectRootDir);
186
- return { include: projectConfig == null ? void 0 : projectConfig.include, exclude: projectConfig == null ? void 0 : projectConfig.exclude };
187
- });
188
- /**
189
- * Whether a file should be compiled: it must be a salty file and pass the project's
190
- * `include` / `exclude` filters. `relPath` is the path relative to the project root.
191
- */
192
- __publicField(this, "isAllowedSaltyFile", (file, filter) => {
193
- if (!isSaltyFile(file)) return false;
194
- const relPath = normalizePath(relative(this.projectRootDir, file));
195
- return isPathAllowed(relPath, filter);
196
- });
197
- __publicField(this, "getExternalModules", (coreConfigPath) => {
198
- if (this.cache.externalModules.length > 0) return this.cache.externalModules;
199
- const content = readFileSync(coreConfigPath, "utf8");
200
- const match = content.match(/externalModules:\s?\[(.*)\]/);
201
- if (!match) return [];
202
- const externalModules = match[1].split(",").map((d) => d.replace(/['"`]/g, "").trim());
203
- this.cache.externalModules = externalModules;
204
- return externalModules;
205
- });
206
- /**
207
- * Get the destination directory for generated files based on the project configuration.
208
- * Caches the result to avoid redundant computations.
209
- */
210
- __publicField(this, "getDestDir", async () => {
211
- if (this.cache.destDir) return this.cache.destDir;
212
- const projectConfig = await this.getRCProjectConfig(this.projectRootDir);
213
- const destDir = join(this.projectRootDir, (projectConfig == null ? void 0 : projectConfig.saltygenDir) || "saltygen");
214
- this.cache.destDir = destDir;
215
- return destDir;
216
- });
217
- __publicField(this, "generateConfig", async () => {
218
- const rcProject = await this.getRCProjectConfig(this.projectRootDir);
219
- const destDir = await this.getDestDir();
220
- const coreConfigPath = join(this.projectRootDir, (rcProject == null ? void 0 : rcProject.configDir) || "", "salty.config.ts");
221
- const coreConfigDest = join(destDir, "salty.config.js");
222
- const moduleType = await detectCurrentModuleType(this.projectRootDir);
223
- const externalModules = this.getExternalModules(coreConfigPath);
224
- await esbuild.build({
225
- entryPoints: [coreConfigPath],
226
- minify: true,
227
- treeShaking: true,
228
- bundle: true,
229
- outfile: coreConfigDest,
230
- format: moduleType,
231
- external: externalModules
232
- });
233
- const { config } = await this.importFile(coreConfigDest);
234
- return { config, path: coreConfigDest };
235
- });
236
- __publicField(this, "addConfigCache", (currentFile) => {
237
- try {
238
- const saltyCachedConfig = readFileSync(join(this.projectRootDir, "saltygen/cache/config-cache.json"), "utf8");
239
- if (!saltyCachedConfig) return `globalThis.saltyConfig = {};
240
-
241
- ${currentFile}`;
242
- return `globalThis.saltyConfig = ${saltyCachedConfig};
243
-
244
- ${currentFile}`;
245
- } catch {
246
- return currentFile;
247
- }
248
- });
249
- __publicField(this, "getConfigCache", async () => {
250
- const destDir = await this.getDestDir();
251
- const coreConfigDest = join(destDir, "cache/config-cache.json");
252
- const contents = readFileSync(coreConfigDest, "utf8");
253
- if (!contents) throw new Error("Could not find config cache file");
254
- return JSON.parse(contents);
255
- });
256
- __publicField(this, "getConfig", async () => {
257
- const cached = await this.getConfigCache();
258
- const destDir = await this.getDestDir();
259
- const coreConfigDest = join(destDir, "salty.config.js");
260
- const { config } = await this.importFile(coreConfigDest);
261
- return mergeObjects(cached, config);
262
- });
263
- /**
264
- * Generate CSS files based on the Salty CSS configuration and source files.
265
- */
266
- __publicField(this, "generateCss", async (clean = true) => {
267
- try {
268
- const start = Date.now();
269
- if (this.isProduction) logger.info("Generating CSS in production mode! 🔥");
270
- else logger.info("Generating CSS in development mode! 🚀");
271
- const globalCssFiles = [];
272
- const cssFiles = [];
273
- const destDir = await this.getDestDir();
274
- const cssFile = join(destDir, "index.css");
275
- const clearDistDir = () => {
276
- if (existsSync(destDir)) execSync("rm -rf " + destDir);
277
- mkdirSync(destDir, { recursive: true });
278
- mkdirSync(join(destDir, "css"));
279
- mkdirSync(join(destDir, "types"));
280
- mkdirSync(join(destDir, "js"));
281
- mkdirSync(join(destDir, "cache"));
282
- mkdirSync(join(destDir, "imports"));
283
- };
284
- if (clean) clearDistDir();
285
- const files = /* @__PURE__ */ new Set();
286
- const configFiles = /* @__PURE__ */ new Set();
287
- const pathFilter = await this.getPathFilter();
288
- const { exclude } = pathFilter;
289
- const projectRootDir = this.projectRootDir;
290
- async function collectFiles(src) {
291
- const foldersToSkip = ["node_modules", "saltygen"];
292
- const stats = statSync(src);
293
- if (stats.isDirectory()) {
294
- const shouldSkip = foldersToSkip.some((folder) => src.includes(folder));
295
- if (shouldSkip) return;
296
- if (exclude == null ? void 0 : exclude.length) {
297
- const relDir = normalizePath(relative(projectRootDir, src));
298
- if (relDir && !isPathAllowed(relDir, { exclude })) return;
299
- }
300
- const files2 = readdirSync(src);
301
- await Promise.all(files2.map((file) => collectFiles(join(src, file))));
302
- } else if (stats.isFile()) {
303
- const validFile = isSaltyFile(src) && isPathAllowed(normalizePath(relative(projectRootDir, src)), pathFilter);
304
- if (validFile) {
305
- files.add(src);
306
- const contents = readFileSync(src, "utf8");
307
- const hasDefineFunction = /define[\w\d]+\(/.test(contents);
308
- if (hasDefineFunction) configFiles.add(src);
309
- }
310
- }
311
- }
312
- await collectFiles(this.projectRootDir);
313
- await this.generateConfigStyles(configFiles);
314
- const generationResults = {
315
- keyframes: [],
316
- components: [],
317
- classNames: []
318
- };
319
- await Promise.all(
320
- [...files].map(async (src) => {
321
- const { contents } = await this.compileSaltyFile(src, destDir);
322
- for (const [name, value] of Object.entries(contents)) {
323
- const resolved = await resolveExportValue(value, 1);
324
- if (resolved.isKeyframes) {
325
- generationResults.keyframes.push({
326
- value: resolved,
327
- src,
328
- name
329
- });
330
- } else if (resolved.isClassName) {
331
- generationResults.classNames.push({
332
- ...value,
333
- src,
334
- name
335
- });
336
- } else if (resolved.generator) {
337
- generationResults.components.push({
338
- ...value,
339
- src,
340
- name
341
- });
342
- }
343
- }
344
- })
345
- );
346
- const config = await this.getConfig();
347
- for (const keyframes of generationResults.keyframes) {
348
- const { value } = keyframes;
349
- const fileName = `a_${value.animationName}.css`;
350
- const filePath = `css/${fileName}`;
351
- const cssPath = join(destDir, filePath);
352
- globalCssFiles.push(fileName);
353
- writeFileSync(cssPath, value.css);
354
- }
355
- const localCssFiles = {};
356
- for (const componentResult of generationResults.components) {
357
- const { src, name } = componentResult;
358
- if (!localCssFiles[src]) localCssFiles[src] = [];
359
- const generator = componentResult.generator._withBuildContext({
360
- callerName: name,
361
- isProduction: this.isProduction,
362
- config
363
- });
364
- if (!cssFiles[generator.priority]) cssFiles[generator.priority] = [];
365
- const styles = await generator.css;
366
- if (!styles) continue;
367
- cssFiles[generator.priority].push(generator.cssFileName);
368
- const filePath = `css/${generator.cssFileName}`;
369
- const cssPath = join(destDir, filePath);
370
- writeFileSync(cssPath, styles);
371
- if (config.importStrategy === "component") {
372
- localCssFiles[src].push(generator.cssFileName);
373
- }
374
- }
375
- for (const classNameResult of generationResults.classNames) {
376
- const { src, name } = classNameResult;
377
- if (!localCssFiles[src]) localCssFiles[src] = [];
378
- const generator = classNameResult.generator._withBuildContext({
379
- callerName: name,
380
- isProduction: this.isProduction,
381
- config
382
- });
383
- const styles = await generator.css;
384
- if (!styles) continue;
385
- if (!cssFiles[generator.priority]) cssFiles[generator.priority] = [];
386
- cssFiles[generator.priority].push(generator.cssFileName);
387
- const filePath = `css/${generator.cssFileName}`;
388
- const cssPath = join(destDir, filePath);
389
- writeFileSync(cssPath, styles);
390
- if (config.importStrategy === "component") {
391
- localCssFiles[src].push(generator.cssFileName);
392
- }
393
- }
394
- if (config.importStrategy === "component") {
395
- Object.entries(localCssFiles).forEach(([src, localCssFile]) => {
396
- const cssContent2 = localCssFile.map((file) => `@import url('./${file}');`).join("\n");
397
- const hashName = toHash(src, 6);
398
- const parsedPath = parse(src);
399
- const dasherized = dashCase(parsedPath.name);
400
- const cssFile2 = join(destDir, `css/f_${dasherized}-${hashName}.css`);
401
- writeFileSync(cssFile2, cssContent2 || `/* Empty file */`);
402
- });
403
- }
404
- const otherGlobalCssFiles = globalCssFiles.map((file) => `@import url('./css/${file}');`).join("\n");
405
- const globalCssFilenames = ["_imports.css", "_variables.css", "_reset.css", "_global.css", "_templates.css", "_fonts.css"];
406
- const importsWithData = globalCssFilenames.filter((file) => {
407
- try {
408
- const data = readFileSync(join(destDir, "css", file), "utf8");
409
- return data.length > 0;
410
- } catch {
411
- return false;
412
- }
413
- });
414
- const globalImports = importsWithData.map((file) => {
415
- const layerSuffix = file === "_imports.css" ? " layer(imports)" : "";
416
- return `@import url('./css/${file}')${layerSuffix};`;
417
- });
418
- const generatorText = "/*!\n * Generated with Salty CSS (https://salty-css.dev)\n * Do not edit this file directly\n */\n";
419
- let cssContent = `${generatorText}@layer imports, reset, global, templates, fonts, l0, l1, l2, l3, l4, l5, l6, l7, l8;
420
-
421
- ${globalImports.join(
422
- "\n"
423
- )}
424
- ${otherGlobalCssFiles}`;
425
- if (config.importStrategy !== "component") {
426
- const mergedContent = cssFiles.reduce((acc, val, layer) => {
427
- const layerContent = val.reduce((layerAcc, file) => {
428
- var _a;
429
- const filepath = join(destDir, "css", file);
430
- const css = readFileSync(filepath, "utf8");
431
- const filepathHash = ((_a = /.*-([^-]+)-\d+.css/.exec(file)) == null ? void 0 : _a.at(1)) || toHash(filepath, 6);
432
- if (layerAcc.includes(filepathHash)) return layerAcc;
433
- return `${layerAcc}
434
- /*start:${filepathHash}-${file}*/
435
- ${css}
436
- /*end:${filepathHash}*/
437
- `;
438
- }, "");
439
- const layerFileName = `l_${layer}.css`;
440
- const layerFilePath = join(destDir, "css", layerFileName);
441
- const layerContentWithLayer = `@layer l${layer} { ${layerContent}
442
- }`;
443
- writeFileSync(layerFilePath, layerContentWithLayer);
444
- return `${acc}
445
- @import url('./css/${layerFileName}');`;
446
- }, "");
447
- cssContent += mergedContent;
448
- }
449
- writeFileSync(cssFile, cssContent);
450
- const end = Date.now();
451
- const time = end - start;
452
- const emoji = time < 200 ? "🔥" : time < 500 ? "🚀" : time < 1e3 ? "🎉" : time < 2e3 ? "🚗" : time < 5e3 ? "🤔" : "🥴";
453
- logger.info(`Generated CSS in ${time}ms! ${emoji}`);
454
- } catch (e) {
455
- console.error(e);
456
- }
457
- });
458
- __publicField(this, "generateConfigStyles", async (configFiles) => {
459
- var _a, _b;
460
- const destDir = await this.getDestDir();
461
- const generationResults = {
462
- mediaQueries: [],
463
- globalStyles: [],
464
- variables: [],
465
- templates: [],
466
- imports: [],
467
- fonts: []
468
- };
469
- await Promise.all(
470
- [...configFiles].map(async (src) => {
471
- const { contents, outputFilePath } = await this.compileSaltyFile(src, destDir);
472
- Object.entries(contents).forEach(([name, value]) => {
473
- if (value.isMedia) generationResults.mediaQueries.push([name, value]);
474
- else if (value.isGlobalDefine) generationResults.globalStyles.push(value);
475
- else if (value.isDefineVariables) generationResults.variables.push(value);
476
- else if (value.isDefineTemplates) generationResults.templates.push(value._setPath(`${name};;${outputFilePath}`));
477
- else if (value.isDefineImport) generationResults.imports.push(value._setPath(src));
478
- else if (value.isDefineFont) generationResults.fonts.push(value);
479
- });
480
- })
481
- );
482
- const { config, path: configPath } = await this.generateConfig();
483
- const configCacheContent = { ...config };
484
- const { mediaQueries } = generationResults;
485
- configCacheContent.mediaQueries = Object.fromEntries(mediaQueries.map(([name, value]) => [`@${name}`, value]));
486
- const mediaQueryKeys = mediaQueries.map(([name]) => `'@${name}'`).join(" | ");
487
- const variableTokens = /* @__PURE__ */ new Set();
488
- const parseVariables = async (obj, path = []) => {
489
- if (!obj) return [];
490
- const promises = Object.entries(obj).map(async ([key, value]) => {
491
- const parseVariable = async (value2) => {
492
- if (!value2) return void 0;
493
- if (value2 instanceof Promise) return await parseVariable(await value2);
494
- if (typeof value2 === "function") return await parseVariable(await value2());
495
- if (typeof value2 === "object") return await parseVariables(value2, [...path, key]);
496
- const dottedKey = dotCase(key);
497
- const dashedKey = dashCase(key);
498
- const tsName = [...path, dottedKey].join(".");
499
- variableTokens.add(`"${tsName}"`);
500
- const cssName = [...path.map(dashCase), dashedKey].join("-");
501
- const result = parseVariableTokens(value2);
502
- if (!result) return `--${cssName}: ${value2};`;
503
- return `--${cssName}: ${result.transformed};`;
504
- };
505
- return await parseVariable(value);
506
- });
507
- const results = await Promise.all(promises);
508
- return results.flat();
509
- };
510
- const parseResponsiveVariables = async (obj) => {
511
- if (!obj) return [];
512
- const promises = Object.entries(obj).map(async ([mediaQuery, values]) => {
513
- const variables = await parseVariables(values);
514
- if (mediaQuery === "base") return variables.join("");
515
- if (configCacheContent.mediaQueries[mediaQuery]) {
516
- const mediaQueryValue = configCacheContent.mediaQueries[mediaQuery];
517
- return `${mediaQueryValue} { ${variables.join("")} }`;
518
- }
519
- return `${mediaQuery} { ${variables.join("")} }`;
520
- });
521
- const results = await Promise.all(promises);
522
- return results.flat();
523
- };
524
- const parseConditionalVariables = async (obj) => {
525
- if (!obj) return [];
526
- const promises = Object.entries(obj).map(async ([property, conditions]) => {
527
- const promises2 = Object.entries(conditions).map(async ([condition, values]) => {
528
- const variables = await parseVariables(values, [property]);
529
- const conditionScope = `.${property}-${condition}, [data-${property}="${condition}"]`;
530
- const combined = variables.join("");
531
- return `${conditionScope} { ${combined} }`;
532
- });
533
- const result = await Promise.all(promises2);
534
- return result.flat();
535
- });
536
- const results = await Promise.all(promises);
537
- return results.flat();
538
- };
539
- const getStaticVariables = (variables = {}) => {
540
- return { ...variables, responsive: void 0, conditional: void 0 };
541
- };
542
- const getGeneratedVariables = (type) => {
543
- return generationResults.variables.map((factory) => {
544
- if (type === "static") return getStaticVariables(factory._current);
545
- return factory._current[type];
546
- });
547
- };
548
- const _staticVariables = mergeObjects(getStaticVariables(config.variables), getGeneratedVariables("static"));
549
- const staticVariables = await parseVariables(_staticVariables);
550
- const _responsiveVariables = mergeObjects((_a = config.variables) == null ? void 0 : _a.responsive, getGeneratedVariables("responsive"));
551
- const responsiveVariables = await parseResponsiveVariables(_responsiveVariables);
552
- const _conditionalVariables = mergeObjects((_b = config.variables) == null ? void 0 : _b.conditional, getGeneratedVariables("conditional"));
553
- const conditionalVariables = await parseConditionalVariables(_conditionalVariables);
554
- const variablesPath = join(destDir, "css/_variables.css");
555
- const variablesCss = `:root { ${staticVariables.join("")} ${responsiveVariables.join("")} } ${conditionalVariables.join("")}`;
556
- writeFileSync(variablesPath, variablesCss);
557
- configCacheContent.staticVariables = _staticVariables;
558
- const globalStylesPath = join(destDir, "css/_global.css");
559
- const mergedGlobalStyles = mergeObjects(config.global, generationResults.globalStyles);
560
- const globalStylesString = await parseAndJoinStyles(mergedGlobalStyles, "");
561
- writeFileSync(globalStylesPath, `@layer global { ${globalStylesString} }`);
562
- const resetStylesPath = join(destDir, "css/_reset.css");
563
- const getResetStyles = () => {
564
- if (config.reset === "none") return {};
565
- if (typeof config.reset === "object") return config.reset;
566
- return saltyReset;
567
- };
568
- const resetStyles = getResetStyles();
569
- const resetStylesString = await parseAndJoinStyles(resetStyles, "");
570
- writeFileSync(resetStylesPath, `@layer reset { ${resetStylesString} }`);
571
- const templateStylesPath = join(destDir, "css/_templates.css");
572
- const templates = mergeObjects(config.templates, generationResults.templates);
573
- const templateStylesString = await parseTemplates(templates);
574
- const templateTokens = getTemplateTypes(templates);
575
- const templateVariantMaps = getTemplateVariantMaps(templates);
576
- writeFileSync(templateStylesPath, `@layer templates { ${templateStylesString} }`);
577
- configCacheContent.templates = templates;
578
- const importsPath = join(destDir, "css/_imports.css");
579
- const importRules = [];
580
- for (const factory of generationResults.imports) {
581
- const sourceFile = factory._path;
582
- if (!sourceFile) continue;
583
- for (const spec of factory._current) {
584
- try {
585
- const { rule } = resolveImport(spec, sourceFile, destDir);
586
- importRules.push(rule);
587
- } catch (e) {
588
- const url = typeof spec === "string" ? spec : spec.url;
589
- logger.error(`Failed to resolve defineImport(${JSON.stringify(url)}) from ${sourceFile}: ${e.message}`);
590
- }
591
- }
592
- }
593
- writeFileSync(importsPath, importRules.join("\n"));
594
- const configTemplateFactories = config.templates ? [defineTemplates(config.templates)._setPath(`config;;${configPath}`)] : [];
595
- const templateFactories = mergeFactories(generationResults.templates, configTemplateFactories);
596
- configCacheContent.templatePaths = Object.fromEntries(Object.entries(templateFactories).map(([key, faktory]) => [key, faktory._path]));
597
- const fontsStylesPath = join(destDir, "css/_fonts.css");
598
- if (generationResults.fonts.length === 0) {
599
- writeFileSync(fontsStylesPath, "");
600
- } else {
601
- const fontImports = [];
602
- const fontBodies = [];
603
- for (const font of generationResults.fonts) {
604
- const { imports, body } = font._toCss();
605
- fontImports.push(...imports);
606
- fontBodies.push(body);
607
- }
608
- const importBlock = fontImports.length ? `${fontImports.join("\n")}
609
-
610
- ` : "";
611
- writeFileSync(fontsStylesPath, `${importBlock}@layer fonts { ${fontBodies.join(" ")} }`);
612
- }
613
- const tsTokensPath = join(destDir, "types/css-tokens.d.ts");
614
- const tsVariableTokens = [...variableTokens].join("|");
615
- const pascal = (str) => str.split(/[.\-_]/).filter(Boolean).map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join("");
616
- const templateVariantMapEntries = Object.entries(templateVariantMaps);
617
- const hasVariantMaps = templateVariantMapEntries.some(([, pathMap]) => Object.keys(pathMap).length > 0);
618
- const tsTemplateVariantMap = hasVariantMaps ? `type TemplateVariantTokens = {
619
- ${templateVariantMapEntries.filter(([, pathMap]) => Object.keys(pathMap).length > 0).map(([templateKey, pathMap]) => {
620
- const pathEntries = Object.entries(pathMap).map(
621
- ([dotPath, axes]) => `'${dotPath}': { ${Object.entries(axes).map(([axis, valueType]) => `${axis}?: ${valueType}`).join("; ")} }`
622
- ).join(";\n ");
623
- return `${templateKey}: {
624
- ${pathEntries}
625
- }`;
626
- }).join(";\n ")}
627
- }` : `type TemplateVariantTokens = Record<string, Record<string, Record<string, never>>>;`;
628
- const tsTemplateVariantAliases = templateVariantMapEntries.flatMap(
629
- ([templateKey, pathMap]) => Object.keys(pathMap).map((dotPath) => `type ${pascal(templateKey)}${pascal(dotPath)}Variants = TemplateVariantTokens['${templateKey}']['${dotPath}'];`)
630
- ).join("\n ");
631
- const tsTokensTypes = `
632
- // Variable types
633
- type VariableTokens = ${tsVariableTokens || `''`};
634
- type PropertyValueToken = \`{\${VariableTokens}}\`;
635
-
636
- // Template types
637
- type TemplateTokens = {
638
- ${Object.entries(templateTokens).map(([key, value]) => {
639
- if (!value || value === "any") return `${key}?: ${value || "any"}`;
640
- return `${key}?: ${value} | \`\${${value}}@\${string}\``;
641
- }).join("\n")}
642
- }
643
-
644
- // Template variant types (per docs/template-variants-spec.md §7)
645
- ${tsTemplateVariantMap}
646
- ${tsTemplateVariantAliases}
647
-
648
- // Media query types
649
- type MediaQueryKeys = ${mediaQueryKeys || `''`};
650
- `;
651
- writeFileSync(tsTokensPath, tsTokensTypes);
652
- const configCachePath = join(destDir, "cache/config-cache.json");
653
- writeFileSync(configCachePath, JSON.stringify(configCacheContent, null, 2));
654
- });
655
- __publicField(this, "compileSaltyFile", async (sourceFilePath, outputDirectory) => {
656
- const hashedName = toHash(sourceFilePath);
657
- const tempDir = join(outputDirectory, "./temp");
658
- if (!existsSync(tempDir)) mkdirSync(tempDir);
659
- const parsed = parse(sourceFilePath);
660
- let currentFile = readFileSync(sourceFilePath, "utf8");
661
- currentFile = this.replaceStyledTag(currentFile);
662
- currentFile = this.addConfigCache(currentFile);
663
- const currentFileHash = toHash(currentFile);
664
- const outputFilePath = join(outputDirectory, "js", `${hashedName}-${currentFileHash}.js`);
665
- const rcProject = await this.getRCProjectConfig(this.projectRootDir);
666
- const coreConfigPath = join(this.projectRootDir, (rcProject == null ? void 0 : rcProject.configDir) || "", "salty.config.ts");
667
- const externalModules = this.getExternalModules(coreConfigPath);
668
- const moduleType = await detectCurrentModuleType(this.projectRootDir);
669
- await esbuild.build({
670
- stdin: {
671
- contents: currentFile,
672
- sourcefile: parsed.base,
673
- resolveDir: parsed.dir,
674
- loader: "tsx"
675
- },
676
- minify: false,
677
- treeShaking: true,
678
- bundle: true,
679
- outfile: outputFilePath,
680
- format: moduleType,
681
- target: ["node20"],
682
- keepNames: true,
683
- external: externalModules,
684
- packages: "external",
685
- plugins: [
686
- {
687
- name: "test",
688
- setup: (build) => {
689
- build.onLoad({ filter: /.*\.css|salty|styles|styled\.ts/ }, (args) => {
690
- const original = readFileSync(args.path, "utf8");
691
- const modified = this.replaceStyledTag(original);
692
- return { contents: modified, loader: "ts" };
693
- });
694
- }
695
- }
696
- ]
697
- });
698
- const contents = await this.importFile(outputFilePath);
699
- return { contents, outputFilePath };
700
- });
701
- /**
702
- * Read the framework field from the current project's entry in `.saltyrc.json`.
703
- * Used by framework-aware bundler plugins to dispatch to the right transform.
704
- */
705
- __publicField(this, "getFramework", async () => {
706
- const projectConfig = await this.getRCProjectConfig(this.projectRootDir);
707
- return projectConfig == null ? void 0 : projectConfig.framework;
708
- });
709
- __publicField(this, "generateFile", async (file) => {
710
- try {
711
- const destDir = await this.getDestDir();
712
- const pathFilter = await this.getPathFilter();
713
- const validFile = this.isAllowedSaltyFile(file, pathFilter);
714
- if (validFile) {
715
- const cssFiles = [];
716
- const config = await this.getConfig();
717
- const { contents } = await this.compileSaltyFile(file, destDir);
718
- for (const [name, value] of Object.entries(contents)) {
719
- const resolved = await resolveExportValue(value, 1);
720
- if (resolved.isKeyframes && resolved.css) {
721
- const fileName = `a_${resolved.animationName}.css`;
722
- const filePath2 = `css/${fileName}`;
723
- const cssPath2 = join(destDir, filePath2);
724
- writeFileSync(cssPath2, await resolved.css);
725
- continue;
726
- }
727
- if (resolved.isClassName) {
728
- const generator2 = resolved.generator._withBuildContext({
729
- callerName: name,
730
- isProduction: this.isProduction,
731
- config
732
- });
733
- const styles2 = await generator2.css;
734
- if (!styles2) continue;
735
- if (!cssFiles[generator2.priority]) cssFiles[generator2.priority] = [];
736
- cssFiles[generator2.priority].push(generator2.cssFileName);
737
- const filePath2 = `css/${generator2.cssFileName}`;
738
- const cssPath2 = join(destDir, filePath2);
739
- writeFileSync(cssPath2, styles2);
740
- continue;
741
- }
742
- if (!resolved.generator) continue;
743
- const generator = resolved.generator._withBuildContext({
744
- callerName: name,
745
- isProduction: this.isProduction,
746
- config
747
- });
748
- const styles = await generator.css;
749
- if (!styles) continue;
750
- const filePath = `css/${generator.cssFileName}`;
751
- const cssPath = join(destDir, filePath);
752
- writeFileSync(cssPath, styles);
753
- if (!cssFiles[generator.priority]) cssFiles[generator.priority] = [];
754
- cssFiles[generator.priority].push(generator.cssFileName);
755
- }
756
- if (config.importStrategy !== "component") {
757
- cssFiles.forEach((val, layer) => {
758
- const layerFileName = `l_${layer}.css`;
759
- const layerFilePath = join(destDir, "css", layerFileName);
760
- let currentLayerFileContent = readFileSync(layerFilePath, "utf8");
761
- val.forEach((file2) => {
762
- var _a;
763
- const filepath = join(destDir, "css", file2);
764
- const filepathHash = ((_a = /.*-([^-]+)-\d+.css/.exec(file2)) == null ? void 0 : _a.at(1)) || toHash(filepath, 6);
765
- const found = currentLayerFileContent.includes(filepathHash);
766
- if (!found) {
767
- const css = readFileSync(filepath, "utf8");
768
- const newContent = `/*start:${filepathHash}-${file2}*/
769
- ${css}
770
- /*end:${filepathHash}*/
771
- `;
772
- currentLayerFileContent = `${currentLayerFileContent.replace(/\}$/, "")}
773
- ${newContent}
774
- }`;
775
- }
776
- });
777
- writeFileSync(layerFilePath, currentLayerFileContent);
778
- });
779
- } else {
780
- const cssContent = cssFiles.flat().map((file2) => `@import url('./${file2}');`).join("\n");
781
- const hashName = toHash(file, 6);
782
- const parsedPath = parse(file);
783
- const dasherized = dashCase(parsedPath.name);
784
- const cssFile = join(destDir, `css/f_${dasherized}-${hashName}.css`);
785
- writeFileSync(cssFile, cssContent || `/* Empty file */`);
786
- }
787
- }
788
- } catch (e) {
789
- console.error(e);
790
- }
791
- });
792
- __publicField(this, "replaceStyledTag", (currentFile) => {
793
- return currentFile.replace(/styled\(([^"'`{,]+),/g, (match, tag) => {
794
- const isString = /^['"`]/.test(tag);
795
- if (isString) return match;
796
- const isImportedRegExp = new RegExp(`import[^;]*${tag}[,\\s{][^;]*from\\s?([^{};]+);`);
797
- const isImported = isImportedRegExp.test(currentFile);
798
- if (!isImported) return match;
799
- const importResult = isImportedRegExp.exec(currentFile);
800
- if (importResult) {
801
- const importPath = importResult.at(1);
802
- const isSaltyImport = saltyFileExtensions.some((ext) => importPath == null ? void 0 : importPath.includes(ext));
803
- if (isSaltyImport) return match;
804
- }
805
- return "styled('div',";
806
- });
807
- });
808
- this.projectRootDir = projectRootDir;
809
- this.options = options;
810
- if (typeof process === "undefined") {
811
- throw new Error("SaltyServer can only be used in a Node.js environment.");
812
- }
813
- }
814
- get isProduction() {
815
- if (this.options.mode) return this.options.mode === "production";
816
- try {
817
- return process.env["NODE_ENV"] !== "development";
818
- } catch {
819
- return false;
820
- }
821
- }
822
- }
823
- export {
824
- SaltyCompiler,
825
- logError as a,
826
- logger as l
827
- };