ChunkTranslator.js 17 KB

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