ChunkTranslator.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. import _ from 'lodash'
  2. import logger from '@overleaf/logger'
  3. import OError from '@overleaf/o-error'
  4. import * as HistoryStoreManager from './HistoryStoreManager.js'
  5. import * as WebApiManager from './WebApiManager.js'
  6. import * as Errors from './Errors.js'
  7. import {
  8. TextOperation,
  9. InsertOp,
  10. RemoveOp,
  11. RetainOp,
  12. Range,
  13. TrackedChangeList,
  14. } from 'overleaf-editor-core'
  15. /**
  16. * @import { RawEditOperation, TrackedChangeRawData } from 'overleaf-editor-core/lib/types'
  17. */
  18. export function convertToSummarizedUpdates(chunk, callback) {
  19. const version = chunk.chunk.startVersion
  20. const { files } = chunk.chunk.history.snapshot
  21. const builder = new UpdateSetBuilder(version, files)
  22. for (const change of chunk.chunk.history.changes) {
  23. try {
  24. builder.applyChange(change)
  25. } catch (error1) {
  26. const error = error1
  27. return callback(error)
  28. }
  29. }
  30. callback(null, builder.summarizedUpdates)
  31. }
  32. export function convertToDiffUpdates(
  33. projectId,
  34. chunk,
  35. pathname,
  36. fromVersion,
  37. toVersion,
  38. callback
  39. ) {
  40. let error
  41. let version = chunk.chunk.startVersion
  42. const { files } = chunk.chunk.history.snapshot
  43. const builder = new UpdateSetBuilder(version, files)
  44. let file = null
  45. for (const change of chunk.chunk.history.changes) {
  46. // Because we're referencing by pathname, which can change, we
  47. // want to get the first file in the range fromVersion:toVersion
  48. // that has the pathname we want. Note that this might not exist yet
  49. // at fromVersion, so we'll just settle for the first one we find
  50. // after that.
  51. if (fromVersion <= version && version <= toVersion) {
  52. if (file == null) {
  53. file = builder.getFile(pathname)
  54. }
  55. }
  56. try {
  57. builder.applyChange(change)
  58. } catch (error1) {
  59. error = error1
  60. return callback(error)
  61. }
  62. version += 1
  63. }
  64. // Versions act as fence posts, with updates taking us from one to another,
  65. // so we also need to check after the final update, when we're at the last version.
  66. if (fromVersion <= version && version <= toVersion) {
  67. if (file == null) {
  68. file = builder.getFile(pathname)
  69. }
  70. }
  71. // return an empty diff if the file was flagged as missing with an explicit null
  72. if (builder.getFile(pathname) === null) {
  73. return callback(null, { initialContent: '', updates: [] })
  74. }
  75. if (file == null) {
  76. error = new Errors.NotFoundError(
  77. `pathname '${pathname}' not found in range`
  78. )
  79. return callback(error)
  80. }
  81. WebApiManager.getHistoryId(projectId, (err, historyId) => {
  82. if (err) {
  83. return callback(err)
  84. }
  85. file.getDiffUpdates(historyId, fromVersion, toVersion, callback)
  86. })
  87. }
  88. class UpdateSetBuilder {
  89. constructor(startVersion, files) {
  90. this.version = startVersion
  91. this.summarizedUpdates = []
  92. this.files = Object.create(null)
  93. for (const pathname in files) {
  94. // initialize file from snapshot
  95. const data = files[pathname]
  96. this.files[pathname] = new File(pathname, data, startVersion)
  97. }
  98. }
  99. getFile(pathname) {
  100. return this.files[pathname]
  101. }
  102. applyChange(change) {
  103. const timestamp = new Date(change.timestamp)
  104. let authors = _.map(change.authors, id => {
  105. if (id == null) {
  106. return null
  107. }
  108. return id
  109. })
  110. authors = authors.concat(change.v2Authors || [])
  111. this.currentUpdate = {
  112. meta: {
  113. users: authors,
  114. start_ts: timestamp.getTime(),
  115. end_ts: timestamp.getTime(),
  116. },
  117. v: this.version,
  118. pathnames: new Set([]),
  119. project_ops: [],
  120. }
  121. if (change.origin) {
  122. this.currentUpdate.meta.origin = change.origin
  123. }
  124. for (const op of change.operations) {
  125. this.applyOperation(op, timestamp, authors, change.origin)
  126. }
  127. this.currentUpdate.pathnames = Array.from(this.currentUpdate.pathnames)
  128. this.summarizedUpdates.push(this.currentUpdate)
  129. this.version += 1
  130. }
  131. applyOperation(op, timestamp, authors, origin) {
  132. if (UpdateSetBuilder._isTextOperation(op)) {
  133. this.applyTextOperation(op, timestamp, authors, origin)
  134. } else if (UpdateSetBuilder._isRenameOperation(op)) {
  135. this.applyRenameOperation(op, timestamp, authors)
  136. } else if (UpdateSetBuilder._isRemoveFileOperation(op)) {
  137. this.applyRemoveFileOperation(op, timestamp, authors)
  138. } else if (UpdateSetBuilder._isAddFileOperation(op)) {
  139. this.applyAddFileOperation(op, timestamp, authors)
  140. }
  141. }
  142. applyTextOperation(operation, timestamp, authors, origin) {
  143. const { pathname } = operation
  144. if (pathname === '') {
  145. // this shouldn't happen, but we continue to allow the user to see the history
  146. logger.warn(
  147. { operation, timestamp, authors },
  148. 'pathname is empty for text operation'
  149. )
  150. return
  151. }
  152. const file = this.files[pathname]
  153. if (file == null) {
  154. // this shouldn't happen, but we continue to allow the user to see the history
  155. logger.warn(
  156. { operation, timestamp, authors },
  157. 'file is missing for text operation'
  158. )
  159. this.files[pathname] = null // marker for a missing file
  160. return
  161. }
  162. file.applyTextOperation(authors, timestamp, this.version, operation, origin)
  163. this.currentUpdate.pathnames.add(pathname)
  164. }
  165. applyRenameOperation(operation, timestamp, authors) {
  166. const { pathname, newPathname } = operation
  167. const file = this.files[pathname]
  168. if (file == null) {
  169. // this shouldn't happen, but we continue to allow the user to see the history
  170. logger.warn(
  171. { operation, timestamp, authors },
  172. 'file is missing for rename operation'
  173. )
  174. this.files[pathname] = null // marker for a missing file
  175. return
  176. }
  177. file.rename(newPathname)
  178. delete this.files[pathname]
  179. this.files[newPathname] = file
  180. this.currentUpdate.project_ops.push({
  181. rename: { pathname, newPathname },
  182. })
  183. }
  184. applyAddFileOperation(operation, timestamp, authors) {
  185. const { pathname } = operation
  186. // add file
  187. this.files[pathname] = new File(pathname, operation.file, this.version)
  188. this.currentUpdate.project_ops.push({ add: { pathname } })
  189. }
  190. applyRemoveFileOperation(operation, timestamp, authors) {
  191. const { pathname } = operation
  192. const file = this.files[pathname]
  193. if (file == null) {
  194. // this shouldn't happen, but we continue to allow the user to see the history
  195. logger.warn(
  196. { operation, timestamp, authors },
  197. 'pathname not found when removing file'
  198. )
  199. this.files[pathname] = null // marker for a missing file
  200. return
  201. }
  202. delete this.files[pathname]
  203. this.currentUpdate.project_ops.push({ remove: { pathname } })
  204. }
  205. static _isTextOperation(op) {
  206. return Object.prototype.hasOwnProperty.call(op, 'textOperation')
  207. }
  208. static _isRenameOperation(op) {
  209. return (
  210. Object.prototype.hasOwnProperty.call(op, 'newPathname') &&
  211. op.newPathname !== ''
  212. )
  213. }
  214. static _isRemoveFileOperation(op) {
  215. return (
  216. Object.prototype.hasOwnProperty.call(op, 'newPathname') &&
  217. op.newPathname === ''
  218. )
  219. }
  220. static _isAddFileOperation(op) {
  221. return Object.prototype.hasOwnProperty.call(op, 'file')
  222. }
  223. }
  224. /**
  225. * @param {string} content
  226. * @param {TrackedChangeList} trackedChanges
  227. * @returns {string}
  228. */
  229. function removeTrackedDeletesFromString(content, trackedChanges) {
  230. let result = ''
  231. let cursor = 0
  232. const trackedDeletes = trackedChanges
  233. .asSorted()
  234. .filter(tc => tc.tracking.type === 'delete')
  235. for (const trackedChange of trackedDeletes) {
  236. if (cursor < trackedChange.range.start) {
  237. result += content.slice(cursor, trackedChange.range.start)
  238. }
  239. // skip the tracked change itself
  240. cursor = trackedChange.range.end
  241. }
  242. result += content.slice(cursor)
  243. return result
  244. }
  245. class File {
  246. constructor(pathname, snapshot, initialVersion) {
  247. this.pathname = pathname
  248. this.snapshot = snapshot
  249. this.initialVersion = initialVersion
  250. this.operations = []
  251. }
  252. applyTextOperation(authors, timestamp, version, operation, origin) {
  253. this.operations.push({ authors, timestamp, version, operation, origin })
  254. }
  255. rename(pathname) {
  256. this.pathname = pathname
  257. }
  258. getDiffUpdates(historyId, fromVersion, toVersion, callback) {
  259. if (this.snapshot.stringLength == null) {
  260. // Binary file
  261. return callback(null, { binary: true })
  262. }
  263. this._loadContentAndRanges(historyId, (error, content, ranges) => {
  264. if (error != null) {
  265. return callback(OError.tag(error))
  266. }
  267. const trackedChanges = TrackedChangeList.fromRaw(
  268. ranges?.trackedChanges || []
  269. )
  270. /** @type {string | undefined} */
  271. let initialContent
  272. const updates = []
  273. for (const operationInfo of this.operations) {
  274. if (!('textOperation' in operationInfo.operation)) {
  275. // We only care about text operations
  276. continue
  277. }
  278. const { authors, timestamp, version, operation } = operationInfo
  279. // Set the initialContent to the latest version we have before the diff
  280. // begins. 'version' here refers to the document version as we are
  281. // applying the updates. So we store the content *before* applying the
  282. // updates.
  283. if (version >= fromVersion && initialContent === undefined) {
  284. initialContent = removeTrackedDeletesFromString(
  285. content,
  286. trackedChanges
  287. )
  288. }
  289. let ops
  290. ;({ content, ops } = this._convertTextOperation(
  291. content,
  292. operation,
  293. trackedChanges
  294. ))
  295. // We only need to return the updates between fromVersion and toVersion
  296. if (fromVersion <= version && version < toVersion) {
  297. const update = {
  298. meta: {
  299. users: authors,
  300. start_ts: timestamp.getTime(),
  301. end_ts: timestamp.getTime(),
  302. },
  303. v: version,
  304. op: ops,
  305. }
  306. if (operationInfo.origin) {
  307. update.meta.origin = operationInfo.origin
  308. }
  309. updates.push(update)
  310. }
  311. }
  312. if (initialContent === undefined) {
  313. initialContent = removeTrackedDeletesFromString(content, trackedChanges)
  314. }
  315. callback(null, { initialContent, updates })
  316. })
  317. }
  318. /**
  319. *
  320. * @param {string} initialContent
  321. * @param {RawEditOperation} operation
  322. * @param {TrackedChangeList} trackedChanges
  323. */
  324. _convertTextOperation(initialContent, operation, trackedChanges) {
  325. const textOp = TextOperation.fromJSON(operation)
  326. const textUpdateBuilder = new TextUpdateBuilder(
  327. initialContent,
  328. trackedChanges
  329. )
  330. for (const op of textOp.ops) {
  331. textUpdateBuilder.applyOp(op)
  332. }
  333. textUpdateBuilder.finish()
  334. return {
  335. content: textUpdateBuilder.result,
  336. ops: textUpdateBuilder.changes,
  337. }
  338. }
  339. _loadContentAndRanges(historyId, callback) {
  340. HistoryStoreManager.getProjectBlob(
  341. historyId,
  342. this.snapshot.hash,
  343. (err, content) => {
  344. if (err) {
  345. return callback(err)
  346. }
  347. if (this.snapshot.rangesHash) {
  348. HistoryStoreManager.getProjectBlob(
  349. historyId,
  350. this.snapshot.rangesHash,
  351. (err, ranges) => {
  352. if (err) {
  353. return callback(err)
  354. }
  355. return callback(null, content, JSON.parse(ranges))
  356. }
  357. )
  358. } else {
  359. return callback(null, content, undefined)
  360. }
  361. }
  362. )
  363. }
  364. }
  365. class TextUpdateBuilder {
  366. /**
  367. *
  368. * @param {string} source
  369. * @param {TrackedChangeList} ranges
  370. */
  371. constructor(source, ranges) {
  372. this.trackedChanges = ranges
  373. this.source = source
  374. this.sourceCursor = 0
  375. this.result = ''
  376. /** @type {({i: string, p: number} | {d: string, p: number})[]} */
  377. this.changes = []
  378. }
  379. applyOp(op) {
  380. if (op instanceof RetainOp) {
  381. const length = this.result.length
  382. this.applyRetain(op)
  383. this.trackedChanges.applyRetain(length, op.length, {
  384. tracking: op.tracking,
  385. })
  386. }
  387. if (op instanceof InsertOp) {
  388. const length = this.result.length
  389. this.applyInsert(op)
  390. this.trackedChanges.applyInsert(length, op.insertion, {
  391. tracking: op.tracking,
  392. })
  393. }
  394. if (op instanceof RemoveOp) {
  395. const length = this.result.length
  396. this.applyDelete(op)
  397. this.trackedChanges.applyDelete(length, op.length)
  398. }
  399. }
  400. /**
  401. *
  402. * @param {RetainOp} retain
  403. */
  404. applyRetain(retain) {
  405. const resultRetentionRange = new Range(this.result.length, retain.length)
  406. const sourceRetentionRange = new Range(this.sourceCursor, retain.length)
  407. let scanCursor = this.result.length
  408. if (retain.tracking) {
  409. // We are modifying existing tracked deletes. We need to treat removal
  410. // (type insert/none) of a tracked delete as an insertion. Similarly, any
  411. // range we introduce as a tracked deletion must be reported as a deletion.
  412. const trackedDeletes = this.trackedChanges
  413. .asSorted()
  414. .filter(
  415. tc =>
  416. tc.tracking.type === 'delete' &&
  417. tc.range.overlaps(resultRetentionRange)
  418. )
  419. const sourceOffset = this.sourceCursor - this.result.length
  420. for (const trackedDelete of trackedDeletes) {
  421. const resultTrackedDelete = trackedDelete.range
  422. const sourceTrackedDelete = trackedDelete.range.moveBy(sourceOffset)
  423. if (scanCursor < resultTrackedDelete.start) {
  424. if (retain.tracking.type === 'delete') {
  425. this.changes.push({
  426. d: this.source.slice(
  427. this.sourceCursor,
  428. sourceTrackedDelete.start
  429. ),
  430. p: this.result.length,
  431. })
  432. }
  433. this.result += this.source.slice(
  434. this.sourceCursor,
  435. sourceTrackedDelete.start
  436. )
  437. scanCursor = resultTrackedDelete.start
  438. this.sourceCursor = sourceTrackedDelete.start
  439. }
  440. const endOfInsertionResult = Math.min(
  441. resultTrackedDelete.end,
  442. resultRetentionRange.end
  443. )
  444. const endOfInsertionSource = Math.min(
  445. sourceTrackedDelete.end,
  446. sourceRetentionRange.end
  447. )
  448. const text = this.source.slice(this.sourceCursor, endOfInsertionSource)
  449. if (
  450. retain.tracking.type === 'none' ||
  451. retain.tracking.type === 'insert'
  452. ) {
  453. this.changes.push({
  454. i: text,
  455. p: this.result.length,
  456. })
  457. }
  458. this.result += text
  459. // skip the tracked delete itself
  460. scanCursor = endOfInsertionResult
  461. this.sourceCursor = endOfInsertionSource
  462. if (scanCursor >= resultRetentionRange.end) {
  463. break
  464. }
  465. }
  466. }
  467. if (scanCursor < resultRetentionRange.end) {
  468. // The last region is not a tracked delete. But we should still handle
  469. // a new tracked delete as a deletion.
  470. const text = this.source.slice(
  471. this.sourceCursor,
  472. sourceRetentionRange.end
  473. )
  474. if (retain.tracking?.type === 'delete') {
  475. this.changes.push({
  476. d: text,
  477. p: this.result.length,
  478. })
  479. }
  480. this.result += text
  481. }
  482. this.sourceCursor = sourceRetentionRange.end
  483. }
  484. /**
  485. *
  486. * @param {InsertOp} insert
  487. */
  488. applyInsert(insert) {
  489. if (insert.tracking?.type !== 'delete') {
  490. // Skip tracked deletions
  491. this.changes.push({
  492. i: insert.insertion,
  493. p: this.result.length,
  494. })
  495. }
  496. this.result += insert.insertion
  497. // The source cursor doesn't advance
  498. }
  499. /**
  500. *
  501. * @param {RemoveOp} deletion
  502. */
  503. applyDelete(deletion) {
  504. const sourceDeletionRange = new Range(this.sourceCursor, deletion.length)
  505. const resultDeletionRange = new Range(this.result.length, deletion.length)
  506. const trackedDeletes = this.trackedChanges
  507. .asSorted()
  508. .filter(
  509. tc =>
  510. tc.tracking.type === 'delete' &&
  511. tc.range.overlaps(resultDeletionRange)
  512. )
  513. .sort((a, b) => a.range.start - b.range.start)
  514. let scanCursor = this.result.length
  515. const sourceOffset = this.sourceCursor - this.result.length
  516. for (const trackedDelete of trackedDeletes) {
  517. const resultTrackDeleteRange = trackedDelete.range
  518. const sourceTrackDeleteRange = trackedDelete.range.moveBy(sourceOffset)
  519. if (scanCursor < resultTrackDeleteRange.start) {
  520. this.changes.push({
  521. d: this.source.slice(this.sourceCursor, sourceTrackDeleteRange.start),
  522. p: this.result.length,
  523. })
  524. }
  525. // skip the tracked delete itself
  526. scanCursor = Math.min(resultTrackDeleteRange.end, resultDeletionRange.end)
  527. this.sourceCursor = Math.min(
  528. sourceTrackDeleteRange.end,
  529. sourceDeletionRange.end
  530. )
  531. if (scanCursor >= resultDeletionRange.end) {
  532. break
  533. }
  534. }
  535. if (scanCursor < resultDeletionRange.end) {
  536. this.changes.push({
  537. d: this.source.slice(this.sourceCursor, sourceDeletionRange.end),
  538. p: this.result.length,
  539. })
  540. }
  541. this.sourceCursor = sourceDeletionRange.end
  542. }
  543. finish() {
  544. if (this.sourceCursor < this.source.length) {
  545. this.result += this.source.slice(this.sourceCursor)
  546. }
  547. for (const op of this.changes) {
  548. if ('p' in op && typeof op.p === 'number') {
  549. // Maybe we have to move the position of the deletion to account for
  550. // tracked changes that we're hiding in the UI.
  551. op.p -= this.trackedChanges
  552. .asSorted()
  553. .filter(tc => tc.tracking.type === 'delete' && tc.range.start < op.p)
  554. .map(tc => {
  555. if (tc.range.end < op.p) {
  556. return tc.range.length
  557. }
  558. return op.p - tc.range.start
  559. })
  560. .reduce((a, b) => a + b, 0)
  561. }
  562. }
  563. }
  564. }