@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
@@ -0,0 +1,464 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { link, mkdir, readFile, unlink } from 'node:fs/promises';
3
+ import { createRequire } from 'node:module';
4
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
5
+ import { defineBuild } from './index.mjs';
6
+ import { clearBuildDirectory } from './build.mjs';
7
+ import { generateThemeDiscovery, generateThemeImporters, themeDiscoveryPlugin } from './theme-discovery.mjs';
8
+ import { processEightshiftCss } from './eightshift-css.mjs';
9
+ import { flattenAssets, packageFlatRelease, publishFlatRelease } from './flat-publication.mjs';
10
+ import { editorWorkerPlugin } from './media.mjs';
11
+ import { processCss } from './css.mjs';
12
+ import { buildSsr as buildDefaultSsr } from './ssr.mjs';
13
+
14
+ /**
15
+ * Define a conventional theme build. extraCss may be a hook or an array of
16
+ * { files, output?, keys?, href? }; package files use the `package:` prefix.
17
+ * Omitted output names use a content hash. Keys attach CSS to frontend importers.
18
+ * SSR is built when conventional entries exist; ssr: false disables it.
19
+ * watch: false disables watching; an object overrides the safe watch defaults.
20
+ */
21
+ export function defineThemeBuild({
22
+ root,
23
+ publicPrefix: configuredPublicPrefix,
24
+ buildSsr,
25
+ createPlugins = () => [],
26
+ frontendStyles = [],
27
+ extraCss = async () => {},
28
+ aliases = {},
29
+ requireEditorWorker = false,
30
+ media = {},
31
+ watch = {},
32
+ entries,
33
+ editor,
34
+ responsive = {},
35
+ css,
36
+ discovery,
37
+ ssr,
38
+ publish,
39
+ } = {}) {
40
+ if (typeof root !== 'string' || !root) {
41
+ throw new TypeError('root must be a non-empty string');
42
+ }
43
+
44
+ if (typeof createPlugins !== 'function') {
45
+ throw new TypeError('createPlugins must be a function');
46
+ }
47
+
48
+ if (extraCss !== false && typeof extraCss !== 'function' && !Array.isArray(extraCss)) {
49
+ throw new TypeError('extraCss must be false, a function, or an array');
50
+ }
51
+
52
+ if (watch !== false && (!watch || typeof watch !== 'object' || Array.isArray(watch))) {
53
+ throw new TypeError('watch must be false or an object');
54
+ }
55
+
56
+ for (const [name, value] of Object.entries({ css, discovery, ssr, publish })) {
57
+ if (value !== undefined && value !== false && typeof value !== 'function') {
58
+ throw new TypeError(`${name} must be false or a function`);
59
+ }
60
+ }
61
+
62
+ if (buildSsr !== undefined && typeof buildSsr !== 'function') {
63
+ throw new TypeError('buildSsr must be a function');
64
+ }
65
+
66
+ if (ssr !== undefined && buildSsr !== undefined) {
67
+ throw new TypeError('Use either ssr or buildSsr, not both');
68
+ }
69
+
70
+ if (entries !== undefined && (!entries || typeof entries !== 'object' || Array.isArray(entries) || !Object.keys(entries).length)) {
71
+ throw new TypeError('entries must contain named entrypoints');
72
+ }
73
+
74
+ if (editor !== undefined && editor !== false && (!editor || typeof editor !== 'object' || Array.isArray(editor))) {
75
+ throw new TypeError('editor must be false or an object');
76
+ }
77
+
78
+ if (responsive !== false && (!responsive || typeof responsive !== 'object' || Array.isArray(responsive))) {
79
+ throw new TypeError('responsive must be false or an object');
80
+ }
81
+
82
+ if (responsive === false && css === undefined) {
83
+ throw new TypeError('Default CSS requires responsive generation; configure css or enable responsive');
84
+ }
85
+
86
+ if (publish === undefined && css === false) {
87
+ throw new TypeError('Default publication requires CSS; configure publish or css');
88
+ }
89
+
90
+ if (publish === undefined && editor === false) {
91
+ throw new TypeError('Default publication requires an editor; configure publish or editor');
92
+ }
93
+
94
+ if (publish === undefined && entries && (!entries.frontend || !entries.admin || !entries.editor || Object.keys(entries).length !== 3)) {
95
+ throw new TypeError('Default publication requires frontend, admin, and editor entries');
96
+ }
97
+
98
+ if (publish === undefined && editor && editor.entry !== 'editor') {
99
+ throw new TypeError('Default publication requires editor.entry to be editor');
100
+ }
101
+
102
+ if (!Array.isArray(frontendStyles)) {
103
+ throw new TypeError('frontendStyles must be an array');
104
+ }
105
+
106
+ const cssDefinitions = Array.isArray(extraCss) ? extraCss : [];
107
+ const cssNames = new Set();
108
+
109
+ for (const item of cssDefinitions) {
110
+ if (
111
+ !item ||
112
+ typeof item !== 'object' ||
113
+ (item.output !== undefined && (typeof item.output !== 'string' || !/^[\w.-]+\.css$/.test(item.output) || item.output.startsWith('.'))) ||
114
+ !Array.isArray(item.files) ||
115
+ !item.files.length ||
116
+ (item.keys !== undefined && (!Array.isArray(item.keys) || !item.keys.length || item.keys.some((key) => typeof key !== 'string' || !key))) ||
117
+ (item.href !== undefined && (typeof item.href !== 'string' || !item.href))
118
+ ) {
119
+ throw new TypeError('Invalid extraCss definition');
120
+ }
121
+
122
+ if (item.output && (cssNames.has(item.output) || ['applicationBlocksFrontend.css', 'applicationBlocksEditor.css', 'applicationAdmin.css'].includes(item.output))) {
123
+ throw new TypeError(`Duplicate CSS output: ${item.output}`);
124
+ }
125
+
126
+ if (item.output) {
127
+ cssNames.add(item.output);
128
+ }
129
+ }
130
+
131
+ if (discovery !== undefined && (frontendStyles.length || cssDefinitions.some(({ keys }) => keys))) {
132
+ throw new TypeError('frontend styles require default discovery');
133
+ }
134
+
135
+ if (!media || typeof media !== 'object' || Array.isArray(media) || Object.keys(media).some((key) => key !== 'editorWorker')) {
136
+ throw new TypeError('Invalid media options');
137
+ }
138
+
139
+ if (media.editorWorker !== undefined && media.editorWorker !== false && typeof media.editorWorker !== 'function') {
140
+ throw new TypeError('media.editorWorker must be false or a plugin factory');
141
+ }
142
+
143
+ const wpRoot = process.env.EIGHTSHIFT_WP_ROOT ? resolve(process.env.EIGHTSHIFT_WP_ROOT) : resolve(root, '../../..');
144
+ const themePath = relative(wpRoot, resolve(root));
145
+ let publicPath = configuredPublicPrefix ?? process.env.EIGHTSHIFT_PUBLIC_PREFIX;
146
+ if (publicPath === undefined) {
147
+ if (!themePath || themePath === '..' || themePath.startsWith(`..${sep}`) || isAbsolute(themePath)) {
148
+ throw new Error('Theme must be inside the WordPress root unless publicPrefix is configured');
149
+ }
150
+ publicPath = `/${themePath.split(sep).join('/')}/public/`;
151
+ }
152
+ if (typeof publicPath !== 'string' || !publicPath.startsWith('/') || publicPath.startsWith('//') || !publicPath.endsWith('/') || publicPath.includes('\\') || /[?#\s\x00-\x1f]/.test(publicPath) || publicPath.split('/').some((part) => part === '.' || part === '..')) {
153
+ throw new Error('publicPrefix must be a root-relative URL path ending in /');
154
+ }
155
+ let outdir;
156
+ let editorWorker;
157
+ const makePreset = async ({ sourcemaps }) => {
158
+ const versionFile = resolve(wpRoot, 'wp-includes/version.php');
159
+ let versionSource;
160
+ try {
161
+ versionSource = await readFile(versionFile, 'utf8');
162
+ } catch (error) {
163
+ throw new Error(`Cannot read WordPress version at ${versionFile}. Set EIGHTSHIFT_WP_ROOT to a WordPress installation.`, { cause: error });
164
+ }
165
+ const version = versionSource.match(/^\s*\$wp_version\s*=\s*['"](\d+)\.(\d+)(?:\.(\d+))?(['"]);/m);
166
+ if (!version) {
167
+ throw new Error(`Cannot determine a stable WordPress version from ${versionFile}; WordPress 7.0 or newer is required.`);
168
+ }
169
+ if (Number(version[1]) < 7) {
170
+ throw new Error(`WordPress 7.0 or newer is required; found ${version[1]}.${version[2]}${version[3] === undefined ? '' : `.${version[3]}`}.`);
171
+ }
172
+
173
+ editorWorker = undefined;
174
+ const publicDir = resolve(root, 'public');
175
+ outdir = resolve(publicDir, '.build');
176
+ if (publish === undefined) {
177
+ await clearBuildDirectory(publicDir, root);
178
+ await mkdir(publicDir, { recursive: true });
179
+ } else {
180
+ await clearBuildDirectory(outdir, root);
181
+ }
182
+ const require = createRequire(resolve(root, 'package.json'));
183
+ const names = ['componentManifests', 'customManifests', 'customBlocks', 'customHooks', 'customTransforms', 'customDeprecations', 'customOverrides', 'variationManifests', 'customVariationManifests', 'variationOverrides', 'componentAdminAssets', 'customAdminAssets'];
184
+ const specs = [
185
+ ['componentManifests', 'components', /manifest\.json$/],
186
+ ['customManifests', 'custom', /manifest\.json$/],
187
+ ...['block', 'hooks', 'transforms', 'deprecations', 'overrides'].map((suffix, index) => [names[index + 2], 'custom', new RegExp(`-${suffix}.js$`)]),
188
+ ['componentAdminAssets', 'components', /assets-admin\/index\.js$/, 'lazy'],
189
+ ['customAdminAssets', 'custom', /assets-admin\/index\.js$/, 'lazy'],
190
+ ];
191
+ const entryNames = {
192
+ frontend: names.slice(0, 2),
193
+ admin: [names[0], names[1], names[10], names[11]],
194
+ };
195
+ const surfaces = Object.fromEntries(Object.entries(entryNames).map(([entry, selected]) => [entry, specs.filter(([name]) => selected.includes(name)).map(([name, directory, pattern, mode]) => ({ name, directory: `src/Blocks/${directory}`, pattern, mode }))]));
196
+ let frontendImporters;
197
+ const manifestReplacements = [
198
+ ["require.context('./../../components', true, /manifest\\.json$/)", 'componentManifests'],
199
+ ["require.context('./../../custom', true, /manifest\\.json$/)", 'customManifests'],
200
+ ];
201
+ let discoveryDir;
202
+ const discoveryPlugin = {
203
+ name: 'theme-discovery-setup',
204
+ setup(builder) {
205
+ themeDiscoveryPlugin({
206
+ root,
207
+ entries: [
208
+ {
209
+ path: 'src/Blocks/assets/scripts/application-blocks-frontend.js',
210
+ module: resolve(discoveryDir, 'frontend.mjs'),
211
+ imports: entryNames.frontend,
212
+ importStatement: "import { dynamicImport } from '@eightshift/frontend-libs-tailwind/scripts/helpers';",
213
+ prefix: frontendImporters,
214
+ replacements: [
215
+ ...manifestReplacements,
216
+ ['return import(/* webpackMode: "lazy" */ `./../../${importBasePath}/${directory}/assets/index.js`);', 'const importer = bunFrontendImporters[`${importBasePath}/${directory}`]; if (!importer) return Promise.reject(new Error("Missing frontend asset")); return importer();'],
217
+ ],
218
+ remove: [/dynamicImport\(require\.context\([^\n]+\)\);/g],
219
+ },
220
+ {
221
+ path: 'src/Blocks/assets/scripts/application-admin.js',
222
+ module: resolve(discoveryDir, 'admin.mjs'),
223
+ imports: entryNames.admin,
224
+ importStatement: "import { dynamicImport } from '@eightshift/frontend-libs-tailwind/scripts/helpers';",
225
+ replacements: [
226
+ ...manifestReplacements,
227
+ ["require.context('./../../components', true, /assets-admin\\/index\\.js$/)", 'componentAdminAssets'],
228
+ ["require.context('./../../custom', true, /assets-admin\\/index\\.js$/)", 'customAdminAssets'],
229
+ ['return import(/* webpackMode: "lazy" */ `./../../${importBasePath}/${directory}/assets-admin/index.js`);', 'return assetContext(assetPath);'],
230
+ ],
231
+ remove: [/dynamicImport\(require\.context\([^\n]+\)\);/g],
232
+ },
233
+ ],
234
+ }).setup(builder);
235
+ },
236
+ };
237
+ const pluginContext = {
238
+ root,
239
+ setEditorWorker: (worker) => {
240
+ editorWorker = worker;
241
+ },
242
+ getEditorWorker: () => editorWorker,
243
+ };
244
+ const callerPlugins = createPlugins(pluginContext);
245
+
246
+ if (!Array.isArray(callerPlugins)) {
247
+ throw new TypeError('createPlugins must return an array');
248
+ }
249
+
250
+ const workerFactory = media.editorWorker === undefined ? editorWorkerPlugin : media.editorWorker;
251
+ const plugins = workerFactory ? [workerFactory(pluginContext), ...callerPlugins] : [...callerPlugins];
252
+
253
+ if (discovery === undefined) {
254
+ plugins.push(discoveryPlugin);
255
+ } else if (discovery) {
256
+ const plugin = await discovery(pluginContext);
257
+
258
+ if (!plugin || typeof plugin.setup !== 'function') {
259
+ throw new TypeError('discovery must return a Bun plugin');
260
+ }
261
+
262
+ plugins.push(plugin);
263
+ }
264
+
265
+ return {
266
+ root,
267
+ outdir,
268
+ direct: true,
269
+ wpRoot,
270
+ entries: entries ?? { frontend: 'src/Blocks/assets/scripts/application-blocks-frontend.js', admin: 'src/Blocks/assets/scripts/application-admin.js', editor: 'src/Blocks/assets/scripts/application-blocks-editor.js' },
271
+ responsive,
272
+ editor: editor ?? {
273
+ entry: 'editor',
274
+ filename: 'applicationBlocksEditor.js',
275
+ discovery: {
276
+ filter: /application-blocks-editor\.js$/,
277
+ omitContexts: ({ pattern }) => pattern.source === 'styles-editor.css$',
278
+ },
279
+ },
280
+ css: async (context) => {
281
+ const { outdir: stage, responsive: generated } = context;
282
+
283
+ if (css === undefined) {
284
+ for (const surface of ['frontend', 'editor', 'admin']) {
285
+ const name = surface === 'admin' ? 'applicationAdmin' : `applicationBlocks${surface === 'frontend' ? 'Frontend' : 'Editor'}`;
286
+
287
+ await processEightshiftCss({ projectDir: root, surface, responsiveFile: generated[surface], outputFile: resolve(stage, 'css', `${name}.css`), production: true });
288
+ }
289
+ } else if (css) {
290
+ await css({ ...context, stage, require });
291
+ }
292
+
293
+ if (typeof extraCss === 'function') {
294
+ await extraCss({ root, stage, require });
295
+ }
296
+
297
+ const styles = [...frontendStyles];
298
+ const outputNames = new Set(cssNames);
299
+
300
+ for (const { output, files, keys, href } of cssDefinitions) {
301
+ const resolveFile = (file) => {
302
+ if (typeof file !== 'string' || !file) {
303
+ throw new TypeError('Invalid extraCss file');
304
+ }
305
+
306
+ return file.startsWith('package:') ? require.resolve(file.slice(8)) : isAbsolute(file) ? file : resolve(root, file);
307
+ };
308
+ const temporary = resolve(stage, 'css', `.extra-${randomUUID()}.css`);
309
+ const outputFile = output ? resolve(stage, 'css', output) : temporary;
310
+
311
+ await processCss({ projectDir: root, outputFile, files: files.map((entry) => (typeof entry === 'string' ? resolveFile(entry) : { ...entry, file: resolveFile(entry?.file) })), production: true });
312
+ let name = output;
313
+
314
+ if (!name) {
315
+ const hash = createHash('sha256')
316
+ .update(await readFile(temporary))
317
+ .digest('hex')
318
+ .slice(0, 20);
319
+
320
+ name = `extra-${hash}.css`;
321
+
322
+ if (outputNames.has(name)) {
323
+ throw new Error(`Duplicate CSS output: ${name}`);
324
+ }
325
+
326
+ outputNames.add(name);
327
+ await link(temporary, resolve(stage, 'css', name));
328
+ await unlink(temporary);
329
+ }
330
+
331
+ if (keys) {
332
+ styles.push({ keys, href: href ?? `../css/${name}` });
333
+ }
334
+ }
335
+
336
+ if (discovery === undefined) {
337
+ frontendImporters = await generateThemeImporters({
338
+ root,
339
+ glob: 'src/Blocks/{components,custom}/**/assets/index.js',
340
+ key: (file) => file.replace(/^src\/Blocks\//, '').replace(/\/assets\/index\.js$/, ''),
341
+ styles,
342
+ });
343
+ discoveryDir = resolve(stage, 'discovery');
344
+ await generateThemeDiscovery({ root, outputDir: discoveryDir, surfaces });
345
+ }
346
+ },
347
+ buildOptions: {
348
+ minify: true,
349
+ publicPath,
350
+ naming: { entry: '[name]-[hash].[ext]', chunk: '[name]-[hash].[ext]', asset: '[name]-[hash].[ext]' },
351
+ sourcemap: sourcemaps ? 'external' : 'none',
352
+ loader: { '.js': 'jsx', '.svg': 'file' },
353
+ define: { 'process.browser': 'true', 'process.env.NODE_ENV': '"production"', 'process.env.VERSION': '"library-release"' },
354
+ plugins,
355
+ },
356
+ };
357
+ };
358
+ const defaultPublish = async ({ result }) => {
359
+ const editorScript = await readFile(resolve(outdir, result.entries.editor.entry), 'utf8');
360
+
361
+ if (requireEditorWorker && !editorWorker) {
362
+ throw new Error('Missing editor worker');
363
+ }
364
+
365
+ const ssrDir = resolve(outdir, 'ssr/production');
366
+ const ssrNames = [];
367
+
368
+ if (ssr !== false) {
369
+ if (ssr || buildSsr) {
370
+ await (ssr ?? buildSsr)({ root, mode: 'production' });
371
+ }
372
+
373
+ for await (const file of new Bun.Glob('src/**/assets-ssr/ssr.{js,mjs}').scan({ cwd: root })) {
374
+ const name = file.split('/').at(-3);
375
+
376
+ if (ssrNames.includes(name)) {
377
+ throw new Error(`Duplicate SSR entry: ${name}`);
378
+ }
379
+
380
+ ssrNames.push(name);
381
+ }
382
+
383
+ if (ssrNames.length && !ssr && !buildSsr) {
384
+ await defaultSsr({ root, mode: 'production' });
385
+ }
386
+
387
+ if (!ssrNames.length && (ssr || buildSsr)) {
388
+ throw new Error('No SSR entries found');
389
+ }
390
+ }
391
+
392
+ const surfaces = { frontend: 'applicationBlocksFrontend', editor: 'applicationBlocksEditor', admin: 'applicationAdmin' };
393
+ const flatDir = resolve(outdir, 'flat');
394
+ const { rewrite } = await flattenAssets({
395
+ outdir,
396
+ flatDir,
397
+ extraSources: editorWorker ? { [`editor/editor-assets/${basename(editorWorker)}`]: editorWorker } : {},
398
+ editorEntry: result.entries.editor.entry,
399
+ editorScript,
400
+ });
401
+ // Webpack exposed standalone images by basename, even when not imported by JS.
402
+ const standaloneAssets = new Map();
403
+
404
+ for await (const file of new Bun.Glob('src/Blocks/assets/images/**/*').scan({ cwd: root, onlyFiles: true })) {
405
+ const name = basename(file);
406
+
407
+ if (standaloneAssets.has(name)) {
408
+ throw new Error(`Duplicate standalone asset: ${name}`);
409
+ }
410
+
411
+ standaloneAssets.set(name, resolve(root, file));
412
+ }
413
+
414
+ const entries = Object.entries(surfaces).map(([surface, name]) => {
415
+ const entry = result.entries[surface];
416
+ const script = surface === 'editor' ? rewrite(editorScript, entry.entry) : undefined;
417
+
418
+ console.log(`${surface}: ${entry.entry}; dependencies: ${entry.dependencies.join(', ') || 'none'}`);
419
+
420
+ return { name, entry: surface === 'editor' ? 'editor-entry.js' : basename(entry.entry), style: `${name}.css`, dependencies: entry.dependencies, ...(script && { script }) };
421
+ });
422
+ const { release, version, manifest } = await packageFlatRelease({
423
+ root: resolve(root, 'public'),
424
+ outputDirectory: resolve(root, 'public'),
425
+ flatDir,
426
+ entries,
427
+ ssrDir,
428
+ ssrNames,
429
+ standaloneAssets,
430
+ aliases,
431
+ });
432
+
433
+ await publishFlatRelease({ root, wpRoot, release, manifest, version, direct: true, publicPrefix: publicPath });
434
+ await clearBuildDirectory(outdir, root);
435
+ };
436
+ const defaultSsr = ({ root, mode }) => buildDefaultSsr({ root, mode, outdir: resolve(outdir, 'ssr', mode) });
437
+ const customSsr = ssr ?? buildSsr;
438
+ const definition = defineBuild({
439
+ root,
440
+ preset: makePreset,
441
+ ssr:
442
+ publish !== undefined && ssr !== false
443
+ ? async (state) => {
444
+ if (customSsr) {
445
+ return customSsr({ ...state, mode: 'production' });
446
+ }
447
+
448
+ for await (const _file of new Bun.Glob('src/**/assets-ssr/ssr.{js,mjs}').scan({ cwd: root, onlyFiles: true })) {
449
+ return defaultSsr({ root, mode: 'production' });
450
+ }
451
+ }
452
+ : undefined,
453
+ publish: publish === undefined ? defaultPublish : publish || undefined,
454
+ watch: { sources: ['src', 'build', 'eightshift.build.mjs', 'package.json', 'bun.lock', 'tailwind.css', 'tailwind-editor.css', 'tailwind-frontend.css', 'color-themes.css'], ignored: ['.git', '.bun-pilot', 'node_modules', 'vendor', 'vendor-prefixed', 'public'], ...(watch || {}) },
455
+ });
456
+
457
+ if (watch === false) {
458
+ definition.watch = () => {
459
+ throw new Error('Watching is disabled');
460
+ };
461
+ }
462
+
463
+ return definition;
464
+ }
@@ -0,0 +1,171 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { dirname, resolve } from 'node:path';
3
+ import { generateDiscovery } from './discovery.mjs';
4
+
5
+ /**
6
+ * Generate caller-defined contexts for each surface. Returns absolute module
7
+ * paths keyed by surface. Regenerate after adding or removing source files.
8
+ */
9
+ export async function generateThemeDiscovery({ root, outputDir, surfaces }) {
10
+ if (!root || !outputDir || !surfaces || typeof surfaces !== 'object') {
11
+ throw new TypeError('Expected root, outputDir and surfaces');
12
+ }
13
+
14
+ const modules = {};
15
+
16
+ for (const [surface, definitions] of Object.entries(surfaces)) {
17
+ if (!/^[\w-]+$/.test(surface) || !Array.isArray(definitions)) {
18
+ throw new TypeError('Invalid discovery surface');
19
+ }
20
+
21
+ const output = resolve(root, outputDir, `${surface}.mjs`);
22
+
23
+ await generateDiscovery({ root, output, definitions });
24
+ modules[surface] = output;
25
+ }
26
+
27
+ return modules;
28
+ }
29
+
30
+ /**
31
+ * Build a static, lazy importer map from a caller-selected Bun glob. `key`
32
+ * maps each root-relative file to its runtime lookup key. Styles are optional
33
+ * { keys, href } groups, loaded once before the corresponding importer; failed
34
+ * loads remove their link and can be retried. URLs resolve relative to the
35
+ * generated JavaScript module, matching Bun's import.meta.url behavior.
36
+ */
37
+ export async function generateThemeImporters({ root, glob, key, styles = [] }) {
38
+ if (!root || typeof glob !== 'string' || typeof key !== 'function' || !Array.isArray(styles)) {
39
+ throw new TypeError('Expected root, glob, key and styles');
40
+ }
41
+
42
+ const entries = [];
43
+ const keys = new Set();
44
+
45
+ for await (const file of new Bun.Glob(glob).scan({ cwd: root, onlyFiles: true })) {
46
+ const name = key(file);
47
+
48
+ if (typeof name !== 'string' || keys.has(name)) {
49
+ throw new TypeError(`Invalid or duplicate importer key: ${name}`);
50
+ }
51
+
52
+ keys.add(name);
53
+ entries.push([name, resolve(root, file)]);
54
+ }
55
+
56
+ entries.sort(([a], [b]) => a.localeCompare(b));
57
+ const styleByKey = new Map();
58
+
59
+ for (const [index, style] of styles.entries()) {
60
+ if (!style || !Array.isArray(style.keys) || typeof style.href !== 'string') {
61
+ throw new TypeError('Invalid importer style');
62
+ }
63
+
64
+ for (const name of style.keys) {
65
+ if (!keys.has(name) || styleByKey.has(name)) {
66
+ throw new TypeError(`Unknown or duplicate styled importer: ${name}`);
67
+ }
68
+
69
+ styleByKey.set(name, index);
70
+ }
71
+ }
72
+
73
+ const loaders = styles
74
+ .map(
75
+ ({ href }, index) =>
76
+ `let stylePromise${index};
77
+ const loadStyle${index} = () => stylePromise${index} ??= new Promise((resolve, reject) => {
78
+ const link = document.createElement('link');
79
+ link.rel = 'stylesheet';
80
+ link.href = new URL(${JSON.stringify(href)}, import.meta.url).href;
81
+ link.onload = resolve;
82
+ link.onerror = () => {
83
+ link.remove();
84
+ stylePromise${index} = undefined;
85
+ reject(new Error('Failed to load stylesheet: ' + link.href));
86
+ };
87
+ document.head.appendChild(link);
88
+ });`,
89
+ )
90
+ .join('\n');
91
+ const importers = entries.map(([name, path]) => {
92
+ const importer = `() => import(${JSON.stringify(path)})`;
93
+ const style = styleByKey.get(name);
94
+
95
+ return `${JSON.stringify(name)}: ${style === undefined ? importer : `() => loadStyle${style}().then(${importer})`}`;
96
+ });
97
+
98
+ return `${loaders}\nconst bunFrontendImporters = {${importers.join(',')}};`;
99
+ }
100
+
101
+ /**
102
+ * Transform only explicitly selected entry paths. Each entry specifies
103
+ * { path, module, imports, importStatement, replacements, prefix, remove }.
104
+ * Replacements are [literal, replacement] pairs and must occur exactly once.
105
+ * `remove` is an optional array of RegExps; remaining webpack discovery is
106
+ * rejected. `prefix` can contain the generated importer map.
107
+ */
108
+ export function themeDiscoveryPlugin({ root, entries }) {
109
+ if (!root || !Array.isArray(entries)) {
110
+ throw new TypeError('Expected root and entries');
111
+ }
112
+
113
+ const byPath = new Map();
114
+
115
+ for (const entry of entries) {
116
+ if (!entry.path || !entry.module || !Array.isArray(entry.imports) || typeof entry.importStatement !== 'string' || !Array.isArray(entry.replacements) || (entry.remove && !Array.isArray(entry.remove))) {
117
+ throw new TypeError('Invalid discovery entry');
118
+ }
119
+
120
+ const path = resolve(root, entry.path);
121
+
122
+ if (byPath.has(path)) {
123
+ throw new TypeError(`Duplicate discovery entry: ${path}`);
124
+ }
125
+
126
+ byPath.set(path, entry);
127
+ }
128
+
129
+ const replaceOnce = (source, original, replacement) => {
130
+ if (typeof original !== 'string' || !original || typeof replacement !== 'string' || source.split(original).length !== 2) {
131
+ throw new Error(`Source changed; cannot replace: ${original}`);
132
+ }
133
+
134
+ return source.replace(original, () => replacement);
135
+ };
136
+
137
+ return {
138
+ name: 'theme-discovery',
139
+ setup(builder) {
140
+ builder.onLoad({ filter: /\.[cm]?jsx?$/ }, async ({ path }) => {
141
+ const entry = byPath.get(path);
142
+
143
+ if (!entry) {
144
+ return;
145
+ }
146
+
147
+ let source = await readFile(path, 'utf8');
148
+
149
+ source = replaceOnce(source, entry.importStatement, `import { ${entry.imports.join(', ')} } from ${JSON.stringify(resolve(root, entry.module))};\n${entry.prefix || ''}`);
150
+
151
+ for (const [original, replacement] of entry.replacements) {
152
+ source = replaceOnce(source, original, replacement);
153
+ }
154
+
155
+ for (const pattern of entry.remove || []) {
156
+ if (!(pattern instanceof RegExp)) {
157
+ throw new TypeError('Removal patterns must be RegExp');
158
+ }
159
+
160
+ source = source.replace(pattern, '');
161
+ }
162
+
163
+ if (source.includes('require.context') || source.includes('dynamicImport(')) {
164
+ throw new Error(`Unsupported discovery remains in ${path}`);
165
+ }
166
+
167
+ return { contents: source, loader: 'jsx', resolveDir: dirname(path) };
168
+ });
169
+ },
170
+ };
171
+ }