@emit-vision/cli 0.2.6 → 0.2.7

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 (2) hide show
  1. package/dist/index.js +372 -13
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -74,9 +74,8 @@ async function apiFetch(path, options = {}) {
74
74
  const config = loadConfig();
75
75
  const apiUrl = options.apiUrl ?? config.apiUrl ?? DEFAULT_API_URL;
76
76
  const pat = options.pat ?? config.pat;
77
- const headers = {
78
- "Content-Type": "application/json"
79
- };
77
+ const headers = {};
78
+ if (options.body !== void 0) headers["Content-Type"] = "application/json";
80
79
  if (pat) headers["Authorization"] = `Bearer ${pat}`;
81
80
  let res;
82
81
  try {
@@ -287,6 +286,25 @@ function runLogout() {
287
286
  console.log("Logged out.");
288
287
  }
289
288
 
289
+ // src/lib/format-date.ts
290
+ var PLACEHOLDER = "\u2014";
291
+ function pad(value, width = 2) {
292
+ return String(value).padStart(width, "0");
293
+ }
294
+ function formatTimestamp(value) {
295
+ const date = new Date(value);
296
+ if (Number.isNaN(date.getTime())) return PLACEHOLDER;
297
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
298
+ }
299
+ function formatDate(value) {
300
+ const date = new Date(value);
301
+ if (Number.isNaN(date.getTime())) return PLACEHOLDER;
302
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
303
+ }
304
+ function formatDateOrDash(value) {
305
+ return value === null || value === void 0 ? PLACEHOLDER : formatDate(value);
306
+ }
307
+
290
308
  // src/commands/project.ts
291
309
  async function runProjectList() {
292
310
  const projects = await apiFetch("/v1/management/projects");
@@ -300,7 +318,7 @@ async function runProjectList() {
300
318
  p.name,
301
319
  p.id,
302
320
  p.environment ?? "\u2014",
303
- p.createdAt ? new Date(p.createdAt).toLocaleDateString() : "\u2014"
321
+ formatDateOrDash(p.createdAt)
304
322
  ]);
305
323
  printTable(["Name", "ID", "Environment", "Created"], rows);
306
324
  }
@@ -337,7 +355,13 @@ async function runProjectEnvCreate(args) {
337
355
  }
338
356
  const result = await apiFetch(`/v1/management/projects/${encodeURIComponent(projectId)}/environments`, {
339
357
  method: "POST",
340
- body: { name: envName, ...envType ? { type: envType } : {} }
358
+ // The API's body schema is { name, environmentType } — sending `type`
359
+ // made every invocation fail with `invalid_payload` (found 2026-09-11
360
+ // running the instance-telemetry runbook against CLI 0.2.5).
361
+ body: {
362
+ name: envName,
363
+ ...envType ? { environmentType: envType } : {}
364
+ }
341
365
  });
342
366
  if (json) {
343
367
  console.log(JSON.stringify(result, null, 2));
@@ -377,7 +401,7 @@ async function runKeyGet(args) {
377
401
  console.log(`Prefix: ${key.keyPrefix}`);
378
402
  console.log(`Scope: ${key.scope}`);
379
403
  console.log(
380
- `Last used: ${key.lastUsedAt ? new Date(key.lastUsedAt).toLocaleDateString() : "Never"}`
404
+ `Last used: ${key.lastUsedAt ? formatDate(key.lastUsedAt) : "Never"}`
381
405
  );
382
406
  }
383
407
  async function runKeyRotate(args) {
@@ -491,7 +515,7 @@ async function runEventsRecent(args) {
491
515
  printTable(
492
516
  ["Timestamp", "Name", "User", "Environment"],
493
517
  events.map((e) => [
494
- new Date(e.timestamp).toLocaleString(),
518
+ formatTimestamp(e.timestamp),
495
519
  e.event_name,
496
520
  e.user_id || null,
497
521
  e.environment || null
@@ -522,7 +546,7 @@ async function runErrorsRecent(args) {
522
546
  printTable(
523
547
  ["Timestamp", "Name", "User", "Environment"],
524
548
  errors.map((e) => [
525
- new Date(e.timestamp).toLocaleString(),
549
+ formatTimestamp(e.timestamp),
526
550
  e.event_name,
527
551
  e.user_id || null,
528
552
  e.environment || null
@@ -555,7 +579,7 @@ async function runErrorsGrouped(args) {
555
579
  groups.map((g) => [
556
580
  String(g.count),
557
581
  g.status,
558
- new Date(g.lastSeen).toLocaleString(),
582
+ formatTimestamp(g.lastSeen),
559
583
  truncate(g.sampleMessage, 60)
560
584
  ])
561
585
  );
@@ -614,7 +638,7 @@ async function runLogs(args) {
614
638
  printTable(
615
639
  ["Timestamp", "Severity", "Message"],
616
640
  logs.map((l) => [
617
- new Date(l.timestamp).toLocaleString(),
641
+ formatTimestamp(l.timestamp),
618
642
  l.severity_text,
619
643
  truncate(l.body, 80)
620
644
  ])
@@ -724,7 +748,7 @@ async function runUsersList(args) {
724
748
  u.name || "\u2014",
725
749
  String(u.event_count),
726
750
  String(u.error_count),
727
- u.last_seen ? new Date(u.last_seen).toLocaleDateString() : "\u2014"
751
+ formatDateOrDash(u.last_seen)
728
752
  ]);
729
753
  printTable(
730
754
  ["User ID", "Email", "Name", "Events", "Errors", "Last Seen"],
@@ -1006,7 +1030,7 @@ async function runPulseList(args) {
1006
1030
  c.name,
1007
1031
  c.slug,
1008
1032
  c.status,
1009
- c.lastPingAt ? new Date(c.lastPingAt).toLocaleString() : "never",
1033
+ c.lastPingAt ? formatTimestamp(c.lastPingAt) : "never",
1010
1034
  c.lastReportedRelease ?? "-",
1011
1035
  `${c.expectedIntervalSeconds}s`
1012
1036
  ]);
@@ -1142,7 +1166,7 @@ async function runFlagsList(args) {
1142
1166
  f.name,
1143
1167
  f.isEnabled ? "yes" : "no",
1144
1168
  `${f.rolloutPercentage ?? 100}%`,
1145
- f.updatedAt ? new Date(f.updatedAt).toLocaleDateString() : "\u2014"
1169
+ formatDateOrDash(f.updatedAt)
1146
1170
  ])
1147
1171
  );
1148
1172
  }
@@ -1539,6 +1563,333 @@ At least one of --name, --description, --environments, --default-variant is requ
1539
1563
  console.log(`${flag.key} updated.`);
1540
1564
  }
1541
1565
 
1566
+ // src/commands/migration-export.ts
1567
+ import { mkdirSync as mkdirSync2, createWriteStream } from "fs";
1568
+ import { writeFile } from "fs/promises";
1569
+ import { join as join2 } from "path";
1570
+
1571
+ // src/commands/migration-shared.ts
1572
+ var MIGRATION_SCHEMA_VERSION = 1;
1573
+ var MIGRATION_CLICKHOUSE_TABLES = [
1574
+ "telemetry_events",
1575
+ "error_fingerprints",
1576
+ "error_occurrences",
1577
+ "crawler_hits"
1578
+ ];
1579
+ var MIGRATION_TIMESTAMPED_TABLES = /* @__PURE__ */ new Set([
1580
+ "telemetry_events",
1581
+ "error_occurrences",
1582
+ "crawler_hits"
1583
+ ]);
1584
+ function parseFlagArg(args, name) {
1585
+ const idx = args.indexOf(name);
1586
+ return idx !== -1 ? args[idx + 1] : void 0;
1587
+ }
1588
+ var DataRangeTracker = class {
1589
+ earliest = null;
1590
+ latest = null;
1591
+ observe(timestamp) {
1592
+ if (typeof timestamp !== "string" || !timestamp) return;
1593
+ if (this.earliest === null || timestamp < this.earliest) {
1594
+ this.earliest = timestamp;
1595
+ }
1596
+ if (this.latest === null || timestamp > this.latest) {
1597
+ this.latest = timestamp;
1598
+ }
1599
+ }
1600
+ result() {
1601
+ if (this.earliest === null || this.latest === null) return null;
1602
+ return { earliest: this.earliest, latest: this.latest };
1603
+ }
1604
+ };
1605
+
1606
+ // src/commands/migration-export.ts
1607
+ var PAGE_LIMIT = 5e3;
1608
+ async function runMigrationExport(args) {
1609
+ if (!args.includes("--all")) {
1610
+ console.error(
1611
+ "Usage: emit-vision export --all --out <directory> [--api-url <url>]"
1612
+ );
1613
+ process.exit(1);
1614
+ }
1615
+ const out = parseFlagArg(args, "--out");
1616
+ const apiUrl = parseFlagArg(args, "--api-url");
1617
+ if (!out) {
1618
+ console.error(
1619
+ "Usage: emit-vision export --all --out <directory> [--api-url <url>]"
1620
+ );
1621
+ process.exit(1);
1622
+ }
1623
+ mkdirSync2(out, { recursive: true });
1624
+ console.log("Fetching export size preview\u2026");
1625
+ const preview = await apiFetch(
1626
+ "/v1/admin/migration/manifest",
1627
+ {
1628
+ apiUrl
1629
+ }
1630
+ );
1631
+ for (const [table, count] of Object.entries(preview.tables)) {
1632
+ console.log(` ${table}: ${count.toLocaleString()}`);
1633
+ }
1634
+ console.log("\nExporting organization, projects, flags, alerts, segments\u2026");
1635
+ const { data } = await apiFetch(
1636
+ "/v1/admin/migration/export/postgres",
1637
+ { apiUrl }
1638
+ );
1639
+ await writeFile(join2(out, "postgres.json"), JSON.stringify(data, null, 2));
1640
+ const writtenCounts = {
1641
+ organization: 1,
1642
+ projects: data.projects.length,
1643
+ project_members: data.projectMembers.length,
1644
+ users: data.organizationMembers.length,
1645
+ feature_flags: data.featureFlags.length,
1646
+ feature_flag_variants: data.featureFlagVariants.length,
1647
+ alert_rules: data.alertRules.length,
1648
+ saved_segments: data.savedSegments.length
1649
+ };
1650
+ const dataRange = new DataRangeTracker();
1651
+ for (const table of MIGRATION_CLICKHOUSE_TABLES) {
1652
+ console.log(`Exporting ${table}\u2026`);
1653
+ const written = await exportClickHouseTable({
1654
+ table,
1655
+ out,
1656
+ apiUrl,
1657
+ dataRange
1658
+ });
1659
+ writtenCounts[table] = written;
1660
+ console.log(` ${table}: ${written.toLocaleString()} rows`);
1661
+ }
1662
+ const manifest = {
1663
+ schemaVersion: MIGRATION_SCHEMA_VERSION,
1664
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
1665
+ sourceOrganizationId: preview.sourceOrganizationId,
1666
+ sourceApiUrl: apiUrl ?? "",
1667
+ tables: writtenCounts,
1668
+ dataRange: dataRange.result()
1669
+ };
1670
+ await writeFile(
1671
+ join2(out, "manifest.json"),
1672
+ JSON.stringify(manifest, null, 2)
1673
+ );
1674
+ console.log(`
1675
+ Export complete: ${out}`);
1676
+ console.log(
1677
+ "Run `emit-vision import " + out + "` against the destination to migrate."
1678
+ );
1679
+ }
1680
+ async function exportClickHouseTable(params) {
1681
+ const file = createWriteStream(join2(params.out, `${params.table}.ndjson`));
1682
+ const trackTimestamp = MIGRATION_TIMESTAMPED_TABLES.has(params.table);
1683
+ let cursor = null;
1684
+ let total = 0;
1685
+ do {
1686
+ const query = new URLSearchParams({ limit: String(PAGE_LIMIT) });
1687
+ if (cursor) query.set("cursor", cursor);
1688
+ const page = await apiFetch(
1689
+ `/v1/admin/migration/export/clickhouse/${params.table}?${query.toString()}`,
1690
+ { apiUrl: params.apiUrl }
1691
+ );
1692
+ for (const row of page.rows) {
1693
+ if (trackTimestamp) params.dataRange.observe(row.timestamp);
1694
+ file.write(`${JSON.stringify(row)}
1695
+ `);
1696
+ }
1697
+ total += page.count;
1698
+ cursor = page.nextCursor;
1699
+ } while (cursor !== null);
1700
+ await new Promise((resolve, reject) => {
1701
+ file.end(
1702
+ (err) => err ? reject(err) : resolve()
1703
+ );
1704
+ });
1705
+ return total;
1706
+ }
1707
+
1708
+ // src/commands/migration-import.ts
1709
+ import { createInterface as createInterface4 } from "readline";
1710
+ import { createReadStream, existsSync as existsSync2 } from "fs";
1711
+ import { readFile } from "fs/promises";
1712
+ import { join as join3 } from "path";
1713
+ var BATCH_SIZE = 2e3;
1714
+ async function runMigrationImport(args) {
1715
+ const dir = args.find((a) => !a.startsWith("--"));
1716
+ const apiUrl = parseFlagArg(args, "--api-url");
1717
+ const dryRunOnly = args.includes("--dry-run");
1718
+ const confirmed = args.includes("--yes") || args.includes("-y");
1719
+ if (!dir) {
1720
+ console.error(
1721
+ "Usage: emit-vision import <archiveDirectory> [--dry-run] [--yes] [--api-url <url>]"
1722
+ );
1723
+ process.exit(1);
1724
+ }
1725
+ const manifest = await readJson(
1726
+ join3(dir, "manifest.json")
1727
+ );
1728
+ const data = await readJson(join3(dir, "postgres.json"));
1729
+ const planResponse = await apiFetch(
1730
+ "/v1/admin/migration/import",
1731
+ {
1732
+ method: "POST",
1733
+ apiUrl,
1734
+ body: { manifest, data, dataRange: manifest.dataRange, dryRun: true }
1735
+ }
1736
+ );
1737
+ printPlan(planResponse.result, manifest);
1738
+ if (dryRunOnly) return;
1739
+ if (!confirmed) {
1740
+ if (!process.stdin.isTTY) {
1741
+ console.error(
1742
+ "stdin is not a terminal.\nPass --yes to confirm the import non-interactively."
1743
+ );
1744
+ process.exit(1);
1745
+ }
1746
+ const rl = createInterface4({
1747
+ input: process.stdin,
1748
+ output: process.stdout
1749
+ });
1750
+ const answer = await new Promise((resolve) => {
1751
+ rl.question("Proceed with this import? [y/N] ", (a) => {
1752
+ rl.close();
1753
+ resolve(a.trim().toLowerCase());
1754
+ });
1755
+ });
1756
+ if (answer !== "y" && answer !== "yes") {
1757
+ console.log("Aborted.");
1758
+ return;
1759
+ }
1760
+ }
1761
+ const { result } = await apiFetch(
1762
+ "/v1/admin/migration/import",
1763
+ {
1764
+ method: "POST",
1765
+ apiUrl,
1766
+ body: { manifest, data, dataRange: manifest.dataRange }
1767
+ }
1768
+ );
1769
+ console.log(`
1770
+ Created organization ${result.organizationId}.`);
1771
+ const clickhouseCounts = {};
1772
+ for (const table of MIGRATION_CLICKHOUSE_TABLES) {
1773
+ const file = join3(dir, `${table}.ndjson`);
1774
+ if (!existsSync2(file)) {
1775
+ clickhouseCounts[table] = 0;
1776
+ continue;
1777
+ }
1778
+ console.log(`Importing ${table}\u2026`);
1779
+ clickhouseCounts[table] = await importClickHouseTable({
1780
+ file,
1781
+ table,
1782
+ apiUrl,
1783
+ organizationId: result.organizationId,
1784
+ idMap: result.idMap
1785
+ });
1786
+ }
1787
+ printReconciliation(manifest, result, clickhouseCounts);
1788
+ printApiKeys(result);
1789
+ printMembers(result);
1790
+ }
1791
+ async function readJson(path) {
1792
+ try {
1793
+ return JSON.parse(await readFile(path, "utf-8"));
1794
+ } catch (err) {
1795
+ console.error(
1796
+ `Failed to read ${path}: ${err instanceof Error ? err.message : String(err)}
1797
+ Is this a complete archive produced by \`emit-vision export --all\`?`
1798
+ );
1799
+ process.exit(1);
1800
+ }
1801
+ }
1802
+ function printPlan(plan, manifest) {
1803
+ console.log(`
1804
+ Plan for organization "${manifest.sourceOrganizationId}":`);
1805
+ console.log(` Projects to import: ${plan.counts.projects}`);
1806
+ if (plan.projectsOverPlanLimit.length > 0) {
1807
+ console.log(
1808
+ ` \u26A0 Over the free plan's project limit, will NOT be imported: ${plan.projectsOverPlanLimit.join(", ")}`
1809
+ );
1810
+ }
1811
+ if (plan.retentionWarning) {
1812
+ console.log(` \u26A0 ${plan.retentionWarning}`);
1813
+ }
1814
+ console.log(
1815
+ ` Members to invite (existing accounts): ${plan.invitedMembers.length}`
1816
+ );
1817
+ if (plan.unresolvedMembers.length > 0) {
1818
+ console.log(
1819
+ ` Members needing a manual invite (no account yet): ${plan.unresolvedMembers.join(", ")}`
1820
+ );
1821
+ }
1822
+ }
1823
+ async function importClickHouseTable(params) {
1824
+ const rl = createInterface4({
1825
+ input: createReadStream(params.file),
1826
+ crlfDelay: Infinity
1827
+ });
1828
+ let batch = [];
1829
+ let total = 0;
1830
+ const flush = async () => {
1831
+ if (batch.length === 0) return;
1832
+ const { inserted } = await apiFetch(
1833
+ `/v1/admin/migration/import/${encodeURIComponent(params.organizationId)}/clickhouse/${params.table}`,
1834
+ {
1835
+ method: "POST",
1836
+ apiUrl: params.apiUrl,
1837
+ body: { idMap: params.idMap, rows: batch }
1838
+ }
1839
+ );
1840
+ total += inserted;
1841
+ batch = [];
1842
+ };
1843
+ for await (const line of rl) {
1844
+ if (!line.trim()) continue;
1845
+ batch.push(JSON.parse(line));
1846
+ if (batch.length >= BATCH_SIZE) await flush();
1847
+ }
1848
+ await flush();
1849
+ console.log(` ${params.table}: ${total.toLocaleString()} rows imported`);
1850
+ return total;
1851
+ }
1852
+ function printReconciliation(manifest, result, clickhouseCounts) {
1853
+ const actual = {
1854
+ ...result.counts,
1855
+ ...clickhouseCounts
1856
+ };
1857
+ console.log(
1858
+ "\nReconciliation (expected from archive vs. actually imported):"
1859
+ );
1860
+ for (const [table, expected] of Object.entries(manifest.tables)) {
1861
+ if (table === "organization" || table === "users") continue;
1862
+ const got = actual[table];
1863
+ if (got === void 0) continue;
1864
+ const flag = got === expected ? "\u2713" : "\u26A0";
1865
+ console.log(
1866
+ ` ${flag} ${table}: ${got.toLocaleString()} / ${expected.toLocaleString()}`
1867
+ );
1868
+ }
1869
+ }
1870
+ function printApiKeys(result) {
1871
+ if (result.apiKeys.length === 0) return;
1872
+ console.log(
1873
+ "\nNew API keys (source keys can't be recovered \u2014 copy these now, then update your SDKs):"
1874
+ );
1875
+ for (const key of result.apiKeys) {
1876
+ console.log(` ${key.projectName} (${key.type}): ${key.rawKey}`);
1877
+ }
1878
+ }
1879
+ function printMembers(result) {
1880
+ if (result.invitedMembers.length > 0) {
1881
+ console.log(
1882
+ `
1883
+ Invited (pending acceptance): ${result.invitedMembers.join(", ")}`
1884
+ );
1885
+ }
1886
+ if (result.unresolvedMembers.length > 0) {
1887
+ console.log(
1888
+ `Need a manual invite (no hosted account yet): ${result.unresolvedMembers.join(", ")}`
1889
+ );
1890
+ }
1891
+ }
1892
+
1542
1893
  // src/index.ts
1543
1894
  var VERSION = "0.2.5";
1544
1895
  var [cmd, subcmd, ...rest] = process.argv.slice(2);
@@ -1621,6 +1972,10 @@ async function main() {
1621
1972
  printHelp();
1622
1973
  process.exit(1);
1623
1974
  }
1975
+ } else if (cmd === "export") {
1976
+ await runMigrationExport(subcmd ? [subcmd, ...rest] : rest);
1977
+ } else if (cmd === "import") {
1978
+ await runMigrationImport(subcmd ? [subcmd, ...rest] : rest);
1624
1979
  } else if (cmd === "flags") {
1625
1980
  if (subcmd === "list") {
1626
1981
  await runFlagsList(rest);
@@ -1705,6 +2060,10 @@ Commands:
1705
2060
  pulse list --project <projectId> [--json] List pulse checks for a project
1706
2061
  pulse status --project <projectId> [--json] Show check health with colored status indicators
1707
2062
 
2063
+ export --all --out <directory> [--api-url <url>] Export an organization's full data for self-host \u2192 cloud migration
2064
+ import <archiveDirectory> [--dry-run] [--yes] [--api-url <url>]
2065
+ Import an export archive into a fresh organization
2066
+
1708
2067
  flags list <projectId> [--limit <n>] [--offset <n>] [--json] List feature flags for a project
1709
2068
  flags evaluate <projectId> --environment <env> [--user-key <key>] [--flag <key>]... [--json]
1710
2069
  Evaluate flags for a user/environment
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@emit-vision/cli",
3
- "version": "0.2.6",
3
+ "version": "0.2.7",
4
4
  "description": "CLI for Emit Vision — query telemetry, manage projects and ingest keys, and control feature flags from the terminal.",
5
5
  "private": false,
6
6
  "license": "MIT",
@@ -18,7 +18,7 @@
18
18
  "url": "https://emitvision.com/docs/cli"
19
19
  },
20
20
  "bugs": {
21
- "email": "hello@emit-vision.dev"
21
+ "email": "hello@emitvision.com"
22
22
  },
23
23
  "bin": {
24
24
  "emit-vision": "dist/index.js"