-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.mjs
1563 lines (1358 loc) · 64.9 KB
/
index.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Roadroller: Flattens your JS demo
// Copyright (c) 2021 Kang Seonghoon. See LICENSE.txt for details.
import {
jsTokens,
TYPE_WhiteSpace,
TYPE_MultiLineComment,
TYPE_SingleLineComment,
TYPE_LineTerminatorSequence,
TYPE_IdentifierName,
TYPE_StringLiteral,
TYPE_NoSubstitutionTemplate,
TYPE_TemplateHead,
TYPE_TemplateTail,
TYPE_RegularExpressionLiteral,
TYPE_Invalid,
} from './js-tokens.mjs';
import { estimateDeflatedSize } from './deflate.mjs';
import { getContextItemShift, makeDefaultModelRunner } from './wasm.mjs';
//------------------------------------------------------------------------------
// returns clamp(0, floor(log2(x/y)), 31) where x and y are integers.
// not prone to floating point errors.
const floorLog2 = (x, y = 1) => {
let n = 0;
if (x >= y * 65536) y *= 65536, n += 16;
if (x >= y * 256) y *= 256, n += 8;
if (x >= y * 16) y *= 16, n += 4;
if (x >= y * 4) y *= 4, n += 2;
if (x >= y * 2) n += 1;
return n;
};
// returns clamp(1, ceil(log2(x/y)), 32) where x and y are integers.
// not prone to floating point errors.
const ceilLog2 = (x, y = 1) => {
let n = 1;
if (x > y * 65536) y *= 65536, n += 16;
if (x > y * 256) y *= 256, n += 8;
if (x > y * 16) y *= 16, n += 4;
if (x > y * 4) y *= 4, n += 2;
if (x > y * 2) n += 1;
return n;
};
// returns [m, e, m * 10^e] where (m-1) * 10^e < v <= m * 10^e, m < 100 and m mod 10 != 0.
// therefore `${m}e${e}` is an upper bound approximation with ~2 significant digits.
const approximateWithTwoSigDigits = v => {
if (v <= 0) return [0, 0, 0]; // special case
let exp = 0;
let tens = 1;
while (v >= tens * 100) {
++exp;
tens *= 10;
}
let mant = Math.ceil(v / tens);
if (mant % 10 === 0) { // 60e6 -> 6e7
mant /= 10;
++exp;
tens *= 10;
}
return [mant, exp, mant * tens];
};
// Node.js 14 doesn't have a global performance object.
const getPerformanceObject = async () => {
return globalThis.performance || (await import('perf_hooks')).performance;
};
//------------------------------------------------------------------------------
export class ResourcePool {
constructor() {
// arrayBuffers.get(size) is an array of ArrayBuffer of given size
this.arrayBuffers = new Map();
this.wasmRunners = new Map();
}
allocate(parent, size) {
const available = this.arrayBuffers.get(size);
let buf;
if (available) buf = available.pop();
if (!buf) buf = new ArrayBuffer(size);
return buf;
}
// FinalizationRegistry is also possible, but GC couldn't keep up with the memory usage
release(buf) {
let available = this.arrayBuffers.get(buf.byteLength);
if (!available) {
available = [];
this.arrayBuffers.set(buf.byteLength, available);
}
available.push(buf);
}
wasmDefaultModelRunner(contextItemShift) {
if (!this.wasmRunners.get(contextItemShift)) {
this.wasmRunners.set(contextItemShift, makeDefaultModelRunner(contextItemShift));
}
return this.wasmRunners.get(contextItemShift);
}
}
export const ArrayBufferPool = ResourcePool;
const newUintArray = (pool, parent, nbits, length) => {
if (nbits <= 8) return new Uint8Array(pool ? pool.allocate(parent, length) : length);
if (nbits <= 16) return new Uint16Array(pool ? pool.allocate(parent, length * 2) : length);
if (nbits <= 32) return new Uint32Array(pool ? pool.allocate(parent, length * 4) : length);
throw 'newUintArray: nbits is too large';
};
//------------------------------------------------------------------------------
// this is slightly configurable (ryg_rans equivalent would be 31),
// but we already have too many parameters.
const ANS_BITS = 28;
// roughly based on https://github.com/rygorous/ryg_rans/blob/master/rans_byte.h
export class AnsEncoder {
constructor({ outBits, precision }) {
// all input frequencies are assumed to be scaled by 2^precision
this.precision = precision;
// the number of output bits, or -(the number of output symbols) if negative
this.outBits = outBits;
// the bits and corresponding frequencies to be written.
// rANS decoder and encoder works in the reverse.
// therefore we buffer bits and encode them in the reverse,
// so that the decoder will decode bits in the correct order.
this.input = [];
}
writeBit(bit, predictedFreq) {
if (bit !== 0 && bit !== 1) {
throw new Error('AnsEncoder.writeBit: bad bit');
}
if (predictedFreq !== ~~predictedFreq ||
predictedFreq < 0 ||
predictedFreq >= (1 << this.precision)
) {
throw new Error('AnsEncoder.writeBit: bad predictedFreq');
}
if (this.finished) {
throw new Error('AnsEncoder.writeBit: already finished');
}
this.input.push({ bit, predictedFreq });
}
finish() {
if (this.finished) {
throw new Error('AnsEncoder.writeBit: already finished');
}
this.finished = true;
const outSymbols = this.outBits < 0 ? -this.outBits : 1 << this.outBits;
let state = 1 << (ANS_BITS - ceilLog2(outSymbols));
const buf = [];
const probScale = this.precision + 1;
const stateShift = ANS_BITS - ceilLog2(outSymbols) - probScale;
for (const { bit, predictedFreq } of this.input.reverse()) {
// example: if precision=2, freq={0, 1, 2, 3} map to prob={1/8, 3/8, 5/8, 7/8}.
// this adjustment is used to avoid the probability of exactly 0 or 1.
const prob = (predictedFreq << 1) | 1;
let start, size;
if (bit) {
start = 0;
size = prob;
} else {
start = prob;
size = (1 << probScale) - prob;
}
// renormalize
const maxState = size * outSymbols << stateShift;
while (state >= maxState) {
buf.push(state % outSymbols);
state = (state / outSymbols) | 0;
}
// add the bit to the state
state = ((state / size | 0) << probScale) + state % size + start;
if (state >= 0x80000000) {
throw new Error('ANSEncoder.finish: state overflow');
}
}
buf.reverse();
return { state, buf };
}
}
export class AnsDecoder {
constructor({ state, buf }, { outBits, precision }) {
this.state = state;
this.buf = buf;
this.offset = 0;
this.precision = precision;
this.outSymbols = outBits < 0 ? -outBits : 1 << outBits;
this.renormLimit = 1 << (ANS_BITS - ceilLog2(this.outSymbols));
}
readBit(predictedFreq) {
const prob = (predictedFreq << 1) | 1;
const probScale = this.precision + 1;
const rem = this.state & ((1 << probScale) - 1);
const bit = rem < prob ? 1 : 0;
let start, size;
if (bit) {
start = 0;
size = prob;
} else {
start = prob;
size = (1 << probScale) - prob;
}
this.state = size * (this.state >> probScale) + rem - start;
// renormalize
while (this.state < this.renormLimit) {
if (this.offset >= this.buf.length) {
throw new Error('AnsDecoder.readBit: out of buffer bounds');
}
this.state *= this.outSymbols;
this.state += this.buf[this.offset++] % this.outSymbols;
}
return bit;
}
}
//------------------------------------------------------------------------------
export class DirectContextModel {
constructor({ inBits, contextBits, precision, modelMaxCount, modelRecipBaseCount, arrayBufferPool, resourcePool }) {
this.inBits = inBits;
this.contextBits = contextBits;
this.precision = precision;
this.modelMaxCount = modelMaxCount;
this.modelBaseCount = 1 / modelRecipBaseCount;
this.resourcePool = resourcePool || arrayBufferPool;
this.predictions = newUintArray(this.resourcePool, this, precision, 1 << contextBits);
this.counts = newUintArray(this.resourcePool, this, ceilLog2(modelMaxCount + 1), 1 << contextBits);
if (this.resourcePool) {
// we need to initialize the array since it may have been already used,
// but UintXXArray.fill is comparatively slow, less than 5 GB/s even in fastest browsers.
// we instead use more memory to confirm that each bit of context has been initialized.
//
// the final excess element is the maximum mark in use.
// (this kind of size is not used elsewhere, so we can safely reuse that.)
// we choose a new mark to mark initialized elements *in this instance*.
// if the mark reaches 255 we reset the entire array and start over.
// this scheme effectively reduces the number of fill calls by a factor of 510.
this.confirmations = newUintArray(this.resourcePool, this, 8, (1 << contextBits) + 1);
this.mark = this.confirmations[1 << contextBits] + 1;
if (this.mark === 256) {
this.mark = 1;
this.confirmations.fill(0);
}
this.confirmations[1 << contextBits] = this.mark;
} else {
this.predictions.fill(1 << (precision - 1));
//this.counts.fill(0); // we don't really need this
}
this.bitContext = 1;
}
predict(context = 0) {
context = (context + this.bitContext) & ((1 << this.contextBits) - 1);
if (this.confirmations && this.confirmations[context] !== this.mark) {
this.confirmations[context] = this.mark;
this.predictions[context] = 1 << (this.precision - 1);
this.counts[context] = 0;
}
return this.predictions[context];
}
update(actualBit, context = 0) {
if (actualBit !== 0 && actualBit !== 1) {
throw new Error('DirectContextModel.update: bad actualBit');
}
context = (context + this.bitContext) & ((1 << this.contextBits) - 1);
if (this.counts[context] < this.modelMaxCount) {
++this.counts[context];
}
// adjust P = predictions[context] by (actual - P) / (counts[context] + 1 / modelRecipBaseCount).
// modelRecipBaseCount should be <= M such that 1 / modelRecipBaseCount isn't cancelled out.
//
// claim:
// 1. the entire calculation always stays in the 32-bit signed integer.
// 2. P always stays in the [0, 2^precision) range.
//
// proof:
// assume that 0 <= P < 2^precision and P is an integer.
// counts[context] is already updated so counts[context] >= 1.
//
// if delta > 0, delta = (2^precision - P) * 2^(29-precision) < 2^29.
// then P' = P + trunc(delta / (counts[context] + 1 / modelRecipBaseCount)) / 2^(29-precision)
// <= P + delta / (1 + 1/M) / 2^(29-precision)
// = P + (2^precision - P) * 2^(29-precision) / 2^(29-precision) / (1 + 1/M)
// = P (1 + 1/M) / (1 + 1/M) + 2^precision / (1 + 1/M) - P / (1 + 1/M)
// = (2^precision - P/M) / (1 + 1/M)
// < 2^precision - P/M
// <= 2^precision.
// therefore P' < 2^precision.
//
// if delta < 0, delta = -P * 2^(29-precision) > -2^29.
// then P' = P + trunc(delta / (counts[context] + 1 / modelRecipBaseCount)) / 2^(29-precision)
// >= P + delta / (1 + 1/1) / 2^(29-precision)
// = P + (-P) / 2
// = P/2
// >= 0.
// therefore P' >= 0.
const delta = ((actualBit << this.precision) - this.predictions[context]) << (29 - this.precision);
this.predictions[context] += (delta / (this.counts[context] + this.modelBaseCount) | 0) >> (29 - this.precision);
this.bitContext = (this.bitContext << 1) | actualBit;
}
flushByte() {
this.bitContext = 1;
}
release() {
if (this.resourcePool) {
if (this.predictions) this.resourcePool.release(this.predictions.buffer);
if (this.counts) this.resourcePool.release(this.counts.buffer);
if (this.confirmations) this.resourcePool.release(this.confirmations.buffer);
this.predictions = null;
this.counts = null;
this.confirmations = null;
}
}
}
export class SparseContextModel extends DirectContextModel {
constructor(options) {
super(options);
this.selector = options.sparseSelector;
this.recentBytes = [];
for (let i = 0; (this.selector >> i) > 0; ++i) {
this.recentBytes.push(0);
}
this.sparseContext = 0;
}
predict(context = 0) {
return super.predict(this.sparseContext + context);
}
update(actualBit, context = 0) {
super.update(actualBit, this.sparseContext + context);
}
flushByte(currentByte, inBits) {
super.flushByte(currentByte, inBits);
this.recentBytes.unshift(currentByte);
this.recentBytes.pop();
let context = 0;
for (let i = this.recentBytes.length - 1; i >= 0; --i) {
if (this.selector >> i & 1) {
// this can result in negative numbers, which should be "fixed" by later bit masking
context = (context + this.recentBytes[i]) * 997 | 0;
}
}
this.sparseContext = context;
}
}
export class LogisticMixModel {
constructor(models, { recipLearningRate, precision }) {
this.models = models;
this.precision = precision;
this.recipLearningRate = recipLearningRate;
this.mixedProb = 0;
this.stretchedProbs = [];
this.weights = [];
for (let i = 0; i < models.length; ++i) {
this.stretchedProbs.push(0);
this.weights.push(0);
}
}
predict(context = 0) {
let total = 0;
for (let i = 0; i < this.models.length; ++i) {
const weight = this.weights[i];
const prob = this.models[i].predict(context) * 2 + 1;
const stretchedProb = Math.log(prob / ((2 << this.precision) - prob));
this.stretchedProbs[i] = stretchedProb;
total += weight * stretchedProb;
}
// since CM is the last model and predictions are not stored,
// we can just compute the external probability directly.
const mixedProb = ((2 << this.precision) - 1) / (1 + Math.exp(-total));
this.mixedProb = mixedProb | 1;
// this adjustment can be combined and elided in the optimized decompressor
return this.mixedProb >> 1;
}
update(actualBit, context = 0) {
const mixedProb = this.mixedProb / (2 << this.precision);
for (let i = 0; i < this.models.length; ++i) {
this.models[i].update(actualBit, context);
let prob = this.stretchedProbs[i];
prob = prob / this.recipLearningRate;
this.weights[i] += prob * (actualBit - mixedProb);
}
}
flushByte(currentByte, inBits) {
for (const model of this.models) {
model.flushByte(currentByte, inBits);
}
}
release() {
for (const model of this.models) {
if (model.release) model.release();
}
}
}
//------------------------------------------------------------------------------
export class DefaultModel extends LogisticMixModel {
constructor(options) {
const { inBits, sparseSelectors, modelQuotes } = options;
const models = sparseSelectors.map(sparseSelector => {
return new SparseContextModel({ ...options, sparseSelector });
});
super(models, options);
this.modelQuotes = modelQuotes;
this.quote = 0;
this.quotesSeen = new Set();
}
predict(context = 0) {
if (this.quote > 0) context += 129;
return super.predict(context);
}
update(actualBit, context = 0) {
if (this.quote > 0) context += 129;
super.update(actualBit, context);
}
flushByte(currentByte, inBits) {
super.flushByte(currentByte, inBits);
if (this.modelQuotes) {
if (this.quote && this.quote === currentByte) {
this.quote = 0;
} else if (!this.quote && [34, 39, 96].includes(currentByte)) {
this.quote = currentByte;
this.quotesSeen.add(currentByte);
}
}
}
}
//------------------------------------------------------------------------------
export const compressWithModel = (input, model, options) => {
const { inBits, outBits, precision, preset = [], inputEndsWithByte, calculateByteEntropy } = options;
const encoder = new AnsEncoder(options);
if (inputEndsWithByte !== undefined) {
if (input.length === 0) {
throw new Error('compressWithModel: inputEndsWithByte given but input is empty');
}
if (input[input.length - 1] !== inputEndsWithByte) {
throw new Error('compressWithModel: input does not agree with inputEndsWithByte');
}
for (let offset = 0; offset < input.length - 1; ++offset) {
if (input[offset] === inputEndsWithByte) {
throw new Error('compressWithModel: input contains multiple inputEndsWithByte');
}
}
}
for (let offset = 0; offset < preset.length; ++offset) {
const code = preset[offset];
for (let i = inBits - 1; i >= 0; --i) {
model.predict();
model.update((code >> i) & 1);
}
model.flushByte(code, inBits);
}
const byteProbs = [];
for (let offset = 0; offset < input.length; ++offset) {
const code = input[offset];
let byteProb = calculateByteEntropy ? 1 : 0;
for (let i = inBits - 1; i >= 0; --i) {
const bit = (code >> i) & 1;
const prob = model.predict();
if (byteProb) {
byteProb *= (bit ? prob : (1 << precision) - prob) * 2 + 1;
}
encoder.writeBit(bit, prob);
model.update(bit);
}
model.flushByte(code, inBits);
if (calculateByteEntropy) {
byteProbs.push(byteProb);
}
}
if (model.release) model.release();
const { state, buf } = encoder.finish();
let byteEntropy;
if (calculateByteEntropy) {
byteEntropy = byteProbs.map(prob => (precision + 1) * inBits - Math.log2(prob));
}
const bufLengthInBytes = Math.ceil(buf.length * (outBits < 0 ? Math.log2(-outBits) : outBits) / 8);
const inputLength = inputEndsWithByte === undefined ? input.length : -1; // so that the caller can't rely on this
return { state, buf, inputLength, bufLengthInBytes, byteEntropy };
};
export const compressWithDefaultModel = (input, options) => {
// if the model is _exactly_ a DefaultModel and no fancy options are in use,
// we have a faster implementation using JIT-compiled WebAssembly instances.
// we only use it when we have a guarantee that the wasm instance can be cached.
let runDefaultModel;
const resourcePool = options.resourcePool || options.arrayBufferPool;
if (
resourcePool &&
(options.preset || []).length === 0 &&
!options.disableWasm &&
!options.calculateByteEntropy &&
options.sparseSelectors.length <= 64 &&
options.sparseSelectors.every(sel => sel < 0x8000)
) {
const contextItemShift = getContextItemShift(options);
const resourcePool = options.resourcePool || options.arrayBufferPool;
try {
runDefaultModel = resourcePool.wasmDefaultModelRunner(contextItemShift);
} catch (e) {
// WebAssembly is probably not supported, fall back to the pure JS impl
}
}
if (runDefaultModel) {
const { predictions, quotesSeen } = runDefaultModel(input, options);
const { inBits, outBits } = options;
const encoder = new AnsEncoder(options);
for (let offset = 0, bitOffset = 0; offset < input.length; ++offset) {
const code = input[offset];
for (let i = inBits - 1; i >= 0; --i) {
const bit = (code >> i) & 1;
const prob = predictions[bitOffset++];
encoder.writeBit(bit, prob);
}
}
const { state, buf } = encoder.finish();
const bufLengthInBytes = Math.ceil(buf.length * (outBits < 0 ? Math.log2(-outBits) : outBits) / 8);
const inputLength = input.length;
return { state, buf, inputLength, bufLengthInBytes, quotesSeen };
} else {
const model = new DefaultModel(options);
const ret = compressWithModel(input, model, options);
ret.quotesSeen = model.quotesSeen;
return ret;
}
};
export const decompressWithModel = ({ state, buf, inputLength }, model, options) => {
const { inBits, preset = [], inputEndsWithByte } = options;
const decoder = new AnsDecoder({ state, buf }, options);
for (let offset = 0; offset < preset.length; ++offset) {
const code = preset[offset];
for (let i = inBits - 1; i >= 0; --i) {
model.predict();
model.update((code >> i) & 1);
}
model.flushByte(code, inBits);
}
const reconstructed = [];
if (inputEndsWithByte !== undefined) {
let current;
do {
current = 0;
for (let i = inBits - 1; i >= 0; --i) {
const prob = model.predict();
const actualBit = decoder.readBit(prob);
current = (current << 1) | actualBit;
model.update(actualBit);
}
model.flushByte(current, inBits);
reconstructed.push(current);
} while (current !== inputEndsWithByte);
} else {
for (let offset = 0; offset < inputLength; ++offset) {
let current = 0;
for (let i = inBits - 1; i >= 0; --i) {
const prob = model.predict();
const actualBit = decoder.readBit(prob);
current = (current << 1) | actualBit;
model.update(actualBit);
}
model.flushByte(current, inBits);
reconstructed.push(current);
}
}
if (model.release) model.release();
return reconstructed;
};
//------------------------------------------------------------------------------
// we do not automatically search beyond 9th order for the simpler decoder code
const AUTO_SELECTOR_LIMIT = 512;
export const defaultSparseSelectors = (numContexts = 12) => {
numContexts = Math.max(0, Math.min(64, numContexts));
// this was determined from running a simple search against samples,
// where selectors are limited to 0..63 for more thorough search.
// these were most frequent sparse orders and should be a good baseline.
const selectors = [0, 1, 2, 3, 6, 7, 13, 21, 25, 42, 50, 57].slice(0, numContexts);
// if more contexts are desired we just add random selectors.
while (selectors.length < numContexts) {
const added = Math.random() * AUTO_SELECTOR_LIMIT | 0;
if (!selectors.includes(added)) selectors.push(added);
}
return selectors.sort((a, b) => a - b);
};
//------------------------------------------------------------------------------
const predictionBytesPerContext = options => (options.precision <= 8 ? 1 : options.precision <= 16 ? 2 : 4);
const countBytesPerContext = options => (options.modelMaxCount < 128 ? 1 : options.modelMaxCount < 32768 ? 2 : 4);
const contextBitsFromMaxMemory = options => {
const bytesPerContext = predictionBytesPerContext(options) + countBytesPerContext(options);
let contextBits = floorLog2(options.maxMemoryMB * 1048576, options.sparseSelectors.length * bytesPerContext);
// the decoder slightly overallocates the memory (~1%) so a naive calculation can exceed the memory limit;
// recalculate the actual memory usage and decrease contextBits in that case.
const [, , actualNumContexts] = approximateWithTwoSigDigits(options.sparseSelectors.length << contextBits);
if (actualNumContexts * bytesPerContext > options.maxMemoryMB * 1048576) --contextBits;
return contextBits;
};
// String.fromCharCode(...array) is short but doesn't work when array.length is "long enough".
// the threshold is implementation-defined, but 2^16 - epsilon seems common.
const TEXT_DECODER_THRESHOLD = 65000;
const DYN_MODEL_QUOTES = 1;
export class Packer {
constructor(inputs, options = {}) {
this.options = {
sparseSelectors: options.sparseSelectors ? options.sparseSelectors.slice() : defaultSparseSelectors(),
maxMemoryMB: options.maxMemoryMB || 150,
precision: options.precision || 16,
modelMaxCount: options.modelMaxCount || 5,
modelRecipBaseCount: options.modelRecipBaseCount || 20,
recipLearningRate: options.recipLearningRate || Math.max(1, 500),
contextBits: options.contextBits,
resourcePool: options.resourcePool || options.arrayBufferPool || new ResourcePool(),
numAbbreviations: typeof options.numAbbreviations === 'number' ? options.numAbbreviations : 64,
dynamicModels: options.dynamicModels,
allowFreeVars: options.allowFreeVars,
disableWasm: options.disableWasm,
};
this.inputsByType = {};
this.evalInput = null;
for (let i = 0; i < inputs.length; ++i) {
const { data, type, action } = inputs[i];
const input = { data, type, action };
if (!['js', 'glsl', 'html', 'text', 'binary'].includes(type)) {
throw new Error('Packer: unknown input type');
}
if (!['eval', 'json', 'string', 'write', 'console', 'return', 'array', 'u8array', 'base64'].includes(action)) {
throw new Error('Packer: unknown input action');
}
if (typeof data === 'string' && type === 'binary') {
throw new Error('Packer: binary input should have an array-like data');
}
if (typeof data !== 'string' && type !== 'binary') {
throw new Error('Packer: non-binary input should have a string data');
}
if (!['js', 'text'].includes(type) && ['eval', 'json'].includes(action)) {
throw new Error('Packer: eval or json actions can be used only with js inputs');
}
if (type === 'binary' && ['string', 'write', 'console'].includes(action)) {
throw new Error('Packer: binary inputs cannot use string or write action');
}
this.inputsByType[type] = this.inputsByType[type] || [];
this.inputsByType[type].push(input);
if (action === 'eval') {
if (this.evalInput) {
throw new Error('Packer: there can be at most one input with eval action');
}
this.evalInput = input;
}
}
// TODO
if (inputs.length !== 1 || !['js', 'text'].includes(inputs[0].type) || !['eval', 'write', 'console', 'return'].includes(inputs[0].action)) {
throw new Error('Packer: this version of Roadroller supports exactly one JS or text input, please stay tuned for more!');
}
if (this.options.dynamicModels === undefined) {
this.options.dynamicModels = inputs[0].type === 'js' ? DYN_MODEL_QUOTES : 0;
}
}
get memoryUsageMB() {
const contextBits = this.options.contextBits || contextBitsFromMaxMemory(this.options);
const [, , numContexts] = approximateWithTwoSigDigits(this.options.sparseSelectors.length << contextBits);
const bytesPerContext = predictionBytesPerContext(this.options) + countBytesPerContext(this.options);
return numContexts * bytesPerContext / 1048576;
}
static prepareText(inputs) {
let text = inputs.map(input => input.data).join('');
if (text.length >= TEXT_DECODER_THRESHOLD || text.match(/[\u0100-\uffff]/)) {
return { utf8: true, text: unescape(encodeURIComponent(text)) };
} else {
return { utf8: false, text };
}
}
static prepareJs(inputs, { dynamicModels, numAbbreviations }) {
const modelQuotes = dynamicModels & DYN_MODEL_QUOTES;
// we strongly avoid a token like 'this\'one' because the context model doesn't
// know about escapes and anything after that would be suboptimally compressed.
// we can't still avoid something like `foo${`bar`}quux`, where `bar` would be
// suboptimally compressed, but at least we will return to the normal state at the end.
const reescape = (s, pattern) => {
if (modelQuotes) {
return s.replace(
new RegExp(`\\\\?(${pattern})|\\\\.`, 'g'),
(m, q) => q ? '\\x' + q.charCodeAt(0).toString(16).padStart(2, '0') : m);
} else {
return s;
}
};
const identFreqs = new Map();
const inputTokens = [];
for (const input of inputs) {
const tokens = [];
for (const token of jsTokens(input.data)) {
if (token.closed === false) {
throw new Error('Packer: invalid JS code in the input');
}
switch (token.type) {
case TYPE_WhiteSpace:
case TYPE_MultiLineComment:
case TYPE_SingleLineComment:
continue;
case TYPE_LineTerminatorSequence:
if ((tokens[tokens.length - 1] || {}).type === TYPE_LineTerminatorSequence) continue;
token.value = '\n'; // normalize to the same terminator
break;
case TYPE_IdentifierName:
if (token.value.length > 1) {
identFreqs.set(token.value, (identFreqs.get(token.value) || 0) + 1);
}
break;
case TYPE_StringLiteral:
case TYPE_NoSubstitutionTemplate:
token.value = token.value[0] + reescape(token.value.slice(1, -1), token.value[0]) + token.value[0];
break;
case TYPE_TemplateHead:
token.value = '`' + reescape(token.value.slice(1), '`');
break;
case TYPE_TemplateTail:
token.value = reescape(token.value.slice(0, -1), '`') + '`';
break;
case TYPE_RegularExpressionLiteral:
token.value = reescape(token.value, '[\'"`]');
break;
case TYPE_Invalid:
throw new Error('Packer: invalid JS code in the input');
}
token.value = token.value
// \n, \r, \r\n all reads as \n in JS, so there is no reason not to normalize them
.replace(/\r\n?/g, '\n')
// identifiers in addition to string literals can be escaped in JS code.
// those characters can't appear anywhere else, so this doesn't alter the validity.
.replace(/[^\n\x20-\x7f]/g, m => '\\u' + m.charCodeAt(0).toString(16).padStart(4, '0'));
tokens.push(token);
}
if ((tokens[tokens.length - 1] || {}).type === TYPE_LineTerminatorSequence) tokens.pop();
inputTokens.push(tokens);
}
const unseenChars = new Set();
for (let i = 0; i < 128; ++i) {
// even though there might be no whitespace in the tokens,
// we may have to need some space between two namelike tokens later.
if (i !== 32 && !(modelQuotes && [34, 39, 96].includes(i))) unseenChars.add(String.fromCharCode(i));
}
for (const tokens of inputTokens) {
for (const token of tokens) {
for (const ch of token.value) unseenChars.delete(ch);
}
}
const usableChars = [...unseenChars].sort();
// replace "common" enough identifiers & reserved words with unused characters.
//
// "commonness" is determined by a heuristic score and not by an output length,
// since the compressor does perform a sort of deduplication via its context modelling
// and it's hard to calculate the actual compressed size beforehand.
// therefore this should be rather thought as reducing the burden of context models.
// (this is also why the full deduplication actually performs worse than no deduplication.)
let commonIdents = [...identFreqs.entries()]
.map(([ident, freq]) => [ident, ident.length * (freq - 1)])
.filter(([, score]) => score > 0)
.sort(([, a], [, b]) => b - a)
.slice(0, usableChars.length)
.map(([ident], i) => [ident, usableChars[i]]);
const maxAbbreviations = commonIdents.length;
commonIdents = commonIdents.slice(0, numAbbreviations);
const identAbbrs = new Map(commonIdents);
// construct the combined code with abbreviations replaced, inserting a whitespace as needed
let output = '';
let prevToken;
const NEED_SPACE_BEFORE = 1, NEED_SPACE_AFTER = 2;
const needSpace = {};
let consecutiveAbbrs = new Set(); // a set of two abbreviated chars appearing in a row
for (const tokens of inputTokens) {
for (const token of tokens) {
/*
if (token.value.match(/\$ROADROLLER.*\$/)) {
// $ROADROLLERnn$ gets replaced with the input nn
}
*/
if (token.type === TYPE_IdentifierName) {
token.abbr = identAbbrs.get(token.value);
}
// insert a space if needed
if (prevToken && (
// - `ident1 ident2` vs. `ident1ident2`
// - `ident1 234` vs. `ident1234` (but e.g. `case.123` is okay)
(prevToken.type === TYPE_IdentifierName && token.value.match(/^[\w$\\]/)) ||
// - `a / /.../` vs. `a //.../`
// - `/.../ in b` vs. `/.../in b`; also applies to other names or number literals
// starting with digits, but only `in` and `instanceof` are possible in the valid JS.
// - `a + + b` vs. `a ++ b`
// - `a - - b` vs. `a -- b`
// - short HTML comments only recognized in web browsers:
// - `a < ! --b` vs. `a <!--b`
// - `a-- > b` vs. `a-->b`
(prevToken.value + ' ' + token.value).match(/^\/ \/|\/ in(?:stanceof)?$|^(?:\+ \+|- -|! --|-- >)$/)
)) {
if (prevToken.abbr) {
if (token.abbr) {
// either one of prevToken or token should have a space in the abbreviation;
// we resolve which one to put a space later
consecutiveAbbrs.add(prevToken.abbr + token.abbr);
} else {
needSpace[prevToken.abbr] |= NEED_SPACE_AFTER;
}
} else if (token.abbr) {
needSpace[token.abbr] |= NEED_SPACE_BEFORE;
} else {
output += ' ';
}
}
output += token.abbr || token.value;
prevToken = token;
}
}
// resolve consecutive abbrs, by putting the minimal number of additional spaces to them.
// this is actually a hard problem, corresponding to finding 2-coloring of given bipartite graph
// with the biggest difference in partition sizes, which is a set cover problem in disguise.
// we use a greedy approximation algorithm that chooses the abbr with the most covering every time.
while (true) {
consecutiveAbbrs = new Set([...consecutiveAbbrs].filter(abbrs => {
return !(needSpace[abbrs[0]] & NEED_SPACE_AFTER) && !(needSpace[abbrs[1]] & NEED_SPACE_BEFORE);
}));
if (consecutiveAbbrs.size === 0) break;
const covers = new Map();
for (const abbrs of consecutiveAbbrs) {
const left = (abbrs.charCodeAt(0) << 1);
const right = (abbrs.charCodeAt(1) << 1) | 1;
covers.set(left, (covers.get(left) || 0) + 1);
covers.set(right, (covers.get(right) || 0) + 1);
}
const [[best]] = [...covers.entries()].sort(([a,na], [b,nb]) => (nb - na) || (a - b));
needSpace[String.fromCharCode(best >> 1)] |= best & 1 ? NEED_SPACE_BEFORE : NEED_SPACE_AFTER;
}
let replacements = '';
for (const [ident, abbr] of commonIdents) {
if (needSpace[abbr] & NEED_SPACE_BEFORE) replacements += ' ';
replacements += ident;
if (needSpace[abbr] & NEED_SPACE_AFTER) replacements += ' ';
replacements += abbr;
}
return { abbrs: commonIdents, code: replacements + output, maxAbbreviations };
}
static doPack(preparedText, preparedJs, mainInputAction, options) {
// TODO if we are to have multiple inputs they have to be splitted
const combinedInput = [...preparedText.text, ...preparedJs.code].map(c => c.charCodeAt(0));
const inBits = combinedInput.every(c => c <= 0x7f) ? 7 : 8;
const outBits = 6;
// TODO again, this should be controlled dynamically
const modelQuotes = !!(options.dynamicModels & DYN_MODEL_QUOTES);
const {
sparseSelectors, precision, modelMaxCount, modelRecipBaseCount,
recipLearningRate, allowFreeVars,
} = options;
const contextBits = options.contextBits || contextBitsFromMaxMemory(options);
const compressOptions = { ...options, inBits, outBits, modelQuotes, contextBits };
const { buf, state, inputLength, bufLengthInBytes, quotesSeen } = compressWithDefaultModel(combinedInput, compressOptions);
const numModels = sparseSelectors.length;
const predictionBits = 8 * predictionBytesPerContext(compressOptions);
const countBits = 8 * countBytesPerContext(compressOptions);
const selectors = [];
for (const selector of sparseSelectors) {
const bits = [];
for (let j = 0; (1 << j) <= selector; ++j) {
if (selector >> j & 1) bits.push(j + 1);
}
selectors.push(bits.reverse());
}
const singleDigitSelectors = sparseSelectors.every(sel => sel < 512);
const quotes = [...quotesSeen].sort((a, b) => a - b);
// 2+ decimal points doesn't seem to make any difference after DEFLATE
const modelBaseCount = { 1: '1', 2: '.5', 5: '.2', 10: '.1' }[modelRecipBaseCount] || `1/${modelRecipBaseCount}`;
// JS allows \0 but <script> replace it with U+FFFE,
// so we are fine to use it with eval but not outside.
const charEscapesInTemplate = {
// <script> replaces \0 with U+FFFE, so it has to be escaped.
// but JS itself allows \0 so we don't need additional escapes for eval.
'\0': '\\0',
// any \r in template literals is replaced with \n.
'\r': options.allowFreeVars ? '\\r' : '\\\\r',
'\\': options.allowFreeVars ? '\\\\' : '\\\\\\\\',
'`': options.allowFreeVars ? '\\`' : '\\\\`',