sharejs.js 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456
  1. import { generateSHA1Hash } from '../../shared/utils/sha1'
  2. import { debugging, debugConsole } from '@/utils/debugging'
  3. import getMeta from '@/utils/meta'
  4. import { postJSON } from '@/infrastructure/fetch-json'
  5. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  6. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  7. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
  8. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9. /* eslint-disable
  10. camelcase,
  11. max-len,
  12. no-class-assign,
  13. no-return-assign,
  14. no-undef,
  15. no-unused-vars,
  16. no-use-before-define,
  17. standard/object-curly-even-spacing,
  18. */
  19. // TODO: This file was created by bulk-decaffeinate.
  20. // Fix any style issues and re-enable lint.
  21. /*
  22. * decaffeinate suggestions:
  23. * DS101: Remove unnecessary use of Array.from
  24. * DS102: Remove unnecessary code created because of implicit returns
  25. * DS205: Consider reworking code to avoid use of IIFEs
  26. * DS207: Consider shorter variations of null checks
  27. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  28. */
  29. export const { Doc } = (() => {
  30. var append = void 0,
  31. bootstrapTransform = void 0,
  32. exports = void 0,
  33. transformComponent = void 0;
  34. var WEB = true;
  35. window.sharejs = exports = {};
  36. var types = exports.types = {};
  37. // These methods let you build a transform function from a transformComponent function
  38. // for OT types like text and JSON in which operations are lists of components
  39. // and transforming them requires N^2 work.
  40. // Add transform and transformX functions for an OT type which has transformComponent defined.
  41. // transformComponent(destination array, component, other component, side)
  42. exports['_bt'] = bootstrapTransform = function bootstrapTransform(type, transformComponent, checkValidOp, append) {
  43. var _transformX = void 0;
  44. var transformComponentX = function transformComponentX(left, right, destLeft, destRight) {
  45. transformComponent(destLeft, left, right, 'left');
  46. return transformComponent(destRight, right, left, 'right');
  47. };
  48. // Transforms rightOp by leftOp. Returns ['rightOp', clientOp']
  49. type.transformX = type['transformX'] = _transformX = function transformX(leftOp, rightOp) {
  50. checkValidOp(leftOp);
  51. checkValidOp(rightOp);
  52. var newRightOp = [];
  53. var _iteratorNormalCompletion = true;
  54. var _didIteratorError = false;
  55. var _iteratorError = undefined;
  56. try {
  57. for (var _iterator = Array.from(rightOp)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  58. var rightComponent = _step.value;
  59. // Generate newLeftOp by composing leftOp by rightComponent
  60. var newLeftOp = [];
  61. var k = 0;
  62. while (k < leftOp.length) {
  63. var l;
  64. var nextC = [];
  65. transformComponentX(leftOp[k], rightComponent, newLeftOp, nextC);
  66. k++;
  67. if (nextC.length === 1) {
  68. rightComponent = nextC[0];
  69. } else if (nextC.length === 0) {
  70. var _iteratorNormalCompletion2 = true;
  71. var _didIteratorError2 = false;
  72. var _iteratorError2 = undefined;
  73. try {
  74. for (var _iterator2 = Array.from(leftOp.slice(k))[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
  75. l = _step2.value;
  76. append(newLeftOp, l);
  77. }
  78. } catch (err) {
  79. _didIteratorError2 = true;
  80. _iteratorError2 = err;
  81. } finally {
  82. try {
  83. if (!_iteratorNormalCompletion2 && _iterator2.return) {
  84. _iterator2.return();
  85. }
  86. } finally {
  87. if (_didIteratorError2) {
  88. throw _iteratorError2;
  89. }
  90. }
  91. }
  92. rightComponent = null;
  93. break;
  94. } else {
  95. // Recurse.
  96. var _Array$from = Array.from(_transformX(leftOp.slice(k), nextC)),
  97. _Array$from2 = _slicedToArray(_Array$from, 2),
  98. l_ = _Array$from2[0],
  99. r_ = _Array$from2[1];
  100. var _iteratorNormalCompletion3 = true;
  101. var _didIteratorError3 = false;
  102. var _iteratorError3 = undefined;
  103. try {
  104. for (var _iterator3 = Array.from(l_)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
  105. l = _step3.value;
  106. append(newLeftOp, l);
  107. }
  108. } catch (err) {
  109. _didIteratorError3 = true;
  110. _iteratorError3 = err;
  111. } finally {
  112. try {
  113. if (!_iteratorNormalCompletion3 && _iterator3.return) {
  114. _iterator3.return();
  115. }
  116. } finally {
  117. if (_didIteratorError3) {
  118. throw _iteratorError3;
  119. }
  120. }
  121. }
  122. var _iteratorNormalCompletion4 = true;
  123. var _didIteratorError4 = false;
  124. var _iteratorError4 = undefined;
  125. try {
  126. for (var _iterator4 = Array.from(r_)[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
  127. var r = _step4.value;
  128. append(newRightOp, r);
  129. }
  130. } catch (err) {
  131. _didIteratorError4 = true;
  132. _iteratorError4 = err;
  133. } finally {
  134. try {
  135. if (!_iteratorNormalCompletion4 && _iterator4.return) {
  136. _iterator4.return();
  137. }
  138. } finally {
  139. if (_didIteratorError4) {
  140. throw _iteratorError4;
  141. }
  142. }
  143. }
  144. rightComponent = null;
  145. break;
  146. }
  147. }
  148. if (rightComponent != null) {
  149. append(newRightOp, rightComponent);
  150. }
  151. leftOp = newLeftOp;
  152. }
  153. } catch (err) {
  154. _didIteratorError = true;
  155. _iteratorError = err;
  156. } finally {
  157. try {
  158. if (!_iteratorNormalCompletion && _iterator.return) {
  159. _iterator.return();
  160. }
  161. } finally {
  162. if (_didIteratorError) {
  163. throw _iteratorError;
  164. }
  165. }
  166. }
  167. return [leftOp, newRightOp];
  168. };
  169. // Transforms op with specified type ('left' or 'right') by otherOp.
  170. return type.transform = type['transform'] = function (op, otherOp, type) {
  171. var _ = void 0;
  172. if (type !== 'left' && type !== 'right') {
  173. throw new Error("type must be 'left' or 'right'");
  174. }
  175. if (otherOp.length === 0) {
  176. return op;
  177. }
  178. // TODO: Benchmark with and without this line. I _think_ it'll make a big difference...?
  179. if (op.length === 1 && otherOp.length === 1) {
  180. return transformComponent([], op[0], otherOp[0], type);
  181. }
  182. if (type === 'left') {
  183. var left = void 0;
  184. var _Array$from3 = Array.from(_transformX(op, otherOp));
  185. var _Array$from4 = _slicedToArray(_Array$from3, 2);
  186. left = _Array$from4[0];
  187. _ = _Array$from4[1];
  188. return left;
  189. } else {
  190. var right = void 0;
  191. var _Array$from5 = Array.from(_transformX(otherOp, op));
  192. var _Array$from6 = _slicedToArray(_Array$from5, 2);
  193. _ = _Array$from6[0];
  194. right = _Array$from6[1];
  195. return right;
  196. }
  197. };
  198. };
  199. // A simple text implementation
  200. //
  201. // Operations are lists of components.
  202. // Each component either inserts or deletes at a specified position in the document.
  203. //
  204. // Components are either:
  205. // {i:'str', p:100}: Insert 'str' at position 100 in the document
  206. // {d:'str', p:100}: Delete 'str' at position 100 in the document
  207. //
  208. // Components in an operation are executed sequentially, so the position of components
  209. // assumes previous components have already executed.
  210. //
  211. // Eg: This op:
  212. // [{i:'abc', p:0}]
  213. // is equivalent to this op:
  214. // [{i:'a', p:0}, {i:'b', p:1}, {i:'c', p:2}]
  215. // NOTE: The global scope here is shared with other sharejs files when built with closure.
  216. // Be careful what ends up in your namespace.
  217. var text = {};
  218. text.name = 'text';
  219. text.create = function () {
  220. return '';
  221. };
  222. var strInject = function strInject(s1, pos, s2) {
  223. return s1.slice(0, pos) + s2 + s1.slice(pos);
  224. };
  225. var checkValidComponent = function checkValidComponent(c) {
  226. if (typeof c.p !== 'number') {
  227. throw new Error('component missing position field');
  228. }
  229. var i_type = _typeof(c.i);
  230. var d_type = _typeof(c.d);
  231. var c_type = _typeof(c.c);
  232. if (!(i_type === 'string' ^ d_type === 'string' ^ c_type === 'string')) {
  233. throw new Error('component needs an i, d or c field');
  234. }
  235. if (!(c.p >= 0)) {
  236. throw new Error('position cannot be negative');
  237. }
  238. };
  239. var checkValidOp = function checkValidOp(op) {
  240. var _iteratorNormalCompletion5 = true;
  241. var _didIteratorError5 = false;
  242. var _iteratorError5 = undefined;
  243. try {
  244. for (var _iterator5 = Array.from(op)[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
  245. var c = _step5.value;
  246. checkValidComponent(c);
  247. }
  248. } catch (err) {
  249. _didIteratorError5 = true;
  250. _iteratorError5 = err;
  251. } finally {
  252. try {
  253. if (!_iteratorNormalCompletion5 && _iterator5.return) {
  254. _iterator5.return();
  255. }
  256. } finally {
  257. if (_didIteratorError5) {
  258. throw _iteratorError5;
  259. }
  260. }
  261. }
  262. return true;
  263. };
  264. text.apply = function (snapshot, op) {
  265. checkValidOp(op);
  266. var _iteratorNormalCompletion6 = true;
  267. var _didIteratorError6 = false;
  268. var _iteratorError6 = undefined;
  269. try {
  270. for (var _iterator6 = Array.from(op)[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
  271. var component = _step6.value;
  272. if (component.i != null) {
  273. snapshot = strInject(snapshot, component.p, component.i);
  274. } else if (component.d != null) {
  275. var deleted = snapshot.slice(component.p, component.p + component.d.length);
  276. if (component.d !== deleted) {
  277. throw new Error('Delete component \'' + component.d + '\' does not match deleted text \'' + deleted + '\'');
  278. }
  279. snapshot = snapshot.slice(0, component.p) + snapshot.slice(component.p + component.d.length);
  280. } else if (component.c != null) {
  281. var comment = snapshot.slice(component.p, component.p + component.c.length);
  282. if (component.c !== comment) {
  283. throw new Error('Comment component \'' + component.c + '\' does not match commented text \'' + comment + '\'');
  284. }
  285. } else {
  286. throw new Error('Unknown op type');
  287. }
  288. }
  289. } catch (err) {
  290. _didIteratorError6 = true;
  291. _iteratorError6 = err;
  292. } finally {
  293. try {
  294. if (!_iteratorNormalCompletion6 && _iterator6.return) {
  295. _iterator6.return();
  296. }
  297. } finally {
  298. if (_didIteratorError6) {
  299. throw _iteratorError6;
  300. }
  301. }
  302. }
  303. return snapshot;
  304. };
  305. var cloneAndModify = function cloneAndModify(op, modifications) {
  306. var v = void 0;
  307. var newOp = {};
  308. for (var k in op) {
  309. v = op[k];
  310. newOp[k] = v;
  311. }
  312. for (k in modifications) {
  313. v = modifications[k];
  314. newOp[k] = v;
  315. }
  316. return newOp;
  317. };
  318. // Exported for use by the random op generator.
  319. //
  320. // For simplicity, this version of append does not compress adjacent inserts and deletes of
  321. // the same text. It would be nice to change that at some stage.
  322. text._append = append = function append(newOp, c) {
  323. if (c.i === '' || c.d === '') {
  324. return;
  325. }
  326. if (newOp.length === 0) {
  327. return newOp.push(c);
  328. } else {
  329. var last = newOp[newOp.length - 1];
  330. // Compose the insert into the previous insert if possible
  331. if (last.i != null && c.i != null && last.p <= c.p && c.p <= last.p + last.i.length && last.u === c.u) {
  332. return newOp[newOp.length - 1] = cloneAndModify(last, { i: strInject(last.i, c.p - last.p, c.i) });
  333. } else if (last.d != null && c.d != null && c.p <= last.p && last.p <= c.p + c.d.length && last.u === c.u) {
  334. return newOp[newOp.length - 1] = cloneAndModify(last, { d: strInject(c.d, last.p - c.p, last.d), p: c.p });
  335. } else {
  336. return newOp.push(c);
  337. }
  338. }
  339. };
  340. text.compose = function (op1, op2) {
  341. checkValidOp(op1);
  342. checkValidOp(op2);
  343. var newOp = op1.slice();
  344. var _iteratorNormalCompletion7 = true;
  345. var _didIteratorError7 = false;
  346. var _iteratorError7 = undefined;
  347. try {
  348. for (var _iterator7 = Array.from(op2)[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
  349. var c = _step7.value;
  350. append(newOp, c);
  351. }
  352. } catch (err) {
  353. _didIteratorError7 = true;
  354. _iteratorError7 = err;
  355. } finally {
  356. try {
  357. if (!_iteratorNormalCompletion7 && _iterator7.return) {
  358. _iterator7.return();
  359. }
  360. } finally {
  361. if (_didIteratorError7) {
  362. throw _iteratorError7;
  363. }
  364. }
  365. }
  366. return newOp;
  367. };
  368. // Attempt to compress the op components together 'as much as possible'.
  369. // This implementation preserves order and preserves create/delete pairs.
  370. text.compress = function (op) {
  371. return text.compose([], op);
  372. };
  373. text.normalize = function (op) {
  374. var newOp = [];
  375. // Normalize should allow ops which are a single (unwrapped) component:
  376. // {i:'asdf', p:23}.
  377. // There's no good way to test if something is an array:
  378. // http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
  379. // so this is probably the least bad solution.
  380. if (op.i != null || op.p != null) {
  381. op = [op];
  382. }
  383. var _iteratorNormalCompletion8 = true;
  384. var _didIteratorError8 = false;
  385. var _iteratorError8 = undefined;
  386. try {
  387. for (var _iterator8 = Array.from(op)[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
  388. var c = _step8.value;
  389. if (c.p == null) {
  390. c.p = 0;
  391. }
  392. append(newOp, c);
  393. }
  394. } catch (err) {
  395. _didIteratorError8 = true;
  396. _iteratorError8 = err;
  397. } finally {
  398. try {
  399. if (!_iteratorNormalCompletion8 && _iterator8.return) {
  400. _iterator8.return();
  401. }
  402. } finally {
  403. if (_didIteratorError8) {
  404. throw _iteratorError8;
  405. }
  406. }
  407. }
  408. return newOp;
  409. };
  410. // This helper method transforms a position by an op component.
  411. //
  412. // If c is an insert, insertAfter specifies whether the transform
  413. // is pushed after the insert (true) or before it (false).
  414. //
  415. // insertAfter is optional for deletes.
  416. var transformPosition = function transformPosition(pos, c, insertAfter) {
  417. if (c.i != null) {
  418. if (c.p < pos || c.p === pos && insertAfter) {
  419. return pos + c.i.length;
  420. } else {
  421. return pos;
  422. }
  423. } else if (c.d != null) {
  424. // I think this could also be written as: Math.min(c.p, Math.min(c.p - otherC.p, otherC.d.length))
  425. // but I think its harder to read that way, and it compiles using ternary operators anyway
  426. // so its no slower written like this.
  427. if (pos <= c.p) {
  428. return pos;
  429. } else if (pos <= c.p + c.d.length) {
  430. return c.p;
  431. } else {
  432. return pos - c.d.length;
  433. }
  434. } else if (c.c != null) {
  435. return pos;
  436. } else {
  437. throw new Error('unknown op type');
  438. }
  439. };
  440. // Helper method to transform a cursor position as a result of an op.
  441. //
  442. // Like transformPosition above, if c is an insert, insertAfter specifies whether the cursor position
  443. // is pushed after an insert (true) or before it (false).
  444. text.transformCursor = function (position, op, side) {
  445. var insertAfter = side === 'right';
  446. var _iteratorNormalCompletion9 = true;
  447. var _didIteratorError9 = false;
  448. var _iteratorError9 = undefined;
  449. try {
  450. for (var _iterator9 = Array.from(op)[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
  451. var c = _step9.value;
  452. position = transformPosition(position, c, insertAfter);
  453. }
  454. } catch (err) {
  455. _didIteratorError9 = true;
  456. _iteratorError9 = err;
  457. } finally {
  458. try {
  459. if (!_iteratorNormalCompletion9 && _iterator9.return) {
  460. _iterator9.return();
  461. }
  462. } finally {
  463. if (_didIteratorError9) {
  464. throw _iteratorError9;
  465. }
  466. }
  467. }
  468. return position;
  469. };
  470. // Transform an op component by another op component. Asymmetric.
  471. // The result will be appended to destination.
  472. //
  473. // exported for use in JSON type
  474. text._tc = transformComponent = function transformComponent(dest, c, otherC, side) {
  475. var cIntersect = void 0,
  476. intersectEnd = void 0,
  477. intersectStart = void 0,
  478. newC = void 0,
  479. otherIntersect = void 0;
  480. checkValidOp([c]);
  481. checkValidOp([otherC]);
  482. if (c.i != null) {
  483. append(dest, cloneAndModify(c, { p: transformPosition(c.p, otherC, side === 'right') }));
  484. } else if (c.d != null) {
  485. // Delete
  486. if (otherC.i != null) {
  487. // delete vs insert
  488. var s = c.d;
  489. if (c.p < otherC.p) {
  490. append(dest, cloneAndModify(c, { d: s.slice(0, otherC.p - c.p) }));
  491. s = s.slice(otherC.p - c.p);
  492. }
  493. if (s !== '') {
  494. append(dest, cloneAndModify(c, { d: s, p: c.p + otherC.i.length }));
  495. }
  496. } else if (otherC.d != null) {
  497. // Delete vs delete
  498. if (c.p >= otherC.p + otherC.d.length) {
  499. append(dest, cloneAndModify(c, { p: c.p - otherC.d.length }));
  500. } else if (c.p + c.d.length <= otherC.p) {
  501. append(dest, c);
  502. } else {
  503. // They overlap somewhere.
  504. newC = cloneAndModify(c, { d: '' });
  505. if (c.p < otherC.p) {
  506. newC.d = c.d.slice(0, otherC.p - c.p);
  507. }
  508. if (c.p + c.d.length > otherC.p + otherC.d.length) {
  509. newC.d += c.d.slice(otherC.p + otherC.d.length - c.p);
  510. }
  511. // This is entirely optional - just for a check that the deleted
  512. // text in the two ops matches
  513. intersectStart = Math.max(c.p, otherC.p);
  514. intersectEnd = Math.min(c.p + c.d.length, otherC.p + otherC.d.length);
  515. cIntersect = c.d.slice(intersectStart - c.p, intersectEnd - c.p);
  516. otherIntersect = otherC.d.slice(intersectStart - otherC.p, intersectEnd - otherC.p);
  517. if (cIntersect !== otherIntersect) {
  518. throw new Error('Delete ops delete different text in the same region of the document');
  519. }
  520. if (newC.d !== '') {
  521. // This could be rewritten similarly to insert v delete, above.
  522. newC.p = transformPosition(newC.p, otherC);
  523. append(dest, newC);
  524. }
  525. }
  526. } else if (otherC.c != null) {
  527. append(dest, c);
  528. } else {
  529. throw new Error('unknown op type');
  530. }
  531. } else if (c.c != null) {
  532. // Comment
  533. if (otherC.i != null) {
  534. if (c.p < otherC.p && otherC.p < c.p + c.c.length) {
  535. var offset = otherC.p - c.p;
  536. var new_c = c.c.slice(0, +(offset - 1) + 1 || undefined) + otherC.i + c.c.slice(offset);
  537. append(dest, cloneAndModify(c, { c: new_c }));
  538. } else {
  539. append(dest, cloneAndModify(c, { p: transformPosition(c.p, otherC, true) }));
  540. }
  541. } else if (otherC.d != null) {
  542. if (c.p >= otherC.p + otherC.d.length) {
  543. append(dest, cloneAndModify(c, { p: c.p - otherC.d.length }));
  544. } else if (c.p + c.c.length <= otherC.p) {
  545. append(dest, c);
  546. } else {
  547. // Delete overlaps comment
  548. // They overlap somewhere.
  549. newC = cloneAndModify(c, { c: '' });
  550. if (c.p < otherC.p) {
  551. newC.c = c.c.slice(0, otherC.p - c.p);
  552. }
  553. if (c.p + c.c.length > otherC.p + otherC.d.length) {
  554. newC.c += c.c.slice(otherC.p + otherC.d.length - c.p);
  555. }
  556. // This is entirely optional - just for a check that the deleted
  557. // text in the two ops matches
  558. intersectStart = Math.max(c.p, otherC.p);
  559. intersectEnd = Math.min(c.p + c.c.length, otherC.p + otherC.d.length);
  560. cIntersect = c.c.slice(intersectStart - c.p, intersectEnd - c.p);
  561. otherIntersect = otherC.d.slice(intersectStart - otherC.p, intersectEnd - otherC.p);
  562. if (cIntersect !== otherIntersect) {
  563. throw new Error('Delete ops delete different text in the same region of the document');
  564. }
  565. newC.p = transformPosition(newC.p, otherC);
  566. append(dest, newC);
  567. }
  568. } else if (otherC.c != null) {
  569. append(dest, c);
  570. } else {
  571. throw new Error('unknown op type');
  572. }
  573. }
  574. return dest;
  575. };
  576. var invertComponent = function invertComponent(c) {
  577. if (c.i != null) {
  578. return { d: c.i, p: c.p };
  579. } else {
  580. return { i: c.d, p: c.p };
  581. }
  582. };
  583. // No need to use append for invert, because the components won't be able to
  584. // cancel with one another.
  585. text.invert = function (op) {
  586. return Array.from(op.slice().reverse()).map(function (c) {
  587. return invertComponent(c);
  588. });
  589. };
  590. if (WEB != null) {
  591. if (!exports.types) {
  592. exports.types = {};
  593. }
  594. // This is kind of awful - come up with a better way to hook this helper code up.
  595. bootstrapTransform(text, transformComponent, checkValidOp, append);
  596. // [] is used to prevent closure from renaming types.text
  597. exports.types.text = text;
  598. }
  599. // Text document API for text
  600. text.api = {
  601. provides: { text: true },
  602. // The number of characters in the string
  603. getLength: function getLength() {
  604. return this.snapshot.length;
  605. },
  606. // Get the text contents of a document
  607. getText: function getText() {
  608. return this.snapshot;
  609. },
  610. insert: function insert(pos, text, fromUndo, callback) {
  611. var op = { p: pos, i: text };
  612. if (fromUndo) {
  613. op.u = true;
  614. }
  615. op = [op];
  616. this.submitOp(op, callback);
  617. return op;
  618. },
  619. del: function del(pos, length, fromUndo, callback) {
  620. var op = { p: pos, d: this.snapshot.slice(pos, pos + length) };
  621. if (fromUndo) {
  622. op.u = true;
  623. }
  624. op = [op];
  625. this.submitOp(op, callback);
  626. return op;
  627. },
  628. _register: function _register() {
  629. return this.on('remoteop', function (op) {
  630. var _this = this;
  631. return function () {
  632. var result = [];
  633. var _iteratorNormalCompletion10 = true;
  634. var _didIteratorError10 = false;
  635. var _iteratorError10 = undefined;
  636. try {
  637. for (var _iterator10 = Array.from(op)[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
  638. var component = _step10.value;
  639. if (component.i !== undefined) {
  640. result.push(_this.emit('insert', component.p, component.i));
  641. } else if (component.d !== undefined) {
  642. result.push(_this.emit('delete', component.p, component.d));
  643. } else {
  644. result.push(undefined);
  645. }
  646. }
  647. } catch (err) {
  648. _didIteratorError10 = true;
  649. _iteratorError10 = err;
  650. } finally {
  651. try {
  652. if (!_iteratorNormalCompletion10 && _iterator10.return) {
  653. _iterator10.return();
  654. }
  655. } finally {
  656. if (_didIteratorError10) {
  657. throw _iteratorError10;
  658. }
  659. }
  660. }
  661. return result;
  662. }();
  663. });
  664. }
  665. };
  666. // This is a simple port of microevent.js to Coffeescript. I've changed the
  667. // function names to be consistent with node.js EventEmitter.
  668. //
  669. // microevent.js is copyright Jerome Etienne, and licensed under the MIT license:
  670. // https://github.com/jeromeetienne/microevent.js
  671. var nextTick = WEB != null ? function (fn) {
  672. return setTimeout(fn, 0);
  673. } : process['nextTick'];
  674. var MicroEvent = function () {
  675. function MicroEvent() {
  676. _classCallCheck(this, MicroEvent);
  677. }
  678. _createClass(MicroEvent, [{
  679. key: 'on',
  680. value: function on(event, fct) {
  681. if (!this._events) {
  682. this._events = {};
  683. }
  684. if (!this._events[event]) {
  685. this._events[event] = [];
  686. }
  687. this._events[event].push(fct);
  688. return this;
  689. }
  690. }, {
  691. key: 'removeListener',
  692. value: function removeListener(event, fct) {
  693. var _this2 = this;
  694. if (!this._events) {
  695. this._events = {};
  696. }
  697. var listeners = this._events[event] || (this._events[event] = []);
  698. // Sadly, there's no IE8- support for indexOf.
  699. var i = 0;
  700. while (i < listeners.length) {
  701. if (listeners[i] === fct) {
  702. listeners[i] = undefined;
  703. }
  704. i++;
  705. }
  706. nextTick(function () {
  707. return _this2._events[event] = Array.from(_this2._events[event]).filter(function (x) {
  708. return x;
  709. });
  710. });
  711. return this;
  712. }
  713. }, {
  714. key: 'emit',
  715. value: function emit(event) {
  716. if (!(this._events != null ? this._events[event] : undefined)) {
  717. return this;
  718. }
  719. for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  720. args[_key - 1] = arguments[_key];
  721. }
  722. var _iteratorNormalCompletion11 = true;
  723. var _didIteratorError11 = false;
  724. var _iteratorError11 = undefined;
  725. try {
  726. for (var _iterator11 = Array.from(this._events[event])[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {
  727. var fn = _step11.value;
  728. if (fn) {
  729. fn.apply(this, args);
  730. }
  731. }
  732. } catch (err) {
  733. _didIteratorError11 = true;
  734. _iteratorError11 = err;
  735. } finally {
  736. try {
  737. if (!_iteratorNormalCompletion11 && _iterator11.return) {
  738. _iterator11.return();
  739. }
  740. } finally {
  741. if (_didIteratorError11) {
  742. throw _iteratorError11;
  743. }
  744. }
  745. }
  746. return this;
  747. }
  748. }]);
  749. return MicroEvent;
  750. }();
  751. // mixin will delegate all MicroEvent.js function in the destination object
  752. MicroEvent.mixin = function (obj) {
  753. var proto = obj.prototype || obj;
  754. // Damn closure compiler :/
  755. proto.on = MicroEvent.prototype.on;
  756. proto.removeListener = MicroEvent.prototype.removeListener;
  757. proto.emit = MicroEvent.prototype.emit;
  758. return obj;
  759. };
  760. if (WEB == null) {
  761. module.exports = MicroEvent;
  762. }
  763. if (WEB != null) {
  764. exports.extendDoc = function (name, fn) {
  765. return Doc.prototype[name] = fn;
  766. };
  767. }
  768. // A Doc is a client's view on a sharejs document.
  769. //
  770. // Documents are created by calling Connection.open().
  771. //
  772. // Documents are event emitters - use doc.on(eventname, fn) to subscribe.
  773. //
  774. // Documents get mixed in with their type's API methods. So, you can .insert('foo', 0) into
  775. // a text document and stuff like that.
  776. //
  777. // Events:
  778. // - remoteop (op)
  779. // - changed (op)
  780. // - acknowledge (op)
  781. // - error
  782. // - open, closing, closed. 'closing' is not guaranteed to fire before closed.
  783. var Doc = function () {
  784. // connection is a Connection object.
  785. // name is the documents' docName.
  786. // data can optionally contain known document data, and initial open() call arguments:
  787. // {v[erson], snapshot={...}, type, create=true/false/undefined}
  788. // callback will be called once the document is first opened.
  789. function Doc(connection, name, openData) {
  790. _classCallCheck(this, Doc);
  791. // Any of these can be null / undefined at this stage.
  792. this.flush = this.flush.bind(this);
  793. this.setFlushDelay = this.setFlushDelay.bind(this);
  794. this.shout = this.shout.bind(this);
  795. this.connection = connection;
  796. this.name = name;
  797. if (!openData) {
  798. openData = {};
  799. }
  800. this.version = openData.v;
  801. this.lastServerActivity = performance.now()
  802. this.snapshot = openData.snaphot;
  803. if (openData.type) {
  804. this._setType(openData.type);
  805. }
  806. this.state = 'closed';
  807. this.autoOpen = false;
  808. // Has the document already been created?
  809. this._create = openData.create;
  810. // The op that is currently roundtripping to the server, or null.
  811. //
  812. // When the connection reconnects, the inflight op is resubmitted.
  813. this.inflightOp = null;
  814. this.inflightCallbacks = [];
  815. // The auth ids which the client has previously used to attempt to send inflightOp. This is
  816. // usually empty.
  817. this.inflightSubmittedIds = [];
  818. // All ops that are waiting for the server to acknowledge @inflightOp
  819. this.pendingOp = null;
  820. this.pendingCallbacks = [];
  821. }
  822. // Transform a server op by a client op, and vice versa.
  823. _createClass(Doc, [{
  824. key: '_xf',
  825. value: function _xf(client, server) {
  826. if (this.type.transformX) {
  827. return this.type.transformX(client, server);
  828. } else {
  829. var client_ = this.type.transform(client, server, 'left');
  830. var server_ = this.type.transform(server, client, 'right');
  831. return [client_, server_];
  832. }
  833. }
  834. }, {
  835. key: '_otApply',
  836. value: function _otApply(docOp, isRemote, msg) {
  837. var oldSnapshot = this.snapshot;
  838. this.snapshot = this.type.apply(this.snapshot, docOp);
  839. // Its important that these event handlers are called with oldSnapshot.
  840. // The reason is that the OT type APIs might need to access the snapshots to
  841. // determine information about the received op.
  842. this.emit('change', docOp, oldSnapshot, msg, isRemote);
  843. if (isRemote) {
  844. return this.emit('remoteop', docOp, oldSnapshot, msg);
  845. }
  846. }
  847. }, {
  848. key: '_connectionStateChanged',
  849. value: function _connectionStateChanged(state, data) {
  850. switch (state) {
  851. case 'disconnected':
  852. this.state = 'closed';
  853. // This is used by the server to make sure that when an op is resubmitted it
  854. // doesn't end up getting applied twice.
  855. if (this.inflightOp) {
  856. this.inflightSubmittedIds.push(this.connection.id);
  857. }
  858. this.emit('closed');
  859. break;
  860. case 'ok':
  861. // Might be able to do this when we're connecting... that would save a roundtrip.
  862. if (this.autoOpen) {
  863. this.open();
  864. }
  865. break;
  866. case 'stopped':
  867. if (typeof this._openCallback === 'function') {
  868. this._openCallback(data);
  869. }
  870. break;
  871. }
  872. return this.emit(state, data);
  873. }
  874. }, {
  875. key: '_setType',
  876. value: function _setType(type) {
  877. if (typeof type === 'string') {
  878. type = types[type];
  879. }
  880. if (!type || !type.compose) {
  881. throw new Error('Support for types without compose() is not implemented');
  882. }
  883. this.type = type;
  884. if (type.api) {
  885. for (var k in type.api) {
  886. var v = type.api[k];this[k] = v;
  887. }
  888. return typeof this._register === 'function' ? this._register() : undefined;
  889. } else {
  890. return this.provides = {};
  891. }
  892. }
  893. }, {
  894. key: '_onMessage',
  895. value: function _onMessage(msg) {
  896. // debugConsole.warn('s->c', msg)
  897. if (msg.open === true) {
  898. // The document has been successfully opened.
  899. this.state = 'open';
  900. this._create = false; // Don't try and create the document again next time open() is called.
  901. if (this.created == null) {
  902. this.created = !!msg.create;
  903. }
  904. if (msg.type) {
  905. this._setType(msg.type);
  906. }
  907. if (msg.create) {
  908. this.created = true;
  909. this.snapshot = this.type.create();
  910. } else {
  911. if (this.created !== true) {
  912. this.created = false;
  913. }
  914. if (msg.snapshot !== undefined) {
  915. this.snapshot = msg.snapshot;
  916. }
  917. }
  918. if (msg.v != null) {
  919. this.version = msg.v;
  920. }
  921. // Resend any previously queued operation.
  922. if (this.inflightOp) {
  923. var response = {
  924. doc: this.name,
  925. op: this.inflightOp,
  926. v: this.version
  927. };
  928. if (this.inflightSubmittedIds.length) {
  929. response.dupIfSource = this.inflightSubmittedIds;
  930. }
  931. this.connection.send(response);
  932. } else {
  933. this.flush();
  934. }
  935. this.emit('open');
  936. return typeof this._openCallback === 'function' ? this._openCallback(null) : undefined;
  937. } else if (msg.open === false) {
  938. // The document has either been closed, or an open request has failed.
  939. if (msg.error) {
  940. // An error occurred opening the document.
  941. debugConsole.error('Could not open document: ' + msg.error);
  942. this.emit('error', msg.error);
  943. if (typeof this._openCallback === 'function') {
  944. this._openCallback(msg.error);
  945. }
  946. }
  947. this.state = 'closed';
  948. this.emit('closed');
  949. if (typeof this._closeCallback === 'function') {
  950. this._closeCallback();
  951. }
  952. return this._closeCallback = null;
  953. } else if (msg.op === null && error === 'Op already submitted') {
  954. // Overleaf: note that this branch is never reached, as `error` is always undefined
  955. // We've tried to resend an op to the server, which has already been received successfully. Do nothing.
  956. // The op will be confirmed normally when we get the op itself was echoed back from the server
  957. // (handled below).
  958. } else if (msg.op === undefined && msg.v !== undefined || msg.op && Array.from(this.inflightSubmittedIds).includes(msg.meta.source)) {
  959. // Overleaf: avoid clearing inflightOp on repeated acknowledgement of operations on the same version
  960. if (!msg.error) {
  961. if (msg.op === undefined && msg.v !== undefined) {
  962. if (msg.v < this.version) {
  963. postJSON('/error/client', {
  964. body: {
  965. error: {
  966. message: 'out-of-order-ack-ignored'
  967. },
  968. meta: { msg, version: this.version }
  969. }
  970. })
  971. return
  972. }
  973. } else {
  974. if (msg.v < this.version) {
  975. postJSON('/error/client', {
  976. body: {
  977. error: {
  978. message: 'out-of-order-self-op-ignored'
  979. },
  980. meta: { msg: { v: msg.v }, version: this.version }
  981. }
  982. })
  983. // return // TODO: enable this?
  984. }
  985. }
  986. }
  987. // Our inflight op has been acknowledged.
  988. var callback = void 0;
  989. var oldInflightOp = this.inflightOp;
  990. this.inflightOp = null;
  991. this.inflightSubmittedIds.length = 0;
  992. if (this.pendingOp === null) {
  993. // All ops are acked
  994. this.emit('saved');
  995. }
  996. var error = msg.error;
  997. if (error) {
  998. // The server has rejected an op from the client for some reason.
  999. // We'll send the error message to the user and roll back the change.
  1000. //
  1001. // If the server isn't going to allow edits anyway, we should probably
  1002. // figure out some way to flag that (readonly:true in the open request?)
  1003. if (this.type.invert) {
  1004. var undo = this.type.invert(oldInflightOp);
  1005. // Now we have to transform the undo operation by any server ops & pending ops
  1006. if (this.pendingOp) {
  1007. var _Array$from7 = Array.from(this._xf(this.pendingOp, undo));
  1008. var _Array$from8 = _slicedToArray(_Array$from7, 2);
  1009. this.pendingOp = _Array$from8[0];
  1010. undo = _Array$from8[1];
  1011. }
  1012. // ... and apply it locally, reverting the changes.
  1013. //
  1014. // This call will also call @emit 'remoteop'. I'm still not 100% sure about this
  1015. // functionality, because its really a local op. Basically, the problem is that
  1016. // if the client's op is rejected by the server, the editor window should update
  1017. // to reflect the undo.
  1018. this._otApply(undo, true, msg);
  1019. } else {
  1020. this.emit('error', 'Op apply failed (' + error + ') and the op could not be reverted');
  1021. }
  1022. var _iteratorNormalCompletion12 = true;
  1023. var _didIteratorError12 = false;
  1024. var _iteratorError12 = undefined;
  1025. try {
  1026. for (var _iterator12 = Array.from(this.inflightCallbacks)[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) {
  1027. callback = _step12.value;
  1028. callback(error);
  1029. }
  1030. } catch (err) {
  1031. _didIteratorError12 = true;
  1032. _iteratorError12 = err;
  1033. } finally {
  1034. try {
  1035. if (!_iteratorNormalCompletion12 && _iterator12.return) {
  1036. _iterator12.return();
  1037. }
  1038. } finally {
  1039. if (_didIteratorError12) {
  1040. throw _iteratorError12;
  1041. }
  1042. }
  1043. }
  1044. } else {
  1045. // The op applied successfully.
  1046. // We may get multiple acks of the same message if we retried it,
  1047. // so its ok if we receive an ack for a version that we've already gone past.
  1048. // If so, just ignore it
  1049. if (msg.v < this.version) {
  1050. return;
  1051. }
  1052. if (msg.v !== this.version) {
  1053. throw new Error('Invalid version from server');
  1054. }
  1055. this.version++;
  1056. this.lastServerActivity = performance.now()
  1057. this.emit('acknowledge', oldInflightOp);
  1058. var _iteratorNormalCompletion13 = true;
  1059. var _didIteratorError13 = false;
  1060. var _iteratorError13 = undefined;
  1061. try {
  1062. for (var _iterator13 = Array.from(this.inflightCallbacks)[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) {
  1063. callback = _step13.value;
  1064. callback(null, oldInflightOp);
  1065. }
  1066. } catch (err) {
  1067. _didIteratorError13 = true;
  1068. _iteratorError13 = err;
  1069. } finally {
  1070. try {
  1071. if (!_iteratorNormalCompletion13 && _iterator13.return) {
  1072. _iterator13.return();
  1073. }
  1074. } finally {
  1075. if (_didIteratorError13) {
  1076. throw _iteratorError13;
  1077. }
  1078. }
  1079. }
  1080. }
  1081. // Send the next op.
  1082. return this.delayedFlush();
  1083. } else if (msg.op) {
  1084. // We got a new op from the server.
  1085. // msg is {doc:, op:, v:}
  1086. // There is a bug in socket.io (produced on firefox 3.6) which causes messages
  1087. // to be duplicated sometimes.
  1088. // We'll just silently drop subsequent messages.
  1089. if (msg.v < this.version) {
  1090. return;
  1091. }
  1092. if (msg.doc !== this.name) {
  1093. return this.emit('error', 'Expected docName \'' + this.name + '\' but got ' + msg.doc);
  1094. }
  1095. if (msg.v !== this.version) {
  1096. return this.emit('error', 'Expected version ' + this.version + ' but got ' + msg.v);
  1097. }
  1098. // p "if: #{i @inflightOp} pending: #{i @pendingOp} doc '#{@snapshot}' op: #{i msg.op}"
  1099. var docOp = msg.op;
  1100. if (this.inflightOp !== null) {
  1101. var _Array$from9 = Array.from(this._xf(this.inflightOp, docOp));
  1102. var _Array$from10 = _slicedToArray(_Array$from9, 2);
  1103. this.inflightOp = _Array$from10[0];
  1104. docOp = _Array$from10[1];
  1105. }
  1106. if (this.pendingOp !== null) {
  1107. var _Array$from11 = Array.from(this._xf(this.pendingOp, docOp));
  1108. var _Array$from12 = _slicedToArray(_Array$from11, 2);
  1109. this.pendingOp = _Array$from12[0];
  1110. docOp = _Array$from12[1];
  1111. }
  1112. this.version++;
  1113. this.lastServerActivity = performance.now()
  1114. // Finally, apply the op to @snapshot and trigger any event listeners
  1115. return this._otApply(docOp, true, msg);
  1116. } else if (msg.meta) {
  1117. var _msg$meta = msg.meta,
  1118. path = _msg$meta.path,
  1119. value = _msg$meta.value;
  1120. switch (path != null ? path[0] : undefined) {
  1121. case 'shout':
  1122. return this.emit('shout', value);
  1123. default:
  1124. return debugConsole.warn('Unhandled meta op:', msg);
  1125. }
  1126. } else {
  1127. return debugConsole.warn('Unhandled document message:', msg);
  1128. }
  1129. }
  1130. // Send ops to the server, if appropriate.
  1131. //
  1132. // Only one op can be in-flight at a time, so if an op is already on its way then
  1133. // this method does nothing.
  1134. }, {
  1135. key: 'flush',
  1136. value: function flush() {
  1137. this.flushTimeout = null;
  1138. // console.log "CALLED FLUSH"
  1139. if (this.connection.state !== 'ok' || this.inflightOp !== null || this.pendingOp === null) {
  1140. return;
  1141. }
  1142. // Rotate null -> pending -> inflight
  1143. this.inflightOp = this.pendingOp;
  1144. this.inflightCallbacks = this.pendingCallbacks;
  1145. this.pendingOp = null;
  1146. this.pendingCallbacks = [];
  1147. this.emit('flipped_pending_to_inflight');
  1148. if (getMeta('ol-useShareJsHash') || debugging) {
  1149. var now = Date.now()
  1150. var age = this.__lastSubmitTimestamp && (now - this.__lastSubmitTimestamp)
  1151. var RECOMPUTE_HASH_INTERVAL = 5000
  1152. // check the document hash regularly (but not if we have checked in the last 5 seconds)
  1153. var needToRecomputeHash = !this.__lastSubmitTimestamp || (age > RECOMPUTE_HASH_INTERVAL) || (age < 0)
  1154. if (needToRecomputeHash || debugging) {
  1155. // send git hash of current snapshot
  1156. var sha1 = generateSHA1Hash("blob " + this.snapshot.length + "\x00" + this.snapshot)
  1157. this.__lastSubmitTimestamp = now;
  1158. }
  1159. }
  1160. // console.log "SENDING OP TO SERVER", @inflightOp, @version
  1161. var lastVersion = this.__lastVersion;
  1162. this.__lastVersion = this.version;
  1163. return this.connection.send({ doc: this.name, op: this.inflightOp, v: this.version, lastV: lastVersion, hash: sha1});
  1164. }
  1165. // Submit an op to the server. The op maybe held for a little while before being sent, as only one
  1166. // op can be inflight at any time.
  1167. }, {
  1168. key: 'submitOp',
  1169. value: function submitOp(op, callback) {
  1170. if (this.type.normalize != null) {
  1171. op = this.type.normalize(op);
  1172. }
  1173. var oldSnapshot = this.snapshot;
  1174. // If this throws an exception, no changes should have been made to the doc
  1175. this.snapshot = this.type.apply(this.snapshot, op);
  1176. if (this.pendingOp !== null) {
  1177. this.pendingOp = this.type.compose(this.pendingOp, op);
  1178. } else {
  1179. this.pendingOp = op;
  1180. }
  1181. if (callback) {
  1182. this.pendingCallbacks.push(callback);
  1183. }
  1184. this.emit('change', op, oldSnapshot);
  1185. return this.delayedFlush();
  1186. }
  1187. }, {
  1188. key: 'delayedFlush',
  1189. value: function delayedFlush() {
  1190. if (this.flushTimeout == null) {
  1191. return this.flushTimeout = setTimeout(this.flush, this._flushDelay || 0);
  1192. }
  1193. }
  1194. }, {
  1195. key: 'setFlushDelay',
  1196. value: function setFlushDelay(delay) {
  1197. return this._flushDelay = delay;
  1198. }
  1199. }, {
  1200. key: 'shout',
  1201. value: function shout(msg) {
  1202. // Meta ops don't have to queue, they can go direct. Good/bad idea?
  1203. return this.connection.send({ doc: this.name, meta: { path: ['shout'], value: msg } });
  1204. }
  1205. // Open a document. The document starts closed.
  1206. }, {
  1207. key: 'open',
  1208. value: function open(callback) {
  1209. var _this3 = this;
  1210. this.autoOpen = true;
  1211. if (this.state !== 'closed') {
  1212. return;
  1213. }
  1214. var message = {
  1215. doc: this.name,
  1216. open: true
  1217. };
  1218. if (this.snapshot === undefined) {
  1219. message.snapshot = null;
  1220. }
  1221. if (this.type) {
  1222. message.type = this.type.name;
  1223. }
  1224. if (this.version != null) {
  1225. message.v = this.version;
  1226. }
  1227. if (this._create) {
  1228. message.create = true;
  1229. }
  1230. this.connection.send(message);
  1231. this.state = 'opening';
  1232. return this._openCallback = function (error) {
  1233. _this3._openCallback = null;
  1234. return typeof callback === 'function' ? callback(error) : undefined;
  1235. };
  1236. }
  1237. // Close a document.
  1238. }, {
  1239. key: 'close',
  1240. value: function close(callback) {
  1241. this.autoOpen = false;
  1242. if (this.state === 'closed') {
  1243. return typeof callback === 'function' ? callback() : undefined;
  1244. }
  1245. this.connection.send({ doc: this.name, open: false });
  1246. // Should this happen immediately or when we get open:false back from the server?
  1247. this.state = 'closed';
  1248. this.emit('closing');
  1249. return this._closeCallback = callback;
  1250. }
  1251. }]);
  1252. return Doc;
  1253. }();
  1254. // Make documents event emitters
  1255. MicroEvent.mixin(Doc);
  1256. exports.Doc = Doc;
  1257. return exports;
  1258. })()
  1259. export default window.sharejs