@wordpress/build 0.23.1-next.v.202609031004.0 → 0.24.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/README.md CHANGED
@@ -6,11 +6,11 @@ Build tool for WordPress plugins.
6
6
 
7
7
  `@wordpress/build` is an opinionated build system designed for WordPress plugins. It provides:
8
8
 
9
- - **Transpilation**: Converts TypeScript/JSX source code to both CommonJS (`build/`) and ESM (`build-module/`) formats using esbuild
10
- - **Style Compilation**: Processes SCSS files and CSS modules, generating LTR and RTL versions
11
- - **Bundling**: Creates browser-ready bundles for WordPress scripts and modules
12
- - **PHP Generation**: Automatically generates PHP registration files for scripts, modules, and styles
13
- - **Watch Mode**: Incremental rebuilds during development
9
+ - **Transpilation**: Converts TypeScript/JSX source code to both CommonJS (`build/`) and ESM (`build-module/`) formats using esbuild
10
+ - **Style Compilation**: Processes SCSS files and CSS modules, generating LTR and RTL versions
11
+ - **Bundling**: Creates browser-ready bundles for WordPress scripts and modules
12
+ - **PHP Generation**: Automatically generates PHP registration files for scripts, modules, and styles
13
+ - **Watch Mode**: Incremental rebuilds during development
14
14
 
15
15
  ## Installation
16
16
 
@@ -54,10 +54,11 @@ or via npm script:
54
54
 
55
55
  ### Testing Generated Styles
56
56
 
57
- Generated CSS module output skips automatic style injection when `NODE_ENV` is
58
- `test`. Node-based DOM implementations such as jsdom do not reliably support
59
- modern CSS features, so tests that need actual styles in the DOM should
60
- run in a browser environment.
57
+ Generated CSS output skips automatic style injection in Node-based environments
58
+ when `NODE_ENV` is `test` and `process` is defined. Browsers have no `process`,
59
+ so they always receive styles. Node-based DOM implementations such as jsdom do
60
+ not reliably support modern CSS features, so tests that need actual styles in
61
+ the DOM should run in a browser environment.
61
62
 
62
63
  ## Browser support
63
64
 
@@ -74,9 +75,9 @@ Configure your `package.json` with the following optional fields:
74
75
 
75
76
  Controls whether the package is exposed as a bundled WordPress script/module and accessible via the configured global variable.
76
77
 
77
- - **`true`**: The package will be bundled and exposed as a WordPress script. It will be available in WordPress as part of the configured global (e.g., `wp.blockEditor`, `wp.data`, or a custom global name if configured differently).
78
+ - **`true`**: The package will be bundled and exposed as a WordPress script. It will be available in WordPress as part of the configured global (e.g., `wp.blockEditor`, `wp.data`, or a custom global name if configured differently).
78
79
 
79
- - **Omitted or `false` (default)**: The package will not be exposed as a WordPress script. Use this for packages designed solely as dependencies for other packages. The package can still be used as a dependency via npm imports by other packages.
80
+ - **Omitted or `false` (default)**: The package will not be exposed as a WordPress script. Use this for packages designed solely as dependencies for other packages. The package can still be used as a dependency via npm imports by other packages.
80
81
 
81
82
  ```json
82
83
  {
@@ -239,8 +240,8 @@ The prefix used for WordPress script handles in `.asset.php` files (e.g., `wp-da
239
240
 
240
241
  With this configuration:
241
242
 
242
- - `@my-plugin/editor` → `window.myPlugin.editor` with handle `mp-editor`
243
- - `@my-plugin/data` → `window.myPlugin.data` with handle `mp-data`
243
+ - `@my-plugin/editor` → `window.myPlugin.editor` with handle `mp-editor`
244
+ - `@my-plugin/data` → `window.myPlugin.data` with handle `mp-data`
244
245
 
245
246
  ### `wpPlugin.externalNamespaces`
246
247
 
@@ -265,9 +266,9 @@ Additional package namespaces to externalize (consume as externals, not expose).
265
266
 
266
267
  This allows your packages to consume third-party dependencies as externals:
267
268
 
268
- - `import { Cart } from '@woo/cart'` → `window.woo.cart` with handle `woocommerce-cart`
269
- - `import { Button } from '@acme/ui'` → `window.acme.ui` with handle `acme-plugin-ui`
270
- - Dependencies are tracked in `.asset.php` files
269
+ - `import { Cart } from '@woo/cart'` → `window.woo.cart` with handle `woocommerce-cart`
270
+ - `import { Button } from '@acme/ui'` → `window.acme.ui` with handle `acme-plugin-ui`
271
+ - Dependencies are tracked in `.asset.php` files
271
272
 
272
273
  If `handlePrefix` is omitted, it defaults to the namespace key (e.g., `"woo"` → `woo-cart`).
273
274
 
@@ -293,20 +294,20 @@ Pages can be defined as simple strings or as objects with initialization modules
293
294
 
294
295
  **Page Configuration:**
295
296
 
296
- - **String format**: `"my-admin-page"` - Simple page with no init modules
297
- - **Object format**: `{ "id": "page-slug", "init": ["@scope/package"], "capability": "edit_theme_options", "experimental": true }` - Page with optional init modules
298
- - **`id`** (required): The page slug used in WordPress admin URLs
299
- - **`init`** (optional): Array of script module IDs to execute during page initialization
300
- - **`capability`** (optional, default `manage_options`): Capability a user needs to view the page. Full-page mode enforces this itself, since it renders outside the menu page callback flow; match it to the capability used when registering the page's menu entry.
301
- - **`experimental`** (optional, default `false`): When `true`, the page is excluded from WordPress Core builds (`IS_WORDPRESS_CORE=true`), along with any route that belongs only to experimental pages.
297
+ - **String format**: `"my-admin-page"` - Simple page with no init modules
298
+ - **Object format**: `{ "id": "page-slug", "init": ["@scope/package"], "capability": "edit_theme_options", "experimental": true }` - Page with optional init modules
299
+ - **`id`** (required): The page slug used in WordPress admin URLs
300
+ - **`init`** (optional): Array of script module IDs to execute during page initialization
301
+ - **`capability`** (optional, default `manage_options`): Capability a user needs to view the page. Full-page mode enforces this itself, since it renders outside the menu page callback flow; match it to the capability used when registering the page's menu entry.
302
+ - **`experimental`** (optional, default `false`): When `true`, the page is excluded from WordPress Core builds (`IS_WORDPRESS_CORE=true`), along with any route that belongs only to experimental pages.
302
303
 
303
304
  **Generated Files:**
304
305
 
305
306
  This generates two page modes:
306
307
 
307
- - `build/pages/my-admin-page/page.php` - Full-page mode (takes over entire admin screen with custom sidebar)
308
- - `build/pages/my-admin-page/page-wp-admin.php` - WP-Admin mode (integrates within standard wp-admin interface)
309
- - `build/pages.php` - Loader for all pages
308
+ - `build/pages/my-admin-page/page.php` - Full-page mode (takes over entire admin screen with custom sidebar)
309
+ - `build/pages/my-admin-page/page-wp-admin.php` - WP-Admin mode (integrates within standard wp-admin interface)
310
+ - `build/pages.php` - Loader for all pages
310
311
 
311
312
  Each mode provides route/menu registration functions and a render callback. Routes are automatically registered for both modes.
312
313
 
@@ -357,8 +358,8 @@ add_menu_page( 'Title', 'Menu', 'capability', 'my-admin-page', 'my_plugin_my_adm
357
358
  **Init Modules:**
358
359
  Init modules are JavaScript packages that execute during page initialization, after menu items and routes are registered and before the app renders. They're ideal for:
359
360
 
360
- - Adding icons to menu items (icons can't be passed from PHP)
361
- - Registering command palette entries
361
+ - Adding icons to menu items (icons can't be passed from PHP)
362
+ - Registering command palette entries
362
363
 
363
364
  **Creating an Init Module:**
364
365
 
@@ -409,9 +410,9 @@ The `init()` function is **mandatory** - all init modules must export this named
409
410
 
410
411
  This configuration:
411
412
 
412
- - Packages like `@wordpress/data` expose `window.wp.data`
413
- - Packages like `@wordpress/block-editor` expose `window.wp.blockEditor`
414
- - All packages can consume `@wordpress/*` as externals
413
+ - Packages like `@wordpress/data` expose `window.wp.data`
414
+ - Packages like `@wordpress/block-editor` expose `window.wp.blockEditor`
415
+ - All packages can consume `@wordpress/*` as externals
415
416
 
416
417
  ### Example: Third-Party Plugin
417
418
 
@@ -427,18 +428,18 @@ This configuration:
427
428
 
428
429
  This configuration:
429
430
 
430
- - Packages like `@acme/editor` expose `window.acme.editor`
431
- - Packages like `@acme/data` expose `window.acme.data`
432
- - All packages can still consume `@wordpress/*` → `window.wp.*`
433
- - All packages can still consume vendors (react, lodash) → `window.React`, `window.lodash`
431
+ - Packages like `@acme/editor` expose `window.acme.editor`
432
+ - Packages like `@acme/data` expose `window.acme.data`
433
+ - All packages can still consume `@wordpress/*` → `window.wp.*`
434
+ - All packages can still consume vendors (react, lodash) → `window.React`, `window.lodash`
434
435
 
435
436
  ### Behavior
436
437
 
437
- - **Packages with `wpScript: true` matching the namespace**: Bundled with global exposure
438
- - **Packages with `wpScript: true` not matching the namespace**: Bundled without global exposure
439
- - **Dependencies**: `@wordpress/*` packages are always externalized to `wp.*` globals
440
- - **Vendors**: React, lodash, jQuery, moment are always externalized to their standard globals
441
- - **Asset files**: `.asset.php` files are always generated for WordPress dependency management
438
+ - **Packages with `wpScript: true` matching the namespace**: Bundled with global exposure
439
+ - **Packages with `wpScript: true` not matching the namespace**: Bundled without global exposure
440
+ - **Dependencies**: `@wordpress/*` packages are always externalized to `wp.*` globals
441
+ - **Vendors**: React, lodash, jQuery, moment are always externalized to their standard globals
442
+ - **Asset files**: `.asset.php` files are always generated for WordPress dependency management
442
443
 
443
444
  ## Output Structure
444
445
 
@@ -492,8 +493,8 @@ For routes that should appear on multiple pages:
492
493
 
493
494
  The `page` field can be either:
494
495
 
495
- - **String**: Route belongs to a single page
496
- - **Array**: Route appears on multiple pages (the build system will register the route for each page)
496
+ - **String**: Route belongs to a single page
497
+ - **Array**: Route appears on multiple pages (the build system will register the route for each page)
497
498
 
498
499
  Each page ID must match one of the pages defined in `wpPlugin.pages` in your root `package.json`. This tells the build system which page(s) this route belongs to. It can also map to existing pages registered by other plugins.
499
500
 
@@ -527,12 +528,12 @@ The canvas is a full-screen area typically used for editor previews. To use a cu
527
528
 
528
529
  Export a `route` object with optional hooks. Each hook receives `{ params, search }` — path parameters and query string values from the URL.
529
530
 
530
- - **`beforeLoad`** — Runs before navigation completes. Use for auth checks, validation, or redirects. Throw `redirect()` or `notFound()` from `@wordpress/route` to abort navigation.
531
- - **`loader`** — Runs while the route is loading. Use to preload data (for example, `resolveSelect` from `@wordpress/data`) so `stage` components can read from the store without a loading state. May return an object whose properties are merged into the route's loader data. For data that must be available before the JavaScript application loads, use [`rest_preload_api_request()`](https://developer.wordpress.org/reference/functions/rest_preload_api_request/) in your page's PHP render callback instead.
532
- - **`canvas`** — Runs in parallel with `loader`. Controls which canvas is rendered depending on return values:
533
- - `CanvasData` (`{ postType, postId, isPreview?, editLink? }`) → default WordPress editor canvas
534
- - `null` → custom `canvas.tsx` component (if provided)
535
- - `undefined` or omitted → no canvas
531
+ - **`beforeLoad`** — Runs before navigation completes. Use for auth checks, validation, or redirects. Throw `redirect()` or `notFound()` from `@wordpress/route` to abort navigation.
532
+ - **`loader`** — Runs while the route is loading. Use to preload data (for example, `resolveSelect` from `@wordpress/data`) so `stage` components can read from the store without a loading state. May return an object whose properties are merged into the route's loader data. For data that must be available before the JavaScript application loads, use [`rest_preload_api_request()`](https://developer.wordpress.org/reference/functions/rest_preload_api_request/) in your page's PHP render callback instead.
533
+ - **`canvas`** — Runs in parallel with `loader`. Controls which canvas is rendered depending on return values:
534
+ - `CanvasData` (`{ postType, postId, isPreview?, editLink? }`) → default WordPress editor canvas
535
+ - `null` → custom `canvas.tsx` component (if provided)
536
+ - `undefined` or omitted → no canvas
536
537
 
537
538
  ```tsx
538
539
  export const route = {
@@ -564,10 +565,10 @@ export const route = {
564
565
 
565
566
  The build system generates:
566
567
 
567
- - `build/routes/{route-name}/content.js` - Bundled stage/inspector/canvas components
568
- - `build/routes/{route-name}/route.js` - Bundled lifecycle hooks (if present)
569
- - `build/routes/registry.php` - Route registry data
570
- - `build/routes.php` - Route registration logic
568
+ - `build/routes/{route-name}/content.js` - Bundled stage/inspector/canvas components
569
+ - `build/routes/{route-name}/route.js` - Bundled lifecycle hooks (if present)
570
+ - `build/routes/registry.php` - Route registry data
571
+ - `build/routes.php` - Route registration logic
571
572
 
572
573
  The boot package in Gutenberg will automatically use these routes and make them available.
573
574
 
@@ -584,7 +585,7 @@ Widgets provide a file-based discovery system for building self-contained UI com
584
585
  widgets/
585
586
  hello-world/
586
587
  widget.json # Static discovery metadata (required)
587
- widget.ts # Runtime schema entry point (optional)
588
+ widget.ts # Runtime values entry point (optional)
588
589
  render.tsx # UI component entry point (optional)
589
590
  render.scss # Optional styles (bundled inline when imported from render.tsx)
590
591
  package.json # Optional npm dependencies manifest
@@ -594,15 +595,15 @@ widgets/
594
595
 
595
596
  Widgets use a dual-entry pattern, similar in spirit to how blocks split metadata between `block.json` and `edit.js`:
596
597
 
597
- | Concern | Lives in | Reason |
598
- | ------------------------------------------------------------------ | ----------------- | ---------------------------------------------------------------------------------------------------- |
599
- | Identity (`name`) | both (must match) | server needs it to register; client uses it to resolve the runtime entry |
600
- | Translatable metadata (`title`, `description`, `help`, `keywords`) | `widget.json` | translated server-side via `textdomain`, so the host receives localized strings without a JS runtime |
601
- | Framing (`category`, `presentation`) | `widget.json` | plain JSON the host reads without a JS runtime |
602
- | Attribute schema (types, options, labels, `relevance`) | `widget.ts` | needs TypeScript coupling with `render` props; labels are translated with `__()` |
603
- | Icon and `example` | `widget.ts` | runtime values co-located with the attribute schema |
598
+ | Concern | Lives in | Reason |
599
+ | ------------------------------------------------------------------ | ----------------- | -------------------------------------------------------------------------------------------------------------------------------- |
600
+ | Identity (`name`) | both (must match) | server needs it to register; client uses it to resolve the runtime entry |
601
+ | Translatable metadata (`title`, `description`, `help`, `keywords`) | `widget.json` | translated server-side via `textdomain`, so the host receives localized strings without a JS runtime |
602
+ | Framing (`category`, `presentation`) | `widget.json` | plain JSON the host reads without a JS runtime |
603
+ | Attribute schema (types, options, labels, `relevance`) | `widget.json` | plain JSON; labels translated server-side via `textdomain`; a `widget.ts` entry with the same `id` adds what JSON cannot express |
604
+ | `example`, attribute props that need code | `widget.ts` | runtime values |
604
605
 
605
- Rule of thumb: anything the host needs before loading a widget's module — identity, translatable copy, framing — goes in `widget.json`, which the build forwards to `build/widgets/registry.php` and exposes through the REST API. Anything that needs TypeScript or runtime values (attribute schema, icon, `example`) goes in `widget.ts`.
606
+ Rule of thumb: anything the host needs before loading a widget's module — identity, translatable copy, framing, attribute schema — goes in `widget.json`, which the build forwards to `build/widgets/registry.php` and exposes through the REST API. Anything that needs code (`example`, an attribute's `Edit` component or custom validator) goes in `widget.ts`.
606
607
 
607
608
  ### `widget.json` — static discovery metadata
608
609
 
@@ -621,23 +622,23 @@ Rule of thumb: anything the host needs before loading a widget's module — iden
621
622
 
622
623
  **Fields:**
623
624
 
624
- - **`name`** (required): Namespaced identifier (e.g., `"my-plugin/hello-world"`)
625
- - **`title`** (optional): Human-readable title. Translated server-side using `textdomain`.
626
- - **`description`** (optional): Short description. Translated server-side using `textdomain`.
627
- - **`help`** (optional): Contextual help note for compact surfaces. An object with `content` (may carry `<em>`/`<strong>`) and optional `links` (`label`, `href`). Translated server-side using `textdomain`.
628
- - **`keywords`** (optional): Search aliases. Translated server-side using `textdomain`.
629
- - **`category`** (optional): Grouping category for filtering
630
- - **`presentation`** (optional): Rendering intent (`framed`, `content-bleed`, `full-bleed`)
631
- - **`textdomain`** (optional): Gettext text domain for translating `title`, `description`, `help`, and `keywords`
625
+ - **`name`** (required): Namespaced identifier (e.g., `"my-plugin/hello-world"`)
626
+ - **`title`** (optional): Human-readable title. Translated server-side using `textdomain`.
627
+ - **`description`** (optional): Short description. Translated server-side using `textdomain`.
628
+ - **`help`** (optional): Contextual help note for compact surfaces. An object with `content` (may carry `<em>`/`<strong>`) and optional `links` (`label`, `href`). Translated server-side using `textdomain`.
629
+ - **`keywords`** (optional): Search aliases. Translated server-side using `textdomain`.
630
+ - **`attributes`** (optional): Attribute schema, one entry per attribute with the JSON-expressible subset of a DataViews `Field` (`id`, `type`, `label`, `elements`, `isValid` without `custom`, ...) plus an optional `relevance` (`high`, `medium`, `low`). `type` may name a registered field type. `label`, `header`, `description`, `placeholder`, and option labels and descriptions are translated server-side using `textdomain`.
631
+ - **`category`** (optional): Grouping category for filtering
632
+ - **`presentation`** (optional): Rendering intent (`framed`, `content-bleed`, `full-bleed`)
633
+ - **`textdomain`** (optional): Gettext text domain for translating `title`, `description`, `help`, `keywords`, and attribute labels
632
634
 
633
- ### `widget.ts` — runtime schema
635
+ ### `widget.ts` — runtime values
634
636
 
635
- Exports a default object with the widget's runtime contract: typed attributes (with translated labels), icon, and example data. Identity and translatable copy (`title`, `description`, `keywords`) live in `widget.json`. The build system injects the `render_module` handle at registration time, so authors don't need to declare it.
637
+ Optional. Exports a default object with what needs code: `example` data, and attribute entries that add an `Edit` component or a custom validator to a `widget.json` attribute with the same `id`. The build system injects the `render_module` handle at registration time, so authors don't need to declare it.
636
638
 
637
639
  ```ts
638
- import { wordpress } from '@wordpress/icons';
639
- import { __ } from '@wordpress/i18n';
640
640
  import type { WidgetAttributeField } from '@wordpress/widget-primitives';
641
+ import { GreetingControl } from './greeting-control';
641
642
 
642
643
  type HelloWorldAttributes = {
643
644
  greeting: string;
@@ -646,20 +647,9 @@ type HelloWorldAttributes = {
646
647
 
647
648
  const widget = {
648
649
  name: 'my-plugin/hello-world',
649
- icon: wordpress,
650
- attributes: [
651
- {
652
- id: 'greeting',
653
- type: 'text',
654
- label: __( 'Greeting', 'my-plugin' ),
655
- relevance: 'high',
656
- },
657
- {
658
- id: 'showDate',
659
- type: 'boolean',
660
- label: __( 'Show current date', 'my-plugin' ),
661
- },
662
- ] satisfies WidgetAttributeField< HelloWorldAttributes >[],
650
+ attributes: [ { id: 'greeting', Edit: GreetingControl } ] satisfies Partial<
651
+ WidgetAttributeField< HelloWorldAttributes >
652
+ >[],
663
653
  example: {
664
654
  attributes: {
665
655
  greeting: 'World',
@@ -671,13 +661,11 @@ const widget = {
671
661
  export default widget;
672
662
  ```
673
663
 
674
- Each attribute entry is a DataViews `Field` plus an optional `relevance` hint (`'high' | 'medium' | 'low'`). The widget declares importance; the host decides where to expose each field. When absent, `relevance` defaults to `'low'`.
675
-
676
- The same `HelloWorldAttributes` type is consumed by `render.tsx`, giving the author a single source of truth for the data contract.
664
+ Entries merge by `id` with the `widget.json` schema: the JSON value wins a shared key, the module adds the rest, and `isValid` merges rule by rule so JSON rules and a module `custom` validator coexist. A widget whose attributes are plain data needs no `widget.ts`.
677
665
 
678
666
  ### `render.tsx` — UI component
679
667
 
680
- The render entry receives `attributes` matching the schema declared in `widget.ts`. It is bundled with CSS support (import `.scss` / `.css` directly).
668
+ The render entry receives `attributes` matching the schema declared in `widget.json`. It is bundled with CSS support (import `.scss` / `.css` directly).
681
669
 
682
670
  ```tsx
683
671
  interface HelloWorldRenderProps {
@@ -705,12 +693,12 @@ All non-JSON entries are optional. The build system checks for files with extens
705
693
 
706
694
  The build system generates:
707
695
 
708
- - `build/widgets/{widget-name}/render.min.js` + `render.js` — Bundled UI component (ESM)
709
- - `build/widgets/{widget-name}/render.min.asset.php` — Asset metadata for render module
710
- - `build/widgets/{widget-name}/widget.min.js` + `widget.js` — Bundled metadata (ESM)
711
- - `build/widgets/{widget-name}/widget.min.asset.php` — Asset metadata for widget module
712
- - `build/widgets/registry.php` — Widget registry data
713
- - `build/widgets.php` — Script module registration logic
696
+ - `build/widgets/{widget-name}/render.min.js` + `render.js` — Bundled UI component (ESM)
697
+ - `build/widgets/{widget-name}/render.min.asset.php` — Asset metadata for render module
698
+ - `build/widgets/{widget-name}/widget.min.js` + `widget.js` — Bundled metadata (ESM)
699
+ - `build/widgets/{widget-name}/widget.min.asset.php` — Asset metadata for widget module
700
+ - `build/widgets/registry.php` — Widget registry data
701
+ - `build/widgets.php` — Script module registration logic
714
702
 
715
703
  ### PHP Registration
716
704
 
package/lib/build.mjs CHANGED
@@ -1,7 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFile, writeFile, copyFile, mkdir, unlink } from 'fs/promises';
3
3
  import path from 'path';
4
- import { createHash } from 'node:crypto';
5
4
  import { createRequire as createNodeRequire } from 'node:module';
6
5
  import { parseArgs } from 'node:util';
7
6
  import esbuild from 'esbuild';
@@ -10,7 +9,6 @@ import chokidar from 'chokidar';
10
9
  import browserslistToEsbuild from 'browserslist-to-esbuild';
11
10
  import { sassPlugin } from 'esbuild-sass-plugin';
12
11
  import postcss from 'postcss';
13
- import postcssModules from 'postcss-modules';
14
12
  import autoprefixer from 'autoprefixer';
15
13
  import rtlcss from 'rtlcss';
16
14
  import cssnano from 'cssnano';
@@ -47,6 +45,10 @@ import {
47
45
  buildWorkers,
48
46
  generateWorkerCode,
49
47
  } from './worker-build.mjs';
48
+ import {
49
+ compileInlineStyle,
50
+ dsTokenFallbacks,
51
+ } from './compile-inline-style.mjs';
50
52
 
51
53
  /**
52
54
  * Resolve the ESBuild target from the project's Browserslist config.
@@ -56,19 +58,13 @@ import {
56
58
  function getEsbuildTarget() {
57
59
  return browserslistToEsbuild( getBrowserslistQueries() );
58
60
  }
59
- // Optional dependency: @wordpress/theme provides plugins that inject fallback
60
- // values for design system tokens. Fails gracefully when the package is not
61
- // installed (it is an optional peerDependency).
62
- let dsTokenFallbacks;
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).
63
64
  let dsTokenFallbacksJs;
64
65
  try {
65
- const { default: postcssPlugin } = await import(
66
- '@wordpress/theme/postcss-plugins/postcss-ds-token-fallbacks'
67
- );
68
- const { default: esbuildPlugin } = await import(
69
- '@wordpress/theme/esbuild-plugins/esbuild-ds-token-fallbacks'
70
- );
71
- dsTokenFallbacks = postcssPlugin;
66
+ const { default: esbuildPlugin } =
67
+ await import( '@wordpress/theme/esbuild-plugins/esbuild-ds-token-fallbacks' );
72
68
  dsTokenFallbacksJs = esbuildPlugin;
73
69
  } catch {
74
70
  // @wordpress/theme is optional; skip token fallbacks if not available.
@@ -209,66 +205,6 @@ function getSassOptions( workingDir ) {
209
205
  };
210
206
  }
211
207
 
212
- function compileInlineStyle( { cssModules = false, minify = true } = {} ) {
213
- return async function styleType( cssText, _dirname, filePath ) {
214
- let moduleExports = null;
215
-
216
- // Transform the code: token fallbacks, CSS modules and minification.
217
- const plugins = [
218
- dsTokenFallbacks,
219
- cssModules &&
220
- postcssModules( {
221
- generateScopedName: '[contenthash]__[local]',
222
- getJSON: ( _, json ) => {
223
- moduleExports = json;
224
- },
225
- } ),
226
- minify &&
227
- cssnano( {
228
- preset: [
229
- 'default',
230
- { discardComments: { removeAll: true } },
231
- ],
232
- } ),
233
- ].filter( Boolean );
234
-
235
- const { css } = await postcss( plugins ).process( cssText, {
236
- from: filePath,
237
- map: false,
238
- } );
239
-
240
- // Hash the transformed CSS so that the dedup key reflects the actual
241
- // injected content, including mangled CSS module class names.
242
- const hash = createHash( 'sha1' )
243
- .update( css )
244
- .digest( 'hex' )
245
- .slice( 0, 10 );
246
-
247
- // Skip automatic style injection in Node-based test environments, where DOM
248
- // implementations do not reliably support modern CSS features like @layer.
249
- let cssModule = cssModules
250
- ? `import { registerStyle } from '@wordpress/style-runtime';
251
- if (typeof process === 'undefined' || process.env.NODE_ENV !== 'test') {
252
- registerStyle("${ hash }", ${ JSON.stringify( css ) });
253
- }
254
- `
255
- : `if (typeof document !== 'undefined' && process.env.NODE_ENV !== 'test' && !document.head.querySelector("style[data-wp-hash='${ hash }']")) {
256
- const style = document.createElement("style");
257
- style.setAttribute("data-wp-hash", "${ hash }");
258
- style.appendChild(document.createTextNode(${ JSON.stringify( css ) }));
259
- document.head.appendChild(style);
260
- }
261
- `;
262
-
263
- // The CSS modules transform produces an `exports` object with class name mappings.
264
- if ( moduleExports ) {
265
- const exportsString = JSON.stringify( moduleExports );
266
- cssModule += `export default ${ exportsString };\n`;
267
- }
268
- return cssModule;
269
- };
270
- }
271
-
272
208
  function inlineStyle( contents ) {
273
209
  // The `contents` is already a JS code created by `compileInlineStyle`.
274
210
  return contents;
@@ -1396,7 +1332,7 @@ async function transpilePackage( packageName ) {
1396
1332
  // Ideally we should remove this exception and move away from emotion.
1397
1333
  const needsEmotionPlugin = packageName === 'components';
1398
1334
  const emotionPlugin = babel( {
1399
- filter: /\.[jt]sx?$/,
1335
+ filter: /\.[cm]?[jt]sx?$/,
1400
1336
  config: {
1401
1337
  plugins: [ styleRuntimeRequire.resolve( '@emotion/babel-plugin' ) ],
1402
1338
  },
@@ -1451,7 +1387,10 @@ async function transpilePackage( packageName ) {
1451
1387
  // Replace extension: make sure that file extension is always `.mjs` or `.cjs`.
1452
1388
  const newExt =
1453
1389
  build.initialOptions.format === 'cjs' ? '.cjs' : '.mjs';
1454
- relativePath = relativePath.replace( /\.[jt]sx?$/, newExt );
1390
+ relativePath = relativePath.replace(
1391
+ /\.[cm]?[jt]sx?$/,
1392
+ newExt
1393
+ );
1455
1394
 
1456
1395
  return {
1457
1396
  path: relativePath,
@@ -1876,7 +1815,7 @@ async function buildRoutes( experimentalPageIds = new Set() ) {
1876
1815
  return metadata.pages.some(
1877
1816
  ( page ) => ! experimentalPageIds.has( page )
1878
1817
  );
1879
- } );
1818
+ } );
1880
1819
 
1881
1820
  if ( routes.length === 0 ) {
1882
1821
  console.log( ' No routes found, skipping.\n' );
@@ -1886,9 +1825,7 @@ async function buildRoutes( experimentalPageIds = new Set() ) {
1886
1825
  await Promise.all(
1887
1826
  routes.map( async ( routeName ) => {
1888
1827
  const buildTime = await buildRoute( routeName );
1889
- console.log(
1890
- ` ✔ Built route ${ routeName } (${ buildTime }ms)`
1891
- );
1828
+ console.log( ` ✔ Built route ${ routeName } (${ buildTime }ms)` );
1892
1829
  } )
1893
1830
  );
1894
1831
  }
@@ -2045,7 +1982,7 @@ async function buildAllWidgets() {
2045
1982
  * Discover all widgets and collect their registry-facing data.
2046
1983
  * Widgets without a valid widget.json are skipped.
2047
1984
  *
2048
- * @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, hasRender: boolean, hasWidget: boolean, presentation: string | null, category: string | null, keywords: string[] | null, textdomain: string | null }>} Array of widget objects.
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.
2049
1986
  */
2050
1987
  function collectWidgets() {
2051
1988
  return getAllWidgets( ROOT_DIR ).flatMap( ( widgetName ) => {
@@ -2069,6 +2006,7 @@ function collectWidgets() {
2069
2006
  help: metadata.help ?? null,
2070
2007
  icon: metadata.icon ?? null,
2071
2008
  actions: metadata.actions ?? null,
2009
+ attributes: metadata.attributes ?? null,
2072
2010
  hasRender: widgetFiles.hasRender,
2073
2011
  hasWidget: widgetFiles.hasWidget,
2074
2012
  presentation: metadata.presentation ?? null,
@@ -2174,10 +2112,10 @@ function toPhpActionsLiteral( actions ) {
2174
2112
  typeof action.download === 'boolean'
2175
2113
  ? `'download' => ${
2176
2114
  action.download ? 'true' : 'false'
2177
- }`
2115
+ }`
2178
2116
  : `'download' => ${ toPhpStringLiteral(
2179
2117
  action.download
2180
- ) }`
2118
+ ) }`
2181
2119
  );
2182
2120
  }
2183
2121
 
@@ -2211,6 +2149,74 @@ function toPhpActionsLiteral( actions ) {
2211
2149
  return `array( ${ entries.join( ', ' ) } )`;
2212
2150
  }
2213
2151
 
2152
+ /**
2153
+ * Format any JSON value as a PHP literal: scalars as-is, lists as
2154
+ * `array( ... )`, objects as `array( 'key' => ... )`. Non-finite numbers
2155
+ * and unsupported values become `null`.
2156
+ *
2157
+ * @param {unknown} value Source value.
2158
+ * @return {string} PHP literal.
2159
+ */
2160
+ function toPhpValueLiteral( value ) {
2161
+ if ( value === null || value === undefined ) {
2162
+ return 'null';
2163
+ }
2164
+ if ( typeof value === 'boolean' ) {
2165
+ return value ? 'true' : 'false';
2166
+ }
2167
+ if ( typeof value === 'number' ) {
2168
+ return Number.isFinite( value ) ? String( value ) : 'null';
2169
+ }
2170
+ if ( typeof value === 'string' ) {
2171
+ const escaped = value.replace( /\\/g, '\\\\' ).replace( /'/g, "\\'" );
2172
+ return `'${ escaped }'`;
2173
+ }
2174
+ if ( Array.isArray( value ) ) {
2175
+ return `array( ${ value.map( toPhpValueLiteral ).join( ', ' ) } )`;
2176
+ }
2177
+ if ( typeof value === 'object' ) {
2178
+ const entries = Object.entries( value ).map(
2179
+ ( [ key, entry ] ) =>
2180
+ `${ toPhpValueLiteral( key ) } => ${ toPhpValueLiteral(
2181
+ entry
2182
+ ) }`
2183
+ );
2184
+ return `array( ${ entries.join( ', ' ) } )`;
2185
+ }
2186
+ return 'null';
2187
+ }
2188
+
2189
+ /**
2190
+ * Format a widget's attribute schema as a PHP array literal. Returns the
2191
+ * PHP literal `null` when there are no valid entries; entries without a
2192
+ * string `id` are dropped. Everything else is copied as declared; the
2193
+ * registration gate constrains the shape.
2194
+ *
2195
+ * @param {import('./widget-utils.mjs').WidgetAttributeMetadata[]|null|undefined} attributes Source value.
2196
+ * @return {string} PHP array literal, or `null`.
2197
+ */
2198
+ function toPhpAttributesLiteral( attributes ) {
2199
+ if ( ! Array.isArray( attributes ) ) {
2200
+ return 'null';
2201
+ }
2202
+
2203
+ const entries = attributes
2204
+ .filter(
2205
+ ( attribute ) =>
2206
+ attribute &&
2207
+ typeof attribute === 'object' &&
2208
+ typeof attribute.id === 'string' &&
2209
+ attribute.id !== ''
2210
+ )
2211
+ .map( toPhpValueLiteral );
2212
+
2213
+ if ( entries.length === 0 ) {
2214
+ return 'null';
2215
+ }
2216
+
2217
+ return `array( ${ entries.join( ', ' ) } )`;
2218
+ }
2219
+
2214
2220
  /**
2215
2221
  * Generate global widget registry file.
2216
2222
  * Creates a single registry with all widgets including file availability.
@@ -2238,6 +2244,7 @@ async function generateWidgetRegistry( widgets, replacements ) {
2238
2244
  const helpStr = toPhpHelpLiteral( widget.help );
2239
2245
  const iconStr = toPhpStringLiteral( widget.icon );
2240
2246
  const actionsStr = toPhpActionsLiteral( widget.actions );
2247
+ const attributesStr = toPhpAttributesLiteral( widget.attributes );
2241
2248
  const keywordsStr = toPhpStringArrayLiteral( widget.keywords );
2242
2249
  const textdomainStr = toPhpStringLiteral( widget.textdomain );
2243
2250
  return `\tarray(
@@ -2248,6 +2255,7 @@ async function generateWidgetRegistry( widgets, replacements ) {
2248
2255
  'help' => ${ helpStr },
2249
2256
  'icon' => ${ iconStr },
2250
2257
  'actions' => ${ actionsStr },
2258
+ 'attributes' => ${ attributesStr },
2251
2259
  'has_render' => ${ hasRenderStr },
2252
2260
  'has_widget' => ${ hasWidgetStr },
2253
2261
  'presentation' => ${ presentationStr },
@@ -2388,7 +2396,7 @@ async function buildAll( baseUrlExpression ) {
2388
2396
  normalizedPages
2389
2397
  .filter( ( page ) => page.experimental )
2390
2398
  .map( ( page ) => page.id )
2391
- )
2399
+ )
2392
2400
  : new Set();
2393
2401
  await buildRoutes( experimentalPageIds );
2394
2402
 
@@ -2475,9 +2483,7 @@ async function buildAll( baseUrlExpression ) {
2475
2483
  if ( pageData.length > 0 ) {
2476
2484
  console.log( ' ✔ Generated build/pages.php' );
2477
2485
  for ( const page of pageData ) {
2478
- console.log(
2479
- ` ✔ Generated build/pages/${ page.slug }/page.php`
2480
- );
2486
+ console.log( ` ✔ Generated build/pages/${ page.slug }/page.php` );
2481
2487
  console.log(
2482
2488
  ` ✔ Generated build/pages/${ page.slug }/page-wp-admin.php`
2483
2489
  );
@@ -2828,10 +2834,10 @@ async function main() {
2828
2834
  'base-url': {
2829
2835
  type: 'string',
2830
2836
  default:
2831
- boolConfigVal( process.env.IS_WORDPRESS_CORE ) ??
2837
+ ( boolConfigVal( process.env.IS_WORDPRESS_CORE ) ??
2832
2838
  boolConfigVal(
2833
2839
  process.env.npm_package_config_IS_WORDPRESS_CORE
2834
- )
2840
+ ) )
2835
2841
  ? "includes_url( 'build/' )"
2836
2842
  : 'plugin_dir_url( __FILE__ )',
2837
2843
  },