YouTube JS Engine Tamer

修改 YouTube 的 JS 引擎以提升性能

当前为 2025-04-20 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name YouTube JS Engine Tamer
  3. // @name:ja YouTube JS Engine Tamer
  4. // @name:zh-TW YouTube JS Engine Tamer
  5. // @name:zh-CN YouTube JS Engine Tamer
  6. // @namespace UserScripts
  7. // @version 0.20.11
  8. // @match https://www.youtube.com/*
  9. // @match https://www.youtube-nocookie.com/embed/*
  10. // @match https://studio.youtube.com/live_chat*
  11. // @license MIT
  12. // @author CY Fung
  13. // @icon https://raw.githubusercontent.com/cyfung1031/userscript-supports/main/icons/yt-engine.png
  14. // @grant none
  15. // @require https://cdn.jsdelivr.net/gh/cyfung1031/userscript-supports@c2b707e4977f77792042d4a5015fb188aae4772e/library/nextBrowserTick.min.js
  16. // @run-at document-start
  17. // @unwrap
  18. // @inject-into page
  19. // @allFrames true
  20. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  21. //
  22. // @description To enhance YouTube performance by modifying YouTube JS Engine
  23. // @description:ja YouTubeのJSエンジンを変更してパフォーマンスを向上させる
  24. // @description:zh-TW 修改 YouTube 的 JS 引擎以提升效能
  25. // @description:zh-CN 修改 YouTube 的 JS 引擎以提升性能
  26. //
  27. // ==/UserScript==
  28.  
  29. (() => {
  30.  
  31. /** @type {WeakMapConstructor} */
  32. const WeakMap = window.WeakMapOriginal || window.WeakMap;
  33.  
  34. const NATIVE_CANVAS_ANIMATION = false; // for #cinematics
  35. const FIX_schedulerInstanceInstance = 2 | 4;
  36. const FIX_yt_player = true; // DONT CHANGE
  37. const FIX_Animation_n_timeline = true;
  38. const NO_PRELOAD_GENERATE_204 = false;
  39. const ENABLE_COMPUTEDSTYLE_CACHE = true;
  40. const NO_SCHEDULING_DUE_TO_COMPUTEDSTYLE = true;
  41. const CHANGE_appendChild = true; // discussions#236759
  42. const FIX_bind_self_this = false; // EXPERIMENTAL !!!!! this affect page switch after live ends
  43. const FIX_weakMap_weakRef = false; // EXPERIMENTAL !!!!! Might Incompatible to some userscripts (as the strong relationship is removed)
  44.  
  45. const FIX_error_many_stack = true; // should be a bug caused by uBlock Origin
  46. // const FIX_error_many_stack_keepAliveDuration = 200; // ms
  47. // const FIX_error_many_stack_keepAliveDuration_check_if_n_larger_than = 8;
  48.  
  49. const FIX_Iframe_NULL_SRC = false;
  50.  
  51. const IGNORE_bindAnimationForCustomEffect = true; // prevent `v.bindAnimationForCustomEffect(this);` being executed
  52.  
  53. const FIX_ytdExpander_childrenChanged = true;
  54. const FIX_paper_ripple_animate = true;
  55. const FIX_avoid_incorrect_video_meta = true; // omit the incorrect yt-animated-rolling-number
  56. const FIX_avoid_incorrect_video_meta_emitterBehavior = true;
  57.  
  58. const FIX_doIdomRender = true;
  59.  
  60. const FIX_Shady = true;
  61.  
  62. // [[ 2024.04.24 ]]
  63. const MODIFY_ShadyDOM_OBJ = true;
  64. // << if MODIFY_ShadyDOM_OBJ >>
  65. const WEAKREF_ShadyDOM = true;
  66. const OMIT_ShadyDOM_EXPERIMENTAL = 1 | 0; // 1 => enable; 2 => composedPath
  67. const OMIT_ShadyDOM_settings = 0 | 0 | 0; // 1: inUse; 2: handlesDynamicScoping; 4: force // {{ PRELIM TESTING PURPOSE }}
  68. // << end >>
  69.  
  70. const WEAK_REF_BINDING_CONTROL = 1 | 2; // 2 - conflict control with ShadyDOM weakref
  71.  
  72. const FIX_ytAction_ = true; // ytd-app
  73. const FIX_onVideoDataChange = false;
  74. // const FIX_onClick = true;
  75. const FIX_onStateChange = true;
  76. const FIX_onLoopRangeChange = true;
  77. // const FIX_maybeUpdateFlexibleMenu = true; // ytd-menu-renderer
  78. const FIX_VideoEVENTS_v2 = true; // true might cause bug in switching page
  79.  
  80. const ENABLE_discreteTasking = false; // removed since 0.20.0
  81. const FIX_stampDomArray_ = true; // changed since 0.20.0
  82. const FIX_stampDomArray = FIX_stampDomArray_ && typeof WeakRef === "function" && typeof FinalizationRegistry === "function";
  83.  
  84. const FIX_perfNow = true; // history state issue; see https://bugzilla.mozilla.org/show_bug.cgi?id=1756970
  85. const ENABLE_ASYNC_DISPATCHEVENT = false; // problematic
  86.  
  87. const FIX_Polymer_dom = true;
  88.  
  89. const SCRIPTLET_REMOVE_PRUNE_propNeedles = true; // brave scriptlet related
  90. const DEBUG_removePrune = false; // true for DEBUG
  91.  
  92. const FIX_XHR_REQUESTING = true;
  93.  
  94. const LOG_FETCHMETA_UPDATE = false; // for DEBUG
  95.  
  96. const IGNORE_bufferhealth_CHECK = false; // experimental; true will make "Stats for nerds" no info.
  97.  
  98. const DENY_requestStorageAccess = true; // remove document.requestStorageAccess
  99. const DISABLE_IFRAME_requestStorageAccess = true; // no effect if DENY_requestStorageAccess is true
  100.  
  101. const DISABLE_COOLDOWN_SCROLLING = true; // YT cause scroll hang in MacOS
  102.  
  103. const FIX_removeChild = true;
  104. const FIX_fix_requestIdleCallback_timing = true;
  105.  
  106. const HOOK_CSSPD_LEFT = true; // global css hack for style.left
  107. const FORCE_NO_REUSEABLE_ELEMENT_POOL = true;
  108.  
  109. const FIX_TRANSCRIPT_SEGMENTS = true; // Based on Tabview Youtube's implementation
  110. // const DO_createStampDomArrayFnE1_ = true; // added in 2025.02.11 - to improve stampDom responsiveness
  111. // const DO_createStampDomArrayFnE1_noConstraintE = true;
  112. // const DO_createStampDomArrayFnE1_nativeAppendD = true;
  113. // const DO_createStampDomArrayFnF1_ = true;
  114. // const DO_createStampDomArray_STRICT_FULFILLMENT = true; // avoid issues; can be changed to false
  115. // const DO_createStampDomArray_DEBUG = false;
  116.  
  117. const FIX_POPUP_UNIQUE_ID = true; // currently only for channel about popup;
  118.  
  119. // ----------------------------- POPUP UNIQUE ID ISSUE -----------------------------
  120. // example. https://www.youtube.com/channel/UCgPev1KKSCMbnNRsvN83Hag/about
  121. // first tp-yt-paper-dialog: show once the page is loaded.
  122. // second tp-yt-paper-dialog: click "...more"
  123. // third tp-yt-paper-dialog: click "... and 3 more links"
  124. // check with document.querySelectorAll('ytd-popup-container tp-yt-paper-dialog').length
  125. // currently, uniqueId is preassigned by the network resolveCommand.
  126. // so don't modify the source side, just modify the display side (popup display) via handleOpenPopupAction
  127. // other related functions e.g. handleClosePopupCommand_, getAndMaybeCreatePopup_, handleClosePopupAction_, getAndMaybeCreatePopup_
  128.  
  129. // handleOpenPopupAction -> createCacheKey
  130. // handleClosePopupAction_ -> createCacheKey
  131. // handleGetPopupOpenedAction_ -> createCacheKey
  132. // getAndMaybeCreatePopup_ -> createCacheKey
  133. // closePopup -> createCacheKey
  134.  
  135. // yt-close-popup-command -> handleClosePopupCommand_
  136.  
  137. // ensurePopup_ -> getAndMaybeCreatePopup_
  138.  
  139. // yt-close-popup-action -> handleClosePopupAction_
  140. // closePopup -> handleClosePopupAction_
  141. // handleOpenPopupAction -> handleClosePopupAction_
  142. // handleClosePopupCommand_ -> handleClosePopupAction_
  143. // closeSheet -> handleClosePopupAction_("yt-sheet-view-model")
  144.  
  145. // yt-open-popup-action -> handleOpenPopupAction
  146.  
  147.  
  148. // yt-close-popup-action -> handleClosePopupAction_ -> createCacheKey
  149. // yt-close-popup-command -> handleClosePopupCommand_ -> handleClosePopupAction_ -> createCacheKey
  150.  
  151. // Experimental flag "ytpopup_disable_default_html_caching" is disabled by default.
  152. // Not sure enabling it can make GC or not (Yt Components are usually not GC-able)
  153. // ----------------------------- POPUP UNIQUE ID ISSUE -----------------------------
  154.  
  155.  
  156. const FIX_DOM_IF_REPEAT = true; // semi-experimental (added in 0.17.0)
  157. const FIX_DOM_IF_TEMPLATE = true;
  158. // const FIX_DOM_REPEAT_TEMPLATE = true; // to be implemented
  159. const FIX_DOM_IFREPEAT_RenderDebouncerChange = false; // semi-experimental (added in 0.17.0) // found buggy for chat ticker sizing
  160. const DEBUG_DBR847 = false;
  161. const DEBUG_xx847 = false;
  162. const FIX_DOM_IFREPEAT_RenderDebouncerChange_SET_TO_PROPNAME = true; // default true. false might be required for future change
  163. const DEBUG_renderDebounceTs = false;
  164.  
  165. const FIX_ICON_RENDER = true;
  166.  
  167. const FIX_VIDEO_PLAYER_MOUSEHOVER_EVENTS = true; // avoid unnecessary reflows due to cursor moves on the web player.
  168.  
  169. /*
  170.  
  171. FIX_DOM_IFREPEAT_RenderDebouncerChange
  172.  
  173. avoid Polymer.flush
  174. // https://www.youtube.com/s/desktop/26a583e4/jsbin/live_chat_polymer.vflset/live_chat_polymer.js
  175.  
  176. var Is = function() {
  177. do {
  178. var a = window.ShadyDOM && ShadyDOM.flush();
  179. window.ShadyCSS && window.ShadyCSS.ScopingShim && window.ShadyCSS.ScopingShim.flush();
  180. var b = NNa()
  181. } while (a || b)
  182. };
  183.  
  184. , NNa = function() {
  185. var a = !!ts.size;
  186. ts.forEach(function(b) {
  187. try {
  188. b.flush()
  189. } catch (c) {
  190. setTimeout(function() {
  191. throw c
  192. })
  193. }
  194. });
  195. return a
  196. };
  197.  
  198. // why flush twice after all ts are completed? (!!ts.size => true => loop again)
  199. // this coding logic should be incorrect (mistake).
  200.  
  201. */
  202.  
  203.  
  204.  
  205. // ----------------------------- Shortkey Keyboard Control -----------------------------
  206. // dependency: FIX_yt_player
  207.  
  208. const FIX_SHORTCUTKEYS = 2; // 0 - no fix; 1 - basic fix; 2 - advanced fix
  209. // [0] no fix - not recommended
  210. // [1] basic fix - just fix the global focus detection variable
  211. // [2] advanced fix - call the shortcut actions directly, auto foucs change, direct control of spacebar behavior, etc
  212. // (note) 0 or 1 if you find conflict with other userscripts/plugin
  213.  
  214. const CHANGE_SPEEDMASTER_SPACEBAR_CONTROL = 0; // 0 - disable; 1 - force true; 2 - force false
  215. const USE_IMPROVED_PAUSERESUME_UNDER_NO_SPEEDMASTER = true; // only for SPEEDMASTER = false & FIX_SHORTCUTKEYS = 2
  216.  
  217. const PROP_OverReInclusion_AVOID = true;
  218. const PROP_OverReInclusion_DEBUGLOG = false;
  219. const PROP_OverReInclusion_LIST = new Set([
  220. 'hostElement72',
  221. 'parentComponent72',
  222. 'localVisibilityObserver_72',
  223. 'cachedProviderNode_72',
  224. '__template72',
  225. '__templatizeOwner72',
  226. '__templateInfo72',
  227. '__dataHost72',
  228. '__CE_shadowRoot72',
  229. 'elements_72',
  230.  
  231. 'ky36',
  232. 'kz62',
  233. 'm822',
  234.  
  235.  
  236.  
  237. // To be reviewed.
  238.  
  239. // chat messages
  240. 'disabled', 'allowedProps',
  241. 'filledButtonOverrides', 'openPopupConfig', 'supportsInlineActionButtons', 'allowedProps',
  242.  
  243. 'dimension', 'loadTime', 'pendingPaint',
  244.  
  245. 'countdownDurationMs', 'countdownMs', 'lastCountdownTimeMs', 'rafId', 'playerProgressSec', 'detlaSincePausedSecs', 'behaviorActionMap', 'selected', 'maxLikeCount', 'maxReplyCount', 'isMouseOver',
  246.  
  247. 'respectLangDir', 'noEndpoints',
  248.  
  249.  
  250. 'objectURL',
  251. 'buttonOverrides', 'queuedMessages',
  252. 'STEP', 'BLOCK_ON', 'MIN_PROGESS', 'MAX_PROGESS',
  253. 'DISMISSED_CONTENT_KEYSPACE', 'followUpDialogPromise', 'followUpDialogPromiseResolve', 'followUpDialogPromiseReject',
  254. 'hoverJobId', 'JSC$14573_touched',
  255.  
  256.  
  257. // tbc
  258. 'toggleable', 'isConnected',
  259. 'scrollDistance', 'dragging', 'dragMouseStart', 'dragOffsetStart', 'containerWidthDiff',
  260. 'disableDeselectEvent',
  261. 'emojiSize',
  262.  
  263. 'buttonOverride',
  264. 'shouldUseStickyPreferences', 'longPressTimeoutId',
  265.  
  266. // others
  267. 'observeVisibleOption', 'observeHiddenOption', 'observePrescanOption', 'visibilityMonitorKeys',
  268. // 'filledButtonOverrides', 'openPopupConfig', 'supportsInlineActionButtons',
  269. 'observeVisibleOption', 'observeHiddenOption', 'observePrescanOption', 'visibilityMonitorKeys',
  270. // 'dimension', 'loadTime', 'pendingPaint',
  271. // 'disabled', 'allowedProps',
  272.  
  273.  
  274. // 'enableMssLazyLoad', 'popupContainerConfig', 'actionRouterNode', 'actionRouterIsRoot', 'actionMap', 'dynamicActionMap',
  275. // 'actionMap',
  276.  
  277. // 'sharedTooltipPosition', 'sharedTooltipAnimationDelay', 'disableEmojiPickerIncrementalLoading', 'useResolveCommand', 'activeRequest', 'popoutWindowCheckIntervalId', 'supportedTooltipTargets', 'closeActionPanelTimerId', 'delayCloseActionPanelTimerId', 'tooltipTimerIds', 'queuedTooltips', 'isPopupConfigReady', 'popoutWindow', 'actionMap',
  278.  
  279. 'clearTimeout',
  280. 'switchTemplateAtRegistration', 'hasUnmounted',
  281. 'switchTemplateAtRegistration', 'stopKeyboardEventPropagation',
  282. 'tangoConfiguration',
  283. 'itemIdToDockDurationMap',
  284. 'actionMap',
  285.  
  286. 'emojiManager', 'inputMethodEditorActive', 'suggestionIndex', 'JSC$10745_lastSuggestionRange',
  287. 'actionMap', 'asyncHandle', 'shouldAnimateIn', 'lastFrameTimestamp', 'scrollClampRaf',
  288. 'scrollRatePixelsPerSecond', 'scrollStartTime', 'scrollStopHandle'
  289.  
  290. // 'buttonOverrides', 'queuedMessages', 'clearTimeout', 'actionMap',
  291. // 'stopKeyboardEventPropagation', 'emojiSize',
  292. // 'switchTemplateAtRegistration', 'hasUnmounted',
  293. // 'buttonOverrides', 'queuedMessages', 'clearTimeout', 'actionMap',
  294. // 'isReusable', 'tangoConfiguration',
  295. // 'itemIdToDockDurationMap', 'bottomAlignMessages', 'actionMap',
  296. // */
  297.  
  298. ]);
  299.  
  300.  
  301. // const CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE = false; // NO USE; TO BE REVIEWED
  302.  
  303. // ----------------------------- Shortkey Keyboard Control -----------------------------
  304.  
  305. /*
  306. window.addEventListener('edm',()=>{
  307. let p = [...this.onerror.errorTokens][0].token; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })()
  308. });
  309.  
  310. window.addEventListener('edn',()=>{
  311. let p = [...this.onerror.errorTokens][0].token+"X"; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })()
  312. });
  313. window.addEventListener('edr',()=>{
  314. let p = '123'; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })()
  315. });
  316. */
  317.  
  318. // only for macOS with Chrome/Firefox 100+
  319. const advanceLogging = typeof AbortSignal !== 'undefined' && typeof (AbortSignal || 0).timeout === 'function' && typeof navigator !== 'undefined' && /\b(Macintosh|Mac\s*OS)\b/i.test((navigator || 0).userAgent || '');
  320.  
  321. const win = this instanceof Window ? this : window;
  322.  
  323. // Create a unique key for the script and check if it is already running
  324. const hkey_script = 'jswylcojvzts';
  325. if (win[hkey_script]) throw new Error('Duplicated Userscript Calling'); // avoid duplicated scripting
  326. win[hkey_script] = true;
  327.  
  328.  
  329. // const [setTimeoutX0, clearTimeoutX0] = [setTimeout, clearTimeout];
  330.  
  331. let BY_PASS_KEYBOARD_CONTROL = false;
  332.  
  333.  
  334. // const setImmediate = ((self || 0).jmt || 0).setImmediate;
  335. /** @type {(f: ()=>{})=>{}} */
  336. const nextBrowserTick_ = nextBrowserTick;
  337. if (typeof nextBrowserTick_ !== "function" || (nextBrowserTick_.version || 0) < 2) {
  338. console.log('nextBrowserTick is not found.');
  339. return;
  340. }
  341.  
  342. let p59 = 0;
  343.  
  344. const Promise = (async () => { })().constructor;
  345.  
  346. const PromiseExternal = ((resolve_, reject_) => {
  347. const h = (resolve, reject) => { resolve_ = resolve; reject_ = reject };
  348. return class PromiseExternal extends Promise {
  349. constructor(cb = h) {
  350. super(cb);
  351. if (cb === h) {
  352. /** @type {(value: any) => void} */
  353. this.resolve = resolve_;
  354. /** @type {(reason?: any) => void} */
  355. this.reject = reject_;
  356. }
  357. }
  358. };
  359. })();
  360.  
  361. let ttpHTML = (s) => {
  362. ttpHTML = s => s;
  363. if (typeof trustedTypes !== 'undefined' && trustedTypes.defaultPolicy === null) {
  364. let s = s => s;
  365. trustedTypes.createPolicy('default', { createHTML: s, createScriptURL: s, createScript: s });
  366. }
  367. return s;
  368. }
  369.  
  370.  
  371. /** @type { typeof HTMLElement } */
  372. const HTMLElement_ = Reflect.getPrototypeOf(HTMLTitleElement);
  373. const nativeAppendE = HTMLElement_.prototype.append;
  374. const nativeRemoveE = HTMLElement_.prototype.remove;
  375. const DocumentFragment_ = DocumentFragment;
  376. const nativeAppendD = DocumentFragment_.prototype.append;
  377. const Node_ = Node;
  378.  
  379. /**
  380. @param {number} x
  381. @param {number} d */
  382. const toFixed2 = (x, d) => {
  383. let t = x.toFixed(d);
  384. let y = `${+t}`;
  385. return y.length > t.length ? t : y;
  386. }
  387.  
  388.  
  389. const isChatRoomURL = location.pathname.startsWith('/live_chat');
  390.  
  391.  
  392. const TRANSLATE_DEBUG = false;
  393.  
  394.  
  395. function getTranslate() {
  396.  
  397. pLoad.then(() => {
  398.  
  399. let nonce = document.querySelector('style[nonce]');
  400. nonce = nonce ? nonce.getAttribute('nonce') : null;
  401. const st = document.createElement('style');
  402. if (typeof nonce === 'string') st.setAttribute('nonce', nonce);
  403. st.textContent = ".yt-formatted-string-block-line{display:block;}";
  404. let parent;
  405. if (parent = document.head) parent.appendChild(st);
  406. else if (parent = (document.body || document.documentElement)) parent.insertBefore(st, parent.firstChild);
  407.  
  408. });
  409.  
  410. const snCache = new Map();
  411.  
  412. if (TRANSLATE_DEBUG) {
  413. console.log(11)
  414. }
  415.  
  416. /** @type {(str: string?) => string} */
  417. function _snippetText(str) {
  418. // str can be underfinded
  419. if (!str || typeof str !== 'string') return '';
  420. let res = snCache.get(str);
  421. if (res === undefined) {
  422. let b = false;
  423. res = str.replace(/[\s\u3000\u200b]*[\u200b\xA0\x20\n]+[\s\u3000\u200b]*/g, (m) => {
  424. b = true;
  425. return m.includes('\n') ? '\n' : m.replace(/\u200b/g, '').replace(/[\xA0\x20]+/g, ' ');
  426. });
  427. res = res.replace(/^[\s\u3000]+|[\u3000\s]+$/g, () => {
  428. b = true;
  429. return '';
  430. });
  431. if (b) {
  432. snCache.set(str, res);
  433. snCache.set(res, null);
  434. } else {
  435. res = null;
  436. snCache.set(str, null);
  437. }
  438. }
  439. return res === null ? str : res;
  440. }
  441.  
  442. /** @type {(snippet: Object) => string} */
  443. function snippetText(snippet) {
  444. let runs = snippet.runs;
  445. const n = runs.length;
  446. if (n === 1) return _snippetText(runs[0].text);
  447. let res = new Array(n);
  448. let ci = 0;
  449. for (const s of runs) {
  450. res[ci++] = _snippetText(s.text);
  451. }
  452. return res.join('\n');
  453. }
  454.  
  455. const _DEBUG_szz = (t) => t.map(x => {
  456. const tsr = x.transcriptSegmentRenderer;
  457. return ({
  458. t: tsr.snippet.runs.map(x => x.text).join('//'),
  459. a: tsr.startMs,
  460. b: tsr.endMs
  461. });
  462. });
  463.  
  464. const fixRuns = (runs) => {
  465. if (runs.length === 1 && runs[0]?.text?.includes('\n')) {
  466. // https://www.youtube.com/watch?v=dmHJJ5k_G-A
  467. const text = runs[0].text;
  468. const nlc = text.includes('\r\n') ? '\r\n' : text.includes('\n\r') ? '\n\r' : text.includes('\r') ? '\r' : '\n';
  469. const s = text.split(nlc);
  470. let bi = 0;
  471. runs.length = s.length;
  472. for (const text of s) {
  473. runs[bi++] = { ...runs[0], text, ...{blockLine: true} };
  474. }
  475. }
  476. for (const s of runs) {
  477. s.text = _snippetText(s.text);
  478. }
  479. }
  480.  
  481. function translate(initialSegments) {
  482. // 2023.07.13 - fix initialSegments with transcriptSectionHeaderRenderer
  483.  
  484. if (!initialSegments) return initialSegments;
  485.  
  486. if (TRANSLATE_DEBUG) {
  487. console.log(12);
  488. Promise.resolve(JSON.stringify(initialSegments)).then((r) => {
  489. let obj = JSON.parse(r);
  490. console.log(7558, 1, obj)
  491. return obj;
  492. }).then(p => {
  493. let obj = _DEBUG_szz(p)
  494. console.log(7558, 2, obj)
  495. })
  496. }
  497.  
  498.  
  499. //let mapRej = new WeakSet();
  500.  
  501. const n1 = initialSegments.length;
  502. if (!n1) return fRes;
  503. let n2 = 0;
  504.  
  505.  
  506. const fRes = new Array(n1);
  507. // -----------------------------------------------------------------------------------------
  508.  
  509. const s8 = Symbol();
  510.  
  511. {
  512.  
  513. /** @type {Map<String, Object>} */
  514. let cacheTexts = new Map(); // avoid duplicate with javascript object properties
  515.  
  516. // /-* * @type {Map<String, number>} *-/
  517. // let mh1 = new Map(); // avoid duplicate with javascript object properties
  518. // 1: ok
  519. // 2: abandoned effect text
  520.  
  521. for (const initialSegment of initialSegments) {
  522. const transcript = (initialSegment || 0).transcriptSegmentRenderer;
  523. if (!transcript) {
  524. // https://www.youtube.com/watch?v=dmHJJ5k_G-A - transcriptSectionHeaderRenderer
  525. fRes[n2++] = initialSegment;
  526. continue;
  527. }
  528. const runs = transcript.snippet.runs
  529. if (!runs || runs.length === 0) {
  530. initialSegment[s8] = true;
  531. continue;
  532. }
  533. let startMs = (+transcript.startMs || 0); //integer
  534. let endMs = (+transcript.endMs || 0); //integer
  535. if (startMs === endMs) {
  536. // effect text
  537. // https://www.youtube.com/watch?v=Ud73fm4Uoq0
  538. //mapRej.add(initialSegment)
  539. continue;
  540. }
  541. if (endMs - startMs < 30) {
  542. continue;
  543. }
  544. const text = snippetText(transcript.snippet);
  545. const hEntry = cacheTexts.get(text);
  546. const mh1e = hEntry === undefined ? 0 : hEntry === null ? 2 : 1;
  547. if (mh1e === 2) continue;
  548. const entry = {
  549. startMs,
  550. endMs,
  551. initialSegment,
  552. text
  553. };
  554. if (mh1e === 0) {
  555. if (/^[,.\x60\x27\x22\u200b\xA0\x20;-]*$/.test(text)) {
  556. initialSegment[s8] = true;
  557. cacheTexts.set(text, null);
  558. //effect only
  559. // https://www.youtube.com/watch?v=zLak0dxBKpM
  560. //mapRej.add(initialSegment)
  561. continue;
  562. }
  563. } else if (hEntry) {
  564.  
  565. const timeDiff = entry.startMs - hEntry.endMs;
  566. let shouldMerge = false;
  567.  
  568. if (timeDiff >= 0) {
  569.  
  570. if (timeDiff < 25) {
  571. shouldMerge = true;
  572. } else if (timeDiff < 450 && entry.endMs - entry.startMs < 900) {
  573. shouldMerge = true;
  574. } else if (timeDiff < 150 && entry.endMs - entry.startMs > 800) {
  575. shouldMerge = true;
  576. }
  577.  
  578. if (shouldMerge && hEntry.endMs <= endMs && startMs <= endMs) {
  579. // abandon the current entry.
  580. // absorbed by previous entry
  581. hEntry.endMs = entry.endMs;
  582. hEntry.initialSegment.transcriptSegmentRenderer.endMs = entry.initialSegment.transcriptSegmentRenderer.endMs; // update fRes & initialSegments as well using object reference
  583. //mapRej.add(entry.initialSegment);
  584. continue;
  585. }
  586.  
  587. } else if (entry.startMs < hEntry.startMs && hEntry.startMs < entry.endMs) {
  588.  
  589. // abandon the current entry.
  590. // absorbed by previous entry
  591. if (entry.endMs > hEntry.endMs) {
  592. hEntry.endMs = entry.endMs;
  593. hEntry.initialSegment.transcriptSegmentRenderer.endMs = entry.initialSegment.transcriptSegmentRenderer.endMs; // update fRes & initialSegments as well using object reference
  594. }
  595. //mapRej.add(entry.initialSegment);
  596. continue;
  597.  
  598. }
  599.  
  600. }
  601. //if not abandoned
  602. cacheTexts.set(text, entry); //replace the previous valid entry object if any
  603. // for (const s of runs) {
  604. // s.text = _snippetText(s.text);
  605. // }
  606. fixRuns(runs);
  607. fRes[n2++] = initialSegment;
  608. }
  609.  
  610. // cacheTexts.clear(); // let GC do it.
  611. cacheTexts = null;
  612. // mh1.clear(); // let GC do it.
  613. // mh1 = null;
  614.  
  615. }
  616.  
  617. const si_length = fRes.length = n2;
  618. const sj_length = n1;
  619.  
  620. if (si_length !== sj_length) { // for equal length, no fix is required & ignore spacing fix
  621. // collect the abandon text to become second subtitle
  622.  
  623. let sj_start = 0;
  624. let invalid_sj = -1;
  625. for (let si = 0; si < si_length; si++) {
  626. const segment = fRes[si];
  627. let transcript = segment.transcriptSegmentRenderer;
  628. if (!transcript) continue; // e.g. transcriptSectionHeaderRenderer
  629. const runs = transcript.snippet.runs;
  630. // fixRuns(runs);
  631. if (runs.length > 1 || runs[0].text.includes('\n')) continue; // skip multi lines
  632. const main_startMs = (+transcript.startMs || 0);
  633. const main_endMs = (+transcript.endMs || 0);
  634. transcript = null;
  635.  
  636. /** @type {Map<string, number>} */
  637. let tMap = new Map(); // avoid duplicate with javascript object properties
  638.  
  639. // assume that it is asc-ordered array of key startMs;
  640. for (let sj = sj_start; sj < sj_length; sj++) {
  641. const initialSegment = initialSegments[sj];
  642.  
  643. if (!initialSegment || initialSegment[s8]) continue; // should invalid_sj be set ?
  644.  
  645. const tSegment = initialSegment.transcriptSegmentRenderer;
  646.  
  647. if (!tSegment) {
  648. // https://www.youtube.com/watch?v=dmHJJ5k_G-A - transcriptSectionHeaderRenderer
  649. invalid_sj = sj; // should invalid_sj be set ?
  650. continue;
  651. }
  652.  
  653. const startMs = (+tSegment.startMs || 0)
  654. const isStartValid = startMs >= main_startMs;
  655. if (!isStartValid) {
  656. invalid_sj = sj;
  657. continue;
  658. }
  659. // isStartValid must be true
  660. if (startMs > main_endMs) {
  661. sj_start = invalid_sj + 1;
  662. break;
  663. }
  664.  
  665. const endMs = (+tSegment.endMs || 0)
  666. if (endMs <= main_endMs) {
  667. const mt = snippetText(tSegment.snippet);
  668. const prev = tMap.get(mt);
  669. if (endMs >= startMs) {
  670. tMap.set(mt, (prev || 0) + 1 + (endMs - startMs));
  671. }
  672. }
  673.  
  674. }
  675.  
  676. if (tMap.size <= 1) continue; // no second line
  677. let rg = [...tMap.entries()]; // N x 2 2D-array [string,number][]
  678. tMap = null;
  679.  
  680. // https://www.youtube.com/watch?v=Ud73fm4Uoq0
  681.  
  682. rg.sort((a, b) => b[1] - a[1]); //descending order of number
  683.  
  684. let targetZ = rg[1][1];
  685. if (targetZ > 4) {
  686. let az = 0;
  687. let fail = false;
  688. for (let idx = 2, rgl = rg.length; idx < rgl; idx++) {
  689. az += rg[idx][1];
  690. if (az >= targetZ) {
  691. fail = true;
  692. break;
  693. }
  694. }
  695. if (!fail) {
  696. const rgA = rg[0][0];
  697. const rgB = rg[1][0];
  698. const isDiff = rgB.replace(/\s/g, '') !== rgA.replace(/\s/g, '');
  699. if (isDiff && rgA === _snippetText(runs[0].text)) {
  700. if (runs[0] && runs[0].text) runs[0].blockLine = true;
  701. runs.push({ text: rgB, blockLine: true });
  702. }
  703. }
  704. }
  705. rg = null;
  706. }
  707.  
  708. TRANSLATE_DEBUG && Promise.resolve(fRes).then((r) => {
  709.  
  710. let obj = r;
  711. console.log(7559, 1, obj)
  712. return obj;
  713. }).then(p => {
  714. let obj = _DEBUG_szz(p)
  715. console.log(7559, 2, obj)
  716.  
  717. });
  718. }
  719.  
  720. // -----------------------------------------------------------------------------------------
  721. snCache.clear();
  722. return fRes;
  723.  
  724. }
  725.  
  726.  
  727. return translate
  728.  
  729. }
  730.  
  731.  
  732. let translateFn = null;
  733.  
  734. FIX_TRANSCRIPT_SEGMENTS && !isChatRoomURL && (() => {
  735.  
  736. const wmx = new WeakMap();
  737.  
  738. function fixSegments(ytObj) {
  739. let a, b;
  740. let seg = ((a = ytObj.data) == null ? void 0 : a[b = 'searchResultSegments']) || ((a = ytObj.data) == null ? void 0 : a[b = 'initialSegments']) || [];
  741. if (!seg || !a || !b || typeof (seg || 0) !== 'object' || !Number.isFinite(seg.length * 1)) return;
  742. translateFn = translateFn || getTranslate();
  743. let cSeg;
  744. cSeg = wmx.get(seg);
  745. if (!cSeg) {
  746. let vSeg = null;
  747. try {
  748. vSeg = translateFn(seg);
  749. } catch (e) {
  750. }
  751. if (seg && typeof seg === 'object' && seg.length >= 1 && vSeg && typeof vSeg === 'object' && vSeg.length >= 1) {
  752. // console.log('translated', vSeg);
  753. cSeg = vSeg;
  754. wmx.set(seg, cSeg);
  755. wmx.set(cSeg, cSeg);
  756. }
  757. }
  758. if (cSeg && cSeg !== seg) {
  759. a[b] = cSeg;
  760. }
  761. }
  762.  
  763. const dfn = Symbol();
  764. const Object_ = Object;
  765. Object_[dfn] = Object_.defineProperties;
  766. let activation = true;
  767. Object_.defineProperties = function (obj, pds) {
  768. let segments, get_;
  769. if (activation && pds && (segments = pds.segments) && (get_ = segments.get)) {
  770. activation = false;
  771. segments.get = function () {
  772. fixSegments(this);
  773. return get_.call(this);
  774. };
  775. }
  776. return Object_[dfn](obj, pds);
  777. };
  778.  
  779. })();
  780.  
  781.  
  782. let pf31 = new PromiseExternal();
  783.  
  784. // native RAF
  785. let __requestAnimationFrame__ = typeof webkitRequestAnimationFrame === 'function' ? window.webkitRequestAnimationFrame.bind(window) : window.requestAnimationFrame.bind(window);
  786.  
  787. // 1st wrapped RAF
  788. const baseRAF = (callback) => {
  789. return p59 ? __requestAnimationFrame__(callback) : __requestAnimationFrame__((hRes) => {
  790. pf31.then(() => {
  791. callback(hRes);
  792. });
  793. });
  794. };
  795.  
  796. // 2nd wrapped RAF
  797. window.requestAnimationFrame = baseRAF;
  798.  
  799. const insp = o => o ? (o.polymerController || o.inst || o || 0) : (o || 0);
  800. const indr = o => insp(o).$ || o.$ || 0;
  801.  
  802. const prototypeInherit = (d, b) => {
  803. const m = Object.getOwnPropertyDescriptors(b);
  804. for (const p in m) {
  805. if (!Object.getOwnPropertyDescriptor(d, p)) {
  806. Object.defineProperty(d, p, m[p]);
  807. }
  808. }
  809. };
  810.  
  811.  
  812. const firstObjectKey = (obj) => {
  813. for (const key in obj) {
  814. if (obj.hasOwnProperty(key) && typeof obj[key] === 'object') return key;
  815. }
  816. return null;
  817. };
  818.  
  819. function searchNestedObject(obj, predicate, maxDepth = 64) {
  820. // normal case: depth until 36
  821. const result = [];
  822. const visited = new WeakSet();
  823.  
  824. function search(obj, depth) {
  825. visited.add(obj);
  826. for (const [key, value] of Object.entries(obj)) {
  827. // Recursively search nested objects and arrays
  828. if (value !== null && typeof value === 'object') {
  829. // Prevent infinite loops by checking if the object is already visited or depth exceeded
  830. if (depth + 1 <= maxDepth && !visited.has(value)) {
  831. search(value, depth + 1);
  832. }
  833. } else if (predicate(value)) {
  834. result.push([obj, key]);
  835. }
  836. }
  837. }
  838.  
  839. typeof (obj || 0) === 'object' && search(obj, 0);
  840. return result;
  841. }
  842.  
  843. /** @type {(o: Object | null) => WeakRef | null} */
  844. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null);
  845.  
  846. /** @type {(wr: Object | null) => Object | null} */
  847. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  848.  
  849. const isIterable = (obj) => (Symbol.iterator in Object_(obj));
  850.  
  851. if (typeof Document.prototype.requestStorageAccessFor === 'function') {
  852. if (DENY_requestStorageAccess) {
  853. // https://developer.mozilla.org/en-US/docs/Web/API/Document/requestStorageAccessFor
  854. Document.prototype.requestStorageAccessFor = undefined;
  855. console.log('[yt-js-engine-tamer]', 'requestStorageAccessFor is removed.');
  856. } else if (DISABLE_IFRAME_requestStorageAccess && window !== top) {
  857. Document.prototype.requestStorageAccessFor = function () {
  858. return new Promise((resolve, reject) => {
  859. reject();
  860. });
  861. };
  862. }
  863. }
  864.  
  865. const traceStack = (stack) => {
  866. let result = new Set();
  867. let p = new Set();
  868. let u = ''
  869. for (const s of stack.split('\n')) {
  870. if (s.split(':').length < 3) continue;
  871. let m = /(([\w-_\.]+):\d+:\d+)[^:\r\n]*/.exec(s);
  872. if (!m) continue;
  873. p.add(m[2]);
  874. if (p.size >= 3) break;
  875. if(!u) u = m[2];
  876. else if(p.size === 2 && u && u=== m[2]) break;
  877. result.add(s);
  878. }
  879. return [...result].join('\n');
  880. }
  881.  
  882. if (FIX_bind_self_this && !Function.prototype.bind488 && !Function.prototype.bind588) {
  883. // window.m3bb = new Set();
  884.  
  885. // const smb = Symbol();
  886. const vmb = 'dtz02' // Symbol(); // return kThis for thisArg
  887. const vmc = 'dtz04' // Symbol(); // whether it is proxied fn
  888. const vmd = 'dtz08' // Symbol(); // self fn proxy (fn--fn)
  889.  
  890. // const fnProxySelf = function (...args) {
  891. // if (args[0] === smb) return this;
  892. // const cnt = kRef(this.ref);
  893. // if (cnt) {
  894. // if (typeof cnt[this.prop] !== 'function') console.error(`this.${this.prop} is not a function. [${cnt.is || 'nil'}]`)
  895. // return cnt[this.prop](...args); // might throw error
  896. // }
  897. // }
  898. // fnProxySelf.bind588 = fnProxySelf.bind;
  899. // const pFnHandler = {
  900. // get(target, prop){
  901. // if(prop === 'bind588') return 2;
  902. // const fnThis = target(smb);
  903. // if (fnThis && fnThis.prop && fnThis.ref) {
  904. // const cnt = kRef(fnThis.ref || null) || null;
  905. // if (cnt) {
  906. // const h = cnt[fnThis.prop];
  907. // const v = h[prop];
  908. // if (typeof v === 'function'){
  909. // if(typeof h === 'function'){
  910. // if (prop === 'call' || prop === 'bind' || prop === 'bind588' || prop === 'bind488' || prop === 'apply') {
  911. // if(h.bind588 === 1){
  912. // const g = function(...args){
  913. // console.log(1288, this)
  914. // return h.call(this, ...args);
  915. // };
  916. // console.log(399, g)
  917. // return g[prop];
  918. // // console.log(12778)
  919. // // console.log(target, target.call)
  920. // // return target[prop];
  921. // }
  922. // // independent of this
  923. // return v; // function.bind, function.call, function.apply
  924. // }
  925. // }
  926. // console.warn('cnt[fnThis.prop][prop] is function; might rely on this', { prop, fProp: fnThis.prop, is: cnt.is, h: h });
  927.  
  928. // // return new Proxy(fnProxySelf.bind588({ prop: prop, ref: new WeakRef(cnt[fnThis.prop]) }), pFnHandler);
  929. // }
  930. // return v;
  931. // }
  932. // }
  933. // },
  934. // set(target, prop, value) {
  935. // const fnThis = target(smb);
  936. // if (fnThis && fnThis.prop && fnThis.ref) {
  937. // const cnt = kRef(fnThis.ref || null) || null;
  938. // if (cnt) {
  939. // const h = cnt[fnThis.prop];
  940. // if (h) {
  941. // h[prop] = value;
  942. // } else {
  943. // console.log('h is nout found', { prop, fProp: fnThis.prop, is: cnt.is, h: h });
  944. // }
  945. // }
  946. // }
  947. // return true;
  948. // }
  949. // };
  950.  
  951. const thisConversionFn = (thisArg) => {
  952. if (!thisArg) return null;
  953. const kThis = thisArg[vmb];
  954. if (kThis) {
  955. const ref = kThis.ref;
  956. return (ref ? kRef(ref) : null) || null;
  957. }
  958. return thisArg;
  959. }
  960.  
  961. const pFnHandler2 = {
  962. get(target, prop) {
  963. if (prop === vmc) return target;
  964. return Reflect.get(target, prop);
  965. },
  966. apply(target, thisArg, argumentsList) {
  967. thisArg = thisConversionFn(thisArg);
  968. if (thisArg) return Reflect.apply(target, thisArg, argumentsList);
  969. }
  970. }
  971.  
  972.  
  973. const proxySelfHandler = {
  974. get(target, prop) {
  975. if(prop === vmb) return target;
  976. const ref = target.ref;
  977. const cnt = kRef(ref);
  978. if (!cnt) return;
  979. if (typeof cnt[prop] === 'function' && !cnt[prop][vmc] && !cnt[prop][vmb]) {
  980. if (!cnt[prop][vmd]) cnt[prop][vmd] = new Proxy(cnt[prop], pFnHandler2);
  981. return cnt[prop][vmd];
  982. }
  983. return cnt[prop];
  984. },
  985. set(target, prop, value) {
  986. const cnt = kRef(target.ref);
  987. if (!cnt) return true;
  988. if(value && (value[vmc] || value[vmb])){
  989. cnt[prop] = value[vmc] || thisConversionFn(value);
  990. return true;
  991. }
  992. cnt[prop] = value;
  993. return true;
  994. }
  995. };
  996.  
  997. const weakWrap = (thisArg) => {
  998. thisArg = thisConversionFn(thisArg);
  999. if (!thisArg) {
  1000. console.error('thisArg is not found');
  1001. return null;
  1002. }
  1003. return new Proxy({ ref: mWeakRef(thisArg) }, proxySelfHandler);
  1004. }
  1005.  
  1006. if (!window.getComputedStyle533 && typeof window.getComputedStyle === 'function') {
  1007. window.getComputedStyle533 = window.getComputedStyle;
  1008. window.getComputedStyle = function (a, ...args) {
  1009. a = thisConversionFn(a);
  1010. if (a) {
  1011. return getComputedStyle533(a, ...args);
  1012. }
  1013. return null;
  1014. }
  1015. }
  1016.  
  1017. Function._count_bind_00 = 0;
  1018. // Function._count_bind_01 = 0;
  1019.  
  1020. // let matchNativeCode = (Object+"");
  1021. // let matchNativeCode1 = matchNativeCode.includes("[native code]");
  1022. // let matchNativeLen = matchNativeCode.length - Object.name.length;
  1023.  
  1024. // const matchConstructor = (thisArg) => {
  1025. // const f = `${(thisArg || 0).constructor}`;
  1026. // if (f.length > 45) return true;
  1027. // if (matchNativeCode1 && f.length - thisArg.constructor.name.length === matchNativeLen) {
  1028. // if (f.includes('[native code]')){
  1029. // return false;
  1030. // }
  1031. // return true;
  1032. // }
  1033. // return false;
  1034. // }
  1035.  
  1036. // const acceptThis = (thisArg)=>{
  1037. // // if(!thisArg || typeof thisArg !=='object') return false;
  1038. // // // if((((thisArg||0).constructor||0).name || 'XXXXXXXX').length < 3) return true;
  1039. // // if(typeof thisArg.path === 'string') return true;
  1040. // // if(typeof thisArg.fn === 'function') return true;
  1041. // // if(typeof thisArg.id === 'string') return true;
  1042. // // if(typeof thisArg.isLoaded === 'boolean') return true;
  1043. // return false;
  1044. // }
  1045.  
  1046. const patchFn = (fn) => {
  1047.  
  1048. let s = `${fn}`;
  1049. if (s.length < 11 || s.includes('\n')) return false;
  1050. if(s.includes('bind(this')) return true;
  1051. if(s.includes('=this') && /[,\s][a-zA-Z_][a-zA-Z0-9_]*=this[;,]/.test(s) ) return true;
  1052. // var a=this;
  1053. // f.bind(this)
  1054.  
  1055.  
  1056. return false;
  1057. }
  1058.  
  1059. Function.prototype.bind488 = Function.prototype.bind;
  1060. Function.prototype.bind = function(thisArg, ...args){
  1061.  
  1062. if (thisConversionFn(thisArg) !== thisArg) {
  1063. return this.bind488(thisArg, ...args);
  1064. }
  1065. if( thisArg && patchFn(this) ){
  1066.  
  1067. // console.log(599,`${this}`)
  1068.  
  1069. try {
  1070. // let b1 = thisArg && typeof thisArg === 'object' && typeof thisArg.isAttached === 'boolean' && !thisArg.dtz06; // ready cnt
  1071. // let b2 = !b1 && thisArg && (thisArg instanceof Node) && typeof thisArg.nodeName === 'string' && !thisArg.dtz06; // dom
  1072. // let b3 = !b1 && !b2 && thisArg && typeof thisArg === 'object' && typeof thisArg.is === 'string' && !thisArg.dtz06; // init stage ?
  1073. // // let b4 = !b1 && !b2 && !b3 && thisArg && typeof thisArg === 'object' && !thisArg.dtz06 && matchConstructor(thisArg);
  1074. // // let b5 = !b1 && !b2 && !b3 && !b4 && thisArg && typeof thisArg === 'object' && !thisArg.dtz06 && acceptThis(thisArg);
  1075. // // let b5 = !b1 && !b2 && !b3 && thisArg && typeof thisArg === 'object' && !thisArg.dtz06 && !(thisArg instanceof Window);
  1076. // // let b4 = false;
  1077. // let b4 = !b1 && !b2 && !b3 && thisArg && !thisArg.dtz06;
  1078.  
  1079. // // b3 = false;
  1080. // // b4 = false;
  1081. // // b5 = false;
  1082.  
  1083. // if (b1 || b2 || b3 ||b4 ) {
  1084. const f = this;
  1085. const ps = thisArg.__proxySelf0__ || (thisArg.__proxySelf0__ = weakWrap(thisArg));
  1086. if (ps && ps[vmb]) {
  1087. Function._count_bind_00++;
  1088. return f.bind488(ps, ...args)
  1089. }
  1090. // }
  1091. } catch (e) {
  1092. console.warn(e)
  1093. }
  1094. }
  1095. return this.bind488(thisArg, ...args);
  1096. }
  1097. Function.prototype.bind588 = 1;
  1098. }
  1099.  
  1100.  
  1101. if (FIX_weakMap_weakRef && !window.WeakMapOriginal && typeof window.WeakMap === 'function' && typeof WeakRef === 'function') {
  1102. const WeakMapOriginal = window.WeakMapOriginal = window.WeakMap;
  1103. const wm6 = new WeakMapOriginal();
  1104.  
  1105. const skipW = new WeakSet();
  1106.  
  1107.  
  1108. window.WeakMap = class WeakMap extends WeakMapOriginal {
  1109. constructor(iterable = undefined) {
  1110. super();
  1111. if (iterable && iterable[Symbol.iterator]) {
  1112. for (const entry of iterable) {
  1113. entry && this.set(entry[0], entry[1]);
  1114. }
  1115. }
  1116. }
  1117. delete(a) {
  1118. if (!this.has(a)) return false;
  1119. super.delete(a);
  1120. return true;
  1121. }
  1122. get(a) {
  1123. const p = super.get(a);
  1124. if (p && typeof p === 'object' && p.deref && !skipW.has(p)) {
  1125. let v = kRef(p);
  1126. if (!v) {
  1127. super.delete(a);
  1128. }
  1129. return v || undefined;
  1130. }
  1131. return p;
  1132. }
  1133. has(a) {
  1134. if (!super.has(a)) return false;
  1135. const p = super.get(a);
  1136. if (p && typeof p === 'object' && p.deref && !skipW.has(p)) {
  1137. if (!kRef(p)) {
  1138. super.delete(a);
  1139. return false;
  1140. }
  1141. }
  1142. return true;
  1143. }
  1144. set(a, b) {
  1145. let wq = b;
  1146. if (b && (typeof b === 'function' || typeof b === 'object')) {
  1147. if (b.deref) {
  1148. skipW.add(b);
  1149. wq = b;
  1150. } else {
  1151. wq = wm6.get(b);
  1152. if (!wq) {
  1153. wq = mWeakRef(b);
  1154. wm6.set(b, wq);
  1155. }
  1156. }
  1157. }
  1158. super.set(a, wq);
  1159. return this;
  1160. }
  1161. }
  1162. Object.defineProperty(window.WeakMap, Symbol.toStringTag, {
  1163. configurable: true,
  1164. enumerable: false,
  1165. value: "WeakMap",
  1166. writable: false
  1167. });
  1168. }
  1169.  
  1170. const isWatchPageURL = (url) => {
  1171. url = url || location;
  1172. return location.pathname === '/watch' || location.pathname.startsWith('/live/')
  1173. };
  1174.  
  1175. const isCustomElementsProvided = typeof customElements !== "undefined" && typeof (customElements || 0).whenDefined === "function";
  1176.  
  1177. const promiseForCustomYtElementsReady = isCustomElementsProvided ? Promise.resolve(0) : new Promise((callback) => {
  1178. const EVENT_KEY_ON_REGISTRY_READY = "ytI-ce-registry-created";
  1179. if (typeof customElements === 'undefined') {
  1180. if (!('__CE_registry' in document)) {
  1181. // https://github.com/webcomponents/polyfills/
  1182. Object.defineProperty(document, '__CE_registry', {
  1183. get() {
  1184. // return undefined
  1185. },
  1186. set(nv) {
  1187. if (typeof nv == 'object') {
  1188. delete this.__CE_registry;
  1189. this.__CE_registry = nv;
  1190. this.dispatchEvent(new CustomEvent(EVENT_KEY_ON_REGISTRY_READY));
  1191. }
  1192. return true;
  1193. },
  1194. enumerable: false,
  1195. configurable: true
  1196. })
  1197. }
  1198. let eventHandler = (evt) => {
  1199. document.removeEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  1200. const f = callback;
  1201. callback = null;
  1202. eventHandler = null;
  1203. f();
  1204. };
  1205. document.addEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  1206. } else {
  1207. callback();
  1208. }
  1209. });
  1210.  
  1211. const whenCEDefined = isCustomElementsProvided
  1212. ? (nodeName) => customElements.whenDefined(nodeName)
  1213. : (nodeName) => promiseForCustomYtElementsReady.then(() => customElements.whenDefined(nodeName));
  1214.  
  1215. FIX_perfNow && performance.timeOrigin > 9 && (() => {
  1216. if (performance.now23 || performance.now16 || typeof Performance.prototype.now !== 'function') return;
  1217. const f = performance.now23 = Performance.prototype.now;
  1218.  
  1219. let k = 0; // 0 <= k < 9998m
  1220. let u = 0;
  1221. let s = ((performance.timeOrigin % 7) + 1) / 7 - 1e-2 / 7; // s > 0.14
  1222.  
  1223. // By definition, performance.now() is mono increasing.
  1224. // Fixing in YouTube.com is required to ensure performance.now() is strictly increasing.
  1225. performance.now = performance.now16 = function () {
  1226. /**
  1227. * Bug 1842437 - When attempting to go back on youtube.com, the content remains the same
  1228. *
  1229. * If consecutive session history entries had history.state.entryTime set to same value,
  1230. * back button doesn't work as expected. The entryTime value is coming from performance.now()
  1231. * and modifying its return value slightly to make sure two close consecutive calls don't
  1232. * get the same result helped with resolving the issue.
  1233. */
  1234. // see https://bugzilla.mozilla.org/show_bug.cgi?id=1756970
  1235. // see https://bugzilla.mozilla.org/show_bug.cgi?id=1842437
  1236.  
  1237. const v = typeof (this || 0).now23 === 'function' ? this.now23() + s : f.call(performance) + s; // v > 0.14
  1238. if (u + 0.0015 < (u = v)) k = 0; // note: hRes should be accurate to 5 µs in isolated contexts
  1239. else if (k < 0.001428) k += 1e-6 / 7; // M = 10000 * m; m * 9996 = 0.001428
  1240. else { // more than 9998 consecutive calls
  1241. /**
  1242. *
  1243. * max no. of consecutive calls
  1244. *
  1245. * Sample Size: 4800
  1246. * Sample Avg = 1565.375
  1247. * Sample Median = 1469.5
  1248. * Sample Max = 5660 << 7500 << 9999
  1249. *
  1250. *
  1251. * */
  1252. k = 0;
  1253. s += 1 / 7;
  1254. }
  1255. return v + k; // 0 < v - M < v - M + k < v
  1256. }
  1257.  
  1258. let loggerMsg = '';
  1259. if (`${performance.now()}` === `${performance.now()}`) {
  1260. const msg1 = 'performance.now is modified but performance.now() is not strictly increasing.';
  1261. const msg2 = 'performance.now cannot be modified and performance.now() is not strictly increasing.';
  1262. loggerMsg = performance.now !== performance.now16 ? msg1 : msg2; // might not able to set in Firefox
  1263. }
  1264. loggerMsg && console.warn(loggerMsg);
  1265. })();
  1266.  
  1267. FIX_removeChild && (() => {
  1268. if (typeof Node.prototype.removeChild === 'function' && typeof Node.prototype.removeChild062 !== 'function') {
  1269. Node.prototype.removeChild062 = Node.prototype.removeChild;
  1270. Node.prototype.removeChild = function (child) {
  1271. if (typeof this.__shady_native_removeChild !== 'function' || ((child instanceof Node) && child.parentNode === this)) {
  1272. this.removeChild062(child);
  1273. } else if ((child instanceof Element) && child.is === 'tp-yt-paper-tooltip') {
  1274. // tooltip bug
  1275. } else {
  1276. console.warn('[yt-js-engine-tamer] Node is not removed from parent', { parent: this, child: child })
  1277. }
  1278. return child;
  1279. }
  1280. }
  1281. })();
  1282.  
  1283.  
  1284. FIX_VIDEO_PLAYER_MOUSEHOVER_EVENTS && !isChatRoomURL && (() => {
  1285.  
  1286. const [setIntervalX0, clearIntervalX0] = [setInterval, clearInterval];
  1287.  
  1288. // let cid = 0;
  1289.  
  1290. let mousemoveFn = null;
  1291. let mousemoveDT = 0;
  1292. let mousemoveCount = 0;
  1293. // let qv = false;
  1294. const cif = () => {
  1295. if (!mousemoveFn) return;
  1296. const ct = Date.now();
  1297. if (mousemoveDT + 1200 > ct) { // avoid setTimeout delay too long without execution
  1298. mousemoveFn && mousemoveFn();
  1299. }
  1300. mousemoveFn = null;
  1301. };
  1302. let mousemoveCId = 0;
  1303. let mouseoverFn = null;
  1304. HTMLElement_.prototype.addEventListener4882 = HTMLElement_.prototype.addEventListener;
  1305. HTMLElement_.prototype.addEventListener = function (a, b, c) {
  1306. if (this.id == 'movie_player' && `${a}`.startsWith('mouse') && c === undefined) {
  1307. const bt = `${b}`;
  1308. if (bt.length >= 61 && bt.length <= 71 && bt.startsWith('function(){try{return ') && bt.includes('.apply(this,arguments)}catch(')) {
  1309. b[`__$$${a}$$1926__`] = true;
  1310. this[`__$$${a}$$1937__`] = (this[`__$$${a}$$1937__`] || 0) + 1;
  1311. if (this[`__$$${a}$$1937__`] > 1073741823) this[`__$$${a}$$1937__`] -= 536870911;
  1312. // console.log(3928, a, this[`__$$${a}$$1937__`])
  1313. if (!this[`__$$${a}$$1938__`]) {
  1314. this[`__$$${a}$$1938__`] = b;
  1315. if (a === 'mousemove') {
  1316. this.addEventListener4882('mouseenter', (evt) => {
  1317. if (mousemoveCId) return;
  1318. mousemoveCId = setIntervalX0(cif, 380);
  1319. });
  1320. this.addEventListener4882('mouseleave', (evt) => {
  1321. clearIntervalX0(mousemoveCId);
  1322. mousemoveCId = 0;
  1323. });
  1324. }
  1325. this.addEventListener4882(a, (evt) => {
  1326. const evt_ = evt;
  1327. if (!this[`__$$${a}$$1937__`]) return;
  1328. if (!this[`__$$${a}$$1938__`]) return;
  1329. if (a === 'mousemove') {
  1330. mouseoverFn && mouseoverFn();
  1331. if (mousemoveDT + 350 > (mousemoveDT = Date.now())) {
  1332. (++mousemoveCount > 1e9) && (mousemoveCount = 9);
  1333. } else {
  1334. mousemoveCount = 0;
  1335. }
  1336. const f = mousemoveFn = () => {
  1337. if (f !== mousemoveFn) return;
  1338. mousemoveFn = null;
  1339. this[`__$$${a}$$1938__`](evt_);
  1340. };
  1341. if (mousemoveCount <= 1) mousemoveFn();
  1342. } else {
  1343. if (a === 'mouseout' || a === 'mouseleave') {
  1344. mousemoveFn = null;
  1345. mousemoveDT = 0;
  1346. mousemoveCount = 0;
  1347. this[`__$$${a}$$1938__`](evt_);
  1348. mouseoverFn && mouseoverFn();
  1349. } else { // mouseover, mouseenter
  1350. mousemoveFn = null;
  1351. mousemoveDT = 0;
  1352. mousemoveCount = 0;
  1353. mouseoverFn && mouseoverFn(); // just in case
  1354. const f = mouseoverFn = () => {
  1355. if (f !== mouseoverFn) return;
  1356. mouseoverFn = null;
  1357. this[`__$$${a}$$1938__`](evt_);
  1358. }
  1359. nextBrowserTick_(mouseoverFn);
  1360. }
  1361. }
  1362. }, c);
  1363.  
  1364.  
  1365. return;
  1366. } else {
  1367.  
  1368. return;
  1369. }
  1370. }
  1371.  
  1372. }
  1373. return this.addEventListener4882(a, b, c)
  1374. }
  1375.  
  1376.  
  1377.  
  1378.  
  1379. HTMLElement_.prototype.removeEventListener4882 = HTMLElement_.prototype.removeEventListener;
  1380. HTMLElement_.prototype.removeEventListener = function (a, b, c) {
  1381. if (this.id == 'movie_player' && `${a}`.startsWith('mouse') && c === undefined) {
  1382.  
  1383. if (b[`__$$${a}$$1926__`]) {
  1384. b[`__$$${a}$$1926__`] = false;
  1385.  
  1386. if (this[`__$$${a}$$1937__`]) this[`__$$${a}$$1937__`] -= 1;
  1387.  
  1388. // console.log(3929, a, this[`__$$${a}$$1937__`], b[`__$$${a}$$1926__`])
  1389.  
  1390. return;
  1391.  
  1392. }
  1393.  
  1394. }
  1395. return this.removeEventListener4882(a, b, c)
  1396. }
  1397.  
  1398.  
  1399. })();
  1400.  
  1401.  
  1402. FIX_DOM_IF_REPEAT && (() => {
  1403. // https://www.youtube.com/s/desktop/26a583e4/jsbin/live_chat_polymer.vflset/live_chat_polymer.js
  1404. // DOM-IF is still a core class of Polymer, so no polymerController is available.
  1405. // Be careful of the mixture of polymer functions and native Element functions
  1406. // Be careful of the coding design is different with the modern Yt elements
  1407.  
  1408.  
  1409. /*
  1410.  
  1411.  
  1412. function Ks(a, b, c) {
  1413. if (kj && !BOa(a))
  1414. throw Error("strictTemplatePolicy: template owner not trusted");
  1415. c = c || {};
  1416. if (a.__templatizeOwner)
  1417. throw Error("A <template> can only be templatized once");
  1418. a.__templatizeOwner = b;
  1419. var d = (b ? b.constructor : Js)._parseTemplate(a)
  1420. , e = d.templatizeInstanceClass;
  1421. e || (e = COa(a, d, c),
  1422. d.templatizeInstanceClass = e);
  1423. var g = BOa(a);
  1424. EOa(a, d, c, g);
  1425. c = function() {
  1426. return e.apply(this, arguments) || this
  1427. }
  1428. ;
  1429. h(c, e);
  1430. c.prototype._methodHost = g;
  1431. c.prototype.__dataHost = a;
  1432. c.prototype.__templatizeOwner = b;
  1433. c.prototype.__hostProps = d.hostProps;
  1434. return c
  1435. }
  1436.  
  1437. */
  1438.  
  1439. // Polymer.enqueueDebouncer
  1440.  
  1441. const s81 = Symbol();
  1442. const s83 = Symbol();
  1443. const s84 = Symbol();
  1444. const s85 = Symbol();
  1445. const s85b = Symbol();
  1446. const s85c = Symbol();
  1447.  
  1448. let renderDebounceTs = null;
  1449.  
  1450. let renderDebouncePromise = null;
  1451. let qp;
  1452.  
  1453. let cme = 0;
  1454.  
  1455. const shadyFlushMO = new MutationObserver(() => {
  1456.  
  1457. if (!renderDebounceTs) return;
  1458.  
  1459. if (renderDebounceTs.size > 0) {
  1460. console.warn('renderDebounceTs.size is incorect', renderDebounceTs.size);
  1461. try {
  1462. Polymer.flush();
  1463. return;
  1464. } catch (e) { }
  1465. }
  1466.  
  1467. renderDebouncePromise && Promise.resolve().then(() => {
  1468.  
  1469. if (renderDebouncePromise) {
  1470. renderDebouncePromise && renderDebouncePromise.resolve();
  1471. renderDebouncePromise = null;
  1472. DEBUG_DBR847 && console.log('__DBR847__ renderDebouncePromise.resolve by MutationObserver')
  1473. }
  1474.  
  1475. });
  1476.  
  1477. // Polymer.flush
  1478.  
  1479. window.ShadyDOM && ShadyDOM.flush();
  1480. window.ShadyCSS && window.ShadyCSS.ScopingShim && window.ShadyCSS.ScopingShim.flush();
  1481.  
  1482.  
  1483. });
  1484.  
  1485. if (FIX_DOM_IFREPEAT_RenderDebouncerChange) {
  1486.  
  1487. const observablePromise = (proc, timeoutPromise) => {
  1488. let promise = null;
  1489. return {
  1490. obtain() {
  1491. if (!promise) {
  1492. promise = new Promise(resolve => {
  1493. let mo = null;
  1494. const f = () => {
  1495. let t = proc();
  1496. if (t) {
  1497. mo.disconnect();
  1498. mo.takeRecords();
  1499. mo = null;
  1500. resolve(t);
  1501. }
  1502. }
  1503. mo = new MutationObserver(f);
  1504. mo.observe(document, { subtree: true, childList: true })
  1505. f();
  1506. timeoutPromise && timeoutPromise.then(() => {
  1507. resolve(null)
  1508. });
  1509. });
  1510. }
  1511. return promise
  1512. }
  1513. }
  1514. }
  1515.  
  1516.  
  1517. let p = 0;
  1518. qp = observablePromise(() => {
  1519. if (!(p & 1)) {
  1520.  
  1521. if (window.ShadyDOM && ShadyDOM.flush) {
  1522. p |= 1;
  1523. if (!ShadyDOM.flush847) {
  1524.  
  1525. ShadyDOM.flush847 = ShadyDOM.flush;
  1526. ShadyDOM.flush = function () {
  1527.  
  1528. DEBUG_xx847 && console.log('xx847 ShadyDOM.flush')
  1529. renderDebouncePromise && Promise.resolve().then(() => {
  1530. if (renderDebouncePromise) {
  1531.  
  1532. renderDebouncePromise && renderDebouncePromise.resolve();
  1533. renderDebouncePromise = null;
  1534.  
  1535. DEBUG_DBR847 && console.log('__DBR847__ renderDebouncePromise.resolve by ShadyDOM.flush')
  1536.  
  1537. }
  1538.  
  1539. });
  1540. let r = this.flush847(...arguments);
  1541. if (r) {
  1542. document.documentElement.setAttribute('nw3a24np', (cme = (cme % 511 + 1)));
  1543. }
  1544. return r
  1545. }
  1546.  
  1547. }
  1548. }
  1549. }
  1550.  
  1551. if (!(p & 2)) {
  1552.  
  1553. if (window.ShadyCSS && window.ShadyCSS.ScopingShim && window.ShadyCSS.ScopingShim.flush) {
  1554. p |= 2;
  1555. const ScopingShim = window.ShadyCSS && window.ShadyCSS.ScopingShim;
  1556. if (!ScopingShim.flush848) {
  1557.  
  1558. ScopingShim.flush848 = ScopingShim.flush;
  1559. ScopingShim.flush = function () {
  1560.  
  1561. DEBUG_xx847 && console.log('xx847 ScopingShim.flush')
  1562.  
  1563. renderDebouncePromise && Promise.resolve().then(() => {
  1564.  
  1565. if (renderDebouncePromise) {
  1566.  
  1567. renderDebouncePromise && renderDebouncePromise.resolve();
  1568. renderDebouncePromise = null;
  1569.  
  1570. DEBUG_DBR847 && console.log('__DBR847__ renderDebouncePromise.resolve by ScopingShim.flush')
  1571.  
  1572.  
  1573.  
  1574. }
  1575.  
  1576. });
  1577. return this.flush848(...arguments);
  1578. }
  1579.  
  1580. }
  1581. }
  1582. }
  1583. if (p === 3) {
  1584. p |= 8;
  1585.  
  1586. let r = (window.ShadyDOM && ShadyDOM.flush && ShadyDOM.flush847
  1587. && window.ShadyCSS && window.ShadyCSS.ScopingShim &&
  1588. window.ShadyCSS.ScopingShim.flush && window.ShadyCSS.ScopingShim.flush848);
  1589.  
  1590. if (r) {
  1591. let w = Set.prototype.add;
  1592. let u = null;
  1593. Set.prototype.add = function () {
  1594. u = this;
  1595. throw new Error();
  1596. }
  1597. try {
  1598. Polymer.enqueueDebouncer()
  1599. } catch (e) { }
  1600. Set.prototype.add = w;
  1601. if (u !== null) {
  1602. renderDebounceTs = u;
  1603. if (DEBUG_renderDebounceTs) {
  1604. renderDebounceTs.add58438 = renderDebounceTs.add;
  1605. renderDebounceTs.add = function () {
  1606. console.log('renderDebounceTs.add')
  1607. console.log(traceStack((new Error()).stack))
  1608. // debugger;
  1609. return this.add58438(...arguments)
  1610. }
  1611.  
  1612. renderDebounceTs.delete58438 = renderDebounceTs.delete;
  1613. renderDebounceTs.delete = function () {
  1614. console.log('renderDebounceTs.delete')
  1615. const stack = `${(new Error()).stack}`
  1616. let isCallbackRemoval = false;
  1617. if (stack) {
  1618. let t = stack.replace(/[^\r\n]+renderDebounceTs\.delete[^\r\n]+/, '').replace('://','');
  1619. const s = t.split(':');
  1620. if (s.length === 3 && +s[1] > 0 && +s[2] > 0) {
  1621. isCallbackRemoval = true;
  1622. }
  1623. }
  1624. if (isCallbackRemoval) {
  1625. return this.delete58438(...arguments)
  1626. }
  1627. console.log(traceStack((new Error()).stack))
  1628. // debugger;
  1629. return this.delete58438(...arguments)
  1630. }
  1631. }
  1632. DEBUG_renderDebounceTs && (window.renderDebounceTs = renderDebounceTs);
  1633. console.log('renderDebounceTs', renderDebounceTs, `debug=${DEBUG_renderDebounceTs}`);
  1634. }
  1635. }
  1636.  
  1637. return true;
  1638. }
  1639. })
  1640.  
  1641. // if(window.ShadyDOM && ShadyDOM.flush){
  1642. // console.log('FIX_DOM_IF_RenderDebouncerChange X1')
  1643.  
  1644. // }
  1645. // if(window.ShadyCSS && window.ShadyCSS.ScopingShim && window.ShadyCSS.ScopingShim.flush){
  1646.  
  1647. // console.log('FIX_DOM_IF_RenderDebouncerChange X2')
  1648. // }
  1649.  
  1650. // console.log('FIX_DOM_IF_RenderDebouncerChange X3')
  1651.  
  1652. }
  1653.  
  1654. Object.defineProperty(Object.prototype, '_lastIf', {
  1655. get() {
  1656. return this[s81];
  1657. },
  1658. set(nv) {
  1659. if (nv === false && this.nodeName === "DOM-IF" && this.__renderDebouncer === null && this[s81] === undefined) {
  1660. // DOM-IF initialization
  1661. nv = null; // avoid (this.if == this._lastIf) primitive type conversion (object vs false)
  1662.  
  1663. this.__xiWB8__ = 2;
  1664.  
  1665. const cProto = this.__proto__;
  1666. if (cProto && !cProto.__xiWB7__) {
  1667. cProto.__xiWB7__ = 1;
  1668.  
  1669. // dom-if __template
  1670. // dom-repeat template
  1671. if (FIX_DOM_IF_TEMPLATE && !cProto.__template && !cProto.__template847) {
  1672. cProto.__template847 = true;
  1673. try {
  1674. // note: this is not "_template" in Polymer ( see POLYMER_COMPONENT_DEFINITION )
  1675. Object.defineProperty(cProto, '__template', {
  1676. get() {
  1677. const v = this[s84];
  1678. return (typeof (v || 0) === 'object' && v.deref) ? kRef(v) : v;
  1679. },
  1680. set(nv) {
  1681. if (typeof (nv || 0) === 'object' && !nv.deref) nv = mWeakRef(nv);
  1682. this[s84] = nv;
  1683. return true;
  1684. }
  1685. });
  1686. } catch (e) {
  1687. console.warn(e);
  1688. }
  1689.  
  1690. console.log('FIX_DOM_IF - __template')
  1691. }
  1692.  
  1693. // dom-if __ensureTemplate
  1694. // dom-repeat __ensureTemplatized
  1695. if (FIX_DOM_IF_TEMPLATE && !cProto.__ensureTemplate847 && typeof cProto.__ensureTemplate === 'function' && cProto.__ensureTemplate.length === 0 && this instanceof HTMLElement_ && `${cProto.__ensureTemplate}`.length > 20) {
  1696. // note that "_templateInfo" diffs the different version of DOM-IF
  1697.  
  1698. cProto.__ensureTemplate847 = cProto.__ensureTemplate;
  1699. cProto.__ensureTemplate = function () {
  1700. if (!(this instanceof HTMLElement_) || arguments.length > 0) return this.__ensureTemplate847(...arguments);
  1701. if (!this.__template) {
  1702. let b;
  1703. if (this._templateInfo) {
  1704. b = this;
  1705. } else {
  1706. if (!this.__templateCollection011__) this.__templateCollection011__ = this.getElementsByTagName('template');
  1707. b = this.__templateCollection011__[0];
  1708. if (!b) {
  1709. let a = mWeakRef(this);
  1710. let c = new MutationObserver(function () {
  1711. if (!this.__templateCollection011__[0]) throw Error("dom-if requires a <template> child"); // to be reviewed
  1712. if (c && a) {
  1713. c.disconnect();
  1714. a = kRef(a);
  1715. a && a.__render();
  1716. a && (a.__templateCollection011__ = null);
  1717. }
  1718. c = null;
  1719. a = null;
  1720. });
  1721. c && c.observe(this, {
  1722. childList: !0
  1723. });
  1724. return !1
  1725. } else {
  1726. this.__templateCollection011__ = null;
  1727. }
  1728. }
  1729. this.__template = b
  1730. }
  1731. return !0
  1732. }
  1733.  
  1734. console.log('FIX_DOM_IF - __ensureTemplate')
  1735.  
  1736. }
  1737.  
  1738.  
  1739. // if(!cProto.__createAndInsertInstance847 && typeof cProto.__createAndInsertInstance === 'function' && cProto.__createAndInsertInstance.length === 1 && `${cProto.__createAndInsertInstance}`.length >20){
  1740.  
  1741. // cProto.__createAndInsertInstance847 = cProto.__createAndInsertInstance;
  1742.  
  1743. // cProto.__createAndInsertInstance = function (a) {
  1744. // Promise.resolve().then(()=>{
  1745. // console.log('__createAndInsertInstance')
  1746. // window.lm5 = window.lm5 || [];
  1747. // window.lm5.push([mWeakRef(this), mWeakRef(this.__instance)])
  1748. // });
  1749. // return this.__createAndInsertInstance847(a);
  1750. // }
  1751.  
  1752. // }
  1753.  
  1754.  
  1755. // if(!cProto._bindTemplate847 && typeof cProto._bindTemplate === 'function' && cProto._bindTemplate.length === 2){
  1756.  
  1757. // cProto._bindTemplate847 = cProto._bindTemplate;
  1758.  
  1759. // cProto._bindTemplate = function (a, b) {
  1760. // return this._bindTemplate847(kRef(a), b); // might throw Error as a -> null inside _bindTemplate847
  1761. // }
  1762.  
  1763. // }
  1764. // if(!cProto._stampTemplate847 && typeof cProto._stampTemplate === 'function' && cProto._stampTemplate.length === 2){
  1765.  
  1766. // cProto._stampTemplate847 = cProto._stampTemplate;
  1767.  
  1768. // cProto._stampTemplate = function (a, b) {
  1769. // return this._stampTemplate847(kRef(a), b); // might throw Error as a -> null inside _stampTemplate847
  1770. // }
  1771.  
  1772. // }
  1773. console.log('FIX_DOM_IF OK', Object.keys(cProto))
  1774. }
  1775.  
  1776.  
  1777. // need to fix __observeEffects
  1778. // this.__observeEffects.if[0].info.method === this.__debounceRender
  1779. const f = () => {
  1780.  
  1781. const __observeEffects = this.__observeEffects;
  1782.  
  1783. if (__observeEffects && __observeEffects.if && isIterable(__observeEffects.if)) {
  1784. for (const effect of __observeEffects.if) {
  1785. const info = effect.info;
  1786. if (info && typeof info.method === 'function') {
  1787.  
  1788. if (info.method === this.__debounceRender847 || info.method === this.__debounceRender) {
  1789. info.method = FIX_DOM_IFREPEAT_RenderDebouncerChange_SET_TO_PROPNAME ? '__debounceRender' : this.__debounceRender;
  1790. }
  1791.  
  1792. }
  1793. }
  1794. }
  1795.  
  1796.  
  1797. if (__observeEffects && __observeEffects.restamp && isIterable(__observeEffects.restamp)) {
  1798. for (const effect of __observeEffects.restamp) {
  1799. const info = effect.info;
  1800. if (info && typeof info.method === 'function') {
  1801.  
  1802. if (info.method === this.__debounceRender847 || info.method === this.__debounceRender) {
  1803. info.method = FIX_DOM_IFREPEAT_RenderDebouncerChange_SET_TO_PROPNAME ? '__debounceRender' : this.__debounceRender;
  1804. }
  1805.  
  1806. }
  1807. }
  1808. }
  1809.  
  1810. // console.log(5881, this.__observeEffects)
  1811. }
  1812. if (FIX_DOM_IFREPEAT_RenderDebouncerChange) {
  1813. f();
  1814. Promise.resolve().then(f);
  1815. // afterward, don't care adding fn directly (the fn is already modified)
  1816. }
  1817.  
  1818. }
  1819. this[s81] = nv;
  1820. return true;
  1821. }
  1822. });
  1823.  
  1824.  
  1825. Object.defineProperty(Object.prototype, '__renderDebouncer', {
  1826. get() {
  1827. return this[s85];
  1828. },
  1829. set(nv) {
  1830. if (nv === null && this[s85] === undefined) {
  1831. // DOM-IF / DOM-REPEAT initialization
  1832.  
  1833.  
  1834. const cProto = this.__proto__;
  1835. if (qp) {
  1836. qp.obtain();
  1837. qp = null;
  1838. shadyFlushMO.observe(document.documentElement, { attributes: ['nw3a24np'] });
  1839. }
  1840. if (FIX_DOM_IFREPEAT_RenderDebouncerChange && !cProto.__debounceRender847 && typeof cProto.__debounceRender === 'function' && !(`${cProto.__debounceRender}`.includes("{}"))) {
  1841.  
  1842. cProto.__debounceRender847 = cProto.__debounceRender;
  1843.  
  1844. if (cProto.__debounceRender.length === 2) {
  1845.  
  1846. cProto.__debounceRender = function (a, b) {
  1847.  
  1848. if (!renderDebounceTs) return this.__debounceRender847(a, b);
  1849.  
  1850. b = b === void 0 ? 0 : b;
  1851.  
  1852. /*
  1853. b = b === void 0 ? 0 : b;
  1854. this.__renderDebouncer = us(this.__renderDebouncer, b > 0 ? Rr.after(b) : Tr, a.bind(this));
  1855. vs(this.__renderDebouncer)
  1856. */
  1857.  
  1858. this.__DBR848__ = this.__DBR848__ || `${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}`;
  1859.  
  1860. if (!renderDebouncePromise) {
  1861. renderDebouncePromise = new PromiseExternal();
  1862. document.documentElement.setAttribute('nw3a24np', (cme = (cme % 511 + 1)));
  1863. }
  1864.  
  1865. renderDebouncePromise.then(async () => {
  1866. if (b > 0) await delayPn(b);
  1867.  
  1868. const f = this.__dsIRYqw1__;
  1869. if (f === cme) return;
  1870. this.__dsIRYqw1__ = cme;
  1871. a.call(this);
  1872. DEBUG_DBR847 && console.log(`__DBR847__ done 01 (delay=${b})`, this.__DBR848__)
  1873.  
  1874. });
  1875.  
  1876. DEBUG_DBR847 && console.log(`__DBR847__ add 01 (delay=${b})`, this.__DBR848__)
  1877. }
  1878.  
  1879. } else if (cProto.__debounceRender.length === 0) {
  1880.  
  1881.  
  1882. cProto.__debounceRender = function () {
  1883.  
  1884. if (!renderDebounceTs) return this.__debounceRender847();
  1885.  
  1886. this.__DBR848__ = this.__DBR848__ || `${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}`;
  1887. /*
  1888. var a = this;
  1889. this.__renderDebouncer = us(this.__renderDebouncer, Tr, function() {
  1890. return a.__render()
  1891. });
  1892. vs(this.__renderDebouncer)
  1893. */
  1894.  
  1895. if (!renderDebouncePromise) {
  1896. renderDebouncePromise = new PromiseExternal();
  1897. document.documentElement.setAttribute('nw3a24np', (cme = (cme % 511 + 1)));
  1898. }
  1899. renderDebouncePromise.then(() => {
  1900. const f = this.__dsIRYqw1__;
  1901. if (f === cme) return;
  1902. this.__dsIRYqw1__ = cme;
  1903. this.__render()
  1904. DEBUG_DBR847 && console.log('__DBR847__ done 02', this.__DBR848__)
  1905. });
  1906. DEBUG_DBR847 && console.log('__DBR847__ add 02', this.__DBR848__)
  1907.  
  1908.  
  1909. }
  1910. }
  1911. }
  1912.  
  1913.  
  1914.  
  1915. // if(FIX_DOM_IFREPEAT_RenderDebouncerChange && !cProto.render847 && typeof cProto.render === 'function' && cProto.render.length === 0 && !(`${cProto.render}`.includes("{}"))){
  1916. // cProto.render847 = cProto.render;
  1917. // cProto.render = function(){
  1918.  
  1919. // this.__DBR848__ = this.__DBR848__ || `${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}`;
  1920. // try{
  1921. // this.render847();
  1922. // }catch(e){}
  1923. // // if(this.__DBR847__){
  1924. // // this.__DBR847__.resolve();
  1925. // // DEBUG_DBR847 && console.log('__DBR847__ resolve', this.__DBR848__)
  1926. // // }
  1927.  
  1928. // // renderDebouncePromise && renderDebouncePromise.resolve()
  1929. // // renderDebouncePromise = null;
  1930. // // DEBUG_DBR847 && console.log('__DBR847__ renderDebouncePromise.resolve by render', this.__DBR848__)
  1931.  
  1932. // }
  1933. // console.log('FIX_DOM_IF - render', `${cProto.render847}`, cProto.render847)
  1934. // }
  1935.  
  1936. }
  1937. this[s85] = nv;
  1938. return true;
  1939. }
  1940. });
  1941.  
  1942. // PS-DOM-REPEAT
  1943.  
  1944. Object.defineProperty(Object.prototype, 'JSC$10034_renderDebouncer', {
  1945. get() {
  1946. return this[s85b];
  1947. },
  1948. set(nv) {
  1949.  
  1950. this[s85b] = nv;
  1951. return true;
  1952. }
  1953. })
  1954.  
  1955. Object.defineProperty(Object.prototype, 'JSC$10027_renderDebouncer', {
  1956. get() {
  1957. return this[s85c];
  1958. },
  1959. set(nv) {
  1960.  
  1961. this[s85c] = nv;
  1962. return true;
  1963. }
  1964. })
  1965.  
  1966.  
  1967. })();
  1968.  
  1969. let xdeadc00 = null; // a deteched node with __domApi
  1970. let xlivec00 = null; // a deteched node with __domApi
  1971.  
  1972. const setupXdeadC = (cnt)=>{
  1973.  
  1974. let xdeadc = xdeadc00;
  1975. if(!xdeadc){
  1976. setupSDomWrapper(); // just in case
  1977. const hostElement = cnt.hostElement;
  1978. const el = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  1979. hostElement.insertAdjacentHTML('beforeend', ttpHTML('<!---->'));
  1980. hostElement.lastChild.replaceWith(el);
  1981. el.insertAdjacentHTML('afterbegin', ttpHTML(`<div></div>`));
  1982. const rid = `xdead_${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}`;
  1983. el.firstElementChild.id = rid;
  1984. cnt.$[rid] = el.firstElementChild;
  1985. cnt.stampDomArray9682_(null, rid, null, false, false, false);
  1986.  
  1987. xdeadc = cnt.getStampContainer_(rid);
  1988. el.remove();
  1989. xdeadc00 = xdeadc;
  1990. // console.log(xdeadc.__domApi)
  1991. // debugger;
  1992. // const xdeadv = xdeadc.__domApi;
  1993. }
  1994.  
  1995. let xlivec = xlivec00;
  1996. if(!xlivec){
  1997. setupSDomWrapper(); // just in case
  1998. const hostElement = cnt.hostElement;
  1999. const el = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  2000. hostElement.insertAdjacentHTML('beforeend', ttpHTML('<!---->'));
  2001. hostElement.lastChild.replaceWith(el);
  2002. el.insertAdjacentHTML('afterbegin', ttpHTML(`<div></div>`));
  2003. const rid = `xlive_${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}`;
  2004. el.firstElementChild.id = rid;
  2005. cnt.$[rid] = el.firstElementChild;
  2006. cnt.stampDomArray9682_(null, rid, null, false, false, false);
  2007.  
  2008. xlivec = cnt.getStampContainer_(rid);
  2009. xlivec00 = xlivec;
  2010. // console.log(xdeadc.__domApi)
  2011. // debugger;
  2012. // const xdeadv = xdeadc.__domApi;
  2013. }
  2014.  
  2015. return xdeadc00;
  2016. }
  2017.  
  2018. const setupSDomWrapper = () => {
  2019.  
  2020. const sdwProto = ShadyDOM.Wrapper.prototype;
  2021.  
  2022. if (sdwProto.__pseudo__isConnected__ !== null) {
  2023. sdwProto.__pseudo__isConnected__ = null;
  2024. const isConnectedPd = Object.getOwnPropertyDescriptor(sdwProto, 'isConnected');
  2025. if (isConnectedPd && isConnectedPd.get && isConnectedPd.configurable === true) {
  2026. const get = isConnectedPd.get;
  2027. isConnectedPd.get = function () {
  2028. const pseudoVal = this.__pseudo__isConnected__;
  2029. return typeof pseudoVal === 'boolean' ? pseudoVal : get.call(this);
  2030. }
  2031. Object.defineProperty(sdwProto, 'isConnected', { ...isConnectedPd });
  2032. }
  2033.  
  2034.  
  2035.  
  2036. // if (!sdwProto.__nodeMove__) {
  2037.  
  2038. // sdwProto.__nodeMove__ = function (dest) {
  2039.  
  2040.  
  2041. // }
  2042.  
  2043.  
  2044. // }
  2045.  
  2046.  
  2047.  
  2048.  
  2049. // debugger;
  2050. // new xdeadc.__domApi.constructor(document.createElement('div'));
  2051. }
  2052.  
  2053. }
  2054. const setupDomApi = (daProto) => {
  2055.  
  2056. daProto.__daHook377__ = true;
  2057.  
  2058.  
  2059.  
  2060. }
  2061.  
  2062.  
  2063. // WEAKREF_ShadyDOM
  2064.  
  2065. MODIFY_ShadyDOM_OBJ && ((WeakRef) => {
  2066.  
  2067. const setupPlainShadyDOM = (b) => {
  2068. (OMIT_ShadyDOM_settings & 1) && (b.inUse === true) && (b.inUse = false);
  2069. (OMIT_ShadyDOM_settings & 2) && (b.handlesDynamicScoping === true) && (b.handlesDynamicScoping = false);
  2070. (OMIT_ShadyDOM_settings & 4) && (b.force === true) && (b.force = false);
  2071. b.patchOnDemand = true;
  2072. b.preferPerformance = true;
  2073. b.noPatch = true;
  2074. }
  2075.  
  2076. const isPlainObject = (b, m) => {
  2077. if (!b || typeof b !== 'object') return false;
  2078. const e = Object.getOwnPropertyDescriptors(b);
  2079. if (e.length <= m) return false;
  2080. let pr = 0;
  2081. for (const k in e) {
  2082. const d = e[k];
  2083. if (!d || d.get || d.set || !d.enumerable || !d.configurable) return false;
  2084. if (!('value' in d) || typeof d.value === 'function') return false;
  2085. pr++;
  2086. }
  2087. return pr > m;
  2088. }
  2089.  
  2090. let b;
  2091.  
  2092. let lz = 0;
  2093.  
  2094. const sdp = Object.getOwnPropertyDescriptor(window, 'ShadyDOM');
  2095. if (sdp && sdp.configurable && sdp.value && sdp.enumerable && sdp.writable) {
  2096.  
  2097. // Brave - ShadyDOM exists before userscripting
  2098. b = sdp.value;
  2099.  
  2100. if (b && typeof b === 'object' && isPlainObject(b, 0)) {
  2101. OMIT_ShadyDOM_EXPERIMENTAL && setupPlainShadyDOM(b);
  2102. lz = 1;
  2103. }
  2104.  
  2105. }
  2106.  
  2107.  
  2108. if (sdp && sdp.configurable && sdp.value && sdp.enumerable && sdp.writable && !sdp.get && !sdp.set) {
  2109. } else if (!sdp) {
  2110. } else {
  2111. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM is not applied [ PropertyDescriptor issue ]', sdp);
  2112. return;
  2113. }
  2114.  
  2115. const shadyDOMNodeWRM = new WeakMap();
  2116.  
  2117. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM << 01 >>', b);
  2118.  
  2119. const selfWrKey = Symbol();
  2120.  
  2121. const weakWrapperNodeHandlerFn = () => ({
  2122. get() {
  2123. const wv = this[selfWrKey];
  2124. if (typeof wv === 'undefined') return undefined;
  2125. let node = kRef(wv);
  2126. if (!node) this[selfWrKey] = undefined;
  2127. return node || undefined;
  2128. // let w = shadyDOMNodeWRM.get(this);
  2129. // if (typeof w === 'object') w = kRef(w) || (shadyDOMNodeWRM.delete(this), undefined);
  2130. // return w;
  2131. },
  2132. set(nv) {
  2133. const wv = (nv[selfWrKey] || (nv[selfWrKey] = mWeakRef(nv)));
  2134. this[selfWrKey] = wv;
  2135. return true;
  2136. },
  2137. enumerable: true,
  2138. configurable: true
  2139. });
  2140.  
  2141. /*
  2142. const weakWrapperNodeHandlerFn = () => ({
  2143. get() {
  2144. let w = shadyDOMNodeWRM.get(this);
  2145. if (typeof w === 'object') w = kRef(w) || (shadyDOMNodeWRM.delete(this), undefined);
  2146. return w;
  2147. },
  2148. set(nv) {
  2149. const wv = (nv[selfWrKey] || (nv[selfWrKey] = mWeakRef(nv)));
  2150. shadyDOMNodeWRM.set(this, wv);
  2151. return true;
  2152. },
  2153. enumerable: true,
  2154. configurable: true
  2155. });
  2156. */
  2157.  
  2158. function weakWrapper(_ShadyDOM) {
  2159. const ShadyDOM = _ShadyDOM;
  2160. if (WEAKREF_ShadyDOM && lz < 3 && typeof WeakRef === 'function' && typeof ShadyDOM.Wrapper === 'function' && ShadyDOM.Wrapper.length === 1 && typeof (ShadyDOM.Wrapper.prototype || 0) === 'object') {
  2161. let nullElement = { node: null };
  2162. Object.setPrototypeOf(nullElement, Element.prototype);
  2163. let p = new ShadyDOM.Wrapper(nullElement);
  2164. let d = Object.getOwnPropertyDescriptor(p, 'node');
  2165. if (d.configurable && d.enumerable && !d.get && !d.set && d.writable && d.value === nullElement && !Object.getOwnPropertyDescriptor(ShadyDOM.Wrapper.prototype, 'node')) {
  2166. Object.defineProperty(ShadyDOM.Wrapper.prototype, 'node', weakWrapperNodeHandlerFn());
  2167. console.log('[yt-js-engine-tamer] FIX::ShadyDOM << WEAKREF_ShadyDOM >>')
  2168. }
  2169. // Object.defineProperty(ShadyDOM.Wrapper.prototype, '__cleanup__', function(){
  2170. // // to be reviewed
  2171. // debugger;
  2172.  
  2173.  
  2174.  
  2175.  
  2176. // });
  2177.  
  2178.  
  2179. }
  2180. if (typeof (((ShadyDOM || 0).Wrapper || 0).prototype || 0) === 'object') {
  2181. try {
  2182. setupSDomWrapper();
  2183. } catch (e) { }
  2184. }
  2185.  
  2186. }
  2187.  
  2188. let previousWrapStore = null;
  2189.  
  2190. const standardWrap = function (a) {
  2191. if (a instanceof ShadowRoot || a instanceof ShadyDOM.Wrapper) return a;
  2192. if (previousWrapStore) {
  2193. const s = kRef(previousWrapStore.get(a)); // kRef for play safe only
  2194. if (s) {
  2195. previousWrapStore.delete(a);
  2196. shadyDOMNodeWRM.set(a, mWeakRef(s));
  2197. }
  2198. }
  2199. let u = kRef(shadyDOMNodeWRM.get(a));
  2200. if (!u) {
  2201. u = new ShadyDOM.Wrapper(a);
  2202. shadyDOMNodeWRM.set(a, mWeakRef(u));
  2203. }
  2204. return u;
  2205. }
  2206.  
  2207.  
  2208. function setupWrapFunc(_ShadyDOM) {
  2209. const ShadyDOM = _ShadyDOM;
  2210.  
  2211.  
  2212. const wmPD = Object.getOwnPropertyDescriptor(WeakMap.prototype, 'get');
  2213. if (!(wmPD && wmPD.writable && !wmPD.enumerable && wmPD.configurable && wmPD.value && !wmPD.get && !wmPD.set)) {
  2214. return;
  2215. }
  2216. let mm = new Set();
  2217. const pget = wmPD.value;
  2218. WeakMap.prototype.get = function (a) {
  2219. mm.add(this);
  2220. return a;
  2221. }
  2222. try {
  2223. let nullElement = { node: null };
  2224. Object.setPrototypeOf(nullElement, Element.prototype);
  2225. ShadyDOM.wrapIfNeeded(nullElement)
  2226. ShadyDOM.wrap(nullElement)
  2227. } catch (e) { }
  2228. WeakMap.prototype.get = pget;
  2229. if (mm.size !== 1) {
  2230. mm.clear();
  2231. return;
  2232. }
  2233. const p = mm.values().next().value;
  2234. if (!(p instanceof WeakMap)) return;
  2235. // p.clear();
  2236. // p.get = function (a) { return a }
  2237. // p.set = function (a, b) { return this }
  2238. // console.log(188, window.n2n = mm, window.n2p = p)
  2239.  
  2240. // console.log(34929,p.size)
  2241. previousWrapStore = p;
  2242.  
  2243. if (typeof ShadyDOM.wrap === 'function' && ShadyDOM.wrap.length === 1) {
  2244. ShadyDOM.wrap = function (a) { 0 && console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - wrap'); return standardWrap(a) }
  2245. }
  2246. if (typeof ShadyDOM.wrapIfNeeded === 'function' && ShadyDOM.wrapIfNeeded.length === 1) {
  2247. ShadyDOM.wrapIfNeeded = function (a) { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - wrapIfNeeded'); return standardWrap(a) }
  2248. }
  2249.  
  2250. }
  2251.  
  2252. function setupLZ3(nv) {
  2253.  
  2254. const ShadyDOM = nv;
  2255.  
  2256. const ShadyDOMSettings = ShadyDOM.settings;
  2257. if (!(ShadyDOMSettings.inUse === true && ShadyDOM.inUse === true && (ShadyDOMSettings.handlesDynamicScoping || ShadyDOM.handlesDynamicScoping) === true)) {
  2258. console.log(3719, '[yt-js-engine-tamer] OMIT_ShadyDOM is not applied [02]', window.ShadyDOM);
  2259. return false;
  2260. }
  2261.  
  2262. weakWrapper(ShadyDOM);
  2263.  
  2264. if (OMIT_ShadyDOM_EXPERIMENTAL && lz < 3) {
  2265.  
  2266. setupPlainShadyDOM(ShadyDOMSettings);
  2267. setupPlainShadyDOM(ShadyDOM);
  2268.  
  2269. ShadyDOM.isShadyRoot = function () { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - isShadyRoot'); return false; }
  2270.  
  2271. setupWrapFunc(ShadyDOM);
  2272. ShadyDOM.patchElementProto = function () { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - patchElementProto') }
  2273. ShadyDOM.patch = function () { console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM) function call - patch') }
  2274.  
  2275. // To be confirmed
  2276. if (OMIT_ShadyDOM_EXPERIMENTAL & 2) {
  2277. ShadyDOM.composedPath = function (e) {
  2278. const t = (e || 0).target || null;
  2279. if (!(t instanceof HTMLElement_)) {
  2280. console.log(3719, '[yt-js-engine-tamer] (OMIT_ShadyDOM&2) composedPath', t)
  2281. }
  2282. return t instanceof HTMLElement_ ? [t] : [];
  2283. };
  2284. }
  2285.  
  2286. }
  2287.  
  2288. }
  2289.  
  2290.  
  2291. function setupLZ6(nv) {
  2292.  
  2293. const ShadyDOM = nv;
  2294.  
  2295. const ShadyDOMSettings = ShadyDOM.settings;
  2296.  
  2297. if (!(ShadyDOMSettings.inUse === true && ShadyDOM.inUse === true && (ShadyDOMSettings.handlesDynamicScoping || ShadyDOM.handlesDynamicScoping) === true)) {
  2298. console.log(3719, '[yt-js-engine-tamer] OMIT_ShadyDOM is not applied [02]', window.ShadyDOM);
  2299. return false;
  2300. }
  2301.  
  2302. weakWrapper(ShadyDOM);
  2303.  
  2304. if (OMIT_ShadyDOM_EXPERIMENTAL && lz < 3) {
  2305.  
  2306. setupPlainShadyDOM(ShadyDOMSettings);
  2307. setupPlainShadyDOM(ShadyDOM);
  2308.  
  2309. setupWrapFunc(ShadyDOM);
  2310.  
  2311. }
  2312.  
  2313. }
  2314.  
  2315. if (b && typeof b.Wrapper === 'function' && typeof b.settings === 'object' && typeof b.wrap === 'function') {
  2316.  
  2317. const nv = b;
  2318.  
  2319. if (setupLZ6(nv) === false) return;
  2320.  
  2321. lz = 6;
  2322.  
  2323. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM << 02b >>', nv)
  2324.  
  2325. return;
  2326. }
  2327.  
  2328. delete window.ShadyDOM;
  2329.  
  2330. Object.defineProperty(window, 'ShadyDOM', {
  2331. get() {
  2332. return b;
  2333. },
  2334. set(nv) {
  2335. let ret = 0;
  2336. try {
  2337. do {
  2338. if (!nv || !nv.settings) {
  2339. if (lz < 1 && nv && typeof nv === 'object' && isPlainObject(nv, 0)) {
  2340. OMIT_ShadyDOM_EXPERIMENTAL && setupPlainShadyDOM(nv);
  2341. lz = 1;
  2342. break;
  2343. } else {
  2344. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM is not applied [nv:null]', nv);
  2345. break;
  2346. }
  2347. }
  2348.  
  2349. const sdp = Object.getOwnPropertyDescriptor(this || {}, 'ShadyDOM');
  2350. if (!(sdp && sdp.configurable && sdp.get && sdp.set)) {
  2351. console.log(3719, '[yt-js-engine-tamer] OMIT_ShadyDOM is not applied [ incorrect PropertyDescriptor ]', nv);
  2352. break;
  2353. }
  2354.  
  2355. if (setupLZ3(nv) === false) break;
  2356.  
  2357. lz = 3;
  2358.  
  2359. console.log(3719, '[yt-js-engine-tamer] FIX::ShadyDOM << 02a >>', nv)
  2360.  
  2361. ret = 1;
  2362.  
  2363. } while (0);
  2364. } catch (e) {
  2365. console.log('[yt-js-engine-tamer] FIX::ShadyDOM << ERROR >>', e)
  2366. }
  2367.  
  2368. if (!ret) b = nv;
  2369. else {
  2370. delete this.ShadyDOM;
  2371. this.ShadyDOM = nv;
  2372. }
  2373. return true;
  2374. },
  2375. enumerable: false,
  2376. configurable: true
  2377. });
  2378.  
  2379. })(typeof WeakRef !== 'undefined' ? WeakRef : function () { });
  2380.  
  2381. if (ENABLE_ASYNC_DISPATCHEVENT) {
  2382. const filter = new Set([
  2383. 'yt-action',
  2384. // 'iframe-src-replaced',
  2385. 'shown-items-changed',
  2386. 'can-show-more-changed', 'collapsed-changed',
  2387.  
  2388. 'yt-navigate', 'yt-navigate-start', 'yt-navigate-cache',
  2389. 'yt-player-updated', 'yt-page-data-fetched', 'yt-page-type-changed', 'yt-page-data-updated',
  2390. 'yt-navigate-finish',
  2391.  
  2392. // 'data-changed','yt-watch-comments-ready'
  2393. ])
  2394. EventTarget.prototype.dispatchEvent938 = EventTarget.prototype.dispatchEvent;
  2395. EventTarget.prototype.dispatchEvent = function (event) {
  2396. const type = (event || 0).type;
  2397. if (typeof type === 'string' && event.isTrusted === false && (event instanceof CustomEvent) && event.cancelable === false) {
  2398. if (!filter.has(type) && !type.endsWith('-changed')) {
  2399. if (this instanceof Node || this instanceof Window) {
  2400. nextBrowserTick_(() => this.dispatchEvent938(event));
  2401. return true;
  2402. }
  2403. }
  2404. }
  2405. return this.dispatchEvent938(event);
  2406. }
  2407. }
  2408.  
  2409. // avoid REGEXP testPattern execution in Brave's scriptlet for performance boost
  2410. SCRIPTLET_REMOVE_PRUNE_propNeedles && (() => {
  2411. // const xhr = new XMLHttpRequest;
  2412. const pdOri = Object.getOwnPropertyDescriptor(Map.prototype, 'size');
  2413. if (!pdOri || pdOri.configurable !== true) return;
  2414. let propNeedles = null;
  2415. const pdNew = {
  2416. configurable: true,
  2417. enumerable: true,
  2418. get: function () {
  2419. propNeedles = this;
  2420. if (DEBUG_removePrune) debugger; // to locate Brave scriptlets
  2421. throw new Error();
  2422. }
  2423. }
  2424. Object.defineProperty(Map.prototype, 'size', pdNew);
  2425. try {
  2426. XMLHttpRequest.prototype.open.call(0);
  2427. // xhr.open.call(null)
  2428. } catch (e) { }
  2429. Object.defineProperty(Map.prototype, 'size', pdOri);
  2430. if (!propNeedles) return;
  2431. const entries = [...propNeedles.entries()];
  2432. propNeedles.clear();
  2433. console.log('[yt-js-engine-tamer] propNeedles is cleared from scriptlet', entries, propNeedles);
  2434. })();
  2435.  
  2436. if (FIX_XHR_REQUESTING) {
  2437.  
  2438. const URL = window.URL || new Function('return URL')();
  2439. const createObjectURL = URL.createObjectURL.bind(URL);
  2440.  
  2441. XMLHttpRequest = (() => {
  2442. const XMLHttpRequest_ = XMLHttpRequest;
  2443. if ('__xmMc8__' in XMLHttpRequest_.prototype) return XMLHttpRequest_;
  2444. const url0 = createObjectURL(new Blob([], { type: 'text/plain' }));
  2445. const c = class XMLHttpRequest extends XMLHttpRequest_ {
  2446. constructor(...args) {
  2447. super(...args);
  2448. }
  2449. open(method, url, ...args) {
  2450. let skip = false;
  2451. if (!url || typeof url !== 'string') skip = true;
  2452. else if (typeof url === 'string') {
  2453. let turl = url[0] === '/' ? `.youtube.com${url}` : `${url}`;
  2454. if (turl.includes('googleads') || turl.includes('doubleclick.net')) {
  2455. skip = true;
  2456. } else if (turl.includes('.youtube.com/pagead/')) {
  2457. skip = true;
  2458. } else if (turl.includes('.youtube.com/ptracking')) {
  2459. skip = true;
  2460. } else if (turl.includes('.youtube.com/youtubei/v1/log_event?')) {
  2461. skip = true;
  2462. } else if (turl.includes('.youtube.com/api/stats/')) { // /api/stats/
  2463. if (turl.includes('.youtube.com/api/stats/qoe?')) {
  2464. skip = true;
  2465. } else if (turl.includes('.youtube.com/api/stats/ads?')) {
  2466. skip = true;
  2467. } else {
  2468. // skip = true; // for user activity logging e.g. watched videos
  2469. }
  2470. } else if (turl.includes('play.google.com/log')) {
  2471. skip = true;
  2472. } else if (turl.includes('.youtube.com//?')) { // //?cpn=
  2473. skip = true;
  2474. }
  2475. }
  2476. if (!skip) {
  2477. this.__xmMc8__ = 1;
  2478. return super.open(method, url, ...args);
  2479. } else {
  2480. this.__xmMc8__ = 2;
  2481. return super.open('GET', url0);
  2482. }
  2483. }
  2484. send(...args) {
  2485. if (this.__xmMc8__ === 1) {
  2486. return super.send(...args);
  2487. } else if (this.__xmMc8__ === 2) {
  2488. return super.send();
  2489. } else {
  2490. console.log('[yt-js-engine-tamer]', 'xhr warning');
  2491. return super.send(...args);
  2492. }
  2493. }
  2494. }
  2495. c.prototype.__xmMc8__ = 0;
  2496. prototypeInherit(c.prototype, XMLHttpRequest_.prototype);
  2497. return c;
  2498. })();
  2499. }
  2500.  
  2501. // Alternative HACK -> Tabview Youtube
  2502. if (DISABLE_COOLDOWN_SCROLLING && typeof EventTarget.prototype.addEventListener52178 !== 'function' && typeof EventTarget.prototype.addEventListener === 'function') {
  2503.  
  2504. // ---- << this.overscrollConfig HACK >> -----
  2505.  
  2506. // 2024.04.19 - Playlist in Single Column Mode cannot be scrolled correctly.
  2507.  
  2508. /*
  2509.  
  2510. ;function gZb(a, b) {
  2511. b = void 0 === b ? !0 : b;
  2512. a.addEventListener("wheel", hZb);
  2513. a.overscrollConfig = {
  2514. cooldown: b
  2515. }
  2516. }
  2517. function iZb(a) {
  2518. a.overscrollConfig = void 0;
  2519. a.removeEventListener("wheel", hZb)
  2520. }
  2521. function hZb(a) {
  2522. var b = a.deltaY
  2523. , c = a.target
  2524. , d = null;
  2525. if (window.Polymer && window.Polymer.Element) {
  2526. if (c = a.path || a.composedPath && a.composedPath()) {
  2527. c = g(c);
  2528. for (var e = c.next(); !e.done && (e = e.value,
  2529. !jZb(e, b)); e = c.next())
  2530. if (e.overscrollConfig) {
  2531. d = e;
  2532. break
  2533. }
  2534. }
  2535. } else
  2536. for (; c && !jZb(c, b); ) {
  2537. if (c.overscrollConfig) {
  2538. d = c;
  2539. break
  2540. }
  2541. c = c.parentElement
  2542. }
  2543. d && (b = d.overscrollConfig,
  2544. b.cooldown ? (d = a.deltaY,
  2545. c = b.lastDeltaY || 0,
  2546. b.lastDeltaY = d,
  2547. e = b.lastStopped || 0,
  2548. c && e && 0 < c == 0 < d ? Math.abs(c) >= Math.abs(d) ? (d = e + 1200,
  2549. c = !1) : (d = e + 600,
  2550. c = !0) : (d = Date.now() + 600,
  2551. c = !0),
  2552. d > Date.now() && (a.preventDefault(),
  2553. c && (b.lastStopped = Date.now()))) : a.preventDefault())
  2554. }
  2555. */
  2556.  
  2557. let wheelHandler = function (a) {
  2558. if (window.Polymer && window.Polymer.Element) {
  2559. let c;
  2560. if (c = a.path || a.composedPath && a.composedPath()) {
  2561. for (const e of c) {
  2562. const cnt = insp(e);
  2563. if (e.overscrollConfig) e.overscrollConfig = void 0;
  2564. if (cnt.overscrollConfig) cnt.overscrollConfig = void 0;
  2565. }
  2566. }
  2567. } else {
  2568. let e = a.target;
  2569. for (; e instanceof Element; e = e.parentElement) {
  2570. const cnt = insp(e);
  2571. if (e.overscrollConfig) e.overscrollConfig = void 0;
  2572. if (cnt.overscrollConfig) cnt.overscrollConfig = void 0;
  2573. }
  2574. }
  2575. };
  2576.  
  2577. let checkWheelListenerObjs = null;
  2578.  
  2579. let getObjsFn = () => {
  2580. let euyVal = 0;
  2581. const eukElm = {};
  2582. Object.setPrototypeOf(eukElm, HTMLElement_.prototype);
  2583. const euzObj = new Proxy(eukElm, {
  2584. get(target, prop) {
  2585. throw `ErrorF31.get(${prop})`
  2586. },
  2587. set(target, prop, value) {
  2588. throw `ErrorF33.set(${prop}, ${value})`
  2589. }
  2590. });
  2591. const euxElm = new Proxy(eukElm, {
  2592. get(target, prop) {
  2593. if (prop === 'scrollTop') {
  2594. euyVal = euyVal | 8;
  2595. return 0;
  2596. }
  2597. if (prop === 'overscrollConfig') {
  2598. euyVal = euyVal | 16;
  2599. return void 0;
  2600. }
  2601. if (prop === 'scrollHeight' || prop === 'clientHeight' || prop === 'offsetHeight') {
  2602. return 640;
  2603. }
  2604. if (prop === 'scrollLeft') {
  2605. euyVal = euyVal | 8;
  2606. return 0;
  2607. }
  2608. if (prop === 'scrollWidth' || prop === 'clientWidth' || prop === 'offsetWidth') {
  2609. return 800;
  2610. }
  2611. throw `ErrorF45.get(${prop})`
  2612. },
  2613. set(target, prop, value) {
  2614. throw `ErrorF47.set(${prop}, ${value})`
  2615. }
  2616. });
  2617. const eukEvt = {};
  2618. Object.setPrototypeOf(eukEvt, WheelEvent.prototype);
  2619. const euyEvt = new Proxy(eukEvt, {
  2620. get(target, prop) {
  2621. if (prop === 'deltaY' || prop === 'deltaX') {
  2622. euyVal = euyVal | 1;
  2623. return -999;
  2624. }
  2625. if (prop === 'target') {
  2626. euyVal = euyVal | 2;
  2627. return euxElm
  2628. }
  2629. if (prop === 'path' || prop === 'composedPath') {
  2630. euyVal = euyVal | 2;
  2631. return [euxElm]
  2632. }
  2633. throw `ErrorF51.get(${prop})`
  2634. },
  2635. set(target, prop, value) {
  2636. throw `ErrorF53.set(${prop}, ${value})`
  2637. }
  2638. });
  2639. const setVal = (v) => {
  2640. euyVal = v;
  2641. }
  2642. const getVal = () => {
  2643. return euyVal;
  2644. }
  2645. return { euzObj, euyEvt, setVal, getVal };
  2646. }
  2647.  
  2648. let checkWheelListener = (callback) => {
  2649.  
  2650. let callbackIdentifier = '';
  2651.  
  2652. let res = null;
  2653. try {
  2654. const { euzObj, euyEvt, getVal, setVal } = checkWheelListenerObjs || (checkWheelListenerObjs = getObjsFn());
  2655. setVal(0);
  2656. if (callback.call(euzObj, euyEvt) !== void 0) throw 'ErrorF99';
  2657. throw `RESULT${getVal()}`;
  2658. } catch (e) {
  2659. res = e;
  2660. }
  2661.  
  2662. res = `${res}` || `${null}`;
  2663. if (res.length > 20) res = `${res.substring(0, 20)}...`;
  2664.  
  2665. callbackIdentifier = res;
  2666. if (callbackIdentifier === 'RESULT27') 0;
  2667. else if (callbackIdentifier === 'RESULT0') {
  2668. // a.isSearch && !a.disableWheelScroll && B("desktop_enable_dmpanel_wheel_scroll")
  2669. } else if (callbackIdentifier.startsWith('RESULT')) {
  2670. console.log('wheel eventListener - RESULT', callbackIdentifier, callback)
  2671. }
  2672. return callbackIdentifier;
  2673.  
  2674. };
  2675.  
  2676. let callbackFound = false;
  2677. EventTarget.prototype.addEventListener52178 = EventTarget.prototype.addEventListener;
  2678. EventTarget.prototype.addEventListener = function (type, callback, option = void 0) {
  2679. // M-youtube-js-engine-tamer.52178
  2680. if (type === 'wheel' && !option && typeof callback === 'function' && callback.length === 1) {
  2681. // (( match with signature `a.addEventListener("wheel", hZb);` )) [subject to further review]
  2682. const callbackIdentifier = callback.yaujmoms || (callbackFound ? 'IGNORE' : (callback.yaujmoms = checkWheelListener(callback)));
  2683. // RESULTXX / ErrorFXX / Other...
  2684. if (callbackIdentifier === 'RESULT27') {
  2685. this.overscrollConfigDisable = true;
  2686. if (!callbackFound) {
  2687. callbackFound = true; // suppose only one function is assigned to overscrollConfig cooldown [no function binding]
  2688. getObjsFn = checkWheelListener = null;
  2689. checkWheelListenerObjs = null;
  2690. wheelHandler = null;
  2691. }
  2692. return void 0;
  2693. } else if (!callbackFound && !this.overscrollConfigDisable) {
  2694. this.overscrollConfigDisable = true;
  2695. this.addEventListener52178('wheel', wheelHandler, { passive: false });
  2696. }
  2697. }
  2698. return this.addEventListener52178(type, callback, option);
  2699. };
  2700.  
  2701. // ---- << this.overscrollConfig HACK >> -----
  2702.  
  2703. }
  2704.  
  2705. const { pageMediaWatcher, shortcutKeysFixer, keyboardController } = (() => {
  2706.  
  2707. let p_a_objWR = null;
  2708. let isSpaceKeyImmediate = false; // for ADVANCED_FIX_SHORTCUTKEYS
  2709. let ytPageReady = 0;
  2710.  
  2711. let isSpeedMastSpacebarControlEnabled = false; // youtube experimental feature // can be forced by CHANGE_SPEEDMASTER_SPACEBAR_CONTROL
  2712. let isGlobalSpaceControl = true;
  2713. let mediaPlayerElementWR = null;
  2714. let focusedElementAtSelection = null;
  2715.  
  2716. // let want_control_video = false;
  2717.  
  2718. let spaceBarControl_keyG = '';
  2719.  
  2720. let lastUserAction = 0;
  2721.  
  2722. const wmKeyControlPhase = new WeakMap();
  2723.  
  2724. let currentSelectionText = null;
  2725.  
  2726. const getCurrentSelectionText = () => {
  2727. if (currentSelectionText !== null) return currentSelectionText
  2728. return (currentSelectionText = `${getSelection()}`)
  2729. }
  2730.  
  2731. const pageMediaWatcher = () => {
  2732.  
  2733. // CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE && document.addEventListener('wheel', () => {
  2734. // want_control_video = false;
  2735. // }, { capture: true, passive: true });
  2736.  
  2737. document.addEventListener('yt-navigate', () => {
  2738. ytPageReady = 0;
  2739. });
  2740. document.addEventListener('yt-navigate-start', () => {
  2741. ytPageReady = 0;
  2742. });
  2743. document.addEventListener('yt-navigate-cache', () => {
  2744. ytPageReady = 0;
  2745. });
  2746.  
  2747. document.addEventListener('yt-navigate-finish', () => {
  2748. ytPageReady = 1;
  2749. });
  2750.  
  2751. document.addEventListener('durationchange', () => {
  2752. for (const elm of document.querySelectorAll('#movie_player video[src], #movie_player audio[src]')) {
  2753. if (elm.duration > 0.01) {
  2754. if (elm.closest('[hidden]')) continue;
  2755. mediaPlayerElementWR = mWeakRef(elm);
  2756. return;
  2757. }
  2758. }
  2759. }, { capture: true, passive: true });
  2760.  
  2761. document.addEventListener('selectionchange', (evt) => {
  2762. if (!evt || !evt.isTrusted || !(evt instanceof Event)) return;
  2763. currentSelectionText = null;
  2764. if (!(evt.target instanceof Node)) return;
  2765. focusedElementAtSelection = evt.target;
  2766. }, { capture: true, passive: true })
  2767.  
  2768. document.addEventListener('pointerdown', (evt) => {
  2769. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  2770. }, { capture: true, passive: true });
  2771.  
  2772.  
  2773. document.addEventListener('pointerup', (evt) => {
  2774. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  2775. }, { capture: true, passive: true });
  2776.  
  2777.  
  2778. document.addEventListener('keydown', (evt) => {
  2779. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  2780. }, { capture: true, passive: true });
  2781.  
  2782. document.addEventListener('keyup', (evt) => {
  2783. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  2784. }, { capture: true, passive: true });
  2785.  
  2786. };
  2787.  
  2788.  
  2789. const checkKeyB = (p_a_obj) => {
  2790.  
  2791. const boolList = new Set();
  2792. const p_a_obj_api = p_a_obj.api;
  2793.  
  2794. const nilFunc0 = function () {
  2795. return void 0
  2796. };
  2797. const mt = new Proxy({}, {
  2798. get(target, prop) {
  2799. if (prop === 'get') return nilFunc0;
  2800. return mt;
  2801. }
  2802. });
  2803. const nilFunc = function () {
  2804. return mt
  2805. };
  2806. const mw = new Proxy({}, {
  2807. get(target, prop) {
  2808. if (prop in p_a_obj_api) {
  2809. if (typeof p_a_obj_api.constructor.prototype[prop] === 'function') return nilFunc;
  2810. let q = Object.getOwnPropertyDescriptor(p_a_obj_api, prop);
  2811. if (q && q.value) {
  2812. if (!q.writable) return q.value;
  2813. if (typeof q.value === 'string') return '';
  2814. if (typeof q.value === 'number') return 0;
  2815. if (typeof q.value === 'boolean') return false;
  2816. if (q.value && typeof q.value === 'object') return {};
  2817. }
  2818. }
  2819. return undefined;
  2820. },
  2821. set(target, prop) {
  2822. throw 'mwSet';
  2823. }
  2824. });
  2825.  
  2826. const mq = new Proxy({}, {
  2827. get(target, prop) {
  2828. if (prop === 'api') return mw;
  2829. if (prop in p_a_obj) {
  2830. if (typeof p_a_obj.constructor.prototype[prop] === 'function') return nilFunc;
  2831. let q = Object.getOwnPropertyDescriptor(p_a_obj, prop);
  2832. if (q && q.value) {
  2833. if (!q.writable) return q.value;
  2834. if (typeof q.value === 'string') return '';
  2835. if (typeof q.value === 'number') return 0;
  2836. if (typeof q.value === 'boolean') return false;
  2837. if (q.value && typeof q.value === 'object') return {};
  2838. }
  2839. }
  2840. return undefined;
  2841. },
  2842. set(target, prop, val) {
  2843. if (typeof val === 'boolean') boolList.add(prop)
  2844. throw `mqSet(${prop},${val})`;
  2845. }
  2846. });
  2847.  
  2848. let res = ''
  2849. try {
  2850. res = `RESULT::${p_a_obj.handleGlobalKeyUp.call(mq, 9, false, false, false, false, "Tab", "Tab")}`;
  2851. } catch (e) {
  2852. res = `ERROR::${e}`;
  2853. }
  2854.  
  2855. if (boolList.size === 1) {
  2856. const value = boolList.values().next().value;
  2857. if (res === `ERROR::mqSet(${value},${true})`) {
  2858. p_a_obj.__uZWaD__ = value;
  2859. }
  2860. }
  2861.  
  2862. console.log('[yt-js-engine-tamer] global shortcut control', { '__uZWaD__': p_a_obj.__uZWaD__ });
  2863.  
  2864. }
  2865.  
  2866.  
  2867. let pm_p_a = null;
  2868.  
  2869. const p_a_init = function () {
  2870. const r = this.init91();
  2871. const keyBw = this.__cPzfo__ || '__NIL__';
  2872. const p_a_obj = this[keyBw];
  2873. if (!p_a_obj) return;
  2874. try {
  2875. checkKeyB(p_a_obj);
  2876. } catch (e) { }
  2877. p_a_objWR = mWeakRef(p_a_obj);
  2878. if (FIX_SHORTCUTKEYS > 0) {
  2879. if (p_a_obj && !p_a_obj.hVhtg) {
  2880. p_a_obj.hVhtg = 1;
  2881.  
  2882. p_a_obj.handleGlobalKeyUp91 = p_a_obj.handleGlobalKeyUp;
  2883. p_a_obj.handleGlobalKeyUp = p_a_xt.handleGlobalKeyUp;
  2884. p_a_obj.handleGlobalKeyDown91 = p_a_obj.handleGlobalKeyDown;
  2885. p_a_obj.handleGlobalKeyDown = p_a_xt.handleGlobalKeyDown;
  2886. p_a_obj.__handleGlobalKeyBefore__ = p_a_xt.__handleGlobalKeyBefore__;
  2887. p_a_obj.__handleGlobalKeyAfter__ = p_a_xt.__handleGlobalKeyAfter__;
  2888.  
  2889. }
  2890. // if (CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE && p_a_obj && p_a_obj.api && !p_a_obj.api.hVhtg) {
  2891. // const api = p_a_obj.api
  2892. // api.hVhtg = 1;
  2893. // api.playVideo91 = api.playVideo;
  2894. // api.playVideo = p_a_jt.playVideo;
  2895. // api.pauseVideo91 = api.pauseVideo;
  2896. // api.pauseVideo = p_a_jt.pauseVideo;
  2897. // }
  2898. }
  2899. if (pm_p_a) {
  2900. pm_p_a.resolve();
  2901. pm_p_a = null;
  2902. }
  2903. return r;
  2904. };
  2905.  
  2906. const p_a_xt = {
  2907.  
  2908. __handleGlobalKeyBefore__(a, b, c, d, e, f, h, activeElement) {
  2909.  
  2910. if (FIX_SHORTCUTKEYS === 2) {
  2911.  
  2912. // if (flagSpeedMaster !== false && !getGlobalSpacebarControlFlag()) return false;
  2913.  
  2914. if (activeElement) {
  2915.  
  2916. const controlPhaseCache = wmKeyControlPhase.get(activeElement);
  2917.  
  2918. if (controlPhaseCache === 6 && getCurrentSelectionText() !== "") void 0;
  2919. else if (controlPhaseCache === 1 || controlPhaseCache === 2 || controlPhaseCache === 5) return false;
  2920. else if ((controlPhaseCache !== 6 || focusedElementAtSelection === document.activeElement) && getCurrentSelectionText() !== "") return false;
  2921.  
  2922. }
  2923.  
  2924. const isSpaceBar = a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space';
  2925. const isDelayedSpaceBar = FIX_SHORTCUTKEYS === 2 && isSpaceBar && !isSpaceKeyImmediate && (isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag());
  2926. // console.log(582, isDelayedSpaceBar)
  2927. if (isDelayedSpaceBar) return void 0; // accept delay spacebar under isSpeedMastSpacebarControlEnabled (no rejection)
  2928.  
  2929. if (activeElement && (h === 'Space' || h === 'Enter')) {
  2930. const controlPhase = wmKeyControlPhase.get(activeElement);
  2931. if (controlPhase === 4 || controlPhase === 5) return false;
  2932. }
  2933. if (focusedElementAtSelection === activeElement && getCurrentSelectionText() !== "") return false;
  2934. // if (!isSpeedMastSpacebarControlEnabled && a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space') {
  2935. // if (!isSpaceKeyImmediate) return false;
  2936. // }
  2937. }
  2938.  
  2939. },
  2940.  
  2941. __handleGlobalKeyAfter__(a, b, c, d, e, f, h, activeElement, ret) {
  2942.  
  2943. if (FIX_SHORTCUTKEYS === 2 && ret && a >= 32 && ytPageReady === 1 && Date.now() - lastUserAction < 40 && activeElement === document.activeElement) {
  2944.  
  2945. const isSpaceBar = a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space';
  2946. const isDelayedSpaceBar = FIX_SHORTCUTKEYS === 2 && isSpaceBar && !isSpaceKeyImmediate && (isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag());
  2947. // console.log(583, isDelayedSpaceBar)
  2948. if (isDelayedSpaceBar) return void 0; // accept delay spacebar under isSpeedMastSpacebarControlEnabled (no rejection)
  2949.  
  2950. const mediaPlayerElement = kRef(mediaPlayerElementWR);
  2951.  
  2952. let mediaWorking = false;
  2953. if (mediaPlayerElement && (mediaPlayerElement.readyState === 4 || mediaPlayerElement.readyState === 1) && mediaPlayerElement.networkState === 2 && mediaPlayerElement.duration > 0.01) {
  2954. mediaWorking = true;
  2955. } else if (mediaPlayerElement && !mediaPlayerElement.paused && !mediaPlayerElement.muted && mediaPlayerElement.duration > 0.01) {
  2956. mediaWorking = true;
  2957. }
  2958. // console.log(182, mediaWorking, mediaPlayerElement.readyState , mediaPlayerElement.networkState)
  2959. mediaWorking && Promise.resolve().then(() => {
  2960. if (activeElement === document.activeElement) {
  2961. return activeElement.blur()
  2962. } else {
  2963. return false
  2964. }
  2965. }).then((r) => {
  2966. r !== false && mediaPlayerElement.focus();
  2967. });
  2968. }
  2969. },
  2970.  
  2971.  
  2972. handleGlobalKeyUp(a, b, c, d, e, f, h) {
  2973.  
  2974. if (BY_PASS_KEYBOARD_CONTROL) return this.handleGlobalKeyUp91(a, b, c, d, e, f, h);
  2975.  
  2976. const activeElement = document.activeElement;
  2977.  
  2978. const allow = typeof this.__handleGlobalKeyBefore__ === 'function' ? this.__handleGlobalKeyBefore__(a, b, c, d, e, f, h, activeElement) : void 0;
  2979. if (allow === false) return false;
  2980.  
  2981. const ret = this.handleGlobalKeyUp91(a, b, c, d, e, f, h);
  2982. // console.log('handleGlobalKeyUp',ret, a, b, c, d, e, f, h);
  2983.  
  2984. typeof this.__handleGlobalKeyAfter__ === 'function' && this.__handleGlobalKeyAfter__(a, b, c, d, e, f, h, activeElement, ret);
  2985.  
  2986. return ret;
  2987. },
  2988. handleGlobalKeyDown(a, b, c, d, e, f, h, l) {
  2989.  
  2990.  
  2991. if (BY_PASS_KEYBOARD_CONTROL) return this.handleGlobalKeyDown91(a, b, c, d, e, f, h, l);
  2992.  
  2993. const activeElement = document.activeElement;
  2994. // if (a === 32 && b === false && c === false && d === false && e === false && f === ' ' && h === 'Space' && !(isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag())) {
  2995. // return this.handleGlobalKeyDown91(a, b, c, d, e, f, h, l);
  2996. // }
  2997. const allow = typeof this.__handleGlobalKeyBefore__ === 'function' ? this.__handleGlobalKeyBefore__(a, b, c, d, e, f, h, activeElement) : void 0;
  2998. if (allow === false) return false;
  2999.  
  3000. const ret = this.handleGlobalKeyDown91(a, b, c, d, e, f, h, l);
  3001. // console.log('handleGlobalKeyDown',ret, a, b, c, d, e, f, h,l)
  3002.  
  3003. typeof this.__handleGlobalKeyAfter__ === 'function' && this.__handleGlobalKeyAfter__(a, b, c, d, e, f, h, activeElement, ret);
  3004.  
  3005. return ret;
  3006. }
  3007.  
  3008. };
  3009.  
  3010. // const p_a_jt = { // API
  3011.  
  3012. // playVideo(a) { // without spinner effect
  3013.  
  3014. // if (CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE) {
  3015.  
  3016. // const mediaPlayerElement = kRef(mediaPlayerElementWR);
  3017. // if (mediaPlayerElement && !mediaPlayerElement.paused && !mediaPlayerElement.muted && mediaPlayerElement.duration > 0.01) {
  3018. // want_control_video = true;
  3019. // // Promise.resolve().then(()=> mediaPlayerElement.focus() );
  3020. // }
  3021.  
  3022. // }
  3023. // return this.playVideo91(a);
  3024.  
  3025. // },
  3026.  
  3027. // pauseVideo(a) { // without spinner effect
  3028.  
  3029. // if (CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE) {
  3030.  
  3031. // const mediaPlayerElement = kRef(mediaPlayerElementWR);
  3032. // if (mediaPlayerElement && mediaPlayerElement.paused && !mediaPlayerElement.muted && mediaPlayerElement.duration > 0.01) {
  3033. // want_control_video = true;
  3034. // // Promise.resolve().then(()=> mediaPlayerElement.focus() );
  3035. // }
  3036.  
  3037. // }
  3038. // return this.pauseVideo91(a);
  3039.  
  3040. // }
  3041. // };
  3042.  
  3043. let flagSpeedMaster = null;
  3044. const getSpeedMasterControlFlag = () => {
  3045.  
  3046. const config = (win.yt || 0).config_ || (win.ytcfg || 0).data_ || 0;
  3047. isSpeedMastSpacebarControlEnabled = false;
  3048. if (config && config.EXPERIMENT_FLAGS && config.EXPERIMENT_FLAGS.web_speedmaster_spacebar_control) {
  3049. isSpeedMastSpacebarControlEnabled = true;
  3050. }
  3051. if (config && config.EXPERIMENTS_FORCED_FLAGS && config.EXPERIMENTS_FORCED_FLAGS.web_speedmaster_spacebar_control) {
  3052. isSpeedMastSpacebarControlEnabled = true;
  3053. }
  3054.  
  3055. if (flagSpeedMaster === null) {
  3056. const p = (((config || 0).WEB_PLAYER_CONTEXT_CONFIGS || 0).WEB_PLAYER_CONTEXT_CONFIG_ID_KEVLAR_WATCH || 0).serializedExperimentFlags;
  3057. if (!p) {
  3058. flagSpeedMaster = false;
  3059. } else {
  3060.  
  3061. flagSpeedMaster = (p.includes('web_enable_speedmaster=true') && p.includes('web_speedmaster_spacebar_control=true') && p.includes('web_speedmaster_updated_edu=true'));
  3062.  
  3063. }
  3064.  
  3065. }
  3066. if (!flagSpeedMaster) isSpeedMastSpacebarControlEnabled = false;
  3067.  
  3068. return isSpeedMastSpacebarControlEnabled;
  3069. }
  3070.  
  3071.  
  3072. const getGlobalSpacebarControlFlag = () => {
  3073.  
  3074. const config = (win.yt || 0).config_ || (win.ytcfg || 0).data_ || 0;
  3075. isGlobalSpaceControl = false;
  3076. if (config && config.EXPERIMENT_FLAGS && config.EXPERIMENT_FLAGS.global_spacebar_pause) {
  3077. isGlobalSpaceControl = true;
  3078. }
  3079. if (config && config.EXPERIMENTS_FORCED_FLAGS && config.EXPERIMENTS_FORCED_FLAGS.global_spacebar_pause) {
  3080. isGlobalSpaceControl = true;
  3081. }
  3082.  
  3083. return isGlobalSpaceControl;
  3084. }
  3085.  
  3086. const keyboardController = async (_yt_player) => {
  3087.  
  3088. const keyQT = getQT(_yt_player);
  3089. const keySV = getSV(_yt_player);
  3090. const keyDX = getDX(_yt_player);
  3091. console.log(`[QT,SV,DX]`, [keyQT, keySV, keyDX]);
  3092.  
  3093. if (!keyDX) return;
  3094. if (keyDX === keyQT || keyDX === keySV) return;
  3095.  
  3096. if (typeof keyDX !== 'string') return;
  3097.  
  3098. let lastAccessKey = '';
  3099. let lastAccessKeyConfirmed = '';
  3100. const mb = new Proxy({}, {
  3101. get(target, prop) {
  3102. if (prop === 'handleGlobalKeyUp') lastAccessKeyConfirmed = lastAccessKey;
  3103. throw 'mbGet'
  3104. },
  3105. set(target, prop, val) {
  3106. throw 'mbSet'
  3107. }
  3108. });
  3109. const ma = new Proxy({}, {
  3110. get(target, prop) {
  3111. lastAccessKey = prop;
  3112. return mb
  3113. },
  3114. set(target, prop, val) {
  3115. throw 'maSet'
  3116. }
  3117. });
  3118.  
  3119. let keyBw = '';
  3120. try {
  3121. _yt_player[keyDX].prototype.handleGlobalKeyUp.call(ma);
  3122. } catch (e) {
  3123. if (e === 'mbGet' && typeof lastAccessKeyConfirmed === 'string' && lastAccessKeyConfirmed.length > 0) {
  3124. keyBw = lastAccessKeyConfirmed;
  3125. }
  3126. }
  3127.  
  3128. if (!keyBw) return;
  3129.  
  3130. if (typeof _yt_player[keyDX].prototype.init !== 'function' || _yt_player[keyDX].prototype.init.length !== 0) return;
  3131.  
  3132. pm_p_a = new PromiseExternal();
  3133.  
  3134. _yt_player[keyDX].prototype.__cPzfo__ = keyBw;
  3135.  
  3136. _yt_player[keyDX].prototype.init91 = _yt_player[keyDX].prototype.init;
  3137.  
  3138. _yt_player[keyDX].prototype.init = p_a_init;
  3139.  
  3140. await pm_p_a.then();
  3141. const p_a_obj = kRef(p_a_objWR);
  3142.  
  3143. const isSpeedMastSpacebarControlEnabledA = getSpeedMasterControlFlag();
  3144.  
  3145.  
  3146. if (CHANGE_SPEEDMASTER_SPACEBAR_CONTROL > 0) {
  3147.  
  3148. isSpeedMastSpacebarControlEnabled = CHANGE_SPEEDMASTER_SPACEBAR_CONTROL == 1;
  3149.  
  3150. if (!isSpeedMastSpacebarControlEnabled) {
  3151.  
  3152. if (config && config.EXPERIMENT_FLAGS) {
  3153. config.EXPERIMENT_FLAGS.web_speedmaster_spacebar_control = false;
  3154. }
  3155. if (config && config.EXPERIMENTS_FORCED_FLAGS) {
  3156. config.EXPERIMENTS_FORCED_FLAGS.web_speedmaster_spacebar_control = false;
  3157. }
  3158.  
  3159. } else {
  3160.  
  3161. if (config && config.EXPERIMENT_FLAGS) {
  3162. config.EXPERIMENT_FLAGS.web_speedmaster_spacebar_control = true;
  3163. }
  3164. if (config && config.EXPERIMENTS_FORCED_FLAGS) {
  3165. config.EXPERIMENTS_FORCED_FLAGS.web_speedmaster_spacebar_control = true;
  3166. }
  3167.  
  3168. }
  3169.  
  3170. }
  3171.  
  3172. const isSpeedMastSpacebarControlEnabledB = getSpeedMasterControlFlag();
  3173.  
  3174.  
  3175.  
  3176.  
  3177. console.log('[yt-js-engine-tamer] speedmaster by space (yt setting)', isSpeedMastSpacebarControlEnabledA, isSpeedMastSpacebarControlEnabledB);
  3178.  
  3179. // console.log(p_a_obj.handleGlobalKeyUp)
  3180. console.log('[yt-js-engine-tamer] p_a', p_a_obj);
  3181.  
  3182. // console.log(p_a_obj.api)
  3183.  
  3184.  
  3185. // QT -> DX(SV) -> p_a
  3186.  
  3187.  
  3188. /*
  3189. *
  3190. *
  3191. g.k.handleGlobalKeyUp = function(a, b, c, d, e, f, h) {
  3192. b = void 0 === b ? !1 : b;
  3193. c = void 0 === c ? !1 : c;
  3194. d = void 0 === d ? !1 : d;
  3195. e = void 0 === e ? !1 : e;
  3196. var l = g.PT(this);
  3197. l && l.handleGlobalKeyUp(a, b, c, d, e, f, h)
  3198. }
  3199.  
  3200. */
  3201.  
  3202. /*
  3203. *
  3204. *
  3205. *
  3206. g.k.handleGlobalKeyUp = function(a, b, c, d, e, f, h) {
  3207. return this.Bw ? this.Bw.handleGlobalKeyUp(a, b, c, d, e, f, h) : !1
  3208. }
  3209.  
  3210. */
  3211.  
  3212.  
  3213. // if(!keyDX) return;
  3214.  
  3215. // console.log(4999, keyDX)
  3216.  
  3217. };
  3218.  
  3219.  
  3220. const ytResumeFn = function () { // ADVANCED_FIX_SHORTCUTKEYS
  3221.  
  3222. const p_a_obj = kRef(p_a_objWR);
  3223. // const api = p_a_obj.api;
  3224.  
  3225.  
  3226. // console.log(540);
  3227.  
  3228. let boolList = null;
  3229. let ret;
  3230. isSpaceKeyImmediate = true;
  3231. try {
  3232.  
  3233. ret = 0;
  3234. ret = ret | (p_a_obj.handleGlobalKeyDown(32, false, false, false, false, ' ', 'Space', false) ? 1 : 0);
  3235. let p_a_objT;
  3236. if (!spaceBarControl_keyG) { // just in case
  3237. boolList = new Set();
  3238. p_a_objT = new Proxy(p_a_obj, {
  3239. get(target, prop, handler) {
  3240. const val = target[prop];
  3241. if (typeof val !== 'boolean') return val;
  3242. boolList.add(prop);
  3243. // console.log(555, prop, val);
  3244. if (typeof prop === 'string' && prop.length <= 3 && val === true && boolList.length === 1) {
  3245. spaceBarControl_keyG = prop;
  3246. p_a_obj.__uZWaD__ = spaceBarControl_keyG;
  3247. val = false;
  3248. }
  3249. return val;
  3250. }
  3251. });
  3252.  
  3253.  
  3254. } else if (p_a_obj[spaceBarControl_keyG] === true) {
  3255. p_a_obj[spaceBarControl_keyG] = false;
  3256. p_a_objT = p_a_obj;
  3257. // console.log(p_a_obj, spaceBarControl_keyG, p_a_obj[spaceBarControl_keyG] )
  3258. } else {
  3259.  
  3260. p_a_objT = p_a_obj;
  3261. }
  3262.  
  3263. ret = ret | (p_a_objT.handleGlobalKeyUp(32, false, false, false, false, ' ', 'Space') ? 2 : 0);
  3264.  
  3265.  
  3266. } catch (e) {
  3267. console.log(e)
  3268. }
  3269. isSpaceKeyImmediate = false;
  3270.  
  3271. if (boolList && boolList.size === 1) {
  3272. const value = boolList.values().next().value;
  3273. spaceBarControl_keyG = value;
  3274. p_a_obj.__uZWaD__ = spaceBarControl_keyG;
  3275.  
  3276. }
  3277.  
  3278. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  3279.  
  3280. return ret;
  3281. }
  3282.  
  3283. const shortcutKeysFixer = () => {
  3284.  
  3285. let pausePromiseControlJ = 0;
  3286.  
  3287.  
  3288. const obtainCurrentControlPhase = (evt, mediaPlayerElement) => {
  3289.  
  3290. let controlPhase = 0;
  3291. const aElm = document.activeElement;
  3292.  
  3293. if (aElm) {
  3294.  
  3295. const controlPhaseCache = wmKeyControlPhase.get(aElm);
  3296.  
  3297. if (typeof controlPhaseCache === 'number') {
  3298.  
  3299. controlPhase = controlPhaseCache;
  3300. } else {
  3301.  
  3302. if (aElm instanceof HTMLInputElement) controlPhase = 1;
  3303. else if (aElm instanceof HTMLTextAreaElement) controlPhase = 1;
  3304. else if (aElm instanceof HTMLButtonElement) controlPhase = 2;
  3305. else if (aElm instanceof HTMLIFrameElement) controlPhase = 2;
  3306. else if (aElm instanceof HTMLImageElement) controlPhase = 2;
  3307. else if (aElm instanceof HTMLEmbedElement) controlPhase = 2;
  3308. else {
  3309. if (aElm instanceof HTMLElement_ && aElm.closest('[role]')) controlPhase = 5;
  3310. if (aElm instanceof HTMLDivElement) controlPhase = 2;
  3311. else if (aElm instanceof HTMLAnchorElement) controlPhase = 2;
  3312. else if (!(aElm instanceof HTMLElement_) && (aElm instanceof Element)) controlPhase = 2; // svg
  3313. }
  3314.  
  3315. if ((controlPhase === 2 || controlPhase === 5) && (aElm instanceof HTMLElement_) && aElm.contains(mediaPlayerElement)) {
  3316. controlPhase = 0;
  3317. }
  3318.  
  3319. if ((controlPhase === 2 || controlPhase === 5) && evt && evt.target && evt.target === aElm) {
  3320. if (aElm.closest('[contenteditable], input, textarea')) {
  3321. controlPhase = 5;
  3322. } else if (aElm.closest('button')) {
  3323. controlPhase = 4;
  3324. }
  3325. }
  3326.  
  3327. if (aElm.closest('#movie_player')) controlPhase = 6;
  3328.  
  3329. wmKeyControlPhase.set(aElm, controlPhase);
  3330.  
  3331. }
  3332. }
  3333.  
  3334. return controlPhase;
  3335.  
  3336. }
  3337.  
  3338. const isStateControllable = (api) => {
  3339. let appState = null;
  3340. let playerState = null;
  3341. let adState = null;
  3342. try {
  3343. appState = api.getAppState();
  3344. playerState = api.getPlayerState();
  3345. adState = api.getAdState();
  3346. } catch (e) { }
  3347. // ignore playerState -1
  3348. return appState === 5 && adState === -1 && (playerState === 1 || playerState === 2 || playerState === 3);
  3349. };
  3350.  
  3351.  
  3352. const keyEventListener = (evt) => {
  3353. if (BY_PASS_KEYBOARD_CONTROL) return;
  3354.  
  3355. if (evt.isTrusted && evt instanceof Event) lastUserAction = Date.now();
  3356. if (isSpaceKeyImmediate || !evt.isTrusted || !(evt instanceof KeyboardEvent)) return;
  3357. if (!ytPageReady) return;
  3358.  
  3359. if (evt.defaultPrevented === true) return;
  3360.  
  3361. const p_a_obj = kRef(p_a_objWR);
  3362.  
  3363. if (!p_a_obj) return;
  3364.  
  3365.  
  3366. const mediaPlayerElement = kRef(mediaPlayerElementWR);
  3367. if (!mediaPlayerElement) return;
  3368.  
  3369. // let focusBodyIfSuccess = false;
  3370.  
  3371. const controlPhase = obtainCurrentControlPhase(evt, mediaPlayerElement);
  3372.  
  3373. if (controlPhase === 6 && getCurrentSelectionText() !== "") void 0;
  3374. else if (controlPhase === 1 || controlPhase === 2 || controlPhase === 5) return;
  3375. else if ((controlPhase !== 6 || focusedElementAtSelection === document.activeElement) && getCurrentSelectionText() !== "") return;
  3376.  
  3377.  
  3378. if (evt.code === 'Space' && !getGlobalSpacebarControlFlag()) return;
  3379.  
  3380. // console.log(`${evt.type}::controlPhase`,controlPhase)
  3381.  
  3382. // if (controlPhase == 4) {
  3383. // focusBodyIfSuccess = true;
  3384. // }
  3385.  
  3386. spaceBarControl_keyG = spaceBarControl_keyG || p_a_obj.__uZWaD__ || ''
  3387. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  3388.  
  3389. if (FIX_SHORTCUTKEYS < 2) return;
  3390. if (!(!evt.shiftKey && !evt.ctrlKey && !evt.altKey && !evt.metaKey)) return; // ignore if modifier key is pressed -> let other event listener to handle first
  3391.  
  3392. let rr;
  3393. const isSpaceBar = evt.code === 'Space' && !evt.shiftKey && !evt.ctrlKey && !evt.altKey && !evt.metaKey;
  3394.  
  3395.  
  3396.  
  3397. let useImprovedPauseResume = false;
  3398.  
  3399. if (USE_IMPROVED_PAUSERESUME_UNDER_NO_SPEEDMASTER && isSpaceBar && !(isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag())) {
  3400.  
  3401. const api = p_a_obj.api;
  3402. const stateControllable = isStateControllable(api);
  3403. // console.log(2122, appState, playerState, adState)
  3404.  
  3405. if (stateControllable && isWatchPageURL() && mediaPlayerElement.duration > 0.01 && (mediaPlayerElement.readyState === 4 || mediaPlayerElement.readyState === 1) && mediaPlayerElement.networkState === 2) {
  3406.  
  3407. useImprovedPauseResume = true;
  3408.  
  3409. }
  3410.  
  3411.  
  3412. }
  3413.  
  3414.  
  3415. // force flag: CHANGE_SPEEDMASTER_SPACEBAR_CONTROL
  3416. if (evt.type === 'keydown') {
  3417.  
  3418. if (useImprovedPauseResume) {
  3419.  
  3420. const isPaused = mediaPlayerElement.paused;
  3421.  
  3422. const cj = ++pausePromiseControlJ;
  3423. Promise.resolve().then(() => {
  3424.  
  3425. if (cj !== pausePromiseControlJ) return;
  3426.  
  3427. if (mediaPlayerElement.paused !== isPaused) return;
  3428.  
  3429. const ret = ytResumeFn();
  3430. if (!ret) { // fallback
  3431. isPaused ? api.playVideo() : api.pauseVideo();
  3432. }
  3433.  
  3434. /*
  3435. let a = void 0;
  3436. console.log('Rb', api.Rb())
  3437. a = !window._yt_player.nL(api.Rb());
  3438. p_a_obj.Wd.kG(a)
  3439. a ? api.playVideo() : api.pauseVideo();
  3440.  
  3441. */
  3442.  
  3443.  
  3444. });
  3445. rr = true;
  3446. } else {
  3447.  
  3448. isSpaceKeyImmediate = true;
  3449. rr = p_a_obj.handleGlobalKeyDown(evt.keyCode, evt.shiftKey, evt.ctrlKey, evt.altKey, evt.metaKey, evt.key, evt.code, evt.repeat);
  3450. isSpaceKeyImmediate = false;
  3451. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  3452.  
  3453. }
  3454.  
  3455.  
  3456. } else if (evt.type === 'keyup') {
  3457.  
  3458. if (isSpaceBar && useImprovedPauseResume && !(isSpeedMastSpacebarControlEnabled = getSpeedMasterControlFlag())) {
  3459.  
  3460. rr = true;
  3461. } else {
  3462.  
  3463. isSpaceKeyImmediate = true;
  3464. rr = p_a_obj.handleGlobalKeyUp(evt.keyCode, evt.shiftKey, evt.ctrlKey, evt.altKey, evt.metaKey, evt.key, evt.code);
  3465. isSpaceKeyImmediate = false;
  3466. if (spaceBarControl_keyG && p_a_obj[spaceBarControl_keyG] === true) p_a_obj[spaceBarControl_keyG] = false;
  3467.  
  3468. }
  3469.  
  3470.  
  3471. /*
  3472.  
  3473. if (d)
  3474. switch (c) {
  3475. case 32:
  3476. case 13:
  3477. if ("BUTTON" === d.tagName || "A" === d.tagName || "INPUT" === d.tagName)
  3478. b = !0,
  3479. e = !1;
  3480. else if (e) {
  3481. var m = d.getAttribute("role");
  3482. !m || "option" !== m && "button" !== m && 0 !== m.indexOf("menuitem") || (b = !0,
  3483. d.click(),
  3484. f = !0)
  3485. }
  3486. break;
  3487. case 37:
  3488. case 39:
  3489. case 36:
  3490. case 35:
  3491. b = "slider" === d.getAttribute("role");
  3492. break;
  3493. case 38:
  3494. case 40:
  3495. m = d.getAttribute("role"),
  3496. d = 38 === c ? d.previousSibling : d.nextSibling,
  3497. "slider" === m ? b = !0 : e && ("option" === m ? (d && "option" === d.getAttribute("role") && d.focus(),
  3498. f = b = !0) : m && 0 === m.indexOf("menuitem") && (d && d.hasAttribute("role") && 0 === d.getAttribute("role").indexOf("menuitem") && d.focus(),
  3499. f = b = !0))
  3500. }
  3501. if (e && !f)
  3502. switch (c) {
  3503. case 38:
  3504. f = Math.min(this.api.getVolume() + 5, 100);
  3505. XV(this.Wd, f, !1);
  3506. this.api.setVolume(f);
  3507. h = f = !0;
  3508. break;
  3509. case 40:
  3510. f = Math.max(this.api.getVolume() - 5, 0);
  3511. XV(this.Wd, f, !0);
  3512. this.api.setVolume(f);
  3513. h = f = !0;
  3514. break;
  3515. case 36:
  3516. this.api.Yh() && (this.api.startSeekCsiAction(),
  3517. this.api.seekTo(0, void 0, void 0, void 0, 79),
  3518. h = f = !0);
  3519. break;
  3520. case 35:
  3521. this.api.Yh() && (this.api.startSeekCsiAction(),
  3522. this.api.seekTo(Infinity, void 0, void 0, void 0, 80),
  3523. h = f = !0)
  3524. }
  3525. */
  3526.  
  3527. }
  3528.  
  3529.  
  3530. if (rr) {
  3531.  
  3532. // focusBodyIfSuccess && Promise.resolve().then(() => {
  3533. // activeElement === document.activeElement && activeElement.blur();
  3534. // });
  3535.  
  3536. evt.preventDefault();
  3537. evt.stopImmediatePropagation();
  3538. evt.stopPropagation();
  3539.  
  3540. }
  3541.  
  3542. };
  3543.  
  3544. document.addEventListener('keydown', keyEventListener, { capture: true });
  3545.  
  3546.  
  3547. document.addEventListener('keyup', keyEventListener, { capture: true });
  3548.  
  3549. }
  3550.  
  3551. return { pageMediaWatcher, shortcutKeysFixer, keyboardController };
  3552.  
  3553. })();
  3554.  
  3555.  
  3556. pageMediaWatcher();
  3557. FIX_SHORTCUTKEYS > 0 && shortcutKeysFixer();
  3558.  
  3559.  
  3560. const check_for_set_key_order = (() => {
  3561.  
  3562. let mySet = new Set();
  3563.  
  3564. mySet.add("value1");
  3565. mySet.add("value2");
  3566. mySet.add("value3");
  3567.  
  3568. // Function to convert Set values to an array
  3569. function getSetValues(set) {
  3570. return Array.from(set.values());
  3571. }
  3572.  
  3573. // Function to test if the Set maintains insertion order
  3574. function testSetOrder(set, expectedOrder) {
  3575. let values = getSetValues(set);
  3576. return expectedOrder.join(',') === values.join(',');
  3577. }
  3578.  
  3579. // Test 1: Initial order
  3580. if (mySet.values().next().value !== "value1") return false;
  3581. if (!testSetOrder(mySet, ["value1", "value2", "value3"])) return false;
  3582.  
  3583. // Test 2: After deleting an element
  3584. mySet.delete("value2");
  3585. if (mySet.values().next().value !== "value1") return false;
  3586. if (!testSetOrder(mySet, ["value1", "value3"])) return false;
  3587.  
  3588. // Test 3: After re-adding a deleted element
  3589. mySet.add("value2");
  3590. if (mySet.values().next().value !== "value1") return false;
  3591. if (!testSetOrder(mySet, ["value1", "value3", "value2"])) return false;
  3592.  
  3593. // Test 4: After adding a new element
  3594. mySet.add("value4");
  3595. if (mySet.values().next().value !== "value1") return false;
  3596. if (!testSetOrder(mySet, ["value1", "value3", "value2", "value4"])) return false;
  3597.  
  3598. // Test 5: Delete+Add
  3599. mySet.delete("value1");
  3600. mySet.delete("value3");
  3601. mySet.add("value3");
  3602. mySet.add("value1");
  3603. if (mySet.values().next().value !== "value2") return false;
  3604. if (!testSetOrder(mySet, ["value2", "value4", "value3", "value1"])) return false;
  3605.  
  3606. return true;
  3607. })();
  3608.  
  3609.  
  3610. // const qm47 = Symbol();
  3611. const qm57 = Symbol();
  3612. const qm53 = Symbol();
  3613. const qn53 = Symbol();
  3614.  
  3615.  
  3616. const ump3 = new WeakMap();
  3617.  
  3618. const stp = document.createElement('noscript');
  3619. stp.id = 'weakref-placeholder';
  3620.  
  3621. PROP_OverReInclusion_AVOID && (() => {
  3622.  
  3623.  
  3624. if (typeof HTMLElement_.prototype.hasOwnProperty72 === 'function' || typeof HTMLElement_.prototype.hasOwnProperty !== 'function') return;
  3625. const f = HTMLElement_.prototype.hasOwnProperty72 = HTMLElement_.prototype.hasOwnProperty;
  3626. let byPassVal = null;
  3627. let byPassCount = 0;
  3628. let mmw = new Set();
  3629. HTMLElement_.prototype.hasOwnProperty = function (prop) {
  3630. if (arguments.length !== 1) return f.apply(this, arguments);
  3631. if (byPassVal !== null && typeof prop === 'string') {
  3632.  
  3633. if (PROP_OverReInclusion_LIST.has(prop)) {
  3634. byPassCount++;
  3635. return byPassVal;
  3636. }
  3637. PROP_OverReInclusion_DEBUGLOG && mmw.add(prop);
  3638.  
  3639. }
  3640. return this.hasOwnProperty72(prop);
  3641. };
  3642.  
  3643.  
  3644. /*
  3645.  
  3646.  
  3647. z.prototype.forwardDynamicProps = function() {
  3648. var B = m(this.inst);
  3649. B = h(B);
  3650. for (var F = B.next(); !F.done; F = B.next()) {
  3651. var H = h(F.value);
  3652. F = H.next().value;
  3653. H = H.next().value;
  3654. my(this, F, H);
  3655. r(b) && !ly(F) && Wua(this.inst, F)
  3656. }
  3657. }
  3658.  
  3659. */
  3660.  
  3661.  
  3662.  
  3663. let byPassZeroShowed = false;
  3664. const forwardDynamicPropsGeneral = function () {
  3665. byPassVal = true;
  3666. byPassCount = 0;
  3667. PROP_OverReInclusion_DEBUGLOG && mmw.clear();
  3668. const ret = this.forwardDynamicProps72();
  3669. byPassVal = null;
  3670. if (byPassCount === 0 && !byPassZeroShowed) {
  3671. byPassZeroShowed = true;
  3672. console.log('[yt-js-engine-tamer] byPassCount = 0 in forwardDynamicProps')
  3673. }
  3674. byPassCount = 0;
  3675. if (PROP_OverReInclusion_DEBUGLOG && mmw.size > 0) {
  3676. console.log(399, '[yt-js-engine-tamer]', [...mmw]);
  3677. mmw.clear();
  3678. }
  3679. return ret;
  3680. };
  3681.  
  3682. const propCheck = (proto) => {
  3683. if (typeof (proto || 0) == 'object' && typeof proto.forwardDynamicProps === 'function' && typeof proto.forwardDynamicProps72 !== 'function') {
  3684. proto.forwardDynamicProps72 = proto.forwardDynamicProps;
  3685. if (proto.forwardDynamicProps.length === 0) {
  3686. proto.forwardDynamicProps = forwardDynamicPropsGeneral;
  3687. }
  3688. }
  3689. };
  3690.  
  3691. const valMap = new WeakMap();
  3692. Object.defineProperty(HTMLElement_.prototype, 'didForwardDynamicProps', {
  3693. get() {
  3694. propCheck(this.constructor.prototype);
  3695. return valMap.get(this);
  3696. },
  3697. set(nv) {
  3698. propCheck(this.constructor.prototype);
  3699. valMap.set(this, nv);
  3700. return true;
  3701. },
  3702. enumerable: false,
  3703. configurable: true
  3704.  
  3705. });
  3706.  
  3707. promiseForCustomYtElementsReady.then(() => {
  3708. if (typeof customElements !== 'object' || typeof customElements.define72 === 'function' || typeof customElements.define !== 'function') return;
  3709. if (customElements.define.length !== 2) return;
  3710. customElements.define72 = customElements.define;
  3711. customElements.define = function (b, w) {
  3712. propCheck(w.prototype);
  3713. const ret = this.define72(b, w);
  3714. return ret;
  3715. }
  3716. });
  3717.  
  3718. })();
  3719.  
  3720.  
  3721. let marcoPr = new PromiseExternal();
  3722. const trackMarcoCm = document.createComment('1');
  3723. const trackMarcoCmObs = new MutationObserver(()=>{
  3724. marcoPr.resolve();
  3725. marcoPr = new PromiseExternal();
  3726. });
  3727. trackMarcoCmObs.observe(trackMarcoCm, {characterData: true});
  3728.  
  3729.  
  3730. // ----------------------------
  3731.  
  3732.  
  3733.  
  3734. // const rendererStamperCreationFactory = (cProto, options) => {
  3735.  
  3736. // const { key, stamperDomClass, preloadFn } = options;
  3737.  
  3738. // // const newDoc = document.implementation.createHTMLDocument("NewDoc");
  3739. // const pSpace = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  3740. // document.documentElement.insertAdjacentElement('beforeend', pSpace);
  3741. // const pNode = document.createElement('ns-538');
  3742. // pSpace.insertAdjacentElement('beforeend', pNode);
  3743.  
  3744. // const pDiv = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  3745. // if (typeof pNode.attachShadow === 'function') {
  3746. // const pShadow = pNode.attachShadow({ mode: "open" });
  3747. // pShadow.replaceChildren(pDiv);
  3748. // } else {
  3749. // pNode.insertAdjacentElement('beforeend', pDiv);
  3750. // }
  3751.  
  3752. // const pDivNew = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  3753. // pDiv.insertAdjacentElement('beforeend', pDivNew);
  3754.  
  3755. // const wmRemoved = new Map();
  3756.  
  3757. // // const wmMapToItem = new WeakMap();
  3758. // // let wmPendingList = null;
  3759.  
  3760. // const nullComponents = new Map();
  3761.  
  3762. // const componentDefaultAttributes = new WeakMap();
  3763.  
  3764. // const fnKeyH = `${key}$$c472`;
  3765.  
  3766. // cProto[fnKeyH] = async function (cTag, cId, pr00) {
  3767. // // await the current executing task (if any)
  3768. // // and avoid stacking in the same marco task
  3769. // await Promise.all([pr00, nextBrowserTick_()]);
  3770. // if (!this.ec389a && !this.ec389r) return;
  3771. // const addedCount0 = this.ec389a;
  3772. // const removedCount0 = this.ec389r;
  3773.  
  3774. // this.ec389 = false;
  3775. // this.ec389a = 0;
  3776. // this.ec389r = 0;
  3777.  
  3778. // const stampDomMap = this.stampDom[cTag].mapping;
  3779. // const isTickerRendering = cTag === 'tickerItems';
  3780. // const isMessageListRendering = cTag === 'visibleItems';
  3781.  
  3782. // // coming process can be stacked as ec389a and ec389r are reset.
  3783.  
  3784. // const deObjectComponent = (itemEntry) => {
  3785. // const I = firstObjectKey(itemEntry);
  3786. // const L = stampDomMap[I];
  3787. // const H = itemEntry[I];
  3788. // return [L, H];
  3789. // }
  3790.  
  3791. // const hostElement = this.hostElement;
  3792.  
  3793. // let renderNodeCount = 0;
  3794. // const renderList = this[cTag].map((item) => {
  3795. // const [L, H] = deObjectComponent(item);
  3796. // const node = kRef(renderMap.get(H));
  3797. // return node && hostElement.contains(node) ? (renderNodeCount++, node) : item;
  3798. // });
  3799.  
  3800. // // this.ec389 = null;
  3801. // // this.ec389a = 0;
  3802. // // this.ec389r = 0;
  3803.  
  3804. // let addedCounter = 0;
  3805. // let removedCounter = 0;
  3806.  
  3807. // const createConnectedComponentElm = (insertionObj, L, H, componentName) => {
  3808. // // const reusable = false;
  3809. // // const componentName = this.getComponentName_(L, H);
  3810. // let component;
  3811. // if (!nullComponents.has(componentName)) {
  3812. // nullComponents.set(componentName, (component = document.createElement(componentName)));
  3813. // component.className = stamperDomClass;
  3814. // // shadowElm.insertAdjacentElement('beforeend', component);
  3815. // } else {
  3816. // component = nullComponents.get(componentName);
  3817. // }
  3818. // component = component.cloneNode(false);
  3819.  
  3820. // // const cnt = insp(component);
  3821.  
  3822. // // cnt.__dataOld = cnt.__dataPending = null;
  3823. // pDivNew.insertAdjacentElement('beforeend', component);
  3824. // // cnt.__dataOld = cnt.__dataPending = null;
  3825.  
  3826. // return component;
  3827. // }
  3828.  
  3829. // const listDom = this.getStampContainer_(cId);
  3830.  
  3831. // const pnForNewItem = (item) => {
  3832.  
  3833. // const [L, H] = deObjectComponent(item);
  3834.  
  3835. // const componentName = this.getComponentName_(L, H);
  3836.  
  3837. // const wmList = wmRemoved.get(componentName.toLowerCase());
  3838.  
  3839. // let connectedComponent = null;
  3840. // if (wmList && (connectedComponent = wmList.firstElementChild)) {
  3841. // if (this.telemetry_) this.telemetry_.reuse++;
  3842. // // if (!wmPendingList) {
  3843. // // wmPendingList = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  3844. // // wmPendingList.setAttributeNS('http://www.w3.org/2000/svg', 'wm-pending', 'true');
  3845. // // pDiv.insertAdjacentElement('afterend', wmPendingList);
  3846. // // }
  3847. // // wmPendingList.insertAdjacentElement('beforeend', connectedComponent);
  3848. // pDivNew.insertAdjacentElement('beforeend', connectedComponent);
  3849. // const attrMap = connectedComponent.attributes;
  3850. // const defaultAttrs = componentDefaultAttributes.get(connectedComponent);
  3851. // if (defaultAttrs) {
  3852. // for (const attr of attrMap) {
  3853. // const name = attr.name;
  3854. // if (name in defaultAttrs) attr.value = defaultAttrs[name];
  3855. // else attrMap.removeNamedItem(name);
  3856. // }
  3857. // if (attrMap.length !== defaultAttrs['"']) {
  3858. // for (const name in defaultAttrs) {
  3859. // if (!attrMap[name] && name !== '"') connectedComponent.setAttribute(name, defaultAttrs[name]);
  3860. // }
  3861. // }
  3862. // }
  3863.  
  3864. // } else {
  3865. // connectedComponent = createConnectedComponentElm(item, L, H, componentName);
  3866. // if (this.telemetry_) this.telemetry_.create++;
  3867. // }
  3868. // if (isTickerRendering) {
  3869. // const container = connectedComponent.firstElementChild;
  3870. // if (container) container.classList.add('yt-live-chat-ticker-stampdom-container');
  3871. // }
  3872.  
  3873. // return [item, L, H, connectedComponent];
  3874.  
  3875. // };
  3876.  
  3877. // let imgPreloadPr = null;
  3878. // if (isMessageListRendering) {
  3879. // const addedItems = renderList.filter(item => item === 'object' && (item instanceof Node));
  3880. // imgPreloadPr = preloadFn(addedItems)();
  3881. // }
  3882.  
  3883. // const newComponentsEntries = await executeTaskBatch(renderList.map(item => ({
  3884. // item,
  3885. // fn(task) {
  3886. // const { item } = task;
  3887. // return typeof item === 'object' && !(item instanceof Node) ? pnForNewItem(item) : item;
  3888. // }
  3889. // })));
  3890.  
  3891. // const imgPromises = [];
  3892.  
  3893. // const imgPaths = new Set();
  3894.  
  3895. // const pnForRenderNewItem = (entry) => {
  3896. // const [item, L, H, connectedComponent] = entry;
  3897.  
  3898. // const cnt = insp(connectedComponent);
  3899. // if (!cnt.__refreshData938__) {
  3900. // cnt.constructor.prototype.__refreshData938__ = __refreshData938__;
  3901. // }
  3902. // if (typeof cnt.data === 'object' && cnt.__dataEnabled === true && cnt.__dataReady === true && cnt.__dataInvalid === false) {
  3903. // cnt.data = H;
  3904. // } else {
  3905. // const q = this.deferRenderStamperBinding_
  3906. // let q2;
  3907. // if (typeof q === 'object') q2 = this.deferRenderStamperBinding_ = [];
  3908. // this.deferRenderStamperBinding_(connectedComponent, L, H);
  3909. // this.flushRenderStamperComponentBindings_();
  3910. // if (typeof q === 'object') {
  3911. // this.deferRenderStamperBinding_ = q;
  3912. // q2.length = 0;
  3913. // }
  3914. // }
  3915. // if (cnt.data) cnt.__refreshData938__('data', !0); // ensure data is invalidated
  3916.  
  3917. // // fix yt-icon issue
  3918. // for (const node of connectedComponent.getElementsByTagName('yt-icon')) {
  3919. // try {
  3920. // const cnt = insp(node);
  3921. // if (!cnt.__refreshProps938__) cnt.constructor.prototype.__refreshProps938__ = __refreshProps938__;
  3922. // cnt.__refreshProps938__();
  3923. // } catch (e) { }
  3924. // }
  3925.  
  3926. // componentDefaultAttributes.set(connectedComponent, getAttributes(connectedComponent));
  3927. // return entry;
  3928. // }
  3929.  
  3930. // const newRenderedComponents = await executeTaskBatch(newComponentsEntries.map(entry => ({
  3931. // entry,
  3932. // fn(task) {
  3933. // const { entry } = task;
  3934. // return typeof entry === 'object' && !(entry instanceof Node) ? pnForRenderNewItem(entry) : entry;
  3935. // }
  3936. // })));
  3937.  
  3938.  
  3939. // this.flushRenderStamperComponentBindings_(); // ensure all deferred flush render tasks clear.
  3940.  
  3941. // // imgPromises.push(imageFetch('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'));
  3942. // if (imgPromises.length > 0) {
  3943. // const pr1 = Promise.all(imgPromises).catch(e => { });
  3944. // const pr2 = autoTimerFn();
  3945. // await Promise.race([pr1, pr2]).catch(e => { });
  3946. // imgPaths.clear();
  3947. // imgPromises.length = 0;
  3948. // }
  3949. // if (imgPreloadPr) await imgPreloadPr;
  3950.  
  3951. // // const batching = [];
  3952. // // let j = 0;
  3953. // // let elNode;
  3954.  
  3955. // const sideProcesses = [];
  3956.  
  3957. // const removeStampNode_ = (elNode) => {
  3958. // const elm = elNode;
  3959. // const cnt = insp(elm);
  3960. // const componentName = elm.nodeName.toLowerCase();
  3961. // let wmList = wmRemoved.get(componentName);
  3962. // if (!wmList) {
  3963. // wmList = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  3964. // wmList.setAttributeNS('http://www.w3.org/2000/svg', 'wm-component', componentName);
  3965. // pDiv.insertAdjacentElement('afterend', wmList);
  3966. // wmRemoved.set(componentName, wmList);
  3967. // }
  3968. // wmList.insertAdjacentElement('beforeend', elm);
  3969. // const data = cnt.data;
  3970. // if (data) renderMap.delete(cnt.data);
  3971.  
  3972. // sideProcesses.push(reuseFixDataViewModel(elm));
  3973. // sideProcesses.push(reuseFixYtIconRendering(elm));
  3974. // }
  3975.  
  3976. // // const removeStampNode = async () => {
  3977.  
  3978. // // removedCounter++;
  3979.  
  3980. // // const nextElm = nextComponentSiblingFn(elNode);
  3981. // // const elmId = elNode.id;
  3982. // // removeStampNode_(elNode);
  3983. // // // const dzid = this.getAttribute('dz-component-id');
  3984. // // // ---- no-cache ----
  3985. // // // try{
  3986. // // // elm.remove();
  3987. // // // }catch(e){}
  3988. // // // ---- no-cache ----
  3989.  
  3990. // // if (cTag === 'visibleItems') {
  3991. // // sideProcesses.push(onVisibleItemStampNodeRemoval(elmId));
  3992. // // }
  3993.  
  3994. // // j++;
  3995. // // elNode = nextElm;
  3996.  
  3997. // // }
  3998.  
  3999. // // if (typeof Polymer !== "undefined" && typeof Polymer.flush === "function") {
  4000. // // // clear all pending rendering first
  4001. // // await stackMarcoTask(async () => {
  4002. // // Polymer.flush();
  4003. // // });
  4004. // // }
  4005.  
  4006. // // main UI thread - DOM modification
  4007. // await new Promise((resolveDM) => {
  4008. // nextBrowserTick_(() => {
  4009.  
  4010. // const isAtBottom = this.atBottom === true;
  4011. // // if (ENABLE_OVERFLOW_ANCHOR && isAtBottom) {
  4012. // // shouldScrollAfterFlush = true;
  4013. // // }
  4014.  
  4015.  
  4016. // const tasks = [];
  4017.  
  4018. // const taskFn = {
  4019. // remove: (task) => {
  4020.  
  4021. // const { elNode } = task;
  4022.  
  4023. // removedCounter++;
  4024.  
  4025. // const elmId = elNode.id;
  4026. // removeStampNode_(elNode);
  4027. // // const dzid = this.getAttribute('dz-component-id');
  4028. // // ---- no-cache ----
  4029. // // try{
  4030. // // elm.remove();
  4031. // // }catch(e){}
  4032. // // ---- no-cache ----
  4033.  
  4034. // if (isMessageListRendering) {
  4035. // sideProcesses.push(onVisibleItemStampNodeRemoval(elmId));
  4036. // }
  4037.  
  4038. // return 2
  4039.  
  4040. // },
  4041. // append: (task) => {
  4042.  
  4043. // const { newNode, nodeAfter, parentNode } = task;
  4044.  
  4045. // nodeAfter ? nodeAfter.insertAdjacentElement('beforebegin', newNode) : parentNode.insertAdjacentElement('beforeend', newNode);
  4046. // const connectedComponent = newNode;
  4047. // const cnt = insp(connectedComponent);
  4048. // renderMap.set(cnt.data, mWeakRef(connectedComponent));
  4049. // mutationDelayedRefreshData(cnt); // not included to sideProcesses
  4050. // addedCounter++;
  4051.  
  4052. // if (isTickerRendering) {
  4053. // sideProcesses.push(onTickerItemStampNodeAdded());
  4054. // }
  4055.  
  4056. // if (isMessageListRendering && isAtBottom) {
  4057.  
  4058. // const itemScroller = this.itemScroller;
  4059. // if (itemScroller && (!ENABLE_OVERFLOW_ANCHOR || itemScroller.scrollTop === 0)) itemScroller.scrollTop = 16777216;
  4060.  
  4061. // }
  4062.  
  4063. // return 1
  4064. // }
  4065. // }
  4066.  
  4067. // {
  4068. // const indexMap = new WeakMap();
  4069. // let index = 0;
  4070. // for (let elNode_ = firstComponentChildFn(listDom); elNode_ instanceof Node; elNode_ = nextComponentSiblingFn(elNode_)) {
  4071. // indexMap.set(elNode_, index++);
  4072. // }
  4073.  
  4074. // const keepIndices = new Array(renderNodeCount);
  4075. // let keepIndicesLen = 0, lastKeepIndex = -1, requireSort = false;
  4076. // for (let i = 0, l = newRenderedComponents.length; i < l; i++) {
  4077. // const entry = newRenderedComponents[i];
  4078. // if (entry instanceof Node) {
  4079. // const index = indexMap.get(entry);
  4080. // keepIndices[keepIndicesLen++] = [index, entry];
  4081. // if (index > lastKeepIndex) lastKeepIndex = index;
  4082. // else requireSort = true;
  4083. // }
  4084. // }
  4085. // keepIndices.length = keepIndicesLen;
  4086. // if (requireSort) keepIndices.sort((a, b) => a[0] - b[0]);
  4087. // let dk = 0;
  4088.  
  4089. // let j = 0;
  4090. // let elNode;
  4091.  
  4092. // elNode = firstComponentChildFn(listDom);
  4093.  
  4094. // for (const rcEntry of newRenderedComponents) {
  4095. // const index = indexMap.get(rcEntry);
  4096. // if (typeof index === 'number') {
  4097. // const indexEntry = keepIndices[dk++];
  4098. // const [dIdx, dNode] = indexEntry;
  4099. // indexMap.delete(rcEntry);
  4100. // const idx = dIdx;
  4101. // while (j < idx && elNode) {
  4102. // tasks.push({
  4103. // type: 'remove',
  4104. // elNode,
  4105. // fn: taskFn.remove
  4106. // });
  4107. // elNode = nextComponentSiblingFn(elNode);
  4108. // j++;
  4109. // }
  4110. // if (j === idx) {
  4111. // if (elNode) {
  4112. // // if (dNode !== elNode) tasks.push({
  4113. // // type: 'swap',
  4114. // // earlyNode: indexEntry[1],
  4115. // // laterNode: elNode
  4116. // // });
  4117. // elNode = nextComponentSiblingFn(elNode);
  4118. // j++;
  4119. // } else {
  4120. // console.warn('elNode is not available?', renderList, addedCount0, removedCount0, j, idx);
  4121. // }
  4122. // }
  4123. // } else if (rcEntry instanceof Node) {
  4124. // // interruped by the external like clearList
  4125.  
  4126. // tasks.push({
  4127. // type: 'remove',
  4128. // elNode: rcEntry,
  4129. // fn: taskFn.remove
  4130. // });
  4131.  
  4132. // } else {
  4133. // const [item, L, H, connectedComponent] = rcEntry;
  4134.  
  4135. // tasks.push({
  4136. // type: 'append',
  4137. // newNode: connectedComponent,
  4138. // nodeAfter: elNode,
  4139. // parentNode: listDom,
  4140. // fn: taskFn.append
  4141. // });
  4142.  
  4143. // }
  4144.  
  4145. // }
  4146.  
  4147. // while (elNode) {
  4148.  
  4149. // tasks.push({
  4150. // type: 'remove',
  4151. // elNode,
  4152. // fn: taskFn.remove
  4153. // });
  4154. // elNode = nextComponentSiblingFn(elNode);
  4155.  
  4156. // }
  4157.  
  4158. // }
  4159.  
  4160.  
  4161. // executeTaskBatch(tasks).then(resolveDM).catch(console.warn);
  4162.  
  4163. // });
  4164. // }).catch(console.warn);
  4165.  
  4166. // {
  4167. // const arr = this[cTag];
  4168. // let b = 0;
  4169. // b = b | this._setPendingPropertyOrPath(`${cTag}.splices`, {}, true, true);
  4170. // b = b | this._setPendingPropertyOrPath(`${cTag}.length`, arr.length, true, true);
  4171. // b && this._invalidateProperties();
  4172. // }
  4173.  
  4174. // // this.flushRenderStamperComponentBindings_(); // just in case...
  4175.  
  4176. // await Promise.all(sideProcesses);
  4177.  
  4178. // const detail = {
  4179. // container: listDom
  4180. // };
  4181. // this.stampDom[cTag].events && this.hostElement.dispatchEvent(new CustomEvent("yt-rendererstamper-finished", {
  4182. // bubbles: !0,
  4183. // cancelable: !1,
  4184. // composed: !0,
  4185. // detail
  4186. // }));
  4187. // detail.container = null;
  4188.  
  4189. // // if (typeof Polymer !== "undefined" && typeof Polymer.flush === "function") {
  4190. // // // clear all remaining rendering before promise resolve
  4191. // // await stackMarcoTask(async () => {
  4192. // // Polymer.flush();
  4193. // // });
  4194. // // }
  4195.  
  4196. // }
  4197.  
  4198. // cProto[key] = function (cTag, cId, indexSplice) {
  4199. // // console.log('proceedStampDomArraySplices_')
  4200. // // assume no error -> no try catch (performance consideration)
  4201. // const { index, addedCount, removed } = indexSplice;
  4202. // const removedCount = removed ? removed.length : indexSplice.removedCount;
  4203. // indexSplice = null;
  4204. // if (!addedCount && !removedCount) {
  4205. // console.warn('proceedStampDomArraySplices_', 'Error 001');
  4206. // return false;
  4207. // }
  4208. // // const streamArr = this[cTag];
  4209. // if (!this.ec389) {
  4210. // if (this.ec389a || this.ec389r) {
  4211. // console.warn('proceedStampDomArraySplices_', 'Error 002');
  4212. // return false;
  4213. // }
  4214. // this.ec389 = true;
  4215. // this.ec389a = 0;
  4216. // this.ec389r = 0;
  4217. // }
  4218. // const shouldExecute = !this.ec389a && !this.ec389r;
  4219.  
  4220. // this.ec389a += addedCount;
  4221. // this.ec389r += removedCount;
  4222.  
  4223. // if (shouldExecute) {
  4224.  
  4225. // // let shouldScrollAfterFlush = false;
  4226. // const pr00 = this.ec389pr;
  4227. // const ec389pr = this.ec389pr = this[fnKeyH](cTag, cId, pr00).catch(console.warn);
  4228.  
  4229. // if (cTag === 'visibleItems') {
  4230. // this.prDelay288 = ec389pr;
  4231. // // this.hasUserJustInteracted12_ = (this.hasUserJustInteracted11_ || (() => false));
  4232.  
  4233. // // the first microtask after promise resolved
  4234. // // YYYYYYY
  4235. // // ec389pr.then(async () => {
  4236. // // if (shouldScrollAfterFlush) {
  4237. // // if (this.atBottom === false && this.allowScroll === true && !this.hasUserJustInteracted12_()) this.scrollToBottom_();
  4238. // // wme.data = `${(wme.data & 7) + 1}`;
  4239. // // await wmp;
  4240. // // if (this.atBottom === false && this.allowScroll === true && !this.hasUserJustInteracted12_()) this.scrollToBottom_();
  4241. // // }
  4242. // // });
  4243.  
  4244. // }
  4245.  
  4246. // }
  4247.  
  4248. // return true;
  4249. // }
  4250.  
  4251.  
  4252.  
  4253.  
  4254.  
  4255. // }
  4256.  
  4257. // ----------------------------
  4258.  
  4259.  
  4260. // const convertionFuncMap = new WeakMap();
  4261. // let val_kevlar_should_maintain_stable_list = null;
  4262.  
  4263. // const csb = (a, b) => { for (const c in a) if (a.hasOwnProperty(c) && b[c]) return c; return null }
  4264. // const createStampDomArrayFnE1_ = function (items, containerId, componentConfig, rendererConfig, shouldTriggerRendererStamperFinished, isStableList) {
  4265.  
  4266.  
  4267. // // this.__$$fs894$$__ = this.__$$fs894$$__ || `${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}`;
  4268.  
  4269. // // console.log(1880, this.__$$fs894$$__)
  4270. // if(!this[`__0p893::${containerId}__`]) this[`__0p893::${containerId}__`]= [];
  4271.  
  4272. // // const task =
  4273. // queueMicrotask_(()=>{
  4274.  
  4275.  
  4276. // });
  4277. // this[`__0p892::${containerId}__`] = (this[`__0p892::${containerId}__`] || Promise.resolve(0)).then(async () => {
  4278.  
  4279. // try {
  4280.  
  4281. // if ((this.hostElement || 0).isConnected) this[`__0fs892::${containerId}__`] = `${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}`;
  4282. // const t892 = this[`__0fs892::${containerId}__`];
  4283. // // a - array
  4284. // // c - mapping
  4285. // // d - reuseComponents
  4286. // // e - events (shouldTriggerRendererStamperFinished)
  4287. // // h - stamperStableList
  4288.  
  4289. // // this is for flushing the new elements to a blank container. (without reusing)
  4290.  
  4291. // const b_ = containerId;
  4292. // const c_ = componentConfig;
  4293. // const items_ = items;
  4294.  
  4295. // const doDeferRenderStamperBinding_ = async (component) => {
  4296. // const i = component[stampIdxSb];
  4297. // const u = items_[i];
  4298. // const c = c_;
  4299. // const x = csb(c, u);
  4300. // this.deferRenderStamperBinding_(component, c[x], u[x]); // necessary?
  4301. // };
  4302.  
  4303. // const container = this.getStampContainer_(b_);
  4304.  
  4305. // const domShell = container.__domApi || container;
  4306. // if (!domShell || !domShell.appendChild || typeof domShell.childElementCount !== 'number') throw new Error();
  4307. // const domShellElementCount = domShell.childElementCount;
  4308. // const noscript = document.createElement('noscript');
  4309. // // document.body.appendChild(noscript);
  4310.  
  4311. // let doc = document;
  4312.  
  4313. // const nofn = () => true;
  4314. // const n = items_.length;
  4315. // const fns = new Array(n);
  4316. // let cxt = 0;
  4317.  
  4318. // let qxd = domShellElementCount > 0 ? new WeakSet() : null;
  4319. // const nextTickFnE1 = () => {
  4320. // items_.some((item, i) => {
  4321.  
  4322. // const componentKey = csb(componentConfig, item);
  4323. // if (!componentKey) {
  4324. // fns[i] = nofn;
  4325. // cxt++;
  4326. // } else {
  4327.  
  4328. // const newComponent = this.createComponent_(componentConfig[componentKey], item[componentKey], rendererConfig);
  4329. // newComponent[stampIdxSb] = i;
  4330. // doDeferRenderStamperBinding_(newComponent);
  4331. // // mutex = mutex.then(() => {
  4332. // noscript.appendChild(newComponent);
  4333. // // });
  4334.  
  4335. // // Promise.resolve(cp).then(doDeferRenderStamperBinding_);
  4336. // let newComponent_ = newComponent;
  4337. // fns[i] = () => {
  4338. // if (!newComponent_) return true;
  4339. // if (newComponent_.parentNode === noscript) {
  4340. // newComponent_ = null;
  4341. // return true;
  4342. // }
  4343. // return false;
  4344. // };
  4345.  
  4346. // }
  4347.  
  4348. // });
  4349. // noscript.setAttribute('ylul8gr', `${Date.now()}`);
  4350. // };
  4351.  
  4352. // const nextTickFnF1 = () => {
  4353. // let startNode = null;
  4354.  
  4355. // const isSet = new Set();
  4356. // items_.some((item, i) => {
  4357.  
  4358. // const componentKey = csb(componentConfig, item);
  4359. // if (!componentKey) {
  4360. // fns[i] = nofn;
  4361. // cxt++;
  4362. // } else {
  4363.  
  4364. // const componentName = this.getComponentName_(componentConfig[componentKey], item[componentKey]);
  4365. // isSet.add(componentName);
  4366. // let np = startNode || domShell.firstElementChild;
  4367. // let chosenNode = null;
  4368. // while (np) {
  4369. // if (np instanceof Node_ && np.is === componentName && !qxd.has(np)) {
  4370. // qxd.add(np);
  4371. // chosenNode = np;
  4372. // break;
  4373. // }
  4374. // np = np.nextElementSibling;
  4375. // }
  4376.  
  4377.  
  4378. // const cp = chosenNode || this.createComponent_(componentConfig[componentKey], item[componentKey], rendererConfig);
  4379. // let oldIdx = cp[stampIdxSb];
  4380.  
  4381. // cp[stampIdxSb] = i;
  4382. // doDeferRenderStamperBinding_(cp);
  4383. // if (chosenNode !== null && cp === chosenNode) {
  4384.  
  4385. // fns[i] = nofn;
  4386. // startNode = chosenNode;
  4387. // } else {
  4388.  
  4389. // // mutex = mutex.then(() => {
  4390. // noscript.appendChild(cp); // ui formation
  4391. // // });
  4392.  
  4393. // // Promise.resolve(cp).then(doDeferRenderStamperBinding_);
  4394. // let q = cp;
  4395. // fns[i] = () => {
  4396. // if (q && q.parentNode === noscript) {
  4397. // const cp = q;
  4398. // q = null;
  4399. // }
  4400. // if (!q) return true;
  4401. // };
  4402.  
  4403. // }
  4404.  
  4405. // }
  4406.  
  4407. // });
  4408.  
  4409. // if (isSet.size === 1 && qxd !== null) {
  4410.  
  4411. // const is = isSet.values().next().value;
  4412.  
  4413. // if (typeof is === 'string' && is.length >= 1) {
  4414.  
  4415. // let np = startNode || domShell.firstElementChild;
  4416. // const removal = [];
  4417. // while (np) {
  4418. // if (np instanceof Node_ && np.is === is && !qxd.has(np)) {
  4419. // removal.push(np);
  4420. // np[stampIdxSb] = -1;
  4421. // }
  4422. // np = np.nextElementSibling;
  4423. // }
  4424. // // by default, removal.length shoule be zero. just play safe.
  4425. // if (removal.length > 0) {
  4426. // const dFrag = doc.createDocumentFragment();
  4427. // dFrag.append(...removal);
  4428. // removal.length = 0;
  4429. // }
  4430.  
  4431. // }
  4432.  
  4433. // }
  4434. // noscript.setAttribute('ylul8gr', `${Date.now()}`);
  4435.  
  4436.  
  4437.  
  4438. // }
  4439.  
  4440. // const pr = new Promise(resolvePR => {
  4441.  
  4442. // let mo = new MutationObserver(() => {
  4443. // if (typeof fns[n - 1] !== 'function') return;
  4444. // if (!noscript.hasAttribute('ylul8gr')) return;
  4445. // const everyTrue = fns.every(fn => fn() === true);
  4446. // if (everyTrue) {
  4447. // if (mo) {
  4448. // mo.disconnect();
  4449. // mo.takeRecords();
  4450. // mo = null;
  4451. // }
  4452. // resolvePR();
  4453. // }
  4454. // });
  4455. // mo.observe(noscript, { subtree: false, childList: true, attributes: ['ylul8gr'] });
  4456.  
  4457. // if (domShellElementCount > 0) {
  4458. // nextBrowserTick_(nextTickFnF1);
  4459. // } else {
  4460. // nextBrowserTick_(nextTickFnE1);
  4461. // }
  4462.  
  4463. // });
  4464. // await pr.then();
  4465. // fns.length = 0;
  4466. // qxd = null;
  4467.  
  4468. // // console.log(3025)
  4469.  
  4470.  
  4471.  
  4472. // // document.documentElement.appendChild.call(doc.documentElement, noscript);
  4473. // // nativeRemoveE.call(noscript);
  4474.  
  4475. // // nativeRemoveE.call(noscript);
  4476. // noscript.remove(); // trigger isAttached change
  4477. // const hostElement = this.hostElement;
  4478.  
  4479.  
  4480. // /** @type {DocumentFragment} */
  4481. // // const gFragment = document.createDocumentFragment();
  4482. // const gFragment = doc.createDocumentFragment();
  4483.  
  4484. // const fnE = () => {
  4485. // const evt = new CustomEvent("yt-rendererstamper-finished", {
  4486. // bubbles: !0,
  4487. // cancelable: !1,
  4488. // composed: !0,
  4489. // detail: {
  4490. // container
  4491. // }
  4492. // });
  4493. // hostElement.dispatchEvent(evt);
  4494. // };
  4495.  
  4496. // let f1, f2;
  4497. // f1 = async () => {
  4498. // await new Promise(r => nextBrowserTick_(r));
  4499. // if (t892 !== this[`__0fs892::${containerId}__`]) return;
  4500. // // await new Promise(r=>setTimeout(r, 1000));
  4501.  
  4502. // // if (this.data !== data || this.__data !== __data) return;
  4503.  
  4504. // const domShellElementCountCurrent = domShell.childElementCount;
  4505. // if (domShellElementCountCurrent !== domShellElementCount) return;
  4506. // if (hostElement.isConnected === false || this.isAttached === false || !hostElement.contains(container) || container.__domApi !== domShell) {
  4507. // return;
  4508. // }
  4509. // // const t1 = performance.now();
  4510.  
  4511. // if (DO_createStampDomArrayFnE1_nativeAppendD) {
  4512. // let elm;
  4513. // while (elm = noscript.firstChild) {
  4514. // nativeAppendD.call(gFragment, elm); // no attached / detached
  4515. // }
  4516. // } else {
  4517. // let elm;
  4518. // while (elm = noscript.firstChild) {
  4519. // gFragment.appendChild(elm);
  4520. // }
  4521. // }
  4522. // // const t2 = performance.now();
  4523.  
  4524. // // console.log('createStampDomArrayFn_{T2}', t2-t1);
  4525.  
  4526. // // nextBrowserTick_(f2);
  4527. // return true;
  4528. // };
  4529.  
  4530. // f2 = async () => {
  4531. // await new Promise(r => nextBrowserTick_(r));
  4532. // if (t892 !== this[`__0fs892::${containerId}__`]) return;
  4533. // // if (this.data !== data || this.__data !== __data) return;
  4534.  
  4535. // const domShellElementCountCurrent = domShell.childElementCount;
  4536. // if (domShellElementCountCurrent !== domShellElementCount) return;
  4537. // if (hostElement.isConnected === false || this.isAttached === false || !hostElement.contains(container) || container.__domApi !== domShell) {
  4538. // return;
  4539. // }
  4540.  
  4541. // domShell.appendChild(gFragment);
  4542. // this.flushRenderStamperComponentBindings_();
  4543. // this.markDirty && this.markDirty();
  4544.  
  4545. // if (shouldTriggerRendererStamperFinished) {
  4546. // nextBrowserTick_(fnE);
  4547. // }
  4548.  
  4549. // return true;
  4550.  
  4551. // };
  4552.  
  4553. // const r1 = await f1();
  4554. // if (r1 === true) {
  4555. // const r2 = await f2();
  4556. // }
  4557.  
  4558.  
  4559. // } catch (err) {
  4560.  
  4561. // console.warn(err);
  4562.  
  4563. // } finally {
  4564. // //
  4565. // }
  4566.  
  4567. // }).catch(() => 0);
  4568.  
  4569.  
  4570. // };
  4571.  
  4572.  
  4573. // const stampIdxSb = Symbol();
  4574. // 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
  4575. // const byPassIs55 = new Set(['ytd-rich-grid-renderer', 'ytd-rich-shelf-renderer']);
  4576. // const byPassIs55 = new Set([
  4577. // 'ytd-rich-grid-renderer', 'ytd-rich-shelf-renderer', // avoid disappearing of video/short entries
  4578. // 'ytd-unified-share-panel-renderer', 'yt-third-party-share-target-section-renderer', 'ytd-add-to-playlist-renderer', // avoid share-panel being non-central
  4579. // 'ytd-continuation-item-renderer', 'tp-yt-paper-spinner',
  4580. // 'ytd-multi-page-menu-renderer', 'yt-multi-page-menu-section-renderer'
  4581. // ]);
  4582. // const byPassB55 = new Set(['continuations']);
  4583. // const byPassB55 = new Set(['flexible-item-buttons', 'continuations', 'header', 'sections']);
  4584.  
  4585. // let stampContainer = null;
  4586. // const requestDomApiObject = { getStampContainer_: () => stampContainer };
  4587. // const requestDomApiProxy = new Proxy(requestDomApiObject, {
  4588. // get(target, prop, receiver) {
  4589. // if (prop === 'getStampContainer_') return target[prop];
  4590. // throw new Error("requestDomApiProxyGet");
  4591. // },
  4592. // set(target, prop, value, receiver) {
  4593. // throw new Error("requestDomApiProxySet");
  4594. // }
  4595. // });
  4596. // const fulfillment2Set = new Set([
  4597. // 'ytd-watch-next-secondary-results-renderer.items',
  4598. // 'yt-related-chip-cloud-renderer.content',
  4599. // 'yt-chip-cloud-renderer.chips',
  4600. // // 'ytd-section-list-renderer.contents', // affect loading of https://www.youtube.com/feed/history
  4601. // 'ytd-engagement-panel-section-list-renderer.content',
  4602. // 'ytd-engagement-panel-section-list-renderer.header',
  4603. // 'ytd-video-description-infocards-section-renderer.items',
  4604. // 'yt-clip-creation-renderer.title-input',
  4605. // 'yt-clip-creation-renderer.scrubber',
  4606. // 'ytd-watch-flexy.info-contents',
  4607. // 'ytd-video-primary-info-renderer.menu',
  4608. // 'ytd-menu-renderer.flexible-item-buttons',
  4609. // 'ytd-metadata-row-container-renderer.always-shown',
  4610. // 'ytd-subscribe-button-renderer.notification-preference-button',
  4611. // 'ytd-watch-metadata.subscribe-button',
  4612. // 'ytd-watch-metadata.teaser-carousel',
  4613. // 'ytd-structured-description-content-renderer.items',
  4614. // 'ytd-video-description-infocards-section-renderer.infocard-videos-button',
  4615. // 'ytd-video-description-infocards-section-renderer.infocard-channel-button',
  4616. // 'ytd-rich-metadata-row-renderer.contents',
  4617. // 'ytd-subscribe-button-renderer.notification-preference-button',
  4618. // 'ytd-watch-flexy.panels',
  4619. // // yt-live-chat
  4620. // 'yt-live-chat-renderer.input-panel',
  4621. // 'yt-live-chat-app.contents',
  4622. // 'yt-live-chat-message-input-renderer.picker-buttons',
  4623. // 'yt-live-chat-message-input-renderer.pickers',
  4624. // 'yt-live-chat-message-input-renderer.emoji-picker-button',
  4625. // 'yt-live-chat-product-picker-panel-view-model.items',
  4626. // 'yt-live-chat-message-input-renderer.send-button',
  4627. // 'yt-live-chat-renderer.continuations',
  4628. // // 'yt-live-chat-renderer.item-list', // affect yt live chat message init
  4629. // 'yt-live-chat-renderer.ticker'
  4630. // ]);
  4631.  
  4632. const __refreshData938o__ = {};
  4633. const __refreshData938__ = function (prop, opt) {
  4634. const d = this[prop];
  4635. if (d) {
  4636. this._setPendingProperty(prop, __refreshData938o__, opt);
  4637. this._setPendingProperty(prop, d, opt);
  4638. this._invalidateProperties();
  4639. }
  4640. };
  4641.  
  4642. // const pendingStampFlushs = [];
  4643.  
  4644. const nativeNow = performance.constructor.prototype.now.bind(performance);
  4645.  
  4646. const queueMicrotask_ = typeof queueMicrotask === 'function' ? queueMicrotask : (f) => (Promise.resolve().then(f), void 0);
  4647.  
  4648. const executeTaskBatch = function (taskArr, firstMarco = true) {
  4649. if (!(taskArr || 0).length) throw new TypeError(`Illegal invocation`);
  4650. return new Promise(resolveFinal => {
  4651. let resolveFn = null;
  4652. const len = taskArr.length;
  4653. const results = new Array(len);
  4654. const makePromise = () => new Promise(resolve => { resolveFn = resolve });
  4655. let firedCount = 0;
  4656. const executor = () => {
  4657. if (taskArr.length !== len) throw new TypeError(`Illegal invocation`);
  4658. const resolveFn_ = resolveFn;
  4659. let t0 = 0;
  4660. let next = 0;
  4661. taskArr.forEach((task, idx) => {
  4662. if (typeof (task || 0) !== 'object') throw new TypeError(`Illegal invocation`);
  4663. if (!task.fired) {
  4664. queueMicrotask_(() => {
  4665. if (next || task.fired) return;
  4666. task.fired = true;
  4667. if (++firedCount === len) next |= 2;
  4668. if (!t0) t0 = nativeNow() + 10;
  4669. const { fn } = task;
  4670. results[idx] = fn(task); // sync task only
  4671. if (nativeNow() > t0) next |= 1;
  4672. });
  4673. }
  4674. });
  4675. queueMicrotask_(() => resolveFn_(next))
  4676. }
  4677. const looper = (next) => {
  4678. if (!next) throw new TypeError(`Illegal invocation`);
  4679. if (next & 2) {
  4680. if (next & 1) {
  4681. nextBrowserTick_(() => resolveFinal(results))
  4682. } else {
  4683. resolveFinal(results);
  4684. }
  4685. } else {
  4686. const p = makePromise();
  4687. nextBrowserTick_(executor);
  4688. p.then(looper);
  4689. }
  4690. }
  4691. const p = makePromise();
  4692. firstMarco ? nextBrowserTick_(executor) : executor();
  4693. p.then(looper);
  4694.  
  4695. })
  4696.  
  4697. }
  4698.  
  4699.  
  4700. FIX_ICON_RENDER && whenCEDefined('yt-icon').then(async () => {
  4701.  
  4702.  
  4703. // const globalPromiseStack = {};
  4704.  
  4705. // let dummy;
  4706. // while(!dummy){
  4707.  
  4708. // dummy = document.querySelector('yt-icon');
  4709. // await new Promise(r=>setTimeout(r,0));
  4710. // }
  4711.  
  4712. dummy = document.createElement('yt-icon');
  4713.  
  4714. let cProto;
  4715. if (!(dummy instanceof Element)) return;
  4716. cProto = insp(dummy).constructor.prototype;
  4717.  
  4718. cProto.handlePropertyChange671 = cProto.handlePropertyChange;
  4719. cProto.determineIconSet671 = cProto.determineIconSet;
  4720. cProto.switchToYtSysIconset671 = cProto.switchToYtSysIconset;
  4721. cProto.useYtSysIconsetForMissingIcons671 = cProto.useYtSysIconsetForMissingIcons;
  4722. cProto.getIconManager671 = cProto.getIconManager;
  4723. cProto.getIconShapeData671 = cProto.getIconShapeData;
  4724. cProto.renderIcon671 = cProto.renderIcon;
  4725.  
  4726. // cProto.attached488 = cProto.attached;
  4727. // cProto.attached = function(){
  4728. // console.log('attached')
  4729. // return this.attached488(...arguments);
  4730. // }
  4731. // cProto.detached488 = cProto.detached;
  4732. // cProto.detached = function(){
  4733. // console.log('detached')
  4734. // return this.detached488(...arguments);
  4735. // }
  4736.  
  4737. if(cProto.__renderIconFix__) return;
  4738. cProto.__renderIconFix__ = true;
  4739.  
  4740. let taskStack = [];
  4741. const cmObs = new MutationObserver(()=>{
  4742. const tasks = taskStack.slice();
  4743. taskStack.length = 0;
  4744. for(const task of tasks){
  4745. task();
  4746. }
  4747. })
  4748. const cm = document.createComment('1');
  4749. const stackTask = (f) => {
  4750. taskStack.push(f);
  4751. cm.data = `${(cm.data & 7) + 1}`;
  4752. }
  4753. cmObs.observe(cm, { characterData: true });
  4754.  
  4755. // let iconManagers = {}; // assume shared
  4756.  
  4757. // window.iconManagers = () => iconManagers;
  4758.  
  4759.  
  4760. const setupYtIcon = (inst) => {
  4761.  
  4762. if (inst.__ytIconSetup588__) return;
  4763. const cProto = Reflect.getPrototypeOf(inst);
  4764. cProto.__ytIconSetup588__ = true;
  4765.  
  4766.  
  4767. const config = (win.yt || 0).config_ || (win.ytcfg || 0).data_ || 0;
  4768.  
  4769. config.EXPERIMENT_FLAGS.wil_icon_render_when_idle = false; // single rendering
  4770. config.EXPERIMENT_FLAGS.wil_icon_load_immediately = true; // single rendering
  4771. // config.EXPERIMENT_FLAGS.wil_icon_use_mask_rendering = false; // DON'T!
  4772. config.EXPERIMENT_FLAGS.wil_icon_network_first = true; // single rendering
  4773.  
  4774.  
  4775. // this.renderingMode = _.x("wil_icon_use_mask_rendering") ? 1 : 0;
  4776. // this.isNetworkFirstStrategy = _.x("wil_icon_network_first");
  4777. // this.renderWhenIdle = _.x("wil_icon_render_when_idle");
  4778. // this.waitForAnimationFrame = !_.x("wil_icon_load_immediately");
  4779.  
  4780.  
  4781.  
  4782. }
  4783.  
  4784. cProto.handlePropertyChange = function (...a) { // 10+
  4785.  
  4786. if (!this.__ytIconSetup588__) setupYtIcon(this);
  4787. // string bool=false bool int=24 (empty string?) bool? bool
  4788. // undefined bool=false bool int bool? true
  4789.  
  4790.  
  4791. // if(typeof a[0]==='string'&& typeof (a[1]||false)==='boolean' && typeof a[2]==='boolean' && typeof a[3] === 'number'){
  4792.  
  4793. // if(a[0].)
  4794. // this.determineIconSet()
  4795.  
  4796. // }
  4797.  
  4798. // const lastData = this.__lastData__;
  4799. // let newData = '';
  4800. this.__resolved__ = {
  4801.  
  4802. };
  4803.  
  4804. // let chAction = null;
  4805.  
  4806. // let returnNone = false;
  4807.  
  4808. // // w.nextAddress ...
  4809. // if(typeof a[0] === 'string' && a[0].length > 9 && a[1]===false && a[2] ===false && a[3]===24 && a[5] === true && a[0].length >= 3){
  4810.  
  4811. // console.log(12398, this.icon, this.iconsetName, this.iconType)
  4812. // if(this.icon === a[0] && this.icon === `${this.iconsetName}:${this.iconType}` && this.iconType && this.iconsetName && typeof this.targetContainer === 'string'){
  4813.  
  4814. // console.log(12399)
  4815. // newData = `renderIcon_${this.targetContainer}_${this.icon}`;
  4816. // chAction = ()=>{
  4817. // this.renderIcon(this.targetContainer, this.icon);
  4818. // console.log('yt-icon.xxs')
  4819. // }
  4820.  
  4821. // returnNone = true;
  4822.  
  4823. // }
  4824. // }
  4825.  
  4826.  
  4827. // if(!newData) newData = `x${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}_${Date.now()}`;
  4828.  
  4829. // if (lastData !== newData) {
  4830. // this.__lastData__ = newData;
  4831.  
  4832. // if (chAction && newData.startsWith('renderIcon_')) {
  4833. // stackTask(chAction);
  4834. // }
  4835.  
  4836. // }
  4837. const a01 = this.isAttached;
  4838. let a02, a03;
  4839.  
  4840.  
  4841. const t = this.__stackedKey3818__ = (this.__stackedKey3818__ & 1073741823) + 1;
  4842.  
  4843. const stackFn = () => {
  4844. if (t !== this.__stackedKey3818__) {
  4845. return;
  4846. }
  4847. a03 = this.isAttached;
  4848.  
  4849. // if(!a02 && !a03){
  4850.  
  4851. // }
  4852.  
  4853. if (a01 === false && a02 === false && a03 === false) return;
  4854.  
  4855. if (a01 === true && a02 === true && a03 === true) {
  4856.  
  4857. } else {
  4858. if (a01 === undefined && a02 === undefined && a03 === undefined && (this.hostElement || this).isConnected === false) {
  4859. // unknown yt-icon#label-icon
  4860. return;
  4861. } else {
  4862. console.log('[yt-icon] debug', a01, a02, a03, this)
  4863. }
  4864. }
  4865.  
  4866. this.handlePropertyChange671(...arguments);
  4867.  
  4868. };
  4869.  
  4870.  
  4871.  
  4872. Promise.resolve().then(() => {
  4873. a02 = this.isAttached;
  4874. stackTask(stackFn);
  4875. });
  4876.  
  4877.  
  4878.  
  4879.  
  4880.  
  4881. // console.log('yt-icon.handlePropertyChange', ...arguments);
  4882.  
  4883. // if(returnNone) return;
  4884. // return this.handlePropertyChange671(...arguments);
  4885. }
  4886.  
  4887. cProto.determineIconSet = function (a, b, c, d) { // 10-
  4888.  
  4889. if (!this.__ytIconSetup588__) setupYtIcon(this);
  4890. // string bool? bool=false int=24
  4891. // NOTIFICATIONS_NONE OR LIKE
  4892. // console.log('yt-icon.determineIconSet', ...arguments);
  4893.  
  4894. const r = this.determineIconSet671(...arguments);
  4895. // if(r.then){
  4896. // r.then((result)=>{
  4897. // console.log('yt-icon.determineIconSet.result = ', result)
  4898. // })
  4899. // }
  4900. return r;
  4901. }
  4902.  
  4903. cProto.switchToYtSysIconset = function (a, b, c, d) { // 10-
  4904.  
  4905. if (!this.__ytIconSetup588__) setupYtIcon(this);
  4906. // same as determineIconSet
  4907. // console.log('yt-icon.switchToYtSysIconset', ...arguments);
  4908. return this.switchToYtSysIconset671(...arguments);
  4909. }
  4910.  
  4911. cProto.useYtSysIconsetForMissingIcons = function (a, b, c, d) { // X
  4912.  
  4913. if (!this.__ytIconSetup588__) setupYtIcon(this);
  4914. // console.log('yt-icon.useYtSysIconsetForMissingIcons', ...arguments);
  4915. return this.useYtSysIconsetForMissingIcons671(...arguments);
  4916. }
  4917.  
  4918. cProto.getIconManager = function () { // 10+
  4919.  
  4920. if (!this.__ytIconSetup588__) setupYtIcon(this);
  4921. // no argument
  4922.  
  4923. // if(this.iconsetName && this.iconType){
  4924. // const p = kRef(iconManagers[this.iconsetName]);
  4925. // if(p) return p;
  4926. // }
  4927. // console.log(2388, this.iconType)
  4928. // console.log('yt-icon.getIconManager', ...arguments);
  4929. if (!this.__resolved__) this.__resolved__ = {};
  4930. if (!this.__resolved__.getIconManager) this.__resolved__.getIconManager = this.getIconManager671(...arguments);
  4931. const r = this.__resolved__.getIconManager;
  4932. // if(r.then){
  4933. // r.then((result)=>{
  4934. // iconManagers[this.iconsetName] = mWeakRef(result);
  4935. // console.log('yt-icon.getIconManager.result = ', result)
  4936. // })
  4937. // }
  4938. return r;
  4939. }
  4940.  
  4941. cProto.getIconShapeData = function () { // 10+
  4942.  
  4943. if (!this.__ytIconSetup588__) setupYtIcon(this);
  4944.  
  4945. // let rr;
  4946. // if (typeof (this.iconType || 0) === 'string' && typeof (this.iconsetName || 0) === 'string' && this.icon === `${this.iconsetName}:${this.iconType}` && (+this.size >= 1)) {
  4947. // const a = this;
  4948. // rr= {
  4949. // iconName: a.iconType.toLowerCase(),
  4950. // iconStyle: (a.active || a.defaultToFilled || c ? "youtube_fill" : "youtube_outline"),
  4951. // iconSize: a.size,
  4952. // iconSetName: a.iconsetName
  4953. // };
  4954.  
  4955. // }
  4956.  
  4957. // no argument
  4958. // console.log('yt-icon.getIconShapeData', ...arguments);
  4959. if (!this.__resolved__) this.__resolved__ = {};
  4960. if (!this.__resolved__.getIconShapeData) this.__resolved__.getIconShapeData = this.getIconShapeData671(...arguments);
  4961. const r = this.__resolved__.getIconShapeData;
  4962. // if (r.then) {
  4963. // r.then((result) =>{
  4964.  
  4965. // console.log('yt-icon.getIconShapeData.result = ', result)
  4966. // console.log('yt-icon.getIconShapeData.resultxx = ', rr)
  4967. // } )
  4968. // }
  4969.  
  4970.  
  4971.  
  4972. /*
  4973.  
  4974. temp1.resolveIcon({
  4975. iconName: a.iconType.toLowerCase(),
  4976. iconStyle: (a.active || a.defaultToFilled || c ? "youtube_fill" : "youtube_outline"),
  4977. iconSize: a.size,
  4978. iconSetName: a.iconsetName
  4979. })
  4980.  
  4981. */
  4982. return r
  4983. }
  4984.  
  4985. cProto.renderIcon = function (a, b) { // X
  4986.  
  4987. if (!this.__ytIconSetup588__) setupYtIcon(this);
  4988. // "" yt-icons:xxx
  4989. // console.log('yt-icon.renderIcon', ...arguments);
  4990. return this.renderIcon671(...arguments);
  4991. }
  4992.  
  4993. });
  4994.  
  4995. // stampDomArray_
  4996. const createStampDomArrayFn_ = () => {
  4997. // if (val_kevlar_should_maintain_stable_list === null) {
  4998. // const config_ = ((window.yt || 0).config_ || 0);
  4999. // val_kevlar_should_maintain_stable_list = ((config_ || 0).EXPERIMENT_FLAGS || 0).kevlar_should_maintain_stable_list === true;
  5000. // }
  5001.  
  5002. // if(true){
  5003.  
  5004.  
  5005. const pSpace = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  5006. document.documentElement.insertAdjacentElement('beforeend', pSpace);
  5007. const pNode = document.createElement('ns-538');
  5008. pSpace.insertAdjacentElement('beforeend', pNode);
  5009.  
  5010. const pDiv = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  5011. if (typeof pNode.attachShadow === 'function') {
  5012. const pShadow = pNode.attachShadow({ mode: "open" });
  5013. pShadow.replaceChildren(pDiv);
  5014. } else {
  5015. pNode.insertAdjacentElement('beforeend', pDiv);
  5016. }
  5017.  
  5018. const pDivTempRemoval = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  5019. pDiv.insertAdjacentElement('beforeend', pDivTempRemoval);
  5020. pDivTempRemoval.setAttribute('attm', 'pDivTempRemoval');
  5021.  
  5022. const pDivDeletion = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  5023. pDiv.insertAdjacentElement('beforeend', pDivDeletion);
  5024. pDivDeletion.setAttribute('attm', 'pDivDeletion');
  5025. const pDivKeep = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  5026. pDiv.insertAdjacentElement('beforeend', pDivKeep);
  5027. pDivKeep.setAttribute('attm', 'pDivKeep');
  5028.  
  5029.  
  5030. const pDivDeletionObs = new MutationObserver(() => {
  5031. let node = pDivDeletion.firstElementChild;
  5032. while (node) {
  5033. let nextNode = node.nextElementSibling;
  5034. if (node.__delayRemoved__) {
  5035. removeTNode_(node)
  5036. // } else {
  5037. // node.remove();
  5038. }
  5039. node = nextNode;
  5040. }
  5041. if (pDivDeletion.firstChild) pDivDeletion.textContent = '';
  5042. });
  5043. pDivDeletionObs.observe(pDivDeletion, { childList: true, subtree: false });
  5044.  
  5045. // const URa = function (a, b) {
  5046. // for (var c in a)
  5047. // if (a.hasOwnProperty(c) && b[c])
  5048. // return c;
  5049. // return null
  5050. // }
  5051.  
  5052. const syta = Symbol(); // container uid
  5053. // const sytb = Symbol();
  5054. const sytc = Symbol(); // data & parent relationship
  5055. const sytd = Symbol(); // bind data and component (in case not .data relationship -- to be reviewed)
  5056. const syte = Symbol(); // data uid
  5057.  
  5058. // const tmpElementNode = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
  5059.  
  5060. let fallbackToDefault = false;
  5061.  
  5062. const attributeMutationObserver = new MutationObserver((mutations) => {
  5063. const targets = new Set();
  5064. for (const mutation of mutations) {
  5065. targets.add(mutation.target);
  5066. }
  5067. for (const container of targets) {
  5068. const tag = container.__closestYtTag388__;
  5069. if (tag) {
  5070. const hostElement = container.closest(tag);
  5071. if (hostElement && hostElement.is === tag) {
  5072. const detail = {
  5073. container
  5074. };
  5075. hostElement.dispatchEvent(new CustomEvent("yt-rendererstamper-finished", {
  5076. bubbles: !0,
  5077. cancelable: !1,
  5078. composed: !0,
  5079. detail
  5080. }));
  5081. detail.container = null;
  5082. }
  5083. }
  5084. }
  5085. });
  5086.  
  5087. const stamperTasksA = {};
  5088.  
  5089. const YRa = (a, b) => {
  5090. for (const c in a)
  5091. if (a.hasOwnProperty(c) && b[c])
  5092. return c;
  5093. return null
  5094. }
  5095.  
  5096. // let lastClickX33 = 0;
  5097. // let minusX33 = 0;
  5098. // document.addEventListener('pointerdown', ()=>{
  5099. // nextBrowserTick_(()=>{
  5100. // minusX33 = 10000;
  5101. // });
  5102. // minusX33 = 0;
  5103. // lastClickX33 = Date.now();
  5104. // },true);
  5105. // document.addEventListener('keydown', ()=>{
  5106. // nextBrowserTick_(()=>{
  5107. // minusX33 = 10000;
  5108. // });
  5109. // minusX33 = 0;
  5110. // lastClickX33 = Date.now();
  5111. // },true);
  5112. // document.addEventListener('keyup', ()=>{
  5113. // nextBrowserTick_(()=>{
  5114. // minusX33 = 10000;
  5115. // });
  5116. // minusX33 = 0;
  5117. // lastClickX33 = Date.now();
  5118. // },true);
  5119. // document.addEventListener('pointerup', ()=>{
  5120. // nextBrowserTick_(()=>{
  5121. // minusX33 = 10000;
  5122. // });
  5123. // minusX33 = 0;
  5124. // lastClickX33 = Date.now();
  5125. // },true);
  5126.  
  5127. // document.addEventListener('pointercancel', ()=>{
  5128. // nextBrowserTick_(()=>{
  5129. // minusX33 = 10000;
  5130. // });
  5131. // minusX33 = 0;
  5132. // lastClickX33 = Date.now();
  5133. // },true);
  5134.  
  5135. let pageFirstDom = '';
  5136.  
  5137. // let emComponents = new Set();
  5138. let withStampDomExx = false;
  5139.  
  5140. const DEBUG_STAMP_CHANGE = false;
  5141. const DEBUG_FINALIZATION = false;
  5142.  
  5143.  
  5144. const reuseStore = typeof WeakRef === "function" && typeof FinalizationRegistry === "function" ? new Map() : null;
  5145. const registry = typeof WeakRef === "function" && typeof FinalizationRegistry === "function" ? new FinalizationRegistry((heldValue) => {
  5146. DEBUG_FINALIZATION && console.log(`Object(${heldValue}) has been released`);
  5147. }) : null;
  5148.  
  5149. const registerFn = typeof WeakRef === "function" && typeof FinalizationRegistry === "function" ? (node, heldValue) => {
  5150. Promise.resolve(node).then((node) => {
  5151. registry.register(node, heldValue);
  5152. });
  5153. } : () => { }
  5154.  
  5155.  
  5156. const go = function (a, b, c, d) {
  5157. d || (d = {
  5158. bubbles: !0,
  5159. cancelable: !1,
  5160. composed: !0
  5161. });
  5162. c !== null && c !== void 0 && (d.detail = c);
  5163. b = new CustomEvent(b, d);
  5164. a.dispatchEvent(b);
  5165. return b
  5166. };
  5167.  
  5168.  
  5169. const removeTNode__ = (node) => { // need trigger removal of its parent component
  5170. const xlivev = xlivec00.__domApi;
  5171. if (node.isConnected === true) {
  5172. xlivev.appendChild(node); // attached -> detached
  5173. // xlivev.removeChild(node); // detached -> detached
  5174. } else {
  5175. xlivev.appendChild(node); // detached -> detached
  5176. // xlivev.removeChild(node); // detached -> detached
  5177. }
  5178. }
  5179. // window.removeTNode__ = removeTNode__;
  5180.  
  5181. const removeTNode_ = (node) => { // need trigger removal of its parent component
  5182. const xdeadv = xdeadc00.__domApi;
  5183. // if (node.isConnected === true) {
  5184. xdeadv.appendChild(node); // attached -> detached
  5185. xdeadv.removeChild(node); // detached -> detached
  5186. // } else {
  5187. // xdeadv.appendChild(node); // detached -> detached
  5188. // xdeadv.removeChild(node); // detached -> detached
  5189. // }
  5190. }
  5191. // window.removeTNode_ = removeTNode_;
  5192.  
  5193. const removeTNode = (node) => { // need trigger removal of its parent component
  5194. const xdeadv = xdeadc00.__domApi;
  5195. if (node.isConnected === true) {
  5196. if (node.parentNode !== pDivDeletion) {
  5197. pDivDeletion.insertAdjacentHTML('afterbegin', ttpHTML('<!---->'));
  5198. pDivDeletion.lastChild.replaceWith(node); // attached -> attached
  5199. }
  5200.  
  5201. // xdeadv.appendChild(node); // attached -> detached
  5202. // xdeadv.removeChild(node); // detached -> detached
  5203.  
  5204. node.remove(); // attached -> detached
  5205. xdeadv.appendChild(node); // detached -> detached
  5206. xdeadv.removeChild(node); // detached -> detached
  5207. } else {
  5208.  
  5209. node.remove(); // detached -> detached
  5210. xdeadv.appendChild(node); // detached -> detached
  5211. xdeadv.removeChild(node); // detached -> detached
  5212.  
  5213. // xdeadv.appendChild(node); // detached -> detached
  5214. // xdeadv.removeChild(node); // detached -> detached
  5215. }
  5216. }
  5217. // window.removeTNode = removeTNode;
  5218.  
  5219.  
  5220. const removeTNodeDelayed = (node) => {
  5221. if (node.isConnected === true) {
  5222. node.__delayRemoved__ = true;
  5223. pDivDeletion.insertAdjacentHTML('afterbegin', ttpHTML('<!---->'));
  5224. pDivDeletion.lastChild.replaceWith(node); // attached -> attached
  5225. } else {
  5226. const xdeadv = xdeadc00.__domApi;
  5227. xdeadv.appendChild(node); // detached -> detached
  5228. xdeadv.removeChild(node); // detached -> detached
  5229. }
  5230. }
  5231. // window.removeTNodeDelayed = removeTNodeDelayed;
  5232.  
  5233. let triggerCountWithinMicro = 0;
  5234.  
  5235.  
  5236. const gn = function (items__, containerId, componentConfig, bReuseComponent, bEventCallback, bStableList) {
  5237. if (!xdeadc00) setupXdeadC(this);
  5238. let useSyncE = false; // essential components
  5239. // let useNative = false; // native
  5240. let disableTaskSkip = false;
  5241.  
  5242. triggerCountWithinMicro++;
  5243. const triggerCountWithinMicro_ = triggerCountWithinMicro;
  5244. Promise.resolve().then(() => {
  5245. triggerCountWithinMicro--;
  5246. });
  5247.  
  5248. const stack = new Error().stack;
  5249.  
  5250. let appendFrag = null;
  5251.  
  5252.  
  5253. // const safeFn0 = (items, containerId, componentConfig, bReuseComponent, bEventCallback, bStableList) => {
  5254.  
  5255. // let err, result;
  5256.  
  5257.  
  5258. // const qv1 = config.DEFERRED_DETACH;
  5259. // const qv2 = config.REUSE_COMPONENTS;
  5260. // const qv3 = config.STAMPER_STABLE_LIST;
  5261. // if (typeof qv1 !== 'undefined') config.DEFERRED_DETACH = false;
  5262. // if (typeof qv2 !== 'undefined') config.REUSE_COMPONENTS = false;
  5263. // // if (typeof qv3 !== 'undefined') config.STAMPER_STABLE_LIST = false;
  5264.  
  5265.  
  5266. // try {
  5267. // result = this.stampDomArray9682_(items, containerId, componentConfig, bReuseComponent, bEventCallback, bStableList);
  5268. // } catch (e) {
  5269. // err = e;
  5270. // }
  5271.  
  5272. // if (typeof qv1 !== 'undefined') config.DEFERRED_DETACH = qv1;
  5273. // if (typeof qv2 !== 'undefined') config.REUSE_COMPONENTS = qv2;
  5274. // // if (typeof qv3 !== 'undefined') config.STAMPER_STABLE_LIST = qv3;
  5275.  
  5276. // if (err) throw err;
  5277.  
  5278. // return result;
  5279.  
  5280.  
  5281. // };
  5282.  
  5283. // const safeFn = (items, containerId, componentConfig, bReuseComponent, bEventCallback, bStableList) => {
  5284.  
  5285. // let err, result;
  5286.  
  5287.  
  5288. // const qv1 = config.DEFERRED_DETACH;
  5289. // const qv2 = config.REUSE_COMPONENTS;
  5290. // const qv3 = config.STAMPER_STABLE_LIST;
  5291. // if (typeof qv1 !== 'undefined') config.DEFERRED_DETACH = false;
  5292. // if (typeof qv2 !== 'undefined') config.REUSE_COMPONENTS = false;
  5293. // if (typeof qv3 !== 'undefined') config.STAMPER_STABLE_LIST = false;
  5294.  
  5295.  
  5296. // try {
  5297. // this.stampDomArray9682_(null, containerId, null, bReuseComponent, null, null);
  5298. // result = this.stampDomArray9682_(items, containerId, componentConfig, bReuseComponent, bEventCallback, bStableList);
  5299. // } catch (e) {
  5300. // err = e;
  5301. // }
  5302.  
  5303. // if (typeof qv1 !== 'undefined') config.DEFERRED_DETACH = qv1;
  5304. // if (typeof qv2 !== 'undefined') config.REUSE_COMPONENTS = qv2;
  5305. // if (typeof qv3 !== 'undefined') config.STAMPER_STABLE_LIST = qv3;
  5306.  
  5307. // if (err) throw err;
  5308.  
  5309. // return result;
  5310.  
  5311.  
  5312. // };
  5313.  
  5314. // const safeClear = (containerId, bEventCallback, finishState) => {
  5315.  
  5316. // let err, result;
  5317.  
  5318.  
  5319. // const qv1 = config.DEFERRED_DETACH;
  5320. // const qv2 = config.REUSE_COMPONENTS;
  5321. // const qv3 = config.STAMPER_STABLE_LIST;
  5322. // if (typeof qv1 !== 'undefined') config.DEFERRED_DETACH = false;
  5323. // if (typeof qv2 !== 'undefined') config.REUSE_COMPONENTS = false;
  5324. // if (typeof qv3 !== 'undefined') config.STAMPER_STABLE_LIST = false;
  5325.  
  5326.  
  5327. // try {
  5328. // this.stampDomArray9682_(null, containerId, null, false, null, null);
  5329. // const k = this.getStampContainer_(containerId);
  5330.  
  5331. // if (finishState & 1) {
  5332. // this.flushRenderStamperComponentBindings_();
  5333. // }
  5334. // if (finishState & 2) {
  5335. // this.markDirty && this.markDirty();
  5336. // }
  5337. // if (finishState & 4) {
  5338. // bEventCallback && go(this.hostElement, "yt-rendererstamper-finished", {
  5339. // container: k
  5340. // });
  5341. // }
  5342. // } catch (e) {
  5343. // err = e;
  5344. // }
  5345.  
  5346. // if (typeof qv1 !== 'undefined') config.DEFERRED_DETACH = qv1;
  5347. // if (typeof qv2 !== 'undefined') config.REUSE_COMPONENTS = qv2;
  5348. // if (typeof qv3 !== 'undefined') config.STAMPER_STABLE_LIST = qv3;
  5349.  
  5350. // if (err) throw err;
  5351.  
  5352. // return result;
  5353.  
  5354.  
  5355. // };
  5356.  
  5357.  
  5358.  
  5359. // const safeAppendElm = (elm, items, containerId, componentConfig, bEventCallback, removeExisting, finishState) => {
  5360.  
  5361. // let err, result;
  5362.  
  5363.  
  5364. // const qv1 = config.DEFERRED_DETACH;
  5365. // const qv2 = config.REUSE_COMPONENTS;
  5366. // const qv3 = config.STAMPER_STABLE_LIST;
  5367. // if (typeof qv1 !== 'undefined') config.DEFERRED_DETACH = false;
  5368. // if (typeof qv2 !== 'undefined') config.REUSE_COMPONENTS = false;
  5369. // if (typeof qv3 !== 'undefined') config.STAMPER_STABLE_LIST = false;
  5370.  
  5371.  
  5372. // try {
  5373. // if (removeExisting) this.stampDomArray9682_(null, containerId, null, false, null, null);
  5374. // const c = componentConfig;
  5375. // const k = this.getStampContainer_(containerId);
  5376. // const b = k.__domApi || k;
  5377.  
  5378. // const g = appendFrag || (appendFrag = document.createDocumentFragment());
  5379. // let r;
  5380. // for (let i = 0, l = items.length; i < l; i++) {
  5381. // const u = items[i];
  5382. // const w = YRa(c, u);
  5383. // if (w) {
  5384. // r = elm;
  5385. // this.deferRenderStamperBinding_(r, c[w], u[w]);
  5386. // g.appendChild(r);
  5387. // }
  5388. // }
  5389. // b.appendChild(g)
  5390.  
  5391. // if (finishState & 1) {
  5392. // this.flushRenderStamperComponentBindings_();
  5393. // }
  5394. // if (finishState & 2) {
  5395. // this.markDirty && this.markDirty();
  5396. // }
  5397. // if (finishState & 4) {
  5398. // bEventCallback && go(this.hostElement, "yt-rendererstamper-finished", {
  5399. // container: k
  5400. // });
  5401. // }
  5402. // } catch (e) {
  5403. // err = e;
  5404. // }
  5405.  
  5406. // if (typeof qv1 !== 'undefined') config.DEFERRED_DETACH = qv1;
  5407. // if (typeof qv2 !== 'undefined') config.REUSE_COMPONENTS = qv2;
  5408. // if (typeof qv3 !== 'undefined') config.STAMPER_STABLE_LIST = qv3;
  5409.  
  5410. // if (err) throw err;
  5411.  
  5412. // return result;
  5413.  
  5414.  
  5415. // };
  5416.  
  5417.  
  5418. const safeAppend = (items, containerId, componentConfig, bEventCallback, removeExisting, finishState) => {
  5419.  
  5420. let err, result;
  5421.  
  5422.  
  5423. const qv1 = config.DEFERRED_DETACH;
  5424. const qv2 = config.REUSE_COMPONENTS;
  5425. const qv3 = config.STAMPER_STABLE_LIST;
  5426. if (typeof qv1 !== 'undefined') config.DEFERRED_DETACH = false;
  5427. if (typeof qv2 !== 'undefined') config.REUSE_COMPONENTS = false;
  5428. if (typeof qv3 !== 'undefined') config.STAMPER_STABLE_LIST = false;
  5429.  
  5430.  
  5431. try {
  5432. if (removeExisting) this.stampDomArray9682_(null, containerId, null, false, null, null);
  5433. const c = componentConfig;
  5434. const k = this.getStampContainer_(containerId);
  5435. const b = k.__domApi || k;
  5436. /*
  5437. const g = document.createDocumentFragment();
  5438. let r;
  5439. for(let i = 0, l =items.length; i<l;i++){
  5440. const u = items[i];
  5441. const w = YRa(c, u);
  5442. if (w) {
  5443. r = this.createComponent_(c[w], u[w], false);
  5444. this.deferRenderStamperBinding_(r, c[w], u[w]);
  5445. g.appendChild(r);
  5446. }
  5447. }
  5448. b.appendChild(g)
  5449. */
  5450.  
  5451. const g = appendFrag || (appendFrag = document.createDocumentFragment());
  5452. let r;
  5453. for (let i = 0, l = items.length; i < l; i++) {
  5454. const u = items[i];
  5455. const w = YRa(c, u);
  5456. if (w) {
  5457. r = this.createComponent_(c[w], u[w], false);
  5458. this.deferRenderStamperBinding_(r, c[w], u[w]);
  5459. g.appendChild(r);
  5460. }
  5461. }
  5462. b.appendChild(g)
  5463.  
  5464. if (finishState & 1) {
  5465. this.flushRenderStamperComponentBindings_();
  5466. }
  5467. if (finishState & 2) {
  5468. this.markDirty && this.markDirty();
  5469. }
  5470. if (finishState & 4) {
  5471. bEventCallback && go(this.hostElement, "yt-rendererstamper-finished", {
  5472. container: k
  5473. });
  5474. }
  5475. } catch (e) {
  5476. err = e;
  5477. }
  5478.  
  5479. if (typeof qv1 !== 'undefined') config.DEFERRED_DETACH = qv1;
  5480. if (typeof qv2 !== 'undefined') config.REUSE_COMPONENTS = qv2;
  5481. if (typeof qv3 !== 'undefined') config.STAMPER_STABLE_LIST = qv3;
  5482.  
  5483. if (err) throw err;
  5484.  
  5485. return result;
  5486.  
  5487.  
  5488. };
  5489.  
  5490.  
  5491. const safeFinish = (containerId, bEventCallback) => {
  5492.  
  5493. let err, result;
  5494.  
  5495.  
  5496. const qv1 = config.DEFERRED_DETACH;
  5497. const qv2 = config.REUSE_COMPONENTS;
  5498. const qv3 = config.STAMPER_STABLE_LIST;
  5499. if (typeof qv1 !== 'undefined') config.DEFERRED_DETACH = false;
  5500. if (typeof qv2 !== 'undefined') config.REUSE_COMPONENTS = false;
  5501. if (typeof qv3 !== 'undefined') config.STAMPER_STABLE_LIST = false;
  5502.  
  5503.  
  5504. try {
  5505. const k = this.getStampContainer_(containerId);
  5506.  
  5507. this.flushRenderStamperComponentBindings_();
  5508. this.markDirty && this.markDirty();
  5509. bEventCallback && go(this.hostElement, "yt-rendererstamper-finished", {
  5510. container: k
  5511. });
  5512.  
  5513. } catch (e) {
  5514. err = e;
  5515. }
  5516.  
  5517. if (typeof qv1 !== 'undefined') config.DEFERRED_DETACH = qv1;
  5518. if (typeof qv2 !== 'undefined') config.REUSE_COMPONENTS = qv2;
  5519. if (typeof qv3 !== 'undefined') config.STAMPER_STABLE_LIST = qv3;
  5520.  
  5521. if (err) throw err;
  5522.  
  5523. return result;
  5524.  
  5525.  
  5526. };
  5527.  
  5528. const stamperTasksKey = `${this.is}::${containerId}`;
  5529. const stamperTasks = stamperTasksA[stamperTasksKey] || (stamperTasksA[stamperTasksKey] = []);
  5530.  
  5531. let renderJob = this.renderJobsMap_ && containerId ? this.renderJobsMap_[containerId] : null;
  5532. const items_ = items__;
  5533. const hasRunningTasks = stamperTasks.length >= 1;
  5534. const config = (win.yt || 0).config_ || (win.ytcfg || 0).data_ || 0;
  5535. const container = typeof this.getStampContainer_ === 'function' ? this.getStampContainer_(containerId) : (this.$ || 0)[containerId];
  5536.  
  5537. if (!config) {
  5538. console.warn('no config');
  5539. fallbackToDefault = true;
  5540. } else if (!this.deferredBindingTasks_ || this.deferredBindingTasks_.length !== 0) {
  5541. console.warn('no deferredBindingTasks_');
  5542. fallbackToDefault = true;
  5543. } else if (!container) {
  5544. console.warn('no container');
  5545. fallbackToDefault = true;
  5546. } else {
  5547. if (container.__xnHookE93__ !== null) {
  5548. if (container.firstElementChild !== null) {
  5549. if (!container.__xnHookE93__) container.__xnHookE93__ = new Set();
  5550. container.__xnHookE93__.add(containerId);
  5551. } else if (container.__xnHookE93__) {
  5552. container.__xnHookE93__.delete(containerId);
  5553. if (container.__xnHookE93__.size === 0) {
  5554. container.__xnHookE93__ = null;
  5555. }
  5556. }
  5557. if (container.__xnHookE93__ !== null) {
  5558. fallbackToDefault = true; // skip handling weird element. wait until container become clean
  5559. } else {
  5560. container.__xnHookE93__ = null;
  5561. try {
  5562. this.stampDomArray9682_(null, containerId, null, false, false, false); // bind the yt dom api
  5563. } catch (e) { }
  5564. if (container.__domApi && !container.__domApi.__daHook377__) {
  5565. setupDomApi(Reflect.getPrototypeOf(container.__domApi));
  5566. setupSDomWrapper();
  5567. }
  5568. }
  5569. }
  5570. }
  5571.  
  5572. if (fallbackToDefault) {
  5573. return this.stampDomArray9682_(...arguments);
  5574. }
  5575.  
  5576.  
  5577. const bStableListA = bStableList !== undefined ? Boolean(bStableList) : (typeof config.STAMPER_STABLE_LIST !== "undefined" ? !!config.STAMPER_STABLE_LIST : false);
  5578.  
  5579. const containerDomApi = (container || 0).__domApi || container;
  5580. const containerElement = containerDomApi instanceof Node ? containerDomApi : insp(container).hostElement instanceof Node ? insp(container).hostElement : container;
  5581.  
  5582. const keyRequireAsync = `__stamperRequireAsync#${containerId}__`;
  5583. const key5993 = `__stamperCounter5993#${containerId}__`;
  5584. const key5996 = `__stamperCounter5996#${containerId}__`;
  5585. // const keyOnSync = `__stamperOnSync#${containerId}__`;
  5586.  
  5587.  
  5588.  
  5589. let hasKey = false;
  5590. if (items_ && items_.length >= 1) {
  5591.  
  5592. hasKey = items_.some((v) => (typeof YRa(componentConfig, v) === 'string'));
  5593.  
  5594. }
  5595.  
  5596. if (bEventCallback) {
  5597. if (!container.__rendererStamperEventCallback388__) {
  5598. container.__rendererStamperEventCallback388__ = true;
  5599. container.__closestYtTag388__ = this.is;
  5600. attributeMutationObserver.observe(container, { attributes: ['ytxx-stamper-finished'] });
  5601. }
  5602. }
  5603.  
  5604.  
  5605. if (!this.__rendererStamperFinishFn588__) {
  5606. this.__rendererStamperFinishFn588__ = () => {
  5607. if (this.deferredBindingTasks_ && this.deferredBindingTasks_.length >= 1) {
  5608. this.flushRenderStamperComponentBindings_();
  5609. }
  5610. this.markDirty && this.markDirty();
  5611. };
  5612.  
  5613. }
  5614.  
  5615.  
  5616.  
  5617.  
  5618. const items = hasKey ? items_.slice() : []; // avoid memory leakge
  5619.  
  5620. this[key5993] = (this[key5993] & 1073741823) + 1;
  5621.  
  5622. let leaveWithNoChange = false;
  5623.  
  5624.  
  5625. if (!hasRunningTasks && !this[keyRequireAsync]) {
  5626. if (!pageFirstDom) { // initial stamp action
  5627. pageFirstDom = this.is;
  5628. useSyncE = true;
  5629. this.__stampDomExx__ = true;
  5630. } else if (this.__stampDomExx__) { // essential component
  5631. useSyncE = true;
  5632. } else if (!withStampDomExx) { // not ready
  5633. useSyncE = true;
  5634. } else if (triggerCountWithinMicro_ === 1) { // first stamp action (user action)
  5635. useSyncE = true;
  5636. }
  5637. if (!hasKey) { // noChange
  5638. leaveWithNoChange = true;
  5639. useSyncE = true;
  5640. }
  5641. }
  5642.  
  5643. const useSync_ = useSyncE;
  5644. const tryBatchUpdate_ = !useSync_ && (renderJob || hasRunningTasks || this[keyRequireAsync]);
  5645.  
  5646. const skey = stamperTasks.__skey__ = `${Date.now()}`;
  5647.  
  5648. let taskFinish = false;
  5649.  
  5650. let result;
  5651.  
  5652. let skipToNextTask = false;
  5653.  
  5654. stamperTasks.push(() => {
  5655. if (skey !== stamperTasks.__skey__ && !disableTaskSkip) {
  5656. skipToNextTask = true;
  5657. // taskFinish = true;
  5658. }
  5659. });
  5660.  
  5661. if (leaveWithNoChange) {
  5662. if (container.__rendererStamperEventCallback388__) {
  5663. stamperTasks.push(() => {
  5664. if (taskFinish) return;
  5665. if(skipToNextTask) return;
  5666. if (container.__rendererStamperEventCallback388__) {
  5667. taskFinish = true;
  5668. container.setAttribute('ytxx-stamper-finished', (container.getAttribute('ytxx-stamper-finished') & 7) + 1);
  5669. return;
  5670. }
  5671. });
  5672. }
  5673. } else {
  5674.  
  5675. this[key5996] = (this[key5996] & 1073741823) + 1;
  5676. }
  5677.  
  5678. // this[key5996] = (this[key5996] & 1073741823) + 1;
  5679.  
  5680.  
  5681.  
  5682.  
  5683.  
  5684. containerElement[syta] = containerElement[syta] || `${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}_${Date.now()}`;
  5685. containerElement[sytd] = containerElement[sytd] || new WeakMap();
  5686.  
  5687. const mkData = new Set();
  5688.  
  5689. const pneItems = items.map(eq => {
  5690. const dataKey = firstObjectKey(eq);
  5691. const dataKey2 = YRa(componentConfig, eq)
  5692. if (dataKey && dataKey2 === dataKey) {
  5693. const targetComponentName = this.getComponentName_(componentConfig[dataKey], eq[dataKey]);
  5694. const data = eq[dataKey];
  5695. // if (data) data[sytb] = (data[sytb] & 1073741823) + 1;
  5696. if (data) {
  5697. data[syte] = data[syte] || `${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}_${Date.now()}`;
  5698. const arr = new Set((data[sytc] || '').split(','));
  5699. arr.delete('');
  5700. arr.add(containerElement[syta]);
  5701. data[sytc] = [...arr].join(',');
  5702. // addData.add(data);
  5703. mkData.add(data[syte]);
  5704. const dte = data[syte];
  5705. return {
  5706. targetComponentName,
  5707. dataKey,
  5708. data,
  5709. item: eq,
  5710. dte
  5711. }
  5712. }
  5713. }
  5714. return {
  5715. data: void 0,
  5716. item: eq,
  5717. dte: ''
  5718. };
  5719. }).filter(e=>!!e.dte);
  5720.  
  5721.  
  5722. let elementIter = containerElement.firstElementChild;
  5723. const uneElements = !elementIter ? [] : new Array(containerElement.childElementCount);
  5724. for (let i = 0, l = uneElements.length; i < l; i++) {
  5725. const pageElement = elementIter;
  5726. if (!pageElement) {
  5727. uneElements.length = i;
  5728. break;
  5729. }
  5730. const pageElementData = kRef(containerElement[sytd].get(pageElement));
  5731. const dte_ = pageElement[syte];
  5732. const dte = pageElementData && dte_ && pageElementData[syte] === dte_ && (insp(pageElement).data || 0)[syte] === dte_ ? dte_ : '';
  5733.  
  5734. uneElements[i] = {
  5735. pageElement: pageElement,
  5736. pageElementData: pageElementData,
  5737. dte
  5738. }
  5739. elementIter = elementIter.nextElementSibling;
  5740. }
  5741.  
  5742.  
  5743. const reuseKey = `${containerElement[syta]}**${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}_${Date.now()}`
  5744.  
  5745.  
  5746. let reuseRefreshMode = 1;
  5747.  
  5748. const setupComponent = (data, component, refNode, deferredBindingTask, reused = false) => {
  5749.  
  5750. let noRenderTaskForResuedComponent = false;
  5751. if (component instanceof Node) {
  5752.  
  5753.  
  5754. if (data && data[syte]) {
  5755. // component[sytb] = data[sytb]
  5756. component[sytc] = data[sytc]
  5757. component[syte] = data[syte];
  5758. // containerElement[sytd].set(data, mWeakRef(component));
  5759. containerElement[sytd].set(component, mWeakRef(data));
  5760. if(reuseStore) reuseStore.set(data[syte], mWeakRef(component));
  5761. }
  5762.  
  5763. const cnt = insp(component);
  5764.  
  5765. if (reused && reuseRefreshMode >= 1 && cnt.data) {
  5766. if (!cnt.__refreshData938__) {
  5767. cnt.constructor.prototype.__refreshData938__ = __refreshData938__;
  5768. }
  5769. try {
  5770. cnt.__refreshData938__('data', !0);
  5771. if(reuseRefreshMode >= 2) noRenderTaskForResuedComponent = true;
  5772. } catch (e) {
  5773. }
  5774. }
  5775.  
  5776. if (refNode !== undefined) {
  5777. const componentX = component;
  5778. if (componentX instanceof Node) {
  5779. if (refNode !== componentX) {
  5780. if (!refNode) {
  5781. containerElement.insertAdjacentHTML('beforeend', ttpHTML('<!---->'));
  5782. containerElement.lastChild.replaceWith(componentX);
  5783. } else {
  5784. refNode.insertAdjacentHTML('beforebegin', ttpHTML('<!---->'));
  5785. refNode.previousSibling.replaceWith(componentX);
  5786. }
  5787. }
  5788. }
  5789.  
  5790. }
  5791.  
  5792. if (noRenderTaskForResuedComponent) {
  5793.  
  5794. } else if (deferredBindingTask && deferredBindingTask.typeOrConfig) {
  5795. this.deferredBindingTasks_.push(deferredBindingTask);
  5796. this.flushRenderStamperComponentBindings_();
  5797. if (this.deferredBindingTasks_.length >= 1) this.deferredBindingTasks_.length = 0;
  5798. }
  5799.  
  5800. return true;
  5801.  
  5802. }
  5803. return false;
  5804.  
  5805. }
  5806.  
  5807. // if(!useNative)
  5808. stamperTasks.push(() => {
  5809.  
  5810. if (taskFinish) return;
  5811. if(skipToNextTask) return;
  5812.  
  5813. // if(skipToNextTask) return;
  5814.  
  5815.  
  5816. let tryStable = null;
  5817. if (bStableListA) {
  5818. tryStable = {};
  5819.  
  5820. pneItems.forEach(pneItem => {
  5821.  
  5822.  
  5823. const { item, dte, data, dataKey, targetComponentName } = pneItem;
  5824.  
  5825.  
  5826. const q_ = reuseStore ? kRef(reuseStore.get(dte)) : null; // no rendered dom for the item
  5827.  
  5828. if (!q_) {
  5829.  
  5830. if(!tryStable[targetComponentName]) tryStable[targetComponentName] = new Set();
  5831.  
  5832. tryStable[targetComponentName].add((node)=>{
  5833.  
  5834. const component = node;
  5835. const oldDte = node[syte];
  5836. const cnt = insp(node);
  5837. if (oldDte && oldDte !== dte && node.parentNode === containerElement && data && data[syte] && cnt.data && cnt.data[syte] ) {
  5838.  
  5839. this.telemetry_.reuse++;
  5840.  
  5841. // console.log(123992, node, componentConfig[dataKey], data, cnt.data, oldDte, dte )
  5842.  
  5843. // play safe
  5844. // component[sytb] = null;
  5845. component[sytc] = null;
  5846. component[syte] = null;
  5847. containerElement[sytd].delete(component);
  5848. // play safe
  5849.  
  5850. if (reuseStore) reuseStore.delete(oldDte);
  5851. node[syte] = dte;
  5852. node.___reuseFor__ = reuseKey; // once only
  5853.  
  5854.  
  5855.  
  5856. // cnt.data = data;
  5857. const deferredBindingTaskX = { component: component, typeOrConfig: componentConfig[dataKey], data: data }
  5858. setupComponent(data, component, undefined, deferredBindingTaskX, true);
  5859.  
  5860. // console.log(123993,'true')
  5861.  
  5862. return true;
  5863.  
  5864.  
  5865. }
  5866.  
  5867. return false;
  5868.  
  5869. });
  5870.  
  5871. }
  5872.  
  5873. })
  5874.  
  5875. }
  5876.  
  5877.  
  5878. const removes = [];
  5879.  
  5880.  
  5881. let node = containerElement.firstElementChild;
  5882. while (node !== null) {
  5883.  
  5884. const dte = node[syte];
  5885. const nextNode = node.nextElementSibling;
  5886.  
  5887.  
  5888. const tryStableCur = tryStable ? tryStable[node.is] : null;
  5889.  
  5890. if (tryStableCur && dte && !mkData.has(dte) && tryStableCur.size >= 1) {
  5891. // to be removed as no equal entry, but try to make it for tryStable
  5892.  
  5893. // this.deferRenderStamperBinding_(r, c[t], g[t]);
  5894. const fn = tryStableCur.values().next().value;
  5895. tryStableCur.delete(fn) && fn(node);
  5896. // this.deferRenderStamperBinding_(r, c[t], g[t]);
  5897.  
  5898. }
  5899.  
  5900. if(node.___reuseFor__ === reuseKey){
  5901.  
  5902.  
  5903. } else if (!(typeof (dte || 0) === 'string' && mkData.has(dte))) {
  5904.  
  5905. // console.log(insp(node).data);
  5906. // console.log(items)
  5907. removes.push(node);
  5908. // q30 = true;
  5909. // u.removeChild(node)
  5910. // try{
  5911. // v.removeChild(node); // just to trigger some internal removal
  5912. // }catch(e){
  5913. // }
  5914. }
  5915. node = nextNode;
  5916.  
  5917. }
  5918.  
  5919. tryStable = null;
  5920.  
  5921. if(removes.length === 0) return;
  5922.  
  5923. // let xdeadc = xdeadc00;
  5924. if (!xdeadc00) setupXdeadC(this);
  5925. // const xdeadv = xdeadc.__domApi;
  5926.  
  5927. for (const node of removes) {
  5928. removeTNode_(node);
  5929. registerFn(node, '01');
  5930. }
  5931.  
  5932. // safeClear(containerId, null, 2 | 4)
  5933.  
  5934. });
  5935.  
  5936.  
  5937. let refNode = null;
  5938. let refNodeIdx = -1;
  5939.  
  5940. const taskPerPneItem = (pneItem) => {
  5941.  
  5942.  
  5943. let reused = false;
  5944.  
  5945. const { item, dte, data, dataKey, targetComponentName } = pneItem;
  5946.  
  5947. refNode = ++refNodeIdx === 0 ? containerElement.firstElementChild : refNode && refNode.nextElementSibling;
  5948.  
  5949.  
  5950. const q_ = reuseStore ? kRef(reuseStore.get(dte)) : null;
  5951. const q = (q_ && (q_.___reuseFor__ === reuseKey || q_.closest('defs'))) ? q_ : null;
  5952.  
  5953. let deferredBindingTaskX = null;
  5954. let component = null;
  5955. if (q && q.is === targetComponentName) {
  5956.  
  5957. if (q_.closest('defs')) {
  5958.  
  5959. const node = component = q;
  5960. const cnt = insp(node);
  5961. cnt.data = data;
  5962. deferredBindingTaskX = { component: q, data: data }
  5963. // listX.push(deferredBindingTaskX);
  5964.  
  5965. DEBUG_STAMP_CHANGE && console.log('reuse X0')
  5966. reused = true;
  5967.  
  5968. } else {
  5969.  
  5970. const node = component = q;
  5971. const cnt = insp(node);
  5972. // cnt.data = data;
  5973. deferredBindingTaskX = { component: q, typeOrConfig: componentConfig[dataKey], data: data }
  5974. // listX.push(deferredBindingTaskX);
  5975.  
  5976. reused = true;
  5977.  
  5978. DEBUG_STAMP_CHANGE && console.log('reuse S0')
  5979.  
  5980. }
  5981.  
  5982.  
  5983.  
  5984. } else {
  5985.  
  5986. // console.log('new')
  5987.  
  5988.  
  5989. // const qf2 = this.deferRenderStamperBinding_;
  5990. // let deferredBindingTaskX = null;
  5991. this.deferRenderStamperBinding_ = function (a, b, c) {
  5992. deferredBindingTaskX = {
  5993. component: a,
  5994. typeOrConfig: b,
  5995. data: c
  5996. };
  5997. }
  5998.  
  5999. // console.log(23400, containerElement.childElementCount)
  6000. safeAppend([item], containerId, componentConfig, bEventCallback, false, 0 | 2 | 4);
  6001.  
  6002. // console.log(23401, containerElement.childElementCount)
  6003.  
  6004. // safeFn([item], containerId, componentConfig, false, bEventCallback, false);
  6005.  
  6006. delete this.deferRenderStamperBinding_;
  6007. // this.deferRenderStamperBinding_ = qf2;
  6008. // console.log(deferredBindingTaskX)
  6009. // listX.push(deferredBindingTaskX);
  6010.  
  6011. component = deferredBindingTaskX.component;
  6012.  
  6013. }
  6014.  
  6015.  
  6016. if (setupComponent(data, component, refNode, deferredBindingTaskX, reused)) {
  6017.  
  6018. refNode = component;
  6019. }
  6020.  
  6021.  
  6022.  
  6023.  
  6024. }
  6025.  
  6026. // if (!useNative)
  6027. pneItems.forEach((pneItem, idx) => {
  6028.  
  6029. stamperTasks.push(() => {
  6030. if (taskFinish) return;
  6031. if (skipToNextTask) return;
  6032.  
  6033. if (skipToNextTask) {
  6034.  
  6035. if (idx === 0) {
  6036.  
  6037. for (const pneItem of pneItems) {
  6038.  
  6039. taskPerPneItem(pneItem);
  6040. }
  6041. } else {
  6042. // skip
  6043.  
  6044. }
  6045. } else {
  6046.  
  6047.  
  6048. taskPerPneItem(pneItem);
  6049.  
  6050. }
  6051.  
  6052. });
  6053.  
  6054.  
  6055. });
  6056.  
  6057.  
  6058. // if(!useNative)
  6059. stamperTasks.push(() => {
  6060. if (taskFinish) return;
  6061. if (skipToNextTask) return;
  6062. // if (skipToNextTask) return;
  6063. let node = refNode;
  6064. if (!node) return;
  6065. node = node.nextElementSibling;
  6066. while (node) {
  6067. let nextNode = node.nextElementSibling;
  6068. removeTNode_(node);
  6069. registerFn(node, '02');
  6070. node = nextNode;
  6071. }
  6072. });
  6073.  
  6074.  
  6075.  
  6076. // if(useNative && stamperTasks.length === 0){
  6077.  
  6078.  
  6079. // this.stampDomArray9682_(...arguments);
  6080. // return;
  6081.  
  6082. // }
  6083.  
  6084.  
  6085. // if (useNative) {
  6086.  
  6087. // useSyncE = true;
  6088.  
  6089. // stamperTasks.push(() => {
  6090.  
  6091. // if (taskFinish) return;
  6092. // // if (skipToNextTask) return;
  6093.  
  6094. // // safeFn0(items__, containerId, componentConfig, false, bEventCallback, false);
  6095. // // safeFn(pneItems.map(e => e.item), containerId, componentConfig, false, bEventCallback, false)
  6096.  
  6097. // // this.stampDomArray9682_(items_, containerId, componentConfig, false, bEventCallback, false);
  6098. // // this.stampDomArray9682_(pneItems.map(e => e.item), containerId, componentConfig, false, bEventCallback, false);
  6099.  
  6100.  
  6101. // safeFn0(pneItems.map(e => e.item), containerId, componentConfig, bReuseComponent, bEventCallback, bStableList);
  6102. // // this.stampDomArray9682_(pneItems.map(e => e.item), containerId, componentConfig, bReuseComponent, bEventCallback, bStableList);
  6103.  
  6104. // // this.stampDomArray9682_(...arguments);
  6105. // })
  6106.  
  6107. // }
  6108.  
  6109.  
  6110.  
  6111. stamperTasks.push(() => {
  6112.  
  6113.  
  6114. if (!skipToNextTask) {
  6115.  
  6116. safeFinish(containerId, bEventCallback);
  6117. }
  6118.  
  6119. });
  6120.  
  6121.  
  6122. this[keyRequireAsync] = (this[keyRequireAsync] || 0) + 1;
  6123.  
  6124.  
  6125. stamperTasks.push(() => {
  6126.  
  6127. if (!skipToNextTask) {
  6128.  
  6129. this.__rendererStamperFinishFn588__();
  6130. }
  6131.  
  6132. this[keyRequireAsync] = (this[keyRequireAsync] || 0) - 1;
  6133.  
  6134. });
  6135.  
  6136.  
  6137. if(
  6138. // useNative &&
  6139. !leaveWithNoChange) {
  6140. disableTaskSkip = true;
  6141.  
  6142. const tasks = stamperTasks.slice();
  6143. stamperTasks.length = 0;
  6144.  
  6145. for (const task of tasks) {
  6146. task();
  6147. }
  6148. return;
  6149. }
  6150.  
  6151. if (useSync_) {
  6152.  
  6153. disableTaskSkip = true;
  6154.  
  6155. // [[ FOR CRITICAL TASK ]]
  6156.  
  6157. // if (!this[keyOnSync]) this[keyOnSync] = 0;
  6158. // this[keyOnSync]++;
  6159.  
  6160. // const pr = marcoPr;
  6161. // console.log(2992, pr, trackMarcoCm.data)
  6162. // trackMarcoCm.data = `${(trackMarcoCm.data & 7) + 1}`;
  6163. // pr.then(() => {
  6164. // this[keyOnSync]--;
  6165. // // console.log(3992, this.is);
  6166. // });
  6167.  
  6168. const tasks = stamperTasks.slice();
  6169. stamperTasks.length = 0;
  6170.  
  6171. for (const task of tasks) {
  6172. task();
  6173. }
  6174.  
  6175. if (!withStampDomExx && useSync_ && this.is === pageFirstDom) {
  6176. // we treat the components generated by initial stampDom as important
  6177.  
  6178. for (const elm of document.getElementsByTagName('*')) {
  6179. if (elm.is) {
  6180. insp(elm).__stampDomExx__ = true;
  6181. // emComponents.add(elm.is);
  6182. }
  6183. }
  6184. withStampDomExx = true;
  6185. }
  6186.  
  6187. } else {
  6188.  
  6189. if (!hasRunningTasks) {
  6190.  
  6191. const f = () => {
  6192. if (!stamperTasks.length) return;
  6193. const tasks = stamperTasks.slice();
  6194. stamperTasks.length = 0;
  6195. executeTaskBatch(tasks.map(fn => ({ fn })), false);
  6196. }
  6197.  
  6198. if (tryBatchUpdate_) {
  6199. nextBrowserTick_(f);// collecting all tasks (after reflow)
  6200. } else {
  6201. queueMicrotask_(f); // collecting some tasks (before reflow)
  6202. }
  6203.  
  6204. }
  6205.  
  6206. }
  6207.  
  6208. return;
  6209.  
  6210.  
  6211.  
  6212.  
  6213.  
  6214. }
  6215.  
  6216. return gn;
  6217.  
  6218. };
  6219.  
  6220.  
  6221. const setupDiscreteTasks = (h, rb) => {
  6222.  
  6223.  
  6224.  
  6225. if (typeof h.onYtRendererstamperFinished === 'function' && !(h.onYtRendererstamperFinished.km34)) {
  6226. const f = h.onYtRendererstamperFinished;
  6227. const g = ump3.get(f) || function () {
  6228. if (this.updateChildVisibilityProperties && !this.markDirty) {
  6229. return f.apply(this, arguments);
  6230. }
  6231. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6232. }
  6233. ump3.set(f, g);
  6234. g.km34 = 1;
  6235. h.onYtRendererstamperFinished = g;
  6236.  
  6237. }
  6238.  
  6239. if (typeof h.onYtUpdateDescriptionAction === 'function' && !(h.onYtUpdateDescriptionAction.km34)) {
  6240. const f = h.onYtUpdateDescriptionAction;
  6241. const g = ump3.get(f) || function (a) {
  6242. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6243. }
  6244. ump3.set(f, g);
  6245. g.km34 = 1;
  6246. h.onYtUpdateDescriptionAction = g;
  6247.  
  6248. }
  6249.  
  6250. if (typeof h.handleUpdateDescriptionAction === 'function' && !(h.handleUpdateDescriptionAction.km34)) {
  6251. const f = h.handleUpdateDescriptionAction;
  6252. const g = ump3.get(f) || function (a) {
  6253. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6254. }
  6255. ump3.set(f, g);
  6256. g.km34 = 1;
  6257. h.handleUpdateDescriptionAction = g;
  6258.  
  6259. }
  6260.  
  6261. if (typeof h.handleUpdateLiveChatPollAction === 'function' && !(h.handleUpdateLiveChatPollAction.km34)) {
  6262. const f = h.handleUpdateLiveChatPollAction;
  6263. const g = ump3.get(f) || function (a) {
  6264. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6265. }
  6266. ump3.set(f, g);
  6267. g.km34 = 1;
  6268. h.handleUpdateLiveChatPollAction = g;
  6269.  
  6270. }
  6271.  
  6272. if (typeof h.onTextChanged === 'function' && !(h.onTextChanged.km34)) {
  6273. const f = h.onTextChanged;
  6274. const g = ump3.get(f) || function () {
  6275. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6276. }
  6277. ump3.set(f, g);
  6278. g.km34 = 1;
  6279. h.onTextChanged = g;
  6280.  
  6281. }
  6282.  
  6283. if (typeof h.onVideoDataChange === 'function' && !(h.onVideoDataChange.km34)) {
  6284. const f = h.onVideoDataChange;
  6285. const g = ump3.get(f) || function (a) {
  6286. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6287. }
  6288. ump3.set(f, g);
  6289. g.km34 = 1;
  6290. h.onVideoDataChange = g;
  6291.  
  6292. }
  6293.  
  6294. if (typeof h.onVideoDataChange_ === 'function' && !(h.onVideoDataChange_.km34)) {
  6295. const f = h.onVideoDataChange_;
  6296. const g = ump3.get(f) || function () {
  6297. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6298. }
  6299. ump3.set(f, g);
  6300. g.km34 = 1;
  6301. h.onVideoDataChange_ = g;
  6302.  
  6303. }
  6304.  
  6305. if (typeof h.addTooltips_ === 'function' && !(h.addTooltips_.km34)) {
  6306.  
  6307. const f = h.addTooltips_;
  6308. const g = ump3.get(f) || function () {
  6309. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6310. }
  6311. ump3.set(f, g);
  6312. g.km34 = 1;
  6313. h.addTooltips_ = g;
  6314.  
  6315. }
  6316.  
  6317. if (typeof h.updateRenderedElements === 'function' && !(h.updateRenderedElements.km34)) {
  6318.  
  6319. const f = h.updateRenderedElements;
  6320. const g = ump3.get(f) || function () {
  6321. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6322. }
  6323. ump3.set(f, g);
  6324. g.km34 = 1;
  6325. h.updateRenderedElements = g;
  6326.  
  6327. }
  6328.  
  6329. if ((WEAK_REF_BINDING_CONTROL & 2) && typeof h.loadPage_ === 'function' && !(h.loadPage_.km34)) {
  6330. const f = h.loadPage_;
  6331. const g = ump3.get(f) || function (a) {
  6332. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6333. }
  6334. ump3.set(f, g);
  6335. g.km34 = 1;
  6336. h.loadPage_ = g;
  6337.  
  6338. }
  6339. // updatePageData_ : possible conflict with Omit ShadyDOM
  6340. if ((WEAK_REF_BINDING_CONTROL & 2) && typeof h.updatePageData_ === 'function' && !(h.updatePageData_.km34)) {
  6341. const f = h.updatePageData_;
  6342. const g = ump3.get(f) || function (a) {
  6343. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6344. }
  6345. ump3.set(f, g);
  6346. g.km34 = 1;
  6347. h.updatePageData_ = g;
  6348.  
  6349. }
  6350.  
  6351.  
  6352. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onFocus_ === 'function' && !(h.onFocus_.km34)) {
  6353.  
  6354. const f = h.onFocus_;
  6355. const g = ump3.get(f) || function () {
  6356. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6357. }
  6358. ump3.set(f, g);
  6359. g.km34 = 1;
  6360. h.onFocus_ = g;
  6361.  
  6362. }
  6363.  
  6364. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onBlur_ === 'function' && !(h.onBlur_.km34)) {
  6365.  
  6366. const f = h.onBlur_;
  6367. const g = ump3.get(f) || function () {
  6368. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6369. }
  6370. ump3.set(f, g);
  6371. g.km34 = 1;
  6372. h.onBlur_ = g;
  6373.  
  6374. }
  6375.  
  6376.  
  6377. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.buttonClassChanged_ === 'function' && !(h.buttonClassChanged_.km34)) {
  6378.  
  6379. const f = h.buttonClassChanged_;
  6380. const g = ump3.get(f) || function (a, b) {
  6381. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6382. }
  6383. ump3.set(f, g);
  6384. g.km34 = 1;
  6385. h.buttonClassChanged_ = g;
  6386.  
  6387. }
  6388.  
  6389. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.buttonIconChanged_ === 'function' && !(h.buttonIconChanged_.km34)) {
  6390.  
  6391. const f = h.buttonIconChanged_;
  6392. const g = ump3.get(f) || function (a) {
  6393. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6394. }
  6395. ump3.set(f, g);
  6396. g.km34 = 1;
  6397. h.buttonIconChanged_ = g;
  6398.  
  6399. }
  6400.  
  6401. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.dataChangedInBehavior_ === 'function' && !(h.dataChangedInBehavior_.km34)) {
  6402.  
  6403. const f = h.dataChangedInBehavior_;
  6404. const g = ump3.get(f) || function () {
  6405. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6406. }
  6407. ump3.set(f, g);
  6408. g.km34 = 1;
  6409. h.dataChangedInBehavior_ = g;
  6410.  
  6411. }
  6412.  
  6413. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.continuationsChanged_ === 'function' && !(h.continuationsChanged_.km34)) {
  6414.  
  6415. const f = h.continuationsChanged_;
  6416. const g = ump3.get(f) || function () {
  6417. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6418. }
  6419. ump3.set(f, g);
  6420. g.km34 = 1;
  6421. h.continuationsChanged_ = g;
  6422.  
  6423. }
  6424.  
  6425.  
  6426. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.forceChatPoll_ === 'function' && !(h.forceChatPoll_.km34)) {
  6427.  
  6428. const f = h.forceChatPoll_;
  6429. const g = ump3.get(f) || function (a) {
  6430. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6431. }
  6432. ump3.set(f, g);
  6433. g.km34 = 1;
  6434. h.forceChatPoll_ = g;
  6435.  
  6436. }
  6437.  
  6438. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onEndpointClick_ === 'function' && !(h.onEndpointClick_.km34)) {
  6439.  
  6440. const f = h.onEndpointClick_;
  6441. const g = ump3.get(f) || function (a) {
  6442. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6443. }
  6444. ump3.set(f, g);
  6445. g.km34 = 1;
  6446. h.onEndpointClick_ = g;
  6447.  
  6448. }
  6449.  
  6450. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onEndpointTap_ === 'function' && !(h.onEndpointTap_.km34)) {
  6451.  
  6452. const f = h.onEndpointTap_;
  6453. const g = ump3.get(f) || function (a) {
  6454. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6455. }
  6456. ump3.set(f, g);
  6457. g.km34 = 1;
  6458. h.onEndpointTap_ = g;
  6459.  
  6460. }
  6461.  
  6462. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.handleClick_ === 'function' && !(h.handleClick_.km34)) {
  6463.  
  6464. const f = h.handleClick_;
  6465. const g = ump3.get(f) || function (a, b) {
  6466. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6467. }
  6468. ump3.set(f, g);
  6469. g.km34 = 1;
  6470. h.handleClick_ = g;
  6471.  
  6472. }
  6473.  
  6474. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onReadyStateChange_ === 'function' && !(h.onReadyStateChange_.km34)) {
  6475.  
  6476. const f = h.onReadyStateChange_;
  6477. const g = ump3.get(f) || function () {
  6478. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6479. }
  6480. ump3.set(f, g);
  6481. g.km34 = 1;
  6482. h.onReadyStateChange_ = g;
  6483.  
  6484. }
  6485.  
  6486. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onReadyStateChangeEntryPoint_ === 'function' && !(h.onReadyStateChangeEntryPoint_.km34)) {
  6487.  
  6488. const f = h.onReadyStateChangeEntryPoint_;
  6489. const g = ump3.get(f) || function () {
  6490. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6491. }
  6492. ump3.set(f, g);
  6493. g.km34 = 1;
  6494. h.onReadyStateChangeEntryPoint_ = g;
  6495.  
  6496. }
  6497.  
  6498. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.readyStateChangeHandler_ === 'function' && !(h.readyStateChangeHandler_.km34)) {
  6499.  
  6500. const f = h.readyStateChangeHandler_;
  6501. const g = ump3.get(f) || function (a) {
  6502. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6503. }
  6504. ump3.set(f, g);
  6505. g.km34 = 1;
  6506. h.readyStateChangeHandler_ = g;
  6507.  
  6508. }
  6509.  
  6510. if (typeof h.xmlHttpHandler_ === 'function' && !(h.xmlHttpHandler_.km34)) {
  6511.  
  6512. const f = h.xmlHttpHandler_;
  6513. const g = ump3.get(f) || function (a) {
  6514. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6515. }
  6516. ump3.set(f, g);
  6517. g.km34 = 1;
  6518. h.xmlHttpHandler_ = g;
  6519.  
  6520. }
  6521.  
  6522. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.executeCallbacks_ === 'function' && !(h.executeCallbacks_.km34)) {
  6523.  
  6524. const f = h.executeCallbacks_; // overloaded
  6525. const g = ump3.get(f) || function (a) {
  6526. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6527. }
  6528. ump3.set(f, g);
  6529. g.km34 = 1;
  6530. h.executeCallbacks_ = g;
  6531.  
  6532. }
  6533.  
  6534. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.handleInvalidationData_ === 'function' && !(h.handleInvalidationData_.km34)) {
  6535.  
  6536. const f = h.handleInvalidationData_;
  6537. const g = ump3.get(f) || function (a, b) {
  6538. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6539. }
  6540. ump3.set(f, g);
  6541. g.km34 = 1;
  6542. h.handleInvalidationData_ = g;
  6543.  
  6544. }
  6545.  
  6546. if (typeof h.onInput_ === 'function' && !(h.onInput_.km34)) {
  6547.  
  6548. const f = h.onInput_;
  6549. const g = ump3.get(f) || function () {
  6550. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6551. }
  6552. ump3.set(f, g);
  6553. g.km34 = 1;
  6554. h.onInput_ = g;
  6555.  
  6556. }
  6557. if (typeof h.trigger_ === 'function' && !(h.trigger_.km34)) {
  6558.  
  6559. const f = h.trigger_;
  6560. const g = ump3.get(f) || function (a) {
  6561. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6562. }
  6563. ump3.set(f, g);
  6564. g.km34 = 1;
  6565. h.trigger_ = g;
  6566.  
  6567. }
  6568.  
  6569. if (typeof h.requestData_ === 'function' && !(h.requestData_.km34)) {
  6570.  
  6571. const f = h.requestData_;
  6572. const g = ump3.get(f) || function (a) {
  6573. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6574. }
  6575. ump3.set(f, g);
  6576. g.km34 = 1;
  6577. h.requestData_ = g;
  6578.  
  6579. }
  6580.  
  6581. if (typeof h.onLoadReloadContinuation_ === 'function' && !(h.onLoadReloadContinuation_.km34)) {
  6582.  
  6583. const f = h.onLoadReloadContinuation_;
  6584. const g = ump3.get(f) || function (a, b) {
  6585. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6586. }
  6587. ump3.set(f, g);
  6588. g.km34 = 1;
  6589. h.onLoadReloadContinuation_ = g;
  6590.  
  6591. }
  6592.  
  6593. if (typeof h.onLoadIncrementalContinuation_ === 'function' && !(h.onLoadIncrementalContinuation_.km34)) {
  6594.  
  6595. const f = h.onLoadIncrementalContinuation_;
  6596. const g = ump3.get(f) || function (a, b) {
  6597. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6598. }
  6599. ump3.set(f, g);
  6600. g.km34 = 1;
  6601. h.onLoadIncrementalContinuation_ = g;
  6602.  
  6603. }
  6604.  
  6605. if (typeof h.onLoadSeekContinuation_ === 'function' && !(h.onLoadSeekContinuation_.km34)) {
  6606.  
  6607. const f = h.onLoadSeekContinuation_;
  6608. const g = ump3.get(f) || function (a, b) {
  6609. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6610. }
  6611. ump3.set(f, g);
  6612. g.km34 = 1;
  6613. h.onLoadSeekContinuation_ = g;
  6614.  
  6615. }
  6616. if (typeof h.onLoadReplayContinuation_ === 'function' && !(h.onLoadReplayContinuation_.km34)) {
  6617.  
  6618. const f = h.onLoadReplayContinuation_;
  6619. const g = ump3.get(f) || function (a, b) {
  6620. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6621. }
  6622. ump3.set(f, g);
  6623. g.km34 = 1;
  6624. h.onLoadReplayContinuation_ = g;
  6625.  
  6626. }
  6627. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.onNavigate_ === 'function' && !(h.onNavigate_.km34)) {
  6628.  
  6629. const f = h.onNavigate_;
  6630. const g = ump3.get(f) || function (a) {
  6631. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6632. }
  6633. ump3.set(f, g);
  6634. g.km34 = 1;
  6635. h.onNavigate_ = g;
  6636.  
  6637. }
  6638.  
  6639. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.ytRendererBehaviorDataObserver_ === 'function' && !(h.ytRendererBehaviorDataObserver_.km34)) {
  6640.  
  6641. const f = h.ytRendererBehaviorDataObserver_;
  6642. const g = ump3.get(f) || function () {
  6643. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6644. }
  6645. ump3.set(f, g);
  6646. g.km34 = 1;
  6647. h.ytRendererBehaviorDataObserver_ = g;
  6648.  
  6649. }
  6650.  
  6651. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.ytRendererBehaviorTargetIdObserver_ === 'function' && !(h.ytRendererBehaviorTargetIdObserver_.km34)) {
  6652.  
  6653. const f = h.ytRendererBehaviorTargetIdObserver_;
  6654. const g = ump3.get(f) || function () {
  6655. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6656. }
  6657. ump3.set(f, g);
  6658. g.km34 = 1;
  6659. h.ytRendererBehaviorTargetIdObserver_ = g;
  6660.  
  6661. }
  6662.  
  6663. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.unregisterRenderer_ === 'function' && !(h.unregisterRenderer_.km34)) {
  6664.  
  6665. const f = h.unregisterRenderer_;
  6666. const g = ump3.get(f) || function (a) {
  6667. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6668. }
  6669. ump3.set(f, g);
  6670. g.km34 = 1;
  6671. h.unregisterRenderer_ = g;
  6672.  
  6673. }
  6674.  
  6675. if ((WEAK_REF_BINDING_CONTROL & 1) && typeof h.textChanged_ === 'function' && !(h.textChanged_.km34)) {
  6676.  
  6677. const f = h.textChanged_;
  6678. const g = ump3.get(f) || function (a) {
  6679. if (void 0 !== this.isAttached) {
  6680. const hostElement = this.hostElement;
  6681. if (!(hostElement instanceof Node) || hostElement.nodeName === 'NOSCRIPT') {
  6682. return;
  6683. }
  6684. }
  6685. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6686. }
  6687. ump3.set(f, g);
  6688. g.km34 = 1;
  6689. h.textChanged_ = g;
  6690.  
  6691. }
  6692.  
  6693.  
  6694.  
  6695. /**
  6696. *
  6697. * Neglect following
  6698. *
  6699. * h.onYtAction_
  6700. * h.startLoadingWatch [ buggy for yt-player-updated ]
  6701. * h.deferRenderStamperBinding_
  6702. *
  6703. * h.stampDomArray_
  6704. * h.stampDomArraySplices_
  6705. *
  6706. */
  6707.  
  6708.  
  6709. // RP.prototype.searchChanged_ = RP.prototype.searchChanged_;
  6710. // RP.prototype.skinToneChanged_ = RP.prototype.skinToneChanged_;
  6711. // RP.prototype.onEmojiHover_ = RP.prototype.onEmojiHover_;
  6712. // RP.prototype.onSelectCategory_ = RP.prototype.onSelectCategory_;
  6713. // RP.prototype.onShowEmojiVariantSelector = RP.prototype.onShowEmojiVariantSelector;
  6714. // RP.prototype.updateCategoriesAndPlaceholder_ = RP.prototype.updateCategoriesAndPlaceholder_;
  6715.  
  6716. if (typeof h.searchChanged_ === 'function' && !(h.searchChanged_.km34)) {
  6717.  
  6718. const f = h.searchChanged_;
  6719. const g = ump3.get(f) || function () {
  6720. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6721. }
  6722. ump3.set(f, g);
  6723. g.km34 = 1;
  6724. h.searchChanged_ = g;
  6725.  
  6726. }
  6727.  
  6728. if (typeof h.skinToneChanged_ === 'function' && !(h.skinToneChanged_.km34)) {
  6729.  
  6730. const f = h.skinToneChanged_;
  6731. const g = ump3.get(f) || function (a) {
  6732. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6733. }
  6734. ump3.set(f, g);
  6735. g.km34 = 1;
  6736. h.skinToneChanged_ = g;
  6737.  
  6738. }
  6739.  
  6740. if (typeof h.onEmojiHover_ === 'function' && !(h.onEmojiHover_.km34)) {
  6741.  
  6742. const f = h.onEmojiHover_;
  6743. const g = ump3.get(f) || function (a) {
  6744. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6745. }
  6746. ump3.set(f, g);
  6747. g.km34 = 1;
  6748. h.onEmojiHover_ = g;
  6749.  
  6750. }
  6751.  
  6752. if (typeof h.onSelectCategory_ === 'function' && !(h.onSelectCategory_.km34)) {
  6753.  
  6754. const f = h.onSelectCategory_;
  6755. const g = ump3.get(f) || function (a) {
  6756. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6757. }
  6758. ump3.set(f, g);
  6759. g.km34 = 1;
  6760. h.onSelectCategory_ = g;
  6761.  
  6762. }
  6763.  
  6764. if (typeof h.onShowEmojiVariantSelector === 'function' && !(h.onShowEmojiVariantSelector.km34)) {
  6765.  
  6766. const f = h.onShowEmojiVariantSelector;
  6767. const g = ump3.get(f) || function (a) {
  6768. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6769. }
  6770. ump3.set(f, g);
  6771. g.km34 = 1;
  6772. h.onShowEmojiVariantSelector = g;
  6773.  
  6774. }
  6775.  
  6776. if (typeof h.updateCategoriesAndPlaceholder_ === 'function' && !(h.updateCategoriesAndPlaceholder_.km34)) {
  6777.  
  6778. const f = h.updateCategoriesAndPlaceholder_;
  6779. const g = ump3.get(f) || function () {
  6780. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6781. }
  6782. ump3.set(f, g);
  6783. g.km34 = 1;
  6784. h.updateCategoriesAndPlaceholder_ = g;
  6785.  
  6786. }
  6787.  
  6788. if (typeof h.watchPageActiveChanged_ === 'function' && !(h.watchPageActiveChanged_.km34)) {
  6789.  
  6790. const f = h.watchPageActiveChanged_;
  6791. const g = ump3.get(f) || function () {
  6792. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6793. }
  6794. ump3.set(f, g);
  6795. g.km34 = 1;
  6796. h.watchPageActiveChanged_ = g;
  6797.  
  6798. }
  6799.  
  6800. if (typeof h.activate_ === 'function' && !(h.activate_.km34)) {
  6801.  
  6802. const f = h.activate_;
  6803. const g = ump3.get(f) || function () {
  6804. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6805. }
  6806. ump3.set(f, g);
  6807. g.km34 = 1;
  6808. h.activate_ = g;
  6809.  
  6810. }
  6811. if (typeof h.onYtPlaylistDataUpdated_ === 'function' && !(h.onYtPlaylistDataUpdated_.km34)) {
  6812.  
  6813. const f = h.onYtPlaylistDataUpdated_;
  6814. const g = ump3.get(f) || function () {
  6815. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6816. }
  6817. ump3.set(f, g);
  6818. g.km34 = 1;
  6819. h.onYtPlaylistDataUpdated_ = g;
  6820.  
  6821. }
  6822.  
  6823.  
  6824.  
  6825. /**
  6826. *
  6827. * Neglect following
  6828. *
  6829. * h.rendererStamperObserver_
  6830. * h.rendererStamperApplyChangeRecord_
  6831. * h.flushRenderStamperComponentBindings_
  6832. * h.forwardRendererStamperChanges_
  6833. *
  6834. */
  6835.  
  6836. if (typeof h.tryRenderChunk_ === 'function' && !(h.tryRenderChunk_.km34)) {
  6837.  
  6838. const f = h.tryRenderChunk_;
  6839. const g = ump3.get(f) || function () {
  6840. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6841. }
  6842. ump3.set(f, g);
  6843. g.km34 = 1;
  6844. h.tryRenderChunk_ = g;
  6845.  
  6846. }
  6847.  
  6848.  
  6849. if (typeof h.renderChunk_ === 'function' && !(h.renderChunk_.km34)) {
  6850.  
  6851. const f = h.renderChunk_;
  6852. const g = ump3.get(f) || function () {
  6853. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6854. }
  6855. ump3.set(f, g);
  6856. g.km34 = 1;
  6857. h.renderChunk_ = g;
  6858.  
  6859. }
  6860.  
  6861. if (typeof h.deepLazyListObserver_ === 'function' && !(h.deepLazyListObserver_.km34)) {
  6862.  
  6863. const f = h.deepLazyListObserver_;
  6864. const g = ump3.get(f) || function () {
  6865. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6866. }
  6867. ump3.set(f, g);
  6868. g.km34 = 1;
  6869. h.deepLazyListObserver_ = g;
  6870.  
  6871. }
  6872.  
  6873. if (typeof h.onItemsUpdated_ === 'function' && !(h.onItemsUpdated_.km34)) {
  6874.  
  6875. const f = h.onItemsUpdated_;
  6876. const g = ump3.get(f) || function () {
  6877. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6878. }
  6879. ump3.set(f, g);
  6880. g.km34 = 1;
  6881. h.onItemsUpdated_ = g;
  6882.  
  6883. }
  6884.  
  6885. if (typeof h.requestRenderChunk_ === 'function' && !(h.requestRenderChunk_.km34)) {
  6886.  
  6887. const f = h.requestRenderChunk_;
  6888. const g = ump3.get(f) || function () {
  6889. Promise.resolve().then(() => f.apply(this, arguments)).catch(console.log);
  6890. }
  6891. ump3.set(f, g);
  6892. g.km34 = 1;
  6893. h.requestRenderChunk_ = g;
  6894.  
  6895. }
  6896.  
  6897. /**
  6898. *
  6899. * Neglect following
  6900. *
  6901. * h.dataChanged_ [ buggy for page swtiching ]
  6902. *
  6903. * h.updateChangeRecord_ [ see https://github.com/cyfung1031/userscript-supports/issues/20 ]
  6904. *
  6905. * h.cancelPendingTasks_
  6906. * h.fillRange_
  6907. * h.addTextNodes_
  6908. * h.updateText_
  6909. * h.stampTypeChanged_
  6910. *
  6911. */
  6912.  
  6913.  
  6914. }
  6915.  
  6916. const keyStConnectedCallback = Symbol(); // avoid copying the value
  6917.  
  6918. // const keyStDisconnectedCallback = Symbol(); // avoid copying the value
  6919. const cmf = new WeakMap();
  6920. const dmf = new WeakMap();
  6921.  
  6922. const gvGenerator = (nv) => {
  6923. return function () {
  6924. const cnt = insp(this);
  6925. const hostElement = cnt.hostElement || 0;
  6926. const dollar = hostElement ? (this.$ || indr(this)) : 0;
  6927. let p = (hostElement instanceof HTMLElement_) && (dollar || !this.is);
  6928. if (p && (!dollar && !this.is)) {
  6929. const nodeName = hostElement.nodeName;
  6930. if (typeof nodeName !== 'string') {
  6931. // just in case
  6932. } else if (nodeName.startsWith("DOM-")) {
  6933. // dom-if, dom-repeat, etc
  6934. } else {
  6935. // yt element - new model, yt-xxxx, anixxxxxx
  6936. p = false;
  6937. }
  6938. }
  6939. if (p) {
  6940. if (typeof cnt.markDirty === 'function') {
  6941. // the yt element might call markDirty (occasionally)
  6942. p = false;
  6943. } else if (this.is === 'ytd-engagement-panel-section-list-renderer') {
  6944. // see https://github.com/cyfung1031/userscript-supports/issues/20
  6945. p = false;
  6946. }
  6947. }
  6948. if (p) {
  6949.  
  6950. // << dom-repeat & dom-if >>
  6951.  
  6952. // sequence on the same instance
  6953. this[qm57] = (this[qm57] || Promise.resolve()).then(() => nv.apply(this, arguments)).catch(console.log);
  6954. } else {
  6955. nv.apply(this, arguments);
  6956. }
  6957. };
  6958. }
  6959.  
  6960. // const assignedHolderWS = new WeakSet();
  6961.  
  6962. const setupWeakRef = (h) => {
  6963.  
  6964.  
  6965. }
  6966.  
  6967.  
  6968. let nativeHTMLElement = Reflect.getPrototypeOf(HTMLFontElement);
  6969.  
  6970. try {
  6971.  
  6972. const q = document.createElement('template');
  6973. q.innerHTML = '<ytz-null361></ytz-null361>';
  6974. nativeHTMLElement = q.content.firstChild.constructor
  6975.  
  6976. } catch (e) { }
  6977.  
  6978. if (!nativeHTMLElement.prototype.connectedCallback) {
  6979. nativeHTMLElement.prototype.connectedCallback79 = nativeHTMLElement.prototype.connectedCallback;
  6980. nativeHTMLElement.prototype.connectedCallback = function () {
  6981. let r;
  6982. if (this.connectedCallback79) r = this.connectedCallback79.apply(this, arguments);
  6983. return r;
  6984. }
  6985. }
  6986. const pvr = Symbol()
  6987.  
  6988. let stampDomArrayMethod = null;
  6989. const setupMap = new WeakSet();
  6990.  
  6991. // const ENABLE_weakenStampReferencesQ = ENABLE_weakenStampReferences && typeof DocumentTimeline !== 'undefined' && typeof WeakRef !== 'undefined';
  6992. const setupYtComponent = (cnt) => {
  6993. const cProto = (cnt || 0).__proto__ || 0;
  6994. if (!cProto || setupMap.has(cProto)) return;
  6995. setupMap.add(cProto);
  6996. if (FIX_stampDomArray && !(cProto[pvr] & 1) && 'stampDomArray_' in cProto) {
  6997. cProto[pvr] |= 1;
  6998. if (FIX_stampDomArray && cProto.stampDomArray_ && !cProto.stampDomArray9682_) {
  6999. if (!stampDomArrayMethod) stampDomArrayMethod = createStampDomArrayFn_();
  7000. cProto.stampDomArray9682_ = cProto.stampDomArray_;
  7001. cProto.stampDomArray_ = stampDomArrayMethod;
  7002. }
  7003. }
  7004. if (ENABLE_discreteTasking && !(cProto[pvr] & 2) && (typeof (cProto.is || 0) === 'string' || ('attached' in cProto) || ('isAttached' in cProto))) {
  7005. cProto[pvr] |= 2;
  7006. setupDiscreteTasks(cProto);
  7007. }
  7008. };
  7009.  
  7010. (ENABLE_discreteTasking || FIX_stampDomArray) && Object.defineProperty(Object.prototype, 'connectedCallback', {
  7011. get() {
  7012. const f = this[keyStConnectedCallback];
  7013. if (this.is) {
  7014. setupYtComponent(this);
  7015. }
  7016. /*
  7017. if (this.is) {
  7018. setupDiscreteTasks(this, true);
  7019. if (f) this.ky36 = 1;
  7020. }
  7021. */
  7022. return f;
  7023. },
  7024. set(nv) {
  7025. let gv = nv;
  7026. /*
  7027. if (typeof nv === 'function') {
  7028.  
  7029. gv = cmf.get(nv) || gvGenerator(nv);
  7030. if (gv !== nv) {
  7031. cmf.set(nv, gv);
  7032. cmf.set(gv, gv);
  7033. dmf.set(gv, nv);
  7034. }
  7035.  
  7036. } else {
  7037. gv = nv;
  7038. }
  7039. */
  7040. this[keyStConnectedCallback] = gv; // proto or object
  7041. /*
  7042. if (this.is) {
  7043. setupDiscreteTasks(this);
  7044. }
  7045. */
  7046. return true;
  7047. },
  7048. enumerable: false,
  7049. configurable: true
  7050.  
  7051. });
  7052.  
  7053. const pLoad = new Promise(resolve => {
  7054. if (document.readyState !== 'loading') {
  7055. resolve();
  7056. } else {
  7057. window.addEventListener("DOMContentLoaded", resolve, false);
  7058. }
  7059. });
  7060.  
  7061. if (FIX_fix_requestIdleCallback_timing && !window.requestIdleCallback471 && typeof window.requestIdleCallback === 'function') {
  7062. window.requestIdleCallback471 = window.requestIdleCallback;
  7063. window.requestIdleCallback = function (f, ...args) {
  7064. return (this || window).requestIdleCallback471(async function () {
  7065. await pLoad.then();
  7066. // await new Promise(nextBrowserTick_);
  7067. f.call(this, ...arguments)
  7068. }, ...args);
  7069. }
  7070. }
  7071.  
  7072. pLoad.then(() => {
  7073.  
  7074. let nonce = document.querySelector('style[nonce]');
  7075. nonce = nonce ? nonce.getAttribute('nonce') : null;
  7076. const st = document.createElement('style');
  7077. if (typeof nonce === 'string') st.setAttribute('nonce', nonce);
  7078. st.textContent = "none-element-k47{order:0}";
  7079. st.addEventListener('load', () => {
  7080. pf31.resolve();
  7081. p59 = 1;
  7082. }, false);
  7083. (document.body || document.head || document.documentElement).appendChild(st);
  7084.  
  7085. });
  7086.  
  7087. const prepareLogs = [];
  7088.  
  7089. const skipAdsDetection = new Set(['/robots.txt', '/live_chat', '/live_chat_replay']);
  7090.  
  7091. let winError00 = window.onerror;
  7092.  
  7093. let fix_error_many_stack_state = !FIX_error_many_stack ? 0 : skipAdsDetection.has(location.pathname) ? 2 : 1;
  7094.  
  7095. if (!JSON || !('parse' in JSON)) fix_error_many_stack_state = 0;
  7096.  
  7097. ; FIX_Iframe_NULL_SRC && !isChatRoomURL && typeof kagi === 'undefined' && (() => {
  7098.  
  7099. const emptyBlobUrl = URL.createObjectURL(new Blob([], { type: 'text/html' }));
  7100. const lcOpt = { sensitivity: 'base' };
  7101. document.createElement24 = document.createElement;
  7102. document.createElement = function (t) {
  7103. if (typeof t === 'string' && t.length === 6) {
  7104. if (t.localeCompare('iframe', undefined, lcOpt) === 0) {
  7105. const p = this.createElement24(t);
  7106. try {
  7107. const stack = new Error().stack;
  7108. const isSearchbox = stack.includes('initializeSearchbox'); // see https://greasyfork.org/scripts/473972-youtube-js-engine-tamer/discussions/217084
  7109. if (!isSearchbox) {
  7110. p.src = emptyBlobUrl; // avoid iframe is appended to DOM without any url
  7111. }
  7112. } catch (e) { }
  7113. return p;
  7114. }
  7115. }
  7116. return this.createElement24.apply(this, arguments);
  7117. };
  7118.  
  7119. })();
  7120.  
  7121. ; fix_error_many_stack_state === 1 && (() => {
  7122.  
  7123.  
  7124. let p1 = winError00;
  7125.  
  7126. let stackNeedleDetails = null;
  7127.  
  7128. Object.defineProperty(Object.prototype, 'matchAll', {
  7129. get() {
  7130. stackNeedleDetails = this;
  7131. return true;
  7132. },
  7133. enumerable: true,
  7134. configurable: true
  7135. });
  7136.  
  7137. try {
  7138. JSON.parse("{}");
  7139. } catch (e) {
  7140. console.warn(e)
  7141. fix_error_many_stack_state = 0;
  7142. }
  7143.  
  7144. delete Object.prototype['matchAll'];
  7145.  
  7146. let p2 = window.onerror;
  7147.  
  7148. window.onerror = p1;
  7149.  
  7150. if (fix_error_many_stack_state === 0) return;
  7151.  
  7152. if (stackNeedleDetails) {
  7153. JSON.parse.stackNeedleDetails = stackNeedleDetails;
  7154. stackNeedleDetails.matchAll = true;
  7155. }
  7156.  
  7157. if (p1 === p2) return (fix_error_many_stack_state = 0);
  7158.  
  7159. // p1!==p2
  7160. fix_error_many_stack_state = !stackNeedleDetails ? 4 : 3;
  7161.  
  7162. })();
  7163.  
  7164. ; fix_error_many_stack_state === 2 && (() => {
  7165.  
  7166.  
  7167. let p1 = winError00;
  7168.  
  7169. let objectPrune = null;
  7170. let stackNeedleDetails = null;
  7171.  
  7172. Object.defineProperty(Function.prototype, 'findOwner', {
  7173. get() {
  7174. objectPrune = this;
  7175. return this._findOwner;
  7176. },
  7177. set(nv) {
  7178. this._findOwner = nv;
  7179. return true;
  7180. },
  7181. enumerable: true,
  7182. configurable: true
  7183. });
  7184.  
  7185. Object.defineProperty(Object.prototype, 'matchAll', {
  7186. get() {
  7187. stackNeedleDetails = this;
  7188. return true;
  7189. },
  7190. enumerable: true,
  7191. configurable: true
  7192. });
  7193.  
  7194. try {
  7195. JSON.parse("{}");
  7196. } catch (e) {
  7197. console.warn(e)
  7198. fix_error_many_stack_state = 0;
  7199. }
  7200.  
  7201. delete Function.prototype['findOwner'];
  7202. delete Object.prototype['matchAll'];
  7203.  
  7204. let p2 = window.onerror;
  7205.  
  7206. if (p1 !== p2) return (fix_error_many_stack_state = 4); // p1 != p2
  7207.  
  7208. if (fix_error_many_stack_state == 0) return;
  7209.  
  7210. // the following will only execute when Brave's scriptlets.js is executed.
  7211.  
  7212. prepareLogs.push("fix_error_many_stack_state NB")
  7213.  
  7214. if (stackNeedleDetails) {
  7215. stackNeedleDetails.pattern = null;
  7216. stackNeedleDetails.re = null;
  7217. stackNeedleDetails.expect = null;
  7218. stackNeedleDetails.matchAll = true;
  7219. }
  7220.  
  7221. if (objectPrune) {
  7222. objectPrune.findOwner = objectPrune.mustProcess = objectPrune.logJson = () => { }
  7223. delete objectPrune._findOwner;
  7224. }
  7225.  
  7226. fix_error_many_stack_state = 3;
  7227. JSON.parse.stackNeedleDetails = stackNeedleDetails;
  7228. JSON.parse.objectPrune = objectPrune;
  7229.  
  7230. })();
  7231.  
  7232. ; fix_error_many_stack_state === 3 && (() => {
  7233.  
  7234.  
  7235. let p1 = winError00;
  7236.  
  7237. try {
  7238. JSON.parse("{}");
  7239. } catch (e) {
  7240. console.warn(e)
  7241. fix_error_many_stack_state = 0;
  7242. }
  7243.  
  7244. let p2 = window.onerror;
  7245.  
  7246. if (p1 === p2) return;
  7247.  
  7248. window.onerror = p1;
  7249.  
  7250. if (fix_error_many_stack_state === 0) return;
  7251.  
  7252. fix_error_many_stack_state = 4; // p1 != p2
  7253.  
  7254.  
  7255. })();
  7256.  
  7257. fix_error_many_stack_state === 4 && (() => {
  7258.  
  7259. // the following will only execute when Brave's scriptlets.js is executed.
  7260.  
  7261. prepareLogs.push("fix_error_many_stack_state AB")
  7262.  
  7263. JSON.parseProxy = JSON.parse;
  7264.  
  7265. JSON.parse = ((parse) => {
  7266.  
  7267. parse = parse.bind(JSON); // get a new instance of the current JSON.parse
  7268. return function (text, reviver) {
  7269. const onerror = window.onerror;
  7270. window.onerror = null;
  7271. let r;
  7272. try {
  7273. r = parse(...arguments);
  7274. } catch (e) {
  7275. r = e;
  7276. }
  7277. window.onerror = onerror;
  7278. if (r instanceof Error) {
  7279. throw r;
  7280. }
  7281. return r;
  7282. }
  7283.  
  7284. })(JSON.parse);
  7285.  
  7286.  
  7287. })();
  7288.  
  7289.  
  7290. // << if FIX_yt_player >>
  7291.  
  7292. // credit to @nopeless (https://greasyfork.org/scripts/471489-youtube-player-perf/)
  7293. const PERF_471489_ = true;
  7294. // PERF_471489_ is not exactly the same to Youtube Player perf v0.7
  7295. // This script uses a much gentle way to tamer the JS engine instead.
  7296.  
  7297. // << end >>
  7298.  
  7299. const steppingScaleN = 200; // transform: scaleX(k/N); 0<k<N
  7300.  
  7301.  
  7302.  
  7303. const nilFn = () => { };
  7304.  
  7305. let isMainWindow = false;
  7306. try {
  7307. isMainWindow = window.document === window.top.document
  7308. } catch (e) { }
  7309.  
  7310. let NO_PRELOAD_GENERATE_204_BYPASS = NO_PRELOAD_GENERATE_204 ? false : true;
  7311. let headLinkCollection = null;
  7312.  
  7313.  
  7314. // const assertor = (f) => f() || console.assert(false, `${f}`);
  7315.  
  7316. const fnIntegrity = (f, d) => {
  7317. if (!f || typeof f !== 'function') {
  7318. console.warn('f is not a function', f);
  7319. return;
  7320. }
  7321. let p = `${f}`, s = 0, j = -1, w = 0;
  7322. for (let i = 0, l = p.length; i < l; i++) {
  7323. const t = p[i];
  7324. if (((t >= 'a' && t <= 'z') || (t >= 'A' && t <= 'Z'))) {
  7325. if (j < i - 1) w++;
  7326. j = i;
  7327. } else {
  7328. s++;
  7329. }
  7330. }
  7331. let itz = `${f.length}.${s}.${w}`;
  7332. if (!d) {
  7333. return itz;
  7334. } else {
  7335. return itz === d;
  7336. }
  7337. };
  7338.  
  7339. const getZqOu = (_yt_player) => {
  7340.  
  7341. const w = 'ZqOu';
  7342.  
  7343. let arr = [];
  7344.  
  7345. for (const [k, v] of Object.entries(_yt_player)) {
  7346.  
  7347. const p = typeof v === 'function' ? v.prototype : 0;
  7348. if (p
  7349. && typeof p.start === 'function' && p.start.length === 0 // Ou
  7350. && typeof p.isActive === 'function' && p.isActive.length === 0
  7351. && typeof p.stop === 'function' && p.stop.length === 0
  7352. && !p.isComplete && !p.getStatus && !p.getResponseHeader && !p.getLastError
  7353. && !p.send && !p.abort
  7354. && !p.sample && !p.initialize && !p.fail && !p.getName
  7355. // && !p.dispose && !p.isDisposed
  7356.  
  7357. ) {
  7358. arr = addProtoToArr(_yt_player, k, arr) || arr;
  7359.  
  7360.  
  7361. }
  7362.  
  7363. }
  7364.  
  7365. if (arr.length === 0) {
  7366.  
  7367. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  7368. } else {
  7369.  
  7370. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  7371. return arr[0];
  7372. }
  7373.  
  7374. }
  7375.  
  7376. const getZqQu = (_yt_player) => {
  7377.  
  7378. const w = 'ZqQu';
  7379.  
  7380. let arr = [];
  7381.  
  7382.  
  7383. for (const [k, v] of Object.entries(_yt_player)) {
  7384.  
  7385. const p = typeof v === 'function' ? v.prototype : 0;
  7386. if (p
  7387. && typeof p.start === 'function' && p.start.length === 1 // Qu
  7388. && typeof p.isActive === 'function' && p.isActive.length === 0
  7389. && typeof p.stop === 'function' && p.stop.length === 0
  7390. && !p.isComplete && !p.getStatus && !p.getResponseHeader && !p.getLastError
  7391. && !p.send && !p.abort
  7392. && !p.sample && !p.initialize && !p.fail && !p.getName
  7393. // && !p.dispose && !p.isDisposed
  7394.  
  7395. ) {
  7396. arr = addProtoToArr(_yt_player, k, arr) || arr;
  7397.  
  7398.  
  7399. }
  7400.  
  7401. }
  7402.  
  7403. if (arr.length === 0) {
  7404.  
  7405. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  7406. } else {
  7407.  
  7408. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  7409. return arr[0];
  7410. }
  7411.  
  7412. }
  7413.  
  7414.  
  7415. const getVG = (_yt_player) => {
  7416. const w = 'VG';
  7417.  
  7418. let arr = [];
  7419.  
  7420. for (const [k, v] of Object.entries(_yt_player)) {
  7421.  
  7422. const p = typeof v === 'function' ? v.prototype : 0;
  7423. if (p
  7424. && typeof p.show === 'function' && p.show.length === 1
  7425. && typeof p.hide === 'function' && p.hide.length === 0
  7426. && typeof p.stop === 'function' && p.stop.length === 0) {
  7427.  
  7428. arr = addProtoToArr(_yt_player, k, arr) || arr;
  7429.  
  7430. }
  7431.  
  7432. }
  7433.  
  7434.  
  7435. if (arr.length === 0) {
  7436.  
  7437. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  7438. } else {
  7439.  
  7440. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  7441. return arr[0];
  7442. }
  7443.  
  7444.  
  7445.  
  7446. }
  7447.  
  7448.  
  7449. const getzo = (_yt_player) => {
  7450. const w = 'zo';
  7451.  
  7452. let arr = [];
  7453.  
  7454. for (const [k, v] of Object.entries(_yt_player)) {
  7455.  
  7456. if (
  7457. typeof v === 'function' && v.length === 3 && k.length < 3
  7458. ) {
  7459. const vt = `${v}`;
  7460. if (vt.length >= 21 && vt.includes(".style[")) {
  7461. if (/\((\w{1,3}),(\w{1,3}),(\w{1,3})\)\{[\s\S]*\1\.style\[\2\]=\3\W/.test(vt)) {
  7462. arr.push(k);
  7463. } else {
  7464. console.warn('[yt-js-engine-tamer] unexpected zo::vt', vt);
  7465. }
  7466. }
  7467. }
  7468.  
  7469. }
  7470.  
  7471. if (arr.length === 0) {
  7472.  
  7473. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  7474. } else {
  7475.  
  7476. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  7477. return arr[0];
  7478. }
  7479.  
  7480. }
  7481.  
  7482. const addProtoToArr = (parent, key, arr) => {
  7483.  
  7484.  
  7485. let isChildProto = false;
  7486. for (const sr of arr) {
  7487. if (parent[key].prototype instanceof parent[sr]) {
  7488. isChildProto = true;
  7489. break;
  7490. }
  7491. }
  7492.  
  7493. if (isChildProto) return;
  7494.  
  7495. arr = arr.filter(sr => {
  7496. if (parent[sr].prototype instanceof parent[key]) {
  7497. return false;
  7498. }
  7499. return true;
  7500. });
  7501.  
  7502. arr.push(key);
  7503.  
  7504. return arr;
  7505.  
  7506.  
  7507. }
  7508.  
  7509. const getuG = (_yt_player) => {
  7510.  
  7511. const w = 'uG';
  7512.  
  7513. let arr = [];
  7514.  
  7515. for (const [k, v] of Object.entries(_yt_player)) {
  7516.  
  7517.  
  7518. const p = typeof v === 'function' ? v.prototype : 0;
  7519.  
  7520. if (p
  7521. && typeof p.createElement === 'function' && p.createElement.length === 2
  7522. && typeof p.detach === 'function' && p.detach.length === 0
  7523. && typeof p.update === 'function' && p.update.length === 1
  7524. && typeof p.updateValue === 'function' && p.updateValue.length === 2
  7525. ) {
  7526.  
  7527. arr = addProtoToArr(_yt_player, k, arr) || arr;
  7528.  
  7529. }
  7530.  
  7531. }
  7532.  
  7533.  
  7534.  
  7535.  
  7536.  
  7537. if (arr.length === 0) {
  7538.  
  7539. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  7540. } else {
  7541.  
  7542. console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  7543. return arr[0];
  7544. }
  7545.  
  7546. }
  7547.  
  7548.  
  7549. const getQT = (_yt_player) => {
  7550. const w = 'QT';
  7551.  
  7552. let arr = [];
  7553. let brr = new Map();
  7554.  
  7555. for (const [k, v] of Object.entries(_yt_player)) {
  7556.  
  7557. const p = typeof v === 'function' ? v.prototype : 0;
  7558. if (p) {
  7559. let q = 0;
  7560. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 7) q += 400;
  7561. else if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 8) q += 300;
  7562. else if (typeof p.handleGlobalKeyUp === 'function') q += 200;
  7563.  
  7564. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 0) q -= 600; // avoid SV
  7565.  
  7566. if (q < 200) continue; // p.handleGlobalKeyUp must be available
  7567.  
  7568. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 8) q += 80;
  7569. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 7) q += 30;
  7570. if (typeof p.step === 'function' && p.step.length === 1) q += 10;
  7571. if (typeof p.step === 'function' && p.step.length !== 1) q += 5;
  7572.  
  7573.  
  7574. // differentiate QT and DX
  7575.  
  7576. q += 280;
  7577. if (typeof p.cueVideoByPlayerVars === 'function') q += 4;
  7578. if (typeof p.loadVideoByPlayerVars === 'function') q += 4;
  7579. if (typeof p.preloadVideoByPlayerVars === 'function') q += 4;
  7580. if (typeof p.seekBy === 'function') q += 4;
  7581. if (typeof p.seekTo === 'function') q += 4;
  7582. if (typeof p.getStoryboardFormat === 'function') q += 4;
  7583. if (typeof p.getDuration === 'function') q += 4;
  7584. if (typeof p.loadModule === 'function') q += 4;
  7585. if (typeof p.unloadModule === 'function') q += 4;
  7586. if (typeof p.getOption === 'function') q += 4;
  7587. if (typeof p.getOptions === 'function') q += 4;
  7588. if (typeof p.setOption === 'function') q += 4;
  7589. if (typeof p.addCueRange === 'function') q += 4;
  7590. if (typeof p.getDebugText === 'function') q += 4;
  7591. if (typeof p.getCurrentBroadcastId === 'function') q += 4;
  7592. if (typeof p.setSizeStyle === 'function') q += 4;
  7593. if (typeof p.showControls === 'function') q += 4;
  7594. if (typeof p.hideControls === 'function') q += 4;
  7595. if (typeof p.getVideoContentRect === 'function') q += 4;
  7596. if (typeof p.toggleFullscreen === 'function') q += 4;
  7597. if (typeof p.isFullscreen === 'function') q += 4;
  7598. if (typeof p.cancelPlayback === 'function') q += 4;
  7599. if (typeof p.getProgressState === 'function') q += 4;
  7600. if (typeof p.isInline === 'function') q += 4;
  7601. if (typeof p.setInline === 'function') q += 4;
  7602. if (typeof p.toggleSubtitles === 'function') q += 4;
  7603. if (typeof p.getPlayerSize === 'function') q += 4;
  7604. if (typeof p.wakeUpControls === 'function') q += 4;
  7605. if (typeof p.setCenterCrop === 'function') q += 4;
  7606. if (typeof p.getLoopVideo === 'function') q += 4;
  7607. if (typeof p.setLoopVideo === 'function') q += 4;
  7608.  
  7609.  
  7610. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  7611.  
  7612. if (q > 0) brr.set(k, q);
  7613.  
  7614. }
  7615.  
  7616. }
  7617.  
  7618. if (arr.length === 0) {
  7619.  
  7620. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  7621. } else {
  7622.  
  7623. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  7624.  
  7625. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  7626.  
  7627. if (arr.length > 2) console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  7628. return arr[0][0];
  7629. }
  7630.  
  7631.  
  7632.  
  7633. }
  7634.  
  7635.  
  7636.  
  7637. const getSV = (_yt_player) => {
  7638. const w = 'SV';
  7639.  
  7640. let arr = [];
  7641. let brr = new Map();
  7642.  
  7643. for (const [k, v] of Object.entries(_yt_player)) {
  7644.  
  7645. const p = typeof v === 'function' ? v.prototype : 0;
  7646. if (p) {
  7647. let q = 0;
  7648. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 7) q += 400;
  7649. else if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 8) q += 300;
  7650. else if (typeof p.handleGlobalKeyUp === 'function') q += 200;
  7651.  
  7652. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 0) q += 600; // SV
  7653.  
  7654. if (q < 200) continue; // p.handleGlobalKeyUp must be available
  7655.  
  7656. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 8) q += 80;
  7657. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 7) q += 30;
  7658. if (typeof p.step === 'function' && p.step.length === 1) q += 10;
  7659. if (typeof p.step === 'function' && p.step.length !== 1) q += 5;
  7660.  
  7661.  
  7662. // differentiate QT and DX
  7663.  
  7664.  
  7665. q += 280;
  7666.  
  7667. if (typeof p.cueVideoByPlayerVars === 'function') q -= 4;
  7668. if (typeof p.loadVideoByPlayerVars === 'function') q -= 4;
  7669. if (typeof p.preloadVideoByPlayerVars === 'function') q -= 4;
  7670. if (typeof p.seekBy === 'function') q -= 4;
  7671. if (typeof p.seekTo === 'function') q -= 4;
  7672. if (typeof p.getStoryboardFormat === 'function') q -= 4;
  7673. if (typeof p.getDuration === 'function') q -= 4;
  7674. if (typeof p.loadModule === 'function') q -= 4;
  7675. if (typeof p.unloadModule === 'function') q -= 4;
  7676. if (typeof p.getOption === 'function') q -= 4;
  7677. if (typeof p.getOptions === 'function') q -= 4;
  7678. if (typeof p.setOption === 'function') q -= 4;
  7679. if (typeof p.addCueRange === 'function') q -= 4;
  7680. if (typeof p.getDebugText === 'function') q -= 4;
  7681. if (typeof p.getCurrentBroadcastId === 'function') q -= 4;
  7682. if (typeof p.setSizeStyle === 'function') q -= 4;
  7683. if (typeof p.showControls === 'function') q -= 4;
  7684. if (typeof p.hideControls === 'function') q -= 4;
  7685. if (typeof p.getVideoContentRect === 'function') q -= 4;
  7686. if (typeof p.toggleFullscreen === 'function') q -= 4;
  7687. if (typeof p.isFullscreen === 'function') q -= 4;
  7688. if (typeof p.cancelPlayback === 'function') q -= 4;
  7689. if (typeof p.getProgressState === 'function') q -= 4;
  7690. if (typeof p.isInline === 'function') q -= 4;
  7691. if (typeof p.setInline === 'function') q -= 4;
  7692. if (typeof p.toggleSubtitles === 'function') q -= 4;
  7693. if (typeof p.getPlayerSize === 'function') q -= 4;
  7694. if (typeof p.wakeUpControls === 'function') q -= 4;
  7695. if (typeof p.setCenterCrop === 'function') q -= 4;
  7696. if (typeof p.getLoopVideo === 'function') q -= 4;
  7697. if (typeof p.setLoopVideo === 'function') q -= 4;
  7698.  
  7699.  
  7700. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  7701.  
  7702. if (q > 0) brr.set(k, q);
  7703.  
  7704. }
  7705.  
  7706. }
  7707.  
  7708. if (arr.length === 0) {
  7709.  
  7710. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  7711. } else {
  7712.  
  7713. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  7714.  
  7715. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  7716.  
  7717. if (arr.length > 2) console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  7718. return arr[0][0];
  7719. }
  7720.  
  7721.  
  7722.  
  7723. }
  7724.  
  7725.  
  7726.  
  7727.  
  7728. const getDX = (_yt_player) => {
  7729. const w = 'DX';
  7730.  
  7731. let arr = [];
  7732. let brr = new Map();
  7733.  
  7734. for (const [k, v] of Object.entries(_yt_player)) {
  7735.  
  7736. const p = typeof v === 'function' ? v.prototype : 0;
  7737. if (p) {
  7738. let q = 0;
  7739. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 7) q += 400;
  7740. else if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 8) q += 300;
  7741. else if (typeof p.handleGlobalKeyUp === 'function') q += 200;
  7742.  
  7743. if (typeof p.handleGlobalKeyUp === 'function' && p.handleGlobalKeyUp.length === 0) q -= 600; // avoid SV
  7744.  
  7745.  
  7746. if (!(typeof p.init === 'function' && p.init.length === 0)) q -= 300; // init is required
  7747.  
  7748. if (q < 200) continue; // p.handleGlobalKeyUp must be available
  7749.  
  7750. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 8) q += 80;
  7751. if (typeof p.handleGlobalKeyDown === 'function' && p.handleGlobalKeyDown.length === 7) q += 30;
  7752. if (typeof p.step === 'function' && p.step.length === 1) q += 10;
  7753. if (typeof p.step === 'function' && p.step.length !== 1) q += 5;
  7754.  
  7755.  
  7756. // differentiate QT and DX
  7757.  
  7758.  
  7759. q += 280;
  7760.  
  7761. if (typeof p.cueVideoByPlayerVars === 'function') q -= 4;
  7762. if (typeof p.loadVideoByPlayerVars === 'function') q -= 4;
  7763. if (typeof p.preloadVideoByPlayerVars === 'function') q -= 4;
  7764. if (typeof p.seekBy === 'function') q -= 4;
  7765. if (typeof p.seekTo === 'function') q -= 4;
  7766. if (typeof p.getStoryboardFormat === 'function') q -= 4;
  7767. if (typeof p.getDuration === 'function') q -= 4;
  7768. if (typeof p.loadModule === 'function') q -= 4;
  7769. if (typeof p.unloadModule === 'function') q -= 4;
  7770. if (typeof p.getOption === 'function') q -= 4;
  7771. if (typeof p.getOptions === 'function') q -= 4;
  7772. if (typeof p.setOption === 'function') q -= 4;
  7773. if (typeof p.addCueRange === 'function') q -= 4;
  7774. if (typeof p.getDebugText === 'function') q -= 4;
  7775. if (typeof p.getCurrentBroadcastId === 'function') q -= 4;
  7776. if (typeof p.setSizeStyle === 'function') q -= 4;
  7777. if (typeof p.showControls === 'function') q -= 4;
  7778. if (typeof p.hideControls === 'function') q -= 4;
  7779. if (typeof p.getVideoContentRect === 'function') q -= 4;
  7780. if (typeof p.toggleFullscreen === 'function') q -= 4;
  7781. if (typeof p.isFullscreen === 'function') q -= 4;
  7782. if (typeof p.cancelPlayback === 'function') q -= 4;
  7783. if (typeof p.getProgressState === 'function') q -= 4;
  7784. if (typeof p.isInline === 'function') q -= 4;
  7785. if (typeof p.setInline === 'function') q -= 4;
  7786. if (typeof p.toggleSubtitles === 'function') q -= 4;
  7787. if (typeof p.getPlayerSize === 'function') q -= 4;
  7788. if (typeof p.wakeUpControls === 'function') q -= 4;
  7789. if (typeof p.setCenterCrop === 'function') q -= 4;
  7790. if (typeof p.getLoopVideo === 'function') q -= 4;
  7791. if (typeof p.setLoopVideo === 'function') q -= 4;
  7792.  
  7793.  
  7794. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  7795.  
  7796. if (q > 0) brr.set(k, q);
  7797.  
  7798. }
  7799.  
  7800. }
  7801.  
  7802. if (arr.length === 0) {
  7803.  
  7804. console.warn(`[yt-js-engine-tamer] (key-extraction) Key does not exist. [${w}]`);
  7805. } else {
  7806.  
  7807. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  7808.  
  7809. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  7810.  
  7811. if (arr.length > 2) console.log(`[yt-js-engine-tamer] (key-extraction) [${w}]`, arr);
  7812. return arr[0][0];
  7813. }
  7814.  
  7815.  
  7816.  
  7817. }
  7818.  
  7819.  
  7820.  
  7821. const isPrepareCachedV = (FIX_avoid_incorrect_video_meta ? true : false) && (window === top);
  7822.  
  7823. let pageSetupVideoId = null; // set at finish; '' for indeterminate state
  7824. let pageSetupState = 0;
  7825.  
  7826. isPrepareCachedV && (() => {
  7827.  
  7828. pageSetupVideoId = '';
  7829. const clearCachedV = () => {
  7830. pageSetupVideoId = '';
  7831. pageSetupState = 0;
  7832. }
  7833. document.addEventListener('yt-navigate-start', clearCachedV, false); // user action
  7834. document.addEventListener('yt-navigate-cache', clearCachedV, false); // pop state
  7835. document.addEventListener('yt-page-data-fetched', clearCachedV, false); // still consider invalid until url is ready in yt-navigate-finish
  7836. document.addEventListener('yt-navigate-finish', () => {
  7837. pageSetupState = 1;
  7838. try {
  7839. const url = new URL(location.href);
  7840. if (!url || !isWatchPageURL(url)) {
  7841. pageSetupVideoId = '';
  7842. } else {
  7843. pageSetupVideoId = url.searchParams.get('v') || '';
  7844. }
  7845. } catch (e) {
  7846. pageSetupVideoId = '';
  7847. }
  7848. }, false);
  7849.  
  7850. })();
  7851.  
  7852. let videoPlayingY = null;
  7853.  
  7854. isPrepareCachedV && (() => {
  7855.  
  7856. let getNext = true;
  7857. let videoPlayingX = {
  7858. get videoId() {
  7859. if (getNext) {
  7860. getNext = false;
  7861.  
  7862. let elements = document.querySelectorAll('ytd-watch-flexy[video-id]');
  7863. const arr = [];
  7864. for (const element of elements) {
  7865. if (!element.closest('[hidden]')) arr.push(element);
  7866. }
  7867. if (arr.length !== 1) this.__videoId__ = '';
  7868. else {
  7869. this.__videoId__ = arr[0].getAttribute('video-id');
  7870. }
  7871.  
  7872. }
  7873. return this.__videoId__ || '';
  7874. }
  7875. }
  7876.  
  7877. videoPlayingY = videoPlayingX;
  7878. const handler = (evt) => {
  7879. const target = (evt || 0).target;
  7880. if (target instanceof HTMLVideoElement) {
  7881. getNext = true;
  7882. }
  7883. }
  7884. document.addEventListener('loadedmetadata', handler, true);
  7885. document.addEventListener('durationchange', handler, true);
  7886.  
  7887. })();
  7888.  
  7889.  
  7890.  
  7891. const cleanContext = async (win) => {
  7892. const waitFn = requestAnimationFrame; // shall have been binded to window
  7893. try {
  7894. let mx = 16; // MAX TRIAL
  7895. const frameId = 'vanillajs-iframe-v1';
  7896. /** @type {HTMLIFrameElement | null} */
  7897. let frame = document.getElementById(frameId);
  7898. let removeIframeFn = null;
  7899. if (!frame) {
  7900. frame = document.createElement('iframe');
  7901. frame.id = frameId;
  7902. const blobURL = typeof webkitCancelAnimationFrame === 'function' && typeof kagi === 'undefined' ? (frame.src = URL.createObjectURL(new Blob([], { type: 'text/html' }))) : null; // avoid Brave Crash
  7903. frame.sandbox = 'allow-same-origin'; // script cannot be run inside iframe but API can be obtained from iframe
  7904. let n = document.createElement('noscript'); // wrap into NOSCRPIT to avoid reflow (layouting)
  7905. n.appendChild(frame);
  7906. while (!document.documentElement && mx-- > 0) await new Promise(waitFn); // requestAnimationFrame here could get modified by YouTube engine
  7907. const root = document.documentElement;
  7908. root.appendChild(n); // throw error if root is null due to exceeding MAX TRIAL
  7909. if (blobURL) Promise.resolve().then(() => URL.revokeObjectURL(blobURL));
  7910.  
  7911. removeIframeFn = (setTimeout) => {
  7912. const removeIframeOnDocumentReady = (e) => {
  7913. e && win.removeEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  7914. e = n;
  7915. n = win = removeIframeFn = 0;
  7916. setTimeout ? setTimeout(() => e.remove(), 200) : e.remove();
  7917. }
  7918. if (!setTimeout || document.readyState !== 'loading') {
  7919. removeIframeOnDocumentReady();
  7920. } else {
  7921. win.addEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  7922. }
  7923. }
  7924. }
  7925. while (!frame.contentWindow && mx-- > 0) await new Promise(waitFn);
  7926. const fc = frame.contentWindow;
  7927. if (!fc) throw "window is not found."; // throw error if root is null due to exceeding MAX TRIAL
  7928. try {
  7929. const { requestAnimationFrame, setTimeout, clearTimeout, cancelAnimationFrame, setInterval, clearInterval, requestIdleCallback, getComputedStyle } = fc;
  7930. const res = { requestAnimationFrame, setTimeout, clearTimeout, cancelAnimationFrame, setInterval, clearInterval, requestIdleCallback, getComputedStyle };
  7931. for (let k in res) res[k] = res[k].bind(win); // necessary
  7932. if (removeIframeFn) Promise.resolve(res.setTimeout).then(removeIframeFn);
  7933. res.animate = fc.HTMLElement.prototype.animate;
  7934. res.perfNow = fc.performance.now;
  7935. return res;
  7936. } catch (e) {
  7937. if (removeIframeFn) removeIframeFn();
  7938. return null;
  7939. }
  7940. } catch (e) {
  7941. console.warn(e);
  7942. return null;
  7943. }
  7944. };
  7945.  
  7946. const promiseForYtActionCalled = new Promise(resolve => {
  7947.  
  7948. const appTag = isChatRoomURL ? 'yt-live-chat-app' : 'ytd-app';
  7949. if (typeof AbortSignal !== 'undefined') {
  7950. let hn = () => {
  7951. if (!hn) return;
  7952. hn = null;
  7953. resolve(document.querySelector(appTag));
  7954. };
  7955. document.addEventListener('yt-action', hn, { capture: true, passive: true, once: true });
  7956. } else {
  7957. let hn = () => {
  7958. if (!hn) return;
  7959. document.removeEventListener('yt-action', hn, true);
  7960. hn = null;
  7961. resolve(document.querySelector(appTag));
  7962. };
  7963. document.addEventListener('yt-action', hn, true);
  7964. }
  7965. });
  7966.  
  7967. cleanContext(window).then(__CONTEXT__ => {
  7968. if (!__CONTEXT__) return null;
  7969.  
  7970. const { requestAnimationFrame, setTimeout, clearTimeout, cancelAnimationFrame, setInterval, clearInterval, animate, requestIdleCallback, getComputedStyle, perfNow } = __CONTEXT__;
  7971.  
  7972.  
  7973. performance.now17 = perfNow.bind(performance);
  7974.  
  7975.  
  7976.  
  7977. __requestAnimationFrame__ = requestAnimationFrame;
  7978.  
  7979.  
  7980. const isGPUAccelerationAvailable = (() => {
  7981. // https://gist.github.com/cvan/042b2448fcecefafbb6a91469484cdf8
  7982. try {
  7983. const canvas = document.createElement('canvas');
  7984. return !!(canvas.getContext('webgl') || canvas.getContext('experimental-webgl'));
  7985. } catch (e) {
  7986. return false;
  7987. }
  7988. })();
  7989.  
  7990. const foregroundPromiseFn_noGPU = (() => {
  7991.  
  7992. if (isGPUAccelerationAvailable) return null;
  7993.  
  7994. const pd = Object.getOwnPropertyDescriptor(Document.prototype, 'visibilityState');
  7995. if (!pd || typeof pd.get !== 'function') return null;
  7996. const pdGet = pd.get;
  7997.  
  7998. let pr = null;
  7999.  
  8000. let hState = pdGet.call(document) === 'hidden';
  8001. // let cid = 0;
  8002. pureAddEventListener.call(document, 'visibilitychange', (evt) => {
  8003. const newHState = pdGet.call(document) === 'hidden';
  8004. if (hState !== newHState) {
  8005. // if (cid > 0) cid = clearInterval(cid);
  8006. hState = newHState;
  8007. if (!hState && pr) pr = pr.resolve();
  8008. }
  8009. });
  8010.  
  8011. // cid = setInterval(() => {
  8012. // const newHState = document.visibilityState === 'hidden';
  8013. // if (hState !== newHState) {
  8014. // hState = newHState;
  8015. // if (!hState && pr) pr = pr.resolve();
  8016. // }
  8017. // }, 100);
  8018.  
  8019.  
  8020. return (() => {
  8021. if (pr) return pr;
  8022. const w = ((!hState && setTimeout(() => {
  8023. if (!hState && pr === w) pr = pr.resolve();
  8024. })), (pr = new PromiseExternal()));
  8025. return w;
  8026. });
  8027.  
  8028. })();
  8029.  
  8030.  
  8031. let rafPromise = null;
  8032. const getRafPromise = () => rafPromise || (rafPromise = new Promise(resolve => {
  8033. requestAnimationFrame(hRes => {
  8034. rafPromise = null;
  8035. resolve(hRes);
  8036. });
  8037. }));
  8038.  
  8039. const foregroundPromiseFn = foregroundPromiseFn_noGPU || getRafPromise;
  8040.  
  8041.  
  8042. const wmComputedStyle = new WeakMap();
  8043.  
  8044. if (!window.__native__getComputedStyle__ && !window.__jst__getComputedStyle__ && typeof window.getComputedStyle === 'function' && window.getComputedStyle.length === 1) {
  8045. window.__native__getComputedStyle__ = getComputedStyle;
  8046. if (ENABLE_COMPUTEDSTYLE_CACHE) {
  8047. window.__original__getComputedStyle__ = window.getComputedStyle;
  8048. window.getComputedStyle = function (elem) {
  8049. if (!(elem instanceof Element) || (arguments.length === 2 && arguments[1]) || (arguments.length > 2)) {
  8050. return window.__original__getComputedStyle__(...arguments);
  8051. }
  8052. let cs = wmComputedStyle.get(elem);
  8053. if (!cs) {
  8054. cs = window.__native__getComputedStyle__(elem);
  8055. wmComputedStyle.set(elem, cs);
  8056. }
  8057. return cs;
  8058. };
  8059. } else {
  8060. window.__original__getComputedStyle__ = null;
  8061. }
  8062. window.__jst__getComputedStyle__ = window.getComputedStyle;
  8063. }
  8064.  
  8065. NO_SCHEDULING_DUE_TO_COMPUTEDSTYLE && promiseForYtActionCalled.then(() => {
  8066. if (typeof window.__jst__getComputedStyle__ === 'function' && window.__jst__getComputedStyle__.length === 1 && window.__jst__getComputedStyle__ !== window.getComputedStyle) {
  8067. window.getComputedStyle = window.__jst__getComputedStyle__;
  8068. }
  8069. });
  8070.  
  8071. const isUrlInEmbed = location.href.includes('.youtube.com/embed/');
  8072. const isAbortSignalSupported = typeof AbortSignal !== "undefined";
  8073.  
  8074. const promiseForTamerTimeout = new Promise(resolve => {
  8075. !isUrlInEmbed && isAbortSignalSupported && document.addEventListener('yt-action', function () {
  8076. setTimeout(resolve, 480);
  8077. }, { capture: true, passive: true, once: true });
  8078. !isUrlInEmbed && isAbortSignalSupported && typeof customElements === "object" && whenCEDefined('ytd-app').then(() => {
  8079. setTimeout(resolve, 1200);
  8080. });
  8081. setTimeout(resolve, 3000);
  8082. });
  8083.  
  8084. const promiseForPageInitied = new Promise(resolve => {
  8085. !isUrlInEmbed && isAbortSignalSupported && document.addEventListener('yt-action', function () {
  8086. setTimeout(resolve, 450);
  8087. }, { capture: true, passive: true, once: true });
  8088. !isUrlInEmbed && isAbortSignalSupported && typeof customElements === "object" && whenCEDefined('ytd-app').then(() => {
  8089. setTimeout(resolve, 900);
  8090. });
  8091. setTimeout(resolve, 1800);
  8092. });
  8093.  
  8094. NO_PRELOAD_GENERATE_204_BYPASS || promiseForPageInitied.then(() => {
  8095. NO_PRELOAD_GENERATE_204_BYPASS = true;
  8096. headLinkCollection = null;
  8097. });
  8098.  
  8099.  
  8100. NATIVE_CANVAS_ANIMATION && (() => {
  8101.  
  8102. observablePromise(() => {
  8103. HTMLCanvasElement.prototype.animate = animate;
  8104. }, promiseForTamerTimeout).obtain();
  8105.  
  8106. })();
  8107.  
  8108.  
  8109.  
  8110.  
  8111. FIX_ytAction_ && (async () => {
  8112.  
  8113. const appTag = isChatRoomURL ? 'yt-live-chat-app' : 'ytd-app';
  8114.  
  8115. const ytdApp = await new Promise(resolve => {
  8116.  
  8117. whenCEDefined(appTag).then(() => {
  8118. const ytdApp = document.querySelector(appTag);
  8119. if (ytdApp) {
  8120. resolve(ytdApp);
  8121. return;
  8122. }
  8123. let mo = new MutationObserver(() => {
  8124. const ytdApp = document.querySelector(appTag);
  8125. if (!ytdApp) return;
  8126. if (mo) {
  8127. mo.disconnect();
  8128. mo.takeRecords();
  8129. mo = null;
  8130. }
  8131. resolve(ytdApp);
  8132. });
  8133. mo.observe(document, { subtree: true, childList: true });
  8134. });
  8135.  
  8136. });
  8137.  
  8138. if (!ytdApp) return;
  8139. const cProto = insp(ytdApp).constructor.prototype;
  8140.  
  8141. if (!cProto) return;
  8142. let mbd = 0;
  8143.  
  8144. const fixer = (_ytdApp) => {
  8145. const ytdApp = insp(_ytdApp);
  8146. if (ytdApp && typeof ytdApp.onYtActionBoundListener_ === 'function' && !ytdApp.onYtActionBoundListener57_) {
  8147. ytdApp.onYtActionBoundListener57_ = ytdApp.onYtActionBoundListener_;
  8148. ytdApp.onYtActionBoundListener_ = ytdApp.onYtAction_.bind(ytdApp);
  8149. mbd++;
  8150. }
  8151. }
  8152.  
  8153. observablePromise(() => {
  8154.  
  8155. if (typeof cProto.created === 'function' && !cProto.created56) {
  8156. cProto.created56 = cProto.created;
  8157. cProto.created = function (...args) {
  8158. const r = this.created56(...args);
  8159. fixer(this);
  8160. return r;
  8161. };
  8162. mbd++;
  8163. }
  8164.  
  8165. if (typeof cProto.onYtAction_ === 'function' && !cProto.onYtAction57_) {
  8166. cProto.onYtAction57_ = cProto.onYtAction_;
  8167. cProto.onYtAction_ = function (...args) {
  8168. Promise.resolve().then(() => this.onYtAction57_(...args));
  8169. };
  8170. mbd++;
  8171. }
  8172.  
  8173. if (ytdApp) fixer(ytdApp);
  8174.  
  8175. /*
  8176. const actionRouter_ = ytdApp ? ytdApp.actionRouter_ : null;
  8177. if (actionRouter_ && typeof actionRouter_.handleAction === 'function' && !actionRouter_.handleAction57) {
  8178. actionRouter_.handleAction57 = actionRouter_.handleAction;
  8179. actionRouter_.handleAction = function (...args) {
  8180. Promise.resolve().then(() => this.handleAction57(...args));
  8181. }
  8182. mbd++;
  8183. }
  8184. */
  8185.  
  8186. // if(mbd === 3) return 1;
  8187. if (mbd >= 3) return 1;
  8188.  
  8189. }, new Promise(r => setTimeout(r, 1000))).obtain();
  8190.  
  8191. })();
  8192.  
  8193.  
  8194.  
  8195. FORCE_NO_REUSEABLE_ELEMENT_POOL && promiseForYtActionCalled.then(async () => {
  8196.  
  8197. const appTag = isChatRoomURL ? 'yt-live-chat-app' : 'ytd-watch-flexy';
  8198.  
  8199. const app = await observablePromise(() => {
  8200.  
  8201. return document.querySelector(appTag);
  8202.  
  8203. }).obtain();
  8204.  
  8205. if (!app) return;
  8206.  
  8207.  
  8208. const appCnt = insp(app);
  8209.  
  8210. if (typeof appCnt.createComponent_ !== 'function' || appCnt.createComponent_.length != 3) return;
  8211.  
  8212.  
  8213. const mapGet = Map.prototype.get;
  8214.  
  8215.  
  8216. /** @type {Map | null} */
  8217. let qcMap = null;
  8218.  
  8219. Map.prototype.get = function (a) {
  8220. if (a === 'dummy-4718') qcMap = this;
  8221. return mapGet.call(this, a);
  8222. };
  8223. const r = appCnt.createComponent_('dummy-4718', {}, true);
  8224. Map.prototype.get = mapGet;
  8225.  
  8226. if (r && (r.nodeName || '').toLowerCase() === 'dummy-4718') {
  8227.  
  8228.  
  8229. // clearInterval(ckId);
  8230. // ckId = 0;
  8231.  
  8232. if (qcMap !== null && qcMap instanceof Map) {
  8233.  
  8234. console.log('[yt-js-engine-tamer] qcMap', qcMap);
  8235.  
  8236. const setArrayC = (c) => {
  8237. if (c instanceof Array) {
  8238. c.length = 0;
  8239. c.push = function () { };
  8240. c.pop = function () { };
  8241. c.shift = function () { };
  8242. c.unshift = function () { };
  8243. c.splice = function () { };
  8244. c.sort = function () { };
  8245. c.reverse = function () { };
  8246. }
  8247. }
  8248.  
  8249. const cleaning = function () {
  8250. qcMap.forEach(setArrayC);
  8251. qcMap.clear();
  8252. }
  8253.  
  8254. qcMap.set = function (b, c) {
  8255.  
  8256. setArrayC(c);
  8257.  
  8258. // console.log('qcMap.set', b, c);
  8259.  
  8260. if (qcMap.size > 0) {
  8261. // play safe
  8262.  
  8263. console.log('[yt-js-engine-tamer] qcMap', 'clear 01')
  8264. cleaning();
  8265. }
  8266.  
  8267. }
  8268. qcMap.get = function (b) {
  8269.  
  8270. // console.log('qcMap.get', b);
  8271.  
  8272. if (qcMap.size > 0) {
  8273. // play safe
  8274.  
  8275. console.log('[yt-js-engine-tamer] qcMap', 'clear 02')
  8276. cleaning();
  8277. }
  8278.  
  8279. }
  8280.  
  8281.  
  8282. if (qcMap.size > 0) {
  8283.  
  8284. console.log('[yt-js-engine-tamer] qcMap', 'clear 03')
  8285. cleaning();
  8286. }
  8287.  
  8288. }
  8289.  
  8290. }
  8291.  
  8292.  
  8293. });
  8294.  
  8295.  
  8296. const observablePromise = (proc, timeoutPromise) => {
  8297. let promise = null;
  8298. return {
  8299. obtain() {
  8300. if (!promise) {
  8301. promise = new Promise(resolve => {
  8302. let mo = null;
  8303. const f = () => {
  8304. let t = proc();
  8305. if (t) {
  8306. mo.disconnect();
  8307. mo.takeRecords();
  8308. mo = null;
  8309. resolve(t);
  8310. }
  8311. }
  8312. mo = new MutationObserver(f);
  8313. mo.observe(document, { subtree: true, childList: true })
  8314. f();
  8315. timeoutPromise && timeoutPromise.then(() => {
  8316. resolve(null)
  8317. });
  8318. });
  8319. }
  8320. return promise
  8321. }
  8322. }
  8323. }
  8324.  
  8325. // let _yt_player_promise = null;
  8326. /*
  8327. const getYtPlayerPromise = () => {
  8328. if (!_yt_player_promise) {
  8329. _yt_player_promise = new Promise(resolve => {
  8330. let cid = setInterval(() => {
  8331. let t = (((window || 0)._yt_player || 0) || 0);
  8332. if (t) {
  8333. clearInterval(cid);
  8334. resolve(t);
  8335. }
  8336. }, 1);
  8337. promiseForTamerTimeout.then(() => {
  8338. resolve(null)
  8339. });
  8340. });
  8341. }
  8342. return _yt_player_promise;
  8343. }
  8344. */
  8345. const _yt_player_observable = observablePromise(() => {
  8346. const _yt_player = (((window || 0)._yt_player || 0) || 0);
  8347. if (_yt_player) {
  8348. _yt_player[`__is_yt_player__${Date.now()}`] = 1;
  8349. return _yt_player;
  8350. }
  8351. }, promiseForTamerTimeout);
  8352.  
  8353. const polymerObservable = observablePromise(() => {
  8354. const Polymer = window.Polymer;
  8355. if (typeof Polymer !== 'function') return;
  8356. if (!(Polymer.Base || 0).connectedCallback || !(Polymer.Base || 0).disconnectedCallback) return;
  8357. return Polymer;
  8358. }, promiseForTamerTimeout);
  8359.  
  8360. const schedulerInstanceObservable = observablePromise(() => {
  8361. return (((window || 0).ytglobal || 0).schedulerInstanceInstance_ || 0);
  8362. }, promiseForTamerTimeout);
  8363.  
  8364. const timelineObservable = observablePromise(() => {
  8365. let t = (((document || 0).timeline || 0) || 0);
  8366. if (t && typeof t._play === 'function') {
  8367. return t;
  8368. }
  8369. }, promiseForTamerTimeout);
  8370. const animationObservable = observablePromise(() => {
  8371. let t = (((window || 0).Animation || 0) || 0);
  8372. if (t && typeof t === 'function' && t.length === 2 && typeof t.prototype._updatePromises === 'function') {
  8373. return t;
  8374. }
  8375. }, promiseForTamerTimeout);
  8376.  
  8377.  
  8378. const getScreenInfo = {
  8379. screenWidth: 0,
  8380. screenHeight: 0,
  8381. valueReady: false,
  8382. onResize: () => {
  8383. getScreenInfo.valueReady = false;
  8384. },
  8385. sizeProvided: () => {
  8386. if (getScreenInfo.valueReady) return true;
  8387. getScreenInfo.screenWidth = screen.width;
  8388. getScreenInfo.screenHeight = screen.height;
  8389. if (getScreenInfo.screenWidth * getScreenInfo.screenHeight > 1) {
  8390. getScreenInfo.valueReady = true;
  8391. return true;
  8392. }
  8393. return false;
  8394. }
  8395. };
  8396.  
  8397. window.addEventListener('resize', getScreenInfo.onResize, true);
  8398.  
  8399.  
  8400. // const hookLeftPending = new WeakMap();
  8401.  
  8402. const isNaNx = Number.isNaN;
  8403.  
  8404. const hookLeftPD = {
  8405. get() {
  8406. const p = 'left';
  8407. // const o = hookLeftPending.get(this);
  8408. // if (o && o.key) {
  8409. // this.setProperty(p, o.value);
  8410. // o.key = null
  8411. // }
  8412. return this.getPropertyValue(p);
  8413. },
  8414. set(v) {
  8415.  
  8416. const p = 'left';
  8417. const cv = this.getPropertyValue(p);
  8418. const sv = v;
  8419.  
  8420. // const did = Math.floor(Math.random() * 314159265359 + 314159265359).toString(36);
  8421.  
  8422. // console.log(8380,did, cv, sv)
  8423. if (!cv && !sv) return true;
  8424. if (cv === sv) return true;
  8425.  
  8426. // skip 0~9px => L>=4
  8427.  
  8428. const qsv = `${sv}`.length >= 4 && `${sv}`.endsWith('px') ? +sv.slice(0, -2) : NaN;
  8429.  
  8430. if (!isNaNx(qsv)) {
  8431. const qcv = `${cv}`.length >= 4 && `${cv}`.endsWith('px') ? +cv.slice(0, -2) : NaN;
  8432.  
  8433. if (!isNaNx(qcv) && getScreenInfo.sizeProvided()) {
  8434. const { screenWidth, screenHeight } = getScreenInfo;
  8435. let pWidth = screenWidth + 1024;
  8436. let pHeight = screenHeight + 768;
  8437. const minRatio = 0.003;
  8438. const dw = pWidth * 0.0003; // min dw = 0.3072
  8439. const dh = pHeight * 0.0003; // min dh = 0.2304
  8440. // console.log(8381,did, Math.abs(qcv - qsv) < dw)
  8441. if (Math.abs(qcv - qsv) < dw) return true;
  8442. }
  8443.  
  8444. v = `${qsv > -1e-5 && qsv < 1e-5 ? 0 : qsv.toFixed(4)}px`;
  8445. if (`${v}`.length > `${sv}`.length) v = sv;
  8446. // console.log(8382, did, sv, nv, cv, this)
  8447. }
  8448.  
  8449. // Promise.resolve().then(() => {
  8450. // const o = hookLeftPending.get(this);
  8451. // if (o && o.key === did) {
  8452. // this.setProperty(p, o.value);
  8453. // o.key = null;
  8454. // }
  8455. // });
  8456. // hookLeftPending.set(this, {
  8457. // key: did,
  8458. // value: nv
  8459. // });
  8460.  
  8461. // if (nv != v) {
  8462. // console.log(8387, v, nv);
  8463. // }
  8464.  
  8465. this.setProperty(p, v);
  8466. // console.log(8383, did, this.getPropertyValue(p))
  8467. return true;
  8468. },
  8469. enumerable: true,
  8470. configurable: true
  8471. };
  8472.  
  8473.  
  8474. if (HOOK_CSSPD_LEFT) {
  8475.  
  8476.  
  8477. Object.defineProperty(CSSStyleDeclaration.prototype, 'left', hookLeftPD);
  8478.  
  8479. }
  8480.  
  8481.  
  8482.  
  8483.  
  8484.  
  8485. const generalEvtHandler = async (_evKey, _fvKey, _debug) => {
  8486.  
  8487. const evKey = `${_evKey}`;
  8488. const fvKey = `${_fvKey}`;
  8489. const debug = !!_debug;
  8490.  
  8491. const _yt_player = await _yt_player_observable.obtain();
  8492.  
  8493.  
  8494. if (!_yt_player || typeof _yt_player !== 'object') return;
  8495.  
  8496.  
  8497. const getArr = (_yt_player) => {
  8498.  
  8499. let arr = [];
  8500.  
  8501. for (const [k, v] of Object.entries(_yt_player)) {
  8502.  
  8503. const p = typeof v === 'function' ? v.prototype : 0;
  8504. if (p
  8505. && typeof p[evKey] === 'function' && p[evKey].length >= 0 && !p[fvKey]
  8506.  
  8507. ) {
  8508. arr = addProtoToArr(_yt_player, k, arr) || arr;
  8509.  
  8510. }
  8511.  
  8512. }
  8513.  
  8514. if (arr.length === 0) {
  8515.  
  8516. console.warn(`Key prop [${evKey}] does not exist.`);
  8517. } else {
  8518.  
  8519. return arr;
  8520. }
  8521.  
  8522. };
  8523.  
  8524. const arr = getArr(_yt_player);
  8525.  
  8526.  
  8527. if (!arr) return;
  8528.  
  8529. debug && console.log(`FIX_${evKey}`, arr);
  8530.  
  8531. const f = function (...args) {
  8532. Promise.resolve().then(() => this[fvKey](...args));
  8533. };
  8534.  
  8535.  
  8536. for (const k of arr) {
  8537.  
  8538. const g = _yt_player;
  8539. const gk = g[k];
  8540. const gkp = gk.prototype;
  8541.  
  8542. debug && console.log(237, k, gkp)
  8543.  
  8544. if (typeof gkp[evKey] == 'function' && !gkp[fvKey]) {
  8545. gkp[fvKey] = gkp[evKey];
  8546. gkp[evKey] = f;
  8547. }
  8548. }
  8549.  
  8550.  
  8551.  
  8552.  
  8553. }
  8554.  
  8555. if (!isChatRoomURL) {
  8556.  
  8557. FIX_onVideoDataChange && generalEvtHandler('onVideoDataChange', 'onVideoDataChange57');
  8558. // FIX_onClick && generalEvtHandler('onClick', 'onClick57');
  8559. FIX_onStateChange && generalEvtHandler('onStateChange', 'onStateChange57');
  8560. FIX_onLoopRangeChange && generalEvtHandler('onLoopRangeChange', 'onLoopRangeChange57');
  8561. if (FIX_VideoEVENTS_v2) {
  8562. const FIX_VideoEVENTS_DEBUG = 0;
  8563. generalEvtHandler('onVideoProgress', 'onVideoProgress57', FIX_VideoEVENTS_DEBUG); // --
  8564. // generalEvtHandler('onAutoplayBlocked', 'onAutoplayBlocked57', FIX_VideoEVENTS_DEBUG);
  8565. // generalEvtHandler('onLoadProgress', 'onLoadProgress57', FIX_VideoEVENTS_DEBUG); // << CAUSE ISSUE >>
  8566. generalEvtHandler('onFullscreenChange', 'onFullscreenChange57', FIX_VideoEVENTS_DEBUG); // --
  8567. // generalEvtHandler('onLoadedMetadata', 'onLoadedMetadata57', FIX_VideoEVENTS_DEBUG);
  8568. // generalEvtHandler('onDrmOutputRestricted', 'onDrmOutputRestricted57', FIX_VideoEVENTS_DEBUG);
  8569. // generalEvtHandler('onAirPlayActiveChange', 'onAirPlayActiveChange57', FIX_VideoEVENTS_DEBUG);
  8570. // generalEvtHandler('onAirPlayAvailabilityChange', 'onAirPlayAvailabilityChange57', FIX_VideoEVENTS_DEBUG);
  8571. // generalEvtHandler('onApiChange', 'onApiChange57', FIX_VideoEVENTS_DEBUG);
  8572.  
  8573. }
  8574. // onMutedAutoplayChange
  8575. // onVolumeChange
  8576. // onPlaybackRateChange
  8577.  
  8578. // onAirPlayActiveChange
  8579. // onAirPlayAvailabilityChange
  8580. // onApiChange
  8581. // onAutoplayBlocked
  8582. // onDrmOutputRestricted
  8583. // onFullscreenChange
  8584. // onLoadProgress
  8585. // onLoadedMetadata
  8586. // onVideoDataChange
  8587. // onVideoProgress
  8588.  
  8589. }
  8590.  
  8591.  
  8592.  
  8593. (ENABLE_discreteTasking || FIX_Polymer_dom || FIX_stampDomArray ) && (async () => {
  8594.  
  8595. const Polymer = await polymerObservable.obtain();
  8596. if (!Polymer) return;
  8597.  
  8598. if (FIX_Polymer_dom) {
  8599.  
  8600. const checkPDFuncValue = (pd) => {
  8601. return pd && pd.writable && pd.enumerable && pd.configurable && typeof pd.value == 'function'
  8602. }
  8603. const checkPDFuncValue2 = (pd) => {
  8604. return pd && typeof pd.value == 'function'
  8605. }
  8606.  
  8607. const checkPDFuncGet = (pd) => {
  8608. return pd && typeof pd.get == 'function'
  8609. }
  8610.  
  8611. const domX = Polymer.dom(document.createElement('null'));
  8612. const domXP = (((domX || 0).constructor || 0).prototype || 0);
  8613. const pd1 = Object.getOwnPropertyDescriptor(domXP, 'getOwnerRoot');
  8614. const pd2 = Object.getOwnPropertyDescriptor(Node.prototype, 'parentElement');
  8615. const pd3 = Object.getOwnPropertyDescriptor(domXP, 'querySelector'); // undefined
  8616. const pd4 = Object.getOwnPropertyDescriptor(Element.prototype, 'querySelector');
  8617. const pd4b = Object.getOwnPropertyDescriptor(Document.prototype, 'querySelector');
  8618. const pd5 = Object.getOwnPropertyDescriptor(domXP, 'querySelectorAll'); // undefined
  8619. const pd6 = Object.getOwnPropertyDescriptor(Element.prototype, 'querySelectorAll');
  8620. const pd6b = Object.getOwnPropertyDescriptor(Document.prototype, 'querySelectorAll');
  8621.  
  8622.  
  8623. // getOwnerRoot - to be reviewed
  8624. if (0 && checkPDFuncValue(pd1) && checkPDFuncGet(pd2) && !domXP.getOwnerRoot15 && typeof domXP.getOwnerRoot === 'function') {
  8625.  
  8626. domXP.getOwnerRoot15 = domXP.getOwnerRoot;
  8627. domXP.getOwnerRoot = function () {
  8628. try {
  8629. const p = this.node;
  8630.  
  8631. if (p instanceof HTMLElement_) {
  8632. const pp = pd2.get.call(p);
  8633. if (pp instanceof HTMLElement_ && pp.isConnected === true) {
  8634. return pp.getRootNode();
  8635. }
  8636.  
  8637. }
  8638. } catch (e) { }
  8639. return this.getOwnerRoot15();
  8640. }
  8641.  
  8642. Polymer.__fixedGetOwnerRoot__ = 1;
  8643. }
  8644.  
  8645.  
  8646.  
  8647.  
  8648. if ((!pd3 || checkPDFuncValue(pd3)) && checkPDFuncValue2(pd4) && checkPDFuncValue2(pd4b) && !('querySelector15' in domXP)) {
  8649.  
  8650. domXP.querySelector15 = domXP.querySelector;
  8651.  
  8652. const querySelectorFn = function (query) {
  8653. try {
  8654. const p = this.node;
  8655.  
  8656. if (p instanceof Document && p.isConnected === true) {
  8657. return pd4b.value.call(p, query);
  8658. }
  8659.  
  8660. } catch (e) { }
  8661. return this.querySelector15(query);
  8662. }
  8663.  
  8664. Object.defineProperty(domXP, 'querySelector', {
  8665. get() {
  8666. return querySelectorFn;
  8667. },
  8668. set(nv) {
  8669. if (nv === querySelectorFn) return true;
  8670. this.querySelector15 = nv;
  8671. return true;
  8672. },
  8673.  
  8674. enumerable: false,
  8675. configurable: true
  8676. });
  8677.  
  8678. Polymer.__fixedQuerySelector__ = 1;
  8679. }
  8680.  
  8681. if ((!pd5 || checkPDFuncValue(pd5)) && checkPDFuncValue2(pd6) && checkPDFuncValue2(pd6b) && !('querySelectorAll15' in domXP)) {
  8682.  
  8683. domXP.querySelectorAll15 = domXP.querySelectorAll;
  8684.  
  8685. const querySelectorAllFn = function (query) {
  8686.  
  8687. try {
  8688.  
  8689. const p = this.node;
  8690.  
  8691. if (p instanceof Document && p.isConnected === true) {
  8692. return pd6b.value.call(p, query);
  8693. }
  8694.  
  8695. } catch (e) {
  8696.  
  8697. }
  8698. return this.querySelectorAll15(query);
  8699. }
  8700.  
  8701. Object.defineProperty(domXP, 'querySelectorAll', {
  8702. get() {
  8703. return querySelectorAllFn;
  8704. },
  8705. set(nv) {
  8706. if (nv === querySelectorAllFn) return true;
  8707. this.querySelectorAll15 = nv;
  8708. return true;
  8709. },
  8710.  
  8711. enumerable: false,
  8712. configurable: true
  8713. });
  8714.  
  8715. Polymer.__fixedQuerySelectorAll__ = 1;
  8716. }
  8717. }
  8718.  
  8719.  
  8720. if (ENABLE_discreteTasking || FIX_stampDomArray) {
  8721.  
  8722. Polymer.Base.__connInit__ = function () {
  8723. setupYtComponent(this);
  8724. }
  8725.  
  8726.  
  8727. /** @type {Function} */
  8728. const connectedCallbackK = function (...args) {
  8729. !this.mh35 && typeof this.__connInit__ === 'function' && this.__connInit__();
  8730. const r = this[qm53](...args);
  8731. !this.mh35 && typeof this.__connInit__ === 'function' && this.__connInit__();
  8732. this.mh35 = 1;
  8733. return r;
  8734. };
  8735.  
  8736. connectedCallbackK.m353 = 1;
  8737.  
  8738.  
  8739. const qt53 = Polymer.Base.connectedCallback;
  8740. Polymer.Base[qm53] = dmf.get(qt53) || qt53;
  8741.  
  8742. Polymer.Base.connectedCallback = connectedCallbackK;
  8743.  
  8744.  
  8745. /** @type {Function} */
  8746. const createdK = function (...args) {
  8747. !this.mh36 && typeof this.__connInit__ === 'function' && this.__connInit__();
  8748. const r = this[qn53](...args);
  8749. !this.mh36 && typeof this.__connInit__ === 'function' && this.__connInit__();
  8750. this.mh36 = 1;
  8751. return r;
  8752. };
  8753.  
  8754.  
  8755. createdK.m353 = 1;
  8756. Polymer.Base[qn53] = Polymer.Base.created;
  8757. Polymer.Base.created = createdK;
  8758.  
  8759. }
  8760.  
  8761. })();
  8762.  
  8763.  
  8764. /*
  8765.  
  8766. e.nativeAppendChild = d.prototype.appendChild,
  8767. d.prototype.appendChild = function(h) {
  8768. return function(l) {
  8769. if (l instanceof DocumentFragment) {
  8770. var m = Array.from(l.children);
  8771. l = h.nativeAppendChild.call(this, l);
  8772. if (this.isConnected) {
  8773. m = g(m);
  8774. for (var p = m.next(); !p.done; p = m.next())
  8775. YD(p.value)
  8776. }
  8777. return l
  8778. }
  8779. m = l instanceof Element && l.isConnected;
  8780. p = h.nativeAppendChild.call(this, l);
  8781. m && ZD(l);
  8782. this.isConnected && YD(l);
  8783. return p
  8784. }
  8785. }(e),
  8786.  
  8787. */
  8788.  
  8789. CHANGE_appendChild && !Node.prototype.appendChild73 && Node.prototype.appendChild && (() => {
  8790.  
  8791. const f = Node.prototype.appendChild73 = Node.prototype.appendChild;
  8792. if (f) Node.prototype.appendChild = function (a) {
  8793. if (this instanceof Element) { // exclude DocumentFragment
  8794. try {
  8795. let checkFragmentA = (a instanceof DocumentFragment);
  8796. if (!NO_PRELOAD_GENERATE_204_BYPASS && document.head === this) {
  8797. if (headLinkCollection === null) headLinkCollection = document.head.getElementsByTagName('LINK');
  8798. for (const node of headLinkCollection) {
  8799. if (node.rel === 'preload' && node.as === 'fetch') {
  8800. node.rel = 'prefetch'; // see https://github.com/GoogleChromeLabs/quicklink
  8801. }
  8802. }
  8803. } else if (checkFragmentA && this.nodeName.startsWith('YT-')) { // yt-animated-rolling-number, yt-attributed-string
  8804. checkFragmentA = false;
  8805. }
  8806. if (checkFragmentA && a.firstElementChild === null) {
  8807. // no element in fragmentA
  8808. let doNormal = false;
  8809. for (let child = a.firstChild; child instanceof Node; child = child.nextSibling) {
  8810. if (child.nodeType === 3) { doNormal = true; break; }
  8811. }
  8812. if (!doNormal) return a;
  8813. }
  8814. } catch (e) {
  8815. console.log(e);
  8816. }
  8817. }
  8818. return arguments.length === 1 ? f.call(this, a) : f.apply(this, arguments);
  8819. }
  8820.  
  8821. })();
  8822.  
  8823. if (FIX_Shady) {
  8824.  
  8825. observablePromise(() => {
  8826. const { ShadyDOM, ShadyCSS } = window;
  8827. if (ShadyDOM) {
  8828. ShadyDOM.handlesDynamicScoping = false; // 9 of 10
  8829. ShadyDOM.noPatch = true; // 1 of 10
  8830. ShadyDOM.patchOnDemand = false; // 1 of 10
  8831. ShadyDOM.preferPerformance = true; // 1 of 10
  8832. ShadyDOM.querySelectorImplementation = undefined; // 1 of 10
  8833. }
  8834. if (ShadyCSS) {
  8835. ShadyCSS.nativeCss = true; // 1 of 10
  8836. ShadyCSS.nativeShadow = true; // 6 of 10
  8837. ShadyCSS.cssBuild = undefined; // 1 of 10
  8838. ShadyCSS.disableRuntime = true; // 1 of 10
  8839. }
  8840. if (ShadyDOM && ShadyCSS) return 1;
  8841. }, promiseForTamerTimeout).obtain(); // clear until 1 is return
  8842.  
  8843. }
  8844.  
  8845.  
  8846. // let schedulerInstancePropOfTimerType = '';
  8847. // let schedulerInstancePropOfTimerId = '';
  8848. (FIX_schedulerInstanceInstance & 2) && (async () => {
  8849.  
  8850. const schedulerInstanceInstance_ = await schedulerInstanceObservable.obtain();
  8851.  
  8852. if (!schedulerInstanceInstance_) return;
  8853.  
  8854. const checkOK = typeof schedulerInstanceInstance_.start === 'function' && !schedulerInstanceInstance_.start993 && !schedulerInstanceInstance_.stop && !schedulerInstanceInstance_.cancel && !schedulerInstanceInstance_.terminate && !schedulerInstanceInstance_.interupt;
  8855. if (checkOK) {
  8856.  
  8857. schedulerInstanceInstance_.start993 = schedulerInstanceInstance_.start;
  8858.  
  8859. let requestingFn = null;
  8860. let requestingArgs = null;
  8861.  
  8862. const f = function () {
  8863. requestingFn = this.fn;
  8864. requestingArgs = [...arguments];
  8865. return 12373;
  8866. };
  8867.  
  8868. const fakeFns = [
  8869. f.bind({ fn: requestAnimationFrame }),
  8870. f.bind({ fn: setInterval }),
  8871. f.bind({ fn: setTimeout }),
  8872. f.bind({ fn: requestIdleCallback })
  8873. ];
  8874.  
  8875. let mzt = 0;
  8876.  
  8877. let _fnSelectorProp = null;
  8878. const mkFns = new Array(4);
  8879.  
  8880. /*
  8881. case 1:
  8882. var a = this.K;
  8883. this.g = this.I ? window.requestIdleCallback(a, {
  8884. timeout: 3E3
  8885. }) : window.setTimeout(a, ma);
  8886. break;
  8887. case 2:
  8888. this.g = window.setTimeout(this.M, this.N);
  8889. break;
  8890. case 3:
  8891. this.g = window.requestAnimationFrame(this.L);
  8892. break;
  8893. case 4:
  8894. this.g = window.setTimeout(this.J, 0)
  8895. }
  8896.  
  8897. */
  8898. const startFnHandler = {
  8899. get(target, prop, receiver) {
  8900. if (prop === '$$12377$$') return true;
  8901. if (prop === '$$12378$$') return target;
  8902.  
  8903. // console.log('get',prop)
  8904. return target[prop]
  8905. },
  8906. set(target, prop, value, receiver) {
  8907. // console.log('set', prop, value)
  8908.  
  8909. if (value >= 1 && value <= 4) _fnSelectorProp = prop;
  8910. if (value === 12373 && _fnSelectorProp) {
  8911.  
  8912. const schedulerTypeSelection = target[_fnSelectorProp];
  8913. const timerIdProp = prop;
  8914.  
  8915. // if (schedulerTypeSelection && schedulerTypeSelection >= 1 && schedulerTypeSelection <= 4 && timerIdProp) {
  8916. // schedulerInstancePropOfTimerType = _fnSelectorProp || '';
  8917. // schedulerInstancePropOfTimerId = timerIdProp || '';
  8918. // }
  8919.  
  8920. if (schedulerTypeSelection === 3 && requestingFn === requestAnimationFrame) { // rAF(fn)
  8921. target[timerIdProp] = baseRAF.apply(window, requestingArgs);
  8922. } else if (schedulerTypeSelection === 2 && requestingFn === setTimeout) { // setTimeout(fn, delay)
  8923. // rare
  8924. target[timerIdProp] = mkFns[2].apply(window, requestingArgs);
  8925. } else if (schedulerTypeSelection === 4 && requestingFn === setTimeout && !requestingArgs[1]) { // setTimeout(fn, 0)
  8926. // often
  8927. if ((FIX_schedulerInstanceInstance & 4)) {
  8928. const f = requestingArgs[0];
  8929. const tir = ++mzt;
  8930. nextBrowserTick_(() => {
  8931. if (target[timerIdProp] === -tir) f();
  8932. });
  8933. target[_fnSelectorProp] = 940;
  8934. target[timerIdProp] = -tir;
  8935. } else {
  8936. const f = requestingArgs[0];
  8937. const tir = ++mzt;
  8938. Promise.resolve().then(() => {
  8939. if (target[timerIdProp] === -tir) f();
  8940. });
  8941. target[_fnSelectorProp] = 930;
  8942. target[timerIdProp] = -tir;
  8943. }
  8944. } else if (schedulerTypeSelection === 1 && (requestingFn === requestIdleCallback || requestingFn === setTimeout)) { // setTimeout(requestIdleCallback)
  8945. // often
  8946. if (requestingFn === requestIdleCallback) {
  8947. target[timerIdProp] = requestIdleCallback.apply(window, requestingArgs);
  8948. } else {
  8949. target[timerIdProp] = mkFns[2].apply(window, requestingArgs);
  8950. }
  8951. } else {
  8952. target[_fnSelectorProp] = 0;
  8953. target[timerIdProp] = 0;
  8954. }
  8955. } else {
  8956. target[prop] = value;
  8957. }
  8958. return true;
  8959. }
  8960. };
  8961.  
  8962. let startBusy = false;
  8963. schedulerInstanceInstance_.start = function () {
  8964. if (startBusy) return;
  8965. startBusy = true;
  8966. try {
  8967. mkFns[0] = window.requestAnimationFrame;
  8968. mkFns[1] = window.setInterval;
  8969. mkFns[2] = window.setTimeout;
  8970. mkFns[3] = window.requestIdleCallback;
  8971. const tThis = this['$$12378$$'] || this;
  8972. window.requestAnimationFrame = fakeFns[0]
  8973. window.setInterval = fakeFns[1]
  8974. window.setTimeout = fakeFns[2]
  8975. window.requestIdleCallback = fakeFns[3]
  8976. _fnSelectorProp = null;
  8977. tThis.start993.call(new Proxy(tThis, startFnHandler));
  8978. _fnSelectorProp = null;
  8979. window.requestAnimationFrame = mkFns[0];
  8980. window.setInterval = mkFns[1];
  8981. window.setTimeout = mkFns[2];
  8982. window.requestIdleCallback = mkFns[3];
  8983. } catch (e) {
  8984. console.warn(e);
  8985. }
  8986. startBusy = false;
  8987. }
  8988.  
  8989. schedulerInstanceInstance_.start.toString = schedulerInstanceInstance_.start993.toString.bind(schedulerInstanceInstance_.start993);
  8990.  
  8991. }
  8992. })();
  8993.  
  8994. FIX_yt_player && !isChatRoomURL && (async () => {
  8995.  
  8996. const fOption = 1 | 2 | 4;
  8997.  
  8998. const _yt_player = await _yt_player_observable.obtain();
  8999.  
  9000. if (!_yt_player || typeof _yt_player !== 'object') return;
  9001.  
  9002. const g = _yt_player;
  9003. let k;
  9004.  
  9005. if (fOption & 1) {
  9006.  
  9007. // rAf scheduling
  9008.  
  9009. const keyZqOu = getZqOu(_yt_player);
  9010. if (!keyZqOu) {
  9011. console.warn('[yt-js-engine-tamer] FIX_yt_player::keyZqOu error');
  9012. return;
  9013. }
  9014. k = keyZqOu
  9015.  
  9016. const gk = g[k];
  9017. if (typeof gk !== 'function') {
  9018. console.warn('[yt-js-engine-tamer] FIX_yt_player::g[keyZqOu] error');
  9019. return;
  9020. }
  9021. const gkp = gk.prototype;
  9022.  
  9023. const dummyObject = new gk;
  9024. const nilFunc = () => { };
  9025.  
  9026. const nilObj = {};
  9027.  
  9028. // console.log(1111111111)
  9029.  
  9030. let keyBoolD = '';
  9031. let keyWindow = '';
  9032. let keyFuncC = '';
  9033. let keyCidj = '';
  9034.  
  9035. for (const [t, y] of Object.entries(dummyObject)) {
  9036. if (y instanceof Window) keyWindow = t;
  9037. }
  9038.  
  9039. const dummyObjectProxyHandler = {
  9040. get(target, prop) {
  9041. let v = target[prop]
  9042. if (v instanceof Window && !keyWindow) {
  9043. keyWindow = t;
  9044. }
  9045. let y = typeof v === 'function' ? nilFunc : typeof v === 'object' ? nilObj : v;
  9046. if (prop === keyWindow) y = {
  9047. requestAnimationFrame(f) {
  9048. return 3;
  9049. },
  9050. cancelAnimationFrame() {
  9051.  
  9052. }
  9053. }
  9054. if (!keyFuncC && typeof v === 'function' && !(prop in target.constructor.prototype)) {
  9055. keyFuncC = prop;
  9056. }
  9057. // console.log('[get]', prop, typeof target[prop])
  9058.  
  9059.  
  9060. return y;
  9061. },
  9062. set(target, prop, value) {
  9063.  
  9064. if (typeof value === 'boolean' && !keyBoolD) {
  9065. keyBoolD = prop;
  9066. }
  9067. if (typeof value === 'number' && !keyCidj && value >= 2) {
  9068. keyCidj = prop;
  9069. }
  9070.  
  9071. // console.log('[set]', prop, value)
  9072. target[prop] = value;
  9073.  
  9074. return true;
  9075. }
  9076. };
  9077.  
  9078. dummyObject.start.call(new Proxy(dummyObject, dummyObjectProxyHandler));
  9079.  
  9080. // console.log('gkp.start',gkp.start);
  9081. // console.log('gkp.stop',gkp.stop);
  9082. gkp._activation = false;
  9083.  
  9084. gkp.start = function () {
  9085. // p59 || console.log(12100)
  9086. if (!this._activation) {
  9087. this._activation = true;
  9088. foregroundPromiseFn().then(() => {
  9089. this._activation = false;
  9090. if (this[keyCidj]) {
  9091. Promise.resolve().then(this[keyFuncC]);
  9092. }
  9093. });
  9094. }
  9095. this[keyCidj] = 1;
  9096. this[keyBoolD] = true;
  9097. };
  9098.  
  9099. gkp.stop = function () {
  9100. this[keyCidj] = null;
  9101. };
  9102.  
  9103.  
  9104. /*
  9105. g[k].start = function() {
  9106. this.stop();
  9107. this.D = true;
  9108. var a = requestAnimationFrame
  9109. , b = cancelAnimationFrame;
  9110. this.j = a.call(this.B, this.C)
  9111. }
  9112. ;
  9113. g[k].stop = function() {
  9114. if (this.isActive()) {
  9115. var a = requestAnimationFrame
  9116. , b = cancelAnimationFrame;
  9117. b.call(this.B, this.j)
  9118. }
  9119. this.j = null
  9120. }
  9121. */
  9122. }
  9123.  
  9124. if (fOption & 2) {
  9125. const keyzo = PERF_471489_ ? getzo(_yt_player) : null;
  9126.  
  9127. if (keyzo) {
  9128.  
  9129. k = keyzo;
  9130.  
  9131. const attrUpdateFn = g[k];
  9132. // console.log(5992, attrUpdateFn)
  9133. g['$$original$$' + k] = attrUpdateFn;
  9134. const zoTransform = async (a, c) => {
  9135.  
  9136. let transformType = '';
  9137. let transformValue = 0;
  9138. let transformUnit = '';
  9139. let transformTypeI = 0;
  9140.  
  9141. const aStyle = a.style;
  9142.  
  9143. let cType = 0;
  9144.  
  9145. const cl = c.length;
  9146.  
  9147. if (cl >= 8) {
  9148. // scale(1)
  9149. if (c.startsWith('scale') && c.charCodeAt(6) === 40 && c.charCodeAt(cl - 1) === 41) {
  9150. cType = 1;
  9151. let t = c.charCodeAt(5);
  9152. if (t === 88 || t === 120) cType = 1 | 4;
  9153. if (t === 89 || t === 121) cType = 1 | 8;
  9154. } else if (c.startsWith('translate') && c.charCodeAt(10) === 40 && c.charCodeAt(cl - 1) === 41) {
  9155. cType = 2;
  9156. let t = c.charCodeAt(9);
  9157. if (t === 88 || t === 120) cType = 2 | 4;
  9158. if (t === 89 || t === 121) cType = 2 | 8;
  9159. }
  9160. let w = 0;
  9161. if (w = (cType === 5) ? 1 : (cType === 9) ? 2 : 0) {
  9162. let p = c.substring(7, cl - 1);
  9163. let q = p.length >= 1 ? parseFloat(p) : NaN;
  9164. if (typeof q === 'number' && !isNaNx(q)) {
  9165. transformType = w === 1 ? 'scaleX' : 'scaleY';
  9166. transformValue = q;
  9167. transformUnit = '';
  9168. transformTypeI = 1;
  9169. } else {
  9170. cType = 256;
  9171. }
  9172. } else if (w = (cType === 6) ? 1 : (cType === 10) ? 2 : 0) {
  9173. if (c.endsWith('px)')) {
  9174. let p = c.substring(11, cl - 3);
  9175. let q = p.length >= 1 ? parseFloat(p) : NaN;
  9176. if (typeof q === 'number' && !isNaNx(q)) {
  9177. transformType = w === 1 ? 'translateX' : 'translateY';
  9178. transformValue = q;
  9179. transformUnit = 'px';
  9180. transformTypeI = 2;
  9181. } else if (p === 'NaN') {
  9182. return;
  9183. }
  9184. } else {
  9185. cType = 256;
  9186. }
  9187. } else if (cType > 0) {
  9188. cType = 256;
  9189. }
  9190. }
  9191.  
  9192.  
  9193. if (cType === 256) {
  9194. console.log('[yt-js-engine-tamer] zoTransform undefined', c);
  9195. }
  9196.  
  9197. if (transformTypeI === 1) {
  9198. const q = Math.round(transformValue * steppingScaleN) / steppingScaleN;
  9199. const vz = toFixed2(q, 3);
  9200. c = `${transformType}(${vz})`;
  9201. const cv = aStyle.transform;
  9202. if (c === cv) return;
  9203. aStyle.transform = c;
  9204. } else if (transformTypeI === 2) {
  9205. const q = transformValue;
  9206. const vz = toFixed2(q, 1);
  9207. c = `${transformType}(${vz}${transformUnit})`;
  9208. const cv = aStyle.transform;
  9209. if (c === cv) return;
  9210. aStyle.transform = c;
  9211. } else { // eg empty
  9212. const cv = aStyle.transform;
  9213. if (!c && !cv) return;
  9214. else if (c === cv) return;
  9215. aStyle.transform = c;
  9216. }
  9217.  
  9218. };
  9219.  
  9220. const elmTransformTemp = new WeakMap();
  9221. const elmPropTemps = {
  9222. 'display': new WeakMap(),
  9223. 'width': new WeakMap(),
  9224. 'height': new WeakMap(),
  9225. 'outlineWidth': new WeakMap(),
  9226. 'position': new WeakMap(),
  9227. 'padding': new WeakMap(),
  9228. "cssText": new WeakMap(),
  9229. "right": new WeakMap(),
  9230. "left": new WeakMap(),
  9231. "top": new WeakMap(),
  9232. "bottom": new WeakMap(),
  9233. "transitionDelay": new WeakMap(),
  9234. "marginLeft": new WeakMap(),
  9235. "marginTop": new WeakMap(),
  9236. "marginRight": new WeakMap(),
  9237. "marginBottom": new WeakMap(),
  9238. }
  9239.  
  9240. const ns5 = Symbol();
  9241. const nextModify = (a, c, m, f, immediate) => {
  9242. const a_ = a;
  9243. const m_ = m;
  9244. const noKey = !m_.has(a_);
  9245. if (immediate || noKey) {
  9246. m_.set(a_, ns5);
  9247. f(a_, c);
  9248. noKey && nextBrowserTick_(() => {
  9249. const d = m_.get(a_);
  9250. if (d === undefined) return;
  9251. m_.delete(a_);
  9252. if (d !== ns5) f(a_, d);
  9253. });
  9254. } else {
  9255. m_.set(a_, c);
  9256. }
  9257. };
  9258.  
  9259. const set66 = new Set();
  9260. const log77 = new Map();
  9261. // const set77 = new Set(['top', 'left', 'bottom', 'right']); // caption positioning - immediate change
  9262.  
  9263. const modifiedFn = function (a, b, c, immediateChange = false) { // arrow function does not have function.prototype
  9264.  
  9265. // console.log(140000, a, b, c);
  9266. if (typeof c === 'number' && typeof b === 'string' && a instanceof HTMLElement_) {
  9267. const num = c;
  9268. c = `${num}`;
  9269. if (c.length > 5) c = (num < 10 && num > -10) ? toFixed2(num, 3) : toFixed2(num, 1);
  9270. }
  9271.  
  9272. if (typeof b === 'string' && typeof c === 'string' && a instanceof HTMLElement_) {
  9273.  
  9274. let elmPropTemp = null;
  9275.  
  9276. if (b === "transform") {
  9277. // div.ytp-hover-progress.ytp-hover-progress-light
  9278. // div.ytp-play-progress.ytp-swatch-background-color
  9279.  
  9280. nextModify(a, c, elmTransformTemp, zoTransform, immediateChange);
  9281. return;
  9282.  
  9283. } else if (elmPropTemp = elmPropTemps[b]) {
  9284.  
  9285. // if (c.length > 5 && c.includes('.')) {
  9286. // console.log(123213, c)
  9287. // }
  9288.  
  9289. const b_ = b;
  9290. nextModify(a, c, elmPropTemp, (a, c) => {
  9291. const style = a.style;
  9292. const cv = style[b_];
  9293. if (!cv && !c) return;
  9294. if (cv === c) return;
  9295. style[b_] = c;
  9296. }, immediateChange);
  9297. return;
  9298.  
  9299. } else if (b === "outline-width") {
  9300.  
  9301. const b_ = 'outlineWidth';
  9302. elmPropTemp = elmPropTemps[b_];
  9303. nextModify(a, c, elmPropTemp, (a, c) => {
  9304. const style = a.style;
  9305. const cv = style[b_];
  9306. if (!cv && !c) return;
  9307. if (cv === c) return;
  9308. style[b_] = c;
  9309. }, immediateChange);
  9310. return;
  9311.  
  9312. } else if (b === 'maxWidth' || b === 'maxHeight') {
  9313. // I think these can be directly assigned.
  9314.  
  9315. const b_ = b;
  9316. const style = a.style;
  9317. const cv = style[b_];
  9318. if (!cv && !c) return;
  9319. if (cv === c) return;
  9320. style[b_] = c;
  9321. return;
  9322.  
  9323. } else {
  9324. // if(immediate && elmPropTemps[b]){
  9325. // console.log(5191, b)
  9326. // }
  9327. // caption-window
  9328. // margin-left max-height max-width font-family fill color font-size background white-space margin
  9329. // text-align background-color
  9330. // console.log(27304, a, b, c)
  9331. if (!set66.has(b)) {
  9332. set66.add(b);
  9333. nextBrowserTick_(() => {
  9334. if (!a.classList.contains('caption-window') && !a.classList.contains('ytp-caption-segment')) {
  9335. console.log(27304, a, b, c)
  9336. }
  9337. })
  9338. }
  9339. }
  9340.  
  9341. attrUpdateFn.call(this, a, b, c);
  9342. return;
  9343. } else if (typeof (b || 0) === 'object') {
  9344.  
  9345. // this is to fix caption positioning
  9346. // const immediate = (a.id || 0).length > 14 && (('top' in b) || ('left' in b) || ('right' in b) || ('bottom' in b));
  9347. const immediate = (a.id || 0).length > 14;
  9348. for (const [k, v] of Object.entries(b)) {
  9349. modifiedFn.call(this, a, k, v, immediate);
  9350. }
  9351.  
  9352. } else {
  9353.  
  9354. // a = circle, b = stroke-dasharray, c= "1.8422857142857143 32"
  9355. // ytp-ad-timed-pie-countdown-inner
  9356.  
  9357. if (typeof b === 'string') {
  9358.  
  9359. let m = log77.get(b);
  9360. if (!m) {
  9361. m = [];
  9362. console.log(27306, m);
  9363. log77.set(b, m);
  9364. }
  9365. m.push([a, b, c]);
  9366.  
  9367. } else {
  9368. console.log(27306, a, b, c);
  9369. }
  9370.  
  9371. attrUpdateFn.call(this, a, b, c);
  9372. return;
  9373. }
  9374.  
  9375. // console.log(130000, a, b, c);
  9376.  
  9377. };
  9378. g[k] = modifiedFn;
  9379.  
  9380.  
  9381. /*
  9382.  
  9383. g.zo = function(a, b, c) {
  9384. if ("string" === typeof b)
  9385. (b = yo(a, b)) && (a.style[b] = c);
  9386. else
  9387. for (var d in b) {
  9388. c = a;
  9389. var e = b[d]
  9390. , f = yo(c, d);
  9391. f && (c.style[f] = e)
  9392. }
  9393. }
  9394.  
  9395.  
  9396. */
  9397.  
  9398.  
  9399. }
  9400. }
  9401.  
  9402. if (fOption & 4) {
  9403. const keyuG = PERF_471489_ ? getuG(_yt_player) : null;
  9404.  
  9405. if (keyuG) {
  9406.  
  9407. k = keyuG;
  9408.  
  9409. const gk = g[k];
  9410. const gkp = gk.prototype;
  9411.  
  9412.  
  9413. /** @type { Map<string, WeakMap<any, any>> } */
  9414. const ntLogs = new Map();
  9415.  
  9416. if (typeof gkp.updateValue === 'function' && gkp.updateValue.length === 2 && !gkp.updateValue31) {
  9417.  
  9418. gkp.updateValue31 = gkp.updateValue;
  9419. gkp.updateValue = function (a, b) {
  9420. if (typeof a !== 'string') return this.updateValue31(a, b);
  9421.  
  9422. const element = this.element;
  9423. if (!(element instanceof HTMLElement_)) return this.updateValue31(a, b);
  9424.  
  9425. let ntLog = ntLogs.get(a);
  9426. if (!ntLog) ntLogs.set(a, (ntLog = new WeakMap()));
  9427.  
  9428. let cache = ntLog.get(element);
  9429. if (cache && cache.value === b) {
  9430. return;
  9431. }
  9432. if (!cache) {
  9433. this.__oldValueByUpdateValue__ = null;
  9434. ntLog.set(element, cache = { value: b });
  9435. } else {
  9436. this.__oldValueByUpdateValue__ = cache.value;
  9437. cache.value = b;
  9438. }
  9439.  
  9440. return this.updateValue31(a, b);
  9441. }
  9442.  
  9443. /*
  9444. g.k.update = function(a) {
  9445. for (var b = g.u(Object.keys(a)), c = b.next(); !c.done; c = b.next())
  9446. c = c.value,
  9447. this.updateValue(c, a[c])
  9448. }
  9449. ;
  9450. g.k.updateValue = function(a, b) {
  9451. (a = this.Td["{{" + a + "}}"]) && wG(this, a[0], a[1], b)
  9452. }
  9453. */
  9454.  
  9455. }
  9456.  
  9457.  
  9458. }
  9459. }
  9460.  
  9461.  
  9462.  
  9463. })();
  9464.  
  9465.  
  9466. FIX_yt_player && !isChatRoomURL && FIX_SHORTCUTKEYS > 0 && (async () => {
  9467. // keyboard shortcut keys controller
  9468.  
  9469. const _yt_player = await _yt_player_observable.obtain();
  9470.  
  9471. if (!_yt_player || typeof _yt_player !== 'object') return;
  9472.  
  9473. keyboardController(_yt_player);
  9474.  
  9475. })();
  9476.  
  9477. FIX_yt_player && !isChatRoomURL && (async () => {
  9478. // timer scheduling
  9479.  
  9480. const _yt_player = await _yt_player_observable.obtain();
  9481.  
  9482. if (!_yt_player || typeof _yt_player !== 'object') return;
  9483.  
  9484. let keyZqQu = getZqQu(_yt_player);
  9485.  
  9486. if (!keyZqQu) return;
  9487.  
  9488. const g = _yt_player
  9489. let k = keyZqQu
  9490.  
  9491. const gk = g[k];
  9492. if (typeof gk !== 'function') return;
  9493. const gkp = gk.prototype;
  9494.  
  9495. const extractKeysZqQu = () => {
  9496.  
  9497.  
  9498. let _keyeC = '';
  9499. try {
  9500. gkp.stop.call(new Proxy({
  9501. isActive: () => { }
  9502. }, {
  9503. set(target, prop, value) {
  9504. if (value === 0) _keyeC = prop;
  9505. return true;
  9506. }
  9507. }));
  9508. } catch (e) { }
  9509. if (!_keyeC) return;
  9510. const keyeC = _keyeC;
  9511.  
  9512. let keyC = ''; // this.C = this.ST.bind(this)
  9513. let keyhj = ''; // 1000ms
  9514. try {
  9515. gkp.start.call(new Proxy({
  9516. stop: () => { },
  9517. [keyeC]: 0,
  9518. }, {
  9519. get(target, prop) {
  9520. if (prop in target) return target[prop];
  9521. if (!keyC) {
  9522. keyC = prop;
  9523. return null; // throw error
  9524. }
  9525. else if (!keyhj) {
  9526. keyhj = prop;
  9527. }
  9528.  
  9529. }
  9530. }));
  9531. } catch (e) {
  9532. if (!keyC || !keyhj) {
  9533. console.log(e)
  9534. }
  9535. }
  9536.  
  9537. if (!keyC || !keyhj) return;
  9538. let keyST = '';
  9539. let keyj = '';
  9540. let keyB = '';
  9541. let keyxa = '';
  9542.  
  9543. const possibleKs = new Set();
  9544.  
  9545. for (const [k, v] of Object.entries(gkp)) {
  9546. if (k === 'stop' || k === 'start' || k === 'isActive' || k === 'constructor' || k === keyeC || k === keyC || k === keyhj) {
  9547. continue;
  9548. }
  9549. if (typeof v === 'function') {
  9550. const m = /this\.(\w+)\.call\(this\.(\w+)\)/.exec(v + '');
  9551. if (m) {
  9552. keyST = k;
  9553. keyj = m[1];
  9554. keyB = m[2];
  9555. } else {
  9556. possibleKs.add(k);
  9557. }
  9558. }
  9559. }
  9560.  
  9561. if (!keyST || !keyj || !keyB) return;
  9562.  
  9563. for (const k of possibleKs) {
  9564. if (k === keyST || k === keyj || k === keyB) {
  9565. continue;
  9566. }
  9567. const v = gkp[k];
  9568. if (typeof v === 'function' && (v + '').includes(`this.stop();delete this.${keyj};delete this.${keyB}`)) {
  9569. keyxa = k;
  9570. }
  9571. }
  9572.  
  9573. return [keyeC, keyC, keyhj, keyST, keyj, keyB, keyxa];
  9574.  
  9575. }
  9576.  
  9577. const keys = extractKeysZqQu();
  9578. if (!keys || !keys.length) return;
  9579. const [keyeC, keyC, keyhj, keyST, keyj, keyB, keyxa] = keys; // [timerId, binded executorFn, 1000ms, executorFn, dataJ, objectB, disposeFn]
  9580.  
  9581. if (!keyeC || !keyC || !keyhj || !keyST || !keyj || !keyB || !keyxa) return;
  9582.  
  9583. let disposeKeys = null;
  9584.  
  9585. gkp[keyxa] = function () {
  9586. // dispose
  9587. if (!disposeKeys) {
  9588. disposeKeys = Object.getOwnPropertyNames(this).filter(key => {
  9589. if (key != keyeC && key != keyC && key != keyhj && key != keyST && key != keyj && key != keyB && key != keyxa) {
  9590. const t = typeof this[key];
  9591. return t === 'undefined' || t === 'object'
  9592. }
  9593. return false;
  9594. });
  9595. }
  9596. for (const key of disposeKeys) {
  9597. const v = this[key];
  9598. if ((v || 0).length >= 1) v.length = 0; // function (){if(this.fn)for(;this.fn.length;)this.fn.shift()()}
  9599. }
  9600. if (this[keyeC] > 0) this.stop();
  9601. this[keyj] = null;
  9602. this[keyB] = null;
  9603. };
  9604.  
  9605. gkp.start = function (a) {
  9606. if (this[keyeC] > 0) this.stop();
  9607. const delay = void 0 !== a ? a : this[keyhj];
  9608. this[keyeC] = window.setTimeout(this[keyC], delay);
  9609. };
  9610. gkp.stop = function () {
  9611. if (this[keyeC] > 0) {
  9612. window.clearTimeout(this[keyeC]);
  9613. this[keyeC] = 0;
  9614. }
  9615. };
  9616.  
  9617. gkp.isActive = function () {
  9618. return this[keyeC] > 0;
  9619. };
  9620.  
  9621. gkp[keyST] = function () {
  9622. this.stop(); // this[keyeC] = 0;
  9623. const fn = this[keyj];
  9624. const obj = this[keyB];
  9625. let skip = false;
  9626. if (!fn) skip = true;
  9627. else if (IGNORE_bufferhealth_CHECK && obj) {
  9628. let m;
  9629. if ((m = obj[keyC]) instanceof Map || (m = obj[keyj]) instanceof Map) {
  9630. if (m.has("bufferhealth")) skip = true;
  9631. }
  9632. }
  9633. if (!skip) {
  9634. fn.call(obj);
  9635. }
  9636. };
  9637.  
  9638.  
  9639.  
  9640.  
  9641. /*
  9642.  
  9643. g.k.eC = 0;
  9644. g.k.xa = function() {
  9645. g.Qu.Vf.xa.call(this);
  9646. this.stop();
  9647. delete this.j;
  9648. delete this.B
  9649. }
  9650. ;
  9651. g.k.start = function(a) {
  9652. this.stop();
  9653. this.eC = g.gg(this.C, void 0 !== a ? a : this.hj)
  9654. }
  9655. ;
  9656. g.k.stop = function() {
  9657. this.isActive() && g.Sa.clearTimeout(this.eC);
  9658. this.eC = 0
  9659. }
  9660. ;
  9661. g.k.isActive = function() {
  9662. return 0 != this.eC
  9663. }
  9664. ;
  9665. g.k.ST = function() {
  9666. this.eC = 0;
  9667. this.j && this.j.call(this.B)
  9668. }
  9669. ;
  9670. */
  9671.  
  9672.  
  9673.  
  9674.  
  9675. })();
  9676.  
  9677. FIX_Animation_n_timeline && (async () => {
  9678.  
  9679. const [timeline, Animation] = await Promise.all([timelineObservable.obtain(), animationObservable.obtain()]);
  9680.  
  9681. if (!timeline || !Animation) return;
  9682.  
  9683. const aniProto = Animation.prototype;
  9684. // aniProto.sequenceNumber = 0; // native YouTube engine bug - sequenceNumber is not set
  9685.  
  9686. const getXroto = (x) => {
  9687. try {
  9688. return x.__proto__;
  9689. } catch (e) { }
  9690. return null;
  9691. }
  9692. const timProto = getXroto(timeline);
  9693. if (!timProto) return;
  9694. if (
  9695. (
  9696. typeof timProto.getAnimations === 'function' && typeof timProto.play === 'function' &&
  9697. typeof timProto._discardAnimations === 'function' && typeof timProto._play === 'function' &&
  9698. typeof timProto._updateAnimationsPromises === 'function' && !timProto.nofCQ &&
  9699. typeof aniProto._updatePromises === 'function' && !aniProto.nofYH
  9700. )
  9701.  
  9702. ) {
  9703.  
  9704. timProto.nofCQ = 1;
  9705. aniProto.nofYH = 1;
  9706.  
  9707. const originalAnimationsWithPromises = ((_updateAnimationsPromises) => {
  9708.  
  9709.  
  9710. /*
  9711. v.animationsWithPromises = v.animationsWithPromises.filter(function (c) {
  9712. return c._updatePromises();
  9713. });
  9714. */
  9715.  
  9716. const p = Array.prototype.filter;
  9717.  
  9718. let res = null;
  9719. Array.prototype.filter = function () {
  9720.  
  9721. res = this;
  9722. return this;
  9723.  
  9724. };
  9725.  
  9726. _updateAnimationsPromises.call({});
  9727.  
  9728. Array.prototype.filter = p;
  9729.  
  9730. if (res && typeof res.length === 'number') {
  9731. /** @type {any[]} */
  9732. const _res = res;
  9733. return _res;
  9734. }
  9735.  
  9736.  
  9737. return null;
  9738.  
  9739.  
  9740.  
  9741.  
  9742. })(timProto._updateAnimationsPromises);
  9743.  
  9744. if (!originalAnimationsWithPromises || typeof originalAnimationsWithPromises.length !== 'number') return;
  9745.  
  9746. // console.log('originalAnimationsWithPromises', originalAnimationsWithPromises)
  9747.  
  9748. aniProto._updatePromises31 = aniProto._updatePromises;
  9749.  
  9750. /*
  9751. aniProto._updatePromises = function(){
  9752. console.log('eff',this._oldPlayState, this.playState)
  9753. return this._updatePromises31.apply(this, arguments)
  9754. }
  9755. */
  9756.  
  9757. aniProto._updatePromises = function () {
  9758. var oldPlayState = this._oldPlayState;
  9759. var newPlayState = this.playState;
  9760. // console.log('ett', oldPlayState, newPlayState)
  9761. if (newPlayState !== oldPlayState) {
  9762. this._oldPlayState = newPlayState;
  9763. if (this._readyPromise) {
  9764. if ("idle" == newPlayState) {
  9765. this._rejectReadyPromise();
  9766. this._readyPromise = void 0;
  9767. } else if ("pending" == oldPlayState) {
  9768. this._resolveReadyPromise();
  9769. } else if ("pending" == newPlayState) {
  9770. this._readyPromise = void 0;
  9771. }
  9772. }
  9773. if (this._finishedPromise) {
  9774. if ("idle" == newPlayState) {
  9775. this._rejectFinishedPromise();
  9776. this._finishedPromise = void 0;
  9777. } else if ("finished" == newPlayState) {
  9778. this._resolveFinishedPromise();
  9779. } else if ("finished" == oldPlayState) {
  9780. this._finishedPromise = void 0;
  9781. }
  9782. }
  9783. }
  9784. return this._readyPromise || this._finishedPromise;
  9785. };
  9786.  
  9787.  
  9788. let restartWebAnimationsNextTickFlag = false;
  9789.  
  9790. const looperMethodT = () => {
  9791.  
  9792. const runnerFn = (hRes) => {
  9793. var b = timeline;
  9794. b.currentTime = hRes;
  9795. b._discardAnimations();
  9796. if (0 == b._animations.length) {
  9797. restartWebAnimationsNextTickFlag = false;
  9798. } else {
  9799. getRafPromise().then(runnerFn);
  9800. }
  9801. }
  9802.  
  9803. const restartWebAnimationsNextTick = () => {
  9804. if (!restartWebAnimationsNextTickFlag) {
  9805. restartWebAnimationsNextTickFlag = true;
  9806. getRafPromise().then(runnerFn);
  9807. }
  9808. }
  9809.  
  9810. return { restartWebAnimationsNextTick }
  9811. };
  9812.  
  9813.  
  9814. const looperMethodN = () => {
  9815.  
  9816. const acs = document.createElement('a-f');
  9817. acs.id = 'a-f';
  9818.  
  9819. if (!document.getElementById('afscript')) {
  9820. const style = document.createElement('style');
  9821. style.id = 'afscript';
  9822. style.textContent = `
  9823. @keyFrames aF1 {
  9824. 0% {
  9825. order: 0;
  9826. }
  9827. 100% {
  9828. order: 1;
  9829. }
  9830. }
  9831. #a-f[id] {
  9832. visibility: collapse !important;
  9833. position: fixed !important;
  9834. display: block !important;
  9835. top: -100px !important;
  9836. left: -100px !important;
  9837. margin:0 !important;
  9838. padding:0 !important;
  9839. outline:0 !important;
  9840. border:0 !important;
  9841. z-index:-1 !important;
  9842. width: 0px !important;
  9843. height: 0px !important;
  9844. contain: strict !important;
  9845. pointer-events: none !important;
  9846. animation: 1ms steps(2, jump-none) 0ms infinite alternate forwards running aF1 !important;
  9847. }
  9848. `;
  9849. (document.head || document.documentElement).appendChild(style);
  9850. }
  9851.  
  9852. document.documentElement.insertBefore(acs, document.documentElement.firstChild);
  9853.  
  9854. const _onanimationiteration = function (evt) {
  9855. const hRes = evt.timeStamp;
  9856. var b = timeline;
  9857. b.currentTime = hRes;
  9858. b._discardAnimations();
  9859. if (0 == b._animations.length) {
  9860. restartWebAnimationsNextTickFlag = false;
  9861. acs.onanimationiteration = null;
  9862. } else {
  9863. acs.onanimationiteration = _onanimationiteration;
  9864. }
  9865.  
  9866. }
  9867.  
  9868.  
  9869.  
  9870. const restartWebAnimationsNextTick = () => {
  9871. if (!restartWebAnimationsNextTickFlag) {
  9872. restartWebAnimationsNextTickFlag = true;
  9873. acs.onanimationiteration = _onanimationiteration;
  9874.  
  9875. }
  9876. }
  9877.  
  9878. return { restartWebAnimationsNextTick }
  9879. };
  9880.  
  9881.  
  9882.  
  9883. const { restartWebAnimationsNextTick } = ('onanimationiteration' in document.documentElement) ? looperMethodN() : looperMethodT();
  9884.  
  9885.  
  9886. // console.log(571, timProto);
  9887. timProto._play = function (c) {
  9888. c = new Animation(c, this);
  9889. this._animations.push(c);
  9890. restartWebAnimationsNextTick();
  9891. c._updatePromises();
  9892. c._animation.play();
  9893. c._updatePromises();
  9894. return c
  9895. }
  9896.  
  9897. const animationsWithPromisesMap = new Set(originalAnimationsWithPromises);
  9898. originalAnimationsWithPromises.length = 0;
  9899. originalAnimationsWithPromises.push = null;
  9900. originalAnimationsWithPromises.splice = null;
  9901. originalAnimationsWithPromises.slice = null;
  9902. originalAnimationsWithPromises.indexOf = null;
  9903. originalAnimationsWithPromises.unshift = null;
  9904. originalAnimationsWithPromises.shift = null;
  9905. originalAnimationsWithPromises.pop = null;
  9906. originalAnimationsWithPromises.filter = null;
  9907. originalAnimationsWithPromises.forEach = null;
  9908. originalAnimationsWithPromises.map = null;
  9909.  
  9910.  
  9911. const _updateAnimationsPromises = () => {
  9912. animationsWithPromisesMap.forEach(c => {
  9913. if (!c._updatePromises()) animationsWithPromisesMap.delete(c);
  9914. });
  9915. /*
  9916. v.animationsWithPromises = v.animationsWithPromises.filter(function (c) {
  9917. return c._updatePromises();
  9918. });
  9919. */
  9920. }
  9921.  
  9922. timProto._updateAnimationsPromises31 = timProto._updateAnimationsPromises;
  9923.  
  9924. timProto._updateAnimationsPromises = _updateAnimationsPromises;
  9925.  
  9926. delete timProto._updateAnimationsPromises;
  9927. Object.defineProperty(timProto, '_updateAnimationsPromises', {
  9928. get() {
  9929. if (animationsWithPromisesMap.size === 0) return nilFn;
  9930. return _updateAnimationsPromises;
  9931. },
  9932. set(nv) {
  9933. delete this._updateAnimationsPromises;
  9934. this._updateAnimationsPromises = nv;
  9935. },
  9936. enumerable: true,
  9937. configurable: true,
  9938. });
  9939.  
  9940.  
  9941. let pdFinished = Object.getOwnPropertyDescriptor(aniProto, 'finished');
  9942. aniProto.__finished_native_get__ = pdFinished.get;
  9943. if (typeof pdFinished.get === 'function' && !pdFinished.set && pdFinished.configurable === true && pdFinished.enumerable === true) {
  9944.  
  9945.  
  9946. Object.defineProperty(aniProto, 'finished', {
  9947. get() {
  9948. this._finishedPromise || (!animationsWithPromisesMap.has(this) && animationsWithPromisesMap.add(this),
  9949. this._finishedPromise = new Promise((resolve, reject) => {
  9950. this._resolveFinishedPromise = function () {
  9951. resolve(this)
  9952. };
  9953. this._rejectFinishedPromise = function () {
  9954. reject({
  9955. type: DOMException.ABORT_ERR,
  9956. name: "AbortError"
  9957. })
  9958. };
  9959. }),
  9960. "finished" == this.playState && this._resolveFinishedPromise());
  9961. return this._finishedPromise
  9962. },
  9963. set: undefined,
  9964. enumerable: true,
  9965. configurable: true
  9966. });
  9967.  
  9968. }
  9969.  
  9970.  
  9971.  
  9972. let pdReady = Object.getOwnPropertyDescriptor(aniProto, 'ready');
  9973. aniProto.__ready_native_get__ = pdReady.get;
  9974. if (typeof pdReady.get === 'function' && !pdReady.set && pdReady.configurable === true && pdReady.enumerable === true) {
  9975.  
  9976. Object.defineProperty(aniProto, 'ready', {
  9977. get() {
  9978. this._readyPromise || (!animationsWithPromisesMap.has(this) && animationsWithPromisesMap.add(this),
  9979. this._readyPromise = new Promise((resolve, reject) => {
  9980. this._resolveReadyPromise = function () {
  9981. resolve(this)
  9982. };
  9983. this._rejectReadyPromise = function () {
  9984. reject({
  9985. type: DOMException.ABORT_ERR,
  9986. name: "AbortError"
  9987. })
  9988. };
  9989. }),
  9990. "pending" !== this.playState && this._resolveReadyPromise());
  9991. return this._readyPromise
  9992. },
  9993. set: undefined,
  9994. enumerable: true,
  9995. configurable: true
  9996. });
  9997.  
  9998. }
  9999.  
  10000.  
  10001. if (IGNORE_bindAnimationForCustomEffect && typeof aniProto._rebuildUnderlyingAnimation === 'function' && !aniProto._rebuildUnderlyingAnimation21 && aniProto._rebuildUnderlyingAnimation.length === 0) {
  10002.  
  10003. aniProto._rebuildUnderlyingAnimation21 = aniProto._rebuildUnderlyingAnimation;
  10004. const _rebuildUnderlyingAnimation = function () {
  10005. // if (isNaN(this._sequenceNumber)) return; // do not rebuild underlying animation if native animation is used.
  10006. this.effect && this.effect._onsample && (this.effect._onsample = null);
  10007. return this._rebuildUnderlyingAnimation21();
  10008. }
  10009. aniProto._rebuildUnderlyingAnimation = _rebuildUnderlyingAnimation;
  10010. // delete aniProto._rebuildUnderlyingAnimation;
  10011. // Object.defineProperty(aniProto, '_rebuildUnderlyingAnimation', {
  10012. // get() {
  10013. // if (isNaN(this._sequenceNumber)) return nilFn;
  10014. // return this._rebuildUnderlyingAnimation21;
  10015. // },
  10016. // set(nv) {
  10017. // delete this._rebuildUnderlyingAnimation;
  10018. // this._rebuildUnderlyingAnimation = nv;
  10019. // },
  10020. // enumerable: true,
  10021. // configurable: true
  10022. // });
  10023. }
  10024.  
  10025.  
  10026. /*
  10027.  
  10028.  
  10029. function f(c) {
  10030. var b = v.timeline;
  10031. b.currentTime = c;
  10032. b._discardAnimations();
  10033. 0 == b._animations.length ? d = !1 : requestAnimationFrame(f)
  10034. }
  10035. var h = window.requestAnimationFrame;
  10036. window.requestAnimationFrame = function(c) {
  10037. return h(function(b) {
  10038. v.timeline._updateAnimationsPromises();
  10039. c(b);
  10040. v.timeline._updateAnimationsPromises()
  10041. })
  10042. }
  10043. ;
  10044. v.AnimationTimeline = function() {
  10045. this._animations = [];
  10046. this.currentTime = void 0
  10047. }
  10048. ;
  10049. v.AnimationTimeline.prototype = {
  10050. getAnimations: function() {
  10051. this._discardAnimations();
  10052. return this._animations.slice()
  10053. },
  10054. _updateAnimationsPromises: function() {
  10055. v.animationsWithPromises = v.animationsWithPromises.filter(function(c) {
  10056. return c._updatePromises()
  10057. })
  10058. },
  10059. _discardAnimations: function() {
  10060. this._updateAnimationsPromises();
  10061. this._animations = this._animations.filter(function(c) {
  10062. return "finished" != c.playState && "idle" != c.playState
  10063. })
  10064. },
  10065. _play: function(c) {
  10066. c = new v.Animation(c,this);
  10067. this._animations.push(c);
  10068. v.restartWebAnimationsNextTick();
  10069. c._updatePromises();
  10070. c._animation.play();
  10071. c._updatePromises();
  10072. return c
  10073. },
  10074. play: function(c) {
  10075. c && c.remove();
  10076. return this._play(c)
  10077. }
  10078. };
  10079. var d = !1;
  10080. v.restartWebAnimationsNextTick = function() {
  10081. d || (d = !0,
  10082. requestAnimationFrame(f))
  10083. }
  10084. ;
  10085. var a = new v.AnimationTimeline;
  10086. v.timeline = a;
  10087. try {
  10088. Object.defineProperty(window.document, "timeline", {
  10089. configurable: !0,
  10090. get: function() {
  10091. return a
  10092. }
  10093. })
  10094. } catch (c) {}
  10095. try {
  10096. window.document.timeline = a
  10097. } catch (c) {}
  10098.  
  10099. */
  10100.  
  10101.  
  10102.  
  10103. /*
  10104.  
  10105. var g = window.getComputedStyle;
  10106. Object.defineProperty(window, "getComputedStyle", {
  10107. configurable: !0,
  10108. enumerable: !0,
  10109. value: function() {
  10110. v.timeline._updateAnimationsPromises();
  10111. var e = g.apply(this, arguments);
  10112. h() && (e = g.apply(this, arguments));
  10113. v.timeline._updateAnimationsPromises();
  10114. return e
  10115. }
  10116. });
  10117.  
  10118. */
  10119.  
  10120.  
  10121.  
  10122.  
  10123. }
  10124.  
  10125.  
  10126.  
  10127.  
  10128. })();
  10129.  
  10130. !isUrlInEmbed && Promise.resolve().then(() => {
  10131.  
  10132. // ==================================== FIX_avoid_incorrect_video_meta ====================================
  10133.  
  10134.  
  10135.  
  10136. class LimitedSizeSet extends Set {
  10137. constructor(n) {
  10138. super();
  10139. this.limit = n;
  10140. }
  10141.  
  10142. add(key) {
  10143. if (!super.has(key)) {
  10144. super.add(key);
  10145. let n = super.size - this.limit;
  10146. if (n > 0) {
  10147. const iterator = super.values();
  10148. do {
  10149. const firstKey = iterator.next().value; // Get the first (oldest) key
  10150. super.delete(firstKey); // Delete the oldest key
  10151. } while (--n > 0)
  10152. }
  10153. }
  10154. }
  10155.  
  10156. removeAdd(key) {
  10157. super.delete(key);
  10158. this.add(key);
  10159. }
  10160.  
  10161. }
  10162.  
  10163. // const wk3 = new WeakMap();
  10164.  
  10165. // let mtxVideoId = '';
  10166. // let aje3 = [];
  10167. const mfvContinuationRecorded = new LimitedSizeSet(8); // record all success continuation keys
  10168. const mfyContinuationIgnored = new LimitedSizeSet(8); // ignore continuation keys by copying the keys in the past
  10169. let mtzlastAllowedContinuation = ''; // the key stored at the last success; clear when scheduling changes
  10170. let mtzCount = 0; // the key keeps unchanged
  10171. // let mjtNextMainKey = '';
  10172. let mjtRecordedPrevKey = ''; // the key stored at the last success (no clear)
  10173. let mjtLockPreviousKey = ''; // the key before fetch() should be discarded. (uncertain continuation)
  10174. let mbCId322 = 0; // cid for delay fetchUpdatedMetadata
  10175. // let allowNoDelay322=false;
  10176. let mbDelayBelowNCalls = 0; // after N calls, by pass delay; reset when scheduling changes
  10177.  
  10178. let mpKey22 = ''; // last success continutation key & url pair
  10179. let mpUrl22 = ''; // last success continutation key & url pair
  10180. let mpKey21 = ''; // latest requested continutation key & url pair
  10181. let mpUrl21 = ''; // latest requested continutation key & url pair
  10182.  
  10183.  
  10184. async function sha1Hex(message) {
  10185. const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array
  10186. const hashBuffer = await crypto.subtle.digest("SHA-1", msgUint8); // hash the message
  10187. const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array
  10188. const hashHex = hashArray
  10189. .map((b) => b.toString(16).padStart(2, "0"))
  10190. .join(""); // convert bytes to hex string
  10191. return hashHex;
  10192. }
  10193.  
  10194. async function continuationLog(a, ...args) {
  10195. let b = a;
  10196. try {
  10197. if (advanceLogging) b = await sha1Hex(a);
  10198. let c = args.map(e => {
  10199. return e === a ? b : e
  10200. });
  10201. console.log(...c)
  10202. } catch (e) { console.warn(e) }
  10203. }
  10204.  
  10205. function copyPreviousContiuationToIgnored374(toClearRecorded) {
  10206.  
  10207.  
  10208. if (mfvContinuationRecorded.length > 0) {
  10209. for (const [e, d] of mfvContinuationRecorded) {
  10210. mfyContinuationIgnored.removeAdd(e);
  10211. }
  10212. toClearRecorded && mfvContinuationRecorded.clear();
  10213. }
  10214.  
  10215. }
  10216.  
  10217. function setup_ytTaskEmitterBehavior_TaskMgr374(taskMgr) {
  10218.  
  10219. const tmProto = taskMgr.constructor.prototype;
  10220. if (tmProto && typeof tmProto.addJob === 'function' && tmProto.addJob.length === 3 && typeof tmProto.cancelJob === 'function' && tmProto.cancelJob.length === 1) {
  10221.  
  10222. if (!tmProto.addJob714) {
  10223.  
  10224. tmProto.addJob714 = tmProto.addJob;
  10225.  
  10226. tmProto.addJob = function (a, b, c) {
  10227. const jobId = this.addJob714(a, b, c);
  10228. if (jobId > 0) {
  10229. // const ez = wk3.get(this);
  10230. // const dz = ez ? ez.data?.updatedMetadataEndpoint?.updatedMetadataEndpoint : null;
  10231. // aje3.push({mtx, jobId, a,b,c, element: this, dz, data: (ez?.data || null) })
  10232.  
  10233. this.__lastJobId863__ = jobId;
  10234. }
  10235. return jobId;
  10236. }
  10237.  
  10238. }
  10239.  
  10240. if (!tmProto.cancelJob714) {
  10241.  
  10242. tmProto.cancelJob714 = tmProto.cancelJob;
  10243.  
  10244. tmProto.cancelJob = function (a) {
  10245. const res = this.cancelJob714(a);
  10246. // if (a > 0) {
  10247. // for (const e of aje3) {
  10248. // if (e.jobId === a) e.cancelled = true;
  10249. // }
  10250. // }
  10251. return res;
  10252. }
  10253.  
  10254. }
  10255.  
  10256. }
  10257. }
  10258.  
  10259.  
  10260. const FIX_avoid_incorrect_video_meta_bool = FIX_avoid_incorrect_video_meta && isPrepareCachedV && check_for_set_key_order && !isChatRoomURL;
  10261.  
  10262.  
  10263. FIX_avoid_incorrect_video_meta_bool && whenCEDefined('ytd-video-primary-info-renderer').then(() => {
  10264. let dummy;
  10265. let cProto;
  10266. // let mc = 4;
  10267. // dummy = await observablePromise(() => {
  10268. // const r = document.querySelector('ytd-video-primary-info-renderer');
  10269. // if (!r) return;
  10270. // let cProto = insp(r).constructor.prototype;
  10271. // if (cProto.fetchUpdatedMetadata) return r;
  10272. // if (--mc < 0) return -1;
  10273. // return null;
  10274. // }).obtain();
  10275. dummy = document.createElement('ytd-video-primary-info-renderer');
  10276. if (!(dummy instanceof Element)) return;
  10277. // console.log(5022, dummy)
  10278. cProto = insp(dummy).constructor.prototype;
  10279.  
  10280. cProto.__getEmittorTaskMgr859__ = function () {
  10281. let taskMgr_ = null;
  10282. try {
  10283. taskMgr_ = (this.ytTaskEmitterBehavior || 0).getTaskManager() || null;
  10284. } catch (e) { }
  10285. return taskMgr_;
  10286. }
  10287. if (typeof cProto.fetchUpdatedMetadata === 'function' && cProto.fetchUpdatedMetadata.length === 1 && !cProto.fetchUpdatedMetadata717) {
  10288. // console.log(1234, cProto, cProto.is)
  10289. cProto.fetchUpdatedMetadata717 = cProto.fetchUpdatedMetadata;
  10290.  
  10291. let c_;
  10292. cProto.fetchUpdatedMetadata718 = function (a) {
  10293. // delay or immediate call the actual fetchUpdatedMetadata
  10294.  
  10295. let doImmediately = false;
  10296. if (a && typeof a === 'string' && mjtRecordedPrevKey && mjtRecordedPrevKey === mpKey22 && a === mpKey22 && (!pageSetupVideoId || pageSetupVideoId !== mpUrl22)) {
  10297.  
  10298. if (!pageSetupVideoId && videoPlayingY.videoId === mpUrl22) doImmediately = true;
  10299.  
  10300. } else if (typeof a !== 'string' || mbDelayBelowNCalls > 3 || !mpKey22 || (mpKey22 === a && mpKey22 !== mjtLockPreviousKey) || (mjtLockPreviousKey && mjtLockPreviousKey !== a)) {
  10301.  
  10302. doImmediately = true;
  10303.  
  10304. }
  10305.  
  10306. if (mbCId322) {
  10307. clearTimeout(mbCId322);
  10308. mbCId322 = 0;
  10309. }
  10310.  
  10311. if (doImmediately) return this.fetchUpdatedMetadata717(a);
  10312.  
  10313. let delay = mjtLockPreviousKey === a ? 8000 : 800;
  10314.  
  10315. mbCId322 = setTimeout(() => {
  10316. this.fetchUpdatedMetadata717(a);
  10317. }, delay);
  10318.  
  10319. console.log('[yt-js-engine-tamer]', '5190 delayed fetchUpdatedMetadata', delay);
  10320.  
  10321. }
  10322.  
  10323. cProto.fetchUpdatedMetadata = function (a) {
  10324.  
  10325. if (!pageSetupState) {
  10326. if (c_) clearTimeout(c_);
  10327. c_ = setTimeout(() => {
  10328. this.fetchUpdatedMetadata718(a);
  10329. }, 300);
  10330. return;
  10331. }
  10332.  
  10333. // pageSetupState == 0
  10334.  
  10335. try {
  10336.  
  10337. mbDelayBelowNCalls++;
  10338.  
  10339. if (arguments.length > 1 || !(a === undefined || (typeof a === 'string' && a))) {
  10340. console.warn("CAUTION: fetchUpdatedMetadata coding might have to be updated.");
  10341. }
  10342.  
  10343. // console.log('fum377', a)
  10344. if (typeof a === 'string' && mfyContinuationIgnored.has(a)) {
  10345. console.log('[yt-js-engine-tamer]', '5040 skip fetchUpdatedMetadata', a);
  10346. return;
  10347. }
  10348.  
  10349. if (!a && (this.data || 0).updatedMetadataEndpoint) {
  10350. if (mjtRecordedPrevKey && mjtLockPreviousKey !== mjtRecordedPrevKey) {
  10351. mjtLockPreviousKey = mjtRecordedPrevKey;
  10352. LOG_FETCHMETA_UPDATE && continuationLog(mjtLockPreviousKey, '5150 Lock Key', mjtLockPreviousKey);
  10353. }
  10354. // mjtNextMainKey = true;
  10355. mtzlastAllowedContinuation = '';
  10356. mtzCount = 0;
  10357. // allowNoDelay322 = false;
  10358. // fetch new metadata, cancel all previous continuations
  10359. copyPreviousContiuationToIgnored374(true);
  10360. } else if (typeof a === 'string') {
  10361. const videoPlayingId = videoPlayingY.videoId;
  10362.  
  10363. // if(mjtNextMainKey === true) mjtNextMainKey = a;
  10364.  
  10365. let update21 = !!pageSetupVideoId;
  10366. if (mpKey22 === a && mpUrl22 === videoPlayingId && mpUrl22 && videoPlayingId && (!pageSetupVideoId || pageSetupVideoId === videoPlayingId)) {
  10367. update21 = true;
  10368. } else if (mpKey22 === a && mpUrl22 !== pageSetupVideoId) {
  10369. LOG_FETCHMETA_UPDATE && continuationLog(mpKey22, '5060 mpUrl22 mismatched', mpKey22, mpUrl22, pageSetupVideoId || '(null)', videoPlayingId || '(null)');
  10370. return;
  10371. }
  10372. if (update21) {
  10373. mpKey21 = a;
  10374. mpUrl21 = pageSetupVideoId || videoPlayingId;
  10375. }
  10376.  
  10377. if (!mfvContinuationRecorded.has(a)) mfvContinuationRecorded.add(a);
  10378. }
  10379. LOG_FETCHMETA_UPDATE && continuationLog(a, '5180 fetchUpdatedMetadata\t', a, pageSetupVideoId || '(null)', videoPlayingY.videoId || '(null)');
  10380. // if (!pageSetupVideoId && typeof a === 'string' && a.length > 40) return; // ignore incorrect continuation
  10381. // if(a === mjtNextMainKey) allowNoDelay322 = false;
  10382. return this.fetchUpdatedMetadata718(a);
  10383.  
  10384. } catch (e) {
  10385. console.log('Code Error in fetchUpdatedMetadata', e);
  10386. }
  10387. return this.fetchUpdatedMetadata717(a)
  10388. }
  10389. }
  10390.  
  10391.  
  10392. if (typeof cProto.scheduleInitialUpdatedMetadataRequest === 'function' && cProto.scheduleInitialUpdatedMetadataRequest.length === 0 && !cProto.scheduleInitialUpdatedMetadataRequest717) {
  10393. // console.log(1234, cProto, cProto.is)
  10394. cProto.scheduleInitialUpdatedMetadataRequest717 = cProto.scheduleInitialUpdatedMetadataRequest;
  10395. let mJob = null;
  10396.  
  10397. cProto.scheduleInitialUpdatedMetadataRequest = function () {
  10398.  
  10399. try {
  10400.  
  10401. if (arguments.length > 0) {
  10402. console.warn("CAUTION: scheduleInitialUpdatedMetadataRequest coding might have to be updated.");
  10403. }
  10404. // mfy = mfv;
  10405.  
  10406. // mjtNextMainKey = '';
  10407. mtzlastAllowedContinuation = '';
  10408. mtzCount = 0;
  10409. if (mbCId322) {
  10410. clearTimeout(mbCId322);
  10411. mbCId322 = 0;
  10412. }
  10413. mbDelayBelowNCalls = 0;
  10414. // allowNoDelay322 = false;
  10415. copyPreviousContiuationToIgnored374(true);
  10416.  
  10417. const taskMgr = this.__getEmittorTaskMgr859__();
  10418. if (FIX_avoid_incorrect_video_meta_emitterBehavior && taskMgr && !taskMgr.addJob714 && taskMgr.addJob && taskMgr.cancelJob) setup_ytTaskEmitterBehavior_TaskMgr374(taskMgr);
  10419. if (FIX_avoid_incorrect_video_meta_emitterBehavior && taskMgr && !taskMgr.addJob714) {
  10420. console.log('[yt-js-engine-tamer]', 'scheduleInitialUpdatedMetadataRequest error 507');
  10421. }
  10422.  
  10423. // prevent depulicated schedule job by clearing previous JobId
  10424. if (taskMgr && typeof taskMgr.addLowPriorityJob === 'function' && taskMgr.addLowPriorityJob.length === 2 && typeof taskMgr.cancelJob === 'function' && taskMgr.cancelJob.length === 1) {
  10425.  
  10426. let res;
  10427.  
  10428. if (mJob) {
  10429. const job = mJob;
  10430. mJob = null;
  10431. console.log('cancelJob', job)
  10432. taskMgr.cancelJob(job); // clear previous [Interval Meta Update] job
  10433. // p.cancelJob(a,b);
  10434. }
  10435.  
  10436. // const updatedMetadataEndpoint = this.data?.updatedMetadataEndpoint?.updatedMetadataEndpoint
  10437.  
  10438. let pza = taskMgr.__lastJobId863__;
  10439. try { res = this.scheduleInitialUpdatedMetadataRequest717(); } catch (e) { }
  10440. let pzb = taskMgr.__lastJobId863__
  10441. if (pza !== pzb) {
  10442. mJob = pzb; // set [Interval Meta Update] jobId
  10443. }
  10444.  
  10445. // if (updatedMetadataEndpoint && updatedMetadataEndpoint.videoId) {
  10446. // mtxVideoId = updatedMetadataEndpoint.videoId || ''; // set the current target VideoId
  10447. // } else {
  10448. // mtxVideoId = ''; // sometimes updatedMetadataEndpoint is not ready
  10449. // }
  10450.  
  10451. return res;
  10452.  
  10453. } else {
  10454. console.log('[yt-js-engine-tamer]', 'scheduleInitialUpdatedMetadataRequest error 601');
  10455. }
  10456.  
  10457. } catch (e) {
  10458. console.log('Code Error in scheduleInitialUpdatedMetadataRequest', e);
  10459. }
  10460.  
  10461.  
  10462. return this.scheduleInitialUpdatedMetadataRequest717();
  10463. }
  10464. }
  10465.  
  10466.  
  10467. });
  10468.  
  10469. FIX_avoid_incorrect_video_meta_bool && promiseForYtActionCalled.then((ytAppDom) => {
  10470. let dummy;
  10471. let cProto;
  10472. dummy = ytAppDom;
  10473. if (!(dummy instanceof Element)) return;
  10474. cProto = insp(dummy).constructor.prototype;
  10475. if (typeof cProto.sendServiceAjax_ === 'function' && cProto.sendServiceAjax_.length === 4 && !cProto.sendServiceAjax717_) {
  10476. // console.log(1234, cProto, cProto.is);
  10477. // cProto.handleServiceRequest717_ = cProto.handleServiceRequest_;
  10478. // cProto.handleServiceRequest_ = function (a, b, c, d) {
  10479. // console.log(123401, arguments);
  10480. // return this.handleServiceRequest717_(a, b, c, d);
  10481. // }
  10482.  
  10483. // cProto.handleServiceRequest717_ = cProto.handleServiceRequest_;
  10484.  
  10485. // cProto.handleServiceRequest_ = function(a,b,c,d){
  10486. // console.log(59901, a?.is, b?.updatedMetadataEndpoint?.videoId, c?.continuation)
  10487. // if(a?.is === 'ytd-video-primary-info-renderer' && b?.updatedMetadataEndpoint?.videoId && c?.continuation && typeof c?.continuation ==='string'){
  10488. // console.log('mfv', c.continuation);
  10489. // mfv.add( c.continuation);
  10490. // }
  10491. // return this.handleServiceRequest717_(a,b,c,d);
  10492. // }
  10493.  
  10494. function extraArguments322(a, b, c) {
  10495. let is = (a || 0).is;
  10496. let videoId = ((b || 0).updatedMetadataEndpoint || 0).videoId;
  10497. let continuation = (c || 0).continuation;
  10498. if (typeof is !== 'string') is = null;
  10499. if (typeof videoId !== 'string') videoId = null;
  10500. if (typeof continuation !== 'string') continuation = null;
  10501. return { is, videoId, continuation };
  10502. }
  10503.  
  10504. cProto.sendServiceAjax717_ = cProto.sendServiceAjax_;
  10505. cProto.sendServiceAjax_ = function (a, b, c, d) {
  10506.  
  10507. // console.log(8001)
  10508. try {
  10509.  
  10510. const { is, videoId, continuation } = extraArguments322(a, b, c);
  10511.  
  10512. if ((videoId || continuation) && (is !== 'ytd-video-primary-info-renderer')) {
  10513. console.warn("CAUTION: sendServiceAjax_ coding might have to be updated.");
  10514. }
  10515.  
  10516. if (pageSetupVideoId && videoId && continuation) {
  10517. if (mpKey21 && mpUrl21 && mpKey21 === continuation && mpUrl21 !== pageSetupVideoId) {
  10518. mfyContinuationIgnored.removeAdd(continuation);
  10519. mfvContinuationRecorded.delete(continuation);
  10520. return;
  10521. }
  10522. }
  10523.  
  10524. if (mjtLockPreviousKey && mjtLockPreviousKey !== continuation && continuation) {
  10525. copyPreviousContiuationToIgnored374(false);
  10526. mfyContinuationIgnored.delete(continuation);
  10527. mfvContinuationRecorded.removeAdd(continuation);
  10528. mfyContinuationIgnored.removeAdd(mjtLockPreviousKey);
  10529. mfvContinuationRecorded.delete(mjtLockPreviousKey);
  10530. mjtLockPreviousKey = '';
  10531. }
  10532. // if (mjtNextMainKey === continuation) {
  10533. // copyPreviousContiuationToIgnored(false);
  10534. // mfyContinuationIgnored.delete(continuation);
  10535. // mfvContinuationRecorded.add(continuation);
  10536. // }
  10537.  
  10538.  
  10539. if (mfyContinuationIgnored && continuation) {
  10540. if (mfyContinuationIgnored.has(continuation)) {
  10541. LOG_FETCHMETA_UPDATE && continuationLog(continuation, '5260 matched01', continuation)
  10542. return;
  10543. }
  10544. }
  10545.  
  10546. // console.log(59902, a?.is, b,c,d)
  10547. // console.log(59903, a?.is, b?.updatedMetadataEndpoint?.videoId, c?.continuation)
  10548. if (is === 'ytd-video-primary-info-renderer' && videoId && continuation && !mfvContinuationRecorded.has(continuation)) {
  10549. // console.log('mfv377', continuation);
  10550. mfvContinuationRecorded.add(continuation);
  10551. }
  10552.  
  10553. // if (videoId) {
  10554. // if (!pageSetupVideoId) return; // ignore page not ready
  10555. // // if (mtxVideoId && b.updatedMetadataEndpoint.videoId !== mtxVideoId) return; // ignore videoID not matched
  10556. // if (videoId !== pageSetupVideoId) {
  10557. // return;
  10558. // }
  10559. // }
  10560.  
  10561. } catch (e) {
  10562. console.log('Coding Error in sendServiceAjax_', e)
  10563. }
  10564. // console.log(8002)
  10565. // console.log(123402, arguments);
  10566. // console.log(5162, 'a',a?.is,'b',b,'c',c,'d',d);
  10567.  
  10568. // console.log(5211, b?.updatedMetadataEndpoint?.kdkw33);
  10569. // if(b &&b.updatedMetadataEndpoint && !b.updatedMetadataEndpoint.kdkw33){
  10570. // b.updatedMetadataEndpoint = new Proxy(b.updatedMetadataEndpoint, {
  10571. // get(target, prop, receiver){
  10572. // console.log('xxs99', target.videoId, mtx)
  10573. // if(prop ==='kdkw33') return 1;
  10574. // console.log(3322, prop, target)
  10575. // if(prop === 'initialDelayMs') {
  10576. // throw new Error("ABCC");
  10577. // }
  10578. // return target[prop];
  10579. // },
  10580. // set(target, prop, value, receiver){
  10581.  
  10582. // if(prop ==='kdkw33') return true;
  10583. // target[prop]=value;
  10584. // return true;
  10585. // }
  10586. // });
  10587. // }
  10588. // console.log(5533, b?.updatedMetadataEndpoint?.kdkw33)
  10589. return this.sendServiceAjax717_(a, b, c, d);
  10590. }
  10591. }
  10592.  
  10593. function delayClearOtherKeys(lztContinuation) {
  10594. // // schedule delayed removal if mfyContinuationIgnored is not empty
  10595. // getRafPromise().then(() => {
  10596. // // assume the repeat continuation could be only for popstate which is triggered by user interaction
  10597. // // foreground page only
  10598.  
  10599. // });
  10600.  
  10601.  
  10602. if (lztContinuation !== mtzlastAllowedContinuation) return;
  10603. if (lztContinuation !== mpKey21 || lztContinuation !== mpKey22) return;
  10604. if (!mfyContinuationIgnored.size) return;
  10605. if (mfyContinuationIgnored.size > 1) {
  10606. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, 'delayClearOtherKeys, current = ', lztContinuation);
  10607. }
  10608. mfyContinuationIgnored.forEach((value, key) => {
  10609. if (key !== lztContinuation) {
  10610. mfyContinuationIgnored.delete(key);
  10611. LOG_FETCHMETA_UPDATE && continuationLog(key, 'previous continuation removed from ignored store', key);
  10612. }
  10613. });
  10614.  
  10615. }
  10616. if (typeof cProto.getCancellableNetworkPromise_ === 'function' && cProto.getCancellableNetworkPromise_.length === 5 && !cProto.getCancellableNetworkPromise717_) {
  10617. cProto.getCancellableNetworkPromise717_ = cProto.getCancellableNetworkPromise_;
  10618. cProto.getCancellableNetworkPromise_ = function (a, b, c, d, e) {
  10619.  
  10620. // console.log(8003)
  10621. try {
  10622.  
  10623.  
  10624. const { is, videoId, continuation } = extraArguments322(b, c, d);
  10625.  
  10626. if ((videoId || continuation) && (is !== 'ytd-video-primary-info-renderer')) {
  10627. console.warn("CAUTION: getCancellableNetworkPromise_ coding might have to be updated.");
  10628. }
  10629.  
  10630. if (pageSetupVideoId && videoId && continuation) {
  10631. if (mpKey21 && mpUrl21 && mpKey21 === continuation && mpUrl21 !== pageSetupVideoId) {
  10632. mfyContinuationIgnored.removeAdd(continuation);
  10633. mfvContinuationRecorded.delete(continuation);
  10634. return;
  10635. }
  10636. }
  10637.  
  10638. if (mjtLockPreviousKey && mjtLockPreviousKey !== continuation && continuation) {
  10639. copyPreviousContiuationToIgnored374(false);
  10640. mfyContinuationIgnored.delete(continuation);
  10641. mfvContinuationRecorded.removeAdd(continuation);
  10642. mfyContinuationIgnored.removeAdd(mjtLockPreviousKey);
  10643. mfvContinuationRecorded.delete(mjtLockPreviousKey);
  10644. mjtLockPreviousKey = '';
  10645. }
  10646.  
  10647. // if (mjtNextMainKey === continuation) {
  10648. // copyPreviousContiuationToIgnored(false);
  10649. // mfyContinuationIgnored.delete(continuation);
  10650. // mfvContinuationRecorded.add(continuation);
  10651. // }
  10652.  
  10653. const lztContinuation = continuation;
  10654.  
  10655. if (mfyContinuationIgnored && lztContinuation && typeof lztContinuation === 'string') {
  10656. if (mfyContinuationIgnored.has(lztContinuation)) {
  10657. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, '5360 matched02', lztContinuation)
  10658. return;
  10659. }
  10660. }
  10661.  
  10662. // if (videoId) {
  10663. // if (!pageSetupVideoId) return; // ignore page not ready
  10664. // // if (mtxVideoId && c.updatedMetadataEndpoint.videoId !== mtxVideoId) return; // ignore videoID not matched
  10665. // if (videoId !== pageSetupVideoId) {
  10666. // return;
  10667. // }
  10668. // }
  10669.  
  10670. if (typeof lztContinuation === 'string' && mtzlastAllowedContinuation !== lztContinuation) {
  10671. mtzlastAllowedContinuation = lztContinuation;
  10672. // console.log(70401, lztContinuation, mfyContinuationIgnored.size)
  10673.  
  10674. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, '5382 Continuation sets to\t', lztContinuation, `C${mtzCount}.R${mfvContinuationRecorded.size}.I${mfyContinuationIgnored.size}`);
  10675. mjtRecordedPrevKey = lztContinuation;
  10676. if (mjtLockPreviousKey === lztContinuation) mjtLockPreviousKey = '';
  10677. // if (mfyContinuationIgnored.size > 0) {
  10678. // delayClearOtherKeys(lztContinuation);
  10679. // }
  10680. mtzCount = 0;
  10681. // allowNoDelay322 = false;
  10682. } else if (typeof lztContinuation === 'string' && mtzlastAllowedContinuation && mtzlastAllowedContinuation === lztContinuation) {
  10683. // repeated
  10684. if (++mtzCount > 1e9) mtzCount = 1e4;
  10685. LOG_FETCHMETA_UPDATE && continuationLog(lztContinuation, '5386 Same Continuation\t\t', lztContinuation, `C${mtzCount}.R${mfvContinuationRecorded.size}.I${mfyContinuationIgnored.size}`);
  10686.  
  10687. // if (mtzCount >= 3) allowNoDelay322 = true;
  10688. if (mtzCount >= 3 && mfyContinuationIgnored.size > 0) {
  10689. Promise.resolve(lztContinuation).then(delayClearOtherKeys).catch(console.warn);
  10690. }
  10691. if (mtzCount === 5) {
  10692. mfvContinuationRecorded.clear();
  10693. mfvContinuationRecorded.add(lztContinuation);
  10694. }
  10695.  
  10696. }
  10697.  
  10698. if (typeof lztContinuation === 'string' && lztContinuation && (pageSetupVideoId || videoPlayingY.videoId)) {
  10699. mpKey22 = lztContinuation;
  10700. mpUrl22 = pageSetupVideoId || videoPlayingY.videoId;
  10701. }
  10702.  
  10703. if (mbCId322) {
  10704. clearTimeout(mbCId322);
  10705. mbCId322 = 0;
  10706. }
  10707. } catch (e) {
  10708. console.log('Coding Error in getCancellableNetworkPromise_', e)
  10709. }
  10710.  
  10711. // console.log(8004)
  10712. // console.log(123403, arguments);
  10713. // if(c.updatedMetadataEndpoint) console.log(123404, pageSetupVideoId, JSON.stringify(c.updatedMetadataEndpoint))
  10714.  
  10715. // console.log(5163, a?.is,b,c,d,e);
  10716. return this.getCancellableNetworkPromise717_(a, b, c, d, e);
  10717. }
  10718. }
  10719. });
  10720.  
  10721. // ==================================== FIX_avoid_incorrect_video_meta ====================================
  10722.  
  10723.  
  10724. FIX_ytdExpander_childrenChanged && !isChatRoomURL && whenCEDefined('ytd-expander').then(() => {
  10725.  
  10726. let dummy;
  10727. let cProto;
  10728.  
  10729. dummy = document.createElement('ytd-expander');
  10730. cProto = insp(dummy).constructor.prototype;
  10731.  
  10732. if (fnIntegrity(cProto.initChildrenObserver, '0.48.21') && fnIntegrity(cProto.childrenChanged, '0.40.22')) {
  10733.  
  10734. cProto.initChildrenObserver14 = cProto.initChildrenObserver;
  10735. cProto.childrenChanged14 = cProto.childrenChanged;
  10736.  
  10737. cProto.initChildrenObserver = function () {
  10738. var a = this;
  10739. this.observer = new MutationObserver(function () {
  10740. a.childrenChanged()
  10741. }
  10742. );
  10743. this.observer.observe(this.content, {
  10744. subtree: !0,
  10745. childList: !0,
  10746. attributes: !0,
  10747. characterData: !0
  10748. });
  10749. this.childrenChanged()
  10750. }
  10751. ;
  10752. cProto.childrenChanged = function () {
  10753. if (this.alwaysToggleable) {
  10754. this.canToggle = this.alwaysToggleable;
  10755. } else if (!this.canToggleJobId) {
  10756. this.canToggleJobId = 1;
  10757. foregroundPromiseFn().then(() => {
  10758. this.canToggleJobId = 0;
  10759. this.calculateCanCollapse()
  10760. })
  10761. }
  10762. }
  10763.  
  10764. // console.log(cProto.initChildrenObserver)
  10765. console.debug('ytd-expander-fix-childrenChanged');
  10766.  
  10767. }
  10768.  
  10769. });
  10770.  
  10771.  
  10772. FIX_paper_ripple_animate && whenCEDefined('paper-ripple').then(() => {
  10773.  
  10774. let dummy;
  10775. let cProto;
  10776. dummy = document.createElement('paper-ripple');
  10777. cProto = insp(dummy).constructor.prototype;
  10778.  
  10779. if (fnIntegrity(cProto.animate, '0.74.5')) {
  10780.  
  10781.  
  10782. cProto.animate34 = cProto.animate;
  10783. cProto.animate = function () {
  10784. if (this._animating) {
  10785. var a;
  10786. const ripples = this.ripples;
  10787. for (a = 0; a < ripples.length; ++a) {
  10788. var b = ripples[a];
  10789. b.draw();
  10790. this.$.background.style.opacity = b.outerOpacity;
  10791. b.isOpacityFullyDecayed && !b.isRestingAtMaxRadius && this.removeRipple(b)
  10792. }
  10793. if ((this.shouldKeepAnimating || 0) !== ripples.length) {
  10794. if (!this._boundAnimate38) this._boundAnimate38 = this.animate.bind(this);
  10795. foregroundPromiseFn().then(this._boundAnimate38);
  10796. } else {
  10797. this.onAnimationComplete();
  10798. }
  10799. }
  10800. }
  10801.  
  10802. console.debug('FIX_paper_ripple_animate')
  10803.  
  10804. // console.log(cProto.animate)
  10805.  
  10806. }
  10807.  
  10808. });
  10809.  
  10810. if (FIX_doIdomRender) {
  10811.  
  10812. const xsetTimeout = function (f, d) {
  10813. if (xsetTimeout.m511 === 1 && !d) {
  10814. xsetTimeout.m511 = 2;
  10815. xsetTimeout.m568 = f;
  10816. } else {
  10817. return setTimeout.apply(window, arguments)
  10818. }
  10819.  
  10820. }
  10821.  
  10822. /**
  10823. *
  10824. IGb = function(a) {
  10825. var b, c = null == (b = a.requestAninmationFrameResolver) ? void 0 : b.promise;
  10826. c || (a.requestAninmationFrameResolver = new Vi,
  10827. c = a.requestAninmationFrameResolver.promise,
  10828. Da.requestAnimationFrame(function() {
  10829. var d;
  10830. null == (d = a.requestAninmationFrameResolver) || d.resolve();
  10831. a.requestAninmationFrameResolver = null
  10832. }));
  10833. return c
  10834. }
  10835.  
  10836.  
  10837. */
  10838.  
  10839. const xrequestAnimationFrame = function (f) {
  10840. const h = `${f}`;
  10841. if (h.startsWith("function(){setTimeout(function(){") && h.endsWith("})}")) {
  10842. let t = null;
  10843. xsetTimeout.m511 = 1;
  10844. f();
  10845. if (xsetTimeout.m511 === 2) {
  10846. t = xsetTimeout.m568;
  10847. xsetTimeout.m568 = null;
  10848. }
  10849. xsetTimeout.m511 = 0;
  10850. if (typeof t === 'function') {
  10851. foregroundPromiseFn().then(t);
  10852. }
  10853. } else if (h.includes("requestAninmationFrameResolver")) {
  10854. foregroundPromiseFn().then(f);
  10855. } else {
  10856. return requestAnimationFrame.apply(window, arguments);
  10857. }
  10858. }
  10859.  
  10860. let busy = false;
  10861. const doIdomRender = function () {
  10862.  
  10863. if (!this) return;
  10864. if (busy) {
  10865. return this.doIdomRender13(...arguments);
  10866. }
  10867. busy = true;
  10868. const { requestAnimationFrame, setTimeout } = window;
  10869. window.requestAnimationFrame = xrequestAnimationFrame;
  10870. window.setTimeout = xsetTimeout;
  10871. let r = this.doIdomRender13(...arguments);
  10872. window.requestAnimationFrame = requestAnimationFrame;
  10873. window.setTimeout = setTimeout;
  10874. busy = false;
  10875. return r;
  10876. };
  10877. 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']) {
  10878.  
  10879.  
  10880. whenCEDefined(ytTag).then(() => {
  10881.  
  10882. let dummy;
  10883. let cProto;
  10884. dummy = document.createElement(ytTag);
  10885. cProto = insp(dummy).constructor.prototype;
  10886.  
  10887. cProto.doIdomRender13 = cProto.doIdomRender;
  10888. cProto.doIdomRender = doIdomRender;
  10889.  
  10890. if (cProto.doIdomRender13 === cProto.templatingFn) cProto.templatingFn = doIdomRender;
  10891.  
  10892. console.debug('[yt-js-engine-tamer] FIX_doIdomRender', ytTag)
  10893.  
  10894.  
  10895.  
  10896. });
  10897.  
  10898. }
  10899.  
  10900. }
  10901.  
  10902.  
  10903.  
  10904.  
  10905. FIX_POPUP_UNIQUE_ID && whenCEDefined('ytd-popup-container').then(async () => {
  10906.  
  10907. const sMap = new Map();
  10908.  
  10909. const ZTa = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
  10910. const ZT = function () {
  10911. for (var a = Array(36), b = 0, c, d = 0; d < 36; d++)
  10912. d == 8 || d == 13 || d == 18 || d == 23 ? a[d] = "-" : d == 14 ? a[d] = "4" : (b <= 2 && (b = 33554432 + Math.random() * 16777216 | 0),
  10913. c = b & 15,
  10914. b >>= 4,
  10915. a[d] = ZTa[d == 19 ? c & 3 | 8 : c]);
  10916. return a.join("")
  10917. };
  10918.  
  10919.  
  10920. const popupContainerCollection = document.getElementsByTagName('ytd-popup-container');
  10921.  
  10922. const popupContainer = await observablePromise(() => {
  10923. return popupContainerCollection[0];
  10924. }).obtain();
  10925.  
  10926.  
  10927. let cProto;
  10928. cProto = insp(popupContainer).constructor.prototype;
  10929.  
  10930.  
  10931. if (!cProto || typeof cProto.handleOpenPopupAction !== 'function' || cProto.handleOpenPopupAction3868 || cProto.handleOpenPopupAction.length !== 2) {
  10932. console.log('FIX_POPUP_UNIQUE_ID NG')
  10933. return;
  10934. }
  10935. cProto.handleOpenPopupAction3868 = cProto.handleOpenPopupAction;
  10936.  
  10937. cProto.handleOpenPopupAction = function (a, b) {
  10938.  
  10939. if (typeof (a || 0) === 'object' && !a.__jOdQA__) {
  10940.  
  10941. a.__jOdQA__ = true;
  10942.  
  10943. try {
  10944.  
  10945. const h = this.hostElement;
  10946.  
  10947. if (h instanceof HTMLElement_) {
  10948.  
  10949. const map = h.__skme44__ = h.__skme44__ || new Map();
  10950.  
  10951. let mKey = '';
  10952. const wKey = firstObjectKey(a);
  10953. const wObj = wKey ? a[wKey] : null;
  10954. if (wKey && wObj && typeof (wObj.popup || 0) === 'object') {
  10955. const pKey = firstObjectKey(wObj.popup)
  10956. const pObj = pKey ? wObj.popup[pKey] : null;
  10957. let contentKey = '';
  10958. let headerKey = '';
  10959.  
  10960. if (pObj && pObj.identifier && pObj.content && pObj.header) {
  10961. contentKey = firstObjectKey(pObj.content)
  10962. headerKey = firstObjectKey(pObj.header)
  10963. }
  10964. if (contentKey && headerKey) {
  10965.  
  10966. mKey = `${wKey}(popupType:${wObj.popupType},popup(${pKey}(content(${contentKey}:...),header(${headerKey}:...),identifer(surface:${pObj.identifier.surface}))))`
  10967.  
  10968. if (mKey) {
  10969.  
  10970. if (!wObj.uniqueId) {
  10971. for (let i = 0; i < 8; i++) {
  10972. wObj.uniqueId = ZT();
  10973. if (!sMap.has(wObj.uniqueId)) break;
  10974. }
  10975. }
  10976. const oId = wObj.uniqueId
  10977.  
  10978. let nId_ = map.get(mKey);
  10979. if (!nId_) {
  10980. map.set(mKey, nId_ = oId);
  10981. }
  10982.  
  10983. wObj.uniqueId = nId_ || wObj.uniqueId;
  10984.  
  10985. const nId = wObj.uniqueId
  10986.  
  10987. sMap.set(oId, nId);
  10988. sMap.set(nId, nId);
  10989.  
  10990. wObj.uniqueId = nId;
  10991. pObj.targetId = nId;
  10992. pObj.identifier.tag = nId;
  10993.  
  10994. if (oId !== nId) {
  10995. console.log('FIX_POPUP_UNIQUE_ID', oId, nId);
  10996. }
  10997.  
  10998. }
  10999.  
  11000. }
  11001. }
  11002.  
  11003. // console.log(12213, mKey, a, b, h)
  11004.  
  11005. }
  11006.  
  11007. } catch (e) {
  11008. console.warn(e)
  11009. }
  11010.  
  11011. try {
  11012.  
  11013. const results = searchNestedObject(a, (x) => {
  11014. if (typeof x === 'string' && x.length === 36) {
  11015. 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;
  11016. }
  11017. return false;
  11018. });
  11019. for (const [obj, key] of results) {
  11020. const oId = obj[key];
  11021. const nId = sMap.get(oId);
  11022. if (nId) obj[key] = nId;
  11023. }
  11024. } catch (e) {
  11025. console.warn(e)
  11026. }
  11027.  
  11028.  
  11029. }
  11030.  
  11031. return this.handleOpenPopupAction3868(...arguments)
  11032. }
  11033.  
  11034. console.log('FIX_POPUP_UNIQUE_ID OK')
  11035.  
  11036.  
  11037. });
  11038.  
  11039.  
  11040. // FIX_TRANSCRIPT_SEGMENTS && (async ()=>{
  11041.  
  11042.  
  11043. // })();
  11044.  
  11045. // FIX_TRANSCRIPT_SEGMENTS && whenCEDefined('ytd-transcript-search-panel-renderer').then(async () => {
  11046.  
  11047.  
  11048. // let dummy;
  11049. // let cProto;
  11050. // dummy = document.createElement('ytd-transcript-search-panel-renderer');
  11051. // cProto = insp(dummy).constructor.prototype;
  11052.  
  11053.  
  11054. // if (!cProto || typeof cProto.bodyChanged !== 'function' || cProto.bodyChanged1848 || cProto.bodyChanged.length !== 0) {
  11055. // console.log('FIX_TRANSCRIPT_SEGMENTS NG')
  11056. // return;
  11057. // }
  11058. // cProto.bodyChanged1848 = cProto.bodyChanged;
  11059.  
  11060. // const wmx = new WeakMap();
  11061.  
  11062. // const sb35 = Symbol();
  11063. // cProto.bodyChanged = function () {
  11064. // let a = null;
  11065. // try {
  11066. // a = this.getBodyRenderer();
  11067. // } catch (e) { }
  11068. // if (!a || !a.initialSegments) {
  11069. // a = this.data;
  11070. // if (a.body) a = a.body;
  11071. // if (a.transcriptSegmentListRenderer) a = a.transcriptSegmentListRenderer;
  11072. // }
  11073. // const a_ = a;
  11074. // const initialSegments = (a_ || 0).initialSegments;
  11075. // if (typeof (initialSegments || 0) === 'object' && initialSegments.length >= 1){
  11076. // ((async () => { })()).then(() => {
  11077.  
  11078. // const c = wmx.get(initialSegments);
  11079. // if (!c) {
  11080. // const d = translateFn(initialSegments);
  11081. // wmx.set(initialSegments, d);
  11082. // console.log('translated', d);
  11083. // wmx.set(d, d);
  11084. // a_.initialSegments = d;
  11085. // } else {
  11086. // a_.initialSegments = c;
  11087. // }
  11088.  
  11089.  
  11090. // }).then(() => {
  11091. // // this.bodyChanged1848();
  11092. // });
  11093.  
  11094. // }else{
  11095.  
  11096. // // return this.bodyChanged1848();
  11097. // }
  11098. // }
  11099.  
  11100. // console.log('FIX_TRANSCRIPT_SEGMENTS OK')
  11101.  
  11102.  
  11103.  
  11104.  
  11105. // });
  11106.  
  11107.  
  11108. FIX_TRANSCRIPT_SEGMENTS && !isChatRoomURL && whenCEDefined('yt-formatted-string').then(async () => {
  11109.  
  11110. let dummy;
  11111. let cProto;
  11112. dummy = document.createElement('yt-formatted-string');
  11113. cProto = insp(dummy).constructor.prototype;
  11114.  
  11115. if (!cProto || typeof cProto.setNodeStyle_ !== 'function' || cProto.setNodeStyle17_ || cProto.setNodeStyle_.length !== 2) {
  11116. console.log('FIX_TRANSCRIPT_SEGMENTS(2) NG');
  11117. return;
  11118. }
  11119.  
  11120. cProto.setNodeStyle17_ = cProto.setNodeStyle_;
  11121. cProto.setNodeStyle_ = function (a, b) {
  11122. if (b instanceof HTMLElement_ && typeof (a || 0) === 'object') b.classList.toggle('yt-formatted-string-block-line', !!a.blockLine);
  11123. return this.setNodeStyle17_(a, b);
  11124. }
  11125.  
  11126. console.log('FIX_TRANSCRIPT_SEGMENTS(2) OK');
  11127. });
  11128.  
  11129. });
  11130.  
  11131. });
  11132.  
  11133.  
  11134.  
  11135.  
  11136. if (isMainWindow) {
  11137.  
  11138. console.groupCollapsed(
  11139. "%cYouTube JS Engine Tamer",
  11140. "background-color: #EDE43B ; color: #000 ; font-weight: bold ; padding: 4px ;"
  11141. );
  11142.  
  11143.  
  11144.  
  11145. console.log("Script is loaded.");
  11146. console.log("This script changes the core mechanisms of the YouTube JS engine.");
  11147.  
  11148. console.log("This script is experimental and subject to further changes.");
  11149.  
  11150. console.log("This might boost your YouTube performance.");
  11151.  
  11152. console.log("CAUTION: This might break your YouTube.");
  11153.  
  11154.  
  11155. if (prepareLogs.length >= 1) {
  11156. console.log(" =========================================================================== ");
  11157.  
  11158. for (const msg of prepareLogs) {
  11159. console.log(msg)
  11160. }
  11161.  
  11162. console.log(" =========================================================================== ");
  11163. }
  11164.  
  11165. console.groupEnd();
  11166.  
  11167. }
  11168.  
  11169.  
  11170.  
  11171. })();