YouTube JS Engine Tamer

To enhance YouTube performance by modifying YouTube JS Engine

目前為 2025-02-10 提交的版本,檢視 最新版本

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