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

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
@@ -10,9 +10,19 @@ This projects adheres to [Semantic Versioning](https://semver.org/) and [Keep a
10
10
 
11
11
  ### Changed
12
12
 
13
+ - Show build/watch progress and total duration by default, with `--quiet` and `--verbose` output modes.
14
+ - Stage theme releases before replacing public assets, preserving the previous release on build or cache failures.
15
+ - Support extra publication files, manifest aliases and explicit file retention through the shared publisher.
16
+
13
17
  - **Breaking:** the conventional theme build requires a stable WordPress 7.0 or newer installation.
14
18
  - **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.
19
+ - Added Bun build helpers with a conventional theme preset, CSS processing and watch support. These are not a drop-in replacement for Webpack; project configuration and WordPress asset integration must be migrated.
20
+ - Enabled import optimization for `@eightshift/ui-components` by default in conventional theme builds.
21
+ - Improved browser bundle tree-shaking and WordPress dependency metadata.
22
+ - Prevented unnecessary watch rebuilds on macOS.
23
+ - Removed the experimental `editor.sharedPackages` option. Existing configurations must remove it or migrate to a supported sharing mode.
24
+ - Added opt-in editor sharing modes: `native` shares lazy-loaded modules while preserving synchronous registration; `unified` also shares registration code and requires matching PHP module-readiness integration. Independent builds remain the default.
25
+ - Added opt-in `editor.pureJsxGroups` to reduce chunk requests in unified production builds. Unsupported configurations, including source-map builds, fall back to ungrouped output.
16
26
 
17
27
  ## [3.5.0]
18
28
 
package/README.md CHANGED
@@ -45,14 +45,14 @@ The conventional theme build requires a stable WordPress 7.0 or newer installati
45
45
  }
46
46
  ```
47
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.
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. By default, builds log a short start message and total elapsed seconds on success. Use `--quiet` to suppress informational output while retaining warnings and errors, or `--verbose` for build stages and theme entry/dependency details. These flags are mutually exclusive. The obsolete `--timings` flag is rejected. Both modes work with `build` and `watch`; each rebuild gets its own timer. Completion is reported only after configured SSR and publication callbacks succeed, including staged theme publication. The theme publisher may also build SSR during its publication stage. Use `eightshift-build --help` for CLI options. Programmatic `defineBuild` and theme definitions accept `{ quiet: true }` or `{ verbose: true }` in `.build()` and `.watch()`; combining them or providing the removed `timings` option throws. Custom callbacks should use the invocation context’s `quiet` and `verbose` fields to control their own informational logging. It is `eightshift-build`, not `bun build`: the library orchestrates CSS, discovery, WordPress dependencies and publication around Bun's bundler.
49
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
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.
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 stages intermediate assets in `.bun-pilot/theme-build`, including SSR output in `.bun-pilot/theme-build/ssr/production`, and replaces `public/` with the packaged assets and manifest only after packaging succeeds. Build or packaging failures preserve the existing public assets. Successful builds remove the staging directory. Only custom or disabled publication uses `public/.build`; the project owns its publication and cleanup. 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
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. **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.
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
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.
55
+ Successful default publication replaces 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. Account for cached pages that may still request files removed by successful publication; retain old releases externally if needed. 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
56
 
57
57
  ### Lower-level build API
58
58
 
@@ -101,12 +101,142 @@ Run `bun run build.mjs`, add `--production` for minification, or `--watch` for a
101
101
 
102
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
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 editor entry and each lazy chunk are bundled separately: modules included in more than one bundle may initialize more than once and have separate state. Avoid relying on shared module identity or one-time side effects across those bundles.
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
105
177
 
106
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.
107
179
 
108
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'`.
109
181
 
182
+ ### Staged theme publication
183
+
184
+ Default theme builds now prepare assets outside `public`, then swap the validated
185
+ release into place. Build/package failures preserve the previous release; cache
186
+ update failures roll publication back. Custom `publish` hooks remain responsible
187
+ for their own publication and rollback.
188
+
189
+ Use `publication` to supply additional already-built files (for example Infobip
190
+ UTM scripts/fonts or Forms custom entry bundles) without replacing the publisher:
191
+
192
+ ```js
193
+ import { resolve } from 'node:path';
194
+ import { defineThemeBuild } from '@eightshift/frontend-libs-tailwind/bun/theme-build.mjs';
195
+
196
+ export default defineThemeBuild({
197
+ root: import.meta.dirname,
198
+ publication: async ({ root }) => ({
199
+ extraFiles: [
200
+ { source: resolve(root, 'build/utm.js'), destination: 'utm.js' },
201
+ { source: resolve(root, 'build/fonts'), destination: 'fonts' },
202
+ { source: resolve(root, 'build/forms.js'), destination: 'forms.js' },
203
+ ],
204
+ aliases: { 'utm.js': 'utm.js', 'forms.js': 'forms.js', 'font.woff2': 'fonts/font.woff2' },
205
+ retain: [],
206
+ }),
207
+ });
208
+ ```
209
+
210
+ Sources must exist before packaging; the hook can build them into `outdir`.
211
+ The hook may return `undefined` for no additions, or a non-array object. When
212
+ provided, `aliases` must be a non-null, non-array object and `extraFiles` must be
213
+ an array; invalid results throw a `TypeError` before packaging.
214
+ Paths are release-relative destinations; duplicate destinations fail rather than
215
+ silently overwrite. `packageFlatRelease` also accepts `extraFiles`, `retain` and
216
+ `previousPublic`. Retention is opt-in and names exact existing files, not globs or
217
+ filename heuristics. Retained files cannot collide with new outputs. Fixed names
218
+ are replaced on successful publication: they cannot preserve old browser sessions
219
+ like content-hashed filenames. Additional manifest generation and automatic
220
+ multi-release retention are not provided. Aliases join the primary manifest and
221
+ PHP asset cache; consumers needing separate manifests must use custom publication.
222
+
223
+ ### Optimizing package imports
224
+
225
+ `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:
226
+
227
+ ```js
228
+ import { defineThemeBuild } from '@eightshift/frontend-libs-tailwind/bun/theme-build.mjs';
229
+
230
+ export default defineThemeBuild({
231
+ root: import.meta.dirname,
232
+ optimizeImports: [], // Disable the preset's explicit package list.
233
+ });
234
+ ```
235
+
236
+ To retain UI Components and add another package, set `optimizeImports: ['@eightshift/ui-components', 'another-package']`.
237
+
238
+ 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.
239
+
110
240
  ### Additional and lazy stylesheets
111
241
 
112
242
  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:
@@ -132,9 +262,9 @@ The default flat publisher includes generated stylesheets in `public/` and its m
132
262
 
133
263
  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.
134
264
 
135
- 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.
265
+ 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 `.bun-pilot/theme-build/ssr/production`. With default publication, custom `ssr` (or legacy `buildSsr`) callbacks receive `{ root, mode: 'production', outdir }`, where `outdir` is the absolute path to that SSR output directory. Callbacks must finish writing `<name>.js` files there before resolving, where `<name>` is the directory containing each conventional `assets-ssr` directory; `packageFlatRelease` reads those files from the same directory. 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.
136
266
 
137
- 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 }`; use a fresh adapter for each build and absolute paths.
267
+ 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.
138
268
 
139
269
  `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`.
140
270
 
package/bun/build.mjs CHANGED
@@ -132,7 +132,8 @@ async function assertOwned(directory) {
132
132
  * splitting, naming, plugins, loaders and defines. Entry points, output directory
133
133
  * and writing are controlled by this API to protect staged publication.
134
134
  *
135
- * editor optionally selects a synchronous classic entry with lazy ESM chunks.
135
+ * editor selects classic registration with lazy ESM chunks by default;
136
+ * unified sharing uses module registration with explicit PHP readiness integration.
136
137
  * Existing output is replaced only if it contains this API's ownership marker
137
138
  * and every build and callback succeeds. Output trees must not contain symlinks.
138
139
  * `direct: true` writes to a fresh output directory without staging or rollback.
@@ -241,7 +242,11 @@ export async function build({ root = process.cwd(), outdir, entries, wpRoot, wor
241
242
  .update(bytes);
242
243
  }
243
244
 
244
- const metadata = { dependencies: [...(wp?.dependencies ?? [])].sort(), version: digest.digest('hex') };
245
+ const metadata = {
246
+ dependencies: [...(wp?.dependencies ?? [])].sort(),
247
+ version: digest.digest('hex'),
248
+ ...(built.format === 'module' ? { format: built.format, readiness: built.readiness } : {}),
249
+ };
245
250
 
246
251
  await writeFile(join(directory, `${name}.asset.json`), `${JSON.stringify(metadata, null, 2)}\n`);
247
252
  manifest[name] = { entry: `${name}/${relative(directory, built.entry).replaceAll('\\', '/')}`, styles: [], ...metadata };
@@ -254,6 +259,7 @@ export async function build({ root = process.cwd(), outdir, entries, wpRoot, wor
254
259
  splitting: true,
255
260
  naming: { entry: '[name]-[hash].[ext]', chunk: 'chunks/[name]-[hash].[ext]', asset: 'assets/[name]-[hash].[ext]' },
256
261
  ...buildOptions,
262
+ metafile: Boolean(wp) || buildOptions.metafile,
257
263
  entrypoints: [resolve(root, entry)],
258
264
  outdir: directory,
259
265
  write: true,
@@ -289,7 +295,17 @@ export async function build({ root = process.cwd(), outdir, entries, wpRoot, wor
289
295
  .update(bytes);
290
296
  }
291
297
 
292
- const metadata = { dependencies: [...(wp?.dependencies ?? [])].sort(), version: digest.digest('hex') };
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') };
293
309
 
294
310
  await writeFile(join(directory, `${name}.asset.json`), `${JSON.stringify(metadata, null, 2)}\n`);
295
311
  manifest[name] = { entry: `${name}/${relative(directory, output[0].path).replaceAll('\\', '/')}`, styles: files.filter(({ path }) => path.endsWith('.css')).map(({ path }) => `${name}/${path}`), ...metadata };
@@ -333,7 +349,13 @@ export async function build({ root = process.cwd(), outdir, entries, wpRoot, wor
333
349
  return { outdir, entries: manifest };
334
350
  } finally {
335
351
  if (!published) {
336
- await removeTree(stage);
352
+ try {
353
+ await removeTree(stage);
354
+ } catch (error) {
355
+ if (error.code !== 'ENOENT') {
356
+ console.warn(`Build staging cleanup failed at ${stage}:`, error);
357
+ }
358
+ }
337
359
  }
338
360
  }
339
361
  }
package/bun/cli.mjs CHANGED
@@ -26,8 +26,15 @@ if (!(process.env.NODE_PATH ?? '').split(delimiter).includes(projectModules)) {
26
26
  const args = process.argv.slice(2);
27
27
  const command = args.shift();
28
28
 
29
+ const usage = 'Usage: eightshift-build <build|watch> [--config path] [--sourcemaps] [--quiet | --verbose]';
30
+
31
+ if (command === '--help' || command === '-h' || args.includes('--help') || args.includes('-h')) {
32
+ console.log(`${usage}\n --quiet Suppress informational output (warnings/errors remain).\n --verbose Show build stages and entry/dependency details.`);
33
+ process.exit(0);
34
+ }
35
+
29
36
  if (!['build', 'watch'].includes(command)) {
30
- throw new Error('Usage: eightshift-build <build|watch> [--config path] [--sourcemaps]');
37
+ throw new Error(usage);
31
38
  }
32
39
 
33
40
  let config = 'eightshift.build.mjs';
@@ -42,6 +49,8 @@ while (args.length) {
42
49
  if (!config || config.startsWith('--')) {
43
50
  throw new Error('--config requires a path');
44
51
  }
52
+ } else if (arg === '--verbose' || arg === '--quiet') {
53
+ options[arg.slice(2)] = true;
45
54
  } else if (arg === '--sourcemaps') {
46
55
  options.sourcemaps = true;
47
56
  } else {
@@ -49,6 +58,10 @@ while (args.length) {
49
58
  }
50
59
  }
51
60
 
61
+ if (options.quiet && options.verbose) {
62
+ throw new Error('--quiet and --verbose cannot be combined');
63
+ }
64
+
52
65
  const { default: definition } = await import(pathToFileURL(resolve(config)).href);
53
66
 
54
67
  if (!definition || typeof definition.build !== 'function' || typeof definition.watch !== 'function') {
@@ -0,0 +1,191 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, readdir, rmdir, unlink } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
4
+ import { supportsPureJsxGrouping } from './plugin-capabilities.mjs';
5
+
6
+ const removePassDirectory = async (directory) => {
7
+ for (const item of await readdir(directory, { withFileTypes: true })) {
8
+ const path = resolve(directory, item.name);
9
+ if (item.isDirectory()) {
10
+ await removePassDirectory(path);
11
+ } else {
12
+ await unlink(path);
13
+ }
14
+ }
15
+ await rmdir(directory);
16
+ };
17
+
18
+ /** Build lazy targets together without replacing their native import namespaces. */
19
+ export async function buildNativeEditorChunks(options) {
20
+ const directory = resolve(options.directory);
21
+ await mkdir(dirname(directory), { recursive: true });
22
+ // Some Bun versions write outdir despite write:false. Never expose discarded passes.
23
+ const privateDirectory = resolve(dirname(directory), `.eightshift-native-${randomUUID()}`);
24
+ await mkdir(privateDirectory);
25
+ try {
26
+ const result = await compileNativeEditorChunks({ ...options, directory: privateDirectory, scriptDirectory: directory });
27
+ const mapPath = (path) => {
28
+ const location = relative(privateDirectory, path);
29
+ if (!location || isAbsolute(location) || location === '..' || location.startsWith(`..${sep}`)) {
30
+ throw new Error(`Native editor output escapes its private directory: ${path}`);
31
+ }
32
+ return resolve(directory, location);
33
+ };
34
+ const outputs = [];
35
+ const byPath = new Map();
36
+ for (const output of result.outputs) {
37
+ // Materialize before cleanup: a BuildArtifact may be backed by its emitted file.
38
+ const bytes = await output.arrayBuffer();
39
+ const artifact = new Blob([bytes], { type: output.type });
40
+ Object.assign(artifact, { path: mapPath(output.path), kind: output.kind, loader: output.loader, hash: output.hash });
41
+ outputs.push(artifact);
42
+ byPath.set(output.path, artifact);
43
+ }
44
+ for (const [index, output] of result.outputs.entries()) {
45
+ if (output.sourcemap) {
46
+ const map = byPath.get(output.sourcemap.path);
47
+ if (!map) {
48
+ throw new Error('Missing native editor source map artifact');
49
+ }
50
+ outputs[index].sourcemap = map;
51
+ }
52
+ }
53
+ const metafile = {
54
+ ...result.metafile,
55
+ outputs: Object.fromEntries(Object.entries(result.metafile.outputs).map(([path, info]) => [mapPath(resolve(privateDirectory, path)), { ...info, imports: info.imports?.map((item) => ({ ...item, path: isAbsolute(item.path) && !item.external ? mapPath(item.path) : item.path })) }])),
56
+ };
57
+ return { ...result, outputs, metafile };
58
+ } finally {
59
+ await removePassDirectory(privateDirectory);
60
+ }
61
+ }
62
+
63
+ async function compileNativeEditorChunks({ chunks, directory, scriptDirectory, entryOutput, scriptUrlIdentifier, buildOptions, plugins, pureJsxGroups = false }) {
64
+ let entryPath = relative(scriptDirectory, entryOutput).split(sep).join('/');
65
+ if (!entryPath.startsWith('.')) {
66
+ entryPath = `./${entryPath}`;
67
+ }
68
+
69
+ const options = {
70
+ target: 'browser',
71
+ ...buildOptions,
72
+ entrypoints: [...chunks.keys()],
73
+ outdir: directory,
74
+ format: 'esm',
75
+ splitting: true,
76
+ write: false,
77
+ metafile: true,
78
+ publicPath: '',
79
+ naming: { entry: 'editor-lazy-[name]-[hash].[ext]', chunk: 'editor-shared-[hash].[ext]', asset: 'editor-asset-[hash].[ext]' },
80
+ banner: `const ${scriptUrlIdentifier} = new URL(${JSON.stringify(entryPath)}, import.meta.url).href;\n${buildOptions.banner ?? ''}`,
81
+ plugins,
82
+ };
83
+ let result = await Bun.build(options);
84
+
85
+ if (!result.success) {
86
+ throw new AggregateError(result.logs, 'Native editor sharing build failed');
87
+ }
88
+
89
+ const readMetadata = (build) => {
90
+ let metadata;
91
+ try {
92
+ metadata = typeof build.metafile === 'string' ? JSON.parse(build.metafile) : build.metafile;
93
+ if (!metadata?.outputs || typeof metadata.outputs !== 'object') {
94
+ throw new Error('Missing output metadata');
95
+ }
96
+ } catch (cause) {
97
+ throw new Error('Cannot map native editor entries: Bun returned unreadable build metadata', { cause });
98
+ }
99
+ if (!metadata.inputs || typeof metadata.inputs !== 'object') {
100
+ throw new Error('Cannot verify native editor dynamic imports: missing input metadata');
101
+ }
102
+ for (const [source, info] of Object.entries(metadata.inputs)) {
103
+ if (!Array.isArray(info?.imports)) {
104
+ throw new Error(`Cannot verify native editor dynamic imports in ${source}`);
105
+ }
106
+ // Inlined dynamic imports can return plain objects or broken self-import helpers.
107
+ for (const imported of info.imports) {
108
+ if (imported.kind === 'dynamic-import' && !imported.external) {
109
+ throw new Error(`Native editor sharing cannot preserve an inlined dynamic import in ${source}: ${imported.original ?? imported.path}`);
110
+ }
111
+ }
112
+ }
113
+ return metadata;
114
+ };
115
+ let metadata = readMetadata(result);
116
+ let grouping;
117
+ if (pureJsxGroups) {
118
+ let reason;
119
+ if (options.sourcemap && options.sourcemap !== 'none') {
120
+ reason = 'source maps require original ungrouped sources';
121
+ } else if (plugins.some((plugin) => !supportsPureJsxGrouping(plugin))) {
122
+ reason = 'custom plugins/transforms are not supported';
123
+ } else if (buildOptions.alias && Object.keys(buildOptions.alias).length) {
124
+ reason = 'custom resolution aliases are not supported';
125
+ } else if (buildOptions.define?.['process.env.NODE_ENV'] !== '"production"') {
126
+ reason = 'only the standard production JSX runtime is supported';
127
+ }
128
+ if (!reason) {
129
+ try {
130
+ const { createPureJsxGroups } = await import('./editor-pure-jsx.mjs');
131
+ const plan = await createPureJsxGroups({ result, metadata, directory, entries: chunks, maxBytes: pureJsxGroups.maxBytes });
132
+ grouping = plan.summary;
133
+ if (plan.groups.length) {
134
+ const grouped = await Bun.build({ ...options, plugins: [plan.plugin, ...plugins] });
135
+ if (!grouped.success) {
136
+ throw new AggregateError(grouped.logs, 'Grouped native editor compilation failed');
137
+ }
138
+ const groupedMetadata = readMetadata(grouped);
139
+ await plan.verify(groupedMetadata, grouped);
140
+ result = grouped;
141
+ metadata = groupedMetadata;
142
+ }
143
+ } catch (error) {
144
+ reason = error.message;
145
+ }
146
+ }
147
+ if (reason) {
148
+ console.warn(`[eightshift] Pure JSX grouping disabled: ${reason}. Using the ungrouped native build.`);
149
+ grouping = { maxBytes: pureJsxGroups.maxBytes, groups: [], disabled: reason };
150
+ }
151
+ }
152
+
153
+ const outputPaths = new Set();
154
+ for (const output of result.outputs) {
155
+ const location = relative(directory, output.path);
156
+ if (!location || isAbsolute(location) || location === '..' || location.startsWith(`..${sep}`)) {
157
+ throw new Error(`Native editor output escapes its directory: ${output.path}`);
158
+ }
159
+ if (!['entry-point', 'chunk', 'sourcemap'].includes(output.kind) || !/\.js(?:\.map)?$/.test(location)) {
160
+ throw new Error(`Unexpected native editor asset: ${output.path}`);
161
+ }
162
+ if (outputPaths.has(output.path)) {
163
+ throw new Error(`Duplicate native editor output: ${output.path}`);
164
+ }
165
+ outputPaths.add(output.path);
166
+ }
167
+
168
+ const names = new Map();
169
+ const entries = new Set();
170
+ for (const [file, info] of Object.entries(metadata.outputs)) {
171
+ if (!info.entryPoint) {
172
+ continue;
173
+ }
174
+ const target = resolve(info.entryPoint);
175
+ if (!chunks.has(target)) {
176
+ continue;
177
+ }
178
+ const output = resolve(directory, file);
179
+ if (!outputPaths.has(output) || entries.has(output)) {
180
+ throw new Error(`Missing or ambiguous native editor entry: ${target}`);
181
+ }
182
+ entries.add(output);
183
+ names.set(target, relative(directory, output).split(sep).join('/'));
184
+ }
185
+
186
+ if (names.size !== chunks.size) {
187
+ throw new Error(`Expected ${chunks.size} native editor entries, found ${names.size}`);
188
+ }
189
+
190
+ return { names, outputs: result.outputs, metafile: metadata, ...(grouping ? { pureJsxGroups: grouping } : {}) };
191
+ }