1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 1× 9× 1× 3× 13× 13× 13× 13× 13× 18× 1× 17× 17× 17× 16× 16× 8× 16× 7× 17× 17× 17× 17× 17× 17× 1× 57× 10× 10× 17× 13× 15× 15× 15× 13× 17× 91× 17× 16× 16× 16× 1× 15× 17× 107× 107× 68× 107× 91× 91× 60× 60× 60× 60× 2× 58× 58× 58× 58× 58× 16× 57× 57× 30× 30× 30× 27× 27× 27× 27× 27× 27× 27× 107× 17× 17× 7343× 7343× 32× 7311× 2× 1× 2× 1× 18× | "use strict"; const get = require("lodash/get"); const set = require("lodash/set"); const wrap = require("lodash/wrap"); const template = require("lodash/template"); const isObject = require("lodash/isObject"); const Module = require("module"); const InstantiateReactComponent = require("react-dom/lib/instantiateReactComponent"); const escapeTextContentForBrowser = require("react-dom/lib/escapeTextContentForBrowser"); const require_ = Module.prototype.require; const cache = require("lru-cache"); const MILLISECONDS_IN_ONE_SECOND = 1000; const SECONDS_IN_ONE_MINUTE = 60; const DEFAULT_MINUTES_TO_CACHE = 60; const DEFAULT_LRU_CONFIG = { max: 500, //The maximum size of the cache maxAge: DEFAULT_MINUTES_TO_CACHE * SECONDS_IN_ONE_MINUTE * MILLISECONDS_IN_ONE_SECOND }; const EMPTY_ID = -1; const defaultCacheKeyFunction = () => { return "_defaultKey"; }; const genAttrBasedKeyFunction = (attrs) => { return ((props) => { let key = ""; attrs.forEach((attr) => { const val = get(props, attr); key += isObject(val) ? JSON.stringify(val) : val; }); return key; }); }; class InstantiateReactComponentOptimizer { constructor(config) { if (process.env.NODE_ENV !== "production") { console.info( // eslint-disable-line no-console "Caching is disabled in non-production environments." ); } else { this.config = config; this.componentsToCache = config.components ? Object.keys(config.components) : []; this.componentsToCache.forEach((cmpName) => { let cacheConfig = config.components[cmpName]; if (cacheConfig instanceof Function) { cacheConfig = config.components[cmpName] = { cacheKeyGen: cacheConfig }; } if (isObject(cacheConfig) && !cacheConfig.cacheKeyGen) { cacheConfig.cacheKeyGen = cacheConfig.cacheAttrs && cacheConfig.cacheAttrs.length ? genAttrBasedKeyFunction(cacheConfig.cacheAttrs) : defaultCacheKeyFunction; } }, this); /* eslint-disable no-nested-ternary */ this.lruCache = (config.cacheImpl) ? config.cacheImpl : (config.lruCacheSettings) ? cache(config.lruCacheSettings) : cache(DEFAULT_LRU_CONFIG); this.enabled = !(config.disabled === true); this.eventCallback = config.eventCallback; this.shouldCollectLoadTimeStats = config.collectLoadTimeStats; this.wrapInstantiateReactComponent(); } } wrapInstantiateReactComponent() { const self = this; function eventCallback(event) { if (self.eventCallback) { process.nextTick(() => { self.eventCallback(event); }); } } /* eslint-disable max-params, no-console*/ const restorePropsAndProcessTemplate = (compiled, templateAttrs, templateAttrValues, curEl) => { templateAttrs.forEach((attrKey) => { const _attrKey = attrKey.replace(".", "__"); set(curEl.props, attrKey, templateAttrValues[_attrKey]); templateAttrValues[_attrKey] = escapeTextContentForBrowser(templateAttrValues[_attrKey]); }); return compiled(templateAttrValues); }; /* eslint-enable max-params, no-console*/ const shouldComponentBeCached = function (curEl) { return curEl && curEl.type && (self.componentsToCache.indexOf(curEl.type.displayName) > EMPTY_ID || self.componentsToCache.indexOf(curEl.type.name) > EMPTY_ID); }; /* eslint-disable max-params */ const templatizeProps = function (attrKey, templateAttrValues, curEl, cmpName) { const _attrKey = attrKey.replace(".", "__"); templateAttrValues[_attrKey] = get(curEl.props, attrKey); if (isObject(templateAttrValues[_attrKey])) { throw new Error( `Cannot templatize Object at ${attrKey} for component ${cmpName}` ); } /* eslint-disable prefer-template */ set(curEl.props, attrKey, "${" + _attrKey + "}"); }; const WrappedInstantiateReactComponent = wrap(InstantiateReactComponent, function (instantiate) { const component = instantiate.apply( instantiate, [].slice.call(arguments, 1)); if (component._instantiateReactComponent && (!component._instantiateReactComponent.__wrapped)) { component._instantiateReactComponent = WrappedInstantiateReactComponent; } if (self.enabled) { const curEl = component._currentElement; if (shouldComponentBeCached(curEl)) { /* eslint-disable max-statements */ component.mountComponent = wrap( component.mountComponent, function (mount) { const cmpName = (curEl.type.displayName || curEl.type.name); const generatedKey = self.config.components[cmpName].cacheKeyGen(curEl.props); if (generatedKey === null) { return mount.apply(component, [].slice.call(arguments, 1)); } const cacheKey = `${cmpName}:${generatedKey}`; const rootID = arguments[1]; const templateAttrs = self.config.components[cmpName].templateAttrs || []; const templateAttrValues = {}; templateAttrs.forEach((attrKey) => { templatizeProps(attrKey, templateAttrValues, curEl, cmpName); }); const cachedObj = self.lruCache.get(cacheKey); if (cachedObj) { eventCallback({type: "cache", event: "hit", cmpName: cmpName}); const cacheMarkup = templateAttrs.length ? restorePropsAndProcessTemplate(cachedObj.compiled, templateAttrs, templateAttrValues, curEl) : cachedObj.markup; /* eslint-disable quotes */ return cacheMarkup.replace( new RegExp(`data-reactid="${cachedObj.rootId}`, "g"), `data-reactid="${rootID}`); } const markUpGenerateStartTime = self.shouldCollectLoadTimeStats ? process.hrtime() : 0; const markup = mount.apply(component, [].slice.call(arguments, 1)); const compiledMarkup = templateAttrs.length ? template(markup) : null; const markUpGenerateEndTime = self.shouldCollectLoadTimeStats ? process.hrtime(markUpGenerateStartTime) : 0; eventCallback({type: "cache", event: "miss", cmpName: cmpName, loadTimeNS: (markUpGenerateEndTime[1])}); self.lruCache.set(cacheKey, { markup: markup, compiled: compiledMarkup, rootId: rootID }); return templateAttrs.length ? restorePropsAndProcessTemplate( compiledMarkup, templateAttrs, templateAttrValues, curEl) : markup; }); /* eslint-enable max-statements */ } } return component; } ); WrappedInstantiateReactComponent.__wrapped = true; Module.prototype.require = function (path) { const m = require_.apply(this, arguments); if (path === "./instantiateReactComponent") { return WrappedInstantiateReactComponent; } return m; }; } enable(enableFlag) { this.enabled = enableFlag; } cacheDump() { return this.lruCache.dump(); } cacheLength() { return this.lruCache.length; } cacheReset() { return this.lruCache.reset(); } } module.exports = (config) => new InstantiateReactComponentOptimizer(config); |