@eightshift/frontend-libs-tailwind 4.0.0-beta.4 → 4.0.0-beta.6

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.
@@ -1,12 +1,14 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
- import { link, mkdir, readFile, unlink } from 'node:fs/promises';
2
+ import { link, mkdir, readFile, realpath, unlink } from 'node:fs/promises';
3
3
  import { createRequire } from 'node:module';
4
4
  import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
5
5
  import { defineBuild } from './index.mjs';
6
6
  import { clearBuildDirectory } from './build.mjs';
7
7
  import { generateThemeDiscovery, generateThemeImporters, themeDiscoveryPlugin } from './theme-discovery.mjs';
8
- import { processEightshiftCss } from './eightshift-css.mjs';
9
- import { flattenAssets, packageFlatRelease, publishFlatRelease } from './flat-publication.mjs';
8
+ import { eightshiftCssEntries } from './eightshift-css.mjs';
9
+ import { preserveAssets } from './structured-publication.mjs';
10
+ import { packageFlatRelease, publishFlatRelease } from './flat-publication.mjs';
11
+ import { browserCssPlugin, browserCssRuntime, collectConventionalCss } from './browser-css.mjs';
10
12
  import { editorWorkerPlugin } from './media.mjs';
11
13
  import { allowPureJsxGrouping } from './plugin-capabilities.mjs';
12
14
  import { processCss } from './css.mjs';
@@ -17,33 +19,46 @@ import { prepareSharedFonts } from './shared-fonts.mjs';
17
19
  * Define a conventional theme build. extraCss may be a hook or an array of
18
20
  * { files, output?, keys?, href? }; package files use the `package:` prefix.
19
21
  * Omitted output names use a content hash. Keys attach CSS to frontend importers.
22
+ * Frontend/admin JS imports compile styles separately and load them before the
23
+ * importing module; styles imported by lazy modules remain lazy.
24
+ * Direct imports already in conventional CSS are not loaded twice.
20
25
  * SSR is built when conventional entries exist; ssr: false disables it.
21
26
  * optimizeImports controls Bun's package barrel optimization for browser builds.
22
27
  * UI Components is optimized by default; pass [] to disable the explicit default.
23
28
  * watch: false disables watching; an object overrides the safe watch defaults.
29
+ * @param {object} [options]
30
+ * @param {boolean} [options.removeUnreferencedStyles] Override entry CSS cleanup
31
+ * for default publication; omitted enables it only with the default CSS compiler.
24
32
  */
25
- export function defineThemeBuild({
26
- root,
27
- publicPrefix: configuredPublicPrefix,
28
- buildSsr,
29
- createPlugins = () => [],
30
- frontendStyles = [],
31
- optimizeImports = ['@eightshift/ui-components'],
32
- sharedFonts = false,
33
- extraCss = async () => {},
34
- aliases = {},
35
- publication = async () => ({}),
36
- requireEditorWorker = false,
37
- media = {},
38
- watch = {},
39
- entries,
40
- editor,
41
- responsive = {},
42
- css,
43
- discovery,
44
- ssr,
45
- publish,
46
- } = {}) {
33
+ export function defineThemeBuild(options = {}) {
34
+ if (Object.hasOwn(options, 'publicationLayout')) {
35
+ throw new TypeError('publicationLayout has been removed; theme builds use structured publication. Remove the option and migrate publication hooks to publicationRoot.');
36
+ }
37
+
38
+ const {
39
+ root,
40
+ publicPrefix: configuredPublicPrefix,
41
+ buildSsr,
42
+ createPlugins = () => [],
43
+ frontendStyles = [],
44
+ optimizeImports = ['@eightshift/ui-components'],
45
+ sharedFonts = false,
46
+ extraCss = async () => {},
47
+ aliases = {},
48
+ publication = async () => ({}),
49
+ requireEditorWorker = false,
50
+ media = {},
51
+ watch = {},
52
+ entries,
53
+ editor,
54
+ responsive = {},
55
+ css,
56
+ removeUnreferencedStyles = css === undefined,
57
+ discovery,
58
+ ssr,
59
+ publish,
60
+ } = options;
61
+
47
62
  if (typeof root !== 'string' || !root) {
48
63
  throw new TypeError('root must be a non-empty string');
49
64
  }
@@ -52,6 +67,14 @@ export function defineThemeBuild({
52
67
  throw new TypeError('sharedFonts must be a boolean and requires default theme publication');
53
68
  }
54
69
 
70
+ if (typeof removeUnreferencedStyles !== 'boolean') {
71
+ throw new TypeError('removeUnreferencedStyles must be a boolean');
72
+ }
73
+
74
+ if (Object.hasOwn(options, 'removeUnreferencedStyles') && publish !== undefined) {
75
+ throw new TypeError('removeUnreferencedStyles requires default theme publication');
76
+ }
77
+
55
78
  if (typeof createPlugins !== 'function') {
56
79
  throw new TypeError('createPlugins must be a function');
57
80
  }
@@ -158,34 +181,47 @@ export function defineThemeBuild({
158
181
  const wpRoot = process.env.EIGHTSHIFT_WP_ROOT ? resolve(process.env.EIGHTSHIFT_WP_ROOT) : resolve(root, '../../..');
159
182
  const themePath = relative(wpRoot, resolve(root));
160
183
  let publicPath = configuredPublicPrefix ?? process.env.EIGHTSHIFT_PUBLIC_PREFIX;
184
+
161
185
  if (publicPath === undefined) {
162
186
  if (!themePath || themePath === '..' || themePath.startsWith(`..${sep}`) || isAbsolute(themePath)) {
163
187
  throw new Error('Theme must be inside the WordPress root unless publicPrefix is configured');
164
188
  }
189
+
165
190
  publicPath = `/${themePath.split(sep).join('/')}/public/`;
166
191
  }
192
+
167
193
  if (typeof publicPath !== 'string' || !publicPath.startsWith('/') || publicPath.startsWith('//') || !publicPath.endsWith('/') || publicPath.includes('\\') || /[?#\s\x00-\x1f]/.test(publicPath) || publicPath.split('/').some((part) => part === '.' || part === '..')) {
168
194
  throw new Error('publicPrefix must be a root-relative URL path ending in /');
169
195
  }
196
+
170
197
  let outdir;
171
198
  let editorWorker;
199
+ let retainedStyles;
172
200
  const makePreset = async ({ sourcemaps }) => {
173
201
  const versionFile = resolve(wpRoot, 'wp-includes/version.php');
174
202
  let versionSource;
203
+
175
204
  try {
176
205
  versionSource = await readFile(versionFile, 'utf8');
177
206
  } catch (error) {
178
207
  throw new Error(`Cannot read WordPress version at ${versionFile}. Set EIGHTSHIFT_WP_ROOT to a WordPress installation.`, { cause: error });
179
208
  }
209
+
180
210
  const version = versionSource.match(/^\s*\$wp_version\s*=\s*['"](\d+)\.(\d+)(?:\.(\d+))?(['"]);/m);
211
+
181
212
  if (!version) {
182
213
  throw new Error(`Cannot determine a stable WordPress version from ${versionFile}; WordPress 7.0 or newer is required.`);
183
214
  }
215
+
184
216
  if (Number(version[1]) < 7) {
185
217
  throw new Error(`WordPress 7.0 or newer is required; found ${version[1]}.${version[2]}${version[3] === undefined ? '' : `.${version[3]}`}.`);
186
218
  }
187
219
 
188
220
  editorWorker = undefined;
221
+ retainedStyles = new Set();
222
+ const extraCssByFile = new Map();
223
+ const conventionalCss = new Map();
224
+ const responsiveFiles = {};
189
225
  const publicDir = resolve(root, 'public');
190
226
  outdir = publish === undefined ? resolve(root, '.bun-pilot/theme-build') : resolve(publicDir, '.build');
191
227
  await clearBuildDirectory(outdir, root);
@@ -225,7 +261,7 @@ export function defineThemeBuild({
225
261
  ...manifestReplacements,
226
262
  ['return import(/* webpackMode: "lazy" */ `./../../${importBasePath}/${directory}/assets/index.js`);', 'const importer = bunFrontendImporters[`${importBasePath}/${directory}`]; if (!importer) return Promise.reject(new Error("Missing frontend asset")); return importer();'],
227
263
  ],
228
- remove: [/dynamicImport\(require\.context\([^\n]+\)\);/g],
264
+ omitContexts: ({ directory, pattern }) => css === undefined && ['components', 'custom', 'wrapper'].some((group) => directory === resolve(root, 'src/Blocks', group)) && ['styles-frontend.css$', 'styles-frontend\\.css$'].includes(pattern.source) && !pattern.flags,
229
265
  },
230
266
  {
231
267
  path: 'src/Blocks/assets/scripts/application-admin.js',
@@ -238,7 +274,7 @@ export function defineThemeBuild({
238
274
  ["require.context('./../../custom', true, /assets-admin\\/index\\.js$/)", 'customAdminAssets'],
239
275
  ['return import(/* webpackMode: "lazy" */ `./../../${importBasePath}/${directory}/assets-admin/index.js`);', 'return assetContext(assetPath);'],
240
276
  ],
241
- remove: [/dynamicImport\(require\.context\([^\n]+\)\);/g],
277
+ omitContexts: ({ directory, pattern }) => css === undefined && ['components', 'custom'].some((group) => directory === resolve(root, 'src/Blocks', group)) && ['styles-admin.css$', 'styles-admin\\.css$'].includes(pattern.source) && !pattern.flags,
242
278
  },
243
279
  ],
244
280
  }).setup(builder);
@@ -246,6 +282,8 @@ export function defineThemeBuild({
246
282
  };
247
283
  const pluginContext = {
248
284
  root,
285
+ publicPrefix: publicPath,
286
+ scriptUrlIdentifier: editor?.scriptUrlIdentifier ?? '__eightshiftEditorScriptUrl',
249
287
  setEditorWorker: (worker) => {
250
288
  editorWorker = worker;
251
289
  },
@@ -260,6 +298,10 @@ export function defineThemeBuild({
260
298
  const workerFactory = media.editorWorker === undefined ? editorWorkerPlugin : media.editorWorker;
261
299
  const plugins = workerFactory ? [workerFactory(pluginContext), ...callerPlugins] : [...callerPlugins];
262
300
 
301
+ if (publish === undefined) {
302
+ plugins.push(browserCssPlugin({ root, outdir, conventionalCss, extraCssByFile, responsiveFiles, retainedStyles }));
303
+ }
304
+
263
305
  if (discovery === undefined) {
264
306
  plugins.push(allowPureJsxGrouping(discoveryPlugin));
265
307
  } else if (discovery) {
@@ -285,17 +327,23 @@ export function defineThemeBuild({
285
327
  sharing: 'unified',
286
328
  discovery: {
287
329
  filter: /application-blocks-editor\.js$/,
288
- omitContexts: ({ pattern }) => pattern.source === 'styles-editor.css$',
330
+ omitContexts: ({ pattern }) => ['styles-editor.css$', 'styles-editor\\.css$'].includes(pattern.source),
289
331
  },
290
332
  },
291
333
  css: async (context) => {
292
334
  const { outdir: stage, responsive: generated } = context;
335
+ Object.assign(responsiveFiles, generated);
293
336
 
294
337
  if (css === undefined) {
295
338
  for (const surface of ['frontend', 'editor', 'admin']) {
296
339
  const name = surface === 'admin' ? 'applicationAdmin' : `applicationBlocks${surface === 'frontend' ? 'Frontend' : 'Editor'}`;
297
340
 
298
- await processEightshiftCss({ projectDir: root, surface, responsiveFile: generated[surface], outputFile: resolve(stage, 'css', `${name}.css`), production: true });
341
+ const files = await eightshiftCssEntries({ projectDir: root, surface, responsiveFile: generated[surface] });
342
+ await processCss({ projectDir: root, files, outputFile: resolve(stage, 'css', `${name}.css`), production: true });
343
+
344
+ if (surface !== 'editor' && publish === undefined) {
345
+ conventionalCss.set(surface, await collectConventionalCss({ root, files }));
346
+ }
299
347
  }
300
348
  } else if (css) {
301
349
  await css({ ...context, stage, require });
@@ -316,10 +364,12 @@ export function defineThemeBuild({
316
364
 
317
365
  return file.startsWith('package:') ? require.resolve(file.slice(8)) : isAbsolute(file) ? file : resolve(root, file);
318
366
  };
367
+
319
368
  const temporary = resolve(stage, 'css', `.extra-${randomUUID()}.css`);
320
369
  const outputFile = output ? resolve(stage, 'css', output) : temporary;
370
+ const resolvedFiles = files.map((entry) => (typeof entry === 'string' ? resolveFile(entry) : { ...entry, file: resolveFile(entry?.file) }));
321
371
 
322
- await processCss({ projectDir: root, outputFile, files: files.map((entry) => (typeof entry === 'string' ? resolveFile(entry) : { ...entry, file: resolveFile(entry?.file) })), production: true });
372
+ await processCss({ projectDir: root, outputFile, files: resolvedFiles, production: true });
323
373
  let name = output;
324
374
 
325
375
  if (!name) {
@@ -339,8 +389,20 @@ export function defineThemeBuild({
339
389
  await unlink(temporary);
340
390
  }
341
391
 
392
+ retainedStyles.add(name);
393
+
342
394
  if (keys) {
343
- styles.push({ keys, href: href ?? `../css/${name}` });
395
+ const group = { href: href ?? `../css/${name}`, files: resolvedFiles };
396
+ styles.push({ keys, href: group.href });
397
+
398
+ if (publish === undefined) {
399
+ for (const entry of resolvedFiles) {
400
+ const file = await realpath(typeof entry === 'string' ? entry : entry.file);
401
+ const groups = extraCssByFile.get(file) ?? [];
402
+ groups.push(group);
403
+ extraCssByFile.set(file, groups);
404
+ }
405
+ }
344
406
  }
345
407
  }
346
408
 
@@ -350,11 +412,13 @@ export function defineThemeBuild({
350
412
  glob: 'src/Blocks/{components,custom}/**/assets/index.js',
351
413
  key: (file) => file.replace(/^src\/Blocks\//, '').replace(/\/assets\/index\.js$/, ''),
352
414
  styles,
415
+ ...(publish === undefined ? { styleRuntime: browserCssRuntime } : {}),
353
416
  });
354
417
  discoveryDir = resolve(stage, 'discovery');
355
418
  await generateThemeDiscovery({ root, outputDir: discoveryDir, surfaces });
356
419
  }
357
420
  },
421
+ entryPublicPaths: Object.fromEntries(['frontend', 'admin'].filter((name) => entries === undefined || Object.hasOwn(entries, name)).map((name) => [name, `${publicPath}${name}/`])),
358
422
  buildOptions: {
359
423
  optimizeImports,
360
424
  minify: true,
@@ -362,11 +426,12 @@ export function defineThemeBuild({
362
426
  naming: { entry: '[name]-[hash].[ext]', chunk: '[name]-[hash].[ext]', asset: '[name]-[hash].[ext]' },
363
427
  sourcemap: sourcemaps ? 'external' : 'none',
364
428
  loader: { '.js': 'jsx', '.svg': 'file' },
365
- define: { 'process.browser': 'true', 'process.env.NODE_ENV': '"production"', 'process.env.VERSION': '"library-release"' },
429
+ define: { 'process.browser': 'true', 'process.env.NODE_ENV': '"production"', 'process.env.VERSION': JSON.stringify(createHash('sha256').update(publicPath).digest('hex').slice(0, 20)) },
366
430
  plugins,
367
431
  },
368
432
  };
369
433
  };
434
+
370
435
  const defaultPublish = async ({ result, verbose, quiet }) => {
371
436
  const editorScript = await readFile(resolve(outdir, result.entries.editor.entry), 'utf8');
372
437
 
@@ -401,14 +466,18 @@ export function defineThemeBuild({
401
466
  }
402
467
  }
403
468
 
469
+ for (const surface of ['frontend', 'admin']) {
470
+ if (result.entries[surface].styles.length) {
471
+ throw new Error(`Unexpected Bun CSS output for ${surface}; a custom plugin bypassed the theme CSS loader. Configure a compatible plugin or custom publication.`);
472
+ }
473
+ }
474
+
404
475
  const surfaces = { frontend: 'applicationBlocksFrontend', editor: 'applicationBlocksEditor', admin: 'applicationAdmin' };
405
- const flatDir = resolve(outdir, 'flat');
406
- const { rewrite } = await flattenAssets({
476
+ const flatDir = resolve(outdir, 'structured');
477
+ await preserveAssets({
407
478
  outdir,
408
479
  flatDir,
409
480
  extraSources: editorWorker ? { [`editor/editor-assets/${basename(editorWorker)}`]: editorWorker } : {},
410
- editorEntry: result.entries.editor.entry,
411
- editorScript,
412
481
  });
413
482
  // Webpack exposed standalone images by basename, even when not imported by JS.
414
483
  const standaloneAssets = new Map();
@@ -425,7 +494,22 @@ export function defineThemeBuild({
425
494
 
426
495
  const entries = Object.entries(surfaces).map(([surface, name]) => {
427
496
  const entry = result.entries[surface];
428
- const script = surface === 'editor' ? rewrite(editorScript, entry.entry) : undefined;
497
+ let script;
498
+
499
+ if (surface === 'editor') {
500
+ if (entry.format === 'module') {
501
+ script = editorScript.replace(/^(import ["'])\.\//gm, `$1./${entry.entry.slice(0, entry.entry.lastIndexOf('/') + 1)}`);
502
+ } else {
503
+ const wrapper = '})(document.currentScript.src);\n';
504
+
505
+ if (editorScript.split(wrapper).length !== 2) {
506
+ throw new Error('Cannot relocate the classic editor script wrapper');
507
+ }
508
+
509
+ script = editorScript.replace(wrapper, () => `})(new URL(${JSON.stringify(entry.entry)}, document.currentScript.src).href);\n`);
510
+ script = script.replace(/^(\/\/# sourceMappingURL=)([^\r\n]+)$/m, (_match, prefix, map) => `${prefix}${entry.entry.slice(0, entry.entry.lastIndexOf('/') + 1)}${map}`);
511
+ }
512
+ }
429
513
 
430
514
  if (verbose && !quiet) {
431
515
  console.log(`${surface}: ${entry.entry}; dependencies: ${entry.dependencies.join(', ') || 'none'}`);
@@ -433,14 +517,14 @@ export function defineThemeBuild({
433
517
 
434
518
  return {
435
519
  name,
436
- entry: surface === 'editor' ? 'editor-entry.js' : basename(entry.entry),
437
- style: `${name}.css`,
520
+ entry: entry.entry,
521
+ style: `css/${name}.css`,
438
522
  dependencies: entry.dependencies,
439
523
  ...(script && { script }),
440
524
  ...(entry.format === 'module' ? { format: entry.format, readiness: entry.readiness } : {}),
441
525
  };
442
526
  });
443
- const publicationResult = await publication({ root, outdir, result });
527
+ const publicationResult = await publication({ root, outdir, result, publicationRoot: flatDir });
444
528
  const additions = publicationResult === undefined ? {} : publicationResult;
445
529
 
446
530
  if (!additions || typeof additions !== 'object' || Array.isArray(additions)) {
@@ -460,16 +544,19 @@ export function defineThemeBuild({
460
544
  throw new Error(`Duplicate publication alias: ${key}`);
461
545
  }
462
546
  }
463
- const fontAssets = sharedFonts ? await prepareSharedFonts({ root, flatDir }) : { extraFiles: [], aliases: {} };
547
+
548
+ const fontAssets = sharedFonts ? await prepareSharedFonts({ root, flatDir, retainedStyles }) : { extraFiles: [], aliases: {} };
549
+
464
550
  if (sharedFonts && (Object.hasOwn(aliases, 'shared-fonts.json') || Object.hasOwn(additions.aliases ?? {}, 'shared-fonts.json'))) {
465
551
  throw new Error('shared-fonts.json is reserved when sharedFonts is enabled');
466
552
  }
553
+
467
554
  const { release, version, manifest } = await packageFlatRelease({
468
555
  extraFiles: [...fontAssets.extraFiles, ...(additions.extraFiles ?? [])],
469
556
  retain: additions.retain,
470
557
  previousPublic: resolve(root, 'public'),
471
558
  root: outdir,
472
- removeIntermediates: true,
559
+ removeUnreferencedStyles,
473
560
  flatDir,
474
561
  entries,
475
562
  ssrDir,
@@ -481,6 +568,7 @@ export function defineThemeBuild({
481
568
  await publishFlatRelease({ root, wpRoot, release, manifest, version, publicPrefix: publicPath });
482
569
  await clearBuildDirectory(outdir, root);
483
570
  };
571
+
484
572
  const defaultSsr = ({ root, mode }) => buildDefaultSsr({ root, mode, outdir: resolve(outdir, 'ssr', mode) });
485
573
  const customSsr = ssr ?? buildSsr;
486
574
  const definition = defineBuild({
@@ -490,7 +578,7 @@ export function defineThemeBuild({
490
578
  publish !== undefined && ssr !== false
491
579
  ? async (state) => {
492
580
  if (customSsr) {
493
- return customSsr({ ...state, mode: 'production' });
581
+ return customSsr({ ...state, mode: 'production', outdir: resolve(outdir, 'ssr', 'production') });
494
582
  }
495
583
 
496
584
  for await (const _file of new Bun.Glob('src/**/assets-ssr/ssr.{js,mjs}').scan({ cwd: root, onlyFiles: true })) {
@@ -1,5 +1,6 @@
1
1
  import { readFile } from 'node:fs/promises';
2
- import { dirname, resolve } from 'node:path';
2
+ import { basename, dirname, resolve } from 'node:path';
3
+ import { Linter } from 'eslint';
3
4
  import { generateDiscovery } from './discovery.mjs';
4
5
 
5
6
  /**
@@ -34,8 +35,8 @@ export async function generateThemeDiscovery({ root, outputDir, surfaces }) {
34
35
  * loads remove their link and can be retried. URLs resolve relative to the
35
36
  * generated JavaScript module, matching Bun's import.meta.url behavior.
36
37
  */
37
- export async function generateThemeImporters({ root, glob, key, styles = [] }) {
38
- if (!root || typeof glob !== 'string' || typeof key !== 'function' || !Array.isArray(styles)) {
38
+ export async function generateThemeImporters({ root, glob, key, styles = [], styleRuntime }) {
39
+ if (!root || typeof glob !== 'string' || typeof key !== 'function' || !Array.isArray(styles) || (styleRuntime !== undefined && (typeof styleRuntime !== 'string' || !styleRuntime))) {
39
40
  throw new TypeError('Expected root, glob, key and styles');
40
41
  }
41
42
 
@@ -71,9 +72,10 @@ export async function generateThemeImporters({ root, glob, key, styles = [] }) {
71
72
  }
72
73
 
73
74
  const loaders = styles
74
- .map(
75
- ({ href }, index) =>
76
- `let stylePromise${index};
75
+ .map(({ href }, index) =>
76
+ styleRuntime
77
+ ? `const loadStyle${index} = () => __eightshiftLoadStylesheet(new URL(${JSON.stringify(href)}, import.meta.url).href);`
78
+ : `let stylePromise${index};
77
79
  const loadStyle${index} = () => stylePromise${index} ??= new Promise((resolve, reject) => {
78
80
  const link = document.createElement('link');
79
81
  link.rel = 'stylesheet';
@@ -95,15 +97,115 @@ const loadStyle${index} = () => stylePromise${index} ??= new Promise((resolve, r
95
97
  return `${JSON.stringify(name)}: ${style === undefined ? importer : `() => loadStyle${style}().then(${importer})`}`;
96
98
  });
97
99
 
98
- return `${loaders}\nconst bunFrontendImporters = {${importers.join(',')}};`;
100
+ return `${styleRuntime && styles.length ? `import { loadStylesheet as __eightshiftLoadStylesheet } from ${JSON.stringify(styleRuntime)};\n` : ''}${loaders}\nconst bunFrontendImporters = {${importers.join(',')}};`;
101
+ }
102
+
103
+ async function transformEagerContexts(source, path, root, output, omitContexts) {
104
+ const calls = [];
105
+ const identifiers = new Set();
106
+ const messages = new Linter().verify(
107
+ source,
108
+ [
109
+ {
110
+ languageOptions: { ecmaVersion: 'latest', sourceType: 'module', parserOptions: { ecmaFeatures: { jsx: true } } },
111
+ linterOptions: { noInlineConfig: true },
112
+ plugins: {
113
+ capture: {
114
+ rules: {
115
+ contexts: {
116
+ create: () => ({
117
+ Identifier: (node) => identifiers.add(node.name),
118
+ CallExpression: (node) => {
119
+ const context = node.arguments[0];
120
+
121
+ if (
122
+ node.callee.type === 'Identifier' &&
123
+ node.callee.name === 'dynamicImport' &&
124
+ !node.optional &&
125
+ node.arguments.length === 1 &&
126
+ context?.type === 'CallExpression' &&
127
+ context.callee.type === 'MemberExpression' &&
128
+ !context.callee.computed &&
129
+ context.callee.object.name === 'require' &&
130
+ context.callee.property.name === 'context'
131
+ ) {
132
+ calls.push({ node, context });
133
+ }
134
+ },
135
+ }),
136
+ },
137
+ },
138
+ },
139
+ },
140
+ rules: { 'capture/contexts': 'error' },
141
+ },
142
+ ],
143
+ { filename: 'module.js' },
144
+ );
145
+ const fatal = messages.find((message) => message.fatal);
146
+
147
+ if (fatal) {
148
+ throw new Error(`Cannot parse ${path}: ${fatal.message}`);
149
+ }
150
+
151
+ const definitions = [];
152
+ const replacements = [];
153
+
154
+ for (const { node, context } of calls) {
155
+ const [directory, recursive, pattern, mode] = context.arguments;
156
+
157
+ if (
158
+ context.optional ||
159
+ context.arguments.length < 3 ||
160
+ context.arguments.length > 4 ||
161
+ directory?.type !== 'Literal' ||
162
+ typeof directory.value !== 'string' ||
163
+ recursive?.type !== 'Literal' ||
164
+ recursive.value !== true ||
165
+ !pattern?.regex ||
166
+ (mode && (mode.type !== 'Literal' || mode.value !== 'sync'))
167
+ ) {
168
+ throw new Error(`Unsupported eager require.context in ${path}`);
169
+ }
170
+
171
+ const definition = { directory: resolve(dirname(path), directory.value), pattern: new RegExp(pattern.regex.pattern, pattern.regex.flags) };
172
+ let replacement = 'void 0';
173
+
174
+ if (!omitContexts?.({ ...definition, path })) {
175
+ let index = definitions.length;
176
+ let name = `eagerContext${index}`;
177
+
178
+ while (identifiers.has(name)) {
179
+ name = `eagerContext${++index}`;
180
+ }
181
+
182
+ identifiers.add(name);
183
+ definitions.push({ ...definition, name });
184
+ replacement = `${name}.keys().forEach(${name})`;
185
+ }
186
+
187
+ replacements.push({ start: node.start, end: node.end, replacement });
188
+ }
189
+
190
+ for (const { start, end, replacement } of replacements.sort((a, b) => b.start - a.start)) {
191
+ source = source.slice(0, start) + replacement + source.slice(end);
192
+ }
193
+
194
+ if (definitions.length) {
195
+ await generateDiscovery({ root, output, definitions });
196
+ source = `import { ${definitions.map(({ name }) => name).join(', ')} } from ${JSON.stringify(output)};\n${source}`;
197
+ }
198
+
199
+ return source;
99
200
  }
100
201
 
101
202
  /**
102
203
  * Transform only explicitly selected entry paths. Each entry specifies
103
204
  * { path, module, imports, importStatement, replacements, prefix, remove }.
104
205
  * Replacements are [literal, replacement] pairs and must occur exactly once.
105
- * `remove` is an optional array of RegExps; remaining webpack discovery is
106
- * rejected. `prefix` can contain the generated importer map.
206
+ * `remove` is an optional array of RegExps. Remaining eager dynamicImport
207
+ * contexts are generated; `omitContexts` selects separately handled styles.
208
+ * Other webpack discovery is rejected. `prefix` can contain the importer map.
107
209
  */
108
210
  export function themeDiscoveryPlugin({ root, entries }) {
109
211
  if (!root || !Array.isArray(entries)) {
@@ -160,6 +262,8 @@ export function themeDiscoveryPlugin({ root, entries }) {
160
262
  source = source.replace(pattern, '');
161
263
  }
162
264
 
265
+ source = await transformEagerContexts(source, path, root, resolve(dirname(resolve(root, entry.module)), `${basename(path)}.contexts.mjs`), entry.omitContexts);
266
+
163
267
  if (source.includes('require.context') || source.includes('dynamicImport(')) {
164
268
  throw new Error(`Unsupported discovery remains in ${path}`);
165
269
  }