initial
This commit is contained in:
commit
9883323161
17470 files changed
+4470592
No files matched your search
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace Automattic\Jetpack_Boost\Modules\Image_Guide;
|
||||
|
||||
use Automattic\Jetpack\Image_CDN\Image_CDN_Core;
|
||||
|
||||
/**
|
||||
* Add an ajax endpoint to proxy external CSS files.
|
||||
*/
|
||||
class Image_Guide_Proxy {
|
||||
const NONCE_ACTION = 'jb-ig-proxy-nonce';
|
||||
|
||||
public static function init() {
|
||||
add_action( 'wp_ajax_boost_proxy_ig', array( __CLASS__, 'handle_proxy' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* AJAX handler to handle proxying of external image resources.
|
||||
*
|
||||
* @return never
|
||||
*/
|
||||
public static function handle_proxy() {
|
||||
// Verify valid nonce.
|
||||
if ( empty( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['nonce'] ), self::NONCE_ACTION ) ) {
|
||||
wp_send_json_error( 'bad nonce', 400, JSON_UNESCAPED_SLASHES );
|
||||
}
|
||||
|
||||
// Make sure currently logged in as admin.
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_send_json_error( 'not admin', 400, JSON_UNESCAPED_SLASHES );
|
||||
}
|
||||
|
||||
// Validate URL and fetch.
|
||||
$proxy_url = filter_var( wp_unslash( $_POST['proxy_url'] ?? '' ), FILTER_VALIDATE_URL );
|
||||
if ( ! wp_http_validate_url( $proxy_url ) ) {
|
||||
wp_send_json_error( 'Invalid URL', 400, JSON_UNESCAPED_SLASHES );
|
||||
}
|
||||
|
||||
$photon_url = Image_CDN_Core::cdn_url( $proxy_url );
|
||||
if ( ! Image_CDN_Core::is_cdn_url( $proxy_url ) ) {
|
||||
wp_send_json_error( 'Failed to proxy the image.', 400, JSON_UNESCAPED_SLASHES );
|
||||
}
|
||||
|
||||
$response = wp_safe_remote_get( $photon_url );
|
||||
if ( is_wp_error( $response ) ) {
|
||||
wp_send_json_error( 'error', 400, JSON_UNESCAPED_SLASHES );
|
||||
}
|
||||
|
||||
// @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
|
||||
wp_send_json_success( iterator_to_array( wp_remote_retrieve_headers( $response ) ), null, JSON_UNESCAPED_SLASHES );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace Automattic\Jetpack_Boost\Modules\Image_Guide;
|
||||
|
||||
use Automattic\Jetpack_Boost\Admin\Admin;
|
||||
use Automattic\Jetpack_Boost\Contracts\Feature;
|
||||
use Automattic\Jetpack_Boost\Lib\Analytics;
|
||||
|
||||
class Image_Guide implements Feature {
|
||||
|
||||
public function setup() {
|
||||
if ( is_user_logged_in() && current_user_can( 'manage_options' ) ) {
|
||||
Image_Guide_Proxy::init();
|
||||
}
|
||||
|
||||
// Show the UI only when the user is logged in, with sufficient permissions and isn't looking at the dashboard.
|
||||
if ( is_admin() || ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Enqueue the tracks library.
|
||||
add_action( 'wp_enqueue_scripts', array( Analytics::class, 'init_tracks_scripts' ) );
|
||||
|
||||
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );
|
||||
|
||||
/**
|
||||
* The priority determines where the admin bar menu item is placed.
|
||||
*/
|
||||
add_action( 'admin_bar_menu', array( $this, 'add_to_adminbar' ), 500 );
|
||||
}
|
||||
|
||||
public static function get_slug() {
|
||||
return 'image_guide';
|
||||
}
|
||||
|
||||
public function enqueue_assets() {
|
||||
wp_enqueue_script( 'jetpack-boost-guide', plugins_url( 'dist/guide.min.js', __FILE__ ), array( 'wp-i18n' ), JETPACK_BOOST_VERSION, true );
|
||||
wp_enqueue_style( 'jetpack-boost-guide', plugins_url( 'dist/guide.min.css', __FILE__ ), array(), JETPACK_BOOST_VERSION, 'screen' );
|
||||
|
||||
wp_localize_script(
|
||||
'jetpack-boost-guide',
|
||||
'jetpackBoostAnalytics',
|
||||
array(
|
||||
'tracksData' => Analytics::get_tracking_data(),
|
||||
)
|
||||
);
|
||||
wp_localize_script(
|
||||
'jetpack-boost-guide',
|
||||
'jbImageGuide',
|
||||
array(
|
||||
'proxyNonce' => wp_create_nonce( Image_Guide_Proxy::NONCE_ACTION ),
|
||||
'ajax_url' => admin_url( 'admin-ajax.php' ),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param \WP_Admin_Bar $bar
|
||||
*/
|
||||
public function add_to_adminbar( $bar ) {
|
||||
// Disable in Admin Dashboard
|
||||
if ( is_admin() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$bar->add_menu(
|
||||
array(
|
||||
'id' => 'jetpack-boost-guide',
|
||||
'parent' => null,
|
||||
'group' => null,
|
||||
'title' => 'Jetpack Boost', // "Jetpack Boost" is a product name, do not translate.
|
||||
'href' => admin_url( 'admin.php?page=' . Admin::MENU_SLUG ),
|
||||
'meta' => array(
|
||||
'target' => '_self',
|
||||
'class' => 'jetpack-boost-guide',
|
||||
),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public static function is_available() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
<?php return array('dependencies' => array('wp-i18n', 'wp-polyfill'), 'version' => '6c102965235b0a1f6156');
|
||||
@@ -0,0 +1 @@
|
||||
div.svelte-1yjr9q3{align-items:center;display:flex;justify-content:center}.spinner.svelte-q7ue1b{animation:svelte-q7ue1b-pulse 1.25s ease-in-out infinite reverse}@keyframes svelte-q7ue1b-pulse{0%{transform:scale(1) rotate(0deg)}70%{transform:scale(1.4) rotate(30deg)}to{transform:scale(.9) rotate(-190deg)}}svg.svelte-qy5udj{transform:translateY(2px)}.interaction-area.svelte-1vido64{margin-bottom:-15px;margin-left:-15px;margin-top:-15px;padding:15px}.bubble.svelte-1vido64{background-color:#069e08;border:1px solid #ffffff0d;border-radius:50%;color:#fff;cursor:default;font-family:sans-serif;font-size:.8em;font-weight:600;height:32px;position:relative;text-align:center;text-shadow:0 0 1px #00000026;transition:background-color .3s ease;width:32px}.high.svelte-1vido64 .bubble:where(.svelte-1vido64){background-color:#e52e00}.medium.svelte-1vido64 .bubble:where(.svelte-1vido64){background-color:#e98800}.bubble-inner.svelte-1vido64{align-items:center;bottom:0;display:flex;height:100%;justify-content:center;left:0;margin:auto;position:absolute;right:0;top:0;width:100%}.guide.small .interaction-area.svelte-1vido64{padding:15px}.guide.small .bubble.svelte-1vido64{font-size:10px;height:28px;width:28px}.guide.micro .interaction-area.svelte-1vido64{margin-left:-10px;margin-top:-10px;padding:10px}.guide.micro .bubble.svelte-1vido64{border:1px solid #ffffff4d;font-size:0;height:10px;width:10px}.guide.micro .bubble.svelte-1vido64 svg{display:none}svg.svelte-1b220d7{fill:currentcolor;height:1em;margin:0;vertical-align:middle;width:1em}a.svelte-1okxgd8{color:#3c434a!important;font-weight:600!important}a.documentation.svelte-1okxgd8{color:#3c434a!important;font-weight:500!important}.preview.svelte-1okxgd8{align-items:flex-start;display:flex;gap:15px;margin-bottom:15px;max-width:360px;width:100%}.preview.svelte-1okxgd8 img:where(.svelte-1okxgd8){border-radius:3px;box-shadow:0 0 2px 1px #f2f2f2}.info.svelte-1okxgd8{font-size:.9em;margin-top:15px}.jetpack-boost-guide-popup.svelte-1okxgd8{background-color:#fff;background:linear-gradient(159.87deg,#f6f6f4 7.24%,#f7f4ea 64.73%,#ddedd5 116.53%);border-radius:6px;color:#3c434a;font-family:sans-serif;margin-bottom:10px;min-width:320px;overflow:hidden;padding:25px;position:fixed;text-align:left;width:fit-content;z-index:90000}.title.svelte-1okxgd8{font-weight:600;overflow-wrap:anywhere}.explanation.svelte-1okxgd8{margin-top:5px}.description.svelte-1okxgd8{font-size:.9em}.row.svelte-1okxgd8{border-bottom:1px dotted #d9d9d9;display:flex;font-size:14px;gap:10px;justify-content:space-between;margin-bottom:5px}.row.svelte-1okxgd8:last-child{border-bottom:none}.logo.svelte-1okxgd8{bottom:-25px;opacity:.04;pointer-events:none;position:absolute;right:-50px;transform:rotate(15deg)}.guide.small .preview.svelte-1okxgd8{gap:8px}.jetpack-boost-guide:not(.relative){left:0;position:absolute;top:0}.jetpack-boost-guide.relative{position:relative}.guide.svelte-6tsow1{left:0;line-height:1.55;padding:20px;position:absolute;top:0;z-index:8000}.guide.small.svelte-6tsow1{font-size:13px}.guide.micro.svelte-6tsow1{font-size:13px;padding:10px}.guide.show.svelte-6tsow1{z-index:9000}.guide.svelte-6tsow1{font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen-Sans,Ubuntu,Cantarell,Helvetica Neue,sans-serif!important;font-size:15px!important}.previews.svelte-6tsow1{display:flex;flex-wrap:wrap;gap:15px;margin-bottom:15px;width:100%}.jetpack-boost-guide__backdrop{filter:brightness(.3);transition:opacity .2s ease-in-out,filter .2s ease-in-out}#jetpack-boost-guide-bar.ab-item.svelte-1km5e3e{align-items:center;display:flex;gap:10px}#jetpack-boost-guide-bar.ab-item.paused.svelte-1km5e3e svg{filter:grayscale(100%) contrast(1.7)}
|
||||
@@ -0,0 +1,2 @@
|
||||
(()=>{var e={941(e,t,n){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,i=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(r++,"%c"===e&&(i=r))}),t.splice(i,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=n(212)(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},212(e,t,n){e.exports=function(e){function t(e){let n,i,s,o=null;function a(...e){if(!a.enabled)return;const r=a,i=Number(new Date),s=i-(n||i);r.diff=s,r.prev=n,r.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(n,i)=>{if("%%"===n)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];n=s.call(r,t),e.splice(o,1),o--}return n}),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function i(e,t){let n=0,r=0,i=-1,s=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||"*"===t[r]))"*"===t[r]?(i=r,s=n,r++):(n++,r++);else{if(-1===i)return!1;r=i+1,s++,n=s}for(;r<t.length&&"*"===t[r];)r++;return r===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of n)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const n of t.skips)if(i(e,n))return!1;for(const n of t.names)if(i(e,n))return!0;return!1},t.humanize=n(997),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(n=>{t[n]=e[n]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t}},997(e){var t=1e3,n=60*t,r=60*n,i=24*r,s=7*i,o=365.25*i;function a(e,t,n,r){var i=t>=1.5*n;return Math.round(e/n)+" "+r+(i?"s":"")}e.exports=function(e,l){l=l||{};var c=typeof e;if("string"===c&&e.length>0)return function(e){if((e=String(e)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(millisecondLine truncated
|
||||
__("Received HTTP %d while communicating with your WordPress site","jetpack-boost"),s.status));return s}},723(e){"use strict";e.exports=window.wp.i18n},482(e,t,n){"use strict";n.d(t,{zo:()=>Zi});const r=globalThis.process?.env?.NODE_ENV;var i=r&&!r.toLowerCase().startsWith("prod"),s=Array.isArray,o=Array.prototype.indexOf,a=Array.prototype.includes,l=Array.from,c=Object.defineProperty,u=Object.getOwnPropertyDescriptor,f=Object.getOwnPropertyDescriptors,d=Object.prototype,h=Array.prototype,v=Object.getPrototypeOf,p=Object.isExtensible;const g=()=>{};function m(e){return e()}function w(e){for(var t=0;t<e.length;t++)e[t]()}function y(){var e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}const b=16,_=32,k=512,x=1024,C=2048,S=4096,$=8192,E=16384,z=32768,j=1<<25,F=65536,O=1<<17,A=1<<19,T=1<<25,M=65536,P=1<<21,L=1<<23,I=Symbol("$state"),R=Symbol("legacy props"),D=Symbol(""),U=Symbol("proxy path"),W=Symbol("attributes"),B=Symbol("class"),q=Symbol("style"),N=Symbol("text"),H=Symbol("hmr anchor"),V=new class extends Error{name="StaleReactionError";message="The reaction that called `getAbortSignal()` was re-run or destroyed"};function K(e){if(i){const t=new Error(`lifecycle_outside_component\n\`${e}(...)\` can only be used during component initialisation\nhttps://svelte.dev/e/lifecycle_outside_component`);throw t.name="Svelte error",t}throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function G(e,t,n){if(i){const r=new Error(`each_key_duplicate\n${n?`Keyed each block has duplicate key \`${n}\` at indexes ${e} and ${t}`:`Keyed each block has duplicate key at indexes ${e} and ${t}`}\nhttps://svelte.dev/e/each_key_duplicate`);throw r.name="Svelte error",r}throw new Error("https://svelte.dev/e/each_key_duplicate")}function Z(e,t,n){if(i){const r=new Error(`each_key_volatile\nKeyed each block has key that is not idempotent — the key for item at index ${e} was \`${t}\` but is now \`${n}\`. Keys must be the same each time for a given item\nhttps://svelte.dev/e/each_key_volatile`);throw r.name="Svelte error",r}throw new Error("https://svelte.dev/e/each_key_volatile")}const J=Symbol(),X=Symbol("filename"),Y="http://www.w3.org/1999/xhtml";var Q="font-weight: bold",ee="font-weight: normal";function te(e){i?console.warn(`%c[svelte] state_proxy_equality_mismatch\n%cReactive \`$state(...)\` proxies and the values they proxy have different identities. Because of this, comparisons with \`${e}\` will produce unexpected results\nhttps://svelte.dev/e/state_proxy_equality_mismatch`,Q,ee):console.warn("https://svelte.dev/e/state_proxy_equality_mismatch")}function ne(e){return e===this.v}function re(e,t){return e!=e?t==t:e!==t||null!==e&&"object"==typeof e||"function"==typeof e}function ie(e){return!re(e,this.v)}let se=!1;function oe(e,t){return e.label=t,ae(e.v,t),e}function ae(e,t){return e?.[U]?.(t),e}function le(e){const t=new Error,n=function(){const e=Error.stackTraceLimit;Error.stackTraceLimit=1/0;const t=(new Error).stack;if(Error.stackTraceLimit=e,!t)return[];const n=t.split("\n"),r=[];for(let e=0;e<n.length;e++){const t=n[e],i=t.replaceAll("\\","/");if("Error"!==t.trim()){if(t.includes("validate_each_keys"))return[];i.includes("svelte/src/internal")||i.includes("node_modules/.vite")||r.push(t)}}return r}();return 0===n.length?null:(n.unshift("\n"),c(t,"stack",{value:n.join("\n")}),c(t,"name",{value:e}),t)}function ce(e,t){if(!i)throw new Error("invariant(...) was not guarded by if (DEV)");e||function(e){if(i){const t=new Error(`invariant_violation\nAn invariant violation occurred, meaning Svelte's internal assumptions were flawed. This is a bug in Svelte, not your app — please open an issue at https://github.com/sveltejs/svelte, citing the following message: "${e}"\nhttps://svelte.dev/e/invariant_violation`);throw t.name="Svelte error",t}throw new Error("https://svelte.dev/e/invariant_violation")}(t)}let ue=null;function fe(e){ue=e}let de=null;function he(e){de=e}let ve=null;function pe(e){ve=e}function ge(e,t=!1,n){ue={p:ue,i:!1,c:null,e:null,s:e,x:null,r:$n,l:se&&!t?{s:null,u:null,$:[]}:null},i&&(ue.function=n,ve=n)}function me(e){var t=ue,n=t.e;if(null!==n)for(var r of(t.e=null,n))tn(r);return void 0!==e&&(t.x=e),t.i=!0,ue=t.p,i&&(ve=ue?.function??null),e??{}}function we(){return!se||null!==ue&&null===ue.l}let ye=[];function be(e){if(0===ye.length&&!He){var t=ye;queueMicrotask(()=>{t===ye&&function(){var e=ye;ye=[],w(e)}()})}ye.push(e)}const _e=new WeakMap;function ke(e){var t=$n;if(null===t)return xn.f|=L,e;if(i&&e instanceof Error&&!_e.has(e)&&_e.set(e,function(e,t){const n=u(e,"message");if(!n||n.configurable){for(var r=Dt?" ":"\t",i=`\n${r}in ${t.fn?.name||"<unknown>"}`,s=t.ctx;null!==s;)i+=`\n${r}in ${s.function?.[X].split("/").pop()}`,s=s.p;return{message:e.message+`\n${i}\n`,stack:e.stack?.split("\n").filter(e=>!e.includes("svelte/src/internal")).join("\n")}}}(e,t)),0===(t.f&z)&&!(4&t.f))throw i&&!t.parent&&e instanceof Error&&Ce(e),e;xe(e,t)}function xe(e,t){for(;null!==t;){Line truncated
|
||||
@@ -0,0 +1,80 @@
|
||||
import { setupImageGuideUI } from '@automattic/jetpack-image-guide';
|
||||
import { isSameOrigin } from '../../../assets/src/js/lib/utils/is-same-origin';
|
||||
import { prepareAdminAjaxRequest } from '../../../assets/src/js/lib/utils/make-admin-ajax-request';
|
||||
import { recordBoostPixelEvent } from '$lib/utils/analytics';
|
||||
import analytics from '@automattic/jetpack-analytics';
|
||||
|
||||
/**
|
||||
* Fetches the weight of a resource using a proxy if the resource is not on the same origin.
|
||||
* This function is passed to MeasurableImageStore to be used when fetching the file size of images.
|
||||
*
|
||||
* @param url The URL of the resource to fetch.
|
||||
* @return A Promise that resolves to a Response object.
|
||||
*/
|
||||
async function fetchWeightUsingProxy( url: string ): Promise< Response > {
|
||||
if ( ! isSameOrigin( url ) ) {
|
||||
const response = await prepareAdminAjaxRequest(
|
||||
{
|
||||
action: 'boost_proxy_ig',
|
||||
proxy_url: url,
|
||||
nonce: jbImageGuide.proxyNonce,
|
||||
},
|
||||
jbImageGuide.ajax_url
|
||||
);
|
||||
|
||||
const contentType = response.headers.get( 'content-type' );
|
||||
|
||||
if ( contentType && contentType.indexOf( 'application/json' ) !== -1 ) {
|
||||
const json = await response.clone().json();
|
||||
if ( json && json.data[ 'content-length' ] ) {
|
||||
// If the JSON data contains the content length, create a new response object with the JSON headers and the original response body.
|
||||
const headers = new Headers();
|
||||
for ( const key in json.data ) {
|
||||
if ( Object.hasOwn( json.data, key ) ) {
|
||||
headers.set( key, json.data[ key ] );
|
||||
}
|
||||
}
|
||||
|
||||
const newResponse = new Response( response.body, {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers,
|
||||
} );
|
||||
return newResponse;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If the resource is on the same origin or the response is not JSON, fetch the resource using a HEAD request with no-cors mode.
|
||||
return await fetch( url, { method: 'HEAD', mode: 'no-cors' } );
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the AdminBarToggle component when the DOM is ready.
|
||||
*/
|
||||
document.addEventListener( 'DOMContentLoaded', () => {
|
||||
analytics.initialize(
|
||||
jetpackBoostAnalytics.tracksData.userData.userid,
|
||||
jetpackBoostAnalytics.tracksData.userData.username,
|
||||
{
|
||||
blog_id: jetpackBoostAnalytics.tracksData.blogId,
|
||||
}
|
||||
);
|
||||
|
||||
const tracksCallback = ( action: string, props: { [ key: string ]: number | string } ) => {
|
||||
recordBoostPixelEvent( action, props );
|
||||
};
|
||||
|
||||
const adminBarToggle = document.getElementById( 'wp-admin-bar-jetpack-boost-guide' );
|
||||
const link = adminBarToggle?.querySelector( 'a' );
|
||||
if ( adminBarToggle && link ) {
|
||||
const href = link.getAttribute( 'href' );
|
||||
link.remove();
|
||||
|
||||
setupImageGuideUI( adminBarToggle, {
|
||||
href: href!,
|
||||
tracksCallback,
|
||||
fetchFunction: fetchWeightUsingProxy,
|
||||
} );
|
||||
}
|
||||
} );
|
||||
Reference in new issue
Block a user