@stylexjs/babel-plugin 0.5.0-alpha.4 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -30,6 +30,7 @@ var name = "@stylexjs/stylex";
30
30
 
31
31
  const defaultMessage = expected => (value, name) => name ? `Expected (${name}) to be ${expected}, but got \`${JSON.stringify(value)}\`.` : expected;
32
32
  const defaultUnionMessage = expected => (value, name) => name ? `Expected (${name}) to be ${expected}` : expected;
33
+ const defaultObjectMessage = expected => (value, name) => name ? `Expected (${name}) to be ${expected} but:` : expected;
33
34
  const indent = str => str.split('\n').filter(line => !line.trim().startsWith('But got:')).map(line => line.includes(', but got') ? line.replace(/, but got.+$/, '') : line).map(line => line.trim()[0] === '-' ? line : `- ${line}`).map(line => `\n\t${line}`).join('');
34
35
  const string = function () {
35
36
  let message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultMessage('a string');
@@ -104,6 +105,23 @@ const object = function (shape) {
104
105
  return result;
105
106
  };
106
107
  };
108
+ const objectOf = function (check) {
109
+ let message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultObjectMessage('an object');
110
+ return (value, name) => {
111
+ if (typeof value !== 'object' || value == null) {
112
+ return new Error(message(value, name));
113
+ }
114
+ const result = {};
115
+ for (const key in value) {
116
+ const item = check(value[key], name ? `${name}.${key}` : `With the key '${key}':`);
117
+ if (item instanceof Error) {
118
+ return new Error(`${message(value, name)}${indent(item.message)}\nBut got: ${indent(JSON.stringify(value))}`);
119
+ }
120
+ result[key] = item;
121
+ }
122
+ return result;
123
+ };
124
+ };
107
125
  const unionOf = function (a, b) {
108
126
  let message = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultUnionMessage('one of');
109
127
  return (value, name) => {
@@ -314,8 +332,16 @@ class StateManager {
314
332
  const styleResolution = logAndDefault(unionOf3(literal('application-order'), literal('property-specificity'), literal('legacy-expand-shorthands')), options.styleResolution ?? 'application-order', 'application-order', 'options.styleResolution');
315
333
  const unstable_moduleResolution = logAndDefault(unionOf(nullish(), CheckModuleResolution), options.unstable_moduleResolution, null, 'options.unstable_moduleResolution');
316
334
  const treeshakeCompensation = logAndDefault(boolean(), options.treeshakeCompensation ?? false, false, 'options.treeshakeCompensation');
335
+ const aliasesOption = logAndDefault(unionOf(nullish(), objectOf(unionOf(string(), array(string())))), options.aliases, null, 'options.aliases');
336
+ const aliases = aliasesOption == null ? aliasesOption : Object.fromEntries(Object.entries(aliasesOption).map(_ref => {
337
+ let [key, value] = _ref;
338
+ if (typeof value === 'string') {
339
+ return [key, [value]];
340
+ }
341
+ return [key, value];
342
+ }));
317
343
  const opts = {
318
- ...options,
344
+ aliases,
319
345
  dev,
320
346
  test,
321
347
  runtimeInjection,
@@ -455,11 +481,12 @@ class StateManager {
455
481
  case 'commonJS':
456
482
  {
457
483
  const rootDir = this.options.unstable_moduleResolution.rootDir;
458
- const themeFileExtension = this.options.unstable_moduleResolution.themeFileExtension ?? '.stylex';
484
+ const aliases = this.options.aliases;
485
+ const themeFileExtension = this.options.unstable_moduleResolution?.themeFileExtension ?? '.stylex';
459
486
  if (!matchesFileSuffix(themeFileExtension)(importPath)) {
460
487
  return false;
461
488
  }
462
- const resolvedFilePath = filePathResolver(importPath, sourceFilePath);
489
+ const resolvedFilePath = filePathResolver(importPath, sourceFilePath, aliases);
463
490
  return resolvedFilePath ? ['themeNameRef', path.relative(rootDir, resolvedFilePath)] : false;
464
491
  }
465
492
  case 'haste':
@@ -472,11 +499,12 @@ class StateManager {
472
499
  }
473
500
  case 'experimental_crossFileParsing':
474
501
  {
502
+ const aliases = this.options.aliases;
475
503
  const themeFileExtension = this.options.unstable_moduleResolution.themeFileExtension ?? '.stylex';
476
504
  if (!matchesFileSuffix(themeFileExtension)(importPath)) {
477
505
  return false;
478
506
  }
479
- const resolvedFilePath = filePathResolver(importPath, sourceFilePath);
507
+ const resolvedFilePath = filePathResolver(importPath, sourceFilePath, aliases);
480
508
  return resolvedFilePath ? ['filePath', resolvedFilePath] : false;
481
509
  }
482
510
  default:
@@ -490,25 +518,48 @@ class StateManager {
490
518
  this.styleVarsToKeep.add(memberExpression);
491
519
  }
492
520
  }
493
- const filePathResolver = (relativeFilePath, sourceFilePath) => {
494
- const fileToLookFor = relativeFilePath;
495
- if (EXTENSIONS.some(ext => fileToLookFor.endsWith(ext))) {
496
- try {
497
- const resolvedFilePath = require.resolve(fileToLookFor, {
498
- paths: [path.dirname(sourceFilePath)]
499
- });
500
- return resolvedFilePath;
501
- } catch {}
502
- }
503
- for (const ext of EXTENSIONS) {
504
- try {
505
- const importPathStr = fileToLookFor.startsWith('.') ? fileToLookFor + ext : fileToLookFor;
506
- const resolvedFilePath = require.resolve(importPathStr, {
507
- paths: [path.dirname(sourceFilePath)]
521
+ function possibleAliasedPaths(importPath, aliases) {
522
+ const result = [importPath];
523
+ if (aliases == null || Object.keys(aliases).length === 0) {
524
+ return result;
525
+ }
526
+ for (const [alias, value] of Object.entries(aliases)) {
527
+ if (alias.includes('*')) {
528
+ const [before, after] = alias.split('*');
529
+ if (importPath.startsWith(before) && importPath.endsWith(after)) {
530
+ const replacementString = importPath.slice(before.length, after.length > 0 ? -after.length : undefined);
531
+ value.forEach(v => {
532
+ result.push(v.split('*').join(replacementString));
533
+ });
534
+ }
535
+ } else if (alias === importPath) {
536
+ value.forEach(v => {
537
+ result.push(v);
508
538
  });
509
- return resolvedFilePath;
510
- } catch {}
539
+ }
540
+ }
541
+ return result;
542
+ }
543
+ const filePathResolver = (relativeFilePath, sourceFilePath, aliases) => {
544
+ for (const ext of ['', ...EXTENSIONS]) {
545
+ const importPathStr = relativeFilePath + ext;
546
+ if (importPathStr.startsWith('.')) {
547
+ try {
548
+ return require.resolve(importPathStr, {
549
+ paths: [path.dirname(sourceFilePath)]
550
+ });
551
+ } catch {}
552
+ }
553
+ const allAliases = possibleAliasedPaths(importPathStr, aliases);
554
+ for (const possiblePath of allAliases) {
555
+ try {
556
+ return require.resolve(possiblePath, {
557
+ paths: [path.dirname(sourceFilePath)]
558
+ });
559
+ } catch {}
560
+ }
511
561
  }
562
+ return null;
512
563
  };
513
564
  const EXTENSIONS = ['.js', '.ts', '.tsx', '.jsx', '.mjs', '.cjs'];
514
565
  const addFileExtension = (importedFilePath, sourceFile) => {
@@ -1320,7 +1371,10 @@ function getExpandedKeys(options) {
1320
1371
  return Object.keys(expansions[options.styleResolution ?? 'application-order']);
1321
1372
  }
1322
1373
  function flatMapExpandedShorthands(objEntry, options) {
1323
- const [key, value] = objEntry;
1374
+ let [key, value] = objEntry;
1375
+ if (key.startsWith('var(') && key.endsWith(')')) {
1376
+ key = key.slice(4, -1);
1377
+ }
1324
1378
  const expansion = expansions[options.styleResolution ?? 'application-order'][key];
1325
1379
  if (expansion) {
1326
1380
  if (Array.isArray(value)) {
@@ -1502,6 +1556,16 @@ function normalizeWhitespace(ast, _) {
1502
1556
  break;
1503
1557
  }
1504
1558
  case 'div':
1559
+ {
1560
+ if (node.value === ',') {
1561
+ node.before = '';
1562
+ node.after = '';
1563
+ } else {
1564
+ node.before = ' ';
1565
+ node.after = ' ';
1566
+ }
1567
+ break;
1568
+ }
1505
1569
  case 'function':
1506
1570
  {
1507
1571
  node.before = '';
@@ -1533,7 +1597,14 @@ function _interopRequireDefault$b(obj) { return obj && obj.__esModule ? obj : {
1533
1597
  const angles = ['deg', 'grad', 'turn', 'rad'];
1534
1598
  const timings = ['ms', 's'];
1535
1599
  function normalizeZeroDimensions(ast, _) {
1600
+ let endFunction = 0;
1536
1601
  ast.walk(node => {
1602
+ if (node.type === 'function' && !endFunction) {
1603
+ endFunction = node.sourceEndIndex ?? 0;
1604
+ }
1605
+ if (endFunction > 0 && node.sourceIndex > endFunction) {
1606
+ endFunction = 0;
1607
+ }
1537
1608
  if (node.type !== 'word') {
1538
1609
  return;
1539
1610
  }
@@ -1545,7 +1616,7 @@ function normalizeZeroDimensions(ast, _) {
1545
1616
  node.value = '0deg';
1546
1617
  } else if (timings.indexOf(dimension.unit) !== -1) {
1547
1618
  node.value = '0s';
1548
- } else {
1619
+ } else if (!endFunction) {
1549
1620
  node.value = '0';
1550
1621
  }
1551
1622
  });
@@ -1982,6 +2053,7 @@ var propertyPriorities = {};
1982
2053
  Object.defineProperty(propertyPriorities, "__esModule", {
1983
2054
  value: true
1984
2055
  });
2056
+ propertyPriorities.PSEUDO_ELEMENT_PRIORITY = propertyPriorities.PSEUDO_CLASS_PRIORITIES = propertyPriorities.AT_RULE_PRIORITIES = void 0;
1985
2057
  propertyPriorities.default = getPriority;
1986
2058
  const longHandPhysical = new Set();
1987
2059
  const longHandLogical = new Set();
@@ -2419,7 +2491,7 @@ longHandLogical.add('math-depth');
2419
2491
  longHandLogical.add('math-shift');
2420
2492
  longHandLogical.add('math-style');
2421
2493
  longHandLogical.add('touch-action');
2422
- const PRIORITIES = {
2494
+ const PSEUDO_CLASS_PRIORITIES = propertyPriorities.PSEUDO_CLASS_PRIORITIES = {
2423
2495
  ':is': 40,
2424
2496
  ':where': 40,
2425
2497
  ':not': 40,
@@ -2474,25 +2546,31 @@ const PRIORITIES = {
2474
2546
  ':focusVisible': 160,
2475
2547
  ':active': 170
2476
2548
  };
2549
+ const AT_RULE_PRIORITIES = propertyPriorities.AT_RULE_PRIORITIES = {
2550
+ '@supports': 30,
2551
+ '@media': 200,
2552
+ '@container': 300
2553
+ };
2554
+ const PSEUDO_ELEMENT_PRIORITY = propertyPriorities.PSEUDO_ELEMENT_PRIORITY = 5000;
2477
2555
  function getPriority(key) {
2478
2556
  if (key.startsWith('--')) {
2479
2557
  return 1;
2480
2558
  }
2481
2559
  if (key.startsWith('@supports')) {
2482
- return 30;
2560
+ return AT_RULE_PRIORITIES['@supports'];
2483
2561
  }
2484
2562
  if (key.startsWith('@media')) {
2485
- return 200;
2563
+ return AT_RULE_PRIORITIES['@media'];
2486
2564
  }
2487
2565
  if (key.startsWith('@container')) {
2488
- return 300;
2566
+ return AT_RULE_PRIORITIES['@container'];
2489
2567
  }
2490
2568
  if (key.startsWith('::')) {
2491
- return 5000;
2569
+ return PSEUDO_ELEMENT_PRIORITY;
2492
2570
  }
2493
2571
  if (key.startsWith(':')) {
2494
2572
  const prop = key.startsWith(':') && key.includes('(') ? key.slice(0, key.indexOf('(')) : key;
2495
- return PRIORITIES[prop] ?? 40;
2573
+ return PSEUDO_CLASS_PRIORITIES[prop] ?? 40;
2496
2574
  }
2497
2575
  if (longHandPhysical.has(key)) {
2498
2576
  return 4000;
@@ -2516,7 +2594,7 @@ generateCssRule.generateRule = generateRule;
2516
2594
  var _generateLtr$1 = _interopRequireDefault$6(generateLtr);
2517
2595
  var _generateRtl$1 = _interopRequireDefault$6(generateRtl);
2518
2596
  var _genCSSRule = genCSSRule$1;
2519
- var _propertyPriorities = _interopRequireDefault$6(propertyPriorities);
2597
+ var _propertyPriorities$1 = _interopRequireDefault$6(propertyPriorities);
2520
2598
  function _interopRequireDefault$6(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2521
2599
  function generateRule(className, key, value, pseudos, atRules) {
2522
2600
  const pairs = Array.isArray(value) ? value.map(eachValue => [key, eachValue]) : [[key, value]];
@@ -2525,7 +2603,7 @@ function generateRule(className, key, value, pseudos, atRules) {
2525
2603
  const rtlDecls = pairs.map(_generateRtl$1.default).filter(Boolean).map(pair => pair.join(':')).join(';');
2526
2604
  const ltrRule = (0, _genCSSRule.genCSSRule)(className, ltrDecls, pseudos, atRules);
2527
2605
  const rtlRule = !rtlDecls ? null : (0, _genCSSRule.genCSSRule)(className, rtlDecls, pseudos, atRules);
2528
- const priority = (0, _propertyPriorities.default)(key) + pseudos.map(_propertyPriorities.default).reduce((a, b) => a + b, 0) + atRules.map(_propertyPriorities.default).reduce((a, b) => a + b, 0);
2606
+ const priority = (0, _propertyPriorities$1.default)(key) + pseudos.map(_propertyPriorities$1.default).reduce((a, b) => a + b, 0) + atRules.map(_propertyPriorities$1.default).reduce((a, b) => a + b, 0);
2529
2607
  return {
2530
2608
  priority,
2531
2609
  ltr: ltrRule,
@@ -3331,7 +3409,7 @@ var messages_1;
3331
3409
  Object.defineProperty(lib, "__esModule", {
3332
3410
  value: true
3333
3411
  });
3334
- var utils_1 = lib.utils = lib.types = messages_1 = lib.messages = keyframes_1 = lib.keyframes = include_1 = lib.include = firstThatWorks_1 = lib.firstThatWorks = defineVars_1 = lib.defineVars = createTheme_1 = lib.createTheme = create_1 = lib.create = IncludedStyles_1 = lib.IncludedStyles = void 0;
3412
+ var utils_1 = lib.utils = lib.types = messages_1 = lib.messages = keyframes_1 = lib.keyframes = include_1 = lib.include = firstThatWorks_1 = lib.firstThatWorks = defineVars_1 = lib.defineVars = createTheme_1 = lib.createTheme = create_1 = lib.create = lib.PSEUDO_ELEMENT_PRIORITY = lib.PSEUDO_CLASS_PRIORITIES = IncludedStyles_1 = lib.IncludedStyles = lib.AT_RULE_PRIORITIES = void 0;
3335
3413
  var _stylexCreate = _interopRequireDefault(stylexCreate$1);
3336
3414
  var _stylexDefineVars = _interopRequireDefault(stylexDefineVars$1);
3337
3415
  var _stylexCreateTheme = _interopRequireDefault(stylexCreateTheme$1);
@@ -3343,6 +3421,7 @@ var _fileBasedIdentifier = _interopRequireDefault(fileBasedIdentifier);
3343
3421
  var m = _interopRequireWildcard(messages$3);
3344
3422
  var _types = _interopRequireWildcard(types$1);
3345
3423
  lib.types = _types;
3424
+ var _propertyPriorities = propertyPriorities;
3346
3425
  function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
3347
3426
  function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
3348
3427
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
@@ -3358,6 +3437,9 @@ utils_1 = lib.utils = {
3358
3437
  messages_1 = lib.messages = m;
3359
3438
  IncludedStyles_1 = lib.IncludedStyles = _stylexInclude.IncludedStyles;
3360
3439
  firstThatWorks_1 = lib.firstThatWorks = _stylexFirstThatWorks.default;
3440
+ lib.PSEUDO_CLASS_PRIORITIES = _propertyPriorities.PSEUDO_CLASS_PRIORITIES;
3441
+ lib.AT_RULE_PRIORITIES = _propertyPriorities.AT_RULE_PRIORITIES;
3442
+ lib.PSEUDO_ELEMENT_PRIORITY = _propertyPriorities.PSEUDO_ELEMENT_PRIORITY;
3361
3443
 
3362
3444
  function namespaceToDevClassName(namespace, varName, filename) {
3363
3445
  const basename = path.basename(filename).split('.')[0];
@@ -4016,7 +4098,10 @@ function evaluatePartialObjectRecursively(path, traversalState) {
4016
4098
  value: null
4017
4099
  };
4018
4100
  }
4019
- const key = keyResult.value;
4101
+ let key = keyResult.value;
4102
+ if (key.startsWith('var(') && key.endsWith(')')) {
4103
+ key = key.slice(4, -1);
4104
+ }
4020
4105
  const valuePath = prop.get('value');
4021
4106
  if (isObjectExpression(valuePath)) {
4022
4107
  const result = evaluatePartialObjectRecursively(valuePath, traversalState, functions, [...keyPath, key]);
@@ -48,6 +48,10 @@ export type StyleXOptions = Readonly<
48
48
  treeshakeCompensation?: boolean;
49
49
  genConditionalClasses: boolean;
50
50
  unstable_moduleResolution: null | undefined | ModuleResolution;
51
+ aliases?:
52
+ | null
53
+ | undefined
54
+ | Readonly<{ [$$Key$$: string]: string | ReadonlyArray<string> }>;
51
55
  })
52
56
  > & {
53
57
  importSources: ReadonlyArray<
@@ -60,6 +64,10 @@ export type StyleXOptions = Readonly<
60
64
  treeshakeCompensation?: boolean;
61
65
  genConditionalClasses: boolean;
62
66
  unstable_moduleResolution: null | undefined | ModuleResolution;
67
+ aliases?:
68
+ | null
69
+ | undefined
70
+ | Readonly<{ [$$Key$$: string]: string | ReadonlyArray<string> }>;
63
71
  }
64
72
  >;
65
73
  type StyleXStateOptions = Readonly<
@@ -69,11 +77,19 @@ type StyleXStateOptions = Readonly<
69
77
  runtimeInjection:
70
78
  | (null | undefined | string)
71
79
  | Readonly<{ from: string; as: null | undefined | string }>;
80
+ aliases?:
81
+ | null
82
+ | undefined
83
+ | Readonly<{ [$$Key$$: string]: ReadonlyArray<string> }>;
72
84
  })
73
85
  > & {
74
86
  runtimeInjection:
75
87
  | (null | undefined | string)
76
88
  | Readonly<{ from: string; as: null | undefined | string }>;
89
+ aliases?:
90
+ | null
91
+ | undefined
92
+ | Readonly<{ [$$Key$$: string]: ReadonlyArray<string> }>;
77
93
  }
78
94
  >;
79
95
  declare class StateManager {
@@ -49,12 +49,14 @@ export type StyleXOptions = $ReadOnly<{
49
49
  treeshakeCompensation?: boolean,
50
50
  genConditionalClasses: boolean,
51
51
  unstable_moduleResolution: ?ModuleResolution,
52
+ aliases?: ?$ReadOnly<{ [string]: string | $ReadOnlyArray<string> }>,
52
53
  ...
53
54
  }>;
54
55
 
55
56
  type StyleXStateOptions = $ReadOnly<{
56
57
  ...StyleXOptions,
57
58
  runtimeInjection: ?string | $ReadOnly<{ from: string, as: ?string }>,
59
+ aliases?: ?$ReadOnly<{ [string]: $ReadOnlyArray<string> }>,
58
60
  ...
59
61
  }>;
60
62
 
@@ -39,7 +39,7 @@ export declare const object: <
39
39
  ) => Check<ObjOfChecks<T>>;
40
40
  export declare const objectOf: <T>(
41
41
  $$PARAM_0$$: Check<T>,
42
- $$PARAM_1$$: Msg,
42
+ message?: Msg,
43
43
  ) => Check<{ readonly [$$Key$$: string]: T }>;
44
44
  export declare const unionOf: <A, B>(
45
45
  a: Check<A>,
@@ -40,7 +40,10 @@ declare export const object: <T: { +[string]: Check<mixed> }>(
40
40
  msg?: Msg,
41
41
  ) => Check<ObjOfChecks<T>>;
42
42
 
43
- declare export const objectOf: <T>(Check<T>, Msg) => Check<{ +[string]: T }>;
43
+ declare export const objectOf: <T>(
44
+ Check<T>,
45
+ message?: Msg,
46
+ ) => Check<{ +[string]: T }>;
44
47
 
45
48
  declare export const unionOf: <A, B>(
46
49
  a: Check<A>,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stylexjs/babel-plugin",
3
- "version": "0.5.0-alpha.4",
3
+ "version": "0.5.0",
4
4
  "description": "StyleX babel plugin.",
5
5
  "main": "lib/index.js",
6
6
  "repository": "https://github.com/facebook/stylex",
@@ -9,12 +9,13 @@
9
9
  "prebuild": "gen-types -i src/ -o lib/",
10
10
  "build": "rollup --config ./rollup.config.mjs",
11
11
  "build-haste": "HASTE=true rollup --config ./rollup.config.mjs",
12
+ "build-watch": "rollup --config ./rollup.config.mjs --watch",
12
13
  "test": "jest"
13
14
  },
14
15
  "dependencies": {
15
16
  "@babel/helper-module-imports": "^7.22.15",
16
- "@stylexjs/shared": "0.5.0-alpha.4",
17
- "@stylexjs/stylex": "0.5.0-alpha.4",
17
+ "@stylexjs/shared": "0.5.0",
18
+ "@stylexjs/stylex": "0.5.0",
18
19
  "@babel/core": "^7.23.6",
19
20
  "@babel/traverse": "^7.23.6",
20
21
  "@babel/types": "^7.23.6"