UpdateTranslator.js 13 KB

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