<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[58579] trunk: Script Modules: Add new API to embed server data in HTML.</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { white-space: pre-line; overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta" style="font-size: 105%">
<dt style="float: left; width: 6em; font-weight: bold">Revision</dt> <dd><a style="font-weight: bold" href="https://core.trac.wordpress.org/changeset/58579">58579</a><script type="application/ld+json">{"@context":"http://schema.org","@type":"EmailMessage","description":"Review this Commit","action":{"@type":"ViewAction","url":"https://core.trac.wordpress.org/changeset/58579","name":"Review Commit"}}</script></dd>
<dt style="float: left; width: 6em; font-weight: bold">Author</dt> <dd>Bernhard Reiter</dd>
<dt style="float: left; width: 6em; font-weight: bold">Date</dt> <dd>2024-06-26 13:19:47 +0000 (Wed, 26 Jun 2024)</dd>
</dl>

<pre style='padding-left: 1em; margin: 2em 0; border-left: 2px solid #ccc; line-height: 1.25; font-size: 105%; font-family: sans-serif'>Script Modules: Add new API to embed server data in HTML.

Add a new filter `script_module_data_{$module_id}` to associate data
with a Script Module. For example:

{{{#!php
add_filter(
        'script_module_data_MyScriptModuleID',
        function ( array $data ): array {
                $data['script-needs-this-data'] = 'ok';
                return $data;
        }
);
}}}

If the Script Module is included in the page, enqueued or as a
dependency, the associated data will be JSON-encoded and embedded in the
HTML in a `<script type="application/json">` tag with an ID of the form
`wp-script-module-data-{$module_id}` allowing the Script Module to
access the data on the client.

See the original proposal: https://make.wordpress.org/core/2024/05/06/proposal-server-to-client-data-sharing-for-script-modules/

Developed in https://github.com/WordPress/wordpress-develop/pull/6682.

Props jonsurrell, cbravobernal, westonruter, gziolo, bernhard-reiter, youknowriad, sergiomdgomes, czapla.
Fixes <a href="https://core.trac.wordpress.org/ticket/61510">#61510</a>. See <a href="https://core.trac.wordpress.org/ticket/60647">#60647</a>.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#trunksrcwpincludesclasswpscriptmodulesphp">trunk/src/wp-includes/class-wp-script-modules.php</a></li>
<li><a href="#trunktestsphpunittestsscriptmoduleswpScriptModulesphp">trunk/tests/phpunit/tests/script-modules/wpScriptModules.php</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="trunksrcwpincludesclasswpscriptmodulesphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/src/wp-includes/class-wp-script-modules.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/src/wp-includes/class-wp-script-modules.php 2024-06-26 08:52:12 UTC (rev 58578)
+++ trunk/src/wp-includes/class-wp-script-modules.php   2024-06-26 13:19:47 UTC (rev 58579)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -182,6 +182,9 @@
</span><span class="cx" style="display: block; padding: 0 10px">                add_action( 'admin_print_footer_scripts', array( $this, 'print_import_map' ) );
</span><span class="cx" style="display: block; padding: 0 10px">                add_action( 'admin_print_footer_scripts', array( $this, 'print_enqueued_script_modules' ) );
</span><span class="cx" style="display: block; padding: 0 10px">                add_action( 'admin_print_footer_scripts', array( $this, 'print_script_module_preloads' ) );
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+
+               add_action( 'wp_footer', array( $this, 'print_script_module_data' ) );
+               add_action( 'admin_print_footer_scripts', array( $this, 'print_script_module_data' ) );
</ins><span class="cx" style="display: block; padding: 0 10px">         }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -363,4 +366,119 @@
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                return $src;
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+
+       /**
+        * Print data associated with Script Modules.
+        *
+        * The data will be embedded in the page HTML and can be read by Script Modules on page load.
+        *
+        * @since 6.7.0
+        *
+        * Data can be associated with a Script Module via the
+        * {@see "script_module_data_{$module_id}"} filter.
+        *
+        * The data for a Script Module will be serialized as JSON in a script tag with an ID of the
+        * form `wp-script-module-data-{$module_id}`.
+        */
+       public function print_script_module_data(): void {
+               $modules = array();
+               foreach ( array_keys( $this->get_marked_for_enqueue() ) as $id ) {
+                       $modules[ $id ] = true;
+               }
+               foreach ( array_keys( $this->get_import_map()['imports'] ) as $id ) {
+                       $modules[ $id ] = true;
+               }
+
+               foreach ( array_keys( $modules ) as $module_id ) {
+                       /**
+                        * Filters data associated with a given Script Module.
+                        *
+                        * Script Modules may require data that is required for initialization or is essential
+                        * to have immediately available on page load. These are suitable use cases for
+                        * this data.
+                        *
+                        * The dynamic portion of the hook name, `$module_id`, refers to the Script Module ID
+                        * that the data is associated with.
+                        *
+                        * This is best suited to pass essential data that must be available to the module for
+                        * initialization or immediately on page load. It does not replace the REST API or
+                        * fetching data from the client.
+                        *
+                        * @example
+                        *   add_filter(
+                        *     'script_module_data_MyScriptModuleID',
+                        *     function ( array $data ): array {
+                        *       $data['script-needs-this-data'] = 'ok';
+                        *       return $data;
+                        *     }
+                        *   );
+                        *
+                        * If the filter returns no data (an empty array), nothing will be embedded in the page.
+                        *
+                        * The data for a given Script Module, if provided, will be JSON serialized in a script
+                        * tag with an ID of the form `wp-script-module-data-{$module_id}`.
+                        *
+                        * The data can be read on the client with a pattern like this:
+                        *
+                        * @example
+                        *   const dataContainer = document.getElementById( 'wp-script-module-data-MyScriptModuleID' );
+                        *   let data = {};
+                        *   if ( dataContainer ) {
+                        *     try {
+                        *       data = JSON.parse( dataContainer.textContent );
+                        *     } catch {}
+                        *   }
+                        *   initMyScriptModuleWithData( data );
+                        *
+                        * @since 6.7.0
+                        *
+                        * @param array $data The data associated with the Script Module.
+                        */
+                       $data = apply_filters( "script_module_data_{$module_id}", array() );
+
+                       if ( is_array( $data ) && array() !== $data ) {
+                               /*
+                                * This data will be printed as JSON inside a script tag like this:
+                                *   <script type="application/json"></script>
+                                *
+                                * A script tag must be closed by a sequence beginning with `</`. It's impossible to
+                                * close a script tag without using `<`. We ensure that `<` is escaped and `/` can
+                                * remain unescaped, so `</script>` will be printed as `\u003C/script\u00E3`.
+                                *
+                                *   - JSON_HEX_TAG: All < and > are converted to \u003C and \u003E.
+                                *   - JSON_UNESCAPED_SLASHES: Don't escape /.
+                                *
+                                * If the page will use UTF-8 encoding, it's safe to print unescaped unicode:
+                                *
+                                *   - JSON_UNESCAPED_UNICODE: Encode multibyte Unicode characters literally (instead of as `\uXXXX`).
+                                *   - JSON_UNESCAPED_LINE_TERMINATORS: The line terminators are kept unescaped when
+                                *     JSON_UNESCAPED_UNICODE is supplied. It uses the same behaviour as it was
+                                *     before PHP 7.1 without this constant. Available as of PHP 7.1.0.
+                                *
+                                * The JSON specification requires encoding in UTF-8, so if the generated HTML page
+                                * is not encoded in UTF-8 then it's not safe to include those literals. They must
+                                * be escaped to avoid encoding issues.
+                                *
+                                * @see https://www.rfc-editor.org/rfc/rfc8259.html for details on encoding requirements.
+                                * @see https://www.php.net/manual/en/json.constants.php for details on these constants.
+                                * @see https://html.spec.whatwg.org/#script-data-state for details on script tag parsing.
+                                */
+                               $json_encode_flags = JSON_HEX_TAG | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_LINE_TERMINATORS;
+                               if ( ! is_utf8_charset() ) {
+                                       $json_encode_flags = JSON_HEX_TAG | JSON_UNESCAPED_SLASHES;
+                               }
+
+                               wp_print_inline_script_tag(
+                                       wp_json_encode(
+                                               $data,
+                                               $json_encode_flags
+                                       ),
+                                       array(
+                                               'type' => 'application/json',
+                                               'id'   => "wp-script-module-data-{$module_id}",
+                                       )
+                               );
+                       }
+               }
+       }
</ins><span class="cx" style="display: block; padding: 0 10px"> }
</span></span></pre></div>
<a id="trunktestsphpunittestsscriptmoduleswpScriptModulesphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/tests/phpunit/tests/script-modules/wpScriptModules.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/tests/phpunit/tests/script-modules/wpScriptModules.php      2024-06-26 08:52:12 UTC (rev 58578)
+++ trunk/tests/phpunit/tests/script-modules/wpScriptModules.php        2024-06-26 13:19:47 UTC (rev 58579)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -732,4 +732,211 @@
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                $this->assertSame( 'wp-load-polyfill-importmap', $id );
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+
+       /**
+        * @ticket 61510
+        */
+       public function test_print_script_module_data_prints_enqueued_module_data() {
+               $this->script_modules->enqueue( '@test/module', '/example.js' );
+               add_action(
+                       'script_module_data_@test/module',
+                       function ( $data ) {
+                               $data['foo'] = 'bar';
+                               return $data;
+                       }
+               );
+
+               $actual = get_echo( array( $this->script_modules, 'print_script_module_data' ) );
+
+               $expected = <<<HTML
+<script type="application/json" id="wp-script-module-data-@test/module">
+{"foo":"bar"}
+</script>
+
+HTML;
+               $this->assertSame( $expected, $actual );
+       }
+
+       /**
+        * @ticket 61510
+        */
+       public function test_print_script_module_data_prints_dependency_module_data() {
+               $this->script_modules->register( '@test/dependency', '/dependency.js' );
+               $this->script_modules->enqueue( '@test/module', '/example.js', array( '@test/dependency' ) );
+               add_action(
+                       'script_module_data_@test/dependency',
+                       function ( $data ) {
+                               $data['foo'] = 'bar';
+                               return $data;
+                       }
+               );
+
+               $actual = get_echo( array( $this->script_modules, 'print_script_module_data' ) );
+
+               $expected = <<<HTML
+<script type="application/json" id="wp-script-module-data-@test/dependency">
+{"foo":"bar"}
+</script>
+
+HTML;
+               $this->assertSame( $expected, $actual );
+       }
+
+       /**
+        * @ticket 61510
+        */
+       public function test_print_script_module_data_does_not_print_nondependency_module_data() {
+               $this->script_modules->register( '@test/other', '/dependency.js' );
+               $this->script_modules->enqueue( '@test/module', '/example.js' );
+               add_action(
+                       'script_module_data_@test/other',
+                       function ( $data ) {
+                               $data['foo'] = 'bar';
+                               return $data;
+                       }
+               );
+
+               $actual = get_echo( array( $this->script_modules, 'print_script_module_data' ) );
+
+               $this->assertSame( '', $actual );
+       }
+
+       /**
+        * @ticket 61510
+        */
+       public function test_print_script_module_data_does_not_print_empty_data() {
+               $this->script_modules->enqueue( '@test/module', '/example.js' );
+               add_action(
+                       'script_module_data_@test/module',
+                       function ( $data ) {
+                               return $data;
+                       }
+               );
+
+               $actual = get_echo( array( $this->script_modules, 'print_script_module_data' ) );
+
+               $this->assertSame( '', $actual );
+       }
+
+       /**
+        * @ticket 61510
+        *
+        * @dataProvider data_special_chars_script_encoding
+        * @param string $input    Raw input string.
+        * @param string $expected Expected output string.
+        * @param string $charset  Blog charset option.
+        */
+       public function test_print_script_module_data_encoding( $input, $expected, $charset ) {
+               add_filter(
+                       'pre_option_blog_charset',
+                       function () use ( $charset ) {
+                               return $charset;
+                       }
+               );
+
+               $this->script_modules->enqueue( '@test/module', '/example.js' );
+               add_action(
+                       'script_module_data_@test/module',
+                       function ( $data ) use ( $input ) {
+                               $data[''] = $input;
+                               return $data;
+                       }
+               );
+
+               $actual = get_echo( array( $this->script_modules, 'print_script_module_data' ) );
+
+               $expected = <<<HTML
+<script type="application/json" id="wp-script-module-data-@test/module">
+{"":"{$expected}"}
+</script>
+
+HTML;
+
+               $this->assertSame( $expected, $actual );
+       }
+
+       /**
+        * Data provider.
+        *
+        * @return array
+        */
+       public static function data_special_chars_script_encoding(): array {
+               return array(
+                       // UTF-8
+                       'Solidus'                                => array( '/', '/', 'UTF-8' ),
+                       'Double quote'                           => array( '"', '\\"', 'UTF-8' ),
+                       'Single quote'                           => array( '\'', '\'', 'UTF-8' ),
+                       'Less than'                              => array( '<', '\u003C', 'UTF-8' ),
+                       'Greater than'                           => array( '>', '\u003E', 'UTF-8' ),
+                       'Ampersand'                              => array( '&', '&', 'UTF-8' ),
+                       'Newline'                                => array( "\n", "\\n", 'UTF-8' ),
+                       'Tab'                                    => array( "\t", "\\t", 'UTF-8' ),
+                       'Form feed'                              => array( "\f", "\\f", 'UTF-8' ),
+                       'Carriage return'                        => array( "\r", "\\r", 'UTF-8' ),
+                       'Line separator'                         => array( "\u{2028}", "\u{2028}", 'UTF-8' ),
+                       'Paragraph separator'                    => array( "\u{2029}", "\u{2029}", 'UTF-8' ),
+
+                       /*
+                        * The following is the Flag of England emoji
+                        * PHP: "\u{1F3F4}\u{E0067}\u{E0062}\u{E0065}\u{E006E}\u{E0067}\u{E007F}"
+                        */
+                       'Flag of england'                        => array( '🏴󠁧󠁢󠁥󠁮󠁧󠁿', '🏴󠁧󠁢󠁥󠁮󠁧󠁿', 'UTF-8' ),
+                       'Malicious script closer'                => array( '</script>', '\u003C/script\u003E', 'UTF-8' ),
+                       'Entity-encoded malicious script closer' => array( '&lt;/script&gt;', '&lt;/script&gt;', 'UTF-8' ),
+
+                       // Non UTF-8
+                       'Solidus'                                => array( '/', '/', 'iso-8859-1' ),
+                       'Less than'                              => array( '<', '\u003C', 'iso-8859-1' ),
+                       'Greater than'                           => array( '>', '\u003E', 'iso-8859-1' ),
+                       'Ampersand'                              => array( '&', '&', 'iso-8859-1' ),
+                       'Newline'                                => array( "\n", "\\n", 'iso-8859-1' ),
+                       'Tab'                                    => array( "\t", "\\t", 'iso-8859-1' ),
+                       'Form feed'                              => array( "\f", "\\f", 'iso-8859-1' ),
+                       'Carriage return'                        => array( "\r", "\\r", 'iso-8859-1' ),
+                       'Line separator'                         => array( "\u{2028}", "\u2028", 'iso-8859-1' ),
+                       'Paragraph separator'                    => array( "\u{2029}", "\u2029", 'iso-8859-1' ),
+                       /*
+                        * The following is the Flag of England emoji
+                        * PHP: "\u{1F3F4}\u{E0067}\u{E0062}\u{E0065}\u{E006E}\u{E0067}\u{E007F}"
+                        */
+                       'Flag of england'                        => array( '🏴󠁧󠁢󠁥󠁮󠁧󠁿', "\ud83c\udff4\udb40\udc67\udb40\udc62\udb40\udc65\udb40\udc6e\udb40\udc67\udb40\udc7f", 'iso-8859-1' ),
+                       'Malicious script closer'                => array( '</script>', '\u003C/script\u003E', 'iso-8859-1' ),
+                       'Entity-encoded malicious script closer' => array( '&lt;/script&gt;', '&lt;/script&gt;', 'iso-8859-1' ),
+
+               );
+       }
+
+       /**
+        * @ticket 61510
+        *
+        * @dataProvider data_invalid_script_module_data
+        * @param mixed $data Data to return in filter.
+        */
+       public function test_print_script_module_data_does_not_print_invalid_data( $data ) {
+               $this->script_modules->enqueue( '@test/module', '/example.js' );
+               add_action(
+                       'script_module_data_@test/module',
+                       function ( $_ ) use ( $data ) {
+                               return $data;
+                       }
+               );
+
+               $actual = get_echo( array( $this->script_modules, 'print_script_module_data' ) );
+
+               $this->assertSame( '', $actual );
+       }
+
+       /**
+        * Data provider.
+        *
+        * @return array
+        */
+       public static function data_invalid_script_module_data(): array {
+               return array(
+                       'null'     => array( null ),
+                       'stdClass' => array( new stdClass() ),
+                       'number 1' => array( 1 ),
+                       'string'   => array( 'string' ),
+               );
+       }
</ins><span class="cx" style="display: block; padding: 0 10px"> }
</span></span></pre>
</div>
</div>

</body>
</html>