UpdateTranslator.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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.ts').AddDocUpdate} AddDocUpdate
  8. * @typedef {import('./types.ts').AddFileUpdate} AddFileUpdate
  9. * @typedef {import('./types.ts').CommentOp} CommentOp
  10. * @typedef {import('./types.ts').DeleteOp} DeleteOp
  11. * @typedef {import('./types.ts').InsertOp} InsertOp
  12. * @typedef {import('./types.ts').Op} Op
  13. * @typedef {import('./types.ts').RenameUpdate} RenameUpdate
  14. * @typedef {import('./types.ts').TextUpdate} TextUpdate
  15. * @typedef {import('./types.ts').Update} Update
  16. * @typedef {import('./types.ts').UpdateWithBlob} UpdateWithBlob
  17. */
  18. /**
  19. * Convert updates into history changes
  20. *
  21. * @param {string} projectId
  22. * @param {UpdateWithBlob[]} updatesWithBlobs
  23. * @returns {Array<Core.Change | null>}
  24. */
  25. export function convertToChanges(projectId, updatesWithBlobs) {
  26. return updatesWithBlobs.map(update => _convertToChange(projectId, update))
  27. }
  28. /**
  29. * Convert an update into a history change
  30. *
  31. * @param {string} projectId
  32. * @param {UpdateWithBlob} updateWithBlob
  33. * @returns {Core.Change | null}
  34. */
  35. function _convertToChange(projectId, updateWithBlob) {
  36. let operations
  37. const { update } = updateWithBlob
  38. let projectVersion = null
  39. const v2DocVersions = {}
  40. if (_isRenameUpdate(update)) {
  41. operations = [
  42. {
  43. pathname: _convertPathname(update.pathname),
  44. newPathname: _convertPathname(update.new_pathname),
  45. },
  46. ]
  47. projectVersion = update.version
  48. } else if (isAddUpdate(update)) {
  49. operations = [
  50. {
  51. pathname: _convertPathname(update.pathname),
  52. file: {
  53. hash: updateWithBlob.blobHash,
  54. },
  55. },
  56. ]
  57. projectVersion = update.version
  58. } else if (isTextUpdate(update)) {
  59. const docLength = update.meta.doc_length
  60. let pathname = update.meta.pathname
  61. pathname = _convertPathname(pathname)
  62. const builder = new OperationsBuilder(docLength, pathname)
  63. // convert ops
  64. for (const op of update.op) {
  65. // if this throws an exception it will be caught in convertToChanges
  66. builder.addOp(op)
  67. }
  68. operations = builder.finish()
  69. // add doc version information if present
  70. if (update.v != null) {
  71. v2DocVersions[update.doc] = { pathname, v: update.v }
  72. }
  73. } else {
  74. const error = new Errors.UpdateWithUnknownFormatError(
  75. 'update with unknown format',
  76. { projectId, update }
  77. )
  78. throw error
  79. }
  80. let v2Authors
  81. if (update.meta.user_id === 'anonymous-user') {
  82. // history-v1 uses null to represent an anonymous author
  83. v2Authors = [null]
  84. } else {
  85. // user_id is missing on resync operations that update the contents of a doc
  86. v2Authors = _.compact([update.meta.user_id])
  87. }
  88. const rawChange = {
  89. operations,
  90. v2Authors,
  91. timestamp: new Date(update.meta.ts).toISOString(),
  92. projectVersion,
  93. v2DocVersions: Object.keys(v2DocVersions).length ? v2DocVersions : null,
  94. }
  95. if (update.meta.origin) {
  96. rawChange.origin = update.meta.origin
  97. } else if (update.meta.type === 'external' && update.meta.source) {
  98. rawChange.origin = { kind: update.meta.source }
  99. }
  100. const change = Core.Change.fromRaw(rawChange)
  101. if (change != null) {
  102. change.operations = OperationsCompressor.compressOperations(
  103. change.operations
  104. )
  105. }
  106. return change
  107. }
  108. /**
  109. * @param {Update} update
  110. * @returns {update is RenameUpdate}
  111. */
  112. function _isRenameUpdate(update) {
  113. return 'new_pathname' in update && update.new_pathname != null
  114. }
  115. /**
  116. * @param {Update} update
  117. * @returns {update is AddDocUpdate}
  118. */
  119. function _isAddDocUpdate(update) {
  120. return (
  121. 'doc' in update &&
  122. update.doc != null &&
  123. 'docLines' in update &&
  124. update.docLines != null
  125. )
  126. }
  127. /**
  128. * @param {Update} update
  129. * @returns {update is AddFileUpdate}
  130. */
  131. function _isAddFileUpdate(update) {
  132. return (
  133. 'file' in update &&
  134. update.file != null &&
  135. 'url' in update &&
  136. update.url != null
  137. )
  138. }
  139. /**
  140. * @param {Update} update
  141. * @returns {update is TextUpdate}
  142. */
  143. export function isTextUpdate(update) {
  144. return (
  145. 'doc' in update &&
  146. update.doc != null &&
  147. 'op' in update &&
  148. update.op != null &&
  149. 'pathname' in update.meta &&
  150. update.meta.pathname != null &&
  151. 'doc_length' in update.meta &&
  152. update.meta.doc_length != null
  153. )
  154. }
  155. export function isProjectStructureUpdate(update) {
  156. return isAddUpdate(update) || _isRenameUpdate(update)
  157. }
  158. /**
  159. * @param {Update} update
  160. * @returns {update is AddDocUpdate | AddFileUpdate}
  161. */
  162. export function isAddUpdate(update) {
  163. return _isAddDocUpdate(update) || _isAddFileUpdate(update)
  164. }
  165. export function _convertPathname(pathname) {
  166. // Strip leading /
  167. pathname = pathname.replace(/^\//, '')
  168. // Replace \\ with _. Backslashes are no longer allowed
  169. // in projects in web, but we have some which have gone through
  170. // into history before this restriction was added. This makes
  171. // them valid for the history store.
  172. // See https://github.com/overleaf/write_latex/issues/4471
  173. pathname = pathname.replace(/\\/g, '_')
  174. // workaround for filenames containing asterisks, this will
  175. // fail if a corresponding replacement file already exists but it
  176. // would fail anyway without this attempt to fix the pathname.
  177. // See https://github.com/overleaf/internal/issues/900
  178. pathname = pathname.replace(/\*/g, '__ASTERISK__')
  179. // workaround for filenames beginning with spaces
  180. // See https://github.com/overleaf/internal/issues/1404
  181. // note: we have already stripped any leading slash above
  182. pathname = pathname.replace(/^ /, '__SPACE__') // handle top-level
  183. pathname = pathname.replace(/\/ /g, '/__SPACE__') // handle folders
  184. return pathname
  185. }
  186. class OperationsBuilder {
  187. /**
  188. * @param {number} docLength
  189. * @param {string} pathname
  190. */
  191. constructor(docLength, pathname) {
  192. /**
  193. * List of operations being built
  194. */
  195. this.operations = []
  196. /**
  197. * Currently built text operation
  198. *
  199. * @type {(number | string)[]}
  200. */
  201. this.textOperation = []
  202. /**
  203. * Cursor inside the current text operation
  204. */
  205. this.cursor = 0
  206. this.docLength = docLength
  207. this.pathname = pathname
  208. }
  209. /**
  210. * @param {Op} op
  211. * @returns {void}
  212. */
  213. addOp(op) {
  214. if (isComment(op)) {
  215. // Close the current text operation
  216. this.pushTextOperation()
  217. // Add a comment operation
  218. this.operations.push({
  219. pathname: this.pathname,
  220. commentId: op.t,
  221. ranges: [
  222. {
  223. pos: op.p,
  224. length: op.c.length,
  225. },
  226. ],
  227. })
  228. return
  229. }
  230. if (!isInsert(op) && !isDelete(op)) {
  231. throw new Errors.UnexpectedOpTypeError('unexpected op type', { op })
  232. }
  233. // We sometimes receive operations that operate at positions outside the
  234. // docLength. Document updater coerces the position to the end of the
  235. // document. We do the same here.
  236. const pos = Math.min(op.p, this.docLength)
  237. if (pos < this.cursor) {
  238. this.pushTextOperation()
  239. // At this point, this.cursor === 0 and we can continue
  240. }
  241. if (pos > this.cursor) {
  242. this.retain(pos - this.cursor)
  243. }
  244. if (isInsert(op)) {
  245. this.insert(op.i)
  246. }
  247. if (isDelete(op)) {
  248. this.delete(op.d.length)
  249. }
  250. }
  251. retain(length) {
  252. this.textOperation.push(length)
  253. this.cursor += length
  254. }
  255. insert(str) {
  256. this.textOperation.push(str)
  257. this.cursor += str.length
  258. this.docLength += str.length
  259. }
  260. delete(length) {
  261. this.textOperation.push(-length)
  262. this.docLength -= length
  263. }
  264. pushTextOperation() {
  265. if (this.textOperation.length > 0)
  266. if (this.cursor < this.docLength) {
  267. this.retain(this.docLength - this.cursor)
  268. }
  269. if (this.textOperation.length > 0) {
  270. this.operations.push({
  271. pathname: this.pathname,
  272. textOperation: this.textOperation,
  273. })
  274. this.textOperation = []
  275. }
  276. this.cursor = 0
  277. }
  278. finish() {
  279. this.pushTextOperation()
  280. return this.operations
  281. }
  282. }
  283. /**
  284. * @param {Op} op
  285. * @returns {op is InsertOp}
  286. */
  287. function isInsert(op) {
  288. return 'i' in op && op.i != null
  289. }
  290. /**
  291. * @param {Op} op
  292. * @returns {op is DeleteOp}
  293. */
  294. function isDelete(op) {
  295. return 'd' in op && op.d != null
  296. }
  297. /**
  298. * @param {Op} op
  299. * @returns {op is CommentOp}
  300. */
  301. function isComment(op) {
  302. return 'c' in op && op.c != null && 't' in op && op.t != null
  303. }