@xyo-network/archivist-indexeddb 2.99.2 → 2.99.3

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.
@@ -0,0 +1,71 @@
1
+ import { Hash } from '@xylabs/hex';
2
+ import { AbstractArchivist } from '@xyo-network/archivist-abstract';
3
+ import { ArchivistModuleEventData } from '@xyo-network/archivist-model';
4
+ import { Payload, PayloadWithMeta, Schema } from '@xyo-network/payload-model';
5
+ import { IDBPDatabase } from 'idb';
6
+ import { IndexedDbArchivistParams } from './Params';
7
+ export interface PayloadStore {
8
+ [s: string]: Payload;
9
+ }
10
+ export declare class IndexedDbArchivist<TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams, TEventData extends ArchivistModuleEventData = ArchivistModuleEventData> extends AbstractArchivist<TParams, TEventData> {
11
+ static readonly configSchemas: Schema[];
12
+ static readonly defaultConfigSchema: Schema;
13
+ static readonly defaultDbName = "archivist";
14
+ static readonly defaultDbVersion = 1;
15
+ static readonly defaultStoreName = "payloads";
16
+ private static readonly dataHashIndex;
17
+ private static readonly hashIndex;
18
+ private static readonly schemaIndex;
19
+ static readonly hashIndexName: string;
20
+ static readonly dataHashIndexName: string;
21
+ static readonly schemaIndexName: string;
22
+ /**
23
+ * The database name. If not supplied via config, it defaults
24
+ * to the module name (not guaranteed to be unique) and if module
25
+ * name is not supplied, it defaults to `archivist`. This behavior
26
+ * biases towards a single, isolated DB per archivist which seems to
27
+ * make the most sense for 99% of use cases.
28
+ */
29
+ get dbName(): string;
30
+ /**
31
+ * The database version. If not supplied via config, it defaults to 1.
32
+ */
33
+ get dbVersion(): number;
34
+ get queries(): string[];
35
+ /**
36
+ * The name of the object store. If not supplied via config, it defaults
37
+ * to `payloads`.
38
+ */
39
+ get storeName(): string;
40
+ /**
41
+ * The indexes to create on the store
42
+ */
43
+ private get indexes();
44
+ protected allHandler(): Promise<PayloadWithMeta[]>;
45
+ protected clearHandler(): Promise<void>;
46
+ protected deleteHandler(hashes: Hash[]): Promise<Hash[]>;
47
+ /**
48
+ * Uses an index to get a payload by the index value, but returns the value with the primary key (from the root store)
49
+ * @param db The db instance to use
50
+ * @param storeName The name of the store to use
51
+ * @param indexName The index to use
52
+ * @param key The key to get from the index
53
+ * @returns The primary key and the payload, or undefined if not found
54
+ */
55
+ protected getFromIndexWithPrimaryKey(db: IDBPDatabase<PayloadStore>, storeName: string, indexName: string, key: IDBValidKey): Promise<[number, PayloadWithMeta] | undefined>;
56
+ protected getHandler(hashes: string[]): Promise<PayloadWithMeta[]>;
57
+ protected insertHandler(payloads: Payload[]): Promise<PayloadWithMeta[]>;
58
+ protected startHandler(): Promise<boolean>;
59
+ /**
60
+ * Returns that the desired DB/Store initialized to the correct version
61
+ * @returns The initialized DB
62
+ */
63
+ private getInitializedDb;
64
+ /**
65
+ * Executes a callback with the initialized DB and then closes the db
66
+ * @param callback The method to execute with the initialized DB
67
+ * @returns
68
+ */
69
+ private useDb;
70
+ }
71
+ //# sourceMappingURL=Archivist.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Archivist.d.ts","sourceRoot":"","sources":["../../src/Archivist.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAKL,wBAAwB,EAGzB,MAAM,8BAA8B,CAAA;AAGrC,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAA;AAC7E,OAAO,EAAE,YAAY,EAAU,MAAM,KAAK,CAAA;AAG1C,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAA;AAEnD,MAAM,WAAW,YAAY;IAC3B,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAA;CACrB;AAED,qBACa,kBAAkB,CAC7B,OAAO,SAAS,wBAAwB,GAAG,wBAAwB,EACnE,UAAU,SAAS,wBAAwB,GAAG,w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AAE,CAAC;cAmCxD,aAAa,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;cA0C9D,YAAY;IAQrC;;;OAGG;YACW,gBAAgB;IAiD9B;;;;OAIG;YACW,KAAK;CAWpB"}
@@ -0,0 +1,71 @@
1
+ import { Hash } from '@xylabs/hex';
2
+ import { AbstractArchivist } from '@xyo-network/archivist-abstract';
3
+ import { ArchivistModuleEventData } from '@xyo-network/archivist-model';
4
+ import { Payload, PayloadWithMeta, Schema } from '@xyo-network/payload-model';
5
+ import { IDBPDatabase } from 'idb';
6
+ import { IndexedDbArchivistParams } from './Params';
7
+ export interface PayloadStore {
8
+ [s: string]: Payload;
9
+ }
10
+ export declare class IndexedDbArchivist<TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams, TEventData extends ArchivistModuleEventData = ArchivistModuleEventData> extends AbstractArchivist<TParams, TEventData> {
11
+ static readonly configSchemas: Schema[];
12
+ static readonly defaultConfigSchema: Schema;
13
+ static readonly defaultDbName = "archivist";
14
+ static readonly defaultDbVersion = 1;
15
+ static readonly defaultStoreName = "payloads";
16
+ private static readonly dataHashIndex;
17
+ private static readonly hashIndex;
18
+ private static readonly schemaIndex;
19
+ static readonly hashIndexName: string;
20
+ static readonly dataHashIndexName: string;
21
+ static readonly schemaIndexName: string;
22
+ /**
23
+ * The database name. If not supplied via config, it defaults
24
+ * to the module name (not guaranteed to be unique) and if module
25
+ * name is not supplied, it defaults to `archivist`. This behavior
26
+ * biases towards a single, isolated DB per archivist which seems to
27
+ * make the most sense for 99% of use cases.
28
+ */
29
+ get dbName(): string;
30
+ /**
31
+ * The database version. If not supplied via config, it defaults to 1.
32
+ */
33
+ get dbVersion(): number;
34
+ get queries(): string[];
35
+ /**
36
+ * The name of the object store. If not supplied via config, it defaults
37
+ * to `payloads`.
38
+ */
39
+ get storeName(): string;
40
+ /**
41
+ * The indexes to create on the store
42
+ */
43
+ private get indexes();
44
+ protected allHandler(): Promise<PayloadWithMeta[]>;
45
+ protected clearHandler(): Promise<void>;
46
+ protected deleteHandler(hashes: Hash[]): Promise<Hash[]>;
47
+ /**
48
+ * Uses an index to get a payload by the index value, but returns the value with the primary key (from the root store)
49
+ * @param db The db instance to use
50
+ * @param storeName The name of the store to use
51
+ * @param indexName The index to use
52
+ * @param key The key to get from the index
53
+ * @returns The primary key and the payload, or undefined if not found
54
+ */
55
+ protected getFromIndexWithPrimaryKey(db: IDBPDatabase<PayloadStore>, storeName: string, indexName: string, key: IDBValidKey): Promise<[number, PayloadWithMeta] | undefined>;
56
+ protected getHandler(hashes: string[]): Promise<PayloadWithMeta[]>;
57
+ protected insertHandler(payloads: Payload[]): Promise<PayloadWithMeta[]>;
58
+ protected startHandler(): Promise<boolean>;
59
+ /**
60
+ * Returns that the desired DB/Store initialized to the correct version
61
+ * @returns The initialized DB
62
+ */
63
+ private getInitializedDb;
64
+ /**
65
+ * Executes a callback with the initialized DB and then closes the db
66
+ * @param callback The method to execute with the initialized DB
67
+ * @returns
68
+ */
69
+ private useDb;
70
+ }
71
+ //# sourceMappingURL=Archivist.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Archivist.d.ts","sourceRoot":"","sources":["../../src/Archivist.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAKL,wBAAwB,EAGzB,MAAM,8BAA8B,CAAA;AAGrC,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAA;AAC7E,OAAO,EAAE,YAAY,EAAU,MAAM,KAAK,CAAA;AAG1C,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAA;AAEnD,MAAM,WAAW,YAAY;IAC3B,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAA;CACrB;AAED,qBACa,kBAAkB,CAC7B,OAAO,SAAS,wB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AAC,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;cAmCxD,aAAa,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;cA0C9D,YAAY;IAQrC;;;OAGG;YACW,gBAAgB;IAiD9B;;;;OAIG;YACW,KAAK;CAWpB"}
@@ -0,0 +1,71 @@
1
+ import { Hash } from '@xylabs/hex';
2
+ import { AbstractArchivist } from '@xyo-network/archivist-abstract';
3
+ import { ArchivistModuleEventData } from '@xyo-network/archivist-model';
4
+ import { Payload, PayloadWithMeta, Schema } from '@xyo-network/payload-model';
5
+ import { IDBPDatabase } from 'idb';
6
+ import { IndexedDbArchivistParams } from './Params';
7
+ export interface PayloadStore {
8
+ [s: string]: Payload;
9
+ }
10
+ export declare class IndexedDbArchivist<TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams, TEventData extends ArchivistModuleEventData = ArchivistModuleEventData> extends AbstractArchivist<TParams, TEventData> {
11
+ static readonly configSchemas: Schema[];
12
+ static readonly defaultConfigSchema: Schema;
13
+ static readonly defaultDbName = "archivist";
14
+ static readonly defaultDbVersion = 1;
15
+ static readonly defaultStoreName = "payloads";
16
+ private static readonly dataHashIndex;
17
+ private static readonly hashIndex;
18
+ private static readonly schemaIndex;
19
+ static readonly hashIndexName: string;
20
+ static readonly dataHashIndexName: string;
21
+ static readonly schemaIndexName: string;
22
+ /**
23
+ * The database name. If not supplied via config, it defaults
24
+ * to the module name (not guaranteed to be unique) and if module
25
+ * name is not supplied, it defaults to `archivist`. This behavior
26
+ * biases towards a single, isolated DB per archivist which seems to
27
+ * make the most sense for 99% of use cases.
28
+ */
29
+ get dbName(): string;
30
+ /**
31
+ * The database version. If not supplied via config, it defaults to 1.
32
+ */
33
+ get dbVersion(): number;
34
+ get queries(): string[];
35
+ /**
36
+ * The name of the object store. If not supplied via config, it defaults
37
+ * to `payloads`.
38
+ */
39
+ get storeName(): string;
40
+ /**
41
+ * The indexes to create on the store
42
+ */
43
+ private get indexes();
44
+ protected allHandler(): Promise<PayloadWithMeta[]>;
45
+ protected clearHandler(): Promise<void>;
46
+ protected deleteHandler(hashes: Hash[]): Promise<Hash[]>;
47
+ /**
48
+ * Uses an index to get a payload by the index value, but returns the value with the primary key (from the root store)
49
+ * @param db The db instance to use
50
+ * @param storeName The name of the store to use
51
+ * @param indexName The index to use
52
+ * @param key The key to get from the index
53
+ * @returns The primary key and the payload, or undefined if not found
54
+ */
55
+ protected getFromIndexWithPrimaryKey(db: IDBPDatabase<PayloadStore>, storeName: string, indexName: string, key: IDBValidKey): Promise<[number, PayloadWithMeta] | undefined>;
56
+ protected getHandler(hashes: string[]): Promise<PayloadWithMeta[]>;
57
+ protected insertHandler(payloads: Payload[]): Promise<PayloadWithMeta[]>;
58
+ protected startHandler(): Promise<boolean>;
59
+ /**
60
+ * Returns that the desired DB/Store initialized to the correct version
61
+ * @returns The initialized DB
62
+ */
63
+ private getInitializedDb;
64
+ /**
65
+ * Executes a callback with the initialized DB and then closes the db
66
+ * @param callback The method to execute with the initialized DB
67
+ * @returns
68
+ */
69
+ private useDb;
70
+ }
71
+ //# sourceMappingURL=Archivist.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Archivist.d.ts","sourceRoot":"","sources":["../../src/Archivist.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAA;AACnE,OAAO,EAKL,wBAAwB,EAGzB,MAAM,8BAA8B,CAAA;AAGrC,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAA;AAC7E,OAAO,EAAE,YAAY,EAAU,MAAM,KAAK,CAAA;AAG1C,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAA;AAEnD,MAAM,WAAW,YAAY;IAC3B,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO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M,EAAE,eAAe,CAAC,GAAG,SAAS,CAAC;cAgBxB,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;cAmCxD,aAAa,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC;cA0C9D,YAAY;IAQrC;;;OAGG;YACW,gBAAgB;IAiD9B;;;;OAIG;YACW,KAAK;CAWpB"}
@@ -0,0 +1,30 @@
1
+ import { ArchivistConfig, IndexDescription } from '@xyo-network/archivist-model';
2
+ import { IndexedDbArchivistSchema } from './Schema';
3
+ export type IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`;
4
+ export declare const IndexedDbArchivistConfigSchema: IndexedDbArchivistConfigSchema;
5
+ export type IndexedDbArchivistConfig = ArchivistConfig<{
6
+ /**
7
+ * The database name
8
+ */
9
+ dbName?: string;
10
+ /**
11
+ * The version of the DB, defaults to 1
12
+ */
13
+ dbVersion?: number;
14
+ schema: IndexedDbArchivistConfigSchema;
15
+ /**
16
+ * The storage configuration
17
+ * // TODO: Hoist to main archivist config
18
+ */
19
+ storage?: {
20
+ /**
21
+ * The indexes to create on the object store
22
+ */
23
+ indexes?: IndexDescription[];
24
+ };
25
+ /**
26
+ * The name of the object store
27
+ */
28
+ storeName?: string;
29
+ }>;
30
+ //# sourceMappingURL=Config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Config.d.ts","sourceRoot":"","sources":["../../src/Config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAA;AAEhF,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAA;AAEnD,MAAM,MAAM,8BAA8B,GAAG,GAAG,wBAAwB,SAAS,CAAA;AACjF,eAAO,MAAM,8BAA8B,EAAE,8BAAqE,CAAA;AAElH,MAAM,MAAM,wBAAwB,GAAG,eAAe,CAAC;IACrD;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IACf;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,MAAM,EAAE,8BAA8B,CAAA;IACtC;;;OAGG;IACH,OAAO,CAAC,EAAE;QACR;;WAEG;QACH,OAAO,CAAC,EAAE,gBAAgB,EAAE,CAAA;KAC7B,CAAA;IACD;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB,CAAC,CAAA"}
@@ -0,0 +1,30 @@
1
+ import { ArchivistConfig, IndexDescription } from '@xyo-network/archivist-model';
2
+ import { IndexedDbArchivistSchema } from './Schema';
3
+ export type IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`;
4
+ export declare const IndexedDbArchivistConfigSchema: IndexedDbArchivistConfigSchema;
5
+ export type IndexedDbArchivistConfig = ArchivistConfig<{
6
+ /**
7
+ * The database name
8
+ */
9
+ dbName?: string;
10
+ /**
11
+ * The version of the DB, defaults to 1
12
+ */
13
+ dbVersion?: number;
14
+ schema: IndexedDbArchivistConfigSchema;
15
+ /**
16
+ * The storage configuration
17
+ * // TODO: Hoist to main archivist config
18
+ */
19
+ storage?: {
20
+ /**
21
+ * The indexes to create on the object store
22
+ */
23
+ indexes?: IndexDescription[];
24
+ };
25
+ /**
26
+ * The name of the object store
27
+ */
28
+ storeName?: string;
29
+ }>;
30
+ //# sourceMappingURL=Config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Config.d.ts","sourceRoot":"","sources":["../../src/Config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAA;AAEhF,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAA;AAEnD,MAAM,MAAM,8BAA8B,GAAG,GAAG,wBAAwB,SAAS,CAAA;AACjF,eAAO,MAAM,8BAA8B,EAAE,8BAAqE,CAAA;AAElH,MAAM,MAAM,wBAAwB,GAAG,eAAe,CAAC;IACrD;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IACf;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,MAAM,EAAE,8BAA8B,CAAA;IACtC;;;OAGG;IACH,OAAO,CAAC,EAAE;QACR;;WAEG;QACH,OAAO,CAAC,EAAE,gBAAgB,EAAE,CAAA;KAC7B,CAAA;IACD;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB,CAAC,CAAA"}
@@ -0,0 +1,30 @@
1
+ import { ArchivistConfig, IndexDescription } from '@xyo-network/archivist-model';
2
+ import { IndexedDbArchivistSchema } from './Schema';
3
+ export type IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`;
4
+ export declare const IndexedDbArchivistConfigSchema: IndexedDbArchivistConfigSchema;
5
+ export type IndexedDbArchivistConfig = ArchivistConfig<{
6
+ /**
7
+ * The database name
8
+ */
9
+ dbName?: string;
10
+ /**
11
+ * The version of the DB, defaults to 1
12
+ */
13
+ dbVersion?: number;
14
+ schema: IndexedDbArchivistConfigSchema;
15
+ /**
16
+ * The storage configuration
17
+ * // TODO: Hoist to main archivist config
18
+ */
19
+ storage?: {
20
+ /**
21
+ * The indexes to create on the object store
22
+ */
23
+ indexes?: IndexDescription[];
24
+ };
25
+ /**
26
+ * The name of the object store
27
+ */
28
+ storeName?: string;
29
+ }>;
30
+ //# sourceMappingURL=Config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Config.d.ts","sourceRoot":"","sources":["../../src/Config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAA;AAEhF,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAA;AAEnD,MAAM,MAAM,8BAA8B,GAAG,GAAG,wBAAwB,SAAS,CAAA;AACjF,eAAO,MAAM,8BAA8B,EAAE,8BAAqE,CAAA;AAElH,MAAM,MAAM,wBAAwB,GAAG,eAAe,CAAC;IACrD;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAA;IACf;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,MAAM,EAAE,8BAA8B,CAAA;IACtC;;;OAGG;IACH,OAAO,CAAC,EAAE;QACR;;WAEG;QACH,OAAO,CAAC,EAAE,gBAAgB,EAAE,CAAA;KAC7B,CAAA;IACD;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB,CAAC,CAAA"}
@@ -0,0 +1,5 @@
1
+ import { ArchivistParams } from '@xyo-network/archivist-model';
2
+ import { AnyConfigSchema } from '@xyo-network/module-model';
3
+ import { IndexedDbArchivistConfig } from './Config';
4
+ export type IndexedDbArchivistParams = ArchivistParams<AnyConfigSchema<IndexedDbArchivistConfig>>;
5
+ //# sourceMappingURL=Params.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Params.d.ts","sourceRoot":"","sources":["../../src/Params.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAA;AAC9D,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAA;AAE3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAA;AAEnD,MAAM,MAAM,wBAAwB,GAAG,eAAe,CAAC,eAAe,CAAC,wBAAwB,CAAC,CAAC,CAAA"}
@@ -0,0 +1,5 @@
1
+ import { ArchivistParams } from '@xyo-network/archivist-model';
2
+ import { AnyConfigSchema } from '@xyo-network/module-model';
3
+ import { IndexedDbArchivistConfig } from './Config';
4
+ export type IndexedDbArchivistParams = ArchivistParams<AnyConfigSchema<IndexedDbArchivistConfig>>;
5
+ //# sourceMappingURL=Params.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Params.d.ts","sourceRoot":"","sources":["../../src/Params.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAA;AAC9D,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAA;AAE3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAA;AAEnD,MAAM,MAAM,wBAAwB,GAAG,eAAe,CAAC,eAAe,CAAC,wBAAwB,CAAC,CAAC,CAAA"}
@@ -0,0 +1,5 @@
1
+ import { ArchivistParams } from '@xyo-network/archivist-model';
2
+ import { AnyConfigSchema } from '@xyo-network/module-model';
3
+ import { IndexedDbArchivistConfig } from './Config';
4
+ export type IndexedDbArchivistParams = ArchivistParams<AnyConfigSchema<IndexedDbArchivistConfig>>;
5
+ //# sourceMappingURL=Params.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Params.d.ts","sourceRoot":"","sources":["../../src/Params.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAA;AAC9D,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAA;AAE3D,OAAO,EAAE,wBAAwB,EAAE,MAAM,UAAU,CAAA;AAEnD,MAAM,MAAM,wBAAwB,GAAG,eAAe,CAAC,eAAe,CAAC,wBAAwB,CAAC,CAAC,CAAA"}
@@ -0,0 +1,3 @@
1
+ export type IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb';
2
+ export declare const IndexedDbArchivistSchema: IndexedDbArchivistSchema;
3
+ //# sourceMappingURL=Schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Schema.d.ts","sourceRoot":"","sources":["../../src/Schema.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,wBAAwB,GAAG,iCAAiC,CAAA;AACxE,eAAO,MAAM,wBAAwB,EAAE,wBAA4D,CAAA"}
@@ -0,0 +1,3 @@
1
+ export type IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb';
2
+ export declare const IndexedDbArchivistSchema: IndexedDbArchivistSchema;
3
+ //# sourceMappingURL=Schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Schema.d.ts","sourceRoot":"","sources":["../../src/Schema.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,wBAAwB,GAAG,iCAAiC,CAAA;AACxE,eAAO,MAAM,wBAAwB,EAAE,wBAA4D,CAAA"}
@@ -0,0 +1,3 @@
1
+ export type IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb';
2
+ export declare const IndexedDbArchivistSchema: IndexedDbArchivistSchema;
3
+ //# sourceMappingURL=Schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Schema.d.ts","sourceRoot":"","sources":["../../src/Schema.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,wBAAwB,GAAG,iCAAiC,CAAA;AACxE,eAAO,MAAM,wBAAwB,EAAE,wBAA4D,CAAA"}
@@ -0,0 +1,320 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var src_exports = {};
23
+ __export(src_exports, {
24
+ IndexedDbArchivist: () => IndexedDbArchivist,
25
+ IndexedDbArchivistConfigSchema: () => IndexedDbArchivistConfigSchema,
26
+ IndexedDbArchivistSchema: () => IndexedDbArchivistSchema
27
+ });
28
+ module.exports = __toCommonJS(src_exports);
29
+
30
+ // src/Archivist.ts
31
+ var import_exists = require("@xylabs/exists");
32
+ var import_archivist_abstract = require("@xyo-network/archivist-abstract");
33
+ var import_archivist_model = require("@xyo-network/archivist-model");
34
+ var import_module_model = require("@xyo-network/module-model");
35
+ var import_payload_builder = require("@xyo-network/payload-builder");
36
+ var import_idb = require("idb");
37
+
38
+ // src/Schema.ts
39
+ var IndexedDbArchivistSchema = "network.xyo.archivist.indexeddb";
40
+
41
+ // src/Config.ts
42
+ var IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`;
43
+
44
+ // src/Archivist.ts
45
+ function _ts_decorate(decorators, target, key, desc) {
46
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
47
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
48
+ r = Reflect.decorate(decorators, target, key, desc);
49
+ else
50
+ for (var i = decorators.length - 1; i >= 0; i--)
51
+ if (d = decorators[i])
52
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
53
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
54
+ }
55
+ __name(_ts_decorate, "_ts_decorate");
56
+ var IndexedDbArchivist = class _IndexedDbArchivist extends import_archivist_abstract.AbstractArchivist {
57
+ static {
58
+ __name(this, "IndexedDbArchivist");
59
+ }
60
+ static configSchemas = [
61
+ ...super.configSchemas,
62
+ IndexedDbArchivistConfigSchema
63
+ ];
64
+ static defaultConfigSchema = IndexedDbArchivistConfigSchema;
65
+ static defaultDbName = "archivist";
66
+ static defaultDbVersion = 1;
67
+ static defaultStoreName = "payloads";
68
+ static dataHashIndex = {
69
+ key: {
70
+ $hash: 1
71
+ },
72
+ multiEntry: false,
73
+ unique: false
74
+ };
75
+ static hashIndex = {
76
+ key: {
77
+ _hash: 1
78
+ },
79
+ multiEntry: false,
80
+ unique: true
81
+ };
82
+ static schemaIndex = {
83
+ key: {
84
+ schema: 1
85
+ },
86
+ multiEntry: false,
87
+ unique: false
88
+ };
89
+ // eslint-disable-next-line @typescript-eslint/member-ordering
90
+ static hashIndexName = (0, import_archivist_model.buildStandardIndexName)(_IndexedDbArchivist.hashIndex);
91
+ // eslint-disable-next-line @typescript-eslint/member-ordering
92
+ static dataHashIndexName = (0, import_archivist_model.buildStandardIndexName)(_IndexedDbArchivist.dataHashIndex);
93
+ // eslint-disable-next-line @typescript-eslint/member-ordering
94
+ static schemaIndexName = (0, import_archivist_model.buildStandardIndexName)(_IndexedDbArchivist.schemaIndex);
95
+ /**
96
+ * The database name. If not supplied via config, it defaults
97
+ * to the module name (not guaranteed to be unique) and if module
98
+ * name is not supplied, it defaults to `archivist`. This behavior
99
+ * biases towards a single, isolated DB per archivist which seems to
100
+ * make the most sense for 99% of use cases.
101
+ */
102
+ get dbName() {
103
+ return this.config?.dbName ?? this.config?.name ?? _IndexedDbArchivist.defaultDbName;
104
+ }
105
+ /**
106
+ * The database version. If not supplied via config, it defaults to 1.
107
+ */
108
+ get dbVersion() {
109
+ return this.config?.dbVersion ?? _IndexedDbArchivist.defaultDbVersion;
110
+ }
111
+ get queries() {
112
+ return [
113
+ import_archivist_model.ArchivistAllQuerySchema,
114
+ import_archivist_model.ArchivistClearQuerySchema,
115
+ import_archivist_model.ArchivistDeleteQuerySchema,
116
+ import_archivist_model.ArchivistInsertQuerySchema,
117
+ ...super.queries
118
+ ];
119
+ }
120
+ /**
121
+ * The name of the object store. If not supplied via config, it defaults
122
+ * to `payloads`.
123
+ */
124
+ get storeName() {
125
+ return this.config?.storeName ?? _IndexedDbArchivist.defaultStoreName;
126
+ }
127
+ /**
128
+ * The indexes to create on the store
129
+ */
130
+ get indexes() {
131
+ return [
132
+ _IndexedDbArchivist.dataHashIndex,
133
+ _IndexedDbArchivist.hashIndex,
134
+ _IndexedDbArchivist.schemaIndex,
135
+ ...this.config?.storage?.indexes ?? []
136
+ ];
137
+ }
138
+ async allHandler() {
139
+ const payloads = await this.useDb((db) => db.getAll(this.storeName));
140
+ return await Promise.all(payloads.map((payload) => import_payload_builder.PayloadBuilder.build(payload)));
141
+ }
142
+ async clearHandler() {
143
+ await this.useDb((db) => db.clear(this.storeName));
144
+ }
145
+ async deleteHandler(hashes) {
146
+ const pairs = await import_payload_builder.PayloadBuilder.hashPairs(await this.getHandler(hashes));
147
+ const hashesToDelete = pairs.flatMap((pair) => [
148
+ pair[0].$hash,
149
+ pair[1]
150
+ ]);
151
+ const distinctHashes = [
152
+ ...new Set(hashesToDelete)
153
+ ];
154
+ return await this.useDb(async (db) => {
155
+ const found = await Promise.all(distinctHashes.map(async (hash) => {
156
+ const existing = await db.getKeyFromIndex(this.storeName, _IndexedDbArchivist.hashIndexName, hash) ?? await db.getKeyFromIndex(this.storeName, _IndexedDbArchivist.dataHashIndexName, hash);
157
+ if (existing) {
158
+ await db.delete(this.storeName, existing);
159
+ return hash;
160
+ }
161
+ }));
162
+ return found.filter(import_exists.exists).filter((hash) => hashes.includes(hash));
163
+ });
164
+ }
165
+ /**
166
+ * Uses an index to get a payload by the index value, but returns the value with the primary key (from the root store)
167
+ * @param db The db instance to use
168
+ * @param storeName The name of the store to use
169
+ * @param indexName The index to use
170
+ * @param key The key to get from the index
171
+ * @returns The primary key and the payload, or undefined if not found
172
+ */
173
+ async getFromIndexWithPrimaryKey(db, storeName, indexName, key) {
174
+ const transaction = db.transaction(storeName, "readonly");
175
+ const store = transaction.objectStore(storeName);
176
+ const index = store.index(indexName);
177
+ const cursor = await index.openCursor(key);
178
+ if (cursor) {
179
+ const singleValue = cursor.value;
180
+ if (typeof cursor.primaryKey !== "number") {
181
+ throw new TypeError("primaryKey must be a number");
182
+ }
183
+ return [
184
+ cursor.primaryKey,
185
+ singleValue
186
+ ];
187
+ }
188
+ }
189
+ async getHandler(hashes) {
190
+ const payloads = await this.useDb((db) => Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, _IndexedDbArchivist.hashIndexName, hash))));
191
+ const payloadsFromDataHashes = await this.useDb((db) => Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, _IndexedDbArchivist.dataHashIndexName, hash))));
192
+ const found = /* @__PURE__ */ new Set();
193
+ const payloadsFromHash = payloads.filter(import_exists.exists).filter(([_key, payload]) => {
194
+ if (found.has(payload.$hash)) {
195
+ return false;
196
+ } else {
197
+ found.add(payload.$hash);
198
+ return true;
199
+ }
200
+ });
201
+ const payloadsFromDataHash = payloadsFromDataHashes.filter(import_exists.exists).filter(([_key, payload]) => {
202
+ if (found.has(payload.$hash)) {
203
+ return false;
204
+ } else {
205
+ found.add(payload.$hash);
206
+ return true;
207
+ }
208
+ });
209
+ return (
210
+ // Merge what we found from the hash and data hash indexes
211
+ [
212
+ ...payloadsFromHash,
213
+ ...payloadsFromDataHash
214
+ ].sort((a, b) => a[0] - b[0]).map(([_key, payload]) => payload)
215
+ );
216
+ }
217
+ async insertHandler(payloads) {
218
+ const pairs = await import_payload_builder.PayloadBuilder.hashPairs(payloads);
219
+ const db = await this.getInitializedDb();
220
+ try {
221
+ const inserted = await Promise.all(pairs.map(async ([payload, _hash]) => {
222
+ const existing = (await this.getHandler([
223
+ _hash
224
+ ])).shift();
225
+ if (existing) {
226
+ return;
227
+ }
228
+ const tx = db.transaction(this.storeName, "readwrite");
229
+ try {
230
+ const store = tx.objectStore(this.storeName);
231
+ const existingTopHash = await store.index(_IndexedDbArchivist.hashIndexName).get(_hash);
232
+ if (!existingTopHash) {
233
+ await store.put({
234
+ ...payload,
235
+ _hash
236
+ });
237
+ }
238
+ return payload;
239
+ } finally {
240
+ await tx.done;
241
+ }
242
+ }));
243
+ return inserted.filter(import_exists.exists);
244
+ } finally {
245
+ db.close();
246
+ }
247
+ }
248
+ async startHandler() {
249
+ await super.startHandler();
250
+ await this.useDb(() => {
251
+ });
252
+ return true;
253
+ }
254
+ /**
255
+ * Returns that the desired DB/Store initialized to the correct version
256
+ * @returns The initialized DB
257
+ */
258
+ async getInitializedDb() {
259
+ const { dbName, dbVersion, indexes, storeName, logger } = this;
260
+ const db = await (0, import_idb.openDB)(dbName, dbVersion, {
261
+ blocked(currentVersion, blockedVersion, event) {
262
+ logger.warn(`IndexedDbArchivist: Blocked from upgrading from ${currentVersion} to ${blockedVersion}`, event);
263
+ },
264
+ blocking(currentVersion, blockedVersion, event) {
265
+ logger.warn(`IndexedDbArchivist: Blocking upgrade from ${currentVersion} to ${blockedVersion}`, event);
266
+ },
267
+ terminated() {
268
+ logger.log("IndexedDbArchivist: Terminated");
269
+ },
270
+ upgrade(database, oldVersion, newVersion, transaction) {
271
+ if (oldVersion !== newVersion) {
272
+ logger.log(`IndexedDbArchivist: Upgrading from ${oldVersion} to ${newVersion}`);
273
+ const objectStores = transaction.objectStoreNames;
274
+ for (const name of objectStores) {
275
+ try {
276
+ database.deleteObjectStore(name);
277
+ } catch {
278
+ logger.log(`IndexedDbArchivist: Failed to delete existing object store ${name}`);
279
+ }
280
+ }
281
+ }
282
+ const store = database.createObjectStore(storeName, {
283
+ // If it isn't explicitly set, create a value by auto incrementing.
284
+ autoIncrement: true
285
+ });
286
+ store.name = storeName;
287
+ for (const { key, multiEntry, unique } of indexes) {
288
+ const indexKeys = Object.keys(key);
289
+ const keys = indexKeys.length === 1 ? indexKeys[0] : indexKeys;
290
+ const indexName = (0, import_archivist_model.buildStandardIndexName)({
291
+ key,
292
+ unique
293
+ });
294
+ store.createIndex(indexName, keys, {
295
+ multiEntry,
296
+ unique
297
+ });
298
+ }
299
+ }
300
+ });
301
+ return db;
302
+ }
303
+ /**
304
+ * Executes a callback with the initialized DB and then closes the db
305
+ * @param callback The method to execute with the initialized DB
306
+ * @returns
307
+ */
308
+ async useDb(callback) {
309
+ const db = await this.getInitializedDb();
310
+ try {
311
+ return await callback(db);
312
+ } finally {
313
+ db.close();
314
+ }
315
+ }
316
+ };
317
+ IndexedDbArchivist = _ts_decorate([
318
+ (0, import_module_model.creatableModule)()
319
+ ], IndexedDbArchivist);
320
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/index.ts","../../src/Archivist.ts","../../src/Schema.ts","../../src/Config.ts"],"sourcesContent":["export * from './Archivist'\nexport * from './Config'\nexport * from './Params'\nexport * from './Schema'\n","import { exists } from '@xylabs/exists'\nimport { Hash } from '@xylabs/hex'\nimport { AbstractArchivist } from '@xyo-network/archivist-abstract'\nimport {\n ArchivistAllQuerySchema,\n ArchivistClearQuerySchema,\n ArchivistDeleteQuerySchema,\n ArchivistInsertQuerySchema,\n ArchivistModuleEventData,\n buildStandardIndexName,\n IndexDescription,\n} from '@xyo-network/archivist-model'\nimport { creatableModule } from '@xyo-network/module-model'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport { Payload, PayloadWithMeta, Schema } from '@xyo-network/payload-model'\nimport { IDBPDatabase, openDB } from 'idb'\n\nimport { IndexedDbArchivistConfigSchema } from './Config'\nimport { IndexedDbArchivistParams } from './Params'\n\nexport interface PayloadStore {\n [s: string]: Payload\n}\n\n@creatableModule()\nexport class IndexedDbArchivist<\n TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams,\n TEventData extends ArchivistModuleEventData = ArchivistModuleEventData,\n> extends AbstractArchivist<TParams, TEventData> {\n static override readonly configSchemas: Schema[] = [...super.configSchemas, IndexedDbArchivistConfigSchema]\n static override readonly defaultConfigSchema: Schema = IndexedDbArchivistConfigSchema\n static readonly defaultDbName = 'archivist'\n static readonly defaultDbVersion = 1\n static readonly defaultStoreName = 'payloads'\n private static readonly dataHashIndex: IndexDescription = { key: { $hash: 1 }, multiEntry: false, unique: false }\n private static readonly hashIndex: IndexDescription = { key: { _hash: 1 }, multiEntry: false, unique: true }\n private static readonly schemaIndex: IndexDescription = { key: { schema: 1 }, multiEntry: false, unique: false }\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly hashIndexName = buildStandardIndexName(IndexedDbArchivist.hashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly dataHashIndexName = buildStandardIndexName(IndexedDbArchivist.dataHashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly schemaIndexName = buildStandardIndexName(IndexedDbArchivist.schemaIndex)\n\n /**\n * The database name. If not supplied via config, it defaults\n * to the module name (not guaranteed to be unique) and if module\n * name is not supplied, it defaults to `archivist`. This behavior\n * biases towards a single, isolated DB per archivist which seems to\n * make the most sense for 99% of use cases.\n */\n get dbName() {\n return this.config?.dbName ?? this.config?.name ?? IndexedDbArchivist.defaultDbName\n }\n\n /**\n * The database version. If not supplied via config, it defaults to 1.\n */\n get dbVersion() {\n return this.config?.dbVersion ?? IndexedDbArchivist.defaultDbVersion\n }\n\n override get queries() {\n return [ArchivistAllQuerySchema, ArchivistClearQuerySchema, ArchivistDeleteQuerySchema, ArchivistInsertQuerySchema, ...super.queries]\n }\n\n /**\n * The name of the object store. If not supplied via config, it defaults\n * to `payloads`.\n */\n get storeName() {\n return this.config?.storeName ?? IndexedDbArchivist.defaultStoreName\n }\n\n /**\n * The indexes to create on the store\n */\n private get indexes() {\n return [IndexedDbArchivist.dataHashIndex, IndexedDbArchivist.hashIndex, IndexedDbArchivist.schemaIndex, ...(this.config?.storage?.indexes ?? [])]\n }\n\n protected override async allHandler(): Promise<PayloadWithMeta[]> {\n // Get all payloads from the store\n const payloads = await this.useDb((db) => db.getAll(this.storeName))\n // Remove any metadata before returning to the client\n return await Promise.all(payloads.map((payload) => PayloadBuilder.build(payload)))\n }\n\n protected override async clearHandler(): Promise<void> {\n await this.useDb((db) => db.clear(this.storeName))\n }\n\n protected override async deleteHandler(hashes: Hash[]): Promise<Hash[]> {\n const pairs = await PayloadBuilder.hashPairs(await this.getHandler(hashes))\n const hashesToDelete = pairs.flatMap<Hash>((pair) => [pair[0].$hash, pair[1]])\n // Remove any duplicates\n const distinctHashes = [...new Set(hashesToDelete)]\n return await this.useDb(async (db) => {\n // Only return hashes that were successfully deleted\n const found = await Promise.all(\n distinctHashes.map(async (hash) => {\n // Check if the hash exists\n const existing =\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.hashIndexName, hash)) ??\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.dataHashIndexName, hash))\n // If it does exist\n if (existing) {\n // Delete it\n await db.delete(this.storeName, existing)\n // Return the hash so it gets added to the list of deleted hashes\n return hash\n }\n }),\n )\n return found.filter(exists).filter((hash) => hashes.includes(hash))\n })\n }\n\n /**\n * Uses an index to get a payload by the index value, but returns the value with the primary key (from the root store)\n * @param db The db instance to use\n * @param storeName The name of the store to use\n * @param indexName The index to use\n * @param key The key to get from the index\n * @returns The primary key and the payload, or undefined if not found\n */\n protected async getFromIndexWithPrimaryKey(\n db: IDBPDatabase<PayloadStore>,\n storeName: string,\n indexName: string,\n key: IDBValidKey,\n ): Promise<[number, PayloadWithMeta] | undefined> {\n const transaction = db.transaction(storeName, 'readonly')\n const store = transaction.objectStore(storeName)\n const index = store.index(indexName)\n const cursor = await index.openCursor(key)\n if (cursor) {\n const singleValue = cursor.value\n // NOTE: It's known to be a number because we are using IndexedDB supplied auto-incrementing keys\n if (typeof cursor.primaryKey !== 'number') {\n throw new TypeError('primaryKey must be a number')\n }\n\n return [cursor.primaryKey, singleValue]\n }\n }\n\n protected override async getHandler(hashes: string[]): Promise<PayloadWithMeta[]> {\n const payloads = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.hashIndexName, hash))),\n )\n const payloadsFromDataHashes = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.dataHashIndexName, hash))),\n )\n //filter out duplicates\n const found = new Set<string>()\n const payloadsFromHash = payloads.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n const payloadsFromDataHash = payloadsFromDataHashes.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n return (\n // Merge what we found from the hash and data hash indexes\n [...payloadsFromHash, ...payloadsFromDataHash]\n // Sort in ascending order by primary key (for semi-predictable ordering in terms of insertion order)\n .sort((a, b) => a[0] - b[0])\n // Return just the payloads\n .map(([_key, payload]) => payload)\n )\n }\n\n protected override async insertHandler(payloads: Payload[]): Promise<PayloadWithMeta[]> {\n const pairs = await PayloadBuilder.hashPairs(payloads)\n\n const db = await this.getInitializedDb()\n try {\n // Only return the payloads that were successfully inserted\n const inserted = await Promise.all(\n pairs.map(async ([payload, _hash]) => {\n const existing = (await this.getHandler([_hash])).shift()\n if (existing) {\n return\n }\n // Perform each insert via a transaction to ensure it is atomic\n // with respect to checking for the pre-existence of the hash.\n // This is done to preserve iteration via insertion order.\n const tx = db.transaction(this.storeName, 'readwrite')\n try {\n // Get the object store\n const store = tx.objectStore(this.storeName)\n\n // Check if the hash already exists\n const existingTopHash = await store.index(IndexedDbArchivist.hashIndexName).get(_hash)\n // If it does not already exist\n if (!existingTopHash) {\n // Insert the payload\n await store.put({ ...payload, _hash })\n }\n\n // Return it so it gets added to the list of inserted payloads\n return payload\n } finally {\n // Close the transaction\n await tx.done\n }\n }),\n )\n return inserted.filter(exists)\n } finally {\n db.close()\n }\n }\n\n protected override async startHandler() {\n await super.startHandler()\n // NOTE: We could defer this creation to first access but we\n // want to fail fast here in case something is wrong\n await this.useDb(() => {})\n return true\n }\n\n /**\n * Returns that the desired DB/Store initialized to the correct version\n * @returns The initialized DB\n */\n private async getInitializedDb(): Promise<IDBPDatabase<PayloadStore>> {\n const { dbName, dbVersion, indexes, storeName, logger } = this\n const db = await openDB<PayloadStore>(dbName, dbVersion, {\n blocked(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocked from upgrading from ${currentVersion} to ${blockedVersion}`, event)\n },\n blocking(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocking upgrade from ${currentVersion} to ${blockedVersion}`, event)\n },\n terminated() {\n logger.log('IndexedDbArchivist: Terminated')\n },\n upgrade(database, oldVersion, newVersion, transaction) {\n // NOTE: This is called whenever the DB is created/updated. We could simply ensure the desired end\n // state but, out of an abundance of caution, we will just delete (so we know where we are starting\n // from a known good point) and recreate the desired state. This prioritizes resilience over data\n // retention but we can revisit that tradeoff when it becomes limiting. Because distributed browser\n // state is extremely hard to debug, this seems like fair tradeoff for now.\n if (oldVersion !== newVersion) {\n logger.log(`IndexedDbArchivist: Upgrading from ${oldVersion} to ${newVersion}`)\n // Delete any existing databases that are not the current version\n const objectStores = transaction.objectStoreNames\n for (const name of objectStores) {\n try {\n database.deleteObjectStore(name)\n } catch {\n logger.log(`IndexedDbArchivist: Failed to delete existing object store ${name}`)\n }\n }\n }\n // Create the store\n const store = database.createObjectStore(storeName, {\n // If it isn't explicitly set, create a value by auto incrementing.\n autoIncrement: true,\n })\n // Name the store\n store.name = storeName\n // Create an index on the hash\n for (const { key, multiEntry, unique } of indexes) {\n const indexKeys = Object.keys(key)\n const keys = indexKeys.length === 1 ? indexKeys[0] : indexKeys\n const indexName = buildStandardIndexName({ key, unique })\n store.createIndex(indexName, keys, { multiEntry, unique })\n }\n },\n })\n return db\n }\n\n /**\n * Executes a callback with the initialized DB and then closes the db\n * @param callback The method to execute with the initialized DB\n * @returns\n */\n private async useDb<T>(callback: (db: IDBPDatabase<PayloadStore>) => Promise<T> | T): Promise<T> {\n // Get the initialized DB\n const db = await this.getInitializedDb()\n try {\n // Perform the callback\n return await callback(db)\n } finally {\n // Close the DB\n db.close()\n }\n }\n}\n","export type IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\nexport const IndexedDbArchivistSchema: IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\n","import { ArchivistConfig, IndexDescription } from '@xyo-network/archivist-model'\n\nimport { IndexedDbArchivistSchema } from './Schema'\n\nexport type IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\nexport const IndexedDbArchivistConfigSchema: IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\n\nexport type IndexedDbArchivistConfig = ArchivistConfig<{\n /**\n * The database name\n */\n dbName?: string\n /**\n * The version of the DB, defaults to 1\n */\n dbVersion?: number\n schema: IndexedDbArchivistConfigSchema\n /**\n * The storage configuration\n * // TODO: Hoist to main archivist config\n */\n storage?: {\n /**\n * The indexes to create on the object store\n */\n indexes?: IndexDescription[]\n }\n /**\n * The name of the object store\n */\n storeName?: string\n}>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;ACAA,oBAAuB;AAEvB,gCAAkC;AAClC,6BAQO;AACP,0BAAgC;AAChC,6BAA+B;AAE/B,iBAAqC;;;ACd9B,IAAMA,2BAAqD;;;ACI3D,IAAMC,iCAAiE,GAAGC,wBAAAA;;;;;;;;;;;;;;AFoB1E,IAAMC,qBAAN,MAAMA,4BAGHC,4CAAAA;SAAAA;;;EACR,OAAyBC,gBAA0B;OAAI,MAAMA;IAAeC;;EAC5E,OAAyBC,sBAA8BD;EACvD,OAAgBE,gBAAgB;EAChC,OAAgBC,mBAAmB;EACnC,OAAgBC,mBAAmB;EACnC,OAAwBC,gBAAkC;IAAEC,KAAK;MAAEC,OAAO;IAAE;IAAGC,YAAY;IAAOC,QAAQ;EAAM;EAChH,OAAwBC,YAA8B;IAAEJ,KAAK;MAAEK,OAAO;IAAE;IAAGH,YAAY;IAAOC,QAAQ;EAAK;EAC3G,OAAwBG,cAAgC;IAAEN,KAAK;MAAEO,QAAQ;IAAE;IAAGL,YAAY;IAAOC,QAAQ;EAAM;;EAE/G,OAAgBK,oBAAgBC,+CAAuBlB,oBAAmBa,SAAS;;EAEnF,OAAgBM,wBAAoBD,+CAAuBlB,oBAAmBQ,aAAa;;EAE3F,OAAgBY,sBAAkBF,+CAAuBlB,oBAAmBe,WAAW;;;;;;;;EASvF,IAAIM,SAAS;AACX,WAAO,KAAKC,QAAQD,UAAU,KAAKC,QAAQC,QAAQvB,oBAAmBK;EACxE;;;;EAKA,IAAImB,YAAY;AACd,WAAO,KAAK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;UAAO,CAAA;QAC1D;MACF;IACF,CAAA;AACA,WAAOwB;EACT;;;;;;EAOA,MAAcD,MAASqF,UAA0E;AAE/F,UAAMpF,KAAK,MAAM,KAAKkD,iBAAgB;AACtC,QAAI;AAEF,aAAO,MAAMkC,SAASpF,EAAAA;IACxB,UAAA;AAEEA,SAAG0D,MAAK;IACV;EACF;AACF;AApRa9F,qBAAAA,aAAAA;MADZyH,qCAAAA;GACYzH,kBAAAA;","names":["IndexedDbArchivistSchema","IndexedDbArchivistConfigSchema","IndexedDbArchivistSchema","IndexedDbArchivist","AbstractArchivist","configSchemas","IndexedDbArchivistConfigSchema","defaultConfigSchema","defaultDbName","defaultDbVersion","defaultStoreName","dataHashIndex","key","$hash","multiEntry","unique","hashIndex","_hash","schemaIndex","schema","hashIndexName","buildStandardIndexName","dataHashIndexName","schemaIndexName","dbName","config","name","dbVersion","queries","ArchivistAllQuerySchema","ArchivistClearQuerySchema","ArchivistDeleteQuerySchema","ArchivistInsertQuerySchema","storeName","indexes","storage","allHandler","payloads","useDb","db","getAll","Promise","all","map","payload","PayloadBuilder","build","clearHandler","clear","deleteHandler","hashes","pairs","hashPairs","getHandler","hashesToDelete","flatMap","pair","distinctHashes","Set","found","hash","existing","getKeyFromIndex","delete","filter","exists","includes","getFromIndexWithPrimaryKey","indexName","transaction","store","objectStore","index","cursor","openCursor","singleValue","value","primaryKey","TypeError","payloadsFromDataHashes","payloadsFromHash","_key","has","add","payloadsFromDataHash","sort","a","b","insertHandler","getInitializedDb","inserted","shift","tx","existingTopHash","get","put","done","close","startHandler","logger","openDB","blocked","currentVersion","blockedVersion","event","warn","blocking","terminated","log","upgrade","database","oldVersion","newVersion","objectStores","objectStoreNames","deleteObjectStore","createObjectStore","autoIncrement","indexKeys","Object","keys","length","createIndex","callback","creatableModule"]}
@@ -0,0 +1,5 @@
1
+ export * from './Archivist';
2
+ export * from './Config';
3
+ export * from './Params';
4
+ export * from './Schema';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAA;AAC3B,cAAc,UAAU,CAAA;AACxB,cAAc,UAAU,CAAA;AACxB,cAAc,UAAU,CAAA"}
@@ -0,0 +1,5 @@
1
+ export * from './Archivist';
2
+ export * from './Config';
3
+ export * from './Params';
4
+ export * from './Schema';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAA;AAC3B,cAAc,UAAU,CAAA;AACxB,cAAc,UAAU,CAAA;AACxB,cAAc,UAAU,CAAA"}
@@ -0,0 +1,5 @@
1
+ export * from './Archivist';
2
+ export * from './Config';
3
+ export * from './Params';
4
+ export * from './Schema';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAA;AAC3B,cAAc,UAAU,CAAA;AACxB,cAAc,UAAU,CAAA;AACxB,cAAc,UAAU,CAAA"}
@@ -0,0 +1,299 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/Archivist.ts
5
+ import { exists } from "@xylabs/exists";
6
+ import { AbstractArchivist } from "@xyo-network/archivist-abstract";
7
+ import { ArchivistAllQuerySchema, ArchivistClearQuerySchema, ArchivistDeleteQuerySchema, ArchivistInsertQuerySchema, buildStandardIndexName } from "@xyo-network/archivist-model";
8
+ import { creatableModule } from "@xyo-network/module-model";
9
+ import { PayloadBuilder } from "@xyo-network/payload-builder";
10
+ import { openDB } from "idb";
11
+
12
+ // src/Schema.ts
13
+ var IndexedDbArchivistSchema = "network.xyo.archivist.indexeddb";
14
+
15
+ // src/Config.ts
16
+ var IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`;
17
+
18
+ // src/Archivist.ts
19
+ function _ts_decorate(decorators, target, key, desc) {
20
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
21
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
22
+ r = Reflect.decorate(decorators, target, key, desc);
23
+ else
24
+ for (var i = decorators.length - 1; i >= 0; i--)
25
+ if (d = decorators[i])
26
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
27
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
28
+ }
29
+ __name(_ts_decorate, "_ts_decorate");
30
+ var IndexedDbArchivist = class _IndexedDbArchivist extends AbstractArchivist {
31
+ static {
32
+ __name(this, "IndexedDbArchivist");
33
+ }
34
+ static configSchemas = [
35
+ ...super.configSchemas,
36
+ IndexedDbArchivistConfigSchema
37
+ ];
38
+ static defaultConfigSchema = IndexedDbArchivistConfigSchema;
39
+ static defaultDbName = "archivist";
40
+ static defaultDbVersion = 1;
41
+ static defaultStoreName = "payloads";
42
+ static dataHashIndex = {
43
+ key: {
44
+ $hash: 1
45
+ },
46
+ multiEntry: false,
47
+ unique: false
48
+ };
49
+ static hashIndex = {
50
+ key: {
51
+ _hash: 1
52
+ },
53
+ multiEntry: false,
54
+ unique: true
55
+ };
56
+ static schemaIndex = {
57
+ key: {
58
+ schema: 1
59
+ },
60
+ multiEntry: false,
61
+ unique: false
62
+ };
63
+ // eslint-disable-next-line @typescript-eslint/member-ordering
64
+ static hashIndexName = buildStandardIndexName(_IndexedDbArchivist.hashIndex);
65
+ // eslint-disable-next-line @typescript-eslint/member-ordering
66
+ static dataHashIndexName = buildStandardIndexName(_IndexedDbArchivist.dataHashIndex);
67
+ // eslint-disable-next-line @typescript-eslint/member-ordering
68
+ static schemaIndexName = buildStandardIndexName(_IndexedDbArchivist.schemaIndex);
69
+ /**
70
+ * The database name. If not supplied via config, it defaults
71
+ * to the module name (not guaranteed to be unique) and if module
72
+ * name is not supplied, it defaults to `archivist`. This behavior
73
+ * biases towards a single, isolated DB per archivist which seems to
74
+ * make the most sense for 99% of use cases.
75
+ */
76
+ get dbName() {
77
+ return this.config?.dbName ?? this.config?.name ?? _IndexedDbArchivist.defaultDbName;
78
+ }
79
+ /**
80
+ * The database version. If not supplied via config, it defaults to 1.
81
+ */
82
+ get dbVersion() {
83
+ return this.config?.dbVersion ?? _IndexedDbArchivist.defaultDbVersion;
84
+ }
85
+ get queries() {
86
+ return [
87
+ ArchivistAllQuerySchema,
88
+ ArchivistClearQuerySchema,
89
+ ArchivistDeleteQuerySchema,
90
+ ArchivistInsertQuerySchema,
91
+ ...super.queries
92
+ ];
93
+ }
94
+ /**
95
+ * The name of the object store. If not supplied via config, it defaults
96
+ * to `payloads`.
97
+ */
98
+ get storeName() {
99
+ return this.config?.storeName ?? _IndexedDbArchivist.defaultStoreName;
100
+ }
101
+ /**
102
+ * The indexes to create on the store
103
+ */
104
+ get indexes() {
105
+ return [
106
+ _IndexedDbArchivist.dataHashIndex,
107
+ _IndexedDbArchivist.hashIndex,
108
+ _IndexedDbArchivist.schemaIndex,
109
+ ...this.config?.storage?.indexes ?? []
110
+ ];
111
+ }
112
+ async allHandler() {
113
+ const payloads = await this.useDb((db) => db.getAll(this.storeName));
114
+ return await Promise.all(payloads.map((payload) => PayloadBuilder.build(payload)));
115
+ }
116
+ async clearHandler() {
117
+ await this.useDb((db) => db.clear(this.storeName));
118
+ }
119
+ async deleteHandler(hashes) {
120
+ const pairs = await PayloadBuilder.hashPairs(await this.getHandler(hashes));
121
+ const hashesToDelete = pairs.flatMap((pair) => [
122
+ pair[0].$hash,
123
+ pair[1]
124
+ ]);
125
+ const distinctHashes = [
126
+ ...new Set(hashesToDelete)
127
+ ];
128
+ return await this.useDb(async (db) => {
129
+ const found = await Promise.all(distinctHashes.map(async (hash) => {
130
+ const existing = await db.getKeyFromIndex(this.storeName, _IndexedDbArchivist.hashIndexName, hash) ?? await db.getKeyFromIndex(this.storeName, _IndexedDbArchivist.dataHashIndexName, hash);
131
+ if (existing) {
132
+ await db.delete(this.storeName, existing);
133
+ return hash;
134
+ }
135
+ }));
136
+ return found.filter(exists).filter((hash) => hashes.includes(hash));
137
+ });
138
+ }
139
+ /**
140
+ * Uses an index to get a payload by the index value, but returns the value with the primary key (from the root store)
141
+ * @param db The db instance to use
142
+ * @param storeName The name of the store to use
143
+ * @param indexName The index to use
144
+ * @param key The key to get from the index
145
+ * @returns The primary key and the payload, or undefined if not found
146
+ */
147
+ async getFromIndexWithPrimaryKey(db, storeName, indexName, key) {
148
+ const transaction = db.transaction(storeName, "readonly");
149
+ const store = transaction.objectStore(storeName);
150
+ const index = store.index(indexName);
151
+ const cursor = await index.openCursor(key);
152
+ if (cursor) {
153
+ const singleValue = cursor.value;
154
+ if (typeof cursor.primaryKey !== "number") {
155
+ throw new TypeError("primaryKey must be a number");
156
+ }
157
+ return [
158
+ cursor.primaryKey,
159
+ singleValue
160
+ ];
161
+ }
162
+ }
163
+ async getHandler(hashes) {
164
+ const payloads = await this.useDb((db) => Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, _IndexedDbArchivist.hashIndexName, hash))));
165
+ const payloadsFromDataHashes = await this.useDb((db) => Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, _IndexedDbArchivist.dataHashIndexName, hash))));
166
+ const found = /* @__PURE__ */ new Set();
167
+ const payloadsFromHash = payloads.filter(exists).filter(([_key, payload]) => {
168
+ if (found.has(payload.$hash)) {
169
+ return false;
170
+ } else {
171
+ found.add(payload.$hash);
172
+ return true;
173
+ }
174
+ });
175
+ const payloadsFromDataHash = payloadsFromDataHashes.filter(exists).filter(([_key, payload]) => {
176
+ if (found.has(payload.$hash)) {
177
+ return false;
178
+ } else {
179
+ found.add(payload.$hash);
180
+ return true;
181
+ }
182
+ });
183
+ return (
184
+ // Merge what we found from the hash and data hash indexes
185
+ [
186
+ ...payloadsFromHash,
187
+ ...payloadsFromDataHash
188
+ ].sort((a, b) => a[0] - b[0]).map(([_key, payload]) => payload)
189
+ );
190
+ }
191
+ async insertHandler(payloads) {
192
+ const pairs = await PayloadBuilder.hashPairs(payloads);
193
+ const db = await this.getInitializedDb();
194
+ try {
195
+ const inserted = await Promise.all(pairs.map(async ([payload, _hash]) => {
196
+ const existing = (await this.getHandler([
197
+ _hash
198
+ ])).shift();
199
+ if (existing) {
200
+ return;
201
+ }
202
+ const tx = db.transaction(this.storeName, "readwrite");
203
+ try {
204
+ const store = tx.objectStore(this.storeName);
205
+ const existingTopHash = await store.index(_IndexedDbArchivist.hashIndexName).get(_hash);
206
+ if (!existingTopHash) {
207
+ await store.put({
208
+ ...payload,
209
+ _hash
210
+ });
211
+ }
212
+ return payload;
213
+ } finally {
214
+ await tx.done;
215
+ }
216
+ }));
217
+ return inserted.filter(exists);
218
+ } finally {
219
+ db.close();
220
+ }
221
+ }
222
+ async startHandler() {
223
+ await super.startHandler();
224
+ await this.useDb(() => {
225
+ });
226
+ return true;
227
+ }
228
+ /**
229
+ * Returns that the desired DB/Store initialized to the correct version
230
+ * @returns The initialized DB
231
+ */
232
+ async getInitializedDb() {
233
+ const { dbName, dbVersion, indexes, storeName, logger } = this;
234
+ const db = await openDB(dbName, dbVersion, {
235
+ blocked(currentVersion, blockedVersion, event) {
236
+ logger.warn(`IndexedDbArchivist: Blocked from upgrading from ${currentVersion} to ${blockedVersion}`, event);
237
+ },
238
+ blocking(currentVersion, blockedVersion, event) {
239
+ logger.warn(`IndexedDbArchivist: Blocking upgrade from ${currentVersion} to ${blockedVersion}`, event);
240
+ },
241
+ terminated() {
242
+ logger.log("IndexedDbArchivist: Terminated");
243
+ },
244
+ upgrade(database, oldVersion, newVersion, transaction) {
245
+ if (oldVersion !== newVersion) {
246
+ logger.log(`IndexedDbArchivist: Upgrading from ${oldVersion} to ${newVersion}`);
247
+ const objectStores = transaction.objectStoreNames;
248
+ for (const name of objectStores) {
249
+ try {
250
+ database.deleteObjectStore(name);
251
+ } catch {
252
+ logger.log(`IndexedDbArchivist: Failed to delete existing object store ${name}`);
253
+ }
254
+ }
255
+ }
256
+ const store = database.createObjectStore(storeName, {
257
+ // If it isn't explicitly set, create a value by auto incrementing.
258
+ autoIncrement: true
259
+ });
260
+ store.name = storeName;
261
+ for (const { key, multiEntry, unique } of indexes) {
262
+ const indexKeys = Object.keys(key);
263
+ const keys = indexKeys.length === 1 ? indexKeys[0] : indexKeys;
264
+ const indexName = buildStandardIndexName({
265
+ key,
266
+ unique
267
+ });
268
+ store.createIndex(indexName, keys, {
269
+ multiEntry,
270
+ unique
271
+ });
272
+ }
273
+ }
274
+ });
275
+ return db;
276
+ }
277
+ /**
278
+ * Executes a callback with the initialized DB and then closes the db
279
+ * @param callback The method to execute with the initialized DB
280
+ * @returns
281
+ */
282
+ async useDb(callback) {
283
+ const db = await this.getInitializedDb();
284
+ try {
285
+ return await callback(db);
286
+ } finally {
287
+ db.close();
288
+ }
289
+ }
290
+ };
291
+ IndexedDbArchivist = _ts_decorate([
292
+ creatableModule()
293
+ ], IndexedDbArchivist);
294
+ export {
295
+ IndexedDbArchivist,
296
+ IndexedDbArchivistConfigSchema,
297
+ IndexedDbArchivistSchema
298
+ };
299
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/Archivist.ts","../../src/Schema.ts","../../src/Config.ts"],"sourcesContent":["import { exists } from '@xylabs/exists'\nimport { Hash } from '@xylabs/hex'\nimport { AbstractArchivist } from '@xyo-network/archivist-abstract'\nimport {\n ArchivistAllQuerySchema,\n ArchivistClearQuerySchema,\n ArchivistDeleteQuerySchema,\n ArchivistInsertQuerySchema,\n ArchivistModuleEventData,\n buildStandardIndexName,\n IndexDescription,\n} from '@xyo-network/archivist-model'\nimport { creatableModule } from '@xyo-network/module-model'\nimport { PayloadBuilder } from '@xyo-network/payload-builder'\nimport { Payload, PayloadWithMeta, Schema } from '@xyo-network/payload-model'\nimport { IDBPDatabase, openDB } from 'idb'\n\nimport { IndexedDbArchivistConfigSchema } from './Config'\nimport { IndexedDbArchivistParams } from './Params'\n\nexport interface PayloadStore {\n [s: string]: Payload\n}\n\n@creatableModule()\nexport class IndexedDbArchivist<\n TParams extends IndexedDbArchivistParams = IndexedDbArchivistParams,\n TEventData extends ArchivistModuleEventData = ArchivistModuleEventData,\n> extends AbstractArchivist<TParams, TEventData> {\n static override readonly configSchemas: Schema[] = [...super.configSchemas, IndexedDbArchivistConfigSchema]\n static override readonly defaultConfigSchema: Schema = IndexedDbArchivistConfigSchema\n static readonly defaultDbName = 'archivist'\n static readonly defaultDbVersion = 1\n static readonly defaultStoreName = 'payloads'\n private static readonly dataHashIndex: IndexDescription = { key: { $hash: 1 }, multiEntry: false, unique: false }\n private static readonly hashIndex: IndexDescription = { key: { _hash: 1 }, multiEntry: false, unique: true }\n private static readonly schemaIndex: IndexDescription = { key: { schema: 1 }, multiEntry: false, unique: false }\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly hashIndexName = buildStandardIndexName(IndexedDbArchivist.hashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly dataHashIndexName = buildStandardIndexName(IndexedDbArchivist.dataHashIndex)\n // eslint-disable-next-line @typescript-eslint/member-ordering\n static readonly schemaIndexName = buildStandardIndexName(IndexedDbArchivist.schemaIndex)\n\n /**\n * The database name. If not supplied via config, it defaults\n * to the module name (not guaranteed to be unique) and if module\n * name is not supplied, it defaults to `archivist`. This behavior\n * biases towards a single, isolated DB per archivist which seems to\n * make the most sense for 99% of use cases.\n */\n get dbName() {\n return this.config?.dbName ?? this.config?.name ?? IndexedDbArchivist.defaultDbName\n }\n\n /**\n * The database version. If not supplied via config, it defaults to 1.\n */\n get dbVersion() {\n return this.config?.dbVersion ?? IndexedDbArchivist.defaultDbVersion\n }\n\n override get queries() {\n return [ArchivistAllQuerySchema, ArchivistClearQuerySchema, ArchivistDeleteQuerySchema, ArchivistInsertQuerySchema, ...super.queries]\n }\n\n /**\n * The name of the object store. If not supplied via config, it defaults\n * to `payloads`.\n */\n get storeName() {\n return this.config?.storeName ?? IndexedDbArchivist.defaultStoreName\n }\n\n /**\n * The indexes to create on the store\n */\n private get indexes() {\n return [IndexedDbArchivist.dataHashIndex, IndexedDbArchivist.hashIndex, IndexedDbArchivist.schemaIndex, ...(this.config?.storage?.indexes ?? [])]\n }\n\n protected override async allHandler(): Promise<PayloadWithMeta[]> {\n // Get all payloads from the store\n const payloads = await this.useDb((db) => db.getAll(this.storeName))\n // Remove any metadata before returning to the client\n return await Promise.all(payloads.map((payload) => PayloadBuilder.build(payload)))\n }\n\n protected override async clearHandler(): Promise<void> {\n await this.useDb((db) => db.clear(this.storeName))\n }\n\n protected override async deleteHandler(hashes: Hash[]): Promise<Hash[]> {\n const pairs = await PayloadBuilder.hashPairs(await this.getHandler(hashes))\n const hashesToDelete = pairs.flatMap<Hash>((pair) => [pair[0].$hash, pair[1]])\n // Remove any duplicates\n const distinctHashes = [...new Set(hashesToDelete)]\n return await this.useDb(async (db) => {\n // Only return hashes that were successfully deleted\n const found = await Promise.all(\n distinctHashes.map(async (hash) => {\n // Check if the hash exists\n const existing =\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.hashIndexName, hash)) ??\n (await db.getKeyFromIndex(this.storeName, IndexedDbArchivist.dataHashIndexName, hash))\n // If it does exist\n if (existing) {\n // Delete it\n await db.delete(this.storeName, existing)\n // Return the hash so it gets added to the list of deleted hashes\n return hash\n }\n }),\n )\n return found.filter(exists).filter((hash) => hashes.includes(hash))\n })\n }\n\n /**\n * Uses an index to get a payload by the index value, but returns the value with the primary key (from the root store)\n * @param db The db instance to use\n * @param storeName The name of the store to use\n * @param indexName The index to use\n * @param key The key to get from the index\n * @returns The primary key and the payload, or undefined if not found\n */\n protected async getFromIndexWithPrimaryKey(\n db: IDBPDatabase<PayloadStore>,\n storeName: string,\n indexName: string,\n key: IDBValidKey,\n ): Promise<[number, PayloadWithMeta] | undefined> {\n const transaction = db.transaction(storeName, 'readonly')\n const store = transaction.objectStore(storeName)\n const index = store.index(indexName)\n const cursor = await index.openCursor(key)\n if (cursor) {\n const singleValue = cursor.value\n // NOTE: It's known to be a number because we are using IndexedDB supplied auto-incrementing keys\n if (typeof cursor.primaryKey !== 'number') {\n throw new TypeError('primaryKey must be a number')\n }\n\n return [cursor.primaryKey, singleValue]\n }\n }\n\n protected override async getHandler(hashes: string[]): Promise<PayloadWithMeta[]> {\n const payloads = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.hashIndexName, hash))),\n )\n const payloadsFromDataHashes = await this.useDb((db) =>\n Promise.all(hashes.map((hash) => this.getFromIndexWithPrimaryKey(db, this.storeName, IndexedDbArchivist.dataHashIndexName, hash))),\n )\n //filter out duplicates\n const found = new Set<string>()\n const payloadsFromHash = payloads.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n const payloadsFromDataHash = payloadsFromDataHashes.filter(exists).filter(([_key, payload]) => {\n if (found.has(payload.$hash)) {\n return false\n } else {\n found.add(payload.$hash)\n return true\n }\n })\n return (\n // Merge what we found from the hash and data hash indexes\n [...payloadsFromHash, ...payloadsFromDataHash]\n // Sort in ascending order by primary key (for semi-predictable ordering in terms of insertion order)\n .sort((a, b) => a[0] - b[0])\n // Return just the payloads\n .map(([_key, payload]) => payload)\n )\n }\n\n protected override async insertHandler(payloads: Payload[]): Promise<PayloadWithMeta[]> {\n const pairs = await PayloadBuilder.hashPairs(payloads)\n\n const db = await this.getInitializedDb()\n try {\n // Only return the payloads that were successfully inserted\n const inserted = await Promise.all(\n pairs.map(async ([payload, _hash]) => {\n const existing = (await this.getHandler([_hash])).shift()\n if (existing) {\n return\n }\n // Perform each insert via a transaction to ensure it is atomic\n // with respect to checking for the pre-existence of the hash.\n // This is done to preserve iteration via insertion order.\n const tx = db.transaction(this.storeName, 'readwrite')\n try {\n // Get the object store\n const store = tx.objectStore(this.storeName)\n\n // Check if the hash already exists\n const existingTopHash = await store.index(IndexedDbArchivist.hashIndexName).get(_hash)\n // If it does not already exist\n if (!existingTopHash) {\n // Insert the payload\n await store.put({ ...payload, _hash })\n }\n\n // Return it so it gets added to the list of inserted payloads\n return payload\n } finally {\n // Close the transaction\n await tx.done\n }\n }),\n )\n return inserted.filter(exists)\n } finally {\n db.close()\n }\n }\n\n protected override async startHandler() {\n await super.startHandler()\n // NOTE: We could defer this creation to first access but we\n // want to fail fast here in case something is wrong\n await this.useDb(() => {})\n return true\n }\n\n /**\n * Returns that the desired DB/Store initialized to the correct version\n * @returns The initialized DB\n */\n private async getInitializedDb(): Promise<IDBPDatabase<PayloadStore>> {\n const { dbName, dbVersion, indexes, storeName, logger } = this\n const db = await openDB<PayloadStore>(dbName, dbVersion, {\n blocked(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocked from upgrading from ${currentVersion} to ${blockedVersion}`, event)\n },\n blocking(currentVersion, blockedVersion, event) {\n logger.warn(`IndexedDbArchivist: Blocking upgrade from ${currentVersion} to ${blockedVersion}`, event)\n },\n terminated() {\n logger.log('IndexedDbArchivist: Terminated')\n },\n upgrade(database, oldVersion, newVersion, transaction) {\n // NOTE: This is called whenever the DB is created/updated. We could simply ensure the desired end\n // state but, out of an abundance of caution, we will just delete (so we know where we are starting\n // from a known good point) and recreate the desired state. This prioritizes resilience over data\n // retention but we can revisit that tradeoff when it becomes limiting. Because distributed browser\n // state is extremely hard to debug, this seems like fair tradeoff for now.\n if (oldVersion !== newVersion) {\n logger.log(`IndexedDbArchivist: Upgrading from ${oldVersion} to ${newVersion}`)\n // Delete any existing databases that are not the current version\n const objectStores = transaction.objectStoreNames\n for (const name of objectStores) {\n try {\n database.deleteObjectStore(name)\n } catch {\n logger.log(`IndexedDbArchivist: Failed to delete existing object store ${name}`)\n }\n }\n }\n // Create the store\n const store = database.createObjectStore(storeName, {\n // If it isn't explicitly set, create a value by auto incrementing.\n autoIncrement: true,\n })\n // Name the store\n store.name = storeName\n // Create an index on the hash\n for (const { key, multiEntry, unique } of indexes) {\n const indexKeys = Object.keys(key)\n const keys = indexKeys.length === 1 ? indexKeys[0] : indexKeys\n const indexName = buildStandardIndexName({ key, unique })\n store.createIndex(indexName, keys, { multiEntry, unique })\n }\n },\n })\n return db\n }\n\n /**\n * Executes a callback with the initialized DB and then closes the db\n * @param callback The method to execute with the initialized DB\n * @returns\n */\n private async useDb<T>(callback: (db: IDBPDatabase<PayloadStore>) => Promise<T> | T): Promise<T> {\n // Get the initialized DB\n const db = await this.getInitializedDb()\n try {\n // Perform the callback\n return await callback(db)\n } finally {\n // Close the DB\n db.close()\n }\n }\n}\n","export type IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\nexport const IndexedDbArchivistSchema: IndexedDbArchivistSchema = 'network.xyo.archivist.indexeddb'\n","import { ArchivistConfig, IndexDescription } from '@xyo-network/archivist-model'\n\nimport { IndexedDbArchivistSchema } from './Schema'\n\nexport type IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\nexport const IndexedDbArchivistConfigSchema: IndexedDbArchivistConfigSchema = `${IndexedDbArchivistSchema}.config`\n\nexport type IndexedDbArchivistConfig = ArchivistConfig<{\n /**\n * The database name\n */\n dbName?: string\n /**\n * The version of the DB, defaults to 1\n */\n dbVersion?: number\n schema: IndexedDbArchivistConfigSchema\n /**\n * The storage configuration\n * // TODO: Hoist to main archivist config\n */\n storage?: {\n /**\n * The indexes to create on the object store\n */\n indexes?: IndexDescription[]\n }\n /**\n * The name of the object store\n */\n storeName?: string\n}>\n"],"mappings":";;;;AAAA,SAASA,cAAc;AAEvB,SAASC,yBAAyB;AAClC,SACEC,yBACAC,2BACAC,4BACAC,4BAEAC,8BAEK;AACP,SAASC,uBAAuB;AAChC,SAASC,sBAAsB;AAE/B,SAAuBC,cAAc;;;ACd9B,IAAMC,2BAAqD;;;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OM,KAAK,6CAA6CH,cAAAA,OAAqBC,cAAAA,IAAkBC,KAAAA;MAClG;MACAG,aAAAA;AACER,eAAOS,IAAI,gCAAA;MACb;MACAC,QAAQC,UAAUC,YAAYC,YAAY3C,aAAW;AAMnD,YAAI0C,eAAeC,YAAY;AAC7Bb,iBAAOS,IAAI,sCAAsCG,UAAAA,OAAiBC,UAAAA,EAAY;AAE9E,gBAAMC,eAAe5C,YAAY6C;AACjC,qBAAWxF,QAAQuF,cAAc;AAC/B,gBAAI;AACFH,uBAASK,kBAAkBzF,IAAAA;YAC7B,QAAQ;AACNyE,qBAAOS,IAAI,8DAA8DlF,IAAAA,EAAM;YACjF;UACF;QACF;AAEA,cAAM4C,QAAQwC,SAASM,kBAAkBnF,WAAW;;UAElDoF,eAAe;QACjB,CAAA;AAEA/C,cAAM5C,OAAOO;AAEb,mBAAW,EAAErB,KAAKE,YAAYC,OAAM,KAAMmB,SAAS;AACjD,gBAAMoF,YAAYC,OAAOC,KAAK5G,GAAAA;AAC9B,gBAAM4G,OAAOF,UAAUG,WAAW,IAAIH,UAAU,CAAA,IAAKA;AACrD,gBAAMlD,YAAY/C,uBAAuB;YAAET;YAAKG;UAAO,CAAA;AACvDuD,gBAAMoD,YAAYtD,WAAWoD,MAAM;YAAE1G;YAAYC;UAAO,CAAA;QAC1D;MACF;IACF,CAAA;AACA,WAAOwB;EACT;;;;;;EAOA,MAAcD,MAASqF,UAA0E;AAE/F,UAAMpF,KAAK,MAAM,KAAKkD,iBAAgB;AACtC,QAAI;AAEF,aAAO,MAAMkC,SAASpF,EAAAA;IACxB,UAAA;AAEEA,SAAG0D,MAAK;IACV;EACF;AACF;AApRa9F,qBAAAA,aAAAA;EADZyH,gBAAAA;GACYzH,kBAAAA;","names":["exists","AbstractArchivist","ArchivistAllQuerySchema","ArchivistClearQuerySchema","ArchivistDeleteQuerySchema","ArchivistInsertQuerySchema","buildStandardIndexName","creatableModule","PayloadBuilder","openDB","IndexedDbArchivistSchema","IndexedDbArchivistConfigSchema","IndexedDbArchivistSchema","IndexedDbArchivist","AbstractArchivist","configSchemas","IndexedDbArchivistConfigSchema","defaultConfigSchema","defaultDbName","defaultDbVersion","defaultStoreName","dataHashIndex","key","$hash","multiEntry","unique","hashIndex","_hash","schemaIndex","schema","hashIndexName","buildStandardIndexName","dataHashIndexName","schemaIndexName","dbName","config","name","dbVersion","queries","ArchivistAllQuerySchema","ArchivistClearQuerySchema","ArchivistDeleteQuerySchema","ArchivistInsertQuerySchema","storeName","indexes","storage","allHandler","payloads","useDb","db","getAll","Promise","all","map","payload","PayloadBuilder","build","clearHandler","clear","deleteHandler","hashes","pairs","hashPairs","getHandler","hashesToDelete","flatMap","pair","distinctHashes","Set","found","hash","existing","getKeyFromIndex","delete","filter","exists","includes","getFromIndexWithPrimaryKey","indexName","transaction","store","objectStore","index","cursor","openCursor","singleValue","value","primaryKey","TypeError","payloadsFromDataHashes","payloadsFromHash","_key","has","add","payloadsFromDataHash","sort","a","b","insertHandler","getInitializedDb","inserted","shift","tx","existingTopHash","get","put","done","close","startHandler","logger","openDB","blocked","currentVersion","blockedVersion","event","warn","blocking","terminated","log","upgrade","database","oldVersion","newVersion","objectStores","objectStoreNames","deleteObjectStore","createObjectStore","autoIncrement","indexKeys","Object","keys","length","createIndex","callback","creatableModule"]}
package/package.json CHANGED
@@ -10,21 +10,21 @@
10
10
  "url": "https://github.com/XYOracleNetwork/sdk-xyo-client-js/issues"
11
11
  },
12
12
  "dependencies": {
13
- "@xylabs/exists": "^3.1.11",
14
- "@xylabs/hex": "^3.1.11",
15
- "@xyo-network/archivist-abstract": "~2.99.2",
16
- "@xyo-network/archivist-model": "~2.99.2",
17
- "@xyo-network/module-model": "~2.99.2",
18
- "@xyo-network/payload-builder": "~2.99.2",
19
- "@xyo-network/payload-model": "~2.99.2",
13
+ "@xylabs/exists": "^3.3.2",
14
+ "@xylabs/hex": "^3.3.2",
15
+ "@xyo-network/archivist-abstract": "~2.99.3",
16
+ "@xyo-network/archivist-model": "~2.99.3",
17
+ "@xyo-network/module-model": "~2.99.3",
18
+ "@xyo-network/payload-builder": "~2.99.3",
19
+ "@xyo-network/payload-model": "~2.99.3",
20
20
  "idb": "^8.0.0"
21
21
  },
22
22
  "devDependencies": {
23
- "@xylabs/ts-scripts-yarn3": "^3.9.1",
24
- "@xylabs/tsconfig": "^3.9.1",
25
- "@xyo-network/account": "~2.99.2",
26
- "@xyo-network/id-payload-plugin": "~2.99.2",
27
- "@xyo-network/payload-wrapper": "~2.99.2",
23
+ "@xylabs/ts-scripts-yarn3": "^3.10.0",
24
+ "@xylabs/tsconfig": "^3.10.0",
25
+ "@xyo-network/account": "~2.99.3",
26
+ "@xyo-network/id-payload-plugin": "~2.99.3",
27
+ "@xyo-network/payload-wrapper": "~2.99.3",
28
28
  "fake-indexeddb": "^5.0.2",
29
29
  "typescript": "^5.4.5"
30
30
  },
@@ -67,6 +67,6 @@
67
67
  "url": "https://github.com/XYOracleNetwork/sdk-xyo-client-js.git"
68
68
  },
69
69
  "sideEffects": false,
70
- "version": "2.99.2",
70
+ "version": "2.99.3",
71
71
  "type": "module"
72
72
  }