@eightshift/frontend-libs-tailwind 4.0.0-beta.3 → 4.0.0-beta.5

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.
Files changed (41) hide show
  1. package/CHANGELOG.md +30 -1
  2. package/README.md +149 -12
  3. package/bin/tw-sweep.mjs +35 -14
  4. package/bun/browser-css.mjs +487 -0
  5. package/bun/build.mjs +20 -1
  6. package/bun/cli-supervisor.mjs +171 -0
  7. package/bun/cli-worker.mjs +57 -0
  8. package/bun/cli.mjs +3 -49
  9. package/bun/css.mjs +126 -25
  10. package/bun/discovery.mjs +12 -1
  11. package/bun/editor-native.mjs +38 -0
  12. package/bun/editor-pure-jsx.mjs +88 -0
  13. package/bun/editor.mjs +33 -0
  14. package/bun/eightshift-discovery.mjs +102 -26
  15. package/bun/flat-publication.mjs +19 -184
  16. package/bun/index.mjs +14 -0
  17. package/bun/media.mjs +17 -5
  18. package/bun/plugin-capabilities.mjs +1 -0
  19. package/bun/preset.mjs +6 -4
  20. package/bun/publish.mjs +7 -4
  21. package/bun/release.mjs +56 -4
  22. package/bun/shared-fonts.mjs +140 -0
  23. package/bun/ssr.mjs +26 -12
  24. package/bun/structured-publication.mjs +66 -0
  25. package/bun/theme-build.mjs +130 -43
  26. package/bun/theme-discovery.mjs +113 -9
  27. package/bun/watch.mjs +32 -0
  28. package/bun/wordpress.mjs +49 -23
  29. package/eslint.config.mjs +22 -1
  30. package/linters/base.config.mjs +1 -0
  31. package/linters/tw-sweep-extract.mjs +5 -0
  32. package/package.json +5 -5
  33. package/scripts/components/link-section-editor.js +1 -0
  34. package/scripts/editor/editor.js +1 -0
  35. package/scripts/editor/registration.js +3 -0
  36. package/scripts/editor/store.js +7 -0
  37. package/test/bun-discovery.test.mjs +69 -0
  38. package/test/bun-publication.test.mjs +144 -0
  39. package/test/bun-theme-build.test.mjs +12 -0
  40. package/test/bun-wordpress.test.mjs +82 -0
  41. package/test/fixtures/theme-build-regressions.mjs +585 -0
@@ -1,51 +1,68 @@
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';
13
15
  import { buildSsr as buildDefaultSsr } from './ssr.mjs';
16
+ import { prepareSharedFonts } from './shared-fonts.mjs';
14
17
 
15
18
  /**
16
19
  * Define a conventional theme build. extraCss may be a hook or an array of
17
20
  * { files, output?, keys?, href? }; package files use the `package:` prefix.
18
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.
19
25
  * SSR is built when conventional entries exist; ssr: false disables it.
20
26
  * optimizeImports controls Bun's package barrel optimization for browser builds.
21
27
  * UI Components is optimized by default; pass [] to disable the explicit default.
22
28
  * watch: false disables watching; an object overrides the safe watch defaults.
23
29
  */
24
- export function defineThemeBuild({
25
- root,
26
- publicPrefix: configuredPublicPrefix,
27
- buildSsr,
28
- createPlugins = () => [],
29
- frontendStyles = [],
30
- optimizeImports = ['@eightshift/ui-components'],
31
- extraCss = async () => {},
32
- aliases = {},
33
- publication = async () => ({}),
34
- requireEditorWorker = false,
35
- media = {},
36
- watch = {},
37
- entries,
38
- editor,
39
- responsive = {},
40
- css,
41
- discovery,
42
- ssr,
43
- publish,
44
- } = {}) {
30
+ export function defineThemeBuild(options = {}) {
31
+ if (Object.hasOwn(options, 'publicationLayout')) {
32
+ throw new TypeError('publicationLayout has been removed; theme builds use structured publication. Remove the option and migrate publication hooks to publicationRoot.');
33
+ }
34
+
35
+ const {
36
+ root,
37
+ publicPrefix: configuredPublicPrefix,
38
+ buildSsr,
39
+ createPlugins = () => [],
40
+ frontendStyles = [],
41
+ optimizeImports = ['@eightshift/ui-components'],
42
+ sharedFonts = false,
43
+ extraCss = async () => {},
44
+ aliases = {},
45
+ publication = async () => ({}),
46
+ requireEditorWorker = false,
47
+ media = {},
48
+ watch = {},
49
+ entries,
50
+ editor,
51
+ responsive = {},
52
+ css,
53
+ discovery,
54
+ ssr,
55
+ publish,
56
+ } = options;
57
+
45
58
  if (typeof root !== 'string' || !root) {
46
59
  throw new TypeError('root must be a non-empty string');
47
60
  }
48
61
 
62
+ if (typeof sharedFonts !== 'boolean' || (sharedFonts && publish !== undefined)) {
63
+ throw new TypeError('sharedFonts must be a boolean and requires default theme publication');
64
+ }
65
+
49
66
  if (typeof createPlugins !== 'function') {
50
67
  throw new TypeError('createPlugins must be a function');
51
68
  }
@@ -152,34 +169,47 @@ export function defineThemeBuild({
152
169
  const wpRoot = process.env.EIGHTSHIFT_WP_ROOT ? resolve(process.env.EIGHTSHIFT_WP_ROOT) : resolve(root, '../../..');
153
170
  const themePath = relative(wpRoot, resolve(root));
154
171
  let publicPath = configuredPublicPrefix ?? process.env.EIGHTSHIFT_PUBLIC_PREFIX;
172
+
155
173
  if (publicPath === undefined) {
156
174
  if (!themePath || themePath === '..' || themePath.startsWith(`..${sep}`) || isAbsolute(themePath)) {
157
175
  throw new Error('Theme must be inside the WordPress root unless publicPrefix is configured');
158
176
  }
177
+
159
178
  publicPath = `/${themePath.split(sep).join('/')}/public/`;
160
179
  }
180
+
161
181
  if (typeof publicPath !== 'string' || !publicPath.startsWith('/') || publicPath.startsWith('//') || !publicPath.endsWith('/') || publicPath.includes('\\') || /[?#\s\x00-\x1f]/.test(publicPath) || publicPath.split('/').some((part) => part === '.' || part === '..')) {
162
182
  throw new Error('publicPrefix must be a root-relative URL path ending in /');
163
183
  }
184
+
164
185
  let outdir;
165
186
  let editorWorker;
187
+ let retainedStyles;
166
188
  const makePreset = async ({ sourcemaps }) => {
167
189
  const versionFile = resolve(wpRoot, 'wp-includes/version.php');
168
190
  let versionSource;
191
+
169
192
  try {
170
193
  versionSource = await readFile(versionFile, 'utf8');
171
194
  } catch (error) {
172
195
  throw new Error(`Cannot read WordPress version at ${versionFile}. Set EIGHTSHIFT_WP_ROOT to a WordPress installation.`, { cause: error });
173
196
  }
197
+
174
198
  const version = versionSource.match(/^\s*\$wp_version\s*=\s*['"](\d+)\.(\d+)(?:\.(\d+))?(['"]);/m);
199
+
175
200
  if (!version) {
176
201
  throw new Error(`Cannot determine a stable WordPress version from ${versionFile}; WordPress 7.0 or newer is required.`);
177
202
  }
203
+
178
204
  if (Number(version[1]) < 7) {
179
205
  throw new Error(`WordPress 7.0 or newer is required; found ${version[1]}.${version[2]}${version[3] === undefined ? '' : `.${version[3]}`}.`);
180
206
  }
181
207
 
182
208
  editorWorker = undefined;
209
+ retainedStyles = new Set();
210
+ const extraCssByFile = new Map();
211
+ const conventionalCss = new Map();
212
+ const responsiveFiles = {};
183
213
  const publicDir = resolve(root, 'public');
184
214
  outdir = publish === undefined ? resolve(root, '.bun-pilot/theme-build') : resolve(publicDir, '.build');
185
215
  await clearBuildDirectory(outdir, root);
@@ -219,7 +249,7 @@ export function defineThemeBuild({
219
249
  ...manifestReplacements,
220
250
  ['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();'],
221
251
  ],
222
- remove: [/dynamicImport\(require\.context\([^\n]+\)\);/g],
252
+ 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,
223
253
  },
224
254
  {
225
255
  path: 'src/Blocks/assets/scripts/application-admin.js',
@@ -232,7 +262,7 @@ export function defineThemeBuild({
232
262
  ["require.context('./../../custom', true, /assets-admin\\/index\\.js$/)", 'customAdminAssets'],
233
263
  ['return import(/* webpackMode: "lazy" */ `./../../${importBasePath}/${directory}/assets-admin/index.js`);', 'return assetContext(assetPath);'],
234
264
  ],
235
- remove: [/dynamicImport\(require\.context\([^\n]+\)\);/g],
265
+ 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,
236
266
  },
237
267
  ],
238
268
  }).setup(builder);
@@ -240,6 +270,8 @@ export function defineThemeBuild({
240
270
  };
241
271
  const pluginContext = {
242
272
  root,
273
+ publicPrefix: publicPath,
274
+ scriptUrlIdentifier: editor?.scriptUrlIdentifier ?? '__eightshiftEditorScriptUrl',
243
275
  setEditorWorker: (worker) => {
244
276
  editorWorker = worker;
245
277
  },
@@ -254,6 +286,10 @@ export function defineThemeBuild({
254
286
  const workerFactory = media.editorWorker === undefined ? editorWorkerPlugin : media.editorWorker;
255
287
  const plugins = workerFactory ? [workerFactory(pluginContext), ...callerPlugins] : [...callerPlugins];
256
288
 
289
+ if (publish === undefined) {
290
+ plugins.push(browserCssPlugin({ root, outdir, conventionalCss, extraCssByFile, responsiveFiles, retainedStyles }));
291
+ }
292
+
257
293
  if (discovery === undefined) {
258
294
  plugins.push(allowPureJsxGrouping(discoveryPlugin));
259
295
  } else if (discovery) {
@@ -276,19 +312,26 @@ export function defineThemeBuild({
276
312
  editor: editor ?? {
277
313
  entry: 'editor',
278
314
  filename: 'applicationBlocksEditor.js',
315
+ sharing: 'unified',
279
316
  discovery: {
280
317
  filter: /application-blocks-editor\.js$/,
281
- omitContexts: ({ pattern }) => pattern.source === 'styles-editor.css$',
318
+ omitContexts: ({ pattern }) => ['styles-editor.css$', 'styles-editor\\.css$'].includes(pattern.source),
282
319
  },
283
320
  },
284
321
  css: async (context) => {
285
322
  const { outdir: stage, responsive: generated } = context;
323
+ Object.assign(responsiveFiles, generated);
286
324
 
287
325
  if (css === undefined) {
288
326
  for (const surface of ['frontend', 'editor', 'admin']) {
289
327
  const name = surface === 'admin' ? 'applicationAdmin' : `applicationBlocks${surface === 'frontend' ? 'Frontend' : 'Editor'}`;
290
328
 
291
- await processEightshiftCss({ projectDir: root, surface, responsiveFile: generated[surface], outputFile: resolve(stage, 'css', `${name}.css`), production: true });
329
+ const files = await eightshiftCssEntries({ projectDir: root, surface, responsiveFile: generated[surface] });
330
+ await processCss({ projectDir: root, files, outputFile: resolve(stage, 'css', `${name}.css`), production: true });
331
+
332
+ if (surface !== 'editor' && publish === undefined) {
333
+ conventionalCss.set(surface, await collectConventionalCss({ root, files }));
334
+ }
292
335
  }
293
336
  } else if (css) {
294
337
  await css({ ...context, stage, require });
@@ -309,10 +352,12 @@ export function defineThemeBuild({
309
352
 
310
353
  return file.startsWith('package:') ? require.resolve(file.slice(8)) : isAbsolute(file) ? file : resolve(root, file);
311
354
  };
355
+
312
356
  const temporary = resolve(stage, 'css', `.extra-${randomUUID()}.css`);
313
357
  const outputFile = output ? resolve(stage, 'css', output) : temporary;
358
+ const resolvedFiles = files.map((entry) => (typeof entry === 'string' ? resolveFile(entry) : { ...entry, file: resolveFile(entry?.file) }));
314
359
 
315
- await processCss({ projectDir: root, outputFile, files: files.map((entry) => (typeof entry === 'string' ? resolveFile(entry) : { ...entry, file: resolveFile(entry?.file) })), production: true });
360
+ await processCss({ projectDir: root, outputFile, files: resolvedFiles, production: true });
316
361
  let name = output;
317
362
 
318
363
  if (!name) {
@@ -332,8 +377,20 @@ export function defineThemeBuild({
332
377
  await unlink(temporary);
333
378
  }
334
379
 
380
+ retainedStyles.add(name);
381
+
335
382
  if (keys) {
336
- styles.push({ keys, href: href ?? `../css/${name}` });
383
+ const group = { href: href ?? `../css/${name}`, files: resolvedFiles };
384
+ styles.push({ keys, href: group.href });
385
+
386
+ if (publish === undefined) {
387
+ for (const entry of resolvedFiles) {
388
+ const file = await realpath(typeof entry === 'string' ? entry : entry.file);
389
+ const groups = extraCssByFile.get(file) ?? [];
390
+ groups.push(group);
391
+ extraCssByFile.set(file, groups);
392
+ }
393
+ }
337
394
  }
338
395
  }
339
396
 
@@ -343,11 +400,13 @@ export function defineThemeBuild({
343
400
  glob: 'src/Blocks/{components,custom}/**/assets/index.js',
344
401
  key: (file) => file.replace(/^src\/Blocks\//, '').replace(/\/assets\/index\.js$/, ''),
345
402
  styles,
403
+ ...(publish === undefined ? { styleRuntime: browserCssRuntime } : {}),
346
404
  });
347
405
  discoveryDir = resolve(stage, 'discovery');
348
406
  await generateThemeDiscovery({ root, outputDir: discoveryDir, surfaces });
349
407
  }
350
408
  },
409
+ entryPublicPaths: Object.fromEntries(['frontend', 'admin'].filter((name) => entries === undefined || Object.hasOwn(entries, name)).map((name) => [name, `${publicPath}${name}/`])),
351
410
  buildOptions: {
352
411
  optimizeImports,
353
412
  minify: true,
@@ -355,11 +414,12 @@ export function defineThemeBuild({
355
414
  naming: { entry: '[name]-[hash].[ext]', chunk: '[name]-[hash].[ext]', asset: '[name]-[hash].[ext]' },
356
415
  sourcemap: sourcemaps ? 'external' : 'none',
357
416
  loader: { '.js': 'jsx', '.svg': 'file' },
358
- define: { 'process.browser': 'true', 'process.env.NODE_ENV': '"production"', 'process.env.VERSION': '"library-release"' },
417
+ define: { 'process.browser': 'true', 'process.env.NODE_ENV': '"production"', 'process.env.VERSION': JSON.stringify(createHash('sha256').update(publicPath).digest('hex').slice(0, 20)) },
359
418
  plugins,
360
419
  },
361
420
  };
362
421
  };
422
+
363
423
  const defaultPublish = async ({ result, verbose, quiet }) => {
364
424
  const editorScript = await readFile(resolve(outdir, result.entries.editor.entry), 'utf8');
365
425
 
@@ -394,14 +454,18 @@ export function defineThemeBuild({
394
454
  }
395
455
  }
396
456
 
457
+ for (const surface of ['frontend', 'admin']) {
458
+ if (result.entries[surface].styles.length) {
459
+ throw new Error(`Unexpected Bun CSS output for ${surface}; a custom plugin bypassed the theme CSS loader. Configure a compatible plugin or custom publication.`);
460
+ }
461
+ }
462
+
397
463
  const surfaces = { frontend: 'applicationBlocksFrontend', editor: 'applicationBlocksEditor', admin: 'applicationAdmin' };
398
- const flatDir = resolve(outdir, 'flat');
399
- const { rewrite } = await flattenAssets({
464
+ const flatDir = resolve(outdir, 'structured');
465
+ await preserveAssets({
400
466
  outdir,
401
467
  flatDir,
402
468
  extraSources: editorWorker ? { [`editor/editor-assets/${basename(editorWorker)}`]: editorWorker } : {},
403
- editorEntry: result.entries.editor.entry,
404
- editorScript,
405
469
  });
406
470
  // Webpack exposed standalone images by basename, even when not imported by JS.
407
471
  const standaloneAssets = new Map();
@@ -418,7 +482,22 @@ export function defineThemeBuild({
418
482
 
419
483
  const entries = Object.entries(surfaces).map(([surface, name]) => {
420
484
  const entry = result.entries[surface];
421
- const script = surface === 'editor' ? rewrite(editorScript, entry.entry) : undefined;
485
+ let script;
486
+
487
+ if (surface === 'editor') {
488
+ if (entry.format === 'module') {
489
+ script = editorScript.replace(/^(import ["'])\.\//gm, `$1./${entry.entry.slice(0, entry.entry.lastIndexOf('/') + 1)}`);
490
+ } else {
491
+ const wrapper = '})(document.currentScript.src);\n';
492
+
493
+ if (editorScript.split(wrapper).length !== 2) {
494
+ throw new Error('Cannot relocate the classic editor script wrapper');
495
+ }
496
+
497
+ script = editorScript.replace(wrapper, () => `})(new URL(${JSON.stringify(entry.entry)}, document.currentScript.src).href);\n`);
498
+ script = script.replace(/^(\/\/# sourceMappingURL=)([^\r\n]+)$/m, (_match, prefix, map) => `${prefix}${entry.entry.slice(0, entry.entry.lastIndexOf('/') + 1)}${map}`);
499
+ }
500
+ }
422
501
 
423
502
  if (verbose && !quiet) {
424
503
  console.log(`${surface}: ${entry.entry}; dependencies: ${entry.dependencies.join(', ') || 'none'}`);
@@ -426,14 +505,14 @@ export function defineThemeBuild({
426
505
 
427
506
  return {
428
507
  name,
429
- entry: surface === 'editor' ? 'editor-entry.js' : basename(entry.entry),
430
- style: `${name}.css`,
508
+ entry: entry.entry,
509
+ style: `css/${name}.css`,
431
510
  dependencies: entry.dependencies,
432
511
  ...(script && { script }),
433
512
  ...(entry.format === 'module' ? { format: entry.format, readiness: entry.readiness } : {}),
434
513
  };
435
514
  });
436
- const publicationResult = await publication({ root, outdir, result });
515
+ const publicationResult = await publication({ root, outdir, result, publicationRoot: flatDir });
437
516
  const additions = publicationResult === undefined ? {} : publicationResult;
438
517
 
439
518
  if (!additions || typeof additions !== 'object' || Array.isArray(additions)) {
@@ -453,23 +532,31 @@ export function defineThemeBuild({
453
532
  throw new Error(`Duplicate publication alias: ${key}`);
454
533
  }
455
534
  }
535
+
536
+ const fontAssets = sharedFonts ? await prepareSharedFonts({ root, flatDir, retainedStyles }) : { extraFiles: [], aliases: {} };
537
+
538
+ if (sharedFonts && (Object.hasOwn(aliases, 'shared-fonts.json') || Object.hasOwn(additions.aliases ?? {}, 'shared-fonts.json'))) {
539
+ throw new Error('shared-fonts.json is reserved when sharedFonts is enabled');
540
+ }
541
+
456
542
  const { release, version, manifest } = await packageFlatRelease({
457
- extraFiles: additions.extraFiles,
543
+ extraFiles: [...fontAssets.extraFiles, ...(additions.extraFiles ?? [])],
458
544
  retain: additions.retain,
459
545
  previousPublic: resolve(root, 'public'),
460
546
  root: outdir,
461
- removeIntermediates: true,
547
+ removeUnreferencedStyles: css === undefined,
462
548
  flatDir,
463
549
  entries,
464
550
  ssrDir,
465
551
  ssrNames,
466
552
  standaloneAssets,
467
- aliases: { ...aliases, ...additions.aliases },
553
+ aliases: { ...aliases, ...additions.aliases, ...fontAssets.aliases },
468
554
  });
469
555
 
470
556
  await publishFlatRelease({ root, wpRoot, release, manifest, version, publicPrefix: publicPath });
471
557
  await clearBuildDirectory(outdir, root);
472
558
  };
559
+
473
560
  const defaultSsr = ({ root, mode }) => buildDefaultSsr({ root, mode, outdir: resolve(outdir, 'ssr', mode) });
474
561
  const customSsr = ssr ?? buildSsr;
475
562
  const definition = defineBuild({
@@ -479,7 +566,7 @@ export function defineThemeBuild({
479
566
  publish !== undefined && ssr !== false
480
567
  ? async (state) => {
481
568
  if (customSsr) {
482
- return customSsr({ ...state, mode: 'production' });
569
+ return customSsr({ ...state, mode: 'production', outdir: resolve(outdir, 'ssr', 'production') });
483
570
  }
484
571
 
485
572
  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
  }