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:
@@ -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 {
|
||||||
switch (data.action) {
|
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) {
|
||||||
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,84 +53,93 @@ 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)
|
const loadResult = tryImportScripts();
|
||||||
try {
|
if (loadResult !== null) {
|
||||||
importScripts('sqlite3.js');
|
handleInitError(loadResult);
|
||||||
} catch (e) {
|
return;
|
||||||
throw new Error(`importScripts('sqlite3.js') failed – is the file served at root? ${e.message}`);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
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
|
||||||
const wasmResponse = await fetch('sqlite3.wasm');
|
let wasmBinary;
|
||||||
if (!wasmResponse.ok) {
|
try {
|
||||||
throw new Error(`Failed to fetch sqlite3.wasm: ${wasmResponse.status} ${wasmResponse.statusText}`);
|
const wasmResponse = await fetch('sqlite3.wasm');
|
||||||
}
|
if (!wasmResponse.ok) {
|
||||||
const wasmBinary = await wasmResponse.arrayBuffer();
|
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 sqlite3 = await self.sqlite3InitModule({
|
try {
|
||||||
print: console.log,
|
const sqlite3 = await self.sqlite3InitModule({
|
||||||
printErr: console.error,
|
print: console.log,
|
||||||
wasmBinary,
|
printErr: console.error,
|
||||||
});
|
wasmBinary,
|
||||||
|
});
|
||||||
|
|
||||||
const opfsAvailable = 'opfs' in sqlite3;
|
const dbName = 'app.db';
|
||||||
const dbName = 'app.db';
|
if ('opfs' in sqlite3) {
|
||||||
|
console.log(`[sqlite.worker] Using persistent OPFS database: ${dbName}`);
|
||||||
|
db = new sqlite3.oo1.OpfsDb(dbName);
|
||||||
|
} else {
|
||||||
|
console.warn('[sqlite.worker] OPFS not available – falling back to in-memory database');
|
||||||
|
db = new sqlite3.oo1.DB(dbName);
|
||||||
|
}
|
||||||
|
|
||||||
if (opfsAvailable) {
|
// Flush buffered messages
|
||||||
console.log(`[sqlite.worker] Using persistent OPFS database: ${dbName}`);
|
isReady = true;
|
||||||
db = new sqlite3.oo1.OpfsDb(dbName);
|
console.log(`[sqlite.worker] Ready. Flushing ${messageQueue.length} buffered message(s).`);
|
||||||
} else {
|
while (messageQueue.length > 0) {
|
||||||
console.warn('[sqlite.worker] OPFS not available – falling back to in-memory database');
|
processMessage(messageQueue.shift());
|
||||||
db = new sqlite3.oo1.DB(dbName);
|
}
|
||||||
}
|
} catch (e) {
|
||||||
|
handleInitError(e?.message ?? String(e));
|
||||||
// Flush buffered messages
|
}
|
||||||
isReady = true;
|
}
|
||||||
console.log(`[sqlite.worker] Ready. Flushing ${messageQueue.length} buffered message(s).`);
|
|
||||||
while (messageQueue.length > 0) {
|
|
||||||
processMessage(messageQueue.shift());
|
|
||||||
}
|
|
||||||
|
|
||||||
|
function tryImportScripts() {
|
||||||
|
try {
|
||||||
|
importScripts('sqlite3.js');
|
||||||
|
return null;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
initError = e?.message ?? String(e);
|
return `importScripts('sqlite3.js') failed – is the file served at root? ${e.message}`;
|
||||||
console.error('[sqlite.worker] Initialization failed:', e);
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Notify all buffered callers so they don't hang indefinitely
|
function handleInitError(message) {
|
||||||
while (messageQueue.length > 0) {
|
initError = message;
|
||||||
|
console.error('[sqlite.worker] Initialization failed:', message);
|
||||||
|
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}`});
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+6
-9
@@ -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"
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user