@eightshift/frontend-libs-tailwind 4.0.0-beta.1 → 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 +10 -0
- package/README.md +92 -3
- package/bun/build.mjs +19 -3
- package/bun/editor-native.mjs +191 -0
- package/bun/editor-pure-jsx.mjs +381 -0
- package/bun/editor.mjs +120 -10
- package/bun/eightshift-discovery.mjs +14 -9
- package/bun/flat-publication.mjs +71 -3
- package/bun/media.mjs +3 -2
- package/bun/plugin-capabilities.mjs +11 -0
- package/bun/preset.mjs +5 -3
- package/bun/release.mjs +30 -5
- package/bun/theme-build.mjs +19 -2
- package/bun/watch.mjs +54 -1
- package/bun/wordpress.mjs +50 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -13,6 +13,16 @@ This projects adheres to [Semantic Versioning](https://semver.org/) and [Keep a
|
|
|
13
13
|
- **Breaking:** the conventional theme build requires a stable WordPress 7.0 or newer installation.
|
|
14
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
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.
|
|
16
26
|
|
|
17
27
|
## [3.5.0]
|
|
18
28
|
|
package/README.md
CHANGED
|
@@ -50,7 +50,7 @@ The conventional theme build requires a stable WordPress 7.0 or newer installati
|
|
|
50
50
|
|
|
51
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
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
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
56
|
|
|
@@ -101,12 +101,101 @@ 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
|
|
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
|
+
### 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
|
+
|
|
110
199
|
### Additional and lazy stylesheets
|
|
111
200
|
|
|
112
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:
|
|
@@ -134,7 +223,7 @@ The build regenerates discovery and CSS on each rebuild. Watch monitors the conf
|
|
|
134
223
|
|
|
135
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.
|
|
136
225
|
|
|
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.
|
|
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.
|
|
138
227
|
|
|
139
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`.
|
|
140
229
|
|
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
|
|
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 = {
|
|
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
|
-
|
|
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 };
|
|
@@ -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
|
+
}
|