vite-userscript-plugin 0.5.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,5 @@
1
1
  # vite-userscript-plugin
2
2
 
3
- ![ci](https://img.shields.io/github/workflow/status/crashmax-dev/vite-userscript-plugin/npm-publish)
4
3
  ![npm](https://img.shields.io/npm/v/vite-userscript-plugin)
5
4
  ![license](https://img.shields.io/github/license/crashmax-dev/vite-userscript-plugin)
6
5
 
@@ -85,11 +84,6 @@ export interface UserscriptPluginConfig {
85
84
  * @default true
86
85
  */
87
86
  autoGrants?: boolean
88
-
89
- /**
90
- * Server config (used in development mode for hot reloading).
91
- */
92
- server?: ServerConfig
93
87
  }
94
88
  ```
95
89
 
@@ -0,0 +1 @@
1
+ "use strict";async function n(){let o=new WebSocket("ws://localhost:__PORT__");o.addEventListener("open",()=>{let{script:e}=GM_info;console.group(`${e.name}@${e.version}`),console.log(GM_info),console.groupEnd()}),o.addEventListener("close",()=>{setTimeout(n,1e3)}),o.addEventListener("error",()=>{o.close()}),o.addEventListener("message",()=>{location.reload()})}n().then(()=>console.info("Connection to ws...")).finally(()=>console.clear());
@@ -0,0 +1 @@
1
+
@@ -0,0 +1 @@
1
+ async function n(){let o=new WebSocket("ws://localhost:__PORT__");o.addEventListener("open",()=>{let{script:e}=GM_info;console.group(`${e.name}@${e.version}`),console.log(GM_info),console.groupEnd()}),o.addEventListener("close",()=>{setTimeout(n,1e3)}),o.addEventListener("error",()=>{o.close()}),o.addEventListener("message",()=>{location.reload()})}n().then(()=>console.info("Connection to ws...")).finally(()=>console.clear());
package/dist/index.cjs ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";var W=Object.create;var h=Object.defineProperty;var N=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var z=Object.getPrototypeOf,I=Object.prototype.hasOwnProperty;var J=(e,t)=>{for(var r in t)h(e,r,{get:t[r],enumerable:!0})},R=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of K(t))!I.call(e,o)&&o!==r&&h(e,o,{get:()=>t[o],enumerable:!(n=N(t,o))||n.enumerable});return e};var C=(e,t,r)=>(r=e!=null?W(z(e)):{},R(t||!e||!e.__esModule?h(r,"default",{value:e,enumerable:!0}):r,e)),H=e=>R(h({},"__esModule",{value:!0}),e);var X={};J(X,{UserscriptPlugin:()=>V,default:()=>Q});module.exports=H(X);var k=C(require("get-port"),1),c=require("fs"),q=require("http"),d=require("path"),v=require("url"),F=C(require("sanitize-filename"),1),L=require("websocket");function j(e){let t=[],r=Object.keys(e),n=Math.max(...r.map(a=>a.length))+1,o=a=>" ".repeat(n-a.length),g=(a,i)=>{let s=typeof i=="boolean";s&&!i||(i=s?"":o(a)+i.toString(),t.push(`// @${a}${i}`))};for(let[a,i]of Object.entries(e))if(Array.isArray(i))i.forEach(s=>g(a,s));else{if(i===void 0)continue;g(a,i)}return["// ==UserScript==",...t,"// ==/UserScript=="].join(`
2
+ `)}var T=new RegExp(/\.(tsx?|jsx?)$/),$=new RegExp(/\.(s?css|sass)$/),S='console.warn("__TEMPLATE__")',x=["unsafeWindow","window.onurlchange","window.focus","window.close","GM_setValue","GM_getValue","GM_deleteValue","GM_listValues","GM_setClipboard","GM_addStyle","GM_addElement","GM_addValueChangeListener","GM_removeValueChangeListener","GM_registerMenuCommand","GM_unregisterMenuCommand","GM_download","GM_getTab","GM_getTabs","GM_saveTab","GM_openInTab","GM_notification","GM_getResourceURL","GM_getResourceText","GM_xmlhttpRequest","GM_webRequest","GM_log","GM_info"];var O=require("vite");function u(e){return[...new Set(Array.isArray(e)?e:e?[e]:[])]}async function G({file:e,name:t,loader:r}){let{code:n}=await(0,O.transformWithEsbuild)(e,t,{loader:r,minify:!0});return n}function E(e){let t=[];for(let r of x)e.indexOf(r)!==-1&&t.push(r);return t}var P=class{styles=new Map;async add(t,r){let n=await G({file:t,name:r,loader:"css"});return this.styles.set(r,n.replace(`
3
+ `,"")),""}inject(){let t=[...this.styles.values()].join("");if(!!t)return`GM_addStyle(\`${t}\`)`}merge(t){let r=[];for(let n of t){let o=this.styles.get(n);!o||r.push([n,o])}this.styles.clear(),r.forEach(n=>this.styles.set(...n))}},w=new P;var U={};function V(e){let t,r,n=null,o=null,g=(0,q.createServer)(),a=L.server;return new a({httpServer:g}).on("request",s=>{o=s.accept(null,s.origin)}),{name:"vite-userscript-plugin",apply:"build",config(){return{build:{lib:{entry:e.entry,name:e.metadata.name,formats:["iife"],fileName:()=>`${e.metadata.name}.js`},rollupOptions:{output:{exports:"none",extend:!0}}}}},configResolved(s){t=s,r=s.build.watch??!1;let{name:l,match:y,require:p,include:f,exclude:_,resource:M,connect:b}=e.metadata;e.metadata.name=(0,F.default)(l),e.metadata.match=u(y),e.metadata.require=u(p),e.metadata.include=u(f),e.metadata.exclude=u(_),e.metadata.resource=u(M),e.metadata.connect=u(b)},async transform(s,l){return $.test(l)?{code:await w.add(s,l)}:l.includes(e.entry)?{code:s+S}:null},generateBundle(s,l){for(let[y,p]of Object.entries(l)){let f=Object.keys(p.modules);w.merge(f)}},async writeBundle(s,l){!n&&r&&(n=await(0,k.default)(),g.listen(n));for(let[y]of Object.entries(l))if(T.test(y)){let p=t.root,f=t.build.outDir||"dist",_=(0,d.resolve)(p,f,y),M=(0,d.resolve)((0,d.dirname)((0,v.fileURLToPath)(U.url)),`hot-reload-${e.metadata.name}.js`),b=(0,d.resolve)(p,f,`${e.metadata.name}.proxy.user.js`),A=(0,d.resolve)(p,f,`${e.metadata.name}.user.js`);try{let m=(0,c.readFileSync)(_,"utf8");if(e.metadata.grant=u(r?x:e.autoGrants??!0?E(m):[...e.metadata.grant??[],"GM_addStyle","GM_info"]),r){let D=(0,c.readFileSync)((0,d.resolve)((0,d.dirname)((0,v.fileURLToPath)(U.url)),"hot-reload.js"),"utf8"),B=await G({file:D.replace("__PORT__",n.toString()),name:M,loader:"js"});(0,c.writeFileSync)(M,B),(0,c.writeFileSync)(b,j({...e.metadata,require:[...e.metadata.require,"file://"+M,"file://"+_]}))}m=m.replace(S,`${w.inject()}`),m=await G({file:m,name:y,loader:"js"}),(0,c.writeFileSync)(_,m),(0,c.writeFileSync)(A,`${j(e.metadata)}
4
+
5
+ ${m}`)}catch(m){console.log(m)}}r||(g.close(),process.exit(0))},buildEnd(){o&&o.sendUTF(JSON.stringify({message:"reload"}))}}}var Q=V;0&&(module.exports={UserscriptPlugin});
package/dist/index.d.ts CHANGED
@@ -1,6 +1,208 @@
1
1
  import { PluginOption } from 'vite';
2
- import type { UserscriptPluginConfig } from './types.js';
2
+
3
+ declare const grants: readonly ["unsafeWindow", "window.onurlchange", "window.focus", "window.close", "GM_setValue", "GM_getValue", "GM_deleteValue", "GM_listValues", "GM_setClipboard", "GM_addStyle", "GM_addElement", "GM_addValueChangeListener", "GM_removeValueChangeListener", "GM_registerMenuCommand", "GM_unregisterMenuCommand", "GM_download", "GM_getTab", "GM_getTabs", "GM_saveTab", "GM_openInTab", "GM_notification", "GM_getResourceURL", "GM_getResourceText", "GM_xmlhttpRequest", "GM_webRequest", "GM_log", "GM_info"];
4
+
5
+ declare type RunAt = 'document-start' | 'document-body' | 'document-end' | 'document-idle' | 'context-menu';
6
+ declare type Grants = typeof grants[number];
7
+ declare type MetadataConfig = {
8
+ [property: string]: string | boolean | number | string[] | undefined;
9
+ /**
10
+ * The name of the script.
11
+ * Internationalization is done by adding an appendix naming the locale.
12
+ */
13
+ name: string;
14
+ /**
15
+ * Version of the script,
16
+ * it can be used to check if a script has new versions. It is composed
17
+ * of several parts, joined by `.` Each part must start with numbers,
18
+ * and can be followed by alphabetic characters.
19
+ */
20
+ version: string;
21
+ /**
22
+ * A brief summary to describe the script.
23
+ */
24
+ description?: string;
25
+ /**
26
+ * The scripts author.
27
+ */
28
+ author?: string;
29
+ /**
30
+ * The script license.
31
+ */
32
+ license?: string;
33
+ /**
34
+ * The combination of `@namespace` and `@name` is the unique identifier for
35
+ * a userscript. `@namespace` can be any string, for example the homepage
36
+ * of a group of userscripts by the same author. If not provided
37
+ * the `@namespace` falls back to an empty string ('').
38
+ */
39
+ namespace?: string;
40
+ /**
41
+ * The authors homepage that is used at the options page to link from
42
+ * the scripts name to the given page. Please note that if the `@namespace`
43
+ * tag starts with `https://` its content will be used for this too.
44
+ */
45
+ homepage?: string;
46
+ /**
47
+ * An update URL for the userscript.
48
+ * Note:
49
+ * - a `@version` tag is required to make update checks work.
50
+ */
51
+ updateURL?: string;
52
+ /**
53
+ * Defines the URL where the script will be downloaded from when an update was
54
+ * detected. If the value none is used, then no update check will be done.
55
+ */
56
+ downloadURL?: string;
57
+ /**
58
+ * Defines the URL where the user can report issues and get personal support.
59
+ */
60
+ supportURL?: string;
61
+ /**
62
+ * Specify an icon for the script. Almost any image will work,
63
+ * but a 32x32 pixel size is best. This value may be specified relative
64
+ * to the URL the script itself is downloaded from.
65
+ */
66
+ icon?: string;
67
+ icon64?: string;
68
+ /**
69
+ * Each `@include` and `@exclude` rule can be one of the following:
70
+ * - a normal string
71
+ * > If the string does not start or end with a slash (/),
72
+ * > it will be used as a normal string.
73
+ * > If there are wildcards (*), each of them matches any characters.
74
+ * > e.g. https://www.google.com/* matches the following:
75
+ * - https://www.google.com/
76
+ * - https://www.google.com/any/subview
77
+ * > but not the following:
78
+ * - http://www.google.com/
79
+ * - https://www.google.com.hk/
80
+ * > If there is no wildcard in the string, the rule matches the entire URL.
81
+ * > e.g. https://www.google.com/ matches only https://www.google.com/
82
+ * > but not https://www.google.com/any/subview.
83
+ * > The host part accepts .tld to match top level domain suffix.
84
+ * > e.g. https://www.google.tld/ matches both https://www.google.com/
85
+ * > and https://www.google.co.jp/.
86
+ *
87
+ * - a regular expression
88
+ * > If the string starts and ends with a slash (/),
89
+ * > it will be compiled as a regular expression.
90
+ * > e.g. /\.google\.com[\.\/]/ matches the following:
91
+ * - https://www.google.com/,
92
+ * - https://www.google.com/any/subview
93
+ * - http://www.google.com/
94
+ * - https://www.google.com.hk/
95
+ */
96
+ include?: string[] | string;
97
+ exclude?: string[] | string;
98
+ /**
99
+ * More or less equal to the `@include` tag.
100
+ * You can get more information
101
+ * [here](https://developer.chrome.com/docs/extensions/mv2/match_patterns/).
102
+ *
103
+ * Note:
104
+ * - The `<all_urls>` statement is not yet supported and the scheme part also
105
+ * accepts `http*://`.
106
+ */
107
+ match: string[] | string;
108
+ /**
109
+ * Points to a JavaScript file that is loaded and executed before the script
110
+ * itself starts running.
111
+ *
112
+ * Note:
113
+ * - The scripts loaded via `@require` and their "use strict" statements
114
+ * might influence the userscript's strict mode!
115
+ */
116
+ require?: string[] | string;
117
+ /**
118
+ * Preloads resources that can by accessed
119
+ * via `GM_getResourceURL` and `GM_getResourceText` by the script.
120
+ */
121
+ resource?: string[] | string;
122
+ /**
123
+ * This tag defines the domains (no top-level domains) including subdomains
124
+ * which are allowed to be retrieved by `GM_xmlhttpRequest`
125
+ *
126
+ * - domains like tampermonkey.net (this will also allow all sub-domains)
127
+ * - sub-domains i.e. safari.tampermonkey.net
128
+ * - self to whitelist the domain the script is currently running at
129
+ * - localhost to access the localhost
130
+ * - 1.2.3.4 to connect to an IP address
131
+ *
132
+ * If it's not possible to declare all domains a userscript might connect
133
+ * to then it's a good practice to do the following: ***Declare all known or
134
+ * at least all common domains*** that might be connected by the script.
135
+ * This way the confirmation dialog can be avoided for most of the users.
136
+ *
137
+ * Additionally add `@connect *` to the script. By doing so Tampermonkey will
138
+ * still ask the user whether the next connection to a not mentioned domain
139
+ * is allowed, but also ***offer a "Always allow all domains" button***.
140
+ * If the user clicks at this button then all future requestswill
141
+ * be permitted automatically.
142
+ */
143
+ connect?: string[] | string;
144
+ /**
145
+ * This tag makes the script running on the main pages, but not at iframes.
146
+ * @default false
147
+ */
148
+ noframes?: boolean;
149
+ /**
150
+ * `@grant` is used to whitelist GM_* functions, the `unsafeWindow` object and
151
+ * some powerful window functions. If no `@grant` tag is given TM guesses
152
+ * the scripts needs.
153
+ */
154
+ grant?: Exclude<Grants, 'GM_addStyle' | 'GM_info'>[];
155
+ /**
156
+ * Defines the moment the script is injected. In opposition to other script
157
+ * handlers, `@run-at` defines the first possible moment a script wants to
158
+ * run. This means it may happen, that a script that uses the `@require` tag
159
+ * may be executed after the document is already loaded, cause fetching the
160
+ * required script took that long. Anyhow, all `DOMNodeInserted` and
161
+ * `DOMContentLoaded` events that happended after the given injection
162
+ * moment are cached and delivered to the script when it is injected.
163
+ *
164
+ * - `document-start`
165
+ * The script will be injected as fast as possible.
166
+ *
167
+ * - `document-body`
168
+ * The script will be injected if the body element exists.
169
+ *
170
+ * - `document-end`
171
+ * The script will be injected when or after the `DOMContentLoaded` event
172
+ * was dispatched.
173
+ *
174
+ * - `document-idle`
175
+ * The script will be injected after the DOMContentLoaded event was
176
+ * dispatched. This is the default value if no `@run-at` tag is given.
177
+ *
178
+ * - `context-menu`
179
+ * The script will be injected if it is clicked at the browser context menu
180
+ * (desktop Chrome-based browsers only).
181
+ *
182
+ * Note:
183
+ * - all `@include` and `@exclude` statements will be ignored if this value
184
+ * is used, but this may change in the future.
185
+ *
186
+ * @default 'document-idle'
187
+ */
188
+ 'run-at'?: RunAt;
189
+ };
190
+ interface UserscriptPluginConfig {
191
+ /**
192
+ * Path of userscript entry.
193
+ */
194
+ entry: string;
195
+ /**
196
+ * Userscript header config.
197
+ */
198
+ metadata: MetadataConfig;
199
+ /**
200
+ * Import all `@grant` in development mode.
201
+ * @default true
202
+ */
203
+ autoGrants?: boolean;
204
+ }
205
+
3
206
  declare function UserscriptPlugin(config: UserscriptPluginConfig): PluginOption;
4
- export { UserscriptPlugin };
5
- export default UserscriptPlugin;
6
- export type { UserscriptPluginConfig };
207
+
208
+ export { UserscriptPlugin, UserscriptPluginConfig, UserscriptPlugin as default };
package/dist/index.js CHANGED
@@ -1,130 +1,5 @@
1
- import { readFileSync, writeFileSync } from 'node:fs';
2
- import { createServer } from 'node:http';
3
- import { dirname, resolve } from 'node:path';
4
- import { fileURLToPath } from 'node:url';
5
- import websocket from 'websocket';
6
- import { banner } from './banner.js';
7
- import { grants, regexpScripts, template } from './constants.js';
8
- import css from './css.js';
9
- import { defineGrants, removeDuplicates, transform } from './helpers.js';
10
- function UserscriptPlugin(config) {
11
- let pluginConfig;
12
- let isBuildWatch;
13
- let socketConnection = null;
14
- const port = config.server?.port || 8000;
15
- const server = createServer((_, res) => {
16
- // const index = resolve(
17
- // dirname(fileURLToPath(import.meta.url)), '..', 'src', 'index.html'
18
- // )
19
- // res.writeHead(200, { 'Content-Type': 'html' })
20
- // res.end(readFileSync(index))
21
- });
22
- server.listen(port);
23
- const WebSocketServer = websocket.server;
24
- const ws = new WebSocketServer({ httpServer: server });
25
- ws.on('request', (request) => {
26
- socketConnection = request.accept(null, request.origin);
27
- });
28
- return {
29
- name: 'vite-userscript-plugin',
30
- apply: 'build',
31
- config() {
32
- return {
33
- build: {
34
- lib: {
35
- entry: config.entry,
36
- name: config.metadata.name,
37
- formats: ['iife'],
38
- fileName: () => `${config.metadata.name}.js`
39
- },
40
- rollupOptions: {
41
- output: {
42
- exports: 'none',
43
- extend: true
44
- }
45
- }
46
- }
47
- };
48
- },
49
- configResolved(cfg) {
50
- pluginConfig = cfg;
51
- isBuildWatch = (cfg.build.watch ?? false);
52
- const { match, require, include, exclude, resource, connect } = config.metadata;
53
- config.metadata.match = removeDuplicates(match);
54
- config.metadata.require = removeDuplicates(require);
55
- config.metadata.include = removeDuplicates(include);
56
- config.metadata.exclude = removeDuplicates(exclude);
57
- config.metadata.resource = removeDuplicates(resource);
58
- config.metadata.connect = removeDuplicates(connect);
59
- },
60
- async transform(code, path) {
61
- const style = await css.minify(code, path);
62
- return css.add(config.entry, style.replace('\n', ''), path);
63
- },
64
- generateBundle(_, bundle) {
65
- for (const [_, file] of Object.entries(bundle)) {
66
- const styleModules = Object.keys(file.modules);
67
- css.merge(styleModules);
68
- }
69
- },
70
- async writeBundle(_, bundle) {
71
- for (const [fileName] of Object.entries(bundle)) {
72
- if (regexpScripts.test(fileName)) {
73
- const rootDir = pluginConfig.root;
74
- const outDir = pluginConfig.build.outDir;
75
- const outPath = resolve(rootDir, outDir, fileName);
76
- const hmrPath = resolve(rootDir, outDir, 'hmr.js');
77
- const proxyFilePath = resolve(rootDir, outDir, `${config.metadata.name}.proxy.user.js`);
78
- const userFilePath = resolve(rootDir, outDir, `${config.metadata.name}.user.js`);
79
- try {
80
- let source = readFileSync(outPath, 'utf8');
81
- // prettier-ignore
82
- config.metadata.grant = removeDuplicates(isBuildWatch
83
- ? grants
84
- : config.autoGrants ?? true
85
- ? defineGrants(source)
86
- : [...(config.metadata.grant ?? []), 'GM_addStyle', 'GM_info']);
87
- // prettier-ignore-end
88
- if (isBuildWatch) {
89
- const hmrFile = readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), 'hmr.js'), 'utf8');
90
- const hmrScript = await transform({
91
- file: hmrFile.replace('__PORT__', port.toString()),
92
- name: hmrPath,
93
- loader: 'js'
94
- });
95
- writeFileSync(hmrPath, hmrScript);
96
- writeFileSync(proxyFilePath, banner({
97
- ...config.metadata,
98
- require: [
99
- ...config.metadata.require,
100
- 'file://' + hmrPath,
101
- 'file://' + outPath
102
- ]
103
- }));
104
- }
105
- source = source.replace(template, `${css.inject()}`);
106
- source = await transform({
107
- file: source,
108
- name: fileName,
109
- loader: 'js'
110
- });
111
- writeFileSync(outPath, source);
112
- writeFileSync(userFilePath, `${banner(config.metadata)}\n\n${source}`);
113
- }
114
- catch (err) {
115
- console.log(err);
116
- }
117
- }
118
- }
119
- },
120
- buildEnd() {
121
- if (socketConnection) {
122
- socketConnection.sendUTF(JSON.stringify({
123
- message: 'reload'
124
- }));
125
- }
126
- }
127
- };
128
- }
129
- export { UserscriptPlugin };
130
- export default UserscriptPlugin;
1
+ import q from"get-port";import{readFileSync as C,writeFileSync as x}from"fs";import{createServer as F}from"http";import{dirname as T,resolve as M}from"path";import{fileURLToPath as $}from"url";import L from"sanitize-filename";import{server as V}from"websocket";function b(e){let t=[],r=Object.keys(e),n=Math.max(...r.map(o=>o.length))+1,m=o=>" ".repeat(n-o.length),p=(o,a)=>{let s=typeof a=="boolean";s&&!a||(a=s?"":m(o)+a.toString(),t.push(`// @${o}${a}`))};for(let[o,a]of Object.entries(e))if(Array.isArray(a))a.forEach(s=>p(o,s));else{if(a===void 0)continue;p(o,a)}return["// ==UserScript==",...t,"// ==/UserScript=="].join(`
2
+ `)}var P=new RegExp(/\.(tsx?|jsx?)$/),v=new RegExp(/\.(s?css|sass)$/),j='console.warn("__TEMPLATE__")',G=["unsafeWindow","window.onurlchange","window.focus","window.close","GM_setValue","GM_getValue","GM_deleteValue","GM_listValues","GM_setClipboard","GM_addStyle","GM_addElement","GM_addValueChangeListener","GM_removeValueChangeListener","GM_registerMenuCommand","GM_unregisterMenuCommand","GM_download","GM_getTab","GM_getTabs","GM_saveTab","GM_openInTab","GM_notification","GM_getResourceURL","GM_getResourceText","GM_xmlhttpRequest","GM_webRequest","GM_log","GM_info"];import{transformWithEsbuild as k}from"vite";function d(e){return[...new Set(Array.isArray(e)?e:e?[e]:[])]}async function _({file:e,name:t,loader:r}){let{code:n}=await k(e,t,{loader:r,minify:!0});return n}function R(e){let t=[];for(let r of G)e.indexOf(r)!==-1&&t.push(r);return t}var S=class{styles=new Map;async add(t,r){let n=await _({file:t,name:r,loader:"css"});return this.styles.set(r,n.replace(`
3
+ `,"")),""}inject(){let t=[...this.styles.values()].join("");if(!!t)return`GM_addStyle(\`${t}\`)`}merge(t){let r=[];for(let n of t){let m=this.styles.get(n);!m||r.push([n,m])}this.styles.clear(),r.forEach(n=>this.styles.set(...n))}},h=new S;function A(e){let t,r,n=null,m=null,p=F(),o=V;return new o({httpServer:p}).on("request",s=>{m=s.accept(null,s.origin)}),{name:"vite-userscript-plugin",apply:"build",config(){return{build:{lib:{entry:e.entry,name:e.metadata.name,formats:["iife"],fileName:()=>`${e.metadata.name}.js`},rollupOptions:{output:{exports:"none",extend:!0}}}}},configResolved(s){t=s,r=s.build.watch??!1;let{name:i,match:f,require:u,include:c,exclude:g,resource:y,connect:w}=e.metadata;e.metadata.name=L(i),e.metadata.match=d(f),e.metadata.require=d(u),e.metadata.include=d(c),e.metadata.exclude=d(g),e.metadata.resource=d(y),e.metadata.connect=d(w)},async transform(s,i){return v.test(i)?{code:await h.add(s,i)}:i.includes(e.entry)?{code:s+j}:null},generateBundle(s,i){for(let[f,u]of Object.entries(i)){let c=Object.keys(u.modules);h.merge(c)}},async writeBundle(s,i){!n&&r&&(n=await q(),p.listen(n));for(let[f]of Object.entries(i))if(P.test(f)){let u=t.root,c=t.build.outDir||"dist",g=M(u,c,f),y=M(T($(import.meta.url)),`hot-reload-${e.metadata.name}.js`),w=M(u,c,`${e.metadata.name}.proxy.user.js`),O=M(u,c,`${e.metadata.name}.user.js`);try{let l=C(g,"utf8");if(e.metadata.grant=d(r?G:e.autoGrants??!0?R(l):[...e.metadata.grant??[],"GM_addStyle","GM_info"]),r){let E=C(M(T($(import.meta.url)),"hot-reload.js"),"utf8"),U=await _({file:E.replace("__PORT__",n.toString()),name:y,loader:"js"});x(y,U),x(w,b({...e.metadata,require:[...e.metadata.require,"file://"+y,"file://"+g]}))}l=l.replace(j,`${h.inject()}`),l=await _({file:l,name:f,loader:"js"}),x(g,l),x(O,`${b(e.metadata)}
4
+
5
+ ${l}`)}catch(l){console.log(l)}}r||(p.close(),process.exit(0))},buildEnd(){m&&m.sendUTF(JSON.stringify({message:"reload"}))}}}var oe=A;export{A as UserscriptPlugin,oe as default};
package/package.json CHANGED
@@ -1,9 +1,14 @@
1
1
  {
2
2
  "name": "vite-userscript-plugin",
3
- "version": "0.5.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "types": "./dist/index.d.ts",
6
- "main": "./dist/index.js",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "exports": {
9
+ "require": "./dist/index.cjs",
10
+ "import": "./dist/index.js"
11
+ },
7
12
  "files": [
8
13
  "dist"
9
14
  ],
@@ -27,17 +32,18 @@
27
32
  "url": "https://github.com/crashmax-dev/vite-userscript-plugin/issues"
28
33
  },
29
34
  "dependencies": {
35
+ "get-port": "^6.1.2",
36
+ "sanitize-filename": "^1.6.3",
30
37
  "websocket": "^1.0.34"
31
38
  },
32
39
  "devDependencies": {
33
40
  "@types/websocket": "^1.0.5"
34
41
  },
35
42
  "peerDependencies": {
36
- "@types/tampermonkey": "latest"
43
+ "@types/tampermonkey": ">=4.0.0"
37
44
  },
38
45
  "scripts": {
39
- "dev": "tsc --build --watch",
40
- "build": "pnpm clean && tsc --build",
41
- "clean": "del-cli dist"
46
+ "dev": "tsup --watch",
47
+ "build": "tsup"
42
48
  }
43
49
  }
package/dist/banner.d.ts DELETED
@@ -1,2 +0,0 @@
1
- import type { MetadataConfig } from './types.js';
2
- export declare function banner(config: MetadataConfig): string;
package/dist/banner.js DELETED
@@ -1,30 +0,0 @@
1
- export function banner(config) {
2
- const metadata = [];
3
- const configKeys = Object.keys(config);
4
- const maxKeyLength = Math.max(...configKeys.map((key) => key.length)) + 1;
5
- const addSpaces = (str) => {
6
- return ' '.repeat(maxKeyLength - str.length);
7
- };
8
- const addMetadata = (key, value) => {
9
- const isBoolean = typeof value === 'boolean';
10
- if (isBoolean && !value)
11
- return;
12
- value = !isBoolean ? addSpaces(key) + value.toString() : '';
13
- metadata.push(`// @${key}${value}`);
14
- };
15
- for (const [key, value] of Object.entries(config)) {
16
- if (Array.isArray(value)) {
17
- value.forEach((value) => addMetadata(key, value));
18
- }
19
- else {
20
- if (value === undefined)
21
- continue;
22
- addMetadata(key, value);
23
- }
24
- }
25
- return [
26
- '// ==UserScript==',
27
- ...metadata,
28
- '// ==/UserScript=='
29
- ].join('\n');
30
- }
@@ -1,4 +0,0 @@
1
- export declare const regexpScripts: RegExp;
2
- export declare const regexpStyles: RegExp;
3
- export declare const template = "console.warn(\"__TEMPLATE__\")";
4
- export declare const grants: readonly ["unsafeWindow", "window.onurlchange", "window.focus", "window.close", "GM_setValue", "GM_getValue", "GM_deleteValue", "GM_listValues", "GM_setClipboard", "GM_addStyle", "GM_addElement", "GM_addValueChangeListener", "GM_removeValueChangeListener", "GM_registerMenuCommand", "GM_unregisterMenuCommand", "GM_download", "GM_getTab", "GM_getTabs", "GM_saveTab", "GM_openInTab", "GM_notification", "GM_getResourceURL", "GM_getResourceText", "GM_xmlhttpRequest", "GM_webRequest", "GM_log", "GM_info"];
package/dist/constants.js DELETED
@@ -1,32 +0,0 @@
1
- export const regexpScripts = new RegExp(/\.js/);
2
- export const regexpStyles = new RegExp(/\.css|\.sass|\.scss|\.less/);
3
- export const template = `console.warn("__TEMPLATE__")`;
4
- export const grants = [
5
- 'unsafeWindow',
6
- 'window.onurlchange',
7
- 'window.focus',
8
- 'window.close',
9
- 'GM_setValue',
10
- 'GM_getValue',
11
- 'GM_deleteValue',
12
- 'GM_listValues',
13
- 'GM_setClipboard',
14
- 'GM_addStyle',
15
- 'GM_addElement',
16
- 'GM_addValueChangeListener',
17
- 'GM_removeValueChangeListener',
18
- 'GM_registerMenuCommand',
19
- 'GM_unregisterMenuCommand',
20
- 'GM_download',
21
- 'GM_getTab',
22
- 'GM_getTabs',
23
- 'GM_saveTab',
24
- 'GM_openInTab',
25
- 'GM_notification',
26
- 'GM_getResourceURL',
27
- 'GM_getResourceText',
28
- 'GM_xmlhttpRequest',
29
- 'GM_webRequest',
30
- 'GM_log',
31
- 'GM_info'
32
- ];
package/dist/css.d.ts DELETED
@@ -1,11 +0,0 @@
1
- declare class CSS {
2
- private readonly styles;
3
- add(entry: string, code: string, path: string): {
4
- code: string;
5
- } | null;
6
- minify(file: string, name: string): Promise<string>;
7
- inject(): string | void;
8
- merge(modules: string[]): void;
9
- }
10
- declare const _default: CSS;
11
- export default _default;
package/dist/css.js DELETED
@@ -1,51 +0,0 @@
1
- import { regexpStyles, template } from './constants.js';
2
- import { transform } from './helpers.js';
3
- class CSS {
4
- constructor() {
5
- Object.defineProperty(this, "styles", {
6
- enumerable: true,
7
- configurable: true,
8
- writable: true,
9
- value: new Map()
10
- });
11
- }
12
- add(entry, code, path) {
13
- if (regexpStyles.test(path)) {
14
- this.styles.set(path, code);
15
- return {
16
- code: ''
17
- };
18
- }
19
- if (path.includes(entry)) {
20
- return {
21
- code: code + template
22
- };
23
- }
24
- return null;
25
- }
26
- async minify(file, name) {
27
- return await transform({
28
- file,
29
- name,
30
- loader: 'css'
31
- });
32
- }
33
- inject() {
34
- const styles = [...this.styles.values()].join('');
35
- if (!styles)
36
- return;
37
- return `GM_addStyle(\`${styles}\`)`;
38
- }
39
- merge(modules) {
40
- const styleModules = [];
41
- for (const module of modules) {
42
- const style = this.styles.get(module);
43
- if (!style)
44
- continue;
45
- styleModules.push([module, style]);
46
- }
47
- this.styles.clear();
48
- styleModules.forEach((value) => this.styles.set(...value));
49
- }
50
- }
51
- export default new CSS();
package/dist/helpers.d.ts DELETED
@@ -1,4 +0,0 @@
1
- import { Grants, Transform } from './types.js';
2
- export declare function removeDuplicates(arr: string | string[] | readonly string[] | undefined): any[];
3
- export declare function transform({ file, name, loader }: Transform): Promise<string>;
4
- export declare function defineGrants(code: string): Grants[];
package/dist/helpers.js DELETED
@@ -1,21 +0,0 @@
1
- import { transformWithEsbuild } from 'vite';
2
- import { grants } from './constants.js';
3
- export function removeDuplicates(arr) {
4
- return [...new Set(Array.isArray(arr) ? arr : arr ? [arr] : [])];
5
- }
6
- export async function transform({ file, name, loader }) {
7
- const { code } = await transformWithEsbuild(file, name, {
8
- loader,
9
- minify: true
10
- });
11
- return code;
12
- }
13
- export function defineGrants(code) {
14
- const definedGrants = [];
15
- for (const grant of grants) {
16
- if (code.indexOf(grant) !== -1) {
17
- definedGrants.push(grant);
18
- }
19
- }
20
- return definedGrants;
21
- }
package/dist/hmr.d.ts DELETED
@@ -1 +0,0 @@
1
- declare function HRM(): void;
package/dist/hmr.js DELETED
@@ -1,22 +0,0 @@
1
- "use strict";
2
- function HRM() {
3
- const ws = new WebSocket('ws://localhost:__PORT__');
4
- ws.addEventListener('open', () => {
5
- console.clear();
6
- const { script } = GM_info;
7
- console.group(`${script.name}@${script.version}`);
8
- console.log(GM_info);
9
- console.groupEnd();
10
- });
11
- ws.addEventListener('close', (event) => {
12
- console.warn('Socket is closed. Reconnect will be attempted in 1 second.', event.reason);
13
- setTimeout(HRM, 1000);
14
- });
15
- ws.addEventListener('error', () => {
16
- ws.close();
17
- });
18
- ws.addEventListener('message', () => {
19
- location.reload();
20
- });
21
- }
22
- HRM();
package/dist/types.d.ts DELETED
@@ -1,217 +0,0 @@
1
- import { grants } from './constants.js';
2
- export interface Transform {
3
- file: string;
4
- name: string;
5
- loader: 'js' | 'css';
6
- }
7
- export declare type RunAt = 'document-start' | 'document-body' | 'document-end' | 'document-idle' | 'context-menu';
8
- export declare type Grants = typeof grants[number];
9
- export declare type MetadataConfig = {
10
- [property: string]: string | boolean | number | string[] | undefined;
11
- /**
12
- * The name of the script.
13
- * Internationalization is done by adding an appendix naming the locale.
14
- */
15
- name: string;
16
- /**
17
- * Version of the script,
18
- * it can be used to check if a script has new versions. It is composed
19
- * of several parts, joined by `.` Each part must start with numbers,
20
- * and can be followed by alphabetic characters.
21
- */
22
- version: string;
23
- /**
24
- * A brief summary to describe the script.
25
- */
26
- description?: string;
27
- /**
28
- * The scripts author.
29
- */
30
- author?: string;
31
- /**
32
- * The script license.
33
- */
34
- license?: string;
35
- /**
36
- * The combination of `@namespace` and `@name` is the unique identifier for
37
- * a userscript. `@namespace` can be any string, for example the homepage
38
- * of a group of userscripts by the same author. If not provided
39
- * the `@namespace` falls back to an empty string ('').
40
- */
41
- namespace?: string;
42
- /**
43
- * The authors homepage that is used at the options page to link from
44
- * the scripts name to the given page. Please note that if the `@namespace`
45
- * tag starts with `https://` its content will be used for this too.
46
- */
47
- homepage?: string;
48
- /**
49
- * An update URL for the userscript.
50
- * Note:
51
- * - a `@version` tag is required to make update checks work.
52
- */
53
- updateURL?: string;
54
- /**
55
- * Defines the URL where the script will be downloaded from when an update was
56
- * detected. If the value none is used, then no update check will be done.
57
- */
58
- downloadURL?: string;
59
- /**
60
- * Defines the URL where the user can report issues and get personal support.
61
- */
62
- supportURL?: string;
63
- /**
64
- * Specify an icon for the script. Almost any image will work,
65
- * but a 32x32 pixel size is best. This value may be specified relative
66
- * to the URL the script itself is downloaded from.
67
- */
68
- icon?: string;
69
- icon64?: string;
70
- /**
71
- * Each `@include` and `@exclude` rule can be one of the following:
72
- * - a normal string
73
- * > If the string does not start or end with a slash (/),
74
- * > it will be used as a normal string.
75
- * > If there are wildcards (*), each of them matches any characters.
76
- * > e.g. https://www.google.com/* matches the following:
77
- * - https://www.google.com/
78
- * - https://www.google.com/any/subview
79
- * > but not the following:
80
- * - http://www.google.com/
81
- * - https://www.google.com.hk/
82
- * > If there is no wildcard in the string, the rule matches the entire URL.
83
- * > e.g. https://www.google.com/ matches only https://www.google.com/
84
- * > but not https://www.google.com/any/subview.
85
- * > The host part accepts .tld to match top level domain suffix.
86
- * > e.g. https://www.google.tld/ matches both https://www.google.com/
87
- * > and https://www.google.co.jp/.
88
- *
89
- * - a regular expression
90
- * > If the string starts and ends with a slash (/),
91
- * > it will be compiled as a regular expression.
92
- * > e.g. /\.google\.com[\.\/]/ matches the following:
93
- * - https://www.google.com/,
94
- * - https://www.google.com/any/subview
95
- * - http://www.google.com/
96
- * - https://www.google.com.hk/
97
- */
98
- include?: string[] | string;
99
- exclude?: string[] | string;
100
- /**
101
- * More or less equal to the `@include` tag.
102
- * You can get more information
103
- * [here](https://developer.chrome.com/docs/extensions/mv2/match_patterns/).
104
- *
105
- * Note:
106
- * - The `<all_urls>` statement is not yet supported and the scheme part also
107
- * accepts `http*://`.
108
- */
109
- match: string[] | string;
110
- /**
111
- * Points to a JavaScript file that is loaded and executed before the script
112
- * itself starts running.
113
- *
114
- * Note:
115
- * - The scripts loaded via `@require` and their "use strict" statements
116
- * might influence the userscript's strict mode!
117
- */
118
- require?: string[] | string;
119
- /**
120
- * Preloads resources that can by accessed
121
- * via `GM_getResourceURL` and `GM_getResourceText` by the script.
122
- */
123
- resource?: string[] | string;
124
- /**
125
- * This tag defines the domains (no top-level domains) including subdomains
126
- * which are allowed to be retrieved by `GM_xmlhttpRequest`
127
- *
128
- * - domains like tampermonkey.net (this will also allow all sub-domains)
129
- * - sub-domains i.e. safari.tampermonkey.net
130
- * - self to whitelist the domain the script is currently running at
131
- * - localhost to access the localhost
132
- * - 1.2.3.4 to connect to an IP address
133
- *
134
- * If it's not possible to declare all domains a userscript might connect
135
- * to then it's a good practice to do the following: ***Declare all known or
136
- * at least all common domains*** that might be connected by the script.
137
- * This way the confirmation dialog can be avoided for most of the users.
138
- *
139
- * Additionally add `@connect *` to the script. By doing so Tampermonkey will
140
- * still ask the user whether the next connection to a not mentioned domain
141
- * is allowed, but also ***offer a "Always allow all domains" button***.
142
- * If the user clicks at this button then all future requestswill
143
- * be permitted automatically.
144
- */
145
- connect?: string[] | string;
146
- /**
147
- * This tag makes the script running on the main pages, but not at iframes.
148
- * @default false
149
- */
150
- noframes?: boolean;
151
- /**
152
- * `@grant` is used to whitelist GM_* functions, the `unsafeWindow` object and
153
- * some powerful window functions. If no `@grant` tag is given TM guesses
154
- * the scripts needs.
155
- */
156
- grant?: Exclude<Grants, 'GM_addStyle' | 'GM_info'>[];
157
- /**
158
- * Defines the moment the script is injected. In opposition to other script
159
- * handlers, `@run-at` defines the first possible moment a script wants to
160
- * run. This means it may happen, that a script that uses the `@require` tag
161
- * may be executed after the document is already loaded, cause fetching the
162
- * required script took that long. Anyhow, all `DOMNodeInserted` and
163
- * `DOMContentLoaded` events that happended after the given injection
164
- * moment are cached and delivered to the script when it is injected.
165
- *
166
- * - `document-start`
167
- * The script will be injected as fast as possible.
168
- *
169
- * - `document-body`
170
- * The script will be injected if the body element exists.
171
- *
172
- * - `document-end`
173
- * The script will be injected when or after the `DOMContentLoaded` event
174
- * was dispatched.
175
- *
176
- * - `document-idle`
177
- * The script will be injected after the DOMContentLoaded event was
178
- * dispatched. This is the default value if no `@run-at` tag is given.
179
- *
180
- * - `context-menu`
181
- * The script will be injected if it is clicked at the browser context menu
182
- * (desktop Chrome-based browsers only).
183
- *
184
- * Note:
185
- * - all `@include` and `@exclude` statements will be ignored if this value
186
- * is used, but this may change in the future.
187
- *
188
- * @default 'document-idle'
189
- */
190
- 'run-at'?: RunAt;
191
- };
192
- export interface ServerConfig {
193
- /**
194
- * Server port.
195
- * @default 8000
196
- */
197
- port?: number;
198
- }
199
- export interface UserscriptPluginConfig {
200
- /**
201
- * Path of userscript entry.
202
- */
203
- entry: string;
204
- /**
205
- * Userscript header config.
206
- */
207
- metadata: MetadataConfig;
208
- /**
209
- * Import all `@grant` in development mode.
210
- * @default true
211
- */
212
- autoGrants?: boolean;
213
- /**
214
- * Server config (used in development mode for hot reloading).
215
- */
216
- server?: ServerConfig;
217
- }
package/dist/types.js DELETED
@@ -1 +0,0 @@
1
- export {};