mdedit-cli 0.1.3 → 0.2.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/dist/index.js CHANGED
@@ -2,9 +2,9 @@
2
2
 
3
3
  // src/index.ts
4
4
  import { Command as Command7 } from "commander";
5
- import { readFileSync as readFileSync2 } from "fs";
6
- import { dirname, join as join2 } from "path";
7
- import { fileURLToPath } from "url";
5
+ import { readFileSync as readFileSync3 } from "fs";
6
+ import { dirname as dirname2, join as join3 } from "path";
7
+ import { fileURLToPath as fileURLToPath2 } from "url";
8
8
 
9
9
  // ../sdk/dist/index.js
10
10
  var _defaultFetchers = null;
@@ -404,62 +404,7 @@ var deleteFolder = async (workspaceId, folderId, fetchers) => {
404
404
  }
405
405
  return true;
406
406
  };
407
- var listTemplates = async (workspaceId, fetchers) => {
408
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
409
- const response = await fetchV2(`/workspaces/${workspaceId}/templates`, {
410
- method: "GET"
411
- });
412
- if (!response.ok) {
413
- throw new Error(`Failed to fetch templates: ${response.statusText}`);
414
- }
415
- return response.json();
416
- };
417
- var getTemplateById = async (templateId, fetchers) => {
418
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
419
- const response = await fetchV2(`/templates/${templateId}`, { method: "GET" });
420
- if (!response.ok) {
421
- throw new Error(`Failed to fetch template: ${response.statusText}`);
422
- }
423
- return response.json();
424
- };
425
- var getTemplateBySlug = async (slug, fetchers) => {
426
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
427
- const response = await fetchV2(`/templates/slug/${encodeURIComponent(slug)}`, { method: "GET" });
428
- if (!response.ok) {
429
- throw new Error(`Failed to fetch template by slug: ${response.statusText}`);
430
- }
431
- return response.json();
432
- };
433
- var saveArticleAsTemplate = async (workspaceId, articleId, templateData, fetchers) => {
434
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
435
- const response = await fetchV2(
436
- `/workspaces/${workspaceId}/articles/${articleId}/save-as-template`,
437
- { method: "POST", body: JSON.stringify(templateData) }
438
- );
439
- if (!response.ok) {
440
- throw new Error(`Failed to save template: ${response.statusText}`);
441
- }
442
- return response.json();
443
- };
444
- var updateTemplate = async (templateId, updates, fetchers) => {
445
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
446
- const response = await fetchV2(`/templates/${templateId}`, {
447
- method: "PUT",
448
- body: JSON.stringify(updates)
449
- });
450
- if (!response.ok) {
451
- throw new Error(`Failed to update template: ${response.statusText}`);
452
- }
453
- return response.json();
454
- };
455
- var deleteTemplate = async (templateId, fetchers) => {
456
- const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
457
- const response = await fetchV2(`/templates/${templateId}`, { method: "DELETE" });
458
- if (!response.ok) {
459
- throw new Error(`Failed to delete template: ${response.statusText}`);
460
- }
461
- };
462
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
407
+ var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
463
408
  var isRetriableStatus = (status) => status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
464
409
  var withRetries = async (fn, maxAttempts = 3) => {
465
410
  let lastError;
@@ -580,14 +525,6 @@ function createSdkClient(config) {
580
525
  },
581
526
  saveContent: (workspaceId, articleId, content) => withFetchError(() => saveArticleContent(workspaceId, articleId, content, fetchers)),
582
527
  exportZip: (workspaceId, articleId) => withFetchError(() => exportArticleZip(workspaceId, articleId, fetchers))
583
- },
584
- template: {
585
- list: (workspaceId) => withFetchError(() => listTemplates(workspaceId, fetchers)),
586
- get: (templateId) => withFetchError(() => getTemplateById(templateId, fetchers)),
587
- getBySlug: (slug) => withFetchError(() => getTemplateBySlug(slug, fetchers)),
588
- createFromArticle: (workspaceId, articleId, req) => withFetchError(() => saveArticleAsTemplate(workspaceId, articleId, req, fetchers)),
589
- update: (templateId, updates) => withFetchError(() => updateTemplate(templateId, updates, fetchers)),
590
- delete: (templateId) => withFetchError(() => deleteTemplate(templateId, fetchers))
591
528
  }
592
529
  };
593
530
  }
@@ -668,13 +605,30 @@ var ConfigManager = class {
668
605
  var configManager = new ConfigManager();
669
606
 
670
607
  // src/utils/output.ts
608
+ var MAX_TABLE_CELL_WIDTH = 80;
609
+ function normalizeFormat(value) {
610
+ const raw = String(value || "").trim().toLowerCase();
611
+ if (raw === "json" || raw === "table" || raw === "plain") return raw;
612
+ return "table";
613
+ }
614
+ function truncateCell(value, max = MAX_TABLE_CELL_WIDTH) {
615
+ const text = value.replace(/\s+/g, " ").trim();
616
+ if (text.length <= max) return text;
617
+ return text.slice(0, Math.max(0, max - 1)).trimEnd() + "\u2026";
618
+ }
671
619
  var OutputFormatter = class {
672
620
  format;
673
621
  constructor() {
674
- this.format = configManager.get("outputFormat") || "plain";
622
+ this.format = normalizeFormat(configManager.get("outputFormat") || "table");
675
623
  }
676
624
  setFormat(format) {
677
- this.format = format;
625
+ this.format = normalizeFormat(format);
626
+ }
627
+ getFormat() {
628
+ return this.format;
629
+ }
630
+ isJson() {
631
+ return this.format === "json";
678
632
  }
679
633
  log(message) {
680
634
  if (this.format === "json") {
@@ -703,9 +657,15 @@ var OutputFormatter = class {
703
657
  console.log(JSON.stringify(data, null, 2));
704
658
  return;
705
659
  }
706
- if (this.format === "table" && Array.isArray(data)) {
707
- console.table(data);
708
- return;
660
+ if (this.format === "table") {
661
+ if (Array.isArray(data)) {
662
+ this.printTable(data);
663
+ return;
664
+ }
665
+ if (typeof data === "object" && data !== null) {
666
+ this.printObject(data);
667
+ return;
668
+ }
709
669
  }
710
670
  if (this.format === "plain") {
711
671
  if (typeof data === "object" && data !== null) {
@@ -722,6 +682,58 @@ var OutputFormatter = class {
722
682
  ${chalk.bold.underline(text)}
723
683
  `);
724
684
  }
685
+ printTable(rowsRaw) {
686
+ if (rowsRaw.length === 0) {
687
+ console.log("(no results)");
688
+ return;
689
+ }
690
+ const rows = rowsRaw.map((row) => {
691
+ if (row && typeof row === "object" && !Array.isArray(row)) return row;
692
+ return { value: row };
693
+ });
694
+ const columns = [];
695
+ const seen = /* @__PURE__ */ new Set();
696
+ const addColumn = (col) => {
697
+ if (seen.has(col)) return;
698
+ seen.add(col);
699
+ columns.push(col);
700
+ };
701
+ addColumn("(index)");
702
+ for (const key of Object.keys(rows[0] || {})) addColumn(key);
703
+ for (const row of rows) {
704
+ for (const key of Object.keys(row)) addColumn(key);
705
+ }
706
+ const cell = (value) => {
707
+ if (value === null || value === void 0) return "";
708
+ if (typeof value === "string") return truncateCell(value);
709
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
710
+ try {
711
+ return truncateCell(JSON.stringify(value));
712
+ } catch {
713
+ return truncateCell(String(value));
714
+ }
715
+ };
716
+ const grid = rows.map((row, idx) => {
717
+ const record = { ...row };
718
+ return columns.map((col) => {
719
+ if (col === "(index)") return String(idx);
720
+ return cell(record[col]);
721
+ });
722
+ });
723
+ const widths = columns.map((col, i) => {
724
+ const headerWidth = col.length;
725
+ const cellsWidth = Math.max(...grid.map((r) => (r[i] ?? "").length), 0);
726
+ return Math.min(MAX_TABLE_CELL_WIDTH, Math.max(headerWidth, cellsWidth));
727
+ });
728
+ const pad = (text, width) => text.length >= width ? text.slice(0, width) : text + " ".repeat(width - text.length);
729
+ const line = (left, mid, right) => left + widths.map((w) => "\u2500".repeat(w + 2)).join(mid) + right;
730
+ const rowLine = (values) => "\u2502" + values.map((v, i) => ` ${pad(v, widths[i])} `).join("\u2502") + "\u2502";
731
+ console.log(line("\u250C", "\u252C", "\u2510"));
732
+ console.log(rowLine(columns.map((c, i) => pad(c, widths[i]))));
733
+ console.log(line("\u251C", "\u253C", "\u2524"));
734
+ for (const r of grid) console.log(rowLine(r.map((v, i) => pad(v, widths[i]))));
735
+ console.log(line("\u2514", "\u2534", "\u2518"));
736
+ }
725
737
  printObject(obj, indent = 0) {
726
738
  if (Array.isArray(obj)) {
727
739
  obj.forEach((item, index) => {
@@ -818,13 +830,95 @@ function getApiClient() {
818
830
  return client;
819
831
  }
820
832
 
833
+ // src/presenters/common.ts
834
+ function isIsoDateString(value) {
835
+ return /^\d{4}-\d{2}-\d{2}T/.test(value);
836
+ }
837
+ function truncate(value, max = 60) {
838
+ const text = String(value ?? "").trim();
839
+ if (!text) return "";
840
+ if (text.length <= max) return text;
841
+ return text.slice(0, Math.max(0, max - 1)).trimEnd() + "\u2026";
842
+ }
843
+ function formatCount(value) {
844
+ const num = typeof value === "number" ? value : Number(value);
845
+ if (!Number.isFinite(num)) return "";
846
+ return new Intl.NumberFormat(void 0, { maximumFractionDigits: 0 }).format(num);
847
+ }
848
+ function toDate(value) {
849
+ if (value === null || value === void 0) return null;
850
+ if (typeof value === "number" && Number.isFinite(value)) {
851
+ const ms = value > 1e12 ? value : value * 1e3;
852
+ const d = new Date(ms);
853
+ return Number.isNaN(d.getTime()) ? null : d;
854
+ }
855
+ if (typeof value === "string") {
856
+ const trimmed = value.trim();
857
+ if (!trimmed) return null;
858
+ if (/^\d+$/.test(trimmed)) {
859
+ const n = Number(trimmed);
860
+ if (!Number.isFinite(n)) return null;
861
+ const ms = n > 1e12 ? n : n * 1e3;
862
+ const d = new Date(ms);
863
+ return Number.isNaN(d.getTime()) ? null : d;
864
+ }
865
+ if (isIsoDateString(trimmed)) {
866
+ const d = new Date(trimmed);
867
+ return Number.isNaN(d.getTime()) ? null : d;
868
+ }
869
+ }
870
+ return null;
871
+ }
872
+ function formatDateShort(value) {
873
+ const d = toDate(value);
874
+ if (!d) return "";
875
+ return d.toISOString().slice(0, 10);
876
+ }
877
+ function formatDateTime(value) {
878
+ const d = toDate(value);
879
+ if (!d) return "";
880
+ return d.toISOString().replace(".000Z", "Z");
881
+ }
882
+
883
+ // src/presenters/article.ts
884
+ function flagsForArticle(article) {
885
+ const pinned = Boolean(article?.isPinned) ? "P" : "";
886
+ const archived = Boolean(article?.isArchived) ? "A" : "";
887
+ return `${pinned}${archived}`;
888
+ }
889
+ function presentArticleListRow(article) {
890
+ const title = article?.title || article?.preview || "";
891
+ const lastEditedAt = article?.lastEditedAt ?? article?.updatedAt ?? article?.createdAt;
892
+ return {
893
+ articleId: article?.articleId ?? "",
894
+ title: truncate(title, 64),
895
+ wordCount: formatCount(article?.wordCount),
896
+ lastEditedAt: formatDateShort(lastEditedAt),
897
+ flags: flagsForArticle(article)
898
+ };
899
+ }
900
+ function presentArticleDetails(article) {
901
+ const lastEditedAt = article?.lastEditedAt ?? article?.updatedAt ?? article?.createdAt;
902
+ return {
903
+ articleId: article?.articleId ?? "",
904
+ title: article?.title ?? "",
905
+ wordCount: formatCount(article?.wordCount) || void 0,
906
+ folderId: article?.folderId ?? null,
907
+ isArchived: Boolean(article?.isArchived),
908
+ isPinned: Boolean(article?.isPinned),
909
+ lastEditedAt: formatDateTime(lastEditedAt) || void 0,
910
+ createdAt: formatDateTime(article?.createdAt) || void 0,
911
+ updatedAt: formatDateTime(article?.updatedAt) || void 0
912
+ };
913
+ }
914
+
821
915
  // src/commands/article.ts
822
916
  async function readContentFromFile(filePath) {
823
917
  if (filePath === "-") {
824
- return new Promise((resolve, reject) => {
918
+ return new Promise((resolve2, reject) => {
825
919
  const chunks = [];
826
920
  process.stdin.on("data", (d) => chunks.push(Buffer.isBuffer(d) ? d : Buffer.from(d)));
827
- process.stdin.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8")));
921
+ process.stdin.on("end", () => resolve2(Buffer.concat(chunks).toString("utf-8")));
828
922
  process.stdin.on("error", reject);
829
923
  });
830
924
  }
@@ -836,7 +930,7 @@ async function writeBlobToFile(blob, filePath) {
836
930
  }
837
931
  function createArticleCommands() {
838
932
  const article = new Command("article").description("Manage articles").action(() => article.help());
839
- article.command("list").description("List all articles").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-f, --folder <folderId>", "Filter by folder ID").option("-l, --limit <number>", "Limit number of results (client-side)", "50").option("-o, --offset <number>", "Offset for pagination (client-side)", "0").action(async (options) => {
933
+ article.command("list").description("List all articles").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-f, --folder <folderId>", "Filter by folder ID").option("-l, --limit <number>", "Limit number of results (client-side)", "50").option("-o, --offset <number>", "Offset for pagination (client-side)", "0").option("--full", "Show full article objects (all fields)").action(async (options) => {
840
934
  requireApiKey();
841
935
  const client = getApiClient();
842
936
  const workspaceId = requireWorkspaceId(options.workspace);
@@ -844,9 +938,14 @@ function createArticleCommands() {
844
938
  output.header("Articles");
845
939
  const offset = Number(options.offset) || 0;
846
940
  const limit = Number(options.limit) || articles.length;
847
- output.output(articles.slice(offset, offset + limit));
941
+ const slice = articles.slice(offset, offset + limit);
942
+ if (output.isJson() || options.full) {
943
+ output.output(slice);
944
+ return;
945
+ }
946
+ output.output(slice.map(presentArticleListRow));
848
947
  });
849
- article.command("get <articleId>").description("Get article details").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-o, --output <file>", "Save article content (markdown) to this file path; use - for stdout").option("--content-only", "Print only the article markdown content to stdout (useful for piping / AI agents)").action(async (articleId, options) => {
948
+ article.command("get <articleId>").description("Get article details").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-o, --output <file>", "Save article content (markdown) to this file path; use - for stdout").option("--content-only", "Print only the article markdown content to stdout (useful for piping / AI agents)").option("--include-content", "Include the article markdown content in the output object").option("--full", "Show full article object (all fields, including nested metadata)").action(async (articleId, options) => {
850
949
  requireApiKey();
851
950
  const client = getApiClient();
852
951
  const workspaceId = requireWorkspaceId(options.workspace);
@@ -866,7 +965,13 @@ function createArticleCommands() {
866
965
  return;
867
966
  }
868
967
  output.header(`Article: ${articleId}`);
869
- output.output(result);
968
+ const wantsFull = Boolean(options.full) || Boolean(options.includeContent);
969
+ if (output.isJson() || wantsFull) {
970
+ output.output(result);
971
+ return;
972
+ }
973
+ output.output(presentArticleDetails(result));
974
+ output.info("Hint: use `mdedit article get <articleId> --content-only` to print markdown, or `--include-content` to include it in the output.");
870
975
  });
871
976
  article.command("create").description("Create a new article").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-i, --id <articleId>", "Article ID (defaults to a UUID)").option("-t, --title <title>", "Article title").option("-f, --folder <folderId>", "Folder ID").option("-c, --collaborative", "Enable collaborative editing").option("--file <path>", "Read initial article content from a file (use - for stdin)").option("--content <text>", "Set initial article content as an inline string").action(async (options) => {
872
977
  requireApiKey();
@@ -967,21 +1072,52 @@ function createArticleCommands() {
967
1072
  // src/commands/workspace.ts
968
1073
  import { Command as Command2 } from "commander";
969
1074
  import inquirer2 from "inquirer";
1075
+
1076
+ // src/presenters/workspace.ts
1077
+ function presentWorkspaceListRow(workspace) {
1078
+ return {
1079
+ workspaceId: workspace?.workspaceId ?? "",
1080
+ name: truncate(workspace?.name ?? "", 48),
1081
+ type: workspace?.type ?? "",
1082
+ ownerUsername: workspace?.ownerUsername ?? "",
1083
+ updatedAt: formatDateShort(workspace?.updatedAt)
1084
+ };
1085
+ }
1086
+ function presentWorkspaceDetails(workspace) {
1087
+ return {
1088
+ workspaceId: workspace?.workspaceId ?? "",
1089
+ name: workspace?.name ?? "",
1090
+ type: workspace?.type ?? "",
1091
+ ownerUsername: workspace?.ownerUsername ?? "",
1092
+ createdAt: formatDateTime(workspace?.createdAt) || void 0,
1093
+ updatedAt: formatDateTime(workspace?.updatedAt) || void 0
1094
+ };
1095
+ }
1096
+
1097
+ // src/commands/workspace.ts
970
1098
  function createWorkspaceCommands() {
971
1099
  const workspace = new Command2("workspace").description("Manage workspaces").action(() => workspace.help());
972
- workspace.command("list").description("List all workspaces").action(async () => {
1100
+ workspace.command("list").description("List all workspaces").option("--full", "Show full workspace objects (all fields)").action(async (options) => {
973
1101
  requireApiKey();
974
1102
  const client = getApiClient();
975
1103
  const workspaces = await client.workspace.list();
976
1104
  output.header("Workspaces");
977
- output.output(workspaces);
1105
+ if (output.isJson() || options.full) {
1106
+ output.output(workspaces);
1107
+ return;
1108
+ }
1109
+ output.output(workspaces.map(presentWorkspaceListRow));
978
1110
  });
979
- workspace.command("get <workspaceId>").description("Get workspace details").action(async (workspaceId) => {
1111
+ workspace.command("get <workspaceId>").description("Get workspace details").option("--full", "Show full workspace object (all fields)").action(async (workspaceId, options) => {
980
1112
  requireApiKey();
981
1113
  const client = getApiClient();
982
1114
  const result = await client.workspace.get(workspaceId);
983
1115
  output.header(`Workspace: ${workspaceId}`);
984
- output.output(result);
1116
+ if (output.isJson() || options.full) {
1117
+ output.output(result);
1118
+ return;
1119
+ }
1120
+ output.output(presentWorkspaceDetails(result));
985
1121
  });
986
1122
  workspace.command("create").description("Create a new workspace").option("-n, --name <name>", "Workspace name").option("-t, --type <type>", "Workspace type: user|team", "user").action(async (options) => {
987
1123
  requireApiKey();
@@ -1044,23 +1180,56 @@ function createWorkspaceCommands() {
1044
1180
  import { Command as Command3 } from "commander";
1045
1181
  import inquirer3 from "inquirer";
1046
1182
  import { v4 as uuidv42 } from "uuid";
1183
+
1184
+ // src/presenters/folder.ts
1185
+ function presentFolderListRow(folder) {
1186
+ return {
1187
+ id: folder?.id ?? "",
1188
+ name: truncate(folder?.name ?? "", 48),
1189
+ parentId: folder?.parentId ?? null,
1190
+ updatedAt: formatDateShort(folder?.updatedAt),
1191
+ deletedAt: formatDateShort(folder?.deletedAt)
1192
+ };
1193
+ }
1194
+ function presentFolderDetails(folder) {
1195
+ return {
1196
+ id: folder?.id ?? "",
1197
+ name: folder?.name ?? "",
1198
+ parentId: folder?.parentId ?? null,
1199
+ workspaceId: folder?.workspaceId ?? "",
1200
+ createdAt: formatDateTime(folder?.createdAt) || void 0,
1201
+ updatedAt: formatDateTime(folder?.updatedAt) || void 0,
1202
+ deletedAt: formatDateTime(folder?.deletedAt) || void 0,
1203
+ deletedBy: folder?.deletedBy
1204
+ };
1205
+ }
1206
+
1207
+ // src/commands/folder.ts
1047
1208
  function createFolderCommands() {
1048
1209
  const folder = new Command3("folder").description("Manage folders").action(() => folder.help());
1049
- folder.command("list").description("List all folders").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("--include-deleted", "Include deleted/tombstoned folders").action(async (options) => {
1210
+ folder.command("list").description("List all folders").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("--include-deleted", "Include deleted/tombstoned folders").option("--full", "Show full folder objects (all fields)").action(async (options) => {
1050
1211
  requireApiKey();
1051
1212
  const client = getApiClient();
1052
1213
  const workspaceId = requireWorkspaceId(options.workspace);
1053
1214
  const folders = await client.folder.list(workspaceId, { includeDeleted: Boolean(options.includeDeleted) });
1054
1215
  output.header("Folders");
1055
- output.output(folders);
1216
+ if (output.isJson() || options.full) {
1217
+ output.output(folders);
1218
+ return;
1219
+ }
1220
+ output.output(folders.map(presentFolderListRow));
1056
1221
  });
1057
- folder.command("get <folderId>").description("Get folder details").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").action(async (folderId, options) => {
1222
+ folder.command("get <folderId>").description("Get folder details").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("--full", "Show full folder object (all fields)").action(async (folderId, options) => {
1058
1223
  requireApiKey();
1059
1224
  const client = getApiClient();
1060
1225
  const workspaceId = requireWorkspaceId(options.workspace);
1061
1226
  const result = await client.folder.get(workspaceId, folderId);
1062
1227
  output.header(`Folder: ${folderId}`);
1063
- output.output(result);
1228
+ if (output.isJson() || options.full) {
1229
+ output.output(result);
1230
+ return;
1231
+ }
1232
+ output.output(presentFolderDetails(result));
1064
1233
  });
1065
1234
  folder.command("create").description("Create a new folder").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-i, --id <folderId>", "Folder ID (optional)").option("-n, --name <name>", "Folder name").option("-p, --parent <parentId>", "Parent folder ID").action(async (options) => {
1066
1235
  requireApiKey();
@@ -1122,110 +1291,9 @@ function createFolderCommands() {
1122
1291
  return folder;
1123
1292
  }
1124
1293
 
1125
- // src/commands/template.ts
1294
+ // src/commands/config.ts
1126
1295
  import { Command as Command4 } from "commander";
1127
1296
  import inquirer4 from "inquirer";
1128
- function slugify(input) {
1129
- return input.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
1130
- }
1131
- function createTemplateCommands() {
1132
- const template = new Command4("template").description("Manage templates").action(() => template.help());
1133
- template.command("list").description("List all templates").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").action(async (options) => {
1134
- requireApiKey();
1135
- const client = getApiClient();
1136
- const workspaceId = requireWorkspaceId(options.workspace);
1137
- const templates = await client.template.list(workspaceId);
1138
- output.header("Templates");
1139
- output.output(templates);
1140
- });
1141
- template.command("get <templateId>").description("Get template details").action(async (templateId) => {
1142
- requireApiKey();
1143
- const client = getApiClient();
1144
- const result = await client.template.get(templateId);
1145
- output.header(`Template: ${templateId}`);
1146
- output.output(result);
1147
- });
1148
- template.command("get-by-slug <slug>").description("Get template details by slug").action(async (slug) => {
1149
- requireApiKey();
1150
- const client = getApiClient();
1151
- const result = await client.template.getBySlug(slug);
1152
- output.header(`Template: ${slug}`);
1153
- output.output(result);
1154
- });
1155
- template.command("create <articleId>").description("Create a template from an article").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-n, --name <name>", "Template name").option("--slug <slug>", "Template slug (defaults to slugified name)").option("-d, --description <desc>", "Template description").option("-c, --category <category>", "Category: writing|documentation|planning|general|custom", "custom").option("-t, --tags <tags>", "Comma-separated tags", "").option("-v, --visibility <visibility>", "Visibility: private|workspace", "workspace").action(async (articleId, options) => {
1156
- requireApiKey();
1157
- const client = getApiClient();
1158
- const workspaceId = requireWorkspaceId(options.workspace);
1159
- let name = options.name;
1160
- if (!name) {
1161
- const answers = await inquirer4.prompt([
1162
- {
1163
- type: "input",
1164
- name: "name",
1165
- message: "Template name:",
1166
- validate: (input) => input.length > 0 || "Name is required"
1167
- }
1168
- ]);
1169
- name = String(answers.name);
1170
- }
1171
- const desc = options.description || "";
1172
- const slug = options.slug || slugify(String(name));
1173
- const tags = String(options.tags || "").split(",").map((t) => t.trim()).filter(Boolean);
1174
- const result = await client.template.createFromArticle(workspaceId, articleId, {
1175
- name: String(name),
1176
- slug,
1177
- category: options.category,
1178
- description: desc,
1179
- tags,
1180
- visibility: options.visibility
1181
- });
1182
- output.success("Template created successfully");
1183
- output.output(result);
1184
- });
1185
- template.command("update <templateId>").description("Update a template").option("-n, --name <name>", "Template name").option("-d, --description <desc>", "Template description").option("-c, --category <category>", "Category: writing|documentation|planning|general|custom").option("-t, --tags <tags>", "Comma-separated tags").action(async (templateId, options) => {
1186
- requireApiKey();
1187
- const client = getApiClient();
1188
- const body = {};
1189
- if (options.name) body.name = options.name;
1190
- if (options.description) body.description = options.description;
1191
- if (options.category) body.category = options.category;
1192
- if (typeof options.tags === "string") {
1193
- body.tags = options.tags.split(",").map((t) => t.trim()).filter(Boolean);
1194
- }
1195
- if (Object.keys(body).length === 0) {
1196
- output.warning("No changes provided. Use --name, --description, --category, or --tags.");
1197
- return;
1198
- }
1199
- const result = await client.template.update(templateId, body);
1200
- output.success("Template updated successfully");
1201
- output.output(result);
1202
- });
1203
- template.command("delete <templateId>").description("Delete a template").option("-y, --yes", "Skip confirmation").action(async (templateId, options) => {
1204
- requireApiKey();
1205
- const client = getApiClient();
1206
- if (!options.yes) {
1207
- const { confirm } = await inquirer4.prompt([
1208
- {
1209
- type: "confirm",
1210
- name: "confirm",
1211
- message: `Are you sure you want to delete template ${templateId}?`,
1212
- default: false
1213
- }
1214
- ]);
1215
- if (!confirm) {
1216
- output.info("Delete cancelled");
1217
- return;
1218
- }
1219
- }
1220
- await client.template.delete(templateId);
1221
- output.success("Template deleted successfully");
1222
- });
1223
- return template;
1224
- }
1225
-
1226
- // src/commands/config.ts
1227
- import { Command as Command5 } from "commander";
1228
- import inquirer5 from "inquirer";
1229
1297
  function redactSecret(value) {
1230
1298
  if (!value) return value;
1231
1299
  if (value.length <= 8) return "********";
@@ -1239,7 +1307,7 @@ var ALLOWED_KEYS = [
1239
1307
  "outputFormat"
1240
1308
  ];
1241
1309
  function createConfigCommands() {
1242
- const config = new Command5("config").description("Manage CLI configuration").action(() => config.help());
1310
+ const config = new Command4("config").description("Manage CLI configuration").action(() => config.help());
1243
1311
  config.command("show").description("Show current configuration (effective values including environment variable overrides)").action(() => {
1244
1312
  const effectiveConfig = {};
1245
1313
  for (const key of ALLOWED_KEYS) {
@@ -1272,7 +1340,7 @@ function createConfigCommands() {
1272
1340
  let apiKey = options.apiKey || process.env.MDEDIT_API_KEY;
1273
1341
  if (!apiKey) {
1274
1342
  output.info("Get an API key: https://docs.mdedit.ai/api-keys");
1275
- const answers = await inquirer5.prompt([
1343
+ const answers = await inquirer4.prompt([
1276
1344
  {
1277
1345
  type: "password",
1278
1346
  name: "apiKey",
@@ -1313,7 +1381,7 @@ function createConfigCommands() {
1313
1381
  });
1314
1382
  config.command("clear").description("Clear all configuration").option("-y, --yes", "Skip confirmation").action(async (options) => {
1315
1383
  if (!options.yes) {
1316
- const { confirm } = await inquirer5.prompt([
1384
+ const { confirm } = await inquirer4.prompt([
1317
1385
  {
1318
1386
  type: "confirm",
1319
1387
  name: "confirm",
@@ -1333,16 +1401,31 @@ function createConfigCommands() {
1333
1401
  }
1334
1402
 
1335
1403
  // src/commands/apikey.ts
1336
- import { Command as Command6 } from "commander";
1337
- import inquirer6 from "inquirer";
1404
+ import { Command as Command5 } from "commander";
1405
+ import inquirer5 from "inquirer";
1406
+
1407
+ // src/presenters/apikey.ts
1408
+ function presentApiKeyListRow(key) {
1409
+ return {
1410
+ keyId: key?.keyId ?? "",
1411
+ name: key?.name ?? "",
1412
+ keyPrefix: key?.keyPrefix ?? "",
1413
+ status: key?.status ?? "",
1414
+ lastUsedAt: formatDateShort(key?.lastUsedAt),
1415
+ expiresAt: formatDateShort(key?.expiresAt),
1416
+ usageCount: formatCount(key?.usageCount)
1417
+ };
1418
+ }
1419
+
1420
+ // src/commands/apikey.ts
1338
1421
  function createApiKeyCommands() {
1339
- const apiKey = new Command6("api-key").description("Manage API keys for authentication").aliases(["apikey"]).action(() => apiKey.help());
1422
+ const apiKey = new Command5("api-key").description("Manage API keys for authentication").aliases(["apikey"]).action(() => apiKey.help());
1340
1423
  apiKey.command("create").description("Create a new API key").option("-n, --name <name>", 'Key name (e.g., "Local Dev", "CI/CD")').option("-d, --description <desc>", "Key description").option("--expires <days>", "Expiration in days (optional)").action(async (options) => {
1341
1424
  requireApiKey();
1342
1425
  const client = getApiClient();
1343
1426
  let name = options.name;
1344
1427
  if (!name) {
1345
- const answers = await inquirer6.prompt([
1428
+ const answers = await inquirer5.prompt([
1346
1429
  {
1347
1430
  type: "input",
1348
1431
  name: "name",
@@ -1367,35 +1450,41 @@ function createApiKeyCommands() {
1367
1450
  if (expiresInDays !== void 0) req.expiresInDays = expiresInDays;
1368
1451
  const result = await client.apiKeys.create(req);
1369
1452
  output.success("API key created successfully!");
1370
- output.warning("\n\u26A0\uFE0F IMPORTANT: Save this API key now. It will not be shown again!\n");
1371
- console.log("API Key ID:", result.keyId);
1372
- console.log("API Key: ", result.key);
1373
- console.log("Name: ", result.name);
1374
- console.log("Created: ", result.createdAt);
1375
- if (result.expiresAt) {
1376
- console.log("Expires: ", result.expiresAt);
1377
- }
1453
+ output.warning("IMPORTANT: Save this API key now. It will not be shown again.");
1454
+ output.output({
1455
+ keyId: result.keyId,
1456
+ keyPrefix: result.keyPrefix,
1457
+ name: result.name,
1458
+ createdAt: result.createdAt,
1459
+ expiresAt: result.expiresAt,
1460
+ key: result.key
1461
+ });
1378
1462
  output.info("\nTo use this key with the CLI:");
1379
1463
  output.info(` mdedit config set apiKey ${result.key}`);
1380
1464
  output.info("\nOr set environment variable:");
1381
1465
  output.info(` export MDEDIT_API_KEY="${result.key}"`);
1382
1466
  });
1383
- apiKey.command("list").description("List your API keys").action(async () => {
1467
+ apiKey.command("list").description("List your API keys").option("--full", "Show full API key objects (all fields)").action(async (options) => {
1384
1468
  requireApiKey();
1385
1469
  const client = getApiClient();
1386
1470
  const result = await client.apiKeys.list();
1471
+ output.header("Your API Keys");
1472
+ if (output.isJson() || options.full) {
1473
+ output.output(result.keys);
1474
+ return;
1475
+ }
1387
1476
  if (result.keys.length === 0) {
1477
+ output.output([]);
1388
1478
  output.info("No API keys found. Create one with: mdedit apikey create");
1389
1479
  return;
1390
1480
  }
1391
- output.header("Your API Keys");
1392
- output.output(result.keys);
1481
+ output.output(result.keys.map(presentApiKeyListRow));
1393
1482
  });
1394
1483
  apiKey.command("revoke <keyId>").description("Revoke an API key").option("-y, --yes", "Skip confirmation").action(async (keyId, options) => {
1395
1484
  requireApiKey();
1396
1485
  const client = getApiClient();
1397
1486
  if (!options.yes) {
1398
- const { confirm } = await inquirer6.prompt([
1487
+ const { confirm } = await inquirer5.prompt([
1399
1488
  {
1400
1489
  type: "confirm",
1401
1490
  name: "confirm",
@@ -1415,17 +1504,112 @@ function createApiKeyCommands() {
1415
1504
  return apiKey;
1416
1505
  }
1417
1506
 
1418
- // src/index.ts
1507
+ // src/commands/skill.ts
1508
+ import { Command as Command6 } from "commander";
1509
+ import { readFileSync as readFileSync2, mkdirSync as mkdirSync2, existsSync as existsSync2, appendFileSync, writeFileSync as writeFileSync2 } from "fs";
1510
+ import { dirname, join as join2, resolve } from "path";
1511
+ import { homedir as homedir2 } from "os";
1512
+ import { fileURLToPath } from "url";
1419
1513
  var __filename = fileURLToPath(import.meta.url);
1420
1514
  var __dirname = dirname(__filename);
1515
+ function getSkillContent() {
1516
+ const candidates = [join2(__dirname, "../skill.md"), join2(__dirname, "../../skill.md")];
1517
+ for (const candidate of candidates) {
1518
+ if (existsSync2(candidate)) return readFileSync2(candidate, "utf-8");
1519
+ }
1520
+ throw new Error(`skill.md not found (searched: ${candidates.join(", ")})`);
1521
+ }
1522
+ var NAMED_TARGETS = ["claude", "cursor", "codex"];
1523
+ var TARGETS = {
1524
+ claude: {
1525
+ label: "Claude Code",
1526
+ path: (_cwd, global) => global ? join2(homedir2(), ".claude", "CLAUDE.md") : join2(process.cwd(), "CLAUDE.md"),
1527
+ mode: "append-section",
1528
+ sectionHeading: "## mdedit CLI"
1529
+ },
1530
+ cursor: {
1531
+ label: "Cursor",
1532
+ path: (_cwd, global) => global ? join2(homedir2(), ".cursor", "rules", "mdedit.mdc") : join2(process.cwd(), ".cursor", "rules", "mdedit.mdc"),
1533
+ mode: "write"
1534
+ },
1535
+ codex: {
1536
+ label: "GitHub Copilot / Codex",
1537
+ path: (cwd, _global) => join2(cwd, ".github", "copilot-instructions.md"),
1538
+ mode: "append-section",
1539
+ sectionHeading: "## mdedit CLI"
1540
+ }
1541
+ };
1542
+ function installToTarget(targetKey, spec, skillContent, global) {
1543
+ const targetPath = spec.path(process.cwd(), global);
1544
+ const dir = dirname(resolve(targetPath));
1545
+ if (!existsSync2(dir)) {
1546
+ mkdirSync2(dir, { recursive: true });
1547
+ }
1548
+ if (spec.mode === "write") {
1549
+ writeFileSync2(targetPath, skillContent, "utf-8");
1550
+ output.success(`${spec.label}: skill written to ${targetPath}`);
1551
+ return;
1552
+ }
1553
+ const heading = spec.sectionHeading ?? "## mdedit CLI";
1554
+ if (existsSync2(targetPath)) {
1555
+ const existing = readFileSync2(targetPath, "utf-8");
1556
+ if (existing.includes(heading)) {
1557
+ output.info(`${spec.label}: skill section already present in ${targetPath} (skipped)`);
1558
+ return;
1559
+ }
1560
+ const trimmed = existing.trimEnd();
1561
+ appendFileSync(targetPath, `${trimmed}
1562
+
1563
+ ${heading}
1564
+
1565
+ ${skillContent}`, "utf-8");
1566
+ } else {
1567
+ writeFileSync2(targetPath, `${heading}
1568
+
1569
+ ${skillContent}`, "utf-8");
1570
+ }
1571
+ output.success(`${spec.label}: skill appended to ${targetPath}`);
1572
+ }
1573
+ function createSkillCommands() {
1574
+ const skill = new Command6("skill").description("Manage and install the mdedit agent skill").action(() => skill.help());
1575
+ skill.command("show").description("Print the mdedit agent skill to stdout").action(() => {
1576
+ process.stdout.write(getSkillContent());
1577
+ });
1578
+ skill.command("install").description(
1579
+ "Install the mdedit skill into AI agent configuration files (Claude Code, Cursor, GitHub Copilot/Codex)"
1580
+ ).option(
1581
+ "-t, --target <target>",
1582
+ "Which agent tool to install for: claude | cursor | codex | all (default: all)",
1583
+ "all"
1584
+ ).option("--global", "Install to home-directory targets instead of current project directory").action((options) => {
1585
+ const target = String(options.target).toLowerCase();
1586
+ const global = Boolean(options.global);
1587
+ const skillContent = getSkillContent();
1588
+ const validTargets = [...NAMED_TARGETS, "all"];
1589
+ if (!validTargets.includes(target)) {
1590
+ throw new Error(`Unknown target "${target}". Valid targets: ${validTargets.join(", ")}`);
1591
+ }
1592
+ const keys = target === "all" ? [...NAMED_TARGETS] : [target];
1593
+ for (const key of keys) {
1594
+ installToTarget(key, TARGETS[key], skillContent, global);
1595
+ }
1596
+ output.info("");
1597
+ output.info("To view the installed skill at any time: mdedit skill show");
1598
+ });
1599
+ return skill;
1600
+ }
1601
+
1602
+ // src/index.ts
1603
+ var __filename2 = fileURLToPath2(import.meta.url);
1604
+ var __dirname2 = dirname2(__filename2);
1421
1605
  var version = "0.0.0";
1422
1606
  try {
1423
- const packageJson = JSON.parse(readFileSync2(join2(__dirname, "../package.json"), "utf-8"));
1607
+ const packageJson = JSON.parse(readFileSync3(join3(__dirname2, "../package.json"), "utf-8"));
1424
1608
  version = packageJson.version || version;
1425
1609
  } catch {
1426
1610
  }
1427
1611
  var program = new Command7();
1428
- program.name("mdedit").description("MDEdit.ai CLI - Command-line interface for the markdown editor platform").version(version).option("-F, --format <format>", "Output format: json, table, or plain", "plain").option("--local", "Use local API at http://localhost:8080").option("--api-url <url>", "Override API URL for this invocation").option("--api-key <key>", "Override API key for this invocation (use env/config in preference)").option("--workspace <workspaceId>", "Override default workspaceId for this invocation").option("--debug", "Show debug output (stacks, request info)").hook("preAction", (thisCommand) => {
1612
+ program.name("mdedit").description("MDEdit.ai CLI - Command-line interface for the markdown editor platform").version(version).option("-F, --format <format>", "Output format: json, table, or plain (default: table)").option("--local", "Use local API at http://localhost:8080").option("--api-url <url>", "Override API URL for this invocation").option("--api-key <key>", "Override API key for this invocation (use env/config in preference)").option("--workspace <workspaceId>", "Override default workspaceId for this invocation").option("--debug", "Show debug output (stacks, request info)").hook("preAction", (thisCommand) => {
1429
1613
  const opts = typeof thisCommand.optsWithGlobals === "function" ? (
1430
1614
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1431
1615
  thisCommand.optsWithGlobals()
@@ -1440,9 +1624,9 @@ program.name("mdedit").description("MDEdit.ai CLI - Command-line interface for t
1440
1624
  program.addCommand(createArticleCommands());
1441
1625
  program.addCommand(createWorkspaceCommands());
1442
1626
  program.addCommand(createFolderCommands());
1443
- program.addCommand(createTemplateCommands());
1444
1627
  program.addCommand(createConfigCommands());
1445
1628
  program.addCommand(createApiKeyCommands());
1629
+ program.addCommand(createSkillCommands());
1446
1630
  program.command("health").description("Check API health status").action(async () => {
1447
1631
  const base = getApiBaseUrlRoot();
1448
1632
  const response = await fetch(`${base}/health`, { method: "GET" });
@@ -1451,32 +1635,59 @@ program.command("health").description("Check API health status").action(async ()
1451
1635
  }
1452
1636
  const result = await response.json().catch(() => ({}));
1453
1637
  output.success("API is healthy");
1454
- output.output(result);
1638
+ if (output.isJson()) {
1639
+ output.output(result);
1640
+ return;
1641
+ }
1642
+ if (result && typeof result === "object" && "status" in result) {
1643
+ output.info(`Status: ${result.status}`);
1644
+ }
1455
1645
  });
1456
1646
  program.command("info").description("Display CLI and API information").action(async () => {
1457
- output.header("MDEdit.ai CLI Information");
1458
- output.info(`CLI Version: ${version}`);
1459
1647
  const apiUrl = configManager.get("apiUrl") || process.env.MDEDIT_API_URL || "https://apiv2.mdedit.ai";
1460
- output.info(`API URL: ${apiUrl}`);
1461
1648
  const apiKey = configManager.get("apiKey");
1462
- output.info(`Auth Method: ${apiKey ? "API Key" : "None"}`);
1649
+ const workspaceId = configManager.get("workspaceId") || process.env.MDEDIT_WORKSPACE_ID || null;
1650
+ const authMethod = apiKey ? "apiKey" : "none";
1651
+ let health = void 0;
1652
+ let apiStatus = "unavailable";
1463
1653
  try {
1464
1654
  const base = getApiBaseUrlRoot();
1465
- const health = await fetch(`${base}/health`, { method: "GET" }).then((r) => r.json());
1466
- output.success("API Status: Healthy");
1467
- output.output(health);
1655
+ health = await fetch(`${base}/health`, { method: "GET" }).then((r) => r.json());
1656
+ apiStatus = "healthy";
1468
1657
  } catch {
1469
- output.warning("API Status: Unavailable");
1658
+ apiStatus = "unavailable";
1470
1659
  }
1471
- try {
1472
- if (apiKey) {
1660
+ let authOk = null;
1661
+ if (apiKey) {
1662
+ try {
1473
1663
  const client = getApiClient();
1474
1664
  await client.workspace.list();
1475
- output.success("Auth: OK");
1665
+ authOk = true;
1666
+ } catch {
1667
+ authOk = false;
1476
1668
  }
1477
- } catch {
1478
- output.warning("Auth: Failed");
1479
1669
  }
1670
+ if (output.isJson()) {
1671
+ output.output({
1672
+ cliVersion: version,
1673
+ apiUrl,
1674
+ workspaceId,
1675
+ authMethod,
1676
+ apiStatus,
1677
+ health,
1678
+ authOk
1679
+ });
1680
+ return;
1681
+ }
1682
+ output.header("MDEdit.ai CLI");
1683
+ output.info(`CLI Version: ${version}`);
1684
+ output.info(`API URL: ${apiUrl}`);
1685
+ if (workspaceId) output.info(`Workspace: ${workspaceId}`);
1686
+ output.info(`Auth Method: ${authMethod === "apiKey" ? "API Key" : "None"}`);
1687
+ if (apiStatus === "healthy") output.success("API Status: Healthy");
1688
+ else output.warning("API Status: Unavailable");
1689
+ if (authOk === true) output.success("Auth: OK");
1690
+ if (authOk === false) output.warning("Auth: Failed");
1480
1691
  });
1481
1692
  program.action(() => {
1482
1693
  program.outputHelp();