@emit-vision/cli 0.2.6 → 0.3.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 (3) hide show
  1. package/README.md +33 -1
  2. package/dist/index.js +865 -155
  3. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -7,30 +7,214 @@ import { exec } from "child_process";
7
7
  // src/config.ts
8
8
  import { homedir } from "os";
9
9
  import { join } from "path";
10
- import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
10
+ import {
11
+ readFileSync,
12
+ writeFileSync,
13
+ mkdirSync,
14
+ existsSync,
15
+ chmodSync
16
+ } from "fs";
17
+
18
+ // src/config-shape.ts
19
+ var DEFAULT_PROFILE_NAME = "default";
20
+ var PROFILE_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,39}$/;
21
+ function validateProfileName(name) {
22
+ if (!PROFILE_NAME_PATTERN.test(name)) {
23
+ throw new Error(
24
+ `Invalid profile name "${name}". Use 1-40 lowercase letters, digits, "-" or "_", starting with a letter or digit.`
25
+ );
26
+ }
27
+ }
28
+ function isRecord(value) {
29
+ return typeof value === "object" && value !== null && !Array.isArray(value);
30
+ }
31
+ function normalizeConfig(raw) {
32
+ const config = normalizeProfiles(raw);
33
+ if (isRecord(raw) && typeof raw.projectId === "string" && raw.projectId) {
34
+ config.projectId = raw.projectId;
35
+ }
36
+ return config;
37
+ }
38
+ function normalizeProfiles(raw) {
39
+ if (!isRecord(raw)) return { profiles: {} };
40
+ if (isRecord(raw.profiles)) {
41
+ const profiles = {};
42
+ for (const [name, value] of Object.entries(raw.profiles)) {
43
+ if (isRecord(value)) profiles[name] = value;
44
+ }
45
+ const currentProfile = typeof raw.currentProfile === "string" ? raw.currentProfile : void 0;
46
+ return { currentProfile, profiles };
47
+ }
48
+ const pat = typeof raw.pat === "string" ? raw.pat : void 0;
49
+ const apiUrl = typeof raw.apiUrl === "string" ? raw.apiUrl : void 0;
50
+ if (!pat && !apiUrl) return { profiles: {} };
51
+ return {
52
+ currentProfile: DEFAULT_PROFILE_NAME,
53
+ profiles: { [DEFAULT_PROFILE_NAME]: { apiUrl, pat } }
54
+ };
55
+ }
56
+
57
+ // src/config.ts
11
58
  var DEFAULT_API_URL = "https://api.emitvision.com";
12
- var CONFIG_DIR = join(homedir(), ".emit-vision");
13
- var CONFIG_PATH = join(CONFIG_DIR, "config.json");
59
+ function configDir() {
60
+ return process.env.EMIT_VISION_CONFIG_DIR || join(homedir(), ".emit-vision");
61
+ }
62
+ function configPath() {
63
+ return join(configDir(), "config.json");
64
+ }
14
65
  function loadConfig() {
15
- if (!existsSync(CONFIG_PATH)) return {};
66
+ const path = configPath();
67
+ if (!existsSync(path)) return { profiles: {} };
16
68
  try {
17
- return JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));
69
+ return normalizeConfig(JSON.parse(readFileSync(path, "utf-8")));
18
70
  } catch {
19
- return {};
71
+ return { profiles: {} };
20
72
  }
21
73
  }
22
- function saveConfig(patch) {
23
- mkdirSync(CONFIG_DIR, { recursive: true });
24
- const current = loadConfig();
25
- writeFileSync(
26
- CONFIG_PATH,
27
- JSON.stringify({ ...current, ...patch }, null, 2),
28
- "utf-8"
29
- );
74
+ function writeConfig(config) {
75
+ mkdirSync(configDir(), { recursive: true });
76
+ const path = configPath();
77
+ writeFileSync(path, JSON.stringify(config, null, 2), {
78
+ encoding: "utf-8",
79
+ mode: 384
80
+ });
81
+ chmodSync(path, 384);
82
+ }
83
+ function saveProfile(name, profile) {
84
+ validateProfileName(name);
85
+ const config = loadConfig();
86
+ const entry = { pat: profile.pat };
87
+ if (profile.apiUrl) entry.apiUrl = profile.apiUrl;
88
+ config.profiles[name] = entry;
89
+ if (!config.currentProfile || !config.profiles[config.currentProfile]) {
90
+ config.currentProfile = name;
91
+ }
92
+ writeConfig(config);
93
+ }
94
+ function removeProfile(name) {
95
+ const config = loadConfig();
96
+ if (!config.profiles[name]) return false;
97
+ delete config.profiles[name];
98
+ if (config.currentProfile === name) delete config.currentProfile;
99
+ writeConfig(config);
100
+ return true;
101
+ }
102
+ function setCurrentProfile(name) {
103
+ validateProfileName(name);
104
+ const config = loadConfig();
105
+ if (!config.profiles[name]) {
106
+ throw new Error(`Profile "${name}" not found.`);
107
+ }
108
+ config.currentProfile = name;
109
+ writeConfig(config);
30
110
  }
31
111
  function clearConfig() {
32
- mkdirSync(CONFIG_DIR, { recursive: true });
33
- writeFileSync(CONFIG_PATH, "{}", "utf-8");
112
+ writeConfig({ profiles: {} });
113
+ }
114
+
115
+ // src/repo-config.ts
116
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
117
+ import { dirname, join as join2, resolve } from "path";
118
+ var REPO_CONFIG_FILENAME = ".emit-vision.json";
119
+ var SECRET_KEYS = ["pat", "token", "apiKey"];
120
+ function parseRepoConfig(path) {
121
+ let raw;
122
+ try {
123
+ raw = JSON.parse(readFileSync2(path, "utf-8"));
124
+ } catch (err) {
125
+ throw new Error(
126
+ `Could not parse ${path}: ${err instanceof Error ? err.message : String(err)}`
127
+ );
128
+ }
129
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
130
+ throw new Error(`${path} must contain a JSON object.`);
131
+ }
132
+ const record = raw;
133
+ const secret = SECRET_KEYS.find((key) => key in record);
134
+ if (secret) {
135
+ throw new Error(
136
+ `${path} contains a "${secret}" key. This file is meant to be committed, so it must not hold a token. Run \`emit-vision login --profile <name>\` to store the token, then delete "${secret}" from the file.`
137
+ );
138
+ }
139
+ const config = { path };
140
+ if (typeof record.profile === "string" && record.profile) {
141
+ config.profile = record.profile;
142
+ }
143
+ if (typeof record.projectId === "string" && record.projectId) {
144
+ config.projectId = record.projectId;
145
+ }
146
+ return config;
147
+ }
148
+ function findRepoConfig(startDir = process.cwd()) {
149
+ let dir = resolve(startDir);
150
+ for (; ; ) {
151
+ const candidate = join2(dir, REPO_CONFIG_FILENAME);
152
+ if (existsSync2(candidate)) return parseRepoConfig(candidate);
153
+ if (existsSync2(join2(dir, ".git"))) return null;
154
+ const parent = dirname(dir);
155
+ if (parent === dir) return null;
156
+ dir = parent;
157
+ }
158
+ }
159
+
160
+ // src/credentials.ts
161
+ var activeProfileFlag;
162
+ function setActiveProfileFlag(name) {
163
+ activeProfileFlag = name;
164
+ }
165
+ function resolveCredentials(options = {}) {
166
+ const env = options.env ?? process.env;
167
+ const profileFlag = options.profileFlag ?? activeProfileFlag;
168
+ const config = normalizeConfig(loadConfig());
169
+ const named = (name, source) => {
170
+ const profile = config.profiles[name];
171
+ if (!profile) {
172
+ throw new Error(
173
+ `Profile "${name}" not found. Run \`emit-vision login --profile ${name}\`.`
174
+ );
175
+ }
176
+ return {
177
+ pat: profile.pat,
178
+ apiUrl: profile.apiUrl ?? DEFAULT_API_URL,
179
+ profile: name,
180
+ source
181
+ };
182
+ };
183
+ if (profileFlag) return named(profileFlag, "flag");
184
+ if (env.EMIT_VISION_PAT) {
185
+ const current = config.currentProfile ? config.profiles[config.currentProfile] : void 0;
186
+ return {
187
+ pat: env.EMIT_VISION_PAT,
188
+ apiUrl: env.EMIT_VISION_API_URL || current?.apiUrl || DEFAULT_API_URL,
189
+ source: "env-pat"
190
+ };
191
+ }
192
+ if (env.EMIT_VISION_PROFILE) {
193
+ return named(env.EMIT_VISION_PROFILE, "env-profile");
194
+ }
195
+ const repo = findRepoConfig(options.repoStartDir);
196
+ if (repo?.profile) {
197
+ if (!config.profiles[repo.profile]) {
198
+ throw new Error(
199
+ `This repo (${repo.path}) uses profile "${repo.profile}", which isn't logged in here. Run \`emit-vision login --profile ${repo.profile}\`.`
200
+ );
201
+ }
202
+ return { ...named(repo.profile, "repo"), repoConfigPath: repo.path };
203
+ }
204
+ if (config.currentProfile && config.profiles[config.currentProfile]) {
205
+ return named(config.currentProfile, "current");
206
+ }
207
+ return {
208
+ apiUrl: DEFAULT_API_URL,
209
+ profile: config.currentProfile ?? DEFAULT_PROFILE_NAME,
210
+ source: "default"
211
+ };
212
+ }
213
+ function targetProfileName() {
214
+ if (activeProfileFlag) return activeProfileFlag;
215
+ const env = process.env.EMIT_VISION_PROFILE;
216
+ if (env) return env;
217
+ return normalizeConfig(loadConfig()).currentProfile ?? DEFAULT_PROFILE_NAME;
34
218
  }
35
219
 
36
220
  // src/api.ts
@@ -71,12 +255,12 @@ function assertShape(data, expect, path) {
71
255
  }
72
256
  }
73
257
  async function apiFetch(path, options = {}) {
74
- const config = loadConfig();
75
- const apiUrl = options.apiUrl ?? config.apiUrl ?? DEFAULT_API_URL;
76
- const pat = options.pat ?? config.pat;
77
- const headers = {
78
- "Content-Type": "application/json"
79
- };
258
+ const needsResolve = !options.anonymous && (options.pat === void 0 || options.apiUrl === void 0);
259
+ const resolved = needsResolve ? resolveCredentials() : void 0;
260
+ const apiUrl = options.apiUrl ?? resolved?.apiUrl ?? DEFAULT_API_URL;
261
+ const pat = options.pat ?? resolved?.pat;
262
+ const headers = {};
263
+ if (options.body !== void 0) headers["Content-Type"] = "application/json";
80
264
  if (pat) headers["Authorization"] = `Bearer ${pat}`;
81
265
  let res;
82
266
  try {
@@ -127,26 +311,32 @@ async function runLogin(args) {
127
311
  if (apiUrlIdx !== -1 && args[apiUrlIdx + 1]) {
128
312
  apiUrl = args[apiUrlIdx + 1];
129
313
  }
314
+ const profile = targetProfileName();
315
+ apiUrl ??= loadConfig().profiles[profile]?.apiUrl ?? DEFAULT_API_URL;
130
316
  const tokenFlagIdx = args.indexOf("--token");
131
317
  const token = (tokenFlagIdx !== -1 ? args[tokenFlagIdx + 1] : void 0) ?? process.env.EMIT_VISION_PAT;
132
318
  if (token) {
133
- await runDirectLogin(token, apiUrl);
319
+ await runDirectLogin(token, apiUrl, profile);
134
320
  return;
135
321
  }
136
322
  const force = args.includes("--yes") || args.includes("-y");
137
323
  if (args.includes("--browser")) {
138
- await runBrowserLogin(apiUrl, force);
324
+ await runBrowserLogin(apiUrl, profile, force);
139
325
  return;
140
326
  }
141
- await runPasteLogin(apiUrl);
327
+ await runPasteLogin(apiUrl, profile);
142
328
  }
143
- async function runDirectLogin(pat, apiUrl) {
329
+ function persistLogin(pat, apiUrl, profile) {
330
+ saveProfile(profile, {
331
+ pat,
332
+ apiUrl: apiUrl === DEFAULT_API_URL ? void 0 : apiUrl
333
+ });
334
+ console.log(`Logged in successfully (profile: ${profile}).`);
335
+ }
336
+ async function runDirectLogin(pat, apiUrl, profile) {
144
337
  try {
145
338
  await apiFetch("/v1/management/projects", { pat, apiUrl });
146
- const patch = { pat };
147
- if (apiUrl) patch.apiUrl = apiUrl;
148
- saveConfig(patch);
149
- console.log("Logged in successfully.");
339
+ persistLogin(pat, apiUrl, profile);
150
340
  } catch (err) {
151
341
  console.error(
152
342
  `Login failed: ${err instanceof Error ? err.message : String(err)}`
@@ -154,7 +344,7 @@ async function runDirectLogin(pat, apiUrl) {
154
344
  process.exit(1);
155
345
  }
156
346
  }
157
- async function runPasteLogin(apiUrl) {
347
+ async function runPasteLogin(apiUrl, profile) {
158
348
  if (!process.stdin.isTTY) {
159
349
  console.error(
160
350
  "stdin is not a terminal.\nPass --token <pat> or set EMIT_VISION_PAT=<token> to log in non-interactively."
@@ -162,10 +352,10 @@ async function runPasteLogin(apiUrl) {
162
352
  process.exit(1);
163
353
  }
164
354
  const rl = createInterface({ input: process.stdin, output: process.stdout });
165
- const pat = await new Promise((resolve) => {
355
+ const pat = await new Promise((resolve2) => {
166
356
  rl.question("Paste your Personal Access Token: ", (answer) => {
167
357
  rl.close();
168
- resolve(answer.trim());
358
+ resolve2(answer.trim());
169
359
  });
170
360
  });
171
361
  if (!pat) {
@@ -174,10 +364,7 @@ async function runPasteLogin(apiUrl) {
174
364
  }
175
365
  try {
176
366
  await apiFetch("/v1/management/projects", { pat, apiUrl });
177
- const patch = { pat };
178
- if (apiUrl) patch.apiUrl = apiUrl;
179
- saveConfig(patch);
180
- console.log("Logged in successfully.");
367
+ persistLogin(pat, apiUrl, profile);
181
368
  } catch (err) {
182
369
  console.error(
183
370
  `Login failed: ${err instanceof Error ? err.message : String(err)}`
@@ -185,20 +372,23 @@ async function runPasteLogin(apiUrl) {
185
372
  process.exit(1);
186
373
  }
187
374
  }
188
- async function runBrowserLogin(apiUrl, force = false) {
189
- const config = loadConfig();
190
- if (config.pat && !force) {
375
+ async function runBrowserLogin(apiUrl, profile, force = false) {
376
+ const existing = loadConfig().profiles[profile];
377
+ if (existing?.pat && !force) {
191
378
  if (!process.stdin.isTTY) {
192
379
  } else {
193
380
  const rl = createInterface({
194
381
  input: process.stdin,
195
382
  output: process.stdout
196
383
  });
197
- const answer = await new Promise((resolve) => {
198
- rl.question("Already logged in. Overwrite? [y/N] ", (a) => {
199
- rl.close();
200
- resolve(a.trim().toLowerCase());
201
- });
384
+ const answer = await new Promise((resolve2) => {
385
+ rl.question(
386
+ `Profile "${profile}" is already logged in. Overwrite? [y/N] `,
387
+ (a) => {
388
+ rl.close();
389
+ resolve2(a.trim().toLowerCase());
390
+ }
391
+ );
202
392
  });
203
393
  if (answer !== "y" && answer !== "yes") {
204
394
  console.log("Aborted.");
@@ -210,7 +400,7 @@ async function runBrowserLogin(apiUrl, force = false) {
210
400
  try {
211
401
  initResult = await apiFetch(
212
402
  "/v1/cli-auth/init",
213
- { method: "POST", apiUrl }
403
+ { method: "POST", apiUrl, anonymous: true }
214
404
  );
215
405
  } catch (err) {
216
406
  console.error(
@@ -243,7 +433,7 @@ async function runBrowserLogin(apiUrl, force = false) {
243
433
  try {
244
434
  pollResult = await apiFetch(
245
435
  `/v1/cli-auth/poll/${encodeURIComponent(code)}`,
246
- { apiUrl }
436
+ { apiUrl, anonymous: true }
247
437
  );
248
438
  } catch {
249
439
  continue;
@@ -253,12 +443,7 @@ async function runBrowserLogin(apiUrl, force = false) {
253
443
  console.error("Authorization succeeded but no token was returned.");
254
444
  process.exit(1);
255
445
  }
256
- const patch = {
257
- pat: pollResult.rawToken
258
- };
259
- if (apiUrl) patch.apiUrl = apiUrl;
260
- saveConfig(patch);
261
- console.log("Logged in successfully.");
446
+ persistLogin(pollResult.rawToken, apiUrl, profile);
262
447
  return;
263
448
  }
264
449
  if (pollResult.status === "expired") {
@@ -278,13 +463,41 @@ function openBrowser(url) {
278
463
  });
279
464
  }
280
465
  function sleep(ms) {
281
- return new Promise((resolve) => setTimeout(resolve, ms));
466
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
282
467
  }
283
468
 
284
469
  // src/commands/logout.ts
285
- function runLogout() {
286
- clearConfig();
287
- console.log("Logged out.");
470
+ function runLogout(args = []) {
471
+ if (args.includes("--all")) {
472
+ clearConfig();
473
+ console.log("Logged out of all profiles.");
474
+ return;
475
+ }
476
+ const profile = targetProfileName();
477
+ if (removeProfile(profile)) {
478
+ console.log(`Logged out (profile: ${profile}).`);
479
+ } else {
480
+ console.log(`Profile "${profile}" is not logged in.`);
481
+ }
482
+ }
483
+
484
+ // src/lib/format-date.ts
485
+ var PLACEHOLDER = "\u2014";
486
+ function pad(value, width = 2) {
487
+ return String(value).padStart(width, "0");
488
+ }
489
+ function formatTimestamp(value) {
490
+ const date = new Date(value);
491
+ if (Number.isNaN(date.getTime())) return PLACEHOLDER;
492
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
493
+ }
494
+ function formatDate(value) {
495
+ const date = new Date(value);
496
+ if (Number.isNaN(date.getTime())) return PLACEHOLDER;
497
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
498
+ }
499
+ function formatDateOrDash(value) {
500
+ return value === null || value === void 0 ? PLACEHOLDER : formatDate(value);
288
501
  }
289
502
 
290
503
  // src/commands/project.ts
@@ -300,7 +513,7 @@ async function runProjectList() {
300
513
  p.name,
301
514
  p.id,
302
515
  p.environment ?? "\u2014",
303
- p.createdAt ? new Date(p.createdAt).toLocaleDateString() : "\u2014"
516
+ formatDateOrDash(p.createdAt)
304
517
  ]);
305
518
  printTable(["Name", "ID", "Environment", "Created"], rows);
306
519
  }
@@ -337,7 +550,13 @@ async function runProjectEnvCreate(args) {
337
550
  }
338
551
  const result = await apiFetch(`/v1/management/projects/${encodeURIComponent(projectId)}/environments`, {
339
552
  method: "POST",
340
- body: { name: envName, ...envType ? { type: envType } : {} }
553
+ // The API's body schema is { name, environmentType } — sending `type`
554
+ // made every invocation fail with `invalid_payload` (found 2026-09-11
555
+ // running the instance-telemetry runbook against CLI 0.2.5).
556
+ body: {
557
+ name: envName,
558
+ ...envType ? { environmentType: envType } : {}
559
+ }
341
560
  });
342
561
  if (json) {
343
562
  console.log(JSON.stringify(result, null, 2));
@@ -365,11 +584,35 @@ function printTable(headers, rows) {
365
584
 
366
585
  // src/commands/key.ts
367
586
  import { createInterface as createInterface2 } from "readline";
587
+
588
+ // src/lib/project-arg.ts
589
+ var PROJECT_ID_TIP = 'Tip: add "projectId" to .emit-vision.json to skip this argument.';
590
+ function repoProjectId(findConfig) {
591
+ return findConfig()?.projectId;
592
+ }
593
+ function withDefaultProjectId(args, findConfig = findRepoConfig) {
594
+ const first = args[0];
595
+ if (first && !first.startsWith("--")) return args;
596
+ const projectId = repoProjectId(findConfig);
597
+ return projectId ? [projectId, ...args] : args;
598
+ }
599
+ function withDefaultProjectFlag(args, findConfig = findRepoConfig) {
600
+ const idx = args.indexOf("--project");
601
+ if (idx !== -1 && args[idx + 1]) return args;
602
+ const projectId = repoProjectId(findConfig);
603
+ return projectId ? [...args, "--project", projectId] : args;
604
+ }
605
+ function exitMissingProjectId(usage) {
606
+ console.error(usage);
607
+ console.error(PROJECT_ID_TIP);
608
+ process.exit(1);
609
+ }
610
+
611
+ // src/commands/key.ts
368
612
  async function runKeyGet(args) {
369
- const projectId = args[0];
613
+ const projectId = withDefaultProjectId(args)[0];
370
614
  if (!projectId) {
371
- console.error("Usage: emit-vision key get <projectId>");
372
- process.exit(1);
615
+ exitMissingProjectId("Usage: emit-vision key get [projectId]");
373
616
  }
374
617
  const key = await apiFetch(
375
618
  `/v1/management/projects/${encodeURIComponent(projectId)}/keys`
@@ -377,14 +620,13 @@ async function runKeyGet(args) {
377
620
  console.log(`Prefix: ${key.keyPrefix}`);
378
621
  console.log(`Scope: ${key.scope}`);
379
622
  console.log(
380
- `Last used: ${key.lastUsedAt ? new Date(key.lastUsedAt).toLocaleDateString() : "Never"}`
623
+ `Last used: ${key.lastUsedAt ? formatDate(key.lastUsedAt) : "Never"}`
381
624
  );
382
625
  }
383
626
  async function runKeyRotate(args) {
384
- const projectId = args[0];
627
+ const projectId = withDefaultProjectId(args)[0];
385
628
  if (!projectId) {
386
- console.error("Usage: emit-vision key rotate <projectId> [--yes]");
387
- process.exit(1);
629
+ exitMissingProjectId("Usage: emit-vision key rotate [projectId] [--yes]");
388
630
  }
389
631
  const confirmed = args.includes("--yes") || args.includes("-y");
390
632
  if (!confirmed) {
@@ -398,12 +640,12 @@ async function runKeyRotate(args) {
398
640
  input: process.stdin,
399
641
  output: process.stdout
400
642
  });
401
- const answer = await new Promise((resolve) => {
643
+ const answer = await new Promise((resolve2) => {
402
644
  rl.question(
403
645
  "Rotate the ingest key? This will invalidate the current key. [y/N] ",
404
646
  (a) => {
405
647
  rl.close();
406
- resolve(a.trim().toLowerCase());
648
+ resolve2(a.trim().toLowerCase());
407
649
  }
408
650
  );
409
651
  });
@@ -436,6 +678,8 @@ function parseFlags(args) {
436
678
  flags[arg.slice(2)] = args[++i];
437
679
  } else if (arg === "--json") {
438
680
  flags.json = "true";
681
+ } else if (arg === "--system") {
682
+ flags.system = "true";
439
683
  }
440
684
  }
441
685
  return flags;
@@ -468,16 +712,16 @@ function truncate(value, max) {
468
712
  return value.length > max ? `${value.slice(0, max - 3)}...` : value;
469
713
  }
470
714
  async function runEventsRecent(args) {
471
- const [projectId, ...rest2] = args;
715
+ const [projectId, ...rest2] = withDefaultProjectId(args);
472
716
  if (!projectId) {
473
- console.error(
474
- "Usage: emit-vision events recent <projectId> [--from <iso>] [--to <iso>] [--environment <env>] [--limit <n>] [--json]"
717
+ exitMissingProjectId(
718
+ "Usage: emit-vision events recent [projectId] [--from <iso>] [--to <iso>] [--environment <env>] [--limit <n>] [--system] [--json]"
475
719
  );
476
- process.exit(1);
477
720
  }
478
721
  const flags = parseFlags(rest2);
722
+ const qs = buildQs(projectId, flags);
479
723
  const events = await apiFetch(
480
- `/v1/events/recent?${buildQs(projectId, flags)}`,
724
+ `/v1/events/recent?${qs}${flags.system ? "&eventType=system" : ""}`,
481
725
  { expect: RECENT_FIELDS }
482
726
  );
483
727
  if (flags.json) {
@@ -491,7 +735,7 @@ async function runEventsRecent(args) {
491
735
  printTable(
492
736
  ["Timestamp", "Name", "User", "Environment"],
493
737
  events.map((e) => [
494
- new Date(e.timestamp).toLocaleString(),
738
+ formatTimestamp(e.timestamp),
495
739
  e.event_name,
496
740
  e.user_id || null,
497
741
  e.environment || null
@@ -499,12 +743,11 @@ async function runEventsRecent(args) {
499
743
  );
500
744
  }
501
745
  async function runErrorsRecent(args) {
502
- const [projectId, ...rest2] = args;
746
+ const [projectId, ...rest2] = withDefaultProjectId(args);
503
747
  if (!projectId) {
504
- console.error(
505
- "Usage: emit-vision errors recent <projectId> [--from <iso>] [--to <iso>] [--environment <env>] [--limit <n>] [--json]"
748
+ exitMissingProjectId(
749
+ "Usage: emit-vision errors recent [projectId] [--from <iso>] [--to <iso>] [--environment <env>] [--limit <n>] [--json]"
506
750
  );
507
- process.exit(1);
508
751
  }
509
752
  const flags = parseFlags(rest2);
510
753
  const errors = await apiFetch(
@@ -522,7 +765,7 @@ async function runErrorsRecent(args) {
522
765
  printTable(
523
766
  ["Timestamp", "Name", "User", "Environment"],
524
767
  errors.map((e) => [
525
- new Date(e.timestamp).toLocaleString(),
768
+ formatTimestamp(e.timestamp),
526
769
  e.event_name,
527
770
  e.user_id || null,
528
771
  e.environment || null
@@ -530,12 +773,11 @@ async function runErrorsRecent(args) {
530
773
  );
531
774
  }
532
775
  async function runErrorsGrouped(args) {
533
- const [projectId, ...rest2] = args;
776
+ const [projectId, ...rest2] = withDefaultProjectId(args);
534
777
  if (!projectId) {
535
- console.error(
536
- "Usage: emit-vision errors grouped <projectId> [--from <iso>] [--to <iso>] [--environment <env>] [--limit <n>] [--json]"
778
+ exitMissingProjectId(
779
+ "Usage: emit-vision errors grouped [projectId] [--from <iso>] [--to <iso>] [--environment <env>] [--limit <n>] [--json]"
537
780
  );
538
- process.exit(1);
539
781
  }
540
782
  const flags = parseFlags(rest2);
541
783
  const groups = await apiFetch(
@@ -555,18 +797,17 @@ async function runErrorsGrouped(args) {
555
797
  groups.map((g) => [
556
798
  String(g.count),
557
799
  g.status,
558
- new Date(g.lastSeen).toLocaleString(),
800
+ formatTimestamp(g.lastSeen),
559
801
  truncate(g.sampleMessage, 60)
560
802
  ])
561
803
  );
562
804
  }
563
805
  async function runOverview(args) {
564
- const [projectId, ...rest2] = args;
806
+ const [projectId, ...rest2] = withDefaultProjectId(args);
565
807
  if (!projectId) {
566
- console.error(
567
- "Usage: emit-vision overview <projectId> [--from <iso>] [--to <iso>] [--environment <env>] [--json]"
808
+ exitMissingProjectId(
809
+ "Usage: emit-vision overview [projectId] [--from <iso>] [--to <iso>] [--environment <env>] [--json]"
568
810
  );
569
- process.exit(1);
570
811
  }
571
812
  const flags = parseFlags(rest2);
572
813
  const data = await apiFetch(
@@ -591,12 +832,11 @@ async function runOverview(args) {
591
832
  }
592
833
  }
593
834
  async function runLogs(args) {
594
- const [projectId, ...rest2] = args;
835
+ const [projectId, ...rest2] = withDefaultProjectId(args);
595
836
  if (!projectId) {
596
- console.error(
597
- "Usage: emit-vision logs <projectId> [--from <iso>] [--to <iso>] [--severity <level>] [--limit <n>] [--json]"
837
+ exitMissingProjectId(
838
+ "Usage: emit-vision logs [projectId] [--from <iso>] [--to <iso>] [--severity <level>] [--limit <n>] [--json]"
598
839
  );
599
- process.exit(1);
600
840
  }
601
841
  const flags = parseFlags(rest2);
602
842
  const { logs } = await apiFetch(
@@ -614,7 +854,7 @@ async function runLogs(args) {
614
854
  printTable(
615
855
  ["Timestamp", "Severity", "Message"],
616
856
  logs.map((l) => [
617
- new Date(l.timestamp).toLocaleString(),
857
+ formatTimestamp(l.timestamp),
618
858
  l.severity_text,
619
859
  truncate(l.body, 80)
620
860
  ])
@@ -622,13 +862,48 @@ async function runLogs(args) {
622
862
  }
623
863
 
624
864
  // src/commands/status.ts
865
+ function describeSource(creds) {
866
+ switch (creds.source) {
867
+ case "flag":
868
+ return "from --profile";
869
+ case "env-profile":
870
+ return "from EMIT_VISION_PROFILE";
871
+ case "repo":
872
+ return `from ${creds.repoConfigPath}`;
873
+ default:
874
+ return "current profile";
875
+ }
876
+ }
625
877
  async function runStatus(args = []) {
626
- const config = loadConfig();
627
- const apiUrl = config.apiUrl ?? DEFAULT_API_URL;
628
878
  const json = args.includes("--json");
879
+ let config;
880
+ try {
881
+ config = resolveCredentials();
882
+ } catch (err) {
883
+ const message = err instanceof Error ? err.message : String(err);
884
+ if (json) {
885
+ console.log(
886
+ JSON.stringify({ tokenPrefix: null, valid: false, error: message })
887
+ );
888
+ } else {
889
+ console.log(message);
890
+ }
891
+ return;
892
+ }
893
+ const apiUrl = config.apiUrl;
894
+ const profile = config.profile ?? null;
895
+ const source = config.source;
629
896
  if (!config.pat) {
630
897
  if (json) {
631
- console.log(JSON.stringify({ apiUrl, tokenPrefix: null, valid: false }));
898
+ console.log(
899
+ JSON.stringify({
900
+ apiUrl,
901
+ tokenPrefix: null,
902
+ valid: false,
903
+ profile,
904
+ source
905
+ })
906
+ );
632
907
  } else {
633
908
  console.log("Not logged in.");
634
909
  console.log(` API: ${apiUrl}`);
@@ -643,10 +918,19 @@ async function runStatus(args = []) {
643
918
  } catch {
644
919
  }
645
920
  if (json) {
646
- console.log(
647
- JSON.stringify({ apiUrl, tokenPrefix: config.pat.slice(0, 12), valid })
648
- );
921
+ const out = {
922
+ apiUrl,
923
+ tokenPrefix: config.pat.slice(0, 12),
924
+ valid,
925
+ profile,
926
+ source
927
+ };
928
+ if (config.repoConfigPath) out.repoConfigPath = config.repoConfigPath;
929
+ console.log(JSON.stringify(out));
649
930
  } else {
931
+ if (profile) {
932
+ console.log(` Profile: ${profile} (${describeSource(config)})`);
933
+ }
650
934
  console.log(` API: ${apiUrl}`);
651
935
  console.log(` Token: ${config.pat.slice(0, 12)}\u2026`);
652
936
  console.log(
@@ -655,6 +939,53 @@ async function runStatus(args = []) {
655
939
  }
656
940
  }
657
941
 
942
+ // src/commands/profile.ts
943
+ function resolvedProfileName() {
944
+ try {
945
+ return resolveCredentials().profile;
946
+ } catch {
947
+ return void 0;
948
+ }
949
+ }
950
+ function runProfileList(args = []) {
951
+ const config = loadConfig();
952
+ const active = resolvedProfileName();
953
+ const rows = Object.entries(config.profiles).map(([name, profile]) => ({
954
+ name,
955
+ apiUrl: profile.apiUrl ?? DEFAULT_API_URL,
956
+ tokenPrefix: profile.pat ? profile.pat.slice(0, 12) : null,
957
+ active: name === active
958
+ }));
959
+ if (args.includes("--json")) {
960
+ console.log(JSON.stringify(rows));
961
+ return;
962
+ }
963
+ if (rows.length === 0) {
964
+ console.log("No profiles. Run `emit-vision login --profile <name>`.");
965
+ return;
966
+ }
967
+ for (const row of rows) {
968
+ const token = row.tokenPrefix ? `${row.tokenPrefix}\u2026` : "(no token)";
969
+ console.log(
970
+ `${row.active ? "*" : " "} ${row.name} ${row.apiUrl} ${token}`
971
+ );
972
+ }
973
+ }
974
+ function runProfileUse(args = []) {
975
+ const name = args[0];
976
+ if (!name) {
977
+ throw new Error("Usage: emit-vision profile use <name>");
978
+ }
979
+ setCurrentProfile(name);
980
+ console.log(`Current profile: ${name}`);
981
+ const repo = findRepoConfig();
982
+ if (repo?.profile && repo.profile !== name) {
983
+ console.log(
984
+ `Note: ${repo.path} pins this repo to "${repo.profile}", which takes precedence here.`
985
+ );
986
+ }
987
+ }
988
+
658
989
  // src/commands/audience.ts
659
990
  import { writeFileSync as writeFileSync2 } from "fs";
660
991
  var VALUE_FLAGS = /* @__PURE__ */ new Set([
@@ -694,8 +1025,8 @@ function buildQs2(projectId, flags, extras) {
694
1025
  return params.toString();
695
1026
  }
696
1027
  async function apiFetchText(path) {
697
- const config = loadConfig();
698
- const apiUrl = config.apiUrl ?? DEFAULT_API_URL;
1028
+ const config = resolveCredentials();
1029
+ const apiUrl = config.apiUrl;
699
1030
  const headers = {};
700
1031
  if (config.pat) headers["Authorization"] = `Bearer ${config.pat}`;
701
1032
  const res = await fetch(`${apiUrl}${path}`, { headers });
@@ -703,12 +1034,11 @@ async function apiFetchText(path) {
703
1034
  return res.text();
704
1035
  }
705
1036
  async function runUsersList(args) {
706
- const [projectId, ...rest2] = args;
1037
+ const [projectId, ...rest2] = withDefaultProjectId(args);
707
1038
  if (!projectId) {
708
- console.error(
709
- "Usage: emit-vision users list <projectId> [--limit <n>] [--json]"
1039
+ exitMissingProjectId(
1040
+ "Usage: emit-vision users list [projectId] [--limit <n>] [--json]"
710
1041
  );
711
- process.exit(1);
712
1042
  }
713
1043
  const flags = parseFlags2(rest2);
714
1044
  const data = await apiFetch(
@@ -724,7 +1054,7 @@ async function runUsersList(args) {
724
1054
  u.name || "\u2014",
725
1055
  String(u.event_count),
726
1056
  String(u.error_count),
727
- u.last_seen ? new Date(u.last_seen).toLocaleDateString() : "\u2014"
1057
+ formatDateOrDash(u.last_seen)
728
1058
  ]);
729
1059
  printTable(
730
1060
  ["User ID", "Email", "Name", "Events", "Errors", "Last Seen"],
@@ -732,12 +1062,11 @@ async function runUsersList(args) {
732
1062
  );
733
1063
  }
734
1064
  async function runAudienceExport(args) {
735
- const [projectId, ...rest2] = args;
1065
+ const [projectId, ...rest2] = withDefaultProjectId(args);
736
1066
  if (!projectId) {
737
- console.error(
738
- "Usage: emit-vision audience export <projectId> [--segment dormant|power-user|high-errors|new] [--format csv|json] [--limit <n>] [--output <file>]"
1067
+ exitMissingProjectId(
1068
+ "Usage: emit-vision audience export [projectId] [--segment dormant|power-user|high-errors|new] [--format csv|json] [--limit <n>] [--output <file>]"
739
1069
  );
740
- process.exit(1);
741
1070
  }
742
1071
  const flags = parseFlags2(rest2);
743
1072
  const format = flags.format === "csv" ? "csv" : "json";
@@ -780,12 +1109,11 @@ async function deleMailFetch(baseUrl, apiKey, path, body) {
780
1109
  return res.json();
781
1110
  }
782
1111
  async function runAudienceSync(args) {
783
- const [projectId, ...rest2] = args;
1112
+ const [projectId, ...rest2] = withDefaultProjectId(args);
784
1113
  if (!projectId) {
785
- console.error(
786
- "Usage: emit-vision audience sync <projectId> [--segment <name>] [--tag <tag>] [--develemail-url <url>] [--develemail-key <key>] [--develemail-project <id>] [--limit <n>] [--dry-run]"
1114
+ exitMissingProjectId(
1115
+ "Usage: emit-vision audience sync [projectId] [--segment <name>] [--tag <tag>] [--develemail-url <url>] [--develemail-key <key>] [--develemail-project <id>] [--limit <n>] [--dry-run]"
787
1116
  );
788
- process.exit(1);
789
1117
  }
790
1118
  const flags = parseFlags2(rest2);
791
1119
  const deleUrl = flags["develemail-url"] ?? process.env.DEVELEMAIL_BASE_URL;
@@ -933,13 +1261,14 @@ function parseFlag(args, flag) {
933
1261
  function resolveProjectId(args) {
934
1262
  const fromFlag = parseFlag(args, "--project");
935
1263
  if (fromFlag) return fromFlag;
1264
+ const repoValue = parseFlag(withDefaultProjectFlag(args), "--project");
1265
+ if (repoValue) return repoValue;
936
1266
  const config = loadConfig();
937
1267
  const fromConfig = config.projectId;
938
1268
  if (typeof fromConfig === "string" && fromConfig) return fromConfig;
939
- console.error(
940
- "Missing --project flag. Usage: emit-vision pulse init --project <projectId> --name <name>"
1269
+ exitMissingProjectId(
1270
+ "Missing --project flag. Usage: emit-vision pulse init [--project <projectId>] --name <name>"
941
1271
  );
942
- process.exit(1);
943
1272
  }
944
1273
  async function runPulseInit(args) {
945
1274
  const projectId = resolveProjectId(args);
@@ -971,8 +1300,7 @@ async function runPulseInit(args) {
971
1300
  }
972
1301
  }
973
1302
  );
974
- const config = loadConfig();
975
- const apiUrl = config.apiUrl ?? "https://api.emitvision.com";
1303
+ const apiUrl = resolveCredentials().apiUrl;
976
1304
  const pingUrl = `${apiUrl}/v1/pulse/${check.slug}`;
977
1305
  console.log(`Check created: ${check.name}`);
978
1306
  console.log(` Slug: ${check.slug}`);
@@ -1006,7 +1334,7 @@ async function runPulseList(args) {
1006
1334
  c.name,
1007
1335
  c.slug,
1008
1336
  c.status,
1009
- c.lastPingAt ? new Date(c.lastPingAt).toLocaleString() : "never",
1337
+ c.lastPingAt ? formatTimestamp(c.lastPingAt) : "never",
1010
1338
  c.lastReportedRelease ?? "-",
1011
1339
  `${c.expectedIntervalSeconds}s`
1012
1340
  ]);
@@ -1111,12 +1439,11 @@ function repeatedValues(args, flag) {
1111
1439
  return values;
1112
1440
  }
1113
1441
  async function runFlagsList(args) {
1114
- const [projectId, ...rest2] = args;
1442
+ const [projectId, ...rest2] = withDefaultProjectId(args);
1115
1443
  if (!projectId) {
1116
- console.error(
1117
- "Usage: emit-vision flags list <projectId> [--limit <n>] [--offset <n>] [--json]"
1444
+ exitMissingProjectId(
1445
+ "Usage: emit-vision flags list [projectId] [--limit <n>] [--offset <n>] [--json]"
1118
1446
  );
1119
- process.exit(1);
1120
1447
  }
1121
1448
  const limit = valueOf(rest2, "--limit");
1122
1449
  const offset = valueOf(rest2, "--offset");
@@ -1142,17 +1469,14 @@ async function runFlagsList(args) {
1142
1469
  f.name,
1143
1470
  f.isEnabled ? "yes" : "no",
1144
1471
  `${f.rolloutPercentage ?? 100}%`,
1145
- f.updatedAt ? new Date(f.updatedAt).toLocaleDateString() : "\u2014"
1472
+ formatDateOrDash(f.updatedAt)
1146
1473
  ])
1147
1474
  );
1148
1475
  }
1149
1476
  async function runFlagsEvaluate(args) {
1150
- const usage = "Usage: emit-vision flags evaluate <projectId> --environment <env> [--user-key <key>] [--flag <key>]... [--json]";
1151
- const [projectId, ...rest2] = args;
1152
- if (!projectId) {
1153
- console.error(usage);
1154
- process.exit(1);
1155
- }
1477
+ const usage = "Usage: emit-vision flags evaluate [projectId] --environment <env> [--user-key <key>] [--flag <key>]... [--json]";
1478
+ const [projectId, ...rest2] = withDefaultProjectId(args);
1479
+ if (!projectId) exitMissingProjectId(usage);
1156
1480
  const environment = valueOf(rest2, "--environment");
1157
1481
  if (!environment) {
1158
1482
  console.error(usage);
@@ -1286,12 +1610,12 @@ async function runFlagsArchive(args) {
1286
1610
  input: process.stdin,
1287
1611
  output: process.stdout
1288
1612
  });
1289
- const answer = await new Promise((resolve) => {
1613
+ const answer = await new Promise((resolve2) => {
1290
1614
  rl.question(
1291
1615
  `Archive flag "${flagKey}"? This cannot be undone. [y/N] `,
1292
1616
  (a) => {
1293
1617
  rl.close();
1294
- resolve(a.trim().toLowerCase());
1618
+ resolve2(a.trim().toLowerCase());
1295
1619
  }
1296
1620
  );
1297
1621
  });
@@ -1313,7 +1637,7 @@ async function runFlagsArchive(args) {
1313
1637
  }
1314
1638
 
1315
1639
  // src/commands/flags-create.ts
1316
- import { readFileSync as readFileSync2 } from "fs";
1640
+ import { readFileSync as readFileSync3 } from "fs";
1317
1641
 
1318
1642
  // src/commands/flags-validate.ts
1319
1643
  var FLAG_KEY_RE = /^[a-z0-9_-]+$/;
@@ -1398,7 +1722,7 @@ function readJsonSource(source) {
1398
1722
  const label = source === "-" ? "stdin" : source;
1399
1723
  let raw;
1400
1724
  try {
1401
- raw = source === "-" ? readFileSync2(0, "utf-8") : readFileSync2(source, "utf-8");
1725
+ raw = source === "-" ? readFileSync3(0, "utf-8") : readFileSync3(source, "utf-8");
1402
1726
  } catch (err) {
1403
1727
  console.error(
1404
1728
  `Could not read ${label}: ${err instanceof Error ? err.message : String(err)}`
@@ -1539,9 +1863,367 @@ At least one of --name, --description, --environments, --default-variant is requ
1539
1863
  console.log(`${flag.key} updated.`);
1540
1864
  }
1541
1865
 
1866
+ // src/commands/migration-export.ts
1867
+ import { mkdirSync as mkdirSync2, createWriteStream } from "fs";
1868
+ import { writeFile } from "fs/promises";
1869
+ import { join as join3 } from "path";
1870
+
1871
+ // src/commands/migration-shared.ts
1872
+ var MIGRATION_SCHEMA_VERSION = 1;
1873
+ var MIGRATION_CLICKHOUSE_TABLES = [
1874
+ "telemetry_events",
1875
+ "error_fingerprints",
1876
+ "error_occurrences",
1877
+ "crawler_hits"
1878
+ ];
1879
+ var MIGRATION_TIMESTAMPED_TABLES = /* @__PURE__ */ new Set([
1880
+ "telemetry_events",
1881
+ "error_occurrences",
1882
+ "crawler_hits"
1883
+ ]);
1884
+ function parseFlagArg(args, name) {
1885
+ const idx = args.indexOf(name);
1886
+ return idx !== -1 ? args[idx + 1] : void 0;
1887
+ }
1888
+ var DataRangeTracker = class {
1889
+ earliest = null;
1890
+ latest = null;
1891
+ observe(timestamp) {
1892
+ if (typeof timestamp !== "string" || !timestamp) return;
1893
+ if (this.earliest === null || timestamp < this.earliest) {
1894
+ this.earliest = timestamp;
1895
+ }
1896
+ if (this.latest === null || timestamp > this.latest) {
1897
+ this.latest = timestamp;
1898
+ }
1899
+ }
1900
+ result() {
1901
+ if (this.earliest === null || this.latest === null) return null;
1902
+ return { earliest: this.earliest, latest: this.latest };
1903
+ }
1904
+ };
1905
+
1906
+ // src/commands/migration-export.ts
1907
+ var PAGE_LIMIT = 5e3;
1908
+ async function runMigrationExport(args) {
1909
+ if (!args.includes("--all")) {
1910
+ console.error(
1911
+ "Usage: emit-vision export --all --out <directory> [--api-url <url>]"
1912
+ );
1913
+ process.exit(1);
1914
+ }
1915
+ const out = parseFlagArg(args, "--out");
1916
+ const apiUrl = parseFlagArg(args, "--api-url");
1917
+ if (!out) {
1918
+ console.error(
1919
+ "Usage: emit-vision export --all --out <directory> [--api-url <url>]"
1920
+ );
1921
+ process.exit(1);
1922
+ }
1923
+ mkdirSync2(out, { recursive: true });
1924
+ console.log("Fetching export size preview\u2026");
1925
+ const preview = await apiFetch(
1926
+ "/v1/admin/migration/manifest",
1927
+ {
1928
+ apiUrl
1929
+ }
1930
+ );
1931
+ for (const [table, count] of Object.entries(preview.tables)) {
1932
+ console.log(` ${table}: ${count.toLocaleString()}`);
1933
+ }
1934
+ console.log("\nExporting organization, projects, flags, alerts, segments\u2026");
1935
+ const { data } = await apiFetch(
1936
+ "/v1/admin/migration/export/postgres",
1937
+ { apiUrl }
1938
+ );
1939
+ await writeFile(join3(out, "postgres.json"), JSON.stringify(data, null, 2));
1940
+ const writtenCounts = {
1941
+ organization: 1,
1942
+ projects: data.projects.length,
1943
+ project_members: data.projectMembers.length,
1944
+ users: data.organizationMembers.length,
1945
+ feature_flags: data.featureFlags.length,
1946
+ feature_flag_variants: data.featureFlagVariants.length,
1947
+ alert_rules: data.alertRules.length,
1948
+ saved_segments: data.savedSegments.length
1949
+ };
1950
+ const dataRange = new DataRangeTracker();
1951
+ for (const table of MIGRATION_CLICKHOUSE_TABLES) {
1952
+ console.log(`Exporting ${table}\u2026`);
1953
+ const written = await exportClickHouseTable({
1954
+ table,
1955
+ out,
1956
+ apiUrl,
1957
+ dataRange
1958
+ });
1959
+ writtenCounts[table] = written;
1960
+ console.log(` ${table}: ${written.toLocaleString()} rows`);
1961
+ }
1962
+ const manifest = {
1963
+ schemaVersion: MIGRATION_SCHEMA_VERSION,
1964
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
1965
+ sourceOrganizationId: preview.sourceOrganizationId,
1966
+ sourceApiUrl: apiUrl ?? "",
1967
+ tables: writtenCounts,
1968
+ dataRange: dataRange.result()
1969
+ };
1970
+ await writeFile(
1971
+ join3(out, "manifest.json"),
1972
+ JSON.stringify(manifest, null, 2)
1973
+ );
1974
+ console.log(`
1975
+ Export complete: ${out}`);
1976
+ console.log(
1977
+ "Run `emit-vision import " + out + "` against the destination to migrate."
1978
+ );
1979
+ }
1980
+ async function exportClickHouseTable(params) {
1981
+ const file = createWriteStream(join3(params.out, `${params.table}.ndjson`));
1982
+ const trackTimestamp = MIGRATION_TIMESTAMPED_TABLES.has(params.table);
1983
+ let cursor = null;
1984
+ let total = 0;
1985
+ do {
1986
+ const query = new URLSearchParams({ limit: String(PAGE_LIMIT) });
1987
+ if (cursor) query.set("cursor", cursor);
1988
+ const page = await apiFetch(
1989
+ `/v1/admin/migration/export/clickhouse/${params.table}?${query.toString()}`,
1990
+ { apiUrl: params.apiUrl }
1991
+ );
1992
+ for (const row of page.rows) {
1993
+ if (trackTimestamp) params.dataRange.observe(row.timestamp);
1994
+ file.write(`${JSON.stringify(row)}
1995
+ `);
1996
+ }
1997
+ total += page.count;
1998
+ cursor = page.nextCursor;
1999
+ } while (cursor !== null);
2000
+ await new Promise((resolve2, reject) => {
2001
+ file.end(
2002
+ (err) => err ? reject(err) : resolve2()
2003
+ );
2004
+ });
2005
+ return total;
2006
+ }
2007
+
2008
+ // src/commands/migration-import.ts
2009
+ import { createInterface as createInterface4 } from "readline";
2010
+ import { createReadStream, existsSync as existsSync3 } from "fs";
2011
+ import { readFile } from "fs/promises";
2012
+ import { join as join4 } from "path";
2013
+ var BATCH_SIZE = 2e3;
2014
+ async function runMigrationImport(args) {
2015
+ const dir = args.find((a) => !a.startsWith("--"));
2016
+ const apiUrl = parseFlagArg(args, "--api-url");
2017
+ const dryRunOnly = args.includes("--dry-run");
2018
+ const confirmed = args.includes("--yes") || args.includes("-y");
2019
+ if (!dir) {
2020
+ console.error(
2021
+ "Usage: emit-vision import <archiveDirectory> [--dry-run] [--yes] [--api-url <url>]"
2022
+ );
2023
+ process.exit(1);
2024
+ }
2025
+ const manifest = await readJson(
2026
+ join4(dir, "manifest.json")
2027
+ );
2028
+ const data = await readJson(join4(dir, "postgres.json"));
2029
+ const planResponse = await apiFetch(
2030
+ "/v1/admin/migration/import",
2031
+ {
2032
+ method: "POST",
2033
+ apiUrl,
2034
+ body: { manifest, data, dataRange: manifest.dataRange, dryRun: true }
2035
+ }
2036
+ );
2037
+ printPlan(planResponse.result, manifest);
2038
+ if (dryRunOnly) return;
2039
+ if (!confirmed) {
2040
+ if (!process.stdin.isTTY) {
2041
+ console.error(
2042
+ "stdin is not a terminal.\nPass --yes to confirm the import non-interactively."
2043
+ );
2044
+ process.exit(1);
2045
+ }
2046
+ const rl = createInterface4({
2047
+ input: process.stdin,
2048
+ output: process.stdout
2049
+ });
2050
+ const answer = await new Promise((resolve2) => {
2051
+ rl.question("Proceed with this import? [y/N] ", (a) => {
2052
+ rl.close();
2053
+ resolve2(a.trim().toLowerCase());
2054
+ });
2055
+ });
2056
+ if (answer !== "y" && answer !== "yes") {
2057
+ console.log("Aborted.");
2058
+ return;
2059
+ }
2060
+ }
2061
+ const { result } = await apiFetch(
2062
+ "/v1/admin/migration/import",
2063
+ {
2064
+ method: "POST",
2065
+ apiUrl,
2066
+ body: { manifest, data, dataRange: manifest.dataRange }
2067
+ }
2068
+ );
2069
+ console.log(`
2070
+ Created organization ${result.organizationId}.`);
2071
+ const clickhouseCounts = {};
2072
+ for (const table of MIGRATION_CLICKHOUSE_TABLES) {
2073
+ const file = join4(dir, `${table}.ndjson`);
2074
+ if (!existsSync3(file)) {
2075
+ clickhouseCounts[table] = 0;
2076
+ continue;
2077
+ }
2078
+ console.log(`Importing ${table}\u2026`);
2079
+ clickhouseCounts[table] = await importClickHouseTable({
2080
+ file,
2081
+ table,
2082
+ apiUrl,
2083
+ organizationId: result.organizationId,
2084
+ idMap: result.idMap
2085
+ });
2086
+ }
2087
+ printReconciliation(manifest, result, clickhouseCounts);
2088
+ printApiKeys(result);
2089
+ printMembers(result);
2090
+ }
2091
+ async function readJson(path) {
2092
+ try {
2093
+ return JSON.parse(await readFile(path, "utf-8"));
2094
+ } catch (err) {
2095
+ console.error(
2096
+ `Failed to read ${path}: ${err instanceof Error ? err.message : String(err)}
2097
+ Is this a complete archive produced by \`emit-vision export --all\`?`
2098
+ );
2099
+ process.exit(1);
2100
+ }
2101
+ }
2102
+ function printPlan(plan, manifest) {
2103
+ console.log(`
2104
+ Plan for organization "${manifest.sourceOrganizationId}":`);
2105
+ console.log(` Projects to import: ${plan.counts.projects}`);
2106
+ if (plan.projectsOverPlanLimit.length > 0) {
2107
+ console.log(
2108
+ ` \u26A0 Over the free plan's project limit, will NOT be imported: ${plan.projectsOverPlanLimit.join(", ")}`
2109
+ );
2110
+ }
2111
+ if (plan.retentionWarning) {
2112
+ console.log(` \u26A0 ${plan.retentionWarning}`);
2113
+ }
2114
+ console.log(
2115
+ ` Members to invite (existing accounts): ${plan.invitedMembers.length}`
2116
+ );
2117
+ if (plan.unresolvedMembers.length > 0) {
2118
+ console.log(
2119
+ ` Members needing a manual invite (no account yet): ${plan.unresolvedMembers.join(", ")}`
2120
+ );
2121
+ }
2122
+ }
2123
+ async function importClickHouseTable(params) {
2124
+ const rl = createInterface4({
2125
+ input: createReadStream(params.file),
2126
+ crlfDelay: Infinity
2127
+ });
2128
+ let batch = [];
2129
+ let total = 0;
2130
+ const flush = async () => {
2131
+ if (batch.length === 0) return;
2132
+ const { inserted } = await apiFetch(
2133
+ `/v1/admin/migration/import/${encodeURIComponent(params.organizationId)}/clickhouse/${params.table}`,
2134
+ {
2135
+ method: "POST",
2136
+ apiUrl: params.apiUrl,
2137
+ body: { idMap: params.idMap, rows: batch }
2138
+ }
2139
+ );
2140
+ total += inserted;
2141
+ batch = [];
2142
+ };
2143
+ for await (const line of rl) {
2144
+ if (!line.trim()) continue;
2145
+ batch.push(JSON.parse(line));
2146
+ if (batch.length >= BATCH_SIZE) await flush();
2147
+ }
2148
+ await flush();
2149
+ console.log(` ${params.table}: ${total.toLocaleString()} rows imported`);
2150
+ return total;
2151
+ }
2152
+ function printReconciliation(manifest, result, clickhouseCounts) {
2153
+ const actual = {
2154
+ ...result.counts,
2155
+ ...clickhouseCounts
2156
+ };
2157
+ console.log(
2158
+ "\nReconciliation (expected from archive vs. actually imported):"
2159
+ );
2160
+ for (const [table, expected] of Object.entries(manifest.tables)) {
2161
+ if (table === "organization" || table === "users") continue;
2162
+ const got = actual[table];
2163
+ if (got === void 0) continue;
2164
+ const flag = got === expected ? "\u2713" : "\u26A0";
2165
+ console.log(
2166
+ ` ${flag} ${table}: ${got.toLocaleString()} / ${expected.toLocaleString()}`
2167
+ );
2168
+ }
2169
+ }
2170
+ function printApiKeys(result) {
2171
+ if (result.apiKeys.length === 0) return;
2172
+ console.log(
2173
+ "\nNew API keys (source keys can't be recovered \u2014 copy these now, then update your SDKs):"
2174
+ );
2175
+ for (const key of result.apiKeys) {
2176
+ console.log(` ${key.projectName} (${key.type}): ${key.rawKey}`);
2177
+ }
2178
+ }
2179
+ function printMembers(result) {
2180
+ if (result.invitedMembers.length > 0) {
2181
+ console.log(
2182
+ `
2183
+ Invited (pending acceptance): ${result.invitedMembers.join(", ")}`
2184
+ );
2185
+ }
2186
+ if (result.unresolvedMembers.length > 0) {
2187
+ console.log(
2188
+ `Need a manual invite (no hosted account yet): ${result.unresolvedMembers.join(", ")}`
2189
+ );
2190
+ }
2191
+ }
2192
+
2193
+ // src/lib/global-flags.ts
2194
+ function extractGlobalFlags(argv) {
2195
+ const rest2 = [];
2196
+ let profile;
2197
+ for (let i = 0; i < argv.length; i++) {
2198
+ const arg = argv[i];
2199
+ if (arg === "--profile") {
2200
+ const value = argv[i + 1];
2201
+ if (value === void 0 || value.startsWith("--")) {
2202
+ throw new Error("--profile requires a profile name.");
2203
+ }
2204
+ profile = value;
2205
+ i++;
2206
+ } else if (arg.startsWith("--profile=")) {
2207
+ profile = arg.slice("--profile=".length);
2208
+ if (!profile) throw new Error("--profile requires a profile name.");
2209
+ } else {
2210
+ rest2.push(arg);
2211
+ }
2212
+ }
2213
+ return { profile, argv: rest2 };
2214
+ }
2215
+
1542
2216
  // src/index.ts
1543
- var VERSION = "0.2.5";
1544
- var [cmd, subcmd, ...rest] = process.argv.slice(2);
2217
+ var VERSION = "0.3.0";
2218
+ var globalFlags;
2219
+ try {
2220
+ globalFlags = extractGlobalFlags(process.argv.slice(2));
2221
+ } catch (err) {
2222
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
2223
+ process.exit(1);
2224
+ }
2225
+ setActiveProfileFlag(globalFlags.profile);
2226
+ var [cmd, subcmd, ...rest] = globalFlags.argv;
1545
2227
  async function main() {
1546
2228
  if (cmd === "--version" || cmd === "-v") {
1547
2229
  console.log(VERSION);
@@ -1551,7 +2233,16 @@ async function main() {
1551
2233
  if (cmd === "login") {
1552
2234
  await runLogin(subcmd ? [subcmd, ...rest] : rest);
1553
2235
  } else if (cmd === "logout") {
1554
- runLogout();
2236
+ runLogout(subcmd ? [subcmd, ...rest] : rest);
2237
+ } else if (cmd === "profile") {
2238
+ if (subcmd === "list") {
2239
+ runProfileList(rest);
2240
+ } else if (subcmd === "use") {
2241
+ runProfileUse(rest);
2242
+ } else {
2243
+ printHelp();
2244
+ process.exit(1);
2245
+ }
1555
2246
  } else if (cmd === "project") {
1556
2247
  if (subcmd === "list") {
1557
2248
  await runProjectList();
@@ -1621,6 +2312,10 @@ async function main() {
1621
2312
  printHelp();
1622
2313
  process.exit(1);
1623
2314
  }
2315
+ } else if (cmd === "export") {
2316
+ await runMigrationExport(subcmd ? [subcmd, ...rest] : rest);
2317
+ } else if (cmd === "import") {
2318
+ await runMigrationImport(subcmd ? [subcmd, ...rest] : rest);
1624
2319
  } else if (cmd === "flags") {
1625
2320
  if (subcmd === "list") {
1626
2321
  await runFlagsList(rest);
@@ -1673,40 +2368,46 @@ function printHelp() {
1673
2368
  Commands:
1674
2369
  login [--token <pat>] [--api-url <url>] Authenticate (non-interactive: --token or EMIT_VISION_PAT env)
1675
2370
  login --browser [--yes] [--api-url <url>] Authenticate via browser OAuth
1676
- logout Clear stored credentials
1677
- status [--json] Show auth status and verify token
2371
+ logout [--all] Remove the active profile's credentials (--all removes every profile)
2372
+ status [--json] Show auth status, active profile and why, and verify token
2373
+ profile list [--json] List login profiles (* marks the one in use here)
2374
+ profile use <name> Set the current profile
1678
2375
 
1679
2376
  project list List your projects
1680
2377
  project create <name> [--json] Create a new project
1681
2378
  project env create <projectId> <name> [--type ...] [--json] Create a new environment
1682
- key get <projectId> Get ingest key info for a project
1683
- key rotate <projectId> [--yes] [--json] Rotate the ingest key (--yes skips confirmation)
2379
+ key get [projectId] Get ingest key info for a project
2380
+ key rotate [projectId] [--yes] [--json] Rotate the ingest key (--yes skips confirmation)
1684
2381
 
1685
- overview <projectId> [--from <iso>] [--to <iso>] [--environment <env>] [--json]
2382
+ overview [projectId] [--from <iso>] [--to <iso>] [--environment <env>] [--json]
1686
2383
  Project summary (events, errors, top events)
1687
- events recent <projectId> [--from <iso>] [--to <iso>] [--environment <env>] [--limit <n>] [--json]
2384
+ events recent [projectId] [--from <iso>] [--to <iso>] [--environment <env>] [--limit <n>] [--json]
1688
2385
  Recent events
1689
- errors recent <projectId> [--from <iso>] [--to <iso>] [--environment <env>] [--limit <n>] [--json]
2386
+ errors recent [projectId] [--from <iso>] [--to <iso>] [--environment <env>] [--limit <n>] [--json]
1690
2387
  Recent error occurrences
1691
- errors grouped <projectId> [--from <iso>] [--to <iso>] [--environment <env>] [--limit <n>] [--json]
2388
+ errors grouped [projectId] [--from <iso>] [--to <iso>] [--environment <env>] [--limit <n>] [--json]
1692
2389
  Grouped/deduplicated errors with counts
1693
- logs <projectId> [--from <iso>] [--to <iso>] [--severity <level>] [--limit <n>] [--json]
2390
+ logs [projectId] [--from <iso>] [--to <iso>] [--severity <level>] [--limit <n>] [--json]
1694
2391
  Recent log entries
1695
2392
 
1696
- users list <projectId> [--limit <n>] [--json] Identified users with email, name, and activity stats
1697
- audience export <projectId> [--segment dormant|power-user|high-errors|new] [--format csv|json] [--limit <n>] [--output <file>]
2393
+ users list [projectId] [--limit <n>] [--json] Identified users with email, name, and activity stats
2394
+ audience export [projectId] [--segment dormant|power-user|high-errors|new] [--format csv|json] [--limit <n>] [--output <file>]
1698
2395
  Export audience contacts (default: JSON to stdout)
1699
- audience sync <projectId> [--segment <name>] [--tag <tag>] [--limit <n>] [--dry-run]
2396
+ audience sync [projectId] [--segment <name>] [--tag <tag>] [--limit <n>] [--dry-run]
1700
2397
  [--develemail-url <url>] [--develemail-key <key>] [--develemail-project <id>]
1701
2398
  Push audience to develemail contacts
1702
2399
 
1703
- pulse init --project <projectId> --name <name> [--interval <s>] [--grace <s>] [--verify] [--snippet <type>]
2400
+ pulse init [--project <projectId>] --name <name> [--interval <s>] [--grace <s>] [--verify] [--snippet <type>]
1704
2401
  Create a pulse check, print ping snippets (cURL, Docker, systemd, crontab)
1705
- pulse list --project <projectId> [--json] List pulse checks for a project
1706
- pulse status --project <projectId> [--json] Show check health with colored status indicators
2402
+ pulse list [--project <projectId>] [--json] List pulse checks for a project
2403
+ pulse status [--project <projectId>] [--json] Show check health with colored status indicators
1707
2404
 
1708
- flags list <projectId> [--limit <n>] [--offset <n>] [--json] List feature flags for a project
1709
- flags evaluate <projectId> --environment <env> [--user-key <key>] [--flag <key>]... [--json]
2405
+ export --all --out <directory> [--api-url <url>] Export an organization's full data for self-host \u2192 cloud migration
2406
+ import <archiveDirectory> [--dry-run] [--yes] [--api-url <url>]
2407
+ Import an export archive into a fresh organization
2408
+
2409
+ flags list [projectId] [--limit <n>] [--offset <n>] [--json] List feature flags for a project
2410
+ flags evaluate [projectId] --environment <env> [--user-key <key>] [--flag <key>]... [--json]
1710
2411
  Evaluate flags for a user/environment
1711
2412
  flags enable <projectId> <flagKey> [--json] Enable a flag (requires admin role)
1712
2413
  flags disable <projectId> <flagKey> [--json] Disable a flag (requires admin role)
@@ -1718,7 +2419,16 @@ Commands:
1718
2419
  flags update <projectId> <flagKey> [--name <name>] [--description <text>] [--environments <csv>] [--default-variant <key>] [--json]
1719
2420
  Update non-variant fields on a flag (requires admin role)
1720
2421
 
2422
+ --profile <name> Use a named login profile (any command; login saves to it)
1721
2423
  --version, -v Print CLI version
2424
+
2425
+ Environment:
2426
+ EMIT_VISION_PAT Use this token directly, no login needed
2427
+ EMIT_VISION_API_URL API URL to use with EMIT_VISION_PAT
2428
+ EMIT_VISION_PROFILE Profile to use when --profile is not given
2429
+ .emit-vision.json Repo file {"profile": "<name>", "projectId": "proj_..."} pins the profile and the
2430
+ default [projectId] for that repo (no tokens!)
2431
+ EMIT_VISION_CONFIG_DIR Config directory (default ~/.emit-vision)
1722
2432
  `);
1723
2433
  }
1724
2434
  main();