@dmisdm/pandatail 0.4.0 → 0.5.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/README.md CHANGED
@@ -41,6 +41,7 @@ pandatail build --css src/app.css # codegen + stylesheet (default)
41
41
  pandatail codegen --css src/app.css # styled-system/ only
42
42
  pandatail cssgen --css src/app.css -o out.css # stylesheet only
43
43
  pandatail watch --css src/app.css # rebuild on change
44
+ pandatail studio --css src/app.css # live Panda Studio (Panda >= 2.4)
44
45
  ```
45
46
 
46
47
  | Option | Meaning |
@@ -54,6 +55,18 @@ pandatail watch --css src/app.css # rebuild on change
54
55
 
55
56
  Import the generated `styled-system/styles.css` after Tailwind's CSS.
56
57
 
58
+ ### Panda Studio
59
+
60
+ `pandatail studio --css src/app.css` opens [Panda Studio](https://panda-css.com/docs/theming/studio)
61
+ with your Tailwind-derived tokens and live usage of Panda styles. It uses Panda's local Studio server
62
+ and accepts `--cwd`, `--include`, `--outdir`, and optional `--config`. It doesn't create a project
63
+ `panda.config.ts` or write build artifacts. Use `--no-open` to print the link, or `--port 3001` to
64
+ choose a port (defaults to `6420`). The link is for local development, not a public URL.
65
+
66
+ Studio previews resolve simple aliases from `@theme` and unconditional `:root` declarations in local
67
+ stylesheets. They don't run your app's CSS cascade, so conditional overrides and unresolved CSS
68
+ variables may not render. Normal builds still reference Tailwind's variables.
69
+
57
70
  ## Vite plugin
58
71
 
59
72
  Runs codegen and the stylesheet before your modules build, then watches CSS, config and source files during `vite dev`.
@@ -79,14 +92,14 @@ Options: everything `createPandatailProject` takes (`css`, `config`, `include`,
79
92
 
80
93
  ## What maps, and what doesn't
81
94
 
82
- | Tailwind | Panda |
83
- | --- | --- |
84
- | `@theme` | `theme.tokens` + `breakpoints`, as `var(--…)` references |
85
- | `@source "x"` / `@source not "x"` | `include` / `exclude` |
86
- | `@custom-variant n (sel);` | `conditions.extend.n` |
87
- | `@custom-variant n { &:hover, &:focus { @slot } }` | same (single selector or at-rule wrapping one `@slot`) |
88
- | `@plugin` | loaded for token extraction; plugin-defined utilities are not Panda utilities |
89
- | `@source inline(...)`, complex `@custom-variant` blocks, `@utility` | warned about, not mapped |
95
+ | Tailwind | Panda |
96
+ | ------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
97
+ | `@theme` | `theme.tokens` + `breakpoints`, as `var(--…)` references |
98
+ | `@source "x"` / `@source not "x"` | `include` / `exclude` |
99
+ | `@custom-variant n (sel);` | `conditions.extend.n` |
100
+ | `@custom-variant n { &:hover, &:focus { @slot } }` | same (single selector or at-rule wrapping one `@slot`) |
101
+ | `@plugin` | loaded for token extraction; plugin-defined utilities are not Panda utilities |
102
+ | `@source inline(...)`, complex `@custom-variant` blocks, `@utility` | warned about, not mapped |
90
103
 
91
104
  Anything CSS can't express (text styles, recipes, patterns, utilities) goes in an optional
92
105
  `panda.config.ts` passed with `--config`. It is merged after Tailwind's tokens, so it wins.
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { existsSync as existsSync3, watch } from "node:fs";
5
- import { relative as relative2, resolve as resolve5, sep } from "node:path";
5
+ import { relative as relative2, resolve as resolve6, sep } from "node:path";
6
6
  import { parseArgs } from "node:util";
7
7
 
8
8
  // src/project.ts
@@ -163,11 +163,17 @@ function pushNamed(out) {
163
163
 
164
164
  // src/extract.ts
165
165
  async function extractTokens(opts) {
166
+ return tokensFromTheme(await loadThemeEntries(opts));
167
+ }
168
+ async function loadThemeEntries(opts) {
166
169
  const base = resolve(opts.base ?? process.cwd());
167
170
  const ds = await __unstable__loadDesignSystem(opts.css, { base });
168
171
  const themeEntries = new Map;
169
172
  for (const [key, entry] of ds.theme.entries())
170
173
  themeEntries.set(key, entry.value);
174
+ return themeEntries;
175
+ }
176
+ function tokensFromTheme(themeEntries) {
171
177
  const out = [];
172
178
  for (const [key, rawValue] of themeEntries) {
173
179
  const matched = matchNamespace(key);
@@ -194,7 +200,7 @@ async function extractTokensFromFile(path) {
194
200
  import postcss from "postcss";
195
201
  import { existsSync, readFileSync } from "node:fs";
196
202
  import { dirname as dirname2, resolve as resolve2 } from "node:path";
197
- function scanCss(opts) {
203
+ function scanCss(opts, rootVariables) {
198
204
  const out = {
199
205
  sources: [],
200
206
  excludes: [],
@@ -202,10 +208,10 @@ function scanCss(opts) {
202
208
  warnings: [],
203
209
  files: opts.file ? [opts.file] : []
204
210
  };
205
- walk(opts.css, opts.base, out, new Set(opts.file ? [opts.file] : []));
211
+ walk(opts.css, opts.base, out, new Set(opts.file ? [opts.file] : []), rootVariables);
206
212
  return out;
207
213
  }
208
- function walk(css, base, out, seen) {
214
+ function walk(css, base, out, seen, rootVariables) {
209
215
  let root;
210
216
  try {
211
217
  root = postcss.parse(css);
@@ -213,7 +219,11 @@ function walk(css, base, out, seen) {
213
219
  out.warnings.push(`could not parse CSS in ${base}: ${e.message}`);
214
220
  return;
215
221
  }
216
- root.walkAtRules((rule) => {
222
+ root.walk((rule) => {
223
+ if (rule.type === "rule" && rootVariables)
224
+ collectRootVariables(rule, rootVariables);
225
+ if (rule.type !== "atrule")
226
+ return;
217
227
  switch (rule.name) {
218
228
  case "import": {
219
229
  const id = quoted(rule.params) ?? urlTarget(rule.params);
@@ -224,7 +234,7 @@ function walk(css, base, out, seen) {
224
234
  return;
225
235
  seen.add(path);
226
236
  out.files.push(path);
227
- walk(readFileSync(path, "utf8"), dirname2(path), out, seen);
237
+ walk(readFileSync(path, "utf8"), dirname2(path), out, seen, rootVariables);
228
238
  return;
229
239
  }
230
240
  case "source":
@@ -234,6 +244,17 @@ function walk(css, base, out, seen) {
234
244
  }
235
245
  });
236
246
  }
247
+ function collectRootVariables(rule, variables) {
248
+ let parent = rule.parent;
249
+ while (parent?.type === "atrule" && parent.name === "layer")
250
+ parent = parent.parent;
251
+ if (parent?.type !== "root" || !rule.selectors.includes(":root"))
252
+ return;
253
+ for (const node of rule.nodes) {
254
+ if (node.type === "decl" && node.prop.startsWith("--"))
255
+ variables.set(node.prop, node.value);
256
+ }
257
+ }
237
258
  function handleSource(rule, base, out) {
238
259
  const params = rule.params.trim();
239
260
  if (params.startsWith("inline(") || params.startsWith("not inline(")) {
@@ -283,7 +304,7 @@ function urlTarget(params) {
283
304
  }
284
305
 
285
306
  // src/preset.ts
286
- async function loadTailwind(opts) {
307
+ async function loadTailwind(opts, preview = false) {
287
308
  let css;
288
309
  let base;
289
310
  let file;
@@ -297,13 +318,32 @@ async function loadTailwind(opts) {
297
318
  } else {
298
319
  throw new Error("pandatail: provide either `css` or `cssPath`");
299
320
  }
300
- const tokens = await extractTokens({ css, base });
301
- const scan = scanCss({ css, base, file });
302
- return { preset: buildPreset(tokens, scan), scan, tokens };
321
+ const theme = await loadThemeEntries({ css, base });
322
+ const tokens = tokensFromTheme(theme);
323
+ const variables = preview ? new Map(theme) : undefined;
324
+ const scan = scanCss({ css, base, file }, variables);
325
+ const presetTokens = variables ? tokens.map((token) => ({
326
+ ...token,
327
+ value: resolvePreviewValue(token.value, variables)
328
+ })) : tokens;
329
+ return { preset: buildPreset(presetTokens, scan), scan, tokens };
303
330
  }
304
331
  async function tailwindPreset(opts) {
305
332
  return (await loadTailwind(opts)).preset;
306
333
  }
334
+ function resolvePreviewValue(value, variables, resolving = new Set) {
335
+ return value.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|(?<![\w-])var\(\s*(--[\w-]+)\s*\)/gi, (match, name) => {
336
+ if (name === undefined || resolving.has(name))
337
+ return match;
338
+ const definition = variables.get(name);
339
+ if (definition === undefined)
340
+ return match;
341
+ resolving.add(name);
342
+ const resolved = resolvePreviewValue(definition, variables, resolving);
343
+ resolving.delete(name);
344
+ return resolved;
345
+ });
346
+ }
307
347
  function buildPreset(tokens, scan) {
308
348
  const breakpoints = {};
309
349
  const tokenTokens = [];
@@ -369,11 +409,16 @@ function buildTree(tokens, category) {
369
409
  // src/project.ts
370
410
  var DEFAULT_EXT = "{js,jsx,ts,tsx,mdx}";
371
411
  async function createPandatailProject(opts) {
412
+ const project = await resolvePandatailConfig(opts);
413
+ const compiler = createCompilerFromSnapshot(createConfigSnapshot(project.config));
414
+ return { compiler, ...project };
415
+ }
416
+ async function resolvePandatailConfig(opts, preview = false) {
372
417
  const cwd = resolve4(opts.cwd ?? process.cwd());
373
418
  const cssPath = resolve4(cwd, opts.css);
374
419
  if (!existsSync2(cssPath))
375
420
  throw new Error(`pandatail: CSS entry not found: ${cssPath}`);
376
- const tw = await loadTailwind({ cssPath });
421
+ const tw = await loadTailwind({ cssPath }, preview);
377
422
  const dependencies = [...tw.scan.files];
378
423
  let user = {};
379
424
  if (typeof opts.config === "string") {
@@ -424,9 +469,7 @@ async function createPandatailProject(opts) {
424
469
  finalOverrides
425
470
  ]);
426
471
  const config = applyConfigDefaults(merged, cwd);
427
- const compiler = createCompilerFromSnapshot(createConfigSnapshot(config));
428
472
  return {
429
- compiler,
430
473
  config,
431
474
  cwd,
432
475
  outdir: resolve4(cwd, config.outdir ?? "styled-system"),
@@ -484,6 +527,59 @@ function unique(xs) {
484
527
  return [...new Set(xs)];
485
528
  }
486
529
 
530
+ // src/studio.ts
531
+ import { spawn } from "node:child_process";
532
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
533
+ import { createRequire as createRequire2 } from "node:module";
534
+ import { constants, tmpdir } from "node:os";
535
+ import { dirname as dirname4, join, resolve as resolve5 } from "node:path";
536
+ async function studioConfig(options) {
537
+ const { config, dependencies, warnings } = await resolvePandatailConfig(options, true);
538
+ for (const warning of warnings)
539
+ console.warn(`pandatail: warning: ${warning}`);
540
+ return { ...config, dependencies: [...config.dependencies ?? [], ...dependencies] };
541
+ }
542
+ async function runPandatailStudio(options, { port, noOpen }) {
543
+ const require2 = createRequire2(import.meta.url);
544
+ const manifestPath = require2.resolve("@pandacss/dev/package.json");
545
+ const { bin, version } = require2(manifestPath);
546
+ const [major, minor] = version.split(".");
547
+ if (major !== "2" || !(Number(minor) >= 4)) {
548
+ throw new Error(`studio requires Panda CSS 2.4 or newer (found ${version})`);
549
+ }
550
+ const cwd = resolve5(options.cwd ?? process.cwd());
551
+ const dir = mkdtempSync(join(tmpdir(), "pandatail-studio-"));
552
+ try {
553
+ const config = join(dir, "panda.config.mjs");
554
+ const entry = new URL(import.meta.url.endsWith(".ts") ? "./studio.ts" : "./studio.js", import.meta.url);
555
+ writeFileSync(config, `
556
+ const { studioConfig } = await import(new URL(${JSON.stringify(entry.href)}).href);
557
+ export default await studioConfig(${JSON.stringify({ ...options, cwd })});
558
+ `);
559
+ const args = [resolve5(dirname4(manifestPath), bin.panda), "studio", "--cwd", cwd, "--config", config];
560
+ if (port !== undefined)
561
+ args.push(`--port=${port}`);
562
+ if (noOpen)
563
+ args.push("--no-open");
564
+ const child = spawn(process.execPath, args, { stdio: "inherit" });
565
+ const interrupt = () => child.kill("SIGINT");
566
+ const terminate = () => child.kill("SIGTERM");
567
+ process.on("SIGINT", interrupt);
568
+ process.on("SIGTERM", terminate);
569
+ try {
570
+ return await new Promise((done, reject) => {
571
+ child.once("error", reject);
572
+ child.once("exit", (code, signal) => done(code ?? (signal ? 128 + constants.signals[signal] : 1)));
573
+ });
574
+ } finally {
575
+ process.off("SIGINT", interrupt);
576
+ process.off("SIGTERM", terminate);
577
+ }
578
+ } finally {
579
+ rmSync(dir, { recursive: true, force: true });
580
+ }
581
+ }
582
+
487
583
  // src/cli.ts
488
584
  var HELP = `pandatail: run Panda from a Tailwind v4 stylesheet, no panda.config.ts needed
489
585
 
@@ -495,6 +591,7 @@ Commands
495
591
  codegen generate styled-system/ only
496
592
  cssgen write the stylesheet only
497
593
  watch build, then rebuild on change
594
+ studio open Panda Studio with live tokens and source usage (Panda >= 2.4)
498
595
 
499
596
  Options
500
597
  -c, --css <file> Tailwind entry stylesheet (required)
@@ -503,6 +600,8 @@ Options
503
600
  --outdir <dir> generated code directory (default: styled-system)
504
601
  -i, --include <glob> source glob to scan; repeatable
505
602
  --cwd <dir> project root (default: current directory)
603
+ --port <port> Studio port (default: 6420)
604
+ --no-open print the Studio link without opening a browser
506
605
  -h, --help
507
606
  `;
508
607
  async function main() {
@@ -515,11 +614,13 @@ async function main() {
515
614
  outdir: { type: "string" },
516
615
  include: { type: "string", short: "i", multiple: true },
517
616
  cwd: { type: "string" },
617
+ port: { type: "string" },
618
+ "no-open": { type: "boolean" },
518
619
  help: { type: "boolean", short: "h" }
519
620
  }
520
621
  });
521
622
  const command = positionals[0] ?? "build";
522
- if (values.help || !["build", "codegen", "cssgen", "watch"].includes(command)) {
623
+ if (values.help || !["build", "codegen", "cssgen", "watch", "studio"].includes(command)) {
523
624
  console.log(HELP);
524
625
  process.exit(values.help ? 0 : 1);
525
626
  }
@@ -536,6 +637,13 @@ async function main() {
536
637
  outdir: values.outdir,
537
638
  include: values.include
538
639
  };
640
+ if (command === "studio") {
641
+ process.exitCode = await runPandatailStudio(options, {
642
+ port: values.port,
643
+ noOpen: values["no-open"]
644
+ });
645
+ return;
646
+ }
539
647
  const buildOpts = {
540
648
  codegen: command !== "cssgen",
541
649
  outfile: command === "codegen" ? false : values.out
@@ -571,7 +679,7 @@ async function main() {
571
679
  watch(project.cwd, { recursive: true }, (_event, name) => {
572
680
  if (!name)
573
681
  return;
574
- const abs = resolve5(project.cwd, name.toString());
682
+ const abs = resolve6(project.cwd, name.toString());
575
683
  if (ignored(abs))
576
684
  return;
577
685
  const isDep = project.dependencies.includes(abs);
package/dist/extract.d.ts CHANGED
@@ -43,5 +43,7 @@ export interface ExtractOptions {
43
43
  * theme into a flat list of {@link ExtractedToken}s ready for Panda.
44
44
  */
45
45
  export declare function extractTokens(opts: ExtractOptions): Promise<ExtractedToken[]>;
46
+ export declare function loadThemeEntries(opts: ExtractOptions): Promise<Map<string, string>>;
47
+ export declare function tokensFromTheme(themeEntries: ReadonlyMap<string, string>): ExtractedToken[];
46
48
  /** Convenience: load CSS from a file path then extract. */
47
49
  export declare function extractTokensFromFile(path: string): Promise<ExtractedToken[]>;
package/dist/index.js CHANGED
@@ -156,11 +156,17 @@ function pushNamed(out) {
156
156
 
157
157
  // src/extract.ts
158
158
  async function extractTokens(opts) {
159
+ return tokensFromTheme(await loadThemeEntries(opts));
160
+ }
161
+ async function loadThemeEntries(opts) {
159
162
  const base = resolve(opts.base ?? process.cwd());
160
163
  const ds = await __unstable__loadDesignSystem(opts.css, { base });
161
164
  const themeEntries = new Map;
162
165
  for (const [key, entry] of ds.theme.entries())
163
166
  themeEntries.set(key, entry.value);
167
+ return themeEntries;
168
+ }
169
+ function tokensFromTheme(themeEntries) {
164
170
  const out = [];
165
171
  for (const [key, rawValue] of themeEntries) {
166
172
  const matched = matchNamespace(key);
@@ -187,7 +193,7 @@ async function extractTokensFromFile(path) {
187
193
  import postcss from "postcss";
188
194
  import { existsSync, readFileSync } from "node:fs";
189
195
  import { dirname as dirname2, resolve as resolve2 } from "node:path";
190
- function scanCss(opts) {
196
+ function scanCss(opts, rootVariables) {
191
197
  const out = {
192
198
  sources: [],
193
199
  excludes: [],
@@ -195,10 +201,10 @@ function scanCss(opts) {
195
201
  warnings: [],
196
202
  files: opts.file ? [opts.file] : []
197
203
  };
198
- walk(opts.css, opts.base, out, new Set(opts.file ? [opts.file] : []));
204
+ walk(opts.css, opts.base, out, new Set(opts.file ? [opts.file] : []), rootVariables);
199
205
  return out;
200
206
  }
201
- function walk(css, base, out, seen) {
207
+ function walk(css, base, out, seen, rootVariables) {
202
208
  let root;
203
209
  try {
204
210
  root = postcss.parse(css);
@@ -206,7 +212,11 @@ function walk(css, base, out, seen) {
206
212
  out.warnings.push(`could not parse CSS in ${base}: ${e.message}`);
207
213
  return;
208
214
  }
209
- root.walkAtRules((rule) => {
215
+ root.walk((rule) => {
216
+ if (rule.type === "rule" && rootVariables)
217
+ collectRootVariables(rule, rootVariables);
218
+ if (rule.type !== "atrule")
219
+ return;
210
220
  switch (rule.name) {
211
221
  case "import": {
212
222
  const id = quoted(rule.params) ?? urlTarget(rule.params);
@@ -217,7 +227,7 @@ function walk(css, base, out, seen) {
217
227
  return;
218
228
  seen.add(path);
219
229
  out.files.push(path);
220
- walk(readFileSync(path, "utf8"), dirname2(path), out, seen);
230
+ walk(readFileSync(path, "utf8"), dirname2(path), out, seen, rootVariables);
221
231
  return;
222
232
  }
223
233
  case "source":
@@ -227,6 +237,17 @@ function walk(css, base, out, seen) {
227
237
  }
228
238
  });
229
239
  }
240
+ function collectRootVariables(rule, variables) {
241
+ let parent = rule.parent;
242
+ while (parent?.type === "atrule" && parent.name === "layer")
243
+ parent = parent.parent;
244
+ if (parent?.type !== "root" || !rule.selectors.includes(":root"))
245
+ return;
246
+ for (const node of rule.nodes) {
247
+ if (node.type === "decl" && node.prop.startsWith("--"))
248
+ variables.set(node.prop, node.value);
249
+ }
250
+ }
230
251
  function handleSource(rule, base, out) {
231
252
  const params = rule.params.trim();
232
253
  if (params.startsWith("inline(") || params.startsWith("not inline(")) {
@@ -276,7 +297,7 @@ function urlTarget(params) {
276
297
  }
277
298
 
278
299
  // src/preset.ts
279
- async function loadTailwind(opts) {
300
+ async function loadTailwind(opts, preview = false) {
280
301
  let css;
281
302
  let base;
282
303
  let file;
@@ -290,13 +311,32 @@ async function loadTailwind(opts) {
290
311
  } else {
291
312
  throw new Error("pandatail: provide either `css` or `cssPath`");
292
313
  }
293
- const tokens = await extractTokens({ css, base });
294
- const scan = scanCss({ css, base, file });
295
- return { preset: buildPreset(tokens, scan), scan, tokens };
314
+ const theme = await loadThemeEntries({ css, base });
315
+ const tokens = tokensFromTheme(theme);
316
+ const variables = preview ? new Map(theme) : undefined;
317
+ const scan = scanCss({ css, base, file }, variables);
318
+ const presetTokens = variables ? tokens.map((token) => ({
319
+ ...token,
320
+ value: resolvePreviewValue(token.value, variables)
321
+ })) : tokens;
322
+ return { preset: buildPreset(presetTokens, scan), scan, tokens };
296
323
  }
297
324
  async function tailwindPreset(opts) {
298
325
  return (await loadTailwind(opts)).preset;
299
326
  }
327
+ function resolvePreviewValue(value, variables, resolving = new Set) {
328
+ return value.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|(?<![\w-])var\(\s*(--[\w-]+)\s*\)/gi, (match, name) => {
329
+ if (name === undefined || resolving.has(name))
330
+ return match;
331
+ const definition = variables.get(name);
332
+ if (definition === undefined)
333
+ return match;
334
+ resolving.add(name);
335
+ const resolved = resolvePreviewValue(definition, variables, resolving);
336
+ resolving.delete(name);
337
+ return resolved;
338
+ });
339
+ }
300
340
  function buildPreset(tokens, scan) {
301
341
  const breakpoints = {};
302
342
  const tokenTokens = [];
@@ -362,11 +402,16 @@ function buildTree(tokens, category) {
362
402
  // src/project.ts
363
403
  var DEFAULT_EXT = "{js,jsx,ts,tsx,mdx}";
364
404
  async function createPandatailProject(opts) {
405
+ const project = await resolvePandatailConfig(opts);
406
+ const compiler = createCompilerFromSnapshot(createConfigSnapshot(project.config));
407
+ return { compiler, ...project };
408
+ }
409
+ async function resolvePandatailConfig(opts, preview = false) {
365
410
  const cwd = resolve4(opts.cwd ?? process.cwd());
366
411
  const cssPath = resolve4(cwd, opts.css);
367
412
  if (!existsSync2(cssPath))
368
413
  throw new Error(`pandatail: CSS entry not found: ${cssPath}`);
369
- const tw = await loadTailwind({ cssPath });
414
+ const tw = await loadTailwind({ cssPath }, preview);
370
415
  const dependencies = [...tw.scan.files];
371
416
  let user = {};
372
417
  if (typeof opts.config === "string") {
@@ -417,9 +462,7 @@ async function createPandatailProject(opts) {
417
462
  finalOverrides
418
463
  ]);
419
464
  const config = applyConfigDefaults(merged, cwd);
420
- const compiler = createCompilerFromSnapshot(createConfigSnapshot(config));
421
465
  return {
422
- compiler,
423
466
  config,
424
467
  cwd,
425
468
  outdir: resolve4(cwd, config.outdir ?? "styled-system"),
package/dist/preset.d.ts CHANGED
@@ -30,7 +30,7 @@ export interface LoadedTailwind {
30
30
  * `@import`, `@theme` and `@plugin` behave exactly as they do in Tailwind) and
31
31
  * project it into Panda.
32
32
  */
33
- export declare function loadTailwind(opts: TailwindPresetOptions): Promise<LoadedTailwind>;
33
+ export declare function loadTailwind(opts: TailwindPresetOptions, preview?: boolean): Promise<LoadedTailwind>;
34
34
  /**
35
35
  * Build a PandaCSS preset whose token layer references the CSS custom
36
36
  * properties that Tailwind v4 emits from the user's `@theme` blocks, and whose
package/dist/project.d.ts CHANGED
@@ -56,6 +56,13 @@ export interface PandatailProject {
56
56
  * `panda.config.ts` required.
57
57
  */
58
58
  export declare function createPandatailProject(opts: PandatailOptions): Promise<PandatailProject>;
59
+ export declare function resolvePandatailConfig(opts: PandatailOptions, preview?: boolean): Promise<{
60
+ config: AnyConfig;
61
+ cwd: string;
62
+ outdir: string;
63
+ dependencies: string[];
64
+ warnings: string[];
65
+ }>;
59
66
  export interface BuildResult {
60
67
  files: string[];
61
68
  artifacts: number;
package/dist/scanCss.d.ts CHANGED
@@ -27,4 +27,4 @@ export interface ScanCssOptions {
27
27
  * `tailwindcss` are skipped: they carry no project-specific `@source`s or
28
28
  * variants).
29
29
  */
30
- export declare function scanCss(opts: ScanCssOptions): CssScan;
30
+ export declare function scanCss(opts: ScanCssOptions, rootVariables?: Map<string, string>): CssScan;
@@ -0,0 +1,8 @@
1
+ import { type PandatailOptions } from "./project";
2
+ export declare function studioConfig(options: PandatailOptions): Promise<{
3
+ dependencies: any[];
4
+ }>;
5
+ export declare function runPandatailStudio(options: PandatailOptions, { port, noOpen }: {
6
+ port?: string;
7
+ noOpen?: boolean;
8
+ }): Promise<number>;
package/dist/studio.js ADDED
@@ -0,0 +1,580 @@
1
+ // src/studio.ts
2
+ import { spawn } from "node:child_process";
3
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
+ import { createRequire as createRequire2 } from "node:module";
5
+ import { constants, tmpdir } from "node:os";
6
+ import { dirname as dirname4, join, resolve as resolve5 } from "node:path";
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";
26
+
27
+ // 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
+ function deriveTokenPath(rest) {
50
+ const lastDash = rest.lastIndexOf("-");
51
+ if (lastDash > 0) {
52
+ const after = rest.slice(lastDash + 1);
53
+ if (/^\d+$/.test(after)) {
54
+ return [rest.slice(0, lastDash), after];
55
+ }
56
+ }
57
+ return [rest];
58
+ }
59
+ function matchNamespace(themeKey) {
60
+ if (!themeKey.startsWith("--"))
61
+ return null;
62
+ const stripped = themeKey.slice(2);
63
+ if (stripped.includes("--"))
64
+ return null;
65
+ for (const mapping of TAILWIND_NAMESPACES) {
66
+ if (stripped === mapping.prefix) {
67
+ return { mapping, rest: "DEFAULT" };
68
+ }
69
+ const withDash = `${mapping.prefix}-`;
70
+ if (stripped.startsWith(withDash)) {
71
+ return { mapping, rest: stripped.slice(withDash.length) };
72
+ }
73
+ }
74
+ return null;
75
+ }
76
+
77
+ // 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
+ function synthesiseDerivedTokens(hasSpacingBase) {
128
+ const out = [];
129
+ if (hasSpacingBase) {
130
+ pushNumericScale(out);
131
+ }
132
+ pushNamed(out);
133
+ return out;
134
+ }
135
+ function pushNumericScale(out) {
136
+ for (const step of TAILWIND_NUMERIC_STEPS) {
137
+ const name = String(step);
138
+ const value = `calc(var(--spacing) * ${name})`;
139
+ const cssVar = `--spacing-${name.replace(".", "_")}`;
140
+ out.push({ cssVar, value, category: "spacing", path: [name] });
141
+ out.push({ cssVar, value, category: "sizes", path: [name] });
142
+ out.push({ cssVar, value, category: "lineHeights", path: [name] });
143
+ }
144
+ }
145
+ function pushNamed(out) {
146
+ for (const [name, value] of Object.entries(NAMED_SIZES)) {
147
+ out.push({
148
+ cssVar: `--sizes-${name.replace(".", "_")}`,
149
+ value,
150
+ category: "sizes",
151
+ path: [name]
152
+ });
153
+ }
154
+ for (const [name, value] of Object.entries(NAMED_RADII)) {
155
+ out.push({
156
+ cssVar: `--radii-${name}`,
157
+ value,
158
+ category: "radii",
159
+ path: [name]
160
+ });
161
+ }
162
+ }
163
+
164
+ // src/extract.ts
165
+ async function extractTokens(opts) {
166
+ return tokensFromTheme(await loadThemeEntries(opts));
167
+ }
168
+ async function loadThemeEntries(opts) {
169
+ const base = resolve(opts.base ?? process.cwd());
170
+ const ds = await __unstable__loadDesignSystem(opts.css, { base });
171
+ const themeEntries = new Map;
172
+ for (const [key, entry] of ds.theme.entries())
173
+ themeEntries.set(key, entry.value);
174
+ return themeEntries;
175
+ }
176
+ function tokensFromTheme(themeEntries) {
177
+ const out = [];
178
+ for (const [key, rawValue] of themeEntries) {
179
+ const matched = matchNamespace(key);
180
+ if (!matched)
181
+ continue;
182
+ if (matched.rest === "DEFAULT")
183
+ continue;
184
+ out.push({
185
+ cssVar: key,
186
+ value: matched.mapping.category === "breakpoints" ? rawValue : `var(${key})`,
187
+ category: matched.mapping.category,
188
+ path: deriveTokenPath(matched.rest)
189
+ });
190
+ }
191
+ out.push(...synthesiseDerivedTokens(themeEntries.has("--spacing")));
192
+ return out;
193
+ }
194
+ async function extractTokensFromFile(path) {
195
+ const css = await readFile(path, "utf8");
196
+ return extractTokens({ css, base: dirname(resolve(path)) });
197
+ }
198
+
199
+ // src/scanCss.ts
200
+ import postcss from "postcss";
201
+ import { existsSync, readFileSync } from "node:fs";
202
+ import { dirname as dirname2, resolve as resolve2 } from "node:path";
203
+ function scanCss(opts, rootVariables) {
204
+ const out = {
205
+ sources: [],
206
+ excludes: [],
207
+ conditions: {},
208
+ warnings: [],
209
+ files: opts.file ? [opts.file] : []
210
+ };
211
+ walk(opts.css, opts.base, out, new Set(opts.file ? [opts.file] : []), rootVariables);
212
+ return out;
213
+ }
214
+ function walk(css, base, out, seen, rootVariables) {
215
+ let root;
216
+ try {
217
+ root = postcss.parse(css);
218
+ } catch (e) {
219
+ out.warnings.push(`could not parse CSS in ${base}: ${e.message}`);
220
+ return;
221
+ }
222
+ root.walk((rule) => {
223
+ if (rule.type === "rule" && rootVariables)
224
+ collectRootVariables(rule, rootVariables);
225
+ if (rule.type !== "atrule")
226
+ return;
227
+ switch (rule.name) {
228
+ case "import": {
229
+ const id = quoted(rule.params) ?? urlTarget(rule.params);
230
+ if (!id || !id.startsWith("."))
231
+ return;
232
+ const path = resolve2(base, id);
233
+ if (seen.has(path) || !existsSync(path))
234
+ return;
235
+ seen.add(path);
236
+ out.files.push(path);
237
+ walk(readFileSync(path, "utf8"), dirname2(path), out, seen, rootVariables);
238
+ return;
239
+ }
240
+ case "source":
241
+ return handleSource(rule, base, out);
242
+ case "custom-variant":
243
+ return handleCustomVariant(rule, out);
244
+ }
245
+ });
246
+ }
247
+ function collectRootVariables(rule, variables) {
248
+ let parent = rule.parent;
249
+ while (parent?.type === "atrule" && parent.name === "layer")
250
+ parent = parent.parent;
251
+ if (parent?.type !== "root" || !rule.selectors.includes(":root"))
252
+ return;
253
+ for (const node of rule.nodes) {
254
+ if (node.type === "decl" && node.prop.startsWith("--"))
255
+ variables.set(node.prop, node.value);
256
+ }
257
+ }
258
+ function handleSource(rule, base, out) {
259
+ const params = rule.params.trim();
260
+ if (params.startsWith("inline(") || params.startsWith("not inline(")) {
261
+ out.warnings.push(`@source ${params}: inline sources have no Panda equivalent`);
262
+ return;
263
+ }
264
+ const isNot = /^not\s/.test(params);
265
+ const target = quoted(isNot ? params.replace(/^not\s+/, "") : params);
266
+ if (!target)
267
+ return;
268
+ (isNot ? out.excludes : out.sources).push(resolve2(base, target));
269
+ }
270
+ function handleCustomVariant(rule, out) {
271
+ const params = rule.params.trim();
272
+ const name = /^([\w-]+)/.exec(params)?.[1];
273
+ if (!name)
274
+ return;
275
+ if (!rule.nodes) {
276
+ const m = /^[\w-]+\s*\(([\s\S]+)\)$/.exec(params);
277
+ if (m)
278
+ out.conditions[name] = m[1].trim();
279
+ else
280
+ out.warnings.push(`@custom-variant ${name}: unrecognised form`);
281
+ return;
282
+ }
283
+ const body = rule.nodes.filter((n) => n.type !== "comment");
284
+ const only = body.length === 1 ? body[0] : undefined;
285
+ if (only?.type === "atrule" && only.name !== "slot" && isSlotOnly(only)) {
286
+ out.conditions[name] = `@${only.name} ${only.params}`.trim();
287
+ return;
288
+ }
289
+ if (only?.type === "rule" && isSlotOnly(only)) {
290
+ out.conditions[name] = only.selector;
291
+ return;
292
+ }
293
+ out.warnings.push(`@custom-variant ${name}: block form is too complex to map to a Panda condition`);
294
+ }
295
+ function isSlotOnly(node) {
296
+ const kids = (node.nodes ?? []).filter((n) => n.type !== "comment");
297
+ return kids.length === 1 && kids[0].type === "atrule" && kids[0].name === "slot";
298
+ }
299
+ function quoted(params) {
300
+ return /^\s*["']([^"']+)["']/.exec(params)?.[1] ?? null;
301
+ }
302
+ function urlTarget(params) {
303
+ return /^\s*url\(\s*["']?([^"')]+)["']?\s*\)/.exec(params)?.[1] ?? null;
304
+ }
305
+
306
+ // src/preset.ts
307
+ async function loadTailwind(opts, preview = false) {
308
+ let css;
309
+ let base;
310
+ let file;
311
+ if (opts.css != null) {
312
+ css = opts.css;
313
+ base = opts.base ?? process.cwd();
314
+ } else if (opts.cssPath != null) {
315
+ file = resolve3(opts.cssPath);
316
+ css = await readFile2(file, "utf8");
317
+ base = dirname3(file);
318
+ } else {
319
+ throw new Error("pandatail: provide either `css` or `cssPath`");
320
+ }
321
+ const theme = await loadThemeEntries({ css, base });
322
+ const tokens = tokensFromTheme(theme);
323
+ const variables = preview ? new Map(theme) : undefined;
324
+ const scan = scanCss({ css, base, file }, variables);
325
+ const presetTokens = variables ? tokens.map((token) => ({
326
+ ...token,
327
+ value: resolvePreviewValue(token.value, variables)
328
+ })) : tokens;
329
+ return { preset: buildPreset(presetTokens, scan), scan, tokens };
330
+ }
331
+ async function tailwindPreset(opts) {
332
+ return (await loadTailwind(opts)).preset;
333
+ }
334
+ function resolvePreviewValue(value, variables, resolving = new Set) {
335
+ return value.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|(?<![\w-])var\(\s*(--[\w-]+)\s*\)/gi, (match, name) => {
336
+ if (name === undefined || resolving.has(name))
337
+ return match;
338
+ const definition = variables.get(name);
339
+ if (definition === undefined)
340
+ return match;
341
+ resolving.add(name);
342
+ const resolved = resolvePreviewValue(definition, variables, resolving);
343
+ resolving.delete(name);
344
+ return resolved;
345
+ });
346
+ }
347
+ function buildPreset(tokens, scan) {
348
+ const breakpoints = {};
349
+ const tokenTokens = [];
350
+ for (const t of tokens) {
351
+ if (t.category === "breakpoints") {
352
+ breakpoints[t.path.join("-")] = t.value;
353
+ } else {
354
+ tokenTokens.push(t);
355
+ }
356
+ }
357
+ const tokensByCategory = groupByCategory(tokenTokens);
358
+ const theme = {};
359
+ for (const [category, list] of Object.entries(tokensByCategory)) {
360
+ theme[category] = buildTree(list, category);
361
+ }
362
+ const preset = definePreset({
363
+ name: "tailwind",
364
+ theme: {
365
+ tokens: theme,
366
+ breakpoints
367
+ }
368
+ });
369
+ if (scan && Object.keys(scan.conditions).length > 0) {
370
+ preset.conditions = { extend: scan.conditions };
371
+ }
372
+ return preset;
373
+ }
374
+ function groupByCategory(tokens) {
375
+ const out = {};
376
+ for (const t of tokens) {
377
+ (out[t.category] ??= []).push(t);
378
+ }
379
+ return out;
380
+ }
381
+ function buildTree(tokens, category) {
382
+ const root = {};
383
+ for (const t of tokens) {
384
+ let cursor = root;
385
+ for (let i = 0;i < t.path.length - 1; i++) {
386
+ const seg = t.path[i];
387
+ const next = cursor[seg];
388
+ if (next && "value" in next) {
389
+ throw new Error(`pandatail: token path collision in '${category}' at ` + `'${t.path.slice(0, i + 1).join(".")}': ` + `'${t.path.join(".")}' nests under a token that is already a leaf.`);
390
+ }
391
+ if (!next) {
392
+ const fresh = {};
393
+ cursor[seg] = fresh;
394
+ cursor = fresh;
395
+ } else {
396
+ cursor = next;
397
+ }
398
+ }
399
+ const leaf = t.path[t.path.length - 1];
400
+ const existing = cursor[leaf];
401
+ if (existing && !("value" in existing)) {
402
+ throw new Error(`pandatail: token path collision in '${category}' at ` + `'${t.path.join(".")}': a leaf token clashes with an existing group.`);
403
+ }
404
+ cursor[leaf] = { value: t.value };
405
+ }
406
+ return root;
407
+ }
408
+
409
+ // src/project.ts
410
+ var DEFAULT_EXT = "{js,jsx,ts,tsx,mdx}";
411
+ async function createPandatailProject(opts) {
412
+ const project = await resolvePandatailConfig(opts);
413
+ const compiler = createCompilerFromSnapshot(createConfigSnapshot(project.config));
414
+ return { compiler, ...project };
415
+ }
416
+ async function resolvePandatailConfig(opts, preview = false) {
417
+ const cwd = resolve4(opts.cwd ?? process.cwd());
418
+ const cssPath = resolve4(cwd, opts.css);
419
+ if (!existsSync2(cssPath))
420
+ throw new Error(`pandatail: CSS entry not found: ${cssPath}`);
421
+ const tw = await loadTailwind({ cssPath }, preview);
422
+ const dependencies = [...tw.scan.files];
423
+ let user = {};
424
+ if (typeof opts.config === "string") {
425
+ const file = resolve4(cwd, opts.config);
426
+ const bundled = await bundleConfig(file, cwd);
427
+ user = bundled.config;
428
+ dependencies.push(file, ...bundled.dependencies);
429
+ } else if (opts.config) {
430
+ user = opts.config;
431
+ }
432
+ const { presets: userPresetList, ...userRest } = user;
433
+ const userPresets = await resolvePresets(userPresetList, cwd);
434
+ const include = opts.include ?? unique([
435
+ ...userRest.include ?? [`./src/**/*.${DEFAULT_EXT}`],
436
+ ...tw.scan.sources.map((p) => sourceToGlob(p, cwd))
437
+ ]);
438
+ const exclude = opts.exclude ?? unique([
439
+ ...userRest.exclude ?? [],
440
+ ...tw.scan.excludes.map((p) => sourceToGlob(p, cwd))
441
+ ]);
442
+ const defaults = {
443
+ cwd,
444
+ preflight: false,
445
+ jsxFramework: "react",
446
+ jsxStyleProps: "all",
447
+ outdir: "styled-system"
448
+ };
449
+ const finalOverrides = { include, exclude, cwd };
450
+ for (const key of [
451
+ "outdir",
452
+ "jsxFramework",
453
+ "jsxStyleProps",
454
+ "preflight",
455
+ "importMap",
456
+ "prefix",
457
+ "hash",
458
+ "minify"
459
+ ]) {
460
+ if (opts[key] !== undefined)
461
+ finalOverrides[key] = opts[key];
462
+ }
463
+ const merged = mergeConfigs([
464
+ defaults,
465
+ presetBase,
466
+ ...userPresets,
467
+ tw.preset,
468
+ userRest,
469
+ finalOverrides
470
+ ]);
471
+ const config = applyConfigDefaults(merged, cwd);
472
+ return {
473
+ config,
474
+ cwd,
475
+ outdir: resolve4(cwd, config.outdir ?? "styled-system"),
476
+ dependencies: unique(dependencies),
477
+ warnings: tw.scan.warnings
478
+ };
479
+ }
480
+ function buildProject(project, opts = {}) {
481
+ const { compiler, cwd, outdir } = project;
482
+ const files = compiler.scan();
483
+ compiler.parseFiles(files);
484
+ let artifacts = 0;
485
+ if (opts.codegen !== false) {
486
+ artifacts = compiler.writeArtifacts({ outdir, cwd }).length;
487
+ }
488
+ let cssPath;
489
+ if (opts.outfile !== false) {
490
+ const outfile = opts.outfile ?? relative(cwd, resolve4(outdir, "styles.css"));
491
+ cssPath = compiler.writeCss({ outfile, cwd }).path;
492
+ }
493
+ return { files, artifacts, cssPath, diagnostics: compiler.diagnostics() };
494
+ }
495
+ function sourceToGlob(path, cwd) {
496
+ const rel = relative(cwd, path).split("\\").join("/");
497
+ const p = rel.startsWith(".") ? rel : `./${rel}`;
498
+ const hasGlob = /[*?{}\[\]]/.test(p);
499
+ if (!hasGlob && existsSync2(path) && statSync(path).isDirectory()) {
500
+ return `${p}/**/*.${DEFAULT_EXT}`;
501
+ }
502
+ return p;
503
+ }
504
+ async function resolvePresets(list, cwd) {
505
+ const out = [];
506
+ for (const entry of list ?? []) {
507
+ const preset = await loadPreset(entry, cwd);
508
+ const { presets, ...rest } = preset;
509
+ out.push(...await resolvePresets(presets, cwd), rest);
510
+ }
511
+ return out;
512
+ }
513
+ async function loadPreset(entry, cwd) {
514
+ const value = await entry;
515
+ if (typeof value !== "string")
516
+ return value;
517
+ const req = createRequire(resolve4(cwd, "__pandatail_anchor__"));
518
+ let mod;
519
+ try {
520
+ mod = await import(req.resolve(value));
521
+ } catch {
522
+ mod = await import(value);
523
+ }
524
+ return mod.default ?? mod.preset ?? mod;
525
+ }
526
+ function unique(xs) {
527
+ return [...new Set(xs)];
528
+ }
529
+
530
+ // src/studio.ts
531
+ async function studioConfig(options) {
532
+ const { config, dependencies, warnings } = await resolvePandatailConfig(options, true);
533
+ for (const warning of warnings)
534
+ console.warn(`pandatail: warning: ${warning}`);
535
+ return { ...config, dependencies: [...config.dependencies ?? [], ...dependencies] };
536
+ }
537
+ async function runPandatailStudio(options, { port, noOpen }) {
538
+ const require2 = createRequire2(import.meta.url);
539
+ const manifestPath = require2.resolve("@pandacss/dev/package.json");
540
+ const { bin, version } = require2(manifestPath);
541
+ const [major, minor] = version.split(".");
542
+ if (major !== "2" || !(Number(minor) >= 4)) {
543
+ throw new Error(`studio requires Panda CSS 2.4 or newer (found ${version})`);
544
+ }
545
+ const cwd = resolve5(options.cwd ?? process.cwd());
546
+ const dir = mkdtempSync(join(tmpdir(), "pandatail-studio-"));
547
+ try {
548
+ const config = join(dir, "panda.config.mjs");
549
+ const entry = new URL(import.meta.url.endsWith(".ts") ? "./studio.ts" : "./studio.js", import.meta.url);
550
+ writeFileSync(config, `
551
+ const { studioConfig } = await import(new URL(${JSON.stringify(entry.href)}).href);
552
+ export default await studioConfig(${JSON.stringify({ ...options, cwd })});
553
+ `);
554
+ const args = [resolve5(dirname4(manifestPath), bin.panda), "studio", "--cwd", cwd, "--config", config];
555
+ if (port !== undefined)
556
+ args.push(`--port=${port}`);
557
+ if (noOpen)
558
+ args.push("--no-open");
559
+ const child = spawn(process.execPath, args, { stdio: "inherit" });
560
+ const interrupt = () => child.kill("SIGINT");
561
+ const terminate = () => child.kill("SIGTERM");
562
+ process.on("SIGINT", interrupt);
563
+ process.on("SIGTERM", terminate);
564
+ try {
565
+ return await new Promise((done, reject) => {
566
+ child.once("error", reject);
567
+ child.once("exit", (code, signal) => done(code ?? (signal ? 128 + constants.signals[signal] : 1)));
568
+ });
569
+ } finally {
570
+ process.off("SIGINT", interrupt);
571
+ process.off("SIGTERM", terminate);
572
+ }
573
+ } finally {
574
+ rmSync(dir, { recursive: true, force: true });
575
+ }
576
+ }
577
+ export {
578
+ runPandatailStudio,
579
+ studioConfig
580
+ };
package/dist/vite.js CHANGED
@@ -160,11 +160,17 @@ function pushNamed(out) {
160
160
 
161
161
  // src/extract.ts
162
162
  async function extractTokens(opts) {
163
+ return tokensFromTheme(await loadThemeEntries(opts));
164
+ }
165
+ async function loadThemeEntries(opts) {
163
166
  const base = resolve(opts.base ?? process.cwd());
164
167
  const ds = await __unstable__loadDesignSystem(opts.css, { base });
165
168
  const themeEntries = new Map;
166
169
  for (const [key, entry] of ds.theme.entries())
167
170
  themeEntries.set(key, entry.value);
171
+ return themeEntries;
172
+ }
173
+ function tokensFromTheme(themeEntries) {
168
174
  const out = [];
169
175
  for (const [key, rawValue] of themeEntries) {
170
176
  const matched = matchNamespace(key);
@@ -191,7 +197,7 @@ async function extractTokensFromFile(path) {
191
197
  import postcss from "postcss";
192
198
  import { existsSync, readFileSync } from "node:fs";
193
199
  import { dirname as dirname2, resolve as resolve2 } from "node:path";
194
- function scanCss(opts) {
200
+ function scanCss(opts, rootVariables) {
195
201
  const out = {
196
202
  sources: [],
197
203
  excludes: [],
@@ -199,10 +205,10 @@ function scanCss(opts) {
199
205
  warnings: [],
200
206
  files: opts.file ? [opts.file] : []
201
207
  };
202
- walk(opts.css, opts.base, out, new Set(opts.file ? [opts.file] : []));
208
+ walk(opts.css, opts.base, out, new Set(opts.file ? [opts.file] : []), rootVariables);
203
209
  return out;
204
210
  }
205
- function walk(css, base, out, seen) {
211
+ function walk(css, base, out, seen, rootVariables) {
206
212
  let root;
207
213
  try {
208
214
  root = postcss.parse(css);
@@ -210,7 +216,11 @@ function walk(css, base, out, seen) {
210
216
  out.warnings.push(`could not parse CSS in ${base}: ${e.message}`);
211
217
  return;
212
218
  }
213
- root.walkAtRules((rule) => {
219
+ root.walk((rule) => {
220
+ if (rule.type === "rule" && rootVariables)
221
+ collectRootVariables(rule, rootVariables);
222
+ if (rule.type !== "atrule")
223
+ return;
214
224
  switch (rule.name) {
215
225
  case "import": {
216
226
  const id = quoted(rule.params) ?? urlTarget(rule.params);
@@ -221,7 +231,7 @@ function walk(css, base, out, seen) {
221
231
  return;
222
232
  seen.add(path);
223
233
  out.files.push(path);
224
- walk(readFileSync(path, "utf8"), dirname2(path), out, seen);
234
+ walk(readFileSync(path, "utf8"), dirname2(path), out, seen, rootVariables);
225
235
  return;
226
236
  }
227
237
  case "source":
@@ -231,6 +241,17 @@ function walk(css, base, out, seen) {
231
241
  }
232
242
  });
233
243
  }
244
+ function collectRootVariables(rule, variables) {
245
+ let parent = rule.parent;
246
+ while (parent?.type === "atrule" && parent.name === "layer")
247
+ parent = parent.parent;
248
+ if (parent?.type !== "root" || !rule.selectors.includes(":root"))
249
+ return;
250
+ for (const node of rule.nodes) {
251
+ if (node.type === "decl" && node.prop.startsWith("--"))
252
+ variables.set(node.prop, node.value);
253
+ }
254
+ }
234
255
  function handleSource(rule, base, out) {
235
256
  const params = rule.params.trim();
236
257
  if (params.startsWith("inline(") || params.startsWith("not inline(")) {
@@ -280,7 +301,7 @@ function urlTarget(params) {
280
301
  }
281
302
 
282
303
  // src/preset.ts
283
- async function loadTailwind(opts) {
304
+ async function loadTailwind(opts, preview = false) {
284
305
  let css;
285
306
  let base;
286
307
  let file;
@@ -294,13 +315,32 @@ async function loadTailwind(opts) {
294
315
  } else {
295
316
  throw new Error("pandatail: provide either `css` or `cssPath`");
296
317
  }
297
- const tokens = await extractTokens({ css, base });
298
- const scan = scanCss({ css, base, file });
299
- return { preset: buildPreset(tokens, scan), scan, tokens };
318
+ const theme = await loadThemeEntries({ css, base });
319
+ const tokens = tokensFromTheme(theme);
320
+ const variables = preview ? new Map(theme) : undefined;
321
+ const scan = scanCss({ css, base, file }, variables);
322
+ const presetTokens = variables ? tokens.map((token) => ({
323
+ ...token,
324
+ value: resolvePreviewValue(token.value, variables)
325
+ })) : tokens;
326
+ return { preset: buildPreset(presetTokens, scan), scan, tokens };
300
327
  }
301
328
  async function tailwindPreset(opts) {
302
329
  return (await loadTailwind(opts)).preset;
303
330
  }
331
+ function resolvePreviewValue(value, variables, resolving = new Set) {
332
+ return value.replace(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|(?<![\w-])var\(\s*(--[\w-]+)\s*\)/gi, (match, name) => {
333
+ if (name === undefined || resolving.has(name))
334
+ return match;
335
+ const definition = variables.get(name);
336
+ if (definition === undefined)
337
+ return match;
338
+ resolving.add(name);
339
+ const resolved = resolvePreviewValue(definition, variables, resolving);
340
+ resolving.delete(name);
341
+ return resolved;
342
+ });
343
+ }
304
344
  function buildPreset(tokens, scan) {
305
345
  const breakpoints = {};
306
346
  const tokenTokens = [];
@@ -366,11 +406,16 @@ function buildTree(tokens, category) {
366
406
  // src/project.ts
367
407
  var DEFAULT_EXT = "{js,jsx,ts,tsx,mdx}";
368
408
  async function createPandatailProject(opts) {
409
+ const project = await resolvePandatailConfig(opts);
410
+ const compiler = createCompilerFromSnapshot(createConfigSnapshot(project.config));
411
+ return { compiler, ...project };
412
+ }
413
+ async function resolvePandatailConfig(opts, preview = false) {
369
414
  const cwd = resolve4(opts.cwd ?? process.cwd());
370
415
  const cssPath = resolve4(cwd, opts.css);
371
416
  if (!existsSync2(cssPath))
372
417
  throw new Error(`pandatail: CSS entry not found: ${cssPath}`);
373
- const tw = await loadTailwind({ cssPath });
418
+ const tw = await loadTailwind({ cssPath }, preview);
374
419
  const dependencies = [...tw.scan.files];
375
420
  let user = {};
376
421
  if (typeof opts.config === "string") {
@@ -421,9 +466,7 @@ async function createPandatailProject(opts) {
421
466
  finalOverrides
422
467
  ]);
423
468
  const config = applyConfigDefaults(merged, cwd);
424
- const compiler = createCompilerFromSnapshot(createConfigSnapshot(config));
425
469
  return {
426
- compiler,
427
470
  config,
428
471
  cwd,
429
472
  outdir: resolve4(cwd, config.outdir ?? "styled-system"),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dmisdm/pandatail",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Run PandaCSS from a Tailwind v4 stylesheet. Your @theme becomes typed Panda style props, with no panda.config.ts required.",
5
5
  "license": "MIT",
6
6
  "keywords": [
@@ -40,7 +40,7 @@
40
40
  ],
41
41
  "scripts": {
42
42
  "build": "bun run clean && bun run build:js && bun run build:types",
43
- "build:js": "bun build src/index.ts src/cli.ts src/vite.ts --outdir dist --target node --format esm --external \"@pandacss/*\" --external @tailwindcss/node --external postcss --external vite",
43
+ "build:js": "bun build src/index.ts src/cli.ts src/vite.ts src/studio.ts --outdir dist --target node --format esm --external \"@pandacss/*\" --external @tailwindcss/node --external postcss --external vite",
44
44
  "build:types": "tsc --project tsconfig.build.json",
45
45
  "clean": "rm -rf dist",
46
46
  "test": "bun test",