UpdateTranslator.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. // @ts-check
  2. import _ from 'lodash'
  3. import Core from 'overleaf-editor-core'
  4. import * as Errors from './Errors.js'
  5. import * as OperationsCompressor from './OperationsCompressor.js'
  6. import { isInsert, isRetain, isDelete, isComment } from './Utils.js'
  7. /**
  8. * @typedef {import('./types').AddDocUpdate} AddDocUpdate
  9. * @typedef {import('./types').AddFileUpdate} AddFileUpdate
  10. * @typedef {import('./types').DeleteCommentUpdate} DeleteCommentUpdate
  11. * @typedef {import('./types').Op} Op
  12. * @typedef {import('./types').RawScanOp} RawScanOp
  13. * @typedef {import('./types').RenameUpdate} RenameUpdate
  14. * @typedef {import('./types').TextUpdate} TextUpdate
  15. * @typedef {import('./types').TrackingDirective} TrackingDirective
  16. * @typedef {import('./types').TrackingProps} TrackingProps
  17. * @typedef {import('./types').SetCommentStateUpdate} SetCommentStateUpdate
  18. * @typedef {import('./types').Update} Update
  19. * @typedef {import('./types').UpdateWithBlob} UpdateWithBlob
  20. */
  21. /**
  22. * Convert updates into history changes
  23. *
  24. * @param {string} projectId
  25. * @param {UpdateWithBlob[]} updatesWithBlobs
  26. * @returns {Array<Core.Change | null>}
  27. */
  28. export function convertToChanges(projectId, updatesWithBlobs) {
  29. return updatesWithBlobs.map(update => _convertToChange(projectId, update))
  30. }
  31. /**
  32. * Convert an update into a history change
  33. *
  34. * @param {string} projectId
  35. * @param {UpdateWithBlob} updateWithBlob
  36. * @returns {Core.Change | null}
  37. */
  38. function _convertToChange(projectId, updateWithBlob) {
  39. let operations
  40. const { update } = updateWithBlob
  41. let projectVersion = null
  42. const v2DocVersions = {}
  43. if (_isRenameUpdate(update)) {
  44. operations = [
  45. {
  46. pathname: _convertPathname(update.pathname),
  47. newPathname: _convertPathname(update.new_pathname),
  48. },
  49. ]
  50. projectVersion = update.version
  51. } else if (isAddUpdate(update)) {
  52. operations = [
  53. {
  54. pathname: _convertPathname(update.pathname),
  55. file: {
  56. hash: updateWithBlob.blobHash,
  57. },
  58. },
  59. ]
  60. projectVersion = update.version
  61. } else if (isTextUpdate(update)) {
  62. const docLength = update.meta.history_doc_length ?? update.meta.doc_length
  63. let pathname = update.meta.pathname
  64. pathname = _convertPathname(pathname)
  65. const builder = new OperationsBuilder(docLength, pathname)
  66. // convert ops
  67. for (const op of update.op) {
  68. builder.addOp(op, update)
  69. }
  70. operations = builder.finish()
  71. // add doc version information if present
  72. if (update.v != null) {
  73. v2DocVersions[update.doc] = { pathname, v: update.v }
  74. }
  75. } else if (isSetCommentStateUpdate(update)) {
  76. operations = [
  77. {
  78. pathname: _convertPathname(update.pathname),
  79. commentId: update.commentId,
  80. resolved: update.resolved,
  81. },
  82. ]
  83. } else if (isDeleteCommentUpdate(update)) {
  84. operations = [
  85. {
  86. pathname: _convertPathname(update.pathname),
  87. deleteComment: update.deleteComment,
  88. },
  89. ]
  90. } else {
  91. const error = new Errors.UpdateWithUnknownFormatError(
  92. 'update with unknown format',
  93. { projectId, update }
  94. )
  95. throw error
  96. }
  97. let v2Authors
  98. if (update.meta.user_id === 'anonymous-user') {
  99. // history-v1 uses null to represent an anonymous author
  100. v2Authors = [null]
  101. } else {
  102. // user_id is missing on resync operations that update the contents of a doc
  103. v2Authors = _.compact([update.meta.user_id])
  104. }
  105. const rawChange = {
  106. operations,
  107. v2Authors,
  108. timestamp: new Date(update.meta.ts).toISOString(),
  109. projectVersion,
  110. v2DocVersions: Object.keys(v2DocVersions).length ? v2DocVersions : null,
  111. }
  112. if (update.meta.origin) {
  113. rawChange.origin = update.meta.origin
  114. } else if (update.meta.type === 'external' && update.meta.source) {
  115. rawChange.origin = { kind: update.meta.source }
  116. }
  117. const change = Core.Change.fromRaw(rawChange)
  118. if (change != null) {
  119. change.operations = OperationsCompressor.compressOperations(
  120. change.operations
  121. )
  122. }
  123. return change
  124. }
  125. /**
  126. * @param {Update} update
  127. * @returns {update is RenameUpdate}
  128. */
  129. function _isRenameUpdate(update) {
  130. return 'new_pathname' in update && update.new_pathname != null
  131. }
  132. /**
  133. * @param {Update} update
  134. * @returns {update is AddDocUpdate}
  135. */
  136. function _isAddDocUpdate(update) {
  137. return (
  138. 'doc' in update &&
  139. update.doc != null &&
  140. 'docLines' in update &&
  141. update.docLines != null
  142. )
  143. }
  144. /**
  145. * @param {Update} update
  146. * @returns {update is AddFileUpdate}
  147. */
  148. function _isAddFileUpdate(update) {
  149. return (
  150. 'file' in update &&
  151. update.file != null &&
  152. 'url' in update &&
  153. update.url != null
  154. )
  155. }
  156. /**
  157. * @param {Update} update
  158. * @returns {update is TextUpdate}
  159. */
  160. export function isTextUpdate(update) {
  161. return (
  162. 'doc' in update &&
  163. update.doc != null &&
  164. 'op' in update &&
  165. update.op != null &&
  166. 'pathname' in update.meta &&
  167. update.meta.pathname != null &&
  168. 'doc_length' in update.meta &&
  169. update.meta.doc_length != null
  170. )
  171. }
  172. export function isProjectStructureUpdate(update) {
  173. return isAddUpdate(update) || _isRenameUpdate(update)
  174. }
  175. /**
  176. * @param {Update} update
  177. * @returns {update is AddDocUpdate | AddFileUpdate}
  178. */
  179. export function isAddUpdate(update) {
  180. return _isAddDocUpdate(update) || _isAddFileUpdate(update)
  181. }
  182. /**
  183. * @param {Update} update
  184. * @returns {update is SetCommentStateUpdate}
  185. */
  186. export function isSetCommentStateUpdate(update) {
  187. return 'commentId' in update && 'resolved' in update
  188. }
  189. /**
  190. * @param {Update} update
  191. * @returns {update is DeleteCommentUpdate}
  192. */
  193. export function isDeleteCommentUpdate(update) {
  194. return 'deleteComment' in update
  195. }
  196. export function _convertPathname(pathname) {
  197. // Strip leading /
  198. pathname = pathname.replace(/^\//, '')
  199. // Replace \\ with _. Backslashes are no longer allowed
  200. // in projects in web, but we have some which have gone through
  201. // into history before this restriction was added. This makes
  202. // them valid for the history store.
  203. // See https://github.com/overleaf/write_latex/issues/4471
  204. pathname = pathname.replace(/\\/g, '_')
  205. // workaround for filenames containing asterisks, this will
  206. // fail if a corresponding replacement file already exists but it
  207. // would fail anyway without this attempt to fix the pathname.
  208. // See https://github.com/overleaf/internal/issues/900
  209. pathname = pathname.replace(/\*/g, '__ASTERISK__')
  210. // workaround for filenames beginning with spaces
  211. // See https://github.com/overleaf/internal/issues/1404
  212. // note: we have already stripped any leading slash above
  213. pathname = pathname.replace(/^ /, '__SPACE__') // handle top-level
  214. pathname = pathname.replace(/\/ /g, '/__SPACE__') // handle folders
  215. return pathname
  216. }
  217. class OperationsBuilder {
  218. /**
  219. * @param {number} docLength
  220. * @param {string} pathname
  221. */
  222. constructor(docLength, pathname) {
  223. /**
  224. * List of operations being built
  225. */
  226. this.operations = []
  227. /**
  228. * Currently built text operation
  229. *
  230. * @type {RawScanOp[]}
  231. */
  232. this.textOperation = []
  233. /**
  234. * Cursor inside the current text operation
  235. */
  236. this.cursor = 0
  237. this.docLength = docLength
  238. this.pathname = pathname
  239. }
  240. /**
  241. * @param {Op} op
  242. * @param {TextUpdate} update
  243. * @returns {void}
  244. */
  245. addOp(op, update) {
  246. // We sometimes receive operations that operate at positions outside the
  247. // docLength. Document updater coerces the position to the end of the
  248. // document. We do the same here.
  249. const pos = Math.min(op.hpos ?? op.p, this.docLength)
  250. if (isComment(op)) {
  251. // Close the current text operation
  252. this.pushTextOperation()
  253. // Add a comment operation
  254. const commentOp = {
  255. pathname: this.pathname,
  256. commentId: op.t,
  257. ranges: [
  258. {
  259. pos,
  260. length: op.hlen ?? op.c.length,
  261. },
  262. ],
  263. }
  264. if ('resolved' in op) {
  265. commentOp.resolved = op.resolved
  266. }
  267. this.operations.push(commentOp)
  268. return
  269. }
  270. if (!isInsert(op) && !isDelete(op) && !isRetain(op)) {
  271. throw new Errors.UnexpectedOpTypeError('unexpected op type', { op })
  272. }
  273. if (pos < this.cursor) {
  274. this.pushTextOperation()
  275. // At this point, this.cursor === 0 and we can continue
  276. }
  277. if (pos > this.cursor) {
  278. this.retain(pos - this.cursor)
  279. }
  280. if (isInsert(op)) {
  281. if (op.trackedDeleteRejection) {
  282. this.retain(op.i.length, {
  283. tracking: { type: 'none' },
  284. })
  285. } else {
  286. const opts = {}
  287. if (update.meta.tc != null) {
  288. opts.tracking = {
  289. type: 'insert',
  290. userId: update.meta.user_id,
  291. ts: new Date(update.meta.ts).toISOString(),
  292. }
  293. }
  294. if (op.commentIds != null) {
  295. opts.commentIds = op.commentIds
  296. }
  297. this.insert(op.i, opts)
  298. }
  299. }
  300. if (isRetain(op)) {
  301. if (op.tracking) {
  302. this.retain(op.r.length, { tracking: op.tracking })
  303. } else {
  304. this.retain(op.r.length)
  305. }
  306. }
  307. if (isDelete(op)) {
  308. const changes = op.trackedChanges ?? []
  309. // Tracked changes should already be ordered by offset, but let's make
  310. // sure they are.
  311. changes.sort((a, b) => {
  312. const posOrder = a.offset - b.offset
  313. if (posOrder !== 0) {
  314. return posOrder
  315. } else if (a.type === 'insert' && b.type === 'delete') {
  316. return 1
  317. } else if (a.type === 'delete' && b.type === 'insert') {
  318. return -1
  319. } else {
  320. return 0
  321. }
  322. })
  323. let offset = 0
  324. for (const change of changes) {
  325. if (change.offset > offset) {
  326. // Handle the portion before the tracked change
  327. if (update.meta.tc != null && op.u == null) {
  328. // This is a tracked delete
  329. this.retain(change.offset - offset, {
  330. tracking: {
  331. type: 'delete',
  332. userId: update.meta.user_id,
  333. ts: new Date(update.meta.ts).toISOString(),
  334. },
  335. })
  336. } else {
  337. // This is a regular delete
  338. this.delete(change.offset - offset)
  339. }
  340. offset = change.offset
  341. }
  342. // Now, handle the portion inside the tracked change
  343. if (change.type === 'delete') {
  344. // Tracked deletes are skipped over when deleting
  345. this.retain(change.length)
  346. } else if (change.type === 'insert') {
  347. // Deletes inside tracked inserts are always regular deletes
  348. this.delete(change.length)
  349. offset += change.length
  350. }
  351. }
  352. if (offset < op.d.length) {
  353. // Handle the portion after the last tracked change
  354. if (update.meta.tc != null && op.u == null) {
  355. // This is a tracked delete
  356. this.retain(op.d.length - offset, {
  357. tracking: {
  358. type: 'delete',
  359. userId: update.meta.user_id,
  360. ts: new Date(update.meta.ts).toISOString(),
  361. },
  362. })
  363. } else {
  364. // This is a regular delete
  365. this.delete(op.d.length - offset)
  366. }
  367. }
  368. }
  369. }
  370. /**
  371. * @param {number} length
  372. * @param {object} opts
  373. * @param {TrackingDirective} [opts.tracking]
  374. */
  375. retain(length, opts = {}) {
  376. if (opts.tracking) {
  377. this.textOperation.push({ r: length, ...opts })
  378. } else {
  379. this.textOperation.push(length)
  380. }
  381. this.cursor += length
  382. }
  383. /**
  384. * @param {string} str
  385. * @param {object} opts
  386. * @param {TrackingProps} [opts.tracking]
  387. * @param {string[]} [opts.commentIds]
  388. */
  389. insert(str, opts = {}) {
  390. if (opts.tracking || opts.commentIds) {
  391. this.textOperation.push({ i: str, ...opts })
  392. } else {
  393. this.textOperation.push(str)
  394. }
  395. this.cursor += str.length
  396. this.docLength += str.length
  397. }
  398. /**
  399. * @param {number} length
  400. * @param {object} opts
  401. */
  402. delete(length, opts = {}) {
  403. this.textOperation.push(-length)
  404. this.docLength -= length
  405. }
  406. pushTextOperation() {
  407. if (this.textOperation.length > 0)
  408. if (this.cursor < this.docLength) {
  409. this.retain(this.docLength - this.cursor)
  410. }
  411. if (this.textOperation.length > 0) {
  412. this.operations.push({
  413. pathname: this.pathname,
  414. textOperation: this.textOperation,
  415. })
  416. this.textOperation = []
  417. }
  418. this.cursor = 0
  419. }
  420. finish() {
  421. this.pushTextOperation()
  422. return this.operations
  423. }
  424. }