@coderich/sandman 0.0.8 → 0.0.10

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coderich/sandman",
3
- "version": "0.0.8",
3
+ "version": "0.0.10",
4
4
  "main": "index.js",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -1,3 +1,4 @@
1
+ const FS = require('fs');
1
2
  const Path = require('path');
2
3
  const Chokidar = require('chokidar');
3
4
  const Config = require('@coderich/config');
@@ -10,7 +11,17 @@ module.exports = class ConfigClient extends Config {
10
11
 
11
12
  constructor(configDir) {
12
13
  super({}, {
13
- file: name => `file-${name}`,
14
+ file: (name) => {
15
+ if (name == null || `${name}` === 'undefined') return name;
16
+ const path = Path.resolve(process.cwd(), name);
17
+ try {
18
+ const buffer = FS.readFileSync(path);
19
+ return new File([buffer], name);
20
+ } catch {
21
+ process.stdout.write(`Unable to load file: "${name}"\n`);
22
+ return undefined;
23
+ }
24
+ },
14
25
  });
15
26
  this.#configDir = configDir;
16
27
  this.mergeDir();
@@ -41,11 +52,16 @@ module.exports = class ConfigClient extends Config {
41
52
  return super.set(key, value);
42
53
  }
43
54
 
55
+ del(key = '') {
56
+ if (key.startsWith?.('.')) return Util.set(this.toObject().dictionary['.'], [key.substring(1)], undefined);
57
+ return super.del(key);
58
+ }
59
+
44
60
  mergeDir(dir = this.#configDir) {
45
61
  return this.merge(Config.parseDir(dir, (...args) => this.#ignore(...args)));
46
62
  }
47
63
 
48
- watch(dir = this.#configDir) {
64
+ watch(dir = this.#configDir, onSave) {
49
65
  const watcher = Chokidar.watch(dir, {
50
66
  awaitWriteFinish: true,
51
67
  ignoreInitial: true,
@@ -59,7 +75,7 @@ module.exports = class ConfigClient extends Config {
59
75
  const api = Config.parseFile(path);
60
76
  if (key) this.set(key, api);
61
77
  else this.merge(api); // index.yaml
62
- // if (api.request) this.emit('save', { key, api });
78
+ if (api.request) onSave({ key, api });
63
79
  } else if (['unlink', 'unlinkDir'].includes(event)) {
64
80
  this.del(key);
65
81
  }
@@ -72,11 +88,21 @@ module.exports = class ConfigClient extends Config {
72
88
  const flatData = key === undefined ? Util.flatten(data) : Util.flatten({ [key]: data });
73
89
  const apiKeys = Array.from(new Set(Object.keys(flatData).map(k => k.substring(0, Math.max(k.indexOf('.request'), 0))).filter(Boolean)));
74
90
 
91
+ const mergeKeys = Object.keys(this.#mergeData).reverse();
92
+
75
93
  apiKeys.forEach((apiKey) => {
76
- Reflect.ownKeys(this.#mergeData).forEach((mergeKey) => {
77
- if (mergeKey === dataSymbol) flatData[apiKey] = { ...this.#mergeData[dataSymbol], ...flatData[apiKey] };
78
- else if (apiKey.startsWith(mergeKey)) flatData[apiKey] = { ...this.#mergeData[mergeKey][dataSymbol], ...flatData[apiKey] };
94
+ mergeKeys.forEach((mergeKey) => {
95
+ if (apiKey.startsWith(mergeKey)) {
96
+ Object.entries(this.#mergeData[mergeKey][dataSymbol]).forEach(([k, v]) => {
97
+ flatData[`${apiKey}.${k}`] ??= v;
98
+ });
99
+ }
79
100
  });
101
+ if (this.#mergeData[dataSymbol]) {
102
+ Object.entries(this.#mergeData[dataSymbol]).forEach(([k, v]) => {
103
+ flatData[`${apiKey}.${k}`] ??= v;
104
+ });
105
+ }
80
106
  });
81
107
 
82
108
  const unflatData = Util.unflatten(flatData);
@@ -1,10 +1,11 @@
1
1
  const Readline = require('readline');
2
2
  const Util = require('@coderich/util');
3
+ const UtilService = require('./UtilService');
3
4
 
4
5
  exports.createInterface = (cli, configClient) => {
5
6
  const captureInfo = {
6
7
  line: '',
7
- lastToken: '',
8
+ lastArg: '',
8
9
  candidates: [],
9
10
  tabCounter: 0,
10
11
  candidateIndex: -1,
@@ -16,53 +17,37 @@ exports.createInterface = (cli, configClient) => {
16
17
  output: process.stdout,
17
18
  terminal: true,
18
19
  completer: (line) => {
20
+ const [cmd, ...args] = UtilService.parseArgs(line);
21
+
19
22
  // Show available CLI commands
20
- if (!line) return [Object.keys(cli), line];
23
+ if (!cmd) return [Object.keys(cli), line];
24
+ if (line.split(' ').length < 2) return [Object.keys(cli).filter(key => key.toLowerCase().startsWith(cmd.toLowerCase())), line];
21
25
 
22
- const tokens = line.split(' ');
23
- const lastToken = tokens.at(-1);
24
- const paths = lastToken.split('.');
25
- const path = paths.at(-1);
26
+ const lastArg = args.at(-1) || '';
27
+ const lastPaths = lastArg.split('.');
28
+ const lastPath = lastPaths.at(-1); // current typing
29
+ const previousPath = lastPaths.slice(0, -1).join('.');
26
30
 
27
31
  // Specific request.data selector
28
- if (lastToken.startsWith('.')) {
29
- const api = configClient.get(tokens.at(-2));
30
- if (!api?.request) return [[], path];
31
- const { config } = configClient.toObject();
32
- const conf = Util.get(config, tokens.at(-2), {});
33
- return [Object.keys(conf), path];
34
- // const dataPath = ['request'].concat(paths.slice(1, -1)).join('.');
35
- // const data = get(api, dataPath, {});
36
- // return [Object.keys(data).filter(k => k.toLowerCase().startsWith(path.toLowerCase())), path];
32
+ if (lastArg.startsWith('.')) {
33
+ const requestAttrPath = `${args.at(-2)}.request${previousPath}`;
34
+ const requestAttrObj = configClient.get(requestAttrPath, {});
35
+ return [Object.keys(requestAttrObj).filter(key => key.toLowerCase().startsWith(lastPath.toLowerCase())), lastPath];
37
36
  }
38
37
 
39
38
  //
40
39
  const flatKeys = Object.keys(Util.flatten(configClient.get()));
40
+ const requestKeys = flatKeys.map(k => k.substring(0, Math.max(k.indexOf('.request'), 0))).filter(Boolean);
41
41
 
42
- // These keys follow the typing of the user
43
- const startsWithCandidates = Array.from(new Set(flatKeys.map((flatKey) => {
44
- return flatKey.split('.').slice(0, paths.length).join('.');
45
- }))).filter((c) => {
46
- return c.toLowerCase().startsWith(lastToken.toLowerCase());
47
- }); // .map(p => p.split('.').at(-1)); // Here!
48
-
49
- // These are shortcut keys to requests
50
- const requestKeyCandidates = Array.from(new Set(flatKeys.map((flatKey) => {
51
- const keys = flatKey.split('.');
52
- const index = keys.indexOf('request');
53
- return index && flatKey.split('.').slice(0, index).join('.');
54
- // const typedPath = keys.slice(0, paths.length - 1).join('.');
55
- // const autocompletePath = keys.slice(paths.length - 1, index).join('.');
56
- // return index > 0 && lastToken.toLowerCase().startsWith(typedPath.toLowerCase()) && autocompletePath;
57
- }).filter(Boolean))).filter((c) => {
58
- return c.toLowerCase().includes(lastToken.toLowerCase());
59
- // return c.toLowerCase().includes(path.toLowerCase());
60
- });
42
+ const candidates = Array.from(new Set(requestKeys
43
+ .filter(requestKey => requestKey.toLowerCase().startsWith(previousPath.toLowerCase()))
44
+ .filter(requestKey => requestKey.split('.').slice(lastPaths.length - 1).join('.').toLowerCase().includes(lastPath.toLowerCase()))
45
+ // .concat(Object.keys(cli).filter(key => key.toLowerCase().startsWith(cmd.toLowerCase())))
46
+ ));
61
47
 
62
- const candidates = Array.from(new Set(startsWithCandidates.concat(requestKeyCandidates)));
63
- if (captureInfo.captureCandidates) { captureInfo.candidates = candidates; captureInfo.line = line; captureInfo.lastToken = lastToken; captureInfo.candidateIndex = -1; }
64
- if (candidates.length === 1 && candidates[0] === lastToken) return [[], lastToken];
65
- return [candidates, lastToken];
48
+ if (captureInfo.captureCandidates && lastArg) { captureInfo.candidates = candidates; captureInfo.line = line; captureInfo.lastArg = lastArg; captureInfo.candidateIndex = -1; }
49
+ if (captureInfo.tabbing || (candidates.length === 1 && candidates[0] === lastArg)) return [[], lastArg];
50
+ return [candidates, lastArg];
66
51
  },
67
52
  });
68
53
 
@@ -76,11 +61,14 @@ exports.createInterface = (cli, configClient) => {
76
61
  Readline.clearLine(process.stdout, 0);
77
62
  readline.prompt();
78
63
  } else if (captureInfo.tabCounter > 2 && captureInfo.candidates.length) {
64
+ captureInfo.tabbing = true;
79
65
  const candidate = captureInfo.candidates[captureInfo.candidateIndex = ++captureInfo.candidateIndex % captureInfo.candidates.length];
80
- const value = captureInfo.line.replace(captureInfo.lastToken, candidate);
66
+ const value = captureInfo.line.replace(captureInfo.lastArg, candidate);
81
67
  readline.line = value;
82
68
  readline.cursor = value.length;
83
69
  readline.prompt(true);
70
+ } else {
71
+ captureInfo.tabbing = false;
84
72
  }
85
73
  });
86
74
 
package/src/Sandman.js CHANGED
@@ -1,5 +1,6 @@
1
1
  const EventEmitter = require('events');
2
2
  const ReadlineService = require('./ReadlineService');
3
+ const UtilService = require('./UtilService');
3
4
  const FetchService = require('./FetchService');
4
5
  const ConfigClient = require('./ConfigClient');
5
6
 
@@ -12,16 +13,16 @@ module.exports = class Sandman extends EventEmitter {
12
13
  this.#configClient = new ConfigClient(configDir);
13
14
  this.#createCLI();
14
15
  this.#readline = ReadlineService.createInterface(this.#cli, this.#configClient);
16
+ this.#configClient.watch(configDir, event => this.emit('save', event));
15
17
 
16
18
  this.#readline.on('line', async (line) => {
17
19
  if (!line) return this.#prompt();
18
- const [cmd, ...args] = Sandman.parseArgs(line.trim());
20
+ const [cmd, ...args] = UtilService.parseArgs(line.trim());
19
21
  const info = this.#cli[cmd] ? { cmd, args } : { cmd: 'run', args: [cmd, ...args] };
20
22
  const value = await Promise.resolve(this.#cli[info.cmd](...info.args)).catch(e => e);
21
23
  return this.emit(cmd, value);
22
24
  });
23
25
 
24
- this.#configClient.watch();
25
26
  this.#prompt();
26
27
  }
27
28
 
@@ -65,6 +66,7 @@ module.exports = class Sandman extends EventEmitter {
65
66
  raw: key => this.#configClient.raw(key),
66
67
  get: (...args) => this.#configClient.get(...args),
67
68
  set: (...args) => this.#configClient.set(...args),
69
+ del: (...args) => this.#configClient.del(...args),
68
70
  curl: key => FetchService.toCURL(this.#configClient.get(key, {}).request),
69
71
  quit: () => process.exit(),
70
72
  }, {
@@ -86,6 +88,10 @@ module.exports = class Sandman extends EventEmitter {
86
88
  return value;
87
89
  },
88
90
  }), {
91
+ '/': {
92
+ configurable: true,
93
+ value: (...args) => this.#run(...args),
94
+ },
89
95
  run: {
90
96
  configurable: true,
91
97
  value: (...args) => this.#run(...args),
@@ -99,22 +105,4 @@ module.exports = class Sandman extends EventEmitter {
99
105
  },
100
106
  });
101
107
  }
102
-
103
- static parseArgs(line) {
104
- const regex = /"([^"]*)"|'([^']*)'|(\S+)/g;
105
- const args = [];
106
- let match;
107
-
108
- while ((match = regex.exec(line)) !== null) {
109
- if (match[1] !== undefined) {
110
- args.push(match[1]); // double-quoted
111
- } else if (match[2] !== undefined) {
112
- args.push(match[2]); // single-quoted
113
- } else if (match[3] !== undefined) {
114
- args.push(match[3]); // bare word
115
- }
116
- }
117
-
118
- return args;
119
- }
120
108
  };
@@ -0,0 +1,17 @@
1
+ exports.parseArgs = (line) => {
2
+ const regex = /"([^"]*)"|'([^']*)'|(\S+)/g;
3
+ const args = [];
4
+ let match;
5
+
6
+ while ((match = regex.exec(line)) !== null) {
7
+ if (match[1] !== undefined) {
8
+ args.push(match[1]); // double-quoted
9
+ } else if (match[2] !== undefined) {
10
+ args.push(match[2]); // single-quoted
11
+ } else if (match[3] !== undefined) {
12
+ args.push(match[3]); // bare word
13
+ }
14
+ }
15
+
16
+ return args;
17
+ };