Commit fadb3fa2308 for woocommerce
commit fadb3fa2308344651432beaddeaaece22dfdaae9
Author: Mario Santos <34552881+SantosGuillamot@users.noreply.github.com>
Date: Tue Nov 24 09:25:23 2026 +0100
Add product data from the unified `woocommerce` store (#69036)
* Read product data from the woocommerce store's server state
Once a ProductsStore loader runs, the woocommerce store's server state holds
products and productVariations views that read woocommerce/products by ID and
serialize as empty objects, so directives and PHP code read the same records
without a second copy being sent to the page.
* Read product data from the woocommerce store in the browser
The woocommerce store gains read-only products and productVariations getters
that return the woocommerce/products state, and its module now loads that
store itself.
* Document the woocommerce store's product data
* Add changelog entries for the woocommerce store's product data
* Test the woocommerce store's product data against its own contract
The PHP test reads the record a loader loaded by ID, so it holds once the
store keeps the data itself. The serialized-data test goes, and one Jest
test covers the getters: empty, then the woocommerce/products objects.
* Say in ProductDataView that the class is deleted once loaders write to woocommerce
* Say the woocommerce product keys exist once a loader has loaded data
* Declare the ?array return type of ProductDataView::offsetGet()
diff --git a/plugins/woocommerce/changelog/read-product-data-from-woocommerce-store b/plugins/woocommerce/changelog/read-product-data-from-woocommerce-store
new file mode 100644
index 00000000000..2cb51ee21d2
--- /dev/null
+++ b/plugins/woocommerce/changelog/read-product-data-from-woocommerce-store
@@ -0,0 +1,3 @@
+Significance: patch
+Type: dev
+Comment: Expose product data from the private woocommerce Interactivity API store; no change for merchants.
diff --git a/plugins/woocommerce/client/blocks/CLAUDE.md b/plugins/woocommerce/client/blocks/CLAUDE.md
index c5ff58769e7..8a1a6379e4e 100644
--- a/plugins/woocommerce/client/blocks/CLAUDE.md
+++ b/plugins/woocommerce/client/blocks/CLAUDE.md
@@ -143,7 +143,7 @@ For private stores:
- Not intended for third-party extension
- Removing/changing store state is NOT a breaking change
- `assets/js/base/stores/` holds each separate store as one file (`products.ts`, `shopper-lists.ts`, `store-notices.ts`)
-- The `woocommerce` store lives in `assets/js/base/stores/woocommerce/`: `index.ts` registers it, `types.ts` declares its store-wide types, and `cart/` holds the cart code split by concern, with the cart-only types in `cart/types.ts`
+- The `woocommerce` store lives in `assets/js/base/stores/woocommerce/`: `index.ts` registers it, `types.ts` declares its store-wide types, `products.ts` exposes the product data of `woocommerce/products` without copying it, and `cart/` holds the cart code split by concern, with the cart-only types in `cart/types.ts`
- Cart store uses mutation batching for performance
### IntegrationRegistry (Extension API)
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/stores/README.md b/plugins/woocommerce/client/blocks/assets/js/base/stores/README.md
index e0acf871b41..5a8d8d031eb 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/stores/README.md
+++ b/plugins/woocommerce/client/blocks/assets/js/base/stores/README.md
@@ -5,7 +5,7 @@ This folder contains the Interactivity API (iAPI) stores that WooCommerce blocks
Stores in this folder:
- [`woocommerce/products`](#woocommerceproducts-store) — server-populated cache of product and variation data in Store API format.
-- [`woocommerce`](#woocommerce-store) — loaded from the `@woocommerce/stores/woocommerce` script module; cart state and actions (with mutation batching for performance). `addCartItem` resolves with a structured per-call outcome (`AddCartItemOutcome`) instead of `void`, and the store's cross-cutting side effects (sync event, legacy event, screen-reader announcement) fire exactly once per batch cycle, not once per request — see below.
+- [`woocommerce`](#woocommerce-store) — loaded from the `@woocommerce/stores/woocommerce` script module; the product and variation data of `woocommerce/products`, read-only, and cart state and actions (with mutation batching for performance). `addCartItem` resolves with a structured per-call outcome (`AddCartItemOutcome`) instead of `void`, and the store's cross-cutting side effects (sync event, legacy event, screen-reader announcement) fire exactly once per batch cycle, not once per request — see below.
---
@@ -237,7 +237,45 @@ For variable products, `findProduct` returns `null` when no variation matches th
## `woocommerce` store
-The `woocommerce` Interactivity API store (`base/stores/woocommerce/`) is served as the script module `@woocommerce/stores/woocommerce`, and blocks load it from that id. It holds cart state and actions, with mutation batching for performance. This section covers the `addCartItem` outcome contract and the once-per-cycle cross-cutting side effects below — it is not a write-up of the store's full state shape, its other actions, or the rest of the mutation batcher's internals.
+The `woocommerce` Interactivity API store (`base/stores/woocommerce/`) is served as the script module `@woocommerce/stores/woocommerce`, and blocks load it from that id. It holds cart state and actions, with mutation batching for performance, and exposes the product data of `woocommerce/products`. This section covers that product data, the `addCartItem` outcome contract, and the once-per-cycle cross-cutting side effects below — it is not a write-up of the store's full state shape, its other actions, or the rest of the mutation batcher's internals.
+
+### Product data
+
+`state.products` and `state.productVariations` hold the same products and variations as the [`woocommerce/products` store](#woocommerceproducts-store), keyed by ID, in Store API format (`ProductResponseItem`, without `images`). An ID with no entry reads as `undefined` on the client and `null` on the server. The data is loaded the same way as for `woocommerce/products`, through the `ProductsStore` loaders, and it is read-only: nothing writes product data to the `woocommerce` store.
+
+Read it in directives, on the server and the client:
+
+```html
+<div data-wp-interactive="woocommerce">
+ <span data-wp-text="state.products.42.name"></span>
+</div>
+```
+
+From PHP, while directives are processed, index the state by ID:
+
+```php
+$state = wp_interactivity_state( 'woocommerce' );
+$product = $state['products'][ $product_id ] ?? null;
+```
+
+From JS, with the `ProductDataState` type exported by `@woocommerce/stores/woocommerce`:
+
+```ts
+import type { ProductDataState } from '@woocommerce/stores/woocommerce';
+
+const { state } = store< { state: ProductDataState } >(
+ 'woocommerce',
+ {},
+ { lock: universalLock }
+);
+
+const product = state.products[ productId ];
+```
+
+For now the `woocommerce` store reads this data from `woocommerce/products` instead of holding a copy, so each record is sent to the page once. This has two consequences:
+
+- On the server, `products` and `productVariations` aren't arrays, so read them by ID only. `is_array()` is false for them, `foreach` finds no entries, and array functions such as `array_key_exists()` don't accept them (a `TypeError` on PHP 8). They exist only once a loader has loaded data in the request.
+- In the serialized interactivity data, `woocommerce` carries them as empty objects. The client reads the data once the `@woocommerce/stores/woocommerce` module loads, so a block that binds it must load that module.
### The `addCartItem` outcome contract
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/stores/woocommerce/cart/test/cart.ts b/plugins/woocommerce/client/blocks/assets/js/base/stores/woocommerce/cart/test/cart.ts
index a0e0c5f4d35..db8d1bc9a32 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/stores/woocommerce/cart/test/cart.ts
+++ b/plugins/woocommerce/client/blocks/assets/js/base/stores/woocommerce/cart/test/cart.ts
@@ -20,12 +20,13 @@ const mockState = {
nonce: 'test-nonce-123',
} as Store[ 'state' ];
const mockActions = {} as Store[ 'actions' ];
+const mockOtherStates: Record< string, object > = {};
jest.mock(
'@wordpress/interactivity',
() => ( {
getConfig: jest.fn(),
- store: jest.fn( ( _name, definition ) => {
+ store: jest.fn( ( name: string, definition ) => {
// The `woocommerce` store is assembled from several `store()`
// calls, one per file, which the library merges into one store.
// Mirror that: merge each call's `state` descriptors (e.g. the
@@ -34,12 +35,20 @@ jest.mock(
// `actions` into one object that every call returns. Actions
// registered by one file are then reachable from the others, and a
// spy assigned to the object replaces the action for all of them.
+ // Other namespaces (e.g. `woocommerce/products`) keep their own state.
+ const state =
+ name === 'woocommerce'
+ ? mockState
+ : ( mockOtherStates[ name ] ??= {} );
if ( definition?.state ) {
Object.defineProperties(
- mockState,
+ state,
Object.getOwnPropertyDescriptors( definition.state )
);
}
+ if ( name !== 'woocommerce' ) {
+ return { state, actions: mockActions };
+ }
if ( definition?.actions ) {
Object.defineProperties(
mockActions,
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/stores/woocommerce/index.ts b/plugins/woocommerce/client/blocks/assets/js/base/stores/woocommerce/index.ts
index c973be569c2..591e537c4ad 100644
--- a/plugins/woocommerce/client/blocks/assets/js/base/stores/woocommerce/index.ts
+++ b/plugins/woocommerce/client/blocks/assets/js/base/stores/woocommerce/index.ts
@@ -9,8 +9,10 @@
*/
import './cart/notices';
import './cart/actions';
+import './products';
export type { WooCommerceConfig, SelectedAttributes } from './types';
+export type { ProductDataState } from './products';
export type {
OptimisticCartItem,
ClientCartItem,
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/stores/woocommerce/products.ts b/plugins/woocommerce/client/blocks/assets/js/base/stores/woocommerce/products.ts
new file mode 100644
index 00000000000..de54bf256fe
--- /dev/null
+++ b/plugins/woocommerce/client/blocks/assets/js/base/stores/woocommerce/products.ts
@@ -0,0 +1,46 @@
+/**
+ * External dependencies
+ */
+import { store } from '@wordpress/interactivity';
+import type { ProductResponseItem } from '@woocommerce/types';
+import '@woocommerce/stores/woocommerce/products';
+import type { ProductsStore } from '@woocommerce/stores/woocommerce/products';
+
+/**
+ * Product and variation data in the `woocommerce` store, keyed by ID, in
+ * Store API format. Read-only: product data is loaded from PHP.
+ */
+export type ProductDataState = {
+ readonly products: Readonly< Record< number, ProductResponseItem > >;
+ readonly productVariations: Readonly<
+ Record< number, ProductResponseItem >
+ >;
+};
+
+// Stores are locked to prevent 3PD usage until the API is stable.
+const universalLock =
+ 'I acknowledge that using a private store means my plugin will inevitably break on the next store release.';
+
+const { state: productsState } = store< ProductsStore >(
+ 'woocommerce/products',
+ {},
+ { lock: universalLock }
+);
+
+// Temporary: until every block reads product data from `woocommerce`, these
+// getters return the `woocommerce/products` data instead of a copy. The store
+// then holds the data itself, and code that reads it doesn't change.
+store< { state: ProductDataState } >(
+ 'woocommerce',
+ {
+ state: {
+ get products() {
+ return productsState.products;
+ },
+ get productVariations() {
+ return productsState.productVariations;
+ },
+ },
+ },
+ { lock: universalLock }
+);
diff --git a/plugins/woocommerce/client/blocks/assets/js/base/stores/woocommerce/test/products.ts b/plugins/woocommerce/client/blocks/assets/js/base/stores/woocommerce/test/products.ts
new file mode 100644
index 00000000000..f32ffcb9c44
--- /dev/null
+++ b/plugins/woocommerce/client/blocks/assets/js/base/stores/woocommerce/test/products.ts
@@ -0,0 +1,57 @@
+/**
+ * External dependencies
+ */
+import type { ProductResponseItem } from '@woocommerce/types';
+import type { ProductsStore } from '@woocommerce/stores/woocommerce/products';
+
+/**
+ * Internal dependencies
+ */
+import type { ProductDataState } from '../products';
+
+const mockStates: Record< string, Record< string, unknown > > = {};
+
+jest.mock(
+ '@wordpress/interactivity',
+ () => ( {
+ getContext: jest.fn(),
+ // Each namespace gets one state object, and every `store()` call for it
+ // merges its `state` descriptors (getters included) onto that object, as
+ // the library does when several modules contribute to the same store.
+ store: jest.fn( ( namespace: string, definition ) => {
+ mockStates[ namespace ] ??= {};
+ if ( definition?.state ) {
+ Object.defineProperties(
+ mockStates[ namespace ],
+ Object.getOwnPropertyDescriptors( definition.state )
+ );
+ }
+ return { state: mockStates[ namespace ] };
+ } ),
+ } ),
+ { virtual: true }
+);
+
+const product = { id: 42, name: 'Hoodie' } as ProductResponseItem;
+const variation = { id: 99, name: 'Hoodie - Blue' } as ProductResponseItem;
+
+describe( 'woocommerce store – product data', () => {
+ it( 'returns the woocommerce/products objects, empty when it holds no product data', () => {
+ require( '../products' );
+ const productsState = mockStates[
+ 'woocommerce/products'
+ ] as ProductsStore[ 'state' ];
+ const state = mockStates.woocommerce as ProductDataState;
+
+ expect( state.products ).toEqual( {} );
+ expect( state.productVariations ).toEqual( {} );
+
+ productsState.products = { 42: product };
+ productsState.productVariations = { 99: variation };
+
+ expect( state.products ).toBe( productsState.products );
+ expect( state.productVariations ).toBe(
+ productsState.productVariations
+ );
+ } );
+} );
diff --git a/plugins/woocommerce/client/blocks/changelog/read-product-data-from-woocommerce-store b/plugins/woocommerce/client/blocks/changelog/read-product-data-from-woocommerce-store
new file mode 100644
index 00000000000..2cb51ee21d2
--- /dev/null
+++ b/plugins/woocommerce/client/blocks/changelog/read-product-data-from-woocommerce-store
@@ -0,0 +1,3 @@
+Significance: patch
+Type: dev
+Comment: Expose product data from the private woocommerce Interactivity API store; no change for merchants.
diff --git a/plugins/woocommerce/src/Blocks/SharedStores/ProductDataView.php b/plugins/woocommerce/src/Blocks/SharedStores/ProductDataView.php
new file mode 100644
index 00000000000..af04fe0299d
--- /dev/null
+++ b/plugins/woocommerce/src/Blocks/SharedStores/ProductDataView.php
@@ -0,0 +1,92 @@
+<?php
+declare(strict_types=1);
+
+namespace Automattic\WooCommerce\Blocks\SharedStores;
+
+/**
+ * Read-only, by-ID view of one member (`products` or `productVariations`) of the
+ * `woocommerce/products` server state, placed in the `woocommerce` server state.
+ *
+ * Each read returns what `woocommerce/products` holds under that ID at that moment,
+ * and the view serializes as an empty object, so the page carries each record once.
+ *
+ * Temporary: once every block reads product data from the `woocommerce` store, the
+ * loaders write the data there directly and this class is deleted. Code that reads
+ * it by ID doesn't change.
+ *
+ * @internal
+ *
+ * @implements \ArrayAccess<int|string, array|null>
+ */
+final class ProductDataView implements \ArrayAccess, \JsonSerializable {
+
+ /**
+ * The `woocommerce/products` state member this view reads.
+ *
+ * @var string
+ */
+ private string $member;
+
+ /**
+ * Constructor.
+ *
+ * @param string $member The `woocommerce/products` state member to read: `products` or `productVariations`.
+ */
+ public function __construct( string $member ) {
+ $this->member = $member;
+ }
+
+ /**
+ * Whether `woocommerce/products` holds a record under this ID.
+ *
+ * @param mixed $offset The product or variation ID.
+ * @return bool
+ */
+ public function offsetExists( $offset ): bool {
+ return null !== $this->offsetGet( $offset );
+ }
+
+ /**
+ * The record `woocommerce/products` holds under this ID.
+ *
+ * @param mixed $offset The product or variation ID.
+ * @return array|null The record in Store API shape, or null when there is none.
+ */
+ public function offsetGet( $offset ): ?array {
+ $state = wp_interactivity_state( 'woocommerce/products' );
+
+ return $state[ $this->member ][ $offset ] ?? null;
+ }
+
+ /**
+ * Writing through the view is not supported: product data is put in `woocommerce/products`.
+ *
+ * @param mixed $offset The product or variation ID.
+ * @param mixed $value The record.
+ * @return void
+ * @throws \LogicException Always.
+ */
+ public function offsetSet( $offset, $value ): void {
+ throw new \LogicException( 'Product data is read-only in the woocommerce store. Load it into woocommerce/products instead.' );
+ }
+
+ /**
+ * Removing through the view is not supported: product data is put in `woocommerce/products`.
+ *
+ * @param mixed $offset The product or variation ID.
+ * @return void
+ * @throws \LogicException Always.
+ */
+ public function offsetUnset( $offset ): void {
+ throw new \LogicException( 'Product data is read-only in the woocommerce store. Load it into woocommerce/products instead.' );
+ }
+
+ /**
+ * Serialize as an empty object, so the records are sent to the page only under `woocommerce/products`.
+ *
+ * @return object
+ */
+ public function jsonSerialize(): object {
+ return new \stdClass();
+ }
+}
diff --git a/plugins/woocommerce/src/Blocks/SharedStores/ProductsStore.php b/plugins/woocommerce/src/Blocks/SharedStores/ProductsStore.php
index c58706780f2..d1e3500120e 100644
--- a/plugins/woocommerce/src/Blocks/SharedStores/ProductsStore.php
+++ b/plugins/woocommerce/src/Blocks/SharedStores/ProductsStore.php
@@ -100,6 +100,9 @@ class ProductsStore {
* wp_interactivity_state() at call time, they only need to be
* registered once regardless of how many products are added.
*
+ * It also makes the raw data readable from the `woocommerce` store as
+ * `state.products` and `state.productVariations`, without a copy.
+ *
* @return void
*/
private static function register_getters(): void {
@@ -109,6 +112,16 @@ class ProductsStore {
self::$getters_registered = true;
+ // Temporary: until every block reads product data from `woocommerce`,
+ // that store reads it from `woocommerce/products` through these views.
+ wp_interactivity_state(
+ 'woocommerce',
+ array(
+ 'products' => new ProductDataView( 'products' ),
+ 'productVariations' => new ProductDataView( 'productVariations' ),
+ )
+ );
+
wp_interactivity_state(
self::$store_namespace,
array(
diff --git a/plugins/woocommerce/tests/php/src/Blocks/SharedStores/ProductsStore.php b/plugins/woocommerce/tests/php/src/Blocks/SharedStores/ProductsStore.php
index 6bb3d0ecf36..b25ef1aaa57 100644
--- a/plugins/woocommerce/tests/php/src/Blocks/SharedStores/ProductsStore.php
+++ b/plugins/woocommerce/tests/php/src/Blocks/SharedStores/ProductsStore.php
@@ -432,6 +432,49 @@ class ProductsStore extends \WC_Unit_Test_Case {
$product->delete( true );
}
+ /**
+ * @testdox The woocommerce store's products and productVariations return the record a loader loaded under each ID.
+ */
+ public function test_woocommerce_store_reads_loaded_product_data_by_id(): void {
+ $product = WC_Helper_Product::create_variation_product();
+ $variation_id = $product->get_children()[0];
+
+ $loaded_product = TestedProductsStore::load_product( $this->consent, $product->get_id() );
+ $loaded_variations = TestedProductsStore::load_variations( $this->consent, $product->get_id() );
+
+ $state = wp_interactivity_state( 'woocommerce' );
+
+ $this->assertTrue( isset( $state['products'][ $product->get_id() ] ) );
+ $this->assertSame( $loaded_product['name'], $state['products'][ $product->get_id() ]['name'] ?? null );
+ $this->assertTrue( isset( $state['productVariations'][ $variation_id ] ) );
+ $this->assertSame( $loaded_variations[ $variation_id ]['sku'], $state['productVariations'][ $variation_id ]['sku'] ?? null );
+ $this->assertNull( $state['products'][999999] ?? null, 'An ID no loader loaded should read as null.' );
+ $this->assertFalse( isset( $state['productVariations'][999999] ) );
+ }
+
+ /**
+ * @testdox Directives bound to the woocommerce store's product data render the loaded values on the server.
+ */
+ public function test_woocommerce_store_product_data_renders_in_directives(): void {
+ $product = WC_Helper_Product::create_variation_product();
+ $variation_id = $product->get_children()[0];
+
+ TestedProductsStore::load_product( $this->consent, $product->get_id() );
+ TestedProductsStore::load_variations( $this->consent, $product->get_id() );
+
+ $html = wp_interactivity_process_directives(
+ sprintf(
+ '<div data-wp-interactive="woocommerce"><span id="product" data-wp-text="state.products.%d.name"></span><span id="variation" data-wp-text="state.productVariations.%d.sku"></span><span id="absent" data-wp-text="state.products.999999.name"></span></div>',
+ $product->get_id(),
+ $variation_id
+ )
+ );
+
+ $this->assertStringContainsString( '<span id="product" data-wp-text="state.products.' . $product->get_id() . '.name">' . $product->get_name() . '</span>', $html );
+ $this->assertStringContainsString( '>' . wc_get_product( $variation_id )->get_sku() . '</span>', $html );
+ $this->assertStringContainsString( '<span id="absent" data-wp-text="state.products.999999.name"></span>', $html );
+ }
+
/**
* Create an anonymous Hydration stand-in that counts how many times
* get_rest_api_response_data was called and returns a canned response.