refactor: streamline deep link handling and improve sqlite worker initialization

- Simplified `DeepLinkHandler` logic by removing redundant return values and enhancing route parsing with `ifBlank()`.
- Refactored `sqlite.worker.js` for better modularity and error handling.
- Added helper methods for script imports and initialization error management.

Signed-off-by: Stefan Mogeritsch <stefan.mo.co@gmail.com>
This commit is contained in:
2026-03-16 10:26:41 +01:00
parent d1fce33716
commit 2c822f8007
2 changed files with 86 additions and 66 deletions
@@ -28,10 +28,24 @@ function processMessage(event) {
const data = event.data; const data = event.data;
if (!data) return; if (!data) return;
let result;
try { try {
result = executeAction(data);
} catch (err) {
console.error('[sqlite.worker] Error processing message:', err);
postMessage({id: data.id, error: err?.message ?? String(err)});
return;
}
postMessage({id: data.id, ...result});
}
function executeAction(data) {
switch (data.action) { switch (data.action) {
case 'exec': { case 'exec': {
if (!data.sql) throw new Error('exec: Missing sql string'); if (!data.sql) {
postMessage({id: data.id, error: 'exec: Missing sql string'});
return null;
}
const rows = []; const rows = [];
db.exec({ db.exec({
sql: data.sql, sql: data.sql,
@@ -39,61 +53,60 @@ function processMessage(event) {
rowMode: 'array', rowMode: 'array',
callback: (row) => rows.push(row), callback: (row) => rows.push(row),
}); });
postMessage({id: data.id, results: {values: rows}}); return {results: {values: rows}};
break;
} }
case 'begin_transaction': case 'begin_transaction':
db.exec('BEGIN TRANSACTION;'); db.exec('BEGIN TRANSACTION;');
postMessage({id: data.id, results: []}); return {results: []};
break;
case 'end_transaction': case 'end_transaction':
db.exec('END TRANSACTION;'); db.exec('END TRANSACTION;');
postMessage({id: data.id, results: []}); return {results: []};
break;
case 'rollback_transaction': case 'rollback_transaction':
db.exec('ROLLBACK TRANSACTION;'); db.exec('ROLLBACK TRANSACTION;');
postMessage({id: data.id, results: []}); return {results: []};
break;
default: default:
throw new Error(`Unsupported action: ${data.action}`); postMessage({id: data.id, error: `Unsupported action: ${data.action}`});
} return null;
} catch (err) {
console.error('[sqlite.worker] Error processing message:', err);
postMessage({id: data.id, error: err?.message ?? String(err)});
} }
} }
// --- Initialization --- // --- Initialization ---
async function init() { async function init() {
try {
// Load sqlite3.js via importScripts (avoids Webpack bundling issues) // Load sqlite3.js via importScripts (avoids Webpack bundling issues)
try { const loadResult = tryImportScripts();
importScripts('sqlite3.js'); if (loadResult !== null) {
} catch (e) { handleInitError(loadResult);
throw new Error(`importScripts('sqlite3.js') failed is the file served at root? ${e.message}`); return;
} }
if (typeof self.sqlite3InitModule !== 'function') { if (typeof self.sqlite3InitModule !== 'function') {
throw new Error('sqlite3InitModule not found after importScripts sqlite3.js may be corrupt or wrong version.'); handleInitError('sqlite3InitModule not found after importScripts sqlite3.js may be corrupt or wrong version.');
return;
} }
// Fetch WASM binary manually so we control the URL and can detect failures early // Fetch WASM binary manually so we control the URL and can detect failures early
let wasmBinary;
try {
const wasmResponse = await fetch('sqlite3.wasm'); const wasmResponse = await fetch('sqlite3.wasm');
if (!wasmResponse.ok) { if (!wasmResponse.ok) {
throw new Error(`Failed to fetch sqlite3.wasm: ${wasmResponse.status} ${wasmResponse.statusText}`); handleInitError(`Failed to fetch sqlite3.wasm: ${wasmResponse.status} ${wasmResponse.statusText}`);
return;
}
wasmBinary = await wasmResponse.arrayBuffer();
} catch (e) {
handleInitError(`Failed to fetch sqlite3.wasm: ${e.message}`);
return;
} }
const wasmBinary = await wasmResponse.arrayBuffer();
try {
const sqlite3 = await self.sqlite3InitModule({ const sqlite3 = await self.sqlite3InitModule({
print: console.log, print: console.log,
printErr: console.error, printErr: console.error,
wasmBinary, wasmBinary,
}); });
const opfsAvailable = 'opfs' in sqlite3;
const dbName = 'app.db'; const dbName = 'app.db';
if ('opfs' in sqlite3) {
if (opfsAvailable) {
console.log(`[sqlite.worker] Using persistent OPFS database: ${dbName}`); console.log(`[sqlite.worker] Using persistent OPFS database: ${dbName}`);
db = new sqlite3.oo1.OpfsDb(dbName); db = new sqlite3.oo1.OpfsDb(dbName);
} else { } else {
@@ -107,17 +120,27 @@ async function init() {
while (messageQueue.length > 0) { while (messageQueue.length > 0) {
processMessage(messageQueue.shift()); processMessage(messageQueue.shift());
} }
} catch (e) { } catch (e) {
initError = e?.message ?? String(e); handleInitError(e?.message ?? String(e));
console.error('[sqlite.worker] Initialization failed:', e); }
}
// Notify all buffered callers so they don't hang indefinitely function tryImportScripts() {
try {
importScripts('sqlite3.js');
return null;
} catch (e) {
return `importScripts('sqlite3.js') failed is the file served at root? ${e.message}`;
}
}
function handleInitError(message) {
initError = message;
console.error('[sqlite.worker] Initialization failed:', message);
while (messageQueue.length > 0) { while (messageQueue.length > 0) {
const queued = messageQueue.shift(); const queued = messageQueue.shift();
postMessage({id: queued.data?.id, error: `Worker initialization failed: ${initError}`}); postMessage({id: queued.data?.id, error: `Worker initialization failed: ${initError}`});
} }
} }
}
init(); init();
@@ -22,10 +22,11 @@ class DeepLinkHandler(
fun handleDeepLink(url: String): Boolean { fun handleDeepLink(url: String): Boolean {
val parsed = parseDeepLink(url) ?: return false val parsed = parseDeepLink(url) ?: return false
return processDeepLink(parsed) processDeepLink(parsed)
return true
} }
private fun processDeepLink(deepLink: DeepLink): Boolean { private fun processDeepLink(deepLink: DeepLink) {
val route = cleanRoute(deepLink.route) val route = cleanRoute(deepLink.route)
// If the route requires auth and the user is missing → redirect to log in // If the route requires auth and the user is missing → redirect to log in
@@ -33,20 +34,19 @@ class DeepLinkHandler(
val user = currentUserProvider.getCurrentUser() val user = currentUserProvider.getCurrentUser()
if (user == null) { if (user == null) {
navigation.navigateTo(config.loginRoute) navigation.navigateTo(config.loginRoute)
return true return
} }
// Admin section guard: requires ADMIN role // Admin section guard: requires ADMIN role
if (requiresAdmin(route)) { if (requiresAdmin(route)) {
val isAdmin = user.roles.contains(AppRoles.ADMIN) val isAdmin = user.roles.contains(AppRoles.ADMIN)
if (!isAdmin) { if (!isAdmin) {
navigation.navigateTo(Routes.HOME) navigation.navigateTo(Routes.HOME)
return true return
} }
} }
} }
navigation.navigateTo(deepLink.route) navigation.navigateTo(deepLink.route)
return true
} }
private fun parseDeepLink(url: String): DeepLink? { private fun parseDeepLink(url: String): DeepLink? {
@@ -62,7 +62,7 @@ class DeepLinkHandler(
val parts = withoutScheme.split("/") val parts = withoutScheme.split("/")
if (parts.isEmpty() || parts[0] != config.host) return null if (parts.isEmpty() || parts[0] != config.host) return null
val path = "/" + parts.drop(1).joinToString("/") val path = "/" + parts.drop(1).joinToString("/")
val route = if (path.isBlank()) Routes.HOME else path val route = path.ifBlank { Routes.HOME }
return DeepLink(DeepLinkType.CUSTOM_SCHEME, route, url) return DeepLink(DeepLinkType.CUSTOM_SCHEME, route, url)
} }
@@ -86,7 +86,4 @@ class DeepLinkHandler(
} }
private fun requiresAdmin(route: String): Boolean = route.startsWith("${Routes.Admin.ROOT}/") private fun requiresAdmin(route: String): Boolean = route.startsWith("${Routes.Admin.ROOT}/")
fun generateDeepLink(route: String, useCustomScheme: Boolean = true): String =
if (useCustomScheme) "${config.scheme}://${config.host}$route" else "https://${config.allowedDomains.first()}$route"
} }