@better-css-modules/core 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -49,9 +49,10 @@ try {
49
49
  - `loadConfig({ cwd?, config? })` loads the config file `config` names, relative to `cwd`, or the `better-css-modules.config.*` in `cwd` (by default the working directory), and returns it as a `ResolvedConfig`: the defaults filled in, checked, and with `root`, the directory every relative path starts from, and `file`, the config file or `null`.
50
50
  - `generate(config)` writes the `.d.ts` files and their declaration maps, removes the ones it wrote for stylesheets that are gone, and returns a `GenerateResult`: `files`, `removed` and the syntax `diagnostics`.
51
51
  - `check(config)` runs every check and returns a `CheckResult`: the sorted `diagnostics`, how many `modules` it checked, and the token categories (`tokens`) the global CSS restricts.
52
+ - `exportTokens(config)` reads the global CSS and returns its tokens as a DTCG resolver document, the `DtcgResolver` the `tokens` command prints; see [Token export](https://github.com/k35o/better-css-modules#token-export).
52
53
  - `formatDiagnostic(diagnostic, cwd)` gives the `file:line:col error rule: message` line of the CLI, and `formatGitHubAnnotation(diagnostic, cwd)` the GitHub Actions workflow command of `--format github`.
53
- - `ConfigError` is a mistake in the config or in the files it names. `loadConfig` throws it, and so does `check` when `include` matches no file, the global CSS cannot be read, or it does not declare the `layer`.
54
- - The types `Config`, `ResolvedConfig`, `GenerateResult`, `CheckResult`, `Diagnostic` and `RuleId` describe these.
54
+ - `ConfigError` is a mistake in the config or in the files it names. `loadConfig` throws it, and so does `check` when `include` matches no file, the global CSS cannot be read, or it does not declare the `layer`, and `exportTokens` when the global CSS cannot be read or a token has a name DTCG cannot hold.
55
+ - The types `Config`, `ResolvedConfig`, `GenerateResult`, `CheckResult`, `Diagnostic`, `RuleId`, `DtcgResolver` and `DtcgToken` describe these.
55
56
 
56
57
  `@better-css-modules/core/internal` holds what the CLI and the plugins share. It is for those packages only and outside semver.
57
58
 
@@ -6,8 +6,8 @@ import { createJiti } from "jiti";
6
6
  import path from "node:path";
7
7
  import fs$1 from "node:fs/promises";
8
8
  import { ResolverFactory } from "oxc-resolver";
9
- import fg from "fast-glob";
10
9
  import picomatch from "picomatch";
10
+ import { glob } from "tinyglobby";
11
11
  import { SourceMapGenerator } from "source-map-js";
12
12
  const { parse, generate: generate$1, lexer } = csstree.fork({
13
13
  atrules: patches.next.atrules,
@@ -742,6 +742,25 @@ function categoryOf(name) {
742
742
  return null;
743
743
  }
744
744
  //#endregion
745
+ //#region src/glob.ts
746
+ /**
747
+ * The files under `cwd` that a pattern matches and no ignore pattern does, as
748
+ * absolute paths. A pattern does not enter dot directories unless it names
749
+ * them, while an ignore pattern reaches into them too, as the matcher of the
750
+ * watcher and the plugins does (`createMatcher`).
751
+ */
752
+ async function globFiles(patterns, options) {
753
+ const { cwd, ignore } = options;
754
+ const files = await glob(patterns, {
755
+ cwd,
756
+ ignore,
757
+ absolute: true,
758
+ expandDirectories: false
759
+ });
760
+ const ignored = picomatch(ignore, { dot: true });
761
+ return files.filter((file) => !ignored(path.relative(cwd, file).split(path.sep).join("/")));
762
+ }
763
+ //#endregion
745
764
  //#region src/project.ts
746
765
  /** Globs no `include` pattern should reach: dependencies and the tool's own output. */
747
766
  function defaultIgnore(config) {
@@ -786,10 +805,9 @@ function createMatcher(config) {
786
805
  /** The CSS Modules files the config includes. */
787
806
  async function findCssModules(config) {
788
807
  const { include, exclude } = patternsOf(config);
789
- return (await fg(include, {
808
+ return (await globFiles(include, {
790
809
  cwd: config.root,
791
- ignore: exclude,
792
- absolute: true
810
+ ignore: exclude
793
811
  })).sort();
794
812
  }
795
813
  /** Read and analyze one file. A stylesheet that does not parse yields its syntax diagnostic. */
@@ -890,10 +908,11 @@ function globalCssFrom(files) {
890
908
  for (const [name, source] of registrations) if (!sources.has(name)) sources.set(name, source);
891
909
  const values = resolveValues(new Map([...sources].map(([name, { text }]) => [name, text])));
892
910
  const tokens = /* @__PURE__ */ new Map();
893
- for (const [name, { node, file }] of sources) tokens.set(name, {
911
+ for (const [name, { node, file, text }] of sources) tokens.set(name, {
894
912
  name,
895
913
  category: categoryOf(name),
896
914
  value: values.get(name) ?? "",
915
+ text,
897
916
  file,
898
917
  node
899
918
  });
@@ -927,7 +946,7 @@ function layersOf(files) {
927
946
  return;
928
947
  }
929
948
  const imported = imports.get(node);
930
- if (!imported || imported.conditional) return;
949
+ if (!imported || imported.condition !== null) return;
931
950
  const target = byFile.get(imported.file);
932
951
  if (imported.layer === null && target) visit(target);
933
952
  else if (imported.layer) names.add(imported.layer);
@@ -1072,18 +1091,18 @@ var Loader = class {
1072
1091
  if (node.type !== "atrule" || node.name.toLowerCase() !== "import") continue;
1073
1092
  const prelude = readImport(node.params);
1074
1093
  if (!prelude) fail(`${this.at(file, node)}: cannot read @import ${node.params}`);
1075
- const { url, layer, conditional: condition } = prelude;
1094
+ const { url, layer, condition } = prelude;
1076
1095
  if (/^([a-z][a-z\d+.-]*:|\/\/)/i.test(url)) fail(`${this.at(file, node)}: global CSS cannot import ${url}`);
1077
1096
  const imported = this.imports.sync(path.dirname(file), url).path;
1078
1097
  if (!imported) fail(`${this.at(file, node)}: cannot resolve "${url}"`);
1079
1098
  entry.imports.push({
1080
1099
  rule: node,
1081
1100
  file: imported,
1082
- conditional: condition,
1101
+ condition,
1083
1102
  layer
1084
1103
  });
1085
- if (!condition) imports.push(imported);
1086
- await this.load(imported, conditional || condition, [...importers, file]);
1104
+ if (condition === null) imports.push(imported);
1105
+ await this.load(imported, conditional || condition !== null, [...importers, file]);
1087
1106
  }
1088
1107
  this.files.push(entry);
1089
1108
  }
@@ -1122,19 +1141,23 @@ function readImport(params) {
1122
1141
  const [target, ...rest] = prelude.type === "AtrulePrelude" ? prelude.children.toArray() : [];
1123
1142
  if (target?.type !== "String" && target?.type !== "Url" || !target.loc) return null;
1124
1143
  let layer = null;
1125
- let conditional = false;
1144
+ let supports = null;
1145
+ let media = null;
1146
+ const text = ({ loc }) => loc ? params.slice(loc.start.offset, loc.end.offset) : "";
1126
1147
  for (const node of rest) {
1127
1148
  const name = node.type === "Function" || node.type === "Identifier" ? node.name.toLowerCase() : "";
1128
1149
  if (name === "layer") {
1129
1150
  const [named] = node.type === "Function" ? node.children.toArray() : [];
1130
1151
  layer = named?.type === "Layer" ? named.name : "";
1131
- } else if (node.type === "MediaQueryList" && !isUnknownMediaType(node) || node.type === "Function" && name === "supports") conditional = true;
1152
+ } else if (node.type === "Function" && name === "supports") supports = `@supports (${text(node).slice(9, -1).trim()})`;
1153
+ else if (node.type === "MediaQueryList" && !isUnknownMediaType(node)) media = `@media ${text(node)}`;
1132
1154
  }
1155
+ const conditions = [supports, media].filter((condition) => condition !== null);
1133
1156
  return {
1134
1157
  url: target.value,
1135
1158
  urlEnd: target.loc.end.offset,
1136
1159
  layer,
1137
- conditional
1160
+ condition: conditions.length > 0 ? conditions.join(" ") : null
1138
1161
  };
1139
1162
  }
1140
1163
  /**
@@ -1539,13 +1562,11 @@ async function wroteDts(dtsPath) {
1539
1562
  * are taken, because outDir may hold other files, or be the root itself.
1540
1563
  */
1541
1564
  async function outputsIn(config) {
1542
- const patterns = config.include.filter((pattern) => !pattern.startsWith("!")).flatMap((pattern) => [`${pattern}.d.ts`, `${pattern}.d.ts.map`]);
1543
- const outputs = await fg(patterns, {
1565
+ const outputs = await globFiles(config.include.filter((pattern) => !pattern.startsWith("!")).flatMap((pattern) => [`${pattern}.d.ts`, `${pattern}.d.ts.map`]), {
1544
1566
  cwd: path.join(config.root, config.outDir),
1545
- ignore: ["**/node_modules/**"],
1546
- absolute: true
1567
+ ignore: ["**/node_modules/**"]
1547
1568
  });
1548
1569
  return [...new Set(outputs.map((file) => path.resolve(file.replace(/\.map$/, ""))))].sort();
1549
1570
  }
1550
1571
  //#endregion
1551
- export { find as C, property as D, parse as E, walk as O, valueStart as S, lexer as T, sortDiagnostics as _, resolveLayer as a, loadConfig as b, loadGlobalCss as c, findCssModules as d, loadCssModules as f, formatGitHubAnnotation as g, formatDiagnostic as h, createLayerWrapper as i, createMatcher as l, tokenCategories as m, regenerateDts as n, declaresToken as o, categoryOf as p, checkLayer as r, isForeign as s, generate as t, defaultIgnore as u, ConfigError as v, generate$1 as w, paramsStart as x, defineConfig as y };
1572
+ export { valueStart as C, parse as D, lexer as E, property as O, paramsStart as S, generate$1 as T, formatGitHubAnnotation as _, resolveLayer as a, defineConfig as b, loadGlobalCss as c, findCssModules as d, loadCssModules as f, formatDiagnostic as g, tokenCategories as h, createLayerWrapper as i, walk as k, createMatcher as l, categoryOf as m, regenerateDts as n, declaresToken as o, globFiles as p, checkLayer as r, isForeign as s, generate as t, defaultIgnore as u, sortDiagnostics as v, find as w, loadConfig as x, ConfigError as y };
package/dist/index.d.mts CHANGED
@@ -17,4 +17,92 @@ interface CheckResult {
17
17
  */
18
18
  export declare function check(config: ResolvedConfig): Promise<CheckResult>;
19
19
  //#endregion
20
- export { type CheckResult, type Config, ConfigError, type Diagnostic, type GenerateResult, type ResolvedConfig, type RuleId, defineConfig, formatDiagnostic, formatGitHubAnnotation, generate, loadConfig };
20
+ //#region src/dtcg.d.ts
21
+ /** A reference to another token: its name without the leading `--`, in braces. */
22
+ type DtcgAlias = `{${string}}`;
23
+ type DtcgComponent = number | "none";
24
+ interface DtcgColor {
25
+ colorSpace: "srgb" | "srgb-linear" | "hsl" | "hwb" | "lab" | "lch" | "oklab" | "oklch" | "display-p3" | "a98-rgb" | "prophoto-rgb" | "rec2020" | "xyz-d65" | "xyz-d50";
26
+ components: [DtcgComponent, DtcgComponent, DtcgComponent];
27
+ /** Present when the color is written with one. */
28
+ alpha?: number;
29
+ }
30
+ interface DtcgDimension {
31
+ value: number;
32
+ unit: "px" | "rem";
33
+ }
34
+ interface DtcgDuration {
35
+ value: number;
36
+ unit: "ms" | "s";
37
+ }
38
+ interface DtcgShadow {
39
+ color: DtcgColor | DtcgAlias;
40
+ offsetX: DtcgDimension;
41
+ offsetY: DtcgDimension;
42
+ blur: DtcgDimension;
43
+ spread: DtcgDimension;
44
+ inset?: true;
45
+ }
46
+ /**
47
+ * A token. A value DTCG has no form for keeps its CSS text and has no type,
48
+ * which DTCG takes for an invalid token; so does an alias of one.
49
+ */
50
+ type DtcgToken = {
51
+ $type: "color";
52
+ $value: DtcgColor | DtcgAlias;
53
+ } | {
54
+ $type: "dimension";
55
+ $value: DtcgDimension | DtcgAlias;
56
+ } | {
57
+ $type: "duration";
58
+ $value: DtcgDuration | DtcgAlias;
59
+ } | {
60
+ $type: "number";
61
+ $value: number | DtcgAlias;
62
+ } | {
63
+ $type: "fontWeight";
64
+ $value: number | "normal" | "bold" | DtcgAlias;
65
+ } | {
66
+ $type: "fontFamily";
67
+ $value: string | string[];
68
+ } | {
69
+ $type: "cubicBezier";
70
+ $value: [number, number, number, number] | DtcgAlias;
71
+ } | {
72
+ $type: "shadow";
73
+ $value: DtcgShadow | DtcgShadow[] | DtcgAlias;
74
+ } | {
75
+ $type?: undefined;
76
+ $value: string;
77
+ };
78
+ /** Tokens by their names without the leading `--`. */
79
+ type DtcgTokens = Record<string, DtcgToken>;
80
+ interface DtcgSet {
81
+ type: "set";
82
+ name: ":root";
83
+ sources: [DtcgTokens];
84
+ }
85
+ /** A place other than `:root` that overrides tokens, named by its conditions as written. */
86
+ interface DtcgModifier {
87
+ type: "modifier";
88
+ name: string;
89
+ contexts: {
90
+ off: [];
91
+ on: [DtcgTokens];
92
+ };
93
+ default: "off";
94
+ }
95
+ /**
96
+ * The tokens as a DTCG resolver document (Resolver Module 2025.10): the tokens
97
+ * at `:root` as a set, then each mode as a modifier the input turns on, in the
98
+ * source order of its first place. The input turns on every mode whose
99
+ * conditions hold at once.
100
+ */
101
+ interface DtcgResolver {
102
+ version: "2025.10";
103
+ resolutionOrder: [DtcgSet, ...DtcgModifier[]];
104
+ }
105
+ /** Read the global CSS a config lists and write its tokens as a DTCG resolver document. */
106
+ export declare function exportTokens(config: ResolvedConfig): Promise<DtcgResolver>;
107
+ //#endregion
108
+ export { type CheckResult, type Config, ConfigError, type Diagnostic, type DtcgResolver, type DtcgToken, type GenerateResult, type ResolvedConfig, type RuleId, defineConfig, formatDiagnostic, formatGitHubAnnotation, generate, loadConfig };
package/dist/index.mjs CHANGED
@@ -1,8 +1,7 @@
1
- import { C as find, D as property, E as parse, O as walk$1, S as valueStart, T as lexer, _ as sortDiagnostics, a as resolveLayer, b as loadConfig, c as loadGlobalCss, d as findCssModules, f as loadCssModules, g as formatGitHubAnnotation, h as formatDiagnostic, m as tokenCategories, o as declaresToken, p as categoryOf, r as checkLayer, s as isForeign, t as generate, u as defaultIgnore, v as ConfigError, w as generate$1, x as paramsStart, y as defineConfig } from "./dts-De2E7b59.mjs";
1
+ import { C as valueStart, D as parse, E as lexer, O as property, S as paramsStart, T as generate$1, _ as formatGitHubAnnotation, a as resolveLayer, b as defineConfig, c as loadGlobalCss, d as findCssModules, f as loadCssModules, g as formatDiagnostic, h as tokenCategories, k as walk$1, m as categoryOf, o as declaresToken, p as globFiles, r as checkLayer, s as isForeign, t as generate, u as defaultIgnore, v as sortDiagnostics, w as find, x as loadConfig, y as ConfigError } from "./dts-QJXWpHAG.mjs";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { ResolverFactory } from "oxc-resolver";
5
- import fg from "fast-glob";
6
5
  import { parseSync } from "oxc-parser";
7
6
  //#region src/breakpoint.ts
8
7
  /** Media features that compare the width of the viewport. */
@@ -1857,10 +1856,9 @@ function isUsed(moduleUsage, name) {
1857
1856
  }
1858
1857
  async function findSources(config, cwd) {
1859
1858
  const ignore = [...defaultIgnore(config), ...IGNORED_DIRS.map((dir) => `${dir}/**`)];
1860
- return (await fg(SOURCE_GLOBS, {
1859
+ return (await globFiles(SOURCE_GLOBS, {
1861
1860
  cwd,
1862
- ignore,
1863
- absolute: true
1861
+ ignore
1864
1862
  })).filter((file) => !/\.d\.[mc]?ts$/.test(file)).sort();
1865
1863
  }
1866
1864
  function langOf(file) {
@@ -2696,4 +2694,544 @@ function isZero(node) {
2696
2694
  return Number(node.value) === 0;
2697
2695
  }
2698
2696
  //#endregion
2699
- export { ConfigError, check, defineConfig, formatDiagnostic, formatGitHubAnnotation, generate, loadConfig };
2697
+ //#region src/dtcg.ts
2698
+ /** Read the global CSS a config lists and write its tokens as a DTCG resolver document. */
2699
+ async function exportTokens(config) {
2700
+ return dtcgFrom(await loadGlobalCss(config));
2701
+ }
2702
+ /** Write the tokens of global CSS already read as a DTCG resolver document. Pure. */
2703
+ function dtcgFrom(globalCss) {
2704
+ const { tokens } = globalCss;
2705
+ for (const token of tokens.values()) checkName(token);
2706
+ const writer = new Writer(tokens);
2707
+ const write = (values) => Object.fromEntries([...values].map(([name, text]) => [name.slice(2), writer.token(text, tokens.get(name)?.category ?? null)]));
2708
+ const modifiers = [...modesOf(globalCss)].map(([name, values]) => ({
2709
+ type: "modifier",
2710
+ name,
2711
+ contexts: {
2712
+ off: [],
2713
+ on: [write(values)]
2714
+ },
2715
+ default: "off"
2716
+ }));
2717
+ return {
2718
+ version: "2025.10",
2719
+ resolutionOrder: [{
2720
+ type: "set",
2721
+ name: ":root",
2722
+ sources: [write([...tokens.values()].map(({ name, text }) => [name, text]))]
2723
+ }, ...modifiers]
2724
+ };
2725
+ }
2726
+ /** Refuse a name DTCG cannot hold: it forbids `.`, `{` and `}` in a name and `$` at its start. */
2727
+ function checkName({ name, file, node }) {
2728
+ if (!/[.{}]/.test(name) && !name.startsWith("--$")) return;
2729
+ const start = node.source?.start;
2730
+ throw new ConfigError(`${path.relative(process.cwd(), file)}:${start?.line ?? 1}:${start?.column ?? 1}: ${name} cannot be a DTCG token name: DTCG forbids ".", "{" and "}" in names, and "$" at their start`);
2731
+ }
2732
+ /**
2733
+ * The modes by name, each with the value it gives each token it overrides, in
2734
+ * cascade order: what the global CSS declares outside `:root` for a name
2735
+ * `:root` declares. A place that overrides no token is no mode.
2736
+ */
2737
+ function modesOf({ files, tokens }) {
2738
+ const conditions = conditionsOf(files);
2739
+ const modes = /* @__PURE__ */ new Map();
2740
+ for (const sheet of files) sheet.root.walkDecls((decl) => {
2741
+ if (!tokens.has(decl.prop) || isForeign(decl) || declaresToken(decl, sheet.conditional)) return;
2742
+ const name = placeOf(decl, conditions.get(sheet.file) ?? "");
2743
+ modes.set(name, (modes.get(name) ?? /* @__PURE__ */ new Map()).set(decl.prop, decl.value));
2744
+ });
2745
+ return modes;
2746
+ }
2747
+ /**
2748
+ * The conditions of the imports each stylesheet read only under conditions
2749
+ * is first reached through, outermost first.
2750
+ */
2751
+ function conditionsOf(files) {
2752
+ const byFile = new Map(files.map((sheet) => [sheet.file, sheet]));
2753
+ const conditions = /* @__PURE__ */ new Map();
2754
+ const reached = /* @__PURE__ */ new Set();
2755
+ const visit = (sheet, outer) => {
2756
+ for (const { file, condition } of sheet.imports) {
2757
+ const target = byFile.get(file);
2758
+ if (!target || reached.has(file)) continue;
2759
+ reached.add(file);
2760
+ const inner = target.conditional ? joined([outer, condition ?? ""]) : "";
2761
+ if (target.conditional) conditions.set(file, inner);
2762
+ visit(target, inner);
2763
+ }
2764
+ };
2765
+ for (const sheet of files) if (sheet.listed) visit(sheet, "");
2766
+ return conditions;
2767
+ }
2768
+ /** A place by its conditions: the rules and at-rules around it, outermost first, without `@layer`. */
2769
+ function placeOf(node, conditions) {
2770
+ const parts = [];
2771
+ for (let parent = node.parent; parent && parent.type !== "root"; parent = parent.parent) if (parent.type === "rule") parts.unshift(parent.selector);
2772
+ else if (parent.type === "atrule" && parent.name.toLowerCase() !== "layer") {
2773
+ const { name, params } = parent;
2774
+ parts.unshift(`@${name} ${params}`);
2775
+ }
2776
+ return joined([conditions, ...parts]);
2777
+ }
2778
+ function joined(parts) {
2779
+ return parts.join(" ").replace(/\s+/g, " ").trim();
2780
+ }
2781
+ /** Writes the values of the custom properties of the global CSS as tokens. */
2782
+ var Writer = class {
2783
+ tokens;
2784
+ references = /* @__PURE__ */ new Map();
2785
+ types = /* @__PURE__ */ new Map();
2786
+ constructor(tokens) {
2787
+ this.tokens = tokens;
2788
+ }
2789
+ token(text, category) {
2790
+ const nodes = valueNodes(text);
2791
+ if (nodes) {
2792
+ const alias = this.alias(nodes);
2793
+ if (alias) return alias.$type ? alias : { $value: alias.$value };
2794
+ const token = (category ? READERS[category] : readInternal)(nodes, this);
2795
+ if (token) return token;
2796
+ }
2797
+ return { $value: text.trim() };
2798
+ }
2799
+ /** A color, or an alias of a color token. */
2800
+ color(node) {
2801
+ const written = color(node);
2802
+ if (written) return written;
2803
+ const alias = this.alias([node]);
2804
+ return alias?.$type === "color" ? alias.$value : null;
2805
+ }
2806
+ /**
2807
+ * The alias a value that is one var() of a token is, with the type of the
2808
+ * token its chain of aliases ends at; null when the chain loops.
2809
+ */
2810
+ alias(nodes) {
2811
+ const target = this.reference(nodes);
2812
+ const end = target === null ? null : this.end(target);
2813
+ if (target === null || end === null) return null;
2814
+ return {
2815
+ $type: this.typeOf(end),
2816
+ $value: `{${target.slice(2)}}`
2817
+ };
2818
+ }
2819
+ /** The token a value that is one var() of a token names, whatever its fallback. */
2820
+ reference(nodes) {
2821
+ const [node] = nodes;
2822
+ if (nodes.length !== 1 || node.type !== "Function" || node.name.toLowerCase() !== "var") return null;
2823
+ const [name] = node.children.toArray();
2824
+ return name?.type === "Identifier" && this.tokens.has(name.name) ? name.name : null;
2825
+ }
2826
+ /** The token a chain of aliases from a token ends at, or null when it loops. */
2827
+ end(name) {
2828
+ const seen = /* @__PURE__ */ new Set();
2829
+ let current = name;
2830
+ for (let next = this.referenceOf(current); next !== null; next = this.referenceOf(current)) {
2831
+ seen.add(current);
2832
+ if (seen.has(next)) return null;
2833
+ current = next;
2834
+ }
2835
+ return current;
2836
+ }
2837
+ /** The token the value a token is declared with is one var() of, or null. */
2838
+ referenceOf(name) {
2839
+ if (!this.references.has(name)) {
2840
+ const nodes = valueNodes(this.tokens.get(name)?.text ?? "");
2841
+ this.references.set(name, nodes && this.reference(nodes));
2842
+ }
2843
+ return this.references.get(name) ?? null;
2844
+ }
2845
+ typeOf(name) {
2846
+ const token = this.tokens.get(name);
2847
+ if (!this.types.has(name) && token) {
2848
+ this.types.set(name, void 0);
2849
+ this.types.set(name, this.token(token.text, token.category).$type);
2850
+ }
2851
+ return this.types.get(name);
2852
+ }
2853
+ };
2854
+ function valueNodes(text) {
2855
+ let value;
2856
+ try {
2857
+ value = parse(text, { context: "value" });
2858
+ } catch {
2859
+ return null;
2860
+ }
2861
+ return value.type === "Value" ? value.children.toArray() : null;
2862
+ }
2863
+ /** The token a value written in the form of `type` is, or null. */
2864
+ function typed(type, value) {
2865
+ return value === null ? null : {
2866
+ $type: type,
2867
+ $value: value
2868
+ };
2869
+ }
2870
+ function one(nodes, read) {
2871
+ return nodes.length === 1 ? read(nodes[0]) : null;
2872
+ }
2873
+ function dimensionToken(nodes) {
2874
+ return typed("dimension", one(nodes, dimension));
2875
+ }
2876
+ /** How each category's value is read as a token; null when DTCG has no form for it. */
2877
+ const READERS = {
2878
+ color: (nodes) => typed("color", one(nodes, color)),
2879
+ spacing: dimensionToken,
2880
+ radius: dimensionToken,
2881
+ shadow: (nodes, writer) => typed("shadow", shadow(nodes, writer)),
2882
+ "font-family": (nodes) => typed("fontFamily", fontFamily(nodes)),
2883
+ "font-size": dimensionToken,
2884
+ "font-weight": (nodes) => typed("fontWeight", one(nodes, fontWeight)),
2885
+ "line-height": (nodes) => typed("number", one(nodes, number)) ?? dimensionToken(nodes),
2886
+ "letter-spacing": dimensionToken,
2887
+ "z-index": (nodes) => typed("number", one(nodes, integer)),
2888
+ duration: (nodes) => typed("duration", one(nodes, duration)),
2889
+ easing: (nodes) => typed("cubicBezier", one(nodes, easing)),
2890
+ breakpoint: dimensionToken
2891
+ };
2892
+ /** A name without a category is typed by how its value is written. */
2893
+ const readInternal = (nodes) => typed("color", one(nodes, color)) ?? typed("dimension", one(nodes, (node) => node.type === "Dimension" ? dimension(node) : null)) ?? typed("duration", one(nodes, duration)) ?? typed("number", one(nodes, number)) ?? typed("cubicBezier", one(nodes, cubicBezier));
2894
+ function number(node) {
2895
+ return node.type === "Number" ? Number(node.value) : null;
2896
+ }
2897
+ function integer(node) {
2898
+ const value = number(node);
2899
+ return value !== null && Number.isInteger(value) ? value : null;
2900
+ }
2901
+ /** A length in `px` or `rem`, or zero, which is a length in any unit. */
2902
+ function dimension(node) {
2903
+ if (node.type === "Number") return Number(node.value) === 0 ? {
2904
+ value: 0,
2905
+ unit: "px"
2906
+ } : null;
2907
+ if (node.type !== "Dimension") return null;
2908
+ const unit = node.unit.toLowerCase();
2909
+ const value = Number(node.value);
2910
+ if (unit === "px" || unit === "rem") return {
2911
+ value,
2912
+ unit
2913
+ };
2914
+ return value === 0 && lexer.matchType("length", node).matched !== null ? {
2915
+ value: 0,
2916
+ unit: "px"
2917
+ } : null;
2918
+ }
2919
+ function duration(node) {
2920
+ if (node.type !== "Dimension") return null;
2921
+ const unit = node.unit.toLowerCase();
2922
+ return unit === "ms" || unit === "s" ? {
2923
+ value: Number(node.value),
2924
+ unit
2925
+ } : null;
2926
+ }
2927
+ function fontWeight(node) {
2928
+ if (node.type === "Identifier") {
2929
+ const keyword = node.name.toLowerCase();
2930
+ return keyword === "normal" || keyword === "bold" ? keyword : null;
2931
+ }
2932
+ const value = number(node);
2933
+ return value !== null && value >= 1 && value <= 1e3 ? value : null;
2934
+ }
2935
+ /** The families, each a string or the identifiers of an unquoted name. */
2936
+ function fontFamily(nodes) {
2937
+ const families = [];
2938
+ for (const family of items(nodes)) {
2939
+ const [first] = family;
2940
+ if (family.length === 1 && first.type === "String") families.push(first.value);
2941
+ else if (family.length > 0 && family.every((node) => node.type === "Identifier")) families.push(family.map((node) => node.name).join(" "));
2942
+ else return null;
2943
+ }
2944
+ if (families.length === 1 && CSS_WIDE_KEYWORDS.has(families[0].toLowerCase())) return null;
2945
+ return families.length === 1 ? families[0] : families;
2946
+ }
2947
+ const EASINGS = /* @__PURE__ */ new Map([
2948
+ ["linear", [
2949
+ 0,
2950
+ 0,
2951
+ 1,
2952
+ 1
2953
+ ]],
2954
+ ["ease", [
2955
+ .25,
2956
+ .1,
2957
+ .25,
2958
+ 1
2959
+ ]],
2960
+ ["ease-in", [
2961
+ .42,
2962
+ 0,
2963
+ 1,
2964
+ 1
2965
+ ]],
2966
+ ["ease-out", [
2967
+ 0,
2968
+ 0,
2969
+ .58,
2970
+ 1
2971
+ ]],
2972
+ ["ease-in-out", [
2973
+ .42,
2974
+ 0,
2975
+ .58,
2976
+ 1
2977
+ ]]
2978
+ ]);
2979
+ function easing(node) {
2980
+ return node.type === "Identifier" ? EASINGS.get(node.name.toLowerCase()) ?? null : cubicBezier(node);
2981
+ }
2982
+ function cubicBezier(node) {
2983
+ if (node.type !== "Function" || node.name.toLowerCase() !== "cubic-bezier") return null;
2984
+ const points = items(node.children.toArray()).map((item) => item.length === 1 ? number(item[0]) : null);
2985
+ if (points.length !== 4 || points.includes(null)) return null;
2986
+ const [x1, y1, x2, y2] = points;
2987
+ return [x1, x2].every((x) => x >= 0 && x <= 1) ? [
2988
+ x1,
2989
+ y1,
2990
+ x2,
2991
+ y2
2992
+ ] : null;
2993
+ }
2994
+ function shadow(nodes, writer) {
2995
+ const shadows = [];
2996
+ for (const layer of items(nodes)) {
2997
+ const read = shadowOf(layer, writer);
2998
+ if (!read) return null;
2999
+ shadows.push(read);
3000
+ }
3001
+ return shadows.length === 1 ? shadows[0] : shadows;
3002
+ }
3003
+ /** One shadow: two to four lengths together, a color, and `inset`, in any order. */
3004
+ function shadowOf(layer, writer) {
3005
+ const read = layer.map((node) => node.type === "Number" || node.type === "Dimension" ? dimension(node) : null);
3006
+ const at = read.flatMap((length, index) => length ? [index] : []);
3007
+ const [first, last] = [at[0] ?? -1, at.at(-1) ?? -1];
3008
+ const lengths = read.slice(first, last + 1);
3009
+ if (first === -1 || lengths.length < 2 || lengths.length > 4 || lengths.includes(null)) return null;
3010
+ let inset = false;
3011
+ let color = null;
3012
+ for (const node of [...layer.slice(0, first), ...layer.slice(last + 1)]) if (!inset && node.type === "Identifier" && node.name.toLowerCase() === "inset") inset = true;
3013
+ else if (color === null) {
3014
+ color = writer.color(node);
3015
+ if (color === null) return null;
3016
+ } else return null;
3017
+ if (color === null) return null;
3018
+ const zero = {
3019
+ value: 0,
3020
+ unit: "px"
3021
+ };
3022
+ const [offsetX, offsetY, blur = zero, spread = zero] = lengths;
3023
+ return {
3024
+ color,
3025
+ offsetX,
3026
+ offsetY,
3027
+ blur,
3028
+ spread,
3029
+ ...inset && { inset: true }
3030
+ };
3031
+ }
3032
+ /** A color written with its channels, or `transparent`. */
3033
+ function color(node) {
3034
+ if (node.type === "Hash") return hex(node.value);
3035
+ if (node.type === "Identifier") return node.name.toLowerCase() === "transparent" ? {
3036
+ colorSpace: "srgb",
3037
+ components: [
3038
+ 0,
3039
+ 0,
3040
+ 0
3041
+ ],
3042
+ alpha: 0
3043
+ } : null;
3044
+ if (node.type !== "Function") return null;
3045
+ let args = node.children.toArray();
3046
+ let space = FUNCTIONS.get(node.name.toLowerCase());
3047
+ if (node.name.toLowerCase() === "color") {
3048
+ const [named, ...rest] = args;
3049
+ space = named?.type === "Identifier" ? PREDEFINED.get(named.name.toLowerCase()) : void 0;
3050
+ args = rest;
3051
+ }
3052
+ const written = space && channelsOf(args);
3053
+ if (!space || !written) return null;
3054
+ const components = written.channels.map((value, index) => space.channels[index](value));
3055
+ if (components.includes(null)) return null;
3056
+ const result = {
3057
+ colorSpace: space.colorSpace,
3058
+ components
3059
+ };
3060
+ if (!written.alpha) return result;
3061
+ const alpha = alphaOf(written.alpha);
3062
+ return alpha === null ? null : {
3063
+ ...result,
3064
+ alpha
3065
+ };
3066
+ }
3067
+ /** The channels and the alpha of a color function, which the legacy syntax separates with commas. */
3068
+ function channelsOf(args) {
3069
+ let channels;
3070
+ let alpha;
3071
+ if (args.some((arg) => arg.type === "Operator" && arg.value === ",")) {
3072
+ const values = items(args);
3073
+ if (values.some((value) => value.length !== 1)) return null;
3074
+ [channels, alpha] = [values.slice(0, 3).flat(), values.slice(3).flat()];
3075
+ } else {
3076
+ const slash = args.findIndex((arg) => arg.type === "Operator" && arg.value === "/");
3077
+ [channels, alpha] = slash === -1 ? [args, []] : [args.slice(0, slash), args.slice(slash + 1)];
3078
+ if (slash !== -1 && alpha.length === 0) return null;
3079
+ }
3080
+ return channels.length === 3 && alpha.length <= 1 ? {
3081
+ channels,
3082
+ alpha: alpha[0]
3083
+ } : null;
3084
+ }
3085
+ function scaled(value) {
3086
+ return Number(value.toPrecision(15));
3087
+ }
3088
+ /** A channel that is a number, or a percentage of `reference`. */
3089
+ function percent(reference) {
3090
+ return (node) => {
3091
+ if (node.type === "Number") return Number(node.value);
3092
+ if (node.type === "Percentage") return scaled(Number(node.value) * reference / 100);
3093
+ return none(node);
3094
+ };
3095
+ }
3096
+ /** A red, green or blue channel of rgb(): a number of 255, or a percentage. */
3097
+ const rgb = (node) => node.type === "Number" ? scaled(Number(node.value) / 255) : percent(1)(node);
3098
+ const DEGREES = /* @__PURE__ */ new Map([
3099
+ ["deg", 1],
3100
+ ["grad", 360 / 400],
3101
+ ["rad", 180 / Math.PI],
3102
+ ["turn", 360]
3103
+ ]);
3104
+ /** A hue in degrees, from 0 up to 360. */
3105
+ const hue = (node) => {
3106
+ if (node.type !== "Number" && node.type !== "Dimension") return none(node);
3107
+ const factor = node.type === "Number" ? 1 : DEGREES.get(node.unit.toLowerCase());
3108
+ if (factor === void 0) return null;
3109
+ const degrees = scaled(Number(node.value) * factor);
3110
+ return degrees >= 0 && degrees < 360 ? degrees : scaled((degrees % 360 + 360) % 360);
3111
+ };
3112
+ function none(node) {
3113
+ return node.type === "Identifier" && node.name.toLowerCase() === "none" ? "none" : null;
3114
+ }
3115
+ function alphaOf(node) {
3116
+ if (node.type === "Number") return Number(node.value);
3117
+ if (node.type === "Percentage") return scaled(Number(node.value) / 100);
3118
+ return null;
3119
+ }
3120
+ const FUNCTIONS = /* @__PURE__ */ new Map([
3121
+ ["rgb", {
3122
+ colorSpace: "srgb",
3123
+ channels: [
3124
+ rgb,
3125
+ rgb,
3126
+ rgb
3127
+ ]
3128
+ }],
3129
+ ["rgba", {
3130
+ colorSpace: "srgb",
3131
+ channels: [
3132
+ rgb,
3133
+ rgb,
3134
+ rgb
3135
+ ]
3136
+ }],
3137
+ ["hsl", {
3138
+ colorSpace: "hsl",
3139
+ channels: [
3140
+ hue,
3141
+ percent(100),
3142
+ percent(100)
3143
+ ]
3144
+ }],
3145
+ ["hsla", {
3146
+ colorSpace: "hsl",
3147
+ channels: [
3148
+ hue,
3149
+ percent(100),
3150
+ percent(100)
3151
+ ]
3152
+ }],
3153
+ ["hwb", {
3154
+ colorSpace: "hwb",
3155
+ channels: [
3156
+ hue,
3157
+ percent(100),
3158
+ percent(100)
3159
+ ]
3160
+ }],
3161
+ ["lab", {
3162
+ colorSpace: "lab",
3163
+ channels: [
3164
+ percent(100),
3165
+ percent(125),
3166
+ percent(125)
3167
+ ]
3168
+ }],
3169
+ ["lch", {
3170
+ colorSpace: "lch",
3171
+ channels: [
3172
+ percent(100),
3173
+ percent(150),
3174
+ hue
3175
+ ]
3176
+ }],
3177
+ ["oklab", {
3178
+ colorSpace: "oklab",
3179
+ channels: [
3180
+ percent(1),
3181
+ percent(.4),
3182
+ percent(.4)
3183
+ ]
3184
+ }],
3185
+ ["oklch", {
3186
+ colorSpace: "oklch",
3187
+ channels: [
3188
+ percent(1),
3189
+ percent(.4),
3190
+ hue
3191
+ ]
3192
+ }]
3193
+ ]);
3194
+ /** The spaces of color(), whose channels are all from 0 to 1. */
3195
+ const PREDEFINED = new Map([
3196
+ ["srgb", "srgb"],
3197
+ ["srgb-linear", "srgb-linear"],
3198
+ ["display-p3", "display-p3"],
3199
+ ["a98-rgb", "a98-rgb"],
3200
+ ["prophoto-rgb", "prophoto-rgb"],
3201
+ ["rec2020", "rec2020"],
3202
+ ["xyz", "xyz-d65"],
3203
+ ["xyz-d65", "xyz-d65"],
3204
+ ["xyz-d50", "xyz-d50"]
3205
+ ].map(([name, colorSpace]) => [name, {
3206
+ colorSpace,
3207
+ channels: [
3208
+ percent(1),
3209
+ percent(1),
3210
+ percent(1)
3211
+ ]
3212
+ }]));
3213
+ function hex(digits) {
3214
+ if (!/^([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i.test(digits)) return null;
3215
+ const [r, g, b, alpha] = (digits.length <= 4 ? [...digits].map((digit) => digit + digit) : digits.match(/../g)).map((pair) => scaled(parseInt(pair, 16) / 255));
3216
+ const result = {
3217
+ colorSpace: "srgb",
3218
+ components: [
3219
+ r,
3220
+ g,
3221
+ b
3222
+ ]
3223
+ };
3224
+ return alpha === void 0 ? result : {
3225
+ ...result,
3226
+ alpha
3227
+ };
3228
+ }
3229
+ /** A comma-separated list, item by item. */
3230
+ function items(nodes) {
3231
+ const list = [[]];
3232
+ for (const node of nodes) if (node.type === "Operator" && node.value === ",") list.push([]);
3233
+ else list[list.length - 1].push(node);
3234
+ return list;
3235
+ }
3236
+ //#endregion
3237
+ export { ConfigError, check, defineConfig, exportTokens, formatDiagnostic, formatGitHubAnnotation, generate, loadConfig };
package/dist/internal.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { h as formatDiagnostic, i as createLayerWrapper, l as createMatcher, n as regenerateDts, t as generate } from "./dts-De2E7b59.mjs";
1
+ import { g as formatDiagnostic, i as createLayerWrapper, l as createMatcher, n as regenerateDts, t as generate } from "./dts-QJXWpHAG.mjs";
2
2
  import path from "node:path";
3
3
  import { watch } from "chokidar";
4
4
  //#region src/watcher.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@better-css-modules/core",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Analysis, type generation, unused-class detection, token checks, watcher and config for better-css-modules",
5
5
  "keywords": [
6
6
  "css-modules",
@@ -35,13 +35,13 @@
35
35
  "@csstools/css-syntax-patches-for-csstree": "1.1.14",
36
36
  "chokidar": "5.0.0",
37
37
  "css-tree": "3.2.1",
38
- "fast-glob": "3.3.3",
39
38
  "jiti": "2.6.1",
40
39
  "oxc-parser": "0.151.0",
41
40
  "oxc-resolver": "11.24.2",
42
41
  "picomatch": "4.0.7",
43
- "postcss": "8.5.8",
44
- "source-map-js": "1.2.1"
42
+ "postcss": "8.5.31",
43
+ "source-map-js": "1.2.2",
44
+ "tinyglobby": "0.2.17"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@types/css-tree": "3.2.0",