DataStore.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2. //#region types
  3. /** Function that takes the data in the old format and returns the data in the new format. Also supports an asynchronous migration. */
  4. type MigrationFunc = (oldData: any) => any | Promise<any>;
  5. /** Dictionary of format version numbers and the function that migrates to them from the previous whole integer */
  6. export type DataMigrationsDict = Record<number, MigrationFunc>;
  7. /** Options for the DataStore instance */
  8. export type DataStoreOptions<TData> =
  9. & {
  10. /**
  11. * A unique internal ID for this data store.
  12. * To avoid conflicts with other scripts, it is recommended to use a prefix that is unique to your script.
  13. * If you want to change the ID, you should make use of the {@linkcode DataStore.migrateId()} method.
  14. */
  15. id: string;
  16. /**
  17. * The default data object to use if no data is saved in persistent storage yet.
  18. * Until the data is loaded from persistent storage with {@linkcode DataStore.loadData()}, this will be the data returned by {@linkcode DataStore.getData()}.
  19. *
  20. * ⚠️ This has to be an object that can be serialized to JSON using `JSON.stringify()`, so no functions or circular references are allowed, they will cause unexpected behavior.
  21. */
  22. defaultData: TData;
  23. /**
  24. * An incremental, whole integer version number of the current format of data.
  25. * 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.
  26. *
  27. * ⚠️ Never decrement this number and optimally don't skip any numbers either!
  28. */
  29. formatVersion: number;
  30. /**
  31. * A dictionary of functions that can be used to migrate data from older versions to newer ones.
  32. * The keys of the dictionary should be the format version that the functions can migrate to, from the previous whole integer value.
  33. * The values should be functions that take the data in the old format and return the data in the new format.
  34. * The functions will be run in order from the oldest to the newest version.
  35. * If the current format version is not in the dictionary, no migrations will be run.
  36. */
  37. migrations?: DataMigrationsDict;
  38. /**
  39. * If an ID or multiple IDs are passed here, the data will be migrated from the old ID(s) to the current ID.
  40. * This will happen once per page load, when {@linkcode DataStore.loadData()} is called.
  41. * All future calls to {@linkcode DataStore.loadData()} in the session will not check for the old ID(s) anymore.
  42. * To migrate IDs manually, use the method {@linkcode DataStore.migrateId()} instead.
  43. */
  44. migrateIds?: string | string[];
  45. /**
  46. * Where the data should be saved (`"GM"` by default).
  47. * The protected methods {@linkcode DataStore.getValue()}, {@linkcode DataStore.setValue()} and {@linkcode DataStore.deleteValue()} are used to interact with the storage.
  48. * `"GM"` storage, `"localStorage"` and `"sessionStorage"` are supported out of the box, but in an extended class you can overwrite those methods to implement any other storage method.
  49. */
  50. storageMethod?: "GM" | "localStorage" | "sessionStorage";
  51. }
  52. & (
  53. | {
  54. /**
  55. * Function to use to encode the data prior to saving it in persistent storage.
  56. * If this is specified, make sure to declare {@linkcode decodeData()} as well.
  57. *
  58. * 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.
  59. * @param data The input data as a serialized object (JSON string)
  60. */
  61. encodeData: (data: string) => string | Promise<string>,
  62. /**
  63. * Function to use to decode the data after reading it from persistent storage.
  64. * If this is specified, make sure to declare {@linkcode encodeData()} as well.
  65. *
  66. * 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.
  67. * @returns The resulting data as a valid serialized object (JSON string)
  68. */
  69. decodeData: (data: string) => string | Promise<string>,
  70. }
  71. | {
  72. encodeData?: never,
  73. decodeData?: never,
  74. }
  75. );
  76. //#region class
  77. /**
  78. * Manages a hybrid synchronous & asynchronous persistent JSON database that is cached in memory and persistently saved across sessions using [GM storage](https://wiki.greasespot.net/GM.setValue) (default), [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) or [sessionStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage).
  79. * Supports migrating data from older format versions to newer ones and populating the cache with default data if no persistent data is found.
  80. * Can be overridden to implement any other storage method.
  81. *
  82. * All methods are at least `protected`, so you can easily extend this class and overwrite them to use a different storage method or to add additional functionality.
  83. * Remember that you can call `super.methodName()` in the subclass to access the original method.
  84. *
  85. * ⚠️ The stored data has to be **serializable using `JSON.stringify()`**, meaning no undefined, circular references, etc. are allowed.
  86. * ⚠️ If the storageMethod is left as the default of `"GM"` the directives `@grant GM.getValue` and `@grant GM.setValue` are required. If you then also use the method {@linkcode DataStore.deleteData()}, the extra directive `@grant GM.deleteValue` is needed too.
  87. * ⚠️ Make sure to call {@linkcode loadData()} at least once after creating an instance, or the returned data will be the same as `options.defaultData`
  88. *
  89. * @template TData The type of the data that is saved in persistent storage for the currently set format version (will be automatically inferred from `defaultData` if not provided)
  90. */
  91. export class DataStore<TData extends object = object> {
  92. public readonly id: string;
  93. public readonly formatVersion: number;
  94. public readonly defaultData: TData;
  95. public readonly encodeData: DataStoreOptions<TData>["encodeData"];
  96. public readonly decodeData: DataStoreOptions<TData>["decodeData"];
  97. public readonly storageMethod: Required<DataStoreOptions<TData>>["storageMethod"];
  98. private cachedData: TData;
  99. private migrations?: DataMigrationsDict;
  100. private migrateIds: string[] = [];
  101. /**
  102. * Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
  103. * Supports migrating data from older versions to newer ones and populating the cache with default data if no persistent data is found.
  104. *
  105. * ⚠️ Requires the directives `@grant GM.getValue` and `@grant GM.setValue` if the storageMethod is left as the default of `"GM"`
  106. * ⚠️ Make sure to call {@linkcode loadData()} at least once after creating an instance, or the returned data will be the same as `options.defaultData`
  107. *
  108. * @template TData The type of the data that is saved in persistent storage for the currently set format version (will be automatically inferred from `defaultData` if not provided) - **This has to be a JSON-compatible object!** (no undefined, circular references, etc.)
  109. * @param options The options for this DataStore instance
  110. */
  111. constructor(options: DataStoreOptions<TData>) {
  112. this.id = options.id;
  113. this.formatVersion = options.formatVersion;
  114. this.defaultData = options.defaultData;
  115. this.cachedData = options.defaultData;
  116. this.migrations = options.migrations;
  117. if(options.migrateIds)
  118. this.migrateIds = Array.isArray(options.migrateIds) ? options.migrateIds : [options.migrateIds];
  119. this.storageMethod = options.storageMethod ?? "GM";
  120. this.encodeData = options.encodeData;
  121. this.decodeData = options.decodeData;
  122. }
  123. //#region public
  124. /**
  125. * Loads the data saved in persistent storage into the in-memory cache and also returns it.
  126. * Automatically populates persistent storage with default data if it doesn't contain any data yet.
  127. * Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
  128. */
  129. public async loadData(): Promise<TData> {
  130. try {
  131. if(this.migrateIds.length > 0) {
  132. await this.migrateId(this.migrateIds);
  133. this.migrateIds = [];
  134. }
  135. const gmData = await this.getValue(`_uucfg-${this.id}`, JSON.stringify(this.defaultData));
  136. let gmFmtVer = Number(await this.getValue(`_uucfgver-${this.id}`, NaN));
  137. if(typeof gmData !== "string") {
  138. await this.saveDefaultData();
  139. return { ...this.defaultData };
  140. }
  141. const isEncoded = Boolean(await this.getValue(`_uucfgenc-${this.id}`, false));
  142. let saveData = false;
  143. if(isNaN(gmFmtVer)) {
  144. await this.setValue(`_uucfgver-${this.id}`, gmFmtVer = this.formatVersion);
  145. saveData = true;
  146. }
  147. let parsed = await this.deserializeData(gmData, isEncoded);
  148. if(gmFmtVer < this.formatVersion && this.migrations)
  149. parsed = await this.runMigrations(parsed, gmFmtVer);
  150. if(saveData)
  151. await this.setData(parsed);
  152. this.cachedData = { ...parsed };
  153. return this.cachedData;
  154. }
  155. catch(err) {
  156. console.warn("Error while parsing JSON data, resetting it to the default value.", err);
  157. await this.saveDefaultData();
  158. return this.defaultData;
  159. }
  160. }
  161. /**
  162. * Returns a copy of the data from the in-memory cache.
  163. * Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
  164. * @param deepCopy Whether to return a deep copy of the data (default: `false`) - only necessary if your data object is nested and may have a bigger performance impact if enabled
  165. */
  166. public getData(deepCopy = false): TData {
  167. return deepCopy
  168. ? this.deepCopy(this.cachedData)
  169. : { ...this.cachedData };
  170. }
  171. /** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
  172. public setData(data: TData): Promise<void> {
  173. this.cachedData = data;
  174. const useEncoding = this.encodingEnabled();
  175. return new Promise<void>(async (resolve) => {
  176. await Promise.all([
  177. this.setValue(`_uucfg-${this.id}`, await this.serializeData(data, useEncoding)),
  178. this.setValue(`_uucfgver-${this.id}`, this.formatVersion),
  179. this.setValue(`_uucfgenc-${this.id}`, useEncoding),
  180. ]);
  181. resolve();
  182. });
  183. }
  184. /** Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
  185. public async saveDefaultData(): Promise<void> {
  186. this.cachedData = this.defaultData;
  187. const useEncoding = this.encodingEnabled();
  188. return new Promise<void>(async (resolve) => {
  189. await Promise.all([
  190. this.setValue(`_uucfg-${this.id}`, await this.serializeData(this.defaultData, useEncoding)),
  191. this.setValue(`_uucfgver-${this.id}`, this.formatVersion),
  192. this.setValue(`_uucfgenc-${this.id}`, useEncoding),
  193. ]);
  194. resolve();
  195. });
  196. }
  197. /**
  198. * Call this method to clear all persistently stored data associated with this DataStore instance.
  199. * The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
  200. * Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
  201. *
  202. * ⚠️ This requires the additional directive `@grant GM.deleteValue` if the storageMethod is left as the default of `"GM"`
  203. */
  204. public async deleteData(): Promise<void> {
  205. await Promise.all([
  206. this.deleteValue(`_uucfg-${this.id}`),
  207. this.deleteValue(`_uucfgver-${this.id}`),
  208. this.deleteValue(`_uucfgenc-${this.id}`),
  209. ]);
  210. }
  211. /** Returns whether encoding and decoding are enabled for this DataStore instance */
  212. public encodingEnabled(): this is Required<Pick<DataStoreOptions<TData>, "encodeData" | "decodeData">> {
  213. return Boolean(this.encodeData && this.decodeData);
  214. }
  215. //#region migrations
  216. /**
  217. * Runs all necessary migration functions consecutively and saves the result to the in-memory cache and persistent storage and also returns it.
  218. * This method is automatically called by {@linkcode loadData()} if the data format has changed since the last time the data was saved.
  219. * Though calling this method manually is not necessary, it can be useful if you want to run migrations for special occasions like a user importing potentially outdated data that has been previously exported.
  220. *
  221. * If one of the migrations fails, the data will be reset to the default value if `resetOnError` is set to `true` (default). Otherwise, an error will be thrown and no data will be saved.
  222. */
  223. public async runMigrations(oldData: any, oldFmtVer: number, resetOnError = true): Promise<TData> {
  224. if(!this.migrations)
  225. return oldData as TData;
  226. let newData = oldData;
  227. const sortedMigrations = Object.entries(this.migrations)
  228. .sort(([a], [b]) => Number(a) - Number(b));
  229. let lastFmtVer = oldFmtVer;
  230. for(const [fmtVer, migrationFunc] of sortedMigrations) {
  231. const ver = Number(fmtVer);
  232. if(oldFmtVer < this.formatVersion && oldFmtVer < ver) {
  233. try {
  234. const migRes = migrationFunc(newData);
  235. newData = migRes instanceof Promise ? await migRes : migRes;
  236. lastFmtVer = oldFmtVer = ver;
  237. }
  238. catch(err) {
  239. if(!resetOnError)
  240. throw new Error(`Error while running migration function for format version '${fmtVer}'`);
  241. console.error(`Error while running migration function for format version '${fmtVer}' - resetting to the default value.`, err);
  242. await this.saveDefaultData();
  243. return this.getData();
  244. }
  245. }
  246. }
  247. await Promise.all([
  248. this.setValue(`_uucfg-${this.id}`, await this.serializeData(newData)),
  249. this.setValue(`_uucfgver-${this.id}`, lastFmtVer),
  250. this.setValue(`_uucfgenc-${this.id}`, this.encodingEnabled()),
  251. ]);
  252. return this.cachedData = { ...newData as TData };
  253. }
  254. /**
  255. * Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
  256. * If no data exist for the old ID(s), nothing will be done, but some time may still pass trying to fetch the non-existent data.
  257. */
  258. public async migrateId(oldIds: string | string[]): Promise<void> {
  259. const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
  260. await Promise.all(ids.map(async id => {
  261. const data = await this.getValue(`_uucfg-${id}`, JSON.stringify(this.defaultData));
  262. const fmtVer = Number(await this.getValue(`_uucfgver-${id}`, NaN));
  263. const isEncoded = Boolean(await this.getValue(`_uucfgenc-${id}`, false));
  264. if(data === undefined || isNaN(fmtVer))
  265. return;
  266. const parsed = await this.deserializeData(data, isEncoded);
  267. await Promise.allSettled([
  268. this.setValue(`_uucfg-${this.id}`, await this.serializeData(parsed)),
  269. this.setValue(`_uucfgver-${this.id}`, fmtVer),
  270. this.setValue(`_uucfgenc-${this.id}`, isEncoded),
  271. this.deleteValue(`_uucfg-${id}`),
  272. this.deleteValue(`_uucfgver-${id}`),
  273. this.deleteValue(`_uucfgenc-${id}`),
  274. ]);
  275. }));
  276. }
  277. //#region serialization
  278. /** Serializes the data using the optional this.encodeData() and returns it as a string */
  279. protected async serializeData(data: TData, useEncoding = true): Promise<string> {
  280. const stringData = JSON.stringify(data);
  281. if(!this.encodingEnabled() || !useEncoding)
  282. return stringData;
  283. const encRes = this.encodeData(stringData);
  284. if(encRes instanceof Promise)
  285. return await encRes;
  286. return encRes;
  287. }
  288. /** Deserializes the data using the optional this.decodeData() and returns it as a JSON object */
  289. protected async deserializeData(data: string, useEncoding = true): Promise<TData> {
  290. let decRes = this.encodingEnabled() && useEncoding ? this.decodeData(data) : undefined;
  291. if(decRes instanceof Promise)
  292. decRes = await decRes;
  293. return JSON.parse(decRes ?? data) as TData;
  294. }
  295. //#region misc
  296. /** Copies a JSON-compatible object and loses all its internal references in the process */
  297. protected deepCopy<T>(obj: T): T {
  298. return JSON.parse(JSON.stringify(obj));
  299. }
  300. //#region storage
  301. /** Gets a value from persistent storage - can be overwritten in a subclass if you want to use something other than GM storage */
  302. protected async getValue<TValue extends GM.Value = string>(name: string, defaultValue: TValue): Promise<string | TValue> {
  303. switch(this.storageMethod) {
  304. case "localStorage":
  305. return localStorage.getItem(name) as TValue ?? defaultValue;
  306. case "sessionStorage":
  307. return sessionStorage.getItem(name) as string ?? defaultValue;
  308. default:
  309. return GM.getValue<TValue>(name, defaultValue);
  310. }
  311. }
  312. /**
  313. * Sets a value in persistent storage - can be overwritten in a subclass if you want to use something other than GM storage.
  314. * The default storage engines will stringify all passed values like numbers or booleans, so be aware of that.
  315. */
  316. protected async setValue(name: string, value: GM.Value): Promise<void> {
  317. switch(this.storageMethod) {
  318. case "localStorage":
  319. return localStorage.setItem(name, String(value));
  320. case "sessionStorage":
  321. return sessionStorage.setItem(name, String(value));
  322. default:
  323. return GM.setValue(name, String(value));
  324. }
  325. }
  326. /** Deletes a value from persistent storage - can be overwritten in a subclass if you want to use something other than GM storage */
  327. protected async deleteValue(name: string): Promise<void> {
  328. switch(this.storageMethod) {
  329. case "localStorage":
  330. return localStorage.removeItem(name);
  331. case "sessionStorage":
  332. return sessionStorage.removeItem(name);
  333. default:
  334. return GM.deleteValue(name);
  335. }
  336. }
  337. }