@kbach/react 1.0.0-beta.2 → 1.0.0-beta.21

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.
@@ -0,0 +1,1253 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/postcss-plugin/index.ts
31
+ var postcss_plugin_exports = {};
32
+ __export(postcss_plugin_exports, {
33
+ default: () => kbachPostcss
34
+ });
35
+ module.exports = __toCommonJS(postcss_plugin_exports);
36
+ var import_postcss = __toESM(require("postcss"));
37
+ var import_path5 = require("path");
38
+
39
+ // src/staticCss/engine.ts
40
+ var import_path3 = require("path");
41
+
42
+ // src/vite-plugin/wasmNode.ts
43
+ var import_node = require("@kbach/core-engine/node");
44
+ function generateCssForToken(token, themeJson) {
45
+ return JSON.parse((0, import_node.generate_css)(token, themeJson));
46
+ }
47
+
48
+ // src/vite-plugin/scan.ts
49
+ var import_fs = require("fs");
50
+ var import_path = require("path");
51
+ function stripComments(code) {
52
+ let out = "";
53
+ let i = 0;
54
+ const n = code.length;
55
+ while (i < n) {
56
+ const two = code[i] + (code[i + 1] ?? "");
57
+ if (two === "//") {
58
+ i += 2;
59
+ while (i < n && code[i] !== "\n") i++;
60
+ continue;
61
+ }
62
+ if (two === "/*") {
63
+ i += 2;
64
+ while (i < n && code[i] + (code[i + 1] ?? "") !== "*/") i++;
65
+ i += 2;
66
+ continue;
67
+ }
68
+ const ch = code[i];
69
+ if (ch === '"' || ch === "'") {
70
+ out += ch;
71
+ i++;
72
+ while (i < n && code[i] !== ch) {
73
+ if (code[i] === "\\") {
74
+ out += code[i] + (code[i + 1] ?? "");
75
+ i += 2;
76
+ continue;
77
+ }
78
+ out += code[i];
79
+ i++;
80
+ }
81
+ out += code[i] ?? "";
82
+ i++;
83
+ continue;
84
+ }
85
+ if (ch === "`") {
86
+ out += ch;
87
+ i++;
88
+ let interpolationDepth = 0;
89
+ while (i < n) {
90
+ if (interpolationDepth === 0 && code[i] === "`") {
91
+ out += code[i];
92
+ i++;
93
+ break;
94
+ }
95
+ if (interpolationDepth === 0 && code[i] === "\\") {
96
+ out += code[i] + (code[i + 1] ?? "");
97
+ i += 2;
98
+ continue;
99
+ }
100
+ if (interpolationDepth === 0 && code[i] + (code[i + 1] ?? "") === "${") {
101
+ out += "${";
102
+ i += 2;
103
+ interpolationDepth = 1;
104
+ continue;
105
+ }
106
+ if (interpolationDepth > 0) {
107
+ if (code[i] === "{") interpolationDepth++;
108
+ else if (code[i] === "}") {
109
+ interpolationDepth--;
110
+ if (interpolationDepth === 0) {
111
+ out += "}";
112
+ i++;
113
+ continue;
114
+ }
115
+ }
116
+ }
117
+ out += code[i];
118
+ i++;
119
+ }
120
+ continue;
121
+ }
122
+ out += ch;
123
+ i++;
124
+ }
125
+ return out;
126
+ }
127
+ function splitClassTokens(str) {
128
+ return str.split(/\s+/).filter(Boolean);
129
+ }
130
+ var NOT_A_CLASS_NAME_RE = /[${}]|-$|^[?:&|!"'=<>]+$/;
131
+ function pushTokens(str, into) {
132
+ for (const tok of splitClassTokens(str)) {
133
+ if (tok && !NOT_A_CLASS_NAME_RE.test(tok)) into.add(tok);
134
+ }
135
+ }
136
+ function pushTemplateLiteralBody(body, into) {
137
+ const interpolationRe = /\$\{(?:[^{}]|\{[^{}]*\})*\}/g;
138
+ let im;
139
+ while ((im = interpolationRe.exec(body)) !== null) {
140
+ pushClassLikeStrings(im[0], into);
141
+ }
142
+ pushTokens(body.replace(/\$\{(?:[^{}]|\{[^{}]*\})*\}/g, () => "$"), into);
143
+ }
144
+ function pushClassLikeStrings(text, into) {
145
+ const quotedStringRe = /(["'`])((?:(?!\1).)*)\1/g;
146
+ let qm;
147
+ while ((qm = quotedStringRe.exec(text)) !== null) {
148
+ const [, quote, content] = qm;
149
+ if (quote === "`") pushTemplateLiteralBody(content, into);
150
+ else pushTokens(content, into);
151
+ }
152
+ }
153
+ var JSX_TAG_RE = /<([a-z][a-zA-Z0-9]*)[\s/>]/g;
154
+ function scanUsedTags(code) {
155
+ const cleaned = stripComments(code);
156
+ const tags = /* @__PURE__ */ new Set();
157
+ let m;
158
+ JSX_TAG_RE.lastIndex = 0;
159
+ while ((m = JSX_TAG_RE.exec(cleaned)) !== null) tags.add(m[1]);
160
+ return tags;
161
+ }
162
+ function extractClassStrings(rawCode) {
163
+ const code = stripComments(rawCode);
164
+ const found = /* @__PURE__ */ new Set();
165
+ const simpleRe = /(?:className|kb)=(["'])((?:(?!\1).)*)\1/g;
166
+ let m;
167
+ while ((m = simpleRe.exec(code)) !== null) pushTokens(m[2], found);
168
+ const MAX_BLOCK_SCAN_LEN = 2e4;
169
+ const jsxExprRe = /\b(?:className|kb)=\{/g;
170
+ while ((m = jsxExprRe.exec(code)) !== null) {
171
+ let depth = 1;
172
+ let i = m.index + m[0].length;
173
+ const scanEnd = Math.min(code.length, i + MAX_BLOCK_SCAN_LEN);
174
+ let block = "";
175
+ while (i < scanEnd && depth > 0) {
176
+ const ch = code[i];
177
+ if (ch === "{") depth++;
178
+ else if (ch === "}") {
179
+ if (--depth === 0) break;
180
+ }
181
+ block += ch;
182
+ i++;
183
+ }
184
+ jsxExprRe.lastIndex = i + 1;
185
+ if (depth === 0) pushClassLikeStrings(block, found);
186
+ }
187
+ const classComposerCallRe = /\b(?:clsx|cn|classnames|cx|kb)\(/g;
188
+ while ((m = classComposerCallRe.exec(code)) !== null) {
189
+ let depth = 1;
190
+ let i = m.index + m[0].length;
191
+ const scanEnd = Math.min(code.length, i + MAX_BLOCK_SCAN_LEN);
192
+ let block = "";
193
+ while (i < scanEnd && depth > 0) {
194
+ const ch = code[i];
195
+ if (ch === "(") depth++;
196
+ else if (ch === ")") {
197
+ if (--depth === 0) break;
198
+ }
199
+ block += ch;
200
+ i++;
201
+ }
202
+ classComposerCallRe.lastIndex = i + 1;
203
+ if (depth === 0) pushClassLikeStrings(block, found);
204
+ }
205
+ const templateRe = /`([^`]{1,2000})`/g;
206
+ while ((m = templateRe.exec(code)) !== null) pushTemplateLiteralBody(m[1], found);
207
+ return [...found];
208
+ }
209
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "dist", "build", "out", ".next", ".output", ".git", ".svn", ".cache", "coverage"]);
210
+ var MAX_SCAN_DEPTH = 10;
211
+ var DEFAULT_FILE_MATCH = /\.(tsx?|jsx?)$/;
212
+ function scanDir(dir, onFile, depth = 0, fileMatch = DEFAULT_FILE_MATCH) {
213
+ if (depth > MAX_SCAN_DEPTH) return;
214
+ let entries;
215
+ try {
216
+ entries = (0, import_fs.readdirSync)(dir);
217
+ } catch {
218
+ return;
219
+ }
220
+ for (const entry of entries) {
221
+ if (entry.startsWith(".") || SKIP_DIRS.has(entry)) continue;
222
+ const full = (0, import_path.join)(dir, entry);
223
+ try {
224
+ const st = (0, import_fs.statSync)(full);
225
+ if (st.isDirectory()) scanDir(full, onFile, depth + 1, fileMatch);
226
+ else if (fileMatch.test(entry)) onFile(full, (0, import_fs.readFileSync)(full, "utf-8"));
227
+ } catch {
228
+ }
229
+ }
230
+ }
231
+
232
+ // src/vite-plugin/cssVars.ts
233
+ function hexToRgbTriplet(hex) {
234
+ const h = hex.replace("#", "");
235
+ const expand = (s) => s.length === 3 ? s.split("").map((c) => c + c).join("") : s;
236
+ const full = expand(h);
237
+ if (full.length !== 6) return null;
238
+ const r = parseInt(full.slice(0, 2), 16);
239
+ const g = parseInt(full.slice(2, 4), 16);
240
+ const b = parseInt(full.slice(4, 6), 16);
241
+ if ([r, g, b].some((n) => Number.isNaN(n))) return null;
242
+ return `${r},${g},${b}`;
243
+ }
244
+ function buildColorVarMap(theme, cssText) {
245
+ const replacements = /* @__PURE__ */ new Map();
246
+ const declarations = /* @__PURE__ */ new Map();
247
+ for (const [name, value] of Object.entries(theme.colors)) {
248
+ if (typeof value !== "string") continue;
249
+ const varName = `--color-${name}`;
250
+ if (cssText.includes(value)) {
251
+ replacements.set(value, `var(${varName})`);
252
+ declarations.set(varName, value);
253
+ }
254
+ const triplet = hexToRgbTriplet(value);
255
+ if (!triplet) continue;
256
+ const rgbaPrefix = `rgba(${triplet},`;
257
+ if (cssText.includes(rgbaPrefix)) {
258
+ const rgbVarName = `--color-${name}-rgb`;
259
+ replacements.set(rgbaPrefix, `rgba(var(${rgbVarName}),`);
260
+ declarations.set(rgbVarName, triplet);
261
+ }
262
+ }
263
+ return { replacements, declarations };
264
+ }
265
+ var SPACING_PROPS = /* @__PURE__ */ new Set([
266
+ "padding",
267
+ "padding-top",
268
+ "padding-right",
269
+ "padding-bottom",
270
+ "padding-left",
271
+ "margin",
272
+ "margin-top",
273
+ "margin-right",
274
+ "margin-bottom",
275
+ "margin-left",
276
+ "gap",
277
+ "column-gap",
278
+ "row-gap",
279
+ "width",
280
+ "height",
281
+ "min-width",
282
+ "min-height",
283
+ "max-width",
284
+ "max-height",
285
+ "top",
286
+ "right",
287
+ "bottom",
288
+ "left"
289
+ ]);
290
+ function buildSpacingVarMap(theme, cssText) {
291
+ const replacements = /* @__PURE__ */ new Map();
292
+ const declarations = /* @__PURE__ */ new Map();
293
+ const pxToKey = /* @__PURE__ */ new Map();
294
+ for (const [key, val] of Object.entries(theme.spacing)) {
295
+ if (!pxToKey.has(val)) pxToKey.set(val, key);
296
+ }
297
+ const varNameFor = (key) => `--spacing-${key.replace(/\./g, "_")}`;
298
+ const declRe = /([a-z-]+): (\d+(?:\.\d+)?)px/g;
299
+ let m;
300
+ while ((m = declRe.exec(cssText)) !== null) {
301
+ const [, prop, numStr] = m;
302
+ if (!SPACING_PROPS.has(prop)) continue;
303
+ const key = pxToKey.get(parseFloat(numStr));
304
+ if (key === void 0) continue;
305
+ const varName = varNameFor(key);
306
+ replacements.set(`${prop}: ${numStr}px`, `${prop}: var(${varName})`);
307
+ declarations.set(varName, `${numStr}px`);
308
+ }
309
+ return { replacements, declarations };
310
+ }
311
+ function applyVarMap(cssText, ...maps) {
312
+ const replacements = /* @__PURE__ */ new Map();
313
+ const declarations = /* @__PURE__ */ new Map();
314
+ for (const map of maps) {
315
+ for (const [k, v] of map.replacements) replacements.set(k, v);
316
+ for (const [k, v] of map.declarations) declarations.set(k, v);
317
+ }
318
+ const sorted = [...replacements].sort(([a], [b]) => b.length - a.length);
319
+ const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
320
+ const patterns = sorted.map(([pattern, replacement]) => [new RegExp(escapeRegex(pattern), "g"), replacement]);
321
+ const text = cssText.replace(/\{([^{}]*)\}/g, (_whole, inner) => {
322
+ let replaced = inner;
323
+ for (const [re, replacement] of patterns) {
324
+ replaced = replaced.replace(re, () => replacement);
325
+ }
326
+ return `{${replaced}}`;
327
+ });
328
+ return { text, declarations };
329
+ }
330
+
331
+ // src/vite-plugin/mediaMerge.ts
332
+ var RESPONSIVE_MEDIA_RE = /^@media \(min-width: (\d+)px\) \{ (.+) \}$/;
333
+ function mergeResponsiveMediaBlocks(rules) {
334
+ const byWidth = /* @__PURE__ */ new Map();
335
+ const widthOrder = [];
336
+ const unwrapped = [];
337
+ for (const rule of rules) {
338
+ const m = RESPONSIVE_MEDIA_RE.exec(rule);
339
+ if (!m) {
340
+ unwrapped.push(rule);
341
+ continue;
342
+ }
343
+ const width = Number(m[1]);
344
+ if (!byWidth.has(width)) {
345
+ byWidth.set(width, []);
346
+ widthOrder.push(width);
347
+ }
348
+ byWidth.get(width).push(m[2]);
349
+ }
350
+ widthOrder.sort((a, b) => a - b);
351
+ const merged = widthOrder.map((w) => `@media (min-width: ${w}px) { ${byWidth.get(w).join(" ")} }`);
352
+ return [...unwrapped, ...merged];
353
+ }
354
+
355
+ // src/vite-plugin/prettify.ts
356
+ function prettifyCSS(css) {
357
+ const out = [];
358
+ let depth = 0;
359
+ let current = "";
360
+ for (const ch of css) {
361
+ if (ch === "{") {
362
+ const selector = current.trim();
363
+ if (selector) out.push(`${" ".repeat(depth)}${selector} {`);
364
+ depth++;
365
+ current = "";
366
+ } else if (ch === "}") {
367
+ const decl = current.trim();
368
+ if (decl) out.push(`${" ".repeat(depth)}${decl};`);
369
+ depth = Math.max(0, depth - 1);
370
+ out.push(`${" ".repeat(depth)}}`);
371
+ current = "";
372
+ } else if (ch === ";") {
373
+ const decl = current.trim();
374
+ if (decl) out.push(`${" ".repeat(depth)}${decl};`);
375
+ current = "";
376
+ } else {
377
+ current += ch;
378
+ }
379
+ }
380
+ const trailing = current.trim();
381
+ if (trailing) out.push(trailing);
382
+ return out.join("\n");
383
+ }
384
+
385
+ // src/reset.ts
386
+ var RESET_RULES = [
387
+ // border-style: solid means border-N utilities show a visible border without an extra border-solid class.
388
+ // border-width: 0 keeps all elements borderless by default.
389
+ { css: "*, *::before, *::after { box-sizing: border-box; border-width: 0; border-style: solid; border-color: currentColor; }" },
390
+ { css: "body { margin: 0; padding: 0; }" },
391
+ { css: "h1, h2, h3, h4, h5, h6 { margin: 0; font-size: inherit; font-weight: inherit; }", tags: ["h1", "h2", "h3", "h4", "h5", "h6"] },
392
+ { css: "p { margin: 0; }", tags: ["p"] },
393
+ { css: "a { color: inherit; text-decoration: none; }", tags: ["a"] },
394
+ { css: "ul, ol { margin: 0; padding: 0; list-style: none; }", tags: ["ul", "ol"] },
395
+ // svg here only covers a literal <svg> tag in JSX — an icon imported as
396
+ // a component (e.g. `<ArrowIcon />`) never appears as the text "svg" in
397
+ // source, so this rule won't be pulled in by that usage alone. Same
398
+ // caveat applies to every tag-gated rule below: detection is a literal
399
+ // source-text scan (see vite-plugin/scan.ts's scanUsedTags), not a real
400
+ // DOM/type check.
401
+ { css: "img, video, svg { display: block; max-width: 100%; }", tags: ["img", "video", "svg"] },
402
+ // appearance: none is deliberately NOT applied to checkbox/radio/select below —
403
+ // stripping it hides their native checkmark/arrow with nothing rendered in its
404
+ // place, leaving an invisible checkbox or an arrow-less <select> that looks like
405
+ // plain text. Text-like inputs, textarea, and button don't have that problem
406
+ // (their native chrome is just a skin around content utilities can fully
407
+ // restyle), so they keep the blank-canvas treatment.
408
+ // :where() wraps the :not() exclusions so they contribute ZERO specificity
409
+ // (unlike a bare `input:not([type='checkbox']):not([type='radio'])`, whose
410
+ // two :not([attr]) clauses each add a class-level specificity point — (0,2,1)
411
+ // total, MORE than any single utility class (0,1,0)). Without :where(), this
412
+ // reset's `color: inherit` always won the cascade over a text-* color
413
+ // utility applied directly to a <input>/<textarea> regardless of source
414
+ // order, since author rules only override on a tie or higher specificity —
415
+ // confirmed on a real app: a TextInput's own text color utility resolved
416
+ // and injected correctly, class and all, but silently never painted.
417
+ {
418
+ css: "input:where(:not([type='checkbox']):not([type='radio'])), textarea { appearance: none; -webkit-appearance: none; background: transparent; padding: 0; margin: 0; font: inherit; color: inherit; line-height: inherit; }",
419
+ tags: ["input", "textarea"]
420
+ },
421
+ // Native checkbox/radio/range still get typography + spacing normalized, and
422
+ // accent-color re-themes their native indicator to the current text color
423
+ // instead of the browser/OS default blue, so they stay on-brand without
424
+ // needing to be rebuilt from scratch. Wrapped in :where() for the exact
425
+ // same reason as the input:not(...) exclusions above — a bare
426
+ // `input[type='range']` attribute selector has specificity (0,1,1),
427
+ // MORE than any single utility class (0,1,0), so an `accent-*` utility
428
+ // (Phase 23) applied directly to a checkbox/radio/range would resolve and
429
+ // inject correctly but silently never paint, losing the cascade to this
430
+ // reset regardless of source order — confirmed by hand via
431
+ // getComputedStyle on a real `accent-red-6` range input, which reported
432
+ // `currentColor`'s inherited value instead. `:where()` zeroes this
433
+ // selector's specificity contribution entirely, so any `accent-*`
434
+ // utility trivially wins once applied.
435
+ {
436
+ css: ":where(input[type='checkbox'], input[type='radio'], input[type='range']) { margin: 0; font: inherit; accent-color: currentColor; }",
437
+ tags: ["input"]
438
+ },
439
+ // select keeps its native chrome (border/background/arrow are all part of the
440
+ // same OS-drawn widget that appearance: none would blank out) — only typography
441
+ // and spacing are normalized so it still matches surrounding text.
442
+ { css: "select { margin: 0; font: inherit; color: inherit; line-height: inherit; }", tags: ["select"] },
443
+ { css: "button { appearance: none; -webkit-appearance: none; background: transparent; padding: 0; margin: 0; font: inherit; color: inherit; cursor: pointer; line-height: inherit; text-align: inherit; }", tags: ["button"] },
444
+ // Also covers any element opted into the button role (`role="button"` on
445
+ // a <div>/<span>) — but only when a literal <button> tag is ALSO
446
+ // somewhere in the scanned source, since detection here is purely
447
+ // tag-name-based; a project using role="button" exclusively, with no
448
+ // real <button> anywhere, won't pull this rule in. Acceptable tradeoff
449
+ // for this project's scope (rare pattern) — cheap enough that scanning
450
+ // for it separately isn't worth the added complexity.
451
+ { css: "button, [role='button'] { cursor: pointer; }", tags: ["button"] },
452
+ { css: ":disabled { cursor: default; }", tags: ["button", "input", "select", "textarea"] },
453
+ { css: "textarea { resize: vertical; }", tags: ["textarea"] },
454
+ // Firefox renders placeholders at ~54% opacity by default; every other browser uses 1 —
455
+ // normalize to 1 so placeholder color is consistent and fully controlled by the placeholder: modifier.
456
+ { css: "::placeholder { opacity: 1; }", tags: ["input", "textarea"] },
457
+ { css: "input[type='number']::-webkit-inner-spin-button, input[type='number']::-webkit-outer-spin-button { margin: 0; }", tags: ["input"] },
458
+ { css: "input[type='search']::-webkit-search-decoration, input[type='search']::-webkit-search-cancel-button { -webkit-appearance: none; }", tags: ["input"] },
459
+ { css: "fieldset { padding: 0; margin: 0; }", tags: ["fieldset"] },
460
+ { css: "table { border-collapse: collapse; border-spacing: 0; }", tags: ["table"] }
461
+ ];
462
+ var BASE_RESET = RESET_RULES.map((r) => r.css).join("\n");
463
+ function buildResetCSS(usedTags) {
464
+ if (!usedTags) return BASE_RESET;
465
+ return RESET_RULES.filter((r) => !r.tags || r.tags.some((t) => usedTags.has(t))).map((r) => r.css).join("\n");
466
+ }
467
+
468
+ // src/vite-plugin/format.ts
469
+ function formatKbachCSS(tokenRules, theme, usedTags) {
470
+ const allEntries = [];
471
+ for (const rules of tokenRules.values()) {
472
+ for (const entry of rules) allEntries.push(entry);
473
+ }
474
+ allEntries.sort((a, b) => a.order - b.order);
475
+ const allRules = allEntries.map((e) => e.rule);
476
+ const merged = mergeResponsiveMediaBlocks(allRules);
477
+ const compact = merged.join("\n");
478
+ const colorMap = buildColorVarMap(theme, compact);
479
+ const spacingMap = buildSpacingVarMap(theme, compact);
480
+ const { text, declarations } = applyVarMap(compact, colorMap, spacingMap);
481
+ const lines = ["/* Generated by Kbach \u2014 do not edit */", "", buildResetCSS(usedTags)];
482
+ lines.push("", ":root {", ` --kb-dark-mode: ${theme.darkMode};`);
483
+ for (const [varName, val] of declarations) lines.push(` ${varName}: ${val};`);
484
+ lines.push("}");
485
+ lines.push("", prettifyCSS(text));
486
+ return lines.join("\n");
487
+ }
488
+
489
+ // src/vite-plugin/unknownClassWarnings.ts
490
+ var import_path2 = require("path");
491
+
492
+ // src/terminalWarn.ts
493
+ var useColor = !!process.stdout?.isTTY && !process.env.NO_COLOR;
494
+ var paint = (code, s) => useColor ? `\x1B[${code}m${s}\x1B[0m` : s;
495
+ var green = (s) => paint("32", s);
496
+ var blue = (s) => paint("34", s);
497
+ var white = (s) => paint("97", s);
498
+ var gray = (s) => paint("90", s);
499
+ var bold = (s) => paint("1", s);
500
+ var highlight = (s) => bold(white(s));
501
+ function kbachTag() {
502
+ return `${green("\u2192")} ${bold(green("[Kbach]"))}`;
503
+ }
504
+
505
+ // src/vite-plugin/unknownClassWarnings.ts
506
+ var CSS_CLASS_SELECTOR_RE = /\.(-?[a-zA-Z_][a-zA-Z0-9_-]*)/g;
507
+ var CSS_FILE_RE = /\.(css|scss|sass|less)$/;
508
+ function findLineCol(code, needle) {
509
+ const index = code.indexOf(needle);
510
+ if (index === -1) return null;
511
+ let line = 1;
512
+ let lastNewline = -1;
513
+ for (let i = 0; i < index; i++) {
514
+ if (code.charCodeAt(i) === 10) {
515
+ line++;
516
+ lastNewline = i;
517
+ }
518
+ }
519
+ return { line, column: index - lastNewline };
520
+ }
521
+ function scanCssFileInto(code, into) {
522
+ const re = new RegExp(CSS_CLASS_SELECTOR_RE.source, "g");
523
+ let m;
524
+ while ((m = re.exec(code)) !== null) into.add(m[1]);
525
+ }
526
+ function scanProjectCssSelectors(root, includeDirs) {
527
+ const projectCssClasses = /* @__PURE__ */ new Set();
528
+ for (const dir of includeDirs) {
529
+ scanDir((0, import_path2.join)(root, dir), (_filePath, code) => scanCssFileInto(code, projectCssClasses), 0, CSS_FILE_RE);
530
+ }
531
+ return projectCssClasses;
532
+ }
533
+ function stripModifierPrefix(token) {
534
+ return token.replace(/^(?:[a-zA-Z0-9_/-]+:)+/, "");
535
+ }
536
+ var MARKER_CLASSES = /* @__PURE__ */ new Set(["group", "peer"]);
537
+ function isMarkerClass(base) {
538
+ if (MARKER_CLASSES.has(base)) return true;
539
+ const slashIdx = base.lastIndexOf("/");
540
+ if (slashIdx === -1) return false;
541
+ return MARKER_CLASSES.has(base.slice(0, slashIdx)) && slashIdx < base.length - 1;
542
+ }
543
+ function warnIfUnknownClass(token, filePath, code, isResolvable, projectCssClasses, warnedTokens) {
544
+ if (isResolvable || warnedTokens.has(token)) return;
545
+ const base = stripModifierPrefix(token);
546
+ if (!base || projectCssClasses.has(base) || isMarkerClass(base)) return;
547
+ warnedTokens.add(token);
548
+ const pos = findLineCol(code, token);
549
+ const location = pos ? `${blue(filePath)}${green(`:${pos.line}:${pos.column}`)}` : blue(filePath);
550
+ console.warn(
551
+ `${kbachTag()} ${gray("Unknown class")} ${highlight(token)} ${gray("\u2014 no Kbach utility or project CSS rule matches it. Typo?")}
552
+ ${bold("at")} ${location}`
553
+ );
554
+ }
555
+
556
+ // src/staticCss/engine.ts
557
+ function normPath(p) {
558
+ const fwd = p.replace(/\\/g, "/");
559
+ return process.platform === "win32" ? fwd.toLowerCase() : fwd;
560
+ }
561
+ var SAFELIST_KEY = "\0kbach-safelist";
562
+ function createKbachStaticCssEngine(options) {
563
+ const { root, theme, themeJson, includeDirs, safelist } = options;
564
+ const fileTokens = /* @__PURE__ */ new Map();
565
+ const tokenRules = /* @__PURE__ */ new Map();
566
+ const fileTags = /* @__PURE__ */ new Map();
567
+ let projectCssClasses = /* @__PURE__ */ new Set();
568
+ const warnedTokens = /* @__PURE__ */ new Set();
569
+ function resolveToken(tok) {
570
+ if (!tokenRules.has(tok)) {
571
+ tokenRules.set(tok, generateCssForToken(tok, themeJson).rules);
572
+ }
573
+ return tokenRules.get(tok);
574
+ }
575
+ function processFile(filePath, code) {
576
+ const tokens = /* @__PURE__ */ new Set();
577
+ for (const tok of extractClassStrings(code)) {
578
+ tokens.add(tok);
579
+ const rules = resolveToken(tok);
580
+ if (process.env.NODE_ENV !== "production") {
581
+ warnIfUnknownClass(tok, filePath, code, rules.length > 0, projectCssClasses, warnedTokens);
582
+ }
583
+ }
584
+ fileTokens.set(normPath(filePath), tokens);
585
+ fileTags.set(normPath(filePath), scanUsedTags(code));
586
+ }
587
+ function removeFile(filePath) {
588
+ fileTokens.delete(normPath(filePath));
589
+ fileTags.delete(normPath(filePath));
590
+ }
591
+ function processSafelist() {
592
+ if (safelist.length === 0) return;
593
+ const tokens = new Set(safelist);
594
+ for (const tok of tokens) resolveToken(tok);
595
+ fileTokens.set(SAFELIST_KEY, tokens);
596
+ }
597
+ function activeTokens() {
598
+ const active = /* @__PURE__ */ new Set();
599
+ for (const tokens of fileTokens.values()) for (const t of tokens) active.add(t);
600
+ return active;
601
+ }
602
+ function activeTags() {
603
+ const active = /* @__PURE__ */ new Set();
604
+ for (const tags of fileTags.values()) for (const t of tags) active.add(t);
605
+ return active;
606
+ }
607
+ function generateCSS() {
608
+ const active = activeTokens();
609
+ const view = /* @__PURE__ */ new Map();
610
+ for (const tok of active) {
611
+ const rules = tokenRules.get(tok);
612
+ if (rules) view.set(tok, rules);
613
+ }
614
+ for (const tok of tokenRules.keys()) {
615
+ if (!active.has(tok)) tokenRules.delete(tok);
616
+ }
617
+ return formatKbachCSS(view, theme, activeTags());
618
+ }
619
+ function initialScan() {
620
+ for (const dir of includeDirs) {
621
+ scanDir((0, import_path3.join)(root, dir), processFile);
622
+ }
623
+ }
624
+ function scanProjectCssSelectorsOnce() {
625
+ projectCssClasses = scanProjectCssSelectors(root, includeDirs);
626
+ }
627
+ return { processFile, removeFile, initialScan, processSafelist, generateCSS, scanProjectCssSelectorsOnce };
628
+ }
629
+
630
+ // src/vite-plugin/index.ts
631
+ var import_fs2 = require("fs");
632
+ var import_path4 = require("path");
633
+ var import_url = require("url");
634
+ var import_module = require("module");
635
+
636
+ // src/generatedPalette.ts
637
+ var PALETTE = {
638
+ "amber-1": "#fffbeb",
639
+ "amber-10": "#78350f",
640
+ "amber-11": "#451a03",
641
+ "amber-12": "#291002",
642
+ "amber-2": "#fef3c7",
643
+ "amber-3": "#fde68a",
644
+ "amber-4": "#fcd34d",
645
+ "amber-5": "#fbbf24",
646
+ "amber-6": "#f59e0b",
647
+ "amber-7": "#d97706",
648
+ "amber-8": "#b45309",
649
+ "amber-9": "#92400e",
650
+ "black": "#000000",
651
+ "blue-1": "#eff6ff",
652
+ "blue-10": "#1e3a8a",
653
+ "blue-11": "#172554",
654
+ "blue-12": "#0d1633",
655
+ "blue-2": "#dbeafe",
656
+ "blue-3": "#bfdbfe",
657
+ "blue-4": "#93c5fd",
658
+ "blue-5": "#60a5fa",
659
+ "blue-6": "#3b82f6",
660
+ "blue-7": "#2563eb",
661
+ "blue-8": "#1d4ed8",
662
+ "blue-9": "#1e40af",
663
+ "bronze": "#cd7f32",
664
+ "coal": "#1c1c1c",
665
+ "copper": "#b87333",
666
+ "current": "currentColor",
667
+ "cyan-1": "#ecfeff",
668
+ "cyan-10": "#164e63",
669
+ "cyan-11": "#083344",
670
+ "cyan-12": "#041e28",
671
+ "cyan-2": "#cffafe",
672
+ "cyan-3": "#a5f3fc",
673
+ "cyan-4": "#67e8f9",
674
+ "cyan-5": "#22d3ee",
675
+ "cyan-6": "#06b6d4",
676
+ "cyan-7": "#0891b2",
677
+ "cyan-8": "#0e7490",
678
+ "cyan-9": "#155e75",
679
+ "emerald-1": "#ecfdf5",
680
+ "emerald-10": "#064e3b",
681
+ "emerald-11": "#022c22",
682
+ "emerald-12": "#011a14",
683
+ "emerald-2": "#d1fae5",
684
+ "emerald-3": "#a7f3d0",
685
+ "emerald-4": "#6ee7b7",
686
+ "emerald-5": "#34d399",
687
+ "emerald-6": "#10b981",
688
+ "emerald-7": "#059669",
689
+ "emerald-8": "#047857",
690
+ "emerald-9": "#065f46",
691
+ "fuchsia-1": "#fdf4ff",
692
+ "fuchsia-10": "#701a75",
693
+ "fuchsia-11": "#4a044e",
694
+ "fuchsia-12": "#2d022f",
695
+ "fuchsia-2": "#fae8ff",
696
+ "fuchsia-3": "#f5d0fe",
697
+ "fuchsia-4": "#f0abfc",
698
+ "fuchsia-5": "#e879f9",
699
+ "fuchsia-6": "#d946ef",
700
+ "fuchsia-7": "#c026d3",
701
+ "fuchsia-8": "#a21caf",
702
+ "fuchsia-9": "#86198f",
703
+ "gold": "#d4af37",
704
+ "gray-1": "#f9fafb",
705
+ "gray-10": "#111827",
706
+ "gray-11": "#030712",
707
+ "gray-12": "#020409",
708
+ "gray-2": "#f3f4f6",
709
+ "gray-3": "#e5e7eb",
710
+ "gray-4": "#d1d5db",
711
+ "gray-5": "#9ca3af",
712
+ "gray-6": "#6b7280",
713
+ "gray-7": "#4b5563",
714
+ "gray-8": "#374151",
715
+ "gray-9": "#1f2937",
716
+ "green-1": "#f0fdf4",
717
+ "green-10": "#14532d",
718
+ "green-11": "#052e16",
719
+ "green-12": "#031b0d",
720
+ "green-2": "#dcfce7",
721
+ "green-3": "#bbf7d0",
722
+ "green-4": "#86efac",
723
+ "green-5": "#4ade80",
724
+ "green-6": "#22c55e",
725
+ "green-7": "#16a34a",
726
+ "green-8": "#15803d",
727
+ "green-9": "#166534",
728
+ "indigo-1": "#eef2ff",
729
+ "indigo-10": "#312e81",
730
+ "indigo-11": "#1e1b4b",
731
+ "indigo-12": "#12102d",
732
+ "indigo-2": "#e0e7ff",
733
+ "indigo-3": "#c7d2fe",
734
+ "indigo-4": "#a5b4fc",
735
+ "indigo-5": "#818cf8",
736
+ "indigo-6": "#6366f1",
737
+ "indigo-7": "#4f46e5",
738
+ "indigo-8": "#4338ca",
739
+ "indigo-9": "#3730a3",
740
+ "lime-1": "#f7fee7",
741
+ "lime-10": "#365314",
742
+ "lime-11": "#1a2e05",
743
+ "lime-12": "#0f1b03",
744
+ "lime-2": "#ecfccb",
745
+ "lime-3": "#d9f99d",
746
+ "lime-4": "#bef264",
747
+ "lime-5": "#a3e635",
748
+ "lime-6": "#84cc16",
749
+ "lime-7": "#65a30d",
750
+ "lime-8": "#4d7c0f",
751
+ "lime-9": "#3f6212",
752
+ "neutral-1": "#fafafa",
753
+ "neutral-10": "#171717",
754
+ "neutral-11": "#0a0a0a",
755
+ "neutral-12": "#050505",
756
+ "neutral-2": "#f5f5f5",
757
+ "neutral-3": "#e5e5e5",
758
+ "neutral-4": "#d4d4d4",
759
+ "neutral-5": "#a3a3a3",
760
+ "neutral-6": "#737373",
761
+ "neutral-7": "#525252",
762
+ "neutral-8": "#404040",
763
+ "neutral-9": "#262626",
764
+ "orange-1": "#fff7ed",
765
+ "orange-10": "#7c2d12",
766
+ "orange-11": "#431407",
767
+ "orange-12": "#270c04",
768
+ "orange-2": "#ffedd5",
769
+ "orange-3": "#fed7aa",
770
+ "orange-4": "#fdba74",
771
+ "orange-5": "#fb923c",
772
+ "orange-6": "#f97316",
773
+ "orange-7": "#ea580c",
774
+ "orange-8": "#c2410c",
775
+ "orange-9": "#9a3412",
776
+ "pink-1": "#fdf2f8",
777
+ "pink-10": "#831843",
778
+ "pink-11": "#500724",
779
+ "pink-12": "#300415",
780
+ "pink-2": "#fce7f3",
781
+ "pink-3": "#fbcfe8",
782
+ "pink-4": "#f9a8d4",
783
+ "pink-5": "#f472b6",
784
+ "pink-6": "#ec4899",
785
+ "pink-7": "#db2777",
786
+ "pink-8": "#be185d",
787
+ "pink-9": "#9d174d",
788
+ "purple-1": "#faf5ff",
789
+ "purple-10": "#581c87",
790
+ "purple-11": "#3b0764",
791
+ "purple-12": "#23043c",
792
+ "purple-2": "#f3e8ff",
793
+ "purple-3": "#e9d5ff",
794
+ "purple-4": "#d8b4fe",
795
+ "purple-5": "#c084fc",
796
+ "purple-6": "#a855f7",
797
+ "purple-7": "#9333ea",
798
+ "purple-8": "#7e22ce",
799
+ "purple-9": "#6b21a8",
800
+ "red-1": "#fef2f2",
801
+ "red-10": "#7f1d1d",
802
+ "red-11": "#450a0a",
803
+ "red-12": "#280606",
804
+ "red-2": "#fee2e2",
805
+ "red-3": "#fecaca",
806
+ "red-4": "#fca5a5",
807
+ "red-5": "#f87171",
808
+ "red-6": "#ef4444",
809
+ "red-7": "#dc2626",
810
+ "red-8": "#b91c1c",
811
+ "red-9": "#991b1b",
812
+ "rose-1": "#fff1f2",
813
+ "rose-10": "#881337",
814
+ "rose-11": "#4c0519",
815
+ "rose-12": "#2d030e",
816
+ "rose-2": "#ffe4e6",
817
+ "rose-3": "#fecdd3",
818
+ "rose-4": "#fda4af",
819
+ "rose-5": "#fb7185",
820
+ "rose-6": "#f43f5e",
821
+ "rose-7": "#e11d48",
822
+ "rose-8": "#be123c",
823
+ "rose-9": "#9f1239",
824
+ "silver": "#c0c0c0",
825
+ "sky-1": "#f0f9ff",
826
+ "sky-10": "#0c4a6e",
827
+ "sky-11": "#082f49",
828
+ "sky-12": "#041b2b",
829
+ "sky-2": "#e0f2fe",
830
+ "sky-3": "#bae6fd",
831
+ "sky-4": "#7dd3fc",
832
+ "sky-5": "#38bdf8",
833
+ "sky-6": "#0ea5e9",
834
+ "sky-7": "#0284c7",
835
+ "sky-8": "#0369a1",
836
+ "sky-9": "#075985",
837
+ "slate-1": "#f8fafc",
838
+ "slate-10": "#0f172a",
839
+ "slate-11": "#020617",
840
+ "slate-12": "#01020a",
841
+ "slate-2": "#f1f5f9",
842
+ "slate-3": "#e2e8f0",
843
+ "slate-4": "#cbd5e1",
844
+ "slate-5": "#94a3b8",
845
+ "slate-6": "#64748b",
846
+ "slate-7": "#475569",
847
+ "slate-8": "#334155",
848
+ "slate-9": "#1e293b",
849
+ "stone-1": "#fafaf9",
850
+ "stone-10": "#1c1917",
851
+ "stone-11": "#0c0a09",
852
+ "stone-12": "#070605",
853
+ "stone-2": "#f5f5f4",
854
+ "stone-3": "#e7e5e4",
855
+ "stone-4": "#d6d3d1",
856
+ "stone-5": "#a8a29e",
857
+ "stone-6": "#78716c",
858
+ "stone-7": "#57534e",
859
+ "stone-8": "#44403c",
860
+ "stone-9": "#292524",
861
+ "teal-1": "#f0fdfa",
862
+ "teal-10": "#134e4a",
863
+ "teal-11": "#042f2e",
864
+ "teal-12": "#021c1b",
865
+ "teal-2": "#ccfbf1",
866
+ "teal-3": "#99f6e4",
867
+ "teal-4": "#5eead4",
868
+ "teal-5": "#2dd4bf",
869
+ "teal-6": "#14b8a6",
870
+ "teal-7": "#0d9488",
871
+ "teal-8": "#0f766e",
872
+ "teal-9": "#115e59",
873
+ "transparent": "transparent",
874
+ "violet-1": "#f5f3ff",
875
+ "violet-10": "#4c1d95",
876
+ "violet-11": "#2e1065",
877
+ "violet-12": "#1c0a3d",
878
+ "violet-2": "#ede9fe",
879
+ "violet-3": "#ddd6fe",
880
+ "violet-4": "#c4b5fd",
881
+ "violet-5": "#a78bfa",
882
+ "violet-6": "#8b5cf6",
883
+ "violet-7": "#7c3aed",
884
+ "violet-8": "#6d28d9",
885
+ "violet-9": "#5b21b6",
886
+ "white": "#ffffff",
887
+ "yellow-1": "#fefce8",
888
+ "yellow-10": "#713f12",
889
+ "yellow-11": "#422006",
890
+ "yellow-12": "#271304",
891
+ "yellow-2": "#fef9c3",
892
+ "yellow-3": "#fef08a",
893
+ "yellow-4": "#fde047",
894
+ "yellow-5": "#facc15",
895
+ "yellow-6": "#eab308",
896
+ "yellow-7": "#ca8a04",
897
+ "yellow-8": "#a16207",
898
+ "yellow-9": "#854d0e",
899
+ "zinc-1": "#fafafa",
900
+ "zinc-10": "#18181b",
901
+ "zinc-11": "#09090b",
902
+ "zinc-12": "#050506",
903
+ "zinc-2": "#f4f4f5",
904
+ "zinc-3": "#e4e4e7",
905
+ "zinc-4": "#d4d4d8",
906
+ "zinc-5": "#a1a1aa",
907
+ "zinc-6": "#71717a",
908
+ "zinc-7": "#52525b",
909
+ "zinc-8": "#3f3f46",
910
+ "zinc-9": "#27272a"
911
+ };
912
+
913
+ // src/theme.ts
914
+ var defaultTheme = {
915
+ colors: {
916
+ ...PALETTE,
917
+ surface: { light: "#f9fafb", dark: "#111827" }
918
+ },
919
+ // Real Tailwind's default spacing scale in full — every step is exactly
920
+ // `n * 4px` (Tailwind's base spacing unit), including the fractional
921
+ // `.5` steps (`1.5` -> 6px, `2.5` -> 10px, `3.5` -> 14px) and the "px"
922
+ // literal (a bare 1px, for `p-px`-style hairline spacing). This table is
923
+ // only the "usual stops", though — the Rust/JS engines' shared
924
+ // `spacing_px`/`spacingPx` helper falls back to Tailwind v4's own live
925
+ // `n * 4px` formula for any bare numeric step NOT listed here (`p-0.25`,
926
+ // `gap-1.75`, `w-13`, ...), so this table exists to name the common
927
+ // values and give a theme customization something to override, not to
928
+ // enumerate every resolvable step. "px" is the one exception that must
929
+ // stay listed explicitly — it isn't a number, so the formula can't
930
+ // derive it.
931
+ spacing: {
932
+ "0": 0,
933
+ "px": 1,
934
+ "0.5": 2,
935
+ "1": 4,
936
+ "1.5": 6,
937
+ "2": 8,
938
+ "2.5": 10,
939
+ "3": 12,
940
+ "3.5": 14,
941
+ "4": 16,
942
+ "5": 20,
943
+ "6": 24,
944
+ "7": 28,
945
+ "8": 32,
946
+ "9": 36,
947
+ "10": 40,
948
+ "11": 44,
949
+ "12": 48,
950
+ "14": 56,
951
+ "16": 64,
952
+ "20": 80,
953
+ "24": 96,
954
+ "28": 112,
955
+ "32": 128,
956
+ "36": 144,
957
+ "40": 160,
958
+ "44": 176,
959
+ "48": 192,
960
+ "52": 208,
961
+ "56": 224,
962
+ "60": 240,
963
+ "64": 256,
964
+ "72": 288,
965
+ "80": 320,
966
+ "96": 384
967
+ },
968
+ screens: {
969
+ sm: 640,
970
+ md: 768,
971
+ lg: 1024,
972
+ xl: 1280,
973
+ "2xl": 1536
974
+ },
975
+ // Byte-for-byte the same three stacks
976
+ // packages/core-engine/src/resolvers/typography.rs's `font_family_value`
977
+ // falls back to — kept here too (rather than leaving this empty and
978
+ // relying purely on the Rust-side fallback) so `defaultTheme.fontFamily.sans`
979
+ // is a real, readable value for anything that wants to extend rather
980
+ // than replace it (see `KbachConfig.extend.fontFamily` in config.ts).
981
+ fontFamily: {
982
+ sans: 'ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"',
983
+ serif: 'ui-serif, Georgia, Cambria, "Times New Roman", Times, serif',
984
+ mono: 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace'
985
+ },
986
+ // Matches real Tailwind's own default (`darkMode: 'media'`): pure
987
+ // `@media (prefers-color-scheme: dark)`, works with zero JS — a project
988
+ // using only static `className` strings gets working `dark:` classes
989
+ // out of the box, with no runtime import required to write `data-theme`/
990
+ // `.dark` onto `<html>` (see darkModeStore.ts's `applyToDom`). The
991
+ // tradeoff: `'media'` can't be overridden by a manual light/dark toggle —
992
+ // `useTheme()`/`toggleGlobalDarkMode()` still track `isDark` correctly
993
+ // for JS consumers, but flipping it has no visible effect on `dark:`
994
+ // classes, since the browser's media query only ever reflects the real
995
+ // OS setting. Opt into `darkMode: 'class'` or `'attribute'` explicitly
996
+ // (via `kbach.config.js` or the `config`/`theme` plugin option) as soon
997
+ // as an app wants a real in-app toggle.
998
+ darkMode: "media",
999
+ // Empty by default, matching real Tailwind's own defaults (no forced
1000
+ // centering/padding) — see `ContainerConfig`'s own doc comment.
1001
+ container: {}
1002
+ };
1003
+ var activeTheme = defaultTheme;
1004
+ var activeThemeJson = JSON.stringify(defaultTheme);
1005
+ function setTheme(theme) {
1006
+ activeTheme = theme;
1007
+ activeThemeJson = JSON.stringify(theme);
1008
+ }
1009
+ function getTheme() {
1010
+ return activeTheme;
1011
+ }
1012
+ var DARK_MODE_STRATEGIES = /* @__PURE__ */ new Set(["attribute", "class", "media"]);
1013
+ function detectDarkModeStrategyFromDom() {
1014
+ if (typeof document === "undefined") return;
1015
+ const raw = getComputedStyle(document.documentElement).getPropertyValue("--kb-dark-mode").trim();
1016
+ if (!DARK_MODE_STRATEGIES.has(raw) || raw === activeTheme.darkMode) return;
1017
+ setTheme({ ...activeTheme, darkMode: raw });
1018
+ }
1019
+
1020
+ // src/colorVariables.ts
1021
+ function parseHexRgb(hex) {
1022
+ const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(hex.trim());
1023
+ if (!m) return null;
1024
+ let h = m[1];
1025
+ if (h.length === 3) h = h.split("").map((c) => c + c).join("");
1026
+ const n = parseInt(h, 16);
1027
+ return [n >> 16 & 255, n >> 8 & 255, n & 255];
1028
+ }
1029
+
1030
+ // src/darkModeStore.ts
1031
+ var STORAGE_KEY = "kbach-theme";
1032
+ var listeners = /* @__PURE__ */ new Set();
1033
+ function systemPrefersDark() {
1034
+ if (typeof window === "undefined" || !window.matchMedia) return false;
1035
+ return window.matchMedia("(prefers-color-scheme: dark)").matches;
1036
+ }
1037
+ function storage() {
1038
+ return typeof window === "undefined" ? null : window.localStorage;
1039
+ }
1040
+ function readPersistedMode() {
1041
+ const ls = storage();
1042
+ if (!ls) return null;
1043
+ try {
1044
+ const raw = ls.getItem(STORAGE_KEY);
1045
+ return raw === "light" || raw === "dark" || raw === "system" ? raw : null;
1046
+ } catch {
1047
+ return null;
1048
+ }
1049
+ }
1050
+ function resolveIsDark(m) {
1051
+ return m === "system" ? systemPrefersDark() : m === "dark";
1052
+ }
1053
+ function applyToDom(dark) {
1054
+ if (typeof document === "undefined") return;
1055
+ const root = document.documentElement;
1056
+ const strategy = getTheme().darkMode;
1057
+ root.classList.toggle("dark", strategy === "class" && dark);
1058
+ root.classList.toggle("light", strategy === "class" && !dark);
1059
+ if (strategy === "attribute") {
1060
+ root.setAttribute("data-theme", dark ? "dark" : "light");
1061
+ } else {
1062
+ root.removeAttribute("data-theme");
1063
+ }
1064
+ }
1065
+ detectDarkModeStrategyFromDom();
1066
+ var persistedMode = readPersistedMode();
1067
+ var mode = persistedMode ?? "system";
1068
+ var isDark = resolveIsDark(mode);
1069
+ applyToDom(isDark);
1070
+ if (typeof window !== "undefined" && window.matchMedia) {
1071
+ const mq = window.matchMedia("(prefers-color-scheme: dark)");
1072
+ const onSystemChange = (event) => {
1073
+ if (mode !== "system") return;
1074
+ isDark = event.matches;
1075
+ applyToDom(isDark);
1076
+ notify();
1077
+ };
1078
+ if (mq.addEventListener) mq.addEventListener("change", onSystemChange);
1079
+ else mq.addListener(onSystemChange);
1080
+ }
1081
+ function notify() {
1082
+ for (const listener of listeners) listener();
1083
+ }
1084
+
1085
+ // src/config.ts
1086
+ function applyOpacityToHex(hex, opacityText) {
1087
+ const rgb = parseHexRgb(hex);
1088
+ if (!rgb) return hex;
1089
+ const a = Number(opacityText) / 100;
1090
+ const clamped = Number.isFinite(a) ? Math.min(1, Math.max(0, a)) : 1;
1091
+ return `rgba(${rgb.join(",")},${clamped})`;
1092
+ }
1093
+ function resolveColorEntry(value, lookup) {
1094
+ if (typeof value !== "string") return value;
1095
+ const slash = value.indexOf("/");
1096
+ const name = slash === -1 ? value : value.slice(0, slash);
1097
+ const opacity = slash === -1 ? void 0 : value.slice(slash + 1);
1098
+ const base = lookup(name);
1099
+ if (base === void 0) return value;
1100
+ if (opacity === void 0) return base;
1101
+ return typeof base === "string" ? applyOpacityToHex(base, opacity) : { light: applyOpacityToHex(base.light, opacity), dark: applyOpacityToHex(base.dark, opacity) };
1102
+ }
1103
+ function resolveColors(extend, existing) {
1104
+ const { dark: darkExtend, ...lightExtend } = extend;
1105
+ const resolved = {};
1106
+ const lookup = (name) => resolved[name] ?? existing[name];
1107
+ for (const [name, value] of Object.entries(lightExtend)) {
1108
+ if (typeof value === "object" && value !== null && !("light" in value) && !("dark" in value)) continue;
1109
+ resolved[name] = resolveColorEntry(value, lookup);
1110
+ }
1111
+ if (darkExtend) {
1112
+ const resolvedDark = {};
1113
+ const lookupDark = (name) => {
1114
+ const found = resolvedDark[name] ?? existing[name];
1115
+ return typeof found === "string" ? found : void 0;
1116
+ };
1117
+ for (const [name, value] of Object.entries(darkExtend)) {
1118
+ const entry = resolveColorEntry(value, lookupDark);
1119
+ resolvedDark[name] = typeof entry === "string" ? entry : entry.dark;
1120
+ }
1121
+ for (const [name, darkValue] of Object.entries(resolvedDark)) {
1122
+ const lightEntry = resolved[name];
1123
+ if (lightEntry === void 0 || typeof lightEntry !== "string") continue;
1124
+ resolved[name] = { light: lightEntry, dark: darkValue };
1125
+ }
1126
+ }
1127
+ return resolved;
1128
+ }
1129
+ function resolveKbachConfig(config) {
1130
+ let theme = { ...defaultTheme, ...config.theme };
1131
+ if (config.extend?.colors) {
1132
+ theme = { ...theme, colors: { ...theme.colors, ...resolveColors(config.extend.colors, theme.colors) } };
1133
+ }
1134
+ if (config.extend?.spacing) {
1135
+ theme = { ...theme, spacing: { ...theme.spacing, ...config.extend.spacing } };
1136
+ }
1137
+ if (config.extend?.screens) {
1138
+ theme = { ...theme, screens: { ...theme.screens, ...config.extend.screens } };
1139
+ }
1140
+ if (config.extend?.fontFamily) {
1141
+ theme = { ...theme, fontFamily: { ...theme.fontFamily, ...config.extend.fontFamily } };
1142
+ }
1143
+ if (config.extend?.container) {
1144
+ theme = { ...theme, container: { ...theme.container, ...config.extend.container } };
1145
+ }
1146
+ if (config.darkMode) {
1147
+ theme = { ...theme, darkMode: config.darkMode };
1148
+ }
1149
+ return theme;
1150
+ }
1151
+
1152
+ // src/vite-plugin/index.ts
1153
+ var DEFAULT_SCAN_DIRS = ["src", "app", "pages", "components"];
1154
+ function isEsmRequireFailure(err) {
1155
+ if (!(err instanceof Error)) return false;
1156
+ return err.code === "ERR_REQUIRE_ESM" || /is not defined in ES module scope/.test(err.message);
1157
+ }
1158
+ async function importConfigModule(path) {
1159
+ const mod = await import((0, import_url.pathToFileURL)(path).href);
1160
+ return mod.default ?? mod;
1161
+ }
1162
+ function requireConfigModule(root, path) {
1163
+ const mod = (0, import_module.createRequire)(root)(path);
1164
+ return mod.default ?? mod;
1165
+ }
1166
+ async function loadConfigFile(root) {
1167
+ const cjsPath = (0, import_path4.join)(root, "kbach.config.cjs");
1168
+ if ((0, import_fs2.existsSync)(cjsPath)) return requireConfigModule(root, cjsPath);
1169
+ const mjsPath = (0, import_path4.join)(root, "kbach.config.mjs");
1170
+ if ((0, import_fs2.existsSync)(mjsPath)) return importConfigModule(mjsPath);
1171
+ const jsPath = (0, import_path4.join)(root, "kbach.config.js");
1172
+ if (!(0, import_fs2.existsSync)(jsPath)) return void 0;
1173
+ try {
1174
+ return requireConfigModule(root, jsPath);
1175
+ } catch (err) {
1176
+ if (!isEsmRequireFailure(err)) throw err;
1177
+ return importConfigModule(jsPath);
1178
+ }
1179
+ }
1180
+ async function resolveEffectiveTheme(root, options) {
1181
+ if (options.theme) return options.theme;
1182
+ if (options.config) return resolveKbachConfig(options.config);
1183
+ const discovered = await loadConfigFile(root);
1184
+ return discovered ? resolveKbachConfig(discovered) : defaultTheme;
1185
+ }
1186
+
1187
+ // src/postcss-plugin/index.ts
1188
+ var KBACH_START_TEXT = "kbach:start";
1189
+ var KBACH_END_TEXT = "kbach:end";
1190
+ function isKbachMarker(node, text) {
1191
+ return !!node && node.type === "comment" && node.text === text;
1192
+ }
1193
+ function spliceGeneratedCss(root, generatedCss) {
1194
+ const nodes = root.nodes;
1195
+ let startIdx = -1;
1196
+ let endIdx = -1;
1197
+ for (let i = 0; i < nodes.length; i++) {
1198
+ if (startIdx === -1 && isKbachMarker(nodes[i], KBACH_START_TEXT)) {
1199
+ startIdx = i;
1200
+ continue;
1201
+ }
1202
+ if (startIdx !== -1 && isKbachMarker(nodes[i], KBACH_END_TEXT)) {
1203
+ endIdx = i;
1204
+ break;
1205
+ }
1206
+ }
1207
+ if (startIdx === -1 || endIdx === -1) {
1208
+ console.warn(
1209
+ `${kbachTag()} ${gray("No")} ${highlight("/* kbach:start */")}${gray(" / ")}${highlight("/* kbach:end */")} ${gray("marker pair found in this file \u2014 nothing was generated.")}
1210
+ ${bold("fix:")} ${gray("add both markers to the file this plugin processes (same convention the Vite plugin's generated kbach.css uses).")}`
1211
+ );
1212
+ return;
1213
+ }
1214
+ for (const stale of nodes.slice(startIdx + 1, endIdx)) stale.remove();
1215
+ const parsed = import_postcss.default.parse(generatedCss);
1216
+ const newNodes = [...parsed.nodes];
1217
+ let after = nodes[startIdx];
1218
+ for (const node of newNodes) {
1219
+ root.insertAfter(after, node);
1220
+ after = node;
1221
+ }
1222
+ }
1223
+ function kbachPostcss(options = {}) {
1224
+ return {
1225
+ postcssPlugin: "kbach",
1226
+ async Once(root, { result }) {
1227
+ const projectRoot = options.root ?? process.cwd();
1228
+ const theme = await resolveEffectiveTheme(projectRoot, options);
1229
+ const includeDirs = options.include ?? DEFAULT_SCAN_DIRS;
1230
+ const safelist = options.safelist ?? [];
1231
+ const engine = createKbachStaticCssEngine({
1232
+ root: projectRoot,
1233
+ theme,
1234
+ themeJson: JSON.stringify(theme),
1235
+ includeDirs,
1236
+ safelist
1237
+ });
1238
+ engine.scanProjectCssSelectorsOnce();
1239
+ engine.initialScan();
1240
+ engine.processSafelist();
1241
+ for (const dir of includeDirs) {
1242
+ result.messages.push({
1243
+ type: "dir-dependency",
1244
+ plugin: "kbach",
1245
+ dir: (0, import_path5.resolve)(projectRoot, dir),
1246
+ glob: "**/*"
1247
+ });
1248
+ }
1249
+ spliceGeneratedCss(root, engine.generateCSS());
1250
+ }
1251
+ };
1252
+ }
1253
+ kbachPostcss.postcss = true;