mdtolink 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,479 @@
1
+ #!/usr/bin/env node
2
+ import fs, { constants } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import process from "node:process";
6
+ import { Buffer } from "node:buffer";
7
+ import { fileURLToPath } from "node:url";
8
+ import { promisify } from "node:util";
9
+ import childProcess, { execFile } from "node:child_process";
10
+ import fs$1 from "node:fs";
11
+
12
+ //#region ../../node_modules/.pnpm/is-docker@3.0.0/node_modules/is-docker/index.js
13
+ let isDockerCached;
14
+ function hasDockerEnv() {
15
+ try {
16
+ fs$1.statSync("/.dockerenv");
17
+ return true;
18
+ } catch {
19
+ return false;
20
+ }
21
+ }
22
+ function hasDockerCGroup() {
23
+ try {
24
+ return fs$1.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
25
+ } catch {
26
+ return false;
27
+ }
28
+ }
29
+ function isDocker() {
30
+ if (isDockerCached === void 0) isDockerCached = hasDockerEnv() || hasDockerCGroup();
31
+ return isDockerCached;
32
+ }
33
+
34
+ //#endregion
35
+ //#region ../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
36
+ let cachedResult;
37
+ const hasContainerEnv = () => {
38
+ try {
39
+ fs$1.statSync("/run/.containerenv");
40
+ return true;
41
+ } catch {
42
+ return false;
43
+ }
44
+ };
45
+ function isInsideContainer() {
46
+ if (cachedResult === void 0) cachedResult = hasContainerEnv() || isDocker();
47
+ return cachedResult;
48
+ }
49
+
50
+ //#endregion
51
+ //#region ../../node_modules/.pnpm/is-wsl@3.1.1/node_modules/is-wsl/index.js
52
+ const isWsl = () => {
53
+ if (process.platform !== "linux") return false;
54
+ if (os.release().toLowerCase().includes("microsoft")) {
55
+ if (isInsideContainer()) return false;
56
+ return true;
57
+ }
58
+ try {
59
+ if (fs$1.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft")) return !isInsideContainer();
60
+ } catch {}
61
+ if (fs$1.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop") || fs$1.existsSync("/run/WSL")) return !isInsideContainer();
62
+ return false;
63
+ };
64
+ var is_wsl_default = process.env.__IS_WSL_TEST__ ? isWsl : isWsl();
65
+
66
+ //#endregion
67
+ //#region ../../node_modules/.pnpm/wsl-utils@0.1.0/node_modules/wsl-utils/index.js
68
+ const wslDrivesMountPoint = (() => {
69
+ const defaultMountPoint = "/mnt/";
70
+ let mountPoint;
71
+ return async function() {
72
+ if (mountPoint) return mountPoint;
73
+ const configFilePath = "/etc/wsl.conf";
74
+ let isConfigFileExists = false;
75
+ try {
76
+ await fs.access(configFilePath, constants.F_OK);
77
+ isConfigFileExists = true;
78
+ } catch {}
79
+ if (!isConfigFileExists) return defaultMountPoint;
80
+ const configContent = await fs.readFile(configFilePath, { encoding: "utf8" });
81
+ const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
82
+ if (!configMountPoint) return defaultMountPoint;
83
+ mountPoint = configMountPoint.groups.mountPoint.trim();
84
+ mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
85
+ return mountPoint;
86
+ };
87
+ })();
88
+ const powerShellPathFromWsl = async () => {
89
+ return `${await wslDrivesMountPoint()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
90
+ };
91
+ const powerShellPath = async () => {
92
+ if (is_wsl_default) return powerShellPathFromWsl();
93
+ return `${process.env.SYSTEMROOT || process.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
94
+ };
95
+
96
+ //#endregion
97
+ //#region ../../node_modules/.pnpm/define-lazy-prop@3.0.0/node_modules/define-lazy-prop/index.js
98
+ function defineLazyProperty(object, propertyName, valueGetter) {
99
+ const define = (value) => Object.defineProperty(object, propertyName, {
100
+ value,
101
+ enumerable: true,
102
+ writable: true
103
+ });
104
+ Object.defineProperty(object, propertyName, {
105
+ configurable: true,
106
+ enumerable: true,
107
+ get() {
108
+ const result = valueGetter();
109
+ define(result);
110
+ return result;
111
+ },
112
+ set(value) {
113
+ define(value);
114
+ }
115
+ });
116
+ return object;
117
+ }
118
+
119
+ //#endregion
120
+ //#region ../../node_modules/.pnpm/default-browser-id@5.0.1/node_modules/default-browser-id/index.js
121
+ const execFileAsync$3 = promisify(execFile);
122
+ async function defaultBrowserId() {
123
+ if (process.platform !== "darwin") throw new Error("macOS only");
124
+ const { stdout } = await execFileAsync$3("defaults", [
125
+ "read",
126
+ "com.apple.LaunchServices/com.apple.launchservices.secure",
127
+ "LSHandlers"
128
+ ]);
129
+ const browserId = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout)?.groups.id ?? "com.apple.Safari";
130
+ if (browserId === "com.apple.safari") return "com.apple.Safari";
131
+ return browserId;
132
+ }
133
+
134
+ //#endregion
135
+ //#region ../../node_modules/.pnpm/run-applescript@7.1.0/node_modules/run-applescript/index.js
136
+ const execFileAsync$2 = promisify(execFile);
137
+ async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
138
+ if (process.platform !== "darwin") throw new Error("macOS only");
139
+ const outputArguments = humanReadableOutput ? [] : ["-ss"];
140
+ const execOptions = {};
141
+ if (signal) execOptions.signal = signal;
142
+ const { stdout } = await execFileAsync$2("osascript", [
143
+ "-e",
144
+ script,
145
+ outputArguments
146
+ ], execOptions);
147
+ return stdout.trim();
148
+ }
149
+
150
+ //#endregion
151
+ //#region ../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js
152
+ async function bundleName(bundleId) {
153
+ return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
154
+ }
155
+
156
+ //#endregion
157
+ //#region ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/windows.js
158
+ const execFileAsync$1 = promisify(execFile);
159
+ const windowsBrowserProgIds = {
160
+ MSEdgeHTM: {
161
+ name: "Edge",
162
+ id: "com.microsoft.edge"
163
+ },
164
+ MSEdgeBHTML: {
165
+ name: "Edge Beta",
166
+ id: "com.microsoft.edge.beta"
167
+ },
168
+ MSEdgeDHTML: {
169
+ name: "Edge Dev",
170
+ id: "com.microsoft.edge.dev"
171
+ },
172
+ AppXq0fevzme2pys62n3e0fbqa7peapykr8v: {
173
+ name: "Edge",
174
+ id: "com.microsoft.edge.old"
175
+ },
176
+ ChromeHTML: {
177
+ name: "Chrome",
178
+ id: "com.google.chrome"
179
+ },
180
+ ChromeBHTML: {
181
+ name: "Chrome Beta",
182
+ id: "com.google.chrome.beta"
183
+ },
184
+ ChromeDHTML: {
185
+ name: "Chrome Dev",
186
+ id: "com.google.chrome.dev"
187
+ },
188
+ ChromiumHTM: {
189
+ name: "Chromium",
190
+ id: "org.chromium.Chromium"
191
+ },
192
+ BraveHTML: {
193
+ name: "Brave",
194
+ id: "com.brave.Browser"
195
+ },
196
+ BraveBHTML: {
197
+ name: "Brave Beta",
198
+ id: "com.brave.Browser.beta"
199
+ },
200
+ BraveDHTML: {
201
+ name: "Brave Dev",
202
+ id: "com.brave.Browser.dev"
203
+ },
204
+ BraveSSHTM: {
205
+ name: "Brave Nightly",
206
+ id: "com.brave.Browser.nightly"
207
+ },
208
+ FirefoxURL: {
209
+ name: "Firefox",
210
+ id: "org.mozilla.firefox"
211
+ },
212
+ OperaStable: {
213
+ name: "Opera",
214
+ id: "com.operasoftware.Opera"
215
+ },
216
+ VivaldiHTM: {
217
+ name: "Vivaldi",
218
+ id: "com.vivaldi.Vivaldi"
219
+ },
220
+ "IE.HTTP": {
221
+ name: "Internet Explorer",
222
+ id: "com.microsoft.ie"
223
+ }
224
+ };
225
+ const _windowsBrowserProgIdMap = new Map(Object.entries(windowsBrowserProgIds));
226
+ var UnknownBrowserError = class extends Error {};
227
+ async function defaultBrowser$1(_execFileAsync = execFileAsync$1) {
228
+ const { stdout } = await _execFileAsync("reg", [
229
+ "QUERY",
230
+ " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
231
+ "/v",
232
+ "ProgId"
233
+ ]);
234
+ const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
235
+ if (!match) throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
236
+ const { id } = match.groups;
237
+ const dotIndex = id.lastIndexOf(".");
238
+ const hyphenIndex = id.lastIndexOf("-");
239
+ const baseIdByDot = dotIndex === -1 ? void 0 : id.slice(0, dotIndex);
240
+ const baseIdByHyphen = hyphenIndex === -1 ? void 0 : id.slice(0, hyphenIndex);
241
+ return windowsBrowserProgIds[id] ?? windowsBrowserProgIds[baseIdByDot] ?? windowsBrowserProgIds[baseIdByHyphen] ?? {
242
+ name: id,
243
+ id
244
+ };
245
+ }
246
+
247
+ //#endregion
248
+ //#region ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/index.js
249
+ const execFileAsync = promisify(execFile);
250
+ const titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
251
+ async function defaultBrowser() {
252
+ if (process.platform === "darwin") {
253
+ const id = await defaultBrowserId();
254
+ return {
255
+ name: await bundleName(id),
256
+ id
257
+ };
258
+ }
259
+ if (process.platform === "linux") {
260
+ const { stdout } = await execFileAsync("xdg-mime", [
261
+ "query",
262
+ "default",
263
+ "x-scheme-handler/http"
264
+ ]);
265
+ const id = stdout.trim();
266
+ return {
267
+ name: titleize(id.replace(/.desktop$/, "").replace("-", " ")),
268
+ id
269
+ };
270
+ }
271
+ if (process.platform === "win32") return defaultBrowser$1();
272
+ throw new Error("Only macOS, Linux, and Windows are supported");
273
+ }
274
+
275
+ //#endregion
276
+ //#region ../../node_modules/.pnpm/open@10.2.0/node_modules/open/index.js
277
+ const execFile$1 = promisify(childProcess.execFile);
278
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
279
+ const localXdgOpenPath = path.join(__dirname, "xdg-open");
280
+ const { platform, arch } = process;
281
+ /**
282
+ Get the default browser name in Windows from WSL.
283
+
284
+ @returns {Promise<string>} Browser name.
285
+ */
286
+ async function getWindowsDefaultBrowserFromWsl() {
287
+ const powershellPath = await powerShellPath();
288
+ const rawCommand = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
289
+ const { stdout } = await execFile$1(powershellPath, [
290
+ "-NoProfile",
291
+ "-NonInteractive",
292
+ "-ExecutionPolicy",
293
+ "Bypass",
294
+ "-EncodedCommand",
295
+ Buffer.from(rawCommand, "utf16le").toString("base64")
296
+ ], { encoding: "utf8" });
297
+ const progId = stdout.trim();
298
+ const browserMap = {
299
+ ChromeHTML: "com.google.chrome",
300
+ BraveHTML: "com.brave.Browser",
301
+ MSEdgeHTM: "com.microsoft.edge",
302
+ FirefoxURL: "org.mozilla.firefox"
303
+ };
304
+ return browserMap[progId] ? { id: browserMap[progId] } : {};
305
+ }
306
+ const pTryEach = async (array, mapper) => {
307
+ let latestError;
308
+ for (const item of array) try {
309
+ return await mapper(item);
310
+ } catch (error) {
311
+ latestError = error;
312
+ }
313
+ throw latestError;
314
+ };
315
+ const baseOpen = async (options) => {
316
+ options = {
317
+ wait: false,
318
+ background: false,
319
+ newInstance: false,
320
+ allowNonzeroExitCode: false,
321
+ ...options
322
+ };
323
+ if (Array.isArray(options.app)) return pTryEach(options.app, (singleApp) => baseOpen({
324
+ ...options,
325
+ app: singleApp
326
+ }));
327
+ let { name: app, arguments: appArguments = [] } = options.app ?? {};
328
+ appArguments = [...appArguments];
329
+ if (Array.isArray(app)) return pTryEach(app, (appName) => baseOpen({
330
+ ...options,
331
+ app: {
332
+ name: appName,
333
+ arguments: appArguments
334
+ }
335
+ }));
336
+ if (app === "browser" || app === "browserPrivate") {
337
+ const ids = {
338
+ "com.google.chrome": "chrome",
339
+ "google-chrome.desktop": "chrome",
340
+ "com.brave.Browser": "brave",
341
+ "org.mozilla.firefox": "firefox",
342
+ "firefox.desktop": "firefox",
343
+ "com.microsoft.msedge": "edge",
344
+ "com.microsoft.edge": "edge",
345
+ "com.microsoft.edgemac": "edge",
346
+ "microsoft-edge.desktop": "edge"
347
+ };
348
+ const flags = {
349
+ chrome: "--incognito",
350
+ brave: "--incognito",
351
+ firefox: "--private-window",
352
+ edge: "--inPrivate"
353
+ };
354
+ const browser = is_wsl_default ? await getWindowsDefaultBrowserFromWsl() : await defaultBrowser();
355
+ if (browser.id in ids) {
356
+ const browserName = ids[browser.id];
357
+ if (app === "browserPrivate") appArguments.push(flags[browserName]);
358
+ return baseOpen({
359
+ ...options,
360
+ app: {
361
+ name: apps[browserName],
362
+ arguments: appArguments
363
+ }
364
+ });
365
+ }
366
+ throw new Error(`${browser.name} is not supported as a default browser`);
367
+ }
368
+ let command;
369
+ const cliArguments = [];
370
+ const childProcessOptions = {};
371
+ if (platform === "darwin") {
372
+ command = "open";
373
+ if (options.wait) cliArguments.push("--wait-apps");
374
+ if (options.background) cliArguments.push("--background");
375
+ if (options.newInstance) cliArguments.push("--new");
376
+ if (app) cliArguments.push("-a", app);
377
+ } else if (platform === "win32" || is_wsl_default && !isInsideContainer() && !app) {
378
+ command = await powerShellPath();
379
+ cliArguments.push("-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand");
380
+ if (!is_wsl_default) childProcessOptions.windowsVerbatimArguments = true;
381
+ const encodedArguments = ["Start"];
382
+ if (options.wait) encodedArguments.push("-Wait");
383
+ if (app) {
384
+ encodedArguments.push(`"\`"${app}\`""`);
385
+ if (options.target) appArguments.push(options.target);
386
+ } else if (options.target) encodedArguments.push(`"${options.target}"`);
387
+ if (appArguments.length > 0) {
388
+ appArguments = appArguments.map((argument) => `"\`"${argument}\`""`);
389
+ encodedArguments.push("-ArgumentList", appArguments.join(","));
390
+ }
391
+ options.target = Buffer.from(encodedArguments.join(" "), "utf16le").toString("base64");
392
+ } else {
393
+ if (app) command = app;
394
+ else {
395
+ const isBundled = !__dirname || __dirname === "/";
396
+ let exeLocalXdgOpen = false;
397
+ try {
398
+ await fs.access(localXdgOpenPath, constants.X_OK);
399
+ exeLocalXdgOpen = true;
400
+ } catch {}
401
+ command = process.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen) ? "xdg-open" : localXdgOpenPath;
402
+ }
403
+ if (appArguments.length > 0) cliArguments.push(...appArguments);
404
+ if (!options.wait) {
405
+ childProcessOptions.stdio = "ignore";
406
+ childProcessOptions.detached = true;
407
+ }
408
+ }
409
+ if (platform === "darwin" && appArguments.length > 0) cliArguments.push("--args", ...appArguments);
410
+ if (options.target) cliArguments.push(options.target);
411
+ const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
412
+ if (options.wait) return new Promise((resolve$1, reject) => {
413
+ subprocess.once("error", reject);
414
+ subprocess.once("close", (exitCode) => {
415
+ if (!options.allowNonzeroExitCode && exitCode > 0) {
416
+ reject(/* @__PURE__ */ new Error(`Exited with code ${exitCode}`));
417
+ return;
418
+ }
419
+ resolve$1(subprocess);
420
+ });
421
+ });
422
+ subprocess.unref();
423
+ return subprocess;
424
+ };
425
+ const open = (target, options) => {
426
+ if (typeof target !== "string") throw new TypeError("Expected a `target`");
427
+ return baseOpen({
428
+ ...options,
429
+ target
430
+ });
431
+ };
432
+ function detectArchBinary(binary) {
433
+ if (typeof binary === "string" || Array.isArray(binary)) return binary;
434
+ const { [arch]: archBinary } = binary;
435
+ if (!archBinary) throw new Error(`${arch} is not supported`);
436
+ return archBinary;
437
+ }
438
+ function detectPlatformBinary({ [platform]: platformBinary }, { wsl }) {
439
+ if (wsl && is_wsl_default) return detectArchBinary(wsl);
440
+ if (!platformBinary) throw new Error(`${platform} is not supported`);
441
+ return detectArchBinary(platformBinary);
442
+ }
443
+ const apps = {};
444
+ defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
445
+ darwin: "google chrome",
446
+ win32: "chrome",
447
+ linux: [
448
+ "google-chrome",
449
+ "google-chrome-stable",
450
+ "chromium"
451
+ ]
452
+ }, { wsl: {
453
+ ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
454
+ x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
455
+ } }));
456
+ defineLazyProperty(apps, "brave", () => detectPlatformBinary({
457
+ darwin: "brave browser",
458
+ win32: "brave",
459
+ linux: ["brave-browser", "brave"]
460
+ }, { wsl: {
461
+ ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
462
+ x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
463
+ } }));
464
+ defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
465
+ darwin: "firefox",
466
+ win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,
467
+ linux: "firefox"
468
+ }, { wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe" }));
469
+ defineLazyProperty(apps, "edge", () => detectPlatformBinary({
470
+ darwin: "microsoft edge",
471
+ win32: "msedge",
472
+ linux: ["microsoft-edge", "microsoft-edge-dev"]
473
+ }, { wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" }));
474
+ defineLazyProperty(apps, "browser", () => "browser");
475
+ defineLazyProperty(apps, "browserPrivate", () => "browserPrivate");
476
+ var open_default = open;
477
+
478
+ //#endregion
479
+ export { open_default as default };
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env node
2
+ import { t as createApiClient } from "./api-CdA_O32l.mjs";
3
+ import { a as getDocumentMap, l as setDocumentMapping, o as getToken } from "./config-CTqVqsq8.mjs";
4
+ import { n as formatDocumentUrl } from "./format-C4j0hJTz.mjs";
5
+ import { confirm, isCancel, log, spinner } from "@clack/prompts";
6
+ import { access, readFile } from "node:fs/promises";
7
+ import { basename, extname, resolve } from "node:path";
8
+
9
+ //#region src/cli/commands/publish.ts
10
+ async function publish(filePath, options) {
11
+ const absolutePath = resolve(filePath);
12
+ try {
13
+ await access(absolutePath);
14
+ } catch {
15
+ log.error(`File not found: ${absolutePath}`);
16
+ process.exitCode = 1;
17
+ return;
18
+ }
19
+ let token = await getToken();
20
+ if (!token) {
21
+ const shouldLogin = await confirm({ message: "You are not logged in. Would you like to authorize now?" });
22
+ if (isCancel(shouldLogin) || !shouldLogin) {
23
+ log.info("Publish cancelled. Run `mdtolink login` to authenticate.");
24
+ return;
25
+ }
26
+ const { login } = await import("./login-DhnCjQAQ.mjs");
27
+ await login();
28
+ token = await getToken();
29
+ if (!token) {
30
+ log.error("Authentication failed. Cannot publish.");
31
+ process.exitCode = 1;
32
+ return;
33
+ }
34
+ }
35
+ const content = await readFile(absolutePath, "utf-8");
36
+ if (content.trim().length === 0) {
37
+ log.error("File is empty.");
38
+ process.exitCode = 1;
39
+ return;
40
+ }
41
+ const title = options.title ?? basename(absolutePath, extname(absolutePath));
42
+ const existingMapping = (await getDocumentMap())[absolutePath];
43
+ const api = createApiClient(token);
44
+ const spin = spinner();
45
+ if (existingMapping) {
46
+ spin.start("Updating document...");
47
+ await updateExisting(api, absolutePath, existingMapping.documentId, content, title, options.slug, spin);
48
+ } else {
49
+ spin.start("Publishing document...");
50
+ await publishNew(api, absolutePath, content, title, options.slug, spin);
51
+ }
52
+ }
53
+ async function updateExisting(api, absolutePath, documentId, content, title, slug, spin) {
54
+ try {
55
+ const result = await api.documents.update({
56
+ params: { id: documentId },
57
+ body: {
58
+ content,
59
+ title,
60
+ slug
61
+ }
62
+ });
63
+ if (result.status === 200) {
64
+ const doc = result.body;
65
+ const url = formatDocumentUrl(doc);
66
+ await setDocumentMapping(absolutePath, {
67
+ documentId: doc.id,
68
+ slug: doc.slug,
69
+ url,
70
+ lastPublished: (/* @__PURE__ */ new Date()).toISOString()
71
+ });
72
+ spin.stop("Document updated!");
73
+ log.success(`Updated: ${url}`);
74
+ return;
75
+ }
76
+ spin.stop("Update failed.");
77
+ if (result.status === 401) {
78
+ log.error("Session expired. Run `mdtolink login` to re-authenticate.");
79
+ process.exitCode = 1;
80
+ return;
81
+ }
82
+ if (result.status === 404) {
83
+ log.warning("Previous document no longer exists on server. Creating a new one...");
84
+ const newSpin = spinner();
85
+ newSpin.start("Publishing document...");
86
+ await publishNew(api, absolutePath, content, title, slug, newSpin);
87
+ return;
88
+ }
89
+ const body = result.body;
90
+ log.error(body.message ?? body.error);
91
+ process.exitCode = 1;
92
+ } catch {
93
+ spin.stop("Update failed.");
94
+ log.error("Could not connect to server. Check MDTOLINK_SERVER_URL.");
95
+ process.exitCode = 1;
96
+ }
97
+ }
98
+ async function publishNew(api, absolutePath, content, title, slug, spin) {
99
+ try {
100
+ const result = await api.documents.create({ body: {
101
+ content,
102
+ title,
103
+ slug,
104
+ isPublic: true
105
+ } });
106
+ if (result.status === 201) {
107
+ const doc = result.body;
108
+ const url = formatDocumentUrl(doc);
109
+ await setDocumentMapping(absolutePath, {
110
+ documentId: doc.id,
111
+ slug: doc.slug,
112
+ url,
113
+ lastPublished: (/* @__PURE__ */ new Date()).toISOString()
114
+ });
115
+ spin.stop("Published!");
116
+ log.success(`Published: ${url}`);
117
+ return;
118
+ }
119
+ spin.stop("Publish failed.");
120
+ const body = result.body;
121
+ if (result.status === 401) log.error("Session expired. Run `mdtolink login` to re-authenticate.");
122
+ else if (result.status === 403) {
123
+ log.error(body.message ?? body.error);
124
+ log.info("Upgrade at https://mdtolink.com/pricing");
125
+ } else log.error(body.message ?? body.error);
126
+ process.exitCode = 1;
127
+ } catch {
128
+ spin.stop("Publish failed.");
129
+ log.error("Could not connect to server. Check MDTOLINK_SERVER_URL.");
130
+ process.exitCode = 1;
131
+ }
132
+ }
133
+
134
+ //#endregion
135
+ export { publish };