@cloudcare/browser-rum 3.3.5 → 3.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (381) hide show
  1. package/README.md +24 -3
  2. package/README.zh.md +19 -3
  3. package/bundle/dataflux-rum.js +1 -1
  4. package/cjs/boot/buildEnv.js +1 -1
  5. package/cjs/boot/buildEnv.js.map +1 -1
  6. package/cjs/boot/perStartRum.js +42 -6
  7. package/cjs/boot/perStartRum.js.map +1 -1
  8. package/cjs/boot/recorderApi.js +190 -195
  9. package/cjs/boot/recorderApi.js.map +1 -1
  10. package/cjs/boot/recorderApiStub.js +3 -29
  11. package/cjs/boot/recorderApiStub.js.map +1 -1
  12. package/cjs/boot/rum.entry.js.map +1 -1
  13. package/cjs/boot/rum.js +8 -0
  14. package/cjs/boot/rum.js.map +1 -1
  15. package/cjs/boot/rum.slim.entry.js.map +1 -1
  16. package/cjs/boot/rumEntryFactory.js.map +1 -1
  17. package/cjs/boot/rumPublicApi.js +36 -3
  18. package/cjs/boot/rumPublicApi.js.map +1 -1
  19. package/cjs/boot/rumRecorderApiStub.js.map +1 -1
  20. package/cjs/boot/rumSlimConfiguration.js.map +1 -1
  21. package/cjs/boot/sessionReplayPublicApi.js +14 -27
  22. package/cjs/boot/sessionReplayPublicApi.js.map +1 -1
  23. package/cjs/boot/startRecording.js +333 -108
  24. package/cjs/boot/startRecording.js.map +1 -1
  25. package/cjs/constants.js.map +1 -1
  26. package/cjs/domain/assembly.js +1 -7
  27. package/cjs/domain/assembly.js.map +1 -1
  28. package/cjs/domain/configuration.js +38 -43
  29. package/cjs/domain/configuration.js.map +1 -1
  30. package/cjs/domain/contexts/commonContext.js.map +1 -1
  31. package/cjs/domain/contexts/displayContext.js.map +1 -1
  32. package/cjs/domain/contexts/foregroundContexts.js.map +1 -1
  33. package/cjs/domain/contexts/internalContext.js.map +1 -1
  34. package/cjs/domain/contexts/pageStateHistory.js.map +1 -1
  35. package/cjs/domain/contexts/urlContexts.js +20 -2
  36. package/cjs/domain/contexts/urlContexts.js.map +1 -1
  37. package/cjs/domain/contexts/viewContexts.js +2 -2
  38. package/cjs/domain/contexts/viewContexts.js.map +1 -1
  39. package/cjs/domain/deflate/deflateEncoder.js +517 -39
  40. package/cjs/domain/deflate/deflateEncoder.js.map +1 -1
  41. package/cjs/domain/deflate/deflateWorker.js +194 -115
  42. package/cjs/domain/deflate/deflateWorker.js.map +1 -1
  43. package/cjs/domain/deflate/index.js.map +1 -1
  44. package/cjs/domain/domMutationObservable.js.map +1 -1
  45. package/cjs/domain/encoderStreamId.js.map +1 -1
  46. package/cjs/domain/firstInputPolyfill.js.map +1 -1
  47. package/cjs/domain/initViewportObservable.js.map +1 -1
  48. package/cjs/domain/locationChangeObservable.js.map +1 -1
  49. package/cjs/domain/performanceObservable.js.map +1 -1
  50. package/cjs/domain/performanceUtils.js.map +1 -1
  51. package/cjs/domain/plugins.js +67 -0
  52. package/cjs/domain/plugins.js.map +1 -0
  53. package/cjs/domain/replay/record/canvasAutoSnapshot.js.map +1 -1
  54. package/cjs/domain/replay/record/canvasCommandCapture.js +968 -167
  55. package/cjs/domain/replay/record/canvasCommandCapture.js.map +1 -1
  56. package/cjs/domain/replay/record/canvasCommandObserver.js +1058 -119
  57. package/cjs/domain/replay/record/canvasCommandObserver.js.map +1 -1
  58. package/cjs/domain/replay/record/canvasCommandSerializeArgs.js +61 -37
  59. package/cjs/domain/replay/record/canvasCommandSerializeArgs.js.map +1 -1
  60. package/cjs/domain/replay/record/canvasContext.js +63 -0
  61. package/cjs/domain/replay/record/canvasContext.js.map +1 -0
  62. package/cjs/domain/replay/record/canvasContinuousScheduler.js +246 -118
  63. package/cjs/domain/replay/record/canvasContinuousScheduler.js.map +1 -1
  64. package/cjs/domain/replay/record/canvasEncodeBridge.js +539 -87
  65. package/cjs/domain/replay/record/canvasEncodeBridge.js.map +1 -1
  66. package/cjs/domain/replay/record/canvasEncodeWorker.js +50 -32
  67. package/cjs/domain/replay/record/canvasEncodeWorker.js.map +1 -1
  68. package/cjs/domain/replay/record/canvasFrameSignature.js +49 -17
  69. package/cjs/domain/replay/record/canvasFrameSignature.js.map +1 -1
  70. package/cjs/domain/replay/record/canvasMutationRecord.js.map +1 -1
  71. package/cjs/domain/replay/record/canvasObserver.js +295 -59
  72. package/cjs/domain/replay/record/canvasObserver.js.map +1 -1
  73. package/cjs/domain/replay/record/canvasSerializeArgs.js.map +1 -1
  74. package/cjs/domain/replay/record/canvasWebGLPluginHost.js +33 -0
  75. package/cjs/domain/replay/record/canvasWebGLPluginHost.js.map +1 -0
  76. package/cjs/domain/replay/record/elementsScrollPositions.js +3 -0
  77. package/cjs/domain/replay/record/elementsScrollPositions.js.map +1 -1
  78. package/cjs/domain/replay/record/index.js.map +1 -1
  79. package/cjs/domain/replay/record/mutationBatch.js +542 -25
  80. package/cjs/domain/replay/record/mutationBatch.js.map +1 -1
  81. package/cjs/domain/replay/record/mutationObserver.js +1900 -191
  82. package/cjs/domain/replay/record/mutationObserver.js.map +1 -1
  83. package/cjs/domain/replay/record/mutationResourceBudget.js +144 -0
  84. package/cjs/domain/replay/record/mutationResourceBudget.js.map +1 -0
  85. package/cjs/domain/replay/record/observers.js +222 -53
  86. package/cjs/domain/replay/record/observers.js.map +1 -1
  87. package/cjs/domain/replay/record/privacy.js +31 -8
  88. package/cjs/domain/replay/record/privacy.js.map +1 -1
  89. package/cjs/domain/replay/record/record.js +3083 -321
  90. package/cjs/domain/replay/record/record.js.map +1 -1
  91. package/cjs/domain/replay/record/serializationUtils.js +426 -26
  92. package/cjs/domain/replay/record/serializationUtils.js.map +1 -1
  93. package/cjs/domain/replay/record/serialize.js +259 -49
  94. package/cjs/domain/replay/record/serialize.js.map +1 -1
  95. package/cjs/domain/replay/record/shadowRootsController.js +875 -21
  96. package/cjs/domain/replay/record/shadowRootsController.js.map +1 -1
  97. package/cjs/domain/replay/record/utils.js.map +1 -1
  98. package/cjs/domain/replay/record/viewports.js.map +1 -1
  99. package/cjs/domain/replay/replayStats.js.map +1 -1
  100. package/cjs/domain/replay/segmentCollection/buildReplayPayload.js.map +1 -1
  101. package/cjs/domain/replay/segmentCollection/index.js.map +1 -1
  102. package/cjs/domain/replay/segmentCollection/segment.js +315 -11
  103. package/cjs/domain/replay/segmentCollection/segment.js.map +1 -1
  104. package/cjs/domain/replay/segmentCollection/segmentCollection.js +956 -71
  105. package/cjs/domain/replay/segmentCollection/segmentCollection.js.map +1 -1
  106. package/cjs/domain/replay/startRecordBridge.js.map +1 -1
  107. package/cjs/domain/requestCollection.js.map +1 -1
  108. package/cjs/domain/rumEventsCollection/actions/actionCollection.js.map +1 -1
  109. package/cjs/domain/rumEventsCollection/actions/clickChain.js.map +1 -1
  110. package/cjs/domain/rumEventsCollection/actions/computeFrustration.js.map +1 -1
  111. package/cjs/domain/rumEventsCollection/actions/getActionNameFromElement.js.map +1 -1
  112. package/cjs/domain/rumEventsCollection/actions/getSelectorsFromElement.js.map +1 -1
  113. package/cjs/domain/rumEventsCollection/actions/interactionSelectorCache.js.map +1 -1
  114. package/cjs/domain/rumEventsCollection/actions/listenActionEvents.js.map +1 -1
  115. package/cjs/domain/rumEventsCollection/actions/trackClickActions.js.map +1 -1
  116. package/cjs/domain/rumEventsCollection/error/errorCollection.js.map +1 -1
  117. package/cjs/domain/rumEventsCollection/error/trackConsoleError.js.map +1 -1
  118. package/cjs/domain/rumEventsCollection/error/trackReportError.js.map +1 -1
  119. package/cjs/domain/rumEventsCollection/longTask/longAnimationFrameCollection.js.map +1 -1
  120. package/cjs/domain/rumEventsCollection/longTask/longTaskCollection.js.map +1 -1
  121. package/cjs/domain/rumEventsCollection/resource/matchRequestResourceEntry.js.map +1 -1
  122. package/cjs/domain/rumEventsCollection/resource/resourceCollection.js +56 -0
  123. package/cjs/domain/rumEventsCollection/resource/resourceCollection.js.map +1 -1
  124. package/cjs/domain/rumEventsCollection/resource/resourceTrackerManager.js.map +1 -1
  125. package/cjs/domain/rumEventsCollection/resource/resourceUtils.js.map +1 -1
  126. package/cjs/domain/rumEventsCollection/resource/retrieveInitialDocumentResourceTiming.js.map +1 -1
  127. package/cjs/domain/rumEventsCollection/resource/webSocketCollection.js +196 -0
  128. package/cjs/domain/rumEventsCollection/resource/webSocketCollection.js.map +1 -0
  129. package/cjs/domain/rumEventsCollection/view/interactionCountPolyfill.js.map +1 -1
  130. package/cjs/domain/rumEventsCollection/view/trackCommonViewMetrics.js.map +1 -1
  131. package/cjs/domain/rumEventsCollection/view/trackCumulativeLayoutShift.js.map +1 -1
  132. package/cjs/domain/rumEventsCollection/view/trackFirstContentfulPaint.js.map +1 -1
  133. package/cjs/domain/rumEventsCollection/view/trackFirstHidden.js.map +1 -1
  134. package/cjs/domain/rumEventsCollection/view/trackFirstInput.js.map +1 -1
  135. package/cjs/domain/rumEventsCollection/view/trackInitialViewTimings.js.map +1 -1
  136. package/cjs/domain/rumEventsCollection/view/trackInteractionToNextPaint.js.map +1 -1
  137. package/cjs/domain/rumEventsCollection/view/trackLargestContentfulPaint.js.map +1 -1
  138. package/cjs/domain/rumEventsCollection/view/trackLoadingTime.js +8 -3
  139. package/cjs/domain/rumEventsCollection/view/trackLoadingTime.js.map +1 -1
  140. package/cjs/domain/rumEventsCollection/view/trackNavigationTimings.js.map +1 -1
  141. package/cjs/domain/rumEventsCollection/view/trackScrollMetrics.js.map +1 -1
  142. package/cjs/domain/rumEventsCollection/view/trackViewEventCounts.js.map +1 -1
  143. package/cjs/domain/rumEventsCollection/view/trackViews.js +31 -12
  144. package/cjs/domain/rumEventsCollection/view/trackViews.js.map +1 -1
  145. package/cjs/domain/rumEventsCollection/view/viewCollection.js.map +1 -1
  146. package/cjs/domain/rumSessionManager.js +23 -3
  147. package/cjs/domain/rumSessionManager.js.map +1 -1
  148. package/cjs/domain/tracing/ddtraceTracer.js.map +1 -1
  149. package/cjs/domain/tracing/getDocumentTraceId.js.map +1 -1
  150. package/cjs/domain/tracing/jaegerTracer.js.map +1 -1
  151. package/cjs/domain/tracing/sampler.js.map +1 -1
  152. package/cjs/domain/tracing/skywalkingTracer.js.map +1 -1
  153. package/cjs/domain/tracing/traceIdentifier.js.map +1 -1
  154. package/cjs/domain/tracing/tracer.js +2 -2
  155. package/cjs/domain/tracing/tracer.js.map +1 -1
  156. package/cjs/domain/tracing/w3cTraceParentTracer.js.map +1 -1
  157. package/cjs/domain/tracing/zipkinMultiTracer.js.map +1 -1
  158. package/cjs/domain/tracing/zipkinSingleTracer.js.map +1 -1
  159. package/cjs/domain/trackEventCounts.js.map +1 -1
  160. package/cjs/domain/usr/index.js.map +1 -1
  161. package/cjs/domain/waitPageActivityEnd.js.map +1 -1
  162. package/cjs/index.js.map +1 -1
  163. package/cjs/transport/startRumBatch.js +3 -1
  164. package/cjs/transport/startRumBatch.js.map +1 -1
  165. package/cjs/transport/startRumEventBridge.js.map +1 -1
  166. package/cjs/types/index.js.map +1 -1
  167. package/cjs/types/sessionReplayConstants.js.map +1 -1
  168. package/esm/boot/buildEnv.js +1 -1
  169. package/esm/boot/buildEnv.js.map +1 -1
  170. package/esm/boot/perStartRum.js +42 -6
  171. package/esm/boot/perStartRum.js.map +1 -1
  172. package/esm/boot/recorderApi.js +192 -197
  173. package/esm/boot/recorderApi.js.map +1 -1
  174. package/esm/boot/recorderApiStub.js +3 -29
  175. package/esm/boot/recorderApiStub.js.map +1 -1
  176. package/esm/boot/rum.entry.js.map +1 -1
  177. package/esm/boot/rum.js +8 -0
  178. package/esm/boot/rum.js.map +1 -1
  179. package/esm/boot/rum.slim.entry.js.map +1 -1
  180. package/esm/boot/rumEntryFactory.js.map +1 -1
  181. package/esm/boot/rumPublicApi.js +36 -3
  182. package/esm/boot/rumPublicApi.js.map +1 -1
  183. package/esm/boot/rumRecorderApiStub.js.map +1 -1
  184. package/esm/boot/rumSlimConfiguration.js.map +1 -1
  185. package/esm/boot/sessionReplayPublicApi.js +14 -27
  186. package/esm/boot/sessionReplayPublicApi.js.map +1 -1
  187. package/esm/boot/startRecording.js +334 -109
  188. package/esm/boot/startRecording.js.map +1 -1
  189. package/esm/constants.js.map +1 -1
  190. package/esm/domain/assembly.js +1 -7
  191. package/esm/domain/assembly.js.map +1 -1
  192. package/esm/domain/configuration.js +39 -44
  193. package/esm/domain/configuration.js.map +1 -1
  194. package/esm/domain/contexts/commonContext.js.map +1 -1
  195. package/esm/domain/contexts/displayContext.js.map +1 -1
  196. package/esm/domain/contexts/foregroundContexts.js.map +1 -1
  197. package/esm/domain/contexts/internalContext.js.map +1 -1
  198. package/esm/domain/contexts/pageStateHistory.js.map +1 -1
  199. package/esm/domain/contexts/urlContexts.js +21 -3
  200. package/esm/domain/contexts/urlContexts.js.map +1 -1
  201. package/esm/domain/contexts/viewContexts.js +2 -2
  202. package/esm/domain/contexts/viewContexts.js.map +1 -1
  203. package/esm/domain/deflate/deflateEncoder.js +517 -39
  204. package/esm/domain/deflate/deflateEncoder.js.map +1 -1
  205. package/esm/domain/deflate/deflateWorker.js +193 -116
  206. package/esm/domain/deflate/deflateWorker.js.map +1 -1
  207. package/esm/domain/deflate/index.js.map +1 -1
  208. package/esm/domain/domMutationObservable.js.map +1 -1
  209. package/esm/domain/encoderStreamId.js.map +1 -1
  210. package/esm/domain/firstInputPolyfill.js.map +1 -1
  211. package/esm/domain/initViewportObservable.js.map +1 -1
  212. package/esm/domain/locationChangeObservable.js.map +1 -1
  213. package/esm/domain/performanceObservable.js.map +1 -1
  214. package/esm/domain/performanceUtils.js.map +1 -1
  215. package/esm/domain/plugins.js +59 -0
  216. package/esm/domain/plugins.js.map +1 -0
  217. package/esm/domain/replay/record/canvasAutoSnapshot.js.map +1 -1
  218. package/esm/domain/replay/record/canvasCommandCapture.js +968 -168
  219. package/esm/domain/replay/record/canvasCommandCapture.js.map +1 -1
  220. package/esm/domain/replay/record/canvasCommandObserver.js +1058 -119
  221. package/esm/domain/replay/record/canvasCommandObserver.js.map +1 -1
  222. package/esm/domain/replay/record/canvasCommandSerializeArgs.js +60 -37
  223. package/esm/domain/replay/record/canvasCommandSerializeArgs.js.map +1 -1
  224. package/esm/domain/replay/record/canvasContext.js +50 -0
  225. package/esm/domain/replay/record/canvasContext.js.map +1 -0
  226. package/esm/domain/replay/record/canvasContinuousScheduler.js +246 -118
  227. package/esm/domain/replay/record/canvasContinuousScheduler.js.map +1 -1
  228. package/esm/domain/replay/record/canvasEncodeBridge.js +539 -87
  229. package/esm/domain/replay/record/canvasEncodeBridge.js.map +1 -1
  230. package/esm/domain/replay/record/canvasEncodeWorker.js +51 -33
  231. package/esm/domain/replay/record/canvasEncodeWorker.js.map +1 -1
  232. package/esm/domain/replay/record/canvasFrameSignature.js +50 -17
  233. package/esm/domain/replay/record/canvasFrameSignature.js.map +1 -1
  234. package/esm/domain/replay/record/canvasMutationRecord.js.map +1 -1
  235. package/esm/domain/replay/record/canvasObserver.js +295 -59
  236. package/esm/domain/replay/record/canvasObserver.js.map +1 -1
  237. package/esm/domain/replay/record/canvasSerializeArgs.js.map +1 -1
  238. package/esm/domain/replay/record/canvasWebGLPluginHost.js +26 -0
  239. package/esm/domain/replay/record/canvasWebGLPluginHost.js.map +1 -0
  240. package/esm/domain/replay/record/elementsScrollPositions.js +3 -0
  241. package/esm/domain/replay/record/elementsScrollPositions.js.map +1 -1
  242. package/esm/domain/replay/record/index.js.map +1 -1
  243. package/esm/domain/replay/record/mutationBatch.js +541 -25
  244. package/esm/domain/replay/record/mutationBatch.js.map +1 -1
  245. package/esm/domain/replay/record/mutationObserver.js +1892 -195
  246. package/esm/domain/replay/record/mutationObserver.js.map +1 -1
  247. package/esm/domain/replay/record/mutationResourceBudget.js +137 -0
  248. package/esm/domain/replay/record/mutationResourceBudget.js.map +1 -0
  249. package/esm/domain/replay/record/observers.js +224 -55
  250. package/esm/domain/replay/record/observers.js.map +1 -1
  251. package/esm/domain/replay/record/privacy.js +30 -7
  252. package/esm/domain/replay/record/privacy.js.map +1 -1
  253. package/esm/domain/replay/record/record.js +3086 -325
  254. package/esm/domain/replay/record/record.js.map +1 -1
  255. package/esm/domain/replay/record/serializationUtils.js +422 -25
  256. package/esm/domain/replay/record/serializationUtils.js.map +1 -1
  257. package/esm/domain/replay/record/serialize.js +258 -50
  258. package/esm/domain/replay/record/serialize.js.map +1 -1
  259. package/esm/domain/replay/record/shadowRootsController.js +875 -21
  260. package/esm/domain/replay/record/shadowRootsController.js.map +1 -1
  261. package/esm/domain/replay/record/utils.js.map +1 -1
  262. package/esm/domain/replay/record/viewports.js.map +1 -1
  263. package/esm/domain/replay/replayStats.js.map +1 -1
  264. package/esm/domain/replay/segmentCollection/buildReplayPayload.js.map +1 -1
  265. package/esm/domain/replay/segmentCollection/index.js.map +1 -1
  266. package/esm/domain/replay/segmentCollection/segment.js +315 -10
  267. package/esm/domain/replay/segmentCollection/segment.js.map +1 -1
  268. package/esm/domain/replay/segmentCollection/segmentCollection.js +957 -72
  269. package/esm/domain/replay/segmentCollection/segmentCollection.js.map +1 -1
  270. package/esm/domain/replay/startRecordBridge.js.map +1 -1
  271. package/esm/domain/requestCollection.js.map +1 -1
  272. package/esm/domain/rumEventsCollection/actions/actionCollection.js.map +1 -1
  273. package/esm/domain/rumEventsCollection/actions/clickChain.js.map +1 -1
  274. package/esm/domain/rumEventsCollection/actions/computeFrustration.js.map +1 -1
  275. package/esm/domain/rumEventsCollection/actions/getActionNameFromElement.js.map +1 -1
  276. package/esm/domain/rumEventsCollection/actions/getSelectorsFromElement.js.map +1 -1
  277. package/esm/domain/rumEventsCollection/actions/interactionSelectorCache.js.map +1 -1
  278. package/esm/domain/rumEventsCollection/actions/listenActionEvents.js.map +1 -1
  279. package/esm/domain/rumEventsCollection/actions/trackClickActions.js.map +1 -1
  280. package/esm/domain/rumEventsCollection/error/errorCollection.js.map +1 -1
  281. package/esm/domain/rumEventsCollection/error/trackConsoleError.js.map +1 -1
  282. package/esm/domain/rumEventsCollection/error/trackReportError.js.map +1 -1
  283. package/esm/domain/rumEventsCollection/longTask/longAnimationFrameCollection.js.map +1 -1
  284. package/esm/domain/rumEventsCollection/longTask/longTaskCollection.js.map +1 -1
  285. package/esm/domain/rumEventsCollection/resource/matchRequestResourceEntry.js.map +1 -1
  286. package/esm/domain/rumEventsCollection/resource/resourceCollection.js +55 -0
  287. package/esm/domain/rumEventsCollection/resource/resourceCollection.js.map +1 -1
  288. package/esm/domain/rumEventsCollection/resource/resourceTrackerManager.js.map +1 -1
  289. package/esm/domain/rumEventsCollection/resource/resourceUtils.js.map +1 -1
  290. package/esm/domain/rumEventsCollection/resource/retrieveInitialDocumentResourceTiming.js.map +1 -1
  291. package/esm/domain/rumEventsCollection/resource/webSocketCollection.js +189 -0
  292. package/esm/domain/rumEventsCollection/resource/webSocketCollection.js.map +1 -0
  293. package/esm/domain/rumEventsCollection/view/interactionCountPolyfill.js.map +1 -1
  294. package/esm/domain/rumEventsCollection/view/trackCommonViewMetrics.js.map +1 -1
  295. package/esm/domain/rumEventsCollection/view/trackCumulativeLayoutShift.js.map +1 -1
  296. package/esm/domain/rumEventsCollection/view/trackFirstContentfulPaint.js.map +1 -1
  297. package/esm/domain/rumEventsCollection/view/trackFirstHidden.js.map +1 -1
  298. package/esm/domain/rumEventsCollection/view/trackFirstInput.js.map +1 -1
  299. package/esm/domain/rumEventsCollection/view/trackInitialViewTimings.js.map +1 -1
  300. package/esm/domain/rumEventsCollection/view/trackInteractionToNextPaint.js.map +1 -1
  301. package/esm/domain/rumEventsCollection/view/trackLargestContentfulPaint.js.map +1 -1
  302. package/esm/domain/rumEventsCollection/view/trackLoadingTime.js +8 -3
  303. package/esm/domain/rumEventsCollection/view/trackLoadingTime.js.map +1 -1
  304. package/esm/domain/rumEventsCollection/view/trackNavigationTimings.js.map +1 -1
  305. package/esm/domain/rumEventsCollection/view/trackScrollMetrics.js.map +1 -1
  306. package/esm/domain/rumEventsCollection/view/trackViewEventCounts.js.map +1 -1
  307. package/esm/domain/rumEventsCollection/view/trackViews.js +32 -13
  308. package/esm/domain/rumEventsCollection/view/trackViews.js.map +1 -1
  309. package/esm/domain/rumEventsCollection/view/viewCollection.js.map +1 -1
  310. package/esm/domain/rumSessionManager.js +24 -4
  311. package/esm/domain/rumSessionManager.js.map +1 -1
  312. package/esm/domain/tracing/ddtraceTracer.js.map +1 -1
  313. package/esm/domain/tracing/getDocumentTraceId.js.map +1 -1
  314. package/esm/domain/tracing/jaegerTracer.js.map +1 -1
  315. package/esm/domain/tracing/sampler.js.map +1 -1
  316. package/esm/domain/tracing/skywalkingTracer.js.map +1 -1
  317. package/esm/domain/tracing/traceIdentifier.js.map +1 -1
  318. package/esm/domain/tracing/tracer.js +2 -2
  319. package/esm/domain/tracing/tracer.js.map +1 -1
  320. package/esm/domain/tracing/w3cTraceParentTracer.js.map +1 -1
  321. package/esm/domain/tracing/zipkinMultiTracer.js.map +1 -1
  322. package/esm/domain/tracing/zipkinSingleTracer.js.map +1 -1
  323. package/esm/domain/trackEventCounts.js.map +1 -1
  324. package/esm/domain/usr/index.js.map +1 -1
  325. package/esm/domain/waitPageActivityEnd.js.map +1 -1
  326. package/esm/index.js.map +1 -1
  327. package/esm/transport/startRumBatch.js +4 -2
  328. package/esm/transport/startRumBatch.js.map +1 -1
  329. package/esm/transport/startRumEventBridge.js.map +1 -1
  330. package/esm/types/index.js.map +1 -1
  331. package/esm/types/sessionReplayConstants.js.map +1 -1
  332. package/package.json +12 -7
  333. package/src/boot/perStartRum.js +47 -7
  334. package/src/boot/recorderApi.js +271 -220
  335. package/src/boot/recorderApiStub.js +3 -29
  336. package/src/boot/rum.js +11 -0
  337. package/src/boot/rumPublicApi.js +38 -3
  338. package/src/boot/sessionReplayPublicApi.js +15 -28
  339. package/src/boot/startRecording.js +429 -146
  340. package/src/domain/assembly.js +5 -4
  341. package/src/domain/configuration.js +76 -101
  342. package/src/domain/contexts/urlContexts.js +29 -3
  343. package/src/domain/contexts/viewContexts.js +2 -2
  344. package/src/domain/deflate/deflateEncoder.js +699 -43
  345. package/src/domain/deflate/deflateWorker.js +237 -136
  346. package/src/domain/plugins.js +94 -0
  347. package/src/domain/replay/record/canvasCommandCapture.js +1374 -180
  348. package/src/domain/replay/record/canvasCommandObserver.js +1585 -150
  349. package/src/domain/replay/record/canvasCommandSerializeArgs.js +79 -42
  350. package/src/domain/replay/record/canvasContext.js +67 -0
  351. package/src/domain/replay/record/canvasContinuousScheduler.js +379 -143
  352. package/src/domain/replay/record/canvasEncodeBridge.js +691 -106
  353. package/src/domain/replay/record/canvasEncodeWorker.js +67 -43
  354. package/src/domain/replay/record/canvasFrameSignature.js +58 -24
  355. package/src/domain/replay/record/canvasObserver.js +461 -89
  356. package/src/domain/replay/record/canvasWebGLPluginHost.js +43 -0
  357. package/src/domain/replay/record/elementsScrollPositions.js +3 -0
  358. package/src/domain/replay/record/mutationBatch.js +761 -27
  359. package/src/domain/replay/record/mutationObserver.js +2992 -261
  360. package/src/domain/replay/record/mutationResourceBudget.js +191 -0
  361. package/src/domain/replay/record/observers.js +367 -97
  362. package/src/domain/replay/record/privacy.js +34 -12
  363. package/src/domain/replay/record/record.js +4284 -413
  364. package/src/domain/replay/record/serializationUtils.js +587 -28
  365. package/src/domain/replay/record/serialize.js +432 -66
  366. package/src/domain/replay/record/shadowRootsController.js +1108 -30
  367. package/src/domain/replay/segmentCollection/segment.js +441 -11
  368. package/src/domain/replay/segmentCollection/segmentCollection.js +1300 -77
  369. package/src/domain/rumEventsCollection/resource/resourceCollection.js +70 -0
  370. package/src/domain/rumEventsCollection/resource/webSocketCollection.js +271 -0
  371. package/src/domain/rumEventsCollection/view/trackLoadingTime.js +12 -3
  372. package/src/domain/rumEventsCollection/view/trackViews.js +38 -13
  373. package/src/domain/rumSessionManager.js +33 -2
  374. package/src/domain/tracing/tracer.js +4 -5
  375. package/src/transport/startRumBatch.js +6 -1
  376. package/types/index.d.ts +100 -8
  377. package/cjs/domain/replay/record/canvasReplayFixtures.js +0 -105
  378. package/cjs/domain/replay/record/canvasReplayFixtures.js.map +0 -1
  379. package/esm/domain/replay/record/canvasReplayFixtures.js +0 -96
  380. package/esm/domain/replay/record/canvasReplayFixtures.js.map +0 -1
  381. package/src/domain/replay/record/canvasReplayFixtures.js +0 -113
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  noop,
3
- forEachChildNodes,
4
3
  isNodeShadowHost,
5
4
  getParentNode,
6
5
  isNullUndefinedDefaultValue,
7
- monitor
6
+ monitor,
7
+ assign
8
8
  } from '@cloudcare/browser-core'
9
9
  import { getMutationObserverConstructor } from '../../domMutationObservable'
10
10
  import { NodePrivacyLevel } from '../../../constants'
@@ -13,18 +13,192 @@ import {
13
13
  getElementInputValue,
14
14
  getSerializedNodeId,
15
15
  hasSerializedNode,
16
+ MAX_SERIALIZED_NODE_ANCESTOR_DEPTH,
16
17
  nodeAndAncestorsHaveSerializedNode
17
18
  } from './serializationUtils'
18
19
  import {
19
20
  serializeNodeWithId,
20
21
  createMutationSerializerTask,
21
22
  serializeAttribute,
23
+ truncateSerializedValue,
24
+ SERIALIZATION_MAX_MUTATION_SOURCE_LENGTH,
22
25
  SerializationContextStatus
23
26
  } from './serialize'
24
- import { createMutationBatch } from './mutationBatch'
27
+ import {
28
+ createMutationBatch,
29
+ MAX_QUEUED_MUTATION_NODES
30
+ } from './mutationBatch'
31
+ import { MUTATION_RESOURCE_RETAINED } from './mutationResourceBudget'
25
32
 
26
33
  var MUTATION_SERIALIZATION_SLICE_MS = 4
27
- var MUTATION_SERIALIZATION_EMIT_DELAY_MS = 16
34
+ var MUTATION_SERIALIZATION_FLUSH_BUDGET_MS = 4
35
+ export var MUTATION_NORMALIZATION_MAX_DURATION_MS = 4
36
+ var MUTATION_NORMALIZATION_TIME_CHECK_INTERVAL = 32
37
+ // performance.now() can jump across a short GC pause or an interrupted
38
+ // observer callback. Let a small, raw-batch-bounded amount of normalization
39
+ // finish before treating the wall-clock deadline as structural loss.
40
+ var MUTATION_NORMALIZATION_SMALL_BATCH_MAX_RECORDS = 32
41
+ var MUTATION_NORMALIZATION_MIN_OPERATIONS_BEFORE_TIMEOUT = 256
42
+ var MUTATION_NORMALIZATION_ABORT = {}
43
+ // A serialized add cannot be split below its root. Stop before building one
44
+ // that would exceed record.js' single mutation emit watermark.
45
+ var MUTATION_SERIALIZATION_MAX_NODE_COUNT = 5000
46
+ var MUTATION_SERIALIZATION_MAX_APPROX_BYTES = 200000
47
+ export var MAX_PENDING_MUTATION_ROOT_TASKS = 256
48
+ // Keep the expensive serializer state bounded while allowing a large burst of
49
+ // unpublished, add-only roots to wait as lightweight DOM references. The
50
+ // deferred queue is intentionally finite and matches the raw node watermark:
51
+ // one accepted native callback can therefore be drained without dropping a
52
+ // root, while a sustained producer still cannot grow the queue without bound.
53
+ export var MAX_DEFERRED_MUTATION_ROOT_TASKS =
54
+ MAX_QUEUED_MUTATION_NODES
55
+ var DEFERRED_MUTATION_ROOT_TASK_APPROX_BYTES = 128
56
+ export var MAX_PENDING_MUTATION_GROUPS = 256
57
+ export var MAX_PENDING_MUTATION_ROOT_APPROX_BYTES = 4 * 1024 * 1024
58
+ export var MAX_MUTATION_ROOT_TASK_REFRESH_COUNT = 16
59
+ export var MAX_REMOVED_SUBTREE_TRAVERSAL_NODES = 5000
60
+ // MutationBatch can only account for MutationRecord.oldValue. Bound the
61
+ // current text/attribute values separately before privacy transforms and
62
+ // record-size estimation scan them synchronously.
63
+ export var MAX_MUTATION_CURRENT_SOURCE_CHARACTERS = 512 * 1024
64
+ export var MAX_MUTATION_SERIALIZED_VALUE_CHARACTERS =
65
+ SERIALIZATION_MAX_MUTATION_SOURCE_LENGTH
66
+ var AGGREGATE_RETAINED_MUTATION_WATERMARK =
67
+ 'aggregate_retained_mutation_watermark'
68
+ var MUTATION_ROOT_ADMISSION_WATERMARK =
69
+ 'mutation_root_admission_watermark'
70
+ var MUTATION_ROOT_RETAINED_BYTES_WATERMARK =
71
+ 'mutation_root_retained_bytes_watermark'
72
+ var MAX_REMOVED_SUBTREE_TRAVERSAL_DURATION_MS = 4
73
+ var REMOVED_SUBTREE_TIME_CHECK_INTERVAL = 32
74
+ var publicationTokenByMutationAdd = new WeakMap()
75
+ var sourceNodeByMutationRemove = new WeakMap()
76
+ var approxBytesByMutationPayload = new WeakMap()
77
+
78
+ export function getMutationPayloadApproxBytes(payload) {
79
+ var trackedApproxBytes = approxBytesByMutationPayload.get(payload)
80
+ if (trackedApproxBytes) {
81
+ return trackedApproxBytes
82
+ }
83
+ return estimateFallbackMutationPayloadApproxBytes(payload)
84
+ }
85
+
86
+ function estimateFallbackMutationPayloadApproxBytes(payload) {
87
+ if (!payload) {
88
+ return 64
89
+ }
90
+ return (
91
+ 64 +
92
+ (payload.adds || []).length * 64 +
93
+ estimateMutationPayloadEntriesApproxBytes(payload)
94
+ )
95
+ }
96
+
97
+ function estimateMutationPayloadEntriesApproxBytes(payload) {
98
+ var approxBytes = (payload.removes || []).length * 24
99
+ ;(payload.texts || []).forEach(function (text) {
100
+ approxBytes += 24 + getMutationPayloadStringApproxBytes(text.value)
101
+ })
102
+ ;(payload.attributes || []).forEach(function (attribute) {
103
+ approxBytes += 24
104
+ Object.keys(attribute.attributes || {}).forEach(function (name) {
105
+ approxBytes +=
106
+ getMutationPayloadStringApproxBytes(name) +
107
+ getMutationPayloadStringApproxBytes(attribute.attributes[name])
108
+ })
109
+ })
110
+ return approxBytes
111
+ }
112
+
113
+ function getMutationPayloadStringApproxBytes(value) {
114
+ return typeof value === 'string' ? value.length * 2 : 0
115
+ }
116
+
117
+ function getMutationDependencyState(shadowRootsController) {
118
+ if (!shadowRootsController) {
119
+ return
120
+ }
121
+ if (!shadowRootsController.$rMutationDependencyState) {
122
+ shadowRootsController.$rMutationDependencyState = {
123
+ $rPublishedRoots: new WeakSet(),
124
+ $rLocallyDroppedRoots: new WeakSet()
125
+ }
126
+ }
127
+ return shadowRootsController.$rMutationDependencyState
128
+ }
129
+
130
+ export function consumeMutationAddPublicationToken(add) {
131
+ var publicationToken = publicationTokenByMutationAdd.get(add)
132
+ publicationTokenByMutationAdd.delete(add)
133
+ return publicationToken
134
+ }
135
+
136
+ export function getMutationAddPublicationToken(add) {
137
+ return publicationTokenByMutationAdd.get(add)
138
+ }
139
+
140
+ export function registerMutationAddPublicationToken(add, publicationToken) {
141
+ publicationTokenByMutationAdd.set(add, publicationToken)
142
+ }
143
+
144
+ export function createMutationAddPublicationToken(
145
+ shadowRootsController,
146
+ requiresBaselineOnDrop
147
+ ) {
148
+ return {
149
+ $rPublished: false,
150
+ $rQueued: false,
151
+ $rCanceled: false,
152
+ $rRequiresBaselineOnDrop: Boolean(requiresBaselineOnDrop),
153
+ $rShadowRootsController: shadowRootsController
154
+ }
155
+ }
156
+
157
+ export function publishMutationAddPublicationToken(publicationToken) {
158
+ if (!publicationToken || publicationToken.$rCanceled) {
159
+ return
160
+ }
161
+ publicationToken.$rQueued = false
162
+ publicationToken.$rPublished = true
163
+ var shadowRootsController = publicationToken.$rShadowRootsController
164
+ if (
165
+ shadowRootsController &&
166
+ shadowRootsController.commitProvisionalShadowRoots
167
+ ) {
168
+ shadowRootsController.commitProvisionalShadowRoots(publicationToken)
169
+ }
170
+ publicationToken.$rShadowRootsController = undefined
171
+ }
172
+
173
+ export function cancelMutationAddPublicationToken(publicationToken) {
174
+ if (
175
+ !publicationToken ||
176
+ publicationToken.$rPublished ||
177
+ publicationToken.$rCanceled
178
+ ) {
179
+ return
180
+ }
181
+ publicationToken.$rQueued = false
182
+ publicationToken.$rCanceled = true
183
+ var shadowRootsController = publicationToken.$rShadowRootsController
184
+ if (
185
+ shadowRootsController &&
186
+ shadowRootsController.rollbackProvisionalShadowRoots
187
+ ) {
188
+ shadowRootsController.rollbackProvisionalShadowRoots(publicationToken)
189
+ }
190
+ publicationToken.$rShadowRootsController = undefined
191
+ }
192
+
193
+ export function consumeMutationRemoveSourceNode(remove) {
194
+ var sourceNode = sourceNodeByMutationRemove.get(remove)
195
+ sourceNodeByMutationRemove.delete(remove)
196
+ return sourceNode
197
+ }
198
+
199
+ export function getMutationRemoveSourceNode(remove) {
200
+ return sourceNodeByMutationRemove.get(remove)
201
+ }
28
202
 
29
203
  /**
30
204
  * Buffers and aggregate mutations generated by a MutationObserver into MutationPayload
@@ -34,37 +208,90 @@ export function startMutationObserver(
34
208
  configuration,
35
209
  shadowRootsController,
36
210
  target,
37
- mutationPerfCb
211
+ mutationPerfCb,
212
+ mutationOverflowCb,
213
+ mutationActivityCb,
214
+ mutationNodeSerializationCb,
215
+ isNodeIgnored,
216
+ isNodePublished,
217
+ isSourceActive,
218
+ mutationResourceBudget
38
219
  ) {
39
220
  var MutationObserver = getMutationObserverConstructor()
40
221
  if (!MutationObserver) {
41
- return { stop: noop, flush: noop, reset: noop }
222
+ return { stop: noop, flush: noop, reset: noop, deactivate: noop }
223
+ }
224
+ var active = true
225
+ var isObserverActive = function () {
226
+ return active && (!isSourceActive || isSourceActive())
42
227
  }
43
228
 
44
229
  var mutationTasksController = createMutationTasksController(
45
230
  mutationCallback,
46
231
  configuration,
47
- shadowRootsController
232
+ shadowRootsController,
233
+ mutationPerfCb,
234
+ mutationOverflowCb,
235
+ mutationNodeSerializationCb,
236
+ isNodeIgnored,
237
+ mutationResourceBudget
48
238
  )
49
239
 
50
- var mutationBatch = createMutationBatch(function (mutations) {
51
- var processStart = getCurrentTime()
52
- processMutations(
53
- mutations.concat(observer.takeRecords()),
240
+ var mutationBatch = createMutationBatch(function (
241
+ mutations,
242
+ mutationBatchContext
243
+ ) {
244
+ if (!isObserverActive()) {
245
+ return
246
+ }
247
+ var processStart = __BUILD_ENV__REPLAY_DEBUG_ENABLED__
248
+ ? getCurrentTime()
249
+ : 0
250
+ var overflowCountBeforeProcess =
251
+ mutationTasksController.getOverflowCount()
252
+ var processed = processMutations(
253
+ mutations,
54
254
  mutationCallback,
55
255
  configuration,
56
256
  shadowRootsController,
57
- mutationTasksController
257
+ mutationTasksController,
258
+ isNodeIgnored,
259
+ isNodePublished,
260
+ mutationBatchContext
58
261
  )
59
- if (mutationPerfCb) {
262
+ if (__BUILD_ENV__REPLAY_DEBUG_ENABLED__ && mutationPerfCb) {
60
263
  mutationPerfCb({
61
264
  processMutationsCount: 1,
62
265
  processMutationsDuration: getCurrentTime() - processStart
63
266
  })
64
267
  }
65
- })
268
+ return mutationTasksController.getOverflowCount() ===
269
+ overflowCountBeforeProcess
270
+ ? processed
271
+ : false
272
+ }, function (overflow) {
273
+ if (!active) {
274
+ return
275
+ }
276
+ observer.takeRecords()
277
+ mutationTasksController.reset()
278
+ reportMutationOverflow({
279
+ reason: overflow.reason || 'raw_mutation_watermark',
280
+ mutationRecordCount: overflow.mutationRecordCount,
281
+ mutationNodeCount: overflow.mutationNodeCount,
282
+ mutationApproxBytes: overflow.mutationApproxBytes
283
+ })
284
+ }, mutationResourceBudget)
66
285
 
67
- var observer = new MutationObserver(monitor(mutationBatch.addMutations))
286
+ var observer = new MutationObserver(
287
+ monitor(function (mutations) {
288
+ if (!isObserverActive()) {
289
+ return
290
+ }
291
+ notifyMutationActivity(mutations)
292
+ mutationBatch.addMutations(mutations)
293
+ })
294
+ )
68
295
  try {
69
296
  observer.observe(target, {
70
297
  attributeOldValue: true,
@@ -78,45 +305,229 @@ export function startMutationObserver(
78
305
 
79
306
  return {
80
307
  stop: function () {
308
+ active = false
81
309
  observer.disconnect()
82
310
  mutationBatch.stop()
83
311
  mutationTasksController.stop()
84
312
  },
313
+ deactivate: function () {
314
+ // Shadow-root generation cleanup is deliberately sliced. Stop native
315
+ // callbacks and release queued records/serializer tasks immediately,
316
+ // while leaving the physical disconnect and listener cleanup to stop().
317
+ //
318
+ // Do not mark the task controller as stopped here. A removed-subtree
319
+ // overflow can retire its shadow generation from inside processMutations
320
+ // and must still deliver the paired overflow callback after reset().
321
+ active = false
322
+ mutationBatch.reset()
323
+ mutationTasksController.reset()
324
+ },
325
+ refreshAndFlushPendingRootForNode: function (node) {
326
+ if (!isObserverActive()) {
327
+ return
328
+ }
329
+ // A common attachShadow() pattern appends the host and attaches the root
330
+ // in the same JavaScript turn, before the native MutationObserver
331
+ // callback runs. Materialize those queued host records first so the
332
+ // targeted pending-root lookup also covers that synchronous window.
333
+ var pendingRecords = observer.takeRecords()
334
+ notifyMutationActivity(pendingRecords)
335
+ if (!mutationBatch.addMutations(pendingRecords)) {
336
+ return false
337
+ }
338
+ var batchFlushResult = mutationBatch.flush()
339
+ if (batchFlushResult === false) {
340
+ // A normalization overflow is reported from inside the batch
341
+ // processor. The batch drops its queued generation, but the task
342
+ // controller must also leave its overflowed state so a later DOM
343
+ // change can be recorded after recovery, matching the pre-slicing
344
+ // observer lifecycle.
345
+ mutationTasksController.reset()
346
+ }
347
+ if (batchFlushResult !== true) {
348
+ return batchFlushResult
349
+ }
350
+ return mutationTasksController.refreshAndFlushPendingRootForNode(
351
+ node
352
+ )
353
+ },
85
354
  flush: function () {
86
- mutationBatch.flush()
87
- mutationTasksController.flush()
355
+ if (!isObserverActive()) {
356
+ return true
357
+ }
358
+ var pendingRecords = observer.takeRecords()
359
+ notifyMutationActivity(pendingRecords)
360
+ if (!mutationBatch.addMutations(pendingRecords)) {
361
+ return false
362
+ }
363
+ var overflowCountBeforeFlush =
364
+ mutationTasksController.getOverflowCount()
365
+ var batchFlushResult = mutationBatch.flush()
366
+ if (batchFlushResult === false) {
367
+ // processMutations may fail the task controller while mutationBatch
368
+ // is draining a transaction. Reset both halves of the pipeline; an
369
+ // otherwise sticky overflow would silently drop every later change.
370
+ mutationTasksController.reset()
371
+ }
372
+ if (batchFlushResult !== true) {
373
+ return batchFlushResult
374
+ }
375
+ var taskFlushResult = mutationTasksController.flush()
376
+ if (taskFlushResult === 'pending') {
377
+ return 'pending'
378
+ }
379
+ if (taskFlushResult === false) {
380
+ var overflowAlreadyReported =
381
+ mutationTasksController.getOverflowCount() >
382
+ overflowCountBeforeFlush
383
+ mutationTasksController.reset()
384
+ if (!overflowAlreadyReported) {
385
+ reportMutationOverflow({
386
+ reason: 'serialization_budget'
387
+ })
388
+ }
389
+ return false
390
+ }
391
+ return true
88
392
  },
89
393
  reset: function () {
394
+ if (!isObserverActive()) {
395
+ return
396
+ }
397
+ // Drop records queued by the native observer before resetting the
398
+ // time-sliced serializer. Otherwise they may be delivered after a full
399
+ // snapshot and replay stale mutations on top of the new DOM baseline.
400
+ notifyMutationActivity(observer.takeRecords())
90
401
  if (mutationBatch.reset) {
91
402
  mutationBatch.reset()
92
403
  }
93
404
  mutationTasksController.reset()
94
405
  }
95
406
  }
407
+
408
+ function notifyMutationActivity(mutations) {
409
+ if (mutations.length && mutationActivityCb) {
410
+ mutationActivityCb(target)
411
+ }
412
+ }
413
+
414
+ function reportMutationOverflow(overflow) {
415
+ if (
416
+ mutationResourceBudget &&
417
+ !mutationResourceBudget.failOnce()
418
+ ) {
419
+ return
420
+ }
421
+ if (mutationOverflowCb) {
422
+ mutationOverflowCb(overflow)
423
+ }
424
+ }
96
425
  }
97
426
 
98
- function processMutations(
427
+ export function processMutations(
99
428
  mutations,
100
429
  mutationCallback,
101
430
  configuration,
102
431
  shadowRootsController,
103
- mutationTasksController
432
+ mutationTasksController,
433
+ isNodeIgnored,
434
+ isNodePublished,
435
+ mutationBatchContext
104
436
  ) {
437
+ isNodeIgnored = isNodeIgnored || function () {
438
+ return false
439
+ }
440
+ isNodePublished = isNodePublished || hasSerializedNode
441
+ if (mutationTasksController.isOverflowed()) {
442
+ return
443
+ }
444
+ var transactionState =
445
+ mutationBatchContext && mutationBatchContext.transaction
105
446
  var nodePrivacyLevelCache = new Map()
106
447
  var pendingRootTasksToRefresh = new Set()
107
448
  var childListMutations = []
108
449
  var characterDataMutations = []
109
450
  var attributeMutations = []
451
+ var disconnectedShadowRootsCleaned = false
452
+ var removedSubtreeTraversalState = {
453
+ deadline: undefined,
454
+ nodeCount: 0
455
+ }
456
+ var normalizationState = {
457
+ deadline:
458
+ getCurrentTime() + MUTATION_NORMALIZATION_MAX_DURATION_MS,
459
+ exhausted: false,
460
+ mutationTasksController: mutationTasksController,
461
+ mutationRecordCount: mutations.length,
462
+ timeCheckCount: 0
463
+ }
464
+ var currentSourceState
465
+ if (transactionState) {
466
+ currentSourceState = transactionState.$rCurrentSourceState
467
+ if (!currentSourceState) {
468
+ currentSourceState = { characters: 0 }
469
+ transactionState.$rCurrentSourceState = currentSourceState
470
+ }
471
+ } else {
472
+ currentSourceState = { characters: 0 }
473
+ }
110
474
 
111
475
  for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {
476
+ if (
477
+ consumeMutationNormalizationBudget(
478
+ normalizationState,
479
+ mutationTasksController
480
+ )
481
+ ) {
482
+ cancelNormalizedMutationGroup(
483
+ mutationTasksController,
484
+ mutationGroup
485
+ )
486
+ return
487
+ }
112
488
  var mutation = mutations_1[_i]
113
- if (mutation.type === 'childList') {
114
- mutation.removedNodes.forEach(function (removedNode) {
115
- traverseRemovedShadowDom(
116
- removedNode,
117
- shadowRootsController.removeShadowRoot
118
- )
119
- })
489
+ if (
490
+ mutation.type === 'childList' &&
491
+ mutation.removedNodes.length
492
+ ) {
493
+ if (
494
+ !disconnectedShadowRootsCleaned &&
495
+ shadowRootsController.cleanupDisconnectedShadowRoots
496
+ ) {
497
+ // The controller owns a sliced registry cleanup. It is both safer and
498
+ // cheaper than walking every node in a potentially huge removed
499
+ // subtree merely to discover its shadow hosts. The root removal itself
500
+ // remains a complete replay mutation.
501
+ shadowRootsController.cleanupDisconnectedShadowRoots()
502
+ disconnectedShadowRootsCleaned = true
503
+ } else if (!shadowRootsController.cleanupDisconnectedShadowRoots) {
504
+ // Preserve compatibility with lightweight/custom controllers that do
505
+ // not own a registry by falling back to the bounded subtree walk.
506
+ mutation.removedNodes.forEach(function (removedNode) {
507
+ if (
508
+ !removedSubtreeTraversalState.overflowed &&
509
+ !traverseRemovedShadowDom(
510
+ removedNode,
511
+ shadowRootsController.removeShadowRoot,
512
+ removedSubtreeTraversalState
513
+ )
514
+ ) {
515
+ removedSubtreeTraversalState.overflowed = true
516
+ }
517
+ })
518
+ if (removedSubtreeTraversalState.overflowed) {
519
+ if (shadowRootsController.reset) {
520
+ try {
521
+ shadowRootsController.reset()
522
+ } catch (_) {}
523
+ }
524
+ mutationTasksController.handleOverflow({
525
+ reason: 'removed_subtree_watermark',
526
+ mutationNodeCount: removedSubtreeTraversalState.nodeCount
527
+ })
528
+ return
529
+ }
530
+ }
120
531
  }
121
532
 
122
533
  var target = mutation.target
@@ -124,6 +535,7 @@ function processMutations(
124
535
  if (
125
536
  !target.isConnected ||
126
537
  (!nodeAndAncestorsHaveSerializedNode(target) && !pendingRootTask) ||
538
+ (isNodeIgnored(target) && !pendingRootTask) ||
127
539
  getNodePrivacyLevel(
128
540
  target,
129
541
  configuration.defaultPrivacyLevel,
@@ -145,17 +557,84 @@ function processMutations(
145
557
  break
146
558
  }
147
559
  }
560
+ if (
561
+ consumeMutationNormalizationBudget(
562
+ normalizationState,
563
+ mutationTasksController,
564
+ true
565
+ )
566
+ ) {
567
+ return
568
+ }
148
569
 
570
+ var supportsMutationGroups = Boolean(
571
+ mutationTasksController.createMutationGroup
572
+ )
573
+ var isPureAddTransaction = Boolean(
574
+ transactionState && transactionState.$rPureAdd
575
+ )
576
+ if (transactionState && transactionState.$rFailed) {
577
+ return false
578
+ }
579
+ var shouldCreateMutationGroup =
580
+ supportsMutationGroups &&
581
+ ((!isPureAddTransaction && Boolean(transactionState)) ||
582
+ shouldUseAtomicMutationGroup(
583
+ childListMutations,
584
+ characterDataMutations,
585
+ attributeMutations
586
+ ))
587
+ var mutationGroup
588
+ if (transactionState && !isPureAddTransaction) {
589
+ if (!transactionState.$rMutationGroup) {
590
+ transactionState.$rMutationGroup =
591
+ mutationTasksController.createMutationGroup(mutationCallback)
592
+ if (transactionState.$rMutationGroup) {
593
+ transactionState.$rMutationGroup.$rTransactionState = transactionState
594
+ }
595
+ transactionState.$rPayload = {
596
+ removes: [],
597
+ texts: [],
598
+ attributes: []
599
+ }
600
+ }
601
+ mutationGroup = transactionState.$rMutationGroup
602
+ } else if (shouldCreateMutationGroup) {
603
+ mutationGroup = mutationTasksController.createMutationGroup(
604
+ mutationCallback
605
+ )
606
+ }
607
+ // Overflow recovery can synchronously reset the controller from inside the
608
+ // callback. An empty result is therefore the durable failure signal; the
609
+ // transient overflow flag is not safe to re-read here.
610
+ if (shouldCreateMutationGroup && !mutationGroup) {
611
+ if (transactionState) {
612
+ transactionState.$rFailed = true
613
+ }
614
+ return false
615
+ }
149
616
  var _processChildListMutations = processChildListMutations(
150
617
  childListMutations,
151
618
  configuration,
152
619
  shadowRootsController,
153
620
  nodePrivacyLevelCache,
154
621
  mutationTasksController,
155
- pendingRootTasksToRefresh
622
+ pendingRootTasksToRefresh,
623
+ normalizationState,
624
+ isNodePublished,
625
+ mutationGroup,
626
+ mutationBatchContext &&
627
+ mutationBatchContext.$rTextReplacementByRemovedNode
156
628
  )
157
629
  var removes = _processChildListMutations.removes
158
630
  var serializedNodeIds = _processChildListMutations.serializedNodeIds
631
+ if (_processChildListMutations.overflowed) {
632
+ cancelNormalizedMutationGroup(
633
+ mutationTasksController,
634
+ mutationGroup
635
+ )
636
+ return
637
+ }
159
638
 
160
639
  function hasBeenSerialized(node) {
161
640
  return (
@@ -170,6 +649,18 @@ function processMutations(
170
649
  _a < characterDataMutations_1.length;
171
650
  _a++
172
651
  ) {
652
+ if (
653
+ consumeMutationNormalizationBudget(
654
+ normalizationState,
655
+ mutationTasksController
656
+ )
657
+ ) {
658
+ cancelNormalizedMutationGroup(
659
+ mutationTasksController,
660
+ mutationGroup
661
+ )
662
+ return
663
+ }
173
664
  var characterDataMutation = characterDataMutations_1[_a]
174
665
  var pendingCharacterDataRootTask = mutationTasksController.findPendingRootTask(
175
666
  characterDataMutation.target
@@ -185,15 +676,51 @@ function processMutations(
185
676
  var texts = processCharacterDataMutations(
186
677
  pendingCharacterDataMutations,
187
678
  configuration,
188
- nodePrivacyLevelCache
679
+ nodePrivacyLevelCache,
680
+ mutationTasksController,
681
+ normalizationState,
682
+ currentSourceState,
683
+ transactionState &&
684
+ (transactionState.$rHandledCharacterDataNodes ||
685
+ (transactionState.$rHandledCharacterDataNodes = new Set()))
189
686
  )
190
-
687
+ consumeMutationNormalizationBudget(
688
+ normalizationState,
689
+ mutationTasksController,
690
+ true
691
+ )
692
+ if (normalizationState.exhausted) {
693
+ cancelNormalizedMutationGroup(
694
+ mutationTasksController,
695
+ mutationGroup
696
+ )
697
+ return
698
+ }
699
+ if (mutationTasksController.isOverflowed()) {
700
+ cancelNormalizedMutationGroup(
701
+ mutationTasksController,
702
+ mutationGroup
703
+ )
704
+ return
705
+ }
191
706
  var pendingAttributeMutations = []
192
707
  for (
193
708
  var _b = 0, attributeMutations_1 = attributeMutations;
194
709
  _b < attributeMutations_1.length;
195
710
  _b++
196
711
  ) {
712
+ if (
713
+ consumeMutationNormalizationBudget(
714
+ normalizationState,
715
+ mutationTasksController
716
+ )
717
+ ) {
718
+ cancelNormalizedMutationGroup(
719
+ mutationTasksController,
720
+ mutationGroup
721
+ )
722
+ return
723
+ }
197
724
  var attributeMutation = attributeMutations_1[_b]
198
725
  var pendingAttributeRootTask = mutationTasksController.findPendingRootTask(
199
726
  attributeMutation.target
@@ -209,11 +736,163 @@ function processMutations(
209
736
  var attributes = processAttributesMutations(
210
737
  pendingAttributeMutations,
211
738
  configuration,
212
- nodePrivacyLevelCache
739
+ nodePrivacyLevelCache,
740
+ mutationTasksController,
741
+ normalizationState,
742
+ currentSourceState,
743
+ transactionState &&
744
+ (transactionState.$rHandledAttributeMutations ||
745
+ (transactionState.$rHandledAttributeMutations = new Map()))
213
746
  )
214
- pendingRootTasksToRefresh.forEach(function (task) {
215
- mutationTasksController.refreshPendingRootTask(task)
216
- })
747
+ consumeMutationNormalizationBudget(
748
+ normalizationState,
749
+ mutationTasksController,
750
+ true
751
+ )
752
+ if (normalizationState.exhausted) {
753
+ cancelNormalizedMutationGroup(
754
+ mutationTasksController,
755
+ mutationGroup
756
+ )
757
+ return
758
+ }
759
+ if (mutationTasksController.isOverflowed()) {
760
+ cancelNormalizedMutationGroup(
761
+ mutationTasksController,
762
+ mutationGroup
763
+ )
764
+ return
765
+ }
766
+ var rootTasksToRefresh = Array.from(pendingRootTasksToRefresh)
767
+ var refreshedRootTasks =
768
+ transactionState && rootTasksToRefresh.length
769
+ ? transactionState.$rRefreshedRootTasks ||
770
+ (transactionState.$rRefreshedRootTasks = new Set())
771
+ : undefined
772
+ for (
773
+ var refreshIndex = 0;
774
+ refreshIndex < rootTasksToRefresh.length;
775
+ refreshIndex += 1
776
+ ) {
777
+ var rootTaskToRefresh = rootTasksToRefresh[refreshIndex]
778
+ if (
779
+ refreshedRootTasks &&
780
+ refreshedRootTasks.has(rootTaskToRefresh)
781
+ ) {
782
+ continue
783
+ }
784
+ if (
785
+ consumeMutationNormalizationBudget(
786
+ normalizationState,
787
+ mutationTasksController
788
+ )
789
+ ) {
790
+ cancelNormalizedMutationGroup(
791
+ mutationTasksController,
792
+ mutationGroup
793
+ )
794
+ return
795
+ }
796
+ if (
797
+ !mutationTasksController.refreshPendingRootTask(
798
+ rootTaskToRefresh
799
+ )
800
+ ) {
801
+ cancelNormalizedMutationGroup(
802
+ mutationTasksController,
803
+ mutationGroup
804
+ )
805
+ return
806
+ }
807
+ if (refreshedRootTasks) {
808
+ refreshedRootTasks.add(rootTaskToRefresh)
809
+ }
810
+ }
811
+ if (
812
+ consumeMutationNormalizationBudget(
813
+ normalizationState,
814
+ mutationTasksController,
815
+ true
816
+ )
817
+ ) {
818
+ cancelNormalizedMutationGroup(
819
+ mutationTasksController,
820
+ mutationGroup
821
+ )
822
+ return
823
+ }
824
+ if (transactionState && !isPureAddTransaction) {
825
+ Array.prototype.push.apply(transactionState.$rPayload.removes, removes)
826
+ Array.prototype.push.apply(transactionState.$rPayload.texts, texts)
827
+ Array.prototype.push.apply(
828
+ transactionState.$rPayload.attributes,
829
+ attributes
830
+ )
831
+ if (mutationBatchContext.isLast) {
832
+ completeNormalizedMutation(
833
+ mutationCallback,
834
+ mutationTasksController,
835
+ mutationGroup,
836
+ transactionState.$rPayload.removes,
837
+ transactionState.$rPayload.texts,
838
+ transactionState.$rPayload.attributes
839
+ )
840
+ transactionState.$rCompleted = true
841
+ }
842
+ } else {
843
+ completeNormalizedMutation(
844
+ mutationCallback,
845
+ mutationTasksController,
846
+ mutationGroup,
847
+ removes,
848
+ texts,
849
+ attributes
850
+ )
851
+ }
852
+ return true
853
+ }
854
+
855
+ function shouldUseAtomicMutationGroup(
856
+ childListMutations,
857
+ characterDataMutations,
858
+ attributeMutations
859
+ ) {
860
+ if (characterDataMutations.length || attributeMutations.length) {
861
+ return true
862
+ }
863
+ for (
864
+ var mutationIndex = 0;
865
+ mutationIndex < childListMutations.length;
866
+ mutationIndex += 1
867
+ ) {
868
+ var mutation = childListMutations[mutationIndex]
869
+ if (mutation.removedNodes.length) {
870
+ return true
871
+ }
872
+ }
873
+ return false
874
+ }
875
+
876
+ function completeNormalizedMutation(
877
+ mutationCallback,
878
+ mutationTasksController,
879
+ mutationGroup,
880
+ removes,
881
+ texts,
882
+ attributes
883
+ ) {
884
+ if (
885
+ mutationGroup &&
886
+ mutationTasksController.completeMutationGroup
887
+ ) {
888
+ mutationTasksController.completeMutationGroup(mutationGroup, {
889
+ adds: [],
890
+ removes: removes,
891
+ texts: texts,
892
+ attributes: attributes
893
+ })
894
+ return
895
+ }
217
896
  if (!texts.length && !attributes.length && !removes.length) {
218
897
  return
219
898
  }
@@ -225,13 +904,32 @@ function processMutations(
225
904
  })
226
905
  }
227
906
 
907
+ function cancelNormalizedMutationGroup(
908
+ mutationTasksController,
909
+ mutationGroup
910
+ ) {
911
+ if (
912
+ mutationGroup &&
913
+ mutationTasksController.cancelMutationGroup
914
+ ) {
915
+ if (mutationGroup.$rTransactionState) {
916
+ mutationGroup.$rTransactionState.$rFailed = true
917
+ }
918
+ mutationTasksController.cancelMutationGroup(mutationGroup)
919
+ }
920
+ }
921
+
228
922
  function processChildListMutations(
229
923
  mutations,
230
924
  configuration,
231
925
  shadowRootsController,
232
926
  nodePrivacyLevelCache,
233
927
  mutationTasksController,
234
- pendingRootTasksToRefresh
928
+ pendingRootTasksToRefresh,
929
+ normalizationState,
930
+ isNodePublished,
931
+ mutationGroup,
932
+ coalescedTextReplacementByRemovedNode
235
933
  ) {
236
934
  // First, we iterate over mutations to collect:
237
935
  //
@@ -246,21 +944,342 @@ function processChildListMutations(
246
944
  // the node will be in both sets.
247
945
  var addedAndMovedNodes = new Set()
248
946
  var removedNodes = new Map()
947
+ var replacementNodes = new Set()
948
+ var singleReplacementNodes = new Map()
249
949
  for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {
250
950
  var mutation = mutations_1[_i]
251
- mutation.addedNodes.forEach(function (node) {
252
- addedAndMovedNodes.add(node)
253
- })
254
- mutation.removedNodes.forEach(function (node) {
255
- if (!addedAndMovedNodes.has(node)) {
256
- removedNodes.set(node, mutation.target)
951
+ var coalescedTextReplacementMarker = undefined
952
+ var expectedTextReplacementSource
953
+ if (coalescedTextReplacementByRemovedNode) {
954
+ for (
955
+ var markerIndex = 0;
956
+ markerIndex < mutation.removedNodes.length;
957
+ markerIndex += 1
958
+ ) {
959
+ var markerSource = mutation.removedNodes[markerIndex]
960
+ var currentMarker =
961
+ coalescedTextReplacementByRemovedNode.get(markerSource)
962
+ if (currentMarker) {
963
+ if (coalescedTextReplacementMarker) {
964
+ mutationTasksController.handleOverflow({
965
+ reason: 'published_move_cancelled'
966
+ })
967
+ return createChildListNormalizationOverflowResult()
968
+ }
969
+ coalescedTextReplacementMarker = currentMarker
970
+ expectedTextReplacementSource = markerSource
971
+ }
257
972
  }
258
- addedAndMovedNodes.delete(node)
259
- })
973
+ }
974
+ if (coalescedTextReplacementMarker) {
975
+ var markerAddedNode = mutation.addedNodes[0]
976
+ var markerReachedFinal =
977
+ markerAddedNode === coalescedTextReplacementMarker[1]
978
+ if (
979
+ mutation.removedNodes.length !== 1 ||
980
+ mutation.addedNodes.length !== 1 ||
981
+ expectedTextReplacementSource.nodeType !== 3 ||
982
+ !markerAddedNode ||
983
+ markerAddedNode.nodeType !== 3 ||
984
+ mutation.target !== coalescedTextReplacementMarker[0] ||
985
+ expectedTextReplacementSource.isConnected ||
986
+ isNodePublished(expectedTextReplacementSource) ||
987
+ mutationTasksController.findPendingRootTask(
988
+ expectedTextReplacementSource
989
+ ) ||
990
+ (!markerReachedFinal &&
991
+ (markerAddedNode.isConnected ||
992
+ isNodePublished(markerAddedNode) ||
993
+ mutationTasksController.findPendingRootTask(markerAddedNode)))
994
+ ) {
995
+ mutationTasksController.handleOverflow({
996
+ reason: 'published_move_cancelled'
997
+ })
998
+ return createChildListNormalizationOverflowResult()
999
+ }
1000
+ coalescedTextReplacementByRemovedNode.delete(
1001
+ expectedTextReplacementSource
1002
+ )
1003
+ if (!markerReachedFinal) {
1004
+ coalescedTextReplacementByRemovedNode.set(
1005
+ markerAddedNode,
1006
+ coalescedTextReplacementMarker
1007
+ )
1008
+ }
1009
+ if (
1010
+ consumeMutationNormalizationBudget(
1011
+ normalizationState,
1012
+ mutationTasksController
1013
+ )
1014
+ ) {
1015
+ return createChildListNormalizationOverflowResult()
1016
+ }
1017
+ continue
1018
+ }
1019
+ if (
1020
+ mutation.removedNodes.length === 1 &&
1021
+ mutation.addedNodes.length === 1 &&
1022
+ mutation.removedNodes[0] !== mutation.addedNodes[0]
1023
+ ) {
1024
+ singleReplacementNodes.set(
1025
+ mutation.removedNodes[0],
1026
+ [
1027
+ mutation.addedNodes[0],
1028
+ mutation.target,
1029
+ mutation.previousSibling,
1030
+ mutation.nextSibling
1031
+ ]
1032
+ )
1033
+ }
1034
+ var hasPublishedRemoval = false
1035
+ for (
1036
+ var publishedRemovalIndex = 0;
1037
+ publishedRemovalIndex < mutation.removedNodes.length;
1038
+ publishedRemovalIndex += 1
1039
+ ) {
1040
+ if (
1041
+ consumeMutationNormalizationBudget(
1042
+ normalizationState,
1043
+ mutationTasksController
1044
+ )
1045
+ ) {
1046
+ return createChildListNormalizationOverflowResult()
1047
+ }
1048
+ if (
1049
+ isNodePublished(mutation.removedNodes[publishedRemovalIndex]) ||
1050
+ replacementNodes.has(mutation.removedNodes[publishedRemovalIndex])
1051
+ ) {
1052
+ hasPublishedRemoval = true
1053
+ break
1054
+ }
1055
+ }
1056
+ var structuralState = mutation.$rStructuralState
1057
+ if (structuralState && hasPublishedRemoval) {
1058
+ structuralState.$rHasPublishedRemoval = true
1059
+ }
1060
+ for (
1061
+ var addedIndex = 0;
1062
+ addedIndex < mutation.addedNodes.length;
1063
+ addedIndex += 1
1064
+ ) {
1065
+ if (
1066
+ consumeMutationNormalizationBudget(
1067
+ normalizationState,
1068
+ mutationTasksController
1069
+ )
1070
+ ) {
1071
+ return createChildListNormalizationOverflowResult()
1072
+ }
1073
+ var addedNode = mutation.addedNodes[addedIndex]
1074
+ addedAndMovedNodes.add(addedNode)
1075
+ if (
1076
+ hasPublishedRemoval ||
1077
+ (structuralState && structuralState.$rHasPublishedRemoval)
1078
+ ) {
1079
+ replacementNodes.add(addedNode)
1080
+ }
1081
+ }
1082
+ for (
1083
+ var removedIndex = 0;
1084
+ removedIndex < mutation.removedNodes.length;
1085
+ removedIndex += 1
1086
+ ) {
1087
+ if (
1088
+ consumeMutationNormalizationBudget(
1089
+ normalizationState,
1090
+ mutationTasksController
1091
+ )
1092
+ ) {
1093
+ return createChildListNormalizationOverflowResult()
1094
+ }
1095
+ var removedNode = mutation.removedNodes[removedIndex]
1096
+ if (!addedAndMovedNodes.has(removedNode)) {
1097
+ removedNodes.set(removedNode, mutation.target)
1098
+ }
1099
+ addedAndMovedNodes.delete(removedNode)
1100
+ }
260
1101
  }
261
1102
 
262
- // Then, we sort nodes that are still in the document by topological order, for two reasons:
263
- //
1103
+ // A renderer can replace the same text/element again before the previous
1104
+ // asynchronous add is emitted. Keep the original published removal and
1105
+ // retarget its atomic add to the latest node. Treating the unpublished
1106
+ // intermediate node as a cancelled published move would unnecessarily
1107
+ // invalidate the whole replay while counters or framework text churn.
1108
+ var singleReplacementEntries = Array.from(singleReplacementNodes)
1109
+ for (
1110
+ var replacementIndex = 0;
1111
+ replacementIndex < singleReplacementEntries.length;
1112
+ replacementIndex += 1
1113
+ ) {
1114
+ var replacementEntry = singleReplacementEntries[replacementIndex]
1115
+ var replacedNode = replacementEntry[0]
1116
+ var replacementNode = replacementEntry[1][0]
1117
+ var replacementParent = replacementEntry[1][1]
1118
+ var replacementDepth = 0
1119
+ while (
1120
+ !replacementNode.isConnected &&
1121
+ replacementDepth < singleReplacementNodes.size
1122
+ ) {
1123
+ if (
1124
+ consumeMutationNormalizationBudget(
1125
+ normalizationState,
1126
+ mutationTasksController
1127
+ )
1128
+ ) {
1129
+ return createChildListNormalizationOverflowResult()
1130
+ }
1131
+ var intermediateReplacementOwner =
1132
+ mutationTasksController.findPendingRootTask(replacementNode)
1133
+ if (
1134
+ isNodePublished(replacementNode) ||
1135
+ (intermediateReplacementOwner &&
1136
+ intermediateReplacementOwner.rootNode === replacementNode)
1137
+ ) {
1138
+ mutationTasksController.handleOverflow({
1139
+ reason: 'published_move_cancelled'
1140
+ })
1141
+ return createChildListNormalizationOverflowResult()
1142
+ }
1143
+ var nextReplacement = singleReplacementNodes.get(replacementNode)
1144
+ if (!nextReplacement || nextReplacement[1] !== replacementParent) {
1145
+ break
1146
+ }
1147
+ replacementNode = nextReplacement[0]
1148
+ replacementDepth += 1
1149
+ }
1150
+ var queuedReplacementSourceNode = replacementNode
1151
+ var replacementTask = mutationTasksController.findPendingRootTask(
1152
+ replacedNode,
1153
+ replacementParent
1154
+ )
1155
+ var replacementOwner = mutationTasksController.findPendingRootTask(
1156
+ replacementNode
1157
+ )
1158
+ var coalescedDetachedTextReplacement = false
1159
+ // A hot textContent loop can detach the text node stored by an older
1160
+ // normalization chunk before that chunk runs. Resolve only the exact live
1161
+ // node occupying the MutationRecord's sibling slot. This is O(1), and all
1162
+ // element moves, cross-parent moves, published intermediates, ambiguous
1163
+ // slots and task-owner conflicts keep the existing fail-closed path.
1164
+ if (
1165
+ !replacementNode.isConnected &&
1166
+ replacedNode.nodeType === 3 &&
1167
+ replacementNode.nodeType === 3 &&
1168
+ !isNodePublished(replacementNode) &&
1169
+ !replacementOwner &&
1170
+ isNodePublished(replacementParent) &&
1171
+ (isNodePublished(replacedNode) ||
1172
+ (replacementTask &&
1173
+ replacementTask.rootNode === replacedNode &&
1174
+ replacementTask.requiresBaselineOnDrop))
1175
+ ) {
1176
+ var currentSlotNode = findCurrentTextNodeAtReplacementSlot(
1177
+ replacementParent,
1178
+ replacementEntry[1][2],
1179
+ replacementEntry[1][3]
1180
+ )
1181
+ var currentSlotOwner = currentSlotNode
1182
+ ? mutationTasksController.findPendingRootTask(currentSlotNode)
1183
+ : undefined
1184
+ if (
1185
+ currentSlotNode &&
1186
+ !isNodePublished(currentSlotNode) &&
1187
+ !currentSlotOwner
1188
+ ) {
1189
+ replacementNode = currentSlotNode
1190
+ coalescedDetachedTextReplacement = true
1191
+ }
1192
+ }
1193
+ if (coalescedDetachedTextReplacement) {
1194
+ if (addedAndMovedNodes.delete(queuedReplacementSourceNode)) {
1195
+ addedAndMovedNodes.add(replacementNode)
1196
+ }
1197
+ if (replacementNodes.delete(queuedReplacementSourceNode)) {
1198
+ replacementNodes.add(replacementNode)
1199
+ }
1200
+ if (coalescedTextReplacementByRemovedNode) {
1201
+ coalescedTextReplacementByRemovedNode.set(
1202
+ queuedReplacementSourceNode,
1203
+ [replacementParent, replacementNode]
1204
+ )
1205
+ }
1206
+ }
1207
+ if (
1208
+ replacementTask &&
1209
+ replacementTask.rootNode === replacedNode &&
1210
+ !replacementOwner &&
1211
+ !isNodePublished(replacementNode) &&
1212
+ !replacedNode.isConnected &&
1213
+ replacementNode.isConnected &&
1214
+ getParentNode(replacementNode) === replacementParent
1215
+ ) {
1216
+ if (
1217
+ !mutationTasksController.$rRetargetPendingRootTask(
1218
+ replacementTask,
1219
+ replacementNode
1220
+ )
1221
+ ) {
1222
+ return createChildListNormalizationOverflowResult()
1223
+ }
1224
+ removedNodes.delete(replacedNode)
1225
+ addedAndMovedNodes.delete(replacementNode)
1226
+ }
1227
+ }
1228
+
1229
+ var publishedMoveDependencyRoots = new Set()
1230
+ var sharedDependencyState = getMutationDependencyState(
1231
+ shadowRootsController
1232
+ )
1233
+ var removedNodesForDependency = Array.from(removedNodes.keys())
1234
+ for (
1235
+ var dependencyIndex = 0;
1236
+ dependencyIndex < removedNodesForDependency.length;
1237
+ dependencyIndex += 1
1238
+ ) {
1239
+ var publishedRemovedNode = removedNodesForDependency[dependencyIndex]
1240
+ if (!isNodePublished(publishedRemovedNode)) {
1241
+ continue
1242
+ }
1243
+ var currentDependencyNode = publishedRemovedNode
1244
+ var dependencyDepth = 0
1245
+ while (
1246
+ currentDependencyNode &&
1247
+ dependencyDepth < MAX_SERIALIZED_NODE_ANCESTOR_DEPTH
1248
+ ) {
1249
+ if (
1250
+ consumeMutationNormalizationBudget(
1251
+ normalizationState,
1252
+ mutationTasksController
1253
+ )
1254
+ ) {
1255
+ return createChildListNormalizationOverflowResult()
1256
+ }
1257
+ if (sharedDependencyState) {
1258
+ sharedDependencyState.$rPublishedRoots.add(
1259
+ currentDependencyNode
1260
+ )
1261
+ if (
1262
+ sharedDependencyState.$rLocallyDroppedRoots.has(
1263
+ currentDependencyNode
1264
+ )
1265
+ ) {
1266
+ mutationTasksController.handleOverflow({
1267
+ reason: 'published_move_serialization_watermark'
1268
+ })
1269
+ return createChildListNormalizationOverflowResult()
1270
+ }
1271
+ }
1272
+ if (addedAndMovedNodes.has(currentDependencyNode)) {
1273
+ publishedMoveDependencyRoots.add(currentDependencyNode)
1274
+ break
1275
+ }
1276
+ currentDependencyNode = getParentNode(currentDependencyNode)
1277
+ dependencyDepth += 1
1278
+ }
1279
+ }
1280
+
1281
+ // Then, we sort nodes that are still in the document by topological order, for two reasons:
1282
+ //
264
1283
  // * We will serialize each added nodes with their descendants. We don't want to serialize a node
265
1284
  // twice, so we need to iterate over the parent nodes first and skip any node that is contained in
266
1285
  // a precedent node.
@@ -270,7 +1289,14 @@ function processChildListMutations(
270
1289
  // siblings, we want to iterate from last to first. This will ensure that any "next" node is
271
1290
  // already serialized and have an id.
272
1291
  var sortedAddedAndMovedNodes = Array.from(addedAndMovedNodes)
273
- sortAddedAndMovedNodes(sortedAddedAndMovedNodes)
1292
+ if (!sortAddedAndMovedNodes(sortedAddedAndMovedNodes, normalizationState)) {
1293
+ // Sorting can dominate the observer callback for a wide mutation batch.
1294
+ // The batch is still unpublished here. Retire its complete serializer
1295
+ // generation and require a replacement baseline rather than publishing a
1296
+ // partially ordered prefix.
1297
+ abortMutationNormalization(normalizationState, mutationTasksController)
1298
+ return createChildListNormalizationOverflowResult()
1299
+ }
274
1300
 
275
1301
  // Then, we iterate over our sorted node sets to emit mutations. We collect the newly serialized
276
1302
  // node ids in a set to be able to skip subsequent related mutations.
@@ -281,9 +1307,22 @@ function processChildListMutations(
281
1307
  _a < sortedAddedAndMovedNodes_1.length;
282
1308
  _a++
283
1309
  ) {
1310
+ if (
1311
+ consumeMutationNormalizationBudget(
1312
+ normalizationState,
1313
+ mutationTasksController
1314
+ )
1315
+ ) {
1316
+ return createChildListNormalizationOverflowResult()
1317
+ }
284
1318
  var node = sortedAddedAndMovedNodes_1[_a]
285
1319
  var pendingRootTask = mutationTasksController.findPendingRootTask(node)
286
1320
  if (pendingRootTask) {
1321
+ if (isNodePublished(node)) {
1322
+ mutationTasksController.markPendingRootTaskPublishedDependency(
1323
+ pendingRootTask
1324
+ )
1325
+ }
287
1326
  pendingRootTasksToRefresh.add(pendingRootTask)
288
1327
  continue
289
1328
  }
@@ -304,32 +1343,109 @@ function processChildListMutations(
304
1343
  continue
305
1344
  }
306
1345
 
307
- mutationTasksController.addPendingRootTask(node, {
308
- serializedNodeIds: serializedNodeIds,
309
- parentNodePrivacyLevel: parentNodePrivacyLevel,
310
- serializationContext: {
311
- status: SerializationContextStatus.MUTATION,
312
- shadowRootsController: shadowRootsController
313
- },
314
- configuration
315
- })
1346
+ if (
1347
+ !mutationTasksController.addPendingRootTask(node, {
1348
+ serializedNodeIds: serializedNodeIds,
1349
+ parentNodePrivacyLevel: parentNodePrivacyLevel,
1350
+ serializationContext: {
1351
+ status: SerializationContextStatus.MUTATION,
1352
+ shadowRootsController: shadowRootsController
1353
+ },
1354
+ configuration,
1355
+ normalizationState: normalizationState,
1356
+ // A task paired with a published removal is part of one atomic
1357
+ // replacement. If its add cannot be serialized, emitting only the
1358
+ // removal would leave a permanent hole in the replay tree.
1359
+ requiresBaselineOnDrop:
1360
+ isNodePublished(node) ||
1361
+ replacementNodes.has(node) ||
1362
+ publishedMoveDependencyRoots.has(node) ||
1363
+ (sharedDependencyState &&
1364
+ sharedDependencyState.$rPublishedRoots.has(node)),
1365
+ mutationGroup: mutationGroup
1366
+ })
1367
+ ) {
1368
+ return {
1369
+ removes: [],
1370
+ serializedNodeIds: serializedNodeIds,
1371
+ overflowed: true
1372
+ }
1373
+ }
316
1374
  }
317
1375
  // Finally, we emit remove mutations.
318
1376
  var removedNodeMutations = []
319
- removedNodes.forEach(function (parent, node) {
320
- var pendingRootTask = mutationTasksController.findPendingRootTask(node)
1377
+ var pendingRootRemovalOverflowed = false
1378
+ var removedNodeEntries = Array.from(removedNodes)
1379
+ for (
1380
+ var removedEntryIndex = 0;
1381
+ removedEntryIndex < removedNodeEntries.length;
1382
+ removedEntryIndex += 1
1383
+ ) {
1384
+ if (pendingRootRemovalOverflowed) {
1385
+ break
1386
+ }
1387
+ if (
1388
+ consumeMutationNormalizationBudget(
1389
+ normalizationState,
1390
+ mutationTasksController
1391
+ )
1392
+ ) {
1393
+ return createChildListNormalizationOverflowResult()
1394
+ }
1395
+ var removedNodeEntry = removedNodeEntries[removedEntryIndex]
1396
+ var node = removedNodeEntry[0]
1397
+ var parent = removedNodeEntry[1]
1398
+ // A removed descendant is already detached when the MutationRecord is
1399
+ // processed, so walking from it can no longer reach an unpublished
1400
+ // pending root. The mutation target is its former parent and still gives
1401
+ // us the path needed to refresh that root instead of publishing a stale
1402
+ // subtree followed by an ineffective remove.
1403
+ var pendingRootTask = mutationTasksController.findPendingRootTask(
1404
+ node,
1405
+ parent
1406
+ )
321
1407
  if (pendingRootTask) {
1408
+ if (isNodePublished(node)) {
1409
+ mutationTasksController.markPendingRootTaskPublishedDependency(
1410
+ pendingRootTask
1411
+ )
1412
+ }
1413
+ if (
1414
+ node !== pendingRootTask.rootNode &&
1415
+ pendingRootTask.rootNode.isConnected
1416
+ ) {
1417
+ // Several descendants can be removed in one batch. Rebuild the
1418
+ // unpublished root once after normalization instead of once per node.
1419
+ pendingRootTasksToRefresh.add(pendingRootTask)
1420
+ continue
1421
+ }
322
1422
  pendingRootTasksToRefresh.delete(pendingRootTask)
323
- mutationTasksController.handlePendingRootRemoval(pendingRootTask, node)
324
- return
1423
+ if (
1424
+ !mutationTasksController.handlePendingRootRemoval(
1425
+ pendingRootTask,
1426
+ node
1427
+ )
1428
+ ) {
1429
+ pendingRootRemovalOverflowed = true
1430
+ }
1431
+ continue
325
1432
  }
326
- if (hasSerializedNode(node)) {
327
- removedNodeMutations.push({
1433
+ if (hasSerializedNode(node) && isNodePublished(node)) {
1434
+ var removeMutation = {
328
1435
  parentId: getSerializedNodeId(parent),
329
1436
  id: getSerializedNodeId(node)
330
- })
1437
+ }
1438
+ sourceNodeByMutationRemove.set(removeMutation, node)
1439
+ removedNodeMutations.push(removeMutation)
331
1440
  }
332
- })
1441
+ }
1442
+ if (pendingRootRemovalOverflowed) {
1443
+ return {
1444
+ removes: [],
1445
+ serializedNodeIds: serializedNodeIds,
1446
+ overflowed: true
1447
+ }
1448
+ }
333
1449
 
334
1450
  return {
335
1451
  removes: removedNodeMutations,
@@ -345,16 +1461,69 @@ function processChildListMutations(
345
1461
  }
346
1462
  }
347
1463
 
1464
+ function findCurrentTextNodeAtReplacementSlot(
1465
+ parent,
1466
+ previousSibling,
1467
+ nextSibling
1468
+ ) {
1469
+ // `undefined` means the synthetic record did not preserve native slot
1470
+ // evidence. Never infer a replacement from the current DOM in that case.
1471
+ if (previousSibling === undefined || nextSibling === undefined) {
1472
+ return
1473
+ }
1474
+ if (
1475
+ (previousSibling &&
1476
+ getParentNode(previousSibling) !== parent) ||
1477
+ (nextSibling &&
1478
+ getParentNode(nextSibling) !== parent)
1479
+ ) {
1480
+ return
1481
+ }
1482
+ var candidate = previousSibling
1483
+ ? previousSibling.nextSibling
1484
+ : parent.firstChild
1485
+ if (
1486
+ !candidate ||
1487
+ candidate === nextSibling ||
1488
+ candidate.nextSibling !== nextSibling ||
1489
+ !candidate.isConnected ||
1490
+ candidate.nodeType !== 3
1491
+ ) {
1492
+ return
1493
+ }
1494
+ return candidate
1495
+ }
1496
+
1497
+ function createChildListNormalizationOverflowResult() {
1498
+ return {
1499
+ removes: [],
1500
+ serializedNodeIds: new Set(),
1501
+ overflowed: true
1502
+ }
1503
+ }
1504
+
348
1505
  function processCharacterDataMutations(
349
1506
  mutations,
350
1507
  configuration,
351
- nodePrivacyLevelCache
1508
+ nodePrivacyLevelCache,
1509
+ mutationTasksController,
1510
+ normalizationState,
1511
+ currentSourceState,
1512
+ handledNodes
352
1513
  ) {
353
1514
  var textMutations = []
354
1515
 
355
1516
  // Deduplicate mutations based on their target node
356
- var handledNodes = new Set()
1517
+ handledNodes = handledNodes || new Set()
357
1518
  var filteredMutations = mutations.filter(function (mutation) {
1519
+ if (
1520
+ consumeMutationNormalizationBudget(
1521
+ normalizationState,
1522
+ mutationTasksController
1523
+ )
1524
+ ) {
1525
+ return false
1526
+ }
358
1527
  if (handledNodes.has(mutation.target)) {
359
1528
  return false
360
1529
  }
@@ -368,6 +1537,14 @@ function processCharacterDataMutations(
368
1537
  _i < filteredMutations_1.length;
369
1538
  _i++
370
1539
  ) {
1540
+ if (
1541
+ consumeMutationNormalizationBudget(
1542
+ normalizationState,
1543
+ mutationTasksController
1544
+ )
1545
+ ) {
1546
+ return textMutations
1547
+ }
371
1548
  var mutation = filteredMutations_1[_i]
372
1549
  var value = mutation.target.textContent
373
1550
  if (value === mutation.oldValue) {
@@ -386,9 +1563,8 @@ function processCharacterDataMutations(
386
1563
  continue
387
1564
  }
388
1565
 
389
- textMutations.push({
390
- id: getSerializedNodeId(mutation.target),
391
- value: isNullUndefinedDefaultValue(
1566
+ var serializedTextValue = truncateSerializedValue(
1567
+ isNullUndefinedDefaultValue(
392
1568
  getTextContent(
393
1569
  configuration,
394
1570
  mutation.target,
@@ -396,7 +1572,24 @@ function processCharacterDataMutations(
396
1572
  parentNodePrivacyLevel,
397
1573
  null
398
1574
  )
1575
+ ),
1576
+ MAX_MUTATION_SERIALIZED_VALUE_CHARACTERS
1577
+ )
1578
+ if (
1579
+ !reserveCurrentMutationSource(
1580
+ serializedTextValue,
1581
+ currentSourceState
399
1582
  )
1583
+ ) {
1584
+ mutationTasksController.handleOverflow({
1585
+ reason: 'mutation_current_source_watermark',
1586
+ mutationApproxBytes: currentSourceState.characters * 2
1587
+ })
1588
+ return []
1589
+ }
1590
+ textMutations.push({
1591
+ id: getSerializedNodeId(mutation.target),
1592
+ value: serializedTextValue
400
1593
  })
401
1594
  }
402
1595
 
@@ -406,13 +1599,25 @@ function processCharacterDataMutations(
406
1599
  function processAttributesMutations(
407
1600
  mutations,
408
1601
  configuration,
409
- nodePrivacyLevelCache
1602
+ nodePrivacyLevelCache,
1603
+ mutationTasksController,
1604
+ normalizationState,
1605
+ currentSourceState,
1606
+ handledElements
410
1607
  ) {
411
1608
  var attributeMutations = []
412
1609
 
413
1610
  // Deduplicate mutations based on their target node and changed attribute
414
- var handledElements = new Map()
1611
+ handledElements = handledElements || new Map()
415
1612
  var filteredMutations = mutations.filter(function (mutation) {
1613
+ if (
1614
+ consumeMutationNormalizationBudget(
1615
+ normalizationState,
1616
+ mutationTasksController
1617
+ )
1618
+ ) {
1619
+ return false
1620
+ }
416
1621
  var handledAttributes = handledElements.get(mutation.target)
417
1622
  if (handledAttributes && handledAttributes.has(mutation.attributeName)) {
418
1623
  return false
@@ -432,6 +1637,14 @@ function processAttributesMutations(
432
1637
  _i < filteredMutations_2.length;
433
1638
  _i++
434
1639
  ) {
1640
+ if (
1641
+ consumeMutationNormalizationBudget(
1642
+ normalizationState,
1643
+ mutationTasksController
1644
+ )
1645
+ ) {
1646
+ return attributeMutations
1647
+ }
435
1648
  var mutation = filteredMutations_2[_i]
436
1649
  var uncensoredValue = mutation.target.getAttribute(mutation.attributeName)
437
1650
  if (uncensoredValue === mutation.oldValue) {
@@ -465,6 +1678,22 @@ function processAttributesMutations(
465
1678
  } else {
466
1679
  transformedValue = null
467
1680
  }
1681
+ transformedValue = truncateSerializedValue(
1682
+ transformedValue,
1683
+ MAX_MUTATION_SERIALIZED_VALUE_CHARACTERS
1684
+ )
1685
+ if (
1686
+ !reserveCurrentMutationSource(
1687
+ transformedValue,
1688
+ currentSourceState
1689
+ )
1690
+ ) {
1691
+ mutationTasksController.handleOverflow({
1692
+ reason: 'mutation_current_source_watermark',
1693
+ mutationApproxBytes: currentSourceState.characters * 2
1694
+ })
1695
+ return []
1696
+ }
468
1697
 
469
1698
  var emittedMutation = emittedMutations.get(mutation.target)
470
1699
  if (!emittedMutation) {
@@ -482,238 +1711,1301 @@ function processAttributesMutations(
482
1711
  return attributeMutations
483
1712
  }
484
1713
 
485
- export function sortAddedAndMovedNodes(nodes) {
486
- nodes.sort(function (a, b) {
487
- var position = a.compareDocumentPosition(b)
488
- /* eslint-disable no-bitwise */
489
- if (position & Node.DOCUMENT_POSITION_CONTAINED_BY) {
490
- return -1
491
- } else if (position & Node.DOCUMENT_POSITION_CONTAINS) {
492
- return 1
493
- } else if (position & Node.DOCUMENT_POSITION_FOLLOWING) {
494
- return 1
495
- } else if (position & Node.DOCUMENT_POSITION_PRECEDING) {
496
- return -1
497
- }
498
- /* eslint-enable no-bitwise */
499
- return 0
1714
+ function reserveCurrentMutationSource(
1715
+ value,
1716
+ currentSourceState
1717
+ ) {
1718
+ if (typeof value !== 'string') {
1719
+ return true
1720
+ }
1721
+ currentSourceState.characters += value.length
1722
+ return (
1723
+ currentSourceState.characters <=
1724
+ MAX_MUTATION_CURRENT_SOURCE_CHARACTERS
1725
+ )
1726
+ }
1727
+
1728
+ export function sortAddedAndMovedNodes(nodes, normalizationState) {
1729
+ try {
1730
+ nodes.sort(function (a, b) {
1731
+ if (
1732
+ normalizationState &&
1733
+ consumeMutationNormalizationBudget(
1734
+ normalizationState,
1735
+ normalizationState.mutationTasksController
1736
+ )
1737
+ ) {
1738
+ throw MUTATION_NORMALIZATION_ABORT
1739
+ }
1740
+ var position = a.compareDocumentPosition(b)
1741
+ /* eslint-disable no-bitwise */
1742
+ if (position & Node.DOCUMENT_POSITION_CONTAINED_BY) {
1743
+ return -1
1744
+ } else if (position & Node.DOCUMENT_POSITION_CONTAINS) {
1745
+ return 1
1746
+ } else if (position & Node.DOCUMENT_POSITION_FOLLOWING) {
1747
+ return 1
1748
+ } else if (position & Node.DOCUMENT_POSITION_PRECEDING) {
1749
+ return -1
1750
+ }
1751
+ /* eslint-enable no-bitwise */
1752
+ return 0
1753
+ })
1754
+ } catch (error) {
1755
+ if (error === MUTATION_NORMALIZATION_ABORT) {
1756
+ return false
1757
+ }
1758
+ throw error
1759
+ }
1760
+ return !(
1761
+ normalizationState &&
1762
+ consumeMutationNormalizationBudget(
1763
+ normalizationState,
1764
+ normalizationState.mutationTasksController,
1765
+ true
1766
+ )
1767
+ )
1768
+ }
1769
+
1770
+ function consumeMutationNormalizationBudget(
1771
+ normalizationState,
1772
+ mutationTasksController,
1773
+ forceTimeCheck
1774
+ ) {
1775
+ if (normalizationState.exhausted) {
1776
+ return true
1777
+ }
1778
+ normalizationState.timeCheckCount += 1
1779
+ if (
1780
+ !forceTimeCheck &&
1781
+ normalizationState.timeCheckCount %
1782
+ MUTATION_NORMALIZATION_TIME_CHECK_INTERVAL !==
1783
+ 0
1784
+ ) {
1785
+ return false
1786
+ }
1787
+ if (
1788
+ normalizationState.mutationRecordCount <=
1789
+ MUTATION_NORMALIZATION_SMALL_BATCH_MAX_RECORDS &&
1790
+ normalizationState.timeCheckCount <
1791
+ MUTATION_NORMALIZATION_MIN_OPERATIONS_BEFORE_TIMEOUT
1792
+ ) {
1793
+ return false
1794
+ }
1795
+ if (getCurrentTime() < normalizationState.deadline) {
1796
+ return false
1797
+ }
1798
+ abortMutationNormalization(
1799
+ normalizationState,
1800
+ mutationTasksController
1801
+ )
1802
+ return true
1803
+ }
1804
+
1805
+ function abortMutationNormalization(
1806
+ normalizationState,
1807
+ mutationTasksController
1808
+ ) {
1809
+ if (normalizationState.exhausted) {
1810
+ return
1811
+ }
1812
+ normalizationState.exhausted = true
1813
+ mutationTasksController.handleOverflow({
1814
+ reason: 'mutation_normalization_budget',
1815
+ mutationRecordCount: normalizationState.mutationRecordCount
500
1816
  })
501
1817
  }
502
1818
 
503
- function createMutationTasksController(
1819
+ export function createMutationTasksController(
504
1820
  mutationCallback,
505
1821
  configuration,
506
- shadowRootsController
1822
+ shadowRootsController,
1823
+ mutationPerfCb,
1824
+ mutationOverflowCb,
1825
+ mutationNodeSerializationCb,
1826
+ isNodeIgnored,
1827
+ mutationResourceBudget
507
1828
  ) {
1829
+ isNodeIgnored = isNodeIgnored || function () {
1830
+ return false
1831
+ }
508
1832
  var generation = 0
509
1833
  var nextTaskSequence = 0
510
1834
  var nextEmitSequence = 0
1835
+ var pendingMutationGroups = []
1836
+ var pendingMutationGroupHead = 0
511
1837
  var pendingRootTasks = []
1838
+ var pendingRootTaskHead = 0
1839
+ var pendingRootTaskContinuation
1840
+ var pendingRootTaskCount = 0
1841
+ var activeRootTaskCount = 0
1842
+ var deferredRootTaskCount = 0
1843
+ var deferredRootTaskOutstandingCount = 0
512
1844
  var pendingRootTaskByRootNode = new WeakMap()
513
1845
  var pendingRootTaskBySequence = new Map()
514
1846
  var scheduledFlush = undefined
515
- var scheduledEmit = undefined
516
1847
  var stopped = false
517
- var completedRootTasks = []
1848
+ var overflowed = false
1849
+ var overflowCount = 0
1850
+ var retainedRootTaskApproxBytes = 0
1851
+ var retainedMutationGroupApproxBytes = 0
1852
+ var retainedMutationBudgetReservation
1853
+ var completedRootTasksBySequence = new Map()
1854
+ var locallyDroppedRootNodes = new WeakSet()
518
1855
 
519
1856
  return {
1857
+ createMutationGroup: createMutationGroup,
1858
+ completeMutationGroup: completeMutationGroup,
1859
+ cancelMutationGroup: cancelMutationGroup,
520
1860
  addPendingRootTask: addPendingRootTask,
521
1861
  findPendingRootTask: findPendingRootTask,
1862
+ markPendingRootTaskPublishedDependency:
1863
+ markPendingRootTaskPublishedDependency,
1864
+ refreshAndFlushPendingRootForNode:
1865
+ refreshAndFlushPendingRootForNode,
522
1866
  refreshPendingRootTask: refreshPendingRootTask,
1867
+ $rRetargetPendingRootTask: retargetPendingRootTask,
523
1868
  handlePendingRootRemoval: handlePendingRootRemoval,
524
- flush: function () {
525
- processPendingRootTasks(true)
1869
+ dropMutationGroupTasks: dropMutationGroupTasks,
1870
+ handleOverflow: handleOverflow,
1871
+ getOverflowCount: function () {
1872
+ return overflowCount
526
1873
  },
527
- reset: function () {
528
- generation += 1
529
- nextTaskSequence = 0
530
- nextEmitSequence = 0
531
- clearScheduledFlush()
532
- clearScheduledEmit()
533
- pendingRootTasks = []
534
- completedRootTasks = []
535
- pendingRootTaskByRootNode = new WeakMap()
536
- pendingRootTaskBySequence = new Map()
1874
+ isOverflowed: function () {
1875
+ return overflowed
1876
+ },
1877
+ flush: function () {
1878
+ if (overflowed) {
1879
+ return false
1880
+ }
1881
+ var flushResult = processPendingRootTasks(
1882
+ getCurrentTime() + MUTATION_SERIALIZATION_FLUSH_BUDGET_MS,
1883
+ true
1884
+ )
1885
+ if (flushResult === false && deferredRootTaskOutstandingCount) {
1886
+ return 'pending'
1887
+ }
1888
+ return flushResult
537
1889
  },
1890
+ reset: reset,
538
1891
  stop: function () {
539
1892
  stopped = true
540
- clearScheduledFlush()
541
- clearScheduledEmit()
542
- pendingRootTasks = []
543
- completedRootTasks = []
544
- pendingRootTaskByRootNode = new WeakMap()
545
- pendingRootTaskBySequence = new Map()
1893
+ overflowed = false
1894
+ clearMutationTaskState()
546
1895
  }
547
1896
  }
548
1897
 
549
- function addPendingRootTask(node, serializationOptions) {
550
- if (findPendingRootTask(getParentNode(node))) {
551
- return
552
- }
553
- var serializerTask = createMutationSerializerTask(node, serializationOptions)
554
- if (!serializerTask) {
555
- return
556
- }
557
- var task = {
558
- generation: generation,
559
- sequence: nextTaskSequence++,
560
- rootNode: node,
561
- parentId: getSerializedNodeId(getParentNode(node)),
562
- nextId: getNextSibling(node),
563
- serializerTask: serializerTask
1898
+ function clearMutationTaskState() {
1899
+ pendingRootTaskBySequence.forEach(function (task) {
1900
+ cancelPublicationToken(task.publicationToken)
1901
+ })
1902
+ for (
1903
+ var groupIndex = pendingMutationGroupHead;
1904
+ groupIndex < pendingMutationGroups.length;
1905
+ groupIndex += 1
1906
+ ) {
1907
+ cancelMutationGroupPublicationTokens(
1908
+ pendingMutationGroups[groupIndex]
1909
+ )
564
1910
  }
565
- pendingRootTasks.push(task)
566
- pendingRootTaskByRootNode.set(node, task)
567
- pendingRootTaskBySequence.set(task.sequence, task)
568
- schedulePendingRootTasks()
1911
+ generation += 1
1912
+ nextTaskSequence = 0
1913
+ nextEmitSequence = 0
1914
+ pendingMutationGroups = []
1915
+ pendingMutationGroupHead = 0
1916
+ clearScheduledFlush()
1917
+ pendingRootTasks = []
1918
+ pendingRootTaskHead = 0
1919
+ pendingRootTaskContinuation = undefined
1920
+ pendingRootTaskCount = 0
1921
+ activeRootTaskCount = 0
1922
+ deferredRootTaskCount = 0
1923
+ deferredRootTaskOutstandingCount = 0
1924
+ retainedRootTaskApproxBytes = 0
1925
+ retainedMutationGroupApproxBytes = 0
1926
+ updateRetainedMutationResourceBudget()
1927
+ completedRootTasksBySequence = new Map()
1928
+ locallyDroppedRootNodes = new WeakSet()
1929
+ pendingRootTaskByRootNode = new WeakMap()
1930
+ pendingRootTaskBySequence = new Map()
569
1931
  }
570
1932
 
571
- function findPendingRootTask(node) {
572
- var current = node
573
- while (current) {
574
- var task = pendingRootTaskByRootNode.get(current)
575
- if (task && task.generation === generation) {
576
- return task
577
- }
578
- current = getParentNode(current)
579
- }
1933
+ function reset() {
1934
+ overflowed = false
1935
+ clearMutationTaskState()
580
1936
  }
581
1937
 
582
- function refreshPendingRootTask(task) {
583
- if (!task || task.generation !== generation) {
584
- return
585
- }
586
- if (!task.rootNode.isConnected) {
587
- cancelPendingRootTask(task)
588
- return
589
- }
590
-
591
- var parentNode = getParentNode(task.rootNode)
592
- var parentPendingRootTask = findPendingRootTask(parentNode)
593
- if (parentPendingRootTask && parentPendingRootTask !== task) {
594
- cancelPendingRootTask(task)
1938
+ function createMutationGroup(callback) {
1939
+ if (stopped || overflowed) {
595
1940
  return
596
1941
  }
597
- var parentNodePrivacyLevel = getNodePrivacyLevel(
598
- parentNode,
599
- configuration.defaultPrivacyLevel
600
- )
601
1942
  if (
602
- parentNodePrivacyLevel === NodePrivacyLevel.HIDDEN ||
603
- parentNodePrivacyLevel === NodePrivacyLevel.IGNORE
1943
+ pendingMutationGroups.length - pendingMutationGroupHead >=
1944
+ MAX_PENDING_MUTATION_GROUPS ||
1945
+ getRetainedMutationApproxBytes() + 64 >
1946
+ MAX_PENDING_MUTATION_ROOT_APPROX_BYTES
604
1947
  ) {
605
- cancelPendingRootTask(task)
1948
+ handleOverflow({
1949
+ reason: 'mutation_group_watermark',
1950
+ mutationRecordCount:
1951
+ pendingMutationGroups.length -
1952
+ pendingMutationGroupHead +
1953
+ 1,
1954
+ mutationApproxBytes: getRetainedMutationApproxBytes() + 64
1955
+ })
606
1956
  return
607
1957
  }
608
-
609
- var serializerTask = createMutationSerializerTask(task.rootNode, {
610
- parentNodePrivacyLevel: parentNodePrivacyLevel,
611
- serializationContext: {
612
- status: SerializationContextStatus.MUTATION,
613
- shadowRootsController: shadowRootsController
1958
+ var mutationGroup = {
1959
+ active: true,
1960
+ generation: generation,
1961
+ sequence: nextTaskSequence,
1962
+ callback: callback || mutationCallback,
1963
+ payload: {
1964
+ adds: [],
1965
+ removes: [],
1966
+ texts: [],
1967
+ attributes: []
614
1968
  },
615
- configuration: configuration
616
- })
617
- if (!serializerTask) {
618
- cancelPendingRootTask(task)
1969
+ approxBytes: 64,
1970
+ approxBytesReleased: false,
1971
+ pendingTaskCount: 0,
1972
+ closed: false,
1973
+ canceled: false
1974
+ }
1975
+ pendingMutationGroups.push(mutationGroup)
1976
+ retainedMutationGroupApproxBytes += mutationGroup.approxBytes
1977
+ if (!updateRetainedMutationResourceBudget()) {
1978
+ handleOverflow({
1979
+ reason: AGGREGATE_RETAINED_MUTATION_WATERMARK,
1980
+ mutationApproxBytes: getRetainedMutationApproxBytes()
1981
+ })
619
1982
  return
620
1983
  }
621
- removeCompletedRootTask(task)
622
- task.parentId = getSerializedNodeId(parentNode)
623
- task.nextId = getNextSibling(task.rootNode)
624
- task.serializerTask = serializerTask
625
- task.isCompleted = false
626
- schedulePendingRootTasks()
1984
+ return mutationGroup
627
1985
  }
628
1986
 
629
- function handlePendingRootRemoval(task, node) {
630
- if (!task || task.generation !== generation) {
1987
+ function completeMutationGroup(mutationGroup, payload) {
1988
+ if (
1989
+ !isActiveMutationGroup(mutationGroup) ||
1990
+ mutationGroup.canceled ||
1991
+ mutationGroup.closed
1992
+ ) {
631
1993
  return
632
1994
  }
633
- if (node === task.rootNode) {
634
- if (task.rootNode.isConnected) {
635
- refreshPendingRootTask(task)
636
- return
637
- }
638
- cancelPendingRootTask(task)
1995
+ var payloadApproxBytes =
1996
+ estimateMutationGroupPayloadApproxBytes(payload)
1997
+ if (
1998
+ getRetainedMutationApproxBytes() + payloadApproxBytes >
1999
+ MAX_PENDING_MUTATION_ROOT_APPROX_BYTES
2000
+ ) {
2001
+ handleOverflow({
2002
+ reason: 'mutation_group_byte_watermark',
2003
+ mutationApproxBytes:
2004
+ getRetainedMutationApproxBytes() + payloadApproxBytes
2005
+ })
2006
+ return false
2007
+ }
2008
+ mutationGroup.approxBytes += payloadApproxBytes
2009
+ retainedMutationGroupApproxBytes += payloadApproxBytes
2010
+ if (!updateRetainedMutationResourceBudget()) {
2011
+ return handleOverflow({
2012
+ reason: AGGREGATE_RETAINED_MUTATION_WATERMARK,
2013
+ mutationApproxBytes: getRetainedMutationApproxBytes()
2014
+ })
2015
+ }
2016
+ Array.prototype.push.apply(
2017
+ mutationGroup.payload.removes,
2018
+ payload.removes
2019
+ )
2020
+ Array.prototype.push.apply(
2021
+ mutationGroup.payload.texts,
2022
+ payload.texts
2023
+ )
2024
+ Array.prototype.push.apply(
2025
+ mutationGroup.payload.attributes,
2026
+ payload.attributes
2027
+ )
2028
+ mutationGroup.closed = true
2029
+ emitReadyMutationGroups()
2030
+ }
2031
+
2032
+ function cancelMutationGroup(mutationGroup) {
2033
+ if (!isActiveMutationGroup(mutationGroup)) {
639
2034
  return
640
2035
  }
2036
+ mutationGroup.canceled = true
2037
+ mutationGroup.closed = true
2038
+ cancelMutationGroupPublicationTokens(mutationGroup)
2039
+ releaseMutationGroupApproxBytes(mutationGroup)
2040
+ Array.from(pendingRootTaskBySequence.values()).forEach(function (task) {
2041
+ if (task.mutationGroup === mutationGroup) {
2042
+ cancelPendingRootTask(task)
2043
+ }
2044
+ })
2045
+ emitReadyMutationGroups()
2046
+ }
2047
+
2048
+ function cancelMutationGroupPublicationTokens(mutationGroup) {
2049
+ mutationGroup.payload.adds.forEach(function (add) {
2050
+ cancelPublicationToken(consumeMutationAddPublicationToken(add))
2051
+ })
2052
+ mutationGroup.payload.adds = []
2053
+ }
2054
+
2055
+ function isActiveMutationGroup(mutationGroup) {
2056
+ return Boolean(
2057
+ mutationGroup &&
2058
+ mutationGroup.active &&
2059
+ mutationGroup.generation === generation &&
2060
+ !stopped
2061
+ )
2062
+ }
2063
+
2064
+ function emitReadyMutationGroups() {
2065
+ while (pendingMutationGroupHead < pendingMutationGroups.length) {
2066
+ var mutationGroup =
2067
+ pendingMutationGroups[pendingMutationGroupHead]
2068
+ if (
2069
+ !mutationGroup ||
2070
+ !mutationGroup.closed ||
2071
+ mutationGroup.pendingTaskCount ||
2072
+ nextEmitSequence < mutationGroup.sequence
2073
+ ) {
2074
+ return
2075
+ }
2076
+ mutationGroup.active = false
2077
+ pendingMutationGroups[pendingMutationGroupHead] = undefined
2078
+ pendingMutationGroupHead += 1
2079
+ var mutationGroupApproxBytes = mutationGroup.approxBytes
2080
+ releaseMutationGroupApproxBytes(mutationGroup)
2081
+ if (
2082
+ !mutationGroup.canceled &&
2083
+ hasMutationGroupEntries(mutationGroup.payload)
2084
+ ) {
2085
+ approxBytesByMutationPayload.set(
2086
+ mutationGroup.payload,
2087
+ mutationGroupApproxBytes
2088
+ )
2089
+ mutationGroup.callback(mutationGroup.payload)
2090
+ }
2091
+ }
2092
+ pendingMutationGroups = []
2093
+ pendingMutationGroupHead = 0
2094
+ }
2095
+
2096
+ function hasMutationGroupEntries(payload) {
2097
+ return Boolean(
2098
+ payload.adds.length ||
2099
+ payload.removes.length ||
2100
+ payload.texts.length ||
2101
+ payload.attributes.length
2102
+ )
2103
+ }
2104
+
2105
+ function estimateMutationGroupPayloadApproxBytes(payload) {
2106
+ return estimateMutationPayloadEntriesApproxBytes(payload)
2107
+ }
2108
+
2109
+ function getRetainedMutationApproxBytes() {
2110
+ return (
2111
+ retainedRootTaskApproxBytes +
2112
+ retainedMutationGroupApproxBytes
2113
+ )
2114
+ }
2115
+
2116
+ function releaseMutationGroupApproxBytes(mutationGroup) {
2117
+ if (mutationGroup.approxBytesReleased) {
2118
+ return
2119
+ }
2120
+ mutationGroup.approxBytesReleased = true
2121
+ retainedMutationGroupApproxBytes = Math.max(
2122
+ retainedMutationGroupApproxBytes - mutationGroup.approxBytes,
2123
+ 0
2124
+ )
2125
+ updateRetainedMutationResourceBudget()
2126
+ }
2127
+
2128
+ function transferRetainedRootTaskToMutationGroup(
2129
+ task,
2130
+ mutationGroup
2131
+ ) {
2132
+ var taskApproxBytes = task.accountedApproxBytes
2133
+ task.isRetained = false
2134
+ retainedRootTaskApproxBytes = Math.max(
2135
+ retainedRootTaskApproxBytes - taskApproxBytes,
2136
+ 0
2137
+ )
2138
+ task.accountedApproxBytes = 0
2139
+ mutationGroup.approxBytes += taskApproxBytes
2140
+ retainedMutationGroupApproxBytes += taskApproxBytes
2141
+ releaseActiveRootTask(task)
2142
+ releaseDeferredRootTaskOutstanding(task)
2143
+ }
2144
+
2145
+ function releaseMutationGroupDependency(task) {
2146
+ if (
2147
+ task.mutationGroupDependencyReleased ||
2148
+ !task.mutationGroup
2149
+ ) {
2150
+ return
2151
+ }
2152
+ task.mutationGroupDependencyReleased = true
2153
+ if (isActiveMutationGroup(task.mutationGroup)) {
2154
+ task.mutationGroup.pendingTaskCount = Math.max(
2155
+ task.mutationGroup.pendingTaskCount - 1,
2156
+ 0
2157
+ )
2158
+ }
2159
+ }
2160
+
2161
+ function handleOverflow(overflow) {
2162
+ if (stopped || overflowed) {
2163
+ return false
2164
+ }
2165
+ overflowed = true
2166
+ overflowCount += 1
2167
+ var shouldReportOverflow =
2168
+ !mutationResourceBudget || mutationResourceBudget.failOnce()
2169
+ clearMutationTaskState()
2170
+ if (shouldReportOverflow && mutationOverflowCb) {
2171
+ mutationOverflowCb(overflow)
2172
+ }
2173
+ return false
2174
+ }
2175
+
2176
+ function addPendingRootTask(node, serializationOptions) {
2177
+ if (stopped || overflowed) {
2178
+ return false
2179
+ }
2180
+ var isNormalizationTransaction = Boolean(
2181
+ serializationOptions.normalizationState &&
2182
+ !serializationOptions.normalizationState.exhausted
2183
+ )
2184
+ var mustDeferNormalizationEmission = Boolean(
2185
+ isNormalizationTransaction && !serializationOptions.mutationGroup
2186
+ )
2187
+ var parentPendingRootTask = findPendingRootTask(getParentNode(node))
2188
+ if (parentPendingRootTask) {
2189
+ if (serializationOptions.requiresBaselineOnDrop) {
2190
+ markPendingRootTaskPublishedDependency(parentPendingRootTask)
2191
+ }
2192
+ return true
2193
+ }
2194
+ var canDefer = canDeferPendingRootTask(serializationOptions)
2195
+ if (
2196
+ deferredRootTaskCount &&
2197
+ canDefer
2198
+ ) {
2199
+ return deferPendingRootTask(node, serializationOptions)
2200
+ }
2201
+ if (deferredRootTaskCount) {
2202
+ // A non-deferred task cannot overtake an older deferred sequence: once
2203
+ // later active tasks fill the cap, neither side can publish. Drain the
2204
+ // older work within the normal slice before admitting the dependency.
2205
+ if (!drainPendingRootTasksForAdmission()) {
2206
+ return false
2207
+ }
2208
+ if (deferredRootTaskCount) {
2209
+ return handleOverflow({ reason: MUTATION_ROOT_ADMISSION_WATERMARK })
2210
+ }
2211
+ }
2212
+ if (
2213
+ activeRootTaskCount >=
2214
+ MAX_PENDING_MUTATION_ROOT_TASKS
2215
+ ) {
2216
+ if (
2217
+ !mustDeferNormalizationEmission &&
2218
+ !drainPendingRootTasksForAdmission()
2219
+ ) {
2220
+ return false
2221
+ }
2222
+ if (
2223
+ activeRootTaskCount >=
2224
+ MAX_PENDING_MUTATION_ROOT_TASKS
2225
+ ) {
2226
+ if (canDefer) {
2227
+ return deferPendingRootTask(node, serializationOptions)
2228
+ }
2229
+ return handleOverflow({
2230
+ reason: MUTATION_ROOT_ADMISSION_WATERMARK
2231
+ })
2232
+ }
2233
+ }
2234
+ var trackedSerializerTask = createTrackedMutationSerializerTask(
2235
+ node,
2236
+ serializationOptions
2237
+ )
2238
+ var serializerTask = trackedSerializerTask.serializerTask
2239
+ if (!serializerTask) {
2240
+ return dropUnadmittedRootNode(
2241
+ node,
2242
+ trackedSerializerTask.publicationToken,
2243
+ serializationOptions.requiresBaselineOnDrop,
2244
+ 'published_move_serialization_failed'
2245
+ )
2246
+ }
2247
+ if (serializerTask.isMaxNodeComplexityReached) {
2248
+ return dropUnadmittedRootNode(
2249
+ node,
2250
+ trackedSerializerTask.publicationToken,
2251
+ serializationOptions.requiresBaselineOnDrop,
2252
+ 'published_move_serialization_watermark'
2253
+ )
2254
+ }
2255
+ if (
2256
+ serializerTask.approxBytes >
2257
+ MUTATION_SERIALIZATION_MAX_APPROX_BYTES
2258
+ ) {
2259
+ return dropUnadmittedRootNode(
2260
+ node,
2261
+ trackedSerializerTask.publicationToken,
2262
+ serializationOptions.requiresBaselineOnDrop,
2263
+ serializationOptions.requiresBaselineOnDrop
2264
+ ? 'published_move_serialization_watermark'
2265
+ : 'unpublished_add_serialization_watermark',
2266
+ true
2267
+ )
2268
+ }
2269
+ if (
2270
+ getRetainedMutationApproxBytes() + serializerTask.approxBytes >
2271
+ MAX_PENDING_MUTATION_ROOT_APPROX_BYTES
2272
+ ) {
2273
+ if (mustDeferNormalizationEmission) {
2274
+ cancelPublicationToken(trackedSerializerTask.publicationToken)
2275
+ if (canDeferPendingRootTask(serializationOptions)) {
2276
+ return deferPendingRootTask(node, serializationOptions)
2277
+ }
2278
+ return handleOverflow({
2279
+ reason: MUTATION_ROOT_RETAINED_BYTES_WATERMARK
2280
+ })
2281
+ }
2282
+ if (!drainPendingRootTasksForAdmission()) {
2283
+ cancelPublicationToken(trackedSerializerTask.publicationToken)
2284
+ return false
2285
+ }
2286
+ if (
2287
+ getRetainedMutationApproxBytes() + serializerTask.approxBytes >
2288
+ MAX_PENDING_MUTATION_ROOT_APPROX_BYTES
2289
+ ) {
2290
+ cancelPublicationToken(trackedSerializerTask.publicationToken)
2291
+ if (canDeferPendingRootTask(serializationOptions)) {
2292
+ return deferPendingRootTask(node, serializationOptions)
2293
+ }
2294
+ return handleOverflow({
2295
+ reason: MUTATION_ROOT_RETAINED_BYTES_WATERMARK
2296
+ })
2297
+ }
2298
+ }
2299
+ var task = {
2300
+ generation: generation,
2301
+ sequence: nextTaskSequence++,
2302
+ rootNode: node,
2303
+ parentId: getSerializedNodeId(getParentNode(node)),
2304
+ nextId: null,
2305
+ serializerTask: serializerTask,
2306
+ publicationToken: trackedSerializerTask.publicationToken,
2307
+ serializedNodeIds: serializationOptions.serializedNodeIds,
2308
+ refreshCount: 0,
2309
+ accountedApproxBytes: serializerTask.approxBytes,
2310
+ isRetained: true,
2311
+ mutationGroup: isActiveMutationGroup(
2312
+ serializationOptions.mutationGroup
2313
+ )
2314
+ ? serializationOptions.mutationGroup
2315
+ : undefined,
2316
+ requiresBaselineOnDrop: Boolean(
2317
+ serializationOptions.requiresBaselineOnDrop
2318
+ ),
2319
+ isActiveSerializerTask: true
2320
+ }
2321
+ if (task.mutationGroup) {
2322
+ task.mutationGroup.pendingTaskCount += 1
2323
+ }
2324
+ retainedRootTaskApproxBytes += task.accountedApproxBytes
2325
+ activeRootTaskCount += 1
2326
+ if (!updateRetainedMutationResourceBudget()) {
2327
+ cancelPublicationToken(task.publicationToken)
2328
+ return handleOverflow({
2329
+ reason: AGGREGATE_RETAINED_MUTATION_WATERMARK,
2330
+ mutationApproxBytes: getRetainedMutationApproxBytes()
2331
+ })
2332
+ }
2333
+ clearLocallyDroppedRootNode(node)
2334
+ enqueuePendingRootTask(task)
2335
+ pendingRootTaskByRootNode.set(node, task)
2336
+ pendingRootTaskBySequence.set(task.sequence, task)
2337
+ schedulePendingRootTasks()
2338
+ return true
2339
+ }
2340
+
2341
+ function drainPendingRootTasksForAdmission() {
2342
+ var drainGeneration = generation
2343
+ var overflowCountBeforeDrain = overflowCount
2344
+ processPendingRootTasks(
2345
+ getCurrentTime() + MUTATION_SERIALIZATION_FLUSH_BUDGET_MS,
2346
+ true
2347
+ )
2348
+ return (
2349
+ !stopped &&
2350
+ generation === drainGeneration &&
2351
+ overflowCount === overflowCountBeforeDrain
2352
+ )
2353
+ }
2354
+
2355
+ function canDeferPendingRootTask(serializationOptions) {
2356
+ return Boolean(
2357
+ !serializationOptions.requiresBaselineOnDrop &&
2358
+ !isActiveMutationGroup(serializationOptions.mutationGroup)
2359
+ )
2360
+ }
2361
+
2362
+ function deferPendingRootTask(node, serializationOptions) {
2363
+ // A dropped unpublished add has no replay-tree dependency yet. If the
2364
+ // lightweight queue itself reaches its hard bound, degrading only that
2365
+ // root is safer than replacing (and synchronously serializing) the whole
2366
+ // document under the same load spike.
2367
+ if (
2368
+ deferredRootTaskCount >= MAX_DEFERRED_MUTATION_ROOT_TASKS ||
2369
+ getRetainedMutationApproxBytes() +
2370
+ DEFERRED_MUTATION_ROOT_TASK_APPROX_BYTES >
2371
+ MAX_PENDING_MUTATION_ROOT_APPROX_BYTES
2372
+ ) {
2373
+ reportLocalRootDrop(
2374
+ deferredRootTaskCount >= MAX_DEFERRED_MUTATION_ROOT_TASKS
2375
+ ? MUTATION_ROOT_ADMISSION_WATERMARK
2376
+ : MUTATION_ROOT_RETAINED_BYTES_WATERMARK
2377
+ )
2378
+ markLocallyDroppedRootNode(node)
2379
+ return true
2380
+ }
2381
+ var task = {
2382
+ generation: generation,
2383
+ sequence: nextTaskSequence++,
2384
+ rootNode: node,
2385
+ serializedNodeIds: serializationOptions.serializedNodeIds,
2386
+ refreshCount: 0,
2387
+ accountedApproxBytes: DEFERRED_MUTATION_ROOT_TASK_APPROX_BYTES,
2388
+ isRetained: true,
2389
+ isDeferred: true,
2390
+ wasDeferred: true,
2391
+ requiresBaselineOnDrop: false
2392
+ }
2393
+ retainedRootTaskApproxBytes += task.accountedApproxBytes
2394
+ if (!updateRetainedMutationResourceBudget()) {
2395
+ retainedRootTaskApproxBytes = Math.max(
2396
+ retainedRootTaskApproxBytes - task.accountedApproxBytes,
2397
+ 0
2398
+ )
2399
+ task.isRetained = false
2400
+ task.accountedApproxBytes = 0
2401
+ reportLocalRootDrop(AGGREGATE_RETAINED_MUTATION_WATERMARK)
2402
+ markLocallyDroppedRootNode(node)
2403
+ return true
2404
+ }
2405
+ clearLocallyDroppedRootNode(node)
2406
+ deferredRootTaskCount += 1
2407
+ deferredRootTaskOutstandingCount += 1
2408
+ pendingRootTaskByRootNode.set(node, task)
2409
+ pendingRootTaskBySequence.set(task.sequence, task)
2410
+ enqueuePendingRootTask(task)
2411
+ schedulePendingRootTasks()
2412
+ return true
2413
+ }
2414
+
2415
+ function reportLocalRootDrop(reason) {
2416
+ if (mutationPerfCb) {
2417
+ mutationPerfCb(
2418
+ __BUILD_ENV__REPLAY_DEBUG_ENABLED__
2419
+ ? {
2420
+ mutationLocalDropCount: 1,
2421
+ mutationLocalDropReason: reason
2422
+ }
2423
+ : reason
2424
+ )
2425
+ }
2426
+ }
2427
+
2428
+ function findPendingRootTask(node, fallbackAncestor) {
2429
+ if (overflowed) {
2430
+ return
2431
+ }
2432
+ var current = node
2433
+ var depth = 0
2434
+ while (current) {
2435
+ if (depth >= MAX_SERIALIZED_NODE_ANCESTOR_DEPTH) {
2436
+ return
2437
+ }
2438
+ var task = pendingRootTaskByRootNode.get(current)
2439
+ if (task && task.generation === generation) {
2440
+ return task
2441
+ }
2442
+ depth += 1
2443
+ current = getParentNode(current)
2444
+ }
2445
+ if (fallbackAncestor && fallbackAncestor !== node) {
2446
+ return findPendingRootTask(fallbackAncestor)
2447
+ }
2448
+ }
2449
+
2450
+ function refreshAndFlushPendingRootForNode(node) {
2451
+ if (stopped || overflowed) {
2452
+ return false
2453
+ }
2454
+ var task = findPendingRootTask(node)
2455
+ if (!task) {
2456
+ return
2457
+ }
2458
+ if (!refreshPendingRootTask(task)) {
2459
+ return false
2460
+ }
2461
+ var overflowCountBeforeFlush = overflowCount
2462
+ if (
2463
+ processPendingRootTasks(
2464
+ getCurrentTime() + MUTATION_SERIALIZATION_FLUSH_BUDGET_MS,
2465
+ true
2466
+ )
2467
+ ) {
2468
+ return true
2469
+ }
2470
+ if (
2471
+ overflowed ||
2472
+ overflowCount > overflowCountBeforeFlush
2473
+ ) {
2474
+ return false
2475
+ }
2476
+ // attachShadow() returns to application code synchronously. If the
2477
+ // rebuilt host cannot be published in this bounded drain, later shadow
2478
+ // mutations could overtake or be filtered behind the unpublished host.
2479
+ // Replace the baseline instead of leaving that dependency pending.
2480
+ return handleOverflow({
2481
+ reason: 'dynamic_shadow_pending_host_serialization_budget'
2482
+ })
2483
+ }
2484
+
2485
+ function refreshPendingRootTask(task, activateDeferredTask) {
2486
+ if (!task || task.generation !== generation || task.isCancelled) {
2487
+ return true
2488
+ }
2489
+ if (overflowed) {
2490
+ return false
2491
+ }
641
2492
  if (!task.rootNode.isConnected) {
2493
+ if (taskRequiresBaselineOnDrop(task)) {
2494
+ return handleOverflow({
2495
+ reason: 'published_move_cancelled'
2496
+ })
2497
+ }
642
2498
  cancelPendingRootTask(task)
643
- return
2499
+ return true
2500
+ }
2501
+
2502
+ var parentNode = getParentNode(task.rootNode)
2503
+ var parentPendingRootTask = findPendingRootTask(parentNode)
2504
+ if (parentPendingRootTask && parentPendingRootTask !== task) {
2505
+ if (taskRequiresBaselineOnDrop(task)) {
2506
+ markPendingRootTaskPublishedDependency(parentPendingRootTask)
2507
+ }
2508
+ cancelPendingRootTask(task)
2509
+ // The parent serializer may have already walked this branch before the
2510
+ // child moved under it. Rebuild the surviving task so it cannot publish
2511
+ // a stale subtree after absorbing the child's publication dependency.
2512
+ return refreshPendingRootTask(parentPendingRootTask)
2513
+ }
2514
+ var parentNodePrivacyLevel = getNodePrivacyLevel(
2515
+ parentNode,
2516
+ configuration.defaultPrivacyLevel
2517
+ )
2518
+ if (
2519
+ parentNodePrivacyLevel === NodePrivacyLevel.HIDDEN ||
2520
+ parentNodePrivacyLevel === NodePrivacyLevel.IGNORE
2521
+ ) {
2522
+ if (taskRequiresBaselineOnDrop(task)) {
2523
+ return handleOverflow({
2524
+ reason: 'published_move_cancelled'
2525
+ })
2526
+ }
2527
+ cancelPendingRootTask(task)
2528
+ return true
2529
+ }
2530
+ var wasDeferred = task.isDeferred
2531
+ if (wasDeferred && !activateDeferredTask) {
2532
+ schedulePendingRootTasks()
2533
+ return true
2534
+ }
2535
+ if (
2536
+ !wasDeferred &&
2537
+ task.refreshCount >= MAX_MUTATION_ROOT_TASK_REFRESH_COUNT
2538
+ ) {
2539
+ return dropUnpublishedRootTask(
2540
+ task,
2541
+ taskRequiresBaselineOnDrop(task)
2542
+ ? 'published_move_refresh_watermark'
2543
+ : 'unpublished_add_serialization_watermark',
2544
+ true
2545
+ )
2546
+ }
2547
+
2548
+ // A refresh supersedes the previous serialization generation. Nodes that
2549
+ // are not present in the rebuilt subtree must immediately fall back to
2550
+ // their last published parent instead of remaining blocked by a token that
2551
+ // can no longer be emitted.
2552
+ if (!wasDeferred) {
2553
+ task.requiresBaselineOnDrop = taskRequiresBaselineOnDrop(task)
2554
+ cancelPublicationToken(task.publicationToken)
2555
+ }
2556
+ var trackedSerializerTask = createTrackedMutationSerializerTask(
2557
+ task.rootNode,
2558
+ {
2559
+ serializedNodeIds: task.serializedNodeIds,
2560
+ parentNodePrivacyLevel: parentNodePrivacyLevel,
2561
+ serializationContext: {
2562
+ status: SerializationContextStatus.MUTATION,
2563
+ shadowRootsController: shadowRootsController
2564
+ },
2565
+ configuration: configuration,
2566
+ requiresBaselineOnDrop: taskRequiresBaselineOnDrop(task)
2567
+ }
2568
+ )
2569
+ task.publicationToken = trackedSerializerTask.publicationToken
2570
+ var serializerTask = trackedSerializerTask.serializerTask
2571
+ if (!serializerTask) {
2572
+ if (taskRequiresBaselineOnDrop(task)) {
2573
+ return handleOverflow({
2574
+ reason: 'published_move_serialization_failed'
2575
+ })
2576
+ }
2577
+ cancelPendingRootTask(task)
2578
+ return true
2579
+ }
2580
+ if (!wasDeferred) {
2581
+ task.refreshCount += 1
2582
+ }
2583
+ if (serializerTask.isMaxNodeComplexityReached) {
2584
+ return dropUnpublishedRootTask(
2585
+ task,
2586
+ 'published_move_serialization_watermark'
2587
+ )
2588
+ }
2589
+ if (
2590
+ serializerTask.approxBytes >
2591
+ MUTATION_SERIALIZATION_MAX_APPROX_BYTES
2592
+ ) {
2593
+ return dropUnpublishedRootTask(
2594
+ task,
2595
+ taskRequiresBaselineOnDrop(task)
2596
+ ? 'published_move_serialization_watermark'
2597
+ : 'unpublished_add_serialization_watermark',
2598
+ true
2599
+ )
2600
+ }
2601
+ if (
2602
+ wasDeferred &&
2603
+ getRetainedMutationApproxBytes() -
2604
+ task.accountedApproxBytes +
2605
+ serializerTask.approxBytes >
2606
+ MAX_PENDING_MUTATION_ROOT_APPROX_BYTES
2607
+ ) {
2608
+ cancelPublicationToken(task.publicationToken)
2609
+ task.publicationToken = undefined
2610
+ return 'blocked'
2611
+ }
2612
+ if (
2613
+ !updateRetainedRootTaskApproxBytes(
2614
+ task,
2615
+ serializerTask.approxBytes
2616
+ )
2617
+ ) {
2618
+ return handleOverflow({
2619
+ reason: AGGREGATE_RETAINED_MUTATION_WATERMARK,
2620
+ mutationApproxBytes: getRetainedMutationApproxBytes()
2621
+ })
2622
+ }
2623
+ if (
2624
+ getRetainedMutationApproxBytes() >
2625
+ MAX_PENDING_MUTATION_ROOT_APPROX_BYTES
2626
+ ) {
2627
+ return handleOverflow({
2628
+ reason: MUTATION_ROOT_RETAINED_BYTES_WATERMARK
2629
+ })
644
2630
  }
645
- refreshPendingRootTask(task)
2631
+ removeCompletedRootTask(task)
2632
+ task.parentId = getSerializedNodeId(parentNode)
2633
+ task.nextId = null
2634
+ task.serializerTask = serializerTask
2635
+ task.isCompleted = false
2636
+ task.isCancelled = false
2637
+ if (wasDeferred) {
2638
+ removeDeferredRootTaskQueueMembership(task)
2639
+ task.isActiveSerializerTask = true
2640
+ activeRootTaskCount += 1
2641
+ } else {
2642
+ enqueuePendingRootTask(task)
2643
+ schedulePendingRootTasks()
2644
+ }
2645
+ return true
2646
+ }
2647
+
2648
+ function retargetPendingRootTask(task, replacementNode) {
2649
+ if (
2650
+ !task ||
2651
+ task.generation !== generation ||
2652
+ task.isCancelled ||
2653
+ !replacementNode
2654
+ ) {
2655
+ return true
2656
+ }
2657
+ if (
2658
+ pendingRootTaskByRootNode.get(task.rootNode) !== task ||
2659
+ pendingRootTaskByRootNode.get(replacementNode)
2660
+ ) {
2661
+ return handleOverflow({ reason: 'published_move_cancelled' })
2662
+ }
2663
+ pendingRootTaskByRootNode.delete(task.rootNode)
2664
+ task.rootNode = replacementNode
2665
+ clearLocallyDroppedRootNode(replacementNode)
2666
+ pendingRootTaskByRootNode.set(replacementNode, task)
2667
+ return refreshPendingRootTask(task)
2668
+ }
2669
+
2670
+ function handlePendingRootRemoval(task, node) {
2671
+ if (!task || task.generation !== generation) {
2672
+ return true
2673
+ }
2674
+ if (node === task.rootNode) {
2675
+ if (task.rootNode.isConnected) {
2676
+ return refreshPendingRootTask(task)
2677
+ }
2678
+ if (taskRequiresBaselineOnDrop(task)) {
2679
+ return handleOverflow({
2680
+ reason: 'published_move_cancelled'
2681
+ })
2682
+ }
2683
+ cancelPendingRootTask(task)
2684
+ return true
2685
+ }
2686
+ if (!task.rootNode.isConnected) {
2687
+ if (taskRequiresBaselineOnDrop(task)) {
2688
+ return handleOverflow({
2689
+ reason: 'published_move_cancelled'
2690
+ })
2691
+ }
2692
+ cancelPendingRootTask(task)
2693
+ return true
2694
+ }
2695
+ return refreshPendingRootTask(task)
646
2696
  }
647
2697
 
648
2698
  function cancelPendingRootTask(task) {
2699
+ cancelPublicationToken(task.publicationToken)
2700
+ releaseMutationGroupDependency(task)
2701
+ task.isCancelled = true
2702
+ removeDeferredRootTaskQueueMembership(task)
2703
+ if (task.isQueued) {
2704
+ task.isQueued = false
2705
+ pendingRootTaskCount -= 1
2706
+ if (pendingRootTaskContinuation === task) {
2707
+ pendingRootTaskContinuation = undefined
2708
+ }
2709
+ }
649
2710
  pendingRootTaskByRootNode.delete(task.rootNode)
650
2711
  pendingRootTaskBySequence.delete(task.sequence)
651
2712
  removeCompletedRootTask(task)
652
- pendingRootTasks = pendingRootTasks.filter(function (pendingRootTask) {
653
- return pendingRootTask !== task
654
- })
2713
+ releaseRetainedRootTask(task)
655
2714
  advanceEmitSequencePastGaps()
2715
+ emitReadyMutationGroups()
2716
+ }
2717
+
2718
+ function dropUnpublishedRootTask(
2719
+ task,
2720
+ recoveryReason,
2721
+ shouldRecoverUnpublishedRoot
2722
+ ) {
2723
+ if (
2724
+ taskRequiresBaselineOnDrop(task) ||
2725
+ shouldRecoverUnpublishedRoot
2726
+ ) {
2727
+ return handleOverflow({
2728
+ reason:
2729
+ recoveryReason || 'published_move_serialization_watermark'
2730
+ })
2731
+ }
2732
+ markLocallyDroppedRootNode(task.rootNode)
2733
+ cancelPendingRootTask(task)
2734
+ return true
2735
+ }
2736
+
2737
+ function dropUnadmittedRootNode(
2738
+ node,
2739
+ publicationToken,
2740
+ requiresBaselineOnDrop,
2741
+ recoveryReason,
2742
+ shouldRecoverUnpublishedRoot
2743
+ ) {
2744
+ if (requiresBaselineOnDrop || shouldRecoverUnpublishedRoot) {
2745
+ cancelPublicationToken(publicationToken)
2746
+ return handleOverflow({
2747
+ reason:
2748
+ recoveryReason || 'published_move_serialization_watermark'
2749
+ })
2750
+ }
2751
+ markLocallyDroppedRootNode(node)
2752
+ cancelPublicationToken(publicationToken)
2753
+ return true
2754
+ }
2755
+
2756
+ function dropMutationGroupTasks(mutationGroup) {
2757
+ if (
2758
+ stopped ||
2759
+ overflowed ||
2760
+ !mutationGroup ||
2761
+ !pendingRootTaskBySequence.size
2762
+ ) {
2763
+ return
2764
+ }
2765
+ var tasks = Array.from(pendingRootTaskBySequence.values()).filter(
2766
+ function (task) {
2767
+ return task.mutationGroup === mutationGroup
2768
+ }
2769
+ )
2770
+ if (!tasks.length) {
2771
+ return
2772
+ }
2773
+ if (
2774
+ tasks.some(function (task) {
2775
+ return taskRequiresBaselineOnDrop(task)
2776
+ })
2777
+ ) {
2778
+ return handleOverflow({
2779
+ reason: 'published_move_normalization_budget'
2780
+ })
2781
+ }
2782
+ // Mark the whole group before cancellation. Sibling anchors are resolved
2783
+ // again immediately before emission, so no eager pending-task scan is
2784
+ // needed here.
2785
+ tasks.forEach(function (task) {
2786
+ markSharedLocallyDroppedRootNode(task.rootNode)
2787
+ locallyDroppedRootNodes.add(task.rootNode)
2788
+ })
2789
+ tasks.forEach(function (task) {
2790
+ cancelPendingRootTask(task)
2791
+ })
2792
+ }
2793
+
2794
+ function markPendingRootTaskPublishedDependency(task) {
2795
+ if (
2796
+ task &&
2797
+ task.generation === generation &&
2798
+ !task.isCancelled
2799
+ ) {
2800
+ task.requiresBaselineOnDrop = true
2801
+ }
2802
+ }
2803
+
2804
+ function taskRequiresBaselineOnDrop(task) {
2805
+ return Boolean(task && task.requiresBaselineOnDrop)
2806
+ }
2807
+
2808
+ function markLocallyDroppedRootNode(node) {
2809
+ markSharedLocallyDroppedRootNode(node)
2810
+ locallyDroppedRootNodes.add(node)
2811
+ }
2812
+
2813
+ function markSharedLocallyDroppedRootNode(node) {
2814
+ var dependencyState = getMutationDependencyState(
2815
+ shadowRootsController
2816
+ )
2817
+ if (dependencyState) {
2818
+ dependencyState.$rLocallyDroppedRoots.add(node)
2819
+ }
2820
+ }
2821
+
2822
+ function clearLocallyDroppedRootNode(node) {
2823
+ locallyDroppedRootNodes.delete(node)
2824
+ var dependencyState = getMutationDependencyState(
2825
+ shadowRootsController
2826
+ )
2827
+ if (dependencyState) {
2828
+ dependencyState.$rLocallyDroppedRoots.delete(node)
2829
+ }
2830
+ }
2831
+
2832
+ function removeDeferredRootTaskQueueMembership(task) {
2833
+ if (!task || !task.isDeferred) {
2834
+ return
2835
+ }
2836
+ task.isDeferred = false
2837
+ deferredRootTaskCount = Math.max(deferredRootTaskCount - 1, 0)
656
2838
  }
657
2839
 
658
2840
  function schedulePendingRootTasks() {
659
- if (stopped || scheduledFlush || !pendingRootTasks.length) {
2841
+ if (stopped || overflowed || scheduledFlush || !pendingRootTaskCount) {
660
2842
  return
661
2843
  }
662
2844
  scheduledFlush = setTimeout(function () {
663
2845
  scheduledFlush = undefined
664
- processPendingRootTasks(false)
2846
+ processPendingRootTasks(
2847
+ getCurrentTime() + MUTATION_SERIALIZATION_SLICE_MS,
2848
+ false
2849
+ )
665
2850
  }, 0)
666
2851
  }
667
2852
 
668
- function processPendingRootTasks(forceDrain) {
2853
+ function processPendingRootTasks(deadline, flushCompletedTasks) {
669
2854
  clearScheduledFlush()
670
- if (stopped) {
671
- return
2855
+ if (stopped || overflowed) {
2856
+ return true
672
2857
  }
673
- if (!pendingRootTasks.length) {
674
- if (forceDrain && completedRootTasks.length) {
675
- emitCompletedRootTasks()
676
- }
677
- return
2858
+ if (flushCompletedTasks && completedRootTasksBySequence.size) {
2859
+ emitCompletedRootTasks()
2860
+ }
2861
+ if (!pendingRootTaskCount) {
2862
+ return true
678
2863
  }
679
2864
 
680
- var deadline = forceDrain
681
- ? Infinity
682
- : getCurrentTime() + MUTATION_SERIALIZATION_SLICE_MS
2865
+ var serializationStart = __BUILD_ENV__REPLAY_DEBUG_ENABLED__
2866
+ ? getCurrentTime()
2867
+ : 0
683
2868
 
684
- while (pendingRootTasks.length) {
685
- var task = pendingRootTasks.shift()
2869
+ while (pendingRootTaskCount) {
2870
+ var task = dequeuePendingRootTask()
2871
+ if (!task) {
2872
+ break
2873
+ }
686
2874
  if (task.generation !== generation) {
687
2875
  continue
688
2876
  }
689
2877
 
690
- var completed = task.serializerTask.advance(deadline)
2878
+ if (task.isDeferred) {
2879
+ if (activeRootTaskCount >= MAX_PENDING_MUTATION_ROOT_TASKS) {
2880
+ emitCompletedRootTasks()
2881
+ if (stopped || overflowed) {
2882
+ return false
2883
+ }
2884
+ if (activeRootTaskCount >= MAX_PENDING_MUTATION_ROOT_TASKS) {
2885
+ return handleOverflow({
2886
+ reason: MUTATION_ROOT_ADMISSION_WATERMARK
2887
+ })
2888
+ }
2889
+ }
2890
+ var activationResult = refreshPendingRootTask(task, true)
2891
+ if (activationResult === 'blocked') {
2892
+ emitCompletedRootTasks()
2893
+ if (stopped || overflowed) {
2894
+ return false
2895
+ }
2896
+ activationResult = refreshPendingRootTask(task, true)
2897
+ if (activationResult === 'blocked') {
2898
+ return handleOverflow({
2899
+ reason: MUTATION_ROOT_RETAINED_BYTES_WATERMARK,
2900
+ mutationApproxBytes: getRetainedMutationApproxBytes()
2901
+ })
2902
+ }
2903
+ }
2904
+ if (activationResult === false) {
2905
+ return false
2906
+ }
2907
+ if (task.isCancelled || !task.isActiveSerializerTask) {
2908
+ continue
2909
+ }
2910
+ }
2911
+
2912
+ var completed = task.serializerTask.advance(
2913
+ deadline,
2914
+ MUTATION_SERIALIZATION_MAX_NODE_COUNT,
2915
+ MUTATION_SERIALIZATION_MAX_APPROX_BYTES
2916
+ )
691
2917
  if (task.generation !== generation) {
692
2918
  continue
693
2919
  }
2920
+ if (
2921
+ !updateRetainedRootTaskApproxBytes(
2922
+ task,
2923
+ task.serializerTask.approxBytes
2924
+ )
2925
+ ) {
2926
+ handleOverflow({
2927
+ reason: AGGREGATE_RETAINED_MUTATION_WATERMARK,
2928
+ mutationApproxBytes: getRetainedMutationApproxBytes()
2929
+ })
2930
+ return false
2931
+ }
694
2932
 
2933
+ if (
2934
+ !completed &&
2935
+ (task.serializerTask.isMaxNodeCountReached ||
2936
+ task.serializerTask.isMaxApproxBytesReached ||
2937
+ task.serializerTask.isMaxDepthReached ||
2938
+ task.serializerTask.isMaxNodeComplexityReached)
2939
+ ) {
2940
+ // A new subtree that only exceeds the mutation record's node/byte
2941
+ // watermarks may still fit in the larger full-snapshot budget. Replace
2942
+ // the baseline so a static oversized root is not lost forever. Depth
2943
+ // and per-node complexity use the same hard limits in a full snapshot,
2944
+ // so those remain a bounded local drop.
2945
+ var shouldRecoverUnpublishedRoot =
2946
+ !task.serializerTask.isMaxDepthReached &&
2947
+ !task.serializerTask.isMaxNodeComplexityReached &&
2948
+ (task.serializerTask.isMaxNodeCountReached ||
2949
+ task.serializerTask.isMaxApproxBytesReached)
2950
+ if (
2951
+ !dropUnpublishedRootTask(
2952
+ task,
2953
+ taskRequiresBaselineOnDrop(task)
2954
+ ? 'published_move_serialization_watermark'
2955
+ : 'unpublished_add_serialization_watermark',
2956
+ shouldRecoverUnpublishedRoot
2957
+ )
2958
+ ) {
2959
+ return false
2960
+ }
2961
+ continue
2962
+ }
695
2963
  if (completed) {
696
2964
  task.isCompleted = true
697
- completedRootTasks.push(task)
2965
+ completedRootTasksBySequence.set(task.sequence, task)
2966
+ }
2967
+ if (
2968
+ getRetainedMutationApproxBytes() >
2969
+ MAX_PENDING_MUTATION_ROOT_APPROX_BYTES
2970
+ ) {
2971
+ emitCompletedRootTasks()
2972
+ if (
2973
+ getRetainedMutationApproxBytes() >
2974
+ MAX_PENDING_MUTATION_ROOT_APPROX_BYTES
2975
+ ) {
2976
+ handleOverflow({
2977
+ reason: MUTATION_ROOT_RETAINED_BYTES_WATERMARK
2978
+ })
2979
+ return false
2980
+ }
2981
+ }
2982
+
2983
+ if (completed) {
2984
+ if (getCurrentTime() >= deadline) {
2985
+ break
2986
+ }
698
2987
  } else {
699
- pendingRootTasks.push(task)
700
- if (!forceDrain && getCurrentTime() >= deadline) {
2988
+ enqueuePendingRootTaskContinuation(task)
2989
+ if (getCurrentTime() >= deadline) {
701
2990
  break
702
2991
  }
703
2992
  }
704
2993
  }
705
2994
 
706
- if (completedRootTasks.length) {
707
- if (forceDrain || !pendingRootTasks.length) {
708
- emitCompletedRootTasks()
709
- } else {
710
- scheduleCompletedRootTasksEmit()
711
- }
2995
+ if (completedRootTasksBySequence.size) {
2996
+ emitCompletedRootTasks()
712
2997
  }
713
2998
 
714
- if (pendingRootTasks.length) {
2999
+ if (pendingRootTaskCount) {
715
3000
  schedulePendingRootTasks()
716
3001
  }
3002
+ if (__BUILD_ENV__REPLAY_DEBUG_ENABLED__ && mutationPerfCb) {
3003
+ mutationPerfCb({
3004
+ mutationSerializationCount: 1,
3005
+ mutationSerializationDuration: getCurrentTime() - serializationStart
3006
+ })
3007
+ }
3008
+ return pendingRootTaskCount === 0
717
3009
  }
718
3010
 
719
3011
  function clearScheduledFlush() {
@@ -723,86 +3015,271 @@ function createMutationTasksController(
723
3015
  }
724
3016
  }
725
3017
 
726
- function scheduleCompletedRootTasksEmit() {
727
- if (stopped || scheduledEmit || !completedRootTasks.length) {
728
- return
729
- }
730
- scheduledEmit = setTimeout(function () {
731
- scheduledEmit = undefined
732
- emitCompletedRootTasks()
733
- }, MUTATION_SERIALIZATION_EMIT_DELAY_MS)
734
- }
735
-
736
3018
  function emitCompletedRootTasks() {
737
- clearScheduledEmit()
738
- if (!completedRootTasks.length) {
3019
+ if (overflowed || !completedRootTasksBySequence.size) {
739
3020
  return
740
3021
  }
741
3022
 
742
- var completedTasksBySequence = new Map()
743
- completedRootTasks.forEach(function (task) {
744
- completedTasksBySequence.set(task.sequence, task)
745
- })
746
-
747
3023
  var readyTasks = []
748
3024
  advanceEmitSequencePastGaps()
749
3025
  while (nextEmitSequence < nextTaskSequence) {
750
- var nextTask = completedTasksBySequence.get(nextEmitSequence)
3026
+ var nextTask = completedRootTasksBySequence.get(nextEmitSequence)
751
3027
  if (!nextTask) {
752
3028
  break
753
3029
  }
754
3030
  readyTasks.push(nextTask)
755
- completedTasksBySequence.delete(nextEmitSequence)
3031
+ completedRootTasksBySequence.delete(nextEmitSequence)
756
3032
  nextEmitSequence += 1
757
3033
  }
758
3034
 
759
3035
  if (!readyTasks.length) {
760
- if (pendingRootTasks.length) {
3036
+ if (pendingRootTaskCount || deferredRootTaskCount) {
761
3037
  schedulePendingRootTasks()
762
- } else if (completedRootTasks.length) {
763
- scheduleCompletedRootTasksEmit()
764
3038
  }
765
3039
  return
766
3040
  }
767
3041
 
768
- var adds = readyTasks.map(function (task) {
3042
+ var emissionGeneration = generation
3043
+ var ungroupedAdds = []
3044
+ var ungroupedAddsApproxBytes = 64
3045
+ var queuedRootParentIds = new Map()
3046
+ var siblingResolutionState = [
3047
+ getCurrentTime() + MUTATION_NORMALIZATION_MAX_DURATION_MS,
3048
+ 0,
3049
+ false,
3050
+ new Map(),
3051
+ new Map()
3052
+ ]
3053
+
3054
+ for (
3055
+ var resolutionIndex = 0;
3056
+ resolutionIndex < readyTasks.length;
3057
+ resolutionIndex += 1
3058
+ ) {
3059
+ var resolutionTask = readyTasks[resolutionIndex]
3060
+ resolutionTask.nextId = getNextSibling(
3061
+ resolutionTask.rootNode,
3062
+ queuedRootParentIds,
3063
+ true,
3064
+ siblingResolutionState,
3065
+ resolutionTask.parentId,
3066
+ resolutionTask.sequence
3067
+ )
3068
+ if (siblingResolutionState[2]) {
3069
+ handleOverflow({
3070
+ reason: 'mutation_sibling_resolution_watermark',
3071
+ mutationNodeCount: siblingResolutionState[1]
3072
+ })
3073
+ return
3074
+ }
3075
+ queuedRootParentIds.set(
3076
+ resolutionTask.serializerTask.serializedNode.id,
3077
+ resolutionTask.parentId
3078
+ )
3079
+ }
3080
+
3081
+ function isEmissionGenerationActive() {
3082
+ return (
3083
+ !stopped &&
3084
+ !overflowed &&
3085
+ generation === emissionGeneration
3086
+ )
3087
+ }
3088
+
3089
+ function emitUngroupedAdds() {
3090
+ if (!ungroupedAdds.length) {
3091
+ return true
3092
+ }
3093
+ var adds = ungroupedAdds
3094
+ var approxBytes = ungroupedAddsApproxBytes
3095
+ ungroupedAdds = []
3096
+ ungroupedAddsApproxBytes = 64
3097
+ var payload = {
3098
+ adds: adds,
3099
+ removes: [],
3100
+ texts: [],
3101
+ attributes: []
3102
+ }
3103
+ approxBytesByMutationPayload.set(payload, approxBytes)
3104
+ mutationCallback(payload)
3105
+ return isEmissionGenerationActive()
3106
+ }
3107
+
3108
+ for (
3109
+ var readyTaskIndex = 0;
3110
+ readyTaskIndex < readyTasks.length;
3111
+ readyTaskIndex += 1
3112
+ ) {
3113
+ if (!isEmissionGenerationActive()) {
3114
+ return
3115
+ }
3116
+ var task = readyTasks[readyTaskIndex]
769
3117
  pendingRootTaskByRootNode.delete(task.rootNode)
770
3118
  pendingRootTaskBySequence.delete(task.sequence)
771
- return {
3119
+ var activeMutationGroup =
3120
+ task.mutationGroup &&
3121
+ isActiveMutationGroup(task.mutationGroup) &&
3122
+ !task.mutationGroup.canceled
3123
+ ? task.mutationGroup
3124
+ : undefined
3125
+ if (activeMutationGroup) {
3126
+ // Preserve callback order across the async serializer. A later pure
3127
+ // add can reference a node published by this atomic group through its
3128
+ // nextId, so it must not overtake the group's remove + add payload.
3129
+ if (!emitUngroupedAdds()) {
3130
+ return
3131
+ }
3132
+ transferRetainedRootTaskToMutationGroup(
3133
+ task,
3134
+ activeMutationGroup
3135
+ )
3136
+ } else {
3137
+ ungroupedAddsApproxBytes += task.accountedApproxBytes
3138
+ releaseRetainedRootTask(task)
3139
+ }
3140
+ var add = {
772
3141
  nextId: task.nextId,
773
3142
  parentId: task.parentId,
774
3143
  node: task.serializerTask.serializedNode
775
3144
  }
776
- })
777
- completedRootTasks = completedRootTasks.filter(function (task) {
778
- return readyTasks.indexOf(task) === -1
779
- })
780
-
781
- mutationCallback({
782
- adds: adds,
783
- removes: [],
784
- texts: [],
785
- attributes: []
786
- })
3145
+ task.publicationToken.$rQueued = true
3146
+ publicationTokenByMutationAdd.set(add, task.publicationToken)
3147
+ task.publicationToken = undefined
3148
+ if (activeMutationGroup) {
3149
+ activeMutationGroup.payload.adds.push(add)
3150
+ } else {
3151
+ ungroupedAdds.push(add)
3152
+ }
3153
+ releaseMutationGroupDependency(task)
3154
+ if (activeMutationGroup) {
3155
+ emitReadyMutationGroups()
3156
+ if (!isEmissionGenerationActive()) {
3157
+ return
3158
+ }
3159
+ }
3160
+ }
787
3161
 
788
- if (completedRootTasks.length) {
789
- scheduleCompletedRootTasksEmit()
3162
+ if (!emitUngroupedAdds()) {
3163
+ return
790
3164
  }
3165
+ // An attribute/text-only group can be waiting behind an earlier
3166
+ // ungrouped serializer task even though it has no tasks of its own.
3167
+ emitReadyMutationGroups()
791
3168
  }
792
3169
 
793
3170
  function removeCompletedRootTask(task) {
794
- completedRootTasks = completedRootTasks.filter(function (completedTask) {
795
- return completedTask !== task
3171
+ completedRootTasksBySequence.delete(task.sequence)
3172
+ }
3173
+
3174
+ function updateRetainedRootTaskApproxBytes(task, approxBytes) {
3175
+ if (!task.isRetained) {
3176
+ return true
3177
+ }
3178
+ retainedRootTaskApproxBytes +=
3179
+ approxBytes - task.accountedApproxBytes
3180
+ task.accountedApproxBytes = approxBytes
3181
+ return updateRetainedMutationResourceBudget()
3182
+ }
3183
+
3184
+ function releaseRetainedRootTask(task) {
3185
+ if (!task.isRetained) {
3186
+ return
3187
+ }
3188
+ task.isRetained = false
3189
+ retainedRootTaskApproxBytes = Math.max(
3190
+ 0,
3191
+ retainedRootTaskApproxBytes - task.accountedApproxBytes
3192
+ )
3193
+ task.accountedApproxBytes = 0
3194
+ updateRetainedMutationResourceBudget()
3195
+ releaseActiveRootTask(task)
3196
+ releaseDeferredRootTaskOutstanding(task)
3197
+ }
3198
+
3199
+ function releaseActiveRootTask(task) {
3200
+ if (!task || !task.isActiveSerializerTask) {
3201
+ return
3202
+ }
3203
+ task.isActiveSerializerTask = false
3204
+ activeRootTaskCount = Math.max(activeRootTaskCount - 1, 0)
3205
+ }
3206
+
3207
+ function releaseDeferredRootTaskOutstanding(task) {
3208
+ if (!task || !task.wasDeferred) {
3209
+ return
3210
+ }
3211
+ task.wasDeferred = false
3212
+ deferredRootTaskOutstandingCount = Math.max(
3213
+ deferredRootTaskOutstandingCount - 1,
3214
+ 0
3215
+ )
3216
+ }
3217
+
3218
+ function updateRetainedMutationResourceBudget() {
3219
+ if (!mutationResourceBudget) {
3220
+ return true
3221
+ }
3222
+ var approxBytes = getRetainedMutationApproxBytes()
3223
+ if (!approxBytes) {
3224
+ if (retainedMutationBudgetReservation) {
3225
+ retainedMutationBudgetReservation()
3226
+ retainedMutationBudgetReservation = undefined
3227
+ }
3228
+ return true
3229
+ }
3230
+ if (!retainedMutationBudgetReservation) {
3231
+ retainedMutationBudgetReservation = mutationResourceBudget.reserve(
3232
+ MUTATION_RESOURCE_RETAINED,
3233
+ { approxBytes: approxBytes }
3234
+ )
3235
+ return Boolean(retainedMutationBudgetReservation)
3236
+ }
3237
+ return retainedMutationBudgetReservation.update({
3238
+ approxBytes: approxBytes
796
3239
  })
797
3240
  }
798
3241
 
799
- function clearScheduledEmit() {
800
- if (scheduledEmit) {
801
- clearTimeout(scheduledEmit)
802
- scheduledEmit = undefined
3242
+ function createTrackedMutationSerializerTask(node, serializationOptions) {
3243
+ var publicationToken = createMutationAddPublicationToken(
3244
+ shadowRootsController,
3245
+ serializationOptions.requiresBaselineOnDrop
3246
+ )
3247
+ var serializationContext = assign(
3248
+ {},
3249
+ serializationOptions.serializationContext,
3250
+ {
3251
+ publicationToken: publicationToken
3252
+ }
3253
+ )
3254
+ var serializerTask = createMutationSerializerTask(
3255
+ node,
3256
+ assign({}, serializationOptions, {
3257
+ serializationContext: serializationContext,
3258
+ onSerializedNode: function (node, parentNode) {
3259
+ // A previously degraded node can later be published as a descendant
3260
+ // of a wider root task. Clear both local markers for every staged
3261
+ // node, not only when that node becomes a root task itself.
3262
+ clearLocallyDroppedRootNode(node)
3263
+ if (mutationNodeSerializationCb) {
3264
+ mutationNodeSerializationCb(
3265
+ node,
3266
+ parentNode,
3267
+ publicationToken
3268
+ )
3269
+ }
3270
+ }
3271
+ })
3272
+ )
3273
+ return {
3274
+ serializerTask: serializerTask,
3275
+ publicationToken: publicationToken
803
3276
  }
804
3277
  }
805
3278
 
3279
+ function cancelPublicationToken(publicationToken) {
3280
+ cancelMutationAddPublicationToken(publicationToken)
3281
+ }
3282
+
806
3283
  function advanceEmitSequencePastGaps() {
807
3284
  while (
808
3285
  nextEmitSequence < nextTaskSequence &&
@@ -812,15 +3289,214 @@ function createMutationTasksController(
812
3289
  }
813
3290
  }
814
3291
 
815
- function getNextSibling(node) {
3292
+ function enqueuePendingRootTask(task) {
3293
+ if (task.isQueued) {
3294
+ return
3295
+ }
3296
+ if (!pendingRootTaskCount) {
3297
+ pendingRootTasks = []
3298
+ pendingRootTaskHead = 0
3299
+ }
3300
+ task.isQueued = true
3301
+ pendingRootTaskCount += 1
3302
+ pendingRootTasks.push(task)
3303
+ }
3304
+
3305
+ function enqueuePendingRootTaskContinuation(task) {
3306
+ if (task.isQueued) {
3307
+ return
3308
+ }
3309
+ task.isQueued = true
3310
+ pendingRootTaskCount += 1
3311
+ pendingRootTaskContinuation = task
3312
+ }
3313
+
3314
+ function dequeuePendingRootTask() {
3315
+ if (pendingRootTaskContinuation) {
3316
+ var continuation = pendingRootTaskContinuation
3317
+ pendingRootTaskContinuation = undefined
3318
+ if (continuation.isQueued) {
3319
+ continuation.isQueued = false
3320
+ pendingRootTaskCount -= 1
3321
+ return continuation
3322
+ }
3323
+ }
3324
+ while (pendingRootTaskHead < pendingRootTasks.length) {
3325
+ var task = pendingRootTasks[pendingRootTaskHead++]
3326
+ if (!task.isQueued) {
3327
+ continue
3328
+ }
3329
+ task.isQueued = false
3330
+ pendingRootTaskCount -= 1
3331
+ compactPendingRootTaskQueue()
3332
+ if (!task.isCancelled) {
3333
+ return task
3334
+ }
3335
+ }
3336
+ }
3337
+
3338
+ function compactPendingRootTaskQueue() {
3339
+ if (
3340
+ pendingRootTaskHead >= 256 &&
3341
+ pendingRootTaskHead * 2 >= pendingRootTasks.length
3342
+ ) {
3343
+ pendingRootTasks = pendingRootTasks.slice(pendingRootTaskHead)
3344
+ pendingRootTaskHead = 0
3345
+ }
3346
+ }
3347
+
3348
+ function getNextSibling(
3349
+ node,
3350
+ serializedNodeIds,
3351
+ requireQueued,
3352
+ resolutionState,
3353
+ expectedParentId,
3354
+ taskSequence
3355
+ ) {
3356
+ if (
3357
+ requireQueued &&
3358
+ getSerializedNodeId(getParentNode(node)) !== expectedParentId
3359
+ ) {
3360
+ // The native move is still waiting in MutationBatch. Emit the old-parent
3361
+ // add without a cross-parent anchor; the later normalized move will place
3362
+ // it under the current parent.
3363
+ return null
3364
+ }
816
3365
  var nextSibling = node.nextSibling
3366
+ var visitedNodes = resolutionState ? [] : undefined
817
3367
  while (nextSibling) {
3368
+ if (
3369
+ resolutionState &&
3370
+ consumeSiblingResolutionBudget(resolutionState)
3371
+ ) {
3372
+ return null
3373
+ }
818
3374
  if (hasSerializedNode(nextSibling)) {
819
- return getSerializedNodeId(nextSibling)
3375
+ var nextSiblingId = getSerializedNodeId(nextSibling)
3376
+ var pendingNextSiblingTask = requireQueued
3377
+ ? findPendingRootTask(nextSibling)
3378
+ : undefined
3379
+ var serializedSiblingIsQueuedInCurrentParent = Boolean(
3380
+ serializedNodeIds && serializedNodeIds.has(nextSiblingId)
3381
+ )
3382
+ if (
3383
+ serializedSiblingIsQueuedInCurrentParent &&
3384
+ requireQueued
3385
+ ) {
3386
+ serializedSiblingIsQueuedInCurrentParent =
3387
+ serializedNodeIds.get(nextSiblingId) ===
3388
+ getSerializedNodeId(getParentNode(nextSibling))
3389
+ }
3390
+ if (
3391
+ !locallyDroppedRootNodes.has(nextSibling) &&
3392
+ (!pendingNextSiblingTask ||
3393
+ serializedSiblingIsQueuedInCurrentParent) &&
3394
+ (serializedSiblingIsQueuedInCurrentParent ||
3395
+ !isIgnoredNode(nextSibling, requireQueued))
3396
+ ) {
3397
+ return finalizeSiblingResolution(
3398
+ resolutionState,
3399
+ visitedNodes,
3400
+ nextSiblingId,
3401
+ Infinity
3402
+ )
3403
+ }
3404
+ var cachedMinSequence =
3405
+ resolutionState &&
3406
+ resolutionState[4].get(nextSibling)
3407
+ if (
3408
+ cachedMinSequence !== undefined &&
3409
+ cachedMinSequence >= taskSequence
3410
+ ) {
3411
+ return finalizeSiblingResolution(
3412
+ resolutionState,
3413
+ visitedNodes,
3414
+ resolutionState[3].get(nextSibling),
3415
+ cachedMinSequence
3416
+ )
3417
+ }
3418
+ if (visitedNodes) {
3419
+ visitedNodes.push(
3420
+ nextSibling,
3421
+ pendingNextSiblingTask
3422
+ ? pendingNextSiblingTask.sequence
3423
+ : Infinity
3424
+ )
3425
+ }
3426
+ } else if (visitedNodes) {
3427
+ var cachedIgnoredMinSequence =
3428
+ resolutionState[4].get(nextSibling)
3429
+ if (
3430
+ cachedIgnoredMinSequence !== undefined &&
3431
+ cachedIgnoredMinSequence >= taskSequence
3432
+ ) {
3433
+ return finalizeSiblingResolution(
3434
+ resolutionState,
3435
+ visitedNodes,
3436
+ resolutionState[3].get(nextSibling),
3437
+ cachedIgnoredMinSequence
3438
+ )
3439
+ }
3440
+ visitedNodes.push(nextSibling, Infinity)
820
3441
  }
821
3442
  nextSibling = nextSibling.nextSibling
822
3443
  }
823
- return null
3444
+ return finalizeSiblingResolution(
3445
+ resolutionState,
3446
+ visitedNodes,
3447
+ null,
3448
+ Infinity
3449
+ )
3450
+ }
3451
+
3452
+ function finalizeSiblingResolution(
3453
+ resolutionState,
3454
+ visitedNodes,
3455
+ nextId,
3456
+ minPendingSequence
3457
+ ) {
3458
+ if (!resolutionState) {
3459
+ return nextId
3460
+ }
3461
+ for (
3462
+ var index = visitedNodes.length - 2;
3463
+ index >= 0;
3464
+ index -= 2
3465
+ ) {
3466
+ if (consumeSiblingResolutionBudget(resolutionState)) {
3467
+ return null
3468
+ }
3469
+ minPendingSequence = Math.min(
3470
+ minPendingSequence,
3471
+ visitedNodes[index + 1]
3472
+ )
3473
+ resolutionState[3].set(visitedNodes[index], nextId)
3474
+ resolutionState[4].set(visitedNodes[index], minPendingSequence)
3475
+ }
3476
+ return nextId
3477
+ }
3478
+
3479
+ function consumeSiblingResolutionBudget(resolutionState) {
3480
+ resolutionState[1] += 1
3481
+ if (
3482
+ resolutionState[1] >= MAX_PENDING_MUTATION_ROOT_TASKS * 32 ||
3483
+ (resolutionState[1] %
3484
+ MUTATION_NORMALIZATION_TIME_CHECK_INTERVAL ===
3485
+ 0 &&
3486
+ getCurrentTime() >= resolutionState[0])
3487
+ ) {
3488
+ resolutionState[2] = true
3489
+ return true
3490
+ }
3491
+ return false
3492
+ }
3493
+
3494
+ function isIgnoredNode(node, includeQueued) {
3495
+ try {
3496
+ return isNodeIgnored(node, includeQueued)
3497
+ } catch (_) {
3498
+ return true
3499
+ }
824
3500
  }
825
3501
  }
826
3502
 
@@ -831,11 +3507,66 @@ function getCurrentTime() {
831
3507
  return Date.now()
832
3508
  }
833
3509
 
834
- function traverseRemovedShadowDom(removedNode, shadowDomRemovedCallback) {
835
- if (isNodeShadowHost(removedNode)) {
836
- shadowDomRemovedCallback(removedNode.shadowRoot)
3510
+ function traverseRemovedShadowDom(
3511
+ removedNode,
3512
+ shadowDomRemovedCallback,
3513
+ traversalState
3514
+ ) {
3515
+ if (traversalState.deadline === undefined) {
3516
+ traversalState.deadline =
3517
+ getCurrentTime() + MAX_REMOVED_SUBTREE_TRAVERSAL_DURATION_MS
837
3518
  }
838
- forEachChildNodes(removedNode, function (childNode) {
839
- return traverseRemovedShadowDom(childNode, shadowDomRemovedCallback)
840
- })
3519
+ // Keep one cursor frame per depth level instead of pushing every child of a
3520
+ // wide subtree. The stack itself is therefore bounded by the same node
3521
+ // watermark as the traversal.
3522
+ var traversalStack = [
3523
+ {
3524
+ node: removedNode,
3525
+ entered: false
3526
+ }
3527
+ ]
3528
+ while (traversalStack.length) {
3529
+ var frame = traversalStack[traversalStack.length - 1]
3530
+ if (frame.entered) {
3531
+ if (frame.nextChild) {
3532
+ var nextChild = frame.nextChild
3533
+ frame.nextChild = nextChild.nextSibling
3534
+ traversalStack.push({
3535
+ node: nextChild,
3536
+ entered: false
3537
+ })
3538
+ continue
3539
+ }
3540
+ if (frame.shadowRoot) {
3541
+ var shadowRoot = frame.shadowRoot
3542
+ frame.shadowRoot = undefined
3543
+ traversalStack.push({
3544
+ node: shadowRoot,
3545
+ entered: false
3546
+ })
3547
+ continue
3548
+ }
3549
+ traversalStack.pop()
3550
+ continue
3551
+ }
3552
+ if (
3553
+ traversalState.nodeCount >=
3554
+ MAX_REMOVED_SUBTREE_TRAVERSAL_NODES ||
3555
+ (traversalState.nodeCount %
3556
+ REMOVED_SUBTREE_TIME_CHECK_INTERVAL ===
3557
+ 0 &&
3558
+ getCurrentTime() >= traversalState.deadline)
3559
+ ) {
3560
+ return false
3561
+ }
3562
+ frame.entered = true
3563
+ traversalState.nodeCount += 1
3564
+ var node = frame.node
3565
+ if (isNodeShadowHost(node)) {
3566
+ shadowDomRemovedCallback(node.shadowRoot)
3567
+ frame.shadowRoot = node.shadowRoot
3568
+ }
3569
+ frame.nextChild = node.firstChild
3570
+ }
3571
+ return true
841
3572
  }