YouTube JS Engine Tamer

To enhance YouTube performance by modifying YouTube JS Engine

当前为 2024-04-24 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name YouTube JS Engine Tamer
  3. // @namespace UserScripts
  4. // @match https://www.youtube.com/*
  5. // @version 0.14.1
  6. // @license MIT
  7. // @author CY Fung
  8. // @icon https://github.com/cyfung1031/userscript-supports/raw/main/icons/yt-engine.png
  9. // @description To enhance YouTube performance by modifying YouTube JS Engine
  10. // @grant none
  11. // @require https://cdn.jsdelivr.net/gh/cyfung1031/userscript-supports@7221a4efffd49d852de0074ec503d4febb99f28b/library/nextBrowserTick.min.js
  12. // @run-at document-start
  13. // @unwrap
  14. // @inject-into page
  15. // @allFrames true
  16. // ==/UserScript==
  17.  
  18. (() => {
  19.  
  20. const NATIVE_CANVAS_ANIMATION = false; // for #cinematics
  21. const FIX_schedulerInstanceInstance = 2 | 4;
  22. const FIX_yt_player = true; // DONT CHANGE
  23. const FIX_Animation_n_timeline = true;
  24. const NO_PRELOAD_GENERATE_204 = false;
  25. const ENABLE_COMPUTEDSTYLE_CACHE = true;
  26. const NO_SCHEDULING_DUE_TO_COMPUTEDSTYLE = true;
  27. const CHANGE_appendChild = true; // discussions#236759
  28.  
  29. const FIX_error_many_stack = true; // should be a bug caused by uBlock Origin
  30. // const FIX_error_many_stack_keepAliveDuration = 200; // ms
  31. // const FIX_error_many_stack_keepAliveDuration_check_if_n_larger_than = 8;
  32.  
  33. const FIX_Iframe_NULL_SRC = true;
  34.  
  35. const IGNORE_bindAnimationForCustomEffect = true; // prevent `v.bindAnimationForCustomEffect(this);` being executed
  36.  
  37. const FIX_ytdExpander_childrenChanged = true;
  38. const FIX_paper_ripple_animate = true;
  39. const FIX_avoid_incorrect_video_meta = true; // omit the incorrect yt-animated-rolling-number
  40. const FIX_avoid_incorrect_video_meta_emitterBehavior = true;
  41.  
  42. const FIX_doIdomRender = true;
  43.  
  44. const FIX_Shady = true;
  45.  
  46. // [[ 2024.04.24 ]]
  47. const MODIFY_ShadyDOM_OBJ = true;
  48. // << if MODIFY_ShadyDOM_OBJ >>
  49. const WEAKREF_ShadyDOM = true;
  50. const OMIT_ShadyDOM_EXPERIMENTAL = 1 | 0; // 1 => enable; 2 => composedPath
  51. const OMIT_ShadyDOM_settings = 0 | 0 | 0; // 1: inUse; 2: handlesDynamicScoping; 4: force // {{ PRELIM TESTING PURPOSE }}
  52. // << end >>
  53.  
  54. const WEAK_REF_BINDING_CONTROL = 1 | 2; // 2 - conflict control with ShadyDOM weakref
  55.  
  56. const FIX_ytAction_ = true; // ytd-app
  57. const FIX_onVideoDataChange = false;
  58. // const FIX_onClick = true;
  59. const FIX_onStateChange = true;
  60. const FIX_onLoopRangeChange = true;
  61. // const FIX_maybeUpdateFlexibleMenu = true; // ytd-menu-renderer
  62. const FIX_VideoEVENTS_v2 = true; // true might cause bug in switching page
  63.  
  64. const ENABLE_discreteTasking = true;
  65. // << if ENABLE_discreteTasking >>
  66. const FIX_stampDomArray_stableList = true;
  67. const ENABLE_weakenStampReferences = true; // disabled in old browsers
  68. // << end >>
  69.  
  70. const FIX_perfNow = true; // history state issue; see https://bugzilla.mozilla.org/show_bug.cgi?id=1756970
  71. const ENABLE_ASYNC_DISPATCHEVENT = false; // problematic
  72.  
  73. const UNLOAD_DETACHED_POLYMER = false; // unstable
  74.  
  75. const WEAK_REF_BINDING = true; // false if your browser is slow
  76. // << if WEAK_REF_BINDING >>
  77. const WEAK_REF_PROXY_DOLLAR = true; // false if your browser is slow
  78. // << end >>
  79.  
  80. const TO_REMOVE_PRUNE_propNeedles = true; // brave scriptlet related
  81. const DEBUG_removePrune = false; // true for DEBUG
  82.  
  83. const FIX_XHR_REQUESTING = true;
  84. const FIX_VIDEO_BLOCKING = true; // usually it is a ads block issue
  85.  
  86. const LOG_FETCHMETA_UPDATE = false; // for DEBUG
  87.  
  88. const IGNORE_bufferhealth_CHECK = false; // experimental; true will make "Stats for nerds" no info.
  89.  
  90. const DENY_requestStorageAccess = true; // remove document.requestStorageAccess
  91. const DISABLE_IFRAME_requestStorageAccess = true; // no effect if DENY_requestStorageAccess is true
  92.  
  93. const DISABLE_COOLDOWN_SCROLLING = true; // YT cause scroll hang in MacOS
  94.  
  95. // ----------------------------- Shortkey Keyboard Control -----------------------------
  96. // dependency: FIX_yt_player
  97.  
  98. const FIX_SHORTCUTKEYS = 2; // 0 - no fix; 1 - basic fix; 2 - advanced fix
  99. // [0] no fix - not recommended
  100. // [1] basic fix - just fix the global focus detection variable
  101. // [2] advanced fix - call the shortcut actions directly, auto foucs change, direct control of spacebar behavior, etc
  102. // (note) 0 or 1 if you find conflict with other userscripts/plugin
  103.  
  104. const CHANGE_SPEEDMASTER_SPACEBAR_CONTROL = 0; // 0 - disable; 1 - force true; 2 - force false
  105. const USE_IMPROVED_PAUSERESUME_UNDER_NO_SPEEDMASTER = true; // only for SPEEDMASTER = false & FIX_SHORTCUTKEYS = 2
  106.  
  107.  
  108. // const CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE = false; // NO USE; TO BE REVIEWED
  109.  
  110. // ----------------------------- Shortkey Keyboard Control -----------------------------
  111.  
  112. /*
  113. window.addEventListener('edm',()=>{
  114. let p = [...this.onerror.errorTokens][0].token; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })()
  115. });
  116.  
  117. window.addEventListener('edn',()=>{
  118. let p = [...this.onerror.errorTokens][0].token+"X"; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })()
  119. });
  120. window.addEventListener('edr',()=>{
  121. let p = '123'; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })()
  122. });
  123. */
  124.  
  125. // only for macOS with Chrome/Firefox 100+
  126. const advanceLogging = typeof AbortSignal !== 'undefined' && typeof (AbortSignal || 0).timeout === 'function' && typeof navigator !== 'undefined' && /\b(Macintosh|Mac\s*OS)\b/i.test((navigator || 0).userAgent || '');
  127.  
  128. const win = this instanceof Window ? this : window;
  129.  
  130. // Create a unique key for the script and check if it is already running
  131. const hkey_script = 'jswylcojvzts';
  132. if (win[hkey_script]) throw new Error('Duplicated Userscript Calling'); // avoid duplicated scripting
  133. win[hkey_script] = true;
  134.  
  135.  
  136. // const setImmediate = ((self || 0).jmt || 0).setImmediate;
  137. /** @type {(f: ()=>{})=>{}} */
  138. const nextBrowserTick = (self || 0).nextBrowserTick || 0;
  139. const nextBrowserTick_ = nextBrowserTick || (f => f());
  140.  
  141. let p59 = 0;
  142.  
  143. const Promise = (async () => { })().constructor;
  144.  
  145. const PromiseExternal = ((resolve_, reject_) => {
  146. const h = (resolve, reject) => { resolve_ = resolve; reject_ = reject };
  147. return class PromiseExternal extends Promise {
  148. constructor(cb = h) {
  149. super(cb);
  150. if (cb === h) {
  151. /** @type {(value: any) => void} */
  152. this.resolve = resolve_;
  153. /** @type {(reason?: any) => void} */
  154. this.reject = reject_;
  155. }
  156. }
  157. };
  158. })();
  159.  
  160. /**
  161. @param {number} x
  162. @param {number} d */
  163. const toFixed2 = (x, d) => {
  164. let t = x.toFixed(d);
  165. let y = `${+t}`;
  166. return y.length > t.length ? t : y;
  167. }
  168.  
  169.  
  170. let pf31 = new PromiseExternal();
  171.  
  172. // native RAF
  173. let __requestAnimationFrame__ = typeof webkitRequestAnimationFrame === 'function' ? window.webkitRequestAnimationFrame.bind(window) : window.requestAnimationFrame.bind(window);
  174.  
  175. // 1st wrapped RAF
  176. const baseRAF = (callback) => {
  177. return p59 ? __requestAnimationFrame__(callback) : __requestAnimationFrame__((hRes) => {
  178. pf31.then(() => {
  179. callback(hRes);
  180. });
  181. });
  182. };
  183.  
  184. // 2nd wrapped RAF
  185. window.requestAnimationFrame = baseRAF;
  186.  
  187. const insp = o => o ? (o.polymerController || o.inst || o || 0) : (o || 0);
  188. const indr = o => insp(o).$ || o.$ || 0;
  189.  
  190. const prototypeInherit = (d, b) => {
  191. const m = Object.getOwnPropertyDescriptors(b);
  192. for (const p in m) {
  193. if (!Object.getOwnPropertyDescriptor(d, p)) {
  194. Object.defineProperty(d, p, m[p]);
  195. }
  196. }
  197. };
  198.  
  199. /** @type {(o: Object | null) => WeakRef | null} */
  200. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null);
  201.  
  202. /** @type {(wr: Object | null) => Object | null} */
  203. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  204.  
  205. if (typeof Document.prototype.requestStorageAccessFor === 'function') {
  206. if (DENY_requestStorageAccess) {
  207. // https://developer.mozilla.org/en-US/docs/Web/API/Document/requestStorageAccessFor
  208. Document.prototype.requestStorageAccessFor = undefined;
  209. console.log('[yt-js-engine-tamer]', 'requestStorageAccessFor is removed.');
  210. } else if (DISABLE_IFRAME_requestStorageAccess && window !== top) {
  211. Document.prototype.requestStorageAccessFor = function () {
  212. return new Promise((resolve, reject) => {
  213. reject();
  214. });
  215. };
  216. }
  217. }
  218.  
  219. FIX_perfNow && performance.timeOrigin > 9 && (() => {
  220. if (performance.now23 || performance.now16 || typeof Performance.prototype.now !== 'function') return;
  221. const f = performance.now23 = Performance.prototype.now;
  222.  
  223. let k = 0; // 0 <= k < 9998m
  224. let u = 0;
  225. let s = ((performance.timeOrigin % 7) + 1) / 7 - 1e-2 / 7; // s > 0.14
  226.  
  227. // By definition, performance.now() is mono increasing.
  228. // Fixing in YouTube.com is required to ensure performance.now() is strictly increasing.
  229. performance.now = performance.now16 = function () {
  230. /**
  231. * Bug 1842437 - When attempting to go back on youtube.com, the content remains the same
  232. *
  233. * If consecutive session history entries had history.state.entryTime set to same value,
  234. * back button doesn't work as expected. The entryTime value is coming from performance.now()
  235. * and modifying its return value slightly to make sure two close consecutive calls don't
  236. * get the same result helped with resolving the issue.
  237. */
  238. // see https://bugzilla.mozilla.org/show_bug.cgi?id=1756970
  239. // see https://bugzilla.mozilla.org/show_bug.cgi?id=1842437
  240.  
  241. const v = typeof (this || 0).now23 === 'function' ? this.now23() + s : f.call(performance) + s; // v > 0.14
  242. if (u + 0.0015 < (u = v)) k = 0; // note: hRes should be accurate to 5 µs in isolated contexts
  243. else if (k < 0.001428) k += 1e-6 / 7; // M = 10000 * m; m * 9996 = 0.001428
  244. else { // more than 9998 consecutive calls
  245. /**
  246. *
  247. * max no. of consecutive calls
  248. *
  249. * Sample Size: 4800
  250. * Sample Avg = 1565.375
  251. * Sample Median = 1469.5
  252. * Sample Max = 5660 << 7500 << 9999
  253. *
  254. *
  255. * */
  256. k = 0;
  257. s += 1 / 7;
  258. }
  259. return v + k; // 0 < v - M < v - M + k < v
  260. }
  261.  
  262. let loggerMsg = '';
  263. if (`${performance.now()}` === `${performance.now()}`) {
  264. const msg1 = 'performance.now is modified but performance.now() is not strictly increasing.';
  265. const msg2 = 'performance.now cannot be modified and performance.now() is not strictly increasing.';
  266. loggerMsg = performance.now !== performance.now16 ? msg1 : msg2; // might not able to set in Firefox
  267. }
  268. loggerMsg && console.warn(loggerMsg);
  269. })();
  270.  
  271. // WEAKREF_ShadyDOM
  272.  
  273. MODIFY_ShadyDOM_OBJ && (() => {
  274.  
  275. const setupPlainShadyDOM = (b) => {
  276. (OMIT_ShadyDOM_settings & 1) && (b.inUse === true) && (b.inUse = false);
  277. (OMIT_ShadyDOM_settings & 2) && (b.handlesDynamicScoping === true) && (b.handlesDynamicScoping = false);
  278. (OMIT_ShadyDOM_settings & 4) && (b.force === true) && (b.force = false);
  279. b.patchOnDemand = true;
  280. b.preferPerformance = true;
  281. b.noPatch = true;
  282. }
  283.  
  284. const isPlainObject = (b, m) => {
  285. if (!b || typeof b !== 'object') return false;
  286. const e = Object.getOwnPropertyDescriptors(b);
  287. if (e.length <= m) return false;
  288. let pr = 0;
  289. for (const k in e) {
  290. const d = e[k];
  291. if (!d || d.get || d.set || !d.enumerable || !d.configurable) return false;
  292. if (!('value' in d) || typeof d.value === 'function') return false;
  293. pr++;
  294. }
  295. return pr > m;
  296. }
  297.  
  298. let b;
  299.  
  300. let lz = 0;
  301.  
  302. const sdp = Object.getOwnPropertyDescriptor(window, 'ShadyDOM');
  303. if (sdp && sdp.configurable && sdp.value && sdp.enumerable && sdp.writable) {
  304.  
  305. // Brave - ShadyDOM exists before userscripting
  306. b = sdp.value;
  307.  
  308. if (b && typeof b === 'object' && isPlainObject(b, 0)) {
  309. OMIT_ShadyDOM_EXPERIMENTAL && setupPlainShadyDOM(b);
  310. lz = 1;
  311. }
  312.  
  313. }
  314.  
  315.  
  316. if (sdp && sdp.configurable && sdp.value && sdp.enumerable && sdp.writable && !sdp.get && !sdp.set) {
  317. } else if (!sdp) {
  318. } else {
  319. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM is not applied [ PropertyDescriptor issue ]', sdp);
  320. return;
  321. }
  322.  
  323. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM << 01 >>', b);
  324.  
  325. delete window.ShadyDOM;
  326.  
  327. Object.defineProperty(window, 'ShadyDOM', {
  328. get() {
  329. return b;
  330. },
  331. set(nv) {
  332. let ret = 0;
  333. try {
  334. do {
  335. if (!nv || !nv.settings) {
  336. if (lz < 1 && nv && typeof nv === 'object' && isPlainObject(nv, 0)) {
  337. OMIT_ShadyDOM_EXPERIMENTAL && setupPlainShadyDOM(nv);
  338. lz = 1;
  339. break;
  340. } else {
  341. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM is not applied [nv:null]', nv);
  342. break;
  343. }
  344. }
  345.  
  346. const sdp = Object.getOwnPropertyDescriptor(this || {}, 'ShadyDOM');
  347. if (!(sdp && sdp.configurable && sdp.get && sdp.set)) {
  348. console.log(3719, '[yt-js-engine-tamer] OMIT_ShadyDOM is not applied [ incorrect PropertyDescriptor ]', nv);
  349. break;
  350. }
  351.  
  352. const ShadyDOM = nv;
  353.  
  354. const ShadyDOMSettings = ShadyDOM.settings;
  355. if (!(ShadyDOMSettings.inUse === true && ShadyDOM.inUse === true && (ShadyDOMSettings.handlesDynamicScoping || ShadyDOM.handlesDynamicScoping) === true)) {
  356. console.log(3719, '[yt-js-engine-tamer] OMIT_ShadyDOM is not applied [02]', window.ShadyDOM);
  357. break;
  358. }
  359.  
  360. const shadyDOMNodeWRM = new WeakMap();
  361. if (WEAKREF_ShadyDOM && lz < 3 && typeof WeakRef === 'function' && typeof ShadyDOM.Wrapper === 'function' && ShadyDOM.Wrapper.length === 1 && typeof (ShadyDOM.Wrapper.prototype || 0) === 'object') {
  362.  
  363. let nullElement = { node: null };
  364. Object.setPrototypeOf(nullElement, Element.prototype);
  365. let p = new ShadyDOM.Wrapper(nullElement);
  366. let d = Object.getOwnPropertyDescriptor(p, 'node');
  367. // let dummyElementOnPage = null; // strong reference
  368. // let dummyElementShadowDOM = null;
  369. if (d.configurable && d.enumerable && !d.get && !d.set && d.writable && d.value === nullElement && !Object.getOwnPropertyDescriptor(ShadyDOM.Wrapper.prototype, 'node')) {
  370.  
  371. Object.defineProperty(ShadyDOM.Wrapper.prototype, 'node', {
  372. get() {
  373. let w = shadyDOMNodeWRM.get(this);
  374. if (typeof w === 'object') w = kRef(w) || (shadyDOMNodeWRM.delete(this), undefined);
  375. // if (typeof w === 'undefined') {
  376. // if (!dummyElementOnPage) {
  377. // dummyElementOnPage = document.createElement('noscript');
  378. // document.documentElement.appendChild(dummyElementOnPage);
  379. // dummyElementShadowDOM = new ShadyDOM.Wrapper(dummyElementOnPage);
  380. // }
  381. // w = dummyElementOnPage;
  382. // }
  383. return w;
  384. },
  385. set(nv) {
  386. const isValidNV = typeof nv === 'object' && nv;
  387. if (isValidNV && typeof nv.deref === 'function') nv = nv.deref();
  388. if (nv !== this) {
  389. if (isValidNV && nv) {
  390. let nvWR;
  391. let y = shadyDOMNodeWRM.get(nv);
  392. if (y && typeof y === 'object') {
  393. y = kRef(y);
  394. y && (nvWR = shadyDOMNodeWRM.get(y));
  395. // note: do not unlink the previous ShadowDOM; keep prevShadow -> changedElm*[old]
  396. }
  397. if (y !== this) {
  398. if (!nvWR) nvWR = mWeakRef(nv);
  399. let w = shadyDOMNodeWRM.get(this);
  400. if (typeof w === 'object') {
  401. w = kRef(w);
  402. w && shadyDOMNodeWRM.delete(w); // update prevElm -> CLEAR
  403. }
  404. shadyDOMNodeWRM.set(this, nvWR); // set newShadow -> changedElm*[old]
  405. shadyDOMNodeWRM.set(nv, mWeakRef(this)); // update changedElm -> newShadow*[new]
  406. }
  407. } else {
  408. let w = shadyDOMNodeWRM.get(this);
  409. if (typeof w === 'object') {
  410. w = kRef(w);
  411. w && shadyDOMNodeWRM.delete(w); // update prevElm -> CLEAR
  412. }
  413. shadyDOMNodeWRM.delete(this); // update newShadow -> CLEAR
  414. }
  415. }
  416. return true;
  417. },
  418. enumerable: true,
  419. configurable: true
  420. });
  421. console.log('[yt-js-engine-tamer] FIX::ShadyDOM << WEAKREF_ShadyDOM >>')
  422. }
  423. // Object.getOwnPropertyDescriptor(ShadyDOM.Wrapper.prototype, 'node')
  424. // console.log()
  425. }
  426.  
  427. if (OMIT_ShadyDOM_EXPERIMENTAL && lz < 3) {
  428.  
  429. setupPlainShadyDOM(ShadyDOMSettings);
  430. setupPlainShadyDOM(ShadyDOM);
  431.  
  432. const standardWrap = function (a) {
  433. if (a instanceof ShadowRoot || a instanceof ShadyDOM.Wrapper) return a;
  434. let u = shadyDOMNodeWRM.get(a);
  435. if (typeof u === 'object') u = kRef(u);
  436. if (typeof u === 'object' && u) {
  437. return u;
  438. }
  439. return new ShadyDOM.Wrapper(a);
  440. }
  441.  
  442. ShadyDOM.isShadyRoot = function () { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - isShadyRoot'); return false; }
  443.  
  444. if (typeof ShadyDOM.wrap === 'function' && ShadyDOM.wrap.length === 1) {
  445. ShadyDOM.wrap = function (a) { 0 && console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - wrap'); return standardWrap(a) }
  446. }
  447. if (typeof ShadyDOM.wrapIfNeeded === 'function' && ShadyDOM.wrapIfNeeded.length === 1) {
  448. ShadyDOM.wrapIfNeeded = function (a) { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - wrapIfNeeded'); return standardWrap(a) }
  449. }
  450. ShadyDOM.patchElementProto = function () { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - patchElementProto') }
  451. ShadyDOM.patch = function () { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - patch') }
  452.  
  453. // To be confirmed
  454. if (OMIT_ShadyDOM_EXPERIMENTAL & 2) {
  455. ShadyDOM.composedPath = function (e) {
  456. const t = (e || 0).target || null;
  457. if (!(t instanceof HTMLElement)) {
  458. console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM&2) composedPath', t)
  459. }
  460. return t instanceof HTMLElement ? [t] : [];
  461. };
  462. }
  463.  
  464. }
  465.  
  466. lz = 3;
  467.  
  468. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM << 02 >>', nv)
  469.  
  470. ret = 1;
  471.  
  472. } while (0);
  473. } catch (e) {
  474. console.log('[yt-js-engine-tamer] FIX::ShadyDOM << ERROR >>', e)
  475. }
  476.  
  477. if (!ret) b = nv;
  478. else {
  479. delete this.ShadyDOM;
  480. this.ShadyDOM = nv;
  481. }
  482. return true;
  483. },
  484. enumerable: false,
  485. configurable: true
  486. });
  487.  
  488. })();
  489.  
  490. if (ENABLE_ASYNC_DISPATCHEVENT && nextBrowserTick) {
  491. const filter = new Set([
  492. 'yt-action',
  493. // 'iframe-src-replaced',
  494. 'shown-items-changed',
  495. 'can-show-more-changed', 'collapsed-changed',
  496.  
  497. 'yt-navigate', 'yt-navigate-start', 'yt-navigate-cache',
  498. 'yt-player-updated', 'yt-page-data-fetched', 'yt-page-type-changed', 'yt-page-data-updated',
  499. 'yt-navigate-finish',
  500.  
  501. // 'data-changed','yt-watch-comments-ready'
  502. ])
  503. EventTarget.prototype.dispatchEvent938 = EventTarget.prototype.dispatchEvent;
  504. EventTarget.prototype.dispatchEvent = function (event) {
  505. const type = (event || 0).type;
  506. if (typeof type === 'string' && event.isTrusted === false && (event instanceof CustomEvent) && event.cancelable === false) {
  507. if (!filter.has(type) && !type.endsWith('-changed')) {
  508. if (this instanceof Node || this instanceof Window) {
  509. nextBrowserTick(() => this.dispatchEvent938(event));
  510. return true;
  511. }
  512. }
  513. }
  514. return this.dispatchEvent938(event);
  515. }
  516. }
  517.  
  518. // avoid REGEXP testPattern execution in Brave's scriptlet for performance boost
  519. const removePrune_propNeedles = () => {
  520. // const xhr = new XMLHttpRequest;
  521. const pdOri = Object.getOwnPropertyDescriptor(Map.prototype, 'size');
  522. if (!pdOri || pdOri.configurable !== true) return;
  523. let propNeedles = null;
  524. const pdNew = {
  525. configurable: true,
  526. enumerable: true,
  527. get: function () {
  528. propNeedles = this;
  529. if (DEBUG_removePrune) debugger; // to locate Brave scriptlets
  530. throw new Error();
  531. }
  532. }
  533. Object.defineProperty(Map.prototype, 'size', pdNew);
  534. try {
  535. XMLHttpRequest.prototype.open.call(0);
  536. // xhr.open.call(null)
  537. } catch (e) { }
  538. Object.defineProperty(Map.prototype, 'size', pdOri);
  539. if (!propNeedles) return;
  540. const entries = [...propNeedles.entries()];
  541. propNeedles.clear();
  542. console.log('[yt-js-engine-tamer] propNeedles is cleared from scriptlet', entries, propNeedles);
  543. }
  544.  
  545. if (TO_REMOVE_PRUNE_propNeedles) {
  546. removePrune_propNeedles();
  547. }
  548.  
  549. if (FIX_XHR_REQUESTING) {
  550.  
  551. const URL = window.URL || new Function('return URL')();
  552. const createObjectURL = URL.createObjectURL.bind(URL);
  553.  
  554. XMLHttpRequest = (() => {
  555. const XMLHttpRequest_ = XMLHttpRequest;
  556. if ('__xmMc8__' in XMLHttpRequest_.prototype) return XMLHttpRequest_;
  557. const url0 = createObjectURL(new Blob([], { type: 'text/plain' }));
  558. const c = class XMLHttpRequest extends XMLHttpRequest_ {
  559. constructor(...args) {
  560. super(...args);
  561. }
  562. open(method, url, ...args) {
  563. let skip = false;
  564. if (!url || typeof url !== 'string') skip = true;
  565. else if (typeof url === 'string') {
  566. let turl = url[0] === '/' ? `.youtube.com${url}` : `${url}`;
  567. if (turl.includes('googleads') || turl.includes('doubleclick.net')) {
  568. skip = true;
  569. } else if (turl.includes('.youtube.com/pagead/')) {
  570. skip = true;
  571. } else if (turl.includes('.youtube.com/ptracking')) {
  572. skip = true;
  573. } else if (turl.includes('.youtube.com/youtubei/v1/log_event?')) {
  574. skip = true;
  575. } else if (turl.includes('.youtube.com/api/stats/')) { // /api/stats/
  576. if (turl.includes('.youtube.com/api/stats/qoe?')) {
  577. skip = true;
  578. } else if (turl.includes('.youtube.com/api/stats/ads?')) {
  579. skip = true;
  580. } else {
  581. // skip = true; // for user activity logging e.g. watched videos
  582. }
  583. } else if (turl.includes('play.google.com/log')) {
  584. skip = true;
  585. } else if (turl.includes('.youtube.com//?')) { // //?cpn=
  586. skip = true;
  587. }
  588. }
  589. if (!skip) {
  590. this.__xmMc8__ = 1;
  591. return super.open(method, url, ...args);
  592. } else {
  593. this.__xmMc8__ = 2;
  594. return super.open('GET', url0);
  595. }
  596. }
  597. send(...args) {
  598. if (this.__xmMc8__ === 1) {
  599. return super.send(...args);
  600. } else if (this.__xmMc8__ === 2) {
  601. return super.send();
  602. } else {
  603. console.log('[yt-js-engine-tamer]', 'xhr warning');
  604. return super.send(...args);
  605. }
  606. }
  607. }
  608. c.prototype.__xmMc8__ = 0;
  609. prototypeInherit(c.prototype, XMLHttpRequest_.prototype);
  610. return c;
  611. })();
  612. }
  613.  
  614. // Alternative HACK -> Tabview Youtube
  615. if (DISABLE_COOLDOWN_SCROLLING && typeof EventTarget.prototype.addEventListener52178 !== 'function' && typeof EventTarget.prototype.addEventListener === 'function') {
  616.  
  617. // ---- << this.overscrollConfig HACK >> -----
  618.  
  619. // 2024.04.19 - Playlist in Single Column Mode cannot be scrolled correctly.
  620.  
  621. /*
  622.  
  623. ;function gZb(a, b) {
  624. b = void 0 === b ? !0 : b;
  625. a.addEventListener("wheel", hZb);
  626. a.overscrollConfig = {
  627. cooldown: b
  628. }
  629. }
  630. function iZb(a) {
  631. a.overscrollConfig = void 0;
  632. a.removeEventListener("wheel", hZb)
  633. }
  634. function hZb(a) {
  635. var b = a.deltaY
  636. , c = a.target
  637. , d = null;
  638. if (window.Polymer && window.Polymer.Element) {
  639. if (c = a.path || a.composedPath && a.composedPath()) {
  640. c = g(c);
  641. for (var e = c.next(); !e.done && (e = e.value,
  642. !jZb(e, b)); e = c.next())
  643. if (e.overscrollConfig) {
  644. d = e;
  645. break
  646. }
  647. }
  648. } else
  649. for (; c && !jZb(c, b); ) {
  650. if (c.overscrollConfig) {
  651. d = c;
  652. break
  653. }
  654. c = c.parentElement
  655. }
  656. d && (b = d.overscrollConfig,
  657. b.cooldown ? (d = a.deltaY,
  658. c = b.lastDeltaY || 0,
  659. b.lastDeltaY = d,
  660. e = b.lastStopped || 0,
  661. c && e && 0 < c == 0 < d ? Math.abs(c) >= Math.abs(d) ? (d = e + 1200,
  662. c = !1) : (d = e + 600,
  663. c = !0) : (d = Date.now() + 600,
  664. c = !0),
  665. d > Date.now() && (a.preventDefault(),
  666. c && (b.lastStopped = Date.now()))) : a.preventDefault())
  667. }
  668. */
  669.  
  670. let wheelHandler = function (a) {
  671. if (window.Polymer && window.Polymer.Element) {
  672. let c;
  673. if (c = a.path || a.composedPath && a.composedPath()) {
  674. for (const e of c) {
  675. const cnt = insp(e);
  676. if (e.overscrollConfig) e.overscrollConfig = void 0;
  677. if (cnt.overscrollConfig) cnt.overscrollConfig = void 0;
  678. }
  679. }
  680. } else {
  681. let e = a.target;
  682. for (; e instanceof Element; e = e.parentElement) {
  683. const cnt = insp(e);
  684. if (e.overscrollConfig) e.overscrollConfig = void 0;
  685. if (cnt.overscrollConfig) cnt.overscrollConfig = void 0;
  686. }
  687. }
  688. };
  689.  
  690. let checkWheelListenerObjs = null;
  691.  
  692. let getObjsFn = () => {
  693. let euyVal = 0;
  694. const eukElm = {};
  695. Object.setPrototypeOf(eukElm, HTMLElement.prototype);
  696. const euzObj = new Proxy(eukElm, {
  697. get(target, prop) {
  698. throw `ErrorF31.get(${prop})`
  699. },
  700. set(target, prop, value) {
  701. throw `ErrorF33.set(${prop}, ${value})`
  702. }
  703. });
  704. const euxElm = new Proxy(eukElm, {
  705. get(target, prop) {
  706. if (prop === 'scrollTop') {
  707. euyVal = euyVal | 8;
  708. return 0;
  709. }
  710. if (prop === 'overscrollConfig') {
  711. euyVal = euyVal | 16;
  712. return void 0;
  713. }
  714. if (prop === 'scrollHeight' || prop === 'clientHeight' || prop === 'offsetHeight') {
  715. return 640;
  716. }
  717. if (prop === 'scrollLeft') {
  718. euyVal = euyVal | 8;
  719. return 0;
  720. }
  721. if (prop === 'scrollWidth' || prop === 'clientWidth' || prop === 'offsetWidth') {
  722. return 800;
  723. }
  724. throw `ErrorF45.get(${prop})`
  725. },
  726. set(target, prop, value) {
  727. throw `ErrorF47.set(${prop}, ${value})`
  728. }
  729. });
  730. const eukEvt = {};
  731. Object.setPrototypeOf(eukEvt, WheelEvent.prototype);
  732. const euyEvt = new Proxy(eukEvt, {
  733. get(target, prop) {
  734. if (prop === 'deltaY' || prop === 'deltaX') {
  735. euyVal = euyVal | 1;
  736. return -999;
  737. }
  738. if (prop === 'target') {
  739. euyVal = euyVal | 2;
  740. return euxElm
  741. }
  742. if (prop === 'path' || prop === 'composedPath') {
  743. euyVal = euyVal | 2;
  744. return [euxElm]
  745. }
  746. throw `ErrorF51.get(${prop})`
  747. },
  748. set(target, prop, value) {
  749. throw `ErrorF53.set(${prop}, ${value})`
  750. }
  751. });
  752. const setVal = (v) => {
  753. euyVal = v;
  754. }
  755. const getVal = () => {
  756. return euyVal;
  757. }
  758. return { euzObj, euyEvt, setVal, getVal };
  759. }
  760.  
  761. let checkWheelListener = (callback) => {
  762.  
  763. let callbackIdentifier = '';
  764.  
  765. let res = null;
  766. try {
  767. const { euzObj, euyEvt, getVal, setVal } = checkWheelListenerObjs || (checkWheelListenerObjs = getObjsFn());
  768. setVal(0);
  769. if (callback.call(euzObj, euyEvt) !== void 0) throw 'ErrorF99';
  770. throw `RESULT${getVal()}`;
  771. } catch (e) {
  772. res = e;
  773. }
  774.  
  775. res = `${res}` || `${null}`;
  776. if (res.length > 20) res = `${res.substring(0, 20)}...`;
  777.  
  778. callbackIdentifier = res;
  779. if (callbackIdentifier === 'RESULT27') 0;
  780. else if (callbackIdentifier === 'RESULT0') {
  781. // a.isSearch && !a.disableWheelScroll && B("desktop_enable_dmpanel_wheel_scroll")
  782. } else if (callbackIdentifier.startsWith('RESULT')) {
  783. console.log('wheel eventListener - RESULT', callbackIdentifier, callback)
  784. }
  785. return callbackIdentifier;
  786.  
  787. };
  788.  
  789. let callbackFound = false;
  790. EventTarget.prototype.addEventListener52178 = EventTarget.prototype.addEventListener;
  791. EventTarget.prototype.addEventListener = function (type, callback, option = void 0) {
  792. // M-youtube-js-engine-tamer.52178
  793. if (type === 'wheel' && !option && typeof callback === 'function' && callback.length === 1) {
  794. // (( match with signature `a.addEventListener("wheel", hZb);` )) [subject to further review]
  795. const callbackIdentifier = callback.yaujmoms || (callbackFound ? 'IGNORE' : (callback.yaujmoms = checkWheelListener(callback)));
  796. // RESULTXX / ErrorFXX / Other...
  797. if (callbackIdentifier === 'RESULT27') {
  798. this.overscrollConfigDisable = true;
  799. if (!callbackFound) {
  800. callbackFound = true; // suppose only one function is assigned to overscrollConfig cooldown [no function binding]
  801. getObjsFn = checkWheelListener = null;
  802. checkWheelListenerObjs = null;
  803. wheelHandler = null;
  804. }
  805. return void 0;
  806. } else if (!callbackFound && !this.overscrollConfigDisable) {
  807. this.overscrollConfigDisable = true;
  808. this.addEventListener52178('wheel', wheelHandler, { passive: false });
  809. }
  810. }
  811. return this.addEventListener52178(type, callback, option);
  812. };
  813.  
  814. // ---- << this.overscrollConfig HACK >> -----
  815.  
  816. }
  817.  
  818. const { pageMediaWatcher, shortcutKeysFixer, keyboardController } = (() => {
  819.  
  820. let p_a_objWR = null;
  821. let isSpaceKeyImmediate = false; // for ADVANCED_FIX_SHORTCUTKEYS
  822. let ytPageReady = 0;
  823.  
  824. let isSpeedMastSpacebarControlEnabled = false; // youtube experimental feature // can be forced by CHANGE_SPEEDMASTER_SPACEBAR_CONTROL
  825. let mediaPlayerElementWR = null;
  826. let focusedElementAtSelection = null;
  827.  
  828. // let want_control_video = false;
  829.  
  830. let spaceBarControl_keyG = '';
  831.  
  832. let lastUserAction = 0;
  833.  
  834. const wmKeyControlPhase = new WeakMap();
  835.  
  836. let currentSelectionText = null;
  837.  
  838. const getCurrentSelectionText = () => {
  839. if (currentSelectionText !== null) return currentSelectionText
  840. return (currentSelectionText = getSelection() + "")
  841. }
  842.  
  843. const pageMediaWatcher = () => {
  844.  
  845. // CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE && document.addEventListener('wheel', () => {
  846. // want_control_video = false;
  847. // }, { capture: true, passive: true });
  848.  
  849. document.addEventListener('yt-navigate', () => {
  850. ytPageReady = 0;
  851. });
  852. document.addEventListener('yt-navigate-start', () => {
  853. ytPageReady = 0;
  854. });
  855. document.addEventListener('yt-navigate-cache', () => {
  856. ytPageReady = 0;
  857. });
  858.  
  859. document.addEventListener('yt-navigate-finish', () => {
  860. ytPageReady = 1;
  861. });
  862.  
  863. document.addEventListener('durationchange', () => {
  864. for (const elm of document.querySelectorAll('#movie_player video[src], #movie_player audio[src]')) {
  865. if (elm.duration > 0.01) {
  866. if (elm.closest('[hidden]')) continue;
  867. mediaPlayerElementWR = mWeakRef(elm);
  868. return;
  869. }
  870. }
  871. }, { capture: true, passive: true });
  872.  
  873. document.addEventListener('selectionchange', (evt) => {
  874. if (!evt || !evt.isTrusted || !(evt instanceof Event)) return;
  875. currentSelectionText = null;
  876. if (!(evt.target instanceof Node)) return;
  877. focusedElementAtSelection = evt.target;
  878. }, { capture: true, passive: true })
  879.  
  880. document.addEventListener('pointerdown', (evt) => {
  881. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  882. }, { capture: true, passive: true });
  883.  
  884.  
  885. document.addEventListener('pointerup', (evt) => {
  886. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  887. }, { capture: true, passive: true });
  888.  
  889.  
  890. document.addEventListener('keydown', (evt) => {
  891. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  892. }, { capture: true, passive: true });
  893.  
  894. document.addEventListener('keyup', (evt) => {
  895. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  896. }, { capture: true, passive: true });
  897.  
  898. };
  899.  
  900.  
  901. const checkKeyB = (p_a_obj) => {
  902.  
  903. const boolList = new Set();
  904. const p_a_obj_api = p_a_obj.api;
  905.  
  906. const nilFunc0 = function () {
  907. return void 0
  908. };
  909. const mt = new Proxy({}, {
  910. get(target, prop) {
  911. if (prop === 'get') return nilFunc0;
  912. return mt;
  913. }
  914. });
  915. const nilFunc = function () {
  916. return mt
  917. };
  918. const mw = new Proxy({}, {
  919. get(target, prop) {
  920. if (prop in p_a_obj_api) {
  921. if (typeof p_a_obj_api.constructor.prototype[prop] === 'function') return nilFunc;
  922. let q = Object.getOwnPropertyDescriptor(p_a_obj_api, prop);
  923. if (q && q.value) {
  924. if (!q.writable) return q.value;
  925. if (typeof q.value === 'string') return '';
  926. if (typeof q.value === 'number') return 0;
  927. if (typeof q.value === 'boolean') return false;
  928. if (q.value && typeof q.value === 'object') return {};
  929. }
  930. }
  931. return undefined;
  932. },
  933. set(target, prop) {
  934. throw 'mwSet';
  935. }
  936. });
  937.  
  938. const mq = new Proxy({}, {
  939. get(target, prop) {
  940. if (prop === 'api') return mw;
  941. if (prop in p_a_obj) {
  942. if (typeof p_a_obj.constructor.prototype[prop] === 'function') return nilFunc;
  943. let q = Object.getOwnPropertyDescriptor(p_a_obj, prop);
  944. if (q && q.value) {
  945. if (!q.writable) return q.value;
  946. if (typeof q.value === 'string') return '';
  947. if (typeof q.value === 'number') return 0;
  948. if (typeof q.value === 'boolean') return false;
  949. if (q.value && typeof q.value === 'object') return {};
  950. }
  951. }
  952. return undefined;
  953. },
  954. set(target, prop, val) {
  955. if (typeof val === 'boolean') boolList.add(prop)
  956. throw `mqSet(${prop},${val})`;
  957. }
  958. });
  959.  
  960. let res = ''
  961. try {
  962. res = `RESULT::${p_a_obj.handleGlobalKeyUp.call(mq, 9, false, false, false, false, "Tab", "Tab")}`;
  963. } catch (e) {
  964. res = `ERROR::${e}`;
  965. }
  966.  
  967. if (boolList.size === 1) {
  968. const value = boolList.values().next().value;
  969. if (res === `ERROR::mqSet(${value},${true})`) {
  970. p_a_obj.__uZWaD__ = value;
  971. }
  972. }
  973.  
  974. console.log('[yt-js-engine-tamer] global shortcut control', { '__uZWaD__': p_a_obj.__uZWaD__ });
  975.  
  976. }
  977.  
  978.  
  979. let pm_p_a = null;
  980.  
  981. const p_a_init = function () {
  982. const r = this.init91();
  983. const keyBw = this.__cPzfo__ || '__NIL__';
  984. const p_a_obj = this[keyBw];
  985. if (!p_a_obj) return;
  986. try {
  987. checkKeyB(p_a_obj);
  988. } catch (e) { }
  989. p_a_objWR = mWeakRef(p_a_obj);
  990. if (FIX_SHORTCUTKEYS > 0) {
  991. if (p_a_obj && !p_a_obj.hVhtg) {
  992. p_a_obj.hVhtg = 1;
  993. p_a_obj.handleGlobalKeyUp91 = p_a_obj.handleGlobalKeyUp;
  994. p_a_obj.handleGlobalKeyUp = p_a_xt.handleGlobalKeyUp;
  995. p_a_obj.handleGlobalKeyDown91 = p_a_obj.handleGlobalKeyDown;
  996. p_a_obj.handleGlobalKeyDown = p_a_xt.handleGlobalKeyDown;
  997. p_a_obj.__handleGlobalKeyBefore__ = p_a_xt.__handleGlobalKeyBefore__;
  998. p_a_obj.__handleGlobalKeyAfter__ = p_a_xt.__handleGlobalKeyAfter__;
  999. }
  1000. // if (CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE && p_a_obj && p_a_obj.api && !p_a_obj.api.hVhtg) {
  1001. // const api = p_a_obj.api
  1002. // api.hVhtg = 1;
  1003. // api.playVideo91 = api.playVideo;
  1004. // api.playVideo = p_a_jt.playVideo;
  1005. // api.pauseVideo91 = api.pauseVideo;
  1006. // api.pauseVideo = p_a_jt.pauseVideo;
  1007. // }
  1008. }
  1009. if (pm_p_a) {
  1010. pm_p_a.resolve();
  1011. pm_p_a = null;
  1012. }
  1013. return r;
  1014. };
  1015.  
  1016. const p_a_xt = {
  1017.  
  1018. __handleGlobalKeyBefore__(a, b, c, d, e, f, h, activeElement) {
  1019.  
  1020. if (FIX_SHORTCUTKEYS === 2) {
  1021.  
  1022. if (activeElement) {
  1023.  
  1024. const controlPhaseCache = wmKeyControlPhase.get(activeElement);
  1025.  
  1026. if (controlPhaseCache === 6 && getCurrentSelectionText() !== "") void 0;
  1027. else if (controlPhaseCache === 1 || controlPhaseCache === 2 || controlPhaseCache === 5) return false;
  1028. else if ((controlPhaseCache !== 6 || focusedElementAtSelection === document.activeElement) && getCurrentSelectionText() !== "") return false;
  1029.  
  1030. }
  1031.  
  1032. const isSpaceBar = a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space';
  1033. const isDelayedSpaceBar = FIX_SHORTCUTKEYS === 2 && isSpaceBar && !isSpaceKeyImmediate && isSpeedMastSpacebarControlEnabled;
  1034. // console.log(582, isDelayedSpaceBar)
  1035. if (isDelayedSpaceBar) return void 0; // accept delay spacebar under isSpeedMastSpacebarControlEnabled (no rejection)
  1036.  
  1037. if (activeElement && (h === 'Space' || h === 'Enter')) {
  1038. const controlPhase = wmKeyControlPhase.get(activeElement);
  1039. if (controlPhase === 4 || controlPhase === 5) return false;
  1040. }
  1041. if (focusedElementAtSelection === activeElement && getCurrentSelectionText() !== "") return false;
  1042. // if (!isSpeedMastSpacebarControlEnabled && a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space') {
  1043. // if (!isSpaceKeyImmediate) return false;
  1044. // }
  1045. }
  1046.  
  1047. },
  1048.  
  1049. __handleGlobalKeyAfter__(a, b, c, d, e, f, h, activeElement, ret) {
  1050.  
  1051.  
  1052. if (FIX_SHORTCUTKEYS === 2 && ret && a >= 32 && ytPageReady === 1 && Date.now() - lastUserAction < 40 && activeElement === document.activeElement) {
  1053.  
  1054. const isSpaceBar = a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space';
  1055. const isDelayedSpaceBar = FIX_SHORTCUTKEYS === 2 && isSpaceBar && !isSpaceKeyImmediate && isSpeedMastSpacebarControlEnabled;
  1056. // console.log(583, isDelayedSpaceBar)
  1057. if (isDelayedSpaceBar) return void 0; // accept delay spacebar under isSpeedMastSpacebarControlEnabled (no rejection)
  1058.  
  1059. const mediaPlayerElement = kRef(mediaPlayerElementWR);
  1060.  
  1061. let mediaWorking = false;
  1062. if (mediaPlayerElement && (mediaPlayerElement.readyState === 4 || mediaPlayerElement.readyState === 1) && mediaPlayerElement.networkState === 2 && mediaPlayerElement.duration > 0.01) {
  1063. mediaWorking = true;
  1064. } else if (mediaPlayerElement && !mediaPlayerElement.paused && !mediaPlayerElement.muted && mediaPlayerElement.duration > 0.01) {
  1065. mediaWorking = true;
  1066. }
  1067. // console.log(182, mediaWorking, mediaPlayerElement.readyState , mediaPlayerElement.networkState)
  1068. mediaWorking && Promise.resolve().then(() => {
  1069. if (activeElement === document.activeElement) {
  1070. return activeElement.blur()
  1071. } else {
  1072. return false
  1073. }
  1074. }).then((r) => {
  1075. r !== false && mediaPlayerElement.focus();
  1076. });
  1077. }
  1078. },
  1079.  
  1080.  
  1081. handleGlobalKeyUp(a, b, c, d, e, f, h) {
  1082.  
  1083. const activeElement = document.activeElement;
  1084.  
  1085. const allow = typeof this.__handleGlobalKeyBefore__ === 'function' ? this.__handleGlobalKeyBefore__(a, b, c, d, e, f, h, activeElement) : void 0;
  1086. if (allow === false) return false;
  1087.  
  1088. const ret = this.handleGlobalKeyUp91(a, b, c, d, e, f, h);
  1089. // console.log('handleGlobalKeyUp',ret, a, b, c, d, e, f, h);
  1090.  
  1091. typeof this.__handleGlobalKeyAfter__ === 'function' && this.__handleGlobalKeyAfter__(a, b, c, d, e, f, h, activeElement, ret);
  1092.  
  1093. return ret;
  1094. },
  1095. handleGlobalKeyDown(a, b, c, d, e, f, h, l) {
  1096.  
  1097. const activeElement = document.activeElement;
  1098. if (!isSpeedMastSpacebarControlEnabled && a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space') {
  1099. return false;
  1100. }
  1101. const allow = typeof this.__handleGlobalKeyBefore__ === 'function' ? this.__handleGlobalKeyBefore__(a, b, c, d, e, f, h, activeElement) : void 0;
  1102. if (allow === false) return false;
  1103.  
  1104. const ret = this.handleGlobalKeyDown91(a, b, c, d, e, f, h, l);
  1105. // console.log('handleGlobalKeyDown',ret, a, b, c, d, e, f, h,l)
  1106.  
  1107. typeof this.__handleGlobalKeyAfter__ === 'function' && this.__handleGlobalKeyAfter__(a, b, c, d, e, f, h, activeElement, ret);
  1108.  
  1109. return ret;
  1110. }
  1111.  
  1112. };
  1113.  
  1114. // const p_a_jt = { // API
  1115.  
  1116. // playVideo(a) { // without spinner effect
  1117.  
  1118. // if (CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE) {
  1119.  
  1120. // const mediaPlayerElement = kRef(mediaPlayerElementWR);
  1121. // if (mediaPlayerElement && !mediaPlayerElement.paused && !mediaPlayerElement.muted && mediaPlayerElement.duration > 0.01) {
  1122. // want_control_video = true;
  1123. // // Promise.resolve().then(()=> mediaPlayerElement.focus() );
  1124. // }
  1125.  
  1126. // }
  1127. // return this.playVideo91(a);
  1128.  
  1129. // },
  1130.  
  1131. // pauseVideo(a) { // without spinner effect
  1132.  
  1133. // if (CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE) {
  1134.  
  1135. // const mediaPlayerElement = kRef(mediaPlayerElementWR);
  1136. // if (mediaPlayerElement && mediaPlayerElement.paused && !mediaPlayerElement.muted && mediaPlayerElement.duration > 0.01) {
  1137. // want_control_video = true;
  1138. // // Promise.resolve().then(()=> mediaPlayerElement.focus() );
  1139. // }
  1140.  
  1141. // }
  1142. // return this.pauseVideo91(a);
  1143.  
  1144. // }
  1145. // };
  1146.  
  1147.  
  1148. const keyboardController = async (_yt_player) => {
  1149.  
  1150. const keyQT = getQT(_yt_player);
  1151. const keySV = getSV(_yt_player);
  1152. const keyDX = getDX(_yt_player);
  1153. console.log(`[QT,SV,DX]`, [keyQT, keySV, keyDX]);
  1154.  
  1155. if (!keyDX) return;
  1156. if (keyDX === keyQT || keyDX === keySV) return;
  1157.  
  1158. if (typeof keyDX !== 'string') return;
  1159.  
  1160. let lastAccessKey = '';
  1161. let lastAccessKeyConfirmed = '';
  1162. const mb = new Proxy({}, {
  1163. get(target, prop) {
  1164. if (prop === 'handleGlobalKeyUp') lastAccessKeyConfirmed = lastAccessKey;
  1165. throw 'mbGet'
  1166. },
  1167. set(target, prop, val) {
  1168. throw 'mbSet'
  1169. }
  1170. });
  1171. const ma = new Proxy({}, {
  1172. get(target, prop) {
  1173. lastAccessKey = prop;
  1174. return mb
  1175. },
  1176. set(target, prop, val) {
  1177. throw 'maSet'
  1178. }
  1179. });
  1180.  
  1181. let keyBw = '';
  1182. try {
  1183. _yt_player[keyDX].prototype.handleGlobalKeyUp.call(ma);
  1184. } catch (e) {
  1185. if (e === 'mbGet' && typeof lastAccessKeyConfirmed === 'string' && lastAccessKeyConfirmed.length > 0) {
  1186. keyBw = lastAccessKeyConfirmed;
  1187. }
  1188. }
  1189.  
  1190. if (!keyBw) return;
  1191.  
  1192. if (typeof _yt_player[keyDX].prototype.init !== 'function' || _yt_player[keyDX].prototype.init.length !== 0) return;
  1193.  
  1194. pm_p_a = new PromiseExternal();
  1195.  
  1196. _yt_player[keyDX].prototype.__cPzfo__ = keyBw;
  1197.  
  1198. _yt_player[keyDX].prototype.init91 = _yt_player[keyDX].prototype.init;
  1199.  
  1200. _yt_player[keyDX].prototype.init = p_a_init;
  1201.  
  1202. await pm_p_a.then();
  1203. const p_a_obj = kRef(p_a_objWR);
  1204.  
  1205. const config = (win.yt || 0).config_ || (win.ytcfg || 0).data_ || 0;
  1206. if (config && config.EXPERIMENT_FLAGS && config.EXPERIMENT_FLAGS.web_speedmaster_spacebar_control) {
  1207. isSpeedMastSpacebarControlEnabled = true;
  1208. }
  1209. if (config && config.EXPERIMENTS_FORCED_FLAGS && config.EXPERIMENTS_FORCED_FLAGS.web_speedmaster_spacebar_control) {
  1210. isSpeedMastSpacebarControlEnabled = true;
  1211. }
  1212.  
  1213. const isSpeedMastSpacebarControlEnabledA = isSpeedMastSpacebarControlEnabled;
  1214.  
  1215. if (CHANGE_SPEEDMASTER_SPACEBAR_CONTROL > 0) {
  1216.  
  1217. isSpeedMastSpacebarControlEnabled = CHANGE_SPEEDMASTER_SPACEBAR_CONTROL == 1;
  1218.  
  1219. if (!isSpeedMastSpacebarControlEnabled) {
  1220.  
  1221. if (config && config.EXPERIMENT_FLAGS) {
  1222. config.EXPERIMENT_FLAGS.web_speedmaster_spacebar_control = false;
  1223. }
  1224. if (config && config.EXPERIMENTS_FORCED_FLAGS) {
  1225. config.EXPERIMENTS_FORCED_FLAGS.web_speedmaster_spacebar_control = false;
  1226. }
  1227.  
  1228. } else {
  1229.  
  1230. if (config && config.EXPERIMENT_FLAGS) {
  1231. config.EXPERIMENT_FLAGS.web_speedmaster_spacebar_control = true;
  1232. }
  1233. if (config && config.EXPERIMENTS_FORCED_FLAGS) {
  1234. config.EXPERIMENTS_FORCED_FLAGS.web_speedmaster_spacebar_control = true;
  1235. }
  1236.  
  1237. }
  1238.  
  1239. }
  1240.  
  1241. const isSpeedMastSpacebarControlEnabledB = isSpeedMastSpacebarControlEnabled;
  1242.  
  1243. console.log('[yt-js-engine-tamer] speedmaster by space (yt setting)', isSpeedMastSpacebarControlEnabledA, isSpeedMastSpacebarControlEnabledB);
  1244.  
  1245. // console.log(p_a_obj.handleGlobalKeyUp)
  1246. console.log('[yt-js-engine-tamer] p_a', p_a_obj)
  1247.  
  1248. // console.log(p_a_obj.api)
  1249.  
  1250.  
  1251. // QT -> DX(SV) -> p_a
  1252.  
  1253.  
  1254. /*
  1255. *
  1256. *
  1257. g.k.handleGlobalKeyUp = function(a, b, c, d, e, f, h) {
  1258. b = void 0 === b ? !1 : b;
  1259. c = void 0 === c ? !1 : c;
  1260. d = void 0 === d ? !1 : d;
  1261. e = void 0 === e ? !1 : e;
  1262. var l = g.PT(this);
  1263. l && l.handleGlobalKeyUp(a, b, c, d, e, f, h)
  1264. }
  1265.  
  1266. */
  1267.  
  1268. /*
  1269. *
  1270. *
  1271. *
  1272. g.k.handleGlobalKeyUp = function(a, b, c, d, e, f, h) {
  1273. return this.Bw ? this.Bw.handleGlobalKeyUp(a, b, c, d, e, f, h) : !1
  1274. }
  1275.  
  1276. */
  1277.  
  1278.  
  1279. // if(!keyDX) return;
  1280.  
  1281. // console.log(4999, keyDX)
  1282.  
  1283. };
  1284.  
  1285.  
  1286. const ytResumeFn = function () { // ADVANCED_FIX_SHORTCUTKEYS
  1287.  
  1288. const p_a_obj = kRef(p_a_objWR);
  1289. // const api = p_a_obj.api;
  1290.  
  1291.  
  1292. // console.log(540);
  1293.  
  1294. let boolList = null;
  1295. let ret;
  1296. isSpaceKeyImmediate = true;
  1297. try {
  1298.  
  1299. ret = 0;
  1300. ret = ret | (p_a_obj.handleGlobalKeyDown(32, false, false, false, false, ' ', 'Space', false) ? 1 : 0);
  1301. let p_a_objT;
  1302. if (!spaceBarControl_keyG) { // just in case
  1303. boolList = new Set();
  1304. p_a_objT = new Proxy(p_a_obj, {
  1305. get(target, prop, handler) {
  1306. const val = target[prop];
  1307. if (typeof val !== 'boolean') return val;
  1308. boolList.add(prop);
  1309. // console.log(555, prop, val);
  1310. if (typeof prop === 'string' && prop.length <= 3 && val === true && boolList.length === 1) {
  1311. spaceBarControl_keyG = prop;
  1312. p_a_obj.__uZWaD__ = spaceBarControl_keyG;
  1313. val = false;
  1314. }
  1315. return val;
  1316. }
  1317. });
  1318.  
  1319.  
  1320. } else if (p_a_obj[spaceBarControl_keyG] === true) {
  1321. p_a_obj[spaceBarControl_keyG] = false;
  1322. p_a_objT = p_a_obj;
  1323. // console.log(p_a_obj, spaceBarControl_keyG, p_a_obj[spaceBarControl_keyG] )
  1324. } else {
  1325.  
  1326. p_a_objT = p_a_obj;
  1327. }
  1328.  
  1329. ret = ret | (p_a_objT.handleGlobalKeyUp(32, false, false, false, false, ' ', 'Space') ? 2 : 0);
  1330.  
  1331.  
  1332. } catch (e) {
  1333. console.log(e)
  1334. }
  1335. isSpaceKeyImmediate = false;
  1336.  
  1337. if (boolList && boolList.size === 1) {
  1338. const value = boolList.values().next().value;
  1339. spaceBarControl_keyG = value;
  1340. p_a_obj.__uZWaD__ = spaceBarControl_keyG;
  1341.  
  1342. }
  1343.  
  1344. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  1345.  
  1346. return ret;
  1347. }
  1348.  
  1349. const shortcutKeysFixer = () => {
  1350.  
  1351. let pausePromiseControlJ = 0;
  1352.  
  1353.  
  1354. const obtainCurrentControlPhase = (evt, mediaPlayerElement) => {
  1355.  
  1356. let controlPhase = 0;
  1357. const aElm = document.activeElement;
  1358.  
  1359. if (aElm) {
  1360.  
  1361. const controlPhaseCache = wmKeyControlPhase.get(aElm);
  1362.  
  1363. if (typeof controlPhaseCache === 'number') {
  1364.  
  1365. controlPhase = controlPhaseCache;
  1366. } else {
  1367.  
  1368. if (aElm instanceof HTMLInputElement) controlPhase = 1;
  1369. else if (aElm instanceof HTMLTextAreaElement) controlPhase = 1;
  1370. else if (aElm instanceof HTMLButtonElement) controlPhase = 2;
  1371. else if (aElm instanceof HTMLIFrameElement) controlPhase = 2;
  1372. else if (aElm instanceof HTMLImageElement) controlPhase = 2;
  1373. else if (aElm instanceof HTMLEmbedElement) controlPhase = 2;
  1374. else {
  1375. if (aElm instanceof HTMLElement && aElm.closest('[role]')) controlPhase = 5;
  1376. if (aElm instanceof HTMLDivElement) controlPhase = 2;
  1377. else if (aElm instanceof HTMLAnchorElement) controlPhase = 2;
  1378. else if (!(aElm instanceof HTMLElement) && (aElm instanceof Element)) controlPhase = 2; // svg
  1379. }
  1380.  
  1381. if ((controlPhase === 2 || controlPhase === 5) && (aElm instanceof HTMLElement) && aElm.contains(mediaPlayerElement)) {
  1382. controlPhase = 0;
  1383. }
  1384.  
  1385. if ((controlPhase === 2 || controlPhase === 5) && evt && evt.target && evt.target === aElm) {
  1386. if (aElm.closest('[contenteditable], input, textarea')) {
  1387. controlPhase = 5;
  1388. } else if (aElm.closest('button')) {
  1389. controlPhase = 4;
  1390. }
  1391. }
  1392.  
  1393. if (aElm.closest('#movie_player')) controlPhase = 6;
  1394.  
  1395. wmKeyControlPhase.set(aElm, controlPhase);
  1396.  
  1397. }
  1398. }
  1399.  
  1400. return controlPhase;
  1401.  
  1402. }
  1403.  
  1404. const isStateControllable = (api) => {
  1405. let appState = null;
  1406. let playerState = null;
  1407. let adState = null;
  1408. try {
  1409. appState = api.getAppState();
  1410. playerState = api.getPlayerState();
  1411. adState = api.getAdState();
  1412. } catch (e) { }
  1413. // ignore playerState -1
  1414. return appState === 5 && adState === -1 && (playerState === 1 || playerState === 2 || playerState === 3);
  1415. };
  1416.  
  1417.  
  1418. const keyEventListener = (evt) => {
  1419.  
  1420. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  1421. if (isSpaceKeyImmediate || !evt.isTrusted || !(evt instanceof KeyboardEvent)) return;
  1422. if (!ytPageReady) return;
  1423.  
  1424. if (evt.defaultPrevented === true) return;
  1425.  
  1426. const p_a_obj = kRef(p_a_objWR);
  1427.  
  1428. if (!p_a_obj) return;
  1429.  
  1430. const mediaPlayerElement = kRef(mediaPlayerElementWR);
  1431. if (!mediaPlayerElement) return;
  1432.  
  1433. // let focusBodyIfSuccess = false;
  1434.  
  1435. const controlPhase = obtainCurrentControlPhase(evt, mediaPlayerElement);
  1436.  
  1437. if (controlPhase === 6 && getCurrentSelectionText() !== "") void 0;
  1438. else if (controlPhase === 1 || controlPhase === 2 || controlPhase === 5) return;
  1439. else if ((controlPhase !== 6 || focusedElementAtSelection === document.activeElement) && getCurrentSelectionText() !== "") return;
  1440.  
  1441.  
  1442. // console.log(`${evt.type}::controlPhase`,controlPhase)
  1443.  
  1444. // if (controlPhase == 4) {
  1445. // focusBodyIfSuccess = true;
  1446. // }
  1447.  
  1448. spaceBarControl_keyG = spaceBarControl_keyG || p_a_obj.__uZWaD__ || ''
  1449. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  1450.  
  1451. if (FIX_SHORTCUTKEYS < 2) return;
  1452. if (!(!evt.shiftKey && !evt.ctrlKey && !evt.altKey && !evt.metaKey)) return; // ignore if modifier key is pressed -> let other event listener to handle first
  1453.  
  1454. let rr;
  1455. const isSpaceBar = evt.code === 'Space' && !evt.shiftKey && !evt.ctrlKey && !evt.altKey && !evt.metaKey;
  1456.  
  1457.  
  1458.  
  1459. let useImprovedPauseResume = false;
  1460.  
  1461. if (USE_IMPROVED_PAUSERESUME_UNDER_NO_SPEEDMASTER && isSpaceBar && !isSpeedMastSpacebarControlEnabled) {
  1462.  
  1463. const api = p_a_obj.api;
  1464. const stateControllable = isStateControllable(api);
  1465. // console.log(2122, appState, playerState, adState)
  1466.  
  1467. if (stateControllable && location.pathname === '/watch' && mediaPlayerElement.duration > 0.01 && (mediaPlayerElement.readyState === 4 || mediaPlayerElement.readyState === 1) && mediaPlayerElement.networkState === 2) {
  1468.  
  1469. useImprovedPauseResume = true;
  1470.  
  1471. }
  1472.  
  1473.  
  1474. }
  1475.  
  1476.  
  1477. // force flag: CHANGE_SPEEDMASTER_SPACEBAR_CONTROL
  1478. if (evt.type === 'keydown') {
  1479.  
  1480. if (useImprovedPauseResume) {
  1481.  
  1482. const isPaused = mediaPlayerElement.paused;
  1483.  
  1484. const cj = ++pausePromiseControlJ;
  1485. Promise.resolve().then(() => {
  1486.  
  1487. if (cj !== pausePromiseControlJ) return;
  1488.  
  1489. if (mediaPlayerElement.paused !== isPaused) return;
  1490.  
  1491. const ret = ytResumeFn();
  1492. if (!ret) { // fallback
  1493. isPaused ? api.playVideo() : api.pauseVideo();
  1494. }
  1495.  
  1496. /*
  1497. let a = void 0;
  1498. console.log('Rb', api.Rb())
  1499. a = !window._yt_player.nL(api.Rb());
  1500. p_a_obj.Wd.kG(a)
  1501. a ? api.playVideo() : api.pauseVideo();
  1502.  
  1503. */
  1504.  
  1505.  
  1506. });
  1507. rr = true;
  1508. } else {
  1509.  
  1510. isSpaceKeyImmediate = true;
  1511. rr = p_a_obj.handleGlobalKeyDown(evt.keyCode, evt.shiftKey, evt.ctrlKey, evt.altKey, evt.metaKey, evt.key, evt.code, evt.repeat);
  1512. isSpaceKeyImmediate = false;
  1513. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  1514.  
  1515. }
  1516.  
  1517.  
  1518. } else if (evt.type === 'keyup') {
  1519.  
  1520. if (isSpaceBar && useImprovedPauseResume && !isSpeedMastSpacebarControlEnabled) {
  1521.  
  1522. rr = true;
  1523. } else {
  1524.  
  1525. isSpaceKeyImmediate = true;
  1526. rr = p_a_obj.handleGlobalKeyUp(evt.keyCode, evt.shiftKey, evt.ctrlKey, evt.altKey, evt.metaKey, evt.key, evt.code);
  1527. isSpaceKeyImmediate = false;
  1528. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  1529.  
  1530. }
  1531.  
  1532.  
  1533. /*
  1534.  
  1535. if (d)
  1536. switch (c) {
  1537. case 32:
  1538. case 13:
  1539. if ("BUTTON" === d.tagName || "A" === d.tagName || "INPUT" === d.tagName)
  1540. b = !0,
  1541. e = !1;
  1542. else if (e) {
  1543. var m = d.getAttribute("role");
  1544. !m || "option" !== m && "button" !== m && 0 !== m.indexOf("menuitem") || (b = !0,
  1545. d.click(),
  1546. f = !0)
  1547. }
  1548. break;
  1549. case 37:
  1550. case 39:
  1551. case 36:
  1552. case 35:
  1553. b = "slider" === d.getAttribute("role");
  1554. break;
  1555. case 38:
  1556. case 40:
  1557. m = d.getAttribute("role"),
  1558. d = 38 === c ? d.previousSibling : d.nextSibling,
  1559. "slider" === m ? b = !0 : e && ("option" === m ? (d && "option" === d.getAttribute("role") && d.focus(),
  1560. f = b = !0) : m && 0 === m.indexOf("menuitem") && (d && d.hasAttribute("role") && 0 === d.getAttribute("role").indexOf("menuitem") && d.focus(),
  1561. f = b = !0))
  1562. }
  1563. if (e && !f)
  1564. switch (c) {
  1565. case 38:
  1566. f = Math.min(this.api.getVolume() + 5, 100);
  1567. XV(this.Wd, f, !1);
  1568. this.api.setVolume(f);
  1569. h = f = !0;
  1570. break;
  1571. case 40:
  1572. f = Math.max(this.api.getVolume() - 5, 0);
  1573. XV(this.Wd, f, !0);
  1574. this.api.setVolume(f);
  1575. h = f = !0;
  1576. break;
  1577. case 36:
  1578. this.api.Yh() && (this.api.startSeekCsiAction(),
  1579. this.api.seekTo(0, void 0, void 0, void 0, 79),
  1580. h = f = !0);
  1581. break;
  1582. case 35:
  1583. this.api.Yh() && (this.api.startSeekCsiAction(),
  1584. this.api.seekTo(Infinity, void 0, void 0, void 0, 80),
  1585. h = f = !0)
  1586. }
  1587. */
  1588.  
  1589. }
  1590.  
  1591.  
  1592. if (rr) {
  1593.  
  1594. // focusBodyIfSuccess && Promise.resolve().then(() => {
  1595. // activeElement === document.activeElement && activeElement.blur();
  1596. // });
  1597.  
  1598. evt.preventDefault();
  1599. evt.stopImmediatePropagation();
  1600. evt.stopPropagation();
  1601.  
  1602. }
  1603.  
  1604. };
  1605.  
  1606. document.addEventListener('keydown', keyEventListener, { capture: true });
  1607.  
  1608.  
  1609. document.addEventListener('keyup', keyEventListener, { capture: true });
  1610.  
  1611. }
  1612.  
  1613. return { pageMediaWatcher, shortcutKeysFixer, keyboardController };
  1614.  
  1615. })();
  1616.  
  1617.  
  1618. pageMediaWatcher();
  1619. FIX_SHORTCUTKEYS > 0 && shortcutKeysFixer();
  1620.  
  1621.  
  1622. const check_for_set_key_order = (() => {
  1623.  
  1624. let mySet = new Set();
  1625.  
  1626. mySet.add("value1");
  1627. mySet.add("value2");
  1628. mySet.add("value3");
  1629.  
  1630. // Function to convert Set values to an array
  1631. function getSetValues(set) {
  1632. return Array.from(set.values());
  1633. }
  1634.  
  1635. // Function to test if the Set maintains insertion order
  1636. function testSetOrder(set, expectedOrder) {
  1637. let values = getSetValues(set);
  1638. return expectedOrder.join(',') === values.join(',');
  1639. }
  1640.  
  1641. // Test 1: Initial order
  1642. if (mySet.values().next().value !== "value1") return false;
  1643. if (!testSetOrder(mySet, ["value1", "value2", "value3"])) return false;
  1644.  
  1645. // Test 2: After deleting an element
  1646. mySet.delete("value2");
  1647. if (mySet.values().next().value !== "value1") return false;
  1648. if (!testSetOrder(mySet, ["value1", "value3"])) return false;
  1649.  
  1650. // Test 3: After re-adding a deleted element
  1651. mySet.add("value2");
  1652. if (mySet.values().next().value !== "value1") return false;
  1653. if (!testSetOrder(mySet, ["value1", "value3", "value2"])) return false;
  1654.  
  1655. // Test 4: After adding a new element
  1656. mySet.add("value4");
  1657. if (mySet.values().next().value !== "value1") return false;
  1658. if (!testSetOrder(mySet, ["value1", "value3", "value2", "value4"])) return false;
  1659.  
  1660. // Test 5: Delete+Add
  1661. mySet.delete("value1");
  1662. mySet.delete("value3");
  1663. mySet.add("value3");
  1664. mySet.add("value1");
  1665. if (mySet.values().next().value !== "value2") return false;
  1666. if (!testSetOrder(mySet, ["value2", "value4", "value3", "value1"])) return false;
  1667.  
  1668. return true;
  1669. })();
  1670.  
  1671.  
  1672. // const qm47 = Symbol();
  1673. const qm57 = Symbol();
  1674. const qm53 = Symbol();
  1675. const qn53 = Symbol();
  1676.  
  1677.  
  1678. const ump3 = new WeakMap();
  1679.  
  1680. const stp = document.createElement('noscript');
  1681. stp.id = 'weakref-placeholder'
  1682.  
  1683.  
  1684. const setupD = typeof WeakRef !== 'undefined' ? (elm, s, usePlaceholder) => {
  1685.  
  1686. const z = `${s}72`;
  1687.  
  1688. if (s in elm) {
  1689.  
  1690. const p = elm[s];
  1691.  
  1692. delete elm[s];
  1693.  
  1694. Object.defineProperty(elm, s, {
  1695. get() {
  1696. const elm = this;
  1697. const wr = elm[z];
  1698. if (!wr) return null;
  1699. const m = kRef(wr);
  1700. if (!m && usePlaceholder) {
  1701. if (typeof usePlaceholder === 'function') usePlaceholder(elm);
  1702. return stp;
  1703. }
  1704. return m;
  1705. },
  1706. set(nv) {
  1707. const elm = this;
  1708. elm[z] = nv ? mWeakRef(nv) : null;
  1709. return true;
  1710. },
  1711. configurable: true,
  1712. enumerable: true
  1713.  
  1714. });
  1715.  
  1716. elm[s] = p;
  1717. elm = null;
  1718.  
  1719.  
  1720. }
  1721. } : null;
  1722.  
  1723. const mxMap = new WeakMap();
  1724.  
  1725. const myMap = new WeakSet();
  1726.  
  1727. const setup$ = typeof WeakRef !== 'undefined' ? function (dh) {
  1728.  
  1729. const $ = dh.$;
  1730.  
  1731. if (WEAK_REF_PROXY_DOLLAR && $ && typeof $ === 'object' && !dh.$ky37) {
  1732.  
  1733. dh.$ky37 = 1;
  1734.  
  1735. if (!myMap.has($)) {
  1736.  
  1737. for (const [k, v] of Object.entries($)) {
  1738. if (v instanceof Node) {
  1739. $[k] = mWeakRef(v);
  1740. }
  1741. }
  1742.  
  1743. dh.$ = mxMap.get($) || new Proxy($, {
  1744. get(obj, prop) {
  1745. const val = obj[prop];
  1746. if (typeof (val || 0).deref === 'function') {
  1747. return val.deref();
  1748. }
  1749. return val;
  1750. },
  1751. set(obj, prop, val) {
  1752. if (val instanceof Node) {
  1753. obj[prop] = mWeakRef(val);
  1754. } else {
  1755. obj[prop] = val;
  1756. }
  1757. return true;
  1758. }
  1759. });
  1760.  
  1761. mxMap.set($, dh.$);
  1762. myMap.add(dh.$);
  1763.  
  1764. }
  1765.  
  1766. }
  1767.  
  1768. } : null;
  1769.  
  1770.  
  1771. const configureVisibilityObserverT_ = function () {
  1772. const hostElement = this.hostElement;
  1773. if (!(hostElement instanceof Node) || hostElement.nodeName === 'NOSCRIPT') {
  1774. this.unobserve_();
  1775. } else {
  1776. return this.configureVisibilityObserver27_();
  1777. }
  1778. };
  1779. const getParentRendererT = function () {
  1780. const hostElement = this.hostElement;
  1781. if (!(hostElement instanceof Node) || hostElement.nodeName === 'NOSCRIPT') {
  1782. return null;
  1783. } else {
  1784. return this.getParentRenderer27();
  1785. }
  1786. }
  1787.  
  1788. const attachedT = function () {
  1789. const hostElement = this.hostElement;
  1790. if (!(hostElement instanceof Node) || hostElement.nodeName === 'NOSCRIPT') {
  1791. if (this.isAttached === true) this.isAttached = false;
  1792. return void 0;
  1793. } else {
  1794. return this.attached27();
  1795. }
  1796. }
  1797.  
  1798. const hostElementCleanUp = (dh) => {
  1799. if (typeof dh.dispose === 'function') {
  1800. try {
  1801. if (dh.visibilityMonitor || dh.visibilityObserver) {
  1802. dh.dispose();
  1803. dh.visibilityMonitor = null;
  1804. dh.visibilityObserver = null;
  1805. }
  1806. } catch (e) { }
  1807. }
  1808. if (typeof dh.detached === 'function') {
  1809. try {
  1810. if (dh.visibilityObserverForChild_ || dh.localVisibilityObserver_) {
  1811. dh.detached();
  1812. dh.visibilityObserverForChild_ = null;
  1813. dh.localVisibilityObserver_ = null;
  1814. }
  1815. } catch (e) { }
  1816. }
  1817. };
  1818. const setupDataHost = setupD && setup$ ? function (dh, opt) {
  1819.  
  1820. if (dh && typeof dh === 'object') {
  1821.  
  1822. if (typeof dh.configureVisibilityObserver_ === 'function' && !dh.configureVisibilityObserver27_) {
  1823. dh.configureVisibilityObserver27_ = dh.configureVisibilityObserver_;
  1824. dh.configureVisibilityObserver_ = configureVisibilityObserverT_;
  1825. }
  1826.  
  1827. if (typeof dh.getParentRenderer === 'function' && !dh.getParentRenderer27) {
  1828. dh.getParentRenderer27 = dh.getParentRenderer;
  1829. dh.getParentRenderer = getParentRendererT;
  1830. }
  1831.  
  1832. if (typeof dh.attached === 'function' && !dh.attached27) {
  1833. dh.attached27 = dh.attached;
  1834. dh.attached = attachedT;
  1835. }
  1836.  
  1837. setupD(dh, 'hostElement', hostElementCleanUp);
  1838. setupD(dh, 'parentComponent');
  1839. setupD(dh, 'localVisibilityObserver_');
  1840. setupD(dh, 'cachedProviderNode_');
  1841.  
  1842.  
  1843. setupD(dh, '__template');
  1844. setupD(dh, '__templatizeOwner');
  1845. setupD(dh, '__templateInfo');
  1846.  
  1847. // setupD(dh, 'root', 1);
  1848.  
  1849. const elements_ = dh.elements_;
  1850. if (elements_ && typeof elements_ === 'object' && Object.keys(elements_).length > 0) setupD(dh, 'elements_');
  1851.  
  1852. setup$(dh);
  1853. }
  1854.  
  1855.  
  1856.  
  1857.  
  1858. } : null;
  1859.  
  1860.  
  1861. let delay300 = null;
  1862.  
  1863. if (UNLOAD_DETACHED_POLYMER || WEAK_REF_BINDING) {
  1864. delay300 = new PromiseExternal();
  1865. setInterval(() => {
  1866. delay300.resolve();
  1867. delay300 = new PromiseExternal();
  1868. }, 300);
  1869. }
  1870.  
  1871. const aDelay = async function () {
  1872. await delay300.then();
  1873. await delay300.then();
  1874. }
  1875.  
  1876. const convertionFuncMap = new WeakMap();
  1877. let val_kevlar_should_maintain_stable_list = null;
  1878.  
  1879. const createStampDomArrayFn_ = (fn) => {
  1880. if (val_kevlar_should_maintain_stable_list === null) {
  1881. const config_ = ((window.yt || 0).config_ || 0);
  1882. val_kevlar_should_maintain_stable_list = ((config_ || 0).EXPERIMENT_FLAGS || 0).kevlar_should_maintain_stable_list === true
  1883. }
  1884. const gn = function (a, b, c, d, e, h) {
  1885. const isNonEmptyArray = (a || 0).length >= 1
  1886. if (!isNonEmptyArray) {
  1887. return fn.call(this, undefined, b, undefined, d);
  1888. } else if (h === undefined && typeof b === 'string' && c && typeof c === 'object' && this.is && val_kevlar_should_maintain_stable_list) {
  1889. if (c.clientSideToggleMenuItemRenderer) {
  1890. h = false;
  1891. } else {
  1892. h = true;
  1893. }
  1894. }
  1895. return fn.call(this, a, b, c, d, e, h)
  1896. }
  1897. gn.originalFn = fn;
  1898. convertionFuncMap.set(fn, gn);
  1899. return gn;
  1900. }
  1901.  
  1902. const fixStampDomArrayStableList = (h) => {
  1903. if (!h.stampDomArray_) return;
  1904. const proto = h.__proto__;
  1905. const f = proto.stampDomArray_;
  1906. if (!proto.stampDomArrayF001_ && typeof f === 'function' && f.length === 6) {
  1907. proto.stampDomArrayF001_ = 1;
  1908. proto.stampDomArray_ = convertionFuncMap.get(f) || createStampDomArrayFn_(f);
  1909. }
  1910. }
  1911.  
  1912. const weakenStampReferences = (() => {
  1913.  
  1914. const DEBUG_STAMP = false;
  1915.  
  1916. const s1 = Symbol();
  1917. const handler1 = {
  1918. get(target, prop, receiver) {
  1919. if (prop === 'object') {
  1920. return kRef(target[s1]); // avoid memory leakage
  1921. }
  1922. if (prop === '__proxy312__') return 1;
  1923. return target[prop];
  1924. }
  1925. };
  1926. const handler2 = {
  1927. get(target, prop, receiver) {
  1928. if (prop === 'indexSplices') {
  1929. return kRef(target[s1]); // avoid memory leakage
  1930. }
  1931. if (prop === '__proxy312__') return 1;
  1932. return target[prop];
  1933. }
  1934. }
  1935. return (h) => {
  1936.  
  1937. if (h.rendererStamperApplyChangeRecord_ || h.stampDomArraySplices_) {
  1938. const proto = h.__proto__;
  1939. if (!proto.yzxer && (proto.rendererStamperApplyChangeRecord_ || proto.stampDomArraySplices_)) {
  1940. proto.yzxer = 1;
  1941.  
  1942. const list = [
  1943. // "rendererStamperObserver_", // 3 ==> rendererStamperApplyChangeRecord_
  1944. "rendererStamperApplyChangeRecord_", // 3
  1945. "forwardRendererStamperChanges_", // 3
  1946. "stampDomArraySplices_", // 3
  1947. "stampDomArray_", // 6
  1948. "deferRenderStamperBinding_", // 3
  1949. ];
  1950. for (const key of list) {
  1951. const pey = `${key}$wq0iw_`;
  1952. const vKey = proto[key];
  1953. if (typeof vKey !== 'function') continue;
  1954. if (proto[pey] || vKey.length === 0) continue;
  1955.  
  1956. if (key === 'stampDomArraySplices_' && vKey.length === 3) {
  1957. proto[pey] = vKey;
  1958. proto[key] = function (a, b, c) {
  1959.  
  1960. if (typeof a === 'string' && typeof b === 'string' && typeof c === 'object' && c && c.indexSplices && c.indexSplices.length >= 1 && !c.indexSplices.rzgjr) {
  1961.  
  1962. c.indexSplices = c.indexSplices.map(e => {
  1963. if (e.__proxy312__) return e;
  1964. e[s1] = mWeakRef(e.object);
  1965. e.object = null;
  1966. return new Proxy(e, handler1);
  1967. });
  1968. c.indexSplices.rzgjr = 1;
  1969.  
  1970. c[s1] = mWeakRef(c.indexSplices);
  1971. c.indexSplices = null;
  1972. c = new Proxy(c, handler2)
  1973. arguments[2] = c;
  1974.  
  1975. }
  1976. // console.log(key, arguments.length, [...arguments]);
  1977. return proto[pey].call(this, a, b, c);
  1978. }
  1979.  
  1980. } else if (key === 'rendererStamperApplyChangeRecord_' && vKey.length === 3) {
  1981.  
  1982. // Nil
  1983.  
  1984. } else if (DEBUG_STAMP) {
  1985.  
  1986. console.log(proto.isRenderer_, 'ms_' + key, vKey.length, h.is)
  1987. proto[pey] = vKey;
  1988. proto[key] = function () {
  1989. if (key === 'rendererStamperApplyChangeRecord_' && typeof arguments[3] === 'object') {
  1990. console.log(key, arguments.length, { value: arguments[3].value, base: arguments[3].base, })
  1991. }
  1992. console.log(key, arguments.length, [...arguments]);
  1993. return proto[pey].apply(this, arguments);
  1994. }
  1995.  
  1996. }
  1997.  
  1998. }
  1999.  
  2000.  
  2001. // const m = (Object.mkss = Object.mkss || new Set());
  2002. // Object.keys(h.__proto__).filter(e => e.toLowerCase().includes('stamp') && typeof h[e] === 'function').forEach(e => m.add(e))
  2003. // console.log([...m])
  2004. }
  2005. }
  2006.  
  2007. }
  2008. })();
  2009.  
  2010. const setupDiscreteTasks = (h, rb) => {
  2011.  
  2012. if (rb) {
  2013. if (h.ky36) return;
  2014. }
  2015.  
  2016.  
  2017. if (typeof h.onYtRendererstamperFinished === 'function' && !(h.onYtRendererstamperFinished.km34)) {
  2018. const f = h.onYtRendererstamperFinished;
  2019. const g = ump3.get(f) || function () {
  2020. if (this.updateChildVisibilityProperties && !this.markDirty) {
  2021. return f.apply(this, arguments);
  2022. }
  2023. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2024. }
  2025. ump3.set(f, g);
  2026. g.km34 = 1;
  2027. h.onYtRendererstamperFinished = g;
  2028.  
  2029. }
  2030.  
  2031. if (typeof h.onYtUpdateDescriptionAction === 'function' && !(h.onYtUpdateDescriptionAction.km34)) {
  2032. const f = h.onYtUpdateDescriptionAction;
  2033. const g = ump3.get(f) || function (a) {
  2034. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2035. }
  2036. ump3.set(f, g);
  2037. g.km34 = 1;
  2038. h.onYtUpdateDescriptionAction = g;
  2039.  
  2040. }
  2041.  
  2042. if (typeof h.handleUpdateDescriptionAction === 'function' && !(h.handleUpdateDescriptionAction.km34)) {
  2043. const f = h.handleUpdateDescriptionAction;
  2044. const g = ump3.get(f) || function (a) {
  2045. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2046. }
  2047. ump3.set(f, g);
  2048. g.km34 = 1;
  2049. h.handleUpdateDescriptionAction = g;
  2050.  
  2051. }
  2052.  
  2053. if (typeof h.handleUpdateLiveChatPollAction === 'function' && !(h.handleUpdateLiveChatPollAction.km34)) {
  2054. const f = h.handleUpdateLiveChatPollAction;
  2055. const g = ump3.get(f) || function (a) {
  2056. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2057. }
  2058. ump3.set(f, g);
  2059. g.km34 = 1;
  2060. h.handleUpdateLiveChatPollAction = g;
  2061.  
  2062. }
  2063.  
  2064. if (typeof h.onTextChanged === 'function' && !(h.onTextChanged.km34)) {
  2065. const f = h.onTextChanged;
  2066. const g = ump3.get(f) || function () {
  2067. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2068. }
  2069. ump3.set(f, g);
  2070. g.km34 = 1;
  2071. h.onTextChanged = g;
  2072.  
  2073. }
  2074.  
  2075. if (typeof h.onVideoDataChange === 'function' && !(h.onVideoDataChange.km34)) {
  2076. const f = h.onVideoDataChange;
  2077. const g = ump3.get(f) || function (a) {
  2078. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2079. }
  2080. ump3.set(f, g);
  2081. g.km34 = 1;
  2082. h.onVideoDataChange = g;
  2083.  
  2084. }
  2085.  
  2086. if (typeof h.onVideoDataChange_ === 'function' && !(h.onVideoDataChange_.km34)) {
  2087. const f = h.onVideoDataChange_;
  2088. const g = ump3.get(f) || function () {
  2089. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2090. }
  2091. ump3.set(f, g);
  2092. g.km34 = 1;
  2093. h.onVideoDataChange_ = g;
  2094.  
  2095. }
  2096.  
  2097. if (typeof h.addTooltips === 'function' && !(h.addTooltips.km34)) {
  2098.  
  2099. const f = h.addTooltips;
  2100. const g = ump3.get(f) || function () {
  2101. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2102. }
  2103. ump3.set(f, g);
  2104. g.km34 = 1;
  2105. h.addTooltips = g;
  2106.  
  2107. }
  2108.  
  2109. if (typeof h.addTooltips_ === 'function' && !(h.addTooltips_.km34)) {
  2110.  
  2111. const f = h.addTooltips_;
  2112. const g = ump3.get(f) || function () {
  2113. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2114. }
  2115. ump3.set(f, g);
  2116. g.km34 = 1;
  2117. h.addTooltips_ = g;
  2118.  
  2119. }
  2120.  
  2121. if (typeof h.updateRenderedElements === 'function' && !(h.updateRenderedElements.km34)) {
  2122.  
  2123. const f = h.updateRenderedElements;
  2124. const g = ump3.get(f) || function () {
  2125. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2126. }
  2127. ump3.set(f, g);
  2128. g.km34 = 1;
  2129. h.updateRenderedElements = g;
  2130.  
  2131. }
  2132.  
  2133. if ((WEAK_REF_BINDING_CONTROL & 2) && typeof h.loadPage_ === 'function' && !(h.loadPage_.km34)) {
  2134. const f = h.loadPage_;
  2135. const g = ump3.get(f) || function (a) {
  2136. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2137. }
  2138. ump3.set(f, g);
  2139. g.km34 = 1;
  2140. h.loadPage_ = g;
  2141.  
  2142. }
  2143. // updatePageData_ : possible conflict with Omit ShadyDOM
  2144. if ((WEAK_REF_BINDING_CONTROL & 2) && typeof h.updatePageData_ === 'function' && !(h.updatePageData_.km34)) {
  2145. const f = h.updatePageData_;
  2146. const g = ump3.get(f) || function (a) {
  2147. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2148. }
  2149. ump3.set(f, g);
  2150. g.km34 = 1;
  2151. h.updatePageData_ = g;
  2152.  
  2153. }
  2154.  
  2155.  
  2156. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onFocus_ === 'function' && !(h.onFocus_.km34)) {
  2157.  
  2158. const f = h.onFocus_;
  2159. const g = ump3.get(f) || function () {
  2160. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2161. }
  2162. ump3.set(f, g);
  2163. g.km34 = 1;
  2164. h.onFocus_ = g;
  2165.  
  2166. }
  2167.  
  2168. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onBlur_ === 'function' && !(h.onBlur_.km34)) {
  2169.  
  2170. const f = h.onBlur_;
  2171. const g = ump3.get(f) || function () {
  2172. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2173. }
  2174. ump3.set(f, g);
  2175. g.km34 = 1;
  2176. h.onBlur_ = g;
  2177.  
  2178. }
  2179.  
  2180.  
  2181. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.buttonClassChanged_ === 'function' && !(h.buttonClassChanged_.km34)) {
  2182.  
  2183. const f = h.buttonClassChanged_;
  2184. const g = ump3.get(f) || function (a, b) {
  2185. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2186. }
  2187. ump3.set(f, g);
  2188. g.km34 = 1;
  2189. h.buttonClassChanged_ = g;
  2190.  
  2191. }
  2192.  
  2193. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.buttonIconChanged_ === 'function' && !(h.buttonIconChanged_.km34)) {
  2194.  
  2195. const f = h.buttonIconChanged_;
  2196. const g = ump3.get(f) || function (a) {
  2197. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2198. }
  2199. ump3.set(f, g);
  2200. g.km34 = 1;
  2201. h.buttonIconChanged_ = g;
  2202.  
  2203. }
  2204.  
  2205. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.dataChangedInBehavior_ === 'function' && !(h.dataChangedInBehavior_.km34)) {
  2206.  
  2207. const f = h.dataChangedInBehavior_;
  2208. const g = ump3.get(f) || function () {
  2209. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2210. }
  2211. ump3.set(f, g);
  2212. g.km34 = 1;
  2213. h.dataChangedInBehavior_ = g;
  2214.  
  2215. }
  2216.  
  2217. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.continuationsChanged_ === 'function' && !(h.continuationsChanged_.km34)) {
  2218.  
  2219. const f = h.continuationsChanged_;
  2220. const g = ump3.get(f) || function () {
  2221. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2222. }
  2223. ump3.set(f, g);
  2224. g.km34 = 1;
  2225. h.continuationsChanged_ = g;
  2226.  
  2227. }
  2228.  
  2229.  
  2230. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.forceChatPoll_ === 'function' && !(h.forceChatPoll_.km34)) {
  2231.  
  2232. const f = h.forceChatPoll_;
  2233. const g = ump3.get(f) || function (a) {
  2234. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2235. }
  2236. ump3.set(f, g);
  2237. g.km34 = 1;
  2238. h.forceChatPoll_ = g;
  2239.  
  2240. }
  2241.  
  2242. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onEndpointClick_ === 'function' && !(h.onEndpointClick_.km34)) {
  2243.  
  2244. const f = h.onEndpointClick_;
  2245. const g = ump3.get(f) || function (a) {
  2246. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2247. }
  2248. ump3.set(f, g);
  2249. g.km34 = 1;
  2250. h.onEndpointClick_ = g;
  2251.  
  2252. }
  2253.  
  2254. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onEndpointTap_ === 'function' && !(h.onEndpointTap_.km34)) {
  2255.  
  2256. const f = h.onEndpointTap_;
  2257. const g = ump3.get(f) || function (a) {
  2258. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2259. }
  2260. ump3.set(f, g);
  2261. g.km34 = 1;
  2262. h.onEndpointTap_ = g;
  2263.  
  2264. }
  2265.  
  2266. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.handleClick_ === 'function' && !(h.handleClick_.km34)) {
  2267.  
  2268. const f = h.handleClick_;
  2269. const g = ump3.get(f) || function (a, b) {
  2270. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2271. }
  2272. ump3.set(f, g);
  2273. g.km34 = 1;
  2274. h.handleClick_ = g;
  2275.  
  2276. }
  2277.  
  2278. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onReadyStateChange_ === 'function' && !(h.onReadyStateChange_.km34)) {
  2279.  
  2280. const f = h.onReadyStateChange_;
  2281. const g = ump3.get(f) || function () {
  2282. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2283. }
  2284. ump3.set(f, g);
  2285. g.km34 = 1;
  2286. h.onReadyStateChange_ = g;
  2287.  
  2288. }
  2289.  
  2290. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onReadyStateChangeEntryPoint_ === 'function' && !(h.onReadyStateChangeEntryPoint_.km34)) {
  2291.  
  2292. const f = h.onReadyStateChangeEntryPoint_;
  2293. const g = ump3.get(f) || function () {
  2294. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2295. }
  2296. ump3.set(f, g);
  2297. g.km34 = 1;
  2298. h.onReadyStateChangeEntryPoint_ = g;
  2299.  
  2300. }
  2301.  
  2302. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.readyStateChangeHandler_ === 'function' && !(h.readyStateChangeHandler_.km34)) {
  2303.  
  2304. const f = h.readyStateChangeHandler_;
  2305. const g = ump3.get(f) || function (a) {
  2306. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2307. }
  2308. ump3.set(f, g);
  2309. g.km34 = 1;
  2310. h.readyStateChangeHandler_ = g;
  2311.  
  2312. }
  2313.  
  2314. if (typeof h.xmlHttpHandler_ === 'function' && !(h.xmlHttpHandler_.km34)) {
  2315.  
  2316. const f = h.xmlHttpHandler_;
  2317. const g = ump3.get(f) || function (a) {
  2318. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2319. }
  2320. ump3.set(f, g);
  2321. g.km34 = 1;
  2322. h.xmlHttpHandler_ = g;
  2323.  
  2324. }
  2325.  
  2326. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.executeCallbacks_ === 'function' && !(h.executeCallbacks_.km34)) {
  2327.  
  2328. const f = h.executeCallbacks_; // overloaded
  2329. const g = ump3.get(f) || function (a) {
  2330. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2331. }
  2332. ump3.set(f, g);
  2333. g.km34 = 1;
  2334. h.executeCallbacks_ = g;
  2335.  
  2336. }
  2337.  
  2338. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.handleInvalidationData_ === 'function' && !(h.handleInvalidationData_.km34)) {
  2339.  
  2340. const f = h.handleInvalidationData_;
  2341. const g = ump3.get(f) || function (a, b) {
  2342. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2343. }
  2344. ump3.set(f, g);
  2345. g.km34 = 1;
  2346. h.handleInvalidationData_ = g;
  2347.  
  2348. }
  2349.  
  2350. if (typeof h.onInput_ === 'function' && !(h.onInput_.km34)) {
  2351.  
  2352. const f = h.onInput_;
  2353. const g = ump3.get(f) || function () {
  2354. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2355. }
  2356. ump3.set(f, g);
  2357. g.km34 = 1;
  2358. h.onInput_ = g;
  2359.  
  2360. }
  2361. if (typeof h.trigger_ === 'function' && !(h.trigger_.km34)) {
  2362.  
  2363. const f = h.trigger_;
  2364. const g = ump3.get(f) || function (a) {
  2365. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2366. }
  2367. ump3.set(f, g);
  2368. g.km34 = 1;
  2369. h.trigger_ = g;
  2370.  
  2371. }
  2372.  
  2373. if (typeof h.requestData_ === 'function' && !(h.requestData_.km34)) {
  2374.  
  2375. const f = h.requestData_;
  2376. const g = ump3.get(f) || function (a) {
  2377. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2378. }
  2379. ump3.set(f, g);
  2380. g.km34 = 1;
  2381. h.requestData_ = g;
  2382.  
  2383. }
  2384.  
  2385. if (typeof h.onLoadReloadContinuation_ === 'function' && !(h.onLoadReloadContinuation_.km34)) {
  2386.  
  2387. const f = h.onLoadReloadContinuation_;
  2388. const g = ump3.get(f) || function (a, b) {
  2389. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2390. }
  2391. ump3.set(f, g);
  2392. g.km34 = 1;
  2393. h.onLoadReloadContinuation_ = g;
  2394.  
  2395. }
  2396.  
  2397. if (typeof h.onLoadIncrementalContinuation_ === 'function' && !(h.onLoadIncrementalContinuation_.km34)) {
  2398.  
  2399. const f = h.onLoadIncrementalContinuation_;
  2400. const g = ump3.get(f) || function (a, b) {
  2401. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2402. }
  2403. ump3.set(f, g);
  2404. g.km34 = 1;
  2405. h.onLoadIncrementalContinuation_ = g;
  2406.  
  2407. }
  2408.  
  2409. if (typeof h.onLoadSeekContinuation_ === 'function' && !(h.onLoadSeekContinuation_.km34)) {
  2410.  
  2411. const f = h.onLoadSeekContinuation_;
  2412. const g = ump3.get(f) || function (a, b) {
  2413. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2414. }
  2415. ump3.set(f, g);
  2416. g.km34 = 1;
  2417. h.onLoadSeekContinuation_ = g;
  2418.  
  2419. }
  2420. if (typeof h.onLoadReplayContinuation_ === 'function' && !(h.onLoadReplayContinuation_.km34)) {
  2421.  
  2422. const f = h.onLoadReplayContinuation_;
  2423. const g = ump3.get(f) || function (a, b) {
  2424. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2425. }
  2426. ump3.set(f, g);
  2427. g.km34 = 1;
  2428. h.onLoadReplayContinuation_ = g;
  2429.  
  2430. }
  2431. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onNavigate_ === 'function' && !(h.onNavigate_.km34)) {
  2432.  
  2433. const f = h.onNavigate_;
  2434. const g = ump3.get(f) || function (a) {
  2435. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2436. }
  2437. ump3.set(f, g);
  2438. g.km34 = 1;
  2439. h.onNavigate_ = g;
  2440.  
  2441. }
  2442.  
  2443. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.ytRendererBehaviorDataObserver_ === 'function' && !(h.ytRendererBehaviorDataObserver_.km34)) {
  2444.  
  2445. const f = h.ytRendererBehaviorDataObserver_;
  2446. const g = ump3.get(f) || function () {
  2447. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2448. }
  2449. ump3.set(f, g);
  2450. g.km34 = 1;
  2451. h.ytRendererBehaviorDataObserver_ = g;
  2452.  
  2453. }
  2454.  
  2455. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.ytRendererBehaviorTargetIdObserver_ === 'function' && !(h.ytRendererBehaviorTargetIdObserver_.km34)) {
  2456.  
  2457. const f = h.ytRendererBehaviorTargetIdObserver_;
  2458. const g = ump3.get(f) || function () {
  2459. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2460. }
  2461. ump3.set(f, g);
  2462. g.km34 = 1;
  2463. h.ytRendererBehaviorTargetIdObserver_ = g;
  2464.  
  2465. }
  2466.  
  2467. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.unregisterRenderer_ === 'function' && !(h.unregisterRenderer_.km34)) {
  2468.  
  2469. const f = h.unregisterRenderer_;
  2470. const g = ump3.get(f) || function (a) {
  2471. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2472. }
  2473. ump3.set(f, g);
  2474. g.km34 = 1;
  2475. h.unregisterRenderer_ = g;
  2476.  
  2477. }
  2478.  
  2479. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.textChanged_ === 'function' && !(h.textChanged_.km34)) {
  2480.  
  2481. const f = h.textChanged_;
  2482. const g = ump3.get(f) || function (a) {
  2483. if (void 0 !== this.isAttached) {
  2484. const hostElement = this.hostElement;
  2485. if (!(hostElement instanceof Node) || hostElement.nodeName === 'NOSCRIPT') {
  2486. return;
  2487. }
  2488. }
  2489. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2490. }
  2491. ump3.set(f, g);
  2492. g.km34 = 1;
  2493. h.textChanged_ = g;
  2494.  
  2495. }
  2496.  
  2497.  
  2498.  
  2499. /**
  2500. *
  2501. * Neglect following
  2502. *
  2503. * h.onYtAction_
  2504. * h.startLoadingWatch [ buggy for yt-player-updated ]
  2505. * h.deferRenderStamperBinding_
  2506. *
  2507. * h.stampDomArray_
  2508. * h.stampDomArraySplices_
  2509. *
  2510. */
  2511.  
  2512.  
  2513. // RP.prototype.searchChanged_ = RP.prototype.searchChanged_;
  2514. // RP.prototype.skinToneChanged_ = RP.prototype.skinToneChanged_;
  2515. // RP.prototype.onEmojiHover_ = RP.prototype.onEmojiHover_;
  2516. // RP.prototype.onSelectCategory_ = RP.prototype.onSelectCategory_;
  2517. // RP.prototype.onShowEmojiVariantSelector = RP.prototype.onShowEmojiVariantSelector;
  2518. // RP.prototype.updateCategoriesAndPlaceholder_ = RP.prototype.updateCategoriesAndPlaceholder_;
  2519.  
  2520. if (typeof h.searchChanged_ === 'function' && !(h.searchChanged_.km34)) {
  2521.  
  2522. const f = h.searchChanged_;
  2523. const g = ump3.get(f) || function () {
  2524. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2525. }
  2526. ump3.set(f, g);
  2527. g.km34 = 1;
  2528. h.searchChanged_ = g;
  2529.  
  2530. }
  2531.  
  2532. if (typeof h.skinToneChanged_ === 'function' && !(h.skinToneChanged_.km34)) {
  2533.  
  2534. const f = h.skinToneChanged_;
  2535. const g = ump3.get(f) || function (a) {
  2536. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2537. }
  2538. ump3.set(f, g);
  2539. g.km34 = 1;
  2540. h.skinToneChanged_ = g;
  2541.  
  2542. }
  2543.  
  2544. if (typeof h.onEmojiHover_ === 'function' && !(h.onEmojiHover_.km34)) {
  2545.  
  2546. const f = h.onEmojiHover_;
  2547. const g = ump3.get(f) || function (a) {
  2548. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2549. }
  2550. ump3.set(f, g);
  2551. g.km34 = 1;
  2552. h.onEmojiHover_ = g;
  2553.  
  2554. }
  2555.  
  2556. if (typeof h.onSelectCategory_ === 'function' && !(h.onSelectCategory_.km34)) {
  2557.  
  2558. const f = h.onSelectCategory_;
  2559. const g = ump3.get(f) || function (a) {
  2560. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2561. }
  2562. ump3.set(f, g);
  2563. g.km34 = 1;
  2564. h.onSelectCategory_ = g;
  2565.  
  2566. }
  2567.  
  2568. if (typeof h.onShowEmojiVariantSelector === 'function' && !(h.onShowEmojiVariantSelector.km34)) {
  2569.  
  2570. const f = h.onShowEmojiVariantSelector;
  2571. const g = ump3.get(f) || function (a) {
  2572. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2573. }
  2574. ump3.set(f, g);
  2575. g.km34 = 1;
  2576. h.onShowEmojiVariantSelector = g;
  2577.  
  2578. }
  2579.  
  2580. if (typeof h.updateCategoriesAndPlaceholder_ === 'function' && !(h.updateCategoriesAndPlaceholder_.km34)) {
  2581.  
  2582. const f = h.updateCategoriesAndPlaceholder_;
  2583. const g = ump3.get(f) || function () {
  2584. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2585. }
  2586. ump3.set(f, g);
  2587. g.km34 = 1;
  2588. h.updateCategoriesAndPlaceholder_ = g;
  2589.  
  2590. }
  2591.  
  2592. if (typeof h.watchPageActiveChanged_ === 'function' && !(h.watchPageActiveChanged_.km34)) {
  2593.  
  2594. const f = h.watchPageActiveChanged_;
  2595. const g = ump3.get(f) || function () {
  2596. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2597. }
  2598. ump3.set(f, g);
  2599. g.km34 = 1;
  2600. h.watchPageActiveChanged_ = g;
  2601.  
  2602. }
  2603.  
  2604. if (typeof h.activate_ === 'function' && !(h.activate_.km34)) {
  2605.  
  2606. const f = h.activate_;
  2607. const g = ump3.get(f) || function () {
  2608. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2609. }
  2610. ump3.set(f, g);
  2611. g.km34 = 1;
  2612. h.activate_ = g;
  2613.  
  2614. }
  2615. if (typeof h.onYtPlaylistDataUpdated_ === 'function' && !(h.onYtPlaylistDataUpdated_.km34)) {
  2616.  
  2617. const f = h.onYtPlaylistDataUpdated_;
  2618. const g = ump3.get(f) || function () {
  2619. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2620. }
  2621. ump3.set(f, g);
  2622. g.km34 = 1;
  2623. h.onYtPlaylistDataUpdated_ = g;
  2624.  
  2625. }
  2626.  
  2627. FIX_stampDomArray_stableList && fixStampDomArrayStableList(h);
  2628. const ENABLE_weakenStampReferencesQ = ENABLE_weakenStampReferences && typeof DocumentTimeline !== 'undefined' && typeof WeakRef !== 'undefined';
  2629. ENABLE_weakenStampReferencesQ && weakenStampReferences(h);
  2630.  
  2631.  
  2632. /**
  2633. *
  2634. * Neglect following
  2635. *
  2636. * h.rendererStamperObserver_
  2637. * h.rendererStamperApplyChangeRecord_
  2638. * h.flushRenderStamperComponentBindings_
  2639. * h.forwardRendererStamperChanges_
  2640. *
  2641. */
  2642.  
  2643. if (typeof h.tryRenderChunk_ === 'function' && !(h.tryRenderChunk_.km34)) {
  2644.  
  2645. const f = h.tryRenderChunk_;
  2646. const g = ump3.get(f) || function () {
  2647. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2648. }
  2649. ump3.set(f, g);
  2650. g.km34 = 1;
  2651. h.tryRenderChunk_ = g;
  2652.  
  2653. }
  2654.  
  2655.  
  2656. if (typeof h.renderChunk_ === 'function' && !(h.renderChunk_.km34)) {
  2657.  
  2658. const f = h.renderChunk_;
  2659. const g = ump3.get(f) || function () {
  2660. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2661. }
  2662. ump3.set(f, g);
  2663. g.km34 = 1;
  2664. h.renderChunk_ = g;
  2665.  
  2666. }
  2667.  
  2668. if (typeof h.deepLazyListObserver_ === 'function' && !(h.deepLazyListObserver_.km34)) {
  2669.  
  2670. const f = h.deepLazyListObserver_;
  2671. const g = ump3.get(f) || function () {
  2672. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2673. }
  2674. ump3.set(f, g);
  2675. g.km34 = 1;
  2676. h.deepLazyListObserver_ = g;
  2677.  
  2678. }
  2679.  
  2680. if (typeof h.onItemsUpdated_ === 'function' && !(h.onItemsUpdated_.km34)) {
  2681.  
  2682. const f = h.onItemsUpdated_;
  2683. const g = ump3.get(f) || function () {
  2684. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2685. }
  2686. ump3.set(f, g);
  2687. g.km34 = 1;
  2688. h.onItemsUpdated_ = g;
  2689.  
  2690. }
  2691.  
  2692. if (typeof h.requestRenderChunk_ === 'function' && !(h.requestRenderChunk_.km34)) {
  2693.  
  2694. const f = h.requestRenderChunk_;
  2695. const g = ump3.get(f) || function () {
  2696. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  2697. }
  2698. ump3.set(f, g);
  2699. g.km34 = 1;
  2700. h.requestRenderChunk_ = g;
  2701.  
  2702. }
  2703.  
  2704. /**
  2705. *
  2706. * Neglect following
  2707. *
  2708. * h.dataChanged_ [ buggy for page swtiching ]
  2709. *
  2710. * h.updateChangeRecord_ [ see https://github.com/cyfung1031/userscript-supports/issues/20 ]
  2711. *
  2712. * h.cancelPendingTasks_
  2713. * h.fillRange_
  2714. * h.addTextNodes_
  2715. * h.updateText_
  2716. * h.stampTypeChanged_
  2717. *
  2718. */
  2719.  
  2720.  
  2721. }
  2722.  
  2723. const keyStConnectedCallback = Symbol(); // avoid copying the value
  2724.  
  2725. // const keyStDisconnectedCallback = Symbol(); // avoid copying the value
  2726. const cmf = new WeakMap();
  2727. const dmf = new WeakMap();
  2728.  
  2729. const gvGenerator = (nv) => {
  2730. return function () {
  2731. const cnt = insp(this);
  2732. const hostElement = cnt.hostElement || 0;
  2733. const dollar = hostElement ? (this.$ || indr(this)) : 0;
  2734. let p = (hostElement instanceof HTMLElement) && (dollar || !this.is);
  2735. if (p && (!dollar && !this.is)) {
  2736. const nodeName = hostElement.nodeName;
  2737. if (typeof nodeName !== 'string') {
  2738. // just in case
  2739. } else if (nodeName.startsWith("DOM-")) {
  2740. // dom-if, dom-repeat, etc
  2741. } else {
  2742. // yt element - new model, yt-xxxx, anixxxxxx
  2743. p = false;
  2744. }
  2745. }
  2746. if (p) {
  2747. if (typeof cnt.markDirty === 'function') {
  2748. // the yt element might call markDirty (occasionally)
  2749. p = false;
  2750. } else if (this.is === 'ytd-engagement-panel-section-list-renderer') {
  2751. // see https://github.com/cyfung1031/userscript-supports/issues/20
  2752. p = false;
  2753. }
  2754. }
  2755. if (p) {
  2756.  
  2757. // << dom-repeat & dom-if >>
  2758.  
  2759. // sequence on the same instance
  2760. this[qm57] = (this[qm57] || Promise.resolve()).then(() => nv.apply(this, arguments)).catch(console.log);
  2761. } else {
  2762. nv.apply(this, arguments);
  2763. }
  2764. };
  2765. }
  2766.  
  2767. const setupWeakRef = (h) => {
  2768.  
  2769.  
  2770. if (WEAK_REF_BINDING && !h.kz62 && setup$ && setupD && setupDataHost && (h.is || h.__dataHost)) {
  2771.  
  2772. let skip = false;
  2773. // if (h.is && typeof h.is === 'string' && h.is.length > 15 && h.is.length < 30) {
  2774. // if (h.is.includes('yt-') && !h.$ && h.is.length !== 20 && h.is.length !== 21 && h.is.length !== 22) {
  2775. // skip = true;
  2776. // // return;
  2777. // }
  2778. // }
  2779.  
  2780. h.kz62 = 1;
  2781.  
  2782. //
  2783.  
  2784. setup$(h);
  2785. const hostElement = h.hostElement;
  2786.  
  2787. if (hostElement !== h) {
  2788.  
  2789. for (const s of ['__dataHost', '__CE_shadowRoot', '__template', '__templatizeOwner']) {
  2790. setupD(h, s);
  2791. }
  2792.  
  2793. const dh = h.__dataHost;
  2794. setupDataHost(dh, skip);
  2795. }
  2796.  
  2797. if (hostElement) {
  2798.  
  2799. for (const s of ['__dataHost', '__CE_shadowRoot', '__template', '__templatizeOwner']) {
  2800. setupD(hostElement, s);
  2801. }
  2802.  
  2803. const dh = hostElement.__dataHost;
  2804. setupDataHost(dh, skip);
  2805.  
  2806. aDelay().then(() => {
  2807. setupD(hostElement, '__CE_shadowRoot');
  2808. });
  2809.  
  2810. }
  2811.  
  2812. }
  2813.  
  2814. }
  2815.  
  2816.  
  2817. let nativeHTMLElement = window.HTMLElement;
  2818.  
  2819. try {
  2820.  
  2821. const q = document.createElement('template');
  2822. q.innerHTML = '<ytz-null361></ytz-null361>';
  2823. nativeHTMLElement = q.content.firstChild.constructor
  2824.  
  2825. } catch (e) { }
  2826.  
  2827. if (!nativeHTMLElement.prototype.connectedCallback) {
  2828. nativeHTMLElement.prototype.connectedCallback79 = nativeHTMLElement.prototype.connectedCallback;
  2829. nativeHTMLElement.prototype.connectedCallback = function () {
  2830. let r;
  2831. if (this.connectedCallback79) r = this.connectedCallback79.apply(this, arguments);
  2832.  
  2833. if (WEAK_REF_BINDING && (this instanceof Node) && (this.is || this.__dataHost)) {
  2834. setupWeakRef(this)
  2835. // setupWeakRef(this.__dataHost)
  2836. }
  2837. return r;
  2838. }
  2839. }
  2840.  
  2841. ENABLE_discreteTasking && Object.defineProperty(Object.prototype, 'connectedCallback', {
  2842. get() {
  2843. const f = this[keyStConnectedCallback];
  2844. if (this.is) {
  2845. setupDiscreteTasks(this, true);
  2846. if (f) this.ky36 = 1;
  2847. }
  2848. if (WEAK_REF_BINDING && (this.is || this instanceof Node)) {
  2849. setupWeakRef(this)
  2850. }
  2851. return f;
  2852. },
  2853. set(nv) {
  2854. let gv;
  2855. if (typeof nv === 'function') {
  2856.  
  2857. gv = cmf.get(nv) || gvGenerator(nv);
  2858. if (gv !== nv) {
  2859. cmf.set(nv, gv);
  2860. cmf.set(gv, gv);
  2861. dmf.set(gv, nv);
  2862. }
  2863.  
  2864. } else {
  2865. gv = nv;
  2866. }
  2867. this[keyStConnectedCallback] = gv; // proto or object
  2868. if (this.is) {
  2869. setupDiscreteTasks(this);
  2870. }
  2871. if (WEAK_REF_BINDING && (this.is || this instanceof Node)) {
  2872. setupWeakRef(this)
  2873. }
  2874. return true;
  2875. },
  2876. enumerable: false,
  2877. configurable: true
  2878.  
  2879. });
  2880.  
  2881. const pLoad = new Promise(resolve => {
  2882. if (document.readyState !== 'loading') {
  2883. resolve();
  2884. } else {
  2885. window.addEventListener("DOMContentLoaded", resolve, false);
  2886. }
  2887. });
  2888. pLoad.then(() => {
  2889.  
  2890. let nonce = document.querySelector('style[nonce]');
  2891. nonce = nonce ? nonce.getAttribute('nonce') : null;
  2892. const st = document.createElement('style');
  2893. if (typeof nonce === 'string') st.setAttribute('nonce', nonce);
  2894. st.textContent = "none-element-k47{order:0}";
  2895. st.addEventListener('load', () => {
  2896. pf31.resolve();
  2897. p59 = 1;
  2898. }, false);
  2899. (document.body || document.head || document.documentElement).appendChild(st);
  2900.  
  2901. });
  2902.  
  2903. const prepareLogs = [];
  2904.  
  2905. const skipAdsDetection = new Set(['/robots.txt', '/live_chat', '/live_chat_replay']);
  2906.  
  2907. let winError00 = window.onerror;
  2908.  
  2909. let fix_error_many_stack_state = !FIX_error_many_stack ? 0 : skipAdsDetection.has(location.pathname) ? 2 : 1;
  2910.  
  2911. if (!JSON || !('parse' in JSON)) fix_error_many_stack_state = 0;
  2912.  
  2913. ; FIX_Iframe_NULL_SRC && (() => {
  2914.  
  2915. const emptyBlobUrl = URL.createObjectURL(new Blob([], { type: 'text/html' }));
  2916. const lcOpt = { sensitivity: 'base' };
  2917. document.createElement24 = document.createElement;
  2918. document.createElement = function (t) {
  2919. if (typeof t === 'string' && t.length === 6) {
  2920. if (t.localeCompare('iframe', undefined, lcOpt) === 0) {
  2921. const p = this.createElement24(t);
  2922. try {
  2923. const stack = new Error().stack;
  2924. const isSearchbox = stack.includes('initializeSearchbox'); // see https://greasyfork.org/scripts/473972-youtube-js-engine-tamer/discussions/217084
  2925. if (!isSearchbox) {
  2926. p.src = emptyBlobUrl; // avoid iframe is appended to DOM without any url
  2927. }
  2928. } catch (e) { }
  2929. return p;
  2930. }
  2931. }
  2932. return this.createElement24.apply(this, arguments);
  2933. };
  2934.  
  2935. })();
  2936.  
  2937. ; fix_error_many_stack_state === 1 && (() => {
  2938.  
  2939.  
  2940. let p1 = winError00;
  2941.  
  2942. let stackNeedleDetails = null;
  2943.  
  2944. Object.defineProperty(Object.prototype, 'matchAll', {
  2945. get() {
  2946. stackNeedleDetails = this;
  2947. return true;
  2948. },
  2949. enumerable: true,
  2950. configurable: true
  2951. });
  2952.  
  2953. try {
  2954. JSON.parse("{}");
  2955. } catch (e) {
  2956. console.warn(e)
  2957. fix_error_many_stack_state = 0;
  2958. }
  2959.  
  2960. delete Object.prototype['matchAll'];
  2961.  
  2962. let p2 = window.onerror;
  2963.  
  2964. window.onerror = p1;
  2965.  
  2966. if (fix_error_many_stack_state === 0) return;
  2967.  
  2968. if (stackNeedleDetails) {
  2969. JSON.parse.stackNeedleDetails = stackNeedleDetails;
  2970. stackNeedleDetails.matchAll = true;
  2971. }
  2972.  
  2973. if (p1 === p2) return (fix_error_many_stack_state = 0);
  2974.  
  2975. // p1!==p2
  2976. fix_error_many_stack_state = !stackNeedleDetails ? 4 : 3;
  2977.  
  2978. })();
  2979.  
  2980. ; fix_error_many_stack_state === 2 && (() => {
  2981.  
  2982.  
  2983. let p1 = winError00;
  2984.  
  2985. let objectPrune = null;
  2986. let stackNeedleDetails = null;
  2987.  
  2988. Object.defineProperty(Function.prototype, 'findOwner', {
  2989. get() {
  2990. objectPrune = this;
  2991. return this._findOwner;
  2992. },
  2993. set(nv) {
  2994. this._findOwner = nv;
  2995. return true;
  2996. },
  2997. enumerable: true,
  2998. configurable: true
  2999. });
  3000.  
  3001. Object.defineProperty(Object.prototype, 'matchAll', {
  3002. get() {
  3003. stackNeedleDetails = this;
  3004. return true;
  3005. },
  3006. enumerable: true,
  3007. configurable: true
  3008. });
  3009.  
  3010. try {
  3011. JSON.parse("{}");
  3012. } catch (e) {
  3013. console.warn(e)
  3014. fix_error_many_stack_state = 0;
  3015. }
  3016.  
  3017. delete Function.prototype['findOwner'];
  3018. delete Object.prototype['matchAll'];
  3019.  
  3020. let p2 = window.onerror;
  3021.  
  3022. if (p1 !== p2) return (fix_error_many_stack_state = 4); // p1 != p2
  3023.  
  3024. if (fix_error_many_stack_state == 0) return;
  3025.  
  3026. // the following will only execute when Brave's scriptlets.js is executed.
  3027.  
  3028. prepareLogs.push("fix_error_many_stack_state NB")
  3029.  
  3030. if (stackNeedleDetails) {
  3031. stackNeedleDetails.pattern = null;
  3032. stackNeedleDetails.re = null;
  3033. stackNeedleDetails.expect = null;
  3034. stackNeedleDetails.matchAll = true;
  3035. }
  3036.  
  3037. if (objectPrune) {
  3038. objectPrune.findOwner = objectPrune.mustProcess = objectPrune.logJson = () => { }
  3039. delete objectPrune._findOwner;
  3040. }
  3041.  
  3042. fix_error_many_stack_state = 3;
  3043. JSON.parse.stackNeedleDetails = stackNeedleDetails;
  3044. JSON.parse.objectPrune = objectPrune;
  3045.  
  3046. })();
  3047.  
  3048. ; fix_error_many_stack_state === 3 && (() => {
  3049.  
  3050.  
  3051. let p1 = winError00;
  3052.  
  3053. try {
  3054. JSON.parse("{}");
  3055. } catch (e) {
  3056. console.warn(e)
  3057. fix_error_many_stack_state = 0;
  3058. }
  3059.  
  3060. let p2 = window.onerror;
  3061.  
  3062. if (p1 === p2) return;
  3063.  
  3064. window.onerror = p1;
  3065.  
  3066. if (fix_error_many_stack_state === 0) return;
  3067.  
  3068. fix_error_many_stack_state = 4; // p1 != p2
  3069.  
  3070.  
  3071. })();
  3072.  
  3073. fix_error_many_stack_state === 4 && (() => {
  3074.  
  3075. // the following will only execute when Brave's scriptlets.js is executed.
  3076.  
  3077. prepareLogs.push("fix_error_many_stack_state AB")
  3078.  
  3079. JSON.parseProxy = JSON.parse;
  3080.  
  3081. JSON.parse = ((parse) => {
  3082.  
  3083. parse = parse.bind(JSON); // get a new instance of the current JSON.parse
  3084. return function (text, reviver) {
  3085. const onerror = window.onerror;
  3086. window.onerror = null;
  3087. let r;
  3088. try {
  3089. r = parse(...arguments);
  3090. } catch (e) {
  3091. r = e;
  3092. }
  3093. window.onerror = onerror;
  3094. if (r instanceof Error) {
  3095. throw r;
  3096. }
  3097. return r;
  3098. }
  3099.  
  3100. })(JSON.parse);
  3101.  
  3102.  
  3103. })();
  3104.  
  3105.  
  3106. // << if FIX_yt_player >>
  3107.  
  3108. // credit to @nopeless (https://greasyfork.org/scripts/471489-youtube-player-perf/)
  3109. const PERF_471489_ = true;
  3110. // PERF_471489_ is not exactly the same to Youtube Player perf v0.7
  3111. // This script uses a much gentle way to tamer the JS engine instead.
  3112.  
  3113. // << end >>
  3114.  
  3115. const steppingScaleN = 200; // transform: scaleX(k/N); 0<k<N
  3116.  
  3117.  
  3118.  
  3119. const nilFn = () => { };
  3120.  
  3121. let isMainWindow = false;
  3122. try {
  3123. isMainWindow = window.document === window.top.document
  3124. } catch (e) { }
  3125.  
  3126. let NO_PRELOAD_GENERATE_204_BYPASS = NO_PRELOAD_GENERATE_204 ? false : true;
  3127. let headLinkCollection = null;
  3128.  
  3129. const isCustomElementsProvided = typeof customElements !== "undefined" && typeof (customElements || 0).whenDefined === "function";
  3130.  
  3131. const promiseForCustomYtElementsReady = isCustomElementsProvided ? null : new Promise((callback) => {
  3132. const EVENT_KEY_ON_REGISTRY_READY = "ytI-ce-registry-created";
  3133. if (typeof customElements === 'undefined') {
  3134. if (!('__CE_registry' in document)) {
  3135. // https://github.com/webcomponents/polyfills/
  3136. Object.defineProperty(document, '__CE_registry', {
  3137. get() {
  3138. // return undefined
  3139. },
  3140. set(nv) {
  3141. if (typeof nv == 'object') {
  3142. delete this.__CE_registry;
  3143. this.__CE_registry = nv;
  3144. this.dispatchEvent(new CustomEvent(EVENT_KEY_ON_REGISTRY_READY));
  3145. }
  3146. return true;
  3147. },
  3148. enumerable: false,
  3149. configurable: true
  3150. })
  3151. }
  3152. let eventHandler = (evt) => {
  3153. document.removeEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  3154. const f = callback;
  3155. callback = null;
  3156. eventHandler = null;
  3157. f();
  3158. };
  3159. document.addEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  3160. } else {
  3161. callback();
  3162. }
  3163. });
  3164.  
  3165. const whenCEDefined = isCustomElementsProvided
  3166. ? (nodeName) => customElements.whenDefined(nodeName)
  3167. : (nodeName) => promiseForCustomYtElementsReady.then(() => customElements.whenDefined(nodeName));
  3168.  
  3169. // const assertor = (f) => f() || console.assert(false, f + "");
  3170.  
  3171. const fnIntegrity = (f, d) => {
  3172. if (!f || typeof f !== 'function') {
  3173. console.warn('f is not a function', f);
  3174. return;
  3175. }
  3176. let p = f + "", s = 0, j = -1, w = 0;
  3177. for (let i = 0, l = p.length; i < l; i++) {
  3178. const t = p[i];
  3179. if (((t >= 'a' && t <= 'z') || (t >= 'A' && t <= 'Z'))) {
  3180. if (j < i - 1) w++;
  3181. j = i;
  3182. } else {
  3183. s++;
  3184. }
  3185. }
  3186. let itz = `${f.length}.${s}.${w}`;
  3187. if (!d) {
  3188. return itz;
  3189. } else {
  3190. return itz === d;
  3191. }
  3192. };
  3193.  
  3194. const getZqOu = (_yt_player) => {
  3195.  
  3196. const w = 'ZqOu';
  3197.  
  3198. let arr = [];
  3199.  
  3200. for (const [k, v] of Object.entries(_yt_player)) {
  3201.  
  3202. const p = typeof v === 'function' ? v.prototype : 0;
  3203. if (p
  3204. && typeof p.start === 'function' && p.start.length === 0 // Ou
  3205. && typeof p.isActive === 'function' && p.isActive.length === 0
  3206. && typeof p.stop === 'function' && p.stop.length === 0
  3207. && !p.isComplete && !p.getStatus && !p.getResponseHeader && !p.getLastError
  3208. && !p.send && !p.abort
  3209. && !p.sample && !p.initialize && !p.fail && !p.getName
  3210. // && !p.dispose && !p.isDisposed
  3211.  
  3212. ) {
  3213. arr = addProtoToArr(_yt_player, k, arr) || arr;
  3214.  
  3215.  
  3216. }
  3217.  
  3218. }
  3219.  
  3220. if (arr.length === 0) {
  3221.  
  3222. console.warn(`Key does not exist. [${w}]`);
  3223. } else {
  3224.  
  3225. console.log(`[${w}]`, arr);
  3226. return arr[0];
  3227. }
  3228.  
  3229. }
  3230.  
  3231. const getZqQu = (_yt_player) => {
  3232.  
  3233. const w = 'ZqQu';
  3234.  
  3235. let arr = [];
  3236.  
  3237.  
  3238. for (const [k, v] of Object.entries(_yt_player)) {
  3239.  
  3240. const p = typeof v === 'function' ? v.prototype : 0;
  3241. if (p
  3242. && typeof p.start === 'function' && p.start.length === 1 // Qu
  3243. && typeof p.isActive === 'function' && p.isActive.length === 0
  3244. && typeof p.stop === 'function' && p.stop.length === 0
  3245. && !p.isComplete && !p.getStatus && !p.getResponseHeader && !p.getLastError
  3246. && !p.send && !p.abort
  3247. && !p.sample && !p.initialize && !p.fail && !p.getName
  3248. // && !p.dispose && !p.isDisposed
  3249.  
  3250. ) {
  3251. arr = addProtoToArr(_yt_player, k, arr) || arr;
  3252.  
  3253.  
  3254. }
  3255.  
  3256. }
  3257.  
  3258. if (arr.length === 0) {
  3259.  
  3260. console.warn(`Key does not exist. [${w}]`);
  3261. } else {
  3262.  
  3263. console.log(`[${w}]`, arr);
  3264. return arr[0];
  3265. }
  3266.  
  3267. }
  3268.  
  3269.  
  3270. const getVG = (_yt_player) => {
  3271. const w = 'VG';
  3272.  
  3273. let arr = [];
  3274.  
  3275. for (const [k, v] of Object.entries(_yt_player)) {
  3276.  
  3277. const p = typeof v === 'function' ? v.prototype : 0;
  3278. if (p
  3279. && typeof p.show === 'function' && p.show.length === 1
  3280. && typeof p.hide === 'function' && p.hide.length === 0
  3281. && typeof p.stop === 'function' && p.stop.length === 0) {
  3282.  
  3283. arr = addProtoToArr(_yt_player, k, arr) || arr;
  3284.  
  3285. }
  3286.  
  3287. }
  3288.  
  3289.  
  3290. if (arr.length === 0) {
  3291.  
  3292. console.warn(`Key does not exist. [${w}]`);
  3293. } else {
  3294.  
  3295. console.log(`[${w}]`, arr);
  3296. return arr[0];
  3297. }
  3298.  
  3299.  
  3300.  
  3301. }
  3302.  
  3303.  
  3304. const getzo = (_yt_player) => {
  3305. const w = 'zo';
  3306.  
  3307. let arr = [];
  3308.  
  3309. for (const [k, v] of Object.entries(_yt_player)) {
  3310.  
  3311. if (
  3312. typeof v === 'function' && v.length === 3 && k.length < 3
  3313. && (v + "").includes("a.style[b]=c")
  3314. ) {
  3315.  
  3316. arr.push(k);
  3317.  
  3318. }
  3319.  
  3320. }
  3321.  
  3322.  
  3323. if (arr.length === 0) {
  3324.  
  3325. console.warn(`Key does not exist. [${w}]`);
  3326. } else {
  3327.  
  3328. console.log(`[${w}]`, arr);
  3329. return arr[0];
  3330. }
  3331.  
  3332. }
  3333.  
  3334. const addProtoToArr = (parent, key, arr) => {
  3335.  
  3336.  
  3337. let isChildProto = false;
  3338. for (const sr of arr) {
  3339. if (parent[key].prototype instanceof parent[sr]) {
  3340. isChildProto = true;
  3341. break;
  3342. }
  3343. }
  3344.  
  3345. if (isChildProto) return;
  3346.  
  3347. arr = arr.filter(sr => {
  3348. if (parent[sr].prototype instanceof parent[key]) {
  3349. return false;
  3350. }
  3351. return true;
  3352. });
  3353.  
  3354. arr.push(key);
  3355.  
  3356. return arr;
  3357.  
  3358.  
  3359. }
  3360.  
  3361. const getuG = (_yt_player) => {
  3362.  
  3363. const w = 'uG';
  3364.  
  3365. let arr = [];
  3366.  
  3367. for (const [k, v] of Object.entries(_yt_player)) {
  3368.  
  3369.  
  3370. const p = typeof v === 'function' ? v.prototype : 0;
  3371.  
  3372. if (p
  3373. && typeof p.createElement === 'function' && p.createElement.length === 2
  3374. && typeof p.detach === 'function' && p.detach.length === 0
  3375. && typeof p.update === 'function' && p.update.length === 1
  3376. && typeof p.updateValue === 'function' && p.updateValue.length === 2
  3377. ) {
  3378.  
  3379. arr = addProtoToArr(_yt_player, k, arr) || arr;
  3380.  
  3381. }
  3382.  
  3383. }
  3384.  
  3385.  
  3386.  
  3387.  
  3388.  
  3389. if (arr.length === 0) {
  3390.  
  3391. console.warn(`Key does not exist. [${w}]`);
  3392. } else {
  3393.  
  3394. console.log(`[${w}]`, arr);
  3395. return arr[0];
  3396. }
  3397.  
  3398. }
  3399.  
  3400.  
  3401. const getQT = (_yt_player) => {
  3402. const w = 'QT';
  3403.  
  3404. let arr = [];
  3405. let brr = new Map();
  3406.  
  3407. for (const [k, v] of Object.entries(_yt_player)) {
  3408.  
  3409. const p = typeof v === 'function' ? v.prototype : 0;
  3410. if (p) {
  3411. let q = 0;
  3412. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 7) q += 400;
  3413. else if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 8) q += 300;
  3414. else if (typeof p.handleGlobalKeyUp === 'function') q += 200;
  3415.  
  3416. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 0) q -= 600; // avoid SV
  3417.  
  3418. if (q < 200) continue; // p.handleGlobalKeyUp must be available
  3419.  
  3420. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 8) q += 80;
  3421. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 7) q += 30;
  3422. if (typeof p.step === 'function' && p.step.length === 1) q += 10;
  3423. if (typeof p.step === 'function' && p.step.length !== 1) q += 5;
  3424.  
  3425.  
  3426. // differentiate QT and DX
  3427.  
  3428. q += 280;
  3429. if (typeof p.cueVideoByPlayerVars === 'function') q += 4;
  3430. if (typeof p.loadVideoByPlayerVars === 'function') q += 4;
  3431. if (typeof p.preloadVideoByPlayerVars === 'function') q += 4;
  3432. if (typeof p.seekBy === 'function') q += 4;
  3433. if (typeof p.seekTo === 'function') q += 4;
  3434. if (typeof p.getStoryboardFormat === 'function') q += 4;
  3435. if (typeof p.getDuration === 'function') q += 4;
  3436. if (typeof p.loadModule === 'function') q += 4;
  3437. if (typeof p.unloadModule === 'function') q += 4;
  3438. if (typeof p.getOption === 'function') q += 4;
  3439. if (typeof p.getOptions === 'function') q += 4;
  3440. if (typeof p.setOption === 'function') q += 4;
  3441. if (typeof p.addCueRange === 'function') q += 4;
  3442. if (typeof p.getDebugText === 'function') q += 4;
  3443. if (typeof p.getCurrentBroadcastId === 'function') q += 4;
  3444. if (typeof p.setSizeStyle === 'function') q += 4;
  3445. if (typeof p.showControls === 'function') q += 4;
  3446. if (typeof p.hideControls === 'function') q += 4;
  3447. if (typeof p.getVideoContentRect === 'function') q += 4;
  3448. if (typeof p.toggleFullscreen === 'function') q += 4;
  3449. if (typeof p.isFullscreen === 'function') q += 4;
  3450. if (typeof p.cancelPlayback === 'function') q += 4;
  3451. if (typeof p.getProgressState === 'function') q += 4;
  3452. if (typeof p.isInline === 'function') q += 4;
  3453. if (typeof p.setInline === 'function') q += 4;
  3454. if (typeof p.toggleSubtitles === 'function') q += 4;
  3455. if (typeof p.getPlayerSize === 'function') q += 4;
  3456. if (typeof p.wakeUpControls === 'function') q += 4;
  3457. if (typeof p.setCenterCrop === 'function') q += 4;
  3458. if (typeof p.getLoopVideo === 'function') q += 4;
  3459. if (typeof p.setLoopVideo === 'function') q += 4;
  3460.  
  3461.  
  3462. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  3463.  
  3464. if (q > 0) brr.set(k, q);
  3465.  
  3466. }
  3467.  
  3468. }
  3469.  
  3470. if (arr.length === 0) {
  3471.  
  3472. console.warn(`Key does not exist. [${w}]`);
  3473. } else {
  3474.  
  3475. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  3476.  
  3477. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  3478.  
  3479. if (arr.length > 2) console.log(`[${w}]`, arr);
  3480. return arr[0][0];
  3481. }
  3482.  
  3483.  
  3484.  
  3485. }
  3486.  
  3487.  
  3488.  
  3489. const getSV = (_yt_player) => {
  3490. const w = 'SV';
  3491.  
  3492. let arr = [];
  3493. let brr = new Map();
  3494.  
  3495. for (const [k, v] of Object.entries(_yt_player)) {
  3496.  
  3497. const p = typeof v === 'function' ? v.prototype : 0;
  3498. if (p) {
  3499. let q = 0;
  3500. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 7) q += 400;
  3501. else if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 8) q += 300;
  3502. else if (typeof p.handleGlobalKeyUp === 'function') q += 200;
  3503.  
  3504. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 0) q += 600; // SV
  3505.  
  3506. if (q < 200) continue; // p.handleGlobalKeyUp must be available
  3507.  
  3508. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 8) q += 80;
  3509. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 7) q += 30;
  3510. if (typeof p.step === 'function' && p.step.length === 1) q += 10;
  3511. if (typeof p.step === 'function' && p.step.length !== 1) q += 5;
  3512.  
  3513.  
  3514. // differentiate QT and DX
  3515.  
  3516.  
  3517. q += 280;
  3518.  
  3519. if (typeof p.cueVideoByPlayerVars === 'function') q -= 4;
  3520. if (typeof p.loadVideoByPlayerVars === 'function') q -= 4;
  3521. if (typeof p.preloadVideoByPlayerVars === 'function') q -= 4;
  3522. if (typeof p.seekBy === 'function') q -= 4;
  3523. if (typeof p.seekTo === 'function') q -= 4;
  3524. if (typeof p.getStoryboardFormat === 'function') q -= 4;
  3525. if (typeof p.getDuration === 'function') q -= 4;
  3526. if (typeof p.loadModule === 'function') q -= 4;
  3527. if (typeof p.unloadModule === 'function') q -= 4;
  3528. if (typeof p.getOption === 'function') q -= 4;
  3529. if (typeof p.getOptions === 'function') q -= 4;
  3530. if (typeof p.setOption === 'function') q -= 4;
  3531. if (typeof p.addCueRange === 'function') q -= 4;
  3532. if (typeof p.getDebugText === 'function') q -= 4;
  3533. if (typeof p.getCurrentBroadcastId === 'function') q -= 4;
  3534. if (typeof p.setSizeStyle === 'function') q -= 4;
  3535. if (typeof p.showControls === 'function') q -= 4;
  3536. if (typeof p.hideControls === 'function') q -= 4;
  3537. if (typeof p.getVideoContentRect === 'function') q -= 4;
  3538. if (typeof p.toggleFullscreen === 'function') q -= 4;
  3539. if (typeof p.isFullscreen === 'function') q -= 4;
  3540. if (typeof p.cancelPlayback === 'function') q -= 4;
  3541. if (typeof p.getProgressState === 'function') q -= 4;
  3542. if (typeof p.isInline === 'function') q -= 4;
  3543. if (typeof p.setInline === 'function') q -= 4;
  3544. if (typeof p.toggleSubtitles === 'function') q -= 4;
  3545. if (typeof p.getPlayerSize === 'function') q -= 4;
  3546. if (typeof p.wakeUpControls === 'function') q -= 4;
  3547. if (typeof p.setCenterCrop === 'function') q -= 4;
  3548. if (typeof p.getLoopVideo === 'function') q -= 4;
  3549. if (typeof p.setLoopVideo === 'function') q -= 4;
  3550.  
  3551.  
  3552. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  3553.  
  3554. if (q > 0) brr.set(k, q);
  3555.  
  3556. }
  3557.  
  3558. }
  3559.  
  3560. if (arr.length === 0) {
  3561.  
  3562. console.warn(`Key does not exist. [${w}]`);
  3563. } else {
  3564.  
  3565. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  3566.  
  3567. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  3568.  
  3569. if (arr.length > 2) console.log(`[${w}]`, arr);
  3570. return arr[0][0];
  3571. }
  3572.  
  3573.  
  3574.  
  3575. }
  3576.  
  3577.  
  3578.  
  3579.  
  3580. const getDX = (_yt_player) => {
  3581. const w = 'DX';
  3582.  
  3583. let arr = [];
  3584. let brr = new Map();
  3585.  
  3586. for (const [k, v] of Object.entries(_yt_player)) {
  3587.  
  3588. const p = typeof v === 'function' ? v.prototype : 0;
  3589. if (p) {
  3590. let q = 0;
  3591. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 7) q += 400;
  3592. else if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 8) q += 300;
  3593. else if (typeof p.handleGlobalKeyUp === 'function') q += 200;
  3594.  
  3595. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 0) q -= 600; // avoid SV
  3596.  
  3597.  
  3598. if (!(typeof p.init === 'function' && p.init.length === 0)) q -= 300; // init is required
  3599.  
  3600. if (q < 200) continue; // p.handleGlobalKeyUp must be available
  3601.  
  3602. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 8) q += 80;
  3603. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 7) q += 30;
  3604. if (typeof p.step === 'function' && p.step.length === 1) q += 10;
  3605. if (typeof p.step === 'function' && p.step.length !== 1) q += 5;
  3606.  
  3607.  
  3608. // differentiate QT and DX
  3609.  
  3610.  
  3611. q += 280;
  3612.  
  3613. if (typeof p.cueVideoByPlayerVars === 'function') q -= 4;
  3614. if (typeof p.loadVideoByPlayerVars === 'function') q -= 4;
  3615. if (typeof p.preloadVideoByPlayerVars === 'function') q -= 4;
  3616. if (typeof p.seekBy === 'function') q -= 4;
  3617. if (typeof p.seekTo === 'function') q -= 4;
  3618. if (typeof p.getStoryboardFormat === 'function') q -= 4;
  3619. if (typeof p.getDuration === 'function') q -= 4;
  3620. if (typeof p.loadModule === 'function') q -= 4;
  3621. if (typeof p.unloadModule === 'function') q -= 4;
  3622. if (typeof p.getOption === 'function') q -= 4;
  3623. if (typeof p.getOptions === 'function') q -= 4;
  3624. if (typeof p.setOption === 'function') q -= 4;
  3625. if (typeof p.addCueRange === 'function') q -= 4;
  3626. if (typeof p.getDebugText === 'function') q -= 4;
  3627. if (typeof p.getCurrentBroadcastId === 'function') q -= 4;
  3628. if (typeof p.setSizeStyle === 'function') q -= 4;
  3629. if (typeof p.showControls === 'function') q -= 4;
  3630. if (typeof p.hideControls === 'function') q -= 4;
  3631. if (typeof p.getVideoContentRect === 'function') q -= 4;
  3632. if (typeof p.toggleFullscreen === 'function') q -= 4;
  3633. if (typeof p.isFullscreen === 'function') q -= 4;
  3634. if (typeof p.cancelPlayback === 'function') q -= 4;
  3635. if (typeof p.getProgressState === 'function') q -= 4;
  3636. if (typeof p.isInline === 'function') q -= 4;
  3637. if (typeof p.setInline === 'function') q -= 4;
  3638. if (typeof p.toggleSubtitles === 'function') q -= 4;
  3639. if (typeof p.getPlayerSize === 'function') q -= 4;
  3640. if (typeof p.wakeUpControls === 'function') q -= 4;
  3641. if (typeof p.setCenterCrop === 'function') q -= 4;
  3642. if (typeof p.getLoopVideo === 'function') q -= 4;
  3643. if (typeof p.setLoopVideo === 'function') q -= 4;
  3644.  
  3645.  
  3646. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  3647.  
  3648. if (q > 0) brr.set(k, q);
  3649.  
  3650. }
  3651.  
  3652. }
  3653.  
  3654. if (arr.length === 0) {
  3655.  
  3656. console.warn(`Key does not exist. [${w}]`);
  3657. } else {
  3658.  
  3659. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  3660.  
  3661. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  3662.  
  3663. if (arr.length > 2) console.log(`[${w}]`, arr);
  3664. return arr[0][0];
  3665. }
  3666.  
  3667.  
  3668.  
  3669. }
  3670.  
  3671.  
  3672.  
  3673. const isPrepareCachedV = (FIX_avoid_incorrect_video_meta ? true : false) && (window === top);
  3674.  
  3675. let pageSetupVideoId = null; // set at finish; '' for indeterminate state
  3676. let pageSetupState = 0;
  3677.  
  3678. isPrepareCachedV && (() => {
  3679.  
  3680. pageSetupVideoId = '';
  3681. const clearCachedV = () => {
  3682. pageSetupVideoId = '';
  3683. pageSetupState = 0;
  3684. }
  3685. document.addEventListener('yt-navigate-start', clearCachedV, false); // user action
  3686. document.addEventListener('yt-navigate-cache', clearCachedV, false); // pop state
  3687. document.addEventListener('yt-page-data-fetched', clearCachedV, false); // still consider invalid until url is ready in yt-navigate-finish
  3688. document.addEventListener('yt-navigate-finish', () => {
  3689. pageSetupState = 1;
  3690. try {
  3691. const url = new URL(location.href);
  3692. if (!url || url.pathname !== '/watch') {
  3693. pageSetupVideoId = '';
  3694. } else {
  3695. pageSetupVideoId = url.searchParams.get('v') || '';
  3696. }
  3697. } catch (e) {
  3698. pageSetupVideoId = '';
  3699. }
  3700. }, false);
  3701.  
  3702. })();
  3703.  
  3704. let videoPlayingY = null;
  3705.  
  3706. isPrepareCachedV && (() => {
  3707.  
  3708. let getNext = true;
  3709. let videoPlayingX = {
  3710. get videoId() {
  3711. if (getNext) {
  3712. getNext = false;
  3713.  
  3714. let elements = document.querySelectorAll('ytd-watch-flexy[video-id]');
  3715. const arr = [];
  3716. for (const element of elements) {
  3717. if (!element.closest('[hidden]')) arr.push(element);
  3718. }
  3719. if (arr.length !== 1) this.__videoId__ = '';
  3720. else {
  3721. this.__videoId__ = arr[0].getAttribute('video-id');
  3722. }
  3723.  
  3724. }
  3725. return this.__videoId__ || '';
  3726. }
  3727. }
  3728.  
  3729. videoPlayingY = videoPlayingX;
  3730. const handler = (evt) => {
  3731. const target = (evt || 0).target;
  3732. if (target instanceof HTMLVideoElement) {
  3733. getNext = true;
  3734. }
  3735. }
  3736. document.addEventListener('loadedmetadata', handler, true);
  3737. document.addEventListener('durationchange', handler, true);
  3738.  
  3739. })();
  3740.  
  3741.  
  3742.  
  3743. const cleanContext = async (win) => {
  3744. const waitFn = requestAnimationFrame; // shall have been binded to window
  3745. try {
  3746. let mx = 16; // MAX TRIAL
  3747. const frameId = 'vanillajs-iframe-v1';
  3748. /** @type {HTMLIFrameElement | null} */
  3749. let frame = document.getElementById(frameId);
  3750. let removeIframeFn = null;
  3751. if (!frame) {
  3752. frame = document.createElement('iframe');
  3753. frame.id = frameId;
  3754. const blobURL = typeof webkitCancelAnimationFrame === 'function' ? (frame.src = URL.createObjectURL(new Blob([], { type: 'text/html' }))) : null; // avoid Brave Crash
  3755. frame.sandbox = 'allow-same-origin'; // script cannot be run inside iframe but API can be obtained from iframe
  3756. let n = document.createElement('noscript'); // wrap into NOSCRPIT to avoid reflow (layouting)
  3757. n.appendChild(frame);
  3758. while (!document.documentElement && mx-- > 0) await new Promise(waitFn); // requestAnimationFrame here could get modified by YouTube engine
  3759. const root = document.documentElement;
  3760. root.appendChild(n); // throw error if root is null due to exceeding MAX TRIAL
  3761. if (blobURL) Promise.resolve().then(() => URL.revokeObjectURL(blobURL));
  3762.  
  3763. removeIframeFn = (setTimeout) => {
  3764. const removeIframeOnDocumentReady = (e) => {
  3765. e && win.removeEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  3766. e = n;
  3767. n = win = removeIframeFn = 0;
  3768. setTimeout ? setTimeout(() => e.remove(), 200) : e.remove();
  3769. }
  3770. if (!setTimeout || document.readyState !== 'loading') {
  3771. removeIframeOnDocumentReady();
  3772. } else {
  3773. win.addEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  3774. }
  3775. }
  3776. }
  3777. while (!frame.contentWindow && mx-- > 0) await new Promise(waitFn);
  3778. const fc = frame.contentWindow;
  3779. if (!fc) throw "window is not found."; // throw error if root is null due to exceeding MAX TRIAL
  3780. try {
  3781. const { requestAnimationFrame, setTimeout, clearTimeout, cancelAnimationFrame, setInterval, clearInterval, requestIdleCallback, getComputedStyle } = fc;
  3782. const res = { requestAnimationFrame, setTimeout, clearTimeout, cancelAnimationFrame, setInterval, clearInterval, requestIdleCallback, getComputedStyle };
  3783. for (let k in res) res[k] = res[k].bind(win); // necessary
  3784. if (removeIframeFn) Promise.resolve(res.setTimeout).then(removeIframeFn);
  3785. res.animate = fc.HTMLElement.prototype.animate;
  3786. res.perfNow = fc.performance.now;
  3787. return res;
  3788. } catch (e) {
  3789. if (removeIframeFn) removeIframeFn();
  3790. return null;
  3791. }
  3792. } catch (e) {
  3793. console.warn(e);
  3794. return null;
  3795. }
  3796. };
  3797.  
  3798. const promiseForYtActionCalled = new Promise(resolve => {
  3799. if (typeof AbortSignal !== 'undefined') {
  3800. let hn = () => {
  3801. if (!hn) return;
  3802. hn = null;
  3803. resolve(document.querySelector('ytd-app'));
  3804. };
  3805. document.addEventListener('yt-action', hn, { capture: true, passive: true, once: true });
  3806. } else {
  3807. let hn = () => {
  3808. if (!hn) return;
  3809. document.removeEventListener('yt-action', hn, true);
  3810. hn = null;
  3811. resolve(document.querySelector('ytd-app'));
  3812. };
  3813. document.addEventListener('yt-action', hn, true);
  3814. }
  3815. });
  3816.  
  3817.  
  3818.  
  3819. cleanContext(window).then(__CONTEXT__ => {
  3820. if (!__CONTEXT__) return null;
  3821.  
  3822. const { requestAnimationFrame, setTimeout, clearTimeout, cancelAnimationFrame, setInterval, clearInterval, animate, requestIdleCallback, getComputedStyle, perfNow } = __CONTEXT__;
  3823.  
  3824.  
  3825. performance.now17 = perfNow.bind(performance);
  3826.  
  3827.  
  3828.  
  3829. __requestAnimationFrame__ = requestAnimationFrame;
  3830.  
  3831. let rafPromise = null;
  3832.  
  3833. const getRafPromise = () => rafPromise || (rafPromise = new Promise(resolve => {
  3834. requestAnimationFrame(hRes => {
  3835. rafPromise = null;
  3836. resolve(hRes);
  3837. });
  3838. }));
  3839.  
  3840.  
  3841. const wmComputedStyle = new WeakMap();
  3842.  
  3843. if (!window.__native__getComputedStyle__ && !window.__jst__getComputedStyle__ && typeof window.getComputedStyle === 'function' && window.getComputedStyle.length === 1) {
  3844. window.__native__getComputedStyle__ = getComputedStyle;
  3845. if (ENABLE_COMPUTEDSTYLE_CACHE) {
  3846. window.__original__getComputedStyle__ = window.getComputedStyle;
  3847. window.getComputedStyle = function (elem) {
  3848. if (!(elem instanceof Element) || (arguments.length === 2 && arguments[1]) || (arguments.length > 2)) {
  3849. return window.__native__getComputedStyle__(...arguments);
  3850. }
  3851. let cs = wmComputedStyle.get(elem);
  3852. if (!cs) {
  3853. cs = window.__native__getComputedStyle__(elem);
  3854. wmComputedStyle.set(elem, cs);
  3855. }
  3856. return cs;
  3857. };
  3858. } else {
  3859. window.__original__getComputedStyle__ = null;
  3860. }
  3861. window.__jst__getComputedStyle__ = window.getComputedStyle;
  3862. }
  3863.  
  3864. NO_SCHEDULING_DUE_TO_COMPUTEDSTYLE && promiseForYtActionCalled.then(() => {
  3865. if (typeof window.__jst__getComputedStyle__ === 'function' && window.__jst__getComputedStyle__.length === 1 && window.__jst__getComputedStyle__ !== window.getComputedStyle) {
  3866. window.getComputedStyle = window.__jst__getComputedStyle__;
  3867. }
  3868. });
  3869.  
  3870. const isUrlInEmbed = location.href.includes('.youtube.com/embed/');
  3871. const isAbortSignalSupported = typeof AbortSignal !== "undefined";
  3872.  
  3873. const promiseForTamerTimeout = new Promise(resolve => {
  3874. !isUrlInEmbed && isAbortSignalSupported && document.addEventListener('yt-action', function () {
  3875. setTimeout(resolve, 480);
  3876. }, { capture: true, passive: true, once: true });
  3877. !isUrlInEmbed && isAbortSignalSupported && typeof customElements === "object" && whenCEDefined('ytd-app').then(() => {
  3878. setTimeout(resolve, 1200);
  3879. });
  3880. setTimeout(resolve, 3000);
  3881. });
  3882.  
  3883. const promiseForPageInitied = new Promise(resolve => {
  3884. !isUrlInEmbed && isAbortSignalSupported && document.addEventListener('yt-action', function () {
  3885. setTimeout(resolve, 450);
  3886. }, { capture: true, passive: true, once: true });
  3887. !isUrlInEmbed && isAbortSignalSupported && typeof customElements === "object" && whenCEDefined('ytd-app').then(() => {
  3888. setTimeout(resolve, 900);
  3889. });
  3890. setTimeout(resolve, 1800);
  3891. });
  3892.  
  3893. NO_PRELOAD_GENERATE_204_BYPASS || promiseForPageInitied.then(() => {
  3894. NO_PRELOAD_GENERATE_204_BYPASS = true;
  3895. headLinkCollection = null;
  3896. });
  3897.  
  3898.  
  3899. NATIVE_CANVAS_ANIMATION && (() => {
  3900.  
  3901. observablePromise(() => {
  3902. HTMLCanvasElement.prototype.animate = animate;
  3903. }, promiseForTamerTimeout).obtain();
  3904.  
  3905. })();
  3906.  
  3907. FIX_ytAction_ && (async () => {
  3908.  
  3909. const ytdApp = await new Promise(resolve => {
  3910.  
  3911. whenCEDefined('ytd-app').then(() => {
  3912. const ytdApp = document.querySelector('ytd-app');
  3913. if (ytdApp) {
  3914. resolve(ytdApp);
  3915. return;
  3916. }
  3917. let mo = new MutationObserver(() => {
  3918. const ytdApp = document.querySelector('ytd-app');
  3919. if (!ytdApp) return;
  3920. if (mo) {
  3921. mo.disconnect();
  3922. mo.takeRecords();
  3923. mo = null;
  3924. }
  3925. resolve(ytdApp);
  3926. });
  3927. mo.observe(document, { subtree: true, childList: true });
  3928. });
  3929.  
  3930. });
  3931.  
  3932. if (!ytdApp) return;
  3933. const cProto = insp(ytdApp).constructor.prototype;
  3934.  
  3935. if (!cProto) return;
  3936. let mbd = 0;
  3937.  
  3938. const fixer = (_ytdApp) => {
  3939. const ytdApp = insp(_ytdApp);
  3940. if (ytdApp && typeof ytdApp.onYtActionBoundListener_ === 'function' && !ytdApp.onYtActionBoundListener57_) {
  3941. ytdApp.onYtActionBoundListener57_ = ytdApp.onYtActionBoundListener_;
  3942. ytdApp.onYtActionBoundListener_ = ytdApp.onYtAction_.bind(ytdApp);
  3943. mbd++;
  3944. }
  3945. }
  3946.  
  3947. observablePromise(() => {
  3948.  
  3949. if (typeof cProto.created === 'function' && !cProto.created56) {
  3950. cProto.created56 = cProto.created;
  3951. cProto.created = function (...args) {
  3952. const r = this.created56(...args);
  3953. fixer(this);
  3954. return r;
  3955. };
  3956. mbd++;
  3957. }
  3958.  
  3959. if (typeof cProto.onYtAction_ === 'function' && !cProto.onYtAction57_) {
  3960. cProto.onYtAction57_ = cProto.onYtAction_;
  3961. cProto.onYtAction_ = function (...args) {
  3962. Promise.resolve().then(() => this.onYtAction57_(...args));
  3963. };
  3964. mbd++;
  3965. }
  3966.  
  3967. if (ytdApp) fixer(ytdApp);
  3968.  
  3969. /*
  3970. const actionRouter_ = ytdApp ? ytdApp.actionRouter_ : null;
  3971. if (actionRouter_ && typeof actionRouter_.handleAction === 'function' && !actionRouter_.handleAction57) {
  3972. actionRouter_.handleAction57 = actionRouter_.handleAction;
  3973. actionRouter_.handleAction = function (...args) {
  3974. Promise.resolve().then(() => this.handleAction57(...args));
  3975. }
  3976. mbd++;
  3977. }
  3978. */
  3979.  
  3980. // if(mbd === 3) return 1;
  3981. if (mbd >= 3) return 1;
  3982.  
  3983. }, new Promise(r => setTimeout(r, 1000))).obtain();
  3984.  
  3985. })();
  3986.  
  3987. const observablePromise = (proc, timeoutPromise) => {
  3988. let promise = null;
  3989. return {
  3990. obtain() {
  3991. if (!promise) {
  3992. promise = new Promise(resolve => {
  3993. let mo = null;
  3994. const f = () => {
  3995. let t = proc();
  3996. if (t) {
  3997. mo.disconnect();
  3998. mo.takeRecords();
  3999. mo = null;
  4000. resolve(t);
  4001. }
  4002. }
  4003. mo = new MutationObserver(f);
  4004. mo.observe(document, { subtree: true, childList: true })
  4005. f();
  4006. timeoutPromise && timeoutPromise.then(() => {
  4007. resolve(null)
  4008. });
  4009. });
  4010. }
  4011. return promise
  4012. }
  4013. }
  4014. }
  4015.  
  4016. // let _yt_player_promise = null;
  4017. /*
  4018. const getYtPlayerPromise = () => {
  4019. if (!_yt_player_promise) {
  4020. _yt_player_promise = new Promise(resolve => {
  4021. let cid = setInterval(() => {
  4022. let t = (((window || 0)._yt_player || 0) || 0);
  4023. if (t) {
  4024. clearInterval(cid);
  4025. resolve(t);
  4026. }
  4027. }, 1);
  4028. promiseForTamerTimeout.then(() => {
  4029. resolve(null)
  4030. });
  4031. });
  4032. }
  4033. return _yt_player_promise;
  4034. }
  4035. */
  4036. const _yt_player_observable = observablePromise(() => {
  4037. return (((window || 0)._yt_player || 0) || 0);
  4038. }, promiseForTamerTimeout);
  4039.  
  4040. const polymerObservable = observablePromise(() => {
  4041. const Polymer = window.Polymer;
  4042. if (typeof Polymer !== 'function') return;
  4043. if (!(Polymer.Base || 0).connectedCallback || !(Polymer.Base || 0).disconnectedCallback) return;
  4044. return Polymer;
  4045. }, promiseForTamerTimeout);
  4046.  
  4047. const schedulerInstanceObservable = observablePromise(() => {
  4048. return (((window || 0).ytglobal || 0).schedulerInstanceInstance_ || 0);
  4049. }, promiseForTamerTimeout);
  4050.  
  4051. const timelineObservable = observablePromise(() => {
  4052. let t = (((document || 0).timeline || 0) || 0);
  4053. if (t && typeof t._play === 'function') {
  4054. return t;
  4055. }
  4056. }, promiseForTamerTimeout);
  4057. const animationObservable = observablePromise(() => {
  4058. let t = (((window || 0).Animation || 0) || 0);
  4059. if (t && typeof t === 'function' && t.length === 2 && typeof t.prototype._updatePromises === 'function') {
  4060. return t;
  4061. }
  4062. }, promiseForTamerTimeout);
  4063.  
  4064.  
  4065.  
  4066.  
  4067. const generalEvtHandler = async (_evKey, _fvKey, _debug) => {
  4068.  
  4069. const evKey = `${_evKey}`;
  4070. const fvKey = `${_fvKey}`;
  4071. const debug = !!_debug;
  4072.  
  4073. const _yt_player = await _yt_player_observable.obtain();
  4074.  
  4075.  
  4076. if (!_yt_player || typeof _yt_player !== 'object') return;
  4077.  
  4078.  
  4079. const getArr = (_yt_player) => {
  4080.  
  4081. let arr = [];
  4082.  
  4083. for (const [k, v] of Object.entries(_yt_player)) {
  4084.  
  4085. const p = typeof v === 'function' ? v.prototype : 0;
  4086. if (p
  4087. && typeof p[evKey] === 'function' && p[evKey].length >= 0 && !p[fvKey]
  4088.  
  4089. ) {
  4090. arr = addProtoToArr(_yt_player, k, arr) || arr;
  4091.  
  4092. }
  4093.  
  4094. }
  4095.  
  4096. if (arr.length === 0) {
  4097.  
  4098. console.warn(`Key prop [${evKey}] does not exist.`);
  4099. } else {
  4100.  
  4101. return arr;
  4102. }
  4103.  
  4104. };
  4105.  
  4106. const arr = getArr(_yt_player);
  4107.  
  4108.  
  4109. if (!arr) return;
  4110.  
  4111. debug && console.log(`FIX_${evKey}`, arr);
  4112.  
  4113. const f = function (...args) {
  4114. Promise.resolve().then(() => this[fvKey](...args));
  4115. };
  4116.  
  4117.  
  4118. for (const k of arr) {
  4119.  
  4120. const g = _yt_player;
  4121. const gk = g[k];
  4122. const gkp = gk.prototype;
  4123.  
  4124. debug && console.log(237, k, gkp)
  4125.  
  4126. if (typeof gkp[evKey] == 'function' && !gkp[fvKey]) {
  4127. gkp[fvKey] = gkp[evKey];
  4128. gkp[evKey] = f;
  4129. }
  4130. }
  4131.  
  4132.  
  4133.  
  4134.  
  4135. }
  4136.  
  4137. FIX_onVideoDataChange && generalEvtHandler('onVideoDataChange', 'onVideoDataChange57');
  4138. // FIX_onClick && generalEvtHandler('onClick', 'onClick57');
  4139. FIX_onStateChange && generalEvtHandler('onStateChange', 'onStateChange57');
  4140. FIX_onLoopRangeChange && generalEvtHandler('onLoopRangeChange', 'onLoopRangeChange57');
  4141. if (FIX_VideoEVENTS_v2) {
  4142. const FIX_VideoEVENTS_DEBUG = 0;
  4143. generalEvtHandler('onVideoProgress', 'onVideoProgress57', FIX_VideoEVENTS_DEBUG); // --
  4144. // generalEvtHandler('onAutoplayBlocked', 'onAutoplayBlocked57', FIX_VideoEVENTS_DEBUG);
  4145. // generalEvtHandler('onLoadProgress', 'onLoadProgress57', FIX_VideoEVENTS_DEBUG); // << CAUSE ISSUE >>
  4146. generalEvtHandler('onFullscreenChange', 'onFullscreenChange57', FIX_VideoEVENTS_DEBUG); // --
  4147. // generalEvtHandler('onLoadedMetadata', 'onLoadedMetadata57', FIX_VideoEVENTS_DEBUG);
  4148. // generalEvtHandler('onDrmOutputRestricted', 'onDrmOutputRestricted57', FIX_VideoEVENTS_DEBUG);
  4149. // generalEvtHandler('onAirPlayActiveChange', 'onAirPlayActiveChange57', FIX_VideoEVENTS_DEBUG);
  4150. // generalEvtHandler('onAirPlayAvailabilityChange', 'onAirPlayAvailabilityChange57', FIX_VideoEVENTS_DEBUG);
  4151. // generalEvtHandler('onApiChange', 'onApiChange57', FIX_VideoEVENTS_DEBUG);
  4152.  
  4153. }
  4154. // onMutedAutoplayChange
  4155. // onVolumeChange
  4156. // onPlaybackRateChange
  4157.  
  4158. // onAirPlayActiveChange
  4159. // onAirPlayAvailabilityChange
  4160. // onApiChange
  4161. // onAutoplayBlocked
  4162. // onDrmOutputRestricted
  4163. // onFullscreenChange
  4164. // onLoadProgress
  4165. // onLoadedMetadata
  4166. // onVideoDataChange
  4167. // onVideoProgress
  4168.  
  4169.  
  4170. (ENABLE_discreteTasking || UNLOAD_DETACHED_POLYMER) && (async () => {
  4171.  
  4172. const Polymer = await polymerObservable.obtain();
  4173. if (!Polymer) return;
  4174.  
  4175.  
  4176. if (UNLOAD_DETACHED_POLYMER && typeof Polymer.Base.detached === 'function' && !Polymer.Base.detached92 && Polymer.Base.detached.length === 0) {
  4177. Polymer.Base.detached92 = Polymer.Base.detached;
  4178.  
  4179. const detachedPlus = async function (elem) {
  4180. await delay300.then();
  4181. if (elem.isAttached !== false) return;
  4182. await delay300.then();
  4183. if (elem.isAttached !== false) return;
  4184.  
  4185. if (elem.__dataClientsReady === true) elem.__dataClientsReady = false;
  4186. // if (elem.__dataEnabled === true) elem.__dataEnabled = false;
  4187. if (elem.__dataReady === true) elem.__dataReady = false;
  4188.  
  4189. elem.__dataLinkedPaths = elem.__dataToNotify = elem.__dataPendingClients = null;
  4190. elem.__dataHasPaths = false;
  4191. // elem.__dataCompoundStorage = null;
  4192. elem.__dataHost = null;
  4193. elem.__dataTemp = null;
  4194. elem.__dataClientsInitialized = false;
  4195.  
  4196.  
  4197. // elem.data = {};
  4198. elem.data = null;
  4199. elem.__dataPending = null;
  4200. elem.__dataOld = null;
  4201. elem.__dataInstanceProps = null;
  4202.  
  4203. elem.__dataCounter = 0;
  4204. elem.__serializing = false;
  4205.  
  4206. }
  4207. Polymer.Base.detached = function () {
  4208. Promise.resolve(this).then(detachedPlus);
  4209. return Polymer.Base.detached92();
  4210. };
  4211. }
  4212.  
  4213.  
  4214. if (ENABLE_discreteTasking) {
  4215.  
  4216. Polymer.Base.__connInit__ = function () {
  4217. setupDiscreteTasks(this);
  4218. // if (WEAK_REF_BINDING && (this.is || this instanceof Node)) {
  4219. // setupWeakRef(this)
  4220. // }
  4221. }
  4222.  
  4223.  
  4224. /** @type {Function} */
  4225. const connectedCallbackK = function (...args) {
  4226. !this.mh35 && typeof this.__connInit__ === 'function' && this.__connInit__();
  4227. const r = this[qm53](...args);
  4228. !this.mh35 && typeof this.__connInit__ === 'function' && this.__connInit__();
  4229. this.mh35 = 1;
  4230. return r;
  4231. };
  4232.  
  4233. connectedCallbackK.m353 = 1;
  4234.  
  4235.  
  4236. const qt53 = Polymer.Base.connectedCallback;
  4237. Polymer.Base[qm53] = dmf.get(qt53) || qt53;
  4238.  
  4239. Polymer.Base.connectedCallback = connectedCallbackK;
  4240.  
  4241.  
  4242. /** @type {Function} */
  4243. const createdK = function (...args) {
  4244. !this.mh36 && typeof this.__connInit__ === 'function' && this.__connInit__();
  4245. const r = this[qn53](...args);
  4246. !this.mh36 && typeof this.__connInit__ === 'function' && this.__connInit__();
  4247. this.mh36 = 1;
  4248. return r;
  4249. };
  4250.  
  4251.  
  4252. createdK.m353 = 1;
  4253. Polymer.Base[qn53] = Polymer.Base.created;
  4254. Polymer.Base.created = createdK;
  4255.  
  4256. }
  4257.  
  4258. })();
  4259.  
  4260.  
  4261. /*
  4262.  
  4263. e.nativeAppendChild = d.prototype.appendChild,
  4264. d.prototype.appendChild = function(h) {
  4265. return function(l) {
  4266. if (l instanceof DocumentFragment) {
  4267. var m = Array.from(l.children);
  4268. l = h.nativeAppendChild.call(this, l);
  4269. if (this.isConnected) {
  4270. m = g(m);
  4271. for (var p = m.next(); !p.done; p = m.next())
  4272. YD(p.value)
  4273. }
  4274. return l
  4275. }
  4276. m = l instanceof Element && l.isConnected;
  4277. p = h.nativeAppendChild.call(this, l);
  4278. m && ZD(l);
  4279. this.isConnected && YD(l);
  4280. return p
  4281. }
  4282. }(e),
  4283.  
  4284. */
  4285.  
  4286. CHANGE_appendChild && !Node.prototype.appendChild73 && Node.prototype.appendChild && (() => {
  4287.  
  4288. let __src__ = '';
  4289. const handlerCanplay = (evt) => {
  4290. const a = evt.target;
  4291. console.log('[yt-js-engine-tamer]', `video element added to dom | canplay`, mWeakRef(a), a.readyState, a.networkState, a.currentTime);
  4292. if (a.currentTime < 1e-8 && a.currentTime > -1e-9 && a.autoplay === false) a.currentTime += 1e-8;
  4293. };
  4294.  
  4295. const handlerTimeupdate = (evt) => {
  4296. const a = evt.target;
  4297. console.log('[yt-js-engine-tamer]', `video element added to dom | ontimeupdate`, mWeakRef(a), a.readyState, a.networkState, a.currentTime);
  4298. if (a.duration < 2.01 && a.duration > 1.99 && a.currentSrc === __src__) {
  4299. try {
  4300. URL.revokeObjectURL(__src__);
  4301. __src__ = '';
  4302. } finally {
  4303. console.log('[yt-js-engine-tamer]', `video element added to dom | revokeObjectURL`, mWeakRef(a), a.readyState, a.networkState, a.currentTime);
  4304. }
  4305. }
  4306. };
  4307.  
  4308. const f = Node.prototype.appendChild73 = Node.prototype.appendChild;
  4309. if (f) Node.prototype.appendChild = function (a) {
  4310. if (this instanceof Element) { // exclude DocumentFragment
  4311. try {
  4312. if (a instanceof HTMLVideoElement && FIX_VIDEO_BLOCKING) {
  4313. const src = `${a.src}`;
  4314. const b = src.length > 5 && src.startsWith('blob:') && typeof a.ontimeupdate === 'function' && a.autoplay === false && a.paused === true && a.isConnected === false && typeof nextBrowserTick === 'function' && typeof AbortSignal !== 'undefined';
  4315. if (b) {
  4316. __src__ = src;
  4317. a.addEventListener('canplay', handlerCanplay, { once: true, passive: true, capture: false });
  4318. a.addEventListener('timeupdate', handlerTimeupdate, { once: true, passive: true, capture: false });
  4319. }
  4320. console.log('[yt-js-engine-tamer]', `video element added to dom | treatment = ${b}`, mWeakRef(a), a.readyState, a.networkState);
  4321. } else {
  4322. let checkFragmentA = true;
  4323. if (!NO_PRELOAD_GENERATE_204_BYPASS && document.head === this) {
  4324. if (headLinkCollection === null) headLinkCollection = document.head.getElementsByTagName('LINK');
  4325. for (const node of headLinkCollection) {
  4326. if (node.rel === 'preload' && node.as === 'fetch') {
  4327. node.rel = 'prefetch'; // see https://github.com/GoogleChromeLabs/quicklink
  4328. }
  4329. }
  4330. } else if (this.nodeName.startsWith('YT-')) { // yt-animated-rolling-number, yt-attributed-string
  4331. checkFragmentA = false;
  4332. }
  4333. if ((a instanceof DocumentFragment) && checkFragmentA && a.firstElementChild === null) {
  4334. // no element in fragmentA
  4335. let doNormal = false;
  4336. for (let child = a.firstChild; child instanceof Node; child = child.nextSibling) {
  4337. if (child.nodeType === 3) { doNormal = true; break; }
  4338. }
  4339. if (!doNormal) return a;
  4340. }
  4341. }
  4342. } catch (e) {
  4343. console.log(e);
  4344. }
  4345. }
  4346. return arguments.length === 1 && this.appendChild73 ? this.appendChild73(a) : (this.appendChild73 || Node.prototype.appendChild73 || f).apply(this, arguments);
  4347. }
  4348.  
  4349.  
  4350. })();
  4351.  
  4352. if (FIX_Shady) {
  4353.  
  4354. observablePromise(() => {
  4355. const { ShadyDOM, ShadyCSS } = window;
  4356. if (ShadyDOM) {
  4357. ShadyDOM.handlesDynamicScoping = false; // 9 of 10
  4358. ShadyDOM.noPatch = true; // 1 of 10
  4359. ShadyDOM.patchOnDemand = false; // 1 of 10
  4360. ShadyDOM.preferPerformance = true; // 1 of 10
  4361. ShadyDOM.querySelectorImplementation = undefined; // 1 of 10
  4362. }
  4363. if (ShadyCSS) {
  4364. ShadyCSS.nativeCss = true; // 1 of 10
  4365. ShadyCSS.nativeShadow = true; // 6 of 10
  4366. ShadyCSS.cssBuild = undefined; // 1 of 10
  4367. ShadyCSS.disableRuntime = true; // 1 of 10
  4368. }
  4369. if (ShadyDOM && ShadyCSS) return 1;
  4370. }, promiseForTamerTimeout).obtain(); // clear until 1 is return
  4371.  
  4372. }
  4373.  
  4374.  
  4375. // let schedulerInstancePropOfTimerType = '';
  4376. // let schedulerInstancePropOfTimerId = '';
  4377. (FIX_schedulerInstanceInstance & 2) && (async () => {
  4378.  
  4379. const schedulerInstanceInstance_ = await schedulerInstanceObservable.obtain();
  4380.  
  4381. if (!schedulerInstanceInstance_) return;
  4382.  
  4383. const checkOK = typeof schedulerInstanceInstance_.start === 'function' && !schedulerInstanceInstance_.start993 && !schedulerInstanceInstance_.stop && !schedulerInstanceInstance_.cancel && !schedulerInstanceInstance_.terminate && !schedulerInstanceInstance_.interupt;
  4384. if (checkOK) {
  4385.  
  4386. schedulerInstanceInstance_.start993 = schedulerInstanceInstance_.start;
  4387.  
  4388. let requestingFn = null;
  4389. let requestingArgs = null;
  4390.  
  4391. const f = function () {
  4392. requestingFn = this.fn;
  4393. requestingArgs = [...arguments];
  4394. return 12373;
  4395. };
  4396.  
  4397. const fakeFns = [
  4398. f.bind({ fn: requestAnimationFrame }),
  4399. f.bind({ fn: setInterval }),
  4400. f.bind({ fn: setTimeout }),
  4401. f.bind({ fn: requestIdleCallback })
  4402. ];
  4403.  
  4404. let mzt = 0;
  4405.  
  4406. let _fnSelectorProp = null;
  4407. const mkFns = new Array(4);
  4408.  
  4409. /*
  4410. case 1:
  4411. var a = this.K;
  4412. this.g = this.I ? window.requestIdleCallback(a, {
  4413. timeout: 3E3
  4414. }) : window.setTimeout(a, ma);
  4415. break;
  4416. case 2:
  4417. this.g = window.setTimeout(this.M, this.N);
  4418. break;
  4419. case 3:
  4420. this.g = window.requestAnimationFrame(this.L);
  4421. break;
  4422. case 4:
  4423. this.g = window.setTimeout(this.J, 0)
  4424. }
  4425.  
  4426. */
  4427. const startFnHandler = {
  4428. get(target, prop, receiver) {
  4429. if (prop === '$$12377$$') return true;
  4430. if (prop === '$$12378$$') return target;
  4431.  
  4432. // console.log('get',prop)
  4433. return target[prop]
  4434. },
  4435. set(target, prop, value, receiver) {
  4436. // console.log('set', prop, value)
  4437.  
  4438. if (value >= 1 && value <= 4) _fnSelectorProp = prop;
  4439. if (value === 12373 && _fnSelectorProp) {
  4440.  
  4441. const schedulerTypeSelection = target[_fnSelectorProp];
  4442. const timerIdProp = prop;
  4443.  
  4444. // if (schedulerTypeSelection && schedulerTypeSelection >= 1 && schedulerTypeSelection <= 4 && timerIdProp) {
  4445. // schedulerInstancePropOfTimerType = _fnSelectorProp || '';
  4446. // schedulerInstancePropOfTimerId = timerIdProp || '';
  4447. // }
  4448.  
  4449. if (schedulerTypeSelection === 3 && requestingFn === requestAnimationFrame) { // rAF(fn)
  4450. target[timerIdProp] = baseRAF.apply(window, requestingArgs);
  4451. } else if (schedulerTypeSelection === 2 && requestingFn === setTimeout) { // setTimeout(fn, delay)
  4452. // rare
  4453. target[timerIdProp] = mkFns[2].apply(window, requestingArgs);
  4454. } else if (schedulerTypeSelection === 4 && requestingFn === setTimeout && !requestingArgs[1]) { // setTimeout(fn, 0)
  4455. // often
  4456. if ((FIX_schedulerInstanceInstance & 4) && typeof nextBrowserTick == 'function') {
  4457. const f = requestingArgs[0];
  4458. const tir = ++mzt;
  4459. nextBrowserTick(() => {
  4460. if (target[timerIdProp] === -tir) f();
  4461. });
  4462. target[_fnSelectorProp] = 940;
  4463. target[timerIdProp] = -tir;
  4464. } else {
  4465. const f = requestingArgs[0];
  4466. const tir = ++mzt;
  4467. Promise.resolve().then(() => {
  4468. if (target[timerIdProp] === -tir) f();
  4469. });
  4470. target[_fnSelectorProp] = 930;
  4471. target[timerIdProp] = -tir;
  4472. }
  4473. } else if (schedulerTypeSelection === 1 && (requestingFn === requestIdleCallback || requestingFn === setTimeout)) { // setTimeout(requestIdleCallback)
  4474. // often
  4475. if (requestingFn === requestIdleCallback) {
  4476. target[timerIdProp] = requestIdleCallback.apply(window, requestingArgs);
  4477. } else {
  4478. target[timerIdProp] = mkFns[2].apply(window, requestingArgs);
  4479. }
  4480. } else {
  4481. target[_fnSelectorProp] = 0;
  4482. target[timerIdProp] = 0;
  4483. }
  4484. } else {
  4485. target[prop] = value;
  4486. }
  4487. return true;
  4488. }
  4489. };
  4490.  
  4491. let startBusy = false;
  4492. schedulerInstanceInstance_.start = function () {
  4493. if (startBusy) return;
  4494. startBusy = true;
  4495. try {
  4496. mkFns[0] = window.requestAnimationFrame;
  4497. mkFns[1] = window.setInterval;
  4498. mkFns[2] = window.setTimeout;
  4499. mkFns[3] = window.requestIdleCallback;
  4500. const tThis = this['$$12378$$'] || this;
  4501. window.requestAnimationFrame = fakeFns[0]
  4502. window.setInterval = fakeFns[1]
  4503. window.setTimeout = fakeFns[2]
  4504. window.requestIdleCallback = fakeFns[3]
  4505. _fnSelectorProp = null;
  4506. tThis.start993.call(new Proxy(tThis, startFnHandler));
  4507. _fnSelectorProp = null;
  4508. window.requestAnimationFrame = mkFns[0];
  4509. window.setInterval = mkFns[1];
  4510. window.setTimeout = mkFns[2];
  4511. window.requestIdleCallback = mkFns[3];
  4512. } catch (e) {
  4513. console.warn(e);
  4514. }
  4515. startBusy = false;
  4516. }
  4517.  
  4518. schedulerInstanceInstance_.start.toString = schedulerInstanceInstance_.start993.toString.bind(schedulerInstanceInstance_.start993);
  4519.  
  4520. }
  4521. })();
  4522.  
  4523. FIX_yt_player && (async () => {
  4524. // rAf scheduling
  4525.  
  4526. const _yt_player = await _yt_player_observable.obtain();
  4527.  
  4528. if (!_yt_player || typeof _yt_player !== 'object') return;
  4529.  
  4530. let keyZqOu = getZqOu(_yt_player);
  4531.  
  4532.  
  4533. if (!keyZqOu) return;
  4534.  
  4535.  
  4536. const g = _yt_player
  4537. let k = keyZqOu
  4538.  
  4539. const gk = g[k];
  4540. if (typeof gk !== 'function') return;
  4541. const gkp = gk.prototype;
  4542.  
  4543. let dummyObject = new gk;
  4544. let nilFunc = () => { };
  4545.  
  4546. let nilObj = {};
  4547.  
  4548. // console.log(1111111111)
  4549.  
  4550. let keyBoolD = '';
  4551. let keyWindow = '';
  4552. let keyFuncC = '';
  4553. let keyCidj = '';
  4554.  
  4555. for (const [t, y] of Object.entries(dummyObject)) {
  4556. if (y instanceof Window) keyWindow = t;
  4557. }
  4558.  
  4559. const dummyObjectProxyHandler = {
  4560. get(target, prop) {
  4561. let v = target[prop]
  4562. if (v instanceof Window && !keyWindow) {
  4563. keyWindow = t;
  4564. }
  4565. let y = typeof v === 'function' ? nilFunc : typeof v === 'object' ? nilObj : v;
  4566. if (prop === keyWindow) y = {
  4567. requestAnimationFrame(f) {
  4568. return 3;
  4569. },
  4570. cancelAnimationFrame() {
  4571.  
  4572. }
  4573. }
  4574. if (!keyFuncC && typeof v === 'function' && !(prop in target.constructor.prototype)) {
  4575. keyFuncC = prop;
  4576. }
  4577. // console.log('[get]', prop, typeof target[prop])
  4578.  
  4579.  
  4580. return y;
  4581. },
  4582. set(target, prop, value) {
  4583.  
  4584. if (typeof value === 'boolean' && !keyBoolD) {
  4585. keyBoolD = prop;
  4586. }
  4587. if (typeof value === 'number' && !keyCidj && value >= 2) {
  4588. keyCidj = prop;
  4589. }
  4590.  
  4591. // console.log('[set]', prop, value)
  4592. target[prop] = value
  4593.  
  4594. return true;
  4595. }
  4596. };
  4597.  
  4598. dummyObject.start.call(new Proxy(dummyObject, dummyObjectProxyHandler));
  4599.  
  4600. // console.log('gkp.start',gkp.start);
  4601. // console.log('gkp.stop',gkp.stop);
  4602. gkp._activation = false;
  4603.  
  4604. gkp.start = function () {
  4605. // p59 || console.log(12100)
  4606. if (!this._activation) {
  4607. this._activation = true;
  4608. getRafPromise().then(() => {
  4609. this._activation = false;
  4610. if (this[keyCidj]) {
  4611. Promise.resolve().then(this[keyFuncC]);
  4612. }
  4613. });
  4614. }
  4615. this[keyCidj] = 1;
  4616. this[keyBoolD] = true;
  4617. }
  4618. ;
  4619. gkp.stop = function () {
  4620. this[keyCidj] = null
  4621. }
  4622.  
  4623.  
  4624. /*
  4625. g[k].start = function() {
  4626. this.stop();
  4627. this.D = true;
  4628. var a = requestAnimationFrame
  4629. , b = cancelAnimationFrame;
  4630. this.j = a.call(this.B, this.C)
  4631. }
  4632. ;
  4633. g[k].stop = function() {
  4634. if (this.isActive()) {
  4635. var a = requestAnimationFrame
  4636. , b = cancelAnimationFrame;
  4637. b.call(this.B, this.j)
  4638. }
  4639. this.j = null
  4640. }
  4641. */
  4642.  
  4643. const keyzo = PERF_471489_ ? getzo(_yt_player) : null;
  4644.  
  4645. if (keyzo) {
  4646.  
  4647. k = keyzo;
  4648.  
  4649. const attrUpdateFn = g[k];
  4650. // console.log(5992, attrUpdateFn)
  4651. g['$$original$$' + k] = attrUpdateFn;
  4652. const zoTransform = async (a, c) => {
  4653.  
  4654. let transformType = '';
  4655. let transformValue = 0;
  4656. let transformUnit = '';
  4657. let transformTypeI = 0;
  4658.  
  4659. const aStyle = a.style;
  4660.  
  4661. if (c.length < 9) {
  4662.  
  4663. } else if (c.startsWith('scalex(0.') || (c === 'scalex(0)' || c === 'scalex(1)')) {
  4664. let p = c.substring(7, c.length - 1);
  4665. let q = p.length >= 1 ? parseFloat(p) : -1;
  4666. if (q > -1e-5 && q < 1 + 1e-5) {
  4667. transformType = 'scaleX'
  4668. transformValue = q;
  4669. transformUnit = '';
  4670. transformTypeI = 1;
  4671. }
  4672. } else if (c.startsWith('translateX(') && c.endsWith('px)')) {
  4673. let p = c.substring(11, c.length - 3);
  4674. let q = p.length >= 1 ? parseFloat(p) : NaN;
  4675. if (typeof q === 'number' && !isNaN(q)) {
  4676. transformType = 'translateX'
  4677. transformValue = q;
  4678. transformUnit = 'px';
  4679. transformTypeI = 2;
  4680. } else if (p === 'NaN') {
  4681. return;
  4682. }
  4683. } else if (c.startsWith('scaley(0.') || (c === 'scaley(0)' || c === 'scaley(1)')) {
  4684. let p = c.substring(7, c.length - 1);
  4685. let q = p.length >= 1 ? parseFloat(p) : -1;
  4686. if (q > -1e-5 && q < 1 + 1e-5) {
  4687. transformType = 'scaleY'
  4688. transformValue = q;
  4689. transformUnit = '';
  4690. transformTypeI = 1;
  4691. }
  4692. } else if (c.startsWith('translateY(') && c.endsWith('px)')) {
  4693. let p = c.substring(11, c.length - 3);
  4694. let q = p.length >= 1 ? parseFloat(p) : NaN;
  4695. if (typeof q === 'number' && !isNaN(q)) {
  4696. transformType = 'translateY'
  4697. transformValue = q;
  4698. transformUnit = 'px';
  4699. transformTypeI = 2;
  4700. } else if (p === 'NaN') {
  4701. return;
  4702. }
  4703. } else if (c.startsWith('scalex(') && c.includes('e-')) {
  4704. // scalex(1.252057684158767e-16)
  4705. // scalex(3.0393632069734948e-9)
  4706. let p = c.substring(7, c.length - 1);
  4707. let q = p.length >= 1 ? parseFloat(p) : -1;
  4708. if (q > -1e-5 && q < 1e-5) {
  4709. transformType = 'scaleX'
  4710. transformValue = 0;
  4711. transformUnit = '';
  4712. transformTypeI = 1;
  4713. }
  4714. } else if (c.startsWith('scaley(') && c.includes('e-')) {
  4715. let p = c.substring(7, c.length - 1);
  4716. let q = p.length >= 1 ? parseFloat(p) : -1;
  4717. if (q > -1e-5 && q < 1e-5) {
  4718. transformType = 'scaleY'
  4719. transformValue = 0;
  4720. transformUnit = '';
  4721. transformTypeI = 1;
  4722. }
  4723. }
  4724.  
  4725. if (transformTypeI === 1) {
  4726. const q = Math.round(transformValue * steppingScaleN) / steppingScaleN;
  4727. const vz = toFixed2(q, 3);
  4728. c = `${transformType}(${vz})`;
  4729. const cv = aStyle.transform;
  4730. if (c === cv) return;
  4731. aStyle.transform = c;
  4732. } else if (transformTypeI === 2) {
  4733. const q = transformValue;
  4734. const vz = toFixed2(q, 1);
  4735. c = `${transformType}(${vz}${transformUnit})`;
  4736. const cv = aStyle.transform;
  4737. if (c === cv) return;
  4738. aStyle.transform = c;
  4739. } else { // eg empty
  4740. const cv = aStyle.transform;
  4741. if (!c && !cv) return;
  4742. else if (c === cv) return;
  4743. aStyle.transform = c;
  4744. }
  4745.  
  4746. };
  4747.  
  4748. const elmTransformTemp = new WeakMap();
  4749. const elmPropTemps = {
  4750. 'display': new WeakMap(),
  4751. 'width': new WeakMap(),
  4752. 'height': new WeakMap(),
  4753. 'outlineWidth': new WeakMap(),
  4754. 'position': new WeakMap(),
  4755. 'padding': new WeakMap(),
  4756. "cssText": new WeakMap(),
  4757. "right": new WeakMap(),
  4758. "left": new WeakMap(),
  4759. "top": new WeakMap(),
  4760. "bottom": new WeakMap(),
  4761. "transitionDelay": new WeakMap(),
  4762. "marginLeft": new WeakMap(),
  4763. "marginTop": new WeakMap(),
  4764. "marginRight": new WeakMap(),
  4765. "marginBottom": new WeakMap(),
  4766. }
  4767.  
  4768. const ns5 = Symbol();
  4769. const nextModify = (a, c, m, f, immediate) => {
  4770. const a_ = a;
  4771. const m_ = m;
  4772. const noKey = !m_.has(a_);
  4773. if (immediate || noKey) {
  4774. m_.set(a_, ns5);
  4775. f(a_, c);
  4776. noKey && nextBrowserTick_(() => {
  4777. const d = m_.get(a_);
  4778. if (d === undefined) return;
  4779. m_.delete(a_);
  4780. if (d !== ns5) f(a_, d);
  4781. });
  4782. } else {
  4783. m_.set(a_, c);
  4784. }
  4785. };
  4786.  
  4787. const set66 = new Set();
  4788. // const set77 = new Set(['top', 'left', 'bottom', 'right']); // caption positioning - immediate change
  4789.  
  4790. const modifiedFn = function (a, b, c, immediateChange = false) { // arrow function does not have function.prototype
  4791.  
  4792. // console.log(140000, a, b, c);
  4793. if (typeof c === 'number' && typeof b === 'string' && a instanceof HTMLElement) {
  4794. const num = c;
  4795. c = `${num}`;
  4796. if (c.length > 5) c = (num < 10 && num > -10) ? toFixed2(num, 3) : toFixed2(num, 1);
  4797. }
  4798.  
  4799. if (typeof b === 'string' && typeof c === 'string' && a instanceof HTMLElement) {
  4800.  
  4801. let elmPropTemp = null;
  4802.  
  4803. if (b === "transform") {
  4804.  
  4805. nextModify(a, c, elmTransformTemp, zoTransform, immediateChange);
  4806. return;
  4807.  
  4808. } else if (elmPropTemp = elmPropTemps[b]) {
  4809.  
  4810. // if (c.length > 5 && c.includes('.')) {
  4811. // console.log(123213, c)
  4812. // }
  4813.  
  4814. const b_ = b;
  4815. nextModify(a, c, elmPropTemp, (a, c) => {
  4816. const style = a.style;
  4817. const cv = style[b_];
  4818. if (!cv && !c) return;
  4819. if (cv === c) return;
  4820. style[b_] = c;
  4821. }, immediateChange);
  4822. return;
  4823.  
  4824. } else if (b === "outline-width") {
  4825.  
  4826. const b_ = 'outlineWidth';
  4827. elmPropTemp = elmPropTemps[b_];
  4828. nextModify(a, c, elmPropTemp, (a, c) => {
  4829. const style = a.style;
  4830. const cv = style[b_];
  4831. if (!cv && !c) return;
  4832. if (cv === c) return;
  4833. style[b_] = c;
  4834. }, immediateChange);
  4835. return;
  4836.  
  4837. } else if (b === 'maxWidth' || b === 'maxHeight') {
  4838. // I think these can be directly assigned.
  4839.  
  4840. const b_ = b;
  4841. const style = a.style;
  4842. const cv = style[b_];
  4843. if (!cv && !c) return;
  4844. if (cv === c) return;
  4845. style[b_] = c;
  4846. return;
  4847.  
  4848. } else {
  4849. // if(immediate && elmPropTemps[b]){
  4850. // console.log(5191, b)
  4851. // }
  4852. // caption-window
  4853. // margin-left max-height max-width font-family fill color font-size background white-space margin
  4854. // text-align background-color
  4855. // console.log(27304, a, b, c)
  4856. if (!set66.has(b)) {
  4857. set66.add(b);
  4858. nextBrowserTick_(() => {
  4859. if (!a.classList.contains('caption-window') && !a.classList.contains('ytp-caption-segment')) {
  4860. console.log(27304, a, b, c)
  4861. }
  4862. })
  4863. }
  4864. }
  4865.  
  4866. attrUpdateFn.call(this, a, b, c);
  4867. return;
  4868. } else if (typeof (b || 0) === 'object') {
  4869.  
  4870. // this is to fix caption positioning
  4871. // const immediate = (a.id || 0).length > 14 && (('top' in b) || ('left' in b) || ('right' in b) || ('bottom' in b));
  4872. const immediate = (a.id || 0).length > 14;
  4873. for (const [k, v] of Object.entries(b)) {
  4874. modifiedFn.call(this, a, k, v, immediate);
  4875. }
  4876.  
  4877. } else {
  4878. console.log(27306, a, b, c);
  4879.  
  4880. attrUpdateFn.call(this, a, b, c);
  4881. return;
  4882. }
  4883.  
  4884. // console.log(130000, a, b, c);
  4885.  
  4886. };
  4887. g[k] = modifiedFn;
  4888.  
  4889.  
  4890. /*
  4891.  
  4892. g.zo = function(a, b, c) {
  4893. if ("string" === typeof b)
  4894. (b = yo(a, b)) && (a.style[b] = c);
  4895. else
  4896. for (var d in b) {
  4897. c = a;
  4898. var e = b[d]
  4899. , f = yo(c, d);
  4900. f && (c.style[f] = e)
  4901. }
  4902. }
  4903.  
  4904.  
  4905. */
  4906.  
  4907.  
  4908. }
  4909.  
  4910.  
  4911.  
  4912. const keyuG = PERF_471489_ ? getuG(_yt_player) : null;
  4913.  
  4914. if (keyuG) {
  4915.  
  4916. k = keyuG;
  4917.  
  4918. const gk = g[k];
  4919. const gkp = gk.prototype;
  4920.  
  4921.  
  4922. /** @type { Map<string, WeakMap<any, any>> } */
  4923. const ntLogs = new Map();
  4924.  
  4925. if (typeof gkp.updateValue === 'function' && gkp.updateValue.length === 2 && !gkp.updateValue31) {
  4926.  
  4927. gkp.updateValue31 = gkp.updateValue;
  4928. gkp.updateValue = function (a, b) {
  4929. if (typeof a !== 'string') return this.updateValue31(a, b);
  4930.  
  4931. const element = this.element;
  4932. if (!(element instanceof HTMLElement)) return this.updateValue31(a, b);
  4933.  
  4934. let ntLog = ntLogs.get(a);
  4935. if (!ntLog) ntLogs.set(a, (ntLog = new WeakMap()));
  4936.  
  4937. let cache = ntLog.get(element);
  4938. if (cache && cache.value === b) {
  4939. return;
  4940. }
  4941. if (!cache) {
  4942. this.__oldValueByUpdateValue__ = null;
  4943. ntLog.set(element, cache = { value: b });
  4944. } else {
  4945. this.__oldValueByUpdateValue__ = cache.value;
  4946. cache.value = b;
  4947. }
  4948.  
  4949. return this.updateValue31(a, b);
  4950. }
  4951.  
  4952. /*
  4953. g.k.update = function(a) {
  4954. for (var b = g.u(Object.keys(a)), c = b.next(); !c.done; c = b.next())
  4955. c = c.value,
  4956. this.updateValue(c, a[c])
  4957. }
  4958. ;
  4959. g.k.updateValue = function(a, b) {
  4960. (a = this.Td["{{" + a + "}}"]) && wG(this, a[0], a[1], b)
  4961. }
  4962. */
  4963.  
  4964. }
  4965.  
  4966.  
  4967. }
  4968.  
  4969.  
  4970.  
  4971.  
  4972. })();
  4973.  
  4974.  
  4975. FIX_yt_player && FIX_SHORTCUTKEYS > 0 && (async () => {
  4976. // keyboard shortcut keys controller
  4977.  
  4978. const _yt_player = await _yt_player_observable.obtain();
  4979.  
  4980. if (!_yt_player || typeof _yt_player !== 'object') return;
  4981.  
  4982. keyboardController(_yt_player);
  4983.  
  4984. })();
  4985.  
  4986. FIX_yt_player && (async () => {
  4987. // timer scheduling
  4988.  
  4989. const _yt_player = await _yt_player_observable.obtain();
  4990.  
  4991. if (!_yt_player || typeof _yt_player !== 'object') return;
  4992.  
  4993. let keyZqQu = getZqQu(_yt_player);
  4994.  
  4995. if (!keyZqQu) return;
  4996.  
  4997. const g = _yt_player
  4998. let k = keyZqQu
  4999.  
  5000. const gk = g[k];
  5001. if (typeof gk !== 'function') return;
  5002. const gkp = gk.prototype;
  5003.  
  5004. const extractKeysZqQu = () => {
  5005.  
  5006.  
  5007. let _keyeC = '';
  5008. try {
  5009. gkp.stop.call(new Proxy({
  5010. isActive: () => { }
  5011. }, {
  5012. set(target, prop, value) {
  5013. if (value === 0) _keyeC = prop;
  5014. return true;
  5015. }
  5016. }));
  5017. } catch (e) { }
  5018. if (!_keyeC) return;
  5019. const keyeC = _keyeC;
  5020.  
  5021. let keyC = ''; // this.C = this.ST.bind(this)
  5022. let keyhj = ''; // 1000ms
  5023. try {
  5024. gkp.start.call(new Proxy({
  5025. stop: () => { },
  5026. [keyeC]: 0,
  5027. }, {
  5028. get(target, prop) {
  5029. if (prop in target) return target[prop];
  5030. if (!keyC) {
  5031. keyC = prop;
  5032. return null; // throw error
  5033. }
  5034. else if (!keyhj) {
  5035. keyhj = prop;
  5036. }
  5037.  
  5038. }
  5039. }));
  5040. } catch (e) {
  5041. if (!keyC || !keyhj) {
  5042. console.log(e)
  5043. }
  5044. }
  5045.  
  5046. if (!keyC || !keyhj) return;
  5047. let keyST = '';
  5048. let keyj = '';
  5049. let keyB = '';
  5050. let keyxa = '';
  5051.  
  5052. const possibleKs = new Set();
  5053.  
  5054. for (const [k, v] of Object.entries(gkp)) {
  5055. if (k === 'stop' || k === 'start' || k === 'isActive' || k === 'constructor' || k === keyeC || k === keyC || k === keyhj) {
  5056. continue;
  5057. }
  5058. if (typeof v === 'function') {
  5059. const m = /this\.(\w+)\.call\(this\.(\w+)\)/.exec(v + '');
  5060. if (m) {
  5061. keyST = k;
  5062. keyj = m[1];
  5063. keyB = m[2];
  5064. } else {
  5065. possibleKs.add(k);
  5066. }
  5067. }
  5068. }
  5069.  
  5070. if (!keyST || !keyj || !keyB) return;
  5071.  
  5072. for (const k of possibleKs) {
  5073. if (k === keyST || k === keyj || k === keyB) {
  5074. continue;
  5075. }
  5076. const v = gkp[k];
  5077. if (typeof v === 'function' && (v + '').includes(`this.stop();delete this.${keyj};delete this.${keyB}`)) {
  5078. keyxa = k;
  5079. }
  5080. }
  5081.  
  5082. return [keyeC, keyC, keyhj, keyST, keyj, keyB, keyxa];
  5083.  
  5084. }
  5085.  
  5086. const keys = extractKeysZqQu();
  5087. if (!keys || !keys.length) return;
  5088. const [keyeC, keyC, keyhj, keyST, keyj, keyB, keyxa] = keys; // [timerId, binded executorFn, 1000ms, executorFn, dataJ, objectB, disposeFn]
  5089.  
  5090. if (!keyeC || !keyC || !keyhj || !keyST || !keyj || !keyB || !keyxa) return;
  5091.  
  5092. let disposeKeys = null;
  5093.  
  5094. gkp[keyxa] = function () {
  5095. // dispose
  5096. if (!disposeKeys) {
  5097. disposeKeys = Object.getOwnPropertyNames(this).filter(key => {
  5098. if (key != keyeC && key != keyC && key != keyhj && key != keyST && key != keyj && key != keyB && key != keyxa) {
  5099. const t = typeof this[key];
  5100. return t === 'undefined' || t === 'object'
  5101. }
  5102. return false;
  5103. });
  5104. }
  5105. for (const key of disposeKeys) {
  5106. const v = this[key];
  5107. if ((v || 0).length >= 1) v.length = 0; // function (){if(this.fn)for(;this.fn.length;)this.fn.shift()()}
  5108. }
  5109. if (this[keyeC] > 0) this.stop();
  5110. this[keyj] = null;
  5111. this[keyB] = null;
  5112. };
  5113.  
  5114. gkp.start = function (a) {
  5115. if (this[keyeC] > 0) this.stop();
  5116. const delay = void 0 !== a ? a : this[keyhj];
  5117. this[keyeC] = window.setTimeout(this[keyC], delay);
  5118. };
  5119. gkp.stop = function () {
  5120. if (this[keyeC] > 0) {
  5121. window.clearTimeout(this[keyeC]);
  5122. this[keyeC] = 0;
  5123. }
  5124. };
  5125.  
  5126. gkp.isActive = function () {
  5127. return this[keyeC] > 0;
  5128. };
  5129.  
  5130. gkp[keyST] = function () {
  5131. this.stop(); // this[keyeC] = 0;
  5132. const fn = this[keyj];
  5133. const obj = this[keyB];
  5134. let skip = false;
  5135. if (!fn) skip = true;
  5136. else if (IGNORE_bufferhealth_CHECK && obj) {
  5137. let m;
  5138. if ((m = obj[keyC]) instanceof Map || (m = obj[keyj]) instanceof Map) {
  5139. if (m.has("bufferhealth")) skip = true;
  5140. }
  5141. }
  5142. if (!skip) {
  5143. fn.call(obj);
  5144. }
  5145. };
  5146.  
  5147.  
  5148.  
  5149.  
  5150. /*
  5151.  
  5152. g.k.eC = 0;
  5153. g.k.xa = function() {
  5154. g.Qu.Vf.xa.call(this);
  5155. this.stop();
  5156. delete this.j;
  5157. delete this.B
  5158. }
  5159. ;
  5160. g.k.start = function(a) {
  5161. this.stop();
  5162. this.eC = g.gg(this.C, void 0 !== a ? a : this.hj)
  5163. }
  5164. ;
  5165. g.k.stop = function() {
  5166. this.isActive() && g.Sa.clearTimeout(this.eC);
  5167. this.eC = 0
  5168. }
  5169. ;
  5170. g.k.isActive = function() {
  5171. return 0 != this.eC
  5172. }
  5173. ;
  5174. g.k.ST = function() {
  5175. this.eC = 0;
  5176. this.j && this.j.call(this.B)
  5177. }
  5178. ;
  5179. */
  5180.  
  5181.  
  5182.  
  5183.  
  5184. })();
  5185.  
  5186. FIX_Animation_n_timeline && (async () => {
  5187.  
  5188. const [timeline, Animation] = await Promise.all([timelineObservable.obtain(), animationObservable.obtain()]);
  5189.  
  5190. if (!timeline || !Animation) return;
  5191.  
  5192. const aniProto = Animation.prototype;
  5193. // aniProto.sequenceNumber = 0; // native YouTube engine bug - sequenceNumber is not set
  5194.  
  5195. const getXroto = (x) => {
  5196. try {
  5197. return x.__proto__;
  5198. } catch (e) { }
  5199. return null;
  5200. }
  5201. const timProto = getXroto(timeline);
  5202. if (!timProto) return;
  5203. if (
  5204. (
  5205. typeof timProto.getAnimations === 'function' && typeof timProto.play === 'function' &&
  5206. typeof timProto._discardAnimations === 'function' && typeof timProto._play === 'function' &&
  5207. typeof timProto._updateAnimationsPromises === 'function' && !timProto.nofCQ &&
  5208. typeof aniProto._updatePromises === 'function' && !aniProto.nofYH
  5209. )
  5210.  
  5211. ) {
  5212.  
  5213. timProto.nofCQ = 1;
  5214. aniProto.nofYH = 1;
  5215.  
  5216. const originalAnimationsWithPromises = ((_updateAnimationsPromises) => {
  5217.  
  5218.  
  5219. /*
  5220. v.animationsWithPromises = v.animationsWithPromises.filter(function (c) {
  5221. return c._updatePromises();
  5222. });
  5223. */
  5224.  
  5225. const p = Array.prototype.filter;
  5226.  
  5227. let res = null;
  5228. Array.prototype.filter = function () {
  5229.  
  5230. res = this;
  5231. return this;
  5232.  
  5233. };
  5234.  
  5235. _updateAnimationsPromises.call({});
  5236.  
  5237. Array.prototype.filter = p;
  5238.  
  5239. if (res && typeof res.length === 'number') {
  5240. /** @type {any[]} */
  5241. const _res = res;
  5242. return _res;
  5243. }
  5244.  
  5245.  
  5246. return null;
  5247.  
  5248.  
  5249.  
  5250.  
  5251. })(timProto._updateAnimationsPromises);
  5252.  
  5253. if (!originalAnimationsWithPromises || typeof originalAnimationsWithPromises.length !== 'number') return;
  5254.  
  5255. // console.log('originalAnimationsWithPromises', originalAnimationsWithPromises)
  5256.  
  5257. aniProto._updatePromises31 = aniProto._updatePromises;
  5258.  
  5259. /*
  5260. aniProto._updatePromises = function(){
  5261. console.log('eff',this._oldPlayState, this.playState)
  5262. return this._updatePromises31.apply(this, arguments)
  5263. }
  5264. */
  5265.  
  5266. aniProto._updatePromises = function () {
  5267. var oldPlayState = this._oldPlayState;
  5268. var newPlayState = this.playState;
  5269. // console.log('ett', oldPlayState, newPlayState)
  5270. if (newPlayState !== oldPlayState) {
  5271. this._oldPlayState = newPlayState;
  5272. if (this._readyPromise) {
  5273. if ("idle" == newPlayState) {
  5274. this._rejectReadyPromise();
  5275. this._readyPromise = void 0;
  5276. } else if ("pending" == oldPlayState) {
  5277. this._resolveReadyPromise();
  5278. } else if ("pending" == newPlayState) {
  5279. this._readyPromise = void 0;
  5280. }
  5281. }
  5282. if (this._finishedPromise) {
  5283. if ("idle" == newPlayState) {
  5284. this._rejectFinishedPromise();
  5285. this._finishedPromise = void 0;
  5286. } else if ("finished" == newPlayState) {
  5287. this._resolveFinishedPromise();
  5288. } else if ("finished" == oldPlayState) {
  5289. this._finishedPromise = void 0;
  5290. }
  5291. }
  5292. }
  5293. return this._readyPromise || this._finishedPromise;
  5294. };
  5295.  
  5296.  
  5297. let restartWebAnimationsNextTickFlag = false;
  5298.  
  5299. const looperMethodT = () => {
  5300.  
  5301. const runnerFn = (hRes) => {
  5302. var b = timeline;
  5303. b.currentTime = hRes;
  5304. b._discardAnimations();
  5305. if (0 == b._animations.length) {
  5306. restartWebAnimationsNextTickFlag = false;
  5307. } else {
  5308. getRafPromise().then(runnerFn);
  5309. }
  5310. }
  5311.  
  5312. const restartWebAnimationsNextTick = () => {
  5313. if (!restartWebAnimationsNextTickFlag) {
  5314. restartWebAnimationsNextTickFlag = true;
  5315. getRafPromise().then(runnerFn);
  5316. }
  5317. }
  5318.  
  5319. return { restartWebAnimationsNextTick }
  5320. };
  5321.  
  5322.  
  5323. const looperMethodN = () => {
  5324.  
  5325. const acs = document.createElement('a-f');
  5326. acs.id = 'a-f';
  5327.  
  5328. if (!document.getElementById('afscript')) {
  5329. const style = document.createElement('style');
  5330. style.id = 'afscript';
  5331. style.textContent = `
  5332. @keyFrames aF1 {
  5333. 0% {
  5334. order: 0;
  5335. }
  5336. 100% {
  5337. order: 1;
  5338. }
  5339. }
  5340. #a-f[id] {
  5341. visibility: collapse !important;
  5342. position: fixed !important;
  5343. display: block !important;
  5344. top: -100px !important;
  5345. left: -100px !important;
  5346. margin:0 !important;
  5347. padding:0 !important;
  5348. outline:0 !important;
  5349. border:0 !important;
  5350. z-index:-1 !important;
  5351. width: 0px !important;
  5352. height: 0px !important;
  5353. contain: strict !important;
  5354. pointer-events: none !important;
  5355. animation: 1ms steps(2, jump-none) 0ms infinite alternate forwards running aF1 !important;
  5356. }
  5357. `;
  5358. (document.head || document.documentElement).appendChild(style);
  5359. }
  5360.  
  5361. document.documentElement.insertBefore(acs, document.documentElement.firstChild);
  5362.  
  5363. const _onanimationiteration = function (evt) {
  5364. const hRes = evt.timeStamp;
  5365. var b = timeline;
  5366. b.currentTime = hRes;
  5367. b._discardAnimations();
  5368. if (0 == b._animations.length) {
  5369. restartWebAnimationsNextTickFlag = false;
  5370. acs.onanimationiteration = null;
  5371. } else {
  5372. acs.onanimationiteration = _onanimationiteration;
  5373. }
  5374.  
  5375. }
  5376.  
  5377.  
  5378.  
  5379. const restartWebAnimationsNextTick = () => {
  5380. if (!restartWebAnimationsNextTickFlag) {
  5381. restartWebAnimationsNextTickFlag = true;
  5382. acs.onanimationiteration = _onanimationiteration;
  5383.  
  5384. }
  5385. }
  5386.  
  5387. return { restartWebAnimationsNextTick }
  5388. };
  5389.  
  5390.  
  5391.  
  5392. const { restartWebAnimationsNextTick } = ('onanimationiteration' in document.documentElement) ? looperMethodN() : looperMethodT();
  5393.  
  5394.  
  5395. // console.log(571, timProto);
  5396. timProto._play = function (c) {
  5397. c = new Animation(c, this);
  5398. this._animations.push(c);
  5399. restartWebAnimationsNextTick();
  5400. c._updatePromises();
  5401. c._animation.play();
  5402. c._updatePromises();
  5403. return c
  5404. }
  5405.  
  5406. const animationsWithPromisesMap = new Set(originalAnimationsWithPromises);
  5407. originalAnimationsWithPromises.length = 0;
  5408. originalAnimationsWithPromises.push = null;
  5409. originalAnimationsWithPromises.splice = null;
  5410. originalAnimationsWithPromises.slice = null;
  5411. originalAnimationsWithPromises.indexOf = null;
  5412. originalAnimationsWithPromises.unshift = null;
  5413. originalAnimationsWithPromises.shift = null;
  5414. originalAnimationsWithPromises.pop = null;
  5415. originalAnimationsWithPromises.filter = null;
  5416. originalAnimationsWithPromises.forEach = null;
  5417. originalAnimationsWithPromises.map = null;
  5418.  
  5419.  
  5420. const _updateAnimationsPromises = () => {
  5421. animationsWithPromisesMap.forEach(c => {
  5422. if (!c._updatePromises()) animationsWithPromisesMap.delete(c);
  5423. });
  5424. /*
  5425. v.animationsWithPromises = v.animationsWithPromises.filter(function (c) {
  5426. return c._updatePromises();
  5427. });
  5428. */
  5429. }
  5430.  
  5431. timProto._updateAnimationsPromises31 = timProto._updateAnimationsPromises;
  5432.  
  5433. timProto._updateAnimationsPromises = _updateAnimationsPromises;
  5434.  
  5435. delete timProto._updateAnimationsPromises;
  5436. Object.defineProperty(timProto, '_updateAnimationsPromises', {
  5437. get() {
  5438. if (animationsWithPromisesMap.size === 0) return nilFn;
  5439. return _updateAnimationsPromises;
  5440. },
  5441. set(nv) {
  5442. delete this._updateAnimationsPromises;
  5443. this._updateAnimationsPromises = nv;
  5444. },
  5445. enumerable: true,
  5446. configurable: true,
  5447. });
  5448.  
  5449.  
  5450. let pdFinished = Object.getOwnPropertyDescriptor(aniProto, 'finished');
  5451. aniProto.__finished_native_get__ = pdFinished.get;
  5452. if (typeof pdFinished.get === 'function' && !pdFinished.set && pdFinished.configurable === true && pdFinished.enumerable === true) {
  5453.  
  5454.  
  5455. Object.defineProperty(aniProto, 'finished', {
  5456. get() {
  5457. this._finishedPromise || (!animationsWithPromisesMap.has(this) && animationsWithPromisesMap.add(this),
  5458. this._finishedPromise = new Promise((resolve, reject) => {
  5459. this._resolveFinishedPromise = function () {
  5460. resolve(this)
  5461. };
  5462. this._rejectFinishedPromise = function () {
  5463. reject({
  5464. type: DOMException.ABORT_ERR,
  5465. name: "AbortError"
  5466. })
  5467. };
  5468. }),
  5469. "finished" == this.playState && this._resolveFinishedPromise());
  5470. return this._finishedPromise
  5471. },
  5472. set: undefined,
  5473. enumerable: true,
  5474. configurable: true
  5475. });
  5476.  
  5477. }
  5478.  
  5479.  
  5480.  
  5481. let pdReady = Object.getOwnPropertyDescriptor(aniProto, 'ready');
  5482. aniProto.__ready_native_get__ = pdReady.get;
  5483. if (typeof pdReady.get === 'function' && !pdReady.set && pdReady.configurable === true && pdReady.enumerable === true) {
  5484.  
  5485. Object.defineProperty(aniProto, 'ready', {
  5486. get() {
  5487. this._readyPromise || (!animationsWithPromisesMap.has(this) && animationsWithPromisesMap.add(this),
  5488. this._readyPromise = new Promise((resolve, reject) => {
  5489. this._resolveReadyPromise = function () {
  5490. resolve(this)
  5491. };
  5492. this._rejectReadyPromise = function () {
  5493. reject({
  5494. type: DOMException.ABORT_ERR,
  5495. name: "AbortError"
  5496. })
  5497. };
  5498. }),
  5499. "pending" !== this.playState && this._resolveReadyPromise());
  5500. return this._readyPromise
  5501. },
  5502. set: undefined,
  5503. enumerable: true,
  5504. configurable: true
  5505. });
  5506.  
  5507. }
  5508.  
  5509.  
  5510. if (IGNORE_bindAnimationForCustomEffect && typeof aniProto._rebuildUnderlyingAnimation === 'function' && !aniProto._rebuildUnderlyingAnimation21 && aniProto._rebuildUnderlyingAnimation.length === 0) {
  5511.  
  5512. aniProto._rebuildUnderlyingAnimation21 = aniProto._rebuildUnderlyingAnimation;
  5513. const _rebuildUnderlyingAnimation = function () {
  5514. // if (isNaN(this._sequenceNumber)) return; // do not rebuild underlying animation if native animation is used.
  5515. this.effect && this.effect._onsample && (this.effect._onsample = null);
  5516. return this._rebuildUnderlyingAnimation21();
  5517. }
  5518. aniProto._rebuildUnderlyingAnimation = _rebuildUnderlyingAnimation;
  5519. // delete aniProto._rebuildUnderlyingAnimation;
  5520. // Object.defineProperty(aniProto, '_rebuildUnderlyingAnimation', {
  5521. // get() {
  5522. // if (isNaN(this._sequenceNumber)) return nilFn;
  5523. // return this._rebuildUnderlyingAnimation21;
  5524. // },
  5525. // set(nv) {
  5526. // delete this._rebuildUnderlyingAnimation;
  5527. // this._rebuildUnderlyingAnimation = nv;
  5528. // },
  5529. // enumerable: true,
  5530. // configurable: true
  5531. // });
  5532. }
  5533.  
  5534.  
  5535. /*
  5536.  
  5537.  
  5538. function f(c) {
  5539. var b = v.timeline;
  5540. b.currentTime = c;
  5541. b._discardAnimations();
  5542. 0 == b._animations.length ? d = !1 : requestAnimationFrame(f)
  5543. }
  5544. var h = window.requestAnimationFrame;
  5545. window.requestAnimationFrame = function(c) {
  5546. return h(function(b) {
  5547. v.timeline._updateAnimationsPromises();
  5548. c(b);
  5549. v.timeline._updateAnimationsPromises()
  5550. })
  5551. }
  5552. ;
  5553. v.AnimationTimeline = function() {
  5554. this._animations = [];
  5555. this.currentTime = void 0
  5556. }
  5557. ;
  5558. v.AnimationTimeline.prototype = {
  5559. getAnimations: function() {
  5560. this._discardAnimations();
  5561. return this._animations.slice()
  5562. },
  5563. _updateAnimationsPromises: function() {
  5564. v.animationsWithPromises = v.animationsWithPromises.filter(function(c) {
  5565. return c._updatePromises()
  5566. })
  5567. },
  5568. _discardAnimations: function() {
  5569. this._updateAnimationsPromises();
  5570. this._animations = this._animations.filter(function(c) {
  5571. return "finished" != c.playState && "idle" != c.playState
  5572. })
  5573. },
  5574. _play: function(c) {
  5575. c = new v.Animation(c,this);
  5576. this._animations.push(c);
  5577. v.restartWebAnimationsNextTick();
  5578. c._updatePromises();
  5579. c._animation.play();
  5580. c._updatePromises();
  5581. return c
  5582. },
  5583. play: function(c) {
  5584. c && c.remove();
  5585. return this._play(c)
  5586. }
  5587. };
  5588. var d = !1;
  5589. v.restartWebAnimationsNextTick = function() {
  5590. d || (d = !0,
  5591. requestAnimationFrame(f))
  5592. }
  5593. ;
  5594. var a = new v.AnimationTimeline;
  5595. v.timeline = a;
  5596. try {
  5597. Object.defineProperty(window.document, "timeline", {
  5598. configurable: !0,
  5599. get: function() {
  5600. return a
  5601. }
  5602. })
  5603. } catch (c) {}
  5604. try {
  5605. window.document.timeline = a
  5606. } catch (c) {}
  5607.  
  5608. */
  5609.  
  5610.  
  5611.  
  5612. /*
  5613.  
  5614. var g = window.getComputedStyle;
  5615. Object.defineProperty(window, "getComputedStyle", {
  5616. configurable: !0,
  5617. enumerable: !0,
  5618. value: function() {
  5619. v.timeline._updateAnimationsPromises();
  5620. var e = g.apply(this, arguments);
  5621. h() && (e = g.apply(this, arguments));
  5622. v.timeline._updateAnimationsPromises();
  5623. return e
  5624. }
  5625. });
  5626.  
  5627. */
  5628.  
  5629.  
  5630.  
  5631.  
  5632. }
  5633.  
  5634.  
  5635.  
  5636.  
  5637. })();
  5638.  
  5639. !isUrlInEmbed && Promise.resolve().then(() => {
  5640.  
  5641. // ==================================== FIX_avoid_incorrect_video_meta ====================================
  5642.  
  5643.  
  5644.  
  5645. class LimitedSizeSet extends Set {
  5646. constructor(n) {
  5647. super();
  5648.  
  5649. this.limit = n;
  5650. }
  5651.  
  5652. add(key) {
  5653. if (!super.has(key)) {
  5654. super.add(key); // Set the key with a dummy value (true)
  5655. while (super.size > this.limit) {
  5656. const firstKey = super.values().next().value; // Get the first (oldest) key
  5657. super.delete(firstKey); // Delete the oldest key
  5658. }
  5659. }
  5660. }
  5661.  
  5662. removeAdd(key) {
  5663. super.delete(key);
  5664. super.add(key);
  5665. }
  5666.  
  5667. }
  5668.  
  5669. // const wk3 = new WeakMap();
  5670.  
  5671. // let mtxVideoId = '';
  5672. // let aje3 = [];
  5673. const mfvContinuationRecorded = new LimitedSizeSet(8); // record all success continuation keys
  5674. const mfyContinuationIgnored = new LimitedSizeSet(8); // ignore continuation keys by copying the keys in the past
  5675. let mtzlastAllowedContinuation = ''; // the key stored at the last success; clear when scheduling changes
  5676. let mtzCount = 0; // the key keeps unchanged
  5677. // let mjtNextMainKey = '';
  5678. let mjtRecordedPrevKey = ''; // the key stored at the last success (no clear)
  5679. let mjtLockPreviousKey = ''; // the key before fetch() should be discarded. (uncertain continuation)
  5680. let mbCId322 = 0; // cid for delay fetchUpdatedMetadata
  5681. // let allowNoDelay322=false;
  5682. let mbDelayBelowNCalls = 0; // after N calls, by pass delay; reset when scheduling changes
  5683.  
  5684. let mpKey22 = ''; // last success continutation key & url pair
  5685. let mpUrl22 = ''; // last success continutation key & url pair
  5686. let mpKey21 = ''; // latest requested continutation key & url pair
  5687. let mpUrl21 = ''; // latest requested continutation key & url pair
  5688.  
  5689.  
  5690. async function sha1Hex(message) {
  5691. const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array
  5692. const hashBuffer = await crypto.subtle.digest("SHA-1", msgUint8); // hash the message
  5693. const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array
  5694. const hashHex = hashArray
  5695. .map((b) => b.toString(16).padStart(2, "0"))
  5696. .join(""); // convert bytes to hex string
  5697. return hashHex;
  5698. }
  5699.  
  5700. async function continuationLog(a, ...args) {
  5701. let b = a;
  5702. try {
  5703. if (advanceLogging) b = await sha1Hex(a);
  5704. let c = args.map(e => {
  5705. return e === a ? b : e
  5706. });
  5707. console.log(...c)
  5708. } catch (e) { console.warn(e) }
  5709. }
  5710.  
  5711. function copyPreviousContiuationToIgnored374(toClearRecorded) {
  5712.  
  5713.  
  5714. if (mfvContinuationRecorded.length > 0) {
  5715. for (const [e, d] of mfvContinuationRecorded) {
  5716. mfyContinuationIgnored.removeAdd(e);
  5717. }
  5718. toClearRecorded && mfvContinuationRecorded.clear();
  5719. }
  5720.  
  5721. }
  5722.  
  5723. function setup_ytTaskEmitterBehavior_TaskMgr374(taskMgr) {
  5724.  
  5725. const tmProto = taskMgr.constructor.prototype;
  5726. if (tmProto && typeof tmProto.addJob === 'function' && tmProto.addJob.length === 3 && typeof tmProto.cancelJob === 'function' && tmProto.cancelJob.length === 1) {
  5727.  
  5728. if (!tmProto.addJob714) {
  5729.  
  5730. tmProto.addJob714 = tmProto.addJob;
  5731.  
  5732. tmProto.addJob = function (a, b, c) {
  5733. const jobId = this.addJob714(a, b, c);
  5734. if (jobId > 0) {
  5735. // const ez = wk3.get(this);
  5736. // const dz = ez ? ez.data?.updatedMetadataEndpoint?.updatedMetadataEndpoint : null;
  5737. // aje3.push({mtx, jobId, a,b,c, element: this, dz, data: (ez?.data || null) })
  5738.  
  5739. this.__lastJobId863__ = jobId;
  5740. }
  5741. return jobId;
  5742. }
  5743.  
  5744. }
  5745.  
  5746. if (!tmProto.cancelJob714) {
  5747.  
  5748. tmProto.cancelJob714 = tmProto.cancelJob;
  5749.  
  5750. tmProto.cancelJob = function (a) {
  5751. const res = this.cancelJob714(a);
  5752. // if (a > 0) {
  5753. // for (const e of aje3) {
  5754. // if (e.jobId === a) e.cancelled = true;
  5755. // }
  5756. // }
  5757. return res;
  5758. }
  5759.  
  5760. }
  5761.  
  5762. }
  5763. }
  5764.  
  5765.  
  5766. const FIX_avoid_incorrect_video_meta_bool = FIX_avoid_incorrect_video_meta && isPrepareCachedV && check_for_set_key_order;
  5767.  
  5768.  
  5769. FIX_avoid_incorrect_video_meta_bool && whenCEDefined('ytd-video-primary-info-renderer').then(() => {
  5770. let dummy;
  5771. let cProto;
  5772. // let mc = 4;
  5773. // dummy = await observablePromise(() => {
  5774. // const r = document.querySelector('ytd-video-primary-info-renderer');
  5775. // if (!r) return;
  5776. // let cProto = insp(r).constructor.prototype;
  5777. // if (cProto.fetchUpdatedMetadata) return r;
  5778. // if (--mc < 0) return -1;
  5779. // return null;
  5780. // }).obtain();
  5781. dummy = document.createElement('ytd-video-primary-info-renderer');
  5782. if (!(dummy instanceof Element)) return;
  5783. // console.log(5022, dummy)
  5784. cProto = insp(dummy).constructor.prototype;
  5785.  
  5786. cProto.__getEmittorTaskMgr859__ = function () {
  5787. let taskMgr_ = null;
  5788. try {
  5789. taskMgr_ = (this.ytTaskEmitterBehavior || 0).getTaskManager() || null;
  5790. } catch (e) { }
  5791. return taskMgr_;
  5792. }
  5793. if (typeof cProto.fetchUpdatedMetadata === 'function' && cProto.fetchUpdatedMetadata.length === 1 && !cProto.fetchUpdatedMetadata717) {
  5794. // console.log(1234, cProto, cProto.is)
  5795. cProto.fetchUpdatedMetadata717 = cProto.fetchUpdatedMetadata;
  5796.  
  5797. let c_;
  5798. cProto.fetchUpdatedMetadata718 = function (a) {
  5799. // delay or immediate call the actual fetchUpdatedMetadata
  5800.  
  5801. let doImmediately = false;
  5802. if (a && typeof a === 'string' && mjtRecordedPrevKey && mjtRecordedPrevKey === mpKey22 && a === mpKey22 && (!pageSetupVideoId || pageSetupVideoId !== mpUrl22)) {
  5803.  
  5804. if (!pageSetupVideoId && videoPlayingY.videoId === mpUrl22) doImmediately = true;
  5805.  
  5806. } else if (typeof a !== 'string' || mbDelayBelowNCalls > 3 || !mpKey22 || (mpKey22 === a && mpKey22 !== mjtLockPreviousKey) || (mjtLockPreviousKey && mjtLockPreviousKey !== a)) {
  5807.  
  5808. doImmediately = true;
  5809.  
  5810. }
  5811.  
  5812. if (mbCId322) {
  5813. clearTimeout(mbCId322);
  5814. mbCId322 = 0;
  5815. }
  5816.  
  5817. if (doImmediately) return this.fetchUpdatedMetadata717(a);
  5818.  
  5819. let delay = mjtLockPreviousKey === a ? 8000 : 800;
  5820.  
  5821. mbCId322 = setTimeout(() => {
  5822. this.fetchUpdatedMetadata717(a);
  5823. }, delay);
  5824.  
  5825. console.log('[yt-js-engine-tamer]', '5190 delayed fetchUpdatedMetadata', delay);
  5826.  
  5827. }
  5828.  
  5829. cProto.fetchUpdatedMetadata = function (a) {
  5830.  
  5831. if (!pageSetupState) {
  5832. if (c_) clearTimeout(c_);
  5833. c_ = setTimeout(() => {
  5834. this.fetchUpdatedMetadata718(a);
  5835. }, 300);
  5836. return;
  5837. }
  5838.  
  5839. // pageSetupState == 0
  5840.  
  5841. try {
  5842.  
  5843. mbDelayBelowNCalls++;
  5844.  
  5845. if (arguments.length > 1 || !(a === undefined || (typeof a === 'string' && a))) {
  5846. console.warn("CAUTION: fetchUpdatedMetadata coding might have to be updated.");
  5847. }
  5848.  
  5849. // console.log('fum377', a)
  5850. if (typeof a === 'string' && mfyContinuationIgnored.has(a)) {
  5851. console.log('[yt-js-engine-tamer]', '5040 skip fetchUpdatedMetadata', a);
  5852. return;
  5853. }
  5854.  
  5855. if (!a && (this.data || 0).updatedMetadataEndpoint) {
  5856. if (mjtRecordedPrevKey && mjtLockPreviousKey !== mjtRecordedPrevKey) {
  5857. mjtLockPreviousKey = mjtRecordedPrevKey;
  5858. LOG_FETCHMETA_UPDATE && continuationLog(mjtLockPreviousKey, '5150 Lock Key', mjtLockPreviousKey);
  5859. }
  5860. // mjtNextMainKey = true;
  5861. mtzlastAllowedContinuation = '';
  5862. mtzCount = 0;
  5863. // allowNoDelay322 = false;
  5864. // fetch new metadata, cancel all previous continuations
  5865. copyPreviousContiuationToIgnored374(true);
  5866. } else if (typeof a === 'string') {
  5867. const videoPlayingId = videoPlayingY.videoId;
  5868.  
  5869. // if(mjtNextMainKey === true) mjtNextMainKey = a;
  5870.  
  5871. let update21 = !!pageSetupVideoId;
  5872. if (mpKey22 === a && mpUrl22 === videoPlayingId && mpUrl22 && videoPlayingId && (!pageSetupVideoId || pageSetupVideoId === videoPlayingId)) {
  5873. update21 = true;
  5874. } else if (mpKey22 === a && mpUrl22 !== pageSetupVideoId) {
  5875. LOG_FETCHMETA_UPDATE && continuationLog(mpKey22, '5060 mpUrl22 mismatched', mpKey22, mpUrl22, pageSetupVideoId || '(null)', videoPlayingId || '(null)');
  5876. return;
  5877. }
  5878. if (update21) {
  5879. mpKey21 = a;
  5880. mpUrl21 = pageSetupVideoId || videoPlayingId;
  5881. }
  5882.  
  5883. if (!mfvContinuationRecorded.has(a)) mfvContinuationRecorded.add(a);
  5884. }
  5885. LOG_FETCHMETA_UPDATE && continuationLog(a, '5180 fetchUpdatedMetadata\t', a, pageSetupVideoId || '(null)', videoPlayingY.videoId || '(null)');
  5886. // if (!pageSetupVideoId && typeof a === 'string' && a.length > 40) return; // ignore incorrect continuation
  5887. // if(a === mjtNextMainKey) allowNoDelay322 = false;
  5888. return this.fetchUpdatedMetadata718(a);
  5889.  
  5890. } catch (e) {
  5891. console.log('Code Error in fetchUpdatedMetadata', e);
  5892. }
  5893. return this.fetchUpdatedMetadata717(a)
  5894. }
  5895. }
  5896.  
  5897.  
  5898. if (typeof cProto.scheduleInitialUpdatedMetadataRequest === 'function' && cProto.scheduleInitialUpdatedMetadataRequest.length === 0 && !cProto.scheduleInitialUpdatedMetadataRequest717) {
  5899. // console.log(1234, cProto, cProto.is)
  5900. cProto.scheduleInitialUpdatedMetadataRequest717 = cProto.scheduleInitialUpdatedMetadataRequest;
  5901. let mJob = null;
  5902.  
  5903. cProto.scheduleInitialUpdatedMetadataRequest = function () {
  5904.  
  5905. try {
  5906.  
  5907. if (arguments.length > 0) {
  5908. console.warn("CAUTION: scheduleInitialUpdatedMetadataRequest coding might have to be updated.");
  5909. }
  5910. // mfy = mfv;
  5911.  
  5912. // mjtNextMainKey = '';
  5913. mtzlastAllowedContinuation = '';
  5914. mtzCount = 0;
  5915. if (mbCId322) {
  5916. clearTimeout(mbCId322);
  5917. mbCId322 = 0;
  5918. }
  5919. mbDelayBelowNCalls = 0;
  5920. // allowNoDelay322 = false;
  5921. copyPreviousContiuationToIgnored374(true);
  5922.  
  5923. const taskMgr = this.__getEmittorTaskMgr859__();
  5924. if (FIX_avoid_incorrect_video_meta_emitterBehavior && taskMgr && !taskMgr.addJob714 && taskMgr.addJob && taskMgr.cancelJob) setup_ytTaskEmitterBehavior_TaskMgr374(taskMgr);
  5925. if (FIX_avoid_incorrect_video_meta_emitterBehavior && taskMgr && !taskMgr.addJob714) {
  5926. console.log('[yt-js-engine-tamer]', 'scheduleInitialUpdatedMetadataRequest error 507');
  5927. }
  5928.  
  5929. // prevent depulicated schedule job by clearing previous JobId
  5930. if (taskMgr && typeof taskMgr.addLowPriorityJob === 'function' && taskMgr.addLowPriorityJob.length === 2 && typeof taskMgr.cancelJob === 'function' && taskMgr.cancelJob.length === 1) {
  5931.  
  5932. let res;
  5933.  
  5934. if (mJob) {
  5935. const job = mJob;
  5936. mJob = null;
  5937. console.log('cancelJob', job)
  5938. taskMgr.cancelJob(job); // clear previous [Interval Meta Update] job
  5939. // p.cancelJob(a,b);
  5940. }
  5941.  
  5942. // const updatedMetadataEndpoint = this.data?.updatedMetadataEndpoint?.updatedMetadataEndpoint
  5943.  
  5944. let pza = taskMgr.__lastJobId863__;
  5945. try { res = this.scheduleInitialUpdatedMetadataRequest717(); } catch (e) { }
  5946. let pzb = taskMgr.__lastJobId863__
  5947. if (pza !== pzb) {
  5948. mJob = pzb; // set [Interval Meta Update] jobId
  5949. }
  5950.  
  5951. // if (updatedMetadataEndpoint && updatedMetadataEndpoint.videoId) {
  5952. // mtxVideoId = updatedMetadataEndpoint.videoId || ''; // set the current target VideoId
  5953. // } else {
  5954. // mtxVideoId = ''; // sometimes updatedMetadataEndpoint is not ready
  5955. // }
  5956.  
  5957. return res;
  5958.  
  5959. } else {
  5960. console.log('[yt-js-engine-tamer]', 'scheduleInitialUpdatedMetadataRequest error 601');
  5961. }
  5962.  
  5963. } catch (e) {
  5964. console.log('Code Error in scheduleInitialUpdatedMetadataRequest', e);
  5965. }
  5966.  
  5967.  
  5968. return this.scheduleInitialUpdatedMetadataRequest717();
  5969. }
  5970. }
  5971.  
  5972.  
  5973. });
  5974.  
  5975. FIX_avoid_incorrect_video_meta_bool && promiseForYtActionCalled.then((ytAppDom) => {
  5976. let dummy;
  5977. let cProto;
  5978. dummy = ytAppDom;
  5979. if (!(dummy instanceof Element)) return;
  5980. cProto = insp(dummy).constructor.prototype;
  5981. if (typeof cProto.sendServiceAjax_ === 'function' && cProto.sendServiceAjax_.length === 4 && !cProto.sendServiceAjax717_) {
  5982. // console.log(1234, cProto, cProto.is);
  5983. // cProto.handleServiceRequest717_ = cProto.handleServiceRequest_;
  5984. // cProto.handleServiceRequest_ = function (a, b, c, d) {
  5985. // console.log(123401, arguments);
  5986. // return this.handleServiceRequest717_(a, b, c, d);
  5987. // }
  5988.  
  5989. // cProto.handleServiceRequest717_ = cProto.handleServiceRequest_;
  5990.  
  5991. // cProto.handleServiceRequest_ = function(a,b,c,d){
  5992. // console.log(59901, a?.is, b?.updatedMetadataEndpoint?.videoId, c?.continuation)
  5993. // if(a?.is === 'ytd-video-primary-info-renderer' && b?.updatedMetadataEndpoint?.videoId && c?.continuation && typeof c?.continuation ==='string'){
  5994. // console.log('mfv', c.continuation);
  5995. // mfv.add( c.continuation);
  5996. // }
  5997. // return this.handleServiceRequest717_(a,b,c,d);
  5998. // }
  5999.  
  6000. function extraArguments322(a, b, c) {
  6001. let is = (a || 0).is;
  6002. let videoId = ((b || 0).updatedMetadataEndpoint || 0).videoId;
  6003. let continuation = (c || 0).continuation;
  6004. if (typeof is !== 'string') is = null;
  6005. if (typeof videoId !== 'string') videoId = null;
  6006. if (typeof continuation !== 'string') continuation = null;
  6007. return { is, videoId, continuation };
  6008. }
  6009.  
  6010. cProto.sendServiceAjax717_ = cProto.sendServiceAjax_;
  6011. cProto.sendServiceAjax_ = function (a, b, c, d) {
  6012.  
  6013. // console.log(8001)
  6014. try {
  6015.  
  6016. const { is, videoId, continuation } = extraArguments322(a, b, c);
  6017.  
  6018. if ((videoId || continuation) && (is !== 'ytd-video-primary-info-renderer')) {
  6019. console.warn("CAUTION: sendServiceAjax_ coding might have to be updated.");
  6020. }
  6021.  
  6022. if (pageSetupVideoId && videoId && continuation) {
  6023. if (mpKey21 && mpUrl21 && mpKey21 === continuation && mpUrl21 !== pageSetupVideoId) {
  6024. mfyContinuationIgnored.removeAdd(continuation);
  6025. mfvContinuationRecorded.delete(continuation);
  6026. return;
  6027. }
  6028. }
  6029.  
  6030. if (mjtLockPreviousKey && mjtLockPreviousKey !== continuation && continuation) {
  6031. copyPreviousContiuationToIgnored374(false);
  6032. mfyContinuationIgnored.delete(continuation);
  6033. mfvContinuationRecorded.removeAdd(continuation);
  6034. mfyContinuationIgnored.removeAdd(mjtLockPreviousKey);
  6035. mfvContinuationRecorded.delete(mjtLockPreviousKey);
  6036. mjtLockPreviousKey = '';
  6037. }
  6038. // if (mjtNextMainKey === continuation) {
  6039. // copyPreviousContiuationToIgnored(false);
  6040. // mfyContinuationIgnored.delete(continuation);
  6041. // mfvContinuationRecorded.add(continuation);
  6042. // }
  6043.  
  6044.  
  6045. if (mfyContinuationIgnored && continuation) {
  6046. if (mfyContinuationIgnored.has(continuation)) {
  6047. LOG_FETCHMETA_UPDATE && continuationLog(continuation, '5260 matched01', continuation)
  6048. return;
  6049. }
  6050. }
  6051.  
  6052. // console.log(59902, a?.is, b,c,d)
  6053. // console.log(59903, a?.is, b?.updatedMetadataEndpoint?.videoId, c?.continuation)
  6054. if (is === 'ytd-video-primary-info-renderer' && videoId && continuation && !mfvContinuationRecorded.has(continuation)) {
  6055. // console.log('mfv377', continuation);
  6056. mfvContinuationRecorded.add(continuation);
  6057. }
  6058.  
  6059. // if (videoId) {
  6060. // if (!pageSetupVideoId) return; // ignore page not ready
  6061. // // if (mtxVideoId && b.updatedMetadataEndpoint.videoId !== mtxVideoId) return; // ignore videoID not matched
  6062. // if (videoId !== pageSetupVideoId) {
  6063. // return;
  6064. // }
  6065. // }
  6066.  
  6067. } catch (e) {
  6068. console.log('Coding Error in sendServiceAjax_', e)
  6069. }
  6070. // console.log(8002)
  6071. // console.log(123402, arguments);
  6072. // console.log(5162, 'a',a?.is,'b',b,'c',c,'d',d);
  6073.  
  6074. // console.log(5211, b?.updatedMetadataEndpoint?.kdkw33);
  6075. // if(b &&b.updatedMetadataEndpoint && !b.updatedMetadataEndpoint.kdkw33){
  6076. // b.updatedMetadataEndpoint = new Proxy(b.updatedMetadataEndpoint, {
  6077. // get(target, prop, receiver){
  6078. // console.log('xxs99', target.videoId, mtx)
  6079. // if(prop ==='kdkw33') return 1;
  6080. // console.log(3322, prop, target)
  6081. // if(prop === 'initialDelayMs') {
  6082. // throw new Error("ABCC");
  6083. // }
  6084. // return target[prop];
  6085. // },
  6086. // set(target, prop, value, receiver){
  6087.  
  6088. // if(prop ==='kdkw33') return true;
  6089. // target[prop]=value;
  6090. // return true;
  6091. // }
  6092. // });
  6093. // }
  6094. // console.log(5533, b?.updatedMetadataEndpoint?.kdkw33)
  6095. return this.sendServiceAjax717_(a, b, c, d);
  6096. }
  6097. }
  6098.  
  6099. function delayClearOtherKeys(lztContinuation) {
  6100. // // schedule delayed removal if mfyContinuationIgnored is not empty
  6101. // getRafPromise().then(() => {
  6102. // // assume the repeat continuation could be only for popstate which is triggered by user interaction
  6103. // // foreground page only
  6104.  
  6105. // });
  6106.  
  6107.  
  6108. if (lztContinuation !== mtzlastAllowedContinuation) return;
  6109. if (lztContinuation !== mpKey21 || lztContinuation !== mpKey22) return;
  6110. if (!mfyContinuationIgnored.size) return;
  6111. if (mfyContinuationIgnored.size > 1) {
  6112. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, 'delayClearOtherKeys, current = ', lztContinuation);
  6113. }
  6114. mfyContinuationIgnored.forEach((value, key) => {
  6115. if (key !== lztContinuation) {
  6116. mfyContinuationIgnored.delete(key);
  6117. LOG_FETCHMETA_UPDATE && continuationLog(key, 'previous continuation removed from ignored store', key);
  6118. }
  6119. });
  6120.  
  6121. }
  6122. if (typeof cProto.getCancellableNetworkPromise_ === 'function' && cProto.getCancellableNetworkPromise_.length === 5 && !cProto.getCancellableNetworkPromise717_) {
  6123. cProto.getCancellableNetworkPromise717_ = cProto.getCancellableNetworkPromise_;
  6124. cProto.getCancellableNetworkPromise_ = function (a, b, c, d, e) {
  6125.  
  6126. // console.log(8003)
  6127. try {
  6128.  
  6129.  
  6130. const { is, videoId, continuation } = extraArguments322(b, c, d);
  6131.  
  6132. if ((videoId || continuation) && (is !== 'ytd-video-primary-info-renderer')) {
  6133. console.warn("CAUTION: getCancellableNetworkPromise_ coding might have to be updated.");
  6134. }
  6135.  
  6136. if (pageSetupVideoId && videoId && continuation) {
  6137. if (mpKey21 && mpUrl21 && mpKey21 === continuation && mpUrl21 !== pageSetupVideoId) {
  6138. mfyContinuationIgnored.removeAdd(continuation);
  6139. mfvContinuationRecorded.delete(continuation);
  6140. return;
  6141. }
  6142. }
  6143.  
  6144. if (mjtLockPreviousKey && mjtLockPreviousKey !== continuation && continuation) {
  6145. copyPreviousContiuationToIgnored374(false);
  6146. mfyContinuationIgnored.delete(continuation);
  6147. mfvContinuationRecorded.removeAdd(continuation);
  6148. mfyContinuationIgnored.removeAdd(mjtLockPreviousKey);
  6149. mfvContinuationRecorded.delete(mjtLockPreviousKey);
  6150. mjtLockPreviousKey = '';
  6151. }
  6152.  
  6153. // if (mjtNextMainKey === continuation) {
  6154. // copyPreviousContiuationToIgnored(false);
  6155. // mfyContinuationIgnored.delete(continuation);
  6156. // mfvContinuationRecorded.add(continuation);
  6157. // }
  6158.  
  6159. const lztContinuation = continuation;
  6160.  
  6161. if (mfyContinuationIgnored && lztContinuation && typeof lztContinuation === 'string') {
  6162. if (mfyContinuationIgnored.has(lztContinuation)) {
  6163. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, '5360 matched02', lztContinuation)
  6164. return;
  6165. }
  6166. }
  6167.  
  6168. // if (videoId) {
  6169. // if (!pageSetupVideoId) return; // ignore page not ready
  6170. // // if (mtxVideoId && c.updatedMetadataEndpoint.videoId !== mtxVideoId) return; // ignore videoID not matched
  6171. // if (videoId !== pageSetupVideoId) {
  6172. // return;
  6173. // }
  6174. // }
  6175.  
  6176. if (typeof lztContinuation === 'string' && mtzlastAllowedContinuation !== lztContinuation) {
  6177. mtzlastAllowedContinuation = lztContinuation;
  6178. // console.log(70401, lztContinuation, mfyContinuationIgnored.size)
  6179.  
  6180. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, '5382 Continuation sets to\t', lztContinuation, `C${mtzCount}.R${mfvContinuationRecorded.size}.I${mfyContinuationIgnored.size}`);
  6181. mjtRecordedPrevKey = lztContinuation;
  6182. if (mjtLockPreviousKey === lztContinuation) mjtLockPreviousKey = '';
  6183. // if (mfyContinuationIgnored.size > 0) {
  6184. // delayClearOtherKeys(lztContinuation);
  6185. // }
  6186. mtzCount = 0;
  6187. // allowNoDelay322 = false;
  6188. } else if (typeof lztContinuation === 'string' && mtzlastAllowedContinuation && mtzlastAllowedContinuation === lztContinuation) {
  6189. // repeated
  6190. if (mtzCount > 1e9) mtzCount = 1e4;
  6191. ++mtzCount;
  6192. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, '5386 Same Continuation\t\t', lztContinuation, `C${mtzCount}.R${mfvContinuationRecorded.size}.I${mfyContinuationIgnored.size}`);
  6193.  
  6194. // if (mtzCount >= 3) allowNoDelay322 = true;
  6195. if (mtzCount >= 3 && mfyContinuationIgnored.size > 0) {
  6196. Promise.resolve(lztContinuation).then(delayClearOtherKeys).catch(console.warn);
  6197. }
  6198. if (mtzCount === 5) {
  6199. mfvContinuationRecorded.clear();
  6200. mfvContinuationRecorded.add(lztContinuation);
  6201. }
  6202.  
  6203. }
  6204.  
  6205. if (typeof lztContinuation === 'string' && lztContinuation && (pageSetupVideoId || videoPlayingY.videoId)) {
  6206. mpKey22 = lztContinuation;
  6207. mpUrl22 = pageSetupVideoId || videoPlayingY.videoId;
  6208. }
  6209.  
  6210. if (mbCId322) {
  6211. clearTimeout(mbCId322);
  6212. mbCId322 = 0;
  6213. }
  6214. } catch (e) {
  6215. console.log('Coding Error in getCancellableNetworkPromise_', e)
  6216. }
  6217.  
  6218. // console.log(8004)
  6219. // console.log(123403, arguments);
  6220. // if(c.updatedMetadataEndpoint) console.log(123404, pageSetupVideoId, JSON.stringify(c.updatedMetadataEndpoint))
  6221.  
  6222. // console.log(5163, a?.is,b,c,d,e);
  6223. return this.getCancellableNetworkPromise717_(a, b, c, d, e);
  6224. }
  6225. }
  6226. });
  6227.  
  6228. // ==================================== FIX_avoid_incorrect_video_meta ====================================
  6229.  
  6230.  
  6231. FIX_ytdExpander_childrenChanged && whenCEDefined('ytd-expander').then(() => {
  6232.  
  6233. let dummy;
  6234. let cProto;
  6235.  
  6236. dummy = document.createElement('ytd-expander');
  6237. cProto = insp(dummy).constructor.prototype;
  6238.  
  6239. if (fnIntegrity(cProto.initChildrenObserver, '0.48.21') && fnIntegrity(cProto.childrenChanged, '0.40.22')) {
  6240.  
  6241. cProto.initChildrenObserver14 = cProto.initChildrenObserver;
  6242. cProto.childrenChanged14 = cProto.childrenChanged;
  6243.  
  6244. cProto.initChildrenObserver = function () {
  6245. var a = this;
  6246. this.observer = new MutationObserver(function () {
  6247. a.childrenChanged()
  6248. }
  6249. );
  6250. this.observer.observe(this.content, {
  6251. subtree: !0,
  6252. childList: !0,
  6253. attributes: !0,
  6254. characterData: !0
  6255. });
  6256. this.childrenChanged()
  6257. }
  6258. ;
  6259. cProto.childrenChanged = function () {
  6260. if (this.alwaysToggleable) {
  6261. this.canToggle = this.alwaysToggleable;
  6262. } else if (!this.canToggleJobId) {
  6263. this.canToggleJobId = 1;
  6264. getRafPromise().then(() => {
  6265. this.canToggleJobId = 0;
  6266. this.calculateCanCollapse()
  6267. })
  6268. }
  6269. }
  6270.  
  6271. // console.log(cProto.initChildrenObserver)
  6272. console.debug('ytd-expander-fix-childrenChanged');
  6273.  
  6274. }
  6275.  
  6276. });
  6277.  
  6278.  
  6279. FIX_paper_ripple_animate && whenCEDefined('paper-ripple').then(() => {
  6280.  
  6281. let dummy;
  6282. let cProto;
  6283. dummy = document.createElement('paper-ripple');
  6284. cProto = insp(dummy).constructor.prototype;
  6285.  
  6286. if (fnIntegrity(cProto.animate, '0.74.5')) {
  6287.  
  6288.  
  6289. cProto.animate34 = cProto.animate;
  6290. cProto.animate = function () {
  6291. if (this._animating) {
  6292. var a;
  6293. const ripples = this.ripples;
  6294. for (a = 0; a < ripples.length; ++a) {
  6295. var b = ripples[a];
  6296. b.draw();
  6297. this.$.background.style.opacity = b.outerOpacity;
  6298. b.isOpacityFullyDecayed && !b.isRestingAtMaxRadius && this.removeRipple(b)
  6299. }
  6300. if ((this.shouldKeepAnimating || 0) !== ripples.length) {
  6301. if (!this._boundAnimate38) this._boundAnimate38 = this.animate.bind(this);
  6302. getRafPromise().then(this._boundAnimate38);
  6303. } else {
  6304. this.onAnimationComplete()
  6305. }
  6306. }
  6307. }
  6308.  
  6309. console.debug('FIX_paper_ripple_animate')
  6310.  
  6311. // console.log(cProto.animate)
  6312.  
  6313. }
  6314.  
  6315. });
  6316.  
  6317. if (FIX_doIdomRender) {
  6318.  
  6319. const xsetTimeout = function (f, d) {
  6320. if (xsetTimeout.m511 === 1 && !d) {
  6321. xsetTimeout.m511 = 2;
  6322. getRafPromise().then(f);
  6323. } else {
  6324. return setTimeout.apply(window, arguments)
  6325. }
  6326.  
  6327. }
  6328.  
  6329. const xrequestAnimationFrame = function (f) {
  6330. const h = f + "";
  6331. if (h.startsWith("function(){setTimeout(function(){") && h.endsWith("})}")) {
  6332. xsetTimeout.m511 = 1;
  6333. f();
  6334. xsetTimeout.m511 = 0;
  6335. } else if (h.includes("requestAninmationFrameResolver")) {
  6336. getRafPromise().then(f);
  6337. } else {
  6338. return requestAnimationFrame.apply(window, arguments);
  6339. }
  6340. }
  6341.  
  6342. let busy = false;
  6343. const doIdomRender = function () {
  6344. if (busy) {
  6345. return this.doIdomRender13.apply(this, arguments);
  6346. }
  6347. busy = true;
  6348. const { requestAnimationFrame, setTimeout } = window;
  6349. window.requestAnimationFrame = xrequestAnimationFrame;
  6350. window.setTimeout = xsetTimeout;
  6351. let r = this.doIdomRender13.apply(this, arguments);
  6352. window.requestAnimationFrame = requestAnimationFrame;
  6353. window.setTimeout = setTimeout;
  6354. busy = false;
  6355. return r;
  6356. };
  6357. for (const ytTag of ['ytd-lottie-player', 'yt-attributed-string', 'yt-image', 'yt-icon-shape', 'yt-button-shape', 'yt-button-view-model', 'yt-icon-badge-shape']) {
  6358.  
  6359.  
  6360. whenCEDefined(ytTag).then(() => {
  6361.  
  6362. let dummy;
  6363. let cProto;
  6364. dummy = document.createElement(ytTag);
  6365. cProto = insp(dummy).constructor.prototype;
  6366.  
  6367. cProto.doIdomRender13 = cProto.doIdomRender;
  6368. cProto.doIdomRender = doIdomRender;
  6369.  
  6370. if (cProto.doIdomRender13 === cProto.templatingFn) cProto.templatingFn = doIdomRender;
  6371.  
  6372. console.debug('FIX_doIdomRender', ytTag)
  6373.  
  6374.  
  6375.  
  6376. });
  6377.  
  6378. }
  6379.  
  6380. }
  6381.  
  6382.  
  6383.  
  6384. });
  6385.  
  6386. });
  6387.  
  6388.  
  6389.  
  6390.  
  6391. if (isMainWindow) {
  6392.  
  6393. console.groupCollapsed(
  6394. "%cYouTube JS Engine Tamer",
  6395. "background-color: #EDE43B ; color: #000 ; font-weight: bold ; padding: 4px ;"
  6396. );
  6397.  
  6398.  
  6399.  
  6400. console.log("Script is loaded.");
  6401. console.log("This script changes the core mechanisms of the YouTube JS engine.");
  6402.  
  6403. console.log("This script is experimental and subject to further changes.");
  6404.  
  6405. console.log("This might boost your YouTube performance.");
  6406.  
  6407. console.log("CAUTION: This might break your YouTube.");
  6408.  
  6409.  
  6410. if (prepareLogs.length >= 1) {
  6411. console.log(" =========================================================================== ");
  6412.  
  6413. for (const msg of prepareLogs) {
  6414. console.log(msg)
  6415. }
  6416.  
  6417. console.log(" =========================================================================== ");
  6418. }
  6419.  
  6420. console.groupEnd();
  6421.  
  6422. }
  6423.  
  6424.  
  6425.  
  6426. })();