├── userscripts └── .gitkeep ├── images └── github-use-template.png ├── .vscode └── settings.json ├── src ├── index.ts └── adapter.ts ├── webpack ├── prod.ts ├── dev.ts └── base.ts ├── LICENSE ├── README.md ├── package.json ├── .gitignore ├── plugins ├── prettier.plugin.ts └── userscript.plugin.ts └── tsconfig.json /userscripts/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /images/github-use-template.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pboymt/userscript-typescript-template/HEAD/images/github-use-template.png -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "conventionalCommits.scopes": [ 3 | "headers", 4 | "webpack", 5 | "npm" 6 | ] 7 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import axios from "axios"; 2 | import fetchAdapter from "./adapter"; 3 | 4 | axios.defaults.adapter = fetchAdapter; 5 | 6 | async function main() { 7 | console.log('Hello, world!'); 8 | const result = await axios.get('https://github.com/pboymt/userscript-typescript-template'); 9 | console.log(`Status: ${result.status}`); 10 | console.log(`Content Length: ${result.data.length}`); 11 | } 12 | 13 | main(); -------------------------------------------------------------------------------- /webpack/prod.ts: -------------------------------------------------------------------------------- 1 | import { merge } from 'webpack-merge'; 2 | import base from './base'; 3 | import path from 'node:path'; 4 | 5 | export default merge(base, { 6 | mode: 'production', 7 | cache: { 8 | type: 'filesystem', 9 | name: 'prod', 10 | }, 11 | output: { 12 | path: path.resolve(".", "userscripts"), 13 | filename: "index.prod.user.js", 14 | }, 15 | watchOptions: { 16 | ignored: /node_modules/, 17 | }, 18 | }); -------------------------------------------------------------------------------- /webpack/dev.ts: -------------------------------------------------------------------------------- 1 | import { merge } from 'webpack-merge'; 2 | import base from './base'; 3 | import path from 'node:path'; 4 | 5 | export default merge(base, { 6 | mode: 'development', 7 | cache: { 8 | type: 'filesystem', 9 | name: 'dev', 10 | }, 11 | output: { 12 | path: path.resolve(".", "userscripts"), 13 | filename: "index.dev.user.js", 14 | }, 15 | devtool: 'eval-source-map', 16 | watch: true, 17 | watchOptions: { 18 | ignored: /node_modules/, 19 | }, 20 | }); -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 PBOYMT 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /webpack/base.ts: -------------------------------------------------------------------------------- 1 | import TerserPlugin from "terser-webpack-plugin"; 2 | import { Configuration, BannerPlugin } from "webpack"; 3 | import { generateHeader } from "../plugins/userscript.plugin"; 4 | 5 | const config: Configuration = { 6 | entry: "./src/index.ts", 7 | target: "web", 8 | resolve: { 9 | extensions: [".ts", ".js"], 10 | }, 11 | module: { 12 | rules: [ 13 | { 14 | test: /\.m?ts$/, 15 | use: "ts-loader", 16 | exclude: /node_modules/, 17 | }, 18 | ], 19 | }, 20 | externals: { 21 | axios: "axios", 22 | "@trim21/gm-fetch": "GM_fetch", 23 | }, 24 | optimization: { 25 | minimize: false, 26 | minimizer: [new TerserPlugin({ 27 | // minify: TerserPlugin.swcMinify, 28 | terserOptions: { 29 | format: { 30 | comments: false, 31 | }, 32 | compress: false, 33 | mangle: false, 34 | }, 35 | extractComments: false, 36 | })], 37 | }, 38 | plugins: [ 39 | new BannerPlugin({ 40 | banner: generateHeader, 41 | raw: true, 42 | }) 43 | ] 44 | }; 45 | 46 | export default config; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # userscript-typescript-template 2 | 3 | Template repo using Webpack and TypeScript to build your userscript for Tampermonkey and more extensions. 4 | 5 | Automatically generate headers from your package.json! 6 | 7 | ## Usage 8 | 9 | ### 1. Generate repostiory (two-ways) 10 | 11 | #### - Use this template to create your new repository 12 | 13 | ![](./images/github-use-template.png) 14 | 15 | #### - Clone this repository 16 | 17 | ```bash 18 | # Use Github CLI 19 | $ gh repo clone pboymt/userscript-typescript-template 20 | # Or use 'git clone' command directly 21 | $ git clone https://github.com/pboymt/userscript-typescript-template.git 22 | ``` 23 | 24 | ### Development 25 | 26 | 1. Install dependencies with `npm install` or `npm ci`. 27 | 2. Edit settings in `userscript` object in [`package.json`](./package.json), you can refer to the comments in [`plugins/userscript.plugin.ts`](./plugins/userscript.plugin.ts). 28 | 3. Code your userscript in `src` directory (like [`src/index.ts`](./src/index.ts)). 29 | 4. Generate userscript with `npm run build`. 30 | 5. Import generated userscript to Tampermonkey by local file URI. 31 | 32 | ### Compile other file types 33 | 34 | You need install other loader plugins to support other file types. 35 | 36 | For example, you can use `scss-loader` to compile `.scss` files. Install it with `npm install --save-dev scss-loader node-sass` and add it in [`webpack.config.ts`](./webpack.config.ts). 37 | 38 | ### Debug 39 | 40 | Allow Tampermonkey's access to local file URIs ([Tampermonkey FAQs](https://tampermonkey.net/faq.php?ext=dhdg#Q204)) and import built userscript's file URL. 41 | 42 | ### Publish you userscript 43 | 44 | You can publish your userscript to [Greasy Fork](https://greasyfork.org/) or other websites. 45 | 46 | You can push your userscript to [Github](https://github.com) and import it to [Greasy Fork](https://greasyfork.org/import). -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "userscript-typescript-template", 3 | "version": "2.0.2", 4 | "description": "Template repo using Webpack and TypeScript to build your userscript for Tampermonkey and more extensions.", 5 | "main": "userscript/index.user.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1", 8 | "build": "webpack --config webpack/prod.ts", 9 | "dev": "webpack --config webpack/dev.ts", 10 | "build:watch": "webpack --watch" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/pboymt/userscript-typescript-template.git" 15 | }, 16 | "keywords": [], 17 | "author": "pboymt", 18 | "license": "MIT", 19 | "bugs": { 20 | "url": "https://github.com/pboymt/userscript-typescript-template/issues" 21 | }, 22 | "homepage": "https://github.com/pboymt/userscript-typescript-template#readme", 23 | "devDependencies": { 24 | "@types/node": "^18.15.11", 25 | "@types/prettier": "^2.7.0", 26 | "@types/tampermonkey": "^4.0.5", 27 | "@types/webpack": "^5.28.0", 28 | "prettier": "^2.7.1", 29 | "terser-webpack-plugin": "^5.3.6", 30 | "ts-loader": "^9.2.6", 31 | "ts-node": "^10.4.0", 32 | "typescript": "^5.0.4", 33 | "webpack": "^5.64.3", 34 | "webpack-cli": "^5.0.1", 35 | "webpack-merge": "^5.8.0" 36 | }, 37 | "userscript": { 38 | "require-template": "https://cdn.jsdelivr.net/npm/${dependencyName}@${dependencyVersion}", 39 | "namespace": "http://tampermonkey.net/", 40 | "license": "https://opensource.org/licenses/MIT", 41 | "match": [ 42 | "https://github.com/*", 43 | "https://www.baidu.com/*" 44 | ], 45 | "connect": [ 46 | "github.com" 47 | ], 48 | "require": [], 49 | "grant": [ 50 | "GM.xmlHttpRequest" 51 | ], 52 | "exclude": [], 53 | "resources": [], 54 | "keyedResources": {} 55 | }, 56 | "dependencies": { 57 | "@trim21/gm-fetch": "^0.1.13", 58 | "axios": "^1.3.6" 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | 106 | # Custom files 107 | /userscripts/*.js -------------------------------------------------------------------------------- /plugins/prettier.plugin.ts: -------------------------------------------------------------------------------- 1 | import { WebpackPluginInstance, Compiler } from "webpack"; 2 | import { format, getSupportInfo } from "prettier"; 3 | import path from "path"; 4 | import fs from "fs/promises"; 5 | 6 | const DEFAULT_EXTENSIONS = getSupportInfo() 7 | .languages 8 | .map(l => l.extensions) 9 | .reduce((a, b) => (a ?? []).concat(b ?? []), []) 10 | ?? [ 11 | ".css", 12 | ".graphql", 13 | ".js", 14 | ".json", 15 | ".jsx", 16 | ".less", 17 | ".sass", 18 | ".scss", 19 | ".ts", 20 | ".tsx", 21 | ".vue", 22 | ".yaml", 23 | ]; 24 | 25 | export default class PrettierPlugin implements WebpackPluginInstance { 26 | 27 | encoding: string = "utf-8"; 28 | 29 | apply(compiler: Compiler): void { 30 | compiler.hooks.emit.tap("PrettierPlugin", async (compilation) => { 31 | const promises: Promise[] = []; 32 | for (const filepath of compilation.fileDependencies) { 33 | if (DEFAULT_EXTENSIONS.some(ext => filepath.endsWith(ext))) { 34 | await this.formatFile(filepath); 35 | } 36 | } 37 | return Promise.all(promises); 38 | }); 39 | } 40 | 41 | async formatFile(filepath: string): Promise { 42 | try { 43 | if (/node_modules/.exec(filepath)) { 44 | return; 45 | } 46 | console.log(filepath); 47 | const content = await fs.readFile(filepath, { encoding: 'utf-8' }); 48 | const formatted = format(content, { 49 | filepath, 50 | // parser: path.extname(filepath) === ".ts" ? "typescript" : undefined, 51 | // plugins: [ 52 | // "asyncGenerators", 53 | // "bigInt", 54 | // "classProperties", 55 | // "classPrivateProperties", 56 | // "classPrivateMethods", 57 | // "decorators", 58 | // "doExpressions", 59 | // "dynamicImport", 60 | // "exportDefaultFrom", 61 | // "exportNamespaceFrom", 62 | // "functionBind", 63 | // "functionSent", 64 | // "importMeta", 65 | // "logicalAssignment", 66 | // "nullishCoalescingOperator", 67 | // "numericSeparator", 68 | // "objectRestSpread", 69 | // "optionalCatchBinding", 70 | // "optionalChaining", 71 | // "partialApplication", 72 | // "pipelineOperator", 73 | // "throwExpressions", 74 | // ], 75 | }); 76 | try { 77 | await fs.writeFile(filepath, formatted, { encoding: 'utf-8' }); 78 | } catch (error) { 79 | throw error; 80 | } 81 | } catch (error) { 82 | throw error; 83 | } 84 | 85 | } 86 | 87 | } -------------------------------------------------------------------------------- /src/adapter.ts: -------------------------------------------------------------------------------- 1 | import GM_fetch from '@trim21/gm-fetch'; 2 | import { AxiosRequestConfig, AxiosResponse } from 'axios'; 3 | 4 | export default async function fetchAdapter(config: AxiosRequestConfig): Promise> { 5 | const request = createRequest(config); 6 | try { 7 | const response = await createResponse(request, config); 8 | return response; 9 | } catch (error) { 10 | throw error; 11 | } 12 | } 13 | 14 | function createRequest(config: AxiosRequestConfig): Request { 15 | let { method: cMethod, auth: cAuth, data: cData, headers: cHeaders, withCredentials } = config; 16 | const headers = new Headers(Object.entries(cHeaders ?? {}).map(([key, value]) => [key, value.toString()] satisfies [string, string])); 17 | 18 | if (cAuth) { 19 | const { username = '', password = '' } = cAuth; 20 | const token = window.btoa(`${username}:${decodeURI(encodeURIComponent(password))}`); 21 | headers.set('Authorization', `Basic ${token}`); 22 | } 23 | 24 | const method = cMethod?.toUpperCase() ?? 'GET'; 25 | 26 | let options = { 27 | method, 28 | headers, 29 | } as RequestInit; 30 | 31 | if (method !== 'GET' && method !== 'HEAD') { 32 | options.body = cData; 33 | if (cData instanceof FormData) { 34 | headers.delete('Content-Type'); 35 | } 36 | } 37 | 38 | if (typeof withCredentials === 'boolean') { 39 | options.credentials = withCredentials ? 'include' : 'omit'; 40 | } 41 | 42 | const url = new URL(config.url ?? '', config.baseURL); 43 | if (config.params) { 44 | for (const [key, value] of Object.entries(config.params)) { 45 | url.searchParams.set(key, String(value)); 46 | } 47 | } 48 | 49 | return new Request(url.toString(), options); 50 | } 51 | 52 | async function createResponse(request: Request, config: AxiosRequestConfig) { 53 | let res: Response; 54 | try { 55 | res = await GM_fetch(request); 56 | } catch (e) { 57 | throw e; 58 | } 59 | const { status, statusText, headers: rHeaders } = res; 60 | const response = { 61 | status, 62 | statusText, 63 | headers: Object.fromEntries(rHeaders.entries()), 64 | config, 65 | request, 66 | } as AxiosResponse; 67 | 68 | if (status >= 200 && status !== 204) { 69 | switch (config.responseType) { 70 | case 'arraybuffer': 71 | response.data = await res.arrayBuffer(); 72 | break; 73 | case 'blob': 74 | response.data = await res.blob(); 75 | break; 76 | case 'document': 77 | response.data = await res.text(); 78 | break; 79 | case 'json': 80 | response.data = await res.json(); 81 | break; 82 | case 'text': 83 | response.data = await res.text(); 84 | break; 85 | case 'stream': 86 | response.data = res.body; 87 | break; 88 | default: 89 | response.data = await res.text(); 90 | } 91 | } 92 | 93 | return response; 94 | } -------------------------------------------------------------------------------- /plugins/userscript.plugin.ts: -------------------------------------------------------------------------------- 1 | import { readFileSync, writeFileSync } from 'fs'; 2 | import { join } from 'path'; 3 | 4 | /** 5 | * I18n field of the userscript. 6 | */ 7 | type I18nField = { [locale: string]: string }; 8 | 9 | /** 10 | * Userscript's all headers. 11 | */ 12 | interface UserScriptOptions { 13 | 'require-template': string; 14 | name: string; 15 | 'i18n-names': I18nField; 16 | namespace: string; 17 | description: string; 18 | 'i18n-descriptions': I18nField; 19 | version: string; 20 | author: string; 21 | homepage: string; 22 | homepageURL: string; 23 | website: string; 24 | source: string; 25 | icon: string; 26 | iconURL: string; 27 | defaulticon: string; 28 | icon64: string; 29 | icon64URL: string; 30 | updateURL: string; 31 | downloadURL: string; 32 | supportURL: string; 33 | license: string; 34 | include: string[]; 35 | match: string[]; 36 | exclude: string[]; 37 | require: string[]; 38 | resources: string[]; 39 | keyedResources: { [key: string]: string }; 40 | connect: string[]; 41 | 'run-at': string; 42 | grant: string[]; 43 | antifeature: string[]; 44 | noframes: boolean; 45 | nocompat: string; 46 | } 47 | 48 | /** 49 | * Brief interface of the main structure of "package.json". 50 | */ 51 | interface PackageJsonOptions { 52 | name: string; 53 | version: string; 54 | description: string; 55 | author: string; 56 | homepage: string; 57 | userscript: Partial; 58 | dependencies: { [key: string]: string }; 59 | } 60 | 61 | /** 62 | * Generate a userscript's headers from "package.json" file. 63 | * 64 | * @returns {string} Return userscript's header. 65 | */ 66 | export function generateHeader() { 67 | 68 | const packageJsonRaw = readFileSync(join(__dirname, '../package.json'), 'utf8'); 69 | const packageJson = JSON.parse(packageJsonRaw) as Partial; 70 | const userscript = packageJson.userscript as Partial; 71 | 72 | // The regular expression used to remove the dependency version string prefix. 73 | const dependencyVersionRegExp = /^[\^~]/; 74 | // Userscript's header. 75 | const headers = ['// ==UserScript==']; 76 | 77 | /** 78 | * Add userscript header's name. 79 | * If the name is not set, the package name is used. If neither is set, an error is thrown. 80 | */ 81 | if (packageJson.name || userscript.name) { 82 | headers.push(`// @name ${userscript.name ?? packageJson.name}`); 83 | } else { 84 | throw new Error('No name specified in package.json'); 85 | } 86 | /** 87 | * Add userscript header's i18n-names. 88 | */ 89 | if (userscript['i18n-names'] && typeof userscript['i18n-names'] === 'object') { 90 | for (const [locale, name] of Object.entries(userscript['i18n-names'])) { 91 | headers.push(`// @name:${locale} ${name}`); 92 | } 93 | } 94 | /** 95 | * Add userscript header's version. 96 | * If the version is not set, the package version is used. If neither is set, an error is thrown. 97 | */ 98 | if (packageJson.version || userscript.version) { 99 | headers.push(`// @version ${userscript.version ?? packageJson.version}`); 100 | } else { 101 | throw new Error('No version specified in package.json'); 102 | } 103 | // Add userscript header's namespace. 104 | if (userscript.namespace) { 105 | headers.push(`// @namespace ${userscript.namespace}`); 106 | } 107 | // Add userscript header's description. 108 | if (packageJson.description || userscript.description) { 109 | headers.push(`// @description ${userscript.description ?? packageJson.description}`); 110 | } 111 | // Add userscript header's i18n-descriptions. 112 | if (userscript['i18n-descriptions'] && typeof userscript['i18n-descriptions'] === 'object') { 113 | for (const [locale, description] of Object.entries(userscript['i18n-descriptions'])) { 114 | headers.push(`// @description:${locale} ${description}`); 115 | } 116 | } 117 | // Add userscript header's author. 118 | if (packageJson.author || userscript.author) { 119 | headers.push(`// @author ${userscript.author ?? packageJson.author}`); 120 | } 121 | // Add userscript header's homepage, homepageURL, website or source. 122 | if (packageJson.homepage || userscript.homepage) { 123 | headers.push(`// @homepage ${userscript.homepage ?? packageJson['homepage']}`); 124 | } else if (userscript.homepageURL) { 125 | headers.push(`// @homepageURL ${userscript.homepageURL}`); 126 | } else if (userscript.website) { 127 | headers.push(`// @website ${userscript.website}`); 128 | } else if (userscript.source) { 129 | headers.push(`// @source ${userscript.source}`); 130 | } 131 | // Add userscript header's icon, iconURL or defaulticon. 132 | if (userscript.icon) { 133 | headers.push(`// @icon ${userscript.icon}`); 134 | } else if (userscript.iconURL) { 135 | headers.push(`// @iconURL ${userscript.iconURL}`); 136 | } else if (userscript.defaulticon) { 137 | headers.push(`// @defaulticon ${userscript.defaulticon}`); 138 | } 139 | // Add userscript header's icon64 or icon64URL. 140 | if (userscript.icon64) { 141 | headers.push(`// @icon64 ${userscript.icon64}`); 142 | } else if (userscript.icon64URL) { 143 | headers.push(`// @icon64URL ${userscript.icon64URL}`); 144 | } 145 | // Add userscript header's updateURL. 146 | if (userscript.updateURL) { 147 | headers.push(`// @updateURL ${userscript.updateURL}`); 148 | } 149 | // Add userscript header's downloadURL. 150 | if (userscript.downloadURL) { 151 | headers.push(`// @downloadURL ${userscript.downloadURL}`); 152 | } 153 | // Add userscript header's supportURL. 154 | if (userscript.supportURL) { 155 | headers.push(`// @supportURL ${userscript.supportURL}`); 156 | } 157 | // Add userscript header's license. 158 | if (userscript.license) { 159 | headers.push(`// @license ${userscript.license}`); 160 | } 161 | // Add userscript header's includes. 162 | if (userscript.include && userscript.include instanceof Array) { 163 | for (const include of userscript.include) { 164 | headers.push(`// @include ${include}`); 165 | } 166 | } 167 | // Add userscript header's matches. 168 | if (userscript.match && userscript.match instanceof Array) { 169 | for (const match of userscript.match) { 170 | headers.push(`// @match ${match}`); 171 | } 172 | } 173 | // Add userscript header's excludes. 174 | if (userscript.exclude && userscript.exclude instanceof Array) { 175 | for (const exclude of userscript.exclude) { 176 | headers.push(`// @exclude ${exclude}`); 177 | } 178 | } 179 | /** 180 | * Add userscript header's requires. 181 | * The package name and version will be obtained from the "dependencies" field, 182 | * and the jsdelivr link will be generated automatically. 183 | * You can also set the string template with the parameters "{dependencyName}" and "{dependencyVersion}" 184 | * in the "require-template" field of the "userscript" object in the "package.json" file. 185 | */ 186 | if (packageJson.dependencies) { 187 | const urlTemplate = userscript['require-template'] ?? 'https://cdn.jsdelivr.net/npm/${dependencyName}@${dependencyVersion}'; 188 | const requireTemplate = `// @require ${urlTemplate}`; 189 | for (const dependencyName in packageJson.dependencies) { 190 | const dependencyVersion = packageJson.dependencies[dependencyName].replace(dependencyVersionRegExp, ''); 191 | headers.push( 192 | requireTemplate 193 | .replace('${dependencyName}', dependencyName) 194 | .replace('${dependencyVersion}', dependencyVersion) 195 | // Due to the potential conflict caused by this patch, the original template replacement statement was added. 196 | .replace('{dependencyName}', dependencyName) 197 | .replace('{dependencyVersion}', dependencyVersion) 198 | ); 199 | } 200 | } 201 | // You can also add dependencies separately in the require field of the userscript object. 202 | if (userscript.require && userscript.require instanceof Array) { 203 | for (const require of userscript.require) { 204 | headers.push(`// @require ${require}`); 205 | } 206 | } 207 | // Add userscript header's resources. 208 | if (userscript.resources && userscript.resources instanceof Array) { 209 | for (const resource of userscript.resources) { 210 | headers.push(`// @resource ${resource}`); 211 | } 212 | } 213 | // Add userscript header's resources. 214 | // Some of the resources should contain a specified name, for which userscripts can get value from it 215 | // eg. // @resource mycss http://link.to/some.css 216 | // Userscripts have the ability to apply css with `GM_addStyle(GM_getResourceText('mycss'))` 217 | if (userscript.keyedResources) { 218 | for (const dependencyName in userscript.keyedResources) { 219 | headers.push(`// @resource ${dependencyName} ${userscript.keyedResources[dependencyName]}`); 220 | } 221 | } 222 | // Add userscript header's connects. 223 | if (userscript.connect && userscript.connect instanceof Array) { 224 | for (const connect of userscript.connect) { 225 | headers.push(`// @connect ${connect}`); 226 | } 227 | } 228 | // Add userscript header's run-at. 229 | if (userscript['run-at']) { 230 | headers.push(`// @run-at ${userscript['run-at']}`); 231 | } 232 | // Add userscript header's grants. 233 | if (userscript.grant && userscript.grant instanceof Array) { 234 | for (const grant of userscript.grant) { 235 | headers.push(`// @grant ${grant}`); 236 | } 237 | } 238 | // Add userscript header's antifeatures. 239 | if (userscript.antifeature && userscript.antifeature instanceof Array) { 240 | for (const antifeature of userscript.antifeature) { 241 | headers.push(`// @antifeature ${antifeature}`); 242 | } 243 | } 244 | // Add userscript header's noframes. 245 | if (userscript.noframes) { 246 | headers.push('// @noframes'); 247 | } 248 | // Add userscript header's nocompat. 249 | if (userscript.nocompat) { 250 | headers.push(`// @nocompat ${userscript.nocompat}`); 251 | } 252 | // Userscript header's ending. 253 | headers.push('// ==/UserScript==\n') 254 | return headers.join('\n'); 255 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "ES6", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */ 22 | // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | 26 | /* Modules */ 27 | "module": "commonjs", /* Specify what module code is generated. */ 28 | // "rootDir": "./", /* Specify the root folder within your source files. */ 29 | // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ 30 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 31 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 32 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 33 | // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ 34 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 35 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 36 | "resolveJsonModule": true, /* Enable importing .json files */ 37 | // "noResolve": true, /* Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project. */ 38 | 39 | /* JavaScript Support */ 40 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ 41 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 42 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ 43 | 44 | /* Emit */ 45 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 46 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 47 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 48 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 49 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ 50 | // "outDir": "./", /* Specify an output folder for all emitted files. */ 51 | "removeComments": true, /* Disable emitting comments. */ 52 | // "noEmit": true, /* Disable emitting files from a compilation. */ 53 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 54 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */ 55 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 56 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 57 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 58 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 59 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 60 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 61 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 62 | // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */ 63 | // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */ 64 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 65 | // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */ 66 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 67 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 68 | 69 | /* Interop Constraints */ 70 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 71 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 72 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */ 73 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 74 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 75 | 76 | /* Type Checking */ 77 | "strict": true, /* Enable all strict type-checking options. */ 78 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */ 79 | // "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */ 80 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 81 | // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ 82 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 83 | // "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */ 84 | // "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */ 85 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 86 | // "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */ 87 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */ 88 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 89 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 90 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 91 | // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ 92 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 93 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */ 94 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 95 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 96 | 97 | /* Completeness */ 98 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 99 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 100 | }, 101 | "exclude": [ 102 | "node_modules", 103 | "userscripts" 104 | ] 105 | } 106 | --------------------------------------------------------------------------------