defuss-db 1.1.4 → 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/dist/client.mjs CHANGED
@@ -1,22 +1,16 @@
1
- export { DefussTable } from './index.mjs';
1
+ export { AggregationBuilder, DefussTable, aggregationReducers, avgBy, countRows, createAggregation, defineTable, firstBy, lastBy, maxBy, minBy, sumBy } from './index.mjs';
2
+ import { n as normalizeTableDefinition, r as resolveIndexedSelectorValue, m as matchesSelector, a as resolveUniqueSelector, b as mergeSelectorIntoValue, f as fromStoredRecord, t as toStoredRecord } from './runtime-C-5MF9ur.mjs';
2
3
 
3
4
  class DexieProvider {
4
5
  db;
5
6
  tables = /* @__PURE__ */ new Map();
7
+ definitions = /* @__PURE__ */ new Map();
6
8
  databaseName;
7
- schema = /* @__PURE__ */ new Map();
8
9
  schemaVersion = 1;
9
10
  isOpen = false;
10
11
  constructor(databaseName) {
11
- if (!databaseName) {
12
- databaseName = "DefussDB";
13
- }
14
- this.databaseName = databaseName;
12
+ this.databaseName = databaseName || "DefussDB";
15
13
  }
16
- /**
17
- * Connects to IndexedDB. Dexie.js manages connections internally.
18
- * @param options - Dexie-specific configuration options.
19
- */
20
14
  async connect(options = {}) {
21
15
  if (this.db && this.isConnected()) {
22
16
  return;
@@ -29,260 +23,274 @@ class DexieProvider {
29
23
  this.db = new DexieImpl(this.databaseName, options);
30
24
  this.isOpen = true;
31
25
  }
32
- /**
33
- * Disconnects from IndexedDB.
34
- */
35
26
  async disconnect() {
36
27
  if (this.db) {
37
28
  this.db.close();
38
29
  this.isOpen = false;
30
+ this.tables.clear();
39
31
  }
40
32
  }
41
- /**
42
- * Checks if the provider is currently connected to the database.
43
- * @returns True if connected, false otherwise.
44
- */
45
33
  isConnected() {
46
34
  return this.isOpen;
47
35
  }
48
- /**
49
- * Creates a table if it doesn't exist with dynamic schema support.
50
- * @param table - The name of the table.
51
- */
52
- async createTable(table) {
53
- if (this.tables.has(table)) return;
54
- if (!this.schema.has(table)) {
55
- this.schema.set(table, { pk: "++" });
36
+ buildSchemaString(definition) {
37
+ const parts = ["id"];
38
+ for (const index of definition.indexes) {
39
+ if (index.selectorKey === "id") {
40
+ continue;
41
+ }
42
+ parts.push(index.unique ? `&${index.storageKey}` : index.storageKey);
56
43
  }
57
- this.schemaVersion++;
44
+ return parts.join(", ");
45
+ }
46
+ async applySchema() {
58
47
  if (this.isOpen) {
59
48
  this.db.close();
60
49
  }
61
- const tableSchema = {};
62
- for (const [tableName, columns] of this.schema.entries()) {
63
- const schemaString = Object.entries(columns).map(([column, indexType]) => {
64
- if (column === "pk") return "++pk";
65
- return indexType ? `${indexType}${column}` : column;
66
- }).join(", ");
67
- tableSchema[tableName] = schemaString;
50
+ const schema = {};
51
+ for (const definition of this.definitions.values()) {
52
+ schema[definition.name] = this.buildSchemaString(definition);
68
53
  }
69
- this.db.version(this.schemaVersion).stores(tableSchema);
54
+ this.schemaVersion += 1;
55
+ this.db.version(this.schemaVersion).stores(schema);
70
56
  await this.db.open();
71
57
  this.isOpen = true;
72
- const tableDexie = this.db.table(table);
73
- this.tables.set(table, tableDexie);
74
- }
75
- /**
76
- * Adds columns to the schema if they don't exist, with proper indexing.
77
- * @param table - The name of the table.
78
- * @param record - The record with properties to consider adding.
79
- */
80
- async ensureColumnsForRecord(table, record) {
81
- const tableSchema = this.schema.get(table) || { pk: "++" };
82
- let schemaUpdated = false;
83
- for (const [prop, value] of Object.entries(record)) {
84
- if (prop === "pk") continue;
85
- if (prop in tableSchema) continue;
86
- if (prop.endsWith("_index")) {
87
- const baseField = prop.slice(0, -6);
88
- if (!(baseField in tableSchema)) {
89
- if (Array.isArray(value)) {
90
- tableSchema[prop] = "*";
91
- } else {
92
- tableSchema[prop] = "";
93
- }
94
- schemaUpdated = true;
95
- }
96
- } else if (!(prop in tableSchema)) {
97
- tableSchema[prop] = "";
98
- schemaUpdated = true;
99
- }
100
- }
101
- if (schemaUpdated) {
102
- this.schema.set(table, tableSchema);
103
- await this.createTable(table);
58
+ this.tables.clear();
59
+ for (const definition of this.definitions.values()) {
60
+ this.tables.set(definition.name, this.db.table(definition.name));
104
61
  }
105
62
  }
106
- /**
107
- * Inserts a record into a table.
108
- * @param table - The name of the table.
109
- * @param record - The record to insert.
110
- * @returns The primary key of the inserted record.
111
- */
112
- async insert(table, record) {
113
- await this.createTable(table);
114
- const insertData = {};
115
- for (const [key, value] of Object.entries(record)) {
116
- if (key === "pk") {
117
- if (value !== void 0) {
118
- insertData.pk = value;
119
- }
120
- continue;
121
- }
122
- insertData[key] = value;
63
+ async ensureTable(definition) {
64
+ const normalized = normalizeTableDefinition(definition);
65
+ const existing = this.definitions.get(normalized.name);
66
+ if (existing) {
67
+ return;
123
68
  }
124
- await this.ensureColumnsForRecord(table, record);
125
- const tableDexie = this.tables.get(table);
126
- const id = await tableDexie.add(insertData);
127
- if (typeof id === "number") {
128
- return id;
129
- } else if (typeof id === "string") {
130
- return id;
131
- } else {
132
- return String(id);
69
+ this.definitions.set(normalized.name, normalized);
70
+ await this.applySchema();
71
+ }
72
+ getTable(definition) {
73
+ const normalized = normalizeTableDefinition(definition);
74
+ const tableDexie = this.tables.get(normalized.name);
75
+ if (!tableDexie) {
76
+ throw new Error(`defuss-db: table '${normalized.name}' is not initialized.`);
133
77
  }
78
+ return { normalized, tableDexie };
134
79
  }
135
- /**
136
- * Finds records in the table based on query.
137
- * @param table - The name of the table.
138
- * @param query - Query criteria.
139
- * @returns An array of matching records.
140
- */
141
- async find(table, query) {
142
- await this.createTable(table);
143
- const tableDexie = this.tables.get(table);
144
- await this.ensureColumnsForRecord(table, query);
145
- if (Object.keys(query).length === 0) {
80
+ async queryRecords(definition, selector) {
81
+ const { normalized, tableDexie } = this.getTable(definition);
82
+ const selectorEntries = Object.entries(selector).filter(
83
+ (entry) => entry[1] !== void 0
84
+ );
85
+ if (selectorEntries.length === 0) {
146
86
  const results2 = await tableDexie.toArray();
147
- return results2.map((result) => this.normalizeRecord(result));
87
+ return results2.map((result) => fromDexieRecord(result));
148
88
  }
149
- let collection = tableDexie.toCollection();
150
- if ("pk" in query) {
151
- try {
152
- const record = await tableDexie.get(query.pk);
153
- return record ? [this.normalizeRecord(record)] : [];
154
- } catch (err) {
155
- collection = collection.and((item) => item.pk === query.pk);
89
+ const indexedEntry = selectorEntries.find(([key, value]) => {
90
+ return resolveIndexedSelectorValue(normalized, key, value) !== null;
91
+ });
92
+ let results;
93
+ if (indexedEntry) {
94
+ const indexedSelector = resolveIndexedSelectorValue(
95
+ normalized,
96
+ indexedEntry[0],
97
+ normalizeDexieIndexableValue(indexedEntry[1])
98
+ );
99
+ if (indexedSelector.storageKey === "id") {
100
+ const result = await tableDexie.get(indexedSelector.value);
101
+ results = result ? [result] : [];
102
+ } else {
103
+ results = await tableDexie.where(indexedSelector.storageKey).equals(indexedSelector.value).toArray();
156
104
  }
157
105
  } else {
158
- for (const [key, value] of Object.entries(query)) {
159
- if (key.endsWith("_index")) {
160
- collection = collection.and((item) => item[key] === value);
161
- } else {
162
- collection = collection.and((item) => item[key] === value);
163
- }
164
- }
106
+ results = await tableDexie.toArray();
165
107
  }
166
- const results = await collection.toArray();
167
- return results.map((result) => this.normalizeRecord(result));
168
- }
169
- /**
170
- * Finds a single record in the table based on query.
171
- * @param table - The name of the table.
172
- * @param query - Query criteria.
173
- * @returns The first matching record or null.
174
- */
175
- async findOne(table, query) {
176
- if (Object.keys(query).length === 1 && "pk" in query) {
177
- await this.createTable(table);
178
- const tableDexie = this.tables.get(table);
179
- try {
180
- const result = await tableDexie.get(query.pk);
181
- return result ? this.normalizeRecord(result) : null;
182
- } catch (err) {
183
- }
108
+ return results.map((result) => fromDexieRecord(result)).filter((result) => matchesSelector(result, selector, normalized));
109
+ }
110
+ async insert(definition, value) {
111
+ await this.ensureTable(definition);
112
+ const { normalized, tableDexie } = this.getTable(definition);
113
+ const storedRecord = await toDexieStoredRecord(normalized, prepareDexiePrimaryKey(value));
114
+ const insertedId = await tableDexie.add(storedRecord);
115
+ if (typeof insertedId === "bigint" || typeof insertedId === "number") {
116
+ return insertedId;
184
117
  }
185
- const results = await this.find(table, query);
186
- return results.length > 0 ? results[0] : null;
187
- }
188
- /**
189
- * Updates records in the table based on query.
190
- * @param table - The name of the table.
191
- * @param query - Query criteria.
192
- * @param update - Fields to update.
193
- */
194
- async update(table, query, update) {
195
- await this.createTable(table);
196
- const tableDexie = this.tables.get(table);
197
- await this.ensureColumnsForRecord(table, query);
198
- await this.ensureColumnsForRecord(table, update);
199
- const updateData = {};
200
- for (const [key, value] of Object.entries(update)) {
201
- if (key === "pk") continue;
202
- updateData[key] = value;
118
+ if (typeof insertedId === "string") {
119
+ return insertedId;
203
120
  }
204
- if (Object.keys(query).length === 1 && "pk" in query) {
205
- await tableDexie.update(query.pk, updateData);
206
- return;
121
+ return String(insertedId);
122
+ }
123
+ async find(definition, selector = {}) {
124
+ await this.ensureTable(definition);
125
+ return this.queryRecords(definition, selector);
126
+ }
127
+ async findOne(definition, selector = {}) {
128
+ const results = await this.find(definition, selector);
129
+ return results[0] ?? null;
130
+ }
131
+ async update(definition, selector, update) {
132
+ await this.ensureTable(definition);
133
+ const { normalized, tableDexie } = this.getTable(definition);
134
+ if (Object.keys(selector).length === 0) {
135
+ throw new Error("defuss-db: update requires a non-empty selector.");
207
136
  }
208
- const collection = tableDexie.toCollection().and((record) => {
209
- for (const [key, value] of Object.entries(query)) {
210
- if (record[key] !== value) return false;
137
+ const records = await this.queryRecords(definition, selector);
138
+ for (const record of records) {
139
+ if (update.id !== void 0 && update.id !== record.id) {
140
+ throw new Error("defuss-db: id cannot be updated.");
211
141
  }
212
- return true;
213
- });
214
- const keys = await collection.primaryKeys();
215
- for (const key of keys) {
216
- await tableDexie.update(key, updateData);
142
+ const nextRecord = {
143
+ ...record,
144
+ ...update,
145
+ id: record.id
146
+ };
147
+ const storedRecord = await toDexieStoredRecord(normalized, nextRecord);
148
+ await tableDexie.put(storedRecord);
217
149
  }
218
150
  }
219
- /**
220
- * Deletes records from the table based on query.
221
- * @param table - The name of the table.
222
- * @param query - Query criteria.
223
- */
224
- async delete(table, query) {
225
- await this.createTable(table);
226
- const tableDexie = this.tables.get(table);
227
- await this.ensureColumnsForRecord(table, query);
228
- if (Object.keys(query).length === 1 && "pk" in query) {
229
- await tableDexie.delete(query.pk);
230
- return;
151
+ async delete(definition, selector) {
152
+ await this.ensureTable(definition);
153
+ const { tableDexie } = this.getTable(definition);
154
+ if (Object.keys(selector).length === 0) {
155
+ throw new Error("defuss-db: delete requires a non-empty selector.");
231
156
  }
232
- const collection = tableDexie.toCollection().and((record) => {
233
- for (const [key, value] of Object.entries(query)) {
234
- if (record[key] !== value) return false;
157
+ const records = await this.queryRecords(definition, selector);
158
+ const ids = records.map((record) => record.id).filter((id) => id !== void 0);
159
+ await tableDexie.bulkDelete(ids);
160
+ }
161
+ async upsert(definition, selector, value) {
162
+ await this.ensureTable(definition);
163
+ const normalized = normalizeTableDefinition(definition);
164
+ resolveUniqueSelector(normalized, selector);
165
+ const mergedValue = mergeSelectorIntoValue(normalized, selector, value);
166
+ const existing = await this.findOne(definition, selector);
167
+ if (existing?.id !== void 0) {
168
+ await this.update(definition, { id: existing.id }, mergedValue);
169
+ return existing.id;
170
+ }
171
+ try {
172
+ return await this.insert(definition, mergedValue);
173
+ } catch (error) {
174
+ const constraintName = error && typeof error === "object" && "name" in error ? String(error.name) : "";
175
+ if (constraintName !== "ConstraintError") {
176
+ throw error;
235
177
  }
236
- return true;
237
- });
238
- const keys = await collection.primaryKeys();
239
- await tableDexie.bulkDelete(keys);
240
- }
241
- /**
242
- * Upserts a record into the table based on query.
243
- * @param table - The name of the table.
244
- * @param record - The record to upsert.
245
- * @param query - Query criteria.
246
- * @returns The primary key of the upserted record.
247
- */
248
- async upsert(table, record, query) {
249
- await this.createTable(table);
250
- const existingRecord = await this.findOne(table, query);
251
- if (existingRecord && existingRecord.pk !== void 0) {
252
- const mergedRecord = { ...record };
253
- await this.update(
254
- table,
255
- { pk: existingRecord.pk },
256
- mergedRecord
257
- );
258
- return existingRecord.pk;
259
- } else {
260
- const mergedRecord = { ...record };
261
- for (const [key, value] of Object.entries(query)) {
262
- if (!(key in mergedRecord)) {
263
- mergedRecord[key] = value;
264
- }
178
+ const retried = await this.findOne(definition, selector);
179
+ if (!retried?.id) {
180
+ throw error;
265
181
  }
266
- return await this.insert(table, mergedRecord);
182
+ await this.update(definition, { id: retried.id }, mergedValue);
183
+ return retried.id;
184
+ }
185
+ }
186
+ }
187
+ function bytesToBase64(bytes) {
188
+ if (typeof Buffer !== "undefined") {
189
+ return Buffer.from(bytes).toString("base64");
190
+ }
191
+ let binary = "";
192
+ for (const byte of bytes) {
193
+ binary += String.fromCharCode(byte);
194
+ }
195
+ return btoa(binary);
196
+ }
197
+ function base64ToArrayBuffer(base64) {
198
+ if (typeof Buffer !== "undefined") {
199
+ const bytes = Buffer.from(base64, "base64");
200
+ const result2 = new Uint8Array(new ArrayBuffer(bytes.byteLength));
201
+ result2.set(bytes);
202
+ return result2.buffer;
203
+ }
204
+ const binary = atob(base64);
205
+ const result = new Uint8Array(new ArrayBuffer(binary.length));
206
+ for (let index = 0; index < binary.length; index += 1) {
207
+ result[index] = binary.charCodeAt(index);
208
+ }
209
+ return result.buffer;
210
+ }
211
+ function isBlobLike(value) {
212
+ return typeof value === "object" && value !== null && typeof value.arrayBuffer === "function" && typeof value.slice === "function" && typeof value.type === "string";
213
+ }
214
+ function isEncodedDexieValue(value) {
215
+ return value.__defussType === "blob";
216
+ }
217
+ async function encodeDexieValue(value) {
218
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
219
+ return value;
220
+ }
221
+ if (value instanceof Date || value instanceof ArrayBuffer) {
222
+ return value;
223
+ }
224
+ if (isBlobLike(value)) {
225
+ return {
226
+ __defussType: "blob",
227
+ value: bytesToBase64(new Uint8Array(await value.arrayBuffer())),
228
+ mimeType: value.type
229
+ };
230
+ }
231
+ if (Array.isArray(value)) {
232
+ return Promise.all(value.map((item) => encodeDexieValue(item)));
233
+ }
234
+ if (typeof value === "object") {
235
+ const result = {};
236
+ for (const [key, nestedValue] of Object.entries(value)) {
237
+ result[key] = await encodeDexieValue(nestedValue);
267
238
  }
239
+ return result;
240
+ }
241
+ return value;
242
+ }
243
+ function decodeDexieValue(value) {
244
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || value instanceof Date || value instanceof ArrayBuffer) {
245
+ return value;
246
+ }
247
+ if (Array.isArray(value)) {
248
+ return value.map((item) => decodeDexieValue(item));
249
+ }
250
+ if (typeof value === "object" && value !== null && isEncodedDexieValue(value)) {
251
+ return new Blob([
252
+ base64ToArrayBuffer(String(value.value ?? ""))
253
+ ], {
254
+ type: String(value.mimeType ?? "")
255
+ });
268
256
  }
269
- /**
270
- * Normalizes a database record to match DefussRecord structure.
271
- * @param record - The record from the database.
272
- * @returns A normalized DefussRecord.
273
- */
274
- normalizeRecord(record) {
257
+ if (typeof value === "object" && value !== null) {
275
258
  const result = {};
276
- for (const [key, value] of Object.entries(record)) {
277
- if (key === "pk") {
278
- result.pk = value;
279
- continue;
280
- }
281
- if (key.startsWith("_")) continue;
282
- result[key] = value;
259
+ for (const [key, nestedValue] of Object.entries(value)) {
260
+ result[key] = decodeDexieValue(nestedValue);
283
261
  }
284
262
  return result;
285
263
  }
264
+ return value;
265
+ }
266
+ async function toDexieStoredRecord(definition, value) {
267
+ return encodeDexieValue(toStoredRecord(definition, value));
268
+ }
269
+ function fromDexieRecord(storedRecord) {
270
+ return fromStoredRecord(decodeDexieValue(storedRecord));
271
+ }
272
+ function prepareDexiePrimaryKey(value) {
273
+ const nextValue = { ...value };
274
+ if (nextValue.id === void 0) {
275
+ nextValue.id = createDexiePrimaryKey();
276
+ return nextValue;
277
+ }
278
+ if (typeof nextValue.id === "bigint") {
279
+ nextValue.id = String(nextValue.id);
280
+ }
281
+ return nextValue;
282
+ }
283
+ function normalizeDexieIndexableValue(value) {
284
+ if (typeof value === "bigint") {
285
+ return String(value);
286
+ }
287
+ return value;
288
+ }
289
+ function createDexiePrimaryKey() {
290
+ if (typeof globalThis.crypto?.randomUUID === "function") {
291
+ return globalThis.crypto.randomUUID();
292
+ }
293
+ return `id_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
286
294
  }
287
295
 
288
296
  export { DexieProvider };