@astryxdesign/build 0.6.3-canary.7ada42e → 0.6.3-canary.7ec7be0

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
@@ -15,6 +15,7 @@ StyleX generates atomic CSS: same declaration = same class name. Without separat
15
15
  1. Compiling Astryx library code with `astryx` prefix (`.astryx78zum5`)
16
16
  2. Compiling product code with default `x` prefix (`.x78zum5`)
17
17
  3. Placing each group in its own CSS `@layer`
18
+ 4. Rejecting unsupported StyleX declarations instead of silently omitting them
18
19
 
19
20
  ## Packages
20
21
 
@@ -74,6 +75,7 @@ module.exports = {
74
75
  {
75
76
  dev: process.env.NODE_ENV !== 'production',
76
77
  runtimeInjection: false,
78
+ propertyValidationMode: 'throw',
77
79
  treeshakeCompensation: true,
78
80
  enableInlinedConditionalMerge: true,
79
81
  aliases: {
@@ -186,6 +188,7 @@ export default defineConfig({
186
188
  stylexOptions: {
187
189
  dev: process.env.NODE_ENV === 'development',
188
190
  runtimeInjection: false,
191
+ propertyValidationMode: 'throw',
189
192
  treeshakeCompensation: true,
190
193
  unstable_moduleResolution: {
191
194
  type: 'commonJS',
@@ -232,7 +235,9 @@ Compiles StyleX from both library and product source files in two separate passe
232
235
 
233
236
  ### Vite plugin (`@astryxdesign/build/vite`)
234
237
 
235
- Wraps `@stylexjs/unplugin` and intercepts the dev CSS endpoint (`/virtual:stylex.css`). Partitions the collected rules by file path and serves split-layer CSS.
238
+ Wraps `@stylexjs/unplugin` and intercepts the dev CSS endpoint (`/virtual:stylex.css`). Partitions the collected rules by file path and serves split-layer CSS. Production builds write those rules to one cache-safe shared stylesheet and link it from every emitted HTML entry, without cross-loading entry-owned CSS.
239
+
240
+ Unsupported declarations fail the build by default with StyleX's replacement guidance. Set `propertyValidationMode` explicitly in `stylexOverrides` (modern API) or `stylexOptions` (legacy API) only when a migration needs the upstream `warn` or `silent` behavior.
236
241
 
237
242
  ---
238
243
 
package/dist/vite.mjs CHANGED
@@ -7,6 +7,7 @@ import fs from "node:fs";
7
7
  import path from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import { createRequire } from "node:module";
10
+ import { createHash } from "node:crypto";
10
11
  var __dirname = path.dirname(fileURLToPath(import.meta.url));
11
12
  var LIBRARY_PATTERN = "node_modules/@astryxdesign/";
12
13
  var STYLEX_CSS_PATH = "/virtual:stylex.css";
@@ -34,6 +35,7 @@ function astryxStylex(options = {}) {
34
35
  const stylexOptions = {
35
36
  dev,
36
37
  runtimeInjection: false,
38
+ propertyValidationMode: "throw",
37
39
  treeshakeCompensation: true,
38
40
  unstable_moduleResolution: {
39
41
  type: "commonJS",
@@ -189,24 +191,41 @@ function buildLayerSplitPlugin(basePlugin, options) {
189
191
  );
190
192
  const outDir = outputOptions.dir ? outputOptions.dir : outputOptions.file ? path.dirname(outputOptions.file) : null;
191
193
  if (!outDir || !fs.existsSync(outDir)) return;
192
- const patched = [];
194
+ const containingFiles = [];
193
195
  for (const file of listCssFiles(outDir)) {
194
196
  const css = fs.readFileSync(file, "utf-8");
195
197
  const at = css.lastIndexOf(merged);
196
198
  if (at === -1) continue;
197
- fs.writeFileSync(
198
- file,
199
- css.slice(0, at) + split + css.slice(at + merged.length)
200
- );
201
- patched.push(file);
199
+ containingFiles.push({ file, css, at });
202
200
  }
203
- if (patched.length === 0) {
201
+ if (containingFiles.length === 0) {
204
202
  this.error(
205
203
  `astryx-build-layer-split: StyleX emitted rules but its CSS block was not found in any stylesheet under ${outDir}, so Astryx and product styles could not be separated into their cascade layers. Leaving the build unsplit would let product styles lose to a theme. This usually means the StyleX plugin version changed how it emits CSS.`
206
204
  );
207
205
  return;
208
206
  }
209
- linkOrphanStylesheets(outDir, patched, base);
207
+ if (listHtmlFiles(outDir).length === 0) {
208
+ for (const { file, css, at } of containingFiles) {
209
+ fs.writeFileSync(
210
+ file,
211
+ css.slice(0, at) + split + css.slice(at + merged.length)
212
+ );
213
+ }
214
+ return;
215
+ }
216
+ for (const { file, css, at } of containingFiles) {
217
+ fs.writeFileSync(
218
+ file,
219
+ css.slice(0, at) + css.slice(at + merged.length)
220
+ );
221
+ }
222
+ const hash = createHash("sha256").update(split).digest("hex").slice(0, 8);
223
+ const sharedStylesheet = path.join(
224
+ path.dirname(containingFiles[0].file),
225
+ `astryx-stylex-${hash}.css`
226
+ );
227
+ fs.writeFileSync(sharedStylesheet, split);
228
+ linkStylesheetsForEveryPage(outDir, [sharedStylesheet], base);
210
229
  }
211
230
  };
212
231
  }
@@ -228,21 +247,18 @@ function listHtmlFiles(dir) {
228
247
  }
229
248
  return out;
230
249
  }
231
- function linkOrphanStylesheets(outDir, cssFiles, base) {
250
+ function linkStylesheetsForEveryPage(outDir, cssFiles, base) {
232
251
  const pages = listHtmlFiles(outDir);
233
252
  if (pages.length === 0) return;
234
- const orphans = cssFiles.filter((css) => {
235
- const name = path.basename(css);
236
- return !pages.some((page) => fs.readFileSync(page, "utf-8").includes(name));
237
- });
238
- if (orphans.length === 0) return;
239
- const links = orphans.map((css) => {
240
- const href = base.replace(/\/$/, "") + "/" + path.relative(outDir, css).split(path.sep).join("/");
241
- return `<link rel="stylesheet" crossorigin href="${href}">`;
242
- }).join("\n ");
243
253
  for (const page of pages) {
244
254
  const html = fs.readFileSync(page, "utf-8");
245
255
  if (!html.includes("</head>")) continue;
256
+ const missing = cssFiles.filter((css) => !html.includes(path.basename(css)));
257
+ if (missing.length === 0) continue;
258
+ const links = missing.map((css) => {
259
+ const href = base.replace(/\/$/, "") + "/" + path.relative(outDir, css).split(path.sep).join("/");
260
+ return `<link rel="stylesheet" crossorigin href="${href}">`;
261
+ }).join("\n ");
246
262
  fs.writeFileSync(page, html.replace("</head>", ` ${links}
247
263
  </head>`));
248
264
  }
@@ -273,18 +289,22 @@ function astryxStylexLegacy(options) {
273
289
  } = options;
274
290
  const libraryLayer = layers.library ?? "astryx-base";
275
291
  const productLayer = layers.product ?? "product";
292
+ const validatedStylexOptions = {
293
+ propertyValidationMode: "throw",
294
+ ...stylexOptions
295
+ };
276
296
  const astryxBabelPlugin = path.resolve(__dirname, "../src/babel.js");
277
- const existingPlugins = stylexOptions.babelConfig?.plugins ?? [];
297
+ const existingPlugins = validatedStylexOptions.babelConfig?.plugins ?? [];
278
298
  const basePlugin = stylex.vite({
279
- ...stylexOptions,
299
+ ...validatedStylexOptions,
280
300
  useCSSLayers: true,
281
301
  babelConfig: {
282
- ...stylexOptions.babelConfig,
302
+ ...validatedStylexOptions.babelConfig,
283
303
  plugins: [
284
304
  [
285
305
  astryxBabelPlugin,
286
306
  {
287
- ...stylexOptions,
307
+ ...validatedStylexOptions,
288
308
  libraryPrefix: stylexPrefix,
289
309
  babelConfig: void 0
290
310
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astryxdesign/build",
3
- "version": "0.6.3-canary.7ada42e",
3
+ "version": "0.6.3-canary.7ec7be0",
4
4
  "description": "Build plugins for Astryx source builds — babel, PostCSS, and Vite integrations",
5
5
  "author": "Meta Open Source",
6
6
  "license": "MIT",
package/src/babel.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Copyright (c) Meta Platforms, Inc. and affiliates.
2
2
 
3
- "use strict";
3
+ 'use strict';
4
4
 
5
5
  /**
6
6
  * @astryxdesign/build/babel
@@ -28,9 +28,20 @@ module.exports = function astryxBabelPlugin(api, options) {
28
28
  ...stylexOptions
29
29
  } = options;
30
30
 
31
+ // StyleX's upstream default is `silent`, which turns unsupported declarations
32
+ // into missing CSS. Astryx fails closed by default so consumer builds point at
33
+ // the declaration and the supported replacement instead.
34
+ const validatedStylexOptions = {
35
+ propertyValidationMode: 'throw',
36
+ ...stylexOptions,
37
+ };
38
+
31
39
  // Build the two sets of options — only classNamePrefix differs
32
- const libraryOpts = {...stylexOptions, classNamePrefix: libraryPrefix};
33
- const productOpts = {...stylexOptions, classNamePrefix};
40
+ const libraryOpts = {
41
+ ...validatedStylexOptions,
42
+ classNamePrefix: libraryPrefix,
43
+ };
44
+ const productOpts = {...validatedStylexOptions, classNamePrefix};
34
45
 
35
46
  // Create two plugin instances
36
47
  const libraryPlugin = stylexPlugin(api, libraryOpts);
@@ -82,18 +93,18 @@ module.exports = function astryxBabelPlugin(api, options) {
82
93
  // enter/exit form (Program uses this)
83
94
  visitor[key] = {};
84
95
  if (sample.enter) {
85
- visitor[key].enter = function(path, state) {
96
+ visitor[key].enter = function (path, state) {
86
97
  callVisitor.call(this, 'enter', key, path, state);
87
98
  };
88
99
  }
89
100
  if (sample.exit) {
90
- visitor[key].exit = function(path, state) {
101
+ visitor[key].exit = function (path, state) {
91
102
  callVisitor.call(this, 'exit', key, path, state);
92
103
  };
93
104
  }
94
105
  } else {
95
106
  // Simple function visitor
96
- visitor[key] = function(path, state) {
107
+ visitor[key] = function (path, state) {
97
108
  callVisitor.call(this, 'enter', key, path, state);
98
109
  };
99
110
  }
@@ -13,6 +13,7 @@ import {createRequire} from 'node:module';
13
13
  const require = createRequire(import.meta.url);
14
14
  const babel = require('@babel/core');
15
15
  const astryxBabelPlugin = require('./babel.js');
16
+ const {stylexOptions: buildStylexOptions} = require('./config.js');
16
17
 
17
18
  const SOURCE = `
18
19
  import * as stylex from '@stylexjs/stylex';
@@ -21,13 +22,24 @@ export const styles = stylex.create({
21
22
  });
22
23
  `;
23
24
 
25
+ const INVALID_BORDER_SOURCE = `
26
+ import * as stylex from '@stylexjs/stylex';
27
+ export const styles = stylex.create({
28
+ box: {borderTop: '1px solid var(--color-border)'},
29
+ });
30
+ `;
31
+
24
32
  /**
25
33
  * Transform a StyleX source through the Astryx babel wrapper as if it were an
26
34
  * Astryx library file, returning the emitted code. `libraryPrefix` controls the
27
35
  * atomic class-name prefix for library files.
28
36
  */
29
- function transformLibraryFile(libraryPrefix) {
30
- const result = babel.transformSync(SOURCE, {
37
+ function transformLibraryFile(
38
+ libraryPrefix,
39
+ source = SOURCE,
40
+ stylexOptions = {},
41
+ ) {
42
+ const result = babel.transformSync(source, {
31
43
  // A path matching one of the library patterns so the wrapper routes it
32
44
  // through the library plugin instance.
33
45
  filename: 'node_modules/@astryxdesign/core/src/Box/AstryxBox.tsx',
@@ -39,6 +51,7 @@ function transformLibraryFile(libraryPrefix) {
39
51
  {
40
52
  ...(libraryPrefix ? {libraryPrefix} : {}),
41
53
  unstable_moduleResolution: {type: 'commonJS', rootDir: process.cwd()},
54
+ ...stylexOptions,
42
55
  },
43
56
  ],
44
57
  ],
@@ -69,4 +82,30 @@ describe('Astryx babel wrapper -- library StyleX prefix', () => {
69
82
  expect(atoms.length).toBeGreaterThan(0);
70
83
  expect(atoms.every(c => c.startsWith('lib'))).toBe(true);
71
84
  });
85
+
86
+ it('rejects declarations that StyleX would otherwise drop silently', () => {
87
+ expect(() =>
88
+ transformLibraryFile(undefined, INVALID_BORDER_SOURCE),
89
+ ).toThrow(
90
+ /borderTop is not supported.*borderTopWidth.*borderTopStyle.*borderTopColor/s,
91
+ );
92
+ });
93
+
94
+ it('keeps the upstream validation mode override available', () => {
95
+ expect(() =>
96
+ transformLibraryFile(undefined, INVALID_BORDER_SOURCE, {
97
+ propertyValidationMode: 'silent',
98
+ }),
99
+ ).not.toThrow();
100
+ });
101
+
102
+ it('uses the same strict default in generated Babel and PostCSS configs', () => {
103
+ expect(buildStylexOptions(process.cwd()).propertyValidationMode).toBe(
104
+ 'throw',
105
+ );
106
+ expect(
107
+ buildStylexOptions(process.cwd(), {propertyValidationMode: 'warn'})
108
+ .propertyValidationMode,
109
+ ).toBe('warn');
110
+ });
72
111
  });
package/src/config.js CHANGED
@@ -41,6 +41,7 @@ function stylexOptions(rootDir, overrides = {}) {
41
41
  return {
42
42
  dev: process.env.NODE_ENV !== 'production',
43
43
  runtimeInjection: false,
44
+ propertyValidationMode: 'throw',
44
45
  enableInlinedConditionalMerge: true,
45
46
  treeshakeCompensation: true,
46
47
  aliases: resolveAliases(rootDir),
@@ -11,15 +11,20 @@
11
11
  * `astryx-base` they lose to one. Only the built artifact shows it, so this
12
12
  * builds one.
13
13
  *
14
- * Two shapes, because StyleX emits through two different paths:
14
+ * Three shapes, because StyleX emits through two different paths and merges
15
+ * all entries into one stylesheet:
15
16
  *
16
- * `layer-split` the app imports a stylesheet, so the bundle has a CSS
17
- * asset and StyleX appends to it in `generateBundle`
18
- * `layer-split-nocss` the app imports none, so StyleX writes its own file in
19
- * `writeBundle`, outside Rollup's graph
17
+ * `layer-split` the app imports a stylesheet, so the bundle has a
18
+ * CSS asset and StyleX appends in `generateBundle`
19
+ * `layer-split-nocss` the app imports none, so StyleX writes its own file
20
+ * in `writeBundle`, outside Rollup's graph
21
+ * `layer-split-multipage` two entries own distinct authored CSS, while both
22
+ * must load the one shared StyleX result
20
23
  *
21
- * The second is the one that was missing, and it hid two defects: the split did
22
- * not run there at all, and the file StyleX writes is not linked by any page.
24
+ * The no-CSS shape was originally missing, which hid two defects: the split did
25
+ * not run there at all, and the file StyleX writes was not linked by any page.
26
+ * The multi-page shape protects against linking StyleX from only one entry or
27
+ * cross-loading that entry's authored CSS into every page.
23
28
  *
24
29
  * What none of this can prove is which declaration actually paints — that is a
25
30
  * cascade fact, and it lives in .github/scripts/theme-layer-cascade.js.
@@ -43,39 +48,83 @@ const CORE_SRC = path.join(REPO_ROOT, 'packages/core/src');
43
48
  const LIBRARY_CLASS = /\.astryx[a-z0-9]{5,}/g;
44
49
  const PRODUCT_CLASS = /\.x[a-z0-9]{5,}/g;
45
50
 
46
- type Built = {css: string; cssName: string; html: string; outDir: string};
51
+ type Built = {
52
+ css: string;
53
+ cssName: string;
54
+ cssByName: Record<string, string>;
55
+ html: string;
56
+ htmlByName: Record<string, string>;
57
+ outDir: string;
58
+ };
47
59
 
48
- async function buildFixture(name: string): Promise<Built> {
60
+ async function buildFixture(
61
+ name: string,
62
+ htmlNames: string[] = ['index.html'],
63
+ ): Promise<Built> {
49
64
  const root = path.join(FIXTURES, name);
50
65
  const outDir = mkdtempSync(path.join(tmpdir(), `astryx-${name}-`));
51
- await build({
52
- root,
53
- logLevel: 'error',
54
- build: {outDir, emptyOutDir: true},
55
- resolve: {alias: {'@astryxdesign/core': CORE_SRC}},
56
- plugins: [
57
- react(),
58
- ...astryxStylex({
59
- stylexOptions: {
60
- dev: false,
61
- unstable_moduleResolution: {type: 'commonJS', rootDir: REPO_ROOT},
62
- aliases: {
63
- '@astryxdesign/core/*': [path.join(CORE_SRC, '*')],
64
- '@astryxdesign/core': [CORE_SRC],
66
+ try {
67
+ await build({
68
+ root,
69
+ logLevel: 'error',
70
+ build: {
71
+ outDir,
72
+ emptyOutDir: true,
73
+ ...(htmlNames.length > 1 && {
74
+ rollupOptions: {
75
+ input: Object.fromEntries(
76
+ htmlNames.map(file => [
77
+ path.basename(file, '.html'),
78
+ path.join(root, file),
79
+ ]),
80
+ ),
65
81
  },
66
- },
67
- libraryPattern: 'packages/core/',
68
- }),
69
- ],
70
- });
82
+ }),
83
+ },
84
+ resolve: {alias: {'@astryxdesign/core': CORE_SRC}},
85
+ plugins: [
86
+ react(),
87
+ ...astryxStylex({
88
+ stylexOptions: {
89
+ dev: false,
90
+ unstable_moduleResolution: {type: 'commonJS', rootDir: REPO_ROOT},
91
+ aliases: {
92
+ '@astryxdesign/core/*': [path.join(CORE_SRC, '*')],
93
+ '@astryxdesign/core': [CORE_SRC],
94
+ },
95
+ },
96
+ libraryPattern: 'packages/core/',
97
+ }),
98
+ ],
99
+ });
100
+ } catch (error) {
101
+ rmSync(outDir, {recursive: true, force: true});
102
+ throw error;
103
+ }
71
104
 
72
105
  const assets = path.join(outDir, 'assets');
73
- const cssName = readdirSync(assets).find(f => f.endsWith('.css'));
74
- if (!cssName) throw new Error(`no stylesheet emitted into ${assets}`);
106
+ const cssNames = readdirSync(assets).filter(f => f.endsWith('.css'));
107
+ const cssByName = Object.fromEntries(
108
+ cssNames.map(file => [
109
+ file,
110
+ readFileSync(path.join(assets, file), 'utf-8'),
111
+ ]),
112
+ );
113
+ const cssName = cssNames.find(f => f.startsWith('astryx-stylex-'));
114
+ if (!cssName)
115
+ throw new Error(`no shared StyleX stylesheet emitted into ${assets}`);
116
+ const htmlByName = Object.fromEntries(
117
+ htmlNames.map(file => [
118
+ file,
119
+ readFileSync(path.join(outDir, file), 'utf-8'),
120
+ ]),
121
+ );
75
122
  return {
76
- css: readFileSync(path.join(assets, cssName), 'utf-8'),
123
+ css: cssByName[cssName],
77
124
  cssName,
78
- html: readFileSync(path.join(outDir, 'index.html'), 'utf-8'),
125
+ cssByName,
126
+ html: htmlByName['index.html'],
127
+ htmlByName,
79
128
  outDir,
80
129
  };
81
130
  }
@@ -126,6 +175,14 @@ function itSplitsCorrectly(get: () => Built) {
126
175
  expect(library.match(PRODUCT_CLASS)).toBeNull();
127
176
  });
128
177
 
178
+ it('keeps nested pseudo-elements and keyframes in the product layer', () => {
179
+ const product = layerBlock(get().css, 'product');
180
+ expect(product).toContain(':after');
181
+ expect(product).toContain('#010203');
182
+ expect(product).toContain('@keyframes');
183
+ expect(product).toContain('.717s');
184
+ });
185
+
129
186
  it('leaves no StyleX rule outside the two layers', () => {
130
187
  const {css} = get();
131
188
  const outside = css
@@ -176,4 +233,55 @@ describe('a production build separates Astryx and product styles by layer', () =
176
233
 
177
234
  itSplitsCorrectly(() => built);
178
235
  });
236
+
237
+ describe('when the app has multiple HTML entries', () => {
238
+ let built: Built;
239
+ beforeAll(async () => {
240
+ built = await buildFixture('layer-split-multipage', [
241
+ 'index.html',
242
+ 'setup.html',
243
+ ]);
244
+ }, 180_000);
245
+ afterAll(
246
+ () => built && rmSync(built.outDir, {recursive: true, force: true}),
247
+ );
248
+
249
+ it('links the shared StyleX stylesheet from every page exactly once', () => {
250
+ for (const html of Object.values(built.htmlByName)) {
251
+ expect(html).toContain(built.cssName);
252
+ expect(
253
+ html.split(built.cssName).length - 1,
254
+ 'stylesheet is not linked exactly once',
255
+ ).toBe(1);
256
+ }
257
+ });
258
+
259
+ it('keeps entry-owned CSS on its own page', () => {
260
+ const mainCss = Object.entries(built.cssByName).find(([, css]) =>
261
+ css.includes('--multipage-main-only'),
262
+ );
263
+ const setupCss = Object.entries(built.cssByName).find(([, css]) =>
264
+ css.includes('--multipage-setup-only'),
265
+ );
266
+ expect(mainCss).toBeDefined();
267
+ expect(setupCss).toBeDefined();
268
+
269
+ const [mainCssName] = mainCss!;
270
+ const [setupCssName] = setupCss!;
271
+ expect(built.htmlByName['index.html']).toContain(mainCssName);
272
+ expect(built.htmlByName['index.html']).not.toContain(setupCssName);
273
+ expect(built.htmlByName['setup.html']).toContain(setupCssName);
274
+ expect(built.htmlByName['setup.html']).not.toContain(mainCssName);
275
+ expect(built.css).not.toContain('--multipage-main-only');
276
+ expect(built.css).not.toContain('--multipage-setup-only');
277
+ });
278
+ });
279
+ });
280
+
281
+ describe('a production build validates StyleX declarations', () => {
282
+ it('fails with longhand guidance instead of dropping a border shorthand', async () => {
283
+ await expect(buildFixture('invalid-border')).rejects.toThrow(
284
+ /borderTop is not supported.*borderTopWidth.*borderTopStyle.*borderTopColor/s,
285
+ );
286
+ }, 180_000);
179
287
  });
package/src/vite.ts CHANGED
@@ -7,6 +7,7 @@ import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import {fileURLToPath} from 'node:url';
9
9
  import {createRequire} from 'node:module';
10
+ import {createHash} from 'node:crypto';
10
11
 
11
12
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
12
13
 
@@ -136,6 +137,7 @@ export function astryxStylex(
136
137
  const stylexOptions: Record<string, unknown> = {
137
138
  dev,
138
139
  runtimeInjection: false,
140
+ propertyValidationMode: 'throw',
139
141
  treeshakeCompensation: true,
140
142
  unstable_moduleResolution: {
141
143
  type: 'commonJS',
@@ -282,6 +284,10 @@ export function astryxStylex(
282
284
  * layer (below `astryx-theme`, so a theme can override them), product styles
283
285
  * into the product layer (above it, so an app always wins).
284
286
  *
287
+ * The split output is written to one dedicated shared stylesheet. Keeping the
288
+ * collected rules out of an entry-owned CSS asset lets every HTML entry load
289
+ * the same StyleX output without also importing another page's authored CSS.
290
+ *
285
291
  * This is the one implementation. The dev middleware and the build hook differ
286
292
  * only in when they run and what they do with the string — the partition itself
287
293
  * must not diverge, because it did: the build shipped a version that wrapped
@@ -333,11 +339,12 @@ function renderSplitLayers(
333
339
  * component overrides were silently dropped in the built app while working in
334
340
  * dev.
335
341
  *
336
- * This replaces that merged block with the partitioned pair. It runs in
337
- * `writeBundle` because StyleX emits through two different paths depending on
338
- * whether the bundle already has a stylesheet to append to (`generateBundle`)
339
- * or has to write its own file (`writeBundle`) — on disk, after both, there is
340
- * one case instead of two.
342
+ * This removes that merged block from the entry-owned stylesheet, writes the
343
+ * partitioned pair to a dedicated shared stylesheet, and links it from every
344
+ * built HTML page. It runs in `writeBundle` because StyleX emits through two
345
+ * different paths depending on whether the bundle already has a stylesheet to
346
+ * append to (`generateBundle`) or has to write its own file (`writeBundle`) —
347
+ * on disk, after both, there is one case instead of two.
341
348
  *
342
349
  * The block is located by an exact match against StyleX's own collector rather
343
350
  * than by looking for `@layer priority1`: a wrong guess about where the block
@@ -388,19 +395,16 @@ function buildLayerSplitPlugin(
388
395
  // patch and nothing was shipped, so this is not a failure.
389
396
  if (!outDir || !fs.existsSync(outDir)) return;
390
397
 
391
- const patched: string[] = [];
398
+ const containingFiles: Array<{file: string; css: string; at: number}> =
399
+ [];
392
400
  for (const file of listCssFiles(outDir)) {
393
401
  const css = fs.readFileSync(file, 'utf-8');
394
402
  const at = css.lastIndexOf(merged);
395
403
  if (at === -1) continue;
396
- fs.writeFileSync(
397
- file,
398
- css.slice(0, at) + split + css.slice(at + merged.length),
399
- );
400
- patched.push(file);
404
+ containingFiles.push({file, css, at});
401
405
  }
402
406
 
403
- if (patched.length === 0) {
407
+ if (containingFiles.length === 0) {
404
408
  this.error(
405
409
  'astryx-build-layer-split: StyleX emitted rules but its CSS block ' +
406
410
  `was not found in any stylesheet under ${outDir}, so Astryx and ` +
@@ -412,7 +416,30 @@ function buildLayerSplitPlugin(
412
416
  return;
413
417
  }
414
418
 
415
- linkOrphanStylesheets(outDir, patched, base);
419
+ if (listHtmlFiles(outDir).length === 0) {
420
+ for (const {file, css, at} of containingFiles) {
421
+ fs.writeFileSync(
422
+ file,
423
+ css.slice(0, at) + split + css.slice(at + merged.length),
424
+ );
425
+ }
426
+ return;
427
+ }
428
+
429
+ for (const {file, css, at} of containingFiles) {
430
+ fs.writeFileSync(
431
+ file,
432
+ css.slice(0, at) + css.slice(at + merged.length),
433
+ );
434
+ }
435
+
436
+ const hash = createHash('sha256').update(split).digest('hex').slice(0, 8);
437
+ const sharedStylesheet = path.join(
438
+ path.dirname(containingFiles[0].file),
439
+ `astryx-stylex-${hash}.css`,
440
+ );
441
+ fs.writeFileSync(sharedStylesheet, split);
442
+ linkStylesheetsForEveryPage(outDir, [sharedStylesheet], base);
416
443
  },
417
444
  };
418
445
  }
@@ -440,20 +467,21 @@ function listHtmlFiles(dir: string): string[] {
440
467
  }
441
468
 
442
469
  /**
443
- * Link a stylesheet the build wrote but no page loads.
470
+ * Ensure every built page loads the stylesheet containing StyleX's rules.
444
471
  *
445
472
  * When an app imports no CSS of its own, StyleX has no bundle asset to append
446
473
  * to, so it writes `assets/stylex.css` itself — outside Rollup's graph, which
447
- * means Vite's HTML plugin never learns about it and emits no `<link>`. The app
448
- * ships every Astryx style correctly split into layers, and a completely
449
- * unstyled page. Importing any stylesheet hides it, which is why it survives:
450
- * the moment a project has one line of its own CSS the symptom disappears.
474
+ * means Vite's HTML plugin never learns about it and emits no `<link>`. In a
475
+ * multi-page build, Vite can also attach the one merged StyleX stylesheet to
476
+ * only one entry. The other pages then ship valid compiled classes but load no
477
+ * rules for them.
451
478
  *
452
- * Only orphans are linked. A stylesheet already referenced by a page is Vite's,
453
- * and touching it would duplicate the load. A build with no HTML at all —
454
- * library mode — is left alone: its consumer imports the CSS themselves.
479
+ * Check each page independently. A stylesheet already referenced by that page
480
+ * is left alone; a missing reference is inserted exactly once. A build with no
481
+ * HTML at all — library mode — is left alone because its consumer imports the
482
+ * CSS themselves.
455
483
  */
456
- function linkOrphanStylesheets(
484
+ function linkStylesheetsForEveryPage(
457
485
  outDir: string,
458
486
  cssFiles: string[],
459
487
  base: string,
@@ -461,25 +489,23 @@ function linkOrphanStylesheets(
461
489
  const pages = listHtmlFiles(outDir);
462
490
  if (pages.length === 0) return;
463
491
 
464
- const orphans = cssFiles.filter(css => {
465
- const name = path.basename(css);
466
- return !pages.some(page => fs.readFileSync(page, 'utf-8').includes(name));
467
- });
468
- if (orphans.length === 0) return;
469
-
470
- const links = orphans
471
- .map(css => {
472
- const href =
473
- base.replace(/\/$/, '') +
474
- '/' +
475
- path.relative(outDir, css).split(path.sep).join('/');
476
- return `<link rel="stylesheet" crossorigin href="${href}">`;
477
- })
478
- .join('\n ');
479
-
480
492
  for (const page of pages) {
481
493
  const html = fs.readFileSync(page, 'utf-8');
482
494
  if (!html.includes('</head>')) continue;
495
+
496
+ const missing = cssFiles.filter(css => !html.includes(path.basename(css)));
497
+ if (missing.length === 0) continue;
498
+
499
+ const links = missing
500
+ .map(css => {
501
+ const href =
502
+ base.replace(/\/$/, '') +
503
+ '/' +
504
+ path.relative(outDir, css).split(path.sep).join('/');
505
+ return `<link rel="stylesheet" crossorigin href="${href}">`;
506
+ })
507
+ .join('\n ');
508
+
483
509
  fs.writeFileSync(page, html.replace('</head>', ` ${links}\n </head>`));
484
510
  }
485
511
  }
@@ -527,19 +553,23 @@ function astryxStylexLegacy(options: AstryxVitePluginLegacyOptions): Plugin[] {
527
553
  const libraryLayer = layers.library ?? 'astryx-base';
528
554
  const productLayer = layers.product ?? 'product';
529
555
 
556
+ const validatedStylexOptions = {
557
+ propertyValidationMode: 'throw',
558
+ ...(stylexOptions as any),
559
+ };
530
560
  const astryxBabelPlugin = path.resolve(__dirname, 'babel.js');
531
- const existingPlugins = (stylexOptions as any).babelConfig?.plugins ?? [];
561
+ const existingPlugins = validatedStylexOptions.babelConfig?.plugins ?? [];
532
562
 
533
563
  const basePlugin = stylex.vite({
534
- ...(stylexOptions as any),
564
+ ...validatedStylexOptions,
535
565
  useCSSLayers: true,
536
566
  babelConfig: {
537
- ...(stylexOptions as any).babelConfig,
567
+ ...validatedStylexOptions.babelConfig,
538
568
  plugins: [
539
569
  [
540
570
  astryxBabelPlugin,
541
571
  {
542
- ...(stylexOptions as any),
572
+ ...validatedStylexOptions,
543
573
  libraryPrefix: stylexPrefix,
544
574
  babelConfig: undefined,
545
575
  },