@eightshift/frontend-libs-tailwind 3.5.0 → 4.0.0-beta.1
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 +9 -0
- package/README.md +142 -0
- package/bun/build.mjs +341 -0
- package/bun/cli.mjs +77 -0
- package/bun/css.mjs +145 -0
- package/bun/discovery.mjs +121 -0
- package/bun/editor.mjs +105 -0
- package/bun/eightshift-css.mjs +66 -0
- package/bun/eightshift-discovery.mjs +135 -0
- package/bun/flat-publication.mjs +343 -0
- package/bun/index.mjs +118 -0
- package/bun/media.mjs +49 -0
- package/bun/preset.mjs +118 -0
- package/bun/publish.mjs +236 -0
- package/bun/release.mjs +182 -0
- package/{webpack/responsive-compiler.mjs → bun/responsive.mjs} +18 -39
- package/bun/ssr.mjs +89 -0
- package/bun/theme-build.mjs +464 -0
- package/bun/theme-discovery.mjs +171 -0
- package/bun/watch.mjs +211 -0
- package/bun/wordpress.mjs +173 -0
- package/package.json +9 -17
- package/bun.lock +0 -1504
- package/webpack/base.mjs +0 -126
- package/webpack/helpers.mjs +0 -55
- package/webpack/index.mjs +0 -46
- package/webpack/production.mjs +0 -60
- package/webpack/project.mjs +0 -50
package/bun/css.mjs
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { compile, Polyfills } from '@tailwindcss/node';
|
|
2
|
+
import { Scanner } from '@tailwindcss/oxide';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
5
|
+
import { createRequire } from 'node:module';
|
|
6
|
+
import { dirname, extname, relative, resolve } from 'node:path';
|
|
7
|
+
import browserslist from 'browserslist';
|
|
8
|
+
import { browserslistToTargets, transform } from 'lightningcss';
|
|
9
|
+
import postcss from 'postcss';
|
|
10
|
+
import valueParser from 'postcss-value-parser';
|
|
11
|
+
|
|
12
|
+
const require = createRequire(import.meta.url);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Compile ordered stylesheets to one CSS file.
|
|
16
|
+
* Paths are relative to projectDir unless absolute. Each files entry is a path
|
|
17
|
+
* or { file, scan, sources, scanFiles, removeSources }; scan enables Tailwind
|
|
18
|
+
* candidate scanning, sources extends its detected sources, scanFiles adds
|
|
19
|
+
* explicit candidate files, and removeSources removes exact @source rules.
|
|
20
|
+
* Assets are copied beside outputFile with content-hashed names.
|
|
21
|
+
*/
|
|
22
|
+
export async function processCss({ projectDir, outputFile, files, production = false, browsers = '>= 0.25%' }) {
|
|
23
|
+
if (!projectDir || !outputFile || !Array.isArray(files) || files.length === 0) {
|
|
24
|
+
throw new Error('processCss requires projectDir, outputFile and a non-empty files array.');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const root = resolve(projectDir);
|
|
28
|
+
const output = resolve(root, outputFile);
|
|
29
|
+
const outdir = dirname(output);
|
|
30
|
+
|
|
31
|
+
await mkdir(outdir, { recursive: true });
|
|
32
|
+
|
|
33
|
+
const rewriteAssets = async (css, base) => {
|
|
34
|
+
const tree = postcss.parse(css);
|
|
35
|
+
const pending = [];
|
|
36
|
+
|
|
37
|
+
tree.walkDecls((declaration) => {
|
|
38
|
+
const value = valueParser(declaration.value);
|
|
39
|
+
const assets = [];
|
|
40
|
+
|
|
41
|
+
value.walk((node) => {
|
|
42
|
+
if (node.type !== 'function' || node.value.toLowerCase() !== 'url') {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const url = valueParser
|
|
47
|
+
.stringify(node.nodes)
|
|
48
|
+
.trim()
|
|
49
|
+
.replace(/^(['"])(.*)\1$/, '$2');
|
|
50
|
+
|
|
51
|
+
if (!url || /^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(url)) {
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
assets.push(
|
|
56
|
+
(async () => {
|
|
57
|
+
const suffixIndex = url.search(/[?#]/);
|
|
58
|
+
const pathname = suffixIndex < 0 ? url : url.slice(0, suffixIndex);
|
|
59
|
+
const suffix = suffixIndex < 0 ? '' : url.slice(suffixIndex);
|
|
60
|
+
let asset = resolve(base, pathname);
|
|
61
|
+
let content;
|
|
62
|
+
|
|
63
|
+
try {
|
|
64
|
+
content = await readFile(asset);
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (error.code !== 'ENOENT' || pathname.startsWith('.')) {
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
asset = require.resolve(pathname, { paths: [base] });
|
|
71
|
+
content = await readFile(asset);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const name = `${createHash('sha256').update(content).digest('hex').slice(0, 20)}${extname(asset)}`;
|
|
75
|
+
|
|
76
|
+
await writeFile(resolve(outdir, name), content);
|
|
77
|
+
node.nodes = [{ type: 'string', quote: '"', value: `./${name}${suffix}` }];
|
|
78
|
+
})(),
|
|
79
|
+
);
|
|
80
|
+
});
|
|
81
|
+
pending.push(
|
|
82
|
+
Promise.all(assets).then(() => {
|
|
83
|
+
declaration.value = value.toString();
|
|
84
|
+
}),
|
|
85
|
+
);
|
|
86
|
+
});
|
|
87
|
+
await Promise.all(pending);
|
|
88
|
+
|
|
89
|
+
return tree.toString();
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const parts = [];
|
|
93
|
+
const dependencies = new Set();
|
|
94
|
+
|
|
95
|
+
for (const entry of files) {
|
|
96
|
+
const options = typeof entry === 'string' ? { file: entry } : entry;
|
|
97
|
+
|
|
98
|
+
if (!options?.file) {
|
|
99
|
+
throw new Error('Each CSS entry requires a file path.');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const file = resolve(root, options.file);
|
|
103
|
+
let input = await readFile(file, 'utf8');
|
|
104
|
+
|
|
105
|
+
dependencies.add(file);
|
|
106
|
+
|
|
107
|
+
for (const source of options.removeSources ?? []) {
|
|
108
|
+
if (!input.includes(source)) {
|
|
109
|
+
throw new Error(`Missing source rule in ${file}: ${source}`);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
input = input.replace(source, '');
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const compiler = await compile(input, {
|
|
116
|
+
base: dirname(file),
|
|
117
|
+
from: file,
|
|
118
|
+
shouldRewriteUrls: true,
|
|
119
|
+
polyfills: Polyfills.All,
|
|
120
|
+
onDependency: (dependency) => dependencies.add(dependency),
|
|
121
|
+
});
|
|
122
|
+
let candidates = [];
|
|
123
|
+
|
|
124
|
+
if (options.scan) {
|
|
125
|
+
const sources = (compiler.root === 'none' ? [] : compiler.root === null ? [{ base: root, pattern: '**/*', negated: false }] : [{ ...compiler.root, negated: false }]).concat(
|
|
126
|
+
compiler.sources,
|
|
127
|
+
(options.sources ?? []).map((source) => ({ ...source, base: resolve(root, source.base ?? '.') })),
|
|
128
|
+
);
|
|
129
|
+
const scanner = new Scanner({ sources });
|
|
130
|
+
const explicit = (options.scanFiles ?? []).map((item) => (typeof item === 'string' ? { file: resolve(root, item), extension: extname(item).slice(1) } : { ...item, file: resolve(root, item.file) }));
|
|
131
|
+
|
|
132
|
+
explicit.forEach(({ file: candidateFile }) => dependencies.add(candidateFile));
|
|
133
|
+
candidates = [...new Set([...scanner.scan(), ...(explicit.length ? scanner.scanFiles(explicit) : [])])];
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
parts.push(`/* ${relative(root, file)} */\n${await rewriteAssets(compiler.build(candidates), dirname(file))}`);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const css = parts.join('\n');
|
|
140
|
+
const result = production ? transform({ filename: output, code: Buffer.from(css), minify: true, targets: browserslistToTargets(browserslist(browsers)) }).code : css;
|
|
141
|
+
|
|
142
|
+
await writeFile(output, result);
|
|
143
|
+
|
|
144
|
+
return { outputFile: output, dependencies: [...dependencies] };
|
|
145
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { mkdir, readdir, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { dirname, relative, resolve, sep } from 'node:path';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Generate Bun-compatible context modules from caller-supplied definitions.
|
|
6
|
+
*
|
|
7
|
+
* `root` is the base for definition directories; `output` is the generated
|
|
8
|
+
* module path. Each definition has `name`, `directory`, `pattern` (RegExp),
|
|
9
|
+
* and optional `mode` (`sync`, the default, or `lazy`). Lazy contexts return
|
|
10
|
+
* promises and do not import their modules until called. CSS is supported only
|
|
11
|
+
* in synchronous contexts, where it is imported for side effects and resolves
|
|
12
|
+
* to an empty object. JSON contexts return parsed values; other synchronous
|
|
13
|
+
* imports return module namespaces. Regenerate after changing source files.
|
|
14
|
+
* Symlinks are skipped. Missing directories are treated as empty contexts.
|
|
15
|
+
*/
|
|
16
|
+
export async function generateDiscovery({ root, output, definitions }) {
|
|
17
|
+
if (typeof root !== 'string' || typeof output !== 'string' || !Array.isArray(definitions)) {
|
|
18
|
+
throw new TypeError('Expected root, output, and definitions');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const baseRoot = resolve(root);
|
|
22
|
+
const outputFile = resolve(baseRoot, output);
|
|
23
|
+
const outputDirectory = dirname(outputFile);
|
|
24
|
+
const names = new Set();
|
|
25
|
+
const imports = [];
|
|
26
|
+
const contexts = [];
|
|
27
|
+
let counter = 0;
|
|
28
|
+
|
|
29
|
+
for (const definition of definitions) {
|
|
30
|
+
const { name, directory, pattern, mode = 'sync' } = definition;
|
|
31
|
+
|
|
32
|
+
if (typeof name !== 'string' || !/^[$A-Z_a-z][$\w]*$/.test(name) || !isValidExportName(name) || name === 'createContext' || /^module\d+$/.test(name) || names.has(name) || typeof directory !== 'string' || !(pattern instanceof RegExp) || !['sync', 'lazy'].includes(mode)) {
|
|
33
|
+
throw new TypeError('Invalid or duplicate discovery definition');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
names.add(name);
|
|
37
|
+
const base = resolve(baseRoot, directory);
|
|
38
|
+
const entries = [];
|
|
39
|
+
|
|
40
|
+
for (const file of await filesIn(base)) {
|
|
41
|
+
const key = `./${file}`;
|
|
42
|
+
|
|
43
|
+
pattern.lastIndex = 0;
|
|
44
|
+
|
|
45
|
+
if (!pattern.test(key)) {
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
let specifier = relative(outputDirectory, resolve(base, file)).split(sep).join('/');
|
|
50
|
+
|
|
51
|
+
if (!specifier.startsWith('./') && !specifier.startsWith('../')) {
|
|
52
|
+
specifier = `./${specifier}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const quoted = JSON.stringify(specifier);
|
|
56
|
+
|
|
57
|
+
if (mode === 'lazy') {
|
|
58
|
+
if (file.endsWith('.css')) {
|
|
59
|
+
throw new TypeError(`Lazy CSS context is not supported: ${name}`);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
entries.push(`[${JSON.stringify(key)}, () => import(${quoted})]`);
|
|
63
|
+
} else if (file.endsWith('.css')) {
|
|
64
|
+
imports.push(`import ${quoted};`);
|
|
65
|
+
entries.push(`[${JSON.stringify(key)}, {}]`);
|
|
66
|
+
} else {
|
|
67
|
+
const variable = `module${counter++}`;
|
|
68
|
+
|
|
69
|
+
imports.push(file.endsWith('.json') ? `import ${variable} from ${quoted};` : `import * as ${variable} from ${quoted};`);
|
|
70
|
+
entries.push(`[${JSON.stringify(key)}, ${variable}]`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
contexts.push(`export const ${name} = createContext([${entries.join(',\n')}], ${mode === 'lazy'});`);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const source = `// Generated by Bun discovery; do not edit.\n${imports.join('\n')}\n\nfunction createContext(entries, lazy) {\n\tconst modules = new Map(entries);\n\tconst context = (key) => {\n\t\tif (!modules.has(key)) {\n\t\t\tconst error = new Error(\`Cannot find module '\${key}'\`);\n\t\t\terror.code = 'MODULE_NOT_FOUND';\n\t\t\tif (lazy) return Promise.reject(error);\n\t\t\tthrow error;\n\t\t}\n\t\treturn lazy ? modules.get(key)() : modules.get(key);\n\t};\n\tcontext.keys = () => [...modules.keys()];\n\treturn context;\n}\n\n${contexts.join('\n\n')}\n`;
|
|
78
|
+
|
|
79
|
+
await mkdir(outputDirectory, { recursive: true });
|
|
80
|
+
await writeFile(outputFile, source);
|
|
81
|
+
|
|
82
|
+
return { output: outputFile, contexts: definitions.length };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function isValidExportName(name) {
|
|
86
|
+
try {
|
|
87
|
+
new Function(`"use strict"; let ${name};`);
|
|
88
|
+
|
|
89
|
+
return true;
|
|
90
|
+
} catch {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function filesIn(directory, prefix = '') {
|
|
96
|
+
let entries;
|
|
97
|
+
|
|
98
|
+
try {
|
|
99
|
+
entries = await readdir(directory, { withFileTypes: true });
|
|
100
|
+
} catch (error) {
|
|
101
|
+
if (error.code === 'ENOENT') {
|
|
102
|
+
return [];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
throw error;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const files = [];
|
|
109
|
+
|
|
110
|
+
for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
|
|
111
|
+
const name = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
112
|
+
|
|
113
|
+
if (entry.isDirectory()) {
|
|
114
|
+
files.push(...(await filesIn(resolve(directory, entry.name), name)));
|
|
115
|
+
} else if (entry.isFile()) {
|
|
116
|
+
files.push(name);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return files;
|
|
121
|
+
}
|
package/bun/editor.mjs
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
3
|
+
import { eightshiftDiscovery, editorLazyImports } from './eightshift-discovery.mjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Build a synchronous classic entry and lazy ESM chunks. Discovery, when
|
|
7
|
+
* supplied, is composed with lazy rewriting so both can process one file.
|
|
8
|
+
* Other onLoad plugins that consume the same file must compose the rewrite.
|
|
9
|
+
* Editor output must not require extracted CSS or other emitted assets.
|
|
10
|
+
*/
|
|
11
|
+
export async function buildEditor({ root, directory, entry, buildOptions = {}, plugins = [], chunkDir = 'editor-chunks', filename = 'editor.js', scriptUrlIdentifier = '__eightshiftEditorScriptUrl', discovery, lazy = {} }) {
|
|
12
|
+
const inside = (path) => {
|
|
13
|
+
if (typeof path !== 'string' || !path || isAbsolute(path)) {
|
|
14
|
+
throw new TypeError('Editor output paths must be relative');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const output = resolve(directory, path);
|
|
18
|
+
const location = relative(directory, output);
|
|
19
|
+
|
|
20
|
+
if (!location || location === '..' || location.startsWith(`..${sep}`) || isAbsolute(location)) {
|
|
21
|
+
throw new Error(`Editor output escapes entry directory: ${path}`);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
return output;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
if (filename.includes('/') || filename.includes('\\')) {
|
|
28
|
+
throw new TypeError('Editor filename must be a basename');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const entryOutput = inside(filename);
|
|
32
|
+
const chunkOutput = inside(chunkDir);
|
|
33
|
+
|
|
34
|
+
if (relative(chunkOutput, entryOutput) === '' || (!relative(chunkOutput, entryOutput).startsWith(`..${sep}`) && relative(chunkOutput, entryOutput) !== '..')) {
|
|
35
|
+
throw new Error('Editor entry cannot be inside its chunk directory');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (buildOptions.sourcemap !== undefined && !['none', 'external'].includes(buildOptions.sourcemap)) {
|
|
39
|
+
throw new TypeError('Editor sourcemap must be "none" or "external"');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const chunks = new Map();
|
|
43
|
+
const lazyImports = editorLazyImports({ ...lazy, root, chunks, chunkDir, scriptUrlIdentifier });
|
|
44
|
+
const discoveryPlugin = discovery ? eightshiftDiscovery({ ...discovery, root, outputDir: inside(discovery.outputDir ?? 'discovery'), transformSource: (source, path) => lazyImports.transformSource(discovery.transformSource ? discovery.transformSource(source, path) : source, path) }) : undefined;
|
|
45
|
+
const sourcemap = buildOptions.sourcemap === 'external';
|
|
46
|
+
const options = {
|
|
47
|
+
target: 'browser',
|
|
48
|
+
...buildOptions,
|
|
49
|
+
loader: { ...buildOptions.loader, '.svg': 'text' },
|
|
50
|
+
sourcemap: sourcemap ? 'external' : 'none',
|
|
51
|
+
entrypoints: [resolve(root, entry)],
|
|
52
|
+
format: 'iife',
|
|
53
|
+
splitting: false,
|
|
54
|
+
write: false,
|
|
55
|
+
plugins: [...(discoveryPlugin ? [discoveryPlugin] : []), ...plugins, lazyImports.plugin],
|
|
56
|
+
};
|
|
57
|
+
const paths = [];
|
|
58
|
+
const compile = async (target, format) => {
|
|
59
|
+
const result = await Bun.build({ ...options, entrypoints: [target], format });
|
|
60
|
+
|
|
61
|
+
if (!result.success) {
|
|
62
|
+
throw new AggregateError(result.logs, `Editor build failed: ${target}`);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const entries = result.outputs.filter((output) => output.kind === 'entry-point');
|
|
66
|
+
const maps = result.outputs.filter((output) => output.kind === 'sourcemap');
|
|
67
|
+
if (entries.length !== 1 || maps.length !== (sourcemap ? 1 : 0) || result.outputs.length !== entries.length + maps.length) {
|
|
68
|
+
throw new Error(`Unexpected editor assets: ${target}`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const map = sourcemap ? JSON.parse(await maps[0].text()) : undefined;
|
|
72
|
+
if (map) {
|
|
73
|
+
map.mappings = `;${map.mappings}`;
|
|
74
|
+
}
|
|
75
|
+
return { source: await entries[0].text(), map };
|
|
76
|
+
};
|
|
77
|
+
const write = async (path, source) => {
|
|
78
|
+
await mkdir(dirname(path), { recursive: true });
|
|
79
|
+
await writeFile(path, source);
|
|
80
|
+
paths.push(path);
|
|
81
|
+
};
|
|
82
|
+
const entryBuild = await compile(resolve(root, entry), 'iife');
|
|
83
|
+
const entryMap = `${basename(entryOutput)}.map`;
|
|
84
|
+
await write(entryOutput, `((${scriptUrlIdentifier}) => {\n${entryBuild.source}\n})(document.currentScript.src);\n${entryBuild.map ? `//# sourceMappingURL=${entryMap}\n` : ''}`);
|
|
85
|
+
if (entryBuild.map) {
|
|
86
|
+
await write(`${entryOutput}.map`, JSON.stringify(entryBuild.map));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
for (const [target, name] of chunks) {
|
|
90
|
+
const output = inside(`${chunkDir}/${name}`);
|
|
91
|
+
let entryPath = relative(dirname(output), entryOutput).split(sep).join('/');
|
|
92
|
+
|
|
93
|
+
if (!entryPath.startsWith('.')) {
|
|
94
|
+
entryPath = `./${entryPath}`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const chunk = await compile(target, 'esm');
|
|
98
|
+
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` : ''}`);
|
|
99
|
+
if (chunk.map) {
|
|
100
|
+
await write(`${output}.map`, JSON.stringify(chunk.map));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return { entry: entryOutput, paths };
|
|
105
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { glob } from 'glob';
|
|
3
|
+
import { processCss } from './css.mjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Build the ordered CSS inputs used by migrated Eightshift v3 themes.
|
|
7
|
+
* All paths and glob patterns are relative to projectDir unless absolute.
|
|
8
|
+
* Override paths, groups, manifestGlob or scan exclusions for another layout.
|
|
9
|
+
* responsiveFile replaces the generated @source in the Tailwind entry.
|
|
10
|
+
*/
|
|
11
|
+
export async function eightshiftCssEntries({
|
|
12
|
+
projectDir,
|
|
13
|
+
surface,
|
|
14
|
+
responsiveFile,
|
|
15
|
+
blocksDir = 'src/Blocks',
|
|
16
|
+
manifestGlob = 'src/**/manifest.json',
|
|
17
|
+
tailwindFile = `tailwind-${surface}.css`,
|
|
18
|
+
colorThemesFile = 'color-themes.css',
|
|
19
|
+
applicationFile = surface === 'admin' ? `${blocksDir}/assets/styles/application-admin.css` : `${blocksDir}/assets/styles/application-blocks-${surface}.css`,
|
|
20
|
+
groups = surface === 'admin' ? ['components', 'custom'] : ['components', 'custom', 'wrapper'],
|
|
21
|
+
scanExclusions = ['.bun-pilot/**', 'es-tw-*-classes.txt'],
|
|
22
|
+
responsiveSource = `@source './es-tw-${surface}-classes.txt';`,
|
|
23
|
+
} = {}) {
|
|
24
|
+
if (!projectDir || !['frontend', 'editor', 'admin'].includes(surface)) {
|
|
25
|
+
throw new TypeError('projectDir and a valid CSS surface are required');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const root = resolve(projectDir);
|
|
29
|
+
const styles = [];
|
|
30
|
+
|
|
31
|
+
for (const group of groups) {
|
|
32
|
+
const matches = await glob(`**/*styles-${surface}.css`, { cwd: resolve(root, blocksDir, group), absolute: true, nodir: true, follow: false });
|
|
33
|
+
|
|
34
|
+
styles.push(...matches.sort());
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (surface === 'admin') {
|
|
38
|
+
return [applicationFile, ...styles];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (!responsiveFile) {
|
|
42
|
+
throw new TypeError('responsiveFile is required for frontend and editor CSS');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const manifests = (await glob(manifestGlob, { cwd: root, absolute: true, nodir: true, follow: false })).sort();
|
|
46
|
+
|
|
47
|
+
return [
|
|
48
|
+
{
|
|
49
|
+
file: tailwindFile,
|
|
50
|
+
scan: true,
|
|
51
|
+
removeSources: responsiveSource ? [responsiveSource] : [],
|
|
52
|
+
sources: scanExclusions.map((pattern) => ({ pattern, negated: true })),
|
|
53
|
+
scanFiles: [responsiveFile, ...manifests],
|
|
54
|
+
},
|
|
55
|
+
colorThemesFile,
|
|
56
|
+
applicationFile,
|
|
57
|
+
...styles,
|
|
58
|
+
];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Compile one surface. Options accepted by eightshiftCssEntries are forwarded. */
|
|
62
|
+
export async function processEightshiftCss({ outputFile, production = false, browsers, ...options } = {}) {
|
|
63
|
+
const files = await eightshiftCssEntries(options);
|
|
64
|
+
|
|
65
|
+
return processCss({ projectDir: options.projectDir, outputFile, files, production, browsers });
|
|
66
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { realpathSync } from 'node:fs';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
import { dirname, resolve, relative, sep } from 'node:path';
|
|
6
|
+
import { generateDiscovery } from './discovery.mjs';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Migrate literal webpack require.context calls in selected source files.
|
|
10
|
+
* Generated modules live in outputDir and must be regenerated on rebuild.
|
|
11
|
+
* Set lazyContexts to match contexts whose callers expect promises, and
|
|
12
|
+
* omitContexts to match contexts handled separately (for example CSS).
|
|
13
|
+
* Template-literal imports and nonliteral require.context calls are not rewritten.
|
|
14
|
+
*/
|
|
15
|
+
export function eightshiftDiscovery({ root, outputDir, filter = /\.[cm]?jsx?$/, lazyContexts = () => false, omitContexts = () => false, transformSource = (source) => source } = {}) {
|
|
16
|
+
if (!root || !outputDir) {
|
|
17
|
+
throw new TypeError('root and outputDir are required');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
outputDir = resolve(root, outputDir);
|
|
21
|
+
root = realpathSync(root);
|
|
22
|
+
|
|
23
|
+
return {
|
|
24
|
+
name: 'eightshift-discovery',
|
|
25
|
+
setup(builder) {
|
|
26
|
+
builder.onLoad({ filter }, async ({ path }) => {
|
|
27
|
+
if (!path.startsWith(`${root}${sep}`)) {
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const source = await readFile(path, 'utf8');
|
|
32
|
+
|
|
33
|
+
if (!source.includes('require.context')) {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const pattern = /require\.context\(\s*(['"])([^'"\n]+)\1\s*,\s*(true|false)\s*,\s*\/(?!\*)(?!\/)((?:\\.|[^/\n])+)\/([dgimsuvy]*)\s*(?:,\s*(['"])(sync|lazy)\6\s*)?\)/g;
|
|
38
|
+
const matches = [...source.matchAll(pattern)];
|
|
39
|
+
|
|
40
|
+
if (!matches.length) {
|
|
41
|
+
throw new Error(`Unsupported require.context in ${path}`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const definitions = [];
|
|
45
|
+
let contents = '';
|
|
46
|
+
let offset = 0;
|
|
47
|
+
|
|
48
|
+
for (const match of matches) {
|
|
49
|
+
const [, , directory, recursive, expression, flags, , webpackMode] = match;
|
|
50
|
+
|
|
51
|
+
if (recursive !== 'true') {
|
|
52
|
+
throw new Error(`Nonrecursive require.context is unsupported in ${path}`);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const context = { path, directory, pattern: new RegExp(expression, flags), mode: webpackMode || 'sync' };
|
|
56
|
+
const name = `context${definitions.length}`;
|
|
57
|
+
|
|
58
|
+
contents += source.slice(offset, match.index);
|
|
59
|
+
|
|
60
|
+
if (omitContexts(context)) {
|
|
61
|
+
contents += 'Object.assign(() => ({}), { keys: () => [] })';
|
|
62
|
+
} else {
|
|
63
|
+
definitions.push({ name, directory: resolve(dirname(path), directory), pattern: context.pattern, mode: lazyContexts(context) ? 'lazy' : context.mode });
|
|
64
|
+
contents += name;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
offset = match.index + match[0].length;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
contents += source.slice(offset);
|
|
71
|
+
|
|
72
|
+
if (contents.includes('require.context')) {
|
|
73
|
+
throw new Error(`Unsupported require.context remains in ${path}`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (definitions.length) {
|
|
77
|
+
const id = createHash('sha256').update(relative(root, path)).digest('hex').slice(0, 20);
|
|
78
|
+
const output = resolve(outputDir, `${id}.mjs`);
|
|
79
|
+
|
|
80
|
+
await generateDiscovery({ root, output, definitions });
|
|
81
|
+
contents = `import { ${definitions.map(({ name }) => name).join(', ')} } from ${JSON.stringify(output)};\n${contents}`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
contents = transformSource(contents, path);
|
|
85
|
+
|
|
86
|
+
return { contents, loader: 'jsx', resolveDir: dirname(path) };
|
|
87
|
+
});
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Rewrite literal relative dynamic imports for a synchronous IIFE editor build.
|
|
93
|
+
* Build each collected target as an ESM entry with the same plugin, then wrap
|
|
94
|
+
* the IIFE in a function receiving scriptUrlIdentifier from currentScript.src.
|
|
95
|
+
* Chunk URLs are relative to that script. The caller owns chunk output/builds.
|
|
96
|
+
* Pass transformSource to eightshiftDiscovery to compose both onLoad hooks.
|
|
97
|
+
*/
|
|
98
|
+
export function editorLazyImports({ root, chunks, chunkDir = 'editor-chunks', scriptUrlIdentifier = '__eightshiftEditorScriptUrl', filter = /\.[cm]?jsx?$/, include = (path) => !path.split(sep).includes('node_modules') } = {}) {
|
|
99
|
+
if (!root || !(chunks instanceof Map) || !/^[$A-Z_a-z][$\w]*$/.test(scriptUrlIdentifier)) {
|
|
100
|
+
throw new TypeError('Expected root, chunks Map and valid script URL identifier');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
root = realpathSync(resolve(root));
|
|
104
|
+
const require = createRequire(import.meta.url);
|
|
105
|
+
const transformSource = (source, path) =>
|
|
106
|
+
!include(path)
|
|
107
|
+
? source
|
|
108
|
+
: source.replace(/import\(\s*(?:\/\*[\s\S]*?\*\/\s*)?(['"])(\.[^'"\n]+)\1\s*\)/g, (_match, _quote, specifier) => {
|
|
109
|
+
const target = require.resolve(resolve(dirname(path), specifier));
|
|
110
|
+
const name = `${createHash('sha256').update(relative(root, target)).digest('hex').slice(0, 20)}.js`;
|
|
111
|
+
|
|
112
|
+
chunks.set(target, name);
|
|
113
|
+
|
|
114
|
+
return `import(new URL(${JSON.stringify(`${chunkDir}/${name}`)}, ${scriptUrlIdentifier}).href)`;
|
|
115
|
+
});
|
|
116
|
+
const plugin = {
|
|
117
|
+
name: 'eightshift-editor-lazy-imports',
|
|
118
|
+
setup(builder) {
|
|
119
|
+
builder.onLoad({ filter }, async ({ path }) => {
|
|
120
|
+
if (!path.startsWith(`${root}${sep}`)) {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const source = await readFile(path, 'utf8');
|
|
125
|
+
const contents = transformSource(source, path);
|
|
126
|
+
|
|
127
|
+
if (contents !== source) {
|
|
128
|
+
return { contents, loader: 'jsx', resolveDir: dirname(path) };
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
return { plugin, transformSource };
|
|
135
|
+
}
|