pluginCacheBuster.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { clearPluginSettingsCache } from './pluginSettings';
  2. const cache: Record<string, string> = {};
  3. const initializedAt: number = Date.now();
  4. type CacheablePlugin = {
  5. path: string;
  6. version: string;
  7. };
  8. export function registerPluginInCache({ path, version }: CacheablePlugin): void {
  9. if (!cache[path]) {
  10. cache[path] = encodeURI(version);
  11. }
  12. }
  13. export function invalidatePluginInCache(pluginId: string): void {
  14. const path = `plugins/${pluginId}/module`;
  15. if (cache[path]) {
  16. delete cache[path];
  17. }
  18. clearPluginSettingsCache(pluginId);
  19. }
  20. export function locateWithCache(load: { address: string }, defaultBust = initializedAt): string {
  21. const { address } = load;
  22. const path = extractPath(address);
  23. if (!path) {
  24. return `${address}?_cache=${defaultBust}`;
  25. }
  26. const version = cache[path];
  27. const bust = version || defaultBust;
  28. return `${address}?_cache=${bust}`;
  29. }
  30. function extractPath(address: string): string | undefined {
  31. const match = /\/public\/(plugins\/.+\/module)\.js/i.exec(address);
  32. if (!match) {
  33. return;
  34. }
  35. const [_, path] = match;
  36. if (!path) {
  37. return;
  38. }
  39. return path;
  40. }