| 16 | const dataDir = process.env.DATA_PATH || "./.data"; |
| 17 | |
| 18 | const updateCache = async () => { |
| 19 | if (process.env.ENABLE_ASSETS_SERVER !== "true") return; |
| 20 | |
| 21 | const cacheConfigPath = path.join(dataDir, "assets-cache.json"); |
| 22 | let cacheConfig = {}; |
| 23 | |
| 24 | try { |
| 25 | cacheConfig = JSON.parse(await fs.readFile(cacheConfigPath, "utf-8")); |
| 26 | } catch {} |
| 27 | |
| 28 | const lastUpdate = cacheConfig.lastUpdate || 0; |
| 29 | const currentTime = Date.now(); |
| 30 | const updateInterval = 1000 * 60 * 60 * 24; // 1 day |
| 31 | const intervalExceeded = currentTime - lastUpdate > updateInterval; |
| 32 | |
| 33 | const WIDGET_VERSION = process.env.WIDGET_VERSION || "latest"; |
| 34 | const WASM_VERSION = process.env.WASM_VERSION || "latest"; |
| 35 | |
| 36 | if (!cacheConfig.versions) cacheConfig.versions = {}; |
| 37 | const versionsChanged = cacheConfig.versions.widget !== WIDGET_VERSION |
| 38 | || cacheConfig.versions.wasm !== WASM_VERSION; |
| 39 | |
| 40 | if (!intervalExceeded && !versionsChanged) return; |
| 41 | |
| 42 | const CACHE_HOST = process.env.CACHE_HOST || "https://cdn.jsdelivr.net"; |
| 43 | |
| 44 | try { |
| 45 | const [widgetSource, floatingSource, wasmSource, wasmLoaderSource] = |
| 46 | await Promise.all([ |
| 47 | fetch(`${CACHE_HOST}/npm/@cap.js/widget@${WIDGET_VERSION}`).then((r) => |
| 48 | r.text(), |
| 49 | ), |
| 50 | fetch( |
| 51 | `${CACHE_HOST}/npm/@cap.js/widget@${WIDGET_VERSION}/cap-floating.min.js`, |
| 52 | ).then((r) => r.text()), |
| 53 | fetch( |
| 54 | `${CACHE_HOST}/npm/@cap.js/wasm@${WASM_VERSION}/browser/cap_wasm_bg.wasm`, |
| 55 | ).then((r) => r.arrayBuffer()), |
| 56 | fetch( |
| 57 | `${CACHE_HOST}/npm/@cap.js/wasm@${WASM_VERSION}/browser/cap_wasm.min.js`, |
| 58 | ).then((r) => r.text()), |
| 59 | ]); |
| 60 | |
| 61 | cacheConfig.lastUpdate = currentTime; |
| 62 | cacheConfig.versions.widget = WIDGET_VERSION; |
| 63 | cacheConfig.versions.wasm = WASM_VERSION; |
| 64 | await fs.writeFile(cacheConfigPath, JSON.stringify(cacheConfig)); |
| 65 | |
| 66 | await fs.writeFile(path.join(dataDir, "assets-widget.js"), widgetSource); |
| 67 | await fs.writeFile( |
| 68 | path.join(dataDir, "assets-floating.js"), |
| 69 | floatingSource, |
| 70 | ); |
| 71 | await fs.writeFile( |
| 72 | path.join(dataDir, "assets-cap_wasm_bg.wasm"), |
| 73 | Buffer.from(wasmSource), |
| 74 | ); |
| 75 | await fs.writeFile( |