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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +30 -1
  2. package/README.md +149 -12
  3. package/bin/tw-sweep.mjs +35 -14
  4. package/bun/browser-css.mjs +487 -0
  5. package/bun/build.mjs +20 -1
  6. package/bun/cli-supervisor.mjs +171 -0
  7. package/bun/cli-worker.mjs +57 -0
  8. package/bun/cli.mjs +3 -49
  9. package/bun/css.mjs +126 -25
  10. package/bun/discovery.mjs +12 -1
  11. package/bun/editor-native.mjs +38 -0
  12. package/bun/editor-pure-jsx.mjs +88 -0
  13. package/bun/editor.mjs +33 -0
  14. package/bun/eightshift-discovery.mjs +102 -26
  15. package/bun/flat-publication.mjs +19 -184
  16. package/bun/index.mjs +14 -0
  17. package/bun/media.mjs +17 -5
  18. package/bun/plugin-capabilities.mjs +1 -0
  19. package/bun/preset.mjs +6 -4
  20. package/bun/publish.mjs +7 -4
  21. package/bun/release.mjs +56 -4
  22. package/bun/shared-fonts.mjs +140 -0
  23. package/bun/ssr.mjs +26 -12
  24. package/bun/structured-publication.mjs +66 -0
  25. package/bun/theme-build.mjs +130 -43
  26. package/bun/theme-discovery.mjs +113 -9
  27. package/bun/watch.mjs +32 -0
  28. package/bun/wordpress.mjs +49 -23
  29. package/eslint.config.mjs +22 -1
  30. package/linters/base.config.mjs +1 -0
  31. package/linters/tw-sweep-extract.mjs +5 -0
  32. package/package.json +5 -5
  33. package/scripts/components/link-section-editor.js +1 -0
  34. package/scripts/editor/editor.js +1 -0
  35. package/scripts/editor/registration.js +3 -0
  36. package/scripts/editor/store.js +7 -0
  37. package/test/bun-discovery.test.mjs +69 -0
  38. package/test/bun-publication.test.mjs +144 -0
  39. package/test/bun-theme-build.test.mjs +12 -0
  40. package/test/bun-wordpress.test.mjs +82 -0
  41. package/test/fixtures/theme-build-regressions.mjs +585 -0
package/bun/index.mjs CHANGED
@@ -37,6 +37,7 @@ export function defineBuild({ root = process.cwd(), preset, ssr, publish, watch
37
37
  if (Object.hasOwn(options, 'timings')) {
38
38
  throw new Error('The timings option is no longer supported');
39
39
  }
40
+
40
41
  if (options.quiet && options.verbose) {
41
42
  throw new Error('quiet and verbose cannot be combined');
42
43
  }
@@ -47,6 +48,7 @@ export function defineBuild({ root = process.cwd(), preset, ssr, publish, watch
47
48
  const outputs = new Set();
48
49
  const run = async (options = {}) => {
49
50
  validateOptions(options);
51
+
50
52
  if (active) {
51
53
  throw new Error('A build is already running');
52
54
  }
@@ -65,13 +67,17 @@ export function defineBuild({ root = process.cwd(), preset, ssr, publish, watch
65
67
  const configured = typeof preset === 'function' ? await preset(context) : preset;
66
68
  outputs.clear();
67
69
  const output = typeof configured?.outdir === 'string' && configured.outdir ? resolve(root, configured.outdir) : undefined;
70
+
68
71
  if (output) {
69
72
  const rootFromOutput = relative(output, root);
73
+
70
74
  if (!rootFromOutput || (!isAbsolute(rootFromOutput) && rootFromOutput !== '..' && !rootFromOutput.startsWith(`..${sep}`))) {
71
75
  throw new Error('outdir must not contain the project root');
72
76
  }
77
+
73
78
  outputs.add(output);
74
79
  }
80
+
75
81
  report('Building browser assets…');
76
82
  const result = await buildPreset({ ...configured, root });
77
83
  const state = { ...context, result };
@@ -87,6 +93,7 @@ export function defineBuild({ root = process.cwd(), preset, ssr, publish, watch
87
93
  }
88
94
 
89
95
  report(`Build completed in ${((performance.now() - started) / 1000).toFixed(2)}s.`);
96
+
90
97
  return state;
91
98
  })();
92
99
 
@@ -101,6 +108,7 @@ export function defineBuild({ root = process.cwd(), preset, ssr, publish, watch
101
108
  build: run,
102
109
  watch: (options = {}) => {
103
110
  validateOptions(options);
111
+
104
112
  if ((ssr || publish) && watch.sources === undefined && !watch.ignored?.length) {
105
113
  throw new Error('Watch builds with ssr or publish callbacks require explicit watch.sources or watch.ignored');
106
114
  }
@@ -113,22 +121,28 @@ export function defineBuild({ root = process.cwd(), preset, ssr, publish, watch
113
121
  if (watch.ignore?.(path)) {
114
122
  return true;
115
123
  }
124
+
116
125
  for (const output of outputs) {
117
126
  const location = relative(output, path);
127
+
118
128
  if (!location || (!isAbsolute(location) && location !== '..' && !location.startsWith(`..${sep}`))) {
119
129
  return true;
120
130
  }
131
+
121
132
  const sibling = relative(dirname(output), path).split(sep)[0];
133
+
122
134
  if (sibling.startsWith(`.${basename(output)}-stage-`) || sibling.startsWith(`.${basename(output)}-backup-`)) {
123
135
  return true;
124
136
  }
125
137
  }
138
+
126
139
  return false;
127
140
  },
128
141
  build: async () => {
129
142
  while (active) {
130
143
  await active.catch(() => {});
131
144
  }
145
+
132
146
  return run(options);
133
147
  },
134
148
  });
package/bun/media.mjs CHANGED
@@ -3,15 +3,23 @@ import { basename, dirname, resolve } from 'node:path';
3
3
  import { allowPureJsxGrouping } from './plugin-capabilities.mjs';
4
4
 
5
5
  /**
6
- * Adapt the published UI Components smart-image worker for flat theme releases.
6
+ * Adapt the published UI Components smart-image worker for structured theme releases.
7
7
  * Callbacks belong to one build and provide the worker to the publication step.
8
8
  * Unsupported upstream worker URL forms fail rather than producing a broken URL.
9
9
  */
10
- export function editorWorkerPlugin({ setEditorWorker, getEditorWorker }) {
10
+ export function editorWorkerPlugin({ setEditorWorker, getEditorWorker, scriptUrlIdentifier = '__eightshiftEditorScriptUrl', publicPrefix }) {
11
11
  if (typeof setEditorWorker !== 'function' || typeof getEditorWorker !== 'function') {
12
12
  throw new TypeError('Worker callbacks are required');
13
13
  }
14
14
 
15
+ if (typeof scriptUrlIdentifier !== 'string' || !/^[$A-Z_a-z][$\w]*$/.test(scriptUrlIdentifier)) {
16
+ throw new TypeError('Invalid editor script URL identifier');
17
+ }
18
+
19
+ if (publicPrefix !== undefined && (typeof publicPrefix !== 'string' || !publicPrefix)) {
20
+ throw new TypeError('publicPrefix must be a non-empty string');
21
+ }
22
+
15
23
  return allowPureJsxGrouping({
16
24
  name: 'eightshift-editor-worker-url',
17
25
  setup(builder) {
@@ -26,7 +34,7 @@ export function editorWorkerPlugin({ setEditorWorker, getEditorWorker }) {
26
34
  return;
27
35
  }
28
36
 
29
- const pattern = /new URL\("" \+ new URL\("(\.\.\/\.\.\/assets\/image-analysis-worker-[A-Za-z0-9_-]+\.js)", import\.meta\.url\)\.href \+ "", "" \+ import\.meta\.url\)/g;
37
+ const pattern = /new URL\((?:"" \+ )?new URL\("(\.\.\/\.\.\/assets\/image-analysis-worker-[A-Za-z0-9_-]+\.js)", import\.meta\.url\)\.href(?: \+ "")?, "" \+ import\.meta\.url\)/g;
30
38
  const matches = [...source.matchAll(pattern)];
31
39
 
32
40
  if (matches.length !== 1) {
@@ -41,9 +49,13 @@ export function editorWorkerPlugin({ setEditorWorker, getEditorWorker }) {
41
49
  }
42
50
 
43
51
  setEditorWorker(worker);
44
- const base = '(typeof __eightshiftEditorScriptUrl !== "undefined" ? __eightshiftEditorScriptUrl : (() => { throw new Error("Smart-image worker requires the Eightshift editor script URL; override media.editorWorker for other bundles"); })())';
52
+ const editorPath = `editor-assets/${basename(worker)}`;
53
+ const publicPath = `editor/${editorPath}`;
54
+ const url = publicPrefix
55
+ ? `new URL(${JSON.stringify(`${publicPrefix}${publicPath}`)}, globalThis.location.href)`
56
+ : `(typeof ${scriptUrlIdentifier} !== "undefined" ? new URL(${JSON.stringify(editorPath)}, ${scriptUrlIdentifier}) : (() => { throw new Error("Smart-image worker requires a publicPrefix outside the editor"); })())`;
45
57
 
46
- return { contents: source.replace(pattern, `new URL(${JSON.stringify(`editor-assets/${basename(worker)}`)}, ${base})`), loader: 'js', resolveDir: dirname(path) };
58
+ return { contents: source.replace(pattern, url), loader: 'js', resolveDir: dirname(path) };
47
59
  });
48
60
  },
49
61
  });
@@ -3,6 +3,7 @@ const pureJsxCompatible = new WeakMap();
3
3
  // Only audited built-ins may participate; plugin names are not a trust boundary.
4
4
  export function allowPureJsxGrouping(plugin) {
5
5
  pureJsxCompatible.set(plugin, plugin.setup);
6
+
6
7
  return plugin;
7
8
  }
8
9
 
package/bun/preset.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { isAbsolute, relative, resolve, sep } from 'node:path';
2
- import { build } from './build.mjs';
2
+ import { build, validateEntryPublicPaths } from './build.mjs';
3
3
  import { processEightshiftCss } from './eightshift-css.mjs';
4
4
 
5
5
  const checkOptions = (value, keys, label) => {
@@ -39,8 +39,8 @@ const feature = (value, keys, label) => {
39
39
  * Both are opt-in, and all filenames and discovery behavior are overridable.
40
40
  */
41
41
  export function createPreset(options = {}) {
42
- checkOptions(options, ['root', 'outdir', 'entries', 'wpRoot', 'wordpress', 'discovery', 'responsive', 'css', 'editor', 'buildOptions', 'direct'], 'preset');
43
- const { root = process.cwd(), outdir, entries, wpRoot, wordpress = true, buildOptions = {}, direct = false } = options;
42
+ checkOptions(options, ['root', 'outdir', 'entries', 'wpRoot', 'wordpress', 'discovery', 'responsive', 'css', 'editor', 'buildOptions', 'entryPublicPaths', 'direct'], 'preset');
43
+ const { root = process.cwd(), outdir, entries, wpRoot, wordpress = true, buildOptions = {}, entryPublicPaths = {}, direct = false } = options;
44
44
 
45
45
  if (typeof root !== 'string' || !root || typeof outdir !== 'string' || !outdir) {
46
46
  throw new TypeError('root and outdir must be non-empty strings');
@@ -50,6 +50,8 @@ export function createPreset(options = {}) {
50
50
  throw new TypeError('entries must contain named entrypoints');
51
51
  }
52
52
 
53
+ validateEntryPublicPaths(entryPublicPaths, entries);
54
+
53
55
  if (typeof wordpress !== 'boolean') {
54
56
  throw new TypeError('wordpress must be a boolean');
55
57
  }
@@ -111,7 +113,7 @@ export function createPreset(options = {}) {
111
113
  }
112
114
  }
113
115
 
114
- return { root, outdir, entries: { ...entries }, wpRoot, wordpress, discovery, responsive, css, editor, direct, buildOptions: { ...buildOptions } };
116
+ return { root, outdir, entries: { ...entries }, wpRoot, wordpress, discovery, responsive, css, editor, direct, entryPublicPaths: { ...entryPublicPaths }, buildOptions: { ...buildOptions } };
115
117
  }
116
118
 
117
119
  /** Build and atomically publish a configured preset. */
package/bun/publish.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { cp, lstat, mkdir, readFile, readdir, rename, rm, unlink, writeFile } from 'node:fs/promises';
2
+ import { chmod, cp, lstat, mkdir, readFile, readdir, rename, rm, unlink, writeFile } from 'node:fs/promises';
3
3
  import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
4
 
5
5
  const exists = async (path) => {
@@ -13,6 +13,7 @@ const exists = async (path) => {
13
13
  throw error;
14
14
  }
15
15
  };
16
+
16
17
  const pathName = (value) => {
17
18
  if (typeof value !== 'string' || !value || isAbsolute(value) || value.includes('\\') || value.includes('\0') || value.split('/').some((part) => !part || part === '.' || part === '..')) {
18
19
  throw new Error(`Invalid manifest path: ${String(value)}`);
@@ -20,6 +21,7 @@ const pathName = (value) => {
20
21
 
21
22
  return value;
22
23
  };
24
+
23
25
  const inside = (parent, child) => {
24
26
  const path = relative(parent, child);
25
27
 
@@ -30,8 +32,8 @@ const inside = (parent, child) => {
30
32
  * Publish a packageRelease directory without deleting unrelated public files.
31
33
  * root is the theme root; publicDir defaults to root/public. publicPrefix is
32
34
  * the URL prefix including its trailing slash. manifest maps keys to paths in
33
- * release. Existing PHP manifest cache assets are updated;
34
- * missing caches are left alone. Returns { publicDir, manifest }.
35
+ * release. Existing PHP manifest cache assets are updated with their permission
36
+ * bits preserved; missing caches are left alone. Returns { publicDir, manifest }.
35
37
  */
36
38
  export async function publishRelease({ root, release, manifest, publicDir, publicPrefix }) {
37
39
  if (
@@ -182,7 +184,8 @@ export async function publishRelease({ root, release, manifest, publicDir, publi
182
184
 
183
185
  cacheData.assets.assets = publicManifest;
184
186
  cacheTemporary = `${cachePath}.${randomUUID()}`;
185
- await writeFile(cacheTemporary, JSON.stringify(cacheData), { flag: 'wx', mode: cacheInfo.mode });
187
+ await writeFile(cacheTemporary, JSON.stringify(cacheData), { flag: 'wx', mode: cacheInfo.mode & 0o7777 });
188
+ await chmod(cacheTemporary, cacheInfo.mode & 0o7777);
186
189
  }
187
190
 
188
191
  if (publicInfo) {
package/bun/release.mjs CHANGED
@@ -8,6 +8,7 @@ async function ensureDirectory(directory, root) {
8
8
  const location = root && relative(root, directory);
9
9
  const withinRoot = root && (!location || (!isAbsolute(location) && location !== '..' && !location.startsWith(`..${sep}`)));
10
10
  const parent = dirname(directory);
11
+
11
12
  if (parent !== directory && (!withinRoot || directory !== root)) {
12
13
  await ensureDirectory(parent, root);
13
14
  }
@@ -21,6 +22,7 @@ async function ensureDirectory(directory, root) {
21
22
  }
22
23
 
23
24
  const info = await lstat(directory);
25
+
24
26
  if (!info.isDirectory() || info.isSymbolicLink()) {
25
27
  throw new Error(`Release path must be a real directory: ${directory}`);
26
28
  }
@@ -47,7 +49,7 @@ const releasePath = (value) => {
47
49
  * Returns { release, version, manifest }. A failed staging directory is retained.
48
50
  * outputDirectory writes directly to an existing directory instead of staging.
49
51
  */
50
- export async function packageRelease({ root, files, entries, aliases = {}, outputDirectory, omit = [] }) {
52
+ export async function packageRelease({ root, files, entries, aliases = {}, outputDirectory, omit = [], removeUnreferencedStyles = false }) {
51
53
  if (typeof root !== 'string' || !root || !Array.isArray(files) || !Array.isArray(entries) || !entries.length || !aliases || typeof aliases !== 'object' || Array.isArray(aliases)) {
52
54
  throw new TypeError('Expected root, files, entries and optional aliases');
53
55
  }
@@ -62,6 +64,7 @@ export async function packageRelease({ root, files, entries, aliases = {}, outpu
62
64
 
63
65
  contents.set(path, bytes);
64
66
  };
67
+
65
68
  const collect = async (source, destination) => {
66
69
  const info = await lstat(source);
67
70
 
@@ -101,6 +104,7 @@ export async function packageRelease({ root, files, entries, aliases = {}, outpu
101
104
 
102
105
  manifest[key] = value;
103
106
  };
107
+
104
108
  const scripts = new Map();
105
109
 
106
110
  for (const entry of entries) {
@@ -111,8 +115,12 @@ export async function packageRelease({ root, files, entries, aliases = {}, outpu
111
115
  const target = releasePath(entry.entry);
112
116
  const style = releasePath(entry.style);
113
117
 
114
- if (!contents.has(target) || !contents.has(style) || !contents.get(target).length || !contents.get(style).length) {
115
- throw new Error(`Missing or empty entry or style for ${entry.name}`);
118
+ if (!contents.has(target) || !contents.get(target).length) {
119
+ throw new Error(`Missing or empty entry for ${entry.name}`);
120
+ }
121
+
122
+ if (!contents.has(style)) {
123
+ throw new Error(`Missing style for ${entry.name}`);
116
124
  }
117
125
 
118
126
  if (entry.script !== undefined && (typeof entry.script !== 'string' || !entry.script.trim())) {
@@ -122,9 +130,11 @@ export async function packageRelease({ root, files, entries, aliases = {}, outpu
122
130
  if (entry.format !== undefined && entry.format !== 'module') {
123
131
  throw new TypeError(`Unsupported script format for ${entry.name}`);
124
132
  }
133
+
125
134
  if (entry.format === 'module' && (entry.readiness !== 'eightshift-editor-v1' || entry.script === undefined)) {
126
135
  throw new TypeError(`Module entry ${entry.name} requires an explicit script and readiness contract`);
127
136
  }
137
+
128
138
  if (entry.readiness !== undefined && entry.format !== 'module') {
129
139
  throw new TypeError(`Readiness requires a module entry: ${entry.name}`);
130
140
  }
@@ -138,7 +148,9 @@ export async function packageRelease({ root, files, entries, aliases = {}, outpu
138
148
  scripts.set(entry.name, { script, dependencies: entry.dependencies, ...(entry.format === 'module' ? { format: entry.format, readiness: entry.readiness } : {}) });
139
149
  const scriptName = `${entry.name}-${digest(script)}.js`;
140
150
  const styleBytes = contents.get(style);
141
- const styleName = `${entry.name}-${digest(styleBytes)}.css`;
151
+ // Preserve the stylesheet's base directory for relative URLs and imports.
152
+ const styleDirectory = style.slice(0, style.lastIndexOf('/') + 1);
153
+ const styleName = `${styleDirectory}${entry.name}-${digest(styleBytes)}.css`;
142
154
 
143
155
  if (contents.has(scriptName)) {
144
156
  throw new Error(`Duplicate release path: ${scriptName}`);
@@ -166,16 +178,56 @@ export async function packageRelease({ root, files, entries, aliases = {}, outpu
166
178
  if (!Array.isArray(omit)) {
167
179
  throw new TypeError('omit must be an array');
168
180
  }
181
+
169
182
  for (const path of omit) {
170
183
  releasePath(path);
184
+
185
+ if (entries.some((entry) => entry.script === undefined && entry.entry === path)) {
186
+ throw new Error(`Cannot omit a script bootstrap target: ${path}`);
187
+ }
188
+
171
189
  if (Object.values(manifest).includes(path)) {
172
190
  throw new Error(`Cannot omit manifest target: ${path}`);
173
191
  }
192
+
174
193
  if (!contents.delete(path)) {
175
194
  throw new Error(`Cannot omit missing release file: ${path}`);
176
195
  }
177
196
  }
178
197
 
198
+ if (typeof removeUnreferencedStyles !== 'boolean') {
199
+ throw new TypeError('removeUnreferencedStyles must be a boolean');
200
+ }
201
+
202
+ if (removeUnreferencedStyles) {
203
+ // Only entry styles have a generated, same-directory hashed replacement.
204
+ // Conservative name matching also retains ambiguous and absolute references.
205
+ const referenceText = (bytes) =>
206
+ bytes
207
+ .toString()
208
+ .replace(/\\(?:u\{([\da-f]+)\}|u([\da-f]{4})|x([\da-f]{2}))/gi, (match, point, unicode, hex) => {
209
+ const code = Number.parseInt(point ?? unicode ?? hex, 16);
210
+
211
+ return code <= 0x10ffff ? String.fromCodePoint(code) : match;
212
+ })
213
+ .replace(/\\([\da-f]{1,6})[ \t\r\n\f]?/gi, (match, hex) => {
214
+ const code = Number.parseInt(hex, 16);
215
+
216
+ return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : match;
217
+ })
218
+ .replace(/\\([^\r\n])/g, '$1')
219
+ .replace(/%([\da-f]{2})/gi, (_match, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
220
+ const texts = [...contents.values(), ...[...scripts.values()].map(({ script }) => script)].map(referenceText);
221
+
222
+ for (const { style } of entries) {
223
+ const name = style.slice(style.lastIndexOf('/') + 1);
224
+
225
+ if (!Object.values(manifest).includes(style) && !texts.some((text) => text.includes(name))) {
226
+ contents.delete(style);
227
+ }
228
+ }
229
+ }
230
+
179
231
  const inventory = Object.fromEntries([...contents].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([path, bytes]) => [path, digest(bytes)]));
180
232
  const version = digest(JSON.stringify({ format: 1, inventory, scripts: [...scripts].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)), manifest }));
181
233
 
@@ -0,0 +1,140 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { createRequire } from 'node:module';
3
+ import { readFile, readdir, writeFile } from 'node:fs/promises';
4
+ import { basename, dirname, extname, isAbsolute, relative, resolve } from 'node:path';
5
+ import postcss from 'postcss';
6
+ import valueParser from 'postcss-value-parser';
7
+
8
+ /** Extract verified UI Components font faces before stylesheet hashes are calculated. */
9
+ export async function prepareSharedFonts({ root, flatDir, retainedStyles = new Set() }) {
10
+ const require = createRequire(resolve(root, 'package.json'));
11
+ const assets = dirname(require.resolve('@eightshift/ui-components/dist/assets/style.css'));
12
+ const manifest = JSON.parse(await readFile(resolve(assets, 'fonts-manifest.json'), 'utf8'));
13
+
14
+ if (manifest.version !== 1 || !Array.isArray(manifest.fonts) || !manifest.fonts.length || typeof manifest.css !== 'string') {
15
+ throw new Error('Invalid UI Components font manifest; rebuild UI Components with shared-font support.');
16
+ }
17
+
18
+ const hashes = new Set();
19
+
20
+ for (const font of manifest.fonts) {
21
+ if (!font || !/^[a-f0-9]{64}$/.test(font.hash) || typeof font.file !== 'string' || !/^fonts\/[\w.-]+\.woff2$/.test(font.file)) {
22
+ throw new Error('Invalid shared font asset descriptor.');
23
+ }
24
+
25
+ const bytes = await readFile(resolve(assets, font.file));
26
+
27
+ if (createHash('sha256').update(bytes).digest('hex') !== font.hash) {
28
+ throw new Error(`Shared font integrity mismatch: ${font.file}`);
29
+ }
30
+
31
+ hashes.add(font.hash);
32
+ }
33
+
34
+ const faces = new Set();
35
+ let matched = false;
36
+ const fonts = new Map();
37
+ const updated = [];
38
+
39
+ for (const name of (await readdir(flatDir, { recursive: true })).filter((name) => name.endsWith('.css')).sort()) {
40
+ const file = resolve(flatDir, name);
41
+ const tree = postcss.parse(await readFile(file, 'utf8'), { from: file });
42
+ const candidates = [];
43
+ let changed = false;
44
+ tree.walkAtRules('font-face', (face) => candidates.push(face));
45
+
46
+ for (const face of candidates) {
47
+ const sources = [];
48
+ face.walkDecls('src', (decl) => {
49
+ const parsed = valueParser(decl.value);
50
+ parsed.walk((node) => {
51
+ if (node.type === 'function' && node.value.toLowerCase() === 'url') {
52
+ sources.push({
53
+ node,
54
+ parsed,
55
+ decl,
56
+ url: valueParser
57
+ .stringify(node.nodes)
58
+ .trim()
59
+ .replace(/^(['"])(.*)\1$/, '$2'),
60
+ });
61
+ }
62
+ });
63
+ });
64
+
65
+ if (!sources.length) {
66
+ continue;
67
+ }
68
+
69
+ const resolved = [];
70
+
71
+ for (const source of sources) {
72
+ if (/^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(source.url) || /[?#]/.test(source.url)) {
73
+ break;
74
+ }
75
+
76
+ const path = resolve(dirname(file), source.url);
77
+ const rel = relative(flatDir, path);
78
+
79
+ if (isAbsolute(rel) || rel.startsWith('..') || !/\.woff2$/.test(path)) {
80
+ break;
81
+ }
82
+
83
+ const hash = createHash('sha256')
84
+ .update(await readFile(path))
85
+ .digest('hex');
86
+
87
+ if (!hashes.has(hash)) {
88
+ break;
89
+ }
90
+
91
+ resolved.push({ ...source, path, hash, file: `fonts/${hash}${extname(path)}` });
92
+ }
93
+
94
+ // Leave mixed or unrelated font declarations entirely unchanged.
95
+ if (resolved.length !== sources.length) {
96
+ continue;
97
+ }
98
+
99
+ matched = true;
100
+
101
+ // PHP accepts only plain font-face rules; retain all nested contexts.
102
+ if (face.parent !== tree || retainedStyles.has(name) || retainedStyles.has(basename(name))) {
103
+ continue;
104
+ }
105
+
106
+ for (const source of resolved) {
107
+ source.node.nodes = [{ type: 'string', quote: '"', value: `./${source.file}` }];
108
+ fonts.set(source.file, { hash: source.hash, file: source.file, source: source.path });
109
+ }
110
+
111
+ for (const source of resolved) {
112
+ source.decl.value = source.parsed.toString();
113
+ }
114
+
115
+ faces.add(face.toString());
116
+ face.remove();
117
+ changed = true;
118
+ }
119
+
120
+ if (changed) {
121
+ updated.push([file, tree.toString()]);
122
+ }
123
+ }
124
+
125
+ if (!matched) {
126
+ throw new Error('Shared fonts enabled but no verified UI Components font faces were found.');
127
+ }
128
+
129
+ const output = resolve(flatDir, '../shared-fonts.json');
130
+ await writeFile(output, JSON.stringify({ version: 1, fonts: [...fonts.values()].map(({ hash, file }) => ({ hash, file })), css: [...faces].join('\n') }, null, 2));
131
+
132
+ for (const [file, css] of updated) {
133
+ await writeFile(file, css);
134
+ }
135
+
136
+ return {
137
+ extraFiles: [{ source: output, destination: basename(output) }, ...[...fonts.values()].map(({ source, file }) => ({ source, destination: file }))],
138
+ aliases: { 'shared-fonts.json': 'shared-fonts.json' },
139
+ };
140
+ }
package/bun/ssr.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
- import { basename, dirname, resolve } from 'node:path';
2
+ import { basename, dirname, relative, resolve } from 'node:path';
3
3
 
4
4
  /** Discover SSR entries by their block/component directory name. */
5
5
  export async function discoverSsrEntries({ root, pattern = 'src/**/assets-ssr/ssr.{js,mjs}' }) {
@@ -37,9 +37,10 @@ export function ssrCssAsText() {
37
37
  }
38
38
 
39
39
  /**
40
- * Build discovered SSR entries as individual Node CJS bundles. Paths are
41
- * relative to root unless absolute. Caller plugins run before the CSS plugin;
42
- * pass cssAsText: false to disable it. write: false returns in-memory outputs.
40
+ * Build discovered SSR entries as standalone Node CJS bundles in one compilation.
41
+ * Caller plugins retain sequential compilations and run before the CSS plugin.
42
+ * Paths are relative to root unless absolute; cssAsText: false disables the CSS
43
+ * plugin. write: false returns in-memory outputs without touching the output tree.
43
44
  */
44
45
  export async function buildSsr({ root, outdir, pattern, mode = 'development', plugins = [], cssAsText = true, write = true }) {
45
46
  if (typeof root !== 'string' || !root || typeof outdir !== 'string' || !outdir || !['development', 'production'].includes(mode) || !Array.isArray(plugins) || typeof cssAsText !== 'boolean' || typeof write !== 'boolean') {
@@ -50,12 +51,16 @@ export async function buildSsr({ root, outdir, pattern, mode = 'development', pl
50
51
  const entries = await discoverSsrEntries({ root, pattern });
51
52
  const outputs = [];
52
53
 
53
- for (const [name, entrypoint] of entries) {
54
+ // Caller plugins may keep per-build state, so retain their sequential lifecycle.
55
+ const groups = plugins.length ? [...entries].map((entry) => new Map([entry])) : [entries];
56
+
57
+ for (const group of groups) {
54
58
  const result = await Bun.build({
55
- entrypoints: [entrypoint],
56
- outdir: directory,
59
+ entrypoints: [...group.values()],
60
+ root: resolve(root),
61
+ // Omitting outdir is essential: Bun can write files despite write: false.
57
62
  write: false,
58
- naming: `${name}.js`,
63
+ naming: '[dir]/[name].[ext]',
59
64
  target: 'node',
60
65
  format: 'cjs',
61
66
  splitting: false,
@@ -67,14 +72,23 @@ export async function buildSsr({ root, outdir, pattern, mode = 'development', pl
67
72
  });
68
73
 
69
74
  if (!result.success) {
70
- throw new AggregateError(result.logs, `SSR build failed: ${name}`);
75
+ throw new AggregateError(result.logs, `SSR build failed: ${[...group.keys()].join(', ')}`);
71
76
  }
72
77
 
73
- if (result.outputs.length !== 1 || result.outputs[0].kind !== 'entry-point') {
74
- throw new Error(`Unexpected SSR output count or kind for ${name}: ${result.outputs.length}`);
78
+ if (result.outputs.length !== group.size || result.outputs.some((output) => output.kind !== 'entry-point')) {
79
+ throw new Error(`Unexpected SSR output count or kind: ${result.outputs.length}`);
75
80
  }
76
81
 
77
- outputs.push({ name, entrypoint, path: resolve(directory, `${name}.js`), output: result.outputs[0], logs: result.logs });
82
+ for (const [name, entrypoint] of group) {
83
+ const expected = relative(resolve(root), entrypoint).replace(/\.m?js$/, '.js');
84
+ const output = result.outputs.find((item) => resolve(root, item.path) === resolve(root, expected));
85
+
86
+ if (!output) {
87
+ throw new Error(`Missing SSR output: ${name}`);
88
+ }
89
+
90
+ outputs.push({ name, entrypoint, path: resolve(directory, `${name}.js`), output, logs: result.logs });
91
+ }
78
92
  }
79
93
 
80
94
  if (write) {
@@ -0,0 +1,66 @@
1
+ import { lstat, mkdir, readdir, copyFile } from 'node:fs/promises';
2
+ import { resolve, dirname } from 'node:path';
3
+
4
+ // Only compiler-owned output surfaces are eligible; discovery and metadata stay private.
5
+ export async function preserveAssets({ outdir, flatDir, directories = ['frontend', 'editor', 'admin', 'css'], extraSources = {} }) {
6
+ const sources = new Map();
7
+ const valid = (path) => {
8
+ if (typeof path !== 'string' || !path || path.includes('\\') || path.includes('\0') || path.split('/').some((p) => !p || p === '.' || p === '..')) {
9
+ throw new Error(`Invalid output path: ${path}`);
10
+ }
11
+
12
+ return path;
13
+ };
14
+
15
+ const collect = async (directory, prefix) => {
16
+ for (const item of await readdir(directory, { withFileTypes: true })) {
17
+ const path = valid(`${prefix}/${item.name}`);
18
+
19
+ if (path === 'editor/discovery' || (!prefix.includes('/') && item.name === `${prefix}.asset.json`)) {
20
+ continue;
21
+ }
22
+
23
+ if (item.isDirectory()) {
24
+ await collect(resolve(directory, item.name), path);
25
+ } else if (item.isFile()) {
26
+ sources.set(path, resolve(directory, item.name));
27
+ } else {
28
+ throw new Error(`Unsupported output: ${path}`);
29
+ }
30
+ }
31
+ };
32
+
33
+ for (const directory of directories) {
34
+ const source = resolve(outdir, valid(directory));
35
+
36
+ if (!(await lstat(source)).isDirectory()) {
37
+ throw new Error(`Invalid output directory: ${directory}`);
38
+ }
39
+
40
+ await collect(source, directory);
41
+ }
42
+
43
+ for (const [path, source] of Object.entries(extraSources)) {
44
+ valid(path);
45
+
46
+ if (sources.has(path)) {
47
+ throw new Error(`Duplicate output: ${path}`);
48
+ }
49
+
50
+ if (!(await lstat(source)).isFile()) {
51
+ throw new Error(`Invalid extra source: ${path}`);
52
+ }
53
+
54
+ sources.set(path, source);
55
+ }
56
+
57
+ await mkdir(flatDir);
58
+
59
+ for (const [path, source] of sources) {
60
+ const target = resolve(flatDir, path);
61
+ await mkdir(dirname(target), { recursive: true });
62
+ await copyFile(source, target, 1);
63
+ }
64
+
65
+ return { sources };
66
+ }