@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
@@ -0,0 +1,585 @@
1
+ import assert from 'node:assert/strict';
2
+ import { access, mkdir, mkdtemp, readFile, readdir, realpath, rmdir, unlink, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
+ import { defineThemeBuild } from '../../bun/theme-build.mjs';
7
+ import { build } from '../../bun/build.mjs';
8
+
9
+ const temporary = await mkdtemp(join(await realpath(tmpdir()), 'eightshift-theme-build-'));
10
+
11
+ async function removeFixture(directory) {
12
+ for (const item of await readdir(directory, { withFileTypes: true })) {
13
+ const path = join(directory, item.name);
14
+
15
+ if (item.isDirectory()) {
16
+ await removeFixture(path);
17
+ } else {
18
+ await unlink(path);
19
+ }
20
+ }
21
+
22
+ await rmdir(directory);
23
+ }
24
+
25
+ async function readStylesheetGraph(path, seen = new Set()) {
26
+ if (seen.has(path)) {
27
+ return '';
28
+ }
29
+ seen.add(path);
30
+ const css = await readFile(path, 'utf8');
31
+ let combined = css;
32
+ for (const [, target] of css.matchAll(/@import\s+(?:url\()?\s*["']([^"']+)["']/g)) {
33
+ combined += await readStylesheetGraph(fileURLToPath(new URL(target, pathToFileURL(path))), seen);
34
+ }
35
+ return combined;
36
+ }
37
+
38
+ async function remapModuleImports(publicDir, publicPrefix) {
39
+ const filePrefix = pathToFileURL(`${publicDir}/`).href;
40
+ const escaped = publicPrefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
41
+ const pattern = new RegExp(`(\\bfrom\\s*["']|\\bimport\\s*\\(\\s*["'])${escaped}`, 'g');
42
+ for (const name of await readdir(publicDir, { recursive: true })) {
43
+ if (!name.endsWith('.js')) continue;
44
+ const path = join(publicDir, name);
45
+ const source = await readFile(path, 'utf8');
46
+ await writeFile(path, source.replace(pattern, (_, prefix) => `${prefix}${filePrefix}`));
47
+ }
48
+ }
49
+
50
+ async function makeTheme(name, sharing = 'unified') {
51
+ const root = join(temporary, 'wp-content', 'themes', name);
52
+ const src = join(root, 'src');
53
+ const ui = join(root, 'node_modules', '@eightshift', 'ui-components', 'dist');
54
+ await mkdir(src, { recursive: true });
55
+ await mkdir(join(ui, 'components', 'smart-image'), { recursive: true });
56
+ await mkdir(join(ui, 'assets'), { recursive: true });
57
+ const tailwind = join(root, 'node_modules', 'tailwindcss');
58
+ await mkdir(tailwind, { recursive: true });
59
+ await writeFile(join(tailwind, 'package.json'), JSON.stringify({ name: 'tailwindcss', exports: { '.': { style: './index.css' }, './index.css': './index.css' } }));
60
+ await writeFile(join(tailwind, 'index.css'), '@theme { --spacing: 0.25rem; } @tailwind utilities;');
61
+ await writeFile(join(root, 'package.json'), JSON.stringify({ name: `fixture-${name}`, type: 'module' }));
62
+ await writeFile(join(ui, 'assets', 'image-analysis-worker-fixture.js'), 'self.onmessage = () => {};');
63
+ await writeFile(
64
+ join(ui, 'components', 'smart-image', 'smart-image.js'),
65
+ 'export function startWorker() { return new Worker(new URL(new URL("../../assets/image-analysis-worker-fixture.js", import.meta.url).href, "" + import.meta.url), { type: "module" }); }',
66
+ );
67
+ const workerImport = 'import { startWorker } from "../node_modules/@eightshift/ui-components/dist/components/smart-image/smart-image.js";';
68
+ await writeFile(join(src, 'frontend.js'), `import "./frontend.css"; ${workerImport} globalThis.frontendFixture = { startWorker, version: process.env.VERSION }; globalThis.loadLazyFixture = () => import("./lazy.js"); globalThis.loadModuleFixture = () => import("./module.js");`);
69
+ await writeFile(join(src, 'frontend.css'), '.static-css-proof { color: red; }');
70
+ await writeFile(join(src, 'lazy.js'), 'import "./lazy.css"; export const lazy = true; export const loadNested = () => import("./nested.js");');
71
+ await writeFile(join(src, 'lazy.css'), '.lazy-css-proof { color: green; }');
72
+ await writeFile(join(src, 'nested.js'), 'import "./nested.css"; globalThis.nestedFixture = true;');
73
+ await writeFile(join(src, 'nested.css'), '.nested-css-proof { color: purple; }');
74
+ await writeFile(join(src, 'module.js'), 'import styles, { leaf } from "./component.module.css"; import imported from "./imported.module.css"; globalThis.moduleFixture = { classes: styles.leaf, named: leaf, imported: imported.shared, leaked: Object.hasOwn(styles, "shared"), utility: "px-4" };');
75
+ await writeFile(join(src, 'base.module.css'), '.base { color: red; }');
76
+ await writeFile(join(src, 'tokens.css'), '@theme { --spacing: 0.25rem; }');
77
+ await writeFile(join(src, 'global.css'), '@import "./global-layer.css"; .global-import-proof { color: orange; background: url("./icon.svg?v=3#mark"); }');
78
+ await writeFile(join(src, 'icon.svg'), '<svg xmlns="http://www.w3.org/2000/svg"></svg>');
79
+ await writeFile(join(src, 'global-layer.css'), '@import "./imported.module.css"; .global-nested-proof { color: pink; }');
80
+ await writeFile(join(src, 'imported.module.css'), '.shared { color: yellow; }');
81
+ await writeFile(join(src, 'component.module.css'), '@layer reset, theme, imported; @import "tailwindcss" layer(theme); @import url("./global.css?v=1#test"); @import "./imported.module.css" layer(imported); @reference "./tokens.css"; .parent { color: blue; } .leaf { composes: parent; composes: base from "./base.module.css"; @apply flex; }');
82
+ await writeFile(join(src, 'admin.js'), `import "./admin.css"; ${workerImport} globalThis.adminFixture = { startWorker, version: process.env.VERSION }; globalThis.loadAdminLazyFixture = () => import("./admin-lazy.js");`);
83
+ await writeFile(join(src, 'admin.css'), '.admin-css-proof { color: navy; }');
84
+ await writeFile(join(src, 'admin-lazy.js'), 'import "./admin-lazy.css"; export const lazy = true;');
85
+ await writeFile(join(src, 'admin-lazy.css'), '.admin-lazy-css-proof { color: teal; }');
86
+ await writeFile(join(src, 'editor.js'), `${workerImport} globalThis.editorFixture = { startWorker, version: process.env.VERSION };`);
87
+
88
+ const publicPrefix = `/wp-content/themes/${name}/public/`;
89
+ const build = defineThemeBuild({
90
+ root,
91
+ publicPrefix,
92
+ entries: { frontend: 'src/frontend.js', admin: 'src/admin.js', editor: 'src/editor.js' },
93
+ editor: { entry: 'editor', sharing, scriptUrlIdentifier: 'customEditorUrl' },
94
+ discovery: false,
95
+ responsive: false,
96
+ ssr: false,
97
+ watch: false,
98
+ css: async ({ stage }) => {
99
+ const output = join(stage, 'css');
100
+ await mkdir(output, { recursive: true });
101
+ for (const surface of ['applicationBlocksFrontend', 'applicationBlocksEditor', 'applicationAdmin']) {
102
+ await writeFile(join(output, `${surface}.css`), '.conventional-css-proof { display: block; }');
103
+ }
104
+ },
105
+ });
106
+
107
+ return { root, publicPrefix, build };
108
+ }
109
+
110
+ async function checkTailwindImports() {
111
+ const root = join(temporary, 'wp-content', 'themes', 'tailwind-import');
112
+ await mkdir(join(root, 'src'), { recursive: true });
113
+ await writeFile(join(root, 'package.json'), '{"name":"tailwind-import-fixture"}');
114
+ await writeFile(join(root, 'src', 'tailwind.css'), '@theme { --spacing: 0.25rem; }');
115
+ await writeFile(join(root, 'src', 'part.css'), '@reference "./tailwind.css"; .tailwind-proof { @apply flex; }');
116
+ await writeFile(join(root, 'src', 'utilities.css'), '@theme { --spacing: 0.25rem; } @tailwind utilities;');
117
+ await writeFile(join(root, 'src', 'frontend.js'), 'import "./part.css"; import "./utilities.css"; globalThis.tailwindFixture = "px-4";');
118
+ await writeFile(join(root, 'src', 'admin.js'), 'console.log("admin");');
119
+ await writeFile(join(root, 'src', 'editor.js'), 'console.log("editor");');
120
+ await defineThemeBuild({
121
+ root,
122
+ entries: { frontend: 'src/frontend.js', admin: 'src/admin.js', editor: 'src/editor.js' },
123
+ editor: { entry: 'editor', sharing: 'unified' },
124
+ discovery: false,
125
+ responsive: false,
126
+ ssr: false,
127
+ watch: false,
128
+ css: async ({ stage }) => {
129
+ const output = join(stage, 'css');
130
+ await mkdir(output, { recursive: true });
131
+ for (const name of ['applicationBlocksFrontend', 'applicationBlocksEditor', 'applicationAdmin']) {
132
+ await writeFile(join(output, `${name}.css`), '.base { display: block; }');
133
+ }
134
+ },
135
+ }).build({ quiet: true });
136
+ const publicDir = join(root, 'public');
137
+ const cssFiles = (await readdir(publicDir, { recursive: true })).filter((name) => name.endsWith('.css'));
138
+ const styles = (await Promise.all(cssFiles.map((name) => readFile(join(publicDir, name), 'utf8')))).join('\n');
139
+ assert.match(styles, /\.tailwind-proof\s*\{[^}]*display\s*:\s*flex/);
140
+ assert.match(styles, /\.px-4\s*\{[^}]*padding-inline/);
141
+ }
142
+
143
+ async function checkConventionalStyleDedup() {
144
+ const root = join(temporary, 'wp-content', 'themes', 'conventional-css');
145
+ await mkdir(join(root, 'src', 'Blocks', 'assets', 'styles'), { recursive: true });
146
+ for (const name of ['card', 'modal']) {
147
+ await mkdir(join(root, 'src', 'Blocks', 'components', name), { recursive: true });
148
+ }
149
+ await writeFile(join(root, 'package.json'), '{"name":"conventional-css-fixture"}');
150
+ for (const surface of ['frontend', 'editor']) {
151
+ await writeFile(join(root, `tailwind-${surface}.css`), `@source './es-tw-${surface}-classes.txt';`);
152
+ }
153
+ await writeFile(join(root, 'color-themes.css'), '.theme { display: block; }');
154
+ for (const surface of ['frontend', 'editor', 'admin']) {
155
+ const name = surface === 'admin' ? 'application-admin' : `application-blocks-${surface}`;
156
+ await writeFile(join(root, 'src', 'Blocks', 'assets', 'styles', `${name}.css`), '.base { display: block; }');
157
+ }
158
+ await writeFile(join(root, 'src', 'Blocks', 'components', 'card', 'styles-frontend.css'), '@import "../../../shared.css"; @import "../../../conditional.css" screen and (min-width: 40rem); @reference "../../../reference.css"; .review-target { color: red; }');
159
+ await writeFile(join(root, 'src', 'Blocks', 'components', 'card', 'manifest.json'), '{"responsive":true,"twClasses":"p-4"}');
160
+ await writeFile(join(root, 'src', 'Blocks', 'components', 'modal', 'styles-frontend.css'), '.review-target { color: blue; } .duplicate-target { color: blue; }');
161
+ await writeFile(join(root, 'src', 'shared.css'), '.duplicate-target { color: red; }');
162
+ await writeFile(join(root, 'src', 'conditional.css'), '.conditional-import-proof { color: teal; }');
163
+ await writeFile(join(root, 'src', 'reference.css'), '.reference-import-proof { color: purple; }');
164
+ await writeFile(join(root, 'src', 'browser-utilities.css'), '@theme { --spacing: 0.25rem; --breakpoint-sm: 40rem; } @tailwind utilities;');
165
+ await writeFile(join(root, 'src', 'frontend.js'), 'import classes from "./Blocks/components/card/styles-frontend.css"; import "./shared.css"; import "./conditional.css"; import "./reference.css"; import "./browser-utilities.css"; globalThis.dedupStyles = classes;');
166
+ await writeFile(join(root, 'src', 'admin.js'), 'console.log("admin");');
167
+ await writeFile(join(root, 'src', 'editor.js'), 'console.log("editor");');
168
+ const { result } = await defineThemeBuild({
169
+ root,
170
+ entries: { frontend: 'src/frontend.js', admin: 'src/admin.js', editor: 'src/editor.js' },
171
+ editor: { entry: 'editor', sharing: 'unified' },
172
+ discovery: false,
173
+ ssr: false,
174
+ watch: false,
175
+ }).build({ quiet: true });
176
+ const publicDir = join(root, 'public');
177
+ const manifest = JSON.parse(await readFile(join(publicDir, 'manifest.json'), 'utf8'));
178
+ await remapModuleImports(publicDir, '/wp-content/themes/conventional-css/public/');
179
+ const loadedStyles = globalThis.document.querySelectorAll('link[rel=stylesheet]');
180
+ const loadedBefore = loadedStyles.length;
181
+ await import(pathToFileURL(join(publicDir, result.entries.frontend.entry)).href);
182
+ const importedCss = (await Promise.all(loadedStyles.slice(loadedBefore).map((link) => readFile(fileURLToPath(link.href), 'utf8')))).join('\n');
183
+ assert.doesNotMatch(importedCss, /duplicate-target/, 'Unconditionally imported conventional styles must not load twice');
184
+ assert.match(importedCss, /conditional-import-proof/, 'Conditional imports must not suppress an unconditional JS import');
185
+ assert.match(importedCss, /reference-import-proof/, '@reference must not suppress a JS import');
186
+ assert.deepEqual(globalThis.dedupStyles, {});
187
+ const css = await readStylesheetGraph(join(publicDir, manifest['applicationBlocksFrontend.css'].split('/public/')[1]));
188
+ const colors = [...css.matchAll(/([^{}]+)\{([^{}]*)\}/g)].filter((match) => match[1].includes('.review-target')).map((match) => match[2].match(/color\s*:\s*(red|blue|#00f)/)?.[1]).filter(Boolean);
189
+ assert.ok(colors.length > 0);
190
+ assert.ok(['blue', '#00f'].includes(colors.at(-1)), `Auto-discovered CSS must retain its cascade: ${css}`);
191
+ const importedStyles = (await Promise.all((await readdir(publicDir, { recursive: true })).filter((name) => name.split('/').at(-1).startsWith('browser-') && name.endsWith('.css')).map((name) => readFile(join(publicDir, name), 'utf8')))).join('\n');
192
+ assert.match(importedStyles, /\.sm\\:p-4\b/, 'Imported Tailwind utilities must include generated responsive classes');
193
+ }
194
+
195
+ async function checkInvalidCssFailsSafely(mode) {
196
+ const root = join(temporary, 'wp-content', 'themes', `invalid-css-${mode}`);
197
+ await mkdir(join(root, 'src'), { recursive: true });
198
+ await mkdir(join(root, 'public'));
199
+ await writeFile(join(root, 'package.json'), '{"name":"invalid-css-fixture"}');
200
+ await writeFile(join(root, 'public', 'sentinel.txt'), 'previous release');
201
+ await writeFile(join(root, 'src', 'admin.js'), 'console.log("admin");');
202
+ await writeFile(join(root, 'src', 'editor.js'), 'console.log("editor");');
203
+ let createPlugins;
204
+ if (mode === 'composition' || mode === 'cycle' || mode === 'css-cycle' || mode === 'tailwind-entry') {
205
+ await writeFile(join(root, 'src', 'frontend.js'), 'import styles from "./a.module.css"; console.log(styles);');
206
+ const a = mode === 'cycle' ? '.item { composes: present from "./b.module.css"; }' : mode === 'css-cycle' ? '@import "./b.module.css"; .item { color: red; }' : mode === 'tailwind-entry' ? '@import "tailwindcss" prefix(tw); .item { color: red; }' : '.item { composes: missing from "./b.module.css"; }';
207
+ const b = mode === 'cycle' ? '.present { composes: item from "./a.module.css"; }' : mode === 'css-cycle' ? '@import "./a.module.css"; .present { color: blue; }' : '.present { color: red; }';
208
+ await writeFile(join(root, 'src', 'a.module.css'), a);
209
+ await writeFile(join(root, 'src', 'b.module.css'), b);
210
+ } else {
211
+ await writeFile(join(root, 'src', 'frontend.js'), 'import "./custom.css"; console.log("frontend");');
212
+ await writeFile(join(root, 'src', 'custom.css'), '.custom { color: red; }');
213
+ createPlugins = () => [{
214
+ name: 'bypass-css-fixture',
215
+ setup(builder) {
216
+ builder.onResolve({ filter: /custom\.css$/ }, ({ path }) => ({ path, namespace: 'bypass-css' }));
217
+ builder.onLoad({ filter: /.*/, namespace: 'bypass-css' }, () => ({ contents: '.custom { color: red; }', loader: 'css' }));
218
+ },
219
+ }];
220
+ }
221
+ const definition = defineThemeBuild({
222
+ root,
223
+ entries: { frontend: 'src/frontend.js', admin: 'src/admin.js', editor: 'src/editor.js' },
224
+ editor: { entry: 'editor', sharing: 'unified' },
225
+ discovery: false,
226
+ responsive: false,
227
+ ssr: false,
228
+ watch: false,
229
+ ...(createPlugins && { createPlugins }),
230
+ css: async ({ stage }) => {
231
+ const output = join(stage, 'css');
232
+ await mkdir(output, { recursive: true });
233
+ for (const name of ['applicationBlocksFrontend', 'applicationBlocksEditor', 'applicationAdmin']) {
234
+ await writeFile(join(output, `${name}.css`), '.base { display: block; }');
235
+ }
236
+ },
237
+ });
238
+ await assert.rejects(definition.build({ quiet: true }), mode === 'plugin' ? /Unexpected Bun CSS output for frontend/ : /Bundle failed|Bun build failed for frontend/);
239
+ assert.equal(await readFile(join(root, 'public', 'sentinel.txt'), 'utf8'), 'previous release');
240
+ }
241
+
242
+ async function checkCustomSsrOutput() {
243
+ const root = join(temporary, 'custom-ssr');
244
+ await mkdir(root);
245
+ await writeFile(join(root, 'entry.js'), 'console.log("browser");');
246
+ for (const publish of [false, async () => {}]) {
247
+ let state;
248
+ await defineThemeBuild({
249
+ root,
250
+ publicPrefix: '/custom-ssr/',
251
+ entries: { app: 'entry.js' },
252
+ editor: false,
253
+ css: false,
254
+ responsive: false,
255
+ discovery: false,
256
+ publish,
257
+ ssr: async (context) => {
258
+ state = context;
259
+ await mkdir(context.outdir, { recursive: true });
260
+ await writeFile(join(context.outdir, 'ssr.js'), 'SSR output');
261
+ },
262
+ }).build({ quiet: true });
263
+ assert.equal(state.root, root);
264
+ assert.equal(state.mode, 'production');
265
+ assert.ok(state.result.entries.app);
266
+ assert.equal(state.outdir, join(root, 'public', '.build', 'ssr', 'production'));
267
+ assert.equal(await readFile(join(state.outdir, 'ssr.js'), 'utf8'), 'SSR output');
268
+ }
269
+ }
270
+
271
+ async function checkLowLevelBuild() {
272
+ const root = join(temporary, 'low-level');
273
+ await mkdir(root);
274
+ await writeFile(join(root, 'entry.js'), 'import "./style.css"; console.log("loaded");');
275
+ await writeFile(join(root, 'style.css'), '.low-level-css { color: red; }');
276
+ const result = await build({ root, outdir: 'output', entries: { app: 'entry.js' }, wordpress: false });
277
+ assert.equal(result.entries.app.styles.length, 1);
278
+ assert.equal(result.entries.app.entryStyle, undefined);
279
+ assert.match(await readFile(join(result.outdir, result.entries.app.styles[0]), 'utf8'), /low-level-css/);
280
+ }
281
+
282
+ async function checkExplicitExtraCss(mode = 'lazy') {
283
+ const eager = mode === 'static';
284
+ const name = `extra-css-${mode}`;
285
+ const root = join(temporary, 'wp-content', 'themes', name);
286
+ const scripts = join(root, 'src', 'Blocks', 'assets', 'scripts');
287
+ const assetDir = join(root, 'src', 'Blocks', 'components', 'card', 'assets');
288
+ await mkdir(scripts, { recursive: true });
289
+ await mkdir(assetDir, { recursive: true });
290
+ await writeFile(join(root, 'package.json'), '{"name":"extra-css-fixture","type":"module"}');
291
+ await writeFile(join(root, 'src', 'vendor.css'), '.extra-css-proof { color: purple; }');
292
+ await writeFile(join(assetDir, '..', 'manifest.json'), '{}');
293
+ await writeFile(join(assetDir, 'index.js'), 'import classes from "../../../../vendor.css"; globalThis.cardClasses = classes; globalThis.cardLoaded = true;');
294
+ const importHelper = "import { dynamicImport } from '@eightshift/frontend-libs-tailwind/scripts/helpers';";
295
+ const contexts = [
296
+ "const components = require.context('./../../components', true, /manifest\\.json$/);",
297
+ "const custom = require.context('./../../custom', true, /manifest\\.json$/);",
298
+ ];
299
+ await writeFile(join(scripts, 'application-blocks-frontend.js'), [
300
+ importHelper,
301
+ ...contexts,
302
+ ...(mode === 'static' ? ['import "./../../components/card/assets/index.js";'] : []),
303
+ ...(mode === 'bypass' ? ['globalThis.bypassFixture = () => import("./../../components/card/assets/index.js");'] : []),
304
+ 'function load(importBasePath, directory) {',
305
+ ' return import(/* webpackMode: "lazy" */ `./../../${importBasePath}/${directory}/assets/index.js`);',
306
+ '}',
307
+ 'globalThis.loadFixtureCard = () => load("components", "card");',
308
+ 'globalThis.frontendReady();',
309
+ ].join('\n'));
310
+ await writeFile(join(scripts, 'application-admin.js'), [
311
+ importHelper,
312
+ ...contexts,
313
+ "const componentAssets = require.context('./../../components', true, /assets-admin\\/index\\.js$/);",
314
+ "const customAssets = require.context('./../../custom', true, /assets-admin\\/index\\.js$/);",
315
+ 'function load(assetContext, assetPath, importBasePath, directory) {',
316
+ ' return import(/* webpackMode: "lazy" */ `./../../${importBasePath}/${directory}/assets-admin/index.js`);',
317
+ '}',
318
+ ].join('\n'));
319
+ await writeFile(join(root, 'src', 'editor.js'), 'console.log("editor");');
320
+ const definition = defineThemeBuild({
321
+ root,
322
+ entries: { frontend: 'src/Blocks/assets/scripts/application-blocks-frontend.js', admin: 'src/Blocks/assets/scripts/application-admin.js', editor: 'src/editor.js' },
323
+ editor: { entry: 'editor', sharing: 'unified', pureJsxGroups: { maxBytes: 4096 } },
324
+ responsive: false,
325
+ ssr: false,
326
+ watch: false,
327
+ extraCss: [{ files: ['src/vendor.css'], keys: ['components/card'], output: 'shared.css' }],
328
+ css: async ({ stage }) => {
329
+ const output = join(stage, 'css');
330
+ await mkdir(output, { recursive: true });
331
+ for (const name of ['applicationBlocksFrontend', 'applicationBlocksEditor', 'applicationAdmin']) {
332
+ await writeFile(join(output, `${name}.css`), '.base { display: block; }');
333
+ }
334
+ },
335
+ });
336
+ const warnings = [];
337
+ const originalWarn = console.warn;
338
+ try {
339
+ console.warn = (...values) => warnings.push(values.join(' '));
340
+ await definition.build({ quiet: true });
341
+ } finally {
342
+ console.warn = originalWarn;
343
+ }
344
+ assert.doesNotMatch(warnings.join('\n'), /Pure JSX grouping disabled: custom plugins/);
345
+ const publicDir = join(root, 'public');
346
+ const manifest = JSON.parse(await readFile(join(publicDir, 'manifest.json'), 'utf8'));
347
+ const publicPrefix = `/wp-content/themes/${name}/public/`;
348
+ const filePrefix = pathToFileURL(`${publicDir}/`).href;
349
+ for (const name of await readdir(publicDir, { recursive: true })) {
350
+ if (name.endsWith('.js')) {
351
+ const path = join(publicDir, name);
352
+ const source = await readFile(path, 'utf8');
353
+ await writeFile(path, source.replaceAll(publicPrefix, filePrefix));
354
+ }
355
+ }
356
+ const entry = await readFile(join(publicDir, manifest['applicationBlocksFrontend.js'].split('/public/')[1]), 'utf8');
357
+ const styles = [{ getAttribute: () => 'shared.css' }];
358
+ let failNextStyle = mode === 'retry';
359
+ const ready = new Promise((resolve) => { globalThis.frontendReady = resolve; });
360
+ globalThis.document = {
361
+ currentScript: { src: pathToFileURL(join(publicDir, manifest['applicationBlocksFrontend.js'].split('/public/')[1])).href },
362
+ querySelector: () => null,
363
+ querySelectorAll: () => styles,
364
+ createElement() {
365
+ const attributes = new Map();
366
+ const link = { setAttribute: (key, value) => attributes.set(key, value), getAttribute: (key) => attributes.get(key), remove: () => styles.splice(styles.indexOf(link), 1) };
367
+ return link;
368
+ },
369
+ head: {
370
+ appendChild(link) {
371
+ if (link.rel === 'stylesheet') {
372
+ styles.push(link);
373
+ queueMicrotask(() => {
374
+ if (failNextStyle) {
375
+ failNextStyle = false;
376
+ link.onerror();
377
+ } else {
378
+ link.onload();
379
+ }
380
+ });
381
+ }
382
+ },
383
+ },
384
+ };
385
+ new Function(entry)();
386
+ let timeout;
387
+ try {
388
+ await Promise.race([ready, new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error('Frontend bootstrap did not load')), 5000); })]);
389
+ } finally {
390
+ clearTimeout(timeout);
391
+ }
392
+ assert.equal(styles.length, 1 + Number(eager), 'Keyed CSS should load early only for eager imports');
393
+ if (mode === 'bypass') await globalThis.bypassFixture();
394
+ if (mode === 'retry') {
395
+ await assert.rejects(globalThis.loadFixtureCard(), /Failed to load stylesheet/);
396
+ assert.equal(styles.length, 1);
397
+ }
398
+ await globalThis.loadFixtureCard();
399
+ assert.equal(globalThis.cardLoaded, true);
400
+ assert.deepEqual(globalThis.cardClasses, {});
401
+ assert.equal(styles.length, 2);
402
+ const mainFile = join(publicDir, manifest['applicationBlocksFrontend.css'].split('/public/')[1]);
403
+ const main = await readStylesheetGraph(mainFile);
404
+ assert.doesNotMatch(await readFile(mainFile, 'utf8'), /@import/, 'An empty emitted bundle must not add CSS requests');
405
+ const extra = await readFile(fileURLToPath(styles[1].href), 'utf8');
406
+ assert.equal((`${main}\n${extra}`.match(/\.extra-css-proof/g) ?? []).length, 1);
407
+ }
408
+
409
+ try {
410
+ await mkdir(join(temporary, 'wp-includes'), { recursive: true });
411
+ await writeFile(join(temporary, 'wp-includes', 'version.php'), "<?php\n$wp_version = '7.0';\n");
412
+ process.env.EIGHTSHIFT_WP_ROOT = temporary;
413
+ for (const publicationLayout of ['flat', 'structured', undefined]) {
414
+ assert.throws(() => defineThemeBuild({ root: temporary, publicationLayout }), /publicationLayout has been removed/);
415
+ }
416
+ const loadedStyles = [];
417
+ globalThis.document = {
418
+ baseURI: 'https://other.test/current/page/',
419
+ querySelector: () => null,
420
+ querySelectorAll: () => loadedStyles,
421
+ createElement() {
422
+ const attributes = new Map();
423
+ return { setAttribute: (key, value) => attributes.set(key, value), getAttribute: (key) => attributes.get(key), remove() {} };
424
+ },
425
+ head: {
426
+ appendChild(link) {
427
+ if (link.rel === 'stylesheet') {
428
+ loadedStyles.push(link);
429
+ queueMicrotask(() => link.onload());
430
+ }
431
+ },
432
+ },
433
+ };
434
+ globalThis.location = { href: 'https://example.test/current/page/' };
435
+ globalThis.Worker = class {
436
+ constructor(url) {
437
+ this.url = url.href;
438
+ }
439
+ };
440
+ globalThis.eightshiftEditorModules = { version: 1, complete() {} };
441
+
442
+ const first = await makeTheme('first');
443
+ const initial = await first.build.build({ quiet: true });
444
+ const publicDir = join(first.root, 'public');
445
+ await remapModuleImports(publicDir, first.publicPrefix);
446
+ const manifest = JSON.parse(await readFile(join(publicDir, 'manifest.json'), 'utf8'));
447
+ const mainStyle = join(publicDir, manifest['applicationBlocksFrontend.css'].split('/public/')[1]);
448
+ const stylesheet = await readStylesheetGraph(mainStyle);
449
+ assert.doesNotMatch(await readFile(mainStyle, 'utf8'), /@import/, 'Simple bundled CSS should not add stylesheet requests');
450
+ assert.match(stylesheet, /conventional-css-proof/);
451
+ assert.doesNotMatch(stylesheet, /(?:static|lazy)-css-proof/, 'JavaScript styles must remain separate from conventional CSS');
452
+ const adminStyle = await readStylesheetGraph(join(publicDir, manifest['applicationAdmin.css'].split('/public/')[1]));
453
+ assert.doesNotMatch(adminStyle, /admin-(?:lazy-)?css-proof/);
454
+ await import(`${pathToFileURL(join(publicDir, initial.result.entries.frontend.entry)).href}?run=1`);
455
+ const frontendStyles = (await Promise.all(loadedStyles.map((link) => readFile(fileURLToPath(link.href), 'utf8')))).join('\n');
456
+ assert.match(frontendStyles, /static-css-proof/);
457
+ assert.doesNotMatch(frontendStyles, /lazy-css-proof/, 'Lazy component CSS must not load before its import');
458
+ await import(`${pathToFileURL(join(publicDir, initial.result.entries.admin.entry)).href}?run=1`);
459
+ const browserStyles = (await Promise.all(loadedStyles.map((link) => readFile(fileURLToPath(link.href), 'utf8')))).join('\n');
460
+ assert.match(browserStyles, /admin-css-proof/);
461
+ assert.doesNotMatch(browserStyles, /admin-lazy-css-proof/);
462
+ const lazy = await globalThis.loadLazyFixture();
463
+ await globalThis.loadAdminLazyFixture();
464
+ const lazyStyles = (await Promise.all(loadedStyles.map((link) => readFile(fileURLToPath(link.href), 'utf8')))).join('\n');
465
+ assert.match(lazyStyles, /lazy-css-proof/);
466
+ assert.doesNotMatch(lazyStyles, /nested-css-proof/);
467
+ assert.match(lazyStyles, /admin-lazy-css-proof/);
468
+ await lazy.loadNested();
469
+ assert.equal(globalThis.nestedFixture, true);
470
+ const nestedStyles = (await Promise.all(loadedStyles.map((link) => readFile(fileURLToPath(link.href), 'utf8')))).join('\n');
471
+ assert.match(nestedStyles, /nested-css-proof/);
472
+ await globalThis.loadModuleFixture();
473
+ assert.equal(globalThis.moduleFixture.classes, globalThis.moduleFixture.named);
474
+ assert.equal(globalThis.moduleFixture.leaked, false, 'Imported CSS module classes must not be exported by the parent');
475
+ const moduleStyleFiles = new Set();
476
+ const moduleStyles = (await Promise.all(loadedStyles.map((link) => readStylesheetGraph(fileURLToPath(link.href), moduleStyleFiles)))).join('\n');
477
+ assert.match(moduleStyles, /@layer\s+reset\s*,\s*theme\s*,\s*imported\s*;\s*@import\s+["'][^"']+["']\s+layer\(theme\)/, 'Layer order must precede imported styles');
478
+ assert.match(moduleStyles, /\.px-4\b/, 'Tailwind utilities must remain global');
479
+ assert.match(moduleStyles, /@import\s+["'][^"']+["']\s+layer\(imported\)/, 'CSS import layer conditions must be preserved');
480
+ assert.match(moduleStyles, /\?v=1#test/, 'CSS import query and fragment must be preserved');
481
+ assert.match(moduleStyles, /\.global-import-proof\b/, 'Imported global CSS must remain global');
482
+ assert.match(moduleStyles, /\.global-nested-proof\b/, 'Nested imported global CSS must remain global');
483
+ const image = moduleStyles.match(/url\(["']?(\.\/[^"')]+\.svg\?v=3#mark)/)?.[1];
484
+ assert.ok(image, 'CSS asset URL must preserve its query and fragment');
485
+ const imageStylesheet = (await Promise.all([...moduleStyleFiles].map(async (path) => ({ path, css: await readFile(path, 'utf8') })))).find(({ css }) => css.includes(image));
486
+ assert.ok(imageStylesheet, 'The image URL must belong to a published stylesheet');
487
+ assert.match(await readFile(fileURLToPath(new URL(image, pathToFileURL(imageStylesheet.path))), 'utf8'), /<svg/);
488
+ assert.doesNotMatch(moduleStyles, /\.shared\s*\{/, 'Nested CSS modules must not become global');
489
+ assert.ok(moduleStyles.includes(`.${globalThis.moduleFixture.imported}`), 'Imported CSS module must retain its own scope');
490
+ const moduleNames = globalThis.moduleFixture.classes.split(' ');
491
+ assert.equal(moduleNames.length, 3);
492
+ for (const name of moduleNames) assert.ok(moduleStyles.includes(`.${name}`), `CSS module selector missing: ${name}`);
493
+ assert.match(moduleStyles, /display\s*:\s*flex/);
494
+ await import(`${pathToFileURL(join(publicDir, manifest['applicationBlocksEditor.js'].split('/public/')[1])).href}?run=1`);
495
+ const expectedWorker = `https://example.test${first.publicPrefix}editor/editor-assets/image-analysis-worker-fixture.js`;
496
+ assert.equal(globalThis.frontendFixture.startWorker().url, expectedWorker);
497
+ assert.equal(globalThis.adminFixture.startWorker().url, expectedWorker);
498
+ const editorWorker = globalThis.editorFixture.startWorker().url;
499
+ assert.equal(editorWorker, expectedWorker);
500
+ await access(join(publicDir, 'editor/editor-assets/image-analysis-worker-fixture.js'));
501
+ const firstVersion = globalThis.frontendFixture.version;
502
+ assert.equal(globalThis.adminFixture.version, firstVersion);
503
+ assert.equal(globalThis.editorFixture.version, firstVersion);
504
+
505
+ const rebuilt = await first.build.build({ quiet: true });
506
+ await remapModuleImports(publicDir, first.publicPrefix);
507
+ await import(`${pathToFileURL(join(publicDir, rebuilt.result.entries.frontend.entry)).href}?run=2`);
508
+ assert.equal(globalThis.frontendFixture.version, firstVersion);
509
+
510
+ const second = await makeTheme('second');
511
+ const other = await second.build.build({ quiet: true });
512
+ await remapModuleImports(join(second.root, 'public'), second.publicPrefix);
513
+ await import(pathToFileURL(join(second.root, 'public', other.result.entries.frontend.entry)).href);
514
+ assert.notEqual(globalThis.frontendFixture.version, firstVersion);
515
+
516
+ const structured = await makeTheme('structured', 'unified');
517
+ const structuredResult = await structured.build.build({ quiet: true });
518
+ const structuredPublic = join(structured.root, 'public');
519
+ const structuredManifest = JSON.parse(await readFile(join(structuredPublic, 'manifest.json'), 'utf8'));
520
+ await remapModuleImports(structuredPublic, structured.publicPrefix);
521
+ const structuredStylesStart = loadedStyles.length;
522
+ await import(pathToFileURL(join(structuredPublic, structuredResult.result.entries.frontend.entry)).href);
523
+ const structuredWorker = `https://example.test${structured.publicPrefix}editor/editor-assets/image-analysis-worker-fixture.js`;
524
+ assert.equal(globalThis.frontendFixture.startWorker().url, structuredWorker);
525
+ await import(pathToFileURL(join(structuredPublic, structuredResult.result.entries.admin.entry)).href);
526
+ assert.equal(globalThis.adminFixture.startWorker().url, structuredWorker);
527
+ let structuredStyles = (await Promise.all(loadedStyles.slice(structuredStylesStart).map((link) => readStylesheetGraph(fileURLToPath(link.href))))).join('\n');
528
+ assert.match(structuredStyles, /static-css-proof/);
529
+ assert.doesNotMatch(structuredStyles, /lazy-css-proof/);
530
+ await globalThis.loadLazyFixture();
531
+ structuredStyles = (await Promise.all(loadedStyles.slice(structuredStylesStart).map((link) => readStylesheetGraph(fileURLToPath(link.href))))).join('\n');
532
+ assert.match(structuredStyles, /lazy-css-proof/);
533
+ await globalThis.loadModuleFixture();
534
+ structuredStyles = (await Promise.all(loadedStyles.slice(structuredStylesStart).map((link) => readStylesheetGraph(fileURLToPath(link.href))))).join('\n');
535
+ assert.ok(structuredStyles.includes(`.${globalThis.moduleFixture.imported}`));
536
+ const structuredEditor = structuredManifest['applicationBlocksEditor.js'].slice(structured.publicPrefix.length);
537
+ await import(pathToFileURL(join(structuredPublic, structuredEditor)).href);
538
+ assert.equal(globalThis.editorFixture.startWorker().url, structuredWorker);
539
+ await access(join(structuredPublic, 'editor', 'editor-assets', 'image-analysis-worker-fixture.js'));
540
+
541
+ for (const sharing of ['independent', 'native']) {
542
+ const classicStructured = await makeTheme(`structured-${sharing}`, sharing);
543
+ await writeFile(join(classicStructured.root, 'src', 'editor-lazy.js'), 'export const value = "lazy editor loaded";');
544
+ await writeFile(join(classicStructured.root, 'src', 'editor.js'), `${await readFile(join(classicStructured.root, 'src', 'editor.js'), 'utf8')}\nglobalThis.loadEditorFixture = () => import("./editor-lazy.js");`);
545
+ await classicStructured.build.build({ quiet: true, sourcemaps: true });
546
+ const classicPublic = join(classicStructured.root, 'public');
547
+ const classicManifest = JSON.parse(await readFile(join(classicPublic, 'manifest.json'), 'utf8'));
548
+ const classicPath = classicManifest['applicationBlocksEditor.js'].slice(classicStructured.publicPrefix.length);
549
+ const classicScript = await readFile(join(classicPublic, classicPath), 'utf8');
550
+ const sourceMap = classicScript.match(/\/\/# sourceMappingURL=([^\r\n]+)/)?.[1];
551
+ assert.ok(sourceMap);
552
+ await access(fileURLToPath(new URL(sourceMap, pathToFileURL(join(classicPublic, classicPath)))));
553
+ globalThis.document.currentScript = { src: `https://example.test${classicManifest['applicationBlocksEditor.js']}` };
554
+ new Function(classicScript)();
555
+ globalThis.document.currentScript = { src: pathToFileURL(join(classicPublic, classicPath)).href };
556
+ new Function(classicScript)();
557
+ assert.equal((await globalThis.loadEditorFixture()).value, 'lazy editor loaded');
558
+ assert.equal(globalThis.editorFixture.startWorker().url, `https://example.test${classicStructured.publicPrefix}editor/editor-assets/image-analysis-worker-fixture.js`);
559
+ }
560
+
561
+ const classic = await makeTheme('classic', 'independent');
562
+ await classic.build.build({ quiet: true });
563
+ const classicPublic = join(classic.root, 'public');
564
+ const classicManifest = JSON.parse(await readFile(join(classicPublic, 'manifest.json'), 'utf8'));
565
+ const classicEntry = await readFile(join(classicPublic, classicManifest['applicationBlocksEditor.js'].split('/public/')[1]), 'utf8');
566
+ globalThis.document.currentScript = { src: `https://example.test${classic.publicPrefix}editor.js` };
567
+ new Function(classicEntry)();
568
+ assert.equal(globalThis.editorFixture.startWorker().url, `https://example.test${classic.publicPrefix}editor/editor-assets/image-analysis-worker-fixture.js`);
569
+
570
+ await checkCustomSsrOutput();
571
+ await checkLowLevelBuild();
572
+ await checkInvalidCssFailsSafely('composition');
573
+ await checkInvalidCssFailsSafely('cycle');
574
+ await checkInvalidCssFailsSafely('css-cycle');
575
+ await checkInvalidCssFailsSafely('tailwind-entry');
576
+ await checkInvalidCssFailsSafely('plugin');
577
+ await checkTailwindImports();
578
+ await checkConventionalStyleDedup();
579
+ await checkExplicitExtraCss();
580
+ await checkExplicitExtraCss('static');
581
+ await checkExplicitExtraCss('bypass');
582
+ await checkExplicitExtraCss('retry');
583
+ } finally {
584
+ await removeFixture(temporary);
585
+ }