All files / lib idb.svelte.js

81.73% Statements 179/219
82.25% Branches 51/62
83.33% Functions 25/30
81.73% Lines 179/219

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428            1x 1x   1x 1x                       1x     1x 1x 1x 1x 1x 1x                       1x 1x 1x 12x 96x 60x 60x 12x               1x   20x 16x 20x 20x 65x   65x 20x   20x   20x   20x 32x 32x 32x 32x 27x 27x 27x 27x 32x 20x                 20x 1x     1x     1x           1x 1x     1x 1x           1x 1x 1x 1x   1x 20x   20x 1x   1x   20x 20x 1x 1x 20x       20x 1x 1x 1x 1x   1x 1x     20x           20x           20x 20x 20x 20x     20x   20x   20x 2x 2x 20x         20x 2x 2x 2x     20x               1x 40x 40x 40x 40x 40x 40x 40x           1x 2x 2x 2x 2x 2x                 1x 16x 16x 16x 16x 16x 16x 16x                 1x 81x 81x   81x 81x 81x 81x 81x 81x 81x                 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x                 1x 2x 2x 2x 2x 2x 5x 5x 2x                       1x                                                                     1x 3x       3x 3x   1x 160x       25x   25x 25x         25x 200x 200x 200x 200x 50x 50x 25x     25x         25x       25x 200x 200x 25x       25x 25x 25x   25x 25x         25x   25x 25x   1x 24x 22x 22x 22x 24x 24x                                                           1x  
import { openDB } from 'idb';
import { nanoid } from 'nanoid';
import { idComparator, isReactiveTable, Tables, generateId } from './database.js';
import * as devalue from 'devalue';
 
/** @type {number | null} */
export const previewingPrNumber =
	import.meta.env.previewingPrNumber === 'null' ? null : import.meta.env.previewingPrNumber;
 
export const databaseName = previewingPrNumber ? `previews/pr-${previewingPrNumber}` : 'database';
export const databaseRevision = 3;
 
/**
 * @typedef {typeof import('./database.js').NO_REACTIVE_STATE_TABLES[number]} NonReactiveTableNames
 */
 
/**
 * @typedef {Exclude<keyof typeof Tables, NonReactiveTableNames>} ReactiveTableNames
 */
 
/** @type {Array<keyof typeof Tables>} */
// @ts-ignore
const tableNames = Object.keys(Tables);
 
/** @type {{[Table in ReactiveTableNames]: Array<typeof Tables[Table]['infer']>}} */
export const _tablesState = $state({
	Image: [],
	Metadata: [],
	Observation: [],
	Protocol: [],
	Settings: []
});
 
/**
 *
 * @type {{
 *  [Name in ReactiveTableNames]: ReturnType<typeof wrangler<Name>>
 * } & {
 * 	initialize: () => Promise<void>
 * }}
 */
// @ts-ignore
export const tables = {
	...Object.fromEntries(tableNames.filter(isReactiveTable).map((name) => [name, wrangler(name)])),
	async initialize() {
		for (const name of tableNames) {
			if (!isReactiveTable(name)) continue;
			await tables[name].refresh();
		}
	}
};
 
/**
 *
 * @param {Table} table
 * @template {ReactiveTableNames} Table
 */
function wrangler(table) {
	return {
		get state() {
			return _tablesState[table];
		},
		async refresh() {
			console.info(`refresh ${table}`);
			// @ts-ignore
			_tablesState[table] = await this.list();
		},
		/** @param {string} key  */
		get: async (key) => get(table, key),
		/** @param {string} key  */
		getFromState: (key) => _tablesState[table].find((item) => item.id === key),
		/** @param {typeof Tables[Table]['inferIn']} value */
		async set(value) {
			await set(table, value);
			const output = Tables[table].assert(value);
			const index = _tablesState[table].findIndex((item) => item.id === value.id);
			if (index !== -1) _tablesState[table][index] = output;
			else {
				_tablesState[table].push(output);
				_tablesState[table].sort(idComparator);
			}
			return output;
		},
		/**
		 *
		 * @param {string} key
		 * @param {Prop} property
		 * @param {typeof Tables[Table]['inferIn'][Prop]} value
		 * @template {keyof typeof Tables[Table]['inferIn']} Prop
		 * @returns {Promise<boolean>} true if the item was found and updated, false otherwise
		 */
		async update(key, property, value) {
			const logLabel = `upd ${table} ${key} ${typeof property === 'string' ? property : '<Symbol>'} = ${value}`;
 
			// Get item from DB
			const item = await this.raw.get(key);
 
			// Handle not found
			if (!item) {
				console.error(`${logLabel}: item not found`);
				return false;
			}
 
			// Update property in DB object
			item[property] = value;
			await set(table, item);
 
			// Update reactive state
			const index = _tablesState[table].findIndex((item) => item.id === key);
			if (index === -1) {
				console.debug(
					`${logLabel}: item not found in reactive state, refetching entire list`
				);
				// @ts-ignore
				_tablesState[table] = await this.list();
			} else {
				console.debug(`${logLabel}: updating state @ ${table}[${index}]`);
				_tablesState[table][index] = Tables[table].assert(item);
			}
 
			return true;
		},
		/** @param {Omit<typeof Tables[Table]['inferIn'], 'id'>} value */
		async add(value) {
			return this.set(
				// @ts-ignore
				{ ...value, id: generateId(table) }
			);
		},
		async clear() {
			await clear(table);
			_tablesState[table] = [];
		},
		/**
		 * @param {string | IDBKeyRange} id key of the object to remove
		 */
		async remove(id) {
			await drop(table, id);
			const index = _tablesState[table].findIndex((item) => item.id === id);
			if (index !== -1) {
				console.warn(`del ${table} ${id}: not found in reactive state, re-fetching`);
				// @ts-ignore
				_tablesState[table] = await this.list();
			} else {
				delete _tablesState[table][index];
			}
		},
		/**
		 * Create a read-write transaction, execute `actions` given the transaction's object store for that table, and commit the transaction
		 * @param {(store: import('idb').IDBPObjectStore<IDBDatabaseType, [Table], Table, "readwrite">) => void | Promise<void>} actions
		 * @returns
		 */
		async do(actions) {
			const loglabel = `do ${table} #${nanoid()}`;
			console.debug(loglabel);
			await openTransaction([table], {}, async (tx) => {
				await actions(tx.objectStore(table));
			});
		},
		list: async () => list(table),
		all: () => iterator(table),
		count: async () => {
			const db = await openDatabase();
			return await db.count(table);
		},
		/** Do not go through validation or type morphing, manipulate the underlying database values directly. Useful for performance reasons, when changing only a property inside of an object and leaving the others unchanged, for example */
		raw: {
			/** @param {typeof Tables[Table]['inferIn']} value */
			async set(value) {
				const db = await openDatabase();
				return await db.put(table, value);
			},
			/**
			 * @param {string} key
			 * @returns {Promise<typeof Tables[Table]['inferIn'] | undefined>}
			 */
			async get(key) {
				const db = await openDatabase();
				return await db.get(table, key);
			}
		}
	};
}
 
/**
 *
 * @param {TableName} tableName
 * @param {typeof Tables[TableName]['inferIn']} value
 * @template {keyof typeof Tables} TableName
 */
export async function set(tableName, value) {
	const db = await openDatabase();
	const validator = Tables[tableName];
	validator.assert(value);
	return await db.put(tableName, value).then((result) => {
		return result;
	});
}
 
/**
 * @param {TableName} table
 * @template {keyof typeof Tables} TableName
 */
export async function clear(table) {
	const db = await openDatabase();
	await db.clear(table).then((result) => {
		return result;
	});
}
 
/**
 *
 * @param {TableName} tableName
 * @param {string} key
 * @returns {Promise<undefined | typeof Tables[TableName]['infer']>}
 * @template {keyof typeof Tables} TableName
 */
export async function get(tableName, key) {
	const db = await openDatabase();
	const validator = Tables[tableName];
	return await db.get(tableName, key).then((value) => {
		const out = value ? validator.assert(value) : undefined;
		return out;
	});
}
 
/**
 *
 * @param {TableName} tableName
 * @param {IDBKeyRange} [keyRange]
 * @returns {Promise<Array<typeof Tables[TableName]['infer']>>}
 * @template {keyof typeof Tables} TableName
 */
export async function list(tableName, keyRange = undefined) {
	const db = await openDatabase();
	const validator = Tables[tableName];
	// @ts-ignore
	return await db
		.getAll(tableName, keyRange)
		.then((values) => values.map((v) => validator.assert(v)).sort(idComparator))
		.then((result) => {
			return result;
		});
}
 
/**
 * Delete an entry from a table by key
 * @param {TableName} table
 * @param {string | IDBKeyRange} id
 * @returns {Promise<void>}
 * @template {keyof typeof Tables} TableName
 */
export async function drop(table, id) {
	const db = await openDatabase();
	return await db
		.delete(table, id)
		.then(() => {
			return list(table);
		})
		.then((list) => {
			console.debug(
				`delete ${table} ${id}: objects are now ${list.map((o) => o.id).join(', ')}`
			);
		});
}
 
/**
 *
 * @param {TableName} tableName
 * @param {string} [index]
 * @template {keyof typeof Tables} TableName
 * @yields {typeof Tables[TableName]['infer']}
 */
export async function* iterator(tableName, index = undefined) {
	const db = await openDatabase();
	const validator = Tables[tableName];
	const store = db.transaction(tableName).store;
	const iter = index ? store.index(index).iterate() : store.iterate();
	for await (const cursor of iter) {
		yield validator.assert(cursor.value);
	}
}
 
/**
 * Create a transaction, execute `actions`. Commits the transaction and refreshes reactive tables' state for you
 * @template {Array<keyof typeof Tables>} Tables
 * @template {IDBTransactionMode} [Mode="readwrite"]
 * @param {Tables} tableNames
 * @param {object} param1
 * @param {Mode} [param1.mode="readwrite"]
 * @param {IDBTransactionWithAtLeast<Tables, Mode>} [param1.tx] already existing transaction to use instead of creating a new one. In that case, the transaction is not committed and the reactive tables' state is not refreshed, since it's assumed that a openTransactions() call higher up in the call stack will already do this
 * @param {(tx: IDBTransactionWithAtLeast<Tables, Mode>) => void | Promise<void>} actions
 */
export async function openTransaction(tableNames, { mode }, actions) {
	// @ts-ignore
	mode ??= 'readwrite';
 
	// IndexedDB transactions are auto-comitted, so we can't reuse them reliably. will maybe find a fix for this.
	// if (tx) {
	// 	// @ts-ignore
	// 	console.debug(`txn reuse ${tx.id}`);
	// 	await actions(tx);
	// 	return
	// }
 
	const txid = nanoid(8);
 
	console.debug(`txn open ${txid} tables ${tableNames} mode ${mode}`);
 
	const db = await openDatabase();
	const newTx = db.transaction(tableNames, mode);
 
	// @ts-ignore
	newTx.id = txid;
 
	// @ts-ignore
	await actions(newTx);
 
	// @ts-ignore
	console.debug(`txn commit ${txid} `);
 
	await newTx.done;
 
	for (const table of tableNames.filter(isReactiveTable)) {
		await tables[table].refresh();
	}
}
 
export function databaseHandle() {
	if (!_database) {
		throw new Error('Database not initialized. Call openDatabase() first.');
	}
 
	return _database;
}
 
export async function openDatabase() {
	if (_database) return _database;
 
	/** @type {Array<{[K in keyof typeof Tables]: [K, typeof Tables[K]]}[keyof typeof Tables]>} */
	// @ts-ignore
	const tablesByName = Object.entries(Tables);
 
	_database = await openDB(databaseName, databaseRevision, {
		upgrade(db, oldVersion) {
			/**
			 * @param {keyof typeof Tables} tableName
			 * @param {import('arktype').Type} schema
			 */
			const createTable = (tableName, schema) => {
				if (!schema.meta.table) return;
				const keyPath = schema.meta.table.indexes[0];
				const store = db.createObjectStore(tableName, { keyPath });
				for (const index of schema.meta.table.indexes.slice(1)) {
					store.createIndex(index, index);
				}
			};
 
			// No clean migration path for 1 -> 2, just drop everything
			if (oldVersion === 1) {
				for (const tableName of db.objectStoreNames) {
					db.deleteObjectStore(tableName);
				}
			}
			if (oldVersion === 2) {
				createTable(/* @wc-ignore */ 'ImagePreviewFile', Tables.ImagePreviewFile);
				return;
			}
			for (const [tableName, schema] of tablesByName) {
				createTable(tableName, schema);
			}
		}
	});
 
	// Needed for E2E tests, to send non-[Serializable] values between browser and test runner
	window.devalue = {
		stringify: devalue.stringify,
		parse: devalue.parse
	};
	window.DB = _database;
	window.refreshDB = () => {
		for (const table of tableNames) {
			if (!isReactiveTable(table)) continue;
			tables[table].refresh();
		}
	};
 
	return _database;
}
 
export function nukeDatabase() {
	if (_database) {
		_database.close();
		_database = undefined;
	}
	indexedDB.deleteDatabase(databaseName);
}
 
/**
 * @typedef {{
 *   [Name in keyof typeof Tables]: {
 *      value: (typeof Tables[Name])['inferIn']
 *      key: string,
 *     indexes: {
 *        [IndexName in string]: string;
 *     }
 *   }
 * }} IDBDatabaseType
 */
 
/**
 * @template {Array<keyof typeof Tables>} Stores Required stores
 * @template {IDBTransactionMode} [Mode="readwrite"]
 * @typedef {import('idb').IDBPTransaction<IDBDatabaseType, [...Stores, ...Array<keyof typeof Tables>], Mode>} IDBTransactionWithAtLeast
 */
 
/**
 * @typedef {import('idb').IDBPDatabase<IDBDatabaseType>} DatabaseHandle
 */
 
// Magie vodoo Typescript, pas besoin de comprendre
// Si t'es curieuxse, demande à Gwenn qui sera ravie
// de t'expliquer :3
/**
 * @type {DatabaseHandle | undefined}
 */
let _database;