-
Notifications
You must be signed in to change notification settings - Fork 466
Expand file tree
/
Copy pathcore.js
More file actions
607 lines (550 loc) · 19.2 KB
/
Copy pathcore.js
File metadata and controls
607 lines (550 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
import { createUnplugin } from 'unplugin';
import { transformAsync } from '@babel/core';
import stylexBabelPlugin from '@stylexjs/babel-plugin';
import flowSyntaxPlugin from '@babel/plugin-syntax-flow';
import jsxSyntaxPlugin from '@babel/plugin-syntax-jsx';
import typescriptSyntaxPlugin from '@babel/plugin-syntax-typescript';
import path from 'node:path';
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import { createRequire } from 'node:module';
import { transform as lightningTransform } from 'lightningcss';
import browserslist from 'browserslist';
import { browserslistToTargets } from 'lightningcss';
/**
* Try to pick a stable CSS asset to inject into.
* - Prefer files named like `style.css` or `index.css`
* - Otherwise, first .css asset encountered
*/
export function pickCssAssetFromRollupBundle(bundle, choose) {
const assets = Object.values(bundle).filter(
(a) =>
a &&
a.type === 'asset' &&
typeof a.fileName === 'string' &&
a.fileName.endsWith('.css'),
);
if (assets.length === 0) return null;
if (typeof choose === 'function') {
const chosen = assets.find((a) => choose(a.fileName));
if (chosen) return chosen;
}
const best =
assets.find((a) => /(^|\/)index\.css$/.test(a.fileName)) ||
assets.find((a) => /(^|\/)style\.css$/.test(a.fileName));
return best || assets[0];
}
function processCollectedRulesToCSS(rules, options) {
if (!rules || rules.length === 0) return '';
const collectedCSS = stylexBabelPlugin.processStylexRules(rules, {
useLayers: options.useCSSLayers ?? false,
enableLTRRTLComments: options?.enableLTRRTLComments,
});
const { code } = lightningTransform({
targets: browserslistToTargets(browserslist()),
...options.lightningcssOptions,
filename: 'stylex.css',
code: Buffer.from(collectedCSS),
});
return code.toString();
}
function getAssetBaseName(asset) {
if (asset?.name && typeof asset.name === 'string') return asset.name;
const fallback = asset?.fileName
? path.basename(asset.fileName)
: 'stylex.css';
const match = /^(.*?)(-[a-z0-9]{8,})?\.css$/i.exec(fallback);
if (match) return `${match[1]}.css`;
return fallback || 'stylex.css';
}
function replaceBundleReferences(bundle, oldFileName, newFileName) {
for (const item of Object.values(bundle)) {
if (!item) continue;
if (item.type === 'chunk') {
if (typeof item.code === 'string' && item.code.includes(oldFileName)) {
item.code = item.code.split(oldFileName).join(newFileName);
}
const importedCss = item.viteMetadata?.importedCss;
if (importedCss instanceof Set && importedCss.has(oldFileName)) {
importedCss.delete(oldFileName);
importedCss.add(newFileName);
} else if (Array.isArray(importedCss)) {
const next = importedCss.map((name) =>
name === oldFileName ? newFileName : name,
);
item.viteMetadata.importedCss = next;
}
} else if (item.type === 'asset' && typeof item.source === 'string') {
if (item.source.includes(oldFileName)) {
item.source = item.source.split(oldFileName).join(newFileName);
}
}
}
}
export function replaceCssAssetWithHashedCopy(ctx, bundle, asset, nextSource) {
const baseName = getAssetBaseName(asset);
const referenceId = ctx.emitFile({
type: 'asset',
name: baseName,
source: nextSource,
});
const nextFileName = ctx.getFileName(referenceId);
const oldFileName = asset.fileName;
if (!nextFileName || !oldFileName || nextFileName === oldFileName) {
asset.source = nextSource;
return;
}
replaceBundleReferences(bundle, oldFileName, nextFileName);
delete bundle[oldFileName];
}
function readJSON(file) {
try {
const content = fs.readFileSync(file, 'utf8');
return JSON.parse(content);
} catch {
return null;
}
}
function findNearestPackageJson(startDir) {
let dir = startDir;
for (;;) {
const candidate = path.join(dir, 'package.json');
if (fs.existsSync(candidate)) return candidate;
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
return null;
}
function toPackageName(importSource) {
const source =
typeof importSource === 'string' ? importSource : importSource?.from;
if (!source || source.startsWith('.') || source.startsWith('/')) return null;
if (source.startsWith('@')) {
const [scope, name] = source.split('/');
if (scope && name) return `${scope}/${name}`;
}
const [pkg] = source.split('/');
return pkg || null;
}
function hasStylexDependency(manifest, targetPackages) {
if (!manifest || typeof manifest !== 'object') return false;
const depFields = [
'dependencies',
'peerDependencies',
'optionalDependencies',
];
for (const field of depFields) {
const deps = manifest[field];
if (!deps || typeof deps !== 'object') continue;
for (const name of Object.keys(deps)) {
if (targetPackages.has(name)) return true;
}
}
return false;
}
function hasPrecompiledCss(manifest) {
if (!manifest || typeof manifest !== 'object') return false;
if (typeof manifest.style === 'string' && manifest.style.endsWith('.css')) {
return true;
}
const { exports } = manifest;
if (exports && typeof exports === 'object') {
const conditions = [
exports['.'],
...Object.values(exports).filter(
(v) => v !== null && typeof v === 'object',
),
];
for (const cond of conditions) {
if (!cond || typeof cond !== 'object') continue;
if (
(typeof cond.style === 'string' && cond.style.endsWith('.css')) ||
(typeof cond.css === 'string' && cond.css.endsWith('.css'))
) {
return true;
}
}
}
return false;
}
function mapToPackageInfos(map) {
return Array.from(map, ([name, precompiled]) => ({ name, precompiled }));
}
function discoverStylexPackages({
importSources,
explicitPackages,
rootDir,
resolver,
}) {
const targetPackages = new Set(
importSources
.map(toPackageName)
.filter(Boolean)
.concat(['@stylexjs/stylex']),
);
const found = new Map((explicitPackages || []).map((name) => [name, false]));
const pkgJsonPath = findNearestPackageJson(rootDir);
if (!pkgJsonPath) return mapToPackageInfos(found);
const pkgDir = path.dirname(pkgJsonPath);
const pkgJson = readJSON(pkgJsonPath);
if (!pkgJson) return mapToPackageInfos(found);
const depFields = [
'dependencies',
'devDependencies',
'peerDependencies',
'optionalDependencies',
];
const deps = new Set();
for (const field of depFields) {
const entries = pkgJson[field];
if (!entries || typeof entries !== 'object') continue;
for (const name of Object.keys(entries)) deps.add(name);
}
for (const dep of deps) {
let manifestPath = null;
try {
manifestPath = resolver.resolve(`${dep}/package.json`, {
paths: [pkgDir],
});
} catch {
try {
const entry = resolver.resolve(dep, { paths: [pkgDir] });
manifestPath = findNearestPackageJson(path.dirname(entry));
} catch {}
if (!manifestPath) {
const candidate = path.join(
pkgDir,
'node_modules',
dep,
'package.json',
);
if (fs.existsSync(candidate)) manifestPath = candidate;
}
}
if (!manifestPath) continue;
const manifest = readJSON(manifestPath);
if (hasStylexDependency(manifest, targetPackages)) {
found.set(dep, hasPrecompiledCss(manifest));
}
}
return mapToPackageInfos(found);
}
const JS_LIKE_RE = /\.[cm]?[jt]sx?(\?|$)/;
const SVELTE_LIKE_RE = /\.svelte(\?|$)/;
export const unpluginFactory = (userOptions = {}, metaOptions) => {
// framework :: 'rollup' | 'vite' | 'rolldown' | 'farm' | 'unloader'
const framework = metaOptions?.framework;
const {
dev = process.env.NODE_ENV === 'development' ||
process.env.BABEL_ENV === 'development',
unstable_moduleResolution = { type: 'commonJS', rootDir: process.cwd() },
babelConfig: { plugins = [], presets = [] } = {},
importSources = ['stylex', '@stylexjs/stylex'],
useCSSLayers = false,
lightningcssOptions,
cssInjectionTarget,
externalPackages = [],
// Persist rules to disk in dev to bridge multiple plugin containers/processes.
// Off by default; enable if your dev setup runs separate Node processes per environment.
devPersistToDisk = false,
// Dev integration mode: 'full' (runtime + html), 'css-only' (serve CSS endpoint only), 'off'
devMode = 'full',
treeshakeCompensation = ['vite', 'rollup', 'rolldown'].includes(framework),
...stylexOptions
} = userOptions;
// Shared state across a single compilation (used for builds)
const stylexRulesById = new Map(); // id -> Rule[]
// Global shared store for Vite dev to aggregate across environments (client/ssr/rsc)
function getSharedStore() {
try {
const g = globalThis;
if (!g.__stylex_unplugin_store) {
g.__stylex_unplugin_store = { rulesById: new Map(), version: 0 };
}
return g.__stylex_unplugin_store;
} catch {
return { rulesById: stylexRulesById, version: 0 };
}
}
const nearestPkgJson = findNearestPackageJson(process.cwd());
const requireFromCwd = nearestPkgJson
? createRequire(nearestPkgJson)
: createRequire(path.join(process.cwd(), 'package.json'));
const stylexPackageInfos = discoverStylexPackages({
importSources,
explicitPackages: externalPackages,
rootDir: nearestPkgJson ? path.dirname(nearestPkgJson) : process.cwd(),
resolver: requireFromCwd,
});
const precompiledPackages = stylexPackageInfos
.filter((p) => p.precompiled)
.map((p) => p.name);
if (precompiledPackages.length > 0) {
const packageList = precompiledPackages.map((p) => ` • ${p}`).join('\n');
console.warn(`
[StyleX] ⚠️ Potential CSS ordering issue detected.
The following packages use StyleX and ship pre-compiled CSS:
${packageList}
Because these packages are not being re-compiled by the StyleX plugin, both
the library CSS and your app-local CSS are emitted as separate files. They
share the same atomic class names (e.g. .xuxw1ft for white-space:nowrap) but
your app's CSS is loaded last and therefore unconditionally overrides the
library's CSS for any colliding rule — regardless of intended priority.
Recommended fixes (pick one):
1. Publish the library without pre-compiled CSS and add it to Next.js
\`transpilePackages\` so a single compiler handles everything.
2. Enable \`useCSSLayers: true\` in BOTH the library build and this plugin
so @layer order governs priority instead of stylesheet load order.
3. Ensure the library <link> appears after your app <link> in <head>
(workaround only — this is fragile and not recommended long-term).
`);
}
const isNextAppRouter =
!!process.env.NEXT_RUNTIME ||
!!process.env.NEXT_PHASE ||
(framework === 'webpack' &&
!!(
process.env.npm_package_dependencies_next ||
process.env.npm_package_devDependencies_next
));
if (userOptions.runtimeInjection && isNextAppRouter) {
const msg = `[StyleX] ❌ \`runtimeInjection\` must not be used with the Next.js App Router.
The App Router renders on the server and hydrates on the client. Styles
injected at runtime are appended after the static stylesheet, so they always
override static rules — including styles from third-party StyleX libraries.
They also appear as empty <style> tags in browser DevTools.
Remove \`runtimeInjection: true\` from your StyleX plugin config.
`;
if (!dev) {
throw new Error(msg);
} else {
console.error(msg);
}
}
const stylexPackages = stylexPackageInfos.map((p) => p.name);
// Resolve nearest node_modules and cache under node_modules/.stylex/rules.json
function findNearestNodeModules(startDir) {
let dir = startDir;
// Walk upwards until we find a node_modules directory or hit the FS root
for (;;) {
const candidate = path.join(dir, 'node_modules');
if (fs.existsSync(candidate)) {
const stat = fs.statSync(candidate);
if (stat.isDirectory()) return candidate;
}
const parent = path.dirname(dir);
if (parent === dir) break;
dir = parent;
}
return null;
}
const NEAREST_NODE_MODULES = findNearestNodeModules(process.cwd());
const DISK_RULES_DIR = NEAREST_NODE_MODULES
? path.join(NEAREST_NODE_MODULES, '.stylex')
: path.join(process.cwd(), 'node_modules', '.stylex');
const DISK_RULES_PATH = path.join(DISK_RULES_DIR, 'rules.json');
async function runBabelTransform(inputCode, filename, callerName) {
const result = await transformAsync(inputCode, {
babelrc: false,
filename,
presets,
plugins: [
...plugins,
/\.jsx?/.test(path.extname(filename))
? flowSyntaxPlugin
: [typescriptSyntaxPlugin, { isTSX: true }],
jsxSyntaxPlugin,
stylexBabelPlugin.withOptions({
...stylexOptions,
importSources,
treeshakeCompensation,
dev,
unstable_moduleResolution,
}),
],
caller: {
name: callerName,
supportsStaticESM: true,
supportsDynamicImport: true,
supportsTopLevelAwait: !inputCode.includes('require('),
supportsExportNamespaceFrom: true,
},
});
if (!result || result.code == null) {
return { code: inputCode, map: null, metadata: {} };
}
return result;
}
function escapeReg(src) {
return src.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function containsStylexImport(code, source) {
const s = escapeReg(typeof source === 'string' ? source : source.from);
const re = new RegExp(
// import ... from 'source' | import('source') | require('source') | import 'source'
`(?:from\\s*['"]${s}['"]|import\\s*\\(\\s*['"]${s}['"]\\s*\\)|require\\s*\\(\\s*['"]${s}['"]\\s*\\)|^\\s*import\\s*['"]${s}['"])`,
'm',
);
return re.test(code);
}
function shouldHandle(code) {
if (!code) return false;
return importSources.some((src) => containsStylexImport(code, src));
}
function resetState() {
stylexRulesById.clear();
if (devPersistToDisk) {
try {
fs.rmSync(DISK_RULES_PATH, { force: true });
} catch {}
}
}
function collectCss() {
const merged = new Map();
if (devPersistToDisk) {
try {
if (fs.existsSync(DISK_RULES_PATH)) {
const json = JSON.parse(fs.readFileSync(DISK_RULES_PATH, 'utf8'));
for (const [k, v] of Object.entries(json)) merged.set(k, v);
}
} catch {}
}
try {
const shared = getSharedStore().rulesById;
for (const [k, v] of shared.entries()) merged.set(k, v);
} catch {}
for (const [k, v] of stylexRulesById.entries()) merged.set(k, v);
const allRules = Array.from(merged.values()).flat();
return processCollectedRulesToCSS(allRules, {
useCSSLayers,
lightningcssOptions,
enableLTRRTLComments: stylexOptions?.enableLTRRTLComments,
});
}
async function persistRulesToDisk(id, rules) {
if (!devPersistToDisk) return;
try {
let current = {};
try {
const txt = await fsp.readFile(DISK_RULES_PATH, 'utf8');
current = JSON.parse(txt);
} catch {}
if (rules && Array.isArray(rules) && rules.length > 0) {
current[id] = rules;
} else if (current[id]) {
delete current[id];
}
await fsp.writeFile(DISK_RULES_PATH, JSON.stringify(current), 'utf8');
} catch {}
}
// No rollup-style virtual module normalize for webpack/rspack stability
const plugin = {
name: '@stylexjs/unplugin',
apply: (config, env) => {
try {
const command =
env?.command || (typeof config === 'string' ? undefined : undefined);
if (devMode === 'off' && command === 'serve') return false;
} catch {}
return true;
},
// Ensure we run before React refresh transforms so HMR stays intact
enforce: 'pre',
// Vite/Rollup lifecycle resets
buildStart() {
resetState();
},
buildEnd() {
// No-op; bundler-specific hooks handle CSS injection.
},
transformInclude(id) {
return JS_LIKE_RE.test(id) || SVELTE_LIKE_RE.test(id);
},
// Core code transform
async transform(code, id) {
// Only handle JS-like files; avoid parsing CSS/JSON/etc
if (!JS_LIKE_RE.test(id) && !SVELTE_LIKE_RE.test(id)) return null;
if (!shouldHandle(code)) return null;
// Extract the pure filename by removing everything after '?' (e.g., handling Vite's '?v=' cache busting).
const dir = path.dirname(id);
const basename = path.basename(id);
const file = path.join(dir, basename.split('?')[0] || basename);
const result = await runBabelTransform(code, file, '@stylexjs/unplugin');
const { metadata } = result;
if (!stylexOptions.runtimeInjection) {
const hasRules =
metadata &&
Array.isArray(metadata.stylex) &&
metadata.stylex.length > 0;
const shared = getSharedStore();
if (hasRules) {
stylexRulesById.set(id, metadata.stylex);
shared.rulesById.set(id, metadata.stylex);
shared.version++;
await persistRulesToDisk(id, metadata.stylex);
} else {
stylexRulesById.delete(id);
if (shared.rulesById.has(id)) {
shared.rulesById.delete(id);
shared.version++;
}
await persistRulesToDisk(id, []);
}
}
// Rollup/Vite watch-mode support: collect stylex metadata from cached deps
// Only when running in rollup-like context
// $FlowExpectedError[incompatible-use]
const ctx = this;
if (
ctx &&
ctx.meta &&
ctx.meta.watchMode &&
typeof ctx.parse === 'function'
) {
try {
const ast = ctx.parse(result.code);
for (const stmt of ast.body) {
if (stmt.type === 'ImportDeclaration') {
// $FlowExpectedError[incompatible-call]
const resolved = await ctx.resolve(stmt.source.value, id);
if (resolved && !resolved.external) {
// $FlowExpectedError[incompatible-call]
const loaded = await ctx.load(resolved);
if (loaded && loaded.meta && 'stylex' in loaded.meta) {
stylexRulesById.set(resolved.id, loaded.meta.stylex);
}
}
}
}
} catch {}
}
return { code: result.code, map: result.map };
},
// Rollup: ensure cached modules still provide their metadata
shouldTransformCachedModule({ id, meta }) {
if (meta && 'stylex' in meta) {
stylexRulesById.set(id, meta.stylex);
}
return false;
},
};
plugin.__stylexCollectCss = collectCss;
plugin.__stylexResetState = resetState;
plugin.__stylexGetSharedStore = getSharedStore;
plugin.__stylexDevMode = devMode;
plugin.__stylexCssInjectionTarget = cssInjectionTarget;
plugin.__stylexPackages = stylexPackages;
return plugin;
};
const unpluginInstance = createUnplugin(unpluginFactory);
export default unpluginInstance;
export const unplugin = unpluginInstance;