@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/editor.mjs CHANGED
@@ -17,15 +17,19 @@ export async function buildEditor({ root, directory, entry, buildOptions = {}, p
17
17
  if (!['independent', 'native', 'unified'].includes(sharing)) {
18
18
  throw new TypeError('editor.sharing must be "independent", "native" or "unified"');
19
19
  }
20
+
20
21
  if (pureJsxGroups !== false && (!pureJsxGroups || typeof pureJsxGroups !== 'object' || Array.isArray(pureJsxGroups) || Object.keys(pureJsxGroups).some((key) => key !== 'maxBytes') || !Number.isSafeInteger(pureJsxGroups.maxBytes) || pureJsxGroups.maxBytes < 1 || pureJsxGroups.maxBytes > 65536)) {
21
22
  throw new TypeError('editor.pureJsxGroups must be false or { maxBytes: integer between 1 and 65536 }');
22
23
  }
24
+
23
25
  if (pureJsxGroups && sharing !== 'unified') {
24
26
  throw new TypeError('editor.pureJsxGroups requires unified sharing');
25
27
  }
28
+
26
29
  if (sharedPackages !== undefined) {
27
30
  throw new TypeError('editor.sharedPackages was removed; use native or unified sharing after checking their initialization and readiness requirements');
28
31
  }
32
+
29
33
  const inside = (path) => {
30
34
  if (typeof path !== 'string' || !path || isAbsolute(path)) {
31
35
  throw new TypeError('Editor output paths must be relative');
@@ -60,9 +64,11 @@ export async function buildEditor({ root, directory, entry, buildOptions = {}, p
60
64
  if (!/^[$A-Z_a-z][$\w]*$/.test(scriptUrlIdentifier)) {
61
65
  throw new TypeError('Invalid editor script URL identifier');
62
66
  }
67
+
63
68
  if (Object.keys(lazy).length) {
64
69
  throw new TypeError('Unified editor sharing uses native imports and cannot apply lazy import rewriting');
65
70
  }
71
+
66
72
  const target = resolve(root, entry);
67
73
  const nativeDiscovery = discovery ? eightshiftDiscovery({ ...discovery, root, outputDir: inside(discovery.outputDir ?? 'discovery') }) : undefined;
68
74
  const {
@@ -80,23 +86,30 @@ export async function buildEditor({ root, directory, entry, buildOptions = {}, p
80
86
  });
81
87
  const paths = [];
82
88
  await mkdir(chunkOutput, { recursive: true });
89
+
83
90
  for (const output of outputs) {
84
91
  let contents = Buffer.from(await output.arrayBuffer());
92
+
85
93
  if (output.sourcemap) {
86
94
  contents = Buffer.from(`${await output.text()}\n//# sourceMappingURL=${basename(output.sourcemap.path)}\n`);
87
95
  }
96
+
88
97
  await writeFile(output.path, contents);
89
98
  paths.push(output.path);
90
99
  }
100
+
91
101
  let imported = relative(dirname(entryOutput), resolve(chunkOutput, names.get(target)))
92
102
  .split(sep)
93
103
  .join('/');
104
+
94
105
  if (!imported.startsWith('.')) {
95
106
  imported = `./${imported}`;
96
107
  }
108
+
97
109
  const source = `import ${JSON.stringify(imported)};\nconst readiness = globalThis.eightshiftEditorModules;\nif (readiness?.version !== 1 || typeof readiness.complete !== 'function') throw new Error('Unified editor requires the Eightshift module readiness integration');\nreadiness.complete(import.meta.url);\n`;
98
110
  await writeFile(entryOutput, source);
99
111
  paths.push(entryOutput);
112
+
100
113
  return { entry: entryOutput, paths, format: 'module', readiness: 'eightshift-editor-v1', ...(grouping ? { pureJsxGroups: grouping } : {}) };
101
114
  }
102
115
 
@@ -126,23 +139,29 @@ export async function buildEditor({ root, directory, entry, buildOptions = {}, p
126
139
 
127
140
  const entries = result.outputs.filter((output) => output.kind === 'entry-point');
128
141
  const maps = result.outputs.filter((output) => output.kind === 'sourcemap');
142
+
129
143
  if (entries.length !== 1 || maps.length !== (sourcemap ? 1 : 0) || result.outputs.length !== entries.length + maps.length) {
130
144
  throw new Error(`Unexpected editor assets: ${target}`);
131
145
  }
132
146
 
133
147
  const map = sourcemap ? JSON.parse(await maps[0].text()) : undefined;
148
+
134
149
  if (map) {
135
150
  map.mappings = `;${map.mappings}`;
136
151
  }
152
+
137
153
  return { source: await entries[0].text(), map };
138
154
  };
155
+
139
156
  const write = async (path, source) => {
140
157
  await mkdir(dirname(path), { recursive: true });
141
158
  await writeFile(path, source);
142
159
  paths.push(path);
143
160
  };
161
+
144
162
  let entryBuild = await compile(resolve(root, entry), 'iife');
145
163
  const entryMap = `${basename(entryOutput)}.map`;
164
+
146
165
  if (sharing === 'native') {
147
166
  if (chunks.size) {
148
167
  const nativeDiscovery = discovery ? eightshiftDiscovery({ ...discovery, root, outputDir: inside(discovery.outputDir ?? 'discovery') }) : undefined;
@@ -154,14 +173,18 @@ export async function buildEditor({ root, directory, entry, buildOptions = {}, p
154
173
  buildOptions: { ...buildOptions, loader: options.loader, sourcemap: options.sourcemap },
155
174
  plugins: [...(nativeDiscovery ? [nativeDiscovery] : []), ...plugins],
156
175
  });
176
+
157
177
  for (const [target, name] of names) {
158
178
  chunks.set(target, name);
159
179
  }
180
+
160
181
  // Compile against final URLs rather than rewriting code after source-map generation.
161
182
  entryBuild = await compile(resolve(root, entry), 'iife');
183
+
162
184
  if (chunks.size !== names.size) {
163
185
  throw new Error('Editor lazy entries changed during native compilation');
164
186
  }
187
+
165
188
  for (const output of outputs) {
166
189
  if (output.sourcemap) {
167
190
  await write(output.path, `${await output.text()}\n//# sourceMappingURL=${basename(output.sourcemap.path)}\n`);
@@ -170,10 +193,13 @@ export async function buildEditor({ root, directory, entry, buildOptions = {}, p
170
193
  }
171
194
  }
172
195
  }
196
+
173
197
  await write(entryOutput, `((${scriptUrlIdentifier}) => {\n${entryBuild.source}\n})(document.currentScript.src);\n${entryBuild.map ? `//# sourceMappingURL=${entryMap}\n` : ''}`);
198
+
174
199
  if (entryBuild.map) {
175
200
  await write(`${entryOutput}.map`, JSON.stringify(entryBuild.map));
176
201
  }
202
+
177
203
  return { entry: entryOutput, paths };
178
204
  }
179
205
 
@@ -182,12 +208,15 @@ export async function buildEditor({ root, directory, entry, buildOptions = {}, p
182
208
  for (const [target, name] of chunks) {
183
209
  const output = inside(`${chunkDir}/${name}`);
184
210
  let entryPath = relative(dirname(output), entryOutput).split(sep).join('/');
211
+
185
212
  if (!entryPath.startsWith('.')) {
186
213
  entryPath = `./${entryPath}`;
187
214
  }
215
+
188
216
  const chunk = await compile(target, 'esm');
189
217
  await write(output, `const ${scriptUrlIdentifier} = new URL(${JSON.stringify(entryPath)}, import.meta.url).href;\n${chunk.source}${chunk.map ? `\n//# sourceMappingURL=${basename(output)}.map\n` : ''}`);
190
218
  lazyPaths.push(output);
219
+
191
220
  if (chunk.map) {
192
221
  await write(`${output}.map`, JSON.stringify(chunk.map));
193
222
  }
@@ -195,18 +224,22 @@ export async function buildEditor({ root, directory, entry, buildOptions = {}, p
195
224
 
196
225
  const digest = createHash('sha256').update(entryBuild.source);
197
226
  const contents = new Map();
227
+
198
228
  for (const path of lazyPaths.sort()) {
199
229
  const source = await readFile(path, 'utf8');
200
230
  contents.set(path, source);
201
231
  digest.update(path.slice(directory.length)).update('\0').update(source).update('\0');
202
232
  }
233
+
203
234
  const version = digest.digest('hex').slice(0, 20);
204
235
  const withVersion = (source) => source.replaceAll('?v=00000000000000000000', `?v=${version}`);
236
+
205
237
  for (const [path, source] of contents) {
206
238
  await writeFile(path, withVersion(source));
207
239
  }
208
240
 
209
241
  await write(entryOutput, `((${scriptUrlIdentifier}) => {\n${withVersion(entryBuild.source)}\n})(document.currentScript.src);\n${entryBuild.map ? `//# sourceMappingURL=${entryMap}\n` : ''}`);
242
+
210
243
  if (entryBuild.map) {
211
244
  await write(`${entryOutput}.map`, JSON.stringify(entryBuild.map));
212
245
  }
@@ -1,3 +1,4 @@
1
+ import { Linter } from 'eslint';
1
2
  import { createHash } from 'node:crypto';
2
3
  import { realpathSync } from 'node:fs';
3
4
  import { readFile } from 'node:fs/promises';
@@ -6,6 +7,51 @@ import { dirname, resolve, relative, sep } from 'node:path';
6
7
  import { generateDiscovery } from './discovery.mjs';
7
8
  import { allowPureJsxGrouping } from './plugin-capabilities.mjs';
8
9
 
10
+ const linter = new Linter();
11
+
12
+ function executableCalls(source, path) {
13
+ const contexts = [];
14
+ const imports = [];
15
+ const identifiers = new Set();
16
+ const messages = linter.verify(
17
+ source,
18
+ [
19
+ {
20
+ languageOptions: { ecmaVersion: 'latest', sourceType: 'module', parserOptions: { ecmaFeatures: { jsx: true } } },
21
+ linterOptions: { noInlineConfig: true },
22
+ plugins: {
23
+ capture: {
24
+ rules: {
25
+ calls: {
26
+ create: () => ({
27
+ Identifier: (node) => identifiers.add(node.name),
28
+ CallExpression: (node) => {
29
+ const callee = node.callee;
30
+
31
+ if (callee.type === 'MemberExpression' && !callee.computed && callee.object.type === 'Identifier' && callee.object.name === 'require' && callee.property.name === 'context') {
32
+ contexts.push(node);
33
+ }
34
+ },
35
+ ImportExpression: (node) => imports.push(node),
36
+ }),
37
+ },
38
+ },
39
+ },
40
+ },
41
+ rules: { 'capture/calls': 'error' },
42
+ },
43
+ ],
44
+ { filename: 'module.js' },
45
+ );
46
+ const fatal = messages.find((message) => message.fatal);
47
+
48
+ if (fatal) {
49
+ throw new Error(`Cannot parse ${path}: ${fatal.message}`);
50
+ }
51
+
52
+ return { contexts: contexts.sort((a, b) => a.start - b.start), imports, identifiers };
53
+ }
54
+
9
55
  /**
10
56
  * Migrate literal webpack require.context calls in selected source files.
11
57
  * Generated modules live in outputDir and must be regenerated on rebuild.
@@ -31,15 +77,14 @@ export function eightshiftDiscovery({ root, outputDir, filter = /\.[cm]?jsx?$/,
31
77
 
32
78
  const source = await readFile(path, 'utf8');
33
79
 
34
- if (!source.includes('require.context')) {
80
+ if (!source.includes('require') || !source.includes('context')) {
35
81
  return;
36
82
  }
37
83
 
38
- const pattern = /require\.context\(\s*(['"])([^'"\n]+)\1\s*,\s*(true|false)\s*,\s*\/(?!\*)(?!\/)((?:\\.|[^/\n])+)\/([dgimsuvy]*)\s*(?:,\s*(['"])(sync|lazy)\6\s*)?\)/g;
39
- const matches = [...source.matchAll(pattern)];
84
+ const { contexts: matches, identifiers } = executableCalls(source, path);
40
85
 
41
86
  if (!matches.length) {
42
- throw new Error(`Unsupported require.context in ${path}`);
87
+ return;
43
88
  }
44
89
 
45
90
  const definitions = [];
@@ -47,16 +92,38 @@ export function eightshiftDiscovery({ root, outputDir, filter = /\.[cm]?jsx?$/,
47
92
  let offset = 0;
48
93
 
49
94
  for (const match of matches) {
50
- const [, , directory, recursive, expression, flags, , webpackMode] = match;
95
+ const [directoryNode, recursiveNode, patternNode, modeNode] = match.arguments;
96
+
97
+ if (
98
+ match.optional ||
99
+ match.arguments.length < 3 ||
100
+ match.arguments.length > 4 ||
101
+ directoryNode?.type !== 'Literal' ||
102
+ typeof directoryNode.value !== 'string' ||
103
+ recursiveNode?.type !== 'Literal' ||
104
+ typeof recursiveNode.value !== 'boolean' ||
105
+ !patternNode?.regex ||
106
+ (modeNode && (modeNode.type !== 'Literal' || !['sync', 'lazy'].includes(modeNode.value)))
107
+ ) {
108
+ throw new Error(`Unsupported require.context in ${path}`);
109
+ }
51
110
 
52
- if (recursive !== 'true') {
111
+ if (!recursiveNode.value) {
53
112
  throw new Error(`Nonrecursive require.context is unsupported in ${path}`);
54
113
  }
55
114
 
56
- const context = { path, directory, pattern: new RegExp(expression, flags), mode: webpackMode || 'sync' };
57
- const name = `context${definitions.length}`;
115
+ const directory = directoryNode.value;
116
+ const context = { path, directory, pattern: new RegExp(patternNode.regex.pattern, patternNode.regex.flags), mode: modeNode?.value ?? 'sync' };
117
+ let index = definitions.length;
118
+ let name = `context${index}`;
119
+
120
+ while (identifiers.has(name)) {
121
+ name = `context${++index}`;
122
+ }
123
+
124
+ identifiers.add(name);
58
125
 
59
- contents += source.slice(offset, match.index);
126
+ contents += source.slice(offset, match.start);
60
127
 
61
128
  if (omitContexts(context)) {
62
129
  contents += 'Object.assign(() => ({}), { keys: () => [] })';
@@ -65,15 +132,11 @@ export function eightshiftDiscovery({ root, outputDir, filter = /\.[cm]?jsx?$/,
65
132
  contents += name;
66
133
  }
67
134
 
68
- offset = match.index + match[0].length;
135
+ offset = match.end;
69
136
  }
70
137
 
71
138
  contents += source.slice(offset);
72
139
 
73
- if (contents.includes('require.context')) {
74
- throw new Error(`Unsupported require.context remains in ${path}`);
75
- }
76
-
77
140
  if (definitions.length) {
78
141
  const id = createHash('sha256').update(relative(root, path)).digest('hex').slice(0, 20);
79
142
  const output = resolve(outputDir, `${id}.mjs`);
@@ -88,6 +151,7 @@ export function eightshiftDiscovery({ root, outputDir, filter = /\.[cm]?jsx?$/,
88
151
  });
89
152
  },
90
153
  };
154
+
91
155
  return transformSource ? plugin : allowPureJsxGrouping(plugin);
92
156
  }
93
157
 
@@ -106,18 +170,30 @@ export function editorLazyImports({ root, chunks, chunkDir = 'editor-chunks', sc
106
170
 
107
171
  root = realpathSync(resolve(root));
108
172
  const require = createRequire(import.meta.url);
109
- const transformSource = (source, path) =>
110
- !include(path)
111
- ? source
112
- : source.replace(/import\(\s*(?:\/\*[\s\S]*?\*\/\s*)?(['"])(\.[^'"\n]+)\1\s*\)/g, (_match, _quote, specifier) => {
113
- const target = require.resolve(resolve(dirname(path), specifier));
114
- const name = chunks.get(target) ?? `${createHash('sha256').update(relative(root, target)).digest('hex').slice(0, 20)}.js`;
115
-
116
- chunks.set(target, name);
117
- const version = versioned ? '?v=00000000000000000000' : '';
118
-
119
- return `import(new URL(${JSON.stringify(`${chunkDir}/${name}${version}`)}, ${scriptUrlIdentifier}).href)`;
120
- });
173
+ const transformSource = (source, path) => {
174
+ if (!include(path) || !source.includes('import')) {
175
+ return source;
176
+ }
177
+
178
+ const { imports } = executableCalls(source, path);
179
+ let contents = source;
180
+
181
+ for (const node of imports.sort((a, b) => b.start - a.start)) {
182
+ if (node.source.type !== 'Literal' || typeof node.source.value !== 'string' || !node.source.value.startsWith('.') || node.options) {
183
+ continue;
184
+ }
185
+
186
+ const target = require.resolve(resolve(dirname(path), node.source.value));
187
+ const name = chunks.get(target) ?? `${createHash('sha256').update(relative(root, target)).digest('hex').slice(0, 20)}.js`;
188
+ chunks.set(target, name);
189
+ const version = versioned ? '?v=00000000000000000000' : '';
190
+ const replacement = `import(new URL(${JSON.stringify(`${chunkDir}/${name}${version}`)}, ${scriptUrlIdentifier}).href)`;
191
+ contents = contents.slice(0, node.start) + replacement + contents.slice(node.end);
192
+ }
193
+
194
+ return contents;
195
+ };
196
+
121
197
  const plugin = {
122
198
  name: 'eightshift-editor-lazy-imports',
123
199
  setup(builder) {
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { chmod, lstat, mkdir, readFile, readdir, rename, rmdir, unlink, writeFile } from 'node:fs/promises';
3
- import { basename, dirname, isAbsolute, posix, relative, resolve, sep } from 'node:path';
3
+ import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
4
4
  import { packageRelease } from './release.mjs';
5
5
 
6
6
  const pathName = (value) => {
@@ -11,203 +11,30 @@ const pathName = (value) => {
11
11
  return value;
12
12
  };
13
13
 
14
- /** Collect build outputs and flatten them, rewriting relative JS, CSS and map references.
15
- * sources maps output-relative paths to source files. Returns the rewrite function.
16
- */
17
- export async function flattenAssets({ outdir, flatDir, directories = ['frontend', 'editor', 'admin', 'css'], extraSources = {}, editorEntry, editorScript }) {
18
- const sources = new Map();
19
- const collect = async (directory, prefix) => {
20
- for (const item of await readdir(directory, { withFileTypes: true })) {
21
- const path = `${prefix}/${item.name}`;
22
-
23
- if (path === 'editor/discovery' || (item.isFile() && !prefix.includes('/') && item.name === `${prefix}.asset.json`)) {
24
- continue;
25
- }
26
-
27
- if (item.isDirectory()) {
28
- await collect(resolve(directory, item.name), path);
29
- } else if (item.isFile()) {
30
- sources.set(path, resolve(directory, item.name));
31
- } else {
32
- throw new Error(`Unsupported build output: ${path}`);
33
- }
34
- }
35
- };
36
-
37
- for (const directory of directories) {
38
- await collect(resolve(outdir, pathName(directory)), directory);
39
- }
40
-
41
- for (const [path, source] of Object.entries(extraSources)) {
42
- sources.set(pathName(path), source);
43
- }
44
-
45
- const targetsByName = new Map();
46
- for (const target of sources.keys()) {
47
- const name = basename(target);
48
- const targets = targetsByName.get(name) ?? [];
49
- targets.push(target);
50
- targetsByName.set(name, targets);
51
- }
52
- const unusualTargets = [...targetsByName].filter(([name]) => !/^[\w.@+-]+$/.test(name)).flatMap(([, targets]) => targets);
53
- const rewriteLegacy = (input, path) => {
54
- let source = input;
55
- const candidates = new Set(unusualTargets);
56
-
57
- for (const match of input.matchAll(/[/'"=]([\w.@+-]+)/g)) {
58
- for (const target of targetsByName.get(match[1]) ?? []) {
59
- candidates.add(target);
60
- }
61
- }
62
-
63
- for (const target of candidates) {
64
- const reference = posix.relative(posix.dirname(path), target);
65
-
66
- if (!reference) {
67
- continue;
68
- }
69
-
70
- const variants = [reference];
71
-
72
- if (!reference.startsWith('.')) {
73
- variants.push(`./${reference}`);
74
- }
75
-
76
- if (target.startsWith('editor/editor-assets/') || (target.startsWith('editor/') && path.startsWith('editor/'))) {
77
- variants.push(target.slice('editor/'.length));
78
- }
79
-
80
- for (const value of variants) {
81
- for (const quote of ['"', "'"]) {
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)}#`);
85
- }
86
-
87
- source = source.replaceAll(`sourceMappingURL=${value}`, `sourceMappingURL=./${basename(target)}`);
88
- }
89
- }
90
-
91
- return source;
92
- };
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
-
154
- const contentFor = async (path) => {
155
- const content = await readFile(sources.get(path));
156
- return /\.(?:js|css|map)$/.test(basename(path)) ? Buffer.from(rewrite(content.toString(), path)) : content;
157
- };
158
- const outputNames = new Map();
159
- for (const path of sources.keys()) {
160
- if (path === editorEntry) {
161
- continue;
162
- }
163
- const name = basename(path);
164
- const previous = outputNames.get(name);
165
- if (previous !== undefined) {
166
- if (!(await contentFor(path)).equals(await contentFor(previous))) {
167
- throw new Error(`Flat output collision: ${path} and ${previous}`);
168
- }
169
- } else {
170
- outputNames.set(name, path);
171
- }
172
- }
173
-
174
- await mkdir(flatDir);
175
-
176
- for (const [path] of sources) {
177
- const name = basename(path);
178
-
179
- if (path === editorEntry || outputNames.get(name) !== path) {
180
- continue;
181
- }
182
-
183
- await writeFile(resolve(flatDir, name), await contentFor(path), { flag: 'wx' });
184
- }
185
-
186
- if (editorEntry !== undefined) {
187
- await writeFile(resolve(flatDir, 'editor-entry.js'), rewrite(editorScript, editorEntry), { flag: 'wx' });
188
- }
189
-
190
- return { sources, rewrite };
191
- }
192
-
193
- /** Package flattened files, optional SSR files and standalone assets. */
194
- export async function packageFlatRelease({ root, flatDir, entries, ssrDir, ssrNames = [], standaloneAssets = new Map(), aliases = {}, extraFiles = [], retain = [], previousPublic, outputDirectory, removeIntermediates = false }) {
14
+ /** Package prepared files, optional SSR files and standalone assets. */
15
+ export async function packageFlatRelease({ root, flatDir, entries, ssrDir, ssrNames = [], standaloneAssets = new Map(), aliases = {}, extraFiles = [], retain = [], previousPublic, outputDirectory, removeIntermediates = false, removeUnreferencedStyles = false }) {
195
16
  if (!Array.isArray(extraFiles) || !Array.isArray(retain) || (retain.length && !previousPublic)) {
196
17
  throw new TypeError('extraFiles and retain must be arrays; retention requires previousPublic');
197
18
  }
19
+
198
20
  const files = [...extraFiles];
21
+
199
22
  for (const name of retain) {
200
23
  pathName(name);
201
24
  let source = resolve(previousPublic);
25
+
202
26
  for (const part of name.split('/')) {
203
27
  source = resolve(source, part);
28
+
204
29
  if ((await lstat(source)).isSymbolicLink()) {
205
30
  throw new Error(`Symlink in retained path: ${name}`);
206
31
  }
207
32
  }
33
+
208
34
  if (!(await lstat(source)).isFile()) {
209
35
  throw new Error(`Retained path must be an exact file: ${name}`);
210
36
  }
37
+
211
38
  files.push({ source, destination: name });
212
39
  }
213
40
 
@@ -235,15 +62,17 @@ export async function packageFlatRelease({ root, flatDir, entries, ssrDir, ssrNa
235
62
  }
236
63
 
237
64
  const omitted = removeIntermediates ? entries.flatMap((entry) => [entry.style, ...(entry.script !== undefined ? [entry.entry] : [])]) : [];
65
+
238
66
  for (const entry of entries) {
239
67
  if (entry.script === undefined && omitted.includes(entry.entry)) {
240
68
  throw new Error(`Cannot omit a script bootstrap target: ${entry.entry}`);
241
69
  }
242
70
  }
243
- return packageRelease({ root, files, entries, aliases: { ...extraAliases, ...aliases }, outputDirectory, omit: [...new Set(omitted)] });
71
+
72
+ return packageRelease({ root, files, entries, aliases: { ...extraAliases, ...aliases }, outputDirectory, omit: [...new Set(omitted)], removeUnreferencedStyles });
244
73
  }
245
74
 
246
- /** Publish a flat release and synchronize an existing PHP asset cache.
75
+ /** Publish a prepared release and synchronize an existing PHP asset cache.
247
76
  * Staged publication restores the previous public directory on cache failure.
248
77
  * Direct publication writes in public and does not roll back. Missing caches are ignored.
249
78
  */
@@ -342,14 +171,17 @@ export async function publishFlatRelease({ root, wpRoot, release, manifest, vers
342
171
  if (!direct) {
343
172
  await rename(release, publicDir);
344
173
  }
174
+
345
175
  const cachePath = resolve(root, 'eightshift/manifests.json');
346
176
  let cacheExists = false;
347
177
 
348
178
  try {
349
179
  const cacheInfo = await lstat(cachePath);
180
+
350
181
  if (!cacheInfo.isFile() || cacheInfo.isSymbolicLink()) {
351
182
  throw new Error(`Manifest cache must be a regular file: ${cachePath}`);
352
183
  }
184
+
353
185
  cacheExists = true;
354
186
  } catch (error) {
355
187
  if (error.code !== 'ENOENT') {
@@ -362,9 +194,11 @@ export async function publishFlatRelease({ root, wpRoot, release, manifest, vers
362
194
 
363
195
  try {
364
196
  const cacheInfo = await lstat(cachePath);
197
+
365
198
  if (!cacheInfo.isFile() || cacheInfo.isSymbolicLink()) {
366
199
  throw new Error(`Manifest cache must be a regular file: ${cachePath}`);
367
200
  }
201
+
368
202
  const data = JSON.parse(await readFile(cachePath, 'utf8'));
369
203
 
370
204
  if (!data?.assets || Array.isArray(data.assets) || typeof data.assets !== 'object' || !data.assets.assets || Array.isArray(data.assets.assets) || typeof data.assets.assets !== 'object') {
@@ -391,6 +225,7 @@ export async function publishFlatRelease({ root, wpRoot, release, manifest, vers
391
225
  if (direct) {
392
226
  throw error;
393
227
  }
228
+
394
229
  try {
395
230
  await rename(publicDir, release);
396
231
  } catch (rollbackError) {