@airscript/ghitgud 1.0.3 → 2.1.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.
Files changed (50) hide show
  1. package/README.md +113 -18
  2. package/VERSION +1 -1
  3. package/dist/index.js +1010 -0
  4. package/dist/templates/base.json +12 -0
  5. package/dist/templates/conventional.json +52 -0
  6. package/dist/templates/github.json +47 -0
  7. package/package.json +61 -36
  8. package/templates/base.json +1 -1
  9. package/templates/conventional.json +51 -52
  10. package/templates/github.json +1 -1
  11. package/.env.base +0 -2
  12. package/.github/CODEOWNERS +0 -1
  13. package/.github/FUNDING.yml +0 -2
  14. package/.github/ISSUE_TEMPLATE/build.md +0 -9
  15. package/.github/ISSUE_TEMPLATE/chore.md +0 -9
  16. package/.github/ISSUE_TEMPLATE/ci.md +0 -9
  17. package/.github/ISSUE_TEMPLATE/documentation.md +0 -9
  18. package/.github/ISSUE_TEMPLATE/feature.md +0 -9
  19. package/.github/ISSUE_TEMPLATE/fix.md +0 -9
  20. package/.github/ISSUE_TEMPLATE/performance.md +0 -9
  21. package/.github/ISSUE_TEMPLATE/refactor.md +0 -9
  22. package/.github/ISSUE_TEMPLATE/style.md +0 -9
  23. package/.github/ISSUE_TEMPLATE/test.md +0 -9
  24. package/.github/PULL_REQUEST_TEMPLATE.md +0 -28
  25. package/.github/workflows/tests.yml +0 -36
  26. package/CHANGELOG.md +0 -29
  27. package/CITATION.cff +0 -13
  28. package/CODE_OF_CONDUCT.md +0 -121
  29. package/CONTRIBUTING.md +0 -2
  30. package/SECURITY.md +0 -9
  31. package/app/api.ts +0 -136
  32. package/app/ascii.ts +0 -18
  33. package/app/commands.ts +0 -117
  34. package/app/config.ts +0 -9
  35. package/app/functions.ts +0 -43
  36. package/app/ghitgud.ts +0 -19
  37. package/app/library.ts +0 -157
  38. package/app/types.ts +0 -8
  39. package/dist/app/api.js +0 -127
  40. package/dist/app/ascii.js +0 -20
  41. package/dist/app/commands.js +0 -89
  42. package/dist/app/config.js +0 -12
  43. package/dist/app/functions.js +0 -37
  44. package/dist/app/ghitgud.js +0 -20
  45. package/dist/app/library.js +0 -122
  46. package/dist/app/types.js +0 -2
  47. package/dist/tests/library.test.js +0 -81
  48. package/scripts/clean.sh +0 -2
  49. package/tests/library.test.ts +0 -77
  50. package/tsconfig.json +0 -113
package/dist/index.js ADDED
@@ -0,0 +1,1010 @@
1
+ #!/usr/bin/env node
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esmMin = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
10
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
11
+ var __exportAll = (all, no_symbols) => {
12
+ let target = {};
13
+ for (var name in all) __defProp(target, name, {
14
+ get: all[name],
15
+ enumerable: true
16
+ });
17
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
18
+ return target;
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
22
+ key = keys[i];
23
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
24
+ get: ((k) => from[k]).bind(null, key),
25
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
26
+ });
27
+ }
28
+ return to;
29
+ };
30
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
31
+ value: mod,
32
+ enumerable: true
33
+ }) : target, mod));
34
+ var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
35
+ //#endregion
36
+ let process$1 = require("process");
37
+ process$1 = __toESM(process$1);
38
+ let commander = require("commander");
39
+ let figlet = require("figlet");
40
+ figlet = __toESM(figlet);
41
+ let consola = require("consola");
42
+ let child_process = require("child_process");
43
+ let path = require("path");
44
+ path = __toESM(path);
45
+ let fs = require("fs");
46
+ fs = __toESM(fs);
47
+ let os = require("os");
48
+ os = __toESM(os);
49
+ //#region src/cli/ascii.ts
50
+ var ascii = figlet.default.textSync("Ghitgud", {
51
+ font: "Standard",
52
+ width: 80,
53
+ verticalLayout: "default",
54
+ whitespaceBreak: true,
55
+ horizontalLayout: "default"
56
+ });
57
+ //#endregion
58
+ //#region src/core/logger.ts
59
+ var logger = (0, consola.createConsola)({ defaults: { tag: "ghitgud" } });
60
+ //#endregion
61
+ //#region src/commands/gh.ts
62
+ var register$6 = (program) => {
63
+ program.command("gh").description("Pass through to the gh CLI. Usage: ghitgud gh <args>").allowUnknownOption().action((_opts, command) => {
64
+ const args = command.args;
65
+ const child = (0, child_process.spawn)("gh", args, {
66
+ stdio: "inherit",
67
+ shell: false
68
+ });
69
+ child.on("error", (error) => {
70
+ if (error.code === "ENOENT") {
71
+ logger.error("gh CLI is not installed. Install it from https://cli.github.com.");
72
+ process$1.default.exit(1);
73
+ }
74
+ logger.error(String(error));
75
+ process$1.default.exit(1);
76
+ });
77
+ child.on("exit", (code) => {
78
+ process$1.default.exitCode = code ?? 0;
79
+ });
80
+ });
81
+ };
82
+ var gh_default = { register: register$6 };
83
+ //#endregion
84
+ //#region src/core/constants.ts
85
+ var GHITGUD_FOLDER = path.default.join(os.default.homedir(), ".config", "ghitgud");
86
+ var CREDENTIALS_FILE = "credentials.json";
87
+ var METADATA_FILE = "labels.json";
88
+ var ENCODING = "utf8";
89
+ var CREDENTIALS_PATH = path.default.join(GHITGUD_FOLDER, CREDENTIALS_FILE);
90
+ var METADATA_FILE_PATH = path.default.join(GHITGUD_FOLDER, METADATA_FILE);
91
+ var TEMPLATES_DIR = path.default.join(__dirname, "templates");
92
+ var GITHUB_API_VERSION = "2022-11-28";
93
+ var GITHUB_API_BASE_URL = "https://api.github.com";
94
+ var GITHUB_API_ACCEPT = "application/vnd.github+json";
95
+ var ERROR_UNAUTHORIZED = "Unauthorized.";
96
+ var ERROR_NOT_FOUND = "Resource not found.";
97
+ var ERROR_UNPROCESSABLE = "Content is unprocessable.";
98
+ var ERROR_UNEXPECTED = "Unexpected status code.";
99
+ var ERROR_NO_REPO = "Repository not configured. Set it with: ghitgud config set repo owner/repo.";
100
+ var ERROR_NO_TOKEN = "Token not configured. Set it with: ghitgud config set token <your-token>.";
101
+ var ERROR_UNSUPPORTED_KEY = "Trying to set unsupported key.";
102
+ var ERROR_NO_METADATA = "No metadata file found.";
103
+ var INFO_NO_NOTIFICATIONS = "No notifications found.";
104
+ var PING_RESPONSE = "pong";
105
+ var SUPPORTED_CONFIG_KEYS = ["token", "repo"];
106
+ //#endregion
107
+ //#region src/core/io.ts
108
+ var readJsonFile = (filePath) => {
109
+ const data = fs.default.readFileSync(filePath, ENCODING);
110
+ return JSON.parse(data);
111
+ };
112
+ var writeJsonFile = (filePath, data) => {
113
+ fs.default.writeFileSync(filePath, JSON.stringify(data, null, 2), ENCODING);
114
+ };
115
+ var fileExists = (filePath) => {
116
+ return fs.default.existsSync(filePath);
117
+ };
118
+ var ensureDir = (dirPath) => {
119
+ fs.default.mkdirSync(dirPath, { recursive: true });
120
+ };
121
+ var io_default = {
122
+ readJsonFile,
123
+ writeJsonFile,
124
+ fileExists,
125
+ ensureDir
126
+ };
127
+ //#endregion
128
+ //#region node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/package.json
129
+ var package_exports = /* @__PURE__ */ __exportAll({
130
+ browser: () => browser,
131
+ default: () => package_default,
132
+ description: () => description,
133
+ devDependencies: () => devDependencies,
134
+ engines: () => engines,
135
+ exports: () => exports$1,
136
+ funding: () => funding,
137
+ homepage: () => homepage,
138
+ keywords: () => keywords,
139
+ license: () => license,
140
+ main: () => main,
141
+ name: () => name,
142
+ readmeFilename: () => readmeFilename,
143
+ repository: () => repository,
144
+ scripts: () => scripts,
145
+ types: () => types,
146
+ version: () => version
147
+ });
148
+ var name, version, description, main, types, exports$1, scripts, repository, homepage, funding, keywords, readmeFilename, license, devDependencies, engines, browser, package_default;
149
+ var init_package = __esmMin((() => {
150
+ name = "dotenv";
151
+ version = "16.5.0";
152
+ description = "Loads environment variables from .env file";
153
+ main = "lib/main.js";
154
+ types = "lib/main.d.ts";
155
+ exports$1 = {
156
+ ".": {
157
+ "types": "./lib/main.d.ts",
158
+ "require": "./lib/main.js",
159
+ "default": "./lib/main.js"
160
+ },
161
+ "./config": "./config.js",
162
+ "./config.js": "./config.js",
163
+ "./lib/env-options": "./lib/env-options.js",
164
+ "./lib/env-options.js": "./lib/env-options.js",
165
+ "./lib/cli-options": "./lib/cli-options.js",
166
+ "./lib/cli-options.js": "./lib/cli-options.js",
167
+ "./package.json": "./package.json"
168
+ };
169
+ scripts = {
170
+ "dts-check": "tsc --project tests/types/tsconfig.json",
171
+ "lint": "standard",
172
+ "pretest": "npm run lint && npm run dts-check",
173
+ "test": "tap run --allow-empty-coverage --disable-coverage --timeout=60000",
174
+ "test:coverage": "tap run --show-full-coverage --timeout=60000 --coverage-report=lcov",
175
+ "prerelease": "npm test",
176
+ "release": "standard-version"
177
+ };
178
+ repository = {
179
+ "type": "git",
180
+ "url": "git://github.com/motdotla/dotenv.git"
181
+ };
182
+ homepage = "https://github.com/motdotla/dotenv#readme";
183
+ funding = "https://dotenvx.com";
184
+ keywords = [
185
+ "dotenv",
186
+ "env",
187
+ ".env",
188
+ "environment",
189
+ "variables",
190
+ "config",
191
+ "settings"
192
+ ];
193
+ readmeFilename = "README.md";
194
+ license = "BSD-2-Clause";
195
+ devDependencies = {
196
+ "@types/node": "^18.11.3",
197
+ "decache": "^4.6.2",
198
+ "sinon": "^14.0.1",
199
+ "standard": "^17.0.0",
200
+ "standard-version": "^9.5.0",
201
+ "tap": "^19.2.0",
202
+ "typescript": "^4.8.4"
203
+ };
204
+ engines = { "node": ">=12" };
205
+ browser = { "fs": false };
206
+ package_default = {
207
+ name,
208
+ version,
209
+ description,
210
+ main,
211
+ types,
212
+ exports: exports$1,
213
+ scripts,
214
+ repository,
215
+ homepage,
216
+ funding,
217
+ keywords,
218
+ readmeFilename,
219
+ license,
220
+ devDependencies,
221
+ engines,
222
+ browser
223
+ };
224
+ }));
225
+ //#endregion
226
+ //#region node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/lib/main.js
227
+ var require_main = /* @__PURE__ */ __commonJSMin(((exports, module) => {
228
+ var fs$2 = require("fs");
229
+ var path$2 = require("path");
230
+ var os$1 = require("os");
231
+ var crypto = require("crypto");
232
+ var version = (init_package(), __toCommonJS(package_exports).default).version;
233
+ var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
234
+ function parse(src) {
235
+ const obj = {};
236
+ let lines = src.toString();
237
+ lines = lines.replace(/\r\n?/gm, "\n");
238
+ let match;
239
+ while ((match = LINE.exec(lines)) != null) {
240
+ const key = match[1];
241
+ let value = match[2] || "";
242
+ value = value.trim();
243
+ const maybeQuote = value[0];
244
+ value = value.replace(/^(['"`])([\s\S]*)\1$/gm, "$2");
245
+ if (maybeQuote === "\"") {
246
+ value = value.replace(/\\n/g, "\n");
247
+ value = value.replace(/\\r/g, "\r");
248
+ }
249
+ obj[key] = value;
250
+ }
251
+ return obj;
252
+ }
253
+ function _parseVault(options) {
254
+ const vaultPath = _vaultPath(options);
255
+ const result = DotenvModule.configDotenv({ path: vaultPath });
256
+ if (!result.parsed) {
257
+ const err = /* @__PURE__ */ new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
258
+ err.code = "MISSING_DATA";
259
+ throw err;
260
+ }
261
+ const keys = _dotenvKey(options).split(",");
262
+ const length = keys.length;
263
+ let decrypted;
264
+ for (let i = 0; i < length; i++) try {
265
+ const attrs = _instructions(result, keys[i].trim());
266
+ decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
267
+ break;
268
+ } catch (error) {
269
+ if (i + 1 >= length) throw error;
270
+ }
271
+ return DotenvModule.parse(decrypted);
272
+ }
273
+ function _warn(message) {
274
+ console.log(`[dotenv@${version}][WARN] ${message}`);
275
+ }
276
+ function _debug(message) {
277
+ console.log(`[dotenv@${version}][DEBUG] ${message}`);
278
+ }
279
+ function _dotenvKey(options) {
280
+ if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) return options.DOTENV_KEY;
281
+ if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) return process.env.DOTENV_KEY;
282
+ return "";
283
+ }
284
+ function _instructions(result, dotenvKey) {
285
+ let uri;
286
+ try {
287
+ uri = new URL(dotenvKey);
288
+ } catch (error) {
289
+ if (error.code === "ERR_INVALID_URL") {
290
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
291
+ err.code = "INVALID_DOTENV_KEY";
292
+ throw err;
293
+ }
294
+ throw error;
295
+ }
296
+ const key = uri.password;
297
+ if (!key) {
298
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing key part");
299
+ err.code = "INVALID_DOTENV_KEY";
300
+ throw err;
301
+ }
302
+ const environment = uri.searchParams.get("environment");
303
+ if (!environment) {
304
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: Missing environment part");
305
+ err.code = "INVALID_DOTENV_KEY";
306
+ throw err;
307
+ }
308
+ const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
309
+ const ciphertext = result.parsed[environmentKey];
310
+ if (!ciphertext) {
311
+ const err = /* @__PURE__ */ new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
312
+ err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
313
+ throw err;
314
+ }
315
+ return {
316
+ ciphertext,
317
+ key
318
+ };
319
+ }
320
+ function _vaultPath(options) {
321
+ let possibleVaultPath = null;
322
+ if (options && options.path && options.path.length > 0) if (Array.isArray(options.path)) {
323
+ for (const filepath of options.path) if (fs$2.existsSync(filepath)) possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
324
+ } else possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
325
+ else possibleVaultPath = path$2.resolve(process.cwd(), ".env.vault");
326
+ if (fs$2.existsSync(possibleVaultPath)) return possibleVaultPath;
327
+ return null;
328
+ }
329
+ function _resolveHome(envPath) {
330
+ return envPath[0] === "~" ? path$2.join(os$1.homedir(), envPath.slice(1)) : envPath;
331
+ }
332
+ function _configVault(options) {
333
+ if (Boolean(options && options.debug)) _debug("Loading env from encrypted .env.vault");
334
+ const parsed = DotenvModule._parseVault(options);
335
+ let processEnv = process.env;
336
+ if (options && options.processEnv != null) processEnv = options.processEnv;
337
+ DotenvModule.populate(processEnv, parsed, options);
338
+ return { parsed };
339
+ }
340
+ function configDotenv(options) {
341
+ const dotenvPath = path$2.resolve(process.cwd(), ".env");
342
+ let encoding = "utf8";
343
+ const debug = Boolean(options && options.debug);
344
+ if (options && options.encoding) encoding = options.encoding;
345
+ else if (debug) _debug("No encoding is specified. UTF-8 is used by default");
346
+ let optionPaths = [dotenvPath];
347
+ if (options && options.path) if (!Array.isArray(options.path)) optionPaths = [_resolveHome(options.path)];
348
+ else {
349
+ optionPaths = [];
350
+ for (const filepath of options.path) optionPaths.push(_resolveHome(filepath));
351
+ }
352
+ let lastError;
353
+ const parsedAll = {};
354
+ for (const path$4 of optionPaths) try {
355
+ const parsed = DotenvModule.parse(fs$2.readFileSync(path$4, { encoding }));
356
+ DotenvModule.populate(parsedAll, parsed, options);
357
+ } catch (e) {
358
+ if (debug) _debug(`Failed to load ${path$4} ${e.message}`);
359
+ lastError = e;
360
+ }
361
+ let processEnv = process.env;
362
+ if (options && options.processEnv != null) processEnv = options.processEnv;
363
+ DotenvModule.populate(processEnv, parsedAll, options);
364
+ if (lastError) return {
365
+ parsed: parsedAll,
366
+ error: lastError
367
+ };
368
+ else return { parsed: parsedAll };
369
+ }
370
+ function config(options) {
371
+ if (_dotenvKey(options).length === 0) return DotenvModule.configDotenv(options);
372
+ const vaultPath = _vaultPath(options);
373
+ if (!vaultPath) {
374
+ _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
375
+ return DotenvModule.configDotenv(options);
376
+ }
377
+ return DotenvModule._configVault(options);
378
+ }
379
+ function decrypt(encrypted, keyStr) {
380
+ const key = Buffer.from(keyStr.slice(-64), "hex");
381
+ let ciphertext = Buffer.from(encrypted, "base64");
382
+ const nonce = ciphertext.subarray(0, 12);
383
+ const authTag = ciphertext.subarray(-16);
384
+ ciphertext = ciphertext.subarray(12, -16);
385
+ try {
386
+ const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
387
+ aesgcm.setAuthTag(authTag);
388
+ return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
389
+ } catch (error) {
390
+ const isRange = error instanceof RangeError;
391
+ const invalidKeyLength = error.message === "Invalid key length";
392
+ const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
393
+ if (isRange || invalidKeyLength) {
394
+ const err = /* @__PURE__ */ new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
395
+ err.code = "INVALID_DOTENV_KEY";
396
+ throw err;
397
+ } else if (decryptionFailed) {
398
+ const err = /* @__PURE__ */ new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
399
+ err.code = "DECRYPTION_FAILED";
400
+ throw err;
401
+ } else throw error;
402
+ }
403
+ }
404
+ function populate(processEnv, parsed, options = {}) {
405
+ const debug = Boolean(options && options.debug);
406
+ const override = Boolean(options && options.override);
407
+ if (typeof parsed !== "object") {
408
+ const err = /* @__PURE__ */ new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
409
+ err.code = "OBJECT_REQUIRED";
410
+ throw err;
411
+ }
412
+ for (const key of Object.keys(parsed)) if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
413
+ if (override === true) processEnv[key] = parsed[key];
414
+ if (debug) if (override === true) _debug(`"${key}" is already defined and WAS overwritten`);
415
+ else _debug(`"${key}" is already defined and was NOT overwritten`);
416
+ } else processEnv[key] = parsed[key];
417
+ }
418
+ var DotenvModule = {
419
+ configDotenv,
420
+ _configVault,
421
+ _parseVault,
422
+ config,
423
+ decrypt,
424
+ parse,
425
+ populate
426
+ };
427
+ module.exports.configDotenv = DotenvModule.configDotenv;
428
+ module.exports._configVault = DotenvModule._configVault;
429
+ module.exports._parseVault = DotenvModule._parseVault;
430
+ module.exports.config = DotenvModule.config;
431
+ module.exports.decrypt = DotenvModule.decrypt;
432
+ module.exports.parse = DotenvModule.parse;
433
+ module.exports.populate = DotenvModule.populate;
434
+ module.exports = DotenvModule;
435
+ }));
436
+ //#endregion
437
+ //#region node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/lib/env-options.js
438
+ var require_env_options = /* @__PURE__ */ __commonJSMin(((exports, module) => {
439
+ var options = {};
440
+ if (process.env.DOTENV_CONFIG_ENCODING != null) options.encoding = process.env.DOTENV_CONFIG_ENCODING;
441
+ if (process.env.DOTENV_CONFIG_PATH != null) options.path = process.env.DOTENV_CONFIG_PATH;
442
+ if (process.env.DOTENV_CONFIG_DEBUG != null) options.debug = process.env.DOTENV_CONFIG_DEBUG;
443
+ if (process.env.DOTENV_CONFIG_OVERRIDE != null) options.override = process.env.DOTENV_CONFIG_OVERRIDE;
444
+ if (process.env.DOTENV_CONFIG_DOTENV_KEY != null) options.DOTENV_KEY = process.env.DOTENV_CONFIG_DOTENV_KEY;
445
+ module.exports = options;
446
+ }));
447
+ //#endregion
448
+ //#region node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/lib/cli-options.js
449
+ var require_cli_options = /* @__PURE__ */ __commonJSMin(((exports, module) => {
450
+ var re = /^dotenv_config_(encoding|path|debug|override|DOTENV_KEY)=(.+)$/;
451
+ module.exports = function optionMatcher(args) {
452
+ return args.reduce(function(acc, cur) {
453
+ const matches = cur.match(re);
454
+ if (matches) acc[matches[1]] = matches[2];
455
+ return acc;
456
+ }, {});
457
+ };
458
+ }));
459
+ //#endregion
460
+ //#region node_modules/.pnpm/dotenv@16.5.0/node_modules/dotenv/config.js
461
+ (function() {
462
+ require_main().config(Object.assign({}, require_env_options(), require_cli_options()(process.argv)));
463
+ })();
464
+ //#endregion
465
+ //#region src/core/errors.ts
466
+ var GhitgudError = class extends Error {
467
+ constructor(message) {
468
+ super(message);
469
+ this.name = "GhitgudError";
470
+ }
471
+ };
472
+ var AuthError = class extends GhitgudError {
473
+ constructor(message) {
474
+ super(message);
475
+ this.name = "AuthError";
476
+ }
477
+ };
478
+ var ConfigError = class extends GhitgudError {
479
+ constructor(message) {
480
+ super(message);
481
+ this.name = "ConfigError";
482
+ }
483
+ };
484
+ var NotFoundError = class extends GhitgudError {
485
+ constructor(message) {
486
+ super(message);
487
+ this.name = "NotFoundError";
488
+ }
489
+ };
490
+ var UnprocessableError = class extends GhitgudError {
491
+ constructor(message) {
492
+ super(message);
493
+ this.name = "UnprocessableError";
494
+ }
495
+ };
496
+ //#endregion
497
+ //#region src/core/config.ts
498
+ function readCredentialsFile() {
499
+ if (!fs.default.existsSync(CREDENTIALS_PATH)) return null;
500
+ const data = fs.default.readFileSync(CREDENTIALS_PATH, ENCODING);
501
+ return JSON.parse(data);
502
+ }
503
+ function resolve(key, envVar) {
504
+ const envValue = process$1.default.env[envVar];
505
+ if (envValue) return envValue;
506
+ const credentials = readCredentialsFile();
507
+ if (credentials && credentials[key]) return credentials[key];
508
+ throw new ConfigError(key === "repo" ? ERROR_NO_REPO : ERROR_NO_TOKEN);
509
+ }
510
+ function read(key) {
511
+ const credentials = readCredentialsFile();
512
+ if (credentials && credentials[key]) return credentials[key];
513
+ return null;
514
+ }
515
+ function has(key) {
516
+ if (!!process$1.default.env[key === "repo" ? "GHITGUD_GITHUB_REPO" : "GHITGUD_GITHUB_TOKEN"]) return true;
517
+ return !!readCredentialsFile()?.[key];
518
+ }
519
+ function write(key, value) {
520
+ let credentials = {};
521
+ if (fs.default.existsSync(CREDENTIALS_PATH)) {
522
+ const data = fs.default.readFileSync(CREDENTIALS_PATH, ENCODING);
523
+ credentials = JSON.parse(data);
524
+ } else fs.default.mkdirSync(GHITGUD_FOLDER, { recursive: true });
525
+ credentials[key] = value;
526
+ fs.default.writeFileSync(CREDENTIALS_PATH, JSON.stringify(credentials, null, 2), ENCODING);
527
+ }
528
+ function getRepo() {
529
+ return resolve("repo", "GHITGUD_GITHUB_REPO");
530
+ }
531
+ function getToken() {
532
+ return resolve("token", "GHITGUD_GITHUB_TOKEN");
533
+ }
534
+ var config = {
535
+ getRepo,
536
+ getToken,
537
+ read,
538
+ write,
539
+ has
540
+ };
541
+ //#endregion
542
+ //#region src/api/client.ts
543
+ var ERROR_MAP = {
544
+ [401]: AuthError,
545
+ [404]: NotFoundError,
546
+ [422]: UnprocessableError
547
+ };
548
+ var ERROR_MESSAGES = {
549
+ [401]: ERROR_UNAUTHORIZED,
550
+ [404]: ERROR_NOT_FOUND,
551
+ [422]: ERROR_UNPROCESSABLE
552
+ };
553
+ function buildHeaders() {
554
+ return {
555
+ Accept: GITHUB_API_ACCEPT,
556
+ Authorization: `Bearer ${config.getToken()}`,
557
+ "X-GitHub-Api-Version": GITHUB_API_VERSION
558
+ };
559
+ }
560
+ function handleError(status) {
561
+ const ErrorClass = ERROR_MAP[status];
562
+ if (ErrorClass) throw new ErrorClass(ERROR_MESSAGES[status]);
563
+ throw new GhitgudError(`${ERROR_UNEXPECTED}: ${status}`);
564
+ }
565
+ function isSuccessful(status) {
566
+ return status >= 200 && status <= 299;
567
+ }
568
+ async function request(endpoint, options = {}) {
569
+ const url = `${GITHUB_API_BASE_URL}${endpoint}`;
570
+ const headers = buildHeaders();
571
+ const fetchOptions = {
572
+ method: options.method || "GET",
573
+ headers
574
+ };
575
+ if (options.body) fetchOptions.body = JSON.stringify(options.body);
576
+ const response = await fetch(url, fetchOptions);
577
+ if (isSuccessful(response.status)) return response;
578
+ handleError(response.status);
579
+ }
580
+ var client = {
581
+ get: (endpoint) => request(endpoint),
582
+ post: (endpoint, body) => request(endpoint, {
583
+ method: "POST",
584
+ body
585
+ }),
586
+ patch: (endpoint, body) => request(endpoint, {
587
+ method: "PATCH",
588
+ body
589
+ }),
590
+ put: (endpoint, body) => request(endpoint, {
591
+ method: "PUT",
592
+ body
593
+ }),
594
+ getRepo: () => config.getRepo(),
595
+ isOk: (status) => isSuccessful(status),
596
+ isNotFound: (status) => status === 404,
597
+ delete: (endpoint) => request(endpoint, { method: "DELETE" })
598
+ };
599
+ //#endregion
600
+ //#region src/api/labels.ts
601
+ var labels = {
602
+ fetch: async () => {
603
+ const repo = client.getRepo();
604
+ return client.get(`/repos/${repo}/labels`);
605
+ },
606
+ get: async (name) => {
607
+ const repo = client.getRepo();
608
+ return client.get(`/repos/${repo}/labels/${name}`);
609
+ },
610
+ create: async (label) => {
611
+ const repo = client.getRepo();
612
+ return client.post(`/repos/${repo}/labels`, {
613
+ name: label.name,
614
+ color: label.color,
615
+ description: label.description
616
+ });
617
+ },
618
+ patch: async (label) => {
619
+ const repo = client.getRepo();
620
+ return client.patch(`/repos/${repo}/labels/${label.name}`, {
621
+ color: label.color,
622
+ description: label.description,
623
+ new_name: label.newName || label.name
624
+ });
625
+ },
626
+ delete: async (name) => {
627
+ const repo = client.getRepo();
628
+ return client.delete(`/repos/${repo}/labels/${name}`);
629
+ }
630
+ };
631
+ //#endregion
632
+ //#region src/types/index.ts
633
+ var normalizeLabel = (label) => ({
634
+ name: label.name,
635
+ color: label.color,
636
+ description: label.description
637
+ });
638
+ //#endregion
639
+ //#region src/services/labels.ts
640
+ var formatLabels = (labels) => {
641
+ const rows = labels.map((label) => ({
642
+ name: label.name,
643
+ color: label.color,
644
+ description: label.description
645
+ }));
646
+ console.log();
647
+ console.table(rows);
648
+ };
649
+ var ping = () => {
650
+ logger.success(PING_RESPONSE + ".");
651
+ return {
652
+ success: true,
653
+ message: PING_RESPONSE
654
+ };
655
+ };
656
+ var list$1 = async () => {
657
+ logger.info("Fetching labels from repository.");
658
+ const labels$1 = (await (await labels.fetch()).json()).map((label) => normalizeLabel(label));
659
+ formatLabels(labels$1);
660
+ return {
661
+ success: true,
662
+ metadata: labels$1
663
+ };
664
+ };
665
+ var pull = async () => {
666
+ logger.info("Pulling labels from repository.");
667
+ const labels$2 = (await (await labels.fetch()).json()).map((label) => normalizeLabel(label));
668
+ io_default.ensureDir(GHITGUD_FOLDER);
669
+ io_default.writeJsonFile(METADATA_FILE_PATH, labels$2);
670
+ logger.success("Labels pulled successfully.");
671
+ return {
672
+ success: true,
673
+ metadata: labels$2
674
+ };
675
+ };
676
+ var pullTemplate = async (templateName, templatesDir) => {
677
+ logger.info(`Pulling labels from template "${templateName}".`);
678
+ const templatePath = path.default.join(templatesDir, `${templateName}.json`);
679
+ if (!io_default.fileExists(templatePath)) throw new Error(`Template "${templateName}" not found at ${templatePath}.`);
680
+ const labels = io_default.readJsonFile(templatePath);
681
+ io_default.ensureDir(GHITGUD_FOLDER);
682
+ io_default.writeJsonFile(METADATA_FILE_PATH, labels);
683
+ formatLabels(labels);
684
+ logger.success(`Labels pulled from template "${templateName}".`);
685
+ return {
686
+ success: true,
687
+ metadata: labels
688
+ };
689
+ };
690
+ var upsertLabels = async (labels$3) => {
691
+ logger.info(`Upserting ${labels$3.length} label(s).`);
692
+ await Promise.all(labels$3.map(async (label) => {
693
+ try {
694
+ await labels.get(label.name);
695
+ await labels.patch(label);
696
+ } catch (error) {
697
+ if (error instanceof NotFoundError) await labels.create(label);
698
+ else throw error;
699
+ }
700
+ }));
701
+ };
702
+ var push = async () => {
703
+ if (!io_default.fileExists(METADATA_FILE_PATH)) throw new Error(ERROR_NO_METADATA);
704
+ logger.info("Pushing labels to repository.");
705
+ await upsertLabels(io_default.readJsonFile(METADATA_FILE_PATH));
706
+ logger.success("Labels pushed successfully.");
707
+ return { success: true };
708
+ };
709
+ var pushTemplate = async (templateName, templatesDir) => {
710
+ logger.info(`Pushing labels from template "${templateName}".`);
711
+ const templatePath = path.default.join(templatesDir, `${templateName}.json`);
712
+ if (!io_default.fileExists(templatePath)) throw new Error(`Template "${templateName}" not found at ${templatePath}.`);
713
+ await upsertLabels(io_default.readJsonFile(templatePath));
714
+ logger.success(`Labels pushed from template "${templateName}".`);
715
+ return { success: true };
716
+ };
717
+ var prune = async () => {
718
+ if (!io_default.fileExists(METADATA_FILE_PATH)) throw new Error(ERROR_NO_METADATA);
719
+ const labels$4 = io_default.readJsonFile(METADATA_FILE_PATH);
720
+ logger.info(`Pruning ${labels$4.length} label(s) from repository.`);
721
+ await Promise.all(labels$4.map(async (label) => {
722
+ await labels.delete(label.name);
723
+ }));
724
+ logger.success("Labels pruned successfully.");
725
+ return { success: true };
726
+ };
727
+ var labels_default$1 = {
728
+ ping,
729
+ list: list$1,
730
+ pull,
731
+ pullTemplate,
732
+ push,
733
+ pushTemplate,
734
+ prune
735
+ };
736
+ //#endregion
737
+ //#region src/commands/ping.ts
738
+ var register$5 = (program) => {
739
+ program.command("ping").description("Check if the CLI is working.").action(() => void labels_default$1.ping());
740
+ };
741
+ var ping_default = { register: register$5 };
742
+ //#endregion
743
+ //#region src/commands/labels.ts
744
+ var register$4 = (program) => {
745
+ const labels = program.command("labels").description("Manage labels for a repository.");
746
+ labels.command("list").description("List all labels for a repository.").action(() => void labels_default$1.list());
747
+ labels.command("pull").description("Pull all related labels for a repository.").option("-t, --template <name>", "Pull from a built-in template instead of the remote repository").action(async (options) => {
748
+ if (options.template) await labels_default$1.pullTemplate(options.template, TEMPLATES_DIR);
749
+ else await labels_default$1.pull();
750
+ });
751
+ labels.command("push").description("Push all related labels for a repository.").option("-t, --template <name>", "Push from a built-in template instead of the local metadata file").action(async (options) => {
752
+ if (options.template) await labels_default$1.pushTemplate(options.template, TEMPLATES_DIR);
753
+ else await labels_default$1.push();
754
+ });
755
+ labels.command("prune").description("Prune all related labels for a repository.").action(() => void labels_default$1.prune());
756
+ };
757
+ var labels_default = { register: register$4 };
758
+ //#endregion
759
+ //#region src/services/config.ts
760
+ var validateKey = (key) => {
761
+ if (!SUPPORTED_CONFIG_KEYS.includes(key)) throw new ConfigError(ERROR_UNSUPPORTED_KEY);
762
+ return key;
763
+ };
764
+ var set = (key, value) => {
765
+ validateKey(key);
766
+ logger.info(`Setting config "${key}".`);
767
+ config.write(key, value);
768
+ logger.success(`Config "${key}" set successfully.`);
769
+ return { success: true };
770
+ };
771
+ var get = (key) => {
772
+ validateKey(key);
773
+ const value = config.read(key);
774
+ logger.info(`${key}: ${value ?? "(not set)"}.`);
775
+ return {
776
+ success: true,
777
+ key,
778
+ value: value || null
779
+ };
780
+ };
781
+ var config_default$1 = {
782
+ set,
783
+ get
784
+ };
785
+ //#endregion
786
+ //#region src/commands/config.ts
787
+ var register$3 = (program) => {
788
+ const config = program.command("config").description("Set CLI configurations.");
789
+ config.command("set").description("Set configuration.").arguments("<key> <value>").action((key, value) => {
790
+ config_default$1.set(key, value);
791
+ });
792
+ config.command("get").description("Get configuration value.").arguments("<key>").action((key) => {
793
+ config_default$1.get(key);
794
+ });
795
+ };
796
+ var config_default = { register: register$3 };
797
+ //#endregion
798
+ //#region src/api/notifications.ts
799
+ var BASE_PATH = "/notifications";
800
+ var notifications = {
801
+ fetch: (params) => {
802
+ const query = new URLSearchParams();
803
+ if (params?.all) query.set("all", "true");
804
+ if (params?.participating) query.set("participating", "true");
805
+ if (params?.perPage) query.set("per_page", String(params.perPage));
806
+ const qs = query.toString();
807
+ const endpoint = qs ? `${BASE_PATH}?${qs}` : BASE_PATH;
808
+ return client.get(endpoint);
809
+ },
810
+ markRead: (id) => {
811
+ return client.patch(`/notifications/threads/${id}`, {});
812
+ },
813
+ markDone: (id) => {
814
+ return client.put(`/notifications/threads/${id}/subscription`, { ignored: true });
815
+ },
816
+ assignedIssues: () => {
817
+ return client.get("/issues?filter=assigned&state=open");
818
+ },
819
+ reviewRequests: () => {
820
+ return client.get("/search/issues?q=is:pr+is:open+review-requested:@me");
821
+ },
822
+ mentions: (username) => {
823
+ const since = (/* @__PURE__ */ new Date(Date.now() - 10080 * 60 * 1e3)).toISOString().split("T")[0];
824
+ return client.get(`/search/issues?q=mentions:${username}+updated:>${since}`);
825
+ }
826
+ };
827
+ //#endregion
828
+ //#region src/types/notifications.ts
829
+ var normalizeThread = (item) => {
830
+ const data = item;
831
+ const repo = data.repository ?? {};
832
+ const subject = data.subject ?? {};
833
+ return {
834
+ id: String(data.id),
835
+ repository: String(repo.full_name ?? ""),
836
+ subjectTitle: String(subject.title ?? ""),
837
+ subjectType: String(subject.type ?? ""),
838
+ reason: String(data.reason ?? ""),
839
+ unread: Boolean(data.unread),
840
+ updatedAt: String(data.updated_at ?? "")
841
+ };
842
+ };
843
+ var normalizeIssue = (item) => {
844
+ const data = item;
845
+ const repo = data.repository ?? {};
846
+ return {
847
+ id: String(data.id),
848
+ repository: String(repo.full_name ?? ""),
849
+ subjectTitle: String(data.title ?? ""),
850
+ subjectType: String(data.pull_request ? "PullRequest" : "Issue"),
851
+ reason: "assigned",
852
+ unread: false,
853
+ updatedAt: String(data.updated_at ?? "")
854
+ };
855
+ };
856
+ var normalizeSearchItem = (item) => {
857
+ const data = item;
858
+ return {
859
+ id: String(data.id),
860
+ repository: String(data.repository_url ?? "").replace("https://api.github.com/repos/", ""),
861
+ subjectTitle: String(data.title ?? ""),
862
+ subjectType: String(data.pull_request ? "PullRequest" : "Issue"),
863
+ reason: "mention",
864
+ unread: false,
865
+ updatedAt: String(data.updated_at ?? "")
866
+ };
867
+ };
868
+ //#endregion
869
+ //#region src/services/notifications.ts
870
+ var formatTable = (notifications) => {
871
+ if (notifications.length === 0) {
872
+ logger.info(INFO_NO_NOTIFICATIONS);
873
+ return;
874
+ }
875
+ console.log();
876
+ console.table(notifications.map((n) => ({
877
+ repository: n.repository,
878
+ subject: n.subjectTitle,
879
+ type: n.subjectType,
880
+ reason: n.reason
881
+ })));
882
+ };
883
+ var list = async (options = {}) => {
884
+ logger.info("Fetching notifications.");
885
+ let notifications$1 = (await (await notifications.fetch({
886
+ all: options.all,
887
+ participating: options.participating,
888
+ perPage: options.limit
889
+ })).json()).map(normalizeThread);
890
+ if (options.repo) notifications$1 = notifications$1.filter((n) => n.repository === options.repo);
891
+ formatTable(notifications$1);
892
+ return {
893
+ success: true,
894
+ metadata: notifications$1
895
+ };
896
+ };
897
+ var markRead = async (id) => {
898
+ logger.info(`Marking notification ${id} as read.`);
899
+ await notifications.markRead(id);
900
+ logger.success("Notification marked as read.");
901
+ return { success: true };
902
+ };
903
+ var markDone = async (id) => {
904
+ logger.info(`Marking notification ${id} as done.`);
905
+ await notifications.markDone(id);
906
+ logger.success("Notification marked as done.");
907
+ return { success: true };
908
+ };
909
+ var activity = async () => {
910
+ logger.info("Fetching activity.");
911
+ const [issuesRes, reviewsRes, mentionsRes] = await Promise.all([
912
+ notifications.assignedIssues(),
913
+ notifications.reviewRequests(),
914
+ notifications.mentions("@me")
915
+ ]);
916
+ const assignedIssues = await issuesRes.json();
917
+ const reviewData = await reviewsRes.json();
918
+ const mentionData = await mentionsRes.json();
919
+ const result = {
920
+ assignedIssues: assignedIssues.map(normalizeIssue),
921
+ reviewRequests: (reviewData.items ?? []).map(normalizeSearchItem),
922
+ recentMentions: (mentionData.items ?? []).map(normalizeSearchItem)
923
+ };
924
+ console.log();
925
+ console.log("Assigned Issues:", result.assignedIssues.length);
926
+ console.log("Review Requests:", result.reviewRequests.length);
927
+ console.log("Recent Mentions:", result.recentMentions.length);
928
+ return {
929
+ success: true,
930
+ metadata: result
931
+ };
932
+ };
933
+ var mentions = async () => {
934
+ logger.info("Fetching mentions.");
935
+ const notifications$2 = ((await (await notifications.mentions("@me")).json()).items ?? []).map(normalizeSearchItem);
936
+ formatTable(notifications$2);
937
+ return {
938
+ success: true,
939
+ metadata: notifications$2
940
+ };
941
+ };
942
+ var notifications_default$1 = {
943
+ list,
944
+ markRead,
945
+ markDone,
946
+ activity,
947
+ mentions
948
+ };
949
+ //#endregion
950
+ //#region src/commands/mentions.ts
951
+ var register$2 = (program) => {
952
+ program.command("mentions").description("Find recent @mentions of you.").action(() => void notifications_default$1.mentions());
953
+ };
954
+ var mentions_default = { register: register$2 };
955
+ //#endregion
956
+ //#region src/commands/activity.ts
957
+ var register$1 = (program) => {
958
+ program.command("activity").description("Show assigned issues, review requests, and mentions.").action(() => void notifications_default$1.activity());
959
+ };
960
+ var activity_default = { register: register$1 };
961
+ //#endregion
962
+ //#region src/commands/notifications.ts
963
+ var register = (program) => {
964
+ const notifications = program.command("notifications").description("Manage GitHub notifications.");
965
+ notifications.command("list").description("List notifications.").option("-a, --all", "Include read notifications").option("-p, --participating", "Only participating notifications").option("-r, --repo <owner/repo>", "Filter by repository").option("-l, --limit <n>", "Max results").action((options) => {
966
+ notifications_default$1.list({
967
+ all: options.all,
968
+ participating: options.participating,
969
+ repo: options.repo,
970
+ limit: options.limit ? parseInt(options.limit, 10) : void 0
971
+ });
972
+ });
973
+ notifications.command("read <id>").description("Mark a notification as read.").action((id) => {
974
+ notifications_default$1.markRead(id);
975
+ });
976
+ notifications.command("done <id>").description("Mark a notification as done.").action((id) => {
977
+ notifications_default$1.markDone(id);
978
+ });
979
+ };
980
+ var notifications_default = { register };
981
+ //#endregion
982
+ //#region src/cli/index.ts
983
+ commander.program.name("ghitgud").description("A simple CLI to give superpowers to GitHub.").version("2.1.0");
984
+ gh_default.register(commander.program);
985
+ notifications_default.register(commander.program);
986
+ activity_default.register(commander.program);
987
+ mentions_default.register(commander.program);
988
+ ping_default.register(commander.program);
989
+ labels_default.register(commander.program);
990
+ config_default.register(commander.program);
991
+ commander.program.addHelpText("before", ascii);
992
+ commander.program.exitOverride();
993
+ try {
994
+ commander.program.parse(process$1.default.argv);
995
+ } catch (error) {
996
+ if (error instanceof GhitgudError) {
997
+ logger.error(error.message);
998
+ process$1.default.exit(1);
999
+ }
1000
+ if (error.exitCode === 0) process$1.default.exit(0);
1001
+ throw error;
1002
+ }
1003
+ process$1.default.on("unhandledRejection", (error) => {
1004
+ if (error instanceof GhitgudError) {
1005
+ logger.error(error.message);
1006
+ process$1.default.exit(1);
1007
+ }
1008
+ throw error;
1009
+ });
1010
+ //#endregion