mdedit-cli 0.2.1 → 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.
package/README.md CHANGED
@@ -55,6 +55,32 @@ quote, heading, section, or range anchors. The command exits `2` when an anchor
55
55
  `3` when an anchor is ambiguous, and `4` when an edit conflict is reported. In JSON mode,
56
56
  the result or typed error is the only value written to stdout.
57
57
 
58
+ ## Public links
59
+
60
+ Use a key with `publishing:write` to publish or update a public snapshot. Publishing is
61
+ explicit: later edits stay private until the command is run again.
62
+
63
+ ```bash
64
+ mdedit article publish <articleId> --yes
65
+ mdedit article publish <articleId> --slug my-document --yes
66
+ mdedit article publish-status <articleId> --format json
67
+ mdedit article unpublish <articleId> --yes
68
+ ```
69
+
70
+ Create a document from Markdown and publish it in one command:
71
+
72
+ ```bash
73
+ mdedit article create \
74
+ --file document.md \
75
+ --publish \
76
+ --yes
77
+ ```
78
+
79
+ Without `--title`, the CLI uses the first Markdown H1 or the filename.
80
+ The JSON result includes `publication.shortUrl`, such as
81
+ `https://mded.it/my-document`. If article creation succeeds but publishing fails, the
82
+ article is kept private and the command reports its article ID.
83
+
58
84
  ## Review commands
59
85
 
60
86
  Review agents can comment and suggest with `articles:read,reviews:write`; accepting a
package/dist/index.js CHANGED
@@ -349,6 +349,18 @@ var normalizeTimestampMs = (value) => {
349
349
  if (!Number.isFinite(n)) return Date.now();
350
350
  return n < 1e12 ? n * 1e3 : n;
351
351
  };
352
+ var readFolderErrorMessage = async (response, fallback) => {
353
+ const errorText = await response.text();
354
+ try {
355
+ const body = JSON.parse(errorText);
356
+ const message = body?.error?.message ?? body?.message;
357
+ if (typeof message === "string" && message.trim()) {
358
+ return message;
359
+ }
360
+ } catch {
361
+ }
362
+ return errorText.trim() || fallback;
363
+ };
352
364
  var normalizeFolder = (raw) => {
353
365
  const id = raw?.id ?? raw?.folderId;
354
366
  const parentId = raw?.parentId ?? raw?.parentFolderId ?? null;
@@ -389,8 +401,10 @@ var createFolder = async (workspaceId, folderRequest, fetchers) => {
389
401
  })
390
402
  });
391
403
  if (!response.ok) {
392
- const errorText = await response.text();
393
- throw new errors_default(`Error creating folder. ${errorText}`, response.status);
404
+ throw new errors_default(
405
+ await readFolderErrorMessage(response, "Error creating folder"),
406
+ response.status
407
+ );
394
408
  }
395
409
  return normalizeFolder(await response.json());
396
410
  };
@@ -404,8 +418,10 @@ var updateFolder = async (workspaceId, folderId, folderRequest, fetchers) => {
404
418
  })
405
419
  });
406
420
  if (!response.ok) {
407
- const errorText = await response.text();
408
- throw new errors_default(`Error updating folder. ${errorText}`, response.status);
421
+ throw new errors_default(
422
+ await readFolderErrorMessage(response, "Error updating folder"),
423
+ response.status
424
+ );
409
425
  }
410
426
  const result = await response.json();
411
427
  try {
@@ -513,6 +529,82 @@ var revokeApiKey = async (keyId, fetchers) => {
513
529
  }
514
530
  return response.json();
515
531
  };
532
+ var checkpointCollaboration = async (workspaceId, articleId, fetchers) => {
533
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
534
+ const response = await fetchV2(
535
+ `/workspaces/${workspaceId}/articles/${articleId}/collaboration/checkpoint`,
536
+ { method: "POST" }
537
+ );
538
+ if (!response.ok) {
539
+ throw new errors_default(
540
+ `Error checkpointing collaboration. ${await response.text()}`,
541
+ response.status
542
+ );
543
+ }
544
+ return response.json();
545
+ };
546
+ var publishArticle = async (workspaceId, articleId, body, fetchers) => {
547
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
548
+ const response = await fetchV2(
549
+ `/workspaces/${workspaceId}/articles/${articleId}/publish`,
550
+ {
551
+ method: "POST",
552
+ body: JSON.stringify(body)
553
+ }
554
+ );
555
+ if (!response.ok) {
556
+ throw new errors_default(
557
+ `Error publishing article: ${await response.text()}`,
558
+ response.status
559
+ );
560
+ }
561
+ return response.json();
562
+ };
563
+ var unpublishArticle = async (workspaceId, articleId, fetchers) => {
564
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
565
+ const response = await fetchV2(
566
+ `/workspaces/${workspaceId}/articles/${articleId}/publish`,
567
+ { method: "DELETE" }
568
+ );
569
+ if (!response.ok) {
570
+ throw new errors_default(
571
+ `Error unpublishing article: ${await response.text()}`,
572
+ response.status
573
+ );
574
+ }
575
+ return response.json();
576
+ };
577
+ var getPublishStatus = async (workspaceId, articleId, fetchers) => {
578
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
579
+ const response = await fetchV2(
580
+ `/workspaces/${workspaceId}/articles/${articleId}/publish`,
581
+ { method: "GET" }
582
+ );
583
+ if (!response.ok) {
584
+ throw new errors_default(
585
+ `Error fetching publish status: ${await response.text()}`,
586
+ response.status
587
+ );
588
+ }
589
+ return response.json();
590
+ };
591
+ var updatePublishedArticle = async (workspaceId, articleId, body, fetchers) => {
592
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
593
+ const response = await fetchV2(
594
+ `/workspaces/${workspaceId}/articles/${articleId}/publish`,
595
+ {
596
+ method: "PUT",
597
+ body: JSON.stringify(body)
598
+ }
599
+ );
600
+ if (!response.ok) {
601
+ throw new errors_default(
602
+ `Error updating published article: ${await response.text()}`,
603
+ response.status
604
+ );
605
+ }
606
+ return response.json();
607
+ };
516
608
  var FetchError2 = class extends Error {
517
609
  status;
518
610
  data;
@@ -573,6 +665,15 @@ function createSdkClient(config) {
573
665
  },
574
666
  saveContent: (workspaceId, articleId, content, options) => withFetchError(() => saveArticleContent(workspaceId, articleId, content, options, fetchers)),
575
667
  exportZip: (workspaceId, articleId) => withFetchError(() => exportArticleZip(workspaceId, articleId, fetchers))
668
+ },
669
+ collaboration: {
670
+ checkpoint: (workspaceId, articleId) => withFetchError(() => checkpointCollaboration(workspaceId, articleId, fetchers))
671
+ },
672
+ publish: {
673
+ publish: (workspaceId, articleId, request = {}) => withFetchError(() => publishArticle(workspaceId, articleId, request, fetchers)),
674
+ status: (workspaceId, articleId) => withFetchError(() => getPublishStatus(workspaceId, articleId, fetchers)),
675
+ update: (workspaceId, articleId, request = {}) => withFetchError(() => updatePublishedArticle(workspaceId, articleId, request, fetchers)),
676
+ unpublish: (workspaceId, articleId) => withFetchError(() => unpublishArticle(workspaceId, articleId, fetchers))
576
677
  }
577
678
  };
578
679
  }
@@ -586,6 +687,7 @@ import inquirer from "inquirer";
586
687
  import { v4 as uuidv4 } from "uuid";
587
688
  import { readFile, writeFile } from "fs/promises";
588
689
  import { createHash } from "crypto";
690
+ import { basename, extname } from "path";
589
691
  import {
590
692
  openArticleSession
591
693
  } from "@mdedit/agent-client";
@@ -897,7 +999,36 @@ var CLI_EXIT_CODES = {
897
999
  AMBIGUOUS_ANCHOR: 3,
898
1000
  EDIT_CONFLICT: 4
899
1001
  };
1002
+ var ArticleCreateContentError = class extends Error {
1003
+ articleId;
1004
+ compensated;
1005
+ contentError;
1006
+ compensationError;
1007
+ constructor(args) {
1008
+ const contentError = args.contentError instanceof Error ? args.contentError.message : String(args.contentError);
1009
+ const compensationError = args.compensationError instanceof Error ? args.compensationError.message : args.compensationError === void 0 ? void 0 : String(args.compensationError);
1010
+ super(args.compensated ? `Initial article content could not be saved; the created article ${args.articleId} was rolled back.` : `Initial article content could not be saved and article ${args.articleId} could not be rolled back.`);
1011
+ this.name = "ArticleCreateContentError";
1012
+ this.articleId = args.articleId;
1013
+ this.compensated = args.compensated;
1014
+ this.contentError = contentError;
1015
+ this.compensationError = compensationError;
1016
+ }
1017
+ };
900
1018
  function typedCliError(error) {
1019
+ if (error instanceof ArticleCreateContentError) {
1020
+ return {
1021
+ exitCode: CLI_EXIT_CODES.ERROR,
1022
+ code: "ARTICLE_CREATE_CONTENT_FAILED",
1023
+ message: error.message,
1024
+ details: {
1025
+ articleId: error.articleId,
1026
+ compensated: error.compensated,
1027
+ contentError: error.contentError,
1028
+ ...error.compensationError ? { compensationError: error.compensationError } : {}
1029
+ }
1030
+ };
1031
+ }
901
1032
  if (error instanceof AnchorNotFoundError) {
902
1033
  return {
903
1034
  exitCode: CLI_EXIT_CODES.ANCHOR_NOT_FOUND,
@@ -1027,6 +1158,36 @@ async function writeBlobToFile(blob, filePath) {
1027
1158
  function sha256Hex(content) {
1028
1159
  return createHash("sha256").update(content).digest("hex");
1029
1160
  }
1161
+ function inferFileTitle(filePath, content) {
1162
+ const firstHeading = content?.match(/^\s*#\s+(.+?)\s*$/m)?.[1]?.trim();
1163
+ if (firstHeading) return firstHeading;
1164
+ if (filePath === "-") return void 0;
1165
+ const fileName = basename(filePath);
1166
+ const extension = extname(fileName);
1167
+ const stem = (extension ? fileName.slice(0, -extension.length) : fileName).trim();
1168
+ return stem || void 0;
1169
+ }
1170
+ function publishRequest(options) {
1171
+ const seoMetadata = {
1172
+ ...options.seoTitle ? { title: options.seoTitle } : {},
1173
+ ...options.seoDescription ? { description: options.seoDescription } : {}
1174
+ };
1175
+ return {
1176
+ ...options.slug ? { customSlug: options.slug } : {},
1177
+ ...Object.keys(seoMetadata).length > 0 ? { seoMetadata } : {}
1178
+ };
1179
+ }
1180
+ async function confirmPublicPublish(articleId) {
1181
+ const { confirm } = await inquirer.prompt([
1182
+ {
1183
+ type: "confirm",
1184
+ name: "confirm",
1185
+ message: `Publish article ${articleId} publicly? Anyone with the link will be able to view it.`,
1186
+ default: false
1187
+ }
1188
+ ]);
1189
+ return Boolean(confirm);
1190
+ }
1030
1191
  async function readEditOperations(filePath) {
1031
1192
  const raw = await readFile(filePath, "utf-8");
1032
1193
  const parsed = JSON.parse(raw);
@@ -1095,14 +1256,23 @@ function createArticleCommands() {
1095
1256
  output.output(presentArticleDetails(result));
1096
1257
  output.info("Hint: use `mdedit article get <articleId> --content-only` to print markdown, or `--include-content` to include it in the output.");
1097
1258
  });
1098
- 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) => {
1099
- requireApiKey();
1259
+ 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").option("--publish", "Publish the created article to a public mded.it link").option("--slug <slug>", "Custom public-link slug (requires --publish)").option("--seo-title <title>", "SEO/social title for the public page (requires --publish)").option("--seo-description <description>", "SEO/social description for the public page (requires --publish)").option("-y, --yes", "Skip public-publishing confirmation").action(async (options) => {
1260
+ const apiKey = requireApiKey();
1100
1261
  const client = getApiClient();
1101
1262
  const workspaceId = requireWorkspaceId(options.workspace);
1102
1263
  if (options.content !== void 0 && options.file !== void 0) {
1103
1264
  throw new Error("--content and --file are mutually exclusive. Provide only one.");
1104
1265
  }
1266
+ if (!options.publish && (options.slug || options.seoTitle || options.seoDescription)) {
1267
+ throw new Error("--slug, --seo-title, and --seo-description require --publish.");
1268
+ }
1269
+ let contentText = null;
1270
+ if (options.content !== void 0) contentText = options.content;
1271
+ else if (options.file) contentText = await readContentFromFile(options.file);
1105
1272
  let title = options.title;
1273
+ if (!title && options.file) {
1274
+ title = inferFileTitle(options.file, contentText);
1275
+ }
1106
1276
  if (!title) {
1107
1277
  const answers = await inquirer.prompt([
1108
1278
  {
@@ -1115,25 +1285,101 @@ function createArticleCommands() {
1115
1285
  title = String(answers.title);
1116
1286
  }
1117
1287
  const articleId = options.id || uuidv4();
1288
+ if (options.publish && !options.yes && !await confirmPublicPublish(articleId)) {
1289
+ output.info("Article creation cancelled; nothing was published.");
1290
+ return;
1291
+ }
1118
1292
  const created = await client.article.create(workspaceId, {
1119
1293
  articleId,
1120
1294
  title: String(title),
1121
1295
  folderId: options.folder ?? null,
1122
1296
  collaborative: Boolean(options.collaborative)
1123
1297
  });
1124
- output.success("Article created successfully");
1125
- output.output(created);
1126
- let contentText = null;
1127
- if (options.content !== void 0) contentText = options.content;
1128
- else if (options.file) contentText = await readContentFromFile(options.file);
1129
1298
  if (contentText !== null) {
1130
- await client.article.saveContent(workspaceId, articleId, contentText, {
1131
- baseContentRevision: 0,
1132
- contentHash: sha256Hex(contentText),
1133
- title: String(title),
1134
- folderId: options.folder ?? null
1299
+ try {
1300
+ if (options.collaborative) {
1301
+ const session = await openArticleSession({
1302
+ apiKey,
1303
+ websocketToken: apiKey,
1304
+ workspaceId,
1305
+ articleId,
1306
+ agent: { name: "mdedit-cli" },
1307
+ apiUrl: getApiUrlRaw()
1308
+ });
1309
+ try {
1310
+ const currentContent = session.read();
1311
+ await session.edit([{
1312
+ type: "replace",
1313
+ anchor: { range: { from: 0, to: currentContent.length } },
1314
+ text: contentText
1315
+ }]);
1316
+ } finally {
1317
+ await session.close();
1318
+ }
1319
+ const expectedContentHash = sha256Hex(contentText);
1320
+ let checkpointedContentHash;
1321
+ for (let attempt = 0; attempt < 20; attempt += 1) {
1322
+ try {
1323
+ const checkpoint = await client.collaboration.checkpoint(workspaceId, articleId);
1324
+ checkpointedContentHash = checkpoint.targetHashes["content.md"];
1325
+ if (checkpointedContentHash === expectedContentHash) break;
1326
+ } catch (error) {
1327
+ if (!(error instanceof FetchError2) || error.status !== 409 && error.status !== 503) {
1328
+ throw error;
1329
+ }
1330
+ }
1331
+ await new Promise((resolve2) => setTimeout(resolve2, 500));
1332
+ }
1333
+ if (checkpointedContentHash !== expectedContentHash) {
1334
+ throw new Error("Collaborative content did not reach a durable checkpoint within 10 seconds.");
1335
+ }
1336
+ } else {
1337
+ await client.article.saveContent(workspaceId, articleId, contentText, {
1338
+ baseContentRevision: 0,
1339
+ contentHash: sha256Hex(contentText),
1340
+ title: String(title),
1341
+ folderId: options.folder ?? null
1342
+ });
1343
+ }
1344
+ } catch (contentError) {
1345
+ let compensated = false;
1346
+ let compensationError;
1347
+ try {
1348
+ await client.article.delete(workspaceId, articleId);
1349
+ compensated = true;
1350
+ } catch (error) {
1351
+ compensationError = error;
1352
+ }
1353
+ throw new ArticleCreateContentError({
1354
+ articleId,
1355
+ compensated,
1356
+ contentError,
1357
+ compensationError
1358
+ });
1359
+ }
1360
+ }
1361
+ output.success("Article created successfully");
1362
+ if (contentText !== null) output.success("Article content uploaded");
1363
+ if (!options.publish) {
1364
+ output.output(created);
1365
+ return;
1366
+ }
1367
+ try {
1368
+ const publication = await client.publish.publish(
1369
+ workspaceId,
1370
+ articleId,
1371
+ publishRequest(options)
1372
+ );
1373
+ output.success("Article published publicly");
1374
+ output.output({
1375
+ ...created ?? { articleId, workspaceId },
1376
+ publication
1135
1377
  });
1136
- output.success("Article content uploaded");
1378
+ } catch (error) {
1379
+ const message = error instanceof Error ? error.message : String(error);
1380
+ throw new Error(
1381
+ `Article ${articleId} was created and kept, but publishing failed: ${message}`
1382
+ );
1137
1383
  }
1138
1384
  });
1139
1385
  article.command("update <articleId>").description("Update an article").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-t, --title <title>", "New title").option("--archive", "Archive the article").option("--pin", "Pin the article").option("--file <path>", "Update article content from a file (use - for stdin)").option("--content <text>", "Update article content as an inline string").action(async (articleId, options) => {
@@ -1173,6 +1419,50 @@ function createArticleCommands() {
1173
1419
  output.warning("No changes provided. Use --title, --archive, --pin, --file, or --content.");
1174
1420
  }
1175
1421
  });
1422
+ article.command("publish <articleId>").description("Publish or update an article at a public mded.it link").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("--slug <slug>", "Custom public-link slug").option("--seo-title <title>", "SEO/social title for the public page").option("--seo-description <description>", "SEO/social description for the public page").option("-y, --yes", "Skip public-publishing confirmation").action(async (articleId, options) => {
1423
+ requireApiKey();
1424
+ const client = getApiClient();
1425
+ const workspaceId = requireWorkspaceId(options.workspace);
1426
+ if (!options.yes && !await confirmPublicPublish(articleId)) {
1427
+ output.info("Publish cancelled.");
1428
+ return;
1429
+ }
1430
+ const result = await client.publish.publish(
1431
+ workspaceId,
1432
+ articleId,
1433
+ publishRequest(options)
1434
+ );
1435
+ output.success("Article published publicly");
1436
+ output.output(result);
1437
+ });
1438
+ article.command("publish-status <articleId>").description("Show public publishing status for an article").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").action(async (articleId, options) => {
1439
+ requireApiKey();
1440
+ const client = getApiClient();
1441
+ const workspaceId = requireWorkspaceId(options.workspace);
1442
+ output.output(await client.publish.status(workspaceId, articleId));
1443
+ });
1444
+ article.command("unpublish <articleId>").description("Disable an article public link").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-y, --yes", "Skip confirmation").action(async (articleId, options) => {
1445
+ requireApiKey();
1446
+ const client = getApiClient();
1447
+ const workspaceId = requireWorkspaceId(options.workspace);
1448
+ if (!options.yes) {
1449
+ const { confirm } = await inquirer.prompt([
1450
+ {
1451
+ type: "confirm",
1452
+ name: "confirm",
1453
+ message: `Unpublish article ${articleId}? Its public link will stop working.`,
1454
+ default: false
1455
+ }
1456
+ ]);
1457
+ if (!confirm) {
1458
+ output.info("Unpublish cancelled.");
1459
+ return;
1460
+ }
1461
+ }
1462
+ const result = await client.publish.unpublish(workspaceId, articleId);
1463
+ output.success("Article unpublished");
1464
+ output.output(result);
1465
+ });
1176
1466
  article.command("watch <articleId>").description("Stream article and review changes as newline-delimited JSON").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("--agent <name>", "Agent presence name", "mdedit-cli").option("--poll-interval <milliseconds>", "REST fallback polling interval", "2000").action(async (articleId, options) => {
1177
1467
  const apiKey = requireApiKey();
1178
1468
  const workspaceId = requireWorkspaceId(options.workspace);
@@ -2061,7 +2351,11 @@ async function main() {
2061
2351
  if (err.status === 401) {
2062
2352
  output.info("Hint: set an API key via `mdedit config set apiKey <key>` or pass `--api-key <key>`.");
2063
2353
  } else if (err.status === 403) {
2064
- output.info("Hint: check that the API key user has permission for this workspace/resource.");
2354
+ if (err.message.includes("publishing:write")) {
2355
+ output.info("Hint: publishing requires an API key with publishing:write scope.");
2356
+ } else {
2357
+ output.info("Hint: check that the API key has the required scope and permission for this workspace/resource.");
2358
+ }
2065
2359
  } else if (err.status === 404) {
2066
2360
  output.info("Hint: verify your `apiUrl` and that the API build matches the CLI routes.");
2067
2361
  }