mdedit-cli 0.2.2 → 0.3.1
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 +39 -0
- package/dist/index.js +1271 -744
- package/dist/index.js.map +1 -1
- package/openclaw.json +36 -1
- package/package.json +4 -3
- package/skill.md +8 -0
package/dist/index.js
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __esm = (fn, res) => function __init() {
|
|
5
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
6
|
+
};
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
8
11
|
|
|
9
12
|
// ../sdk/dist/index.js
|
|
10
|
-
var _defaultFetchers = null;
|
|
11
13
|
function createFetchers(config) {
|
|
12
14
|
const baseUrlV1 = (config.baseUrlV1 ?? "").replace(/\/$/, "");
|
|
13
15
|
const baseUrlV2 = (config.baseUrlV2 ?? "").replace(/\/$/, "");
|
|
@@ -16,6 +18,7 @@ function createFetchers(config) {
|
|
|
16
18
|
const authHeaders = await getAuthHeaders?.() ?? {};
|
|
17
19
|
return fetch(`${baseUrlV1}${input}`, {
|
|
18
20
|
...init,
|
|
21
|
+
signal: init?.signal ?? config.signal,
|
|
19
22
|
headers: {
|
|
20
23
|
...init?.headers,
|
|
21
24
|
...authHeaders,
|
|
@@ -29,6 +32,7 @@ function createFetchers(config) {
|
|
|
29
32
|
const authHeaders = await getAuthHeaders?.() ?? {};
|
|
30
33
|
return fetch(`${baseUrlV2}${input}`, {
|
|
31
34
|
...init,
|
|
35
|
+
signal: init?.signal ?? config.signal,
|
|
32
36
|
headers: {
|
|
33
37
|
...init?.headers,
|
|
34
38
|
...authHeaders,
|
|
@@ -38,7 +42,7 @@ function createFetchers(config) {
|
|
|
38
42
|
}
|
|
39
43
|
});
|
|
40
44
|
};
|
|
41
|
-
return { customFetch, customFetchV2: customFetchV22 };
|
|
45
|
+
return { customFetch, customFetchV2: customFetchV22, signal: config.signal };
|
|
42
46
|
}
|
|
43
47
|
function getDefaultFetchers() {
|
|
44
48
|
if (_defaultFetchers) return _defaultFetchers;
|
|
@@ -46,164 +50,6 @@ function getDefaultFetchers() {
|
|
|
46
50
|
"MDEdit API client is not initialized. Call initApiClient(config) at app bootstrap (e.g. pages/_app.jsx) before using API functions."
|
|
47
51
|
);
|
|
48
52
|
}
|
|
49
|
-
var customFetchV2 = (input, init) => getDefaultFetchers().customFetchV2(input, init);
|
|
50
|
-
var FetchError = class extends Error {
|
|
51
|
-
name;
|
|
52
|
-
type;
|
|
53
|
-
status;
|
|
54
|
-
data;
|
|
55
|
-
constructor(message, type, data) {
|
|
56
|
-
super(message);
|
|
57
|
-
this.name = "FetchError";
|
|
58
|
-
this.type = type;
|
|
59
|
-
this.status = typeof type === "number" ? type : 500;
|
|
60
|
-
this.data = data;
|
|
61
|
-
}
|
|
62
|
-
};
|
|
63
|
-
var errors_default = FetchError;
|
|
64
|
-
var createArticle = async (workspaceId, articleRequest, fetchers) => {
|
|
65
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
66
|
-
const response = await fetchV2(`/workspaces/${workspaceId}/articles`, {
|
|
67
|
-
method: "POST",
|
|
68
|
-
body: JSON.stringify({
|
|
69
|
-
articleId: articleRequest.articleId,
|
|
70
|
-
title: articleRequest.title,
|
|
71
|
-
folderId: articleRequest.folderId,
|
|
72
|
-
collaborative: articleRequest.collaborative ?? false,
|
|
73
|
-
articleSettings: articleRequest.articleSettings
|
|
74
|
-
})
|
|
75
|
-
});
|
|
76
|
-
if (!response.ok) {
|
|
77
|
-
const errorText = await response.text();
|
|
78
|
-
let errorData;
|
|
79
|
-
try {
|
|
80
|
-
errorData = JSON.parse(errorText);
|
|
81
|
-
} catch {
|
|
82
|
-
throw new errors_default(`Error creating article. ${errorText}`, response.status);
|
|
83
|
-
}
|
|
84
|
-
if (errorData.error && errorData.error.type === "QUOTA_EXCEEDED") {
|
|
85
|
-
const quotaError = new errors_default(`Error creating article. ${errorText}`, response.status);
|
|
86
|
-
quotaError.error = errorData.error;
|
|
87
|
-
throw quotaError;
|
|
88
|
-
}
|
|
89
|
-
throw new errors_default(`Error creating article. ${errorText}`, response.status);
|
|
90
|
-
}
|
|
91
|
-
return response.json();
|
|
92
|
-
};
|
|
93
|
-
var updateArticle = async (workspaceId, articleRequest, fetchers) => {
|
|
94
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
95
|
-
const body = {
|
|
96
|
-
title: articleRequest.title,
|
|
97
|
-
isPinned: articleRequest.isPinned,
|
|
98
|
-
isArchived: articleRequest.isArchived,
|
|
99
|
-
articleSettings: articleRequest.articleSettings
|
|
100
|
-
};
|
|
101
|
-
if (articleRequest.folderId !== void 0) {
|
|
102
|
-
body.folderId = articleRequest.folderId;
|
|
103
|
-
}
|
|
104
|
-
if (articleRequest.preview) {
|
|
105
|
-
body.preview = articleRequest.preview;
|
|
106
|
-
}
|
|
107
|
-
if (articleRequest.wordCount !== void 0) {
|
|
108
|
-
body.wordCount = articleRequest.wordCount;
|
|
109
|
-
}
|
|
110
|
-
if (articleRequest.contentHash !== void 0) {
|
|
111
|
-
body.contentHash = articleRequest.contentHash;
|
|
112
|
-
}
|
|
113
|
-
if (articleRequest.baseArticleRevision !== void 0) {
|
|
114
|
-
body.baseArticleRevision = articleRequest.baseArticleRevision;
|
|
115
|
-
}
|
|
116
|
-
const response = await fetchV2(
|
|
117
|
-
`/workspaces/${workspaceId}/articles/${articleRequest.articleId}`,
|
|
118
|
-
{
|
|
119
|
-
method: "PUT",
|
|
120
|
-
body: JSON.stringify(body)
|
|
121
|
-
}
|
|
122
|
-
);
|
|
123
|
-
if (!response.ok) {
|
|
124
|
-
const errorText = await response.text();
|
|
125
|
-
let errorData;
|
|
126
|
-
try {
|
|
127
|
-
errorData = JSON.parse(errorText);
|
|
128
|
-
} catch {
|
|
129
|
-
throw new errors_default(`Error updating article metadata. ${errorText}`, response.status);
|
|
130
|
-
}
|
|
131
|
-
if (errorData.error && errorData.error.type === "QUOTA_EXCEEDED") {
|
|
132
|
-
const quotaError = new errors_default(
|
|
133
|
-
`Error updating article metadata. ${errorText}`,
|
|
134
|
-
response.status
|
|
135
|
-
);
|
|
136
|
-
quotaError.error = errorData.error;
|
|
137
|
-
throw quotaError;
|
|
138
|
-
}
|
|
139
|
-
throw new errors_default(`Error updating article metadata. ${errorText}`, response.status, errorData);
|
|
140
|
-
}
|
|
141
|
-
return response.json();
|
|
142
|
-
};
|
|
143
|
-
var getArticles = async (workspaceId, fetchers) => {
|
|
144
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
145
|
-
const response = await fetchV2(`/workspaces/${workspaceId}/articles`);
|
|
146
|
-
if (!response.ok) {
|
|
147
|
-
const errorText = await response.text();
|
|
148
|
-
const looksLikeWorkspaceAccessDenied = response.status === 403 && errorText.toLowerCase().includes("access denied to workspace");
|
|
149
|
-
if (looksLikeWorkspaceAccessDenied) {
|
|
150
|
-
throw new errors_default(`Error fetching articles. ${errorText}`, response.status);
|
|
151
|
-
}
|
|
152
|
-
throw new errors_default(`Error fetching articles. ${errorText}`, response.status);
|
|
153
|
-
}
|
|
154
|
-
return response.json();
|
|
155
|
-
};
|
|
156
|
-
var getArticlesByFolder = async (workspaceId, folderId, fetchers) => {
|
|
157
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
158
|
-
const qs = `?folderId=${encodeURIComponent(folderId)}`;
|
|
159
|
-
const response = await fetchV2(`/workspaces/${workspaceId}/articles${qs}`);
|
|
160
|
-
if (!response.ok) {
|
|
161
|
-
const errorText = await response.text();
|
|
162
|
-
throw new errors_default(`Error fetching articles. ${errorText}`, response.status);
|
|
163
|
-
}
|
|
164
|
-
return response.json();
|
|
165
|
-
};
|
|
166
|
-
var getArticle = async (workspaceId, articleId, fetchers) => {
|
|
167
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
168
|
-
const response = await fetchV2(
|
|
169
|
-
`/workspaces/${workspaceId}/articles/${articleId}`
|
|
170
|
-
);
|
|
171
|
-
if (!response.ok) {
|
|
172
|
-
throw new errors_default(
|
|
173
|
-
`Error fetching article. ${await response.text()}`,
|
|
174
|
-
response.status
|
|
175
|
-
);
|
|
176
|
-
}
|
|
177
|
-
return response.json();
|
|
178
|
-
};
|
|
179
|
-
var deleteArticle = async (workspaceId, articleId, fetchers) => {
|
|
180
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
181
|
-
const response = await fetchV2(
|
|
182
|
-
`/workspaces/${workspaceId}/articles/${articleId}`,
|
|
183
|
-
{ method: "DELETE" }
|
|
184
|
-
);
|
|
185
|
-
if (!response.ok) {
|
|
186
|
-
throw new errors_default(
|
|
187
|
-
`Error deleting article. ${await response.text()}`,
|
|
188
|
-
response.status
|
|
189
|
-
);
|
|
190
|
-
}
|
|
191
|
-
return true;
|
|
192
|
-
};
|
|
193
|
-
var exportArticleZip = async (workspaceId, articleId, fetchers) => {
|
|
194
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
195
|
-
const response = await fetchV2(
|
|
196
|
-
`/workspaces/${workspaceId}/articles/${articleId}/export/zip`,
|
|
197
|
-
{ method: "GET" }
|
|
198
|
-
);
|
|
199
|
-
if (!response.ok) {
|
|
200
|
-
throw new errors_default(
|
|
201
|
-
`Failed to export article ZIP. ${await response.text()}`,
|
|
202
|
-
response.status
|
|
203
|
-
);
|
|
204
|
-
}
|
|
205
|
-
return response.blob();
|
|
206
|
-
};
|
|
207
53
|
async function fetchErrorFromResponse(prefix, response) {
|
|
208
54
|
const text = await response.text();
|
|
209
55
|
let data;
|
|
@@ -214,329 +60,6 @@ async function fetchErrorFromResponse(prefix, response) {
|
|
|
214
60
|
}
|
|
215
61
|
return new errors_default(`${prefix}. ${text}`, response.status, data);
|
|
216
62
|
}
|
|
217
|
-
var saveArticleContent = async (workspaceId, articleId, content, optionsOrFetchers, fetchers) => {
|
|
218
|
-
const maybeFetchers = optionsOrFetchers && "customFetchV2" in optionsOrFetchers ? optionsOrFetchers : fetchers;
|
|
219
|
-
const options = optionsOrFetchers && !("customFetchV2" in optionsOrFetchers) ? optionsOrFetchers : void 0;
|
|
220
|
-
const fetchV2 = maybeFetchers?.customFetchV2 ?? customFetchV2;
|
|
221
|
-
const urlResponse = await fetchV2(
|
|
222
|
-
`/workspaces/${workspaceId}/articles/${articleId}/content-upload-url`,
|
|
223
|
-
{
|
|
224
|
-
method: "POST",
|
|
225
|
-
...options ? {
|
|
226
|
-
body: JSON.stringify({
|
|
227
|
-
baseContentRevision: options.baseContentRevision,
|
|
228
|
-
baseContentHash: options.baseContentHash,
|
|
229
|
-
contentHash: options.contentHash,
|
|
230
|
-
contentLength: new TextEncoder().encode(content).byteLength
|
|
231
|
-
})
|
|
232
|
-
} : {}
|
|
233
|
-
}
|
|
234
|
-
);
|
|
235
|
-
if (!urlResponse.ok) {
|
|
236
|
-
throw await fetchErrorFromResponse("Error getting upload URL", urlResponse);
|
|
237
|
-
}
|
|
238
|
-
const { uploadUrl, uploadId } = await urlResponse.json();
|
|
239
|
-
if (!uploadUrl) {
|
|
240
|
-
throw new errors_default("No upload URL returned", 500);
|
|
241
|
-
}
|
|
242
|
-
const uploadResponse = await fetch(uploadUrl, {
|
|
243
|
-
method: "PUT",
|
|
244
|
-
headers: { "Content-Type": "text/markdown" },
|
|
245
|
-
body: content
|
|
246
|
-
});
|
|
247
|
-
if (!uploadResponse.ok) {
|
|
248
|
-
throw await fetchErrorFromResponse("Error uploading content to S3", uploadResponse);
|
|
249
|
-
}
|
|
250
|
-
if (!options) {
|
|
251
|
-
return;
|
|
252
|
-
}
|
|
253
|
-
if (!uploadId) {
|
|
254
|
-
throw new errors_default("No uploadId returned for conditional content upload", 500);
|
|
255
|
-
}
|
|
256
|
-
const commitResponse = await fetchV2(
|
|
257
|
-
`/workspaces/${workspaceId}/articles/${articleId}/content-commit`,
|
|
258
|
-
{
|
|
259
|
-
method: "POST",
|
|
260
|
-
body: JSON.stringify({
|
|
261
|
-
uploadId,
|
|
262
|
-
baseContentRevision: options.baseContentRevision,
|
|
263
|
-
baseContentHash: options.baseContentHash,
|
|
264
|
-
contentHash: options.contentHash,
|
|
265
|
-
title: options.title,
|
|
266
|
-
preview: options.preview,
|
|
267
|
-
wordCount: options.wordCount,
|
|
268
|
-
folderId: options.folderId,
|
|
269
|
-
isPinned: options.isPinned,
|
|
270
|
-
isArchived: options.isArchived,
|
|
271
|
-
articleSettings: options.articleSettings
|
|
272
|
-
})
|
|
273
|
-
}
|
|
274
|
-
);
|
|
275
|
-
if (!commitResponse.ok) {
|
|
276
|
-
throw await fetchErrorFromResponse("Error committing article content", commitResponse);
|
|
277
|
-
}
|
|
278
|
-
return commitResponse.json();
|
|
279
|
-
};
|
|
280
|
-
var getWorkspaces = async (fetchers) => {
|
|
281
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
282
|
-
const response = await fetchV2("/workspaces");
|
|
283
|
-
if (!response.ok) {
|
|
284
|
-
throw new errors_default(
|
|
285
|
-
`Error fetching workspaces. ${await response.text()}`,
|
|
286
|
-
response.status
|
|
287
|
-
);
|
|
288
|
-
}
|
|
289
|
-
return response.json();
|
|
290
|
-
};
|
|
291
|
-
var createWorkspace = async (request, fetchers) => {
|
|
292
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
293
|
-
const response = await fetchV2("/workspaces", {
|
|
294
|
-
method: "POST",
|
|
295
|
-
body: JSON.stringify(request)
|
|
296
|
-
});
|
|
297
|
-
if (!response.ok) {
|
|
298
|
-
throw new errors_default(
|
|
299
|
-
`Error creating workspace. ${await response.text()}`,
|
|
300
|
-
response.status
|
|
301
|
-
);
|
|
302
|
-
}
|
|
303
|
-
return response.json();
|
|
304
|
-
};
|
|
305
|
-
var updateWorkspace = async (workspaceId, request, fetchers) => {
|
|
306
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
307
|
-
const response = await fetchV2(`/workspaces/${workspaceId}`, {
|
|
308
|
-
method: "PUT",
|
|
309
|
-
body: JSON.stringify(request)
|
|
310
|
-
});
|
|
311
|
-
if (!response.ok) {
|
|
312
|
-
throw new errors_default(
|
|
313
|
-
`Error updating workspace. ${await response.text()}`,
|
|
314
|
-
response.status
|
|
315
|
-
);
|
|
316
|
-
}
|
|
317
|
-
return response.json();
|
|
318
|
-
};
|
|
319
|
-
var deleteWorkspace = async (workspaceId, fetchers) => {
|
|
320
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
321
|
-
const response = await fetchV2(`/workspaces/${workspaceId}`, {
|
|
322
|
-
method: "DELETE"
|
|
323
|
-
});
|
|
324
|
-
if (!response.ok) {
|
|
325
|
-
throw new errors_default(
|
|
326
|
-
`Error deleting workspace. ${await response.text()}`,
|
|
327
|
-
response.status
|
|
328
|
-
);
|
|
329
|
-
}
|
|
330
|
-
try {
|
|
331
|
-
return await response.json();
|
|
332
|
-
} catch {
|
|
333
|
-
return;
|
|
334
|
-
}
|
|
335
|
-
};
|
|
336
|
-
var getWorkspace = async (workspaceId, fetchers) => {
|
|
337
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
338
|
-
const response = await fetchV2(`/workspaces/${workspaceId}`);
|
|
339
|
-
if (!response.ok) {
|
|
340
|
-
throw new errors_default(
|
|
341
|
-
`Error fetching workspace. ${await response.text()}`,
|
|
342
|
-
response.status
|
|
343
|
-
);
|
|
344
|
-
}
|
|
345
|
-
return response.json();
|
|
346
|
-
};
|
|
347
|
-
var normalizeTimestampMs = (value) => {
|
|
348
|
-
const n = typeof value === "number" ? value : Number(value);
|
|
349
|
-
if (!Number.isFinite(n)) return Date.now();
|
|
350
|
-
return n < 1e12 ? n * 1e3 : n;
|
|
351
|
-
};
|
|
352
|
-
var normalizeFolder = (raw) => {
|
|
353
|
-
const id = raw?.id ?? raw?.folderId;
|
|
354
|
-
const parentId = raw?.parentId ?? raw?.parentFolderId ?? null;
|
|
355
|
-
const workspaceId = raw?.workspaceId;
|
|
356
|
-
const name = raw?.name ?? "";
|
|
357
|
-
if (!id || !workspaceId) {
|
|
358
|
-
throw new Error("Invalid folder payload from API: missing id or workspaceId");
|
|
359
|
-
}
|
|
360
|
-
if (!name || typeof name !== "string" || name.trim().length === 0) {
|
|
361
|
-
throw new Error("Invalid folder payload from API: name cannot be empty");
|
|
362
|
-
}
|
|
363
|
-
if (name.length > 255) {
|
|
364
|
-
throw new Error("Invalid folder payload from API: name exceeds 255 characters");
|
|
365
|
-
}
|
|
366
|
-
return {
|
|
367
|
-
id,
|
|
368
|
-
name: name.trim(),
|
|
369
|
-
parentId: parentId ?? null,
|
|
370
|
-
workspaceId,
|
|
371
|
-
createdAt: normalizeTimestampMs(raw?.createdAt),
|
|
372
|
-
updatedAt: normalizeTimestampMs(raw?.updatedAt),
|
|
373
|
-
...raw?.deletedAt ? { deletedAt: normalizeTimestampMs(raw?.deletedAt) } : {},
|
|
374
|
-
deletedBy: raw?.deletedBy,
|
|
375
|
-
color: raw?.color,
|
|
376
|
-
icon: raw?.icon,
|
|
377
|
-
order: raw?.order
|
|
378
|
-
};
|
|
379
|
-
};
|
|
380
|
-
var createFolder = async (workspaceId, folderRequest, fetchers) => {
|
|
381
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
382
|
-
const response = await fetchV2(`/workspaces/${workspaceId}/folders`, {
|
|
383
|
-
method: "POST",
|
|
384
|
-
body: JSON.stringify({
|
|
385
|
-
folderId: folderRequest.id,
|
|
386
|
-
id: folderRequest.id,
|
|
387
|
-
name: folderRequest.name,
|
|
388
|
-
parentId: folderRequest.parentId === null ? null : folderRequest.parentId ?? void 0
|
|
389
|
-
})
|
|
390
|
-
});
|
|
391
|
-
if (!response.ok) {
|
|
392
|
-
const errorText = await response.text();
|
|
393
|
-
throw new errors_default(`Error creating folder. ${errorText}`, response.status);
|
|
394
|
-
}
|
|
395
|
-
return normalizeFolder(await response.json());
|
|
396
|
-
};
|
|
397
|
-
var updateFolder = async (workspaceId, folderId, folderRequest, fetchers) => {
|
|
398
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
399
|
-
const response = await fetchV2(`/workspaces/${workspaceId}/folders/${folderId}`, {
|
|
400
|
-
method: "PUT",
|
|
401
|
-
body: JSON.stringify({
|
|
402
|
-
name: folderRequest.name,
|
|
403
|
-
parentId: folderRequest.parentId === null ? null : folderRequest.parentId ?? void 0
|
|
404
|
-
})
|
|
405
|
-
});
|
|
406
|
-
if (!response.ok) {
|
|
407
|
-
const errorText = await response.text();
|
|
408
|
-
throw new errors_default(`Error updating folder. ${errorText}`, response.status);
|
|
409
|
-
}
|
|
410
|
-
const result = await response.json();
|
|
411
|
-
try {
|
|
412
|
-
return normalizeFolder(result);
|
|
413
|
-
} catch {
|
|
414
|
-
return normalizeFolder({
|
|
415
|
-
...folderRequest,
|
|
416
|
-
id: folderId,
|
|
417
|
-
workspaceId,
|
|
418
|
-
parentId: folderRequest.parentId ?? null
|
|
419
|
-
});
|
|
420
|
-
}
|
|
421
|
-
};
|
|
422
|
-
var getFolders = async (workspaceId, options, fetchers) => {
|
|
423
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
424
|
-
const qs = options?.includeDeleted ? "?includeDeleted=true" : "";
|
|
425
|
-
const response = await fetchV2(`/workspaces/${workspaceId}/folders${qs}`);
|
|
426
|
-
if (!response.ok) {
|
|
427
|
-
const errorText = await response.text();
|
|
428
|
-
throw new errors_default(`Error fetching folders. ${errorText}`, response.status);
|
|
429
|
-
}
|
|
430
|
-
const folders = await response.json();
|
|
431
|
-
return Array.isArray(folders) ? folders.map(normalizeFolder) : [];
|
|
432
|
-
};
|
|
433
|
-
var getFolder = async (workspaceId, folderId, fetchers) => {
|
|
434
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
435
|
-
const response = await fetchV2(`/workspaces/${workspaceId}/folders/${folderId}`);
|
|
436
|
-
if (!response.ok) {
|
|
437
|
-
throw new errors_default(
|
|
438
|
-
`Error fetching folder. ${await response.text()}`,
|
|
439
|
-
response.status
|
|
440
|
-
);
|
|
441
|
-
}
|
|
442
|
-
return normalizeFolder(await response.json());
|
|
443
|
-
};
|
|
444
|
-
var deleteFolder = async (workspaceId, folderId, fetchers) => {
|
|
445
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
446
|
-
const response = await fetchV2(`/workspaces/${workspaceId}/folders/${folderId}`, {
|
|
447
|
-
method: "DELETE"
|
|
448
|
-
});
|
|
449
|
-
if (!response.ok) {
|
|
450
|
-
const errorText = await response.text();
|
|
451
|
-
throw new errors_default(`Error deleting folder. ${errorText}`, response.status);
|
|
452
|
-
}
|
|
453
|
-
return true;
|
|
454
|
-
};
|
|
455
|
-
var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
456
|
-
var isRetriableStatus = (status) => status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
|
|
457
|
-
var withRetries = async (fn, maxAttempts = 3) => {
|
|
458
|
-
let lastError;
|
|
459
|
-
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
460
|
-
try {
|
|
461
|
-
const response = await fn();
|
|
462
|
-
if (response.ok) return response;
|
|
463
|
-
if (attempt < maxAttempts && isRetriableStatus(response.status)) {
|
|
464
|
-
const backoffMs = 250 * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 150);
|
|
465
|
-
await sleep(backoffMs);
|
|
466
|
-
continue;
|
|
467
|
-
}
|
|
468
|
-
return response;
|
|
469
|
-
} catch (e) {
|
|
470
|
-
lastError = e;
|
|
471
|
-
if (attempt < maxAttempts) {
|
|
472
|
-
const backoffMs = 250 * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 150);
|
|
473
|
-
await sleep(backoffMs);
|
|
474
|
-
continue;
|
|
475
|
-
}
|
|
476
|
-
throw lastError;
|
|
477
|
-
}
|
|
478
|
-
}
|
|
479
|
-
throw lastError;
|
|
480
|
-
};
|
|
481
|
-
var listApiKeys = async (fetchers) => {
|
|
482
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
483
|
-
const response = await withRetries(() => fetchV2("/api-keys", { method: "GET" }), 3);
|
|
484
|
-
if (!response.ok) {
|
|
485
|
-
throw new Error(`Failed to list API keys: ${response.status} ${response.statusText}`);
|
|
486
|
-
}
|
|
487
|
-
return response.json();
|
|
488
|
-
};
|
|
489
|
-
var createApiKey = async (request, fetchers) => {
|
|
490
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
491
|
-
const response = await withRetries(
|
|
492
|
-
() => fetchV2("/api-keys", {
|
|
493
|
-
method: "POST",
|
|
494
|
-
body: JSON.stringify(request)
|
|
495
|
-
}),
|
|
496
|
-
3
|
|
497
|
-
);
|
|
498
|
-
if (!response.ok) {
|
|
499
|
-
throw new Error(`Failed to create API key: ${response.status} ${response.statusText}`);
|
|
500
|
-
}
|
|
501
|
-
return response.json();
|
|
502
|
-
};
|
|
503
|
-
var revokeApiKey = async (keyId, fetchers) => {
|
|
504
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
505
|
-
const response = await withRetries(
|
|
506
|
-
() => fetchV2(`/api-keys/${encodeURIComponent(keyId)}`, {
|
|
507
|
-
method: "DELETE"
|
|
508
|
-
}),
|
|
509
|
-
3
|
|
510
|
-
);
|
|
511
|
-
if (!response.ok) {
|
|
512
|
-
throw new Error(`Failed to revoke API key: ${response.status} ${response.statusText}`);
|
|
513
|
-
}
|
|
514
|
-
return response.json();
|
|
515
|
-
};
|
|
516
|
-
var checkpointCollaboration = async (workspaceId, articleId, fetchers) => {
|
|
517
|
-
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
518
|
-
const response = await fetchV2(
|
|
519
|
-
`/workspaces/${workspaceId}/articles/${articleId}/collaboration/checkpoint`,
|
|
520
|
-
{ method: "POST" }
|
|
521
|
-
);
|
|
522
|
-
if (!response.ok) {
|
|
523
|
-
throw new errors_default(
|
|
524
|
-
`Error checkpointing collaboration. ${await response.text()}`,
|
|
525
|
-
response.status
|
|
526
|
-
);
|
|
527
|
-
}
|
|
528
|
-
return response.json();
|
|
529
|
-
};
|
|
530
|
-
var FetchError2 = class extends Error {
|
|
531
|
-
status;
|
|
532
|
-
data;
|
|
533
|
-
constructor(message, status, data) {
|
|
534
|
-
super(message);
|
|
535
|
-
this.name = "FetchError";
|
|
536
|
-
this.status = status;
|
|
537
|
-
this.data = data;
|
|
538
|
-
}
|
|
539
|
-
};
|
|
540
63
|
function coerceToFetchError(err) {
|
|
541
64
|
const anyErr = err;
|
|
542
65
|
const status = typeof anyErr?.status === "number" ? anyErr.status : 500;
|
|
@@ -590,94 +113,658 @@ function createSdkClient(config) {
|
|
|
590
113
|
},
|
|
591
114
|
collaboration: {
|
|
592
115
|
checkpoint: (workspaceId, articleId) => withFetchError(() => checkpointCollaboration(workspaceId, articleId, fetchers))
|
|
116
|
+
},
|
|
117
|
+
publish: {
|
|
118
|
+
publish: (workspaceId, articleId, request = {}) => withFetchError(() => publishArticle(workspaceId, articleId, request, fetchers)),
|
|
119
|
+
status: (workspaceId, articleId) => withFetchError(() => getPublishStatus(workspaceId, articleId, fetchers)),
|
|
120
|
+
update: (workspaceId, articleId, request = {}) => withFetchError(() => updatePublishedArticle(workspaceId, articleId, request, fetchers)),
|
|
121
|
+
unpublish: (workspaceId, articleId) => withFetchError(() => unpublishArticle(workspaceId, articleId, fetchers))
|
|
593
122
|
}
|
|
594
123
|
};
|
|
595
124
|
}
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
125
|
+
var _defaultFetchers, customFetchV2, FetchError, errors_default, createArticle, updateArticle, getArticles, getArticlesByFolder, getArticle, deleteArticle, exportArticleZip, 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;
|
|
126
|
+
var init_dist = __esm({
|
|
127
|
+
"../sdk/dist/index.js"() {
|
|
128
|
+
"use strict";
|
|
129
|
+
_defaultFetchers = null;
|
|
130
|
+
customFetchV2 = (input, init) => getDefaultFetchers().customFetchV2(input, init);
|
|
131
|
+
FetchError = class extends Error {
|
|
132
|
+
name;
|
|
133
|
+
type;
|
|
134
|
+
status;
|
|
135
|
+
data;
|
|
136
|
+
constructor(message, type, data) {
|
|
137
|
+
super(message);
|
|
138
|
+
this.name = "FetchError";
|
|
139
|
+
this.type = type;
|
|
140
|
+
this.status = typeof type === "number" ? type : 500;
|
|
141
|
+
this.data = data;
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
errors_default = FetchError;
|
|
145
|
+
createArticle = async (workspaceId, articleRequest, fetchers) => {
|
|
146
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
147
|
+
const response = await fetchV2(`/workspaces/${workspaceId}/articles`, {
|
|
148
|
+
method: "POST",
|
|
149
|
+
body: JSON.stringify({
|
|
150
|
+
articleId: articleRequest.articleId,
|
|
151
|
+
title: articleRequest.title,
|
|
152
|
+
folderId: articleRequest.folderId,
|
|
153
|
+
collaborative: articleRequest.collaborative ?? false,
|
|
154
|
+
articleSettings: articleRequest.articleSettings
|
|
155
|
+
})
|
|
156
|
+
});
|
|
157
|
+
if (!response.ok) {
|
|
158
|
+
const errorText = await response.text();
|
|
159
|
+
let errorData;
|
|
160
|
+
try {
|
|
161
|
+
errorData = JSON.parse(errorText);
|
|
162
|
+
} catch {
|
|
163
|
+
throw new errors_default(`Error creating article. ${errorText}`, response.status);
|
|
164
|
+
}
|
|
165
|
+
if (errorData.error && errorData.error.type === "QUOTA_EXCEEDED") {
|
|
166
|
+
const quotaError = new errors_default(`Error creating article. ${errorText}`, response.status);
|
|
167
|
+
quotaError.error = errorData.error;
|
|
168
|
+
throw quotaError;
|
|
169
|
+
}
|
|
170
|
+
throw new errors_default(`Error creating article. ${errorText}`, response.status);
|
|
171
|
+
}
|
|
172
|
+
return response.json();
|
|
173
|
+
};
|
|
174
|
+
updateArticle = async (workspaceId, articleRequest, fetchers) => {
|
|
175
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
176
|
+
const body = {
|
|
177
|
+
title: articleRequest.title,
|
|
178
|
+
isPinned: articleRequest.isPinned,
|
|
179
|
+
isArchived: articleRequest.isArchived,
|
|
180
|
+
articleSettings: articleRequest.articleSettings
|
|
181
|
+
};
|
|
182
|
+
if (articleRequest.folderId !== void 0) {
|
|
183
|
+
body.folderId = articleRequest.folderId;
|
|
184
|
+
}
|
|
185
|
+
if (articleRequest.preview) {
|
|
186
|
+
body.preview = articleRequest.preview;
|
|
187
|
+
}
|
|
188
|
+
if (articleRequest.wordCount !== void 0) {
|
|
189
|
+
body.wordCount = articleRequest.wordCount;
|
|
190
|
+
}
|
|
191
|
+
if (articleRequest.contentHash !== void 0) {
|
|
192
|
+
body.contentHash = articleRequest.contentHash;
|
|
193
|
+
}
|
|
194
|
+
if (articleRequest.baseArticleRevision !== void 0) {
|
|
195
|
+
body.baseArticleRevision = articleRequest.baseArticleRevision;
|
|
196
|
+
}
|
|
197
|
+
const response = await fetchV2(
|
|
198
|
+
`/workspaces/${workspaceId}/articles/${articleRequest.articleId}`,
|
|
199
|
+
{
|
|
200
|
+
method: "PUT",
|
|
201
|
+
body: JSON.stringify(body)
|
|
202
|
+
}
|
|
203
|
+
);
|
|
204
|
+
if (!response.ok) {
|
|
205
|
+
const errorText = await response.text();
|
|
206
|
+
let errorData;
|
|
207
|
+
try {
|
|
208
|
+
errorData = JSON.parse(errorText);
|
|
209
|
+
} catch {
|
|
210
|
+
throw new errors_default(`Error updating article metadata. ${errorText}`, response.status);
|
|
211
|
+
}
|
|
212
|
+
if (errorData.error && errorData.error.type === "QUOTA_EXCEEDED") {
|
|
213
|
+
const quotaError = new errors_default(
|
|
214
|
+
`Error updating article metadata. ${errorText}`,
|
|
215
|
+
response.status
|
|
216
|
+
);
|
|
217
|
+
quotaError.error = errorData.error;
|
|
218
|
+
throw quotaError;
|
|
219
|
+
}
|
|
220
|
+
throw new errors_default(`Error updating article metadata. ${errorText}`, response.status, errorData);
|
|
221
|
+
}
|
|
222
|
+
return response.json();
|
|
223
|
+
};
|
|
224
|
+
getArticles = async (workspaceId, fetchers) => {
|
|
225
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
226
|
+
const response = await fetchV2(`/workspaces/${workspaceId}/articles`);
|
|
227
|
+
if (!response.ok) {
|
|
228
|
+
const errorText = await response.text();
|
|
229
|
+
const looksLikeWorkspaceAccessDenied = response.status === 403 && errorText.toLowerCase().includes("access denied to workspace");
|
|
230
|
+
if (looksLikeWorkspaceAccessDenied) {
|
|
231
|
+
throw new errors_default(`Error fetching articles. ${errorText}`, response.status);
|
|
232
|
+
}
|
|
233
|
+
throw new errors_default(`Error fetching articles. ${errorText}`, response.status);
|
|
234
|
+
}
|
|
235
|
+
return response.json();
|
|
236
|
+
};
|
|
237
|
+
getArticlesByFolder = async (workspaceId, folderId, fetchers) => {
|
|
238
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
239
|
+
const qs = `?folderId=${encodeURIComponent(folderId)}`;
|
|
240
|
+
const response = await fetchV2(`/workspaces/${workspaceId}/articles${qs}`);
|
|
241
|
+
if (!response.ok) {
|
|
242
|
+
const errorText = await response.text();
|
|
243
|
+
throw new errors_default(`Error fetching articles. ${errorText}`, response.status);
|
|
244
|
+
}
|
|
245
|
+
return response.json();
|
|
246
|
+
};
|
|
247
|
+
getArticle = async (workspaceId, articleId, fetchers) => {
|
|
248
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
249
|
+
const response = await fetchV2(
|
|
250
|
+
`/workspaces/${workspaceId}/articles/${articleId}`
|
|
251
|
+
);
|
|
252
|
+
if (!response.ok) {
|
|
253
|
+
throw new errors_default(
|
|
254
|
+
`Error fetching article. ${await response.text()}`,
|
|
255
|
+
response.status
|
|
256
|
+
);
|
|
257
|
+
}
|
|
258
|
+
return response.json();
|
|
259
|
+
};
|
|
260
|
+
deleteArticle = async (workspaceId, articleId, fetchers) => {
|
|
261
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
262
|
+
const response = await fetchV2(
|
|
263
|
+
`/workspaces/${workspaceId}/articles/${articleId}`,
|
|
264
|
+
{ method: "DELETE" }
|
|
265
|
+
);
|
|
266
|
+
if (!response.ok) {
|
|
267
|
+
throw new errors_default(
|
|
268
|
+
`Error deleting article. ${await response.text()}`,
|
|
269
|
+
response.status
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
return true;
|
|
273
|
+
};
|
|
274
|
+
exportArticleZip = async (workspaceId, articleId, fetchers) => {
|
|
275
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
276
|
+
const response = await fetchV2(
|
|
277
|
+
`/workspaces/${workspaceId}/articles/${articleId}/export/zip`,
|
|
278
|
+
{ method: "GET" }
|
|
279
|
+
);
|
|
280
|
+
if (!response.ok) {
|
|
281
|
+
throw new errors_default(
|
|
282
|
+
`Failed to export article ZIP. ${await response.text()}`,
|
|
283
|
+
response.status
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
return response.blob();
|
|
287
|
+
};
|
|
288
|
+
saveArticleContent = async (workspaceId, articleId, content, optionsOrFetchers, fetchers) => {
|
|
289
|
+
const maybeFetchers = optionsOrFetchers && "customFetchV2" in optionsOrFetchers ? optionsOrFetchers : fetchers;
|
|
290
|
+
const options = optionsOrFetchers && !("customFetchV2" in optionsOrFetchers) ? optionsOrFetchers : void 0;
|
|
291
|
+
const fetchV2 = maybeFetchers?.customFetchV2 ?? customFetchV2;
|
|
292
|
+
const urlResponse = await fetchV2(
|
|
293
|
+
`/workspaces/${workspaceId}/articles/${articleId}/content-upload-url`,
|
|
294
|
+
{
|
|
295
|
+
method: "POST",
|
|
296
|
+
...options ? {
|
|
297
|
+
body: JSON.stringify({
|
|
298
|
+
baseContentRevision: options.baseContentRevision,
|
|
299
|
+
baseContentHash: options.baseContentHash,
|
|
300
|
+
contentHash: options.contentHash,
|
|
301
|
+
contentLength: new TextEncoder().encode(content).byteLength
|
|
302
|
+
})
|
|
303
|
+
} : {}
|
|
304
|
+
}
|
|
305
|
+
);
|
|
306
|
+
if (!urlResponse.ok) {
|
|
307
|
+
throw await fetchErrorFromResponse("Error getting upload URL", urlResponse);
|
|
308
|
+
}
|
|
309
|
+
const { uploadUrl, uploadId } = await urlResponse.json();
|
|
310
|
+
if (!uploadUrl) {
|
|
311
|
+
throw new errors_default("No upload URL returned", 500);
|
|
312
|
+
}
|
|
313
|
+
const uploadResponse = await fetch(uploadUrl, {
|
|
314
|
+
method: "PUT",
|
|
315
|
+
headers: { "Content-Type": "text/markdown" },
|
|
316
|
+
body: content,
|
|
317
|
+
signal: maybeFetchers?.signal
|
|
318
|
+
});
|
|
319
|
+
if (!uploadResponse.ok) {
|
|
320
|
+
throw await fetchErrorFromResponse("Error uploading content to S3", uploadResponse);
|
|
321
|
+
}
|
|
322
|
+
if (!options) {
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
if (!uploadId) {
|
|
326
|
+
throw new errors_default("No uploadId returned for conditional content upload", 500);
|
|
327
|
+
}
|
|
328
|
+
const commitResponse = await fetchV2(
|
|
329
|
+
`/workspaces/${workspaceId}/articles/${articleId}/content-commit`,
|
|
330
|
+
{
|
|
331
|
+
method: "POST",
|
|
332
|
+
body: JSON.stringify({
|
|
333
|
+
uploadId,
|
|
334
|
+
baseContentRevision: options.baseContentRevision,
|
|
335
|
+
baseContentHash: options.baseContentHash,
|
|
336
|
+
contentHash: options.contentHash,
|
|
337
|
+
title: options.title,
|
|
338
|
+
preview: options.preview,
|
|
339
|
+
wordCount: options.wordCount,
|
|
340
|
+
folderId: options.folderId,
|
|
341
|
+
isPinned: options.isPinned,
|
|
342
|
+
isArchived: options.isArchived,
|
|
343
|
+
articleSettings: options.articleSettings
|
|
344
|
+
})
|
|
345
|
+
}
|
|
346
|
+
);
|
|
347
|
+
if (!commitResponse.ok) {
|
|
348
|
+
throw await fetchErrorFromResponse("Error committing article content", commitResponse);
|
|
349
|
+
}
|
|
350
|
+
return commitResponse.json();
|
|
351
|
+
};
|
|
352
|
+
getWorkspaces = async (fetchers) => {
|
|
353
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
354
|
+
const response = await fetchV2("/workspaces");
|
|
355
|
+
if (!response.ok) {
|
|
356
|
+
throw new errors_default(
|
|
357
|
+
`Error fetching workspaces. ${await response.text()}`,
|
|
358
|
+
response.status
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
return response.json();
|
|
362
|
+
};
|
|
363
|
+
createWorkspace = async (request, fetchers) => {
|
|
364
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
365
|
+
const response = await fetchV2("/workspaces", {
|
|
366
|
+
method: "POST",
|
|
367
|
+
body: JSON.stringify(request)
|
|
368
|
+
});
|
|
369
|
+
if (!response.ok) {
|
|
370
|
+
throw new errors_default(
|
|
371
|
+
`Error creating workspace. ${await response.text()}`,
|
|
372
|
+
response.status
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
return response.json();
|
|
376
|
+
};
|
|
377
|
+
updateWorkspace = async (workspaceId, request, fetchers) => {
|
|
378
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
379
|
+
const response = await fetchV2(`/workspaces/${workspaceId}`, {
|
|
380
|
+
method: "PUT",
|
|
381
|
+
body: JSON.stringify(request)
|
|
382
|
+
});
|
|
383
|
+
if (!response.ok) {
|
|
384
|
+
throw new errors_default(
|
|
385
|
+
`Error updating workspace. ${await response.text()}`,
|
|
386
|
+
response.status
|
|
387
|
+
);
|
|
388
|
+
}
|
|
389
|
+
return response.json();
|
|
390
|
+
};
|
|
391
|
+
deleteWorkspace = async (workspaceId, fetchers) => {
|
|
392
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
393
|
+
const response = await fetchV2(`/workspaces/${workspaceId}`, {
|
|
394
|
+
method: "DELETE"
|
|
395
|
+
});
|
|
396
|
+
if (!response.ok) {
|
|
397
|
+
throw new errors_default(
|
|
398
|
+
`Error deleting workspace. ${await response.text()}`,
|
|
399
|
+
response.status
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
try {
|
|
403
|
+
return await response.json();
|
|
404
|
+
} catch {
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
getWorkspace = async (workspaceId, fetchers) => {
|
|
409
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
410
|
+
const response = await fetchV2(`/workspaces/${workspaceId}`);
|
|
411
|
+
if (!response.ok) {
|
|
412
|
+
throw new errors_default(
|
|
413
|
+
`Error fetching workspace. ${await response.text()}`,
|
|
414
|
+
response.status
|
|
415
|
+
);
|
|
416
|
+
}
|
|
417
|
+
return response.json();
|
|
418
|
+
};
|
|
419
|
+
normalizeTimestampMs = (value) => {
|
|
420
|
+
const n = typeof value === "number" ? value : Number(value);
|
|
421
|
+
if (!Number.isFinite(n)) return Date.now();
|
|
422
|
+
return n < 1e12 ? n * 1e3 : n;
|
|
423
|
+
};
|
|
424
|
+
readFolderErrorMessage = async (response, fallback) => {
|
|
425
|
+
const errorText = await response.text();
|
|
426
|
+
try {
|
|
427
|
+
const body = JSON.parse(errorText);
|
|
428
|
+
const message = body?.error?.message ?? body?.message;
|
|
429
|
+
if (typeof message === "string" && message.trim()) {
|
|
430
|
+
return message;
|
|
431
|
+
}
|
|
432
|
+
} catch {
|
|
433
|
+
}
|
|
434
|
+
return errorText.trim() || fallback;
|
|
435
|
+
};
|
|
436
|
+
normalizeFolder = (raw) => {
|
|
437
|
+
const id = raw?.id ?? raw?.folderId;
|
|
438
|
+
const parentId = raw?.parentId ?? raw?.parentFolderId ?? null;
|
|
439
|
+
const workspaceId = raw?.workspaceId;
|
|
440
|
+
const name = raw?.name ?? "";
|
|
441
|
+
if (!id || !workspaceId) {
|
|
442
|
+
throw new Error("Invalid folder payload from API: missing id or workspaceId");
|
|
443
|
+
}
|
|
444
|
+
if (!name || typeof name !== "string" || name.trim().length === 0) {
|
|
445
|
+
throw new Error("Invalid folder payload from API: name cannot be empty");
|
|
446
|
+
}
|
|
447
|
+
if (name.length > 255) {
|
|
448
|
+
throw new Error("Invalid folder payload from API: name exceeds 255 characters");
|
|
449
|
+
}
|
|
450
|
+
return {
|
|
451
|
+
id,
|
|
452
|
+
name: name.trim(),
|
|
453
|
+
parentId: parentId ?? null,
|
|
454
|
+
workspaceId,
|
|
455
|
+
createdAt: normalizeTimestampMs(raw?.createdAt),
|
|
456
|
+
updatedAt: normalizeTimestampMs(raw?.updatedAt),
|
|
457
|
+
...raw?.deletedAt ? { deletedAt: normalizeTimestampMs(raw?.deletedAt) } : {},
|
|
458
|
+
deletedBy: raw?.deletedBy,
|
|
459
|
+
color: raw?.color,
|
|
460
|
+
icon: raw?.icon,
|
|
461
|
+
order: raw?.order
|
|
462
|
+
};
|
|
463
|
+
};
|
|
464
|
+
createFolder = async (workspaceId, folderRequest, fetchers) => {
|
|
465
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
466
|
+
const response = await fetchV2(`/workspaces/${workspaceId}/folders`, {
|
|
467
|
+
method: "POST",
|
|
468
|
+
body: JSON.stringify({
|
|
469
|
+
folderId: folderRequest.id,
|
|
470
|
+
id: folderRequest.id,
|
|
471
|
+
name: folderRequest.name,
|
|
472
|
+
parentId: folderRequest.parentId === null ? null : folderRequest.parentId ?? void 0
|
|
473
|
+
})
|
|
474
|
+
});
|
|
475
|
+
if (!response.ok) {
|
|
476
|
+
throw new errors_default(
|
|
477
|
+
await readFolderErrorMessage(response, "Error creating folder"),
|
|
478
|
+
response.status
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
return normalizeFolder(await response.json());
|
|
482
|
+
};
|
|
483
|
+
updateFolder = async (workspaceId, folderId, folderRequest, fetchers) => {
|
|
484
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
485
|
+
const response = await fetchV2(`/workspaces/${workspaceId}/folders/${folderId}`, {
|
|
486
|
+
method: "PUT",
|
|
487
|
+
body: JSON.stringify({
|
|
488
|
+
name: folderRequest.name,
|
|
489
|
+
parentId: folderRequest.parentId === null ? null : folderRequest.parentId ?? void 0
|
|
490
|
+
})
|
|
491
|
+
});
|
|
492
|
+
if (!response.ok) {
|
|
493
|
+
throw new errors_default(
|
|
494
|
+
await readFolderErrorMessage(response, "Error updating folder"),
|
|
495
|
+
response.status
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
const result = await response.json();
|
|
499
|
+
try {
|
|
500
|
+
return normalizeFolder(result);
|
|
501
|
+
} catch {
|
|
502
|
+
return normalizeFolder({
|
|
503
|
+
...folderRequest,
|
|
504
|
+
id: folderId,
|
|
505
|
+
workspaceId,
|
|
506
|
+
parentId: folderRequest.parentId ?? null
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
};
|
|
510
|
+
getFolders = async (workspaceId, options, fetchers) => {
|
|
511
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
512
|
+
const qs = options?.includeDeleted ? "?includeDeleted=true" : "";
|
|
513
|
+
const response = await fetchV2(`/workspaces/${workspaceId}/folders${qs}`);
|
|
514
|
+
if (!response.ok) {
|
|
515
|
+
const errorText = await response.text();
|
|
516
|
+
throw new errors_default(`Error fetching folders. ${errorText}`, response.status);
|
|
517
|
+
}
|
|
518
|
+
const folders = await response.json();
|
|
519
|
+
return Array.isArray(folders) ? folders.map(normalizeFolder) : [];
|
|
520
|
+
};
|
|
521
|
+
getFolder = async (workspaceId, folderId, fetchers) => {
|
|
522
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
523
|
+
const response = await fetchV2(`/workspaces/${workspaceId}/folders/${folderId}`);
|
|
524
|
+
if (!response.ok) {
|
|
525
|
+
throw new errors_default(
|
|
526
|
+
`Error fetching folder. ${await response.text()}`,
|
|
527
|
+
response.status
|
|
528
|
+
);
|
|
529
|
+
}
|
|
530
|
+
return normalizeFolder(await response.json());
|
|
531
|
+
};
|
|
532
|
+
deleteFolder = async (workspaceId, folderId, fetchers) => {
|
|
533
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
534
|
+
const response = await fetchV2(`/workspaces/${workspaceId}/folders/${folderId}`, {
|
|
535
|
+
method: "DELETE"
|
|
536
|
+
});
|
|
537
|
+
if (!response.ok) {
|
|
538
|
+
const errorText = await response.text();
|
|
539
|
+
throw new errors_default(`Error deleting folder. ${errorText}`, response.status);
|
|
540
|
+
}
|
|
541
|
+
return true;
|
|
542
|
+
};
|
|
543
|
+
sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
544
|
+
isRetriableStatus = (status) => status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
|
|
545
|
+
withRetries = async (fn, maxAttempts = 3) => {
|
|
546
|
+
let lastError;
|
|
547
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
548
|
+
try {
|
|
549
|
+
const response = await fn();
|
|
550
|
+
if (response.ok) return response;
|
|
551
|
+
if (attempt < maxAttempts && isRetriableStatus(response.status)) {
|
|
552
|
+
const backoffMs = 250 * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 150);
|
|
553
|
+
await sleep(backoffMs);
|
|
554
|
+
continue;
|
|
555
|
+
}
|
|
556
|
+
return response;
|
|
557
|
+
} catch (e) {
|
|
558
|
+
lastError = e;
|
|
559
|
+
if (attempt < maxAttempts) {
|
|
560
|
+
const backoffMs = 250 * Math.pow(2, attempt - 1) + Math.floor(Math.random() * 150);
|
|
561
|
+
await sleep(backoffMs);
|
|
562
|
+
continue;
|
|
563
|
+
}
|
|
564
|
+
throw lastError;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
throw lastError;
|
|
568
|
+
};
|
|
569
|
+
listApiKeys = async (fetchers) => {
|
|
570
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
571
|
+
const response = await withRetries(() => fetchV2("/api-keys", { method: "GET" }), 3);
|
|
572
|
+
if (!response.ok) {
|
|
573
|
+
throw new Error(`Failed to list API keys: ${response.status} ${response.statusText}`);
|
|
574
|
+
}
|
|
575
|
+
return response.json();
|
|
576
|
+
};
|
|
577
|
+
createApiKey = async (request, fetchers) => {
|
|
578
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
579
|
+
const response = await withRetries(
|
|
580
|
+
() => fetchV2("/api-keys", {
|
|
581
|
+
method: "POST",
|
|
582
|
+
body: JSON.stringify(request)
|
|
583
|
+
}),
|
|
584
|
+
3
|
|
585
|
+
);
|
|
586
|
+
if (!response.ok) {
|
|
587
|
+
throw new Error(`Failed to create API key: ${response.status} ${response.statusText}`);
|
|
588
|
+
}
|
|
589
|
+
return response.json();
|
|
590
|
+
};
|
|
591
|
+
revokeApiKey = async (keyId, fetchers) => {
|
|
592
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
593
|
+
const response = await withRetries(
|
|
594
|
+
() => fetchV2(`/api-keys/${encodeURIComponent(keyId)}`, {
|
|
595
|
+
method: "DELETE"
|
|
596
|
+
}),
|
|
597
|
+
3
|
|
598
|
+
);
|
|
599
|
+
if (!response.ok) {
|
|
600
|
+
throw new Error(`Failed to revoke API key: ${response.status} ${response.statusText}`);
|
|
601
|
+
}
|
|
602
|
+
return response.json();
|
|
603
|
+
};
|
|
604
|
+
checkpointCollaboration = async (workspaceId, articleId, fetchers) => {
|
|
605
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
606
|
+
const response = await fetchV2(
|
|
607
|
+
`/workspaces/${workspaceId}/articles/${articleId}/collaboration/checkpoint`,
|
|
608
|
+
{ method: "POST" }
|
|
609
|
+
);
|
|
610
|
+
if (!response.ok) {
|
|
611
|
+
throw new errors_default(
|
|
612
|
+
`Error checkpointing collaboration. ${await response.text()}`,
|
|
613
|
+
response.status
|
|
614
|
+
);
|
|
615
|
+
}
|
|
616
|
+
return response.json();
|
|
617
|
+
};
|
|
618
|
+
publishArticle = async (workspaceId, articleId, body, fetchers) => {
|
|
619
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
620
|
+
const response = await fetchV2(
|
|
621
|
+
`/workspaces/${workspaceId}/articles/${articleId}/publish`,
|
|
622
|
+
{
|
|
623
|
+
method: "POST",
|
|
624
|
+
body: JSON.stringify(body)
|
|
625
|
+
}
|
|
626
|
+
);
|
|
627
|
+
if (!response.ok) {
|
|
628
|
+
throw new errors_default(
|
|
629
|
+
`Error publishing article: ${await response.text()}`,
|
|
630
|
+
response.status
|
|
631
|
+
);
|
|
632
|
+
}
|
|
633
|
+
return response.json();
|
|
634
|
+
};
|
|
635
|
+
unpublishArticle = async (workspaceId, articleId, fetchers) => {
|
|
636
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
637
|
+
const response = await fetchV2(
|
|
638
|
+
`/workspaces/${workspaceId}/articles/${articleId}/publish`,
|
|
639
|
+
{ method: "DELETE" }
|
|
640
|
+
);
|
|
641
|
+
if (!response.ok) {
|
|
642
|
+
throw new errors_default(
|
|
643
|
+
`Error unpublishing article: ${await response.text()}`,
|
|
644
|
+
response.status
|
|
645
|
+
);
|
|
646
|
+
}
|
|
647
|
+
return response.json();
|
|
648
|
+
};
|
|
649
|
+
getPublishStatus = async (workspaceId, articleId, fetchers) => {
|
|
650
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
651
|
+
const response = await fetchV2(
|
|
652
|
+
`/workspaces/${workspaceId}/articles/${articleId}/publish`,
|
|
653
|
+
{ method: "GET" }
|
|
654
|
+
);
|
|
655
|
+
if (!response.ok) {
|
|
656
|
+
throw new errors_default(
|
|
657
|
+
`Error fetching publish status: ${await response.text()}`,
|
|
658
|
+
response.status
|
|
659
|
+
);
|
|
660
|
+
}
|
|
661
|
+
return response.json();
|
|
662
|
+
};
|
|
663
|
+
updatePublishedArticle = async (workspaceId, articleId, body, fetchers) => {
|
|
664
|
+
const fetchV2 = fetchers?.customFetchV2 ?? customFetchV2;
|
|
665
|
+
const response = await fetchV2(
|
|
666
|
+
`/workspaces/${workspaceId}/articles/${articleId}/publish`,
|
|
667
|
+
{
|
|
668
|
+
method: "PUT",
|
|
669
|
+
body: JSON.stringify(body)
|
|
670
|
+
}
|
|
671
|
+
);
|
|
672
|
+
if (!response.ok) {
|
|
673
|
+
throw new errors_default(
|
|
674
|
+
`Error updating published article: ${await response.text()}`,
|
|
675
|
+
response.status
|
|
676
|
+
);
|
|
677
|
+
}
|
|
678
|
+
return response.json();
|
|
679
|
+
};
|
|
680
|
+
FetchError2 = class extends Error {
|
|
681
|
+
status;
|
|
682
|
+
data;
|
|
683
|
+
constructor(message, status, data) {
|
|
684
|
+
super(message);
|
|
685
|
+
this.name = "FetchError";
|
|
686
|
+
this.status = status;
|
|
687
|
+
this.data = data;
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
});
|
|
612
692
|
|
|
613
693
|
// src/utils/config.ts
|
|
614
694
|
import { homedir } from "os";
|
|
615
695
|
import { join } from "path";
|
|
616
696
|
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
617
|
-
var CONFIG_DIR
|
|
618
|
-
var
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
const data = readFileSync(CONFIG_FILE, "utf8");
|
|
628
|
-
this.config = JSON.parse(data);
|
|
697
|
+
var CONFIG_DIR, CONFIG_FILE, ConfigManager, configManager;
|
|
698
|
+
var init_config = __esm({
|
|
699
|
+
"src/utils/config.ts"() {
|
|
700
|
+
"use strict";
|
|
701
|
+
CONFIG_DIR = process.env.MDEDIT_CONFIG_DIR || join(homedir(), ".mdedit-cli");
|
|
702
|
+
CONFIG_FILE = process.env.MDEDIT_CONFIG_FILE || join(CONFIG_DIR, "config.json");
|
|
703
|
+
ConfigManager = class {
|
|
704
|
+
config = {};
|
|
705
|
+
constructor() {
|
|
706
|
+
this.load();
|
|
629
707
|
}
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
708
|
+
load() {
|
|
709
|
+
try {
|
|
710
|
+
if (existsSync(CONFIG_FILE)) {
|
|
711
|
+
const data = readFileSync(CONFIG_FILE, "utf8");
|
|
712
|
+
this.config = JSON.parse(data);
|
|
713
|
+
}
|
|
714
|
+
} catch {
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
save() {
|
|
718
|
+
try {
|
|
719
|
+
if (!existsSync(CONFIG_DIR)) {
|
|
720
|
+
mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
|
|
721
|
+
}
|
|
722
|
+
writeFileSync(CONFIG_FILE, JSON.stringify(this.config, null, 2), { mode: 384 });
|
|
723
|
+
try {
|
|
724
|
+
chmodSync(CONFIG_DIR, 448);
|
|
725
|
+
} catch {
|
|
726
|
+
}
|
|
727
|
+
try {
|
|
728
|
+
chmodSync(CONFIG_FILE, 384);
|
|
729
|
+
} catch {
|
|
730
|
+
}
|
|
731
|
+
} catch (error) {
|
|
732
|
+
console.error("Failed to save config:", error.message);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
get(key) {
|
|
736
|
+
const envMap = {
|
|
737
|
+
apiUrl: "MDEDIT_API_URL",
|
|
738
|
+
apiKey: "MDEDIT_API_KEY",
|
|
739
|
+
userId: "MDEDIT_USER_ID",
|
|
740
|
+
workspaceId: "MDEDIT_WORKSPACE_ID",
|
|
741
|
+
outputFormat: "MDEDIT_OUTPUT_FORMAT",
|
|
742
|
+
oauthProfile: "MDEDIT_PROFILE"
|
|
743
|
+
};
|
|
744
|
+
const envKey = envMap[key];
|
|
745
|
+
if (envKey && process.env[envKey] !== void 0) {
|
|
746
|
+
return process.env[envKey];
|
|
747
|
+
}
|
|
748
|
+
return this.config[key];
|
|
637
749
|
}
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
} catch {
|
|
750
|
+
set(key, value) {
|
|
751
|
+
this.config[key] = value;
|
|
752
|
+
this.save();
|
|
642
753
|
}
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
}
|
|
754
|
+
getAll() {
|
|
755
|
+
return { ...this.config };
|
|
756
|
+
}
|
|
757
|
+
clear() {
|
|
758
|
+
this.config = {};
|
|
759
|
+
this.save();
|
|
646
760
|
}
|
|
647
|
-
} catch (error) {
|
|
648
|
-
console.error("Failed to save config:", error.message);
|
|
649
|
-
}
|
|
650
|
-
}
|
|
651
|
-
get(key) {
|
|
652
|
-
const envMap = {
|
|
653
|
-
apiUrl: "MDEDIT_API_URL",
|
|
654
|
-
apiKey: "MDEDIT_API_KEY",
|
|
655
|
-
userId: "MDEDIT_USER_ID",
|
|
656
|
-
workspaceId: "MDEDIT_WORKSPACE_ID",
|
|
657
|
-
outputFormat: "MDEDIT_OUTPUT_FORMAT"
|
|
658
761
|
};
|
|
659
|
-
|
|
660
|
-
if (envKey && process.env[envKey] !== void 0) {
|
|
661
|
-
return process.env[envKey];
|
|
662
|
-
}
|
|
663
|
-
return this.config[key];
|
|
664
|
-
}
|
|
665
|
-
set(key, value) {
|
|
666
|
-
this.config[key] = value;
|
|
667
|
-
this.save();
|
|
668
|
-
}
|
|
669
|
-
getAll() {
|
|
670
|
-
return { ...this.config };
|
|
762
|
+
configManager = new ConfigManager();
|
|
671
763
|
}
|
|
672
|
-
|
|
673
|
-
this.config = {};
|
|
674
|
-
this.save();
|
|
675
|
-
}
|
|
676
|
-
};
|
|
677
|
-
var configManager = new ConfigManager();
|
|
764
|
+
});
|
|
678
765
|
|
|
679
766
|
// src/utils/output.ts
|
|
680
|
-
|
|
767
|
+
import chalk from "chalk";
|
|
681
768
|
function normalizeFormat(value) {
|
|
682
769
|
const raw = String(value || "").trim().toLowerCase();
|
|
683
770
|
if (raw === "json" || raw === "table" || raw === "plain") return raw;
|
|
@@ -688,172 +775,373 @@ function truncateCell(value, max = MAX_TABLE_CELL_WIDTH) {
|
|
|
688
775
|
if (text.length <= max) return text;
|
|
689
776
|
return text.slice(0, Math.max(0, max - 1)).trimEnd() + "\u2026";
|
|
690
777
|
}
|
|
691
|
-
var OutputFormatter
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
}
|
|
702
|
-
isJson() {
|
|
703
|
-
return this.format === "json";
|
|
704
|
-
}
|
|
705
|
-
log(message) {
|
|
706
|
-
if (this.format === "json") {
|
|
707
|
-
console.error(message);
|
|
708
|
-
return;
|
|
709
|
-
}
|
|
710
|
-
console.log(message);
|
|
711
|
-
}
|
|
712
|
-
success(message) {
|
|
713
|
-
this.log(`${chalk.green("\u2713")} ${message}`);
|
|
714
|
-
}
|
|
715
|
-
error(message) {
|
|
716
|
-
const text = this.stringify(message);
|
|
717
|
-
console.error(`${chalk.red("\u2717")} ${text}`);
|
|
718
|
-
}
|
|
719
|
-
warning(message) {
|
|
720
|
-
const text = this.stringify(message);
|
|
721
|
-
console.warn(`${chalk.yellow("\u26A0")} ${text}`);
|
|
722
|
-
}
|
|
723
|
-
info(message) {
|
|
724
|
-
const text = this.stringify(message);
|
|
725
|
-
this.log(`${chalk.blue("\u2139")} ${text}`);
|
|
726
|
-
}
|
|
727
|
-
output(data) {
|
|
728
|
-
if (this.format === "json") {
|
|
729
|
-
console.log(JSON.stringify(data, null, 2));
|
|
730
|
-
return;
|
|
731
|
-
}
|
|
732
|
-
if (this.format === "table") {
|
|
733
|
-
if (Array.isArray(data)) {
|
|
734
|
-
this.printTable(data);
|
|
735
|
-
return;
|
|
778
|
+
var MAX_TABLE_CELL_WIDTH, OutputFormatter, output;
|
|
779
|
+
var init_output = __esm({
|
|
780
|
+
"src/utils/output.ts"() {
|
|
781
|
+
"use strict";
|
|
782
|
+
init_config();
|
|
783
|
+
MAX_TABLE_CELL_WIDTH = 80;
|
|
784
|
+
OutputFormatter = class {
|
|
785
|
+
format;
|
|
786
|
+
constructor() {
|
|
787
|
+
this.format = normalizeFormat(configManager.get("outputFormat") || "table");
|
|
736
788
|
}
|
|
737
|
-
|
|
738
|
-
this.
|
|
739
|
-
return;
|
|
789
|
+
setFormat(format) {
|
|
790
|
+
this.format = normalizeFormat(format);
|
|
740
791
|
}
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
792
|
+
getFormat() {
|
|
793
|
+
return this.format;
|
|
794
|
+
}
|
|
795
|
+
isJson() {
|
|
796
|
+
return this.format === "json";
|
|
797
|
+
}
|
|
798
|
+
log(message) {
|
|
799
|
+
if (this.format === "json") {
|
|
800
|
+
console.error(message);
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
console.log(message);
|
|
804
|
+
}
|
|
805
|
+
success(message) {
|
|
806
|
+
this.log(`${chalk.green("\u2713")} ${message}`);
|
|
807
|
+
}
|
|
808
|
+
error(message) {
|
|
809
|
+
const text = this.stringify(message);
|
|
810
|
+
console.error(`${chalk.red("\u2717")} ${text}`);
|
|
811
|
+
}
|
|
812
|
+
warning(message) {
|
|
813
|
+
const text = this.stringify(message);
|
|
814
|
+
console.warn(`${chalk.yellow("\u26A0")} ${text}`);
|
|
815
|
+
}
|
|
816
|
+
info(message) {
|
|
817
|
+
const text = this.stringify(message);
|
|
818
|
+
this.log(`${chalk.blue("\u2139")} ${text}`);
|
|
819
|
+
}
|
|
820
|
+
output(data) {
|
|
821
|
+
if (this.format === "json") {
|
|
822
|
+
console.log(JSON.stringify(data, null, 2));
|
|
823
|
+
return;
|
|
824
|
+
}
|
|
825
|
+
if (this.format === "table") {
|
|
826
|
+
if (Array.isArray(data)) {
|
|
827
|
+
this.printTable(data);
|
|
828
|
+
return;
|
|
829
|
+
}
|
|
830
|
+
if (typeof data === "object" && data !== null) {
|
|
831
|
+
this.printObject(data);
|
|
832
|
+
return;
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
if (this.format === "plain") {
|
|
836
|
+
if (typeof data === "object" && data !== null) {
|
|
837
|
+
this.printObject(data);
|
|
838
|
+
} else {
|
|
839
|
+
console.log(data);
|
|
840
|
+
}
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
746
843
|
console.log(data);
|
|
747
844
|
}
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
console.log(data);
|
|
751
|
-
}
|
|
752
|
-
header(text) {
|
|
753
|
-
this.log(`
|
|
845
|
+
header(text) {
|
|
846
|
+
this.log(`
|
|
754
847
|
${chalk.bold.underline(text)}
|
|
755
848
|
`);
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
849
|
+
}
|
|
850
|
+
printTable(rowsRaw) {
|
|
851
|
+
if (rowsRaw.length === 0) {
|
|
852
|
+
console.log("(no results)");
|
|
853
|
+
return;
|
|
854
|
+
}
|
|
855
|
+
const rows = rowsRaw.map((row) => {
|
|
856
|
+
if (row && typeof row === "object" && !Array.isArray(row)) return row;
|
|
857
|
+
return { value: row };
|
|
858
|
+
});
|
|
859
|
+
const columns = [];
|
|
860
|
+
const seen = /* @__PURE__ */ new Set();
|
|
861
|
+
const addColumn = (col) => {
|
|
862
|
+
if (seen.has(col)) return;
|
|
863
|
+
seen.add(col);
|
|
864
|
+
columns.push(col);
|
|
865
|
+
};
|
|
866
|
+
addColumn("(index)");
|
|
867
|
+
for (const key of Object.keys(rows[0] || {})) addColumn(key);
|
|
868
|
+
for (const row of rows) {
|
|
869
|
+
for (const key of Object.keys(row)) addColumn(key);
|
|
870
|
+
}
|
|
871
|
+
const cell = (value) => {
|
|
872
|
+
if (value === null || value === void 0) return "";
|
|
873
|
+
if (typeof value === "string") return truncateCell(value);
|
|
874
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
875
|
+
try {
|
|
876
|
+
return truncateCell(JSON.stringify(value));
|
|
877
|
+
} catch {
|
|
878
|
+
return truncateCell(String(value));
|
|
879
|
+
}
|
|
880
|
+
};
|
|
881
|
+
const grid = rows.map((row, idx) => {
|
|
882
|
+
const record = { ...row };
|
|
883
|
+
return columns.map((col) => {
|
|
884
|
+
if (col === "(index)") return String(idx);
|
|
885
|
+
return cell(record[col]);
|
|
886
|
+
});
|
|
887
|
+
});
|
|
888
|
+
const widths = columns.map((col, i) => {
|
|
889
|
+
const headerWidth = col.length;
|
|
890
|
+
const cellsWidth = Math.max(...grid.map((r) => (r[i] ?? "").length), 0);
|
|
891
|
+
return Math.min(MAX_TABLE_CELL_WIDTH, Math.max(headerWidth, cellsWidth));
|
|
892
|
+
});
|
|
893
|
+
const pad = (text, width) => text.length >= width ? text.slice(0, width) : text + " ".repeat(width - text.length);
|
|
894
|
+
const line = (left, mid, right) => left + widths.map((w) => "\u2500".repeat(w + 2)).join(mid) + right;
|
|
895
|
+
const rowLine = (values) => "\u2502" + values.map((v, i) => ` ${pad(v, widths[i])} `).join("\u2502") + "\u2502";
|
|
896
|
+
console.log(line("\u250C", "\u252C", "\u2510"));
|
|
897
|
+
console.log(rowLine(columns.map((c, i) => pad(c, widths[i]))));
|
|
898
|
+
console.log(line("\u251C", "\u253C", "\u2524"));
|
|
899
|
+
for (const r of grid) console.log(rowLine(r.map((v, i) => pad(v, widths[i]))));
|
|
900
|
+
console.log(line("\u2514", "\u2534", "\u2518"));
|
|
901
|
+
}
|
|
902
|
+
printObject(obj, indent = 0) {
|
|
903
|
+
if (Array.isArray(obj)) {
|
|
904
|
+
obj.forEach((item, index) => {
|
|
905
|
+
console.log(" ".repeat(indent) + chalk.cyan(`[${index}]`));
|
|
906
|
+
this.printObject(item, indent + 1);
|
|
907
|
+
});
|
|
908
|
+
return;
|
|
909
|
+
}
|
|
910
|
+
if (typeof obj === "object" && obj !== null) {
|
|
911
|
+
Object.entries(obj).forEach(([key, value]) => {
|
|
912
|
+
if (typeof value === "object" && value !== null) {
|
|
913
|
+
console.log(" ".repeat(indent) + chalk.cyan(key) + ":");
|
|
914
|
+
this.printObject(value, indent + 1);
|
|
915
|
+
} else {
|
|
916
|
+
console.log(" ".repeat(indent) + chalk.cyan(key) + ":", value);
|
|
917
|
+
}
|
|
918
|
+
});
|
|
919
|
+
return;
|
|
920
|
+
}
|
|
921
|
+
console.log(" ".repeat(indent) + String(obj));
|
|
922
|
+
}
|
|
923
|
+
stringify(value) {
|
|
924
|
+
if (typeof value === "string") return value;
|
|
925
|
+
if (value instanceof Error) return value.message || String(value);
|
|
926
|
+
try {
|
|
927
|
+
return JSON.stringify(value);
|
|
928
|
+
} catch {
|
|
929
|
+
return String(value);
|
|
930
|
+
}
|
|
786
931
|
}
|
|
787
932
|
};
|
|
788
|
-
|
|
789
|
-
const record = { ...row };
|
|
790
|
-
return columns.map((col) => {
|
|
791
|
-
if (col === "(index)") return String(idx);
|
|
792
|
-
return cell(record[col]);
|
|
793
|
-
});
|
|
794
|
-
});
|
|
795
|
-
const widths = columns.map((col, i) => {
|
|
796
|
-
const headerWidth = col.length;
|
|
797
|
-
const cellsWidth = Math.max(...grid.map((r) => (r[i] ?? "").length), 0);
|
|
798
|
-
return Math.min(MAX_TABLE_CELL_WIDTH, Math.max(headerWidth, cellsWidth));
|
|
799
|
-
});
|
|
800
|
-
const pad = (text, width) => text.length >= width ? text.slice(0, width) : text + " ".repeat(width - text.length);
|
|
801
|
-
const line = (left, mid, right) => left + widths.map((w) => "\u2500".repeat(w + 2)).join(mid) + right;
|
|
802
|
-
const rowLine = (values) => "\u2502" + values.map((v, i) => ` ${pad(v, widths[i])} `).join("\u2502") + "\u2502";
|
|
803
|
-
console.log(line("\u250C", "\u252C", "\u2510"));
|
|
804
|
-
console.log(rowLine(columns.map((c, i) => pad(c, widths[i]))));
|
|
805
|
-
console.log(line("\u251C", "\u253C", "\u2524"));
|
|
806
|
-
for (const r of grid) console.log(rowLine(r.map((v, i) => pad(v, widths[i]))));
|
|
807
|
-
console.log(line("\u2514", "\u2534", "\u2518"));
|
|
933
|
+
output = new OutputFormatter();
|
|
808
934
|
}
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
935
|
+
});
|
|
936
|
+
|
|
937
|
+
// src/utils/oauth.ts
|
|
938
|
+
var oauth_exports = {};
|
|
939
|
+
__export(oauth_exports, {
|
|
940
|
+
loginWithOAuth: () => loginWithOAuth,
|
|
941
|
+
logoutOAuth: () => logoutOAuth,
|
|
942
|
+
oauthStatus: () => oauthStatus,
|
|
943
|
+
qualifyOAuthScopes: () => qualifyOAuthScopes,
|
|
944
|
+
storedOAuthAccessToken: () => storedOAuthAccessToken
|
|
945
|
+
});
|
|
946
|
+
import { randomBytes } from "crypto";
|
|
947
|
+
import { spawn } from "child_process";
|
|
948
|
+
import {
|
|
949
|
+
NodeOAuthClient,
|
|
950
|
+
OsCredentialStore,
|
|
951
|
+
createPkcePair,
|
|
952
|
+
startLoopbackCallback
|
|
953
|
+
} from "@mdedit/node-auth";
|
|
954
|
+
function activeProfile(profile) {
|
|
955
|
+
return profile?.trim() || configManager.get("oauthProfile") || DEFAULT_PROFILE;
|
|
956
|
+
}
|
|
957
|
+
function profileIndex() {
|
|
958
|
+
return configManager.get("oauthProfiles") || [];
|
|
959
|
+
}
|
|
960
|
+
function setProfileIndex(profiles) {
|
|
961
|
+
configManager.set("oauthProfiles", [...new Set(profiles)].sort());
|
|
962
|
+
}
|
|
963
|
+
async function discoverOAuthConfiguration() {
|
|
964
|
+
const clientId = process.env.MDEDIT_OAUTH_CLIENT_ID;
|
|
965
|
+
const authorizationEndpoint = process.env.MDEDIT_OAUTH_AUTHORIZATION_ENDPOINT;
|
|
966
|
+
const tokenEndpoint = process.env.MDEDIT_OAUTH_TOKEN_ENDPOINT;
|
|
967
|
+
const revocationEndpoint = process.env.MDEDIT_OAUTH_REVOCATION_ENDPOINT;
|
|
968
|
+
if (clientId && authorizationEndpoint && tokenEndpoint && revocationEndpoint) {
|
|
969
|
+
return {
|
|
970
|
+
authorizationEndpoint,
|
|
971
|
+
clientId,
|
|
972
|
+
defaultScopes: (process.env.MDEDIT_OAUTH_SCOPES || "").split(",").map((scope) => scope.trim()).filter(Boolean),
|
|
973
|
+
resource: process.env.MDEDIT_OAUTH_RESOURCE || "https://apiv2.mdedit.ai/api",
|
|
974
|
+
revocationEndpoint,
|
|
975
|
+
tokenEndpoint
|
|
976
|
+
};
|
|
829
977
|
}
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
try {
|
|
834
|
-
return JSON.stringify(value);
|
|
835
|
-
} catch {
|
|
836
|
-
return String(value);
|
|
837
|
-
}
|
|
978
|
+
const response = await fetch(`${getApiBaseUrlRoot()}/.well-known/mdedit-cli-oauth`);
|
|
979
|
+
if (!response.ok) {
|
|
980
|
+
throw new Error(`OAuth discovery failed (${response.status})`);
|
|
838
981
|
}
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
return cliWorkspaceId || configManager.get("workspaceId") || process.env.MDEDIT_WORKSPACE_ID;
|
|
982
|
+
const document = await response.json();
|
|
983
|
+
if (!document.clientId || !document.authorizationEndpoint || !document.tokenEndpoint || !document.revocationEndpoint || !document.resource || !Array.isArray(document.defaultScopes)) {
|
|
984
|
+
throw new Error("OAuth discovery response is incomplete");
|
|
985
|
+
}
|
|
986
|
+
return document;
|
|
845
987
|
}
|
|
846
|
-
function
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
988
|
+
function credentialStore() {
|
|
989
|
+
return new OsCredentialStore({
|
|
990
|
+
loadProfileIndex: async () => profileIndex(),
|
|
991
|
+
saveProfileIndex: async (profiles) => setProfileIndex(profiles)
|
|
992
|
+
});
|
|
993
|
+
}
|
|
994
|
+
function qualifyOAuthScopes(scopes, resource) {
|
|
995
|
+
const prefix = `${resource.replace(/\/+$/, "")}/`;
|
|
996
|
+
return [...new Set(scopes.map((scope) => {
|
|
997
|
+
const normalized = scope.trim();
|
|
998
|
+
if (!normalized) return "";
|
|
999
|
+
if (normalized.startsWith(prefix)) return normalized;
|
|
1000
|
+
if (normalized.includes("://") || normalized.includes("/")) {
|
|
1001
|
+
throw new Error(`OAuth scope is for a different resource: ${normalized}`);
|
|
1002
|
+
}
|
|
1003
|
+
return `${prefix}${normalized}`;
|
|
1004
|
+
}).filter(Boolean))];
|
|
1005
|
+
}
|
|
1006
|
+
async function oauthClient(scopes) {
|
|
1007
|
+
const discovery = await discoverOAuthConfiguration();
|
|
1008
|
+
const selectedScopes = scopes?.length ? scopes : discovery.defaultScopes;
|
|
1009
|
+
const configuration = {
|
|
1010
|
+
authorizationEndpoint: discovery.authorizationEndpoint,
|
|
1011
|
+
clientId: discovery.clientId,
|
|
1012
|
+
redirectUri: FIXED_REDIRECT_URI,
|
|
1013
|
+
resource: discovery.resource,
|
|
1014
|
+
revocationEndpoint: discovery.revocationEndpoint,
|
|
1015
|
+
scopes: qualifyOAuthScopes(selectedScopes, discovery.resource),
|
|
1016
|
+
tokenEndpoint: discovery.tokenEndpoint
|
|
1017
|
+
};
|
|
1018
|
+
const cacheKey = JSON.stringify(configuration);
|
|
1019
|
+
const existing = oauthClientsByConfiguration.get(cacheKey);
|
|
1020
|
+
if (existing) return existing;
|
|
1021
|
+
const client = new NodeOAuthClient({
|
|
1022
|
+
configuration,
|
|
1023
|
+
credentialStore: credentialStore()
|
|
1024
|
+
});
|
|
1025
|
+
oauthClientsByConfiguration.set(cacheKey, client);
|
|
1026
|
+
return client;
|
|
1027
|
+
}
|
|
1028
|
+
function launchBrowser(url) {
|
|
1029
|
+
const command = process.platform === "darwin" ? { executable: "open", args: [url] } : process.platform === "win32" ? { executable: "rundll32.exe", args: ["url.dll,FileProtocolHandler", url] } : { executable: "xdg-open", args: [url] };
|
|
1030
|
+
const child = spawn(command.executable, command.args, {
|
|
1031
|
+
detached: true,
|
|
1032
|
+
stdio: "ignore"
|
|
1033
|
+
});
|
|
1034
|
+
child.unref();
|
|
1035
|
+
}
|
|
1036
|
+
async function loginWithOAuth({
|
|
1037
|
+
noBrowser = false,
|
|
1038
|
+
profile,
|
|
1039
|
+
scopes
|
|
1040
|
+
}) {
|
|
1041
|
+
const normalizedProfile = activeProfile(profile);
|
|
1042
|
+
const client = await oauthClient(scopes);
|
|
1043
|
+
const pkce = createPkcePair();
|
|
1044
|
+
const state = randomBytes(32).toString("base64url");
|
|
1045
|
+
const callback = await startLoopbackCallback({
|
|
1046
|
+
redirectUri: FIXED_REDIRECT_URI,
|
|
1047
|
+
state
|
|
1048
|
+
});
|
|
1049
|
+
const authorization = client.createAuthorizationRequest({
|
|
1050
|
+
challenge: pkce.challenge,
|
|
1051
|
+
state
|
|
1052
|
+
});
|
|
1053
|
+
output.info(
|
|
1054
|
+
noBrowser ? `Open this URL in a browser on this machine: ${authorization.url}` : "Opening a browser for mdedit sign-in\u2026"
|
|
1055
|
+
);
|
|
1056
|
+
if (!noBrowser) launchBrowser(authorization.url);
|
|
1057
|
+
try {
|
|
1058
|
+
const code = await callback.result;
|
|
1059
|
+
const tokenSet = await client.exchangeAuthorizationCode({
|
|
1060
|
+
code,
|
|
1061
|
+
profile: normalizedProfile,
|
|
1062
|
+
verifier: pkce.verifier
|
|
1063
|
+
});
|
|
1064
|
+
configManager.set("oauthProfile", normalizedProfile);
|
|
1065
|
+
return {
|
|
1066
|
+
expiresAt: tokenSet.expiresAt,
|
|
1067
|
+
profile: normalizedProfile,
|
|
1068
|
+
scope: [...tokenSet.scope]
|
|
1069
|
+
};
|
|
1070
|
+
} finally {
|
|
1071
|
+
await callback.close();
|
|
852
1072
|
}
|
|
853
|
-
return workspaceId;
|
|
854
1073
|
}
|
|
1074
|
+
async function oauthStatus(profile) {
|
|
1075
|
+
const normalizedProfile = activeProfile(profile);
|
|
1076
|
+
return (await oauthClient()).status(normalizedProfile);
|
|
1077
|
+
}
|
|
1078
|
+
async function logoutOAuth({
|
|
1079
|
+
all,
|
|
1080
|
+
profile
|
|
1081
|
+
}) {
|
|
1082
|
+
const client = await oauthClient();
|
|
1083
|
+
if (all) {
|
|
1084
|
+
await client.logoutAll();
|
|
1085
|
+
configManager.set("oauthProfile", void 0);
|
|
1086
|
+
return { all: true };
|
|
1087
|
+
}
|
|
1088
|
+
const normalizedProfile = activeProfile(profile);
|
|
1089
|
+
await client.logout(normalizedProfile);
|
|
1090
|
+
if (configManager.get("oauthProfile") === normalizedProfile) {
|
|
1091
|
+
configManager.set("oauthProfile", void 0);
|
|
1092
|
+
}
|
|
1093
|
+
return { all: false, profile: normalizedProfile };
|
|
1094
|
+
}
|
|
1095
|
+
async function storedOAuthAccessToken(profile, forceRefresh = false) {
|
|
1096
|
+
const normalizedProfile = activeProfile(profile);
|
|
1097
|
+
if (!profileIndex().includes(normalizedProfile)) return null;
|
|
1098
|
+
return (await oauthClient()).getAccessToken(normalizedProfile, { forceRefresh });
|
|
1099
|
+
}
|
|
1100
|
+
var DEFAULT_PROFILE, FIXED_REDIRECT_URI, oauthClientsByConfiguration;
|
|
1101
|
+
var init_oauth = __esm({
|
|
1102
|
+
"src/utils/oauth.ts"() {
|
|
1103
|
+
"use strict";
|
|
1104
|
+
init_config();
|
|
1105
|
+
init_api();
|
|
1106
|
+
init_output();
|
|
1107
|
+
DEFAULT_PROFILE = "default";
|
|
1108
|
+
FIXED_REDIRECT_URI = "http://localhost:17643/oauth/callback";
|
|
1109
|
+
oauthClientsByConfiguration = /* @__PURE__ */ new Map();
|
|
1110
|
+
}
|
|
1111
|
+
});
|
|
855
1112
|
|
|
856
1113
|
// src/utils/api.ts
|
|
1114
|
+
function selectAuthentication({
|
|
1115
|
+
explicitApiKey,
|
|
1116
|
+
oauthAccessToken,
|
|
1117
|
+
storedApiKey
|
|
1118
|
+
}) {
|
|
1119
|
+
const normalizedExplicitKey = explicitApiKey?.trim();
|
|
1120
|
+
if (normalizedExplicitKey) {
|
|
1121
|
+
return {
|
|
1122
|
+
headers: { "x-api-key": normalizedExplicitKey },
|
|
1123
|
+
method: "apiKey",
|
|
1124
|
+
websocketToken: normalizedExplicitKey
|
|
1125
|
+
};
|
|
1126
|
+
}
|
|
1127
|
+
const normalizedOAuthToken = oauthAccessToken?.trim();
|
|
1128
|
+
if (normalizedOAuthToken) {
|
|
1129
|
+
return {
|
|
1130
|
+
headers: { Authorization: `Bearer ${normalizedOAuthToken}` },
|
|
1131
|
+
method: "oauth",
|
|
1132
|
+
websocketToken: normalizedOAuthToken
|
|
1133
|
+
};
|
|
1134
|
+
}
|
|
1135
|
+
const normalizedStoredKey = storedApiKey?.trim();
|
|
1136
|
+
if (normalizedStoredKey) {
|
|
1137
|
+
return {
|
|
1138
|
+
headers: { "x-api-key": normalizedStoredKey },
|
|
1139
|
+
method: "apiKey",
|
|
1140
|
+
websocketToken: normalizedStoredKey
|
|
1141
|
+
};
|
|
1142
|
+
}
|
|
1143
|
+
return null;
|
|
1144
|
+
}
|
|
857
1145
|
function trimTrailingSlashes(value) {
|
|
858
1146
|
return value.replace(/\/+$/, "");
|
|
859
1147
|
}
|
|
@@ -872,35 +1160,99 @@ function getApiBaseUrlV2() {
|
|
|
872
1160
|
if (raw.endsWith("/api") || raw.endsWith("/api/v2")) return raw;
|
|
873
1161
|
return `${raw}/api`;
|
|
874
1162
|
}
|
|
875
|
-
function
|
|
876
|
-
const
|
|
877
|
-
|
|
1163
|
+
function requireAuthentication() {
|
|
1164
|
+
const activeProfile2 = configManager.get("oauthProfile") || "default";
|
|
1165
|
+
const oauthConfigured = (configManager.get("oauthProfiles") || []).includes(activeProfile2);
|
|
1166
|
+
const apiKey = process.env.MDEDIT_API_KEY || configManager.getAll().apiKey;
|
|
1167
|
+
if (!apiKey && !oauthConfigured) {
|
|
878
1168
|
throw new Error(
|
|
879
|
-
"
|
|
1169
|
+
"Login required. Run `mdedit auth login`; for headless/CI use --api-key, MDEDIT_API_KEY, or a stored API key."
|
|
880
1170
|
);
|
|
881
1171
|
}
|
|
882
|
-
return String(apiKey);
|
|
883
1172
|
}
|
|
884
|
-
|
|
885
|
-
|
|
1173
|
+
async function resolveAuthentication(forceOAuthRefresh = false) {
|
|
1174
|
+
const explicitApiKey = process.env.MDEDIT_API_KEY;
|
|
1175
|
+
const { storedOAuthAccessToken: storedOAuthAccessToken2 } = await Promise.resolve().then(() => (init_oauth(), oauth_exports));
|
|
1176
|
+
const authentication = selectAuthentication({
|
|
1177
|
+
explicitApiKey,
|
|
1178
|
+
oauthAccessToken: explicitApiKey ? null : await storedOAuthAccessToken2(void 0, forceOAuthRefresh),
|
|
1179
|
+
storedApiKey: configManager.getAll().apiKey
|
|
1180
|
+
});
|
|
1181
|
+
if (authentication) return authentication;
|
|
1182
|
+
throw new Error(
|
|
1183
|
+
"Login required. Run `mdedit auth login`; for headless/CI use --api-key or MDEDIT_API_KEY."
|
|
1184
|
+
);
|
|
1185
|
+
}
|
|
1186
|
+
function getAgentCredentialProvider() {
|
|
1187
|
+
return {
|
|
1188
|
+
getCredential: () => resolveAuthentication(),
|
|
1189
|
+
refreshCredential: () => resolveAuthentication(true)
|
|
1190
|
+
};
|
|
1191
|
+
}
|
|
886
1192
|
function getApiClient() {
|
|
887
1193
|
const baseUrlV2 = getApiBaseUrlV2();
|
|
888
|
-
const
|
|
889
|
-
const cacheKey = `${baseUrlV2}::${apiKey}`;
|
|
1194
|
+
const cacheKey = baseUrlV2;
|
|
890
1195
|
if (_cachedClient && _cachedKey === cacheKey) return _cachedClient;
|
|
891
1196
|
const client = createSdkClient({
|
|
892
1197
|
baseUrlV2,
|
|
893
1198
|
getAuthHeaders: async () => {
|
|
894
|
-
|
|
895
|
-
const headers = {};
|
|
896
|
-
if (key) headers["x-api-key"] = String(key);
|
|
897
|
-
return headers;
|
|
1199
|
+
return (await resolveAuthentication()).headers;
|
|
898
1200
|
}
|
|
899
1201
|
});
|
|
900
1202
|
_cachedKey = cacheKey;
|
|
901
1203
|
_cachedClient = client;
|
|
902
1204
|
return client;
|
|
903
1205
|
}
|
|
1206
|
+
var requireApiKey, _cachedKey, _cachedClient;
|
|
1207
|
+
var init_api = __esm({
|
|
1208
|
+
"src/utils/api.ts"() {
|
|
1209
|
+
"use strict";
|
|
1210
|
+
init_dist();
|
|
1211
|
+
init_config();
|
|
1212
|
+
requireApiKey = requireAuthentication;
|
|
1213
|
+
_cachedKey = null;
|
|
1214
|
+
_cachedClient = null;
|
|
1215
|
+
}
|
|
1216
|
+
});
|
|
1217
|
+
|
|
1218
|
+
// src/index.ts
|
|
1219
|
+
init_dist();
|
|
1220
|
+
import { Command as Command9 } from "commander";
|
|
1221
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
1222
|
+
import { dirname as dirname2, join as join3 } from "path";
|
|
1223
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
1224
|
+
import { AgentClientHttpError } from "@mdedit/agent-client";
|
|
1225
|
+
|
|
1226
|
+
// src/commands/article.ts
|
|
1227
|
+
init_dist();
|
|
1228
|
+
init_output();
|
|
1229
|
+
import { Command } from "commander";
|
|
1230
|
+
import inquirer from "inquirer";
|
|
1231
|
+
import { v4 as uuidv4 } from "uuid";
|
|
1232
|
+
import { readFile, writeFile } from "fs/promises";
|
|
1233
|
+
import { createHash } from "crypto";
|
|
1234
|
+
import { basename, extname } from "path";
|
|
1235
|
+
import {
|
|
1236
|
+
openArticleSession
|
|
1237
|
+
} from "@mdedit/agent-client";
|
|
1238
|
+
|
|
1239
|
+
// src/utils/context.ts
|
|
1240
|
+
init_config();
|
|
1241
|
+
function resolveWorkspaceId(cliWorkspaceId) {
|
|
1242
|
+
return cliWorkspaceId || configManager.get("workspaceId") || process.env.MDEDIT_WORKSPACE_ID;
|
|
1243
|
+
}
|
|
1244
|
+
function requireWorkspaceId(cliWorkspaceId) {
|
|
1245
|
+
const workspaceId = resolveWorkspaceId(cliWorkspaceId);
|
|
1246
|
+
if (!workspaceId) {
|
|
1247
|
+
throw new Error(
|
|
1248
|
+
"workspaceId is required. Pass --workspace <id> or set a default with: mdedit config set workspaceId <id>"
|
|
1249
|
+
);
|
|
1250
|
+
}
|
|
1251
|
+
return workspaceId;
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
// src/commands/article.ts
|
|
1255
|
+
init_api();
|
|
904
1256
|
|
|
905
1257
|
// src/utils/exitCodes.ts
|
|
906
1258
|
import {
|
|
@@ -1073,6 +1425,36 @@ async function writeBlobToFile(blob, filePath) {
|
|
|
1073
1425
|
function sha256Hex(content) {
|
|
1074
1426
|
return createHash("sha256").update(content).digest("hex");
|
|
1075
1427
|
}
|
|
1428
|
+
function inferFileTitle(filePath, content) {
|
|
1429
|
+
const firstHeading = content?.match(/^\s*#\s+(.+?)\s*$/m)?.[1]?.trim();
|
|
1430
|
+
if (firstHeading) return firstHeading;
|
|
1431
|
+
if (filePath === "-") return void 0;
|
|
1432
|
+
const fileName = basename(filePath);
|
|
1433
|
+
const extension = extname(fileName);
|
|
1434
|
+
const stem = (extension ? fileName.slice(0, -extension.length) : fileName).trim();
|
|
1435
|
+
return stem || void 0;
|
|
1436
|
+
}
|
|
1437
|
+
function publishRequest(options) {
|
|
1438
|
+
const seoMetadata = {
|
|
1439
|
+
...options.seoTitle ? { title: options.seoTitle } : {},
|
|
1440
|
+
...options.seoDescription ? { description: options.seoDescription } : {}
|
|
1441
|
+
};
|
|
1442
|
+
return {
|
|
1443
|
+
...options.slug ? { customSlug: options.slug } : {},
|
|
1444
|
+
...Object.keys(seoMetadata).length > 0 ? { seoMetadata } : {}
|
|
1445
|
+
};
|
|
1446
|
+
}
|
|
1447
|
+
async function confirmPublicPublish(articleId) {
|
|
1448
|
+
const { confirm } = await inquirer.prompt([
|
|
1449
|
+
{
|
|
1450
|
+
type: "confirm",
|
|
1451
|
+
name: "confirm",
|
|
1452
|
+
message: `Publish article ${articleId} publicly? Anyone with the link will be able to view it.`,
|
|
1453
|
+
default: false
|
|
1454
|
+
}
|
|
1455
|
+
]);
|
|
1456
|
+
return Boolean(confirm);
|
|
1457
|
+
}
|
|
1076
1458
|
async function readEditOperations(filePath) {
|
|
1077
1459
|
const raw = await readFile(filePath, "utf-8");
|
|
1078
1460
|
const parsed = JSON.parse(raw);
|
|
@@ -1141,17 +1523,24 @@ function createArticleCommands() {
|
|
|
1141
1523
|
output.output(presentArticleDetails(result));
|
|
1142
1524
|
output.info("Hint: use `mdedit article get <articleId> --content-only` to print markdown, or `--include-content` to include it in the output.");
|
|
1143
1525
|
});
|
|
1144
|
-
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) => {
|
|
1145
|
-
|
|
1526
|
+
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) => {
|
|
1527
|
+
requireAuthentication();
|
|
1528
|
+
const credentialProvider = getAgentCredentialProvider();
|
|
1146
1529
|
const client = getApiClient();
|
|
1147
1530
|
const workspaceId = requireWorkspaceId(options.workspace);
|
|
1148
1531
|
if (options.content !== void 0 && options.file !== void 0) {
|
|
1149
1532
|
throw new Error("--content and --file are mutually exclusive. Provide only one.");
|
|
1150
1533
|
}
|
|
1534
|
+
if (!options.publish && (options.slug || options.seoTitle || options.seoDescription)) {
|
|
1535
|
+
throw new Error("--slug, --seo-title, and --seo-description require --publish.");
|
|
1536
|
+
}
|
|
1151
1537
|
let contentText = null;
|
|
1152
1538
|
if (options.content !== void 0) contentText = options.content;
|
|
1153
1539
|
else if (options.file) contentText = await readContentFromFile(options.file);
|
|
1154
1540
|
let title = options.title;
|
|
1541
|
+
if (!title && options.file) {
|
|
1542
|
+
title = inferFileTitle(options.file, contentText);
|
|
1543
|
+
}
|
|
1155
1544
|
if (!title) {
|
|
1156
1545
|
const answers = await inquirer.prompt([
|
|
1157
1546
|
{
|
|
@@ -1164,6 +1553,10 @@ function createArticleCommands() {
|
|
|
1164
1553
|
title = String(answers.title);
|
|
1165
1554
|
}
|
|
1166
1555
|
const articleId = options.id || uuidv4();
|
|
1556
|
+
if (options.publish && !options.yes && !await confirmPublicPublish(articleId)) {
|
|
1557
|
+
output.info("Article creation cancelled; nothing was published.");
|
|
1558
|
+
return;
|
|
1559
|
+
}
|
|
1167
1560
|
const created = await client.article.create(workspaceId, {
|
|
1168
1561
|
articleId,
|
|
1169
1562
|
title: String(title),
|
|
@@ -1174,8 +1567,7 @@ function createArticleCommands() {
|
|
|
1174
1567
|
try {
|
|
1175
1568
|
if (options.collaborative) {
|
|
1176
1569
|
const session = await openArticleSession({
|
|
1177
|
-
|
|
1178
|
-
websocketToken: apiKey,
|
|
1570
|
+
credentialProvider,
|
|
1179
1571
|
workspaceId,
|
|
1180
1572
|
articleId,
|
|
1181
1573
|
agent: { name: "mdedit-cli" },
|
|
@@ -1235,7 +1627,27 @@ function createArticleCommands() {
|
|
|
1235
1627
|
}
|
|
1236
1628
|
output.success("Article created successfully");
|
|
1237
1629
|
if (contentText !== null) output.success("Article content uploaded");
|
|
1238
|
-
|
|
1630
|
+
if (!options.publish) {
|
|
1631
|
+
output.output(created);
|
|
1632
|
+
return;
|
|
1633
|
+
}
|
|
1634
|
+
try {
|
|
1635
|
+
const publication = await client.publish.publish(
|
|
1636
|
+
workspaceId,
|
|
1637
|
+
articleId,
|
|
1638
|
+
publishRequest(options)
|
|
1639
|
+
);
|
|
1640
|
+
output.success("Article published publicly");
|
|
1641
|
+
output.output({
|
|
1642
|
+
...created ?? { articleId, workspaceId },
|
|
1643
|
+
publication
|
|
1644
|
+
});
|
|
1645
|
+
} catch (error) {
|
|
1646
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1647
|
+
throw new Error(
|
|
1648
|
+
`Article ${articleId} was created and kept, but publishing failed: ${message}`
|
|
1649
|
+
);
|
|
1650
|
+
}
|
|
1239
1651
|
});
|
|
1240
1652
|
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) => {
|
|
1241
1653
|
requireApiKey();
|
|
@@ -1274,8 +1686,53 @@ function createArticleCommands() {
|
|
|
1274
1686
|
output.warning("No changes provided. Use --title, --archive, --pin, --file, or --content.");
|
|
1275
1687
|
}
|
|
1276
1688
|
});
|
|
1689
|
+
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) => {
|
|
1690
|
+
requireApiKey();
|
|
1691
|
+
const client = getApiClient();
|
|
1692
|
+
const workspaceId = requireWorkspaceId(options.workspace);
|
|
1693
|
+
if (!options.yes && !await confirmPublicPublish(articleId)) {
|
|
1694
|
+
output.info("Publish cancelled.");
|
|
1695
|
+
return;
|
|
1696
|
+
}
|
|
1697
|
+
const result = await client.publish.publish(
|
|
1698
|
+
workspaceId,
|
|
1699
|
+
articleId,
|
|
1700
|
+
publishRequest(options)
|
|
1701
|
+
);
|
|
1702
|
+
output.success("Article published publicly");
|
|
1703
|
+
output.output(result);
|
|
1704
|
+
});
|
|
1705
|
+
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) => {
|
|
1706
|
+
requireApiKey();
|
|
1707
|
+
const client = getApiClient();
|
|
1708
|
+
const workspaceId = requireWorkspaceId(options.workspace);
|
|
1709
|
+
output.output(await client.publish.status(workspaceId, articleId));
|
|
1710
|
+
});
|
|
1711
|
+
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) => {
|
|
1712
|
+
requireApiKey();
|
|
1713
|
+
const client = getApiClient();
|
|
1714
|
+
const workspaceId = requireWorkspaceId(options.workspace);
|
|
1715
|
+
if (!options.yes) {
|
|
1716
|
+
const { confirm } = await inquirer.prompt([
|
|
1717
|
+
{
|
|
1718
|
+
type: "confirm",
|
|
1719
|
+
name: "confirm",
|
|
1720
|
+
message: `Unpublish article ${articleId}? Its public link will stop working.`,
|
|
1721
|
+
default: false
|
|
1722
|
+
}
|
|
1723
|
+
]);
|
|
1724
|
+
if (!confirm) {
|
|
1725
|
+
output.info("Unpublish cancelled.");
|
|
1726
|
+
return;
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
const result = await client.publish.unpublish(workspaceId, articleId);
|
|
1730
|
+
output.success("Article unpublished");
|
|
1731
|
+
output.output(result);
|
|
1732
|
+
});
|
|
1277
1733
|
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) => {
|
|
1278
|
-
|
|
1734
|
+
requireAuthentication();
|
|
1735
|
+
const credentialProvider = getAgentCredentialProvider();
|
|
1279
1736
|
const workspaceId = requireWorkspaceId(options.workspace);
|
|
1280
1737
|
const pollIntervalMs = Number(options.pollInterval);
|
|
1281
1738
|
if (!Number.isFinite(pollIntervalMs) || pollIntervalMs < 100) {
|
|
@@ -1290,8 +1747,7 @@ function createArticleCommands() {
|
|
|
1290
1747
|
const testEventLimit = Number(process.env.MDEDIT_WATCH_TEST_EVENTS || 0);
|
|
1291
1748
|
try {
|
|
1292
1749
|
session = await openArticleSession({
|
|
1293
|
-
|
|
1294
|
-
websocketToken: apiKey,
|
|
1750
|
+
credentialProvider,
|
|
1295
1751
|
workspaceId,
|
|
1296
1752
|
articleId,
|
|
1297
1753
|
agent: { name: options.agent },
|
|
@@ -1309,7 +1765,8 @@ function createArticleCommands() {
|
|
|
1309
1765
|
}
|
|
1310
1766
|
});
|
|
1311
1767
|
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) => {
|
|
1312
|
-
|
|
1768
|
+
requireAuthentication();
|
|
1769
|
+
const credentialProvider = getAgentCredentialProvider();
|
|
1313
1770
|
const workspaceId = requireWorkspaceId(options.workspace);
|
|
1314
1771
|
const hasInlineOption = options.replace !== void 0 || options.with !== void 0;
|
|
1315
1772
|
if (options.opsFile && hasInlineOption) {
|
|
@@ -1324,8 +1781,7 @@ function createArticleCommands() {
|
|
|
1324
1781
|
let result;
|
|
1325
1782
|
try {
|
|
1326
1783
|
session = await openArticleSession({
|
|
1327
|
-
|
|
1328
|
-
websocketToken: apiKey,
|
|
1784
|
+
credentialProvider,
|
|
1329
1785
|
workspaceId,
|
|
1330
1786
|
articleId,
|
|
1331
1787
|
agent: { name: "mdedit-cli" },
|
|
@@ -1385,6 +1841,8 @@ function createArticleCommands() {
|
|
|
1385
1841
|
}
|
|
1386
1842
|
|
|
1387
1843
|
// src/commands/workspace.ts
|
|
1844
|
+
init_output();
|
|
1845
|
+
init_api();
|
|
1388
1846
|
import { Command as Command2 } from "commander";
|
|
1389
1847
|
import inquirer2 from "inquirer";
|
|
1390
1848
|
|
|
@@ -1492,9 +1950,11 @@ function createWorkspaceCommands() {
|
|
|
1492
1950
|
}
|
|
1493
1951
|
|
|
1494
1952
|
// src/commands/folder.ts
|
|
1953
|
+
init_output();
|
|
1495
1954
|
import { Command as Command3 } from "commander";
|
|
1496
1955
|
import inquirer3 from "inquirer";
|
|
1497
1956
|
import { v4 as uuidv42 } from "uuid";
|
|
1957
|
+
init_api();
|
|
1498
1958
|
|
|
1499
1959
|
// src/presenters/folder.ts
|
|
1500
1960
|
function presentFolderListRow(folder) {
|
|
@@ -1607,6 +2067,9 @@ function createFolderCommands() {
|
|
|
1607
2067
|
}
|
|
1608
2068
|
|
|
1609
2069
|
// src/commands/config.ts
|
|
2070
|
+
init_config();
|
|
2071
|
+
init_output();
|
|
2072
|
+
init_api();
|
|
1610
2073
|
import { Command as Command4 } from "commander";
|
|
1611
2074
|
import inquirer4 from "inquirer";
|
|
1612
2075
|
function redactSecret(value) {
|
|
@@ -1716,6 +2179,8 @@ function createConfigCommands() {
|
|
|
1716
2179
|
}
|
|
1717
2180
|
|
|
1718
2181
|
// src/commands/apikey.ts
|
|
2182
|
+
init_output();
|
|
2183
|
+
init_api();
|
|
1719
2184
|
import { Command as Command5 } from "commander";
|
|
1720
2185
|
import inquirer5 from "inquirer";
|
|
1721
2186
|
|
|
@@ -1827,6 +2292,7 @@ function createApiKeyCommands() {
|
|
|
1827
2292
|
}
|
|
1828
2293
|
|
|
1829
2294
|
// src/commands/skill.ts
|
|
2295
|
+
init_output();
|
|
1830
2296
|
import { Command as Command6 } from "commander";
|
|
1831
2297
|
import { readFileSync as readFileSync2, mkdirSync as mkdirSync2, existsSync as existsSync2, appendFileSync, writeFileSync as writeFileSync2 } from "fs";
|
|
1832
2298
|
import { dirname, join as join2, resolve } from "path";
|
|
@@ -1922,13 +2388,20 @@ function createSkillCommands() {
|
|
|
1922
2388
|
}
|
|
1923
2389
|
|
|
1924
2390
|
// src/commands/review.ts
|
|
2391
|
+
init_output();
|
|
1925
2392
|
import { Command as Command7 } from "commander";
|
|
1926
2393
|
import {
|
|
1927
2394
|
openArticleReviewSession
|
|
1928
2395
|
} from "@mdedit/agent-client";
|
|
2396
|
+
init_api();
|
|
1929
2397
|
async function withReview(articleId, workspaceId, operation) {
|
|
1930
|
-
|
|
1931
|
-
const review = openArticleReviewSession({
|
|
2398
|
+
requireAuthentication();
|
|
2399
|
+
const review = openArticleReviewSession({
|
|
2400
|
+
credentialProvider: getAgentCredentialProvider(),
|
|
2401
|
+
workspaceId,
|
|
2402
|
+
articleId,
|
|
2403
|
+
apiUrl: getApiUrlRaw()
|
|
2404
|
+
});
|
|
1932
2405
|
return { mode: "rest", result: await operation(review) };
|
|
1933
2406
|
}
|
|
1934
2407
|
function quoteAnchor(options) {
|
|
@@ -2021,7 +2494,54 @@ function createSuggestCommand() {
|
|
|
2021
2494
|
});
|
|
2022
2495
|
}
|
|
2023
2496
|
|
|
2497
|
+
// src/commands/auth.ts
|
|
2498
|
+
init_output();
|
|
2499
|
+
init_oauth();
|
|
2500
|
+
import { Command as Command8 } from "commander";
|
|
2501
|
+
var defaultRuntime = {
|
|
2502
|
+
login: loginWithOAuth,
|
|
2503
|
+
logout: logoutOAuth,
|
|
2504
|
+
status: oauthStatus
|
|
2505
|
+
};
|
|
2506
|
+
function profileOption(command) {
|
|
2507
|
+
return command.option("--profile <name>", "OAuth profile name");
|
|
2508
|
+
}
|
|
2509
|
+
function createAuthCommands(runtime = defaultRuntime) {
|
|
2510
|
+
const auth = new Command8("auth").description("Manage OAuth sign-in profiles").action(() => auth.help());
|
|
2511
|
+
profileOption(auth.command("login").description("Sign in with browser authorization-code + PKCE").option(
|
|
2512
|
+
"--no-browser",
|
|
2513
|
+
"Print the same browser URL; the browser must run on this callback-capable machine"
|
|
2514
|
+
).option("--scopes <scopes>", "Comma-separated OAuth scopes")).action(async (options) => {
|
|
2515
|
+
const scopes = options.scopes ? String(options.scopes).split(",").map((scope) => scope.trim()).filter(Boolean) : void 0;
|
|
2516
|
+
const result = await runtime.login({
|
|
2517
|
+
noBrowser: Boolean(options.browser === false),
|
|
2518
|
+
profile: options.profile,
|
|
2519
|
+
...scopes ? { scopes } : {}
|
|
2520
|
+
});
|
|
2521
|
+
if (!output.isJson()) output.success(`Signed in with OAuth profile ${result.profile}`);
|
|
2522
|
+
output.output(result);
|
|
2523
|
+
});
|
|
2524
|
+
profileOption(auth.command("status").description("Show OAuth status without printing tokens")).action(async (options) => {
|
|
2525
|
+
const result = await runtime.status(options.profile);
|
|
2526
|
+
output.output(result);
|
|
2527
|
+
});
|
|
2528
|
+
profileOption(auth.command("logout").description("Revoke refresh access and remove stored OAuth credentials").option("--all", "Revoke and remove every stored OAuth profile")).action(async (options) => {
|
|
2529
|
+
const result = await runtime.logout({
|
|
2530
|
+
all: Boolean(options.all),
|
|
2531
|
+
profile: options.profile
|
|
2532
|
+
});
|
|
2533
|
+
if (!output.isJson()) {
|
|
2534
|
+
output.success(result.all ? "Logged out every OAuth profile" : `Logged out OAuth profile ${result.profile}`);
|
|
2535
|
+
}
|
|
2536
|
+
output.output(result);
|
|
2537
|
+
});
|
|
2538
|
+
return auth;
|
|
2539
|
+
}
|
|
2540
|
+
|
|
2024
2541
|
// src/index.ts
|
|
2542
|
+
init_output();
|
|
2543
|
+
init_config();
|
|
2544
|
+
init_api();
|
|
2025
2545
|
var __filename2 = fileURLToPath2(import.meta.url);
|
|
2026
2546
|
var __dirname2 = dirname2(__filename2);
|
|
2027
2547
|
var version = "0.0.0";
|
|
@@ -2030,7 +2550,7 @@ try {
|
|
|
2030
2550
|
version = packageJson.version || version;
|
|
2031
2551
|
} catch {
|
|
2032
2552
|
}
|
|
2033
|
-
var program = new
|
|
2553
|
+
var program = new Command9();
|
|
2034
2554
|
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) => {
|
|
2035
2555
|
const opts = typeof thisCommand.optsWithGlobals === "function" ? (
|
|
2036
2556
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
@@ -2051,6 +2571,7 @@ program.addCommand(createApiKeyCommands());
|
|
|
2051
2571
|
program.addCommand(createSkillCommands());
|
|
2052
2572
|
program.addCommand(createReviewCommands());
|
|
2053
2573
|
program.addCommand(createSuggestCommand());
|
|
2574
|
+
program.addCommand(createAuthCommands());
|
|
2054
2575
|
program.command("health").description("Check API health status").action(async () => {
|
|
2055
2576
|
const base = getApiBaseUrlRoot();
|
|
2056
2577
|
const response = await fetch(`${base}/health`, { method: "GET" });
|
|
@@ -2069,9 +2590,11 @@ program.command("health").description("Check API health status").action(async ()
|
|
|
2069
2590
|
});
|
|
2070
2591
|
program.command("info").description("Display CLI and API information").action(async () => {
|
|
2071
2592
|
const apiUrl = configManager.get("apiUrl") || process.env.MDEDIT_API_URL || "https://apiv2.mdedit.ai";
|
|
2072
|
-
const apiKey = configManager.
|
|
2593
|
+
const apiKey = process.env.MDEDIT_API_KEY || configManager.getAll().apiKey;
|
|
2594
|
+
const activeProfile2 = configManager.get("oauthProfile") || "default";
|
|
2595
|
+
const oauthConfigured = (configManager.get("oauthProfiles") || []).includes(activeProfile2);
|
|
2073
2596
|
const workspaceId = configManager.get("workspaceId") || process.env.MDEDIT_WORKSPACE_ID || null;
|
|
2074
|
-
const authMethod = apiKey ? "apiKey" : "none";
|
|
2597
|
+
const authMethod = process.env.MDEDIT_API_KEY ? "apiKey" : oauthConfigured ? "oauth" : apiKey ? "apiKey" : "none";
|
|
2075
2598
|
let health = void 0;
|
|
2076
2599
|
let apiStatus = "unavailable";
|
|
2077
2600
|
try {
|
|
@@ -2082,7 +2605,7 @@ program.command("info").description("Display CLI and API information").action(as
|
|
|
2082
2605
|
apiStatus = "unavailable";
|
|
2083
2606
|
}
|
|
2084
2607
|
let authOk = null;
|
|
2085
|
-
if (
|
|
2608
|
+
if (authMethod !== "none") {
|
|
2086
2609
|
try {
|
|
2087
2610
|
const client = getApiClient();
|
|
2088
2611
|
await client.workspace.list();
|
|
@@ -2107,7 +2630,7 @@ program.command("info").description("Display CLI and API information").action(as
|
|
|
2107
2630
|
output.info(`CLI Version: ${version}`);
|
|
2108
2631
|
output.info(`API URL: ${apiUrl}`);
|
|
2109
2632
|
if (workspaceId) output.info(`Workspace: ${workspaceId}`);
|
|
2110
|
-
output.info(`Auth Method: ${authMethod === "apiKey" ? "API Key" : "None"}`);
|
|
2633
|
+
output.info(`Auth Method: ${authMethod === "apiKey" ? "API Key" : authMethod === "oauth" ? `OAuth (${activeProfile2})` : "None"}`);
|
|
2111
2634
|
if (apiStatus === "healthy") output.success("API Status: Healthy");
|
|
2112
2635
|
else output.warning("API Status: Unavailable");
|
|
2113
2636
|
if (authOk === true) output.success("Auth: OK");
|
|
@@ -2160,9 +2683,13 @@ async function main() {
|
|
|
2160
2683
|
} else if (err instanceof FetchError2) {
|
|
2161
2684
|
output.error(`API request failed (${err.status}): ${err.message}`);
|
|
2162
2685
|
if (err.status === 401) {
|
|
2163
|
-
output.info("Hint:
|
|
2686
|
+
output.info("Hint: run `mdedit auth login`; for headless/CI set MDEDIT_API_KEY or pass `--api-key <key>`.");
|
|
2164
2687
|
} else if (err.status === 403) {
|
|
2165
|
-
|
|
2688
|
+
if (err.message.includes("publishing:write")) {
|
|
2689
|
+
output.info("Hint: publishing requires an API key with publishing:write scope.");
|
|
2690
|
+
} else {
|
|
2691
|
+
output.info("Hint: check that the API key has the required scope and permission for this workspace/resource.");
|
|
2692
|
+
}
|
|
2166
2693
|
} else if (err.status === 404) {
|
|
2167
2694
|
output.info("Hint: verify your `apiUrl` and that the API build matches the CLI routes.");
|
|
2168
2695
|
}
|