get_inline_widget_config( $api_key ) ); wp_register_script( self::WIDGET_HANDLE, Agentyme_API::PLATFORM_URL . '/widget.js', [ self::RUNTIME_HANDLE ], AGENTYME_VERSION, true ); wp_enqueue_script( self::WIDGET_HANDLE ); } /** * Adds the API key data attribute to the widget script tag. * * @param string $tag The script HTML tag. * @param string $handle The script handle. * @param string $src The script source URL. * * @return string */ public function add_widget_script_attributes( string $tag, string $handle, string $src ): string { if ( self::WIDGET_HANDLE !== $handle ) { return $tag; } $api_key = get_option( Agentyme_Admin::OPTION_API_KEY, '' ); if ( empty( $api_key ) ) { return $tag; } return wp_get_script_tag( [ 'id' => $handle . '-js', 'src' => $src, 'data-api-key' => $api_key, ] ); } /** * Returns inline configuration and browser compatibility code for the widget. * * @param string $api_key Validated API key. */ private function get_inline_widget_config( string $api_key ): string { $config = wp_json_encode( [ 'apiKey' => $api_key, ] ); return 'window.agentymeConfig = ' . $config . ';' . "\n" . <<<'JS' ( function() { if ( window.crypto && typeof window.crypto.randomUUID === 'function' ) { return; } var cryptoObject = window.crypto || {}; if ( typeof cryptoObject.getRandomValues !== 'function' ) { cryptoObject.getRandomValues = function( values ) { for ( var index = 0; index < values.length; index++ ) { values[ index ] = Math.floor( Math.random() * 256 ); } return values; }; } var randomUUID = function() { return ( [ 1e7 ] + -1e3 + -4e3 + -8e3 + -1e11 ).replace( /[018]/g, function( character ) { return ( character ^ ( cryptoObject.getRandomValues( new Uint8Array( 1 ) )[ 0 ] & ( 15 >> ( character / 4 ) ) ) ).toString( 16 ); } ); }; try { Object.defineProperty( cryptoObject, 'randomUUID', { configurable: true, value: randomUUID } ); } catch ( error ) { cryptoObject.randomUUID = randomUUID; } if ( ! window.crypto ) { window.crypto = cryptoObject; } }() ); JS; } }