@tolinax/ayoune-cli 2026.2.0 → 2026.2.2

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 (80) hide show
  1. package/data/defaultActions.js +9 -0
  2. package/data/modelsAndRights.js +3189 -0
  3. package/data/modules.js +111 -0
  4. package/data/operations.js +5 -0
  5. package/data/services.js +139 -0
  6. package/index.js +11 -0
  7. package/lib/api/apiCallHandler.js +68 -0
  8. package/lib/api/apiClient.js +100 -0
  9. package/lib/api/auditCallHandler.js +21 -0
  10. package/lib/api/decodeToken.js +4 -0
  11. package/lib/api/handleAPIError.js +59 -0
  12. package/lib/api/login.js +45 -0
  13. package/lib/commands/createActionsCommand.js +109 -0
  14. package/lib/commands/createAiCommand.js +188 -0
  15. package/lib/commands/createAliasCommand.js +106 -0
  16. package/lib/commands/createAuditCommand.js +49 -0
  17. package/lib/commands/createCompletionsCommand.js +136 -0
  18. package/lib/commands/createConfigCommand.js +208 -0
  19. package/lib/commands/createCopyCommand.js +39 -0
  20. package/lib/commands/createCreateCommand.js +50 -0
  21. package/lib/commands/createDeployCommand.js +666 -0
  22. package/lib/commands/createDescribeCommand.js +42 -0
  23. package/lib/commands/createEditCommand.js +43 -0
  24. package/lib/commands/createEventsCommand.js +60 -0
  25. package/lib/commands/createExecCommand.js +182 -0
  26. package/lib/commands/createGetCommand.js +47 -0
  27. package/lib/commands/createListCommand.js +49 -0
  28. package/lib/commands/createLoginCommand.js +18 -0
  29. package/lib/commands/createLogoutCommand.js +21 -0
  30. package/lib/commands/createModulesCommand.js +89 -0
  31. package/lib/commands/createMonitorCommand.js +283 -0
  32. package/lib/commands/createProgram.js +163 -0
  33. package/lib/commands/createServicesCommand.js +228 -0
  34. package/lib/commands/createStorageCommand.js +54 -0
  35. package/lib/commands/createStreamCommand.js +50 -0
  36. package/lib/commands/createWhoAmICommand.js +88 -0
  37. package/lib/exitCodes.js +6 -0
  38. package/lib/helpers/addSpacesToCamelCase.js +5 -0
  39. package/lib/helpers/config.js +6 -0
  40. package/lib/helpers/configLoader.js +60 -0
  41. package/lib/helpers/formatDocument.js +176 -0
  42. package/lib/helpers/handleResponseFormatOptions.js +85 -0
  43. package/lib/helpers/initializeSettings.js +14 -0
  44. package/lib/helpers/localStorage.js +4 -0
  45. package/lib/helpers/makeRandomToken.js +27 -0
  46. package/lib/helpers/parseInt.js +7 -0
  47. package/lib/helpers/requireArg.js +9 -0
  48. package/lib/helpers/saveFile.js +39 -0
  49. package/lib/models/getCollections.js +15 -0
  50. package/lib/models/getModelsInModules.js +13 -0
  51. package/lib/models/getModuleFromCollection.js +7 -0
  52. package/lib/operations/handleAuditOperation.js +22 -0
  53. package/lib/operations/handleCollectionOperation.js +91 -0
  54. package/lib/operations/handleCopySingleOperation.js +22 -0
  55. package/lib/operations/handleCreateSingleOperation.js +35 -0
  56. package/lib/operations/handleDeleteSingleOperation.js +14 -0
  57. package/lib/operations/handleDescribeSingleOperation.js +22 -0
  58. package/lib/operations/handleEditOperation.js +51 -0
  59. package/lib/operations/handleEditRawOperation.js +35 -0
  60. package/lib/operations/handleGetOperation.js +29 -0
  61. package/lib/operations/handleGetSingleOperation.js +20 -0
  62. package/lib/operations/handleListOperation.js +63 -0
  63. package/lib/operations/handleSingleAuditOperation.js +27 -0
  64. package/lib/prompts/promptAudits.js +15 -0
  65. package/lib/prompts/promptCollection.js +13 -0
  66. package/lib/prompts/promptCollectionInModule.js +13 -0
  67. package/lib/prompts/promptCollectionWithModule.js +15 -0
  68. package/lib/prompts/promptConfirm.js +12 -0
  69. package/lib/prompts/promptDefaultAction.js +13 -0
  70. package/lib/prompts/promptEntry.js +19 -0
  71. package/lib/prompts/promptFileName.js +12 -0
  72. package/lib/prompts/promptFilePath.js +18 -0
  73. package/lib/prompts/promptModule.js +19 -0
  74. package/lib/prompts/promptName.js +11 -0
  75. package/lib/prompts/promptOperation.js +13 -0
  76. package/lib/socket/customerSocketClient.js +13 -0
  77. package/lib/socket/socketClient.js +12 -0
  78. package/lib/types.js +1 -0
  79. package/package.json +2 -2
  80. package/README.md +0 -505
@@ -0,0 +1,54 @@
1
+ import chalk from "chalk";
2
+ import { localStorage } from "../helpers/localStorage.js";
3
+ import { loadConfig } from "../helpers/configLoader.js";
4
+ import { spinner } from "../../index.js";
5
+ import { EXIT_GENERAL_ERROR } from "../exitCodes.js";
6
+ const REDACT_KEYS = new Set(["token", "refreshToken"]);
7
+ function redact(value) {
8
+ if (value.length <= 8)
9
+ return "••••";
10
+ return value.slice(0, 4) + "••••" + value.slice(-4);
11
+ }
12
+ export function createStorageCommand(program) {
13
+ program
14
+ .command("storage")
15
+ .alias("s")
16
+ .description("Display stored session data and preferences")
17
+ .action(async () => {
18
+ var _a, _b;
19
+ try {
20
+ const storage = {};
21
+ for (let i = 0; i < localStorage.length; i++) {
22
+ const key = localStorage.key(i);
23
+ if (key) {
24
+ const value = (_a = localStorage.getItem(key)) !== null && _a !== void 0 ? _a : "";
25
+ storage[key] = REDACT_KEYS.has(key) ? redact(value) : value;
26
+ }
27
+ }
28
+ console.log();
29
+ console.log(chalk.bold(" Session Storage"));
30
+ console.log(chalk.dim(` ${"─".repeat(44)}`));
31
+ const maxKey = Math.max(...Object.keys(storage).map((k) => k.length), 0);
32
+ for (const [key, value] of Object.entries(storage)) {
33
+ console.log(` ${chalk.dim(key.padEnd(maxKey + 2))} ${chalk.white(value)}`);
34
+ }
35
+ const config = loadConfig();
36
+ const defaults = (_b = config.defaults) !== null && _b !== void 0 ? _b : {};
37
+ const defaultEntries = Object.entries(defaults).filter(([, v]) => v !== undefined && v !== null);
38
+ if (defaultEntries.length > 0) {
39
+ console.log();
40
+ console.log(chalk.bold(" Config Defaults"));
41
+ console.log(chalk.dim(` ${"─".repeat(44)}`));
42
+ const maxDefault = Math.max(...defaultEntries.map(([k]) => k.length));
43
+ for (const [key, value] of defaultEntries) {
44
+ console.log(` ${chalk.dim(key.padEnd(maxDefault + 2))} ${chalk.white(String(value))}`);
45
+ }
46
+ }
47
+ console.log();
48
+ }
49
+ catch (e) {
50
+ spinner.error({ text: e.message || "An unexpected error occurred" });
51
+ process.exit(EXIT_GENERAL_ERROR);
52
+ }
53
+ });
54
+ }
@@ -0,0 +1,50 @@
1
+ import { Option } from "commander";
2
+ import { localStorage } from "../helpers/localStorage.js";
3
+ import { decodeToken } from "../api/decodeToken.js";
4
+ import { customerSocket } from "../socket/customerSocketClient.js";
5
+ import { spinner } from "../../index.js";
6
+ import yaml from "js-yaml";
7
+ import { EXIT_GENERAL_ERROR } from "../exitCodes.js";
8
+ export function createStreamCommand(program) {
9
+ program
10
+ .command("stream")
11
+ .alias("listen")
12
+ .description("Subscribe to real-time data changes via WebSocket")
13
+ .addHelpText("after", `
14
+ Examples:
15
+ ay stream Stream all data changes as JSON
16
+ ay stream -f yaml Stream changes in YAML format
17
+ ay listen -l minimal Stream with minimal detail`)
18
+ .addOption(new Option("-f, --format <format>", "Set the output format")
19
+ .choices(["json", "yaml", "table"])
20
+ .default("json"))
21
+ .addOption(new Option("-l, --level <level>", "Set the detail level")
22
+ .choices(["default", "minimal", "extended"])
23
+ .default("default"))
24
+ .action(async (options) => {
25
+ try {
26
+ const tokenPayload = decodeToken(localStorage.getItem("token"));
27
+ const user = tokenPayload.payload;
28
+ console.log(`Starting stream with [${user._customerID}]`);
29
+ spinner.start({ text: `Starting stream with [${user._customerID}]` });
30
+ const socket = customerSocket(user);
31
+ spinner.update({ text: "Stream active" });
32
+ socket.onAny((channel, data) => {
33
+ spinner.update({ text: `Received [${channel}]` });
34
+ if (options.format === "table") {
35
+ console.table(data);
36
+ }
37
+ if (options.format === "yaml") {
38
+ console.log(yaml.dump(data));
39
+ }
40
+ if (options.format === "json") {
41
+ console.log(JSON.stringify(data, null, 2));
42
+ }
43
+ });
44
+ }
45
+ catch (e) {
46
+ spinner.error({ text: e.message || "An unexpected error occurred" });
47
+ process.exit(EXIT_GENERAL_ERROR);
48
+ }
49
+ });
50
+ }
@@ -0,0 +1,88 @@
1
+ import chalk from "chalk";
2
+ import moment from "moment";
3
+ import { localStorage } from "../helpers/localStorage.js";
4
+ import { decodeToken } from "../api/decodeToken.js";
5
+ import { spinner } from "../../index.js";
6
+ import { login } from "../api/login.js";
7
+ import { EXIT_GENERAL_ERROR } from "../exitCodes.js";
8
+ const LABEL_MAP = {
9
+ _id: "User ID",
10
+ _customerID: "Customer",
11
+ _resellerID: "Reseller",
12
+ _agencyID: "Agency",
13
+ email: "Email",
14
+ name: "Name",
15
+ username: "Username",
16
+ role: "Role",
17
+ type: "Type",
18
+ language: "Language",
19
+ iat: "Issued",
20
+ exp: "Expires",
21
+ };
22
+ const SKIP_FIELDS = new Set(["password", "hash", "salt", "__v"]);
23
+ function formatValue(key, value) {
24
+ if ((key === "iat" || key === "exp") && typeof value === "number") {
25
+ const m = moment.unix(value);
26
+ const relative = m.fromNow();
27
+ const formatted = m.format("YYYY-MM-DD HH:mm:ss");
28
+ if (key === "exp" && m.isBefore(moment())) {
29
+ return chalk.red(`${formatted} (expired ${relative})`);
30
+ }
31
+ return `${formatted} ${chalk.dim(`(${relative})`)}`;
32
+ }
33
+ if (typeof value === "object" && value !== null) {
34
+ return JSON.stringify(value);
35
+ }
36
+ return String(value);
37
+ }
38
+ function displayUser(user) {
39
+ const name = user.name || user.username || user.email || "User";
40
+ const greeting = getGreeting();
41
+ console.log();
42
+ console.log(chalk.bold(` ${greeting}, ${chalk.cyan(name)}!`));
43
+ console.log(chalk.dim(` ${"─".repeat(44)}`));
44
+ const maxLabel = Math.max(...Object.keys(user)
45
+ .filter((k) => !SKIP_FIELDS.has(k))
46
+ .map((k) => (LABEL_MAP[k] || k).length));
47
+ for (const [key, value] of Object.entries(user)) {
48
+ if (SKIP_FIELDS.has(key) || value == null || value === "")
49
+ continue;
50
+ const label = LABEL_MAP[key] || key;
51
+ const formatted = formatValue(key, value);
52
+ console.log(` ${chalk.dim(label.padEnd(maxLabel + 2))} ${chalk.white(formatted)}`);
53
+ }
54
+ console.log();
55
+ }
56
+ function getGreeting() {
57
+ const hour = new Date().getHours();
58
+ if (hour < 12)
59
+ return "Good morning";
60
+ if (hour < 18)
61
+ return "Good afternoon";
62
+ return "Good evening";
63
+ }
64
+ export function createWhoAmICommand(program) {
65
+ program
66
+ .command("whoami")
67
+ .alias("who")
68
+ .description("Display the currently authenticated user")
69
+ .action(async (options) => {
70
+ try {
71
+ const tokenPayload = decodeToken(localStorage.getItem("token"));
72
+ if (tokenPayload) {
73
+ displayUser(tokenPayload.payload);
74
+ }
75
+ else {
76
+ await login();
77
+ const newPayload = decodeToken(localStorage.getItem("token"));
78
+ if (newPayload) {
79
+ displayUser(newPayload.payload);
80
+ }
81
+ }
82
+ }
83
+ catch (e) {
84
+ spinner.error({ text: e.message || "An unexpected error occurred" });
85
+ process.exit(EXIT_GENERAL_ERROR);
86
+ }
87
+ });
88
+ }
@@ -0,0 +1,6 @@
1
+ export const EXIT_SUCCESS = 0;
2
+ export const EXIT_GENERAL_ERROR = 1;
3
+ export const EXIT_MISUSE = 2;
4
+ export const EXIT_AUTH_REQUIRED = 4;
5
+ export const EXIT_PERMISSION_DENIED = 5;
6
+ export const EXIT_CONFIG_ERROR = 6;
@@ -0,0 +1,5 @@
1
+ export const addSpacesToCamelCase = (str) => {
2
+ return str
3
+ .replace(/([a-z])([A-Z])/g, "$1 $2") // add space between lower & upper case letters
4
+ .replace(/^./, (str) => str.toUpperCase()); // capitalize the first letter
5
+ };
@@ -0,0 +1,6 @@
1
+ export const config = {
2
+ apiUrl: process.env.AYOUNE_API_URL || "https://api.ayoune.app",
3
+ auditUrl: process.env.AYOUNE_AUDIT_URL || "https://audit.ayoune.app",
4
+ notifierUrl: process.env.AYOUNE_NOTIFIER_URL || "https://notifier.ayoune.app",
5
+ loginUrl: process.env.AYOUNE_LOGIN_URL || "https://login.ayoune.app",
6
+ };
@@ -0,0 +1,60 @@
1
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
2
+ import path from "path";
3
+ import os from "os";
4
+ const CONFIG_PATHS = [
5
+ path.join(os.homedir(), ".config", "ayoune", "config.json"),
6
+ path.join(os.homedir(), ".ayounerc"),
7
+ ];
8
+ function findConfigFile() {
9
+ for (const configPath of CONFIG_PATHS) {
10
+ if (existsSync(configPath)) {
11
+ return configPath;
12
+ }
13
+ }
14
+ return null;
15
+ }
16
+ export function loadConfig() {
17
+ const configPath = findConfigFile();
18
+ if (!configPath) {
19
+ return {};
20
+ }
21
+ try {
22
+ const raw = readFileSync(configPath, "utf-8");
23
+ return JSON.parse(raw);
24
+ }
25
+ catch (_a) {
26
+ return {};
27
+ }
28
+ }
29
+ export function getConfigPath() {
30
+ return path.join(os.homedir(), ".config", "ayoune", "config.json");
31
+ }
32
+ export function saveConfig(config) {
33
+ const configPath = getConfigPath();
34
+ const dir = path.dirname(configPath);
35
+ if (!existsSync(dir)) {
36
+ mkdirSync(dir, { recursive: true });
37
+ }
38
+ writeFileSync(configPath, JSON.stringify(config, null, 2), "utf-8");
39
+ }
40
+ export function getActiveProfile(config) {
41
+ var _a, _b;
42
+ const profileName = process.env.AYOUNE_PROFILE || config.profile || "production";
43
+ return (_b = (_a = config.profiles) === null || _a === void 0 ? void 0 : _a[profileName]) !== null && _b !== void 0 ? _b : {};
44
+ }
45
+ export function getApiUrl(config) {
46
+ const profile = getActiveProfile(config);
47
+ return (process.env.AYOUNE_API_URL || profile.apiUrl || "https://api.ayoune.app");
48
+ }
49
+ export function getAuditUrl(config) {
50
+ const profile = getActiveProfile(config);
51
+ return (process.env.AYOUNE_AUDIT_URL ||
52
+ profile.auditUrl ||
53
+ "https://audit.ayoune.app");
54
+ }
55
+ export function getNotifierUrl(config) {
56
+ const profile = getActiveProfile(config);
57
+ return (process.env.AYOUNE_NOTIFIER_URL ||
58
+ profile.notifierUrl ||
59
+ "https://notifier.ayoune.app");
60
+ }
@@ -0,0 +1,176 @@
1
+ import chalk from 'chalk';
2
+ import moment from 'moment';
3
+ import { addSpacesToCamelCase } from './addSpacesToCamelCase.js';
4
+ const SKIP_FIELDS = new Set(['__v', 'password', 'hash', 'salt']);
5
+ function isDateField(key, value) {
6
+ if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(value))
7
+ return true;
8
+ if (key.endsWith('At') || key.endsWith('Date'))
9
+ return true;
10
+ return false;
11
+ }
12
+ function formatDate(value) {
13
+ const m = moment(value);
14
+ if (!m.isValid())
15
+ return String(value);
16
+ const formatted = m.format('YYYY-MM-DD HH:mm:ss');
17
+ const relative = m.fromNow();
18
+ return `${formatted} ${chalk.dim(`(${relative})`)}`;
19
+ }
20
+ function formatValue(key, value) {
21
+ if (value == null || value === '')
22
+ return '';
23
+ if (typeof value === 'boolean') {
24
+ return value ? chalk.green('yes') : chalk.red('no');
25
+ }
26
+ if (isDateField(key, value)) {
27
+ return formatDate(value);
28
+ }
29
+ if (typeof value === 'number') {
30
+ return String(value);
31
+ }
32
+ if (Array.isArray(value)) {
33
+ if (value.length === 0)
34
+ return '';
35
+ if (value.every((v) => typeof v !== 'object' || v === null)) {
36
+ return value.join(', ');
37
+ }
38
+ return '';
39
+ }
40
+ if (typeof value === 'object')
41
+ return '';
42
+ const str = String(value);
43
+ if ((key.endsWith('ID') || key.endsWith('Id') || key === '_id') && str.length > 10) {
44
+ return chalk.dim(str);
45
+ }
46
+ return str;
47
+ }
48
+ function getEntryName(obj) {
49
+ return (obj === null || obj === void 0 ? void 0 : obj.name) || (obj === null || obj === void 0 ? void 0 : obj.title) || (obj === null || obj === void 0 ? void 0 : obj.subject) || (obj === null || obj === void 0 ? void 0 : obj.originalname) || '';
50
+ }
51
+ function renderHeader(obj, ctx) {
52
+ const name = getEntryName(obj);
53
+ const contextParts = [];
54
+ if (ctx.module)
55
+ contextParts.push(ctx.module);
56
+ if (ctx.collection)
57
+ contextParts.push(ctx.collection);
58
+ if (ctx.id)
59
+ contextParts.push(ctx.id);
60
+ const contextLine = contextParts.join(chalk.dim(' · '));
61
+ const contentWidth = Math.max(name ? name.length : 0, contextLine ? contextParts.join(' · ').length : 0, 30);
62
+ const boxWidth = contentWidth + 4;
63
+ const lines = [];
64
+ lines.push(chalk.dim(`╭${'─'.repeat(boxWidth)}╮`));
65
+ if (name) {
66
+ lines.push(chalk.dim('│') + ` ${chalk.bold.white(name)}${' '.repeat(boxWidth - name.length - 2)}` + chalk.dim('│'));
67
+ }
68
+ if (contextLine) {
69
+ const plainLen = contextParts.join(' · ').length;
70
+ lines.push(chalk.dim('│') + ` ${chalk.dim(contextLine)}${' '.repeat(boxWidth - plainLen - 2)}` + chalk.dim('│'));
71
+ }
72
+ lines.push(chalk.dim(`╰${'─'.repeat(boxWidth)}╯`));
73
+ return lines.join('\n');
74
+ }
75
+ function collectFields(obj) {
76
+ const flat = [];
77
+ const nested = [];
78
+ const arrayOfObjects = [];
79
+ for (const [key, value] of Object.entries(obj)) {
80
+ if (SKIP_FIELDS.has(key) || value == null || value === '')
81
+ continue;
82
+ if (Array.isArray(value)) {
83
+ if (value.length === 0)
84
+ continue;
85
+ if (value.some((v) => typeof v === 'object' && v !== null)) {
86
+ arrayOfObjects.push([key, value]);
87
+ }
88
+ else {
89
+ flat.push([key, value]);
90
+ }
91
+ }
92
+ else if (typeof value === 'object' && !isDateField(key, value)) {
93
+ nested.push([key, value]);
94
+ }
95
+ else {
96
+ flat.push([key, value]);
97
+ }
98
+ }
99
+ return { flat, nested, arrayOfObjects };
100
+ }
101
+ function renderFields(fields, indent, labelWidth) {
102
+ const pad = ' '.repeat(indent);
103
+ const lines = [];
104
+ for (const [key, value] of fields) {
105
+ const formatted = formatValue(key, value);
106
+ if (!formatted)
107
+ continue;
108
+ const label = addSpacesToCamelCase(key);
109
+ lines.push(`${pad}${chalk.dim(label.padEnd(labelWidth))} ${chalk.white(formatted)}`);
110
+ }
111
+ return lines;
112
+ }
113
+ function getLabelWidth(fields) {
114
+ if (fields.length === 0)
115
+ return 16;
116
+ return Math.max(...fields.map(([k]) => addSpacesToCamelCase(k).length)) + 2;
117
+ }
118
+ function renderSection(title, obj, indent) {
119
+ const pad = ' '.repeat(indent);
120
+ const lines = [];
121
+ const { flat, nested, arrayOfObjects } = collectFields(obj);
122
+ lines.push('');
123
+ lines.push(`${pad}${chalk.dim('── ' + addSpacesToCamelCase(title) + ' ' + '─'.repeat(Math.max(0, 36 - title.length)))}`);
124
+ const labelWidth = getLabelWidth(flat);
125
+ lines.push(...renderFields(flat, indent + 2, labelWidth));
126
+ for (const [key, value] of nested) {
127
+ lines.push(...renderSection(key, value, indent + 2));
128
+ }
129
+ for (const [key, items] of arrayOfObjects) {
130
+ lines.push('');
131
+ lines.push(`${pad} ${chalk.dim('── ' + addSpacesToCamelCase(key) + ' ' + '─'.repeat(Math.max(0, 34 - key.length)))}`);
132
+ items.forEach((item, i) => {
133
+ if (typeof item === 'object' && item !== null) {
134
+ lines.push(`${pad} ${chalk.dim(`[${i + 1}]`)}`);
135
+ const itemFields = collectFields(item);
136
+ const itemLabelWidth = getLabelWidth(itemFields.flat);
137
+ lines.push(...renderFields(itemFields.flat, indent + 6, itemLabelWidth));
138
+ }
139
+ else {
140
+ lines.push(`${pad} ${chalk.dim(`[${i + 1}]`)} ${String(item)}`);
141
+ }
142
+ });
143
+ }
144
+ return lines;
145
+ }
146
+ export function formatDocument(obj, ctx = {}) {
147
+ if (!obj || typeof obj !== 'object')
148
+ return String(obj !== null && obj !== void 0 ? obj : '');
149
+ const lines = [];
150
+ lines.push('');
151
+ lines.push(renderHeader(obj, ctx));
152
+ const { flat, nested, arrayOfObjects } = collectFields(obj);
153
+ const labelWidth = getLabelWidth(flat);
154
+ lines.push('');
155
+ lines.push(...renderFields(flat, 2, labelWidth));
156
+ for (const [key, value] of nested) {
157
+ lines.push(...renderSection(key, value, 2));
158
+ }
159
+ for (const [key, items] of arrayOfObjects) {
160
+ lines.push('');
161
+ lines.push(` ${chalk.dim('── ' + addSpacesToCamelCase(key) + ' ' + '─'.repeat(Math.max(0, 36 - key.length)))}`);
162
+ items.forEach((item, i) => {
163
+ if (typeof item === 'object' && item !== null) {
164
+ lines.push(` ${chalk.dim(`[${i + 1}]`)}`);
165
+ const itemFields = collectFields(item);
166
+ const itemLabelWidth = getLabelWidth(itemFields.flat);
167
+ lines.push(...renderFields(itemFields.flat, 6, itemLabelWidth));
168
+ }
169
+ else {
170
+ lines.push(` ${chalk.dim(`[${i + 1}]`)} ${String(item)}`);
171
+ }
172
+ });
173
+ }
174
+ lines.push('');
175
+ return lines.join('\n');
176
+ }
@@ -0,0 +1,85 @@
1
+ import yaml from "js-yaml";
2
+ import jmespath from "jmespath";
3
+ function filterColumns(data, columns) {
4
+ const fields = columns.split(",").map((c) => c.trim());
5
+ if (Array.isArray(data)) {
6
+ return data.map((item) => {
7
+ const filtered = {};
8
+ for (const f of fields) {
9
+ if (item[f] !== undefined)
10
+ filtered[f] = item[f];
11
+ }
12
+ return filtered;
13
+ });
14
+ }
15
+ if (typeof data === "object" && data !== null) {
16
+ const filtered = {};
17
+ for (const f of fields) {
18
+ if (data[f] !== undefined)
19
+ filtered[f] = data[f];
20
+ }
21
+ return filtered;
22
+ }
23
+ return data;
24
+ }
25
+ export function handleResponseFormatOptions(opts, res) {
26
+ let plainResult;
27
+ let result;
28
+ let meta = {};
29
+ let content;
30
+ if (opts.responseFormat && opts.responseFormat === "yaml") {
31
+ plainResult = yaml.load(res);
32
+ result = plainResult.payload;
33
+ meta = plainResult.meta;
34
+ }
35
+ if (opts.responseFormat && opts.responseFormat === "csv") {
36
+ plainResult = res;
37
+ result = res.payload;
38
+ meta = res.meta;
39
+ }
40
+ if (opts.responseFormat && opts.responseFormat === "table") {
41
+ plainResult = res;
42
+ result = res.payload;
43
+ meta = res.meta;
44
+ }
45
+ if (opts.responseFormat && opts.responseFormat === "json") {
46
+ plainResult = res;
47
+ result = res.payload;
48
+ meta = res.meta;
49
+ }
50
+ // Apply --columns filter
51
+ if (opts.columns && result) {
52
+ result = filterColumns(result, opts.columns);
53
+ }
54
+ // Apply --jq (JMESPath) filter
55
+ if (opts.jq && result) {
56
+ try {
57
+ result = jmespath.search(result, opts.jq);
58
+ }
59
+ catch (e) {
60
+ console.error(`JMESPath error: ${e.message}`);
61
+ }
62
+ }
63
+ // Generate content string after filtering
64
+ if (opts.responseFormat === "yaml") {
65
+ content = yaml.dump(result);
66
+ }
67
+ else if (opts.responseFormat === "csv") {
68
+ content = result;
69
+ }
70
+ else if (opts.responseFormat === "table") {
71
+ content = result;
72
+ }
73
+ else {
74
+ content = JSON.stringify(result, null, 4);
75
+ }
76
+ if (!opts.quiet) {
77
+ if (opts.responseFormat === "table") {
78
+ console.table(result);
79
+ }
80
+ else if (content !== undefined) {
81
+ console.log(content);
82
+ }
83
+ }
84
+ return { plainResult, result, meta, content };
85
+ }
@@ -0,0 +1,14 @@
1
+ //Initializes settings for system environment and inquirer
2
+ import inquirer from "inquirer";
3
+ import inquirerFuzzyPath from "inquirer-fuzzy-path";
4
+ import inquirerSearchList from "inquirer-search-list";
5
+ import inquirerFileTreeSelection from "inquirer-file-tree-selection-prompt";
6
+ import inquirerTableInput from "inquirer-table-input";
7
+ import InterruptedPrompt from "inquirer-interrupted-prompt";
8
+ export function initializeSettings() {
9
+ inquirer.registerPrompt("fuzzypath", inquirerFuzzyPath);
10
+ inquirer.registerPrompt("search-list", inquirerSearchList);
11
+ inquirer.registerPrompt("file-tree-selection", inquirerFileTreeSelection);
12
+ inquirer.registerPrompt("table-input", inquirerTableInput);
13
+ InterruptedPrompt.fromAll(inquirer);
14
+ }
@@ -0,0 +1,4 @@
1
+ import { LocalStorage } from "node-localstorage";
2
+ import path from "path";
3
+ import os from "os";
4
+ export const localStorage = new LocalStorage(path.join(os.homedir(), "aYOUne", "storage"));
@@ -0,0 +1,27 @@
1
+ import { randomBytes } from "crypto";
2
+ /** Sync */
3
+ const randomString = (length, chars) => {
4
+ if (!chars) {
5
+ throw new Error("Argument 'chars' is undefined");
6
+ }
7
+ const charsLength = chars.length;
8
+ if (charsLength > 256) {
9
+ throw new Error("Argument 'chars' should not have more than 256 characters" +
10
+ ", otherwise unpredictability will be broken");
11
+ }
12
+ const _randomBytes = randomBytes(length);
13
+ let result = new Array(length);
14
+ let cursor = 0;
15
+ for (let i = 0; i < length; i++) {
16
+ cursor += _randomBytes[i];
17
+ result[i] = chars[cursor % charsLength];
18
+ }
19
+ return result.join("");
20
+ };
21
+ /** Sync */
22
+ export const randomAsciiString = (length = 32, alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") => {
23
+ if (typeof length === "undefined") {
24
+ length = 32;
25
+ }
26
+ return randomString(length, alphabet);
27
+ };
@@ -0,0 +1,7 @@
1
+ export function parseInteger(value, dummyPrevious) {
2
+ const parsedValue = parseInt(value, 10);
3
+ if (isNaN(parsedValue)) {
4
+ throw new Error("Not a number.");
5
+ }
6
+ return parsedValue;
7
+ }
@@ -0,0 +1,9 @@
1
+ import { spinner } from "../../index.js";
2
+ export function requireArg(value, name) {
3
+ if (value)
4
+ return true;
5
+ if (process.stdin.isTTY)
6
+ return false; // allow prompt to run
7
+ spinner.error({ text: `Missing required argument: ${name}` });
8
+ process.exit(1);
9
+ }
@@ -0,0 +1,39 @@
1
+ import { mkdirp } from "mkdirp";
2
+ import moment from "moment";
3
+ import path from "path";
4
+ import { writeFile } from "fs/promises";
5
+ import { spinner } from "../../index.js";
6
+ export async function saveFile(type, opts, result) {
7
+ if (opts.save) {
8
+ await mkdirp(opts.outPath);
9
+ const fileName = opts.name
10
+ ? opts.name
11
+ : type +
12
+ "_page_" +
13
+ result.meta.pageInfo.page +
14
+ "_" +
15
+ moment().format("YYYY_DD_MM_HH_mm_ss");
16
+ const pathToWrite = path.join(opts.outPath, `${fileName}`).toString();
17
+ console.log(pathToWrite);
18
+ spinner.start({
19
+ text: `Saving operation as ${pathToWrite}.${opts.responseFormat}`,
20
+ color: "yellow",
21
+ });
22
+ await writeFile(`${pathToWrite}.${opts.responseFormat}`, result.content, {
23
+ encoding: "utf8",
24
+ });
25
+ spinner.success({
26
+ text: `File written: ${pathToWrite}.${opts.responseFormat}`,
27
+ });
28
+ if (opts.debug) {
29
+ spinner.start({
30
+ text: `Saving operation as ${pathToWrite}.meta.json`,
31
+ color: "yellow",
32
+ });
33
+ await writeFile(`${pathToWrite}.meta.json`, JSON.stringify(result.meta, null, 4), {
34
+ encoding: "utf8",
35
+ });
36
+ spinner.success({ text: `File written: ${pathToWrite}.meta.json` });
37
+ }
38
+ }
39
+ }
@@ -0,0 +1,15 @@
1
+ import { modelsAndRights } from "../../data/modelsAndRights.js";
2
+ import { addSpacesToCamelCase } from "../helpers/addSpacesToCamelCase.js";
3
+ const getCollections = () => {
4
+ return modelsAndRights
5
+ .filter((el) => {
6
+ return el.module !== "su";
7
+ })
8
+ .map((el) => {
9
+ return {
10
+ name: addSpacesToCamelCase(el.plural),
11
+ value: el.plural.toLowerCase(),
12
+ };
13
+ });
14
+ };
15
+ export { getCollections };
@@ -0,0 +1,13 @@
1
+ import _ from "lodash";
2
+ import { addSpacesToCamelCase } from "../helpers/addSpacesToCamelCase.js";
3
+ import { modelsAndRights } from "../../data/modelsAndRights.js";
4
+ const getModelsInModules = (module) => {
5
+ const m = _.filter(modelsAndRights, { module });
6
+ return m.map((el) => {
7
+ return {
8
+ name: addSpacesToCamelCase(el.plural),
9
+ value: el.plural.toLowerCase(),
10
+ };
11
+ });
12
+ };
13
+ export { getModelsInModules };