@topgunbuild/adapters 0.11.0 → 2.0.0

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/LICENSE CHANGED
@@ -1,97 +1,201 @@
1
- Business Source License 1.1
2
-
3
- Parameters
4
-
5
- Licensor: TopGun Contributors
6
- Licensed Work: TopGun
7
- The Licensed Work is (c) 2024 TopGun Contributors.
8
- Additional Use Grant: You may make production use of the Licensed Work,
9
- provided Your use does not include offering the
10
- Licensed Work to third parties as a commercial
11
- managed database service, database-as-a-service,
12
- or similar hosted database offering that competes
13
- with TopGun products or services.
14
-
15
- For purposes of this license:
16
- - "Managed database service" means a service that
17
- allows third parties to create, manage, or operate
18
- databases using TopGun as the underlying technology.
19
- - Internal use within your organization is permitted.
20
- - Using TopGun as part of your application's backend
21
- (not exposed as a database service) is permitted.
22
- - Consulting and professional services around TopGun
23
- are permitted.
24
-
25
- Change Date: Four years from the date of each version release
26
- Change License: Apache License, Version 2.0
27
-
28
- For information about alternative licensing arrangements for the Licensed Work,
29
- please contact the Licensor.
30
-
31
- Notice
32
-
33
- Business Source License 1.1
34
-
35
- Terms
36
-
37
- The Licensor hereby grants you the right to copy, modify, create derivative
38
- works, redistribute, and make non-production use of the Licensed Work. The
39
- Licensor may make an Additional Use Grant, above, permitting limited production use.
40
-
41
- Effective on the Change Date, or the fourth anniversary of the first publicly
42
- available distribution of a specific version of the Licensed Work under this
43
- License, whichever comes first, the Licensor hereby grants you rights under
44
- the terms of the Change License, and the rights granted in the paragraph
45
- above terminate.
46
-
47
- If your use of the Licensed Work does not comply with the requirements
48
- currently in effect as described in this License, you must purchase a
49
- commercial license from the Licensor, its affiliated entities, or authorized
50
- resellers, or you must refrain from using the Licensed Work.
51
-
52
- All copies of the original and modified Licensed Work, and derivative works
53
- of the Licensed Work, are subject to this License. This License applies
54
- separately for each version of the Licensed Work and the Change Date may vary
55
- for each version of the Licensed Work released by Licensor.
56
-
57
- You must conspicuously display this License on each original or modified copy
58
- of the Licensed Work. If you receive the Licensed Work in original or
59
- modified form from a third party, the terms and conditions set forth in this
60
- License apply to your use of that work.
61
-
62
- Any use of the Licensed Work in violation of this License will automatically
63
- terminate your rights under this License for the current and all other
64
- versions of the Licensed Work.
65
-
66
- This License does not grant you any right in any trademark or logo of
67
- Licensor or its affiliates (provided that you may use a trademark or logo of
68
- Licensor as expressly required by this License).
69
-
70
- TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
71
- AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
72
- EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
73
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
74
- TITLE.
75
-
76
- MariaDB hereby grants you permission to use this License's text to license
77
- your works, and to refer to it using the trademark "Business Source License",
78
- as long as you comply with the Covenants of Licensor below.
79
-
80
- Covenants of Licensor
81
-
82
- In consideration of the right to use this License's text and the "Business
83
- Source License" name and trademark, Licensor covenants to MariaDB, and to all
84
- other recipients of the licensed work to be provided by Licensor:
85
-
86
- 1. To specify as the Change License the GPL Version 2.0 or any later version,
87
- or a license that is compatible with GPL Version 2.0 or a later version,
88
- where "compatible" means that software provided under the Change License can
89
- be included in a program with software provided under GPL Version 2.0 or a
90
- later version. Licensor may specify additional Change Licenses without
91
- limitation.
92
-
93
- 2. To either: (a) specify an Additional Use Grant (above) that does not impose
94
- any additional restriction on the right granted in this License, as the
95
- Additional Use Grant; or (b) insert the text "None" to specify a Change Date.
96
-
97
- 3. Not to modify this License in any other way.
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. Please also get an approval
186
+ for your intended use from the US if you are a foreign entity
187
+ operating in the US.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
200
+ implied. See the License for the specific language governing
201
+ permissions and limitations under the License.
package/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # @topgunbuild/adapters
2
+
3
+ [![npm](https://img.shields.io/npm/v/@topgunbuild/adapters)](https://www.npmjs.com/package/@topgunbuild/adapters) [![License](https://img.shields.io/npm/l/@topgunbuild/adapters)](https://github.com/TopGunBuild/topgun/blob/main/LICENSE)
4
+
5
+ Storage adapters for [TopGun](https://topgun.build). Today: **IndexedDB**.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @topgunbuild/adapters @topgunbuild/client
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```typescript
16
+ import { TopGunClient } from '@topgunbuild/client';
17
+ import { IDBAdapter } from '@topgunbuild/adapters';
18
+
19
+ const client = new TopGunClient({
20
+ storage: new IDBAdapter('my-app'), // database name
21
+ // serverUrl: 'ws://localhost:8080', // optional
22
+ });
23
+ client.start();
24
+ ```
25
+
26
+ ## `IDBAdapter`
27
+
28
+ Non-blocking IndexedDB adapter. Operations queue in memory and replay once the database is ready, so the UI can render immediately without waiting for IDB to open (typically 50–500ms on first visit).
29
+
30
+ ```typescript
31
+ new IDBAdapter(databaseName: string)
32
+ ```
33
+
34
+ The adapter creates three object stores:
35
+
36
+ - `kv_store` — key/value records for `LWWMap` / `ORMap`
37
+ - `op_log` — append-only operation log (auto-incrementing id)
38
+ - `meta_store` — metadata (sync cursors, schema versions, etc.)
39
+
40
+ ### Waiting for initialization (rare)
41
+
42
+ By default, the adapter is fire-and-forget. If you specifically need to ensure persistence is online (e.g., before importing a backup), use:
43
+
44
+ ```typescript
45
+ const adapter = new IDBAdapter('my-app');
46
+ const client = new TopGunClient({ storage: adapter });
47
+ client.start();
48
+ await adapter.waitForReady(); // optional — blocks until openDB resolves
49
+ ```
50
+
51
+ ## Browser support
52
+
53
+ IndexedDB is supported in every modern browser (Chrome, Firefox, Safari, Edge). For Node.js or non-browser environments, a community adapter is on the roadmap.
54
+
55
+ ## Documentation
56
+
57
+ - Full docs: [topgun.build/docs](https://topgun.build/docs)
58
+ - Client API: [`@topgunbuild/client`](https://www.npmjs.com/package/@topgunbuild/client)
59
+ - GitHub: [TopGunBuild/topgun](https://github.com/TopGunBuild/topgun)
60
+
61
+ ## License
62
+
63
+ Apache-2.0
package/dist/index.d.mts CHANGED
@@ -1,21 +1,59 @@
1
1
  import { LWWRecord, ORMapRecord } from '@topgunbuild/core';
2
2
  import { IStorageAdapter, OpLogEntry } from '@topgunbuild/client';
3
3
 
4
+ /**
5
+ * Non-blocking IndexedDB adapter that allows immediate use before initialization completes.
6
+ *
7
+ * Operations are queued in memory and replayed once IndexedDB is ready.
8
+ * This enables true "memory-first" behavior where the UI can render immediately
9
+ * without waiting for IndexedDB to initialize (which can take 50-500ms).
10
+ */
4
11
  declare class IDBAdapter implements IStorageAdapter {
5
12
  private dbPromise?;
6
- private dbName;
13
+ private db?;
14
+ private isReady;
15
+ private operationQueue;
16
+ private initPromise?;
17
+ /**
18
+ * Initializes IndexedDB in the background.
19
+ * Returns immediately - does NOT block on IndexedDB being ready.
20
+ * Use waitForReady() if you need to ensure initialization is complete.
21
+ */
7
22
  initialize(dbName: string): Promise<void>;
23
+ /**
24
+ * Internal initialization that actually opens IndexedDB.
25
+ */
26
+ private initializeInternal;
27
+ /**
28
+ * Waits for IndexedDB to be fully initialized.
29
+ * Call this if you need guaranteed persistence before proceeding.
30
+ */
31
+ waitForReady(): Promise<void>;
32
+ /**
33
+ * Flushes all queued operations once IndexedDB is ready.
34
+ */
35
+ private flushQueue;
36
+ /**
37
+ * Queues an operation if not ready, or executes immediately if ready.
38
+ */
39
+ private queueOrExecute;
8
40
  close(): Promise<void>;
9
41
  get<V>(key: string): Promise<LWWRecord<V> | ORMapRecord<V>[] | any | undefined>;
42
+ getMeta(key: string): Promise<any>;
43
+ getPendingOps(): Promise<OpLogEntry[]>;
44
+ getAllKeys(): Promise<string[]>;
10
45
  put(key: string, value: any): Promise<void>;
46
+ private putInternal;
11
47
  remove(key: string): Promise<void>;
12
- getMeta(key: string): Promise<any>;
48
+ private removeInternal;
13
49
  setMeta(key: string, value: any): Promise<void>;
50
+ private setMetaInternal;
14
51
  batchPut(entries: Map<string, any>): Promise<void>;
52
+ private batchPutInternal;
15
53
  appendOpLog(entry: any): Promise<number>;
16
- getPendingOps(): Promise<OpLogEntry[]>;
54
+ private appendOpLogInternal;
17
55
  markOpsSynced(lastId: number): Promise<void>;
18
- getAllKeys(): Promise<string[]>;
56
+ private markOpsSyncedInternal;
19
57
  }
20
58
 
21
59
  export { IDBAdapter };
package/dist/index.d.ts CHANGED
@@ -1,21 +1,59 @@
1
1
  import { LWWRecord, ORMapRecord } from '@topgunbuild/core';
2
2
  import { IStorageAdapter, OpLogEntry } from '@topgunbuild/client';
3
3
 
4
+ /**
5
+ * Non-blocking IndexedDB adapter that allows immediate use before initialization completes.
6
+ *
7
+ * Operations are queued in memory and replayed once IndexedDB is ready.
8
+ * This enables true "memory-first" behavior where the UI can render immediately
9
+ * without waiting for IndexedDB to initialize (which can take 50-500ms).
10
+ */
4
11
  declare class IDBAdapter implements IStorageAdapter {
5
12
  private dbPromise?;
6
- private dbName;
13
+ private db?;
14
+ private isReady;
15
+ private operationQueue;
16
+ private initPromise?;
17
+ /**
18
+ * Initializes IndexedDB in the background.
19
+ * Returns immediately - does NOT block on IndexedDB being ready.
20
+ * Use waitForReady() if you need to ensure initialization is complete.
21
+ */
7
22
  initialize(dbName: string): Promise<void>;
23
+ /**
24
+ * Internal initialization that actually opens IndexedDB.
25
+ */
26
+ private initializeInternal;
27
+ /**
28
+ * Waits for IndexedDB to be fully initialized.
29
+ * Call this if you need guaranteed persistence before proceeding.
30
+ */
31
+ waitForReady(): Promise<void>;
32
+ /**
33
+ * Flushes all queued operations once IndexedDB is ready.
34
+ */
35
+ private flushQueue;
36
+ /**
37
+ * Queues an operation if not ready, or executes immediately if ready.
38
+ */
39
+ private queueOrExecute;
8
40
  close(): Promise<void>;
9
41
  get<V>(key: string): Promise<LWWRecord<V> | ORMapRecord<V>[] | any | undefined>;
42
+ getMeta(key: string): Promise<any>;
43
+ getPendingOps(): Promise<OpLogEntry[]>;
44
+ getAllKeys(): Promise<string[]>;
10
45
  put(key: string, value: any): Promise<void>;
46
+ private putInternal;
11
47
  remove(key: string): Promise<void>;
12
- getMeta(key: string): Promise<any>;
48
+ private removeInternal;
13
49
  setMeta(key: string, value: any): Promise<void>;
50
+ private setMetaInternal;
14
51
  batchPut(entries: Map<string, any>): Promise<void>;
52
+ private batchPutInternal;
15
53
  appendOpLog(entry: any): Promise<number>;
16
- getPendingOps(): Promise<OpLogEntry[]>;
54
+ private appendOpLogInternal;
17
55
  markOpsSynced(lastId: number): Promise<void>;
18
- getAllKeys(): Promise<string[]>;
56
+ private markOpsSyncedInternal;
19
57
  }
20
58
 
21
59
  export { IDBAdapter };
package/dist/index.js CHANGED
@@ -28,53 +28,151 @@ module.exports = __toCommonJS(index_exports);
28
28
  var import_idb = require("idb");
29
29
  var IDBAdapter = class {
30
30
  constructor() {
31
- this.dbName = "";
31
+ this.isReady = false;
32
+ this.operationQueue = [];
32
33
  }
34
+ /**
35
+ * Initializes IndexedDB in the background.
36
+ * Returns immediately - does NOT block on IndexedDB being ready.
37
+ * Use waitForReady() if you need to ensure initialization is complete.
38
+ */
33
39
  async initialize(dbName) {
34
- this.dbName = dbName;
35
- this.dbPromise = (0, import_idb.openDB)(dbName, 2, {
36
- // Bump version for new stores if needed, though we reuse kv_store
37
- upgrade(db, oldVersion, newVersion, transaction) {
38
- if (!db.objectStoreNames.contains("kv_store")) {
39
- db.createObjectStore("kv_store", { keyPath: "key" });
40
- }
41
- if (!db.objectStoreNames.contains("op_log")) {
42
- db.createObjectStore("op_log", { keyPath: "id", autoIncrement: true });
40
+ this.initPromise = this.initializeInternal(dbName);
41
+ }
42
+ /**
43
+ * Internal initialization that actually opens IndexedDB.
44
+ */
45
+ async initializeInternal(dbName) {
46
+ try {
47
+ this.dbPromise = (0, import_idb.openDB)(dbName, 2, {
48
+ upgrade(db) {
49
+ if (!db.objectStoreNames.contains("kv_store")) {
50
+ db.createObjectStore("kv_store", { keyPath: "key" });
51
+ }
52
+ if (!db.objectStoreNames.contains("op_log")) {
53
+ db.createObjectStore("op_log", { keyPath: "id", autoIncrement: true });
54
+ }
55
+ if (!db.objectStoreNames.contains("meta_store")) {
56
+ db.createObjectStore("meta_store", { keyPath: "key" });
57
+ }
43
58
  }
44
- if (!db.objectStoreNames.contains("meta_store")) {
45
- db.createObjectStore("meta_store", { keyPath: "key" });
59
+ });
60
+ this.db = await this.dbPromise;
61
+ this.isReady = true;
62
+ await this.flushQueue();
63
+ } catch (error) {
64
+ throw error;
65
+ }
66
+ }
67
+ /**
68
+ * Waits for IndexedDB to be fully initialized.
69
+ * Call this if you need guaranteed persistence before proceeding.
70
+ */
71
+ async waitForReady() {
72
+ if (this.isReady) return;
73
+ if (this.initPromise) {
74
+ await this.initPromise;
75
+ }
76
+ }
77
+ /**
78
+ * Flushes all queued operations once IndexedDB is ready.
79
+ */
80
+ async flushQueue() {
81
+ const queue = this.operationQueue;
82
+ this.operationQueue = [];
83
+ for (const op of queue) {
84
+ try {
85
+ let result;
86
+ switch (op.type) {
87
+ case "put":
88
+ result = await this.putInternal(op.args[0], op.args[1]);
89
+ break;
90
+ case "remove":
91
+ result = await this.removeInternal(op.args[0]);
92
+ break;
93
+ case "setMeta":
94
+ result = await this.setMetaInternal(op.args[0], op.args[1]);
95
+ break;
96
+ case "appendOpLog":
97
+ result = await this.appendOpLogInternal(op.args[0]);
98
+ break;
99
+ case "markOpsSynced":
100
+ result = await this.markOpsSyncedInternal(op.args[0]);
101
+ break;
102
+ case "batchPut":
103
+ result = await this.batchPutInternal(op.args[0]);
104
+ break;
46
105
  }
106
+ op.resolve(result);
107
+ } catch (error) {
108
+ op.reject(error);
47
109
  }
110
+ }
111
+ }
112
+ /**
113
+ * Queues an operation if not ready, or executes immediately if ready.
114
+ */
115
+ queueOrExecute(type, args, executor) {
116
+ if (this.isReady) {
117
+ return executor();
118
+ }
119
+ return new Promise((resolve, reject) => {
120
+ this.operationQueue.push({ type, args, resolve, reject });
48
121
  });
49
- await this.dbPromise;
50
122
  }
51
123
  async close() {
124
+ if (this.db) {
125
+ this.db.close();
126
+ }
52
127
  }
128
+ // ============================================
129
+ // Read Operations - Wait for ready
130
+ // ============================================
53
131
  async get(key) {
54
- const db = await this.dbPromise;
55
- const result = await db?.get("kv_store", key);
132
+ await this.waitForReady();
133
+ const result = await this.db?.get("kv_store", key);
56
134
  return result?.value;
57
135
  }
136
+ async getMeta(key) {
137
+ await this.waitForReady();
138
+ const result = await this.db?.get("meta_store", key);
139
+ return result?.value;
140
+ }
141
+ async getPendingOps() {
142
+ await this.waitForReady();
143
+ const all = await this.db?.getAll("op_log");
144
+ return all?.filter((op) => op.synced === 0) || [];
145
+ }
146
+ async getAllKeys() {
147
+ await this.waitForReady();
148
+ return await this.db?.getAllKeys("kv_store") || [];
149
+ }
150
+ // ============================================
151
+ // Write Operations - Queue if not ready
152
+ // ============================================
58
153
  async put(key, value) {
59
- const db = await this.dbPromise;
60
- await db?.put("kv_store", { key, value });
154
+ return this.queueOrExecute("put", [key, value], () => this.putInternal(key, value));
155
+ }
156
+ async putInternal(key, value) {
157
+ await this.db?.put("kv_store", { key, value });
61
158
  }
62
159
  async remove(key) {
63
- const db = await this.dbPromise;
64
- await db?.delete("kv_store", key);
160
+ return this.queueOrExecute("remove", [key], () => this.removeInternal(key));
65
161
  }
66
- async getMeta(key) {
67
- const db = await this.dbPromise;
68
- const result = await db?.get("meta_store", key);
69
- return result?.value;
162
+ async removeInternal(key) {
163
+ await this.db?.delete("kv_store", key);
70
164
  }
71
165
  async setMeta(key, value) {
72
- const db = await this.dbPromise;
73
- await db?.put("meta_store", { key, value });
166
+ return this.queueOrExecute("setMeta", [key, value], () => this.setMetaInternal(key, value));
167
+ }
168
+ async setMetaInternal(key, value) {
169
+ await this.db?.put("meta_store", { key, value });
74
170
  }
75
171
  async batchPut(entries) {
76
- const db = await this.dbPromise;
77
- const tx = db?.transaction("kv_store", "readwrite");
172
+ return this.queueOrExecute("batchPut", [entries], () => this.batchPutInternal(entries));
173
+ }
174
+ async batchPutInternal(entries) {
175
+ const tx = this.db?.transaction("kv_store", "readwrite");
78
176
  if (!tx) return;
79
177
  await Promise.all(
80
178
  Array.from(entries.entries()).map(
@@ -84,18 +182,17 @@ var IDBAdapter = class {
84
182
  await tx.done;
85
183
  }
86
184
  async appendOpLog(entry) {
87
- const db = await this.dbPromise;
88
- const entryToSave = { ...entry, synced: 0 };
89
- return await db?.add("op_log", entryToSave);
185
+ return this.queueOrExecute("appendOpLog", [entry], () => this.appendOpLogInternal(entry));
90
186
  }
91
- async getPendingOps() {
92
- const db = await this.dbPromise;
93
- const all = await db?.getAll("op_log");
94
- return all?.filter((op) => op.synced === 0) || [];
187
+ async appendOpLogInternal(entry) {
188
+ const entryToSave = { ...entry, synced: 0 };
189
+ return await this.db?.add("op_log", entryToSave);
95
190
  }
96
191
  async markOpsSynced(lastId) {
97
- const db = await this.dbPromise;
98
- const tx = db?.transaction("op_log", "readwrite");
192
+ return this.queueOrExecute("markOpsSynced", [lastId], () => this.markOpsSyncedInternal(lastId));
193
+ }
194
+ async markOpsSyncedInternal(lastId) {
195
+ const tx = this.db?.transaction("op_log", "readwrite");
99
196
  if (!tx) return;
100
197
  let cursor = await tx.store.openCursor();
101
198
  while (cursor) {
@@ -107,10 +204,6 @@ var IDBAdapter = class {
107
204
  }
108
205
  await tx.done;
109
206
  }
110
- async getAllKeys() {
111
- const db = await this.dbPromise;
112
- return await db?.getAllKeys("kv_store") || [];
113
- }
114
207
  };
115
208
  // Annotate the CommonJS export names for ESM import in node:
116
209
  0 && (module.exports = {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/IDBAdapter.ts"],"sourcesContent":["export * from './IDBAdapter';\n\n","import { LWWRecord, ORMapRecord } from '@topgunbuild/core';\nimport { IStorageAdapter, OpLogEntry } from '@topgunbuild/client';\nimport { openDB, IDBPDatabase } from 'idb';\n\nexport class IDBAdapter implements IStorageAdapter {\n private dbPromise?: Promise<IDBPDatabase>;\n private dbName: string = '';\n\n async initialize(dbName: string): Promise<void> {\n this.dbName = dbName;\n this.dbPromise = openDB(dbName, 2, { // Bump version for new stores if needed, though we reuse kv_store\n upgrade(db, oldVersion, newVersion, transaction) {\n if (!db.objectStoreNames.contains('kv_store')) {\n db.createObjectStore('kv_store', { keyPath: 'key' });\n }\n if (!db.objectStoreNames.contains('op_log')) {\n db.createObjectStore('op_log', { keyPath: 'id', autoIncrement: true });\n }\n if (!db.objectStoreNames.contains('meta_store')) {\n db.createObjectStore('meta_store', { keyPath: 'key' });\n }\n },\n });\n await this.dbPromise;\n }\n\n async close(): Promise<void> {\n // No-op\n }\n\n async get<V>(key: string): Promise<LWWRecord<V> | ORMapRecord<V>[] | any | undefined> {\n const db = await this.dbPromise;\n const result = await db?.get('kv_store', key);\n return result?.value; // We store { key, value: ... }\n }\n\n async put(key: string, value: any): Promise<void> {\n const db = await this.dbPromise;\n await db?.put('kv_store', { key, value });\n }\n\n async remove(key: string): Promise<void> {\n const db = await this.dbPromise;\n await db?.delete('kv_store', key);\n }\n\n async getMeta(key: string): Promise<any> {\n const db = await this.dbPromise;\n const result = await db?.get('meta_store', key);\n return result?.value;\n }\n\n async setMeta(key: string, value: any): Promise<void> {\n const db = await this.dbPromise;\n await db?.put('meta_store', { key, value });\n }\n\n async batchPut(entries: Map<string, any>): Promise<void> {\n const db = await this.dbPromise;\n const tx = db?.transaction('kv_store', 'readwrite');\n if (!tx) return;\n\n await Promise.all(\n Array.from(entries.entries()).map(([key, value]) =>\n tx.store.put({ key, value })\n )\n );\n await tx.done;\n }\n\n async appendOpLog(entry: any): Promise<number> {\n const db = await this.dbPromise;\n // Ensure synced is 0\n const entryToSave = { ...entry, synced: 0 };\n return await db?.add('op_log', entryToSave) as number;\n }\n\n async getPendingOps(): Promise<OpLogEntry[]> {\n const db = await this.dbPromise;\n const all = await db?.getAll('op_log');\n return all?.filter((op: any) => op.synced === 0) || [];\n }\n\n async markOpsSynced(lastId: number): Promise<void> {\n const db = await this.dbPromise;\n const tx = db?.transaction('op_log', 'readwrite');\n if (!tx) return;\n\n let cursor = await tx.store.openCursor();\n while (cursor) {\n if (cursor.value.id <= lastId) {\n const update = { ...cursor.value, synced: 1 };\n await cursor.update(update);\n }\n cursor = await cursor.continue();\n }\n await tx.done;\n }\n\n async getAllKeys(): Promise<string[]> {\n const db = await this.dbPromise;\n return (await db?.getAllKeys('kv_store')) as string[] || [];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,iBAAqC;AAE9B,IAAM,aAAN,MAA4C;AAAA,EAA5C;AAEL,SAAQ,SAAiB;AAAA;AAAA,EAEzB,MAAM,WAAW,QAA+B;AAC9C,SAAK,SAAS;AACd,SAAK,gBAAY,mBAAO,QAAQ,GAAG;AAAA;AAAA,MACjC,QAAQ,IAAI,YAAY,YAAY,aAAa;AAC/C,YAAI,CAAC,GAAG,iBAAiB,SAAS,UAAU,GAAG;AAC7C,aAAG,kBAAkB,YAAY,EAAE,SAAS,MAAM,CAAC;AAAA,QACrD;AACA,YAAI,CAAC,GAAG,iBAAiB,SAAS,QAAQ,GAAG;AAC3C,aAAG,kBAAkB,UAAU,EAAE,SAAS,MAAM,eAAe,KAAK,CAAC;AAAA,QACvE;AACA,YAAI,CAAC,GAAG,iBAAiB,SAAS,YAAY,GAAG;AAC7C,aAAG,kBAAkB,cAAc,EAAE,SAAS,MAAM,CAAC;AAAA,QACzD;AAAA,MACF;AAAA,IACF,CAAC;AACD,UAAM,KAAK;AAAA,EACb;AAAA,EAEA,MAAM,QAAuB;AAAA,EAE7B;AAAA,EAEA,MAAM,IAAO,KAAyE;AACpF,UAAM,KAAK,MAAM,KAAK;AACtB,UAAM,SAAS,MAAM,IAAI,IAAI,YAAY,GAAG;AAC5C,WAAO,QAAQ;AAAA,EACjB;AAAA,EAEA,MAAM,IAAI,KAAa,OAA2B;AAChD,UAAM,KAAK,MAAM,KAAK;AACtB,UAAM,IAAI,IAAI,YAAY,EAAE,KAAK,MAAM,CAAC;AAAA,EAC1C;AAAA,EAEA,MAAM,OAAO,KAA4B;AACvC,UAAM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,MAAM,MAAM,QAAQ;AAC7B,cAAM,SAAS,EAAE,GAAG,OAAO,OAAO,QAAQ,EAAE;AAC5C,cAAM,OAAO,OAAO,MAAM;AAAA,MAC5B;AACA,eAAS,MAAM,OAAO,SAAS;AAAA,IACjC;AACA,UAAM,GAAG;AAAA,EACX;AAAA,EAEA,MAAM,aAAgC;AACpC,UAAM,KAAK,MAAM,KAAK;AACtB,WAAQ,MAAM,IAAI,WAAW,UAAU,KAAkB,CAAC;AAAA,EAC5D;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/IDBAdapter.ts"],"sourcesContent":["export * from './IDBAdapter';\n\n","import type { LWWRecord, ORMapRecord } from '@topgunbuild/core';\nimport { IStorageAdapter, OpLogEntry } from '@topgunbuild/client';\nimport { openDB } from 'idb';\nimport type { IDBPDatabase } from 'idb';\n\n/**\n * Represents an operation queued before IndexedDB is ready.\n */\ninterface QueuedOperation {\n type: 'put' | 'remove' | 'setMeta' | 'appendOpLog' | 'markOpsSynced' | 'batchPut';\n args: any[];\n resolve: (value: any) => void;\n reject: (error: any) => void;\n}\n\n/**\n * Non-blocking IndexedDB adapter that allows immediate use before initialization completes.\n *\n * Operations are queued in memory and replayed once IndexedDB is ready.\n * This enables true \"memory-first\" behavior where the UI can render immediately\n * without waiting for IndexedDB to initialize (which can take 50-500ms).\n */\nexport class IDBAdapter implements IStorageAdapter {\n private dbPromise?: Promise<IDBPDatabase>;\n private db?: IDBPDatabase;\n private isReady = false;\n private operationQueue: QueuedOperation[] = [];\n private initPromise?: Promise<void>;\n\n /**\n * Initializes IndexedDB in the background.\n * Returns immediately - does NOT block on IndexedDB being ready.\n * Use waitForReady() if you need to ensure initialization is complete.\n */\n async initialize(dbName: string): Promise<void> {\n // Start initialization but don't await it — non-blocking by design\n this.initPromise = this.initializeInternal(dbName);\n // Return immediately\n }\n\n /**\n * Internal initialization that actually opens IndexedDB.\n */\n private async initializeInternal(dbName: string): Promise<void> {\n try {\n this.dbPromise = openDB(dbName, 2, {\n upgrade(db) {\n if (!db.objectStoreNames.contains('kv_store')) {\n db.createObjectStore('kv_store', { keyPath: 'key' });\n }\n if (!db.objectStoreNames.contains('op_log')) {\n db.createObjectStore('op_log', { keyPath: 'id', autoIncrement: true });\n }\n if (!db.objectStoreNames.contains('meta_store')) {\n db.createObjectStore('meta_store', { keyPath: 'key' });\n }\n },\n });\n\n this.db = await this.dbPromise;\n this.isReady = true;\n\n // Replay queued operations in the order they arrived\n await this.flushQueue();\n } catch (error) {\n // Re-throw to allow error handling\n throw error;\n }\n }\n\n /**\n * Waits for IndexedDB to be fully initialized.\n * Call this if you need guaranteed persistence before proceeding.\n */\n async waitForReady(): Promise<void> {\n if (this.isReady) return;\n if (this.initPromise) {\n await this.initPromise;\n }\n }\n\n /**\n * Flushes all queued operations once IndexedDB is ready.\n */\n private async flushQueue(): Promise<void> {\n const queue = this.operationQueue;\n this.operationQueue = [];\n\n for (const op of queue) {\n try {\n let result: any;\n switch (op.type) {\n case 'put':\n result = await this.putInternal(op.args[0], op.args[1]);\n break;\n case 'remove':\n result = await this.removeInternal(op.args[0]);\n break;\n case 'setMeta':\n result = await this.setMetaInternal(op.args[0], op.args[1]);\n break;\n case 'appendOpLog':\n result = await this.appendOpLogInternal(op.args[0]);\n break;\n case 'markOpsSynced':\n result = await this.markOpsSyncedInternal(op.args[0]);\n break;\n case 'batchPut':\n result = await this.batchPutInternal(op.args[0]);\n break;\n }\n op.resolve(result);\n } catch (error) {\n op.reject(error);\n }\n }\n }\n\n /**\n * Queues an operation if not ready, or executes immediately if ready.\n */\n private queueOrExecute<T>(\n type: QueuedOperation['type'],\n args: any[],\n executor: () => Promise<T>\n ): Promise<T> {\n if (this.isReady) {\n return executor();\n }\n\n return new Promise<T>((resolve, reject) => {\n this.operationQueue.push({ type, args, resolve, reject });\n });\n }\n\n async close(): Promise<void> {\n if (this.db) {\n this.db.close();\n }\n }\n\n // ============================================\n // Read Operations - Wait for ready\n // ============================================\n\n async get<V>(key: string): Promise<LWWRecord<V> | ORMapRecord<V>[] | any | undefined> {\n // Read operations must wait for DB to be ready\n await this.waitForReady();\n const result = await this.db?.get('kv_store', key);\n return result?.value;\n }\n\n async getMeta(key: string): Promise<any> {\n await this.waitForReady();\n const result = await this.db?.get('meta_store', key);\n return result?.value;\n }\n\n async getPendingOps(): Promise<OpLogEntry[]> {\n await this.waitForReady();\n const all = await this.db?.getAll('op_log');\n return all?.filter((op: any) => op.synced === 0) || [];\n }\n\n async getAllKeys(): Promise<string[]> {\n await this.waitForReady();\n return (await this.db?.getAllKeys('kv_store')) as string[] || [];\n }\n\n // ============================================\n // Write Operations - Queue if not ready\n // ============================================\n\n async put(key: string, value: any): Promise<void> {\n return this.queueOrExecute('put', [key, value], () => this.putInternal(key, value));\n }\n\n private async putInternal(key: string, value: any): Promise<void> {\n await this.db?.put('kv_store', { key, value });\n }\n\n async remove(key: string): Promise<void> {\n return this.queueOrExecute('remove', [key], () => this.removeInternal(key));\n }\n\n private async removeInternal(key: string): Promise<void> {\n await this.db?.delete('kv_store', key);\n }\n\n async setMeta(key: string, value: any): Promise<void> {\n return this.queueOrExecute('setMeta', [key, value], () => this.setMetaInternal(key, value));\n }\n\n private async setMetaInternal(key: string, value: any): Promise<void> {\n await this.db?.put('meta_store', { key, value });\n }\n\n async batchPut(entries: Map<string, any>): Promise<void> {\n return this.queueOrExecute('batchPut', [entries], () => this.batchPutInternal(entries));\n }\n\n private async batchPutInternal(entries: Map<string, any>): Promise<void> {\n const tx = this.db?.transaction('kv_store', 'readwrite');\n if (!tx) return;\n\n await Promise.all(\n Array.from(entries.entries()).map(([key, value]) =>\n tx.store.put({ key, value })\n )\n );\n await tx.done;\n }\n\n async appendOpLog(entry: any): Promise<number> {\n return this.queueOrExecute('appendOpLog', [entry], () => this.appendOpLogInternal(entry));\n }\n\n private async appendOpLogInternal(entry: any): Promise<number> {\n const entryToSave = { ...entry, synced: 0 };\n return await this.db?.add('op_log', entryToSave) as number;\n }\n\n async markOpsSynced(lastId: number): Promise<void> {\n return this.queueOrExecute('markOpsSynced', [lastId], () => this.markOpsSyncedInternal(lastId));\n }\n\n private async markOpsSyncedInternal(lastId: number): Promise<void> {\n const tx = this.db?.transaction('op_log', 'readwrite');\n if (!tx) return;\n\n let cursor = await tx.store.openCursor();\n while (cursor) {\n if (cursor.value.id <= lastId) {\n const update = { ...cursor.value, synced: 1 };\n await cursor.update(update);\n }\n cursor = await cursor.continue();\n }\n await tx.done;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,iBAAuB;AAoBhB,IAAM,aAAN,MAA4C;AAAA,EAA5C;AAGL,SAAQ,UAAU;AAClB,SAAQ,iBAAoC,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ7C,MAAM,WAAW,QAA+B;AAE9C,SAAK,cAAc,KAAK,mBAAmB,MAAM;AAAA,EAEnD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAc,mBAAmB,QAA+B;AAC9D,QAAI;AACF,WAAK,gBAAY,mBAAO,QAAQ,GAAG;AAAA,QACjC,QAAQ,IAAI;AACV,cAAI,CAAC,GAAG,iBAAiB,SAAS,UAAU,GAAG;AAC7C,eAAG,kBAAkB,YAAY,EAAE,SAAS,MAAM,CAAC;AAAA,UACrD;AACA,cAAI,CAAC,GAAG,iBAAiB,SAAS,QAAQ,GAAG;AAC3C,eAAG,kBAAkB,UAAU,EAAE,SAAS,MAAM,eAAe,KAAK,CAAC;AAAA,UACvE;AACA,cAAI,CAAC,GAAG,iBAAiB,SAAS,YAAY,GAAG;AAC/C,eAAG,kBAAkB,cAAc,EAAE,SAAS,MAAM,CAAC;AAAA,UACvD;AAAA,QACF;AAAA,MACF,CAAC;AAED,WAAK,KAAK,MAAM,KAAK;AACrB,WAAK,UAAU;AAGf,YAAM,KAAK,WAAW;AAAA,IACxB,SAAS,OAAO;AAEd,YAAM;AAAA,IACR;AAAA,EACF;AAAA;AAAA;A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5C,cAAM,OAAO,OAAO,MAAM;AAAA,MAC5B;AACA,eAAS,MAAM,OAAO,SAAS;AAAA,IACjC;AACA,UAAM,GAAG;AAAA,EACX;AACF;","names":[]}
package/dist/index.mjs CHANGED
@@ -2,53 +2,151 @@
2
2
  import { openDB } from "idb";
3
3
  var IDBAdapter = class {
4
4
  constructor() {
5
- this.dbName = "";
5
+ this.isReady = false;
6
+ this.operationQueue = [];
6
7
  }
8
+ /**
9
+ * Initializes IndexedDB in the background.
10
+ * Returns immediately - does NOT block on IndexedDB being ready.
11
+ * Use waitForReady() if you need to ensure initialization is complete.
12
+ */
7
13
  async initialize(dbName) {
8
- this.dbName = dbName;
9
- this.dbPromise = openDB(dbName, 2, {
10
- // Bump version for new stores if needed, though we reuse kv_store
11
- upgrade(db, oldVersion, newVersion, transaction) {
12
- if (!db.objectStoreNames.contains("kv_store")) {
13
- db.createObjectStore("kv_store", { keyPath: "key" });
14
- }
15
- if (!db.objectStoreNames.contains("op_log")) {
16
- db.createObjectStore("op_log", { keyPath: "id", autoIncrement: true });
14
+ this.initPromise = this.initializeInternal(dbName);
15
+ }
16
+ /**
17
+ * Internal initialization that actually opens IndexedDB.
18
+ */
19
+ async initializeInternal(dbName) {
20
+ try {
21
+ this.dbPromise = openDB(dbName, 2, {
22
+ upgrade(db) {
23
+ if (!db.objectStoreNames.contains("kv_store")) {
24
+ db.createObjectStore("kv_store", { keyPath: "key" });
25
+ }
26
+ if (!db.objectStoreNames.contains("op_log")) {
27
+ db.createObjectStore("op_log", { keyPath: "id", autoIncrement: true });
28
+ }
29
+ if (!db.objectStoreNames.contains("meta_store")) {
30
+ db.createObjectStore("meta_store", { keyPath: "key" });
31
+ }
17
32
  }
18
- if (!db.objectStoreNames.contains("meta_store")) {
19
- db.createObjectStore("meta_store", { keyPath: "key" });
33
+ });
34
+ this.db = await this.dbPromise;
35
+ this.isReady = true;
36
+ await this.flushQueue();
37
+ } catch (error) {
38
+ throw error;
39
+ }
40
+ }
41
+ /**
42
+ * Waits for IndexedDB to be fully initialized.
43
+ * Call this if you need guaranteed persistence before proceeding.
44
+ */
45
+ async waitForReady() {
46
+ if (this.isReady) return;
47
+ if (this.initPromise) {
48
+ await this.initPromise;
49
+ }
50
+ }
51
+ /**
52
+ * Flushes all queued operations once IndexedDB is ready.
53
+ */
54
+ async flushQueue() {
55
+ const queue = this.operationQueue;
56
+ this.operationQueue = [];
57
+ for (const op of queue) {
58
+ try {
59
+ let result;
60
+ switch (op.type) {
61
+ case "put":
62
+ result = await this.putInternal(op.args[0], op.args[1]);
63
+ break;
64
+ case "remove":
65
+ result = await this.removeInternal(op.args[0]);
66
+ break;
67
+ case "setMeta":
68
+ result = await this.setMetaInternal(op.args[0], op.args[1]);
69
+ break;
70
+ case "appendOpLog":
71
+ result = await this.appendOpLogInternal(op.args[0]);
72
+ break;
73
+ case "markOpsSynced":
74
+ result = await this.markOpsSyncedInternal(op.args[0]);
75
+ break;
76
+ case "batchPut":
77
+ result = await this.batchPutInternal(op.args[0]);
78
+ break;
20
79
  }
80
+ op.resolve(result);
81
+ } catch (error) {
82
+ op.reject(error);
21
83
  }
84
+ }
85
+ }
86
+ /**
87
+ * Queues an operation if not ready, or executes immediately if ready.
88
+ */
89
+ queueOrExecute(type, args, executor) {
90
+ if (this.isReady) {
91
+ return executor();
92
+ }
93
+ return new Promise((resolve, reject) => {
94
+ this.operationQueue.push({ type, args, resolve, reject });
22
95
  });
23
- await this.dbPromise;
24
96
  }
25
97
  async close() {
98
+ if (this.db) {
99
+ this.db.close();
100
+ }
26
101
  }
102
+ // ============================================
103
+ // Read Operations - Wait for ready
104
+ // ============================================
27
105
  async get(key) {
28
- const db = await this.dbPromise;
29
- const result = await db?.get("kv_store", key);
106
+ await this.waitForReady();
107
+ const result = await this.db?.get("kv_store", key);
30
108
  return result?.value;
31
109
  }
110
+ async getMeta(key) {
111
+ await this.waitForReady();
112
+ const result = await this.db?.get("meta_store", key);
113
+ return result?.value;
114
+ }
115
+ async getPendingOps() {
116
+ await this.waitForReady();
117
+ const all = await this.db?.getAll("op_log");
118
+ return all?.filter((op) => op.synced === 0) || [];
119
+ }
120
+ async getAllKeys() {
121
+ await this.waitForReady();
122
+ return await this.db?.getAllKeys("kv_store") || [];
123
+ }
124
+ // ============================================
125
+ // Write Operations - Queue if not ready
126
+ // ============================================
32
127
  async put(key, value) {
33
- const db = await this.dbPromise;
34
- await db?.put("kv_store", { key, value });
128
+ return this.queueOrExecute("put", [key, value], () => this.putInternal(key, value));
129
+ }
130
+ async putInternal(key, value) {
131
+ await this.db?.put("kv_store", { key, value });
35
132
  }
36
133
  async remove(key) {
37
- const db = await this.dbPromise;
38
- await db?.delete("kv_store", key);
134
+ return this.queueOrExecute("remove", [key], () => this.removeInternal(key));
39
135
  }
40
- async getMeta(key) {
41
- const db = await this.dbPromise;
42
- const result = await db?.get("meta_store", key);
43
- return result?.value;
136
+ async removeInternal(key) {
137
+ await this.db?.delete("kv_store", key);
44
138
  }
45
139
  async setMeta(key, value) {
46
- const db = await this.dbPromise;
47
- await db?.put("meta_store", { key, value });
140
+ return this.queueOrExecute("setMeta", [key, value], () => this.setMetaInternal(key, value));
141
+ }
142
+ async setMetaInternal(key, value) {
143
+ await this.db?.put("meta_store", { key, value });
48
144
  }
49
145
  async batchPut(entries) {
50
- const db = await this.dbPromise;
51
- const tx = db?.transaction("kv_store", "readwrite");
146
+ return this.queueOrExecute("batchPut", [entries], () => this.batchPutInternal(entries));
147
+ }
148
+ async batchPutInternal(entries) {
149
+ const tx = this.db?.transaction("kv_store", "readwrite");
52
150
  if (!tx) return;
53
151
  await Promise.all(
54
152
  Array.from(entries.entries()).map(
@@ -58,18 +156,17 @@ var IDBAdapter = class {
58
156
  await tx.done;
59
157
  }
60
158
  async appendOpLog(entry) {
61
- const db = await this.dbPromise;
62
- const entryToSave = { ...entry, synced: 0 };
63
- return await db?.add("op_log", entryToSave);
159
+ return this.queueOrExecute("appendOpLog", [entry], () => this.appendOpLogInternal(entry));
64
160
  }
65
- async getPendingOps() {
66
- const db = await this.dbPromise;
67
- const all = await db?.getAll("op_log");
68
- return all?.filter((op) => op.synced === 0) || [];
161
+ async appendOpLogInternal(entry) {
162
+ const entryToSave = { ...entry, synced: 0 };
163
+ return await this.db?.add("op_log", entryToSave);
69
164
  }
70
165
  async markOpsSynced(lastId) {
71
- const db = await this.dbPromise;
72
- const tx = db?.transaction("op_log", "readwrite");
166
+ return this.queueOrExecute("markOpsSynced", [lastId], () => this.markOpsSyncedInternal(lastId));
167
+ }
168
+ async markOpsSyncedInternal(lastId) {
169
+ const tx = this.db?.transaction("op_log", "readwrite");
73
170
  if (!tx) return;
74
171
  let cursor = await tx.store.openCursor();
75
172
  while (cursor) {
@@ -81,10 +178,6 @@ var IDBAdapter = class {
81
178
  }
82
179
  await tx.done;
83
180
  }
84
- async getAllKeys() {
85
- const db = await this.dbPromise;
86
- return await db?.getAllKeys("kv_store") || [];
87
- }
88
181
  };
89
182
  export {
90
183
  IDBAdapter
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/IDBAdapter.ts"],"sourcesContent":["import { LWWRecord, ORMapRecord } from '@topgunbuild/core';\nimport { IStorageAdapter, OpLogEntry } from '@topgunbuild/client';\nimport { openDB, IDBPDatabase } from 'idb';\n\nexport class IDBAdapter implements IStorageAdapter {\n private dbPromise?: Promise<IDBPDatabase>;\n private dbName: string = '';\n\n async initialize(dbName: string): Promise<void> {\n this.dbName = dbName;\n this.dbPromise = openDB(dbName, 2, { // Bump version for new stores if needed, though we reuse kv_store\n upgrade(db, oldVersion, newVersion, transaction) {\n if (!db.objectStoreNames.contains('kv_store')) {\n db.createObjectStore('kv_store', { keyPath: 'key' });\n }\n if (!db.objectStoreNames.contains('op_log')) {\n db.createObjectStore('op_log', { keyPath: 'id', autoIncrement: true });\n }\n if (!db.objectStoreNames.contains('meta_store')) {\n db.createObjectStore('meta_store', { keyPath: 'key' });\n }\n },\n });\n await this.dbPromise;\n }\n\n async close(): Promise<void> {\n // No-op\n }\n\n async get<V>(key: string): Promise<LWWRecord<V> | ORMapRecord<V>[] | any | undefined> {\n const db = await this.dbPromise;\n const result = await db?.get('kv_store', key);\n return result?.value; // We store { key, value: ... }\n }\n\n async put(key: string, value: any): Promise<void> {\n const db = await this.dbPromise;\n await db?.put('kv_store', { key, value });\n }\n\n async remove(key: string): Promise<void> {\n const db = await this.dbPromise;\n await db?.delete('kv_store', key);\n }\n\n async getMeta(key: string): Promise<any> {\n const db = await this.dbPromise;\n const result = await db?.get('meta_store', key);\n return result?.value;\n }\n\n async setMeta(key: string, value: any): Promise<void> {\n const db = await this.dbPromise;\n await db?.put('meta_store', { key, value });\n }\n\n async batchPut(entries: Map<string, any>): Promise<void> {\n const db = await this.dbPromise;\n const tx = db?.transaction('kv_store', 'readwrite');\n if (!tx) return;\n\n await Promise.all(\n Array.from(entries.entries()).map(([key, value]) =>\n tx.store.put({ key, value })\n )\n );\n await tx.done;\n }\n\n async appendOpLog(entry: any): Promise<number> {\n const db = await this.dbPromise;\n // Ensure synced is 0\n const entryToSave = { ...entry, synced: 0 };\n return await db?.add('op_log', entryToSave) as number;\n }\n\n async getPendingOps(): Promise<OpLogEntry[]> {\n const db = await this.dbPromise;\n const all = await db?.getAll('op_log');\n return all?.filter((op: any) => op.synced === 0) || [];\n }\n\n async markOpsSynced(lastId: number): Promise<void> {\n const db = await this.dbPromise;\n const tx = db?.transaction('op_log', 'readwrite');\n if (!tx) return;\n\n let cursor = await tx.store.openCursor();\n while (cursor) {\n if (cursor.value.id <= lastId) {\n const update = { ...cursor.value, synced: 1 };\n await cursor.update(update);\n }\n cursor = await cursor.continue();\n }\n await tx.done;\n }\n\n async getAllKeys(): Promise<string[]> {\n const db = await this.dbPromise;\n return (await db?.getAllKeys('kv_store')) as string[] || [];\n }\n}\n"],"mappings":";AAEA,SAAS,cAA4B;AAE9B,IAAM,aAAN,MAA4C;AAAA,EAA5C;AAEL,SAAQ,SAAiB;AAAA;AAAA,EAEzB,MAAM,WAAW,QAA+B;AAC9C,SA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import type { LWWRecord, ORMapRecord } from '@topgunbuild/core';\nimport { IStorageAdapter, OpLogEntry } from '@topgunbuild/client';\nimport { openDB } from 'idb';\nimport type { IDBPDatabase } from 'idb';\n\n/**\n * Represents an operation queued before IndexedDB is ready.\n */\ninterface QueuedOperation {\n type: 'put' | 'remove' | 'setMeta' | 'appendOpLog' | 'markOpsSynced' | 'batchPut';\n args: any[];\n resolve: (value: any) => void;\n reject: (error: any) => void;\n}\n\n/**\n * Non-blocking IndexedDB adapter that allows immediate use before initialization completes.\n *\n * Operations are queued in memory and replayed once IndexedDB is ready.\n * This enables true \"memory-first\" behavior where the UI can render immediately\n * without waiting for IndexedDB to initialize (which can take 50-500ms).\n */\nexport class IDBAdapter implements IStorageAdapter {\n private dbPromise?: Promise<IDBPDatabase>;\n private db?: IDBPDatabase;\n private isReady = false;\n private operationQueue: QueuedOperation[] = [];\n private initPromise?: Promise<void>;\n\n /**\n * Initializes IndexedDB in the background.\n * Returns immediately - does NOT block on IndexedDB being ready.\n * Use waitForReady() if you need to ensure initialization is complete.\n */\n async initialize(dbName: string): Promise<void> {\n // Start initialization but don't await it — non-blocking by design\n this.initPromise = this.initializeInternal(dbName);\n // Return immediately\n }\n\n /**\n * Internal initialization that actually opens IndexedDB.\n */\n private async initializeInternal(dbName: string): Promise<void> {\n try {\n this.dbPromise = openDB(dbName, 2, {\n upgrade(db) {\n if (!db.objectStoreNames.contains('kv_store')) {\n db.createObjectStore('kv_store', { keyPath: 'key' });\n }\n if (!db.objectStoreNames.contains('op_log')) {\n db.createObjectStore('op_log', { keyPath: 'id', autoIncrement: true });\n }\n if (!db.objectStoreNames.contains('meta_store')) {\n db.createObjectStore('meta_store', { keyPath: 'key' });\n }\n },\n });\n\n this.db = await this.dbPromise;\n this.isReady = true;\n\n // Replay queued operations in the order they arrived\n await this.flushQueue();\n } catch (error) {\n // Re-throw to allow error handling\n throw error;\n }\n }\n\n /**\n * Waits for IndexedDB to be fully initialized.\n * Call this if you need guaranteed persistence before proceeding.\n */\n async waitForReady(): Promise<void> {\n if (this.isReady) return;\n if (this.initPromise) {\n await this.initPromise;\n }\n }\n\n /**\n * Flushes all queued operations once IndexedDB is ready.\n */\n private async flushQueue(): Promise<void> {\n const queue = this.operationQueue;\n this.operationQueue = [];\n\n for (const op of queue) {\n try {\n let result: any;\n switch (op.type) {\n case 'put':\n result = await this.putInternal(op.args[0], op.args[1]);\n break;\n case 'remove':\n result = await this.removeInternal(op.args[0]);\n break;\n case 'setMeta':\n result = await this.setMetaInternal(op.args[0], op.args[1]);\n break;\n case 'appendOpLog':\n result = await this.appendOpLogInternal(op.args[0]);\n break;\n case 'markOpsSynced':\n result = await this.markOpsSyncedInternal(op.args[0]);\n break;\n case 'batchPut':\n result = await this.batchPutInternal(op.args[0]);\n break;\n }\n op.resolve(result);\n } catch (error) {\n op.reject(error);\n }\n }\n }\n\n /**\n * Queues an operation if not ready, or executes immediately if ready.\n */\n private queueOrExecute<T>(\n type: QueuedOperation['type'],\n args: any[],\n executor: () => Promise<T>\n ): Promise<T> {\n if (this.isReady) {\n return executor();\n }\n\n return new Promise<T>((resolve, reject) => {\n this.operationQueue.push({ type, args, resolve, reject });\n });\n }\n\n async close(): Promise<void> {\n if (this.db) {\n this.db.close();\n }\n }\n\n // ============================================\n // Read Operations - Wait for ready\n // ============================================\n\n async get<V>(key: string): Promise<LWWRecord<V> | ORMapRecord<V>[] | any | undefined> {\n // Read operations must wait for DB to be ready\n await this.waitForReady();\n const result = await this.db?.get('kv_store', key);\n return result?.value;\n }\n\n async getMeta(key: string): Promise<any> {\n await this.waitForReady();\n const result = await this.db?.get('meta_store', key);\n return result?.value;\n }\n\n async getPendingOps(): Promise<OpLogEntry[]> {\n await this.waitForReady();\n const all = await this.db?.getAll('op_log');\n return all?.filter((op: any) => op.synced === 0) || [];\n }\n\n async getAllKeys(): Promise<string[]> {\n await this.waitForReady();\n return (await this.db?.getAllKeys('kv_store')) as string[] || [];\n }\n\n // ============================================\n // Write Operations - Queue if not ready\n // ============================================\n\n async put(key: string, value: any): Promise<void> {\n return this.queueOrExecute('put', [key, value], () => this.putInternal(key, value));\n }\n\n private async putInternal(key: string, value: any): Promise<void> {\n await this.db?.put('kv_store', { key, value });\n }\n\n async remove(key: string): Promise<void> {\n return this.queueOrExecute('remove', [key], () => this.removeInternal(key));\n }\n\n private async removeInternal(key: string): Promise<void> {\n await this.db?.delete('kv_store', key);\n }\n\n async setMeta(key: string, value: any): Promise<void> {\n return this.queueOrExecute('setMeta', [key, value], () => this.setMetaInternal(key, value));\n }\n\n private async setMetaInternal(key: string, value: any): Promise<void> {\n await this.db?.put('meta_store', { key, value });\n }\n\n async batchPut(entries: Map<string, any>): Promise<void> {\n return this.queueOrExecute('batchPut', [entries], () => this.batchPutInternal(entries));\n }\n\n private async batchPutInternal(entries: Map<string, any>): Promise<void> {\n const tx = this.db?.transaction('kv_store', 'readwrite');\n if (!tx) return;\n\n await Promise.all(\n Array.from(entries.entries()).map(([key, value]) =>\n tx.store.put({ key, value })\n )\n );\n await tx.done;\n }\n\n async appendOpLog(entry: any): Promise<number> {\n return this.queueOrExecute('appendOpLog', [entry], () => this.appendOpLogInternal(entry));\n }\n\n private async appendOpLogInternal(entry: any): Promise<number> {\n const entryToSave = { ...entry, synced: 0 };\n return await this.db?.add('op_log', entryToSave) as number;\n }\n\n async markOpsSynced(lastId: number): Promise<void> {\n return this.queueOrExecute('markOpsSynced', [lastId], () => this.markOpsSyncedInternal(lastId));\n }\n\n private async markOpsSyncedInternal(lastId: number): Promise<void> {\n const tx = this.db?.transaction('op_log', 'readwrite');\n if (!tx) return;\n\n let cursor = await tx.store.openCursor();\n while (cursor) {\n if (cursor.value.id <= lastId) {\n const update = { ...cursor.value, synced: 1 };\n await cursor.update(update);\n }\n cursor = await cursor.continue();\n }\n await tx.done;\n }\n}\n"],"mappings":";AAEA,SAAS,cAAc;AAoBhB,IAAM,aAAN,MAA4C;AAAA,EAA5C;AAGL,SAAQ,UAAU;AAClB,SAAQ,iBAAoC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AAC,KAAK,KAAK,MAC5C,GAAG,MAAM,IAAI,EAAE,KAAK,MAAM,CAAC;AAAA,MAC7B;AAAA,IACF;AACA,UAAM,GAAG;AAAA,EACX;AAAA,EAEA,MAAM,YAAY,OAA6B;AAC7C,WAAO,KAAK,eAAe,eAAe,CAAC,KAAK,GAAG,MAAM,KAAK,oBAAoB,KAAK,CAAC;AAAA,EAC1F;AAAA,EAEA,MAAc,oBAAoB,OAA6B;AAC7D,UAAM,cAAc,EAAE,GAAG,OAAO,QAAQ,EAAE;AAC1C,WAAO,MAAM,KAAK,IAAI,IAAI,UAAU,WAAW;AAAA,EACjD;AAAA,EAEA,MAAM,cAAc,QAA+B;AACjD,WAAO,KAAK,eAAe,iBAAiB,CAAC,MAAM,GAAG,MAAM,KAAK,sBAAsB,MAAM,CAAC;AAAA,EAChG;AAAA,EAEA,MAAc,sBAAsB,QAA+B;AACjE,UAAM,KAAK,KAAK,IAAI,YAAY,UAAU,WAAW;AACrD,QAAI,CAAC,GAAI;AAET,QAAI,SAAS,MAAM,GAAG,MAAM,WAAW;AACvC,WAAO,QAAQ;AACb,UAAI,OAAO,MAAM,MAAM,QAAQ;AAC7B,cAAM,SAAS,EAAE,GAAG,OAAO,OAAO,QAAQ,EAAE;AAC5C,cAAM,OAAO,OAAO,MAAM;AAAA,MAC5B;AACA,eAAS,MAAM,OAAO,SAAS;AAAA,IACjC;AACA,UAAM,GAAG;AAAA,EACX;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@topgunbuild/adapters",
3
- "version": "0.11.0",
3
+ "version": "2.0.0",
4
4
  "main": "./dist/index.js",
5
5
  "module": "./dist/index.mjs",
6
6
  "types": "./dist/index.d.ts",
@@ -20,8 +20,8 @@
20
20
  },
21
21
  "dependencies": {
22
22
  "idb": "^7.1.1",
23
- "@topgunbuild/client": "0.11.0",
24
- "@topgunbuild/core": "0.11.0"
23
+ "@topgunbuild/client": "2.0.0",
24
+ "@topgunbuild/core": "2.0.0"
25
25
  },
26
26
  "devDependencies": {
27
27
  "@types/jest": "^29.5.12",
@@ -33,7 +33,12 @@
33
33
  "engines": {
34
34
  "node": ">=18"
35
35
  },
36
- "license": "BSL-1.1",
36
+ "license": "Apache-2.0",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "https://github.com/TopGunBuild/topgun.git",
40
+ "directory": "packages/adapters"
41
+ },
37
42
  "scripts": {
38
43
  "build": "tsup",
39
44
  "test": "jest",