@eightshift/frontend-libs-tailwind 3.4.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.
Files changed (40) hide show
  1. package/.github/CODEOWNERS +1 -1
  2. package/CHANGELOG.md +19 -1
  3. package/README.md +187 -0
  4. package/bin/tw-sweep.mjs +281 -0
  5. package/bun/build.mjs +341 -0
  6. package/bun/cli.mjs +77 -0
  7. package/bun/css.mjs +145 -0
  8. package/bun/discovery.mjs +121 -0
  9. package/bun/editor.mjs +105 -0
  10. package/bun/eightshift-css.mjs +66 -0
  11. package/bun/eightshift-discovery.mjs +135 -0
  12. package/bun/flat-publication.mjs +343 -0
  13. package/bun/index.mjs +118 -0
  14. package/bun/media.mjs +49 -0
  15. package/bun/preset.mjs +118 -0
  16. package/bun/publish.mjs +236 -0
  17. package/bun/release.mjs +182 -0
  18. package/{webpack/responsive-compiler.mjs → bun/responsive.mjs} +18 -39
  19. package/bun/ssr.mjs +89 -0
  20. package/bun/theme-build.mjs +464 -0
  21. package/bun/theme-discovery.mjs +171 -0
  22. package/bun/watch.mjs +211 -0
  23. package/bun/wordpress.mjs +173 -0
  24. package/linters/oxlint.config.mjs +65 -0
  25. package/linters/tw-ignore.mjs +45 -0
  26. package/linters/tw-sweep-extract.mjs +545 -0
  27. package/package.json +16 -16
  28. package/test/fixtures/theme/src/Blocks/custom/card/card.php +23 -0
  29. package/test/fixtures/theme/src/Blocks/custom/card/manifest.json +13 -0
  30. package/test/fixtures/theme/src/Plugins/Forms.php +15 -0
  31. package/test/fixtures/theme/src/card.js +2 -0
  32. package/test/fixtures/theme/tailwind.css +6 -0
  33. package/test/fixtures/theme/tw-ignore.json +1 -0
  34. package/test/tw-sweep.test.mjs +119 -0
  35. package/bun.lock +0 -1433
  36. package/webpack/base.mjs +0 -126
  37. package/webpack/helpers.mjs +0 -55
  38. package/webpack/index.mjs +0 -46
  39. package/webpack/production.mjs +0 -60
  40. package/webpack/project.mjs +0 -50
package/bun/build.mjs ADDED
@@ -0,0 +1,341 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { lstat, mkdir, readFile, readdir, rename, rmdir, unlink, writeFile } from 'node:fs/promises';
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { generateDiscovery } from './discovery.mjs';
5
+ import { generateResponsiveClasses } from './responsive.mjs';
6
+ import { buildEditor } from './editor.mjs';
7
+ import { wordpressPlugin } from './wordpress.mjs';
8
+
9
+ const markerName = '.eightshift-bun-build';
10
+ const markerContents = 'eightshift-bun-build-v1\n';
11
+
12
+ async function rejectSymlinkPath(path, root) {
13
+ const boundary = root && resolve(root);
14
+ const location = boundary && relative(boundary, path);
15
+ const withinRoot = boundary && (!location || (!isAbsolute(location) && location !== '..' && !location.startsWith(`..${sep}`)));
16
+ const parent = dirname(path);
17
+
18
+ if (parent !== path && (!withinRoot || path !== boundary)) {
19
+ await rejectSymlinkPath(parent, root);
20
+ }
21
+
22
+ try {
23
+ if ((await lstat(path)).isSymbolicLink()) {
24
+ throw new Error(`Symlink is not allowed: ${path}`);
25
+ }
26
+ } catch (error) {
27
+ if (error.code !== 'ENOENT') {
28
+ throw error;
29
+ }
30
+ }
31
+ }
32
+
33
+ async function inspectTree(directory) {
34
+ for (const item of await readdir(directory, { withFileTypes: true })) {
35
+ const path = join(directory, item.name);
36
+ const info = await lstat(path);
37
+
38
+ if (info.isSymbolicLink()) {
39
+ throw new Error(`Symlink is not allowed: ${path}`);
40
+ }
41
+
42
+ if (info.isDirectory()) {
43
+ await inspectTree(path);
44
+ } else if (!info.isFile()) {
45
+ throw new Error(`Unsupported output type: ${path}`);
46
+ }
47
+ }
48
+ }
49
+
50
+ async function removeTree(directory) {
51
+ for (const item of await readdir(directory, { withFileTypes: true })) {
52
+ const path = join(directory, item.name);
53
+ const info = await lstat(path);
54
+
55
+ if (info.isDirectory() && !info.isSymbolicLink()) {
56
+ await removeTree(path);
57
+ } else {
58
+ await unlink(path);
59
+ }
60
+ }
61
+
62
+ await rmdir(directory);
63
+ }
64
+
65
+ export async function clearBuildDirectory(directory, root) {
66
+ await rejectSymlinkPath(resolve(directory), root);
67
+
68
+ try {
69
+ const info = await lstat(directory);
70
+ if (!info.isDirectory() || info.isSymbolicLink()) {
71
+ throw new Error(`Output must be a real directory: ${directory}`);
72
+ }
73
+ await inspectTree(directory);
74
+ await removeTree(directory);
75
+ } catch (error) {
76
+ if (error.code !== 'ENOENT') {
77
+ throw error;
78
+ }
79
+ }
80
+ }
81
+
82
+ async function assertOwned(directory) {
83
+ let info;
84
+
85
+ try {
86
+ info = await lstat(directory);
87
+ } catch (error) {
88
+ if (error.code === 'ENOENT') {
89
+ return false;
90
+ }
91
+
92
+ throw error;
93
+ }
94
+
95
+ if (!info.isDirectory() || info.isSymbolicLink()) {
96
+ throw new Error(`Output must be a real directory: ${directory}`);
97
+ }
98
+
99
+ const marker = join(directory, markerName);
100
+ let markerInfo;
101
+
102
+ try {
103
+ markerInfo = await lstat(marker);
104
+ } catch (error) {
105
+ if (error.code === 'ENOENT') {
106
+ throw new Error(`Refusing to replace unowned output: ${directory}`);
107
+ }
108
+
109
+ throw error;
110
+ }
111
+
112
+ if (!markerInfo.isFile() || markerInfo.isSymbolicLink() || (await readFile(marker, 'utf8')) !== markerContents) {
113
+ throw new Error(`Refusing to replace unowned output: ${directory}`);
114
+ }
115
+
116
+ await inspectTree(directory);
117
+
118
+ return true;
119
+ }
120
+
121
+ /**
122
+ * Build independent browser ESM entries into a staged directory.
123
+ *
124
+ * entries maps logical names to source paths relative to root. Each entry gets
125
+ * its own directory, chunks and .asset.json, so dependencies include its lazy
126
+ * graph without leaking dependencies from other entries. Callers must load the
127
+ * entry as a module. discovery definitions generate a module at discovery.output
128
+ * relative to the staging directory. responsive options are passed to
129
+ * generateResponsiveClasses with outputs inside staging. css is an optional
130
+ * async callback receiving { root, outdir, discovery, responsive }; it may emit
131
+ * additional CSS/assets into staging. buildOptions can override target, format,
132
+ * splitting, naming, plugins, loaders and defines. Entry points, output directory
133
+ * and writing are controlled by this API to protect staged publication.
134
+ *
135
+ * editor optionally selects a synchronous classic entry with lazy ESM chunks.
136
+ * Existing output is replaced only if it contains this API's ownership marker
137
+ * and every build and callback succeeds. Output trees must not contain symlinks.
138
+ * `direct: true` writes to a fresh output directory without staging or rollback.
139
+ * Generated discovery and responsive files are included in the published tree.
140
+ */
141
+ export async function build({ root = process.cwd(), outdir, entries, wpRoot, wordpress = true, discovery, responsive, css, editor, buildOptions = {}, direct = false } = {}) {
142
+ root = resolve(root);
143
+
144
+ if (typeof outdir !== 'string' || !outdir || !entries || typeof entries !== 'object' || Array.isArray(entries) || !Object.keys(entries).length) {
145
+ throw new TypeError('outdir and at least one named entry are required');
146
+ }
147
+
148
+ outdir = resolve(root, outdir);
149
+ const rootFromOutput = relative(outdir, root);
150
+
151
+ if (!rootFromOutput || (!isAbsolute(rootFromOutput) && rootFromOutput !== '..' && !rootFromOutput.startsWith(`..${sep}`))) {
152
+ throw new Error('outdir must not contain the project root');
153
+ }
154
+
155
+ await rejectSymlinkPath(outdir, root);
156
+ await assertOwned(outdir);
157
+
158
+ for (const [name, entry] of Object.entries(entries)) {
159
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(name) || typeof entry !== 'string' || !entry) {
160
+ throw new TypeError(`Invalid entry: ${name}`);
161
+ }
162
+ }
163
+
164
+ if (editor && (!editor.entry || !Object.hasOwn(entries, editor.entry))) {
165
+ throw new TypeError('editor.entry must name an entry');
166
+ }
167
+
168
+ if (css !== undefined && typeof css !== 'function') {
169
+ throw new TypeError('css must be a function');
170
+ }
171
+
172
+ const parent = dirname(outdir);
173
+
174
+ await mkdir(parent, { recursive: true });
175
+ const stage = direct ? outdir : join(parent, `.${basename(outdir)}-stage-${randomUUID()}`);
176
+ const backup = join(parent, `.${basename(outdir)}-backup-${randomUUID()}`);
177
+
178
+ await mkdir(stage);
179
+ let backedUp = false;
180
+ let published = false;
181
+
182
+ try {
183
+ const insideStage = (path) => {
184
+ if (typeof path !== 'string' || !path || isAbsolute(path)) {
185
+ throw new TypeError('Generated output paths must be relative to staging');
186
+ }
187
+
188
+ const file = resolve(stage, path);
189
+ const location = relative(stage, file);
190
+
191
+ if (!location || location === '..' || location.startsWith(`..${sep}`) || isAbsolute(location)) {
192
+ throw new Error(`Output escapes staging: ${path}`);
193
+ }
194
+
195
+ return file;
196
+ };
197
+ let generatedDiscovery;
198
+
199
+ if (discovery) {
200
+ generatedDiscovery = insideStage(discovery.output);
201
+ await generateDiscovery({ root, ...discovery, output: generatedDiscovery });
202
+ }
203
+
204
+ let generatedResponsive;
205
+
206
+ if (responsive) {
207
+ generatedResponsive = {
208
+ frontend: insideStage(responsive.output?.frontend ?? 'responsive/frontend.txt'),
209
+ editor: insideStage(responsive.output?.editor ?? 'responsive/editor.txt'),
210
+ };
211
+ await Promise.all(Object.values(generatedResponsive).map((file) => mkdir(dirname(file), { recursive: true })));
212
+ generateResponsiveClasses({ ...responsive, projectDir: root, output: generatedResponsive });
213
+ }
214
+
215
+ if (css) {
216
+ await css({ root, outdir: stage, discovery: generatedDiscovery, responsive: generatedResponsive });
217
+ }
218
+
219
+ await rejectSymlinkPath(stage, root);
220
+ await inspectTree(stage);
221
+ const manifest = {};
222
+
223
+ for (const [name, entry] of Object.entries(entries)) {
224
+ const directory = join(stage, name);
225
+ const wp = wordpress ? wordpressPlugin({ projectRoot: root, wpRoot: wpRoot && resolve(root, wpRoot) }) : undefined;
226
+
227
+ if (editor?.entry === name) {
228
+ const { entry: _entry, ...editorOptions } = editor;
229
+ const built = await buildEditor({ ...editorOptions, root, directory, entry, buildOptions, plugins: [...(buildOptions.plugins ?? []), ...(wp ? [wp.plugin] : [])] });
230
+
231
+ await inspectTree(stage);
232
+ const digest = createHash('sha256');
233
+
234
+ for (const path of built.paths.map((path) => relative(directory, path).replaceAll('\\', '/')).sort()) {
235
+ const bytes = await readFile(join(directory, path));
236
+
237
+ digest
238
+ .update(`${Buffer.byteLength(path)}:`)
239
+ .update(path)
240
+ .update(`${bytes.length}:`)
241
+ .update(bytes);
242
+ }
243
+
244
+ const metadata = { dependencies: [...(wp?.dependencies ?? [])].sort(), version: digest.digest('hex') };
245
+
246
+ await writeFile(join(directory, `${name}.asset.json`), `${JSON.stringify(metadata, null, 2)}\n`);
247
+ manifest[name] = { entry: `${name}/${relative(directory, built.entry).replaceAll('\\', '/')}`, styles: [], ...metadata };
248
+ continue;
249
+ }
250
+
251
+ const result = await Bun.build({
252
+ target: 'browser',
253
+ format: 'esm',
254
+ splitting: true,
255
+ naming: { entry: '[name]-[hash].[ext]', chunk: 'chunks/[name]-[hash].[ext]', asset: 'assets/[name]-[hash].[ext]' },
256
+ ...buildOptions,
257
+ entrypoints: [resolve(root, entry)],
258
+ outdir: directory,
259
+ write: true,
260
+ plugins: [...(buildOptions.plugins ?? []), ...(wp ? [wp.plugin] : [])],
261
+ });
262
+
263
+ if (!result.success) {
264
+ throw new AggregateError(result.logs, `Bun build failed for ${name}`);
265
+ }
266
+
267
+ await rejectSymlinkPath(stage, root);
268
+ await inspectTree(stage);
269
+ const output = result.outputs.filter((item) => item.kind === 'entry-point');
270
+
271
+ if (output.length !== 1) {
272
+ throw new Error(`Expected one output for ${name}, got ${output.length}`);
273
+ }
274
+
275
+ const digest = createHash('sha256');
276
+ const files = result.outputs.map((item) => ({ item, path: relative(directory, item.path).replaceAll('\\', '/') })).sort((a, b) => a.path.localeCompare(b.path));
277
+
278
+ for (const { item, path } of files) {
279
+ if (!path || path.startsWith('../') || isAbsolute(path)) {
280
+ throw new Error(`Unexpected Bun output path: ${item.path}`);
281
+ }
282
+
283
+ const bytes = await readFile(item.path);
284
+
285
+ digest
286
+ .update(`${Buffer.byteLength(path)}:`)
287
+ .update(path)
288
+ .update(`${bytes.length}:`)
289
+ .update(bytes);
290
+ }
291
+
292
+ const metadata = { dependencies: [...(wp?.dependencies ?? [])].sort(), version: digest.digest('hex') };
293
+
294
+ await writeFile(join(directory, `${name}.asset.json`), `${JSON.stringify(metadata, null, 2)}\n`);
295
+ manifest[name] = { entry: `${name}/${relative(directory, output[0].path).replaceAll('\\', '/')}`, styles: files.filter(({ path }) => path.endsWith('.css')).map(({ path }) => `${name}/${path}`), ...metadata };
296
+ }
297
+
298
+ await inspectTree(stage);
299
+ await writeFile(join(stage, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
300
+ await writeFile(join(stage, markerName), markerContents, { flag: 'wx' });
301
+ if (direct) {
302
+ published = true;
303
+ return { outdir, entries: manifest };
304
+ }
305
+
306
+ await rejectSymlinkPath(outdir, root);
307
+
308
+ if (await assertOwned(outdir)) {
309
+ await rename(outdir, backup);
310
+ backedUp = true;
311
+ }
312
+
313
+ try {
314
+ await rename(stage, outdir);
315
+ published = true;
316
+ } catch (error) {
317
+ if (backedUp) {
318
+ await rename(backup, outdir);
319
+ backedUp = false;
320
+ }
321
+
322
+ throw error;
323
+ }
324
+
325
+ if (backedUp) {
326
+ try {
327
+ await removeTree(backup);
328
+ } catch (error) {
329
+ console.warn(`Build published, but backup cleanup failed at ${backup}:`, error);
330
+ }
331
+ }
332
+
333
+ return { outdir, entries: manifest };
334
+ } finally {
335
+ if (!published) {
336
+ await removeTree(stage);
337
+ }
338
+ }
339
+ }
340
+
341
+ export { generateDiscovery, generateResponsiveClasses, wordpressPlugin };
package/bun/cli.mjs ADDED
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env bun
2
+ import { delimiter, resolve } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+
5
+ const projectModules = resolve('node_modules');
6
+
7
+ if (!(process.env.NODE_PATH ?? '').split(delimiter).includes(projectModules)) {
8
+ const child = Bun.spawn([process.execPath, ...process.argv.slice(1)], {
9
+ cwd: process.cwd(),
10
+ env: { ...process.env, NODE_PATH: [projectModules, process.env.NODE_PATH].filter(Boolean).join(delimiter) },
11
+ stdin: 'inherit',
12
+ stdout: 'inherit',
13
+ stderr: 'inherit',
14
+ });
15
+
16
+ const forwardInt = () => child.kill('SIGINT');
17
+ const forwardTerm = () => child.kill('SIGTERM');
18
+ process.on('SIGINT', forwardInt);
19
+ process.on('SIGTERM', forwardTerm);
20
+ const exitCode = await child.exited;
21
+ process.removeListener('SIGINT', forwardInt);
22
+ process.removeListener('SIGTERM', forwardTerm);
23
+ process.exit(exitCode);
24
+ }
25
+
26
+ const args = process.argv.slice(2);
27
+ const command = args.shift();
28
+
29
+ if (!['build', 'watch'].includes(command)) {
30
+ throw new Error('Usage: eightshift-build <build|watch> [--config path] [--sourcemaps]');
31
+ }
32
+
33
+ let config = 'eightshift.build.mjs';
34
+ const options = { sourcemaps: false };
35
+
36
+ while (args.length) {
37
+ const arg = args.shift();
38
+
39
+ if (arg === '--config') {
40
+ config = args.shift();
41
+
42
+ if (!config || config.startsWith('--')) {
43
+ throw new Error('--config requires a path');
44
+ }
45
+ } else if (arg === '--sourcemaps') {
46
+ options.sourcemaps = true;
47
+ } else {
48
+ throw new Error(`Unknown option: ${arg}`);
49
+ }
50
+ }
51
+
52
+ const { default: definition } = await import(pathToFileURL(resolve(config)).href);
53
+
54
+ if (!definition || typeof definition.build !== 'function' || typeof definition.watch !== 'function') {
55
+ throw new TypeError('Config default export must be a defineBuild result');
56
+ }
57
+
58
+ if (command === 'build') {
59
+ await definition.build(options);
60
+ } else {
61
+ const watcher = definition.watch(options);
62
+ let stopping;
63
+ const stop = () => {
64
+ if (!stopping) {
65
+ stopping = Promise.resolve()
66
+ .then(() => watcher.stop())
67
+ .finally(() => {
68
+ process.removeListener('SIGINT', stop);
69
+ process.removeListener('SIGTERM', stop);
70
+ });
71
+ }
72
+ return stopping;
73
+ };
74
+
75
+ process.on('SIGINT', stop);
76
+ process.on('SIGTERM', stop);
77
+ }
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
+ }