@dmisdm/pandatail 0.4.0 → 0.6.0

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/dist/cli.js CHANGED
@@ -1,51 +1,50 @@
1
1
  #!/usr/bin/env node
2
+ var __esm = (fn, res, err) => () => {
3
+ if (fn)
4
+ try {
5
+ res = fn(fn = 0);
6
+ } catch (e) {
7
+ err = [e];
8
+ }
9
+ if (err)
10
+ throw err[0];
11
+ return res;
12
+ };
2
13
 
3
- // src/cli.ts
4
- import { existsSync as existsSync3, watch } from "node:fs";
5
- import { relative as relative2, resolve as resolve5, sep } from "node:path";
6
- import { parseArgs } from "node:util";
7
-
8
- // src/project.ts
9
- import { bundleConfig, createConfigSnapshot, mergeConfigs } from "@pandacss/config";
10
- import { createCompilerFromSnapshot } from "@pandacss/compiler";
11
- import { applyConfigDefaults, formatDiagnostic } from "@pandacss/compiler-shared";
12
- import presetBase from "@pandacss/preset-base";
13
- import { createRequire } from "node:module";
14
- import { existsSync as existsSync2, statSync } from "node:fs";
15
- import { relative, resolve as resolve4 } from "node:path";
16
-
17
- // src/preset.ts
18
- import { definePreset } from "@pandacss/dev";
19
- import { readFile as readFile2 } from "node:fs/promises";
20
- import { dirname as dirname3, resolve as resolve3 } from "node:path";
21
-
22
- // src/extract.ts
23
- import { __unstable__loadDesignSystem } from "@tailwindcss/node";
24
- import { readFile } from "node:fs/promises";
25
- import { dirname, resolve } from "node:path";
14
+ // src/diagnostics.ts
15
+ function formatCheckDiagnostic(issue) {
16
+ const start = issue.location?.start;
17
+ const where = issue.file ? `${issue.file}${start ? `:${start.line}:${start.column}` : ""}: ` : "";
18
+ return `${where}${issue.severity} [${issue.code}] ${issue.message}`;
19
+ }
20
+ function cssIssue(error, code, file, severity = "error") {
21
+ const { line, column, endLine, endColumn } = error.input ?? error;
22
+ return {
23
+ code,
24
+ severity,
25
+ message: error.reason,
26
+ file: file ?? error.file,
27
+ ...line && column ? {
28
+ location: {
29
+ start: { line, column },
30
+ end: { line: endLine ?? line, column: endColumn ?? column + 1 }
31
+ }
32
+ } : {}
33
+ };
34
+ }
35
+ var PandatailDiagnosticError;
36
+ var init_diagnostics = __esm(() => {
37
+ PandatailDiagnosticError = class PandatailDiagnosticError extends Error {
38
+ diagnostics;
39
+ constructor(diagnostics) {
40
+ super(diagnostics.filter((issue) => issue.severity === "error").map(formatCheckDiagnostic).join(`
41
+ `));
42
+ this.diagnostics = diagnostics;
43
+ }
44
+ };
45
+ });
26
46
 
27
47
  // src/namespaces.ts
28
- var TAILWIND_NAMESPACES = [
29
- { prefix: "font-weight", category: "fontWeights" },
30
- { prefix: "inset-shadow", category: "shadows" },
31
- { prefix: "drop-shadow", category: "dropShadows" },
32
- { prefix: "text-shadow", category: "shadows" },
33
- { prefix: "color", category: "colors" },
34
- { prefix: "spacing", category: "spacing" },
35
- { prefix: "font", category: "fonts" },
36
- { prefix: "text", category: "fontSizes" },
37
- { prefix: "tracking", category: "letterSpacings" },
38
- { prefix: "leading", category: "lineHeights" },
39
- { prefix: "breakpoint", category: "breakpoints" },
40
- { prefix: "container", category: "sizes" },
41
- { prefix: "radius", category: "radii" },
42
- { prefix: "shadow", category: "shadows" },
43
- { prefix: "blur", category: "blurs" },
44
- { prefix: "aspect", category: "aspectRatios" },
45
- { prefix: "ease", category: "easings" },
46
- { prefix: "animate", category: "animations" },
47
- { prefix: "perspective", category: "sizes" }
48
- ];
49
48
  function deriveTokenPath(rest) {
50
49
  const lastDash = rest.lastIndexOf("-");
51
50
  if (lastDash > 0) {
@@ -73,57 +72,32 @@ function matchNamespace(themeKey) {
73
72
  }
74
73
  return null;
75
74
  }
75
+ var TAILWIND_NAMESPACES;
76
+ var init_namespaces = __esm(() => {
77
+ TAILWIND_NAMESPACES = [
78
+ { prefix: "font-weight", category: "fontWeights" },
79
+ { prefix: "inset-shadow", category: "shadows" },
80
+ { prefix: "drop-shadow", category: "dropShadows" },
81
+ { prefix: "text-shadow", category: "shadows" },
82
+ { prefix: "color", category: "colors" },
83
+ { prefix: "spacing", category: "spacing" },
84
+ { prefix: "font", category: "fonts" },
85
+ { prefix: "text", category: "fontSizes" },
86
+ { prefix: "tracking", category: "letterSpacings" },
87
+ { prefix: "leading", category: "lineHeights" },
88
+ { prefix: "breakpoint", category: "breakpoints" },
89
+ { prefix: "container", category: "sizes" },
90
+ { prefix: "radius", category: "radii" },
91
+ { prefix: "shadow", category: "shadows" },
92
+ { prefix: "blur", category: "blurs" },
93
+ { prefix: "aspect", category: "aspectRatios" },
94
+ { prefix: "ease", category: "easings" },
95
+ { prefix: "animate", category: "animations" },
96
+ { prefix: "perspective", category: "sizes" }
97
+ ];
98
+ });
76
99
 
77
100
  // src/derivedScales.ts
78
- var TAILWIND_NUMERIC_STEPS = [
79
- 0,
80
- 0.5,
81
- 1,
82
- 1.5,
83
- 2,
84
- 2.5,
85
- 3,
86
- 3.5,
87
- 4,
88
- 5,
89
- 6,
90
- 7,
91
- 8,
92
- 9,
93
- 10,
94
- 11,
95
- 12,
96
- 14,
97
- 16,
98
- 20,
99
- 24,
100
- 28,
101
- 32,
102
- 36,
103
- 40,
104
- 44,
105
- 48,
106
- 52,
107
- 56,
108
- 60,
109
- 64,
110
- 72,
111
- 80,
112
- 96
113
- ];
114
- var NAMED_SIZES = {
115
- full: "100%",
116
- screen: "100vw",
117
- "screen-h": "100vh",
118
- min: "min-content",
119
- max: "max-content",
120
- fit: "fit-content",
121
- auto: "auto"
122
- };
123
- var NAMED_RADII = {
124
- none: "0",
125
- full: "9999px"
126
- };
127
101
  function synthesiseDerivedTokens(hasSpacingBase) {
128
102
  const out = [];
129
103
  if (hasSpacingBase) {
@@ -160,14 +134,75 @@ function pushNamed(out) {
160
134
  });
161
135
  }
162
136
  }
137
+ var TAILWIND_NUMERIC_STEPS, NAMED_SIZES, NAMED_RADII;
138
+ var init_derivedScales = __esm(() => {
139
+ TAILWIND_NUMERIC_STEPS = [
140
+ 0,
141
+ 0.5,
142
+ 1,
143
+ 1.5,
144
+ 2,
145
+ 2.5,
146
+ 3,
147
+ 3.5,
148
+ 4,
149
+ 5,
150
+ 6,
151
+ 7,
152
+ 8,
153
+ 9,
154
+ 10,
155
+ 11,
156
+ 12,
157
+ 14,
158
+ 16,
159
+ 20,
160
+ 24,
161
+ 28,
162
+ 32,
163
+ 36,
164
+ 40,
165
+ 44,
166
+ 48,
167
+ 52,
168
+ 56,
169
+ 60,
170
+ 64,
171
+ 72,
172
+ 80,
173
+ 96
174
+ ];
175
+ NAMED_SIZES = {
176
+ full: "100%",
177
+ screen: "100vw",
178
+ "screen-h": "100vh",
179
+ min: "min-content",
180
+ max: "max-content",
181
+ fit: "fit-content",
182
+ auto: "auto"
183
+ };
184
+ NAMED_RADII = {
185
+ none: "0",
186
+ full: "9999px"
187
+ };
188
+ });
163
189
 
164
190
  // src/extract.ts
191
+ import { __unstable__loadDesignSystem } from "@tailwindcss/node";
192
+ import { readFile } from "node:fs/promises";
193
+ import { dirname, resolve } from "node:path";
165
194
  async function extractTokens(opts) {
195
+ return tokensFromTheme(await loadThemeEntries(opts));
196
+ }
197
+ async function loadThemeEntries(opts) {
166
198
  const base = resolve(opts.base ?? process.cwd());
167
199
  const ds = await __unstable__loadDesignSystem(opts.css, { base });
168
200
  const themeEntries = new Map;
169
201
  for (const [key, entry] of ds.theme.entries())
170
202
  themeEntries.set(key, entry.value);
203
+ return themeEntries;
204
+ }
205
+ function tokensFromTheme(themeEntries) {
171
206
  const out = [];
172
207
  for (const [key, rawValue] of themeEntries) {
173
208
  const matched = matchNamespace(key);
@@ -189,44 +224,310 @@ async function extractTokensFromFile(path) {
189
224
  const css = await readFile(path, "utf8");
190
225
  return extractTokens({ css, base: dirname(resolve(path)) });
191
226
  }
227
+ var init_extract = __esm(() => {
228
+ init_namespaces();
229
+ init_derivedScales();
230
+ });
231
+
232
+ // src/pandaCss.ts
233
+ import { resolve as resolve2 } from "node:path";
234
+ function readPandaRule(rule, base, out, file) {
235
+ if (rule.parent?.type !== "root")
236
+ throw rule.error("@panda must be at the top level");
237
+ const params = rule.params.trim();
238
+ const [kind, ...args] = params.split(/\s+/);
239
+ if (kind === "config") {
240
+ const path = quoted(params.slice(kind.length).trim());
241
+ if (rule.nodes || !path?.endsWith(".json")) {
242
+ throw rule.error('Expected @panda config "./panda.json";');
243
+ }
244
+ const file = resolve2(base, path);
245
+ if (out.configFile && out.configFile !== file) {
246
+ throw rule.error(`Only one @panda config file is supported (already using ${out.configFile})`);
247
+ }
248
+ out.configFile = file;
249
+ return;
250
+ }
251
+ const name = args[0];
252
+ if (!name || args.length !== 1 || !rule.nodes) {
253
+ throw rule.error("Expected @panda <kind> <name> { … }");
254
+ }
255
+ const { description, body } = readBody(rule.nodes);
256
+ if (kind === "recipe") {
257
+ if (!isName(name) || !/^[a-z_]/i.test(name))
258
+ throw rule.error(`Invalid recipe name: ${name}`);
259
+ (out.theme.recipes ??= {})[name] = readRecipe(name, body, description);
260
+ collectReferences(rule, out.references, file);
261
+ return;
262
+ }
263
+ if (!kind || !Object.hasOwn(compositions, kind)) {
264
+ throw rule.error(`Unknown @panda kind: ${kind}`, { word: kind });
265
+ }
266
+ const category = compositions[kind];
267
+ const path = name.split(".");
268
+ if (path.some((part) => !isName(part) || part === "value")) {
269
+ throw rule.error(`Invalid ${kind} name: ${name}`);
270
+ }
271
+ setComposition(out.theme[category] ??= {}, path, { value: readStyles(body), description }, rule);
272
+ collectReferences(rule, out.references, file);
273
+ }
274
+ function setComposition(tree, path, style, rule) {
275
+ let group = tree;
276
+ for (const key of path.slice(0, -1)) {
277
+ const entry = own(group, key);
278
+ if (entry && Object.hasOwn(entry, "value"))
279
+ throw collision(rule);
280
+ group = group[key] = entry ?? {};
281
+ }
282
+ const leaf = path.at(-1);
283
+ const existing = own(group, leaf);
284
+ if (existing && !Object.hasOwn(existing, "value"))
285
+ throw collision(rule);
286
+ group[leaf] = style;
287
+ }
288
+ function collision(rule) {
289
+ return rule.error(`@panda ${rule.params}: a style cannot also be a group; use a .DEFAULT style for the group`);
290
+ }
291
+ function readBody(nodes) {
292
+ let description;
293
+ const body = nodes.filter((node) => {
294
+ if (node.type !== "atrule" || node.name !== "description")
295
+ return true;
296
+ if (description !== undefined)
297
+ throw node.error("Only one @description is allowed per @panda block");
298
+ description = quoted(node.params);
299
+ if (node.nodes || description === undefined)
300
+ throw node.error('Expected @description "…";');
301
+ return false;
302
+ });
303
+ return { description, body };
304
+ }
305
+ function readRecipe(className, nodes, description) {
306
+ const variants = {};
307
+ const defaults = new Map;
308
+ const base = [];
309
+ for (const node of nodes) {
310
+ if (node.type === "atrule" && node.name === "option") {
311
+ const [axis, value, ...rest] = node.params.trim().split(/\s+/);
312
+ if (!axis || !value || rest.length || !isName(axis) || !isName(value) || !node.nodes) {
313
+ throw node.error("Expected @option <axis> <value> { … }");
314
+ }
315
+ const options = own(variants, axis) ?? (variants[axis] = {});
316
+ if (Object.hasOwn(options, value))
317
+ throw node.error(`Duplicate recipe option: ${axis} ${value}`);
318
+ options[value] = readStyles(node.nodes);
319
+ } else if (node.type === "atrule" && node.name === "defaults") {
320
+ if (node.params || !node.nodes)
321
+ throw node.error("Expected @defaults { axis: value; }");
322
+ for (const decl of node.nodes) {
323
+ if (decl.type === "comment")
324
+ continue;
325
+ if (decl.type !== "decl" || !isName(decl.prop) || !isName(decl.value) || decl.important) {
326
+ throw decl.error("Expected a recipe axis and value in @defaults");
327
+ }
328
+ if (defaults.has(decl.prop))
329
+ throw decl.error(`Duplicate recipe default: ${decl.prop}`);
330
+ defaults.set(decl.prop, decl);
331
+ }
332
+ } else {
333
+ base.push(node);
334
+ }
335
+ }
336
+ for (const [axis, decl] of defaults) {
337
+ const options = own(variants, axis);
338
+ if (!options || !Object.hasOwn(options, decl.value)) {
339
+ const expected = options ? ` Expected one of: ${Object.keys(options).join(", ")}.` : "";
340
+ const index = valueStart(decl);
341
+ throw decl.error(`Recipe ${className} has no option ${axis} ${decl.value}.${expected}`, {
342
+ index,
343
+ endIndex: index + decl.value.length
344
+ });
345
+ }
346
+ }
347
+ return {
348
+ className,
349
+ base: readStyles(base),
350
+ ...description === undefined ? {} : { description },
351
+ ...Object.keys(variants).length === 0 ? {} : { variants },
352
+ ...defaults.size === 0 ? {} : {
353
+ defaultVariants: Object.fromEntries([...defaults].map(([axis, decl]) => [axis, decl.value]))
354
+ }
355
+ };
356
+ }
357
+ function readStyles(nodes) {
358
+ const styles = Object.create(null);
359
+ fillStyles(nodes, styles);
360
+ return styles;
361
+ }
362
+ function fillStyles(nodes, styles) {
363
+ for (const node of nodes) {
364
+ if (node.type === "comment")
365
+ continue;
366
+ if (node.type === "decl") {
367
+ styles[styleProp(node.prop)] = node.value + (node.important ? " !important" : "");
368
+ continue;
369
+ }
370
+ let key;
371
+ if (node.type === "rule") {
372
+ key = node.selectors.map((selector) => selector.includes("&") ? selector : `& ${selector}`).join(", ");
373
+ } else if (node.type === "atrule" && node.nodes && /^(media|supports|container|starting-style)$/.test(node.name)) {
374
+ key = `@${node.name} ${node.params}`.trimEnd();
375
+ } else {
376
+ throw node.error(`Unsupported in @panda styles: @${node.name}`);
377
+ }
378
+ const previous = styles[key];
379
+ const nested = typeof previous === "object" ? previous : Object.create(null);
380
+ fillStyles(node.nodes ?? [], nested);
381
+ styles[key] = nested;
382
+ }
383
+ }
384
+ function collectReferences(rule, references, file) {
385
+ rule.walkDecls((decl) => {
386
+ if (decl.parent?.type === "atrule" && decl.parent.name === "defaults")
387
+ return;
388
+ const prop = styleProp(decl.prop);
389
+ const start = valueStart(decl);
390
+ const raw = decl.raws.value?.raw ?? decl.value;
391
+ const add = (category, name, index) => {
392
+ const range = decl.rangeBy({ index, endIndex: index + name.length });
393
+ const { line, column } = range.start;
394
+ references.push({
395
+ category,
396
+ name,
397
+ file,
398
+ location: {
399
+ start: { line, column },
400
+ end: { line: range.end.line, column: range.end.column }
401
+ }
402
+ });
403
+ };
404
+ if (Object.hasOwn(compositionProps, prop)) {
405
+ add(compositionProps[prop], decl.value, start);
406
+ return;
407
+ }
408
+ for (const match of raw.matchAll(/\/\*[\s\S]*?\*\/|"(?:[^"\\]|\\[\s\S])*"|'(?:[^'\\]|\\[\s\S])*'|(?<![\w-])token\(\s*([\w.-]+)\s*\)/g)) {
409
+ const name = match[1];
410
+ if (name)
411
+ add("tokens", name, start + match.index + match[0].indexOf(name, "token(".length));
412
+ }
413
+ });
414
+ }
415
+ function valueStart(decl) {
416
+ return decl.prop.length + (decl.raws.between?.length ?? 1);
417
+ }
418
+ function styleProp(prop) {
419
+ if (prop.startsWith("--"))
420
+ return prop;
421
+ return prop.replace(/^-ms-/, "ms-").replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
422
+ }
423
+ function isName(name) {
424
+ return /^[\w-]+$/.test(name) && !["__proto__", "constructor", "prototype"].includes(name);
425
+ }
426
+ function own(obj, key) {
427
+ return Object.hasOwn(obj, key) ? obj[key] : undefined;
428
+ }
429
+ function quoted(value) {
430
+ const match = /^(?:"([^"]*)"|'([^']*)')$/.exec(value);
431
+ return match?.[1] ?? match?.[2];
432
+ }
433
+ var compositions, compositionProps;
434
+ var init_pandaCss = __esm(() => {
435
+ compositions = {
436
+ "text-style": "textStyles",
437
+ "layer-style": "layerStyles",
438
+ "animation-style": "animationStyles"
439
+ };
440
+ compositionProps = {
441
+ textStyle: "textStyles",
442
+ layerStyle: "layerStyles",
443
+ animationStyle: "animationStyles"
444
+ };
445
+ });
192
446
 
193
447
  // src/scanCss.ts
194
- import postcss from "postcss";
195
- import { existsSync, readFileSync } from "node:fs";
196
- import { dirname as dirname2, resolve as resolve2 } from "node:path";
197
- function scanCss(opts) {
448
+ import postcss, {
449
+ CssSyntaxError
450
+ } from "postcss";
451
+ import { readFileSync } from "node:fs";
452
+ import { dirname as dirname2, resolve as resolve3 } from "node:path";
453
+ function scanCss(opts, rootVariables) {
198
454
  const out = {
199
455
  sources: [],
200
456
  excludes: [],
201
457
  conditions: {},
202
458
  warnings: [],
459
+ diagnostics: [],
203
460
  files: opts.file ? [opts.file] : []
204
461
  };
205
- walk(opts.css, opts.base, out, new Set(opts.file ? [opts.file] : []));
462
+ walk(opts, out, new Map(opts.file ? [[opts.file, true]] : []), rootVariables);
463
+ if (!opts.recover && out.diagnostics.some((issue) => issue.severity === "error")) {
464
+ throw new PandatailDiagnosticError(out.diagnostics);
465
+ }
206
466
  return out;
207
467
  }
208
- function walk(css, base, out, seen) {
468
+ function walk({ css, base, file, followImports }, out, seen, rootVariables, inReference = false) {
209
469
  let root;
210
470
  try {
211
- root = postcss.parse(css);
212
- } catch (e) {
213
- out.warnings.push(`could not parse CSS in ${base}: ${e.message}`);
471
+ root = postcss.parse(css, { from: file, map: false });
472
+ } catch (error) {
473
+ if (!(error instanceof CssSyntaxError))
474
+ throw error;
475
+ out.diagnostics.push(cssIssue(error, "css-syntax", file));
214
476
  return;
215
477
  }
216
- root.walkAtRules((rule) => {
478
+ const inPandaFile = /\.panda\.css$/i.test(file ?? "") || root.nodes.some((node) => node.type === "atrule" && node.name === "panda");
479
+ root.walk((rule) => {
480
+ if (rule.type === "rule" && rootVariables)
481
+ collectRootVariables(rule, rootVariables);
482
+ if (rule.type !== "atrule")
483
+ return;
217
484
  switch (rule.name) {
218
- case "import": {
219
- const id = quoted(rule.params) ?? urlTarget(rule.params);
485
+ case "import":
486
+ case "reference": {
487
+ if (followImports === false)
488
+ return;
489
+ const id = quoted2(rule.params) ?? urlTarget(rule.params);
220
490
  if (!id || !id.startsWith("."))
221
491
  return;
222
- const path = resolve2(base, id);
223
- if (seen.has(path) || !existsSync(path))
492
+ const path = resolve3(base, id);
493
+ const reference = inReference || rule.name === "reference";
494
+ const visited = seen.get(path);
495
+ if (visited === true || reference && visited === false)
224
496
  return;
225
- seen.add(path);
226
- out.files.push(path);
227
- walk(readFileSync(path, "utf8"), dirname2(path), out, seen);
497
+ let content;
498
+ try {
499
+ content = readFileSync(path, "utf8");
500
+ } catch (error) {
501
+ const code = error.code;
502
+ if (code === "ENOENT" || code === "EISDIR")
503
+ return;
504
+ const reason = `Cannot read @${rule.name} stylesheet ${id}: ${error.message}`;
505
+ out.diagnostics.push(cssIssue(rule.error(reason, { word: id }), "css-import", file));
506
+ return;
507
+ }
508
+ seen.set(path, !reference);
509
+ if (visited === undefined)
510
+ out.files.push(path);
511
+ walk({ css: content, base: dirname2(path), file: path }, out, seen, reference ? undefined : rootVariables, reference);
228
512
  return;
229
513
  }
514
+ case "panda":
515
+ try {
516
+ readPandaRule(rule, base, out.panda ??= { theme: {}, references: [] }, file);
517
+ } catch (error) {
518
+ if (!(error instanceof CssSyntaxError))
519
+ throw error;
520
+ out.diagnostics.push(cssIssue(error, "panda-syntax", file));
521
+ }
522
+ return;
523
+ case "option":
524
+ case "defaults":
525
+ case "description":
526
+ if (inPandaFile && rule.parent?.type === "root") {
527
+ const parent = rule.name === "description" ? "an @panda style or recipe" : "an @panda recipe";
528
+ out.diagnostics.push(cssIssue(rule.error(`@${rule.name} must be inside ${parent}`), "panda-syntax", file));
529
+ }
530
+ return;
230
531
  case "source":
231
532
  return handleSource(rule, base, out);
232
533
  case "custom-variant":
@@ -234,17 +535,28 @@ function walk(css, base, out, seen) {
234
535
  }
235
536
  });
236
537
  }
538
+ function collectRootVariables(rule, variables) {
539
+ let parent = rule.parent;
540
+ while (parent?.type === "atrule" && parent.name === "layer")
541
+ parent = parent.parent;
542
+ if (parent?.type !== "root" || !rule.selectors.includes(":root"))
543
+ return;
544
+ for (const node of rule.nodes) {
545
+ if (node.type === "decl" && node.prop.startsWith("--"))
546
+ variables.set(node.prop, node.value);
547
+ }
548
+ }
237
549
  function handleSource(rule, base, out) {
238
550
  const params = rule.params.trim();
239
551
  if (params.startsWith("inline(") || params.startsWith("not inline(")) {
240
- out.warnings.push(`@source ${params}: inline sources have no Panda equivalent`);
552
+ warn(out, rule, "tailwind-source", `@source ${params}: inline sources have no Panda equivalent`);
241
553
  return;
242
554
  }
243
555
  const isNot = /^not\s/.test(params);
244
- const target = quoted(isNot ? params.replace(/^not\s+/, "") : params);
556
+ const target = quoted2(isNot ? params.replace(/^not\s+/, "") : params);
245
557
  if (!target)
246
558
  return;
247
- (isNot ? out.excludes : out.sources).push(resolve2(base, target));
559
+ (isNot ? out.excludes : out.sources).push(resolve3(base, target));
248
560
  }
249
561
  function handleCustomVariant(rule, out) {
250
562
  const params = rule.params.trim();
@@ -256,7 +568,7 @@ function handleCustomVariant(rule, out) {
256
568
  if (m)
257
569
  out.conditions[name] = m[1].trim();
258
570
  else
259
- out.warnings.push(`@custom-variant ${name}: unrecognised form`);
571
+ warn(out, rule, "tailwind-variant", `@custom-variant ${name}: unrecognised form`);
260
572
  return;
261
573
  }
262
574
  const body = rule.nodes.filter((n) => n.type !== "comment");
@@ -269,21 +581,32 @@ function handleCustomVariant(rule, out) {
269
581
  out.conditions[name] = only.selector;
270
582
  return;
271
583
  }
272
- out.warnings.push(`@custom-variant ${name}: block form is too complex to map to a Panda condition`);
584
+ warn(out, rule, "tailwind-variant", `@custom-variant ${name}: block form is too complex to map to a Panda condition`);
585
+ }
586
+ function warn(out, rule, code, message) {
587
+ out.warnings.push(message);
588
+ out.diagnostics.push(cssIssue(rule.error(message), code, rule.source?.input.file, "warning"));
273
589
  }
274
590
  function isSlotOnly(node) {
275
591
  const kids = (node.nodes ?? []).filter((n) => n.type !== "comment");
276
592
  return kids.length === 1 && kids[0].type === "atrule" && kids[0].name === "slot";
277
593
  }
278
- function quoted(params) {
594
+ function quoted2(params) {
279
595
  return /^\s*["']([^"']+)["']/.exec(params)?.[1] ?? null;
280
596
  }
281
597
  function urlTarget(params) {
282
598
  return /^\s*url\(\s*["']?([^"')]+)["']?\s*\)/.exec(params)?.[1] ?? null;
283
599
  }
600
+ var init_scanCss = __esm(() => {
601
+ init_diagnostics();
602
+ init_pandaCss();
603
+ });
284
604
 
285
605
  // src/preset.ts
286
- async function loadTailwind(opts) {
606
+ import { definePreset } from "@pandacss/dev";
607
+ import { readFile as readFile2 } from "node:fs/promises";
608
+ import { dirname as dirname3, resolve as resolve4 } from "node:path";
609
+ async function loadTailwind(opts, preview = false) {
287
610
  let css;
288
611
  let base;
289
612
  let file;
@@ -291,19 +614,39 @@ async function loadTailwind(opts) {
291
614
  css = opts.css;
292
615
  base = opts.base ?? process.cwd();
293
616
  } else if (opts.cssPath != null) {
294
- file = resolve3(opts.cssPath);
617
+ file = resolve4(opts.cssPath);
295
618
  css = await readFile2(file, "utf8");
296
619
  base = dirname3(file);
297
620
  } else {
298
621
  throw new Error("pandatail: provide either `css` or `cssPath`");
299
622
  }
300
- const tokens = await extractTokens({ css, base });
301
- const scan = scanCss({ css, base, file });
302
- return { preset: buildPreset(tokens, scan), scan, tokens };
623
+ const rootVariables = preview ? new Map : undefined;
624
+ const scan = scanCss({ css, base, file }, rootVariables);
625
+ const theme = await loadThemeEntries({ css, base });
626
+ const tokens = tokensFromTheme(theme);
627
+ const variables = rootVariables && new Map([...theme, ...rootVariables]);
628
+ const presetTokens = variables ? tokens.map((token) => ({
629
+ ...token,
630
+ value: resolvePreviewValue(token.value, variables)
631
+ })) : tokens;
632
+ return { preset: buildPreset(presetTokens, scan), scan, tokens };
303
633
  }
304
634
  async function tailwindPreset(opts) {
305
635
  return (await loadTailwind(opts)).preset;
306
636
  }
637
+ function resolvePreviewValue(value, variables, resolving = new Set) {
638
+ return value.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|(?<![\w-])var\(\s*(--[\w-]+)\s*\)/gi, (match, name) => {
639
+ if (name === undefined || resolving.has(name))
640
+ return match;
641
+ const definition = variables.get(name);
642
+ if (definition === undefined)
643
+ return match;
644
+ resolving.add(name);
645
+ const resolved = resolvePreviewValue(definition, variables, resolving);
646
+ resolving.delete(name);
647
+ return resolved;
648
+ });
649
+ }
307
650
  function buildPreset(tokens, scan) {
308
651
  const breakpoints = {};
309
652
  const tokenTokens = [];
@@ -323,11 +666,14 @@ function buildPreset(tokens, scan) {
323
666
  name: "tailwind",
324
667
  theme: {
325
668
  tokens: theme,
326
- breakpoints
669
+ breakpoints,
670
+ ...scan?.panda ? { extend: scan.panda.theme } : {}
327
671
  }
328
672
  });
329
673
  if (scan && Object.keys(scan.conditions).length > 0) {
330
- preset.conditions = { extend: scan.conditions };
674
+ preset.conditions = {
675
+ extend: scan.conditions
676
+ };
331
677
  }
332
678
  return preset;
333
679
  }
@@ -365,33 +711,73 @@ function buildTree(tokens, category) {
365
711
  }
366
712
  return root;
367
713
  }
714
+ var init_preset = __esm(() => {
715
+ init_extract();
716
+ init_scanCss();
717
+ });
368
718
 
369
719
  // src/project.ts
370
- var DEFAULT_EXT = "{js,jsx,ts,tsx,mdx}";
720
+ import {
721
+ bundleConfig,
722
+ createConfigSnapshot,
723
+ mergeConfigs
724
+ } from "@pandacss/config";
725
+ import {
726
+ createCompilerFromSnapshot
727
+ } from "@pandacss/compiler";
728
+ import {
729
+ applyConfigDefaults,
730
+ collectParseDiagnostics,
731
+ dedupeDiagnostics,
732
+ formatDiagnostic
733
+ } from "@pandacss/compiler-shared";
734
+ import presetBase from "@pandacss/preset-base";
735
+ import { createRequire } from "node:module";
736
+ import { existsSync, statSync } from "node:fs";
737
+ import { readFile as readFile3 } from "node:fs/promises";
738
+ import { relative, resolve as resolve5 } from "node:path";
371
739
  async function createPandatailProject(opts) {
372
- const cwd = resolve4(opts.cwd ?? process.cwd());
373
- const cssPath = resolve4(cwd, opts.css);
374
- if (!existsSync2(cssPath))
375
- throw new Error(`pandatail: CSS entry not found: ${cssPath}`);
376
- const tw = await loadTailwind({ cssPath });
740
+ const project = await resolvePandatailConfig(opts);
741
+ const compiler = createCompilerFromSnapshot(createConfigSnapshot(project.config));
742
+ return { compiler, ...project };
743
+ }
744
+ async function resolvePandatailConfig(opts, preview = false) {
745
+ const cwd = resolve5(opts.cwd ?? process.cwd());
746
+ const cssPath = resolve5(cwd, opts.css);
747
+ if (!existsSync(cssPath)) {
748
+ throw new PandatailDiagnosticError([
749
+ {
750
+ code: "css-entry",
751
+ severity: "error",
752
+ file: cssPath,
753
+ message: `CSS entry not found: ${cssPath}`
754
+ }
755
+ ]);
756
+ }
757
+ const tw = await loadTailwind({ cssPath }, preview);
377
758
  const dependencies = [...tw.scan.files];
759
+ const cssConfigFile = tw.scan.panda?.configFile;
760
+ const cssConfig = cssConfigFile ? await readCssConfig(cssConfigFile) : {};
761
+ if (cssConfigFile)
762
+ dependencies.push(cssConfigFile);
378
763
  let user = {};
379
764
  if (typeof opts.config === "string") {
380
- const file = resolve4(cwd, opts.config);
765
+ const file = resolve5(cwd, opts.config);
381
766
  const bundled = await bundleConfig(file, cwd);
382
767
  user = bundled.config;
383
768
  dependencies.push(file, ...bundled.dependencies);
384
769
  } else if (opts.config) {
385
770
  user = opts.config;
386
771
  }
772
+ const { presets: cssPresetList, ...cssRest } = cssConfig;
387
773
  const { presets: userPresetList, ...userRest } = user;
388
- const userPresets = await resolvePresets(userPresetList, cwd);
774
+ const presets = await resolvePresets([...cssPresetList ?? [], ...userPresetList ?? []], cwd);
389
775
  const include = opts.include ?? unique([
390
- ...userRest.include ?? [`./src/**/*.${DEFAULT_EXT}`],
776
+ ...userRest.include ?? cssRest.include ?? [`./src/**/*.${DEFAULT_EXT}`],
391
777
  ...tw.scan.sources.map((p) => sourceToGlob(p, cwd))
392
778
  ]);
393
779
  const exclude = opts.exclude ?? unique([
394
- ...userRest.exclude ?? [],
780
+ ...userRest.exclude ?? cssRest.exclude ?? [],
395
781
  ...tw.scan.excludes.map((p) => sourceToGlob(p, cwd))
396
782
  ]);
397
783
  const defaults = {
@@ -418,42 +804,83 @@ async function createPandatailProject(opts) {
418
804
  const merged = mergeConfigs([
419
805
  defaults,
420
806
  presetBase,
421
- ...userPresets,
807
+ ...presets,
422
808
  tw.preset,
809
+ cssRest,
423
810
  userRest,
424
811
  finalOverrides
425
812
  ]);
426
813
  const config = applyConfigDefaults(merged, cwd);
427
- const compiler = createCompilerFromSnapshot(createConfigSnapshot(config));
428
814
  return {
429
- compiler,
430
815
  config,
431
816
  cwd,
432
- outdir: resolve4(cwd, config.outdir ?? "styled-system"),
817
+ outdir: resolve5(cwd, config.outdir ?? "styled-system"),
433
818
  dependencies: unique(dependencies),
434
- warnings: tw.scan.warnings
819
+ warnings: tw.scan.warnings,
820
+ cssScan: tw.scan
435
821
  };
436
822
  }
437
823
  function buildProject(project, opts = {}) {
438
- const { compiler, cwd, outdir } = project;
824
+ return writeProject(project, scanProject(project), opts);
825
+ }
826
+ function scanProject({ compiler }) {
439
827
  const files = compiler.scan();
440
- compiler.parseFiles(files);
828
+ return {
829
+ files,
830
+ diagnostics: collectParseDiagnostics(compiler.parseFiles(files))
831
+ };
832
+ }
833
+ function writeProject({ compiler, cwd, outdir }, { files, diagnostics }, opts = {}) {
441
834
  let artifacts = 0;
442
835
  if (opts.codegen !== false) {
443
836
  artifacts = compiler.writeArtifacts({ outdir, cwd }).length;
444
837
  }
445
838
  let cssPath;
446
839
  if (opts.outfile !== false) {
447
- const outfile = opts.outfile ?? relative(cwd, resolve4(outdir, "styles.css"));
840
+ const outfile = opts.outfile ?? relative(cwd, resolve5(outdir, "styles.css"));
448
841
  cssPath = compiler.writeCss({ outfile, cwd }).path;
449
842
  }
450
- return { files, artifacts, cssPath, diagnostics: compiler.diagnostics() };
843
+ return {
844
+ files,
845
+ artifacts,
846
+ cssPath,
847
+ diagnostics: dedupeDiagnostics([...diagnostics, ...compiler.diagnostics()])
848
+ };
849
+ }
850
+ async function readCssConfig(file) {
851
+ try {
852
+ const config = JSON.parse(await readFile3(file, "utf8"));
853
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
854
+ throw new Error("expected a Panda config object");
855
+ }
856
+ for (const key of ["include", "exclude"]) {
857
+ if (config[key] !== undefined && (!Array.isArray(config[key]) || config[key].some((value) => typeof value !== "string"))) {
858
+ throw new Error(`"${key}" must be an array of strings`);
859
+ }
860
+ }
861
+ if (config.presets !== undefined && !Array.isArray(config.presets)) {
862
+ throw new Error('"presets" must be an array');
863
+ }
864
+ if (config.theme !== undefined && (!config.theme || typeof config.theme !== "object" || Array.isArray(config.theme))) {
865
+ throw new Error('"theme" must be an object');
866
+ }
867
+ return config;
868
+ } catch (error) {
869
+ throw new PandatailDiagnosticError([
870
+ {
871
+ code: "panda-config",
872
+ severity: "error",
873
+ file,
874
+ message: `Could not load @panda config ${file}: ${error.message}`
875
+ }
876
+ ]);
877
+ }
451
878
  }
452
879
  function sourceToGlob(path, cwd) {
453
880
  const rel = relative(cwd, path).split("\\").join("/");
454
881
  const p = rel.startsWith(".") ? rel : `./${rel}`;
455
882
  const hasGlob = /[*?{}\[\]]/.test(p);
456
- if (!hasGlob && existsSync2(path) && statSync(path).isDirectory()) {
883
+ if (!hasGlob && existsSync(path) && statSync(path).isDirectory()) {
457
884
  return `${p}/**/*.${DEFAULT_EXT}`;
458
885
  }
459
886
  return p;
@@ -471,7 +898,7 @@ async function loadPreset(entry, cwd) {
471
898
  const value = await entry;
472
899
  if (typeof value !== "string")
473
900
  return value;
474
- const req = createRequire(resolve4(cwd, "__pandatail_anchor__"));
901
+ const req = createRequire(resolve5(cwd, "__pandatail_anchor__"));
475
902
  let mod;
476
903
  try {
477
904
  mod = await import(req.resolve(value));
@@ -483,26 +910,374 @@ async function loadPreset(entry, cwd) {
483
910
  function unique(xs) {
484
911
  return [...new Set(xs)];
485
912
  }
913
+ var DEFAULT_EXT = "{js,jsx,ts,tsx,mdx}";
914
+ var init_project = __esm(() => {
915
+ init_diagnostics();
916
+ init_preset();
917
+ });
918
+
919
+ // src/check.ts
920
+ import { dedupeDiagnostics as dedupeDiagnostics2 } from "@pandacss/compiler-shared";
921
+ import { dirname as dirname4, resolve as resolve6 } from "node:path";
922
+ function checkPandaDocument(css, file) {
923
+ return scanCss({
924
+ css,
925
+ base: dirname4(file),
926
+ file,
927
+ recover: true,
928
+ followImports: false
929
+ }).diagnostics.filter((issue) => issue.severity === "error");
930
+ }
931
+ async function checkProject(options) {
932
+ try {
933
+ return checkLoadedProject(await createPandatailProject(options));
934
+ } catch (error) {
935
+ return {
936
+ files: [],
937
+ diagnostics: projectIssues(error, resolve6(options.cwd ?? process.cwd(), options.css))
938
+ };
939
+ }
940
+ }
941
+ function checkLoadedProject(project) {
942
+ const { files, diagnostics } = scanProject(project);
943
+ return {
944
+ files,
945
+ diagnostics: dedupeDiagnostics2([
946
+ ...project.cssScan?.diagnostics ?? [],
947
+ ...checkReferences(project),
948
+ ...diagnostics,
949
+ ...project.compiler.diagnostics()
950
+ ])
951
+ };
952
+ }
953
+ function projectIssues(error, file) {
954
+ if (error instanceof PandatailDiagnosticError)
955
+ return dedupeDiagnostics2(error.diagnostics);
956
+ return [
957
+ {
958
+ code: "project-load",
959
+ severity: "error",
960
+ file,
961
+ message: error instanceof Error ? error.message : String(error)
962
+ }
963
+ ];
964
+ }
965
+ function checkReferences(project) {
966
+ const references = project.cssScan?.panda?.references ?? [];
967
+ if (!references.length)
968
+ return [];
969
+ const spec = project.compiler.spec();
970
+ return references.flatMap(({ category, name, ...site }) => {
971
+ if (category === "tokens") {
972
+ return Object.hasOwn(spec.tokens.values, name) ? [] : [
973
+ {
974
+ ...site,
975
+ severity: "error",
976
+ code: "panda-token-reference",
977
+ message: `Unknown Panda token: ${name}. Use a full token path, or var() for a CSS variable.`
978
+ }
979
+ ];
980
+ }
981
+ const property = category.slice(0, -1);
982
+ const names = spec.utilities.properties[property]?.literals ?? [];
983
+ if (names.includes(name))
984
+ return [];
985
+ const choices = names.slice(0, 5).join(", ");
986
+ return [
987
+ {
988
+ ...site,
989
+ severity: "error",
990
+ code: "panda-composition-reference",
991
+ message: `Unknown ${property}: ${name}.${choices ? ` Available: ${choices}.` : ""}`
992
+ }
993
+ ];
994
+ });
995
+ }
996
+ var init_check = __esm(() => {
997
+ init_diagnostics();
998
+ init_project();
999
+ init_scanCss();
1000
+ });
1001
+
1002
+ // src/languageServer.ts
1003
+ import { fileURLToPath } from "node:url";
1004
+ import {
1005
+ CompletionItemKind,
1006
+ createConnection,
1007
+ DiagnosticSeverity,
1008
+ MarkupKind,
1009
+ PositionEncodingKind,
1010
+ TextDocuments,
1011
+ TextDocumentSyncKind
1012
+ } from "vscode-languageserver/node.js";
1013
+ import { TextDocument } from "vscode-languageserver-textdocument";
1014
+ function runLanguageServer() {
1015
+ const connection = createConnection(process.stdin, process.stdout);
1016
+ const documents = new TextDocuments(TextDocument);
1017
+ const withDiagnostics = new Set;
1018
+ let hoverFormat = MarkupKind.PlainText;
1019
+ connection.onInitialize(({ capabilities }) => {
1020
+ hoverFormat = capabilities.textDocument?.hover?.contentFormat?.[0] ?? MarkupKind.PlainText;
1021
+ return {
1022
+ serverInfo: { name: "Pandatail" },
1023
+ capabilities: {
1024
+ positionEncoding: PositionEncodingKind.UTF16,
1025
+ textDocumentSync: {
1026
+ openClose: true,
1027
+ change: TextDocumentSyncKind.Incremental
1028
+ },
1029
+ completionProvider: { triggerCharacters: ["@", " "] },
1030
+ hoverProvider: true
1031
+ }
1032
+ };
1033
+ });
1034
+ documents.onDidChangeContent(({ document }) => {
1035
+ const { uri, version } = document;
1036
+ const file = cssFile(document);
1037
+ const css = document.getText();
1038
+ const eligible = file !== undefined && (/\.panda\.css$/i.test(file) || hasPandaDirective(css));
1039
+ if (!eligible && !withDiagnostics.has(uri))
1040
+ return;
1041
+ const diagnostics = eligible ? checkPandaDocument(css, file).map((diagnostic) => toDiagnostic(document, diagnostic)) : [];
1042
+ if (diagnostics.length)
1043
+ withDiagnostics.add(uri);
1044
+ else
1045
+ withDiagnostics.delete(uri);
1046
+ connection.sendDiagnostics({ uri, version, diagnostics });
1047
+ });
1048
+ documents.onDidClose(({ document: { uri } }) => {
1049
+ if (withDiagnostics.delete(uri)) {
1050
+ connection.sendDiagnostics({ uri, diagnostics: [] });
1051
+ }
1052
+ });
1053
+ connection.onCompletion(({ textDocument, position }) => {
1054
+ const document = documents.get(textDocument.uri);
1055
+ return document && cssFile(document) !== undefined ? complete(document, position) : [];
1056
+ });
1057
+ connection.onHover(({ textDocument, position }) => {
1058
+ const document = documents.get(textDocument.uri);
1059
+ return document && cssFile(document) !== undefined ? hover(document, position, hoverFormat) : null;
1060
+ });
1061
+ documents.listen(connection);
1062
+ connection.listen();
1063
+ }
1064
+ function cssFile(document) {
1065
+ let file = document.uri;
1066
+ try {
1067
+ const uri = new URL(file);
1068
+ file = uri.protocol === "file:" ? fileURLToPath(uri) : decodeURIComponent(uri.pathname);
1069
+ } catch {}
1070
+ if (document.languageId === "css" || /\.css$/i.test(file))
1071
+ return file;
1072
+ }
1073
+ function toDiagnostic(document, diagnostic) {
1074
+ const offsetAt = ({ line, column }) => document.offsetAt({ line: line - 1, character: column - 1 });
1075
+ const { location } = diagnostic;
1076
+ const start = location ? offsetAt(location.start) : 0;
1077
+ let end = location ? offsetAt(location.end) : start;
1078
+ if (end <= start) {
1079
+ const text = document.getText();
1080
+ const wide = (text.codePointAt(start) ?? 0) > 65535 || text.startsWith(`\r
1081
+ `, start);
1082
+ end = start + (wide ? 2 : 1);
1083
+ }
1084
+ return {
1085
+ range: rangeAt(document, start, end),
1086
+ source: "pandatail",
1087
+ severity: severity[diagnostic.severity],
1088
+ code: diagnostic.code,
1089
+ message: diagnostic.message
1090
+ };
1091
+ }
1092
+ function rangeAt(document, start, end) {
1093
+ return { start: document.positionAt(start), end: document.positionAt(end) };
1094
+ }
1095
+ function maskCss(css) {
1096
+ return css.replace(/\/\*[\s\S]*?(?:\*\/|$)|"(?:[^"\\]|\\[\s\S]?)*"?|'(?:[^'\\]|\\[\s\S]?)*'?|\\[\s\S]?/g, (token) => {
1097
+ const comment = token.startsWith("/*") && token.length >= 4 && token.endsWith("*/");
1098
+ return (comment ? " " : "\x00").repeat(token.length);
1099
+ });
1100
+ }
1101
+ function hasPandaDirective(css) {
1102
+ return css.includes("@panda") && /(?:^|[{};])\s*@panda(?=$|[\s();{}\[\]#/\0])/.test(maskCss(css));
1103
+ }
1104
+ function topLevelPrelude(prefix) {
1105
+ const css = maskCss(prefix);
1106
+ const groups = [];
1107
+ let start = 0;
1108
+ for (const { 0: token, index } of css.matchAll(/[{}()[\];]/g)) {
1109
+ const end = groupEnds.get(token);
1110
+ if (end)
1111
+ groups.push(end);
1112
+ else if (token === groups.at(-1))
1113
+ groups.pop();
1114
+ if (!groups.length && (token === "}" || token === ";"))
1115
+ start = index + 1;
1116
+ }
1117
+ if (!groups.length)
1118
+ return css.slice(start);
1119
+ }
1120
+ function complete(document, position) {
1121
+ const css = document.getText();
1122
+ const offset = document.offsetAt(position);
1123
+ const prelude = topLevelPrelude(css.slice(0, offset));
1124
+ if (prelude === undefined)
1125
+ return [];
1126
+ const kind = kindPrelude.exec(prelude)?.[1];
1127
+ const atRule = /^\s*(@[\w-]*)?$/.exec(prelude);
1128
+ if (kind === undefined && !atRule)
1129
+ return [];
1130
+ const prefix = kind ?? atRule?.[1] ?? "";
1131
+ const tail = kind !== undefined || prefix ? /^[\w-]*/.exec(css.slice(offset))[0] : "";
1132
+ const range = rangeAt(document, offset - prefix.length, offset + tail.length);
1133
+ return (kind === undefined ? [directive] : keywords).filter(({ label }) => label.startsWith(prefix)).map((item) => ({
1134
+ ...item,
1135
+ kind: CompletionItemKind.Keyword,
1136
+ textEdit: { range, newText: item.label }
1137
+ }));
1138
+ }
1139
+ function hover(document, position, format) {
1140
+ const css = document.getText();
1141
+ const offset = document.offsetAt(position);
1142
+ const end = offset + /^@?[\w-]*/.exec(css.slice(offset))[0].length;
1143
+ const prelude = topLevelPrelude(css.slice(0, end));
1144
+ if (prelude === undefined)
1145
+ return null;
1146
+ const kind = kindPrelude.exec(prelude)?.[1];
1147
+ const item = /^\s*@panda$/.test(prelude) ? directive : keywords.find(({ label }) => label === kind);
1148
+ if (!item)
1149
+ return null;
1150
+ const signature = format === MarkupKind.Markdown ? "```css\n" + item.detail + "\n```" : item.detail;
1151
+ return {
1152
+ range: rangeAt(document, end - item.label.length, end),
1153
+ contents: { kind: format, value: `${signature}
1154
+
1155
+ ${item.documentation}` }
1156
+ };
1157
+ }
1158
+ var directive, keywords, severity, groupEnds, kindPrelude;
1159
+ var init_languageServer = __esm(() => {
1160
+ init_check();
1161
+ directive = {
1162
+ label: "@panda",
1163
+ detail: "@panda <kind> …",
1164
+ documentation: "A top-level Pandatail directive. Define a style or recipe, or reference a JSON config."
1165
+ };
1166
+ keywords = Object.entries({
1167
+ "text-style": "Define reusable typography. Use dotted names to group styles.",
1168
+ "layer-style": "Define reusable visual styles such as a surface. Use dotted names to group styles.",
1169
+ "animation-style": "Define reusable animation styles. Use dotted names to group styles.",
1170
+ recipe: "Define base styles and variants with `@option <axis> <value> { … }` and `@defaults { axis: value; }`.",
1171
+ config: "Reference one JSON config relative to the declaring stylesheet. The language server does not load it."
1172
+ }).map(([label, documentation]) => ({
1173
+ label,
1174
+ documentation,
1175
+ detail: label === "config" ? '@panda config "./panda.json";' : `@panda ${label} <name> { … }`
1176
+ }));
1177
+ severity = {
1178
+ error: DiagnosticSeverity.Error,
1179
+ warning: DiagnosticSeverity.Warning,
1180
+ info: DiagnosticSeverity.Information
1181
+ };
1182
+ groupEnds = new Map([
1183
+ ["{", "}"],
1184
+ ["(", ")"],
1185
+ ["[", "]"]
1186
+ ]);
1187
+ kindPrelude = /^\s*@panda\s+([\w-]*)$/;
1188
+ });
1189
+
1190
+ // src/cli.ts
1191
+ init_check();
1192
+ init_diagnostics();
1193
+ init_project();
1194
+ import { existsSync as existsSync2, watch } from "node:fs";
1195
+ import { readFile as readFile4 } from "node:fs/promises";
1196
+ import { relative as relative2, resolve as resolve8, sep } from "node:path";
1197
+ import { parseArgs } from "node:util";
1198
+
1199
+ // src/studio.ts
1200
+ init_project();
1201
+ import { spawn } from "node:child_process";
1202
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
1203
+ import { createRequire as createRequire2 } from "node:module";
1204
+ import { constants, tmpdir } from "node:os";
1205
+ import { dirname as dirname5, join, resolve as resolve7 } from "node:path";
1206
+ async function studioConfig(options) {
1207
+ const { config, dependencies, warnings } = await resolvePandatailConfig(options, true);
1208
+ for (const warning of warnings)
1209
+ console.warn(`pandatail: warning: ${warning}`);
1210
+ return { ...config, dependencies: [...config.dependencies ?? [], ...dependencies] };
1211
+ }
1212
+ async function runPandatailStudio(options, { port, noOpen }) {
1213
+ const require2 = createRequire2(import.meta.url);
1214
+ const manifestPath = require2.resolve("@pandacss/dev/package.json");
1215
+ const { bin, version } = require2(manifestPath);
1216
+ const [major, minor] = version.split(".");
1217
+ if (major !== "2" || !(Number(minor) >= 4)) {
1218
+ throw new Error(`studio requires Panda CSS 2.4 or newer (found ${version})`);
1219
+ }
1220
+ const cwd = resolve7(options.cwd ?? process.cwd());
1221
+ const dir = mkdtempSync(join(tmpdir(), "pandatail-studio-"));
1222
+ try {
1223
+ const config = join(dir, "panda.config.mjs");
1224
+ const entry = new URL(import.meta.url.endsWith(".ts") ? "./studio.ts" : "./studio.js", import.meta.url);
1225
+ writeFileSync(config, `
1226
+ const { studioConfig } = await import(new URL(${JSON.stringify(entry.href)}).href);
1227
+ export default await studioConfig(${JSON.stringify({ ...options, cwd })});
1228
+ `);
1229
+ const args = [resolve7(dirname5(manifestPath), bin.panda), "studio", "--cwd", cwd, "--config", config];
1230
+ if (port !== undefined)
1231
+ args.push(`--port=${port}`);
1232
+ if (noOpen)
1233
+ args.push("--no-open");
1234
+ const child = spawn(process.execPath, args, { stdio: "inherit" });
1235
+ const interrupt = () => child.kill("SIGINT");
1236
+ const terminate = () => child.kill("SIGTERM");
1237
+ process.on("SIGINT", interrupt);
1238
+ process.on("SIGTERM", terminate);
1239
+ try {
1240
+ return await new Promise((done, reject) => {
1241
+ child.once("error", reject);
1242
+ child.once("exit", (code, signal) => done(code ?? (signal ? 128 + constants.signals[signal] : 1)));
1243
+ });
1244
+ } finally {
1245
+ process.off("SIGINT", interrupt);
1246
+ process.off("SIGTERM", terminate);
1247
+ }
1248
+ } finally {
1249
+ rmSync(dir, { recursive: true, force: true });
1250
+ }
1251
+ }
486
1252
 
487
1253
  // src/cli.ts
488
1254
  var HELP = `pandatail: run Panda from a Tailwind v4 stylesheet, no panda.config.ts needed
489
1255
 
490
1256
  Usage
491
- pandatail <command> --css <entry.css> [options]
1257
+ pandatail [command] (--css <entry.css> | --shadcn) [options]
1258
+ pandatail lsp [--stdio]
492
1259
 
493
1260
  Commands
494
1261
  build generate styled-system/ and the stylesheet (default)
495
1262
  codegen generate styled-system/ only
496
1263
  cssgen write the stylesheet only
497
1264
  watch build, then rebuild on change
1265
+ studio open Panda Studio with live tokens and source usage (Panda >= 2.4)
1266
+ check validate the CSS DSL and project usage without writing files
1267
+ lsp run the Pandatail companion language server over stdio
498
1268
 
499
1269
  Options
500
- -c, --css <file> Tailwind entry stylesheet (required)
1270
+ -c, --css <file> Tailwind entry stylesheet (overrides --shadcn)
1271
+ --shadcn read the stylesheet from components.json (tailwind.css)
501
1272
  -o, --out <file> stylesheet to write (default: <outdir>/styles.css)
502
1273
  --config <file> optional panda.config.ts merged on top of the CSS
503
1274
  --outdir <dir> generated code directory (default: styled-system)
504
1275
  -i, --include <glob> source glob to scan; repeatable
505
1276
  --cwd <dir> project root (default: current directory)
1277
+ --port <port> Studio port (default: 6420)
1278
+ --no-open print the Studio link without opening a browser
1279
+ --json print check diagnostics as JSON
1280
+ --warnings-as-errors fail check if it finds warnings
506
1281
  -h, --help
507
1282
  `;
508
1283
  async function main() {
@@ -510,32 +1285,73 @@ async function main() {
510
1285
  allowPositionals: true,
511
1286
  options: {
512
1287
  css: { type: "string", short: "c" },
1288
+ shadcn: { type: "boolean" },
513
1289
  out: { type: "string", short: "o" },
514
1290
  config: { type: "string" },
515
1291
  outdir: { type: "string" },
516
1292
  include: { type: "string", short: "i", multiple: true },
517
1293
  cwd: { type: "string" },
1294
+ port: { type: "string" },
1295
+ "no-open": { type: "boolean" },
1296
+ json: { type: "boolean" },
1297
+ "warnings-as-errors": { type: "boolean" },
1298
+ stdio: { type: "boolean" },
518
1299
  help: { type: "boolean", short: "h" }
519
1300
  }
520
1301
  });
521
1302
  const command = positionals[0] ?? "build";
522
- if (values.help || !["build", "codegen", "cssgen", "watch"].includes(command)) {
1303
+ if (values.help || !["build", "codegen", "cssgen", "watch", "studio", "check", "lsp"].includes(command)) {
523
1304
  console.log(HELP);
524
1305
  process.exit(values.help ? 0 : 1);
525
1306
  }
526
- if (!values.css) {
527
- console.error(`pandatail: --css <entry.css> is required
528
- `);
529
- console.error(HELP);
530
- process.exit(1);
1307
+ if (command === "lsp") {
1308
+ await Promise.resolve().then(() => init_languageServer());
1309
+ runLanguageServer();
1310
+ return;
531
1311
  }
532
- const options = {
533
- css: values.css,
1312
+ const entry = () => values.css ?? (values.shadcn ? readShadcnCss(values.cwd) : undefined);
1313
+ const projectOptions = {
534
1314
  cwd: values.cwd,
535
1315
  config: values.config,
536
1316
  outdir: values.outdir,
537
1317
  include: values.include
538
1318
  };
1319
+ if (command === "check") {
1320
+ let result;
1321
+ try {
1322
+ const css = await entry();
1323
+ if (!css)
1324
+ throw new Error("--css <entry.css> or --shadcn is required");
1325
+ result = await checkProject({ ...projectOptions, css });
1326
+ } catch (error) {
1327
+ const file = values.shadcn && values.css === undefined ? resolve8(values.cwd ?? process.cwd(), "components.json") : undefined;
1328
+ result = { files: [], diagnostics: projectIssues(error, file) };
1329
+ }
1330
+ if (values.json)
1331
+ console.log(JSON.stringify(result, null, 2));
1332
+ else {
1333
+ for (const issue of result.diagnostics)
1334
+ console.error(formatCheckDiagnostic(issue));
1335
+ console.log(`pandatail: checked ${result.files.length} source file(s); ${result.diagnostics.length} diagnostic(s)`);
1336
+ }
1337
+ process.exitCode = result.diagnostics.some((issue) => issue.severity === "error" || values["warnings-as-errors"] && issue.severity === "warning") ? 1 : 0;
1338
+ return;
1339
+ }
1340
+ const css = await entry();
1341
+ if (!css) {
1342
+ console.error(`pandatail: --css <entry.css> or --shadcn is required
1343
+ `);
1344
+ console.error(HELP);
1345
+ process.exit(1);
1346
+ }
1347
+ const options = { ...projectOptions, css };
1348
+ if (command === "studio") {
1349
+ process.exitCode = await runPandatailStudio(options, {
1350
+ port: values.port,
1351
+ noOpen: values["no-open"]
1352
+ });
1353
+ return;
1354
+ }
539
1355
  const buildOpts = {
540
1356
  codegen: command !== "cssgen",
541
1357
  outfile: command === "codegen" ? false : values.out
@@ -558,7 +1374,7 @@ async function main() {
558
1374
  return;
559
1375
  }
560
1376
  for (const file of changed) {
561
- if (existsSync3(file))
1377
+ if (existsSync2(file))
562
1378
  project.compiler.refreshFile(file);
563
1379
  else
564
1380
  project.compiler.removeFile(file);
@@ -571,7 +1387,7 @@ async function main() {
571
1387
  watch(project.cwd, { recursive: true }, (_event, name) => {
572
1388
  if (!name)
573
1389
  return;
574
- const abs = resolve5(project.cwd, name.toString());
1390
+ const abs = resolve8(project.cwd, name.toString());
575
1391
  if (ignored(abs))
576
1392
  return;
577
1393
  const isDep = project.dependencies.includes(abs);
@@ -583,6 +1399,25 @@ async function main() {
583
1399
  });
584
1400
  await new Promise(() => {});
585
1401
  }
1402
+ async function readShadcnCss(cwd = process.cwd()) {
1403
+ const file = resolve8(cwd, "components.json");
1404
+ const source = await readFile4(file, "utf8").catch((error) => {
1405
+ if (error.code !== "ENOENT")
1406
+ throw error;
1407
+ throw new Error(`--shadcn could not find ${file}. Set --cwd to the shadcn workspace or pass --css.`);
1408
+ });
1409
+ let config;
1410
+ try {
1411
+ config = JSON.parse(source);
1412
+ } catch (error) {
1413
+ throw new Error(`invalid JSON in ${file}: ${error.message}`);
1414
+ }
1415
+ const css = config?.tailwind?.css;
1416
+ if (typeof css !== "string" || !css.trim()) {
1417
+ throw new Error(`--shadcn requires a non-empty "tailwind.css" path in ${file}. Set it or pass --css.`);
1418
+ }
1419
+ return resolve8(cwd, css);
1420
+ }
586
1421
  async function load(options) {
587
1422
  const project = await createPandatailProject(options);
588
1423
  for (const w of project.warnings)