styled-components-to-stylex-codemod 0.0.33 → 0.0.35

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/README.md CHANGED
@@ -36,6 +36,13 @@ const adapter = defineAdapter({
36
36
  styleMerger: null,
37
37
  // Emit sx={} JSX attributes instead of {...stylex.props()} spreads (requires StyleX ≥0.18)
38
38
  useSxProp: false,
39
+ // Optional override for sx-aware wrapped components. Auto-detection is on by
40
+ // default when `useSxProp: true` — the codemod scans the imported component's
41
+ // prop type for an `sx?:` member. Use this hook to override (e.g. for package
42
+ // imports that cannot be resolved to source on disk).
43
+ wrappedComponentInterface(ctx) {
44
+ return undefined;
45
+ },
39
46
  // Optional: customize the runtime theme hook import/call used for theme conditionals
40
47
  // Defaults to { functionName: "useTheme", importSource: { kind: "specifier", value: "styled-components" } }
41
48
  themeHook: {
@@ -172,6 +179,27 @@ const adapter = defineAdapter({
172
179
  */
173
180
  useSxProp: false,
174
181
 
182
+ /**
183
+ * Optional override for sx-aware wrapped components.
184
+ *
185
+ * When `useSxProp: true`, the codemod auto-detects whether an imported
186
+ * component accepts an `sx` prop by walking its declared prop type
187
+ * (intersections, type aliases, and interfaces in the same file). When
188
+ * `styled(Component)` wraps an sx-aware component, the codemod emits
189
+ * `<Component sx={styles.x} />` instead of `<Component {...stylex.props(styles.x)} />`
190
+ * and lets the wrapped component merge className/style itself.
191
+ *
192
+ * Use this hook to override auto-detection for cases it can't see, such as
193
+ * unresolvable package imports or components whose sx support is added by a
194
+ * HOC at runtime. Returning `undefined` falls through to auto-detection.
195
+ */
196
+ wrappedComponentInterface(ctx) {
197
+ if (ctx.importSource.startsWith("@company/ui/")) {
198
+ return { acceptsSx: true };
199
+ }
200
+ return undefined;
201
+ },
202
+
175
203
  /**
176
204
  * Optional: customize the runtime theme hook used when wrappers need theme booleans.
177
205
  * Defaults to useTheme from styled-components.
@@ -203,6 +231,7 @@ Adapters are the main extension point, see full example above. They let you cont
203
231
  - how helper calls are resolved (via `resolveCall({ ... })` returning `{ expr, imports }`, or `{ preserveRuntimeCall: true }` to keep only the original helper runtime call; `null`/`undefined` bails the file)
204
232
  - which exported components should support external className/style extension and/or polymorphic `as` prop (`externalInterface`)
205
233
  - how className/style merging is handled for components accepting external styling (`styleMerger`)
234
+ - which imported components already accept a StyleX `sx` prop (auto-detected from the imported component's prop type when `useSxProp: true`; can be overridden via `wrappedComponentInterface`). When detected, the codemod emits `sx={styles.x}` on the wrapped component instead of `{...stylex.props(styles.x)}`.
206
235
  - which runtime theme hook import/call to use for emitted wrapper theme conditionals (`themeHook`)
207
236
  - how `styled(ImportedComponent)` wrapping an external base component can be inlined into an intrinsic element with static StyleX styles (`resolveBaseComponent`)
208
237
 
@@ -306,6 +335,7 @@ resolveBaseComponent(ctx) {
306
335
  When the codemod encounters an interpolation inside a styled template literal, it runs an internal dynamic resolution pipeline which covers common cases like:
307
336
 
308
337
  - theme access (`props.theme...`) via `resolveValue({ kind: "theme", path })`
338
+ - indexed theme lookups (`props.theme.color[props.$bg]`) — when `ctx.indexedLookup` is true, return `{ usage: "props", dynamicArgUsage: "memberAccess" }` to emit a prebuilt per-property mixin map (e.g., `$colorMixins.backgroundColor[bg]`) instead of a dynamic style function
309
339
  - imported value access (`import { zIndex } ...; ${zIndex.popover}`) via `resolveValue({ kind: "importedValue", importedName, source, path })`
310
340
  - prop access (`props.foo`) and conditionals (`props.foo ? "a" : "b"`, `props.foo && "color: red;"`)
311
341
  - helper calls (`transitionSpeed("slowTransition")`) via `resolveCall({ ... })` — the codemod infers usage from context:
@@ -1,6 +1,6 @@
1
- import { n as escapeRegex } from "./string-utils-5EMAWj3q.mjs";
2
- import { t as toRealPath } from "./path-utils-BlOXGcCF.mjs";
3
- import { t as isSelectorContext } from "./selector-context-heuristic-Dualf7ac.mjs";
1
+ import { r as escapeRegex } from "./string-utils-Bq7DbB2x.mjs";
2
+ import { n as toRealPath } from "./path-utils-GG-vEb5-.mjs";
3
+ import { t as isSelectorContext } from "./selector-context-heuristic-DE3JAmpc.mjs";
4
4
  import { readFileSync } from "node:fs";
5
5
  //#region src/internal/bridge-consumer-patcher.ts
6
6
  /**
@@ -1,5 +1,5 @@
1
- import { n as escapeRegex } from "./string-utils-5EMAWj3q.mjs";
2
- import { t as toRealPath } from "./path-utils-BlOXGcCF.mjs";
1
+ import { r as escapeRegex } from "./string-utils-Bq7DbB2x.mjs";
2
+ import { n as toRealPath } from "./path-utils-GG-vEb5-.mjs";
3
3
  import { readFileSync } from "node:fs";
4
4
  //#region src/internal/forwarded-as-consumer-patcher.ts
5
5
  /**
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as defineAdapter, i as AdapterInput, t as CollectedWarning } from "./logger-C-Mherh5.mjs";
1
+ import { a as ImportSource, i as AdapterInput, o as MarkerFileContext, s as defineAdapter, t as CollectedWarning } from "./logger-BoGU2nCP.mjs";
2
2
 
3
3
  //#region src/run.d.ts
4
4
  interface RunTransformOptions {
@@ -64,6 +64,18 @@ interface RunTransformOptions {
64
64
  * @default false
65
65
  */
66
66
  silent?: boolean;
67
+ /**
68
+ * When true, allow the codemod to leave individual styled declarations as-is when
69
+ * they hit an unsupported pattern while transforming the rest of the file. This
70
+ * enables incremental migration: a file with one unconvertible component still
71
+ * produces useful output for the others.
72
+ *
73
+ * When false (default), any per-decl bail escalates to a whole-file bail — the
74
+ * safer/stricter behavior matching the pre-partial-migration semantics.
75
+ *
76
+ * @default false
77
+ */
78
+ allowPartialMigration?: boolean;
67
79
  }
68
80
  interface RunTransformResult {
69
81
  /** Number of files that had errors */
@@ -107,4 +119,4 @@ interface RunTransformResult {
107
119
  */
108
120
  declare function runTransform(options: RunTransformOptions): Promise<RunTransformResult>;
109
121
  //#endregion
110
- export { type AdapterInput, defineAdapter, runTransform };
122
+ export { type AdapterInput, type ImportSource, type MarkerFileContext, defineAdapter, runTransform };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { a as assertValidAdapterInput, n as defineAdapter, o as describeValue } from "./adapter-Cu-LRuPc.mjs";
2
- import { t as Logger } from "./logger-C2O81VeU.mjs";
1
+ import { o as assertValidAdapterInput, r as defineAdapter, s as describeValue, t as mergeMarkerDeclarations } from "./merge-markers-Bp-ELxFV.mjs";
2
+ import { t as Logger } from "./logger-fIHHMZYO.mjs";
3
3
  import { run } from "jscodeshift/src/Runner.js";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { dirname, join, resolve } from "node:path";
@@ -141,9 +141,9 @@ async function runTransform(options) {
141
141
  `Pattern(s): ${consumerPatterns.join(", ")}`,
142
142
  "Check that the glob pattern is correct and files exist."
143
143
  ].join("\n"));
144
- const { createModuleResolver } = await import("./resolve-imports-DKohVjNI.mjs");
144
+ const { createModuleResolver } = await import("./resolve-imports-BlxKezSJ.mjs").then((n) => n.n);
145
145
  const sharedResolver = createModuleResolver();
146
- const { runPrepass } = await import("./run-prepass-4gxoyZ8y.mjs");
146
+ const { runPrepass } = await import("./run-prepass-DUxB6hxo.mjs");
147
147
  const absoluteFiles = filePaths.map((f) => resolve(f));
148
148
  const absoluteConsumers = consumerFilePaths.map((f) => resolve(f));
149
149
  let prepassResult;
@@ -204,7 +204,9 @@ async function runTransform(options) {
204
204
  resolveCall: resolveCallWithLogging,
205
205
  resolveSelector: resolveSelectorWithLogging,
206
206
  resolveBaseComponent: adapterInput.resolveBaseComponent ? resolveBaseComponentWithLogging : void 0,
207
- resolveThemeCall: resolvedAdapter.resolveThemeCall
207
+ resolveThemeCall: resolvedAdapter.resolveThemeCall,
208
+ wrappedComponentInterface: resolvedAdapter.wrappedComponentInterface,
209
+ markerFile: resolvedAdapter.markerFile
208
210
  };
209
211
  const transformPath = (() => {
210
212
  const adjacent = join(__dirname, "transform.mjs");
@@ -232,12 +234,13 @@ async function runTransform(options) {
232
234
  bridgeResults,
233
235
  transformedFiles,
234
236
  transientPropRenames,
237
+ allowPartialMigration: options.allowPartialMigration ?? false,
235
238
  runInBand: true,
236
239
  silent: options.silent ?? false
237
240
  });
238
241
  if (sidecarFiles.size > 0 && !dryRun) for (const [sidecarPath, content] of sidecarFiles) await writeFile(sidecarPath, mergeSidecarContent(sidecarPath, content), "utf-8");
239
242
  if (bridgeResults.size > 0 && !dryRun) {
240
- const { buildConsumerReplacements, patchConsumerFile } = await import("./bridge-consumer-patcher-BbjyGr2R.mjs");
243
+ const { buildConsumerReplacements, patchConsumerFile } = await import("./bridge-consumer-patcher-DbMPzKPE.mjs");
241
244
  const consumerReplacements = buildConsumerReplacements(crossFilePrepassResult.selectorUsages, bridgeResults, transformedFiles);
242
245
  const patchedFiles = [];
243
246
  for (const [consumerPath, replacements] of consumerReplacements) {
@@ -250,7 +253,7 @@ async function runTransform(options) {
250
253
  if (formatterCommands && patchedFiles.length > 0) await runFormatters(formatterCommands, patchedFiles);
251
254
  }
252
255
  if (prepassResult.forwardedAsConsumers.size > 0 && !dryRun) {
253
- const { buildForwardedAsReplacements, patchConsumerForwardedAs } = await import("./forwarded-as-consumer-patcher-Rd7QcRNR.mjs");
256
+ const { buildForwardedAsReplacements, patchConsumerForwardedAs } = await import("./forwarded-as-consumer-patcher-CXfXrvkk.mjs");
254
257
  const forwardedAsReplacements = buildForwardedAsReplacements(prepassResult.forwardedAsConsumers, transformedFiles);
255
258
  const patchedFiles = [];
256
259
  for (const [consumerPath, entries] of forwardedAsReplacements) {
@@ -263,7 +266,7 @@ async function runTransform(options) {
263
266
  if (formatterCommands && patchedFiles.length > 0) await runFormatters(formatterCommands, patchedFiles);
264
267
  }
265
268
  if (transientPropRenames.size > 0 && !dryRun) {
266
- const { collectTransientPropPatches } = await import("./transient-prop-consumer-patcher-CeMJEJG9.mjs");
269
+ const { collectTransientPropPatches } = await import("./transient-prop-consumer-patcher-C5KQ2iFe.mjs");
267
270
  const patches = collectTransientPropPatches({
268
271
  transientPropRenames,
269
272
  consumerFilePaths: consumerFilePaths.map((p) => resolve(p)),
@@ -307,10 +310,6 @@ function createAutoPrepassFailureError(err, consumerPatterns, parser) {
307
310
  /**
308
311
  * Merge new sidecar marker content into an existing .stylex.ts file, preserving
309
312
  * user-owned exports (e.g. defineVars). If the file doesn't exist, returns content as-is.
310
- *
311
- * New marker declarations (`export const XMarker = stylex.defineMarker()`) are
312
- * appended only if they don't already exist in the file. The stylex import is
313
- * ensured at the top.
314
313
  */
315
314
  function mergeSidecarContent(sidecarPath, newContent) {
316
315
  let existing;
@@ -319,17 +318,7 @@ function mergeSidecarContent(sidecarPath, newContent) {
319
318
  } catch {
320
319
  return newContent;
321
320
  }
322
- const markerLineRe = /^export const \w+ = stylex\.defineMarker\(\);$/gm;
323
- const newMarkers = [];
324
- for (const m of newContent.matchAll(markerLineRe)) newMarkers.push(m[0]);
325
- if (newMarkers.length === 0) return newContent;
326
- const markersToAdd = newMarkers.filter((line) => !existing.includes(line));
327
- if (markersToAdd.length === 0) return existing;
328
- let merged = existing;
329
- if (!merged.includes("@stylexjs/stylex")) merged = `import * as stylex from "@stylexjs/stylex";\n\n${merged}`;
330
- const trailingNewline = merged.endsWith("\n") ? "" : "\n";
331
- merged = merged + trailingNewline + markersToAdd.join("\n") + "\n";
332
- return merged;
321
+ return mergeMarkerDeclarations(existing, newContent);
333
322
  }
334
323
  /** Run formatter commands on a list of files, logging warnings on failure. */
335
324
  async function runFormatters(commands, files) {
@@ -25,6 +25,13 @@ type ThemeResolveContext = {
25
25
  * Example: "padding", "margin", "border"
26
26
  */
27
27
  cssProperty?: string;
28
+ /**
29
+ * When true, this resolution is for an indexed (bracket) lookup like
30
+ * `props.theme.color[props.$bg]`. The adapter can use this to return a
31
+ * CSS-property-aware prebuilt mixin map (`usage: "props"`) instead of a
32
+ * raw token object used in `stylex.create()`.
33
+ */
34
+ indexedLookup?: boolean;
28
35
  };
29
36
  type CssVariableResolveContext = {
30
37
  kind: "cssVariable";
@@ -200,12 +207,22 @@ type ResolveValueResult = {
200
207
  /**
201
208
  * Disambiguates how the resolved expression is used:
202
209
  * - "props": a StyleX style object suitable for passing to `stylex.props(...)`.
203
- * Use this when resolving imported styled component mixins to their StyleX equivalent.
210
+ * Use this when resolving imported styled component mixins to their StyleX equivalent,
211
+ * or for indexed theme lookups that resolve to prebuilt per-property mixin maps.
204
212
  * - undefined (default): a value that can be used inside `stylex.create(...)`.
205
213
  *
206
- * Note: Only meaningful for `{ kind: "importedValue" }`.
214
+ * Meaningful for `{ kind: "importedValue" }` and `{ kind: "theme" }` with `indexedLookup`.
207
215
  */
208
216
  usage?: "props";
217
+ /**
218
+ * When `usage` is `"props"` and the resolved expression should be indexed with a
219
+ * dynamic prop value (e.g., `$colorMixins.backgroundColor[propValue]`):
220
+ * - `"memberAccess"`: the codemod applies `expr[propValue]` computed member access
221
+ *
222
+ * Only meaningful when `usage` is `"props"` and the resolution context is an indexed
223
+ * theme lookup (`indexedLookup: true`).
224
+ */
225
+ dynamicArgUsage?: "memberAccess";
209
226
  };
210
227
  type CallResolveResultWithExpr = {
211
228
  /**
@@ -500,6 +517,45 @@ type ExternalInterfaceResult = {
500
517
  elementProps?: boolean; /** Whether cross-file consumers use JSX spread ({...props}) */
501
518
  spreadProps?: boolean;
502
519
  };
520
+ interface MarkerFileContext {
521
+ /** Absolute path of the file being transformed */
522
+ filePath: string;
523
+ }
524
+ /**
525
+ * Context for `adapter.wrappedComponentInterface(...)`.
526
+ *
527
+ * Called for each `styled(Component)` declaration where `Component` is
528
+ * imported from another module. Lets the adapter declare that the wrapped
529
+ * component already accepts a StyleX `sx` prop so the codemod can emit
530
+ * `sx={style}` instead of `{...stylex.props(style)}`.
531
+ */
532
+ interface WrappedComponentInterfaceContext {
533
+ /**
534
+ * Import source for the wrapped base component.
535
+ * - package import: e.g. `"@company/ui"`
536
+ * - relative import: resolved absolute path
537
+ */
538
+ importSource: string;
539
+ /**
540
+ * Imported binding name for the wrapped base component.
541
+ * Example: `import { Button as UiButton } ...` -> importedName: "Button"
542
+ */
543
+ importedName: string;
544
+ /**
545
+ * Absolute path of the file currently being transformed.
546
+ */
547
+ filePath: string;
548
+ }
549
+ /**
550
+ * Result for `adapter.wrappedComponentInterface(...)`.
551
+ *
552
+ * - `acceptsSx: true` — the wrapped component accepts an `sx` prop. The codemod
553
+ * emits `sx={style}` instead of `{...stylex.props(style)}` and skips
554
+ * className/style merging in the wrapper (the wrapped component owns that).
555
+ */
556
+ interface WrappedComponentInterfaceResult {
557
+ acceptsSx: boolean;
558
+ }
503
559
  /**
504
560
  * Configuration for a custom style merger function that combines stylex.props()
505
561
  * results with external className/style props.
@@ -659,6 +715,49 @@ interface Adapter {
659
715
  * @default false
660
716
  */
661
717
  usePhysicalProperties?: boolean;
718
+ /**
719
+ * Optional override for sx-aware wrapped component detection.
720
+ *
721
+ * When `useSxProp: true`, the codemod auto-detects whether an imported
722
+ * component accepts a StyleX `sx` prop by reading its definition file and
723
+ * walking its declared prop type (intersections, type aliases, interfaces
724
+ * in the same file). When detected, `styled(Component)` emits
725
+ * `<Component sx={styles.x} />` instead of
726
+ * `<Component {...stylex.props(styles.x)} />`.
727
+ *
728
+ * Use this hook to override auto-detection for cases it cannot see — for
729
+ * example unresolvable package imports or components whose sx support is
730
+ * added by a HOC at runtime.
731
+ *
732
+ * Return:
733
+ * - `{ acceptsSx: true }` to force the `sx={...}` path
734
+ * - `{ acceptsSx: false }` to force the `{...stylex.props(...)}` path
735
+ * - `undefined` to fall through to auto-detection (default)
736
+ *
737
+ * Only consulted for `styled(ImportedComponent)` declarations.
738
+ */
739
+ wrappedComponentInterface?: (context: WrappedComponentInterfaceContext) => WrappedComponentInterfaceResult | undefined;
740
+ /**
741
+ * Optional function to customize where marker sidecar files (`stylex.defineMarker()`)
742
+ * are written. By default, markers are placed in a `.stylex.ts` file next to the source.
743
+ *
744
+ * When provided, the function receives the source file path and returns an `ImportSource`
745
+ * that determines both the import path in the transformed file and the file path where
746
+ * markers are written. Return `undefined` to fall back to the default behavior (local
747
+ * sidecar file next to the source).
748
+ *
749
+ * Only consulted when a file has cross-file marker relations. Files that only
750
+ * reference markers internally (e.g., sibling selectors within the same file)
751
+ * always use a local sidecar file regardless of this setting.
752
+ *
753
+ * Example:
754
+ * ```typescript
755
+ * markerFile(ctx) {
756
+ * return { kind: "absolutePath", value: "/path/to/shared/markers.stylex.ts" };
757
+ * }
758
+ * ```
759
+ */
760
+ markerFile?: (context: MarkerFileContext) => ImportSource | undefined;
662
761
  }
663
762
  /**
664
763
  * User-facing adapter input type accepted by `defineAdapter()`.
@@ -686,6 +785,8 @@ interface AdapterInput {
686
785
  themeHook?: Adapter["themeHook"];
687
786
  useSxProp: Adapter["useSxProp"];
688
787
  usePhysicalProperties?: Adapter["usePhysicalProperties"];
788
+ wrappedComponentInterface?: Adapter["wrappedComponentInterface"];
789
+ markerFile?: Adapter["markerFile"];
689
790
  }
690
791
  /**
691
792
  * Helper for nicer user authoring + type inference.
@@ -763,7 +864,7 @@ declare function defineAdapter<T extends AdapterInput>(adapter: T): T;
763
864
  //#endregion
764
865
  //#region src/internal/logger.d.ts
765
866
  type Severity = "info" | "warning" | "error";
766
- type WarningType = "`css` helper function switch must return css templates in all branches" | "`css` helper usage as a function call (css(...)) is not supported" | "`css` helper used outside of a styled component template cannot be statically transformed" | "Adapter helper call in border interpolation did not resolve to a single CSS value" | "Adapter resolveCall returned an unparseable styles expression" | "Adapter resolveCall returned an unparseable value expression" | "Adapter resolveCall returned StyleX styles for helper call where a CSS value was expected" | "Adapter resolveCall returned undefined for helper call" | "Adapter resolveBaseComponent threw an error" | "Adapter resolved StyleX styles cannot be applied under nested selectors/at-rules" | "Adapter resolved StyleX styles inside pseudo selector but did not provide cssText for property expansion — add cssText to resolveCall result to enable pseudo-wrapping" | 'Adapter resolveCall cssText could not be parsed as CSS declarations — expected semicolon-separated property: value pairs (e.g. "white-space: nowrap; overflow: hidden;")' | "Adapter resolveValue returned an unparseable value expression" | "Adapter resolveValue returned undefined for imported value" | "Arrow function: body is not a recognized pattern (expected ternary, logical, call, or member expression)" | "Arrow function: conditional branches could not be resolved to static or theme values" | "Arrow function: helper call body is not supported" | "Arrow function: indexed theme lookup pattern not matched" | "Arrow function: logical expression pattern not supported" | "Arrow function: prop access cannot be converted to style function for this CSS property" | "Arrow function: theme access path could not be resolved" | "Component selectors like `${OtherComponent}:hover &` are not directly representable in StyleX. Manual refactor is required" | "Conditional `css` block: !important is not supported in StyleX" | "Conditional `css` block: @-rules (e.g., @media, @supports) are not supported" | "CSS block contains unsupported at-rule (only @media and @container are supported; @supports, etc. require manual handling)" | "Conditional `css` block: dynamic interpolation could not be resolved to a single component prop" | "Conditional `css` block: failed to parse expression" | "Conditional `css` block: missing CSS property name" | "Conditional `css` block: missing interpolation expression" | "Conditional `css` block: mixed static/dynamic values with non-theme expressions cannot be safely transformed" | "Conditional `css` block: multiple interpolation slots in a single property value" | "Conditional `css` block: ternary branch value could not be resolved (imported values require adapter support)" | "Conditional `css` block: ternary expressions inside pseudo selectors are not supported" | "Conditional `css` block: media query interpolation must be a simple imported reference (expressions like `value + 1` are not supported)" | "Conditional `css` block: unsupported selector" | "Directional border helper styles are not supported" | "Multi-slot border interpolation could not be resolved" | "Resolved border helper value could not be expanded to longhand properties" | "Resolved conditional border variant could not be expanded to longhand properties" | "createGlobalStyle is not supported in StyleX. Global styles should be handled separately (e.g., in a CSS file or using CSS reset libraries)" | "Failed to parse theme expressions" | "Heterogeneous background values (mix of gradients and colors) not currently supported" | "Higher-order styled factory wrappers (e.g. hoc(styled)) are not supported" | "Imported CSS helper mixins: cannot determine inherited properties for correct pseudo selector handling" | "Local helper function returns CSS that cannot be decomposed into individual properties" | "Local helper function computes CSS values that cannot be statically traced to the component prop" | "Styled-components specificity hacks like `&&` / `&&&` are not representable in StyleX" | "Theme-dependent block-level conditional could not be fully resolved (branches may contain dynamic interpolations)" | "Theme-dependant call expression could not be resolved (e.g. theme helper calls like theme.highlight() are not supported)" | "Theme value with fallback (props.theme.X ?? / || default) cannot be resolved statically — use adapter.resolveValue to map theme paths to StyleX tokens" | "Theme-dependent nested prop access requires a project-specific theme source (e.g. useTheme())" | "Theme-dependent template literals require a project-specific theme source (e.g. useTheme())" | "Theme prop overrides on styled components are not supported" | "Universal selectors (`*`) are currently unsupported" | "Unsupported call expression (expected imported helper(...) or imported helper(...)(...))" | "Unsupported conditional test in shouldForwardProp" | "Unsupported shouldForwardProp pattern (only !prop.startsWith(), ![].includes(prop), and prop !== are supported)" | "Unsupported interpolation: arrow function" | "Unsupported interpolation: call expression" | "Unsupported interpolation: identifier" | "Unsupported interpolation: member expression" | "Unsupported interpolation: property" | "Unsupported interpolation: unknown" | "Unsupported nested conditional interpolation" | "Unsupported prop-based inline style expression cannot be safely inlined" | "Unsupported prop-based inline style props.theme access is not supported" | "Unsupported selector interpolation: imported value in selector position" | "Unsupported: media query interpolation must be a simple imported reference (expressions like `value + 1` are not supported)" | "Unsupported selector: class selector" | "Unsupported selector: comma-separated selectors must all be simple pseudos or pseudo-elements" | "Unsupported selector: descendant pseudo selector (space before pseudo)" | "Unsupported selector: descendant/child/sibling selector" | "Unsupported selector: interpolated pseudo selector" | "Unsupported selector: sibling combinator" | "Unsupported selector: unresolved interpolation in sibling selector" | "Unsupported selector: ambiguous element selector" | "Unsupported selector: attribute selector on unsupported element" | "Unsupported selector: element selector on exported component" | "Unsupported selector: element selector with combined ancestor and child pseudos" | "Unsupported selector: element selector with dynamic children" | "Unsupported selector: element selector with plain intrinsic children" | "Unsupported selector: element selector pseudo collision" | "Unsupported selector: cross-file component selector target has no JSX usage in this file" | "Unsupported selector: unresolved interpolation in cross-file component selector" | "Unsupported selector: unresolved interpolation in descendant component selector" | "Unsupported selector: unresolved interpolation in element selector" | "Unsupported selector: unresolved interpolation in reverse component selector" | "Unsupported selector: unresolved interpolation in cross-component sibling selector" | "Unsupported selector: grouped reverse selector references different components" | "Unsupported selector: computed media query inside ancestor attribute selector" | "Unsupported selector: computed media query inside cross-component sibling selector" | "Unsupported selector: computed media query inside sibling selector" | "Unsupported selector: computed media query inside :has() component selector" | "Unsupported selector: cross-file :has() component selector not yet supported" | "Unsupported selector: unresolved interpolation in :has() component selector" | "Unsupported selector: unknown component selector" | "Unsupported css`` mixin: after-base mixin style is not a plain object" | "Unsupported css`` mixin: nested contextual conditions in after-base mixin" | "Unsupported css`` mixin: cannot infer base default for after-base contextual override (base value is non-literal)" | "css`` helper function interpolation references closure variable that cannot be hoisted" | "Using styled-components components as mixins is not supported; use css`` mixins or strings instead" | "styled(ImportedComponent) wraps a component whose file contains internal styled-components — convert the base component's file first to avoid CSS cascade conflicts" | "Transient $-prefixed props renamed on exported component — update consumer call sites to use the new prop names" | "Shorthand property has an opaque value that StyleX will expand to longhands — use `directional` in resolveValue to return separate longhand tokens";
867
+ type WarningType = "`css` helper function switch must return css templates in all branches" | "`css` helper usage as a function call (css(...)) is not supported" | "`css` helper used outside of a styled component template cannot be statically transformed" | "Adapter helper call in border interpolation did not resolve to a single CSS value" | "Adapter resolveCall returned an unparseable styles expression" | "Adapter resolveCall returned an unparseable value expression" | "Adapter resolveCall returned StyleX styles for helper call where a CSS value was expected" | "Adapter resolveCall returned undefined for helper call" | "Adapter resolveBaseComponent threw an error" | "Adapter resolved StyleX styles cannot be applied under nested selectors/at-rules" | "Adapter resolved StyleX styles inside pseudo selector but did not provide cssText for property expansion — add cssText to resolveCall result to enable pseudo-wrapping" | 'Adapter resolveCall cssText could not be parsed as CSS declarations — expected semicolon-separated property: value pairs (e.g. "white-space: nowrap; overflow: hidden;")' | "Adapter resolveValue returned an unparseable value expression" | "Adapter resolveValue returned undefined for imported value" | "Arrow function: body is not a recognized pattern (expected ternary, logical, call, or member expression)" | "Arrow function: conditional branches could not be resolved to static or theme values" | "Arrow function: helper call body is not supported" | "Arrow function: indexed theme lookup pattern not matched" | "Arrow function: logical expression pattern not supported" | "Arrow function: prop access cannot be converted to style function for this CSS property" | "Arrow function: theme access path could not be resolved" | "Component selectors like `${OtherComponent}:hover &` are not directly representable in StyleX. Manual refactor is required" | "Conditional `css` block: !important is not supported in StyleX" | "Conditional `css` block: @-rules (e.g., @media, @supports) are not supported" | "CSS block contains unsupported at-rule (only @media and @container are supported; @supports, etc. require manual handling)" | "Conditional `css` block: dynamic interpolation could not be resolved to a single component prop" | "Conditional `css` block: failed to parse expression" | "Conditional `css` block: missing CSS property name" | "Conditional `css` block: missing interpolation expression" | "Conditional `css` block: mixed static/dynamic values with non-theme expressions cannot be safely transformed" | "Conditional `css` block: multiple interpolation slots in a single property value" | "Conditional `css` block: ternary branch value could not be resolved (imported values require adapter support)" | "Conditional `css` block: ternary expressions inside pseudo selectors are not supported" | "Conditional `css` block: media query interpolation must be a simple imported reference (expressions like `value + 1` are not supported)" | "Conditional `css` block: unsupported selector" | "Directional border helper styles are not supported" | "Multi-slot border interpolation could not be resolved" | "Resolved border helper value could not be expanded to longhand properties" | "Resolved conditional border variant could not be expanded to longhand properties" | "createGlobalStyle is not supported in StyleX. Global styles should be handled separately (e.g., in a CSS file or using CSS reset libraries)" | "Failed to parse theme expressions" | "Heterogeneous background values (mix of gradients and colors) not currently supported" | "Higher-order styled factory wrappers (e.g. hoc(styled)) are not supported" | "Imported CSS helper mixins: cannot determine inherited properties for correct pseudo selector handling" | "Local helper function returns CSS that cannot be decomposed into individual properties" | "Local helper function computes CSS values that cannot be statically traced to the component prop" | "Styled-components specificity hacks like `&&` / `&&&` are not representable in StyleX" | "Theme-dependent block-level conditional could not be fully resolved (branches may contain dynamic interpolations)" | "Theme-dependant call expression could not be resolved (e.g. theme helper calls like theme.highlight() are not supported)" | "Theme value with fallback (props.theme.X ?? / || default) cannot be resolved statically — use adapter.resolveValue to map theme paths to StyleX tokens" | "Theme-dependent nested prop access requires a project-specific theme source (e.g. useTheme())" | "Theme-dependent template literals require a project-specific theme source (e.g. useTheme())" | "Theme prop overrides on styled components are not supported" | "Universal selectors (`*`) are currently unsupported" | "Unsupported call expression (expected imported helper(...) or imported helper(...)(...))" | "Unsupported conditional test in shouldForwardProp" | "Unsupported shouldForwardProp pattern (only !prop.startsWith(), ![].includes(prop), and prop !== are supported)" | "Unsupported interpolation: arrow function" | "Unsupported interpolation: call expression" | "Unsupported interpolation: identifier" | "Unsupported interpolation: member expression" | "Unsupported interpolation: property" | "Unsupported interpolation: unknown" | "Unsupported nested conditional interpolation" | "Unsupported prop-based inline style expression cannot be safely inlined" | "Unsupported prop-based inline style props.theme access is not supported" | "Unsupported selector interpolation: imported value in selector position" | "Unsupported: media query interpolation must be a simple imported reference (expressions like `value + 1` are not supported)" | "Unsupported selector: class selector" | "Unsupported selector: comma-separated selectors must all be simple pseudos or pseudo-elements" | "Unsupported selector: descendant pseudo selector (space before pseudo)" | "Unsupported selector: adjacent sibling combinator" | "Unsupported selector: descendant/child/sibling selector" | "Unsupported selector: interpolated pseudo selector" | "Unsupported selector: sibling combinator" | "Unsupported selector: unresolved interpolation in sibling selector" | "Unsupported selector: ambiguous element selector" | "Unsupported selector: attribute selector on unsupported element" | "Unsupported selector: element selector on exported component" | "Unsupported selector: element selector with combined ancestor and child pseudos" | "Unsupported selector: element selector with dynamic children" | "Unsupported selector: element selector with plain intrinsic children" | "Unsupported selector: element selector pseudo collision" | "Unsupported selector: cross-file component selector target has no JSX usage in this file" | "Unsupported selector: unresolved interpolation in cross-file component selector" | "Unsupported selector: unresolved interpolation in descendant component selector" | "Unsupported selector: unresolved interpolation in element selector" | "Unsupported selector: unresolved interpolation in reverse component selector" | "Unsupported selector: unresolved interpolation in cross-component sibling selector" | "Unsupported selector: grouped reverse selector references different components" | "Unsupported selector: computed media query inside ancestor attribute selector" | "Unsupported selector: computed media query inside cross-component sibling selector" | "Unsupported selector: computed media query inside sibling selector" | "Unsupported selector: computed media query inside :has() component selector" | "Unsupported selector: cross-file :has() component selector not yet supported" | "Unsupported selector: unresolved interpolation in :has() component selector" | "Unsupported selector: unknown component selector" | "Unsupported css`` mixin: after-base mixin style is not a plain object" | "Unsupported css`` mixin: nested contextual conditions in after-base mixin" | "Unsupported css`` mixin: cannot infer base default for after-base contextual override (base value is non-literal)" | "css`` helper function interpolation references closure variable that cannot be hoisted" | "Using styled-components components as mixins is not supported; use css`` mixins or strings instead" | "styled(ImportedComponent) wraps a component whose file uses styled-components — convert the base component's file first to avoid CSS cascade conflicts" | "Partial transform would have a StyleX leaf wrap a styled-components base — the extending component was transformed but its base was not, so the leaf's StyleX overrides cannot reliably beat the base's styled-components styles" | "Transient $-prefixed props renamed on exported component — update consumer call sites to use the new prop names" | "Shorthand property has an opaque value that StyleX will expand to longhands — use `directional` in resolveValue to return separate longhand tokens" | "animation shorthand contains a var() with no classifiable fallback — its longhand position cannot be determined statically; bind the variable to a specific longhand (e.g. animation-duration: var(--x)) instead";
767
868
  interface WarningLog {
768
869
  severity: Severity;
769
870
  type: WarningType;
@@ -777,4 +878,4 @@ interface CollectedWarning extends WarningLog {
777
878
  filePath: string;
778
879
  }
779
880
  //#endregion
780
- export { defineAdapter as a, AdapterInput as i, WarningLog as n, Adapter as r, CollectedWarning as t };
881
+ export { ImportSource as a, AdapterInput as i, WarningLog as n, MarkerFileContext as o, Adapter as r, defineAdapter as s, CollectedWarning as t };
@@ -133,6 +133,23 @@ function assertAdapterShape(candidate, where, allowAutoExtIf) {
133
133
  absolutePathExample: "/path/to/module.ts"
134
134
  });
135
135
  }
136
+ const markerFile = obj?.markerFile;
137
+ if (markerFile !== void 0 && markerFile !== null && typeof markerFile !== "function") throw new Error([
138
+ `${where}: adapter.markerFile must be a function when provided.`,
139
+ `Received: markerFile=${describeValue(markerFile)}`,
140
+ "",
141
+ "Expected signature:",
142
+ " markerFile(ctx: { filePath: string }) => { kind: \"specifier\" | \"absolutePath\", value: string }"
143
+ ].join("\n"));
144
+ const wrappedComponentInterface = obj?.wrappedComponentInterface;
145
+ if (wrappedComponentInterface !== void 0 && wrappedComponentInterface !== null && typeof wrappedComponentInterface !== "function") throw new Error([
146
+ `${where}: adapter.wrappedComponentInterface must be a function when provided.`,
147
+ `Received: wrappedComponentInterface=${describeValue(wrappedComponentInterface)}`,
148
+ "",
149
+ "Expected signature:",
150
+ " wrappedComponentInterface(ctx: { importSource: string; importedName: string; filePath: string })",
151
+ " => { acceptsSx: boolean } | undefined"
152
+ ].join("\n"));
136
153
  const themeHook = obj?.themeHook;
137
154
  if (themeHook !== null && themeHook !== void 0) {
138
155
  if (typeof themeHook !== "object") throw new Error([
@@ -269,4 +286,33 @@ function defineAdapter(adapter) {
269
286
  return adapter;
270
287
  }
271
288
  //#endregion
272
- export { assertValidAdapterInput as a, assertValidAdapter as i, defineAdapter as n, describeValue as o, isDirectionalResult as r, DEFAULT_THEME_HOOK as t };
289
+ //#region src/internal/merge-markers.ts
290
+ /**
291
+ * Shared utility for merging marker sidecar content.
292
+ * Core concepts: deduplication of defineMarker declarations across files.
293
+ */
294
+ /** Regex matching a marker block: optional JSDoc comment followed by the export line. */
295
+ const MARKER_BLOCK_RE = /(?:\/\*\*[^]*?\*\/\n)?export const \w+ = stylex\.defineMarker\(\);/gm;
296
+ /** Regex matching just the export line (used for dedup checks). */
297
+ const MARKER_EXPORT_RE = /^export const \w+ = stylex\.defineMarker\(\);$/gm;
298
+ /**
299
+ * Merge marker declarations from `incoming` into `base`, appending only new
300
+ * marker blocks (JSDoc + export). Returns `base` unchanged if all markers already exist.
301
+ */
302
+ function mergeMarkerDeclarations(base, incoming) {
303
+ const incomingExports = [...incoming.matchAll(MARKER_EXPORT_RE)].map((m) => m[0]);
304
+ if (incomingExports.length === 0) return base;
305
+ const newExportLines = incomingExports.filter((line) => !base.includes(line));
306
+ if (newExportLines.length === 0) return base;
307
+ const newExportSet = new Set(newExportLines);
308
+ const blocksToAdd = [...incoming.matchAll(MARKER_BLOCK_RE)].map((m) => m[0]).filter((block) => {
309
+ const exportLine = block.match(MARKER_EXPORT_RE);
310
+ return exportLine && newExportSet.has(exportLine[0]);
311
+ });
312
+ if (blocksToAdd.length === 0) return base;
313
+ let merged = base;
314
+ if (!merged.includes("@stylexjs/stylex")) merged = `import * as stylex from "@stylexjs/stylex";\n\n${merged}`;
315
+ return merged.trimEnd() + "\n\n" + blocksToAdd.join("\n\n") + "\n";
316
+ }
317
+ //#endregion
318
+ export { assertValidAdapter as a, isDirectionalResult as i, DEFAULT_THEME_HOOK as n, assertValidAdapterInput as o, defineAdapter as r, describeValue as s, mergeMarkerDeclarations as t };
@@ -0,0 +1,30 @@
1
+ import { resolve } from "node:path";
2
+ import { realpathSync } from "node:fs";
3
+ //#region src/internal/utilities/path-utils.ts
4
+ /**
5
+ * Shared path utilities for symlink resolution and path normalization.
6
+ */
7
+ /**
8
+ * Resolve a file path to its real (symlink-resolved) absolute path.
9
+ * Falls back to pathResolve if realpathSync fails (e.g. file doesn't exist yet).
10
+ */
11
+ function toRealPath(filePath) {
12
+ const resolved = resolve(filePath);
13
+ try {
14
+ return realpathSync(resolved);
15
+ } catch {
16
+ return resolved;
17
+ }
18
+ }
19
+ /**
20
+ * Returns `true` for ESM/CJS module specifiers that should be resolved
21
+ * relative to the importing file (e.g. `./foo`, `../bar`, `.`, `..`). Bare
22
+ * specifiers like `react` or `@scope/pkg` return `false`. Backslash-prefixed
23
+ * forms are accepted to match how authoring tools sometimes emit Windows
24
+ * paths into source.
25
+ */
26
+ function isRelativeSpecifier(specifier) {
27
+ return specifier === "." || specifier === ".." || specifier.startsWith("./") || specifier.startsWith("../") || specifier.startsWith(".\\") || specifier.startsWith("..\\");
28
+ }
29
+ //#endregion
30
+ export { toRealPath as n, isRelativeSpecifier as t };
@@ -1,4 +1,16 @@
1
1
  import { ResolverFactory } from "oxc-resolver";
2
+ //#region \0rolldown/runtime.js
3
+ var __defProp = Object.defineProperty;
4
+ var __exportAll = (all, no_symbols) => {
5
+ let target = {};
6
+ for (var name in all) __defProp(target, name, {
7
+ get: all[name],
8
+ enumerable: true
9
+ });
10
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
11
+ return target;
12
+ };
13
+ //#endregion
2
14
  //#region src/internal/prepass/resolve-imports.ts
3
15
  /**
4
16
  * Module resolution using oxc-resolver.
@@ -10,6 +22,7 @@ import { ResolverFactory } from "oxc-resolver";
10
22
  * - Package exports field
11
23
  * - Symlink resolution (pnpm/Yarn workspaces)
12
24
  */
25
+ var resolve_imports_exports = /* @__PURE__ */ __exportAll({ createModuleResolver: () => createModuleResolver });
13
26
  /**
14
27
  * Shared resolver config for TypeScript projects.
15
28
  *
@@ -61,4 +74,4 @@ function createModuleResolver(config = DEFAULT_CONFIG) {
61
74
  } };
62
75
  }
63
76
  //#endregion
64
- export { createModuleResolver };
77
+ export { resolve_imports_exports as n, createModuleResolver as t };
@@ -1,7 +1,7 @@
1
- import { t as Logger } from "./logger-C2O81VeU.mjs";
2
- import { n as escapeRegex } from "./string-utils-5EMAWj3q.mjs";
3
- import { t as PLACEHOLDER_RE } from "./styled-css-C3QKH6Od.mjs";
4
- import { t as isSelectorContext } from "./selector-context-heuristic-Dualf7ac.mjs";
1
+ import { t as Logger } from "./logger-fIHHMZYO.mjs";
2
+ import { r as escapeRegex } from "./string-utils-Bq7DbB2x.mjs";
3
+ import { t as PLACEHOLDER_RE } from "./styled-css-Bu2bjAUW.mjs";
4
+ import { t as isSelectorContext } from "./selector-context-heuristic-DE3JAmpc.mjs";
5
5
  import path, { relative, resolve } from "node:path";
6
6
  import { readFileSync, realpathSync } from "node:fs";
7
7
  import { execSync } from "node:child_process";
@@ -665,12 +665,14 @@ async function runPrepass(options) {
665
665
  {
666
666
  const seen = /* @__PURE__ */ new Set();
667
667
  for (const { file, name } of styledCallUsages) {
668
- const importInfo = findImportSource(cachedRead(file), name);
669
- if (!importInfo) continue;
670
- const { source: importSource, exportedName } = importInfo;
671
- let defFile = resolve$1(importSource, file);
672
- if (!defFile) continue;
673
- defFile = resolveBarrelReExport(defFile, exportedName, resolve$1, cachedRead) ?? defFile;
668
+ const def = resolveDefinitionFile({
669
+ file,
670
+ localName: name,
671
+ cachedRead,
672
+ resolve: resolve$1
673
+ });
674
+ if (!def) continue;
675
+ const { defFile, exportedName } = def;
674
676
  const key = `${defFile}:${exportedName}`;
675
677
  if (seen.has(key)) continue;
676
678
  seen.add(key);
@@ -689,12 +691,14 @@ async function runPrepass(options) {
689
691
  const forwardedAsConsumers = /* @__PURE__ */ new Map();
690
692
  if (createExternalInterface && styledWrapperUsages.length > 0) for (const { file, localStyledName, wrappedName } of styledWrapperUsages) {
691
693
  if (transformSet.has(file)) continue;
692
- const importInfo = findImportSource(cachedRead(file), wrappedName);
693
- if (!importInfo) continue;
694
- const { source: importSource, exportedName } = importInfo;
695
- let defFile = resolve$1(importSource, file);
696
- if (!defFile) continue;
697
- defFile = resolveBarrelReExport(defFile, exportedName, resolve$1, cachedRead) ?? defFile;
694
+ const def = resolveDefinitionFile({
695
+ file,
696
+ localName: wrappedName,
697
+ cachedRead,
698
+ resolve: resolve$1
699
+ });
700
+ if (!def) continue;
701
+ const { defFile } = def;
698
702
  if (!transformSet.has(defFile)) continue;
699
703
  let entries = forwardedAsConsumers.get(file);
700
704
  if (!entries) {
@@ -1005,5 +1009,22 @@ function logPrepassDebug(scannedFiles, info, consumerAnalysis) {
1005
1009
  if (consumerAnalysis) lines.push(` Consumer analysis: ${consumerAnalysis.size} entries`);
1006
1010
  process.stderr.write(lines.join("\n") + "\n");
1007
1011
  }
1012
+ /**
1013
+ * Resolve a local identifier in `file` to the absolute path of the module that
1014
+ * defines it, following barrel re-exports. Returns `null` when the import
1015
+ * cannot be located on disk.
1016
+ */
1017
+ function resolveDefinitionFile(args) {
1018
+ const { file, localName, cachedRead, resolve } = args;
1019
+ const importInfo = findImportSource(cachedRead(file), localName);
1020
+ if (!importInfo) return null;
1021
+ const { source: importSource, exportedName } = importInfo;
1022
+ const initialDefFile = resolve(importSource, file);
1023
+ if (!initialDefFile) return null;
1024
+ return {
1025
+ defFile: resolveBarrelReExport(initialDefFile, exportedName, resolve, cachedRead) ?? initialDefFile,
1026
+ exportedName
1027
+ };
1028
+ }
1008
1029
  //#endregion
1009
1030
  export { runPrepass };
@@ -29,6 +29,18 @@ function kebabToCamelCase(s) {
29
29
  return s.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
30
30
  }
31
31
  /**
32
+ * Converts a camelCase string to kebab-case.
33
+ * Preserves CSS custom property prefixes (`--foo`). React uses leading uppercase
34
+ * to indicate vendor prefixes (e.g. `WebkitAppearance` → `-webkit-appearance`).
35
+ * @example camelToKebabCase("backgroundColor") => "background-color"
36
+ * @example camelToKebabCase("padding") => "padding"
37
+ * @example camelToKebabCase("WebkitAppearance") => "-webkit-appearance"
38
+ */
39
+ function camelToKebabCase(s) {
40
+ if (s.startsWith("--")) return s;
41
+ return s.replace(/([A-Z])/g, (_, ch) => `-${ch.toLowerCase()}`);
42
+ }
43
+ /**
32
44
  * Lowercases the first character of a string.
33
45
  * @example lowerFirst("Hello") => "hello"
34
46
  */
@@ -93,4 +105,4 @@ function normalizeWhitespace(s) {
93
105
  return s.replace(/\s+/g, " ").trim();
94
106
  }
95
107
  //#endregion
96
- export { isValidIdentifierName as a, lowerFirst as c, isPrettierIgnoreComment as i, normalizeWhitespace as l, escapeRegex as n, kebabToCamelCase as o, isBackgroundImageValue as r, looksLikeLength as s, capitalize as t, sanitizeIdentifier as u };
108
+ export { isPrettierIgnoreComment as a, looksLikeLength as c, sanitizeIdentifier as d, isBackgroundImageValue as i, lowerFirst as l, capitalize as n, isValidIdentifierName as o, escapeRegex as r, kebabToCamelCase as s, camelToKebabCase as t, normalizeWhitespace as u };