@pandacss/compiler 2.0.0-beta.4 → 2.0.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1029 @@
1
+ // src/index.ts
2
+ import {
3
+ assertProjectHooks,
4
+ assertProjectCallbacks,
5
+ BuildInfo as BuildInfo2,
6
+ DesignSystem as DesignSystem2,
7
+ getTokenCategoryValues,
8
+ inspectFile,
9
+ inspectFiles,
10
+ mergeCallbacks,
11
+ mergeHooks,
12
+ prepareCompilerConfig
13
+ } from "@pandacss/compiler-shared";
14
+
15
+ // src/callbacks.ts
16
+ import {
17
+ createPatternHelpers,
18
+ createTransformArgs,
19
+ getPatternDefaultValueRefsByTransformId,
20
+ mergePatternDefaultValues
21
+ } from "@pandacss/compiler-shared";
22
+ function registerCallbacks(project, callbacks, hooks, tokenDictionary) {
23
+ const utilityTransforms = callbacks["utility.transform"];
24
+ const hasUtilityTransforms = !!utilityTransforms && Object.keys(utilityTransforms).length > 0;
25
+ const patternTransforms = callbacks["pattern.transform"];
26
+ const hasPatternTransforms = !!patternTransforms && Object.keys(patternTransforms).length > 0;
27
+ const config = project.config();
28
+ const patternDefaultValues = callbacks["pattern.defaultValues"];
29
+ const patternDefaultValueRefs = config && patternDefaultValues ? getPatternDefaultValueRefsByTransformId(config) : /* @__PURE__ */ new Map();
30
+ if (hasPatternTransforms && !project.registerPatternTransform) {
31
+ throw new Error("Native project does not support pattern.transform callbacks");
32
+ }
33
+ if (project.registerPatternTransform && patternTransforms) {
34
+ for (const [id, callback] of Object.entries(patternTransforms)) {
35
+ const defaultValueId = patternDefaultValueRefs.get(id);
36
+ const defaultValue = defaultValueId ? patternDefaultValues?.[defaultValueId] : void 0;
37
+ project.registerPatternTransform(id, (props) => {
38
+ const input = props;
39
+ const nextProps = defaultValue ? mergePatternDefaultValues(defaultValue(input), input) : input;
40
+ return callback(nextProps, createPatternHelpers());
41
+ });
42
+ }
43
+ }
44
+ if (hasUtilityTransforms && !project.registerUtilityTransform) {
45
+ throw new Error("Native project does not support utility.transform callbacks");
46
+ }
47
+ if (project.registerUtilityTransform && utilityTransforms) {
48
+ for (const [id, callback] of Object.entries(utilityTransforms)) {
49
+ project.registerUtilityTransform(id, (resolved, original) => {
50
+ return callback(resolved, createTransformArgs(original, tokenDictionary));
51
+ });
52
+ }
53
+ }
54
+ const sourceTransforms = hooks?.["parser:before"];
55
+ if (sourceTransforms?.length && !project.registerSourceTransform) {
56
+ throw new Error("Native project does not support parser:before callbacks");
57
+ }
58
+ if (project.registerSourceTransform && sourceTransforms) {
59
+ for (const hook of sourceTransforms) {
60
+ const callback = callbacks["parser:before"]?.[hook.id];
61
+ if (!callback) continue;
62
+ project.registerSourceTransform(hook.id, hook.filter, (filePath, content) => {
63
+ const result = callback({ filePath: String(filePath), content: String(content), original: String(content) });
64
+ if (isPromiseLike(result)) {
65
+ throw new Error(`parser:before callback \`${hook.id}\` must be synchronous`);
66
+ }
67
+ return typeof result === "string" ? result : void 0;
68
+ });
69
+ }
70
+ }
71
+ }
72
+ function isPromiseLike(value) {
73
+ return !!value && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
74
+ }
75
+
76
+ // src/fallback.ts
77
+ import { BuildInfo, DesignSystem } from "@pandacss/compiler-shared";
78
+ var fallbackBuildInfo = new BuildInfo({
79
+ serializeBuildInfo: () => ({
80
+ schemaVersion: -1,
81
+ panda: "",
82
+ configFingerprint: "",
83
+ strings: [],
84
+ atoms: [],
85
+ modules: {}
86
+ }),
87
+ applyBuildInfo: () => false,
88
+ buildInfoSchemaVersion: () => -1,
89
+ configFingerprint: () => ""
90
+ });
91
+ var fallbackDesignSystem = new DesignSystem(
92
+ {
93
+ createManifest: (input) => ({ ...input, schemaVersion: -1 }),
94
+ manifestSchemaVersion: () => -1,
95
+ resolveChain: () => ({ status: "ordered", order: [] })
96
+ },
97
+ fallbackBuildInfo
98
+ );
99
+ var FallbackExtractor = class {
100
+ extract() {
101
+ return { calls: [], jsx: [], diagnostics: [] };
102
+ }
103
+ extractDebug() {
104
+ return { imports: [], matched: [], calls: [], jsx: [], diagnostics: [] };
105
+ }
106
+ matchImports() {
107
+ return [];
108
+ }
109
+ };
110
+ var FallbackCompiler = class _FallbackCompiler {
111
+ fs = {
112
+ readFile: (_path) => void 0,
113
+ exists: (_path) => false
114
+ };
115
+ path = {
116
+ realpath: (path) => path,
117
+ resolve: (path, cwd) => this.resolvePath(path, cwd),
118
+ join: (parts) => this.joinPath(parts),
119
+ dirname: (path) => this.dirname(path)
120
+ };
121
+ static fromConfig() {
122
+ return new _FallbackCompiler();
123
+ }
124
+ serializeBuildInfo() {
125
+ return fallbackBuildInfo.create({ panda: "" });
126
+ }
127
+ applyBuildInfo() {
128
+ return false;
129
+ }
130
+ buildInfoSchemaVersion() {
131
+ return -1;
132
+ }
133
+ configFingerprint() {
134
+ return "";
135
+ }
136
+ createDesignSystemManifest(input) {
137
+ return { ...input, schemaVersion: -1 };
138
+ }
139
+ designSystemManifestSchemaVersion() {
140
+ return -1;
141
+ }
142
+ resolveDesignSystemChain() {
143
+ return { status: "ordered", order: [] };
144
+ }
145
+ config() {
146
+ return {};
147
+ }
148
+ extractFileSource() {
149
+ return { calls: [], jsx: [], diagnostics: [] };
150
+ }
151
+ parseFile(path) {
152
+ return { path, cssCalls: 0, cvaCalls: 0, svaCalls: 0, jsxUsages: 0, diagnostics: [] };
153
+ }
154
+ parseFileSource(path) {
155
+ return { path, cssCalls: 0, cvaCalls: 0, svaCalls: 0, jsxUsages: 0, diagnostics: [] };
156
+ }
157
+ refreshFile() {
158
+ return false;
159
+ }
160
+ refreshFileSource() {
161
+ return false;
162
+ }
163
+ removeFile() {
164
+ return false;
165
+ }
166
+ clear() {
167
+ }
168
+ scan() {
169
+ return [];
170
+ }
171
+ realpath(path) {
172
+ return path;
173
+ }
174
+ readFile(_path) {
175
+ return void 0;
176
+ }
177
+ exists(_path) {
178
+ return false;
179
+ }
180
+ resolvePath(path, cwd) {
181
+ if (!cwd || path.startsWith("/")) return path;
182
+ return `${cwd.replace(/\/$/, "")}/${path}`;
183
+ }
184
+ joinPath(parts) {
185
+ return parts.filter(Boolean).join("/");
186
+ }
187
+ dirname(path) {
188
+ const index = path.lastIndexOf("/");
189
+ return index <= 0 ? "" : path.slice(0, index);
190
+ }
191
+ isSourceFile() {
192
+ return false;
193
+ }
194
+ parseFiles(_paths) {
195
+ return [];
196
+ }
197
+ layers() {
198
+ return { reset: "reset", base: "base", tokens: "tokens", recipes: "recipes", utilities: "utilities" };
199
+ }
200
+ hasLayerDeclaration() {
201
+ return false;
202
+ }
203
+ spec() {
204
+ return {
205
+ conditions: { keys: [], breakpoints: [], containers: [] },
206
+ tokens: { categories: {}, colorPalettes: [], values: {}, deprecated: {} },
207
+ utilities: { properties: {}, shorthands: {}, deprecated: {} },
208
+ keyframes: { keys: [] },
209
+ patterns: {},
210
+ recipes: {},
211
+ slotRecipes: {},
212
+ propertyOrder: []
213
+ };
214
+ }
215
+ sources() {
216
+ return [];
217
+ }
218
+ inspectFileSource(_path, _source) {
219
+ return { usages: [], diagnostics: [], calls: [], jsx: [], tokenRefs: [], componentEntries: [], styleEntries: [] };
220
+ }
221
+ inspectFile(input) {
222
+ return { ...this.inspectFileSource(input.path, input.source), path: input.path };
223
+ }
224
+ inspectFiles(files) {
225
+ return { sourceCount: files.length, files: files.map((file) => this.inspectFile(file)) };
226
+ }
227
+ resolveUtilityValue() {
228
+ return null;
229
+ }
230
+ suggestTokens() {
231
+ return [];
232
+ }
233
+ writeArtifacts(_options) {
234
+ return [];
235
+ }
236
+ writeCss(options) {
237
+ return emptyWriteCssResult(options.outfile);
238
+ }
239
+ writeLayerCss(options) {
240
+ return emptyWriteCssResult(options.outfile);
241
+ }
242
+ writeSplitCss(options) {
243
+ return emptyWriteFilesResult(options.outdir ?? "");
244
+ }
245
+ isEmpty() {
246
+ return true;
247
+ }
248
+ atoms() {
249
+ return [];
250
+ }
251
+ recipes() {
252
+ return [];
253
+ }
254
+ slotRecipes() {
255
+ return [];
256
+ }
257
+ encodedRecipes() {
258
+ return { base: [], variants: [], atomic: [] };
259
+ }
260
+ staticPatternAtoms() {
261
+ return { atoms: [], diagnostics: [] };
262
+ }
263
+ getFile() {
264
+ return null;
265
+ }
266
+ fileManifest() {
267
+ return [];
268
+ }
269
+ summary() {
270
+ return { filesProcessed: 0, atomCount: 0, recipeCount: 0, slotRecipeCount: 0 };
271
+ }
272
+ compile() {
273
+ return emptyCompileOutput();
274
+ }
275
+ getLayerCss(_options) {
276
+ return emptyCompileOutput();
277
+ }
278
+ getSplitCss(_options) {
279
+ return [];
280
+ }
281
+ buildInfo = fallbackBuildInfo;
282
+ designSystem = fallbackDesignSystem;
283
+ generateArtifacts() {
284
+ return [];
285
+ }
286
+ generateArtifact() {
287
+ return void 0;
288
+ }
289
+ generateAffectedArtifacts() {
290
+ return [];
291
+ }
292
+ diagnostics() {
293
+ return [];
294
+ }
295
+ };
296
+ var fallback = {
297
+ startTracing() {
298
+ return false;
299
+ },
300
+ flushTracing() {
301
+ },
302
+ shutdownTracing() {
303
+ return false;
304
+ },
305
+ compile() {
306
+ return emptyCompileOutput();
307
+ },
308
+ scanImports() {
309
+ return { imports: [], diagnostics: [] };
310
+ },
311
+ matchImports() {
312
+ return [];
313
+ },
314
+ extractCalls() {
315
+ return { calls: [], diagnostics: [] };
316
+ },
317
+ extractJsx() {
318
+ return { jsx: [], diagnostics: [] };
319
+ },
320
+ extract() {
321
+ return { calls: [], jsx: [], diagnostics: [] };
322
+ },
323
+ extractDebug() {
324
+ return { imports: [], matched: [], calls: [], jsx: [], diagnostics: [] };
325
+ },
326
+ Extractor: FallbackExtractor,
327
+ Compiler: FallbackCompiler
328
+ };
329
+ function emptyCompileOutput() {
330
+ return {
331
+ css: "",
332
+ manifest: { files: [], tokens: [] },
333
+ layerRanges: {},
334
+ diagnostics: []
335
+ };
336
+ }
337
+ function emptyWriteCssResult(path) {
338
+ return {
339
+ path,
340
+ ...emptyCompileOutput()
341
+ };
342
+ }
343
+ function emptyWriteFilesResult(root) {
344
+ return {
345
+ root,
346
+ paths: [],
347
+ files: []
348
+ };
349
+ }
350
+
351
+ // src/load-binary.ts
352
+ import { execFileSync } from "child_process";
353
+ import { existsSync, mkdirSync, readFileSync, rmSync } from "fs";
354
+ import { createRequire } from "module";
355
+ import { dirname, join } from "path";
356
+ import { fileURLToPath } from "url";
357
+ var bindingUrl = new URL("../binding.cjs", import.meta.url);
358
+ var webContainerWasiPackage = "@pandacss/compiler-wasm32-wasi";
359
+ function loadNativeBinding() {
360
+ const bindingPath = resolveBindingPath();
361
+ if (!bindingPath) return void 0;
362
+ const require2 = createRequire(bindingPath);
363
+ try {
364
+ return require2(bindingPath);
365
+ } catch (error) {
366
+ if (!isWebContainer()) throw error;
367
+ return loadWebContainerBinding(require2, bindingPath, error);
368
+ }
369
+ }
370
+ function resolveBindingPath() {
371
+ if (bindingUrl.protocol === "file:") {
372
+ const bindingPath = fileURLToPath(bindingUrl);
373
+ if (existsSync(bindingPath)) return bindingPath;
374
+ }
375
+ return fallbackBindingPaths().find((path) => existsSync(path));
376
+ }
377
+ function fallbackBindingPaths() {
378
+ const cwd = process.cwd();
379
+ const paths = [join(cwd, "packages/compiler/binding.cjs")];
380
+ if (isCompilerPackageRoot(cwd)) {
381
+ paths.unshift(join(cwd, "binding.cjs"));
382
+ }
383
+ return paths;
384
+ }
385
+ function isCompilerPackageRoot(cwd) {
386
+ try {
387
+ const packageJson = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
388
+ return packageJson.name === "@pandacss/compiler";
389
+ } catch {
390
+ return false;
391
+ }
392
+ }
393
+ function isWebContainer() {
394
+ const versions = process.versions;
395
+ return Boolean(versions.webcontainer);
396
+ }
397
+ function resolveWebContainerBinding(version, root = "/tmp") {
398
+ const baseDir = join(root, `pandacss-compiler-${version}`);
399
+ return {
400
+ baseDir,
401
+ bindingPackage: `${webContainerWasiPackage}@${version}`,
402
+ bindingEntry: join(baseDir, "node_modules", webContainerWasiPackage, "compiler.wasi.cjs")
403
+ };
404
+ }
405
+ function loadWebContainerBinding(require2, bindingPath, nativeError) {
406
+ const version = readCompilerVersion(require2, dirname(bindingPath));
407
+ const { baseDir, bindingPackage, bindingEntry } = resolveWebContainerBinding(version);
408
+ if (!existsSync(bindingEntry)) {
409
+ rmSync(baseDir, { recursive: true, force: true });
410
+ mkdirSync(baseDir, { recursive: true });
411
+ execFileSync("pnpm", ["i", bindingPackage], {
412
+ cwd: baseDir,
413
+ stdio: "inherit"
414
+ });
415
+ }
416
+ try {
417
+ return require2(bindingEntry);
418
+ } catch (fallbackError) {
419
+ throw new Error("Failed to load @pandacss/compiler WebContainer WASI fallback", {
420
+ cause: chainError(nativeError, fallbackError)
421
+ });
422
+ }
423
+ }
424
+ function readCompilerVersion(require2, packageRoot) {
425
+ try {
426
+ const packageJsonPath = require2.resolve("@pandacss/compiler/package.json");
427
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf8"));
428
+ return packageJson.version;
429
+ } catch {
430
+ const packageJson = JSON.parse(readFileSync(join(packageRoot, "package.json"), "utf8"));
431
+ return packageJson.version;
432
+ }
433
+ }
434
+ function chainError(primary, cause) {
435
+ if (primary instanceof Error) {
436
+ primary.cause = cause;
437
+ return primary;
438
+ }
439
+ return cause;
440
+ }
441
+
442
+ // src/index.ts
443
+ import { createUsageReport } from "@pandacss/compiler-shared";
444
+
445
+ // src/driver.ts
446
+ import {
447
+ BaseDriver,
448
+ collectParseDiagnostics,
449
+ diagnosticsPass,
450
+ normalizeDiagnostics
451
+ } from "@pandacss/compiler-shared";
452
+ import {
453
+ compilePreset,
454
+ defaultImportMap,
455
+ diffConfig,
456
+ loadConfig,
457
+ mergeExcludes,
458
+ readPackageIdentity,
459
+ resolveSmartInclude,
460
+ syncExports,
461
+ toPosixRelative,
462
+ toRelativeKey
463
+ } from "@pandacss/config";
464
+
465
+ // src/design-system.ts
466
+ import "@pandacss/compiler-shared";
467
+ import { readPandaVersion } from "@pandacss/config";
468
+ function hydrateDesignSystem(compiler, chain, consumerTokenPaths = []) {
469
+ if (!chain || chain.length === 0) return [];
470
+ const pandaVersion = readPandaVersion();
471
+ const diagnostics = [];
472
+ for (const ds of chain) diagnostics.push(...hydrateLevel(compiler, ds, pandaVersion, consumerTokenPaths));
473
+ return diagnostics;
474
+ }
475
+ function hydrateLevel(compiler, ds, pandaVersion, consumerTokenPaths) {
476
+ const compat = compiler.designSystem.validate(ds.manifest, { pandaVersion });
477
+ if (!compat.ok) throw incompatibleManifestError(compiler, ds, compat.reason, pandaVersion);
478
+ const diagnostics = [];
479
+ let buildInfo;
480
+ try {
481
+ const content = compiler.fs.readFile(ds.buildInfoPath);
482
+ if (content == null) throw new Error(`file not found`);
483
+ buildInfo = JSON.parse(content);
484
+ } catch (error) {
485
+ if (!tryStaleFallback(compiler, ds, diagnostics)) throw hydrateReadError(ds, error);
486
+ }
487
+ if (buildInfo) {
488
+ const result = compiler.designSystem.load(ds.manifest, { buildInfo, pandaVersion });
489
+ if (!result.ok && !tryStaleFallback(compiler, ds, diagnostics)) throw hydrateLoadError(ds, result.reason);
490
+ }
491
+ diagnostics.push(...tokenConflictDiagnostics(ds, consumerTokenPaths));
492
+ return diagnostics;
493
+ }
494
+ function tryStaleFallback(compiler, ds, diagnostics) {
495
+ if (ds.files.length === 0) return false;
496
+ const sources = compiler.scan({ include: ds.files, cwd: compiler.path.dirname(ds.manifestPath) });
497
+ if (sources.length === 0) return false;
498
+ compiler.parseFiles(sources);
499
+ diagnostics.push({
500
+ code: "design_system_buildinfo_stale",
501
+ severity: "warning",
502
+ category: "designSystem",
503
+ message: `Re-extracting ${JSON.stringify(ds.name)} from source; rebuild it with \`panda lib\` to restore the fast path.`
504
+ });
505
+ return true;
506
+ }
507
+ function tokenConflictDiagnostics(ds, consumerTokenPaths) {
508
+ if (consumerTokenPaths.length === 0 || ds.tokenPaths.length === 0) return [];
509
+ const designSystemTokenPaths = new Set(ds.tokenPaths);
510
+ const conflicts = [...new Set(consumerTokenPaths.filter((path) => designSystemTokenPaths.has(path)))].sort();
511
+ return conflicts.map((path) => ({
512
+ code: "design_system_token_conflict",
513
+ severity: "warning",
514
+ category: "designSystem",
515
+ message: `Token ${JSON.stringify(path)} is defined by both ${JSON.stringify(ds.name)} and this config; the local value wins.`
516
+ }));
517
+ }
518
+ function incompatibleManifestError(compiler, ds, reason, pandaVersion) {
519
+ if (reason === "schemaVersion") {
520
+ return new Error(
521
+ `Failed to hydrate designSystem ${JSON.stringify(ds.name)} from ${JSON.stringify(ds.manifestPath)}: manifest schemaVersion ${ds.manifest.schemaVersion} is incompatible with this compiler (expected ${compiler.designSystem.schemaVersion}).`
522
+ );
523
+ }
524
+ const running = pandaVersion ? ` (you are on ${pandaVersion})` : "";
525
+ return new Error(
526
+ `Failed to hydrate designSystem ${JSON.stringify(ds.name)}: manifest requires Panda ${ds.manifest.panda}${running}.`
527
+ );
528
+ }
529
+ function hydrateReadError(ds, error) {
530
+ return new Error(
531
+ `Failed to hydrate designSystem ${JSON.stringify(ds.name)} from ${JSON.stringify(ds.buildInfoPath)}: ${errorMessage(error)}`
532
+ );
533
+ }
534
+ function hydrateLoadError(ds, reason) {
535
+ return new Error(
536
+ `Failed to hydrate designSystem ${JSON.stringify(ds.name)} from ${JSON.stringify(ds.buildInfoPath)}: incompatible buildInfo ${reason}.`
537
+ );
538
+ }
539
+ function errorMessage(error) {
540
+ return error instanceof Error ? error.message : String(error);
541
+ }
542
+
543
+ // src/driver.ts
544
+ var DEFAULT_DESIGN_SYSTEM_LIB_OUTDIR = "dist";
545
+ var DEFAULT_DESIGN_SYSTEM_LIB_FILES = ["./**/*.{js,mjs}"];
546
+ async function createNodeDriver(options) {
547
+ const loaded = await loadConfig({ cwd: options.cwd, file: options.configPath });
548
+ if (options.include?.length) applyIncludeOverride(loaded, options.cwd, options.include);
549
+ return new NodeDriver(options, loaded);
550
+ }
551
+ function applyIncludeOverride(loaded, cwd, include) {
552
+ const deps = new Set(loaded.dependencies);
553
+ const resolved = resolveSmartInclude(include, cwd, deps);
554
+ loaded.config.include = resolved.include;
555
+ if (resolved.excludes.length > 0) {
556
+ const existing = Array.isArray(loaded.config.exclude) ? loaded.config.exclude : void 0;
557
+ loaded.config.exclude = mergeExcludes(existing, resolved.excludes);
558
+ }
559
+ loaded.dependencies = Array.from(deps);
560
+ }
561
+ var NodeDriver = class extends BaseDriver {
562
+ #options;
563
+ #loaded;
564
+ #designSystemDiagnostics;
565
+ #designSystemPreset;
566
+ #designSystemArtifactSnapshot;
567
+ #designSystemWatchTargets;
568
+ constructor(options, loaded) {
569
+ const built = buildFromConfig(loaded);
570
+ super(built.compiler);
571
+ this.#options = options;
572
+ this.#loaded = loaded;
573
+ this.#designSystemDiagnostics = built.designSystemDiagnostics;
574
+ this.#designSystemArtifactSnapshot = designSystemArtifactSnapshot(this.compiler, loaded);
575
+ }
576
+ get designSystemDiagnostics() {
577
+ return this.#designSystemDiagnostics;
578
+ }
579
+ get config() {
580
+ return this.#loaded.config;
581
+ }
582
+ get configPath() {
583
+ return this.#loaded.path;
584
+ }
585
+ get configDependencies() {
586
+ return this.#loaded.dependencies;
587
+ }
588
+ designSystemWatchTargets() {
589
+ return this.#designSystemWatchTargets ??= (this.#loaded.metadata?.designSystem ?? []).map((ds) => {
590
+ const base = this.compiler.path.dirname(ds.manifestPath);
591
+ const presetPath = realpathIfExists(this.compiler, this.compiler.path.resolve(ds.manifest.preset, base));
592
+ const sourceFiles = ds.files.length > 0 ? this.compiler.scan({ include: ds.files, cwd: base }).map((file) => realpathIfExists(this.compiler, file)) : [];
593
+ return {
594
+ name: ds.name,
595
+ manifestPath: realpathIfExists(this.compiler, ds.manifestPath),
596
+ buildInfoPath: realpathIfExists(this.compiler, ds.buildInfoPath),
597
+ presetPath,
598
+ sourceFiles: [...new Set(sourceFiles)]
599
+ };
600
+ });
601
+ }
602
+ isDesignSystemFile(file) {
603
+ const target = this.compiler.path.realpath(file);
604
+ for (const watchTarget of this.#designSystemWatchTargets ?? this.designSystemWatchTargets()) {
605
+ if ([watchTarget.manifestPath, watchTarget.buildInfoPath, watchTarget.presetPath].some(
606
+ (path) => this.compiler.path.realpath(path) === target
607
+ )) {
608
+ return "artifact";
609
+ }
610
+ if (watchTarget.sourceFiles.some((path) => this.compiler.path.realpath(path) === target)) {
611
+ return "source";
612
+ }
613
+ }
614
+ return false;
615
+ }
616
+ async syncDesignSystemFileChange(change) {
617
+ const kind = this.isDesignSystemFile(change.path);
618
+ if (kind === "artifact") {
619
+ const diff = await this.reload();
620
+ if (diff.hasChanged) this.parseFiles();
621
+ return diff.hasChanged;
622
+ }
623
+ if (kind === "source") return this.applyChange(change);
624
+ return false;
625
+ }
626
+ async reload() {
627
+ const next = await loadConfig({ cwd: this.#options.cwd, file: this.#options.configPath });
628
+ if (this.#options.include?.length) applyIncludeOverride(next, this.#options.cwd, this.#options.include);
629
+ const diff = diffConfig(this.#loaded, next);
630
+ const nextDesignSystemArtifactSnapshot = designSystemArtifactSnapshot(this.compiler, next);
631
+ const designSystemArtifactsChanged = this.#designSystemArtifactSnapshot !== nextDesignSystemArtifactSnapshot;
632
+ if (diff.hasChanged || designSystemArtifactsChanged) {
633
+ this.#loaded = next;
634
+ const built = buildFromConfig(next);
635
+ this.setCompiler(built.compiler);
636
+ this.#designSystemDiagnostics = built.designSystemDiagnostics;
637
+ this.#designSystemPreset = void 0;
638
+ this.#designSystemArtifactSnapshot = nextDesignSystemArtifactSnapshot;
639
+ this.#designSystemWatchTargets = void 0;
640
+ }
641
+ return designSystemArtifactsChanged && !diff.hasChanged ? { ...diff, hasChanged: true } : diff;
642
+ }
643
+ applyChange(change) {
644
+ if (change.kind === "unlink") {
645
+ return this.compiler.removeFile(change.path);
646
+ }
647
+ if (change.kind === "change") {
648
+ if (change.content == null) {
649
+ if (this.compiler.refreshFile(change.path)) return true;
650
+ this.compiler.parseFile(change.path);
651
+ return true;
652
+ }
653
+ if (this.compiler.refreshFileSource(change.path, change.content)) return true;
654
+ this.compiler.parseFileSource(change.path, change.content);
655
+ return true;
656
+ }
657
+ if (change.content == null) {
658
+ this.compiler.parseFile(change.path);
659
+ return true;
660
+ }
661
+ this.compiler.parseFileSource(change.path, change.content);
662
+ return true;
663
+ }
664
+ getOutdir(outdir) {
665
+ return this.compiler.path.resolve(this.getConfiguredOutdir(outdir));
666
+ }
667
+ async writeDesignSystemLib(options = {}) {
668
+ if (!this.#loaded.path) {
669
+ throw new Error(
670
+ "panda lib requires a resolved config file to compile the design system preset. Run `panda init`, or check --config/--cwd."
671
+ );
672
+ }
673
+ const parsed = this.parseDesignSystemLib();
674
+ if (!diagnosticsPass(parsed.diagnostics, { maxWarnings: options.maxWarnings }))
675
+ return skippedDesignSystemLib(parsed);
676
+ const preset = await this.compileDesignSystemPreset();
677
+ return this.writeDesignSystemLibArtifacts(options, preset, parsed);
678
+ }
679
+ codegen(options) {
680
+ const outdir = this.getOutdir(options?.outdir);
681
+ const cwd = options?.cwd ?? this.#options.cwd;
682
+ const prepareHooks = this.#loaded.hostHooks?.["codegen:prepare"] ?? [];
683
+ const doneHooks = this.#loaded.hostHooks?.["codegen:done"] ?? [];
684
+ const files = prepareHooks.length > 0 ? this.codegenWithPrepareHooks(prepareHooks, outdir, cwd, options) : super.codegen(options);
685
+ for (const entry of doneHooks) {
686
+ const handler = resolveHookHandler(entry.value, "codegen:done");
687
+ handler({ files, outdir, cwd });
688
+ }
689
+ return files;
690
+ }
691
+ codegenWithPrepareHooks(hooks, outdir, cwd, options) {
692
+ let artifacts = this.compiler.generateArtifacts(toGenerateArtifactOptions(options));
693
+ for (const entry of hooks) {
694
+ const handler = resolveHookHandler(entry.value, "codegen:prepare");
695
+ const next = handler({ artifacts, outdir, cwd });
696
+ if (next !== void 0) {
697
+ if (!Array.isArray(next)) {
698
+ throw new Error("Invalid codegen:prepare hook result. Expected an artifact array or undefined.");
699
+ }
700
+ artifacts = next;
701
+ }
702
+ }
703
+ return this.compiler.writeArtifacts({
704
+ outdir,
705
+ cwd,
706
+ forceImportExtension: options?.forceImportExtension,
707
+ artifacts
708
+ });
709
+ }
710
+ isConfigFile(file) {
711
+ const target = this.compiler.path.realpath(file);
712
+ const configPath = this.compiler.path.realpath(this.#loaded.path);
713
+ if (configPath === target) return true;
714
+ return this.#loaded.dependencies.some((dependency) => {
715
+ const dependencyPath = this.compiler.path.resolve(dependency, this.#options.cwd);
716
+ return this.compiler.path.realpath(dependencyPath) === target;
717
+ });
718
+ }
719
+ parseDesignSystemLib() {
720
+ const parsed = this.parseFiles();
721
+ const parseDiagnostics = collectParseDiagnostics(parsed, {
722
+ normalizeFile: (file) => stabilizePath(this.#options.cwd, file)
723
+ });
724
+ const diagnostics = normalizeDiagnostics([...parseDiagnostics, ...this.compiler.diagnostics()], {
725
+ normalizeFile: (file) => stabilizePath(this.#options.cwd, file)
726
+ });
727
+ return { parsedFileCount: parsed.length, diagnostics };
728
+ }
729
+ async compileDesignSystemPreset() {
730
+ return this.#designSystemPreset ??= await compilePreset({
731
+ configPath: this.#loaded.path,
732
+ cwd: this.#options.cwd
733
+ });
734
+ }
735
+ writeDesignSystemLibArtifacts(options, preset, parsed) {
736
+ const identity = readPackageIdentity(this.#options.cwd);
737
+ const pandaRange = options.panda ?? identity.pandaPeer ?? "*";
738
+ const outdir = options.outdir ?? DEFAULT_DESIGN_SYSTEM_LIB_OUTDIR;
739
+ const outRoot = this.compiler.path.resolve(outdir);
740
+ const manifestPath = this.compiler.path.join([outRoot, "panda.lib.json"]);
741
+ const buildInfoPath = this.compiler.path.join([outRoot, "panda.buildinfo.json"]);
742
+ const presetPath = this.compiler.path.join([outRoot, "panda.preset.mjs"]);
743
+ const info = this.compiler.buildInfo.create({ panda: pandaRange });
744
+ const buildInfo = this.compiler.buildInfo.normalize(info, {
745
+ mapModuleKey: (key) => toRelativeKey(key, this.#options.cwd)
746
+ });
747
+ const manifest = this.compiler.designSystem.create({
748
+ name: identity.name,
749
+ version: identity.version,
750
+ panda: pandaRange,
751
+ preset: "./panda.preset.mjs",
752
+ buildInfo: "./panda.buildinfo.json",
753
+ importMap: defaultImportMap(identity.name),
754
+ designSystem: typeof this.config.designSystem === "string" ? this.config.designSystem : void 0,
755
+ files: options.files ?? inferDesignSystemLibFiles(this.compiler, this.#options.cwd, outRoot, buildInfo)
756
+ });
757
+ this.compiler.writeArtifacts({
758
+ outdir,
759
+ cwd: this.#options.cwd,
760
+ artifacts: [
761
+ {
762
+ id: "design-system-lib",
763
+ files: [
764
+ {
765
+ path: "panda.lib.json",
766
+ code: `${JSON.stringify(manifest, null, 2)}
767
+ `,
768
+ dependencies: []
769
+ },
770
+ {
771
+ path: "panda.buildinfo.json",
772
+ code: JSON.stringify(buildInfo, null, options.minify ? 0 : 2),
773
+ dependencies: []
774
+ },
775
+ {
776
+ path: "panda.preset.mjs",
777
+ code: preset.code,
778
+ dependencies: []
779
+ }
780
+ ]
781
+ }
782
+ ]
783
+ });
784
+ const exportsChanged = syncPackageExports(this.compiler, identity.packagePath, {
785
+ manifestPath,
786
+ presetPath
787
+ });
788
+ return {
789
+ manifestPath,
790
+ buildInfoPath,
791
+ presetPath,
792
+ exportsChanged,
793
+ parsedFileCount: parsed.parsedFileCount,
794
+ diagnostics: parsed.diagnostics
795
+ };
796
+ }
797
+ };
798
+ function resolveHookHandler(value, name) {
799
+ if (typeof value === "function") return value;
800
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
801
+ throw new Error(`Invalid ${name} hook. Expected a function or { filter, handler }.`);
802
+ }
803
+ const handler = value.handler;
804
+ if (typeof handler !== "function") {
805
+ throw new Error(`Invalid ${name} hook. Expected a function or { filter, handler }.`);
806
+ }
807
+ return handler;
808
+ }
809
+ function skippedDesignSystemLib(parsed) {
810
+ return {
811
+ manifestPath: "",
812
+ buildInfoPath: "",
813
+ presetPath: "",
814
+ exportsChanged: false,
815
+ parsedFileCount: parsed.parsedFileCount,
816
+ diagnostics: parsed.diagnostics
817
+ };
818
+ }
819
+ function syncPackageExports(compiler, packagePath, paths) {
820
+ const base = compiler.path.dirname(packagePath);
821
+ const entries = {
822
+ "./panda.lib.json": toPosixRelative(base, paths.manifestPath),
823
+ "./preset": toPosixRelative(base, paths.presetPath)
824
+ };
825
+ const packageJson = compiler.fs.readFile(packagePath);
826
+ if (packageJson == null) {
827
+ throw new Error(`Could not read package.json at ${JSON.stringify(packagePath)}.`);
828
+ }
829
+ const result = syncExports({ packageJson, entries });
830
+ if (result.changed) {
831
+ compiler.writeArtifacts({
832
+ outdir: base,
833
+ artifacts: [
834
+ {
835
+ id: "design-system-lib-package",
836
+ files: [{ path: "package.json", code: result.json, dependencies: [] }]
837
+ }
838
+ ]
839
+ });
840
+ }
841
+ return result.changed;
842
+ }
843
+ function stabilizePath(cwd, file) {
844
+ const relativePath = toRelativeKey(file, cwd);
845
+ return relativePath && !relativePath.startsWith("..") ? relativePath : file;
846
+ }
847
+ function buildFromConfig(loaded) {
848
+ const compiler = createCompilerFromSnapshot({
849
+ config: loaded.config,
850
+ callbacks: loaded.callbacks,
851
+ hooks: loaded.hooks
852
+ });
853
+ const designSystemDiagnostics = hydrateDesignSystem(
854
+ compiler,
855
+ loaded.metadata?.designSystem,
856
+ loaded.metadata?.userTokenPaths ?? []
857
+ );
858
+ return { compiler, designSystemDiagnostics };
859
+ }
860
+ function designSystemArtifactSnapshot(compiler, loaded) {
861
+ return JSON.stringify(
862
+ loaded.metadata?.designSystem?.map((ds) => ({
863
+ name: ds.name,
864
+ specifier: ds.specifier,
865
+ manifest: ds.manifest,
866
+ manifestPath: ds.manifestPath,
867
+ buildInfoPath: ds.buildInfoPath,
868
+ buildInfo: compiler.fs.readFile(ds.buildInfoPath) ?? "",
869
+ files: ds.files,
870
+ tokenPaths: ds.tokenPaths
871
+ })) ?? []
872
+ );
873
+ }
874
+ function realpathIfExists(compiler, path) {
875
+ return compiler.fs.exists(path) ? compiler.path.realpath(path) : path;
876
+ }
877
+ function inferDesignSystemLibFiles(compiler, cwd, outRoot, buildInfo) {
878
+ const files = Object.keys(buildInfo.modules).filter((key) => !key.startsWith("buildinfo:")).map((key) => {
879
+ const file = compiler.path.resolve(key, cwd);
880
+ return toPosixRelative(outRoot, file);
881
+ });
882
+ return files.length > 0 ? [...new Set(files)] : DEFAULT_DESIGN_SYSTEM_LIB_FILES;
883
+ }
884
+ function toGenerateArtifactOptions(options) {
885
+ return options?.forceImportExtension === void 0 ? void 0 : { forceImportExtension: options.forceImportExtension };
886
+ }
887
+
888
+ // src/index.ts
889
+ var binding = loadNativeBinding() ?? fallback;
890
+ var nativeCompilerFromConfig = "fromConfig" in binding.Compiler && typeof binding.Compiler.fromConfig === "function" ? binding.Compiler.fromConfig.bind(binding.Compiler) : void 0;
891
+ function compile(input) {
892
+ return binding.compile(input);
893
+ }
894
+ function startTracing(options) {
895
+ return binding.startTracing?.(options) ?? false;
896
+ }
897
+ function flushTracing() {
898
+ binding.flushTracing?.();
899
+ }
900
+ function shutdownTracing() {
901
+ return binding.shutdownTracing?.() ?? false;
902
+ }
903
+ function createCompiler(config, options) {
904
+ return build(config, options?.callbacks ?? {}, options);
905
+ }
906
+ function createCompilerFromSnapshot(snapshot, options) {
907
+ const callbacks = mergeCallbacks(snapshot.callbacks, options?.callbacks);
908
+ const hooks = mergeHooks(snapshot.hooks, options?.hooks);
909
+ return build(snapshot.config, callbacks, { ...options, hooks });
910
+ }
911
+ function getBindingInfo() {
912
+ return {
913
+ native: binding !== fallback
914
+ };
915
+ }
916
+ function build(config, callbacks, options) {
917
+ assertProjectCallbacks(config, callbacks);
918
+ assertProjectHooks(options?.hooks, callbacks);
919
+ if (!nativeCompilerFromConfig) {
920
+ throw new Error("createCompiler is not available in this binding");
921
+ }
922
+ const prepared = prepareCompilerConfig(config);
923
+ const compiler = nativeCompilerFromConfig(prepared, toNativeOptions(options), createUtilityValuesCallbacks(callbacks));
924
+ registerCallbacks(compiler, callbacks, options?.hooks, compiler.token_dictionary?.());
925
+ attachFileSystem(compiler);
926
+ attachPathSystem(compiler);
927
+ attachBuildInfo(compiler);
928
+ attachDesignSystem(compiler);
929
+ attachInspection(compiler);
930
+ return compiler;
931
+ }
932
+ function attachFileSystem(compiler) {
933
+ Object.defineProperty(compiler, "fs", {
934
+ value: {
935
+ readFile: (path) => compiler.readFile(path),
936
+ exists: (path) => compiler.exists(path)
937
+ },
938
+ enumerable: false,
939
+ configurable: true
940
+ });
941
+ }
942
+ function attachPathSystem(compiler) {
943
+ Object.defineProperty(compiler, "path", {
944
+ value: {
945
+ realpath: (path) => compiler.realpath(path),
946
+ resolve: (path, cwd) => compiler.resolvePath(path, cwd),
947
+ join: (parts) => compiler.joinPath(parts),
948
+ dirname: (path) => compiler.dirname(path)
949
+ },
950
+ enumerable: false,
951
+ configurable: true
952
+ });
953
+ }
954
+ function attachBuildInfo(compiler) {
955
+ Object.defineProperty(compiler, "buildInfo", {
956
+ enumerable: false,
957
+ configurable: true,
958
+ get() {
959
+ const api = new BuildInfo2(compiler);
960
+ Object.defineProperty(compiler, "buildInfo", {
961
+ value: api,
962
+ enumerable: false,
963
+ configurable: true
964
+ });
965
+ return api;
966
+ }
967
+ });
968
+ }
969
+ function attachDesignSystem(compiler) {
970
+ Object.defineProperty(compiler, "designSystem", {
971
+ enumerable: false,
972
+ configurable: true,
973
+ get() {
974
+ const api = new DesignSystem2(toDesignSystemBinding(compiler), compiler.buildInfo);
975
+ Object.defineProperty(compiler, "designSystem", {
976
+ value: api,
977
+ enumerable: false,
978
+ configurable: true
979
+ });
980
+ return api;
981
+ }
982
+ });
983
+ }
984
+ function attachInspection(compiler) {
985
+ Object.defineProperty(compiler, "inspectFile", {
986
+ enumerable: false,
987
+ configurable: true,
988
+ value: (input) => inspectFile(compiler, input)
989
+ });
990
+ Object.defineProperty(compiler, "inspectFiles", {
991
+ enumerable: false,
992
+ configurable: true,
993
+ value: (files) => inspectFiles(compiler, files)
994
+ });
995
+ }
996
+ function toDesignSystemBinding(compiler) {
997
+ return {
998
+ createManifest: (input) => compiler.createDesignSystemManifest(input),
999
+ manifestSchemaVersion: () => compiler.designSystemManifestSchemaVersion(),
1000
+ resolveChain: (manifests) => compiler.resolveDesignSystemChain(manifests)
1001
+ };
1002
+ }
1003
+ function toNativeOptions(options) {
1004
+ if (!options || options.crossFile === void 0) return void 0;
1005
+ return { crossFile: options.crossFile };
1006
+ }
1007
+ function createUtilityValuesCallbacks(callbacks) {
1008
+ const utilityValues = callbacks["utility.values"];
1009
+ if (!utilityValues || Object.keys(utilityValues).length === 0) return void 0;
1010
+ return Object.fromEntries(
1011
+ Object.entries(utilityValues).map(([id, callback]) => [
1012
+ id,
1013
+ (tokenDictionary) => callback((category) => getTokenCategoryValues(category, tokenDictionary))
1014
+ ])
1015
+ );
1016
+ }
1017
+
1018
+ export {
1019
+ createNodeDriver,
1020
+ NodeDriver,
1021
+ compile,
1022
+ startTracing,
1023
+ flushTracing,
1024
+ shutdownTracing,
1025
+ createCompiler,
1026
+ createCompilerFromSnapshot,
1027
+ getBindingInfo,
1028
+ createUsageReport
1029
+ };