@fluidframework/sequence 1.4.0-121020 → 2.0.0-dev-rc.1.0.0.225277

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 (350) hide show
  1. package/.eslintrc.js +9 -11
  2. package/.mocharc.js +12 -0
  3. package/CHANGELOG.md +449 -0
  4. package/README.md +364 -183
  5. package/api-extractor-esm.json +4 -0
  6. package/api-extractor-lint.json +4 -0
  7. package/api-extractor.json +2 -2
  8. package/api-report/sequence.api.md +734 -0
  9. package/dist/{defaultMap.js → defaultMap.cjs} +38 -26
  10. package/dist/defaultMap.cjs.map +1 -0
  11. package/dist/defaultMap.d.ts +7 -6
  12. package/dist/defaultMap.d.ts.map +1 -1
  13. package/dist/defaultMapInterfaces.cjs +7 -0
  14. package/dist/defaultMapInterfaces.cjs.map +1 -0
  15. package/dist/defaultMapInterfaces.d.ts +45 -12
  16. package/dist/defaultMapInterfaces.d.ts.map +1 -1
  17. package/dist/index.cjs +60 -0
  18. package/dist/index.cjs.map +1 -0
  19. package/dist/index.d.ts +14 -12
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/intervalCollection.cjs +1193 -0
  22. package/dist/intervalCollection.cjs.map +1 -0
  23. package/dist/intervalCollection.d.ts +448 -162
  24. package/dist/intervalCollection.d.ts.map +1 -1
  25. package/dist/intervalIndex/endpointInRangeIndex.cjs +66 -0
  26. package/dist/intervalIndex/endpointInRangeIndex.cjs.map +1 -0
  27. package/dist/intervalIndex/endpointInRangeIndex.d.ts +34 -0
  28. package/dist/intervalIndex/endpointInRangeIndex.d.ts.map +1 -0
  29. package/dist/intervalIndex/endpointIndex.cjs +47 -0
  30. package/dist/intervalIndex/endpointIndex.cjs.map +1 -0
  31. package/dist/intervalIndex/endpointIndex.d.ts +38 -0
  32. package/dist/intervalIndex/endpointIndex.d.ts.map +1 -0
  33. package/dist/intervalIndex/idIntervalIndex.cjs +44 -0
  34. package/dist/intervalIndex/idIntervalIndex.cjs.map +1 -0
  35. package/dist/intervalIndex/idIntervalIndex.d.ts +18 -0
  36. package/dist/intervalIndex/idIntervalIndex.d.ts.map +1 -0
  37. package/dist/intervalIndex/index.cjs +24 -0
  38. package/dist/intervalIndex/index.cjs.map +1 -0
  39. package/dist/intervalIndex/index.d.ts +13 -0
  40. package/dist/intervalIndex/index.d.ts.map +1 -0
  41. package/dist/{defaultMapInterfaces.js → intervalIndex/intervalIndex.cjs} +1 -1
  42. package/dist/intervalIndex/intervalIndex.cjs.map +1 -0
  43. package/dist/intervalIndex/intervalIndex.d.ts +30 -0
  44. package/dist/intervalIndex/intervalIndex.d.ts.map +1 -0
  45. package/dist/intervalIndex/intervalIndexUtils.cjs +22 -0
  46. package/dist/intervalIndex/intervalIndexUtils.cjs.map +1 -0
  47. package/dist/intervalIndex/intervalIndexUtils.d.ts +17 -0
  48. package/dist/intervalIndex/intervalIndexUtils.d.ts.map +1 -0
  49. package/dist/intervalIndex/overlappingIntervalsIndex.cjs +116 -0
  50. package/dist/intervalIndex/overlappingIntervalsIndex.cjs.map +1 -0
  51. package/dist/intervalIndex/overlappingIntervalsIndex.d.ts +44 -0
  52. package/dist/intervalIndex/overlappingIntervalsIndex.d.ts.map +1 -0
  53. package/dist/intervalIndex/overlappingSequenceIntervalsIndex.cjs +41 -0
  54. package/dist/intervalIndex/overlappingSequenceIntervalsIndex.cjs.map +1 -0
  55. package/dist/intervalIndex/overlappingSequenceIntervalsIndex.d.ts +11 -0
  56. package/dist/intervalIndex/overlappingSequenceIntervalsIndex.d.ts.map +1 -0
  57. package/dist/intervalIndex/sequenceIntervalIndexes.cjs +7 -0
  58. package/dist/intervalIndex/sequenceIntervalIndexes.cjs.map +1 -0
  59. package/dist/intervalIndex/sequenceIntervalIndexes.d.ts +35 -0
  60. package/dist/intervalIndex/sequenceIntervalIndexes.d.ts.map +1 -0
  61. package/dist/intervalIndex/startpointInRangeIndex.cjs +66 -0
  62. package/dist/intervalIndex/startpointInRangeIndex.cjs.map +1 -0
  63. package/dist/intervalIndex/startpointInRangeIndex.d.ts +34 -0
  64. package/dist/intervalIndex/startpointInRangeIndex.d.ts.map +1 -0
  65. package/dist/intervalTree.cjs +80 -0
  66. package/dist/intervalTree.cjs.map +1 -0
  67. package/dist/intervalTree.d.ts +24 -0
  68. package/dist/intervalTree.d.ts.map +1 -0
  69. package/dist/intervals/index.cjs +24 -0
  70. package/dist/intervals/index.cjs.map +1 -0
  71. package/dist/intervals/index.d.ts +8 -0
  72. package/dist/intervals/index.d.ts.map +1 -0
  73. package/dist/intervals/interval.cjs +181 -0
  74. package/dist/intervals/interval.cjs.map +1 -0
  75. package/dist/intervals/interval.d.ts +84 -0
  76. package/dist/intervals/interval.d.ts.map +1 -0
  77. package/dist/intervals/intervalUtils.cjs +90 -0
  78. package/dist/intervals/intervalUtils.cjs.map +1 -0
  79. package/dist/intervals/intervalUtils.d.ts +240 -0
  80. package/dist/intervals/intervalUtils.d.ts.map +1 -0
  81. package/dist/intervals/sequenceInterval.cjs +378 -0
  82. package/dist/intervals/sequenceInterval.cjs.map +1 -0
  83. package/dist/intervals/sequenceInterval.d.ts +137 -0
  84. package/dist/intervals/sequenceInterval.d.ts.map +1 -0
  85. package/dist/{localValues.js → localValues.cjs} +1 -1
  86. package/dist/localValues.cjs.map +1 -0
  87. package/dist/localValues.d.ts +2 -1
  88. package/dist/localValues.d.ts.map +1 -1
  89. package/dist/{packageVersion.js → packageVersion.cjs} +2 -2
  90. package/dist/packageVersion.cjs.map +1 -0
  91. package/dist/packageVersion.d.ts +1 -1
  92. package/dist/packageVersion.d.ts.map +1 -1
  93. package/dist/revertibles.cjs +425 -0
  94. package/dist/revertibles.cjs.map +1 -0
  95. package/dist/revertibles.d.ts +86 -0
  96. package/dist/revertibles.d.ts.map +1 -0
  97. package/dist/sequence-alpha.d.ts +1290 -0
  98. package/dist/sequence-beta.d.ts +244 -0
  99. package/dist/sequence-public.d.ts +244 -0
  100. package/dist/sequence-untrimmed.d.ts +1778 -0
  101. package/dist/{sequence.js → sequence.cjs} +230 -156
  102. package/dist/sequence.cjs.map +1 -0
  103. package/dist/sequence.d.ts +125 -48
  104. package/dist/sequence.d.ts.map +1 -1
  105. package/dist/{sequenceDeltaEvent.js → sequenceDeltaEvent.cjs} +18 -8
  106. package/dist/sequenceDeltaEvent.cjs.map +1 -0
  107. package/dist/sequenceDeltaEvent.d.ts +24 -7
  108. package/dist/sequenceDeltaEvent.d.ts.map +1 -1
  109. package/dist/sequenceFactory.cjs +55 -0
  110. package/dist/sequenceFactory.cjs.map +1 -0
  111. package/dist/sequenceFactory.d.ts +3 -89
  112. package/dist/sequenceFactory.d.ts.map +1 -1
  113. package/dist/{sharedIntervalCollection.js → sharedIntervalCollection.cjs} +17 -22
  114. package/dist/sharedIntervalCollection.cjs.map +1 -0
  115. package/dist/sharedIntervalCollection.d.ts +12 -12
  116. package/dist/sharedIntervalCollection.d.ts.map +1 -1
  117. package/dist/{sharedSequence.js → sharedSequence.cjs} +29 -22
  118. package/dist/sharedSequence.cjs.map +1 -0
  119. package/dist/sharedSequence.d.ts +14 -2
  120. package/dist/sharedSequence.d.ts.map +1 -1
  121. package/dist/sharedString.cjs +274 -0
  122. package/dist/sharedString.cjs.map +1 -0
  123. package/dist/sharedString.d.ts +49 -26
  124. package/dist/sharedString.d.ts.map +1 -1
  125. package/dist/tsdoc-metadata.json +11 -0
  126. package/lib/{defaultMap.d.ts → defaultMap.d.mts} +8 -7
  127. package/lib/defaultMap.d.mts.map +1 -0
  128. package/lib/{defaultMap.js → defaultMap.mjs} +38 -26
  129. package/lib/defaultMap.mjs.map +1 -0
  130. package/lib/{defaultMapInterfaces.d.ts → defaultMapInterfaces.d.mts} +46 -13
  131. package/lib/defaultMapInterfaces.d.mts.map +1 -0
  132. package/lib/defaultMapInterfaces.mjs +6 -0
  133. package/lib/defaultMapInterfaces.mjs.map +1 -0
  134. package/lib/index.d.mts +17 -0
  135. package/lib/index.d.mts.map +1 -0
  136. package/lib/index.mjs +16 -0
  137. package/lib/index.mjs.map +1 -0
  138. package/lib/intervalCollection.d.mts +556 -0
  139. package/lib/intervalCollection.d.mts.map +1 -0
  140. package/lib/intervalCollection.mjs +1178 -0
  141. package/lib/intervalCollection.mjs.map +1 -0
  142. package/lib/intervalIndex/endpointInRangeIndex.d.mts +34 -0
  143. package/lib/intervalIndex/endpointInRangeIndex.d.mts.map +1 -0
  144. package/lib/intervalIndex/endpointInRangeIndex.mjs +61 -0
  145. package/lib/intervalIndex/endpointInRangeIndex.mjs.map +1 -0
  146. package/lib/intervalIndex/endpointIndex.d.mts +38 -0
  147. package/lib/intervalIndex/endpointIndex.d.mts.map +1 -0
  148. package/lib/intervalIndex/endpointIndex.mjs +42 -0
  149. package/lib/intervalIndex/endpointIndex.mjs.map +1 -0
  150. package/lib/intervalIndex/idIntervalIndex.d.mts +18 -0
  151. package/lib/intervalIndex/idIntervalIndex.d.mts.map +1 -0
  152. package/lib/intervalIndex/idIntervalIndex.mjs +40 -0
  153. package/lib/intervalIndex/idIntervalIndex.mjs.map +1 -0
  154. package/lib/intervalIndex/index.d.mts +13 -0
  155. package/lib/intervalIndex/index.d.mts.map +1 -0
  156. package/lib/intervalIndex/index.mjs +11 -0
  157. package/lib/intervalIndex/index.mjs.map +1 -0
  158. package/lib/intervalIndex/intervalIndex.d.mts +30 -0
  159. package/lib/intervalIndex/intervalIndex.d.mts.map +1 -0
  160. package/lib/{defaultMapInterfaces.js → intervalIndex/intervalIndex.mjs} +1 -1
  161. package/lib/intervalIndex/intervalIndex.mjs.map +1 -0
  162. package/lib/intervalIndex/intervalIndexUtils.d.mts +17 -0
  163. package/lib/intervalIndex/intervalIndexUtils.d.mts.map +1 -0
  164. package/lib/intervalIndex/intervalIndexUtils.mjs +18 -0
  165. package/lib/intervalIndex/intervalIndexUtils.mjs.map +1 -0
  166. package/lib/intervalIndex/overlappingIntervalsIndex.d.mts +44 -0
  167. package/lib/intervalIndex/overlappingIntervalsIndex.d.mts.map +1 -0
  168. package/lib/intervalIndex/overlappingIntervalsIndex.mjs +111 -0
  169. package/lib/intervalIndex/overlappingIntervalsIndex.mjs.map +1 -0
  170. package/lib/intervalIndex/overlappingSequenceIntervalsIndex.d.mts +11 -0
  171. package/lib/intervalIndex/overlappingSequenceIntervalsIndex.d.mts.map +1 -0
  172. package/lib/intervalIndex/overlappingSequenceIntervalsIndex.mjs +37 -0
  173. package/lib/intervalIndex/overlappingSequenceIntervalsIndex.mjs.map +1 -0
  174. package/lib/intervalIndex/sequenceIntervalIndexes.d.mts +35 -0
  175. package/lib/intervalIndex/sequenceIntervalIndexes.d.mts.map +1 -0
  176. package/lib/intervalIndex/sequenceIntervalIndexes.mjs +6 -0
  177. package/lib/intervalIndex/sequenceIntervalIndexes.mjs.map +1 -0
  178. package/lib/intervalIndex/startpointInRangeIndex.d.mts +34 -0
  179. package/lib/intervalIndex/startpointInRangeIndex.d.mts.map +1 -0
  180. package/lib/intervalIndex/startpointInRangeIndex.mjs +61 -0
  181. package/lib/intervalIndex/startpointInRangeIndex.mjs.map +1 -0
  182. package/lib/intervalTree.d.mts +24 -0
  183. package/lib/intervalTree.d.mts.map +1 -0
  184. package/lib/intervalTree.mjs +76 -0
  185. package/lib/intervalTree.mjs.map +1 -0
  186. package/lib/intervals/index.d.mts +8 -0
  187. package/lib/intervals/index.d.mts.map +1 -0
  188. package/lib/intervals/index.mjs +8 -0
  189. package/lib/intervals/index.mjs.map +1 -0
  190. package/lib/intervals/interval.d.mts +84 -0
  191. package/lib/intervals/interval.d.mts.map +1 -0
  192. package/lib/intervals/interval.mjs +176 -0
  193. package/lib/intervals/interval.mjs.map +1 -0
  194. package/lib/intervals/intervalUtils.d.mts +240 -0
  195. package/lib/intervals/intervalUtils.d.mts.map +1 -0
  196. package/lib/intervals/intervalUtils.mjs +84 -0
  197. package/lib/intervals/intervalUtils.mjs.map +1 -0
  198. package/lib/intervals/sequenceInterval.d.mts +137 -0
  199. package/lib/intervals/sequenceInterval.d.mts.map +1 -0
  200. package/lib/intervals/sequenceInterval.mjs +370 -0
  201. package/lib/intervals/sequenceInterval.mjs.map +1 -0
  202. package/lib/{localValues.d.ts → localValues.d.mts} +4 -3
  203. package/lib/localValues.d.mts.map +1 -0
  204. package/lib/{localValues.js → localValues.mjs} +2 -2
  205. package/lib/localValues.mjs.map +1 -0
  206. package/lib/{packageVersion.d.ts → packageVersion.d.mts} +2 -2
  207. package/lib/packageVersion.d.mts.map +1 -0
  208. package/lib/{packageVersion.js → packageVersion.mjs} +2 -2
  209. package/lib/packageVersion.mjs.map +1 -0
  210. package/lib/revertibles.d.mts +86 -0
  211. package/lib/revertibles.d.mts.map +1 -0
  212. package/lib/revertibles.mjs +416 -0
  213. package/lib/revertibles.mjs.map +1 -0
  214. package/lib/sequence-alpha.d.mts +1277 -0
  215. package/lib/sequence-beta.d.mts +231 -0
  216. package/lib/sequence-public.d.mts +231 -0
  217. package/lib/sequence-untrimmed.d.mts +1765 -0
  218. package/lib/{sequence.d.ts → sequence.d.mts} +128 -51
  219. package/lib/sequence.d.mts.map +1 -0
  220. package/lib/{sequence.js → sequence.mjs} +229 -152
  221. package/lib/sequence.mjs.map +1 -0
  222. package/lib/{sequenceDeltaEvent.d.ts → sequenceDeltaEvent.d.mts} +25 -8
  223. package/lib/sequenceDeltaEvent.d.mts.map +1 -0
  224. package/lib/{sequenceDeltaEvent.js → sequenceDeltaEvent.mjs} +20 -8
  225. package/lib/sequenceDeltaEvent.mjs.map +1 -0
  226. package/lib/sequenceFactory.d.mts +22 -0
  227. package/lib/sequenceFactory.d.mts.map +1 -0
  228. package/lib/sequenceFactory.mjs +51 -0
  229. package/lib/sequenceFactory.mjs.map +1 -0
  230. package/lib/{sharedIntervalCollection.d.ts → sharedIntervalCollection.d.mts} +13 -13
  231. package/lib/sharedIntervalCollection.d.mts.map +1 -0
  232. package/lib/{sharedIntervalCollection.js → sharedIntervalCollection.mjs} +16 -21
  233. package/lib/sharedIntervalCollection.mjs.map +1 -0
  234. package/lib/{sharedSequence.d.ts → sharedSequence.d.mts} +16 -4
  235. package/lib/sharedSequence.d.mts.map +1 -0
  236. package/lib/{sharedSequence.js → sharedSequence.mjs} +30 -23
  237. package/lib/sharedSequence.mjs.map +1 -0
  238. package/lib/{sharedString.d.ts → sharedString.d.mts} +52 -29
  239. package/lib/sharedString.d.mts.map +1 -0
  240. package/lib/sharedString.mjs +269 -0
  241. package/lib/sharedString.mjs.map +1 -0
  242. package/package.json +168 -75
  243. package/prettier.config.cjs +8 -0
  244. package/src/defaultMap.ts +419 -403
  245. package/src/defaultMapInterfaces.ts +164 -117
  246. package/src/index.ts +86 -26
  247. package/src/intervalCollection.ts +2042 -1563
  248. package/src/intervalIndex/endpointInRangeIndex.ts +116 -0
  249. package/src/intervalIndex/endpointIndex.ts +91 -0
  250. package/src/intervalIndex/idIntervalIndex.ts +64 -0
  251. package/src/intervalIndex/index.ts +25 -0
  252. package/src/intervalIndex/intervalIndex.ts +32 -0
  253. package/src/intervalIndex/intervalIndexUtils.ts +27 -0
  254. package/src/intervalIndex/overlappingIntervalsIndex.ts +187 -0
  255. package/src/intervalIndex/overlappingSequenceIntervalsIndex.ts +80 -0
  256. package/src/intervalIndex/sequenceIntervalIndexes.ts +34 -0
  257. package/src/intervalIndex/startpointInRangeIndex.ts +114 -0
  258. package/src/intervalTree.ts +98 -0
  259. package/src/intervals/index.ts +26 -0
  260. package/src/intervals/interval.ts +238 -0
  261. package/src/intervals/intervalUtils.ts +298 -0
  262. package/src/intervals/sequenceInterval.ts +616 -0
  263. package/src/localValues.ts +68 -73
  264. package/src/packageVersion.ts +1 -1
  265. package/src/revertibles.ts +693 -0
  266. package/src/sequence.ts +850 -690
  267. package/src/sequenceDeltaEvent.ts +164 -131
  268. package/src/sequenceFactory.ts +58 -214
  269. package/src/sharedIntervalCollection.ts +161 -152
  270. package/src/sharedSequence.ts +181 -167
  271. package/src/sharedString.ts +367 -234
  272. package/tsc-multi.test.json +10 -0
  273. package/tsconfig.json +11 -13
  274. package/.editorconfig +0 -7
  275. package/.vscode/launch.json +0 -15
  276. package/dist/defaultMap.js.map +0 -1
  277. package/dist/defaultMapInterfaces.js.map +0 -1
  278. package/dist/index.js +0 -44
  279. package/dist/index.js.map +0 -1
  280. package/dist/intervalCollection.js +0 -1250
  281. package/dist/intervalCollection.js.map +0 -1
  282. package/dist/localValues.js.map +0 -1
  283. package/dist/packageVersion.js.map +0 -1
  284. package/dist/sequence.js.map +0 -1
  285. package/dist/sequenceDeltaEvent.js.map +0 -1
  286. package/dist/sequenceFactory.js +0 -192
  287. package/dist/sequenceFactory.js.map +0 -1
  288. package/dist/sharedIntervalCollection.js.map +0 -1
  289. package/dist/sharedNumberSequence.d.ts +0 -50
  290. package/dist/sharedNumberSequence.d.ts.map +0 -1
  291. package/dist/sharedNumberSequence.js +0 -61
  292. package/dist/sharedNumberSequence.js.map +0 -1
  293. package/dist/sharedObjectSequence.d.ts +0 -50
  294. package/dist/sharedObjectSequence.d.ts.map +0 -1
  295. package/dist/sharedObjectSequence.js +0 -61
  296. package/dist/sharedObjectSequence.js.map +0 -1
  297. package/dist/sharedSequence.js.map +0 -1
  298. package/dist/sharedString.js +0 -187
  299. package/dist/sharedString.js.map +0 -1
  300. package/dist/sparsematrix.d.ts +0 -139
  301. package/dist/sparsematrix.d.ts.map +0 -1
  302. package/dist/sparsematrix.js +0 -332
  303. package/dist/sparsematrix.js.map +0 -1
  304. package/lib/defaultMap.d.ts.map +0 -1
  305. package/lib/defaultMap.js.map +0 -1
  306. package/lib/defaultMapInterfaces.d.ts.map +0 -1
  307. package/lib/defaultMapInterfaces.js.map +0 -1
  308. package/lib/index.d.ts +0 -27
  309. package/lib/index.d.ts.map +0 -1
  310. package/lib/index.js +0 -26
  311. package/lib/index.js.map +0 -1
  312. package/lib/intervalCollection.d.ts +0 -270
  313. package/lib/intervalCollection.d.ts.map +0 -1
  314. package/lib/intervalCollection.js +0 -1238
  315. package/lib/intervalCollection.js.map +0 -1
  316. package/lib/localValues.d.ts.map +0 -1
  317. package/lib/localValues.js.map +0 -1
  318. package/lib/packageVersion.d.ts.map +0 -1
  319. package/lib/packageVersion.js.map +0 -1
  320. package/lib/sequence.d.ts.map +0 -1
  321. package/lib/sequence.js.map +0 -1
  322. package/lib/sequenceDeltaEvent.d.ts.map +0 -1
  323. package/lib/sequenceDeltaEvent.js.map +0 -1
  324. package/lib/sequenceFactory.d.ts +0 -108
  325. package/lib/sequenceFactory.d.ts.map +0 -1
  326. package/lib/sequenceFactory.js +0 -186
  327. package/lib/sequenceFactory.js.map +0 -1
  328. package/lib/sharedIntervalCollection.d.ts.map +0 -1
  329. package/lib/sharedIntervalCollection.js.map +0 -1
  330. package/lib/sharedNumberSequence.d.ts +0 -50
  331. package/lib/sharedNumberSequence.d.ts.map +0 -1
  332. package/lib/sharedNumberSequence.js +0 -57
  333. package/lib/sharedNumberSequence.js.map +0 -1
  334. package/lib/sharedObjectSequence.d.ts +0 -50
  335. package/lib/sharedObjectSequence.d.ts.map +0 -1
  336. package/lib/sharedObjectSequence.js +0 -57
  337. package/lib/sharedObjectSequence.js.map +0 -1
  338. package/lib/sharedSequence.d.ts.map +0 -1
  339. package/lib/sharedSequence.js.map +0 -1
  340. package/lib/sharedString.d.ts.map +0 -1
  341. package/lib/sharedString.js +0 -183
  342. package/lib/sharedString.js.map +0 -1
  343. package/lib/sparsematrix.d.ts +0 -139
  344. package/lib/sparsematrix.d.ts.map +0 -1
  345. package/lib/sparsematrix.js +0 -323
  346. package/lib/sparsematrix.js.map +0 -1
  347. package/src/sharedNumberSequence.ts +0 -62
  348. package/src/sharedObjectSequence.ts +0 -62
  349. package/src/sparsematrix.ts +0 -421
  350. package/tsconfig.esnext.json +0 -7
@@ -4,99 +4,152 @@
4
4
  */
5
5
 
6
6
  /* eslint-disable no-bitwise */
7
+ /* eslint-disable import/no-deprecated */
7
8
 
8
- import { assert, TypedEventEmitter } from "@fluidframework/common-utils";
9
- import { IEvent } from "@fluidframework/common-definitions";
10
- import { UsageError } from "@fluidframework/container-utils";
9
+ import { TypedEventEmitter } from "@fluid-internal/client-utils";
10
+ import { assert, unreachableCase } from "@fluidframework/core-utils";
11
+ import { IEvent } from "@fluidframework/core-interfaces";
11
12
  import {
12
- addProperties,
13
- Client,
14
- ConflictAction,
15
- createMap,
16
- ICombiningOp,
17
- IInterval,
18
- IntervalConflictResolver,
19
- IntervalNode,
20
- IntervalTree,
21
- ISegment,
22
- LocalReference,
23
- MergeTreeDeltaType,
24
- PropertiesManager,
25
- PropertySet,
26
- RedBlackTree,
27
- ReferenceType,
28
- refTypeIncludesFlag,
29
- reservedRangeLabelsKey,
30
- UnassignedSequenceNumber,
13
+ addProperties,
14
+ Client,
15
+ createMap,
16
+ getSlideToSegoff,
17
+ ISegment,
18
+ MergeTreeDeltaType,
19
+ PropertySet,
20
+ LocalReferencePosition,
21
+ ReferenceType,
22
+ refTypeIncludesFlag,
23
+ reservedRangeLabelsKey,
24
+ UnassignedSequenceNumber,
25
+ DetachedReferencePosition,
26
+ UniversalSequenceNumber,
27
+ SlidingPreference,
31
28
  } from "@fluidframework/merge-tree";
32
29
  import { ISequencedDocumentMessage } from "@fluidframework/protocol-definitions";
33
- import { LoggingError } from "@fluidframework/telemetry-utils";
30
+ import { LoggingError, UsageError } from "@fluidframework/telemetry-utils";
34
31
  import { v4 as uuid } from "uuid";
35
32
  import {
36
- IMapMessageLocalMetadata,
37
- IValueFactory,
38
- IValueOpEmitter,
39
- IValueOperation,
40
- IValueType,
41
- IValueTypeOperationValue,
33
+ IMapMessageLocalMetadata,
34
+ IValueFactory,
35
+ IValueOpEmitter,
36
+ IValueOperation,
37
+ IValueType,
38
+ IValueTypeOperationValue,
39
+ SequenceOptions,
42
40
  } from "./defaultMapInterfaces";
41
+ import {
42
+ CompressedSerializedInterval,
43
+ IIntervalHelpers,
44
+ Interval,
45
+ IntervalOpType,
46
+ IntervalStickiness,
47
+ IntervalType,
48
+ ISerializableInterval,
49
+ ISerializedInterval,
50
+ SequenceInterval,
51
+ SerializedIntervalDelta,
52
+ createPositionReferenceFromSegoff,
53
+ endReferenceSlidingPreference,
54
+ startReferenceSlidingPreference,
55
+ sequenceIntervalHelpers,
56
+ createInterval,
57
+ IntervalDeltaOpType,
58
+ } from "./intervals";
59
+ import {
60
+ EndpointIndex,
61
+ IEndpointIndex,
62
+ IIdIntervalIndex,
63
+ IOverlappingIntervalsIndex,
64
+ IntervalIndex,
65
+ OverlappingIntervalsIndex,
66
+ createIdIntervalIndex,
67
+ } from "./intervalIndex";
43
68
 
44
- const reservedIntervalIdKey = "intervalId";
45
-
46
- export enum IntervalType {
47
- Simple = 0x0,
48
- Nest = 0x1,
49
- /**
50
- * SlideOnRemove indicates that the ends of the interval will slide if the segment
51
- * they reference is removed and acked.
52
- * See `packages\dds\merge-tree\REFERENCEPOSITIONS.md` for details
53
- * SlideOnRemove is the default interval behavior and does not need to be specified.
54
- */
55
- SlideOnRemove = 0x2, // SlideOnRemove is default behavior - all intervals are SlideOnRemove
56
- /**
57
- * @internal
58
- * A temporary interval, used internally
59
- */
60
- Transient = 0x4,
61
- }
62
-
63
- export interface ISerializedInterval {
64
- sequenceNumber: number;
65
- start: number;
66
- end: number;
67
- intervalType: IntervalType;
68
- properties?: PropertySet;
69
- }
69
+ /**
70
+ * Defines a position and side relative to a character in a sequence.
71
+ *
72
+ * For this purpose, sequences look like:
73
+ *
74
+ * `{start} - {character 0} - {character 1} - ... - {character N} - {end}`
75
+ *
76
+ * Each `{value}` in the diagram is a character within a sequence.
77
+ * Each `-` in the above diagram is a position where text could be inserted.
78
+ * Each position between a `{value}` and a `-` is a `SequencePlace`.
79
+ *
80
+ * The special endpoints `{start}` and `{end}` refer to positions outside the
81
+ * contents of the string.
82
+ *
83
+ * This gives us 2N + 2 possible positions to refer to within a string, where N
84
+ * is the number of characters.
85
+ *
86
+ * If the position is specified with a bare number, the side defaults to
87
+ * `Side.Before`.
88
+ *
89
+ * If a SequencePlace is the endpoint of a range (e.g. start/end of an interval or search range),
90
+ * the Side value means it is exclusive if it is nearer to the other position and inclusive if it is farther.
91
+ * E.g. the start of a range with Side.After is exclusive of the character at the position.
92
+ * @alpha
93
+ */
94
+ export type SequencePlace = number | "start" | "end" | InteriorSequencePlace;
70
95
 
71
96
  /**
72
- * A size optimization to avoid redundantly storing keys when serializing intervals
73
- * as JSON. Intervals are of the format:
97
+ * A sequence place that does not refer to the special endpoint segments.
74
98
  *
75
- * [start, end, sequenceNumber, intervalType, properties]
99
+ * See {@link SequencePlace} for additional context.
100
+ * @alpha
76
101
  */
77
- export type CompressedSerializedInterval = [number, number, number, IntervalType, PropertySet];
102
+ export interface InteriorSequencePlace {
103
+ pos: number;
104
+ side: Side;
105
+ }
78
106
 
79
107
  /**
80
- * @internal
108
+ * Defines a side relative to a character in a sequence.
109
+ *
110
+ * @remarks See {@link SequencePlace} for additional context on usage.
111
+ * @alpha
81
112
  */
113
+ export enum Side {
114
+ Before = 0,
115
+ After = 1,
116
+ }
117
+
118
+ const reservedIntervalIdKey = "intervalId";
119
+
82
120
  export interface ISerializedIntervalCollectionV2 {
83
- label: string;
84
- version: 2;
85
- intervals: CompressedSerializedInterval[];
121
+ label: string;
122
+ version: 2;
123
+ intervals: CompressedSerializedInterval[];
124
+ }
125
+
126
+ export function sidesFromStickiness(stickiness: IntervalStickiness) {
127
+ const startSide = (stickiness & IntervalStickiness.START) !== 0 ? Side.After : Side.Before;
128
+ const endSide = (stickiness & IntervalStickiness.END) !== 0 ? Side.Before : Side.After;
129
+
130
+ return { startSide, endSide };
86
131
  }
87
132
 
88
133
  /**
89
134
  * Decompress an interval after loading a summary from JSON. The exact format
90
135
  * of this compression is unspecified and subject to change
91
136
  */
92
- function decompressInterval(interval: CompressedSerializedInterval, label?: string): ISerializedInterval {
93
- return {
94
- start: interval[0],
95
- end: interval[1],
96
- sequenceNumber: interval[2],
97
- intervalType: interval[3],
98
- properties: { ...interval[4], [reservedRangeLabelsKey]: label },
99
- };
137
+ function decompressInterval(
138
+ interval: CompressedSerializedInterval,
139
+ label?: string,
140
+ ): ISerializedInterval {
141
+ const stickiness = interval[5] ?? IntervalStickiness.END;
142
+ const { startSide, endSide } = sidesFromStickiness(stickiness);
143
+ return {
144
+ start: interval[0],
145
+ end: interval[1],
146
+ sequenceNumber: interval[2],
147
+ intervalType: interval[3],
148
+ properties: { ...interval[4], [reservedRangeLabelsKey]: [label] },
149
+ stickiness,
150
+ startSide,
151
+ endSide,
152
+ };
100
153
  }
101
154
 
102
155
  /**
@@ -104,1544 +157,1970 @@ function decompressInterval(interval: CompressedSerializedInterval, label?: stri
104
157
  * compression is unspecified and subject to change
105
158
  */
106
159
  function compressInterval(interval: ISerializedInterval): CompressedSerializedInterval {
107
- const { start, end, sequenceNumber, intervalType, properties } = interval;
108
-
109
- return [
110
- start,
111
- end,
112
- sequenceNumber,
113
- intervalType,
114
- // remove the `referenceRangeLabels` property as it is already stored
115
- // in the `label` field of the summary
116
- { ...properties, [reservedRangeLabelsKey]: undefined },
117
- ];
160
+ const { start, end, sequenceNumber, intervalType, properties } = interval;
161
+
162
+ let base: CompressedSerializedInterval = [
163
+ start,
164
+ end,
165
+ sequenceNumber,
166
+ intervalType,
167
+ // remove the `referenceRangeLabels` property as it is already stored
168
+ // in the `label` field of the summary
169
+ { ...properties, [reservedRangeLabelsKey]: undefined },
170
+ ];
171
+
172
+ if (interval.stickiness !== undefined && interval.stickiness !== IntervalStickiness.END) {
173
+ // reassignment to make it easier for typescript to reason about types
174
+ base = [...base, interval.stickiness];
175
+ }
176
+
177
+ return base;
118
178
  }
119
179
 
120
- export interface ISerializableInterval extends IInterval {
121
- properties: PropertySet;
122
- propertyManager: PropertiesManager;
123
- serialize(client: Client): ISerializedInterval;
124
- addProperties(props: PropertySet, collaborating?: boolean, seq?: number):
125
- PropertySet | undefined;
126
- getIntervalId(): string | undefined;
180
+ export function endpointPosAndSide(
181
+ start: SequencePlace | undefined,
182
+ end: SequencePlace | undefined,
183
+ ) {
184
+ const startIsPlainEndpoint = typeof start === "number" || start === "start" || start === "end";
185
+ const endIsPlainEndpoint = typeof end === "number" || end === "start" || end === "end";
186
+
187
+ const startSide = startIsPlainEndpoint ? Side.Before : start?.side;
188
+ const endSide = endIsPlainEndpoint ? Side.Before : end?.side;
189
+
190
+ const startPos = startIsPlainEndpoint ? start : start?.pos;
191
+ const endPos = endIsPlainEndpoint ? end : end?.pos;
192
+
193
+ return {
194
+ startSide,
195
+ endSide,
196
+ startPos,
197
+ endPos,
198
+ };
127
199
  }
128
200
 
129
- export interface IIntervalHelpers<TInterval extends ISerializableInterval> {
130
- compareEnds(a: TInterval, b: TInterval): number;
131
- create(label: string, start: number, end: number,
132
- client: Client, intervalType?: IntervalType, op?: ISequencedDocumentMessage): TInterval;
201
+ function toSequencePlace(pos: number | "start" | "end", side: Side): SequencePlace {
202
+ return typeof pos === "number" ? { pos, side } : pos;
133
203
  }
134
204
 
135
- export class Interval implements ISerializableInterval {
136
- public properties: PropertySet;
137
- public auxProps: PropertySet[];
138
- public propertyManager: PropertiesManager;
139
- constructor(
140
- public start: number,
141
- public end: number,
142
- props?: PropertySet,
143
- ) {
144
- this.propertyManager = new PropertiesManager();
145
- this.properties = {};
146
-
147
- if (props) {
148
- this.addProperties(props);
149
- }
150
- }
151
-
152
- public getIntervalId(): string | undefined {
153
- const id = this.properties?.[reservedIntervalIdKey];
154
- if (id === undefined) {
155
- return undefined;
156
- }
157
- return `${id}`;
158
- }
159
-
160
- public getAdditionalPropertySets() {
161
- return this.auxProps;
162
- }
163
-
164
- public addPropertySet(props: PropertySet) {
165
- if (this.auxProps === undefined) {
166
- this.auxProps = [];
167
- }
168
- this.auxProps.push(props);
169
- }
170
-
171
- public serialize(client: Client): ISerializedInterval {
172
- let seq = 0;
173
- if (client) {
174
- seq = client.getCurrentSeq();
175
- }
176
-
177
- const serializedInterval: ISerializedInterval = {
178
- end: this.end,
179
- intervalType: 0,
180
- sequenceNumber: seq,
181
- start: this.start,
182
- };
183
- if (this.properties) {
184
- serializedInterval.properties = this.properties;
185
- }
186
- return serializedInterval;
187
- }
188
-
189
- public clone() {
190
- return new Interval(this.start, this.end, this.properties);
191
- }
192
-
193
- public compare(b: Interval) {
194
- const startResult = this.compareStart(b);
195
- if (startResult === 0) {
196
- const endResult = this.compareEnd(b);
197
- if (endResult === 0) {
198
- const thisId = this.getIntervalId();
199
- if (thisId) {
200
- const bId = b.getIntervalId();
201
- if (bId) {
202
- return thisId > bId ? 1 : thisId < bId ? -1 : 0;
203
- }
204
- return 0;
205
- }
206
- return 0;
207
- } else {
208
- return endResult;
209
- }
210
- } else {
211
- return startResult;
212
- }
213
- }
214
-
215
- public compareStart(b: Interval) {
216
- return this.start - b.start;
217
- }
218
-
219
- public compareEnd(b: Interval) {
220
- return this.end - b.end;
221
- }
222
-
223
- public overlaps(b: Interval) {
224
- const result = (this.start <= b.end) &&
225
- (this.end >= b.start);
226
- return result;
227
- }
228
-
229
- public union(b: Interval) {
230
- return new Interval(Math.min(this.start, b.start),
231
- Math.max(this.end, b.end), this.properties);
232
- }
233
-
234
- public getProperties() {
235
- return this.properties;
236
- }
237
-
238
- public addProperties(
239
- newProps: PropertySet,
240
- collaborating: boolean = false,
241
- seq?: number,
242
- op?: ICombiningOp,
243
- ): PropertySet | undefined {
244
- if (newProps) {
245
- this.initializeProperties();
246
- return this.propertyManager.addProperties(this.properties, newProps, op, seq, collaborating);
247
- }
248
- }
249
-
250
- public modify(label: string, start: number, end: number, op?: ISequencedDocumentMessage) {
251
- const startPos = start ?? this.start;
252
- const endPos = end ?? this.end;
253
- if (this.start === startPos && this.end === endPos) {
254
- // Return undefined to indicate that no change is necessary.
255
- return;
256
- }
257
- const newInterval = new Interval(startPos, endPos);
258
- if (this.properties) {
259
- newInterval.initializeProperties();
260
- this.propertyManager.copyTo(this.properties, newInterval.properties, newInterval.propertyManager);
261
- }
262
- return newInterval;
263
- }
264
-
265
- private initializeProperties(): void {
266
- if (!this.propertyManager) {
267
- this.propertyManager = new PropertiesManager();
268
- }
269
- if (!this.properties) {
270
- this.properties = createMap<any>();
271
- }
272
- }
205
+ function toOptionalSequencePlace(
206
+ pos: number | "start" | "end" | undefined,
207
+ side: Side = Side.Before,
208
+ ): SequencePlace | undefined {
209
+ return typeof pos === "number" ? { pos, side } : pos;
273
210
  }
274
211
 
275
- export class SequenceInterval implements ISerializableInterval {
276
- public properties: PropertySet;
277
- public propertyManager: PropertiesManager;
278
-
279
- constructor(
280
- public start: LocalReference,
281
- public end: LocalReference,
282
- public intervalType: IntervalType,
283
- props?: PropertySet,
284
- ) {
285
- this.propertyManager = new PropertiesManager();
286
- this.properties = {};
287
-
288
- if (props) {
289
- this.addProperties(props);
290
- }
291
- }
292
-
293
- private callbacks?: Record<"beforePositionChange" | "afterPositionChange", () => void>;
294
-
295
- /**
296
- * @internal
297
- * Subscribes to position change events on this interval if there are no current listeners.
298
- */
299
- public addPositionChangeListeners(beforePositionChange: () => void, afterPositionChange: () => void): void {
300
- if (this.callbacks === undefined) {
301
- this.callbacks = {
302
- beforePositionChange,
303
- afterPositionChange,
304
- };
305
-
306
- const startCbs = this.start.callbacks ??= {};
307
- const endCbs = this.end.callbacks ??= {};
308
- startCbs.beforeSlide = endCbs.beforeSlide = beforePositionChange;
309
- startCbs.afterSlide = endCbs.afterSlide = afterPositionChange;
310
- }
311
- }
312
-
313
- /**
314
- * @internal
315
- * Removes the currently subscribed position change listeners.
316
- */
317
- public removePositionChangeListeners(): void {
318
- if (this.callbacks) {
319
- this.callbacks = undefined;
320
- this.start.callbacks = undefined;
321
- this.end.callbacks = undefined;
322
- }
323
- }
324
-
325
- public serialize(client: Client): ISerializedInterval {
326
- const startPosition = this.start.toPosition();
327
- const endPosition = this.end.toPosition();
328
- const serializedInterval: ISerializedInterval = {
329
- end: endPosition,
330
- intervalType: this.intervalType,
331
- sequenceNumber: client.getCurrentSeq(),
332
- start: startPosition,
333
- };
334
-
335
- if (this.properties) {
336
- serializedInterval.properties = this.properties;
337
- }
338
-
339
- return serializedInterval;
340
- }
341
-
342
- public clone() {
343
- return new SequenceInterval(this.start, this.end, this.intervalType, this.properties);
344
- }
345
-
346
- public compare(b: SequenceInterval) {
347
- const startResult = this.compareStart(b);
348
- if (startResult === 0) {
349
- const endResult = this.compareEnd(b);
350
- if (endResult === 0) {
351
- const thisId = this.getIntervalId();
352
- if (thisId) {
353
- const bId = b.getIntervalId();
354
- if (bId) {
355
- return thisId > bId ? 1 : thisId < bId ? -1 : 0;
356
- }
357
- return 0;
358
- }
359
- return 0;
360
- } else {
361
- return endResult;
362
- }
363
- } else {
364
- return startResult;
365
- }
366
- }
367
-
368
- public compareStart(b: SequenceInterval) {
369
- return this.start.compare(b.start);
370
- }
371
-
372
- public compareEnd(b: SequenceInterval) {
373
- return this.end.compare(b.end);
374
- }
375
-
376
- public overlaps(b: SequenceInterval) {
377
- const result = (this.start.compare(b.end) <= 0) &&
378
- (this.end.compare(b.start) >= 0);
379
- return result;
380
- }
381
-
382
- public getIntervalId(): string | undefined {
383
- const id = this.properties?.[reservedIntervalIdKey];
384
- if (id === undefined) {
385
- return undefined;
386
- }
387
- return `${id}`;
388
- }
389
-
390
- public union(b: SequenceInterval) {
391
- return new SequenceInterval(this.start.min(b.start),
392
- this.end.max(b.end), this.intervalType);
393
- }
394
-
395
- public addProperties(
396
- newProps: PropertySet,
397
- collab: boolean = false,
398
- seq?: number,
399
- op?: ICombiningOp,
400
- ): PropertySet | undefined {
401
- this.initializeProperties();
402
- return this.propertyManager.addProperties(this.properties, newProps, op, seq, collab);
403
- }
404
-
405
- public overlapsPos(bstart: number, bend: number) {
406
- const startPos = this.start.toPosition();
407
- const endPos = this.start.toPosition();
408
- return (endPos > bstart) && (startPos < bend);
409
- }
410
-
411
- public modify(label: string, start: number, end: number, op?: ISequencedDocumentMessage) {
412
- const getRefType = (baseType: ReferenceType): ReferenceType => {
413
- let refType = baseType;
414
- if (op === undefined) {
415
- refType &= ~ReferenceType.SlideOnRemove;
416
- refType |= ReferenceType.StayOnRemove;
417
- }
418
- return refType;
419
- };
420
-
421
- let startRef = this.start;
422
- if (start !== undefined) {
423
- startRef = createPositionReference(this.start.getClient(), start, getRefType(this.start.refType), op);
424
- startRef.addProperties(this.start.properties);
425
- }
426
-
427
- let endRef = this.end;
428
- if (end !== undefined) {
429
- endRef = createPositionReference(this.end.getClient(), end, getRefType(this.end.refType), op);
430
- endRef.addProperties(this.end.properties);
431
- }
432
-
433
- startRef.pairedRef = endRef;
434
- endRef.pairedRef = startRef;
435
-
436
- const newInterval = new SequenceInterval(startRef, endRef, this.intervalType);
437
- if (this.properties) {
438
- newInterval.initializeProperties();
439
- this.propertyManager.copyTo(this.properties, newInterval.properties, newInterval.propertyManager);
440
- }
441
- return newInterval;
442
- }
443
-
444
- private initializeProperties(): void {
445
- if (!this.propertyManager) {
446
- this.propertyManager = new PropertiesManager();
447
- }
448
- if (!this.properties) {
449
- this.properties = createMap<any>();
450
- }
451
- }
452
- }
453
-
454
- function createPositionReferenceFromSegoff(
455
- client: Client,
456
- segoff: { segment: ISegment | undefined; offset: number | undefined; },
457
- refType: ReferenceType,
458
- op?: ISequencedDocumentMessage): LocalReference {
459
- if (segoff.segment) {
460
- const ref = client.createLocalReferencePosition(segoff.segment, segoff.offset, refType, undefined);
461
- return ref as LocalReference;
462
- } else {
463
- if (!op && !refTypeIncludesFlag(refType, ReferenceType.Transient)) {
464
- throw new UsageError("Non-transient references need segment");
465
- }
466
- return new LocalReference(client, undefined, 0, refType);
467
- }
468
- }
212
+ export function computeStickinessFromSide(
213
+ startPos: number | "start" | "end" | undefined = -1,
214
+ startSide: Side = Side.Before,
215
+ endPos: number | "start" | "end" | undefined = -1,
216
+ endSide: Side = Side.Before,
217
+ ): IntervalStickiness {
218
+ let stickiness: IntervalStickiness = IntervalStickiness.NONE;
469
219
 
470
- function createPositionReference(
471
- client: Client,
472
- pos: number,
473
- refType: ReferenceType,
474
- op?: ISequencedDocumentMessage): LocalReference {
475
- let segoff;
476
- if (op) {
477
- assert((refType & ReferenceType.SlideOnRemove) !== 0, 0x2f5 /* op create references must be SlideOnRemove */);
478
- segoff = client.getContainingSegment(pos, op);
479
- segoff = client.getSlideToSegment(segoff);
480
- } else {
481
- assert((refType & ReferenceType.SlideOnRemove) === 0, 0x2f6 /* SlideOnRemove references must be op created */);
482
- segoff = client.getContainingSegment(pos);
483
- }
484
- return createPositionReferenceFromSegoff(client, segoff, refType, op);
485
- }
220
+ if (startSide === Side.After || startPos === "start") {
221
+ stickiness |= IntervalStickiness.START;
222
+ }
486
223
 
487
- function createSequenceInterval(
488
- label: string,
489
- start: number,
490
- end: number,
491
- client: Client,
492
- intervalType?: IntervalType,
493
- op?: ISequencedDocumentMessage): SequenceInterval {
494
- let beginRefType = ReferenceType.RangeBegin;
495
- let endRefType = ReferenceType.RangeEnd;
496
- if (intervalType === IntervalType.Transient) {
497
- beginRefType = ReferenceType.Transient;
498
- endRefType = ReferenceType.Transient;
499
- } else {
500
- if (intervalType === IntervalType.Nest) {
501
- beginRefType = ReferenceType.NestBegin;
502
- endRefType = ReferenceType.NestEnd;
503
- }
504
- // All non-transient interval references must eventually be SlideOnRemove
505
- // To ensure eventual consistency, they must start as StayOnRemove when
506
- // pending (created locally and creation op is not acked)
507
- if (op) {
508
- beginRefType |= ReferenceType.SlideOnRemove;
509
- endRefType |= ReferenceType.SlideOnRemove;
510
- } else {
511
- beginRefType |= ReferenceType.StayOnRemove;
512
- endRefType |= ReferenceType.StayOnRemove;
513
- }
514
- }
515
-
516
- const startLref = createPositionReference(client, start, beginRefType, op);
517
- const endLref = createPositionReference(client, end, endRefType, op);
518
- startLref.pairedRef = endLref;
519
- endLref.pairedRef = startLref;
520
- const rangeProp = {
521
- [reservedRangeLabelsKey]: [label],
522
- };
523
- startLref.addProperties(rangeProp);
524
- endLref.addProperties(rangeProp);
525
-
526
- const ival = new SequenceInterval(startLref, endLref, intervalType, rangeProp);
527
- return ival;
528
- }
224
+ if (endSide === Side.Before || endPos === "end") {
225
+ stickiness |= IntervalStickiness.END;
226
+ }
529
227
 
530
- export function defaultIntervalConflictResolver(a: Interval, b: Interval) {
531
- a.addPropertySet(b.properties);
532
- return a;
228
+ return stickiness as IntervalStickiness;
533
229
  }
534
230
 
535
- export function createIntervalIndex(conflict?: IntervalConflictResolver<Interval>) {
536
- const helpers: IIntervalHelpers<Interval> = {
537
- compareEnds: compareIntervalEnds,
538
- create: createInterval,
539
- };
540
- const lc = new LocalIntervalCollection<Interval>(undefined, "", helpers);
541
- if (conflict) {
542
- lc.addConflictResolver(conflict);
543
- } else {
544
- lc.addConflictResolver(defaultIntervalConflictResolver);
545
- }
546
- return lc;
231
+ export function createIntervalIndex() {
232
+ const helpers: IIntervalHelpers<Interval> = {
233
+ create: createInterval,
234
+ };
235
+ const lc = new LocalIntervalCollection<Interval>(undefined as any as Client, "", helpers, {});
236
+ return lc;
547
237
  }
548
238
 
549
239
  export class LocalIntervalCollection<TInterval extends ISerializableInterval> {
550
- private readonly intervalTree = new IntervalTree<TInterval>();
551
- private readonly endIntervalTree: RedBlackTree<TInterval, TInterval>;
552
- private readonly intervalIdMap: Map<string, TInterval> = new Map();
553
- private conflictResolver: IntervalConflictResolver<TInterval> | undefined;
554
- private endConflictResolver: ConflictAction<TInterval, TInterval> | undefined;
555
-
556
- private static readonly legacyIdPrefix = "legacy";
557
-
558
- constructor(
559
- private readonly client: Client,
560
- private readonly label: string,
561
- private readonly helpers: IIntervalHelpers<TInterval>,
562
- /** Callback invoked each time one of the endpoints of an interval slides. */
563
- private readonly onPositionChange?: (interval: TInterval) => void,
564
- ) {
565
- // eslint-disable-next-line @typescript-eslint/unbound-method
566
- this.endIntervalTree = new RedBlackTree<TInterval, TInterval>(helpers.compareEnds);
567
- }
568
-
569
- public addConflictResolver(conflictResolver: IntervalConflictResolver<TInterval>) {
570
- this.conflictResolver = conflictResolver;
571
- this.endConflictResolver =
572
- (key: TInterval, currentKey: TInterval) => {
573
- const ival = conflictResolver(key, currentKey);
574
- return {
575
- data: ival,
576
- key: ival,
577
- };
578
- };
579
- }
580
-
581
- public map(fn: (interval: TInterval) => void) {
582
- this.intervalTree.map(fn);
583
- }
584
-
585
- public createLegacyId(start: number, end: number): string {
586
- // Create a non-unique ID based on start and end to be used on intervals that come from legacy clients
587
- // without ID's.
588
- return `${LocalIntervalCollection.legacyIdPrefix}${start}-${end}`;
589
- }
590
-
591
- /**
592
- * Validates that a serialized interval has the ID property. Creates an ID
593
- * if one does not already exist
594
- *
595
- * @param serializedInterval - The interval to be checked
596
- * @returns The interval's existing or newly created id
597
- */
598
- public ensureSerializedId(serializedInterval: ISerializedInterval): string {
599
- let id: string | undefined = serializedInterval.properties?.[reservedIntervalIdKey];
600
- if (id === undefined) {
601
- // An interval came over the wire without an ID, so create a non-unique one based on start/end.
602
- // This will allow all clients to refer to this interval consistently.
603
- id = this.createLegacyId(serializedInterval.start, serializedInterval.end);
604
- const newProps = {
605
- [reservedIntervalIdKey]: id,
606
- };
607
- serializedInterval.properties = addProperties(serializedInterval.properties, newProps);
608
- }
609
- // Make the ID immutable for safety's sake.
610
- Object.defineProperty(serializedInterval.properties, reservedIntervalIdKey, {
611
- configurable: false,
612
- enumerable: true,
613
- writable: false,
614
- });
615
-
616
- return id;
617
- }
618
-
619
- public mapUntil(fn: (interval: TInterval) => boolean) {
620
- this.intervalTree.mapUntil(fn);
621
- }
622
-
623
- public gatherIterationResults(
624
- results: TInterval[],
625
- iteratesForward: boolean,
626
- start?: number,
627
- end?: number) {
628
- if (this.intervalTree.intervals.isEmpty()) {
629
- return;
630
- }
631
-
632
- if (start === undefined && end === undefined) {
633
- // No start/end provided. Gather the whole tree in the specified order.
634
- if (iteratesForward) {
635
- this.intervalTree.map((interval: TInterval) => {
636
- results.push(interval);
637
- });
638
- } else {
639
- this.intervalTree.mapBackward((interval: TInterval) => {
640
- results.push(interval);
641
- });
642
- }
643
- } else {
644
- const transientInterval: TInterval = this.helpers.create(
645
- "transient",
646
- start,
647
- end,
648
- this.client,
649
- IntervalType.Transient,
650
- );
651
-
652
- if (start === undefined) {
653
- // Only end position provided. Since the tree is not sorted by end position,
654
- // walk the whole tree in the specified order, gathering intervals that match the end.
655
- if (iteratesForward) {
656
- this.intervalTree.map((interval: TInterval) => {
657
- if (transientInterval.compareEnd(interval) === 0) {
658
- results.push(interval);
659
- }
660
- });
661
- } else {
662
- this.intervalTree.mapBackward((interval: TInterval) => {
663
- if (transientInterval.compareEnd(interval) === 0) {
664
- results.push(interval);
665
- }
666
- });
667
- }
668
- } else {
669
- // Start and (possibly) end provided. Walk the subtrees that may contain
670
- // this start position.
671
- const compareFn =
672
- end === undefined ?
673
- (node: IntervalNode<TInterval>) => {
674
- return transientInterval.compareStart(node.key);
675
- } :
676
- (node: IntervalNode<TInterval>) => {
677
- return transientInterval.compare(node.key);
678
- };
679
- const continueLeftFn = (cmpResult: number) => cmpResult <= 0;
680
- const continueRightFn = (cmpResult: number) => cmpResult >= 0;
681
- const actionFn = (node: IntervalNode<TInterval>) => {
682
- results.push(node.key);
683
- };
684
-
685
- if (iteratesForward) {
686
- this.intervalTree.intervals.walkExactMatchesForward(
687
- compareFn, actionFn, continueLeftFn, continueRightFn,
688
- );
689
- } else {
690
- this.intervalTree.intervals.walkExactMatchesBackward(
691
- compareFn, actionFn, continueLeftFn, continueRightFn,
692
- );
693
- }
694
- }
695
- }
696
- }
697
-
698
- public findOverlappingIntervals(startPosition: number, endPosition: number) {
699
- if (endPosition < startPosition || this.intervalTree.intervals.isEmpty()) {
700
- return [];
701
- }
702
- const transientInterval =
703
- this.helpers.create(
704
- "transient",
705
- startPosition,
706
- endPosition,
707
- this.client,
708
- IntervalType.Transient);
709
-
710
- const overlappingIntervalNodes = this.intervalTree.match(transientInterval);
711
- return overlappingIntervalNodes.map((node) => node.key);
712
- }
713
-
714
- public previousInterval(pos: number) {
715
- const transientInterval = this.helpers.create(
716
- "transient", pos, pos, this.client, IntervalType.Transient);
717
- const rbNode = this.endIntervalTree.floor(transientInterval);
718
- if (rbNode) {
719
- return rbNode.data;
720
- }
721
- }
722
-
723
- public nextInterval(pos: number) {
724
- const transientInterval = this.helpers.create(
725
- "transient", pos, pos, this.client, IntervalType.Transient);
726
- const rbNode = this.endIntervalTree.ceil(transientInterval);
727
- if (rbNode) {
728
- return rbNode.data;
729
- }
730
- }
731
-
732
- public removeInterval(startPosition: number, endPosition: number) {
733
- const transientInterval = this.helpers.create(
734
- "transient", startPosition, endPosition, this.client, IntervalType.Transient);
735
- this.intervalTree.remove(transientInterval);
736
- this.endIntervalTree.remove(transientInterval);
737
- return transientInterval;
738
- }
739
-
740
- private removeIntervalFromIndex(interval: TInterval) {
741
- this.intervalTree.removeExisting(interval);
742
- this.endIntervalTree.remove(interval);
743
-
744
- const id = interval.getIntervalId();
745
-
746
- assert(id !== undefined, 0x311 /* expected id to exist on interval */);
747
-
748
- this.intervalIdMap.delete(id);
749
- }
750
-
751
- public removeExistingInterval(interval: TInterval) {
752
- this.removeIntervalFromIndex(interval);
753
- this.removeIntervalListeners(interval);
754
- }
755
-
756
- public createInterval(
757
- start: number,
758
- end: number,
759
- intervalType: IntervalType,
760
- op?: ISequencedDocumentMessage): TInterval {
761
- return this.helpers.create(this.label, start, end, this.client, intervalType, op);
762
- }
763
-
764
- public addInterval(
765
- start: number,
766
- end: number,
767
- intervalType: IntervalType,
768
- props?: PropertySet,
769
- op?: ISequencedDocumentMessage) {
770
- const interval: TInterval = this.createInterval(start, end, intervalType, op);
771
- if (interval) {
772
- if (!interval.properties) {
773
- interval.properties = createMap<any>();
774
- }
775
- if (props) {
776
- interval.addProperties(props);
777
- }
778
- if (interval.properties[reservedIntervalIdKey] === undefined) {
779
- // Create a new ID.
780
- interval.properties[reservedIntervalIdKey] = uuid();
781
- }
782
- this.add(interval);
783
- }
784
- return interval;
785
- }
786
-
787
- private addIntervalToIndex(interval: TInterval) {
788
- const id = interval.getIntervalId();
789
- assert(id !== undefined, 0x2c0 /* "ID must be created before adding interval to collection" */);
790
- // Make the ID immutable.
791
- Object.defineProperty(interval.properties, reservedIntervalIdKey, {
792
- configurable: false,
793
- enumerable: true,
794
- writable: false,
795
- });
796
- this.intervalTree.put(interval, this.conflictResolver);
797
- this.endIntervalTree.put(interval, interval, this.endConflictResolver);
798
- this.intervalIdMap.set(id, interval);
799
- }
800
-
801
- public add(interval: TInterval) {
802
- this.addIntervalToIndex(interval);
803
- this.addIntervalListeners(interval);
804
- }
805
-
806
- public getIntervalById(id: string) {
807
- return this.intervalIdMap.get(id);
808
- }
809
-
810
- public changeInterval(interval: TInterval, start: number, end: number, op?: ISequencedDocumentMessage) {
811
- const newInterval = interval.modify(this.label, start, end, op) as TInterval | undefined;
812
- if (newInterval) {
813
- this.removeExistingInterval(interval);
814
- this.add(newInterval);
815
- }
816
- return newInterval;
817
- }
818
-
819
- public serialize(): ISerializedIntervalCollectionV2 {
820
- const client = this.client;
821
- const intervals = this.intervalTree.intervals.keys();
822
-
823
- return {
824
- label: this.label,
825
- intervals: intervals.map((interval) => compressInterval(interval.serialize(client))),
826
- version: 2,
827
- };
828
- }
829
-
830
- private addIntervalListeners(interval: TInterval) {
831
- if (interval instanceof SequenceInterval) {
832
- interval.addPositionChangeListeners(
833
- () => this.removeIntervalFromIndex(interval),
834
- () => {
835
- this.addIntervalToIndex(interval);
836
- this.onPositionChange?.(interval);
837
- },
838
- );
839
- }
840
- }
841
-
842
- private removeIntervalListeners(interval: TInterval) {
843
- if (interval instanceof SequenceInterval) {
844
- interval.removePositionChangeListeners();
845
- }
846
- }
240
+ private static readonly legacyIdPrefix = "legacy";
241
+ public readonly overlappingIntervalsIndex: IOverlappingIntervalsIndex<TInterval>;
242
+ public readonly idIntervalIndex: IIdIntervalIndex<TInterval>;
243
+ public readonly endIntervalIndex: IEndpointIndex<TInterval>;
244
+ private readonly indexes: Set<IntervalIndex<TInterval>>;
245
+
246
+ constructor(
247
+ private readonly client: Client,
248
+ private readonly label: string,
249
+ private readonly helpers: IIntervalHelpers<TInterval>,
250
+ private readonly options: Partial<SequenceOptions>,
251
+ /** Callback invoked each time one of the endpoints of an interval slides. */
252
+ private readonly onPositionChange?: (
253
+ interval: TInterval,
254
+ previousInterval: TInterval,
255
+ ) => void,
256
+ ) {
257
+ this.overlappingIntervalsIndex = new OverlappingIntervalsIndex(client, helpers);
258
+ this.idIntervalIndex = createIdIntervalIndex<TInterval>();
259
+ this.endIntervalIndex = new EndpointIndex(client, helpers);
260
+ this.indexes = new Set([
261
+ this.overlappingIntervalsIndex,
262
+ this.idIntervalIndex,
263
+ this.endIntervalIndex,
264
+ ]);
265
+ }
266
+
267
+ public createLegacyId(start: number | "start" | "end", end: number | "start" | "end"): string {
268
+ // Create a non-unique ID based on start and end to be used on intervals that come from legacy clients
269
+ // without ID's.
270
+ return `${LocalIntervalCollection.legacyIdPrefix}${start}-${end}`;
271
+ }
272
+
273
+ /**
274
+ * Validates that a serialized interval has the ID property. Creates an ID
275
+ * if one does not already exist
276
+ *
277
+ * @param serializedInterval - The interval to be checked
278
+ * @returns The interval's existing or newly created id
279
+ */
280
+ public ensureSerializedId(serializedInterval: ISerializedInterval): string {
281
+ let id: string | undefined = serializedInterval.properties?.[reservedIntervalIdKey];
282
+ if (id === undefined) {
283
+ // Back-compat: 0.39 and earlier did not have IDs on intervals. If an interval from such a client
284
+ // comes over the wire, create a non-unique one based on start/end.
285
+ // This will allow all clients to refer to this interval consistently.
286
+ id = this.createLegacyId(serializedInterval.start, serializedInterval.end);
287
+ const newProps = {
288
+ [reservedIntervalIdKey]: id,
289
+ };
290
+ serializedInterval.properties = addProperties(serializedInterval.properties, newProps);
291
+ }
292
+ // Make the ID immutable for safety's sake.
293
+ Object.defineProperty(serializedInterval.properties, reservedIntervalIdKey, {
294
+ configurable: false,
295
+ enumerable: true,
296
+ writable: false,
297
+ });
298
+
299
+ return id;
300
+ }
301
+
302
+ private removeIntervalFromIndexes(interval: TInterval) {
303
+ for (const index of this.indexes) {
304
+ index.remove(interval);
305
+ }
306
+ }
307
+
308
+ public appendIndex(index: IntervalIndex<TInterval>) {
309
+ this.indexes.add(index);
310
+ }
311
+
312
+ public removeIndex(index: IntervalIndex<TInterval>): boolean {
313
+ return this.indexes.delete(index);
314
+ }
315
+
316
+ public removeExistingInterval(interval: TInterval) {
317
+ this.removeIntervalFromIndexes(interval);
318
+ this.removeIntervalListeners(interval);
319
+ }
320
+
321
+ public createInterval(
322
+ start: SequencePlace,
323
+ end: SequencePlace,
324
+ intervalType: IntervalType,
325
+ op?: ISequencedDocumentMessage,
326
+ ): TInterval {
327
+ return this.helpers.create(
328
+ this.label,
329
+ start,
330
+ end,
331
+ this.client,
332
+ intervalType,
333
+ op,
334
+ undefined,
335
+ this.options.mergeTreeReferencesCanSlideToEndpoint,
336
+ );
337
+ }
338
+
339
+ public addInterval(
340
+ start: SequencePlace,
341
+ end: SequencePlace,
342
+ intervalType: IntervalType,
343
+ props?: PropertySet,
344
+ op?: ISequencedDocumentMessage,
345
+ ) {
346
+ const interval: TInterval = this.createInterval(start, end, intervalType, op);
347
+ if (interval) {
348
+ if (!interval.properties) {
349
+ interval.properties = createMap<any>();
350
+ }
351
+
352
+ if (props) {
353
+ // This check is intended to prevent scenarios where a random interval is created and then
354
+ // inserted into a collection. The aim is to ensure that the collection is created first
355
+ // then the user can create/add intervals based on the collection
356
+ if (
357
+ props[reservedRangeLabelsKey] !== undefined &&
358
+ props[reservedRangeLabelsKey][0] !== this.label
359
+ ) {
360
+ throw new LoggingError(
361
+ "Adding an interval that belongs to another interval collection is not permitted",
362
+ );
363
+ }
364
+ interval.addProperties(props);
365
+ }
366
+ interval.properties[reservedIntervalIdKey] ??= uuid();
367
+ this.add(interval);
368
+ }
369
+ return interval;
370
+ }
371
+
372
+ private linkEndpointsToInterval(interval: TInterval): void {
373
+ if (interval instanceof SequenceInterval) {
374
+ interval.start.addProperties({ interval });
375
+ interval.end.addProperties({ interval });
376
+ }
377
+ }
378
+
379
+ private addIntervalToIndexes(interval: TInterval) {
380
+ for (const index of this.indexes) {
381
+ index.add(interval);
382
+ }
383
+ }
384
+
385
+ public add(interval: TInterval): void {
386
+ this.linkEndpointsToInterval(interval);
387
+ this.addIntervalToIndexes(interval);
388
+ this.addIntervalListeners(interval);
389
+ }
390
+
391
+ public changeInterval(
392
+ interval: TInterval,
393
+ start: SequencePlace | undefined,
394
+ end: SequencePlace | undefined,
395
+ op?: ISequencedDocumentMessage,
396
+ localSeq?: number,
397
+ ) {
398
+ const newInterval = interval.modify(
399
+ this.label,
400
+ start,
401
+ end,
402
+ op,
403
+ localSeq,
404
+ this.options.mergeTreeReferencesCanSlideToEndpoint,
405
+ ) as TInterval | undefined;
406
+ if (newInterval) {
407
+ this.removeExistingInterval(interval);
408
+ this.add(newInterval);
409
+ }
410
+ return newInterval;
411
+ }
412
+
413
+ public serialize(): ISerializedIntervalCollectionV2 {
414
+ return {
415
+ label: this.label,
416
+ intervals: Array.from(this.idIntervalIndex, (interval) =>
417
+ compressInterval(interval.serialize()),
418
+ ),
419
+ version: 2,
420
+ };
421
+ }
422
+
423
+ private addIntervalListeners(interval: TInterval) {
424
+ const cloneRef = (ref: LocalReferencePosition) => {
425
+ const segment = ref.getSegment();
426
+ if (segment === undefined) {
427
+ // Cloning is unnecessary: refs which have slid off the string entirely
428
+ // never get slid back on. Creation code for refs doesn't accept undefined segment
429
+ // either, so this must be special-cased.
430
+ return ref;
431
+ }
432
+
433
+ return this.client.createLocalReferencePosition(
434
+ segment,
435
+ ref.getOffset(),
436
+ ReferenceType.Transient,
437
+ ref.properties,
438
+ ref.slidingPreference,
439
+ ref.canSlideToEndpoint,
440
+ );
441
+ };
442
+ if (interval instanceof SequenceInterval) {
443
+ let previousInterval: (TInterval & SequenceInterval) | undefined;
444
+ let pendingChanges = 0;
445
+ interval.addPositionChangeListeners(
446
+ () => {
447
+ pendingChanges++;
448
+ // Note: both start and end can change and invoke beforeSlide on each endpoint before afterSlide.
449
+ if (!previousInterval) {
450
+ previousInterval = interval.clone() as TInterval & SequenceInterval;
451
+ previousInterval.start = cloneRef(previousInterval.start);
452
+ previousInterval.end = cloneRef(previousInterval.end);
453
+ this.removeIntervalFromIndexes(interval);
454
+ }
455
+ },
456
+ () => {
457
+ assert(
458
+ previousInterval !== undefined,
459
+ 0x3fa /* Invalid interleaving of before/after slide */,
460
+ );
461
+ pendingChanges--;
462
+ if (pendingChanges === 0) {
463
+ this.addIntervalToIndexes(interval);
464
+ this.onPositionChange?.(interval, previousInterval);
465
+ previousInterval = undefined;
466
+ }
467
+ },
468
+ );
469
+ }
470
+ }
471
+
472
+ private removeIntervalListeners(interval: TInterval) {
473
+ if (interval instanceof SequenceInterval) {
474
+ interval.removePositionChangeListeners();
475
+ }
476
+ }
847
477
  }
848
478
 
849
- const compareSequenceIntervalEnds = (a: SequenceInterval, b: SequenceInterval): number => a.end.compare(b.end);
850
-
851
479
  class SequenceIntervalCollectionFactory
852
- implements IValueFactory<IntervalCollection<SequenceInterval>> {
853
- public load(
854
- emitter: IValueOpEmitter,
855
- raw: ISerializedInterval[] | ISerializedIntervalCollectionV2 = [],
856
- ): IntervalCollection<SequenceInterval> {
857
- const helpers: IIntervalHelpers<SequenceInterval> = {
858
- compareEnds: compareSequenceIntervalEnds,
859
- create: createSequenceInterval,
860
- };
861
- return new IntervalCollection<SequenceInterval>(helpers, true, emitter, raw);
862
- }
863
-
864
- public store(value: IntervalCollection<SequenceInterval>): ISerializedIntervalCollectionV2 {
865
- return value.serializeInternal();
866
- }
480
+ implements IValueFactory<IntervalCollection<SequenceInterval>>
481
+ {
482
+ public load(
483
+ emitter: IValueOpEmitter,
484
+ raw: ISerializedInterval[] | ISerializedIntervalCollectionV2 = [],
485
+ options?: Partial<SequenceOptions>,
486
+ ): IntervalCollection<SequenceInterval> {
487
+ return new IntervalCollection<SequenceInterval>(
488
+ sequenceIntervalHelpers,
489
+ true,
490
+ emitter,
491
+ raw,
492
+ options,
493
+ );
494
+ }
495
+
496
+ public store(
497
+ value: IntervalCollection<SequenceInterval>,
498
+ ): ISerializedInterval[] | ISerializedIntervalCollectionV2 {
499
+ return value.serializeInternal();
500
+ }
867
501
  }
868
502
 
869
503
  export class SequenceIntervalCollectionValueType
870
- implements IValueType<IntervalCollection<SequenceInterval>> {
871
- public static Name = "sharedStringIntervalCollection";
504
+ implements IValueType<IntervalCollection<SequenceInterval>>
505
+ {
506
+ public static Name = "sharedStringIntervalCollection";
507
+
508
+ public get name(): string {
509
+ return SequenceIntervalCollectionValueType.Name;
510
+ }
872
511
 
873
- public get name(): string {
874
- return SequenceIntervalCollectionValueType.Name;
875
- }
512
+ public get factory(): IValueFactory<IntervalCollection<SequenceInterval>> {
513
+ return SequenceIntervalCollectionValueType._factory;
514
+ }
876
515
 
877
- public get factory(): IValueFactory<IntervalCollection<SequenceInterval>> {
878
- return SequenceIntervalCollectionValueType._factory;
879
- }
516
+ public get ops(): Map<IntervalOpType, IValueOperation<IntervalCollection<SequenceInterval>>> {
517
+ return SequenceIntervalCollectionValueType._ops;
518
+ }
880
519
 
881
- public get ops(): Map<string, IValueOperation<IntervalCollection<SequenceInterval>>> {
882
- return SequenceIntervalCollectionValueType._ops;
883
- }
520
+ private static readonly _factory: IValueFactory<IntervalCollection<SequenceInterval>> =
521
+ new SequenceIntervalCollectionFactory();
884
522
 
885
- private static readonly _factory: IValueFactory<IntervalCollection<SequenceInterval>> =
886
- new SequenceIntervalCollectionFactory();
523
+ private static readonly _ops = makeOpsMap<SequenceInterval>();
524
+ }
887
525
 
888
- private static readonly _ops = makeOpsMap<SequenceInterval>();
526
+ class IntervalCollectionFactory implements IValueFactory<IntervalCollection<Interval>> {
527
+ public load(
528
+ emitter: IValueOpEmitter,
529
+ raw: ISerializedInterval[] | ISerializedIntervalCollectionV2 = [],
530
+ options?: Partial<SequenceOptions>,
531
+ ): IntervalCollection<Interval> {
532
+ const helpers: IIntervalHelpers<Interval> = {
533
+ create: createInterval,
534
+ };
535
+ const collection = new IntervalCollection<Interval>(helpers, false, emitter, raw, options);
536
+ collection.attachGraph(undefined as any as Client, "");
537
+ return collection;
538
+ }
539
+
540
+ public store(value: IntervalCollection<Interval>): ISerializedIntervalCollectionV2 {
541
+ return value.serializeInternal();
542
+ }
889
543
  }
890
544
 
891
- const compareIntervalEnds = (a: Interval, b: Interval) => a.end - b.end;
545
+ export class IntervalCollectionValueType implements IValueType<IntervalCollection<Interval>> {
546
+ public static Name = "sharedIntervalCollection";
547
+
548
+ public get name(): string {
549
+ return IntervalCollectionValueType.Name;
550
+ }
892
551
 
893
- function createInterval(label: string, start: number, end: number, client: Client): Interval {
894
- const rangeProp: PropertySet = {};
552
+ public get factory(): IValueFactory<IntervalCollection<Interval>> {
553
+ return IntervalCollectionValueType._factory;
554
+ }
895
555
 
896
- if (label && label.length > 0) {
897
- rangeProp[reservedRangeLabelsKey] = [label];
898
- }
556
+ public get ops(): Map<IntervalOpType, IValueOperation<IntervalCollection<Interval>>> {
557
+ return IntervalCollectionValueType._ops;
558
+ }
899
559
 
900
- return new Interval(start, end, rangeProp);
560
+ private static readonly _factory: IValueFactory<IntervalCollection<Interval>> =
561
+ new IntervalCollectionFactory();
562
+ private static readonly _ops = makeOpsMap<Interval>();
901
563
  }
902
564
 
903
- class IntervalCollectionFactory
904
- implements IValueFactory<IntervalCollection<Interval>> {
905
- public load(
906
- emitter: IValueOpEmitter,
907
- raw: ISerializedInterval[] | ISerializedIntervalCollectionV2 = [],
908
- ): IntervalCollection<Interval> {
909
- const helpers: IIntervalHelpers<Interval> = {
910
- compareEnds: compareIntervalEnds,
911
- create: createInterval,
912
- };
913
- const collection = new IntervalCollection<Interval>(helpers, false, emitter, raw);
914
- collection.attachGraph(undefined, "");
915
- return collection;
916
- }
917
-
918
- public store(value: IntervalCollection<Interval>): ISerializedIntervalCollectionV2 {
919
- return value.serializeInternal();
920
- }
565
+ export function makeOpsMap<T extends ISerializableInterval>(): Map<
566
+ IntervalOpType,
567
+ IValueOperation<IntervalCollection<T>>
568
+ > {
569
+ const rebase: IValueOperation<IntervalCollection<T>>["rebase"] = (
570
+ collection,
571
+ op,
572
+ localOpMetadata,
573
+ ) => {
574
+ const { localSeq } = localOpMetadata;
575
+ const rebasedValue = collection.rebaseLocalInterval(op.opName, op.value, localSeq);
576
+ if (rebasedValue === undefined) {
577
+ return undefined;
578
+ }
579
+ const rebasedOp = { ...op, value: rebasedValue };
580
+ return { rebasedOp, rebasedLocalOpMetadata: localOpMetadata };
581
+ };
582
+
583
+ const applyStashedOp: IValueOperation<IntervalCollection<T>>["applyStashedOp"] = (
584
+ collection,
585
+ op,
586
+ ) => {
587
+ return collection.applyStashedOp(op);
588
+ };
589
+
590
+ return new Map<IntervalOpType, IValueOperation<IntervalCollection<T>>>([
591
+ [
592
+ IntervalOpType.ADD,
593
+ {
594
+ process: (collection, params, local, op, localOpMetadata) => {
595
+ // if params is undefined, the interval was deleted during
596
+ // rebasing
597
+ if (!params) {
598
+ return;
599
+ }
600
+ assert(op !== undefined, 0x3fb /* op should exist here */);
601
+ collection.ackAdd(params, local, op, localOpMetadata);
602
+ },
603
+ rebase,
604
+ applyStashedOp,
605
+ },
606
+ ],
607
+ [
608
+ IntervalOpType.DELETE,
609
+ {
610
+ process: (collection, params, local, op) => {
611
+ assert(op !== undefined, 0x3fc /* op should exist here */);
612
+ collection.ackDelete(params, local, op);
613
+ },
614
+ rebase: (collection, op, localOpMetadata) => {
615
+ // Deletion of intervals is based on id, so requires no rebasing.
616
+ return { rebasedOp: op, rebasedLocalOpMetadata: localOpMetadata };
617
+ },
618
+ applyStashedOp,
619
+ },
620
+ ],
621
+ [
622
+ IntervalOpType.CHANGE,
623
+ {
624
+ process: (collection, params, local, op, localOpMetadata) => {
625
+ // if params is undefined, the interval was deleted during
626
+ // rebasing
627
+ if (!params) {
628
+ return;
629
+ }
630
+ assert(op !== undefined, 0x3fd /* op should exist here */);
631
+ collection.ackChange(params, local, op, localOpMetadata);
632
+ },
633
+ rebase,
634
+ applyStashedOp,
635
+ },
636
+ ],
637
+ ]);
921
638
  }
922
639
 
923
- export class IntervalCollectionValueType
924
- implements IValueType<IntervalCollection<Interval>> {
925
- public static Name = "sharedIntervalCollection";
640
+ /**
641
+ * @alpha
642
+ */
643
+ export type DeserializeCallback = (properties: PropertySet) => void;
926
644
 
927
- public get name(): string {
928
- return IntervalCollectionValueType.Name;
929
- }
645
+ class IntervalCollectionIterator<TInterval extends ISerializableInterval>
646
+ implements Iterator<TInterval>
647
+ {
648
+ private readonly results: TInterval[];
649
+ private index: number;
650
+
651
+ constructor(
652
+ collection: IntervalCollection<TInterval>,
653
+ iteratesForward: boolean = true,
654
+ start?: number,
655
+ end?: number,
656
+ ) {
657
+ this.results = [];
658
+ this.index = 0;
659
+
660
+ collection.gatherIterationResults(this.results, iteratesForward, start, end);
661
+ }
662
+
663
+ public next(): IteratorResult<TInterval> {
664
+ if (this.index < this.results.length) {
665
+ return {
666
+ value: this.results[this.index++],
667
+ done: false,
668
+ };
669
+ }
670
+
671
+ return {
672
+ value: undefined,
673
+ done: true,
674
+ };
675
+ }
676
+ }
930
677
 
931
- public get factory(): IValueFactory<IntervalCollection<Interval>> {
932
- return IntervalCollectionValueType._factory;
933
- }
678
+ /**
679
+ * Change events emitted by `IntervalCollection`s
680
+ * @alpha
681
+ */
682
+ export interface IIntervalCollectionEvent<TInterval extends ISerializableInterval> extends IEvent {
683
+ /**
684
+ * This event is invoked whenever the endpoints of an interval may have changed.
685
+ * This can happen on:
686
+ * - local endpoint modification
687
+ * - ack of a remote endpoint modification
688
+ * - position change due to segment sliding (slides due to mergeTree segment deletion will always appear local)
689
+ * The `interval` argument reflects the new values.
690
+ * `previousInterval` contains transient `ReferencePosition`s at the same location as the interval's original
691
+ * endpoints. These references should be used for position information only.
692
+ * `local` reflects whether the change originated locally.
693
+ * `op` is defined if and only if the server has acked this change.
694
+ * `slide` is true if the change is due to sliding on removal of position
695
+ */
696
+ (
697
+ event: "changeInterval",
698
+ listener: (
699
+ interval: TInterval,
700
+ previousInterval: TInterval,
701
+ local: boolean,
702
+ op: ISequencedDocumentMessage | undefined,
703
+ slide: boolean,
704
+ ) => void,
705
+ ): void;
706
+ /**
707
+ * This event is invoked whenever an interval is added or removed from the collection.
708
+ * `local` reflects whether the change originated locally.
709
+ * `op` is defined if and only if the server has acked this change.
710
+ */
711
+ (
712
+ event: "addInterval" | "deleteInterval",
713
+ listener: (
714
+ interval: TInterval,
715
+ local: boolean,
716
+ op: ISequencedDocumentMessage | undefined,
717
+ ) => void,
718
+ ): void;
719
+ /**
720
+ * This event is invoked whenever an interval's properties have changed.
721
+ * `interval` reflects the state of the updated properties.
722
+ * `propertyDeltas` is a map-like whose keys contain all values that were changed, and whose
723
+ * values contain all previous values of the property set.
724
+ * This object can be used directly in a call to `changeProperties` to revert the property change if desired.
725
+ * `local` reflects whether the change originated locally.
726
+ * `op` is defined if and only if the server has acked this change.
727
+ */
728
+ (
729
+ event: "propertyChanged",
730
+ listener: (
731
+ interval: TInterval,
732
+ propertyDeltas: PropertySet,
733
+ local: boolean,
734
+ op: ISequencedDocumentMessage | undefined,
735
+ ) => void,
736
+ ): void;
737
+ }
934
738
 
935
- public get ops(): Map<string, IValueOperation<IntervalCollection<Interval>>> {
936
- return IntervalCollectionValueType._ops;
937
- }
739
+ // solely for type checking in the implementation of add - will be removed once
740
+ // deprecated signatures are removed
741
+ const isSequencePlace = (place: any): place is SequencePlace => {
742
+ return typeof place === "number" || typeof place === "string" || place.pos !== undefined;
743
+ };
938
744
 
939
- private static readonly _factory: IValueFactory<IntervalCollection<Interval>> =
940
- new IntervalCollectionFactory();
941
- private static readonly _ops = makeOpsMap<Interval>();
745
+ /**
746
+ * Collection of intervals that supports addition, modification, removal, and efficient spatial querying.
747
+ * Changes to this collection will be incur updates on collaborating clients (i.e. they are not local-only).
748
+ * @alpha
749
+ */
750
+ export interface IIntervalCollection<TInterval extends ISerializableInterval>
751
+ extends TypedEventEmitter<IIntervalCollectionEvent<TInterval>> {
752
+ readonly attached: boolean;
753
+ /**
754
+ * Attaches an index to this collection.
755
+ * All intervals which are part of this collection will be added to the index, and the index will automatically
756
+ * be updated when this collection updates due to local or remote changes.
757
+ *
758
+ * @remarks After attaching an index to an interval collection, applications should typically store this
759
+ * index somewhere in their in-memory data model for future reference and querying.
760
+ */
761
+ attachIndex(index: IntervalIndex<TInterval>): void;
762
+ /**
763
+ * Detaches an index from this collection.
764
+ * All intervals which are part of this collection will be removed from the index, and updates to this collection
765
+ * due to local or remote changes will no longer incur updates to the index.
766
+ *
767
+ * @returns `false` if the target index cannot be found in the indexes, otherwise remove all intervals in the index and return `true`.
768
+ */
769
+ detachIndex(index: IntervalIndex<TInterval>): boolean;
770
+ /**
771
+ * @returns the interval in this collection that has the provided `id`.
772
+ * If no interval in the collection has this `id`, returns `undefined`.
773
+ */
774
+ getIntervalById(id: string): TInterval | undefined;
775
+ /**
776
+ * Creates a new interval and add it to the collection.
777
+ * @param start - interval start position (inclusive)
778
+ * @param end - interval end position (exclusive)
779
+ * @param props - properties of the interval
780
+ * @returns - the created interval
781
+ * @remarks See documentation on {@link SequenceInterval} for comments on
782
+ * interval endpoint semantics: there are subtleties with how the current
783
+ * half-open behavior is represented.
784
+ *
785
+ * Note that intervals may behave unexpectedly if the entire contents
786
+ * of the string are deleted. In this case, it is possible for one endpoint
787
+ * of the interval to become detached, while the other remains on the string.
788
+ *
789
+ * By adjusting the `side` and `pos` values of the `start` and `end` parameters,
790
+ * it is possible to control whether the interval expands to include content
791
+ * inserted at its start or end.
792
+ *
793
+ * See {@link SequencePlace} for more details on the model.
794
+ *
795
+ * @example
796
+ *
797
+ * Given the string "ABCD":
798
+ *
799
+ *```typescript
800
+ * // Refers to "BC". If any content is inserted before B or after C, this
801
+ * // interval will include that content
802
+ * //
803
+ * // Picture:
804
+ * // \{start\} - A[- B - C -]D - \{end\}
805
+ * // \{start\} - A - B - C - D - \{end\}
806
+ * collection.add(\{ pos: 0, side: Side.After \}, \{ pos: 3, side: Side.Before \}, IntervalType.SlideOnRemove);
807
+ * // Equivalent to specifying the same positions and Side.Before.
808
+ * // Refers to "ABC". Content inserted after C will be included in the
809
+ * // interval, but content inserted before A will not.
810
+ * // \{start\} -[A - B - C -]D - \{end\}
811
+ * // \{start\} - A - B - C - D - \{end\}
812
+ * collection.add(0, 3, IntervalType.SlideOnRemove);
813
+ *```
814
+ *
815
+ * In the case of the first example, if text is deleted,
816
+ *
817
+ * ```typescript
818
+ * // Delete the character "B"
819
+ * string.removeRange(1, 2);
820
+ * ```
821
+ *
822
+ * The start point of the interval will slide to the position immediately
823
+ * before "C", and the same will be true.
824
+ *
825
+ * ```
826
+ * \{start\} - A[- C -]D - \{end\}
827
+ * ```
828
+ *
829
+ * In this case, text inserted immediately before "C" would be included in
830
+ * the interval.
831
+ *
832
+ * ```typescript
833
+ * string.insertText(1, "EFG");
834
+ * ```
835
+ *
836
+ * With the string now being,
837
+ *
838
+ * ```
839
+ * \{start\} - A[- E - F - G - C -]D - \{end\}
840
+ * ```
841
+ *
842
+ * @privateRemarks TODO: ADO:5205 the above comment regarding behavior in
843
+ * the case that the entire interval has been deleted should be resolved at
844
+ * the same time as this ticket
845
+ */
846
+ add({
847
+ start,
848
+ end,
849
+ props,
850
+ }: {
851
+ start: SequencePlace;
852
+ end: SequencePlace;
853
+ props?: PropertySet;
854
+ }): TInterval;
855
+ /**
856
+ * Removes an interval from the collection.
857
+ * @param id - Id of the interval to remove
858
+ * @returns the removed interval
859
+ */
860
+ removeIntervalById(id: string): TInterval | undefined;
861
+ /**
862
+ * Changes the properties on an existing interval.
863
+ * @deprecated - call change with the id and and object containing the new properties
864
+ * @param id - Id of the interval whose properties should be changed
865
+ * @param props - Property set to apply to the interval. Shallow merging is used between any existing properties
866
+ * and `prop`, i.e. the interval will end up with a property object equivalent to `{ ...oldProps, ...props }`.
867
+ */
868
+ changeProperties(id: string, props: PropertySet): void;
869
+ /**
870
+ * Changes the endpoints of an existing interval.
871
+ * @deprecated - call change with the start and end parameters encapsulated in an object
872
+ * @param id - Id of the interval to change
873
+ * @param start - New start value. To leave the endpoint unchanged, pass the current value.
874
+ * @param end - New end value. To leave the endpoint unchanged, pass the current value.
875
+ * @returns the interval that was changed, if it existed in the collection.
876
+ */
877
+ change(id: string, start: SequencePlace, end: SequencePlace): TInterval | undefined;
878
+ /**
879
+ * Changes the endpoints, properties, or both of an existing interval.
880
+ * @param id - Id of the Interval to change
881
+ * @returns the interval that was changed, if it existed in the collection.
882
+ * Pass the desired new start position, end position, and/or properties in an object. Start and end positions must be changed
883
+ * simultaneously - they must either both be specified or both undefined. To only change the properties, leave both endpoints
884
+ * undefined. To only change the endpoints, leave the properties undefined.
885
+ */
886
+ change(
887
+ id: string,
888
+ { start, end, props }: { start?: SequencePlace; end?: SequencePlace; props?: PropertySet },
889
+ ): TInterval | undefined;
890
+
891
+ attachDeserializer(onDeserialize: DeserializeCallback): void;
892
+ /**
893
+ * @returns an iterator over all intervals in this collection.
894
+ */
895
+ [Symbol.iterator](): Iterator<TInterval>;
896
+
897
+ /**
898
+ * @returns a forward iterator over all intervals in this collection with start point equal to `startPosition`.
899
+ */
900
+ CreateForwardIteratorWithStartPosition(startPosition: number): Iterator<TInterval>;
901
+
902
+ /**
903
+ * @returns a backward iterator over all intervals in this collection with start point equal to `startPosition`.
904
+ */
905
+ CreateBackwardIteratorWithStartPosition(startPosition: number): Iterator<TInterval>;
906
+
907
+ /**
908
+ * @returns a forward iterator over all intervals in this collection with end point equal to `endPosition`.
909
+ */
910
+ CreateForwardIteratorWithEndPosition(endPosition: number): Iterator<TInterval>;
911
+
912
+ /**
913
+ * @returns a backward iterator over all intervals in this collection with end point equal to `endPosition`.
914
+ */
915
+ CreateBackwardIteratorWithEndPosition(endPosition: number): Iterator<TInterval>;
916
+
917
+ /**
918
+ * Gathers iteration results that optionally match a start/end criteria into the provided array.
919
+ * @param results - Array to gather the results into. In lieu of a return value, this array will be populated with
920
+ * intervals matching the query upon edit.
921
+ * @param iteratesForward - whether or not iteration should be in the forward direction
922
+ * @param start - If provided, only match intervals whose start point is equal to `start`.
923
+ * @param end - If provided, only match intervals whose end point is equal to `end`.
924
+ */
925
+ gatherIterationResults(
926
+ results: TInterval[],
927
+ iteratesForward: boolean,
928
+ start?: number,
929
+ end?: number,
930
+ ): void;
931
+
932
+ /**
933
+ * @deprecated - Users must manually attach the corresponding interval index to utilize this functionality, for instance:
934
+ *
935
+ * ```typescript
936
+ * const overlappingIntervalsIndex = createOverlappingIntervalsIndex(sharedString);
937
+ * collection.attachIndex(overlappingIntervalsIndex)
938
+ * const result = overlappingIntervalsIndex.findOverlappingIntervals(start, end);
939
+ * ```
940
+ *
941
+ * @returns an array of all intervals in this collection that overlap with the interval
942
+ * `[startPosition, endPosition]`.
943
+ */
944
+ findOverlappingIntervals(startPosition: number, endPosition: number): TInterval[];
945
+
946
+ /**
947
+ * Applies a function to each interval in this collection.
948
+ */
949
+ map(fn: (interval: TInterval) => void): void;
950
+
951
+ /**
952
+ * @deprecated - due to the forthcoming change where the endpointIndex will no longer be
953
+ * automatically added to the collection. Users are advised to independently attach the
954
+ * index to the collection and utilize the API accordingly, for instance:
955
+ * ```typescript
956
+ * const endpointIndex = createEndpointIndex(sharedString);
957
+ * collection.attachIndex(endpointIndex);
958
+ * const result1 = endpointIndex.previousInterval(pos);
959
+ * ```
960
+ * If an index is used repeatedly, applications should generally attach it once and store it in memory.
961
+ */
962
+ previousInterval(pos: number): TInterval | undefined;
963
+
964
+ /**
965
+ * @deprecated - due to the forthcoming change where the endpointIndex will no longer be
966
+ * automatically added to the collection. Users are advised to independently attach the
967
+ * index to the collection and utilize the API accordingly, for instance:
968
+ * ```typescript
969
+ * const endpointIndex = createEndpointIndex(sharedString);
970
+ * collection.attachIndex(endpointIndex);
971
+ * const result2 = endpointIndex.nextInterval(pos);
972
+ * ```
973
+ */
974
+ nextInterval(pos: number): TInterval | undefined;
942
975
  }
943
976
 
944
- function makeOpsMap<T extends ISerializableInterval>(): Map<string, IValueOperation<IntervalCollection<T>>> {
945
- const rebase = (
946
- collection: IntervalCollection<T>,
947
- op: IValueTypeOperationValue,
948
- localOpMetadata: IMapMessageLocalMetadata,
949
- ) => {
950
- const { localSeq } = localOpMetadata;
951
- const rebasedValue = collection.rebaseLocalInterval(op.opName, op.value, localSeq);
952
- const rebasedOp = { ...op, value: rebasedValue };
953
- return { rebasedOp, rebasedLocalOpMetadata: localOpMetadata };
954
- };
955
-
956
- return new Map<string, IValueOperation<IntervalCollection<T>>>(
957
- [[
958
- "add",
959
- {
960
- process: (collection, params, local, op) => {
961
- collection.ackAdd(params, local, op);
962
- },
963
- rebase,
964
- },
965
- ],
966
- [
967
- "delete",
968
- {
969
- process: (collection, params, local, op) => {
970
- collection.ackDelete(params, local, op);
971
- },
972
- rebase: (collection, op, localOpMetadata) => {
973
- // Deletion of intervals is based on id, so requires no rebasing.
974
- return { rebasedOp: op, rebasedLocalOpMetadata: localOpMetadata };
975
- },
976
- },
977
- ],
978
- [
979
- "change",
980
- {
981
- process: (collection, params, local, op) => {
982
- collection.ackChange(params, local, op);
983
- },
984
- rebase,
985
- },
986
- ]]);
977
+ /**
978
+ * {@inheritdoc IIntervalCollection}
979
+ */
980
+ export class IntervalCollection<TInterval extends ISerializableInterval>
981
+ extends TypedEventEmitter<IIntervalCollectionEvent<TInterval>>
982
+ implements IIntervalCollection<TInterval>
983
+ {
984
+ private savedSerializedIntervals?: ISerializedInterval[];
985
+ private localCollection: LocalIntervalCollection<TInterval> | undefined;
986
+ private onDeserialize: DeserializeCallback | undefined;
987
+ private client: Client | undefined;
988
+ private readonly localSeqToSerializedInterval = new Map<
989
+ number,
990
+ ISerializedInterval | SerializedIntervalDelta
991
+ >();
992
+ private readonly localSeqToRebasedInterval = new Map<
993
+ number,
994
+ ISerializedInterval | SerializedIntervalDelta
995
+ >();
996
+ private readonly pendingChangesStart: Map<string, ISerializedInterval[]> = new Map<
997
+ string,
998
+ ISerializedInterval[]
999
+ >();
1000
+ private readonly pendingChangesEnd: Map<string, ISerializedInterval[]> = new Map<
1001
+ string,
1002
+ ISerializedInterval[]
1003
+ >();
1004
+
1005
+ public get attached(): boolean {
1006
+ return !!this.localCollection;
1007
+ }
1008
+
1009
+ /** @internal */
1010
+ constructor(
1011
+ private readonly helpers: IIntervalHelpers<TInterval>,
1012
+ private readonly requiresClient: boolean,
1013
+ private readonly emitter: IValueOpEmitter,
1014
+ serializedIntervals: ISerializedInterval[] | ISerializedIntervalCollectionV2,
1015
+ private readonly options: Partial<SequenceOptions> = {},
1016
+ ) {
1017
+ super();
1018
+
1019
+ this.savedSerializedIntervals = Array.isArray(serializedIntervals)
1020
+ ? serializedIntervals
1021
+ : serializedIntervals.intervals.map((i) =>
1022
+ decompressInterval(i, serializedIntervals.label),
1023
+ );
1024
+ }
1025
+
1026
+ /**
1027
+ * {@inheritdoc IIntervalCollection.attachIndex}
1028
+ */
1029
+ public attachIndex(index: IntervalIndex<TInterval>): void {
1030
+ if (!this.attached) {
1031
+ throw new LoggingError("The local interval collection must exist");
1032
+ }
1033
+ for (const interval of this) {
1034
+ index.add(interval);
1035
+ }
1036
+
1037
+ this.localCollection?.appendIndex(index);
1038
+ }
1039
+
1040
+ /**
1041
+ * {@inheritdoc IIntervalCollection.detachIndex}
1042
+ */
1043
+ public detachIndex(index: IntervalIndex<TInterval>): boolean {
1044
+ if (!this.attached) {
1045
+ throw new LoggingError("The local interval collection must exist");
1046
+ }
1047
+
1048
+ // Avoid removing intervals if the index does not exist
1049
+ if (!this.localCollection?.removeIndex(index)) {
1050
+ return false;
1051
+ }
1052
+
1053
+ for (const interval of this) {
1054
+ index.remove(interval);
1055
+ }
1056
+
1057
+ return true;
1058
+ }
1059
+
1060
+ private rebasePositionWithSegmentSlide(
1061
+ pos: number | "start" | "end",
1062
+ seqNumberFrom: number,
1063
+ localSeq: number,
1064
+ ): number | "start" | "end" | undefined {
1065
+ if (!this.client) {
1066
+ throw new LoggingError("mergeTree client must exist");
1067
+ }
1068
+
1069
+ if (pos === "start" || pos === "end") {
1070
+ return pos;
1071
+ }
1072
+
1073
+ const { clientId } = this.client.getCollabWindow();
1074
+ const { segment, offset } = this.client.getContainingSegment(
1075
+ pos,
1076
+ {
1077
+ referenceSequenceNumber: seqNumberFrom,
1078
+ clientId: this.client.getLongClientId(clientId),
1079
+ },
1080
+ localSeq,
1081
+ );
1082
+
1083
+ // if segment is undefined, it slid off the string
1084
+ assert(segment !== undefined, 0x54e /* No segment found */);
1085
+
1086
+ const segoff =
1087
+ getSlideToSegoff(
1088
+ { segment, offset },
1089
+ undefined,
1090
+ this.options.mergeTreeReferencesCanSlideToEndpoint,
1091
+ ) ?? segment;
1092
+
1093
+ // case happens when rebasing op, but concurrently entire string has been deleted
1094
+ if (segoff.segment === undefined || segoff.offset === undefined) {
1095
+ return DetachedReferencePosition;
1096
+ }
1097
+
1098
+ assert(
1099
+ offset !== undefined && 0 <= offset && offset < segment.cachedLength,
1100
+ 0x54f /* Invalid offset */,
1101
+ );
1102
+ return this.client.findReconnectionPosition(segoff.segment, localSeq) + segoff.offset;
1103
+ }
1104
+
1105
+ private computeRebasedPositions(
1106
+ localSeq: number,
1107
+ ): ISerializedInterval | SerializedIntervalDelta {
1108
+ assert(
1109
+ this.client !== undefined,
1110
+ 0x550 /* Client should be defined when computing rebased position */,
1111
+ );
1112
+ const original = this.localSeqToSerializedInterval.get(localSeq);
1113
+ assert(
1114
+ original !== undefined,
1115
+ 0x551 /* Failed to store pending serialized interval info for this localSeq. */,
1116
+ );
1117
+ const rebased = { ...original };
1118
+ const { start, end, sequenceNumber } = original;
1119
+ if (start !== undefined) {
1120
+ rebased.start = this.rebasePositionWithSegmentSlide(start, sequenceNumber, localSeq);
1121
+ }
1122
+ if (end !== undefined) {
1123
+ rebased.end = this.rebasePositionWithSegmentSlide(end, sequenceNumber, localSeq);
1124
+ }
1125
+ return rebased;
1126
+ }
1127
+
1128
+ /** @internal */
1129
+ public attachGraph(client: Client, label: string) {
1130
+ if (this.attached) {
1131
+ throw new LoggingError("Only supports one Sequence attach");
1132
+ }
1133
+
1134
+ if (client === undefined && this.requiresClient) {
1135
+ throw new LoggingError("Client required for this collection");
1136
+ }
1137
+
1138
+ // Instantiate the local interval collection based on the saved intervals
1139
+ this.client = client;
1140
+ if (client) {
1141
+ client.on("normalize", () => {
1142
+ for (const localSeq of this.localSeqToSerializedInterval.keys()) {
1143
+ this.localSeqToRebasedInterval.set(
1144
+ localSeq,
1145
+ this.computeRebasedPositions(localSeq),
1146
+ );
1147
+ }
1148
+ });
1149
+ }
1150
+
1151
+ this.localCollection = new LocalIntervalCollection<TInterval>(
1152
+ client,
1153
+ label,
1154
+ this.helpers,
1155
+ this.options,
1156
+ (interval, previousInterval) => this.emitChange(interval, previousInterval, true, true),
1157
+ );
1158
+ if (this.savedSerializedIntervals) {
1159
+ for (const serializedInterval of this.savedSerializedIntervals) {
1160
+ this.localCollection.ensureSerializedId(serializedInterval);
1161
+ const {
1162
+ start: startPos,
1163
+ end: endPos,
1164
+ intervalType,
1165
+ properties,
1166
+ startSide,
1167
+ endSide,
1168
+ } = serializedInterval;
1169
+ const start =
1170
+ typeof startPos === "number" && startSide !== undefined
1171
+ ? { pos: startPos, side: startSide }
1172
+ : startPos;
1173
+ const end =
1174
+ typeof endPos === "number" && endSide !== undefined
1175
+ ? { pos: endPos, side: endSide }
1176
+ : endPos;
1177
+ const interval = this.helpers.create(
1178
+ label,
1179
+ start,
1180
+ end,
1181
+ client,
1182
+ intervalType,
1183
+ undefined,
1184
+ true,
1185
+ this.options.mergeTreeReferencesCanSlideToEndpoint,
1186
+ );
1187
+ if (properties) {
1188
+ interval.addProperties(properties);
1189
+ }
1190
+ this.localCollection.add(interval);
1191
+ }
1192
+ }
1193
+ this.savedSerializedIntervals = undefined;
1194
+ }
1195
+
1196
+ /**
1197
+ * Gets the next local sequence number, modifying this client's collab window in doing so.
1198
+ */
1199
+ private getNextLocalSeq(): number {
1200
+ if (this.client) {
1201
+ return ++this.client.getCollabWindow().localSeq;
1202
+ }
1203
+
1204
+ return 0;
1205
+ }
1206
+
1207
+ private emitChange(
1208
+ interval: TInterval,
1209
+ previousInterval: TInterval,
1210
+ local: boolean,
1211
+ slide: boolean,
1212
+ op?: ISequencedDocumentMessage,
1213
+ ): void {
1214
+ // Temporarily make references transient so that positional queries work (non-transient refs
1215
+ // on resolve to DetachedPosition on any segments that don't contain them). The original refType
1216
+ // is restored as single-endpoint changes re-use previous references.
1217
+ let startRefType: ReferenceType;
1218
+ let endRefType: ReferenceType;
1219
+ if (previousInterval instanceof SequenceInterval) {
1220
+ startRefType = previousInterval.start.refType;
1221
+ endRefType = previousInterval.end.refType;
1222
+ previousInterval.start.refType = ReferenceType.Transient;
1223
+ previousInterval.end.refType = ReferenceType.Transient;
1224
+ this.emit("changeInterval", interval, previousInterval, local, op, slide);
1225
+ previousInterval.start.refType = startRefType;
1226
+ previousInterval.end.refType = endRefType;
1227
+ } else {
1228
+ this.emit("changeInterval", interval, previousInterval, local, op, slide);
1229
+ }
1230
+ }
1231
+
1232
+ /**
1233
+ * {@inheritdoc IIntervalCollection.getIntervalById}
1234
+ */
1235
+ public getIntervalById(id: string): TInterval | undefined {
1236
+ if (!this.localCollection) {
1237
+ throw new LoggingError("attach must be called before accessing intervals");
1238
+ }
1239
+ return this.localCollection.idIntervalIndex.getIntervalById(id);
1240
+ }
1241
+
1242
+ private assertStickinessEnabled(start: SequencePlace, end: SequencePlace) {
1243
+ if (
1244
+ !(typeof start === "number" && typeof end === "number") &&
1245
+ !this.options.intervalStickinessEnabled
1246
+ ) {
1247
+ throw new UsageError(
1248
+ "attempted to set interval stickiness without enabling `intervalStickinessEnabled` feature flag",
1249
+ );
1250
+ }
1251
+ }
1252
+
1253
+ /**
1254
+ * {@inheritdoc IIntervalCollection.add}
1255
+ */
1256
+ public add({
1257
+ start,
1258
+ end,
1259
+ props,
1260
+ }: {
1261
+ start: SequencePlace;
1262
+ end: SequencePlace;
1263
+ props?: PropertySet;
1264
+ }): TInterval {
1265
+ if (!this.localCollection) {
1266
+ throw new LoggingError("attach must be called prior to adding intervals");
1267
+ }
1268
+
1269
+ const { startSide, endSide, startPos, endPos } = endpointPosAndSide(start, end);
1270
+
1271
+ assert(
1272
+ startPos !== undefined &&
1273
+ endPos !== undefined &&
1274
+ startSide !== undefined &&
1275
+ endSide !== undefined,
1276
+ 0x793 /* start and end cannot be undefined because they were not passed in as undefined */,
1277
+ );
1278
+
1279
+ const stickiness = computeStickinessFromSide(startPos, startSide, endPos, endSide);
1280
+
1281
+ this.assertStickinessEnabled(start, end);
1282
+
1283
+ const interval: TInterval = this.localCollection.addInterval(
1284
+ toSequencePlace(startPos, startSide),
1285
+ toSequencePlace(endPos, endSide),
1286
+ IntervalType.SlideOnRemove,
1287
+ props,
1288
+ );
1289
+
1290
+ if (interval) {
1291
+ if (!this.isCollaborating && interval instanceof SequenceInterval) {
1292
+ setSlideOnRemove(interval.start);
1293
+ setSlideOnRemove(interval.end);
1294
+ }
1295
+ const serializedInterval: ISerializedInterval = {
1296
+ start: startPos,
1297
+ end: endPos,
1298
+ intervalType: IntervalType.SlideOnRemove,
1299
+ properties: interval.properties,
1300
+ sequenceNumber: this.client?.getCurrentSeq() ?? 0,
1301
+ stickiness,
1302
+ startSide,
1303
+ endSide,
1304
+ };
1305
+ const localSeq = this.getNextLocalSeq();
1306
+ this.localSeqToSerializedInterval.set(localSeq, serializedInterval);
1307
+ // Local ops get submitted to the server. Remote ops have the deserializer run.
1308
+ this.emitter.emit("add", undefined, serializedInterval, { localSeq });
1309
+ }
1310
+
1311
+ this.emit("addInterval", interval, true, undefined);
1312
+
1313
+ return interval;
1314
+ }
1315
+
1316
+ private deleteExistingInterval(
1317
+ interval: TInterval,
1318
+ local: boolean,
1319
+ op?: ISequencedDocumentMessage,
1320
+ ) {
1321
+ if (!this.localCollection) {
1322
+ throw new LoggingError("Attach must be called before accessing intervals");
1323
+ }
1324
+ // The given interval is known to exist in the collection.
1325
+ this.localCollection.removeExistingInterval(interval);
1326
+
1327
+ if (interval) {
1328
+ // Local ops get submitted to the server. Remote ops have the deserializer run.
1329
+ if (local) {
1330
+ this.emitter.emit("delete", undefined, interval.serialize(), {
1331
+ localSeq: this.getNextLocalSeq(),
1332
+ });
1333
+ } else {
1334
+ if (this.onDeserialize) {
1335
+ this.onDeserialize(interval);
1336
+ }
1337
+ }
1338
+ }
1339
+
1340
+ this.emit("deleteInterval", interval, local, op);
1341
+ }
1342
+
1343
+ /**
1344
+ * {@inheritdoc IIntervalCollection.removeIntervalById}
1345
+ */
1346
+ public removeIntervalById(id: string): TInterval | undefined {
1347
+ if (!this.localCollection) {
1348
+ throw new LoggingError("Attach must be called before accessing intervals");
1349
+ }
1350
+ const interval = this.localCollection.idIntervalIndex.getIntervalById(id);
1351
+ if (interval) {
1352
+ this.deleteExistingInterval(interval, true, undefined);
1353
+ }
1354
+ return interval;
1355
+ }
1356
+
1357
+ /**
1358
+ * {@inheritdoc IIntervalCollection.changeProperties}
1359
+ * @deprecated - call change with the id and an object containing the new props values
1360
+ */
1361
+ public changeProperties(id: string, props: PropertySet) {
1362
+ this.change(id, { props });
1363
+ }
1364
+
1365
+ /**
1366
+ * {@inheritdoc IIntervalCollection.change}
1367
+ * @deprecated - call change with the id and an object containing the new start, end, and/or props values
1368
+ */
1369
+ public change(id: string, start: SequencePlace, end: SequencePlace): TInterval | undefined;
1370
+ /**
1371
+ * {@inheritdoc IIntervalCollection.change}
1372
+ */
1373
+ public change(
1374
+ id: string,
1375
+ { start, end, props }: { start?: SequencePlace; end?: SequencePlace; props?: PropertySet },
1376
+ ): TInterval | undefined;
1377
+ public change(
1378
+ arg1: string,
1379
+ arg2: SequencePlace | { start?: SequencePlace; end?: SequencePlace; props?: PropertySet },
1380
+ arg3?: SequencePlace,
1381
+ ): TInterval | undefined {
1382
+ const id: string = arg1;
1383
+ let start: SequencePlace | undefined;
1384
+ let end: SequencePlace | undefined;
1385
+ let props: PropertySet | undefined;
1386
+ if (isSequencePlace(arg2)) {
1387
+ start = arg2;
1388
+ end = arg3;
1389
+ } else {
1390
+ start = arg2.start;
1391
+ end = arg2.end;
1392
+ props = arg2.props;
1393
+ }
1394
+
1395
+ if (!this.localCollection) {
1396
+ throw new LoggingError("Attach must be called before accessing intervals");
1397
+ }
1398
+
1399
+ // Force id to be a string.
1400
+ if (typeof id !== "string") {
1401
+ throw new UsageError("Change API requires an ID that is a string");
1402
+ }
1403
+
1404
+ // Ensure that both start and end are defined or both are undefined.
1405
+ if ((start === undefined) !== (end === undefined)) {
1406
+ throw new UsageError(
1407
+ "Change API requires both start and end to be defined or undefined",
1408
+ );
1409
+ }
1410
+
1411
+ // prevent the overwriting of an interval label, it should remain unchanged
1412
+ // once it has been inserted into the collection.
1413
+ if (props?.[reservedRangeLabelsKey] !== undefined) {
1414
+ throw new UsageError(
1415
+ "The label property should not be modified once inserted to the collection",
1416
+ );
1417
+ }
1418
+
1419
+ const interval = this.getIntervalById(id);
1420
+ if (interval) {
1421
+ let deltaProps: PropertySet | undefined;
1422
+ let newInterval: TInterval | undefined;
1423
+ if (props !== undefined) {
1424
+ deltaProps = interval.addProperties(
1425
+ props,
1426
+ true,
1427
+ this.isCollaborating ? UnassignedSequenceNumber : UniversalSequenceNumber,
1428
+ );
1429
+ }
1430
+ if (start !== undefined && end !== undefined) {
1431
+ newInterval = this.localCollection.changeInterval(interval, start, end);
1432
+ if (!this.isCollaborating && newInterval instanceof SequenceInterval) {
1433
+ setSlideOnRemove(newInterval.start);
1434
+ setSlideOnRemove(newInterval.end);
1435
+ }
1436
+ }
1437
+ const serializedInterval: SerializedIntervalDelta = interval.serialize();
1438
+ const { startPos, startSide, endPos, endSide } = endpointPosAndSide(start, end);
1439
+ const stickiness = computeStickinessFromSide(startPos, startSide, endPos, endSide);
1440
+ serializedInterval.start = startPos;
1441
+ serializedInterval.end = endPos;
1442
+ serializedInterval.startSide = startSide;
1443
+ serializedInterval.endSide = endSide;
1444
+ serializedInterval.stickiness = stickiness;
1445
+ // Emit a property bag containing the ID and the other (if any) properties changed
1446
+ serializedInterval.properties = {
1447
+ [reservedIntervalIdKey]: interval.getIntervalId(),
1448
+ ...props,
1449
+ };
1450
+ const localSeq = this.getNextLocalSeq();
1451
+ this.localSeqToSerializedInterval.set(localSeq, serializedInterval);
1452
+ this.emitter.emit("change", undefined, serializedInterval, { localSeq });
1453
+ if (deltaProps !== undefined) {
1454
+ this.emit("propertyChanged", interval, deltaProps, true, undefined);
1455
+ }
1456
+ if (newInterval) {
1457
+ this.addPendingChange(id, serializedInterval);
1458
+ this.emitChange(newInterval, interval, true, false);
1459
+ }
1460
+ return newInterval;
1461
+ }
1462
+ // No interval to change
1463
+ return undefined;
1464
+ }
1465
+
1466
+ private get isCollaborating(): boolean {
1467
+ return this.client?.getCollabWindow().collaborating ?? false;
1468
+ }
1469
+
1470
+ private addPendingChange(id: string, serializedInterval: SerializedIntervalDelta) {
1471
+ if (!this.isCollaborating) {
1472
+ return;
1473
+ }
1474
+ if (serializedInterval.start !== undefined) {
1475
+ this.addPendingChangeHelper(id, this.pendingChangesStart, serializedInterval);
1476
+ }
1477
+ if (serializedInterval.end !== undefined) {
1478
+ this.addPendingChangeHelper(id, this.pendingChangesEnd, serializedInterval);
1479
+ }
1480
+ }
1481
+
1482
+ private addPendingChangeHelper(
1483
+ id: string,
1484
+ pendingChanges: Map<string, SerializedIntervalDelta[]>,
1485
+ serializedInterval: SerializedIntervalDelta,
1486
+ ) {
1487
+ let entries: SerializedIntervalDelta[] | undefined = pendingChanges.get(id);
1488
+ if (!entries) {
1489
+ entries = [];
1490
+ pendingChanges.set(id, entries);
1491
+ }
1492
+ entries.push(serializedInterval);
1493
+ }
1494
+
1495
+ private removePendingChange(serializedInterval: SerializedIntervalDelta) {
1496
+ // Change ops always have an ID.
1497
+ const id: string = serializedInterval.properties?.[reservedIntervalIdKey];
1498
+ if (serializedInterval.start !== undefined) {
1499
+ this.removePendingChangeHelper(id, this.pendingChangesStart, serializedInterval);
1500
+ }
1501
+ if (serializedInterval.end !== undefined) {
1502
+ this.removePendingChangeHelper(id, this.pendingChangesEnd, serializedInterval);
1503
+ }
1504
+ }
1505
+
1506
+ private removePendingChangeHelper(
1507
+ id: string,
1508
+ pendingChanges: Map<string, SerializedIntervalDelta[]>,
1509
+ serializedInterval: SerializedIntervalDelta,
1510
+ ) {
1511
+ const entries = pendingChanges.get(id);
1512
+ if (entries) {
1513
+ const pendingChange = entries.shift();
1514
+ if (entries.length === 0) {
1515
+ pendingChanges.delete(id);
1516
+ }
1517
+ if (
1518
+ pendingChange?.start !== serializedInterval.start ||
1519
+ pendingChange?.end !== serializedInterval.end
1520
+ ) {
1521
+ throw new LoggingError("Mismatch in pending changes");
1522
+ }
1523
+ }
1524
+ }
1525
+
1526
+ private hasPendingChangeStart(id: string) {
1527
+ const entries = this.pendingChangesStart.get(id);
1528
+ return entries && entries.length !== 0;
1529
+ }
1530
+
1531
+ private hasPendingChangeEnd(id: string) {
1532
+ const entries = this.pendingChangesEnd.get(id);
1533
+ return entries && entries.length !== 0;
1534
+ }
1535
+
1536
+ /** @internal */
1537
+ public ackChange(
1538
+ serializedInterval: ISerializedInterval,
1539
+ local: boolean,
1540
+ op: ISequencedDocumentMessage,
1541
+ localOpMetadata: IMapMessageLocalMetadata | undefined,
1542
+ ) {
1543
+ if (!this.localCollection) {
1544
+ throw new LoggingError("Attach must be called before accessing intervals");
1545
+ }
1546
+
1547
+ if (local) {
1548
+ assert(
1549
+ localOpMetadata !== undefined,
1550
+ 0x552 /* op metadata should be defined for local op */,
1551
+ );
1552
+ this.localSeqToSerializedInterval.delete(localOpMetadata?.localSeq);
1553
+ // This is an ack from the server. Remove the pending change.
1554
+ this.removePendingChange(serializedInterval);
1555
+ }
1556
+
1557
+ // Note that the ID is in the property bag only to allow us to find the interval.
1558
+ // This API cannot change the ID, and writing to the ID property will result in an exception. So we
1559
+ // strip it out of the properties here.
1560
+ const { [reservedIntervalIdKey]: id, ...newProps } = serializedInterval.properties ?? {};
1561
+ assert(id !== undefined, 0x3fe /* id must exist on the interval */);
1562
+ const interval: TInterval | undefined = this.getIntervalById(id);
1563
+ if (!interval) {
1564
+ // The interval has been removed locally; no-op.
1565
+ return;
1566
+ }
1567
+
1568
+ if (local) {
1569
+ // Let the propertyManager prune its pending change-properties set.
1570
+ interval.propertyManager?.ackPendingProperties({
1571
+ type: MergeTreeDeltaType.ANNOTATE,
1572
+ props: serializedInterval.properties ?? {},
1573
+ });
1574
+
1575
+ this.ackInterval(interval, op);
1576
+ } else {
1577
+ // If there are pending changes with this ID, don't apply the remote start/end change, as the local ack
1578
+ // should be the winning change.
1579
+ let start: number | "start" | "end" | undefined;
1580
+ let end: number | "start" | "end" | undefined;
1581
+ // Track pending start/end independently of one another.
1582
+ if (!this.hasPendingChangeStart(id)) {
1583
+ start = serializedInterval.start;
1584
+ }
1585
+ if (!this.hasPendingChangeEnd(id)) {
1586
+ end = serializedInterval.end;
1587
+ }
1588
+
1589
+ let newInterval = interval;
1590
+ if (start !== undefined || end !== undefined) {
1591
+ // If changeInterval gives us a new interval, work with that one. Otherwise keep working with
1592
+ // the one we originally found in the tree.
1593
+ newInterval =
1594
+ this.localCollection.changeInterval(
1595
+ interval,
1596
+ toOptionalSequencePlace(start, serializedInterval.startSide),
1597
+ toOptionalSequencePlace(end, serializedInterval.endSide),
1598
+ op,
1599
+ ) ?? interval;
1600
+ }
1601
+ const deltaProps = newInterval.addProperties(newProps, true, op.sequenceNumber);
1602
+ if (this.onDeserialize) {
1603
+ this.onDeserialize(newInterval);
1604
+ }
1605
+
1606
+ if (newInterval !== interval) {
1607
+ this.emitChange(newInterval, interval, local, false, op);
1608
+ }
1609
+
1610
+ const changedProperties = Object.keys(newProps).length > 0;
1611
+ if (changedProperties) {
1612
+ this.emit("propertyChanged", interval, deltaProps, local, op);
1613
+ }
1614
+ }
1615
+ }
1616
+
1617
+ /**
1618
+ * {@inheritdoc IIntervalCollection.attachDeserializer}
1619
+ */
1620
+ public attachDeserializer(onDeserialize: DeserializeCallback): void {
1621
+ // If no deserializer is specified can skip all processing work
1622
+ if (!onDeserialize) {
1623
+ return;
1624
+ }
1625
+
1626
+ // Start by storing the callbacks so that any subsequent modifications make use of them
1627
+ this.onDeserialize = onDeserialize;
1628
+
1629
+ // Trigger the async prepare work across all values in the collection
1630
+ if (this.attached) {
1631
+ this.map(onDeserialize);
1632
+ }
1633
+ }
1634
+
1635
+ /**
1636
+ * Returns new interval after rebasing. If undefined, the interval was
1637
+ * deleted as a result of rebasing. This can occur if the interval applies
1638
+ * to a range that no longer exists, and the interval was unable to slide.
1639
+ *
1640
+ * @internal
1641
+ */
1642
+ public rebaseLocalInterval(
1643
+ opName: string,
1644
+ serializedInterval: SerializedIntervalDelta,
1645
+ localSeq: number,
1646
+ ): SerializedIntervalDelta | undefined {
1647
+ if (!this.client) {
1648
+ // If there's no associated mergeTree client, the originally submitted op is still correct.
1649
+ return serializedInterval;
1650
+ }
1651
+ if (!this.attached) {
1652
+ throw new LoggingError("attachSequence must be called");
1653
+ }
1654
+
1655
+ const { intervalType, properties, stickiness, startSide, endSide } = serializedInterval;
1656
+
1657
+ const { start: startRebased, end: endRebased } =
1658
+ this.localSeqToRebasedInterval.get(localSeq) ?? this.computeRebasedPositions(localSeq);
1659
+
1660
+ const intervalId = properties?.[reservedIntervalIdKey];
1661
+ const localInterval = this.localCollection?.idIntervalIndex.getIntervalById(intervalId);
1662
+
1663
+ const rebased: SerializedIntervalDelta = {
1664
+ start: startRebased,
1665
+ end: endRebased,
1666
+ intervalType,
1667
+ sequenceNumber: this.client?.getCurrentSeq() ?? 0,
1668
+ properties,
1669
+ stickiness,
1670
+ startSide,
1671
+ endSide,
1672
+ };
1673
+
1674
+ if (
1675
+ opName === "change" &&
1676
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- ?? is not logically equivalent when .hasPendingChangeStart returns false.
1677
+ (this.hasPendingChangeStart(intervalId) || this.hasPendingChangeEnd(intervalId))
1678
+ ) {
1679
+ this.removePendingChange(serializedInterval);
1680
+ this.addPendingChange(intervalId, rebased);
1681
+ }
1682
+
1683
+ // if the interval slid off the string, rebase the op to be a noop and delete the interval.
1684
+ if (
1685
+ startRebased === DetachedReferencePosition ||
1686
+ endRebased === DetachedReferencePosition
1687
+ ) {
1688
+ if (localInterval) {
1689
+ this.localCollection?.removeExistingInterval(localInterval);
1690
+ }
1691
+ return undefined;
1692
+ }
1693
+
1694
+ if (localInterval !== undefined) {
1695
+ // we know we must be using `SequenceInterval` because `this.client` exists
1696
+ assert(
1697
+ localInterval instanceof SequenceInterval,
1698
+ 0x3a0 /* localInterval must be `SequenceInterval` when used with client */,
1699
+ );
1700
+ // The rebased op may place this interval's endpoints on different segments. Calling `changeInterval` here
1701
+ // updates the local client's state to be consistent with the emitted op.
1702
+ this.localCollection?.changeInterval(
1703
+ localInterval,
1704
+ toOptionalSequencePlace(startRebased, startSide),
1705
+ toOptionalSequencePlace(endRebased, endSide),
1706
+ undefined,
1707
+ localSeq,
1708
+ );
1709
+ }
1710
+
1711
+ return rebased;
1712
+ }
1713
+
1714
+ public applyStashedOp(op: IValueTypeOperationValue): IMapMessageLocalMetadata {
1715
+ let interval: TInterval | undefined;
1716
+ let props: PropertySet | undefined;
1717
+ let intervalId: string;
1718
+ switch (op.opName) {
1719
+ case IntervalDeltaOpType.ADD: {
1720
+ assert(op.value.start !== undefined, "start is undefined");
1721
+ assert(op.value.end !== undefined, "end is undefined");
1722
+ interval = this.add({
1723
+ start: op.value.start,
1724
+ end: op.value.end,
1725
+ props: op.value.properties,
1726
+ });
1727
+ const metadata = {
1728
+ localSeq: this.getNextLocalSeq(),
1729
+ };
1730
+ if (interval !== undefined) {
1731
+ this.localSeqToSerializedInterval.set(metadata.localSeq, interval.serialize());
1732
+ }
1733
+ return metadata;
1734
+ }
1735
+ case IntervalDeltaOpType.DELETE:
1736
+ this.removeIntervalById(op.value.properties?.intervalId);
1737
+ return {
1738
+ localSeq: this.getNextLocalSeq(),
1739
+ };
1740
+ case IntervalDeltaOpType.CHANGE: {
1741
+ assert(op.value.properties !== undefined, "properties is undefined");
1742
+ ({ intervalId, ...props } = op.value.properties);
1743
+ interval = this.change(intervalId, {
1744
+ start: op.value.start,
1745
+ end: op.value.end,
1746
+ props,
1747
+ });
1748
+ const metadata = {
1749
+ localSeq: this.getNextLocalSeq(),
1750
+ };
1751
+ if (interval !== undefined) {
1752
+ this.localSeqToSerializedInterval.set(metadata.localSeq, interval.serialize());
1753
+ }
1754
+ return metadata;
1755
+ }
1756
+ default:
1757
+ unreachableCase(op.opName, `Unknown interval op type: ${op.opName}`);
1758
+ }
1759
+ }
1760
+
1761
+ private getSlideToSegment(
1762
+ lref: LocalReferencePosition,
1763
+ ): { segment: ISegment | undefined; offset: number | undefined } | undefined {
1764
+ if (!this.client) {
1765
+ throw new LoggingError("client does not exist");
1766
+ }
1767
+ const segoff = { segment: lref.getSegment(), offset: lref.getOffset() };
1768
+ if (segoff.segment?.localRefs?.has(lref) !== true) {
1769
+ return undefined;
1770
+ }
1771
+ const newSegoff = getSlideToSegoff(
1772
+ segoff,
1773
+ undefined,
1774
+ this.options.mergeTreeReferencesCanSlideToEndpoint,
1775
+ );
1776
+ const value: { segment: ISegment | undefined; offset: number | undefined } | undefined =
1777
+ segoff.segment === newSegoff.segment && segoff.offset === newSegoff.offset
1778
+ ? undefined
1779
+ : newSegoff;
1780
+ return value;
1781
+ }
1782
+
1783
+ private ackInterval(interval: TInterval, op: ISequencedDocumentMessage): void {
1784
+ // Only SequenceIntervals need potential sliding
1785
+ if (!(interval instanceof SequenceInterval)) {
1786
+ return;
1787
+ }
1788
+
1789
+ if (
1790
+ !refTypeIncludesFlag(interval.start, ReferenceType.StayOnRemove) &&
1791
+ !refTypeIncludesFlag(interval.end, ReferenceType.StayOnRemove)
1792
+ ) {
1793
+ return;
1794
+ }
1795
+
1796
+ const newStart = this.getSlideToSegment(interval.start);
1797
+ const newEnd = this.getSlideToSegment(interval.end);
1798
+
1799
+ const id = interval.properties[reservedIntervalIdKey];
1800
+ const hasPendingStartChange = this.hasPendingChangeStart(id);
1801
+ const hasPendingEndChange = this.hasPendingChangeEnd(id);
1802
+
1803
+ if (!hasPendingStartChange) {
1804
+ setSlideOnRemove(interval.start);
1805
+ }
1806
+
1807
+ if (!hasPendingEndChange) {
1808
+ setSlideOnRemove(interval.end);
1809
+ }
1810
+
1811
+ const needsStartUpdate = newStart !== undefined && !hasPendingStartChange;
1812
+ const needsEndUpdate = newEnd !== undefined && !hasPendingEndChange;
1813
+
1814
+ if (needsStartUpdate || needsEndUpdate) {
1815
+ if (!this.localCollection) {
1816
+ throw new LoggingError("Attach must be called before accessing intervals");
1817
+ }
1818
+
1819
+ // `interval`'s endpoints will get modified in-place, so clone it prior to doing so for event emission.
1820
+ const oldInterval = interval.clone() as TInterval & SequenceInterval;
1821
+
1822
+ // In this case, where we change the start or end of an interval,
1823
+ // it is necessary to remove and re-add the interval listeners.
1824
+ // This ensures that the correct listeners are added to the LocalReferencePosition.
1825
+ this.localCollection.removeExistingInterval(interval);
1826
+ if (!this.client) {
1827
+ throw new LoggingError("client does not exist");
1828
+ }
1829
+
1830
+ if (needsStartUpdate) {
1831
+ const props = interval.start.properties;
1832
+ interval.start = createPositionReferenceFromSegoff(
1833
+ this.client,
1834
+ newStart,
1835
+ interval.start.refType,
1836
+ op,
1837
+ undefined,
1838
+ undefined,
1839
+ startReferenceSlidingPreference(interval.stickiness),
1840
+ startReferenceSlidingPreference(interval.stickiness) ===
1841
+ SlidingPreference.BACKWARD,
1842
+ );
1843
+ if (props) {
1844
+ interval.start.addProperties(props);
1845
+ }
1846
+ const oldSeg = oldInterval.start.getSegment();
1847
+ // remove and rebuild start interval as transient for event
1848
+ this.client.removeLocalReferencePosition(oldInterval.start);
1849
+ oldInterval.start.refType = ReferenceType.Transient;
1850
+ oldSeg?.localRefs?.addLocalRef(oldInterval.start, oldInterval.start.getOffset());
1851
+ }
1852
+ if (needsEndUpdate) {
1853
+ const props = interval.end.properties;
1854
+ interval.end = createPositionReferenceFromSegoff(
1855
+ this.client,
1856
+ newEnd,
1857
+ interval.end.refType,
1858
+ op,
1859
+ undefined,
1860
+ undefined,
1861
+ endReferenceSlidingPreference(interval.stickiness),
1862
+ endReferenceSlidingPreference(interval.stickiness) ===
1863
+ SlidingPreference.FORWARD,
1864
+ );
1865
+ if (props) {
1866
+ interval.end.addProperties(props);
1867
+ }
1868
+ // remove and rebuild end interval as transient for event
1869
+ const oldSeg = oldInterval.end.getSegment();
1870
+ this.client.removeLocalReferencePosition(oldInterval.end);
1871
+ oldInterval.end.refType = ReferenceType.Transient;
1872
+ oldSeg?.localRefs?.addLocalRef(oldInterval.end, oldInterval.end.getOffset());
1873
+ }
1874
+ this.localCollection.add(interval);
1875
+ this.emitChange(interval, oldInterval as TInterval, true, true, op);
1876
+ }
1877
+ }
1878
+
1879
+ /** @internal */
1880
+ public ackAdd(
1881
+ serializedInterval: ISerializedInterval,
1882
+ local: boolean,
1883
+ op: ISequencedDocumentMessage,
1884
+ localOpMetadata: IMapMessageLocalMetadata | undefined,
1885
+ ) {
1886
+ if (local) {
1887
+ assert(
1888
+ localOpMetadata !== undefined,
1889
+ 0x553 /* op metadata should be defined for local op */,
1890
+ );
1891
+ this.localSeqToSerializedInterval.delete(localOpMetadata.localSeq);
1892
+ const id: string = serializedInterval.properties?.[reservedIntervalIdKey];
1893
+ const localInterval = this.getIntervalById(id);
1894
+ if (localInterval) {
1895
+ this.ackInterval(localInterval, op);
1896
+ }
1897
+ return;
1898
+ }
1899
+
1900
+ if (!this.localCollection) {
1901
+ throw new LoggingError("attachSequence must be called");
1902
+ }
1903
+
1904
+ this.localCollection.ensureSerializedId(serializedInterval);
1905
+
1906
+ const interval: TInterval = this.localCollection.addInterval(
1907
+ toSequencePlace(serializedInterval.start, serializedInterval.startSide ?? Side.Before),
1908
+ toSequencePlace(serializedInterval.end, serializedInterval.endSide ?? Side.Before),
1909
+ serializedInterval.intervalType,
1910
+ serializedInterval.properties,
1911
+ op,
1912
+ );
1913
+
1914
+ if (interval) {
1915
+ if (this.onDeserialize) {
1916
+ this.onDeserialize(interval);
1917
+ }
1918
+ }
1919
+
1920
+ this.emit("addInterval", interval, local, op);
1921
+
1922
+ return interval;
1923
+ }
1924
+
1925
+ /** @internal */
1926
+ public ackDelete(
1927
+ serializedInterval: ISerializedInterval,
1928
+ local: boolean,
1929
+ op: ISequencedDocumentMessage,
1930
+ ): void {
1931
+ if (local) {
1932
+ // Local ops were applied when the message was created and there's no "pending delete"
1933
+ // state to book keep: remote operation application takes into account possibility of
1934
+ // locally deleted interval whenever a lookup happens.
1935
+ return;
1936
+ }
1937
+
1938
+ if (!this.localCollection) {
1939
+ throw new LoggingError("attach must be called prior to deleting intervals");
1940
+ }
1941
+
1942
+ const id = this.localCollection.ensureSerializedId(serializedInterval);
1943
+ const interval = this.localCollection.idIntervalIndex.getIntervalById(id);
1944
+ if (interval) {
1945
+ this.deleteExistingInterval(interval, local, op);
1946
+ }
1947
+ }
1948
+
1949
+ /**
1950
+ * @internal
1951
+ */
1952
+ public serializeInternal(): ISerializedIntervalCollectionV2 {
1953
+ if (!this.localCollection) {
1954
+ throw new LoggingError("attachSequence must be called");
1955
+ }
1956
+
1957
+ return this.localCollection.serialize();
1958
+ }
1959
+
1960
+ /**
1961
+ * @returns an iterator over all intervals in this collection.
1962
+ */
1963
+ public [Symbol.iterator](): IntervalCollectionIterator<TInterval> {
1964
+ const iterator = new IntervalCollectionIterator<TInterval>(this);
1965
+ return iterator;
1966
+ }
1967
+
1968
+ /**
1969
+ * {@inheritdoc IIntervalCollection.CreateForwardIteratorWithStartPosition}
1970
+ */
1971
+ public CreateForwardIteratorWithStartPosition(
1972
+ startPosition: number,
1973
+ ): IntervalCollectionIterator<TInterval> {
1974
+ const iterator = new IntervalCollectionIterator<TInterval>(this, true, startPosition);
1975
+ return iterator;
1976
+ }
1977
+
1978
+ /**
1979
+ * {@inheritdoc IIntervalCollection.CreateBackwardIteratorWithStartPosition}
1980
+ */
1981
+ public CreateBackwardIteratorWithStartPosition(
1982
+ startPosition: number,
1983
+ ): IntervalCollectionIterator<TInterval> {
1984
+ const iterator = new IntervalCollectionIterator<TInterval>(this, false, startPosition);
1985
+ return iterator;
1986
+ }
1987
+
1988
+ /**
1989
+ * {@inheritdoc IIntervalCollection.CreateForwardIteratorWithEndPosition}
1990
+ */
1991
+ public CreateForwardIteratorWithEndPosition(
1992
+ endPosition: number,
1993
+ ): IntervalCollectionIterator<TInterval> {
1994
+ const iterator = new IntervalCollectionIterator<TInterval>(
1995
+ this,
1996
+ true,
1997
+ undefined,
1998
+ endPosition,
1999
+ );
2000
+ return iterator;
2001
+ }
2002
+
2003
+ /**
2004
+ * {@inheritdoc IIntervalCollection.CreateBackwardIteratorWithEndPosition}
2005
+ */
2006
+ public CreateBackwardIteratorWithEndPosition(
2007
+ endPosition: number,
2008
+ ): IntervalCollectionIterator<TInterval> {
2009
+ const iterator = new IntervalCollectionIterator<TInterval>(
2010
+ this,
2011
+ false,
2012
+ undefined,
2013
+ endPosition,
2014
+ );
2015
+ return iterator;
2016
+ }
2017
+
2018
+ /**
2019
+ * {@inheritdoc IIntervalCollection.gatherIterationResults}
2020
+ */
2021
+ public gatherIterationResults(
2022
+ results: TInterval[],
2023
+ iteratesForward: boolean,
2024
+ start?: number,
2025
+ end?: number,
2026
+ ) {
2027
+ if (!this.localCollection) {
2028
+ return;
2029
+ }
2030
+
2031
+ this.localCollection.overlappingIntervalsIndex.gatherIterationResults(
2032
+ results,
2033
+ iteratesForward,
2034
+ start,
2035
+ end,
2036
+ );
2037
+ }
2038
+
2039
+ /**
2040
+ * {@inheritdoc IIntervalCollection.findOverlappingIntervals}
2041
+ */
2042
+ public findOverlappingIntervals(startPosition: number, endPosition: number): TInterval[] {
2043
+ if (!this.localCollection) {
2044
+ throw new LoggingError("attachSequence must be called");
2045
+ }
2046
+
2047
+ return this.localCollection.overlappingIntervalsIndex.findOverlappingIntervals(
2048
+ startPosition,
2049
+ endPosition,
2050
+ );
2051
+ }
2052
+
2053
+ /**
2054
+ * {@inheritdoc IIntervalCollection.map}
2055
+ */
2056
+ public map(fn: (interval: TInterval) => void) {
2057
+ if (!this.localCollection) {
2058
+ throw new LoggingError("attachSequence must be called");
2059
+ }
2060
+
2061
+ for (const interval of this.localCollection.idIntervalIndex) {
2062
+ fn(interval);
2063
+ }
2064
+ }
2065
+
2066
+ /**
2067
+ * {@inheritdoc IIntervalCollection.previousInterval}
2068
+ */
2069
+ public previousInterval(pos: number): TInterval | undefined {
2070
+ if (!this.localCollection) {
2071
+ throw new LoggingError("attachSequence must be called");
2072
+ }
2073
+
2074
+ return this.localCollection.endIntervalIndex.previousInterval(pos);
2075
+ }
2076
+
2077
+ /**
2078
+ * {@inheritdoc IIntervalCollection.nextInterval}
2079
+ */
2080
+ public nextInterval(pos: number): TInterval | undefined {
2081
+ if (!this.localCollection) {
2082
+ throw new LoggingError("attachSequence must be called");
2083
+ }
2084
+
2085
+ return this.localCollection.endIntervalIndex.nextInterval(pos);
2086
+ }
987
2087
  }
988
2088
 
989
- export type DeserializeCallback = (properties: PropertySet) => void;
990
-
991
- export class IntervalCollectionIterator<TInterval extends ISerializableInterval> {
992
- private readonly results: TInterval[];
993
- private index: number;
994
-
995
- constructor(
996
- collection: IntervalCollection<TInterval>,
997
- iteratesForward: boolean = true,
998
- start?: number,
999
- end?: number) {
1000
- this.results = [];
1001
- this.index = 0;
1002
-
1003
- collection.gatherIterationResults(this.results, iteratesForward, start, end);
1004
- }
1005
-
1006
- public next() {
1007
- let _value: TInterval | undefined;
1008
- let _done: boolean = true;
1009
-
1010
- if (this.index < this.results.length) {
1011
- _value = this.results[this.index++];
1012
- _done = false;
1013
- }
1014
-
1015
- return {
1016
- value: _value,
1017
- done: _done,
1018
- };
1019
- }
2089
+ function setSlideOnRemove(lref: LocalReferencePosition) {
2090
+ let refType = lref.refType;
2091
+ refType = refType & ~ReferenceType.StayOnRemove;
2092
+ refType = refType | ReferenceType.SlideOnRemove;
2093
+ lref.refType = refType;
1020
2094
  }
1021
2095
 
1022
- export interface IIntervalCollectionEvent<TInterval extends ISerializableInterval> extends IEvent {
1023
- /**
1024
- * This event is invoked whenever the properties or endpoints of an interval may have changed.
1025
- * This can happen on:
1026
- * - endpoint modification (local or remote)
1027
- * - ack of an endpoint modification
1028
- * - property change (local or remote)
1029
- * - position change due to segment sliding (will always appear as a local change)
1030
- * The `interval` argument reflects the new values.
1031
- */
1032
- (event: "changeInterval",
1033
- listener: (interval: TInterval, local: boolean, op: ISequencedDocumentMessage | undefined) => void);
1034
- (event: "addInterval" | "deleteInterval",
1035
- listener: (interval: TInterval, local: boolean, op: ISequencedDocumentMessage) => void);
1036
- (event: "propertyChanged", listener: (interval: TInterval, propertyArgs: PropertySet) => void);
2096
+ /**
2097
+ * Information that identifies an interval within a `Sequence`.
2098
+ * @internal
2099
+ */
2100
+ export interface IntervalLocator {
2101
+ /**
2102
+ * Label for the collection the interval is a part of
2103
+ */
2104
+ label: string;
2105
+ /**
2106
+ * Interval within that collection
2107
+ */
2108
+ interval: SequenceInterval;
1037
2109
  }
1038
2110
 
1039
- export class IntervalCollection<TInterval extends ISerializableInterval>
1040
- extends TypedEventEmitter<IIntervalCollectionEvent<TInterval>> {
1041
- private savedSerializedIntervals?: ISerializedInterval[];
1042
- private localCollection: LocalIntervalCollection<TInterval>;
1043
- private onDeserialize: DeserializeCallback | undefined;
1044
- private client: Client;
1045
- private readonly pendingChangesStart: Map<string, ISerializedInterval[]> = new Map<string, ISerializedInterval[]>();
1046
- private readonly pendingChangesEnd: Map<string, ISerializedInterval[]> = new Map<string, ISerializedInterval[]>();
1047
-
1048
- public get attached(): boolean {
1049
- return !!this.localCollection;
1050
- }
1051
-
1052
- /** @internal */
1053
- constructor(
1054
- private readonly helpers: IIntervalHelpers<TInterval>,
1055
- private readonly requiresClient: boolean,
1056
- private readonly emitter: IValueOpEmitter,
1057
- serializedIntervals: ISerializedInterval[] | ISerializedIntervalCollectionV2,
1058
- ) {
1059
- super();
1060
-
1061
- if (Array.isArray(serializedIntervals)) {
1062
- this.savedSerializedIntervals = serializedIntervals;
1063
- } else {
1064
- this.savedSerializedIntervals =
1065
- serializedIntervals.intervals.map((i) => decompressInterval(i, serializedIntervals.label));
1066
- }
1067
- }
1068
-
1069
- public attachGraph(client: Client, label: string) {
1070
- if (this.attached) {
1071
- throw new LoggingError("Only supports one Sequence attach");
1072
- }
1073
-
1074
- if ((client === undefined) && (this.requiresClient)) {
1075
- throw new LoggingError("Client required for this collection");
1076
- }
1077
-
1078
- // Instantiate the local interval collection based on the saved intervals
1079
- this.client = client;
1080
- this.localCollection = new LocalIntervalCollection<TInterval>(
1081
- client,
1082
- label,
1083
- this.helpers,
1084
- (interval) => this.emit("changeInterval", interval, true, undefined),
1085
- );
1086
- if (this.savedSerializedIntervals) {
1087
- for (const serializedInterval of this.savedSerializedIntervals) {
1088
- this.localCollection.ensureSerializedId(serializedInterval);
1089
- this.localCollection.addInterval(
1090
- serializedInterval.start,
1091
- serializedInterval.end,
1092
- serializedInterval.intervalType,
1093
- serializedInterval.properties);
1094
- }
1095
- }
1096
- this.savedSerializedIntervals = undefined;
1097
- }
1098
-
1099
- /**
1100
- * Gets the next local sequence number, modifying this client's collab window in doing so.
1101
- */
1102
- private getNextLocalSeq(): number {
1103
- return ++this.client.getCollabWindow().localSeq;
1104
- }
1105
-
1106
- public getIntervalById(id: string) {
1107
- if (!this.attached) {
1108
- throw new LoggingError("attach must be called before accessing intervals");
1109
- }
1110
- return this.localCollection.getIntervalById(id);
1111
- }
1112
-
1113
- /**
1114
- * Create a new interval and add it to the collection
1115
- * @param start - interval start position
1116
- * @param end - interval end position
1117
- * @param intervalType - type of the interval. All intervals are SlideOnRemove. Intervals may not be Transient.
1118
- * @param props - properties of the interval
1119
- * @returns - the created interval
1120
- */
1121
- public add(
1122
- start: number,
1123
- end: number,
1124
- intervalType: IntervalType,
1125
- props?: PropertySet,
1126
- ) {
1127
- if (!this.attached) {
1128
- throw new LoggingError("attach must be called prior to adding intervals");
1129
- }
1130
- if (intervalType & IntervalType.Transient) {
1131
- throw new LoggingError("Can not add transient intervals");
1132
- }
1133
-
1134
- const interval: TInterval = this.localCollection.addInterval(start, end, intervalType, props);
1135
-
1136
- if (interval) {
1137
- const serializedInterval = {
1138
- end,
1139
- intervalType,
1140
- properties: interval.properties,
1141
- sequenceNumber: this.client?.getCurrentSeq() ?? 0,
1142
- start,
1143
- };
1144
- // Local ops get submitted to the server. Remote ops have the deserializer run.
1145
- this.emitter.emit("add", undefined, serializedInterval, { localSeq: this.getNextLocalSeq() });
1146
- }
1147
-
1148
- this.emit("addInterval", interval, true, undefined);
1149
-
1150
- return interval;
1151
- }
1152
-
1153
- private deleteExistingInterval(interval: TInterval, local: boolean, op?: ISequencedDocumentMessage) {
1154
- // The given interval is known to exist in the collection.
1155
- this.localCollection.removeExistingInterval(interval);
1156
-
1157
- if (interval) {
1158
- // Local ops get submitted to the server. Remote ops have the deserializer run.
1159
- if (local) {
1160
- this.emitter.emit(
1161
- "delete",
1162
- undefined,
1163
- interval.serialize(this.client),
1164
- { localSeq: this.getNextLocalSeq() },
1165
- );
1166
- } else {
1167
- if (this.onDeserialize) {
1168
- this.onDeserialize(interval);
1169
- }
1170
- }
1171
- }
1172
-
1173
- this.emit("deleteInterval", interval, local, op);
1174
- }
1175
-
1176
- public removeIntervalById(id: string) {
1177
- const interval = this.localCollection.getIntervalById(id);
1178
- if (interval) {
1179
- this.deleteExistingInterval(interval, true, undefined);
1180
- }
1181
- return interval;
1182
- }
1183
-
1184
- public changeProperties(id: string, props: PropertySet) {
1185
- if (!this.attached) {
1186
- throw new LoggingError("Attach must be called before accessing intervals");
1187
- }
1188
- if (typeof (id) !== "string") {
1189
- throw new LoggingError("Change API requires an ID that is a string");
1190
- }
1191
- if (!props) {
1192
- throw new LoggingError("changeProperties should be called with a property set");
1193
- }
1194
-
1195
- const interval = this.getIntervalById(id);
1196
- if (interval) {
1197
- // Pass Unassigned as the sequence number to indicate that this is a local op that is waiting for an ack.
1198
- const deltaProps = interval.addProperties(props, true, UnassignedSequenceNumber);
1199
- const serializedInterval: ISerializedInterval = interval.serialize(this.client);
1200
-
1201
- // Emit a change op that will only change properties. Add the ID to
1202
- // the property bag provided by the caller.
1203
- serializedInterval.start = undefined as any;
1204
- serializedInterval.end = undefined as any;
1205
-
1206
- serializedInterval.properties = props;
1207
- serializedInterval.properties[reservedIntervalIdKey] = interval.getIntervalId();
1208
- this.emitter.emit("change", undefined, serializedInterval, { localSeq: this.getNextLocalSeq() });
1209
- this.emit("propertyChanged", interval, deltaProps);
1210
- }
1211
- this.emit("changeInterval", interval, true, undefined);
1212
- }
1213
-
1214
- public change(id: string, start?: number, end?: number): TInterval | undefined {
1215
- if (!this.attached) {
1216
- throw new LoggingError("Attach must be called before accessing intervals");
1217
- }
1218
-
1219
- // Force id to be a string.
1220
- if (typeof (id) !== "string") {
1221
- throw new LoggingError("Change API requires an ID that is a string");
1222
- }
1223
-
1224
- const interval = this.getIntervalById(id);
1225
- if (interval) {
1226
- const newInterval = this.localCollection.changeInterval(interval, start, end);
1227
- const serializedInterval: ISerializedInterval = interval.serialize(this.client);
1228
- serializedInterval.start = start;
1229
- serializedInterval.end = end;
1230
- // Emit a property bag containing only the ID, as we don't intend for this op to change any properties.
1231
- serializedInterval.properties =
1232
- {
1233
- [reservedIntervalIdKey]: interval.getIntervalId(),
1234
- };
1235
- this.emitter.emit("change", undefined, serializedInterval, { localSeq: this.getNextLocalSeq() });
1236
- this.addPendingChange(id, serializedInterval);
1237
- this.emit("changeInterval", newInterval, true, undefined);
1238
- return newInterval;
1239
- }
1240
- // No interval to change
1241
- return undefined;
1242
- }
1243
-
1244
- private addPendingChange(id: string, serializedInterval: ISerializedInterval) {
1245
- if (serializedInterval.start !== undefined) {
1246
- this.addPendingChangeHelper(id, this.pendingChangesStart, serializedInterval);
1247
- }
1248
- if (serializedInterval.end !== undefined) {
1249
- this.addPendingChangeHelper(id, this.pendingChangesEnd, serializedInterval);
1250
- }
1251
- }
1252
-
1253
- private addPendingChangeHelper(
1254
- id: string,
1255
- pendingChanges: Map<string, ISerializedInterval[]>,
1256
- serializedInterval: ISerializedInterval,
1257
- ) {
1258
- let entries: ISerializedInterval[] | undefined = pendingChanges.get(id);
1259
- if (!entries) {
1260
- entries = [];
1261
- pendingChanges.set(id, entries);
1262
- }
1263
- entries.push(serializedInterval);
1264
- }
1265
-
1266
- private removePendingChange(serializedInterval: ISerializedInterval) {
1267
- // Change ops always have an ID.
1268
- const id: string = serializedInterval.properties?.[reservedIntervalIdKey];
1269
- if (serializedInterval.start !== undefined) {
1270
- this.removePendingChangeHelper(id, this.pendingChangesStart, serializedInterval);
1271
- }
1272
- if (serializedInterval.end !== undefined) {
1273
- this.removePendingChangeHelper(id, this.pendingChangesEnd, serializedInterval);
1274
- }
1275
- }
1276
-
1277
- private removePendingChangeHelper(
1278
- id: string,
1279
- pendingChanges: Map<string, ISerializedInterval[]>,
1280
- serializedInterval: ISerializedInterval,
1281
- ) {
1282
- const entries = pendingChanges.get(id);
1283
- if (entries) {
1284
- const pendingChange = entries.shift();
1285
- if (entries.length === 0) {
1286
- pendingChanges.delete(id);
1287
- }
1288
- if (pendingChange?.start !== serializedInterval.start ||
1289
- pendingChange?.end !== serializedInterval.end) {
1290
- throw new LoggingError("Mismatch in pending changes");
1291
- }
1292
- }
1293
- }
1294
-
1295
- private hasPendingChangeStart(id: string) {
1296
- const entries = this.pendingChangesStart.get(id);
1297
- return entries && entries.length !== 0;
1298
- }
1299
-
1300
- private hasPendingChangeEnd(id: string) {
1301
- const entries = this.pendingChangesEnd.get(id);
1302
- return entries && entries.length !== 0;
1303
- }
1304
-
1305
- /** @deprecated - use ackChange */
1306
- public changeInterval(serializedInterval: ISerializedInterval, local: boolean, op: ISequencedDocumentMessage) {
1307
- return this.ackChange(serializedInterval, local, op);
1308
- }
1309
-
1310
- /** @internal */
1311
- public ackChange(serializedInterval: ISerializedInterval, local: boolean, op: ISequencedDocumentMessage) {
1312
- if (!this.attached) {
1313
- throw new LoggingError("Attach must be called before accessing intervals");
1314
- }
1315
-
1316
- let interval: TInterval | undefined;
1317
-
1318
- if (local) {
1319
- // This is an ack from the server. Remove the pending change.
1320
- this.removePendingChange(serializedInterval);
1321
- const id: string = serializedInterval.properties?.[reservedIntervalIdKey];
1322
- interval = this.getIntervalById(id);
1323
- if (interval) {
1324
- // Let the propertyManager prune its pending change-properties set.
1325
- interval.propertyManager?.ackPendingProperties(
1326
- {
1327
- type: MergeTreeDeltaType.ANNOTATE,
1328
- props: serializedInterval.properties ?? {},
1329
- });
1330
-
1331
- this.ackInterval(interval, op);
1332
- }
1333
- } else {
1334
- // If there are pending changes with this ID, don't apply the remote start/end change, as the local ack
1335
- // should be the winning change.
1336
- // Note that the ID is in the property bag only to allow us to find the interval.
1337
- // This API cannot change the ID, and writing to the ID property will result in an exception. So we
1338
- // strip it out of the properties here.
1339
- const { [reservedIntervalIdKey]: id, ...newProps } = serializedInterval.properties;
1340
- interval = this.getIntervalById(id);
1341
- if (interval) {
1342
- let start: number | undefined;
1343
- let end: number | undefined;
1344
- // Track pending start/end independently of one another.
1345
- if (!this.hasPendingChangeStart(id)) {
1346
- start = serializedInterval.start;
1347
- }
1348
- if (!this.hasPendingChangeEnd(id)) {
1349
- end = serializedInterval.end;
1350
- }
1351
- if (start !== undefined || end !== undefined) {
1352
- // If changeInterval gives us a new interval, work with that one. Otherwise keep working with
1353
- // the one we originally found in the tree.
1354
- interval = this.localCollection.changeInterval(interval, start, end, op) ?? interval;
1355
- }
1356
- const deltaProps = interval.addProperties(newProps, true, op.sequenceNumber);
1357
- if (this.onDeserialize) {
1358
- this.onDeserialize(interval);
1359
- }
1360
- this.emit("propertyChanged", interval, deltaProps);
1361
- }
1362
- }
1363
- if (interval) {
1364
- this.emit("changeInterval", interval, local, op);
1365
- }
1366
- }
1367
-
1368
- public addConflictResolver(conflictResolver: IntervalConflictResolver<TInterval>): void {
1369
- if (!this.attached) {
1370
- throw new LoggingError("attachSequence must be called");
1371
- }
1372
- this.localCollection.addConflictResolver(conflictResolver);
1373
- }
1374
-
1375
- public attachDeserializer(onDeserialize: DeserializeCallback): void {
1376
- // If no deserializer is specified can skip all processing work
1377
- if (!onDeserialize) {
1378
- return;
1379
- }
1380
-
1381
- // Start by storing the callbacks so that any subsequent modifications make use of them
1382
- this.onDeserialize = onDeserialize;
1383
-
1384
- // Trigger the async prepare work across all values in the collection
1385
- this.localCollection.map((interval) => {
1386
- onDeserialize(interval);
1387
- });
1388
- }
1389
-
1390
- /** @internal */
1391
- public rebaseLocalInterval(
1392
- opName: string,
1393
- serializedInterval: ISerializedInterval,
1394
- localSeq: number,
1395
- ) {
1396
- if (!this.attached) {
1397
- throw new LoggingError("attachSequence must be called");
1398
- }
1399
-
1400
- const { start, end, intervalType, properties, sequenceNumber } = serializedInterval;
1401
- const startRebased = start === undefined ? undefined :
1402
- this.client.rebasePosition(start, sequenceNumber, localSeq);
1403
- const endRebased = end === undefined ? undefined :
1404
- this.client.rebasePosition(end, sequenceNumber, localSeq);
1405
-
1406
- const intervalId = properties?.[reservedIntervalIdKey];
1407
- const rebased: ISerializedInterval = {
1408
- start: startRebased,
1409
- end: endRebased,
1410
- intervalType,
1411
- sequenceNumber: this.client?.getCurrentSeq() ?? 0,
1412
- properties,
1413
- };
1414
- if (opName === "change" && (this.hasPendingChangeStart(intervalId) || this.hasPendingChangeEnd(intervalId))) {
1415
- this.removePendingChange(serializedInterval);
1416
- this.addPendingChange(intervalId, rebased);
1417
- }
1418
- return rebased;
1419
- }
1420
-
1421
- private getSlideToSegment(lref: LocalReference) {
1422
- const segoff = { segment: lref.segment, offset: lref.offset };
1423
- const newSegoff = this.client.getSlideToSegment(segoff);
1424
- const value: { segment: ISegment | undefined; offset: number | undefined; } | undefined
1425
- = (segoff.segment === newSegoff.segment && segoff.offset === newSegoff.offset) ? undefined : newSegoff;
1426
- return value;
1427
- }
1428
-
1429
- private setSlideOnRemove(lref: LocalReference) {
1430
- let refType = lref.refType;
1431
- refType = refType & ~ReferenceType.StayOnRemove;
1432
- refType = refType | ReferenceType.SlideOnRemove;
1433
- lref.refType = refType;
1434
- }
1435
-
1436
- private ackInterval(interval: TInterval, op: ISequencedDocumentMessage) {
1437
- // in current usage, interval is always a SequenceInterval
1438
- if (!(interval instanceof SequenceInterval)) {
1439
- return;
1440
- }
1441
-
1442
- if (!refTypeIncludesFlag(interval.start, ReferenceType.StayOnRemove) &&
1443
- !refTypeIncludesFlag(interval.end, ReferenceType.StayOnRemove)) {
1444
- return;
1445
- }
1446
-
1447
- const newStart = this.getSlideToSegment(interval.start);
1448
- const newEnd = this.getSlideToSegment(interval.end);
1449
-
1450
- const id = interval.properties[reservedIntervalIdKey];
1451
- const hasPendingStartChange = this.hasPendingChangeStart(id);
1452
- const hasPendingEndChange = this.hasPendingChangeEnd(id);
1453
-
1454
- if (!hasPendingStartChange) {
1455
- this.setSlideOnRemove(interval.start);
1456
- }
1457
-
1458
- if (!hasPendingEndChange) {
1459
- this.setSlideOnRemove(interval.end);
1460
- }
1461
-
1462
- const needsStartUpdate = newStart !== undefined && !hasPendingStartChange;
1463
- const needsEndUpdate = newEnd !== undefined && !hasPendingEndChange;
1464
-
1465
- if (needsStartUpdate || needsEndUpdate) {
1466
- // In this case, where we change the start or end of an interval,
1467
- // it is necessary to remove and re-add the interval listeners.
1468
- // This ensures that the correct listeners are added to the ReferencePosition.
1469
- this.localCollection.removeExistingInterval(interval);
1470
-
1471
- if (needsStartUpdate) {
1472
- const props = interval.start.properties;
1473
- this.client.removeLocalReferencePosition(interval.start);
1474
- interval.start = createPositionReferenceFromSegoff(this.client, newStart, interval.start.refType, op);
1475
- if (props) {
1476
- interval.start.addProperties(props);
1477
- }
1478
- }
1479
- if (needsEndUpdate) {
1480
- const props = interval.end.properties;
1481
- this.client.removeLocalReferencePosition(interval.end);
1482
- interval.end = createPositionReferenceFromSegoff(this.client, newEnd, interval.end.refType, op);
1483
- if (props) {
1484
- interval.end.addProperties(props);
1485
- }
1486
- }
1487
- this.localCollection.add(interval);
1488
- }
1489
- }
1490
-
1491
- /** @deprecated - use ackAdd */
1492
- public addInternal(
1493
- serializedInterval: ISerializedInterval,
1494
- local: boolean,
1495
- op: ISequencedDocumentMessage) {
1496
- return this.ackAdd(serializedInterval, local, op);
1497
- }
1498
-
1499
- /** @internal */
1500
- public ackAdd(
1501
- serializedInterval: ISerializedInterval,
1502
- local: boolean,
1503
- op: ISequencedDocumentMessage) {
1504
- if (local) {
1505
- const id: string = serializedInterval.properties?.[reservedIntervalIdKey];
1506
- const localInterval = this.getIntervalById(id);
1507
- if (localInterval) {
1508
- this.ackInterval(localInterval, op);
1509
- }
1510
- return;
1511
- }
1512
-
1513
- if (!this.attached) {
1514
- throw new LoggingError("attachSequence must be called");
1515
- }
1516
-
1517
- this.localCollection.ensureSerializedId(serializedInterval);
1518
-
1519
- const interval: TInterval = this.localCollection.addInterval(
1520
- serializedInterval.start,
1521
- serializedInterval.end,
1522
- serializedInterval.intervalType,
1523
- serializedInterval.properties,
1524
- op);
1525
-
1526
- if (interval) {
1527
- if (this.onDeserialize) {
1528
- this.onDeserialize(interval);
1529
- }
1530
- }
1531
-
1532
- this.emit("addInterval", interval, local, op);
1533
-
1534
- return interval;
1535
- }
1536
-
1537
- /** @deprecated - use ackDelete */
1538
- public deleteInterval(
1539
- serializedInterval: ISerializedInterval,
1540
- local: boolean,
1541
- op: ISequencedDocumentMessage): void {
1542
- return this.ackDelete(serializedInterval, local, op);
1543
- }
1544
-
1545
- /** @internal */
1546
- public ackDelete(
1547
- serializedInterval: ISerializedInterval,
1548
- local: boolean,
1549
- op: ISequencedDocumentMessage): void {
1550
- if (local) {
1551
- // Local ops were applied when the message was created and there's no "pending delete"
1552
- // state to bookkeep: remote operation application takes into account possibility of
1553
- // locally deleted interval whenever a lookup happens.
1554
- return;
1555
- }
1556
-
1557
- if (!this.attached) {
1558
- throw new LoggingError("attach must be called prior to deleting intervals");
1559
- }
1560
-
1561
- const id = this.localCollection.ensureSerializedId(serializedInterval);
1562
- const interval = this.localCollection.getIntervalById(id);
1563
- if (interval) {
1564
- this.deleteExistingInterval(interval, local, op);
1565
- }
1566
- }
1567
-
1568
- /**
1569
- * @internal
1570
- */
1571
- public serializeInternal(): ISerializedIntervalCollectionV2 {
1572
- if (!this.attached) {
1573
- throw new LoggingError("attachSequence must be called");
1574
- }
1575
-
1576
- return this.localCollection.serialize();
1577
- }
1578
-
1579
- public [Symbol.iterator](): IntervalCollectionIterator<TInterval> {
1580
- const iterator = new IntervalCollectionIterator<TInterval>(this);
1581
- return iterator;
1582
- }
1583
-
1584
- public CreateForwardIteratorWithStartPosition(startPosition: number): IntervalCollectionIterator<TInterval> {
1585
- const iterator = new IntervalCollectionIterator<TInterval>(this, true, startPosition);
1586
- return iterator;
1587
- }
1588
-
1589
- public CreateBackwardIteratorWithStartPosition(startPosition: number): IntervalCollectionIterator<TInterval> {
1590
- const iterator = new IntervalCollectionIterator<TInterval>(this, false, startPosition);
1591
- return iterator;
1592
- }
1593
-
1594
- public CreateForwardIteratorWithEndPosition(endPosition: number): IntervalCollectionIterator<TInterval> {
1595
- const iterator = new IntervalCollectionIterator<TInterval>(this, true, undefined, endPosition);
1596
- return iterator;
1597
- }
1598
-
1599
- public CreateBackwardIteratorWithEndPosition(endPosition: number): IntervalCollectionIterator<TInterval> {
1600
- const iterator = new IntervalCollectionIterator<TInterval>(this, false, undefined, endPosition);
1601
- return iterator;
1602
- }
1603
-
1604
- public gatherIterationResults(
1605
- results: TInterval[],
1606
- iteratesForward: boolean,
1607
- start?: number,
1608
- end?: number) {
1609
- if (!this.attached) {
1610
- return;
1611
- }
1612
-
1613
- this.localCollection.gatherIterationResults(results, iteratesForward, start, end);
1614
- }
1615
-
1616
- public findOverlappingIntervals(startPosition: number, endPosition: number): TInterval[] {
1617
- if (!this.attached) {
1618
- throw new LoggingError("attachSequence must be called");
1619
- }
1620
-
1621
- return this.localCollection.findOverlappingIntervals(startPosition, endPosition);
1622
- }
1623
-
1624
- public map(fn: (interval: TInterval) => void) {
1625
- if (!this.attached) {
1626
- throw new LoggingError("attachSequence must be called");
1627
- }
1628
-
1629
- this.localCollection.map(fn);
1630
- }
1631
-
1632
- public previousInterval(pos: number): TInterval {
1633
- if (!this.attached) {
1634
- throw new LoggingError("attachSequence must be called");
1635
- }
1636
-
1637
- return this.localCollection.previousInterval(pos);
1638
- }
1639
-
1640
- public nextInterval(pos: number): TInterval {
1641
- if (!this.attached) {
1642
- throw new LoggingError("attachSequence must be called");
1643
- }
1644
-
1645
- return this.localCollection.nextInterval(pos);
1646
- }
2111
+ /**
2112
+ * Returns an object that can be used to find the interval a given LocalReferencePosition belongs to.
2113
+ * @returns undefined if the reference position is not the endpoint of any interval (e.g. it was created
2114
+ * on the merge tree directly by app code), otherwise an {@link IntervalLocator} for the interval this
2115
+ * endpoint is a part of.
2116
+ * @internal
2117
+ */
2118
+ export function intervalLocatorFromEndpoint(
2119
+ potentialEndpoint: LocalReferencePosition,
2120
+ ): IntervalLocator | undefined {
2121
+ const { interval, [reservedRangeLabelsKey]: collectionNameArray } =
2122
+ potentialEndpoint.properties ?? {};
2123
+ return interval && collectionNameArray?.length === 1
2124
+ ? { label: collectionNameArray[0], interval }
2125
+ : undefined;
1647
2126
  }