@zeyos/cli 0.2.0 → 0.4.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.
package/lib/config.mjs CHANGED
@@ -1,52 +1,142 @@
1
1
  /**
2
- * Credential configuration cascade:
3
- * 1. Environment variables (ZEYOS_BASE_URL, ZEYOS_TOKEN, …)
4
- * 2. .zeyos/auth.json (walk up from CWD, like .gitconfig)
5
- * 3. ~/.config/zeyos/credentials.json
2
+ * Credential configuration with named profiles.
6
3
  *
7
- * The auth file stores connection params AND tokens.
8
- * Add .zeyos/auth.json to .gitignore.
4
+ * A "profile" is a full credential set (baseUrl, clientId, clientSecret, tokens)
5
+ * stored under a name. Profiles live in a global registry; a project can pin which
6
+ * profile it uses. The legacy single-file layout still works unchanged.
7
+ *
8
+ * Resolution cascade (first match decides which credential set is the base):
9
+ * 1. --profile <name> (CLI flag) -> named profile
10
+ * 2. ZEYOS_PROFILE (env var) -> named profile
11
+ * 3. .zeyos/profile (project pin, walked up) -> named profile
12
+ * 4. .zeyos/auth.json (legacy local, walked up)
13
+ * 5. profiles.json "active" (global active profile)
14
+ * 6. ~/.config/zeyos/credentials.json (legacy global)
15
+ * Environment credential vars (ZEYOS_BASE_URL, ZEYOS_TOKEN, …) always field-merge
16
+ * on top of whichever base was chosen.
17
+ *
18
+ * Add .zeyos/auth.json and .zeyos/profile to .gitignore.
9
19
  */
10
- import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
20
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, unlinkSync } from 'node:fs';
11
21
  import { join, dirname } from 'node:path';
12
22
  import { homedir } from 'node:os';
13
23
 
14
24
  /** @typedef {import('./types.mjs').CliConfig} CliConfig */
25
+ /** @typedef {{ kind: 'profile'|'local'|'global', name?: string, path?: string }} ConfigSource */
15
26
 
16
27
  // ── Constants ────────────────────────────────────────────────────────────────
17
28
 
18
- const LOCAL_DIR = '.zeyos';
19
- const LOCAL_FILE = 'auth.json';
20
- const GLOBAL_DIR = join(homedir(), '.config', 'zeyos');
21
- const GLOBAL_FILE = join(GLOBAL_DIR, 'credentials.json');
29
+ const LOCAL_DIR = '.zeyos';
30
+ const LOCAL_FILE = 'auth.json';
31
+ const PIN_FILE = 'profile';
32
+ const GLOBAL_DIR = join(homedir(), '.config', 'zeyos');
33
+ const GLOBAL_FILE = join(GLOBAL_DIR, 'credentials.json');
34
+ const PROFILES_FILE = join(GLOBAL_DIR, 'profiles.json');
35
+
36
+ /** Credential fields that make up a profile / auth file. */
37
+ const CRED_KEYS = [
38
+ 'baseUrl', 'instance', 'clientId', 'clientSecret',
39
+ 'accessToken', 'refreshToken', 'expiresAt', 'refreshTokenExpiresAt'
40
+ ];
41
+ const TOKEN_KEYS = ['accessToken', 'refreshToken', 'expiresAt', 'refreshTokenExpiresAt'];
22
42
 
23
43
  // ── Load ─────────────────────────────────────────────────────────────────────
24
44
 
25
45
  /**
26
46
  * Load the full config object using the cascade.
27
- * Returns a merged object; env vars always win over file values.
47
+ * @param {{ profile?: string }} [opts]
28
48
  */
29
- export function loadConfig() {
30
- return loadConfigWithSource().config;
49
+ export function loadConfig(opts = {}) {
50
+ return loadConfigWithSource(opts).config;
31
51
  }
32
52
 
33
53
  /**
34
- * Load config and identify the credential file scope that should receive
35
- * refreshed tokens. Local config overrides global config field-by-field, so a
36
- * partial local file cannot shadow global connection parameters.
54
+ * Load config and identify the credential store that should receive refreshed
55
+ * tokens (the `source`). Env credential vars field-merge on top of the resolved
56
+ * base so they always win.
57
+ *
58
+ * @param {{ profile?: string }} [opts]
59
+ * @returns {{ config: CliConfig, source: ConfigSource|null, profile: { name: string, origin: string }|null }}
37
60
  */
38
- export function loadConfigWithSource() {
39
- const localPath = _findLocalPath();
40
- const globalFile = _readGlobal();
41
- const localFile = localPath ? _readJson(localPath) : {};
61
+ export function loadConfigWithSource(opts = {}) {
42
62
  const env = _fromEnv();
63
+ const selection = resolveProfileSelection({ profileFlag: opts.profile });
64
+
65
+ let base = {};
66
+ let source = null;
67
+
68
+ if (selection.name) {
69
+ // An explicit/active profile was selected (flag, env, pin, or active pointer).
70
+ const prof = getProfile(selection.name);
71
+ base = prof ?? {};
72
+ source = { kind: 'profile', name: selection.name };
73
+ // selection.missing is surfaced via resolveProfileSelection consumers; base
74
+ // stays {} so requireConfig reports the missing fields.
75
+ } else {
76
+ // No named profile in play — fall back to the legacy single-file layout.
77
+ const localPath = _findLocalPath();
78
+ if (localPath) {
79
+ base = _readJson(localPath);
80
+ source = { kind: 'local', path: localPath };
81
+ } else if (existsSync(GLOBAL_FILE)) {
82
+ base = _readGlobal();
83
+ source = { kind: 'global' };
84
+ }
85
+ }
43
86
 
44
87
  return {
45
- config: { ...globalFile, ...localFile, ...env },
46
- source: localPath ? 'local' : (existsSync(GLOBAL_FILE) ? 'global' : null)
88
+ config: { ...base, ...env },
89
+ source,
90
+ profile: selection.name
91
+ ? { name: selection.name, origin: selection.origin, missing: Boolean(selection.missing) }
92
+ : null
47
93
  };
48
94
  }
49
95
 
96
+ /**
97
+ * Decide which profile name applies, and where the decision came from.
98
+ * Order: flag > ZEYOS_PROFILE env > project pin (.zeyos/profile) > global active.
99
+ * `.zeyos/auth.json` (legacy local) deliberately sits BELOW the pin but is handled
100
+ * in loadConfigWithSource (it is not a named profile).
101
+ *
102
+ * @param {{ profileFlag?: string }} [opts]
103
+ * @returns {{ name: string|null, origin: 'flag'|'env'|'pin'|'active'|null, path?: string, missing?: boolean }}
104
+ */
105
+ export function resolveProfileSelection(opts = {}) {
106
+ const flag = opts.profileFlag;
107
+ if (flag) return _withExistence({ name: flag, origin: 'flag' });
108
+
109
+ const envName = process.env.ZEYOS_PROFILE;
110
+ if (envName) return _withExistence({ name: envName, origin: 'env' });
111
+
112
+ const pin = readLocalPin();
113
+ // A pin only selects a named profile if there is NO legacy local auth.json that
114
+ // sits closer to the cwd (legacy projects keep working). When both exist at the
115
+ // same place the explicit pin wins.
116
+ if (pin) {
117
+ const localPath = _findLocalPath();
118
+ if (!localPath || _isSameOrShallower(pin.dir, localPath)) {
119
+ return _withExistence({ name: pin.name, origin: 'pin', path: pin.path });
120
+ }
121
+ }
122
+
123
+ // If a legacy local auth.json exists, it (not the global active profile) is the
124
+ // base — handled by the caller. Only fall through to the active profile when no
125
+ // local file shadows it.
126
+ if (_findLocalPath()) return { name: null, origin: null };
127
+
128
+ const active = getActiveProfileName();
129
+ if (active) return _withExistence({ name: active, origin: 'active' });
130
+
131
+ return { name: null, origin: null };
132
+ }
133
+
134
+ function _withExistence(sel) {
135
+ return { ...sel, missing: getProfile(sel.name) == null };
136
+ }
137
+
138
+ // ── Require ──────────────────────────────────────────────────────────────────
139
+
50
140
  /**
51
141
  * Require specific keys to be present; throws a human-friendly error if not.
52
142
  * @param {string[]} keys
@@ -67,12 +157,11 @@ export function requireConfig(keys, config) {
67
157
  throw new Error(`Missing required configuration:\n${messages.join('\n')}`);
68
158
  }
69
159
 
70
- // ── Save ─────────────────────────────────────────────────────────────────────
160
+ // ── Save (legacy single-file) ─────────────────────────────────────────────────
71
161
 
72
162
  /**
73
- * Save (merge) config values into the nearest .zeyos/auth.json found while
74
- * walking up, or create one in the current directory. Falls back to the
75
- * global file when `scope === 'global'`.
163
+ * Save (merge) config values into the nearest .zeyos/auth.json (or create one in
164
+ * the current directory), or the global credentials file when scope === 'global'.
76
165
  *
77
166
  * @param {CliConfig} updates
78
167
  * @param {'local'|'global'} scope
@@ -90,39 +179,163 @@ export function saveConfig(updates, scope = 'local') {
90
179
 
91
180
  /** Remove the stored tokens (leave connection params intact). */
92
181
  export function clearTokens(scope = 'local') {
93
- const strip = o => {
94
- const { accessToken, refreshToken, expiresAt, refreshTokenExpiresAt, ...rest } = o;
95
- return rest;
96
- };
97
182
  if (scope === 'global') {
98
- _writeGlobal(strip(_readGlobal()));
183
+ _writeGlobal(_stripTokens(_readGlobal()));
99
184
  return;
100
185
  }
101
186
  const path = _findLocalPath();
102
- if (path) _writeJson(path, strip(_readJson(path)));
187
+ if (path) _writeJson(path, _stripTokens(_readJson(path)));
188
+ }
189
+
190
+ /**
191
+ * Persist refreshed tokens back to wherever the active credentials came from.
192
+ * @param {ConfigSource|null} source
193
+ * @param {Partial<CliConfig>} tokens
194
+ */
195
+ export function persistTokens(source, tokens) {
196
+ if (!source) return;
197
+ const slice = {};
198
+ for (const k of TOKEN_KEYS) if (k in tokens) slice[k] = tokens[k];
199
+ if (source.kind === 'profile') {
200
+ upsertProfile(source.name, slice);
201
+ } else if (source.kind === 'global') {
202
+ saveConfig(slice, 'global');
203
+ } else {
204
+ saveConfig(slice, 'local');
205
+ }
206
+ }
207
+
208
+ /** Clear tokens from whichever store the source points at. */
209
+ export function clearTokensForSource(source) {
210
+ if (!source) return;
211
+ if (source.kind === 'profile') {
212
+ const prof = getProfile(source.name);
213
+ if (prof) upsertProfile(source.name, _stripTokens(prof), { replace: true });
214
+ } else if (source.kind === 'global') {
215
+ clearTokens('global');
216
+ } else {
217
+ clearTokens('local');
218
+ }
219
+ }
220
+
221
+ // ── Profiles ───────────────────────────────────────────────────────────────────
222
+
223
+ /** Read the profiles registry: { active, profiles }. */
224
+ export function readProfiles() {
225
+ const raw = existsSync(PROFILES_FILE) ? _readJson(PROFILES_FILE) : {};
226
+ return {
227
+ active: typeof raw.active === 'string' ? raw.active : null,
228
+ profiles: raw.profiles && typeof raw.profiles === 'object' ? raw.profiles : {}
229
+ };
230
+ }
231
+
232
+ /** List profile names with their (token-stripped-safe) creds and the active name. */
233
+ export function listProfiles() {
234
+ const { active, profiles } = readProfiles();
235
+ return {
236
+ active,
237
+ profiles: Object.fromEntries(Object.entries(profiles).map(([name, creds]) => [name, { ...creds }]))
238
+ };
239
+ }
240
+
241
+ /** Return a single profile's credentials, or null. */
242
+ export function getProfile(name) {
243
+ if (!name) return null;
244
+ const { profiles } = readProfiles();
245
+ return profiles[name] ? { ...profiles[name] } : null;
246
+ }
247
+
248
+ /**
249
+ * Create or update a profile (field merge by default).
250
+ * @param {string} name
251
+ * @param {Partial<CliConfig>} updates
252
+ * @param {{ replace?: boolean }} [opts] replace: overwrite instead of merge
253
+ */
254
+ export function upsertProfile(name, updates, opts = {}) {
255
+ if (!name) throw new Error('Profile name is required.');
256
+ const reg = readProfiles();
257
+ const current = opts.replace ? {} : (reg.profiles[name] || {});
258
+ reg.profiles[name] = _onlyCredKeys({ ...current, ...updates });
259
+ if (!reg.active) reg.active = name; // first profile becomes active
260
+ _writeProfiles(reg);
261
+ }
262
+
263
+ /** Delete a profile. Clears the active pointer if it referenced this profile. */
264
+ export function removeProfile(name) {
265
+ const reg = readProfiles();
266
+ if (!(name in reg.profiles)) return false;
267
+ delete reg.profiles[name];
268
+ if (reg.active === name) {
269
+ reg.active = Object.keys(reg.profiles)[0] ?? null;
270
+ }
271
+ _writeProfiles(reg);
272
+ return true;
273
+ }
274
+
275
+ /** Set the global active profile. Throws if it does not exist. */
276
+ export function setActiveProfile(name) {
277
+ const reg = readProfiles();
278
+ if (!(name in reg.profiles)) throw new Error(`No such profile: "${name}".`);
279
+ reg.active = name;
280
+ _writeProfiles(reg);
281
+ }
282
+
283
+ export function getActiveProfileName() {
284
+ return readProfiles().active;
285
+ }
286
+
287
+ // ── Project pin (.zeyos/profile) ─────────────────────────────────────────────
288
+
289
+ /** Read the nearest project pin: { name, path, dir } or null. */
290
+ export function readLocalPin() {
291
+ let dir = process.cwd();
292
+ for (let i = 0; i < 20; i++) {
293
+ const candidate = join(dir, LOCAL_DIR, PIN_FILE);
294
+ if (existsSync(candidate)) {
295
+ try {
296
+ const name = readFileSync(candidate, 'utf8').trim();
297
+ if (name) return { name, path: candidate, dir };
298
+ } catch { /* ignore unreadable pin */ }
299
+ }
300
+ const parent = dirname(dir);
301
+ if (parent === dir) break;
302
+ dir = parent;
303
+ }
304
+ return null;
103
305
  }
104
306
 
105
- /** Return the path of the active local .zeyos/auth.json (if any). */
106
- export function localConfigPath() {
107
- return _findLocalPath();
307
+ /** Pin a profile for the current project (writes ./.zeyos/profile). */
308
+ export function writeLocalPin(name, dir = process.cwd()) {
309
+ const path = join(dir, LOCAL_DIR, PIN_FILE);
310
+ mkdirSync(dirname(path), { recursive: true });
311
+ writeFileSync(path, `${name}\n`, { mode: 0o600 });
312
+ return path;
108
313
  }
109
314
 
110
- /** Return the global credentials file path. */
111
- export function globalConfigPath() {
112
- return GLOBAL_FILE;
315
+ /** Remove the nearest project pin, if any. Returns the removed path or null. */
316
+ export function clearLocalPin() {
317
+ const pin = readLocalPin();
318
+ if (pin) { unlinkSync(pin.path); return pin.path; }
319
+ return null;
113
320
  }
114
321
 
322
+ // ── Paths (for messages) ───────────────────────────────────────────────────────
323
+
324
+ export function localConfigPath() { return _findLocalPath(); }
325
+ export function globalConfigPath() { return GLOBAL_FILE; }
326
+ export function profilesConfigPath() { return PROFILES_FILE; }
327
+
115
328
  // ── Internals ────────────────────────────────────────────────────────────────
116
329
 
117
330
  function _fromEnv() {
118
331
  const e = process.env;
119
332
  const out = {};
120
- if (e.ZEYOS_BASE_URL) out.baseUrl = e.ZEYOS_BASE_URL;
121
- if (e.ZEYOS_INSTANCE) out.instance = e.ZEYOS_INSTANCE;
122
- if (e.ZEYOS_CLIENT_ID) out.clientId = e.ZEYOS_CLIENT_ID;
123
- if (e.ZEYOS_CLIENT_SECRET) out.clientSecret = e.ZEYOS_CLIENT_SECRET;
124
- if (e.ZEYOS_TOKEN) out.accessToken = e.ZEYOS_TOKEN;
125
- if (e.ZEYOS_REFRESH_TOKEN) out.refreshToken = e.ZEYOS_REFRESH_TOKEN;
333
+ if (e.ZEYOS_BASE_URL) out.baseUrl = e.ZEYOS_BASE_URL;
334
+ if (e.ZEYOS_INSTANCE) out.instance = e.ZEYOS_INSTANCE;
335
+ if (e.ZEYOS_CLIENT_ID) out.clientId = e.ZEYOS_CLIENT_ID;
336
+ if (e.ZEYOS_CLIENT_SECRET) out.clientSecret = e.ZEYOS_CLIENT_SECRET;
337
+ if (e.ZEYOS_TOKEN) out.accessToken = e.ZEYOS_TOKEN;
338
+ if (e.ZEYOS_REFRESH_TOKEN) out.refreshToken = e.ZEYOS_REFRESH_TOKEN;
126
339
  return out;
127
340
  }
128
341
 
@@ -138,6 +351,23 @@ function _findLocalPath() {
138
351
  return null;
139
352
  }
140
353
 
354
+ /** True when the pin directory is at or above the auth.json's directory. */
355
+ function _isSameOrShallower(pinDir, localPath) {
356
+ const localDir = dirname(dirname(localPath)); // strip /.zeyos/auth.json
357
+ return pinDir.length <= localDir.length;
358
+ }
359
+
360
+ function _onlyCredKeys(obj) {
361
+ const out = {};
362
+ for (const k of CRED_KEYS) if (obj[k] != null) out[k] = obj[k];
363
+ return out;
364
+ }
365
+
366
+ function _stripTokens(o) {
367
+ const { accessToken, refreshToken, expiresAt, refreshTokenExpiresAt, ...rest } = o;
368
+ return rest;
369
+ }
370
+
141
371
  function _readGlobal() {
142
372
  return existsSync(GLOBAL_FILE) ? _readJson(GLOBAL_FILE) : {};
143
373
  }
@@ -147,6 +377,11 @@ function _writeGlobal(data) {
147
377
  _writeJson(GLOBAL_FILE, data);
148
378
  }
149
379
 
380
+ function _writeProfiles(reg) {
381
+ mkdirSync(GLOBAL_DIR, { recursive: true });
382
+ _writeJson(PROFILES_FILE, { active: reg.active ?? null, profiles: reg.profiles ?? {} });
383
+ }
384
+
150
385
  function _readJson(path) {
151
386
  try {
152
387
  return JSON.parse(readFileSync(path, 'utf8'));
package/lib/flags.mjs CHANGED
@@ -10,7 +10,7 @@ const RESERVED_FLAGS = new Set([
10
10
  'no-color', 'force', 'fields', 'filter', 'filter-file', 'sort',
11
11
  'limit', 'offset', 'expand', 'base-url', 'client-id',
12
12
  'secret', 'scope', 'global', 'port', 'manual', 'show-token',
13
- 'extdata', 'tags', 'all', 'clean', 'query',
13
+ 'extdata', 'tags', 'all', 'clean', 'query', 'profile',
14
14
  ]);
15
15
 
16
16
  /**
package/lib/resources.mjs CHANGED
@@ -14,13 +14,21 @@
14
14
 
15
15
  /** @type {Record<string, ResourceDef>} */
16
16
  const REGISTRY = {
17
+ actionstep: {
18
+ list: 'listActionSteps',
19
+ get: 'getActionStep',
20
+ create: 'createActionStep',
21
+ update: 'updateActionStep',
22
+ delete: 'deleteActionStep',
23
+ fields: ['ID', 'actionnum', 'name', 'status', 'date', 'duedate', 'effort', 'ticket', 'task', 'account'],
24
+ },
17
25
  ticket: {
18
26
  list: 'listTickets',
19
27
  get: 'getTicket',
20
28
  create: 'createTicket',
21
29
  update: 'updateTicket',
22
30
  delete: 'deleteTicket',
23
- fields: ['ID', 'ticketnum', 'name', 'status', 'priority', 'duedate', 'lastmodified'],
31
+ fields: ['ID', 'ticketnum', 'name', 'status', 'priority', 'duedate', 'account', 'project', 'lastmodified'],
24
32
  },
25
33
  task: {
26
34
  list: 'listTasks',
@@ -28,7 +36,7 @@ const REGISTRY = {
28
36
  create: 'createTask',
29
37
  update: 'updateTask',
30
38
  delete: 'deleteTask',
31
- fields: ['ID', 'tasknum', 'name', 'status', 'priority', 'duedate', 'ticket'],
39
+ fields: ['ID', 'tasknum', 'name', 'status', 'priority', 'duedate', 'ticket', 'project', 'projectedeffort'],
32
40
  },
33
41
  account: {
34
42
  list: 'listAccounts',
@@ -84,7 +92,7 @@ const REGISTRY = {
84
92
  create: 'createMessage',
85
93
  update: 'updateMessage',
86
94
  delete: 'deleteMessage',
87
- fields: ['ID', 'subject', 'sender', 'created', 'read'],
95
+ fields: ['ID', 'date', 'mailbox', 'subject', 'sender_email', 'to_email', 'ticket', 'reference', 'messageid'],
88
96
  },
89
97
  item: {
90
98
  list: 'listItems',
@@ -144,6 +152,11 @@ const REGISTRY = {
144
152
  delete: 'deleteCampaign',
145
153
  fields: ['ID', 'name', 'status', 'startdate', 'enddate'],
146
154
  },
155
+ customfield: {
156
+ list: 'listCustomFields',
157
+ get: 'getCustomField',
158
+ fields: ['ID', 'name', 'identifier', 'context', 'reference', 'type', 'entity', 'activity'],
159
+ },
147
160
  file: {
148
161
  list: 'listFiles',
149
162
  get: 'getFile',
@@ -174,6 +187,13 @@ const REGISTRY = {
174
187
 
175
188
  const ALIASES = {
176
189
  // Plurals
190
+ actionsteps: 'actionstep',
191
+ 'action-steps': 'actionstep',
192
+ action_steps: 'actionstep',
193
+ timeentry: 'actionstep',
194
+ timeentries: 'actionstep',
195
+ 'time-entry': 'actionstep',
196
+ 'time-entries': 'actionstep',
177
197
  tickets: 'ticket',
178
198
  tasks: 'task',
179
199
  accounts: 'account',
@@ -193,6 +213,9 @@ const ALIASES = {
193
213
  payments: 'payment',
194
214
  opportunities:'opportunity',
195
215
  campaigns: 'campaign',
216
+ customfields: 'customfield',
217
+ custom_fields: 'customfield',
218
+ 'custom-fields': 'customfield',
196
219
  files: 'file',
197
220
  invitations: 'invitation',
198
221
  storages: 'storage',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zeyos/cli",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Command-line interface for the ZeyOS API",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -39,7 +39,7 @@
39
39
  "node": ">=18.3"
40
40
  },
41
41
  "dependencies": {
42
- "@zeyos/client": "^0.2.0"
42
+ "@zeyos/client": "^0.4.0"
43
43
  },
44
44
  "scripts": {
45
45
  "test": "node --test test/offline.mjs"