types.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. import type { Emitter } from "nanoevents";
  2. import type * as consts from "./constants";
  3. import type { scriptInfo } from "./constants";
  4. import type { addSelectorListener } from "./observers";
  5. import type resources from "../assets/resources.json";
  6. import type locales from "../assets/locales.json";
  7. import type { getResourceUrl, getSessionId, getVideoTime, TrLocale, t, tp } from "./utils";
  8. import type { getFeatures, setFeatures } from "./config";
  9. import type { SiteEventsMap } from "./siteEvents";
  10. import type { InterfaceEventsMap } from "./interface";
  11. /** Custom CLI args passed to rollup */
  12. export type RollupArgs = Partial<{
  13. "config-mode": "development" | "production";
  14. "config-branch": "main" | "develop";
  15. "config-host": "greasyfork" | "github" | "openuserjs";
  16. "config-assetSource": "local" | "github";
  17. "config-suffix": string;
  18. }>;
  19. // I know TS enums are impure but it doesn't really matter here, plus they look cooler
  20. export enum LogLevel {
  21. Debug,
  22. Info,
  23. }
  24. /** Which domain this script is currently running on */
  25. export type Domain = "yt" | "ytm";
  26. /** A selection option between one of the supported domains, or all of them */
  27. export type SiteSelection = Domain | "all";
  28. /** A selection option between one of the supported domains, or none of them */
  29. export type SiteSelectionOrNone = SiteSelection | "none";
  30. /** Key of a resource in `assets/resources.json` and extra keys defined by `tools/post-build.ts` */
  31. export type ResourceKey = keyof typeof resources | `trans-${keyof typeof locales}` | "changelog" | "css-bundle";
  32. /** Describes a single hotkey */
  33. export type HotkeyObj = {
  34. code: string,
  35. shift: boolean,
  36. ctrl: boolean,
  37. alt: boolean,
  38. };
  39. export type LyricsCacheEntry = {
  40. artist: string;
  41. song: string;
  42. url: string;
  43. viewed: number;
  44. added: number;
  45. };
  46. //#region global
  47. // shim for the BYTM interface properties
  48. export type BytmObject =
  49. {
  50. [key: string]: unknown;
  51. locale: TrLocale;
  52. logLevel: LogLevel;
  53. }
  54. // information from the userscript header
  55. & typeof scriptInfo
  56. // certain variables from `src/constants.ts`
  57. & Pick<typeof consts, "mode" | "branch" | "host" | "buildNumber" | "compressionFormat">
  58. // global functions exposed through the interface in `src/interface.ts`
  59. & InterfaceFunctions
  60. // others
  61. & {
  62. // the entire UserUtils library
  63. UserUtils: typeof import("@sv443-network/userutils");
  64. };
  65. declare global {
  66. interface Window {
  67. // to see the expanded type, install the VS Code extension "MylesMurphy.prettify-ts" and hover over the property below
  68. // alternatively navigate with ctrl+click to find the types
  69. BYTM: BytmObject;
  70. }
  71. }
  72. //#region plugins
  73. /**
  74. * Intents (permissions) BYTM has to grant your plugin for it to be able to access certain features.
  75. * TODO: this feature is unfinished, but you should still specify the intents your plugin needs.
  76. * Never request more permissions than you need, as this is a bad practice and can lead to your plugin being rejected.
  77. */
  78. export enum PluginIntent {
  79. /** Plugin has access to hidden config values */
  80. HiddenConfigValues = 1,
  81. /** Plugin can write to the feature configuration */
  82. WriteFeatureConfig = 2,
  83. /** Plugin can write to the lyrics cache */
  84. WriteLyricsCache = 4,
  85. /** Plugin can add new translations and overwrite existing ones */
  86. WriteTranslations = 8,
  87. /** Plugin can create modal dialogs */
  88. CreateModalDialogs = 16,
  89. }
  90. /** Result of a plugin registration */
  91. export type PluginRegisterResult = {
  92. /** Public info about the registered plugin */
  93. info: PluginInfo;
  94. /** Emitter for plugin events - see {@linkcode PluginEventMap} for a list of events */
  95. events: Emitter<PluginEventMap>;
  96. /** Authentication token for the plugin to use in certain restricted function calls */
  97. token: string;
  98. }
  99. /** Minimal object that describes a plugin - this is all info the other installed plugins can see */
  100. export type PluginInfo = {
  101. /** Name of the plugin */
  102. name: string;
  103. /**
  104. * Adding the namespace and the name property makes the unique identifier for a plugin.
  105. * If one exists with the same name and namespace as this plugin, it may be overwritten at registration.
  106. * I recommend to set this value to a URL pointing to your homepage, or the author's username.
  107. */
  108. namespace: string;
  109. /** Version of the plugin as a semver-compliant string */
  110. version: string;
  111. };
  112. /** Minimum part of the PluginDef object needed to make up the resolvable plugin identifier */
  113. export type PluginDefResolvable = PluginDef | { plugin: Pick<PluginDef["plugin"], "name" | "namespace"> };
  114. /** An object that describes a BYTM plugin */
  115. export type PluginDef = {
  116. plugin: PluginInfo & {
  117. /**
  118. * Descriptions of at least en_US and optionally any other locale supported by BYTM.
  119. * When an untranslated locale is set, the description will default to the value of en_US
  120. */
  121. description: Partial<Record<keyof typeof locales, string>> & {
  122. en_US: string;
  123. };
  124. /** URL to the plugin's icon - recommended size: 48x48 to 128x128 */
  125. iconUrl?: string;
  126. license?: {
  127. /** License name */
  128. name: string;
  129. /** URL to the license text */
  130. url: string;
  131. };
  132. /** Homepage URLs for the plugin */
  133. homepage: {
  134. /** Any other homepage URL */
  135. other?: string;
  136. /** URL to the plugin's source code (i.e. Git repo) - closed source plugins are not officially accepted at the moment. */
  137. source: string;
  138. /** URL to the plugin's bug tracker page, like GitHub issues */
  139. bug?: string;
  140. /** URL to the plugin's GreasyFork page */
  141. greasyfork?: string;
  142. /** URL to the plugin's OpenUserJS page */
  143. openuserjs?: string;
  144. };
  145. };
  146. /** Intents (permissions) BYTM has to grant the plugin for it to work */
  147. intents?: Array<PluginIntent>;
  148. /** Info about the plugin contributors */
  149. contributors?: Array<{
  150. /** Name of this contributor */
  151. name: string;
  152. /** (optional) Email address of this contributor */
  153. email?: string;
  154. /** (optional) URL to this plugin contributor's homepage / GitHub profile */
  155. url?: string;
  156. }>;
  157. };
  158. /** All events that are dispatched to plugins individually, including everything in {@linkcode SiteEventsMap} and {@linkcode InterfaceEventsMap} - these don't have a prefix since they can't conflict with other events */
  159. export type PluginEventMap =
  160. // Emitted on each plugin individually:
  161. & {
  162. /** Emitted when the plugin is registered on BYTM's side */
  163. pluginRegistered: (info: PluginInfo) => void;
  164. }
  165. // Emitted on every plugin simultaneously:
  166. & SiteEventsMap
  167. & InterfaceEventsMap;
  168. /** A plugin in either the queue or registered map */
  169. export type PluginItem =
  170. & {
  171. def: PluginDef;
  172. }
  173. & Pick<PluginRegisterResult, "events">;
  174. /** All functions exposed by the interface on the global `BYTM` object */
  175. export type InterfaceFunctions = {
  176. /** Adds a listener to one of the already present SelectorObserver instances */
  177. addSelectorListener: typeof addSelectorListener;
  178. /**
  179. * Returns the URL of a resource as defined in `assets/resources.json`
  180. * There are also some resources like translation files that get added by `tools/post-build.ts`
  181. *
  182. * The returned URL is a `blob:` URL served up by the userscript extension
  183. * This makes the resource fast to fetch and also prevents CORS issues
  184. */
  185. getResourceUrl: typeof getResourceUrl;
  186. /** Returns the unique session ID for the current tab */
  187. getSessionId: typeof getSessionId;
  188. /**
  189. * Returns the current video time (on both YT and YTM)
  190. * In case it can't be determined on YT, mouse movement is simulated to bring up the video time
  191. * In order for that edge case not to error out, the function would need to be called in response to a user interaction event (e.g. click) due to the strict autoplay policy in browsers
  192. */
  193. getVideoTime: typeof getVideoTime;
  194. /** Returns the translation for the provided translation key and set locale (check the files in the folder `assets/translations`) */
  195. t: typeof t;
  196. /** Returns the translation for the provided translation key, including pluralization identifier and set locale (check the files in the folder `assets/translations`) */
  197. tp: typeof tp;
  198. /** Returns the current feature configuration */
  199. getFeatures: typeof getFeatures;
  200. /** Overwrites the feature configuration with the provided one */
  201. saveFeatures: typeof setFeatures;
  202. };
  203. //#region features
  204. export type FeatureKey = keyof FeatureConfig;
  205. export type FeatureCategory =
  206. | "layout"
  207. | "volume"
  208. | "songLists"
  209. | "behavior"
  210. | "input"
  211. | "lyrics"
  212. | "general";
  213. type SelectOption = {
  214. value: string | number;
  215. label: string;
  216. };
  217. type FeatureTypeProps = ({
  218. type: "toggle";
  219. default: boolean;
  220. } & FeatureFuncProps)
  221. | ({
  222. type: "number";
  223. default: number;
  224. min: number;
  225. max?: number;
  226. step?: number;
  227. unit?: string | ((val: number) => string);
  228. } & FeatureFuncProps)
  229. | ({
  230. type: "select";
  231. default: string | number;
  232. options: SelectOption[] | (() => SelectOption[]);
  233. } & FeatureFuncProps)
  234. | ({
  235. type: "slider";
  236. default: number;
  237. min: number;
  238. max: number;
  239. step?: number;
  240. unit?: string | ((val: number) => string);
  241. } & FeatureFuncProps)
  242. | ({
  243. type: "hotkey";
  244. default: HotkeyObj;
  245. } & FeatureFuncProps)
  246. | ({
  247. type: "text";
  248. default: string;
  249. normalize?: (val: string) => string;
  250. } & FeatureFuncProps)
  251. | {
  252. type: "button";
  253. default?: undefined;
  254. click: () => Promise<void | unknown> | void | unknown;
  255. }
  256. type FeatureFuncProps = (
  257. {
  258. /** Whether the feature requires a page reload to take effect */
  259. reloadRequired: false;
  260. /** Called to instantiate the feature on the page */
  261. enable: (featCfg: FeatureConfig) => void,
  262. }
  263. | {
  264. /** Whether the feature requires a page reload to take effect */
  265. reloadRequired?: true;
  266. /** Called to instantiate the feature on the page */
  267. enable?: undefined;
  268. }
  269. ) & (
  270. {
  271. /** Called to remove all traces of the feature from the page and memory (includes event listeners) */
  272. disable?: (feats: FeatureConfig) => void,
  273. }
  274. | {
  275. /** Called to update the feature's behavior when the config changes */
  276. change?: (key: FeatureKey, initialVal: number | boolean | Record<string, unknown>, newVal: number | boolean | Record<string, unknown>) => void,
  277. }
  278. );
  279. /**
  280. * The feature info object that contains all properties necessary to construct the config menu and the feature config object.
  281. * All values are loosely typed so try to only use this with the `satisfies` keyword.
  282. * Use `typeof featInfo` (from `src/features/index.ts`) instead for full type safety.
  283. */
  284. export type FeatureInfo = Record<
  285. keyof FeatureConfig,
  286. {
  287. category: FeatureCategory;
  288. /**
  289. * HTML string that will be the help text for this feature
  290. * Specifying a function is useful for pluralizing or inserting values into the translation at runtime
  291. */
  292. helpText?: string | (() => string);
  293. /** Whether the value should be hidden in the config menu and from plugins */
  294. valueHidden?: boolean;
  295. /** Transformation function called before the value is rendered in the config menu */
  296. renderValue?: (value: string) => string | Promise<string>;
  297. /** HTML string that is appended to the end of a feature's text description */
  298. textAdornment?: () => (Promise<string | undefined> | string | undefined);
  299. /** Whether to only show this feature when advanced mode is activated (default false) */
  300. advanced?: boolean;
  301. }
  302. & FeatureTypeProps
  303. >;
  304. /** Feature configuration */
  305. export interface FeatureConfig {
  306. //#region layout
  307. /** Show a BetterYTM watermark under the YTM logo */
  308. watermarkEnabled: boolean;
  309. /** Remove the "si" tracking parameter from links in the share menu? */
  310. removeShareTrackingParam: boolean;
  311. /** On which sites to remove the "si" tracking parameter from links in the share menu */
  312. removeShareTrackingParamSites: SiteSelection;
  313. /** Enable skipping to a specific time in the video by pressing a number key (0-9) */
  314. numKeysSkipToTime: boolean;
  315. /** Fix spacing issues in the layout */
  316. fixSpacing: boolean;
  317. /** Remove the \"Upgrade\" / YT Music Premium tab */
  318. removeUpgradeTab: boolean;
  319. /** Where to show a thumbnail overlay over the video element and whether to show it at all */
  320. thumbnailOverlayBehavior: "never" | "videosOnly" | "songsOnly" | "always";
  321. /** Whether to show a button to toggle the thumbnail overlay in the media controls */
  322. thumbnailOverlayToggleBtnShown: boolean;
  323. /** Whether to show an indicator on the thumbnail overlay when it is active */
  324. thumbnailOverlayShowIndicator: boolean;
  325. /** The opacity of the thumbnail overlay indicator element */
  326. thumbnailOverlayIndicatorOpacity: number;
  327. /** How to fit the thumbnail overlay image */
  328. thumbnailOverlayImageFit: "cover" | "contain" | "fill";
  329. /** Hide the cursor when it's idling on the video element for a while */
  330. hideCursorOnIdle: boolean;
  331. /** Delay in seconds after which the cursor should be hidden */
  332. hideCursorOnIdleDelay: number;
  333. /** Whether to fix various issues in the layout when HDR is supported and active */
  334. fixHdrIssues: boolean;
  335. /** On which sites to disable Dark Reader - does nothing if the extension is not installed */
  336. disableDarkReaderSites: SiteSelectionOrNone;
  337. //#region volume
  338. /** Add a percentage label to the volume slider */
  339. volumeSliderLabel: boolean;
  340. /** The width of the volume slider in pixels */
  341. volumeSliderSize: number;
  342. /** Volume slider sensitivity - the smaller this number, the finer the volume control */
  343. volumeSliderStep: number;
  344. /** Volume slider scroll wheel sensitivity */
  345. volumeSliderScrollStep: number;
  346. /** Whether the volume should be locked to the same level across all tabs (changing in one changes in all others too) */
  347. volumeSharedBetweenTabs: boolean;
  348. /** Whether to set an initial volume level for each new session */
  349. setInitialTabVolume: boolean;
  350. /** The initial volume level to set for each new session */
  351. initialTabVolumeLevel: number;
  352. //#region song lists
  353. /** Add a button to each song in the queue to quickly open its lyrics page */
  354. lyricsQueueButton: boolean;
  355. /** Add a button to each song in the queue to quickly remove it */
  356. deleteFromQueueButton: boolean;
  357. /** Where to place the buttons in the queue */
  358. listButtonsPlacement: "queueOnly" | "everywhere";
  359. /** Add a button above the queue to scroll to the currently playing song */
  360. scrollToActiveSongBtn: boolean;
  361. /** Add a button above the queue to clear it */
  362. clearQueueBtn: boolean;
  363. //#region behavior
  364. /** Whether to completely disable the popup that sometimes appears before leaving the site */
  365. disableBeforeUnloadPopup: boolean;
  366. /** After how many milliseconds to close permanent toasts */
  367. closeToastsTimeout: number;
  368. /** Remember the last song's time when reloading or restoring the tab */
  369. rememberSongTime: boolean;
  370. /** Where to remember the song time */
  371. rememberSongTimeSites: SiteSelection;
  372. /** Time in seconds to remember the song time for */
  373. rememberSongTimeDuration: number;
  374. /** Time in seconds to subtract from the remembered song time */
  375. rememberSongTimeReduction: number;
  376. /** Minimum time in seconds the song needs to be played before it is remembered */
  377. rememberSongTimeMinPlayTime: number;
  378. //#region input
  379. /** Arrow keys skip forwards and backwards */
  380. arrowKeySupport: boolean;
  381. /** By how many seconds to skip when pressing the arrow keys */
  382. arrowKeySkipBy: number;
  383. /** Add a hotkey to switch between the YT and YTM sites on a video / song */
  384. switchBetweenSites: boolean;
  385. /** The hotkey that needs to be pressed to initiate the site switch */
  386. switchSitesHotkey: HotkeyObj;
  387. /** Make it so middle clicking a song to open it in a new tab (through thumbnail and song title) is easier */
  388. anchorImprovements: boolean;
  389. /** Whether to auto-like all played videos of configured channels */
  390. autoLikeChannels: boolean;
  391. /** Whether to show toggle buttons on the channel page to enable/disable auto-liking for that channel */
  392. autoLikeChannelToggleBtn: boolean;
  393. /** Whether to show a toggle button in the media controls to enable/disable auto-liking for those channel(s) */
  394. autoLikePlayerBarToggleBtn: boolean;
  395. /** How long to wait after a video has started playing to auto-like it */
  396. autoLikeTimeout: number;
  397. /** Whether to show a toast when a video is auto-liked */
  398. autoLikeShowToast: boolean;
  399. /** Opens the auto-like channels management dialog */
  400. autoLikeOpenMgmtDialog: undefined;
  401. //#region lyrics
  402. /** Add a button to the media controls to open the current song's lyrics on genius.com in a new tab */
  403. geniusLyrics: boolean;
  404. /** Base URL to use for GeniURL */
  405. geniUrlBase: string;
  406. /** Token to use for GeniURL */
  407. geniUrlToken: string;
  408. /** Max size of lyrics cache */
  409. lyricsCacheMaxSize: number;
  410. /** Max TTL of lyrics cache entries, in ms */
  411. lyricsCacheTTL: number;
  412. /** Button to clear lyrics cache */
  413. clearLyricsCache: undefined;
  414. /** Whether to use advanced filtering when searching for lyrics (exact, exact-ish) */
  415. advancedLyricsFilter: boolean;
  416. //#region misc
  417. /** The locale to use for translations */
  418. locale: TrLocale;
  419. /** Whether to default to US-English if the translation for the set locale is missing */
  420. localeFallback: boolean;
  421. /** Whether to check for updates to the script */
  422. versionCheck: boolean;
  423. /** Button to check for updates */
  424. checkVersionNow: undefined;
  425. /** The console log level - 0 = Debug, 1 = Info */
  426. logLevel: LogLevel;
  427. /** Amount of seconds until the feature initialization times out */
  428. initTimeout: number;
  429. /** Whether to show advanced settings in the config menu */
  430. advancedMode: boolean;
  431. }