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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
//! WebAssembly bindings for ELID
//!
//! This module provides JavaScript-friendly bindings for all ELID functions.
//! These bindings work in browsers, Node.js, Deno, and Bun.
use ;
use *;
// Conditional imports for embeddings feature
use crate;
/// Compute the Levenshtein distance between two strings.
///
/// Returns the minimum number of single-character edits needed to transform one string into another.
///
/// # JavaScript Example
///
/// ```javascript
/// import { levenshtein } from 'elid';
///
/// const distance = levenshtein("kitten", "sitting");
/// console.log(distance); // 3
/// ```
/// Compute the normalized Levenshtein similarity between two strings.
///
/// Returns a value between 0.0 (completely different) and 1.0 (identical).
///
/// # JavaScript Example
///
/// ```javascript
/// import { normalizedLevenshtein } from 'elid';
///
/// const similarity = normalizedLevenshtein("hello", "hallo");
/// console.log(similarity); // ~0.8
/// ```
/// Compute the Jaro similarity between two strings.
///
/// Returns a value between 0.0 (completely different) and 1.0 (identical).
/// Particularly effective for short strings like names.
///
/// # JavaScript Example
///
/// ```javascript
/// import { jaro } from 'elid';
///
/// const similarity = jaro("martha", "marhta");
/// console.log(similarity); // ~0.944
/// ```
/// Compute the Jaro-Winkler similarity between two strings.
///
/// Returns a value between 0.0 (completely different) and 1.0 (identical).
/// Gives more favorable ratings to strings with common prefixes.
///
/// # JavaScript Example
///
/// ```javascript
/// import { jaroWinkler } from 'elid';
///
/// const similarity = jaroWinkler("martha", "marhta");
/// console.log(similarity); // ~0.961
/// ```
/// Compute the Hamming distance between two strings.
///
/// Returns the number of positions at which the characters differ.
/// Returns null if strings have different lengths.
///
/// # JavaScript Example
///
/// ```javascript
/// import { hamming } from 'elid';
///
/// const distance = hamming("karolin", "kathrin");
/// console.log(distance); // 3
///
/// const invalid = hamming("hello", "world!");
/// console.log(invalid); // null
/// ```
/// Compute the OSA (Optimal String Alignment) distance between two strings.
///
/// Similar to Levenshtein but also considers transpositions as a single operation.
///
/// # JavaScript Example
///
/// ```javascript
/// import { osaDistance } from 'elid';
///
/// const distance = osaDistance("ca", "ac");
/// console.log(distance); // 1 (transposition)
/// ```
/// Compute the best matching similarity between two strings.
///
/// Runs multiple algorithms and returns the highest score.
///
/// # JavaScript Example
///
/// ```javascript
/// import { bestMatch } from 'elid';
///
/// const score = bestMatch("hello", "hallo");
/// console.log(score); // ~0.8
/// ```
/// Find the best match for a query string in an array of candidates.
///
/// Returns an object with the index and similarity score of the best match.
///
/// # JavaScript Example
///
/// ```javascript
/// import { findBestMatch } from 'elid';
///
/// const candidates = ["apple", "application", "apply"];
/// const result = findBestMatch("app", candidates);
/// console.log(result); // { index: 0, score: 0.907 }
/// ```
/// Find all matches above a threshold score.
///
/// Returns an array of objects with index and score for all candidates above the threshold.
///
/// # JavaScript Example
///
/// ```javascript
/// import { findMatchesAboveThreshold } from 'elid';
///
/// const candidates = ["apple", "application", "apply", "banana"];
/// const matches = findMatchesAboveThreshold("app", candidates, 0.5);
/// console.log(matches); // [{ index: 0, score: 0.907 }, { index: 1, score: 0.830 }, ...]
/// ```
/// Options for configuring string similarity algorithms
/// Compute Levenshtein distance with custom options.
///
/// # JavaScript Example
///
/// ```javascript
/// import { levenshteinWithOpts, SimilarityOptions } from 'elid';
///
/// const opts = new SimilarityOptions();
/// opts.setCaseSensitive(false);
/// opts.setTrimWhitespace(true);
///
/// const distance = levenshteinWithOpts(" HELLO ", "hello", opts);
/// console.log(distance); // 0
/// ```
/// Compute the SimHash fingerprint of a string.
///
/// Returns a 64-bit hash where similar strings produce similar numbers.
/// Use this for database queries by storing the hash and querying by numeric range.
///
/// # JavaScript Example
///
/// ```javascript
/// import { simhash } from 'elid';
///
/// const hash1 = simhash("iPhone 14");
/// const hash2 = simhash("iPhone 15");
/// const hash3 = simhash("Galaxy S23");
///
/// // hash1 and hash2 will be numerically close
/// // hash3 will be numerically distant
///
/// // Store in database as bigint:
/// // { name: "iPhone 14", simhash: hash1 }
/// ```
/// Compute the Hamming distance between two SimHash values.
///
/// Returns the number of differing bits. Lower values = higher similarity.
///
/// # JavaScript Example
///
/// ```javascript
/// import { simhash, simhashDistance } from 'elid';
///
/// const hash1 = simhash("iPhone 14");
/// const hash2 = simhash("iPhone 15");
/// const distance = simhashDistance(hash1, hash2);
///
/// console.log(distance); // Low number = similar
/// ```
/// Compute the normalized SimHash similarity between two strings.
///
/// Returns a value between 0.0 (completely different) and 1.0 (identical).
///
/// # JavaScript Example
///
/// ```javascript
/// import { simhashSimilarity } from 'elid';
///
/// const similarity = simhashSimilarity("iPhone 14", "iPhone 15");
/// console.log(similarity); // ~0.9 (very similar)
///
/// const similarity2 = simhashSimilarity("iPhone", "Galaxy");
/// console.log(similarity2); // ~0.4 (different)
/// ```
/// Find all hashes within a given distance threshold.
///
/// Useful for database queries - pre-compute hashes, then find similar ones.
///
/// # JavaScript Example
///
/// ```javascript
/// import { simhash, findSimilarHashes } from 'elid';
///
/// const candidates = ["iPhone 14 Pro", "iPhone 13", "Galaxy S23"];
/// const hashes = candidates.map(s => simhash(s));
///
/// const queryHash = simhash("iPhone 14");
/// const matches = findSimilarHashes(queryHash, hashes, 10);
///
/// console.log(matches); // [0, 1] - indices of similar items
/// ```
// ============================================================================
// Embedding Functions (feature-gated)
// ============================================================================
/// ELID encoding profile for vector embeddings.
///
/// Choose a profile based on your use case:
/// - `Mini128`: Fast 128-bit SimHash, good for similarity via Hamming distance
/// - `Morton10x10`: Z-order curve encoding, good for range queries
/// - `Hilbert10x10`: Hilbert curve encoding, best locality preservation
///
/// # JavaScript Example
///
/// ```javascript
/// import { ElidProfile, encodeElid } from 'elid';
///
/// const embedding = new Float64Array(768).fill(0.1);
/// const elid = encodeElid(embedding, ElidProfile.Mini128);
/// ```
/// Encode an embedding vector to an ELID string.
///
/// Converts a high-dimensional embedding (64-2048 dimensions) into a compact,
/// sortable identifier. The ELID preserves locality properties for efficient
/// similarity search.
///
/// # Parameters
///
/// - `embedding`: Float64 array of embedding values (64-2048 dimensions)
/// - `profile`: Encoding profile (Mini128, Morton10x10, or Hilbert10x10)
///
/// # Returns
///
/// A base32hex-encoded ELID string suitable for storage and comparison.
///
/// # JavaScript Example
///
/// ```javascript
/// import { encodeElid, ElidProfile } from 'elid';
///
/// // OpenAI embeddings are 1536 dimensions
/// const embedding = await getEmbedding("Hello world");
/// const elid = encodeElid(embedding, ElidProfile.Mini128);
/// console.log(elid); // "012345abcdef..."
/// ```
/// Decode an ELID string to raw bytes.
///
/// Returns the raw byte representation of an ELID, including the header
/// and payload bytes. Useful for custom processing or debugging.
///
/// # Parameters
///
/// - `elid_str`: A valid ELID string (base32hex encoded)
///
/// # Returns
///
/// A Uint8Array containing the raw bytes (header + payload).
///
/// # JavaScript Example
///
/// ```javascript
/// import { decodeElid } from 'elid';
///
/// const bytes = decodeElid("012345abcdef...");
/// console.log(bytes); // Uint8Array [...]
/// ```
/// Compute the Hamming distance between two ELID strings.
///
/// Returns the number of differing bits between two Mini128 ELIDs.
/// This distance is proportional to the angular distance between the
/// original embeddings (lower = more similar).
///
/// # Requirements
///
/// Both ELIDs must use the Mini128 profile.
///
/// # Parameters
///
/// - `elid1`: First ELID string
/// - `elid2`: Second ELID string
///
/// # Returns
///
/// Hamming distance (0-128). 0 means identical, 128 means completely different.
///
/// # JavaScript Example
///
/// ```javascript
/// import { encodeElid, elidHammingDistance, ElidProfile } from 'elid';
///
/// const elid1 = encodeElid(embedding1, ElidProfile.Mini128);
/// const elid2 = encodeElid(embedding2, ElidProfile.Mini128);
///
/// const distance = elidHammingDistance(elid1, elid2);
/// if (distance < 20) {
/// console.log("Very similar embeddings!");
/// }
/// ```
// ============================================================================
// FullVector Encoding Functions (feature-gated)
// ============================================================================
/// Precision options for full vector encoding.
///
/// Controls how many bits are used to represent each dimension value.
/// Higher precision means more accurate reconstruction but larger output.
///
/// # JavaScript Example
///
/// ```javascript
/// import { ElidVectorPrecision, encodeElidWithPrecision } from 'elid';
///
/// const embedding = new Float64Array(768).fill(0.1);
/// // Full32 = lossless, Half16 = smaller with minimal error
/// ```
/// Dimension handling mode for full vector encoding.
///
/// Controls whether to preserve original dimensions, reduce them,
/// or project to a common space for cross-dimensional comparison.
///
/// # JavaScript Example
///
/// ```javascript
/// import { ElidDimensionMode, encodeElidFullVector } from 'elid';
///
/// // Preserve all dimensions
/// // Reduce to fewer dimensions for smaller output
/// // Common space for comparing different-sized embeddings
/// ```
/// Encode an embedding using lossless full vector encoding.
///
/// Preserves the exact embedding values (32-bit float precision) and all dimensions.
/// This produces the largest output but allows exact reconstruction.
///
/// # Parameters
///
/// - `embedding`: Float64 array of embedding values (64-2048 dimensions)
///
/// # Returns
///
/// A base32hex-encoded ELID string that can be decoded back to the original embedding.
///
/// # JavaScript Example
///
/// ```javascript
/// import { encodeElidLossless, decodeElidToEmbedding } from 'elid';
///
/// const embedding = new Float64Array(768).fill(0.1);
/// const elid = encodeElidLossless(embedding);
///
/// // Later, recover the exact embedding
/// const recovered = decodeElidToEmbedding(elid);
/// // recovered is identical to embedding
/// ```
/// Encode an embedding with percentage-based compression.
///
/// The retention percentage (0.0-1.0) controls how much information is preserved:
/// - 1.0 = lossless (Full32 precision, all dimensions)
/// - 0.5 = half precision and/or half dimensions
/// - 0.25 = quarter precision and/or quarter dimensions
///
/// The algorithm optimizes for dimension reduction first (which preserves
/// more geometric relationships) before reducing precision.
///
/// # Parameters
///
/// - `embedding`: Float64 array of embedding values (64-2048 dimensions)
/// - `retention_pct`: Information retention percentage (0.0-1.0)
///
/// # Returns
///
/// A base32hex-encoded ELID string.
///
/// # JavaScript Example
///
/// ```javascript
/// import { encodeElidCompressed } from 'elid';
///
/// const embedding = new Float64Array(768).fill(0.1);
///
/// // 50% retention - good balance of size and fidelity
/// const elid = encodeElidCompressed(embedding, 0.5);
///
/// // 25% retention - smaller but less accurate
/// const smallElid = encodeElidCompressed(embedding, 0.25);
/// ```
/// Encode an embedding with a maximum output string length constraint.
///
/// Calculates the optimal precision and dimension settings to fit within
/// the specified character limit while maximizing fidelity.
///
/// # Parameters
///
/// - `embedding`: Float64 array of embedding values (64-2048 dimensions)
/// - `max_chars`: Maximum output string length in characters
///
/// # Returns
///
/// A base32hex-encoded ELID string guaranteed to be <= max_chars in length.
///
/// # JavaScript Example
///
/// ```javascript
/// import { encodeElidMaxLength } from 'elid';
///
/// const embedding = new Float64Array(768).fill(0.1);
///
/// // Fit in 100 characters (e.g., for database column constraints)
/// const elid = encodeElidMaxLength(embedding, 100);
/// console.log(elid.length <= 100); // true
///
/// // Fit in 50 characters (more compression)
/// const shortElid = encodeElidMaxLength(embedding, 50);
/// ```
/// Decode an ELID string back to an embedding vector.
///
/// Only works for ELIDs encoded with a FullVector profile (lossless,
/// compressed, or max_length). Returns null for non-reversible profiles
/// like Mini128, Morton, or Hilbert.
///
/// # Parameters
///
/// - `elid_str`: A valid ELID string (base32hex encoded)
///
/// # Returns
///
/// A Float64Array containing the decoded embedding, or null if the ELID
/// is not reversible.
///
/// Note: If dimension reduction was used during encoding, the decoded
/// embedding will be in the reduced dimension space, not the original.
///
/// # JavaScript Example
///
/// ```javascript
/// import { encodeElidLossless, decodeElidToEmbedding, isElidReversible } from 'elid';
///
/// const embedding = new Float64Array(768).fill(0.1);
/// const elid = encodeElidLossless(embedding);
///
/// if (isElidReversible(elid)) {
/// const recovered = decodeElidToEmbedding(elid);
/// console.log(recovered.length); // 768
/// }
/// ```
/// Check if an ELID can be decoded back to an embedding.
///
/// Returns true if the ELID was encoded with a FullVector profile
/// (lossless, compressed, or max_length), false otherwise.
///
/// # Parameters
///
/// - `elid_str`: A valid ELID string (base32hex encoded)
///
/// # Returns
///
/// `true` if decodeElidToEmbedding will return an embedding, `false` otherwise.
///
/// # JavaScript Example
///
/// ```javascript
/// import { encodeElid, encodeElidLossless, isElidReversible, ElidProfile } from 'elid';
///
/// const embedding = new Float64Array(768).fill(0.1);
///
/// // Mini128 is NOT reversible
/// const mini128Elid = encodeElid(embedding, ElidProfile.Mini128);
/// console.log(isElidReversible(mini128Elid)); // false
///
/// // Lossless IS reversible
/// const losslessElid = encodeElidLossless(embedding);
/// console.log(isElidReversible(losslessElid)); // true
/// ```
/// Encode an embedding for cross-dimensional comparison.
///
/// Projects the embedding to a common dimension space, allowing comparison
/// between embeddings of different original dimensions (e.g., 256d vs 768d).
///
/// # Parameters
///
/// - `embedding`: Float64 array of embedding values (64-2048 dimensions)
/// - `common_dims`: Target dimension space (all vectors projected here)
///
/// # Returns
///
/// A base32hex-encoded ELID string.
///
/// # JavaScript Example
///
/// ```javascript
/// import { encodeElidCrossDimensional, decodeElidToEmbedding } from 'elid';
///
/// // Different sized embeddings from different models
/// const embedding256 = new Float64Array(256).fill(0.1);
/// const embedding768 = new Float64Array(768).fill(0.1);
///
/// // Project both to 128-dim common space
/// const elid1 = encodeElidCrossDimensional(embedding256, 128);
/// const elid2 = encodeElidCrossDimensional(embedding768, 128);
///
/// // Now they can be compared directly (both decode to 128 dims)
/// const dec1 = decodeElidToEmbedding(elid1);
/// const dec2 = decodeElidToEmbedding(elid2);
/// // Both have length 128
/// ```
/// Convert an embedding vector directly to LSH bands.
///
/// Computes the 128-bit SimHash of the embedding and splits it into bands
/// for Locality-Sensitive Hashing (LSH) indexing in databases.
///
/// # Parameters
///
/// - `embedding`: Float64 array of embedding values (64-2048 dimensions)
/// - `num_bands`: Number of bands to split into (must be 1, 2, 4, 8, or 16)
/// - `seed`: Optional seed for deterministic hashing (defaults to standard ELID seed)
///
/// # Returns
///
/// An array of base32hex-encoded band strings. Returns an empty array if
/// `num_bands` is invalid.
///
/// # JavaScript Example
///
/// ```javascript
/// import { embeddingToBands } from 'elid';
///
/// const embedding = new Float64Array(768).fill(0.1);
///
/// // Split into 4 bands (32 bits each) - good balance for most use cases
/// const bands = embeddingToBands(embedding, 4);
/// console.log(bands.length); // 4
///
/// // Store bands in database for efficient OR queries:
/// // SELECT * FROM embeddings WHERE band0 = ? OR band1 = ? OR band2 = ? OR band3 = ?
///
/// // Use custom seed for different hash family
/// const bandsWithSeed = embeddingToBands(embedding, 4, 12345n);
/// ```
/// Split an existing Mini128 hash into LSH bands.
///
/// Takes a 128-bit hash (16 bytes) and splits it into bands for
/// Locality-Sensitive Hashing (LSH) indexing.
///
/// # Parameters
///
/// - `hash`: Uint8Array containing exactly 16 bytes (128-bit hash)
/// - `num_bands`: Number of bands to split into (must be 1, 2, 4, 8, or 16)
///
/// # Returns
///
/// An array of base32hex-encoded band strings.
///
/// # Throws
///
/// Throws an error if the hash is not exactly 16 bytes.
///
/// # JavaScript Example
///
/// ```javascript
/// import { mini128ToBands, encodeElid, decodeElid, ElidProfile } from 'elid';
///
/// // Get hash bytes from an existing Mini128 ELID
/// const embedding = new Float64Array(768).fill(0.1);
/// const elid = encodeElid(embedding, ElidProfile.Mini128);
/// const bytes = decodeElid(elid);
///
/// // Extract the 16-byte hash (skip header byte)
/// const hashBytes = bytes.slice(1, 17);
///
/// // Split into bands
/// const bands = mini128ToBands(hashBytes, 4);
/// console.log(bands.length); // 4
/// ```
/// Get metadata about a FullVector ELID.
///
/// Returns an object containing information about how the ELID was encoded,
/// including original dimensions, precision, and dimension mode.
///
/// # Parameters
///
/// - `elid_str`: A valid ELID string (base32hex encoded)
///
/// # Returns
///
/// An object with metadata fields, or null if not a FullVector ELID.
///
/// # JavaScript Example
///
/// ```javascript
/// import { encodeElidCompressed, getElidMetadata } from 'elid';
///
/// const embedding = new Float64Array(768).fill(0.1);
/// const elid = encodeElidCompressed(embedding, 0.5);
///
/// const meta = getElidMetadata(elid);
/// if (meta) {
/// console.log(meta.originalDims); // 768
/// console.log(meta.encodedDims); // depends on compression
/// console.log(meta.isLossless); // false
/// }
/// ```