@pandacss/node 0.18.3 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -4,17 +4,10 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __getProtoOf = Object.getPrototypeOf;
6
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
- }) : x)(function(x) {
10
- if (typeof require !== "undefined")
11
- return require.apply(this, arguments);
12
- throw Error('Dynamic require of "' + x + '" is not supported');
13
- });
14
7
  var __esm = (fn, res) => function __init() {
15
8
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
16
9
  };
17
- var __commonJS = (cb, mod) => function __require2() {
10
+ var __commonJS = (cb, mod) => function __require() {
18
11
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
12
  };
20
13
  var __copyProps = (to, from, except, desc) => {
@@ -696,7 +689,7 @@ function analyzeTokens(ctx, options = {}) {
696
689
  const chunkFiles = ctx.chunks.getFiles();
697
690
  ctx.config.optimize = true;
698
691
  ctx.config.minify = false;
699
- const css = ctx.getCss({ files: chunkFiles });
692
+ const css2 = ctx.getCss({ files: chunkFiles });
700
693
  ctx.config.minify = true;
701
694
  const minifiedCss = ctx.getCss({ files: chunkFiles });
702
695
  ctx.config.minify = minify;
@@ -711,11 +704,11 @@ function analyzeTokens(ctx, options = {}) {
711
704
  classify: classifyMs
712
705
  },
713
706
  fileSizes: {
714
- lineCount: css.split("\n").length,
715
- normal: filesize(Buffer.byteLength(css, "utf-8")),
707
+ lineCount: css2.split("\n").length,
708
+ normal: filesize(Buffer.byteLength(css2, "utf-8")),
716
709
  minified: filesize(Buffer.byteLength(minifiedCss, "utf-8")),
717
710
  gzip: {
718
- normal: filesize(gzipSizeSync(css)),
711
+ normal: filesize(gzipSizeSync(css2)),
719
712
  minified: filesize(gzipSizeSync(minifiedCss))
720
713
  }
721
714
  }
@@ -757,13 +750,11 @@ var writeAnalyzeJSON = (filePath, result, ctx) => {
757
750
 
758
751
  // src/builder.ts
759
752
  init_esm_shims();
760
- import { getConfigDependencies } from "@pandacss/config";
761
- import { optimizeCss as optimizeCss2, mergeCss as mergeCss2 } from "@pandacss/core";
753
+ import { optimizeCss as optimizeCss2 } from "@pandacss/core";
762
754
  import { ConfigNotFoundError } from "@pandacss/error";
763
- import { logger as logger5 } from "@pandacss/logger";
755
+ import { logger as logger6 } from "@pandacss/logger";
764
756
  import { existsSync } from "fs";
765
757
  import fsExtra2 from "fs-extra";
766
- import { resolve as resolve2 } from "path";
767
758
 
768
759
  // ../../node_modules/.pnpm/p-limit@4.0.0/node_modules/p-limit/index.js
769
760
  init_esm_shims();
@@ -872,17 +863,20 @@ function pLimit(concurrency) {
872
863
  return generator;
873
864
  }
874
865
 
866
+ // src/builder.ts
867
+ import { resolve as resolve2 } from "pathe";
868
+
875
869
  // src/config.ts
876
870
  init_esm_shims();
877
- import { convertTsPathsToRegexes, loadConfigFile } from "@pandacss/config";
871
+ import { convertTsPathsToRegexes, loadConfigFile as loadConfigFile2 } from "@pandacss/config";
878
872
  import { createDebugger, createHooks } from "hookable";
879
873
  import { lookItUpSync } from "look-it-up";
880
874
  import { parse } from "tsconfck";
881
875
 
882
876
  // src/create-context.ts
883
877
  init_esm_shims();
884
- import { createGenerator } from "@pandacss/generator";
885
- import { logger as logger3 } from "@pandacss/logger";
878
+ import { Generator as Generator2 } from "@pandacss/generator";
879
+ import { logger as logger4 } from "@pandacss/logger";
886
880
  import { createProject } from "@pandacss/parser";
887
881
 
888
882
  // src/chunk-engine.ts
@@ -905,10 +899,11 @@ var getChunkEngine = ({
905
899
  format(file) {
906
900
  return path2.relative(config.cwd, file).replaceAll(path2.sep, "__").replace(path2.extname(file), ".css");
907
901
  },
908
- getArtifact(file, css) {
902
+ getArtifact(file, css2) {
909
903
  const fileName = this.format(file);
910
- const newCss = mergeCss(this.readFile(file), css);
904
+ const newCss = mergeCss(this.readFile(file), css2);
911
905
  return {
906
+ id: fileName,
912
907
  dir: paths.chunk,
913
908
  files: [{ file: fileName, code: newCss }]
914
909
  };
@@ -1000,58 +995,200 @@ process.on("uncaughtException", (reason) => {
1000
995
 
1001
996
  // src/output-engine.ts
1002
997
  init_esm_shims();
1003
- var getOutputEngine = ({
1004
- paths,
1005
- runtime: { path: path2, fs }
1006
- }) => ({
998
+ import { logger as logger3 } from "@pandacss/logger";
999
+ var PandaOutputEngine = class {
1000
+ paths;
1001
+ fs;
1002
+ path;
1003
+ constructor({ paths, runtime: { path: path2, fs } }) {
1004
+ this.paths = paths;
1005
+ this.fs = fs;
1006
+ this.path = path2;
1007
+ }
1007
1008
  empty() {
1008
- fs.rmDirSync(path2.join(...paths.root));
1009
- },
1009
+ this.fs.rmDirSync(this.path.join(...this.paths.root));
1010
+ }
1010
1011
  async write(output) {
1011
1012
  if (!output)
1012
1013
  return;
1013
- const { dir = paths.root, files } = output;
1014
- fs.ensureDirSync(path2.join(...dir));
1014
+ const { dir = this.paths.root, files } = output;
1015
+ this.fs.ensureDirSync(this.path.join(...dir));
1015
1016
  return Promise.allSettled(
1016
1017
  files.map(async (artifact) => {
1017
- if (!artifact)
1018
+ if (!artifact?.code)
1018
1019
  return;
1019
1020
  const { file, code } = artifact;
1020
- const absPath = path2.join(...dir, file);
1021
- if (!code)
1022
- return;
1023
- return fs.writeFile(absPath, code);
1021
+ const absPath = this.path.join(...dir, file);
1022
+ logger3.debug("write:file", dir.slice(-1).concat(file).join("/"));
1023
+ return this.fs.writeFile(absPath, code);
1024
1024
  })
1025
1025
  );
1026
1026
  }
1027
- });
1027
+ };
1028
+
1029
+ // src/diff-engine.ts
1030
+ init_esm_shims();
1031
+ import { loadConfigFile } from "@pandacss/config";
1032
+ import "@pandacss/generator";
1033
+ import { dashCase } from "@pandacss/shared";
1034
+ import diff from "microdiff";
1035
+
1036
+ // src/matcher.ts
1037
+ init_esm_shims();
1038
+ function createMatcher(id, patterns) {
1039
+ if (!patterns?.length)
1040
+ return () => void 0;
1041
+ const includePatterns = [];
1042
+ const excludePatterns = [];
1043
+ const deduped = new Set(patterns);
1044
+ deduped.forEach((pattern) => {
1045
+ const regexString = pattern.replace(/\*/g, ".*");
1046
+ if (pattern.startsWith("!")) {
1047
+ excludePatterns.push(regexString.slice(1));
1048
+ } else {
1049
+ includePatterns.push(regexString);
1050
+ }
1051
+ });
1052
+ const include = new RegExp(includePatterns.join("|"));
1053
+ const exclude = new RegExp(excludePatterns.join("|"));
1054
+ return (path2) => {
1055
+ if (excludePatterns.length && exclude.test(path2))
1056
+ return;
1057
+ return include.test(path2) ? id : void 0;
1058
+ };
1059
+ }
1060
+
1061
+ // src/diff-engine.ts
1062
+ var all = ["outdir", "forceConsistentTypeExtension", "outExtension"];
1063
+ var format = ["syntax", "hash", "prefix", "separator"];
1064
+ var tokens = ["utilities", "conditions", "theme.tokens", "theme.semanticTokens", "theme.breakpoints"];
1065
+ var jsx = ["jsxFramework", "jsxFactory", "jsxStyleProps", "syntax"];
1066
+ var css = ["layers", "optimize", "minify"];
1067
+ var common = tokens.concat(jsx, format);
1068
+ var artifactConfigDeps = {
1069
+ helpers: ["syntax", "jsxFramework"],
1070
+ keyframes: ["theme.keyframes", "layers"],
1071
+ "design-tokens": ["layers", "!utilities.*.className"].concat(tokens),
1072
+ types: ["!utilities.*.className"].concat(common),
1073
+ "css-fn": common,
1074
+ cva: ["syntax"],
1075
+ sva: ["syntax"],
1076
+ cx: [],
1077
+ "create-recipe": ["separator", "prefix", "hash"],
1078
+ "recipes-index": ["theme.recipes", "theme.slotRecipes"],
1079
+ recipes: ["theme.recipes", "theme.slotRecipes"],
1080
+ "patterns-index": ["syntax", "patterns"],
1081
+ patterns: ["syntax", "patterns"],
1082
+ "jsx-is-valid-prop": common,
1083
+ "jsx-factory": jsx,
1084
+ "jsx-helpers": jsx,
1085
+ "jsx-patterns": jsx.concat("patterns"),
1086
+ "jsx-patterns-index": jsx.concat("patterns"),
1087
+ "css-index": ["syntax"],
1088
+ "reset.css": ["preflight", "layers"],
1089
+ "global.css": ["globalCss"].concat(css),
1090
+ "static.css": ["staticCss", "theme.breakpoints"].concat(css),
1091
+ "styles.css": tokens.concat(format),
1092
+ "package.json": ["emitPackage"]
1093
+ };
1094
+ var configDeps = {
1095
+ artifacts: artifactConfigDeps
1096
+ };
1097
+ var matchers = {
1098
+ artifacts: Object.keys(configDeps.artifacts).map((key) => {
1099
+ const paths = configDeps.artifacts[key];
1100
+ if (!paths.length)
1101
+ return () => void 0;
1102
+ return createMatcher(key, paths.concat(all));
1103
+ })
1104
+ };
1105
+ var DiffEngine = class {
1106
+ constructor(ctx) {
1107
+ this.ctx = ctx;
1108
+ this.previousConfig = ctx.conf.deserialize();
1109
+ }
1110
+ previousConfig;
1111
+ /**
1112
+ * Reload config from disk and refresh the context
1113
+ */
1114
+ async reloadConfigAndRefreshContext(fn) {
1115
+ const conf = await loadConfigFile({ cwd: this.ctx.config.cwd, file: this.ctx.conf.path });
1116
+ return this.refresh(conf, fn);
1117
+ }
1118
+ /**
1119
+ * Update the context from the refreshed config
1120
+ * then persist the changes on each affected engines
1121
+ * Returns the list of affected artifacts/engines
1122
+ */
1123
+ refresh(conf, fn) {
1124
+ const affected = {
1125
+ artifacts: /* @__PURE__ */ new Set(),
1126
+ hasConfigChanged: false,
1127
+ diffs: []
1128
+ };
1129
+ if (!this.previousConfig) {
1130
+ affected.hasConfigChanged = true;
1131
+ return affected;
1132
+ }
1133
+ const newConfig = conf.deserialize();
1134
+ const configDiff = diff(this.previousConfig, newConfig);
1135
+ if (!configDiff.length) {
1136
+ return affected;
1137
+ }
1138
+ affected.hasConfigChanged = true;
1139
+ affected.diffs = configDiff;
1140
+ this.previousConfig = newConfig;
1141
+ fn?.(conf);
1142
+ configDiff.forEach((change) => {
1143
+ const changePath = change.path.join(".");
1144
+ matchers.artifacts.forEach((matcher) => {
1145
+ const id = matcher(changePath);
1146
+ if (!id)
1147
+ return;
1148
+ if (id === "recipes") {
1149
+ const name = dashCase(change.path.slice(1, 3).join("."));
1150
+ affected.artifacts.add(name);
1151
+ }
1152
+ if (id === "patterns") {
1153
+ const name = dashCase(change.path.slice(0, 2).join("."));
1154
+ affected.artifacts.add(name);
1155
+ }
1156
+ affected.artifacts.add(id);
1157
+ });
1158
+ });
1159
+ return affected;
1160
+ }
1161
+ };
1028
1162
 
1029
1163
  // src/create-context.ts
1030
- var createContext = (conf) => {
1031
- const generator = createGenerator(conf);
1032
- const config = conf.config;
1033
- const runtime = nodeRuntime;
1034
- config.cwd ||= runtime.cwd();
1035
- if (config.logLevel) {
1036
- logger3.level = config.logLevel;
1037
- }
1038
- const { include, exclude, cwd } = config;
1039
- const getFiles = () => runtime.fs.glob({ include, exclude, cwd });
1040
- const ctx = {
1041
- ...conf,
1042
- ...generator,
1043
- runtime: nodeRuntime,
1044
- hooks: conf.hooks,
1045
- getFiles,
1046
- project: createProject({
1164
+ var PandaContext = class extends Generator2 {
1165
+ runtime;
1166
+ project;
1167
+ getFiles;
1168
+ chunks;
1169
+ output;
1170
+ diff;
1171
+ constructor(conf) {
1172
+ super(conf);
1173
+ const config = conf.config;
1174
+ this.runtime = nodeRuntime;
1175
+ config.cwd ||= this.runtime.cwd();
1176
+ if (config.logLevel) {
1177
+ logger4.level = config.logLevel;
1178
+ }
1179
+ const { include, exclude, cwd } = config;
1180
+ this.getFiles = () => this.runtime.fs.glob({ include, exclude, cwd });
1181
+ this.project = createProject({
1047
1182
  ...conf.tsconfig,
1048
- getFiles,
1049
- readFile: runtime.fs.readFileSync,
1183
+ getFiles: this.getFiles.bind(this),
1184
+ readFile: this.runtime.fs.readFileSync.bind(this),
1050
1185
  hooks: conf.hooks,
1051
- parserOptions: { join: runtime.path.join, ...generator.parserOptions }
1052
- })
1053
- };
1054
- return Object.assign(ctx, { chunks: getChunkEngine(ctx), output: getOutputEngine(ctx) });
1186
+ parserOptions: { join: this.runtime.path.join, ...this.parserOptions }
1187
+ });
1188
+ this.chunks = getChunkEngine(this);
1189
+ this.output = new PandaOutputEngine(this);
1190
+ this.diff = new DiffEngine(this);
1191
+ }
1055
1192
  };
1056
1193
 
1057
1194
  // src/config.ts
@@ -1065,27 +1202,33 @@ function findConfig() {
1065
1202
  }
1066
1203
  }
1067
1204
  async function loadConfigAndCreateContext(options = {}) {
1068
- const hooks = createHooks();
1069
1205
  const { config, configPath } = options;
1070
1206
  const cwd = options.cwd ?? options?.config?.cwd ?? process.cwd();
1071
- const conf = await loadConfigFile({ cwd, file: configPath });
1207
+ const conf = await loadConfigFile2({ cwd, file: configPath });
1072
1208
  if (config) {
1073
1209
  Object.assign(conf.config, config);
1074
1210
  }
1075
1211
  if (options.cwd) {
1076
1212
  conf.config.cwd = options.cwd;
1077
1213
  }
1078
- const tsconfigResult = await parse(conf.path, { root: cwd, resolveWithEmptyIfConfigNotFound: true });
1214
+ const tsconfigResult = await parse(conf.path, {
1215
+ root: cwd,
1216
+ resolveWithEmptyIfConfigNotFound: true
1217
+ });
1079
1218
  if (tsconfigResult) {
1080
1219
  conf.tsconfig = tsconfigResult.tsconfig;
1081
1220
  conf.tsconfigFile = tsconfigResult.tsconfigFile;
1082
1221
  const options2 = tsconfigResult.tsconfig?.compilerOptions;
1083
1222
  if (options2?.paths) {
1084
1223
  const baseUrl = options2.baseUrl;
1085
- conf.tsOptions = { baseUrl, pathMappings: convertTsPathsToRegexes(options2.paths, baseUrl ?? cwd) };
1224
+ conf.tsOptions = {
1225
+ baseUrl,
1226
+ pathMappings: convertTsPathsToRegexes(options2.paths, baseUrl ?? cwd)
1227
+ };
1086
1228
  }
1087
1229
  }
1088
1230
  conf.config.outdir ??= "styled-system";
1231
+ const hooks = createHooks();
1089
1232
  if (conf.config.hooks) {
1090
1233
  hooks.addHooks(conf.config.hooks);
1091
1234
  }
@@ -1093,13 +1236,13 @@ async function loadConfigAndCreateContext(options = {}) {
1093
1236
  if (conf.config.logLevel === "debug") {
1094
1237
  createDebugger(hooks, { tag: "panda" });
1095
1238
  }
1096
- return createContext({ ...conf, hooks });
1239
+ return new PandaContext({ ...conf, hooks });
1097
1240
  }
1098
1241
 
1099
1242
  // src/extract.ts
1100
1243
  init_esm_shims();
1101
1244
  import { optimizeCss } from "@pandacss/core";
1102
- import { logger as logger4 } from "@pandacss/logger";
1245
+ import { logger as logger5 } from "@pandacss/logger";
1103
1246
  import { createParserResult } from "@pandacss/parser";
1104
1247
  import { writeFile as writeFile2 } from "fs/promises";
1105
1248
  import { Obj, pipe, tap, tryCatch } from "lil-fp";
@@ -2421,6 +2564,7 @@ var createBox = (options) => boxen(options.content, {
2421
2564
  async function bundleStyleChunksWithImports(ctx) {
2422
2565
  const files = ctx.chunks.getFiles();
2423
2566
  await ctx.output.write({
2567
+ id: "styles.css",
2424
2568
  dir: ctx.paths.root,
2425
2569
  files: [{ file: "styles.css", code: ctx.getCss({ files }) }]
2426
2570
  });
@@ -2428,11 +2572,11 @@ async function bundleStyleChunksWithImports(ctx) {
2428
2572
  }
2429
2573
  async function writeFileChunk(ctx, file) {
2430
2574
  const { path: path2 } = ctx.runtime;
2431
- logger4.debug("chunk:write", `File: ${path2.relative(ctx.config.cwd, file)}`);
2432
- const css = extractFile(ctx, file);
2433
- if (!css)
2575
+ logger5.debug("chunk:write", `File: ${path2.relative(ctx.config.cwd, file)}`);
2576
+ const css2 = extractFile(ctx, file);
2577
+ if (!css2)
2434
2578
  return;
2435
- const artifact = ctx.chunks.getArtifact(file, css);
2579
+ const artifact = ctx.chunks.getArtifact(file, css2);
2436
2580
  return ctx.output.write(artifact);
2437
2581
  }
2438
2582
  function extractFile(ctx, file) {
@@ -2442,16 +2586,16 @@ function extractFile(ctx, file) {
2442
2586
  } = ctx;
2443
2587
  return pipe(
2444
2588
  { file: path2.abs(cwd, file) },
2445
- tap(() => logger4.debug("file:extract", file)),
2446
- Obj.bind("measure", () => logger4.time.debug(`Extracted ${file}`)),
2589
+ tap(() => logger5.debug("file:extract", file)),
2590
+ Obj.bind("measure", () => logger5.time.debug(`Extracted ${file}`)),
2447
2591
  Obj.bind(
2448
2592
  "result",
2449
2593
  tryCatch(
2450
2594
  ({ file: file2 }) => ctx.project.parseSourceFile(file2),
2451
- (error) => logger4.error("file:parse", error)
2595
+ (error) => logger5.error("file:parse", error)
2452
2596
  )
2453
2597
  ),
2454
- Obj.bind("measureCss", () => logger4.time.debug(`Parsed ${file}`)),
2598
+ Obj.bind("measureCss", () => logger5.time.debug(`Parsed ${file}`)),
2455
2599
  Obj.bind("css", ({ result }) => result ? ctx.getParserCss(result) : void 0),
2456
2600
  tap(({ measure, measureCss }) => [measureCss(), measure()]),
2457
2601
  Obj.get("css")
@@ -2463,10 +2607,10 @@ function writeChunks(ctx) {
2463
2607
  var randomWords = ["Sweet", "Divine", "Pandalicious", "Super"];
2464
2608
  var pickRandom = (arr) => arr[Math.floor(Math.random() * arr.length)];
2465
2609
  var limit = pLimit(20);
2466
- async function emitArtifacts(ctx) {
2610
+ async function emitArtifacts(ctx, ids) {
2467
2611
  if (ctx.config.clean)
2468
2612
  ctx.output.empty();
2469
- const promises = ctx.getArtifacts().map((artifact) => limit(() => ctx.output.write(artifact)));
2613
+ const promises = ctx.getArtifacts(ids).map((artifact) => limit(() => ctx.output.write(artifact)));
2470
2614
  await Promise.allSettled(promises);
2471
2615
  void ctx.hooks.callHook("generator:done");
2472
2616
  return {
@@ -2477,13 +2621,6 @@ async function emitArtifacts(ctx) {
2477
2621
  msg: ctx.messages.artifactsGenerated()
2478
2622
  };
2479
2623
  }
2480
- async function emitArtfifactsAndCssChunks(ctx) {
2481
- await emitArtifacts(ctx);
2482
- if (ctx.config.emitTokensOnly) {
2483
- return { files: [], msg: "Successfully rebuilt the css variables and js function to query your tokens \u2728" };
2484
- }
2485
- return writeAndBundleCssChunks(ctx);
2486
- }
2487
2624
  async function writeAndBundleCssChunks(ctx) {
2488
2625
  await writeChunks(ctx);
2489
2626
  return bundleStyleChunksWithImports(ctx);
@@ -2500,7 +2637,7 @@ async function bundleMinimalFilesCss(ctx, outfile) {
2500
2637
  const filesWithCss = [];
2501
2638
  const collector = createParserResult();
2502
2639
  files.forEach((file) => {
2503
- const measure = logger4.time.debug(`Parsed ${file}`);
2640
+ const measure = logger5.time.debug(`Parsed ${file}`);
2504
2641
  const result = ctx.project.parseSourceFile(file);
2505
2642
  measure();
2506
2643
  if (!result)
@@ -2508,24 +2645,24 @@ async function bundleMinimalFilesCss(ctx, outfile) {
2508
2645
  collector.merge(result);
2509
2646
  filesWithCss.push(file);
2510
2647
  });
2511
- const css = ctx.getParserCss(collector);
2512
- if (!css)
2648
+ const css2 = ctx.getParserCss(collector);
2649
+ if (!css2)
2513
2650
  return { files, msg: ctx.messages.buildComplete(files.length) };
2514
2651
  const minify = ctx.config.minify;
2515
- await writeFile2(outfile, optimizeCss(css, { minify }));
2652
+ await writeFile2(outfile, optimizeCss(css2, { minify }));
2516
2653
  return { files, msg: ctx.messages.buildComplete(files.length) };
2517
2654
  }
2518
2655
  async function generateCssArtifactOfType(ctx, cssType, outfile) {
2519
2656
  let notFound = false;
2520
- const css = match(cssType).with("preflight", () => ctx.getResetCss(ctx)).with("tokens", () => ctx.getTokenCss(ctx)).with("static", () => ctx.getStaticCss(ctx)).with("global", () => ctx.getGlobalCss(ctx)).with("keyframes", () => ctx.getKeyframeCss(ctx)).otherwise(() => {
2657
+ const css2 = match(cssType).with("preflight", () => ctx.getResetCss()).with("tokens", () => ctx.getTokenCss()).with("static", () => ctx.getStaticCss()).with("global", () => ctx.getGlobalCss()).with("keyframes", () => ctx.getKeyframeCss()).otherwise(() => {
2521
2658
  notFound = true;
2522
2659
  });
2523
2660
  if (notFound)
2524
2661
  return { msg: `No css artifact of type <${cssType}> was found` };
2525
- if (!css)
2662
+ if (!css2)
2526
2663
  return { msg: `No css to generate for type <${cssType}>` };
2527
2664
  const minify = ctx.config.minify;
2528
- await writeFile2(outfile, optimizeCss(css, { minify }));
2665
+ await writeFile2(outfile, optimizeCss(css2, { minify }));
2529
2666
  return { msg: `Successfully generated ${cssType} css artifact \u2728` };
2530
2667
  }
2531
2668
 
@@ -2574,8 +2711,8 @@ function parseDependency(fileOrGlob) {
2574
2711
  }
2575
2712
 
2576
2713
  // src/builder.ts
2577
- var configCache = /* @__PURE__ */ new Map();
2578
- var contentFilesCache = /* @__PURE__ */ new WeakMap();
2714
+ var fileCssMap = /* @__PURE__ */ new Map();
2715
+ var fileModifiedMap = /* @__PURE__ */ new Map();
2579
2716
  var limit2 = pLimit(20);
2580
2717
  var Builder = class {
2581
2718
  /**
@@ -2583,34 +2720,8 @@ var Builder = class {
2583
2720
  */
2584
2721
  context;
2585
2722
  hasEmitted = false;
2586
- configDependencies = /* @__PURE__ */ new Set();
2587
- writeFileCss = (file, css) => {
2588
- const oldCss = this.fileCssMap?.get(file) ?? "";
2589
- const newCss = mergeCss2(oldCss, css);
2590
- this.fileCssMap?.set(file, newCss);
2591
- };
2592
- checkConfigDeps = (configPath, deps) => {
2593
- let modified = false;
2594
- const newModified = /* @__PURE__ */ new Map();
2595
- const prevModified = configCache.get(configPath)?.depsModifiedMap;
2596
- for (const file of deps) {
2597
- const stats = fsExtra2.statSync(file, { throwIfNoEntry: false });
2598
- if (!stats)
2599
- continue;
2600
- const time = stats.mtimeMs;
2601
- newModified.set(file, time);
2602
- if (prevModified && (!prevModified.has(file) || time > prevModified.get(file))) {
2603
- modified = true;
2604
- }
2605
- }
2606
- if (!modified) {
2607
- return { isModified: false, modifiedMap: prevModified || /* @__PURE__ */ new Map() };
2608
- }
2609
- for (const file of deps) {
2610
- delete __require.cache[file];
2611
- }
2612
- return { isModified: true, modifiedMap: newModified };
2613
- };
2723
+ hasConfigChanged = false;
2724
+ affecteds;
2614
2725
  getConfigPath = () => {
2615
2726
  const configPath = findConfig();
2616
2727
  if (!configPath) {
@@ -2618,56 +2729,35 @@ var Builder = class {
2618
2729
  }
2619
2730
  return configPath;
2620
2731
  };
2621
- hasConfigChanged = false;
2622
2732
  setup = async (options = {}) => {
2623
- logger5.debug("builder", "\u{1F6A7} Setup");
2733
+ logger6.debug("builder", "\u{1F6A7} Setup");
2624
2734
  const configPath = options.configPath ?? this.getConfigPath();
2625
- const tsOptions = this.context?.tsOptions ?? { baseUrl: void 0, pathMappings: [] };
2626
- const compilerOptions = this.context?.tsconfig?.compilerOptions ?? {};
2627
- const { deps: foundDeps } = getConfigDependencies(configPath, tsOptions, compilerOptions);
2628
- const cwd = options?.cwd ?? this.context?.config.cwd ?? process.cwd();
2629
- const configDeps = /* @__PURE__ */ new Set([...foundDeps, ...(this.context?.dependencies ?? []).map((file) => resolve2(cwd, file))]);
2630
- this.configDependencies = configDeps;
2631
- const deps = this.checkConfigDeps(configPath, configDeps);
2632
- this.hasConfigChanged = deps.isModified;
2633
- if (deps.isModified) {
2634
- await this.setupContext({
2635
- configPath,
2636
- depsModifiedMap: deps.modifiedMap
2637
- });
2638
- const ctx = this.getContextOrThrow();
2639
- logger5.debug("builder", "\u2699\uFE0F Config changed, reloading");
2640
- await ctx.hooks.callHook("config:change", ctx.config);
2735
+ if (!this.context) {
2736
+ return this.setupContext({ configPath });
2641
2737
  }
2642
- const cache = configCache.get(configPath);
2643
- if (cache) {
2644
- this.context = cache.context;
2645
- this.context.project.reloadSourceFiles();
2646
- } else {
2647
- await this.setupContext({
2648
- configPath,
2649
- depsModifiedMap: deps.modifiedMap
2650
- });
2738
+ const ctx = this.getContextOrThrow();
2739
+ this.affecteds = await ctx.diff.reloadConfigAndRefreshContext((conf) => {
2740
+ this.context = new PandaContext({ ...conf, hooks: ctx.hooks });
2741
+ });
2742
+ this.hasConfigChanged = this.affecteds.hasConfigChanged;
2743
+ if (this.affecteds.hasConfigChanged) {
2744
+ logger6.debug("builder", "\u2699\uFE0F Config changed, reloading");
2745
+ await ctx.hooks.callHook("config:change", ctx.config);
2746
+ return;
2651
2747
  }
2748
+ ctx.project.reloadSourceFiles();
2652
2749
  };
2653
- emit() {
2654
- if (this.hasEmitted && this.hasConfigChanged) {
2655
- emitArtifacts(this.getContextOrThrow());
2750
+ async emit() {
2751
+ if (this.hasEmitted && this.affecteds?.hasConfigChanged) {
2752
+ await emitArtifacts(this.getContextOrThrow(), Array.from(this.affecteds.artifacts));
2656
2753
  }
2657
2754
  this.hasEmitted = true;
2658
2755
  }
2659
2756
  setupContext = async (options) => {
2660
- const { configPath, depsModifiedMap } = options;
2661
- this.context = await loadConfigAndCreateContext({ configPath });
2662
- configCache.set(configPath, {
2663
- context: this.context,
2664
- deps: new Set(this.context.dependencies ?? []),
2665
- depsModifiedMap
2666
- });
2667
- contentFilesCache.set(this.context, {
2668
- fileCssMap: /* @__PURE__ */ new Map(),
2669
- fileModifiedMap: /* @__PURE__ */ new Map()
2670
- });
2757
+ const { configPath } = options;
2758
+ const ctx = await loadConfigAndCreateContext({ configPath });
2759
+ this.context = ctx;
2760
+ return ctx;
2671
2761
  };
2672
2762
  getContextOrThrow = () => {
2673
2763
  if (!this.context) {
@@ -2675,29 +2765,23 @@ var Builder = class {
2675
2765
  }
2676
2766
  return this.context;
2677
2767
  };
2678
- get fileModifiedMap() {
2679
- const ctx = this.getContextOrThrow();
2680
- return contentFilesCache.get(ctx).fileModifiedMap;
2681
- }
2682
- get fileCssMap() {
2683
- const ctx = this.getContextOrThrow();
2684
- return contentFilesCache.get(ctx).fileCssMap;
2685
- }
2686
2768
  extractFile = async (ctx, file) => {
2687
2769
  const mtime = existsSync(file) ? fsExtra2.statSync(file).mtimeMs : -Infinity;
2688
- const isUnchanged = this.fileModifiedMap.has(file) && mtime === this.fileModifiedMap.get(file);
2689
- if (isUnchanged)
2770
+ const isUnchanged = fileModifiedMap.has(file) && mtime === fileModifiedMap.get(file);
2771
+ if (isUnchanged && !this.hasConfigChanged)
2690
2772
  return;
2691
- const css = extractFile(ctx, file);
2692
- if (!css)
2773
+ const css2 = extractFile(ctx, file);
2774
+ fileModifiedMap.set(file, mtime);
2775
+ if (!css2) {
2776
+ fileCssMap.delete(file);
2693
2777
  return;
2694
- this.fileModifiedMap.set(file, mtime);
2695
- this.writeFileCss(file, css);
2696
- return css;
2778
+ }
2779
+ fileCssMap.set(file, css2);
2780
+ return css2;
2697
2781
  };
2698
2782
  extract = async () => {
2699
2783
  const ctx = this.getContextOrThrow();
2700
- const done = logger5.time.info("Extracted in");
2784
+ const done = logger6.time.info("Extracted in");
2701
2785
  const promises = ctx.getFiles().map((file) => limit2(() => this.extractFile(ctx, file)));
2702
2786
  await Promise.allSettled(promises);
2703
2787
  done();
@@ -2705,7 +2789,7 @@ var Builder = class {
2705
2789
  toString = () => {
2706
2790
  const ctx = this.getContextOrThrow();
2707
2791
  return ctx.getCss({
2708
- files: Array.from(this.fileCssMap.values()),
2792
+ files: Array.from(fileCssMap.values()),
2709
2793
  resolve: true
2710
2794
  });
2711
2795
  };
@@ -2737,10 +2821,7 @@ var Builder = class {
2737
2821
  fn(dependency);
2738
2822
  }
2739
2823
  }
2740
- for (const file of ctx.dependencies) {
2741
- fn({ type: "dependency", file: resolve2(file) });
2742
- }
2743
- for (const file of this.configDependencies) {
2824
+ for (const file of ctx.conf.dependencies) {
2744
2825
  fn({ type: "dependency", file: resolve2(file) });
2745
2826
  }
2746
2827
  };
@@ -2748,18 +2829,18 @@ var Builder = class {
2748
2829
 
2749
2830
  // src/debug-files.ts
2750
2831
  init_esm_shims();
2751
- import { colors, logger as logger6 } from "@pandacss/logger";
2832
+ import { colors, logger as logger7 } from "@pandacss/logger";
2752
2833
  import * as nodePath from "path";
2753
2834
  async function debugFiles(ctx, options) {
2754
2835
  const files = ctx.getFiles();
2755
- const measureTotal = logger6.time.debug(`Done parsing ${files.length} files`);
2836
+ const measureTotal = logger7.time.debug(`Done parsing ${files.length} files`);
2756
2837
  ctx.config.minify = false;
2757
2838
  ctx.config.optimize = true;
2758
2839
  const { fs, path: path2 } = ctx.runtime;
2759
2840
  const outdir = options.outdir;
2760
2841
  if (!options.dry && outdir) {
2761
2842
  fs.ensureDirSync(outdir);
2762
- logger6.info("cli", `Writing ${colors.bold(`${outdir}/config.json`)}`);
2843
+ logger7.info("cli", `Writing ${colors.bold(`${outdir}/config.json`)}`);
2763
2844
  await fs.writeFile(`${outdir}/config.json`, JSON.stringify(ctx.config, null, 2));
2764
2845
  }
2765
2846
  if (options.onlyConfig) {
@@ -2769,16 +2850,16 @@ async function debugFiles(ctx, options) {
2769
2850
  const filesWithCss = [];
2770
2851
  await Promise.allSettled(
2771
2852
  files.map(async (file) => {
2772
- const measure = logger6.time.debug(`Parsed ${file}`);
2853
+ const measure = logger7.time.debug(`Parsed ${file}`);
2773
2854
  const result = ctx.project.parseSourceFile(file);
2774
2855
  measure();
2775
2856
  if (!result)
2776
2857
  return;
2777
- const css = ctx.getParserCss(result);
2778
- if (!css)
2858
+ const css2 = ctx.getParserCss(result);
2859
+ if (!css2)
2779
2860
  return;
2780
2861
  if (options.dry) {
2781
- console.log({ path: file, ast: result, code: css });
2862
+ console.log({ path: file, ast: result, code: css2 });
2782
2863
  return Promise.resolve();
2783
2864
  }
2784
2865
  if (outdir) {
@@ -2787,22 +2868,22 @@ async function debugFiles(ctx, options) {
2787
2868
  const relative3 = path2.relative(ctx.config.cwd, parsedPath.dir);
2788
2869
  const astJsonPath = `${relative3}/${parsedPath.name}.ast.json`.replaceAll(path2.sep, "__");
2789
2870
  const cssPath = `${relative3}/${parsedPath.name}.css`.replaceAll(path2.sep, "__");
2790
- logger6.info("cli", `Writing ${colors.bold(`${outdir}/${astJsonPath}`)}`);
2791
- logger6.info("cli", `Writing ${colors.bold(`${outdir}/${cssPath}`)}`);
2871
+ logger7.info("cli", `Writing ${colors.bold(`${outdir}/${astJsonPath}`)}`);
2872
+ logger7.info("cli", `Writing ${colors.bold(`${outdir}/${cssPath}`)}`);
2792
2873
  return Promise.allSettled([
2793
2874
  fs.writeFile(`${outdir}/${astJsonPath}`, JSON.stringify(result.toJSON(), null, 2)),
2794
- fs.writeFile(`${outdir}/${cssPath}`, css)
2875
+ fs.writeFile(`${outdir}/${cssPath}`, css2)
2795
2876
  ]);
2796
2877
  }
2797
2878
  })
2798
2879
  );
2799
- logger6.info("cli", `Found ${colors.bold(`${filesWithCss.length}/${files.length}`)} files using Panda`);
2880
+ logger7.info("cli", `Found ${colors.bold(`${filesWithCss.length}/${files.length}`)} files using Panda`);
2800
2881
  measureTotal();
2801
2882
  }
2802
2883
 
2803
2884
  // src/exec-command.ts
2804
2885
  init_esm_shims();
2805
- import { logger as logger7 } from "@pandacss/logger";
2886
+ import { logger as logger8 } from "@pandacss/logger";
2806
2887
  import { spawnSync } from "child_process";
2807
2888
  import getPackageManager from "preferred-pm";
2808
2889
  async function execCommand(cmd, cwd) {
@@ -2814,66 +2895,56 @@ async function execCommand(cmd, cwd) {
2814
2895
  }
2815
2896
  const check = spawnSync(pm, args, { cwd, stdio: "pipe" });
2816
2897
  if (check.status !== 0) {
2817
- logger7.error("exec", check.stderr.toString());
2898
+ logger8.error("exec", check.stderr.toString());
2818
2899
  }
2819
2900
  }
2820
2901
 
2821
2902
  // src/generate.ts
2822
2903
  init_esm_shims();
2823
- import { logger as logger8 } from "@pandacss/logger";
2904
+ import { logger as logger9 } from "@pandacss/logger";
2824
2905
  import { match as match2 } from "ts-pattern";
2825
-
2826
- // src/load-context.ts
2827
- init_esm_shims();
2828
- var loadContext = async (config, configPath) => {
2829
- const ctxRef = { current: void 0 };
2830
- const load = async () => {
2831
- const ctx = await loadConfigAndCreateContext({ config, configPath });
2832
- ctxRef.current = ctx;
2833
- };
2834
- await load();
2835
- return [ctxRef, load];
2836
- };
2837
-
2838
- // src/generate.ts
2839
- async function build(ctx) {
2840
- const { msg } = await emitArtfifactsAndCssChunks(ctx);
2841
- logger8.info("css:emit", msg);
2906
+ async function build(ctx, ids) {
2907
+ await emitArtifacts(ctx, ids);
2908
+ if (ctx.config.emitTokensOnly) {
2909
+ return logger9.info("css:emit", "Successfully rebuilt the css variables and js function to query your tokens \u2728");
2910
+ }
2911
+ const { msg } = await writeAndBundleCssChunks(ctx);
2912
+ logger9.info("css:emit", msg);
2842
2913
  }
2843
2914
  async function generate(config, configPath) {
2844
- const [ctxRef, loadCtx] = await loadContext(config, configPath);
2845
- const ctx = ctxRef.current;
2915
+ const ctx = await loadConfigAndCreateContext({ config, configPath });
2846
2916
  await build(ctx);
2847
2917
  const {
2848
2918
  runtime: { fs, path: path2 },
2849
- dependencies,
2850
2919
  config: { cwd }
2851
2920
  } = ctx;
2852
2921
  if (ctx.config.watch) {
2853
- const configWatcher = fs.watch({ include: dependencies });
2922
+ const configWatcher = fs.watch({ include: ctx.conf.dependencies });
2854
2923
  configWatcher.on("change", async () => {
2855
- logger8.info("config:change", "Config changed, restarting...");
2856
- await loadCtx();
2857
- await ctxRef.current.hooks.callHook("config:change", ctxRef.current.config);
2858
- return build(ctxRef.current);
2924
+ const affecteds = await ctx.diff.reloadConfigAndRefreshContext();
2925
+ if (!affecteds.artifacts.size)
2926
+ return;
2927
+ logger9.info("config:change", "Config changed, restarting...");
2928
+ await ctx.hooks.callHook("config:change", ctx.config);
2929
+ return build(ctx, Array.from(affecteds.artifacts));
2859
2930
  });
2860
2931
  const contentWatcher = fs.watch(ctx.config);
2861
2932
  contentWatcher.on("all", async (event, file) => {
2862
- logger8.info(`file:${event}`, file);
2933
+ logger9.info(`file:${event}`, file);
2863
2934
  match2(event).with("unlink", () => {
2864
2935
  ctx.project.removeSourceFile(path2.abs(cwd, file));
2865
2936
  ctx.chunks.rm(file);
2866
2937
  }).with("change", async () => {
2867
2938
  ctx.project.reloadSourceFile(file);
2868
- await writeFileChunk(ctxRef.current, file);
2869
- return bundleStyleChunksWithImports(ctxRef.current);
2939
+ await writeFileChunk(ctx, file);
2940
+ return bundleStyleChunksWithImports(ctx);
2870
2941
  }).with("add", async () => {
2871
2942
  ctx.project.createSourceFile(file);
2872
- return bundleStyleChunksWithImports(ctxRef.current);
2943
+ return bundleStyleChunksWithImports(ctx);
2873
2944
  }).otherwise(() => {
2874
2945
  });
2875
2946
  });
2876
- logger8.info("ctx:watch", ctx.messages.watch());
2947
+ logger9.info("ctx:watch", ctx.messages.watch());
2877
2948
  }
2878
2949
  }
2879
2950
 
@@ -2905,7 +2976,7 @@ function setupGitIgnore(ctx) {
2905
2976
  // src/setup-config.ts
2906
2977
  init_esm_shims();
2907
2978
  import { messages } from "@pandacss/generator";
2908
- import { logger as logger9, quote } from "@pandacss/logger";
2979
+ import { logger as logger10, quote } from "@pandacss/logger";
2909
2980
  import fsExtra3 from "fs-extra";
2910
2981
  import { lookItUpSync as lookItUpSync3 } from "look-it-up";
2911
2982
  import { outdent as outdent2 } from "outdent";
@@ -2920,9 +2991,9 @@ async function setupConfig(cwd, opts = {}) {
2920
2991
  const cmd = pm === "npm" ? "npm run" : pm;
2921
2992
  const isTs = lookItUpSync3("tsconfig.json", cwd);
2922
2993
  const file = isTs ? "panda.config.ts" : "panda.config.mjs";
2923
- logger9.info("init:config", `creating panda config file: ${quote(file)}`);
2994
+ logger10.info("init:config", `creating panda config file: ${quote(file)}`);
2924
2995
  if (!force && configFile) {
2925
- logger9.warn("init:config", messages.configExists(cmd));
2996
+ logger10.warn("init:config", messages.configExists(cmd));
2926
2997
  } else {
2927
2998
  const content = outdent2`
2928
2999
  import { defineConfig } from "@pandacss/dev"
@@ -2955,11 +3026,11 @@ syntax: '${syntax}'` : ""}
2955
3026
  })
2956
3027
  `;
2957
3028
  await fsExtra3.writeFile(join2(cwd, file), prettier.format(content));
2958
- logger9.log(messages.thankYou());
3029
+ logger10.log(messages.thankYou());
2959
3030
  }
2960
3031
  }
2961
3032
  async function setupPostcss(cwd) {
2962
- logger9.info("init:postcss", `creating postcss config file: ${quote("postcss.config.cjs")}`);
3033
+ logger10.info("init:postcss", `creating postcss config file: ${quote("postcss.config.cjs")}`);
2963
3034
  const content = outdent2`
2964
3035
  module.exports = {
2965
3036
  plugins: {
@@ -2972,7 +3043,7 @@ module.exports = {
2972
3043
 
2973
3044
  // src/ship-files.ts
2974
3045
  init_esm_shims();
2975
- import { colors as colors2, logger as logger10 } from "@pandacss/logger";
3046
+ import { colors as colors2, logger as logger11 } from "@pandacss/logger";
2976
3047
  import { createParserResult as createParserResult2 } from "@pandacss/parser";
2977
3048
  import { writeFile as writeFile3 } from "fs/promises";
2978
3049
  import * as path from "path";
@@ -2984,29 +3055,28 @@ async function shipFiles(ctx, outfile) {
2984
3055
  const result = ctx.project.parseSourceFile(file);
2985
3056
  if (!result || result.isEmpty())
2986
3057
  return;
2987
- const css = ctx.getParserCss(result);
2988
- if (!css)
3058
+ const css2 = ctx.getParserCss(result);
3059
+ if (!css2)
2989
3060
  return;
2990
3061
  extractResult.merge(result);
2991
3062
  filesWithCss.push(path.relative(ctx.config.cwd, file));
2992
3063
  });
2993
- logger10.info("cli", `Found ${colors2.bold(`${filesWithCss.length}/${files.length}`)} files using Panda`);
3064
+ logger11.info("cli", `Found ${colors2.bold(`${filesWithCss.length}/${files.length}`)} files using Panda`);
2994
3065
  const minify = ctx.config.minify;
2995
- logger10.info("cli", `Writing ${minify ? "[min] " : " "}${colors2.bold(outfile)}`);
3066
+ logger11.info("cli", `Writing ${minify ? "[min] " : " "}${colors2.bold(outfile)}`);
2996
3067
  const output = JSON.stringify(extractResult.toJSON(), null, minify ? 0 : 2);
2997
3068
  const dirname2 = ctx.runtime.path.dirname(outfile);
2998
3069
  ctx.runtime.fs.ensureDirSync(dirname2);
2999
3070
  await writeFile3(outfile, output);
3000
- logger10.info("cli", "Done!");
3071
+ logger11.info("cli", "Done!");
3001
3072
  }
3002
3073
  export {
3003
3074
  Builder,
3075
+ PandaContext,
3004
3076
  analyzeTokens,
3005
3077
  bundleCss,
3006
3078
  bundleMinimalFilesCss,
3007
- createContext,
3008
3079
  debugFiles,
3009
- emitArtfifactsAndCssChunks,
3010
3080
  emitArtifacts,
3011
3081
  execCommand,
3012
3082
  extractFile,