mdedit-cli 0.4.3 → 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";
@@ -3137,6 +3311,133 @@ function createAuthCommands(runtime = defaultRuntime) {
3137
3311
  return auth;
3138
3312
  }
3139
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
+
3140
3441
  // src/index.ts
3141
3442
  init_output();
3142
3443
  init_config();
@@ -3149,7 +3450,7 @@ try {
3149
3450
  version = packageJson.version || version;
3150
3451
  } catch {
3151
3452
  }
3152
- var program = new Command9();
3453
+ var program = new Command10();
3153
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) => {
3154
3455
  const opts = typeof thisCommand.optsWithGlobals === "function" ? (
3155
3456
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -3172,6 +3473,7 @@ program.addCommand(createSkillCommands());
3172
3473
  program.addCommand(createReviewCommands());
3173
3474
  program.addCommand(createSuggestCommand());
3174
3475
  program.addCommand(createAuthCommands());
3476
+ program.addCommand(createConvertCommands());
3175
3477
  program.command("health").description("Check API health status").action(async () => {
3176
3478
  const base = getApiBaseUrlRoot();
3177
3479
  const response = await fetch(`${base}/health`, { method: "GET" });
@@ -3287,6 +3589,10 @@ async function main() {
3287
3589
  } else if (err.status === 403) {
3288
3590
  if (err.message.includes("publishing:write")) {
3289
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.");
3290
3596
  } else {
3291
3597
  output.info("Hint: check that the API key has the required scope and permission for this workspace/resource.");
3292
3598
  }