mdedit-cli 0.4.2 → 0.4.4

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
@@ -74,6 +74,158 @@ async function getToolJobStatus(jobId, fetchers) {
74
74
  if (!resp.ok) throw await buildApiError(resp);
75
75
  return resp.json();
76
76
  }
77
+ async function createConversionUploadUrl(request, fetchers, signal) {
78
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
79
+ const resp = await fetchV2("/conversions/uploads", {
80
+ method: "POST",
81
+ body: JSON.stringify(request),
82
+ headers: { "Content-Type": "application/json" },
83
+ signal
84
+ });
85
+ if (!resp.ok) throw await buildApiError(resp);
86
+ return resp.json();
87
+ }
88
+ async function startConversion(request, fetchers, signal) {
89
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
90
+ const resp = await fetchV2("/conversions", {
91
+ method: "POST",
92
+ body: JSON.stringify(request),
93
+ headers: { "Content-Type": "application/json" },
94
+ signal
95
+ });
96
+ if (!resp.ok) throw await buildApiError(resp);
97
+ return resp.json();
98
+ }
99
+ async function getConversionStatus(jobId, fetchers, signal) {
100
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
101
+ const resp = await fetchV2(`/conversions/${encodeURIComponent(jobId)}`, { signal });
102
+ if (!resp.ok) throw await buildApiError(resp);
103
+ return resp.json();
104
+ }
105
+ async function downloadConversion(jobId, fetchers, signal) {
106
+ const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
107
+ const resp = await fetchV2(`/conversions/${encodeURIComponent(jobId)}/download`, { signal });
108
+ if (!resp.ok) throw await buildApiError(resp);
109
+ return resp.blob();
110
+ }
111
+ function newJobId() {
112
+ if (typeof globalThis.crypto?.randomUUID === "function") return globalThis.crypto.randomUUID();
113
+ const bytes = new Uint8Array(16);
114
+ globalThis.crypto.getRandomValues(bytes);
115
+ bytes[6] = bytes[6] & 15 | 64;
116
+ bytes[8] = bytes[8] & 63 | 128;
117
+ const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
118
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
119
+ }
120
+ function safeFileName(fileName) {
121
+ const base = fileName.split(/[\\/]/).pop() || "input";
122
+ return base.replace(/[^\w.\-]+/g, "_").slice(0, 128) || "input";
123
+ }
124
+ function abortReason(signal) {
125
+ const reason = signal?.reason;
126
+ return reason instanceof Error ? reason : new Error("Conversion aborted");
127
+ }
128
+ function withDeadline(timeoutMs, signal) {
129
+ const controller = new AbortController();
130
+ const onAbort = () => controller.abort(abortReason(signal));
131
+ if (signal?.aborted) {
132
+ onAbort();
133
+ } else {
134
+ signal?.addEventListener("abort", onAbort, { once: true });
135
+ }
136
+ const timer = setTimeout(
137
+ () => controller.abort(new Error(`Conversion timed out after ${Math.round(timeoutMs / 1e3)}s`)),
138
+ timeoutMs
139
+ );
140
+ return {
141
+ signal: controller.signal,
142
+ dispose: () => {
143
+ clearTimeout(timer);
144
+ signal?.removeEventListener("abort", onAbort);
145
+ }
146
+ };
147
+ }
148
+ async function startConversionFromBytes(input, fetchers) {
149
+ const {
150
+ data,
151
+ type,
152
+ inputFormat,
153
+ outputFormat,
154
+ outputFileName,
155
+ contentType = "application/octet-stream",
156
+ toolRunId,
157
+ signal
158
+ } = input;
159
+ const jobId = newJobId();
160
+ const fileName = safeFileName(input.fileName);
161
+ const inputKey = `tools/input/${jobId}/${fileName}`;
162
+ const { signedUrl } = await createConversionUploadUrl(
163
+ { key: inputKey, action: "putObject", contentType },
164
+ fetchers,
165
+ signal
166
+ );
167
+ const body = data instanceof Uint8Array ? data : new Uint8Array(data);
168
+ const uploadResponse = await fetch(signedUrl, {
169
+ method: "PUT",
170
+ body,
171
+ headers: { "Content-Type": contentType },
172
+ signal
173
+ });
174
+ if (!uploadResponse.ok) {
175
+ throw new Error(`Upload failed with status ${uploadResponse.status}`);
176
+ }
177
+ await startConversion(
178
+ {
179
+ type,
180
+ inputKey,
181
+ inputFormat,
182
+ ...outputFormat ? { outputFormat } : {},
183
+ ...outputFileName ? { outputFileName } : {},
184
+ ...toolRunId ? { toolRunId } : {}
185
+ },
186
+ fetchers,
187
+ signal
188
+ );
189
+ return { jobId };
190
+ }
191
+ async function convertFile(input, fetchers) {
192
+ const {
193
+ outputFileName,
194
+ onProgress,
195
+ pollIntervalMs = DEFAULT_POLL_INTERVAL_MS,
196
+ timeoutMs = DEFAULT_TIMEOUT_MS,
197
+ signal
198
+ } = input;
199
+ const deadline = withDeadline(timeoutMs, signal);
200
+ try {
201
+ const { jobId } = await startConversionFromBytes(
202
+ { ...input, signal: deadline.signal },
203
+ fetchers
204
+ );
205
+ for (; ; ) {
206
+ const status = await getConversionStatus(jobId, fetchers, deadline.signal);
207
+ onProgress?.(status);
208
+ if (status.status === "completed") {
209
+ const blob = await downloadConversion(jobId, fetchers, deadline.signal);
210
+ return {
211
+ blob,
212
+ jobId,
213
+ fileName: status.fileName || outputFileName || `${jobId}.out`,
214
+ mimeType: status.mimeType || "application/octet-stream"
215
+ };
216
+ }
217
+ if (status.status === "failed") {
218
+ const error = new Error(status.failedReason || "Conversion failed");
219
+ error.errorCode = status.errorCode;
220
+ error.errorDetails = status.errorDetails;
221
+ throw error;
222
+ }
223
+ await sleep(pollIntervalMs, deadline.signal);
224
+ }
225
+ } finally {
226
+ deadline.dispose();
227
+ }
228
+ }
77
229
  async function fetchErrorFromResponse(prefix, response) {
78
230
  const text = await response.text();
79
231
  let data;
@@ -160,6 +312,14 @@ function createSdkClient(config) {
160
312
  collaboration: {
161
313
  checkpoint: (workspaceId, articleId) => withFetchError(() => checkpointCollaboration(workspaceId, articleId, fetchers))
162
314
  },
315
+ tools: {
316
+ createUpload: (request) => withFetchError(() => createConversionUploadUrl(request, fetchers)),
317
+ convert: (request) => withFetchError(() => startConversion(request, fetchers)),
318
+ jobStatus: (jobId) => withFetchError(() => getConversionStatus(jobId, fetchers)),
319
+ download: (jobId) => withFetchError(() => downloadConversion(jobId, fetchers)),
320
+ convertFile: (input) => withFetchError(() => convertFile(input, fetchers)),
321
+ startConversion: (input) => withFetchError(() => startConversionFromBytes(input, fetchers))
322
+ },
163
323
  publish: {
164
324
  publish: (workspaceId, articleId, request = {}) => withFetchError(() => publishArticle(workspaceId, articleId, request, fetchers)),
165
325
  status: (workspaceId, articleId) => withFetchError(() => getPublishStatus(workspaceId, articleId, fetchers)),
@@ -168,7 +328,7 @@ function createSdkClient(config) {
168
328
  }
169
329
  };
170
330
  }
171
- var _defaultFetchers, customFetchV2, FetchError, errors_default, createArticle, updateArticle, getArticles, getArticlesByFolder, getArticle, getArticlePresentation, getArticleAssetDownloadUrls, getArticleMediaProxyUrls, getArticleSafeGists, deleteArticle, exportArticleZip, createArticleExportJob, ApiError, saveArticleContent, getWorkspaces, createWorkspace, updateWorkspace, deleteWorkspace, getWorkspace, normalizeTimestampMs, readFolderErrorMessage, normalizeFolder, createFolder, updateFolder, getFolders, getFolder, deleteFolder, sleep, isRetriableStatus, withRetries, listApiKeys, createApiKey, revokeApiKey, checkpointCollaboration, publishArticle, unpublishArticle, getPublishStatus, updatePublishedArticle, FetchError2;
331
+ var _defaultFetchers, customFetchV2, FetchError, errors_default, createArticle, updateArticle, getArticles, getArticlesByFolder, getArticle, getArticlePresentation, getArticleAssetDownloadUrls, getArticleMediaProxyUrls, getArticleSafeGists, deleteArticle, exportArticleZip, createArticleExportJob, ApiError, DEFAULT_POLL_INTERVAL_MS, DEFAULT_TIMEOUT_MS, sleep, saveArticleContent, getWorkspaces, createWorkspace, updateWorkspace, deleteWorkspace, getWorkspace, normalizeTimestampMs, readFolderErrorMessage, normalizeFolder, createFolder, updateFolder, getFolders, getFolder, deleteFolder, sleep2, isRetriableStatus, withRetries, listApiKeys, createApiKey, revokeApiKey, checkpointCollaboration, publishArticle, unpublishArticle, getPublishStatus, updatePublishedArticle, FetchError2;
172
332
  var init_dist = __esm({
173
333
  "../sdk/dist/index.js"() {
174
334
  "use strict";
@@ -402,6 +562,20 @@ var init_dist = __esm({
402
562
  this.data = data;
403
563
  }
404
564
  };
565
+ DEFAULT_POLL_INTERVAL_MS = 1500;
566
+ DEFAULT_TIMEOUT_MS = 10 * 60 * 1e3;
567
+ sleep = (ms, signal) => new Promise((resolve, reject) => {
568
+ if (signal?.aborted) return reject(abortReason(signal));
569
+ const timer = setTimeout(() => {
570
+ signal?.removeEventListener("abort", onAbort);
571
+ resolve();
572
+ }, ms);
573
+ const onAbort = () => {
574
+ clearTimeout(timer);
575
+ reject(abortReason(signal));
576
+ };
577
+ signal?.addEventListener("abort", onAbort, { once: true });
578
+ });
405
579
  saveArticleContent = async (workspaceId, articleId, content, optionsOrFetchers, fetchers) => {
406
580
  const maybeFetchers = optionsOrFetchers && "customFetchV2" in optionsOrFetchers ? optionsOrFetchers : fetchers;
407
581
  const options = optionsOrFetchers && !("customFetchV2" in optionsOrFetchers) ? optionsOrFetchers : void 0;
@@ -657,7 +831,7 @@ var init_dist = __esm({
657
831
  }
658
832
  return true;
659
833
  };
660
- sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
834
+ sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
661
835
  isRetriableStatus = (status) => status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
662
836
  withRetries = async (fn, maxAttempts = 3) => {
663
837
  let lastError;
@@ -667,7 +841,7 @@ var init_dist = __esm({
667
841
  if (response.ok) return response;
668
842
  if (attempt < maxAttempts && isRetriableStatus(response.status)) {
669
843
  const backoffMs = 250 * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 150);
670
- await sleep(backoffMs);
844
+ await sleep2(backoffMs);
671
845
  continue;
672
846
  }
673
847
  return response;
@@ -675,7 +849,7 @@ var init_dist = __esm({
675
849
  lastError = e;
676
850
  if (attempt < maxAttempts) {
677
851
  const backoffMs = 250 * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 150);
678
- await sleep(backoffMs);
852
+ await sleep2(backoffMs);
679
853
  continue;
680
854
  }
681
855
  throw lastError;
@@ -1695,7 +1869,7 @@ var init_api = __esm({
1695
1869
 
1696
1870
  // src/index.ts
1697
1871
  init_dist();
1698
- import { Command as Command9 } from "commander";
1872
+ import { Command as Command10 } from "commander";
1699
1873
  import { readFileSync as readFileSync3 } from "fs";
1700
1874
  import { dirname as dirname2, join as join3 } from "path";
1701
1875
  import { fileURLToPath as fileURLToPath2 } from "url";
@@ -1752,7 +1926,7 @@ var ArticleCreateContentError = class extends Error {
1752
1926
  constructor(args) {
1753
1927
  const contentError = args.contentError instanceof Error ? args.contentError.message : String(args.contentError);
1754
1928
  const compensationError = args.compensationError instanceof Error ? args.compensationError.message : args.compensationError === void 0 ? void 0 : String(args.compensationError);
1755
- 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.`);
1929
+ super(args.compensated ? `Initial document content could not be saved; the created document ${args.articleId} was rolled back.` : `Initial document content could not be saved and document ${args.articleId} could not be rolled back.`);
1756
1930
  this.name = "ArticleCreateContentError";
1757
1931
  this.articleId = args.articleId;
1758
1932
  this.compensated = args.compensated;
@@ -1959,14 +2133,20 @@ async function readEditOperations(filePath) {
1959
2133
  }
1960
2134
  return parsed;
1961
2135
  }
1962
- function createArticleCommands() {
1963
- const article = new Command("article").description("Manage articles").action(() => article.help());
1964
- 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) => {
2136
+ function createDocumentCommand(commandName, deprecated) {
2137
+ const commandPath = `mdedit ${commandName}`;
2138
+ const article = new Command(commandName).description(deprecated ? "Deprecated alias for document commands" : "Manage documents").action(() => article.help());
2139
+ if (deprecated) {
2140
+ article.hook("preAction", () => {
2141
+ output.warning("`mdedit article` is deprecated. Use `mdedit document` instead.");
2142
+ });
2143
+ }
2144
+ article.command("list").description("List all documents").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 document objects (all fields)").action(async (options) => {
1965
2145
  requireApiKey();
1966
2146
  const client = getApiClient();
1967
2147
  const workspaceId = requireWorkspaceId(options.workspace);
1968
2148
  const articles = options.folder ? await client.article.listByFolder(workspaceId, options.folder) : await client.article.list(workspaceId);
1969
- output.header("Articles");
2149
+ output.header("Documents");
1970
2150
  const offset = Number(options.offset) || 0;
1971
2151
  const limit = Number(options.limit) || articles.length;
1972
2152
  const slice = articles.slice(offset, offset + limit);
@@ -1976,7 +2156,7 @@ function createArticleCommands() {
1976
2156
  }
1977
2157
  output.output(slice.map(presentArticleListRow));
1978
2158
  });
1979
- 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) => {
2159
+ article.command("get <documentId>").description("Get document details").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-o, --output <file>", "Save document content (markdown) to this file path; use - for stdout").option("--content-only", "Print only the document markdown content to stdout (useful for piping / AI agents)").option("--include-content", "Include the document markdown content in the output object").option("--full", "Show full document object (all fields, including nested metadata)").action(async (articleId, options) => {
1980
2160
  requireApiKey();
1981
2161
  const client = getApiClient();
1982
2162
  const workspaceId = requireWorkspaceId(options.workspace);
@@ -1991,20 +2171,20 @@ function createArticleCommands() {
1991
2171
  process.stdout.write(content);
1992
2172
  } else {
1993
2173
  await writeFile(options.output, content, "utf-8");
1994
- output.success(`Article content saved to ${options.output}`);
2174
+ output.success(`Document content saved to ${options.output}`);
1995
2175
  }
1996
2176
  return;
1997
2177
  }
1998
- output.header(`Article: ${articleId}`);
2178
+ output.header(`Document: ${articleId}`);
1999
2179
  const wantsFull = Boolean(options.full) || Boolean(options.includeContent);
2000
2180
  if (output.isJson() || wantsFull) {
2001
2181
  output.output(result);
2002
2182
  return;
2003
2183
  }
2004
2184
  output.output(presentArticleDetails(result));
2005
- output.info("Hint: use `mdedit article get <articleId> --content-only` to print markdown, or `--include-content` to include it in the output.");
2185
+ output.info(`Hint: use \`${commandPath} get <documentId> --content-only\` to print markdown, or \`--include-content\` to include it in the output.`);
2006
2186
  });
2007
- 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 live public mded.it link").option("--snapshot", "Publish a frozen snapshot instead of a live link (requires --publish)").option("--live", "Explicitly publish a live-updating link (requires --publish)").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)").addOption(new Option("-y, --yes").hideHelp()).action(async (options) => {
2187
+ article.command("create").description("Create a new document").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-i, --id <documentId>", "Document ID (defaults to a UUID)").option("-t, --title <title>", "Document title").option("-f, --folder <folderId>", "Folder ID").option("-c, --collaborative", "Enable collaborative editing").option("--file <path>", "Read initial document content from a file (use - for stdin)").option("--content <text>", "Set initial document content as an inline string").option("--publish", "Publish the created document to a live public mded.it link").option("--snapshot", "Publish a frozen snapshot instead of a live link (requires --publish)").option("--live", "Explicitly publish a live-updating link (requires --publish)").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)").addOption(new Option("-y, --yes").hideHelp()).action(async (options) => {
2008
2188
  requireAuthentication();
2009
2189
  const credentialProvider = getAgentCredentialProvider();
2010
2190
  const client = getApiClient();
@@ -2028,7 +2208,7 @@ function createArticleCommands() {
2028
2208
  {
2029
2209
  type: "input",
2030
2210
  name: "title",
2031
- message: "Article title:",
2211
+ message: "Document title:",
2032
2212
  validate: (input) => input.length > 0 || "Title is required"
2033
2213
  }
2034
2214
  ]);
@@ -2103,8 +2283,8 @@ function createArticleCommands() {
2103
2283
  });
2104
2284
  }
2105
2285
  }
2106
- output.success("Article created successfully");
2107
- if (contentText !== null) output.success("Article content uploaded");
2286
+ output.success("Document created successfully");
2287
+ if (contentText !== null) output.success("Document content uploaded");
2108
2288
  if (!options.publish) {
2109
2289
  output.output(created);
2110
2290
  return;
@@ -2115,7 +2295,7 @@ function createArticleCommands() {
2115
2295
  articleId,
2116
2296
  publishRequest(options, "live")
2117
2297
  );
2118
- output.success("Article published publicly");
2298
+ output.success("Document published publicly");
2119
2299
  output.output({
2120
2300
  ...created ?? { articleId, workspaceId },
2121
2301
  publication
@@ -2123,11 +2303,11 @@ function createArticleCommands() {
2123
2303
  } catch (error) {
2124
2304
  const message = error instanceof Error ? error.message : String(error);
2125
2305
  throw new Error(
2126
- `Article ${articleId} was created and kept, but publishing failed: ${message}`
2306
+ `Document ${articleId} was created and kept, but publishing failed: ${message}`
2127
2307
  );
2128
2308
  }
2129
2309
  });
2130
- 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) => {
2310
+ article.command("update <documentId>").description("Update a document").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-t, --title <title>", "New title").option("--archive", "Archive the document").option("--pin", "Pin the document").option("--file <path>", "Update document content from a file (use - for stdin)").option("--content <text>", "Update document content as an inline string").action(async (articleId, options) => {
2131
2311
  requireApiKey();
2132
2312
  const client = getApiClient();
2133
2313
  const workspaceId = requireWorkspaceId(options.workspace);
@@ -2143,7 +2323,7 @@ function createArticleCommands() {
2143
2323
  else if (options.file) contentText = await readContentFromFile(options.file);
2144
2324
  if (contentText === null && Object.keys(body).length > 0) {
2145
2325
  const result = await client.article.update(workspaceId, { articleId, ...body });
2146
- output.success("Article updated successfully");
2326
+ output.success("Document updated successfully");
2147
2327
  output.output(result);
2148
2328
  }
2149
2329
  if (contentText !== null) {
@@ -2157,14 +2337,14 @@ function createArticleCommands() {
2157
2337
  isArchived: body.isArchived,
2158
2338
  isPinned: body.isPinned
2159
2339
  });
2160
- output.success("Article content updated");
2340
+ output.success("Document content updated");
2161
2341
  output.output(result);
2162
2342
  }
2163
2343
  if (Object.keys(body).length === 0 && contentText === null) {
2164
2344
  output.warning("No changes provided. Use --title, --archive, --pin, --file, or --content.");
2165
2345
  }
2166
2346
  });
2167
- 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("--snapshot", "Create or switch to a frozen snapshot").option("--live", "Create or switch to a live-updating public link").addOption(new Option("-y, --yes").hideHelp()).action(async (articleId, options) => {
2347
+ article.command("publish <documentId>").description("Publish or update a document 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("--snapshot", "Create or switch to a frozen snapshot").option("--live", "Create or switch to a live-updating public link").addOption(new Option("-y, --yes").hideHelp()).action(async (articleId, options) => {
2168
2348
  requireApiKey();
2169
2349
  const client = getApiClient();
2170
2350
  const workspaceId = requireWorkspaceId(options.workspace);
@@ -2173,16 +2353,16 @@ function createArticleCommands() {
2173
2353
  articleId,
2174
2354
  agentPublishRequest(options)
2175
2355
  );
2176
- output.success("Article published publicly");
2356
+ output.success("Document published publicly");
2177
2357
  output.output(result);
2178
2358
  });
2179
- 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) => {
2359
+ article.command("publish-status <documentId>").description("Show public publishing status for a document").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").action(async (articleId, options) => {
2180
2360
  requireApiKey();
2181
2361
  const client = getApiClient();
2182
2362
  const workspaceId = requireWorkspaceId(options.workspace);
2183
2363
  output.output(await client.publish.status(workspaceId, articleId));
2184
2364
  });
2185
- 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) => {
2365
+ article.command("unpublish <documentId>").description("Disable a document public link").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-y, --yes", "Skip confirmation").action(async (articleId, options) => {
2186
2366
  requireApiKey();
2187
2367
  const client = getApiClient();
2188
2368
  const workspaceId = requireWorkspaceId(options.workspace);
@@ -2191,7 +2371,7 @@ function createArticleCommands() {
2191
2371
  {
2192
2372
  type: "confirm",
2193
2373
  name: "confirm",
2194
- message: `Unpublish article ${articleId}? Its public link will stop working.`,
2374
+ message: `Unpublish document ${articleId}? Its public link will stop working.`,
2195
2375
  default: false
2196
2376
  }
2197
2377
  ]);
@@ -2201,10 +2381,10 @@ function createArticleCommands() {
2201
2381
  }
2202
2382
  }
2203
2383
  const result = await client.publish.unpublish(workspaceId, articleId);
2204
- output.success("Article unpublished");
2384
+ output.success("Document unpublished");
2205
2385
  output.output(result);
2206
2386
  });
2207
- 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) => {
2387
+ article.command("watch <documentId>").description("Stream document 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) => {
2208
2388
  requireAuthentication();
2209
2389
  const credentialProvider = getAgentCredentialProvider();
2210
2390
  const workspaceId = requireWorkspaceId(options.workspace);
@@ -2238,7 +2418,7 @@ function createArticleCommands() {
2238
2418
  await session?.close();
2239
2419
  }
2240
2420
  });
2241
- article.command("edit <articleId>").description("Apply an anchored one-shot edit through an agent article session").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("--replace <text>", "Replace the unique matching text").option("--with <text>", "Replacement text (used with --replace)").option("--ops-file <path>", "Read a JSON array of edit operations from a file").action(async (articleId, options) => {
2421
+ article.command("edit <documentId>").description("Apply an anchored one-shot edit through an agent document session").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("--replace <text>", "Replace the unique matching text").option("--with <text>", "Replacement text (used with --replace)").option("--ops-file <path>", "Read a JSON array of edit operations from a file").action(async (articleId, options) => {
2242
2422
  requireAuthentication();
2243
2423
  const credentialProvider = getAgentCredentialProvider();
2244
2424
  const workspaceId = requireWorkspaceId(options.workspace);
@@ -2274,14 +2454,14 @@ function createArticleCommands() {
2274
2454
  }
2275
2455
  }
2276
2456
  }
2277
- if (!session || !result) throw new Error("Article edit did not return a result.");
2457
+ if (!session || !result) throw new Error("Document edit did not return a result.");
2278
2458
  output.output({ articleId, mode: session.mode, ...result });
2279
2459
  if (result.conflicts.length > 0) {
2280
- output.warning("The edit was applied with overlapping remote changes; re-read the article before continuing.");
2460
+ output.warning("The edit was applied with overlapping remote changes; re-read the document before continuing.");
2281
2461
  process.exitCode = CLI_EXIT_CODES.EDIT_CONFLICT;
2282
2462
  }
2283
2463
  });
2284
- article.command("delete <articleId>").description("Delete an article").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-y, --yes", "Skip confirmation").action(async (articleId, options) => {
2464
+ article.command("delete <documentId>").description("Delete a document").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-y, --yes", "Skip confirmation").action(async (articleId, options) => {
2285
2465
  requireApiKey();
2286
2466
  const client = getApiClient();
2287
2467
  const workspaceId = requireWorkspaceId(options.workspace);
@@ -2290,7 +2470,7 @@ function createArticleCommands() {
2290
2470
  {
2291
2471
  type: "confirm",
2292
2472
  name: "confirm",
2293
- message: `Are you sure you want to delete article ${articleId}?`,
2473
+ message: `Are you sure you want to delete document ${articleId}?`,
2294
2474
  default: false
2295
2475
  }
2296
2476
  ]);
@@ -2300,19 +2480,29 @@ function createArticleCommands() {
2300
2480
  }
2301
2481
  }
2302
2482
  await client.article.delete(workspaceId, articleId);
2303
- output.success("Article deleted successfully");
2483
+ output.success("Document deleted successfully");
2304
2484
  });
2305
- article.command("export <articleId>").description("Export article as ZIP").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option("-o, --output <path>", "Output file path", "./article.zip").action(async (articleId, options) => {
2485
+ article.command("export <documentId>").description("Export document as ZIP").option("-w, --workspace <workspaceId>", "Workspace ID (or set default via config)").option(
2486
+ "-o, --output <path>",
2487
+ "Output file path",
2488
+ commandName === "article" ? "./article.zip" : "./document.zip"
2489
+ ).action(async (articleId, options) => {
2306
2490
  requireApiKey();
2307
2491
  const client = getApiClient();
2308
2492
  const workspaceId = requireWorkspaceId(options.workspace);
2309
- output.info(`Exporting article ${articleId}...`);
2493
+ output.info(`Exporting document ${articleId}...`);
2310
2494
  const zipBlob = await client.article.exportZip(workspaceId, articleId);
2311
2495
  await writeBlobToFile(zipBlob, options.output);
2312
2496
  output.success(`Exported to ${options.output}`);
2313
2497
  });
2314
2498
  return article;
2315
2499
  }
2500
+ function createDocumentCommands() {
2501
+ return createDocumentCommand("document", false);
2502
+ }
2503
+ function createArticleCommands() {
2504
+ return createDocumentCommand("article", true);
2505
+ }
2316
2506
 
2317
2507
  // src/commands/workspace.ts
2318
2508
  init_output();
@@ -3016,8 +3206,8 @@ function presentReviewItem(item) {
3016
3206
  };
3017
3207
  }
3018
3208
  function createReviewCommands() {
3019
- const review = new Command7("review").description("Review an article through server-authoritative agent commands").action(() => review.help());
3020
- addCommon(review.command("list <articleId>").description("List article review items").option("-s, --status <status>", "Filter by review status")).action(async (articleId, options) => {
3209
+ const review = new Command7("review").description("Review a document through server-authoritative agent commands").action(() => review.help());
3210
+ addCommon(review.command("list <documentId>").description("List document review items").option("-s, --status <status>", "Filter by review status")).action(async (articleId, options) => {
3021
3211
  const workspaceId = requireWorkspaceId(options.workspace);
3022
3212
  const { result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession.list({
3023
3213
  status: options.status,
@@ -3025,7 +3215,7 @@ function createReviewCommands() {
3025
3215
  }));
3026
3216
  output.output(output.isJson() ? result : result.map(presentReviewItem));
3027
3217
  });
3028
- addQuote(review.command("add <articleId>").description("Add a comment anchored to quoted text").requiredOption("-b, --body <text>", "Comment body")).action(async (articleId, options) => {
3218
+ addQuote(review.command("add <documentId>").description("Add a comment anchored to quoted text").requiredOption("-b, --body <text>", "Comment body")).action(async (articleId, options) => {
3029
3219
  const workspaceId = requireWorkspaceId(options.workspace);
3030
3220
  const { mode, result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession.addComment({
3031
3221
  anchor: quoteAnchor(options),
@@ -3034,7 +3224,7 @@ function createReviewCommands() {
3034
3224
  }));
3035
3225
  output.output({ articleId, mode, ...result });
3036
3226
  });
3037
- addCommon(review.command("reply <articleId>").description("Reply to a comment or suggestion thread").requiredOption("--thread <reviewId>", "Review thread ID").requiredOption("-b, --body <text>", "Reply body")).action(async (articleId, options) => {
3227
+ addCommon(review.command("reply <documentId>").description("Reply to a comment or suggestion thread").requiredOption("--thread <reviewId>", "Review thread ID").requiredOption("-b, --body <text>", "Reply body")).action(async (articleId, options) => {
3038
3228
  const workspaceId = requireWorkspaceId(options.workspace);
3039
3229
  const { mode, result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession.reply({
3040
3230
  threadId: options.thread,
@@ -3044,7 +3234,7 @@ function createReviewCommands() {
3044
3234
  output.output({ articleId, mode, ...result });
3045
3235
  });
3046
3236
  for (const verb of ["resolve", "reopen", "accept", "reject"]) {
3047
- addCommon(review.command(`${verb} <articleId>`).description(`${verb[0].toUpperCase()}${verb.slice(1)} a review thread`).requiredOption("--thread <reviewId>", "Review thread ID")).action(async (articleId, options) => {
3237
+ addCommon(review.command(`${verb} <documentId>`).description(`${verb[0].toUpperCase()}${verb.slice(1)} a review thread`).requiredOption("--thread <reviewId>", "Review thread ID")).action(async (articleId, options) => {
3048
3238
  const workspaceId = requireWorkspaceId(options.workspace);
3049
3239
  const { mode, result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession[verb]({
3050
3240
  threadId: options.thread,
@@ -3053,7 +3243,7 @@ function createReviewCommands() {
3053
3243
  output.output({ articleId, mode, ...result });
3054
3244
  });
3055
3245
  }
3056
- addCommon(review.command("delete <articleId>").description("Delete a review item or one of its replies").requiredOption("--thread <reviewId>", "Review thread ID").option("--reply <replyId>", "Reply ID; omit to delete the whole review item")).action(async (articleId, options) => {
3246
+ addCommon(review.command("delete <documentId>").description("Delete a review item or one of its replies").requiredOption("--thread <reviewId>", "Review thread ID").option("--reply <replyId>", "Reply ID; omit to delete the whole review item")).action(async (articleId, options) => {
3057
3247
  const workspaceId = requireWorkspaceId(options.workspace);
3058
3248
  const { mode, result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession.delete({
3059
3249
  threadId: options.thread,
@@ -3065,7 +3255,7 @@ function createReviewCommands() {
3065
3255
  return review;
3066
3256
  }
3067
3257
  function createSuggestCommand() {
3068
- return addQuote(new Command7("suggest").description("Suggest a replacement anchored to quoted text").argument("<articleId>", "Article ID").requiredOption("-r, --replace <text>", "Replacement text").option("-n, --note <text>", "Optional explanation for the suggestion")).action(async (articleId, options) => {
3258
+ return addQuote(new Command7("suggest").description("Suggest a replacement anchored to quoted text").argument("<documentId>", "Document ID").requiredOption("-r, --replace <text>", "Replacement text").option("-n, --note <text>", "Optional explanation for the suggestion")).action(async (articleId, options) => {
3069
3259
  const workspaceId = requireWorkspaceId(options.workspace);
3070
3260
  const { mode, result } = await withReview(articleId, workspaceId, (reviewSession) => reviewSession.suggest({
3071
3261
  anchor: quoteAnchor(options),
@@ -3121,6 +3311,133 @@ function createAuthCommands(runtime = defaultRuntime) {
3121
3311
  return auth;
3122
3312
  }
3123
3313
 
3314
+ // src/commands/convert.ts
3315
+ init_output();
3316
+ init_api();
3317
+ import { Command as Command9 } from "commander";
3318
+ import { readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
3319
+ import { basename as basename2, extname as extname2 } from "path";
3320
+ var MARKDOWN_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".markdown", ".mdown", ".mkd"]);
3321
+ var HTML_EXTENSIONS = /* @__PURE__ */ new Set([".html", ".htm"]);
3322
+ var PANDOC_INPUT_FORMATS = /* @__PURE__ */ new Set([
3323
+ "markdown",
3324
+ "md",
3325
+ "html",
3326
+ "latex",
3327
+ "tex",
3328
+ "rst",
3329
+ "rtf",
3330
+ "docx",
3331
+ "odt",
3332
+ "epub",
3333
+ "ipynb",
3334
+ "asciidoc",
3335
+ "txt",
3336
+ "org",
3337
+ "mediawiki",
3338
+ "typst",
3339
+ "docbook"
3340
+ ]);
3341
+ var PANDOC_OUTPUT_FORMATS = /* @__PURE__ */ new Set([...PANDOC_INPUT_FORMATS, "pdf", "pptx"]);
3342
+ var MARKITDOWN_INPUT_FORMATS = /* @__PURE__ */ new Set(["pdf", "pptx", "xlsx", "xls", "msg"]);
3343
+ var MARKDOWN_OUTPUT_ALIASES = /* @__PURE__ */ new Set(["md", "markdown"]);
3344
+ function resolveConversion(inputFile, to, from) {
3345
+ const outputFormat = to.trim().toLowerCase().replace(/^\./, "");
3346
+ if (!outputFormat) {
3347
+ throw new Error("--to is required, for example --to docx");
3348
+ }
3349
+ const ext = extname2(inputFile).toLowerCase().replace(/^\./, "");
3350
+ const explicitFrom = from?.trim().toLowerCase().replace(/^\./, "");
3351
+ const rawInput = explicitFrom || ext;
3352
+ if (!rawInput) {
3353
+ throw new Error("Cannot tell the input format from the file name. Pass --from, for example --from md.");
3354
+ }
3355
+ const isMarkdown = explicitFrom ? MARKDOWN_OUTPUT_ALIASES.has(explicitFrom) : MARKDOWN_EXTENSIONS.has(`.${ext}`);
3356
+ const isHtml = explicitFrom ? ["html", "htm"].includes(explicitFrom) : HTML_EXTENSIONS.has(`.${ext}`);
3357
+ if (isMarkdown || isHtml) {
3358
+ const inputFormat = isMarkdown ? "markdown" : "html";
3359
+ if (outputFormat === "pdf") return { type: "pdf", inputFormat, outputFormat };
3360
+ if (outputFormat === "mp3") return { type: "mp3", inputFormat, outputFormat };
3361
+ if (outputFormat === "zip") {
3362
+ if (!isMarkdown) {
3363
+ throw new Error("Only Markdown can be converted to zip. Convert the HTML to Markdown first.");
3364
+ }
3365
+ return { type: "zip", inputFormat, outputFormat };
3366
+ }
3367
+ if (!PANDOC_OUTPUT_FORMATS.has(outputFormat)) {
3368
+ throw new Error(
3369
+ `Cannot convert ${inputFormat} to ${outputFormat}. Supported: ${[...PANDOC_OUTPUT_FORMATS].sort().join(", ")}, mp3, zip.`
3370
+ );
3371
+ }
3372
+ return { type: "pandoc", inputFormat, outputFormat };
3373
+ }
3374
+ if (PANDOC_INPUT_FORMATS.has(rawInput)) {
3375
+ if (outputFormat === "mp3" || outputFormat === "zip") {
3376
+ throw new Error(
3377
+ `Cannot convert ${rawInput} to ${outputFormat}. Convert to Markdown first, then to ${outputFormat}.`
3378
+ );
3379
+ }
3380
+ if (!PANDOC_OUTPUT_FORMATS.has(outputFormat)) {
3381
+ throw new Error(
3382
+ `Cannot convert ${rawInput} to ${outputFormat}. Supported: ${[...PANDOC_OUTPUT_FORMATS].sort().join(", ")}.`
3383
+ );
3384
+ }
3385
+ return { type: "pandoc", inputFormat: rawInput, outputFormat };
3386
+ }
3387
+ if (MARKITDOWN_INPUT_FORMATS.has(rawInput)) {
3388
+ if (!MARKDOWN_OUTPUT_ALIASES.has(outputFormat)) {
3389
+ throw new Error(
3390
+ `${rawInput} can only be converted to Markdown. Run a second conversion to reach ${outputFormat}.`
3391
+ );
3392
+ }
3393
+ return { type: "markitdown", inputFormat: rawInput, outputFormat: "markdown" };
3394
+ }
3395
+ throw new Error(
3396
+ `Unsupported input format: ${rawInput}. Supported inputs: ${[.../* @__PURE__ */ new Set([...PANDOC_INPUT_FORMATS, ...MARKITDOWN_INPUT_FORMATS])].sort().join(", ")}.`
3397
+ );
3398
+ }
3399
+ function defaultOutputPath(inputFile, outputFormat) {
3400
+ const stem = basename2(inputFile, extname2(inputFile));
3401
+ const ext = outputFormat === "markdown" ? "md" : outputFormat;
3402
+ return `${stem}.${ext}`;
3403
+ }
3404
+ function createConvertCommands() {
3405
+ return new Command9("convert").description("Convert a document between formats").argument("<input>", "Path to the file to convert").requiredOption("-t, --to <format>", "Target format, for example docx, pdf, md").option("-f, --from <format>", "Override the input format (inferred from the extension)").option("-o, --out <path>", "Where to write the result (defaults to the input name with the new extension)").addHelpText("after", `
3406
+ Examples:
3407
+ $ mdedit convert README.md --to docx
3408
+ $ mdedit convert notes.md --to pdf --out notes.pdf
3409
+ $ mdedit convert report.docx --to md
3410
+ `).action(async (inputFile, options) => {
3411
+ requireApiKey();
3412
+ const client = getApiClient();
3413
+ const conversion = resolveConversion(inputFile, options.to, options.from);
3414
+ const outPath = options.out || defaultOutputPath(inputFile, conversion.outputFormat);
3415
+ const data = await readFile2(inputFile);
3416
+ if (!output.isJson()) {
3417
+ output.info(`Converting ${basename2(inputFile)} to ${conversion.outputFormat}...`);
3418
+ }
3419
+ const result = await client.tools.convertFile({
3420
+ data: new Uint8Array(data),
3421
+ fileName: basename2(inputFile),
3422
+ type: conversion.type,
3423
+ inputFormat: conversion.inputFormat,
3424
+ outputFormat: conversion.outputFormat
3425
+ });
3426
+ await writeFile2(outPath, Buffer.from(await result.blob.arrayBuffer()));
3427
+ if (output.isJson()) {
3428
+ output.output({
3429
+ input: inputFile,
3430
+ output: outPath,
3431
+ jobId: result.jobId,
3432
+ mimeType: result.mimeType,
3433
+ conversion
3434
+ });
3435
+ return;
3436
+ }
3437
+ output.success(`Wrote ${outPath}`);
3438
+ });
3439
+ }
3440
+
3124
3441
  // src/index.ts
3125
3442
  init_output();
3126
3443
  init_config();
@@ -3133,7 +3450,7 @@ try {
3133
3450
  version = packageJson.version || version;
3134
3451
  } catch {
3135
3452
  }
3136
- var program = new Command9();
3453
+ var program = new Command10();
3137
3454
  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) => {
3138
3455
  const opts = typeof thisCommand.optsWithGlobals === "function" ? (
3139
3456
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -3146,6 +3463,7 @@ program.name("mdedit").description("MDEdit.ai CLI - Command-line interface for t
3146
3463
  if (opts.workspace) process.env.MDEDIT_WORKSPACE_ID = opts.workspace;
3147
3464
  if (opts.debug) process.env.MDEDIT_DEBUG = "1";
3148
3465
  });
3466
+ program.addCommand(createDocumentCommands());
3149
3467
  program.addCommand(createArticleCommands());
3150
3468
  program.addCommand(createWorkspaceCommands());
3151
3469
  program.addCommand(createFolderCommands());
@@ -3155,6 +3473,7 @@ program.addCommand(createSkillCommands());
3155
3473
  program.addCommand(createReviewCommands());
3156
3474
  program.addCommand(createSuggestCommand());
3157
3475
  program.addCommand(createAuthCommands());
3476
+ program.addCommand(createConvertCommands());
3158
3477
  program.command("health").description("Check API health status").action(async () => {
3159
3478
  const base = getApiBaseUrlRoot();
3160
3479
  const response = await fetch(`${base}/health`, { method: "GET" });
@@ -3257,7 +3576,7 @@ async function main() {
3257
3576
  } else {
3258
3577
  output.error(`API request failed (${err.status}): ${err.message}`);
3259
3578
  if (details?.requiredScope === "articles:write") {
3260
- output.info("Hint: accepting a suggestion changes article text and requires an API key with articles:write.");
3579
+ output.info("Hint: accepting a suggestion changes document text and requires an API key with articles:write.");
3261
3580
  } else if (err.status === 403) {
3262
3581
  output.info("Hint: review keys need articles:read,reviews:write; accepting suggestions additionally needs articles:write.");
3263
3582
  }
@@ -3270,6 +3589,10 @@ async function main() {
3270
3589
  } else if (err.status === 403) {
3271
3590
  if (err.message.includes("publishing:write")) {
3272
3591
  output.info("Hint: publishing requires an API key with publishing:write scope.");
3592
+ } else if (err.message.includes("conversions:execute")) {
3593
+ output.info("Hint: converting requires an API key with conversions:execute scope.");
3594
+ } else if (/quota|Quota/.test(err.message)) {
3595
+ output.info("Hint: the conversion quota for this plan is spent. It resets at the start of the next period.");
3273
3596
  } else {
3274
3597
  output.info("Hint: check that the API key has the required scope and permission for this workspace/resource.");
3275
3598
  }