interface.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. import * as UserUtils from "@sv443-network/userutils";
  2. import { mode, branch, host, buildNumber, compressionFormat, scriptInfo } from "./constants";
  3. import { getResourceUrl, getSessionId, getVideoTime, log, setLocale, getLocale, hasKey, hasKeyFor, NanoEmitter, t, tp, type TrLocale, info, error } from "./utils";
  4. import { addSelectorListener } from "./observers";
  5. import { getFeatures, setFeatures } from "./config";
  6. import { featInfo, fetchLyricsUrlTop, getLyricsCacheEntry, sanitizeArtists, sanitizeSong, type LyricsCache } from "./features";
  7. import { allSiteEvents, siteEvents, type SiteEventsMap } from "./siteEvents";
  8. import { LogLevel, type FeatureConfig, type FeatureInfo, type LyricsCacheEntry, type PluginDef, type PluginInfo, type PluginRegisterResult, type PluginDefResolvable, type PluginEventMap, type PluginItem } from "./types";
  9. import { BytmDialog, createHotkeyInput, createToggleInput } from "./components";
  10. import { createNanoEvents } from "nanoevents";
  11. const { getUnsafeWindow } = UserUtils;
  12. /** All events that can be emitted on the BYTM interface and the data they provide */
  13. export type InterfaceEvents = {
  14. /** Emitted whenever the plugins should be registered using `unsafeWindow.BYTM.registerPlugin()` */
  15. "bytm:initPlugins": undefined;
  16. /** Emitted whenever all plugins have been loaded */
  17. "bytm:pluginsLoaded": undefined;
  18. /** Emitted when BYTM has finished initializing all features */
  19. "bytm:ready": undefined;
  20. /**
  21. * Emitted whenever the SelectorObserver instances have been initialized
  22. * Use `unsafeWindow.BYTM.addObserverListener()` to add custom listener functions to the observers
  23. */
  24. "bytm:observersReady": undefined;
  25. /** Emitted as soon as the feature config has been loaded */
  26. "bytm:configReady": FeatureConfig;
  27. /** Emitted whenever the locale is changed */
  28. "bytm:setLocale": { locale: TrLocale };
  29. /** Emitted when a dialog was opened - returns the dialog's instance */
  30. "bytm:dialogOpened": BytmDialog;
  31. /** Emitted when the dialog with the specified ID was opened - returns the dialog's instance - use `as "bytm:dialogOpened:id"` in TS to make the error go away */
  32. "bytm:dialogOpened:id": BytmDialog;
  33. /** Emitted whenever the lyrics URL for a song is loaded */
  34. "bytm:lyricsLoaded": { type: "current" | "queue", artists: string, title: string, url: string };
  35. /** Emitted when the lyrics cache has been loaded */
  36. "bytm:lyricsCacheReady": LyricsCache;
  37. /** Emitted when the lyrics cache has been cleared */
  38. "bytm:lyricsCacheCleared": undefined;
  39. /** Emitted when an entry is added to the lyrics cache - "penalized" entries have a lower TTL because they were less related in lyrics lookups, as opposed to the "best" entries */
  40. "bytm:lyricsCacheEntryAdded": { type: "best" | "penalized", entry: LyricsCacheEntry };
  41. // additionally all events from SiteEventsMap in `src/siteEvents.ts`
  42. // are emitted in this format: "bytm:siteEvent:nameOfSiteEvent"
  43. };
  44. const globalFuncs = {
  45. // meta
  46. registerPlugin,
  47. getPluginInfo,
  48. // utils
  49. addSelectorListener,
  50. getResourceUrl,
  51. getSessionId,
  52. getVideoTime,
  53. setLocale,
  54. getLocale,
  55. hasKey,
  56. hasKeyFor,
  57. t,
  58. tp,
  59. getFeatures: getFeaturesInterface,
  60. saveFeatures: setFeatures,
  61. fetchLyricsUrlTop,
  62. getLyricsCacheEntry,
  63. sanitizeArtists,
  64. sanitizeSong,
  65. };
  66. /** Plugins that are queued up for registration */
  67. const pluginQueue = new Map<string, PluginItem>();
  68. /** Registered plugins including their event listener instance */
  69. const pluginMap = new Map<string, PluginItem>();
  70. /** Initializes the BYTM interface */
  71. export function initInterface() {
  72. const props = {
  73. mode,
  74. branch,
  75. host,
  76. buildNumber,
  77. compressionFormat,
  78. ...scriptInfo,
  79. ...globalFuncs,
  80. UserUtils,
  81. NanoEmitter,
  82. BytmDialog,
  83. createHotkeyInput,
  84. createToggleInput,
  85. };
  86. for(const [key, value] of Object.entries(props))
  87. setGlobalProp(key, value);
  88. log("Initialized BYTM interface");
  89. }
  90. /** Sets a global property on the unsafeWindow.BYTM object */
  91. export function setGlobalProp<
  92. TKey extends keyof Window["BYTM"],
  93. TValue = Window["BYTM"][TKey],
  94. > (
  95. key: TKey | (string & {}),
  96. value: TValue,
  97. ) {
  98. // use unsafeWindow so the properties are available to plugins outside of the userscript's scope
  99. const win = getUnsafeWindow();
  100. if(typeof win.BYTM !== "object")
  101. win.BYTM = {} as typeof window.BYTM;
  102. win.BYTM[key] = value;
  103. }
  104. /** Emits an event on the BYTM interface */
  105. export function emitInterface<
  106. TEvt extends keyof InterfaceEvents,
  107. TDetail extends InterfaceEvents[TEvt],
  108. >(
  109. type: TEvt | `bytm:siteEvent:${keyof SiteEventsMap}`,
  110. ...data: (TDetail extends undefined ? [undefined?] : [TDetail])
  111. ) {
  112. getUnsafeWindow().dispatchEvent(new CustomEvent(type, { detail: data[0] }));
  113. }
  114. //#MARKER register plugins
  115. /** Initializes plugins that have been registered already. Needs to be run after `bytm:ready`! */
  116. export function initPlugins() {
  117. // TODO(v1.3): check perms and ask user for initial activation
  118. for(const [key, { def, events }] of pluginQueue) {
  119. pluginMap.set(key, { def, events });
  120. pluginQueue.delete(key);
  121. emitOnPlugins("pluginRegistered", (d) => sameDef(d, def), pluginDefToInfo(def)!);
  122. }
  123. for(const evt of allSiteEvents) // @ts-ignore
  124. siteEvents.on(evt, (...args) => emitOnPlugins(evt, () => true, ...args));
  125. emitInterface("bytm:pluginsLoaded");
  126. }
  127. /** Returns the key for a given plugin definition */
  128. function getPluginKey(plugin: PluginDefResolvable) {
  129. return `${plugin.plugin.namespace}/${plugin.plugin.name}`;
  130. }
  131. /** Converts a PluginDef object (full definition) into a PluginInfo object (restricted definition) or undefined, if undefined is passed */
  132. function pluginDefToInfo(plugin?: PluginDef): PluginInfo | undefined {
  133. return plugin && {
  134. name: plugin.plugin.name,
  135. namespace: plugin.plugin.namespace,
  136. version: plugin.plugin.version,
  137. };
  138. }
  139. /** Checks whether two plugin definitions are the same */
  140. function sameDef(def1: PluginDefResolvable, def2: PluginDefResolvable) {
  141. return getPluginKey(def1) === getPluginKey(def2);
  142. }
  143. /** Emits an event on all plugins that match the predicate (all plugins by default) */
  144. export function emitOnPlugins<TEvtKey extends keyof PluginEventMap>(
  145. event: TEvtKey,
  146. predicate: (def: PluginDef) => boolean = () => true,
  147. ...data: Parameters<PluginEventMap[TEvtKey]>
  148. ) {
  149. for(const { def, events } of pluginMap.values())
  150. predicate(def) && events.emit(event, ...data);
  151. }
  152. /** Returns the internal plugin object by its name and namespace, or undefined if it doesn't exist */
  153. export function getPlugin(name: string, namespace: string): PluginItem | undefined
  154. /** Returns the internal plugin object by its definition, or undefined if it doesn't exist */
  155. export function getPlugin(plugin: PluginDefResolvable): PluginItem | undefined
  156. /** Returns the internal plugin object, or undefined if it doesn't exist */
  157. export function getPlugin(...args: [pluginDefOrName: PluginDefResolvable | string, namespace?: string]): PluginItem | undefined {
  158. return args.length === 2
  159. ? pluginMap.get(`${args[1]}/${args[0]}`)
  160. : pluginMap.get(getPluginKey(args[0] as PluginDefResolvable));
  161. }
  162. /** Returns info about a registered plugin on the BYTM interface by its name and namespace properties, or undefined if the plugin isn't registered */
  163. export function getPluginInfo(name: string, namespace: string): PluginInfo | undefined
  164. /** Returns info about a registered plugin on the BYTM interface, or undefined if the plugin isn't registered */
  165. export function getPluginInfo(plugin: PluginDefResolvable): PluginInfo | undefined
  166. /** Returns info about a registered plugin on the BYTM interface, or undefined if the plugin isn't registered */
  167. export function getPluginInfo(...args: [pluginDefOrName: PluginDefResolvable | string, namespace?: string]): PluginInfo | undefined {
  168. return pluginDefToInfo(
  169. args.length === 2
  170. ? pluginMap.get(`${args[1]}/${args[0]}`)?.def
  171. : pluginMap.get(getPluginKey(args[0] as PluginDefResolvable))?.def
  172. );
  173. }
  174. /** Validates the passed PluginDef object and returns an array of errors */
  175. function validatePluginDef(pluginDef: Partial<PluginDef>) {
  176. const errors = [] as string[];
  177. const addNoPropErr = (prop: string, type: string) =>
  178. errors.push(t("plugin_validation_error_no_property", prop, type));
  179. // def.plugin and its properties:
  180. typeof pluginDef.plugin !== "object" && addNoPropErr("plugin", "object");
  181. const { plugin } = pluginDef;
  182. !plugin?.name && addNoPropErr("plugin.name", "string");
  183. !plugin?.namespace && addNoPropErr("plugin.namespace", "string");
  184. !plugin?.version && addNoPropErr("plugin.version", "[major: number, minor: number, patch: number]");
  185. return errors.length > 0 ? errors : undefined;
  186. }
  187. /** Registers a plugin on the BYTM interface */
  188. export function registerPlugin(def: PluginDef): PluginRegisterResult {
  189. const validationErrors = validatePluginDef(def);
  190. if(validationErrors) {
  191. error(`Failed to register plugin${def?.plugin?.name ? ` '${def?.plugin?.name}'` : ""} with invalid definition:\n- ${validationErrors.join("\n- ")}`, LogLevel.Info);
  192. throw new Error(`Invalid plugin definition:\n- ${validationErrors.join("\n- ")}`);
  193. }
  194. const events = createNanoEvents<PluginEventMap>();
  195. const { plugin: { name } } = def;
  196. pluginQueue.set(getPluginKey(def), {
  197. def: def,
  198. events,
  199. });
  200. info(`Registered plugin: ${name}`, LogLevel.Info);
  201. return {
  202. info: getPluginInfo(def)!,
  203. events,
  204. };
  205. }
  206. //#MARKER proxy functions
  207. /** Returns the current feature config, with sensitive values replaced by `undefined` */
  208. export function getFeaturesInterface() {
  209. const features = getFeatures();
  210. for(const ftKey of Object.keys(features)) {
  211. const info = featInfo[ftKey as keyof typeof featInfo] as FeatureInfo[keyof FeatureInfo];
  212. if(info && info.valueHidden) // @ts-ignore
  213. features[ftKey as keyof typeof features] = undefined;
  214. }
  215. return features as FeatureConfig;
  216. }