@pandacss/compiler 2.0.0-beta.9 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,6 @@ import {
4
4
  assertProjectCallbacks,
5
5
  BuildInfo as BuildInfo2,
6
6
  DesignSystem as DesignSystem2,
7
- getTokenCategoryValues,
8
7
  inspectFile,
9
8
  inspectFiles,
10
9
  mergeCallbacks,
@@ -14,10 +13,10 @@ import {
14
13
 
15
14
  // src/callbacks.ts
16
15
  import {
17
- createPatternHelpers,
18
- createTransformArgs,
16
+ createTransformHelpers,
19
17
  getPatternDefaultValueRefsByTransformId,
20
- mergePatternDefaultValues
18
+ mergePatternDefaultValues,
19
+ PATTERN_HELPERS
21
20
  } from "@pandacss/compiler-shared";
22
21
  function registerCallbacks(project, callbacks, hooks, tokenDictionary) {
23
22
  const utilityTransforms = callbacks["utility.transform"];
@@ -27,6 +26,7 @@ function registerCallbacks(project, callbacks, hooks, tokenDictionary) {
27
26
  const config = project.config();
28
27
  const patternDefaultValues = callbacks["pattern.defaultValues"];
29
28
  const patternDefaultValueRefs = config && patternDefaultValues ? getPatternDefaultValueRefsByTransformId(config) : /* @__PURE__ */ new Map();
29
+ const { token, utils } = createTransformHelpers(tokenDictionary);
30
30
  if (hasPatternTransforms && !project.registerPatternTransform) {
31
31
  throw new Error("Native project does not support pattern.transform callbacks");
32
32
  }
@@ -37,7 +37,7 @@ function registerCallbacks(project, callbacks, hooks, tokenDictionary) {
37
37
  project.registerPatternTransform(id, (props) => {
38
38
  const input = props;
39
39
  const nextProps = defaultValue ? mergePatternDefaultValues(defaultValue(input), input) : input;
40
- return callback(nextProps, createPatternHelpers());
40
+ return callback(nextProps, PATTERN_HELPERS);
41
41
  });
42
42
  }
43
43
  }
@@ -47,7 +47,7 @@ function registerCallbacks(project, callbacks, hooks, tokenDictionary) {
47
47
  if (project.registerUtilityTransform && utilityTransforms) {
48
48
  for (const [id, callback] of Object.entries(utilityTransforms)) {
49
49
  project.registerUtilityTransform(id, (resolved, original) => {
50
- return callback(resolved, createTransformArgs(original, tokenDictionary));
50
+ return callback(resolved, { raw: original, token, utils });
51
51
  });
52
52
  }
53
53
  }
@@ -159,11 +159,17 @@ var FallbackCompiler = class _FallbackCompiler {
159
159
  removeFile() {
160
160
  return false;
161
161
  }
162
+ affectedFiles() {
163
+ return [];
164
+ }
162
165
  clear() {
163
166
  }
164
167
  scan() {
165
168
  return [];
166
169
  }
170
+ designSystemImportSelections() {
171
+ return [];
172
+ }
167
173
  realpath(path) {
168
174
  return path;
169
175
  }
@@ -196,6 +202,9 @@ var FallbackCompiler = class _FallbackCompiler {
196
202
  hasLayerDeclaration() {
197
203
  return false;
198
204
  }
205
+ stripLayerOrderStatements(css) {
206
+ return css;
207
+ }
199
208
  spec() {
200
209
  return {
201
210
  conditions: { keys: [], breakpoints: [], containers: [] },
@@ -222,7 +231,7 @@ var FallbackCompiler = class _FallbackCompiler {
222
231
  bailed: false,
223
232
  diagnostics: [],
224
233
  dependencies: [],
225
- helper: { needsCx: false, needsCva: false, needsSva: false }
234
+ helper: { needsCx: false, needsAttachRecipe: false, needsMemoRecipe: false }
226
235
  };
227
236
  }
228
237
  inspectFile(input) {
@@ -250,7 +259,7 @@ var FallbackCompiler = class _FallbackCompiler {
250
259
  return emptyWriteCssResult(options.outfile);
251
260
  }
252
261
  writeSplitCss(options) {
253
- return emptyWriteFilesResult(options.outdir ?? "");
262
+ return emptyWriteSplitCssResult(options.outdir ?? "");
254
263
  }
255
264
  isEmpty() {
256
265
  return true;
@@ -285,8 +294,11 @@ var FallbackCompiler = class _FallbackCompiler {
285
294
  getLayerCss(_options) {
286
295
  return emptyCompileOutput();
287
296
  }
297
+ getKeyframeCss(_options) {
298
+ return emptyCompileOutput();
299
+ }
288
300
  getSplitCss(_options) {
289
- return [];
301
+ return { files: [], diagnostics: [] };
290
302
  }
291
303
  buildInfo = fallbackBuildInfo;
292
304
  designSystem = fallbackDesignSystem;
@@ -353,21 +365,20 @@ function emptyWriteCssResult(path) {
353
365
  ...emptyCompileOutput()
354
366
  };
355
367
  }
356
- function emptyWriteFilesResult(root) {
368
+ function emptyWriteSplitCssResult(root) {
357
369
  return {
358
370
  root,
359
371
  paths: [],
360
- files: []
372
+ files: [],
373
+ diagnostics: []
361
374
  };
362
375
  }
363
376
 
364
377
  // src/load-binary.ts
365
- import { execFileSync } from "child_process";
366
- import { existsSync, mkdirSync, readFileSync, rmSync } from "fs";
367
- import { createRequire } from "module";
368
- import { dirname, join } from "path";
369
- import { fileURLToPath } from "url";
370
- var bindingUrl = new URL("../binding.cjs", import.meta.url);
378
+ import { execFileSync } from "node:child_process";
379
+ import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
380
+ import { createRequire } from "node:module";
381
+ import { dirname, join } from "node:path";
371
382
  var webContainerWasiPackage = "@pandacss/compiler-wasm32-wasi";
372
383
  function loadNativeBinding() {
373
384
  const bindingPath = resolveBindingPath();
@@ -380,13 +391,21 @@ function loadNativeBinding() {
380
391
  return loadWebContainerBinding(require2, bindingPath, error);
381
392
  }
382
393
  }
383
- function resolveBindingPath() {
384
- if (bindingUrl.protocol === "file:") {
385
- const bindingPath = fileURLToPath(bindingUrl);
394
+ function resolveBindingPath(referrer = import.meta.url) {
395
+ const packageRoot = resolvePackageRoot(referrer);
396
+ if (packageRoot) {
397
+ const bindingPath = join(packageRoot, "binding.cjs");
386
398
  if (existsSync(bindingPath)) return bindingPath;
387
399
  }
388
400
  return fallbackBindingPaths().find((path) => existsSync(path));
389
401
  }
402
+ function resolvePackageRoot(referrer) {
403
+ try {
404
+ return dirname(createRequire(referrer).resolve("@pandacss/compiler/package.json"));
405
+ } catch {
406
+ return void 0;
407
+ }
408
+ }
390
409
  function fallbackBindingPaths() {
391
410
  const cwd = process.cwd();
392
411
  const paths = [join(cwd, "packages/compiler/binding.cjs")];
@@ -460,9 +479,11 @@ import {
460
479
  BaseDriver,
461
480
  collectParseDiagnostics,
462
481
  diagnosticsPass,
482
+ fromCodegenPrepareArtifacts,
463
483
  normalizeDiagnostics
464
484
  } from "@pandacss/compiler-shared";
465
485
  import {
486
+ buildCodegenOverlay,
466
487
  compilePreset,
467
488
  defaultImportMap,
468
489
  diffConfig,
@@ -477,35 +498,144 @@ import {
477
498
  toPosixRelative,
478
499
  toRelativeKey
479
500
  } from "@pandacss/config";
480
-
481
- // src/tooling/create-project.ts
482
- import { defaultConfig } from "@pandacss/compiler-shared";
483
- import { loadConfig } from "@pandacss/config";
501
+ import { statSync } from "node:fs";
502
+ import { dirname as dirname2, resolve as resolvePath } from "node:path";
484
503
 
485
504
  // src/design-system.ts
486
505
  import "@pandacss/compiler-shared";
487
- import { readPandaVersion } from "@pandacss/config";
488
- function hydrateDesignSystem(compiler, chain, consumerTokenPaths = []) {
506
+ import {
507
+ collectArtifactConflicts,
508
+ readPandaVersion
509
+ } from "@pandacss/config";
510
+ function artifactConflictDiagnostics(metadata) {
511
+ return collectArtifactConflicts(metadata).flatMap((conflict) => [
512
+ ...conflict.recipes.map((name) => artifactConflict("Recipe", name, conflict.name)),
513
+ ...conflict.patterns.map((name) => artifactConflict("Pattern", name, conflict.name))
514
+ ]);
515
+ }
516
+ function artifactConflict(kind, name, designSystem) {
517
+ return {
518
+ code: "design_system_artifact_conflict",
519
+ severity: "warning",
520
+ category: "designSystem",
521
+ message: `${kind} ${JSON.stringify(name)} is defined by both ${JSON.stringify(designSystem)} and this config; your definition is merged over the design system's.`
522
+ };
523
+ }
524
+ function hydrateDesignSystem(compiler, options) {
525
+ const { chain, consumerTokenPaths = [], treeshake, importSelections } = options;
489
526
  if (!chain || chain.length === 0) {
490
- return [];
527
+ return { diagnostics: [], treeshakeKey: "" };
491
528
  }
492
529
  const pandaVersion = readPandaVersion();
493
530
  const diagnostics = [];
494
- for (const ds of chain) {
495
- diagnostics.push(...hydrateLevel(compiler, ds, pandaVersion, consumerTokenPaths));
531
+ const appSelections = treeshake ? importSelections ?? collectImportSelections(compiler, chain) : void 0;
532
+ const selections = appSelections && withDependencyImports(compiler, chain, appSelections);
533
+ for (let i = 0; i < chain.length; i++) {
534
+ const ds = chain[i];
535
+ const imports = selections ? selections[i] ?? void 0 : void 0;
536
+ diagnostics.push(...hydrateLevel(compiler, ds, pandaVersion, consumerTokenPaths, imports));
496
537
  }
497
- return diagnostics;
538
+ return {
539
+ diagnostics,
540
+ treeshakeKey: treeshakeKeyFromSelections(chain, appSelections)
541
+ };
498
542
  }
499
- function hydrateLevel(compiler, ds, pandaVersion, consumerTokenPaths) {
543
+ var ALL_MODULES = { kind: "all" };
544
+ var NO_MODULES = { kind: "none" };
545
+ function withDependencyImports(compiler, chain, appSelections) {
546
+ const selections = appSelections.map(selectionFromScan);
547
+ for (let i = chain.length - 1; i > 0; i--) {
548
+ const selected = selections[i];
549
+ if (selected.kind === "none") continue;
550
+ const info = readBuildInfo(compiler, chain[i]);
551
+ for (let ancestorIndex = 0; ancestorIndex < i; ancestorIndex++) {
552
+ const imported = info ? compiler.designSystem.dependencyImports(info, selectionToImports(selected), chain[ancestorIndex].name) : void 0;
553
+ selections[ancestorIndex] = mergeSelection(selections[ancestorIndex], selectionFromImports(imported));
554
+ }
555
+ }
556
+ return selections.map(selectionToScan);
557
+ }
558
+ function selectionFromScan(selection) {
559
+ if (selection == null) return ALL_MODULES;
560
+ return selection.length === 0 ? NO_MODULES : { kind: "names", names: selection };
561
+ }
562
+ function selectionFromImports(imports) {
563
+ if (imports === void 0) return ALL_MODULES;
564
+ return imports.length === 0 ? NO_MODULES : { kind: "names", names: imports };
565
+ }
566
+ function selectionToImports(selection) {
567
+ if (selection.kind === "all") return void 0;
568
+ return selection.kind === "none" ? [] : selection.names;
569
+ }
570
+ function selectionToScan(selection) {
571
+ if (selection.kind === "all") return null;
572
+ return selection.kind === "none" ? [] : selection.names;
573
+ }
574
+ function mergeSelection(current, added) {
575
+ if (current.kind === "all" || added.kind === "all") return ALL_MODULES;
576
+ if (current.kind === "none") return added;
577
+ if (added.kind === "none") return current;
578
+ return { kind: "names", names: [.../* @__PURE__ */ new Set([...current.names, ...added.names])] };
579
+ }
580
+ function readBuildInfo(compiler, ds) {
581
+ if (ds.optionMismatch?.length) return void 0;
582
+ try {
583
+ const content = compiler.fs.readFile(ds.buildInfoPath);
584
+ if (content == null) return void 0;
585
+ const info = JSON.parse(content);
586
+ return compiler.buildInfo.validate(info).ok ? info : void 0;
587
+ } catch {
588
+ return void 0;
589
+ }
590
+ }
591
+ function designSystemDependencies(chain) {
592
+ return (chain ?? []).map((ds) => ({
593
+ name: ds.name,
594
+ packageRoots: getPackageRoots(ds),
595
+ excludeModules: getExcludedModules(ds)
596
+ }));
597
+ }
598
+ function collectImportSelections(compiler, chain) {
599
+ return compiler.designSystemImportSelections(
600
+ chain.map((ds) => ({
601
+ packageRoots: getPackageRoots(ds),
602
+ excludeModules: getExcludedModules(ds)
603
+ }))
604
+ );
605
+ }
606
+ function treeshakeKeyFromSelections(chain, selections) {
607
+ if (!selections?.length) return "";
608
+ return chain.map((ds, i) => `${ds.name}:${JSON.stringify(selections[i] ?? null)}`).join("|");
609
+ }
610
+ var STYLED_SYSTEM_SUBPATHS = ["css", "recipes", "patterns", "jsx", "tokens"];
611
+ function getPackageRoots(ds) {
612
+ return [...new Set([ds.specifier, ds.name].filter((value) => Boolean(value)))];
613
+ }
614
+ function getExcludedModules(ds) {
615
+ const excluded = /* @__PURE__ */ new Set();
616
+ for (const root of getPackageRoots(ds)) {
617
+ for (const sub of STYLED_SYSTEM_SUBPATHS) {
618
+ excluded.add(`${root}/${sub}`);
619
+ }
620
+ }
621
+ const map = ds.importMap;
622
+ if (map) {
623
+ for (const value of [map.css, map.recipes, map.patterns, map.jsx, map.tokens]) {
624
+ if (typeof value === "string" && value.length > 0) excluded.add(value);
625
+ }
626
+ }
627
+ return [...excluded];
628
+ }
629
+ function hydrateLevel(compiler, ds, pandaVersion, consumerTokenPaths, imports) {
500
630
  const compat = compiler.designSystem.validate(ds.manifest, { pandaVersion });
501
631
  if (!compat.ok) {
502
632
  throw incompatibleManifestError(compiler, ds, compat.reason, pandaVersion);
503
633
  }
504
- const diagnostics = hydrateArtifacts(compiler, ds, pandaVersion);
634
+ const diagnostics = hydrateArtifacts(compiler, ds, pandaVersion, imports);
505
635
  diagnostics.push(...tokenConflictDiagnostics(ds, consumerTokenPaths));
506
636
  return diagnostics;
507
637
  }
508
- function hydrateArtifacts(compiler, ds, pandaVersion) {
638
+ function hydrateArtifacts(compiler, ds, pandaVersion, imports) {
509
639
  if (ds.optionMismatch && ds.optionMismatch.length > 0) {
510
640
  const diagnostic = recoverFromSources(
511
641
  compiler,
@@ -530,7 +660,11 @@ function hydrateArtifacts(compiler, ds, pandaVersion) {
530
660
  );
531
661
  return [diagnostic];
532
662
  }
533
- const result = compiler.designSystem.load(ds.manifest, { buildInfo, pandaVersion });
663
+ const result = compiler.designSystem.load(ds.manifest, {
664
+ buildInfo,
665
+ pandaVersion,
666
+ ...imports !== void 0 ? { imports } : {}
667
+ });
534
668
  if (!result.ok) {
535
669
  const issue = result.reason === "schemaVersion" ? {
536
670
  kind: "schemaVersion",
@@ -560,7 +694,8 @@ function extractFallbackSources(compiler, ds) {
560
694
  if (ds.files.length === 0) {
561
695
  return [];
562
696
  }
563
- return compiler.scan({ include: ds.files, cwd: compiler.path.dirname(ds.manifestPath) });
697
+ const filesCwd = compiler.path.resolve(compiler.path.join([compiler.path.dirname(ds.manifestPath), ".."]));
698
+ return compiler.scan({ include: ds.files, cwd: filesCwd });
564
699
  }
565
700
  function buildInfoDiagnostic(ds, issue, sourceCount, severity) {
566
701
  const reason = buildInfoIssueMessage(issue);
@@ -571,7 +706,7 @@ function buildInfoDiagnostic(ds, issue, sourceCount, severity) {
571
706
  category: "designSystem",
572
707
  file: ds.buildInfoPath,
573
708
  message: `${JSON.stringify(ds.name)} build info ${reason}.${outcome}`,
574
- help: [`Run \`panda lib\` in ${JSON.stringify(ds.name)} to rebuild panda.buildinfo.json.`]
709
+ help: [`Run \`panda lib\` in ${JSON.stringify(ds.name)} to rebuild panda/buildinfo.json.`]
575
710
  };
576
711
  }
577
712
  function buildInfoIssueMessage(issue) {
@@ -623,7 +758,7 @@ function incompatibleManifestError(compiler, ds, reason, pandaVersion) {
623
758
  severity: "error",
624
759
  category: "designSystem",
625
760
  file: ds.manifestPath,
626
- message: `${JSON.stringify(ds.name)} panda.lib.json uses schemaVersion ${ds.manifest.schemaVersion}; expected ${compiler.designSystem.schemaVersion}.`,
761
+ message: `${JSON.stringify(ds.name)} panda/lib.json uses schemaVersion ${ds.manifest.schemaVersion}; expected ${compiler.designSystem.schemaVersion}.`,
627
762
  help: [`Upgrade ${JSON.stringify(ds.name)}, or rebuild it with a compatible version of Panda.`]
628
763
  });
629
764
  }
@@ -650,23 +785,40 @@ function errorMessage(error) {
650
785
  }
651
786
 
652
787
  // src/tooling/create-project.ts
788
+ import { defaultConfig } from "@pandacss/compiler-shared";
789
+ import {
790
+ collectExportMissingDiagnostics,
791
+ collectNameCollisionDiagnostics,
792
+ loadConfig
793
+ } from "@pandacss/config";
794
+ function treeshakeDesignSystemEnabled(config) {
795
+ const optimize = config.optimize;
796
+ return optimize?.treeshakeDesignSystem === true;
797
+ }
653
798
  function createProjectFromLoadedConfig(loaded) {
654
799
  const compiler = createCompilerFromSnapshot({
655
800
  config: loaded.config,
656
801
  callbacks: loaded.callbacks,
657
802
  hooks: loaded.hooks
658
803
  });
659
- const designSystemDiagnostics = hydrateDesignSystem(
660
- compiler,
661
- loaded.metadata?.designSystem,
662
- loaded.metadata?.userTokenPaths ?? []
663
- );
804
+ const hydrated = hydrateDesignSystem(compiler, {
805
+ chain: loaded.metadata?.designSystem,
806
+ consumerTokenPaths: loaded.metadata?.userTokenPaths ?? [],
807
+ treeshake: treeshakeDesignSystemEnabled(loaded.config)
808
+ });
809
+ const designSystemDiagnostics = [
810
+ ...hydrated.diagnostics,
811
+ ...artifactConflictDiagnostics(loaded.metadata),
812
+ ...collectExportMissingDiagnostics(loaded.metadata),
813
+ ...collectNameCollisionDiagnostics(loaded.metadata)
814
+ ];
664
815
  return {
665
816
  compiler,
666
817
  configPath: loaded.path,
667
818
  dependencies: loaded.dependencies,
668
819
  outdir: loaded.config.outdir ?? defaultConfig.outdir,
669
- designSystemDiagnostics
820
+ designSystemDiagnostics,
821
+ designSystemTreeshakeKey: hydrated.treeshakeKey
670
822
  };
671
823
  }
672
824
 
@@ -674,7 +826,7 @@ function createProjectFromLoadedConfig(loaded) {
674
826
  var DEFAULT_DESIGN_SYSTEM_LIB_OUTDIR = "dist";
675
827
  var DEFAULT_DESIGN_SYSTEM_LIB_FILES = ["./**/*.{js,mjs}"];
676
828
  async function createNodeDriver(options) {
677
- const loaded = await loadConfig2({ cwd: options.cwd, file: options.configPath });
829
+ const loaded = await loadConfig2({ cwd: options.cwd, file: options.configPath, trackSources: options.trackSources });
678
830
  if (options.include?.length) applyIncludeOverride(loaded, options.cwd, options.include);
679
831
  return new NodeDriver(options, loaded);
680
832
  }
@@ -695,17 +847,35 @@ var NodeDriver = class extends BaseDriver {
695
847
  #designSystemPreset;
696
848
  #designSystemArtifactSnapshot;
697
849
  #designSystemWatchTargets;
850
+ #codegenOverlay;
851
+ #codegenOverlayResolved = false;
852
+ #designSystemTreeshakeKey;
853
+ #configFilePaths;
854
+ #designSystemFileKinds;
855
+ #sourceGeneration = 0;
856
+ #treeshakeSyncedGeneration = -1;
698
857
  constructor(options, loaded) {
699
858
  const built = createProjectFromLoadedConfig(loaded);
700
859
  super(built.compiler);
701
860
  this.#options = options;
702
861
  this.#loaded = loaded;
703
862
  this.#designSystemDiagnostics = built.designSystemDiagnostics;
704
- this.#designSystemArtifactSnapshot = designSystemArtifactSnapshot(this.compiler, loaded);
863
+ this.#designSystemArtifactSnapshot = designSystemArtifactSnapshot(loaded);
864
+ this.#designSystemTreeshakeKey = built.designSystemTreeshakeKey ?? "";
705
865
  }
706
866
  get designSystemDiagnostics() {
707
867
  return this.#designSystemDiagnostics;
708
868
  }
869
+ configSources() {
870
+ return this.#loaded.metadata?.sources;
871
+ }
872
+ codegenOverlay() {
873
+ if (!this.#codegenOverlayResolved) {
874
+ this.#codegenOverlay = buildCodegenOverlay(this.#loaded.metadata);
875
+ this.#codegenOverlayResolved = true;
876
+ }
877
+ return this.#codegenOverlay;
878
+ }
709
879
  get config() {
710
880
  return this.#loaded.config;
711
881
  }
@@ -717,9 +887,10 @@ var NodeDriver = class extends BaseDriver {
717
887
  }
718
888
  designSystemWatchTargets() {
719
889
  return this.#designSystemWatchTargets ??= (this.#loaded.metadata?.designSystem ?? []).map((ds) => {
720
- const base = this.compiler.path.dirname(ds.manifestPath);
721
- const presetPath = realpathIfExists(this.compiler, this.compiler.path.resolve(ds.manifest.preset, base));
722
- const sourceFiles = ds.files.length > 0 ? this.compiler.scan({ include: ds.files, cwd: base }).map((file) => realpathIfExists(this.compiler, file)) : [];
890
+ const manifestDir = this.compiler.path.dirname(ds.manifestPath);
891
+ const presetPath = realpathIfExists(this.compiler, this.compiler.path.resolve(ds.manifest.preset, manifestDir));
892
+ const filesCwd = designSystemFilesCwd(this.compiler, ds.manifestPath);
893
+ const sourceFiles = ds.files.length > 0 ? this.compiler.scan({ include: ds.files, cwd: filesCwd }).map((file) => realpathIfExists(this.compiler, file)) : [];
723
894
  return {
724
895
  name: ds.name,
725
896
  manifestPath: realpathIfExists(this.compiler, ds.manifestPath),
@@ -730,18 +901,20 @@ var NodeDriver = class extends BaseDriver {
730
901
  });
731
902
  }
732
903
  isDesignSystemFile(file) {
733
- const target = this.compiler.path.realpath(file);
904
+ const kinds = this.#designSystemFileKinds ??= this.buildDesignSystemFileKinds();
905
+ return kinds.get(this.compiler.path.realpath(file)) ?? false;
906
+ }
907
+ buildDesignSystemFileKinds() {
908
+ const kinds = /* @__PURE__ */ new Map();
734
909
  for (const watchTarget of this.#designSystemWatchTargets ?? this.designSystemWatchTargets()) {
735
- if ([watchTarget.manifestPath, watchTarget.buildInfoPath, watchTarget.presetPath].some(
736
- (path) => this.compiler.path.realpath(path) === target
737
- )) {
738
- return "artifact";
910
+ for (const path of [watchTarget.manifestPath, watchTarget.buildInfoPath, watchTarget.presetPath]) {
911
+ kinds.set(this.compiler.path.realpath(path), "artifact");
739
912
  }
740
- if (watchTarget.sourceFiles.some((path) => this.compiler.path.realpath(path) === target)) {
741
- return "source";
913
+ for (const path of watchTarget.sourceFiles) {
914
+ kinds.set(this.compiler.path.realpath(path), "source");
742
915
  }
743
916
  }
744
- return false;
917
+ return kinds;
745
918
  }
746
919
  async syncDesignSystemFileChange(change) {
747
920
  const kind = this.isDesignSystemFile(change.path);
@@ -750,7 +923,7 @@ var NodeDriver = class extends BaseDriver {
750
923
  if (diff.hasChanged) this.parseFiles();
751
924
  return diff.hasChanged;
752
925
  }
753
- if (kind === "source") return this.applyChange(change);
926
+ if (kind === "source") return this.applySourceChange(change, "design-system");
754
927
  return false;
755
928
  }
756
929
  syncDesignSystemSources() {
@@ -768,10 +941,14 @@ var NodeDriver = class extends BaseDriver {
768
941
  return this.applyChanges(changes);
769
942
  }
770
943
  async reload() {
771
- const next = await loadConfig2({ cwd: this.#options.cwd, file: this.#options.configPath });
944
+ const next = await loadConfig2({
945
+ cwd: this.#options.cwd,
946
+ file: this.#options.configPath,
947
+ trackSources: this.#options.trackSources
948
+ });
772
949
  if (this.#options.include?.length) applyIncludeOverride(next, this.#options.cwd, this.#options.include);
773
950
  const diff = diffConfig(this.#loaded, next);
774
- const nextDesignSystemArtifactSnapshot = designSystemArtifactSnapshot(this.compiler, next);
951
+ const nextDesignSystemArtifactSnapshot = designSystemArtifactSnapshot(next);
775
952
  const designSystemArtifactsChanged = this.#designSystemArtifactSnapshot !== nextDesignSystemArtifactSnapshot;
776
953
  if (diff.hasChanged || designSystemArtifactsChanged) {
777
954
  this.#loaded = next;
@@ -781,30 +958,64 @@ var NodeDriver = class extends BaseDriver {
781
958
  this.#designSystemPreset = void 0;
782
959
  this.#designSystemArtifactSnapshot = nextDesignSystemArtifactSnapshot;
783
960
  this.#designSystemWatchTargets = void 0;
961
+ this.#codegenOverlay = void 0;
962
+ this.#codegenOverlayResolved = false;
963
+ this.#designSystemTreeshakeKey = built.designSystemTreeshakeKey ?? "";
964
+ this.#configFilePaths = void 0;
965
+ this.#designSystemFileKinds = void 0;
966
+ this.#sourceGeneration++;
967
+ this.#treeshakeSyncedGeneration = -1;
784
968
  }
785
969
  return designSystemArtifactsChanged && !diff.hasChanged ? { ...diff, hasChanged: true } : diff;
786
970
  }
971
+ /** Re-hydrate when treeshake import set changes. */
972
+ syncDesignSystemTreeShake() {
973
+ if (!treeshakeDesignSystemEnabled(this.#loaded.config)) return false;
974
+ const chain = this.#loaded.metadata?.designSystem;
975
+ if (!chain?.length) return false;
976
+ if (this.#treeshakeSyncedGeneration === this.#sourceGeneration) return false;
977
+ const selections = collectImportSelections(this.compiler, chain);
978
+ const nextKey = treeshakeKeyFromSelections(chain, selections);
979
+ this.#treeshakeSyncedGeneration = this.#sourceGeneration;
980
+ if (nextKey === this.#designSystemTreeshakeKey) return false;
981
+ const hydrated = hydrateDesignSystem(this.compiler, {
982
+ chain,
983
+ consumerTokenPaths: this.#loaded.metadata?.userTokenPaths ?? [],
984
+ treeshake: true,
985
+ importSelections: selections
986
+ });
987
+ this.#designSystemDiagnostics = hydrated.diagnostics;
988
+ this.#designSystemTreeshakeKey = hydrated.treeshakeKey;
989
+ return true;
990
+ }
991
+ prepareCssOutput() {
992
+ this.syncDesignSystemTreeShake();
993
+ }
787
994
  applyChange(change) {
788
- if (change.kind === "unlink") {
789
- return this.compiler.removeFile(change.path);
790
- }
791
- if (change.kind === "change") {
792
- if (change.content == null) {
793
- if (this.compiler.refreshFile(change.path)) return true;
794
- this.compiler.parseFile(change.path);
795
- return true;
796
- }
797
- if (this.compiler.refreshFileSource(change.path, change.content)) return true;
798
- this.compiler.parseFileSource(change.path, change.content);
799
- return true;
800
- }
801
- if (change.content == null) {
802
- this.compiler.parseFile(change.path);
803
- return true;
804
- }
805
- this.compiler.parseFileSource(change.path, change.content);
995
+ return this.applySourceChange(change, "project");
996
+ }
997
+ applySourceChange(change, admission) {
998
+ const changed = this.trackSourceChange(change, this.admitSourceChange(change, admission));
999
+ const refreshed = this.refreshAffectedFiles();
1000
+ return this.recordSourceChange(changed || refreshed);
1001
+ }
1002
+ /** Known files always refresh; unknown project paths must match the source globs. */
1003
+ admitSourceChange(change, admission) {
1004
+ if (change.kind === "unlink") return this.compiler.removeFile(change.path);
1005
+ const refreshed = change.content == null ? this.compiler.refreshFile(change.path) : this.compiler.refreshFileSource(change.path, change.content);
1006
+ if (refreshed) return true;
1007
+ if (admission === "project" && !this.isSourceFile(change.path)) return false;
1008
+ if (change.content == null) this.compiler.parseFile(change.path);
1009
+ else this.compiler.parseFileSource(change.path, change.content);
806
1010
  return true;
807
1011
  }
1012
+ recordSourceChange(applied) {
1013
+ if (applied) {
1014
+ this.#sourceGeneration++;
1015
+ this.#treeshakeSyncedGeneration = -1;
1016
+ }
1017
+ return applied;
1018
+ }
808
1019
  getOutdir(outdir) {
809
1020
  return this.compiler.path.resolve(this.getConfiguredOutdir(outdir));
810
1021
  }
@@ -893,7 +1104,8 @@ var NodeDriver = class extends BaseDriver {
893
1104
  }
894
1105
  }
895
1106
  codegenWithPrepareHooks(hooks, outdir, cwd, options) {
896
- let artifacts = this.compiler.generateArtifacts(toGenerateArtifactOptions(options));
1107
+ const overlay = this.codegenOverlay();
1108
+ let artifacts = this.compiler.generateArtifacts({ ...toGenerateArtifactOptions(options), overlay });
897
1109
  for (const entry of hooks) {
898
1110
  const handler = resolveHookHandler(entry.value, "codegen:prepare");
899
1111
  const next = handler({ artifacts, outdir, cwd });
@@ -901,24 +1113,31 @@ var NodeDriver = class extends BaseDriver {
901
1113
  if (!Array.isArray(next)) {
902
1114
  throw new Error("Invalid codegen:prepare hook result. Expected an artifact array or undefined.");
903
1115
  }
904
- artifacts = next;
1116
+ artifacts = fromCodegenPrepareArtifacts(next);
905
1117
  }
906
1118
  }
907
1119
  return this.compiler.writeArtifacts({
908
1120
  outdir,
909
1121
  cwd,
910
1122
  forceImportExtension: options?.forceImportExtension,
911
- artifacts
1123
+ artifacts,
1124
+ overlay
912
1125
  });
913
1126
  }
914
1127
  isConfigFile(file) {
915
- const target = this.compiler.path.realpath(file);
916
- const configPath = this.compiler.path.realpath(this.#loaded.path);
917
- if (configPath === target) return true;
918
- return this.#loaded.dependencies.some((dependency) => {
1128
+ const paths = this.#configFilePaths ??= this.buildConfigFilePaths();
1129
+ return paths.has(this.compiler.path.realpath(file));
1130
+ }
1131
+ buildConfigFilePaths() {
1132
+ const paths = /* @__PURE__ */ new Set();
1133
+ if (this.#loaded.path) {
1134
+ paths.add(this.compiler.path.realpath(this.#loaded.path));
1135
+ }
1136
+ for (const dependency of this.#loaded.dependencies) {
919
1137
  const dependencyPath = this.compiler.path.resolve(dependency, this.#options.cwd);
920
- return this.compiler.path.realpath(dependencyPath) === target;
921
- });
1138
+ paths.add(this.compiler.path.realpath(dependencyPath));
1139
+ }
1140
+ return paths;
922
1141
  }
923
1142
  parseDesignSystemLib() {
924
1143
  const parsed = this.parseFiles();
@@ -941,10 +1160,14 @@ var NodeDriver = class extends BaseDriver {
941
1160
  const pandaRange = resolvePublishedPandaRange(options.panda ?? identity.pandaPeer, readPandaVersion2());
942
1161
  const outdir = options.outdir ?? DEFAULT_DESIGN_SYSTEM_LIB_OUTDIR;
943
1162
  const outRoot = this.compiler.path.resolve(outdir);
944
- const manifestPath = this.compiler.path.join([outRoot, "panda.lib.json"]);
945
- const buildInfoPath = this.compiler.path.join([outRoot, "panda.buildinfo.json"]);
946
- const presetPath = this.compiler.path.join([outRoot, "panda.preset.mjs"]);
947
- const info = this.compiler.buildInfo.create({ panda: pandaRange });
1163
+ const pandaDir = this.compiler.path.join([outRoot, "panda"]);
1164
+ const manifestPath = this.compiler.path.join([pandaDir, "lib.json"]);
1165
+ const buildInfoPath = this.compiler.path.join([pandaDir, "buildinfo.json"]);
1166
+ const presetPath = this.compiler.path.join([pandaDir, "preset.mjs"]);
1167
+ const info = this.compiler.buildInfo.create({
1168
+ panda: pandaRange,
1169
+ designSystemDependencies: designSystemDependencies(this.#loaded.metadata?.designSystem)
1170
+ });
948
1171
  const buildInfo = this.compiler.buildInfo.normalize(info, {
949
1172
  mapModuleKey: (key) => toRelativeKey(key, this.#options.cwd)
950
1173
  });
@@ -952,18 +1175,28 @@ var NodeDriver = class extends BaseDriver {
952
1175
  explicit: options.files,
953
1176
  compiler: this.compiler,
954
1177
  cwd: this.#options.cwd,
955
- outRoot,
1178
+ filesBase: outRoot,
956
1179
  buildInfo,
957
1180
  packageRoot: this.compiler.path.dirname(identity.packagePath),
958
1181
  publishFiles: identity.publishFiles,
959
1182
  packageName: identity.name
960
1183
  });
1184
+ const { spec, diagnostics: specDiagnostics } = resolvePublishableSpec({
1185
+ spec: options.spec,
1186
+ compiler: this.compiler,
1187
+ outRoot,
1188
+ pandaDir,
1189
+ packageRoot: this.compiler.path.dirname(identity.packagePath),
1190
+ publishFiles: identity.publishFiles,
1191
+ packageName: identity.name
1192
+ });
961
1193
  const manifest = this.compiler.designSystem.create({
962
1194
  name: identity.name,
963
1195
  version: identity.version,
964
1196
  panda: pandaRange,
965
- preset: "./panda.preset.mjs",
966
- buildInfo: "./panda.buildinfo.json",
1197
+ preset: "./preset.mjs",
1198
+ buildInfo: "./buildinfo.json",
1199
+ spec,
967
1200
  importMap: defaultImportMap(identity.name),
968
1201
  designSystem: typeof this.config.designSystem === "string" ? this.config.designSystem : void 0,
969
1202
  files: libFiles
@@ -976,18 +1209,18 @@ var NodeDriver = class extends BaseDriver {
976
1209
  id: "design-system-lib",
977
1210
  files: [
978
1211
  {
979
- path: "panda.lib.json",
1212
+ path: "panda/lib.json",
980
1213
  code: `${JSON.stringify(manifest, null, 2)}
981
1214
  `,
982
1215
  dependencies: []
983
1216
  },
984
1217
  {
985
- path: "panda.buildinfo.json",
1218
+ path: "panda/buildinfo.json",
986
1219
  code: JSON.stringify(buildInfo, null, options.minify ? 0 : 2),
987
1220
  dependencies: []
988
1221
  },
989
1222
  {
990
- path: "panda.preset.mjs",
1223
+ path: "panda/preset.mjs",
991
1224
  code: preset.code,
992
1225
  dependencies: []
993
1226
  }
@@ -996,8 +1229,8 @@ var NodeDriver = class extends BaseDriver {
996
1229
  ]
997
1230
  });
998
1231
  const { changed: exportsChanged, conflicts } = syncPackageExports(this.compiler, identity.packagePath, {
999
- manifestPath,
1000
- presetPath
1232
+ pandaDir,
1233
+ styledDir: this.getOutdir()
1001
1234
  });
1002
1235
  return {
1003
1236
  manifestPath,
@@ -1005,19 +1238,46 @@ var NodeDriver = class extends BaseDriver {
1005
1238
  presetPath,
1006
1239
  exportsChanged,
1007
1240
  parsedFileCount: parsed.parsedFileCount,
1008
- diagnostics: [...parsed.diagnostics, ...filesDiagnostics, ...exportConflictDiagnostics(identity.name, conflicts)]
1241
+ diagnostics: [
1242
+ ...parsed.diagnostics,
1243
+ ...filesDiagnostics,
1244
+ ...specDiagnostics,
1245
+ ...exportConflictDiagnostics(identity.name, conflicts)
1246
+ ]
1009
1247
  };
1010
1248
  }
1011
1249
  };
1250
+ function resolvePublishableSpec(options) {
1251
+ if (!options.spec) return { diagnostics: [] };
1252
+ const absolute = options.compiler.path.resolve(options.spec);
1253
+ const { unpublished } = filterPublishableLibFiles({
1254
+ files: [toPosixRelative(options.outRoot, absolute)],
1255
+ packageRoot: options.packageRoot,
1256
+ outRoot: options.outRoot,
1257
+ publishFiles: options.publishFiles
1258
+ });
1259
+ if (unpublished.length > 0) {
1260
+ return { diagnostics: [specNotPublishableDiagnostic(options.packageName, unpublished[0])] };
1261
+ }
1262
+ return { spec: toPosixRelative(options.pandaDir, absolute), diagnostics: [] };
1263
+ }
1264
+ function specNotPublishableDiagnostic(name, spec) {
1265
+ return {
1266
+ code: "design_system_spec_not_publishable",
1267
+ severity: "warning",
1268
+ category: "designSystem",
1269
+ message: `\`panda lib\` left the spec out of ${JSON.stringify(name)}'s manifest because package.json \`"files"\` would not publish ${JSON.stringify(spec)}. A bare \`--spec\` writes it beside preset.mjs, inside what you publish.`
1270
+ };
1271
+ }
1012
1272
  function resolveDesignSystemLibFiles(options) {
1013
1273
  if (options.explicit) {
1014
1274
  return { files: options.explicit, diagnostics: [] };
1015
1275
  }
1016
- const inferred = inferDesignSystemLibFiles(options.compiler, options.cwd, options.outRoot, options.buildInfo);
1276
+ const inferred = inferDesignSystemLibFiles(options.compiler, options.cwd, options.filesBase, options.buildInfo);
1017
1277
  const { files, unpublished } = filterPublishableLibFiles({
1018
1278
  files: inferred,
1019
1279
  packageRoot: options.packageRoot,
1020
- outRoot: options.outRoot,
1280
+ outRoot: options.filesBase,
1021
1281
  publishFiles: options.publishFiles
1022
1282
  });
1023
1283
  if (unpublished.length === 0) {
@@ -1072,11 +1332,15 @@ function skippedDesignSystemLib(parsed) {
1072
1332
  diagnostics: parsed.diagnostics
1073
1333
  };
1074
1334
  }
1335
+ var STYLED_SYSTEM_CATEGORIES = ["css", "recipes", "patterns", "jsx", "tokens", "helpers"];
1336
+ var DEEP_IMPORT_CATEGORIES = /* @__PURE__ */ new Set(["css", "recipes", "patterns", "jsx"]);
1337
+ var SINGLE_FILE_CATEGORIES = /* @__PURE__ */ new Set(["helpers"]);
1075
1338
  function syncPackageExports(compiler, packagePath, paths) {
1076
1339
  const base = compiler.path.dirname(packagePath);
1340
+ const pandaGlob = `${toPosixRelative(base, paths.pandaDir)}/*`;
1077
1341
  const entries = {
1078
- "./panda.lib.json": toPosixRelative(base, paths.manifestPath),
1079
- "./preset": toPosixRelative(base, paths.presetPath)
1342
+ "./panda/*": pandaGlob,
1343
+ ...styledSystemExports(compiler, base, paths.styledDir)
1080
1344
  };
1081
1345
  const packageJson = compiler.fs.readFile(packagePath);
1082
1346
  if (packageJson == null) {
@@ -1096,31 +1360,73 @@ function syncPackageExports(compiler, packagePath, paths) {
1096
1360
  }
1097
1361
  return { changed: result.changed, conflicts: result.conflicts };
1098
1362
  }
1363
+ function styledSystemExports(compiler, base, styledDir) {
1364
+ const rel = (path) => toPosixRelative(base, path);
1365
+ const find = (dir, names) => names.map((name) => compiler.path.join([dir, name])).find((path) => compiler.fs.readFile(path) != null);
1366
+ const entries = {};
1367
+ for (const category of STYLED_SYSTEM_CATEGORIES) {
1368
+ if (SINGLE_FILE_CATEGORIES.has(category)) {
1369
+ const runtime2 = find(styledDir, [`${category}.mjs`, `${category}.js`, `${category}.ts`]);
1370
+ if (!runtime2) continue;
1371
+ const types2 = find(styledDir, [`${category}.d.mts`, `${category}.d.ts`]);
1372
+ entries[`./${category}`] = types2 ? { types: rel(types2), default: rel(runtime2) } : rel(runtime2);
1373
+ continue;
1374
+ }
1375
+ const dir = compiler.path.join([styledDir, category]);
1376
+ const runtime = find(dir, ["index.mjs", "index.js", "index.ts"]);
1377
+ if (!runtime) continue;
1378
+ const types = find(dir, ["index.d.mts", "index.d.ts"]);
1379
+ entries[`./${category}`] = types ? { types: rel(types), default: rel(runtime) } : rel(runtime);
1380
+ if (DEEP_IMPORT_CATEGORIES.has(category)) {
1381
+ const runtimeExt = runtime.endsWith(".mjs") ? "mjs" : runtime.endsWith(".ts") ? "ts" : "js";
1382
+ const runtimeGlob = `${rel(dir)}/*.${runtimeExt}`;
1383
+ const typesGlob = types ? `${rel(dir)}/*.${types.endsWith(".d.mts") ? "d.mts" : "d.ts"}` : void 0;
1384
+ entries[`./${category}/*`] = typesGlob ? { types: typesGlob, default: runtimeGlob } : runtimeGlob;
1385
+ }
1386
+ }
1387
+ return entries;
1388
+ }
1099
1389
  function stabilizePath(cwd, file) {
1100
1390
  const relativePath = toRelativeKey(file, cwd);
1101
1391
  return relativePath && !relativePath.startsWith("..") ? relativePath : file;
1102
1392
  }
1103
- function designSystemArtifactSnapshot(compiler, loaded) {
1393
+ function designSystemArtifactSnapshot(loaded) {
1104
1394
  return JSON.stringify(
1105
- loaded.metadata?.designSystem?.map((ds) => ({
1106
- name: ds.name,
1107
- specifier: ds.specifier,
1108
- manifest: ds.manifest,
1109
- manifestPath: ds.manifestPath,
1110
- buildInfoPath: ds.buildInfoPath,
1111
- buildInfo: compiler.fs.readFile(ds.buildInfoPath) ?? "",
1112
- files: ds.files,
1113
- tokenPaths: ds.tokenPaths
1114
- })) ?? []
1395
+ loaded.metadata?.designSystem?.map((ds) => {
1396
+ const presetPath = resolvePath(dirname2(ds.manifestPath), ds.manifest.preset);
1397
+ return {
1398
+ name: ds.name,
1399
+ specifier: ds.specifier,
1400
+ manifest: ds.manifest,
1401
+ manifestPath: ds.manifestPath,
1402
+ buildInfoPath: ds.buildInfoPath,
1403
+ manifestStamp: diskFileStamp(ds.manifestPath),
1404
+ buildInfoStamp: diskFileStamp(ds.buildInfoPath),
1405
+ presetStamp: diskFileStamp(presetPath),
1406
+ files: ds.files,
1407
+ tokenPaths: ds.tokenPaths
1408
+ };
1409
+ }) ?? []
1115
1410
  );
1116
1411
  }
1412
+ function diskFileStamp(path) {
1413
+ try {
1414
+ const stat = statSync(path);
1415
+ return `${stat.mtimeMs}:${stat.size}`;
1416
+ } catch {
1417
+ return "missing";
1418
+ }
1419
+ }
1117
1420
  function realpathIfExists(compiler, path) {
1118
1421
  return compiler.fs.exists(path) ? compiler.path.realpath(path) : path;
1119
1422
  }
1120
- function inferDesignSystemLibFiles(compiler, cwd, outRoot, buildInfo) {
1423
+ function designSystemFilesCwd(compiler, manifestPath) {
1424
+ return compiler.path.resolve(compiler.path.join([compiler.path.dirname(manifestPath), ".."]));
1425
+ }
1426
+ function inferDesignSystemLibFiles(compiler, cwd, filesBase, buildInfo) {
1121
1427
  const files = Object.keys(buildInfo.modules).filter((key) => !key.startsWith("buildinfo:")).map((key) => {
1122
1428
  const file = compiler.path.resolve(key, cwd);
1123
- return toPosixRelative(outRoot, file);
1429
+ return toPosixRelative(filesBase, file);
1124
1430
  });
1125
1431
  return files.length > 0 ? [...new Set(files)] : DEFAULT_DESIGN_SYSTEM_LIB_FILES;
1126
1432
  }
@@ -1159,15 +1465,27 @@ function getBindingInfo() {
1159
1465
  native: binding !== fallback
1160
1466
  };
1161
1467
  }
1468
+ function assertNativeBinding(callbacks, hooks) {
1469
+ if (binding !== fallback) return;
1470
+ const needed = ["pattern.transform", "utility.transform"].filter(
1471
+ (key) => Object.keys(callbacks[key] ?? {}).length > 0
1472
+ );
1473
+ if (hooks?.["parser:before"]?.length) needed.push("parser:before");
1474
+ if (needed.length === 0) return;
1475
+ throw new Error(
1476
+ `Could not load the native @pandacss/compiler binding for ${process.platform}-${process.arch}, which ${needed.join(", ")} callbacks require. Reinstall your dependencies to fetch the platform package, or open an issue if your platform is unsupported.`
1477
+ );
1478
+ }
1162
1479
  function build(config, callbacks, options) {
1163
1480
  assertProjectCallbacks(config, callbacks);
1164
1481
  assertProjectHooks(options?.hooks, callbacks);
1165
1482
  if (!nativeCompilerFromConfig) {
1166
1483
  throw new Error("createCompiler is not available in this binding");
1167
1484
  }
1485
+ assertNativeBinding(callbacks, options?.hooks);
1168
1486
  const prepared = prepareCompilerConfig(config);
1169
1487
  const compiler = nativeCompilerFromConfig(prepared, toNativeOptions(options), createUtilityValuesCallbacks(callbacks));
1170
- registerCallbacks(compiler, callbacks, options?.hooks, compiler.token_dictionary?.());
1488
+ registerCallbacks(compiler, callbacks, options?.hooks, compiler.tokenDictionary?.());
1171
1489
  attachFileSystem(compiler);
1172
1490
  attachPathSystem(compiler);
1173
1491
  attachBuildInfo(compiler);
@@ -1252,12 +1570,7 @@ function toNativeOptions(options) {
1252
1570
  function createUtilityValuesCallbacks(callbacks) {
1253
1571
  const utilityValues = callbacks["utility.values"];
1254
1572
  if (!utilityValues || Object.keys(utilityValues).length === 0) return void 0;
1255
- return Object.fromEntries(
1256
- Object.entries(utilityValues).map(([id, callback]) => [
1257
- id,
1258
- (tokenDictionary) => callback((category) => getTokenCategoryValues(category, tokenDictionary))
1259
- ])
1260
- );
1573
+ return utilityValues;
1261
1574
  }
1262
1575
 
1263
1576
  export {