1
0

config.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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 `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 `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. /** Returns a copy of the data from the in-memory cache. Use `loadData()` to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage). */
  91. public getData(): TData {
  92. return this.deepCopy(this.cachedConfig);
  93. }
  94. /** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
  95. public setData(data: TData) {
  96. this.cachedConfig = data;
  97. return new Promise<void>(async (resolve) => {
  98. await Promise.all([
  99. GM.setValue(`_uucfg-${this.id}`, JSON.stringify(data)),
  100. GM.setValue(`_uucfgver-${this.id}`, this.formatVersion),
  101. ]);
  102. resolve();
  103. });
  104. }
  105. /** Saves the default configuration data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
  106. public async saveDefaultData() {
  107. this.cachedConfig = this.defaultConfig;
  108. return new Promise<void>(async (resolve) => {
  109. await Promise.all([
  110. GM.setValue(`_uucfg-${this.id}`, JSON.stringify(this.defaultConfig)),
  111. GM.setValue(`_uucfgver-${this.id}`, this.formatVersion),
  112. ]);
  113. resolve();
  114. });
  115. }
  116. /**
  117. * Call this method to clear all persistently stored data associated with this ConfigManager instance.
  118. * The in-memory cache will be left untouched, so you may still access the data with `getData()`.
  119. * Calling `loadData()` or `setData()` after this method was called will recreate persistent storage with the cached or default data.
  120. *
  121. * ⚠️ This requires the additional directive `@grant GM.deleteValue`
  122. */
  123. public async deleteConfig() {
  124. await Promise.all([
  125. GM.deleteValue(`_uucfg-${this.id}`),
  126. GM.deleteValue(`_uucfgver-${this.id}`),
  127. ]);
  128. }
  129. /** Runs all necessary migration functions consecutively - may be overwritten in a subclass */
  130. protected async runMigrations(oldData: any, oldFmtVer: number): Promise<TData> {
  131. if(!this.migrations)
  132. return oldData as TData;
  133. let newData = oldData;
  134. const sortedMigrations = Object.entries(this.migrations)
  135. .sort(([a], [b]) => Number(a) - Number(b));
  136. let lastFmtVer = oldFmtVer;
  137. for(const [fmtVer, migrationFunc] of sortedMigrations) {
  138. const ver = Number(fmtVer);
  139. if(oldFmtVer < this.formatVersion && oldFmtVer < ver) {
  140. try {
  141. const migRes = migrationFunc(newData);
  142. newData = migRes instanceof Promise ? await migRes : migRes;
  143. lastFmtVer = oldFmtVer = ver;
  144. }
  145. catch(err) {
  146. console.error(`Error while running migration function for format version ${fmtVer}:`, err);
  147. }
  148. }
  149. }
  150. await Promise.all([
  151. GM.setValue(`_uucfg-${this.id}`, JSON.stringify(newData)),
  152. GM.setValue(`_uucfgver-${this.id}`, lastFmtVer),
  153. ]);
  154. return newData as TData;
  155. }
  156. /** Copies a JSON-compatible object and loses its internal references */
  157. private deepCopy<T>(obj: T): T {
  158. return JSON.parse(JSON.stringify(obj));
  159. }
  160. }