// ==UserScript== // @name YouTube JS Engine Tamer // @name:ja YouTube JS Engine Tamer // @name:zh-TW YouTube JS Engine Tamer // @name:zh-CN YouTube JS Engine Tamer // @namespace UserScripts // @version 0.41.10 // @match https://www.youtube.com/* // @match https://www.youtube-nocookie.com/embed/* // @match https://studio.youtube.com/live_chat* // @license MIT // @author CY Fung // @icon https://raw.githubusercontent.com/cyfung1031/userscript-supports/main/icons/yt-engine.png // @grant none // @require https://cdn.jsdelivr.net/gh/cyfung1031/userscript-supports@c2b707e4977f77792042d4a5015fb188aae4772e/library/nextBrowserTick.min.js // @run-at document-start // @unwrap // @inject-into page // @allFrames true // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/ // // @description To enhance YouTube performance by modifying YouTube JS Engine // @description:ja YouTubeのJSエンジンを変更してパフォーマンスを向上させる // @description:zh-TW 修改 YouTube 的 JS 引擎以提升效能 // @description:zh-CN 修改 YouTube 的 JS 引擎以提升性能 // // @downloadURL none // ==/UserScript== (() => { /** @type {WeakMapConstructor} */ const WeakMap = window.WeakMapOriginal || window.WeakMap; const HOOK_ACTIVE_MODULES = true; // added in 0.37.0 const HOOK_ACTIVE_MODULES_fetchUpdatedMetadata = true; // added in 0.37.0 (make likeCount update) const NATIVE_CANVAS_ANIMATION = false; // for #cinematics const FIX_schedulerInstanceInstance = 2 | 4; const FIX_yt_player = true; // DONT CHANGE const FIX_Animation_n_timeline = true; const FIX_Animation_n_timeline_cinematic = true; const FIX_ytScheduler = true; const NO_PRELOAD_GENERATE_204 = false; const ENABLE_COMPUTEDSTYLE_CACHE = true; const NO_SCHEDULING_DUE_TO_COMPUTEDSTYLE = true; const CHANGE_appendChild = true; // discussions#236759 const FIX_bind_self_this = false; // EXPERIMENTAL !!!!! this affect page switch after live ends const FIX_error_many_stack = true; // should be a bug caused by uBlock Origin const IGNORE_bindAnimationForCustomEffect = true; // prevent `v.bindAnimationForCustomEffect(this);` being executed const FIX_ytdExpander_childrenChanged = true; const FIX_paper_ripple_animate = true; const FIX_avoid_incorrect_video_meta = true; // [legacy feature for rolling number fixing] 2025.05.10 - obsoleted -> y.fetchUpdatedMetadata(t, e.continuation) const FIX_avoid_incorrect_video_meta_emitterBehavior = true; // [legacy feature for rolling number fixing] 2025.05.10 - obsoleted -> y.fetchUpdatedMetadata(t, e.continuation) const FIX_doIdomRender = true; const FIX_Shady = true; // [[ 2024.04.24 ]] const MODIFY_ShadyDOM_OBJ = true; // DON'T CHANGE. MUST BE TRUE // << if MODIFY_ShadyDOM_OBJ >> const WEAKREF_ShadyDOM = true; const OMIT_ShadyDOM_EXPERIMENTAL = 1 | 0; // 1 => enable; 2 => composedPath const OMIT_ShadyDOM_settings = 0 | 0 | 0; // 1: inUse; 2: handlesDynamicScoping; 4: force // {{ PRELIM TESTING PURPOSE }} // << end >> const WEAK_REF_BINDING_CONTROL = 1 | 2; // 2 - conflict control with ShadyDOM weakref const FIX_ytAction_ = true; // ytd-app const FIX_onVideoDataChange = false; // const FIX_onClick = true; const FIX_onStateChange = true; const FIX_onLoopRangeChange = true; // const FIX_maybeUpdateFlexibleMenu = true; // ytd-menu-renderer const FIX_VideoEVENTS_v2 = true; // true might cause bug in switching page const FIX_stampDomArray_ = true; // v0.30.0 const FIX_stampDomArray = FIX_stampDomArray_ && typeof WeakRef === "function" && typeof FinalizationRegistry === "function"; // const stampDomArray_MemoryFix_Flag001 = false; const XFlag = true; // root issue tbc const MemoryFix_Flag002 = 1 | 2 | 4 | 8 | 0 | 32 | 64 | 0 | 256; // 32 required for new stampDomArray // 128 to be tested const FIX_perfNow = true; // history state issue; see https://bugzilla.mozilla.org/show_bug.cgi?id=1756970 const ENABLE_ASYNC_DISPATCHEVENT = false; // problematic const FIX_Polymer_dom = true; const FIX_Polymer_AF = true; const SCRIPTLET_REMOVE_PRUNE_propNeedles = true; // brave scriptlet related const DEBUG_removePrune = false; // true for DEBUG const FIX_XHR_REQUESTING = true; const LOG_FETCHMETA_UPDATE = false; // for DEBUG const IGNORE_bufferhealth_CHECK = false; // experimental; true will make "Stats for nerds" no info. const DENY_requestStorageAccess = true; // remove document.requestStorageAccess const DISABLE_IFRAME_requestStorageAccess = true; // no effect if DENY_requestStorageAccess is true const DISABLE_COOLDOWN_SCROLLING = true; // YT cause scroll hang in MacOS const FIX_removeChild = true; const FIX_fix_requestIdleCallback_timing = true; const HOOK_CSSPD_LEFT = true; // global css hack for style.left const FORCE_NO_REUSEABLE_ELEMENT_POOL = true; const FIX_TRANSCRIPT_SEGMENTS = true; // Based on Tabview Youtube's implementation const FIX_POPUP_UNIQUE_ID = true; // currently only for channel about popup; // ------------------------------------------------------------------ const MEMORY_RELEASE_NF00 = true; const MEMORY_RELEASE_NF00_SHOW_MESSAGE = false; const MEMORY_RELEASE_MAP_SET_REMOVE_NODE = true; const FULLY_REMOVE_ALL_EVENT_LISTENERS = true; // require MEMORY_RELEASE_NF00 const FUZZY_EVENT_LISTENER_REMOVAL = true; const WEAK_CE_ROOT = true; // shadowRoot of the return value of attachShadow on the node const FIX_TEMPLATE_BINDING = true; const FIX_TEMPLATE_BINDING_SHOW_MESSAGE = false; const FIX_SHADY_METHODS = true; const FIX_FRAGEMENT_HOST = true; const USE_fastDomIf = 2; // fastDomIf is seem to be experimental 0 = no change, 1 = enable, 2 = disable const ENHANCE_DOMIF_createAndInsertInstance = true; // root does not need to store in the instance const ENHANCE_DOMIF_TEARDOWN = true; // require MEMORY_RELEASE_NF00 const FIX_DOM_IF_DETACH = true; const FIX_DOM_IF_REPEAT = true; // semi-experimental (added in 0.17.0) const FIX_DOM_IF_TEMPLATE = true; // const FIX_DOM_REPEAT_TEMPLATE = true; // to be implemented const DEBUG_DBR847 = false; const FIX_DOM_IFREPEAT_RenderDebouncerChange_SET_TO_PROPNAME = true; // default true. false might be required for future change const FIX_ICON_RENDER = true; const FIX_GUIDE_ICON = true; const FIX_ACTIONS_TOOLTIPS = true; const FIX_VIDEO_PLAYER_MOUSEHOVER_EVENTS = true; // avoid unnecessary reflows due to cursor moves on the web player. const DISABLE_isLowLatencyLiveStream = false; // TBC const FIX_FlexibleItemSizing = true; const FIX_ROLLING_NUMBER_UPDATE = true; // ----------------------------- POPUP UNIQUE ID ISSUE ----------------------------- // example. https://www.youtube.com/channel/UCgPev1KKSCMbnNRsvN83Hag/about // first tp-yt-paper-dialog: show once the page is loaded. // second tp-yt-paper-dialog: click "...more" // third tp-yt-paper-dialog: click "... and 3 more links" // check with document.querySelectorAll('ytd-popup-container tp-yt-paper-dialog').length // currently, uniqueId is preassigned by the network resolveCommand. // so don't modify the source side, just modify the display side (popup display) via handleOpenPopupAction // other related functions e.g. handleClosePopupCommand_, getAndMaybeCreatePopup_, handleClosePopupAction_, getAndMaybeCreatePopup_ // handleOpenPopupAction -> createCacheKey // handleClosePopupAction_ -> createCacheKey // handleGetPopupOpenedAction_ -> createCacheKey // getAndMaybeCreatePopup_ -> createCacheKey // closePopup -> createCacheKey // yt-close-popup-command -> handleClosePopupCommand_ // ensurePopup_ -> getAndMaybeCreatePopup_ // yt-close-popup-action -> handleClosePopupAction_ // closePopup -> handleClosePopupAction_ // handleOpenPopupAction -> handleClosePopupAction_ // handleClosePopupCommand_ -> handleClosePopupAction_ // closeSheet -> handleClosePopupAction_("yt-sheet-view-model") // yt-open-popup-action -> handleOpenPopupAction // yt-close-popup-action -> handleClosePopupAction_ -> createCacheKey // yt-close-popup-command -> handleClosePopupCommand_ -> handleClosePopupAction_ -> createCacheKey // Experimental flag "ytpopup_disable_default_html_caching" is disabled by default. // Not sure enabling it can make GC or not (Yt Components are usually not GC-able) // ----------------------------- POPUP UNIQUE ID ISSUE ----------------------------- // ----------------------------- Shortkey Keyboard Control ----------------------------- // dependency: FIX_yt_player const FIX_SHORTCUTKEYS = 2; // 0 - no fix; 1 - basic fix; 2 - advanced fix // [0] no fix - not recommended // [1] basic fix - just fix the global focus detection variable // [2] advanced fix - call the shortcut actions directly, auto foucs change, direct control of spacebar behavior, etc // (note) 0 or 1 if you find conflict with other userscripts/plugin const CHANGE_SPEEDMASTER_SPACEBAR_CONTROL = 0; // 0 - disable; 1 - force true; 2 - force false const USE_IMPROVED_PAUSERESUME_UNDER_NO_SPEEDMASTER = true; // only for SPEEDMASTER = false & FIX_SHORTCUTKEYS = 2 const PROP_OverReInclusion_AVOID = true; const PROP_OverReInclusion_DEBUGLOG = false; const PROP_OverReInclusion_LIST = new Set([ 'hostElement72', 'parentComponent72', 'localVisibilityObserver_72', 'cachedProviderNode_72', '__template72', '__templatizeOwner72', '__templateInfo72', '__dataHost72', '__CE_shadowRoot72', 'elements_72', 'ky36', 'kz62', 'm822', // To be reviewed. // chat messages 'disabled', 'allowedProps', 'filledButtonOverrides', 'openPopupConfig', 'supportsInlineActionButtons', 'allowedProps', 'dimension', 'loadTime', 'pendingPaint', 'countdownDurationMs', 'countdownMs', 'lastCountdownTimeMs', 'rafId', 'playerProgressSec', 'detlaSincePausedSecs', 'behaviorActionMap', 'selected', 'maxLikeCount', 'maxReplyCount', 'isMouseOver', 'respectLangDir', 'noEndpoints', 'objectURL', 'buttonOverrides', 'queuedMessages', 'STEP', 'BLOCK_ON', 'MIN_PROGESS', 'MAX_PROGESS', 'DISMISSED_CONTENT_KEYSPACE', 'followUpDialogPromise', 'followUpDialogPromiseResolve', 'followUpDialogPromiseReject', 'hoverJobId', 'JSC$14573_touched', // tbc 'toggleable', 'isConnected', 'scrollDistance', 'dragging', 'dragMouseStart', 'dragOffsetStart', 'containerWidthDiff', 'disableDeselectEvent', 'emojiSize', 'buttonOverride', 'shouldUseStickyPreferences', 'longPressTimeoutId', // others 'observeVisibleOption', 'observeHiddenOption', 'observePrescanOption', 'visibilityMonitorKeys', // 'filledButtonOverrides', 'openPopupConfig', 'supportsInlineActionButtons', 'observeVisibleOption', 'observeHiddenOption', 'observePrescanOption', 'visibilityMonitorKeys', // 'dimension', 'loadTime', 'pendingPaint', // 'disabled', 'allowedProps', // 'enableMssLazyLoad', 'popupContainerConfig', 'actionRouterNode', 'actionRouterIsRoot', 'actionMap', 'dynamicActionMap', // 'actionMap', // 'sharedTooltipPosition', 'sharedTooltipAnimationDelay', 'disableEmojiPickerIncrementalLoading', 'useResolveCommand', 'activeRequest', 'popoutWindowCheckIntervalId', 'supportedTooltipTargets', 'closeActionPanelTimerId', 'delayCloseActionPanelTimerId', 'tooltipTimerIds', 'queuedTooltips', 'isPopupConfigReady', 'popoutWindow', 'actionMap', 'clearTimeout', 'switchTemplateAtRegistration', 'hasUnmounted', 'switchTemplateAtRegistration', 'stopKeyboardEventPropagation', 'tangoConfiguration', 'itemIdToDockDurationMap', 'actionMap', 'emojiManager', 'inputMethodEditorActive', 'suggestionIndex', 'JSC$10745_lastSuggestionRange', 'actionMap', 'asyncHandle', 'shouldAnimateIn', 'lastFrameTimestamp', 'scrollClampRaf', 'scrollRatePixelsPerSecond', 'scrollStartTime', 'scrollStopHandle' // 'buttonOverrides', 'queuedMessages', 'clearTimeout', 'actionMap', // 'stopKeyboardEventPropagation', 'emojiSize', // 'switchTemplateAtRegistration', 'hasUnmounted', // 'buttonOverrides', 'queuedMessages', 'clearTimeout', 'actionMap', // 'isReusable', 'tangoConfiguration', // 'itemIdToDockDurationMap', 'bottomAlignMessages', 'actionMap', // */ ]); // const CAN_TUNE_VOLUMN_AFTER_RESUME_OR_PAUSE = false; // NO USE; TO BE REVIEWED // ----------------------------- Shortkey Keyboard Control ----------------------------- /* window.addEventListener('edm',()=>{ let p = [...this.onerror.errorTokens][0].token; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })() }); window.addEventListener('edn',()=>{ let p = [...this.onerror.errorTokens][0].token+"X"; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })() }); window.addEventListener('edr',()=>{ let p = '123'; (()=>{ console.log(p); throw new Error(p);console.log(334,p) })() }); */ // only for macOS with Chrome/Firefox 100+ const advanceLogging = typeof AbortSignal !== 'undefined' && typeof (AbortSignal || 0).timeout === 'function' && typeof navigator !== 'undefined' && /\b(Macintosh|Mac\s*OS)\b/i.test((navigator || 0).userAgent || ''); const win = this instanceof Window ? this : window; // Create a unique key for the script and check if it is already running const hkey_script = 'jswylcojvzts'; if (win[hkey_script]) throw new Error('Duplicated Userscript Calling'); // avoid duplicated scripting win[hkey_script] = true; const wk = Symbol(); // const [setTimeoutX0, clearTimeoutX0] = [setTimeout, clearTimeout]; let BY_PASS_KEYBOARD_CONTROL = false; // const setImmediate = ((self || 0).jmt || 0).setImmediate; /** @type {(f: ()=>{})=>{}} */ const nextBrowserTick_ = nextBrowserTick; if (typeof nextBrowserTick_ !== "function" || (nextBrowserTick_.version || 0) < 2) { console.log('nextBrowserTick is not found.'); return; } let p59 = 0; const Promise = (async () => { })().constructor; const PromiseExternal = ((resolve_, reject_) => { const h = (resolve, reject) => { resolve_ = resolve; reject_ = reject }; return class PromiseExternal extends Promise { constructor(cb = h) { super(cb); if (cb === h) { /** @type {(value: any) => void} */ this.resolve = resolve_; /** @type {(reason?: any) => void} */ this.reject = reject_; } } }; })(); const FinalizationRegistry_ = typeof FinalizationRegistry !== "undefined" ? FinalizationRegistry : class FinalizationRegistry__ { constructor(callback = undefined) { } register(target, heldValue, unregisterToken = undefined) { } unregister(unregisterToken) { } } let ttpHTML = (s) => { ttpHTML = s => s; if (typeof trustedTypes !== 'undefined' && trustedTypes.defaultPolicy === null) { let s = s => s; trustedTypes.createPolicy('default', { createHTML: s, createScriptURL: s, createScript: s }); } return s; } /** @type { typeof HTMLElement } */ const HTMLElement_ = Reflect.getPrototypeOf(HTMLTitleElement); const nativeAppendE = HTMLElement_.prototype.append; const nativeRemoveE = HTMLElement_.prototype.remove; const DocumentFragment_ = DocumentFragment; const nativeAppendD = DocumentFragment_.prototype.append; const Node_ = Node; /** @param {number} x @param {number} d */ const toFixed2 = (x, d) => { let t = x.toFixed(d); let y = `${+t}`; return y.length > t.length ? t : y; } const isChatRoomURL = location.pathname.startsWith('/live_chat'); const TRANSLATE_DEBUG = false; let xdeadc00 = null; // a deteched node with __domApi let xlivec00 = null; // a deteched node with __domApi let removeTNodeRM = null; let removeTNodeBP = false; if (Node.isConnectedOverrided === undefined) { const pdConnected = Object.getOwnPropertyDescriptor(Node.prototype, 'isConnected'); if (pdConnected && pdConnected.get && pdConnected.configurable) { Node.isConnectedOverrided = null; const get_ = pdConnected.get; const get = function () { const overrided = Node.isConnectedOverrided; if (typeof overrided === 'boolean') return overrided; return get_.call(this); } Object.defineProperty(Node.prototype, 'isConnected', { ...pdConnected, get }); } } const _nmSet = new Set(); _nmSet.add = _nmSet.addOriginal || _nmSet.add; const _nmMap = new Set(); _nmMap.add = _nmMap.addOriginal || _nmMap.add; const _nmMapV = new Set(); _nmMapV.add = _nmMapV.addOriginal || _nmMapV.add; if (MEMORY_RELEASE_MAP_SET_REMOVE_NODE && !Set.prototype.addOriginal && !Map.prototype.setOriginal) { const Node_ = Node; Set.prototype.addOriginal = Set.prototype.add; Set.prototype.add = function (n) { if (n instanceof Node_) { if (!this[wk]) this[wk] = mWeakRef(this); _nmSet.add(this[wk]); } return this.addOriginal(n); }; Map.prototype.setOriginal = Map.prototype.set; Map.prototype.set = function (n, v) { if (n instanceof Node_) { if (!this[wk]) this[wk] = mWeakRef(this); _nmMap.add(this[wk]); } if (v instanceof Node_) { if (!this[wk]) this[wk] = mWeakRef(this); _nmMapV.add(this[wk]); } return this.setOriginal(n, v); }; } window.showNM00 = () => { const nmSet = [..._nmSet].map(e => kRef(e)).filter(e => !!e); const nmMap = [..._nmMap].map(e => kRef(e)).filter(e => !!e); const nmMapV = [..._nmMapV].map(e => kRef(e)).filter(e => !!e); return { nmSet, nmMap, nmMapV }; }; window.testNM00 = (x) => { const nmSet = [..._nmSet].map(e => kRef(e)).filter(e => !!e); const nmMap = [..._nmMap].map(e => kRef(e)).filter(e => !!e); const nmMapV = [..._nmMapV].map(e => kRef(e)).filter(e => !!e); for (const s of nmSet) if (s.has(x)) return 1; for (const m of nmMap) if (m.has(x)) return 2; for (const m of nmMapV) { for (const [u, v] of m.entries()) { if (v === x) return 4; } } return 0; }; let FORCE_NO_REUSEABLE_ELEMENT_POOL_fired = false; const FORCE_NO_REUSEABLE_ELEMENT_POOL_fn = (mainCnt) => { if (FORCE_NO_REUSEABLE_ELEMENT_POOL_fired) return; FORCE_NO_REUSEABLE_ELEMENT_POOL_fired = true; if (typeof mainCnt.createComponent_ !== 'function' || mainCnt.createComponent_.length != 3) { console.warn('FORCE_NO_REUSEABLE_ELEMENT_POOL_fn failed.') return; } const mapGet = Map.prototype.get; const setHas = Set.prototype.has; /** @type {Map | null} */ let qcMap = null; Set.prototype.has = function (a) { if (a === 'dummy-4718') return false; // false to allow re-use? return setHas.call(this, a); } Map.prototype.get = function (a) { if (a === 'dummy-4718') qcMap = this; return mapGet.call(this, a); }; let r; try { r = mainCnt.createComponent_('dummy-4718', {}, true); } catch (e) { } Map.prototype.get = mapGet; Set.prototype.has = setHas; if (r && (r.nodeName || '').toLowerCase() === 'dummy-4718') { // clearInterval(ckId); // ckId = 0; if (qcMap !== null && qcMap instanceof Map) { console.log('[yt-js-engine-tamer] qcMap', qcMap); qcMap.__qcMap8781__ = true; const setArrayC = (c) => { if (c instanceof Array) { c.length = 0; c.push = function () { }; c.pop = function () { }; c.shift = function () { }; c.unshift = function () { }; c.splice = function () { }; c.sort = function () { }; c.reverse = function () { }; } } const cleaning = function (m) { m.forEach(setArrayC); m.clear(); } qcMap.set = function (b, c) { if (!this.__qcMap8781__) return Map.prototype.set.call(this, b, c); setArrayC(c); // console.log('qcMap.set', b, c); if (this.size > 0) { // play safe console.log('[yt-js-engine-tamer] qcMap', 'clear 01') cleaning(this); } } qcMap.get = function (b) { if (!this.__qcMap8781__) return Map.prototype.get.call(this, b); // console.log('qcMap.get', b); if (this.size > 0) { // play safe console.log('[yt-js-engine-tamer] qcMap', 'clear 02') cleaning(this); } } if (qcMap.size > 0) { console.log('[yt-js-engine-tamer] qcMap', 'clear 03') cleaning(qcMap); } } } r = null; qcMap = null; } const renderPathMake = (elements) => { if(!elements) return; if (!elements.length) elements = [elements]; const s = new Set(); s.add = s.addOriginal || s.add; for (const element of elements) { if (element && element.nodeType >= 1) { s.add(element); if (element.querySelectorAll) { for (const e of element.querySelectorAll('*')) { s.add(e); } } } } const y = [...s]; s.clear(); const f = (elm) => { let x = elm.nodeName.toLowerCase(); let y = elm.id; return y ? `${x}#${y}` : `${x}`; } for (const element of y) { if (element && (element.nodeType >= 1) && !element.__renderPath522__) { let t = element; let w = [f(t)]; if (!element.is) { while (t = t.parentNode) { w.unshift(f(t)) if (t.is) break; } } element.__renderPath522__ = w.join('/'); } } } const dispatchYtEvent = function (a, b, c, d) { d || (d = { bubbles: !0, cancelable: !1, composed: !0 }); c !== null && c !== void 0 && (d.detail = c); b = new CustomEvent(b, d); a.dispatchEvent(b); return b }; if (DISABLE_isLowLatencyLiveStream) { const sm = Symbol(); const f = () => { try { const videoDetails = ytInitialPlayerResponse.videoDetails; if (videoDetails && videoDetails.isLowLatencyLiveStream) { videoDetails.isLowLatencyLiveStream = false; } if (videoDetails && videoDetails.latencyClass === 'MDE_STREAM_OPTIMIZATIONS_RENDERER_LATENCY_LOW') { videoDetails.latencyClass = 'MDE_STREAM_OPTIMIZATIONS_RENDERER_LATENCY_NORMAL'; } if (videoDetails && videoDetails.latencyClass === 'MDE_STREAM_OPTIMIZATIONS_RENDERER_LATENCY_ULTRA_LOW') { videoDetails.latencyClass = 'MDE_STREAM_OPTIMIZATIONS_RENDERER_LATENCY_NORMAL'; } } catch (e) { } } Object.defineProperty(Object.prototype, 'isLowLatencyLiveStream', { get() { const v = this[sm]; if (typeof v === 'undefined') return v; f(); return v; }, set(nv) { f(); if (nv === true) nv = false; this[sm] = nv; }, enumerable: false, configurable: true }); const sm3 = Symbol(); Object.defineProperty(Object.prototype, 'latencyClass', { get() { const v = this[sm3]; if (typeof v === 'undefined') return v; f(); return v; }, set(nv) { f(); if (nv === 'ULTRALOW' || nv === 'LOW') { nv = 'NORMAL'; } else if (nv === 'MDE_STREAM_OPTIMIZATIONS_RENDERER_LATENCY_LOW' || nv === 'MDE_STREAM_OPTIMIZATIONS_RENDERER_LATENCY_ULTRA_LOW') { nv = 'MDE_STREAM_OPTIMIZATIONS_RENDERER_LATENCY_NORMAL'; } this[sm3] = nv; }, enumerable: false, configurable: true }); } class PlainHTMLElement extends HTMLTitleElement { } const removeShady = function (shady) { if (!shady || typeof shady !== 'object') return; const props = [...Object.getOwnPropertyNames(shady), ...Object.getOwnPropertySymbols(shady)]; for (const prop of props) { const node = shady[prop]; if (typeof (node || 0) !== 'object') continue; if (node.nodeType >= 1 && node.isConnected === false) _removedElements.addNode(node); } } const shadys = new Set(); shadys.add = shadys.addOriginal || shadys.add; window.showShadys00 = ()=>[...shadys].map(e=>kRef(e)); const _removedElements = new Set(); _removedElements.add = _removedElements.addOriginal || _removedElements.add; _removedElements.addNode_ = MEMORY_RELEASE_NF00 ? function (node) { if (!node || node.__keepInstance038__ || node.t792 || node instanceof HTMLTitleElement || node.nodeName === 'defs' || node.nodeName === 'TITLE') return; if (node && node.nodeType >= 1 && node.nodeType !== 9) { if (!node[wk]) node[wk] = mWeakRef(node); return this.add(node[wk]); } } : () => { }; _removedElements.addNode = MEMORY_RELEASE_NF00 ? (node) => { if (!node || node.__keepInstance038__ || node.t792 || node instanceof HTMLTitleElement || node.nodeName === 'defs' || node.nodeName === 'TITLE') return; if (node && node.nodeType >= 1 && node.nodeType !== 9) { try { const rootNode = node.getRootNode(); if (rootNode && rootNode !== node) { if (rootNode.nodeType >= 1 && rootNode.nodeType !== 9) _removedElements.addNode_(rootNode); } } catch (e) { } _removedElements.addNode_(node); } } : () => { }; if (WEAK_CE_ROOT) { Object.defineProperty(Object.prototype, '__CE_shadowRoot', { get() { return kRef(this.__CE_shadowRoot366); }, set(nv) { if (typeof nv !== 'object') { // null is okay if (this.__CE_shadowRoot366) this.__CE_shadowRoot366 = null; return false; } if (!nv || typeof nv !== 'object') { this.__CE_shadowRoot366 = nv; } else { if (!nv[wk]) nv[wk] = mWeakRef(nv); this.__CE_shadowRoot366 = nv[wk]; } return true; } }); } const _emptyElement = document.createElementNS('http://www.w3.org/2000/svg', 'defs'); const _emptyTipsElement = document.createElementNS('http://www.w3.org/2000/svg', 'defs'); const _emptyVisibilityElement = document.createElementNS('http://www.w3.org/2000/svg', 'defs'); // const _emptyShady = new (class EmptyShady { }); const nf00 = new FinalizationRegistry_((x) => { if (MEMORY_RELEASE_NF00_SHOW_MESSAGE) console.log(`NF00: node[${x}] fully removed`); }); let ud00 = 0; const ng00 = new Set(); nf00.registerNode = function (node) { if (node && node.nodeType >= 1) { if (!node.t792) { node.t792 = (ud00 = (ud00 & 1073741823) + 1); const x = `${node.nodeName.toLowerCase()}#${node.t792}`; this.register(node, x); if (MEMORY_RELEASE_NF00_SHOW_MESSAGE) console.log(`NF00: try remove node[${x}]`); ng00.add(mWeakRef(node)); } } } window.showNg00 = () => { const ng01 = new Set(); ng01.add = ng01.addOriginal || ng01.add; for (const e of ng00) { const f = kRef(e); if (!f) continue; ng01.add(f); } const ng02 = [...ng01]; ng01.clear(); window.showNg01 = [...ng02]; return window.showNg01; } window.showTemplates00 = () => { const result = {}; const elements = document.querySelectorAll('*'); for (const element of elements) { const tag = element.nodeName.toLocaleLowerCase(); const r = result[tag] || []; const cnt = insp(element); if (cnt !== element) { if (cnt.templateInfo) { r.push(['cnt0', cnt.templateInfo, element]); } if (element._templateInfo) { r.push(['cnt1', cnt._templateInfo, element]); } if (element.__templateInfo) { r.push(['cnt2', cnt.__templateInfo, element]); } } if (element.templateInfo) { r.push(['elm0', element.templateInfo, element]); } if (element._templateInfo) { r.push(['elm1', element._templateInfo, element]); } if (element.__templateInfo) { r.push(['elm2', element.__templateInfo, element]); } if (r.length >= 1) result[tag] = r; } const strCmp = (a, b) => { if (a === b) return 0; let u = [a, b].sort(); return u[0] === a ? -1 : 1; } const counting1 = Object.entries(result).map(e => [e[0], [...new Set(e[1].map(t => t[0]))].join('|')]).sort((a, b) => { return strCmp(`${a[1]}.${a[0]}`, `${b[1]}.${b[0]}`); }); const counting2 = Object.entries(result).map(e => [e[0], [...new Set(e[1].map(t => t[1]))]]); const counting3 = Object.entries(result).map(e => { const a = [...new Set(e[1].map(t => t[1]))]; const b = [...new Set(a.map(e => e.nodeList || e))]; const r = [e[0], b]; return r; }); return {result, counting1, counting2, counting3}; }; window.showFrag00 = function(){ const result = {}; const elements = document.querySelectorAll('*'); for (const element of elements) { const tag = element.nodeName.toLocaleLowerCase(); const r = result[tag] || []; const cnt = insp(element); if (cnt !== element) { if (cnt.templateInfo) { r.push(['cnt0', cnt.templateInfo, element]); } if (element._templateInfo) { r.push(['cnt1', cnt._templateInfo, element]); } if (element.__templateInfo) { r.push(['cnt2', cnt.__templateInfo, element]); } } if (element.templateInfo) { r.push(['elm0', element.templateInfo, element]); } if (element._templateInfo) { r.push(['elm1', element._templateInfo, element]); } if (element.__templateInfo) { r.push(['elm2', element.__templateInfo, element]); } if (r.length >= 1) result[tag] = r; } return result; } const detachShadyRef = (node) => { const shadyArr = [...shadys]; for (let shady of shadyArr) { shady = kRef(shady); if (!shady) continue; const keys = [...Object.getOwnPropertyNames(shady), ...Object.getOwnPropertySymbols(shady)]; for (const p of keys) { const v = keys[p]; if (!v) continue; if (v instanceof Node) { if (node === v || node.contains(v)) keys[p] = _emptyElement; } else if (typeof v === 'object' && v.splice && v.length > 0) { for (let i = v.length - 1; i >= 0; i--) { const t = v[i]; if (t instanceof Node) { if (node === t || node.contains(t)) v.splice(i, 1); } } } } } shadyArr.length = 0; } if (MEMORY_RELEASE_NF00) { const __removedElements = new Set(); __removedElements.add = __removedElements.addOriginal || __removedElements.add; setInterval(() => { const nodesSet = new Set(); nodesSet.add = nodesSet.addOriginal || nodesSet.add; for (const nodeWr of __removedElements) { __removedElements.delete(nodeWr); const node = kRef(nodeWr); if (node && node.nodeType >= 1 && node.isConnected === false) { let rootNode; try { rootNode = node.getRootNode(); } catch (e) { } if (rootNode && rootNode.nodeType >= 1 && rootNode.nodeType !== 9 && rootNode.isConnected === true) { // do nothing } else { nodesSet.add(node); if (node.querySelectorAll) { for (const p of node.querySelectorAll('*')) { nodesSet.add(p); } } } } } for (const nodeWr of _removedElements) { _removedElements.delete(nodeWr); const node = kRef(nodeWr); if (node && node.isConnected === false) { __removedElements.add(nodeWr); } } if(nodesSet.size === 0) return; const nmSet = [..._nmSet].map(e => kRef(e)).filter(e => !!e); const nmMap = [..._nmMap].map(e => kRef(e)).filter(e => !!e); const nmMapV = [..._nmMapV].map(e => kRef(e)).filter(e => !!e); for (const node of nodesSet) { if (node === _emptyElement || node.__keepInstance038__ || node.t792) continue; const hasToolTips = !!((insp(node).$ || 0).tooltip); if (node && node.__shady_getRootNode) { let k = null; try { k = node.__shady_getRootNode(); } catch { } if (k && k.__keepInstance038__) k.__keepInstance038__ = false; if (k && k.nodeType >= 1 && k.isConnected === false) _removedElements.addNode(k); } if (node && node.getRootNode) { const k = node.getRootNode(); if (k && k.__keepInstance038__) k.__keepInstance038__ = false; if (k && k.nodeType >= 1 && k.isConnected === false) _removedElements.addNode(k); } if (node.__instances) { for (const k of node.__instances) { if (k && k.__keepInstance038__) k.__keepInstance038__ = false; if (k && k.nodeType >= 1 && k.isConnected === false) _removedElements.addNode(k); } // node.__instances.length = 0; } if (node && node.nodeType === 1) { if (typeof insp(node).__teardownInstance === 'function') { try { insp(node).__teardownInstance(); } catch (e) { } } else if (typeof node.__teardownInstance === 'function') { try { node.__teardownInstance(); } catch (e) { } } } if (node && node.nodeType === 1 && node.__detachAndRemoveInstance && (node.__instances || 0).length >= 1) { for (let i = node.__instances.length - 1; i >= 0; i--) { node.__detachAndRemoveInstance(i) } } if (node && node.nodeType === 1 && node.is === void 0) { if (typeof insp(node).dispose === 'function') { insp(node).dispose(); } else if (typeof node.dispose === 'function') { node.dispose(); } } if (node && node.nodeType === 1) { if (typeof insp(node).unobserve_ === 'function') { insp(node).unobserve_(); } else if (typeof node.unobserve_ === 'function') { node.unobserve_(); } } if (node) { if (typeof insp(node).unobserveNodes === 'function') { insp(node).unobserveNodes(); } else if (typeof node.unobserveNodes === 'function') { node.unobserveNodes(); } } // if (node && node.nodeType === 1) { // const cnt = insp(node); // const paths = cnt.__dataLinkedPaths; // if (paths && paths.length >= 1 && typeof cnt.unlinkPaths === 'function') { // for (let k in paths) { // cnt.unlinkPaths(k); // } // } // } const visibilityMonitorKeys = insp(node).visibilityMonitorKeys || node.visibilityMonitorKeys; if (visibilityMonitorKeys) { for (const entry of visibilityMonitorKeys) { if (entry.element) { entry.element = null } } visibilityMonitorKeys.length = 0; } const __instances = node.__instances; if (__instances) { for (const k of __instances) { if (k && k.__keepInstance038__) k.__keepInstance038__ = false; if (k && k.nodeType >= 1 && k.isConnected === false) _removedElements.addNode(k); } __instances.length = 0; } const sp = node.__shady_parentNode; if (sp && sp.nodeType >= 1 && sp.isConnected === false) _removedElements.addNode(sp); FULLY_REMOVE_ALL_EVENT_LISTENERS && node.removeAllEventListener001(); if (node && node.remove) node.remove(); /* if (node._templateInfo && node._templateInfo.content) { const templateInfoContent = node._templateInfo.content; if (templateInfoContent.nodeType >= 1 && templateInfoContent.isConnected === false) { _removedElements.addNode(templateInfoContent); } try{ node._templateInfo.content = null; }catch(e){} } */ if (node.__domApi) { node.__domApi = null; } const __shady = node.__shady; if (__shady) { delete node.__shady; if (shadyKey) { const shadyRootNode = __shady[shadyKey]; if (shadyRootNode) { // console.log(shadyRootNode); __shady[shadyKey] = null; for (const key of [...Object.getOwnPropertyNames(__shady), ...Object.getOwnPropertySymbols(__shady)]) { shadyRootNode[key] = null; } } } } const ceRoot = node.__CE_shadowRoot; if (ceRoot) { node.__CE_shadowRoot = null; if (ceRoot.nodeType >= 1 && ceRoot.isConnected === false) { _removedElements.addNode(ceRoot); } } // xTeardownTemplateInfo const snChildNodes = node.__shady_native_childNodes; if (snChildNodes.length > 0) { for (const node of snChildNodes) { if (node && node.nodeType >= 1 && node.isConnected === false) { _removedElements.addNode(node); } } snChildNodes.length = 0; } node.__shady_native_childNodes = null; const __templateInfo = node.__templateInfo; if (__templateInfo) { node.__templateInfo = null; // xTeardownTemplateInfo(__templateInfo); } if (hasToolTips && insp(node).$) { insp(node).$.tooltip = _emptyTipsElement; } if (node && node.nodeType >= 1) { const pd = Object.getOwnPropertyDescriptor(node, 'visibilityMonitorKeys'); if (pd && pd.value && pd.value.length >= 1) { const arr = pd.value; for (let i = 0; i < arr.length; i++) { arr[i].element = _emptyVisibilityElement; arr[i] = null; } } } if (node.__dataHost) { try { delete node.__dataHost } catch (e) { } try { node.__dataHost = null; } catch (e) { } } if (node.root) { try { delete node.root } catch (e) { } try { node.root = null; } catch (e) { } } if (node.children && node.children.splice) { try { delete node.children } catch (e) { } try { node.children = null; } catch (e) { } } if (node.__shady && typeof node.__shady === 'object') { try { node.__shady = null; } catch (e) { } } if (node.nodeType === 1) Reflect.setPrototypeOf(node, PlainHTMLElement.prototype); for (const prop of Object.getOwnPropertyNames(node)) { if (prop === 'host' && typeof (node.host || 0) === 'object') { if (node.nodeType === 11) { const nodeHost = node.host; if (nodeHost && nodeHost.nodeType >= 1) { node.host = _emptyElement; if (nodeHost.isConnected === false && nodeHost !== _emptyElement) { _removedElements.addNode(nodeHost); } } else { node.host = null; } } else { node.host = null; } continue; } const pd = Object.getOwnPropertyDescriptor(node, prop); if (pd.value) { const v = pd.value; if (typeof (v || 0) === 'object') node[prop] = null; else if (typeof (v || 0) === 'function') delete node[prop]; } } for (const prop of Object.getOwnPropertySymbols(node)) { const v = node[prop]; if (typeof (v || 0) === 'object' && !v.deref) node[prop] = null; } if (node.__shady_native_childNodes) { node.__shady_native_childNodes = _emptyElement.childNodes; } if (node.__shady_children) { node.__shady_children = _emptyElement.children; } for (const s of nmSet) s.delete(node); for (const m of nmMap) m.delete(node); mightTeardownShadyDomWrap(node); detachShadyRef(node); nf00.registerNode(node); // console.log(1883001, node) // console.log(3772001, node, node.countEvent767()) } nodesSet.clear(); }, 400); } if (FULLY_REMOVE_ALL_EVENT_LISTENERS && !EventTarget.prototype.addEventListener828 && !EventTarget.prototype.removeAllEventListener001) { const handlerMap = new WeakMap(); EventTarget.prototype.addEventListener828 = EventTarget.prototype.addEventListener; EventTarget.prototype.addEventListener = function (type, handler, option = void 0) { const wr = this[wk] || (this[wk] = mWeakRef(this)); let hds = handlerMap.get(wr); if (!hds) handlerMap.set(wr, (hds = new Set())); hds.add([type, handler, option]); return this.addEventListener828(type, handler, option); } EventTarget.prototype.removeEventListener828 = EventTarget.prototype.removeEventListener; EventTarget.prototype.removeEventListener = function (type, handler, option = void 0) { const wr = this[wk] || (this[wk] = mWeakRef(this)); let hds = handlerMap.get(wr); if (hds) { for (const entry of hds) { if (entry[0] === type && entry[1] === handler) { if (entry[2] === option) { hds.delete(entry); // break; } else if (FUZZY_EVENT_LISTENER_REMOVAL) { hds.delete(entry); this.removeEventListener828(type, handler, entry[2]); } } } } return this.removeEventListener828(type, handler, option); } EventTarget.prototype.countEvent767 = function(){ const wr = this[wk] || (this[wk] = mWeakRef(this)); return handlerMap.get(wr); } EventTarget.prototype.removeAllEventListener001 = function () { const wr = this[wk] || (this[wk] = mWeakRef(this)); let hds = handlerMap.get(wr); if (hds) { handlerMap.delete(wr); for (const entry of hds) { const [type, handler, option] = entry; entry.length = 0; this.removeEventListener828(type, handler, option); } hds.clear(); } } } const globalSetup = (key, setup)=>{ let symb = Symbol(); Object.defineProperty(Object.prototype, key, { get() { return this[symb]; }, set(nv) { if (typeof nv !== 'function') { this[symb] = nv; return true; } if (!(symb in this)) { setup(this); } this[symb] = nv; return true; }, configurable: true, enumerable: false }); } const toActualNode = (e) => { return e && e.getNode592177 ? e.getNode592177() : e; } const removeAllChildNodes = (o)=>{ if ((o instanceof Node) && o.nodeType >= 1) { let t, q = null; while ((t = o.firstChild) && t !== q) { try { t.__keepInstance038__ = false; t.remove(); _removedElements.addNode(t); q = t; } catch (e) { } } try { o.__keepInstance038__ = false; o.remove(); _removedElements.addNode(o); } catch (e) { } } } let shadyInited = false; let shadyKey = ''; let shadyKeyX = ''; const setupShady = () => { shadyInited = true; let p = document.createComment('1'); const x = document.implementation.createHTMLDocument(); const y = x.firstElementChild; y.appendChild(p); let key = ''; p.__shady = new Proxy({}, { get(target, prop) { key = prop; throw new Error(); }, set(target, prop, val) { throw new Error(); } }) try { p.__shady_getRootNode() } catch (e) { } let __shady = null; try { p.__shady = null; p.__shady_getRootNode() __shady = p.__shady; } catch (e) { } y.removeChild(p); if (key && __shady && typeof __shady === 'object' && !('nodeType' in __shady) && !('nodeName' in __shady)) { const sProto = Reflect.getPrototypeOf(__shady); const symb = Symbol('__shady'); // const symbKeys = ['root', 'firstChild', 'lastChild', 'parentNode', 'nextSibling', 'previousSibling']; Object.defineProperty(sProto, key, { get() { if(!this[wk]) this[wk] = mWeakRef(this); shadys.add(this[wk]); return kRef(this[symb]); }, set(nv) { if(!this[wk]) this[wk] = mWeakRef(this); shadys.add(this[wk]); if (typeof (nv || 0) === 'object') { if (!nv[wk]) nv[wk] = mWeakRef(nv); this[symb] = nv[wk]; } else { this[symb] = nv; } return true; }, enumerable: false, configurable: true }); shadyKey = key; console.log('[yt-js-engine-tamer] shadyKey', key); } if (0 && key && __shady && typeof __shady === 'object' && !('nodeType' in __shady) && !('nodeName' in __shady)) { const sProto = Reflect.getPrototypeOf(__shady); const symb = Symbol('__shady'); const symbKeys = ['root', 'firstChild', 'lastChild', 'parentNode', 'nextSibling', 'previousSibling']; Object.defineProperty(sProto, key, { get() { if(!this[wk]) this[wk] = mWeakRef(this); shadys.add(this[wk]); return kRef(this[symb]); }, set(nv) { if(!this[wk]) this[wk] = mWeakRef(this); shadys.add(this[wk]); if (typeof (nv || 0) === 'object') { if (!nv[wk]) nv[wk] = mWeakRef(nv); this[symb] = nv[wk]; } else { this[symb] = nv; } return true; }, enumerable: false, configurable: true }); shadyKey = key; console.log('[yt-js-engine-tamer] shadyKey', key); let shadyKeyCached = new Set(); const fixLastShady = () => { const shady = lastShady; for (const key of Object.keys(shady)) { if (shadyKeyCached.has(key)) continue; shadyKeyCached.add(key); if ((typeof shady[key] === 'object') && !(shady[key] || 0).deref) { if (!shadyKeyX && shady[key] === shady.root) { shadyKeyX = key; const sProto = Reflect.getPrototypeOf(shady); const symb = Symbol(); Object.defineProperty(sProto, shadyKeyX, { get() { return kRef(this[symb]) }, set(nv) { if (typeof (nv || 0) === 'object') { nv = kRef(nv); if (!nv[wk]) nv[wk] = mWeakRef(nv); this[symb] = nv[wk]; } else { this[symb] = nv; } return true; }, enumerable: false, configurable: true, }); delete shady[key]; shady[key] = shady.root; }; // console.log(12883, shady[key], key); // assignedNodes, assignedSlot, ja, K, childNodes, ... (keep strong ref) } } } let lastShady = null; symbKeys.forEach(key => { const symb = Symbol(key); Object.defineProperty(sProto, key, { get() { if (this !== lastShady && lastShady) fixLastShady(); lastShady = this; return kRef(this[symb]); }, set(nv) { if (this !== lastShady && lastShady) fixLastShady(); lastShady = this; if (typeof (nv || 0) === 'object') { nv = kRef(nv); if (!nv[wk]) nv[wk] = mWeakRef(nv); this[symb] = nv[wk]; } else { this[symb] = nv; } return true; }, enumerable: false, configurable: true }); }); } } const stampedNodes = new Map(); /* !!!!!! CAUTION FOR MEMORY LEAKAGE !!!!!!! */ stampedNodes.set = stampedNodes.setOriginal || stampedNodes.set; const stampedFragment = new Map(); /* !!!!!! CAUTION FOR MEMORY LEAKAGE !!!!!!! */ stampedFragment.set = stampedFragment.setOriginal || stampedFragment.set; class WeakNodeC extends Node { constructor() { } addEventListener(type, listener, option = void 0) { const nodeWr = stampedNodes.get(this.eid); const node = kRef(nodeWr); if (!node) return; return node.addEventListener(type, listener, option); } removeEventListener(type, listener, option = void 0) { const nodeWr = stampedNodes.get(this.eid); const node = kRef(nodeWr); if (!node) return; return node.removeEventListener(type, listener, option); } getNode592177() { const nodeWr = stampedNodes.get(this.eid); const node = kRef(nodeWr); return node; } set __dataHost(nv) { const nodeWr = stampedNodes.get(this.eid); const node = kRef(nodeWr); if (!node) return; node.__dataHost = nv; return true; } get __dataHost() { const nodeWr = stampedNodes.get(this.eid); const node = kRef(nodeWr); if (!node) return; return node.__dataHost; } set __dataCompoundStorage(nv) { const nodeWr = stampedNodes.get(this.eid); const node = kRef(nodeWr); if (!node) return; node.__dataCompoundStorage = nv; return true; } get __dataCompoundStorage() { const nodeWr = stampedNodes.get(this.eid); const node = kRef(nodeWr); if (!node) return; return node.__dataCompoundStorage; } set __shady_className(nv) { const nodeWr = stampedNodes.get(this.eid); const node = kRef(nodeWr); if (!node) return; node.__shady_className = nv; // debugger; return true; } get __shady_className() { const nodeWr = stampedNodes.get(this.eid); const node = kRef(nodeWr); if (!node) return; return node.__shady_className; } } if (FIX_TEMPLATE_BINDING) { const templateMap = new Map(); /* !!!!!! CAUTION FOR MEMORY LEAKAGE !!!!!!! */ templateMap.set = templateMap.setOriginal || templateMap.set; // const parsedTemplate = new Map(); const it0 = Date.now() - 80000000000; const genId = () => `${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}_${(Date.now() - it0).toString(36)}`; /* M.prototype._bindTemplate = function(N, R) { var X = this.constructor._parseTemplate(N) , A = this.__preBoundTemplateInfo == X; if (!A) for (var l in X.propertyEffects) this._createPropertyAccessor(l); R ? (X = Object.create(X), X.wasPreBound = A, this.__templateInfo ? (N = N._parentTemplateInfo || this.__templateInfo, R = N.lastChild, X.parent = N, N.lastChild = X, (X.previousSibling = R) ? R.nextSibling = X : N.firstChild = X) : this.__templateInfo = X) : this.__preBoundTemplateInfo = X; return X } ; */ /* ** this.constructor._parseTemplate ** d._parseTemplate = function(N, R) { if (!N._templateInfo) { var X = N._templateInfo = {}; X.nodeInfoList = []; X.nestedTemplate = !!R; X.stripWhiteSpace = R && R.stripWhiteSpace || N.hasAttribute && N.hasAttribute("strip-whitespace"); this._parseTemplateContent(N, X, { parent: null }) } return N._templateInfo } */ const exceptionTriggered = new Set(); const gxx = (window.gxxC572 || (window.gxxC572 = new Set())); // let initied1 = false; // let _parseTemplateByPass = false; const setup1 = (qxx) => { // if(initied1) return; // initied1 = true; const proto = qxx; const constructor = proto.constructor; const _bindTemplate = proto._bindTemplate; // console.log(12883, proto, constructor) const _parseTemplate = constructor._parseTemplate; if (typeof _parseTemplate === 'function' && _parseTemplate.length === 2 && !constructor._parseTemplate322) { FIX_TEMPLATE_BINDING_SHOW_MESSAGE && console.log('Hack00: _parseTemplate', _parseTemplate); constructor._parseTemplate322 = _parseTemplate; const parsedResults = new WeakMap(); const _templateInfoPd = { get() { if (!this || !this[wk]) return undefined; const r = parsedResults.get(this[wk]); return r; }, set(nv) { delete this._templateInfo; this._templateInfo = nv; console.warn('_templateInfoPd set'); return true; }, enumerable: true, configurable: true }; constructor._parseTemplate = function (N, R) { if (!N) return _parseTemplate.call(this, N, R); if (!N[wk]) N[wk] = mWeakRef(N); let r = parsedResults.get(N[wk]); if (r) return r; r = _parseTemplate.call(this, N, R); if (r && !parsedResults.has(N[wk])) { parsedResults.set(N[wk], r); r.iAm68 = '_templateInfo'; N.iHave68 = '_templateInfo'; if (N._templateInfo && N._templateInfo === r) { delete N._templateInfo; if (!N._templateInfo) { Object.defineProperty(N, '_templateInfo', _templateInfoPd); } } } return r; } } if (typeof _bindTemplate === 'function' && _bindTemplate.length === 2 && !proto._bindTemplate322) { FIX_TEMPLATE_BINDING_SHOW_MESSAGE && console.log('Hack00: _bindTemplate', _bindTemplate); proto._bindTemplate322 = _bindTemplate; proto._bindTemplate = function (N, R) { // R = boolean true or undefined // N = template elemenet let M = N; if (typeof (N || 0) === 'object' && N instanceof HTMLTemplateElement && (N.content || 0).nodeType === 11) { let componentIs = ''; try { componentIs = this ? this.is : ''; } catch (e) { } if (typeof (componentIs || 0) === 'string') { if (!templateMap.has(componentIs)) { templateMap.set(componentIs, N); // const parser = this.constructor; // console.log(3882, parser._parseTemplate) /* if (parser._parseTemplate && !parser._parseTemplate477 && parser._parseTemplate.length === 2) { parser._parseTemplate477 = parser._parseTemplate; const _parseTemplate477 = parser._parseTemplate477; parser._parseTemplate = function (N, R) { if (!_parseTemplateByPass && N && N[wk]) { const u = parsedTemplate.get(N[wk]); if (u) { console.log(1838, u) return u; } } return _parseTemplate477.call(this, N, R); }; } if (parser._parseTemplate && parser._parseTemplate477) { if (N && !N[wk]) N[wk] = mWeakRef(N); if (!parsedTemplate.has(N[wk])) { _parseTemplateByPass = true; parsedTemplate.set(N[wk], parser._parseTemplate477(N)); _parseTemplateByPass = false; } } */ } else { M = templateMap.get(componentIs); } } } let r_ = null; // Promise.resolve(N).then((N) => { // console.log(3488,N.templateInfo, N.templateInfo === r_); // }) const r = _bindTemplate.call(this, M, R); r_ = r; return r; } } const _runEffectsForTemplate = proto._runEffectsForTemplate; if (typeof _runEffectsForTemplate === 'function' && _runEffectsForTemplate.length === 4 && !proto._runEffectsForTemplate322) { proto._runEffectsForTemplate322 = _runEffectsForTemplate; // note: fastDomIf does not work well with runEffects ... // so no runEffects actaully? const runner = (Tw, Nw, Rw, Xw, Aw) => { try { // console.log(988003) const T = kRef(Tw); // this const N = kRef(Nw); // __templateInfo if (!T || !N) return; // console.log(988004) const R = kRef(Rw); // __data const X = kRef(Xw); // temp Data ? const A = kRef(Aw); // boolean ? if (typeof (X || 0) === 'object') gxx.delete(X); if (typeof (A || 0) === 'object') gxx.delete(A); // console.log(988005) const nodeList_ = N.nodeList; // console.log(988006, nodeList_) const nodeList = nodeList_ ? nodeList_.map(e => toActualNode(e)) : nodeList_; // console.log(988007, nodeList) const Nx = { propertyEffects: N.propertyEffects, nodeList: nodeList, firstChild: kRef(N.firstChild) }; // if (kRef(N.firstChild)) { // console.log(977001, Nx) // } // console.log(988009, Nx, R, X, A) { const o = Nx; const { propertyEffects, nodeList, firstChild } = o; if (propertyEffects && nodeList && nodeList.length >= 0) { for (const [effectKey, propertyEffectArr] of Object.entries(propertyEffects)) { for (let i = propertyEffectArr.length - 1; i >= 0; i--) { const propertyEffect = propertyEffectArr[i]; const info = (propertyEffect || 0).info; if (info && typeof info.index === 'number' && !nodeList[info.index]) { propertyEffectArr.splice(i, 1); } } } } } // console.log({T, Nx, R, X , A }) // console.log(1737001, T) // console.log(1737002, Nx) // console.log(1737003, R) // console.log(1737004, X) // console.log(1737005, A) const hostElement = T.hostElement; const pChildren = (hostElement instanceof Node && hostElement.isConnected === true) ? [...hostElement.childNodes] : null; renderPathMake(pChildren); try { _runEffectsForTemplate.call(T, Nx, R, X, A); } catch (err) { // debugger; const stack = err.stack; if (!exceptionTriggered.has(stack)) { exceptionTriggered.add(stack); console.warn(`[yt-js-engine-tamer] _runEffectsForTemplate EXCEPTION`+"\n\n", err); } } (pChildren || 0).length >= 1 && Promise.resolve(pChildren).then((pChildren) => { for (const node of pChildren) { if (node.parentNode !== hostElement && node.__weakNodeCId57__) { _removedElements.addNode(node); // rn54001b } // if (node.isConnected === false) { // let tNode = node; // let pNode; // while ((pNode = tNode.parentNode) && pNode.nodeType >= 1) { // tNode = pNode; // } // // _removedElements.addNode(tNode); // rn54001 // } } pChildren.length = 0; pChildren = null; }); } catch (err) { // debugger; // const stack = err.stack; // if (!exceptionTriggered.has(stack)) { // exceptionTriggered.add(stack); // console.warn(`[yt-js-engine-tamer] _runEffectsForTemplate EXCEPTION`, err); console.error(err); // } } }; proto._runEffectsForTemplate = function (N, R, X, A) { // console.log(988001) /* N {wasPreBound: true, nodeList: Array(23)} R {showInput: false, narrow: false, menuStrings: {…}, pageDarkTheme: true, theater: false, …} X {showInput: undefined, narrow: undefined, menuStrings: undefined, pageDarkTheme: undefined, theater: undefined, …} A false */ const Nw = (!N || typeof N !== 'object') ? N : (N[wk] || (N[wk] = mWeakRef(N))); // __templateInfo const Xw = (!X || typeof X !== 'object') ? X : (X[wk] || (X[wk] = mWeakRef(X))); const Rw = (!R || typeof R !== 'object') ? R : (R[wk] || (R[wk] = mWeakRef(R))); // __data const Aw = (!A || typeof A !== 'object') ? A : (A[wk] || (A[wk] = mWeakRef(A))); if (typeof (X || 0) === 'object') gxx.add(X); if (typeof (A || 0) === 'object') gxx.add(A); const Tw = (!this || typeof this !== 'object') ? this : (this[wk] || (this[wk] = mWeakRef(this))); if (N.runEffects) { N.runEffects(() => { runner(Tw, Nw, Rw, Xw, Aw); }, R, A); } else { runner(Tw, Nw, Rw, Xw, Aw); } // console.log(988002) // const N_ = // var l = this // , k = function (T, W) { // XK(l, N.propertyEffects, T, X, W, N.nodeList); // for (var w = N.firstChild; w; w = w.nextSibling) // l._runEffectsForTemplate(w, T, X, W) // }; // N.runEffects ? N.runEffects(k, R, A) : k(R, A) } } const _registerHost = proto._registerHost; if (_registerHost && !proto._registerHost322 && _registerHost.length === 0) { proto._registerHost322 = _registerHost; const map = new WeakMap(); map.set = map.setOriginal || map.set; proto._registerHost = function () { if (!map.has(this)) { map.set(this, (this.__dataHost || null)); Object.defineProperty(this, '__dataHost', { get() { return kRef(map.get(this)) || null }, set(nv) { const w = kRef(nv); if (!w) { map.set(this, null); } else { if (!w[wk]) w[wk] = mWeakRef(w); let byPass = false; if (this.is === 'ytd-masthead') byPass = true; if (byPass) { map.set(this, w); } else { map.set(this, w[wk]); } } return true; }, enumerable: true, configurable: true }); } let previousDataHost = this.__dataHost; renderPathMake(previousDataHost) let r = _registerHost.call(this); let currentDataHost = this.__dataHost; if (currentDataHost !== previousDataHost) { // future use only if (previousDataHost && previousDataHost.nodeType >= 1 && previousDataHost.isConnected === false) { _removedElements.addNode(previousDataHost); // rn54002 } } return r; } } } globalSetup('_removeBoundDom', setup1); /* M.prototype._stampTemplate = function(N, R) { R = R || this._bindTemplate(N, !0); aU.push(this); N = d.prototype._stampTemplate.call(this, N, R); aU.pop(); R.nodeList = N.nodeList; if (!R.wasPreBound) for (var X = R.childNodes = [], A = N.firstChild; A; A = A.nextSibling) X.push(A); N.templateInfo = R; X = R.nodeList; A = R.nodeInfoList; if (A.length) for (var l = 0; l < A.length; l++) { var k = X[l] , T = A[l].bindings; if (T) for (var W = 0; W < T.length; W++) { var w = T[W] , p = k , h = w; if (h.isCompound) { for (var I = p.__dataCompoundStorage || (p.__dataCompoundStorage = {}), O = h.parts, y = Array(O.length), c = 0; c < O.length; c++) y[c] = O[c].literal; O = h.target; I[O] = y; h.literal && h.kind == "property" && (O === "className" && (p = (0, _.FK)(p)), p[O] = h.literal) } gM2(k, this, w) } k.__dataHost = this } this.__dataClientsReady && (this._runEffectsForTemplate(R, this.__data, null, !1), this._flushClients()); return N } ; */ const wnc = new Set(); const __listWeakNodeC__ = window.__listWeakNodeC__ = () => { const result = __listWeakNodeC0__(); return [...result].sort(); } const __listWeakNodeC0__ = () => { let result = new Set(); for (const nodeC of wnc) { for (const k of Object.getOwnPropertyNames(nodeC)) { result.add(k) } } return result; } setInterval(() => { if (wnc.size > 0 && __listWeakNodeC0__().size !== 1) console.warn(`[yt-js-engine-tamer] WARNING 0xF04E: ${__listWeakNodeC__()}`); }, 400); const dollarStore = new Map(); const makeDollarClass = (idsJoined, ids) => { const $ = class {}; const a = $.prototype; ids.forEach(id => { const p = `## ${id}`; Object.defineProperty(a, id, { get() { return kRef(this[p]); }, set(nv) { if (nv instanceof Node) { if (!nv[wk]) nv[wk] = mWeakRef(nv); this[p] = nv[wk]; } else { this[p] = nv; } return true; }, enumerable: true, configurable: true }); }); a.__w646__ = true; dollarStore.set(idsJoined, $); return $; } // let initied2 = false; const setup2 = (qxx) => { // if(initied2) return; // initied2 = true; const proto = qxx; const constructor = proto.constructor; const _stampTemplate = proto._stampTemplate; // console.log(12883, proto, constructor) if (typeof _stampTemplate === 'function' && _stampTemplate.length === 2 && !proto._stampTemplate374) { proto._stampTemplate374 = _stampTemplate; proto._stampTemplate = function (N, R) { if (!shadyInited) setupShady(); let e__ = null; try { // R = boolean true or binded template // N = template elemenet let M = N; let r_ = null; const r = _stampTemplate.call(this, M, R); // return the fragment created with nodeList r_ = r; // if (r && r.host) { // console.log(2883, R.host) // } if (r && r.$ && !r.$.__w646__) { const $ = r.$; const ids = Object.getOwnPropertyNames($) const idsJoined = ids.join(' '); const C = dollarStore.get(idsJoined) || makeDollarClass(idsJoined, ids); const objVals = { ...$ }; Reflect.setPrototypeOf($, C.prototype); for (const id of ids) { delete $[id]; $[id] = objVals[id]; } } if (r && r.nodeType === 11 && !r.__fragId57__) { const fid = genId(); r.__fragId57__ = fid; if (!r[wk]) r[wk] = mWeakRef(r); stampedFragment.set(fid, r[wk]); if (r.nodeList) { const nl = r.nodeList; nl.__belongFragId57__ = fid; for (let i = 0, l = nl.length; i < l; i++) { const t = nl[i]; if (t && t.nodeType >= 1 && !(t instanceof ShadowRoot)) { if (!t[wk]) t[wk] = mWeakRef(t); const eid = `${fid}::${i}`; const wn = Object.create(WeakNodeC.prototype); wn.eid = eid; wnc.add(wn); nl[i] = wn; // we believe the stampedNodes shall be attached to the document DomTree stampedNodes.set(eid, t[wk]); t.__weakNodeCId57__ = eid; } else { if (t instanceof ShadowRoot) { console.warn('[yt-js-engine-tamer]', 'ShadowRoot in _stampTemplate'); } } } } } return r; } catch (e) { console.error(e); e__ = e; } throw e__; } } } globalSetup('_addMethodEventListenerToNode', setup2); } if (FIX_FRAGEMENT_HOST && !DocumentFragment.prototype.host577) { DocumentFragment.prototype.host577 = true; let propsOK = false; const finalizer = new FinalizationRegistry_((frag) => { if (!frag.hostCleared55) { frag.hostCleared55 = true; for (const p of [...Object.getOwnPropertyNames(frag), ...Object.getOwnPropertySymbols(frag)]) { const v = frag[p] || 0; if (typeof v === 'object') { frag[p] = null; if (v.length > 0) v.length = 0; } } } }); Object.defineProperty(DocumentFragment.prototype, 'host', { get() { const r = kRef(this.host677); if (!propsOK && this.nodeType === 11 && r) setupProps(Reflect.getPrototypeOf(this)); return r; }, set(nv) { nv = kRef(nv); if (typeof (nv || 0) === 'object' && nv.nodeType === 1) { if (!nv[wk]) nv[wk] = mWeakRef(nv); this.host677 = nv[wk]; finalizer.register(nv, this); } else { this.host677 = nv; } return true; }, enumerable: true, configurable: true }); const setupProps = (fragProto) => { propsOK = true; ["ownerDocument", "baseURI", "isConnected"].forEach(function (b) { const pd = Object.getOwnPropertyDescriptor(fragProto, b); const pdn = Object.getOwnPropertyDescriptor(Node.prototype, b); const get1 = pd && pd.get; const get2 = pdn && pdn.get; if (get1 && get2) { delete fragProto[b]; Object.defineProperty(fragProto, b, { get: function () { return this.host ? get1.call(this) : get2.call(this); }, configurable: !0 }); } }); } } if (XFlag) { const cMap = new Set(); cMap.add = cMap.addOriginal || cMap.add; const yMap = new Set(); yMap.add = yMap.addOriginal || yMap.add; const ydMap = new Set(); ydMap.add = ydMap.addOriginal || ydMap.add; window.yMap = yMap; window.cMap = cMap; window.ydMap = ydMap; const constructAts = new Set(); constructAts.add = constructAts.addOriginal || constructAts.add; window.constructAts = constructAts; const kMap = new WeakMap(); const kRefProp = (wr, prop)=>{ let o = kRef(wr); return o ? o[prop] : null; } const wrObj = (objRef, props) => { let wr = mWeakRef(objRef); if (wr === objRef || !props || !props.length) return wr; let properties = {}; props.forEach(k => { properties[k] = { get() { return kRefProp(this, k) }, enumerable: false, configurable: true }; }); Object.defineProperties(wr, properties); return wr; } const sProtos = {}; const setupCProto = function (cProto) { if(cProto === Object.prototype) return; if (!kMap.get(cProto)) kMap.set(cProto, `protoKey0_${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}_${Date.now()}`); cProto[kMap.get(cProto)] = true; // debugger; if (FIX_SHADY_METHODS && cProto.appendChild && cProto.cloneNode && cProto.contains && cProto.getRootNode && cProto.insertBefore && cProto.querySelector && cProto.querySelectorAll && cProto.removeAttribute && cProto.removeChild && cProto.replaceChild && cProto.setAttribute && cProto.is === undefined && !(cProto instanceof Node)) { if (!cProto.krmv757) { cProto.krmv757 = true; // const props = Object.entries(Object.getOwnPropertyDescriptors(cProto)).filter(a => { // const e = a[1]; // return typeof e.value === 'function' && e.writable === true && e.enumerable === true && e.configurable === true // }); // const keys = props.map(a => a[0]); const keys = ['querySelector', 'querySelectorAll']; keys.forEach(key => { if (!(key in HTMLTitleElement.prototype)) return; const bey = `${key}588`; cProto[bey] = cProto[key]; const isDomChange = key === 'appendChild' || key === 'insertBefore' || key === 'removeChild' || key === 'replaceChild'; cProto[key] = function () { const p = ((this || 0).root || 0).node; if (!isDomChange && (p instanceof Element) && p.nodeType === 1) { return p[key](...arguments); } else { return this[bey](...arguments); } } }); } } 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]; constructAts.add(constructAt) if (MemoryFix_Flag002 & 32) { if (!cProto.dk322 && (cProto.__attachInstance || cProto.__detachInstance)) { fixDetachFn(cProto); } } if (MemoryFix_Flag002 & 2) { if (cProto._setPendingProperty && !cProto.__setPropDX38__) { cProto.__setPropDX38__ = true; if (cProto._setPendingProperty.length === 3) { cProto._setPendingProperty.bind = sProtos._setPendingProperty$bind || (sProtos._setPendingProperty$bind = function (obj, ...args) { let wobj = obj[wk] || (obj[wk] = mWeakRef(obj)); return () => { const obj = kRef(wobj); let u = Reflect.apply(this, obj, args); args.length = 0; wobj = null; return u; }; }); } } } const cProtoConstructor = cProto.constructor; if (MemoryFix_Flag002 & 8) { if (cProtoConstructor._parseBindings && !cProtoConstructor.__parseBindingsDX38__) { cProtoConstructor.__parseBindingsDX38__ = true; ydMap.add(cProtoConstructor); if (cProtoConstructor._parseBindings.length === 2) { cProtoConstructor._parseBindings3858 = cProtoConstructor._parseBindings; cProtoConstructor._parseBindings = sProtos._parseBindings || (sProtos._parseBindings = function (c, d) { let p = this._parseBindings3858(c, d); this.__bindingsArrs__ = this.__bindingsArrs__ || []; if (p) this.__bindingsArrs__.push(p); return p; }); } } } /* a.prototype._initializeProperties = function() { if (Em && this.hasAttribute("disable-upgrade")) this.__isUpgradeDisabled = !0; else { var e = Object.getPrototypeOf(this); e.hasOwnProperty("__hasRegisterFinished") || (this._registered(), e.__hasRegisterFinished = !0); b.prototype._initializeProperties.call(this); this.root = this; this.created(); fpb && !this._legacyForceObservedAttributes && (this.hasAttributes() ? this._takeAttributes() : this.parentNode || (this.__needsAttributesAtConnected = !0)); this._applyListeners() } } */ /* bOa = function(a, b, c) { var d = bya(a.prototype, $Na, a.prototype.behaviors); d.prototype.is = b; d.prototype.localName = b; c && aOa(d, c); return function(e) { e && (d.prototype.hostElement = e); var g = new d; g.root = g; g.hostElement = e; return g } } */ } const symDH = Symbol(); const wfStore = new WeakMap(); const wrapF = function (f, key) { if (wfStore.get(f)) return wfStore.get(f); let g = function () { const o = kRef(this); if (!o) return; const cnt = insp(o); // if (cnt === o) return; // if (!('ready' in cnt)) return; return f.apply(o, arguments); }; g.key38 = key; g.originalFunc38 = f; g.__wrapF84__ = true; wfStore.set(f, g); wfStore.set(g, g); return g; }; if (MemoryFix_Flag002 & 16) { ['_createPropertyAccessor', '_addPropertyToAttributeMap', '_definePropertyAccessor', 'ready', '_initializeProperties', '_initializeInstanceProperties', '_setProperty', '_getProperty', '_setPendingProperty', '_isPropertyPending', '_invalidateProperties', '_enableProperties', '_flushProperties', '_shouldPropertiesChange', '_propertiesChanged', '_shouldPropertyChange', 'attributeChangedCallback', '_attributeToProperty', '_propertyToAttribute', '_valueToNodeAttribute', '_serializeValue', '_deserializeValue'].forEach(key => { Object.defineProperty(Node.prototype, key, { get() { return this[`__a0939${key}__`]; }, set(nv) { if (typeof nv !== 'function') return; const g = (nv.__wrapF84__) ? nv : wrapF(nv, key); this[`__a0939${key}__`] = g; return true; } }); }); } // const wm = new WeakMap(); const fixDetachFn = (tpProto) => { // & 32 if (tpProto.dk322) return; tpProto.dk322 = true; window.__fixTemplateReuse1058__ = true; tpProto.__ensureTemplatized994 = tpProto.__ensureTemplatized; if (typeof tpProto.__ensureTemplatized994 === 'function' && tpProto.__ensureTemplatized994.length === 0) { tpProto.__ensureTemplatized = function () { // console.log(18470001) return this.__ensureTemplatized994(); } } tpProto.__updateInstances994 = tpProto.__updateInstances; if (typeof tpProto.__updateInstances994 === 'function' && tpProto.__updateInstances994.length === 3) { let bypass= false; tpProto.__updateInstances = function (a, b, c) { // const a_ = [...a]; if(!bypass && a === this.items && (a||0).length >=1 ){ bypass = true; // console.log(18470002, a, b,c) let e; for (e = 0; e < b; e++) { let g = this.__instances[e] , k = c[e] , m = a[k]; if(g && typeof (m||0) === 'object'){ // const q = g._shouldPropertyChange; // g._shouldPropertyChange = ()=>true; // g[this.as] = {}; // a_[k]=a[k] = m; // g[this.as] = m; // use public interface notifyPath instead of internal interface _setPendingProperty const m_ = a[k] = Object.assign({}, a[k]); try { g.notifyPath(this.as, {}); } catch (e) { } try { g.notifyPath(this.as, m_); } catch (e) { } // g._setPendingProperty(this.as, {}); // g._setPendingProperty(this.as, m); // g._setPendingProperty(this.indexAs, e); // g._setPendingProperty(this.itemsIndexAs, k); // delete g._shouldPropertyChange; // if(g._shouldPropertyChange !== q) g._shouldPropertyChange = q; } } bypass = false; } const r = this.__updateInstances994(a,b,c); // for (e = 0; e < b; e++) { // let g = this.__instances[e] // , k = c[e] // , m = a_[k]; // if(g){ // // const q = g._shouldPropertyChange; // // g._shouldPropertyChange = ()=>true; // // g[this.as] = m; // // g._setPendingProperty(this.as, {}); // // g._setPendingProperty(this.as, m); // // g._setPendingProperty(this.indexAs, e); // // g._setPendingProperty(this.itemsIndexAs, k); // // delete g._shouldPropertyChange; // // if(g._shouldPropertyChange !== q) g._shouldPropertyChange = q; // } // } return r; } } tpProto.__detachInstance994 = tpProto.__detachInstance; if (typeof tpProto.__detachInstance994 === 'function' && tpProto.__detachInstance994.length === 1) { tpProto.__detachInstance = function (a) { const u = this.__instances[a]; if (u && !u.__keepInstance038__) u.__keepInstance038__ = true; const children = (u || 0).children; if (children && children.length >= 1) { const pp = document.createDocumentFragment(); for (const s of [...children]) { pp.appendChild(s); } } try { return this.__detachInstance994(a); } catch (e) { } return u; } } tpProto.__attachInstance994 = tpProto.__attachInstance; if (typeof tpProto.__attachInstance994 === 'function' && tpProto.__attachInstance994.length === 2) { tpProto.__attachInstance = function (a, b) { const u = this.__instances[a]; if (u && !u.__keepInstance038__) u.__keepInstance038__ = true; if (u && u.root && b) { const root = u.root; const pp = document.createDocumentFragment(); pp.appendChild(root); root.appendChild(pp); const r = this.__attachInstance994(a, b); if (!this.__chunkingId) this.__chunkingId = 0.25; return r; } } } } const ytTemplateDomEntry = (tpProto) => { console.log('ytTemplateDomEntry triggered') const convertToWeakArr = (arr) => { if (arr.isWeak) return; for (let i = 0, l = arr.length; i < l; i++) { const o = arr[i] if (o) { let p = kRef(o) if (!p) arr[i] = null; else { if (!o[wk]) o[wk] = mWeakRef(o); arr[i] = o[wk]; } } } arr.isWeak = true; } const convertToNormalArr = (arr) => { if (!arr.isWeak) return; for (let i = 0, l = arr.length; i < l; i++) { const o = arr[i] if (o) { let p = kRef(o) arr[i] = p; } } arr.isWeak = false; } if (MemoryFix_Flag002 & 256) { Object.defineProperty(tpProto, '__instances', { get() { this.dk322 || fixDetachFn(Reflect.getPrototypeOf(this)); let arr = this.__instances_actual471__; if (arr && arr.isWeak) { convertToNormalArr(arr); for (let i = arr.length - 1; i >= 0; i--) { const t = arr[i]; if (!t) arr.splice(i, 1); else if (!t.__keepInstance038__) t.__keepInstance038__ = true; } Promise.resolve(arr).then(convertToWeakArr); } return arr; }, set(nv) { this.dk322 || fixDetachFn(Reflect.getPrototypeOf(this)); this.__instances_actual471__ = nv; if (nv && !nv.isWeak) { Promise.resolve(nv).then(convertToWeakArr); } return true; }, enumerable: false, configurable: true }); } // console.log(91901, tpProto.__detachInstance) if (MemoryFix_Flag002 & 32) { if (tpProto.__detachInstance) { fixDetachFn(tpProto); } else { Promise.resolve(tpProto).then((tpProto) => { // console.log(91902, tpProto.__detachInstance) fixDetachFn(tpProto); }) } } } if (MemoryFix_Flag002 & 32) { Object.defineProperty(Object.prototype, '__ensureTemplatized', { set(nv) { if (nv === true) return false; tpProto = this; if ('connectedCallback' in tpProto && tpProto !== Node.prototype && !tpProto.__domDX37__) { tpProto.__domDX37__ = true; ytTemplateDomEntry(tpProto); } this.__ensureTemplatized949__ = nv; return true; }, get() { return this.__ensureTemplatized949__; } }); } if (MemoryFix_Flag002 & 64) { HTMLElement_.prototype.__dataHostBinding374 = true; Object.defineProperty(HTMLElement_.prototype, '__dataHost', { get() { return kRef(this.__dataHostWr413__); }, set(nv) { if (nv && typeof nv === 'object' && !nv.deref) { if (!nv[wk]) nv[wk] = mWeakRef(nv); nv = nv[wk]; } this.__dataHostWr413__ = nv; return true; } }); } const setupYProto = function (yProto) { if(yProto === Object.prototype) return; if (!kMap.get(yProto)) kMap.set(yProto, `protoKey1_${Math.floor(Math.random() * 314159265359 + 314159265359).toString(36)}_${Date.now()}`); yProto[kMap.get(yProto)] = true; if (FIX_DOM_IF_DETACH && !yProto.disconnectedCallback277 && yProto.disconnectedCallback && typeof yProto._readyClients === 'function' && typeof yProto._canApplyPropertyDefault === 'function' && typeof yProto._attachDom === 'function' && !yProto.is && typeof yProto.constructor._finalizeTemplate === 'function') { const disconnectedCallback277 = yProto.disconnectedCallback; yProto.disconnectedCallback277 = true; yProto.disconnectedCallback = function () { disconnectedCallback277.call(this); if (this.nodeName === 'DOM-IF' && this.__instance && typeof this.__teardownInstance === 'function') { const shadyParent = (this.__shady_parentNode || 0); const actualParent = (this.parentNode || 0); if (shadyParent !== actualParent && shadyParent.nodeType === 11 && actualParent.nodeType === 11) { // && (shadyParent.compareDocumentPosition(actualParent) & (1|8|16) === 1) // if (!this.restamp && !this.id && this.__ctor && this.isConnected === false) { const children = (this.__instance.children || 0).length; if (children >= 1) { try { this.__teardownInstance(); } catch (e) { } } // } } } } } if (MemoryFix_Flag002 & 32) { if (!yProto.dk322 && (yProto.__attachInstance || yProto.__detachInstance)) { fixDetachFn(yProto); } } if (MemoryFix_Flag002 & 128) { if (!yProto.__dataHostBinding374) { yProto.__dataHostBinding374 = true; Object.defineProperty(yProto, '__dataHost', { set(nv) { let dh = nv; if (dh && typeof dh === 'object' && !dh.deref) { const wr = dh[wk] || (dh[wk] = mWeakRef(dh)); dh = wr; } this[symDH] = dh; return true; }, get() { let wr = this[symDH]; let obj = typeof wr === 'object' ? kRef(wr) : wr; return obj; }, enumerable: false, configurable: true }); } if (yProto._registerHost && yProto._enqueueClient && yProto.__enableOrFlushClients && !yProto._registerHostDX38__) { yProto._registerHostDX38__ = true; // yProto._registerHost7133 = yProto._registerHost; yProto.__enableOrFlushClients = function () { const c_ = this.__dataPendingClients; if (c_) { const c = c_.slice(); c_.length = 0; for (let d = 0, l = c.length; d < l; d++) { let e = kRef(c[d]); if (e) { e.__dataEnabled ? e.__dataPending && e._flushProperties() : e._enableProperties() } } } } yProto._enqueueClient = function (c) { if (c === this || !c || typeof c !== 'object') return; if (c.deref) c = kRef(c); const m = this.__dataPendingClients || (this.__dataPendingClients = []); if (!c[wk]) c[wk] = mWeakRef(c); m.push(c[wk]); } } } } const setupRendering = function () { const cnt = this; const cProto = Reflect.getPrototypeOf(cnt); let yProto = Reflect.getPrototypeOf(cProto); const yProtos = new Set(); if (!yMap.has(yProto)) { // capture all ancenstor constructors of a and b (non-specific component type) do { if (yProto === Object.prototype || yProto === null) break; if (yProto === Element.prototype || yProto === Node.prototype || yProto === EventTarget.prototype || yProto === HTMLElement_.prototype) break; yProtos.add(yProto); yProto = Reflect.getPrototypeOf(yProto); } while (!yProtos.has(yProto)); for (const yProto of yProtos) { yMap.add(yProto); setupYProto(yProto) } } if (!cMap.has(cProto)) { cMap.add(cProto); // cProto constrcutor is either a or b? (specific component type) setupCProto(cProto); } } /* jF = function(M) { var d = YNV.call(this) || this; d._configureProperties(M); d.root = d._stampTemplate(d.__dataHost); var N = []; d.children = N; for (var R = d.root.firstChild; R; R = R.nextSibling) N.push(R), R.__templatizeInstance = d; d.__templatizeOwner && d.__templatizeOwner.__hideTemplateChildren__ && d._showHideChildren(!0); N = d.__templatizeOptions; (M && N.instanceProps || !N.instanceProps) && d._enableProperties(); return d }; */ const sb1 = Symbol(); Object.defineProperty(Object.prototype, 'root', { get() { return this[sb1]; }, set(nv){ const p = this ? kRef(this) : null; const mv = nv ? kRef(nv) : null; // if (typeof (this.host || 0) === 'object' && !this.host6833) { // const host = this.host; // if (!host[wk]) host[wk] = mWeakRef(host); // this.host6833 = host[wk]; // delete this.host; // console.log(21883, host) // Object.defineProperty(this, 'host', { // get() { // return kRef(this.host6833); // }, // set(nv) { // if (!nv) { // this.host6833 = nv; // } else { // if (!nv[wk]) nv[wk] = mWeakRef(nv); // this.host6833 = nv[wk]; // } // return true; // }, enumerable: false, configurable: true // }); // } if (mv && (mv instanceof Node) && !p.__setupRendered399__) { p.__setupRendered399__ = true; setupRendering.call(p); } if (mv && mv.is && !mv.__setupRendered399__) { mv.__setupRendered399__ = true; setupRendering.call(mv); } this[sb1] = nv; return true; } }); } let _cssSheet = null; const addNewCSS = typeof CSSStyleSheet !== 'undefined' && document.adoptedStyleSheets ? (css) => { if (!_cssSheet) { _cssSheet = new CSSStyleSheet(); document.adoptedStyleSheets.push(_cssSheet); } _cssSheet.insertRule(`${css}`); } : (css) => { let nonce = document.querySelector('style[nonce]'); nonce = nonce ? nonce.getAttribute('nonce') : null; const st = document.createElement('style'); if (typeof nonce === 'string') st.setAttribute('nonce', nonce); st.textContent = `${css}`; let parent; if (parent = document.head) parent.appendChild(st); else if (parent = (document.body || document.documentElement)) parent.insertBefore(st, parent.firstChild); } function getTranslate() { pLoad.then(() => { addNewCSS(".yt-formatted-string-block-line{display:block;}"); }); const snCache = new Map(); if (TRANSLATE_DEBUG) { console.log(11) } /** @type {(str: string?) => string} */ function _snippetText(str) { // str can be underfinded if (!str || typeof str !== 'string') return ''; let res = snCache.get(str); if (res === undefined) { let b = false; res = str.replace(/[\s\u3000\u200b]*[\u200b\xA0\x20\n]+[\s\u3000\u200b]*/g, (m) => { b = true; return m.includes('\n') ? '\n' : m.replace(/\u200b/g, '').replace(/[\xA0\x20]+/g, ' '); }); res = res.replace(/^[\s\u3000]+|[\u3000\s]+$/g, () => { b = true; return ''; }); if (b) { snCache.set(str, res); snCache.set(res, null); } else { res = null; snCache.set(str, null); } } return res === null ? str : res; } /** @type {(snippet: Object) => string} */ function snippetText(snippet) { let runs = snippet.runs; const n = runs.length; if (n === 1) return _snippetText(runs[0].text); let res = new Array(n); let ci = 0; for (const s of runs) { res[ci++] = _snippetText(s.text); } return res.join('\n'); } const _DEBUG_szz = (t) => t.map(x => { const tsr = x.transcriptSegmentRenderer; return ({ t: tsr.snippet.runs.map(x => x.text).join('//'), a: tsr.startMs, b: tsr.endMs }); }); const fixRuns = (runs) => { if (runs.length === 1 && runs[0]?.text?.includes('\n')) { // https://www.youtube.com/watch?v=dmHJJ5k_G-A const text = runs[0].text; const nlc = text.includes('\r\n') ? '\r\n' : text.includes('\n\r') ? '\n\r' : text.includes('\r') ? '\r' : '\n'; const s = text.split(nlc); let bi = 0; runs.length = s.length; for (const text of s) { runs[bi++] = { ...runs[0], text, ...{blockLine: true} }; } } for (const s of runs) { s.text = _snippetText(s.text); } } function translate(initialSegments) { // 2023.07.13 - fix initialSegments with transcriptSectionHeaderRenderer if (!initialSegments) return initialSegments; if (TRANSLATE_DEBUG) { console.log(12); Promise.resolve(JSON.stringify(initialSegments)).then((r) => { let obj = JSON.parse(r); console.log(7558, 1, obj) return obj; }).then(p => { let obj = _DEBUG_szz(p) console.log(7558, 2, obj) }) } //let mapRej = new WeakSet(); const n1 = initialSegments.length; if (!n1) return fRes; let n2 = 0; const fRes = new Array(n1); // ----------------------------------------------------------------------------------------- const s8 = Symbol(); { /** @type {Map} */ let cacheTexts = new Map(); // avoid duplicate with javascript object properties // /-* * @type {Map} *-/ // let mh1 = new Map(); // avoid duplicate with javascript object properties // 1: ok // 2: abandoned effect text for (const initialSegment of initialSegments) { const transcript = (initialSegment || 0).transcriptSegmentRenderer; if (!transcript) { // https://www.youtube.com/watch?v=dmHJJ5k_G-A - transcriptSectionHeaderRenderer fRes[n2++] = initialSegment; continue; } const runs = transcript.snippet.runs if (!runs || runs.length === 0) { initialSegment[s8] = true; continue; } let startMs = (+transcript.startMs || 0); //integer let endMs = (+transcript.endMs || 0); //integer if (startMs === endMs) { // effect text // https://www.youtube.com/watch?v=Ud73fm4Uoq0 //mapRej.add(initialSegment) continue; } if (endMs - startMs < 30) { continue; } const text = snippetText(transcript.snippet); const hEntry = cacheTexts.get(text); const mh1e = hEntry === undefined ? 0 : hEntry === null ? 2 : 1; if (mh1e === 2) continue; const entry = { startMs, endMs, initialSegment, text }; if (mh1e === 0) { if (/^[,.\x60\x27\x22\u200b\xA0\x20;-]*$/.test(text)) { initialSegment[s8] = true; cacheTexts.set(text, null); //effect only // https://www.youtube.com/watch?v=zLak0dxBKpM //mapRej.add(initialSegment) continue; } } else if (hEntry) { const timeDiff = entry.startMs - hEntry.endMs; let shouldMerge = false; if (timeDiff >= 0) { if (timeDiff < 25) { shouldMerge = true; } else if (timeDiff < 450 && entry.endMs - entry.startMs < 900) { shouldMerge = true; } else if (timeDiff < 150 && entry.endMs - entry.startMs > 800) { shouldMerge = true; } if (shouldMerge && hEntry.endMs <= endMs && startMs <= endMs) { // abandon the current entry. // absorbed by previous entry hEntry.endMs = entry.endMs; hEntry.initialSegment.transcriptSegmentRenderer.endMs = entry.initialSegment.transcriptSegmentRenderer.endMs; // update fRes & initialSegments as well using object reference //mapRej.add(entry.initialSegment); continue; } } else if (entry.startMs < hEntry.startMs && hEntry.startMs < entry.endMs) { // abandon the current entry. // absorbed by previous entry if (entry.endMs > hEntry.endMs) { hEntry.endMs = entry.endMs; hEntry.initialSegment.transcriptSegmentRenderer.endMs = entry.initialSegment.transcriptSegmentRenderer.endMs; // update fRes & initialSegments as well using object reference } //mapRej.add(entry.initialSegment); continue; } } //if not abandoned cacheTexts.set(text, entry); //replace the previous valid entry object if any // for (const s of runs) { // s.text = _snippetText(s.text); // } fixRuns(runs); fRes[n2++] = initialSegment; } // cacheTexts.clear(); // let GC do it. cacheTexts = null; // mh1.clear(); // let GC do it. // mh1 = null; } const si_length = fRes.length = n2; const sj_length = n1; if (si_length !== sj_length) { // for equal length, no fix is required & ignore spacing fix // collect the abandon text to become second subtitle let sj_start = 0; let invalid_sj = -1; for (let si = 0; si < si_length; si++) { const segment = fRes[si]; let transcript = segment.transcriptSegmentRenderer; if (!transcript) continue; // e.g. transcriptSectionHeaderRenderer const runs = transcript.snippet.runs; // fixRuns(runs); if (runs.length > 1 || runs[0].text.includes('\n')) continue; // skip multi lines const main_startMs = (+transcript.startMs || 0); const main_endMs = (+transcript.endMs || 0); transcript = null; /** @type {Map} */ let tMap = new Map(); // avoid duplicate with javascript object properties // assume that it is asc-ordered array of key startMs; for (let sj = sj_start; sj < sj_length; sj++) { const initialSegment = initialSegments[sj]; if (!initialSegment || initialSegment[s8]) continue; // should invalid_sj be set ? const tSegment = initialSegment.transcriptSegmentRenderer; if (!tSegment) { // https://www.youtube.com/watch?v=dmHJJ5k_G-A - transcriptSectionHeaderRenderer invalid_sj = sj; // should invalid_sj be set ? continue; } const startMs = (+tSegment.startMs || 0) const isStartValid = startMs >= main_startMs; if (!isStartValid) { invalid_sj = sj; continue; } // isStartValid must be true if (startMs > main_endMs) { sj_start = invalid_sj + 1; break; } const endMs = (+tSegment.endMs || 0) if (endMs <= main_endMs) { const mt = snippetText(tSegment.snippet); const prev = tMap.get(mt); if (endMs >= startMs) { tMap.set(mt, (prev || 0) + 1 + (endMs - startMs)); } } } if (tMap.size <= 1) continue; // no second line let rg = [...tMap.entries()]; // N x 2 2D-array [string,number][] tMap = null; // https://www.youtube.com/watch?v=Ud73fm4Uoq0 rg.sort((a, b) => b[1] - a[1]); //descending order of number let targetZ = rg[1][1]; if (targetZ > 4) { let az = 0; let fail = false; for (let idx = 2, rgl = rg.length; idx < rgl; idx++) { az += rg[idx][1]; if (az >= targetZ) { fail = true; break; } } if (!fail) { const rgA = rg[0][0]; const rgB = rg[1][0]; const isDiff = rgB.replace(/\s/g, '') !== rgA.replace(/\s/g, ''); if (isDiff && rgA === _snippetText(runs[0].text)) { if (runs[0] && runs[0].text) runs[0].blockLine = true; runs.push({ text: rgB, blockLine: true }); } } } rg = null; } TRANSLATE_DEBUG && Promise.resolve(fRes).then((r) => { let obj = r; console.log(7559, 1, obj) return obj; }).then(p => { let obj = _DEBUG_szz(p) console.log(7559, 2, obj) }); } // ----------------------------------------------------------------------------------------- snCache.clear(); return fRes; } return translate } let translateFn = null; FIX_TRANSCRIPT_SEGMENTS && !isChatRoomURL && (() => { const wmx = new WeakMap(); function fixSegments(ytObj) { let a, b; let seg = ((a = ytObj.data) == null ? void 0 : a[b = 'searchResultSegments']) || ((a = ytObj.data) == null ? void 0 : a[b = 'initialSegments']) || []; if (!seg || !a || !b || typeof (seg || 0) !== 'object' || !Number.isFinite(seg.length * 1)) return; translateFn = translateFn || getTranslate(); let cSeg; cSeg = wmx.get(seg); if (!cSeg) { let vSeg = null; try { vSeg = translateFn(seg); } catch (e) { } if (seg && typeof seg === 'object' && seg.length >= 1 && vSeg && typeof vSeg === 'object' && vSeg.length >= 1) { // console.log('translated', vSeg); cSeg = vSeg; wmx.set(seg, cSeg); wmx.set(cSeg, cSeg); } } if (cSeg && cSeg !== seg) { a[b] = cSeg; } } const dfn = Symbol(); const Object_ = Object; Object_[dfn] = Object_.defineProperties; let activation = true; Object_.defineProperties = function (obj, pds) { let segments, get_; if (activation && pds && (segments = pds.segments) && (get_ = segments.get)) { activation = false; segments.get = function () { fixSegments(this); return get_.call(this); }; } return Object_[dfn](obj, pds); }; })(); let pf31 = new PromiseExternal(); // native RAF let __requestAnimationFrame__ = typeof webkitRequestAnimationFrame === 'function' ? window.webkitRequestAnimationFrame.bind(window) : window.requestAnimationFrame.bind(window); // 1st wrapped RAF const baseRAF = (callback) => { return p59 ? __requestAnimationFrame__(callback) : __requestAnimationFrame__((hRes) => { pf31.then(() => { callback(hRes); }); }); }; // 2nd wrapped RAF window.requestAnimationFrame = baseRAF; const insp = o => o ? (o.polymerController || o.inst || o || 0) : (o || 0); const indr = o => insp(o).$ || o.$ || 0; const prototypeInherit = (d, b) => { const m = Object.getOwnPropertyDescriptors(b); for (const p in m) { if (!Object.getOwnPropertyDescriptor(d, p)) { Object.defineProperty(d, p, m[p]); } } }; const firstObjectKey = (obj) => { for (const key in obj) { if (obj.hasOwnProperty(key) && typeof obj[key] === 'object') return key; } return null; }; function searchNestedObject(obj, predicate, maxDepth = 64) { // normal case: depth until 36 const result = []; const visited = new WeakSet(); function search(obj, depth) { visited.add(obj); for (const [key, value] of Object.entries(obj)) { // Recursively search nested objects and arrays if (value !== null && typeof value === 'object') { // Prevent infinite loops by checking if the object is already visited or depth exceeded if (depth + 1 <= maxDepth && !visited.has(value)) { search(value, depth + 1); } } else if (predicate(value)) { result.push([obj, key]); } } } typeof (obj || 0) === 'object' && search(obj, 0); return result; } /** @type {(o: Object | null) => WeakRef | null} */ const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null); /** @type {(wr: Object | null) => Object | null} */ const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr); const isIterable = (obj) => (Symbol.iterator in Object_(obj)); if (typeof Document.prototype.requestStorageAccessFor === 'function') { if (DENY_requestStorageAccess) { // https://developer.mozilla.org/en-US/docs/Web/API/Document/requestStorageAccessFor Document.prototype.requestStorageAccessFor = undefined; console.log('[yt-js-engine-tamer]', 'requestStorageAccessFor is removed.'); } else if (DISABLE_IFRAME_requestStorageAccess && window !== top) { Document.prototype.requestStorageAccessFor = function () { return new Promise((resolve, reject) => { reject(); }); }; } } const traceStack = (stack) => { let result = new Set(); let p = new Set(); let u = '' for (const s of stack.split('\n')) { if (s.split(':').length < 3) continue; let m = /(([\w-_\.]+):\d+:\d+)[^:\r\n]*/.exec(s); if (!m) continue; p.add(m[2]); if (p.size >= 3) break; if(!u) u = m[2]; else if(p.size === 2 && u && u=== m[2]) break; result.add(s); } return [...result].join('\n'); } if (FIX_bind_self_this && !Function.prototype.bind488 && !Function.prototype.bind588) { // window.m3bb = new Set(); // const smb = Symbol(); const vmb = 'dtz02' // Symbol(); // return kThis for thisArg const vmc = 'dtz04' // Symbol(); // whether it is proxied fn const vmd = 'dtz08' // Symbol(); // self fn proxy (fn--fn) const thisConversionFn = (thisArg) => { if (!thisArg) return null; const kThis = thisArg[vmb]; if (kThis) { const ref = kThis.ref; return (ref ? kRef(ref) : null) || null; } return thisArg; } const pFnHandler2 = { get(target, prop) { if (prop === vmc) return target; return Reflect.get(target, prop); }, apply(target, thisArg, argumentsList) { thisArg = thisConversionFn(thisArg); if (thisArg) return Reflect.apply(target, thisArg, argumentsList); } } const proxySelfHandler = { get(target, prop) { if(prop === vmb) return target; const ref = target.ref; const cnt = kRef(ref); if (!cnt) return; if (typeof cnt[prop] === 'function' && !cnt[prop][vmc] && !cnt[prop][vmb]) { if (!cnt[prop][vmd]) cnt[prop][vmd] = new Proxy(cnt[prop], pFnHandler2); return cnt[prop][vmd]; } return cnt[prop]; }, set(target, prop, value) { const cnt = kRef(target.ref); if (!cnt) return true; if(value && (value[vmc] || value[vmb])){ cnt[prop] = value[vmc] || thisConversionFn(value); return true; } cnt[prop] = value; return true; } }; const weakWrap = (thisArg) => { thisArg = thisConversionFn(thisArg); if (!thisArg) { console.error('thisArg is not found'); return null; } return new Proxy({ ref: mWeakRef(thisArg) }, proxySelfHandler); } if (!window.getComputedStyle533 && typeof window.getComputedStyle === 'function') { window.getComputedStyle533 = window.getComputedStyle; window.getComputedStyle = function (a, ...args) { a = thisConversionFn(a); if (a) { return getComputedStyle533(a, ...args); } return null; } } Function._count_bind_00 = 0; // Function._count_bind_01 = 0; // let matchNativeCode = (Object+""); // let matchNativeCode1 = matchNativeCode.includes("[native code]"); // let matchNativeLen = matchNativeCode.length - Object.name.length; // const matchConstructor = (thisArg) => { // const f = `${(thisArg || 0).constructor}`; // if (f.length > 45) return true; // if (matchNativeCode1 && f.length - thisArg.constructor.name.length === matchNativeLen) { // if (f.includes('[native code]')){ // return false; // } // return true; // } // return false; // } // const acceptThis = (thisArg)=>{ // // if(!thisArg || typeof thisArg !=='object') return false; // // // if((((thisArg||0).constructor||0).name || 'XXXXXXXX').length < 3) return true; // // if(typeof thisArg.path === 'string') return true; // // if(typeof thisArg.fn === 'function') return true; // // if(typeof thisArg.id === 'string') return true; // // if(typeof thisArg.isLoaded === 'boolean') return true; // return false; // } const patchFn = (fn) => { let s = `${fn}`; if (s.length < 11 || s.includes('\n')) return false; if(s.includes('bind(this')) return true; if(s.includes('=this') && /[,\s][a-zA-Z_][a-zA-Z0-9_]*=this[;,]/.test(s) ) return true; // var a=this; // f.bind(this) return false; } Function.prototype.bind488 = Function.prototype.bind; Function.prototype.bind = function(thisArg, ...args){ if (thisConversionFn(thisArg) !== thisArg) { return this.bind488(thisArg, ...args); } if( thisArg && patchFn(this) ){ // console.log(599,`${this}`) try { // let b1 = thisArg && typeof thisArg === 'object' && typeof thisArg.isAttached === 'boolean' && !thisArg.dtz06; // ready cnt // let b2 = !b1 && thisArg && (thisArg instanceof Node) && typeof thisArg.nodeName === 'string' && !thisArg.dtz06; // dom // let b3 = !b1 && !b2 && thisArg && typeof thisArg === 'object' && typeof thisArg.is === 'string' && !thisArg.dtz06; // init stage ? // // let b4 = !b1 && !b2 && !b3 && thisArg && typeof thisArg === 'object' && !thisArg.dtz06 && matchConstructor(thisArg); // // let b5 = !b1 && !b2 && !b3 && !b4 && thisArg && typeof thisArg === 'object' && !thisArg.dtz06 && acceptThis(thisArg); // // let b5 = !b1 && !b2 && !b3 && thisArg && typeof thisArg === 'object' && !thisArg.dtz06 && !(thisArg instanceof Window); // // let b4 = false; // let b4 = !b1 && !b2 && !b3 && thisArg && !thisArg.dtz06; // // b3 = false; // // b4 = false; // // b5 = false; // if (b1 || b2 || b3 ||b4 ) { const f = this; const ps = thisArg.__proxySelf0__ || (thisArg.__proxySelf0__ = weakWrap(thisArg)); if (ps && ps[vmb]) { Function._count_bind_00++; return f.bind488(ps, ...args) } // } } catch (e) { console.warn(e) } } return this.bind488(thisArg, ...args); } Function.prototype.bind588 = 1; } const ytSchedulerMethods = { addJob(a, b, c) { const instance = typeof yt !== 'undefined' ? ((yt || 0).scheduler || 0).instance : null; if (instance) { return instance.addJob(a, b, c); } else { return setTimeout(a, c); } }, addImmediateJob(a) { const instance = typeof yt !== 'undefined' ? ((yt || 0).scheduler || 0).instance : null; if (instance) { return instance.addImmediateJob(a); } else { a(); } }, cancelJob(id) { const instance = typeof yt !== 'undefined' ? ((yt || 0).scheduler || 0).instance : null; if (instance) { return instance.cancelJob(id); } else { return clearTimeout(id); } } }; if (FIX_ytScheduler) { let ytSchedulerFixed = 0; // let ytActioned = false; // let pr = new PromiseExternal(); // const hn = function () { // document.removeEventListener('yt-action', hn, true); // nextBrowserTick_(() => { // ytActioned = true; // pr.resolve(); // }); // } // document.addEventListener('yt-action', hn, true); // let cancelStore = {}; // tbc // yt.scheduler.instance.addJob const fixAddJob = (nv) => { /* function Z() { var a = w("ytglobal.schedulerInstanceInstance_"); if (!a || a.s) a = new M(I("scheduler") || {}), x("ytglobal.schedulerInstanceInstance_", a); return a } */ /* function R(a, b, c, d) { ++a.D; if (c === 10) return P(a, b), a.D; var e = a.D; a.h[e] = b; a.l && !d ? a.u.push({ id: e, priority: c }) : (a.i[c].push(e), a.C || a.l || (a.g !== 0 && S(a) !== a.m && T(a), a.start())); return e } */ /* function sa(a, b, c) { if (!c) return c = c === void 0, -R(Z(), a, b, c); var d = window.setTimeout(function() { var e = R(Z(), a, b); W[d] = e }, c); return d } */ window.originalAddJob = nv; // const q1 = new PromiseExternal(); // const q2 = new PromiseExternal(); // let uu = 0; // let q3 = 0; // let mof = null; // const mo = new MutationObserver((mutation, observer) => { // if (mof) { // if (mof() === true) { // observer.disconnect(); // mof = null; // } // } // }); let lenSkip = -1; let lastLen = null; let fetchCommentJobTimerId = 0; let requestFinish = false; const fetchCommentJobDone = ()=>{ clearInterval(fetchCommentJobTimerId); fetchCommentJobTimerId = 0; console.log('[yt-js-engine-tamer] fetchCommentJob done'); } const fetchCommentJob = (a, cid) => { // if (cid && cancelStore[cid]) return; // tbc if(fetchCommentJobTimerId > 0){ fetchCommentJobDone(); } // if (mof) { // console.log('[yt-js-engine-tamer] fetchCommentJob done'); // mof = null; // } let f = a; const selector = 'ytd-comments, ytd-comments > *, ytd-comments [id] > *, ytd-comments ytd-continuation-item-renderer'; console.log('[yt-js-engine-tamer] fetchCommentJob start'); lastLen = -1; let u = 0; let g = () => { if (requestFinish) lastLen = -1; const lastLen_ = lastLen; const len1 = lastLen = document.querySelectorAll(selector).length; let mm = true; let ff = false; if (len1 !== lastLen_) { u = 0; f(); const len2 = lastLen = document.querySelectorAll(selector).length; if (len2 !== len1) { ff = true; mm = false; } } if (mm) { ++u; if (u > 10 || document.querySelector('ytd-comments:not([hidden]) [id]')) { ff = true; } } if (requestFinish) { requestFinish = false; fetchCommentJobDone(); } else if (ff){ fetchCommentJobDone(); } } fetchCommentJobTimerId = setInterval(g, 80); // g(9); // if (lastLen === lenSkip) { // console.log('[yt-js-engine-tamer] fetchCommentJob done'); // g = f = null; // return; // } // console.log('[yt-js-engine-tamer] fetchCommentJob done'); // const q1 = lastLen; // mof = () => { // const q2 = document.querySelectorAll(selector).length; // if (q1 === q2) return; // fetchCommentJobTimerId = setTimeout(g, 80); // g = null; // return true; // } // mo.observe(document, { childList: true, subtree: true }); } // let pr72 = Promise.resolve(); let qa = null; let qasf = ''; document.addEventListener("fullscreenchange", (evt) => { if (evt.isTrusted !== true) return; if (qa) { // qa(); nextBrowserTick_(qa); } // const pr = new Promise(resolve => { setTimeout(resolve, 94.25) }); // pr72 = pr72.then(() => { // return pr // }); }, true); window.addEventListener("resize", (evt) => { if (evt.isTrusted !== true) return; if (qa) { // qa(); nextBrowserTick_(qa); } // const pr = new Promise(resolve => { setTimeout(resolve, 94.25) }); // pr72 = pr72.then(() => { // return pr // }); }, true); setInterval(() => { const f = qa; if (typeof f !== 'function') return; qa = null; // pr72 = pr72.then(() => { // f(); // }); // nextBrowserTick_(()=>{ f(); // }); }, 475.25); return function (a, b, c) { const f = a; // const g = ()=>{ // pr72 = pr72.then(()=>{ // f(); // }); // } if (!c) return arguments.length < 3 ? nv(f, b) : nv(f, b, c); const c_ = c; if (c > 0.25 && (c % 1) === 0) c -= 0.125; if (b === 1 && c_ === 500) { const sf = `${a}`; if (qasf ? (sf === qasf) : (sf.includes('.mediaElement') && sf.includes('.getCurrentTime') && sf.includes('.seekTo'))) { qasf = sf; qa = a; // console.log(12883, a) return nv(() => { if (qa === a) { qa = null; a(); } }, b, c); } } if (!b && c_ === 5000 && `${a}`.includes('.cleanupJob=0')) { // console.log('[yt-js-engine-tamer] cleanupJob 01'); // const pr = new Promise(resolve => { setTimeout(resolve, 94.25) }); // pr72 = pr72.then(() => { // return pr // }); // try { // yt.scheduler.instance.cancelAllJobs(); // yt.scheduler.instance.dispose(); // if(ytglobal.schedulerInstanceInstance_) ytglobal.schedulerInstanceInstance_.dispose(); // console.log('[yt-js-engine-tamer] cleanupJob 02'); // } catch (e) { } return nv(f, b, c); } // if(!b && c > 50) c = 50; // console.log(58372,a,b,c) // function(){xxx(xxx)} if (!b && c_ === 1000 && `${a}`.length <= 20 && a.name === '' && /function\(\)\{\w{1,3}\(\w{1,3}\)\}/.test(`${a}`)) { /* V.setCommentsJobId = _.et(_.r0, function() { F5V(V) }, 1E3) */ requestFinish = false; const cid = nv(() => { if(fetchCommentJobTimerId > 0) requestFinish = true;}, b, 1000); // lastLen = null; fetchCommentJob(a, cid); // queueMicrotask_(a); // nextBrowserTick_(a); // a(); // no need to delay return cid // return nv(a, b, 1.125); // const cid = window.setTimeout(() => { // nextBrowserTick_(() => { // if (cancelStore[cid]) { // console.log('task cancelled'); // return; // } // a(); // }); // }, 0.125); // return cid; } else { return nv(f,b,c); // if (c > 2400) c = 2400; // else if (c > 800) c = 800; // if (c > 0.2 && (c % 1) === c) c -= 0.125; // if (0 && ytActioned && !b) { // const cid = window.setTimeout(() => { // nextBrowserTick_(() => { // if (cancelStore[cid]) { // console.log('task cancelled'); // return; // } // a(); // }); // }, c); // return cid; // } else { // return nv(a, b, c); // } } } } const fixCancelJob = (nv) => { window.originalCancelJob = nv; return function (a) { if (a < 0) return nv(a); // cancelStore[a] = true; // tbc nv(a); } } const sk44 = Symbol(); Object.defineProperty(Object.prototype, 'addJob', { get() { return this[sk44]; }, set(nv) { if (typeof nv === 'function' && !(ytSchedulerFixed & 1) && typeof yt !== 'undefined' && this === ((yt || 0).scheduler || 0).instance) { ytSchedulerFixed |= 1; nv = fixAddJob(nv); } this[sk44] = nv; return true; }, enumerable: false, configurable: true }); const sk45 = Symbol(); Object.defineProperty(Object.prototype, 'cancelJob', { get() { return this[sk45]; }, set(nv) { if (typeof nv === 'function' && !(ytSchedulerFixed & 2) && typeof yt !== 'undefined' && this === ((yt || 0).scheduler || 0).instance) { ytSchedulerFixed |= 2; nv = fixCancelJob(nv); } this[sk45] = nv; return true; }, enumerable: false, configurable: true }); if (typeof yt !== 'undefined' && this === ((yt || 0).scheduler || 0).instance) { const { addJob, cancelJob } = yt.scheduler.instance; if (addJob) { yt.scheduler.instance.addJob = null; yt.scheduler.instance.addJob = addJob; } if (cancelJob) { yt.scheduler.instance.cancelJob = null; yt.scheduler.instance.cancelJob = cancelJob; } } } const isWatchPageURL = (url) => { url = url || location; return location.pathname === '/watch' || location.pathname.startsWith('/live/') }; const isCustomElementsProvided = typeof customElements !== "undefined" && typeof (customElements || 0).whenDefined === "function"; const promiseForCustomYtElementsReady = isCustomElementsProvided ? Promise.resolve(0) : new Promise((callback) => { const EVENT_KEY_ON_REGISTRY_READY = "ytI-ce-registry-created"; if (typeof customElements === 'undefined') { if (!('__CE_registry' in document)) { // https://github.com/webcomponents/polyfills/ Object.defineProperty(document, '__CE_registry', { get() { // return undefined }, set(nv) { if (typeof nv == 'object') { delete this.__CE_registry; this.__CE_registry = nv; this.dispatchEvent(new CustomEvent(EVENT_KEY_ON_REGISTRY_READY)); } return true; }, enumerable: false, configurable: true }) } let eventHandler = (evt) => { document.removeEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false); const f = callback; callback = null; eventHandler = null; f(); }; document.addEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false); } else { callback(); } }); const whenCEDefined = isCustomElementsProvided ? (nodeName) => customElements.whenDefined(nodeName) : (nodeName) => promiseForCustomYtElementsReady.then(() => customElements.whenDefined(nodeName)); FIX_perfNow && performance.timeOrigin > 9 && (() => { if (performance.now23 || performance.now16 || typeof Performance.prototype.now !== 'function') return; const f = performance.now23 = Performance.prototype.now; let k = 0; // 0 <= k < 9998m let u = 0; let s = ((performance.timeOrigin % 7) + 1) / 7 - 1e-2 / 7; // s > 0.14 // By definition, performance.now() is mono increasing. // Fixing in YouTube.com is required to ensure performance.now() is strictly increasing. performance.now = performance.now16 = function () { /** * Bug 1842437 - When attempting to go back on youtube.com, the content remains the same * * If consecutive session history entries had history.state.entryTime set to same value, * back button doesn't work as expected. The entryTime value is coming from performance.now() * and modifying its return value slightly to make sure two close consecutive calls don't * get the same result helped with resolving the issue. */ // see https://bugzilla.mozilla.org/show_bug.cgi?id=1756970 // see https://bugzilla.mozilla.org/show_bug.cgi?id=1842437 const v = typeof (this || 0).now23 === 'function' ? this.now23() + s : f.call(performance) + s; // v > 0.14 if (u + 0.0015 < (u = v)) k = 0; // note: hRes should be accurate to 5 µs in isolated contexts else if (k < 0.001428) k += 1e-6 / 7; // M = 10000 * m; m * 9996 = 0.001428 else { // more than 9998 consecutive calls /** * * max no. of consecutive calls * * Sample Size: 4800 * Sample Avg = 1565.375 * Sample Median = 1469.5 * Sample Max = 5660 << 7500 << 9999 * * * */ k = 0; s += 1 / 7; } return v + k; // 0 < v - M < v - M + k < v } let loggerMsg = ''; if (`${performance.now()}` === `${performance.now()}`) { const msg1 = 'performance.now is modified but performance.now() is not strictly increasing.'; const msg2 = 'performance.now cannot be modified and performance.now() is not strictly increasing.'; loggerMsg = performance.now !== performance.now16 ? msg1 : msg2; // might not able to set in Firefox } loggerMsg && console.warn(loggerMsg); })(); // let __forceRemoveMode__ = false; FIX_removeChild && (() => { if (typeof Node.prototype.removeChild === 'function' && typeof Node.prototype.removeChild062 !== 'function') { let internalByPass = false; const fragD = document.createDocumentFragment(); fragD.appendChild4201 = fragD.appendChild; fragD.removeChild4201 = fragD.removeChild; Node.prototype.removeChild062 = Node.prototype.removeChild; Node.prototype.removeChild = function (child) { try { return this.removeChild062(child); } catch (e) { } if (internalByPass) return child; if (this instanceof Node && child instanceof Node && this.nodeType === 11 && child.parentNode !== this && this.contains(child)) { // eg. child = DOM-IF let idx = (this.childNodes || 0).length >= 1 ? this.childNodes.indexOf(child) : -1; if (idx >= 0) { internalByPass = true; child.parentNode !== fragD && fragD.appendChild4201(child); this.childNodes[idx] === child && typeof this.childNodes.splice === 'function' && this.childNodes.splice(idx, 1); fragD.removeChild4201(child); internalByPass = false; return child; } } // if (this instanceof Node && child instanceof Node && child.parentNode && child.parentNode.nodeType === 11 && child.parentNode !== this && !this.contains(child)) { // // force removal // internalByPass = true; // child.parentNode !== fragD && fragD.appendChild4201(child); // fragD.removeChild4201(child); // internalByPass = false; // return child; // } if (this && child) { if (this.childNodes && this.childNodes.splice) { // tbc let idx = (this.childNodes || 0).length >= 1 ? this.childNodes.indexOf(child) : -1; if (idx >= 0) { internalByPass = true; child.parentNode !== fragD && fragD.appendChild4201(child); this.childNodes[idx] === child && typeof this.childNodes.splice === 'function' && this.childNodes.splice(idx, 1); fragD.removeChild4201(child); internalByPass = false; return child; } } if (child.parentNode !== this && child.parentNode && child.parentNode === child.__shady_parentNode && child.parentNode.nodeType === 11) { if (child.isConnected === false && (this.compareDocumentPosition(child) & (1 | 8 | 16)) === 1) { // just ignore (!e.root && a.localName !== "slot" || f === a.__shady_native_parentNode) && f.__shady_native_removeChild(a)); return child; } } if (child && child.is === 'tp-yt-paper-tooltip' && !child.parentNode && !child.__shady_parentNode) { // skip return child; } console.warn('[yt-js-engine-tamer] Node is not removed from parent', { parent: this, child: child, isParent: child.parentNode === this, isParentParent: (child.parentNode || 0).parentNode === this, parentNode: child.parentNode, shadyParent: child.__shady_parentNode, isShadyParent: child.__shady_parentNode === this, isAncestor: this instanceof Node && child instanceof Node && this.contains(child) }); } return child; } } })(); FIX_VIDEO_PLAYER_MOUSEHOVER_EVENTS && !isChatRoomURL && (() => { const [setIntervalX0, clearIntervalX0] = [setInterval, clearInterval]; // let cid = 0; let mousemoveFn = null; let mousemoveDT = 0; let mousemoveCount = 0; // let qv = false; const cif = () => { if (!mousemoveFn) return; const ct = Date.now(); if (mousemoveDT + 1200 > ct) { // avoid setTimeout delay too long without execution mousemoveFn && mousemoveFn(); } mousemoveFn = null; }; let mousemoveCId = 0; let mouseoverFn = null; HTMLElement_.prototype.addEventListener4882 = HTMLElement_.prototype.addEventListener; HTMLElement_.prototype.addEventListener = function (a, b, c) { if (this.id == 'movie_player' && `${a}`.startsWith('mouse') && c === undefined) { const bt = `${b}`; if (bt.length >= 61 && bt.length <= 71 && bt.startsWith('function(){try{return ') && bt.includes('.apply(this,arguments)}catch(')) { b[`__$$${a}$$1926__`] = true; this[`__$$${a}$$1937__`] = (this[`__$$${a}$$1937__`] || 0) + 1; if (this[`__$$${a}$$1937__`] > 1073741823) this[`__$$${a}$$1937__`] -= 536870911; // console.log(3928, a, this[`__$$${a}$$1937__`]) if (!this[`__$$${a}$$1938__`]) { this[`__$$${a}$$1938__`] = b; if (a === 'mousemove') { this.addEventListener4882('mouseenter', (evt) => { if (mousemoveCId) return; mousemoveCId = setIntervalX0(cif, 380); }); this.addEventListener4882('mouseleave', (evt) => { clearIntervalX0(mousemoveCId); mousemoveCId = 0; }); } this.addEventListener4882(a, (evt) => { const evt_ = evt; if (!this[`__$$${a}$$1937__`]) return; if (!this[`__$$${a}$$1938__`]) return; if (a === 'mousemove') { mouseoverFn && mouseoverFn(); if (mousemoveDT + 350 > (mousemoveDT = Date.now())) { (++mousemoveCount > 1e9) && (mousemoveCount = 9); } else { mousemoveCount = 0; } const f = mousemoveFn = () => { if (f !== mousemoveFn) return; mousemoveFn = null; this[`__$$${a}$$1938__`](evt_); }; if (mousemoveCount <= 1) mousemoveFn(); } else { if (a === 'mouseout' || a === 'mouseleave') { mousemoveFn = null; mousemoveDT = 0; mousemoveCount = 0; this[`__$$${a}$$1938__`](evt_); mouseoverFn && mouseoverFn(); } else { // mouseover, mouseenter mousemoveFn = null; mousemoveDT = 0; mousemoveCount = 0; mouseoverFn && mouseoverFn(); // just in case const f = mouseoverFn = () => { if (f !== mouseoverFn) return; mouseoverFn = null; this[`__$$${a}$$1938__`](evt_); } nextBrowserTick_(mouseoverFn); } } }, c); return; } else { return; } } } return this.addEventListener4882(a, b, c) } HTMLElement_.prototype.removeEventListener4882 = HTMLElement_.prototype.removeEventListener; HTMLElement_.prototype.removeEventListener = function (a, b, c) { if (this.id == 'movie_player' && `${a}`.startsWith('mouse') && c === undefined) { if (b[`__$$${a}$$1926__`]) { b[`__$$${a}$$1926__`] = false; if (this[`__$$${a}$$1937__`]) this[`__$$${a}$$1937__`] -= 1; // console.log(3929, a, this[`__$$${a}$$1937__`], b[`__$$${a}$$1926__`]) return; } } return this.removeEventListener4882(a, b, c) } })(); FIX_DOM_IF_REPEAT && (() => { // https://www.youtube.com/s/desktop/26a583e4/jsbin/live_chat_polymer.vflset/live_chat_polymer.js // DOM-IF is still a core class of Polymer, so no polymerController is available. // Be careful of the mixture of polymer functions and native Element functions // Be careful of the coding design is different with the modern Yt elements /* function Ks(a, b, c) { if (kj && !BOa(a)) throw Error("strictTemplatePolicy: template owner not trusted"); c = c || {}; if (a.__templatizeOwner) throw Error("A