/
types.ts
967 lines (869 loc) 路 28.4 KB
/
types.ts
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
import { DocumentsStore } from './components/documents-store.js'
import { Index } from './components/index.js'
import { DocumentID, InternalDocumentID, InternalDocumentIDStore } from './components/internal-document-id-store.js'
import { Sorter } from './components/sorter.js'
import { Language } from './components/tokenizer/languages.js'
import { Point } from './trees/bkd.js'
export type Nullable<T> = T | null
export type SingleOrArray<T> = T | T[]
export type SyncOrAsyncValue<T = void> = T | PromiseLike<T>
// Given a type T, return a new type with:
// - the concatenation of nested properties as key
// - the type of the nested property as value
type Flatten<T extends object> = object extends T
? object
: {
[K in keyof T]-?: (
// Create a function as argument:
// - Pick<T, K> if the value is not an object (not run recursion)
// - { [key concatenation]: function calculated by recursion }
// - never is the value is an array
x: NonNullable<T[K]> extends infer V
? V extends object
? V extends readonly any[]
? never // Orama schema doens't allow array as value
: Flatten<V> extends infer FV
? {
[P in keyof FV as `${Extract<K, string>}.${Extract<P, string>}`]: FV[P]
}
: never // Never happen: it is needed due to `extends` typescript syntax
: Pick<T, K>
: never, // Never happen: it is needed due to typescript syntax
) => void
} extends Record<keyof T, (y: infer O) => void>
? O // Return the type of the function argument
: never // Never happen: it is needed due to typescript syntax
export type SchemaTypes<Value> = Value extends 'string'
? string
: Value extends 'string[]'
? string[]
: Value extends 'boolean'
? boolean
: Value extends 'boolean[]'
? boolean[]
: Value extends 'number'
? number
: Value extends 'number[]'
? number[]
: Value extends 'enum'
? string | number
: Value extends 'enum[]'
? (string | number)[]
: Value extends 'geopoint'
? Point
: // eslint-disable-next-line @typescript-eslint/no-unused-vars
Value extends `vector[${number}]`
? number[]
: Value extends object
? { [Key in keyof Value]: SchemaTypes<Value[Key]> } & {
[otherKeys: PropertyKey]: any
}
: never
export type Schema<TSchema> = TSchema extends AnySchema
? InternalTypedDocument<{
-readonly [Key in keyof TSchema]: SchemaTypes<TSchema[Key]>
}>
: never
export type AnyDocument = InternalTypedDocument<any>
export type InternalTypedDocument<TSchema extends object> = { id: DocumentID } & TSchema & {
[otherKeys: PropertyKey]: any
}
export type TypedDocument<T extends AnyOrama> = T['typeSchema']
export type AnySchema = {
[key: PropertyKey]: SearchableType | AnySchema
}
export type PartialSchemaDeepObject<T> = T extends object
? {
[K in keyof T]?: T[K]
}
: T
export type PartialSchemaDeep<T> = {
[K in keyof T]?: PartialSchemaDeepObject<T[K]>
}
/**
* @deprecated
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface Document extends Record<string, SearchableValue | Document | unknown> {}
export type Magnitude = number
export type Vector = `vector[${number}]`
export type VectorType = Float32Array
export type ScalarSearchableType = 'string' | 'number' | 'boolean' | 'enum' | 'geopoint'
export type ArraySearchableType = 'string[]' | 'number[]' | 'boolean[]' | 'enum[]' | Vector
export type SearchableType = ScalarSearchableType | ArraySearchableType
export type ScalarSearchableValue = string | number | boolean | Point
export type ArraySearchableValue = string[] | number[] | boolean[] | VectorType
export type SearchableValue = ScalarSearchableValue | ArraySearchableValue
export type SortType = 'string' | 'number' | 'boolean'
export type SortValue = string | number | boolean
export type VectorIndex = {
size: number
vectors: {
[docID: string]: [Magnitude, VectorType]
}
}
export type BM25Params = {
k?: number
b?: number
d?: number
}
export type GenericSorting = 'asc' | 'desc' | 'ASC' | 'DESC'
export type FacetSorting = GenericSorting
export interface StringFacetDefinition {
limit?: number
offset?: number
sort?: FacetSorting
}
export interface NumberFacetDefinition {
ranges: { from: number; to: number }[]
}
export interface BooleanFacetDefinition {
true?: boolean
false?: boolean
}
export type FacetsParams<T extends AnyOrama> = Partial<Record<LiteralUnion<T['schema']>, FacetDefinition>>
export type FacetDefinition = StringFacetDefinition | NumberFacetDefinition | BooleanFacetDefinition
export type ReduceFunction<T, R> = (values: ScalarSearchableValue[], acc: T, value: R, index: number) => T
export type Reduce<T, R = AnyDocument> = {
reducer: ReduceFunction<T, R>
getInitialValue: (elementCount: number) => T
}
export type GroupByParams<T extends AnyOrama, ResultDocument> = {
properties: LiteralUnion<T['schema']>[]
maxResult?: number
reduce?: Reduce<ResultDocument>
}
export type ComparisonOperator = {
gt?: number
gte?: number
lt?: number
lte?: number
eq?: number
between?: [number, number]
}
export type EnumComparisonOperator = {
eq?: string | number | boolean
in?: (string | number | boolean)[]
nin?: (string | number | boolean)[]
}
export type EnumArrComparisonOperator = {
containsAll ?: (string | number | boolean)[]
}
export type GeosearchDistanceUnit =
| 'cm'
| 'm'
| 'km'
| 'ft'
| 'yd'
| 'mi'
export type GeosearchRadiusOperator = {
radius: {
coordinates: Point
value: number
unit?: GeosearchDistanceUnit
inside?: boolean
highPrecision?: boolean
}
}
export type GeosearchPolygonOperator = {
polygon: {
coordinates: Point[]
inside?: boolean
highPrecision?: boolean
}
}
export type GeosearchOperation =
| GeosearchRadiusOperator
| GeosearchPolygonOperator
export type Operator<Value> = Value extends 'string'
? (string | string[])
: Value extends 'string[]'
? (string | string[])
: Value extends 'boolean'
? boolean
: Value extends 'boolean[]'
? boolean
: Value extends 'number'
? ComparisonOperator
: Value extends 'number[]'
? ComparisonOperator
: Value extends 'enum'
? EnumComparisonOperator
: Value extends 'enum[]'
? EnumArrComparisonOperator
: Value extends 'geopoint'
? GeosearchOperation
: never
export type WhereCondition<TSchema> = {
[key in keyof TSchema]?: Operator<TSchema[key]>
}
/**
* A custom sorter function item as [id, score, document].
*/
export type CustomSorterFunctionItem<ResultDocument> = [InternalDocumentID, number, ResultDocument]
export type CustomSorterFunction<ResultDocument> = (
a: CustomSorterFunctionItem<ResultDocument>,
b: CustomSorterFunctionItem<ResultDocument>,
) => number
// thanks to https://github.com/sindresorhus/type-fest/blob/main/source/literal-union.d.ts
export type LiteralUnion<T> = (keyof T extends string ? keyof T : never) | (string & Record<never, never>)
/**
* Define which properties to sort for.
*/
export type SorterParams<T extends AnyOrama> = {
/**
* The key of the document used to sort the result.
*/
property: LiteralUnion<T['schema']>;
/**
* Whether to sort the result in ascending or descending order.
*/
order?: 'ASC' | 'DESC'
}
export type FlattenSchema<T extends AnyOrama> = Flatten<T['schema']>
export type FlattenSchemaProperty<T extends AnyOrama> = T['schema'] extends object ? keyof FlattenSchema<T> : string
export type OnlyStrings<T extends any[]> = T[number] extends infer V ? V extends string ? V : never : never
export type SortByParams<T extends AnyOrama, ResultDocument> = SorterParams<T> | CustomSorterFunction<ResultDocument>
export type SearchParams<T extends AnyOrama, ResultDocument = TypedDocument<T>> = {
/**
* The word to search.
*/
term?: string
/**
* The properties of the document to search in.
*/
properties?: '*' | FlattenSchemaProperty<T>[]
/**
* The number of matched documents to return.
*/
limit?: number
/**
* The number of matched documents to skip.
*/
offset?: number
/**
* The key of the document used to sort the result.
*/
sortBy?: SortByParams<T, ResultDocument>
/**
* Whether to match the term exactly.
*/
exact?: boolean
/**
* The maximum [levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance)
* between the term and the searchable property.
*/
tolerance?: number
/**
* The BM25 parameters to use.
*
* k: Term frequency saturation parameter.
* The higher the value, the more important the term frequency becomes.
* The default value is 1.2. It should be set to a value between 1.2 and 2.0.
*
* b: Document length saturation impact. The higher the value, the more
* important the document length becomes. The default value is 0.75.
*
* d: Frequency normalization lower bound. Default value is 0.5.
*
* Full documentation: https://docs.oramasearch.com/open-source/usage/search/BM25-algorithm
*
* @see https://en.wikipedia.org/wiki/Okapi_BM25
*/
relevance?: BM25Params
/**
* The boost to apply to the properties.
*
* The boost is a number that is multiplied to the score of the property.
* It can be used to give more importance to some properties.
*
* Full documentation: https://docs.oramasearch.com/open-source/usage/search/fields-boosting
*
* @example
* // Give more importance to the 'title' property.
* const result = await search(db, {
* term: 'Michael',
* properties: ['title', 'author'],
* boost: {
* title: 2
* }
* });
*
* // In that case, the score of the 'title' property will be multiplied by 2.
*/
boost?: Partial<Record<OnlyStrings<FlattenSchemaProperty<T>[]>, number>>
/**
* Facets configuration
* Full documentation: https://docs.oramasearch.com/open-source/usage/search/facets
*
* A facet is a feature that allows users to narrow down their search results by specific
* attributes or characteristics, such as category, price, or location.
* This can help users find more relevant and specific results for their search query.
*
* @example
*
* const results = await search(db, {
* term: 'Personal Computer',
* properties: ['title', 'description', 'category.primary', 'category.secondary'],
* facets: {
* 'category.primary': {
* size: 10,
* sort: 'ASC',
* }
* }
* });
*/
facets?: FacetsParams<T>
/**
* Distinct configuration
* Full documentation: https://docs.oramasearch.com/open-source/usage/search/introduction#distinct
*
* @example
* const results = await search(db, {
* term: 'Headphones',
* distinctOn: 'category.primary',
* })
*/
distinctOn?: LiteralUnion<T['schema']>
/**
* Groups configuration
* Full documentation: https://docs.oramasearch.com/open-source/usage/search/grouping
*
* @example
* const results = await search(db, {
* term: 'Headphones',
* groupBy: {
* properties: ['category.primary'],
* maxResult: 10,
* }
* })
*/
groupBy?: GroupByParams<T, ResultDocument>
/**
* Filter the search results.
* Full documentation: https://docs.oramasearch.com/open-source/usage/search/filters
*
* @example
* // Search for documents that contain 'Headphones' in the 'description' and 'title' fields and
* // have a price less than 100.
*
* const result = await search(db, {
* term: 'Headphones',
* properties: ['description', 'title'],
* where: {
* price: {
* lt: 100
* }
* }
* });
*/
where?: Partial<WhereCondition<T['schema']>>
/**
* Threshold to use for refining the search results.
* The threshold is a number between 0 and 1 that represents the minimum score of the documents to return.
* By default, the threshold is 1.
*
* Full documentation: https://docs.oramasearch.com/open-source/usage/search/threshold
*
* @example
*
* const result = await search(db, {
* term: 'Red Headphones'
* threshold: 0
* });
*
* // The result will contain all the documents that contain both 'Red' and 'Headphones' in their properties.
*
* const result2 = await search(db, {
* term: 'Red Headphones'
* threshold: 1
* });
*
* // The result will contain all the documents that contain either 'Red' and 'Headphones' in their properties.
*/
threshold?: number
/**
* Preflight query.
* Will return just the facets (if needed) and the number of matched documents for the given query.
*
* Full documentation: https://docs.oramasearch.com/open-source/usage/search/preflight
*
* @example
*
* const result = await search(db, {
* term: 'Red Headphones',
* preflight: true
* });
*
* console.log(result);
*
* // {
* // elapsed: {
* // raw: 181208,
* // formatted: '181渭s'
* // },
* // count: 100,
* // }
*/
preflight?: boolean
}
export type Result<Document> = {
/**
* The id of the document.
*/
id: string
/**
* The score of the document in the search.
*/
score: number
/**
* The document
*/
document: Document
}
export type FacetResult = Record<
string,
{
count: number
values: Record<string, number>
}
>
export type GroupResult<Document> =
| {
values: ScalarSearchableValue[]
result: Result<Document>[]
}[]
export type TokenScore = [InternalDocumentID, number]
export type TokenMap = Record<string, TokenScore[]>
export type IndexMap = Record<string, TokenMap>
export type SearchContext<T extends AnyOrama, ResultDocument = TypedDocument<T>> = {
timeStart: bigint
tokenizer: Tokenizer
index: T['index']
documentsStore: T['documentsStore']
language: string | undefined
params: SearchParams<T, ResultDocument>
docsCount: number
uniqueDocsIDs: Record<number, number>
indexMap: IndexMap
docsIntersection: TokenMap
}
export type ElapsedTime = {
raw: number
formatted: string
}
export type Results<Document> = {
/**
* The number of all the matched documents.
*/
count: number
/**
* An array of matched documents taking `limit` and `offset` into account.
*/
hits: Result<Document>[]
/**
* The time taken to search.
*/
elapsed: ElapsedTime
/**
* The facets results.
*/
facets?: FacetResult
groups?: GroupResult<Document>
}
/**
* Sometimes {@link doc} will not have the correct type; in these cases,
* you can simply create a new variable and convert it to the correct type like:
*
* @example```ts
* const fixedType = doc as MyType;
* ```
*/
export type SingleCallbackComponent<T extends AnyOrama> = (
orama: T,
id: string,
doc?: TypedDocument<T>,
) => SyncOrAsyncValue
/**
* Sometimes {@link doc} will not have the correct type; in these cases,
* you can simply create a new variable and convert it to the correct type like:
*
* @example```ts
* const fixedType = doc as MyType;
* ```
*/
export type MultipleCallbackComponent<T extends AnyOrama> = (
orama: T,
doc: TypedDocument<T>[] | string[],
) => SyncOrAsyncValue
/**
* Sometimes {@link results} will not have the correct type; in these cases,
* you can simply create a new variable and convert it to the correct type like:
*
* @example```ts
* const fixedType = results as Results<MyType>;
* ```
*/
export type AfterSearch<T extends AnyOrama, ResultDocument extends TypedDocument<T> = TypedDocument<T>> = (
db: T,
params: SearchParams<T, ResultDocument>,
language: string | undefined,
results: Results<ResultDocument>,
) => SyncOrAsyncValue
export type BeforeSearch<T extends AnyOrama> = (
db: T,
params: SearchParams<T>,
language: string | undefined,
) => SyncOrAsyncValue
export type IIndexInsertOrRemoveHookFunction = <R = void>(
index: AnyIndexStore,
prop: string,
id: string,
value: SearchableValue,
type: SearchableType,
language: string | undefined,
tokenizer: Tokenizer,
docsCount: number,
) => SyncOrAsyncValue<R>
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface AnyIndexStore {
vectorIndexes: Record<string, VectorIndex>
}
export type AnyIndex = IIndex<AnyIndexStore>
export interface IIndex<I extends AnyIndexStore> {
create<T extends AnyOrama>(
orama: T,
sharedInternalDocumentStore: T['internalDocumentIDStore'],
schema: T['schema'],
): SyncOrAsyncValue<I>
beforeInsert?: IIndexInsertOrRemoveHookFunction
insert: <T extends I>(
implementation: IIndex<T>,
index: T,
prop: string,
id: DocumentID,
value: SearchableValue,
schemaType: SearchableType,
language: string | undefined,
tokenizer: Tokenizer,
docsCount: number,
) => SyncOrAsyncValue
afterInsert?: IIndexInsertOrRemoveHookFunction
beforeRemove?: IIndexInsertOrRemoveHookFunction
remove: <T extends I>(
implementation: IIndex<T>,
index: T,
prop: string,
id: DocumentID,
value: SearchableValue,
schemaType: SearchableType,
language: string | undefined,
tokenizer: Tokenizer,
docsCount: number,
) => SyncOrAsyncValue<boolean>
afterRemove?: IIndexInsertOrRemoveHookFunction
insertDocumentScoreParameters(
index: I,
prop: string,
id: DocumentID,
tokens: string[],
docsCount: number,
): SyncOrAsyncValue
insertTokenScoreParameters(index: I, prop: string, id: DocumentID, tokens: string[], token: string): SyncOrAsyncValue
removeDocumentScoreParameters(index: I, prop: string, id: DocumentID, docsCount: number): SyncOrAsyncValue
removeTokenScoreParameters(index: I, prop: string, token: string): SyncOrAsyncValue
calculateResultScores<T extends AnyOrama, ResultDocument = TypedDocument<T>>(
context: SearchContext<T, ResultDocument>,
index: I,
prop: string,
term: string,
ids: DocumentID[],
): SyncOrAsyncValue<TokenScore[]>
search<T extends AnyOrama, ResultDocument = TypedDocument<T>>(
context: SearchContext<T, ResultDocument>,
index: I,
prop: string,
term: string,
): SyncOrAsyncValue<TokenScore[]>
searchByWhereClause<T extends AnyOrama, ResultDocument = TypedDocument<T>>(
context: SearchContext<T, ResultDocument>,
index: I,
filters: Partial<WhereCondition<T['schema']>>,
): SyncOrAsyncValue<InternalDocumentID[]>
getSearchableProperties(index: I): SyncOrAsyncValue<string[]>
getSearchablePropertiesWithTypes(index: I): SyncOrAsyncValue<Record<string, SearchableType>>
load<R = unknown>(sharedInternalDocumentStore: InternalDocumentIDStore, raw: R): SyncOrAsyncValue<I>
save<R = unknown>(index: I): SyncOrAsyncValue<R>
}
export interface AnyDocumentStore {
docs: Record<InternalDocumentID, AnyDocument>
}
export interface IDocumentsStore<D extends AnyDocumentStore = AnyDocumentStore> {
create<T extends AnyOrama>(orama: T, sharedInternalDocumentStore: InternalDocumentIDStore): SyncOrAsyncValue<D>
get(store: D, id: DocumentID): SyncOrAsyncValue<AnyDocument | undefined>
getMultiple(store: D, ids: DocumentID[]): SyncOrAsyncValue<(AnyDocument | undefined)[]>
getAll(store: D): SyncOrAsyncValue<Record<InternalDocumentID, AnyDocument>>
store(store: D, id: DocumentID, doc: AnyDocument): SyncOrAsyncValue<boolean>
remove(store: D, id: DocumentID): SyncOrAsyncValue<boolean>
count(store: D): SyncOrAsyncValue<number>
load<R = unknown>(sharedInternalDocumentStore: InternalDocumentIDStore, raw: R): SyncOrAsyncValue<D>
save<R = unknown>(store: D): SyncOrAsyncValue<R>
}
export interface SorterConfig {
enabled?: boolean
unsortableProperties?: string[]
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface AnySorterStore {}
export type AnySorter = ISorter<AnySorterStore>
export interface ISorter<So extends AnySorterStore> {
create<T extends AnyOrama>(
orama: T,
sharedInternalDocumentStore: InternalDocumentIDStore,
schema: T['schema'],
sorterConfig?: SorterConfig,
): SyncOrAsyncValue<So>
insert: <T extends So>(
sorter: T,
prop: string,
id: DocumentID,
value: SortValue,
schemaType: SortType,
language: string | undefined,
) => SyncOrAsyncValue
remove: <T extends So>(sorter: T, prop: string, id: DocumentID) => SyncOrAsyncValue
load<R = unknown>(sharedInternalDocumentStore: InternalDocumentIDStore, raw: R): SyncOrAsyncValue<So>
save<R = unknown>(sorter: So): SyncOrAsyncValue<R>
sortBy<T extends AnyOrama>(
sorter: So,
docIds: [DocumentID, number][],
by: SorterParams<T>,
): Promise<[DocumentID, number][]>
getSortableProperties(sorter: So): SyncOrAsyncValue<string[]>
getSortablePropertiesWithTypes(sorter: So): SyncOrAsyncValue<Record<string, SortType>>
}
export type Stemmer = (word: string) => string
export type DefaultTokenizerConfig = {
language?: Language
stemming?: boolean
stemmer?: Stemmer
stemmerSkipProperties?: string | string[]
tokenizeSkipProperties?: string | string[]
stopWords?: boolean | string[] | ((stopWords: string[]) => string[] | Promise<string[]>)
allowDuplicates?: boolean
}
export interface Tokenizer {
language: string
normalizationCache: Map<string, string>
tokenize: (raw: string, language?: string, prop?: string) => SyncOrAsyncValue<string[]>
}
export interface ObjectComponents<I, D, So> {
tokenizer: Tokenizer | DefaultTokenizerConfig
index: I
documentsStore: D
sorter: So
}
export interface FunctionComponents<S> {
validateSchema(doc: AnyDocument, schema: S): SyncOrAsyncValue<string | undefined>
getDocumentIndexId(doc: AnyDocument): SyncOrAsyncValue<string>
getDocumentProperties(doc: AnyDocument, paths: string[]): SyncOrAsyncValue<Record<string, string | number | boolean>>
formatElapsedTime(number: bigint): SyncOrAsyncValue<number | string | object | ElapsedTime>
}
export interface SingleOrArrayCallbackComponents<T extends AnyOrama> {
/**
* More details {@link SingleCallbackComponent}
*/
beforeInsert: SingleOrArray<SingleCallbackComponent<T>>
/**
* More details {@link SingleCallbackComponent}
*/
afterInsert: SingleOrArray<SingleCallbackComponent<T>>
/**
* More details {@link SingleCallbackComponent}
*/
beforeRemove: SingleOrArray<SingleCallbackComponent<T>>
/**
* More details {@link SingleCallbackComponent}
*/
afterRemove: SingleOrArray<SingleCallbackComponent<T>>
/**
* More details {@link SingleCallbackComponent}
*/
beforeUpdate: SingleOrArray<SingleCallbackComponent<T>>
/**
* More details {@link SingleCallbackComponent}
*/
afterUpdate: SingleOrArray<SingleCallbackComponent<T>>
/**
* More details {@link BeforeSearch}
*/
beforeSearch: SingleOrArray<BeforeSearch<T>>
/**
* More details {@link AfterSearch}
*/
afterSearch: SingleOrArray<AfterSearch<T>>
/**
* More details {@link MultipleCallbackComponent}
*/
beforeInsertMultiple: SingleOrArray<MultipleCallbackComponent<T>>
/**
* More details {@link MultipleCallbackComponent}
*/
afterInsertMultiple: SingleOrArray<MultipleCallbackComponent<T>>
/**
* More details {@link MultipleCallbackComponent}
*/
beforeRemoveMultiple: SingleOrArray<MultipleCallbackComponent<T>>
/**
* More details {@link MultipleCallbackComponent}
*/
afterRemoveMultiple: SingleOrArray<MultipleCallbackComponent<T>>
/**
* More details {@link MultipleCallbackComponent}
*/
beforeUpdateMultiple: SingleOrArray<MultipleCallbackComponent<T>>
/**
* More details {@link MultipleCallbackComponent}
*/
afterUpdateMultiple: SingleOrArray<MultipleCallbackComponent<T>>
}
export interface ArrayCallbackComponents<T extends AnyOrama> {
/**
* More details {@link SingleCallbackComponent}
*/
beforeInsert: SingleCallbackComponent<T>[]
/**
* More details {@link SingleCallbackComponent}
*/
afterInsert: SingleCallbackComponent<T>[]
/**
* More details {@link SingleCallbackComponent}
*/
beforeRemove: SingleCallbackComponent<T>[]
/**
* More details {@link SingleCallbackComponent}
*/
afterRemove: SingleCallbackComponent<T>[]
/**
* More details {@link SingleCallbackComponent}
*/
beforeUpdate: SingleCallbackComponent<T>[]
/**
* More details {@link SingleCallbackComponent}
*/
afterUpdate: SingleCallbackComponent<T>[]
/**
* More details {@link BeforeSearch}
*/
beforeSearch: BeforeSearch<T>[]
/**
* More details {@link AfterSearch}
*/
afterSearch: AfterSearch<T>[]
/**
* More details {@link MultipleCallbackComponent}
*/
beforeInsertMultiple: MultipleCallbackComponent<T>[]
/**
* More details {@link MultipleCallbackComponent}
*/
afterInsertMultiple: MultipleCallbackComponent<T>[]
/**
* More details {@link MultipleCallbackComponent}
*/
beforeRemoveMultiple: MultipleCallbackComponent<T>[]
/**
* More details {@link MultipleCallbackComponent}
*/
afterRemoveMultiple: MultipleCallbackComponent<T>[]
/**
* More details {@link MultipleCallbackComponent}
*/
beforeUpdateMultiple: MultipleCallbackComponent<T>[]
/**
* More details {@link MultipleCallbackComponent}
*/
afterUpdateMultiple: MultipleCallbackComponent<T>[]
}
export type Components<T extends AnyOrama, TSchema, TIndex, TDocumentStore, TSorter> = Partial<
ObjectComponents<TIndex, TDocumentStore, TSorter> & FunctionComponents<TSchema> & SingleOrArrayCallbackComponents<T>
>
export const kInsertions = Symbol('orama.insertions')
export const kRemovals = Symbol('orama.removals')
export type PickIfExtends<T, TExtends, TDefault> = T extends TExtends ? T : TDefault
type Internals<
TSchema,
TIndex extends AnyIndexStore,
TDocumentStore extends AnyDocumentStore,
TSorter extends AnySorterStore,
> = {
schema: TSchema
typeSchema: Schema<TSchema>
tokenizer: Tokenizer
index: IIndex<TIndex>
documentsStore: IDocumentsStore<TDocumentStore>
sorter: ISorter<TSorter>
data: {
index: TIndex
docs: TDocumentStore
sorting: TSorter
}
internalDocumentIDStore: InternalDocumentIDStore
caches: Record<string, unknown>
[kInsertions]: number | undefined
[kRemovals]: number | undefined
}
type OramaID = {
id: string
}
export type ExtractSchema<T> = T extends { schema: infer RawSchema } ? Schema<RawSchema> : never
export type AnyGeneric<T> = T[]
export type AnyGenericIndex<T> = T extends IIndex<infer TStore>
? TStore extends AnyIndexStore
? TStore
: never
: AnyIndexStore
export type AnyGenericDocumentStore<T> = T extends IDocumentsStore<infer TStore>
? TStore extends AnyDocumentStore
? TStore
: never
: AnyDocumentStore
export type AnyGenericSorter<T> = T extends ISorter<infer TSorter>
? TSorter extends AnySorterStore
? TSorter
: never
: AnySorterStore
export type PickInferGeneric<T, Default> = T extends AnyGeneric<infer Generic>
? Generic extends Default
? Generic
: never
: never
export type Orama<TSchema, TIndex = IIndex<Index>, TDocumentStore = IDocumentsStore<DocumentsStore>, TSorter = ISorter<Sorter>> =
FunctionComponents<TSchema>
& Internals<TSchema, AnyGenericIndex<TIndex>, AnyGenericDocumentStore<TDocumentStore>, AnyGenericSorter<TSorter>>
& ArrayCallbackComponents<any>
& OramaID
& { plugins: OramaPlugin[] }
export type AnyOrama<TSchema = any> =
FunctionComponents<TSchema>
& Internals<TSchema, AnyIndexStore, AnyDocumentStore, AnySorterStore>
& ArrayCallbackComponents<any>
& OramaID
& { plugins: OramaPlugin[] }
export type OramaPlugin = {
name: string
beforeInsert?: <T extends AnyOrama>(orama: T, id: string, doc: AnyDocument) => SyncOrAsyncValue
afterInsert?: <T extends AnyOrama>(orama: T, id: string, doc: AnyDocument) => SyncOrAsyncValue
beforeRemove?: <T extends AnyOrama>(orama: T, id: string, doc: AnyDocument) => SyncOrAsyncValue
afterRemove?: <T extends AnyOrama>(orama: T, id: string, doc: AnyDocument) => SyncOrAsyncValue
beforeUpdate?: <T extends AnyOrama>(orama: T, id: string, doc: AnyDocument) => SyncOrAsyncValue
afterUpdate?: <T extends AnyOrama>(orama: T, id: string, doc: AnyDocument) => SyncOrAsyncValue
beforeSearch?: <T extends AnyOrama>(orama: T, params: SearchParams<T>, language: string | undefined) => SyncOrAsyncValue
afterSearch?: <T extends AnyOrama>(orama: T, params: SearchParams<T>, language: string | undefined, results: Results<TypedDocument<T>>) => SyncOrAsyncValue
beforeInsertMultiple?: <T extends AnyOrama>(orama: T, docs: AnyDocument[]) => SyncOrAsyncValue
afterInsertMultiple?: <T extends AnyOrama>(orama: T, docs: AnyDocument[]) => SyncOrAsyncValue
beforeRemoveMultiple?: <T extends AnyOrama>(orama: T, ids: string[]) => SyncOrAsyncValue
afterRemoveMultiple?: <T extends AnyOrama>(orama: T, ids: string[]) => SyncOrAsyncValue
beforeUpdateMultiple?: <T extends AnyOrama>(orama: T, docs: AnyDocument[]) => SyncOrAsyncValue
afterUpdateMultiple?: <T extends AnyOrama>(orama: T, docs: AnyDocument[]) => SyncOrAsyncValue
}