Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions projects/packages/wp-build-polyfills/.gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/node_modules
/build
/build-prod-test
/.cache
/tests/fixtures/wp-build-source/**/build
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: patch
Type: fixed

Bundle a local `keyedReducer` helper so the notices polyfill keeps working with newer `@wordpress/notices` on WordPress versions that ship an older `@wordpress/data`. Upstream Gutenberg PR https://github.com/WordPress/gutenberg/pull/77364 consolidated `keyedReducer` into `@wordpress/data` 10.45.0, after which `@wordpress/notices` 5.45.0 and `@wordpress/core-data` 7.45.0 began importing it from `@wordpress/data`. Sites running older WordPress Core (whose bundled `@wordpress/data` predates 10.45.0) would hit `undefined is not a function` at polyfill load time. This is a workaround: a webpack loader rewrites the `keyedReducer` named import in the affected upstream files to a local shim, while every other `@wordpress/data` symbol stays externalized to the runtime `window.wp.data` global. A longer-term fix (e.g. shipping a `wp-data` polyfill IIFE, or waiting for Core upgrades to catch up) is out of scope for this change. The loader rule is currently scoped to `@wordpress/notices` and `@wordpress/core-data`; future polyfill additions that pull in other upstream packages importing `keyedReducer` from `@wordpress/data` should extend the rule and regression test.
4 changes: 4 additions & 0 deletions projects/packages/wp-build-polyfills/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@
],
"test-php": [
"@composer phpunit"
],
"test-js": [
"pnpm run build",
"pnpm run test"
]
},
"config": {
Expand Down
45 changes: 45 additions & 0 deletions projects/packages/wp-build-polyfills/src/internal/keyed-reducer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Local `keyedReducer` higher-order reducer.
*
* `@wordpress/notices` >= 5.45.0 imports `keyedReducer` from `@wordpress/data`,
* which only added this export in `@wordpress/data` 10.45.0 (Gutenberg
* consolidated copies previously maintained inside notices and core-data;
* see WordPress/gutenberg#77364). The polyfill externalizes `@wordpress/data`
* to the runtime `window.wp.data` global so notices state stays in the shared
* registry. On sites that still ship an older `@wordpress/data` (current
* WordPress Core), `window.wp.data.keyedReducer` is `undefined` and the
* polyfill bundle throws at load time.
*
* To keep `@wordpress/data` externalized for every other symbol (so the store
* registers in the shared registry) while staying robust to the missing
* helper, we ship a local copy and alias only the file that needs it.
* Implementation kept byte-identical to upstream.
*
* @see https://github.com/WordPress/gutenberg/pull/77364
*/

/**
* Returns a higher-order reducer that maintains a sub-state keyed by
* `action[ actionProperty ]`. The wrapped reducer runs against the slice of
* state belonging to that key.
*
* @param {string} actionProperty - Action key whose value selects the sub-state.
* @return {Function} Higher-order reducer factory.
*/
export const keyedReducer =
actionProperty =>
reducer =>
( state = {}, action ) => {
const key = action[ actionProperty ];
if ( key === undefined ) {
return state;
}
const nextKeyState = reducer( state[ key ], action );
if ( nextKeyState === state[ key ] ) {
return state;
}
return {
...state,
[ key ]: nextKeyState,
};
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
/**
* Regression test for the `keyedReducer` runtime breakage introduced when
* `@wordpress/notices` >= 5.45.0 began importing `keyedReducer` from
* `@wordpress/data` (added upstream in `@wordpress/data` 10.45.0). Without
* the inlining loader, the polyfill bundle would call
* `window.wp.data.keyedReducer()` at load time and throw on older WordPress
* Cores that ship `@wordpress/data` < 10.45.0.
*
* The test verifies the built `wp-notices` polyfill ships a working
* `keyedReducer` that does NOT depend on a `keyedReducer` export from the
* runtime `wp.data` global. We extract the reducer function from the bundle
* with an isolated `wp.data` stub (and a stub for every other external
* symbol the bundle touches) and execute it on a fixture state shape.
*
* The same assertions run against BOTH the development (non-minified) and
* production (minified) outputs, because minifiers can rewrite the shape of
* `window["wp"]["data"]["keyedReducer"]` references in ways the static
* regex could otherwise miss (e.g. aliasing `wp.data` into a single
* identifier and then doing `.keyedReducer` off of it).
*/

const { existsSync, readFileSync, rmSync } = require( 'fs' );
const assert = require( 'node:assert/strict' );
const { execFileSync } = require( 'node:child_process' );
const { describe, it, before } = require( 'node:test' );
const vm = require( 'node:vm' );
const path = require( 'path' );

const PACKAGE_ROOT = path.resolve( __dirname, '..', '..' );
const DEV_BUILD_PATH = path.join( PACKAGE_ROOT, 'build', 'scripts', 'notices', 'index.js' );

// We render production output into a sibling tree so the dev build at
// `build/` stays usable for other tests / inspection without interleaving.
const PROD_BUILD_ROOT = path.join( PACKAGE_ROOT, 'build-prod-test' );
const PROD_BUILD_PATH = path.join( PROD_BUILD_ROOT, 'scripts', 'notices', 'index.js' );

/**
* Run the package's webpack build with the given NODE_ENV and output base.
* We invoke webpack-cli directly (rather than the package's `build` script)
* so we can redirect the output path without clobbering the dev build.
*
* @param {object} env - Extra env vars for the child process.
* @param {string} outputBase - Absolute path for `output.path`'s base.
*/
function buildWithEnv( env, outputBase ) {
execFileSync(
process.execPath,
[
require.resolve( 'webpack-cli/bin/cli.js' ),
'--config',
path.join( PACKAGE_ROOT, 'webpack.config.js' ),
],
{
cwd: PACKAGE_ROOT,
env: { ...process.env, ...env, WP_BUILD_POLYFILLS_OUTPUT_BASE: outputBase },
stdio: 'pipe',
}
);
}

/**
* Assertion shared by both build modes: the bundle must not statically
* reference `wp.data.keyedReducer` (whatever shape the minifier picks).
*
* @param {string} source - Raw bundle source.
* @param {string} label - Human-readable build label for assertion msgs.
*/
function assertNoWpDataKeyedReducer( source, label ) {
// Strip block and line comments before matching so JSDoc text in
// preserved source (e.g. the loader / shim) doesn't trip the check.
const stripped = source
.replace( /\/\*[\s\S]*?\*\//g, '' )
.replace( /(^|[^:'"`])\/\/[^\n]*/g, '$1' );

// `keyedReducer` should only appear as the local inlined export, not
// dereferenced off the externalized `wp.data` module. Both the dev and
// minified outputs route `@wordpress/data` through
// `window.wp.data` / `window["wp"]["data"]`, so any property access
// off that reference for `keyedReducer` would indicate the helper is
// being read from the runtime instead of the local copy.
const wpDataKeyedReducer =
/(?:window\s*(?:\.\s*wp|\[\s*['"]wp['"]\s*\])\s*(?:\.\s*data|\[\s*['"]data['"]\s*\])\s*(?:\.\s*keyedReducer|\[\s*['"]keyedReducer['"]\s*\]))/;
assert.ok(
! wpDataKeyedReducer.test( stripped ),
`${ label }: built bundle still reaches for \`wp.data.keyedReducer\`. Confirm the keyed-reducer loader is wired up for the affected reducer source paths.`
);

// Belt-and-braces: in a minified bundle the property may be quoted but
// not chained directly off `wp.data` (e.g. `const d = wp.data; …
// d["keyedReducer"]`). Asserting that the literal string `keyedReducer`
// is absent from the bundle entirely catches that escape hatch. (The
// helper function body in `src/internal/keyed-reducer.js` does not
// itself mention `keyedReducer` — it's exported by that name but
// referenced internally by parameter / closure variables only — so
// this assertion is safe for the inlined-shim case.)
assert.ok(
! /['"]keyedReducer['"]/.test( stripped ) && ! /\bkeyedReducer\b/.test( stripped ),
`${ label }: built bundle contains the literal token \`keyedReducer\`, which suggests an unexpected externalized property access slipped past the static check above.`
);
}

/**
* Runtime assertion: load the bundle in a vm with a stub `wp.data` that
* deliberately omits `keyedReducer`, and exercise the registered notices
* reducer end-to-end.
*
* @param {string} source - Raw bundle source.
*/
function assertReducerWorksWithoutWpDataKeyedReducer( source ) {
const recordedStore = {};
const sandbox = {
window: {
wp: {
components: { SnackbarList: () => null, NoticeList: () => null },
data: {
// Intentionally omit `keyedReducer` — the polyfill must not need it.
createReduxStore: ( name, options ) => {
recordedStore.name = name;
recordedStore.reducer = options.reducer;
return { name };
},
register: () => {},
useDispatch: () => ( {} ),
useSelect: () => undefined,
},
},
polyfill: true,
},
ReactJSXRuntime: { jsx: () => null, jsxs: () => null, Fragment: Symbol( 'Fragment' ) },
};
sandbox.window.window = sandbox.window;
sandbox.globalThis = sandbox.window;
sandbox.self = sandbox.window;

vm.createContext( sandbox );
vm.runInContext( source, sandbox );

assert.equal(
recordedStore.name,
'core/notices',
'expected the bundle to register the `core/notices` store'
);
assert.equal( typeof recordedStore.reducer, 'function', 'reducer must be a function' );

// Empty state, create one notice in the `default` context.
// Compare JSON so deepStrictEqual doesn't flag cross-realm object identity.
const created = recordedStore.reducer( undefined, {
type: 'CREATE_NOTICE',
context: 'default',
notice: { id: 'a', content: 'hi' },
} );
assert.equal(
JSON.stringify( created ),
JSON.stringify( { default: [ { id: 'a', content: 'hi' } ] } )
);

// Remove the only notice.
const removed = recordedStore.reducer( created, {
type: 'REMOVE_NOTICE',
context: 'default',
id: 'a',
} );
assert.equal( JSON.stringify( removed ), JSON.stringify( { default: [] } ) );
}

describe( 'wp-notices polyfill bundle (development build)', () => {
it( 'must not be missing the build artifact', () => {
assert.ok(
existsSync( DEV_BUILD_PATH ),
`Run \`pnpm run build\` first; missing ${ DEV_BUILD_PATH }`
);
} );

it( 'must not reference `wp.data.keyedReducer` in the built bundle', () => {
const raw = readFileSync( DEV_BUILD_PATH, 'utf8' );
assertNoWpDataKeyedReducer( raw, 'dev build' );
} );

it( 'must produce a notices reducer that works without `wp.data.keyedReducer`', () => {
const source = readFileSync( DEV_BUILD_PATH, 'utf8' );
assertReducerWorksWithoutWpDataKeyedReducer( source );
} );
} );

describe( 'wp-notices polyfill bundle (production minified build)', () => {
before( () => {
// Tear down any prior run so we always assert against fresh output.
rmSync( PROD_BUILD_ROOT, { recursive: true, force: true } );
buildWithEnv( { NODE_ENV: 'production', BABEL_ENV: 'production' }, PROD_BUILD_ROOT );
} );

it( 'must produce a minified build artifact', () => {
assert.ok(
existsSync( PROD_BUILD_PATH ),
`Production webpack build did not emit ${ PROD_BUILD_PATH }`
);
const stats = readFileSync( PROD_BUILD_PATH, 'utf8' );
// Sanity-check minification actually happened — non-minified bundles
// are tens of KB; minified should be a fraction of that.
assert.ok(
stats.length < 10000,
`Expected minified bundle, got ${ stats.length } bytes — webpack may not have minified.`
);
} );

it( 'must not reference `wp.data.keyedReducer` in the minified bundle', () => {
const raw = readFileSync( PROD_BUILD_PATH, 'utf8' );
assertNoWpDataKeyedReducer( raw, 'production build' );
} );

it( 'must produce a notices reducer that works without `wp.data.keyedReducer`', () => {
const source = readFileSync( PROD_BUILD_PATH, 'utf8' );
assertReducerWorksWithoutWpDataKeyedReducer( source );
} );
} );
45 changes: 44 additions & 1 deletion projects/packages/wp-build-polyfills/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,12 @@ const jetpackWebpackConfig = require( '@automattic/jetpack-webpack-config/webpac
const packageRoot = __dirname;
const localRequire = require;

const outputBase = path.join( packageRoot, 'build' );
// Allow the regression test (or any external driver) to redirect the
// emitted output base without clobbering the normal `build/` tree, e.g.
// for asserting against a freshly-rebuilt production bundle in parallel.
const outputBase = process.env.WP_BUILD_POLYFILLS_OUTPUT_BASE
? path.resolve( process.env.WP_BUILD_POLYFILLS_OUTPUT_BASE )
: path.join( packageRoot, 'build' );

// ── Helpers ──────────────────────────────────────────────────────────────────

Expand Down Expand Up @@ -94,6 +99,43 @@ function resolveEntry( packageName, subEntry = null ) {

// ── Shared config ───────────────────────────────────────────────────────────

// Files inside upstream @wordpress packages that import a helper from
// `@wordpress/data` that is not guaranteed to exist on the runtime
// `window.wp.data` (i.e. older WordPress Core's bundled `@wordpress/data`).
// For these specific files, rewrite the `keyedReducer` named import to come
// from a local copy bundled with the polyfill, so the helper resolves
// against the inlined implementation instead of the external global. Other
// `@wordpress/data` symbols (`createReduxStore`, `register`, `useSelect`,
// `useDispatch`) remain externalized via the DEP plugin's standard path so
// the notices store registers in the shared `window.wp.data` registry.
//
// A custom loader (rather than `Rule.resolve.alias`) is required because the
// DEP plugin's `externals` callback runs before module resolution, so an
// alias on `@wordpress/data` is bypassed for the externalized request.
//
// Currently only `keyedReducer` is affected — added to `@wordpress/data`
// 10.45.0 alongside a `@wordpress/notices` 5.45.0 / `@wordpress/core-data`
// 7.45.0 refactor that consolidated a local copy (see WordPress/gutenberg#77364).
//
// The rule's `test` is intentionally restricted to upstream files known to
// import `keyedReducer` from `@wordpress/data`: `notices` ships it in
// `store/reducer.{mjs,cjs}`, and `core-data` ships it in
// `queried-data/reducer.{mjs,cjs}`. The loader itself is also defensive — it
// is a no-op for files that do not import `keyedReducer` — so the worst-case
// failure mode on a too-broad path match is a small perf hit, not incorrect
// rewrites. If a future polyfill addition pulls in another upstream package
// that imports `keyedReducer` from `@wordpress/data`, extend this `test`
// regex (and the regression test below) accordingly.
const wpDataKeyedReducerRule = {
test: [
// `@wordpress/notices` >= 5.45.0 `store/reducer.{mjs,cjs}`.
// `@wordpress/core-data` >= 7.45.0 `queried-data/reducer.{mjs,cjs}`.
/[\\/]@wordpress[\\/](?:notices[\\/](?:build|build-module)[\\/]store|core-data[\\/](?:build|build-module)[\\/]queried-data)[\\/]reducer\.(?:m?js|cjs)$/,
],
enforce: 'pre',
loader: path.resolve( packageRoot, 'wp-data-keyed-reducer-loader.js' ),
};

const sharedConfig = {
mode: jetpackWebpackConfig.mode,
devtool: jetpackWebpackConfig.devtool,
Expand All @@ -106,6 +148,7 @@ const sharedConfig = {
},
module: {
rules: [
wpDataKeyedReducerRule,
// Transpile @wordpress/* packages from node_modules.
jetpackWebpackConfig.TranspileRule( {
includeNodeModules: [ '@wordpress/' ],
Expand Down
Loading
Loading