Compare commits

..

22 Commits

Author SHA1 Message Date
ad5f5a3c15 updated help command output 2024-07-17 21:22:33 -05:00
8247860806 v1.1.6 added homepageUrl argument 2024-07-17 21:18:14 -05:00
zomo
9c4fe7d3ea updated dependencies 2024-06-19 09:47:25 -05:00
ec24ba6c3e v1.0.5
fixed watching for meta.json changes
2024-05-30 22:05:05 -05:00
d95a5533b1 fix: corrected dependencies 2023-07-19 23:28:45 -05:00
302b8feee4 fix: shebang insertion broke escaped characters 2023-07-19 23:25:10 -05:00
7df811852d fix: applied shebang to wrong file 2023-07-19 23:20:01 -05:00
d249b02def fix: updated build to include a shebang 2023-07-19 22:47:13 -05:00
5de6a97dbd homepage url hotfix 2023-02-09 18:57:56 -06:00
7e67128abe updated cli args and help screen 2023-02-09 17:24:40 -06:00
806a82baae updated readme 2023-01-11 15:47:18 -06:00
ab8ef4ff5b fixed watch mode 2023-01-11 15:36:34 -06:00
bf50d06d60 reduced indent length for readme file 2022-08-24 12:00:28 -05:00
1b4cb233e5 v1.1.1 2022-08-24 11:59:21 -05:00
c9183d3022 added more data to readme generation 2022-08-24 11:57:11 -05:00
7e24370186 cli arg aliases can only be 1 char 2022-08-24 11:21:52 -05:00
83570d9535 refactord paths.ts 2022-06-11 00:05:32 -05:00
29b40b4e43 changed function returns to objects 2022-06-10 23:04:18 -05:00
d00ddeb1e1 restructured build.ts and added a helpcommand 2022-06-10 22:50:59 -05:00
c51ca65751 Merge branch 'main' of git.zomo.dev:zomo/browser-scripts-builder into main 2022-06-10 21:59:10 -05:00
a10a35d662 built previous commit 2022-06-10 21:55:42 -05:00
85ff5851b5 added multilanguage support 2022-06-10 21:49:13 -05:00
21 changed files with 1711 additions and 1054 deletions

View File

@@ -4,91 +4,62 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const esbuild_1 = require("esbuild"); const esbuild_1 = require("esbuild");
const fs_1 = require("fs");
const paths_1 = require("./paths");
const readmeta_1 = __importDefault(require("./readmeta")); const readmeta_1 = __importDefault(require("./readmeta"));
const prettier_1 = require("prettier"); const prettier_1 = require("prettier");
function default_1(name, watchCallback, PrettierConfig, CLIArgs) { const main_1 = require("./main");
const promises_1 = require("fs/promises");
async function runBuild(name) {
//read meta file //read meta file
let [metaJson, metaString] = (0, readmeta_1.default)(name); let { meta, metaString } = (0, readmeta_1.default)(name);
let pathDist = (0, paths_1.DistPath)(name); let paths = main_1.AllPaths.script(name);
let result = runEsbuild({ let result = await runEsbuild({
entryPoints: [(0, paths_1.ScriptPath)(name).main], entryPoints: [paths.main],
outfile: pathDist, outfile: paths.dist,
target: 'esnext', target: 'esnext',
platform: 'node', platform: 'node',
format: 'esm', format: 'esm',
bundle: true, bundle: true,
minify: CLIArgs.minify, minify: main_1.CLIArgs.minify,
define: { define: {
UserScriptName: `'${metaJson.name}'`, UserScriptName: `'${meta.name}'`,
UserScriptNamespace: `'${metaJson.namespace}'`, UserScriptNamespace: `'${meta.namespace}'`,
UserScriptVersion: `'${metaJson.version}'`, UserScriptVersion: `'${meta.version}'`,
UserScriptDownloadURL: `'${metaJson.downloadURL}'`, UserScriptDownloadURL: `'${meta.downloadURL}'`,
UserScriptSupportURL: `'${metaJson.supportURL}'`, UserScriptSupportURL: `'${meta.supportURL}'`,
UserScriptHomepageURL: `'${metaJson.homepageURL}'`, UserScriptHomepageURL: `'${meta.homepageURL}'`,
}, },
}, result => { });
let error = runPostEsbuild(name, result, metaString, CLIArgs, PrettierConfig); let error = await postBuild(name, result, metaString);
watchCallback(metaJson, error); return {
}, CLIArgs); meta,
let error = runPostEsbuild(name, result, metaString, CLIArgs, PrettierConfig); error,
return [metaJson, error]; };
} }
exports.default = default_1; exports.default = runBuild;
function doErrorFile(pathError, pathOutFile, error) { async function runEsbuild(opts) {
if (error !== null) {
(0, fs_1.writeFileSync)(pathError, `${new Date().toISOString()}\n\n${error}`);
if ((0, fs_1.existsSync)(pathOutFile)) {
(0, fs_1.unlinkSync)(pathOutFile);
}
}
else if ((0, fs_1.existsSync)(pathError)) {
(0, fs_1.unlinkSync)(pathError);
}
}
function runEsbuild(opts, watchCallback, CLIArgs) {
opts.write = false; opts.write = false;
if (CLIArgs.watch) { try {
opts.watch = { let res = await (0, esbuild_1.build)(opts);
onRebuild(err, res) { return getResult(null, res);
if (err) { }
watchCallback({ catch (err) {
content: null, return getResult(err, null);
error: err.message, }
errorRaw: err, }
}); function getResult(error, result) {
} if (error) {
else if (res) { return {
let content = ''; content: null,
if (res.outputFiles && res.outputFiles.length > 0) { error: error.message,
content = res.outputFiles[0].text; errorRaw: error,
}
if (content === '') {
watchCallback({
content: null,
error: 'No output',
});
}
watchCallback({
content,
error: null,
});
}
else {
watchCallback({
content: null,
error: 'No result',
});
}
},
}; };
} }
try { else if (result) {
let res = (0, esbuild_1.buildSync)(opts);
let content = ''; let content = '';
if (res.outputFiles && res.outputFiles.length > 0) { if (result.outputFiles && result.outputFiles.length > 0) {
content = clearFilenameComments(res.outputFiles[0].text); content = result.outputFiles[0].text;
if (!main_1.CLIArgs.srccomment)
content = clearFilenameComments(content);
} }
if (content === '') { if (content === '') {
return { return {
@@ -101,37 +72,59 @@ function runEsbuild(opts, watchCallback, CLIArgs) {
error: null, error: null,
}; };
} }
catch (err) { else {
return { return {
content: null, content: null,
error: err.message, error: 'No result',
}; };
} }
} }
function runPostEsbuild(name, result, metaString, CLIArgs, PrettierConfig) { function clearFilenameComments(content) {
let regexp = new RegExp(`//\\s*${main_1.AllPaths.base.in}/.*(?:\\n|$)`, 'g');
return content.replace(regexp, '');
}
async function postBuild(name, result, metaString) {
let error = null; let error = null;
let path = (0, paths_1.ScriptPath)(name); let paths = main_1.AllPaths.script(name);
let pathDist = (0, paths_1.DistPath)(name); let PrettierConfig = (await (0, prettier_1.resolveConfig)(paths.dir)) ?? {};
if (result.error) { if (result.error) {
console.error(name, result.errorRaw || result.error); console.error(name, result.errorRaw || result.error);
error = result.error; error = result.error;
} }
else if (result.content) { else if (result.content) {
let content = metaString + result.content; let content = metaString + result.content;
if (CLIArgs.prettier) { if (main_1.CLIArgs.prettier) {
content = (0, prettier_1.format)(content, PrettierConfig); content = await (0, prettier_1.format)(content, {
...PrettierConfig,
parser: 'babel',
});
} }
(0, fs_1.writeFileSync)(pathDist, content); await (0, promises_1.writeFile)(paths.dist, content);
} }
else { else {
console.error(name, 'No output'); console.error(name, 'No output');
} }
doErrorFile(path.error, pathDist, error); await doErrorFile(name, error);
return error; return error;
} }
//remove all filename comments async function doErrorFile(name, error) {
function clearFilenameComments(content) { let paths = main_1.AllPaths.script(name);
let regexp = new RegExp(`//\\s*${paths_1.ScriptBase}/.*(?:\\n|$)`, 'g'); let content = `${new Date().toISOString()}\n\n${error}`;
return content.replace(regexp, ''); if (error !== null) {
await (0, promises_1.writeFile)(paths.error, content);
if (await existsFile(paths.dist)) {
await (0, promises_1.unlink)(paths.dist);
}
}
else if (await existsFile(paths.error)) {
await (0, promises_1.unlink)(paths.error);
}
}
function existsFile(path) {
return new Promise(resolve => {
(0, promises_1.stat)(path)
.then(() => resolve(true))
.catch(() => resolve(false));
});
} }
//# sourceMappingURL=build.js.map //# sourceMappingURL=build.js.map

View File

@@ -1 +1 @@
{"version":3,"file":"build.js","sourceRoot":"","sources":["../src/build.ts"],"names":[],"mappings":";;;;;AAAA,qCAA+D;AAC/D,2BAA0D;AAC1D,mCAA0D;AAE1D,0DAAiC;AACjC,uCAA0C;AAG1C,mBACI,IAAY,EACZ,aAAuE,EACvE,cAAuB,EACvB,OAAgB;IAEhB,gBAAgB;IAChB,IAAI,CAAC,QAAQ,EAAE,UAAU,CAAC,GAAG,IAAA,kBAAQ,EAAC,IAAI,CAAC,CAAA;IAC3C,IAAI,QAAQ,GAAG,IAAA,gBAAQ,EAAC,IAAI,CAAC,CAAA;IAE7B,IAAI,MAAM,GAAG,UAAU,CACnB;QACI,WAAW,EAAE,CAAC,IAAA,kBAAU,EAAC,IAAI,CAAC,CAAC,IAAI,CAAC;Q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UAAU,WAAW,CAAC,IAAY,EAAE,KAAoB;IACzD,IAAI,KAAK,GAAG,eAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IAEjC,IAAI,OAAO,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,OAAO,KAAK,EAAE,CAAA;IAEvD,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;QACjB,MAAM,IAAA,oBAAS,EAAC,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC,CAAA;QACrC,IAAI,MAAM,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;YAC/B,MAAM,IAAA,iBAAM,EAAC,KAAK,CAAC,IAAI,CAAC,CAAA;QAC5B,CAAC;IACL,CAAC;SAAM,IAAI,MAAM,UAAU,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC;QACvC,MAAM,IAAA,iBAAM,EAAC,KAAK,CAAC,KAAK,CAAC,CAAA;IAC7B,CAAC;AACL,CAAC;AAED,SAAS,UAAU,CAAC,IAAY;IAC5B,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE;QACzB,IAAA,eAAI,EAAC,IAAI,CAAC;aACL,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;aACzB,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAA;IACpC,CAAC,CAAC,CAAA;AACN,CAAC"}

View File

@@ -1,55 +1,175 @@
#!/usr/bin/env node
"use strict"; "use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) { var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod }; return (mod && mod.__esModule) ? mod : { "default": mod };
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.AllPaths = exports.CLIArgs = void 0;
const fs_1 = require("fs"); const fs_1 = require("fs");
const command_line_args_1 = __importDefault(require("command-line-args")); const command_line_args_1 = __importDefault(require("command-line-args"));
const prettier_1 = require("prettier");
const paths_1 = require("./paths");
const readmefile_1 = require("./readmefile"); const readmefile_1 = require("./readmefile");
const build_1 = __importDefault(require("./build")); const build_1 = __importDefault(require("./build"));
const CLIArgs = (0, command_line_args_1.default)([ const Path = __importStar(require("path"));
const paths_1 = __importDefault(require("./paths"));
const chokidar = __importStar(require("chokidar"));
exports.CLIArgs = (0, command_line_args_1.default)([
{ name: 'watch', alias: 'w', type: Boolean, defaultValue: false }, { name: 'watch', alias: 'w', type: Boolean, defaultValue: false },
{ name: 'minify', alias: 'm', type: Boolean, defaultValue: false }, { name: 'minify', alias: 'm', type: Boolean, defaultValue: false },
{ name: 'prettier', alias: 'p', type: Boolean, defaultValue: false }, { name: 'prettier', alias: 'p', type: Boolean, defaultValue: false },
{ name: 'srccomment', alias: 'c', type: Boolean, defaultValue: false },
{ name: 'readme', alias: 'r', type: Boolean, defaultValue: false },
{ name: 'url', alias: 'u', type: String, defaultValue: '' },
{ name: 'supporturl', alias: 's', type: String, defaultValue: '' },
{ name: 'homepageurl', alias: 'U', type: String, defaultValue: '' },
{ name: 'remotebranch', alias: 'b', type: String, defaultValue: '' },
{ name: 'in', alias: 'i', type: String, defaultValue: 'scripts' },
{ name: 'out', alias: 'o', type: String, defaultValue: 'dist' },
{ name: 'help', alias: 'h', type: Boolean },
]); ]);
exports.AllPaths = (0, paths_1.default)({
baseUrl: exports.CLIArgs.url || '',
supportUrl: exports.CLIArgs.supporturl || '',
homepageUrl: exports.CLIArgs.homepageurl || '',
remoteBranch: exports.CLIArgs.remotebranch || '',
inBase: exports.CLIArgs.in || 'scripts',
outBase: exports.CLIArgs.out || 'dist',
});
if (exports.CLIArgs.help) {
let command = '<command>';
if (process.argv.length > 0) {
command = Path.parse(process.argv[0]).name;
}
if (command.toLowerCase() === 'node' && process.argv.length > 1) {
let path = Path.relative(process.cwd(), process.argv[1]) || '.';
command = `${command} ${path}`;
}
console.log(`
Usage: ${command} [options]
options:
--watch
alias: -w
default: false
automatically recompile on save
--minify
alias: -m
default: false
minify output files
--prettier
alias: -p
default: false
prettify output files
--srccomment
alias: -c
default: false
include src file path comments in the output files, i.e. // scripts/example/main.ts
--readme
alias: -r
default: false
update the readme.md file in your directory to include links to each userscript
--url <url>
alias: -u <url>
default: ""
the base for urls used in the meta comments for @downloadURL
--supporturl <url>
alias: -s <url>
default: ""
the support url used in the meta comments for @supportURL
--homepageurl <url>
alias: -U <url>
default: ""
the support url used in the meta comments for @homepageURL
--remotebranch <name>
alias: -b <name>
default: ""
if included, the included base url will be treated as a git repo, and the support url is not required
--in
alias: -i
default: "scripts"
include src file path comments in the output files, i.e. // scripts/example/main.ts
--out
alias: -o
default: "dist"
include src file path comments in the output files, i.e. // scripts/example/main.ts
--help
alias: -h
show this help message
`);
process.exit(0);
}
//if package.json doesn't exist then there is no point in continuing //if package.json doesn't exist then there is no point in continuing
if (!(0, fs_1.existsSync)('package.json') || !(0, fs_1.lstatSync)('package.json').isFile()) { if (!(0, fs_1.existsSync)('package.json') || !(0, fs_1.lstatSync)('package.json').isFile()) {
console.error('package.json not found, unwilling to run'); console.error('package.json not found, unwilling to run');
process.exit(1); process.exit(1);
} }
//delete compiled scripts //delete compiled scripts or create output folder if it doesnt exist
(0, fs_1.readdirSync)(paths_1.DistBase).forEach(file => (0, fs_1.unlinkSync)(`${paths_1.DistBase}/${file}`)); if (!(0, fs_1.existsSync)(exports.AllPaths.base.out)) {
//read prettierrc file and make sure `babel` is the configured parser (0, fs_1.mkdirSync)(exports.AllPaths.base.out);
const PrettierConfig = (() => {
let config = prettier_1.resolveConfig.sync(process.cwd()) || {};
return {
...config,
parser: 'babel',
};
})();
//compile scripts
let scripts = (0, fs_1.readdirSync)(paths_1.ScriptBase);
let scriptMeta = [];
for (let name of scripts) {
let path = (0, paths_1.ScriptPath)(name);
if (!name.endsWith('_') &&
(0, fs_1.existsSync)(path.dir) &&
(0, fs_1.lstatSync)(path.dir).isDirectory() &&
(0, fs_1.existsSync)(path.main) &&
(0, fs_1.lstatSync)(path.main).isFile()) {
let id = scriptMeta.length;
function postWatchUpdate(meta, error) {
scriptMeta[id] = { meta, error };
console.log('WATCH', name, meta.version);
(0, readmefile_1.updateReadmeFile)(scriptMeta);
}
let [meta, error] = (0, build_1.default)(name, postWatchUpdate, PrettierConfig, CLIArgs);
scriptMeta[id] = { meta, error };
console.log(name, meta.version);
}
} }
(0, readmefile_1.updateReadmeFile)(scriptMeta); else {
console.log(`\nFinished Compiling\n${CLIArgs.watch ? 'Listening for Changes\n' : ''}`); (0, fs_1.readdirSync)(exports.AllPaths.base.out).forEach(file => (0, fs_1.unlinkSync)(`${exports.AllPaths.base.out}/${file}`));
}
//compile scripts
async function doCompile() {
let scripts = (0, fs_1.readdirSync)(exports.AllPaths.base.in);
let scriptMeta = [];
for (let name of scripts) {
let path = exports.AllPaths.script(name);
if (!name.endsWith('_') &&
(0, fs_1.existsSync)(path.dir) &&
(0, fs_1.lstatSync)(path.dir).isDirectory() &&
(0, fs_1.existsSync)(path.main) &&
(0, fs_1.lstatSync)(path.main).isFile()) {
let id = scriptMeta.length;
scriptMeta[id] = await (0, build_1.default)(name);
console.log(name, scriptMeta[id].meta.version);
var running = false;
async function update(eventName) {
if (running) {
return;
}
running = true;
scriptMeta[id] = await (0, build_1.default)(name);
console.log(`WATCH ${eventName}`, name, scriptMeta[id].meta.version);
if (exports.CLIArgs.readme)
(0, readmefile_1.updateReadmeFile)(scriptMeta);
running = false;
}
if (exports.CLIArgs.watch) {
chokidar.watch(path.dir).on('all', update);
}
}
}
return scriptMeta;
}
doCompile().then(scriptMeta => {
if (exports.CLIArgs.readme)
(0, readmefile_1.updateReadmeFile)(scriptMeta);
console.log(`\nFinished Compiling\n${exports.CLIArgs.watch ? 'Listening for Changes\n' : ''}`);
});
//# sourceMappingURL=main.js.map //# sourceMappingURL=main.js.map

View File

@@ -1 +1 @@
{"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":";;;;;AAAA,2BAAmE;AACnE,0EAA+C;AAC/C,uCAAwC;AACxC,mCAA0D;AAC1D,6CAA2D;AAC3D,oDAA8B;AAS9B,MAAM,OAAO,GAAG,IAAA,2BAAe,EAAC;IAC5B,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE;IACjE,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE;IAClE,EAAE,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE;CACvE,CAAY,CAAA;AAEb,oEAAoE;AACpE,IAAI,CAAC,IAAA,eAAU,EAAC,cAAc,CAAC,IAAI,CAAC,IAAA,cAAS,EAAC,cAAc,CAAC,CAAC,MAAM,EAAE,EAAE;IACpE,OAAO,CAAC,KAAK,CAAC,0CAA0C,CAAC,CAAA;IACzD,OAAO,CAAC,IAAI,CAAC,CAAC,C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gBAED,IAAI,eAAO,CAAC,MAAM;oBAAE,IAAA,6BAAgB,EAAC,UAAU,CAAC,CAAA;gBAChD,OAAO,GAAG,KAAK,CAAA;YACnB,CAAC;YAED,IAAI,eAAO,CAAC,KAAK,EAAE,CAAC;gBAChB,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,CAAA;YAC9C,CAAC;QACL,CAAC;IACL,CAAC;IACD,OAAO,UAAU,CAAA;AACrB,CAAC;AAED,SAAS,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE;IAC1B,IAAI,eAAO,CAAC,MAAM;QAAE,IAAA,6BAAgB,EAAC,UAAU,CAAC,CAAA;IAEhD,OAAO,CAAC,GAAG,CACP,yBACI,eAAO,CAAC,KAAK,CAAC,CAAC,CAAC,yBAAyB,CAAC,CAAC,CAAC,EAChD,EAAE,CACL,CAAA;AACL,CAAC,CAAC,CAAA"}

View File

@@ -1,20 +1,35 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.DistPath = exports.ScriptPath = exports.FileUrl = exports.SupportUrl = exports.DistBase = exports.ScriptBase = exports.RemoteBranch = exports.BaseUrl = void 0; function getAllPaths({ baseUrl, supportUrl, homepageUrl, remoteBranch, inBase, outBase, }) {
exports.BaseUrl = `https://git.zomo.dev/zomo/browser-scripts`; // generate links for remote git server
exports.RemoteBranch = 'main'; if (baseUrl != '' && remoteBranch != '') {
exports.ScriptBase = 'scripts'; if (supportUrl == '') {
exports.DistBase = 'dist'; supportUrl = `${baseUrl}/issues`;
exports.SupportUrl = `${exports.BaseUrl}/issues`; }
const FileUrl = (name) => `${exports.BaseUrl}/raw/branch/${exports.RemoteBranch}/${exports.DistBase}/${name}.user.js`; if (homepageUrl == '') {
exports.FileUrl = FileUrl; homepageUrl = baseUrl;
const ScriptPath = (name) => ({ }
dir: `${exports.ScriptBase}/${name}`, baseUrl = `${baseUrl}/raw/branch/${remoteBranch}/${outBase}`;
main: `${exports.ScriptBase}/${name}/main.ts`, }
meta: `${exports.ScriptBase}/${name}/meta.json`, return {
error: `${exports.ScriptBase}/${name}/error.log`, base: {
}); in: inBase,
exports.ScriptPath = ScriptPath; out: outBase,
const DistPath = (name) => `${exports.DistBase}/${name}.user.js`; },
exports.DistPath = DistPath; url: {
home: homepageUrl,
base: baseUrl,
support: supportUrl,
},
script: (name) => ({
dir: `${inBase}/${name}`,
main: `${inBase}/${name}/main.ts`,
meta: `${inBase}/${name}/meta.json`,
error: `${inBase}/${name}/error.log`,
dist: `${outBase}/${name}.user.js`,
url: `${baseUrl}/${name}.user.js`,
}),
};
}
exports.default = getAllPaths;
//# sourceMappingURL=paths.js.map //# sourceMappingURL=paths.js.map

View File

@@ -1 +1 @@
{"version":3,"file":"paths.js","sourceRoot":"","sources":["../src/paths.ts"],"names":[],"mappings":";;;AAAa,QAAA,OAAO,GAAG,2CAA2C,CAAA;AACrD,QAAA,YAAY,GAAG,MAAM,CAAA;AACrB,QAAA,UAAU,GAAG,SAAS,CAAA;AACtB,QAAA,QAAQ,GAAG,MAAM,CAAA;AAEjB,QAAA,UAAU,GAAG,GAAG,eAAO,SAAS,CAAA;AACtC,MAAM,OAAO,GAAG,CAAC,IAAY,EAAE,EAAE,CACpC,GAAG,eAAO,eAAe,oBAAY,IAAI,gBAAQ,IAAI,IAAI,UAAU,CAAA;AAD1D,QAAA,OAAO,WACmD;AAEhE,MAAM,UAAU,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,CAAC;IACzC,GAAG,EAAE,GAAG,kBAAU,IAAI,IAAI,EAAE;IAC5B,IAAI,EAAE,GAAG,kBAAU,IAAI,IAAI,UAAU;IACrC,IAAI,EAAE,GAAG,kBAAU,IAAI,IAAI,YAAY;IACvC,KAAK,EAAE,GAAG,kBAAU,IAAI,IAAI,YAAY;CAC3C,CAAC,CAAA;AALW,QAAA,UAAU,cAKrB;AAEK,MAAM,QAAQ,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,GAAG,gBAAQ,IAAI,IAAI,UAAU,CAAA;AAA1D,QAAA,QAAQ,YAAkD"} {"version":3,"file":"paths.js","sourceRoot":"","sources":["../src/paths.ts"],"names":[],"mappings":";;AAkBA,SAAwB,WAAW,CAAC,EAChC,OAAO,EACP,UAAU,EACV,WAAW,EACX,YAAY,EACZ,MAAM,EACN,OAAO,GACM;IACb,uCAAuC;IACvC,IAAI,OAAO,IAAI,EAAE,IAAI,YAAY,IAAI,EAAE,EAAE,CAAC;QACtC,IAAI,UAAU,IAAI,EAAE,EAAE,CAAC;YACnB,UAAU,GAAG,GAAG,OAAO,SAAS,CAAA;QACpC,CAAC;QAED,IAAI,WAAW,IAAI,EAAE,EAAE,CAAC;YACpB,WAAW,GAAG,OAAO,CAAA;QACzB,CAAC;QACD,OAAO,GAAG,GAAG,OAAO,eAAe,YAAY,IAAI,OAAO,EAAE,CAAA;IAChE,CAAC;IAED,OAAO;QACH,IAAI,EAAE;YACF,EAAE,EAAE,MAAM;YACV,GAAG,EAAE,OAAO;SACf;QACD,GAAG,EAAE;YACD,IAAI,EAAE,WAAW;YACjB,IAAI,EAAE,OAAO;YACb,OAAO,EAAE,UAAU;SACtB;QACD,MAAM,EAAE,CAAC,IAAY,EAAe,EAAE,CAAC,CAAC;YACpC,GAAG,EAAE,GAAG,MAAM,IAAI,IAAI,EAAE;YACxB,IAAI,EAAE,GAAG,MAAM,IAAI,IAAI,UAAU;YACjC,IAAI,EAAE,GAAG,MAAM,IAAI,IAAI,YAAY;YACnC,KAAK,EAAE,GAAG,MAAM,IAAI,IAAI,YAAY;YACpC,IAAI,EAAE,GAAG,OAAO,IAAI,IAAI,UAAU;YAClC,GAAG,EAAE,GAAG,OAAO,IAAI,IAAI,UAAU;SACpC,CAAC;KACL,CAAA;AACL,CAAC;AAvCD,8BAuCC"}

View File

@@ -26,11 +26,15 @@ function readmeDataErrorString(error) {
.join('\n'); .join('\n');
return `\n\n${error}`; return `\n\n${error}`;
} }
function readmeDataToString(readmeData) { function readmeDataToString(results) {
let { meta, error } = readmeData; let { meta, error } = results;
let errStr = error !== null ? '~~' : ''; let errStr = error !== null ? '~~' : '';
let errMsg = readmeDataErrorString(error); let errMsg = readmeDataErrorString(error);
return `- ${errStr}[${meta.name}](${meta.downloadURL})${errStr}${errMsg}`; return `
- ${errStr}[${meta.name}](${meta.downloadURL})${errStr}${errMsg}
- ${meta.namespace} ${meta.version}
- ${meta.description}
`.trim();
} }
function getReadmeFileName() { function getReadmeFileName() {
let files = (0, fs_1.readdirSync)('.'); let files = (0, fs_1.readdirSync)('.');

View File

@@ -1 +1 @@
{"version":3,"file":"readmefile.js","sourceRoot":"","sources":["../src/readmefile.ts"],"names":[],"mappings":";;;AAAA,2BAA6D;AAQ7D,SAAgB,gBAAgB,CAAC,QAAsB;IACnD,IAAI,UAAU,GAAG,iBAAiB,EAAE,CAAA;IACpC,IAAI,UAAU,KAAK,IAAI,EAAE;QACrB,IAAI,CAAC,WAAW,EAAE,SAAS,CAAC,GAAG,cAAc,CAAC,UAAU,CAAC,CAAA;QAEzD,IAAI,YAAY,GAAG,QAAQ,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QAE9D,IAAI,eAAe,GAAG;;;EAG5B,YAAY;2BACa,CAAA;QAEnB,IAAI,OAAO,GAAG,WAAW,GAAG,eAAe,GAAG,SAAS,CAAA;QACvD,IAAA,kBAAa,EAAC,UAAU,EAAE,OAAO,CAAC,CAAA;KACrC;AACL,CAAC;AAhBD,4CAgBC;AAED,SAAS,qBAAqB,CAAC,KAAoB;IAC/C,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,EAAE,CAAA;IAC7B,KAAK,GAAG,KAAK;SACR,KAAK,CAAC,IAAI,CAAC;SACX,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,IAAI,EAAE,CAAC;SAC1B,IAAI,CAAC,IA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AA;QAChD,UAAU,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,CAAA;QAC5C,WAAW,GAAG,eAAe,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;IAC9C,CAAC;IAED,IAAI,UAAU,CAAC,OAAO,EAAE,CAAC,MAAM,KAAK,CAAC;QAAE,UAAU,GAAG,EAAE,CAAA;;QACjD,UAAU,GAAG,UAAU,CAAC,OAAO,EAAE,GAAG,MAAM,CAAA;IAE/C,IAAI,WAAW,CAAC,SAAS,EAAE,CAAC,MAAM,KAAK,CAAC;QAAE,WAAW,GAAG,IAAI,CAAA;;QACvD,WAAW,GAAG,MAAM,GAAG,WAAW,CAAC,SAAS,EAAE,CAAA;IAEnD,OAAO,CAAC,UAAU,EAAE,WAAW,CAAC,CAAA;AACpC,CAAC"}

View File

@@ -1,8 +1,10 @@
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const fs_1 = require("fs"); const fs_1 = require("fs");
const paths_1 = require("./paths"); const main_1 = require("./main");
function default_1(name) { function readMeta(name) {
let paths = main_1.AllPaths.script(name);
let urls = main_1.AllPaths.url;
var meta = { var meta = {
name: name, name: name,
namespace: 'zomo.dev', namespace: 'zomo.dev',
@@ -17,12 +19,12 @@ function default_1(name) {
noframes: false, noframes: false,
grant: '', grant: '',
injectinto: '', injectinto: '',
downloadURL: (0, paths_1.FileUrl)(name), downloadURL: paths.url,
supportURL: paths_1.SupportUrl, supportURL: urls.support,
homepageURL: paths_1.BaseUrl, homepageURL: urls.home,
unwrap: false, unwrap: false,
}; };
let metaPath = (0, paths_1.ScriptPath)(name).meta; let metaPath = paths.meta;
if ((0, fs_1.existsSync)(metaPath) && (0, fs_1.lstatSync)(metaPath).isFile()) { if ((0, fs_1.existsSync)(metaPath) && (0, fs_1.lstatSync)(metaPath).isFile()) {
try { try {
let args = JSON.parse((0, fs_1.readFileSync)(metaPath).toString()); let args = JSON.parse((0, fs_1.readFileSync)(metaPath).toString());
@@ -50,9 +52,9 @@ function default_1(name) {
injectinto: 'inject-into', injectinto: 'inject-into',
excludematch: 'exclude-match', excludematch: 'exclude-match',
}; };
return [ return {
meta, meta,
`// ==UserScript== metaString: `// ==UserScript==
${Object.keys(meta) ${Object.keys(meta)
.filter(key => { .filter(key => {
let val = meta[key]; let val = meta[key];
@@ -71,22 +73,35 @@ ${Object.keys(meta)
: key; : key;
key_str = key_str.padEnd(12, ' '); key_str = key_str.padEnd(12, ' ');
if (typeof val === 'boolean') { if (typeof val === 'boolean') {
//bool
if (val) if (val)
return `// @${key_str}`; return `// @${key_str}`;
} }
else if (typeof val === 'string') { else if (typeof val === 'string') {
//string
return `// @${key_str} ${val}`; return `// @${key_str} ${val}`;
} }
else if (Array.isArray(val)) { else if (Array.isArray(val)) {
//multiple
return val.map(v => `// @${key_str} ${v}`).join('\n'); return val.map(v => `// @${key_str} ${v}`).join('\n');
} }
else if (typeof val === 'object') {
//multilingual
let langs = val;
return Object.keys(langs)
.map(lang => {
let langStr = lang === 'default' ? '' : `:${lang}`;
return `// @${key_str}${langStr} ${langs[lang]}`;
})
.join('\n');
}
return ''; return '';
}) })
.filter(l => l.length) .filter(l => l.length)
.join('\n')} .join('\n')}
// ==/UserScript== // ==/UserScript==
`, `,
]; };
} }
exports.default = default_1; exports.default = readMeta;
//# sourceMappingURL=readmeta.js.map //# sourceMappingURL=readmeta.js.map

View File

@@ -1 +1 @@
{"version":3,"file":"readmeta.js","sourceRoot":"","sources":["../src/readmeta.ts"],"names":[],"mappings":";;AAAA,2BAAwD;AACxD,mCAAkE;AAOlE,mBAAyB,IAAY;IACjC,IAAI,IAAI,GAAuB;QAC3B,IAAI,EAAE,IAAI;QACV,SAAS,EAAE,UAAU;QACrB,KAAK,EAAE,EAAE;QACT,YAAY,EAAE,EAAE;QAChB,OAAO,EAAE,OAAO;QAChB,WAAW,EAAE,EAAE;QACf,IAAI,EAAE,EAAE;QACR,OAAO,EAAE,EA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OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;gBAC5B,UAAU;gBACV,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,OAAO,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;YACzD,CAAC;iBAAM,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;gBACjC,cAAc;gBACd,IAAI,KAAK,GAAG,GAAG,CAAA;gBACf,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC;qBACpB,GAAG,CAAC,IAAI,CAAC,EAAE;oBACR,IAAI,OAAO,GAAG,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAA;oBAClD,OAAO,OAAO,OAAO,GAAG,OAAO,IAAI,KAAK,CAAC,IAAI,CAAC,EAAE,CAAA;gBACpD,CAAC,CAAC;qBACD,IAAI,CAAC,IAAI,CAAC,CAAA;YACnB,CAAC;YAED,OAAO,EAAE,CAAA;QACb,CAAC,CAAC;aACD,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC;aACrB,IAAI,CAAC,IAAI,CAAC;;CAEd;KACI,CAAA;AACL,CAAC;AAvGD,2BAuGC"}

View File

@@ -1,103 +1,123 @@
{ {
"$schema": "http://json-schema.org/draft-04/schema#", "$schema": "http://json-schema.org/draft-04/schema",
"$id": "https://git.zomo.dev/zomo/browser-scripts-builder/raw/branch/main/meta.schema.json",
"title": "UserScriptMeta", "title": "UserScriptMeta",
"description": "UserScript metadata fields, from https://violentmonkey.github.io/api/metadata-block/",
"type": "object", "type": "object",
"properties": { "properties": {
"$schema": {
"type": "string",
"description": "Read https://violentmonkey.github.io/api/metadata-block/ for more examples and information about metadata"
},
"name": { "name": {
"description": "Script Name", "description": "The name of the script, shown in script list and menus",
"type": "string" "type": ["string", "object"],
"properties": {
"default": {
"type": "string"
}
},
"additionalProperties": {
"type": "string"
},
"required": ["default"]
}, },
"namespace": { "namespace": {
"description": "Author namespace", "description": "The combination of namespace and name is the unique identifier for a userscript",
"type": "string" "type": "string"
}, },
"match": { "match": {
"description": "", "description": "Define rules to decide whether a script should be executed",
"type": ["string", "array"], "type": ["string", "array"],
"minItems": 1,
"uniqueItems": true, "uniqueItems": true,
"items": { "items": {
"type": "string" "type": "string"
} }
}, },
"excludematch": { "excludematch": {
"description": "", "description": "Define rules to decide whether a script should be executed",
"type": ["string", "array"], "type": ["string", "array"],
"minItems": 1,
"uniqueItems": true, "uniqueItems": true,
"items": { "items": {
"type": "string" "type": "string"
} }
}, },
"version": { "version": {
"description": "", "description": "Version of the script, it can be used to check if a script has new versions",
"type": "string" "type": "string"
}, },
"description": { "description": {
"description": "", "description": "A brief summary to describe the script",
"type": "string" "type": ["string", "object"],
"properties": {
"default": {
"type": "string"
}
},
"additionalProperties": {
"type": "string"
},
"required": ["default"]
}, },
"icon": { "icon": {
"description": "", "description": "Specify an icon for the script",
"type": "string" "type": "string"
}, },
"require": { "require": {
"description": "", "description": "Require another script to execute before the current one\n\nThe value is the URL to the required script, which may be relative to the URL the script is being installed from",
"type": ["string", "array"], "type": ["string", "array"],
"minItems": 1,
"uniqueItems": true, "uniqueItems": true,
"items": { "items": {
"type": "string" "type": "string"
} }
}, },
"resource": { "resource": {
"description": "", "description": "Static resources that can be accessed in the script by GM_getResourceText and GM_getResourceURL\n\nThe value is composed of two parts, joined with one or more white spaces\n\nThe first part is the name of the resource, no white space is allowed in it\n\nThe second part is the URL to the resource, which may be relative to the URL the script is being installed from",
"type": ["string", "array"], "type": ["string", "array"],
"minItems": 1,
"uniqueItems": true, "uniqueItems": true,
"items": { "items": {
"type": "string" "type": "string"
} }
}, },
"runat": { "runat": {
"description": "", "description": "Decide when the script will execute\n\ndocument-end: (default) The script executes when DOMContentLoaded is fired\n\ndocument-start: The script executes as soon as possible\n\ndocument-idle: The script executes after DOMContentLoaded is fired, ensuring other resources like images are loaded",
"type": "string", "type": "string",
"enum": ["document-start", "document-end", "document-idle"] "enum": ["document-end", "document-idle", "document-start"]
}, },
"noframes": { "noframes": {
"description": "", "description": "When present, the script will execute only in top level document, but not in nested frames",
"type": "boolean" "type": "boolean"
}, },
"grant": { "grant": {
"description": "", "description": "Specify which special APIs should be granted and can be used when the script executes\n\nIf nothing is present, \"none\" is assumed\n\nAny GM_ or GM. function used, including window.close and window.focus",
"type": ["string", "array"], "type": ["string", "array"],
"minItems": 1,
"uniqueItems": true, "uniqueItems": true,
"items": { "items": {
"type": "string" "type": "string"
} }
}, },
"injectinto": { "injectinto": {
"description": "", "description": "Decide which context the script will be injected into\n\npage: Inject into context of the web page\nIn this mode, unsafeWindow refers to the window object, allowing the script to access JavaScript objects of the web page, just like normal page scripts can\n\ncontent: Inject into context of content scripts.\nIn this mode, unsafeWindow refers to the global object in content script. As a result, the script can access and modify the page's DOM, but cannot access JavaScript objects of the web page.\n\nauto: Try to inject into context of the web page. If blocked by CSP rules, inject as a content script.",
"type": "string", "type": "string",
"enum": ["page", "content", "auto"] "enum": ["page", "content", "auto"]
}, },
"downloadURL": { "downloadURL": {
"description": "", "description": "The URL the script can be downloaded from",
"type": "string" "type": "string"
}, },
"supportURL": { "supportURL": {
"description": "", "description": "If supplied, the question mark icon in the user scripts list will link to this.",
"type": "string" "type": "string"
}, },
"homepageURL": { "homepageURL": {
"description": "", "description": "If supplied, the home icon in the user scripts list will link to this.",
"type": "string" "type": "string"
}, },
"unwrap": { "unwrap": {
"description": "", "description": "If supplied, the script will be injected as is into the global scope of the page, i.e. without our standard wrapper like window.VMxxx=function(){...}.\n\nThe @grant key is ignored so the script won't have access to GM.* or GM_* API. ",
"type": "boolean" "type": "boolean"
} }
}, },
"additionalProperties": false,
"required": ["name", "namespace", "version"] "required": ["name", "namespace", "version"]
} }

View File

@@ -1,6 +1,6 @@
{ {
"name": "browser-scripts-builder", "name": "browser-scripts-builder",
"version": "1.0.0", "version": "1.1.6",
"description": "", "description": "",
"main": "./lib/main.js", "main": "./lib/main.js",
"module": "./lib/main.js", "module": "./lib/main.js",
@@ -9,7 +9,7 @@
}, },
"scripts": { "scripts": {
"prettier": "prettier --write .", "prettier": "prettier --write .",
"build": "npm run prettier && tsc", "build": "npm run prettier && tsc && node -e \"(async () => { const p = 'lib/main.js'; await fs.promises.writeFile(p, '#!/usr/bin/env node\\n' + await fs.promises.readFile(p)); await fs.promises.chmod(p, 754); })()\"",
"test": "node ./test/test.mjs" "test": "node ./test/test.mjs"
}, },
"repository": { "repository": {
@@ -19,15 +19,16 @@
"author": "", "author": "",
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
"chokidar": "^3.6.0",
"command-line-args": "^5.2.1", "command-line-args": "^5.2.1",
"esbuild": "^0.14.42", "esbuild": "^0.21.5",
"typescript": "^4.7.3", "prettier": "^3.3.2"
"prettier": "^2.6.2"
}, },
"devDependencies": { "devDependencies": {
"@types/command-line-args": "^5.2.0", "@types/command-line-args": "^5.2.3",
"@types/node": "^17.0.40", "@types/node": "^20.14.5",
"@types/prettier": "^2.6.3", "@types/prettier": "^2.7.3",
"eslint": "^8.17.0" "eslint": "^9.5.0",
"typescript": "^5.4.5"
} }
} }

1561
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -4,6 +4,8 @@ builder for [browser-scripts](https://git.zomo.dev/zomo/browser-scripts)
## Source File Structure ## Source File Structure
note: if `package.json` is not present, running the command is presumed to be a mistake and will refuse to run
```text ```text
Root Root
├───<package.json/etc> ├───<package.json/etc>
@@ -39,11 +41,51 @@ Root
```text ```text
--watch --watch
alias: -w alias: -w
default: false
automatically recompile on save automatically recompile on save
--minify --minify
alias: -m alias: -m
default: false
minify output files minify output files
--prettier --prettier
alias: -p alias: -p
default: false
prettify output files prettify output files
--srccomment
alias: -c
default: false
include src file path comments in the output files, i.e. // scripts/example/main.ts
--readme
alias: -r
default: false
update the readme.md file in your directory to include links to each userscript
--url <url>
alias: -u <url>
default: ""
the base for urls used in the meta comments for @downloadURL
--supporturl <url>
alias: -s <url>
default: ""
the support url used in the meta comments for @supportURL
--homepageurl <url>
alias: -U <url>
default: ""
the support url used in the meta comments for @homepageURL
--remotebranch <name>
alias: -b <name>
default: ""
if included, the included base url will be treated as a git repo, and the support url is not required
--in
alias: -i
default: "scripts"
include src file path comments in the output files, i.e. // scripts/example/main.ts
--out
alias: -o
default: "dist"
include src file path comments in the output files, i.e. // scripts/example/main.ts
--help
alias: -h
show this help message
``` ```

View File

@@ -1,80 +1,47 @@
import { buildSync, BuildFailure, BuildOptions } from 'esbuild' import { BuildFailure, BuildOptions, BuildResult, build } from 'esbuild'
import { existsSync, writeFileSync, unlinkSync } from 'fs'
import { DistPath, ScriptBase, ScriptPath } from './paths'
import { UserScriptMetaFull } from './types' import { UserScriptMetaFull } from './types'
import readMeta from './readmeta' import readMeta from './readmeta'
import { format, Options } from 'prettier' import { format, resolveConfig } from 'prettier'
import { CLIArgs } from './main' import { AllPaths, CLIArgs } from './main'
import { writeFile, stat, unlink } from 'fs/promises'
export default function ( export interface runBuildResult {
name: string, meta: UserScriptMetaFull
watchCallback: (meta: UserScriptMetaFull, error: string | null) => void, error: string | null
PrettierConfig: Options,
CLIArgs: CLIArgs
): [UserScriptMetaFull, string | null] {
//read meta file
let [metaJson, metaString] = readMeta(name)
let pathDist = DistPath(name)
let result = runEsbuild(
{
entryPoints: [ScriptPath(name).main],
outfile: pathDist,
target: 'esnext',
platform: 'node',
format: 'esm',
bundle: true,
minify: CLIArgs.minify,
define: {
UserScriptName: `'${metaJson.name}'`,
UserScriptNamespace: `'${metaJson.namespace}'`,
UserScriptVersion: `'${metaJson.version}'`,
UserScriptDownloadURL: `'${metaJson.downloadURL}'`,
UserScriptSupportURL: `'${metaJson.supportURL}'`,
UserScriptHomepageURL: `'${metaJson.homepageURL}'`,
},
},
result => {
let error = runPostEsbuild(
name,
result,
metaString,
CLIArgs,
PrettierConfig
)
watchCallback(metaJson, error)
},
CLIArgs
)
let error = runPostEsbuild(
name,
result,
metaString,
CLIArgs,
PrettierConfig
)
return [metaJson, error]
} }
function doErrorFile( export default async function runBuild(name: string) {
pathError: string, //read meta file
pathOutFile: string, let { meta, metaString } = readMeta(name)
error: string | null let paths = AllPaths.script(name)
) {
if (error !== null) {
writeFileSync(pathError, `${new Date().toISOString()}\n\n${error}`)
if (existsSync(pathOutFile)) { let result = await runEsbuild({
unlinkSync(pathOutFile) entryPoints: [paths.main],
} outfile: paths.dist,
} else if (existsSync(pathError)) {
unlinkSync(pathError) target: 'esnext',
platform: 'node',
format: 'esm',
bundle: true,
minify: CLIArgs.minify,
define: {
UserScriptName: `'${meta.name}'`,
UserScriptNamespace: `'${meta.namespace}'`,
UserScriptVersion: `'${meta.version}'`,
UserScriptDownloadURL: `'${meta.downloadURL}'`,
UserScriptSupportURL: `'${meta.supportURL}'`,
UserScriptHomepageURL: `'${meta.homepageURL}'`,
},
})
let error = await postBuild(name, result, metaString)
return {
meta,
error,
} }
} }
@@ -84,51 +51,29 @@ interface RunEsbuildResult {
errorRaw?: BuildFailure errorRaw?: BuildFailure
} }
function runEsbuild( async function runEsbuild(opts: BuildOptions): Promise<RunEsbuildResult> {
opts: BuildOptions,
watchCallback: (result: RunEsbuildResult) => void,
CLIArgs: CLIArgs
): RunEsbuildResult {
opts.write = false opts.write = false
if (CLIArgs.watch) {
opts.watch = {
onRebuild(err, res) {
if (err) {
watchCallback({
content: null,
error: (err as BuildFailure).message,
errorRaw: err,
})
} else if (res) {
let content = ''
if (res.outputFiles && res.outputFiles.length > 0) {
content = res.outputFiles[0].text
}
if (content === '') {
watchCallback({
content: null,
error: 'No output',
})
}
watchCallback({
content,
error: null,
})
} else {
watchCallback({
content: null,
error: 'No result',
})
}
},
}
}
try { try {
let res = buildSync(opts) let res = await build(opts)
return getResult(null, res)
} catch (err) {
return getResult(err as BuildFailure, null)
}
}
function getResult(error: BuildFailure | null, result: BuildResult | null) {
if (error) {
return {
content: null,
error: (error as BuildFailure).message,
errorRaw: error,
}
} else if (result) {
let content = '' let content = ''
if (res.outputFiles && res.outputFiles.length > 0) { if (result.outputFiles && result.outputFiles.length > 0) {
content = clearFilenameComments(res.outputFiles[0].text) content = result.outputFiles[0].text
if (!CLIArgs.srccomment) content = clearFilenameComments(content)
} }
if (content === '') { if (content === '') {
return { return {
@@ -140,24 +85,28 @@ function runEsbuild(
content, content,
error: null, error: null,
} }
} catch (err) { } else {
return { return {
content: null, content: null,
error: (err as BuildFailure).message, error: 'No result',
} }
} }
} }
function runPostEsbuild( function clearFilenameComments(content: string): string {
let regexp = new RegExp(`//\\s*${AllPaths.base.in}/.*(?:\\n|$)`, 'g')
return content.replace(regexp, '')
}
async function postBuild(
name: string, name: string,
result: RunEsbuildResult, result: RunEsbuildResult,
metaString: string, metaString: string
CLIArgs: CLIArgs,
PrettierConfig: Options
) { ) {
let error: string | null = null let error: string | null = null
let path = ScriptPath(name) let paths = AllPaths.script(name)
let pathDist = DistPath(name)
let PrettierConfig = (await resolveConfig(paths.dir)) ?? {}
if (result.error) { if (result.error) {
console.error(name, result.errorRaw || result.error) console.error(name, result.errorRaw || result.error)
@@ -165,20 +114,40 @@ function runPostEsbuild(
} else if (result.content) { } else if (result.content) {
let content = metaString + result.content let content = metaString + result.content
if (CLIArgs.prettier) { if (CLIArgs.prettier) {
content = format(content, PrettierConfig) content = await format(content, {
...PrettierConfig,
parser: 'babel',
})
} }
writeFileSync(pathDist, content) await writeFile(paths.dist, content)
} else { } else {
console.error(name, 'No output') console.error(name, 'No output')
} }
doErrorFile(path.error, pathDist, error) await doErrorFile(name, error)
return error return error
} }
//remove all filename comments async function doErrorFile(name: string, error: string | null) {
function clearFilenameComments(content: string): string { let paths = AllPaths.script(name)
let regexp = new RegExp(`//\\s*${ScriptBase}/.*(?:\\n|$)`, 'g')
return content.replace(regexp, '') let content = `${new Date().toISOString()}\n\n${error}`
if (error !== null) {
await writeFile(paths.error, content)
if (await existsFile(paths.dist)) {
await unlink(paths.dist)
}
} else if (await existsFile(paths.error)) {
await unlink(paths.error)
}
}
function existsFile(path: string): Promise<boolean> {
return new Promise(resolve => {
stat(path)
.then(() => resolve(true))
.catch(() => resolve(false))
})
} }

View File

@@ -1,22 +1,122 @@
import { existsSync, lstatSync, readdirSync, unlinkSync } from 'fs' import { existsSync, lstatSync, mkdirSync, readdirSync, unlinkSync } from 'fs'
import commandLineArgs from 'command-line-args' import commandLineArgs from 'command-line-args'
import { resolveConfig } from 'prettier' import { updateReadmeFile } from './readmefile'
import { DistBase, ScriptBase, ScriptPath } from './paths' import runBuild, { runBuildResult } from './build'
import { readmeData, updateReadmeFile } from './readmefile' import * as Path from 'path'
import runBuild from './build' import getAllPaths from './paths'
import { UserScriptMetaFull } from './types' import * as chokidar from 'chokidar'
export interface CLIArgs { export interface CLIArgsT {
watch: boolean watch: boolean
minify: boolean minify: boolean
prettier: boolean prettier: boolean
srccomment: boolean
readme: boolean
url?: string
supporturl?: string
homepageurl?: string
remotebranch?: string
in?: string
out?: string
help?: boolean
src?: string
} }
const CLIArgs = commandLineArgs([ export const CLIArgs = commandLineArgs([
{ name: 'watch', alias: 'w', type: Boolean, defaultValue: false }, { name: 'watch', alias: 'w', type: Boolean, defaultValue: false },
{ name: 'minify', alias: 'm', type: Boolean, defaultValue: false }, { name: 'minify', alias: 'm', type: Boolean, defaultValue: false },
{ name: 'prettier', alias: 'p', type: Boolean, defaultValue: false }, { name: 'prettier', alias: 'p', type: Boolean, defaultValue: false },
]) as CLIArgs { name: 'srccomment', alias: 'c', type: Boolean, defaultValue: false },
{ name: 'readme', alias: 'r', type: Boolean, defaultValue: false },
{ name: 'url', alias: 'u', type: String, defaultValue: '' },
{ name: 'supporturl', alias: 's', type: String, defaultValue: '' },
{ name: 'homepageurl', alias: 'U', type: String, defaultValue: '' },
{ name: 'remotebranch', alias: 'b', type: String, defaultValue: '' },
{ name: 'in', alias: 'i', type: String, defaultValue: 'scripts' },
{ name: 'out', alias: 'o', type: String, defaultValue: 'dist' },
{ name: 'help', alias: 'h', type: Boolean },
]) as CLIArgsT
export const AllPaths = getAllPaths({
baseUrl: CLIArgs.url || '',
supportUrl: CLIArgs.supporturl || '',
homepageUrl: CLIArgs.homepageurl || '',
remoteBranch: CLIArgs.remotebranch || '',
inBase: CLIArgs.in || 'scripts',
outBase: CLIArgs.out || 'dist',
})
if (CLIArgs.help) {
let command = '<command>'
if (process.argv.length > 0) {
command = Path.parse(process.argv[0]).name
}
if (command.toLowerCase() === 'node' && process.argv.length > 1) {
let path = Path.relative(process.cwd(), process.argv[1]) || '.'
command = `${command} ${path}`
}
console.log(`
Usage: ${command} [options]
options:
--watch
alias: -w
default: false
automatically recompile on save
--minify
alias: -m
default: false
minify output files
--prettier
alias: -p
default: false
prettify output files
--srccomment
alias: -c
default: false
include src file path comments in the output files, i.e. // scripts/example/main.ts
--readme
alias: -r
default: false
update the readme.md file in your directory to include links to each userscript
--url <url>
alias: -u <url>
default: ""
the base for urls used in the meta comments for @downloadURL
--supporturl <url>
alias: -s <url>
default: ""
the support url used in the meta comments for @supportURL
--homepageurl <url>
alias: -U <url>
default: ""
the support url used in the meta comments for @homepageURL
--remotebranch <name>
alias: -b <name>
default: ""
if included, the included base url will be treated as a git repo, and the support url is not required
--in
alias: -i
default: "scripts"
include src file path comments in the output files, i.e. // scripts/example/main.ts
--out
alias: -o
default: "dist"
include src file path comments in the output files, i.e. // scripts/example/main.ts
--help
alias: -h
show this help message
`)
process.exit(0)
}
//if package.json doesn't exist then there is no point in continuing //if package.json doesn't exist then there is no point in continuing
if (!existsSync('package.json') || !lstatSync('package.json').isFile()) { if (!existsSync('package.json') || !lstatSync('package.json').isFile()) {
@@ -24,57 +124,67 @@ if (!existsSync('package.json') || !lstatSync('package.json').isFile()) {
process.exit(1) process.exit(1)
} }
//delete compiled scripts //delete compiled scripts or create output folder if it doesnt exist
readdirSync(DistBase).forEach(file => unlinkSync(`${DistBase}/${file}`)) if (!existsSync(AllPaths.base.out)) {
mkdirSync(AllPaths.base.out)
//read prettierrc file and make sure `babel` is the configured parser } else {
const PrettierConfig = (() => { readdirSync(AllPaths.base.out).forEach(file =>
let config = resolveConfig.sync(process.cwd()) || {} unlinkSync(`${AllPaths.base.out}/${file}`)
return { )
...config,
parser: 'babel',
}
})()
//compile scripts
let scripts = readdirSync(ScriptBase)
let scriptMeta: readmeData[] = []
for (let name of scripts) {
let path = ScriptPath(name)
if (
!name.endsWith('_') &&
existsSync(path.dir) &&
lstatSync(path.dir).isDirectory() &&
existsSync(path.main) &&
lstatSync(path.main).isFile()
) {
let id = scriptMeta.length
function postWatchUpdate(
meta: UserScriptMetaFull,
error: string | null
) {
scriptMeta[id] = { meta, error }
console.log('WATCH', name, meta.version)
updateReadmeFile(scriptMeta)
}
let [meta, error] = runBuild(
name,
postWatchUpdate,
PrettierConfig,
CLIArgs
)
scriptMeta[id] = { meta, error }
console.log(name, meta.version)
}
} }
updateReadmeFile(scriptMeta) //compile scripts
async function doCompile() {
let scripts = readdirSync(AllPaths.base.in)
let scriptMeta: runBuildResult[] = []
console.log( for (let name of scripts) {
`\nFinished Compiling\n${CLIArgs.watch ? 'Listening for Changes\n' : ''}` let path = AllPaths.script(name)
)
if (
!name.endsWith('_') &&
existsSync(path.dir) &&
lstatSync(path.dir).isDirectory() &&
existsSync(path.main) &&
lstatSync(path.main).isFile()
) {
let id = scriptMeta.length
scriptMeta[id] = await runBuild(name)
console.log(name, scriptMeta[id].meta.version)
var running = false
async function update(eventName: string) {
if (running) {
return
}
running = true
scriptMeta[id] = await runBuild(name)
console.log(
`WATCH ${eventName}`,
name,
scriptMeta[id].meta.version
)
if (CLIArgs.readme) updateReadmeFile(scriptMeta)
running = false
}
if (CLIArgs.watch) {
chokidar.watch(path.dir).on('all', update)
}
}
}
return scriptMeta
}
doCompile().then(scriptMeta => {
if (CLIArgs.readme) updateReadmeFile(scriptMeta)
console.log(
`\nFinished Compiling\n${
CLIArgs.watch ? 'Listening for Changes\n' : ''
}`
)
})

View File

@@ -1,17 +1,58 @@
export const BaseUrl = `https://git.zomo.dev/zomo/browser-scripts` export interface ScriptPathT {
export const RemoteBranch = 'main' dir: `${string}/${string}`
export const ScriptBase = 'scripts' main: `${string}/${string}/main.ts`
export const DistBase = 'dist' meta: `${string}/${string}/meta.json`
error: `${string}/${string}/error.log`
dist: `${string}/${string}.user.js`
url: `${string}/${string}.user.js`
}
export const SupportUrl = `${BaseUrl}/issues` export interface getAllPathsOps {
export const FileUrl = (name: string) => baseUrl: string
`${BaseUrl}/raw/branch/${RemoteBranch}/${DistBase}/${name}.user.js` supportUrl: string
homepageUrl: string
remoteBranch: string
inBase: string
outBase: string
}
export const ScriptPath = (name: string) => ({ export default function getAllPaths({
dir: `${ScriptBase}/${name}`, baseUrl,
main: `${ScriptBase}/${name}/main.ts`, supportUrl,
meta: `${ScriptBase}/${name}/meta.json`, homepageUrl,
error: `${ScriptBase}/${name}/error.log`, remoteBranch,
}) inBase,
outBase,
}: getAllPathsOps) {
// generate links for remote git server
if (baseUrl != '' && remoteBranch != '') {
if (supportUrl == '') {
supportUrl = `${baseUrl}/issues`
}
export const DistPath = (name: string) => `${DistBase}/${name}.user.js` if (homepageUrl == '') {
homepageUrl = baseUrl
}
baseUrl = `${baseUrl}/raw/branch/${remoteBranch}/${outBase}`
}
return {
base: {
in: inBase,
out: outBase,
},
url: {
home: homepageUrl,
base: baseUrl,
support: supportUrl,
},
script: (name: string): ScriptPathT => ({
dir: `${inBase}/${name}`,
main: `${inBase}/${name}/main.ts`,
meta: `${inBase}/${name}/meta.json`,
error: `${inBase}/${name}/error.log`,
dist: `${outBase}/${name}.user.js`,
url: `${baseUrl}/${name}.user.js`,
}),
}
}

View File

@@ -1,12 +1,7 @@
import { readdirSync, readFileSync, writeFileSync } from 'fs' import { readdirSync, readFileSync, writeFileSync } from 'fs'
import { UserScriptMetaFull } from './types' import { runBuildResult } from './build'
export interface readmeData { export function updateReadmeFile(fileList: runBuildResult[]) {
meta: UserScriptMetaFull
error: string | null
}
export function updateReadmeFile(fileList: readmeData[]) {
let readmeFile = getReadmeFileName() let readmeFile = getReadmeFileName()
if (readmeFile !== null) { if (readmeFile !== null) {
let [readmeStart, readmeEnd] = readReadmeFile(readmeFile) let [readmeStart, readmeEnd] = readReadmeFile(readmeFile)
@@ -33,11 +28,15 @@ function readmeDataErrorString(error: string | null): string {
return `\n\n${error}` return `\n\n${error}`
} }
function readmeDataToString(readmeData: readmeData): string { function readmeDataToString(results: runBuildResult): string {
let { meta, error } = readmeData let { meta, error } = results
let errStr = error !== null ? '~~' : '' let errStr = error !== null ? '~~' : ''
let errMsg = readmeDataErrorString(error) let errMsg = readmeDataErrorString(error)
return `- ${errStr}[${meta.name}](${meta.downloadURL})${errStr}${errMsg}` return `
- ${errStr}[${meta.name}](${meta.downloadURL})${errStr}${errMsg}
- ${meta.namespace} ${meta.version}
- ${meta.description}
`.trim()
} }
function getReadmeFileName(): string | null { function getReadmeFileName(): string | null {

View File

@@ -1,12 +1,20 @@
import { existsSync, lstatSync, readFileSync } from 'fs' import { existsSync, lstatSync, readFileSync } from 'fs'
import { BaseUrl, FileUrl, ScriptPath, SupportUrl } from './paths' import { AllPaths } from './main'
import { import {
UserScriptMeta, UserScriptMeta,
UserScriptMetaFull, UserScriptMetaFull,
UserScriptMetaPartial, UserScriptMetaPartial,
} from './types' } from './types'
export default function (name: string): [UserScriptMetaFull, string] { export default interface readMeta {
meta: UserScriptMetaFull
metaString: string
}
export default function readMeta(name: string) {
let paths = AllPaths.script(name)
let urls = AllPaths.url
var meta: UserScriptMetaFull = { var meta: UserScriptMetaFull = {
name: name, name: name,
namespace: 'zomo.dev', namespace: 'zomo.dev',
@@ -21,13 +29,13 @@ export default function (name: string): [UserScriptMetaFull, string] {
noframes: false, noframes: false,
grant: '', grant: '',
injectinto: '', injectinto: '',
downloadURL: FileUrl(name), downloadURL: paths.url,
supportURL: SupportUrl, supportURL: urls.support,
homepageURL: BaseUrl, homepageURL: urls.home,
unwrap: false, unwrap: false,
} }
let metaPath = ScriptPath(name).meta let metaPath = paths.meta
if (existsSync(metaPath) && lstatSync(metaPath).isFile()) { if (existsSync(metaPath) && lstatSync(metaPath).isFile()) {
try { try {
@@ -60,9 +68,9 @@ export default function (name: string): [UserScriptMetaFull, string] {
excludematch: 'exclude-match', excludematch: 'exclude-match',
} }
return [ return {
meta, meta,
`// ==UserScript== metaString: `// ==UserScript==
${(Object.keys(meta) as Array<keyof UserScriptMetaFull>) ${(Object.keys(meta) as Array<keyof UserScriptMetaFull>)
.filter(key => { .filter(key => {
let val = meta[key] let val = meta[key]
@@ -80,11 +88,23 @@ ${(Object.keys(meta) as Array<keyof UserScriptMetaFull>)
key_str = key_str.padEnd(12, ' ') key_str = key_str.padEnd(12, ' ')
if (typeof val === 'boolean') { if (typeof val === 'boolean') {
//bool
if (val) return `// @${key_str}` if (val) return `// @${key_str}`
} else if (typeof val === 'string') { } else if (typeof val === 'string') {
//string
return `// @${key_str} ${val}` return `// @${key_str} ${val}`
} else if (Array.isArray(val)) { } else if (Array.isArray(val)) {
//multiple
return val.map(v => `// @${key_str} ${v}`).join('\n') return val.map(v => `// @${key_str} ${v}`).join('\n')
} else if (typeof val === 'object') {
//multilingual
let langs = val
return Object.keys(langs)
.map(lang => {
let langStr = lang === 'default' ? '' : `:${lang}`
return `// @${key_str}${langStr} ${langs[lang]}`
})
.join('\n')
} }
return '' return ''
@@ -93,5 +113,5 @@ ${(Object.keys(meta) as Array<keyof UserScriptMetaFull>)
.join('\n')} .join('\n')}
// ==/UserScript== // ==/UserScript==
`, `,
] }
} }

View File

@@ -1,16 +1,24 @@
export type UserScriptMetaMultilingual =
| string
| {
default: string
[lang: string]: string
}
export type UserScriptMetaMultiple = string | string[]
export interface UserScriptMetaPartial { export interface UserScriptMetaPartial {
name?: string name?: UserScriptMetaMultilingual
namespace?: string namespace?: string
match?: string | string[] match?: UserScriptMetaMultiple
excludematch?: string | string[] excludematch?: UserScriptMetaMultiple
version?: string version?: string
description?: string description?: UserScriptMetaMultilingual
icon?: string icon?: string
require?: string | string[] require?: UserScriptMetaMultiple
resource?: string | string[] resource?: UserScriptMetaMultiple
runat?: 'document-start' | 'document-end' | 'document-idle' | '' runat?: 'document-start' | 'document-end' | 'document-idle' | ''
noframes?: boolean noframes?: boolean
grant?: string | string[] grant?: UserScriptMetaMultiple
injectinto?: 'page' | 'content' | 'auto' | '' injectinto?: 'page' | 'content' | 'auto' | ''
downloadURL?: string downloadURL?: string
supportURL?: string supportURL?: string
@@ -19,7 +27,7 @@ export interface UserScriptMetaPartial {
} }
export interface UserScriptMeta extends UserScriptMetaPartial { export interface UserScriptMeta extends UserScriptMetaPartial {
name: string name: UserScriptMetaMultilingual
namespace: string namespace: string
version: string version: string
downloadURL: string downloadURL: string
@@ -28,15 +36,15 @@ export interface UserScriptMeta extends UserScriptMetaPartial {
} }
export interface UserScriptMetaFull extends UserScriptMeta { export interface UserScriptMetaFull extends UserScriptMeta {
match: string | string[] match: UserScriptMetaMultiple
excludematch: string | string[] excludematch: UserScriptMetaMultiple
description: string description: UserScriptMetaMultilingual
icon: string icon: string
require: string | string[] require: UserScriptMetaMultiple
resource: string | string[] resource: UserScriptMetaMultiple
runat: 'document-start' | 'document-end' | 'document-idle' | '' runat: 'document-start' | 'document-end' | 'document-idle' | ''
noframes: boolean noframes: boolean
grant: string | string[] grant: UserScriptMetaMultiple
injectinto: 'page' | 'content' | 'auto' | '' injectinto: 'page' | 'content' | 'auto' | ''
unwrap: boolean unwrap: boolean
} }

View File

@@ -0,0 +1 @@
// TODO add tests