Greasy Fork is available in English.

YouTube JS Engine Tamer

To enhance YouTube performance by modifying YouTube JS Engine

As of 2025-02-10. See the latest version.

  1. // ==UserScript==
  2. // @name YouTube JS Engine Tamer
  3. // @namespace UserScripts
  4. // @version 0.17.12
  5. // @match https://www.youtube.com/*
  6. // @match https://www.youtube-nocookie.com/embed/*
  7. // @match https://studio.youtube.com/live_chat*
  8. // @license MIT
  9. // @author CY Fung
  10. // @icon https://raw.githubusercontent.com/cyfung1031/userscript-supports/main/icons/yt-engine.png
  11. // @description To enhance YouTube performance by modifying YouTube JS Engine
  12. // @grant none
  13. // @require https://cdn.jsdelivr.net/gh/cyfung1031/userscript-supports@7221a4efffd49d852de0074ec503d4febb99f28b/library/nextBrowserTick.min.js
  14. // @run-at document-start
  15. // @unwrap
  16. // @inject-into page
  17. // @allFrames true
  18. // ==/UserScript==
  19.  
  20. (() => {
  21.  
  22. /** @type {WeakMapConstructor} */
  23. const WeakMap = window.WeakMapOriginal || window.WeakMap;
  24.  
  25. const NATIVE_CANVAS_ANIMATION = false; // for #cinematics
  26. const FIX_schedulerInstanceInstance = 2 | 4;
  27. const FIX_yt_player = true; // DONT CHANGE
  28. const FIX_Animation_n_timeline = true;
  29. const NO_PRELOAD_GENERATE_204 = false;
  30. const ENABLE_COMPUTEDSTYLE_CACHE = true;
  31. const NO_SCHEDULING_DUE_TO_COMPUTEDSTYLE = true;
  32. const CHANGE_appendChild = true; // discussions#236759
  33. const FIX_bind_self_this = false; // EXPERIMENTAL !!!!! this affect page switch after live ends
  34. const FIX_weakMap_weakRef = false; // EXPERIMENTAL !!!!! Might Incompatible to some userscripts (as the strong relationship is removed)
  35.  
  36. const FIX_error_many_stack = true; // should be a bug caused by uBlock Origin
  37. // const FIX_error_many_stack_keepAliveDuration = 200; // ms
  38. // const FIX_error_many_stack_keepAliveDuration_check_if_n_larger_than = 8;
  39.  
  40. const FIX_Iframe_NULL_SRC = false;
  41.  
  42. const IGNORE_bindAnimationForCustomEffect = true; // prevent `v.bindAnimationForCustomEffect(this);` being executed
  43.  
  44. const FIX_ytdExpander_childrenChanged = true;
  45. const FIX_paper_ripple_animate = true;
  46. const FIX_avoid_incorrect_video_meta = true; // omit the incorrect yt-animated-rolling-number
  47. const FIX_avoid_incorrect_video_meta_emitterBehavior = true;
  48.  
  49. const FIX_doIdomRender = true;
  50.  
  51. const FIX_Shady = true;
  52.  
  53. // [[ 2024.04.24 ]]
  54. const MODIFY_ShadyDOM_OBJ = true;
  55. // << if MODIFY_ShadyDOM_OBJ >>
  56. const WEAKREF_ShadyDOM = true;
  57. const OMIT_ShadyDOM_EXPERIMENTAL = 1 | 0; // 1 => enable; 2 => composedPath
  58. const OMIT_ShadyDOM_settings = 0 | 0 | 0; // 1: inUse; 2: handlesDynamicScoping; 4: force // {{ PRELIM TESTING PURPOSE }}
  59. // << end >>
  60.  
  61. const WEAK_REF_BINDING_CONTROL = 1 | 2; // 2 - conflict control with ShadyDOM weakref
  62.  
  63. const FIX_ytAction_ = true; // ytd-app
  64. const FIX_onVideoDataChange = false;
  65. // const FIX_onClick = true;
  66. const FIX_onStateChange = true;
  67. const FIX_onLoopRangeChange = true;
  68. // const FIX_maybeUpdateFlexibleMenu = true; // ytd-menu-renderer
  69. const FIX_VideoEVENTS_v2 = true; // true might cause bug in switching page
  70.  
  71. const ENABLE_discreteTasking = true;
  72. // << if ENABLE_discreteTasking >>
  73. const FIX_stampDomArray_stableList = true;
  74. const ENABLE_weakenStampReferences = true; // disabled in old browsers
  75. // << end >>
  76.  
  77. const FIX_perfNow = true; // history state issue; see https://bugzilla.mozilla.org/show_bug.cgi?id=1756970
  78. const ENABLE_ASYNC_DISPATCHEVENT = false; // problematic
  79.  
  80. const FIX_Polymer_dom = true;
  81.  
  82. const SCRIPTLET_REMOVE_PRUNE_propNeedles = true; // brave scriptlet related
  83. const DEBUG_removePrune = false; // true for DEBUG
  84.  
  85. const FIX_XHR_REQUESTING = true;
  86.  
  87. const LOG_FETCHMETA_UPDATE = false; // for DEBUG
  88.  
  89. const IGNORE_bufferhealth_CHECK = false; // experimental; true will make "Stats for nerds" no info.
  90.  
  91. const DENY_requestStorageAccess = true; // remove document.requestStorageAccess
  92. const DISABLE_IFRAME_requestStorageAccess = true; // no effect if DENY_requestStorageAccess is true
  93.  
  94. const DISABLE_COOLDOWN_SCROLLING = true; // YT cause scroll hang in MacOS
  95.  
  96. const FIX_removeChild = true;
  97. const FIX_fix_requestIdleCallback_timing = true;
  98.  
  99. const HOOK_CSSPD_LEFT = true; // global css hack for style.left
  100. const FORCE_NO_REUSEABLE_ELEMENT_POOL = true;
  101.  
  102. const FIX_TRANSCRIPT_SEGMENTS = true; // Based on Tabview Youtube's implementation
  103.  
  104. const FIX_POPUP_UNIQUE_ID = true; // currently only for channel about popup;
  105.  
  106. // ----------------------------- POPUP UNIQUE ID ISSUE -----------------------------
  107. // example. https://www.youtube.com/channel/UCgPev1KKSCMbnNRsvN83Hag/about
  108. // first tp-yt-paper-dialog: show once the page is loaded.
  109. // second tp-yt-paper-dialog: click "...more"
  110. // third tp-yt-paper-dialog: click "... and 3 more links"
  111. // check with document.querySelectorAll('ytd-popup-container tp-yt-paper-dialog').length
  112. // currently, uniqueId is preassigned by the network resolveCommand.
  113. // so don't modify the source side, just modify the display side (popup display) via handleOpenPopupAction
  114. // other related functions e.g. handleClosePopupCommand_, getAndMaybeCreatePopup_, handleClosePopupAction_, getAndMaybeCreatePopup_
  115.  
  116. // handleOpenPopupAction -> createCacheKey
  117. // handleClosePopupAction_ -> createCacheKey
  118. // handleGetPopupOpenedAction_ -> createCacheKey
  119. // getAndMaybeCreatePopup_ -> createCacheKey
  120. // closePopup -> createCacheKey
  121.  
  122. // yt-close-popup-command -> handleClosePopupCommand_
  123.  
  124. // ensurePopup_ -> getAndMaybeCreatePopup_
  125.  
  126. // yt-close-popup-action -> handleClosePopupAction_
  127. // closePopup -> handleClosePopupAction_
  128. // handleOpenPopupAction -> handleClosePopupAction_
  129. // handleClosePopupCommand_ -> handleClosePopupAction_
  130. // closeSheet -> handleClosePopupAction_("yt-sheet-view-model")
  131.  
  132. // yt-open-popup-action -> handleOpenPopupAction
  133.  
  134.  
  135. // yt-close-popup-action -> handleClosePopupAction_ -> createCacheKey
  136. // yt-close-popup-command -> handleClosePopupCommand_ -> handleClosePopupAction_ -> createCacheKey
  137.  
  138. // Experimental flag "ytpopup_disable_default_html_caching" is disabled by default.
  139. // Not sure enabling it can make GC or not (Yt Components are usually not GC-able)
  140. // ----------------------------- POPUP UNIQUE ID ISSUE -----------------------------
  141.  
  142.  
  143. const FIX_DOM_IF_REPEAT = true; // semi-experimental (added in 0.17.0)
  144. const FIX_DOM_IF_TEMPLATE = true;
  145. // const FIX_DOM_REPEAT_TEMPLATE = true; // to be implemented
  146. const FIX_DOM_IFREPEAT_RenderDebouncerChange = false; // semi-experimental (added in 0.17.0) // found buggy for chat ticker sizing
  147. const DEBUG_DBR847 = false;
  148. const DEBUG_xx847 = false;
  149. const FIX_DOM_IFREPEAT_RenderDebouncerChange_SET_TO_PROPNAME = true; // default true. false might be required for future change
  150. const DEBUG_renderDebounceTs = false;
  151.  
  152.  
  153. const FIX_VIDEO_PLAYER_MOUSEHOVER_EVENTS = true; // avoid unnecessary reflows due to cursor moves on the web player.
  154.  
  155. /*
  156.  
  157. FIX_DOM_IFREPEAT_RenderDebouncerChange
  158.  
  159. avoid Polymer.flush
  160. // https://www.youtube.com/s/desktop/26a583e4/jsbin/live_chat_polymer.vflset/live_chat_polymer.js
  161.  
  162. var Is = function() {
  163. do {
  164. var a = window.ShadyDOM && ShadyDOM.flush();
  165. window.ShadyCSS && window.ShadyCSS.ScopingShim && window.ShadyCSS.ScopingShim.flush();
  166. var b = NNa()
  167. } while (a || b)
  168. };
  169.  
  170. , NNa = function() {
  171. var a = !!ts.size;
  172. ts.forEach(function(b) {
  173. try {
  174. b.flush()
  175. } catch (c) {
  176. setTimeout(function() {
  177. throw c
  178. })
  179. }
  180. });
  181. return a
  182. };
  183.  
  184. // why flush twice after all ts are completed? (!!ts.size => true => loop again)
  185. // this coding logic should be incorrect (mistake).
  186.  
  187. */
  188.  
  189.  
  190.  
  191. // ----------------------------- Shortkey Keyboard Control -----------------------------
  192. // dependency: FIX_yt_player
  193.  
  194. const FIX_SHORTCUTKEYS = 2; // 0 - no fix; 1 - basic fix; 2 - advanced fix
  195. // [0] no fix - not recommended
  196. // [1] basic fix - just fix the global focus detection variable
  197. // [2] advanced fix - call the shortcut actions directly, auto foucs change, direct control of spacebar behavior, etc
  198. // (note) 0 or 1 if you find conflict with other userscripts/plugin
  199.  
  200. const CHANGE_SPEEDMASTER_SPACEBAR_CONTROL = 0; // 0 - disable; 1 - force true; 2 - force false
  201. const USE_IMPROVED_PAUSERESUME_UNDER_NO_SPEEDMASTER = true; // only for SPEEDMASTER = false & FIX_SHORTCUTKEYS = 2
  202.  
  203. const PROP_OverReInclusion_AVOID = true;
  204. const PROP_OverReInclusion_DEBUGLOG = false;
  205. const PROP_OverReInclusion_LIST = new Set([
  206. 'hostElement72',
  207. 'parentComponent72',
  208. 'localVisibilityObserver_72',
  209. 'cachedProviderNode_72',
  210. '__template72',
  211. '__templatizeOwner72',
  212. '__templateInfo72',
  213. '__dataHost72',
  214. '__CE_shadowRoot72',
  215. 'elements_72',
  216.  
  217. 'ky36',
  218. 'kz62',
  219. 'm822',
  220.  
  221.  
  222.  
  223. // To be reviewed.
  224.  
  225. // chat messages
  226. 'disabled', 'allowedProps',
  227. 'filledButtonOverrides', 'openPopupConfig', 'supportsInlineActionButtons', 'allowedProps',
  228.  
  229. 'dimension', 'loadTime', 'pendingPaint',
  230.  
  231. 'countdownDurationMs', 'countdownMs', 'lastCountdownTimeMs', 'rafId', 'playerProgressSec', 'detlaSincePausedSecs', 'behaviorActionMap', 'selected', 'maxLikeCount', 'maxReplyCount', 'isMouseOver',
  232.  
  233. 'respectLangDir', 'noEndpoints',
  234.  
  235.  
  236. 'objectURL',
  237. 'buttonOverrides', 'queuedMessages',
  238. 'STEP', 'BLOCK_ON', 'MIN_PROGESS', 'MAX_PROGESS',
  239. 'DISMISSED_CONTENT_KEYSPACE', 'followUpDialogPromise', 'followUpDialogPromiseResolve', 'followUpDialogPromiseReject',
  240. 'hoverJobId', 'JSC$14573_touched',
  241.  
  242.  
  243. // tbc
  244. 'toggleable', 'isConnected',
  245. 'scrollDistance', 'dragging', 'dragMouseStart', 'dragOffsetStart', 'containerWidthDiff',
  246. 'disableDeselectEvent',
  247. 'emojiSize',
  248.  
  249. 'buttonOverride',
  250. 'shouldUseStickyPreferences', 'longPressTimeoutId',
  251.  
  252. // others
  253. 'observeVisibleOption', 'observeHiddenOption', 'observePrescanOption', 'visibilityMonitorKeys',
  254. // 'filledButtonOverrides', 'openPopupConfig', 'supportsInlineActionButtons',
  255. 'observeVisibleOption', 'observeHiddenOption', 'observePrescanOption', 'visibilityMonitorKeys',
  256. // 'dimension', 'loadTime', 'pendingPaint',
  257. // 'disabled', 'allowedProps',
  258.  
  259.  
  260. // 'enableMssLazyLoad', 'popupContainerConfig', 'actionRouterNode', 'actionRouterIsRoot', 'actionMap', 'dynamicActionMap',
  261. // 'actionMap',
  262.  
  263. // 'sharedTooltipPosition', 'sharedTooltipAnimationDelay', 'disableEmojiPickerIncrementalLoading', 'useResolveCommand', 'activeRequest', 'popoutWindowCheckIntervalId', 'supportedTooltipTargets', 'closeActionPanelTimerId', 'delayCloseActionPanelTimerId', 'tooltipTimerIds', 'queuedTooltips', 'isPopupConfigReady', 'popoutWindow', 'actionMap',
  264.  
  265. 'clearTimeout',
  266. 'switchTemplateAtRegistration', 'hasUnmounted',
  267. 'switchTemplateAtRegistration', 'stopKeyboardEventPropagation',
  268. 'tangoConfiguration',
  269. 'itemIdToDockDurationMap',
  270. 'actionMap',
  271.  
  272. 'emojiManager', 'inputMethodEditorActive', 'suggestionIndex', 'JSC$10745_lastSuggestionRange',
  273. 'actionMap', 'asyncHandle', 'shouldAnimateIn', 'lastFrameTimestamp', 'scrollClampRaf',
  274. 'scrollRatePixelsPerSecond', 'scrollStartTime', 'scrollStopHandle'
  275.  
  276. // 'buttonOverrides', 'queuedMessages', 'clearTimeout', 'actionMap',
  277. // 'stopKeyboardEventPropagation', 'emojiSize',
  278. // 'switchTemplateAtRegistration', 'hasUnmounted',
  279. // 'buttonOverrides', 'queuedMessages', 'clearTimeout', 'actionMap',
  280. // 'isReusable', 'tangoConfiguration',
  281. // 'itemIdToDockDurationMap', 'bottomAlignMessages', 'actionMap',
  282. // */
  283.  
  284. ]);
  285.  
  286.  
  287. // const CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE = false; // NO USE; TO BE REVIEWED
  288.  
  289. // ----------------------------- Shortkey Keyboard Control -----------------------------
  290.  
  291. /*
  292. window.addEventListener('edm',()=>{
  293. let p = [...this.onerror.errorTokens][0].token; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })()
  294. });
  295.  
  296. window.addEventListener('edn',()=>{
  297. let p = [...this.onerror.errorTokens][0].token+"X"; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })()
  298. });
  299. window.addEventListener('edr',()=>{
  300. let p = '123'; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })()
  301. });
  302. */
  303.  
  304. // only for macOS with Chrome/Firefox 100+
  305. const advanceLogging = typeof AbortSignal !== 'undefined' && typeof (AbortSignal || 0).timeout === 'function' && typeof navigator !== 'undefined' && /\b(Macintosh|Mac\s*OS)\b/i.test((navigator || 0).userAgent || '');
  306.  
  307. const win = this instanceof Window ? this : window;
  308.  
  309. // Create a unique key for the script and check if it is already running
  310. const hkey_script = 'jswylcojvzts';
  311. if (win[hkey_script]) throw new Error('Duplicated Userscript Calling'); // avoid duplicated scripting
  312. win[hkey_script] = true;
  313.  
  314.  
  315. // const [setTimeoutX0, clearTimeoutX0] = [setTimeout, clearTimeout];
  316.  
  317. let BY_PASS_KEYBOARD_CONTROL = false;
  318.  
  319.  
  320. // const setImmediate = ((self || 0).jmt || 0).setImmediate;
  321. /** @type {(f: ()=>{})=>{}} */
  322. const nextBrowserTick = (self || 0).nextBrowserTick || 0;
  323. const nextBrowserTick_ = nextBrowserTick || (f => f());
  324.  
  325. let p59 = 0;
  326.  
  327. const Promise = (async () => { })().constructor;
  328.  
  329. const PromiseExternal = ((resolve_, reject_) => {
  330. const h = (resolve, reject) => { resolve_ = resolve; reject_ = reject };
  331. return class PromiseExternal extends Promise {
  332. constructor(cb = h) {
  333. super(cb);
  334. if (cb === h) {
  335. /** @type {(value: any) => void} */
  336. this.resolve = resolve_;
  337. /** @type {(reason?: any) => void} */
  338. this.reject = reject_;
  339. }
  340. }
  341. };
  342. })();
  343.  
  344. /**
  345. @param {number} x
  346. @param {number} d */
  347. const toFixed2 = (x, d) => {
  348. let t = x.toFixed(d);
  349. let y = `${+t}`;
  350. return y.length > t.length ? t : y;
  351. }
  352.  
  353.  
  354. const isChatRoomURL = location.pathname.startsWith('/live_chat');
  355.  
  356.  
  357. const TRANSLATE_DEBUG = false;
  358.  
  359.  
  360. function getTranslate() {
  361.  
  362. pLoad.then(() => {
  363.  
  364. let nonce = document.querySelector('style[nonce]');
  365. nonce = nonce ? nonce.getAttribute('nonce') : null;
  366. const st = document.createElement('style');
  367. if (typeof nonce === 'string') st.setAttribute('nonce', nonce);
  368. st.textContent = "yt-formatted-string.segment-text.style-scope.ytd-transcript-segment-renderer>span{display:block}";
  369. let parent;
  370. if (parent = document.head) parent.appendChild(st);
  371. else if (parent = (document.body || document.documentElement)) parent.insertBefore(st, parent.firstChild);
  372.  
  373. });
  374.  
  375. const snCache = new Map();
  376.  
  377. if (TRANSLATE_DEBUG) {
  378. console.log(11)
  379. }
  380.  
  381. /** @type {(str: string?) => string} */
  382. function _snippetText(str) {
  383. // str can be underfinded
  384. if (!str || typeof str !== 'string') return '';
  385. let res = snCache.get(str);
  386. if (res === undefined) {
  387. let b = false;
  388. res = str.replace(/[\s\u3000\u200b]*[\u200b\xA0\x20\n]+[\s\u3000\u200b]*/g, (m) => {
  389. b = true;
  390. return m.includes('\n') ? '\n' : m.replace(/\u200b/g, '').replace(/[\xA0\x20]+/g, ' ');
  391. });
  392. res = res.replace(/^[\s\u3000]+|[\u3000\s]+$/g, () => {
  393. b = true;
  394. return '';
  395. });
  396. if (b) {
  397. snCache.set(str, res);
  398. snCache.set(res, null);
  399. } else {
  400. res = null;
  401. snCache.set(str, null);
  402. }
  403. }
  404. return res === null ? str : res;
  405. }
  406.  
  407. /** @type {(snippet: Object) => string} */
  408. function snippetText(snippet) {
  409. let runs = snippet.runs;
  410. const n = runs.length;
  411. if (n === 1) return _snippetText(runs[0].text);
  412. let res = new Array(n);
  413. let ci = 0;
  414. for (const s of runs) {
  415. res[ci++] = _snippetText(s.text);
  416. }
  417. return res.join('\n');
  418. }
  419.  
  420. const _DEBUG_szz = (t) => t.map(x => {
  421. const tsr = x.transcriptSegmentRenderer;
  422. return ({
  423. t: tsr.snippet.runs.map(x => x.text).join('//'),
  424. a: tsr.startMs,
  425. b: tsr.endMs
  426. });
  427. });
  428.  
  429. const fixRuns = (runs) => {
  430. if (runs.length === 1 && runs[0]?.text?.includes('\n')) {
  431. // https://www.youtube.com/watch?v=dmHJJ5k_G-A
  432. const text = runs[0].text;
  433. const nlc = text.includes('\r\n') ? '\r\n' : text.includes('\n\r') ? '\n\r' : text.includes('\r') ? '\r' : '\n';
  434. const s = text.split(nlc);
  435. let bi = 0;
  436. runs.length = s.length;
  437. for (const text of s) {
  438. runs[bi++] = { ...runs[0], text };
  439. }
  440. }
  441. for (const s of runs) {
  442. s.text = _snippetText(s.text);
  443. }
  444. }
  445.  
  446. function translate(initialSegments) {
  447. // 2023.07.13 - fix initialSegments with transcriptSectionHeaderRenderer
  448.  
  449. if (!initialSegments) return initialSegments;
  450.  
  451. if (TRANSLATE_DEBUG) {
  452. console.log(12);
  453. Promise.resolve(JSON.stringify(initialSegments)).then((r) => {
  454. let obj = JSON.parse(r);
  455. console.log(7558, 1, obj)
  456. return obj;
  457. }).then(p => {
  458. let obj = _DEBUG_szz(p)
  459. console.log(7558, 2, obj)
  460. })
  461. }
  462.  
  463.  
  464. //let mapRej = new WeakSet();
  465.  
  466. const n1 = initialSegments.length;
  467. if (!n1) return fRes;
  468. let n2 = 0;
  469.  
  470.  
  471. const fRes = new Array(n1);
  472. // -----------------------------------------------------------------------------------------
  473.  
  474. const s8 = Symbol();
  475.  
  476. {
  477.  
  478. /** @type {Map<String, Object>} */
  479. let cacheTexts = new Map(); // avoid duplicate with javascript object properties
  480.  
  481. // /-* * @type {Map<String, number>} *-/
  482. // let mh1 = new Map(); // avoid duplicate with javascript object properties
  483. // 1: ok
  484. // 2: abandoned effect text
  485.  
  486. for (const initialSegment of initialSegments) {
  487. const transcript = (initialSegment || 0).transcriptSegmentRenderer;
  488. if (!transcript) {
  489. // https://www.youtube.com/watch?v=dmHJJ5k_G-A - transcriptSectionHeaderRenderer
  490. fRes[n2++] = initialSegment;
  491. continue;
  492. }
  493. const runs = transcript.snippet.runs
  494. if (!runs || runs.length === 0) {
  495. initialSegment[s8] = true;
  496. continue;
  497. }
  498. let startMs = (+transcript.startMs || 0); //integer
  499. let endMs = (+transcript.endMs || 0); //integer
  500. if (startMs === endMs) {
  501. // effect text
  502. // https://www.youtube.com/watch?v=Ud73fm4Uoq0
  503. //mapRej.add(initialSegment)
  504. continue;
  505. }
  506. if (endMs - startMs < 30) {
  507. continue;
  508. }
  509. const text = snippetText(transcript.snippet);
  510. const hEntry = cacheTexts.get(text);
  511. const mh1e = hEntry === undefined ? 0 : hEntry === null ? 2 : 1;
  512. if (mh1e === 2) continue;
  513. const entry = {
  514. startMs,
  515. endMs,
  516. initialSegment,
  517. text
  518. };
  519. if (mh1e === 0) {
  520. if (/^[,.\x60\x27\x22\u200b\xA0\x20;-]*$/.test(text)) {
  521. initialSegment[s8] = true;
  522. cacheTexts.set(text, null);
  523. //effect only
  524. // https://www.youtube.com/watch?v=zLak0dxBKpM
  525. //mapRej.add(initialSegment)
  526. continue;
  527. }
  528. } else if (hEntry) {
  529.  
  530. const timeDiff = entry.startMs - hEntry.endMs;
  531. let shouldMerge = false;
  532.  
  533. if (timeDiff >= 0) {
  534.  
  535. if (timeDiff < 25) {
  536. shouldMerge = true;
  537. } else if (timeDiff < 450 && entry.endMs - entry.startMs < 900) {
  538. shouldMerge = true;
  539. } else if (timeDiff < 150 && entry.endMs - entry.startMs > 800) {
  540. shouldMerge = true;
  541. }
  542.  
  543. if (shouldMerge && hEntry.endMs <= endMs && startMs <= endMs) {
  544. // abandon the current entry.
  545. // absorbed by previous entry
  546. hEntry.endMs = entry.endMs;
  547. hEntry.initialSegment.transcriptSegmentRenderer.endMs = entry.initialSegment.transcriptSegmentRenderer.endMs; // update fRes & initialSegments as well using object reference
  548. //mapRej.add(entry.initialSegment);
  549. continue;
  550. }
  551.  
  552. } else if (entry.startMs < hEntry.startMs && hEntry.startMs < entry.endMs) {
  553.  
  554. // abandon the current entry.
  555. // absorbed by previous entry
  556. if (entry.endMs > hEntry.endMs) {
  557. hEntry.endMs = entry.endMs;
  558. hEntry.initialSegment.transcriptSegmentRenderer.endMs = entry.initialSegment.transcriptSegmentRenderer.endMs; // update fRes & initialSegments as well using object reference
  559. }
  560. //mapRej.add(entry.initialSegment);
  561. continue;
  562.  
  563. }
  564.  
  565. }
  566. //if not abandoned
  567. cacheTexts.set(text, entry); //replace the previous valid entry object if any
  568. // for (const s of runs) {
  569. // s.text = _snippetText(s.text);
  570. // }
  571. fixRuns(runs);
  572. fRes[n2++] = initialSegment;
  573. }
  574.  
  575. // cacheTexts.clear(); // let GC do it.
  576. cacheTexts = null;
  577. // mh1.clear(); // let GC do it.
  578. // mh1 = null;
  579.  
  580. }
  581.  
  582. const si_length = fRes.length = n2;
  583. const sj_length = n1;
  584.  
  585. if (si_length !== sj_length) { // for equal length, no fix is required & ignore spacing fix
  586. // collect the abandon text to become second subtitle
  587.  
  588. let sj_start = 0;
  589. let invalid_sj = -1;
  590. for (let si = 0; si < si_length; si++) {
  591. const segment = fRes[si];
  592. let transcript = segment.transcriptSegmentRenderer;
  593. if (!transcript) continue; // e.g. transcriptSectionHeaderRenderer
  594. const runs = transcript.snippet.runs;
  595. // fixRuns(runs);
  596. if (runs.length > 1 || runs[0].text.includes('\n')) continue; // skip multi lines
  597. const main_startMs = (+transcript.startMs || 0);
  598. const main_endMs = (+transcript.endMs || 0);
  599. transcript = null;
  600.  
  601. /** @type {Map<string, number>} */
  602. let tMap = new Map(); // avoid duplicate with javascript object properties
  603.  
  604. // assume that it is asc-ordered array of key startMs;
  605. for (let sj = sj_start; sj < sj_length; sj++) {
  606. const initialSegment = initialSegments[sj];
  607.  
  608. if (!initialSegment || initialSegment[s8]) continue; // should invalid_sj be set ?
  609.  
  610. const tSegment = initialSegment.transcriptSegmentRenderer;
  611.  
  612. if (!tSegment) {
  613. // https://www.youtube.com/watch?v=dmHJJ5k_G-A - transcriptSectionHeaderRenderer
  614. invalid_sj = sj; // should invalid_sj be set ?
  615. continue;
  616. }
  617.  
  618. const startMs = (+tSegment.startMs || 0)
  619. const isStartValid = startMs >= main_startMs;
  620. if (!isStartValid) {
  621. invalid_sj = sj;
  622. continue;
  623. }
  624. // isStartValid must be true
  625. if (startMs > main_endMs) {
  626. sj_start = invalid_sj + 1;
  627. break;
  628. }
  629.  
  630. const endMs = (+tSegment.endMs || 0)
  631. if (endMs <= main_endMs) {
  632. const mt = snippetText(tSegment.snippet);
  633. const prev = tMap.get(mt);
  634. if (endMs >= startMs) {
  635. tMap.set(mt, (prev || 0) + 1 + (endMs - startMs));
  636. }
  637. }
  638.  
  639. }
  640.  
  641. if (tMap.size <= 1) continue; // no second line
  642. let rg = [...tMap.entries()]; // N x 2 2D-array [string,number][]
  643. tMap = null;
  644.  
  645. // https://www.youtube.com/watch?v=Ud73fm4Uoq0
  646.  
  647. rg.sort((a, b) => b[1] - a[1]); //descending order of number
  648.  
  649. let targetZ = rg[1][1];
  650. if (targetZ > 4) {
  651. let az = 0;
  652. let fail = false;
  653. for (let idx = 2, rgl = rg.length; idx < rgl; idx++) {
  654. az += rg[idx][1];
  655. if (az >= targetZ) {
  656. fail = true;
  657. break;
  658. }
  659. }
  660. if (!fail) {
  661. const rgA = rg[0][0];
  662. const rgB = rg[1][0];
  663. const isDiff = rgB.replace(/\s/g, '') !== rgA.replace(/\s/g, '');
  664. if (isDiff && rgA === _snippetText(runs[0].text)) {
  665. runs.push({ text: rgB });
  666. }
  667. }
  668. }
  669. rg = null;
  670. }
  671.  
  672. TRANSLATE_DEBUG && Promise.resolve(fRes).then((r) => {
  673.  
  674. let obj = r;
  675. console.log(7559, 1, obj)
  676. return obj;
  677. }).then(p => {
  678. let obj = _DEBUG_szz(p)
  679. console.log(7559, 2, obj)
  680.  
  681. });
  682. }
  683.  
  684. // -----------------------------------------------------------------------------------------
  685. snCache.clear();
  686. return fRes;
  687.  
  688. }
  689.  
  690.  
  691. return translate
  692.  
  693. }
  694.  
  695.  
  696. let translateFn = null;
  697.  
  698. FIX_TRANSCRIPT_SEGMENTS && !isChatRoomURL && (() => {
  699.  
  700. const wmx = new WeakMap();
  701.  
  702. function fixSegments(ytObj) {
  703. let a, b;
  704. let seg = ((a = ytObj.data) == null ? void 0 : a[b = 'searchResultSegments']) || ((a = ytObj.data) == null ? void 0 : a[b = 'initialSegments']) || [];
  705. if (!seg || !a || !b || typeof (seg || 0) !== 'object' || !Number.isFinite(seg.length * 1)) return;
  706. translateFn = translateFn || getTranslate();
  707. let cSeg;
  708. cSeg = wmx.get(seg);
  709. if (!cSeg) {
  710. let vSeg = null;
  711. try {
  712. vSeg = translateFn(seg);
  713. } catch (e) {
  714. }
  715. if (seg && typeof seg === 'object' && seg.length >= 1 && vSeg && typeof vSeg === 'object' && vSeg.length >= 1) {
  716. // console.log('translated', vSeg);
  717. cSeg = vSeg;
  718. wmx.set(seg, cSeg);
  719. wmx.set(cSeg, cSeg);
  720. }
  721. }
  722. if (cSeg && cSeg !== seg) {
  723. a[b] = cSeg;
  724. }
  725. }
  726.  
  727. const dfn = Symbol();
  728. const Object_ = Object;
  729. Object_[dfn] = Object_.defineProperties;
  730. let activation = true;
  731. Object_.defineProperties = function (obj, pds) {
  732. let segments, get_;
  733. if (activation && pds && (segments = pds.segments) && (get_ = segments.get)) {
  734. activation = false;
  735. segments.get = function () {
  736. fixSegments(this);
  737. return get_.call(this);
  738. };
  739. }
  740. return Object_[dfn](obj, pds);
  741. };
  742.  
  743. })();
  744.  
  745.  
  746. let pf31 = new PromiseExternal();
  747.  
  748. // native RAF
  749. let __requestAnimationFrame__ = typeof webkitRequestAnimationFrame === 'function' ? window.webkitRequestAnimationFrame.bind(window) : window.requestAnimationFrame.bind(window);
  750.  
  751. // 1st wrapped RAF
  752. const baseRAF = (callback) => {
  753. return p59 ? __requestAnimationFrame__(callback) : __requestAnimationFrame__((hRes) => {
  754. pf31.then(() => {
  755. callback(hRes);
  756. });
  757. });
  758. };
  759.  
  760. // 2nd wrapped RAF
  761. window.requestAnimationFrame = baseRAF;
  762.  
  763. const insp = o => o ? (o.polymerController || o.inst || o || 0) : (o || 0);
  764. const indr = o => insp(o).$ || o.$ || 0;
  765.  
  766. const prototypeInherit = (d, b) => {
  767. const m = Object.getOwnPropertyDescriptors(b);
  768. for (const p in m) {
  769. if (!Object.getOwnPropertyDescriptor(d, p)) {
  770. Object.defineProperty(d, p, m[p]);
  771. }
  772. }
  773. };
  774.  
  775.  
  776. const firstObjectKey = (obj) => {
  777. for (const key in obj) {
  778. if (obj.hasOwnProperty(key) && typeof obj[key] === 'object') return key;
  779. }
  780. return null;
  781. };
  782.  
  783. function searchNestedObject(obj, predicate, maxDepth = 64) {
  784. // normal case: depth until 36
  785. const result = [];
  786. const visited = new WeakSet();
  787.  
  788. function search(obj, depth) {
  789. visited.add(obj);
  790. for (const [key, value] of Object.entries(obj)) {
  791. // Recursively search nested objects and arrays
  792. if (value !== null && typeof value === 'object') {
  793. // Prevent infinite loops by checking if the object is already visited or depth exceeded
  794. if (depth + 1 <= maxDepth && !visited.has(value)) {
  795. search(value, depth + 1);
  796. }
  797. } else if (predicate(value)) {
  798. result.push([obj, key]);
  799. }
  800. }
  801. }
  802.  
  803. typeof (obj || 0) === 'object' && search(obj, 0);
  804. return result;
  805. }
  806.  
  807. /** @type {(o: Object | null) => WeakRef | null} */
  808. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null);
  809.  
  810. /** @type {(wr: Object | null) => Object | null} */
  811. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  812.  
  813. const isIterable = (obj) => (Symbol.iterator in Object_(obj));
  814.  
  815. if (typeof Document.prototype.requestStorageAccessFor === 'function') {
  816. if (DENY_requestStorageAccess) {
  817. // https://developer.mozilla.org/en-US/docs/Web/API/Document/requestStorageAccessFor
  818. Document.prototype.requestStorageAccessFor = undefined;
  819. console.log('[yt-js-engine-tamer]', 'requestStorageAccessFor is removed.');
  820. } else if (DISABLE_IFRAME_requestStorageAccess && window !== top) {
  821. Document.prototype.requestStorageAccessFor = function () {
  822. return new Promise((resolve, reject) => {
  823. reject();
  824. });
  825. };
  826. }
  827. }
  828.  
  829. const traceStack = (stack) => {
  830. let result = new Set();
  831. let p = new Set();
  832. let u = ''
  833. for (const s of stack.split('\n')) {
  834. if (s.split(':').length < 3) continue;
  835. let m = /(([\w-_\.]+):\d+:\d+)[^:\r\n]*/.exec(s);
  836. if (!m) continue;
  837. p.add(m[2]);
  838. if (p.size >= 3) break;
  839. if(!u) u = m[2];
  840. else if(p.size === 2 && u && u=== m[2]) break;
  841. result.add(s);
  842. }
  843. return [...result].join('\n');
  844. }
  845.  
  846. if (FIX_bind_self_this && !Function.prototype.bind488 && !Function.prototype.bind588) {
  847. // window.m3bb = new Set();
  848.  
  849. // const smb = Symbol();
  850. const vmb = 'dtz02' // Symbol(); // return kThis for thisArg
  851. const vmc = 'dtz04' // Symbol(); // whether it is proxied fn
  852. const vmd = 'dtz08' // Symbol(); // self fn proxy (fn--fn)
  853.  
  854. // const fnProxySelf = function (...args) {
  855. // if (args[0] === smb) return this;
  856. // const cnt = kRef(this.ref);
  857. // if (cnt) {
  858. // if (typeof cnt[this.prop] !== 'function') console.error(`this.${this.prop} is not a function. [${cnt.is || 'nil'}]`)
  859. // return cnt[this.prop](...args); // might throw error
  860. // }
  861. // }
  862. // fnProxySelf.bind588 = fnProxySelf.bind;
  863. // const pFnHandler = {
  864. // get(target, prop){
  865. // if(prop === 'bind588') return 2;
  866. // const fnThis = target(smb);
  867. // if (fnThis && fnThis.prop && fnThis.ref) {
  868. // const cnt = kRef(fnThis.ref || null) || null;
  869. // if (cnt) {
  870. // const h = cnt[fnThis.prop];
  871. // const v = h[prop];
  872. // if (typeof v === 'function'){
  873. // if(typeof h === 'function'){
  874. // if (prop === 'call' || prop === 'bind' || prop === 'bind588' || prop === 'bind488' || prop === 'apply') {
  875. // if(h.bind588 === 1){
  876. // const g = function(...args){
  877. // console.log(1288, this)
  878. // return h.call(this, ...args);
  879. // };
  880. // console.log(399, g)
  881. // return g[prop];
  882. // // console.log(12778)
  883. // // console.log(target, target.call)
  884. // // return target[prop];
  885. // }
  886. // // independent of this
  887. // return v; // function.bind, function.call, function.apply
  888. // }
  889. // }
  890. // console.warn('cnt[fnThis.prop][prop] is function; might rely on this', { prop, fProp: fnThis.prop, is: cnt.is, h: h });
  891.  
  892. // // return new Proxy(fnProxySelf.bind588({ prop: prop, ref: new WeakRef(cnt[fnThis.prop]) }), pFnHandler);
  893. // }
  894. // return v;
  895. // }
  896. // }
  897. // },
  898. // set(target, prop, value) {
  899. // const fnThis = target(smb);
  900. // if (fnThis && fnThis.prop && fnThis.ref) {
  901. // const cnt = kRef(fnThis.ref || null) || null;
  902. // if (cnt) {
  903. // const h = cnt[fnThis.prop];
  904. // if (h) {
  905. // h[prop] = value;
  906. // } else {
  907. // console.log('h is nout found', { prop, fProp: fnThis.prop, is: cnt.is, h: h });
  908. // }
  909. // }
  910. // }
  911. // return true;
  912. // }
  913. // };
  914.  
  915. const thisConversionFn = (thisArg) => {
  916. if (!thisArg) return null;
  917. const kThis = thisArg[vmb];
  918. if (kThis) {
  919. const ref = kThis.ref;
  920. return (ref ? kRef(ref) : null) || null;
  921. }
  922. return thisArg;
  923. }
  924.  
  925. const pFnHandler2 = {
  926. get(target, prop) {
  927. if (prop === vmc) return target;
  928. return Reflect.get(target, prop);
  929. },
  930. apply(target, thisArg, argumentsList) {
  931. thisArg = thisConversionFn(thisArg);
  932. if (thisArg) return Reflect.apply(target, thisArg, argumentsList);
  933. }
  934. }
  935.  
  936.  
  937. const proxySelfHandler = {
  938. get(target, prop) {
  939. if(prop === vmb) return target;
  940. const ref = target.ref;
  941. const cnt = kRef(ref);
  942. if (!cnt) return;
  943. if (typeof cnt[prop] === 'function' && !cnt[prop][vmc] && !cnt[prop][vmb]) {
  944. if (!cnt[prop][vmd]) cnt[prop][vmd] = new Proxy(cnt[prop], pFnHandler2);
  945. return cnt[prop][vmd];
  946. }
  947. return cnt[prop];
  948. },
  949. set(target, prop, value) {
  950. const cnt = kRef(target.ref);
  951. if (!cnt) return true;
  952. if(value && (value[vmc] || value[vmb])){
  953. cnt[prop] = value[vmc] || thisConversionFn(value);
  954. return true;
  955. }
  956. cnt[prop] = value;
  957. return true;
  958. }
  959. };
  960.  
  961. const weakWrap = (thisArg) => {
  962. thisArg = thisConversionFn(thisArg);
  963. if (!thisArg) {
  964. console.error('thisArg is not found');
  965. return null;
  966. }
  967. return new Proxy({ ref: mWeakRef(thisArg) }, proxySelfHandler);
  968. }
  969.  
  970. if (!window.getComputedStyle533 && typeof window.getComputedStyle === 'function') {
  971. window.getComputedStyle533 = window.getComputedStyle;
  972. window.getComputedStyle = function (a, ...args) {
  973. a = thisConversionFn(a);
  974. if (a) {
  975. return getComputedStyle533(a, ...args);
  976. }
  977. return null;
  978. }
  979. }
  980.  
  981. Function._count_bind_00 = 0;
  982. // Function._count_bind_01 = 0;
  983.  
  984. // let matchNativeCode = (Object+"");
  985. // let matchNativeCode1 = matchNativeCode.includes("[native code]");
  986. // let matchNativeLen = matchNativeCode.length - Object.name.length;
  987.  
  988. // const matchConstructor = (thisArg) => {
  989. // const f = `${(thisArg || 0).constructor}`;
  990. // if (f.length > 45) return true;
  991. // if (matchNativeCode1 && f.length - thisArg.constructor.name.length === matchNativeLen) {
  992. // if (f.includes('[native code]')){
  993. // return false;
  994. // }
  995. // return true;
  996. // }
  997. // return false;
  998. // }
  999.  
  1000. // const acceptThis = (thisArg)=>{
  1001. // // if(!thisArg || typeof thisArg !=='object') return false;
  1002. // // // if((((thisArg||0).constructor||0).name || 'XXXXXXXX').length < 3) return true;
  1003. // // if(typeof thisArg.path === 'string') return true;
  1004. // // if(typeof thisArg.fn === 'function') return true;
  1005. // // if(typeof thisArg.id === 'string') return true;
  1006. // // if(typeof thisArg.isLoaded === 'boolean') return true;
  1007. // return false;
  1008. // }
  1009.  
  1010. const patchFn = (fn) => {
  1011.  
  1012. let s = `${fn}`;
  1013. if (s.length < 11 || s.includes('\n')) return false;
  1014. if(s.includes('bind(this')) return true;
  1015. if(s.includes('=this') && /[,\s][a-zA-Z_][a-zA-Z0-9_]*=this[;,]/.test(s) ) return true;
  1016. // var a=this;
  1017. // f.bind(this)
  1018.  
  1019.  
  1020. return false;
  1021. }
  1022.  
  1023. Function.prototype.bind488 = Function.prototype.bind;
  1024. Function.prototype.bind = function(thisArg, ...args){
  1025.  
  1026. if (thisConversionFn(thisArg) !== thisArg) {
  1027. return this.bind488(thisArg, ...args);
  1028. }
  1029. if( thisArg && patchFn(this) ){
  1030.  
  1031. // console.log(599,`${this}`)
  1032.  
  1033. try {
  1034. // let b1 = thisArg && typeof thisArg === 'object' && typeof thisArg.isAttached === 'boolean' && !thisArg.dtz06; // ready cnt
  1035. // let b2 = !b1 && thisArg && (thisArg instanceof Node) && typeof thisArg.nodeName === 'string' && !thisArg.dtz06; // dom
  1036. // let b3 = !b1 && !b2 && thisArg && typeof thisArg === 'object' && typeof thisArg.is === 'string' && !thisArg.dtz06; // init stage ?
  1037. // // let b4 = !b1 && !b2 && !b3 && thisArg && typeof thisArg === 'object' && !thisArg.dtz06 && matchConstructor(thisArg);
  1038. // // let b5 = !b1 && !b2 && !b3 && !b4 && thisArg && typeof thisArg === 'object' && !thisArg.dtz06 && acceptThis(thisArg);
  1039. // // let b5 = !b1 && !b2 && !b3 && thisArg && typeof thisArg === 'object' && !thisArg.dtz06 && !(thisArg instanceof Window);
  1040. // // let b4 = false;
  1041. // let b4 = !b1 && !b2 && !b3 && thisArg && !thisArg.dtz06;
  1042.  
  1043. // // b3 = false;
  1044. // // b4 = false;
  1045. // // b5 = false;
  1046.  
  1047. // if (b1 || b2 || b3 ||b4 ) {
  1048. const f = this;
  1049. const ps = thisArg.__proxySelf0__ || (thisArg.__proxySelf0__ = weakWrap(thisArg));
  1050. if (ps && ps[vmb]) {
  1051. Function._count_bind_00++;
  1052. return f.bind488(ps, ...args)
  1053. }
  1054. // }
  1055. } catch (e) {
  1056. console.warn(e)
  1057. }
  1058. }
  1059. return this.bind488(thisArg, ...args);
  1060. }
  1061. Function.prototype.bind588 = 1;
  1062. }
  1063.  
  1064.  
  1065. if (FIX_weakMap_weakRef && !window.WeakMapOriginal && typeof window.WeakMap === 'function' && typeof WeakRef === 'function') {
  1066. const WeakMapOriginal = window.WeakMapOriginal = window.WeakMap;
  1067. const wm6 = new WeakMapOriginal();
  1068.  
  1069. const skipW = new WeakSet();
  1070.  
  1071.  
  1072. window.WeakMap = class WeakMap extends WeakMapOriginal {
  1073. constructor(iterable = undefined) {
  1074. super();
  1075. if (iterable && iterable[Symbol.iterator]) {
  1076. for (const entry of iterable) {
  1077. entry && this.set(entry[0], entry[1]);
  1078. }
  1079. }
  1080. }
  1081. delete(a) {
  1082. if (!this.has(a)) return false;
  1083. super.delete(a);
  1084. return true;
  1085. }
  1086. get(a) {
  1087. const p = super.get(a);
  1088. if (p && typeof p === 'object' && p.deref && !skipW.has(p)) {
  1089. let v = kRef(p);
  1090. if (!v) {
  1091. super.delete(a);
  1092. }
  1093. return v || undefined;
  1094. }
  1095. return p;
  1096. }
  1097. has(a) {
  1098. if (!super.has(a)) return false;
  1099. const p = super.get(a);
  1100. if (p && typeof p === 'object' && p.deref && !skipW.has(p)) {
  1101. if (!kRef(p)) {
  1102. super.delete(a);
  1103. return false;
  1104. }
  1105. }
  1106. return true;
  1107. }
  1108. set(a, b) {
  1109. let wq = b;
  1110. if (b && (typeof b === 'function' || typeof b === 'object')) {
  1111. if (b.deref) {
  1112. skipW.add(b);
  1113. wq = b;
  1114. } else {
  1115. wq = wm6.get(b);
  1116. if (!wq) {
  1117. wq = mWeakRef(b);
  1118. wm6.set(b, wq);
  1119. }
  1120. }
  1121. }
  1122. super.set(a, wq);
  1123. return this;
  1124. }
  1125. }
  1126. Object.defineProperty(window.WeakMap, Symbol.toStringTag, {
  1127. configurable: true,
  1128. enumerable: false,
  1129. value: "WeakMap",
  1130. writable: false
  1131. });
  1132. }
  1133.  
  1134. const isWatchPageURL = (url) => {
  1135. url = url || location;
  1136. return location.pathname === '/watch' || location.pathname.startsWith('/live/')
  1137. };
  1138.  
  1139. const isCustomElementsProvided = typeof customElements !== "undefined" && typeof (customElements || 0).whenDefined === "function";
  1140.  
  1141. const promiseForCustomYtElementsReady = isCustomElementsProvided ? Promise.resolve(0) : new Promise((callback) => {
  1142. const EVENT_KEY_ON_REGISTRY_READY = "ytI-ce-registry-created";
  1143. if (typeof customElements === 'undefined') {
  1144. if (!('__CE_registry' in document)) {
  1145. // https://github.com/webcomponents/polyfills/
  1146. Object.defineProperty(document, '__CE_registry', {
  1147. get() {
  1148. // return undefined
  1149. },
  1150. set(nv) {
  1151. if (typeof nv == 'object') {
  1152. delete this.__CE_registry;
  1153. this.__CE_registry = nv;
  1154. this.dispatchEvent(new CustomEvent(EVENT_KEY_ON_REGISTRY_READY));
  1155. }
  1156. return true;
  1157. },
  1158. enumerable: false,
  1159. configurable: true
  1160. })
  1161. }
  1162. let eventHandler = (evt) => {
  1163. document.removeEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  1164. const f = callback;
  1165. callback = null;
  1166. eventHandler = null;
  1167. f();
  1168. };
  1169. document.addEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  1170. } else {
  1171. callback();
  1172. }
  1173. });
  1174.  
  1175. const whenCEDefined = isCustomElementsProvided
  1176. ? (nodeName) => customElements.whenDefined(nodeName)
  1177. : (nodeName) => promiseForCustomYtElementsReady.then(() => customElements.whenDefined(nodeName));
  1178.  
  1179. FIX_perfNow && performance.timeOrigin > 9 && (() => {
  1180. if (performance.now23 || performance.now16 || typeof Performance.prototype.now !== 'function') return;
  1181. const f = performance.now23 = Performance.prototype.now;
  1182.  
  1183. let k = 0; // 0 <= k < 9998m
  1184. let u = 0;
  1185. let s = ((performance.timeOrigin % 7) + 1) / 7 - 1e-2 / 7; // s > 0.14
  1186.  
  1187. // By definition, performance.now() is mono increasing.
  1188. // Fixing in YouTube.com is required to ensure performance.now() is strictly increasing.
  1189. performance.now = performance.now16 = function () {
  1190. /**
  1191. * Bug 1842437 - When attempting to go back on youtube.com, the content remains the same
  1192. *
  1193. * If consecutive session history entries had history.state.entryTime set to same value,
  1194. * back button doesn't work as expected. The entryTime value is coming from performance.now()
  1195. * and modifying its return value slightly to make sure two close consecutive calls don't
  1196. * get the same result helped with resolving the issue.
  1197. */
  1198. // see https://bugzilla.mozilla.org/show_bug.cgi?id=1756970
  1199. // see https://bugzilla.mozilla.org/show_bug.cgi?id=1842437
  1200.  
  1201. const v = typeof (this || 0).now23 === 'function' ? this.now23() + s : f.call(performance) + s; // v > 0.14
  1202. if (u + 0.0015 < (u = v)) k = 0; // note: hRes should be accurate to 5 µs in isolated contexts
  1203. else if (k < 0.001428) k += 1e-6 / 7; // M = 10000 * m; m * 9996 = 0.001428
  1204. else { // more than 9998 consecutive calls
  1205. /**
  1206. *
  1207. * max no. of consecutive calls
  1208. *
  1209. * Sample Size: 4800
  1210. * Sample Avg = 1565.375
  1211. * Sample Median = 1469.5
  1212. * Sample Max = 5660 << 7500 << 9999
  1213. *
  1214. *
  1215. * */
  1216. k = 0;
  1217. s += 1 / 7;
  1218. }
  1219. return v + k; // 0 < v - M < v - M + k < v
  1220. }
  1221.  
  1222. let loggerMsg = '';
  1223. if (`${performance.now()}` === `${performance.now()}`) {
  1224. const msg1 = 'performance.now is modified but performance.now() is not strictly increasing.';
  1225. const msg2 = 'performance.now cannot be modified and performance.now() is not strictly increasing.';
  1226. loggerMsg = performance.now !== performance.now16 ? msg1 : msg2; // might not able to set in Firefox
  1227. }
  1228. loggerMsg && console.warn(loggerMsg);
  1229. })();
  1230.  
  1231. FIX_removeChild && (() => {
  1232. if (typeof Node.prototype.removeChild === 'function' && typeof Node.prototype.removeChild062 !== 'function') {
  1233. Node.prototype.removeChild062 = Node.prototype.removeChild;
  1234. Node.prototype.removeChild = function (child) {
  1235. if (typeof this.__shady_native_removeChild !== 'function' || ((child instanceof Node) && child.parentNode === this)) {
  1236. this.removeChild062(child);
  1237. } else if ((child instanceof Element) && child.is === 'tp-yt-paper-tooltip') {
  1238. // tooltip bug
  1239. } else {
  1240. console.warn('[yt-js-engine-tamer] Node is not removed from parent', { parent: this, child: child })
  1241. }
  1242. return child;
  1243. }
  1244. }
  1245. })();
  1246.  
  1247.  
  1248. FIX_VIDEO_PLAYER_MOUSEHOVER_EVENTS && !isChatRoomURL && (() => {
  1249.  
  1250. const [setIntervalX0, clearIntervalX0] = [setInterval, clearInterval];
  1251.  
  1252. // let cid = 0;
  1253.  
  1254. let mousemoveFn = null;
  1255. let mousemoveDT = 0;
  1256. let mousemoveCount = 0;
  1257. // let qv = false;
  1258. const cif = () => {
  1259. if (!mousemoveFn) return;
  1260. const ct = Date.now();
  1261. if (mousemoveDT + 1200 > ct) { // avoid setTimeout delay too long without execution
  1262. mousemoveFn && mousemoveFn();
  1263. }
  1264. mousemoveFn = null;
  1265. };
  1266. let mousemoveCId = 0;
  1267. let mouseoverFn = null;
  1268. HTMLElement.prototype.addEventListener4882 = HTMLElement.prototype.addEventListener;
  1269. HTMLElement.prototype.addEventListener = function (a, b, c) {
  1270. if (this.id == 'movie_player' && `${a}`.startsWith('mouse') && c === undefined) {
  1271. const bt = `${b}`;
  1272. if (bt.length >= 61 && bt.length <= 71 && bt.startsWith('function(){try{return ') && bt.includes('.apply(this,arguments)}catch(')) {
  1273. b[`__$$${a}$$1926__`] = true;
  1274. this[`__$$${a}$$1937__`] = (this[`__$$${a}$$1937__`] || 0) + 1;
  1275. if (this[`__$$${a}$$1937__`] > 1073741823) this[`__$$${a}$$1937__`] -= 536870911;
  1276. // console.log(3928, a, this[`__$$${a}$$1937__`])
  1277. if (!this[`__$$${a}$$1938__`]) {
  1278. this[`__$$${a}$$1938__`] = b;
  1279. if (a === 'mousemove') {
  1280. this.addEventListener4882('mouseenter', (evt) => {
  1281. if (mousemoveCId) return;
  1282. mousemoveCId = setIntervalX0(cif, 380);
  1283. });
  1284. this.addEventListener4882('mouseleave', (evt) => {
  1285. clearIntervalX0(mousemoveCId);
  1286. mousemoveCId = 0;
  1287. });
  1288. }
  1289. this.addEventListener4882(a, (evt) => {
  1290. const evt_ = evt;
  1291. if (!this[`__$$${a}$$1937__`]) return;
  1292. if (!this[`__$$${a}$$1938__`]) return;
  1293. if (a === 'mousemove') {
  1294. mouseoverFn && mouseoverFn();
  1295. if (mousemoveDT + 350 > (mousemoveDT = Date.now())) {
  1296. (++mousemoveCount > 1e9) && (mousemoveCount = 9);
  1297. } else {
  1298. mousemoveCount = 0;
  1299. }
  1300. const f = mousemoveFn = () => {
  1301. if (f !== mousemoveFn) return;
  1302. mousemoveFn = null;
  1303. this[`__$$${a}$$1938__`](evt_);
  1304. };
  1305. if (mousemoveCount <= 1) mousemoveFn();
  1306. } else {
  1307. if (a === 'mouseout' || a === 'mouseleave') {
  1308. mousemoveFn = null;
  1309. mousemoveDT = 0;
  1310. mousemoveCount = 0;
  1311. this[`__$$${a}$$1938__`](evt_);
  1312. mouseoverFn && mouseoverFn();
  1313. } else { // mouseover, mouseenter
  1314. mousemoveFn = null;
  1315. mousemoveDT = 0;
  1316. mousemoveCount = 0;
  1317. mouseoverFn && mouseoverFn(); // just in case
  1318. const f = mouseoverFn = () => {
  1319. if (f !== mouseoverFn) return;
  1320. mouseoverFn = null;
  1321. this[`__$$${a}$$1938__`](evt_);
  1322. }
  1323. nextBrowserTick(mouseoverFn);
  1324. }
  1325. }
  1326. }, c);
  1327.  
  1328.  
  1329. return;
  1330. } else {
  1331.  
  1332. return;
  1333. }
  1334. }
  1335.  
  1336. }
  1337. return this.addEventListener4882(a, b, c)
  1338. }
  1339.  
  1340.  
  1341.  
  1342.  
  1343. HTMLElement.prototype.removeEventListener4882 = HTMLElement.prototype.removeEventListener;
  1344. HTMLElement.prototype.removeEventListener = function (a, b, c) {
  1345. if (this.id == 'movie_player' && `${a}`.startsWith('mouse') && c === undefined) {
  1346.  
  1347. if (b[`__$$${a}$$1926__`]) {
  1348. b[`__$$${a}$$1926__`] = false;
  1349.  
  1350. if (this[`__$$${a}$$1937__`]) this[`__$$${a}$$1937__`] -= 1;
  1351.  
  1352. // console.log(3929, a, this[`__$$${a}$$1937__`], b[`__$$${a}$$1926__`])
  1353.  
  1354. return;
  1355.  
  1356. }
  1357.  
  1358. }
  1359. return this.removeEventListener4882(a, b, c)
  1360. }
  1361.  
  1362.  
  1363. })();
  1364.  
  1365.  
  1366. FIX_DOM_IF_REPEAT && (() => {
  1367. // https://www.youtube.com/s/desktop/26a583e4/jsbin/live_chat_polymer.vflset/live_chat_polymer.js
  1368. // DOM-IF is still a core class of Polymer, so no polymerController is available.
  1369. // Be careful of the mixture of polymer functions and native Element functions
  1370. // Be careful of the coding design is different with the modern Yt elements
  1371.  
  1372.  
  1373. /*
  1374.  
  1375.  
  1376. function Ks(a, b, c) {
  1377. if (kj && !BOa(a))
  1378. throw Error("strictTemplatePolicy: template owner not trusted");
  1379. c = c || {};
  1380. if (a.__templatizeOwner)
  1381. throw Error("A <template> can only be templatized once");
  1382. a.__templatizeOwner = b;
  1383. var d = (b ? b.constructor : Js)._parseTemplate(a)
  1384. , e = d.templatizeInstanceClass;
  1385. e || (e = COa(a, d, c),
  1386. d.templatizeInstanceClass = e);
  1387. var g = BOa(a);
  1388. EOa(a, d, c, g);
  1389. c = function() {
  1390. return e.apply(this, arguments) || this
  1391. }
  1392. ;
  1393. h(c, e);
  1394. c.prototype._methodHost = g;
  1395. c.prototype.__dataHost = a;
  1396. c.prototype.__templatizeOwner = b;
  1397. c.prototype.__hostProps = d.hostProps;
  1398. return c
  1399. }
  1400.  
  1401. */
  1402.  
  1403. // Polymer.enqueueDebouncer
  1404.  
  1405. const s81 = Symbol();
  1406. const s83 = Symbol();
  1407. const s84 = Symbol();
  1408. const s85 = Symbol();
  1409. const s85b = Symbol();
  1410. const s85c = Symbol();
  1411.  
  1412. let renderDebounceTs = null;
  1413.  
  1414. let renderDebouncePromise = null;
  1415. let qp;
  1416.  
  1417. let cme = 0;
  1418.  
  1419. const shadyFlushMO = new MutationObserver(() => {
  1420.  
  1421. if (!renderDebounceTs) return;
  1422.  
  1423. if (renderDebounceTs.size > 0) {
  1424. console.warn('renderDebounceTs.size is incorect', renderDebounceTs.size);
  1425. try {
  1426. Polymer.flush();
  1427. return;
  1428. } catch (e) { }
  1429. }
  1430.  
  1431. renderDebouncePromise && Promise.resolve().then(() => {
  1432.  
  1433. if (renderDebouncePromise) {
  1434. renderDebouncePromise && renderDebouncePromise.resolve();
  1435. renderDebouncePromise = null;
  1436. DEBUG_DBR847 && console.log('__DBR847__ renderDebouncePromise.resolve by MutationObserver')
  1437. }
  1438.  
  1439. });
  1440.  
  1441. // Polymer.flush
  1442.  
  1443. window.ShadyDOM && ShadyDOM.flush();
  1444. window.ShadyCSS && window.ShadyCSS.ScopingShim && window.ShadyCSS.ScopingShim.flush();
  1445.  
  1446.  
  1447. });
  1448.  
  1449. if (FIX_DOM_IFREPEAT_RenderDebouncerChange) {
  1450.  
  1451. const observablePromise = (proc, timeoutPromise) => {
  1452. let promise = null;
  1453. return {
  1454. obtain() {
  1455. if (!promise) {
  1456. promise = new Promise(resolve => {
  1457. let mo = null;
  1458. const f = () => {
  1459. let t = proc();
  1460. if (t) {
  1461. mo.disconnect();
  1462. mo.takeRecords();
  1463. mo = null;
  1464. resolve(t);
  1465. }
  1466. }
  1467. mo = new MutationObserver(f);
  1468. mo.observe(document, { subtree: true, childList: true })
  1469. f();
  1470. timeoutPromise && timeoutPromise.then(() => {
  1471. resolve(null)
  1472. });
  1473. });
  1474. }
  1475. return promise
  1476. }
  1477. }
  1478. }
  1479.  
  1480.  
  1481. let p = 0;
  1482. qp = observablePromise(() => {
  1483. if (!(p & 1)) {
  1484.  
  1485. if (window.ShadyDOM && ShadyDOM.flush) {
  1486. p |= 1;
  1487. if (!ShadyDOM.flush847) {
  1488.  
  1489. ShadyDOM.flush847 = ShadyDOM.flush;
  1490. ShadyDOM.flush = function () {
  1491.  
  1492. DEBUG_xx847 && console.log('xx847 ShadyDOM.flush')
  1493. renderDebouncePromise && Promise.resolve().then(() => {
  1494. if (renderDebouncePromise) {
  1495.  
  1496. renderDebouncePromise && renderDebouncePromise.resolve();
  1497. renderDebouncePromise = null;
  1498.  
  1499. DEBUG_DBR847 && console.log('__DBR847__ renderDebouncePromise.resolve by ShadyDOM.flush')
  1500.  
  1501. }
  1502.  
  1503. });
  1504. let r = this.flush847(...arguments);
  1505. if (r) {
  1506. document.documentElement.setAttribute('nw3a24np', (cme = (cme % 511 + 1)));
  1507. }
  1508. return r
  1509. }
  1510.  
  1511. }
  1512. }
  1513. }
  1514.  
  1515. if (!(p & 2)) {
  1516.  
  1517. if (window.ShadyCSS && window.ShadyCSS.ScopingShim && window.ShadyCSS.ScopingShim.flush) {
  1518. p |= 2;
  1519. const ScopingShim = window.ShadyCSS && window.ShadyCSS.ScopingShim;
  1520. if (!ScopingShim.flush848) {
  1521.  
  1522. ScopingShim.flush848 = ScopingShim.flush;
  1523. ScopingShim.flush = function () {
  1524.  
  1525. DEBUG_xx847 && console.log('xx847 ScopingShim.flush')
  1526.  
  1527. renderDebouncePromise && Promise.resolve().then(() => {
  1528.  
  1529. if (renderDebouncePromise) {
  1530.  
  1531. renderDebouncePromise && renderDebouncePromise.resolve();
  1532. renderDebouncePromise = null;
  1533.  
  1534. DEBUG_DBR847 && console.log('__DBR847__ renderDebouncePromise.resolve by ScopingShim.flush')
  1535.  
  1536.  
  1537.  
  1538. }
  1539.  
  1540. });
  1541. return this.flush848(...arguments);
  1542. }
  1543.  
  1544. }
  1545. }
  1546. }
  1547. if (p === 3) {
  1548. p |= 8;
  1549.  
  1550. let r = (window.ShadyDOM && ShadyDOM.flush && ShadyDOM.flush847
  1551. && window.ShadyCSS && window.ShadyCSS.ScopingShim &&
  1552. window.ShadyCSS.ScopingShim.flush && window.ShadyCSS.ScopingShim.flush848);
  1553.  
  1554. if (r) {
  1555. let w = Set.prototype.add;
  1556. let u = null;
  1557. Set.prototype.add = function () {
  1558. u = this;
  1559. throw new Error();
  1560. }
  1561. try {
  1562. Polymer.enqueueDebouncer()
  1563. } catch (e) { }
  1564. Set.prototype.add = w;
  1565. if (u !== null) {
  1566. renderDebounceTs = u;
  1567. if (DEBUG_renderDebounceTs) {
  1568. renderDebounceTs.add58438 = renderDebounceTs.add;
  1569. renderDebounceTs.add = function () {
  1570. console.log('renderDebounceTs.add')
  1571. console.log(traceStack((new Error()).stack))
  1572. // debugger;
  1573. return this.add58438(...arguments)
  1574. }
  1575.  
  1576. renderDebounceTs.delete58438 = renderDebounceTs.delete;
  1577. renderDebounceTs.delete = function () {
  1578. console.log('renderDebounceTs.delete')
  1579. const stack = `${(new Error()).stack}`
  1580. let isCallbackRemoval = false;
  1581. if (stack) {
  1582. let t = stack.replace(/[^\r\n]+renderDebounceTs\.delete[^\r\n]+/, '').replace('://','');
  1583. const s = t.split(':');
  1584. if (s.length === 3 && +s[1] > 0 && +s[2] > 0) {
  1585. isCallbackRemoval = true;
  1586. }
  1587. }
  1588. if (isCallbackRemoval) {
  1589. return this.delete58438(...arguments)
  1590. }
  1591. console.log(traceStack((new Error()).stack))
  1592. // debugger;
  1593. return this.delete58438(...arguments)
  1594. }
  1595. }
  1596. DEBUG_renderDebounceTs && (window.renderDebounceTs = renderDebounceTs);
  1597. console.log('renderDebounceTs', renderDebounceTs, `debug=${DEBUG_renderDebounceTs}`);
  1598. }
  1599. }
  1600.  
  1601. return true;
  1602. }
  1603. })
  1604.  
  1605. // if(window.ShadyDOM && ShadyDOM.flush){
  1606. // console.log('FIX_DOM_IF_RenderDebouncerChange X1')
  1607.  
  1608. // }
  1609. // if(window.ShadyCSS && window.ShadyCSS.ScopingShim && window.ShadyCSS.ScopingShim.flush){
  1610.  
  1611. // console.log('FIX_DOM_IF_RenderDebouncerChange X2')
  1612. // }
  1613.  
  1614. // console.log('FIX_DOM_IF_RenderDebouncerChange X3')
  1615.  
  1616. }
  1617.  
  1618. Object.defineProperty(Object.prototype, '_lastIf', {
  1619. get() {
  1620. return this[s81];
  1621. },
  1622. set(nv) {
  1623. if (nv === false && this.nodeName === "DOM-IF" && this.__renderDebouncer === null && this[s81] === undefined) {
  1624. // DOM-IF initialization
  1625. nv = null; // avoid (this.if == this._lastIf) primitive type conversion (object vs false)
  1626.  
  1627. this.__xiWB8__ = 2;
  1628.  
  1629. const cProto = this.__proto__;
  1630. if (cProto && !cProto.__xiWB7__) {
  1631. cProto.__xiWB7__ = 1;
  1632.  
  1633. // dom-if __template
  1634. // dom-repeat template
  1635. if (FIX_DOM_IF_TEMPLATE && !cProto.__template && !cProto.__template847) {
  1636. cProto.__template847 = true;
  1637. try {
  1638. // note: this is not "_template" in Polymer ( see POLYMER_COMPONENT_DEFINITION )
  1639. Object.defineProperty(cProto, '__template', {
  1640. get() {
  1641. const v = this[s84];
  1642. return (typeof (v || 0) === 'object' && v.deref) ? kRef(v) : v;
  1643. },
  1644. set(nv) {
  1645. if (typeof (nv || 0) === 'object' && !nv.deref) nv = mWeakRef(nv);
  1646. this[s84] = nv;
  1647. return true;
  1648. }
  1649. });
  1650. } catch (e) {
  1651. console.warn(e);
  1652. }
  1653.  
  1654. console.log('FIX_DOM_IF - __template')
  1655. }
  1656.  
  1657. // dom-if __ensureTemplate
  1658. // dom-repeat __ensureTemplatized
  1659. if (FIX_DOM_IF_TEMPLATE && !cProto.__ensureTemplate847 && typeof cProto.__ensureTemplate === 'function' && cProto.__ensureTemplate.length === 0 && this instanceof HTMLElement && `${cProto.__ensureTemplate}`.length > 20) {
  1660. // note that "_templateInfo" diffs the different version of DOM-IF
  1661.  
  1662. cProto.__ensureTemplate847 = cProto.__ensureTemplate;
  1663. cProto.__ensureTemplate = function () {
  1664. if (!(this instanceof HTMLElement) || arguments.length > 0) return this.__ensureTemplate847(...arguments);
  1665. if (!this.__template) {
  1666. let b;
  1667. if (this._templateInfo) {
  1668. b = this;
  1669. } else {
  1670. if (!this.__templateCollection011__) this.__templateCollection011__ = this.getElementsByTagName('template');
  1671. b = this.__templateCollection011__[0];
  1672. if (!b) {
  1673. let a = mWeakRef(this);
  1674. let c = new MutationObserver(function () {
  1675. if (!this.__templateCollection011__[0]) throw Error("dom-if requires a <template> child"); // to be reviewed
  1676. if (c && a) {
  1677. c.disconnect();
  1678. a = kRef(a);
  1679. a && a.__render();
  1680. a && (a.__templateCollection011__ = null);
  1681. }
  1682. c = null;
  1683. a = null;
  1684. });
  1685. c && c.observe(this, {
  1686. childList: !0
  1687. });
  1688. return !1
  1689. } else {
  1690. this.__templateCollection011__ = null;
  1691. }
  1692. }
  1693. this.__template = b
  1694. }
  1695. return !0
  1696. }
  1697.  
  1698. console.log('FIX_DOM_IF - __ensureTemplate')
  1699.  
  1700. }
  1701.  
  1702.  
  1703. // if(!cProto.__createAndInsertInstance847 && typeof cProto.__createAndInsertInstance === 'function' && cProto.__createAndInsertInstance.length === 1 && `${cProto.__createAndInsertInstance}`.length >20){
  1704.  
  1705. // cProto.__createAndInsertInstance847 = cProto.__createAndInsertInstance;
  1706.  
  1707. // cProto.__createAndInsertInstance = function (a) {
  1708. // Promise.resolve().then(()=>{
  1709. // console.log('__createAndInsertInstance')
  1710. // window.lm5 = window.lm5 || [];
  1711. // window.lm5.push([mWeakRef(this), mWeakRef(this.__instance)])
  1712. // });
  1713. // return this.__createAndInsertInstance847(a);
  1714. // }
  1715.  
  1716. // }
  1717.  
  1718.  
  1719. // if(!cProto._bindTemplate847 && typeof cProto._bindTemplate === 'function' && cProto._bindTemplate.length === 2){
  1720.  
  1721. // cProto._bindTemplate847 = cProto._bindTemplate;
  1722.  
  1723. // cProto._bindTemplate = function (a, b) {
  1724. // return this._bindTemplate847(kRef(a), b); // might throw Error as a -> null inside _bindTemplate847
  1725. // }
  1726.  
  1727. // }
  1728. // if(!cProto._stampTemplate847 && typeof cProto._stampTemplate === 'function' && cProto._stampTemplate.length === 2){
  1729.  
  1730. // cProto._stampTemplate847 = cProto._stampTemplate;
  1731.  
  1732. // cProto._stampTemplate = function (a, b) {
  1733. // return this._stampTemplate847(kRef(a), b); // might throw Error as a -> null inside _stampTemplate847
  1734. // }
  1735.  
  1736. // }
  1737. console.log('FIX_DOM_IF OK', Object.keys(cProto))
  1738. }
  1739.  
  1740.  
  1741. // need to fix __observeEffects
  1742. // this.__observeEffects.if[0].info.method === this.__debounceRender
  1743. const f = () => {
  1744.  
  1745. const __observeEffects = this.__observeEffects;
  1746.  
  1747. if (__observeEffects && __observeEffects.if && isIterable(__observeEffects.if)) {
  1748. for (const effect of __observeEffects.if) {
  1749. const info = effect.info;
  1750. if (info && typeof info.method === 'function') {
  1751.  
  1752. if (info.method === this.__debounceRender847 || info.method === this.__debounceRender) {
  1753. info.method = FIX_DOM_IFREPEAT_RenderDebouncerChange_SET_TO_PROPNAME ? '__debounceRender' : this.__debounceRender;
  1754. }
  1755.  
  1756. }
  1757. }
  1758. }
  1759.  
  1760.  
  1761. if (__observeEffects && __observeEffects.restamp && isIterable(__observeEffects.restamp)) {
  1762. for (const effect of __observeEffects.restamp) {
  1763. const info = effect.info;
  1764. if (info && typeof info.method === 'function') {
  1765.  
  1766. if (info.method === this.__debounceRender847 || info.method === this.__debounceRender) {
  1767. info.method = FIX_DOM_IFREPEAT_RenderDebouncerChange_SET_TO_PROPNAME ? '__debounceRender' : this.__debounceRender;
  1768. }
  1769.  
  1770. }
  1771. }
  1772. }
  1773.  
  1774. // console.log(5881, this.__observeEffects)
  1775. }
  1776. if (FIX_DOM_IFREPEAT_RenderDebouncerChange) {
  1777. f();
  1778. Promise.resolve().then(f);
  1779. // afterward, don't care adding fn directly (the fn is already modified)
  1780. }
  1781.  
  1782. }
  1783. this[s81] = nv;
  1784. return true;
  1785. }
  1786. });
  1787.  
  1788.  
  1789. Object.defineProperty(Object.prototype, '__renderDebouncer', {
  1790. get() {
  1791. return this[s85];
  1792. },
  1793. set(nv) {
  1794. if (nv === null && this[s85] === undefined) {
  1795. // DOM-IF / DOM-REPEAT initialization
  1796.  
  1797.  
  1798. const cProto = this.__proto__;
  1799. if (qp) {
  1800. qp.obtain();
  1801. qp = null;
  1802. shadyFlushMO.observe(document.documentElement, { attributes: ['nw3a24np'] });
  1803. }
  1804. if (FIX_DOM_IFREPEAT_RenderDebouncerChange && !cProto.__debounceRender847 && typeof cProto.__debounceRender === 'function' && !(`${cProto.__debounceRender}`.includes("{}"))) {
  1805.  
  1806. cProto.__debounceRender847 = cProto.__debounceRender;
  1807.  
  1808. if (cProto.__debounceRender.length === 2) {
  1809.  
  1810. cProto.__debounceRender = function (a, b) {
  1811.  
  1812. if (!renderDebounceTs) return this.__debounceRender847(a, b);
  1813.  
  1814. b = b === void 0 ? 0 : b;
  1815.  
  1816. /*
  1817. b = b === void 0 ? 0 : b;
  1818. this.__renderDebouncer = us(this.__renderDebouncer, b > 0 ? Rr.after(b) : Tr, a.bind(this));
  1819. vs(this.__renderDebouncer)
  1820. */
  1821.  
  1822. this.__DBR848__ = this.__DBR848__ || `${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}`;
  1823.  
  1824. if (!renderDebouncePromise) {
  1825. renderDebouncePromise = new PromiseExternal();
  1826. document.documentElement.setAttribute('nw3a24np', (cme = (cme % 511 + 1)));
  1827. }
  1828.  
  1829. renderDebouncePromise.then(async () => {
  1830. if (b > 0) await delayPn(b);
  1831.  
  1832. const f = this.__dsIRYqw1__;
  1833. if (f === cme) return;
  1834. this.__dsIRYqw1__ = cme;
  1835. a.call(this);
  1836. DEBUG_DBR847 && console.log(`__DBR847__ done 01 (delay=${b})`, this.__DBR848__)
  1837.  
  1838. });
  1839.  
  1840. DEBUG_DBR847 && console.log(`__DBR847__ add 01 (delay=${b})`, this.__DBR848__)
  1841. }
  1842.  
  1843. } else if (cProto.__debounceRender.length === 0) {
  1844.  
  1845.  
  1846. cProto.__debounceRender = function () {
  1847.  
  1848. if (!renderDebounceTs) return this.__debounceRender847();
  1849.  
  1850. this.__DBR848__ = this.__DBR848__ || `${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}`;
  1851. /*
  1852. var a = this;
  1853. this.__renderDebouncer = us(this.__renderDebouncer, Tr, function() {
  1854. return a.__render()
  1855. });
  1856. vs(this.__renderDebouncer)
  1857. */
  1858.  
  1859. if (!renderDebouncePromise) {
  1860. renderDebouncePromise = new PromiseExternal();
  1861. document.documentElement.setAttribute('nw3a24np', (cme = (cme % 511 + 1)));
  1862. }
  1863. renderDebouncePromise.then(() => {
  1864. const f = this.__dsIRYqw1__;
  1865. if (f === cme) return;
  1866. this.__dsIRYqw1__ = cme;
  1867. this.__render()
  1868. DEBUG_DBR847 && console.log('__DBR847__ done 02', this.__DBR848__)
  1869. });
  1870. DEBUG_DBR847 && console.log('__DBR847__ add 02', this.__DBR848__)
  1871.  
  1872.  
  1873. }
  1874. }
  1875. }
  1876.  
  1877.  
  1878.  
  1879. // if(FIX_DOM_IFREPEAT_RenderDebouncerChange && !cProto.render847 && typeof cProto.render === 'function' && cProto.render.length === 0 && !(`${cProto.render}`.includes("{}"))){
  1880. // cProto.render847 = cProto.render;
  1881. // cProto.render = function(){
  1882.  
  1883. // this.__DBR848__ = this.__DBR848__ || `${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}`;
  1884. // try{
  1885. // this.render847();
  1886. // }catch(e){}
  1887. // // if(this.__DBR847__){
  1888. // // this.__DBR847__.resolve();
  1889. // // DEBUG_DBR847 && console.log('__DBR847__ resolve', this.__DBR848__)
  1890. // // }
  1891.  
  1892. // // renderDebouncePromise && renderDebouncePromise.resolve()
  1893. // // renderDebouncePromise = null;
  1894. // // DEBUG_DBR847 && console.log('__DBR847__ renderDebouncePromise.resolve by render', this.__DBR848__)
  1895.  
  1896. // }
  1897. // console.log('FIX_DOM_IF - render', `${cProto.render847}`, cProto.render847)
  1898. // }
  1899.  
  1900. }
  1901. this[s85] = nv;
  1902. return true;
  1903. }
  1904. });
  1905.  
  1906. // PS-DOM-REPEAT
  1907.  
  1908. Object.defineProperty(Object.prototype, 'JSC$10034_renderDebouncer', {
  1909. get() {
  1910. return this[s85b];
  1911. },
  1912. set(nv) {
  1913.  
  1914. this[s85b] = nv;
  1915. return true;
  1916. }
  1917. })
  1918.  
  1919. Object.defineProperty(Object.prototype, 'JSC$10027_renderDebouncer', {
  1920. get() {
  1921. return this[s85c];
  1922. },
  1923. set(nv) {
  1924.  
  1925. this[s85c] = nv;
  1926. return true;
  1927. }
  1928. })
  1929.  
  1930.  
  1931. })();
  1932.  
  1933. // WEAKREF_ShadyDOM
  1934.  
  1935. MODIFY_ShadyDOM_OBJ && ((WeakRef) => {
  1936.  
  1937. const setupPlainShadyDOM = (b) => {
  1938. (OMIT_ShadyDOM_settings & 1) && (b.inUse === true) && (b.inUse = false);
  1939. (OMIT_ShadyDOM_settings & 2) && (b.handlesDynamicScoping === true) && (b.handlesDynamicScoping = false);
  1940. (OMIT_ShadyDOM_settings & 4) && (b.force === true) && (b.force = false);
  1941. b.patchOnDemand = true;
  1942. b.preferPerformance = true;
  1943. b.noPatch = true;
  1944. }
  1945.  
  1946. const isPlainObject = (b, m) => {
  1947. if (!b || typeof b !== 'object') return false;
  1948. const e = Object.getOwnPropertyDescriptors(b);
  1949. if (e.length <= m) return false;
  1950. let pr = 0;
  1951. for (const k in e) {
  1952. const d = e[k];
  1953. if (!d || d.get || d.set || !d.enumerable || !d.configurable) return false;
  1954. if (!('value' in d) || typeof d.value === 'function') return false;
  1955. pr++;
  1956. }
  1957. return pr > m;
  1958. }
  1959.  
  1960. let b;
  1961.  
  1962. let lz = 0;
  1963.  
  1964. const sdp = Object.getOwnPropertyDescriptor(window, 'ShadyDOM');
  1965. if (sdp && sdp.configurable && sdp.value && sdp.enumerable && sdp.writable) {
  1966.  
  1967. // Brave - ShadyDOM exists before userscripting
  1968. b = sdp.value;
  1969.  
  1970. if (b && typeof b === 'object' && isPlainObject(b, 0)) {
  1971. OMIT_ShadyDOM_EXPERIMENTAL && setupPlainShadyDOM(b);
  1972. lz = 1;
  1973. }
  1974.  
  1975. }
  1976.  
  1977.  
  1978. if (sdp && sdp.configurable && sdp.value && sdp.enumerable && sdp.writable && !sdp.get && !sdp.set) {
  1979. } else if (!sdp) {
  1980. } else {
  1981. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM is not applied [ PropertyDescriptor issue ]', sdp);
  1982. return;
  1983. }
  1984.  
  1985. const shadyDOMNodeWRM = new WeakMap();
  1986.  
  1987. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM << 01 >>', b);
  1988.  
  1989. const weakWrapperNodeHandlerFn = () => ({
  1990. get() {
  1991. let w = shadyDOMNodeWRM.get(this);
  1992. if (typeof w === 'object') w = kRef(w) || (shadyDOMNodeWRM.delete(this), undefined);
  1993. return w;
  1994. },
  1995. set(nv) {
  1996. shadyDOMNodeWRM.set(this, mWeakRef(nv));
  1997. return true;
  1998. },
  1999. enumerable: true,
  2000. configurable: true
  2001. });
  2002.  
  2003. function weakWrapper(_ShadyDOM) {
  2004. const ShadyDOM = _ShadyDOM;
  2005. if (WEAKREF_ShadyDOM && lz < 3 && typeof WeakRef === 'function' && typeof ShadyDOM.Wrapper === 'function' && ShadyDOM.Wrapper.length === 1 && typeof (ShadyDOM.Wrapper.prototype || 0) === 'object') {
  2006. let nullElement = { node: null };
  2007. Object.setPrototypeOf(nullElement, Element.prototype);
  2008. let p = new ShadyDOM.Wrapper(nullElement);
  2009. let d = Object.getOwnPropertyDescriptor(p, 'node');
  2010. if (d.configurable && d.enumerable && !d.get && !d.set && d.writable && d.value === nullElement && !Object.getOwnPropertyDescriptor(ShadyDOM.Wrapper.prototype, 'node')) {
  2011. Object.defineProperty(ShadyDOM.Wrapper.prototype, 'node', weakWrapperNodeHandlerFn());
  2012. console.log('[yt-js-engine-tamer] FIX::ShadyDOM << WEAKREF_ShadyDOM >>')
  2013. }
  2014. }
  2015. }
  2016.  
  2017. let previousWrapStore = null;
  2018.  
  2019. const standardWrap = function (a) {
  2020. if (a instanceof ShadowRoot || a instanceof ShadyDOM.Wrapper) return a;
  2021. if (previousWrapStore) {
  2022. const s = kRef(previousWrapStore.get(a)); // kRef for play safe only
  2023. if (s) {
  2024. previousWrapStore.delete(a);
  2025. shadyDOMNodeWRM.set(a, mWeakRef(s));
  2026. }
  2027. }
  2028. let u = kRef(shadyDOMNodeWRM.get(a));
  2029. if (!u) {
  2030. u = new ShadyDOM.Wrapper(a);
  2031. shadyDOMNodeWRM.set(a, mWeakRef(u));
  2032. }
  2033. return u;
  2034. }
  2035.  
  2036.  
  2037. function setupWrapFunc(_ShadyDOM) {
  2038. const ShadyDOM = _ShadyDOM;
  2039.  
  2040.  
  2041. const wmPD = Object.getOwnPropertyDescriptor(WeakMap.prototype, 'get');
  2042. if (!(wmPD && wmPD.writable && !wmPD.enumerable && wmPD.configurable && wmPD.value && !wmPD.get && !wmPD.set)) {
  2043. return;
  2044. }
  2045. let mm = new Set();
  2046. const pget = wmPD.value;
  2047. WeakMap.prototype.get = function (a) {
  2048. mm.add(this);
  2049. return a;
  2050. }
  2051. try {
  2052. let nullElement = { node: null };
  2053. Object.setPrototypeOf(nullElement, Element.prototype);
  2054. ShadyDOM.wrapIfNeeded(nullElement)
  2055. ShadyDOM.wrap(nullElement)
  2056. } catch (e) { }
  2057. WeakMap.prototype.get = pget;
  2058. if (mm.size !== 1) {
  2059. mm.clear();
  2060. return;
  2061. }
  2062. const p = mm.values().next().value;
  2063. if (!(p instanceof WeakMap)) return;
  2064. // p.clear();
  2065. // p.get = function (a) { return a }
  2066. // p.set = function (a, b) { return this }
  2067. // console.log(188, window.n2n = mm, window.n2p = p)
  2068.  
  2069. // console.log(34929,p.size)
  2070. previousWrapStore = p;
  2071.  
  2072. if (typeof ShadyDOM.wrap === 'function' && ShadyDOM.wrap.length === 1) {
  2073. ShadyDOM.wrap = function (a) { 0 && console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - wrap'); return standardWrap(a) }
  2074. }
  2075. if (typeof ShadyDOM.wrapIfNeeded === 'function' && ShadyDOM.wrapIfNeeded.length === 1) {
  2076. ShadyDOM.wrapIfNeeded = function (a) { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - wrapIfNeeded'); return standardWrap(a) }
  2077. }
  2078.  
  2079. }
  2080.  
  2081. function setupLZ3(nv) {
  2082.  
  2083. const ShadyDOM = nv;
  2084.  
  2085. const ShadyDOMSettings = ShadyDOM.settings;
  2086. if (!(ShadyDOMSettings.inUse === true && ShadyDOM.inUse === true && (ShadyDOMSettings.handlesDynamicScoping || ShadyDOM.handlesDynamicScoping) === true)) {
  2087. console.log(3719, '[yt-js-engine-tamer] OMIT_ShadyDOM is not applied [02]', window.ShadyDOM);
  2088. return false;
  2089. }
  2090.  
  2091. weakWrapper(ShadyDOM);
  2092.  
  2093. if (OMIT_ShadyDOM_EXPERIMENTAL && lz < 3) {
  2094.  
  2095. setupPlainShadyDOM(ShadyDOMSettings);
  2096. setupPlainShadyDOM(ShadyDOM);
  2097.  
  2098. ShadyDOM.isShadyRoot = function () { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - isShadyRoot'); return false; }
  2099.  
  2100. setupWrapFunc(ShadyDOM);
  2101. ShadyDOM.patchElementProto = function () { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - patchElementProto') }
  2102. ShadyDOM.patch = function () { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - patch') }
  2103.  
  2104. // To be confirmed
  2105. if (OMIT_ShadyDOM_EXPERIMENTAL & 2) {
  2106. ShadyDOM.composedPath = function (e) {
  2107. const t = (e || 0).target || null;
  2108. if (!(t instanceof HTMLElement)) {
  2109. console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM&2) composedPath', t)
  2110. }
  2111. return t instanceof HTMLElement ? [t] : [];
  2112. };
  2113. }
  2114.  
  2115. }
  2116.  
  2117. }
  2118.  
  2119.  
  2120. function setupLZ6(nv) {
  2121.  
  2122. const ShadyDOM = nv;
  2123.  
  2124. const ShadyDOMSettings = ShadyDOM.settings;
  2125.  
  2126. if (!(ShadyDOMSettings.inUse === true && ShadyDOM.inUse === true && (ShadyDOMSettings.handlesDynamicScoping || ShadyDOM.handlesDynamicScoping) === true)) {
  2127. console.log(3719, '[yt-js-engine-tamer] OMIT_ShadyDOM is not applied [02]', window.ShadyDOM);
  2128. return false;
  2129. }
  2130.  
  2131. weakWrapper(ShadyDOM);
  2132.  
  2133. if (OMIT_ShadyDOM_EXPERIMENTAL && lz < 3) {
  2134.  
  2135. setupPlainShadyDOM(ShadyDOMSettings);
  2136. setupPlainShadyDOM(ShadyDOM);
  2137.  
  2138. setupWrapFunc(ShadyDOM);
  2139.  
  2140. }
  2141.  
  2142. }
  2143.  
  2144. if (b && typeof b.Wrapper === 'function' && typeof b.settings === 'object' && typeof b.wrap === 'function') {
  2145.  
  2146. const nv = b;
  2147.  
  2148. if (setupLZ6(nv) === false) return;
  2149.  
  2150. lz = 6;
  2151.  
  2152. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM << 02b >>', nv)
  2153.  
  2154. return;
  2155. }
  2156.  
  2157. delete window.ShadyDOM;
  2158.  
  2159. Object.defineProperty(window, 'ShadyDOM', {
  2160. get() {
  2161. return b;
  2162. },
  2163. set(nv) {
  2164. let ret = 0;
  2165. try {
  2166. do {
  2167. if (!nv || !nv.settings) {
  2168. if (lz < 1 && nv && typeof nv === 'object' && isPlainObject(nv, 0)) {
  2169. OMIT_ShadyDOM_EXPERIMENTAL && setupPlainShadyDOM(nv);
  2170. lz = 1;
  2171. break;
  2172. } else {
  2173. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM is not applied [nv:null]', nv);
  2174. break;
  2175. }
  2176. }
  2177.  
  2178. const sdp = Object.getOwnPropertyDescriptor(this || {}, 'ShadyDOM');
  2179. if (!(sdp && sdp.configurable && sdp.get && sdp.set)) {
  2180. console.log(3719, '[yt-js-engine-tamer] OMIT_ShadyDOM is not applied [ incorrect PropertyDescriptor ]', nv);
  2181. break;
  2182. }
  2183.  
  2184. if (setupLZ3(nv) === false) break;
  2185.  
  2186. lz = 3;
  2187.  
  2188. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM << 02a >>', nv)
  2189.  
  2190. ret = 1;
  2191.  
  2192. } while (0);
  2193. } catch (e) {
  2194. console.log('[yt-js-engine-tamer] FIX::ShadyDOM << ERROR >>', e)
  2195. }
  2196.  
  2197. if (!ret) b = nv;
  2198. else {
  2199. delete this.ShadyDOM;
  2200. this.ShadyDOM = nv;
  2201. }
  2202. return true;
  2203. },
  2204. enumerable: false,
  2205. configurable: true
  2206. });
  2207.  
  2208. })(typeof WeakRef !== 'undefined' ? WeakRef : function () { });
  2209.  
  2210. if (ENABLE_ASYNC_DISPATCHEVENT && nextBrowserTick) {
  2211. const filter = new Set([
  2212. 'yt-action',
  2213. // 'iframe-src-replaced',
  2214. 'shown-items-changed',
  2215. 'can-show-more-changed', 'collapsed-changed',
  2216.  
  2217. 'yt-navigate', 'yt-navigate-start', 'yt-navigate-cache',
  2218. 'yt-player-updated', 'yt-page-data-fetched', 'yt-page-type-changed', 'yt-page-data-updated',
  2219. 'yt-navigate-finish',
  2220.  
  2221. // 'data-changed','yt-watch-comments-ready'
  2222. ])
  2223. EventTarget.prototype.dispatchEvent938 = EventTarget.prototype.dispatchEvent;
  2224. EventTarget.prototype.dispatchEvent = function (event) {
  2225. const type = (event || 0).type;
  2226. if (typeof type === 'string' && event.isTrusted === false && (event instanceof CustomEvent) && event.cancelable === false) {
  2227. if (!filter.has(type) && !type.endsWith('-changed')) {
  2228. if (this instanceof Node || this instanceof Window) {
  2229. nextBrowserTick(() => this.dispatchEvent938(event));
  2230. return true;
  2231. }
  2232. }
  2233. }
  2234. return this.dispatchEvent938(event);
  2235. }
  2236. }
  2237.  
  2238. // avoid REGEXP testPattern execution in Brave's scriptlet for performance boost
  2239. SCRIPTLET_REMOVE_PRUNE_propNeedles && (() => {
  2240. // const xhr = new XMLHttpRequest;
  2241. const pdOri = Object.getOwnPropertyDescriptor(Map.prototype, 'size');
  2242. if (!pdOri || pdOri.configurable !== true) return;
  2243. let propNeedles = null;
  2244. const pdNew = {
  2245. configurable: true,
  2246. enumerable: true,
  2247. get: function () {
  2248. propNeedles = this;
  2249. if (DEBUG_removePrune) debugger; // to locate Brave scriptlets
  2250. throw new Error();
  2251. }
  2252. }
  2253. Object.defineProperty(Map.prototype, 'size', pdNew);
  2254. try {
  2255. XMLHttpRequest.prototype.open.call(0);
  2256. // xhr.open.call(null)
  2257. } catch (e) { }
  2258. Object.defineProperty(Map.prototype, 'size', pdOri);
  2259. if (!propNeedles) return;
  2260. const entries = [...propNeedles.entries()];
  2261. propNeedles.clear();
  2262. console.log('[yt-js-engine-tamer] propNeedles is cleared from scriptlet', entries, propNeedles);
  2263. })();
  2264.  
  2265. if (FIX_XHR_REQUESTING) {
  2266.  
  2267. const URL = window.URL || new Function('return URL')();
  2268. const createObjectURL = URL.createObjectURL.bind(URL);
  2269.  
  2270. XMLHttpRequest = (() => {
  2271. const XMLHttpRequest_ = XMLHttpRequest;
  2272. if ('__xmMc8__' in XMLHttpRequest_.prototype) return XMLHttpRequest_;
  2273. const url0 = createObjectURL(new Blob([], { type: 'text/plain' }));
  2274. const c = class XMLHttpRequest extends XMLHttpRequest_ {
  2275. constructor(...args) {
  2276. super(...args);
  2277. }
  2278. open(method, url, ...args) {
  2279. let skip = false;
  2280. if (!url || typeof url !== 'string') skip = true;
  2281. else if (typeof url === 'string') {
  2282. let turl = url[0] === '/' ? `.youtube.com${url}` : `${url}`;
  2283. if (turl.includes('googleads') || turl.includes('doubleclick.net')) {
  2284. skip = true;
  2285. } else if (turl.includes('.youtube.com/pagead/')) {
  2286. skip = true;
  2287. } else if (turl.includes('.youtube.com/ptracking')) {
  2288. skip = true;
  2289. } else if (turl.includes('.youtube.com/youtubei/v1/log_event?')) {
  2290. skip = true;
  2291. } else if (turl.includes('.youtube.com/api/stats/')) { // /api/stats/
  2292. if (turl.includes('.youtube.com/api/stats/qoe?')) {
  2293. skip = true;
  2294. } else if (turl.includes('.youtube.com/api/stats/ads?')) {
  2295. skip = true;
  2296. } else {
  2297. // skip = true; // for user activity logging e.g. watched videos
  2298. }
  2299. } else if (turl.includes('play.google.com/log')) {
  2300. skip = true;
  2301. } else if (turl.includes('.youtube.com//?')) { // //?cpn=
  2302. skip = true;
  2303. }
  2304. }
  2305. if (!skip) {
  2306. this.__xmMc8__ = 1;
  2307. return super.open(method, url, ...args);
  2308. } else {
  2309. this.__xmMc8__ = 2;
  2310. return super.open('GET', url0);
  2311. }
  2312. }
  2313. send(...args) {
  2314. if (this.__xmMc8__ === 1) {
  2315. return super.send(...args);
  2316. } else if (this.__xmMc8__ === 2) {
  2317. return super.send();
  2318. } else {
  2319. console.log('[yt-js-engine-tamer]', 'xhr warning');
  2320. return super.send(...args);
  2321. }
  2322. }
  2323. }
  2324. c.prototype.__xmMc8__ = 0;
  2325. prototypeInherit(c.prototype, XMLHttpRequest_.prototype);
  2326. return c;
  2327. })();
  2328. }
  2329.  
  2330. // Alternative HACK -> Tabview Youtube
  2331. if (DISABLE_COOLDOWN_SCROLLING && typeof EventTarget.prototype.addEventListener52178 !== 'function' && typeof EventTarget.prototype.addEventListener === 'function') {
  2332.  
  2333. // ---- << this.overscrollConfig HACK >> -----
  2334.  
  2335. // 2024.04.19 - Playlist in Single Column Mode cannot be scrolled correctly.
  2336.  
  2337. /*
  2338.  
  2339. ;function gZb(a, b) {
  2340. b = void 0 === b ? !0 : b;
  2341. a.addEventListener("wheel", hZb);
  2342. a.overscrollConfig = {
  2343. cooldown: b
  2344. }
  2345. }
  2346. function iZb(a) {
  2347. a.overscrollConfig = void 0;
  2348. a.removeEventListener("wheel", hZb)
  2349. }
  2350. function hZb(a) {
  2351. var b = a.deltaY
  2352. , c = a.target
  2353. , d = null;
  2354. if (window.Polymer && window.Polymer.Element) {
  2355. if (c = a.path || a.composedPath && a.composedPath()) {
  2356. c = g(c);
  2357. for (var e = c.next(); !e.done && (e = e.value,
  2358. !jZb(e, b)); e = c.next())
  2359. if (e.overscrollConfig) {
  2360. d = e;
  2361. break
  2362. }
  2363. }
  2364. } else
  2365. for (; c && !jZb(c, b); ) {
  2366. if (c.overscrollConfig) {
  2367. d = c;
  2368. break
  2369. }
  2370. c = c.parentElement
  2371. }
  2372. d && (b = d.overscrollConfig,
  2373. b.cooldown ? (d = a.deltaY,
  2374. c = b.lastDeltaY || 0,
  2375. b.lastDeltaY = d,
  2376. e = b.lastStopped || 0,
  2377. c && e && 0 < c == 0 < d ? Math.abs(c) >= Math.abs(d) ? (d = e + 1200,
  2378. c = !1) : (d = e + 600,
  2379. c = !0) : (d = Date.now() + 600,
  2380. c = !0),
  2381. d > Date.now() && (a.preventDefault(),
  2382. c && (b.lastStopped = Date.now()))) : a.preventDefault())
  2383. }
  2384. */
  2385.  
  2386. let wheelHandler = function (a) {
  2387. if (window.Polymer && window.Polymer.Element) {
  2388. let c;
  2389. if (c = a.path || a.composedPath && a.composedPath()) {
  2390. for (const e of c) {
  2391. const cnt = insp(e);
  2392. if (e.overscrollConfig) e.overscrollConfig = void 0;
  2393. if (cnt.overscrollConfig) cnt.overscrollConfig = void 0;
  2394. }
  2395. }
  2396. } else {
  2397. let e = a.target;
  2398. for (; e instanceof Element; e = e.parentElement) {
  2399. const cnt = insp(e);
  2400. if (e.overscrollConfig) e.overscrollConfig = void 0;
  2401. if (cnt.overscrollConfig) cnt.overscrollConfig = void 0;
  2402. }
  2403. }
  2404. };
  2405.  
  2406. let checkWheelListenerObjs = null;
  2407.  
  2408. let getObjsFn = () => {
  2409. let euyVal = 0;
  2410. const eukElm = {};
  2411. Object.setPrototypeOf(eukElm, HTMLElement.prototype);
  2412. const euzObj = new Proxy(eukElm, {
  2413. get(target, prop) {
  2414. throw `ErrorF31.get(${prop})`
  2415. },
  2416. set(target, prop, value) {
  2417. throw `ErrorF33.set(${prop}, ${value})`
  2418. }
  2419. });
  2420. const euxElm = new Proxy(eukElm, {
  2421. get(target, prop) {
  2422. if (prop === 'scrollTop') {
  2423. euyVal = euyVal | 8;
  2424. return 0;
  2425. }
  2426. if (prop === 'overscrollConfig') {
  2427. euyVal = euyVal | 16;
  2428. return void 0;
  2429. }
  2430. if (prop === 'scrollHeight' || prop === 'clientHeight' || prop === 'offsetHeight') {
  2431. return 640;
  2432. }
  2433. if (prop === 'scrollLeft') {
  2434. euyVal = euyVal | 8;
  2435. return 0;
  2436. }
  2437. if (prop === 'scrollWidth' || prop === 'clientWidth' || prop === 'offsetWidth') {
  2438. return 800;
  2439. }
  2440. throw `ErrorF45.get(${prop})`
  2441. },
  2442. set(target, prop, value) {
  2443. throw `ErrorF47.set(${prop}, ${value})`
  2444. }
  2445. });
  2446. const eukEvt = {};
  2447. Object.setPrototypeOf(eukEvt, WheelEvent.prototype);
  2448. const euyEvt = new Proxy(eukEvt, {
  2449. get(target, prop) {
  2450. if (prop === 'deltaY' || prop === 'deltaX') {
  2451. euyVal = euyVal | 1;
  2452. return -999;
  2453. }
  2454. if (prop === 'target') {
  2455. euyVal = euyVal | 2;
  2456. return euxElm
  2457. }
  2458. if (prop === 'path' || prop === 'composedPath') {
  2459. euyVal = euyVal | 2;
  2460. return [euxElm]
  2461. }
  2462. throw `ErrorF51.get(${prop})`
  2463. },
  2464. set(target, prop, value) {
  2465. throw `ErrorF53.set(${prop}, ${value})`
  2466. }
  2467. });
  2468. const setVal = (v) => {
  2469. euyVal = v;
  2470. }
  2471. const getVal = () => {
  2472. return euyVal;
  2473. }
  2474. return { euzObj, euyEvt, setVal, getVal };
  2475. }
  2476.  
  2477. let checkWheelListener = (callback) => {
  2478.  
  2479. let callbackIdentifier = '';
  2480.  
  2481. let res = null;
  2482. try {
  2483. const { euzObj, euyEvt, getVal, setVal } = checkWheelListenerObjs || (checkWheelListenerObjs = getObjsFn());
  2484. setVal(0);
  2485. if (callback.call(euzObj, euyEvt) !== void 0) throw 'ErrorF99';
  2486. throw `RESULT${getVal()}`;
  2487. } catch (e) {
  2488. res = e;
  2489. }
  2490.  
  2491. res = `${res}` || `${null}`;
  2492. if (res.length > 20) res = `${res.substring(0, 20)}...`;
  2493.  
  2494. callbackIdentifier = res;
  2495. if (callbackIdentifier === 'RESULT27') 0;
  2496. else if (callbackIdentifier === 'RESULT0') {
  2497. // a.isSearch && !a.disableWheelScroll && B("desktop_enable_dmpanel_wheel_scroll")
  2498. } else if (callbackIdentifier.startsWith('RESULT')) {
  2499. console.log('wheel eventListener - RESULT', callbackIdentifier, callback)
  2500. }
  2501. return callbackIdentifier;
  2502.  
  2503. };
  2504.  
  2505. let callbackFound = false;
  2506. EventTarget.prototype.addEventListener52178 = EventTarget.prototype.addEventListener;
  2507. EventTarget.prototype.addEventListener = function (type, callback, option = void 0) {
  2508. // M-youtube-js-engine-tamer.52178
  2509. if (type === 'wheel' && !option && typeof callback === 'function' && callback.length === 1) {
  2510. // (( match with signature `a.addEventListener("wheel", hZb);` )) [subject to further review]
  2511. const callbackIdentifier = callback.yaujmoms || (callbackFound ? 'IGNORE' : (callback.yaujmoms = checkWheelListener(callback)));
  2512. // RESULTXX / ErrorFXX / Other...
  2513. if (callbackIdentifier === 'RESULT27') {
  2514. this.overscrollConfigDisable = true;
  2515. if (!callbackFound) {
  2516. callbackFound = true; // suppose only one function is assigned to overscrollConfig cooldown [no function binding]
  2517. getObjsFn = checkWheelListener = null;
  2518. checkWheelListenerObjs = null;
  2519. wheelHandler = null;
  2520. }
  2521. return void 0;
  2522. } else if (!callbackFound && !this.overscrollConfigDisable) {
  2523. this.overscrollConfigDisable = true;
  2524. this.addEventListener52178('wheel', wheelHandler, { passive: false });
  2525. }
  2526. }
  2527. return this.addEventListener52178(type, callback, option);
  2528. };
  2529.  
  2530. // ---- << this.overscrollConfig HACK >> -----
  2531.  
  2532. }
  2533.  
  2534. const { pageMediaWatcher, shortcutKeysFixer, keyboardController } = (() => {
  2535.  
  2536. let p_a_objWR = null;
  2537. let isSpaceKeyImmediate = false; // for ADVANCED_FIX_SHORTCUTKEYS
  2538. let ytPageReady = 0;
  2539.  
  2540. let isSpeedMastSpacebarControlEnabled = false; // youtube experimental feature // can be forced by CHANGE_SPEEDMASTER_SPACEBAR_CONTROL
  2541. let isGlobalSpaceControl = true;
  2542. let mediaPlayerElementWR = null;
  2543. let focusedElementAtSelection = null;
  2544.  
  2545. // let want_control_video = false;
  2546.  
  2547. let spaceBarControl_keyG = '';
  2548.  
  2549. let lastUserAction = 0;
  2550.  
  2551. const wmKeyControlPhase = new WeakMap();
  2552.  
  2553. let currentSelectionText = null;
  2554.  
  2555. const getCurrentSelectionText = () => {
  2556. if (currentSelectionText !== null) return currentSelectionText
  2557. return (currentSelectionText = `${getSelection()}`)
  2558. }
  2559.  
  2560. const pageMediaWatcher = () => {
  2561.  
  2562. // CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE && document.addEventListener('wheel', () => {
  2563. // want_control_video = false;
  2564. // }, { capture: true, passive: true });
  2565.  
  2566. document.addEventListener('yt-navigate', () => {
  2567. ytPageReady = 0;
  2568. });
  2569. document.addEventListener('yt-navigate-start', () => {
  2570. ytPageReady = 0;
  2571. });
  2572. document.addEventListener('yt-navigate-cache', () => {
  2573. ytPageReady = 0;
  2574. });
  2575.  
  2576. document.addEventListener('yt-navigate-finish', () => {
  2577. ytPageReady = 1;
  2578. });
  2579.  
  2580. document.addEventListener('durationchange', () => {
  2581. for (const elm of document.querySelectorAll('#movie_player video[src], #movie_player audio[src]')) {
  2582. if (elm.duration > 0.01) {
  2583. if (elm.closest('[hidden]')) continue;
  2584. mediaPlayerElementWR = mWeakRef(elm);
  2585. return;
  2586. }
  2587. }
  2588. }, { capture: true, passive: true });
  2589.  
  2590. document.addEventListener('selectionchange', (evt) => {
  2591. if (!evt || !evt.isTrusted || !(evt instanceof Event)) return;
  2592. currentSelectionText = null;
  2593. if (!(evt.target instanceof Node)) return;
  2594. focusedElementAtSelection = evt.target;
  2595. }, { capture: true, passive: true })
  2596.  
  2597. document.addEventListener('pointerdown', (evt) => {
  2598. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  2599. }, { capture: true, passive: true });
  2600.  
  2601.  
  2602. document.addEventListener('pointerup', (evt) => {
  2603. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  2604. }, { capture: true, passive: true });
  2605.  
  2606.  
  2607. document.addEventListener('keydown', (evt) => {
  2608. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  2609. }, { capture: true, passive: true });
  2610.  
  2611. document.addEventListener('keyup', (evt) => {
  2612. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  2613. }, { capture: true, passive: true });
  2614.  
  2615. };
  2616.  
  2617.  
  2618. const checkKeyB = (p_a_obj) => {
  2619.  
  2620. const boolList = new Set();
  2621. const p_a_obj_api = p_a_obj.api;
  2622.  
  2623. const nilFunc0 = function () {
  2624. return void 0
  2625. };
  2626. const mt = new Proxy({}, {
  2627. get(target, prop) {
  2628. if (prop === 'get') return nilFunc0;
  2629. return mt;
  2630. }
  2631. });
  2632. const nilFunc = function () {
  2633. return mt
  2634. };
  2635. const mw = new Proxy({}, {
  2636. get(target, prop) {
  2637. if (prop in p_a_obj_api) {
  2638. if (typeof p_a_obj_api.constructor.prototype[prop] === 'function') return nilFunc;
  2639. let q = Object.getOwnPropertyDescriptor(p_a_obj_api, prop);
  2640. if (q && q.value) {
  2641. if (!q.writable) return q.value;
  2642. if (typeof q.value === 'string') return '';
  2643. if (typeof q.value === 'number') return 0;
  2644. if (typeof q.value === 'boolean') return false;
  2645. if (q.value && typeof q.value === 'object') return {};
  2646. }
  2647. }
  2648. return undefined;
  2649. },
  2650. set(target, prop) {
  2651. throw 'mwSet';
  2652. }
  2653. });
  2654.  
  2655. const mq = new Proxy({}, {
  2656. get(target, prop) {
  2657. if (prop === 'api') return mw;
  2658. if (prop in p_a_obj) {
  2659. if (typeof p_a_obj.constructor.prototype[prop] === 'function') return nilFunc;
  2660. let q = Object.getOwnPropertyDescriptor(p_a_obj, prop);
  2661. if (q && q.value) {
  2662. if (!q.writable) return q.value;
  2663. if (typeof q.value === 'string') return '';
  2664. if (typeof q.value === 'number') return 0;
  2665. if (typeof q.value === 'boolean') return false;
  2666. if (q.value && typeof q.value === 'object') return {};
  2667. }
  2668. }
  2669. return undefined;
  2670. },
  2671. set(target, prop, val) {
  2672. if (typeof val === 'boolean') boolList.add(prop)
  2673. throw `mqSet(${prop},${val})`;
  2674. }
  2675. });
  2676.  
  2677. let res = ''
  2678. try {
  2679. res = `RESULT::${p_a_obj.handleGlobalKeyUp.call(mq, 9, false, false, false, false, "Tab", "Tab")}`;
  2680. } catch (e) {
  2681. res = `ERROR::${e}`;
  2682. }
  2683.  
  2684. if (boolList.size === 1) {
  2685. const value = boolList.values().next().value;
  2686. if (res === `ERROR::mqSet(${value},${true})`) {
  2687. p_a_obj.__uZWaD__ = value;
  2688. }
  2689. }
  2690.  
  2691. console.log('[yt-js-engine-tamer] global shortcut control', { '__uZWaD__': p_a_obj.__uZWaD__ });
  2692.  
  2693. }
  2694.  
  2695.  
  2696. let pm_p_a = null;
  2697.  
  2698. const p_a_init = function () {
  2699. const r = this.init91();
  2700. const keyBw = this.__cPzfo__ || '__NIL__';
  2701. const p_a_obj = this[keyBw];
  2702. if (!p_a_obj) return;
  2703. try {
  2704. checkKeyB(p_a_obj);
  2705. } catch (e) { }
  2706. p_a_objWR = mWeakRef(p_a_obj);
  2707. if (FIX_SHORTCUTKEYS > 0) {
  2708. if (p_a_obj && !p_a_obj.hVhtg) {
  2709. p_a_obj.hVhtg = 1;
  2710.  
  2711. p_a_obj.handleGlobalKeyUp91 = p_a_obj.handleGlobalKeyUp;
  2712. p_a_obj.handleGlobalKeyUp = p_a_xt.handleGlobalKeyUp;
  2713. p_a_obj.handleGlobalKeyDown91 = p_a_obj.handleGlobalKeyDown;
  2714. p_a_obj.handleGlobalKeyDown = p_a_xt.handleGlobalKeyDown;
  2715. p_a_obj.__handleGlobalKeyBefore__ = p_a_xt.__handleGlobalKeyBefore__;
  2716. p_a_obj.__handleGlobalKeyAfter__ = p_a_xt.__handleGlobalKeyAfter__;
  2717.  
  2718. }
  2719. // if (CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE && p_a_obj && p_a_obj.api && !p_a_obj.api.hVhtg) {
  2720. // const api = p_a_obj.api
  2721. // api.hVhtg = 1;
  2722. // api.playVideo91 = api.playVideo;
  2723. // api.playVideo = p_a_jt.playVideo;
  2724. // api.pauseVideo91 = api.pauseVideo;
  2725. // api.pauseVideo = p_a_jt.pauseVideo;
  2726. // }
  2727. }
  2728. if (pm_p_a) {
  2729. pm_p_a.resolve();
  2730. pm_p_a = null;
  2731. }
  2732. return r;
  2733. };
  2734.  
  2735. const p_a_xt = {
  2736.  
  2737. __handleGlobalKeyBefore__(a, b, c, d, e, f, h, activeElement) {
  2738.  
  2739. if (FIX_SHORTCUTKEYS === 2) {
  2740.  
  2741. // if (flagSpeedMaster !== false && !getGlobalSpacebarControlFlag()) return false;
  2742.  
  2743. if (activeElement) {
  2744.  
  2745. const controlPhaseCache = wmKeyControlPhase.get(activeElement);
  2746.  
  2747. if (controlPhaseCache === 6 && getCurrentSelectionText() !== "") void 0;
  2748. else if (controlPhaseCache === 1 || controlPhaseCache === 2 || controlPhaseCache === 5) return false;
  2749. else if ((controlPhaseCache !== 6 || focusedElementAtSelection === document.activeElement) && getCurrentSelectionText() !== "") return false;
  2750.  
  2751. }
  2752.  
  2753. const isSpaceBar = a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space';
  2754. const isDelayedSpaceBar = FIX_SHORTCUTKEYS === 2 && isSpaceBar && !isSpaceKeyImmediate && (isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag());
  2755. // console.log(582, isDelayedSpaceBar)
  2756. if (isDelayedSpaceBar) return void 0; // accept delay spacebar under isSpeedMastSpacebarControlEnabled (no rejection)
  2757.  
  2758. if (activeElement && (h === 'Space' || h === 'Enter')) {
  2759. const controlPhase = wmKeyControlPhase.get(activeElement);
  2760. if (controlPhase === 4 || controlPhase === 5) return false;
  2761. }
  2762. if (focusedElementAtSelection === activeElement && getCurrentSelectionText() !== "") return false;
  2763. // if (!isSpeedMastSpacebarControlEnabled && a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space') {
  2764. // if (!isSpaceKeyImmediate) return false;
  2765. // }
  2766. }
  2767.  
  2768. },
  2769.  
  2770. __handleGlobalKeyAfter__(a, b, c, d, e, f, h, activeElement, ret) {
  2771.  
  2772. if (FIX_SHORTCUTKEYS === 2 && ret && a >= 32 && ytPageReady === 1 && Date.now() - lastUserAction < 40 && activeElement === document.activeElement) {
  2773.  
  2774. const isSpaceBar = a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space';
  2775. const isDelayedSpaceBar = FIX_SHORTCUTKEYS === 2 && isSpaceBar && !isSpaceKeyImmediate && (isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag());
  2776. // console.log(583, isDelayedSpaceBar)
  2777. if (isDelayedSpaceBar) return void 0; // accept delay spacebar under isSpeedMastSpacebarControlEnabled (no rejection)
  2778.  
  2779. const mediaPlayerElement = kRef(mediaPlayerElementWR);
  2780.  
  2781. let mediaWorking = false;
  2782. if (mediaPlayerElement && (mediaPlayerElement.readyState === 4 || mediaPlayerElement.readyState === 1) && mediaPlayerElement.networkState === 2 && mediaPlayerElement.duration > 0.01) {
  2783. mediaWorking = true;
  2784. } else if (mediaPlayerElement && !mediaPlayerElement.paused && !mediaPlayerElement.muted && mediaPlayerElement.duration > 0.01) {
  2785. mediaWorking = true;
  2786. }
  2787. // console.log(182, mediaWorking, mediaPlayerElement.readyState , mediaPlayerElement.networkState)
  2788. mediaWorking && Promise.resolve().then(() => {
  2789. if (activeElement === document.activeElement) {
  2790. return activeElement.blur()
  2791. } else {
  2792. return false
  2793. }
  2794. }).then((r) => {
  2795. r !== false && mediaPlayerElement.focus();
  2796. });
  2797. }
  2798. },
  2799.  
  2800.  
  2801. handleGlobalKeyUp(a, b, c, d, e, f, h) {
  2802.  
  2803. if (BY_PASS_KEYBOARD_CONTROL) return this.handleGlobalKeyUp91(a, b, c, d, e, f, h);
  2804.  
  2805. const activeElement = document.activeElement;
  2806.  
  2807. const allow = typeof this.__handleGlobalKeyBefore__ === 'function' ? this.__handleGlobalKeyBefore__(a, b, c, d, e, f, h, activeElement) : void 0;
  2808. if (allow === false) return false;
  2809.  
  2810. const ret = this.handleGlobalKeyUp91(a, b, c, d, e, f, h);
  2811. // console.log('handleGlobalKeyUp',ret, a, b, c, d, e, f, h);
  2812.  
  2813. typeof this.__handleGlobalKeyAfter__ === 'function' && this.__handleGlobalKeyAfter__(a, b, c, d, e, f, h, activeElement, ret);
  2814.  
  2815. return ret;
  2816. },
  2817. handleGlobalKeyDown(a, b, c, d, e, f, h, l) {
  2818.  
  2819.  
  2820. if (BY_PASS_KEYBOARD_CONTROL) return this.handleGlobalKeyDown91(a, b, c, d, e, f, h, l);
  2821.  
  2822. const activeElement = document.activeElement;
  2823. // if (a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space' && !(isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag())) {
  2824. // return this.handleGlobalKeyDown91(a, b, c, d, e, f, h, l);
  2825. // }
  2826. const allow = typeof this.__handleGlobalKeyBefore__ === 'function' ? this.__handleGlobalKeyBefore__(a, b, c, d, e, f, h, activeElement) : void 0;
  2827. if (allow === false) return false;
  2828.  
  2829. const ret = this.handleGlobalKeyDown91(a, b, c, d, e, f, h, l);
  2830. // console.log('handleGlobalKeyDown',ret, a, b, c, d, e, f, h,l)
  2831.  
  2832. typeof this.__handleGlobalKeyAfter__ === 'function' && this.__handleGlobalKeyAfter__(a, b, c, d, e, f, h, activeElement, ret);
  2833.  
  2834. return ret;
  2835. }
  2836.  
  2837. };
  2838.  
  2839. // const p_a_jt = { // API
  2840.  
  2841. // playVideo(a) { // without spinner effect
  2842.  
  2843. // if (CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE) {
  2844.  
  2845. // const mediaPlayerElement = kRef(mediaPlayerElementWR);
  2846. // if (mediaPlayerElement && !mediaPlayerElement.paused && !mediaPlayerElement.muted && mediaPlayerElement.duration > 0.01) {
  2847. // want_control_video = true;
  2848. // // Promise.resolve().then(()=> mediaPlayerElement.focus() );
  2849. // }
  2850.  
  2851. // }
  2852. // return this.playVideo91(a);
  2853.  
  2854. // },
  2855.  
  2856. // pauseVideo(a) { // without spinner effect
  2857.  
  2858. // if (CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE) {
  2859.  
  2860. // const mediaPlayerElement = kRef(mediaPlayerElementWR);
  2861. // if (mediaPlayerElement && mediaPlayerElement.paused && !mediaPlayerElement.muted && mediaPlayerElement.duration > 0.01) {
  2862. // want_control_video = true;
  2863. // // Promise.resolve().then(()=> mediaPlayerElement.focus() );
  2864. // }
  2865.  
  2866. // }
  2867. // return this.pauseVideo91(a);
  2868.  
  2869. // }
  2870. // };
  2871.  
  2872. let flagSpeedMaster = null;
  2873. const getSpeedMasterControlFlag = () => {
  2874.  
  2875. const config = (win.yt || 0).config_ || (win.ytcfg || 0).data_ || 0;
  2876. isSpeedMastSpacebarControlEnabled = false;
  2877. if (config && config.EXPERIMENT_FLAGS && config.EXPERIMENT_FLAGS.web_speedmaster_spacebar_control) {
  2878. isSpeedMastSpacebarControlEnabled = true;
  2879. }
  2880. if (config && config.EXPERIMENTS_FORCED_FLAGS && config.EXPERIMENTS_FORCED_FLAGS.web_speedmaster_spacebar_control) {
  2881. isSpeedMastSpacebarControlEnabled = true;
  2882. }
  2883.  
  2884. if (flagSpeedMaster === null) {
  2885. const p = (((config || 0).WEB_PLAYER_CONTEXT_CONFIGS || 0).WEB_PLAYER_CONTEXT_CONFIG_ID_KEVLAR_WATCH || 0).serializedExperimentFlags;
  2886. if (!p) {
  2887. flagSpeedMaster = false;
  2888. } else {
  2889.  
  2890. flagSpeedMaster = (p.includes('web_enable_speedmaster=true') && p.includes('web_speedmaster_spacebar_control=true') && p.includes('web_speedmaster_updated_edu=true'));
  2891.  
  2892. }
  2893.  
  2894. }
  2895. if (!flagSpeedMaster) isSpeedMastSpacebarControlEnabled = false;
  2896.  
  2897. return isSpeedMastSpacebarControlEnabled;
  2898. }
  2899.  
  2900.  
  2901. const getGlobalSpacebarControlFlag = () => {
  2902.  
  2903. const config = (win.yt || 0).config_ || (win.ytcfg || 0).data_ || 0;
  2904. isGlobalSpaceControl = false;
  2905. if (config && config.EXPERIMENT_FLAGS && config.EXPERIMENT_FLAGS.global_spacebar_pause) {
  2906. isGlobalSpaceControl = true;
  2907. }
  2908. if (config && config.EXPERIMENTS_FORCED_FLAGS && config.EXPERIMENTS_FORCED_FLAGS.global_spacebar_pause) {
  2909. isGlobalSpaceControl = true;
  2910. }
  2911.  
  2912. return isGlobalSpaceControl;
  2913. }
  2914.  
  2915. const keyboardController = async (_yt_player) => {
  2916.  
  2917. const keyQT = getQT(_yt_player);
  2918. const keySV = getSV(_yt_player);
  2919. const keyDX = getDX(_yt_player);
  2920. console.log(`[QT,SV,DX]`, [keyQT, keySV, keyDX]);
  2921.  
  2922. if (!keyDX) return;
  2923. if (keyDX === keyQT || keyDX === keySV) return;
  2924.  
  2925. if (typeof keyDX !== 'string') return;
  2926.  
  2927. let lastAccessKey = '';
  2928. let lastAccessKeyConfirmed = '';
  2929. const mb = new Proxy({}, {
  2930. get(target, prop) {
  2931. if (prop === 'handleGlobalKeyUp') lastAccessKeyConfirmed = lastAccessKey;
  2932. throw 'mbGet'
  2933. },
  2934. set(target, prop, val) {
  2935. throw 'mbSet'
  2936. }
  2937. });
  2938. const ma = new Proxy({}, {
  2939. get(target, prop) {
  2940. lastAccessKey = prop;
  2941. return mb
  2942. },
  2943. set(target, prop, val) {
  2944. throw 'maSet'
  2945. }
  2946. });
  2947.  
  2948. let keyBw = '';
  2949. try {
  2950. _yt_player[keyDX].prototype.handleGlobalKeyUp.call(ma);
  2951. } catch (e) {
  2952. if (e === 'mbGet' && typeof lastAccessKeyConfirmed === 'string' && lastAccessKeyConfirmed.length > 0) {
  2953. keyBw = lastAccessKeyConfirmed;
  2954. }
  2955. }
  2956.  
  2957. if (!keyBw) return;
  2958.  
  2959. if (typeof _yt_player[keyDX].prototype.init !== 'function' || _yt_player[keyDX].prototype.init.length !== 0) return;
  2960.  
  2961. pm_p_a = new PromiseExternal();
  2962.  
  2963. _yt_player[keyDX].prototype.__cPzfo__ = keyBw;
  2964.  
  2965. _yt_player[keyDX].prototype.init91 = _yt_player[keyDX].prototype.init;
  2966.  
  2967. _yt_player[keyDX].prototype.init = p_a_init;
  2968.  
  2969. await pm_p_a.then();
  2970. const p_a_obj = kRef(p_a_objWR);
  2971.  
  2972. const isSpeedMastSpacebarControlEnabledA = getSpeedMasterControlFlag();
  2973.  
  2974.  
  2975. if (CHANGE_SPEEDMASTER_SPACEBAR_CONTROL > 0) {
  2976.  
  2977. isSpeedMastSpacebarControlEnabled = CHANGE_SPEEDMASTER_SPACEBAR_CONTROL == 1;
  2978.  
  2979. if (!isSpeedMastSpacebarControlEnabled) {
  2980.  
  2981. if (config && config.EXPERIMENT_FLAGS) {
  2982. config.EXPERIMENT_FLAGS.web_speedmaster_spacebar_control = false;
  2983. }
  2984. if (config && config.EXPERIMENTS_FORCED_FLAGS) {
  2985. config.EXPERIMENTS_FORCED_FLAGS.web_speedmaster_spacebar_control = false;
  2986. }
  2987.  
  2988. } else {
  2989.  
  2990. if (config && config.EXPERIMENT_FLAGS) {
  2991. config.EXPERIMENT_FLAGS.web_speedmaster_spacebar_control = true;
  2992. }
  2993. if (config && config.EXPERIMENTS_FORCED_FLAGS) {
  2994. config.EXPERIMENTS_FORCED_FLAGS.web_speedmaster_spacebar_control = true;
  2995. }
  2996.  
  2997. }
  2998.  
  2999. }
  3000.  
  3001. const isSpeedMastSpacebarControlEnabledB = getSpeedMasterControlFlag();
  3002.  
  3003.  
  3004.  
  3005.  
  3006. console.log('[yt-js-engine-tamer] speedmaster by space (yt setting)', isSpeedMastSpacebarControlEnabledA, isSpeedMastSpacebarControlEnabledB);
  3007.  
  3008. // console.log(p_a_obj.handleGlobalKeyUp)
  3009. console.log('[yt-js-engine-tamer] p_a', p_a_obj);
  3010.  
  3011. // console.log(p_a_obj.api)
  3012.  
  3013.  
  3014. // QT -> DX(SV) -> p_a
  3015.  
  3016.  
  3017. /*
  3018. *
  3019. *
  3020. g.k.handleGlobalKeyUp = function(a, b, c, d, e, f, h) {
  3021. b = void 0 === b ? !1 : b;
  3022. c = void 0 === c ? !1 : c;
  3023. d = void 0 === d ? !1 : d;
  3024. e = void 0 === e ? !1 : e;
  3025. var l = g.PT(this);
  3026. l && l.handleGlobalKeyUp(a, b, c, d, e, f, h)
  3027. }
  3028.  
  3029. */
  3030.  
  3031. /*
  3032. *
  3033. *
  3034. *
  3035. g.k.handleGlobalKeyUp = function(a, b, c, d, e, f, h) {
  3036. return this.Bw ? this.Bw.handleGlobalKeyUp(a, b, c, d, e, f, h) : !1
  3037. }
  3038.  
  3039. */
  3040.  
  3041.  
  3042. // if(!keyDX) return;
  3043.  
  3044. // console.log(4999, keyDX)
  3045.  
  3046. };
  3047.  
  3048.  
  3049. const ytResumeFn = function () { // ADVANCED_FIX_SHORTCUTKEYS
  3050.  
  3051. const p_a_obj = kRef(p_a_objWR);
  3052. // const api = p_a_obj.api;
  3053.  
  3054.  
  3055. // console.log(540);
  3056.  
  3057. let boolList = null;
  3058. let ret;
  3059. isSpaceKeyImmediate = true;
  3060. try {
  3061.  
  3062. ret = 0;
  3063. ret = ret | (p_a_obj.handleGlobalKeyDown(32, false, false, false, false, ' ', 'Space', false) ? 1 : 0);
  3064. let p_a_objT;
  3065. if (!spaceBarControl_keyG) { // just in case
  3066. boolList = new Set();
  3067. p_a_objT = new Proxy(p_a_obj, {
  3068. get(target, prop, handler) {
  3069. const val = target[prop];
  3070. if (typeof val !== 'boolean') return val;
  3071. boolList.add(prop);
  3072. // console.log(555, prop, val);
  3073. if (typeof prop === 'string' && prop.length <= 3 && val === true && boolList.length === 1) {
  3074. spaceBarControl_keyG = prop;
  3075. p_a_obj.__uZWaD__ = spaceBarControl_keyG;
  3076. val = false;
  3077. }
  3078. return val;
  3079. }
  3080. });
  3081.  
  3082.  
  3083. } else if (p_a_obj[spaceBarControl_keyG] === true) {
  3084. p_a_obj[spaceBarControl_keyG] = false;
  3085. p_a_objT = p_a_obj;
  3086. // console.log(p_a_obj, spaceBarControl_keyG, p_a_obj[spaceBarControl_keyG] )
  3087. } else {
  3088.  
  3089. p_a_objT = p_a_obj;
  3090. }
  3091.  
  3092. ret = ret | (p_a_objT.handleGlobalKeyUp(32, false, false, false, false, ' ', 'Space') ? 2 : 0);
  3093.  
  3094.  
  3095. } catch (e) {
  3096. console.log(e)
  3097. }
  3098. isSpaceKeyImmediate = false;
  3099.  
  3100. if (boolList && boolList.size === 1) {
  3101. const value = boolList.values().next().value;
  3102. spaceBarControl_keyG = value;
  3103. p_a_obj.__uZWaD__ = spaceBarControl_keyG;
  3104.  
  3105. }
  3106.  
  3107. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  3108.  
  3109. return ret;
  3110. }
  3111.  
  3112. const shortcutKeysFixer = () => {
  3113.  
  3114. let pausePromiseControlJ = 0;
  3115.  
  3116.  
  3117. const obtainCurrentControlPhase = (evt, mediaPlayerElement) => {
  3118.  
  3119. let controlPhase = 0;
  3120. const aElm = document.activeElement;
  3121.  
  3122. if (aElm) {
  3123.  
  3124. const controlPhaseCache = wmKeyControlPhase.get(aElm);
  3125.  
  3126. if (typeof controlPhaseCache === 'number') {
  3127.  
  3128. controlPhase = controlPhaseCache;
  3129. } else {
  3130.  
  3131. if (aElm instanceof HTMLInputElement) controlPhase = 1;
  3132. else if (aElm instanceof HTMLTextAreaElement) controlPhase = 1;
  3133. else if (aElm instanceof HTMLButtonElement) controlPhase = 2;
  3134. else if (aElm instanceof HTMLIFrameElement) controlPhase = 2;
  3135. else if (aElm instanceof HTMLImageElement) controlPhase = 2;
  3136. else if (aElm instanceof HTMLEmbedElement) controlPhase = 2;
  3137. else {
  3138. if (aElm instanceof HTMLElement && aElm.closest('[role]')) controlPhase = 5;
  3139. if (aElm instanceof HTMLDivElement) controlPhase = 2;
  3140. else if (aElm instanceof HTMLAnchorElement) controlPhase = 2;
  3141. else if (!(aElm instanceof HTMLElement) && (aElm instanceof Element)) controlPhase = 2; // svg
  3142. }
  3143.  
  3144. if ((controlPhase === 2 || controlPhase === 5) && (aElm instanceof HTMLElement) && aElm.contains(mediaPlayerElement)) {
  3145. controlPhase = 0;
  3146. }
  3147.  
  3148. if ((controlPhase === 2 || controlPhase === 5) && evt && evt.target && evt.target === aElm) {
  3149. if (aElm.closest('[contenteditable], input, textarea')) {
  3150. controlPhase = 5;
  3151. } else if (aElm.closest('button')) {
  3152. controlPhase = 4;
  3153. }
  3154. }
  3155.  
  3156. if (aElm.closest('#movie_player')) controlPhase = 6;
  3157.  
  3158. wmKeyControlPhase.set(aElm, controlPhase);
  3159.  
  3160. }
  3161. }
  3162.  
  3163. return controlPhase;
  3164.  
  3165. }
  3166.  
  3167. const isStateControllable = (api) => {
  3168. let appState = null;
  3169. let playerState = null;
  3170. let adState = null;
  3171. try {
  3172. appState = api.getAppState();
  3173. playerState = api.getPlayerState();
  3174. adState = api.getAdState();
  3175. } catch (e) { }
  3176. // ignore playerState -1
  3177. return appState === 5 && adState === -1 && (playerState === 1 || playerState === 2 || playerState === 3);
  3178. };
  3179.  
  3180.  
  3181. const keyEventListener = (evt) => {
  3182. if (BY_PASS_KEYBOARD_CONTROL) return;
  3183.  
  3184. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  3185. if (isSpaceKeyImmediate || !evt.isTrusted || !(evt instanceof KeyboardEvent)) return;
  3186. if (!ytPageReady) return;
  3187.  
  3188. if (evt.defaultPrevented === true) return;
  3189.  
  3190. const p_a_obj = kRef(p_a_objWR);
  3191.  
  3192. if (!p_a_obj) return;
  3193.  
  3194.  
  3195. const mediaPlayerElement = kRef(mediaPlayerElementWR);
  3196. if (!mediaPlayerElement) return;
  3197.  
  3198. // let focusBodyIfSuccess = false;
  3199.  
  3200. const controlPhase = obtainCurrentControlPhase(evt, mediaPlayerElement);
  3201.  
  3202. if (controlPhase === 6 && getCurrentSelectionText() !== "") void 0;
  3203. else if (controlPhase === 1 || controlPhase === 2 || controlPhase === 5) return;
  3204. else if ((controlPhase !== 6 || focusedElementAtSelection === document.activeElement) && getCurrentSelectionText() !== "") return;
  3205.  
  3206.  
  3207. if (evt.code === 'Space' && !getGlobalSpacebarControlFlag()) return;
  3208.  
  3209. // console.log(`${evt.type}::controlPhase`,controlPhase)
  3210.  
  3211. // if (controlPhase == 4) {
  3212. // focusBodyIfSuccess = true;
  3213. // }
  3214.  
  3215. spaceBarControl_keyG = spaceBarControl_keyG || p_a_obj.__uZWaD__ || ''
  3216. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  3217.  
  3218. if (FIX_SHORTCUTKEYS < 2) return;
  3219. if (!(!evt.shiftKey && !evt.ctrlKey && !evt.altKey && !evt.metaKey)) return; // ignore if modifier key is pressed -> let other event listener to handle first
  3220.  
  3221. let rr;
  3222. const isSpaceBar = evt.code === 'Space' && !evt.shiftKey && !evt.ctrlKey && !evt.altKey && !evt.metaKey;
  3223.  
  3224.  
  3225.  
  3226. let useImprovedPauseResume = false;
  3227.  
  3228. if (USE_IMPROVED_PAUSERESUME_UNDER_NO_SPEEDMASTER && isSpaceBar && !(isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag())) {
  3229.  
  3230. const api = p_a_obj.api;
  3231. const stateControllable = isStateControllable(api);
  3232. // console.log(2122, appState, playerState, adState)
  3233.  
  3234. if (stateControllable && isWatchPageURL() && mediaPlayerElement.duration > 0.01 && (mediaPlayerElement.readyState === 4 || mediaPlayerElement.readyState === 1) && mediaPlayerElement.networkState === 2) {
  3235.  
  3236. useImprovedPauseResume = true;
  3237.  
  3238. }
  3239.  
  3240.  
  3241. }
  3242.  
  3243.  
  3244. // force flag: CHANGE_SPEEDMASTER_SPACEBAR_CONTROL
  3245. if (evt.type === 'keydown') {
  3246.  
  3247. if (useImprovedPauseResume) {
  3248.  
  3249. const isPaused = mediaPlayerElement.paused;
  3250.  
  3251. const cj = ++pausePromiseControlJ;
  3252. Promise.resolve().then(() => {
  3253.  
  3254. if (cj !== pausePromiseControlJ) return;
  3255.  
  3256. if (mediaPlayerElement.paused !== isPaused) return;
  3257.  
  3258. const ret = ytResumeFn();
  3259. if (!ret) { // fallback
  3260. isPaused ? api.playVideo() : api.pauseVideo();
  3261. }
  3262.  
  3263. /*
  3264. let a = void 0;
  3265. console.log('Rb', api.Rb())
  3266. a = !window._yt_player.nL(api.Rb());
  3267. p_a_obj.Wd.kG(a)
  3268. a ? api.playVideo() : api.pauseVideo();
  3269.  
  3270. */
  3271.  
  3272.  
  3273. });
  3274. rr = true;
  3275. } else {
  3276.  
  3277. isSpaceKeyImmediate = true;
  3278. rr = p_a_obj.handleGlobalKeyDown(evt.keyCode, evt.shiftKey, evt.ctrlKey, evt.altKey, evt.metaKey, evt.key, evt.code, evt.repeat);
  3279. isSpaceKeyImmediate = false;
  3280. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  3281.  
  3282. }
  3283.  
  3284.  
  3285. } else if (evt.type === 'keyup') {
  3286.  
  3287. if (isSpaceBar && useImprovedPauseResume && !(isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag())) {
  3288.  
  3289. rr = true;
  3290. } else {
  3291.  
  3292. isSpaceKeyImmediate = true;
  3293. rr = p_a_obj.handleGlobalKeyUp(evt.keyCode, evt.shiftKey, evt.ctrlKey, evt.altKey, evt.metaKey, evt.key, evt.code);
  3294. isSpaceKeyImmediate = false;
  3295. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  3296.  
  3297. }
  3298.  
  3299.  
  3300. /*
  3301.  
  3302. if (d)
  3303. switch (c) {
  3304. case 32:
  3305. case 13:
  3306. if ("BUTTON" === d.tagName || "A" === d.tagName || "INPUT" === d.tagName)
  3307. b = !0,
  3308. e = !1;
  3309. else if (e) {
  3310. var m = d.getAttribute("role");
  3311. !m || "option" !== m && "button" !== m && 0 !== m.indexOf("menuitem") || (b = !0,
  3312. d.click(),
  3313. f = !0)
  3314. }
  3315. break;
  3316. case 37:
  3317. case 39:
  3318. case 36:
  3319. case 35:
  3320. b = "slider" === d.getAttribute("role");
  3321. break;
  3322. case 38:
  3323. case 40:
  3324. m = d.getAttribute("role"),
  3325. d = 38 === c ? d.previousSibling : d.nextSibling,
  3326. "slider" === m ? b = !0 : e && ("option" === m ? (d && "option" === d.getAttribute("role") && d.focus(),
  3327. f = b = !0) : m && 0 === m.indexOf("menuitem") && (d && d.hasAttribute("role") && 0 === d.getAttribute("role").indexOf("menuitem") && d.focus(),
  3328. f = b = !0))
  3329. }
  3330. if (e && !f)
  3331. switch (c) {
  3332. case 38:
  3333. f = Math.min(this.api.getVolume() + 5, 100);
  3334. XV(this.Wd, f, !1);
  3335. this.api.setVolume(f);
  3336. h = f = !0;
  3337. break;
  3338. case 40:
  3339. f = Math.max(this.api.getVolume() - 5, 0);
  3340. XV(this.Wd, f, !0);
  3341. this.api.setVolume(f);
  3342. h = f = !0;
  3343. break;
  3344. case 36:
  3345. this.api.Yh() && (this.api.startSeekCsiAction(),
  3346. this.api.seekTo(0, void 0, void 0, void 0, 79),
  3347. h = f = !0);
  3348. break;
  3349. case 35:
  3350. this.api.Yh() && (this.api.startSeekCsiAction(),
  3351. this.api.seekTo(Infinity, void 0, void 0, void 0, 80),
  3352. h = f = !0)
  3353. }
  3354. */
  3355.  
  3356. }
  3357.  
  3358.  
  3359. if (rr) {
  3360.  
  3361. // focusBodyIfSuccess && Promise.resolve().then(() => {
  3362. // activeElement === document.activeElement && activeElement.blur();
  3363. // });
  3364.  
  3365. evt.preventDefault();
  3366. evt.stopImmediatePropagation();
  3367. evt.stopPropagation();
  3368.  
  3369. }
  3370.  
  3371. };
  3372.  
  3373. document.addEventListener('keydown', keyEventListener, { capture: true });
  3374.  
  3375.  
  3376. document.addEventListener('keyup', keyEventListener, { capture: true });
  3377.  
  3378. }
  3379.  
  3380. return { pageMediaWatcher, shortcutKeysFixer, keyboardController };
  3381.  
  3382. })();
  3383.  
  3384.  
  3385. pageMediaWatcher();
  3386. FIX_SHORTCUTKEYS > 0 && shortcutKeysFixer();
  3387.  
  3388.  
  3389. const check_for_set_key_order = (() => {
  3390.  
  3391. let mySet = new Set();
  3392.  
  3393. mySet.add("value1");
  3394. mySet.add("value2");
  3395. mySet.add("value3");
  3396.  
  3397. // Function to convert Set values to an array
  3398. function getSetValues(set) {
  3399. return Array.from(set.values());
  3400. }
  3401.  
  3402. // Function to test if the Set maintains insertion order
  3403. function testSetOrder(set, expectedOrder) {
  3404. let values = getSetValues(set);
  3405. return expectedOrder.join(',') === values.join(',');
  3406. }
  3407.  
  3408. // Test 1: Initial order
  3409. if (mySet.values().next().value !== "value1") return false;
  3410. if (!testSetOrder(mySet, ["value1", "value2", "value3"])) return false;
  3411.  
  3412. // Test 2: After deleting an element
  3413. mySet.delete("value2");
  3414. if (mySet.values().next().value !== "value1") return false;
  3415. if (!testSetOrder(mySet, ["value1", "value3"])) return false;
  3416.  
  3417. // Test 3: After re-adding a deleted element
  3418. mySet.add("value2");
  3419. if (mySet.values().next().value !== "value1") return false;
  3420. if (!testSetOrder(mySet, ["value1", "value3", "value2"])) return false;
  3421.  
  3422. // Test 4: After adding a new element
  3423. mySet.add("value4");
  3424. if (mySet.values().next().value !== "value1") return false;
  3425. if (!testSetOrder(mySet, ["value1", "value3", "value2", "value4"])) return false;
  3426.  
  3427. // Test 5: Delete+Add
  3428. mySet.delete("value1");
  3429. mySet.delete("value3");
  3430. mySet.add("value3");
  3431. mySet.add("value1");
  3432. if (mySet.values().next().value !== "value2") return false;
  3433. if (!testSetOrder(mySet, ["value2", "value4", "value3", "value1"])) return false;
  3434.  
  3435. return true;
  3436. })();
  3437.  
  3438.  
  3439. // const qm47 = Symbol();
  3440. const qm57 = Symbol();
  3441. const qm53 = Symbol();
  3442. const qn53 = Symbol();
  3443.  
  3444.  
  3445. const ump3 = new WeakMap();
  3446.  
  3447. const stp = document.createElement('noscript');
  3448. stp.id = 'weakref-placeholder';
  3449.  
  3450. PROP_OverReInclusion_AVOID && (() => {
  3451.  
  3452.  
  3453. if (typeof HTMLElement.prototype.hasOwnProperty72 === 'function' || typeof HTMLElement.prototype.hasOwnProperty !== 'function') return;
  3454. const f = HTMLElement.prototype.hasOwnProperty72 = HTMLElement.prototype.hasOwnProperty;
  3455. let byPassVal = null;
  3456. let byPassCount = 0;
  3457. let mmw = new Set();
  3458. HTMLElement.prototype.hasOwnProperty = function (prop) {
  3459. if (arguments.length !== 1) return f.apply(this, arguments);
  3460. if (byPassVal !== null && typeof prop === 'string') {
  3461.  
  3462. if (PROP_OverReInclusion_LIST.has(prop)) {
  3463. byPassCount++;
  3464. return byPassVal;
  3465. }
  3466. PROP_OverReInclusion_DEBUGLOG && mmw.add(prop);
  3467.  
  3468. }
  3469. return this.hasOwnProperty72(prop);
  3470. };
  3471.  
  3472.  
  3473. /*
  3474.  
  3475.  
  3476. z.prototype.forwardDynamicProps = function() {
  3477. var B = m(this.inst);
  3478. B = h(B);
  3479. for (var F = B.next(); !F.done; F = B.next()) {
  3480. var H = h(F.value);
  3481. F = H.next().value;
  3482. H = H.next().value;
  3483. my(this, F, H);
  3484. r(b) && !ly(F) && Wua(this.inst, F)
  3485. }
  3486. }
  3487.  
  3488. */
  3489.  
  3490.  
  3491.  
  3492. let byPassZeroShowed = false;
  3493. const forwardDynamicPropsGeneral = function () {
  3494. byPassVal = true;
  3495. byPassCount = 0;
  3496. PROP_OverReInclusion_DEBUGLOG && mmw.clear();
  3497. const ret = this.forwardDynamicProps72();
  3498. byPassVal = null;
  3499. if (byPassCount === 0 && !byPassZeroShowed) {
  3500. byPassZeroShowed = true;
  3501. console.log('[yt-js-engine-tamer] byPassCount = 0 in forwardDynamicProps')
  3502. }
  3503. byPassCount = 0;
  3504. if (PROP_OverReInclusion_DEBUGLOG && mmw.size > 0) {
  3505. console.log(399, '[yt-js-engine-tamer]', [...mmw]);
  3506. mmw.clear();
  3507. }
  3508. return ret;
  3509. };
  3510.  
  3511. const propCheck = (proto) => {
  3512. if (typeof (proto || 0) == 'object' && typeof proto.forwardDynamicProps === 'function' && typeof proto.forwardDynamicProps72 !== 'function') {
  3513. proto.forwardDynamicProps72 = proto.forwardDynamicProps;
  3514. if (proto.forwardDynamicProps.length === 0) {
  3515. proto.forwardDynamicProps = forwardDynamicPropsGeneral;
  3516. }
  3517. }
  3518. };
  3519.  
  3520. const valMap = new WeakMap();
  3521. Object.defineProperty(HTMLElement.prototype, 'didForwardDynamicProps', {
  3522. get() {
  3523. propCheck(this.constructor.prototype);
  3524. return valMap.get(this);
  3525. },
  3526. set(nv) {
  3527. propCheck(this.constructor.prototype);
  3528. valMap.set(this, nv);
  3529. return true;
  3530. },
  3531. enumerable: false,
  3532. configurable: true
  3533.  
  3534. });
  3535.  
  3536. promiseForCustomYtElementsReady.then(() => {
  3537. if (typeof customElements !== 'object' || typeof customElements.define72 === 'function' || typeof customElements.define !== 'function') return;
  3538. if (customElements.define.length !== 2) return;
  3539. customElements.define72 = customElements.define;
  3540. customElements.define = function (b, w) {
  3541. propCheck(w.prototype);
  3542. const ret = this.define72(b, w);
  3543. return ret;
  3544. }
  3545. });
  3546.  
  3547. })();
  3548.  
  3549.  
  3550. const convertionFuncMap = new WeakMap();
  3551. let val_kevlar_should_maintain_stable_list = null;
  3552.  
  3553. const createStampDomArrayFn_ = (fn) => {
  3554. if (val_kevlar_should_maintain_stable_list === null) {
  3555. const config_ = ((window.yt || 0).config_ || 0);
  3556. val_kevlar_should_maintain_stable_list = ((config_ || 0).EXPERIMENT_FLAGS || 0).kevlar_should_maintain_stable_list === true
  3557. }
  3558. const gn = function (a, b, c, d, e, h) {
  3559. const isNonEmptyArray = (a || 0).length >= 1
  3560. if (!isNonEmptyArray) {
  3561. return fn.call(this, undefined, b, undefined, d);
  3562. } else if (h === undefined && typeof b === 'string' && c && typeof c === 'object' && this.is && val_kevlar_should_maintain_stable_list) {
  3563. if (c.clientSideToggleMenuItemRenderer) {
  3564. h = false;
  3565. } else {
  3566. h = true;
  3567. }
  3568. }
  3569. return fn.call(this, a, b, c, d, e, h)
  3570. }
  3571. gn.originalFn = fn;
  3572. convertionFuncMap.set(fn, gn);
  3573. return gn;
  3574. }
  3575.  
  3576. const fixStampDomArrayStableList = (h) => {
  3577. if (!h.stampDomArray_) return;
  3578. const proto = h.__proto__;
  3579. const f = proto.stampDomArray_;
  3580. if (!proto.stampDomArrayF001_ && typeof f === 'function' && f.length === 6) {
  3581. proto.stampDomArrayF001_ = 1;
  3582. proto.stampDomArray_ = convertionFuncMap.get(f) || createStampDomArrayFn_(f);
  3583. }
  3584. }
  3585.  
  3586. const weakenStampReferences = (() => {
  3587.  
  3588. const DEBUG_STAMP = false;
  3589.  
  3590. const s1 = Symbol();
  3591. const handler1 = {
  3592. get(target, prop, receiver) {
  3593. if (prop === 'object') {
  3594. return kRef(target[s1]); // avoid memory leakage
  3595. }
  3596. if (prop === '__proxy312__') return 1;
  3597. return target[prop];
  3598. }
  3599. };
  3600. const handler2 = {
  3601. get(target, prop, receiver) {
  3602. if (prop === 'indexSplices') {
  3603. return kRef(target[s1]); // avoid memory leakage
  3604. }
  3605. if (prop === '__proxy312__') return 1;
  3606. return target[prop];
  3607. }
  3608. }
  3609. return (h) => {
  3610.  
  3611. if (h.rendererStamperApplyChangeRecord_ || h.stampDomArraySplices_) {
  3612. const proto = h.__proto__;
  3613. if (!proto.yzxer && (proto.rendererStamperApplyChangeRecord_ || proto.stampDomArraySplices_)) {
  3614. proto.yzxer = 1;
  3615.  
  3616. const list = [
  3617. // "rendererStamperObserver_", // 3 ==> rendererStamperApplyChangeRecord_
  3618. "rendererStamperApplyChangeRecord_", // 3
  3619. "forwardRendererStamperChanges_", // 3
  3620. "stampDomArraySplices_", // 3
  3621. "stampDomArray_", // 6
  3622. "deferRenderStamperBinding_", // 3
  3623. ];
  3624. for (const key of list) {
  3625. const pey = `${key}$wq0iw_`;
  3626. const vKey = proto[key];
  3627. if (typeof vKey !== 'function') continue;
  3628. if (proto[pey] || vKey.length === 0) continue;
  3629.  
  3630. if (key === 'stampDomArraySplices_' && vKey.length === 3) {
  3631. proto[pey] = vKey;
  3632. proto[key] = function (a, b, c) {
  3633.  
  3634. if (typeof a === 'string' && typeof b === 'string' && typeof c === 'object' && c && c.indexSplices && c.indexSplices.length >= 1 && !c.indexSplices.rzgjr) {
  3635.  
  3636. c.indexSplices = c.indexSplices.map(e => {
  3637. if (e.__proxy312__) return e;
  3638. e[s1] = mWeakRef(e.object);
  3639. e.object = null;
  3640. return new Proxy(e, handler1);
  3641. });
  3642. c.indexSplices.rzgjr = 1;
  3643.  
  3644. c[s1] = mWeakRef(c.indexSplices);
  3645. c.indexSplices = null;
  3646. c = new Proxy(c, handler2)
  3647. arguments[2] = c;
  3648.  
  3649. }
  3650. // console.log(key, arguments.length, [...arguments]);
  3651. return proto[pey].call(this, a, b, c);
  3652. }
  3653.  
  3654. } else if (key === 'rendererStamperApplyChangeRecord_' && vKey.length === 3) {
  3655.  
  3656. // Nil
  3657.  
  3658. } else if (DEBUG_STAMP) {
  3659.  
  3660. console.log(proto.isRenderer_, 'ms_' + key, vKey.length, h.is)
  3661. proto[pey] = vKey;
  3662. proto[key] = function () {
  3663. if (key === 'rendererStamperApplyChangeRecord_' && typeof arguments[3] === 'object') {
  3664. console.log(key, arguments.length, { value: arguments[3].value, base: arguments[3].base, })
  3665. }
  3666. console.log(key, arguments.length, [...arguments]);
  3667. return proto[pey].apply(this, arguments);
  3668. }
  3669.  
  3670. }
  3671.  
  3672. }
  3673.  
  3674.  
  3675. // const m = (Object.mkss = Object.mkss || new Set());
  3676. // Object.keys(h.__proto__).filter(e => e.toLowerCase().includes('stamp') && typeof h[e] === 'function').forEach(e => m.add(e))
  3677. // console.log([...m])
  3678. }
  3679. }
  3680.  
  3681. }
  3682. })();
  3683.  
  3684. const setupDiscreteTasks = (h, rb) => {
  3685.  
  3686. if (rb) {
  3687. if (h.ky36) return;
  3688. }
  3689.  
  3690.  
  3691. if (typeof h.onYtRendererstamperFinished === 'function' && !(h.onYtRendererstamperFinished.km34)) {
  3692. const f = h.onYtRendererstamperFinished;
  3693. const g = ump3.get(f) || function () {
  3694. if (this.updateChildVisibilityProperties && !this.markDirty) {
  3695. return f.apply(this, arguments);
  3696. }
  3697. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3698. }
  3699. ump3.set(f, g);
  3700. g.km34 = 1;
  3701. h.onYtRendererstamperFinished = g;
  3702.  
  3703. }
  3704.  
  3705. if (typeof h.onYtUpdateDescriptionAction === 'function' && !(h.onYtUpdateDescriptionAction.km34)) {
  3706. const f = h.onYtUpdateDescriptionAction;
  3707. const g = ump3.get(f) || function (a) {
  3708. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3709. }
  3710. ump3.set(f, g);
  3711. g.km34 = 1;
  3712. h.onYtUpdateDescriptionAction = g;
  3713.  
  3714. }
  3715.  
  3716. if (typeof h.handleUpdateDescriptionAction === 'function' && !(h.handleUpdateDescriptionAction.km34)) {
  3717. const f = h.handleUpdateDescriptionAction;
  3718. const g = ump3.get(f) || function (a) {
  3719. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3720. }
  3721. ump3.set(f, g);
  3722. g.km34 = 1;
  3723. h.handleUpdateDescriptionAction = g;
  3724.  
  3725. }
  3726.  
  3727. if (typeof h.handleUpdateLiveChatPollAction === 'function' && !(h.handleUpdateLiveChatPollAction.km34)) {
  3728. const f = h.handleUpdateLiveChatPollAction;
  3729. const g = ump3.get(f) || function (a) {
  3730. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3731. }
  3732. ump3.set(f, g);
  3733. g.km34 = 1;
  3734. h.handleUpdateLiveChatPollAction = g;
  3735.  
  3736. }
  3737.  
  3738. if (typeof h.onTextChanged === 'function' && !(h.onTextChanged.km34)) {
  3739. const f = h.onTextChanged;
  3740. const g = ump3.get(f) || function () {
  3741. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3742. }
  3743. ump3.set(f, g);
  3744. g.km34 = 1;
  3745. h.onTextChanged = g;
  3746.  
  3747. }
  3748.  
  3749. if (typeof h.onVideoDataChange === 'function' && !(h.onVideoDataChange.km34)) {
  3750. const f = h.onVideoDataChange;
  3751. const g = ump3.get(f) || function (a) {
  3752. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3753. }
  3754. ump3.set(f, g);
  3755. g.km34 = 1;
  3756. h.onVideoDataChange = g;
  3757.  
  3758. }
  3759.  
  3760. if (typeof h.onVideoDataChange_ === 'function' && !(h.onVideoDataChange_.km34)) {
  3761. const f = h.onVideoDataChange_;
  3762. const g = ump3.get(f) || function () {
  3763. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3764. }
  3765. ump3.set(f, g);
  3766. g.km34 = 1;
  3767. h.onVideoDataChange_ = g;
  3768.  
  3769. }
  3770.  
  3771. /*
  3772. // affect chat message icon tooltips
  3773. if (typeof h.addTooltips === 'function' && !(h.addTooltips.km34)) {
  3774.  
  3775. const f = h.addTooltips;
  3776. const g = ump3.get(f) || function () {
  3777. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3778. }
  3779. ump3.set(f, g);
  3780. g.km34 = 1;
  3781. h.addTooltips = g;
  3782.  
  3783. }
  3784. */
  3785. /*
  3786. if (typeof h.onMouseOver_ === 'function' && !(h.onMouseOver_.km34) && typeof h.createTooltipIfRequired_ === 'function') {
  3787. console.log(212, h.is);
  3788. const f = h.onMouseOver_;
  3789. const g = ump3.get(f) || function () {
  3790.  
  3791. if (!this.__mEZ__) {
  3792.  
  3793.  
  3794. const w = document.createElement;
  3795. let EU = null;
  3796. document.createElement = function () {
  3797. let r = w.apply(this, arguments);
  3798. EU = r;
  3799. return r;
  3800. };
  3801. let done = false;
  3802. try {
  3803. this.polymerController.createTooltipIfRequired_();
  3804. done = true;
  3805. } catch (e) {
  3806.  
  3807. }
  3808. if (!done) {
  3809. try {
  3810. this.createTooltipIfRequired_();
  3811. done = true;
  3812. } catch (e) {
  3813.  
  3814. }
  3815.  
  3816. }
  3817. this.__mEZ__ = EU;
  3818. document.createElement = w;
  3819. }
  3820. if(this.__mEZ__){
  3821. this.__mEZ__.remove();
  3822. // this.__mEZ__.for = null;
  3823. [...this.__mEZ__.querySelectorAll('.hidden')].forEach(e=>e.classList.remove('hidden'))
  3824. }
  3825. console.log(212,this, this.is, this.__mEZ__)
  3826. return f.apply(this, arguments)
  3827. }
  3828. ump3.set(f, g);
  3829. g.km34 = 1;
  3830. h.onMouseOver_ = g;
  3831.  
  3832. }
  3833. */
  3834.  
  3835.  
  3836. if (typeof h.addTooltips_ === 'function' && !(h.addTooltips_.km34)) {
  3837.  
  3838. const f = h.addTooltips_;
  3839. const g = ump3.get(f) || function () {
  3840. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3841. }
  3842. ump3.set(f, g);
  3843. g.km34 = 1;
  3844. h.addTooltips_ = g;
  3845.  
  3846. }
  3847.  
  3848. if (typeof h.updateRenderedElements === 'function' && !(h.updateRenderedElements.km34)) {
  3849.  
  3850. const f = h.updateRenderedElements;
  3851. const g = ump3.get(f) || function () {
  3852. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3853. }
  3854. ump3.set(f, g);
  3855. g.km34 = 1;
  3856. h.updateRenderedElements = g;
  3857.  
  3858. }
  3859.  
  3860. if ((WEAK_REF_BINDING_CONTROL & 2) && typeof h.loadPage_ === 'function' && !(h.loadPage_.km34)) {
  3861. const f = h.loadPage_;
  3862. const g = ump3.get(f) || function (a) {
  3863. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3864. }
  3865. ump3.set(f, g);
  3866. g.km34 = 1;
  3867. h.loadPage_ = g;
  3868.  
  3869. }
  3870. // updatePageData_ : possible conflict with Omit ShadyDOM
  3871. if ((WEAK_REF_BINDING_CONTROL & 2) && typeof h.updatePageData_ === 'function' && !(h.updatePageData_.km34)) {
  3872. const f = h.updatePageData_;
  3873. const g = ump3.get(f) || function (a) {
  3874. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3875. }
  3876. ump3.set(f, g);
  3877. g.km34 = 1;
  3878. h.updatePageData_ = g;
  3879.  
  3880. }
  3881.  
  3882.  
  3883. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onFocus_ === 'function' && !(h.onFocus_.km34)) {
  3884.  
  3885. const f = h.onFocus_;
  3886. const g = ump3.get(f) || function () {
  3887. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3888. }
  3889. ump3.set(f, g);
  3890. g.km34 = 1;
  3891. h.onFocus_ = g;
  3892.  
  3893. }
  3894.  
  3895. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onBlur_ === 'function' && !(h.onBlur_.km34)) {
  3896.  
  3897. const f = h.onBlur_;
  3898. const g = ump3.get(f) || function () {
  3899. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3900. }
  3901. ump3.set(f, g);
  3902. g.km34 = 1;
  3903. h.onBlur_ = g;
  3904.  
  3905. }
  3906.  
  3907.  
  3908. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.buttonClassChanged_ === 'function' && !(h.buttonClassChanged_.km34)) {
  3909.  
  3910. const f = h.buttonClassChanged_;
  3911. const g = ump3.get(f) || function (a, b) {
  3912. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3913. }
  3914. ump3.set(f, g);
  3915. g.km34 = 1;
  3916. h.buttonClassChanged_ = g;
  3917.  
  3918. }
  3919.  
  3920. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.buttonIconChanged_ === 'function' && !(h.buttonIconChanged_.km34)) {
  3921.  
  3922. const f = h.buttonIconChanged_;
  3923. const g = ump3.get(f) || function (a) {
  3924. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3925. }
  3926. ump3.set(f, g);
  3927. g.km34 = 1;
  3928. h.buttonIconChanged_ = g;
  3929.  
  3930. }
  3931.  
  3932. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.dataChangedInBehavior_ === 'function' && !(h.dataChangedInBehavior_.km34)) {
  3933.  
  3934. const f = h.dataChangedInBehavior_;
  3935. const g = ump3.get(f) || function () {
  3936. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3937. }
  3938. ump3.set(f, g);
  3939. g.km34 = 1;
  3940. h.dataChangedInBehavior_ = g;
  3941.  
  3942. }
  3943.  
  3944. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.continuationsChanged_ === 'function' && !(h.continuationsChanged_.km34)) {
  3945.  
  3946. const f = h.continuationsChanged_;
  3947. const g = ump3.get(f) || function () {
  3948. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3949. }
  3950. ump3.set(f, g);
  3951. g.km34 = 1;
  3952. h.continuationsChanged_ = g;
  3953.  
  3954. }
  3955.  
  3956.  
  3957. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.forceChatPoll_ === 'function' && !(h.forceChatPoll_.km34)) {
  3958.  
  3959. const f = h.forceChatPoll_;
  3960. const g = ump3.get(f) || function (a) {
  3961. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3962. }
  3963. ump3.set(f, g);
  3964. g.km34 = 1;
  3965. h.forceChatPoll_ = g;
  3966.  
  3967. }
  3968.  
  3969. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onEndpointClick_ === 'function' && !(h.onEndpointClick_.km34)) {
  3970.  
  3971. const f = h.onEndpointClick_;
  3972. const g = ump3.get(f) || function (a) {
  3973. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3974. }
  3975. ump3.set(f, g);
  3976. g.km34 = 1;
  3977. h.onEndpointClick_ = g;
  3978.  
  3979. }
  3980.  
  3981. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onEndpointTap_ === 'function' && !(h.onEndpointTap_.km34)) {
  3982.  
  3983. const f = h.onEndpointTap_;
  3984. const g = ump3.get(f) || function (a) {
  3985. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3986. }
  3987. ump3.set(f, g);
  3988. g.km34 = 1;
  3989. h.onEndpointTap_ = g;
  3990.  
  3991. }
  3992.  
  3993. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.handleClick_ === 'function' && !(h.handleClick_.km34)) {
  3994.  
  3995. const f = h.handleClick_;
  3996. const g = ump3.get(f) || function (a, b) {
  3997. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  3998. }
  3999. ump3.set(f, g);
  4000. g.km34 = 1;
  4001. h.handleClick_ = g;
  4002.  
  4003. }
  4004.  
  4005. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onReadyStateChange_ === 'function' && !(h.onReadyStateChange_.km34)) {
  4006.  
  4007. const f = h.onReadyStateChange_;
  4008. const g = ump3.get(f) || function () {
  4009. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4010. }
  4011. ump3.set(f, g);
  4012. g.km34 = 1;
  4013. h.onReadyStateChange_ = g;
  4014.  
  4015. }
  4016.  
  4017. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onReadyStateChangeEntryPoint_ === 'function' && !(h.onReadyStateChangeEntryPoint_.km34)) {
  4018.  
  4019. const f = h.onReadyStateChangeEntryPoint_;
  4020. const g = ump3.get(f) || function () {
  4021. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4022. }
  4023. ump3.set(f, g);
  4024. g.km34 = 1;
  4025. h.onReadyStateChangeEntryPoint_ = g;
  4026.  
  4027. }
  4028.  
  4029. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.readyStateChangeHandler_ === 'function' && !(h.readyStateChangeHandler_.km34)) {
  4030.  
  4031. const f = h.readyStateChangeHandler_;
  4032. const g = ump3.get(f) || function (a) {
  4033. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4034. }
  4035. ump3.set(f, g);
  4036. g.km34 = 1;
  4037. h.readyStateChangeHandler_ = g;
  4038.  
  4039. }
  4040.  
  4041. if (typeof h.xmlHttpHandler_ === 'function' && !(h.xmlHttpHandler_.km34)) {
  4042.  
  4043. const f = h.xmlHttpHandler_;
  4044. const g = ump3.get(f) || function (a) {
  4045. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4046. }
  4047. ump3.set(f, g);
  4048. g.km34 = 1;
  4049. h.xmlHttpHandler_ = g;
  4050.  
  4051. }
  4052.  
  4053. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.executeCallbacks_ === 'function' && !(h.executeCallbacks_.km34)) {
  4054.  
  4055. const f = h.executeCallbacks_; // overloaded
  4056. const g = ump3.get(f) || function (a) {
  4057. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4058. }
  4059. ump3.set(f, g);
  4060. g.km34 = 1;
  4061. h.executeCallbacks_ = g;
  4062.  
  4063. }
  4064.  
  4065. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.handleInvalidationData_ === 'function' && !(h.handleInvalidationData_.km34)) {
  4066.  
  4067. const f = h.handleInvalidationData_;
  4068. const g = ump3.get(f) || function (a, b) {
  4069. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4070. }
  4071. ump3.set(f, g);
  4072. g.km34 = 1;
  4073. h.handleInvalidationData_ = g;
  4074.  
  4075. }
  4076.  
  4077. if (typeof h.onInput_ === 'function' && !(h.onInput_.km34)) {
  4078.  
  4079. const f = h.onInput_;
  4080. const g = ump3.get(f) || function () {
  4081. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4082. }
  4083. ump3.set(f, g);
  4084. g.km34 = 1;
  4085. h.onInput_ = g;
  4086.  
  4087. }
  4088. if (typeof h.trigger_ === 'function' && !(h.trigger_.km34)) {
  4089.  
  4090. const f = h.trigger_;
  4091. const g = ump3.get(f) || function (a) {
  4092. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4093. }
  4094. ump3.set(f, g);
  4095. g.km34 = 1;
  4096. h.trigger_ = g;
  4097.  
  4098. }
  4099.  
  4100. if (typeof h.requestData_ === 'function' && !(h.requestData_.km34)) {
  4101.  
  4102. const f = h.requestData_;
  4103. const g = ump3.get(f) || function (a) {
  4104. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4105. }
  4106. ump3.set(f, g);
  4107. g.km34 = 1;
  4108. h.requestData_ = g;
  4109.  
  4110. }
  4111.  
  4112. if (typeof h.onLoadReloadContinuation_ === 'function' && !(h.onLoadReloadContinuation_.km34)) {
  4113.  
  4114. const f = h.onLoadReloadContinuation_;
  4115. const g = ump3.get(f) || function (a, b) {
  4116. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4117. }
  4118. ump3.set(f, g);
  4119. g.km34 = 1;
  4120. h.onLoadReloadContinuation_ = g;
  4121.  
  4122. }
  4123.  
  4124. if (typeof h.onLoadIncrementalContinuation_ === 'function' && !(h.onLoadIncrementalContinuation_.km34)) {
  4125.  
  4126. const f = h.onLoadIncrementalContinuation_;
  4127. const g = ump3.get(f) || function (a, b) {
  4128. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4129. }
  4130. ump3.set(f, g);
  4131. g.km34 = 1;
  4132. h.onLoadIncrementalContinuation_ = g;
  4133.  
  4134. }
  4135.  
  4136. if (typeof h.onLoadSeekContinuation_ === 'function' && !(h.onLoadSeekContinuation_.km34)) {
  4137.  
  4138. const f = h.onLoadSeekContinuation_;
  4139. const g = ump3.get(f) || function (a, b) {
  4140. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4141. }
  4142. ump3.set(f, g);
  4143. g.km34 = 1;
  4144. h.onLoadSeekContinuation_ = g;
  4145.  
  4146. }
  4147. if (typeof h.onLoadReplayContinuation_ === 'function' && !(h.onLoadReplayContinuation_.km34)) {
  4148.  
  4149. const f = h.onLoadReplayContinuation_;
  4150. const g = ump3.get(f) || function (a, b) {
  4151. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4152. }
  4153. ump3.set(f, g);
  4154. g.km34 = 1;
  4155. h.onLoadReplayContinuation_ = g;
  4156.  
  4157. }
  4158. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onNavigate_ === 'function' && !(h.onNavigate_.km34)) {
  4159.  
  4160. const f = h.onNavigate_;
  4161. const g = ump3.get(f) || function (a) {
  4162. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4163. }
  4164. ump3.set(f, g);
  4165. g.km34 = 1;
  4166. h.onNavigate_ = g;
  4167.  
  4168. }
  4169.  
  4170. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.ytRendererBehaviorDataObserver_ === 'function' && !(h.ytRendererBehaviorDataObserver_.km34)) {
  4171.  
  4172. const f = h.ytRendererBehaviorDataObserver_;
  4173. const g = ump3.get(f) || function () {
  4174. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4175. }
  4176. ump3.set(f, g);
  4177. g.km34 = 1;
  4178. h.ytRendererBehaviorDataObserver_ = g;
  4179.  
  4180. }
  4181.  
  4182. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.ytRendererBehaviorTargetIdObserver_ === 'function' && !(h.ytRendererBehaviorTargetIdObserver_.km34)) {
  4183.  
  4184. const f = h.ytRendererBehaviorTargetIdObserver_;
  4185. const g = ump3.get(f) || function () {
  4186. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4187. }
  4188. ump3.set(f, g);
  4189. g.km34 = 1;
  4190. h.ytRendererBehaviorTargetIdObserver_ = g;
  4191.  
  4192. }
  4193.  
  4194. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.unregisterRenderer_ === 'function' && !(h.unregisterRenderer_.km34)) {
  4195.  
  4196. const f = h.unregisterRenderer_;
  4197. const g = ump3.get(f) || function (a) {
  4198. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4199. }
  4200. ump3.set(f, g);
  4201. g.km34 = 1;
  4202. h.unregisterRenderer_ = g;
  4203.  
  4204. }
  4205.  
  4206. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.textChanged_ === 'function' && !(h.textChanged_.km34)) {
  4207.  
  4208. const f = h.textChanged_;
  4209. const g = ump3.get(f) || function (a) {
  4210. if (void 0 !== this.isAttached) {
  4211. const hostElement = this.hostElement;
  4212. if (!(hostElement instanceof Node) || hostElement.nodeName === 'NOSCRIPT') {
  4213. return;
  4214. }
  4215. }
  4216. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4217. }
  4218. ump3.set(f, g);
  4219. g.km34 = 1;
  4220. h.textChanged_ = g;
  4221.  
  4222. }
  4223.  
  4224.  
  4225.  
  4226. /**
  4227. *
  4228. * Neglect following
  4229. *
  4230. * h.onYtAction_
  4231. * h.startLoadingWatch [ buggy for yt-player-updated ]
  4232. * h.deferRenderStamperBinding_
  4233. *
  4234. * h.stampDomArray_
  4235. * h.stampDomArraySplices_
  4236. *
  4237. */
  4238.  
  4239.  
  4240. // RP.prototype.searchChanged_ = RP.prototype.searchChanged_;
  4241. // RP.prototype.skinToneChanged_ = RP.prototype.skinToneChanged_;
  4242. // RP.prototype.onEmojiHover_ = RP.prototype.onEmojiHover_;
  4243. // RP.prototype.onSelectCategory_ = RP.prototype.onSelectCategory_;
  4244. // RP.prototype.onShowEmojiVariantSelector = RP.prototype.onShowEmojiVariantSelector;
  4245. // RP.prototype.updateCategoriesAndPlaceholder_ = RP.prototype.updateCategoriesAndPlaceholder_;
  4246.  
  4247. if (typeof h.searchChanged_ === 'function' && !(h.searchChanged_.km34)) {
  4248.  
  4249. const f = h.searchChanged_;
  4250. const g = ump3.get(f) || function () {
  4251. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4252. }
  4253. ump3.set(f, g);
  4254. g.km34 = 1;
  4255. h.searchChanged_ = g;
  4256.  
  4257. }
  4258.  
  4259. if (typeof h.skinToneChanged_ === 'function' && !(h.skinToneChanged_.km34)) {
  4260.  
  4261. const f = h.skinToneChanged_;
  4262. const g = ump3.get(f) || function (a) {
  4263. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4264. }
  4265. ump3.set(f, g);
  4266. g.km34 = 1;
  4267. h.skinToneChanged_ = g;
  4268.  
  4269. }
  4270.  
  4271. if (typeof h.onEmojiHover_ === 'function' && !(h.onEmojiHover_.km34)) {
  4272.  
  4273. const f = h.onEmojiHover_;
  4274. const g = ump3.get(f) || function (a) {
  4275. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4276. }
  4277. ump3.set(f, g);
  4278. g.km34 = 1;
  4279. h.onEmojiHover_ = g;
  4280.  
  4281. }
  4282.  
  4283. if (typeof h.onSelectCategory_ === 'function' && !(h.onSelectCategory_.km34)) {
  4284.  
  4285. const f = h.onSelectCategory_;
  4286. const g = ump3.get(f) || function (a) {
  4287. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4288. }
  4289. ump3.set(f, g);
  4290. g.km34 = 1;
  4291. h.onSelectCategory_ = g;
  4292.  
  4293. }
  4294.  
  4295. if (typeof h.onShowEmojiVariantSelector === 'function' && !(h.onShowEmojiVariantSelector.km34)) {
  4296.  
  4297. const f = h.onShowEmojiVariantSelector;
  4298. const g = ump3.get(f) || function (a) {
  4299. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4300. }
  4301. ump3.set(f, g);
  4302. g.km34 = 1;
  4303. h.onShowEmojiVariantSelector = g;
  4304.  
  4305. }
  4306.  
  4307. if (typeof h.updateCategoriesAndPlaceholder_ === 'function' && !(h.updateCategoriesAndPlaceholder_.km34)) {
  4308.  
  4309. const f = h.updateCategoriesAndPlaceholder_;
  4310. const g = ump3.get(f) || function () {
  4311. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4312. }
  4313. ump3.set(f, g);
  4314. g.km34 = 1;
  4315. h.updateCategoriesAndPlaceholder_ = g;
  4316.  
  4317. }
  4318.  
  4319. if (typeof h.watchPageActiveChanged_ === 'function' && !(h.watchPageActiveChanged_.km34)) {
  4320.  
  4321. const f = h.watchPageActiveChanged_;
  4322. const g = ump3.get(f) || function () {
  4323. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4324. }
  4325. ump3.set(f, g);
  4326. g.km34 = 1;
  4327. h.watchPageActiveChanged_ = g;
  4328.  
  4329. }
  4330.  
  4331. if (typeof h.activate_ === 'function' && !(h.activate_.km34)) {
  4332.  
  4333. const f = h.activate_;
  4334. const g = ump3.get(f) || function () {
  4335. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4336. }
  4337. ump3.set(f, g);
  4338. g.km34 = 1;
  4339. h.activate_ = g;
  4340.  
  4341. }
  4342. if (typeof h.onYtPlaylistDataUpdated_ === 'function' && !(h.onYtPlaylistDataUpdated_.km34)) {
  4343.  
  4344. const f = h.onYtPlaylistDataUpdated_;
  4345. const g = ump3.get(f) || function () {
  4346. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4347. }
  4348. ump3.set(f, g);
  4349. g.km34 = 1;
  4350. h.onYtPlaylistDataUpdated_ = g;
  4351.  
  4352. }
  4353.  
  4354. FIX_stampDomArray_stableList && fixStampDomArrayStableList(h);
  4355. const ENABLE_weakenStampReferencesQ = ENABLE_weakenStampReferences && typeof DocumentTimeline !== 'undefined' && typeof WeakRef !== 'undefined';
  4356. ENABLE_weakenStampReferencesQ && weakenStampReferences(h);
  4357.  
  4358.  
  4359. /**
  4360. *
  4361. * Neglect following
  4362. *
  4363. * h.rendererStamperObserver_
  4364. * h.rendererStamperApplyChangeRecord_
  4365. * h.flushRenderStamperComponentBindings_
  4366. * h.forwardRendererStamperChanges_
  4367. *
  4368. */
  4369.  
  4370. if (typeof h.tryRenderChunk_ === 'function' && !(h.tryRenderChunk_.km34)) {
  4371.  
  4372. const f = h.tryRenderChunk_;
  4373. const g = ump3.get(f) || function () {
  4374. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4375. }
  4376. ump3.set(f, g);
  4377. g.km34 = 1;
  4378. h.tryRenderChunk_ = g;
  4379.  
  4380. }
  4381.  
  4382.  
  4383. if (typeof h.renderChunk_ === 'function' && !(h.renderChunk_.km34)) {
  4384.  
  4385. const f = h.renderChunk_;
  4386. const g = ump3.get(f) || function () {
  4387. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4388. }
  4389. ump3.set(f, g);
  4390. g.km34 = 1;
  4391. h.renderChunk_ = g;
  4392.  
  4393. }
  4394.  
  4395. if (typeof h.deepLazyListObserver_ === 'function' && !(h.deepLazyListObserver_.km34)) {
  4396.  
  4397. const f = h.deepLazyListObserver_;
  4398. const g = ump3.get(f) || function () {
  4399. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4400. }
  4401. ump3.set(f, g);
  4402. g.km34 = 1;
  4403. h.deepLazyListObserver_ = g;
  4404.  
  4405. }
  4406.  
  4407. if (typeof h.onItemsUpdated_ === 'function' && !(h.onItemsUpdated_.km34)) {
  4408.  
  4409. const f = h.onItemsUpdated_;
  4410. const g = ump3.get(f) || function () {
  4411. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4412. }
  4413. ump3.set(f, g);
  4414. g.km34 = 1;
  4415. h.onItemsUpdated_ = g;
  4416.  
  4417. }
  4418.  
  4419. if (typeof h.requestRenderChunk_ === 'function' && !(h.requestRenderChunk_.km34)) {
  4420.  
  4421. const f = h.requestRenderChunk_;
  4422. const g = ump3.get(f) || function () {
  4423. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  4424. }
  4425. ump3.set(f, g);
  4426. g.km34 = 1;
  4427. h.requestRenderChunk_ = g;
  4428.  
  4429. }
  4430.  
  4431. /**
  4432. *
  4433. * Neglect following
  4434. *
  4435. * h.dataChanged_ [ buggy for page swtiching ]
  4436. *
  4437. * h.updateChangeRecord_ [ see https://github.com/cyfung1031/userscript-supports/issues/20 ]
  4438. *
  4439. * h.cancelPendingTasks_
  4440. * h.fillRange_
  4441. * h.addTextNodes_
  4442. * h.updateText_
  4443. * h.stampTypeChanged_
  4444. *
  4445. */
  4446.  
  4447.  
  4448. }
  4449.  
  4450. const keyStConnectedCallback = Symbol(); // avoid copying the value
  4451.  
  4452. // const keyStDisconnectedCallback = Symbol(); // avoid copying the value
  4453. const cmf = new WeakMap();
  4454. const dmf = new WeakMap();
  4455.  
  4456. const gvGenerator = (nv) => {
  4457. return function () {
  4458. const cnt = insp(this);
  4459. const hostElement = cnt.hostElement || 0;
  4460. const dollar = hostElement ? (this.$ || indr(this)) : 0;
  4461. let p = (hostElement instanceof HTMLElement) && (dollar || !this.is);
  4462. if (p && (!dollar && !this.is)) {
  4463. const nodeName = hostElement.nodeName;
  4464. if (typeof nodeName !== 'string') {
  4465. // just in case
  4466. } else if (nodeName.startsWith("DOM-")) {
  4467. // dom-if, dom-repeat, etc
  4468. } else {
  4469. // yt element - new model, yt-xxxx, anixxxxxx
  4470. p = false;
  4471. }
  4472. }
  4473. if (p) {
  4474. if (typeof cnt.markDirty === 'function') {
  4475. // the yt element might call markDirty (occasionally)
  4476. p = false;
  4477. } else if (this.is === 'ytd-engagement-panel-section-list-renderer') {
  4478. // see https://github.com/cyfung1031/userscript-supports/issues/20
  4479. p = false;
  4480. }
  4481. }
  4482. if (p) {
  4483.  
  4484. // << dom-repeat & dom-if >>
  4485.  
  4486. // sequence on the same instance
  4487. this[qm57] = (this[qm57] || Promise.resolve()).then(() => nv.apply(this, arguments)).catch(console.log);
  4488. } else {
  4489. nv.apply(this, arguments);
  4490. }
  4491. };
  4492. }
  4493.  
  4494. // const assignedHolderWS = new WeakSet();
  4495.  
  4496. const setupWeakRef = (h) => {
  4497.  
  4498.  
  4499. }
  4500.  
  4501.  
  4502. let nativeHTMLElement = window.HTMLElement;
  4503.  
  4504. try {
  4505.  
  4506. const q = document.createElement('template');
  4507. q.innerHTML = '<ytz-null361></ytz-null361>';
  4508. nativeHTMLElement = q.content.firstChild.constructor
  4509.  
  4510. } catch (e) { }
  4511.  
  4512. if (!nativeHTMLElement.prototype.connectedCallback) {
  4513. nativeHTMLElement.prototype.connectedCallback79 = nativeHTMLElement.prototype.connectedCallback;
  4514. nativeHTMLElement.prototype.connectedCallback = function () {
  4515. let r;
  4516. if (this.connectedCallback79) r = this.connectedCallback79.apply(this, arguments);
  4517. return r;
  4518. }
  4519. }
  4520.  
  4521. ENABLE_discreteTasking && Object.defineProperty(Object.prototype, 'connectedCallback', {
  4522. get() {
  4523. const f = this[keyStConnectedCallback];
  4524. if (this.is) {
  4525. setupDiscreteTasks(this, true);
  4526. if (f) this.ky36 = 1;
  4527. }
  4528. return f;
  4529. },
  4530. set(nv) {
  4531. let gv;
  4532. if (typeof nv === 'function') {
  4533.  
  4534. gv = cmf.get(nv) || gvGenerator(nv);
  4535. if (gv !== nv) {
  4536. cmf.set(nv, gv);
  4537. cmf.set(gv, gv);
  4538. dmf.set(gv, nv);
  4539. }
  4540.  
  4541. } else {
  4542. gv = nv;
  4543. }
  4544. this[keyStConnectedCallback] = gv; // proto or object
  4545. if (this.is) {
  4546. setupDiscreteTasks(this);
  4547. }
  4548. return true;
  4549. },
  4550. enumerable: false,
  4551. configurable: true
  4552.  
  4553. });
  4554.  
  4555. const pLoad = new Promise(resolve => {
  4556. if (document.readyState !== 'loading') {
  4557. resolve();
  4558. } else {
  4559. window.addEventListener("DOMContentLoaded", resolve, false);
  4560. }
  4561. });
  4562.  
  4563. if (FIX_fix_requestIdleCallback_timing && !window.requestIdleCallback471 && typeof window.requestIdleCallback === 'function') {
  4564. window.requestIdleCallback471 = window.requestIdleCallback;
  4565. window.requestIdleCallback = function (f, ...args) {
  4566. return (this || window).requestIdleCallback471(async function () {
  4567. await pLoad.then();
  4568. // await new Promise(nextBrowserTick_);
  4569. f.call(this, ...arguments)
  4570. }, ...args);
  4571. }
  4572. }
  4573.  
  4574. pLoad.then(() => {
  4575.  
  4576. let nonce = document.querySelector('style[nonce]');
  4577. nonce = nonce ? nonce.getAttribute('nonce') : null;
  4578. const st = document.createElement('style');
  4579. if (typeof nonce === 'string') st.setAttribute('nonce', nonce);
  4580. st.textContent = "none-element-k47{order:0}";
  4581. st.addEventListener('load', () => {
  4582. pf31.resolve();
  4583. p59 = 1;
  4584. }, false);
  4585. (document.body || document.head || document.documentElement).appendChild(st);
  4586.  
  4587. });
  4588.  
  4589. const prepareLogs = [];
  4590.  
  4591. const skipAdsDetection = new Set(['/robots.txt', '/live_chat', '/live_chat_replay']);
  4592.  
  4593. let winError00 = window.onerror;
  4594.  
  4595. let fix_error_many_stack_state = !FIX_error_many_stack ? 0 : skipAdsDetection.has(location.pathname) ? 2 : 1;
  4596.  
  4597. if (!JSON || !('parse' in JSON)) fix_error_many_stack_state = 0;
  4598.  
  4599. ; FIX_Iframe_NULL_SRC && !isChatRoomURL && typeof kagi === 'undefined' && (() => {
  4600.  
  4601. const emptyBlobUrl = URL.createObjectURL(new Blob([], { type: 'text/html' }));
  4602. const lcOpt = { sensitivity: 'base' };
  4603. document.createElement24 = document.createElement;
  4604. document.createElement = function (t) {
  4605. if (typeof t === 'string' && t.length === 6) {
  4606. if (t.localeCompare('iframe', undefined, lcOpt) === 0) {
  4607. const p = this.createElement24(t);
  4608. try {
  4609. const stack = new Error().stack;
  4610. const isSearchbox = stack.includes('initializeSearchbox'); // see https://greatest.deepsurf.us/scripts/473972-youtube-js-engine-tamer/discussions/217084
  4611. if (!isSearchbox) {
  4612. p.src = emptyBlobUrl; // avoid iframe is appended to DOM without any url
  4613. }
  4614. } catch (e) { }
  4615. return p;
  4616. }
  4617. }
  4618. return this.createElement24.apply(this, arguments);
  4619. };
  4620.  
  4621. })();
  4622.  
  4623. ; fix_error_many_stack_state === 1 && (() => {
  4624.  
  4625.  
  4626. let p1 = winError00;
  4627.  
  4628. let stackNeedleDetails = null;
  4629.  
  4630. Object.defineProperty(Object.prototype, 'matchAll', {
  4631. get() {
  4632. stackNeedleDetails = this;
  4633. return true;
  4634. },
  4635. enumerable: true,
  4636. configurable: true
  4637. });
  4638.  
  4639. try {
  4640. JSON.parse("{}");
  4641. } catch (e) {
  4642. console.warn(e)
  4643. fix_error_many_stack_state = 0;
  4644. }
  4645.  
  4646. delete Object.prototype['matchAll'];
  4647.  
  4648. let p2 = window.onerror;
  4649.  
  4650. window.onerror = p1;
  4651.  
  4652. if (fix_error_many_stack_state === 0) return;
  4653.  
  4654. if (stackNeedleDetails) {
  4655. JSON.parse.stackNeedleDetails = stackNeedleDetails;
  4656. stackNeedleDetails.matchAll = true;
  4657. }
  4658.  
  4659. if (p1 === p2) return (fix_error_many_stack_state = 0);
  4660.  
  4661. // p1!==p2
  4662. fix_error_many_stack_state = !stackNeedleDetails ? 4 : 3;
  4663.  
  4664. })();
  4665.  
  4666. ; fix_error_many_stack_state === 2 && (() => {
  4667.  
  4668.  
  4669. let p1 = winError00;
  4670.  
  4671. let objectPrune = null;
  4672. let stackNeedleDetails = null;
  4673.  
  4674. Object.defineProperty(Function.prototype, 'findOwner', {
  4675. get() {
  4676. objectPrune = this;
  4677. return this._findOwner;
  4678. },
  4679. set(nv) {
  4680. this._findOwner = nv;
  4681. return true;
  4682. },
  4683. enumerable: true,
  4684. configurable: true
  4685. });
  4686.  
  4687. Object.defineProperty(Object.prototype, 'matchAll', {
  4688. get() {
  4689. stackNeedleDetails = this;
  4690. return true;
  4691. },
  4692. enumerable: true,
  4693. configurable: true
  4694. });
  4695.  
  4696. try {
  4697. JSON.parse("{}");
  4698. } catch (e) {
  4699. console.warn(e)
  4700. fix_error_many_stack_state = 0;
  4701. }
  4702.  
  4703. delete Function.prototype['findOwner'];
  4704. delete Object.prototype['matchAll'];
  4705.  
  4706. let p2 = window.onerror;
  4707.  
  4708. if (p1 !== p2) return (fix_error_many_stack_state = 4); // p1 != p2
  4709.  
  4710. if (fix_error_many_stack_state == 0) return;
  4711.  
  4712. // the following will only execute when Brave's scriptlets.js is executed.
  4713.  
  4714. prepareLogs.push("fix_error_many_stack_state NB")
  4715.  
  4716. if (stackNeedleDetails) {
  4717. stackNeedleDetails.pattern = null;
  4718. stackNeedleDetails.re = null;
  4719. stackNeedleDetails.expect = null;
  4720. stackNeedleDetails.matchAll = true;
  4721. }
  4722.  
  4723. if (objectPrune) {
  4724. objectPrune.findOwner = objectPrune.mustProcess = objectPrune.logJson = () => { }
  4725. delete objectPrune._findOwner;
  4726. }
  4727.  
  4728. fix_error_many_stack_state = 3;
  4729. JSON.parse.stackNeedleDetails = stackNeedleDetails;
  4730. JSON.parse.objectPrune = objectPrune;
  4731.  
  4732. })();
  4733.  
  4734. ; fix_error_many_stack_state === 3 && (() => {
  4735.  
  4736.  
  4737. let p1 = winError00;
  4738.  
  4739. try {
  4740. JSON.parse("{}");
  4741. } catch (e) {
  4742. console.warn(e)
  4743. fix_error_many_stack_state = 0;
  4744. }
  4745.  
  4746. let p2 = window.onerror;
  4747.  
  4748. if (p1 === p2) return;
  4749.  
  4750. window.onerror = p1;
  4751.  
  4752. if (fix_error_many_stack_state === 0) return;
  4753.  
  4754. fix_error_many_stack_state = 4; // p1 != p2
  4755.  
  4756.  
  4757. })();
  4758.  
  4759. fix_error_many_stack_state === 4 && (() => {
  4760.  
  4761. // the following will only execute when Brave's scriptlets.js is executed.
  4762.  
  4763. prepareLogs.push("fix_error_many_stack_state AB")
  4764.  
  4765. JSON.parseProxy = JSON.parse;
  4766.  
  4767. JSON.parse = ((parse) => {
  4768.  
  4769. parse = parse.bind(JSON); // get a new instance of the current JSON.parse
  4770. return function (text, reviver) {
  4771. const onerror = window.onerror;
  4772. window.onerror = null;
  4773. let r;
  4774. try {
  4775. r = parse(...arguments);
  4776. } catch (e) {
  4777. r = e;
  4778. }
  4779. window.onerror = onerror;
  4780. if (r instanceof Error) {
  4781. throw r;
  4782. }
  4783. return r;
  4784. }
  4785.  
  4786. })(JSON.parse);
  4787.  
  4788.  
  4789. })();
  4790.  
  4791.  
  4792. // << if FIX_yt_player >>
  4793.  
  4794. // credit to @nopeless (https://greatest.deepsurf.us/scripts/471489-youtube-player-perf/)
  4795. const PERF_471489_ = true;
  4796. // PERF_471489_ is not exactly the same to Youtube Player perf v0.7
  4797. // This script uses a much gentle way to tamer the JS engine instead.
  4798.  
  4799. // << end >>
  4800.  
  4801. const steppingScaleN = 200; // transform: scaleX(k/N); 0<k<N
  4802.  
  4803.  
  4804.  
  4805. const nilFn = () => { };
  4806.  
  4807. let isMainWindow = false;
  4808. try {
  4809. isMainWindow = window.document === window.top.document
  4810. } catch (e) { }
  4811.  
  4812. let NO_PRELOAD_GENERATE_204_BYPASS = NO_PRELOAD_GENERATE_204 ? false : true;
  4813. let headLinkCollection = null;
  4814.  
  4815.  
  4816. // const assertor = (f) => f() || console.assert(false, `${f}`);
  4817.  
  4818. const fnIntegrity = (f, d) => {
  4819. if (!f || typeof f !== 'function') {
  4820. console.warn('f is not a function', f);
  4821. return;
  4822. }
  4823. let p = `${f}`, s = 0, j = -1, w = 0;
  4824. for (let i = 0, l = p.length; i < l; i++) {
  4825. const t = p[i];
  4826. if (((t >= 'a' && t <= 'z') || (t >= 'A' && t <= 'Z'))) {
  4827. if (j < i - 1) w++;
  4828. j = i;
  4829. } else {
  4830. s++;
  4831. }
  4832. }
  4833. let itz = `${f.length}.${s}.${w}`;
  4834. if (!d) {
  4835. return itz;
  4836. } else {
  4837. return itz === d;
  4838. }
  4839. };
  4840.  
  4841. const getZqOu = (_yt_player) => {
  4842.  
  4843. const w = 'ZqOu';
  4844.  
  4845. let arr = [];
  4846.  
  4847. for (const [k, v] of Object.entries(_yt_player)) {
  4848.  
  4849. const p = typeof v === 'function' ? v.prototype : 0;
  4850. if (p
  4851. && typeof p.start === 'function' && p.start.length === 0 // Ou
  4852. && typeof p.isActive === 'function' && p.isActive.length === 0
  4853. && typeof p.stop === 'function' && p.stop.length === 0
  4854. && !p.isComplete && !p.getStatus && !p.getResponseHeader && !p.getLastError
  4855. && !p.send && !p.abort
  4856. && !p.sample && !p.initialize && !p.fail && !p.getName
  4857. // && !p.dispose && !p.isDisposed
  4858.  
  4859. ) {
  4860. arr = addProtoToArr(_yt_player, k, arr) || arr;
  4861.  
  4862.  
  4863. }
  4864.  
  4865. }
  4866.  
  4867. if (arr.length === 0) {
  4868.  
  4869. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  4870. } else {
  4871.  
  4872. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  4873. return arr[0];
  4874. }
  4875.  
  4876. }
  4877.  
  4878. const getZqQu = (_yt_player) => {
  4879.  
  4880. const w = 'ZqQu';
  4881.  
  4882. let arr = [];
  4883.  
  4884.  
  4885. for (const [k, v] of Object.entries(_yt_player)) {
  4886.  
  4887. const p = typeof v === 'function' ? v.prototype : 0;
  4888. if (p
  4889. && typeof p.start === 'function' && p.start.length === 1 // Qu
  4890. && typeof p.isActive === 'function' && p.isActive.length === 0
  4891. && typeof p.stop === 'function' && p.stop.length === 0
  4892. && !p.isComplete && !p.getStatus && !p.getResponseHeader && !p.getLastError
  4893. && !p.send && !p.abort
  4894. && !p.sample && !p.initialize && !p.fail && !p.getName
  4895. // && !p.dispose && !p.isDisposed
  4896.  
  4897. ) {
  4898. arr = addProtoToArr(_yt_player, k, arr) || arr;
  4899.  
  4900.  
  4901. }
  4902.  
  4903. }
  4904.  
  4905. if (arr.length === 0) {
  4906.  
  4907. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  4908. } else {
  4909.  
  4910. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  4911. return arr[0];
  4912. }
  4913.  
  4914. }
  4915.  
  4916.  
  4917. const getVG = (_yt_player) => {
  4918. const w = 'VG';
  4919.  
  4920. let arr = [];
  4921.  
  4922. for (const [k, v] of Object.entries(_yt_player)) {
  4923.  
  4924. const p = typeof v === 'function' ? v.prototype : 0;
  4925. if (p
  4926. && typeof p.show === 'function' && p.show.length === 1
  4927. && typeof p.hide === 'function' && p.hide.length === 0
  4928. && typeof p.stop === 'function' && p.stop.length === 0) {
  4929.  
  4930. arr = addProtoToArr(_yt_player, k, arr) || arr;
  4931.  
  4932. }
  4933.  
  4934. }
  4935.  
  4936.  
  4937. if (arr.length === 0) {
  4938.  
  4939. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  4940. } else {
  4941.  
  4942. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  4943. return arr[0];
  4944. }
  4945.  
  4946.  
  4947.  
  4948. }
  4949.  
  4950.  
  4951. const getzo = (_yt_player) => {
  4952. const w = 'zo';
  4953.  
  4954. let arr = [];
  4955.  
  4956. for (const [k, v] of Object.entries(_yt_player)) {
  4957.  
  4958. if (
  4959. typeof v === 'function' && v.length === 3 && k.length < 3
  4960. ) {
  4961. const vt = `${v}`;
  4962. if (vt.length >= 21 && vt.includes(".style[")) {
  4963. if (/\((\w{1,3}),(\w{1,3}),(\w{1,3})\)\{[\s\S]*\1\.style\[\2\]=\3\W/.test(vt)) {
  4964. arr.push(k);
  4965. } else {
  4966. console.warn('[yt-js-engine-tamer] unexpected zo::vt', vt);
  4967. }
  4968. }
  4969. }
  4970.  
  4971. }
  4972.  
  4973. if (arr.length === 0) {
  4974.  
  4975. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  4976. } else {
  4977.  
  4978. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  4979. return arr[0];
  4980. }
  4981.  
  4982. }
  4983.  
  4984. const addProtoToArr = (parent, key, arr) => {
  4985.  
  4986.  
  4987. let isChildProto = false;
  4988. for (const sr of arr) {
  4989. if (parent[key].prototype instanceof parent[sr]) {
  4990. isChildProto = true;
  4991. break;
  4992. }
  4993. }
  4994.  
  4995. if (isChildProto) return;
  4996.  
  4997. arr = arr.filter(sr => {
  4998. if (parent[sr].prototype instanceof parent[key]) {
  4999. return false;
  5000. }
  5001. return true;
  5002. });
  5003.  
  5004. arr.push(key);
  5005.  
  5006. return arr;
  5007.  
  5008.  
  5009. }
  5010.  
  5011. const getuG = (_yt_player) => {
  5012.  
  5013. const w = 'uG';
  5014.  
  5015. let arr = [];
  5016.  
  5017. for (const [k, v] of Object.entries(_yt_player)) {
  5018.  
  5019.  
  5020. const p = typeof v === 'function' ? v.prototype : 0;
  5021.  
  5022. if (p
  5023. && typeof p.createElement === 'function' && p.createElement.length === 2
  5024. && typeof p.detach === 'function' && p.detach.length === 0
  5025. && typeof p.update === 'function' && p.update.length === 1
  5026. && typeof p.updateValue === 'function' && p.updateValue.length === 2
  5027. ) {
  5028.  
  5029. arr = addProtoToArr(_yt_player, k, arr) || arr;
  5030.  
  5031. }
  5032.  
  5033. }
  5034.  
  5035.  
  5036.  
  5037.  
  5038.  
  5039. if (arr.length === 0) {
  5040.  
  5041. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  5042. } else {
  5043.  
  5044. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  5045. return arr[0];
  5046. }
  5047.  
  5048. }
  5049.  
  5050.  
  5051. const getQT = (_yt_player) => {
  5052. const w = 'QT';
  5053.  
  5054. let arr = [];
  5055. let brr = new Map();
  5056.  
  5057. for (const [k, v] of Object.entries(_yt_player)) {
  5058.  
  5059. const p = typeof v === 'function' ? v.prototype : 0;
  5060. if (p) {
  5061. let q = 0;
  5062. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 7) q += 400;
  5063. else if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 8) q += 300;
  5064. else if (typeof p.handleGlobalKeyUp === 'function') q += 200;
  5065.  
  5066. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 0) q -= 600; // avoid SV
  5067.  
  5068. if (q < 200) continue; // p.handleGlobalKeyUp must be available
  5069.  
  5070. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 8) q += 80;
  5071. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 7) q += 30;
  5072. if (typeof p.step === 'function' && p.step.length === 1) q += 10;
  5073. if (typeof p.step === 'function' && p.step.length !== 1) q += 5;
  5074.  
  5075.  
  5076. // differentiate QT and DX
  5077.  
  5078. q += 280;
  5079. if (typeof p.cueVideoByPlayerVars === 'function') q += 4;
  5080. if (typeof p.loadVideoByPlayerVars === 'function') q += 4;
  5081. if (typeof p.preloadVideoByPlayerVars === 'function') q += 4;
  5082. if (typeof p.seekBy === 'function') q += 4;
  5083. if (typeof p.seekTo === 'function') q += 4;
  5084. if (typeof p.getStoryboardFormat === 'function') q += 4;
  5085. if (typeof p.getDuration === 'function') q += 4;
  5086. if (typeof p.loadModule === 'function') q += 4;
  5087. if (typeof p.unloadModule === 'function') q += 4;
  5088. if (typeof p.getOption === 'function') q += 4;
  5089. if (typeof p.getOptions === 'function') q += 4;
  5090. if (typeof p.setOption === 'function') q += 4;
  5091. if (typeof p.addCueRange === 'function') q += 4;
  5092. if (typeof p.getDebugText === 'function') q += 4;
  5093. if (typeof p.getCurrentBroadcastId === 'function') q += 4;
  5094. if (typeof p.setSizeStyle === 'function') q += 4;
  5095. if (typeof p.showControls === 'function') q += 4;
  5096. if (typeof p.hideControls === 'function') q += 4;
  5097. if (typeof p.getVideoContentRect === 'function') q += 4;
  5098. if (typeof p.toggleFullscreen === 'function') q += 4;
  5099. if (typeof p.isFullscreen === 'function') q += 4;
  5100. if (typeof p.cancelPlayback === 'function') q += 4;
  5101. if (typeof p.getProgressState === 'function') q += 4;
  5102. if (typeof p.isInline === 'function') q += 4;
  5103. if (typeof p.setInline === 'function') q += 4;
  5104. if (typeof p.toggleSubtitles === 'function') q += 4;
  5105. if (typeof p.getPlayerSize === 'function') q += 4;
  5106. if (typeof p.wakeUpControls === 'function') q += 4;
  5107. if (typeof p.setCenterCrop === 'function') q += 4;
  5108. if (typeof p.getLoopVideo === 'function') q += 4;
  5109. if (typeof p.setLoopVideo === 'function') q += 4;
  5110.  
  5111.  
  5112. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  5113.  
  5114. if (q > 0) brr.set(k, q);
  5115.  
  5116. }
  5117.  
  5118. }
  5119.  
  5120. if (arr.length === 0) {
  5121.  
  5122. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  5123. } else {
  5124.  
  5125. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  5126.  
  5127. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  5128.  
  5129. if (arr.length > 2) console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  5130. return arr[0][0];
  5131. }
  5132.  
  5133.  
  5134.  
  5135. }
  5136.  
  5137.  
  5138.  
  5139. const getSV = (_yt_player) => {
  5140. const w = 'SV';
  5141.  
  5142. let arr = [];
  5143. let brr = new Map();
  5144.  
  5145. for (const [k, v] of Object.entries(_yt_player)) {
  5146.  
  5147. const p = typeof v === 'function' ? v.prototype : 0;
  5148. if (p) {
  5149. let q = 0;
  5150. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 7) q += 400;
  5151. else if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 8) q += 300;
  5152. else if (typeof p.handleGlobalKeyUp === 'function') q += 200;
  5153.  
  5154. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 0) q += 600; // SV
  5155.  
  5156. if (q < 200) continue; // p.handleGlobalKeyUp must be available
  5157.  
  5158. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 8) q += 80;
  5159. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 7) q += 30;
  5160. if (typeof p.step === 'function' && p.step.length === 1) q += 10;
  5161. if (typeof p.step === 'function' && p.step.length !== 1) q += 5;
  5162.  
  5163.  
  5164. // differentiate QT and DX
  5165.  
  5166.  
  5167. q += 280;
  5168.  
  5169. if (typeof p.cueVideoByPlayerVars === 'function') q -= 4;
  5170. if (typeof p.loadVideoByPlayerVars === 'function') q -= 4;
  5171. if (typeof p.preloadVideoByPlayerVars === 'function') q -= 4;
  5172. if (typeof p.seekBy === 'function') q -= 4;
  5173. if (typeof p.seekTo === 'function') q -= 4;
  5174. if (typeof p.getStoryboardFormat === 'function') q -= 4;
  5175. if (typeof p.getDuration === 'function') q -= 4;
  5176. if (typeof p.loadModule === 'function') q -= 4;
  5177. if (typeof p.unloadModule === 'function') q -= 4;
  5178. if (typeof p.getOption === 'function') q -= 4;
  5179. if (typeof p.getOptions === 'function') q -= 4;
  5180. if (typeof p.setOption === 'function') q -= 4;
  5181. if (typeof p.addCueRange === 'function') q -= 4;
  5182. if (typeof p.getDebugText === 'function') q -= 4;
  5183. if (typeof p.getCurrentBroadcastId === 'function') q -= 4;
  5184. if (typeof p.setSizeStyle === 'function') q -= 4;
  5185. if (typeof p.showControls === 'function') q -= 4;
  5186. if (typeof p.hideControls === 'function') q -= 4;
  5187. if (typeof p.getVideoContentRect === 'function') q -= 4;
  5188. if (typeof p.toggleFullscreen === 'function') q -= 4;
  5189. if (typeof p.isFullscreen === 'function') q -= 4;
  5190. if (typeof p.cancelPlayback === 'function') q -= 4;
  5191. if (typeof p.getProgressState === 'function') q -= 4;
  5192. if (typeof p.isInline === 'function') q -= 4;
  5193. if (typeof p.setInline === 'function') q -= 4;
  5194. if (typeof p.toggleSubtitles === 'function') q -= 4;
  5195. if (typeof p.getPlayerSize === 'function') q -= 4;
  5196. if (typeof p.wakeUpControls === 'function') q -= 4;
  5197. if (typeof p.setCenterCrop === 'function') q -= 4;
  5198. if (typeof p.getLoopVideo === 'function') q -= 4;
  5199. if (typeof p.setLoopVideo === 'function') q -= 4;
  5200.  
  5201.  
  5202. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  5203.  
  5204. if (q > 0) brr.set(k, q);
  5205.  
  5206. }
  5207.  
  5208. }
  5209.  
  5210. if (arr.length === 0) {
  5211.  
  5212. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  5213. } else {
  5214.  
  5215. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  5216.  
  5217. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  5218.  
  5219. if (arr.length > 2) console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  5220. return arr[0][0];
  5221. }
  5222.  
  5223.  
  5224.  
  5225. }
  5226.  
  5227.  
  5228.  
  5229.  
  5230. const getDX = (_yt_player) => {
  5231. const w = 'DX';
  5232.  
  5233. let arr = [];
  5234. let brr = new Map();
  5235.  
  5236. for (const [k, v] of Object.entries(_yt_player)) {
  5237.  
  5238. const p = typeof v === 'function' ? v.prototype : 0;
  5239. if (p) {
  5240. let q = 0;
  5241. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 7) q += 400;
  5242. else if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 8) q += 300;
  5243. else if (typeof p.handleGlobalKeyUp === 'function') q += 200;
  5244.  
  5245. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 0) q -= 600; // avoid SV
  5246.  
  5247.  
  5248. if (!(typeof p.init === 'function' && p.init.length === 0)) q -= 300; // init is required
  5249.  
  5250. if (q < 200) continue; // p.handleGlobalKeyUp must be available
  5251.  
  5252. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 8) q += 80;
  5253. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 7) q += 30;
  5254. if (typeof p.step === 'function' && p.step.length === 1) q += 10;
  5255. if (typeof p.step === 'function' && p.step.length !== 1) q += 5;
  5256.  
  5257.  
  5258. // differentiate QT and DX
  5259.  
  5260.  
  5261. q += 280;
  5262.  
  5263. if (typeof p.cueVideoByPlayerVars === 'function') q -= 4;
  5264. if (typeof p.loadVideoByPlayerVars === 'function') q -= 4;
  5265. if (typeof p.preloadVideoByPlayerVars === 'function') q -= 4;
  5266. if (typeof p.seekBy === 'function') q -= 4;
  5267. if (typeof p.seekTo === 'function') q -= 4;
  5268. if (typeof p.getStoryboardFormat === 'function') q -= 4;
  5269. if (typeof p.getDuration === 'function') q -= 4;
  5270. if (typeof p.loadModule === 'function') q -= 4;
  5271. if (typeof p.unloadModule === 'function') q -= 4;
  5272. if (typeof p.getOption === 'function') q -= 4;
  5273. if (typeof p.getOptions === 'function') q -= 4;
  5274. if (typeof p.setOption === 'function') q -= 4;
  5275. if (typeof p.addCueRange === 'function') q -= 4;
  5276. if (typeof p.getDebugText === 'function') q -= 4;
  5277. if (typeof p.getCurrentBroadcastId === 'function') q -= 4;
  5278. if (typeof p.setSizeStyle === 'function') q -= 4;
  5279. if (typeof p.showControls === 'function') q -= 4;
  5280. if (typeof p.hideControls === 'function') q -= 4;
  5281. if (typeof p.getVideoContentRect === 'function') q -= 4;
  5282. if (typeof p.toggleFullscreen === 'function') q -= 4;
  5283. if (typeof p.isFullscreen === 'function') q -= 4;
  5284. if (typeof p.cancelPlayback === 'function') q -= 4;
  5285. if (typeof p.getProgressState === 'function') q -= 4;
  5286. if (typeof p.isInline === 'function') q -= 4;
  5287. if (typeof p.setInline === 'function') q -= 4;
  5288. if (typeof p.toggleSubtitles === 'function') q -= 4;
  5289. if (typeof p.getPlayerSize === 'function') q -= 4;
  5290. if (typeof p.wakeUpControls === 'function') q -= 4;
  5291. if (typeof p.setCenterCrop === 'function') q -= 4;
  5292. if (typeof p.getLoopVideo === 'function') q -= 4;
  5293. if (typeof p.setLoopVideo === 'function') q -= 4;
  5294.  
  5295.  
  5296. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  5297.  
  5298. if (q > 0) brr.set(k, q);
  5299.  
  5300. }
  5301.  
  5302. }
  5303.  
  5304. if (arr.length === 0) {
  5305.  
  5306. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  5307. } else {
  5308.  
  5309. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  5310.  
  5311. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  5312.  
  5313. if (arr.length > 2) console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  5314. return arr[0][0];
  5315. }
  5316.  
  5317.  
  5318.  
  5319. }
  5320.  
  5321.  
  5322.  
  5323. const isPrepareCachedV = (FIX_avoid_incorrect_video_meta ? true : false) && (window === top);
  5324.  
  5325. let pageSetupVideoId = null; // set at finish; '' for indeterminate state
  5326. let pageSetupState = 0;
  5327.  
  5328. isPrepareCachedV && (() => {
  5329.  
  5330. pageSetupVideoId = '';
  5331. const clearCachedV = () => {
  5332. pageSetupVideoId = '';
  5333. pageSetupState = 0;
  5334. }
  5335. document.addEventListener('yt-navigate-start', clearCachedV, false); // user action
  5336. document.addEventListener('yt-navigate-cache', clearCachedV, false); // pop state
  5337. document.addEventListener('yt-page-data-fetched', clearCachedV, false); // still consider invalid until url is ready in yt-navigate-finish
  5338. document.addEventListener('yt-navigate-finish', () => {
  5339. pageSetupState = 1;
  5340. try {
  5341. const url = new URL(location.href);
  5342. if (!url || !isWatchPageURL(url)) {
  5343. pageSetupVideoId = '';
  5344. } else {
  5345. pageSetupVideoId = url.searchParams.get('v') || '';
  5346. }
  5347. } catch (e) {
  5348. pageSetupVideoId = '';
  5349. }
  5350. }, false);
  5351.  
  5352. })();
  5353.  
  5354. let videoPlayingY = null;
  5355.  
  5356. isPrepareCachedV && (() => {
  5357.  
  5358. let getNext = true;
  5359. let videoPlayingX = {
  5360. get videoId() {
  5361. if (getNext) {
  5362. getNext = false;
  5363.  
  5364. let elements = document.querySelectorAll('ytd-watch-flexy[video-id]');
  5365. const arr = [];
  5366. for (const element of elements) {
  5367. if (!element.closest('[hidden]')) arr.push(element);
  5368. }
  5369. if (arr.length !== 1) this.__videoId__ = '';
  5370. else {
  5371. this.__videoId__ = arr[0].getAttribute('video-id');
  5372. }
  5373.  
  5374. }
  5375. return this.__videoId__ || '';
  5376. }
  5377. }
  5378.  
  5379. videoPlayingY = videoPlayingX;
  5380. const handler = (evt) => {
  5381. const target = (evt || 0).target;
  5382. if (target instanceof HTMLVideoElement) {
  5383. getNext = true;
  5384. }
  5385. }
  5386. document.addEventListener('loadedmetadata', handler, true);
  5387. document.addEventListener('durationchange', handler, true);
  5388.  
  5389. })();
  5390.  
  5391.  
  5392.  
  5393. const cleanContext = async (win) => {
  5394. const waitFn = requestAnimationFrame; // shall have been binded to window
  5395. try {
  5396. let mx = 16; // MAX TRIAL
  5397. const frameId = 'vanillajs-iframe-v1';
  5398. /** @type {HTMLIFrameElement | null} */
  5399. let frame = document.getElementById(frameId);
  5400. let removeIframeFn = null;
  5401. if (!frame) {
  5402. frame = document.createElement('iframe');
  5403. frame.id = frameId;
  5404. const blobURL = typeof webkitCancelAnimationFrame === 'function' && typeof kagi === 'undefined' ? (frame.src = URL.createObjectURL(new Blob([], { type: 'text/html' }))) : null; // avoid Brave Crash
  5405. frame.sandbox = 'allow-same-origin'; // script cannot be run inside iframe but API can be obtained from iframe
  5406. let n = document.createElement('noscript'); // wrap into NOSCRPIT to avoid reflow (layouting)
  5407. n.appendChild(frame);
  5408. while (!document.documentElement && mx-- > 0) await new Promise(waitFn); // requestAnimationFrame here could get modified by YouTube engine
  5409. const root = document.documentElement;
  5410. root.appendChild(n); // throw error if root is null due to exceeding MAX TRIAL
  5411. if (blobURL) Promise.resolve().then(() => URL.revokeObjectURL(blobURL));
  5412.  
  5413. removeIframeFn = (setTimeout) => {
  5414. const removeIframeOnDocumentReady = (e) => {
  5415. e && win.removeEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  5416. e = n;
  5417. n = win = removeIframeFn = 0;
  5418. setTimeout ? setTimeout(() => e.remove(), 200) : e.remove();
  5419. }
  5420. if (!setTimeout || document.readyState !== 'loading') {
  5421. removeIframeOnDocumentReady();
  5422. } else {
  5423. win.addEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  5424. }
  5425. }
  5426. }
  5427. while (!frame.contentWindow && mx-- > 0) await new Promise(waitFn);
  5428. const fc = frame.contentWindow;
  5429. if (!fc) throw "window is not found."; // throw error if root is null due to exceeding MAX TRIAL
  5430. try {
  5431. const { requestAnimationFrame, setTimeout, clearTimeout, cancelAnimationFrame, setInterval, clearInterval, requestIdleCallback, getComputedStyle } = fc;
  5432. const res = { requestAnimationFrame, setTimeout, clearTimeout, cancelAnimationFrame, setInterval, clearInterval, requestIdleCallback, getComputedStyle };
  5433. for (let k in res) res[k] = res[k].bind(win); // necessary
  5434. if (removeIframeFn) Promise.resolve(res.setTimeout).then(removeIframeFn);
  5435. res.animate = fc.HTMLElement.prototype.animate;
  5436. res.perfNow = fc.performance.now;
  5437. return res;
  5438. } catch (e) {
  5439. if (removeIframeFn) removeIframeFn();
  5440. return null;
  5441. }
  5442. } catch (e) {
  5443. console.warn(e);
  5444. return null;
  5445. }
  5446. };
  5447.  
  5448. const promiseForYtActionCalled = new Promise(resolve => {
  5449.  
  5450. const appTag = isChatRoomURL ? 'yt-live-chat-app' : 'ytd-app';
  5451. if (typeof AbortSignal !== 'undefined') {
  5452. let hn = () => {
  5453. if (!hn) return;
  5454. hn = null;
  5455. resolve(document.querySelector(appTag));
  5456. };
  5457. document.addEventListener('yt-action', hn, { capture: true, passive: true, once: true });
  5458. } else {
  5459. let hn = () => {
  5460. if (!hn) return;
  5461. document.removeEventListener('yt-action', hn, true);
  5462. hn = null;
  5463. resolve(document.querySelector(appTag));
  5464. };
  5465. document.addEventListener('yt-action', hn, true);
  5466. }
  5467. });
  5468.  
  5469. cleanContext(window).then(__CONTEXT__ => {
  5470. if (!__CONTEXT__) return null;
  5471.  
  5472. const { requestAnimationFrame, setTimeout, clearTimeout, cancelAnimationFrame, setInterval, clearInterval, animate, requestIdleCallback, getComputedStyle, perfNow } = __CONTEXT__;
  5473.  
  5474.  
  5475. performance.now17 = perfNow.bind(performance);
  5476.  
  5477.  
  5478.  
  5479. __requestAnimationFrame__ = requestAnimationFrame;
  5480.  
  5481.  
  5482. const isGPUAccelerationAvailable = (() => {
  5483. // https://gist.github.com/cvan/042b2448fcecefafbb6a91469484cdf8
  5484. try {
  5485. const canvas = document.createElement('canvas');
  5486. return !!(canvas.getContext('webgl') || canvas.getContext('experimental-webgl'));
  5487. } catch (e) {
  5488. return false;
  5489. }
  5490. })();
  5491.  
  5492. const foregroundPromiseFn_noGPU = (() => {
  5493.  
  5494. if (isGPUAccelerationAvailable) return null;
  5495.  
  5496. const pd = Object.getOwnPropertyDescriptor(Document.prototype, 'visibilityState');
  5497. if (!pd || typeof pd.get !== 'function') return null;
  5498. const pdGet = pd.get;
  5499.  
  5500. let pr = null;
  5501.  
  5502. let hState = pdGet.call(document) === 'hidden';
  5503. // let cid = 0;
  5504. pureAddEventListener.call(document, 'visibilitychange', (evt) => {
  5505. const newHState = pdGet.call(document) === 'hidden';
  5506. if (hState !== newHState) {
  5507. // if (cid > 0) cid = clearInterval(cid);
  5508. hState = newHState;
  5509. if (!hState && pr) pr = pr.resolve();
  5510. }
  5511. });
  5512.  
  5513. // cid = setInterval(() => {
  5514. // const newHState = document.visibilityState === 'hidden';
  5515. // if (hState !== newHState) {
  5516. // hState = newHState;
  5517. // if (!hState && pr) pr = pr.resolve();
  5518. // }
  5519. // }, 100);
  5520.  
  5521.  
  5522. return (() => {
  5523. if (pr) return pr;
  5524. const w = ((!hState && setTimeout(() => {
  5525. if (!hState && pr === w) pr = pr.resolve();
  5526. })), (pr = new PromiseExternal()));
  5527. return w;
  5528. });
  5529.  
  5530. })();
  5531.  
  5532.  
  5533. let rafPromise = null;
  5534. const getRafPromise = () => rafPromise || (rafPromise = new Promise(resolve => {
  5535. requestAnimationFrame(hRes => {
  5536. rafPromise = null;
  5537. resolve(hRes);
  5538. });
  5539. }));
  5540.  
  5541. const foregroundPromiseFn = foregroundPromiseFn_noGPU || getRafPromise;
  5542.  
  5543.  
  5544. const wmComputedStyle = new WeakMap();
  5545.  
  5546. if (!window.__native__getComputedStyle__ && !window.__jst__getComputedStyle__ && typeof window.getComputedStyle === 'function' && window.getComputedStyle.length === 1) {
  5547. window.__native__getComputedStyle__ = getComputedStyle;
  5548. if (ENABLE_COMPUTEDSTYLE_CACHE) {
  5549. window.__original__getComputedStyle__ = window.getComputedStyle;
  5550. window.getComputedStyle = function (elem) {
  5551. if (!(elem instanceof Element) || (arguments.length === 2 && arguments[1]) || (arguments.length > 2)) {
  5552. return window.__original__getComputedStyle__(...arguments);
  5553. }
  5554. let cs = wmComputedStyle.get(elem);
  5555. if (!cs) {
  5556. cs = window.__native__getComputedStyle__(elem);
  5557. wmComputedStyle.set(elem, cs);
  5558. }
  5559. return cs;
  5560. };
  5561. } else {
  5562. window.__original__getComputedStyle__ = null;
  5563. }
  5564. window.__jst__getComputedStyle__ = window.getComputedStyle;
  5565. }
  5566.  
  5567. NO_SCHEDULING_DUE_TO_COMPUTEDSTYLE && promiseForYtActionCalled.then(() => {
  5568. if (typeof window.__jst__getComputedStyle__ === 'function' && window.__jst__getComputedStyle__.length === 1 && window.__jst__getComputedStyle__ !== window.getComputedStyle) {
  5569. window.getComputedStyle = window.__jst__getComputedStyle__;
  5570. }
  5571. });
  5572.  
  5573. const isUrlInEmbed = location.href.includes('.youtube.com/embed/');
  5574. const isAbortSignalSupported = typeof AbortSignal !== "undefined";
  5575.  
  5576. const promiseForTamerTimeout = new Promise(resolve => {
  5577. !isUrlInEmbed && isAbortSignalSupported && document.addEventListener('yt-action', function () {
  5578. setTimeout(resolve, 480);
  5579. }, { capture: true, passive: true, once: true });
  5580. !isUrlInEmbed && isAbortSignalSupported && typeof customElements === "object" && whenCEDefined('ytd-app').then(() => {
  5581. setTimeout(resolve, 1200);
  5582. });
  5583. setTimeout(resolve, 3000);
  5584. });
  5585.  
  5586. const promiseForPageInitied = new Promise(resolve => {
  5587. !isUrlInEmbed && isAbortSignalSupported && document.addEventListener('yt-action', function () {
  5588. setTimeout(resolve, 450);
  5589. }, { capture: true, passive: true, once: true });
  5590. !isUrlInEmbed && isAbortSignalSupported && typeof customElements === "object" && whenCEDefined('ytd-app').then(() => {
  5591. setTimeout(resolve, 900);
  5592. });
  5593. setTimeout(resolve, 1800);
  5594. });
  5595.  
  5596. NO_PRELOAD_GENERATE_204_BYPASS || promiseForPageInitied.then(() => {
  5597. NO_PRELOAD_GENERATE_204_BYPASS = true;
  5598. headLinkCollection = null;
  5599. });
  5600.  
  5601.  
  5602. NATIVE_CANVAS_ANIMATION && (() => {
  5603.  
  5604. observablePromise(() => {
  5605. HTMLCanvasElement.prototype.animate = animate;
  5606. }, promiseForTamerTimeout).obtain();
  5607.  
  5608. })();
  5609.  
  5610.  
  5611.  
  5612.  
  5613. FIX_ytAction_ && (async () => {
  5614.  
  5615. const appTag = isChatRoomURL ? 'yt-live-chat-app' : 'ytd-app';
  5616.  
  5617. const ytdApp = await new Promise(resolve => {
  5618.  
  5619. whenCEDefined(appTag).then(() => {
  5620. const ytdApp = document.querySelector(appTag);
  5621. if (ytdApp) {
  5622. resolve(ytdApp);
  5623. return;
  5624. }
  5625. let mo = new MutationObserver(() => {
  5626. const ytdApp = document.querySelector(appTag);
  5627. if (!ytdApp) return;
  5628. if (mo) {
  5629. mo.disconnect();
  5630. mo.takeRecords();
  5631. mo = null;
  5632. }
  5633. resolve(ytdApp);
  5634. });
  5635. mo.observe(document, { subtree: true, childList: true });
  5636. });
  5637.  
  5638. });
  5639.  
  5640. if (!ytdApp) return;
  5641. const cProto = insp(ytdApp).constructor.prototype;
  5642.  
  5643. if (!cProto) return;
  5644. let mbd = 0;
  5645.  
  5646. const fixer = (_ytdApp) => {
  5647. const ytdApp = insp(_ytdApp);
  5648. if (ytdApp && typeof ytdApp.onYtActionBoundListener_ === 'function' && !ytdApp.onYtActionBoundListener57_) {
  5649. ytdApp.onYtActionBoundListener57_ = ytdApp.onYtActionBoundListener_;
  5650. ytdApp.onYtActionBoundListener_ = ytdApp.onYtAction_.bind(ytdApp);
  5651. mbd++;
  5652. }
  5653. }
  5654.  
  5655. observablePromise(() => {
  5656.  
  5657. if (typeof cProto.created === 'function' && !cProto.created56) {
  5658. cProto.created56 = cProto.created;
  5659. cProto.created = function (...args) {
  5660. const r = this.created56(...args);
  5661. fixer(this);
  5662. return r;
  5663. };
  5664. mbd++;
  5665. }
  5666.  
  5667. if (typeof cProto.onYtAction_ === 'function' && !cProto.onYtAction57_) {
  5668. cProto.onYtAction57_ = cProto.onYtAction_;
  5669. cProto.onYtAction_ = function (...args) {
  5670. Promise.resolve().then(() => this.onYtAction57_(...args));
  5671. };
  5672. mbd++;
  5673. }
  5674.  
  5675. if (ytdApp) fixer(ytdApp);
  5676.  
  5677. /*
  5678. const actionRouter_ = ytdApp ? ytdApp.actionRouter_ : null;
  5679. if (actionRouter_ && typeof actionRouter_.handleAction === 'function' && !actionRouter_.handleAction57) {
  5680. actionRouter_.handleAction57 = actionRouter_.handleAction;
  5681. actionRouter_.handleAction = function (...args) {
  5682. Promise.resolve().then(() => this.handleAction57(...args));
  5683. }
  5684. mbd++;
  5685. }
  5686. */
  5687.  
  5688. // if(mbd === 3) return 1;
  5689. if (mbd >= 3) return 1;
  5690.  
  5691. }, new Promise(r => setTimeout(r, 1000))).obtain();
  5692.  
  5693. })();
  5694.  
  5695.  
  5696.  
  5697. FORCE_NO_REUSEABLE_ELEMENT_POOL && promiseForYtActionCalled.then(async () => {
  5698.  
  5699. const appTag = isChatRoomURL ? 'yt-live-chat-app' : 'ytd-watch-flexy';
  5700.  
  5701. const app = await observablePromise(() => {
  5702.  
  5703. return document.querySelector(appTag);
  5704.  
  5705. }).obtain();
  5706.  
  5707. if (!app) return;
  5708.  
  5709.  
  5710. const appCnt = insp(app);
  5711.  
  5712. if (typeof appCnt.createComponent_ !== 'function' || appCnt.createComponent_.length != 3) return;
  5713.  
  5714.  
  5715. const mapGet = Map.prototype.get;
  5716.  
  5717.  
  5718. /** @type {Map | null} */
  5719. let qcMap = null;
  5720.  
  5721. Map.prototype.get = function (a) {
  5722. if (a === 'dummy-4718') qcMap = this;
  5723. return mapGet.call(this, a);
  5724. };
  5725. const r = appCnt.createComponent_('dummy-4718', {}, true);
  5726. Map.prototype.get = mapGet;
  5727.  
  5728. if (r && (r.nodeName || '').toLowerCase() === 'dummy-4718') {
  5729.  
  5730.  
  5731. // clearInterval(ckId);
  5732. // ckId = 0;
  5733.  
  5734. if (qcMap !== null && qcMap instanceof Map) {
  5735.  
  5736. console.log('[yt-js-engine-tamer] qcMap', qcMap);
  5737.  
  5738. const setArrayC = (c) => {
  5739. if (c instanceof Array) {
  5740. c.length = 0;
  5741. c.push = function () { };
  5742. c.pop = function () { };
  5743. c.shift = function () { };
  5744. c.unshift = function () { };
  5745. c.splice = function () { };
  5746. c.sort = function () { };
  5747. c.reverse = function () { };
  5748. }
  5749. }
  5750.  
  5751. const cleaning = function () {
  5752. qcMap.forEach(setArrayC);
  5753. qcMap.clear();
  5754. }
  5755.  
  5756. qcMap.set = function (b, c) {
  5757.  
  5758. setArrayC(c);
  5759.  
  5760. // console.log('qcMap.set', b, c);
  5761.  
  5762. if (qcMap.size > 0) {
  5763. // play safe
  5764.  
  5765. console.log('[yt-js-engine-tamer] qcMap', 'clear 01')
  5766. cleaning();
  5767. }
  5768.  
  5769. }
  5770. qcMap.get = function (b) {
  5771.  
  5772. // console.log('qcMap.get', b);
  5773.  
  5774. if (qcMap.size > 0) {
  5775. // play safe
  5776.  
  5777. console.log('[yt-js-engine-tamer] qcMap', 'clear 02')
  5778. cleaning();
  5779. }
  5780.  
  5781. }
  5782.  
  5783.  
  5784. if (qcMap.size > 0) {
  5785.  
  5786. console.log('[yt-js-engine-tamer] qcMap', 'clear 03')
  5787. cleaning();
  5788. }
  5789.  
  5790. }
  5791.  
  5792. }
  5793.  
  5794.  
  5795. });
  5796.  
  5797.  
  5798. const observablePromise = (proc, timeoutPromise) => {
  5799. let promise = null;
  5800. return {
  5801. obtain() {
  5802. if (!promise) {
  5803. promise = new Promise(resolve => {
  5804. let mo = null;
  5805. const f = () => {
  5806. let t = proc();
  5807. if (t) {
  5808. mo.disconnect();
  5809. mo.takeRecords();
  5810. mo = null;
  5811. resolve(t);
  5812. }
  5813. }
  5814. mo = new MutationObserver(f);
  5815. mo.observe(document, { subtree: true, childList: true })
  5816. f();
  5817. timeoutPromise && timeoutPromise.then(() => {
  5818. resolve(null)
  5819. });
  5820. });
  5821. }
  5822. return promise
  5823. }
  5824. }
  5825. }
  5826.  
  5827. // let _yt_player_promise = null;
  5828. /*
  5829. const getYtPlayerPromise = () => {
  5830. if (!_yt_player_promise) {
  5831. _yt_player_promise = new Promise(resolve => {
  5832. let cid = setInterval(() => {
  5833. let t = (((window || 0)._yt_player || 0) || 0);
  5834. if (t) {
  5835. clearInterval(cid);
  5836. resolve(t);
  5837. }
  5838. }, 1);
  5839. promiseForTamerTimeout.then(() => {
  5840. resolve(null)
  5841. });
  5842. });
  5843. }
  5844. return _yt_player_promise;
  5845. }
  5846. */
  5847. const _yt_player_observable = observablePromise(() => {
  5848. const _yt_player = (((window || 0)._yt_player || 0) || 0);
  5849. if (_yt_player) {
  5850. _yt_player[`__is_yt_player__${Date.now()}`] = 1;
  5851. return _yt_player;
  5852. }
  5853. }, promiseForTamerTimeout);
  5854.  
  5855. const polymerObservable = observablePromise(() => {
  5856. const Polymer = window.Polymer;
  5857. if (typeof Polymer !== 'function') return;
  5858. if (!(Polymer.Base || 0).connectedCallback || !(Polymer.Base || 0).disconnectedCallback) return;
  5859. return Polymer;
  5860. }, promiseForTamerTimeout);
  5861.  
  5862. const schedulerInstanceObservable = observablePromise(() => {
  5863. return (((window || 0).ytglobal || 0).schedulerInstanceInstance_ || 0);
  5864. }, promiseForTamerTimeout);
  5865.  
  5866. const timelineObservable = observablePromise(() => {
  5867. let t = (((document || 0).timeline || 0) || 0);
  5868. if (t && typeof t._play === 'function') {
  5869. return t;
  5870. }
  5871. }, promiseForTamerTimeout);
  5872. const animationObservable = observablePromise(() => {
  5873. let t = (((window || 0).Animation || 0) || 0);
  5874. if (t && typeof t === 'function' && t.length === 2 && typeof t.prototype._updatePromises === 'function') {
  5875. return t;
  5876. }
  5877. }, promiseForTamerTimeout);
  5878.  
  5879.  
  5880. const getScreenInfo = {
  5881. screenWidth: 0,
  5882. screenHeight: 0,
  5883. valueReady: false,
  5884. onResize: () => {
  5885. getScreenInfo.valueReady = false;
  5886. },
  5887. sizeProvided: () => {
  5888. if (getScreenInfo.valueReady) return true;
  5889. getScreenInfo.screenWidth = screen.width;
  5890. getScreenInfo.screenHeight = screen.height;
  5891. if (getScreenInfo.screenWidth * getScreenInfo.screenHeight > 1) {
  5892. getScreenInfo.valueReady = true;
  5893. return true;
  5894. }
  5895. return false;
  5896. }
  5897. };
  5898.  
  5899. window.addEventListener('resize', getScreenInfo.onResize, true);
  5900.  
  5901.  
  5902. // const hookLeftPending = new WeakMap();
  5903.  
  5904. const isNaNx = Number.isNaN;
  5905.  
  5906. const hookLeftPD = {
  5907. get() {
  5908. const p = 'left';
  5909. // const o = hookLeftPending.get(this);
  5910. // if (o && o.key) {
  5911. // this.setProperty(p, o.value);
  5912. // o.key = null
  5913. // }
  5914. return this.getPropertyValue(p);
  5915. },
  5916. set(v) {
  5917.  
  5918. const p = 'left';
  5919. const cv = this.getPropertyValue(p);
  5920. const sv = v;
  5921.  
  5922. // const did = Math.floor(Math.random() * 314159265359 + 314159265359).toString(36);
  5923.  
  5924. // console.log(8380,did, cv, sv)
  5925. if (!cv && !sv) return true;
  5926. if (cv === sv) return true;
  5927.  
  5928. // skip 0~9px => L>=4
  5929.  
  5930. const qsv = `${sv}`.length >= 4 && `${sv}`.endsWith('px') ? +sv.slice(0, -2) : NaN;
  5931.  
  5932. if (!isNaNx(qsv)) {
  5933. const qcv = `${cv}`.length >= 4 && `${cv}`.endsWith('px') ? +cv.slice(0, -2) : NaN;
  5934.  
  5935. if (!isNaNx(qcv) && getScreenInfo.sizeProvided()) {
  5936. const { screenWidth, screenHeight } = getScreenInfo;
  5937. let pWidth = screenWidth + 1024;
  5938. let pHeight = screenHeight + 768;
  5939. const minRatio = 0.003;
  5940. const dw = pWidth * 0.0003; // min dw = 0.3072
  5941. const dh = pHeight * 0.0003; // min dh = 0.2304
  5942. // console.log(8381,did, Math.abs(qcv - qsv) < dw)
  5943. if (Math.abs(qcv - qsv) < dw) return true;
  5944. }
  5945.  
  5946. v = `${qsv > -1e-5 && qsv < 1e-5 ? 0 : qsv.toFixed(4)}px`;
  5947. if (`${v}`.length > `${sv}`.length) v = sv;
  5948. // console.log(8382, did, sv, nv, cv, this)
  5949. }
  5950.  
  5951. // Promise.resolve().then(() => {
  5952. // const o = hookLeftPending.get(this);
  5953. // if (o && o.key === did) {
  5954. // this.setProperty(p, o.value);
  5955. // o.key = null;
  5956. // }
  5957. // });
  5958. // hookLeftPending.set(this, {
  5959. // key: did,
  5960. // value: nv
  5961. // });
  5962.  
  5963. // if (nv != v) {
  5964. // console.log(8387, v, nv);
  5965. // }
  5966.  
  5967. this.setProperty(p, v);
  5968. // console.log(8383, did, this.getPropertyValue(p))
  5969. return true;
  5970. },
  5971. enumerable: true,
  5972. configurable: true
  5973. };
  5974.  
  5975.  
  5976. if (HOOK_CSSPD_LEFT) {
  5977.  
  5978.  
  5979. Object.defineProperty(CSSStyleDeclaration.prototype, 'left', hookLeftPD);
  5980.  
  5981. }
  5982.  
  5983.  
  5984.  
  5985.  
  5986.  
  5987. const generalEvtHandler = async (_evKey, _fvKey, _debug) => {
  5988.  
  5989. const evKey = `${_evKey}`;
  5990. const fvKey = `${_fvKey}`;
  5991. const debug = !!_debug;
  5992.  
  5993. const _yt_player = await _yt_player_observable.obtain();
  5994.  
  5995.  
  5996. if (!_yt_player || typeof _yt_player !== 'object') return;
  5997.  
  5998.  
  5999. const getArr = (_yt_player) => {
  6000.  
  6001. let arr = [];
  6002.  
  6003. for (const [k, v] of Object.entries(_yt_player)) {
  6004.  
  6005. const p = typeof v === 'function' ? v.prototype : 0;
  6006. if (p
  6007. && typeof p[evKey] === 'function' && p[evKey].length >= 0 && !p[fvKey]
  6008.  
  6009. ) {
  6010. arr = addProtoToArr(_yt_player, k, arr) || arr;
  6011.  
  6012. }
  6013.  
  6014. }
  6015.  
  6016. if (arr.length === 0) {
  6017.  
  6018. console.warn(`Key prop [${evKey}] does not exist.`);
  6019. } else {
  6020.  
  6021. return arr;
  6022. }
  6023.  
  6024. };
  6025.  
  6026. const arr = getArr(_yt_player);
  6027.  
  6028.  
  6029. if (!arr) return;
  6030.  
  6031. debug && console.log(`FIX_${evKey}`, arr);
  6032.  
  6033. const f = function (...args) {
  6034. Promise.resolve().then(() => this[fvKey](...args));
  6035. };
  6036.  
  6037.  
  6038. for (const k of arr) {
  6039.  
  6040. const g = _yt_player;
  6041. const gk = g[k];
  6042. const gkp = gk.prototype;
  6043.  
  6044. debug && console.log(237, k, gkp)
  6045.  
  6046. if (typeof gkp[evKey] == 'function' && !gkp[fvKey]) {
  6047. gkp[fvKey] = gkp[evKey];
  6048. gkp[evKey] = f;
  6049. }
  6050. }
  6051.  
  6052.  
  6053.  
  6054.  
  6055. }
  6056.  
  6057. if (!isChatRoomURL) {
  6058.  
  6059. FIX_onVideoDataChange && generalEvtHandler('onVideoDataChange', 'onVideoDataChange57');
  6060. // FIX_onClick && generalEvtHandler('onClick', 'onClick57');
  6061. FIX_onStateChange && generalEvtHandler('onStateChange', 'onStateChange57');
  6062. FIX_onLoopRangeChange && generalEvtHandler('onLoopRangeChange', 'onLoopRangeChange57');
  6063. if (FIX_VideoEVENTS_v2) {
  6064. const FIX_VideoEVENTS_DEBUG = 0;
  6065. generalEvtHandler('onVideoProgress', 'onVideoProgress57', FIX_VideoEVENTS_DEBUG); // --
  6066. // generalEvtHandler('onAutoplayBlocked', 'onAutoplayBlocked57', FIX_VideoEVENTS_DEBUG);
  6067. // generalEvtHandler('onLoadProgress', 'onLoadProgress57', FIX_VideoEVENTS_DEBUG); // << CAUSE ISSUE >>
  6068. generalEvtHandler('onFullscreenChange', 'onFullscreenChange57', FIX_VideoEVENTS_DEBUG); // --
  6069. // generalEvtHandler('onLoadedMetadata', 'onLoadedMetadata57', FIX_VideoEVENTS_DEBUG);
  6070. // generalEvtHandler('onDrmOutputRestricted', 'onDrmOutputRestricted57', FIX_VideoEVENTS_DEBUG);
  6071. // generalEvtHandler('onAirPlayActiveChange', 'onAirPlayActiveChange57', FIX_VideoEVENTS_DEBUG);
  6072. // generalEvtHandler('onAirPlayAvailabilityChange', 'onAirPlayAvailabilityChange57', FIX_VideoEVENTS_DEBUG);
  6073. // generalEvtHandler('onApiChange', 'onApiChange57', FIX_VideoEVENTS_DEBUG);
  6074.  
  6075. }
  6076. // onMutedAutoplayChange
  6077. // onVolumeChange
  6078. // onPlaybackRateChange
  6079.  
  6080. // onAirPlayActiveChange
  6081. // onAirPlayAvailabilityChange
  6082. // onApiChange
  6083. // onAutoplayBlocked
  6084. // onDrmOutputRestricted
  6085. // onFullscreenChange
  6086. // onLoadProgress
  6087. // onLoadedMetadata
  6088. // onVideoDataChange
  6089. // onVideoProgress
  6090.  
  6091. }
  6092.  
  6093.  
  6094.  
  6095. (ENABLE_discreteTasking || FIX_Polymer_dom) && (async () => {
  6096.  
  6097. const Polymer = await polymerObservable.obtain();
  6098. if (!Polymer) return;
  6099.  
  6100. if (FIX_Polymer_dom) {
  6101.  
  6102. const checkPDFuncValue = (pd) => {
  6103. return pd && pd.writable && pd.enumerable && pd.configurable && typeof pd.value == 'function'
  6104. }
  6105. const checkPDFuncValue2 = (pd) => {
  6106. return pd && typeof pd.value == 'function'
  6107. }
  6108.  
  6109. const checkPDFuncGet = (pd) => {
  6110. return pd && typeof pd.get == 'function'
  6111. }
  6112.  
  6113. const domX = Polymer.dom(document.createElement('null'));
  6114. const domXP = (((domX || 0).constructor || 0).prototype || 0);
  6115. const pd1 = Object.getOwnPropertyDescriptor(domXP, 'getOwnerRoot');
  6116. const pd2 = Object.getOwnPropertyDescriptor(Node.prototype, 'parentElement');
  6117. const pd3 = Object.getOwnPropertyDescriptor(domXP, 'querySelector'); // undefined
  6118. const pd4 = Object.getOwnPropertyDescriptor(Element.prototype, 'querySelector');
  6119. const pd4b = Object.getOwnPropertyDescriptor(Document.prototype, 'querySelector');
  6120. const pd5 = Object.getOwnPropertyDescriptor(domXP, 'querySelectorAll'); // undefined
  6121. const pd6 = Object.getOwnPropertyDescriptor(Element.prototype, 'querySelectorAll');
  6122. const pd6b = Object.getOwnPropertyDescriptor(Document.prototype, 'querySelectorAll');
  6123.  
  6124.  
  6125. // getOwnerRoot - to be reviewed
  6126. if (0 && checkPDFuncValue(pd1) && checkPDFuncGet(pd2) && !domXP.getOwnerRoot15 && typeof domXP.getOwnerRoot === 'function') {
  6127.  
  6128. domXP.getOwnerRoot15 = domXP.getOwnerRoot;
  6129. domXP.getOwnerRoot = function () {
  6130. try {
  6131. const p = this.node;
  6132.  
  6133. if (p instanceof HTMLElement) {
  6134. const pp = pd2.get.call(p);
  6135. if (pp instanceof HTMLElement && pp.isConnected === true) {
  6136. return pp.getRootNode();
  6137. }
  6138.  
  6139. }
  6140. } catch (e) { }
  6141. return this.getOwnerRoot15();
  6142. }
  6143.  
  6144. Polymer.__fixedGetOwnerRoot__ = 1;
  6145. }
  6146.  
  6147.  
  6148.  
  6149.  
  6150. if ((!pd3 || checkPDFuncValue(pd3)) && checkPDFuncValue2(pd4) && checkPDFuncValue2(pd4b) && !('querySelector15' in domXP)) {
  6151.  
  6152. domXP.querySelector15 = domXP.querySelector;
  6153.  
  6154. const querySelectorFn = function (query) {
  6155. try {
  6156. const p = this.node;
  6157.  
  6158. // if (p instanceof HTMLElement && p.isConnected === true) {
  6159. // return pd4.value.call(p, query);
  6160. // }
  6161.  
  6162. if (p instanceof Document && p.isConnected === true) {
  6163. return pd4b.value.call(p, query);
  6164. }
  6165.  
  6166. } catch (e) { }
  6167. return this.querySelector15(query);
  6168. }
  6169.  
  6170. Object.defineProperty(domXP, 'querySelector', {
  6171. get() {
  6172. return querySelectorFn;
  6173. },
  6174. set(nv) {
  6175. if (nv === querySelectorFn) return true;
  6176. this.querySelector15 = nv;
  6177. return true;
  6178. },
  6179.  
  6180. enumerable: false,
  6181. configurable: true
  6182. });
  6183.  
  6184. Polymer.__fixedQuerySelector__ = 1;
  6185. }
  6186.  
  6187. if ((!pd5 || checkPDFuncValue(pd5)) && checkPDFuncValue2(pd6) && checkPDFuncValue2(pd6b) && !('querySelectorAll15' in domXP)) {
  6188.  
  6189. domXP.querySelectorAll15 = domXP.querySelectorAll;
  6190.  
  6191. const querySelectorAllFn = function (query) {
  6192.  
  6193. try {
  6194.  
  6195. const p = this.node;
  6196.  
  6197. // if (p instanceof HTMLElement && p.isConnected === true) {
  6198. // return pd6.value.call(p, query);
  6199. // }
  6200.  
  6201. if (p instanceof Document && p.isConnected === true) {
  6202. return pd6b.value.call(p, query);
  6203. }
  6204.  
  6205. } catch (e) {
  6206.  
  6207. }
  6208. return this.querySelectorAll15(query);
  6209. }
  6210.  
  6211. Object.defineProperty(domXP, 'querySelectorAll', {
  6212. get() {
  6213. return querySelectorAllFn;
  6214. },
  6215. set(nv) {
  6216. if (nv === querySelectorAllFn) return true;
  6217. this.querySelectorAll15 = nv;
  6218. return true;
  6219. },
  6220.  
  6221. enumerable: false,
  6222. configurable: true
  6223. });
  6224.  
  6225. Polymer.__fixedQuerySelectorAll__ = 1;
  6226. }
  6227. }
  6228.  
  6229.  
  6230. if (ENABLE_discreteTasking) {
  6231.  
  6232. Polymer.Base.__connInit__ = function () {
  6233. setupDiscreteTasks(this);
  6234. }
  6235.  
  6236.  
  6237. /** @type {Function} */
  6238. const connectedCallbackK = function (...args) {
  6239. !this.mh35 && typeof this.__connInit__ === 'function' && this.__connInit__();
  6240. const r = this[qm53](...args);
  6241. !this.mh35 && typeof this.__connInit__ === 'function' && this.__connInit__();
  6242. this.mh35 = 1;
  6243. return r;
  6244. };
  6245.  
  6246. connectedCallbackK.m353 = 1;
  6247.  
  6248.  
  6249. const qt53 = Polymer.Base.connectedCallback;
  6250. Polymer.Base[qm53] = dmf.get(qt53) || qt53;
  6251.  
  6252. Polymer.Base.connectedCallback = connectedCallbackK;
  6253.  
  6254.  
  6255. /** @type {Function} */
  6256. const createdK = function (...args) {
  6257. !this.mh36 && typeof this.__connInit__ === 'function' && this.__connInit__();
  6258. const r = this[qn53](...args);
  6259. !this.mh36 && typeof this.__connInit__ === 'function' && this.__connInit__();
  6260. this.mh36 = 1;
  6261. return r;
  6262. };
  6263.  
  6264.  
  6265. createdK.m353 = 1;
  6266. Polymer.Base[qn53] = Polymer.Base.created;
  6267. Polymer.Base.created = createdK;
  6268.  
  6269. }
  6270.  
  6271. })();
  6272.  
  6273.  
  6274. /*
  6275.  
  6276. e.nativeAppendChild = d.prototype.appendChild,
  6277. d.prototype.appendChild = function(h) {
  6278. return function(l) {
  6279. if (l instanceof DocumentFragment) {
  6280. var m = Array.from(l.children);
  6281. l = h.nativeAppendChild.call(this, l);
  6282. if (this.isConnected) {
  6283. m = g(m);
  6284. for (var p = m.next(); !p.done; p = m.next())
  6285. YD(p.value)
  6286. }
  6287. return l
  6288. }
  6289. m = l instanceof Element && l.isConnected;
  6290. p = h.nativeAppendChild.call(this, l);
  6291. m && ZD(l);
  6292. this.isConnected && YD(l);
  6293. return p
  6294. }
  6295. }(e),
  6296.  
  6297. */
  6298.  
  6299. CHANGE_appendChild && !Node.prototype.appendChild73 && Node.prototype.appendChild && (() => {
  6300.  
  6301. const f = Node.prototype.appendChild73 = Node.prototype.appendChild;
  6302. if (f) Node.prototype.appendChild = function (a) {
  6303. if (this instanceof Element) { // exclude DocumentFragment
  6304. try {
  6305. let checkFragmentA = (a instanceof DocumentFragment);
  6306. if (!NO_PRELOAD_GENERATE_204_BYPASS && document.head === this) {
  6307. if (headLinkCollection === null) headLinkCollection = document.head.getElementsByTagName('LINK');
  6308. for (const node of headLinkCollection) {
  6309. if (node.rel === 'preload' && node.as === 'fetch') {
  6310. node.rel = 'prefetch'; // see https://github.com/GoogleChromeLabs/quicklink
  6311. }
  6312. }
  6313. } else if (checkFragmentA && this.nodeName.startsWith('YT-')) { // yt-animated-rolling-number, yt-attributed-string
  6314. checkFragmentA = false;
  6315. }
  6316. if (checkFragmentA && a.firstElementChild === null) {
  6317. // no element in fragmentA
  6318. let doNormal = false;
  6319. for (let child = a.firstChild; child instanceof Node; child = child.nextSibling) {
  6320. if (child.nodeType === 3) { doNormal = true; break; }
  6321. }
  6322. if (!doNormal) return a;
  6323. }
  6324. } catch (e) {
  6325. console.log(e);
  6326. }
  6327. }
  6328. return arguments.length === 1 ? f.call(this, a) : f.apply(this, arguments);
  6329. }
  6330.  
  6331. })();
  6332.  
  6333. if (FIX_Shady) {
  6334.  
  6335. observablePromise(() => {
  6336. const { ShadyDOM, ShadyCSS } = window;
  6337. if (ShadyDOM) {
  6338. ShadyDOM.handlesDynamicScoping = false; // 9 of 10
  6339. ShadyDOM.noPatch = true; // 1 of 10
  6340. ShadyDOM.patchOnDemand = false; // 1 of 10
  6341. ShadyDOM.preferPerformance = true; // 1 of 10
  6342. ShadyDOM.querySelectorImplementation = undefined; // 1 of 10
  6343. }
  6344. if (ShadyCSS) {
  6345. ShadyCSS.nativeCss = true; // 1 of 10
  6346. ShadyCSS.nativeShadow = true; // 6 of 10
  6347. ShadyCSS.cssBuild = undefined; // 1 of 10
  6348. ShadyCSS.disableRuntime = true; // 1 of 10
  6349. }
  6350. if (ShadyDOM && ShadyCSS) return 1;
  6351. }, promiseForTamerTimeout).obtain(); // clear until 1 is return
  6352.  
  6353. }
  6354.  
  6355.  
  6356. // let schedulerInstancePropOfTimerType = '';
  6357. // let schedulerInstancePropOfTimerId = '';
  6358. (FIX_schedulerInstanceInstance & 2) && (async () => {
  6359.  
  6360. const schedulerInstanceInstance_ = await schedulerInstanceObservable.obtain();
  6361.  
  6362. if (!schedulerInstanceInstance_) return;
  6363.  
  6364. const checkOK = typeof schedulerInstanceInstance_.start === 'function' && !schedulerInstanceInstance_.start993 && !schedulerInstanceInstance_.stop && !schedulerInstanceInstance_.cancel && !schedulerInstanceInstance_.terminate && !schedulerInstanceInstance_.interupt;
  6365. if (checkOK) {
  6366.  
  6367. schedulerInstanceInstance_.start993 = schedulerInstanceInstance_.start;
  6368.  
  6369. let requestingFn = null;
  6370. let requestingArgs = null;
  6371.  
  6372. const f = function () {
  6373. requestingFn = this.fn;
  6374. requestingArgs = [...arguments];
  6375. return 12373;
  6376. };
  6377.  
  6378. const fakeFns = [
  6379. f.bind({ fn: requestAnimationFrame }),
  6380. f.bind({ fn: setInterval }),
  6381. f.bind({ fn: setTimeout }),
  6382. f.bind({ fn: requestIdleCallback })
  6383. ];
  6384.  
  6385. let mzt = 0;
  6386.  
  6387. let _fnSelectorProp = null;
  6388. const mkFns = new Array(4);
  6389.  
  6390. /*
  6391. case 1:
  6392. var a = this.K;
  6393. this.g = this.I ? window.requestIdleCallback(a, {
  6394. timeout: 3E3
  6395. }) : window.setTimeout(a, ma);
  6396. break;
  6397. case 2:
  6398. this.g = window.setTimeout(this.M, this.N);
  6399. break;
  6400. case 3:
  6401. this.g = window.requestAnimationFrame(this.L);
  6402. break;
  6403. case 4:
  6404. this.g = window.setTimeout(this.J, 0)
  6405. }
  6406.  
  6407. */
  6408. const startFnHandler = {
  6409. get(target, prop, receiver) {
  6410. if (prop === '$$12377$$') return true;
  6411. if (prop === '$$12378$$') return target;
  6412.  
  6413. // console.log('get',prop)
  6414. return target[prop]
  6415. },
  6416. set(target, prop, value, receiver) {
  6417. // console.log('set', prop, value)
  6418.  
  6419. if (value >= 1 && value <= 4) _fnSelectorProp = prop;
  6420. if (value === 12373 && _fnSelectorProp) {
  6421.  
  6422. const schedulerTypeSelection = target[_fnSelectorProp];
  6423. const timerIdProp = prop;
  6424.  
  6425. // if (schedulerTypeSelection && schedulerTypeSelection >= 1 && schedulerTypeSelection <= 4 && timerIdProp) {
  6426. // schedulerInstancePropOfTimerType = _fnSelectorProp || '';
  6427. // schedulerInstancePropOfTimerId = timerIdProp || '';
  6428. // }
  6429.  
  6430. if (schedulerTypeSelection === 3 && requestingFn === requestAnimationFrame) { // rAF(fn)
  6431. target[timerIdProp] = baseRAF.apply(window, requestingArgs);
  6432. } else if (schedulerTypeSelection === 2 && requestingFn === setTimeout) { // setTimeout(fn, delay)
  6433. // rare
  6434. target[timerIdProp] = mkFns[2].apply(window, requestingArgs);
  6435. } else if (schedulerTypeSelection === 4 && requestingFn === setTimeout && !requestingArgs[1]) { // setTimeout(fn, 0)
  6436. // often
  6437. if ((FIX_schedulerInstanceInstance & 4) && typeof nextBrowserTick == 'function') {
  6438. const f = requestingArgs[0];
  6439. const tir = ++mzt;
  6440. nextBrowserTick(() => {
  6441. if (target[timerIdProp] === -tir) f();
  6442. });
  6443. target[_fnSelectorProp] = 940;
  6444. target[timerIdProp] = -tir;
  6445. } else {
  6446. const f = requestingArgs[0];
  6447. const tir = ++mzt;
  6448. Promise.resolve().then(() => {
  6449. if (target[timerIdProp] === -tir) f();
  6450. });
  6451. target[_fnSelectorProp] = 930;
  6452. target[timerIdProp] = -tir;
  6453. }
  6454. } else if (schedulerTypeSelection === 1 && (requestingFn === requestIdleCallback || requestingFn === setTimeout)) { // setTimeout(requestIdleCallback)
  6455. // often
  6456. if (requestingFn === requestIdleCallback) {
  6457. target[timerIdProp] = requestIdleCallback.apply(window, requestingArgs);
  6458. } else {
  6459. target[timerIdProp] = mkFns[2].apply(window, requestingArgs);
  6460. }
  6461. } else {
  6462. target[_fnSelectorProp] = 0;
  6463. target[timerIdProp] = 0;
  6464. }
  6465. } else {
  6466. target[prop] = value;
  6467. }
  6468. return true;
  6469. }
  6470. };
  6471.  
  6472. let startBusy = false;
  6473. schedulerInstanceInstance_.start = function () {
  6474. if (startBusy) return;
  6475. startBusy = true;
  6476. try {
  6477. mkFns[0] = window.requestAnimationFrame;
  6478. mkFns[1] = window.setInterval;
  6479. mkFns[2] = window.setTimeout;
  6480. mkFns[3] = window.requestIdleCallback;
  6481. const tThis = this['$$12378$$'] || this;
  6482. window.requestAnimationFrame = fakeFns[0]
  6483. window.setInterval = fakeFns[1]
  6484. window.setTimeout = fakeFns[2]
  6485. window.requestIdleCallback = fakeFns[3]
  6486. _fnSelectorProp = null;
  6487. tThis.start993.call(new Proxy(tThis, startFnHandler));
  6488. _fnSelectorProp = null;
  6489. window.requestAnimationFrame = mkFns[0];
  6490. window.setInterval = mkFns[1];
  6491. window.setTimeout = mkFns[2];
  6492. window.requestIdleCallback = mkFns[3];
  6493. } catch (e) {
  6494. console.warn(e);
  6495. }
  6496. startBusy = false;
  6497. }
  6498.  
  6499. schedulerInstanceInstance_.start.toString = schedulerInstanceInstance_.start993.toString.bind(schedulerInstanceInstance_.start993);
  6500.  
  6501. }
  6502. })();
  6503.  
  6504. FIX_yt_player && !isChatRoomURL && (async () => {
  6505.  
  6506. const fOption = 1 | 2 | 4;
  6507.  
  6508. const _yt_player = await _yt_player_observable.obtain();
  6509.  
  6510. if (!_yt_player || typeof _yt_player !== 'object') return;
  6511.  
  6512. const g = _yt_player;
  6513. let k;
  6514.  
  6515. if (fOption & 1) {
  6516.  
  6517. // rAf scheduling
  6518.  
  6519. const keyZqOu = getZqOu(_yt_player);
  6520. if (!keyZqOu) {
  6521. console.warn('[yt-js-engine-tamer] FIX_yt_player::keyZqOu error');
  6522. return;
  6523. }
  6524. k = keyZqOu
  6525.  
  6526. const gk = g[k];
  6527. if (typeof gk !== 'function') {
  6528. console.warn('[yt-js-engine-tamer] FIX_yt_player::g[keyZqOu] error');
  6529. return;
  6530. }
  6531. const gkp = gk.prototype;
  6532.  
  6533. const dummyObject = new gk;
  6534. const nilFunc = () => { };
  6535.  
  6536. const nilObj = {};
  6537.  
  6538. // console.log(1111111111)
  6539.  
  6540. let keyBoolD = '';
  6541. let keyWindow = '';
  6542. let keyFuncC = '';
  6543. let keyCidj = '';
  6544.  
  6545. for (const [t, y] of Object.entries(dummyObject)) {
  6546. if (y instanceof Window) keyWindow = t;
  6547. }
  6548.  
  6549. const dummyObjectProxyHandler = {
  6550. get(target, prop) {
  6551. let v = target[prop]
  6552. if (v instanceof Window && !keyWindow) {
  6553. keyWindow = t;
  6554. }
  6555. let y = typeof v === 'function' ? nilFunc : typeof v === 'object' ? nilObj : v;
  6556. if (prop === keyWindow) y = {
  6557. requestAnimationFrame(f) {
  6558. return 3;
  6559. },
  6560. cancelAnimationFrame() {
  6561.  
  6562. }
  6563. }
  6564. if (!keyFuncC && typeof v === 'function' && !(prop in target.constructor.prototype)) {
  6565. keyFuncC = prop;
  6566. }
  6567. // console.log('[get]', prop, typeof target[prop])
  6568.  
  6569.  
  6570. return y;
  6571. },
  6572. set(target, prop, value) {
  6573.  
  6574. if (typeof value === 'boolean' && !keyBoolD) {
  6575. keyBoolD = prop;
  6576. }
  6577. if (typeof value === 'number' && !keyCidj && value >= 2) {
  6578. keyCidj = prop;
  6579. }
  6580.  
  6581. // console.log('[set]', prop, value)
  6582. target[prop] = value;
  6583.  
  6584. return true;
  6585. }
  6586. };
  6587.  
  6588. dummyObject.start.call(new Proxy(dummyObject, dummyObjectProxyHandler));
  6589.  
  6590. // console.log('gkp.start',gkp.start);
  6591. // console.log('gkp.stop',gkp.stop);
  6592. gkp._activation = false;
  6593.  
  6594. gkp.start = function () {
  6595. // p59 || console.log(12100)
  6596. if (!this._activation) {
  6597. this._activation = true;
  6598. foregroundPromiseFn().then(() => {
  6599. this._activation = false;
  6600. if (this[keyCidj]) {
  6601. Promise.resolve().then(this[keyFuncC]);
  6602. }
  6603. });
  6604. }
  6605. this[keyCidj] = 1;
  6606. this[keyBoolD] = true;
  6607. };
  6608.  
  6609. gkp.stop = function () {
  6610. this[keyCidj] = null;
  6611. };
  6612.  
  6613.  
  6614. /*
  6615. g[k].start = function() {
  6616. this.stop();
  6617. this.D = true;
  6618. var a = requestAnimationFrame
  6619. , b = cancelAnimationFrame;
  6620. this.j = a.call(this.B, this.C)
  6621. }
  6622. ;
  6623. g[k].stop = function() {
  6624. if (this.isActive()) {
  6625. var a = requestAnimationFrame
  6626. , b = cancelAnimationFrame;
  6627. b.call(this.B, this.j)
  6628. }
  6629. this.j = null
  6630. }
  6631. */
  6632. }
  6633.  
  6634. if (fOption & 2) {
  6635. const keyzo = PERF_471489_ ? getzo(_yt_player) : null;
  6636.  
  6637. if (keyzo) {
  6638.  
  6639. k = keyzo;
  6640.  
  6641. const attrUpdateFn = g[k];
  6642. // console.log(5992, attrUpdateFn)
  6643. g['$$original$$' + k] = attrUpdateFn;
  6644. const zoTransform = async (a, c) => {
  6645.  
  6646. let transformType = '';
  6647. let transformValue = 0;
  6648. let transformUnit = '';
  6649. let transformTypeI = 0;
  6650.  
  6651. const aStyle = a.style;
  6652.  
  6653. let cType = 0;
  6654.  
  6655. const cl = c.length;
  6656.  
  6657. if (cl >= 8) {
  6658. // scale(1)
  6659. if (c.startsWith('scale') && c.charCodeAt(6) === 40 && c.charCodeAt(cl - 1) === 41) {
  6660. cType = 1;
  6661. let t = c.charCodeAt(5);
  6662. if (t === 88 || t === 120) cType = 1 | 4;
  6663. if (t === 89 || t === 121) cType = 1 | 8;
  6664. } else if (c.startsWith('translate') && c.charCodeAt(10) === 40 && c.charCodeAt(cl - 1) === 41) {
  6665. cType = 2;
  6666. let t = c.charCodeAt(9);
  6667. if (t === 88 || t === 120) cType = 2 | 4;
  6668. if (t === 89 || t === 121) cType = 2 | 8;
  6669. }
  6670. let w = 0;
  6671. if (w = (cType === 5) ? 1 : (cType === 9) ? 2 : 0) {
  6672. let p = c.substring(7, cl - 1);
  6673. let q = p.length >= 1 ? parseFloat(p) : NaN;
  6674. if (typeof q === 'number' && !isNaNx(q)) {
  6675. transformType = w === 1 ? 'scaleX' : 'scaleY';
  6676. transformValue = q;
  6677. transformUnit = '';
  6678. transformTypeI = 1;
  6679. } else {
  6680. cType = 256;
  6681. }
  6682. } else if (w = (cType === 6) ? 1 : (cType === 10) ? 2 : 0) {
  6683. if (c.endsWith('px)')) {
  6684. let p = c.substring(11, cl - 3);
  6685. let q = p.length >= 1 ? parseFloat(p) : NaN;
  6686. if (typeof q === 'number' && !isNaNx(q)) {
  6687. transformType = w === 1 ? 'translateX' : 'translateY';
  6688. transformValue = q;
  6689. transformUnit = 'px';
  6690. transformTypeI = 2;
  6691. } else if (p === 'NaN') {
  6692. return;
  6693. }
  6694. } else {
  6695. cType = 256;
  6696. }
  6697. } else if (cType > 0) {
  6698. cType = 256;
  6699. }
  6700. }
  6701.  
  6702.  
  6703. if (cType === 256) {
  6704. console.log('[yt-js-engine-tamer] zoTransform undefined', c);
  6705. }
  6706.  
  6707. if (transformTypeI === 1) {
  6708. const q = Math.round(transformValue * steppingScaleN) / steppingScaleN;
  6709. const vz = toFixed2(q, 3);
  6710. c = `${transformType}(${vz})`;
  6711. const cv = aStyle.transform;
  6712. if (c === cv) return;
  6713. aStyle.transform = c;
  6714. } else if (transformTypeI === 2) {
  6715. const q = transformValue;
  6716. const vz = toFixed2(q, 1);
  6717. c = `${transformType}(${vz}${transformUnit})`;
  6718. const cv = aStyle.transform;
  6719. if (c === cv) return;
  6720. aStyle.transform = c;
  6721. } else { // eg empty
  6722. const cv = aStyle.transform;
  6723. if (!c && !cv) return;
  6724. else if (c === cv) return;
  6725. aStyle.transform = c;
  6726. }
  6727.  
  6728. };
  6729.  
  6730. const elmTransformTemp = new WeakMap();
  6731. const elmPropTemps = {
  6732. 'display': new WeakMap(),
  6733. 'width': new WeakMap(),
  6734. 'height': new WeakMap(),
  6735. 'outlineWidth': new WeakMap(),
  6736. 'position': new WeakMap(),
  6737. 'padding': new WeakMap(),
  6738. "cssText": new WeakMap(),
  6739. "right": new WeakMap(),
  6740. "left": new WeakMap(),
  6741. "top": new WeakMap(),
  6742. "bottom": new WeakMap(),
  6743. "transitionDelay": new WeakMap(),
  6744. "marginLeft": new WeakMap(),
  6745. "marginTop": new WeakMap(),
  6746. "marginRight": new WeakMap(),
  6747. "marginBottom": new WeakMap(),
  6748. }
  6749.  
  6750. const ns5 = Symbol();
  6751. const nextModify = (a, c, m, f, immediate) => {
  6752. const a_ = a;
  6753. const m_ = m;
  6754. const noKey = !m_.has(a_);
  6755. if (immediate || noKey) {
  6756. m_.set(a_, ns5);
  6757. f(a_, c);
  6758. noKey && nextBrowserTick_(() => {
  6759. const d = m_.get(a_);
  6760. if (d === undefined) return;
  6761. m_.delete(a_);
  6762. if (d !== ns5) f(a_, d);
  6763. });
  6764. } else {
  6765. m_.set(a_, c);
  6766. }
  6767. };
  6768.  
  6769. const set66 = new Set();
  6770. const log77 = new Map();
  6771. // const set77 = new Set(['top', 'left', 'bottom', 'right']); // caption positioning - immediate change
  6772.  
  6773. const modifiedFn = function (a, b, c, immediateChange = false) { // arrow function does not have function.prototype
  6774.  
  6775. // console.log(140000, a, b, c);
  6776. if (typeof c === 'number' && typeof b === 'string' && a instanceof HTMLElement) {
  6777. const num = c;
  6778. c = `${num}`;
  6779. if (c.length > 5) c = (num < 10 && num > -10) ? toFixed2(num, 3) : toFixed2(num, 1);
  6780. }
  6781.  
  6782. if (typeof b === 'string' && typeof c === 'string' && a instanceof HTMLElement) {
  6783.  
  6784. let elmPropTemp = null;
  6785.  
  6786. if (b === "transform") {
  6787. // div.ytp-hover-progress.ytp-hover-progress-light
  6788. // div.ytp-play-progress.ytp-swatch-background-color
  6789.  
  6790. nextModify(a, c, elmTransformTemp, zoTransform, immediateChange);
  6791. // let ast = null;
  6792. // if (a instanceof HTMLElement && !('__styleH745__' in a) && (ast = a.style)) {
  6793. // a.__styleH745__ = 1;
  6794. // Object.defineProperty(ast, 'left', hookLeftPD);
  6795. // }
  6796. return;
  6797.  
  6798. } else if (elmPropTemp = elmPropTemps[b]) {
  6799.  
  6800. // if (c.length > 5 && c.includes('.')) {
  6801. // console.log(123213, c)
  6802. // }
  6803.  
  6804. const b_ = b;
  6805. nextModify(a, c, elmPropTemp, (a, c) => {
  6806. const style = a.style;
  6807. const cv = style[b_];
  6808. if (!cv && !c) return;
  6809. if (cv === c) return;
  6810. style[b_] = c;
  6811. }, immediateChange);
  6812. return;
  6813.  
  6814. } else if (b === "outline-width") {
  6815.  
  6816. const b_ = 'outlineWidth';
  6817. elmPropTemp = elmPropTemps[b_];
  6818. nextModify(a, c, elmPropTemp, (a, c) => {
  6819. const style = a.style;
  6820. const cv = style[b_];
  6821. if (!cv && !c) return;
  6822. if (cv === c) return;
  6823. style[b_] = c;
  6824. }, immediateChange);
  6825. return;
  6826.  
  6827. } else if (b === 'maxWidth' || b === 'maxHeight') {
  6828. // I think these can be directly assigned.
  6829.  
  6830. const b_ = b;
  6831. const style = a.style;
  6832. const cv = style[b_];
  6833. if (!cv && !c) return;
  6834. if (cv === c) return;
  6835. style[b_] = c;
  6836. return;
  6837.  
  6838. } else {
  6839. // if(immediate && elmPropTemps[b]){
  6840. // console.log(5191, b)
  6841. // }
  6842. // caption-window
  6843. // margin-left max-height max-width font-family fill color font-size background white-space margin
  6844. // text-align background-color
  6845. // console.log(27304, a, b, c)
  6846. if (!set66.has(b)) {
  6847. set66.add(b);
  6848. nextBrowserTick_(() => {
  6849. if (!a.classList.contains('caption-window') && !a.classList.contains('ytp-caption-segment')) {
  6850. console.log(27304, a, b, c)
  6851. }
  6852. })
  6853. }
  6854. }
  6855.  
  6856. attrUpdateFn.call(this, a, b, c);
  6857. return;
  6858. } else if (typeof (b || 0) === 'object') {
  6859.  
  6860. // this is to fix caption positioning
  6861. // const immediate = (a.id || 0).length > 14 && (('top' in b) || ('left' in b) || ('right' in b) || ('bottom' in b));
  6862. const immediate = (a.id || 0).length > 14;
  6863. for (const [k, v] of Object.entries(b)) {
  6864. modifiedFn.call(this, a, k, v, immediate);
  6865. }
  6866.  
  6867. } else {
  6868.  
  6869. // a = circle, b = stroke-dasharray, c= "1.8422857142857143 32"
  6870. // ytp-ad-timed-pie-countdown-inner
  6871.  
  6872. if (typeof b === 'string') {
  6873.  
  6874. let m = log77.get(b);
  6875. if (!m) {
  6876. m = [];
  6877. console.log(27306, m);
  6878. log77.set(b, m);
  6879. }
  6880. m.push([a, b, c]);
  6881.  
  6882. } else {
  6883. console.log(27306, a, b, c);
  6884. }
  6885.  
  6886. attrUpdateFn.call(this, a, b, c);
  6887. return;
  6888. }
  6889.  
  6890. // console.log(130000, a, b, c);
  6891.  
  6892. };
  6893. g[k] = modifiedFn;
  6894.  
  6895.  
  6896. /*
  6897.  
  6898. g.zo = function(a, b, c) {
  6899. if ("string" === typeof b)
  6900. (b = yo(a, b)) && (a.style[b] = c);
  6901. else
  6902. for (var d in b) {
  6903. c = a;
  6904. var e = b[d]
  6905. , f = yo(c, d);
  6906. f && (c.style[f] = e)
  6907. }
  6908. }
  6909.  
  6910.  
  6911. */
  6912.  
  6913.  
  6914. }
  6915. }
  6916.  
  6917. if (fOption & 4) {
  6918. const keyuG = PERF_471489_ ? getuG(_yt_player) : null;
  6919.  
  6920. if (keyuG) {
  6921.  
  6922. k = keyuG;
  6923.  
  6924. const gk = g[k];
  6925. const gkp = gk.prototype;
  6926.  
  6927.  
  6928. /** @type { Map<string, WeakMap<any, any>> } */
  6929. const ntLogs = new Map();
  6930.  
  6931. if (typeof gkp.updateValue === 'function' && gkp.updateValue.length === 2 && !gkp.updateValue31) {
  6932.  
  6933. gkp.updateValue31 = gkp.updateValue;
  6934. gkp.updateValue = function (a, b) {
  6935. if (typeof a !== 'string') return this.updateValue31(a, b);
  6936.  
  6937. const element = this.element;
  6938. if (!(element instanceof HTMLElement)) return this.updateValue31(a, b);
  6939.  
  6940. let ntLog = ntLogs.get(a);
  6941. if (!ntLog) ntLogs.set(a, (ntLog = new WeakMap()));
  6942.  
  6943. let cache = ntLog.get(element);
  6944. if (cache && cache.value === b) {
  6945. return;
  6946. }
  6947. if (!cache) {
  6948. this.__oldValueByUpdateValue__ = null;
  6949. ntLog.set(element, cache = { value: b });
  6950. } else {
  6951. this.__oldValueByUpdateValue__ = cache.value;
  6952. cache.value = b;
  6953. }
  6954.  
  6955. return this.updateValue31(a, b);
  6956. }
  6957.  
  6958. /*
  6959. g.k.update = function(a) {
  6960. for (var b = g.u(Object.keys(a)), c = b.next(); !c.done; c = b.next())
  6961. c = c.value,
  6962. this.updateValue(c, a[c])
  6963. }
  6964. ;
  6965. g.k.updateValue = function(a, b) {
  6966. (a = this.Td["{{" + a + "}}"]) && wG(this, a[0], a[1], b)
  6967. }
  6968. */
  6969.  
  6970. }
  6971.  
  6972.  
  6973. }
  6974. }
  6975.  
  6976.  
  6977.  
  6978. })();
  6979.  
  6980.  
  6981. FIX_yt_player && !isChatRoomURL && FIX_SHORTCUTKEYS > 0 && (async () => {
  6982. // keyboard shortcut keys controller
  6983.  
  6984. const _yt_player = await _yt_player_observable.obtain();
  6985.  
  6986. if (!_yt_player || typeof _yt_player !== 'object') return;
  6987.  
  6988. keyboardController(_yt_player);
  6989.  
  6990. })();
  6991.  
  6992. FIX_yt_player && !isChatRoomURL && (async () => {
  6993. // timer scheduling
  6994.  
  6995. const _yt_player = await _yt_player_observable.obtain();
  6996.  
  6997. if (!_yt_player || typeof _yt_player !== 'object') return;
  6998.  
  6999. let keyZqQu = getZqQu(_yt_player);
  7000.  
  7001. if (!keyZqQu) return;
  7002.  
  7003. const g = _yt_player
  7004. let k = keyZqQu
  7005.  
  7006. const gk = g[k];
  7007. if (typeof gk !== 'function') return;
  7008. const gkp = gk.prototype;
  7009.  
  7010. const extractKeysZqQu = () => {
  7011.  
  7012.  
  7013. let _keyeC = '';
  7014. try {
  7015. gkp.stop.call(new Proxy({
  7016. isActive: () => { }
  7017. }, {
  7018. set(target, prop, value) {
  7019. if (value === 0) _keyeC = prop;
  7020. return true;
  7021. }
  7022. }));
  7023. } catch (e) { }
  7024. if (!_keyeC) return;
  7025. const keyeC = _keyeC;
  7026.  
  7027. let keyC = ''; // this.C = this.ST.bind(this)
  7028. let keyhj = ''; // 1000ms
  7029. try {
  7030. gkp.start.call(new Proxy({
  7031. stop: () => { },
  7032. [keyeC]: 0,
  7033. }, {
  7034. get(target, prop) {
  7035. if (prop in target) return target[prop];
  7036. if (!keyC) {
  7037. keyC = prop;
  7038. return null; // throw error
  7039. }
  7040. else if (!keyhj) {
  7041. keyhj = prop;
  7042. }
  7043.  
  7044. }
  7045. }));
  7046. } catch (e) {
  7047. if (!keyC || !keyhj) {
  7048. console.log(e)
  7049. }
  7050. }
  7051.  
  7052. if (!keyC || !keyhj) return;
  7053. let keyST = '';
  7054. let keyj = '';
  7055. let keyB = '';
  7056. let keyxa = '';
  7057.  
  7058. const possibleKs = new Set();
  7059.  
  7060. for (const [k, v] of Object.entries(gkp)) {
  7061. if (k === 'stop' || k === 'start' || k === 'isActive' || k === 'constructor' || k === keyeC || k === keyC || k === keyhj) {
  7062. continue;
  7063. }
  7064. if (typeof v === 'function') {
  7065. const m = /this\.(\w+)\.call\(this\.(\w+)\)/.exec(v + '');
  7066. if (m) {
  7067. keyST = k;
  7068. keyj = m[1];
  7069. keyB = m[2];
  7070. } else {
  7071. possibleKs.add(k);
  7072. }
  7073. }
  7074. }
  7075.  
  7076. if (!keyST || !keyj || !keyB) return;
  7077.  
  7078. for (const k of possibleKs) {
  7079. if (k === keyST || k === keyj || k === keyB) {
  7080. continue;
  7081. }
  7082. const v = gkp[k];
  7083. if (typeof v === 'function' && (v + '').includes(`this.stop();delete this.${keyj};delete this.${keyB}`)) {
  7084. keyxa = k;
  7085. }
  7086. }
  7087.  
  7088. return [keyeC, keyC, keyhj, keyST, keyj, keyB, keyxa];
  7089.  
  7090. }
  7091.  
  7092. const keys = extractKeysZqQu();
  7093. if (!keys || !keys.length) return;
  7094. const [keyeC, keyC, keyhj, keyST, keyj, keyB, keyxa] = keys; // [timerId, binded executorFn, 1000ms, executorFn, dataJ, objectB, disposeFn]
  7095.  
  7096. if (!keyeC || !keyC || !keyhj || !keyST || !keyj || !keyB || !keyxa) return;
  7097.  
  7098. let disposeKeys = null;
  7099.  
  7100. gkp[keyxa] = function () {
  7101. // dispose
  7102. if (!disposeKeys) {
  7103. disposeKeys = Object.getOwnPropertyNames(this).filter(key => {
  7104. if (key != keyeC && key != keyC && key != keyhj && key != keyST && key != keyj && key != keyB && key != keyxa) {
  7105. const t = typeof this[key];
  7106. return t === 'undefined' || t === 'object'
  7107. }
  7108. return false;
  7109. });
  7110. }
  7111. for (const key of disposeKeys) {
  7112. const v = this[key];
  7113. if ((v || 0).length >= 1) v.length = 0; // function (){if(this.fn)for(;this.fn.length;)this.fn.shift()()}
  7114. }
  7115. if (this[keyeC] > 0) this.stop();
  7116. this[keyj] = null;
  7117. this[keyB] = null;
  7118. };
  7119.  
  7120. gkp.start = function (a) {
  7121. if (this[keyeC] > 0) this.stop();
  7122. const delay = void 0 !== a ? a : this[keyhj];
  7123. this[keyeC] = window.setTimeout(this[keyC], delay);
  7124. };
  7125. gkp.stop = function () {
  7126. if (this[keyeC] > 0) {
  7127. window.clearTimeout(this[keyeC]);
  7128. this[keyeC] = 0;
  7129. }
  7130. };
  7131.  
  7132. gkp.isActive = function () {
  7133. return this[keyeC] > 0;
  7134. };
  7135.  
  7136. gkp[keyST] = function () {
  7137. this.stop(); // this[keyeC] = 0;
  7138. const fn = this[keyj];
  7139. const obj = this[keyB];
  7140. let skip = false;
  7141. if (!fn) skip = true;
  7142. else if (IGNORE_bufferhealth_CHECK && obj) {
  7143. let m;
  7144. if ((m = obj[keyC]) instanceof Map || (m = obj[keyj]) instanceof Map) {
  7145. if (m.has("bufferhealth")) skip = true;
  7146. }
  7147. }
  7148. if (!skip) {
  7149. fn.call(obj);
  7150. }
  7151. };
  7152.  
  7153.  
  7154.  
  7155.  
  7156. /*
  7157.  
  7158. g.k.eC = 0;
  7159. g.k.xa = function() {
  7160. g.Qu.Vf.xa.call(this);
  7161. this.stop();
  7162. delete this.j;
  7163. delete this.B
  7164. }
  7165. ;
  7166. g.k.start = function(a) {
  7167. this.stop();
  7168. this.eC = g.gg(this.C, void 0 !== a ? a : this.hj)
  7169. }
  7170. ;
  7171. g.k.stop = function() {
  7172. this.isActive() && g.Sa.clearTimeout(this.eC);
  7173. this.eC = 0
  7174. }
  7175. ;
  7176. g.k.isActive = function() {
  7177. return 0 != this.eC
  7178. }
  7179. ;
  7180. g.k.ST = function() {
  7181. this.eC = 0;
  7182. this.j && this.j.call(this.B)
  7183. }
  7184. ;
  7185. */
  7186.  
  7187.  
  7188.  
  7189.  
  7190. })();
  7191.  
  7192. FIX_Animation_n_timeline && (async () => {
  7193.  
  7194. const [timeline, Animation] = await Promise.all([timelineObservable.obtain(), animationObservable.obtain()]);
  7195.  
  7196. if (!timeline || !Animation) return;
  7197.  
  7198. const aniProto = Animation.prototype;
  7199. // aniProto.sequenceNumber = 0; // native YouTube engine bug - sequenceNumber is not set
  7200.  
  7201. const getXroto = (x) => {
  7202. try {
  7203. return x.__proto__;
  7204. } catch (e) { }
  7205. return null;
  7206. }
  7207. const timProto = getXroto(timeline);
  7208. if (!timProto) return;
  7209. if (
  7210. (
  7211. typeof timProto.getAnimations === 'function' && typeof timProto.play === 'function' &&
  7212. typeof timProto._discardAnimations === 'function' && typeof timProto._play === 'function' &&
  7213. typeof timProto._updateAnimationsPromises === 'function' && !timProto.nofCQ &&
  7214. typeof aniProto._updatePromises === 'function' && !aniProto.nofYH
  7215. )
  7216.  
  7217. ) {
  7218.  
  7219. timProto.nofCQ = 1;
  7220. aniProto.nofYH = 1;
  7221.  
  7222. const originalAnimationsWithPromises = ((_updateAnimationsPromises) => {
  7223.  
  7224.  
  7225. /*
  7226. v.animationsWithPromises = v.animationsWithPromises.filter(function (c) {
  7227. return c._updatePromises();
  7228. });
  7229. */
  7230.  
  7231. const p = Array.prototype.filter;
  7232.  
  7233. let res = null;
  7234. Array.prototype.filter = function () {
  7235.  
  7236. res = this;
  7237. return this;
  7238.  
  7239. };
  7240.  
  7241. _updateAnimationsPromises.call({});
  7242.  
  7243. Array.prototype.filter = p;
  7244.  
  7245. if (res && typeof res.length === 'number') {
  7246. /** @type {any[]} */
  7247. const _res = res;
  7248. return _res;
  7249. }
  7250.  
  7251.  
  7252. return null;
  7253.  
  7254.  
  7255.  
  7256.  
  7257. })(timProto._updateAnimationsPromises);
  7258.  
  7259. if (!originalAnimationsWithPromises || typeof originalAnimationsWithPromises.length !== 'number') return;
  7260.  
  7261. // console.log('originalAnimationsWithPromises', originalAnimationsWithPromises)
  7262.  
  7263. aniProto._updatePromises31 = aniProto._updatePromises;
  7264.  
  7265. /*
  7266. aniProto._updatePromises = function(){
  7267. console.log('eff',this._oldPlayState, this.playState)
  7268. return this._updatePromises31.apply(this, arguments)
  7269. }
  7270. */
  7271.  
  7272. aniProto._updatePromises = function () {
  7273. var oldPlayState = this._oldPlayState;
  7274. var newPlayState = this.playState;
  7275. // console.log('ett', oldPlayState, newPlayState)
  7276. if (newPlayState !== oldPlayState) {
  7277. this._oldPlayState = newPlayState;
  7278. if (this._readyPromise) {
  7279. if ("idle" == newPlayState) {
  7280. this._rejectReadyPromise();
  7281. this._readyPromise = void 0;
  7282. } else if ("pending" == oldPlayState) {
  7283. this._resolveReadyPromise();
  7284. } else if ("pending" == newPlayState) {
  7285. this._readyPromise = void 0;
  7286. }
  7287. }
  7288. if (this._finishedPromise) {
  7289. if ("idle" == newPlayState) {
  7290. this._rejectFinishedPromise();
  7291. this._finishedPromise = void 0;
  7292. } else if ("finished" == newPlayState) {
  7293. this._resolveFinishedPromise();
  7294. } else if ("finished" == oldPlayState) {
  7295. this._finishedPromise = void 0;
  7296. }
  7297. }
  7298. }
  7299. return this._readyPromise || this._finishedPromise;
  7300. };
  7301.  
  7302.  
  7303. let restartWebAnimationsNextTickFlag = false;
  7304.  
  7305. const looperMethodT = () => {
  7306.  
  7307. const runnerFn = (hRes) => {
  7308. var b = timeline;
  7309. b.currentTime = hRes;
  7310. b._discardAnimations();
  7311. if (0 == b._animations.length) {
  7312. restartWebAnimationsNextTickFlag = false;
  7313. } else {
  7314. getRafPromise().then(runnerFn);
  7315. }
  7316. }
  7317.  
  7318. const restartWebAnimationsNextTick = () => {
  7319. if (!restartWebAnimationsNextTickFlag) {
  7320. restartWebAnimationsNextTickFlag = true;
  7321. getRafPromise().then(runnerFn);
  7322. }
  7323. }
  7324.  
  7325. return { restartWebAnimationsNextTick }
  7326. };
  7327.  
  7328.  
  7329. const looperMethodN = () => {
  7330.  
  7331. const acs = document.createElement('a-f');
  7332. acs.id = 'a-f';
  7333.  
  7334. if (!document.getElementById('afscript')) {
  7335. const style = document.createElement('style');
  7336. style.id = 'afscript';
  7337. style.textContent = `
  7338. @keyFrames aF1 {
  7339. 0% {
  7340. order: 0;
  7341. }
  7342. 100% {
  7343. order: 1;
  7344. }
  7345. }
  7346. #a-f[id] {
  7347. visibility: collapse !important;
  7348. position: fixed !important;
  7349. display: block !important;
  7350. top: -100px !important;
  7351. left: -100px !important;
  7352. margin:0 !important;
  7353. padding:0 !important;
  7354. outline:0 !important;
  7355. border:0 !important;
  7356. z-index:-1 !important;
  7357. width: 0px !important;
  7358. height: 0px !important;
  7359. contain: strict !important;
  7360. pointer-events: none !important;
  7361. animation: 1ms steps(2, jump-none) 0ms infinite alternate forwards running aF1 !important;
  7362. }
  7363. `;
  7364. (document.head || document.documentElement).appendChild(style);
  7365. }
  7366.  
  7367. document.documentElement.insertBefore(acs, document.documentElement.firstChild);
  7368.  
  7369. const _onanimationiteration = function (evt) {
  7370. const hRes = evt.timeStamp;
  7371. var b = timeline;
  7372. b.currentTime = hRes;
  7373. b._discardAnimations();
  7374. if (0 == b._animations.length) {
  7375. restartWebAnimationsNextTickFlag = false;
  7376. acs.onanimationiteration = null;
  7377. } else {
  7378. acs.onanimationiteration = _onanimationiteration;
  7379. }
  7380.  
  7381. }
  7382.  
  7383.  
  7384.  
  7385. const restartWebAnimationsNextTick = () => {
  7386. if (!restartWebAnimationsNextTickFlag) {
  7387. restartWebAnimationsNextTickFlag = true;
  7388. acs.onanimationiteration = _onanimationiteration;
  7389.  
  7390. }
  7391. }
  7392.  
  7393. return { restartWebAnimationsNextTick }
  7394. };
  7395.  
  7396.  
  7397.  
  7398. const { restartWebAnimationsNextTick } = ('onanimationiteration' in document.documentElement) ? looperMethodN() : looperMethodT();
  7399.  
  7400.  
  7401. // console.log(571, timProto);
  7402. timProto._play = function (c) {
  7403. c = new Animation(c, this);
  7404. this._animations.push(c);
  7405. restartWebAnimationsNextTick();
  7406. c._updatePromises();
  7407. c._animation.play();
  7408. c._updatePromises();
  7409. return c
  7410. }
  7411.  
  7412. const animationsWithPromisesMap = new Set(originalAnimationsWithPromises);
  7413. originalAnimationsWithPromises.length = 0;
  7414. originalAnimationsWithPromises.push = null;
  7415. originalAnimationsWithPromises.splice = null;
  7416. originalAnimationsWithPromises.slice = null;
  7417. originalAnimationsWithPromises.indexOf = null;
  7418. originalAnimationsWithPromises.unshift = null;
  7419. originalAnimationsWithPromises.shift = null;
  7420. originalAnimationsWithPromises.pop = null;
  7421. originalAnimationsWithPromises.filter = null;
  7422. originalAnimationsWithPromises.forEach = null;
  7423. originalAnimationsWithPromises.map = null;
  7424.  
  7425.  
  7426. const _updateAnimationsPromises = () => {
  7427. animationsWithPromisesMap.forEach(c => {
  7428. if (!c._updatePromises()) animationsWithPromisesMap.delete(c);
  7429. });
  7430. /*
  7431. v.animationsWithPromises = v.animationsWithPromises.filter(function (c) {
  7432. return c._updatePromises();
  7433. });
  7434. */
  7435. }
  7436.  
  7437. timProto._updateAnimationsPromises31 = timProto._updateAnimationsPromises;
  7438.  
  7439. timProto._updateAnimationsPromises = _updateAnimationsPromises;
  7440.  
  7441. delete timProto._updateAnimationsPromises;
  7442. Object.defineProperty(timProto, '_updateAnimationsPromises', {
  7443. get() {
  7444. if (animationsWithPromisesMap.size === 0) return nilFn;
  7445. return _updateAnimationsPromises;
  7446. },
  7447. set(nv) {
  7448. delete this._updateAnimationsPromises;
  7449. this._updateAnimationsPromises = nv;
  7450. },
  7451. enumerable: true,
  7452. configurable: true,
  7453. });
  7454.  
  7455.  
  7456. let pdFinished = Object.getOwnPropertyDescriptor(aniProto, 'finished');
  7457. aniProto.__finished_native_get__ = pdFinished.get;
  7458. if (typeof pdFinished.get === 'function' && !pdFinished.set && pdFinished.configurable === true && pdFinished.enumerable === true) {
  7459.  
  7460.  
  7461. Object.defineProperty(aniProto, 'finished', {
  7462. get() {
  7463. this._finishedPromise || (!animationsWithPromisesMap.has(this) && animationsWithPromisesMap.add(this),
  7464. this._finishedPromise = new Promise((resolve, reject) => {
  7465. this._resolveFinishedPromise = function () {
  7466. resolve(this)
  7467. };
  7468. this._rejectFinishedPromise = function () {
  7469. reject({
  7470. type: DOMException.ABORT_ERR,
  7471. name: "AbortError"
  7472. })
  7473. };
  7474. }),
  7475. "finished" == this.playState && this._resolveFinishedPromise());
  7476. return this._finishedPromise
  7477. },
  7478. set: undefined,
  7479. enumerable: true,
  7480. configurable: true
  7481. });
  7482.  
  7483. }
  7484.  
  7485.  
  7486.  
  7487. let pdReady = Object.getOwnPropertyDescriptor(aniProto, 'ready');
  7488. aniProto.__ready_native_get__ = pdReady.get;
  7489. if (typeof pdReady.get === 'function' && !pdReady.set && pdReady.configurable === true && pdReady.enumerable === true) {
  7490.  
  7491. Object.defineProperty(aniProto, 'ready', {
  7492. get() {
  7493. this._readyPromise || (!animationsWithPromisesMap.has(this) && animationsWithPromisesMap.add(this),
  7494. this._readyPromise = new Promise((resolve, reject) => {
  7495. this._resolveReadyPromise = function () {
  7496. resolve(this)
  7497. };
  7498. this._rejectReadyPromise = function () {
  7499. reject({
  7500. type: DOMException.ABORT_ERR,
  7501. name: "AbortError"
  7502. })
  7503. };
  7504. }),
  7505. "pending" !== this.playState && this._resolveReadyPromise());
  7506. return this._readyPromise
  7507. },
  7508. set: undefined,
  7509. enumerable: true,
  7510. configurable: true
  7511. });
  7512.  
  7513. }
  7514.  
  7515.  
  7516. if (IGNORE_bindAnimationForCustomEffect && typeof aniProto._rebuildUnderlyingAnimation === 'function' && !aniProto._rebuildUnderlyingAnimation21 && aniProto._rebuildUnderlyingAnimation.length === 0) {
  7517.  
  7518. aniProto._rebuildUnderlyingAnimation21 = aniProto._rebuildUnderlyingAnimation;
  7519. const _rebuildUnderlyingAnimation = function () {
  7520. // if (isNaN(this._sequenceNumber)) return; // do not rebuild underlying animation if native animation is used.
  7521. this.effect && this.effect._onsample && (this.effect._onsample = null);
  7522. return this._rebuildUnderlyingAnimation21();
  7523. }
  7524. aniProto._rebuildUnderlyingAnimation = _rebuildUnderlyingAnimation;
  7525. // delete aniProto._rebuildUnderlyingAnimation;
  7526. // Object.defineProperty(aniProto, '_rebuildUnderlyingAnimation', {
  7527. // get() {
  7528. // if (isNaN(this._sequenceNumber)) return nilFn;
  7529. // return this._rebuildUnderlyingAnimation21;
  7530. // },
  7531. // set(nv) {
  7532. // delete this._rebuildUnderlyingAnimation;
  7533. // this._rebuildUnderlyingAnimation = nv;
  7534. // },
  7535. // enumerable: true,
  7536. // configurable: true
  7537. // });
  7538. }
  7539.  
  7540.  
  7541. /*
  7542.  
  7543.  
  7544. function f(c) {
  7545. var b = v.timeline;
  7546. b.currentTime = c;
  7547. b._discardAnimations();
  7548. 0 == b._animations.length ? d = !1 : requestAnimationFrame(f)
  7549. }
  7550. var h = window.requestAnimationFrame;
  7551. window.requestAnimationFrame = function(c) {
  7552. return h(function(b) {
  7553. v.timeline._updateAnimationsPromises();
  7554. c(b);
  7555. v.timeline._updateAnimationsPromises()
  7556. })
  7557. }
  7558. ;
  7559. v.AnimationTimeline = function() {
  7560. this._animations = [];
  7561. this.currentTime = void 0
  7562. }
  7563. ;
  7564. v.AnimationTimeline.prototype = {
  7565. getAnimations: function() {
  7566. this._discardAnimations();
  7567. return this._animations.slice()
  7568. },
  7569. _updateAnimationsPromises: function() {
  7570. v.animationsWithPromises = v.animationsWithPromises.filter(function(c) {
  7571. return c._updatePromises()
  7572. })
  7573. },
  7574. _discardAnimations: function() {
  7575. this._updateAnimationsPromises();
  7576. this._animations = this._animations.filter(function(c) {
  7577. return "finished" != c.playState && "idle" != c.playState
  7578. })
  7579. },
  7580. _play: function(c) {
  7581. c = new v.Animation(c,this);
  7582. this._animations.push(c);
  7583. v.restartWebAnimationsNextTick();
  7584. c._updatePromises();
  7585. c._animation.play();
  7586. c._updatePromises();
  7587. return c
  7588. },
  7589. play: function(c) {
  7590. c && c.remove();
  7591. return this._play(c)
  7592. }
  7593. };
  7594. var d = !1;
  7595. v.restartWebAnimationsNextTick = function() {
  7596. d || (d = !0,
  7597. requestAnimationFrame(f))
  7598. }
  7599. ;
  7600. var a = new v.AnimationTimeline;
  7601. v.timeline = a;
  7602. try {
  7603. Object.defineProperty(window.document, "timeline", {
  7604. configurable: !0,
  7605. get: function() {
  7606. return a
  7607. }
  7608. })
  7609. } catch (c) {}
  7610. try {
  7611. window.document.timeline = a
  7612. } catch (c) {}
  7613.  
  7614. */
  7615.  
  7616.  
  7617.  
  7618. /*
  7619.  
  7620. var g = window.getComputedStyle;
  7621. Object.defineProperty(window, "getComputedStyle", {
  7622. configurable: !0,
  7623. enumerable: !0,
  7624. value: function() {
  7625. v.timeline._updateAnimationsPromises();
  7626. var e = g.apply(this, arguments);
  7627. h() && (e = g.apply(this, arguments));
  7628. v.timeline._updateAnimationsPromises();
  7629. return e
  7630. }
  7631. });
  7632.  
  7633. */
  7634.  
  7635.  
  7636.  
  7637.  
  7638. }
  7639.  
  7640.  
  7641.  
  7642.  
  7643. })();
  7644.  
  7645. !isUrlInEmbed && Promise.resolve().then(() => {
  7646.  
  7647. // ==================================== FIX_avoid_incorrect_video_meta ====================================
  7648.  
  7649.  
  7650.  
  7651. class LimitedSizeSet extends Set {
  7652. constructor(n) {
  7653. super();
  7654. this.limit = n;
  7655. }
  7656.  
  7657. add(key) {
  7658. if (!super.has(key)) {
  7659. super.add(key);
  7660. let n = super.size - this.limit;
  7661. if (n > 0) {
  7662. const iterator = super.values();
  7663. do {
  7664. const firstKey = iterator.next().value; // Get the first (oldest) key
  7665. super.delete(firstKey); // Delete the oldest key
  7666. } while (--n > 0)
  7667. }
  7668. }
  7669. }
  7670.  
  7671. removeAdd(key) {
  7672. super.delete(key);
  7673. this.add(key);
  7674. }
  7675.  
  7676. }
  7677.  
  7678. // const wk3 = new WeakMap();
  7679.  
  7680. // let mtxVideoId = '';
  7681. // let aje3 = [];
  7682. const mfvContinuationRecorded = new LimitedSizeSet(8); // record all success continuation keys
  7683. const mfyContinuationIgnored = new LimitedSizeSet(8); // ignore continuation keys by copying the keys in the past
  7684. let mtzlastAllowedContinuation = ''; // the key stored at the last success; clear when scheduling changes
  7685. let mtzCount = 0; // the key keeps unchanged
  7686. // let mjtNextMainKey = '';
  7687. let mjtRecordedPrevKey = ''; // the key stored at the last success (no clear)
  7688. let mjtLockPreviousKey = ''; // the key before fetch() should be discarded. (uncertain continuation)
  7689. let mbCId322 = 0; // cid for delay fetchUpdatedMetadata
  7690. // let allowNoDelay322=false;
  7691. let mbDelayBelowNCalls = 0; // after N calls, by pass delay; reset when scheduling changes
  7692.  
  7693. let mpKey22 = ''; // last success continutation key & url pair
  7694. let mpUrl22 = ''; // last success continutation key & url pair
  7695. let mpKey21 = ''; // latest requested continutation key & url pair
  7696. let mpUrl21 = ''; // latest requested continutation key & url pair
  7697.  
  7698.  
  7699. async function sha1Hex(message) {
  7700. const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array
  7701. const hashBuffer = await crypto.subtle.digest("SHA-1", msgUint8); // hash the message
  7702. const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array
  7703. const hashHex = hashArray
  7704. .map((b) => b.toString(16).padStart(2, "0"))
  7705. .join(""); // convert bytes to hex string
  7706. return hashHex;
  7707. }
  7708.  
  7709. async function continuationLog(a, ...args) {
  7710. let b = a;
  7711. try {
  7712. if (advanceLogging) b = await sha1Hex(a);
  7713. let c = args.map(e => {
  7714. return e === a ? b : e
  7715. });
  7716. console.log(...c)
  7717. } catch (e) { console.warn(e) }
  7718. }
  7719.  
  7720. function copyPreviousContiuationToIgnored374(toClearRecorded) {
  7721.  
  7722.  
  7723. if (mfvContinuationRecorded.length > 0) {
  7724. for (const [e, d] of mfvContinuationRecorded) {
  7725. mfyContinuationIgnored.removeAdd(e);
  7726. }
  7727. toClearRecorded && mfvContinuationRecorded.clear();
  7728. }
  7729.  
  7730. }
  7731.  
  7732. function setup_ytTaskEmitterBehavior_TaskMgr374(taskMgr) {
  7733.  
  7734. const tmProto = taskMgr.constructor.prototype;
  7735. if (tmProto && typeof tmProto.addJob === 'function' && tmProto.addJob.length === 3 && typeof tmProto.cancelJob === 'function' && tmProto.cancelJob.length === 1) {
  7736.  
  7737. if (!tmProto.addJob714) {
  7738.  
  7739. tmProto.addJob714 = tmProto.addJob;
  7740.  
  7741. tmProto.addJob = function (a, b, c) {
  7742. const jobId = this.addJob714(a, b, c);
  7743. if (jobId > 0) {
  7744. // const ez = wk3.get(this);
  7745. // const dz = ez ? ez.data?.updatedMetadataEndpoint?.updatedMetadataEndpoint : null;
  7746. // aje3.push({mtx, jobId, a,b,c, element: this, dz, data: (ez?.data || null) })
  7747.  
  7748. this.__lastJobId863__ = jobId;
  7749. }
  7750. return jobId;
  7751. }
  7752.  
  7753. }
  7754.  
  7755. if (!tmProto.cancelJob714) {
  7756.  
  7757. tmProto.cancelJob714 = tmProto.cancelJob;
  7758.  
  7759. tmProto.cancelJob = function (a) {
  7760. const res = this.cancelJob714(a);
  7761. // if (a > 0) {
  7762. // for (const e of aje3) {
  7763. // if (e.jobId === a) e.cancelled = true;
  7764. // }
  7765. // }
  7766. return res;
  7767. }
  7768.  
  7769. }
  7770.  
  7771. }
  7772. }
  7773.  
  7774.  
  7775. const FIX_avoid_incorrect_video_meta_bool = FIX_avoid_incorrect_video_meta && isPrepareCachedV && check_for_set_key_order && !isChatRoomURL;
  7776.  
  7777.  
  7778. FIX_avoid_incorrect_video_meta_bool && whenCEDefined('ytd-video-primary-info-renderer').then(() => {
  7779. let dummy;
  7780. let cProto;
  7781. // let mc = 4;
  7782. // dummy = await observablePromise(() => {
  7783. // const r = document.querySelector('ytd-video-primary-info-renderer');
  7784. // if (!r) return;
  7785. // let cProto = insp(r).constructor.prototype;
  7786. // if (cProto.fetchUpdatedMetadata) return r;
  7787. // if (--mc < 0) return -1;
  7788. // return null;
  7789. // }).obtain();
  7790. dummy = document.createElement('ytd-video-primary-info-renderer');
  7791. if (!(dummy instanceof Element)) return;
  7792. // console.log(5022, dummy)
  7793. cProto = insp(dummy).constructor.prototype;
  7794.  
  7795. cProto.__getEmittorTaskMgr859__ = function () {
  7796. let taskMgr_ = null;
  7797. try {
  7798. taskMgr_ = (this.ytTaskEmitterBehavior || 0).getTaskManager() || null;
  7799. } catch (e) { }
  7800. return taskMgr_;
  7801. }
  7802. if (typeof cProto.fetchUpdatedMetadata === 'function' && cProto.fetchUpdatedMetadata.length === 1 && !cProto.fetchUpdatedMetadata717) {
  7803. // console.log(1234, cProto, cProto.is)
  7804. cProto.fetchUpdatedMetadata717 = cProto.fetchUpdatedMetadata;
  7805.  
  7806. let c_;
  7807. cProto.fetchUpdatedMetadata718 = function (a) {
  7808. // delay or immediate call the actual fetchUpdatedMetadata
  7809.  
  7810. let doImmediately = false;
  7811. if (a && typeof a === 'string' && mjtRecordedPrevKey && mjtRecordedPrevKey === mpKey22 && a === mpKey22 && (!pageSetupVideoId || pageSetupVideoId !== mpUrl22)) {
  7812.  
  7813. if (!pageSetupVideoId && videoPlayingY.videoId === mpUrl22) doImmediately = true;
  7814.  
  7815. } else if (typeof a !== 'string' || mbDelayBelowNCalls > 3 || !mpKey22 || (mpKey22 === a && mpKey22 !== mjtLockPreviousKey) || (mjtLockPreviousKey && mjtLockPreviousKey !== a)) {
  7816.  
  7817. doImmediately = true;
  7818.  
  7819. }
  7820.  
  7821. if (mbCId322) {
  7822. clearTimeout(mbCId322);
  7823. mbCId322 = 0;
  7824. }
  7825.  
  7826. if (doImmediately) return this.fetchUpdatedMetadata717(a);
  7827.  
  7828. let delay = mjtLockPreviousKey === a ? 8000 : 800;
  7829.  
  7830. mbCId322 = setTimeout(() => {
  7831. this.fetchUpdatedMetadata717(a);
  7832. }, delay);
  7833.  
  7834. console.log('[yt-js-engine-tamer]', '5190 delayed fetchUpdatedMetadata', delay);
  7835.  
  7836. }
  7837.  
  7838. cProto.fetchUpdatedMetadata = function (a) {
  7839.  
  7840. if (!pageSetupState) {
  7841. if (c_) clearTimeout(c_);
  7842. c_ = setTimeout(() => {
  7843. this.fetchUpdatedMetadata718(a);
  7844. }, 300);
  7845. return;
  7846. }
  7847.  
  7848. // pageSetupState == 0
  7849.  
  7850. try {
  7851.  
  7852. mbDelayBelowNCalls++;
  7853.  
  7854. if (arguments.length > 1 || !(a === undefined || (typeof a === 'string' && a))) {
  7855. console.warn("CAUTION: fetchUpdatedMetadata coding might have to be updated.");
  7856. }
  7857.  
  7858. // console.log('fum377', a)
  7859. if (typeof a === 'string' && mfyContinuationIgnored.has(a)) {
  7860. console.log('[yt-js-engine-tamer]', '5040 skip fetchUpdatedMetadata', a);
  7861. return;
  7862. }
  7863.  
  7864. if (!a && (this.data || 0).updatedMetadataEndpoint) {
  7865. if (mjtRecordedPrevKey && mjtLockPreviousKey !== mjtRecordedPrevKey) {
  7866. mjtLockPreviousKey = mjtRecordedPrevKey;
  7867. LOG_FETCHMETA_UPDATE && continuationLog(mjtLockPreviousKey, '5150 Lock Key', mjtLockPreviousKey);
  7868. }
  7869. // mjtNextMainKey = true;
  7870. mtzlastAllowedContinuation = '';
  7871. mtzCount = 0;
  7872. // allowNoDelay322 = false;
  7873. // fetch new metadata, cancel all previous continuations
  7874. copyPreviousContiuationToIgnored374(true);
  7875. } else if (typeof a === 'string') {
  7876. const videoPlayingId = videoPlayingY.videoId;
  7877.  
  7878. // if(mjtNextMainKey === true) mjtNextMainKey = a;
  7879.  
  7880. let update21 = !!pageSetupVideoId;
  7881. if (mpKey22 === a && mpUrl22 === videoPlayingId && mpUrl22 && videoPlayingId && (!pageSetupVideoId || pageSetupVideoId === videoPlayingId)) {
  7882. update21 = true;
  7883. } else if (mpKey22 === a && mpUrl22 !== pageSetupVideoId) {
  7884. LOG_FETCHMETA_UPDATE && continuationLog(mpKey22, '5060 mpUrl22 mismatched', mpKey22, mpUrl22, pageSetupVideoId || '(null)', videoPlayingId || '(null)');
  7885. return;
  7886. }
  7887. if (update21) {
  7888. mpKey21 = a;
  7889. mpUrl21 = pageSetupVideoId || videoPlayingId;
  7890. }
  7891.  
  7892. if (!mfvContinuationRecorded.has(a)) mfvContinuationRecorded.add(a);
  7893. }
  7894. LOG_FETCHMETA_UPDATE && continuationLog(a, '5180 fetchUpdatedMetadata\t', a, pageSetupVideoId || '(null)', videoPlayingY.videoId || '(null)');
  7895. // if (!pageSetupVideoId && typeof a === 'string' && a.length > 40) return; // ignore incorrect continuation
  7896. // if(a === mjtNextMainKey) allowNoDelay322 = false;
  7897. return this.fetchUpdatedMetadata718(a);
  7898.  
  7899. } catch (e) {
  7900. console.log('Code Error in fetchUpdatedMetadata', e);
  7901. }
  7902. return this.fetchUpdatedMetadata717(a)
  7903. }
  7904. }
  7905.  
  7906.  
  7907. if (typeof cProto.scheduleInitialUpdatedMetadataRequest === 'function' && cProto.scheduleInitialUpdatedMetadataRequest.length === 0 && !cProto.scheduleInitialUpdatedMetadataRequest717) {
  7908. // console.log(1234, cProto, cProto.is)
  7909. cProto.scheduleInitialUpdatedMetadataRequest717 = cProto.scheduleInitialUpdatedMetadataRequest;
  7910. let mJob = null;
  7911.  
  7912. cProto.scheduleInitialUpdatedMetadataRequest = function () {
  7913.  
  7914. try {
  7915.  
  7916. if (arguments.length > 0) {
  7917. console.warn("CAUTION: scheduleInitialUpdatedMetadataRequest coding might have to be updated.");
  7918. }
  7919. // mfy = mfv;
  7920.  
  7921. // mjtNextMainKey = '';
  7922. mtzlastAllowedContinuation = '';
  7923. mtzCount = 0;
  7924. if (mbCId322) {
  7925. clearTimeout(mbCId322);
  7926. mbCId322 = 0;
  7927. }
  7928. mbDelayBelowNCalls = 0;
  7929. // allowNoDelay322 = false;
  7930. copyPreviousContiuationToIgnored374(true);
  7931.  
  7932. const taskMgr = this.__getEmittorTaskMgr859__();
  7933. if (FIX_avoid_incorrect_video_meta_emitterBehavior && taskMgr && !taskMgr.addJob714 && taskMgr.addJob && taskMgr.cancelJob) setup_ytTaskEmitterBehavior_TaskMgr374(taskMgr);
  7934. if (FIX_avoid_incorrect_video_meta_emitterBehavior && taskMgr && !taskMgr.addJob714) {
  7935. console.log('[yt-js-engine-tamer]', 'scheduleInitialUpdatedMetadataRequest error 507');
  7936. }
  7937.  
  7938. // prevent depulicated schedule job by clearing previous JobId
  7939. if (taskMgr && typeof taskMgr.addLowPriorityJob === 'function' && taskMgr.addLowPriorityJob.length === 2 && typeof taskMgr.cancelJob === 'function' && taskMgr.cancelJob.length === 1) {
  7940.  
  7941. let res;
  7942.  
  7943. if (mJob) {
  7944. const job = mJob;
  7945. mJob = null;
  7946. console.log('cancelJob', job)
  7947. taskMgr.cancelJob(job); // clear previous [Interval Meta Update] job
  7948. // p.cancelJob(a,b);
  7949. }
  7950.  
  7951. // const updatedMetadataEndpoint = this.data?.updatedMetadataEndpoint?.updatedMetadataEndpoint
  7952.  
  7953. let pza = taskMgr.__lastJobId863__;
  7954. try { res = this.scheduleInitialUpdatedMetadataRequest717(); } catch (e) { }
  7955. let pzb = taskMgr.__lastJobId863__
  7956. if (pza !== pzb) {
  7957. mJob = pzb; // set [Interval Meta Update] jobId
  7958. }
  7959.  
  7960. // if (updatedMetadataEndpoint && updatedMetadataEndpoint.videoId) {
  7961. // mtxVideoId = updatedMetadataEndpoint.videoId || ''; // set the current target VideoId
  7962. // } else {
  7963. // mtxVideoId = ''; // sometimes updatedMetadataEndpoint is not ready
  7964. // }
  7965.  
  7966. return res;
  7967.  
  7968. } else {
  7969. console.log('[yt-js-engine-tamer]', 'scheduleInitialUpdatedMetadataRequest error 601');
  7970. }
  7971.  
  7972. } catch (e) {
  7973. console.log('Code Error in scheduleInitialUpdatedMetadataRequest', e);
  7974. }
  7975.  
  7976.  
  7977. return this.scheduleInitialUpdatedMetadataRequest717();
  7978. }
  7979. }
  7980.  
  7981.  
  7982. });
  7983.  
  7984. FIX_avoid_incorrect_video_meta_bool && promiseForYtActionCalled.then((ytAppDom) => {
  7985. let dummy;
  7986. let cProto;
  7987. dummy = ytAppDom;
  7988. if (!(dummy instanceof Element)) return;
  7989. cProto = insp(dummy).constructor.prototype;
  7990. if (typeof cProto.sendServiceAjax_ === 'function' && cProto.sendServiceAjax_.length === 4 && !cProto.sendServiceAjax717_) {
  7991. // console.log(1234, cProto, cProto.is);
  7992. // cProto.handleServiceRequest717_ = cProto.handleServiceRequest_;
  7993. // cProto.handleServiceRequest_ = function (a, b, c, d) {
  7994. // console.log(123401, arguments);
  7995. // return this.handleServiceRequest717_(a, b, c, d);
  7996. // }
  7997.  
  7998. // cProto.handleServiceRequest717_ = cProto.handleServiceRequest_;
  7999.  
  8000. // cProto.handleServiceRequest_ = function(a,b,c,d){
  8001. // console.log(59901, a?.is, b?.updatedMetadataEndpoint?.videoId, c?.continuation)
  8002. // if(a?.is === 'ytd-video-primary-info-renderer' && b?.updatedMetadataEndpoint?.videoId && c?.continuation && typeof c?.continuation ==='string'){
  8003. // console.log('mfv', c.continuation);
  8004. // mfv.add( c.continuation);
  8005. // }
  8006. // return this.handleServiceRequest717_(a,b,c,d);
  8007. // }
  8008.  
  8009. function extraArguments322(a, b, c) {
  8010. let is = (a || 0).is;
  8011. let videoId = ((b || 0).updatedMetadataEndpoint || 0).videoId;
  8012. let continuation = (c || 0).continuation;
  8013. if (typeof is !== 'string') is = null;
  8014. if (typeof videoId !== 'string') videoId = null;
  8015. if (typeof continuation !== 'string') continuation = null;
  8016. return { is, videoId, continuation };
  8017. }
  8018.  
  8019. cProto.sendServiceAjax717_ = cProto.sendServiceAjax_;
  8020. cProto.sendServiceAjax_ = function (a, b, c, d) {
  8021.  
  8022. // console.log(8001)
  8023. try {
  8024.  
  8025. const { is, videoId, continuation } = extraArguments322(a, b, c);
  8026.  
  8027. if ((videoId || continuation) && (is !== 'ytd-video-primary-info-renderer')) {
  8028. console.warn("CAUTION: sendServiceAjax_ coding might have to be updated.");
  8029. }
  8030.  
  8031. if (pageSetupVideoId && videoId && continuation) {
  8032. if (mpKey21 && mpUrl21 && mpKey21 === continuation && mpUrl21 !== pageSetupVideoId) {
  8033. mfyContinuationIgnored.removeAdd(continuation);
  8034. mfvContinuationRecorded.delete(continuation);
  8035. return;
  8036. }
  8037. }
  8038.  
  8039. if (mjtLockPreviousKey && mjtLockPreviousKey !== continuation && continuation) {
  8040. copyPreviousContiuationToIgnored374(false);
  8041. mfyContinuationIgnored.delete(continuation);
  8042. mfvContinuationRecorded.removeAdd(continuation);
  8043. mfyContinuationIgnored.removeAdd(mjtLockPreviousKey);
  8044. mfvContinuationRecorded.delete(mjtLockPreviousKey);
  8045. mjtLockPreviousKey = '';
  8046. }
  8047. // if (mjtNextMainKey === continuation) {
  8048. // copyPreviousContiuationToIgnored(false);
  8049. // mfyContinuationIgnored.delete(continuation);
  8050. // mfvContinuationRecorded.add(continuation);
  8051. // }
  8052.  
  8053.  
  8054. if (mfyContinuationIgnored && continuation) {
  8055. if (mfyContinuationIgnored.has(continuation)) {
  8056. LOG_FETCHMETA_UPDATE && continuationLog(continuation, '5260 matched01', continuation)
  8057. return;
  8058. }
  8059. }
  8060.  
  8061. // console.log(59902, a?.is, b,c,d)
  8062. // console.log(59903, a?.is, b?.updatedMetadataEndpoint?.videoId, c?.continuation)
  8063. if (is === 'ytd-video-primary-info-renderer' && videoId && continuation && !mfvContinuationRecorded.has(continuation)) {
  8064. // console.log('mfv377', continuation);
  8065. mfvContinuationRecorded.add(continuation);
  8066. }
  8067.  
  8068. // if (videoId) {
  8069. // if (!pageSetupVideoId) return; // ignore page not ready
  8070. // // if (mtxVideoId && b.updatedMetadataEndpoint.videoId !== mtxVideoId) return; // ignore videoID not matched
  8071. // if (videoId !== pageSetupVideoId) {
  8072. // return;
  8073. // }
  8074. // }
  8075.  
  8076. } catch (e) {
  8077. console.log('Coding Error in sendServiceAjax_', e)
  8078. }
  8079. // console.log(8002)
  8080. // console.log(123402, arguments);
  8081. // console.log(5162, 'a',a?.is,'b',b,'c',c,'d',d);
  8082.  
  8083. // console.log(5211, b?.updatedMetadataEndpoint?.kdkw33);
  8084. // if(b &&b.updatedMetadataEndpoint && !b.updatedMetadataEndpoint.kdkw33){
  8085. // b.updatedMetadataEndpoint = new Proxy(b.updatedMetadataEndpoint, {
  8086. // get(target, prop, receiver){
  8087. // console.log('xxs99', target.videoId, mtx)
  8088. // if(prop ==='kdkw33') return 1;
  8089. // console.log(3322, prop, target)
  8090. // if(prop === 'initialDelayMs') {
  8091. // throw new Error("ABCC");
  8092. // }
  8093. // return target[prop];
  8094. // },
  8095. // set(target, prop, value, receiver){
  8096.  
  8097. // if(prop ==='kdkw33') return true;
  8098. // target[prop]=value;
  8099. // return true;
  8100. // }
  8101. // });
  8102. // }
  8103. // console.log(5533, b?.updatedMetadataEndpoint?.kdkw33)
  8104. return this.sendServiceAjax717_(a, b, c, d);
  8105. }
  8106. }
  8107.  
  8108. function delayClearOtherKeys(lztContinuation) {
  8109. // // schedule delayed removal if mfyContinuationIgnored is not empty
  8110. // getRafPromise().then(() => {
  8111. // // assume the repeat continuation could be only for popstate which is triggered by user interaction
  8112. // // foreground page only
  8113.  
  8114. // });
  8115.  
  8116.  
  8117. if (lztContinuation !== mtzlastAllowedContinuation) return;
  8118. if (lztContinuation !== mpKey21 || lztContinuation !== mpKey22) return;
  8119. if (!mfyContinuationIgnored.size) return;
  8120. if (mfyContinuationIgnored.size > 1) {
  8121. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, 'delayClearOtherKeys, current = ', lztContinuation);
  8122. }
  8123. mfyContinuationIgnored.forEach((value, key) => {
  8124. if (key !== lztContinuation) {
  8125. mfyContinuationIgnored.delete(key);
  8126. LOG_FETCHMETA_UPDATE && continuationLog(key, 'previous continuation removed from ignored store', key);
  8127. }
  8128. });
  8129.  
  8130. }
  8131. if (typeof cProto.getCancellableNetworkPromise_ === 'function' && cProto.getCancellableNetworkPromise_.length === 5 && !cProto.getCancellableNetworkPromise717_) {
  8132. cProto.getCancellableNetworkPromise717_ = cProto.getCancellableNetworkPromise_;
  8133. cProto.getCancellableNetworkPromise_ = function (a, b, c, d, e) {
  8134.  
  8135. // console.log(8003)
  8136. try {
  8137.  
  8138.  
  8139. const { is, videoId, continuation } = extraArguments322(b, c, d);
  8140.  
  8141. if ((videoId || continuation) && (is !== 'ytd-video-primary-info-renderer')) {
  8142. console.warn("CAUTION: getCancellableNetworkPromise_ coding might have to be updated.");
  8143. }
  8144.  
  8145. if (pageSetupVideoId && videoId && continuation) {
  8146. if (mpKey21 && mpUrl21 && mpKey21 === continuation && mpUrl21 !== pageSetupVideoId) {
  8147. mfyContinuationIgnored.removeAdd(continuation);
  8148. mfvContinuationRecorded.delete(continuation);
  8149. return;
  8150. }
  8151. }
  8152.  
  8153. if (mjtLockPreviousKey && mjtLockPreviousKey !== continuation && continuation) {
  8154. copyPreviousContiuationToIgnored374(false);
  8155. mfyContinuationIgnored.delete(continuation);
  8156. mfvContinuationRecorded.removeAdd(continuation);
  8157. mfyContinuationIgnored.removeAdd(mjtLockPreviousKey);
  8158. mfvContinuationRecorded.delete(mjtLockPreviousKey);
  8159. mjtLockPreviousKey = '';
  8160. }
  8161.  
  8162. // if (mjtNextMainKey === continuation) {
  8163. // copyPreviousContiuationToIgnored(false);
  8164. // mfyContinuationIgnored.delete(continuation);
  8165. // mfvContinuationRecorded.add(continuation);
  8166. // }
  8167.  
  8168. const lztContinuation = continuation;
  8169.  
  8170. if (mfyContinuationIgnored && lztContinuation && typeof lztContinuation === 'string') {
  8171. if (mfyContinuationIgnored.has(lztContinuation)) {
  8172. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, '5360 matched02', lztContinuation)
  8173. return;
  8174. }
  8175. }
  8176.  
  8177. // if (videoId) {
  8178. // if (!pageSetupVideoId) return; // ignore page not ready
  8179. // // if (mtxVideoId && c.updatedMetadataEndpoint.videoId !== mtxVideoId) return; // ignore videoID not matched
  8180. // if (videoId !== pageSetupVideoId) {
  8181. // return;
  8182. // }
  8183. // }
  8184.  
  8185. if (typeof lztContinuation === 'string' && mtzlastAllowedContinuation !== lztContinuation) {
  8186. mtzlastAllowedContinuation = lztContinuation;
  8187. // console.log(70401, lztContinuation, mfyContinuationIgnored.size)
  8188.  
  8189. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, '5382 Continuation sets to\t', lztContinuation, `C${mtzCount}.R${mfvContinuationRecorded.size}.I${mfyContinuationIgnored.size}`);
  8190. mjtRecordedPrevKey = lztContinuation;
  8191. if (mjtLockPreviousKey === lztContinuation) mjtLockPreviousKey = '';
  8192. // if (mfyContinuationIgnored.size > 0) {
  8193. // delayClearOtherKeys(lztContinuation);
  8194. // }
  8195. mtzCount = 0;
  8196. // allowNoDelay322 = false;
  8197. } else if (typeof lztContinuation === 'string' && mtzlastAllowedContinuation && mtzlastAllowedContinuation === lztContinuation) {
  8198. // repeated
  8199. if (++mtzCount > 1e9) mtzCount = 1e4;
  8200. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, '5386 Same Continuation\t\t', lztContinuation, `C${mtzCount}.R${mfvContinuationRecorded.size}.I${mfyContinuationIgnored.size}`);
  8201.  
  8202. // if (mtzCount >= 3) allowNoDelay322 = true;
  8203. if (mtzCount >= 3 && mfyContinuationIgnored.size > 0) {
  8204. Promise.resolve(lztContinuation).then(delayClearOtherKeys).catch(console.warn);
  8205. }
  8206. if (mtzCount === 5) {
  8207. mfvContinuationRecorded.clear();
  8208. mfvContinuationRecorded.add(lztContinuation);
  8209. }
  8210.  
  8211. }
  8212.  
  8213. if (typeof lztContinuation === 'string' && lztContinuation && (pageSetupVideoId || videoPlayingY.videoId)) {
  8214. mpKey22 = lztContinuation;
  8215. mpUrl22 = pageSetupVideoId || videoPlayingY.videoId;
  8216. }
  8217.  
  8218. if (mbCId322) {
  8219. clearTimeout(mbCId322);
  8220. mbCId322 = 0;
  8221. }
  8222. } catch (e) {
  8223. console.log('Coding Error in getCancellableNetworkPromise_', e)
  8224. }
  8225.  
  8226. // console.log(8004)
  8227. // console.log(123403, arguments);
  8228. // if(c.updatedMetadataEndpoint) console.log(123404, pageSetupVideoId, JSON.stringify(c.updatedMetadataEndpoint))
  8229.  
  8230. // console.log(5163, a?.is,b,c,d,e);
  8231. return this.getCancellableNetworkPromise717_(a, b, c, d, e);
  8232. }
  8233. }
  8234. });
  8235.  
  8236. // ==================================== FIX_avoid_incorrect_video_meta ====================================
  8237.  
  8238.  
  8239. FIX_ytdExpander_childrenChanged && !isChatRoomURL && whenCEDefined('ytd-expander').then(() => {
  8240.  
  8241. let dummy;
  8242. let cProto;
  8243.  
  8244. dummy = document.createElement('ytd-expander');
  8245. cProto = insp(dummy).constructor.prototype;
  8246.  
  8247. if (fnIntegrity(cProto.initChildrenObserver, '0.48.21') && fnIntegrity(cProto.childrenChanged, '0.40.22')) {
  8248.  
  8249. cProto.initChildrenObserver14 = cProto.initChildrenObserver;
  8250. cProto.childrenChanged14 = cProto.childrenChanged;
  8251.  
  8252. cProto.initChildrenObserver = function () {
  8253. var a = this;
  8254. this.observer = new MutationObserver(function () {
  8255. a.childrenChanged()
  8256. }
  8257. );
  8258. this.observer.observe(this.content, {
  8259. subtree: !0,
  8260. childList: !0,
  8261. attributes: !0,
  8262. characterData: !0
  8263. });
  8264. this.childrenChanged()
  8265. }
  8266. ;
  8267. cProto.childrenChanged = function () {
  8268. if (this.alwaysToggleable) {
  8269. this.canToggle = this.alwaysToggleable;
  8270. } else if (!this.canToggleJobId) {
  8271. this.canToggleJobId = 1;
  8272. foregroundPromiseFn().then(() => {
  8273. this.canToggleJobId = 0;
  8274. this.calculateCanCollapse()
  8275. })
  8276. }
  8277. }
  8278.  
  8279. // console.log(cProto.initChildrenObserver)
  8280. console.debug('ytd-expander-fix-childrenChanged');
  8281.  
  8282. }
  8283.  
  8284. });
  8285.  
  8286.  
  8287. FIX_paper_ripple_animate && whenCEDefined('paper-ripple').then(() => {
  8288.  
  8289. let dummy;
  8290. let cProto;
  8291. dummy = document.createElement('paper-ripple');
  8292. cProto = insp(dummy).constructor.prototype;
  8293.  
  8294. if (fnIntegrity(cProto.animate, '0.74.5')) {
  8295.  
  8296.  
  8297. cProto.animate34 = cProto.animate;
  8298. cProto.animate = function () {
  8299. if (this._animating) {
  8300. var a;
  8301. const ripples = this.ripples;
  8302. for (a = 0; a < ripples.length; ++a) {
  8303. var b = ripples[a];
  8304. b.draw();
  8305. this.$.background.style.opacity = b.outerOpacity;
  8306. b.isOpacityFullyDecayed && !b.isRestingAtMaxRadius && this.removeRipple(b)
  8307. }
  8308. if ((this.shouldKeepAnimating || 0) !== ripples.length) {
  8309. if (!this._boundAnimate38) this._boundAnimate38 = this.animate.bind(this);
  8310. foregroundPromiseFn().then(this._boundAnimate38);
  8311. } else {
  8312. this.onAnimationComplete();
  8313. }
  8314. }
  8315. }
  8316.  
  8317. console.debug('FIX_paper_ripple_animate')
  8318.  
  8319. // console.log(cProto.animate)
  8320.  
  8321. }
  8322.  
  8323. });
  8324.  
  8325. if (FIX_doIdomRender) {
  8326.  
  8327. const xsetTimeout = function (f, d) {
  8328. if (xsetTimeout.m511 === 1 && !d) {
  8329. xsetTimeout.m511 = 2;
  8330. xsetTimeout.m568 = f;
  8331. } else {
  8332. return setTimeout.apply(window, arguments)
  8333. }
  8334.  
  8335. }
  8336.  
  8337. /**
  8338. *
  8339. IGb = function(a) {
  8340. var b, c = null == (b = a.requestAninmationFrameResolver) ? void 0 : b.promise;
  8341. c || (a.requestAninmationFrameResolver = new Vi,
  8342. c = a.requestAninmationFrameResolver.promise,
  8343. Da.requestAnimationFrame(function() {
  8344. var d;
  8345. null == (d = a.requestAninmationFrameResolver) || d.resolve();
  8346. a.requestAninmationFrameResolver = null
  8347. }));
  8348. return c
  8349. }
  8350.  
  8351.  
  8352. */
  8353.  
  8354. const xrequestAnimationFrame = function (f) {
  8355. const h = `${f}`;
  8356. if (h.startsWith("function(){setTimeout(function(){") && h.endsWith("})}")) {
  8357. let t = null;
  8358. xsetTimeout.m511 = 1;
  8359. f();
  8360. if (xsetTimeout.m511 === 2) {
  8361. t = xsetTimeout.m568;
  8362. xsetTimeout.m568 = null;
  8363. }
  8364. xsetTimeout.m511 = 0;
  8365. if (typeof t === 'function') {
  8366. foregroundPromiseFn().then(t);
  8367. }
  8368. } else if (h.includes("requestAninmationFrameResolver")) {
  8369. foregroundPromiseFn().then(f);
  8370. } else {
  8371. return requestAnimationFrame.apply(window, arguments);
  8372. }
  8373. }
  8374.  
  8375. let busy = false;
  8376. const doIdomRender = function () {
  8377.  
  8378. if (!this) return;
  8379. if (busy) {
  8380. return this.doIdomRender13(...arguments);
  8381. }
  8382. busy = true;
  8383. const { requestAnimationFrame, setTimeout } = window;
  8384. window.requestAnimationFrame = xrequestAnimationFrame;
  8385. window.setTimeout = xsetTimeout;
  8386. let r = this.doIdomRender13(...arguments);
  8387. window.requestAnimationFrame = requestAnimationFrame;
  8388. window.setTimeout = setTimeout;
  8389. busy = false;
  8390. return r;
  8391. };
  8392. 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']) {
  8393.  
  8394.  
  8395. whenCEDefined(ytTag).then(() => {
  8396.  
  8397. let dummy;
  8398. let cProto;
  8399. dummy = document.createElement(ytTag);
  8400. cProto = insp(dummy).constructor.prototype;
  8401.  
  8402. cProto.doIdomRender13 = cProto.doIdomRender;
  8403. cProto.doIdomRender = doIdomRender;
  8404.  
  8405. if (cProto.doIdomRender13 === cProto.templatingFn) cProto.templatingFn = doIdomRender;
  8406.  
  8407. console.debug('[yt-js-engine-tamer] FIX_doIdomRender', ytTag)
  8408.  
  8409.  
  8410.  
  8411. });
  8412.  
  8413. }
  8414.  
  8415. }
  8416.  
  8417.  
  8418.  
  8419.  
  8420. FIX_POPUP_UNIQUE_ID && whenCEDefined('ytd-popup-container').then(async () => {
  8421.  
  8422. const sMap = new Map();
  8423.  
  8424. const ZTa = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
  8425. const ZT = function () {
  8426. for (var a = Array(36), b = 0, c, d = 0; d < 36; d++)
  8427. d == 8 || d == 13 || d == 18 || d == 23 ? a[d] = "-" : d == 14 ? a[d] = "4" : (b <= 2 && (b = 33554432 + Math.random() * 16777216 | 0),
  8428. c = b & 15,
  8429. b >>= 4,
  8430. a[d] = ZTa[d == 19 ? c & 3 | 8 : c]);
  8431. return a.join("")
  8432. };
  8433.  
  8434.  
  8435. const popupContainerCollection = document.getElementsByTagName('ytd-popup-container');
  8436.  
  8437. const popupContainer = await observablePromise(() => {
  8438. return popupContainerCollection[0];
  8439. }).obtain();
  8440.  
  8441.  
  8442. let cProto;
  8443. cProto = insp(popupContainer).constructor.prototype;
  8444.  
  8445.  
  8446. if (!cProto || typeof cProto.handleOpenPopupAction !== 'function' || cProto.handleOpenPopupAction3868 || cProto.handleOpenPopupAction.length !== 2) {
  8447. console.log('FIX_POPUP_UNIQUE_ID NG')
  8448. return;
  8449. }
  8450. cProto.handleOpenPopupAction3868 = cProto.handleOpenPopupAction;
  8451.  
  8452. cProto.handleOpenPopupAction = function (a, b) {
  8453.  
  8454. if (typeof (a || 0) === 'object' && !a.__jOdQA__) {
  8455.  
  8456. a.__jOdQA__ = true;
  8457.  
  8458. try {
  8459.  
  8460. const h = this.hostElement;
  8461.  
  8462. if (h instanceof HTMLElement) {
  8463.  
  8464. const map = h.__skme44__ = h.__skme44__ || new Map();
  8465.  
  8466. let mKey = '';
  8467. const wKey = firstObjectKey(a);
  8468. const wObj = wKey ? a[wKey] : null;
  8469. if (wKey && wObj && typeof (wObj.popup || 0) === 'object') {
  8470. const pKey = firstObjectKey(wObj.popup)
  8471. const pObj = pKey ? wObj.popup[pKey] : null;
  8472. let contentKey = '';
  8473. let headerKey = '';
  8474.  
  8475. if (pObj && pObj.identifier && pObj.content && pObj.header) {
  8476. contentKey = firstObjectKey(pObj.content)
  8477. headerKey = firstObjectKey(pObj.header)
  8478. }
  8479. if (contentKey && headerKey) {
  8480.  
  8481. mKey = `${wKey}(popupType:${wObj.popupType},popup(${pKey}(content(${contentKey}:...),header(${headerKey}:...),identifer(surface:${pObj.identifier.surface}))))`
  8482.  
  8483. if (mKey) {
  8484.  
  8485. if (!wObj.uniqueId) {
  8486. for (let i = 0; i < 8; i++) {
  8487. wObj.uniqueId = ZT();
  8488. if (!sMap.has(wObj.uniqueId)) break;
  8489. }
  8490. }
  8491. const oId = wObj.uniqueId
  8492.  
  8493. let nId_ = map.get(mKey);
  8494. if (!nId_) {
  8495. map.set(mKey, nId_ = oId);
  8496. }
  8497.  
  8498. wObj.uniqueId = nId_ || wObj.uniqueId;
  8499.  
  8500. const nId = wObj.uniqueId
  8501.  
  8502. sMap.set(oId, nId);
  8503. sMap.set(nId, nId);
  8504.  
  8505. wObj.uniqueId = nId;
  8506. pObj.targetId = nId;
  8507. pObj.identifier.tag = nId;
  8508.  
  8509. if (oId !== nId) {
  8510. console.log('FIX_POPUP_UNIQUE_ID', oId, nId);
  8511. }
  8512.  
  8513. }
  8514.  
  8515. }
  8516. }
  8517.  
  8518. // console.log(12213, mKey, a, b, h)
  8519.  
  8520. }
  8521.  
  8522. } catch (e) {
  8523. console.warn(e)
  8524. }
  8525.  
  8526. try {
  8527.  
  8528. const results = searchNestedObject(a, (x) => {
  8529. if (typeof x === 'string' && x.length === 36) {
  8530. if (/[a-zA-Z\d]{8}-[a-zA-Z\d]{4}-[a-zA-Z\d]{4}-[a-zA-Z\d]{4}-[a-zA-Z\d]{12}/.test(x)) return true;
  8531. }
  8532. return false;
  8533. });
  8534. for (const [obj, key] of results) {
  8535. const oId = obj[key];
  8536. const nId = sMap.get(oId);
  8537. if (nId) obj[key] = nId;
  8538. }
  8539. } catch (e) {
  8540. console.warn(e)
  8541. }
  8542.  
  8543.  
  8544. }
  8545.  
  8546. return this.handleOpenPopupAction3868(...arguments)
  8547. }
  8548.  
  8549. console.log('FIX_POPUP_UNIQUE_ID OK')
  8550.  
  8551.  
  8552. });
  8553.  
  8554.  
  8555. // FIX_TRANSCRIPT_SEGMENTS && (async ()=>{
  8556.  
  8557.  
  8558. // })();
  8559.  
  8560. // FIX_TRANSCRIPT_SEGMENTS && whenCEDefined('ytd-transcript-search-panel-renderer').then(async () => {
  8561.  
  8562.  
  8563. // let dummy;
  8564. // let cProto;
  8565. // dummy = document.createElement('ytd-transcript-search-panel-renderer');
  8566. // cProto = insp(dummy).constructor.prototype;
  8567.  
  8568.  
  8569. // if (!cProto || typeof cProto.bodyChanged !== 'function' || cProto.bodyChanged1848 || cProto.bodyChanged.length !== 0) {
  8570. // console.log('FIX_TRANSCRIPT_SEGMENTS NG')
  8571. // return;
  8572. // }
  8573. // cProto.bodyChanged1848 = cProto.bodyChanged;
  8574.  
  8575. // const wmx = new WeakMap();
  8576.  
  8577. // const sb35 = Symbol();
  8578. // cProto.bodyChanged = function () {
  8579. // let a = null;
  8580. // try {
  8581. // a = this.getBodyRenderer();
  8582. // } catch (e) { }
  8583. // if (!a || !a.initialSegments) {
  8584. // a = this.data;
  8585. // if (a.body) a = a.body;
  8586. // if (a.transcriptSegmentListRenderer) a = a.transcriptSegmentListRenderer;
  8587. // }
  8588. // const a_ = a;
  8589. // const initialSegments = (a_ || 0).initialSegments;
  8590. // if (typeof (initialSegments || 0) === 'object' && initialSegments.length >= 1){
  8591. // ((async () => { })()).then(() => {
  8592.  
  8593. // const c = wmx.get(initialSegments);
  8594. // if (!c) {
  8595. // const d = translateFn(initialSegments);
  8596. // wmx.set(initialSegments, d);
  8597. // console.log('translated', d);
  8598. // wmx.set(d, d);
  8599. // a_.initialSegments = d;
  8600. // } else {
  8601. // a_.initialSegments = c;
  8602. // }
  8603.  
  8604.  
  8605. // }).then(() => {
  8606. // // this.bodyChanged1848();
  8607. // });
  8608.  
  8609. // }else{
  8610.  
  8611. // // return this.bodyChanged1848();
  8612. // }
  8613. // }
  8614.  
  8615. // console.log('FIX_TRANSCRIPT_SEGMENTS OK')
  8616.  
  8617.  
  8618.  
  8619.  
  8620. // });
  8621.  
  8622.  
  8623. });
  8624.  
  8625. });
  8626.  
  8627.  
  8628.  
  8629.  
  8630. if (isMainWindow) {
  8631.  
  8632. console.groupCollapsed(
  8633. "%cYouTube JS Engine Tamer",
  8634. "background-color: #EDE43B ; color: #000 ; font-weight: bold ; padding: 4px ;"
  8635. );
  8636.  
  8637.  
  8638.  
  8639. console.log("Script is loaded.");
  8640. console.log("This script changes the core mechanisms of the YouTube JS engine.");
  8641.  
  8642. console.log("This script is experimental and subject to further changes.");
  8643.  
  8644. console.log("This might boost your YouTube performance.");
  8645.  
  8646. console.log("CAUTION: This might break your YouTube.");
  8647.  
  8648.  
  8649. if (prepareLogs.length >= 1) {
  8650. console.log(" =========================================================================== ");
  8651.  
  8652. for (const msg of prepareLogs) {
  8653. console.log(msg)
  8654. }
  8655.  
  8656. console.log(" =========================================================================== ");
  8657. }
  8658.  
  8659. console.groupEnd();
  8660.  
  8661. }
  8662.  
  8663.  
  8664.  
  8665. })();