@griffel/transform 3.0.0 → 3.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.
Files changed (46) hide show
  1. package/LICENSE.md +21 -0
  2. package/package.json +9 -6
  3. package/src/constants.mjs +3 -0
  4. package/src/constants.mjs.map +1 -0
  5. package/{evaluation → src/evaluation}/astEvaluator.d.mts +2 -2
  6. package/src/evaluation/astEvaluator.mjs +90 -0
  7. package/src/evaluation/astEvaluator.mjs.map +1 -0
  8. package/{evaluation → src/evaluation}/batchEvaluator.d.mts +4 -4
  9. package/src/evaluation/batchEvaluator.mjs +54 -0
  10. package/src/evaluation/batchEvaluator.mjs.map +1 -0
  11. package/src/evaluation/evalCache.mjs +65 -0
  12. package/src/evaluation/evalCache.mjs.map +1 -0
  13. package/{evaluation → src/evaluation}/fluentTokensPlugin.d.mts +1 -1
  14. package/src/evaluation/fluentTokensPlugin.mjs +70 -0
  15. package/src/evaluation/fluentTokensPlugin.mjs.map +1 -0
  16. package/{evaluation → src/evaluation}/module.d.mts +13 -1
  17. package/src/evaluation/module.mjs +207 -0
  18. package/src/evaluation/module.mjs.map +1 -0
  19. package/src/evaluation/process.mjs +28 -0
  20. package/src/evaluation/process.mjs.map +1 -0
  21. package/{evaluation → src/evaluation}/types.d.mts +1 -1
  22. package/src/evaluation/types.mjs +2 -0
  23. package/src/evaluation/types.mjs.map +1 -0
  24. package/{evaluation → src/evaluation}/vmEvaluator.d.mts +2 -2
  25. package/src/evaluation/vmEvaluator.mjs +33 -0
  26. package/src/evaluation/vmEvaluator.mjs.map +1 -0
  27. package/src/index.mjs +9 -0
  28. package/src/index.mjs.map +1 -0
  29. package/{transformSync.d.mts → src/transformSync.d.mts} +4 -3
  30. package/src/transformSync.mjs +252 -0
  31. package/src/transformSync.mjs.map +1 -0
  32. package/{types.d.mts → src/types.d.mts} +1 -1
  33. package/src/types.mjs +2 -0
  34. package/src/types.mjs.map +1 -0
  35. package/src/utils/convertESMtoCJS.mjs +203 -0
  36. package/src/utils/convertESMtoCJS.mjs.map +1 -0
  37. package/{utils → src/utils}/dedupeCSSRules.d.mts +1 -1
  38. package/src/utils/dedupeCSSRules.mjs +19 -0
  39. package/src/utils/dedupeCSSRules.mjs.map +1 -0
  40. package/CHANGELOG.md +0 -80
  41. package/transform.js +0 -933
  42. /package/{constants.d.mts → src/constants.d.mts} +0 -0
  43. /package/{evaluation → src/evaluation}/evalCache.d.mts +0 -0
  44. /package/{evaluation → src/evaluation}/process.d.mts +0 -0
  45. /package/{index.d.mts → src/index.d.mts} +0 -0
  46. /package/{utils → src/utils}/convertESMtoCJS.d.mts +0 -0
package/transform.js DELETED
@@ -1,933 +0,0 @@
1
- import shakerEvaluator from "@griffel/transform-shaker";
2
- import { default as default2 } from "@griffel/transform-shaker";
3
- import fs from "node:fs";
4
- import NativeModule from "node:module";
5
- import path from "node:path";
6
- import vm from "node:vm";
7
- import createDebug from "debug";
8
- import { parseSync } from "oxc-parser";
9
- import MagicString from "magic-string";
10
- import { createHash } from "node:crypto";
11
- import { ScopeTracker, walk } from "oxc-walker";
12
- import { resolveStaticStyleRules, resolveResetStyleRules, resolveStyleRulesForSlots, normalizeCSSBucketEntry } from "@griffel/core";
13
- const ASSET_TAG_OPEN = "<griffel-asset>";
14
- const ASSET_TAG_CLOSE = "</griffel-asset>";
15
- const prop = (node, key) => node[key];
16
- function extractDeclaredNames(node) {
17
- switch (node.type) {
18
- case "Identifier":
19
- return [prop(node, "name")];
20
- case "ObjectPattern":
21
- return prop(node, "properties").flatMap((p) => {
22
- if (p.type === "RestElement") {
23
- return extractDeclaredNames(prop(p, "argument"));
24
- }
25
- return extractDeclaredNames(prop(p, "value"));
26
- });
27
- case "ArrayPattern":
28
- return prop(node, "elements").filter(Boolean).flatMap((el) => extractDeclaredNames(el));
29
- case "AssignmentPattern":
30
- return extractDeclaredNames(prop(node, "left"));
31
- default:
32
- return [];
33
- }
34
- }
35
- function convertESMtoCJS(code, filename) {
36
- const parseResult = parseSync(filename, code);
37
- if (parseResult.errors.length > 0) {
38
- throw new Error(
39
- `convertESMtoCJS: failed to parse "${filename}": ${parseResult.errors.map((e) => e.message).join(", ")}`
40
- );
41
- }
42
- const program = parseResult.program;
43
- let hasESM = false;
44
- for (const node of program.body) {
45
- if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration" || node.type === "ExportAllDeclaration") {
46
- hasESM = true;
47
- break;
48
- }
49
- }
50
- if (!hasESM) {
51
- return code;
52
- }
53
- const ms = new MagicString(code);
54
- const deferredExports = [];
55
- for (const node of program.body) {
56
- switch (node.type) {
57
- case "ImportDeclaration": {
58
- const source = prop(prop(node, "source"), "value");
59
- const specifiers = prop(node, "specifiers");
60
- if (specifiers.length === 0) {
61
- ms.overwrite(node.start, node.end, `require(${JSON.stringify(source)});`);
62
- } else {
63
- let defaultName = null;
64
- let namespaceName = null;
65
- const namedImports = [];
66
- for (const spec of specifiers) {
67
- if (spec.type === "ImportDefaultSpecifier") {
68
- defaultName = prop(prop(spec, "local"), "name");
69
- } else if (spec.type === "ImportNamespaceSpecifier") {
70
- namespaceName = prop(prop(spec, "local"), "name");
71
- } else if (spec.type === "ImportSpecifier") {
72
- const importedNode = prop(spec, "imported");
73
- const imported = importedNode.type === "Identifier" ? prop(importedNode, "name") : prop(importedNode, "value");
74
- const local = prop(prop(spec, "local"), "name");
75
- if (imported === local) {
76
- namedImports.push(imported);
77
- } else {
78
- namedImports.push(`${imported}: ${local}`);
79
- }
80
- }
81
- }
82
- const parts = [];
83
- if (namespaceName) {
84
- parts.push(`const ${namespaceName} = require(${JSON.stringify(source)});`);
85
- } else if (defaultName && namedImports.length > 0) {
86
- const tempVar = `_require$${defaultName}`;
87
- parts.push(`const ${tempVar} = require(${JSON.stringify(source)});`);
88
- parts.push(`const ${defaultName} = ${tempVar}.__esModule ? ${tempVar}.default : ${tempVar};`);
89
- parts.push(`const { ${namedImports.join(", ")} } = ${tempVar};`);
90
- } else if (defaultName) {
91
- const tempVar = `_require$${defaultName}`;
92
- parts.push(`const ${tempVar} = require(${JSON.stringify(source)});`);
93
- parts.push(`const ${defaultName} = ${tempVar}.__esModule ? ${tempVar}.default : ${tempVar};`);
94
- } else if (namedImports.length > 0) {
95
- parts.push(`const { ${namedImports.join(", ")} } = require(${JSON.stringify(source)});`);
96
- }
97
- ms.overwrite(node.start, node.end, parts.join("\n"));
98
- }
99
- break;
100
- }
101
- case "ExportNamedDeclaration": {
102
- const decl = prop(node, "declaration");
103
- if (decl) {
104
- ms.overwrite(node.start, decl.start, "");
105
- if (decl.type === "VariableDeclaration") {
106
- const names = prop(decl, "declarations").flatMap(
107
- (d) => extractDeclaredNames(prop(d, "id"))
108
- );
109
- deferredExports.push(...names);
110
- } else if (decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") {
111
- const id = prop(decl, "id");
112
- if (id) {
113
- deferredExports.push(prop(id, "name"));
114
- }
115
- }
116
- } else if (prop(node, "source")) {
117
- const source = prop(prop(node, "source"), "value");
118
- const parts = [];
119
- for (const spec of prop(node, "specifiers")) {
120
- const localNode = prop(spec, "local");
121
- const exportedNode = prop(spec, "exported");
122
- const local = localNode.type === "Identifier" ? prop(localNode, "name") : prop(localNode, "value");
123
- const exported = exportedNode.type === "Identifier" ? prop(exportedNode, "name") : prop(exportedNode, "value");
124
- parts.push(
125
- `exports[${JSON.stringify(exported)}] = require(${JSON.stringify(source)})[${JSON.stringify(local)}];`
126
- );
127
- }
128
- ms.overwrite(node.start, node.end, parts.join("\n"));
129
- } else {
130
- const parts = [];
131
- for (const spec of prop(node, "specifiers")) {
132
- const localNode = prop(spec, "local");
133
- const exportedNode = prop(spec, "exported");
134
- const local = localNode.type === "Identifier" ? prop(localNode, "name") : prop(localNode, "value");
135
- const exported = exportedNode.type === "Identifier" ? prop(exportedNode, "name") : prop(exportedNode, "value");
136
- parts.push(`exports[${JSON.stringify(exported)}] = ${local};`);
137
- }
138
- ms.overwrite(node.start, node.end, parts.join("\n"));
139
- }
140
- break;
141
- }
142
- case "ExportDefaultDeclaration": {
143
- const decl = prop(node, "declaration");
144
- if (decl.type === "FunctionDeclaration" || decl.type === "ClassDeclaration") {
145
- const id = prop(decl, "id");
146
- if (id) {
147
- ms.overwrite(node.start, decl.start, "");
148
- ms.appendLeft(node.end, `
149
- exports.default = ${prop(id, "name")};`);
150
- } else {
151
- ms.overwrite(node.start, decl.start, "exports.default = ");
152
- }
153
- } else {
154
- ms.overwrite(node.start, decl.start, "exports.default = ");
155
- if (code[node.end - 1] !== ";") {
156
- ms.appendLeft(node.end, ";");
157
- }
158
- }
159
- break;
160
- }
161
- case "ExportAllDeclaration": {
162
- const source = prop(prop(node, "source"), "value");
163
- const exportedNode = prop(node, "exported");
164
- if (exportedNode) {
165
- const name = exportedNode.type === "Identifier" ? prop(exportedNode, "name") : prop(exportedNode, "value");
166
- ms.overwrite(node.start, node.end, `exports[${JSON.stringify(name)}] = require(${JSON.stringify(source)});`);
167
- } else {
168
- ms.overwrite(node.start, node.end, `Object.assign(exports, require(${JSON.stringify(source)}));`);
169
- }
170
- break;
171
- }
172
- }
173
- }
174
- if (deferredExports.length > 0) {
175
- ms.append("\n" + deferredExports.map((name) => `exports.${name} = ${name};`).join("\n"));
176
- }
177
- ms.prepend('Object.defineProperty(exports, "__esModule", { value: true });\n');
178
- return ms.toString();
179
- }
180
- const debug$1 = createDebug("griffel:eval-cache");
181
- const fileHashes = /* @__PURE__ */ new Map();
182
- const evalCache = /* @__PURE__ */ new Map();
183
- const fileKeys = /* @__PURE__ */ new Map();
184
- const hash = (text) => createHash("sha1").update(text).digest("base64");
185
- let lastText = "";
186
- let lastHash = hash(lastText);
187
- const memoizedHash = (text) => {
188
- if (lastText !== text) {
189
- lastHash = hash(text);
190
- lastText = text;
191
- }
192
- return lastHash;
193
- };
194
- const toKey = (filename, exports$1) => exports$1.length > 0 ? `${filename}:${exports$1.join(",")}` : filename;
195
- const clear = () => {
196
- fileHashes.clear();
197
- evalCache.clear();
198
- fileKeys.clear();
199
- };
200
- const clearForFile = (filename) => {
201
- const keys = fileKeys.get(filename) ?? [];
202
- if (keys.length === 0) {
203
- return;
204
- }
205
- debug$1("clear-for-file", filename);
206
- keys.forEach((key) => {
207
- fileHashes.delete(key);
208
- evalCache.delete(key);
209
- });
210
- fileKeys.set(filename, []);
211
- };
212
- const has = ([filename, ...exports$1], text) => {
213
- const key = toKey(filename, exports$1);
214
- const textHash = memoizedHash(text);
215
- debug$1("has", `${key} ${textHash}`);
216
- return fileHashes.get(key) === textHash;
217
- };
218
- const get = ([filename, ...exports$1], text) => {
219
- const key = toKey(filename, exports$1);
220
- const textHash = memoizedHash(text);
221
- debug$1("get", `${key} ${textHash}`);
222
- if (fileHashes.get(key) !== textHash) {
223
- return void 0;
224
- }
225
- return evalCache.get(key);
226
- };
227
- const set = ([filename, ...exports$1], text, value) => {
228
- const key = toKey(filename, exports$1);
229
- const textHash = memoizedHash(text);
230
- debug$1("set", `${key} ${textHash}`);
231
- fileHashes.set(key, textHash);
232
- evalCache.set(key, value);
233
- if (!fileKeys.has(filename)) {
234
- fileKeys.set(filename, []);
235
- }
236
- fileKeys.get(filename).push(key);
237
- };
238
- const evalCache$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
239
- __proto__: null,
240
- clear,
241
- clearForFile,
242
- get,
243
- has,
244
- set
245
- }, Symbol.toStringTag, { value: "Module" }));
246
- const nextTick = (fn) => setTimeout(fn, 0);
247
- const platform = "browser";
248
- const arch = "browser";
249
- const execPath = "browser";
250
- const title = "browser";
251
- const pid = 1;
252
- const browser = true;
253
- const argv = [];
254
- const binding = function binding2() {
255
- throw new Error("No such module. (Possibly not yet loaded)");
256
- };
257
- const cwd = () => "/";
258
- const noop = () => {
259
- };
260
- const exit = noop;
261
- const kill = noop;
262
- const chdir = noop;
263
- const umask = noop;
264
- const dlopen = noop;
265
- const uptime = noop;
266
- const memoryUsage = noop;
267
- const uvCounters = noop;
268
- const features = {};
269
- const env = process.env;
270
- const mockProcess = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
271
- __proto__: null,
272
- arch,
273
- argv,
274
- binding,
275
- browser,
276
- chdir,
277
- cwd,
278
- dlopen,
279
- env,
280
- execPath,
281
- exit,
282
- features,
283
- kill,
284
- memoryUsage,
285
- nextTick,
286
- pid,
287
- platform,
288
- title,
289
- umask,
290
- uptime,
291
- uvCounters
292
- }, Symbol.toStringTag, { value: "Module" }));
293
- const debug = createDebug("griffel:module");
294
- let cache = {};
295
- const NOOP = () => {
296
- };
297
- function isError$1(e) {
298
- return e != null && typeof e === "object" && "message" in e && "stack" in e;
299
- }
300
- const createCustomDebug = (depth) => (namespaces, arg1, ...args) => {
301
- const modulePrefix = depth === 0 ? "module" : `sub-module-${depth}`;
302
- debug(`${modulePrefix}:${namespaces}`, arg1, ...args);
303
- };
304
- class Module {
305
- id;
306
- filename;
307
- rules;
308
- imports = null;
309
- dependencies = null;
310
- transform = null;
311
- static extensions = /* @__PURE__ */ new Set([".json", ".js", ".jsx", ".ts", ".tsx", ".cjs", ".mjs", ".mts", ".cts"]);
312
- exports = {};
313
- resolveFilename;
314
- debug;
315
- debuggerDepth;
316
- constructor(filename, rules, resolveFilename, debuggerDepth = 0) {
317
- this.id = filename;
318
- this.filename = filename;
319
- this.rules = rules;
320
- this.resolveFilename = resolveFilename;
321
- this.debuggerDepth = debuggerDepth;
322
- this.debug = createCustomDebug(debuggerDepth);
323
- Object.defineProperties(this, {
324
- id: {
325
- value: filename,
326
- writable: false
327
- },
328
- filename: {
329
- value: filename,
330
- writable: false
331
- },
332
- paths: {
333
- value: Object.freeze(
334
- NativeModule._nodeModulePaths(
335
- path.dirname(filename)
336
- )
337
- ),
338
- writable: false
339
- }
340
- });
341
- this.exports = {};
342
- this.debug("prepare", filename);
343
- }
344
- require = Object.assign(
345
- (id) => {
346
- this.debug("require", id);
347
- const resolved = this.resolveFilename(id, this);
348
- if (resolved.builtin) {
349
- throw new Error(`Unable to import "${id}". Importing Node builtins is not supported in the sandbox.`);
350
- }
351
- const filename = resolved.path;
352
- this.dependencies?.push(id);
353
- let cacheKey = filename;
354
- let only = [];
355
- if (this.imports?.has(id)) {
356
- only = this.imports.get(id).sort();
357
- if (only.length === 0) {
358
- only = ["default"];
359
- }
360
- cacheKey += `:${only.join(",")}`;
361
- }
362
- let m = cache[cacheKey];
363
- if (!m) {
364
- this.debug("cached:not-exist", id);
365
- m = new Module(filename, this.rules, this.resolveFilename, this.debuggerDepth + 1);
366
- m.transform = this.transform;
367
- cache[cacheKey] = m;
368
- const ext = path.extname(filename).toLowerCase();
369
- if (Module.extensions.has(ext)) {
370
- const code = fs.readFileSync(filename, "utf-8");
371
- if (ext === ".json") {
372
- m.exports = JSON.parse(code);
373
- } else {
374
- m.evaluate(code, only.includes("*") ? ["*"] : only);
375
- }
376
- } else {
377
- m.exports = ASSET_TAG_OPEN + filename + ASSET_TAG_CLOSE;
378
- }
379
- } else {
380
- this.debug("cached:exist", id);
381
- }
382
- return m.exports;
383
- },
384
- {
385
- ensure: NOOP,
386
- cache,
387
- resolve: (id) => this.resolveFilename(id, this).path
388
- }
389
- );
390
- evaluate(text, only = null, useEvalCache = true) {
391
- const { filename } = this;
392
- let action = "ignore";
393
- for (let i = this.rules.length - 1; i >= 0; i--) {
394
- const { test } = this.rules[i];
395
- if (!test || (typeof test === "function" ? test(filename) : test.test(filename))) {
396
- action = this.rules[i].action;
397
- break;
398
- }
399
- }
400
- const cacheKey = [this.filename, ...only ?? []];
401
- if (useEvalCache && has(cacheKey, text)) {
402
- this.exports = get(cacheKey, text);
403
- return;
404
- }
405
- let code;
406
- if (action === "ignore") {
407
- this.debug("ignore", `${filename}`);
408
- code = text;
409
- } else {
410
- this.debug("prepare-evaluation", this.filename, "using", action.name);
411
- const result = action(this.filename, text, only);
412
- code = result.code;
413
- this.imports = result.imports;
414
- if (result.moduleKind === "esm") {
415
- code = convertESMtoCJS(code, this.filename);
416
- }
417
- this.debug("evaluate", `${this.filename} (only ${(only || []).join(", ")}):
418
- ${code}`);
419
- }
420
- const script = new vm.Script(`(function (exports) { ${code}
421
- })(exports);`, {
422
- filename: this.filename
423
- });
424
- try {
425
- script.runInContext(
426
- vm.createContext({
427
- clearImmediate: NOOP,
428
- clearInterval: NOOP,
429
- clearTimeout: NOOP,
430
- setImmediate: NOOP,
431
- setInterval: NOOP,
432
- setTimeout: NOOP,
433
- fetch: NOOP,
434
- global,
435
- process: mockProcess,
436
- module: this,
437
- exports: this.exports,
438
- require: this.require,
439
- __filename: this.filename,
440
- __dirname: path.dirname(this.filename)
441
- })
442
- );
443
- } catch (vmError) {
444
- const message = isError$1(vmError) ? vmError.message : String(vmError);
445
- const hostError = new Error(message);
446
- if (isError$1(vmError)) {
447
- hostError.stack = vmError.stack;
448
- }
449
- throw hostError;
450
- }
451
- if (useEvalCache) {
452
- set(cacheKey, text, this.exports);
453
- }
454
- }
455
- static invalidate = () => {
456
- cache = {};
457
- };
458
- static invalidateEvalCache = () => {
459
- clear();
460
- };
461
- static _nodeModulePaths = (filename) => NativeModule._nodeModulePaths(filename);
462
- }
463
- const DEOPT = /* @__PURE__ */ Symbol("deopt");
464
- function astEvaluator(node, programAst, plugins = []) {
465
- const context = {
466
- programAst,
467
- evaluateNode
468
- };
469
- function evaluateNode(node2) {
470
- switch (node2.type) {
471
- case "Literal":
472
- return node2.value;
473
- case "ObjectExpression":
474
- return evaluateObjectExpression(node2);
475
- case "TemplateLiteral":
476
- if (node2.expressions.length === 0) {
477
- return node2.quasis[0].value.cooked;
478
- }
479
- break;
480
- }
481
- for (const plugin of plugins) {
482
- const result2 = plugin.evaluateNode(node2, context);
483
- if (result2 !== DEOPT) {
484
- return result2;
485
- }
486
- }
487
- return DEOPT;
488
- }
489
- function evaluateObjectExpression(node2) {
490
- const obj = {};
491
- for (const prop2 of node2.properties) {
492
- if (prop2.type !== "Property" || prop2.kind !== "init") {
493
- return DEOPT;
494
- }
495
- let key;
496
- if (prop2.computed) {
497
- return DEOPT;
498
- } else if (prop2.key.type === "Identifier") {
499
- key = prop2.key.name;
500
- } else if (prop2.key.type === "Literal") {
501
- const keyLiteral = prop2.key;
502
- if (typeof keyLiteral.value === "string" || typeof keyLiteral.value === "number") {
503
- key = String(keyLiteral.value);
504
- } else {
505
- return DEOPT;
506
- }
507
- } else {
508
- return DEOPT;
509
- }
510
- const value = evaluateNode(prop2.value);
511
- if (value === DEOPT) {
512
- return DEOPT;
513
- }
514
- obj[key] = value;
515
- }
516
- return obj;
517
- }
518
- const result = evaluateNode(node);
519
- if (result === DEOPT) {
520
- return {
521
- confident: false,
522
- value: void 0
523
- };
524
- }
525
- return {
526
- confident: true,
527
- value: result
528
- };
529
- }
530
- function isError(e) {
531
- return Object.prototype.toString.call(e) === "[object Error]";
532
- }
533
- function vmEvaluator(sourceCode, filename, expressionCode, evaluationRules, resolveFilename) {
534
- const codeForEvaluation = `
535
- ${sourceCode}
536
-
537
- export const __mkPreval = (() => {
538
- try {
539
- return ([${expressionCode}]);
540
- } catch (e) {
541
- return e;
542
- }
543
- })();
544
- `;
545
- try {
546
- const mod = new Module(filename, evaluationRules, resolveFilename);
547
- mod.evaluate(
548
- codeForEvaluation,
549
- ["__mkPreval"],
550
- /* useEvalCache */
551
- false
552
- );
553
- const result = mod.exports.__mkPreval;
554
- if (isError(result)) {
555
- return { confident: false, error: result };
556
- }
557
- return { confident: true, value: result };
558
- } catch (err) {
559
- return { confident: false, error: err };
560
- }
561
- }
562
- function batchEvaluator(sourceCode, filename, styleCalls, evaluationRules, resolveFilename, programAst, astEvaluationPlugins = []) {
563
- const evaluationResults = new Array(styleCalls.length);
564
- const vmIndices = [];
565
- let expressionCode = "";
566
- for (let i = 0; i < styleCalls.length; i++) {
567
- const styleCall = styleCalls[i];
568
- const staticResult = astEvaluator(styleCall.argumentNode, programAst, astEvaluationPlugins);
569
- if (staticResult.confident) {
570
- evaluationResults[i] = staticResult.value;
571
- continue;
572
- }
573
- if (expressionCode.length > 0) {
574
- expressionCode += ",";
575
- }
576
- expressionCode += styleCall.argumentCode;
577
- vmIndices.push(i);
578
- }
579
- if (vmIndices.length === 0) {
580
- return {
581
- usedVMForEvaluation: false,
582
- evaluationResults
583
- };
584
- }
585
- const vmResult = vmEvaluator(sourceCode, filename, expressionCode, evaluationRules, resolveFilename);
586
- if (!vmResult.confident) {
587
- if (vmResult.error) {
588
- throw vmResult.error;
589
- } else {
590
- throw new Error("Evaluation of a code fragment failed, this is a bug, please report it");
591
- }
592
- }
593
- const vmValues = vmResult.value;
594
- for (let i = 0; i < vmIndices.length; i++) {
595
- evaluationResults[vmIndices[i]] = vmValues[i];
596
- }
597
- return {
598
- usedVMForEvaluation: true,
599
- evaluationResults
600
- };
601
- }
602
- const Z_INDEX_DEFAULTS = {
603
- zIndexBackground: 0,
604
- zIndexContent: 1,
605
- zIndexOverlay: 1e3,
606
- zIndexPopup: 2e3,
607
- zIndexMessages: 3e3,
608
- zIndexFloating: 4e3,
609
- zIndexPriority: 5e3,
610
- zIndexDebug: 6e3
611
- };
612
- function evaluateTemplateLiteralWithTokens(node) {
613
- let result = "";
614
- for (let i = 0; i < node.quasis.length; i++) {
615
- result += node.quasis[i].value.cooked;
616
- if (i < node.expressions.length) {
617
- const expression = node.expressions[i];
618
- if (expression.type === "MemberExpression" && expression.object.type === "Identifier" && expression.object.name === "tokens" && expression.property.type === "Identifier" && !expression.computed) {
619
- const name = expression.property.name;
620
- const fallback = Z_INDEX_DEFAULTS[name];
621
- result += fallback !== void 0 ? `var(--${name}, ${fallback})` : `var(--${name})`;
622
- } else {
623
- return DEOPT;
624
- }
625
- }
626
- }
627
- return result;
628
- }
629
- function evaluateTokensMemberExpression(node) {
630
- if (node.object.type === "Identifier" && node.object.name === "tokens" && node.property.type === "Identifier" && !node.computed) {
631
- const name = node.property.name;
632
- const fallback = Z_INDEX_DEFAULTS[name];
633
- return fallback !== void 0 ? `var(--${name}, ${fallback})` : `var(--${name})`;
634
- } else {
635
- return DEOPT;
636
- }
637
- }
638
- const fluentTokensPlugin = {
639
- name: "fluentTokensPlugin",
640
- evaluateNode(node) {
641
- switch (node.type) {
642
- case "TemplateLiteral":
643
- return evaluateTemplateLiteralWithTokens(node);
644
- case "MemberExpression":
645
- return evaluateTokensMemberExpression(node);
646
- default:
647
- return DEOPT;
648
- }
649
- }
650
- };
651
- function dedupeCSSRules(cssRulesByBucket) {
652
- return Object.fromEntries(
653
- Object.entries(cssRulesByBucket).map(([styleBucketName, cssBucketEntries]) => {
654
- if (styleBucketName === "m") {
655
- const seen = /* @__PURE__ */ new Map();
656
- for (const entry of cssBucketEntries) {
657
- if (!seen.has(entry[0])) {
658
- seen.set(entry[0], entry);
659
- }
660
- }
661
- return [styleBucketName, Array.from(seen.values())];
662
- }
663
- return [styleBucketName, Array.from(new Set(cssBucketEntries))];
664
- })
665
- );
666
- }
667
- const EXPORT_STAR_RE = /export\s+\*\s+from\s/;
668
- function wrapWithPerfIssues(evaluator, perfIssues) {
669
- return (filename, text, only) => {
670
- const result = evaluator(filename, text, only);
671
- if (result.moduleKind === "cjs") {
672
- perfIssues.push({ type: "cjs-module", dependencyFilename: filename });
673
- } else if (EXPORT_STAR_RE.test(result.code)) {
674
- perfIssues.push({ type: "barrel-export-star", dependencyFilename: filename });
675
- }
676
- return result;
677
- };
678
- }
679
- const RUNTIME_IDENTIFIERS = /* @__PURE__ */ new Map([
680
- ["makeStyles", "__css"],
681
- ["makeResetStyles", "__resetCSS"],
682
- ["makeStaticStyles", "__staticCSS"]
683
- ]);
684
- function buildCSSResetEntriesMetadata(cssResetEntries, cssRules, declaratorId) {
685
- const cssRulesByBucket = Array.isArray(cssRules) ? { d: cssRules } : cssRules;
686
- cssResetEntries[declaratorId] ??= [];
687
- cssResetEntries[declaratorId] = Object.values(cssRulesByBucket).flatMap((bucketEntries) => {
688
- return bucketEntries.map((bucketEntry) => {
689
- if (Array.isArray(bucketEntry)) {
690
- throw new Error(
691
- `CSS rules in buckets for "makeResetStyles()" should not contain arrays, got: ${JSON.stringify(
692
- bucketEntry
693
- )})}`
694
- );
695
- }
696
- return bucketEntry;
697
- });
698
- });
699
- }
700
- function buildCSSEntriesMetadata(cssEntries, classnamesMapping, cssRulesByBucket, declaratorId) {
701
- const classesBySlot = Object.fromEntries(
702
- Object.entries(classnamesMapping).map(([slot, cssClassesMap]) => {
703
- const uniqueClasses = /* @__PURE__ */ new Set();
704
- Object.values(cssClassesMap).forEach((cssClasses) => {
705
- if (typeof cssClasses === "string") {
706
- uniqueClasses.add(cssClasses);
707
- } else if (Array.isArray(cssClasses)) {
708
- cssClasses.forEach((cssClass) => uniqueClasses.add(cssClass));
709
- }
710
- });
711
- return [slot, Array.from(uniqueClasses)];
712
- })
713
- );
714
- const cssRules = Object.values(cssRulesByBucket).flatMap((cssRulesByBucket2) => {
715
- return cssRulesByBucket2.map((bucketEntry) => {
716
- const [cssRule] = normalizeCSSBucketEntry(bucketEntry);
717
- return cssRule;
718
- });
719
- });
720
- cssEntries[declaratorId] = Object.fromEntries(
721
- Object.entries(classesBySlot).map(([slot, cssClasses]) => {
722
- return [
723
- slot,
724
- cssClasses.map((cssClass) => {
725
- return cssRules.find((rule) => rule.includes(cssClass));
726
- })
727
- ];
728
- })
729
- );
730
- }
731
- function concatCSSRulesByBucket(bucketA = {}, bucketB) {
732
- for (const cssBucketName in bucketB) {
733
- const bucketName = cssBucketName;
734
- const bucketBEntries = bucketB[bucketName] ?? [];
735
- if (bucketA[bucketName]) {
736
- bucketA[bucketName].push(...bucketBEntries);
737
- } else {
738
- bucketA[bucketName] = bucketBEntries;
739
- }
740
- }
741
- return bucketA;
742
- }
743
- function transformSync(sourceCode, options) {
744
- const perfIssues = options.collectPerfIssues ? [] : void 0;
745
- const {
746
- filename,
747
- resolveModule,
748
- classNameHashSalt = "",
749
- generateMetadata = false,
750
- importsToTransform = ["@griffel/core", "@griffel/react", "@fluentui/react-components"],
751
- functionsToTransform = ["makeStyles", "makeResetStyles", "makeStaticStyles"],
752
- evaluationRules = [{ action: perfIssues ? wrapWithPerfIssues(shakerEvaluator, perfIssues) : shakerEvaluator }],
753
- astEvaluationPlugins = [fluentTokensPlugin]
754
- } = options;
755
- const importsToTransformSet = new Set(importsToTransform);
756
- const functionsToTransformSet = new Set(functionsToTransform);
757
- if (!filename) {
758
- throw new Error('Transform error: "filename" option is required');
759
- }
760
- const parseResult = parseSync(filename, sourceCode);
761
- if (parseResult.errors.length > 0) {
762
- throw new Error(`Failed to parse "${filename}": ${parseResult.errors.map((e) => e.message).join(", ")}`);
763
- }
764
- if (parseResult.program.body.length > 0 && !parseResult.module.hasModuleSyntax) {
765
- throw new Error(
766
- `Transform error: "${filename}" is not an ES module. @griffel/transform only supports ES modules (files using import/export syntax).`
767
- );
768
- }
769
- const magicString = new MagicString(sourceCode);
770
- const programAst = parseResult.program;
771
- const hasGriffelImports = parseResult.module.staticImports.some(
772
- (si) => importsToTransformSet.has(si.moduleRequest.value) && si.entries.some((e) => e.importName.kind === "Name" && functionsToTransformSet.has(e.importName.name))
773
- );
774
- if (!hasGriffelImports) {
775
- return { code: sourceCode, usedProcessing: false, usedVMForEvaluation: false };
776
- }
777
- const styleCalls = [];
778
- const cssEntries = {};
779
- const cssResetEntries = {};
780
- let cssRulesByBucket = {};
781
- const scopeTracker = new ScopeTracker();
782
- const matchedSpecifiers = /* @__PURE__ */ new Map();
783
- walk(programAst, {
784
- scopeTracker,
785
- enter(node, parent) {
786
- if (node.type === "CallExpression" && node.callee.type === "Identifier") {
787
- const declaration = scopeTracker.getDeclaration(node.callee.name);
788
- if (declaration?.type !== "Import" || declaration.node.type !== "ImportSpecifier") {
789
- return;
790
- }
791
- const importSource = declaration.importNode.source.value;
792
- if (!importsToTransformSet.has(importSource)) {
793
- return;
794
- }
795
- const imported = declaration.node.imported;
796
- if (imported.type !== "Identifier") {
797
- return;
798
- }
799
- const importedName = imported.name;
800
- if (!functionsToTransformSet.has(importedName)) {
801
- return;
802
- }
803
- const functionKind = importedName;
804
- if (node.arguments.length !== 1) {
805
- throw new Error(
806
- `${functionKind}() function accepts only a single param, got ${node.arguments.length} in ${filename}`
807
- );
808
- }
809
- matchedSpecifiers.set(declaration.node.start, {
810
- start: declaration.node.start,
811
- end: declaration.node.end,
812
- functionKind
813
- });
814
- let declaratorId = "unknownHook";
815
- let current = parent;
816
- while (current) {
817
- if (!current) {
818
- break;
819
- }
820
- if (current.type === "VariableDeclarator" && current.id.type === "Identifier") {
821
- declaratorId = current.id.name;
822
- break;
823
- }
824
- if ("parent" in current) {
825
- current = current.parent;
826
- continue;
827
- }
828
- break;
829
- }
830
- const argument = node.arguments[0];
831
- styleCalls.push({
832
- declaratorId,
833
- functionKind,
834
- argumentStart: argument.start,
835
- argumentEnd: argument.end,
836
- argumentCode: sourceCode.slice(argument.start, argument.end),
837
- argumentNode: argument,
838
- callStart: node.start,
839
- callEnd: node.end,
840
- importId: node.callee.name
841
- });
842
- }
843
- }
844
- });
845
- if (styleCalls.length === 0) {
846
- return {
847
- code: sourceCode,
848
- usedProcessing: false,
849
- usedVMForEvaluation: false
850
- };
851
- }
852
- const { evaluationResults, usedVMForEvaluation } = batchEvaluator(
853
- sourceCode,
854
- filename,
855
- styleCalls,
856
- evaluationRules,
857
- resolveModule,
858
- programAst,
859
- astEvaluationPlugins
860
- );
861
- for (let i = styleCalls.length - 1; i >= 0; i--) {
862
- const styleCall = styleCalls[i];
863
- const evaluationResult = evaluationResults[i];
864
- switch (styleCall.functionKind) {
865
- case "makeStyles":
866
- {
867
- const stylesBySlots = evaluationResult;
868
- const [classnamesMapping, resolvedCSSRules] = resolveStyleRulesForSlots(stylesBySlots, classNameHashSalt);
869
- const uniqueCSSRules = dedupeCSSRules(cssRulesByBucket);
870
- if (generateMetadata) {
871
- buildCSSEntriesMetadata(cssEntries, classnamesMapping, uniqueCSSRules, styleCall.declaratorId);
872
- }
873
- magicString.overwrite(styleCall.argumentStart, styleCall.argumentEnd, `${JSON.stringify(classnamesMapping)}`);
874
- cssRulesByBucket = concatCSSRulesByBucket(cssRulesByBucket, resolvedCSSRules);
875
- }
876
- break;
877
- case "makeResetStyles":
878
- {
879
- const styles = evaluationResult;
880
- const [ltrClassName, rtlClassName, cssRules] = resolveResetStyleRules(styles, classNameHashSalt);
881
- if (generateMetadata) {
882
- buildCSSResetEntriesMetadata(cssResetEntries, cssRules, styleCall.declaratorId);
883
- }
884
- magicString.overwrite(
885
- styleCall.argumentStart,
886
- styleCall.argumentEnd,
887
- `${JSON.stringify(ltrClassName)}, ${JSON.stringify(rtlClassName)}`
888
- );
889
- cssRulesByBucket = concatCSSRulesByBucket(
890
- cssRulesByBucket,
891
- Array.isArray(cssRules) ? { r: cssRules } : cssRules
892
- );
893
- }
894
- break;
895
- case "makeStaticStyles":
896
- {
897
- const styles = evaluationResult;
898
- const stylesSet = Array.isArray(styles) ? styles : [styles];
899
- const cssRules = resolveStaticStyleRules(stylesSet);
900
- magicString.overwrite(styleCall.argumentStart, styleCall.argumentEnd, JSON.stringify({ d: cssRules }));
901
- cssRulesByBucket = concatCSSRulesByBucket(cssRulesByBucket, { d: cssRules });
902
- }
903
- break;
904
- }
905
- }
906
- for (const specifier of matchedSpecifiers.values()) {
907
- magicString.overwrite(specifier.start, specifier.end, RUNTIME_IDENTIFIERS.get(specifier.functionKind));
908
- }
909
- for (const styleCall of styleCalls) {
910
- magicString.overwrite(
911
- styleCall.callStart,
912
- styleCall.callStart + styleCall.importId.length,
913
- RUNTIME_IDENTIFIERS.get(styleCall.functionKind)
914
- );
915
- }
916
- return {
917
- code: magicString.toString(),
918
- cssRulesByBucket,
919
- usedProcessing: true,
920
- usedVMForEvaluation,
921
- perfIssues
922
- };
923
- }
924
- export {
925
- ASSET_TAG_CLOSE,
926
- ASSET_TAG_OPEN,
927
- DEOPT,
928
- evalCache$1 as EvalCache,
929
- Module,
930
- fluentTokensPlugin,
931
- default2 as shakerEvaluator,
932
- transformSync
933
- };