Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

fix(editor): PWA name respects configured appName (#7420)

Som Samantray1ec84fc6eda2
diff --git a/frontend/src/editor/core/components/AppProviders.tsx b/frontend/src/editor/core/components/AppProviders.tsx
index c918198224..b017d1ef60 100644
--- a/frontend/src/editor/core/components/AppProviders.tsx
+++ b/frontend/src/editor/core/components/AppProviders.tsx
@@ -19,6 +19,7 @@ import { BannerProvider } from "@editor/contexts/BannerContext";
import ErrorBoundary from "@editor/components/shared/ErrorBoundary";
import { useAppInitialization } from "@editor/hooks/useAppInitialization";
import { useLogoAssets } from "@editor/hooks/useLogoAssets";
+import { useManifestUrl } from "@editor/hooks/useManifestUrl";
import AppConfigLoader from "@editor/components/shared/AppConfigLoader";
import { UpdateStartupPopup } from "@editor/components/shared/UpdateStartupPopup";
import { RedactionProvider } from "@editor/contexts/RedactionContext";
@@ -38,7 +39,8 @@ function AppInitializer() {
}
function BrandingAssetManager() {
- const { favicon, logo192, manifestHref } = useLogoAssets();
+ const { favicon, logo192 } = useLogoAssets();
+ const { manifestHref } = useManifestUrl();
useEffect(() => {
if (typeof document === "undefined") {
diff --git a/frontend/src/editor/core/hooks/useManifestUrl.test.tsx b/frontend/src/editor/core/hooks/useManifestUrl.test.tsx
new file mode 100644
index 0000000000..387d2af4db
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useManifestUrl.test.tsx
@@ -0,0 +1,495 @@
+import {
+ describe,
+ expect,
+ test,
+ vi,
+ beforeEach,
+ afterEach,
+ type MockInstance,
+} from "vitest";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { useState, type ReactNode } from "react";
+import { AppConfigProvider } from "@editor/contexts/AppConfigContext";
+import { PreferencesProvider } from "@editor/contexts/PreferencesContext";
+import { TestQueryProvider } from "@editor/tests/utils/TestQueryProvider";
+import { allowConsole } from "@editor/tests/failOnConsole";
+import {
+ MAX_SHORT_NAME_CODE_POINTS,
+ resolveAppName,
+ truncateShortName,
+ mergeManifestName,
+ absolutizeManifestUrls,
+ useManifestUrl,
+ type StaticManifest,
+} from "@editor/hooks/useManifestUrl";
+
+const MODERN_MANIFEST: StaticManifest = {
+ short_name: "Stirling PDF",
+ name: "Stirling PDF",
+ icons: [
+ {
+ src: "modern-logo/favicon.ico",
+ sizes: "64x64 32x32 24x24 16x16",
+ type: "image/x-icon",
+ },
+ { src: "modern-logo/logo192.png", type: "image/png", sizes: "192x192" },
+ { src: "modern-logo/logo512.png", type: "image/png", sizes: "512x512" },
+ ],
+ start_url: ".",
+ display: "standalone",
+ theme_color: "#000000",
+ background_color: "#ffffff",
+};
+
+/** Test double so each scenario can set its own appName. */
+function ConfigHarness({
+ appName,
+ children,
+}: {
+ appName: string | null | undefined;
+ children: ReactNode;
+}) {
+ return (
+ <TestQueryProvider>
+ <PreferencesProvider>
+ <AppConfigProvider
+ bootstrapMode="non-blocking"
+ autoFetch={false}
+ initialConfig={
+ appName == null
+ ? { enableLogin: false }
+ : { enableLogin: false, appNameNavbar: appName }
+ }
+ >
+ {children}
+ </AppConfigProvider>
+ </PreferencesProvider>
+ </TestQueryProvider>
+ );
+}
+
+function renderUseManifestUrl(options?: {
+ wrapper?: (props: { children: ReactNode }) => ReactNode;
+}) {
+ return renderHook(() => useManifestUrl(), options);
+}
+
+/**
+ * jsdom's Blob has no .text(); setupTests mocks Blob.prototype.arrayBuffer
+ * with a dummy buffer, so read the content through FileReader instead.
+ */
+function readBlobText(blob: Blob): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(reader.result as string);
+ reader.onerror = () => reject(reader.error);
+ reader.readAsText(blob);
+ });
+}
+
+/** Parse the most recently created blob as the merged manifest. */
+async function readBlobManifest(
+ createObjectURLSpy: MockInstance<typeof URL.createObjectURL>,
+): Promise<StaticManifest> {
+ const blob = createObjectURLSpy.mock.calls.at(-1)?.[0] as Blob;
+ return JSON.parse(await readBlobText(blob)) as StaticManifest;
+}
+
+describe("resolveAppName", () => {
+ test("treats undefined, null, empty and whitespace-only as unset", () => {
+ expect(resolveAppName(undefined)).toBeNull();
+ expect(resolveAppName(null)).toBeNull();
+ expect(resolveAppName("")).toBeNull();
+ expect(resolveAppName(" ")).toBeNull();
+ expect(resolveAppName("\t\n ")).toBeNull();
+ });
+
+ test("returns the trimmed name when set", () => {
+ expect(resolveAppName("Acme Docs")).toBe("Acme Docs");
+ expect(resolveAppName(" Acme Docs ")).toBe("Acme Docs");
+ });
+});
+
+describe("truncateShortName", () => {
+ test("keeps the full name when at most 12 code points", () => {
+ expect(truncateShortName("Acme Docs")).toBe("Acme Docs");
+ expect(truncateShortName("123456789012")).toBe("123456789012");
+ });
+
+ test("truncates to 11 code points plus ellipsis when longer", () => {
+ const long = "A Very Long Product Name That Exceeds Twelve";
+ const truncated = truncateShortName(long);
+ expect(truncated).toBe("A Very Long\u2026");
+ expect(Array.from(truncated).length).toBe(MAX_SHORT_NAME_CODE_POINTS);
+ expect(truncated.endsWith("\u2026")).toBe(true);
+ });
+
+ test("is surrogate-pair-safe for emoji / non-Latin names", () => {
+ // 12 emoji: each is a surrogate pair; slicing code units would mojibake.
+ const twelveEmoji =
+ "\u{1F600}\u{1F601}\u{1F602}\u{1F603}\u{1F604}\u{1F605}\u{1F606}\u{1F607}\u{1F608}\u{1F609}\u{1F60A}\u{1F60B}";
+ expect(truncateShortName(twelveEmoji)).toBe(twelveEmoji);
+ const thirteenEmoji = twelveEmoji + "\u{1F60C}";
+ const truncated = truncateShortName(thirteenEmoji);
+ expect(Array.from(truncated).length).toBe(MAX_SHORT_NAME_CODE_POINTS);
+ expect(truncated.endsWith("\u2026")).toBe(true);
+ // No lone surrogate halves survive the truncation (the ellipsis itself is
+ // a single code unit and is expected).
+ for (const codePoint of Array.from(truncated)) {
+ const code = codePoint.codePointAt(0)!;
+ if (codePoint !== "\u2026") {
+ expect(code).toBeGreaterThan(0xffff);
+ }
+ }
+ });
+});
+
+describe("mergeManifestName", () => {
+ test("returns the static manifest unchanged when appName is unset", () => {
+ expect(mergeManifestName(MODERN_MANIFEST, null)).toBe(MODERN_MANIFEST);
+ });
+
+ test("merges name and truncated short_name when appName is set", () => {
+ const merged = mergeManifestName(
+ MODERN_MANIFEST,
+ "A Very Long Product Name That Exceeds Twelve",
+ );
+ expect(merged.name).toBe("A Very Long Product Name That Exceeds Twelve");
+ expect(merged.short_name).toBe("A Very Long\u2026");
+ expect(merged.start_url).toBe(".");
+ });
+});
+
+describe("absolutizeManifestUrls", () => {
+ const BASE = "https://pdf.example.com/";
+
+ test("rewrites start_url and every icon src to origin-absolute URLs", () => {
+ const resolved = absolutizeManifestUrls(MODERN_MANIFEST, BASE);
+ expect(resolved.start_url).toBe("https://pdf.example.com/");
+ for (const icon of resolved.icons ?? []) {
+ expect(icon.src).toMatch(/^https:\/\/pdf\.example\.com\//);
+ expect(icon.src).not.toMatch(/^(?!https?:)/);
+ }
+ });
+
+ test("rewrites scope and id when present", () => {
+ const withScopeAndId: StaticManifest = {
+ ...MODERN_MANIFEST,
+ scope: ".",
+ id: "./",
+ };
+ const resolved = absolutizeManifestUrls(withScopeAndId, BASE);
+ expect(resolved.scope).toBe("https://pdf.example.com/");
+ expect(resolved.id).toBe("https://pdf.example.com/");
+ });
+
+ test("resolves id against the start_url origin, not the manifest path", () => {
+ const subpathManifest: StaticManifest = {
+ ...MODERN_MANIFEST,
+ start_url: ".",
+ id: "foo",
+ };
+ const resolved = absolutizeManifestUrls(
+ subpathManifest,
+ "https://pdf.example.com/pdf/manifest.json",
+ );
+ expect(resolved.start_url).toBe("https://pdf.example.com/pdf/");
+ expect(resolved.id).toBe("https://pdf.example.com/foo");
+ });
+
+ test("leaves already-absolute members untouched", () => {
+ const withAbsoluteIcons: StaticManifest = {
+ ...MODERN_MANIFEST,
+ start_url: "https://cdn.example.com/app",
+ icons: [{ src: "https://cdn.example.com/icon.png" }],
+ };
+ const resolved = absolutizeManifestUrls(withAbsoluteIcons, BASE);
+ expect(resolved.start_url).toBe("https://cdn.example.com/app");
+ expect(resolved.icons?.[0]?.src).toBe("https://cdn.example.com/icon.png");
+ });
+});
+
+describe("useManifestUrl", () => {
+ let createObjectURLSpy: MockInstance<typeof URL.createObjectURL>;
+ let revokeObjectURLSpy: MockInstance<typeof URL.revokeObjectURL>;
+ let originalLocation: Location;
+ beforeEach(() => {
+ originalLocation = window.location;
+ createObjectURLSpy = vi
+ .spyOn(URL, "createObjectURL")
+ .mockImplementation(
+ () => `blob:mock-${Math.random().toString(36).slice(2)}`,
+ );
+ revokeObjectURLSpy = vi
+ .spyOn(URL, "revokeObjectURL")
+ .mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ if (window.location !== originalLocation) {
+ Object.defineProperty(window, "location", {
+ value: originalLocation,
+ writable: true,
+ });
+ }
+ });
+
+ const wrapperFor = (appName: string | null | undefined) => {
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <ConfigHarness appName={appName}>{children}</ConfigHarness>
+ );
+ return wrapper;
+ };
+
+ test("URL members are rewritten against the manifest URL, not the page URL (deep-link safe)", async () => {
+ // Page is on a deep route; the manifest lives at the app root. Members
+ // must resolve against the manifest's directory, not the deep link.
+ Object.defineProperty(window, "location", {
+ value: new URL("https://pdf.example.com/share/abc123"),
+ writable: true,
+ });
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response(JSON.stringify(MODERN_MANIFEST)),
+ );
+
+ const { result } = renderUseManifestUrl({
+ wrapper: wrapperFor("Acme Docs"),
+ });
+
+ await waitFor(() => {
+ expect(result.current.manifestHref).toMatch(/^blob:/);
+ });
+
+ const manifest = await readBlobManifest(createObjectURLSpy);
+ // start_url "." resolves against the manifest URL (/manifest.json) -> app root.
+ expect(manifest.start_url).toBe("https://pdf.example.com/");
+ for (const icon of manifest.icons ?? []) {
+ expect(icon.src).toMatch(/^https:\/\/pdf\.example\.com\/modern-logo\//);
+ expect(icon.src).not.toContain("/share/");
+ }
+ });
+
+ test("returns a blob URL and the blob manifest uses appName", async () => {
+ const fetchMock = vi
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue(new Response(JSON.stringify(MODERN_MANIFEST)));
+
+ const { result } = renderUseManifestUrl({
+ wrapper: wrapperFor("Acme Docs"),
+ });
+
+ await waitFor(() => {
+ expect(result.current.manifestHref).toMatch(/^blob:/);
+ });
+
+ const manifest = await readBlobManifest(createObjectURLSpy);
+ expect(manifest.name).toBe("Acme Docs");
+ expect(manifest.short_name).toBe("Acme Docs");
+ // URL members must be origin-absolute in the produced blob.
+ expect(manifest.start_url).toMatch(/^https?:\/\//);
+ for (const icon of manifest.icons ?? []) {
+ expect(icon.src).toMatch(/^https?:\/\//);
+ }
+
+ expect(fetchMock).toHaveBeenCalledWith("/manifest.json", {
+ signal: expect.any(AbortSignal),
+ });
+ });
+
+ test("static manifestHref returned unchanged when appName is unset", async () => {
+ const fetchMock = vi
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue(new Response(JSON.stringify(MODERN_MANIFEST)));
+
+ for (const unset of [undefined, null, "", " "]) {
+ const { result } = renderUseManifestUrl({ wrapper: wrapperFor(unset) });
+ expect(result.current.manifestHref).toBe("/manifest.json");
+ await act(async () => {});
+ // No blob is ever created, no fetch is issued.
+ expect(result.current.manifestHref).toBe("/manifest.json");
+ }
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(createObjectURLSpy).not.toHaveBeenCalled();
+ });
+
+ test("short_name is first 11 code points + ellipsis when appName > 12", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response(JSON.stringify(MODERN_MANIFEST)),
+ );
+
+ const { result } = renderUseManifestUrl({
+ wrapper: wrapperFor("A Very Long Product Name That Exceeds Twelve"),
+ });
+
+ await waitFor(() => expect(result.current.manifestHref).toMatch(/^blob:/));
+ const manifest = await readBlobManifest(createObjectURLSpy);
+ expect(manifest.name).toBe("A Very Long Product Name That Exceeds Twelve");
+ expect(manifest.short_name).toBe("A Very Long\u2026");
+ expect(Array.from(manifest.short_name!).length).toBe(
+ MAX_SHORT_NAME_CODE_POINTS,
+ );
+ });
+
+ test("short_name is the full appName when at most 12 code points", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response(JSON.stringify(MODERN_MANIFEST)),
+ );
+
+ const { result } = renderUseManifestUrl({
+ wrapper: wrapperFor("Acme Docs"),
+ });
+
+ await waitFor(() => expect(result.current.manifestHref).toMatch(/^blob:/));
+ const manifest = await readBlobManifest(createObjectURLSpy);
+ expect(manifest.short_name).toBe("Acme Docs");
+ });
+
+ test("surrogate-pair-safe truncation end-to-end", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response(JSON.stringify(MODERN_MANIFEST)),
+ );
+
+ const longEmoji =
+ "\u{1F600}\u{1F601}\u{1F602}\u{1F603}\u{1F604}\u{1F605}\u{1F606}\u{1F607}\u{1F608}\u{1F609}\u{1F60A}\u{1F60B}\u{1F60C}";
+ const { result } = renderUseManifestUrl({ wrapper: wrapperFor(longEmoji) });
+
+ await waitFor(() => expect(result.current.manifestHref).toMatch(/^blob:/));
+ const manifest = await readBlobManifest(createObjectURLSpy);
+ expect(Array.from(manifest.short_name!).length).toBe(
+ MAX_SHORT_NAME_CODE_POINTS,
+ );
+ expect(manifest.short_name!.endsWith("\u2026")).toBe(true);
+ });
+
+ test("changing appName revokes the previous blob URL", async () => {
+ // A Response body can only be read once; the hook re-fetches when appName
+ // changes, so each call must get a FRESH Response.
+ vi.spyOn(globalThis, "fetch").mockImplementation(() =>
+ Promise.resolve(new Response(JSON.stringify(MODERN_MANIFEST))),
+ );
+
+ // Driver wrapper lets the test change the seeded appName between renders.
+ let setAppName: (value: string) => void = () => {};
+ const Driver = ({ children }: { children: ReactNode }) => {
+ const [appName, setter] = useState("First Name");
+ setAppName = setter;
+ return <ConfigHarness appName={appName}>{children}</ConfigHarness>;
+ };
+
+ const { result } = renderUseManifestUrl({ wrapper: Driver });
+ await waitFor(() => expect(result.current.manifestHref).toMatch(/^blob:/));
+ const firstUrl = result.current.manifestHref;
+ expect(revokeObjectURLSpy).not.toHaveBeenCalled();
+
+ act(() => {
+ setAppName("Second Name");
+ });
+
+ await waitFor(() => {
+ expect(result.current.manifestHref).not.toBe(firstUrl);
+ });
+ await waitFor(() => {
+ expect(revokeObjectURLSpy).toHaveBeenCalledWith(firstUrl);
+ });
+
+ // The new blob URL itself is not revoked.
+ const revocations = revokeObjectURLSpy.mock.calls.map((call) => call[0]);
+ expect(revocations).not.toContain(result.current.manifestHref);
+ });
+
+ test("unmount revokes the blob URL (no leaks)", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response(JSON.stringify(MODERN_MANIFEST)),
+ );
+
+ const { result, unmount } = renderUseManifestUrl({
+ wrapper: wrapperFor("Acme Docs"),
+ });
+ await waitFor(() => expect(result.current.manifestHref).toMatch(/^blob:/));
+ const url = result.current.manifestHref;
+
+ unmount();
+ expect(revokeObjectURLSpy).toHaveBeenCalledWith(url);
+ });
+
+ test("fetch failure falls back to the static manifestHref", async () => {
+ allowConsole.error(/\[useManifestUrl\] Failed to build runtime manifest/);
+ vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("network down"));
+
+ const { result } = renderUseManifestUrl({
+ wrapper: wrapperFor("Acme Docs"),
+ });
+
+ await waitFor(() => {
+ expect(result.current.manifestHref).toBe("/manifest.json");
+ });
+ // No blob URL was ever created.
+ expect(createObjectURLSpy).not.toHaveBeenCalled();
+ expect(revokeObjectURLSpy).not.toHaveBeenCalled();
+ });
+
+ test("non-OK manifest response falls back to the static manifestHref", async () => {
+ allowConsole.error(/\[useManifestUrl\] Failed to build runtime manifest/);
+ const fetchMock = vi
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue(new Response("Not found", { status: 404 }));
+
+ const { result } = renderUseManifestUrl({
+ wrapper: wrapperFor("Acme Docs"),
+ });
+
+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+ await act(async () => {});
+ expect(result.current.manifestHref).toBe("/manifest.json");
+ expect(createObjectURLSpy).not.toHaveBeenCalled();
+ });
+
+ test("clearing appName revokes the blob and restores the static manifestHref", async () => {
+ vi.spyOn(globalThis, "fetch").mockImplementation(() =>
+ Promise.resolve(new Response(JSON.stringify(MODERN_MANIFEST))),
+ );
+
+ let setAppName: (value: string) => void = () => {};
+ const Driver = ({ children }: { children: ReactNode }) => {
+ const [appName, setter] = useState("First Name");
+ setAppName = setter;
+ return <ConfigHarness appName={appName}>{children}</ConfigHarness>;
+ };
+
+ const { result } = renderUseManifestUrl({ wrapper: Driver });
+ await waitFor(() => expect(result.current.manifestHref).toMatch(/^blob:/));
+ const blobUrl = result.current.manifestHref;
+
+ act(() => {
+ setAppName("");
+ });
+
+ await waitFor(() => {
+ expect(result.current.manifestHref).toBe("/manifest.json");
+ });
+ expect(revokeObjectURLSpy).toHaveBeenCalledWith(blobUrl);
+ });
+
+ test("keeps the static manifestHref until the hook resolves", async () => {
+ let resolveFetch: (value: Response) => void = () => {};
+ vi.spyOn(globalThis, "fetch").mockReturnValue(
+ new Promise<Response>((resolve) => {
+ resolveFetch = resolve;
+ }),
+ );
+
+ const { result } = renderUseManifestUrl({
+ wrapper: wrapperFor("Acme Docs"),
+ });
+
+ // In flight: still the static manifest (no transient broken state).
+ expect(result.current.manifestHref).toBe("/manifest.json");
+
+ await act(async () => {
+ resolveFetch(new Response(JSON.stringify(MODERN_MANIFEST)));
+ });
+ await waitFor(() => expect(result.current.manifestHref).toMatch(/^blob:/));
+ });
+});
diff --git a/frontend/src/editor/core/hooks/useManifestUrl.ts b/frontend/src/editor/core/hooks/useManifestUrl.ts
new file mode 100644
index 0000000000..56e220d6b5
--- /dev/null
+++ b/frontend/src/editor/core/hooks/useManifestUrl.ts
@@ -0,0 +1,245 @@
+import { useEffect, useRef, useState } from "react";
+import { useAppConfig } from "@editor/contexts/AppConfigContext";
+import { useLogoAssets } from "@editor/hooks/useLogoAssets";
+
+/**
+ * The served PWA manifest is a static JSON file (manifest.json) that hardcodes
+ * "Stirling PDF". The installed PWA name must reflect the configured
+ * `ui.appNameNavbar` instead (issue #5492). The static file cannot interpolate
+ * runtime config, so the manifest is rebuilt at runtime: fetch the static file,
+ * merge `name`/`short_name` from the config, and inject the result as a blob
+ * URL into the existing <link rel="manifest">.
+ *
+ * URL-member rewriting is required: the static manifest uses relative
+ * members (`"start_url": "."`, `"src": "modern-logo/logo192.png"`). The manifest
+ * spec resolves every URL member against the manifest URL; a blob URL has an
+ * opaque path, so relative references against it fail WHATWG URL parsing and the
+ * icons are dropped — which fails Chrome's installability check. Before creating
+ * the blob, rewrite `start_url`, every `icons[].src`, and (when present)
+ * `scope` to an absolute URL resolved against the manifest's own URL, and
+ * `id` against the origin of `start_url`, as the spec requires.
+ */
+
+/** PWA short names must stay within 12 code points (ellipsis included) */
+export const MAX_SHORT_NAME_CODE_POINTS = 12;
+
+export interface ManifestIcon {
+ src?: string;
+ sizes?: string;
+ type?: string;
+ purpose?: string;
+ [key: string]: unknown;
+}
+
+export interface StaticManifest {
+ name?: string;
+ short_name?: string;
+ start_url?: string;
+ scope?: string;
+ id?: string;
+ icons?: ManifestIcon[];
+ [key: string]: unknown;
+}
+
+/**
+ * Treat undefined / null / empty / whitespace-only as unset. Returns
+ * the trimmed name, or null when there is no usable configured name.
+ */
+export function resolveAppName(
+ value: string | null | undefined,
+): string | null {
+ if (value == null) {
+ return null;
+ }
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : null;
+}
+
+/**
+ * Truncate a PWA short name to at most 12 code points, including the trailing
+ * ellipsis: the first 11 code points + "…" when the name is longer.
+ * Surrogate-pair-safe: uses Array.from so astral characters (emoji, non-Latin)
+ * are never split.
+ */
+export function truncateShortName(name: string): string {
+ const codePoints = Array.from(name);
+ if (codePoints.length <= MAX_SHORT_NAME_CODE_POINTS) {
+ return name;
+ }
+ return `${codePoints
+ .slice(0, MAX_SHORT_NAME_CODE_POINTS - 1)
+ .join("")}\u2026`;
+}
+
+/** Resolve a manifest URL member against a base URL. */
+export function resolveManifestUrl(
+ value: string | undefined,
+ base: string,
+): string | undefined {
+ if (typeof value !== "string" || value.trim() === "") {
+ return undefined;
+ }
+ return new URL(value, base).toString();
+}
+
+/** Merge the configured appName into the static manifest. */
+export function mergeManifestName(
+ manifest: StaticManifest,
+ appName: string | null,
+): StaticManifest {
+ if (appName == null) {
+ return manifest;
+ }
+ return {
+ ...manifest,
+ name: appName,
+ short_name: truncateShortName(appName),
+ };
+}
+
+/** Rewrite all URL members to absolute URLs resolved against `base`. */
+export function absolutizeManifestUrls(
+ manifest: StaticManifest,
+ base: string,
+): StaticManifest {
+ const next: StaticManifest = { ...manifest };
+ for (const key of ["start_url", "scope"] as const) {
+ const resolved = resolveManifestUrl(next[key], base);
+ if (resolved !== undefined) {
+ next[key] = resolved;
+ }
+ }
+ // The spec resolves `id` against the origin of `start_url`, not the manifest URL.
+ if (typeof next.start_url === "string" && typeof next.id === "string") {
+ next.id =
+ resolveManifestUrl(next.id, new URL(next.start_url).origin) ?? next.id;
+ }
+ if (Array.isArray(next.icons)) {
+ next.icons = next.icons.map((icon) => {
+ const resolved = resolveManifestUrl(icon.src, base);
+ return resolved !== undefined ? { ...icon, src: resolved } : icon;
+ });
+ }
+ return next;
+}
+
+export interface UseManifestUrlResult {
+ /** The manifest URL for <link rel="manifest">: blob URL when a custom appName
+ * is set, otherwise the static manifestHref. */
+ manifestHref: string;
+}
+
+/**
+ * Produces the runtime manifest URL reflecting the configured appName.
+ *
+ * - Reads the static manifest URL from `useLogoAssets().manifestHref`.
+ * - Fetches the static manifest, merges `name`/`short_name` from
+ * `AppConfig.appNameNavbar` (unset values fall back to the static ones), and
+ * rewrites URL members to absolute URLs.
+ * - Returns a blob URL once the first manifest is ready. A later name change
+ * keeps the previous blob live until its replacement exists, then revokes it.
+ * Unmount also revokes the live blob, so object URLs do not leak.
+ * - Returns the static manifestHref until a blob is ready, and again when the
+ * name is unset or the fetch fails.
+ */
+export function useManifestUrl(): UseManifestUrlResult {
+ const { config } = useAppConfig();
+ const { manifestHref } = useLogoAssets();
+ const appName = resolveAppName(config?.appNameNavbar);
+
+ const [href, setHref] = useState(manifestHref);
+ const createdUrlRef = useRef<string | null>(null);
+
+ useEffect(() => {
+ if (appName == null) {
+ // No custom name: the static manifest is already correct. Point back
+ // at the static href and release any runtime blob from a previous value.
+ if (createdUrlRef.current) {
+ URL.revokeObjectURL(createdUrlRef.current);
+ createdUrlRef.current = null;
+ }
+ setHref(manifestHref);
+ return;
+ }
+
+ let cancelled = false;
+ const controller = new AbortController();
+
+ async function buildManifestUrl() {
+ try {
+ const response = await fetch(manifestHref, {
+ signal: controller.signal,
+ });
+ if (!response.ok) {
+ throw new Error(`Failed to fetch manifest (HTTP ${response.status})`);
+ }
+ const staticManifest = (await response.json()) as StaticManifest;
+
+ const merged = mergeManifestName(staticManifest, appName);
+ // The manifest spec resolves URL members against the manifest URL,
+ // not the page URL. The static manifest lives at `${BASE_PATH}/`,
+ // so resolve against the manifest's own URL to stay correct on
+ // subpath deploys and deep-linked routes.
+ const manifestBase = new URL(manifestHref, window.location.origin);
+ const resolved = absolutizeManifestUrls(
+ merged,
+ manifestBase.toString(),
+ );
+ const blob = new Blob([JSON.stringify(resolved)], {
+ type: "application/manifest+json",
+ });
+ const newUrl = URL.createObjectURL(blob);
+
+ // Superseded by a newer run or unmounted: never leave a blob behind.
+ if (cancelled) {
+ URL.revokeObjectURL(newUrl);
+ return;
+ }
+
+ // Swap: the new blob replaces the previous one, which is released here.
+ if (createdUrlRef.current) {
+ URL.revokeObjectURL(createdUrlRef.current);
+ }
+ createdUrlRef.current = newUrl;
+ setHref(newUrl);
+ } catch (error) {
+ if (cancelled) {
+ // Teardown aborted the fetch (StrictMode double-mount, dep change,
+ // unmount): a normal transition, not a failure worth logging.
+ return;
+ }
+ // Graceful degradation: keep serving the static manifest, and
+ // release the runtime blob it is replacing so none is orphaned.
+ if (createdUrlRef.current) {
+ URL.revokeObjectURL(createdUrlRef.current);
+ createdUrlRef.current = null;
+ }
+ console.error(
+ "[useManifestUrl] Failed to build runtime manifest:",
+ error,
+ );
+ setHref(manifestHref);
+ }
+ }
+
+ buildManifestUrl();
+
+ return () => {
+ cancelled = true;
+ controller.abort();
+ };
+ }, [manifestHref, appName]);
+
+ // Unmount-only cleanup: release the last runtime blob. The per-change swap
+ // above keeps at most one live blob at a time, so this never double-revokes.
+ useEffect(() => {
+ return () => {
+ if (createdUrlRef.current) {
+ URL.revokeObjectURL(createdUrlRef.current);
+ createdUrlRef.current = null;
+ }
+ };
+ }, []);
+
+ return { manifestHref: href };
+}