YouTube JS Engine Tamer

To enhance YouTube performance by modifying YouTube JS Engine

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址