@peerbit/document 1.0.2

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/src/query.ts ADDED
@@ -0,0 +1,510 @@
1
+ import {
2
+ AbstractType,
3
+ deserialize,
4
+ field,
5
+ fixedArray,
6
+ variant,
7
+ vec,
8
+ } from "@dao-xyz/borsh";
9
+ import { asString } from "./utils.js";
10
+ import { randomBytes, sha256Base64Sync } from "@peerbit/crypto";
11
+
12
+ export enum Compare {
13
+ Equal = 0,
14
+ Greater = 1,
15
+ GreaterOrEqual = 2,
16
+ Less = 3,
17
+ LessOrEqual = 4,
18
+ }
19
+ export const compare = (
20
+ test: bigint | number,
21
+ compare: Compare,
22
+ value: bigint | number
23
+ ) => {
24
+ switch (compare) {
25
+ case Compare.Equal:
26
+ return test == value; // == because with want bigint == number at some cases
27
+ case Compare.Greater:
28
+ return test > value;
29
+ case Compare.GreaterOrEqual:
30
+ return test >= value;
31
+ case Compare.Less:
32
+ return test < value;
33
+ case Compare.LessOrEqual:
34
+ return test <= value;
35
+ default:
36
+ console.warn("Unexpected compare");
37
+ return false;
38
+ }
39
+ };
40
+
41
+ /// ----- QUERY -----
42
+
43
+ export abstract class Query {}
44
+
45
+ export enum SortDirection {
46
+ ASC = 0,
47
+ DESC = 1,
48
+ }
49
+
50
+ @variant(0)
51
+ export class Sort {
52
+ @field({ type: vec("string") })
53
+ key: string[];
54
+
55
+ @field({ type: "u8" })
56
+ direction: SortDirection;
57
+
58
+ constructor(properties: {
59
+ key: string[] | string;
60
+ direction?: SortDirection;
61
+ }) {
62
+ this.key = Array.isArray(properties.key)
63
+ ? properties.key
64
+ : [properties.key];
65
+ this.direction = properties.direction || SortDirection.ASC;
66
+ }
67
+ }
68
+
69
+ export abstract class AbstractSearchRequest {}
70
+
71
+ /**
72
+ * Search with query and collect with sort conditionss
73
+ */
74
+
75
+ const toArray = <T>(arr: T | T[] | undefined) =>
76
+ (arr ? (Array.isArray(arr) ? arr : [arr]) : undefined) || [];
77
+
78
+ @variant(0)
79
+ export class SearchRequest extends AbstractSearchRequest {
80
+ @field({ type: fixedArray("u8", 32) })
81
+ id: Uint8Array; // Session id
82
+
83
+ @field({ type: vec(Query) })
84
+ query: Query[];
85
+
86
+ @field({ type: vec(Sort) })
87
+ sort: Sort[];
88
+
89
+ @field({ type: "u32" })
90
+ fetch: number;
91
+
92
+ constructor(props?: { query?: Query[] | Query; sort?: Sort[] | Sort }) {
93
+ super();
94
+ this.id = randomBytes(32);
95
+ this.query = toArray(props?.query);
96
+ this.sort = toArray(props?.sort);
97
+ this.fetch = 1;
98
+ }
99
+
100
+ private _idString: string;
101
+ get idString(): string {
102
+ return this._idString || (this._idString = sha256Base64Sync(this.id));
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Collect documents from peers using 'collect' session ids. This is used for distributed sorting internally
108
+ */
109
+ @variant(2)
110
+ export class CollectNextRequest extends AbstractSearchRequest {
111
+ @field({ type: fixedArray("u8", 32) })
112
+ id: Uint8Array; // collect with id
113
+
114
+ @field({ type: "u32" })
115
+ amount: number; // number of documents to ask for
116
+
117
+ constructor(properties: { id: Uint8Array; amount: number }) {
118
+ super();
119
+ this.id = properties.id;
120
+ this.amount = properties.amount;
121
+ }
122
+
123
+ private _idString: string;
124
+ get idString(): string {
125
+ return this._idString || (this._idString = sha256Base64Sync(this.id));
126
+ }
127
+ }
128
+
129
+ @variant(3)
130
+ export class CloseIteratorRequest extends AbstractSearchRequest {
131
+ @field({ type: fixedArray("u8", 32) })
132
+ id: Uint8Array; // collect with id
133
+
134
+ constructor(properties: { id: Uint8Array }) {
135
+ super();
136
+ this.id = properties.id;
137
+ }
138
+
139
+ private _idString: string;
140
+ get idString(): string {
141
+ return this._idString || (this._idString = sha256Base64Sync(this.id));
142
+ }
143
+ }
144
+
145
+ @variant(1)
146
+ export abstract class LogicalQuery extends Query {}
147
+
148
+ @variant(0)
149
+ export class And extends LogicalQuery {
150
+ @field({ type: vec(Query) })
151
+ and: Query[];
152
+
153
+ constructor(and: Query[]) {
154
+ super();
155
+ this.and = and;
156
+ }
157
+ }
158
+
159
+ @variant(1)
160
+ export class Or extends LogicalQuery {
161
+ @field({ type: vec(Query) })
162
+ or: Query[];
163
+
164
+ constructor(or: Query[]) {
165
+ super();
166
+ this.or = or;
167
+ }
168
+ }
169
+
170
+ @variant(2)
171
+ export abstract class StateQuery extends Query {}
172
+
173
+ @variant(1)
174
+ export class StateFieldQuery extends StateQuery {
175
+ @field({ type: vec("string") })
176
+ key: string[];
177
+
178
+ constructor(props: { key: string[] | string }) {
179
+ super();
180
+ this.key = Array.isArray(props.key) ? props.key : [props.key];
181
+ }
182
+ }
183
+
184
+ export abstract class PrimitiveValue {}
185
+
186
+ @variant(0)
187
+ export class StringValue extends PrimitiveValue {
188
+ @field({ type: "string" })
189
+ string: string;
190
+
191
+ constructor(string: string) {
192
+ super();
193
+ this.string = string;
194
+ }
195
+ }
196
+
197
+ @variant(1)
198
+ abstract class NumberValue extends PrimitiveValue {
199
+ abstract get value(): number | bigint;
200
+ }
201
+
202
+ @variant(0)
203
+ abstract class IntegerValue extends NumberValue {}
204
+
205
+ @variant(0)
206
+ export class UnsignedIntegerValue extends IntegerValue {
207
+ @field({ type: "u32" })
208
+ number: number;
209
+
210
+ constructor(number: number) {
211
+ super();
212
+ if (
213
+ Number.isInteger(number) === false ||
214
+ number > 4294967295 ||
215
+ number < 0
216
+ ) {
217
+ throw new Error("Number is not u32");
218
+ }
219
+ this.number = number;
220
+ }
221
+
222
+ get value() {
223
+ return this.number;
224
+ }
225
+ }
226
+
227
+ @variant(1)
228
+ export class BigUnsignedIntegerValue extends IntegerValue {
229
+ @field({ type: "u64" })
230
+ number: bigint;
231
+
232
+ constructor(number: bigint) {
233
+ super();
234
+ if (number > 18446744073709551615n || number < 0) {
235
+ throw new Error("Number is not u32");
236
+ }
237
+ this.number = number;
238
+ }
239
+ get value() {
240
+ return this.number;
241
+ }
242
+ }
243
+
244
+ @variant(1)
245
+ export class ByteMatchQuery extends StateFieldQuery {
246
+ @field({ type: Uint8Array })
247
+ value: Uint8Array;
248
+
249
+ @field({ type: "u8" })
250
+ private _reserved: number; // Replcate MemoryCompare query with this?
251
+
252
+ constructor(props: { key: string[] | string; value: Uint8Array }) {
253
+ super(props);
254
+ this.value = props.value;
255
+ this._reserved = 0;
256
+ }
257
+
258
+ _valueString: string;
259
+ /**
260
+ * value `asString`
261
+ */
262
+ get valueString() {
263
+ return this._valueString ?? (this._valueString = asString(this.value));
264
+ }
265
+ }
266
+
267
+ export enum StringMatchMethod {
268
+ "exact" = 0,
269
+ "prefix" = 1,
270
+ "contains" = 2,
271
+ }
272
+
273
+ @variant(2)
274
+ export class StringMatch extends StateFieldQuery {
275
+ @field({ type: "string" })
276
+ value: string;
277
+
278
+ @field({ type: "u8" })
279
+ method: StringMatchMethod;
280
+
281
+ @field({ type: "bool" })
282
+ caseInsensitive: boolean;
283
+
284
+ constructor(props: {
285
+ key: string[] | string;
286
+ value: string;
287
+ method?: StringMatchMethod;
288
+ caseInsensitive?: boolean;
289
+ }) {
290
+ super(props);
291
+ this.value = props.value;
292
+ this.method = props.method ?? StringMatchMethod.exact;
293
+ this.caseInsensitive = props.caseInsensitive ?? false;
294
+ }
295
+ }
296
+
297
+ @variant(3)
298
+ export class IntegerCompare extends StateFieldQuery {
299
+ @field({ type: "u8" })
300
+ compare: Compare;
301
+
302
+ @field({ type: IntegerValue })
303
+ value: IntegerValue;
304
+
305
+ constructor(props: {
306
+ key: string[] | string;
307
+ value: bigint | number | IntegerValue;
308
+ compare: Compare;
309
+ }) {
310
+ super(props);
311
+ if (props.value instanceof IntegerValue) {
312
+ this.value = props.value;
313
+ } else {
314
+ if (typeof props.value === "bigint") {
315
+ this.value = new BigUnsignedIntegerValue(props.value);
316
+ } else {
317
+ this.value = new UnsignedIntegerValue(props.value);
318
+ }
319
+ }
320
+
321
+ this.compare = props.compare;
322
+ }
323
+ }
324
+
325
+ @variant(4)
326
+ export class MissingField extends StateFieldQuery {
327
+ constructor(props: { key: string[] | string }) {
328
+ super(props);
329
+ }
330
+ }
331
+
332
+ @variant(5)
333
+ export class BoolQuery extends StateFieldQuery {
334
+ @field({ type: "bool" })
335
+ value: boolean;
336
+
337
+ constructor(props: { key: string[] | string; value: boolean }) {
338
+ super(props);
339
+ this.value = props.value;
340
+ }
341
+ }
342
+
343
+ // TODO MemoryCompareQuery can be replaces with ByteMatchQuery? Or Nesteed Queries + ByteMatchQuery?
344
+ /* @variant(0)
345
+ export class MemoryCompare {
346
+ @field({ type: Uint8Array })
347
+ bytes: Uint8Array;
348
+
349
+ @field({ type: "u64" })
350
+ offset: bigint;
351
+
352
+ constructor(opts?: { bytes: Uint8Array; offset: bigint }) {
353
+ if (opts) {
354
+ this.bytes = opts.bytes;
355
+ this.offset = opts.offset;
356
+ }
357
+ }
358
+ }
359
+
360
+ @variant(4)
361
+ export class MemoryCompareQuery extends Query {
362
+ @field({ type: vec(MemoryCompare) })
363
+ compares: MemoryCompare[];
364
+
365
+ constructor(opts?: { compares: MemoryCompare[] }) {
366
+ super();
367
+ if (opts) {
368
+ this.compares = opts.compares;
369
+ }
370
+ }
371
+ } */
372
+
373
+ /// ----- RESULTS -----
374
+
375
+ export abstract class Result {}
376
+
377
+ @variant(0)
378
+ export class Context {
379
+ @field({ type: "u64" })
380
+ created: bigint;
381
+
382
+ @field({ type: "u64" })
383
+ modified: bigint;
384
+
385
+ @field({ type: "string" })
386
+ head: string;
387
+
388
+ constructor(properties?: {
389
+ created: bigint;
390
+ modified: bigint;
391
+ head: string;
392
+ }) {
393
+ if (properties) {
394
+ this.created = properties.created;
395
+ this.modified = properties.modified;
396
+ this.head = properties.head;
397
+ }
398
+ }
399
+ }
400
+
401
+ @variant(0)
402
+ export class ResultWithSource<T> extends Result {
403
+ @field({ type: Uint8Array })
404
+ _source: Uint8Array;
405
+
406
+ @field({ type: Context })
407
+ context: Context;
408
+
409
+ _type: AbstractType<T>;
410
+ constructor(opts: { source: Uint8Array; context: Context; value?: T }) {
411
+ super();
412
+ this._source = opts.source;
413
+ this.context = opts.context;
414
+ this._value = opts.value;
415
+ }
416
+
417
+ init(type: AbstractType<T>) {
418
+ this._type = type;
419
+ }
420
+
421
+ _value?: T;
422
+ get value(): T {
423
+ if (this._value) {
424
+ return this._value;
425
+ }
426
+ if (!this._source) {
427
+ throw new Error("Missing source binary");
428
+ }
429
+ this._value = deserialize(this._source, this._type);
430
+ return this._value;
431
+ }
432
+ }
433
+
434
+ @variant(0)
435
+ export class Results<T> {
436
+ @field({ type: vec(ResultWithSource) })
437
+ results: ResultWithSource<T>[];
438
+
439
+ @field({ type: "u64" })
440
+ kept: bigint; // how many results that were not sent, but can be collected later
441
+
442
+ constructor(properties: { results: ResultWithSource<T>[]; kept: bigint }) {
443
+ this.kept = properties.kept;
444
+ this.results = properties.results;
445
+ }
446
+ }
447
+
448
+ /* @variant(5)
449
+ export class LogQuery extends Query { } */
450
+
451
+ /**
452
+ * Find logs that can be decrypted by certain keys
453
+ */
454
+ /*
455
+ @variant(0)
456
+ export class EntryEncryptedByQuery
457
+ extends LogQuery
458
+ implements
459
+ EntryEncryptionTemplate<
460
+ X25519PublicKey[],
461
+ X25519PublicKey[],
462
+ X25519PublicKey[],
463
+ X25519PublicKey[]
464
+ >
465
+ {
466
+ @field({ type: vec(X25519PublicKey) })
467
+ metadata: X25519PublicKey[];
468
+
469
+ @field({ type: vec(X25519PublicKey) })
470
+ payload: X25519PublicKey[];
471
+
472
+ @field({ type: vec(X25519PublicKey) })
473
+ next: X25519PublicKey[];
474
+
475
+ @field({ type: vec(X25519PublicKey) })
476
+ signatures: X25519PublicKey[];
477
+
478
+ constructor(properties?: {
479
+ metadata: X25519PublicKey[];
480
+ next: X25519PublicKey[];
481
+ payload: X25519PublicKey[];
482
+ signatures: X25519PublicKey[];
483
+ }) {
484
+ super();
485
+ if (properties) {
486
+ this.metadata = properties.metadata;
487
+ this.payload = properties.payload;
488
+ this.next = properties.next;
489
+ this.signatures = properties.signatures;
490
+ }
491
+ }
492
+ }
493
+
494
+ @variant(1)
495
+ export class SignedByQuery extends LogQuery {
496
+ @field({ type: vec(PublicSignKey) })
497
+ _publicKeys: PublicSignKey[];
498
+
499
+ constructor(properties: { publicKeys: PublicSignKey[] }) {
500
+ super();
501
+ if (properties) {
502
+ this._publicKeys = properties.publicKeys;
503
+ }
504
+ }
505
+
506
+ get publicKeys() {
507
+ return this._publicKeys;
508
+ }
509
+ }
510
+ */
package/src/utils.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { toBase64 } from "@peerbit/crypto";
2
+
3
+ export type Keyable = string | Uint8Array;
4
+ export const asString = (obj: Keyable) =>
5
+ typeof obj === "string" ? obj : toBase64(obj);
6
+ export const checkKeyable = (obj: Keyable) => {
7
+ if (obj == null) {
8
+ throw new Error(
9
+ `The provided key value is null or undefined, expecting string or Uint8array`
10
+ );
11
+ }
12
+ if (typeof obj === "string" || obj instanceof Uint8Array) {
13
+ return;
14
+ }
15
+
16
+ throw new Error("Key is not string or Uint8array, key value: " + typeof obj);
17
+ };