@wordpress/build 0.27.0 → 0.29.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
@@ -23,10 +23,13 @@ import {
23
23
  getPhpReplacements,
24
24
  renderTemplateToString,
25
25
  } from './php-generator.mjs';
26
- import { getPackageInfo, getPackageInfoFromFile } from './package-utils.mjs';
26
+ import { boolConfigVal, getPackageInfoFromFile } from './package-utils.mjs';
27
+ import { copyPackageFile, getCopyFiles } from './copy-files.mjs';
28
+ import { inferStyleDependencies } from './style-dependencies.mjs';
27
29
  import { getBrowserslistQueries } from './browserslist.mjs';
28
30
  import { getSourceFileGlob, isTestSourceFile } from './source-files.mjs';
29
31
  import { createWordpressExternalsPlugin } from './wordpress-externals-plugin.mjs';
32
+ import { translatorCommentsPlugin } from './translator-comments-plugin.mjs';
30
33
  import {
31
34
  getAllRoutes,
32
35
  getRouteFiles,
@@ -110,20 +113,6 @@ const PAGES = WP_PLUGIN_CONFIG.pages || [];
110
113
  // enforce this themselves.
111
114
  const DEFAULT_PAGE_CAPABILITY = 'manage_options';
112
115
 
113
- /**
114
- * Interprets a configuration value as a boolean, where `"true"` and `"1"`
115
- * are considered true while all other values are false.
116
- *
117
- * @param {string|undefined} value The configuration value to interpret.
118
- * @return {boolean|undefined} Boolean interpretation of the given configuration value, or undefined if not set.
119
- */
120
- const boolConfigVal = ( value ) => {
121
- if ( value === undefined ) {
122
- return undefined;
123
- }
124
- return [ 'true', '1' ].includes( value.toLowerCase() );
125
- };
126
-
127
116
  const baseDefine = {
128
117
  'globalThis.IS_GUTENBERG_PLUGIN': JSON.stringify(
129
118
  boolConfigVal( process.env.IS_GUTENBERG_PLUGIN ) ??
@@ -419,65 +408,6 @@ function normalizePath( p ) {
419
408
  return p.replace( /\\/g, '/' );
420
409
  }
421
410
 
422
- function transformPhpContent( content, transforms ) {
423
- const {
424
- functionPrefix = '',
425
- classSuffix = '',
426
- prefixFunctions = [],
427
- suffixClasses = [],
428
- addActionPriority,
429
- } = transforms;
430
-
431
- content = content.toString();
432
-
433
- /*
434
- * Transforms are used to modify PHP files that are committed to version
435
- * control in their wordpress-develop state (`wp_` function prefixes, `WP_`
436
- * class prefixes, etc.). When building for WordPress Core, it's not
437
- * necessary to perform these steps.
438
- */
439
- if (
440
- boolConfigVal( process.env.IS_WORDPRESS_CORE ) ??
441
- boolConfigVal( process.env.npm_package_config_IS_WORDPRESS_CORE )
442
- ) {
443
- return content;
444
- }
445
-
446
- if ( prefixFunctions.length ) {
447
- content = content.replace(
448
- new RegExp( prefixFunctions.join( '|' ), 'g' ),
449
- ( match ) => `${ functionPrefix }${ match.replace( /^wp_/, '' ) }`
450
- );
451
- }
452
-
453
- if ( suffixClasses.length ) {
454
- content = content.replace(
455
- new RegExp( suffixClasses.join( '|' ), 'g' ),
456
- ( match ) => `${ match }${ classSuffix }`
457
- );
458
- }
459
-
460
- if ( functionPrefix ) {
461
- content = Array.from(
462
- content.matchAll( /^\s*function ([^\(]+)/gm )
463
- ).reduce( ( result, [ , functionName ] ) => {
464
- return result.replace(
465
- new RegExp( functionName + '(?![a-zA-Z0-9_])', 'g' ),
466
- ( match ) => functionPrefix + match.replace( /^wp_/, '' )
467
- );
468
- }, content );
469
- }
470
-
471
- if ( addActionPriority ) {
472
- content = content.replace(
473
- /(add_action\(\s*'init',\s*'gutenberg_register_block_[^']+'(?!,))/,
474
- `$1, ${ addActionPriority }`
475
- );
476
- }
477
-
478
- return content;
479
- }
480
-
481
411
  /**
482
412
  * Plugin to handle moment-timezone aliases.
483
413
  * Redirects moment-timezone imports to use pre-built bundles with limited data.
@@ -610,6 +540,7 @@ async function bundlePackage( packageName, options = {} ) {
610
540
  handlePrefix = HANDLE_PREFIX,
611
541
  scriptGlobal = SCRIPT_GLOBAL,
612
542
  packageNamespace = PACKAGE_NAMESPACE,
543
+ noScriptDebug = false,
613
544
  } = options;
614
545
 
615
546
  const builtModules = [];
@@ -699,32 +630,37 @@ async function bundlePackage( packageName, options = {} ) {
699
630
  file: path.join( outputDir, 'index.min.js' ),
700
631
  minify: true,
701
632
  },
702
- } ),
703
- buildWithConcurrency( {
704
- ...baseConfig,
705
- transform: {
706
- target,
707
- define: getDefine( true ),
708
- jsx: JSX_OPTIONS,
709
- },
710
- resolve: { conditionNames: developmentConditions },
711
- plugins: [
712
- ...baseBundlePlugins,
713
- wordpressExternalsPlugin(
714
- 'index.min',
715
- 'iife',
716
- packageJson.wpScriptExtraDependencies || [],
717
- false // Skip asset file for non-minified build
718
- ),
719
- ],
720
- output: {
721
- ...baseOutput,
722
- file: path.join( outputDir, 'index.js' ),
723
- minify: false,
724
- },
725
633
  } )
726
634
  );
727
635
 
636
+ if ( ! noScriptDebug ) {
637
+ builds.push(
638
+ buildWithConcurrency( {
639
+ ...baseConfig,
640
+ transform: {
641
+ target,
642
+ define: getDefine( true ),
643
+ jsx: JSX_OPTIONS,
644
+ },
645
+ resolve: { conditionNames: developmentConditions },
646
+ plugins: [
647
+ ...baseBundlePlugins,
648
+ wordpressExternalsPlugin(
649
+ 'index.min',
650
+ 'iife',
651
+ packageJson.wpScriptExtraDependencies || [],
652
+ false // Skip asset file for non-minified build
653
+ ),
654
+ ],
655
+ output: {
656
+ ...baseOutput,
657
+ file: path.join( outputDir, 'index.js' ),
658
+ minify: false,
659
+ },
660
+ } )
661
+ );
662
+ }
663
+
728
664
  builtScripts.push( {
729
665
  handle: `${ handlePrefix }-${ packageName }`,
730
666
  path: `${ packageName }/index`,
@@ -796,7 +732,7 @@ async function bundlePackage( packageName, options = {} ) {
796
732
  } )
797
733
  );
798
734
 
799
- if ( ! isWasmWorker ) {
735
+ if ( ! noScriptDebug && ! isWasmWorker ) {
800
736
  builds.push(
801
737
  buildWithConcurrency( {
802
738
  moduleTypes: LOADER_CONFIG,
@@ -868,18 +804,17 @@ async function bundlePackage( packageName, options = {} ) {
868
804
  // Generate minified path: style.css -> style.min.css, style-rtl.css -> style-rtl.min.css
869
805
  const minifiedPath = destPath.replace( /\.css$/, '.min.css' );
870
806
 
871
- // Always produce both versions (like JavaScript does):
872
- // 1. Non-minified version (for SCRIPT_DEBUG=true)
873
- // 2. Minified version (for SCRIPT_DEBUG=false)
874
807
  builds.push(
875
808
  ( async () => {
876
809
  await mkdir( destDir, { recursive: true } );
877
810
  const content = await readFile( cssFile, 'utf8' );
878
811
 
879
- // Write non-minified version
880
- await writeFile( destPath, content );
812
+ // Write non-minified version (for SCRIPT_DEBUG=true)
813
+ if ( ! noScriptDebug ) {
814
+ await writeFile( destPath, content );
815
+ }
881
816
 
882
- // Write minified version
817
+ // Write minified version (for SCRIPT_DEBUG=false)
883
818
  const result = await postcss( [
884
819
  cssnano( {
885
820
  preset: [
@@ -901,76 +836,15 @@ async function bundlePackage( packageName, options = {} ) {
901
836
  }
902
837
  }
903
838
 
904
- if ( packageJson.wpCopyFiles ) {
905
- const { files, transforms = {} } = packageJson.wpCopyFiles;
906
- const packageSourceDir = path.join( packageDir, 'src' );
907
- const outputDir = path.join( BUILD_DIR, 'scripts', packageName );
908
-
909
- for ( const filePattern of files ) {
910
- const matchedFiles = await glob(
911
- normalizePath( path.join( packageDir, filePattern ) )
912
- );
913
-
914
- for ( const sourceFile of matchedFiles ) {
915
- const relativePath = path.relative(
916
- packageSourceDir,
917
- sourceFile
918
- );
919
- const destPath = path.join( outputDir, relativePath );
920
- const destDir = path.dirname( destPath );
921
-
922
- if ( sourceFile.endsWith( '.php' ) && transforms.php ) {
923
- builds.push(
924
- ( async () => {
925
- let finalPath = destPath;
926
- let finalDir = destDir;
927
-
928
- const content = await readFile(
929
- sourceFile,
930
- 'utf8'
931
- );
932
- const transformed = transformPhpContent(
933
- content,
934
- transforms.php
935
- );
936
-
937
- if ( transforms.php.filenameSuffix ) {
938
- const ext = path.extname( destPath );
939
- const base = path.basename( destPath, ext );
940
- finalPath = path.join(
941
- destDir,
942
- `${ base }${ transforms.php.filenameSuffix }${ ext }`
943
- );
944
- }
945
-
946
- // Check if we should flatten index.php files
947
- if (
948
- transforms.php.flattenIndexFiles &&
949
- path.basename( sourceFile ) === 'index.php'
950
- ) {
951
- // Flatten: button/index.php → button.php
952
- const parentDir = path.dirname( finalPath );
953
- const blockName = path.basename( parentDir );
954
- finalPath = path.join(
955
- path.dirname( parentDir ),
956
- `${ blockName }.php`
957
- );
958
- finalDir = path.dirname( finalPath );
959
- }
960
-
961
- await mkdir( finalDir, { recursive: true } );
962
- await writeFile( finalPath, transformed );
963
- } )()
964
- );
965
- } else {
966
- builds.push(
967
- mkdir( destDir, { recursive: true } ).then( () =>
968
- copyFile( sourceFile, destPath )
969
- )
970
- );
971
- }
972
- }
973
- }
839
+ for ( const sourceFile of await getCopyFiles( packageDir, packageJson ) ) {
840
+ builds.push(
841
+ copyPackageFile(
842
+ sourceFile,
843
+ packageDir,
844
+ path.join( BUILD_DIR, 'scripts', packageName ),
845
+ packageJson
846
+ )
847
+ );
974
848
  }
975
849
 
976
850
  if ( builds.length === 0 ) {
@@ -1004,10 +878,10 @@ async function bundlePackage( packageName, options = {} ) {
1004
878
  ?.map( ( d ) => d.replace( /'/g, '' ) ) || [];
1005
879
  }
1006
880
 
1007
- const styleDeps = await inferStyleDependencies(
1008
- scriptDependencies,
1009
- packageName
1010
- );
881
+ const styleDeps = await inferStyleDependencies( scriptDependencies, {
882
+ resolveDir: path.join( PACKAGES_DIR, packageName ),
883
+ buildDir: BUILD_DIR,
884
+ } );
1011
885
 
1012
886
  builtStyles.push( {
1013
887
  handle: `${ handlePrefix }-${ packageName }`,
@@ -1023,69 +897,6 @@ async function bundlePackage( packageName, options = {} ) {
1023
897
  };
1024
898
  }
1025
899
 
1026
- /**
1027
- * Infer style dependencies from script dependencies.
1028
- * Only includes dependencies that:
1029
- * 1. Are `@wordpress` packages (start with 'wp-')
1030
- * 2. Have wpScript: true in their package.json
1031
- * 3. Actually have a built style.css file
1032
- *
1033
- * @param {string[]} scriptDependencies Array of script handles from asset file.
1034
- * @param {string} packageName Package name (short name) being bundled, for context-aware resolution.
1035
- * @return {Promise<string[]>} Array of style handles to depend on.
1036
- */
1037
- async function inferStyleDependencies( scriptDependencies, packageName ) {
1038
- if ( ! scriptDependencies || scriptDependencies.length === 0 ) {
1039
- return [];
1040
- }
1041
-
1042
- const styleDeps = [];
1043
- // Get the resolve directory for context-aware package resolution
1044
- const resolveDir = path.join( PACKAGES_DIR, packageName );
1045
-
1046
- for ( const scriptHandle of scriptDependencies ) {
1047
- // Skip non-package dependencies (like 'react', 'lodash', etc.)
1048
- if ( ! scriptHandle.startsWith( 'wp-' ) ) {
1049
- continue;
1050
- }
1051
-
1052
- // Convert handle to package name: 'wp-components' → '@wordpress/components'
1053
- const shortName = scriptHandle.replace( 'wp-', '' );
1054
- const depPackageName = `@wordpress/${ shortName }`;
1055
-
1056
- // Read the dependency's package.json with context-aware resolution
1057
- try {
1058
- const depPackageJson = getPackageInfo( depPackageName, resolveDir );
1059
-
1060
- if ( ! depPackageJson ) {
1061
- continue;
1062
- }
1063
-
1064
- // ONLY include if it has wpScript: true (which means it builds styles)
1065
- if ( depPackageJson.wpScript === true ) {
1066
- // Double-check the style file actually exists
1067
- const styleFile = path.join(
1068
- BUILD_DIR,
1069
- 'styles',
1070
- shortName,
1071
- 'style.css'
1072
- );
1073
- try {
1074
- await readFile( styleFile );
1075
- styleDeps.push( scriptHandle );
1076
- } catch {
1077
- // Style file doesn't exist, skip it
1078
- }
1079
- }
1080
- } catch {
1081
- // Package not found or can't read package.json - skip it
1082
- continue;
1083
- }
1084
- }
1085
-
1086
- return styleDeps;
1087
- }
1088
-
1089
900
  /**
1090
901
  * Generate PHP files for script module registration.
1091
902
  *
@@ -1492,6 +1303,9 @@ async function transpilePackage( packageName ) {
1492
1303
  },
1493
1304
  };
1494
1305
  const plugins = [
1306
+ // Keeps translator comments in `build` and `build-module`, which the
1307
+ // script and module bundles are built from.
1308
+ translatorCommentsPlugin(),
1495
1309
  dsTokenFallbacksJs,
1496
1310
  wasmInlinePlugin,
1497
1311
  // CSS modules import @wordpress/style-runtime in generated JS. Resolve
@@ -1761,10 +1575,12 @@ function getPackageName( filename ) {
1761
1575
  /**
1762
1576
  * Build a single route's files.
1763
1577
  *
1764
- * @param {string} routeName Route name.
1578
+ * @param {string} routeName Route name.
1579
+ * @param {Object} root0 Options object.
1580
+ * @param {boolean} root0.noScriptDebug Whether to skip unminified builds.
1765
1581
  * @return {Promise<number>} Build time in milliseconds.
1766
1582
  */
1767
- async function buildRoute( routeName ) {
1583
+ async function buildRoute( routeName, { noScriptDebug = false } = {} ) {
1768
1584
  const startTime = Date.now();
1769
1585
  const routeDir = path.join( ROOT_DIR, 'routes', routeName );
1770
1586
  const outputDir = path.join( BUILD_DIR, 'routes', routeName );
@@ -1782,8 +1598,7 @@ async function buildRoute( routeName ) {
1782
1598
  } );
1783
1599
 
1784
1600
  if ( routeEntryPoints.length > 0 ) {
1785
- // Build both minified and non-minified versions in parallel
1786
- await Promise.all( [
1601
+ const routeBuilds = [
1787
1602
  buildWithConcurrency( {
1788
1603
  moduleTypes: LOADER_CONFIG,
1789
1604
  checks: BASE_CHECKS,
@@ -1810,33 +1625,41 @@ async function buildRoute( routeName ) {
1810
1625
  codeSplitting: false,
1811
1626
  },
1812
1627
  } ),
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 },
1823
- plugins: [
1824
- styleRuntimeAliasPlugin(),
1825
- wordpressExternalsPlugin(
1826
- 'route.min',
1827
- 'esm',
1828
- [],
1829
- false // Skip asset file for non-minified build
1830
- ),
1831
- ],
1832
- output: {
1833
- file: path.join( outputDir, 'route.js' ),
1834
- format: 'esm',
1835
- minify: false,
1836
- codeSplitting: false,
1837
- },
1838
- } ),
1839
- ] );
1628
+ ];
1629
+
1630
+ if ( ! noScriptDebug ) {
1631
+ routeBuilds.push(
1632
+ buildWithConcurrency( {
1633
+ moduleTypes: LOADER_CONFIG,
1634
+ checks: BASE_CHECKS,
1635
+ input: routeEntryPoints,
1636
+ transform: {
1637
+ target: getEsbuildTarget(),
1638
+ define: getDefine( true ),
1639
+ jsx: JSX_OPTIONS,
1640
+ },
1641
+ resolve: { conditionNames: developmentConditions },
1642
+ plugins: [
1643
+ translatorCommentsPlugin(),
1644
+ styleRuntimeAliasPlugin(),
1645
+ wordpressExternalsPlugin(
1646
+ 'route.min',
1647
+ 'esm',
1648
+ [],
1649
+ false // Skip asset file for non-minified build
1650
+ ),
1651
+ ],
1652
+ output: {
1653
+ file: path.join( outputDir, 'route.js' ),
1654
+ format: 'esm',
1655
+ minify: false,
1656
+ codeSplitting: false,
1657
+ },
1658
+ } )
1659
+ );
1660
+ }
1661
+
1662
+ await Promise.all( routeBuilds );
1840
1663
  }
1841
1664
  }
1842
1665
 
@@ -1849,8 +1672,7 @@ async function buildRoute( routeName ) {
1849
1672
  // Write temporary entry file
1850
1673
  await writeFile( tempEntryPath, syntheticEntry );
1851
1674
 
1852
- // Build both minified and non-minified versions in parallel
1853
- await Promise.all( [
1675
+ const contentBuilds = [
1854
1676
  buildWithConcurrency( {
1855
1677
  moduleTypes: LOADER_CONFIG,
1856
1678
  checks: BASE_CHECKS,
@@ -1877,33 +1699,41 @@ async function buildRoute( routeName ) {
1877
1699
  codeSplitting: false,
1878
1700
  },
1879
1701
  } ),
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 },
1890
- plugins: [
1891
- ...createStyleBundlingPlugins( routeDir ),
1892
- wordpressExternalsPlugin(
1893
- 'content.min',
1894
- 'esm',
1895
- [],
1896
- false // Skip asset file for non-minified build
1897
- ),
1898
- ],
1899
- output: {
1900
- file: path.join( outputDir, 'content.js' ),
1901
- format: 'esm',
1902
- minify: false,
1903
- codeSplitting: false,
1904
- },
1905
- } ),
1906
- ] );
1702
+ ];
1703
+
1704
+ if ( ! noScriptDebug ) {
1705
+ contentBuilds.push(
1706
+ buildWithConcurrency( {
1707
+ moduleTypes: LOADER_CONFIG,
1708
+ checks: BASE_CHECKS,
1709
+ input: [ tempEntryPath ],
1710
+ transform: {
1711
+ target: getEsbuildTarget(),
1712
+ define: getDefine( true ),
1713
+ jsx: JSX_OPTIONS,
1714
+ },
1715
+ resolve: { conditionNames: developmentConditions },
1716
+ plugins: [
1717
+ translatorCommentsPlugin(),
1718
+ ...createStyleBundlingPlugins( routeDir ),
1719
+ wordpressExternalsPlugin(
1720
+ 'content.min',
1721
+ 'esm',
1722
+ [],
1723
+ false // Skip asset file for non-minified build
1724
+ ),
1725
+ ],
1726
+ output: {
1727
+ file: path.join( outputDir, 'content.js' ),
1728
+ format: 'esm',
1729
+ minify: false,
1730
+ codeSplitting: false,
1731
+ },
1732
+ } )
1733
+ );
1734
+ }
1735
+
1736
+ await Promise.all( contentBuilds );
1907
1737
 
1908
1738
  await unlink( tempEntryPath );
1909
1739
  }
@@ -1918,9 +1748,14 @@ async function buildRoute( routeName ) {
1918
1748
  * empty set (the default) to build every route.
1919
1749
  *
1920
1750
  * @param {Set<string>} experimentalPageIds Page ids marked experimental.
1751
+ * @param {Object} root1 Options object.
1752
+ * @param {boolean} root1.noScriptDebug Whether to skip unminified builds.
1921
1753
  * @return {Promise<void>}
1922
1754
  */
1923
- async function buildRoutes( experimentalPageIds = new Set() ) {
1755
+ async function buildRoutes(
1756
+ experimentalPageIds = new Set(),
1757
+ { noScriptDebug = false } = {}
1758
+ ) {
1924
1759
  console.log( '\n🚦 Phase 3: Building routes...\n' );
1925
1760
 
1926
1761
  const allRoutes = getAllRoutes( ROOT_DIR );
@@ -1945,7 +1780,7 @@ async function buildRoutes( experimentalPageIds = new Set() ) {
1945
1780
 
1946
1781
  await Promise.all(
1947
1782
  routes.map( async ( routeName ) => {
1948
- const buildTime = await buildRoute( routeName );
1783
+ const buildTime = await buildRoute( routeName, { noScriptDebug } );
1949
1784
  console.log( ` ✔ Built route ${ routeName } (${ buildTime }ms)` );
1950
1785
  } )
1951
1786
  );
@@ -1954,10 +1789,12 @@ async function buildRoutes( experimentalPageIds = new Set() ) {
1954
1789
  /**
1955
1790
  * Build a single widget's files.
1956
1791
  *
1957
- * @param {string} widgetName Widget name.
1792
+ * @param {string} widgetName Widget name.
1793
+ * @param {Object} root0 Options object.
1794
+ * @param {boolean} root0.noScriptDebug Whether to skip unminified builds.
1958
1795
  * @return {Promise<number>} Build time in milliseconds.
1959
1796
  */
1960
- async function buildWidget( widgetName ) {
1797
+ async function buildWidget( widgetName, { noScriptDebug = false } = {} ) {
1961
1798
  const startTime = Date.now();
1962
1799
  const widgetDir = path.join( ROOT_DIR, 'widgets', widgetName );
1963
1800
  const outputDir = path.join( BUILD_DIR, 'widgets', widgetName );
@@ -1975,8 +1812,8 @@ async function buildWidget( widgetName ) {
1975
1812
  } );
1976
1813
 
1977
1814
  if ( renderEntryPoints.length > 0 ) {
1978
- // Build both minified and non-minified versions in parallel
1979
- await Promise.all( [
1815
+ // Build minified and (unless skipped) non-minified versions in parallel
1816
+ const renderBuilds = [
1980
1817
  buildWithConcurrency( {
1981
1818
  moduleTypes: LOADER_CONFIG,
1982
1819
  checks: BASE_CHECKS,
@@ -2003,33 +1840,41 @@ async function buildWidget( widgetName ) {
2003
1840
  codeSplitting: false,
2004
1841
  },
2005
1842
  } ),
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 },
2016
- plugins: [
2017
- ...createStyleBundlingPlugins( widgetDir ),
2018
- wordpressExternalsPlugin(
2019
- 'render.min',
2020
- 'esm',
2021
- [],
2022
- false // Skip asset file for non-minified build
2023
- ),
2024
- ],
2025
- output: {
2026
- file: path.join( outputDir, 'render.js' ),
2027
- format: 'esm',
2028
- minify: false,
2029
- codeSplitting: false,
2030
- },
2031
- } ),
2032
- ] );
1843
+ ];
1844
+
1845
+ if ( ! noScriptDebug ) {
1846
+ renderBuilds.push(
1847
+ buildWithConcurrency( {
1848
+ moduleTypes: LOADER_CONFIG,
1849
+ checks: BASE_CHECKS,
1850
+ input: renderEntryPoints,
1851
+ transform: {
1852
+ target: getEsbuildTarget(),
1853
+ define: getDefine( true ),
1854
+ jsx: JSX_OPTIONS,
1855
+ },
1856
+ resolve: { conditionNames: developmentConditions },
1857
+ plugins: [
1858
+ translatorCommentsPlugin(),
1859
+ ...createStyleBundlingPlugins( widgetDir ),
1860
+ wordpressExternalsPlugin(
1861
+ 'render.min',
1862
+ 'esm',
1863
+ [],
1864
+ false // Skip asset file for non-minified build
1865
+ ),
1866
+ ],
1867
+ output: {
1868
+ file: path.join( outputDir, 'render.js' ),
1869
+ format: 'esm',
1870
+ minify: false,
1871
+ codeSplitting: false,
1872
+ },
1873
+ } )
1874
+ );
1875
+ }
1876
+
1877
+ await Promise.all( renderBuilds );
2033
1878
  }
2034
1879
  }
2035
1880
 
@@ -2041,8 +1886,8 @@ async function buildWidget( widgetName ) {
2041
1886
  } );
2042
1887
 
2043
1888
  if ( widgetEntryPoints.length > 0 ) {
2044
- // Build both minified and non-minified versions in parallel
2045
- await Promise.all( [
1889
+ // Build minified and (unless skipped) non-minified versions in parallel
1890
+ const widgetBuilds = [
2046
1891
  buildWithConcurrency( {
2047
1892
  moduleTypes: LOADER_CONFIG,
2048
1893
  checks: BASE_CHECKS,
@@ -2069,33 +1914,41 @@ async function buildWidget( widgetName ) {
2069
1914
  codeSplitting: false,
2070
1915
  },
2071
1916
  } ),
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 },
2082
- plugins: [
2083
- styleRuntimeAliasPlugin(),
2084
- wordpressExternalsPlugin(
2085
- 'widget.min',
2086
- 'esm',
2087
- [],
2088
- false // Skip asset file for non-minified build
2089
- ),
2090
- ],
2091
- output: {
2092
- file: path.join( outputDir, 'widget.js' ),
2093
- format: 'esm',
2094
- minify: false,
2095
- codeSplitting: false,
2096
- },
2097
- } ),
2098
- ] );
1917
+ ];
1918
+
1919
+ if ( ! noScriptDebug ) {
1920
+ widgetBuilds.push(
1921
+ buildWithConcurrency( {
1922
+ moduleTypes: LOADER_CONFIG,
1923
+ checks: BASE_CHECKS,
1924
+ input: widgetEntryPoints,
1925
+ transform: {
1926
+ target: getEsbuildTarget(),
1927
+ define: getDefine( true ),
1928
+ jsx: JSX_OPTIONS,
1929
+ },
1930
+ resolve: { conditionNames: developmentConditions },
1931
+ plugins: [
1932
+ translatorCommentsPlugin(),
1933
+ styleRuntimeAliasPlugin(),
1934
+ wordpressExternalsPlugin(
1935
+ 'widget.min',
1936
+ 'esm',
1937
+ [],
1938
+ false // Skip asset file for non-minified build
1939
+ ),
1940
+ ],
1941
+ output: {
1942
+ file: path.join( outputDir, 'widget.js' ),
1943
+ format: 'esm',
1944
+ minify: false,
1945
+ codeSplitting: false,
1946
+ },
1947
+ } )
1948
+ );
1949
+ }
1950
+
1951
+ await Promise.all( widgetBuilds );
2099
1952
  }
2100
1953
  }
2101
1954
 
@@ -2105,9 +1958,11 @@ async function buildWidget( widgetName ) {
2105
1958
  /**
2106
1959
  * Build all discovered widgets.
2107
1960
  *
1961
+ * @param {Object} root0 Options object.
1962
+ * @param {boolean} root0.noScriptDebug Whether to skip unminified builds.
2108
1963
  * @return {Promise<void>}
2109
1964
  */
2110
- async function buildAllWidgets() {
1965
+ async function buildAllWidgets( { noScriptDebug = false } = {} ) {
2111
1966
  console.log( '\n🧩 Phase 4: Building widgets...\n' );
2112
1967
 
2113
1968
  const widgets = getAllWidgets( ROOT_DIR );
@@ -2123,7 +1978,9 @@ async function buildAllWidgets() {
2123
1978
 
2124
1979
  await Promise.all(
2125
1980
  widgets.map( async ( widgetName ) => {
2126
- const buildTime = await buildWidget( widgetName );
1981
+ const buildTime = await buildWidget( widgetName, {
1982
+ noScriptDebug,
1983
+ } );
2127
1984
  console.log(
2128
1985
  ` ✔ Built widget ${ widgetName } (${ buildTime }ms)`
2129
1986
  );
@@ -2480,8 +2337,10 @@ async function generateWidgetsPhp( widgets, replacements ) {
2480
2337
  * Main build function.
2481
2338
  *
2482
2339
  * @param {string?} baseUrlExpression
2340
+ * @param {Object} root0 Options object.
2341
+ * @param {boolean} root0.noScriptDebug Whether to skip unminified builds.
2483
2342
  */
2484
- async function buildAll( baseUrlExpression ) {
2343
+ async function buildAll( baseUrlExpression, { noScriptDebug = false } = {} ) {
2485
2344
  console.log( '🔨 Building packages...\n' );
2486
2345
 
2487
2346
  const startTime = Date.now();
@@ -2522,7 +2381,9 @@ async function buildAll( baseUrlExpression ) {
2522
2381
  await Promise.all(
2523
2382
  PACKAGES.map( async ( packageName ) => {
2524
2383
  const startBundleTime = Date.now();
2525
- const ret = await bundlePackage( packageName );
2384
+ const ret = await bundlePackage( packageName, {
2385
+ noScriptDebug,
2386
+ } );
2526
2387
  const buildTime = Date.now() - startBundleTime;
2527
2388
  if ( ret ) {
2528
2389
  console.log(
@@ -2577,10 +2438,10 @@ async function buildAll( baseUrlExpression ) {
2577
2438
  .map( ( page ) => page.id )
2578
2439
  )
2579
2440
  : new Set();
2580
- await buildRoutes( experimentalPageIds );
2441
+ await buildRoutes( experimentalPageIds, { noScriptDebug } );
2581
2442
 
2582
2443
  // Build widgets
2583
- await buildAllWidgets();
2444
+ await buildAllWidgets( { noScriptDebug } );
2584
2445
 
2585
2446
  // Collect widget data for PHP generation
2586
2447
  const widgets = collectWidgets();
@@ -2634,6 +2495,9 @@ async function buildAll( baseUrlExpression ) {
2634
2495
  ROOT_DIR,
2635
2496
  baseUrlExpression
2636
2497
  );
2498
+ phpReplacements[ '{{HAS_DEBUG_ASSETS}}' ] = noScriptDebug
2499
+ ? 'false'
2500
+ : 'true';
2637
2501
  await Promise.all( [
2638
2502
  generateMainBuildPhp( phpReplacements ),
2639
2503
  generateModuleRegistrationPhp( modules, phpReplacements ),
@@ -2721,6 +2585,7 @@ async function watchMode() {
2721
2585
  * Rebuild a package and any affected scripts/modules.
2722
2586
  *
2723
2587
  * @param {string} packageName Package to rebuild (short name).
2588
+ * @return {Promise<boolean>} Whether the package itself was rebuilt.
2724
2589
  */
2725
2590
  async function rebuildPackage( packageName ) {
2726
2591
  try {
@@ -2777,8 +2642,10 @@ async function watchMode() {
2777
2642
  );
2778
2643
  }
2779
2644
  }
2645
+ return true;
2780
2646
  } catch ( error ) {
2781
2647
  console.log( `❌ ${ packageName } - Error: ${ error.message }` );
2648
+ return false;
2782
2649
  }
2783
2650
  }
2784
2651
 
@@ -2800,6 +2667,58 @@ async function watchMode() {
2800
2667
  }
2801
2668
  }
2802
2669
 
2670
+ /**
2671
+ * Copy a changed PHP file to the build, without rebuilding its package.
2672
+ *
2673
+ * @param {string} filename Absolute path of the PHP file.
2674
+ */
2675
+ async function recopyPhpFile( filename ) {
2676
+ const packageName = getPackageName( filename );
2677
+ const relativePath = path.relative( PACKAGES_DIR, filename );
2678
+ try {
2679
+ const startTime = Date.now();
2680
+ await copyPackageFile(
2681
+ filename,
2682
+ path.join( PACKAGES_DIR, packageName ),
2683
+ path.join( BUILD_DIR, 'scripts', packageName ),
2684
+ fullToPackageJson.get( shortToFull.get( packageName ) )
2685
+ );
2686
+ const copyTime = Date.now() - startTime;
2687
+ console.log( `✅ ${ relativePath } (copied) (${ copyTime }ms)` );
2688
+ } catch ( error ) {
2689
+ // The file was removed since; its removal rebuilds the package.
2690
+ if ( error.code === 'ENOENT' ) {
2691
+ return;
2692
+ }
2693
+ console.log( `❌ ${ relativePath } - Error: ${ error.message }` );
2694
+ }
2695
+ }
2696
+
2697
+ /*
2698
+ * The PHP files each package copies to the build with `wpCopyFiles`, by
2699
+ * package name. Only the build's copy of such a file depends on it, so a
2700
+ * change to it needs the file copied again, not its package rebuilt.
2701
+ */
2702
+ const copiedPhpFiles = new Map();
2703
+
2704
+ /**
2705
+ * Find the PHP files a package copies to the build with `wpCopyFiles`.
2706
+ *
2707
+ * @param {string} packageName Package name (short name).
2708
+ */
2709
+ async function updateCopiedPhpFiles( packageName ) {
2710
+ const copyFiles = await getCopyFiles(
2711
+ path.join( PACKAGES_DIR, packageName ),
2712
+ fullToPackageJson.get( shortToFull.get( packageName ) )
2713
+ );
2714
+ copiedPhpFiles.set(
2715
+ packageName,
2716
+ new Set( copyFiles.filter( ( file ) => file.endsWith( '.php' ) ) )
2717
+ );
2718
+ }
2719
+
2720
+ await Promise.all( PACKAGES.map( updateCopiedPhpFiles ) );
2721
+
2803
2722
  async function processNextRebuild() {
2804
2723
  if ( needsRebuild.size === 0 ) {
2805
2724
  isRebuilding = false;
@@ -2809,6 +2728,9 @@ async function watchMode() {
2809
2728
  const itemsToRebuild = Array.from( needsRebuild );
2810
2729
  needsRebuild.clear();
2811
2730
 
2731
+ const phpFilesToCopy = [];
2732
+ const rebuiltPackages = new Set();
2733
+
2812
2734
  for ( const item of itemsToRebuild ) {
2813
2735
  // Check if it's a route (prefixed with 'route:')
2814
2736
  if ( item.startsWith( 'route:' ) ) {
@@ -2817,8 +2739,17 @@ async function watchMode() {
2817
2739
  } else if ( item.startsWith( 'widget:' ) ) {
2818
2740
  const widgetDirName = item.slice( 7 ); // Remove 'widget:' prefix
2819
2741
  await rebuildWidget( widgetDirName );
2820
- } else {
2821
- await rebuildPackage( item );
2742
+ } else if ( item.startsWith( 'php:' ) ) {
2743
+ phpFilesToCopy.push( item.slice( 4 ) ); // Remove 'php:' prefix
2744
+ } else if ( await rebuildPackage( item ) ) {
2745
+ rebuiltPackages.add( item );
2746
+ }
2747
+ }
2748
+
2749
+ // Copy the PHP files last, unless a rebuild of their package did.
2750
+ for ( const file of phpFilesToCopy ) {
2751
+ if ( ! rebuiltPackages.has( getPackageName( file ) ) ) {
2752
+ await recopyPhpFile( file );
2822
2753
  }
2823
2754
  }
2824
2755
 
@@ -2860,7 +2791,7 @@ async function watchMode() {
2860
2791
  console.error( '❌ Watcher error:', error );
2861
2792
  } );
2862
2793
 
2863
- const handleFileChange = async ( filename ) => {
2794
+ const handleFileChange = async ( filename, event ) => {
2864
2795
  if ( ! isPackageSourceFile( filename ) ) {
2865
2796
  return;
2866
2797
  }
@@ -2870,19 +2801,47 @@ async function watchMode() {
2870
2801
  return;
2871
2802
  }
2872
2803
 
2804
+ /*
2805
+ * A changed PHP file only needs copying again. An added or removed
2806
+ * one still rebuilds its package, which copies all of its files.
2807
+ */
2808
+ const file = normalizePath( path.resolve( filename ) );
2809
+ const item =
2810
+ event === 'change' && copiedPhpFiles.get( packageName )?.has( file )
2811
+ ? `php:${ file }`
2812
+ : packageName;
2813
+
2814
+ /*
2815
+ * Find the package's copied PHP files again when one may have been
2816
+ * added or removed. Until that finishes, a change to an added file
2817
+ * rebuilds the package, which copies it too.
2818
+ */
2819
+ if ( event !== 'change' && file.endsWith( '.php' ) ) {
2820
+ updateCopiedPhpFiles( packageName ).catch( ( error ) => {
2821
+ console.log(
2822
+ `❌ ${ packageName } - Error finding copied PHP files: ${ error.message }`
2823
+ );
2824
+ } );
2825
+ }
2826
+
2827
+ // Queue the item, so that it is not written while a rebuild is running.
2873
2828
  if ( isRebuilding ) {
2874
- needsRebuild.add( packageName );
2829
+ needsRebuild.add( item );
2875
2830
  return;
2876
2831
  }
2877
2832
 
2878
2833
  isRebuilding = true;
2879
- await rebuildPackage( packageName );
2834
+ needsRebuild.add( item );
2880
2835
  await processNextRebuild();
2881
2836
  };
2882
2837
 
2883
- watcher.on( 'change', handleFileChange );
2884
- watcher.on( 'add', handleFileChange );
2885
- watcher.on( 'unlink', handleFileChange );
2838
+ watcher.on( 'change', ( filename ) =>
2839
+ handleFileChange( filename, 'change' )
2840
+ );
2841
+ watcher.on( 'add', ( filename ) => handleFileChange( filename, 'add' ) );
2842
+ watcher.on( 'unlink', ( filename ) =>
2843
+ handleFileChange( filename, 'unlink' )
2844
+ );
2886
2845
 
2887
2846
  // Watch route files if routes exist
2888
2847
  if ( allRoutes.length > 0 ) {
@@ -3010,6 +2969,10 @@ async function main() {
3010
2969
  short: 'w',
3011
2970
  default: false,
3012
2971
  },
2972
+ 'no-script-debug': {
2973
+ type: 'boolean',
2974
+ default: false,
2975
+ },
3013
2976
  'base-url': {
3014
2977
  type: 'string',
3015
2978
  default:
@@ -3029,7 +2992,16 @@ async function main() {
3029
2992
  setBuildConcurrency( buildConcurrency );
3030
2993
  console.log( `⚙️ Using build concurrency: ${ buildConcurrency }\n` );
3031
2994
 
3032
- await buildAll( baseUrlExpression );
2995
+ let noScriptDebug = values[ 'no-script-debug' ];
2996
+
2997
+ if ( noScriptDebug && values.watch ) {
2998
+ console.warn(
2999
+ '⚠️ --no-script-debug is ignored in watch mode (watch is for development).'
3000
+ );
3001
+ noScriptDebug = false;
3002
+ }
3003
+
3004
+ await buildAll( baseUrlExpression, { noScriptDebug } );
3033
3005
 
3034
3006
  if ( values.watch ) {
3035
3007
  console.log( '\n👀 Watching for changes...\n' );