ConfigManager.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2. /** Function that takes the data in the old format and returns the data in the new format. Also supports an asynchronous migration. */
  3. type MigrationFunc = (oldData: any) => any | Promise<any>;
  4. /** Dictionary of format version numbers and the function that migrates to them from the previous whole integer */
  5. export type ConfigMigrationsDict = Record<number, MigrationFunc>;
  6. /** Options for the ConfigManager instance */
  7. export interface ConfigManagerOptions<TData> {
  8. /** A unique internal ID for this configuration - choose wisely as changing it is not supported yet. */
  9. id: string;
  10. /**
  11. * The default config data object to use if no data is saved in persistent storage yet.
  12. * Until the data is loaded from persistent storage with `loadData()`, this will be the data returned by `getData()`
  13. *
  14. * ⚠️ This has to be an object that can be serialized to JSON, so no functions or circular references are allowed, they will cause unexpected behavior.
  15. */
  16. defaultConfig: TData;
  17. /**
  18. * An incremental, whole integer version number of the current format of config data.
  19. * If the format of the data is changed in any way, this number should be incremented, in which case all necessary functions of the migrations dictionary will be run consecutively.
  20. *
  21. * ⚠️ Never decrement this number and optimally don't skip any numbers either!
  22. */
  23. formatVersion: number;
  24. /**
  25. * A dictionary of functions that can be used to migrate data from older versions of the configuration to newer ones.
  26. * The keys of the dictionary should be the format version that the functions can migrate to, from the previous whole integer value.
  27. * The values should be functions that take the data in the old format and return the data in the new format.
  28. * The functions will be run in order from the oldest to the newest version.
  29. * If the current format version is not in the dictionary, no migrations will be run.
  30. */
  31. migrations?: ConfigMigrationsDict;
  32. }
  33. /**
  34. * Manages a user configuration that is cached in memory and persistently saved across sessions.
  35. * Supports migrating data from older versions of the configuration to newer ones and populating the cache with default data if no persistent data is found.
  36. *
  37. * ⚠️ Requires the directives `@grant GM.getValue` and `@grant GM.setValue`
  38. * ⚠️ Make sure to call {@linkcode loadData()} at least once after creating an instance, or the returned data will be the same as `options.defaultConfig`
  39. *
  40. * @template TData The type of the data that is saved in persistent storage (will be automatically inferred from `config.defaultConfig`) - this should also be the type of the data format associated with the current `options.formatVersion`
  41. */
  42. export class ConfigManager<TData = any> {
  43. public readonly id: string;
  44. public readonly formatVersion: number;
  45. public readonly defaultConfig: TData;
  46. private cachedConfig: TData;
  47. private migrations?: ConfigMigrationsDict;
  48. /**
  49. * Creates an instance of ConfigManager to manage a user configuration that is cached in memory and persistently saved across sessions.
  50. * Supports migrating data from older versions of the configuration to newer ones and populating the cache with default data if no persistent data is found.
  51. *
  52. * ⚠️ Requires the directives `@grant GM.getValue` and `@grant GM.setValue`
  53. * ⚠️ Make sure to call {@linkcode loadData()} at least once after creating an instance, or the returned data will be the same as `options.defaultConfig`
  54. *
  55. * @template TData The type of the data that is saved in persistent storage (will be automatically inferred from `config.defaultConfig`) - this should also be the type of the data format associated with the current `options.formatVersion`
  56. * @param options The options for this ConfigManager instance
  57. */
  58. constructor(options: ConfigManagerOptions<TData>) {
  59. this.id = options.id;
  60. this.formatVersion = options.formatVersion;
  61. this.defaultConfig = options.defaultConfig;
  62. this.cachedConfig = options.defaultConfig;
  63. this.migrations = options.migrations;
  64. }
  65. /**
  66. * Loads the data saved in persistent storage into the in-memory cache and also returns it.
  67. * Automatically populates persistent storage with default data if it doesn't contain any data yet.
  68. * Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
  69. */
  70. public async loadData(): Promise<TData> {
  71. try {
  72. const gmData = await GM.getValue(`_uucfg-${this.id}`, this.defaultConfig);
  73. let gmFmtVer = Number(await GM.getValue(`_uucfgver-${this.id}`));
  74. if(typeof gmData !== "string") {
  75. await this.saveDefaultData();
  76. return this.defaultConfig;
  77. }
  78. if(isNaN(gmFmtVer))
  79. await GM.setValue(`_uucfgver-${this.id}`, gmFmtVer = this.formatVersion);
  80. let parsed = JSON.parse(gmData);
  81. if(gmFmtVer < this.formatVersion && this.migrations)
  82. parsed = await this.runMigrations(parsed, gmFmtVer);
  83. return this.cachedConfig = typeof parsed === "object" ? parsed : undefined;
  84. }
  85. catch(err) {
  86. await this.saveDefaultData();
  87. return this.defaultConfig;
  88. }
  89. }
  90. /**
  91. * Returns a copy of the data from the in-memory cache.
  92. * Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
  93. */
  94. public getData(): TData {
  95. return this.deepCopy(this.cachedConfig);
  96. }
  97. /** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
  98. public setData(data: TData) {
  99. this.cachedConfig = data;
  100. return new Promise<void>(async (resolve) => {
  101. await Promise.all([
  102. GM.setValue(`_uucfg-${this.id}`, JSON.stringify(data)),
  103. GM.setValue(`_uucfgver-${this.id}`, this.formatVersion),
  104. ]);
  105. resolve();
  106. });
  107. }
  108. /** Saves the default configuration data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
  109. public async saveDefaultData() {
  110. this.cachedConfig = this.defaultConfig;
  111. return new Promise<void>(async (resolve) => {
  112. await Promise.all([
  113. GM.setValue(`_uucfg-${this.id}`, JSON.stringify(this.defaultConfig)),
  114. GM.setValue(`_uucfgver-${this.id}`, this.formatVersion),
  115. ]);
  116. resolve();
  117. });
  118. }
  119. /**
  120. * Call this method to clear all persistently stored data associated with this ConfigManager instance.
  121. * The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
  122. * Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
  123. *
  124. * ⚠️ This requires the additional directive `@grant GM.deleteValue`
  125. */
  126. public async deleteConfig() {
  127. await Promise.all([
  128. GM.deleteValue(`_uucfg-${this.id}`),
  129. GM.deleteValue(`_uucfgver-${this.id}`),
  130. ]);
  131. }
  132. /** Runs all necessary migration functions consecutively - may be overwritten in a subclass */
  133. protected async runMigrations(oldData: any, oldFmtVer: number): Promise<TData> {
  134. if(!this.migrations)
  135. return oldData as TData;
  136. let newData = oldData;
  137. const sortedMigrations = Object.entries(this.migrations)
  138. .sort(([a], [b]) => Number(a) - Number(b));
  139. let lastFmtVer = oldFmtVer;
  140. for(const [fmtVer, migrationFunc] of sortedMigrations) {
  141. const ver = Number(fmtVer);
  142. if(oldFmtVer < this.formatVersion && oldFmtVer < ver) {
  143. try {
  144. const migRes = migrationFunc(newData);
  145. newData = migRes instanceof Promise ? await migRes : migRes;
  146. lastFmtVer = oldFmtVer = ver;
  147. }
  148. catch(err) {
  149. console.error(`Error while running migration function for format version ${fmtVer}:`, err);
  150. }
  151. }
  152. }
  153. await Promise.all([
  154. GM.setValue(`_uucfg-${this.id}`, JSON.stringify(newData)),
  155. GM.setValue(`_uucfgver-${this.id}`, lastFmtVer),
  156. ]);
  157. return newData as TData;
  158. }
  159. /** Copies a JSON-compatible object and loses its internal references */
  160. private deepCopy<T>(obj: T): T {
  161. return JSON.parse(JSON.stringify(obj));
  162. }
  163. }