Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support scriptcat background script #151

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 23 additions & 6 deletions packages/vite-plugin-monkey/src/node/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Plugin } from 'vite';
import type { Plugin, UserConfig } from 'vite';
import { resolvedOption } from './option';
import monkeyPluginList from './plugins';
import type { MonkeyOption } from './types';
Expand Down Expand Up @@ -30,7 +30,7 @@ export default (pluginOption: MonkeyOption): Plugin[] => {
async config(userConfig, { command }) {
const isServe = command == 'serve';

return {
const ret: UserConfig = {
resolve: {
alias: {
[finalPluginOption.clientAlias]: 'vite-plugin-monkey/dist/client',
Expand All @@ -56,16 +56,33 @@ export default (pluginOption: MonkeyOption): Plugin[] => {
cssCodeSplit: false,
minify: userConfig.build?.minify ?? false,
cssMinify: userConfig.build?.cssMinify ?? true,
rollupOptions: {
// serve pre-bundling need
input: finalPluginOption.entry,
},

sourcemap: false,

// TODO
// sourcemap: sourcemap,
},
};

// background or crontab script use lib
if (
finalPluginOption.userscript.background ||
finalPluginOption.userscript.crontab
) {
ret.build!.lib = {
entry: finalPluginOption.entry,
name: 'monkey',
formats: ['umd'],
fileName: 'monkey.user.js',
};
} else {
ret.build!.rollupOptions = {
// serve pre-bundling need
input: finalPluginOption.entry,
};
}

return ret;
},
};

Expand Down
4 changes: 4 additions & 0 deletions packages/vite-plugin-monkey/src/node/option.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,8 @@ export const resolvedOption = (
compatible,
sandbox,
unwrap = false,
background,
crontab,
} = pluginOption.userscript ?? {};

const { fileName = projectPkg.name + '.user.js' } = build;
Expand Down Expand Up @@ -281,6 +283,8 @@ export const resolvedOption = (
sandbox,
unwrap,
webRequest: webRequest.map((w) => JSON.stringify(w)),
background,
crontab,
},
clientAlias: pluginOption.clientAlias ?? '$',
entry: pluginOption.entry,
Expand Down
171 changes: 92 additions & 79 deletions packages/vite-plugin-monkey/src/node/plugins/finalBundle.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { OutputChunk, RollupOutput } from 'rollup';
import type { OutputChunk, RollupOutput, OutputAsset } from 'rollup';
import { Plugin, build } from 'vite';
import { lazyValue } from '../_lazy';
import {
Expand Down Expand Up @@ -57,91 +57,100 @@ export const finalBundlePlugin = (finalOption: FinalMonkeyOption): Plugin => {

const tlaIdentifier = lazyValue(() => findSafeTlaIdentifier(rawBundle));

const buildResult = (await build({
logLevel: 'error',
configFile: false,
esbuild: false,
plugins: [
{
name: 'mokey:mock',
enforce: 'pre',
resolveId(source, importer, options) {
if (!importer && options.isEntry) {
return '\0' + source;
}
const chunk = Object.values(rawBundle).find(
(chunk) =>
chunk.type == 'chunk' && source.endsWith(chunk.fileName),
) as OutputChunk | undefined;
if (chunk) {
return '\0' + source;
}
},
async load(id) {
if (!id.startsWith('\0')) return;
const bgScript =
finalOption.userscript.background || finalOption.userscript.crontab;
let buildBundle: (OutputChunk | OutputAsset)[];
if (bgScript) {
buildBundle = [fristEntryChunk!];
} else {
const buildResult = (await build({
logLevel: 'error',
configFile: false,
esbuild: false,
plugins: [
{
name: 'mokey:mock',
enforce: 'pre',
resolveId(source, importer, options) {
if (!importer && options.isEntry) {
return '\0' + source;
}
const chunk = Object.values(rawBundle).find(
(chunk) =>
chunk.type == 'chunk' && source.endsWith(chunk.fileName),
) as OutputChunk | undefined;
if (chunk) {
return '\0' + source;
}
},
async load(id) {
if (!id.startsWith('\0')) return;

if (id.endsWith(__entry_name)) {
return entryChunks
.map((a) => `import ${JSON.stringify(`./${a.fileName}`)};`)
.join('\n');
}
const [k, chunk] =
Object.entries(rawBundle).find(([k, chunk]) =>
id.endsWith(chunk.fileName),
) ?? [];
if (chunk && chunk.type == 'chunk' && k) {
usedModules.add(k);
if (!hasDynamicImport) {
const ch = transformTlaToIdentifier(
this,
chunk,
tlaIdentifier.value,
);
if (ch) return ch;
if (id.endsWith(__entry_name)) {
return entryChunks
.map((a) => `import ${JSON.stringify(`./${a.fileName}`)};`)
.join('\n');
}
return {
code: chunk.code,
map: chunk.map,
};
}
},
generateBundle(_, iifeBundle) {
if (hasDynamicImport) {
return;
}
Object.entries(iifeBundle).forEach(([k, chunk]) => {
transformIdentifierToTla(this, chunk, tlaIdentifier.value);
});
const [k, chunk] =
Object.entries(rawBundle).find(([k, chunk]) =>
id.endsWith(chunk.fileName),
) ?? [];
if (chunk && chunk.type == 'chunk' && k) {
usedModules.add(k);
if (!hasDynamicImport) {
const ch = transformTlaToIdentifier(
this,
chunk,
tlaIdentifier.value,
);
if (ch) return ch;
}
return {
code: chunk.code,
map: chunk.map,
};
}
},
generateBundle(_, iifeBundle) {
if (hasDynamicImport) {
return;
}
Object.entries(iifeBundle).forEach(([k, chunk]) => {
transformIdentifierToTla(this, chunk, tlaIdentifier.value);
});
},
},
},
],
build: {
write: false,
minify: false,
target: 'esnext',
rollupOptions: {
external(source) {
return source in finalOption.globalsPkg2VarName;
],
build: {
write: false,
minify: false,
target: 'esnext',
rollupOptions: {
external(source) {
return source in finalOption.globalsPkg2VarName;
},
output: {
globals: finalOption.globalsPkg2VarName,
},
},
output: {
globals: finalOption.globalsPkg2VarName,
lib: {
entry: __entry_name,
formats: bgScript
? undefined
: ([hasDynamicImport ? 'system' : 'iife'] as any),
name: hasDynamicImport ? undefined : '__expose__',
fileName: () => `__entry.js`,
},
},
lib: {
entry: __entry_name,
formats: [hasDynamicImport ? 'system' : 'iife'] as any,
name: hasDynamicImport ? undefined : '__expose__',
fileName: () => `__entry.js`,
},
},
})) as RollupOutput[];
usedModules.forEach((k) => {
if (fristEntryChunk != rawBundle[k]) {
delete rawBundle[k];
}
});
})) as RollupOutput[];
usedModules.forEach((k) => {
if (fristEntryChunk != rawBundle[k]) {
delete rawBundle[k];
}
});
buildBundle = buildResult[0].output.flat();
}

const buildBundle = buildResult[0].output.flat();
let finalJsCode = ``;
if (hasDynamicImport) {
const systemJsModules: string[] = [];
Expand Down Expand Up @@ -225,6 +234,10 @@ export const finalBundlePlugin = (finalOption: FinalMonkeyOption): Plugin => {
'build',
);

if (bgScript) {
finalJsCode += `\nreturn window.monkey;`;
}

const mergedCode = [comment, injectCssCode, finalJsCode]
.filter((s) => s)
.join(`\n\n`)
Expand Down
18 changes: 18 additions & 0 deletions packages/vite-plugin-monkey/src/node/userscript/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
GreaseRunAt,
} from './greasemonkey';
import { GreaseGrantValueList } from './greasemonkey';
import { ScriptcatUserScript } from './scriptcat';
import type {
AntifeatureType,
TamperGrant,
Expand All @@ -24,6 +25,7 @@ export type {
GreasemonkeyUserScript,
TampermonkeyUserScript,
ViolentmonkeyUserScript,
ScriptcatUserScript,
Format,
};

Expand Down Expand Up @@ -144,6 +146,7 @@ export type MonkeyUserScript = GreasemonkeyUserScript &
TampermonkeyUserScript &
ViolentmonkeyUserScript &
GreasyforkUserScript &
ScriptcatUserScript &
MergemonkeyUserScript;

export type FinalUserScript = {
Expand Down Expand Up @@ -183,6 +186,10 @@ export type FinalUserScript = {
'run-at'?: GreaseRunAt | TamperRunAt | ViolentRunAt;
grant: Set<string>;
$extra: [string, ...string[]][];

// scriptcat backgroud script
background?: boolean;
crontab?: string;
} & GreasyforkUserScript;

export const finalMonkeyOptionToComment = async (
Expand Down Expand Up @@ -244,6 +251,9 @@ export const finalMonkeyOptionToComment = async (
unwrap,
webRequest,
$extra,

background,
crontab,
} = userscript;
Object.entries({
namespace,
Expand Down Expand Up @@ -352,6 +362,14 @@ export const finalMonkeyOptionToComment = async (

attrList = defaultSortFormat(attrList);

if (background) {
attrList.push(['background']);
}

if (crontab) {
attrList.push(['crontab', crontab]);
}

let { align = 2 } = format;

if (align === true) {
Expand Down
Loading