YouTube JS Engine Tamer

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

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

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