@eightshift/frontend-libs-tailwind 3.5.0 → 4.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,24 @@ This projects adheres to [Semantic Versioning](https://semver.org/) and [Keep a
6
6
 
7
7
  ---
8
8
 
9
+ ## [4.0.0]
10
+
11
+ ### Changed
12
+
13
+ - **Breaking:** the conventional theme build requires a stable WordPress 7.0 or newer installation.
14
+ - **Breaking:** removed the Webpack configuration, `webpack/*` API and its build dependencies. Migrate project build scripts to Bun or another independently configured build pipeline.
15
+ - Bun build helpers include a conventional theme preset, CSS processing and watch support. They are not a drop-in replacement for Webpack: projects must verify their layout, WordPress integration and generated asset metadata. The Tailwind lint plugin still transitively requires `tsconfig-paths-webpack-plugin` for resolution, not the Webpack bundler.
16
+ - The conventional theme build defaults to Bun barrel optimization for `@eightshift/ui-components`; `optimizeImports` replaces the list, and `[]` disables the preset's explicit default.
17
+ - Improved flat-asset reference rewriting to avoid repeatedly scanning large generated bundles.
18
+ - Improved browser bundle tree-shaking and WordPress dependency metadata, with a conservative fallback when Bun's metafile cannot be read.
19
+ - Avoided repeated watch builds caused by unchanged directory events from Bun on macOS.
20
+ - Removed the experimental `editor.sharedPackages` vendor bridge in favor of independent builds and opt-in native/unified sharing. Configurations using the removed option fail explicitly.
21
+ - Added experimental `editor.sharing: 'native'` for one shared lazy ESM graph with content-hashed URLs, source maps and synchronous registration. It rejects inlined dynamic imports that cannot preserve native namespaces and remains disabled by default.
22
+
23
+ - Added experimental `editor.sharing: 'unified'` for one registration/lazy ESM graph with module metadata and an explicit readiness completion signal. Requires matching PHP integration; classic defaults and native-lazy sharing remain unchanged.
24
+ - Added opt-in `editor.pureJsxGroups: { maxBytes: 4096 }` for unified production builds: bounded, AST-proven dependency definitions share native chunks without co-loading application initialization. Custom transforms and source-map builds conservatively retain ungrouped output with a warning; default builds remain unchanged.
25
+ - Isolated native editor compilation in private staging so Bun versions ignoring `write: false` cannot publish discarded first-pass chunks; selected artifacts and source maps are materialized before cleanup.
26
+
9
27
  ## [3.5.0]
10
28
 
11
29
  ### Added
@@ -392,6 +410,7 @@ Co-authored with @piqusy
392
410
 
393
411
  - Initial release.
394
412
 
413
+ [4.0.0]: https://github.com/infinum/eightshift-frontend-libs-tailwind/compare/3.5.0...4.0.0
395
414
  [3.5.0]: https://github.com/infinum/eightshift-frontend-libs-tailwind/compare/3.4.0...3.5.0
396
415
  [3.4.0]: https://github.com/infinum/eightshift-frontend-libs-tailwind/compare/3.4.0...3.4.0
397
416
  [3.3.0]: https://github.com/infinum/eightshift-frontend-libs-tailwind/compare/3.2.0...3.3.0
package/README.md CHANGED
@@ -12,6 +12,237 @@ This library is meant to bring you the modern front-end development tools to the
12
12
  ## Documentation
13
13
  **For the full documentation please check this [link](https://eightshift.com).**
14
14
 
15
+ ## Bun build migration
16
+
17
+ The Webpack configuration and `webpack/*` imports have been removed. Projects must replace their Webpack configuration and scripts; this is a breaking change. The Bun helpers are available from `@eightshift/frontend-libs-tailwind/bun/build.mjs`, including `build`, `generateDiscovery`, `generateResponsiveClasses`, and `wordpressPlugin`.
18
+
19
+ The Bun helpers are not a drop-in replacement for Webpack. Start with the theme preset for the conventional Eightshift theme layout. Use the lower-level API below for other layouts.
20
+
21
+ The conventional theme build requires a stable WordPress 7.0 or newer installation. Each build reads `wp-includes/version.php` before modifying output and fails if the version is missing, unrecognized, or too old. By default, the WordPress root is three directories above the theme root; set `EIGHTSHIFT_WP_ROOT` to its absolute path for other layouts. The public asset URL defaults to the theme's path under that root plus `/public/`. If that does not match the site's URL layout, set `publicPrefix` in `defineThemeBuild` or `EIGHTSHIFT_PUBLIC_PREFIX` in the environment to the root-relative public URL path, including its trailing slash (for example, `/wp-content/themes/example/public/`). The option takes precedence over the environment variable. The lower-level build API does not enforce this version check.
22
+
23
+ ### Migrate a conventional theme
24
+
25
+ 1. Keep a working copy of your current build and compare its outputs before removing Webpack. Install a version of this library that contains the Bun build helpers, using Bun, and commit the updated lockfile when that version is available.
26
+ 2. Replace the Webpack configuration with `eightshift.build.mjs` at the project root:
27
+
28
+ ```js
29
+ import { defineThemeBuild } from '@eightshift/frontend-libs-tailwind/bun/theme-build.mjs';
30
+
31
+ export default defineThemeBuild({
32
+ root: import.meta.dirname,
33
+ });
34
+ ```
35
+
36
+ 3. Update the relevant `package.json` scripts:
37
+
38
+ ```json
39
+ {
40
+ "scripts": {
41
+ "start": "eightshift-build watch",
42
+ "build": "eightshift-build build",
43
+ "build:sourcemaps": "eightshift-build build --sourcemaps"
44
+ }
45
+ }
46
+ ```
47
+
48
+ 4. Run `bun run build` and compare the generated assets and site behavior with the previous build. Use `bun run start` for an initial build and subsequent rebuilds, or `bun run build:sourcemaps` for external source maps. The CLI accepts `--config path` to select another configuration. It is `eightshift-build`, not `bun build`: the library orchestrates CSS, discovery, WordPress dependencies and publication around Bun's bundler.
49
+ 5. Update CI and deployment to use Bun and the new scripts. Only remove Webpack dependencies and configuration after verifying the new build. Ensure the deployment environment has access to WordPress and its compatible script metadata for dependency extraction.
50
+
51
+ The default preset discovers conventional block and component assets, builds frontend, editor and admin scripts and styles, and builds conventional SSR entries when present. SVG imports in frontend and admin scripts emit files referenced by root-relative public URLs; editor SVG imports produce SVG text instead. The default build clears `public/` first, writes intermediate assets inside `public/.build`, and publishes the final assets and `public/manifest.json` directly to `public/`. Successful builds remove `public/.build`; failed builds can leave incomplete output. Do not keep manually maintained files in `public/`. Frontend and admin use classic-script bootstraps that dynamically import their bundled modules; the editor is packaged separately. Preserve the generated chunks alongside the entry scripts. The default preset always produces production-optimized assets, including in watch mode; watch does not provide hot reload. With `--sourcemaps`, external maps are generated for the editor entry and its lazy chunks as well as the browser bundles. SSR execution may still require Node in the project's PHP integration.
52
+
53
+ The manifest maps the conventional `applicationBlocksFrontend`, `applicationBlocksEditor` and `applicationAdmin` script and style keys to their generated files. Each entry also has `.asset.json` metadata containing WordPress dependency handles and a release version; the manifest maps its legacy `.json` key to that metadata as well. Browser entry metadata includes handles used by any emitted chunk, including lazy chunks. If Bun's build metadata is unavailable or cannot be read, the build conservatively includes all resolved handles instead; the editor also retains all resolved handles across its independently compiled chunks. **The build does not enqueue assets:** confirm that your installed PHP integration reads the generated metadata and merges its dependencies with the registered handles. Existing PHP/library versions may not support this; update or adapt them before switching, and check that the frontend, editor and admin load without missing globals. Do not assume Bun's `external` option supplies WordPress global mappings.
54
+
55
+ Each build clears the previous `public/` contents. Run only one build or publication per theme at a time; output directories are not locked against concurrent builds. The PHP manifest cache update is not coordinated with PHP cache rebuilds: if they overlap, stale asset URLs can remain until the next successful build or cache reset. Build failures may leave the site without working assets; use a separate deployment process if atomic releases are required, and account for cached pages that may still request removed files. Verify block registration, editor controls and save/reload behavior, frontend styles and lazy assets, representative admin screens, script dependencies, browser console and asset URLs. Keep the previous Webpack build available for rollback until the new build is verified.
56
+
57
+ ### Lower-level build API
58
+
59
+ For a nonstandard project, run the following as a project-root `build.mjs`, adapting the paths to your project:
60
+
61
+ ```js
62
+ import { join } from 'node:path';
63
+ import { build } from '@eightshift/frontend-libs-tailwind/bun/build.mjs';
64
+ import { processCss } from '@eightshift/frontend-libs-tailwind/bun/css.mjs';
65
+ import { watchBuild } from '@eightshift/frontend-libs-tailwind/bun/watch.mjs';
66
+
67
+ const root = process.cwd();
68
+ const production = process.argv.includes('--production');
69
+ const run = () => build({
70
+ root,
71
+ outdir: 'build',
72
+ entries: { app: 'src/app.js' },
73
+ wpRoot: '../../..', // WordPress root from wp-content/themes/<theme>
74
+ responsive: {},
75
+ css: async ({ outdir, responsive }) => {
76
+ await processCss({
77
+ projectDir: root,
78
+ outputFile: join(outdir, 'app.css'),
79
+ files: [{ file: 'src/tailwind.css', scan: true, scanFiles: [responsive.frontend] }],
80
+ production,
81
+ });
82
+ },
83
+ buildOptions: { minify: production },
84
+ });
85
+
86
+ if (process.argv.includes('--watch')) {
87
+ const watcher = watchBuild({
88
+ projectDir: root,
89
+ sources: ['src'],
90
+ ignored: ['build'],
91
+ build: run,
92
+ });
93
+ process.on('SIGINT', async () => { await watcher.stop(); process.exit(); });
94
+ process.on('SIGTERM', async () => { await watcher.stop(); process.exit(); });
95
+ } else {
96
+ await run();
97
+ }
98
+ ```
99
+
100
+ Run `bun run build.mjs`, add `--production` for minification, or `--watch` for an initial build followed by rebuilds. Watch covers only the listed paths, so include other inputs such as configuration files; generated output must be ignored. Directories are watched recursively, files through their parent directories, and missing sources through their nearest existing parents until they appear. Builds run serially with a 200 ms debounce; errors go to `onError` (default `console.error`). `initial: false` skips the initial build. `stop()` closes the watcher and waits for an active build. There is no development server or hot reload.
101
+
102
+ `build` requires named entries and an output directory. By default, it builds each entry separately as browser ESM with splitting and hashed filenames, writes `manifest.json` and an `<entry>/<entry>.asset.json` with dependencies and a version hash, and returns `{ outdir, entries }`. Integrate these files with your WordPress enqueue code; this package does not enqueue them. Output is staged and published only after success. An existing output directory must have the build's ownership marker, and output paths and trees cannot contain symlinks. Do not use a directory containing the project root. `buildOptions` can override Bun defaults such as `target`, `format`, `splitting`, `naming`, loaders and plugins; callers must ensure the resulting format matches their WordPress loading strategy. Entry points, output directory and write mode are controlled by the build API.
103
+
104
+ For projects that prefer a validated configuration, `createPreset` and `buildPreset` are exported from `@eightshift/frontend-libs-tailwind/bun/preset.mjs`. Pass `wordpress: false`, `discovery: false`, `responsive: false` or `css: false` to disable the corresponding feature; discovery, responsive generation and CSS are opt-in. Configure CSS surfaces or pass a custom CSS callback. `buildOptions` accepts the same overrides as `build`. When an editor entry is enabled, `buildOptions.sourcemap` supports only `none` and `external`. The default `editor.sharing: 'independent'` keeps synchronous registration and lazy entries in separate bundles. Its lazy editor URLs use a build-wide query version derived from the registration and lazy bundles; changing either invalidates all lazy URLs. The opt-in sharing modes below change graph layout, and unified mode also changes registration timing.
105
+
106
+ ### Native editor sharing (experimental, opt-in)
107
+
108
+ Set `editor.sharing: 'native'` to compile discovered lazy editor targets together with Bun's native ESM splitting. Registration remains a synchronous classic script. Lazy imports resolve directly to content-hashed ESM entries, without namespace facades or a custom module loader. Shared modules inside this lazy graph have one instance, shared live bindings and shared initialization; this deliberately differs from the duplicated state of independently bundled entries. The synchronous registration bundle remains separate and can still contain another instance. Different resolved package copies are not forcibly merged.
109
+
110
+ For the conventional theme preset, preserve the editor discovery configuration when overriding `editor`:
111
+
112
+ ```js
113
+ import { defineThemeBuild } from '@eightshift/frontend-libs-tailwind/bun/theme-build.mjs';
114
+
115
+ export default defineThemeBuild({
116
+ root: import.meta.dirname,
117
+ editor: {
118
+ entry: 'editor',
119
+ filename: 'applicationBlocksEditor.js',
120
+ sharing: 'native',
121
+ discovery: {
122
+ filter: /application-blocks-editor\.js$/,
123
+ omitContexts: ({ pattern }) => pattern.source === 'styles-editor.css$',
124
+ },
125
+ },
126
+ });
127
+ ```
128
+
129
+ Native sharing preserves nested lazy imports and emits source maps when requested. The classic entry is compiled again against final chunk URLs so its source map matches. Keep every emitted entry and shared chunk together; custom publishers must preserve their URLs and worker paths. Existing watch builds regenerate the graph when their watched inputs change.
130
+
131
+ This mode requires readable Bun entry metadata and rejects dynamic imports that Bun inlines into the current chunk: those can lose native module namespaces, and dynamic self-imports were observed to generate an undefined helper in Bun 1.4.4-canary.1. These cases fail the build rather than silently falling back to different semantics. Native output must remain JavaScript and source maps, as with the existing editor pipeline.
132
+
133
+ Native sharing can substantially reduce total output while increasing the number of files requested by the editor. It does **not** guarantee faster startup or Webpack parity. Validate cold and warm editor loads, first-block rendering, options, custom plugins, worker URLs and module state before enabling it. No theme is opted in automatically. Remove `sharing: 'native'` to restore independent chunks and rebuild; do not mix outputs from the two modes.
134
+
135
+ ### Unified editor graph (experimental, compatibility-changing)
136
+
137
+ `editor.sharing: 'unified'` builds registration and all lazy editor code in one native ESM graph. Unlike `native`, it can share dependency instances between registration and lazy consumers. It does **not** preserve synchronous classic-script registration. Keep it disabled until the matching Eightshift PHP module-readiness integration is installed and every dependent consumer has been checked.
138
+
139
+ Use the native-sharing configuration above with `sharing: 'unified'`. Do not provide `editor.lazy` rewriting options; unified mode lets Bun discover native imports. It keeps the same lazy-transform rejection rules as native mode. Its JavaScript wrapper statically imports the editor graph and signals completion through `globalThis.eightshiftEditorModules.complete(import.meta.url)`. Generated editor asset metadata declares `format: 'module'` and `readiness: 'eightshift-editor-v1'`; frontend/admin and existing editor modes retain their previous metadata. Older classic-only PHP integration is incompatible.
140
+
141
+ The shared PHP integration must establish `globalThis.eightshiftEditorModules.ready`, a map of promises keyed by the actual WordPress script handle, before emitting the parser-inserted `type="module"` entry. A dependent classic script must explicitly await its handle's promise:
142
+
143
+ ```js
144
+ const handle = 'my-theme-block-editor-scripts';
145
+ const ready = globalThis.eightshiftEditorModules?.ready.get(handle);
146
+ if (!ready) {
147
+ throw new Error(`No unified editor readiness contract for ${handle}`);
148
+ }
149
+ ready.then(() => {
150
+ // Initial registration is complete; use the registered blocks here.
151
+ }).catch((error) => {
152
+ console.error('Editor registration failed', error);
153
+ });
154
+ ```
155
+
156
+ Readiness means the registration entry finished evaluating, not that asynchronous sidebar/plugin initialization or every lazy block has finished. A promise does not make an unmodified classic dependent wait. Readiness and registration were checked in synthetic parser-inserted module pages and one authenticated WordPress post editor, including existing content rendering and an unsaved control change followed by undo and reload. This does not certify all editors or plugins, content saving, cross-browser support or deployment behavior. Hook editor JavaScript to `enqueue_block_editor_assets`, not the content iframe's `enqueue_block_assets`; shared content styles can remain on the latter.
157
+
158
+ Do not use `async`, a dynamic-import classic bootstrap, late script insertion, or top-level await in the initial registration graph. Initial registration must complete before `DOMContentLoaded`. Matching PHP integration rejects loading errors, an evaluation failure that fires a load event without completion, and missed readiness deadlines. Third-party script optimizers, CSP rules, translations, post/site editor initialization and save/reload need explicit verification before rollout. Do not replace WordPress boot functions or `wp.domReady` to hide ordering problems.
159
+
160
+ One graph reduces duplication but is not a guarantee of fewer requests or Webpack parity. The measured prototype still loaded more startup files than Webpack. Roll back by restoring the prior editor sharing setting and matching PHP/JavaScript artifacts together; do not activate a unified artifact as a classic script.
161
+
162
+ #### Opt-in bounded pure JSX groups
163
+
164
+ In unified mode only, set `editor.pureJsxGroups: { maxBytes: 4096 }` to co-load small, proven-pure dependency definitions. The default is `false`; `maxBytes` is a required integer from 1 to 65536 and bounds the combined original UTF-8 source bytes per group, not emitted or compressed bytes. This is not a giant vendor chunk or a modulepreload workaround.
165
+
166
+ The first native build identifies single-source dependency chunks and their minimum lazy depth from the **configured initial entries**, not every output marked `entryPoint`. A restricted AST proof accepts literals, arrays/objects and intrinsic-element `jsx`/`jsxs` calls from `react/jsx-runtime`; it rejects application initialization, component calls, arbitrary calls, getters, spreads, mutation and unsupported syntax. Members share a source directory, resolved JSX runtime identity and lazy depth, have distinct export names, and are grouped deterministically within the source budget. Only pure definitions may evaluate earlier; this does not pull unrelated application initialization forward.
167
+
168
+ A second native build compiles the original graph with bounded groups. Static named dependency imports/re-exports can target a group directly; namespace, star, bare and dynamic imports retain per-module native facades. Repeated imports share the same exported element instances. This preserves Bun's existing namespace behavior, not a promise that Bun's synthesized static namespace objects equal dynamic-import namespace objects. No generated import strings are patched; Bun generates final hashes, URLs and graph metadata. Native compilation uses a private sibling staging directory and materializes only the selected pass before cleanup, including on failure. This prevents Bun versions that write despite `write: false` from publishing discarded-pass chunks. `buildEditor()` reports the grouping plan (virtual source, original members, budget, lazy depth and runtime identity) in its optional `pureJsxGroups` result.
169
+
170
+ **Conservative fallbacks:** only production builds with `buildOptions.define['process.env.NODE_ENV']` set to `'"production"'` qualify. External source maps use the original ungrouped build with a warning: synthesized group source maps are not published. Custom Bun plugins/resolvers, discovery `transformSource`, and `buildOptions.alias` also disable grouping with a warning, so custom transforms are never bypassed. Audited built-in WordPress adapters, worker handling and default discovery are supported; trusted plugin identity is checked, not merely the plugin name. Unknown graph forms, changed sources, changed runtime resolution or a non-grouped source moving to an earlier lazy depth similarly keep the first native build. Existing native inlined-dynamic-import rejection remains in force.
171
+
172
+ In an isolated production-release comparison using Bun 1.4.4-canary.1, 4 KiB grouping reduced startup theme-JavaScript requests from 34 to 16 while increasing gzip bytes from 307108 to 309447. After rendering a CTA block, requests fell from 37 to 19 and gzip bytes increased from 388459 to 390798. Both variants registered 33 theme blocks and rendered three editable CTA fields without browser errors. These measurements used a synthetic editor page with the PHP readiness bootstrap and disabled browser cache; WordPress core assets are excluded. The same-source Webpack reference used 10 startup requests / 287529 gzip bytes and 12 requests / 366641 gzip bytes after the CTA. These results do **not** establish a repeatable latency improvement or Webpack parity. Measure your own editor and lazy interactions before opting in. Remove `pureJsxGroups` or set it to `false` and rebuild to roll back; independent and native-lazy modes remain unchanged.
173
+
174
+ The earlier `editor.sharedPackages` vendor-bridge experiment was removed. Existing experimental configurations must remove that option; it now fails configuration validation rather than silently changing initialization behavior. Use independent mode by default, or explicitly evaluate native/unified sharing with their compatibility requirements.
175
+
176
+ ### Theme build and watch integration
177
+
178
+ For `defineBuild` watch configurations with `ssr` or `publish` callbacks, explicitly set `watch.sources` or `watch.ignored`. Exclude every path those callbacks write inside the project root, including paths outside the preset output directory, to avoid rebuild loops.
179
+
180
+ `defineThemeBuild` from `bun/theme-build.mjs` supplies the conventional theme layout and flat publication. `entries` replaces the complete entry map; `editor` replaces the editor preset or may be `false`. `responsive` accepts the preset's options or `false`. `css` accepts an async callback receiving `{ root, outdir, stage, responsive, require }` or `false`; `extraCss` still runs afterwards. `discovery` accepts a plugin factory receiving `{ root, setEditorWorker, getEditorWorker }` (also async) or `false`; with either override, callers must provide discovery compatible with their entry sources. `frontendStyles` applies only to default discovery. The built-in editor worker plugin runs before plugins returned by `createPlugins`; replace it via `media.editorWorker` when custom handling is needed. The returned plugin array is not modified. `ssr` replaces `buildSsr` or can be `false`; do not specify both. `publish` replaces the flat publisher with an async callback receiving the build state, or `false` leaves the intermediate build unpublished in `public/.build`. With custom or disabled publication, the SSR callback runs after the browser build and receives the build state and `mode: 'production'`.
181
+
182
+ ### Optimizing package imports
183
+
184
+ `optimizeImports` is an array of package names passed to Bun's [barrel import optimization](https://bun.com/docs/bundler#optimizeimports) for frontend, editor (including lazy chunks), and admin JavaScript. It also applies in watch and source-map builds, but not to SSR or CSS processing. The conventional theme build defaults to `['@eightshift/ui-components']`. Supply an array to replace the default, or `[]` to disable the preset's explicit optimization:
185
+
186
+ ```js
187
+ import { defineThemeBuild } from '@eightshift/frontend-libs-tailwind/bun/theme-build.mjs';
188
+
189
+ export default defineThemeBuild({
190
+ root: import.meta.dirname,
191
+ optimizeImports: [], // Disable the preset's explicit package list.
192
+ });
193
+ ```
194
+
195
+ To retain UI Components and add another package, set `optimizeImports: ['@eightshift/ui-components', 'another-package']`.
196
+
197
+ Bun can skip unused re-exported modules when a package is listed. The default is tested with UI Components 8.4.0; verify compatibility when using other versions. Only list additional packages after checking that skipped modules have no required JavaScript initialization side effects; verify CSS imports, WordPress dependency handles, worker assets, and affected frontend, editor, and admin screens. An empty list disables the preset's explicit list, but Bun may still optimize packages that declare `sideEffects: false`. Namespace imports, star re-exports, and mixed barrels can limit the optimization. Results vary by package and Bun version; this option was introduced in Bun 1.3.10. It does not deduplicate separate editor bundles or guarantee smaller output.
198
+
199
+ ### Additional and lazy stylesheets
200
+
201
+ Use `extraCss` to compile ordered stylesheets separately from the standard frontend, editor and admin CSS. This is useful for a library used by only one frontend component:
202
+
203
+ ```js
204
+ import { defineThemeBuild } from '@eightshift/frontend-libs-tailwind/bun/theme-build.mjs';
205
+
206
+ export default defineThemeBuild({
207
+ root: import.meta.dirname,
208
+ extraCss: [{
209
+ files: ['package:@vidstack/react/player/styles/base.css'],
210
+ keys: ['components/video'],
211
+ }],
212
+ });
213
+ ```
214
+
215
+ - `files` is a non-empty array processed in order. Paths are relative to the project root; absolute paths and `package:` module specifiers are also supported. Each item may instead be a `processCss` options object with a `file` property.
216
+ - `output` is optional. By default the filename is `extra-<hash>.css`, using the first 20 hexadecimal characters of the SHA-256 hash of the compiled CSS bytes. Set `output: 'video.css'` for a stable filename. Names must be flat CSS filenames and must not collide with other outputs.
217
+ - `keys` optionally lists frontend importer keys, such as `components/video` or `custom/example`. Each must match a discovered `src/Blocks/{components,custom}/**/assets/index.js` file, and a key can belong to only one stylesheet group. When an importer is used, its stylesheet loads before the JavaScript; the load is shared between callers. A failed load rejects, removes the link, and can be retried. Without `keys`, the file is built and published but is not loaded automatically.
218
+ - `href` optionally overrides the URL used by those importers. By default it points to the generated output; custom URLs must be deployed and kept in sync by the project. It has no effect without `keys`.
219
+
220
+ The default flat publisher includes generated stylesheets in `public/` and its manifest; no alias is required for lazy loading. The output hash changes when compiled CSS changes, including rewritten asset URLs. CSS assets are copied with their own content-hashed names. Publication replaces `public/`, so cached older pages can request files no longer present; retain old releases externally if that matters. For a stable PHP manifest key, set an explicit `output` and an appropriate `aliases` entry. Custom publishers must preserve the CSS and the URL expected by the importer.
221
+
222
+ The build regenerates discovery and CSS on each rebuild. Watch monitors the configured project paths, not `node_modules` or arbitrary external files by default; customize `watch.sources` for additional inputs. Default theme builds use production CSS processing, including Lightning CSS minification and its browser targets, even in watch mode. `extraCss` may also be an async hook receiving `{ root, stage, require }`, or `false` to disable it. Hooks are responsible for their own filenames and loading behavior. `frontendStyles` separately attaches existing URLs to keys; both automatic mechanisms require default discovery.
223
+
224
+ Default flat publication requires frontend, admin and editor entries, an editor build, and CSS at the conventional filenames. It scans the conventional SSR source glob and expects matching outputs in `public/.build/ssr/production`; use `ssr: false` to omit SSR or supply custom publication for a different layout. Disabling responsive generation requires custom or disabled CSS. Custom publication is required when disabling CSS or the editor, or changing the entry set. With custom or disabled publication, intermediate output remains in `public/.build`; the project owns its publication and cleanup.
225
+
226
+ WordPress externalization is enabled by default. Set `wpRoot` to the WordPress installation when using externalized `@wordpress/*` imports; export discovery reads its core scripts and requires compatible installed package metadata. The adapter also maps React and selected common dependencies to WordPress globals. Those globals and script handles must be available at runtime. Set `wordpress: false` to disable this adapter. For direct Bun integration, `wordpressPlugin({ projectRoot, wpRoot })` returns `{ plugin, dependencies, getEmittedDependencies }`; use a fresh adapter for each build and absolute paths. `dependencies` contains all resolved handles. Request a Bun metafile and pass it to `getEmittedDependencies(metafile)` to derive handles from every emitted output; invalid metadata falls back to all resolved handles. Some Bun versions can throw when reading `result.metafile` itself, so catch that access and fall back to `dependencies` too.
227
+
228
+ `processCss` compiles the `files` array in order into one output file. Each item is a path or `{ file, scan, sources, scanFiles, removeSources }`: scanning is opt-in; `sources` adds Tailwind scanner source objects, `scanFiles` adds explicit candidate files, and `removeSources` removes exact source-rule strings (and fails if absent). Relative paths resolve from `projectDir`. Local URL assets are copied next to the CSS with content-hashed names. Production uses Lightning CSS and the `browsers` option (default `>= 0.25%`); the return value includes `outputFile` and discovered `dependencies`. Watch does not automatically use those dependencies. `responsive: {}` generates frontend and editor class lists from `src/**/manifest.json`, expanding responsive classes for `sm` and `md`; customize `breakpoints`, `manifestGlob`, and `output`. Pass the relevant generated list to CSS scanning, as above. The standalone `generateResponsiveClasses({ projectDir, ... })` is also exported from `bun/build.mjs`.
229
+
230
+ For Webpack context replacements, generate a module before building and import its named context in your application:
231
+
232
+ ```js
233
+ import { generateDiscovery } from '@eightshift/frontend-libs-tailwind/bun/build.mjs';
234
+
235
+ await generateDiscovery({
236
+ root: process.cwd(),
237
+ output: 'src/generated/blocks.mjs',
238
+ definitions: [{ name: 'blocks', directory: 'src/blocks', pattern: /\.js$/, mode: 'sync' }],
239
+ });
240
+ ```
241
+
242
+ The generated `blocks` function accepts keys such as `./card.js`, and `blocks.keys()` lists them. `mode: 'lazy'` returns promises; synchronous JSON returns parsed values, JS returns module namespaces, and synchronous CSS imports are side effects returning an empty object. Lazy CSS is unsupported. Missing directories produce empty contexts and symlinks are skipped. Regenerate when files are added or removed; if generated files are watched, exclude them to avoid rebuild loops. Alternatively, `build` accepts `discovery: { output, definitions }` and generates the module inside its staging output, exposed as `discovery` to the CSS callback; its output path must be relative to staging, not a stable source import path. Responsive outputs are likewise staged and published.
243
+
244
+ Verify your assets, WordPress dependencies, CSS and development workflow before migrating. The Tailwind lint plugin still transitively installs `tsconfig-paths-webpack-plugin` for module resolution; the Webpack bundler and former Webpack build plugins are not installed by this package.
245
+
15
246
  ## Tailwind class linting
16
247
 
17
248
  Two tools check classes against your project's own Tailwind entry: oxlint for JS, and `tw-sweep` for block manifests and PHP. Both read one ignore list.
package/bun/build.mjs ADDED
@@ -0,0 +1,357 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { lstat, mkdir, readFile, readdir, rename, rmdir, unlink, writeFile } from 'node:fs/promises';
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { generateDiscovery } from './discovery.mjs';
5
+ import { generateResponsiveClasses } from './responsive.mjs';
6
+ import { buildEditor } from './editor.mjs';
7
+ import { wordpressPlugin } from './wordpress.mjs';
8
+
9
+ const markerName = '.eightshift-bun-build';
10
+ const markerContents = 'eightshift-bun-build-v1\n';
11
+
12
+ async function rejectSymlinkPath(path, root) {
13
+ const boundary = root && resolve(root);
14
+ const location = boundary && relative(boundary, path);
15
+ const withinRoot = boundary && (!location || (!isAbsolute(location) && location !== '..' && !location.startsWith(`..${sep}`)));
16
+ const parent = dirname(path);
17
+
18
+ if (parent !== path && (!withinRoot || path !== boundary)) {
19
+ await rejectSymlinkPath(parent, root);
20
+ }
21
+
22
+ try {
23
+ if ((await lstat(path)).isSymbolicLink()) {
24
+ throw new Error(`Symlink is not allowed: ${path}`);
25
+ }
26
+ } catch (error) {
27
+ if (error.code !== 'ENOENT') {
28
+ throw error;
29
+ }
30
+ }
31
+ }
32
+
33
+ async function inspectTree(directory) {
34
+ for (const item of await readdir(directory, { withFileTypes: true })) {
35
+ const path = join(directory, item.name);
36
+ const info = await lstat(path);
37
+
38
+ if (info.isSymbolicLink()) {
39
+ throw new Error(`Symlink is not allowed: ${path}`);
40
+ }
41
+
42
+ if (info.isDirectory()) {
43
+ await inspectTree(path);
44
+ } else if (!info.isFile()) {
45
+ throw new Error(`Unsupported output type: ${path}`);
46
+ }
47
+ }
48
+ }
49
+
50
+ async function removeTree(directory) {
51
+ for (const item of await readdir(directory, { withFileTypes: true })) {
52
+ const path = join(directory, item.name);
53
+ const info = await lstat(path);
54
+
55
+ if (info.isDirectory() && !info.isSymbolicLink()) {
56
+ await removeTree(path);
57
+ } else {
58
+ await unlink(path);
59
+ }
60
+ }
61
+
62
+ await rmdir(directory);
63
+ }
64
+
65
+ export async function clearBuildDirectory(directory, root) {
66
+ await rejectSymlinkPath(resolve(directory), root);
67
+
68
+ try {
69
+ const info = await lstat(directory);
70
+ if (!info.isDirectory() || info.isSymbolicLink()) {
71
+ throw new Error(`Output must be a real directory: ${directory}`);
72
+ }
73
+ await inspectTree(directory);
74
+ await removeTree(directory);
75
+ } catch (error) {
76
+ if (error.code !== 'ENOENT') {
77
+ throw error;
78
+ }
79
+ }
80
+ }
81
+
82
+ async function assertOwned(directory) {
83
+ let info;
84
+
85
+ try {
86
+ info = await lstat(directory);
87
+ } catch (error) {
88
+ if (error.code === 'ENOENT') {
89
+ return false;
90
+ }
91
+
92
+ throw error;
93
+ }
94
+
95
+ if (!info.isDirectory() || info.isSymbolicLink()) {
96
+ throw new Error(`Output must be a real directory: ${directory}`);
97
+ }
98
+
99
+ const marker = join(directory, markerName);
100
+ let markerInfo;
101
+
102
+ try {
103
+ markerInfo = await lstat(marker);
104
+ } catch (error) {
105
+ if (error.code === 'ENOENT') {
106
+ throw new Error(`Refusing to replace unowned output: ${directory}`);
107
+ }
108
+
109
+ throw error;
110
+ }
111
+
112
+ if (!markerInfo.isFile() || markerInfo.isSymbolicLink() || (await readFile(marker, 'utf8')) !== markerContents) {
113
+ throw new Error(`Refusing to replace unowned output: ${directory}`);
114
+ }
115
+
116
+ await inspectTree(directory);
117
+
118
+ return true;
119
+ }
120
+
121
+ /**
122
+ * Build independent browser ESM entries into a staged directory.
123
+ *
124
+ * entries maps logical names to source paths relative to root. Each entry gets
125
+ * its own directory, chunks and .asset.json, so dependencies include its lazy
126
+ * graph without leaking dependencies from other entries. Callers must load the
127
+ * entry as a module. discovery definitions generate a module at discovery.output
128
+ * relative to the staging directory. responsive options are passed to
129
+ * generateResponsiveClasses with outputs inside staging. css is an optional
130
+ * async callback receiving { root, outdir, discovery, responsive }; it may emit
131
+ * additional CSS/assets into staging. buildOptions can override target, format,
132
+ * splitting, naming, plugins, loaders and defines. Entry points, output directory
133
+ * and writing are controlled by this API to protect staged publication.
134
+ *
135
+ * editor selects classic registration with lazy ESM chunks by default;
136
+ * unified sharing uses module registration with explicit PHP readiness integration.
137
+ * Existing output is replaced only if it contains this API's ownership marker
138
+ * and every build and callback succeeds. Output trees must not contain symlinks.
139
+ * `direct: true` writes to a fresh output directory without staging or rollback.
140
+ * Generated discovery and responsive files are included in the published tree.
141
+ */
142
+ export async function build({ root = process.cwd(), outdir, entries, wpRoot, wordpress = true, discovery, responsive, css, editor, buildOptions = {}, direct = false } = {}) {
143
+ root = resolve(root);
144
+
145
+ if (typeof outdir !== 'string' || !outdir || !entries || typeof entries !== 'object' || Array.isArray(entries) || !Object.keys(entries).length) {
146
+ throw new TypeError('outdir and at least one named entry are required');
147
+ }
148
+
149
+ outdir = resolve(root, outdir);
150
+ const rootFromOutput = relative(outdir, root);
151
+
152
+ if (!rootFromOutput || (!isAbsolute(rootFromOutput) && rootFromOutput !== '..' && !rootFromOutput.startsWith(`..${sep}`))) {
153
+ throw new Error('outdir must not contain the project root');
154
+ }
155
+
156
+ await rejectSymlinkPath(outdir, root);
157
+ await assertOwned(outdir);
158
+
159
+ for (const [name, entry] of Object.entries(entries)) {
160
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(name) || typeof entry !== 'string' || !entry) {
161
+ throw new TypeError(`Invalid entry: ${name}`);
162
+ }
163
+ }
164
+
165
+ if (editor && (!editor.entry || !Object.hasOwn(entries, editor.entry))) {
166
+ throw new TypeError('editor.entry must name an entry');
167
+ }
168
+
169
+ if (css !== undefined && typeof css !== 'function') {
170
+ throw new TypeError('css must be a function');
171
+ }
172
+
173
+ const parent = dirname(outdir);
174
+
175
+ await mkdir(parent, { recursive: true });
176
+ const stage = direct ? outdir : join(parent, `.${basename(outdir)}-stage-${randomUUID()}`);
177
+ const backup = join(parent, `.${basename(outdir)}-backup-${randomUUID()}`);
178
+
179
+ await mkdir(stage);
180
+ let backedUp = false;
181
+ let published = false;
182
+
183
+ try {
184
+ const insideStage = (path) => {
185
+ if (typeof path !== 'string' || !path || isAbsolute(path)) {
186
+ throw new TypeError('Generated output paths must be relative to staging');
187
+ }
188
+
189
+ const file = resolve(stage, path);
190
+ const location = relative(stage, file);
191
+
192
+ if (!location || location === '..' || location.startsWith(`..${sep}`) || isAbsolute(location)) {
193
+ throw new Error(`Output escapes staging: ${path}`);
194
+ }
195
+
196
+ return file;
197
+ };
198
+ let generatedDiscovery;
199
+
200
+ if (discovery) {
201
+ generatedDiscovery = insideStage(discovery.output);
202
+ await generateDiscovery({ root, ...discovery, output: generatedDiscovery });
203
+ }
204
+
205
+ let generatedResponsive;
206
+
207
+ if (responsive) {
208
+ generatedResponsive = {
209
+ frontend: insideStage(responsive.output?.frontend ?? 'responsive/frontend.txt'),
210
+ editor: insideStage(responsive.output?.editor ?? 'responsive/editor.txt'),
211
+ };
212
+ await Promise.all(Object.values(generatedResponsive).map((file) => mkdir(dirname(file), { recursive: true })));
213
+ generateResponsiveClasses({ ...responsive, projectDir: root, output: generatedResponsive });
214
+ }
215
+
216
+ if (css) {
217
+ await css({ root, outdir: stage, discovery: generatedDiscovery, responsive: generatedResponsive });
218
+ }
219
+
220
+ await rejectSymlinkPath(stage, root);
221
+ await inspectTree(stage);
222
+ const manifest = {};
223
+
224
+ for (const [name, entry] of Object.entries(entries)) {
225
+ const directory = join(stage, name);
226
+ const wp = wordpress ? wordpressPlugin({ projectRoot: root, wpRoot: wpRoot && resolve(root, wpRoot) }) : undefined;
227
+
228
+ if (editor?.entry === name) {
229
+ const { entry: _entry, ...editorOptions } = editor;
230
+ const built = await buildEditor({ ...editorOptions, root, directory, entry, buildOptions, plugins: [...(buildOptions.plugins ?? []), ...(wp ? [wp.plugin] : [])] });
231
+
232
+ await inspectTree(stage);
233
+ const digest = createHash('sha256');
234
+
235
+ for (const path of built.paths.map((path) => relative(directory, path).replaceAll('\\', '/')).sort()) {
236
+ const bytes = await readFile(join(directory, path));
237
+
238
+ digest
239
+ .update(`${Buffer.byteLength(path)}:`)
240
+ .update(path)
241
+ .update(`${bytes.length}:`)
242
+ .update(bytes);
243
+ }
244
+
245
+ const metadata = {
246
+ dependencies: [...(wp?.dependencies ?? [])].sort(),
247
+ version: digest.digest('hex'),
248
+ ...(built.format === 'module' ? { format: built.format, readiness: built.readiness } : {}),
249
+ };
250
+
251
+ await writeFile(join(directory, `${name}.asset.json`), `${JSON.stringify(metadata, null, 2)}\n`);
252
+ manifest[name] = { entry: `${name}/${relative(directory, built.entry).replaceAll('\\', '/')}`, styles: [], ...metadata };
253
+ continue;
254
+ }
255
+
256
+ const result = await Bun.build({
257
+ target: 'browser',
258
+ format: 'esm',
259
+ splitting: true,
260
+ naming: { entry: '[name]-[hash].[ext]', chunk: 'chunks/[name]-[hash].[ext]', asset: 'assets/[name]-[hash].[ext]' },
261
+ ...buildOptions,
262
+ metafile: Boolean(wp) || buildOptions.metafile,
263
+ entrypoints: [resolve(root, entry)],
264
+ outdir: directory,
265
+ write: true,
266
+ plugins: [...(buildOptions.plugins ?? []), ...(wp ? [wp.plugin] : [])],
267
+ });
268
+
269
+ if (!result.success) {
270
+ throw new AggregateError(result.logs, `Bun build failed for ${name}`);
271
+ }
272
+
273
+ await rejectSymlinkPath(stage, root);
274
+ await inspectTree(stage);
275
+ const output = result.outputs.filter((item) => item.kind === 'entry-point');
276
+
277
+ if (output.length !== 1) {
278
+ throw new Error(`Expected one output for ${name}, got ${output.length}`);
279
+ }
280
+
281
+ const digest = createHash('sha256');
282
+ const files = result.outputs.map((item) => ({ item, path: relative(directory, item.path).replaceAll('\\', '/') })).sort((a, b) => a.path.localeCompare(b.path));
283
+
284
+ for (const { item, path } of files) {
285
+ if (!path || path.startsWith('../') || isAbsolute(path)) {
286
+ throw new Error(`Unexpected Bun output path: ${item.path}`);
287
+ }
288
+
289
+ const bytes = await readFile(item.path);
290
+
291
+ digest
292
+ .update(`${Buffer.byteLength(path)}:`)
293
+ .update(path)
294
+ .update(`${bytes.length}:`)
295
+ .update(bytes);
296
+ }
297
+
298
+ let dependencies = [...(wp?.dependencies ?? [])].sort();
299
+
300
+ if (wp) {
301
+ try {
302
+ dependencies = wp.getEmittedDependencies(result.metafile);
303
+ } catch {
304
+ // Some Bun versions throw while reading a malformed metafile.
305
+ }
306
+ }
307
+
308
+ const metadata = { dependencies, version: digest.digest('hex') };
309
+
310
+ await writeFile(join(directory, `${name}.asset.json`), `${JSON.stringify(metadata, null, 2)}\n`);
311
+ manifest[name] = { entry: `${name}/${relative(directory, output[0].path).replaceAll('\\', '/')}`, styles: files.filter(({ path }) => path.endsWith('.css')).map(({ path }) => `${name}/${path}`), ...metadata };
312
+ }
313
+
314
+ await inspectTree(stage);
315
+ await writeFile(join(stage, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
316
+ await writeFile(join(stage, markerName), markerContents, { flag: 'wx' });
317
+ if (direct) {
318
+ published = true;
319
+ return { outdir, entries: manifest };
320
+ }
321
+
322
+ await rejectSymlinkPath(outdir, root);
323
+
324
+ if (await assertOwned(outdir)) {
325
+ await rename(outdir, backup);
326
+ backedUp = true;
327
+ }
328
+
329
+ try {
330
+ await rename(stage, outdir);
331
+ published = true;
332
+ } catch (error) {
333
+ if (backedUp) {
334
+ await rename(backup, outdir);
335
+ backedUp = false;
336
+ }
337
+
338
+ throw error;
339
+ }
340
+
341
+ if (backedUp) {
342
+ try {
343
+ await removeTree(backup);
344
+ } catch (error) {
345
+ console.warn(`Build published, but backup cleanup failed at ${backup}:`, error);
346
+ }
347
+ }
348
+
349
+ return { outdir, entries: manifest };
350
+ } finally {
351
+ if (!published) {
352
+ await removeTree(stage);
353
+ }
354
+ }
355
+ }
356
+
357
+ export { generateDiscovery, generateResponsiveClasses, wordpressPlugin };