The next-generation file converter. Open source, fully local* and free forever.
feat: welcome back libvips, rework priority system
JovannMC6a5d9d971d2e
diff --git a/bun.lock b/bun.lockindex 3bbbdbe..fd1da6a 100644--- a/bun.lock+++ b/bun.lock@@ -39,6 +39,7 @@"svelte-stripe": "^2.0.0","vert-wasm": "^0.0.2","vite-plugin-wasm": "^3.6.0",+ "wasm-vips": "^0.0.19",},"devDependencies": {"@inlang/paraglide-js": "^2.26.0",@@ -887,6 +888,8 @@"vitefu": ["[email protected]", "", { "peerDependencies": { "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["vite"] }, "sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg=="],+ "wasm-vips": ["[email protected]", "", {}, "sha512-KeejYs8oNqPUd2C/XPRhQtRabydqOSkUyCdWhFf2ucL8rVKqHvtp5ZYuYLyeDG/4y45tvROST3mQWla+1uotSA=="],+"webpack-virtual-modules": ["[email protected]", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="],"which": ["[email protected]", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],diff --git a/messages/en.json b/messages/en.jsonindex d5af6d5..9df7d73 100644--- a/messages/en.json+++ b/messages/en.json@@ -505,6 +505,7 @@"general": "Error converting '{file}': {message}","cancel": "Error canceling conversion for '{file}': {message}","magick": "Error in Magick worker, image conversion may not work as expected.",+ "vips": "Error in libvips worker, image conversion may not work as expected.","ffmpeg": "Error loading FFmpeg, some features may not work as expected.","pandoc": "Error loading Pandoc worker, document conversion may not work as expected.","mediabunny": {diff --git a/package.json b/package.jsonindex fcb1585..1f25c8b 100644--- a/package.json+++ b/package.json@@ -76,7 +76,8 @@"sanitize-html": "^2.18.0","svelte-stripe": "^2.0.0","vert-wasm": "^0.0.2",- "vite-plugin-wasm": "^3.6.0"+ "vite-plugin-wasm": "^3.6.0",+ "wasm-vips": "^0.0.19"},"trustedDependencies": ["@parcel/watcher",diff --git a/src/lib/components/functional/popups/SettingsModal.svelte b/src/lib/components/functional/popups/SettingsModal.svelteindex 3c5255e..24d0e73 100644--- a/src/lib/components/functional/popups/SettingsModal.svelte+++ b/src/lib/components/functional/popups/SettingsModal.svelte@@ -197,6 +197,8 @@continue;}+ void converter.init();+if (targetFile.sequenceKind) {targetFile.conversionSettings = {...targetFile.conversionSettings,diff --git a/src/lib/converters/ffmpeg/ffmpeg.svelte.ts b/src/lib/converters/ffmpeg/ffmpeg.svelte.tsindex 7b97445..43badde 100644--- a/src/lib/converters/ffmpeg/ffmpeg.svelte.ts+++ b/src/lib/converters/ffmpeg/ffmpeg.svelte.ts@@ -18,6 +18,7 @@ import type {NormalizedSettings,} from "#lib/types/conversion-settings";import { videoFormats } from "../vertd/vertd.svelte";+import { applyPriorities } from "../priority";const coreURL = new URL(ffmpegCoreURL, import.meta.url).href;const wasmURL = new URL(ffmpegWasmURL, import.meta.url).href;@@ -33,7 +34,7 @@ export class FFmpegConverter extends Converter {// non supported audio to video formatsprivate cantConvert: string[] = ["ogx"];- public supportedFormats = [+ public supportedFormats = applyPriorities("ffmpeg", [new FormatInfo("mp3", true, true),new FormatInfo("wav", true, true),new FormatInfo("flac", true, true),@@ -66,10 +67,10 @@ export class FFmpegConverter extends Converter {// exclude cantConvert from audio to video(f: string) => {const isCantConvert = this.cantConvert.includes(f);- return new FormatInfo(f, true, !isCantConvert, false, 0);+ return new FormatInfo(f, true, !isCantConvert, false);},),- ];+ ]);public readonly reportsProgress = true;diff --git a/src/lib/converters/index.ts b/src/lib/converters/index.tsindex 5e212f3..39770d9 100644--- a/src/lib/converters/index.ts+++ b/src/lib/converters/index.ts@@ -1,9 +1,10 @@import type { Categories } from "#lib/types";-import type { Converter } from "./converter.svelte";+import type { Converter, WorkerStatus } from "./converter.svelte";import { FFmpegConverter } from "./ffmpeg/ffmpeg.svelte";import { PandocConverter } from "./pandoc/pandoc.svelte";import { VertdConverter } from "./vertd/vertd.svelte";import { MagickConverter } from "./magick/magick.svelte";+import { VipsConverter } from "./vips/vips.svelte";import { MediabunnyConverter } from "./mediabunny/mediabunny.svelte";import { DISABLE_ALL_EXTERNAL_REQUESTS } from "#lib/util/consts";@@ -11,6 +12,7 @@ import { DISABLE_ALL_EXTERNAL_REQUESTS } from "#lib/util/consts";const getConverters = (): Converter[] => {const converters: Converter[] = [new MagickConverter(),+ new VipsConverter(),new FFmpegConverter(),new PandocConverter(),new MediabunnyConverter(),@@ -23,13 +25,14 @@ const getConverters = (): Converter[] => {export const converters = getConverters();export const converterCategories = {- image: ["imagemagick"],+ image: ["libvips", "imagemagick"],video: ["mediabunny", "vertd"],audio: ["ffmpeg"],doc: ["pandoc"],};-export type ConverterCategory = keyof typeof converterCategories | "archive" | "unknown";+export type ConverterCategory =+ keyof typeof converterCategories | "archive" | "unknown";export const categoryByConverter = Object.fromEntries(Object.entries(converterCategories).flatMap(([category, names]) =>@@ -69,10 +72,13 @@ categories.video.formats = [),),];-categories.image.formats =- converters- .find((c) => converterCategories.image.includes(c.name))- ?.formatStrings((f) => f.toSupported) || [];+categories.image.formats = [+ ...new Set(+ converters+ .filter((c) => converterCategories.image.includes(c.name))+ .flatMap((c) => c.formatStrings((f) => f.toSupported)),+ ),+];categories.doc.formats =converters.find((c) => converterCategories.doc.includes(c.name))@@ -90,3 +96,29 @@ export const byNative = (format: string) => {return 0;};};++export function categoryStatus(category: ConverterCategory): WorkerStatus {+ const names =+ (converterCategories as Record<string, string[]>)[category] ?? [];+ const all = converters.filter((c) => names.includes(c.name));+ const available = all.filter((c) => c.isAvailable());+ const members = available.length ? available : all;++ if (!members.length) return "idle";++ const isReady = (s: WorkerStatus) =>+ s === "ready" || s === "partially-ready";+ const readyCount = members.filter((c) => isReady(c.status)).length;++ if (readyCount === members.length) return "ready";+ if (readyCount > 0) return "partially-ready";+ if (members.some((c) => c.status === "error")) return "error";+ if (+ members.some(+ (c) => c.status === "downloading" || c.status === "initializing",+ )+ )+ return "downloading";++ return "idle";+}diff --git a/src/lib/converters/magick/magick.svelte.ts b/src/lib/converters/magick/magick.svelte.tsindex b1b2b58..14d43a7 100644--- a/src/lib/converters/magick/magick.svelte.ts+++ b/src/lib/converters/magick/magick.svelte.ts@@ -3,6 +3,7 @@ import { m } from "#lib/paraglide/messages";import { VertFile, type WorkerMessage } from "#lib/types";import MagickWorker from "#lib/workers/magick?worker&url";import { Converter, FormatInfo } from "../converter.svelte";+import { applyPriorities } from "../priority";import { imageFormats } from "./magick-automated";import {formatsWithoutMetadataRemoval,@@ -25,7 +26,7 @@ export class MagickConverter extends Converter {private activeConversions = new SvelteMap<string, Worker>();- public supportedFormats = [+ public supportedFormats = applyPriorities("imagemagick", [// manually tested formatsnew FormatInfo("png", true, true),new FormatInfo("jpeg", true, true),@@ -86,7 +87,7 @@ export class MagickConverter extends Converter {// formats added from maya's somewhat automated testing...imageFormats,- ];+ ]);public readonly reportsProgress = false;diff --git a/src/lib/converters/mediabunny/mediabunny.svelte.ts b/src/lib/converters/mediabunny/mediabunny.svelte.tsindex 25e8df7..044925d 100644--- a/src/lib/converters/mediabunny/mediabunny.svelte.ts+++ b/src/lib/converters/mediabunny/mediabunny.svelte.ts@@ -26,6 +26,7 @@ import { registerFlacEncoder } from "@mediabunny/flac-encoder";import { registerProresDecoder } from "@mediabunny/prores";import { SvelteMap } from "svelte/reactivity";import { Converter, FormatInfo } from "../converter.svelte";+import { applyPriorities } from "../priority";import { m } from "#lib/paraglide/messages";import type {SettingDefinition,@@ -150,9 +151,10 @@ export class MediabunnyConverter extends Converter {"ts",];- public supportedFormats: FormatInfo[] = [- ...this.formats.map((f) => new FormatInfo(f, true, true, true, 2)),- ];+ public supportedFormats: FormatInfo[] = applyPriorities(+ "mediabunny",+ this.formats.map((f) => new FormatInfo(f, true, true, true)),+ );constructor() {super();diff --git a/src/lib/converters/priority.ts b/src/lib/converters/priority.tsnew file mode 100644index 0000000..9e10549--- /dev/null+++ b/src/lib/converters/priority.ts@@ -0,0 +1,64 @@+import type { FormatInfo } from "./converter.svelte";++export const DEFAULT_PRIORITY = 1;++export const PREFERRED_PRIORITY = 5;++const normalize = (format: string) =>+ (format.startsWith(".") ? format.slice(1) : format).toLowerCase();++export const FORMAT_ENGINES: Record<string, string[]> = {+ // images - prefer libvips for speed & memory efficiency, then ImageMagick+ png: ["libvips", "imagemagick"],+ jpg: ["libvips", "imagemagick"],+ jpeg: ["libvips", "imagemagick"],+ jpe: ["libvips", "imagemagick"],+ jfif: ["libvips", "imagemagick"],+ tif: ["libvips", "imagemagick"],+ tiff: ["libvips", "imagemagick"],+ avif: ["libvips", "imagemagick"],+ jxl: ["libvips", "imagemagick"],+ svg: ["libvips", "imagemagick"],+ heic: ["libvips", "imagemagick"],+ heif: ["libvips", "imagemagick"],+ ppm: ["libvips", "imagemagick"],+ pnm: ["libvips", "imagemagick"],++ // formats that are both image and video (animated formats) — image engines first, then video+ webp: ["libvips", "imagemagick", "vertd"],+ gif: ["libvips", "imagemagick", "vertd"],++ // video - local supported+ mp4: ["mediabunny", "vertd"],+ m4v: ["mediabunny", "vertd"],+ mkv: ["mediabunny", "vertd"],+ webm: ["mediabunny", "vertd"],+ mov: ["mediabunny", "vertd"],+ f4v: ["mediabunny", "vertd"],+ "3gp": ["mediabunny", "vertd"],+ "3g2": ["mediabunny", "vertd"],+ mts: ["mediabunny", "vertd"],+ m2ts: ["mediabunny", "vertd"],+ ts: ["mediabunny", "vertd"],+};++export function priorityFor(converter: string, format: string): number {+ const engines = FORMAT_ENGINES[normalize(format)];+ if (!engines) return DEFAULT_PRIORITY;++ const index = engines.indexOf(converter);+ if (index === -1) return DEFAULT_PRIORITY;++ return Math.max(DEFAULT_PRIORITY, PREFERRED_PRIORITY - index);+}++export function applyPriorities(+ converter: string,+ formats: FormatInfo[],+): FormatInfo[] {+ for (const format of formats) {+ if (FORMAT_ENGINES[normalize(format.name)])+ format.priority = priorityFor(converter, format.name);+ }+ return formats;+}diff --git a/src/lib/converters/vertd/vertd.svelte.ts b/src/lib/converters/vertd/vertd.svelte.tsindex 9d3cae2..cb6aac6 100644--- a/src/lib/converters/vertd/vertd.svelte.ts+++ b/src/lib/converters/vertd/vertd.svelte.ts@@ -8,6 +8,7 @@ import {} from "#lib/sections/settings/vertdSettings.svelte";import { VertFile } from "#lib/types";import { Converter, FormatInfo } from "../converter.svelte";+import { applyPriorities } from "../priority";import { PUB_DISABLE_FAILURE_BLOCKS } from "$app/env/public";import { ToastManager } from "#lib/util/toast.svelte";import type {@@ -370,15 +371,15 @@ export class VertdConverter extends Converter {private cancelledConversions = new SvelteSet<string>();- public supportedFormats = [+ public supportedFormats = applyPriorities("vertd", [new FormatInfo("zip", true, false, false, 0),...videoFormats- .map((f: string) => new FormatInfo(f, true, true, true, 0))+ .map((f: string) => new FormatInfo(f, true, true, true)).filter((format) => !cantEncode.includes(format.name.slice(1))).filter((format) => !cantDecode.includes(format.name.slice(1))),- ...cantEncode.map((f) => new FormatInfo(f, true, false, true, 0)),- ...cantDecode.map((f) => new FormatInfo(f, false, true, true, 0)),- ];+ ...cantEncode.map((f) => new FormatInfo(f, true, false, true)),+ ...cantDecode.map((f) => new FormatInfo(f, false, true, true)),+ ]);private codecs: CodecsResponse = { videoCodecs: [], audioCodecs: [] };diff --git a/src/lib/converters/vips/formats.ts b/src/lib/converters/vips/formats.tsnew file mode 100644index 0000000..afb9707--- /dev/null+++ b/src/lib/converters/vips/formats.ts@@ -0,0 +1,50 @@+import { FormatInfo } from "../converter.svelte";+import { applyPriorities } from "../priority";++const f = (name: string, fromSupported = true, toSupported = true) =>+ new FormatInfo(name, fromSupported, toSupported, true);++export const vipsFormats: FormatInfo[] = applyPriorities("libvips", [+ // read + write+ f("png"),+ f("jpg"),+ f("jpeg"),+ f("jpe"),+ f("jfif"),+ f("webp"),+ f("gif"),+ f("tif"),+ f("tiff"),+ f("avif"),+ f("jxl"),+ f("ppm"),+ f("pnm"),++ // decode only+ f("heic", true, false), // HEIC encode needs an unsupported compression in this build+ f("heif", true, false),+ f("svg", true, false), // rendered via resvg+ f("uhdr", true, false), // gain map / HDR jpeg, load only+]);++export const VIPS_QUALITY_FORMATS = new Set([+ ".png",+ ".jpg",+ ".jpeg",+ ".jpe",+ ".jfif",+ ".webp",+ ".avif",+ ".jxl",+ ".tif",+ ".tiff",+]);++export const VIPS_OPAQUE_FORMATS = new Set([+ ".jpg",+ ".jpeg",+ ".jpe",+ ".jfif",+ ".ppm",+ ".pnm",+]);diff --git a/src/lib/converters/vips/vips.svelte.ts b/src/lib/converters/vips/vips.svelte.tsnew file mode 100644index 0000000..cc64c0b--- /dev/null+++ b/src/lib/converters/vips/vips.svelte.ts@@ -0,0 +1,222 @@+import { browser } from "$app/env";+import { m } from "#lib/paraglide/messages";+import { VertFile, type WorkerMessage } from "#lib/types";+import VipsWorker from "#lib/workers/vips?worker&url";+import { Converter } from "../converter.svelte";+import { ToastManager } from "#lib/util/toast.svelte";+import type {+ SettingDefinition,+ SettingCategories,+ ConversionSettings,+} from "#lib/types/conversion-settings";+import {+ vipsFormats,+ VIPS_QUALITY_FORMATS,+ VIPS_OPAQUE_FORMATS,+} from "./formats";+import { SvelteMap } from "svelte/reactivity";++export class VipsConverter extends Converter {+ public name = "libvips";+ public ready = $state(false);++ private activeConversions = new SvelteMap<string, Worker>();++ public supportedFormats = vipsFormats;++ public readonly reportsProgress = false;++ constructor() {+ super();+ if (!browser) return;+ this.log(`created converter`);+ }++ private get isolated(): boolean {+ return (+ typeof crossOriginIsolated !== "undefined" && crossOriginIsolated+ );+ }++ public override isAvailable(): boolean {+ if (browser && !this.isolated) return false;+ return super.isAvailable();+ }++ protected async download(): Promise<void> {+ const worker = new Worker(VipsWorker, { type: "module" });+ try {+ await this.waitForMessage(worker, "loaded", 60000, () => {+ worker.postMessage({ type: "load", id: "init" });+ });++ this.ready = true;+ this.status = "ready";+ this.log(`wasm-vips initialised`);+ } catch (err) {+ this.error(`failed to initialise wasm-vips: ${err}`);+ ToastManager.add({+ type: "error",+ message: m["workers.errors.vips"](),+ });+ throw err;+ } finally {+ worker.terminate();+ }+ }++ public async getAvailableSettings(+ input: VertFile,+ ): Promise<SettingCategories> {+ const to = input.to.toLowerCase();++ const settings: SettingDefinition[] = [];++ if (VIPS_QUALITY_FORMATS.has(to)) {+ settings.push({+ key: "quality",+ label: m["convert.settings.image.quality.label"](),+ type: "number",+ min: 0,+ max: 100,+ placeholder: m["convert.settings.image.quality.placeholder"](),+ });+ }++ if (!VIPS_OPAQUE_FORMATS.has(to)) {+ settings.push({+ key: "transparency",+ label: m["convert.settings.image.transparency"](),+ type: "boolean",+ default: true,+ });+ }++ const metadata: SettingDefinition = {+ key: "metadata",+ label: m["convert.settings.common.metadata"](),+ type: "boolean",+ default: true,+ };++ return {+ Image: settings,+ General: [metadata],+ };+ }++ public async convert(+ input: VertFile,+ to: string,+ settings: ConversionSettings,+ ): Promise<VertFile> {+ await this.init();++ this.trackConversion(input);+ this.log(`converting ${input.name} to ${to}`);++ if (!this.isolated)+ throw new Error(+ "cross-origin isolation is required for wasm-vips (SharedArrayBuffer unavailable)",+ );++ const worker = new Worker(VipsWorker, { type: "module" });+ this.activeConversions.set(input.id, worker);++ try {+ worker.postMessage({ type: "load", id: input.id });+ await this.waitForMessage(worker, "loaded", 60000);++ const convertMsg: WorkerMessage = {+ type: "convert",+ id: input.id,+ input: {+ file: input.file,+ name: input.name,+ from: input.from,+ to: input.to,+ },+ to,+ conversionSettings: JSON.stringify(settings ?? {}),+ };+ worker.postMessage(convertMsg);++ const res = await this.waitForMessage(worker);+ if (res.type === "finished") {+ this.log(`converted ${input.name} to ${to}`);+ return new VertFile(+ new File([res.output as unknown as BlobPart], input.name),+ res.zip ? ".zip" : to,+ );+ }++ if (res.type === "error") throw new Error(res.error);++ throw new Error("Unknown message type");+ } finally {+ this.clearTrackedConversion(input);+ this.activeConversions.delete(input.id);+ worker.terminate();+ }+ }++ public async cancel(input: VertFile): Promise<void> {+ const worker = this.activeConversions.get(input.id);+ if (!worker) {+ this.error(`no active conversion found for file ${input.name}`);+ return;+ }++ this.log(`cancelling conversion for file ${input.name}`);++ worker.terminate();+ this.activeConversions.delete(input.id);+ }++ private waitForMessage<T = WorkerMessage>(+ worker: Worker,+ type?: string,+ timeout?: number,+ post?: () => void,+ ): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const onMessage = (e: MessageEvent<WorkerMessage>) => {+ if (type && e.data.type === type) {+ cleanup();+ resolve(e.data as T);+ } else if (!type) {+ cleanup();+ resolve(e.data as T);+ } else if (e.data.type === "error") {+ cleanup();+ reject(new Error(e.data.error));+ }+ };++ const onError = (e: ErrorEvent) => {+ cleanup();+ reject(new Error(`Worker error: ${e.message}`));+ };++ const cleanup = () => {+ worker.removeEventListener("message", onMessage);+ worker.removeEventListener("error", onError);+ if (timeoutId) clearTimeout(timeoutId);+ };++ const timeoutId = timeout+ ? setTimeout(() => {+ cleanup();+ reject(+ new Error(`Vips worker timeout after ${timeout}ms`),+ );+ }, timeout)+ : undefined;++ worker.addEventListener("message", onMessage);+ worker.addEventListener("error", onError);++ post?.();+ });+ }+}diff --git a/src/lib/util/debug.svelte.ts b/src/lib/util/debug.svelte.tsindex ec18519..5885ee2 100644--- a/src/lib/util/debug.svelte.ts+++ b/src/lib/util/debug.svelte.ts@@ -44,6 +44,11 @@ export const CONVERTER_META: Record<icon: ImageIcon,accent: "bg-accent-blue",},+ libvips: {+ category: "image",+ icon: ImageIcon,+ accent: "bg-accent-blue-alt",+ },ffmpeg: {category: "audio",icon: AudioLinesIcon,diff --git a/src/lib/util/sw.ts b/src/lib/util/sw.tsindex 3e1e0b8..6da1d5c 100644--- a/src/lib/util/sw.ts+++ b/src/lib/util/sw.ts@@ -1,5 +1,7 @@import { browser } from "$app/env";+const COI_RELOAD_KEY = "vertCoiReloaded";+export interface CacheInfo {totalSize: number;fileCount: number;@@ -28,6 +30,9 @@ class ServiceWorkerManager {);this.initialized = true;++ await navigator.serviceWorker.ready;+ this.ensureCrossOriginIsolation();} catch (error) {console.error("[SW Manager] service worker registration failed:",@@ -36,6 +41,31 @@ class ServiceWorkerManager {}}+ // ensure we are cross-origin isolated (COOP/COEP) so we can use SharedArrayBuffer+ private ensureCrossOriginIsolation(): void {+ const controlled = !!navigator.serviceWorker.controller;+ const isolated = window.crossOriginIsolated === true;++ if (controlled || isolated) {+ // success (or resumed) — allow a future reload for SW updates+ sessionStorage.removeItem(COI_RELOAD_KEY);+ if (controlled && !isolated)+ console.warn(+ "[SW Manager] service worker active but page is not cross-origin isolated; wasm-vips will be unavailable.",+ );+ return;+ }++ // already reloaded once and still not isolated, don't infinite loop+ if (sessionStorage.getItem(COI_RELOAD_KEY)) return;++ sessionStorage.setItem(COI_RELOAD_KEY, "controlling");+ console.log(+ "[SW Manager] reloading to let the service worker enable cross-origin isolation",+ );+ window.location.reload();+ }+async getCacheInfo(): Promise<CacheInfo> {if (!this.registration || !navigator.serviceWorker.controller) {console.warn(diff --git a/src/lib/workers/vips.ts b/src/lib/workers/vips.tsnew file mode 100644index 0000000..a1731fd--- /dev/null+++ b/src/lib/workers/vips.ts@@ -0,0 +1,164 @@+import Vips from "wasm-vips";+import vipsWasm from "wasm-vips/vips.wasm?url";+import vipsJxlWasm from "wasm-vips/vips-jxl.wasm?url";+import vipsHeifWasm from "wasm-vips/vips-heif.wasm?url";+import vipsResvgWasm from "wasm-vips/vips-resvg.wasm?url";+import type { WorkerMessage } from "#lib/types";+import type { ConversionSettings } from "#lib/types/conversion-settings";++type VipsInstance = Awaited<ReturnType<typeof Vips>>;+type VipsImage = ReturnType<VipsInstance["Image"]["newFromBuffer"]>;++const WASM_URLS: Record<string, string> = {+ "vips.wasm": vipsWasm,+ "vips-jxl.wasm": vipsJxlWasm,+ "vips-heif.wasm": vipsHeifWasm,+ "vips-resvg.wasm": vipsResvgWasm,+};++const DYNAMIC_LIBRARIES = [+ "vips-jxl.wasm",+ "vips-heif.wasm",+ "vips-resvg.wasm",+];++const NO_QUALITY = new Set([".gif", ".svg", ".ppm", ".pnm"]);+const OPAQUE = new Set([".jpg", ".jpeg", ".jpe", ".jfif", ".ppm", ".pnm"]);++const isWasmException = (err: unknown): err is WebAssembly.Exception =>+ typeof WebAssembly !== "undefined" &&+ typeof WebAssembly.Exception === "function" &&+ err instanceof WebAssembly.Exception;++const formatError = (err: unknown): string => {+ if (isWasmException(err)) {+ const payload = (err as { message?: unknown }).message;+ if (Array.isArray(payload)) {+ const parts = payload.filter(+ (part): part is string =>+ typeof part === "string" && part.length > 0,+ );+ if (parts.length) return parts.join(": ").trim();+ } else if (typeof payload === "string" && payload.length) {+ return payload;+ }+ }++ if (err instanceof Error) return err.message;+ return String(err);+};++let vips: VipsInstance | null = null;+let vipsPromise: Promise<VipsInstance> | null = null;+let initialized = false;++const loadVips = (): Promise<VipsInstance> => {+ return (vipsPromise ??= Vips({+ dynamicLibraries: DYNAMIC_LIBRARIES,+ locateFile: (name: string) => WASM_URLS[name] ?? name,+ workaroundCors: true,+ }).catch((err) => {+ throw new Error(+ `wasm-vips failed to initialise (is the page cross-origin isolated?): ${err}`,+ );+ }));+};++const conversionOptions = (+ to: string,+ settings: ConversionSettings,+): Record<string, unknown> => {+ const options: Record<string, unknown> = {};++ if (!settings.metadata || settings.metadata === "false")+ options.strip = true;++ const quality = Number(settings.quality ?? settings.compression);+ if (!Number.isNaN(quality) && quality > 0 && !NO_QUALITY.has(to))+ options.Q = Math.min(100, quality);++ return options;+};++const handleMessage = async (+ message: WorkerMessage,+): Promise<Partial<WorkerMessage>> => {+ switch (message.type) {+ case "load": {+ try {+ vips = await loadVips();+ initialized = true;+ return { type: "loaded" };+ } catch (err) {+ return { type: "error", error: formatError(err) };+ }+ }+ case "convert": {+ if (!initialized || !vips)+ return { type: "error", error: "wasm-vips not initialized" };++ const to = message.to.startsWith(".")+ ? message.to.toLowerCase()+ : `.${message.to.toLowerCase()}`;+ const from = message.input.from;++ const settings = JSON.parse(+ message.conversionSettings || "{}",+ ) as ConversionSettings;++ const buffer = new Uint8Array(+ await message.input.file.arrayBuffer(),+ );++ let image: VipsImage | null = null;+ let flattened: VipsImage | null = null;++ try {+ image = vips.Image.newFromBuffer(buffer);++ // re-read with every page/frame if the image is animated+ if (image.getTypeof("n-pages") > 0) {+ image.delete();+ image = vips.Image.newFromBuffer(buffer, "[n=-1]");+ }++ let source = image;++ // flatten transparency when the target can't store alpha or the user opted out+ const keepAlpha = settings.transparency !== false;+ if ((!keepAlpha || OPAQUE.has(to)) && image.hasAlpha()) {+ flattened = image.flatten({ background: [255, 255, 255] });+ source = flattened;+ }++ const result = source.writeToBuffer(+ to,+ conversionOptions(to, settings),+ );++ return { type: "finished", output: result };+ } catch (err) {+ return {+ type: "error",+ error: `vips failed to convert ${from} to ${to}: ${formatError(err)}`,+ };+ } finally {+ flattened?.delete();+ image?.delete();+ }+ }+ default:+ return { type: "error", error: "Unknown message type" };+ }+};++onmessage = async (e: MessageEvent<WorkerMessage>) => {+ const message = e.data;+ try {+ const res = await handleMessage(message);+ if (!res) return;+ postMessage({ ...res, id: message.id });+ } catch (err) {+ postMessage({ type: "error", error: formatError(err), id: message.id });+ }+};diff --git a/src/routes/+page.svelte b/src/routes/+page.svelteindex 7d408c8..23cb9ce 100644--- a/src/routes/+page.svelte+++ b/src/routes/+page.svelte@@ -1,7 +1,7 @@<script lang="ts">import Uploader from "#lib/components/functional/Uploader.svelte";import Tooltip from "#lib/components/visual/Tooltip.svelte";- import { converters } from "#lib/converters";+ import { converters, categoryStatus } from "#lib/converters";import { vertdLoaded } from "#lib/store/index.svelte";import clsx from "clsx";import {@@ -29,6 +29,20 @@).join(", ") || "none";+ const getImageFormats = () =>+ Array.from(+ new Set(+ converters+ .filter((c) => ["imagemagick", "libvips"].includes(c.name))+ .flatMap((c) =>+ c.supportedFormats.map(+ (f) =>+ `${f.name}${f.fromSupported && f.toSupported ? "" : "*"}`,+ ),+ ),+ ),+ ).join(", ");+const worker: {[key: string]: {formats: string;@@ -46,28 +60,22 @@};} = {Images: {- formats: getSupportedFormats("imagemagick"),+ formats: getImageFormats(),icon: ImageIcon,title: m["upload.cards.images"](),- status:- converters.find((c) => c.name === "imagemagick")?.status ||- "idle",+ status: categoryStatus("image"),},Audio: {formats: getSupportedFormats("ffmpeg"),icon: AudioLinesIcon,title: m["upload.cards.audio"](),- status:- converters.find((c) => c.name === "ffmpeg")?.status ||- "idle",+ status: categoryStatus("audio") || "idle",},Documents: {formats: getSupportedFormats("pandoc"),icon: BookTextIcon,title: m["upload.cards.documents"](),- status:- converters.find((c) => c.name === "pandoc")?.status ||- "idle",+ status: categoryStatus("doc") || "idle",},};diff --git a/static/sw.js b/static/sw.jsindex a5b57ae..89d6aa9 100644--- a/static/sw.js+++ b/static/sw.js@@ -1,4 +1,6 @@-const CACHE_NAME = "vert-wasm-cache-v4"; // updated when workers update+const CACHE_NAME = "vert-wasm-cache-v5"; // updated when workers update++let coepCredentialless = false;const WASM_FILES = ["/pandoc.wasm", // from https://github.com/haskell-wasm/pandoc-wasm@@ -8,6 +10,7 @@ const WASM_URL_PATTERNS = [/\/src\/lib\/workers\/.*\.js$/, // dev mode worker files/\/assets\/.*worker.*\.js$/, // prod worker files/magick.*\.wasm$/, // magick-wasm (unneeded?)+ /vips.*\.wasm$/, // wasm-vips (main + dynamic libs)/\/ffmpeg-core[^/]*\.(js|wasm)$/, // ffmpeg wasm core];@@ -62,6 +65,51 @@ async function revalidate(request) {}}+// add COOP/COEP headers to requests so we are cross-origin isolated, needed for SharedArrayBuffer+function withCrossOriginIsolation(response) {+ if (response.status === 0) return response;++ const headers = new Headers(response.headers);+ headers.set(+ "Cross-Origin-Embedder-Policy",+ coepCredentialless ? "credentialless" : "require-corp",+ );+ if (!coepCredentialless)+ headers.set("Cross-Origin-Resource-Policy", "cross-origin");+ headers.set("Cross-Origin-Opener-Policy", "same-origin");++ return new Response(response.body, {+ status: response.status,+ statusText: response.statusText,+ headers,+ });+}++// fetch a cacheable url, storing a copy on success+async function fetchAndCache(request) {+ const response = await fetch(request);++ if (!response.ok) {+ console.warn(+ "[SW] not caching failed response:",+ response.status,+ request.url,+ );+ return response;+ }++ const responseToCache = response.clone();+ caches+ .open(CACHE_NAME)+ .then((cache) => cache.put(request, responseToCache))+ .then(() => console.log("[SW] cached successfully:", request.url))+ .catch((err) =>+ console.warn("[SW] failed to cache:", request.url, err),+ );++ return response;+}+self.addEventListener("install", (e) => {console.log("[SW] installing service worker");@@ -106,60 +154,35 @@ self.addEventListener("activate", (e) => {});self.addEventListener("fetch", (e) => {- const request = e.request;+ const r = e.request;- if (!shouldCacheUrl(request.url)) {- return; // Let the request go through normally if not a target URL- }+ if (r.cache === "only-if-cached" && r.mode !== "same-origin") return;++ const request =+ coepCredentialless && r.mode === "no-cors"+ ? new Request(r, { credentials: "omit" })+ : r;- // else intercept request+ const caching = shouldCacheUrl(request.url);const revalidateInBackground = shouldRevalidate(request.url);e.respondWith(- caches.match(request).then((cachedResponse) => {- if (cachedResponse) {- console.log("[SW] serving from cache:", request.url);- return cachedResponse;- }-- console.log("[SW] fetching and caching:", request.url);- return fetch(request)- .then((response) => {- if (!response.ok) {- console.warn(- "[SW] not caching failed response:",- response.status,- request.url,- );- return response;+ (caching+ ? caches.match(request).then((cachedResponse) => {+ if (cachedResponse) {+ console.log("[SW] serving from cache:", request.url);+ return cachedResponse;}-- const responseToCache = response.clone();- caches.open(CACHE_NAME).then((cache) => {- cache- .put(request, responseToCache)- .then(() => {- console.log(- "[SW] cached successfully:",- request.url,- );- })- .catch((err) => {- console.warn(- "[SW] failed to cache:",- request.url,- err,- );- });- });-- return response;+ console.log("[SW] fetching and caching:", request.url);+ return fetchAndCache(request);})- .catch((err) => {- console.error("[SW] fetch failed for:", request.url, err);- throw err;- });- }),+ : fetch(request)+ )+ .then(withCrossOriginIsolation)+ .catch((err) => {+ console.error("[SW] fetch failed for:", request.url, err);+ throw err;+ }),);// refresh same-origin wasm in the background so a redeploy is picked up, even while the cached copy is served@@ -171,6 +194,11 @@ self.addEventListener("message", (e) => {const type = e.data.type;const port = e.ports?.[0];+ if (type === "coepCredentialless") {+ coepCredentialless = e.data.value === true;+ return;+ }+if (type === "GET_CACHE_INFO") {if (!port) return;e.waitUntil(diff --git a/vite.config.ts b/vite.config.tsindex e61978b..133fafe 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -65,8 +65,15 @@ export default defineConfig(({ command }) => {"@ffmpeg/core-mt","@ffmpeg/ffmpeg","@ffmpeg/util",+ "wasm-vips",],},+ server: {+ headers: {+ "Cross-Origin-Embedder-Policy": "credentialless",+ "Cross-Origin-Opener-Policy": "same-origin",+ },+ },build: {target: "esnext",},