diff --git a/src/index.js b/src/index.js index d010c66..5e964c9 100644 --- a/src/index.js +++ b/src/index.js @@ -1,6 +1,7 @@ /* eslint-disable no-restricted-syntax */ import { request } from 'undici'; -import { join } from 'path'; +import { join } from 'node:path'; +import { URL } from 'node:url'; import loader from '@eik/common-config-loader'; import Asset from './asset.js'; @@ -9,6 +10,8 @@ const trimSlash = (value = '') => { return value; }; +const ABSOLUTE_URL_REGEX = /^[a-zA-Z][a-zA-Z\d+\-.]*?:/; + const fetchImportMaps = async (urls = []) => { try { const maps = urls.map(async (map) => { @@ -95,8 +98,17 @@ export default class NodeClient { file(file = '') { const base = this.base(); + let value; + if (base && ABSOLUTE_URL_REGEX.test(base)) { + const baseURL = new URL(base); + const subPath = join(baseURL.pathname, file); + value = new URL(subPath, base).toString(); + } else { + value = join(base, '/', file); + } + return new Asset({ - value: `${base}${file}`, + value }); } diff --git a/test/index.js b/test/index.js index f91e0b7..fa1a82a 100644 --- a/test/index.js +++ b/test/index.js @@ -186,6 +186,47 @@ tap.test('Client - Retrieve a file path - Development mode is set to "true" - Ba t.end(); }); +tap.test('Client - Retrieve a file path - Development mode is set to "true" - Base is set to absolute URL - file without starting slash', async (t) => { + const client = new NodeClient({ + development: true, + base: 'http://localhost:7777/prefix/', + path: t.context.fixture, + }); + await client.load(); + + const resolved = client.file('some/path/foo.js'); + + t.equal(resolved.value, 'http://localhost:7777/prefix/some/path/foo.js'); + t.end(); +}); + +tap.test('Client - Retrieve a file path - Development mode is set to "true" - Base is set to relative path - file without starting slash', async (t) => { + const client = new NodeClient({ + development: true, + base: '/prefix/', + path: t.context.fixture, + }); + await client.load(); + + const resolved = client.file('some/path/foo.js'); + + t.equal(resolved.value, '/prefix/some/path/foo.js'); + t.end(); +}); + +tap.test('Client - Retrieve a file path - Development mode is set to "true" - Base is unset - file without starting slash', async (t) => { + const client = new NodeClient({ + development: true, + path: t.context.fixture, + }); + await client.load(); + + const resolved = client.file('some/path/foo.js'); + + t.equal(resolved.value, '/some/path/foo.js'); + t.end(); +}); + tap.test('Client - Load maps', async (t) => { const client = new NodeClient({ loadMaps: true,