Skip to content

Commit

Permalink
Merge pull request #52 from yakisova41/change-inject-method-userscript
Browse files Browse the repository at this point in the history
Change inject method userscript
  • Loading branch information
yakisova41 authored Apr 28, 2024
2 parents bfc78ff + fb4f2d9 commit 1aefd6c
Show file tree
Hide file tree
Showing 10 changed files with 233 additions and 186 deletions.
7 changes: 7 additions & 0 deletions dev/crx-monkey.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@
const config = {
importIconToUsercript: true,
userscriptInjectPage: ['src/contentScript/contentScript.ts'],
prettier: {
format: true,
options: {
parser: 'babel',
semi: true,
},
},
};

export default config;
17 changes: 9 additions & 8 deletions packages/crx-monkey/src/node/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { promises } from 'fs';
import { CrxMonkeyConfig } from './types';
import path from 'path';
import consola from 'consola';

const configFileNameMatch = ['crx-monkey.config.js'];

Expand All @@ -18,6 +19,10 @@ const defaultConfig: CrxMonkeyConfig = {
userScriptHeader: [],
importIconToUsercript: false,
userscriptInjectPage: [],
prettier: {
format: true,
options: { parser: 'babel' },
},
};

/**
Expand All @@ -34,11 +39,7 @@ async function getConfigPath(): Promise<string | null> {
} else {
const splited = dir.split('/');
if (splited.length === 1) {
reject(
new Error(
['Config file not found.', 'Please create "crx-monkey-config.js"'].join('\n'),
),
);
reject(new Error('Config file not found. Please create "crx-monkey-config.js"'));
} else {
splited.pop();
dir = splited.join('/');
Expand Down Expand Up @@ -130,11 +131,11 @@ export async function loadConfig(): Promise<CrxMonkeyConfig> {
resolve(configCahce);
});
} else {
throw new Error('Can not import config');
throw consola.error(new Error('Can not import config'));
}
})
.catch((e) => {
throw e;
throw consola.error(e);
});
});
}
Expand All @@ -148,6 +149,6 @@ export function getConfig() {
if (configCahce !== null) {
return configCahce;
} else {
throw new Error('Config has not been loaded. Please using "loadConfig()"');
throw consola.error(new Error('Config has not been loaded. Please using "loadConfig()"'));
}
}
134 changes: 134 additions & 0 deletions packages/crx-monkey/src/node/handlers/UserScript.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/**
* Common methods for userscript
*/
export class UsersScript {
/**
* Start conditional statement of if for branch of href.
* @param matches
*/
public static genarateCodeOfStartIfStatementByMatches(
matches: string[] | undefined,
excludes: string[] | undefined,
) {
let scriptContent = '';

let isAnd = false;

scriptContent = scriptContent + 'if (';

if (matches !== undefined) {
// Does the matches has multiple match href?
let isOrInMatches = false;

scriptContent = scriptContent + `${isAnd ? ' &&' : ''} ( `;

matches.forEach((matchPattern) => {
scriptContent =
scriptContent +
`${isOrInMatches ? ' ||' : ''}location.href.match('${matchPattern}') !== null`;

isOrInMatches = true;
});

scriptContent = scriptContent + ' )';

isAnd = true;
}

if (excludes !== undefined) {
// Does the excludes has multiple match href?
let isOrInExcludes = false;

scriptContent = scriptContent + `${isAnd ? ' &&' : ''} ( `;

excludes.forEach((matchPattern) => {
scriptContent =
scriptContent +
`${isOrInExcludes ? ' ||' : ''} location.href.match('${matchPattern}') === null`;

isOrInExcludes = true;
});

scriptContent = scriptContent + ' )';

isAnd = true;
}

// End conditional statement.
scriptContent = scriptContent + ') {\n';

return scriptContent;
}

/**
* File path convert to base64 and it included "=" convert to "$".
* @param filePath
* @returns
*/
public static convertFilePathToFuncName(filePath: string) {
return btoa(filePath).replaceAll('=', '$');
}

/**
* Generate code containing code to control timing of inject.
* @param run_at
* @param js
* @param css
* @returns
*/
public static generateCodeIncludingInjectTiming(
run_at: string | undefined,
js: string[] | undefined,
css: string[] | undefined,
) {
const syntaxs = {
document_end: {
start: "document.addEventListener('DOMContentLoaded', () => {",
end: '});',
},
document_idle: {
start: "document.addEventListener('DOMContentLoaded', () => {setTimeout(() => {",
end: '}, 1)});',
},
};

let scriptContent = '';
const runAt = run_at === undefined ? 'document_end' : run_at;

if (runAt === 'document_end') {
scriptContent = scriptContent + syntaxs['document_end'].start;
}

if (runAt === 'document_idle') {
scriptContent = scriptContent + syntaxs['document_idle'].start;
}

/**
* Code that executes the function corresponding to the file path.
*/
if (js !== undefined) {
js.forEach((filePath) => {
scriptContent = scriptContent + `${UsersScript.convertFilePathToFuncName(filePath)}();\n`;
});
}

/**
* Code that executes the function injecting css corresponding to the file path.
*/
if (css !== undefined) {
css.forEach((filePath) => {
scriptContent = scriptContent + `${UsersScript.convertFilePathToFuncName(filePath)}();\n`;
});
}

if (runAt === 'document_end') {
scriptContent = scriptContent + syntaxs['document_end'].end;
}

if (runAt === 'document_idle') {
scriptContent = scriptContent + syntaxs['document_idle'].end;
}

return scriptContent;
}
}
3 changes: 2 additions & 1 deletion packages/crx-monkey/src/node/handlers/build/Build.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import consola from 'consola';
import { BuildOptions, BuildResult, Plugin, build } from 'esbuild';
import { getConfig } from 'src/node/config';
import { ManifestFactory } from 'src/node/manifest-factory';
Expand All @@ -14,7 +15,7 @@ export class Build {

const config = getConfig();
if (config === undefined) {
throw new Error(['Config is undefined.'].join('\n'));
throw consola.error(new Error('Config is undefined.'));
}
this.config = config;
}
Expand Down
Loading

0 comments on commit 1aefd6c

Please sign in to comment.