braidfs 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # braidfs
2
+ braid technology synchronizing files and webpages
package/diff.js ADDED
@@ -0,0 +1,785 @@
1
+
2
+ var DIFF_DELETE = -1;
3
+ var DIFF_INSERT = 1;
4
+ var DIFF_EQUAL = 0;
5
+
6
+ function get_merged_diff_patch(a, b, o) {
7
+ var a_diff = get_diff_patch(o, a)
8
+ var b_diff = get_diff_patch(o, b)
9
+ var ds = []
10
+ var prev_d = null
11
+ while (a_diff.length > 0 || b_diff.length > 0) {
12
+ var d = a_diff.length == 0 ?
13
+ b_diff.shift() :
14
+ b_diff.length == 0 ?
15
+ a_diff.shift() :
16
+ a_diff[0][0] < b_diff[0][0] ?
17
+ a_diff.shift() :
18
+ a_diff[0][0] > b_diff[0][0] ?
19
+ b_diff.shift() :
20
+ a_diff[0][2] < b_diff[0][2] ?
21
+ a_diff.shift() :
22
+ b_diff.shift()
23
+ if (prev_d && d[0] < prev_d[0] + prev_d[1]) {
24
+ if (d[0] + d[1] > prev_d[0] + prev_d[1]) {
25
+ prev_d[1] = d[0] + d[1] - prev_d[0]
26
+ }
27
+ prev_d[2] += d[2]
28
+ } else {
29
+ ds.push(d)
30
+ prev_d = d
31
+ }
32
+ }
33
+ return ds
34
+ }
35
+
36
+ function apply_diff_patch(s, diff) {
37
+ var offset = 0
38
+ for (var i = 0; i < diff.length; i++) {
39
+ var d = diff[i]
40
+ s = s.slice(0, d[0] + offset) + d[2] + s.slice(d[0] + offset + d[1])
41
+ offset += d[2].length - d[1]
42
+ }
43
+ return s
44
+ }
45
+
46
+ function diff_convert_to_my_format(d, factor) {
47
+ if (factor === undefined) factor = 1
48
+ var x = []
49
+ var ii = 0
50
+ for (var i = 0; i < d.length; i++) {
51
+ var dd = d[i]
52
+ if (dd[0] == DIFF_EQUAL) {
53
+ ii += dd[1].length
54
+ continue
55
+ }
56
+ var xx = [ii, 0, '']
57
+ if (dd[0] == DIFF_INSERT * factor) {
58
+ xx[2] = dd[1]
59
+ } else if (dd[0] == DIFF_DELETE * factor) {
60
+ xx[1] = dd[1].length
61
+ ii += xx[1]
62
+ }
63
+ if (i + 1 < d.length) {
64
+ dd = d[i + 1]
65
+ if (dd[0] != DIFF_EQUAL) {
66
+ if (dd[0] == DIFF_INSERT * factor) {
67
+ xx[2] = dd[1]
68
+ } else if (dd[0] == DIFF_DELETE * factor) {
69
+ xx[1] = dd[1].length
70
+ ii += xx[1]
71
+ }
72
+ i++
73
+ }
74
+ }
75
+ x.push(xx)
76
+ }
77
+ return x
78
+ }
79
+
80
+ function get_diff_patch(a, b) {
81
+ return diff_convert_to_my_format(diff_main(a, b))
82
+ }
83
+
84
+ function get_diff_patch_2(a, b) {
85
+ var x = diff_main(a, b)
86
+ return [diff_convert_to_my_format(x),
87
+ diff_convert_to_my_format(x, -1)]
88
+ }
89
+
90
+ //diffsync.get_diff_patch = get_diff_patch
91
+ //diffsync.get_diff_patch_2 = get_diff_patch_2
92
+
93
+ /**
94
+ * This library modifies the diff-patch-match library by Neil Fraser
95
+ * by removing the patch and match functionality and certain advanced
96
+ * options in the diff function. The original license is as follows:
97
+ *
98
+ * ===
99
+ *
100
+ * Diff Match and Patch
101
+ *
102
+ * Copyright 2006 Google Inc.
103
+ * http://code.google.com/p/google-diff-match-patch/
104
+ *
105
+ * Licensed under the Apache License, Version 2.0 (the "License");
106
+ * you may not use this file except in compliance with the License.
107
+ * You may obtain a copy of the License at
108
+ *
109
+ * http://www.apache.org/licenses/LICENSE-2.0
110
+ *
111
+ * Unless required by applicable law or agreed to in writing, software
112
+ * distributed under the License is distributed on an "AS IS" BASIS,
113
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
+ * See the License for the specific language governing permissions and
115
+ * limitations under the License.
116
+ */
117
+
118
+
119
+ /**
120
+ * The data structure representing a diff is an array of tuples:
121
+ * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']]
122
+ * which means: delete 'Hello', add 'Goodbye' and keep ' world.'
123
+ */
124
+ var DIFF_DELETE = -1;
125
+ var DIFF_INSERT = 1;
126
+ var DIFF_EQUAL = 0;
127
+
128
+
129
+ /**
130
+ * Find the differences between two texts. Simplifies the problem by stripping
131
+ * any common prefix or suffix off the texts before diffing.
132
+ * @param {string} text1 Old string to be diffed.
133
+ * @param {string} text2 New string to be diffed.
134
+ * @param {Int} cursor_pos Expected edit position in text1 (optional)
135
+ * @return {Array} Array of diff tuples.
136
+ */
137
+ function diff_main(text1, text2, cursor_pos) {
138
+ // Check for equality (speedup).
139
+ if (text1 == text2) {
140
+ if (text1) {
141
+ return [[DIFF_EQUAL, text1]];
142
+ }
143
+ return [];
144
+ }
145
+
146
+ // Check cursor_pos within bounds
147
+ if (cursor_pos < 0 || text1.length < cursor_pos) {
148
+ cursor_pos = null;
149
+ }
150
+
151
+ // Trim off common prefix (speedup).
152
+ var commonlength = diff_commonPrefix(text1, text2);
153
+ var commonprefix = text1.substring(0, commonlength);
154
+ text1 = text1.substring(commonlength);
155
+ text2 = text2.substring(commonlength);
156
+
157
+ // Trim off common suffix (speedup).
158
+ commonlength = diff_commonSuffix(text1, text2);
159
+ var commonsuffix = text1.substring(text1.length - commonlength);
160
+ text1 = text1.substring(0, text1.length - commonlength);
161
+ text2 = text2.substring(0, text2.length - commonlength);
162
+
163
+ // Compute the diff on the middle block.
164
+ var diffs = diff_compute_(text1, text2);
165
+
166
+ // Restore the prefix and suffix.
167
+ if (commonprefix) {
168
+ diffs.unshift([DIFF_EQUAL, commonprefix]);
169
+ }
170
+ if (commonsuffix) {
171
+ diffs.push([DIFF_EQUAL, commonsuffix]);
172
+ }
173
+ diff_cleanupMerge(diffs);
174
+ if (cursor_pos != null) {
175
+ diffs = fix_cursor(diffs, cursor_pos);
176
+ }
177
+ return diffs;
178
+ };
179
+
180
+
181
+ /**
182
+ * Find the differences between two texts. Assumes that the texts do not
183
+ * have any common prefix or suffix.
184
+ * @param {string} text1 Old string to be diffed.
185
+ * @param {string} text2 New string to be diffed.
186
+ * @return {Array} Array of diff tuples.
187
+ */
188
+ function diff_compute_(text1, text2) {
189
+ var diffs;
190
+
191
+ if (!text1) {
192
+ // Just add some text (speedup).
193
+ return [[DIFF_INSERT, text2]];
194
+ }
195
+
196
+ if (!text2) {
197
+ // Just delete some text (speedup).
198
+ return [[DIFF_DELETE, text1]];
199
+ }
200
+
201
+ var longtext = text1.length > text2.length ? text1 : text2;
202
+ var shorttext = text1.length > text2.length ? text2 : text1;
203
+ var i = longtext.indexOf(shorttext);
204
+ if (i != -1) {
205
+ // Shorter text is inside the longer text (speedup).
206
+ diffs = [[DIFF_INSERT, longtext.substring(0, i)],
207
+ [DIFF_EQUAL, shorttext],
208
+ [DIFF_INSERT, longtext.substring(i + shorttext.length)]];
209
+ // Swap insertions for deletions if diff is reversed.
210
+ if (text1.length > text2.length) {
211
+ diffs[0][0] = diffs[2][0] = DIFF_DELETE;
212
+ }
213
+ return diffs;
214
+ }
215
+
216
+ if (shorttext.length == 1) {
217
+ // Single character string.
218
+ // After the previous speedup, the character can't be an equality.
219
+ return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
220
+ }
221
+
222
+ // Check to see if the problem can be split in two.
223
+ var hm = diff_halfMatch_(text1, text2);
224
+ if (hm) {
225
+ // A half-match was found, sort out the return data.
226
+ var text1_a = hm[0];
227
+ var text1_b = hm[1];
228
+ var text2_a = hm[2];
229
+ var text2_b = hm[3];
230
+ var mid_common = hm[4];
231
+ // Send both pairs off for separate processing.
232
+ var diffs_a = diff_main(text1_a, text2_a);
233
+ var diffs_b = diff_main(text1_b, text2_b);
234
+ // Merge the results.
235
+ return diffs_a.concat([[DIFF_EQUAL, mid_common]], diffs_b);
236
+ }
237
+
238
+ return diff_bisect_(text1, text2);
239
+ };
240
+
241
+
242
+ /**
243
+ * Find the 'middle snake' of a diff, split the problem in two
244
+ * and return the recursively constructed diff.
245
+ * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
246
+ * @param {string} text1 Old string to be diffed.
247
+ * @param {string} text2 New string to be diffed.
248
+ * @return {Array} Array of diff tuples.
249
+ * @private
250
+ */
251
+ function diff_bisect_(text1, text2) {
252
+ // Cache the text lengths to prevent multiple calls.
253
+ var text1_length = text1.length;
254
+ var text2_length = text2.length;
255
+ var max_d = Math.ceil((text1_length + text2_length) / 2);
256
+ var v_offset = max_d;
257
+ var v_length = 2 * max_d;
258
+ var v1 = new Array(v_length);
259
+ var v2 = new Array(v_length);
260
+ // Setting all elements to -1 is faster in Chrome & Firefox than mixing
261
+ // integers and undefined.
262
+ for (var x = 0; x < v_length; x++) {
263
+ v1[x] = -1;
264
+ v2[x] = -1;
265
+ }
266
+ v1[v_offset + 1] = 0;
267
+ v2[v_offset + 1] = 0;
268
+ var delta = text1_length - text2_length;
269
+ // If the total number of characters is odd, then the front path will collide
270
+ // with the reverse path.
271
+ var front = (delta % 2 != 0);
272
+ // Offsets for start and end of k loop.
273
+ // Prevents mapping of space beyond the grid.
274
+ var k1start = 0;
275
+ var k1end = 0;
276
+ var k2start = 0;
277
+ var k2end = 0;
278
+ for (var d = 0; d < max_d; d++) {
279
+ // Walk the front path one step.
280
+ for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) {
281
+ var k1_offset = v_offset + k1;
282
+ var x1;
283
+ if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) {
284
+ x1 = v1[k1_offset + 1];
285
+ } else {
286
+ x1 = v1[k1_offset - 1] + 1;
287
+ }
288
+ var y1 = x1 - k1;
289
+ while (x1 < text1_length && y1 < text2_length &&
290
+ text1.charAt(x1) == text2.charAt(y1)) {
291
+ x1++;
292
+ y1++;
293
+ }
294
+ v1[k1_offset] = x1;
295
+ if (x1 > text1_length) {
296
+ // Ran off the right of the graph.
297
+ k1end += 2;
298
+ } else if (y1 > text2_length) {
299
+ // Ran off the bottom of the graph.
300
+ k1start += 2;
301
+ } else if (front) {
302
+ var k2_offset = v_offset + delta - k1;
303
+ if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) {
304
+ // Mirror x2 onto top-left coordinate system.
305
+ var x2 = text1_length - v2[k2_offset];
306
+ if (x1 >= x2) {
307
+ // Overlap detected.
308
+ return diff_bisectSplit_(text1, text2, x1, y1);
309
+ }
310
+ }
311
+ }
312
+ }
313
+
314
+ // Walk the reverse path one step.
315
+ for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) {
316
+ var k2_offset = v_offset + k2;
317
+ var x2;
318
+ if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) {
319
+ x2 = v2[k2_offset + 1];
320
+ } else {
321
+ x2 = v2[k2_offset - 1] + 1;
322
+ }
323
+ var y2 = x2 - k2;
324
+ while (x2 < text1_length && y2 < text2_length &&
325
+ text1.charAt(text1_length - x2 - 1) ==
326
+ text2.charAt(text2_length - y2 - 1)) {
327
+ x2++;
328
+ y2++;
329
+ }
330
+ v2[k2_offset] = x2;
331
+ if (x2 > text1_length) {
332
+ // Ran off the left of the graph.
333
+ k2end += 2;
334
+ } else if (y2 > text2_length) {
335
+ // Ran off the top of the graph.
336
+ k2start += 2;
337
+ } else if (!front) {
338
+ var k1_offset = v_offset + delta - k2;
339
+ if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) {
340
+ var x1 = v1[k1_offset];
341
+ var y1 = v_offset + x1 - k1_offset;
342
+ // Mirror x2 onto top-left coordinate system.
343
+ x2 = text1_length - x2;
344
+ if (x1 >= x2) {
345
+ // Overlap detected.
346
+ return diff_bisectSplit_(text1, text2, x1, y1);
347
+ }
348
+ }
349
+ }
350
+ }
351
+ }
352
+ // Diff took too long and hit the deadline or
353
+ // number of diffs equals number of characters, no commonality at all.
354
+ return [[DIFF_DELETE, text1], [DIFF_INSERT, text2]];
355
+ };
356
+
357
+
358
+ /**
359
+ * Given the location of the 'middle snake', split the diff in two parts
360
+ * and recurse.
361
+ * @param {string} text1 Old string to be diffed.
362
+ * @param {string} text2 New string to be diffed.
363
+ * @param {number} x Index of split point in text1.
364
+ * @param {number} y Index of split point in text2.
365
+ * @return {Array} Array of diff tuples.
366
+ */
367
+ function diff_bisectSplit_(text1, text2, x, y) {
368
+ var text1a = text1.substring(0, x);
369
+ var text2a = text2.substring(0, y);
370
+ var text1b = text1.substring(x);
371
+ var text2b = text2.substring(y);
372
+
373
+ // Compute both diffs serially.
374
+ var diffs = diff_main(text1a, text2a);
375
+ var diffsb = diff_main(text1b, text2b);
376
+
377
+ return diffs.concat(diffsb);
378
+ };
379
+
380
+
381
+ /**
382
+ * Determine the common prefix of two strings.
383
+ * @param {string} text1 First string.
384
+ * @param {string} text2 Second string.
385
+ * @return {number} The number of characters common to the start of each
386
+ * string.
387
+ */
388
+ function diff_commonPrefix(text1, text2) {
389
+ // Quick check for common null cases.
390
+ if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) {
391
+ return 0;
392
+ }
393
+ // Binary search.
394
+ // Performance analysis: http://neil.fraser.name/news/2007/10/09/
395
+ var pointermin = 0;
396
+ var pointermax = Math.min(text1.length, text2.length);
397
+ var pointermid = pointermax;
398
+ var pointerstart = 0;
399
+ while (pointermin < pointermid) {
400
+ if (text1.substring(pointerstart, pointermid) ==
401
+ text2.substring(pointerstart, pointermid)) {
402
+ pointermin = pointermid;
403
+ pointerstart = pointermin;
404
+ } else {
405
+ pointermax = pointermid;
406
+ }
407
+ pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
408
+ }
409
+ return pointermid;
410
+ };
411
+
412
+
413
+ /**
414
+ * Determine the common suffix of two strings.
415
+ * @param {string} text1 First string.
416
+ * @param {string} text2 Second string.
417
+ * @return {number} The number of characters common to the end of each string.
418
+ */
419
+ function diff_commonSuffix(text1, text2) {
420
+ // Quick check for common null cases.
421
+ if (!text1 || !text2 ||
422
+ text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) {
423
+ return 0;
424
+ }
425
+ // Binary search.
426
+ // Performance analysis: http://neil.fraser.name/news/2007/10/09/
427
+ var pointermin = 0;
428
+ var pointermax = Math.min(text1.length, text2.length);
429
+ var pointermid = pointermax;
430
+ var pointerend = 0;
431
+ while (pointermin < pointermid) {
432
+ if (text1.substring(text1.length - pointermid, text1.length - pointerend) ==
433
+ text2.substring(text2.length - pointermid, text2.length - pointerend)) {
434
+ pointermin = pointermid;
435
+ pointerend = pointermin;
436
+ } else {
437
+ pointermax = pointermid;
438
+ }
439
+ pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin);
440
+ }
441
+ return pointermid;
442
+ };
443
+
444
+
445
+ /**
446
+ * Do the two texts share a substring which is at least half the length of the
447
+ * longer text?
448
+ * This speedup can produce non-minimal diffs.
449
+ * @param {string} text1 First string.
450
+ * @param {string} text2 Second string.
451
+ * @return {Array.<string>} Five element Array, containing the prefix of
452
+ * text1, the suffix of text1, the prefix of text2, the suffix of
453
+ * text2 and the common middle. Or null if there was no match.
454
+ */
455
+ function diff_halfMatch_(text1, text2) {
456
+ var longtext = text1.length > text2.length ? text1 : text2;
457
+ var shorttext = text1.length > text2.length ? text2 : text1;
458
+ if (longtext.length < 4 || shorttext.length * 2 < longtext.length) {
459
+ return null; // Pointless.
460
+ }
461
+
462
+ /**
463
+ * Does a substring of shorttext exist within longtext such that the substring
464
+ * is at least half the length of longtext?
465
+ * Closure, but does not reference any external variables.
466
+ * @param {string} longtext Longer string.
467
+ * @param {string} shorttext Shorter string.
468
+ * @param {number} i Start index of quarter length substring within longtext.
469
+ * @return {Array.<string>} Five element Array, containing the prefix of
470
+ * longtext, the suffix of longtext, the prefix of shorttext, the suffix
471
+ * of shorttext and the common middle. Or null if there was no match.
472
+ * @private
473
+ */
474
+ function diff_halfMatchI_(longtext, shorttext, i) {
475
+ // Start with a 1/4 length substring at position i as a seed.
476
+ var seed = longtext.substring(i, i + Math.floor(longtext.length / 4));
477
+ var j = -1;
478
+ var best_common = '';
479
+ var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b;
480
+ while ((j = shorttext.indexOf(seed, j + 1)) != -1) {
481
+ var prefixLength = diff_commonPrefix(longtext.substring(i),
482
+ shorttext.substring(j));
483
+ var suffixLength = diff_commonSuffix(longtext.substring(0, i),
484
+ shorttext.substring(0, j));
485
+ if (best_common.length < suffixLength + prefixLength) {
486
+ best_common = shorttext.substring(j - suffixLength, j) +
487
+ shorttext.substring(j, j + prefixLength);
488
+ best_longtext_a = longtext.substring(0, i - suffixLength);
489
+ best_longtext_b = longtext.substring(i + prefixLength);
490
+ best_shorttext_a = shorttext.substring(0, j - suffixLength);
491
+ best_shorttext_b = shorttext.substring(j + prefixLength);
492
+ }
493
+ }
494
+ if (best_common.length * 2 >= longtext.length) {
495
+ return [best_longtext_a, best_longtext_b,
496
+ best_shorttext_a, best_shorttext_b, best_common];
497
+ } else {
498
+ return null;
499
+ }
500
+ }
501
+
502
+ // First check if the second quarter is the seed for a half-match.
503
+ var hm1 = diff_halfMatchI_(longtext, shorttext,
504
+ Math.ceil(longtext.length / 4));
505
+ // Check again based on the third quarter.
506
+ var hm2 = diff_halfMatchI_(longtext, shorttext,
507
+ Math.ceil(longtext.length / 2));
508
+ var hm;
509
+ if (!hm1 && !hm2) {
510
+ return null;
511
+ } else if (!hm2) {
512
+ hm = hm1;
513
+ } else if (!hm1) {
514
+ hm = hm2;
515
+ } else {
516
+ // Both matched. Select the longest.
517
+ hm = hm1[4].length > hm2[4].length ? hm1 : hm2;
518
+ }
519
+
520
+ // A half-match was found, sort out the return data.
521
+ var text1_a, text1_b, text2_a, text2_b;
522
+ if (text1.length > text2.length) {
523
+ text1_a = hm[0];
524
+ text1_b = hm[1];
525
+ text2_a = hm[2];
526
+ text2_b = hm[3];
527
+ } else {
528
+ text2_a = hm[0];
529
+ text2_b = hm[1];
530
+ text1_a = hm[2];
531
+ text1_b = hm[3];
532
+ }
533
+ var mid_common = hm[4];
534
+ return [text1_a, text1_b, text2_a, text2_b, mid_common];
535
+ };
536
+
537
+
538
+ /**
539
+ * Reorder and merge like edit sections. Merge equalities.
540
+ * Any edit section can move as long as it doesn't cross an equality.
541
+ * @param {Array} diffs Array of diff tuples.
542
+ */
543
+ function diff_cleanupMerge(diffs) {
544
+ diffs.push([DIFF_EQUAL, '']); // Add a dummy entry at the end.
545
+ var pointer = 0;
546
+ var count_delete = 0;
547
+ var count_insert = 0;
548
+ var text_delete = '';
549
+ var text_insert = '';
550
+ var commonlength;
551
+ while (pointer < diffs.length) {
552
+ switch (diffs[pointer][0]) {
553
+ case DIFF_INSERT:
554
+ count_insert++;
555
+ text_insert += diffs[pointer][1];
556
+ pointer++;
557
+ break;
558
+ case DIFF_DELETE:
559
+ count_delete++;
560
+ text_delete += diffs[pointer][1];
561
+ pointer++;
562
+ break;
563
+ case DIFF_EQUAL:
564
+ // Upon reaching an equality, check for prior redundancies.
565
+ if (count_delete + count_insert > 1) {
566
+ if (count_delete !== 0 && count_insert !== 0) {
567
+ // Factor out any common prefixies.
568
+ commonlength = diff_commonPrefix(text_insert, text_delete);
569
+ if (commonlength !== 0) {
570
+ if ((pointer - count_delete - count_insert) > 0 &&
571
+ diffs[pointer - count_delete - count_insert - 1][0] ==
572
+ DIFF_EQUAL) {
573
+ diffs[pointer - count_delete - count_insert - 1][1] +=
574
+ text_insert.substring(0, commonlength);
575
+ } else {
576
+ diffs.splice(0, 0, [DIFF_EQUAL,
577
+ text_insert.substring(0, commonlength)]);
578
+ pointer++;
579
+ }
580
+ text_insert = text_insert.substring(commonlength);
581
+ text_delete = text_delete.substring(commonlength);
582
+ }
583
+ // Factor out any common suffixies.
584
+ commonlength = diff_commonSuffix(text_insert, text_delete);
585
+ if (commonlength !== 0) {
586
+ diffs[pointer][1] = text_insert.substring(text_insert.length -
587
+ commonlength) + diffs[pointer][1];
588
+ text_insert = text_insert.substring(0, text_insert.length -
589
+ commonlength);
590
+ text_delete = text_delete.substring(0, text_delete.length -
591
+ commonlength);
592
+ }
593
+ }
594
+ // Delete the offending records and add the merged ones.
595
+ if (count_delete === 0) {
596
+ diffs.splice(pointer - count_insert,
597
+ count_delete + count_insert, [DIFF_INSERT, text_insert]);
598
+ } else if (count_insert === 0) {
599
+ diffs.splice(pointer - count_delete,
600
+ count_delete + count_insert, [DIFF_DELETE, text_delete]);
601
+ } else {
602
+ diffs.splice(pointer - count_delete - count_insert,
603
+ count_delete + count_insert, [DIFF_DELETE, text_delete],
604
+ [DIFF_INSERT, text_insert]);
605
+ }
606
+ pointer = pointer - count_delete - count_insert +
607
+ (count_delete ? 1 : 0) + (count_insert ? 1 : 0) + 1;
608
+ } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) {
609
+ // Merge this equality with the previous one.
610
+ diffs[pointer - 1][1] += diffs[pointer][1];
611
+ diffs.splice(pointer, 1);
612
+ } else {
613
+ pointer++;
614
+ }
615
+ count_insert = 0;
616
+ count_delete = 0;
617
+ text_delete = '';
618
+ text_insert = '';
619
+ break;
620
+ }
621
+ }
622
+ if (diffs[diffs.length - 1][1] === '') {
623
+ diffs.pop(); // Remove the dummy entry at the end.
624
+ }
625
+
626
+ // Second pass: look for single edits surrounded on both sides by equalities
627
+ // which can be shifted sideways to eliminate an equality.
628
+ // e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
629
+ var changes = false;
630
+ pointer = 1;
631
+ // Intentionally ignore the first and last element (don't need checking).
632
+ while (pointer < diffs.length - 1) {
633
+ if (diffs[pointer - 1][0] == DIFF_EQUAL &&
634
+ diffs[pointer + 1][0] == DIFF_EQUAL) {
635
+ // This is a single edit surrounded by equalities.
636
+ if (diffs[pointer][1].substring(diffs[pointer][1].length -
637
+ diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) {
638
+ // Shift the edit over the previous equality.
639
+ diffs[pointer][1] = diffs[pointer - 1][1] +
640
+ diffs[pointer][1].substring(0, diffs[pointer][1].length -
641
+ diffs[pointer - 1][1].length);
642
+ diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1];
643
+ diffs.splice(pointer - 1, 1);
644
+ changes = true;
645
+ } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) ==
646
+ diffs[pointer + 1][1]) {
647
+ // Shift the edit over the next equality.
648
+ diffs[pointer - 1][1] += diffs[pointer + 1][1];
649
+ diffs[pointer][1] =
650
+ diffs[pointer][1].substring(diffs[pointer + 1][1].length) +
651
+ diffs[pointer + 1][1];
652
+ diffs.splice(pointer + 1, 1);
653
+ changes = true;
654
+ }
655
+ }
656
+ pointer++;
657
+ }
658
+ // If shifts were made, the diff needs reordering and another shift sweep.
659
+ if (changes) {
660
+ diff_cleanupMerge(diffs);
661
+ }
662
+ };
663
+
664
+
665
+ /*
666
+ * Modify a diff such that the cursor position points to the start of a change:
667
+ * E.g.
668
+ * cursor_normalize_diff([[DIFF_EQUAL, 'abc']], 1)
669
+ * => [1, [[DIFF_EQUAL, 'a'], [DIFF_EQUAL, 'bc']]]
670
+ * cursor_normalize_diff([[DIFF_INSERT, 'new'], [DIFF_DELETE, 'xyz']], 2)
671
+ * => [2, [[DIFF_INSERT, 'new'], [DIFF_DELETE, 'xy'], [DIFF_DELETE, 'z']]]
672
+ *
673
+ * @param {Array} diffs Array of diff tuples
674
+ * @param {Int} cursor_pos Suggested edit position. Must not be out of bounds!
675
+ * @return {Array} A tuple [cursor location in the modified diff, modified diff]
676
+ */
677
+ function cursor_normalize_diff (diffs, cursor_pos) {
678
+ if (cursor_pos === 0) {
679
+ return [DIFF_EQUAL, diffs];
680
+ }
681
+ for (var current_pos = 0, i = 0; i < diffs.length; i++) {
682
+ var d = diffs[i];
683
+ if (d[0] === DIFF_DELETE || d[0] === DIFF_EQUAL) {
684
+ var next_pos = current_pos + d[1].length;
685
+ if (cursor_pos === next_pos) {
686
+ return [i + 1, diffs];
687
+ } else if (cursor_pos < next_pos) {
688
+ // copy to prevent side effects
689
+ diffs = diffs.slice();
690
+ // split d into two diff changes
691
+ var split_pos = cursor_pos - current_pos;
692
+ var d_left = [d[0], d[1].slice(0, split_pos)];
693
+ var d_right = [d[0], d[1].slice(split_pos)];
694
+ diffs.splice(i, 1, d_left, d_right);
695
+ return [i + 1, diffs];
696
+ } else {
697
+ current_pos = next_pos;
698
+ }
699
+ }
700
+ }
701
+ throw new Error('cursor_pos is out of bounds!')
702
+ }
703
+
704
+ /*
705
+ * Modify a diff such that the edit position is "shifted" to the proposed edit location (cursor_position).
706
+ *
707
+ * Case 1)
708
+ * Check if a naive shift is possible:
709
+ * [0, X], [ 1, Y] -> [ 1, Y], [0, X] (if X + Y === Y + X)
710
+ * [0, X], [-1, Y] -> [-1, Y], [0, X] (if X + Y === Y + X) - holds same result
711
+ * Case 2)
712
+ * Check if the following shifts are possible:
713
+ * [0, 'pre'], [ 1, 'prefix'] -> [ 1, 'pre'], [0, 'pre'], [ 1, 'fix']
714
+ * [0, 'pre'], [-1, 'prefix'] -> [-1, 'pre'], [0, 'pre'], [-1, 'fix']
715
+ * ^ ^
716
+ * d d_next
717
+ *
718
+ * @param {Array} diffs Array of diff tuples
719
+ * @param {Int} cursor_pos Suggested edit position. Must not be out of bounds!
720
+ * @return {Array} Array of diff tuples
721
+ */
722
+ function fix_cursor (diffs, cursor_pos) {
723
+ var norm = cursor_normalize_diff(diffs, cursor_pos);
724
+ var ndiffs = norm[1];
725
+ var cursor_pointer = norm[0];
726
+ var d = ndiffs[cursor_pointer];
727
+ var d_next = ndiffs[cursor_pointer + 1];
728
+
729
+ if (d == null) {
730
+ // Text was deleted from end of original string,
731
+ // cursor is now out of bounds in new string
732
+ return diffs;
733
+ } else if (d[0] !== DIFF_EQUAL) {
734
+ // A modification happened at the cursor location.
735
+ // This is the expected outcome, so we can return the original diff.
736
+ return diffs;
737
+ } else {
738
+ if (d_next != null && d[1] + d_next[1] === d_next[1] + d[1]) {
739
+ // Case 1)
740
+ // It is possible to perform a naive shift
741
+ ndiffs.splice(cursor_pointer, 2, d_next, d)
742
+ return merge_tuples(ndiffs, cursor_pointer, 2)
743
+ } else if (d_next != null && d_next[1].indexOf(d[1]) === 0) {
744
+ // Case 2)
745
+ // d[1] is a prefix of d_next[1]
746
+ // We can assume that d_next[0] !== 0, since d[0] === 0
747
+ // Shift edit locations..
748
+ ndiffs.splice(cursor_pointer, 2, [d_next[0], d[1]], [0, d[1]]);
749
+ var suffix = d_next[1].slice(d[1].length);
750
+ if (suffix.length > 0) {
751
+ ndiffs.splice(cursor_pointer + 2, 0, [d_next[0], suffix]);
752
+ }
753
+ return merge_tuples(ndiffs, cursor_pointer, 3)
754
+ } else {
755
+ // Not possible to perform any modification
756
+ return diffs;
757
+ }
758
+ }
759
+
760
+ }
761
+
762
+ /*
763
+ * Try to merge tuples with their neigbors in a given range.
764
+ * E.g. [0, 'a'], [0, 'b'] -> [0, 'ab']
765
+ *
766
+ * @param {Array} diffs Array of diff tuples.
767
+ * @param {Int} start Position of the first element to merge (diffs[start] is also merged with diffs[start - 1]).
768
+ * @param {Int} length Number of consecutive elements to check.
769
+ * @return {Array} Array of merged diff tuples.
770
+ */
771
+ function merge_tuples (diffs, start, length) {
772
+ // Check from (start-1) to (start+length).
773
+ for (var i = start + length - 1; i >= 0 && i >= start - 1; i--) {
774
+ if (i + 1 < diffs.length) {
775
+ var left_d = diffs[i];
776
+ var right_d = diffs[i+1];
777
+ if (left_d[0] === right_d[1]) {
778
+ diffs.splice(i, 2, [left_d[0], left_d[1] + right_d[1]]);
779
+ }
780
+ }
781
+ }
782
+ return diffs;
783
+ }
784
+
785
+ module.exports = {diff_main}
package/editor.html ADDED
@@ -0,0 +1,79 @@
1
+ <body style="background: auto; margin: 0px; padding: 0px">
2
+ <textarea
3
+ id="texty"
4
+ style="width: 100%; height: 100%; box-sizing: border-box"
5
+ ></textarea>
6
+ </body>
7
+ <script src="https://braid.org/code/myers-diff1.js"></script>
8
+ <script src="https://unpkg.com/braid-http@~0.3/braid-http-client.js"></script>
9
+ <script src="https://unpkg.com/braid-text/simpleton-client.js"></script>
10
+ <script>
11
+ let simpleton = simpleton_client(location.pathname, {
12
+ apply_remote_update: ({ state, patches }) => {
13
+ if (state !== undefined) texty.value = state;
14
+ else apply_patches_and_update_selection(texty, patches);
15
+ return texty.value;
16
+ },
17
+ generate_local_diff_update: (prev_state) => {
18
+ var patches = diff(prev_state, texty.value);
19
+ if (patches.length === 0) return null;
20
+ return { patches, new_state: texty.value };
21
+ },
22
+ });
23
+
24
+ texty.value = "";
25
+ texty.oninput = (e) => simpleton.changed();
26
+
27
+ function diff(before, after) {
28
+ let diff = diff_main(before, after);
29
+ let patches = [];
30
+ let offset = 0;
31
+ for (let d of diff) {
32
+ let p = null;
33
+ if (d[0] == 1) p = { range: [offset, offset], content: d[1] };
34
+ else if (d[0] == -1) {
35
+ p = { range: [offset, offset + d[1].length], content: "" };
36
+ offset += d[1].length;
37
+ } else offset += d[1].length;
38
+ if (p) {
39
+ p.unit = "text";
40
+ patches.push(p);
41
+ }
42
+ }
43
+ return patches;
44
+ }
45
+
46
+ function apply_patches_and_update_selection(textarea, patches) {
47
+ let offset = 0;
48
+ for (let p of patches) {
49
+ p.range[0] += offset;
50
+ p.range[1] += offset;
51
+ offset -= p.range[1] - p.range[0];
52
+ offset += p.content.length;
53
+ }
54
+
55
+ let original = textarea.value;
56
+ let sel = [textarea.selectionStart, textarea.selectionEnd];
57
+
58
+ for (var p of patches) {
59
+ let range = p.range;
60
+
61
+ for (let i = 0; i < sel.length; i++)
62
+ if (sel[i] > range[0])
63
+ if (sel[i] > range[1]) sel[i] -= range[1] - range[0];
64
+ else sel[i] = range[0];
65
+
66
+ for (let i = 0; i < sel.length; i++)
67
+ if (sel[i] > range[0]) sel[i] += p.content.length;
68
+
69
+ original =
70
+ original.substring(0, range[0]) +
71
+ p.content +
72
+ original.substring(range[1]);
73
+ }
74
+
75
+ textarea.value = original;
76
+ textarea.selectionStart = sel[0];
77
+ textarea.selectionEnd = sel[1];
78
+ }
79
+ </script>
package/index.js ADDED
@@ -0,0 +1,459 @@
1
+
2
+ let http = require('http');
3
+
4
+ let { diff_main } = require('./diff.js')
5
+ let braid_text = require("braid-text");
6
+ let braid_fetch = require('braid-http').fetch
7
+
8
+ let port = 10000
9
+ let cookie = null
10
+ let pin_urls = []
11
+ let pindex_urls = []
12
+ let proxy_base = `./proxy_base`
13
+
14
+ let argv = process.argv.slice(2)
15
+ while (argv.length) {
16
+ let a = argv.shift()
17
+ if (a.match(/^\d+$/)) {
18
+ port = parseInt(a)
19
+ } else if (a === '-pin') {
20
+ let b = argv.shift()
21
+ if (b === 'index') {
22
+ pindex_urls.push(argv.shift())
23
+ } else {
24
+ pin_urls.push(b)
25
+ }
26
+ } else {
27
+ cookie = a
28
+ console.log(`cookie = ${cookie}`)
29
+ }
30
+ }
31
+ console.log({ pin_urls, pindex_urls })
32
+
33
+ process.on("unhandledRejection", (x) => console.log(`unhandledRejection: ${x.stack}`))
34
+ process.on("uncaughtException", (x) => console.log(`uncaughtException: ${x.stack}`))
35
+
36
+ const server = http.createServer(async (req, res) => {
37
+ console.log(`${req.method} ${req.url}`);
38
+
39
+ if (req.url === '/favicon.ico') return;
40
+
41
+ // Security check: Allow only localhost access
42
+ const clientIp = req.socket.remoteAddress;
43
+ if (clientIp !== '127.0.0.1' && clientIp !== '::1') {
44
+ res.writeHead(403, { 'Content-Type': 'text/plain' });
45
+ res.end('Access denied: This proxy is only accessible from localhost');
46
+ return;
47
+ }
48
+
49
+ // Free the CORS
50
+ free_the_cors(req, res);
51
+ if (req.method === 'OPTIONS') return;
52
+
53
+ if (req.url.endsWith("?editor")) {
54
+ res.writeHead(200, { "Content-Type": "text/html", "Cache-Control": "no-cache" })
55
+ require("fs").createReadStream("./editor.html").pipe(res)
56
+ return
57
+ }
58
+
59
+ if (req.url === '/pages') {
60
+ var pages = await braid_text.list()
61
+ res.writeHead(200, {
62
+ "Content-Type": "application/json",
63
+ "Access-Control-Expose-Headers": "*"
64
+ })
65
+ res.end(JSON.stringify(pages))
66
+ return
67
+ }
68
+
69
+ let url = req.url.slice(1)
70
+
71
+ proxy_url(url)
72
+
73
+ // Now serve the collaborative text!
74
+ braid_text.serve(req, res, { key: url })
75
+ });
76
+
77
+ server.listen(port, () => {
78
+ console.log(`Proxy server started on port ${port}`);
79
+ console.log('This proxy is only accessible from localhost');
80
+ });
81
+
82
+ for (let url of pin_urls) proxy_url(url)
83
+ pindex_urls.forEach(async url => {
84
+ let prefix = new URL(url).origin
85
+ while (true) {
86
+ let urls = await (await fetch(url)).json()
87
+ for (let url of urls) proxy_url(prefix + url)
88
+ await new Promise(done => setTimeout(done, 1000 * 60 * 60))
89
+ }
90
+ })
91
+
92
+ braid_text.list().then(x => {
93
+ for (let xx of x) proxy_url(xx)
94
+ })
95
+
96
+ ////////////////////////////////
97
+
98
+ async function proxy_url(url) {
99
+ let chain = proxy_url.chain || (proxy_url.chain = Promise.resolve())
100
+
101
+ async function ensure_path(path) {
102
+ // ensure that the path leading to our file exists..
103
+ await (chain = chain.then(async () => {
104
+ try {
105
+ await require("fs").promises.mkdir(path, { recursive: true })
106
+ } catch (e) {
107
+ let parts = path.split(require("path").sep)
108
+ for (let i = 1; i <= parts.length; i++) {
109
+ let partial = require("path").join(...parts.slice(0, i))
110
+
111
+ if (!(await is_dir(partial))) {
112
+ let save = await require("fs").promises.readFile(partial)
113
+
114
+ await require("fs").promises.unlink(partial)
115
+ await require("fs").promises.mkdir(path, { recursive: true })
116
+
117
+ while (await is_dir(partial))
118
+ partial = require("path").join(partial, 'index.html')
119
+
120
+ await require("fs").promises.writeFile(partial, save)
121
+ break
122
+ }
123
+ }
124
+ }
125
+ }))
126
+ }
127
+
128
+ // normalize url by removing any trailing /index.html/index.html/
129
+ let normalized_url = url.replace(/(\/index\.html|\/)+$/, '')
130
+ let wasnt_normal = normalized_url != url
131
+ url = normalized_url
132
+
133
+ if (!proxy_url.cache) proxy_url.cache = {}
134
+ if (proxy_url.cache[url]) return
135
+ proxy_url.cache[url] = true
136
+
137
+ let path = url.replace(/^https?:\/\//, '')
138
+ let fullpath = require("path").join(proxy_base, path)
139
+
140
+ // if we're accessing /blah/index.html, it will be normalized to /blah,
141
+ // but we still want to create a directory out of blah in this case
142
+ if (wasnt_normal && !(await is_dir(fullpath))) ensure_path(fullpath)
143
+
144
+ let last_text = ''
145
+
146
+ console.log(`proxy_url: ${url}`)
147
+
148
+ let peer = Math.random().toString(36).slice(2)
149
+
150
+ braid_fetch_wrapper(url, {
151
+ headers: {
152
+ "Merge-Type": "dt",
153
+ Accept: 'text/plain'
154
+ },
155
+ subscribe: true,
156
+ retry: true,
157
+ parents: async () => {
158
+ let cur = await braid_text.get(url, {})
159
+ if (cur.version.length) return cur.version
160
+ },
161
+ peer
162
+ }).then(x => {
163
+ x.subscribe(update => {
164
+ // console.log(`update: ${JSON.stringify(update, null, 4)}`)
165
+ if (update.version.length == 0) return;
166
+
167
+ braid_text.put(url, { ...update, peer })
168
+ })
169
+ })
170
+
171
+ // try a HEAD without subscribe to get the version
172
+ braid_fetch_wrapper(url, {
173
+ method: 'HEAD',
174
+ headers: { Accept: 'text/plain' },
175
+ retry: true,
176
+ }).then(async head_res => {
177
+ let parents = head_res.headers.get('version') ?
178
+ JSON.parse(`[${head_res.headers.get('version')}]`) :
179
+ null
180
+
181
+ // now get everything since then, and send it back..
182
+ braid_text.get(url, {
183
+ parents,
184
+ merge_type: 'dt',
185
+ peer,
186
+ subscribe: async ({ version, parents, body, patches }) => {
187
+ if (version.length == 0) return;
188
+
189
+ // console.log(`local got: ${JSON.stringify({ version, parents, body, patches }, null, 4)}`)
190
+ // console.log(`cookie = ${cookie}`)
191
+
192
+ await braid_fetch_wrapper(url, {
193
+ headers: {
194
+ "Merge-Type": "dt",
195
+ "Content-Type": 'text/plain',
196
+ ...(cookie ? { "Cookie": cookie } : {}),
197
+ },
198
+ method: "PUT",
199
+ retry: true,
200
+ version, parents, body, patches,
201
+ peer
202
+ })
203
+ },
204
+ })
205
+ })
206
+
207
+ await ensure_path(require("path").dirname(fullpath))
208
+
209
+ async function get_fullpath() {
210
+ let p = fullpath
211
+ while (await is_dir(p)) p = require("path").join(p, 'index.html')
212
+ return p
213
+ }
214
+
215
+ let simpleton = simpleton_client(url, {
216
+ apply_remote_update: async ({ state, patches }) => {
217
+ return await (chain = chain.then(async () => {
218
+ console.log(`writing file ${await get_fullpath()}`)
219
+
220
+ if (state !== undefined) last_text = state
221
+ else last_text = apply_patches(last_text, patches)
222
+ await require('fs').promises.writeFile(await get_fullpath(), last_text)
223
+ return last_text
224
+ }))
225
+ },
226
+ generate_local_diff_update: async (_) => {
227
+ return await (chain = chain.then(async () => {
228
+ let text = await require('fs').promises.readFile(await get_fullpath(), { encoding: 'utf8' })
229
+ var patches = diff(last_text, text)
230
+ last_text = text
231
+ return patches.length ? { patches, new_state: last_text } : null
232
+ }))
233
+ }
234
+ })
235
+
236
+ if (!proxy_url.path_to_func) proxy_url.path_to_func = {}
237
+ proxy_url.path_to_func[path] = () => simpleton.changed()
238
+
239
+ if (!proxy_url.chokidar) {
240
+ proxy_url.chokidar = true
241
+ require('chokidar').watch(proxy_base).on('change', (path) => {
242
+ path = require('path').relative(proxy_base, path)
243
+ console.log(`path changed: ${path}`)
244
+
245
+ path = path.replace(/(\/index\.html|\/)+$/, '')
246
+ console.log(`normalized path: ${path}`)
247
+
248
+ proxy_url.path_to_func[path]()
249
+ });
250
+ }
251
+ }
252
+
253
+ async function is_dir(p) {
254
+ try {
255
+ return (await require("fs").promises.stat(p)).isDirectory()
256
+ } catch (e) { }
257
+ }
258
+
259
+ function diff(before, after) {
260
+ let diff = diff_main(before, after);
261
+ let patches = [];
262
+ let offset = 0;
263
+ for (let d of diff) {
264
+ let p = null;
265
+ if (d[0] == 1) p = { range: [offset, offset], content: d[1] };
266
+ else if (d[0] == -1) {
267
+ p = { range: [offset, offset + d[1].length], content: "" };
268
+ offset += d[1].length;
269
+ } else offset += d[1].length;
270
+ if (p) {
271
+ p.unit = "text";
272
+ patches.push(p);
273
+ }
274
+ }
275
+ return patches;
276
+ }
277
+
278
+ function free_the_cors(req, res) {
279
+ res.setHeader('Range-Request-Allow-Methods', 'PATCH, PUT');
280
+ res.setHeader('Range-Request-Allow-Units', 'json');
281
+ res.setHeader("Patches", "OK");
282
+ var free_the_cors = {
283
+ "Access-Control-Allow-Origin": "*",
284
+ "Access-Control-Allow-Methods": "OPTIONS, HEAD, GET, PUT, UNSUBSCRIBE",
285
+ "Access-Control-Allow-Headers": "subscribe, client, version, parents, merge-type, content-type, content-range, patches, cache-control, peer"
286
+ };
287
+ Object.entries(free_the_cors).forEach(x => res.setHeader(x[0], x[1]));
288
+ if (req.method === 'OPTIONS') {
289
+ res.writeHead(200);
290
+ res.end();
291
+ }
292
+ }
293
+
294
+ function apply_patches(originalString, patches) {
295
+ let offset = 0;
296
+ for (let p of patches) {
297
+ p.range[0] += offset;
298
+ p.range[1] += offset;
299
+ offset -= p.range[1] - p.range[0];
300
+ offset += p.content.length;
301
+ }
302
+
303
+ let result = originalString;
304
+
305
+ for (let p of patches) {
306
+ let range = p.range;
307
+ result =
308
+ result.substring(0, range[0]) +
309
+ p.content +
310
+ result.substring(range[1]);
311
+ }
312
+
313
+ return result;
314
+ }
315
+
316
+ function simpleton_client(url, { apply_remote_update, generate_local_diff_update, content_type }) {
317
+ var peer = Math.random().toString(36).slice(2)
318
+ var current_version = []
319
+ var prev_state = ""
320
+ var char_counter = -1
321
+ var chain = Promise.resolve()
322
+ var queued_changes = 0
323
+
324
+ braid_text.get(url, {
325
+ peer,
326
+ subscribe: (update) => {
327
+ chain = chain.then(async () => {
328
+ // Only accept the update if its parents == our current version
329
+ update.parents.sort()
330
+ if (current_version.length === update.parents.length
331
+ && current_version.every((v, i) => v === update.parents[i])) {
332
+ current_version = update.version.sort()
333
+ update.state = update.body
334
+
335
+ if (update.patches) {
336
+ for (let p of update.patches) p.range = p.range.match(/\d+/g).map((x) => 1 * x)
337
+ update.patches.sort((a, b) => a.range[0] - b.range[0])
338
+
339
+ // convert from code-points to js-indicies
340
+ let c = 0
341
+ let i = 0
342
+ for (let p of update.patches) {
343
+ while (c < p.range[0]) {
344
+ i += get_char_size(prev_state, i)
345
+ c++
346
+ }
347
+ p.range[0] = i
348
+
349
+ while (c < p.range[1]) {
350
+ i += get_char_size(prev_state, i)
351
+ c++
352
+ }
353
+ p.range[1] = i
354
+ }
355
+ }
356
+
357
+ prev_state = await apply_remote_update(update)
358
+ }
359
+ })
360
+ }
361
+ })
362
+
363
+ return {
364
+ changed: () => {
365
+ if (queued_changes) return
366
+ queued_changes++
367
+ chain = chain.then(async () => {
368
+ queued_changes--
369
+ var update = await generate_local_diff_update(prev_state)
370
+ if (!update) return // Stop if there wasn't a change!
371
+ var { patches, new_state } = update
372
+
373
+ // convert from js-indicies to code-points
374
+ let c = 0
375
+ let i = 0
376
+ for (let p of patches) {
377
+ while (i < p.range[0]) {
378
+ i += get_char_size(prev_state, i)
379
+ c++
380
+ }
381
+ p.range[0] = c
382
+
383
+ while (i < p.range[1]) {
384
+ i += get_char_size(prev_state, i)
385
+ c++
386
+ }
387
+ p.range[1] = c
388
+
389
+ char_counter += p.range[1] - p.range[0]
390
+ char_counter += count_code_points(p.content)
391
+
392
+ p.unit = "text"
393
+ p.range = `[${p.range[0]}:${p.range[1]}]`
394
+ }
395
+
396
+ var version = [peer + "-" + char_counter]
397
+
398
+ var parents = current_version
399
+ current_version = version
400
+ prev_state = new_state
401
+
402
+ braid_text.put(url, { version, parents, patches, peer })
403
+ })
404
+ }
405
+ }
406
+ }
407
+
408
+ function get_char_size(s, i) {
409
+ const charCode = s.charCodeAt(i)
410
+ return (charCode >= 0xd800 && charCode <= 0xdbff) ? 2 : 1
411
+ }
412
+
413
+ function count_code_points(str) {
414
+ let code_points = 0
415
+ for (let i = 0; i < str.length; i++) {
416
+ if (str.charCodeAt(i) >= 0xd800 && str.charCodeAt(i) <= 0xdbff) i++
417
+ code_points++
418
+ }
419
+ return code_points
420
+ }
421
+
422
+ async function braid_fetch_wrapper(url, params) {
423
+ if (!params.retry) throw "wtf"
424
+ var waitTime = 10
425
+ if (params.subscribe) {
426
+ var subscribe_handler = null
427
+ connect()
428
+ async function connect() {
429
+ if (params.signal?.aborted) return
430
+ try {
431
+ var c = await braid_fetch(url, { ...params, parents: await params.parents?.() })
432
+ c.subscribe((...args) => subscribe_handler?.(...args), on_error)
433
+ waitTime = 10
434
+ } catch (e) {
435
+ on_error(e)
436
+ }
437
+ }
438
+ function on_error(e) {
439
+ console.log(`eee[url:${url}] = ` + e.stack)
440
+ setTimeout(connect, waitTime)
441
+ waitTime = Math.min(waitTime * 2, 3000)
442
+ }
443
+ return { subscribe: handler => { subscribe_handler = handler } }
444
+ } else {
445
+ return new Promise((done) => {
446
+ send()
447
+ async function send() {
448
+ try {
449
+ var res = await braid_fetch(url, params)
450
+ if (res.status !== 200) throw "status not 200: " + res.status
451
+ done(res)
452
+ } catch (e) {
453
+ setTimeout(send, waitTime)
454
+ waitTime = Math.min(waitTime * 2, 3000)
455
+ }
456
+ }
457
+ })
458
+ }
459
+ }
package/package.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "name": "braidfs",
3
+ "version": "0.0.12",
4
+ "description": "braid technology synchronizing files and webpages",
5
+ "author": "Braid Working Group",
6
+ "repository": "braid-org/braidfs",
7
+ "homepage": "https://braid.org",
8
+ "dependencies": {
9
+ "braid-http": "^0.3.20",
10
+ "braid-text": "^0.0.22",
11
+ "chokidar": "^3.6.0"
12
+ }
13
+ }