loam icon indicating copy to clipboard operation
loam copied to clipboard

loam.initialize throws Invalid base URL exception

Open LuukMoret opened this issue 3 years ago • 3 comments

I'm importing loam dynamically (I don't have an explicit script tag in the html) but it keeps failing when I call initialize. I get the error Failed to construct 'URL': Invalid base URL.

I am passing an absolute url as the first argument in initialize('http://localhost:3000') (initialize('/') also fails) else the webworker call will fail because it seems it can't import relatively due to security (Uncaught SyntaxError: Failed to execute 'importScripts' on 'WorkerGlobalScope': The URL '/loam-worker.js' is invalid.).

I've searched through the code and it seems it happens because of this function in the loam lib code:

function getPathPrefix() {
    return THIS_SCRIPT.src.substring(0, THIS_SCRIPT.src.lastIndexOf('/')) + '/';
}

This will always try to get the first script tag in the html and looks for the src attribute and it will paste '/' behind it causing the new URL call here new URL(loamPrefix, defaultPrefix) to fail when you don't import loam via a script tag in the html, because '/' is an invalid fallback base url. I don't have this because I'm importing dynamically in the code like this:

const loam = await import('loam');
loam.initialize('http://localhost:3000');

If I remove the defaultPrefix from the new URL function in the worker lib code it actually works new URL(loamPrefix) A possible solution to this is to check if a script tag exists to allow for dynamic imports with absolute path prefix, something like this: https://github.com/azavea/loam/commit/b791b266de4c096b4348469d54b670d949545567

LuukMoret avatar Dec 08 '21 10:12 LuukMoret

Sorry for the slow reply here; I noticed that you opened another issue and am wondering whether you were able to resolve this?

ddohler avatar Dec 20 '21 19:12 ddohler

There is still an error in the lib because of the getPathPrefix function not taking into account if there is no script tag and will only return / which causes the new URL(loamPrefix, defaultPrefix) to fail because / is an invalid base url. I resolved it manually by using the patch-package plugin and removing the defaultPrefix argument for now. If you want I can make a repo which reproduced this issue if it's not entirely clear for you what causes the bug.

LuukMoret avatar Dec 21 '21 08:12 LuukMoret

Thanks for the update -- it looks relatively clear what's happening here. I think I should be able to reproduce the issue, but if I run into difficulties I'll let you know!

ddohler avatar Dec 21 '21 13:12 ddohler

@LuukMoret sorry for the delay with this, I haven't had a lot of free time for this project for the past year or so, but I've just put up #102, which I believe should fix this issue. Do you have a sec to take a quick look and confirm it matches your understanding of the issue?

ddohler avatar Sep 30 '22 21:09 ddohler