// Vite plugin: makes heic2any work under the site's strict CSP (script-src 'self', no 'unsafe-eval'). // // heic2any runs libheif (compiled to asm.js by Emscripten) in a Web Worker. Its "embind" glue builds // three small functions from strings with new Function(), which the CSP blocks, so HEIC conversion // hangs in Chrome, Edge and Firefox. This swaps those three spots for plain closures that do the same // job (the same shapes Emscripten itself emits when built with DYNAMIC_EXECUTION=0). // Only the build output is changed; node_modules stays as installed. // If heic2any is upgraded and a pattern is no longer found, the build stops so nobody ships it broken. const TARGET = /heic2any[\\/]dist[\\/]heic2any(\.min)?\.js$/; // The worker code lives inside a double-quoted string in heic2any.js, so the replacements below // use single quotes only. const PATCHES = [ { name: 'createNamedFunction', find: `new Function(\\"body\\",\\"return function \\"+A+'() {\\\\n \\"use strict\\"; return body.apply(this, arguments);\\\\n};\\\\n')(e)`, replace: 'function(){return e.apply(this,arguments)}', count: 2, }, { name: 'craftInvokerFunction', find: /function xe\(A,e,r,i,f\)\{var n=e\.length;[\s\S]*?He\(Function,d\)\.apply\(null,k\)\}/, replace: "function xe(A,e,r,i,f){var n=e.length;n<2&&HA('argTypes array size mismatch! Must at least get return value and this types!');" + "for(var t=null!==e[1]&&null!==r,o=!1,a=1;a p.replace); } if (/new Function|\(Function,/.test(out)) throw new Error('heic2any CSP patch: some string-built code is left. Check the heic2any version.'); return out; } export default function heicNoEval() { return { name: 'heic2any-no-eval', enforce: 'pre', transform(code, id) { if (!TARGET.test(id.split('?')[0])) return null; return { code: patchHeic2any(code), map: null }; }, }; }