@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.
@@ -50,7 +50,7 @@ export async function flattenAssets({ outdir, flatDir, directories = ['frontend'
50
50
  targetsByName.set(name, targets);
51
51
  }
52
52
  const unusualTargets = [...targetsByName].filter(([name]) => !/^[\w.@+-]+$/.test(name)).flatMap(([, targets]) => targets);
53
- const rewrite = (input, path) => {
53
+ const rewriteLegacy = (input, path) => {
54
54
  let source = input;
55
55
  const candidates = new Set(unusualTargets);
56
56
 
@@ -80,6 +80,8 @@ export async function flattenAssets({ outdir, flatDir, directories = ['frontend'
80
80
  for (const value of variants) {
81
81
  for (const quote of ['"', "'"]) {
82
82
  source = source.replaceAll(`${quote}${value}${quote}`, `${quote}./${basename(target)}${quote}`);
83
+ source = source.replaceAll(`${quote}${value}?`, `${quote}./${basename(target)}?`);
84
+ source = source.replaceAll(`${quote}${value}#`, `${quote}./${basename(target)}#`);
83
85
  }
84
86
 
85
87
  source = source.replaceAll(`sourceMappingURL=${value}`, `sourceMappingURL=./${basename(target)}`);
@@ -89,6 +91,66 @@ export async function flattenAssets({ outdir, flatDir, directories = ['frontend'
89
91
  return source;
90
92
  };
91
93
 
94
+ const referencePatterns = new Map();
95
+ const rewrite = (input, path) => {
96
+ // Keep the existing source-map comment handling for map-bearing files.
97
+ if (input.includes('sourceMappingURL=')) {
98
+ return rewriteLegacy(input, path);
99
+ }
100
+
101
+ const directory = posix.dirname(path);
102
+ const editorPath = path.startsWith('editor/');
103
+ const cacheKey = `${directory}:${editorPath}`;
104
+ let cached = referencePatterns.get(cacheKey);
105
+
106
+ if (!cached) {
107
+ const references = new Map();
108
+
109
+ for (const target of sources.keys()) {
110
+ const reference = posix.relative(directory, target);
111
+ if (!reference) {
112
+ continue;
113
+ }
114
+
115
+ const variants = [reference];
116
+ if (!reference.startsWith('.')) {
117
+ variants.push(`./${reference}`);
118
+ }
119
+ if (target.startsWith('editor/editor-assets/') || (target.startsWith('editor/') && editorPath)) {
120
+ variants.push(target.slice('editor/'.length));
121
+ }
122
+ for (const value of variants) {
123
+ references.set(value, `./${basename(target)}`);
124
+ }
125
+ }
126
+
127
+ const alternatives = [...references.keys()].map((value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|');
128
+ let pattern;
129
+ let fallback = alternatives.length > 200000;
130
+
131
+ if (alternatives && !fallback) {
132
+ try {
133
+ pattern = new RegExp(`(["'])(?:${alternatives})(?=\\1|[?#])`, 'g');
134
+ } catch (error) {
135
+ if (!(error instanceof SyntaxError)) {
136
+ throw error;
137
+ }
138
+ fallback = true;
139
+ }
140
+ }
141
+ cached = { references, pattern, fallback };
142
+ referencePatterns.set(cacheKey, cached);
143
+ }
144
+
145
+ if (cached.fallback) {
146
+ return rewriteLegacy(input, path);
147
+ }
148
+ if (!cached.pattern) {
149
+ return input;
150
+ }
151
+ return input.replace(cached.pattern, (match, quote) => `${quote}${cached.references.get(match.slice(1))}`);
152
+ };
153
+
92
154
  const contentFor = async (path) => {
93
155
  const content = await readFile(sources.get(path));
94
156
  return /\.(?:js|css|map)$/.test(basename(path)) ? Buffer.from(rewrite(content.toString(), path)) : content;
@@ -129,7 +191,7 @@ export async function flattenAssets({ outdir, flatDir, directories = ['frontend'
129
191
  }
130
192
 
131
193
  /** Package flattened files, optional SSR files and standalone assets. */
132
- export async function packageFlatRelease({ root, flatDir, entries, ssrDir, ssrNames = [], standaloneAssets = new Map(), aliases = {}, outputDirectory }) {
194
+ export async function packageFlatRelease({ root, flatDir, entries, ssrDir, ssrNames = [], standaloneAssets = new Map(), aliases = {}, outputDirectory, removeIntermediates = false }) {
133
195
  const files = [];
134
196
 
135
197
  for (const name of await readdir(flatDir)) {
@@ -155,7 +217,13 @@ export async function packageFlatRelease({ root, flatDir, entries, ssrDir, ssrNa
155
217
  extraAliases[name] = name;
156
218
  }
157
219
 
158
- return packageRelease({ root, files, entries, aliases: { ...extraAliases, ...aliases }, outputDirectory });
220
+ const omitted = removeIntermediates ? entries.flatMap((entry) => [entry.style, ...(entry.script !== undefined ? [entry.entry] : [])]) : [];
221
+ for (const entry of entries) {
222
+ if (entry.script === undefined && omitted.includes(entry.entry)) {
223
+ throw new Error(`Cannot omit a script bootstrap target: ${entry.entry}`);
224
+ }
225
+ }
226
+ return packageRelease({ root, files, entries, aliases: { ...extraAliases, ...aliases }, outputDirectory, omit: [...new Set(omitted)] });
159
227
  }
160
228
 
161
229
  /** Publish a flat release and synchronize an existing PHP asset cache.
package/bun/media.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { basename, dirname, resolve } from 'node:path';
3
+ import { allowPureJsxGrouping } from './plugin-capabilities.mjs';
3
4
 
4
5
  /**
5
6
  * Adapt the published UI Components smart-image worker for flat theme releases.
@@ -11,7 +12,7 @@ export function editorWorkerPlugin({ setEditorWorker, getEditorWorker }) {
11
12
  throw new TypeError('Worker callbacks are required');
12
13
  }
13
14
 
14
- return {
15
+ return allowPureJsxGrouping({
15
16
  name: 'eightshift-editor-worker-url',
16
17
  setup(builder) {
17
18
  builder.onLoad({ filter: /[/\\]smart-image[/\\]smart-image\.js$/ }, async ({ path }) => {
@@ -45,5 +46,5 @@ export function editorWorkerPlugin({ setEditorWorker, getEditorWorker }) {
45
46
  return { contents: source.replace(pattern, `new URL(${JSON.stringify(`editor-assets/${basename(worker)}`)}, ${base})`), loader: 'js', resolveDir: dirname(path) };
46
47
  });
47
48
  },
48
- };
49
+ });
49
50
  }
@@ -0,0 +1,11 @@
1
+ const pureJsxCompatible = new WeakMap();
2
+
3
+ // Only audited built-ins may participate; plugin names are not a trust boundary.
4
+ export function allowPureJsxGrouping(plugin) {
5
+ pureJsxCompatible.set(plugin, plugin.setup);
6
+ return plugin;
7
+ }
8
+
9
+ export function supportsPureJsxGrouping(plugin) {
10
+ return pureJsxCompatible.has(plugin) && pureJsxCompatible.get(plugin) === plugin.setup;
11
+ }
package/bun/preset.mjs CHANGED
@@ -31,8 +31,10 @@ const feature = (value, keys, label) => {
31
31
  * Set wordpress: false to bundle dependencies instead of externalizing them.
32
32
  * Configure Bun target, format, naming and splitting via buildOptions.
33
33
  * Entry points, staging output and write mode are controlled by build.
34
- * editor: { entry, filename, chunkDir, scriptUrlIdentifier, discovery, lazy }
35
- * makes the named entry a synchronous classic script with lazy ESM chunks.
34
+ * editor: { entry, filename, chunkDir, scriptUrlIdentifier, discovery, lazy, sharing, pureJsxGroups }
35
+ * builds classic registration with lazy ESM chunks by default.
36
+ * sharing: 'native' bundles lazy targets together; the default is 'independent'.
37
+ * sharing: 'unified' also moves registration to ESM and requires readiness integration.
36
38
  * discovery configures eightshiftDiscovery; lazy configures editorLazyImports.
37
39
  * Both are opt-in, and all filenames and discovery behavior are overridable.
38
40
  */
@@ -66,7 +68,7 @@ export function createPreset(options = {}) {
66
68
  }
67
69
  }
68
70
 
69
- const editor = feature(options.editor, ['entry', 'chunkDir', 'filename', 'scriptUrlIdentifier', 'discovery', 'lazy'], 'editor');
71
+ const editor = feature(options.editor, ['entry', 'chunkDir', 'filename', 'scriptUrlIdentifier', 'discovery', 'lazy', 'sharing', 'pureJsxGroups'], 'editor');
70
72
  const discovery = feature(options.discovery, ['output', 'definitions'], 'discovery');
71
73
  const responsive = feature(options.responsive, ['breakpoints', 'manifestGlob', 'output'], 'responsive');
72
74
 
package/bun/release.mjs CHANGED
@@ -39,13 +39,15 @@ const releasePath = (value) => {
39
39
  *
40
40
  * files: [{ source, destination }] copies files or directory trees.
41
41
  * entries: [{ name, entry, style, dependencies, script? }] generates the root
42
- * scripts and WordPress asset metadata. script supplies synchronous editor code;
42
+ * scripts and WordPress asset metadata. script supplies the entry wrapper code;
43
43
  * otherwise a dynamic-import bootstrap loads entry relative to the root script.
44
+ * Unified editor scripts declare format: 'module', readiness: 'eightshift-editor-v1';
45
+ * their static-import wrapper must be loaded by matching module-aware PHP integration.
44
46
  * aliases maps additional flat manifest keys to packaged paths.
45
47
  * Returns { release, version, manifest }. A failed staging directory is retained.
46
48
  * outputDirectory writes directly to an existing directory instead of staging.
47
49
  */
48
- export async function packageRelease({ root, files, entries, aliases = {}, outputDirectory }) {
50
+ export async function packageRelease({ root, files, entries, aliases = {}, outputDirectory, omit = [] }) {
49
51
  if (typeof root !== 'string' || !root || !Array.isArray(files) || !Array.isArray(entries) || !entries.length || !aliases || typeof aliases !== 'object' || Array.isArray(aliases)) {
50
52
  throw new TypeError('Expected root, files, entries and optional aliases');
51
53
  }
@@ -117,13 +119,23 @@ export async function packageRelease({ root, files, entries, aliases = {}, outpu
117
119
  throw new TypeError(`Invalid script for ${entry.name}`);
118
120
  }
119
121
 
122
+ if (entry.format !== undefined && entry.format !== 'module') {
123
+ throw new TypeError(`Unsupported script format for ${entry.name}`);
124
+ }
125
+ if (entry.format === 'module' && (entry.readiness !== 'eightshift-editor-v1' || entry.script === undefined)) {
126
+ throw new TypeError(`Module entry ${entry.name} requires an explicit script and readiness contract`);
127
+ }
128
+ if (entry.readiness !== undefined && entry.format !== 'module') {
129
+ throw new TypeError(`Readiness requires a module entry: ${entry.name}`);
130
+ }
131
+
120
132
  const script = entry.script ?? `(() => { const url = new URL(${JSON.stringify(target)}, document.currentScript.src); import(url.href).catch((error) => console.error(${JSON.stringify(`Failed to load ${entry.name}:`)}, error)); })();\n`;
121
133
 
122
134
  if (scripts.has(entry.name)) {
123
135
  throw new Error(`Duplicate entry: ${entry.name}`);
124
136
  }
125
137
 
126
- scripts.set(entry.name, { script, dependencies: entry.dependencies });
138
+ scripts.set(entry.name, { script, dependencies: entry.dependencies, ...(entry.format === 'module' ? { format: entry.format, readiness: entry.readiness } : {}) });
127
139
  const scriptName = `${entry.name}-${digest(script)}.js`;
128
140
  const styleBytes = contents.get(style);
129
141
  const styleName = `${entry.name}-${digest(styleBytes)}.css`;
@@ -151,12 +163,25 @@ export async function packageRelease({ root, files, entries, aliases = {}, outpu
151
163
  setManifest(key, value);
152
164
  }
153
165
 
166
+ if (!Array.isArray(omit)) {
167
+ throw new TypeError('omit must be an array');
168
+ }
169
+ for (const path of omit) {
170
+ releasePath(path);
171
+ if (Object.values(manifest).includes(path)) {
172
+ throw new Error(`Cannot omit manifest target: ${path}`);
173
+ }
174
+ if (!contents.delete(path)) {
175
+ throw new Error(`Cannot omit missing release file: ${path}`);
176
+ }
177
+ }
178
+
154
179
  const inventory = Object.fromEntries([...contents].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([path, bytes]) => [path, digest(bytes)]));
155
180
  const version = digest(JSON.stringify({ format: 1, inventory, scripts: [...scripts].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)), manifest }));
156
181
 
157
- for (const [name, { script, dependencies }] of scripts) {
182
+ for (const [name, { script, dependencies, format, readiness }] of scripts) {
158
183
  add(manifest[`${name}.js`], Buffer.from(script));
159
- add(`${name}.asset.json`, Buffer.from(`${JSON.stringify({ dependencies, version }, null, 2)}\n`));
184
+ add(`${name}.asset.json`, Buffer.from(`${JSON.stringify({ dependencies, version, ...(format === 'module' ? { format, readiness } : {}) }, null, 2)}\n`));
160
185
  }
161
186
 
162
187
  add('manifest.json', Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`));
@@ -8,6 +8,7 @@ import { generateThemeDiscovery, generateThemeImporters, themeDiscoveryPlugin }
8
8
  import { processEightshiftCss } from './eightshift-css.mjs';
9
9
  import { flattenAssets, packageFlatRelease, publishFlatRelease } from './flat-publication.mjs';
10
10
  import { editorWorkerPlugin } from './media.mjs';
11
+ import { allowPureJsxGrouping } from './plugin-capabilities.mjs';
11
12
  import { processCss } from './css.mjs';
12
13
  import { buildSsr as buildDefaultSsr } from './ssr.mjs';
13
14
 
@@ -16,6 +17,8 @@ import { buildSsr as buildDefaultSsr } from './ssr.mjs';
16
17
  * { files, output?, keys?, href? }; package files use the `package:` prefix.
17
18
  * Omitted output names use a content hash. Keys attach CSS to frontend importers.
18
19
  * SSR is built when conventional entries exist; ssr: false disables it.
20
+ * optimizeImports controls Bun's package barrel optimization for browser builds.
21
+ * UI Components is optimized by default; pass [] to disable the explicit default.
19
22
  * watch: false disables watching; an object overrides the safe watch defaults.
20
23
  */
21
24
  export function defineThemeBuild({
@@ -24,6 +27,7 @@ export function defineThemeBuild({
24
27
  buildSsr,
25
28
  createPlugins = () => [],
26
29
  frontendStyles = [],
30
+ optimizeImports = ['@eightshift/ui-components'],
27
31
  extraCss = async () => {},
28
32
  aliases = {},
29
33
  requireEditorWorker = false,
@@ -45,6 +49,10 @@ export function defineThemeBuild({
45
49
  throw new TypeError('createPlugins must be a function');
46
50
  }
47
51
 
52
+ if (!Array.isArray(optimizeImports) || optimizeImports.some((name) => typeof name !== 'string' || !name.trim())) {
53
+ throw new TypeError('optimizeImports must be an array of package names');
54
+ }
55
+
48
56
  if (extraCss !== false && typeof extraCss !== 'function' && !Array.isArray(extraCss)) {
49
57
  throw new TypeError('extraCss must be false, a function, or an array');
50
58
  }
@@ -251,7 +259,7 @@ export function defineThemeBuild({
251
259
  const plugins = workerFactory ? [workerFactory(pluginContext), ...callerPlugins] : [...callerPlugins];
252
260
 
253
261
  if (discovery === undefined) {
254
- plugins.push(discoveryPlugin);
262
+ plugins.push(allowPureJsxGrouping(discoveryPlugin));
255
263
  } else if (discovery) {
256
264
  const plugin = await discovery(pluginContext);
257
265
 
@@ -345,6 +353,7 @@ export function defineThemeBuild({
345
353
  }
346
354
  },
347
355
  buildOptions: {
356
+ optimizeImports,
348
357
  minify: true,
349
358
  publicPath,
350
359
  naming: { entry: '[name]-[hash].[ext]', chunk: '[name]-[hash].[ext]', asset: '[name]-[hash].[ext]' },
@@ -417,11 +426,19 @@ export function defineThemeBuild({
417
426
 
418
427
  console.log(`${surface}: ${entry.entry}; dependencies: ${entry.dependencies.join(', ') || 'none'}`);
419
428
 
420
- return { name, entry: surface === 'editor' ? 'editor-entry.js' : basename(entry.entry), style: `${name}.css`, dependencies: entry.dependencies, ...(script && { script }) };
429
+ return {
430
+ name,
431
+ entry: surface === 'editor' ? 'editor-entry.js' : basename(entry.entry),
432
+ style: `${name}.css`,
433
+ dependencies: entry.dependencies,
434
+ ...(script && { script }),
435
+ ...(entry.format === 'module' ? { format: entry.format, readiness: entry.readiness } : {}),
436
+ };
421
437
  });
422
438
  const { release, version, manifest } = await packageFlatRelease({
423
439
  root: resolve(root, 'public'),
424
440
  outputDirectory: resolve(root, 'public'),
441
+ removeIntermediates: true,
425
442
  flatDir,
426
443
  entries,
427
444
  ssrDir,
package/bun/watch.mjs CHANGED
@@ -41,6 +41,21 @@ export function watchBuild({ projectDir, sources, ignored = [], ignore = () => f
41
41
  let pending = false;
42
42
  let stopped = false;
43
43
  const watchers = new Map();
44
+ const directoryStamps = new Map();
45
+ const filterDirectoryEvents = process.platform === 'darwin' && typeof Bun !== 'undefined';
46
+ const directoryStamp = (path) => {
47
+ try {
48
+ const info = statSync(path);
49
+
50
+ return info.isDirectory() ? `${info.dev}:${info.ino}:${info.mode}:${info.mtimeMs}:${info.ctimeMs}` : undefined;
51
+ } catch (error) {
52
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') {
53
+ return undefined;
54
+ }
55
+
56
+ throw error;
57
+ }
58
+ };
44
59
 
45
60
  const report = (error) => {
46
61
  try {
@@ -146,6 +161,9 @@ export function watchBuild({ projectDir, sources, ignored = [], ignore = () => f
146
161
  }
147
162
  }
148
163
  if (current === input && info.isDirectory()) {
164
+ if (filterDirectoryEvents && !directoryStamps.has(input)) {
165
+ directoryStamps.set(input, directoryStamp(input));
166
+ }
149
167
  add(input, true);
150
168
  if (input !== root) {
151
169
  add(dirname(input), false, basename(input));
@@ -171,8 +189,43 @@ export function watchBuild({ projectDir, sources, ignored = [], ignore = () => f
171
189
  return;
172
190
  }
173
191
  const path = resolve(config.directory, name);
174
- onEvent(path);
175
192
  try {
193
+ // Bun on macOS can report unchanged watched directories as changes.
194
+ if (filterDirectoryEvents && _event === 'change') {
195
+ let directory;
196
+
197
+ if (!config.recursive && inputs.includes(path)) {
198
+ directory = path;
199
+ } else if (config.recursive && name === basename(config.directory)) {
200
+ try {
201
+ statSync(path);
202
+ } catch (error) {
203
+ if (error.code !== 'ENOENT') {
204
+ throw error;
205
+ }
206
+ directory = config.directory;
207
+ }
208
+ }
209
+
210
+ if (directory) {
211
+ const stamp = directoryStamp(directory);
212
+
213
+ if (stamp && directoryStamps.get(directory) === stamp) {
214
+ return;
215
+ }
216
+ if (stamp) {
217
+ directoryStamps.set(directory, stamp);
218
+ }
219
+ }
220
+ }
221
+ if (filterDirectoryEvents && config.recursive) {
222
+ const stamp = directoryStamp(config.directory);
223
+
224
+ if (stamp) {
225
+ directoryStamps.set(config.directory, stamp);
226
+ }
227
+ }
228
+ onEvent(path);
176
229
  refresh();
177
230
  } catch (error) {
178
231
  report(error);
package/bun/wordpress.mjs CHANGED
@@ -3,6 +3,7 @@ import { dirname, isAbsolute, resolve } from 'node:path';
3
3
  import { readFile } from 'node:fs/promises';
4
4
  import { promisify } from 'node:util';
5
5
  import { execFile } from 'node:child_process';
6
+ import { allowPureJsxGrouping } from './plugin-capabilities.mjs';
6
7
 
7
8
  const execFileAsync = promisify(execFile);
8
9
  const externals = {
@@ -80,13 +81,58 @@ export function wordpressPlugin({ projectRoot = process.cwd(), wpRoot } = {}) {
80
81
  const projectRequire = createRequire(resolve(projectRoot, 'package.json'));
81
82
  const dependencies = new Set();
82
83
  const modules = new Map();
84
+ const handles = new Map();
83
85
 
84
86
  return {
85
87
  dependencies,
86
- plugin: {
88
+ getEmittedDependencies(metafile) {
89
+ try {
90
+ const data = typeof metafile === 'string' ? JSON.parse(metafile) : metafile;
91
+ const outputs = Object.values(data?.outputs ?? {});
92
+
93
+ if (!outputs.length) {
94
+ return [...dependencies].sort();
95
+ }
96
+
97
+ const emitted = new Set();
98
+
99
+ for (const output of outputs) {
100
+ if (!output?.inputs || typeof output.inputs !== 'object') {
101
+ return [...dependencies].sort();
102
+ }
103
+
104
+ for (const [input, info] of Object.entries(output.inputs)) {
105
+ if (!input.startsWith('wordpress-global:')) {
106
+ continue;
107
+ }
108
+
109
+ if (typeof info?.bytesInOutput !== 'number') {
110
+ return [...dependencies].sort();
111
+ }
112
+
113
+ if (!info.bytesInOutput) {
114
+ continue;
115
+ }
116
+
117
+ const key = input.slice('wordpress-global:'.length);
118
+
119
+ if (!handles.has(key)) {
120
+ return [...dependencies].sort();
121
+ }
122
+
123
+ emitted.add(handles.get(key));
124
+ }
125
+ }
126
+
127
+ return [...emitted].sort();
128
+ } catch {
129
+ return [...dependencies].sort();
130
+ }
131
+ },
132
+ plugin: allowPureJsxGrouping({
87
133
  name: 'wordpress-globals',
88
134
  setup(build) {
89
- build.onResolve({ filter: /.*/ }, async (args) => {
135
+ build.onResolve({ filter: /^(?:moment|jquery|lodash|lodash-es|@babel\/runtime\/regenerator|react|react-dom)(?:$|\/)|^@wordpress\/|react-refresh\/runtime/ }, async (args) => {
90
136
  const request = args.path;
91
137
  const external = externalFor(request);
92
138
 
@@ -163,11 +209,12 @@ export function wordpressPlugin({ projectRoot = process.cwd(), wpRoot } = {}) {
163
209
  }
164
210
 
165
211
  dependencies.add(handle);
212
+ handles.set(key, handle);
166
213
 
167
214
  return { path: key, namespace: 'wordpress-global' };
168
215
  });
169
216
  build.onLoad({ filter: /.*/, namespace: 'wordpress-global' }, (args) => ({ contents: modules.get(args.path), loader: 'js' }));
170
217
  },
171
- },
218
+ }),
172
219
  };
173
220
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eightshift/frontend-libs-tailwind",
3
- "version": "4.0.0-beta.1",
3
+ "version": "4.0.0-beta.2",
4
4
  "description": "A framework for creating modern Gutenberg themes with styling provided by Tailwind CSS.",
5
5
  "author": {
6
6
  "name": "Eightshift team",