ConfigManager.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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 type 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. /**
  35. * Function to use to encode the data prior to saving it in persistent storage.
  36. * If this is specified, make sure to declare {@linkcode decodeData()} as well.
  37. *
  38. * You can make use of UserUtils' [`compress()`](https://github.com/Sv443-Network/UserUtils?tab=readme-ov-file#compress) function here to make the data use up less space at the cost of a little bit of performance.
  39. * @param data The input data as a serialized object (JSON string)
  40. */
  41. encodeData: (data: string) => string | Promise<string>,
  42. /**
  43. * Function to use to decode the data after reading it from persistent storage.
  44. * If this is specified, make sure to declare {@linkcode encodeData()} as well.
  45. *
  46. * You can make use of UserUtils' [`decompress()`](https://github.com/Sv443-Network/UserUtils?tab=readme-ov-file#decompress) function here to make the data use up less space at the cost of a little bit of performance.
  47. * @returns The resulting data as a valid serialized object (JSON string)
  48. */
  49. decodeData: (data: string) => string | Promise<string>,
  50. } | {
  51. encodeData?: never,
  52. decodeData?: never,
  53. });
  54. /**
  55. * Manages a user configuration that is cached in memory and persistently saved across sessions.
  56. * 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.
  57. *
  58. * ⚠️ Requires the directives `@grant GM.getValue` and `@grant GM.setValue`
  59. * ⚠️ Make sure to call {@linkcode loadData()} at least once after creating an instance, or the returned data will be the same as `options.defaultConfig`
  60. *
  61. * @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`
  62. */
  63. export class ConfigManager<TData = any> {
  64. public readonly id: string;
  65. public readonly formatVersion: number;
  66. public readonly defaultConfig: TData;
  67. private cachedConfig: TData;
  68. private migrations?: ConfigMigrationsDict;
  69. private encodeData: ConfigManagerOptions<TData>["encodeData"];
  70. private decodeData: ConfigManagerOptions<TData>["decodeData"];
  71. /**
  72. * Creates an instance of ConfigManager to manage a user configuration that is cached in memory and persistently saved across sessions.
  73. * 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.
  74. *
  75. * ⚠️ Requires the directives `@grant GM.getValue` and `@grant GM.setValue`
  76. * ⚠️ Make sure to call {@linkcode loadData()} at least once after creating an instance, or the returned data will be the same as `options.defaultConfig`
  77. *
  78. * @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`
  79. * @param options The options for this ConfigManager instance
  80. */
  81. constructor(options: ConfigManagerOptions<TData>) {
  82. this.id = options.id;
  83. this.formatVersion = options.formatVersion;
  84. this.defaultConfig = options.defaultConfig;
  85. this.cachedConfig = options.defaultConfig;
  86. this.migrations = options.migrations;
  87. this.encodeData = options.encodeData;
  88. this.decodeData = options.decodeData;
  89. }
  90. /**
  91. * Loads the data saved in persistent storage into the in-memory cache and also returns it.
  92. * Automatically populates persistent storage with default data if it doesn't contain any data yet.
  93. * Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
  94. */
  95. public async loadData(): Promise<TData> {
  96. try {
  97. const gmData = await GM.getValue(`_uucfg-${this.id}`, this.defaultConfig);
  98. let gmFmtVer = Number(await GM.getValue(`_uucfgver-${this.id}`));
  99. if(typeof gmData !== "string") {
  100. await this.saveDefaultData();
  101. return this.defaultConfig;
  102. }
  103. if(isNaN(gmFmtVer))
  104. await GM.setValue(`_uucfgver-${this.id}`, gmFmtVer = this.formatVersion);
  105. let parsed = await this.deserializeData(gmData);
  106. if(gmFmtVer < this.formatVersion && this.migrations)
  107. parsed = await this.runMigrations(parsed, gmFmtVer);
  108. return this.cachedConfig = parsed;
  109. }
  110. catch(err) {
  111. await this.saveDefaultData();
  112. return this.defaultConfig;
  113. }
  114. }
  115. /**
  116. * Returns a copy of the data from the in-memory cache.
  117. * Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
  118. */
  119. public getData(): TData {
  120. return this.deepCopy(this.cachedConfig);
  121. }
  122. /** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
  123. public setData(data: TData) {
  124. this.cachedConfig = data;
  125. return new Promise<void>(async (resolve) => {
  126. await Promise.all([
  127. GM.setValue(`_uucfg-${this.id}`, await this.serializeData(data)),
  128. GM.setValue(`_uucfgver-${this.id}`, this.formatVersion),
  129. ]);
  130. resolve();
  131. });
  132. }
  133. /** Saves the default configuration data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
  134. public async saveDefaultData() {
  135. this.cachedConfig = this.defaultConfig;
  136. return new Promise<void>(async (resolve) => {
  137. await Promise.all([
  138. GM.setValue(`_uucfg-${this.id}`, await this.serializeData(this.defaultConfig)),
  139. GM.setValue(`_uucfgver-${this.id}`, this.formatVersion),
  140. ]);
  141. resolve();
  142. });
  143. }
  144. /**
  145. * Call this method to clear all persistently stored data associated with this ConfigManager instance.
  146. * The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
  147. * Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
  148. *
  149. * ⚠️ This requires the additional directive `@grant GM.deleteValue`
  150. */
  151. public async deleteConfig() {
  152. await Promise.all([
  153. GM.deleteValue(`_uucfg-${this.id}`),
  154. GM.deleteValue(`_uucfgver-${this.id}`),
  155. ]);
  156. }
  157. /** Runs all necessary migration functions consecutively - may be overwritten in a subclass */
  158. protected async runMigrations(oldData: any, oldFmtVer: number): Promise<TData> {
  159. if(!this.migrations)
  160. return oldData as TData;
  161. let newData = oldData;
  162. const sortedMigrations = Object.entries(this.migrations)
  163. .sort(([a], [b]) => Number(a) - Number(b));
  164. let lastFmtVer = oldFmtVer;
  165. for(const [fmtVer, migrationFunc] of sortedMigrations) {
  166. const ver = Number(fmtVer);
  167. if(oldFmtVer < this.formatVersion && oldFmtVer < ver) {
  168. try {
  169. const migRes = migrationFunc(newData);
  170. newData = migRes instanceof Promise ? await migRes : migRes;
  171. lastFmtVer = oldFmtVer = ver;
  172. }
  173. catch(err) {
  174. console.error(`Error while running migration function for format version ${fmtVer}:`, err);
  175. }
  176. }
  177. }
  178. await Promise.all([
  179. GM.setValue(`_uucfg-${this.id}`, await this.serializeData(newData)),
  180. GM.setValue(`_uucfgver-${this.id}`, lastFmtVer),
  181. ]);
  182. return newData as TData;
  183. }
  184. /** Serializes the data using the optional this.encodeData() and returns it as a string */
  185. private async serializeData(data: TData) {
  186. const stringData = JSON.stringify(data);
  187. if(!this.encodeData)
  188. return stringData;
  189. const encRes = this.encodeData(stringData);
  190. if(encRes instanceof Promise)
  191. return await encRes;
  192. return encRes;
  193. }
  194. /** Deserializes the data using the optional this.decodeData() and returns it as a JSON object */
  195. private async deserializeData(data: string) {
  196. let decRes = this.decodeData ? this.decodeData(data) : undefined;
  197. if(decRes instanceof Promise)
  198. decRes = await decRes;
  199. return JSON.parse(decRes ?? data) as TData;
  200. }
  201. /** Copies a JSON-compatible object and loses its internal references */
  202. private deepCopy<T>(obj: T): T {
  203. return JSON.parse(JSON.stringify(obj));
  204. }
  205. }