@stylexjs/unplugin 0.17.5 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/es/index.mjs CHANGED
@@ -1,651 +1,26 @@
1
- import { createUnplugin } from 'unplugin';
2
- import { transformAsync } from '@babel/core';
3
- import stylexBabelPlugin from '@stylexjs/babel-plugin';
4
- import flowSyntaxPlugin from '@babel/plugin-syntax-flow';
5
- import jsxSyntaxPlugin from '@babel/plugin-syntax-jsx';
6
- import typescriptSyntaxPlugin from '@babel/plugin-syntax-typescript';
7
- import path from 'node:path';
8
- import fs from 'node:fs';
9
- import fsp from 'node:fs/promises';
10
- import { createRequire } from 'node:module';
11
- import { transform as lightningTransform } from 'lightningcss';
12
- import browserslist from 'browserslist';
13
- import { browserslistToTargets } from 'lightningcss';
14
- import { devInjectMiddleware } from "./dev-inject-middleware.mjs";
15
- import { DEV_CSS_PATH, VIRTUAL_STYLEX_RUNTIME_SCRIPT, VIRTUAL_STYLEX_CSS_ONLY_SCRIPT } from "./consts.mjs";
16
- function pickCssAssetFromRollupBundle(bundle, choose) {
17
- const assets = Object.values(bundle).filter(a => a && a.type === 'asset' && typeof a.fileName === 'string' && a.fileName.endsWith('.css'));
18
- if (assets.length === 0) return null;
19
- if (typeof choose === 'function') {
20
- const chosen = assets.find(a => choose(a.fileName));
21
- if (chosen) return chosen;
22
- }
23
- const best = assets.find(a => /(^|\/)index\.css$/.test(a.fileName)) || assets.find(a => /(^|\/)style\.css$/.test(a.fileName));
24
- return best || assets[0];
25
- }
26
- function processCollectedRulesToCSS(rules, options) {
27
- if (!rules || rules.length === 0) return '';
28
- const collectedCSS = stylexBabelPlugin.processStylexRules(rules, {
29
- useLayers: !!options.useCSSLayers,
30
- enableLTRRTLComments: options?.enableLTRRTLComments
31
- });
32
- const {
33
- code
34
- } = lightningTransform({
35
- targets: browserslistToTargets(browserslist('>= 1%')),
36
- ...options.lightningcssOptions,
37
- filename: 'stylex.css',
38
- code: Buffer.from(collectedCSS)
39
- });
40
- return code.toString();
41
- }
42
- function getAssetBaseName(asset) {
43
- if (asset?.name && typeof asset.name === 'string') return asset.name;
44
- const fallback = asset?.fileName ? path.basename(asset.fileName) : 'stylex.css';
45
- const match = /^(.*?)(-[a-z0-9]{8,})?\.css$/i.exec(fallback);
46
- if (match) return `${match[1]}.css`;
47
- return fallback || 'stylex.css';
48
- }
49
- function replaceBundleReferences(bundle, oldFileName, newFileName) {
50
- for (const item of Object.values(bundle)) {
51
- if (!item) continue;
52
- if (item.type === 'chunk') {
53
- if (typeof item.code === 'string' && item.code.includes(oldFileName)) {
54
- item.code = item.code.split(oldFileName).join(newFileName);
55
- }
56
- const importedCss = item.viteMetadata?.importedCss;
57
- if (importedCss instanceof Set && importedCss.has(oldFileName)) {
58
- importedCss.delete(oldFileName);
59
- importedCss.add(newFileName);
60
- } else if (Array.isArray(importedCss)) {
61
- const next = importedCss.map(name => name === oldFileName ? newFileName : name);
62
- item.viteMetadata.importedCss = next;
63
- }
64
- } else if (item.type === 'asset' && typeof item.source === 'string') {
65
- if (item.source.includes(oldFileName)) {
66
- item.source = item.source.split(oldFileName).join(newFileName);
67
- }
68
- }
69
- }
70
- }
71
- function replaceCssAssetWithHashedCopy(ctx, bundle, asset, nextSource) {
72
- const baseName = getAssetBaseName(asset);
73
- const referenceId = ctx.emitFile({
74
- type: 'asset',
75
- name: baseName,
76
- source: nextSource
77
- });
78
- const nextFileName = ctx.getFileName(referenceId);
79
- const oldFileName = asset.fileName;
80
- if (!nextFileName || !oldFileName || nextFileName === oldFileName) {
81
- asset.source = nextSource;
82
- return;
83
- }
84
- replaceBundleReferences(bundle, oldFileName, nextFileName);
85
- const emitted = bundle[nextFileName];
86
- if (emitted && emitted !== asset) {
87
- delete bundle[nextFileName];
88
- }
89
- asset.fileName = nextFileName;
90
- asset.source = nextSource;
91
- if (bundle[oldFileName] === asset) {
92
- delete bundle[oldFileName];
93
- }
94
- bundle[nextFileName] = asset;
95
- }
96
- function readJSON(file) {
97
- try {
98
- const content = fs.readFileSync(file, 'utf8');
99
- return JSON.parse(content);
100
- } catch {
101
- return null;
102
- }
103
- }
104
- function findNearestPackageJson(startDir) {
105
- let dir = startDir;
106
- for (;;) {
107
- const candidate = path.join(dir, 'package.json');
108
- if (fs.existsSync(candidate)) return candidate;
109
- const parent = path.dirname(dir);
110
- if (parent === dir) break;
111
- dir = parent;
112
- }
113
- return null;
114
- }
115
- function toPackageName(importSource) {
116
- const source = typeof importSource === 'string' ? importSource : importSource?.from;
117
- if (!source || source.startsWith('.') || source.startsWith('/')) return null;
118
- if (source.startsWith('@')) {
119
- const [scope, name] = source.split('/');
120
- if (scope && name) return `${scope}/${name}`;
121
- }
122
- const [pkg] = source.split('/');
123
- return pkg || null;
124
- }
125
- function hasStylexDependency(manifest, targetPackages) {
126
- if (!manifest || typeof manifest !== 'object') return false;
127
- const depFields = ['dependencies', 'peerDependencies', 'optionalDependencies'];
128
- for (const field of depFields) {
129
- const deps = manifest[field];
130
- if (!deps || typeof deps !== 'object') continue;
131
- for (const name of Object.keys(deps)) {
132
- if (targetPackages.has(name)) return true;
133
- }
134
- }
135
- return false;
136
- }
137
- function discoverStylexPackages({
138
- importSources,
139
- explicitPackages,
140
- rootDir,
141
- resolver
142
- }) {
143
- const targetPackages = new Set(importSources.map(toPackageName).filter(Boolean).concat(['@stylexjs/stylex']));
144
- const found = new Set(explicitPackages || []);
145
- const pkgJsonPath = findNearestPackageJson(rootDir);
146
- if (!pkgJsonPath) return Array.from(found);
147
- const pkgDir = path.dirname(pkgJsonPath);
148
- const pkgJson = readJSON(pkgJsonPath);
149
- if (!pkgJson) return Array.from(found);
150
- const depFields = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'];
151
- const deps = new Set();
152
- for (const field of depFields) {
153
- const entries = pkgJson[field];
154
- if (!entries || typeof entries !== 'object') continue;
155
- for (const name of Object.keys(entries)) deps.add(name);
156
- }
157
- for (const dep of deps) {
158
- let manifestPath = null;
159
- try {
160
- manifestPath = resolver.resolve(`${dep}/package.json`, {
161
- paths: [pkgDir]
162
- });
163
- } catch {}
164
- if (!manifestPath) continue;
165
- const manifest = readJSON(manifestPath);
166
- if (hasStylexDependency(manifest, targetPackages)) {
167
- found.add(dep);
168
- }
169
- }
170
- return Array.from(found);
171
- }
172
- const unpluginInstance = createUnplugin((userOptions = {}, metaOptions) => {
173
- const framework = metaOptions?.framework;
174
- const {
175
- dev = process.env.NODE_ENV === 'development' || process.env.BABEL_ENV === 'development',
176
- unstable_moduleResolution = {
177
- type: 'commonJS',
178
- rootDir: process.cwd()
179
- },
180
- babelConfig: {
181
- plugins = [],
182
- presets = []
183
- } = {},
184
- importSources = ['stylex', '@stylexjs/stylex'],
185
- useCSSLayers = false,
186
- lightningcssOptions,
187
- cssInjectionTarget,
188
- externalPackages = [],
189
- devPersistToDisk = false,
190
- devMode = 'full',
191
- treeshakeCompensation = ['vite', 'rollup', 'rolldown'].includes(framework),
192
- ...stylexOptions
193
- } = userOptions;
194
- const stylexRulesById = new Map();
195
- function getSharedStore() {
196
- try {
197
- const g = globalThis;
198
- if (!g.__stylex_unplugin_store) {
199
- g.__stylex_unplugin_store = {
200
- rulesById: new Map(),
201
- version: 0
202
- };
203
- }
204
- return g.__stylex_unplugin_store;
205
- } catch {
206
- return {
207
- rulesById: stylexRulesById,
208
- version: 0
209
- };
210
- }
211
- }
212
- let viteServer = null;
213
- let viteOutDir = null;
214
- const nearestPkgJson = findNearestPackageJson(process.cwd());
215
- const requireFromCwd = nearestPkgJson ? createRequire(nearestPkgJson) : createRequire(path.join(process.cwd(), 'package.json'));
216
- const stylexPackages = discoverStylexPackages({
217
- importSources,
218
- explicitPackages: externalPackages,
219
- rootDir: nearestPkgJson ? path.dirname(nearestPkgJson) : process.cwd(),
220
- resolver: requireFromCwd
221
- });
222
- function findNearestNodeModules(startDir) {
223
- let dir = startDir;
224
- for (;;) {
225
- const candidate = path.join(dir, 'node_modules');
226
- if (fs.existsSync(candidate)) {
227
- const stat = fs.statSync(candidate);
228
- if (stat.isDirectory()) return candidate;
229
- }
230
- const parent = path.dirname(dir);
231
- if (parent === dir) break;
232
- dir = parent;
233
- }
234
- return null;
235
- }
236
- const NEAREST_NODE_MODULES = findNearestNodeModules(process.cwd());
237
- const DISK_RULES_DIR = NEAREST_NODE_MODULES ? path.join(NEAREST_NODE_MODULES, '.stylex') : path.join(process.cwd(), 'node_modules', '.stylex');
238
- const DISK_RULES_PATH = path.join(DISK_RULES_DIR, 'rules.json');
239
- async function runBabelTransform(inputCode, filename, callerName) {
240
- const result = await transformAsync(inputCode, {
241
- babelrc: false,
242
- filename,
243
- presets,
244
- plugins: [...plugins, /\.jsx?/.test(path.extname(filename)) ? flowSyntaxPlugin : [typescriptSyntaxPlugin, {
245
- isTSX: true
246
- }], jsxSyntaxPlugin, stylexBabelPlugin.withOptions({
247
- ...stylexOptions,
248
- importSources,
249
- treeshakeCompensation,
250
- dev,
251
- unstable_moduleResolution
252
- })],
253
- caller: {
254
- name: callerName,
255
- supportsStaticESM: true,
256
- supportsDynamicImport: true,
257
- supportsTopLevelAwait: !inputCode.includes('require('),
258
- supportsExportNamespaceFrom: true
259
- }
260
- });
261
- if (!result || result.code == null) {
262
- return {
263
- code: inputCode,
264
- map: null,
265
- metadata: {}
266
- };
267
- }
268
- return result;
269
- }
270
- function escapeReg(src) {
271
- return src.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
272
- }
273
- function containsStylexImport(code, source) {
274
- const s = escapeReg(typeof source === 'string' ? source : source.from);
275
- const re = new RegExp(`(?:from\\s*['"]${s}['"]|import\\s*\\(\\s*['"]${s}['"]\\s*\\)|require\\s*\\(\\s*['"]${s}['"]\\s*\\)|^\\s*import\\s*['"]${s}['"])`, 'm');
276
- return re.test(code);
277
- }
278
- function shouldHandle(code) {
279
- if (!code) return false;
280
- return importSources.some(src => containsStylexImport(code, src));
281
- }
282
- function resetState() {
283
- stylexRulesById.clear();
284
- if (devPersistToDisk) {
285
- try {
286
- fs.rmSync(DISK_RULES_PATH, {
287
- force: true
288
- });
289
- } catch {}
290
- }
291
- }
292
- function collectCss() {
293
- const merged = new Map();
294
- if (devPersistToDisk) {
295
- try {
296
- if (fs.existsSync(DISK_RULES_PATH)) {
297
- const json = JSON.parse(fs.readFileSync(DISK_RULES_PATH, 'utf8'));
298
- for (const [k, v] of Object.entries(json)) merged.set(k, v);
299
- }
300
- } catch {}
301
- }
302
- try {
303
- const shared = getSharedStore().rulesById;
304
- for (const [k, v] of shared.entries()) merged.set(k, v);
305
- } catch {}
306
- for (const [k, v] of stylexRulesById.entries()) merged.set(k, v);
307
- const allRules = Array.from(merged.values()).flat();
308
- return processCollectedRulesToCSS(allRules, {
309
- useCSSLayers,
310
- lightningcssOptions,
311
- enableLTRRTLComments: stylexOptions?.enableLTRRTLComments
312
- });
313
- }
314
- async function persistRulesToDisk(id, rules) {
315
- if (!devPersistToDisk) return;
316
- try {
317
- let current = {};
318
- try {
319
- const txt = await fsp.readFile(DISK_RULES_PATH, 'utf8');
320
- current = JSON.parse(txt);
321
- } catch {}
322
- if (rules && Array.isArray(rules) && rules.length > 0) {
323
- current[id] = rules;
324
- } else if (current[id]) {
325
- delete current[id];
326
- }
327
- await fsp.writeFile(DISK_RULES_PATH, JSON.stringify(current), 'utf8');
328
- } catch {}
329
- }
330
- return {
331
- name: '@stylexjs/unplugin',
332
- apply: (config, env) => {
333
- try {
334
- const command = env?.command || (typeof config === 'string' ? undefined : undefined);
335
- if (devMode === 'off' && command === 'serve') return false;
336
- } catch {}
337
- return true;
338
- },
339
- enforce: 'pre',
340
- buildStart() {
341
- resetState();
342
- },
343
- buildEnd() {},
344
- async transform(code, id) {
345
- const JS_LIKE_RE = /\.[cm]?[jt]sx?(\?|$)/;
346
- if (!JS_LIKE_RE.test(id)) return null;
347
- if (!shouldHandle(code)) return null;
348
- const dir = path.dirname(id);
349
- const basename = path.basename(id);
350
- const file = path.join(dir, basename.split('?')[0] || basename);
351
- const result = await runBabelTransform(code, file, '@stylexjs/unplugin');
352
- const {
353
- metadata
354
- } = result;
355
- if (!stylexOptions.runtimeInjection) {
356
- const hasRules = metadata && Array.isArray(metadata.stylex) && metadata.stylex.length > 0;
357
- const shared = getSharedStore();
358
- if (hasRules) {
359
- stylexRulesById.set(id, metadata.stylex);
360
- shared.rulesById.set(id, metadata.stylex);
361
- shared.version++;
362
- await persistRulesToDisk(id, metadata.stylex);
363
- } else {
364
- stylexRulesById.delete(id);
365
- if (shared.rulesById.has(id)) {
366
- shared.rulesById.delete(id);
367
- shared.version++;
368
- }
369
- await persistRulesToDisk(id, []);
370
- }
371
- if (viteServer) {
372
- try {
373
- viteServer.ws.send({
374
- type: 'custom',
375
- event: 'stylex:css-update'
376
- });
377
- } catch {}
378
- }
379
- }
380
- const ctx = this;
381
- if (ctx && ctx.meta && ctx.meta.watchMode && typeof ctx.parse === 'function') {
382
- try {
383
- const ast = ctx.parse(result.code);
384
- for (const stmt of ast.body) {
385
- if (stmt.type === 'ImportDeclaration') {
386
- const resolved = await ctx.resolve(stmt.source.value, id);
387
- if (resolved && !resolved.external) {
388
- const loaded = await ctx.load(resolved);
389
- if (loaded && loaded.meta && 'stylex' in loaded.meta) {
390
- stylexRulesById.set(resolved.id, loaded.meta.stylex);
391
- }
392
- }
393
- }
394
- }
395
- } catch {}
396
- }
397
- return {
398
- code: result.code,
399
- map: result.map
400
- };
401
- },
402
- shouldTransformCachedModule({
403
- id,
404
- meta
405
- }) {
406
- if (meta && 'stylex' in meta) {
407
- stylexRulesById.set(id, meta.stylex);
408
- }
409
- return false;
410
- },
411
- generateBundle(_opts, bundle) {
412
- const css = collectCss();
413
- if (!css) return;
414
- const target = pickCssAssetFromRollupBundle(bundle, cssInjectionTarget);
415
- if (target) {
416
- const current = typeof target.source === 'string' ? target.source : target.source?.toString() || '';
417
- const nextSource = current ? current + '\n' + css : css;
418
- replaceCssAssetWithHashedCopy(this, bundle, target, nextSource);
419
- } else {}
420
- },
421
- vite: devMode === 'off' ? undefined : {
422
- config(config) {
423
- if (!stylexPackages || stylexPackages.length === 0) return;
424
- const addExcludes = (existing = []) => Array.from(new Set([...existing, ...stylexPackages]));
425
- return {
426
- optimizeDeps: {
427
- ...(config?.optimizeDeps || {}),
428
- exclude: addExcludes(config?.optimizeDeps?.exclude || [])
429
- },
430
- ssr: {
431
- ...(config?.ssr || {}),
432
- optimizeDeps: {
433
- ...(config?.ssr?.optimizeDeps || {}),
434
- exclude: addExcludes(config?.ssr?.optimizeDeps?.exclude || [])
435
- }
436
- }
437
- };
438
- },
439
- configResolved(config) {
440
- try {
441
- viteOutDir = config.build?.outDir || viteOutDir;
442
- } catch {}
443
- },
444
- configureServer(server) {
445
- viteServer = server;
446
- if (devMode === 'full') {
447
- server.middlewares.use(devInjectMiddleware);
448
- }
449
- server.middlewares.use((req, res, next) => {
450
- if (!req.url) return next();
451
- if (req.url.startsWith(DEV_CSS_PATH)) {
452
- res.statusCode = 200;
453
- res.setHeader('Content-Type', 'text/css');
454
- res.setHeader('Cache-Control', 'no-store');
455
- const css = collectCss();
456
- res.end(css || '');
457
- return;
458
- }
459
- next();
460
- });
461
- const shared = getSharedStore();
462
- let lastVersion = shared.version;
463
- const interval = setInterval(() => {
464
- const curr = shared.version;
465
- if (curr !== lastVersion) {
466
- lastVersion = curr;
467
- try {
468
- server.ws.send({
469
- type: 'custom',
470
- event: 'stylex:css-update'
471
- });
472
- } catch {}
473
- }
474
- }, 150);
475
- server.httpServer?.once('close', () => clearInterval(interval));
476
- },
477
- resolveId(id) {
478
- if (devMode === 'full' && id.includes('virtual:stylex:runtime')) return id;
479
- if (devMode === 'css-only' && id.includes('virtual:stylex:css-only')) return id;
480
- return null;
481
- },
482
- load(id) {
483
- if (devMode === 'full' && id.includes('virtual:stylex:runtime')) {
484
- return VIRTUAL_STYLEX_RUNTIME_SCRIPT;
485
- }
486
- if (devMode === 'css-only' && id.includes('virtual:stylex:css-only')) {
487
- return VIRTUAL_STYLEX_CSS_ONLY_SCRIPT;
488
- }
489
- return null;
490
- },
491
- transformIndexHtml() {
492
- if (devMode !== 'full') return null;
493
- if (!viteServer) return null;
494
- const base = viteServer.config.base ?? '';
495
- return [{
496
- tag: 'script',
497
- attrs: {
498
- type: 'module',
499
- src: path.join(base, '/@id/virtual:stylex:runtime')
500
- },
501
- injectTo: 'head'
502
- }, {
503
- tag: 'link',
504
- attrs: {
505
- rel: 'stylesheet',
506
- href: path.join(base, DEV_CSS_PATH)
507
- },
508
- injectTo: 'head'
509
- }];
510
- },
511
- handleHotUpdate(ctx) {
512
- const base = ctx.server.config.base ?? '';
513
- const cssMod = ctx.server.moduleGraph.getModuleById(path.join(base, 'virtual:stylex:css-module'));
514
- if (cssMod) {
515
- ctx.server.moduleGraph.invalidateModule(cssMod);
516
- }
517
- try {
518
- ctx.server.ws.send({
519
- type: 'custom',
520
- event: 'stylex:css-update'
521
- });
522
- } catch {}
523
- }
524
- },
525
- webpack(compiler) {
526
- const PLUGIN_NAME = '@stylexjs/unplugin';
527
- compiler.hooks.thisCompilation.tap(PLUGIN_NAME, compilation => {
528
- resetState();
529
- const wp = compiler.webpack || compiler.rspack || undefined;
530
- const stage = wp?.Compilation?.PROCESS_ASSETS_STAGE_SUMMARIZE;
531
- const tapOptions = stage != null ? {
532
- name: PLUGIN_NAME,
533
- stage
534
- } : PLUGIN_NAME;
535
- const toRawSource = content => {
536
- const RawSource = wp?.sources?.RawSource;
537
- return RawSource ? new RawSource(content) : {
538
- source: () => content,
539
- size: () => Buffer.byteLength(content)
540
- };
541
- };
542
- compilation.hooks.processAssets.tap(tapOptions, assets => {
543
- const css = collectCss();
544
- if (!css) return;
545
- const cssAssets = Object.keys(assets).filter(f => f.endsWith('.css'));
546
- if (cssAssets.length === 0) {
547
- compilation.warnings.push(new Error('[stylex] No CSS asset found to inject into. Skipping.'));
548
- return;
549
- }
550
- const pickName = typeof cssInjectionTarget === 'function' && cssAssets.find(f => cssInjectionTarget(f)) || cssAssets.find(f => /(^|\/)index\.css$/.test(f)) || cssAssets.find(f => /(^|\/)style\.css$/.test(f)) || cssAssets[0];
551
- const asset = compilation.getAsset(pickName);
552
- if (!asset) return;
553
- const existing = asset.source.source().toString();
554
- const next = existing ? existing + '\n' + css : css;
555
- compilation.updateAsset(pickName, toRawSource(next));
556
- });
557
- });
558
- },
559
- rspack(compiler) {
560
- this.webpack?.(compiler);
561
- },
562
- esbuild: {
563
- name: '@stylexjs/unplugin',
564
- setup(build) {
565
- build.onEnd(async result => {
566
- try {
567
- const css = collectCss();
568
- if (!css) return;
569
- const initial = build.initialOptions;
570
- const outDir = initial.outdir || (initial.outfile ? path.dirname(initial.outfile) : null);
571
- if (!outDir) return;
572
- let outfile = null;
573
- const meta = result && result.metafile;
574
- if (meta && meta.outputs) {
575
- const outputs = Object.keys(meta.outputs);
576
- const cssOutputs = outputs.filter(f => f.endsWith('.css'));
577
- const pick = cssOutputs.find(f => /(^|\/)index\.css$/.test(f)) || cssOutputs.find(f => /(^|\/)style\.css$/.test(f)) || cssOutputs[0];
578
- if (pick) outfile = path.isAbsolute(pick) ? pick : path.join(process.cwd(), pick);
579
- } else {
580
- try {
581
- const files = fs.readdirSync(outDir).filter(f => f.endsWith('.css'));
582
- const pick = files.find(f => /(^|\/)index\.css$/.test(f)) || files.find(f => /(^|\/)style\.css$/.test(f)) || files[0];
583
- if (pick) outfile = path.join(outDir, pick);
584
- } catch {}
585
- }
586
- if (!outfile) {
587
- const fallback = path.join(outDir, 'stylex.css');
588
- await fsp.mkdir(path.dirname(fallback), {
589
- recursive: true
590
- });
591
- await fsp.writeFile(fallback, css, 'utf8');
592
- return;
593
- }
594
- try {
595
- const current = fs.readFileSync(outfile, 'utf8');
596
- if (!current.includes(css)) {
597
- await fsp.writeFile(outfile, current ? current + '\n' + css : css, 'utf8');
598
- }
599
- } catch {}
600
- } catch {}
601
- });
602
- }
603
- },
604
- async writeBundle(options, bundle) {
605
- try {
606
- const css = collectCss();
607
- if (!css) return;
608
- const target = pickCssAssetFromRollupBundle(bundle, cssInjectionTarget);
609
- const outDir = options?.dir || (options?.file ? path.dirname(options.file) : viteOutDir);
610
- if (!outDir) return;
611
- try {
612
- await fsp.mkdir(outDir, {
613
- recursive: true
614
- });
615
- } catch {}
616
- let outfile;
617
- if (!target) {
618
- try {
619
- const assetsDir = path.join(outDir, 'assets');
620
- if (fs.existsSync(assetsDir)) {
621
- const files = fs.readdirSync(assetsDir).filter(f => f.endsWith('.css'));
622
- const pick = files.find(f => /(^|\/)index\.css$/.test(f)) || files.find(f => /(^|\/)style\.css$/.test(f)) || files[0];
623
- if (pick) outfile = path.join(assetsDir, pick);
624
- }
625
- } catch {}
626
- if (!outfile) {
627
- const assetsDir = path.join(outDir, 'assets');
628
- try {
629
- await fsp.mkdir(assetsDir, {
630
- recursive: true
631
- });
632
- } catch {}
633
- const fallback = path.join(assetsDir, 'stylex.css');
634
- await fsp.writeFile(fallback, css, 'utf8');
635
- return;
636
- }
637
- } else {
638
- outfile = path.join(outDir, target.fileName);
639
- }
640
- try {
641
- const current = fs.readFileSync(outfile, 'utf8');
642
- if (!current.includes(css)) {
643
- await fsp.writeFile(outfile, current ? current + '\n' + css : css, 'utf8');
644
- }
645
- } catch {}
646
- } catch {}
647
- }
648
- };
649
- });
650
- export default unpluginInstance;
651
- export const unplugin = unpluginInstance;
1
+ import bun, { createStylexBunPlugin } from "./bun.mjs";
2
+ import esbuild from "./esbuild.mjs";
3
+ import farm from "./farm.mjs";
4
+ import rolldown from "./rolldown.mjs";
5
+ import rollup from "./rollup.mjs";
6
+ import rspack from "./rspack.mjs";
7
+ import unloader from "./unloader.mjs";
8
+ import vite from "./vite.mjs";
9
+ import webpack from "./webpack.mjs";
10
+ import { unpluginFactory } from "./core.mjs";
11
+ const stylex = {
12
+ bun: createStylexBunPlugin,
13
+ esbuild,
14
+ farm,
15
+ rolldown,
16
+ rollup,
17
+ rspack,
18
+ unloader,
19
+ vite,
20
+ webpack,
21
+ raw: unpluginFactory
22
+ };
23
+ export { bun, esbuild, farm, rolldown, rollup, rspack, unloader, vite, webpack, createStylexBunPlugin };
24
+ export { unpluginFactory } from "./core.mjs";
25
+ export const unplugin = stylex;
26
+ export default stylex;
@@ -0,0 +1,4 @@
1
+ import { createRolldownPlugin } from 'unplugin';
2
+ import { unpluginFactory } from "./core.mjs";
3
+ import { attachRollupHooks } from "./rollup.mjs";
4
+ export default createRolldownPlugin((options, metaOptions) => attachRollupHooks(unpluginFactory(options, metaOptions)));