@wordpress/build 0.25.0 → 0.27.0

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/lib/build.mjs CHANGED
@@ -3,18 +3,16 @@ import { readFile, writeFile, copyFile, mkdir, unlink } from 'fs/promises';
3
3
  import path from 'path';
4
4
  import { createRequire as createNodeRequire } from 'node:module';
5
5
  import { parseArgs } from 'node:util';
6
- import esbuild from 'esbuild';
7
6
  import glob from 'fast-glob';
8
7
  import chokidar from 'chokidar';
9
8
  import browserslistToEsbuild from 'browserslist-to-esbuild';
10
- import { sassPlugin } from 'esbuild-sass-plugin';
11
9
  import postcss from 'postcss';
12
10
  import autoprefixer from 'autoprefixer';
13
11
  import rtlcss from 'rtlcss';
14
12
  import cssnano from 'cssnano';
15
- import babel from 'esbuild-plugin-babel';
16
13
  import { camelCase } from 'change-case';
17
14
  import { NodePackageImporter } from 'sass-embedded';
15
+ import createDsTokenFallbacksPlugin from '@wordpress/theme-build-tools/vite-plugins/vite-ds-token-fallbacks';
18
16
  import {
19
17
  groupByDepth,
20
18
  findScriptsToRebundle,
@@ -49,6 +47,12 @@ import {
49
47
  compileInlineStyle,
50
48
  dsTokenFallbacks,
51
49
  } from './compile-inline-style.mjs';
50
+ import { compileStylesheet, disposeSassCompiler } from './sass-compiler.mjs';
51
+ import {
52
+ buildWithConcurrency,
53
+ getDefaultBuildConcurrency,
54
+ setBuildConcurrency,
55
+ } from './build-concurrency.mjs';
52
56
 
53
57
  /**
54
58
  * Resolve the ESBuild target from the project's Browserslist config.
@@ -58,22 +62,17 @@ import {
58
62
  function getEsbuildTarget() {
59
63
  return browserslistToEsbuild( getBrowserslistQueries() );
60
64
  }
61
- // Optional dependency: @wordpress/theme provides a plugin that injects fallback
62
- // values for design system tokens in JavaScript. Fails gracefully when the
63
- // package is not installed (it is an optional peerDependency).
64
- let dsTokenFallbacksJs;
65
- try {
66
- const { default: esbuildPlugin } =
67
- await import( '@wordpress/theme/esbuild-plugins/esbuild-ds-token-fallbacks' );
68
- dsTokenFallbacksJs = esbuildPlugin;
69
- } catch {
70
- // @wordpress/theme is optional; skip token fallbacks if not available.
71
- }
65
+ // The Vite-only `enforce` property is not a Rolldown plugin property.
66
+ const { enforce, ...dsTokenFallbacksJs } = createDsTokenFallbacksPlugin();
72
67
 
73
68
  const ROOT_DIR = process.cwd();
74
69
  const PACKAGES_DIR = path.join( ROOT_DIR, 'packages' );
75
70
  const BUILD_DIR = path.join( ROOT_DIR, 'build' );
76
71
 
72
+ /**
73
+ * Module types for non-JS imports. SVG files are inlined as `data:` URIs.
74
+ */
75
+ const LOADER_CONFIG = { '.svg': 'dataurl' };
77
76
  const ASSET_EXTENSIONS = 'json';
78
77
  const IGNORE_PATTERNS = [
79
78
  '**/benchmark/**',
@@ -139,6 +138,41 @@ const baseDefine = {
139
138
  false
140
139
  ),
141
140
  };
141
+ // Rolldown's default conditions lack esbuild's module condition.
142
+ const defaultConditions = [ 'module', 'browser', 'default' ];
143
+ const developmentConditions = [ 'development', ...defaultConditions ];
144
+ /*
145
+ * The `jsx` option overrides the tsconfig's `jsx`, which is `preserve` for the
146
+ * type checker.
147
+ */
148
+ const JSX_OPTIONS = { runtime: 'automatic', importSource: 'react' };
149
+ const BASE_CHECKS = {
150
+ configurationFieldConflict: false,
151
+ // Don't warn about directives like 'use client' in bundled dependencies.
152
+ moduleLevelDirective: false,
153
+ };
154
+ // Rolldown's `__toESM` gives namespace imports a `default` unless the module has
155
+ // its own, even when flagged `__esModule`. Follow the flag alone, like esbuild.
156
+ const TO_ESM_OWN_DEFAULT_CHECK = ' || !__hasOwnProp.call(mod, "default")';
157
+ const esModuleInteropPlugin = {
158
+ name: 'es-module-interop',
159
+ renderChunk( code ) {
160
+ if ( ! code.includes( 'var __toESM = ' ) ) {
161
+ return null;
162
+ }
163
+ if ( ! code.includes( TO_ESM_OWN_DEFAULT_CHECK ) ) {
164
+ throw new Error( 'Unexpected Rolldown `__toESM` helper.' );
165
+ }
166
+ // A same-length replacement keeps the source map valid.
167
+ return {
168
+ code: code.replace(
169
+ TO_ESM_OWN_DEFAULT_CHECK,
170
+ ' '.repeat( TO_ESM_OWN_DEFAULT_CHECK.length )
171
+ ),
172
+ map: null,
173
+ };
174
+ },
175
+ };
142
176
  const getDefine = ( scriptDebug ) => ( {
143
177
  ...baseDefine,
144
178
  'globalThis.SCRIPT_DEBUG': JSON.stringify( scriptDebug ),
@@ -172,11 +206,9 @@ const STYLE_RUNTIME_ENTRY = path.join(
172
206
  function styleRuntimeAliasPlugin() {
173
207
  return {
174
208
  name: 'style-runtime-alias',
175
- setup( build ) {
176
- build.onResolve(
177
- { filter: /^@wordpress\/style-runtime$/ },
178
- () => ( { path: STYLE_RUNTIME_ENTRY } )
179
- );
209
+ resolveId: {
210
+ filter: { id: /^@wordpress\/style-runtime$/ },
211
+ handler: () => STYLE_RUNTIME_ENTRY,
180
212
  },
181
213
  };
182
214
  }
@@ -185,7 +217,7 @@ function styleRuntimeAliasPlugin() {
185
217
  * Get SASS options for the given working directory.
186
218
  *
187
219
  * Uses NodePackageImporter from sass-embedded for resolving package imports
188
- * (like @wordpress/base-styles) which works with any package manager (npm, pnpm, yarn).
220
+ * (like `@wordpress/base-styles`) which works with any package manager (npm, pnpm, yarn).
189
221
  *
190
222
  * @param {string} workingDir - The directory where we're working (for NodePackageImporter).
191
223
  * @return {Object} SASS options object with importers and loadPaths.
@@ -205,16 +237,41 @@ function getSassOptions( workingDir ) {
205
237
  };
206
238
  }
207
239
 
208
- function inlineStyle( contents ) {
209
- // The `contents` is already a JS code created by `compileInlineStyle`.
210
- return contents;
240
+ /**
241
+ * Plugin compiling stylesheets with Sass into JS code, created by `transform`
242
+ * from the CSS.
243
+ *
244
+ * @param {Object} options Plugin options, along with the Sass options.
245
+ * @param {RegExp} options.filter Stylesheets to compile.
246
+ * @param {(css: string, resolveDir: string, filePath: string) => Promise<string>} options.transform Transforms the CSS into JS code.
247
+ * @return {import('rolldown').Plugin} Rolldown plugin.
248
+ */
249
+ function sassPlugin( { filter, transform, ...sassOptions } ) {
250
+ // Files transpiled on their own share the plugin, and often a stylesheet.
251
+ const cache = new Map();
252
+ const compile = async ( id ) => {
253
+ const css = await compileStylesheet( id, sassOptions );
254
+ return transform( css, path.dirname( id ), id );
255
+ };
256
+ return {
257
+ name: 'sass',
258
+ load: {
259
+ filter: { id: filter },
260
+ async handler( id ) {
261
+ if ( ! cache.has( id ) ) {
262
+ cache.set( id, compile( id ) );
263
+ }
264
+ return { code: await cache.get( id ), moduleType: 'js' };
265
+ },
266
+ },
267
+ };
211
268
  }
212
269
 
213
270
  /**
214
271
  * Create style bundling plugins with the given working directory.
215
272
  *
216
273
  * @param {string} workingDir - The directory where we're working (for NodePackageImporter).
217
- * @return {object[]} Array of esbuild plugins for handling CSS/SCSS.
274
+ * @return {import('rolldown').Plugin[]} Array of Rolldown plugins for handling CSS/SCSS.
218
275
  */
219
276
  function createStyleBundlingPlugins( workingDir ) {
220
277
  const sassOptions = getSassOptions( workingDir );
@@ -222,21 +279,15 @@ function createStyleBundlingPlugins( workingDir ) {
222
279
  styleRuntimeAliasPlugin(),
223
280
  // Handle CSS modules (.module.css and .module.scss)
224
281
  sassPlugin( {
225
- embedded: true,
226
- sourceMap: false,
227
282
  filter: /\.module\.(css|scss)$/,
228
283
  transform: compileInlineStyle( { cssModules: true } ),
229
- type: inlineStyle,
230
284
  ...sassOptions,
231
285
  } ),
232
286
  // Handle regular CSS/SCSS files
233
287
  // Note: .module.css and .module.scss already handled by plugin above
234
288
  sassPlugin( {
235
- embedded: true,
236
- sourceMap: false,
237
289
  filter: /\.(css|scss)$/,
238
290
  transform: compileInlineStyle(),
239
- type: inlineStyle,
240
291
  ...sassOptions,
241
292
  } ),
242
293
  ];
@@ -298,6 +349,8 @@ function binaryEncode( data ) {
298
349
  return Buffer.from( out ).toString( 'utf8' );
299
350
  }
300
351
 
352
+ const WASM_INLINE_PREFIX = '\0wasm-inline:';
353
+
301
354
  /**
302
355
  * Plugin to inline WASM files into the bundle.
303
356
  *
@@ -306,55 +359,53 @@ function binaryEncode( data ) {
306
359
  * embedded using a compact UTF-8 encoding (rather than base64) so it compresses
307
360
  * well, and is decoded back to a `Uint8Array` at runtime.
308
361
  *
309
- * @return {Object} esbuild plugin.
362
+ * @type {import('rolldown').Plugin}
310
363
  */
311
364
  const wasmInlinePlugin = {
312
365
  name: 'wasm-inline',
313
- setup( build ) {
314
- // Resolve .wasm imports from node_modules.
315
- build.onResolve( { filter: /\.wasm$/ }, async ( args ) => {
316
- // Handle imports like 'wasm-vips/vips.wasm'.
317
- if ( ! args.path.startsWith( '.' ) ) {
318
- const { createRequire } = await import( 'module' );
319
- const require = createRequire( args.resolveDir + '/index.js' );
320
- try {
321
- const resolved = require.resolve( args.path );
322
- return {
323
- path: normalizePath(
324
- path.relative( ROOT_DIR, resolved )
325
- ),
326
- namespace: 'wasm-inline',
327
- pluginData: { resolvedPath: resolved },
328
- };
329
- } catch {
330
- // If resolution fails, let other plugins handle it.
331
- return null;
332
- }
366
+ // Resolve .wasm imports from node_modules, like 'wasm-vips/vips.wasm'.
367
+ resolveId: {
368
+ filter: { id: /^[^.].*\.wasm$/ },
369
+ handler( source, importer ) {
370
+ const require = createNodeRequire(
371
+ importer ?? path.join( ROOT_DIR, 'index.js' )
372
+ );
373
+ try {
374
+ // A path relative to the root keeps the checkout path out of
375
+ // the source map.
376
+ return (
377
+ WASM_INLINE_PREFIX +
378
+ normalizePath(
379
+ path.relative( ROOT_DIR, require.resolve( source ) )
380
+ )
381
+ );
382
+ } catch {
383
+ // If resolution fails, let other plugins handle it.
384
+ return null;
333
385
  }
334
- return null;
335
- } );
386
+ },
387
+ },
336
388
 
337
- // Load WASM files, embed them as a compact UTF-8 string, and decode
338
- // back to a Uint8Array at runtime.
339
- build.onLoad(
340
- { filter: /.*/, namespace: 'wasm-inline' },
341
- async ( args ) => {
342
- const wasmBuffer = await readFile(
343
- args.pluginData.resolvedPath
344
- );
345
- const encoded = binaryEncode( wasmBuffer );
389
+ // Load WASM files, embed them as a compact UTF-8 string, and decode
390
+ // back to a Uint8Array at runtime.
391
+ load: {
392
+ filter: { id: /^\0wasm-inline:/ },
393
+ async handler( id ) {
394
+ const wasmBuffer = await readFile(
395
+ path.join( ROOT_DIR, id.slice( WASM_INLINE_PREFIX.length ) )
396
+ );
397
+ const encoded = binaryEncode( wasmBuffer );
346
398
 
347
- return {
348
- contents: `const s = ${ encoded };
399
+ return {
400
+ code: `const s = ${ encoded };
349
401
  const bytes = new Uint8Array( s.length );
350
402
  for ( let i = 0; i < s.length; i++ ) {
351
403
  bytes[ i ] = s.charCodeAt( i );
352
404
  }
353
405
  export default bytes;`,
354
- loader: 'js',
355
- };
356
- }
357
- );
406
+ moduleType: 'js',
407
+ };
408
+ },
358
409
  },
359
410
  };
360
411
 
@@ -431,41 +482,37 @@ function transformPhpContent( content, transforms ) {
431
482
  * Plugin to handle moment-timezone aliases.
432
483
  * Redirects moment-timezone imports to use pre-built bundles with limited data.
433
484
  *
434
- * @return {Object} esbuild plugin.
485
+ * @return {import('rolldown').Plugin} Rolldown plugin.
435
486
  */
436
487
  function momentTimezoneAliasPlugin() {
437
488
  return {
438
489
  name: 'moment-timezone-alias',
439
- setup( build ) {
440
- // Alias path that esbuild will resolve
441
- const aliasPath =
442
- 'moment-timezone/builds/moment-timezone-with-data-1970-2030.js';
443
-
444
- // Redirect main moment-timezone files to pre-built bundle
445
- build.onResolve(
446
- { filter: /^moment-timezone\/moment-timezone\.js$/ },
447
- ( { importer, resolveDir, kind } ) =>
448
- build.resolve( aliasPath, {
449
- importer,
450
- resolveDir,
490
+ resolveId: {
491
+ filter: { id: /^(moment-timezone\/moment-timezone\.js|\.\/)$/ },
492
+ handler( source, importer, { kind } ) {
493
+ // Alias path that Rolldown will resolve
494
+ const aliasPath =
495
+ 'moment-timezone/builds/moment-timezone-with-data-1970-2030.js';
496
+
497
+ // Redirect main moment-timezone files to pre-built bundle
498
+ if ( source === 'moment-timezone/moment-timezone.js' ) {
499
+ return this.resolve( aliasPath, importer, {
451
500
  kind,
452
- } )
453
- );
501
+ skipSelf: true,
502
+ } );
503
+ }
454
504
 
455
- // Intercept the require('./') call inside moment-timezone-utils
456
- // and redirect it to the pre-built bundle.
457
- build.onResolve(
458
- { filter: /^\.\/$/ },
459
- ( { importer, resolveDir, kind } ) => {
460
- if ( importer.includes( 'moment-timezone-utils' ) ) {
461
- return build.resolve( aliasPath, {
462
- importer,
463
- resolveDir,
464
- kind,
465
- } );
466
- }
505
+ // Intercept the require('./') call inside moment-timezone-utils
506
+ // and redirect it to the pre-built bundle.
507
+ if ( importer?.includes( 'moment-timezone-utils' ) ) {
508
+ return this.resolve( aliasPath, importer, {
509
+ kind,
510
+ skipSelf: true,
511
+ } );
467
512
  }
468
- );
513
+
514
+ return null;
515
+ },
469
516
  },
470
517
  };
471
518
  }
@@ -510,7 +557,48 @@ function resolveEntryPoint( packageDir, packageJson ) {
510
557
  }
511
558
 
512
559
  /**
513
- * Bundle a package for WordPress using esbuild.
560
+ * Rolldown plugin that exposes a classic script's exports on the global,
561
+ * e.g. `window.wp.blocks`.
562
+ *
563
+ * Its `outro` runs at the end of the bundle's function, whose `exports`
564
+ * parameter holds the entry's exports as data properties. A CommonJS entry's
565
+ * `module.exports` is its default export.
566
+ *
567
+ * @param {string} scriptGlobal Global variable name, e.g. `wp`.
568
+ * @param {string} globalMember Member of the global variable, e.g. `blocks`.
569
+ * @param {boolean} exposeDefault Whether to expose the default export instead of the exports.
570
+ * @return {import('rolldown').Plugin} Rolldown plugin.
571
+ */
572
+ function scriptGlobalPlugin( scriptGlobal, globalMember, exposeDefault ) {
573
+ return {
574
+ name: 'script-global',
575
+ outro( chunk ) {
576
+ if ( ! chunk.isEntry ) {
577
+ return '';
578
+ }
579
+ const assign = ( value ) =>
580
+ `(window.${ scriptGlobal } ||= {}).${ globalMember } = ${ value };`;
581
+ // The bundle's function has no `exports` parameter without exports.
582
+ if ( chunk.exports.length === 0 ) {
583
+ return assign( 'undefined' );
584
+ }
585
+ const { inputFormat } = this.getModuleInfo( chunk.facadeModuleId );
586
+ if (
587
+ ( exposeDefault || inputFormat === 'cjs' ) &&
588
+ chunk.exports.includes( 'default' )
589
+ ) {
590
+ return assign( 'exports.default' );
591
+ }
592
+ return [
593
+ "Object.defineProperty(exports, '__esModule', { value: true });",
594
+ assign( 'exports' ),
595
+ ].join( '\n' );
596
+ },
597
+ };
598
+ }
599
+
600
+ /**
601
+ * Bundle a package for WordPress using Rolldown.
514
602
  *
515
603
  * @param {string} packageName Package name.
516
604
  * @param {Object} options Optional bundling options.
@@ -546,59 +634,57 @@ async function bundlePackage( packageName, options = {} ) {
546
634
  );
547
635
  const shouldExposeGlobal = matchesNamespace && scriptGlobal !== false;
548
636
 
549
- const globalName = shouldExposeGlobal
550
- ? `${ scriptGlobal }.${ camelCase( packageName ) }`
551
- : undefined;
552
-
553
637
  const baseConfig = {
554
- entryPoints: [ entryPoint ],
555
- bundle: true,
556
- sourcemap: true,
557
- format: 'iife',
558
- target,
638
+ input: entryPoint,
639
+ moduleTypes: LOADER_CONFIG,
559
640
  platform: 'browser',
560
- globalName,
641
+ checks: {
642
+ ...BASE_CHECKS,
643
+ // The script global plugin exposes the exports, not `output.name`.
644
+ missingNameOptionForIifeExport: false,
645
+ },
561
646
  };
562
647
 
563
- /*
564
- * Wrap the bundle in an IIFE so the `'use strict'` directive esbuild emits for the
565
- * (strict) ES module output stays at the function level. Left at the top of the
566
- * file it is a *file-level* directive, which — because load-scripts.php
567
- * concatenates raw file contents — forces strict mode onto any sloppy-mode script
568
- * bundled after it, throwing on e.g. implicit globals. Wrapping confines the
569
- * directive to this bundle. See https://core.trac.wordpress.org/ticket/65515.
570
- */
571
- baseConfig.banner = { js: '(function() {' };
572
-
573
- /*
574
- * esbuild's `globalName` assigns onto a locally-declared `var` root (using a
575
- * `window.…` global name would emit `var window`, shadowing the real global), so
576
- * that assignment is trapped inside the wrapper. Re-expose it on the real global
577
- * object in the footer, then close the IIFE.
578
- */
579
- let footerJs = '';
580
- if ( shouldExposeGlobal ) {
581
- const globalMember = camelCase( packageName );
582
- // For packages with default exports, expose the default, not the namespace.
583
- if ( packageJson.wpScriptDefaultExport ) {
584
- footerJs += `if (typeof ${ globalName } === 'object' && ${ globalName }.default) { ${ globalName } = ${ globalName }.default; }\n`;
585
- }
586
- footerJs += `(window.${ scriptGlobal } ||= {}).${ globalMember } = ${ scriptGlobal }.${ globalMember };\n`;
587
- }
588
- footerJs += '})();';
589
- baseConfig.footer = { js: footerJs };
648
+ const baseOutput = {
649
+ sourcemap: true,
650
+ format: 'iife',
651
+ codeSplitting: false,
652
+ exports: 'named',
653
+ /*
654
+ * Keep the `'use strict'` directive for the (strict) ES module code inside
655
+ * the bundle's function. Left at the top of the file it is a *file-level*
656
+ * directive, which — because load-scripts.php concatenates raw file
657
+ * contents — forces strict mode onto any sloppy-mode script bundled after
658
+ * it, throwing on e.g. implicit globals.
659
+ * See https://core.trac.wordpress.org/ticket/65515.
660
+ */
661
+ strict: false,
662
+ intro: '"use strict";',
663
+ // The script global plugin adds it, only when there are exports.
664
+ esModule: false,
665
+ generatedCode: { symbols: false },
666
+ };
590
667
 
591
668
  const baseBundlePlugins = [
592
669
  momentTimezoneAliasPlugin(),
593
670
  styleRuntimeAliasPlugin(),
671
+ shouldExposeGlobal &&
672
+ scriptGlobalPlugin(
673
+ scriptGlobal,
674
+ camelCase( packageName ),
675
+ !! packageJson.wpScriptDefaultExport
676
+ ),
594
677
  ];
595
678
 
596
679
  builds.push(
597
- esbuild.build( {
680
+ buildWithConcurrency( {
598
681
  ...baseConfig,
599
- outfile: path.join( outputDir, 'index.min.js' ),
600
- minify: true,
601
- define: getDefine( false ),
682
+ transform: {
683
+ target,
684
+ define: getDefine( false ),
685
+ jsx: JSX_OPTIONS,
686
+ },
687
+ resolve: { conditionNames: defaultConditions },
602
688
  plugins: [
603
689
  ...baseBundlePlugins,
604
690
  wordpressExternalsPlugin(
@@ -608,12 +694,20 @@ async function bundlePackage( packageName, options = {} ) {
608
694
  true // Generate asset file for minified build
609
695
  ),
610
696
  ],
697
+ output: {
698
+ ...baseOutput,
699
+ file: path.join( outputDir, 'index.min.js' ),
700
+ minify: true,
701
+ },
611
702
  } ),
612
- esbuild.build( {
703
+ buildWithConcurrency( {
613
704
  ...baseConfig,
614
- outfile: path.join( outputDir, 'index.js' ),
615
- minify: false,
616
- define: getDefine( true ),
705
+ transform: {
706
+ target,
707
+ define: getDefine( true ),
708
+ jsx: JSX_OPTIONS,
709
+ },
710
+ resolve: { conditionNames: developmentConditions },
617
711
  plugins: [
618
712
  ...baseBundlePlugins,
619
713
  wordpressExternalsPlugin(
@@ -623,6 +717,11 @@ async function bundlePackage( packageName, options = {} ) {
623
717
  false // Skip asset file for non-minified build
624
718
  ),
625
719
  ],
720
+ output: {
721
+ ...baseOutput,
722
+ file: path.join( outputDir, 'index.js' ),
723
+ minify: false,
724
+ },
626
725
  } )
627
726
  );
628
727
 
@@ -664,23 +763,17 @@ async function bundlePackage( packageName, options = {} ) {
664
763
  );
665
764
 
666
765
  builds.push(
667
- esbuild.build( {
668
- entryPoints: [ entryPoint ],
669
- outfile: path.join(
670
- rootBuildModuleDir,
671
- `${ fileName }.min.js`
672
- ),
673
- bundle: true,
674
- // Emit UTF-8 so binary-encoded inlined WASM (e.g. the vips
675
- // worker) stays compact; ASCII output would escape high
676
- // bytes as \uXXXX and defeat the compression.
677
- charset: 'utf8',
678
- sourcemap: ! isWasmWorker,
679
- format: 'esm',
680
- target,
766
+ buildWithConcurrency( {
767
+ moduleTypes: LOADER_CONFIG,
768
+ checks: BASE_CHECKS,
769
+ input: entryPoint,
681
770
  platform: 'browser',
682
- minify: true,
683
- define: getDefine( false ),
771
+ transform: {
772
+ target,
773
+ define: getDefine( false ),
774
+ jsx: JSX_OPTIONS,
775
+ },
776
+ resolve: { conditionNames: defaultConditions },
684
777
  plugins: [
685
778
  styleRuntimeAliasPlugin(),
686
779
  wordpressExternalsPlugin(
@@ -690,25 +783,32 @@ async function bundlePackage( packageName, options = {} ) {
690
783
  true // Generate asset file for minified build
691
784
  ),
692
785
  ],
786
+ output: {
787
+ file: path.join(
788
+ rootBuildModuleDir,
789
+ `${ fileName }.min.js`
790
+ ),
791
+ codeSplitting: false,
792
+ sourcemap: ! isWasmWorker,
793
+ format: 'esm',
794
+ minify: true,
795
+ },
693
796
  } )
694
797
  );
695
798
 
696
799
  if ( ! isWasmWorker ) {
697
800
  builds.push(
698
- esbuild.build( {
699
- entryPoints: [ entryPoint ],
700
- outfile: path.join(
701
- rootBuildModuleDir,
702
- `${ fileName }.js`
703
- ),
704
- bundle: true,
705
- charset: 'utf8',
706
- sourcemap: true,
707
- format: 'esm',
708
- target,
801
+ buildWithConcurrency( {
802
+ moduleTypes: LOADER_CONFIG,
803
+ checks: BASE_CHECKS,
804
+ input: entryPoint,
709
805
  platform: 'browser',
710
- minify: false,
711
- define: getDefine( true ),
806
+ transform: {
807
+ target,
808
+ define: getDefine( true ),
809
+ jsx: JSX_OPTIONS,
810
+ },
811
+ resolve: { conditionNames: developmentConditions },
712
812
  plugins: [
713
813
  styleRuntimeAliasPlugin(),
714
814
  wordpressExternalsPlugin(
@@ -718,6 +818,16 @@ async function bundlePackage( packageName, options = {} ) {
718
818
  false // Skip asset file for non-minified build
719
819
  ),
720
820
  ],
821
+ output: {
822
+ file: path.join(
823
+ rootBuildModuleDir,
824
+ `${ fileName }.js`
825
+ ),
826
+ codeSplitting: false,
827
+ sourcemap: true,
828
+ format: 'esm',
829
+ minify: false,
830
+ },
721
831
  } )
722
832
  );
723
833
  }
@@ -916,7 +1026,7 @@ async function bundlePackage( packageName, options = {} ) {
916
1026
  /**
917
1027
  * Infer style dependencies from script dependencies.
918
1028
  * Only includes dependencies that:
919
- * 1. Are @wordpress packages (start with 'wp-')
1029
+ * 1. Are `@wordpress` packages (start with 'wp-')
920
1030
  * 2. Have wpScript: true in their package.json
921
1031
  * 3. Actually have a built style.css file
922
1032
  *
@@ -1306,7 +1416,8 @@ async function transpilePackage( packageName ) {
1306
1416
 
1307
1417
  const srcFiles = await glob( getSourceFileGlob( 'src/**/*' ), {
1308
1418
  cwd: packageDir,
1309
- ignore: IGNORE_PATTERNS,
1419
+ // Declaration files have no code to transpile.
1420
+ ignore: [ ...IGNORE_PATTERNS, '**/*.d.{ts,mts,cts}' ],
1310
1421
  absolute: true,
1311
1422
  } );
1312
1423
 
@@ -1328,115 +1439,110 @@ async function transpilePackage( packageName ) {
1328
1439
  // before worker bundling, but vips-worker.ts imports from worker-code.ts.
1329
1440
  await generateWorkerPlaceholder( packageDir, packageJson );
1330
1441
 
1331
- // Check if this is the components package that needs emotion babel plugin.
1332
- // Ideally we should remove this exception and move away from emotion.
1333
- const needsEmotionPlugin = packageName === 'components';
1334
- const emotionPlugin = babel( {
1335
- filter: /\.[cm]?[jt]sx?$/,
1336
- config: {
1337
- plugins: [ styleRuntimeRequire.resolve( '@emotion/babel-plugin' ) ],
1338
- },
1339
- } );
1340
- const externalizeAllExceptCssPlugin = {
1341
- name: 'externalize-except-css',
1342
- setup( build ) {
1343
- // Externalize all non-CSS imports
1344
- build.onResolve( { filter: /.*/ }, async ( args ) => {
1345
- // Skip recursive calls.
1346
- if ( args.pluginData?.__fromExternalize ) {
1347
- return null;
1348
- }
1349
-
1350
- // Skip entry points
1351
- if ( args.kind === 'entry-point' ) {
1352
- return null;
1353
- }
1354
-
1355
- // Let CSS/SCSS files be processed by sassPlugin
1356
- if ( args.path.match( /\.(css|scss)$/ ) ) {
1357
- return null;
1358
- }
1442
+ /*
1443
+ * Keeps imports external so each source file is transpiled on its own,
1444
+ * except for styles and SVGs, which are processed and inlined.
1445
+ */
1446
+ const externalizeJsImportsPlugin = {
1447
+ name: 'externalize-js-imports',
1448
+ async resolveId( source, importer, extraOptions ) {
1449
+ // Skip entry points
1450
+ if ( extraOptions.isEntry || ! importer ) {
1451
+ return null;
1452
+ }
1359
1453
 
1360
- // Fully resolve local dependencies without file extension
1361
- // and replace the extension with the target extension.
1362
- if ( args.path.startsWith( '.' ) ) {
1363
- const resolved = await build.resolve( args.path, {
1364
- namespace: args.namespace,
1365
- importer: args.importer,
1366
- kind: args.kind,
1367
- resolveDir: args.resolveDir,
1368
- with: args.with,
1369
- pluginData: {
1370
- ...args.pluginData,
1371
- __fromExternalize: true,
1372
- },
1373
- } );
1454
+ // Let CSS/SCSS files be processed by the style plugin
1455
+ if ( source.match( /\.(css|scss)$/ ) ) {
1456
+ return null;
1457
+ }
1374
1458
 
1375
- if ( resolved.errors.length > 0 ) {
1376
- return resolved;
1377
- }
1459
+ // Let SVG files be inlined by the `dataurl` module type.
1460
+ if ( source.endsWith( '.svg' ) ) {
1461
+ return null;
1462
+ }
1378
1463
 
1379
- // Relativize path: make it relative to resolveDir with leading ./
1380
- let relativePath = normalizePath(
1381
- path.relative( args.resolveDir, resolved.path )
1382
- );
1383
- if ( ! relativePath.startsWith( '.' ) ) {
1384
- relativePath = './' + relativePath;
1385
- }
1464
+ // Fully resolve local dependencies without file extension.
1465
+ // The output's `paths` replace the extension with the target extension.
1466
+ if ( source.startsWith( '.' ) ) {
1467
+ const resolved = await this.resolve( source, importer, {
1468
+ kind: extraOptions.kind,
1469
+ skipSelf: true,
1470
+ } );
1386
1471
 
1387
- // Replace extension: make sure that file extension is always `.mjs` or `.cjs`.
1388
- const newExt =
1389
- build.initialOptions.format === 'cjs' ? '.cjs' : '.mjs';
1390
- relativePath = relativePath.replace(
1391
- /\.[cm]?[jt]sx?$/,
1392
- newExt
1393
- );
1472
+ if ( ! resolved ) {
1473
+ return null;
1474
+ }
1394
1475
 
1395
- return {
1396
- path: relativePath,
1397
- external: true,
1398
- };
1476
+ // Relativize path: make it relative to the importer with leading ./
1477
+ let relativePath = normalizePath(
1478
+ path.relative( path.dirname( importer ), resolved.id )
1479
+ );
1480
+ if ( ! relativePath.startsWith( '.' ) ) {
1481
+ relativePath = './' + relativePath;
1399
1482
  }
1400
1483
 
1401
- // Externalize everything else (keep imports as-is)
1402
- return { path: args.path, external: true };
1403
- } );
1484
+ return {
1485
+ id: relativePath,
1486
+ external: true,
1487
+ };
1488
+ }
1489
+
1490
+ // Externalize everything else (keep imports as-is)
1491
+ return { id: source, external: true };
1404
1492
  },
1405
1493
  };
1406
1494
  const plugins = [
1407
- // Note: dsTokenFallbacksJs and emotionPlugin both use esbuild's onLoad
1408
- // hook, which is non-composable — the first to return contents wins. If a
1409
- // file contains --wpds-* tokens, the Emotion transform will be skipped.
1410
- // Avoid using design tokens in Emotion styles until Emotion is removed.
1411
1495
  dsTokenFallbacksJs,
1412
- needsEmotionPlugin && emotionPlugin,
1413
1496
  wasmInlinePlugin,
1414
1497
  // CSS modules import @wordpress/style-runtime in generated JS. Resolve
1415
1498
  // that alias before externalizing imports so the runtime is bundled.
1416
1499
  ...createStyleBundlingPlugins( packageDir ),
1417
- externalizeAllExceptCssPlugin,
1500
+ externalizeJsImportsPlugin,
1418
1501
  ].filter( Boolean );
1419
1502
 
1503
+ /*
1504
+ * Name each entry after its path in `src`, so the output mirrors it. Each
1505
+ * file is built on its own, so the modules it bundles (styles, the style
1506
+ * runtime, SVGs) are inlined into it instead of moved to shared chunks,
1507
+ * which would also reorder their side effects.
1508
+ */
1509
+ const entryPoints = srcFiles.map( ( file ) => ( {
1510
+ [ normalizePath( path.relative( srcDir, file ) ).replace(
1511
+ /\.[^./]+$/,
1512
+ ''
1513
+ ) ]: file,
1514
+ } ) );
1515
+
1516
+ // Make sure that file extension is always `.mjs` or `.cjs`.
1517
+ const replaceExtension = ( extension ) => ( id ) =>
1518
+ id.startsWith( '.' ) ? id.replace( /\.[cm]?[jt]sx?$/, extension ) : id;
1519
+
1420
1520
  if ( packageJson.main ) {
1421
- builds.push(
1422
- esbuild.build( {
1423
- entryPoints: srcFiles,
1424
- outdir: buildDir,
1425
- outbase: srcDir,
1426
- outExtension: { '.js': '.cjs' },
1427
- bundle: true,
1428
- // Emit UTF-8 so binary-encoded inlined WASM stays compact
1429
- // (ASCII output would escape high bytes as \uXXXX).
1430
- charset: 'utf8',
1431
- platform: 'node',
1432
- format: 'cjs',
1433
- sourcemap: true,
1434
- target,
1435
- jsx: 'automatic',
1436
- jsxImportSource: 'react',
1437
- plugins,
1438
- } )
1439
- );
1521
+ for ( const input of entryPoints ) {
1522
+ builds.push(
1523
+ buildWithConcurrency( {
1524
+ moduleTypes: LOADER_CONFIG,
1525
+ checks: BASE_CHECKS,
1526
+ input,
1527
+ platform: 'node',
1528
+ transform: { target, jsx: JSX_OPTIONS },
1529
+ // Every import is kept, as the imported files are transpiled on their own.
1530
+ treeshake: { moduleSideEffects: true },
1531
+ plugins: [ ...plugins, esModuleInteropPlugin ],
1532
+ output: {
1533
+ dir: buildDir,
1534
+ entryFileNames: '[name].cjs',
1535
+ codeSplitting: false,
1536
+ paths: replaceExtension( '.cjs' ),
1537
+ format: 'cjs',
1538
+ esModule: true,
1539
+ strict: true,
1540
+ exports: 'named',
1541
+ sourcemap: true,
1542
+ },
1543
+ } )
1544
+ );
1545
+ }
1440
1546
 
1441
1547
  for ( const assetFile of assetFiles ) {
1442
1548
  const relativePath = path.relative( srcDir, assetFile );
@@ -1451,25 +1557,28 @@ async function transpilePackage( packageName ) {
1451
1557
  }
1452
1558
 
1453
1559
  if ( packageJson.module ) {
1454
- builds.push(
1455
- esbuild.build( {
1456
- entryPoints: srcFiles,
1457
- outdir: buildModuleDir,
1458
- outbase: srcDir,
1459
- outExtension: { '.js': '.mjs' },
1460
- bundle: true,
1461
- // Emit UTF-8 so binary-encoded inlined WASM stays compact
1462
- // (ASCII output would escape high bytes as \uXXXX).
1463
- charset: 'utf8',
1464
- platform: 'neutral',
1465
- format: 'esm',
1466
- sourcemap: true,
1467
- target,
1468
- jsx: 'automatic',
1469
- jsxImportSource: 'react',
1470
- plugins,
1471
- } )
1472
- );
1560
+ for ( const input of entryPoints ) {
1561
+ builds.push(
1562
+ buildWithConcurrency( {
1563
+ moduleTypes: LOADER_CONFIG,
1564
+ checks: BASE_CHECKS,
1565
+ input,
1566
+ platform: 'neutral',
1567
+ transform: { target, jsx: JSX_OPTIONS },
1568
+ // Every import is kept, as the imported files are transpiled on their own.
1569
+ treeshake: { moduleSideEffects: true },
1570
+ plugins,
1571
+ output: {
1572
+ dir: buildModuleDir,
1573
+ entryFileNames: '[name].mjs',
1574
+ codeSplitting: false,
1575
+ paths: replaceExtension( '.mjs' ),
1576
+ format: 'esm',
1577
+ sourcemap: true,
1578
+ },
1579
+ } )
1580
+ );
1581
+ }
1473
1582
 
1474
1583
  for ( const jsonFile of assetFiles ) {
1475
1584
  const relativePath = path.relative( srcDir, jsonFile );
@@ -1559,56 +1668,36 @@ async function compileStyles( packageName ) {
1559
1668
 
1560
1669
  await mkdir( outputDir, { recursive: true } );
1561
1670
 
1562
- await esbuild.build( {
1563
- entryPoints: [ styleEntryPath ],
1564
- outdir: outputDir,
1565
- bundle: true,
1566
- write: false,
1567
- loader: {
1568
- '.scss': 'css',
1569
- },
1570
- plugins: [
1571
- sassPlugin( {
1572
- embedded: true,
1573
- ...getSassOptions( packageDir ),
1574
- async transform( source ) {
1575
- const ltrResult = await postcss(
1576
- [
1577
- dsTokenFallbacks,
1578
- autoprefixer( {
1579
- grid: true,
1580
- overrideBrowserslist:
1581
- getBrowserslistQueries(),
1582
- } ),
1583
- ].filter( Boolean )
1584
- ).process( source, { from: undefined } );
1585
-
1586
- const rtlResult = await postcss( [
1587
- rtlcss(),
1588
- ] ).process( ltrResult.css, { from: undefined } );
1589
-
1590
- await Promise.all( [
1591
- writeFile(
1592
- path.join(
1593
- outputDir,
1594
- `${ entryName }.css`
1595
- ),
1596
- ltrResult.css
1597
- ),
1598
- writeFile(
1599
- path.join(
1600
- outputDir,
1601
- `${ entryName }-rtl.css`
1602
- ),
1603
- rtlResult.css
1604
- ),
1605
- ] );
1606
-
1607
- return '';
1608
- },
1671
+ const source = await compileStylesheet(
1672
+ styleEntryPath,
1673
+ getSassOptions( packageDir )
1674
+ );
1675
+
1676
+ const ltrResult = await postcss(
1677
+ [
1678
+ dsTokenFallbacks,
1679
+ autoprefixer( {
1680
+ grid: true,
1681
+ overrideBrowserslist: getBrowserslistQueries(),
1609
1682
  } ),
1610
- ],
1611
- } );
1683
+ ].filter( Boolean )
1684
+ ).process( source, { from: undefined } );
1685
+
1686
+ const rtlResult = await postcss( [ rtlcss() ] ).process(
1687
+ ltrResult.css,
1688
+ { from: undefined }
1689
+ );
1690
+
1691
+ await Promise.all( [
1692
+ writeFile(
1693
+ path.join( outputDir, `${ entryName }.css` ),
1694
+ ltrResult.css
1695
+ ),
1696
+ writeFile(
1697
+ path.join( outputDir, `${ entryName }-rtl.css` ),
1698
+ rtlResult.css
1699
+ ),
1700
+ ] );
1612
1701
  } )
1613
1702
  );
1614
1703
 
@@ -1695,14 +1784,16 @@ async function buildRoute( routeName ) {
1695
1784
  if ( routeEntryPoints.length > 0 ) {
1696
1785
  // Build both minified and non-minified versions in parallel
1697
1786
  await Promise.all( [
1698
- esbuild.build( {
1699
- entryPoints: routeEntryPoints,
1700
- outfile: path.join( outputDir, 'route.min.js' ),
1701
- bundle: true,
1702
- format: 'esm',
1703
- target: getEsbuildTarget(),
1704
- minify: true,
1705
- define: getDefine( false ),
1787
+ buildWithConcurrency( {
1788
+ moduleTypes: LOADER_CONFIG,
1789
+ checks: BASE_CHECKS,
1790
+ input: routeEntryPoints,
1791
+ transform: {
1792
+ target: getEsbuildTarget(),
1793
+ define: getDefine( false ),
1794
+ jsx: JSX_OPTIONS,
1795
+ },
1796
+ resolve: { conditionNames: defaultConditions },
1706
1797
  plugins: [
1707
1798
  styleRuntimeAliasPlugin(),
1708
1799
  wordpressExternalsPlugin(
@@ -1712,15 +1803,23 @@ async function buildRoute( routeName ) {
1712
1803
  true // Generate asset file for minified build
1713
1804
  ),
1714
1805
  ],
1806
+ output: {
1807
+ file: path.join( outputDir, 'route.min.js' ),
1808
+ format: 'esm',
1809
+ minify: true,
1810
+ codeSplitting: false,
1811
+ },
1715
1812
  } ),
1716
- esbuild.build( {
1717
- entryPoints: routeEntryPoints,
1718
- outfile: path.join( outputDir, 'route.js' ),
1719
- bundle: true,
1720
- format: 'esm',
1721
- target: getEsbuildTarget(),
1722
- minify: false,
1723
- define: getDefine( true ),
1813
+ buildWithConcurrency( {
1814
+ moduleTypes: LOADER_CONFIG,
1815
+ checks: BASE_CHECKS,
1816
+ input: routeEntryPoints,
1817
+ transform: {
1818
+ target: getEsbuildTarget(),
1819
+ define: getDefine( true ),
1820
+ jsx: JSX_OPTIONS,
1821
+ },
1822
+ resolve: { conditionNames: developmentConditions },
1724
1823
  plugins: [
1725
1824
  styleRuntimeAliasPlugin(),
1726
1825
  wordpressExternalsPlugin(
@@ -1730,6 +1829,12 @@ async function buildRoute( routeName ) {
1730
1829
  false // Skip asset file for non-minified build
1731
1830
  ),
1732
1831
  ],
1832
+ output: {
1833
+ file: path.join( outputDir, 'route.js' ),
1834
+ format: 'esm',
1835
+ minify: false,
1836
+ codeSplitting: false,
1837
+ },
1733
1838
  } ),
1734
1839
  ] );
1735
1840
  }
@@ -1746,14 +1851,16 @@ async function buildRoute( routeName ) {
1746
1851
 
1747
1852
  // Build both minified and non-minified versions in parallel
1748
1853
  await Promise.all( [
1749
- esbuild.build( {
1750
- entryPoints: [ tempEntryPath ],
1751
- outfile: path.join( outputDir, 'content.min.js' ),
1752
- bundle: true,
1753
- format: 'esm',
1754
- target: getEsbuildTarget(),
1755
- minify: true,
1756
- define: getDefine( false ),
1854
+ buildWithConcurrency( {
1855
+ moduleTypes: LOADER_CONFIG,
1856
+ checks: BASE_CHECKS,
1857
+ input: [ tempEntryPath ],
1858
+ transform: {
1859
+ target: getEsbuildTarget(),
1860
+ define: getDefine( false ),
1861
+ jsx: JSX_OPTIONS,
1862
+ },
1863
+ resolve: { conditionNames: defaultConditions },
1757
1864
  plugins: [
1758
1865
  ...createStyleBundlingPlugins( routeDir ),
1759
1866
  wordpressExternalsPlugin(
@@ -1763,15 +1870,23 @@ async function buildRoute( routeName ) {
1763
1870
  true // Generate asset file for minified build
1764
1871
  ),
1765
1872
  ],
1873
+ output: {
1874
+ file: path.join( outputDir, 'content.min.js' ),
1875
+ format: 'esm',
1876
+ minify: true,
1877
+ codeSplitting: false,
1878
+ },
1766
1879
  } ),
1767
- esbuild.build( {
1768
- entryPoints: [ tempEntryPath ],
1769
- outfile: path.join( outputDir, 'content.js' ),
1770
- bundle: true,
1771
- format: 'esm',
1772
- target: getEsbuildTarget(),
1773
- minify: false,
1774
- define: getDefine( true ),
1880
+ buildWithConcurrency( {
1881
+ moduleTypes: LOADER_CONFIG,
1882
+ checks: BASE_CHECKS,
1883
+ input: [ tempEntryPath ],
1884
+ transform: {
1885
+ target: getEsbuildTarget(),
1886
+ define: getDefine( true ),
1887
+ jsx: JSX_OPTIONS,
1888
+ },
1889
+ resolve: { conditionNames: developmentConditions },
1775
1890
  plugins: [
1776
1891
  ...createStyleBundlingPlugins( routeDir ),
1777
1892
  wordpressExternalsPlugin(
@@ -1781,6 +1896,12 @@ async function buildRoute( routeName ) {
1781
1896
  false // Skip asset file for non-minified build
1782
1897
  ),
1783
1898
  ],
1899
+ output: {
1900
+ file: path.join( outputDir, 'content.js' ),
1901
+ format: 'esm',
1902
+ minify: false,
1903
+ codeSplitting: false,
1904
+ },
1784
1905
  } ),
1785
1906
  ] );
1786
1907
 
@@ -1856,14 +1977,16 @@ async function buildWidget( widgetName ) {
1856
1977
  if ( renderEntryPoints.length > 0 ) {
1857
1978
  // Build both minified and non-minified versions in parallel
1858
1979
  await Promise.all( [
1859
- esbuild.build( {
1860
- entryPoints: renderEntryPoints,
1861
- outfile: path.join( outputDir, 'render.min.js' ),
1862
- bundle: true,
1863
- format: 'esm',
1864
- target: getEsbuildTarget(),
1865
- minify: true,
1866
- define: getDefine( false ),
1980
+ buildWithConcurrency( {
1981
+ moduleTypes: LOADER_CONFIG,
1982
+ checks: BASE_CHECKS,
1983
+ input: renderEntryPoints,
1984
+ transform: {
1985
+ target: getEsbuildTarget(),
1986
+ define: getDefine( false ),
1987
+ jsx: JSX_OPTIONS,
1988
+ },
1989
+ resolve: { conditionNames: defaultConditions },
1867
1990
  plugins: [
1868
1991
  ...createStyleBundlingPlugins( widgetDir ),
1869
1992
  wordpressExternalsPlugin(
@@ -1873,15 +1996,23 @@ async function buildWidget( widgetName ) {
1873
1996
  true // Generate asset file for minified build
1874
1997
  ),
1875
1998
  ],
1999
+ output: {
2000
+ file: path.join( outputDir, 'render.min.js' ),
2001
+ format: 'esm',
2002
+ minify: true,
2003
+ codeSplitting: false,
2004
+ },
1876
2005
  } ),
1877
- esbuild.build( {
1878
- entryPoints: renderEntryPoints,
1879
- outfile: path.join( outputDir, 'render.js' ),
1880
- bundle: true,
1881
- format: 'esm',
1882
- target: getEsbuildTarget(),
1883
- minify: false,
1884
- define: getDefine( true ),
2006
+ buildWithConcurrency( {
2007
+ moduleTypes: LOADER_CONFIG,
2008
+ checks: BASE_CHECKS,
2009
+ input: renderEntryPoints,
2010
+ transform: {
2011
+ target: getEsbuildTarget(),
2012
+ define: getDefine( true ),
2013
+ jsx: JSX_OPTIONS,
2014
+ },
2015
+ resolve: { conditionNames: developmentConditions },
1885
2016
  plugins: [
1886
2017
  ...createStyleBundlingPlugins( widgetDir ),
1887
2018
  wordpressExternalsPlugin(
@@ -1891,6 +2022,12 @@ async function buildWidget( widgetName ) {
1891
2022
  false // Skip asset file for non-minified build
1892
2023
  ),
1893
2024
  ],
2025
+ output: {
2026
+ file: path.join( outputDir, 'render.js' ),
2027
+ format: 'esm',
2028
+ minify: false,
2029
+ codeSplitting: false,
2030
+ },
1894
2031
  } ),
1895
2032
  ] );
1896
2033
  }
@@ -1906,14 +2043,16 @@ async function buildWidget( widgetName ) {
1906
2043
  if ( widgetEntryPoints.length > 0 ) {
1907
2044
  // Build both minified and non-minified versions in parallel
1908
2045
  await Promise.all( [
1909
- esbuild.build( {
1910
- entryPoints: widgetEntryPoints,
1911
- outfile: path.join( outputDir, 'widget.min.js' ),
1912
- bundle: true,
1913
- format: 'esm',
1914
- target: getEsbuildTarget(),
1915
- minify: true,
1916
- define: getDefine( false ),
2046
+ buildWithConcurrency( {
2047
+ moduleTypes: LOADER_CONFIG,
2048
+ checks: BASE_CHECKS,
2049
+ input: widgetEntryPoints,
2050
+ transform: {
2051
+ target: getEsbuildTarget(),
2052
+ define: getDefine( false ),
2053
+ jsx: JSX_OPTIONS,
2054
+ },
2055
+ resolve: { conditionNames: defaultConditions },
1917
2056
  plugins: [
1918
2057
  styleRuntimeAliasPlugin(),
1919
2058
  wordpressExternalsPlugin(
@@ -1923,15 +2062,23 @@ async function buildWidget( widgetName ) {
1923
2062
  true // Generate asset file for minified build
1924
2063
  ),
1925
2064
  ],
2065
+ output: {
2066
+ file: path.join( outputDir, 'widget.min.js' ),
2067
+ format: 'esm',
2068
+ minify: true,
2069
+ codeSplitting: false,
2070
+ },
1926
2071
  } ),
1927
- esbuild.build( {
1928
- entryPoints: widgetEntryPoints,
1929
- outfile: path.join( outputDir, 'widget.js' ),
1930
- bundle: true,
1931
- format: 'esm',
1932
- target: getEsbuildTarget(),
1933
- minify: false,
1934
- define: getDefine( true ),
2072
+ buildWithConcurrency( {
2073
+ moduleTypes: LOADER_CONFIG,
2074
+ checks: BASE_CHECKS,
2075
+ input: widgetEntryPoints,
2076
+ transform: {
2077
+ target: getEsbuildTarget(),
2078
+ define: getDefine( true ),
2079
+ jsx: JSX_OPTIONS,
2080
+ },
2081
+ resolve: { conditionNames: developmentConditions },
1935
2082
  plugins: [
1936
2083
  styleRuntimeAliasPlugin(),
1937
2084
  wordpressExternalsPlugin(
@@ -1941,6 +2088,12 @@ async function buildWidget( widgetName ) {
1941
2088
  false // Skip asset file for non-minified build
1942
2089
  ),
1943
2090
  ],
2091
+ output: {
2092
+ file: path.join( outputDir, 'widget.js' ),
2093
+ format: 'esm',
2094
+ minify: false,
2095
+ codeSplitting: false,
2096
+ },
1944
2097
  } ),
1945
2098
  ] );
1946
2099
  }
@@ -1982,7 +2135,7 @@ async function buildAllWidgets() {
1982
2135
  * Discover all widgets and collect their registry-facing data.
1983
2136
  * Widgets without a valid widget.json are skipped.
1984
2137
  *
1985
- * @return {Array<{ name: string, dirName: string, title: string | null, description: string | null, help: import('./widget-utils.mjs').WidgetHelpMetadata | null, icon: string | null, actions: import('./widget-utils.mjs').WidgetActionMetadata[] | null, attributes: import('./widget-utils.mjs').WidgetAttributeMetadata[] | null, hasRender: boolean, hasWidget: boolean, presentation: string | null, category: string | null, keywords: string[] | null, textdomain: string | null }>} Array of widget objects.
2138
+ * @return {Array<{ name: string, dirName: string, title: string | null, description: string | null, help: import('./widget-utils.mjs').WidgetHelpMetadata | null, icon: string | null, actions: import('./widget-utils.mjs').WidgetActionMetadata[] | null, attributes: import('./widget-utils.mjs').WidgetAttributeMetadata[] | null, example: import('./widget-utils.mjs').WidgetExampleMetadata | null, hasRender: boolean, hasWidget: boolean, presentation: string | null, category: string | null, keywords: string[] | null, textdomain: string | null }>} Array of widget objects.
1986
2139
  */
1987
2140
  function collectWidgets() {
1988
2141
  return getAllWidgets( ROOT_DIR ).flatMap( ( widgetName ) => {
@@ -2007,6 +2160,7 @@ function collectWidgets() {
2007
2160
  icon: metadata.icon ?? null,
2008
2161
  actions: metadata.actions ?? null,
2009
2162
  attributes: metadata.attributes ?? null,
2163
+ example: metadata.example ?? null,
2010
2164
  hasRender: widgetFiles.hasRender,
2011
2165
  hasWidget: widgetFiles.hasWidget,
2012
2166
  presentation: metadata.presentation ?? null,
@@ -2217,6 +2371,29 @@ function toPhpAttributesLiteral( attributes ) {
2217
2371
  return `array( ${ entries.join( ', ' ) } )`;
2218
2372
  }
2219
2373
 
2374
+ /**
2375
+ * Format a widget's example as a PHP array literal: `attributes` copied as
2376
+ * declared, with the registration gate constraining the values. Returns the
2377
+ * PHP literal `null` unless `example` carries a non-empty `attributes`
2378
+ * object.
2379
+ *
2380
+ * @param {import('./widget-utils.mjs').WidgetExampleMetadata|null|undefined} example Source value.
2381
+ * @return {string} PHP array literal, or `null`.
2382
+ */
2383
+ function toPhpExampleLiteral( example ) {
2384
+ const attributes = example?.attributes;
2385
+ if (
2386
+ ! attributes ||
2387
+ typeof attributes !== 'object' ||
2388
+ Array.isArray( attributes ) ||
2389
+ Object.keys( attributes ).length === 0
2390
+ ) {
2391
+ return 'null';
2392
+ }
2393
+
2394
+ return toPhpValueLiteral( { attributes } );
2395
+ }
2396
+
2220
2397
  /**
2221
2398
  * Generate global widget registry file.
2222
2399
  * Creates a single registry with all widgets including file availability.
@@ -2245,6 +2422,7 @@ async function generateWidgetRegistry( widgets, replacements ) {
2245
2422
  const iconStr = toPhpStringLiteral( widget.icon );
2246
2423
  const actionsStr = toPhpActionsLiteral( widget.actions );
2247
2424
  const attributesStr = toPhpAttributesLiteral( widget.attributes );
2425
+ const exampleStr = toPhpExampleLiteral( widget.example );
2248
2426
  const keywordsStr = toPhpStringArrayLiteral( widget.keywords );
2249
2427
  const textdomainStr = toPhpStringLiteral( widget.textdomain );
2250
2428
  return `\tarray(
@@ -2256,6 +2434,7 @@ async function generateWidgetRegistry( widgets, replacements ) {
2256
2434
  'icon' => ${ iconStr },
2257
2435
  'actions' => ${ actionsStr },
2258
2436
  'attributes' => ${ attributesStr },
2437
+ 'example' => ${ exampleStr },
2259
2438
  'has_render' => ${ hasRenderStr },
2260
2439
  'has_widget' => ${ hasWidgetStr },
2261
2440
  'presentation' => ${ presentationStr },
@@ -2846,12 +3025,17 @@ async function main() {
2846
3025
  } );
2847
3026
 
2848
3027
  const baseUrlExpression = values[ 'base-url' ];
3028
+ const buildConcurrency = getDefaultBuildConcurrency();
3029
+ setBuildConcurrency( buildConcurrency );
3030
+ console.log( `⚙️ Using build concurrency: ${ buildConcurrency }\n` );
2849
3031
 
2850
3032
  await buildAll( baseUrlExpression );
2851
3033
 
2852
3034
  if ( values.watch ) {
2853
3035
  console.log( '\n👀 Watching for changes...\n' );
2854
3036
  await watchMode();
3037
+ } else {
3038
+ await disposeSassCompiler();
2855
3039
  }
2856
3040
  }
2857
3041