mdedit-cli 0.4.18 → 0.5.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
@@ -10,6 +10,48 @@ var __export = (target, all) => {
10
10
  };
11
11
 
12
12
  // ../sdk/dist/index.js
13
+ function parseClientUpdateRequiredBody(status, body) {
14
+ if (status !== CLIENT_UPDATE_REQUIRED_STATUS || !body || typeof body !== "object") return null;
15
+ const root = body;
16
+ const error = root.error && typeof root.error === "object" ? root.error : root;
17
+ if (error.code !== CLIENT_UPDATE_REQUIRED_CODE) return null;
18
+ const details = error.details && typeof error.details === "object" ? error.details : {};
19
+ return {
20
+ source: "api",
21
+ client: asString(details.client),
22
+ clientVersion: asString(details.clientVersion),
23
+ minimumVersion: asString(details.minimumVersion)
24
+ };
25
+ }
26
+ function reportClientUpdateRequired(info) {
27
+ const next = current ? {
28
+ ...current,
29
+ // Keep the most informative values: the socket refusal carries no versions.
30
+ client: info.client ?? current.client,
31
+ clientVersion: info.clientVersion ?? current.clientVersion,
32
+ minimumVersion: info.minimumVersion ?? current.minimumVersion
33
+ } : { ...info };
34
+ if (current && current.client === next.client && current.clientVersion === next.clientVersion && current.minimumVersion === next.minimumVersion) {
35
+ return;
36
+ }
37
+ current = next;
38
+ listeners.forEach((listener) => {
39
+ try {
40
+ listener(next);
41
+ } catch {
42
+ }
43
+ });
44
+ }
45
+ async function detectClientUpdateRequired(response) {
46
+ if (!response || response.status !== CLIENT_UPDATE_REQUIRED_STATUS) return;
47
+ try {
48
+ const source = typeof response.clone === "function" ? response.clone() : response;
49
+ const body = await source.json();
50
+ const info = parseClientUpdateRequiredBody(response.status, body);
51
+ if (info) reportClientUpdateRequired(info);
52
+ } catch {
53
+ }
54
+ }
13
55
  async function parseMutationJson(response, options) {
14
56
  const body = await response.json();
15
57
  options?.onResponseMetadata?.({
@@ -27,7 +69,7 @@ function createFetchers(config) {
27
69
  const getAuthHeaders = config.getAuthHeaders;
28
70
  const customFetch = async (input, init) => {
29
71
  const authHeaders = await getAuthHeaders?.() ?? {};
30
- return fetch(`${baseUrlV1}${input}`, {
72
+ const response = await fetch(`${baseUrlV1}${input}`, {
31
73
  ...init,
32
74
  signal: init?.signal ?? config.signal,
33
75
  headers: {
@@ -38,10 +80,12 @@ function createFetchers(config) {
38
80
  }
39
81
  }
40
82
  });
83
+ await detectClientUpdateRequired(response);
84
+ return response;
41
85
  };
42
86
  const customFetchV22 = async (input, init) => {
43
87
  const authHeaders = await getAuthHeaders?.() ?? {};
44
- return fetch(`${baseUrlV2}${input}`, {
88
+ const response = await fetch(`${baseUrlV2}${input}`, {
45
89
  ...init,
46
90
  signal: init?.signal ?? config.signal,
47
91
  headers: {
@@ -52,6 +96,8 @@ function createFetchers(config) {
52
96
  }
53
97
  }
54
98
  });
99
+ await detectClientUpdateRequired(response);
100
+ return response;
55
101
  };
56
102
  return { customFetch, customFetchV2: customFetchV22, signal: config.signal };
57
103
  }
@@ -238,16 +284,6 @@ async function convertFile(input, fetchers) {
238
284
  deadline.dispose();
239
285
  }
240
286
  }
241
- async function fetchErrorFromResponse(prefix, response) {
242
- const text = await response.text();
243
- let data;
244
- try {
245
- data = JSON.parse(text);
246
- } catch {
247
- data = void 0;
248
- }
249
- return new errors_default(`${prefix}. ${text}`, response.status, data);
250
- }
251
287
  async function checkpointCollaboration(workspaceId, articleId, requestOrFetchers = {}, suppliedFetchers) {
252
288
  const legacyFetchers = "customFetchV2" in requestOrFetchers ? requestOrFetchers : void 0;
253
289
  const request = legacyFetchers ? {} : requestOrFetchers;
@@ -323,13 +359,6 @@ function createSdkClient(config) {
323
359
  delete: async (workspaceId, articleId, options) => {
324
360
  await withFetchError(() => deleteArticle(workspaceId, articleId, fetchers, options));
325
361
  },
326
- saveContent: (workspaceId, articleId, content, options) => withFetchError(() => saveArticleContent(
327
- workspaceId,
328
- articleId,
329
- content,
330
- options ? { ...options, request: { idempotencyKey: options.idempotencyKey } } : options,
331
- fetchers
332
- )),
333
362
  exportZip: (workspaceId, articleId) => withFetchError(() => exportArticleZip(workspaceId, articleId, fetchers)),
334
363
  presentation: (workspaceId, articleId) => withFetchError(() => getArticlePresentation(workspaceId, articleId, fetchers)),
335
364
  startExport: (workspaceId, articleId, format) => withFetchError(() => createArticleExportJob(workspaceId, articleId, format, fetchers)),
@@ -373,10 +402,15 @@ function createSdkClient(config) {
373
402
  }
374
403
  };
375
404
  }
376
- var _defaultFetchers, customFetchV2, FetchError, errors_default, createArticle, applyArticleEditCommands, updateArticle, getArticles, getArticlesByFolder, getArticle, getArticlePresentation, getArticleAssetDownloadUrls, getArticleMediaProxyUrls, getArticleSafeGists, deleteArticle, exportArticleZip, createArticleExportJob, ApiError, DEFAULT_POLL_INTERVAL_MS, DEFAULT_TIMEOUT_MS, sleep, saveArticleContent, workspaceFetchError, getWorkspaces, createWorkspace, updateWorkspace, deleteWorkspace, cancelWorkspaceDeletion, getWorkspace, normalizeTimestampMs, readFolderErrorMessage, normalizeFolder, createFolder, updateFolder, getFolders, getFolder, deleteFolder, sleep2, isRetriableStatus, withRetries, listApiKeys, createApiKey, revokeApiKey, publishArticle, unpublishArticle, getPublishStatus, updatePublishedArticle, FetchError2;
405
+ var CLIENT_UPDATE_REQUIRED_CODE, CLIENT_UPDATE_REQUIRED_STATUS, current, listeners, asString, _defaultFetchers, customFetchV2, FetchError, errors_default, createArticle, applyArticleEditCommands, updateArticle, getArticles, getArticlesByFolder, getArticle, getArticlePresentation, getArticleAssetDownloadUrls, getArticleMediaProxyUrls, getArticleSafeGists, deleteArticle, exportArticleZip, createArticleExportJob, ApiError, DEFAULT_POLL_INTERVAL_MS, DEFAULT_TIMEOUT_MS, sleep, workspaceFetchError, getWorkspaces, createWorkspace, updateWorkspace, deleteWorkspace, cancelWorkspaceDeletion, getWorkspace, normalizeTimestampMs, readFolderErrorMessage, normalizeFolder, createFolder, updateFolder, getFolders, getFolder, deleteFolder, sleep2, isRetriableStatus, withRetries, listApiKeys, createApiKey, revokeApiKey, publishArticle, unpublishArticle, getPublishStatus, updatePublishedArticle, FetchError2;
377
406
  var init_dist = __esm({
378
407
  "../sdk/dist/index.js"() {
379
408
  "use strict";
409
+ CLIENT_UPDATE_REQUIRED_CODE = "CLIENT_UPDATE_REQUIRED";
410
+ CLIENT_UPDATE_REQUIRED_STATUS = 426;
411
+ current = null;
412
+ listeners = /* @__PURE__ */ new Set();
413
+ asString = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
380
414
  _defaultFetchers = null;
381
415
  customFetchV2 = (input, init) => getDefaultFetchers().customFetchV2(input, init);
382
416
  FetchError = class extends Error {
@@ -404,7 +438,11 @@ var init_dist = __esm({
404
438
  folderId: articleRequest.folderId,
405
439
  collaborative: articleRequest.collaborative ?? false,
406
440
  articleSettings: articleRequest.articleSettings,
407
- tags: articleRequest.tags
441
+ tags: articleRequest.tags,
442
+ // Phase 3: only sent when set, so package creates are byte-identical to before.
443
+ ...articleRequest.storage !== void 0 ? { storage: articleRequest.storage } : {},
444
+ ...articleRequest.yjsGenesis !== void 0 ? { yjsGenesis: articleRequest.yjsGenesis } : {},
445
+ ...articleRequest.content !== void 0 ? { content: articleRequest.content } : {}
408
446
  })
409
447
  });
410
448
  if (!response.ok) {
@@ -456,9 +494,6 @@ var init_dist = __esm({
456
494
  if (articleRequest.wordCount !== void 0) {
457
495
  body.wordCount = articleRequest.wordCount;
458
496
  }
459
- if (articleRequest.contentHash !== void 0) {
460
- body.contentHash = articleRequest.contentHash;
461
- }
462
497
  if (articleRequest.baseArticleRevision !== void 0) {
463
498
  body.baseArticleRevision = articleRequest.baseArticleRevision;
464
499
  }
@@ -639,73 +674,6 @@ var init_dist = __esm({
639
674
  };
640
675
  signal?.addEventListener("abort", onAbort, { once: true });
641
676
  });
642
- saveArticleContent = async (workspaceId, articleId, content, optionsOrFetchers, fetchers) => {
643
- const maybeFetchers = optionsOrFetchers && "customFetchV2" in optionsOrFetchers ? optionsOrFetchers : fetchers;
644
- const options = optionsOrFetchers && !("customFetchV2" in optionsOrFetchers) ? optionsOrFetchers : void 0;
645
- const fetchV2 = maybeFetchers?.customFetchV2 ?? customFetchV2;
646
- const urlResponse = await fetchV2(
647
- `/workspaces/${workspaceId}/articles/${articleId}/content-upload-url`,
648
- {
649
- method: "POST",
650
- ...options ? {
651
- body: JSON.stringify({
652
- uploadId: `${options.baseContentRevision}-${options.contentHash}`,
653
- baseContentRevision: options.baseContentRevision,
654
- baseContentHash: options.baseContentHash,
655
- contentHash: options.contentHash,
656
- contentLength: new TextEncoder().encode(content).byteLength
657
- })
658
- } : {}
659
- }
660
- );
661
- if (!urlResponse.ok) {
662
- throw await fetchErrorFromResponse("Error getting upload URL", urlResponse);
663
- }
664
- const { uploadUrl, uploadId } = await urlResponse.json();
665
- if (!uploadUrl) {
666
- throw new errors_default("No upload URL returned", 500);
667
- }
668
- const uploadResponse = await fetch(uploadUrl, {
669
- method: "PUT",
670
- headers: { "Content-Type": "text/markdown" },
671
- body: content,
672
- signal: maybeFetchers?.signal
673
- });
674
- if (!uploadResponse.ok) {
675
- throw await fetchErrorFromResponse("Error uploading content to S3", uploadResponse);
676
- }
677
- if (!options) {
678
- return;
679
- }
680
- if (!uploadId) {
681
- throw new errors_default("No uploadId returned for conditional content upload", 500);
682
- }
683
- const commitResponse = await fetchV2(
684
- `/workspaces/${workspaceId}/articles/${articleId}/content-commit`,
685
- {
686
- method: "POST",
687
- headers: mutationHeaders(options.request),
688
- body: JSON.stringify({
689
- uploadId,
690
- baseContentRevision: options.baseContentRevision,
691
- baseContentHash: options.baseContentHash,
692
- contentHash: options.contentHash,
693
- title: options.title,
694
- preview: options.preview,
695
- wordCount: options.wordCount,
696
- folderId: options.folderId,
697
- isPinned: options.isPinned,
698
- isArchived: options.isArchived,
699
- articleSettings: options.articleSettings,
700
- tags: options.tags
701
- })
702
- }
703
- );
704
- if (!commitResponse.ok) {
705
- throw await fetchErrorFromResponse("Error committing article content", commitResponse);
706
- }
707
- return commitResponse.json();
708
- };
709
677
  workspaceFetchError = async (action, response) => {
710
678
  const text = await response.text();
711
679
  let data;
@@ -1554,15 +1522,15 @@ var init_dist2 = __esm({
1554
1522
  await this.logout(profile);
1555
1523
  }
1556
1524
  }
1557
- async refresh(profile, current) {
1525
+ async refresh(profile, current2) {
1558
1526
  const replacement = await this.tokenRequest(new URLSearchParams({
1559
1527
  client_id: this.configuration.clientId,
1560
1528
  grant_type: "refresh_token",
1561
- refresh_token: current.refreshToken,
1529
+ refresh_token: current2.refreshToken,
1562
1530
  resource: this.configuration.resource
1563
1531
  }), "OAUTH_REFRESH_FAILED", {
1564
- refreshToken: current.refreshToken,
1565
- scopes: current.scope
1532
+ refreshToken: current2.refreshToken,
1533
+ scopes: current2.scope
1566
1534
  });
1567
1535
  await this.credentialStore.set(profile, replacement);
1568
1536
  return replacement;
@@ -2281,9 +2249,8 @@ function createDocumentCommand(commandName, deprecated) {
2281
2249
  output.output(presentArticleDetails(result));
2282
2250
  output.info(`Hint: use \`${commandPath} get <documentId> --content-only\` to print markdown, or \`--include-content\` to include it in the output.`);
2283
2251
  });
2284
- 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) => {
2252
+ 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", "Mark the document as shared (collaborative); every document is edited live either way").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) => {
2285
2253
  requireAuthentication();
2286
- const credentialProvider = getAgentCredentialProvider();
2287
2254
  const client = getApiClient();
2288
2255
  const workspaceId = requireWorkspaceId(options.workspace);
2289
2256
  if (options.content !== void 0 && options.file !== void 0) {
@@ -2316,58 +2283,10 @@ function createDocumentCommand(commandName, deprecated) {
2316
2283
  articleId,
2317
2284
  title: String(title),
2318
2285
  folderId: options.folder ?? null,
2319
- collaborative: Boolean(options.collaborative)
2286
+ collaborative: Boolean(options.collaborative),
2287
+ storage: "yjs",
2288
+ ...contentText !== null ? { content: contentText } : {}
2320
2289
  });
2321
- if (contentText !== null) {
2322
- try {
2323
- if (options.collaborative) {
2324
- const session = await openArticleSession({
2325
- credentialProvider,
2326
- workspaceId,
2327
- articleId,
2328
- agent: { name: "mdedit-cli" },
2329
- apiUrl: getApiUrlRaw()
2330
- });
2331
- try {
2332
- const currentContent = session.read();
2333
- await session.edit([{
2334
- type: "replace",
2335
- anchor: { range: { from: 0, to: currentContent.length } },
2336
- text: contentText
2337
- }]);
2338
- const receipt = await session.ensureDurable();
2339
- const expectedContentHash = sha256Hex(contentText);
2340
- if (receipt.contentHash !== expectedContentHash) {
2341
- throw new Error("Collaborative content durability receipt did not match the created content.");
2342
- }
2343
- } finally {
2344
- await session.close();
2345
- }
2346
- } else {
2347
- await client.article.saveContent(workspaceId, articleId, contentText, {
2348
- baseContentRevision: 0,
2349
- contentHash: sha256Hex(contentText),
2350
- title: String(title),
2351
- folderId: options.folder ?? null
2352
- });
2353
- }
2354
- } catch (contentError) {
2355
- let compensated = false;
2356
- let compensationError;
2357
- try {
2358
- await client.article.delete(workspaceId, articleId);
2359
- compensated = true;
2360
- } catch (error) {
2361
- compensationError = error;
2362
- }
2363
- throw new ArticleCreateContentError({
2364
- articleId,
2365
- compensated,
2366
- contentError,
2367
- compensationError
2368
- });
2369
- }
2370
- }
2371
2290
  output.success("Document created successfully");
2372
2291
  if (contentText !== null) output.success("Document content uploaded");
2373
2292
  if (!options.publish) {
@@ -2406,25 +2325,32 @@ function createDocumentCommand(commandName, deprecated) {
2406
2325
  let contentText = null;
2407
2326
  if (options.content !== void 0) contentText = options.content;
2408
2327
  else if (options.file) contentText = await readContentFromFile(options.file);
2409
- if (contentText === null && Object.keys(body).length > 0) {
2410
- const result = await client.article.update(workspaceId, { articleId, ...body });
2411
- output.success("Document updated successfully");
2412
- output.output(result);
2413
- }
2328
+ let contentResult;
2414
2329
  if (contentText !== null) {
2415
2330
  const remoteArticle = await client.article.get(workspaceId, articleId);
2416
- const baseContentHash = remoteArticle?.contentHashAlg === "sha256" && remoteArticle?.contentHash ? remoteArticle.contentHash : sha256Hex(remoteArticle?.content || "");
2417
- const result = await client.article.saveContent(workspaceId, articleId, contentText, {
2418
- baseContentRevision: remoteArticle?.contentRevision ?? 0,
2419
- baseContentHash,
2420
- contentHash: sha256Hex(contentText),
2421
- title: body.title,
2422
- isArchived: body.isArchived,
2423
- isPinned: body.isPinned
2331
+ const current2 = String(remoteArticle?.content ?? "");
2332
+ contentResult = await client.article.editCommands(workspaceId, articleId, {
2333
+ commandId: `cli-update-${uuidv4()}`,
2334
+ operations: [{ type: "replace", anchor: { range: { from: 0, to: current2.length } }, text: contentText }],
2335
+ ifContentHash: sha256Hex(current2)
2424
2336
  });
2425
2337
  output.success("Document content updated");
2426
- output.output(result);
2427
2338
  }
2339
+ if (Object.keys(body).length > 0) {
2340
+ let result;
2341
+ try {
2342
+ result = await client.article.update(workspaceId, { articleId, ...body });
2343
+ } catch (error) {
2344
+ if (contentText === null) throw error;
2345
+ const message = error instanceof Error ? error.message : String(error);
2346
+ throw new Error(
2347
+ `Document ${articleId}: the content was updated, but updating ${Object.keys(body).join(", ")} failed: ${message}`
2348
+ );
2349
+ }
2350
+ output.success("Document updated successfully");
2351
+ if (contentText === null) output.output(result);
2352
+ }
2353
+ if (contentText !== null) output.output(contentResult);
2428
2354
  if (Object.keys(body).length === 0 && contentText === null) {
2429
2355
  output.warning("No changes provided. Use --title, --archive, --pin, --file, or --content.");
2430
2356
  }