YouTube JS Engine Tamer

To enhance YouTube performance by modifying YouTube JS Engine

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