feat(docker): serve the app from any subpath with a runtime BASE_URL (#565)

* feat(docker): serve the app from any subpath with a runtime BASE_URL

BASE_URL was a build argument, so hosting under a subfolder meant building
your own image (or pulling the separate baseurl-it-tools tag, which is only
ever right for /it-tools/). Make it a runtime setting instead, so the regular
image works anywhere:

    docker run -e BASE_URL=/it-tools/ ghcr.io/sharevb/it-tools:latest

The build is now path-agnostic. Vite's base is relative, so hashed assets and
lazy chunks resolve against the chunk that imports them, and the single
absolute anchor left in the output is a `<base href="/">` injected into
index.html. nginx rewrites that one tag per request (sub_filter) from the
normalised BASE_URL, and the app reads its base back from it at runtime
(src/utils/base-url.ts) for the router and for every URL it builds into
public/ -- import.meta.env.BASE_URL is meaningless in a relative build.

Also handled:

- both reverse-proxy styles: the prefix may reach the container (stripped by
  the rewrite) or be stripped by the proxy first (nothing to do). The assets
  location matches with or without it, so a missing chunk is still a 404
  rather than the SPA shell.
- `/it-tools` redirects to `/it-tools/`, with a relative Location so the
  scheme of the proxy hop does not leak into it.
- the PWA: manifest URLs are relative to the manifest, workbox precache
  entries relative to the service worker, and the worker is registered
  against the runtime base rather than the build-time one.
- BASE_URL is normalised (`it-tools`, `/it-tools`, `/it-tools/` all work) and
  rejected if it is not a plain path, since it lands in an HTML attribute and
  in an nginx regex.

Defaults are unchanged: with BASE_URL unset the rendered config and the
served page are what they were, except that index.html loses ETag/Last-Modified
to sub_filter. On a read-only filesystem the template cannot be re-rendered,
so BASE_URL is ignored there and the container now says so, like it already
had to for PORT.

Building with --build-arg BASE_URL still works but only moves the image
default; the baseurl-it-tools tag is now just latest with that default.

Closes sharevb/it-tools#403

* fix(docker): restore the PWA update reload, escape BASE_URL in the nginx regexes

Follow-up from review of the runtime BASE_URL change.

- registerSW() in autoUpdate mode reloaded the page when a newly deployed
  worker took over (workbox-window's `activated` handler); hand-rolling the
  registration dropped that, so a tab kept running the previous bundle until
  it navigated. Reimplemented on `controllerchange`, guarded so a first
  install -- which also claims the page -- does not reload. Verified by
  counting document loads across an install and a simulated deploy: 1 load on
  first visit, exactly 1 reload when a new worker takes over.
- The comment justifying the hand-rolled registration was wrong: register()
  does resolve a relative URL against `<base href>`. The real reason is
  workbox-window's own urlsMatch(), which resolves against location.href, so
  a relative sw URL misidentifies the worker on a route deeper than one
  segment. Comment now says that.
- BASE_URL allows `.`, which is a metacharacter in the two nginx regexes it
  is spliced into: `/it.tools/` also matched `/itXtools/`. The entrypoint now
  exports regex-escaped forms for those, keeping the literal value for the
  sub_filter replacement and the redirect target.
- Dropped `$uri/` from try_files. Nothing in the build is a directory with an
  index, so the only thing it ever produced was nginx's trailing-slash
  redirect -- computed after the prefix rewrite, so `/it-tools/figlet-fonts`
  answered `301 /figlet-fonts/` and bounced the browser out of the app.
- The sub_filter comment claimed index.html was the only response losing
  ETag/Last-Modified; public/visualsubnetcalc/calc.html is HTML too and is
  equally affected. Comment corrected.
- README: in the prefix-stripping proxy setup, `/it-tools` without the
  trailing slash never reaches the container, so the proxy has to redirect it
  (as the sample does). Said so.
- The new e2e test reloaded a page that had just started pulling in a tool's
  chunks; WebKit cancelled the load ~1 run in 3 (the app reloads itself on an
  aborted chunk fetch). It opens the URL in a second tab instead: 8/8 on
  WebKit, 3/3 browsers green.

* fix(build): validate BASE_URL before it reaches the <base href>

From Copilot's review of #10.

The container validates its runtime BASE_URL, but the build-time one went
straight into an HTML attribute unchecked: a value carrying a quote rewrote
the tag around it, and one carrying a space or `..` quietly produced a page
that loads from the wrong place. Apply the same rule the entrypoint does --
a plain path of unreserved characters -- and fail the build otherwise.

Also: "can not" -> "cannot" in the read-only filesystem warning.

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-08-19 22:16:54 +02:00
1 parent ec740dd063
commit 0a1f5dc450
25 files changed
+560 -59

No files matched your search

@@ -1,5 +1,10 @@
name: Build and Push Docker Image (baseurl-it-tools)
# Kept for the deployments already pulling the `baseurl-it-tools` tag. It is no longer a
# different build: BASE_URL is a runtime setting now, so this image is the same one as
# `latest` with the default moved to /it-tools/, and `latest` with `-e BASE_URL=/it-tools/`
# gets you exactly the same thing.
env:
VITE_VERCEL_ENV: production
+16 -4
View File
@@ -13,8 +13,10 @@ COPY patches patches
COPY stubs stubs
RUN npm install -g pnpm@11 && pnpm i --ignore-scripts --frozen-lockfile
COPY . .
ARG BASE_URL
ENV BASE_URL=${BASE_URL}
# Deliberately no BASE_URL here: the bundle is built path-agnostic (relative asset URLs
# plus a `<base href="/">` in index.html) so that one image can be served from any
# subpath. The path is a runtime setting instead -- see the BASE_URL environment variable
# on the production stage below.
ARG VITE_AVAILABLE_LOCALES
ENV VITE_AVAILABLE_LOCALES=${VITE_AVAILABLE_LOCALES}
ENV VITE_VERCEL_ENV=production
@@ -28,8 +30,15 @@ LABEL maintainer="ShareVB <sharevb@gmail.com>" \
LABEL org.opencontainers.image.source=github.com/sharevb/it-tools
ENV VITE_VERCEL_ENV=production
ARG BASE_URL
# The path the app is served under. Override it at run time -- `docker run -e
# BASE_URL=/it-tools/`, `environment: BASE_URL: /it-tools/` in a compose file -- and nginx
# rewrites the `<base href>` in index.html on the way out; nothing is baked in. The build
# arg only moves the default, for anyone who prefers to ship an image that is preconfigured
# for a subpath. See docker-entrypoint.d/18-resolve-base-url.envsh and nginx.conf.
ARG BASE_URL=/
ENV BASE_URL=${BASE_URL}
COPY --from=build-stage /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/templates/default.conf.template
@@ -49,7 +58,10 @@ ENV NGINX_ENTRYPOINT_WORKER_PROCESSES_AUTOTUNE=1
# Without this the image would fall back to the stock welcome config from the
# base image: no SPA fallback, so deep links 404 on refresh, and no COOP/COEP,
# so the WebAssembly-backed tools stop working.
RUN envsubst '${PORT}' \
# Sourcing the entrypoint's own resolver keeps the baked-in BASE_URL normalised and
# validated exactly the way a runtime one would be.
RUN . /docker-entrypoint.d/18-resolve-base-url.envsh \
&& envsubst '${PORT} ${BASE_URL} ${BASE_URL_REGEX} ${BASE_URL_NO_SLASH_REGEX}' \
< /etc/nginx/templates/default.conf.template \
> /etc/nginx/conf.d/default.conf
+38 -16
View File
@@ -4,6 +4,10 @@ Since the _base image_ is now `nginx-unpriviledged` the container will now liste
You can override listening port using environment variable `PORT` (docker option `-e PORT=8888`).
You can serve the app from a subfolder using environment variable `BASE_URL` (docker option
`-e BASE_URL=/it-tools/`), without rebuilding the image -- see
[Host in a subfolder](#host-in-a-subfolder-it-tools).
If the container needs to listen to IPv6, it needs to be enabled: https://serverfault.com/questions/1147296/how-to-enable-ipv6-on-ubuntu-20-04. Alternatively, you can mount your own `nginx.conf` own using docker option `-v "./nginx.conf:/etc/nginx/templates/default.conf.template"` (with `listen [::]:8080;` removed)
## Build requirements
@@ -222,29 +226,39 @@ docker build -t it-tools-fr --build-arg VITE_LANGUAGE=fr .
docker run -d --name it-tools-fr --restart unless-stopped -p 8080:8080 it-tools-fr
```
## Build container image for a custom subfolder
## Host in a subfolder (`/it-tools/`)
According to https://github.com/sharevb/it-tools/pull/461#issuecomment-1602506049 and https://github.com/CorentinTh/it-tools/pull/461:
The container serves the app from whatever path you point `BASE_URL` at. Nothing is baked
into the image, so the regular `latest` image works for any subfolder -- no rebuild, no
subfolder-specific tag:
```
docker build -t it-tools --build-arg BASE_URL="/my-folder/" .
docker run -d --name it-tools --restart unless-stopped -p 8080:8080 it-tools
```yaml
services:
it-tools:
image: ghcr.io/sharevb/it-tools:latest
restart: unless-stopped
environment:
BASE_URL: /it-tools/
ports:
- 8080:8080
```
Then if you go to `http://localhost:8080` you'll get a blank page, but opening the DevTools (& refreshing) you'll notice in the Network tab that the app is trying to fetch assets from `/my-folder/...`
or `docker run -d --name it-tools -e BASE_URL=/it-tools/ -p 8080:8080 ghcr.io/sharevb/it-tools:latest`.
So you would need to put another server in front of it, like [Nginx Proxy Manager](https://nginxproxymanager.com/), [Traefik](https://traefik.io/traefik/), [caddy](https://caddyserver.com/) etc. Then setup a reverse proxy pass using `/my-folder`
`BASE_URL` accepts `it-tools`, `/it-tools` and `/it-tools/` alike; the default is `/`.
## Docker compose for hosting in a `/it-tools/` subfolder
You still want a reverse proxy in front -- [Nginx Proxy Manager](https://nginxproxymanager.com/),
[Traefik](https://traefik.io/traefik/), [caddy](https://caddyserver.com/) etc. -- passing
`/it-tools/` through to the container. It does not matter whether the proxy strips the
prefix before forwarding (`proxy_pass http://it-tools:8080/;`) or passes it on as-is
(`proxy_pass http://it-tools:8080;`): the container handles both.
For `/it-tools/` subfolder, you can use `baseurl-it-tools` tag.
See [sample of docker-compose.yml and nginx.conf](https://github.com/sharevb/it-tools/tree/chore/all-my-stuffs/docker-subfolder-sample), this docker image needs to have another reverse proxy in front of it, like [Nginx Proxy Manager](https://nginxproxymanager.com/), [Traefik](https://traefik.io/traefik/), [caddy](https://caddyserver.com/) etc.
Setup a reverse proxy pass using `/it-tools/`. And you should be able to access it-tools in `/it-tools/` of your server.
An example of nginx reverse proxy configuration is available at: https://github.com/sharevb/it-tools/tree/chore/all-my-stuffs/docker-subfolder-sample
One thing only the proxy can do, in the stripping setup: `/it-tools` without the trailing
slash never reaches the container, so redirect it there -- the sample's
`location /it-tools { return 301 /it-tools/; }`. When the prefix is forwarded instead, the
container does that redirect itself.
See the [sample docker-compose.yml and nginx.conf](https://github.com/sharevb/it-tools/tree/chore/all-my-stuffs/docker-subfolder-sample).
To run the sample:
```bash
@@ -253,7 +267,15 @@ cd it-tools/docker-subfolder-sample/
docker compose up
```
Then navigate to http://localhost:8080/it-tools/
Then navigate to http://localhost/it-tools/
Two things worth knowing:
- Building with `--build-arg BASE_URL=/it-tools/` still works, but it now only changes the
image's *default* -- the environment variable still wins at run time.
- On a read-only root filesystem the config template cannot be re-rendered at startup, so
`BASE_URL` (like `PORT`) has no effect unless `/etc/nginx/conf.d` is writable -- mount a
tmpfs or an emptyDir there. The container says so in its log.
## To build using a custom folder:
+54
View File
@@ -0,0 +1,54 @@
# vim:sw=4:ts=4:et
#
# BASE_URL is the path the app is served under: `/` (the default) for a deployment at the
# root of a domain, `/it-tools/` for one behind a reverse proxy that mounts it on a
# subpath. It is a runtime setting, not a build one -- the image ships assets that work at
# any path, and nginx.conf rewrites the `<base href>` in index.html per request.
#
# Normalise it here, once, before 20-envsubst-on-templates.sh renders the config:
#
# - accept `it-tools`, `/it-tools` and `/it-tools/` alike, always emit `/it-tools/`.
# A missing trailing slash would otherwise silently move the app one directory up,
# because that is how the browser resolves relative URLs against `<base href>`.
# - reject anything that is not a plain path. The value is interpolated into an HTML
# attribute and into an nginx regex, so a stray quote or `..` is worth catching here
# rather than letting it land in the served page.
#
# Sourced, not executed, so the export reaches the envsubst step.
_base_url=$(printf '%s' "${BASE_URL:-/}" | sed -e 's#^/*#/#' -e 's#/*$#/#')
case "$_base_url" in
# `/` itself, or `/segment/segment/` made of unreserved URL characters.
/) ;;
*/../* | *//*)
_base_url_invalid=1
;;
*[!A-Za-z0-9._~/-]*)
_base_url_invalid=1
;;
esac
if [ -n "${_base_url_invalid:-}" ]; then
echo "18-resolve-base-url.envsh: error: BASE_URL='$BASE_URL' is not a plain path, falling back to /" >&2
_base_url=/
fi
if [ "$_base_url" != "/" ] && [ -z "${NGINX_ENTRYPOINT_QUIET_LOGS:-}" ]; then
echo "18-resolve-base-url.envsh: info: serving the app under $_base_url"
fi
BASE_URL="$_base_url"
# Regex-safe forms of the same value, for the rewrites in nginx.conf. `.` is a legal
# character in a path and the validation above lets it through, but it is also the one
# regex metacharacter that survives that filter: unescaped, a BASE_URL of `/it.tools/`
# would strip the prefix from `/itXtools/...` too.
BASE_URL_REGEX=$(printf '%s' "$_base_url" | sed 's/\./\\./g')
# `/it-tools/` -> `/it-tools`, so nginx.conf can redirect the slash-less spelling to the
# real one. Empty for a deployment at the root, where there is nothing to redirect.
BASE_URL_NO_SLASH_REGEX="${BASE_URL_REGEX%/}"
export BASE_URL BASE_URL_REGEX BASE_URL_NO_SLASH_REGEX
unset _base_url _base_url_invalid
@@ -23,6 +23,13 @@ if [ -d "${NGINX_ENVSUBST_TEMPLATE_DIR:-/etc/nginx/templates}" ] \
if [ -z "${NGINX_ENTRYPOINT_QUIET_LOGS:-}" ]; then
echo "19-skip-envsubst-if-readonly.envsh: info: $_envsubst_output_dir is not writable, keeping the config baked into the image"
fi
# The baked config carries the image defaults, so anything that is only applied by
# rendering the template is quietly lost. $PORT has always had this caveat; say so for
# BASE_URL too, where the symptom (an app that loads from the wrong path) is a lot less
# obvious than a port that did not move.
if [ "${BASE_URL:-/}" != "/" ]; then
echo "19-skip-envsubst-if-readonly.envsh: warning: BASE_URL=$BASE_URL cannot be applied on a read-only filesystem; mount a writable $_envsubst_output_dir (a tmpfs or an emptyDir will do)" >&2
fi
export NGINX_ENVSUBST_TEMPLATE_DIR=/nonexistent-read-only-filesystem
fi
+7 -2
View File
@@ -1,9 +1,14 @@
services:
it-tools:
container_name: it-tools-subfolder
image: ghcr.io/sharevb/it-tools:baseurl-it-tools
image: ghcr.io/sharevb/it-tools:latest
pull_policy: always
restart: unless-stopped
environment:
# The path the app is served under. This is all a subfolder deployment needs -- the
# regular image works at any path, there is no subfolder-specific tag to pull and
# nothing to rebuild.
BASE_URL: /it-tools/
nginx-reverse-proxy:
image: nginx:alpine
depends_on:
@@ -11,4 +16,4 @@ services:
volumes:
- "./nginx.conf:/etc/nginx/conf.d/default.conf"
ports:
- 80:80
- 80:80
+3
View File
@@ -2,6 +2,9 @@ server {
listen 80;
server_name _;
# The trailing slash on proxy_pass strips /it-tools/ before the request reaches the
# container. It works the other way round too -- `proxy_pass http://it-tools-subfolder:8080;`
# forwards the prefix as-is -- because the app's own nginx.conf handles both.
location /it-tools/ {
proxy_pass http://it-tools-subfolder:8080/;
}
+44 -7
View File
@@ -21,15 +21,52 @@ server {
application/javascript mjs;
}
# Hashed build output. Without this, a missing chunk falls through to
# index.html below and is served as text/html with a 200, which the browser
# rejects with an opaque MIME error instead of a plain 404.
location /assets/ {
try_files $uri =404;
# `/it-tools` is the same place as `/it-tools/`, but only the second one gives the
# browser the right directory to resolve the app's relative URLs against, so send the
# first one there. Renders to `^$` -- which no request URI can match -- when the app is
# served from the root. Relative Location headers, because $scheme is whatever the
# reverse proxy used to reach the container, not what the browser used.
absolute_redirect off;
rewrite ^${BASE_URL_NO_SLASH_REGEX}$ ${BASE_URL} permanent;
# Serving the app from a subpath (BASE_URL, normalised by
# docker-entrypoint.d/18-resolve-base-url.envsh, `/` by default).
#
# The build is path-agnostic: every asset is referenced relatively, and the one
# absolute anchor is a `<base href="/">` in index.html that the app itself reads its
# base from (src/utils/base-url.ts). Rewriting that single tag on the way out is
# therefore enough to move the whole app to another path -- no rebuild, no
# subpath-specific image.
#
# sub_filter drops Last-Modified/ETag from every response it touches, and text/html is
# always in scope (sub_filter_types can add types, not exclude HTML). So: index.html,
# which an SPA must not cache anyway and which the service worker precaches regardless,
# and the one other HTML document in the build -- the visual-subnet-calculator's iframe,
# public/visualsubnetcalc/calc.html -- which loses conditional revalidation and is
# refetched in full when that tool is opened.
sub_filter '<base href="/">' '<base href="${BASE_URL}">';
sub_filter_once on;
# Hashed build output, with or without the deployment prefix in front of it: a reverse
# proxy may pass `/it-tools/assets/...` through as-is or strip the prefix first, and
# both have to land on the same file. Without this, a missing chunk falls through to
# index.html below and is served as text/html with a 200, which the browser rejects
# with an opaque MIME error instead of a plain 404.
location ~ ^/(?:.*/)?assets/(?<asset>.+)$ {
try_files /assets/$asset =404;
}
location / {
rewrite ^/it-tools/(.*) /$1 break;
try_files $uri $uri/ /index.html;
# Same story for everything else the app fetches by path (the JSON config files,
# the WASM helpers in public/): drop the deployment prefix when the proxy forwarded
# it instead of stripping it. Renders to `^/(.*)$` -- a no-op -- for the default
# BASE_URL of `/`.
rewrite ^${BASE_URL_REGEX}(.*)$ /$1 break;
# No `$uri/`: nothing in the build is a directory with an index in it, so the only
# thing matching one ever produced was nginx's own "add the trailing slash"
# redirect -- computed from the URI *after* the rewrite above, so under a subpath
# `/it-tools/figlet-fonts` bounced the browser out of the app to `/figlet-fonts/`
# (and then to a 403). Unknown paths belong to the SPA, which has a 404 page.
try_files $uri /index.html;
}
}
+168
View File
@@ -0,0 +1,168 @@
import { createReadStream, existsSync, readFileSync, statSync } from 'node:fs';
import { createServer } from 'node:http';
import type { Server } from 'node:http';
import { extname, join, normalize, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { expect, test } from '@playwright/test';
// The app is built once, for no particular path, and told where it lives at request time.
// This exercises that: a server that mounts `dist` under a subfolder the way the container
// does -- rewrite the one `<base href>` in index.html, serve everything else from the same
// files -- and then checks the app actually works from there.
//
// See nginx.conf (the real thing), vite.config.ts (`base` and the baseHref plugin) and
// src/utils/base-url.ts (how the app reads it back).
const BASE_URL = '/it-tools/';
const DIST = resolve(fileURLToPath(new URL('.', import.meta.url)), '../dist');
const CONTENT_TYPES: Record<string, string> = {
'.css': 'text/css',
'.html': 'text/html',
'.ico': 'image/x-icon',
'.js': 'text/javascript',
'.json': 'application/json',
'.md': 'text/markdown',
'.mjs': 'text/javascript',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.wasm': 'application/wasm',
'.webmanifest': 'application/manifest+json',
};
function resolveInDist(pathname: string): string | undefined {
const candidate = join(DIST, normalize(pathname));
if (!candidate.startsWith(DIST) || !existsSync(candidate) || !statSync(candidate).isFile()) {
return undefined;
}
return candidate;
}
function serveDistUnder(base: string): Promise<{ server: Server; origin: string }> {
// What nginx.conf does with sub_filter, on every HTML response rather than only on the
// SPA fallback: the service worker precaches index.html by fetching it, and it has to
// get the same document a navigation would.
const withBaseHref = (html: string) => html.replace('<base href="/">', `<base href="${base}">`);
const indexHtml = withBaseHref(readFileSync(join(DIST, 'index.html'), 'utf-8'));
const server = createServer((request, response) => {
const { pathname } = new URL(request.url ?? '/', 'http://localhost');
// Everything below the mount point, with the prefix dropped -- the reverse proxy in
// front of a container may or may not have stripped it already, so nginx.conf copes
// with both and so does this.
const path = decodeURIComponent(pathname.startsWith(base) ? pathname.slice(base.length - 1) : pathname);
const asset = path.match(/^\/(?:.*\/)?assets\/(.+)$/);
const file = asset ? resolveInDist(`/assets/${asset[1]}`) : resolveInDist(path);
if (!file) {
// A missing hashed chunk is a 404, not the SPA shell: serving index.html in its
// place turns a plain 404 into an opaque MIME error in the browser.
if (asset) {
response.writeHead(404).end();
return;
}
response.writeHead(200, { 'content-type': 'text/html' }).end(indexHtml);
return;
}
response.writeHead(200, {
'content-type': CONTENT_TYPES[extname(file)] ?? 'application/octet-stream',
// Same headers the container sets; the WebAssembly-backed tools need them.
'cross-origin-opener-policy': 'same-origin',
'cross-origin-embedder-policy': 'require-corp',
});
if (extname(file) === '.html') {
response.end(withBaseHref(readFileSync(file, 'utf-8')));
return;
}
createReadStream(file).pipe(response);
});
return new Promise((done) => {
server.listen(0, '127.0.0.1', () => {
const address = server.address();
const port = typeof address === 'object' && address !== null ? address.port : 0;
done({ server, origin: `http://127.0.0.1:${port}` });
});
});
}
test.describe('Deployment under a subfolder', () => {
let server: Server;
let origin: string;
test.beforeAll(async () => {
({ server, origin } = await serveDistUnder(BASE_URL));
});
test.afterAll(async () => {
await new Promise((done) => server.close(done));
});
test('loads the app, and everything it asks for, from the subfolder', async ({ page }) => {
const notFound: string[] = [];
page.on('response', (response) => {
if (response.status() === 404 && response.url().startsWith(origin)) {
notFound.push(response.url());
}
});
await page.goto(`${origin}${BASE_URL}`);
await expect(page).toHaveTitle(/IT Tools/);
// Router links carry the subfolder, so navigating inside the app stays inside it.
await expect(page.locator(`a[href^="${BASE_URL}"]`).first()).toBeVisible();
expect(notFound).toEqual([]);
});
test('serves a deep link, whose assets are one directory further down', async ({ page }) => {
// The interesting case for a relative build: index.html is served for a path that is
// not the app root, so `./assets/...` would resolve one level too deep without the
// `<base href>` the server injected.
await page.goto(`${origin}${BASE_URL}json-to-yaml-converter`);
await expect(page).toHaveTitle('JSON to YAML converter - IT Tools');
// Reaching the tool at all means its lazily imported chunk was resolved correctly.
await page.getByTestId('input').fill('{"foo":"bar"}');
expect((await page.getByTestId('area-content').innerText()).trim()).toEqual('foo: bar');
});
test('keeps the subfolder when navigating and reloading', async ({ page }) => {
await page.goto(`${origin}${BASE_URL}`);
const homeTitle = await page.title();
await page.locator('a.it-tool-link').first().click();
// The router was handed the runtime base, so an in-app navigation writes a URL that
// still points inside the subfolder -- and reloading it lands back on the same tool
// instead of on the app root or a 404.
await expect(page).not.toHaveURL(`${origin}${BASE_URL}`);
expect(page.url().startsWith(`${origin}${BASE_URL}`)).toBe(true);
await expect(page).not.toHaveTitle(homeTitle);
const url = page.url();
const title = await page.title();
// Then load that URL from scratch, the way someone pasting the link would: it has to
// come back as the same tool rather than as the app root or a 404. In a second tab
// rather than by reloading this one -- navigating a page that has just pulled in a
// tool's chunks races with those requests, and the app answers an aborted chunk load
// by reloading itself (the vite:preloadError handler in src/main.ts), which cancels
// the navigation the test is waiting on.
const fresh = await page.context().newPage();
await fresh.goto(url);
await expect(fresh).toHaveURL(url);
await expect(fresh).toHaveTitle(title);
await fresh.close();
});
});
+4
View File
@@ -1,4 +1,5 @@
import { figue } from 'figue';
import { appBaseUrl } from '@/utils/base-url';
export const config = figue({
app: {
@@ -18,6 +19,8 @@ export const config = figue({
doc: 'Application base url',
format: 'string',
default: '/',
// Not import.meta.env.BASE_URL: the bundle is built path-agnostic, so the real
// base only shows up at runtime. See src/utils/base-url.ts.
env: 'BASE_URL',
},
env: {
@@ -70,6 +73,7 @@ export const config = figue({
...import.meta.env,
// Because the string 'import.meta.env.PACKAGE_VERSION' is statically replaced during build time (see 'define' in vite.config.ts)
PACKAGE_VERSION: import.meta.env.PACKAGE_VERSION,
BASE_URL: appBaseUrl,
})
.validate()
.getConfig();
+44 -2
View File
@@ -5,9 +5,9 @@ import { LoadingPlugin } from 'vue-loading-overlay';
import { installAbortSignalPolyfill } from 'abort-signal-polyfill';
import { registerSW } from 'virtual:pwa-register';
import shadow from 'vue-shadow-dom';
import { plausible } from './plugins/plausible.plugin';
import { appBaseUrl } from '@/utils/base-url';
import '@/utils/json5-bigint';
import '@/utils/json5-bignum';
@@ -37,7 +37,49 @@ window.addEventListener('vite:preloadError', (event: Event) => {
installAbortSignalPolyfill();
registerSW();
// Not `registerSW()` from virtual:pwa-register. With a relative build base it hands
// workbox-window a relative `./sw.js`, and while the browser resolves that against our
// `<base href>` correctly, workbox-window's own bookkeeping resolves it against
// `location.href` instead (urlsMatch() in workbox-window). On a route one level deeper
// than the app root the two disagree, workbox mistakes its own worker for an external one
// and reloads the page under the user. Every route is a single segment today, so nothing
// is broken right now; registering by absolute URL just takes the trap away.
//
// What that costs us is the update handling `registerType: 'autoUpdate'` would have wired
// up, so it is reimplemented below.
if (import.meta.env.PROD && 'serviceWorker' in navigator) {
// The worker calls skipWaiting()/clientsClaim() (see vite.config.ts), so a newly deployed
// one takes over this page while it is still showing the previous build. Reload when that
// happens -- otherwise the tab keeps running the old bundle until it navigates, and any
// lazily imported chunk it reaches for has already been swept from the cache. A first
// install claims the page too, and must not reload: only a *replacement* means the page
// and its worker have diverged.
const hadController = Boolean(navigator.serviceWorker.controller);
let reloading = false;
navigator.serviceWorker.addEventListener('controllerchange', () => {
if (hadController && !reloading) {
reloading = true;
window.location.reload();
}
});
const registerServiceWorker = () => {
navigator.serviceWorker
.register(`${appBaseUrl}sw.js`, { scope: appBaseUrl })
.catch((error) => console.error('Service worker registration failed:', error));
};
// Registering competes with the page's own loading, so it waits for `load` -- but this
// module sits behind top-level awaits (the config fetches in tools-settings.ts and
// tools/index.ts), so `load` has usually fired long before we get here and waiting for
// it again would mean never registering at all.
if (document.readyState === 'complete') {
registerServiceWorker();
} else {
window.addEventListener('load', registerServiceWorker, { once: true });
}
}
const app = createApp(App);
+1 -1
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { useTheme } from '../ui/c-link/c-link.theme';
import { appBaseUrl as base } from '@/utils/base-url';
// Async: keeps markdown-it out of the startup bundle; the renderer only loads on
// deployments that actually ship a home.custom.md.
@@ -8,7 +9,6 @@ const VueMarkdown = defineAsyncComponent(() => import('vue-markdown-render'));
const linkTheme = useTheme();
const homeCustomMarkdown = ref('');
const base = import.meta.env.BASE_URL ?? '/';
const res = await fetch(`${base}home.custom.md`);
if (res.ok) {
+1 -1
View File
@@ -1,4 +1,4 @@
const base = import.meta.env.BASE_URL ?? '/';
import { appBaseUrl as base } from '@/utils/base-url';
// Optional per-deployment settings. Lives in its own top-level-await module so the
// fetch runs concurrently with the config fetches in src/tools/index.ts (sibling async
+1 -2
View File
@@ -2,6 +2,7 @@
import { useI18n } from 'vue-i18n';
import { useScriptTag } from '@vueuse/core';
import ageWasmUrl from '/age-wasm/age.wasm?url';
import { appBaseUrl as base } from '@/utils/base-url';
const { t } = useI18n();
@@ -43,8 +44,6 @@ declare class Go {
run(instance: WebAssembly.Instance): Promise<void>;
}
const base = import.meta.env.BASE_URL ?? '/';
const { load: loadGo } = useScriptTag(`${base}age-wasm/wasm_exec.js`, undefined, { type: 'module', manual: true });
await loadGo();
@@ -3,6 +3,7 @@ import figlet, { type FigletOptions, type FontName } from 'figlet';
import TextareaCopyable from '@/components/TextareaCopyable.vue';
import { languages, printToLanguage } from '@/utils/ascii-lang-utils';
import { useITStorage } from '@/composable/queryParams';
import { appBaseUrl as base } from '@/utils/base-url';
const input = ref('Ascii ART');
const language = useITStorage('ascii-text-drawer:language', 'raw');
@@ -13,8 +14,6 @@ const errored = ref(false);
const processing = ref(false);
const { t } = useI18n();
const base = import.meta.env.BASE_URL ?? '/';
figlet.defaults({ fontPath: `${base}figlet-fonts` });
const languagesOptions = languages.map((lang) => ({ value: lang.id, label: lang.name }));
+1 -2
View File
@@ -1,10 +1,9 @@
import type { ExternalTool, ToolCategory, ToolWithCategory, ToolsFilter } from './tools.types';
import { translate as t } from '@/plugins/i18n.plugin';
import { appBaseUrl as base } from '@/utils/base-url';
const modules = import.meta.glob<true, string, ToolWithCategory>('./*/index.ts', { eager: true, import: 'tool' });
const base = import.meta.env.BASE_URL ?? '/';
// Both config files are optional; fetch them in parallel so app boot waits on at
// most one network round-trip instead of two sequential ones.
const [filterConfig, externalTools] = await Promise.all([
@@ -3,11 +3,10 @@ import { useI18n } from 'vue-i18n';
import { useScriptTag } from '@vueuse/core';
import { convert_math } from 'mitex-wasm';
import { useQueryParam, useQueryParamOrStorage } from '@/composable/queryParams';
import { appBaseUrl as base } from '@/utils/base-url';
const { t } = useI18n();
const base = import.meta.env.BASE_URL ?? '/';
const { load: loadPlurimath } = useScriptTag(`${base}plurimath/index.js`, undefined, { type: 'module', manual: true });
const formats = [
+1 -2
View File
@@ -2,6 +2,7 @@
import { useI18n } from 'vue-i18n';
import { useScriptTag } from '@vueuse/core';
import { computedRefreshableAsync } from '@/composable/computedRefreshable';
import { appBaseUrl as base } from '@/utils/base-url';
const { t } = useI18n();
@@ -18,8 +19,6 @@ declare global {
}
}
const base = import.meta.env.BASE_URL ?? '/';
const { load: loadIpLookup } = useScriptTag(`${base}iplookup.js`, undefined, { type: 'module', manual: true });
const [clientIPDetails, refreshClientIP] = computedRefreshableAsync(async () => {
+1 -2
View File
@@ -3,6 +3,7 @@ import { useI18n } from 'vue-i18n';
import { Base64 } from 'js-base64';
import createGSModule from 'ghostscript-wasm-esm';
import { useDownloadFileFromBase64 } from '@/composable/downloadBase64';
import { appBaseUrl as base } from '@/utils/base-url';
const { t } = useI18n();
@@ -67,8 +68,6 @@ async function onFileUploaded(uploadedFile: File) {
}
}
const base = import.meta.env.BASE_URL ?? '/';
async function callMainWithInOutPdf(data: ArrayBuffer, args: string[], expected_exitcode: number) {
gsCommand.value = args.join(' ');
logs.value = [];
+1 -1
View File
@@ -8,6 +8,7 @@ import TextareaCopyable from '@/components/TextareaCopyable.vue';
import { potrace as colorPotrace, init as colorPotraceInit } from 'esm-potrace-wasm';
import { useQueryParamOrStorage } from '@/composable/queryParams';
import { convertToSVG } from './colorVTracer';
import { appBaseUrl as base } from '@/utils/base-url';
const { t } = useI18n();
@@ -46,7 +47,6 @@ function file2Buffer(file: File) {
}
// import vtracer as JS module populating window.vtracerInit and ColorImageConverter
const base = import.meta.env.BASE_URL ?? '/';
const { load: loadVTracer } = useScriptTag(`${base}vtracer/vtracer_webapp.js`, undefined, { type: 'module', manual: true });
await loadVTracer();
@@ -1,9 +1,8 @@
<script setup lang="ts">
import { appBaseUrl as base } from '@/utils/base-url';
const isDarkTheme = useDark();
const iframeRef = ref<HTMLIFrameElement | null>(null);
const base = import.meta.env.BASE_URL ?? '/';
const c = new URLSearchParams(window.location.search).get('c');
// Path to iframe content in /public
@@ -1,13 +1,12 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { useThemeVars } from 'naive-ui';
import { appBaseUrl as base } from '@/utils/base-url';
const { t } = useI18n();
const themeVars = useThemeVars();
const base = import.meta.env.BASE_URL ?? '/';
const { load: loadJQuery } = useScriptTag(`${base}zpool-calc/jquery.js`);
await loadJQuery();
+40
View File
@@ -0,0 +1,40 @@
import { describe, expect, it } from 'vitest';
import { resolveAppBaseUrl } from './base-url';
describe('base-url utils', () => {
describe('resolveAppBaseUrl', () => {
it('falls back to the root when there is no <base href>', () => {
expect(resolveAppBaseUrl(undefined, 'https://example.com/base64-string-converter')).to.eql('/');
expect(resolveAppBaseUrl(null, 'https://example.com/base64-string-converter')).to.eql('/');
expect(resolveAppBaseUrl('', 'https://example.com/base64-string-converter')).to.eql('/');
});
it('reads the subpath the container injected, whatever the current route is', () => {
expect(resolveAppBaseUrl('/it-tools/', 'https://example.com/it-tools/base64-string-converter')).to.eql(
'/it-tools/',
);
expect(resolveAppBaseUrl('/some/nested/path/', 'https://example.com/some/nested/path/uuid-generator')).to.eql(
'/some/nested/path/',
);
});
it('always ends on a slash, so `${base}file.json` stays a sibling of index.html', () => {
expect(resolveAppBaseUrl('/it-tools', 'https://example.com/it-tools')).to.eql('/it-tools/');
expect(resolveAppBaseUrl('/', 'https://example.com/')).to.eql('/');
});
it('accepts an absolute <base href>, keeping only its path', () => {
expect(resolveAppBaseUrl('https://tools.example.com/it-tools/', 'https://tools.example.com/it-tools/')).to.eql(
'/it-tools/',
);
});
it('resolves a relative <base href> against the page, not against itself', () => {
expect(resolveAppBaseUrl('./', 'https://example.com/it-tools/')).to.eql('/it-tools/');
});
it('falls back to the root rather than throwing on a href that is not a URL', () => {
expect(resolveAppBaseUrl('http://', 'https://example.com/')).to.eql('/');
});
});
});
+37
View File
@@ -0,0 +1,37 @@
export { appBaseUrl, resolveAppBaseUrl };
/**
* The path the app is served under, resolved at runtime instead of baked into the bundle.
*
* The build is path-agnostic: vite.config.ts uses a relative `base`, so hashed assets and
* lazy chunks resolve against the URL of the chunk that imports them and `import.meta.env.BASE_URL` is a useless `./`.
* The one thing that does know where the app lives is the `<base href>` element injected into index.html at build time --
* the container rewrites it from the BASE_URL environment variable on the way out (see nginx.conf), which is what lets
* a single image serve any subpath.
*
* Anything that builds a URL to a file shipped in `public/`, plus the router base, goes
* through this. Deployments that serve the app from the domain root -- the default -- get
* `/`, exactly as before.
*/
function resolveAppBaseUrl(href: string | null | undefined, documentUrl: string): string {
if (!href) {
// No <base>: a plain `vite dev` (the dev server always serves from the root, even
// when the build base is relative) or a unit test rendering into a bare document.
return '/';
}
try {
// Resolved against the *page* URL, which is how the browser itself resolves a
// relative `<base href>`. `document.baseURI` would already have the base applied.
const { pathname } = new URL(href, documentUrl);
return pathname.endsWith('/') ? pathname : `${pathname}/`;
} catch (_) {
return '/';
}
}
const appBaseUrl =
typeof document === 'undefined'
? '/'
: resolveAppBaseUrl(document.querySelector('base')?.getAttribute('href'), document.URL);
+82 -9
View File
@@ -3,6 +3,7 @@ import { resolve } from 'node:path';
import { nodePolyfills } from 'vite-plugin-node-polyfills';
import wasm from 'vite-plugin-wasm';
import type { Plugin } from 'vite';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
@@ -24,9 +25,65 @@ import Sitemap from 'vite-plugin-sitemap';
import { visualizer } from 'rollup-plugin-visualizer';
const baseUrl = process.env.BASE_URL || '/';
// Where the app will be served from. The build itself is path-agnostic -- `base` below is
// relative, so every asset URL is resolved against the file that references it -- and this
// only seeds the `<base href>` in index.html, which is what the app and the browser read
// the deployment path from at runtime (see src/utils/base-url.ts).
//
// Setting it is only needed for a plain static deployment into a subfolder (GitHub Pages,
// `dist` dropped into a directory), because there is no server to fill it in. The Docker
// image leaves it at `/` and rewrites the tag per request from the BASE_URL environment
// variable instead (see nginx.conf), which is why one image can serve any subpath.
const baseUrl = normalizeBaseUrl(process.env.BASE_URL);
const hostname = process.env.HOSTNAME;
function normalizeBaseUrl(value: string | undefined): string {
const trimmed = (value ?? '').replace(/^\/+|\/+$/g, '');
if (trimmed === '') {
return '/';
}
// The same rule the container applies to the runtime value
// (docker-entrypoint.d/18-resolve-base-url.envsh): a plain path built from unreserved
// characters. This one ends up spliced into an HTML attribute below, so a value carrying
// a quote would rewrite the tag around it, and one carrying a space or `..` would just
// quietly produce a page that loads from the wrong place. Fail the build instead.
const segments = trimmed.split('/');
if (segments.some(segment => segment === '..' || !/^[\w.~-]+$/.test(segment))) {
throw new Error(`BASE_URL must be a plain path such as "/it-tools/", got ${JSON.stringify(value)}`);
}
return `/${segments.join('/')}/`;
}
// index.html gets exactly one `<base href>`, and it has to come before the first relative
// URL in <head> -- Vite injects the entry script and the stylesheet links there, so this
// splices it in right after the opening tag rather than relying on tag-injection order.
// The emitted string is kept byte-stable on purpose: nginx.conf matches it literally to
// swap in the runtime BASE_URL.
function baseHref(base: string): Plugin {
return {
name: 'it-tools:base-href',
// Build only: the dev server always serves from the root (Vite normalizes a relative
// base to `/` for `serve`), and with no `<base>` the app falls back to `/` as well.
apply: 'build',
transformIndexHtml: {
order: 'post',
handler(html) {
const withBase = html.replace(/<head(\s[^>]*)?>/i, match => `${match}\n <base href="${base}">`);
if (withBase === html) {
throw new Error('it-tools:base-href: no <head> to inject the <base href> into');
}
return withBase;
},
},
};
}
// Locales are code-split: only en is bundled eagerly, the rest become lazy chunks fetched on
// first use (see src/plugins/i18n.plugin.ts). VITE_AVAILABLE_LOCALES filters the locales
// offered at runtime instead of trimming the build.
@@ -35,6 +92,7 @@ const includeLocales = [resolve(__dirname, 'src/tools/*/locales/**'), resolve(__
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
baseHref(baseUrl),
VueI18n({
runtimeOnly: true,
compositionOnly: true,
@@ -64,7 +122,13 @@ export default defineConfig({
svgLoader(),
VitePWA({
registerType: 'autoUpdate',
// src/main.ts registers the worker itself, against the base the app resolved at
// runtime. Turning the injection off means the plugin no longer infers the
// `autoUpdate` workbox flags either, hence skipWaiting/clientsClaim below.
injectRegister: false,
workbox: {
skipWaiting: true,
clientsClaim: true,
// Precache only the app shell so the service worker doesn't download every
// tool chunk and WASM binary (~160 MB) on first visit; hashed assets are
// cached on demand as tools are opened. Set VITE_PWA_FULL_PRECACHE=true to
@@ -74,7 +138,9 @@ export default defineConfig({
? ['**\/*.{js,wasm,css,html}']
: ['**\/*.{css,html}'],
maximumFileSizeToCacheInBytes: 25 * 1024 ** 2,
navigateFallback: `${baseUrl}index.html`,
// Relative, like every other precache entry: workbox resolves them against the
// service worker's own URL, so the same sw.js works under any deployment path.
navigateFallback: 'index.html',
runtimeCaching: [
{
urlPattern: ({ sameOrigin, request }) =>
@@ -98,33 +164,36 @@ export default defineConfig({
],
},
strategies: 'generateSW',
// Every URL in here is relative to the manifest itself, which the browser fetches
// from the app root -- so the manifest, like the rest of the build, does not need to
// know where that root is.
manifest: {
name: 'IT Tools',
description: 'Aggregated set of useful tools for developers.',
display: 'standalone',
start_url: `${baseUrl}?utm_source=pwa&utm_medium=pwa`,
scope: baseUrl,
start_url: './?utm_source=pwa&utm_medium=pwa',
scope: './',
orientation: 'any',
theme_color: '#18a058',
background_color: '#f1f5f9',
icons: [
{
src: `${baseUrl}favicon-16x16.png`,
src: './favicon-16x16.png',
type: 'image/png',
sizes: '16x16',
},
{
src: `${baseUrl}favicon-32x32.png`,
src: './favicon-32x32.png',
type: 'image/png',
sizes: '32x32',
},
{
src: `${baseUrl}android-chrome-192x192.png`,
src: './android-chrome-192x192.png',
sizes: '192x192',
type: 'image/png',
},
{
src: `${baseUrl}android-chrome-512x512.png`,
src: './android-chrome-512x512.png',
sizes: '512x512',
type: 'image/png',
purpose: 'any maskable',
@@ -169,7 +238,11 @@ export default defineConfig({
})
: undefined,
],
base: baseUrl,
// Relative, so a built asset is addressed from the chunk that imports it rather than
// from a path fixed at build time. This is what makes the output portable across
// deployment paths; `<base href>` (see baseHref above) covers the entry points in
// index.html, which the browser resolves against the document instead.
base: './',
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),