All files / lib database.js

76.47% Statements 39/51
70% Branches 21/30
91.66% Functions 11/12
79.54% Lines 35/44

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                                                                        10x                                                     8x                       8x                       8x   8x   8x 8x             8x   8x                         16x 16x   16x                   16x 16x                     16x 16x                 16x                     16x               16x       8x                                                     8x                                           8x                           540x     8x                                             72x 64x     72x                     8x   73x   41x   41x   38x 38x   38x 33x                                                                                                                                                                                                                  
import { scope, type } from 'arktype';
 
import { localeFromNavigator } from './i18n.js';
import {
	Dimensions,
	HTTPRequest,
	ID,
	ModelInput,
	Probability,
	References,
	SHA1Hash
} from './schemas/common.js';
import {
	EXIFField,
	MetadataEnumVariant,
	MetadataInferOptions,
	MetadataMergeMethod,
	Metadata as MetadataSchema,
	MetadataType,
	MetadataValue,
	MetadataValues
} from './schemas/metadata.js';
import { Image as ImageSchema, Observation as ObservationSchema } from './schemas/observations.js';
import {
	BeamupSettings,
	FilepathTemplate,
	ModelDetectionOutputShape,
	Protocol as ProtocolSchema
} from './schemas/protocols.js';
import { clamp } from './utils.js';
 
/**
 * Generate an ID for a given table
 * @param {keyof typeof Tables} table
 */
export function generateId(table) {
	return table.slice(0, 1).toLowerCase() + Math.random().toString(36).slice(2, 9);
}
 
if (import.meta.vitest) {
	const { test, expect } = import.meta.vitest;
	test('generateId', () => {
		const id1 = generateId('Protocol');
		const id2 = generateId('Image');
		const id3 = generateId('Observation');
 
		expect(id1.charAt(0)).toBe('p');
		expect(id2.charAt(0)).toBe('i');
		expect(id3.charAt(0)).toBe('o');
 
		expect(id1.length).toBe(8); // 1 + 7 random chars
		expect(id2.length).toBe(8);
		expect(id3.length).toBe(8);
 
		// Should be different each time
		expect(generateId('Protocol')).not.toBe(generateId('Protocol'));
 
		// Should only contain lowercase letters and digits (base36)
		expect(/^[a-z0-9]+$/.test(id1)).toBe(true);
		expect(/^[a-z0-9]+$/.test(id2)).toBe(true);
	});
}
 
const ImageFile = table(
	['id'],
	type({
		/** ID of the associated Image object */
		id: ID,
		bytes: 'ArrayBuffer',
		filename: 'string',
		contentType: /\w+\/\w+/,
		dimensions: Dimensions
	})
);
 
const ImagePreviewFile = table(
	['id'],
	type({
		/** ID of the associated Image object */
		id: ID,
		bytes: 'ArrayBuffer',
		filename: 'string',
		contentType: /\w+\/\w+/,
		dimensions: Dimensions
	})
);
 
const Image = table(['id', 'addedAt'], ImageSchema);
 
const Observation = table(['id', 'addedAt'], ObservationSchema);
 
const Metadata = table('id', MetadataSchema.omit('options'));
const MetadataOption = table(
	['id'],
	MetadataEnumVariant.and({
		id: [/\w+:\w+/, '@', 'ID of the form metadata_id:key'],
		metadataId: ID
	})
);
const Protocol = table('id', ProtocolSchema);
 
const Settings = table(
	'id',
	type({
		id: '"defaults" | "user"',
		protocols: References,
		theme: type.enumerated('dark', 'light', 'auto'),
		// TODO(2025-09-05): remove n===10 after a while
		gridSize: type.number.pipe((n) => (n === 10 ? 1 : clamp(n, 0.5, 2))),
		language: type.enumerated('fr', 'en').default(
			/** @type {() => 'fr' | 'en'} */
			() => {
				// TODO(2025-10-04): remove paraglide migration after a while
 
				try {
					const fromParaglide = localStorage.getItem('PARAGLIDE_LOCALE');
 
					Iif (fromParaglide === 'fr' || fromParaglide === 'en') {
						localStorage.removeItem('PARAGLIDE_LOCALE');
						return fromParaglide;
					}
				} catch (e) {
					// ReferenceError => localStorage not defined => not in browser => isok
					if (!(e instanceof ReferenceError))
						console.warn('Error migrating from PARAGLIDE_LOCALE ', e);
				}
 
				try {
					return localeFromNavigator();
				} catch (e) {
					console.warn('Error getting navigator.language, defaulting to fr', e);
					return 'fr';
				}
			}
		),
		showInputHints: 'boolean',
		showTechnicalMetadata: 'boolean',
		cropAutoNext: 'boolean = false',
		parallelism: type('number').default(() => {
			try {
				return Math.ceil(navigator.hardwareConcurrency / 3);
			} catch (e) {
				console.warn("Couldn't get navigator.hardwareConcurrency, defaulting to 1", e);
				return 1;
			}
		}),
		gallerySort: type({
			direction: type.enumerated('asc', 'desc'),
			key: type.enumerated('filename', 'date')
		}).default(() => ({
			direction: 'asc',
			key: 'date'
		})),
		beamupPreferences: scope({ ID })
			.type({
				'[ID]': {
					enable: 'boolean',
					email: 'string.email | null'
				}
			})
			.default(() => ({})),
		protocolModelSelections: scope({ ID })
			.type({
				'[ID]': {
					// -1 is for none selected
					'[ID]': 'number.integer >= -1'
				}
			})
			.default(() => ({}))
	})
);
 
const BeamupCorrection = table(
	['id'],
	type({
		id: ID,
		client: { version: 'string' },
		protocol: Protocol.pick('id', 'version').and({
			beamup: BeamupSettings
		}),
		metadata: Metadata.pick('id', 'type'),
		subject: {
			'image?': Image.pick('id'),
			'observation?': Observation.pick('id'),
			contentHash: SHA1Hash.or('null')
		},
		'file?': ImageFile.pick(
			'id',
			/* TODO  'contentHash', */ 'filename',
			'contentType',
			'dimensions'
		),
		before: MetadataValue,
		after: MetadataValue,
		occurredAt: 'string.date.iso.parse',
		email: 'string.email | null'
	})
);
 
export const Schemas = {
	ID,
	FilepathTemplate,
	Probability,
	MetadataValues,
	MetadataValue,
	Image,
	ModelInput,
	ModelDetectionOutputShape,
	Observation,
	MetadataInferOptions,
	MetadataType,
	MetadataMergeMethod,
	MetadataEnumVariant,
	Metadata,
	Protocol,
	Settings,
	EXIFField,
	HTTPRequest,
	BeamupCorrection
};
 
export const NO_REACTIVE_STATE_TABLES = /** @type {const} */ ([
	'ImageFile',
	'ImagePreviewFile',
	'MetadataOption',
	'BeamupCorrection'
]);
 
/**
 *
 * @template {keyof typeof Tables} TableName
 * @param {TableName} name
 * @returns {name is Exclude<TableName, typeof NO_REACTIVE_STATE_TABLES[number]>}
 */
export function isReactiveTable(name) {
	return NO_REACTIVE_STATE_TABLES.every((n) => n !== name);
}
 
export const Tables = {
	Image,
	ImageFile,
	ImagePreviewFile,
	Observation,
	Metadata,
	MetadataOption,
	Protocol,
	Settings,
	BeamupCorrection
};
 
/**
 *
 * @param {string|string[]} keyPaths expanded to an array.
 * Every element is an index to be created.
 * Indexes are dot-joined paths to keys in the objects.
 * First index is given as the keyPath argument when creating the object store instead.
 * @param {Schema} schema
 * @template {import('arktype').Type} Schema
 * @returns
 */
function table(keyPaths, schema) {
	const expandedKeyPaths = Array.isArray(keyPaths)
		? keyPaths.map((keyPath) => keyPath)
		: [keyPaths];
 
	return schema.configure({ table: { indexes: expandedKeyPaths } });
}
 
/**
 * Returns a comparator to sort objects by their id property
 * If both IDs are numeric, they are compared numerically even if they are strings
 * @template {{id: string|number} | string | number} IdOrObject
 * @param {IdOrObject} a
 * @param {IdOrObject} b
 * @returns {number}
 */
export const idComparator = (a, b) => {
	// @ts-ignore
	if (typeof a === 'object' && 'id' in a) return idComparator(a.id, b.id);
	// @ts-ignore
	Iif (typeof b === 'object' && 'id' in b) return idComparator(a.id, b.id);
 
	if (typeof a === 'number' && typeof b === 'number') return a - b;
 
	Iif (typeof a === 'number') return -1;
	Iif (typeof b === 'number') return 1;
 
	if (/^\d+$/.test(a) && /^\d+$/.test(b)) return Number(a) - Number(b);
	return a.localeCompare(b);
};
 
/**
 * @typedef  ID
 * @type {typeof ID.infer}
 */
 
/**
 * @typedef  Probability
 * @type {typeof Probability.infer}
 */
 
/**
 * @typedef  MetadataValue
 * @type {typeof MetadataValue.infer}
 */
 
/**
 * @typedef  MetadataValues
 * @type {typeof MetadataValues.infer}
 */
 
/**
 * @typedef  Image
 * @type {typeof Image.infer}
 */
 
/**
 * @typedef  Observation
 * @type {typeof Observation.infer}
 */
 
/**
 * @typedef  MetadataType
 * @type {typeof MetadataType.infer}
 */
 
/**
 * @typedef  MetadataMergeMethod
 * @type {typeof MetadataMergeMethod.infer}
 */
 
/**
 * @typedef  MetadataEnumVariant
 * @type {typeof MetadataEnumVariant.infer}
 */
 
/**
 * @typedef  Metadata
 * @type {typeof Metadata.infer}
 */
 
/**
 * @typedef  Protocol
 * @type {typeof Protocol.infer}
 */
 
/**
 * @typedef  ModelInput
 * @type {typeof ModelInput.infer}
 */
 
/**
 * @typedef  ModelDetectionOutputShape
 * @type {typeof ModelDetectionOutputShape.infer}
 */
 
/**
 * @typedef  Settings
 * @type {typeof Settings.infer}
 */
 
/**
 * @typedef  HTTPRequest
 * @type {typeof HTTPRequest.infer}
 */
 
/**
 * @typedef EXIFField
 * @type {typeof EXIFField.infer}
 */
 
/**
 * @typedef MetadataInferOptions
 * @type {typeof MetadataInferOptions.infer}
 */
 
/**
 * @typedef ImageFile
 * @type {typeof ImageFile.infer}
 */
 
/**
 * @typedef Dimensions
 * @type {typeof Dimensions.infer}
 *
 * @typedef DimensionsInput
 * @type {typeof Dimensions.inferIn}
 */
 
/**
 * @typedef BeamupCorrection
 * @type {typeof BeamupCorrection.infer}
 */