inkmap-mcp 0.2.6 → 0.2.8

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,1764 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // packages/vscode/src/extension.ts
31
+ var extension_exports = {};
32
+ __export(extension_exports, {
33
+ activate: () => activate,
34
+ deactivate: () => deactivate
35
+ });
36
+ module.exports = __toCommonJS(extension_exports);
37
+
38
+ // packages/core/dist/product.js
39
+ var PRODUCT = {
40
+ id: "inkmap-pro",
41
+ entitlement: "inkmap.pro",
42
+ /** JSON list of sponsor ads shown in the free edition; empty means house ads only. */
43
+ adFeedUrl: ""
44
+ };
45
+ var YUNFAN_BILLING_ORIGIN = "https://zhiyuanv.com";
46
+ function billingFlowUrl(raw, origin, mode, legacy = false) {
47
+ if (typeof raw !== "string")
48
+ throw new Error("Invalid Yunfan account link.");
49
+ const url = new URL(raw);
50
+ const base = mode === "restore" && !legacy ? "login" : "checkout";
51
+ if (url.protocol !== "https:" || url.origin !== origin || url.username || url.password || url.search || url.hash || !new RegExp(`^/billing/${base}/[0-9a-f]{32}$`).test(url.pathname)) {
52
+ throw new Error("Invalid Yunfan account link.");
53
+ }
54
+ return url.href;
55
+ }
56
+ var DAY_MS = 24 * 60 * 60 * 1e3;
57
+ var TRIAL_MS = 7 * DAY_MS;
58
+ function hasAccess(state, now = Date.now()) {
59
+ return state.pro || (state.trialUntil ?? 0) > now;
60
+ }
61
+ function sanitizeAds(input) {
62
+ if (!Array.isArray(input))
63
+ return [];
64
+ const str = (v, max) => typeof v === "string" && v.trim() ? v.trim().slice(0, max) : void 0;
65
+ const out = [];
66
+ for (const raw of input.slice(0, 20)) {
67
+ const r = raw;
68
+ const id = str(r?.id, 64);
69
+ const title = str(r?.title, 60);
70
+ const text = str(r?.text, 140);
71
+ const url = str(r?.url, 500);
72
+ if (!id || !title || !text || !url || !/^https:\/\//.test(url))
73
+ continue;
74
+ const locale = r.locale === "zh" || r.locale === "en" ? r.locale : void 0;
75
+ out.push({ id, title, text, url, cta: str(r.cta, 20), locale });
76
+ }
77
+ return out;
78
+ }
79
+
80
+ // packages/core/dist/index.js
81
+ function sanitizeViewState(raw) {
82
+ if (!raw || typeof raw !== "object")
83
+ return void 0;
84
+ const r = raw;
85
+ let folds;
86
+ if (r.folds && typeof r.folds === "object" && !Array.isArray(r.folds)) {
87
+ const out = {};
88
+ for (const [k, v] of Object.entries(r.folds).slice(0, 5e3)) {
89
+ if (typeof v === "boolean")
90
+ out[k] = v;
91
+ }
92
+ if (Object.keys(out).length)
93
+ folds = out;
94
+ }
95
+ let view;
96
+ if (r.view && typeof r.view === "object") {
97
+ const v = r.view;
98
+ if (typeof v.scale === "number" && Number.isFinite(v.scale) && v.scale >= 0.05 && v.scale <= 20 && typeof v.dx === "number" && Number.isFinite(v.dx) && Math.abs(v.dx) < 1e6 && typeof v.dy === "number" && Number.isFinite(v.dy) && Math.abs(v.dy) < 1e6) {
99
+ view = { scale: v.scale, dx: v.dx, dy: v.dy };
100
+ }
101
+ }
102
+ return folds || view ? { ...folds && { folds }, ...view && { view } } : void 0;
103
+ }
104
+
105
+ // packages/vscode/src/extension.ts
106
+ var import_node_fs2 = require("node:fs");
107
+ var import_promises4 = require("node:fs/promises");
108
+ var import_node_os3 = require("node:os");
109
+ var import_node_path3 = require("node:path");
110
+ var vscode6 = __toESM(require("vscode"));
111
+
112
+ // packages/cli/src/license.ts
113
+ var import_promises = require("node:fs/promises");
114
+ var import_node_crypto = require("node:crypto");
115
+ var import_node_os = require("node:os");
116
+ var import_node_path = require("node:path");
117
+ function billingOrigin(raw) {
118
+ if (!raw) throw new Error("Inkmap checkout is not configured.");
119
+ const url = new URL(raw);
120
+ if (url.protocol !== "https:" || url.origin !== raw.replace(/\/$/, "")) {
121
+ throw new Error("Inkmap checkout requires an HTTPS origin.");
122
+ }
123
+ return url.origin;
124
+ }
125
+ function licenseService(storage, getOrigin, { loginOnly = false } = {}) {
126
+ const listeners = /* @__PURE__ */ new Set();
127
+ let current = { pro: false };
128
+ let trial;
129
+ let trialTimer;
130
+ let timer;
131
+ let lastCheck = 0;
132
+ let disposed = false;
133
+ let generation = 0;
134
+ let connection;
135
+ let activeOrigin;
136
+ let pendingWrite = Promise.resolve();
137
+ let pendingCheckout;
138
+ let cachedOrder;
139
+ function mergeCookies(existing, response) {
140
+ const map = /* @__PURE__ */ new Map();
141
+ if (existing) {
142
+ for (const pair of existing.split(/;\s*/)) {
143
+ const eq = pair.indexOf("=");
144
+ if (eq > 0) map.set(pair.slice(0, eq).trim(), pair.slice(eq + 1).trim());
145
+ }
146
+ }
147
+ const headers = response.headers;
148
+ const rawList = typeof headers.getSetCookie === "function" ? headers.getSetCookie() : response.headers.get("set-cookie") ? [response.headers.get("set-cookie")] : [];
149
+ for (const raw of rawList) {
150
+ const first = raw.split(";")[0]?.trim() ?? "";
151
+ const eq = first.indexOf("=");
152
+ if (eq > 0) map.set(first.slice(0, eq).trim(), first.slice(eq + 1).trim());
153
+ }
154
+ return map.size ? [...map.entries()].map(([k, v]) => `${k}=${v}`).join("; ") : void 0;
155
+ }
156
+ function maskPhone(phone) {
157
+ const clean = phone.trim();
158
+ const at = clean.indexOf("@");
159
+ if (at > 0 && at < clean.length - 1) {
160
+ const local = [...clean.slice(0, at)];
161
+ const domain = clean.slice(at + 1);
162
+ return `${local.length <= 1 ? "***" : local[0] + "***"}@${domain}`.slice(0, 64);
163
+ }
164
+ return /^1\d{10}$/.test(clean) ? `${clean.slice(0, 3)}****${clean.slice(7)}` : clean.slice(0, 32);
165
+ }
166
+ function clientLocale() {
167
+ const raw = (process.env.INKMAP_LOCALE || process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || "").trim();
168
+ if (/^zh\b/i.test(raw)) return "zh";
169
+ if (/^en\b/i.test(process.env.INKMAP_LOCALE || "")) return "en";
170
+ try {
171
+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
172
+ if (/^Asia\/(Shanghai|Chongqing|Harbin|Urumqi)$/i.test(tz)) return "zh";
173
+ } catch {
174
+ }
175
+ return "en";
176
+ }
177
+ function writeSession(operation) {
178
+ const next = pendingWrite.then(operation);
179
+ pendingWrite = next.then(() => {
180
+ }, () => {
181
+ });
182
+ return next;
183
+ }
184
+ async function createCheckoutFlow(origin, existingToken, existingCookie) {
185
+ const response = await fetch(origin + "/billing/v1/connections", {
186
+ method: "POST",
187
+ headers: {
188
+ "content-type": "application/json",
189
+ ...existingToken && { authorization: "Bearer " + existingToken },
190
+ ...existingCookie && { cookie: existingCookie }
191
+ },
192
+ redirect: "error",
193
+ body: JSON.stringify({ product: PRODUCT.id, mode: "buy" }),
194
+ signal: AbortSignal.timeout(8e3)
195
+ });
196
+ if (!response.ok) throw new Error("Unable to start the checkout flow.");
197
+ const cookie = mergeCookies(existingCookie, response);
198
+ const data = await response.json();
199
+ const url = billingFlowUrl(data.url, origin, "buy", false);
200
+ if (typeof data.token !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(data.token)) {
201
+ throw new Error("Invalid Inkmap checkout response.");
202
+ }
203
+ return { origin, url, token: data.token, ...cookie && { cookie } };
204
+ }
205
+ function checkoutPost(checkoutUrl, action, origin, body, token, cookie) {
206
+ return fetch(checkoutUrl + "/" + action, {
207
+ method: "POST",
208
+ headers: {
209
+ "content-type": "application/json",
210
+ origin,
211
+ ...token && { authorization: "Bearer " + token },
212
+ ...cookie && { cookie }
213
+ },
214
+ redirect: "error",
215
+ body: JSON.stringify(body),
216
+ signal: AbortSignal.timeout(12e3)
217
+ });
218
+ }
219
+ function phoneRequest(origin, action, phone, code) {
220
+ const isEmail = phone.includes("@");
221
+ const locale = clientLocale();
222
+ return fetch(origin + "/billing/v1/phone-sign-in/" + action, {
223
+ method: "POST",
224
+ headers: {
225
+ "content-type": "application/json",
226
+ "accept-language": locale === "zh" ? "zh-CN,zh;q=0.9" : "en-US,en;q=0.9"
227
+ },
228
+ redirect: "error",
229
+ body: JSON.stringify({ product: PRODUCT.id, phone, ...isEmail && { email: phone, locale }, code }),
230
+ signal: AbortSignal.timeout(12e3)
231
+ });
232
+ }
233
+ function phoneFailure(status) {
234
+ if (status === 400 || status === 401) return { ok: false, reason: "invalid" };
235
+ return { ok: false, reason: status === 429 ? "rateLimited" : "unavailable" };
236
+ }
237
+ function entitlement(origin, token) {
238
+ return fetch(origin + "/billing/v1/entitlement", {
239
+ headers: { authorization: "Bearer " + token },
240
+ redirect: "error",
241
+ signal: AbortSignal.timeout(5e3)
242
+ });
243
+ }
244
+ function applyEntitlement(state) {
245
+ lastCheck = Date.now();
246
+ const connected = state.connected === true;
247
+ const active = connected && state.active === true && state.entitlement === PRODUCT.entitlement;
248
+ const account = typeof state.account === "string" ? state.account.trim().slice(0, 64) : "";
249
+ if (!connected && state.pending === true && current.connected) return;
250
+ update(active, connected, account);
251
+ }
252
+ function update(pro, connected = false, account) {
253
+ const cleanAccount = connected && account ? account : void 0;
254
+ if (current.pro === pro && Boolean(current.connected) === connected && current.account === cleanAccount) return;
255
+ current = {
256
+ pro,
257
+ ...current.trialUntil !== void 0 && { trialUntil: current.trialUntil },
258
+ ...connected && { connected: true },
259
+ ...cleanAccount && { account: cleanAccount }
260
+ };
261
+ for (const listener of listeners) listener(current);
262
+ }
263
+ async function startTrial() {
264
+ const trialUntil = await localTrialDeadline().catch(() => void 0);
265
+ if (disposed || trialUntil === void 0) return;
266
+ current = { ...current, trialUntil };
267
+ const remaining = trialUntil - Date.now();
268
+ if (remaining > 0) {
269
+ trialTimer = setTimeout(() => {
270
+ for (const listener of listeners) listener(current);
271
+ }, remaining);
272
+ trialTimer.unref();
273
+ }
274
+ }
275
+ function schedule(delay) {
276
+ clearTimeout(timer);
277
+ if (disposed) return;
278
+ timer = setTimeout(() => void refresh(), delay);
279
+ timer.unref();
280
+ }
281
+ function refresh() {
282
+ if (connection) return connection;
283
+ const version = generation;
284
+ connection = (async () => {
285
+ let token;
286
+ let delay = 6e4;
287
+ try {
288
+ const origin = billingOrigin(getOrigin());
289
+ if (origin !== activeOrigin) {
290
+ lastCheck = 0;
291
+ activeOrigin = origin;
292
+ update(false);
293
+ }
294
+ const stored = await storage.read();
295
+ if (version !== generation || disposed) return;
296
+ if (!stored) return update(false);
297
+ const record = JSON.parse(stored);
298
+ if (record.origin !== origin || typeof record.token !== "string") return update(false);
299
+ token = record.token;
300
+ const response = await entitlement(origin, record.token);
301
+ if (version !== generation || disposed) return;
302
+ if (response.status === 401) {
303
+ token = void 0;
304
+ return await writeSession(async () => {
305
+ if (version !== generation || disposed) return;
306
+ await storage.write(void 0).catch(() => {
307
+ });
308
+ update(false);
309
+ });
310
+ }
311
+ if (!response.ok) throw new Error("Unable to check Inkmap Pro.");
312
+ const state = await response.json();
313
+ if (version !== generation || disposed) return;
314
+ applyEntitlement(state);
315
+ delay = state.active !== true && state.pending === true ? 4e3 : 6e4;
316
+ } catch {
317
+ if (version === generation && Date.now() - lastCheck > 15 * 6e4) update(false);
318
+ } finally {
319
+ if (version === generation && token) schedule(delay);
320
+ }
321
+ })().finally(() => {
322
+ connection = void 0;
323
+ });
324
+ return connection;
325
+ }
326
+ return {
327
+ async state() {
328
+ await (trial ??= startTrial());
329
+ if (Date.now() - lastCheck >= 4e3) await refresh();
330
+ return current;
331
+ },
332
+ async connect(mode) {
333
+ if (loginOnly && mode !== "restore") throw new Error("Only Yunfan account sign-in is available.");
334
+ const origin = billingOrigin(getOrigin());
335
+ const version = generation;
336
+ let existingToken;
337
+ try {
338
+ const stored = await storage.read();
339
+ if (stored) {
340
+ const record = JSON.parse(stored);
341
+ if (record.origin === origin && typeof record.token === "string") existingToken = record.token;
342
+ }
343
+ } catch {
344
+ }
345
+ const create = (path2, body) => fetch(origin + "/billing/v1/" + path2, {
346
+ method: "POST",
347
+ headers: {
348
+ "content-type": "application/json",
349
+ ...existingToken && { authorization: "Bearer " + existingToken }
350
+ },
351
+ redirect: "error",
352
+ body: JSON.stringify(body),
353
+ signal: AbortSignal.timeout(8e3)
354
+ });
355
+ let legacy = false;
356
+ let response = await (mode === "restore" ? create("restore-connections", { product: PRODUCT.id }) : create("connections", { product: PRODUCT.id, mode }));
357
+ if (mode === "restore" && !loginOnly && response.status === 404) {
358
+ legacy = true;
359
+ response = await create("connections", { product: PRODUCT.id, mode });
360
+ }
361
+ if (!response.ok) throw new Error("Unable to start the Yunfan account flow.");
362
+ const data = await response.json();
363
+ const url = billingFlowUrl(data.url, origin, mode, legacy);
364
+ if (typeof data.token !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(data.token)) {
365
+ throw new Error("Invalid Inkmap checkout response.");
366
+ }
367
+ await writeSession(async () => {
368
+ if (version !== generation || disposed || origin !== billingOrigin(getOrigin())) {
369
+ throw new Error("The Yunfan account session changed. Please try again.");
370
+ }
371
+ await storage.write(JSON.stringify({ origin, token: data.token, ...mode === "buy" && { checkoutUrl: url } }));
372
+ ++generation;
373
+ lastCheck = 0;
374
+ if (mode !== "buy" || !current.connected) update(false);
375
+ schedule(1e3);
376
+ });
377
+ return url;
378
+ },
379
+ async orderPro() {
380
+ if (loginOnly) throw new Error("Only Yunfan account sign-in is available.");
381
+ const origin = billingOrigin(getOrigin());
382
+ if (cachedOrder && cachedOrder.origin === origin && Date.now() - cachedOrder.at < 8e3) {
383
+ const hit = cachedOrder.result;
384
+ cachedOrder = void 0;
385
+ schedule(hit.status === "qr" || hit.status === "redirect" ? 4e3 : 6e4);
386
+ return hit;
387
+ }
388
+ const version = generation;
389
+ let record;
390
+ try {
391
+ const stored = await storage.read();
392
+ if (stored) record = JSON.parse(stored);
393
+ } catch {
394
+ }
395
+ const requestOrder = async (checkoutUrl, token, cookie, persist) => {
396
+ const res = await checkoutPost(checkoutUrl, "order", origin, {}, token, cookie);
397
+ if (res.status === 401 || res.status === 403 || res.status === 404 || res.status === 410) return null;
398
+ if (!res.ok) throw new Error("Unable to load WeChat Pay QR code.");
399
+ const nextCookie = mergeCookies(cookie, res);
400
+ const data = await res.json();
401
+ if (persist || nextCookie !== cookie) {
402
+ await writeSession(async () => {
403
+ if (version !== generation || disposed || origin !== billingOrigin(getOrigin())) return;
404
+ await storage.write(JSON.stringify({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
405
+ if (persist) {
406
+ ++generation;
407
+ lastCheck = 0;
408
+ }
409
+ });
410
+ }
411
+ if (data.active === true) {
412
+ const rights = await entitlement(origin, token).catch(() => null);
413
+ if (rights?.ok) applyEntitlement(await rights.json());
414
+ else update(true, true, current.account);
415
+ schedule(6e4);
416
+ return { status: "active", state: current };
417
+ }
418
+ if (typeof data.qr === "string" && data.qr) {
419
+ schedule(4e3);
420
+ const qr = data.qr.startsWith("data:image/") ? data.qr : "data:image/png;base64," + data.qr;
421
+ return {
422
+ status: "qr",
423
+ qr,
424
+ amountFen: typeof data.amountFen === "number" ? data.amountFen : 2990,
425
+ ...typeof data.expiresAt === "string" && { expiresAt: data.expiresAt }
426
+ };
427
+ }
428
+ if (typeof data.checkoutUrl === "string" && /^https:\/\//.test(data.checkoutUrl)) {
429
+ schedule(4e3);
430
+ return { status: "redirect", url: data.checkoutUrl };
431
+ }
432
+ throw new Error("Invalid Inkmap checkout response.");
433
+ };
434
+ const existingCookie = record?.origin === origin && typeof record.cookie === "string" ? record.cookie : void 0;
435
+ if (record?.origin === origin && typeof record.checkoutUrl === "string" && typeof record.token === "string") {
436
+ const existing = await requestOrder(record.checkoutUrl, record.token, existingCookie, false);
437
+ if (existing) return existing;
438
+ }
439
+ const existingToken = record?.origin === origin && typeof record.token === "string" ? record.token : void 0;
440
+ const flow = await createCheckoutFlow(origin, existingToken, existingCookie);
441
+ const ordered = await requestOrder(flow.url, flow.token, flow.cookie, true);
442
+ if (ordered) return ordered;
443
+ pendingCheckout = flow;
444
+ return { status: "needsPhone" };
445
+ },
446
+ async sendPhoneCode(phone) {
447
+ if (typeof phone !== "string" || !phone.trim() || phone.length > 254) return phoneFailure(400);
448
+ const isEmail = phone.includes("@");
449
+ const locale = clientLocale();
450
+ try {
451
+ const origin = billingOrigin(getOrigin());
452
+ if (!loginOnly) {
453
+ try {
454
+ if (!pendingCheckout || pendingCheckout.origin !== origin) {
455
+ pendingCheckout = await createCheckoutFlow(origin);
456
+ }
457
+ const sendAction = isEmail ? "email/send" : "sms";
458
+ const sendBody = isEmail ? { email: phone, locale } : { phone };
459
+ let smsRes = await checkoutPost(pendingCheckout.url, sendAction, origin, sendBody, pendingCheckout.token, pendingCheckout.cookie);
460
+ if (smsRes.status === 410 || smsRes.status === 404) {
461
+ pendingCheckout = await createCheckoutFlow(origin);
462
+ smsRes = await checkoutPost(pendingCheckout.url, sendAction, origin, sendBody, pendingCheckout.token, pendingCheckout.cookie);
463
+ }
464
+ pendingCheckout.cookie = mergeCookies(pendingCheckout.cookie, smsRes);
465
+ return smsRes.status === 204 ? { ok: true, value: void 0 } : phoneFailure(smsRes.status);
466
+ } catch {
467
+ pendingCheckout = void 0;
468
+ }
469
+ }
470
+ const response = await phoneRequest(origin, "send", phone);
471
+ return response.status === 204 ? { ok: true, value: void 0 } : phoneFailure(response.status);
472
+ } catch {
473
+ return phoneFailure();
474
+ }
475
+ },
476
+ async signInByPhone(phone, code) {
477
+ if (typeof phone !== "string" || !phone.trim() || phone.length > 254 || typeof code !== "string" || !/^\d{6}$/.test(code)) return phoneFailure(400);
478
+ const isEmail = phone.includes("@");
479
+ const version = generation;
480
+ try {
481
+ const origin = billingOrigin(getOrigin());
482
+ let token;
483
+ let checkoutUrl;
484
+ let cookie;
485
+ if (pendingCheckout && pendingCheckout.origin === origin && !loginOnly) {
486
+ const verifyAction = isEmail ? "email/verify" : "login";
487
+ const verifyBody = isEmail ? { email: phone, code } : { phone, code };
488
+ const loginRes = await checkoutPost(pendingCheckout.url, verifyAction, origin, verifyBody, pendingCheckout.token, pendingCheckout.cookie);
489
+ if (!loginRes.ok) {
490
+ if (loginRes.status === 410 || loginRes.status === 404) pendingCheckout = void 0;
491
+ return phoneFailure(loginRes.status);
492
+ }
493
+ cookie = mergeCookies(pendingCheckout.cookie, loginRes);
494
+ token = pendingCheckout.token;
495
+ checkoutUrl = pendingCheckout.url;
496
+ pendingCheckout = void 0;
497
+ const orderRes = await checkoutPost(checkoutUrl, "order", origin, {}, token, cookie).catch(() => null);
498
+ if (orderRes?.ok) {
499
+ cookie = mergeCookies(cookie, orderRes);
500
+ const orderData = await orderRes.json().catch(() => null);
501
+ if (orderData && typeof orderData === "object") {
502
+ if (orderData.active === true) {
503
+ cachedOrder = { at: Date.now(), origin, result: { status: "active", state: current } };
504
+ } else if (typeof orderData.qr === "string" && orderData.qr) {
505
+ const qr = orderData.qr.startsWith("data:image/") ? orderData.qr : "data:image/png;base64," + orderData.qr;
506
+ cachedOrder = {
507
+ at: Date.now(),
508
+ origin,
509
+ result: {
510
+ status: "qr",
511
+ qr,
512
+ amountFen: typeof orderData.amountFen === "number" ? orderData.amountFen : 2990,
513
+ ...typeof orderData.expiresAt === "string" && { expiresAt: orderData.expiresAt }
514
+ }
515
+ };
516
+ } else if (typeof orderData.checkoutUrl === "string" && /^https:\/\//.test(orderData.checkoutUrl)) {
517
+ cachedOrder = { at: Date.now(), origin, result: { status: "redirect", url: orderData.checkoutUrl } };
518
+ }
519
+ }
520
+ }
521
+ } else {
522
+ const response = await phoneRequest(origin, "verify", phone, code);
523
+ if (response.status !== 201) return phoneFailure(response.status);
524
+ cookie = mergeCookies(void 0, response);
525
+ const body = await response.json();
526
+ token = body.token;
527
+ }
528
+ if (typeof token !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(token)) return phoneFailure();
529
+ let state = { entitlement: PRODUCT.entitlement, connected: true, account: maskPhone(phone) };
530
+ const rights = await entitlement(origin, token).catch(() => null);
531
+ if (rights?.ok) {
532
+ state = await rights.json();
533
+ if (state.entitlement !== PRODUCT.entitlement) return phoneFailure();
534
+ if (state.connected !== true) {
535
+ if (!checkoutUrl) return phoneFailure();
536
+ state.connected = true;
537
+ }
538
+ if (checkoutUrl && (!state.account || typeof state.account !== "string" || !state.account.trim())) {
539
+ state.account = maskPhone(phone);
540
+ }
541
+ } else if (!checkoutUrl) {
542
+ return phoneFailure();
543
+ }
544
+ if (cachedOrder?.result.status === "active") state.active = true;
545
+ return await writeSession(async () => {
546
+ if (version !== generation || disposed || origin !== billingOrigin(getOrigin())) return phoneFailure();
547
+ await storage.write(JSON.stringify({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
548
+ ++generation;
549
+ activeOrigin = origin;
550
+ applyEntitlement(state);
551
+ if (cachedOrder?.result.status === "active") cachedOrder.result.state = current;
552
+ schedule(cachedOrder?.result.status === "qr" ? 4e3 : 6e4);
553
+ return { ok: true, value: current };
554
+ });
555
+ } catch {
556
+ return phoneFailure();
557
+ }
558
+ },
559
+ async deactivate() {
560
+ pendingCheckout = void 0;
561
+ cachedOrder = void 0;
562
+ const saved = await writeSession(async () => {
563
+ const previous = await storage.read();
564
+ await storage.write(void 0);
565
+ ++generation;
566
+ clearTimeout(timer);
567
+ lastCheck = 0;
568
+ update(false);
569
+ return previous;
570
+ });
571
+ if (!saved) return;
572
+ try {
573
+ const { origin, token } = JSON.parse(saved);
574
+ if (origin !== billingOrigin(getOrigin())) return;
575
+ await fetch(origin + "/billing/v1/entitlement", {
576
+ method: "DELETE",
577
+ headers: { authorization: "Bearer " + token },
578
+ redirect: "error",
579
+ signal: AbortSignal.timeout(5e3)
580
+ });
581
+ } catch {
582
+ }
583
+ },
584
+ onChange(listener) {
585
+ listeners.add(listener);
586
+ return () => listeners.delete(listener);
587
+ },
588
+ dispose() {
589
+ disposed = true;
590
+ clearTimeout(trialTimer);
591
+ clearTimeout(timer);
592
+ listeners.clear();
593
+ }
594
+ };
595
+ }
596
+ async function localTrialDeadline() {
597
+ const path2 = (0, import_node_path.join)((0, import_node_os.homedir)(), ".inkmap", "trial-start");
598
+ const now = Date.now();
599
+ let value;
600
+ try {
601
+ value = await (0, import_promises.readFile)(path2, "utf8");
602
+ } catch (error) {
603
+ if (error.code !== "ENOENT") throw error;
604
+ await (0, import_promises.mkdir)((0, import_node_path.dirname)(path2), { recursive: true, mode: 448 });
605
+ const temporary = path2 + "." + (0, import_node_crypto.randomUUID)();
606
+ try {
607
+ await (0, import_promises.writeFile)(temporary, String(now), { mode: 384, flag: "wx" });
608
+ await (0, import_promises.link)(temporary, path2).catch((error2) => {
609
+ if (error2.code !== "EEXIST") throw error2;
610
+ });
611
+ } finally {
612
+ await (0, import_promises.rm)(temporary, { force: true });
613
+ }
614
+ value = await (0, import_promises.readFile)(path2, "utf8");
615
+ }
616
+ const started = Number(value);
617
+ return Number.isSafeInteger(started) && started > 0 && started <= Date.now() ? started + TRIAL_MS : void 0;
618
+ }
619
+ var AD_TTL = 6 * 60 * 60 * 1e3;
620
+ function adFeed(url) {
621
+ let cache;
622
+ return async () => {
623
+ if (!url) return [];
624
+ if (cache && Date.now() - cache.at < AD_TTL) return cache.ads;
625
+ try {
626
+ const res = await fetch(url, { signal: AbortSignal.timeout(5e3), headers: { accept: "application/json" } });
627
+ const ads = res.ok ? sanitizeAds(await res.json()) : [];
628
+ cache = { at: Date.now(), ads };
629
+ return ads;
630
+ } catch {
631
+ cache = { at: Date.now(), ads: [] };
632
+ return [];
633
+ }
634
+ };
635
+ }
636
+
637
+ // packages/vscode/src/browser.ts
638
+ var import_node_child_process = require("node:child_process");
639
+ var vscode3 = __toESM(require("vscode"));
640
+
641
+ // packages/cli/src/server.ts
642
+ var import_node_crypto2 = require("node:crypto");
643
+ var import_node_fs = require("node:fs");
644
+ var import_promises2 = require("node:fs/promises");
645
+ var import_node_http = require("node:http");
646
+ var import_node_os2 = require("node:os");
647
+ var import_node_path2 = require("node:path");
648
+ var SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
649
+ ".git",
650
+ ".hg",
651
+ ".svn",
652
+ "node_modules",
653
+ "dist",
654
+ "dist-codex",
655
+ "dist-workbuddy",
656
+ "build",
657
+ "out",
658
+ ".next",
659
+ ".nuxt",
660
+ ".agents",
661
+ ".agent",
662
+ ".gemini",
663
+ ".codex",
664
+ ".venv",
665
+ "venv",
666
+ "target",
667
+ "coverage",
668
+ ".tmp"
669
+ ]);
670
+ function insideRoot(root, target) {
671
+ if (root === target) return true;
672
+ const rel = (0, import_node_path2.relative)(root, target);
673
+ return Boolean(rel && !(0, import_node_path2.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(".." + import_node_path2.sep));
674
+ }
675
+ async function findProjectRoot(filePath) {
676
+ let cur = (0, import_node_path2.dirname)(filePath);
677
+ const home = await (0, import_promises2.realpath)((0, import_node_os2.homedir)()).catch(() => (0, import_node_os2.homedir)());
678
+ while (cur && cur !== (0, import_node_path2.dirname)(cur) && cur !== home) {
679
+ try {
680
+ await (0, import_promises2.lstat)((0, import_node_path2.join)(cur, ".git"));
681
+ return cur;
682
+ } catch {
683
+ }
684
+ cur = (0, import_node_path2.dirname)(cur);
685
+ }
686
+ return (0, import_node_path2.dirname)(filePath);
687
+ }
688
+ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
689
+ const found = [];
690
+ async function walk(dir, depth) {
691
+ if (depth > maxDepth || found.length >= maxFiles) return;
692
+ let entries;
693
+ try {
694
+ entries = await (0, import_promises2.readdir)(dir, { withFileTypes: true });
695
+ } catch {
696
+ return;
697
+ }
698
+ for (const entry of entries) {
699
+ if (found.length >= maxFiles) break;
700
+ if (entry.name.startsWith(".")) continue;
701
+ const full = (0, import_node_path2.join)(dir, entry.name);
702
+ if (entry.isDirectory()) {
703
+ if (!SKIP_SCAN_DIRS.has(entry.name)) await walk(full, depth + 1);
704
+ } else if (entry.isFile() && /\.md$/i.test(entry.name)) {
705
+ try {
706
+ const st = await (0, import_promises2.lstat)(full);
707
+ if (st.isFile() && st.size <= 5 * 1024 * 1024) {
708
+ const real = await (0, import_promises2.realpath)(full);
709
+ if (real === full && insideRoot(rootDir, real)) found.push(real);
710
+ }
711
+ } catch {
712
+ }
713
+ }
714
+ }
715
+ }
716
+ await walk(rootDir, 0);
717
+ found.sort((a, b) => {
718
+ const aM = /\.markmap\.md$/i.test(a) ? 0 : 1;
719
+ const bM = /\.markmap\.md$/i.test(b) ? 0 : 1;
720
+ if (aM !== bM) return aM - bM;
721
+ return a.localeCompare(b);
722
+ });
723
+ return found;
724
+ }
725
+ var MAX_BODY = 20 * 1024 * 1024;
726
+ var TYPES = {
727
+ ".html": "text/html; charset=utf-8",
728
+ ".js": "text/javascript; charset=utf-8",
729
+ ".css": "text/css; charset=utf-8",
730
+ ".svg": "image/svg+xml",
731
+ ".png": "image/png",
732
+ ".jpg": "image/jpeg",
733
+ ".jpeg": "image/jpeg",
734
+ ".gif": "image/gif",
735
+ ".webp": "image/webp",
736
+ ".woff2": "font/woff2",
737
+ ".woff": "font/woff",
738
+ ".ttf": "font/ttf",
739
+ ".json": "application/json"
740
+ };
741
+ var hash = (s) => (0, import_node_crypto2.createHash)("sha1").update(s).digest("hex");
742
+ function docName(path2) {
743
+ return (0, import_node_path2.basename)(path2).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
744
+ }
745
+ function viewStateFile(key) {
746
+ const base = process.env.INKMAP_HOME ?? (0, import_node_path2.join)((0, import_node_os2.homedir)(), ".inkmap");
747
+ return (0, import_node_path2.join)(base, "view-state", hash(key) + ".json");
748
+ }
749
+ async function readDiskViewState(key) {
750
+ try {
751
+ return sanitizeViewState(JSON.parse(await (0, import_promises2.readFile)(viewStateFile(key), "utf8")));
752
+ } catch {
753
+ return void 0;
754
+ }
755
+ }
756
+ async function writeDiskViewState(key, state) {
757
+ const target = viewStateFile(key);
758
+ await (0, import_promises2.mkdir)((0, import_node_path2.dirname)(target), { recursive: true, mode: 448 });
759
+ const temp = `${target}.${process.pid}.${Date.now()}`;
760
+ try {
761
+ await (0, import_promises2.writeFile)(temp, JSON.stringify(state), { mode: 384 });
762
+ await (0, import_promises2.rename)(temp, target);
763
+ } finally {
764
+ await (0, import_promises2.rm)(temp, { force: true }).catch(() => {
765
+ });
766
+ }
767
+ }
768
+ async function fileSource(file, log = () => {
769
+ }) {
770
+ const path2 = (0, import_node_path2.resolve)(file);
771
+ if (!(await (0, import_promises2.stat)(path2)).isFile()) throw new Error(`\u4E0D\u662F\u6587\u4EF6\uFF1A${path2}`);
772
+ const dir = (0, import_node_path2.dirname)(path2);
773
+ return {
774
+ name: docName(path2),
775
+ key: path2,
776
+ dir,
777
+ read: () => (0, import_promises2.readFile)(path2, "utf8"),
778
+ async write(md) {
779
+ await (0, import_promises2.writeFile)(path2, md, "utf8");
780
+ log(`\u5DF2\u5199\u56DE ${path2}`);
781
+ },
782
+ watch(onChange) {
783
+ const watcher = (0, import_node_fs.watch)(dir, (_, changed) => {
784
+ if (!changed || changed === (0, import_node_path2.basename)(path2)) onChange();
785
+ });
786
+ return () => watcher.close();
787
+ },
788
+ readView: () => readDiskViewState(path2),
789
+ writeView: (state) => writeDiskViewState(path2, state)
790
+ };
791
+ }
792
+ function within(root, rel) {
793
+ const base = root.endsWith(import_node_path2.sep) ? root : root + import_node_path2.sep;
794
+ const full = (0, import_node_path2.normalize)((0, import_node_path2.join)(root, decodeURIComponent(rel)));
795
+ return full.startsWith(base) ? full : null;
796
+ }
797
+ async function serve({ source: initialSource, webRoot, port = 4377, host = "127.0.0.1", log = () => {
798
+ }, license, ads, sidebar = false, sidebarPurchase = false, sidebarAccountNavigation = false, loginOnly = false, ideWorkspace = false }) {
799
+ if (sidebar && host !== "127.0.0.1") throw new Error("The sidebar bridge requires loopback.");
800
+ const prefix = sidebar ? `/s/${(0, import_node_crypto2.randomBytes)(24).toString("hex")}/` : "/";
801
+ let activeSource = initialSource;
802
+ let bound;
803
+ let current = await activeSource.read();
804
+ let version = hash(current);
805
+ let viewState = await activeSource.readView?.();
806
+ const clients = /* @__PURE__ */ new Set();
807
+ const canPurchase = !loginOnly && (!sidebar || sidebarPurchase);
808
+ const docState = () => ({
809
+ name: activeSource.name,
810
+ md: current,
811
+ version,
812
+ ...activeSource.key && { currentFile: activeSource.key },
813
+ ...viewState && { viewState }
814
+ });
815
+ const send = (event, data) => {
816
+ const payload = `event: ${event}
817
+ data: ${JSON.stringify(data)}
818
+
819
+ `;
820
+ for (const res of clients) res.write(payload);
821
+ };
822
+ const broadcast = () => send("change", docState());
823
+ const unlisten = license?.onChange((state) => send("license", state)) ?? (() => {
824
+ });
825
+ let queue = Promise.resolve();
826
+ function serialized(work) {
827
+ const result = queue.then(work);
828
+ queue = result.catch(() => {
829
+ });
830
+ return result;
831
+ }
832
+ async function refresh() {
833
+ const text = await activeSource.read();
834
+ if (hash(text) === version) return;
835
+ current = text;
836
+ version = hash(text);
837
+ broadcast();
838
+ }
839
+ let pending;
840
+ let unwatch = activeSource.watch(() => {
841
+ clearTimeout(pending);
842
+ pending = setTimeout(async () => {
843
+ void serialized(refresh).catch(() => {
844
+ });
845
+ }, 80);
846
+ });
847
+ async function collectWorkspaceFiles() {
848
+ const roots = /* @__PURE__ */ new Map();
849
+ if (activeSource.key) {
850
+ const realKey = await (0, import_promises2.realpath)(activeSource.key).catch(() => activeSource.key);
851
+ const projRoot = await (0, import_promises2.realpath)(await findProjectRoot(realKey)).catch(() => (0, import_node_path2.dirname)(realKey));
852
+ roots.set(projRoot, { path: projRoot, name: (0, import_node_path2.basename)(projRoot), active: true });
853
+ }
854
+ const envRoots = (process.env.INKMAP_WORKSPACES || "").split(import_node_path2.delimiter).filter(Boolean);
855
+ for (const raw of envRoots) {
856
+ const real = await (0, import_promises2.realpath)((0, import_node_path2.resolve)(raw)).catch(() => null);
857
+ if (real && !roots.has(real)) {
858
+ roots.set(real, { path: real, name: (0, import_node_path2.basename)(real), active: roots.size === 0 });
859
+ }
860
+ }
861
+ const items = [];
862
+ const seen = /* @__PURE__ */ new Set();
863
+ for (const root of roots.values()) {
864
+ const files = await scanProjectMarkdownFiles(root.path);
865
+ for (const f of files) {
866
+ if (seen.has(f)) continue;
867
+ seen.add(f);
868
+ const rel = (0, import_node_path2.relative)(root.path, f);
869
+ items.push({
870
+ path: f,
871
+ label: `${root.name} / ${rel}`,
872
+ group: root.active ? "active" : "project"
873
+ });
874
+ }
875
+ }
876
+ if (activeSource.key && !seen.has(activeSource.key)) {
877
+ items.unshift({
878
+ path: activeSource.key,
879
+ label: `${(0, import_node_path2.basename)(activeSource.dir)} / ${(0, import_node_path2.basename)(activeSource.key)}`,
880
+ group: "active"
881
+ });
882
+ }
883
+ return { roots: [...roots.values()], files: items };
884
+ }
885
+ async function switchSourceToFile(candidatePath) {
886
+ if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath)) {
887
+ throw new Error("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002");
888
+ }
889
+ const realTarget = await (0, import_promises2.realpath)((0, import_node_path2.resolve)(candidatePath));
890
+ const st = await (0, import_promises2.lstat)(realTarget);
891
+ if (!st.isFile() || st.size > 5 * 1024 * 1024) {
892
+ throw new Error("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684 Markdown \u6587\u4EF6\u3002");
893
+ }
894
+ const { roots } = await collectWorkspaceFiles();
895
+ if (roots.length > 0 && !roots.some((r) => insideRoot(r.path, realTarget))) {
896
+ throw new Error("\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u9879\u76EE\u5DE5\u4F5C\u533A\u5185\u3002");
897
+ }
898
+ if (activeSource.key === realTarget) return;
899
+ clearTimeout(pending);
900
+ unwatch();
901
+ activeSource = await fileSource(realTarget, log);
902
+ current = await activeSource.read();
903
+ version = hash(current);
904
+ viewState = await activeSource.readView?.();
905
+ unwatch = activeSource.watch(() => {
906
+ clearTimeout(pending);
907
+ pending = setTimeout(async () => {
908
+ void serialized(refresh).catch(() => {
909
+ });
910
+ }, 80);
911
+ });
912
+ broadcast();
913
+ }
914
+ const json = (res, status, body) => {
915
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
916
+ res.end(JSON.stringify(body));
917
+ };
918
+ const readBody = (req) => new Promise((ok, fail) => {
919
+ let size = 0;
920
+ const chunks = [];
921
+ req.on("data", (c) => {
922
+ size += c.length;
923
+ if (size > MAX_BODY) {
924
+ fail(new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"));
925
+ req.destroy();
926
+ } else chunks.push(c);
927
+ });
928
+ req.on("end", () => ok(Buffer.concat(chunks).toString("utf8")));
929
+ req.on("error", fail);
930
+ });
931
+ const sendFile = async (res, full) => {
932
+ if (!full) return json(res, 403, { error: "forbidden" });
933
+ try {
934
+ const body = await (0, import_promises2.readFile)(full);
935
+ res.writeHead(200, { "content-type": TYPES[(0, import_node_path2.extname)(full).toLowerCase()] ?? "application/octet-stream", "cache-control": sidebar ? "no-store" : "no-cache" });
936
+ res.end(body);
937
+ } catch {
938
+ json(res, 404, { error: "not found" });
939
+ }
940
+ };
941
+ const server = (0, import_node_http.createServer)(async (req, res) => {
942
+ try {
943
+ const url = new URL(req.url ?? "/", "http://localhost");
944
+ if (sidebar) {
945
+ res.setHeader("Referrer-Policy", "no-referrer");
946
+ res.setHeader("X-Content-Type-Options", "nosniff");
947
+ res.setHeader("Cache-Control", "no-store");
948
+ res.setHeader("Content-Security-Policy", "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; font-src 'self' data:; base-uri 'none'; form-action 'none'; object-src 'none'");
949
+ if (req.headers.host !== `127.0.0.1:${bound}` || !url.pathname.startsWith(prefix)) return json(res, 404, { error: "not found" });
950
+ if ((req.method === "PUT" || req.method === "POST") && (req.headers.origin !== `http://127.0.0.1:${bound}` || req.headers["content-type"] !== "application/json")) {
951
+ return json(res, 403, { error: "forbidden" });
952
+ }
953
+ url.pathname = "/" + url.pathname.slice(prefix.length);
954
+ }
955
+ if (url.pathname === "/api/doc" && req.method === "GET") {
956
+ viewState = await activeSource.readView?.() ?? viewState;
957
+ if (sidebar) await serialized(refresh);
958
+ return json(res, 200, docState());
959
+ }
960
+ if (url.pathname === "/api/files" && req.method === "GET") {
961
+ const { files } = await collectWorkspaceFiles();
962
+ return json(res, 200, { currentFile: activeSource.key ?? null, files });
963
+ }
964
+ if (url.pathname === "/api/capabilities" && req.method === "GET") {
965
+ return json(res, 200, {
966
+ purchase: canPurchase,
967
+ ...ideWorkspace && { ideWorkspace: true },
968
+ ...sidebarAccountNavigation && { accountNavigation: "host" }
969
+ });
970
+ }
971
+ if (url.pathname === "/api/view" && req.method === "PUT") {
972
+ const cleaned = sanitizeViewState(JSON.parse(await readBody(req)));
973
+ if (cleaned) {
974
+ viewState = cleaned;
975
+ await activeSource.writeView?.(cleaned).catch(() => {
976
+ });
977
+ }
978
+ return json(res, 200, { ok: true });
979
+ }
980
+ if (url.pathname === "/api/doc" && req.method === "PUT") {
981
+ const { md, baseVersion } = JSON.parse(await readBody(req));
982
+ if (typeof md !== "string") return json(res, 400, { error: "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32" });
983
+ if (!hasAccess(await license?.state() ?? { pro: false })) return json(res, 403, { error: "Inkmap trial expired" });
984
+ return await serialized(async () => {
985
+ await refresh();
986
+ if (baseVersion !== version) return json(res, 409, docState());
987
+ if (md !== current) {
988
+ await activeSource.write(md);
989
+ current = md;
990
+ version = hash(md);
991
+ if (sidebar) broadcast();
992
+ }
993
+ return json(res, 200, { version });
994
+ });
995
+ }
996
+ if (url.pathname === "/api/license" && req.method === "GET") return json(res, 200, await license?.state() ?? { pro: false });
997
+ const sameOriginPost = () => {
998
+ const origin = req.headers.origin;
999
+ const reqHost = req.headers.host;
1000
+ const local = reqHost && /^(127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/.test(reqHost);
1001
+ return Boolean(local && origin === "http://" + reqHost && req.headers["content-type"] === "application/json");
1002
+ };
1003
+ if (url.pathname === "/api/open" && req.method === "POST") {
1004
+ if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1005
+ const { file } = JSON.parse(await readBody(req));
1006
+ await serialized(() => switchSourceToFile(String(file ?? "")));
1007
+ const { files } = await collectWorkspaceFiles();
1008
+ return json(res, 200, { currentFile: activeSource.key ?? null, files, doc: docState() });
1009
+ }
1010
+ if (url.pathname === "/api/checkout" && req.method === "POST") {
1011
+ if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1012
+ const { mode } = JSON.parse(await readBody(req));
1013
+ if (mode !== "buy" && mode !== "restore") return json(res, 400, { error: "invalid checkout mode" });
1014
+ if (!canPurchase && mode === "buy") return json(res, 403, { error: "forbidden" });
1015
+ if (!license) return json(res, 503, { error: "Inkmap checkout is unavailable." });
1016
+ return json(res, 200, { url: await license.connect(mode) });
1017
+ }
1018
+ if (url.pathname === "/api/order-pro" && req.method === "POST") {
1019
+ if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1020
+ if (!canPurchase) return json(res, 403, { error: "forbidden" });
1021
+ if (!license) return json(res, 503, { error: "Inkmap checkout is unavailable." });
1022
+ if (typeof license.orderPro !== "function") return json(res, 501, { fallback: true });
1023
+ return json(res, 200, { result: await license.orderPro() });
1024
+ }
1025
+ if (url.pathname === "/api/phone-send" && req.method === "POST") {
1026
+ if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1027
+ if (!license || typeof license.sendPhoneCode !== "function") return json(res, 501, { fallback: true });
1028
+ const { phone } = JSON.parse(await readBody(req));
1029
+ return json(res, 200, { result: await license.sendPhoneCode(String(phone ?? "")) });
1030
+ }
1031
+ if (url.pathname === "/api/phone-verify" && req.method === "POST") {
1032
+ if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1033
+ if (!license || typeof license.signInByPhone !== "function") return json(res, 501, { fallback: true });
1034
+ const { phone, code } = JSON.parse(await readBody(req));
1035
+ return json(res, 200, { result: await license.signInByPhone(String(phone ?? ""), String(code ?? "")) });
1036
+ }
1037
+ if (url.pathname === "/api/signout" && req.method === "POST") {
1038
+ if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1039
+ await license?.deactivate();
1040
+ return json(res, 200, await license?.state() ?? { pro: false });
1041
+ }
1042
+ if (url.pathname === "/api/ads") return json(res, 200, sidebar ? [] : await ads?.() ?? []);
1043
+ if (url.pathname === "/api/events") {
1044
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
1045
+ res.write(": connected\n\n");
1046
+ clients.add(res);
1047
+ req.on("close", () => clients.delete(res));
1048
+ return;
1049
+ }
1050
+ if (url.pathname === "/favicon.ico") return void res.writeHead(204).end();
1051
+ if (url.pathname.startsWith("/doc-assets/")) {
1052
+ let asset = within(activeSource.dir, url.pathname.slice("/doc-assets/".length));
1053
+ if (sidebar && asset) {
1054
+ const root = await (0, import_promises2.realpath)(activeSource.dir);
1055
+ asset = await (0, import_promises2.realpath)(asset).catch(() => null);
1056
+ if (asset && (!asset.startsWith(root + import_node_path2.sep) || !/\.(?:png|jpe?g|gif|webp)$/i.test(asset))) asset = null;
1057
+ }
1058
+ return sendFile(res, asset);
1059
+ }
1060
+ return sendFile(res, within(webRoot, url.pathname === "/" ? "index.html" : url.pathname.slice(1)));
1061
+ } catch (err) {
1062
+ json(res, 500, { error: err instanceof Error ? err.message : String(err) });
1063
+ }
1064
+ });
1065
+ const listen = (p) => new Promise((ok, fail) => {
1066
+ server.once("error", fail);
1067
+ server.listen(p, host, () => {
1068
+ server.off("error", fail);
1069
+ ok(server.address().port);
1070
+ });
1071
+ });
1072
+ try {
1073
+ bound = await listen(port);
1074
+ } catch (err) {
1075
+ if (err.code !== "EADDRINUSE") throw err;
1076
+ bound = await listen(0);
1077
+ }
1078
+ return {
1079
+ url: `http://${host}:${bound}${prefix}`,
1080
+ switchToFile: (filePath) => serialized(() => switchSourceToFile(filePath)),
1081
+ close: () => new Promise((done) => {
1082
+ clearTimeout(pending);
1083
+ unwatch();
1084
+ unlisten();
1085
+ for (const res of clients) res.end();
1086
+ server.close(() => done());
1087
+ })
1088
+ };
1089
+ }
1090
+
1091
+ // packages/vscode/src/documents.ts
1092
+ var path = __toESM(require("node:path"));
1093
+ var vscode = __toESM(require("vscode"));
1094
+ function docName2(uri) {
1095
+ return path.basename(uri.path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
1096
+ }
1097
+ function docDir(uri) {
1098
+ if (uri.scheme === "untitled") return vscode.workspace.workspaceFolders?.[0]?.uri;
1099
+ return vscode.Uri.joinPath(uri, "..");
1100
+ }
1101
+ async function replaceText(document, next) {
1102
+ const prev = document.getText();
1103
+ if (prev === next) return true;
1104
+ let start = 0;
1105
+ const max = Math.min(prev.length, next.length);
1106
+ while (start < max && prev.charCodeAt(start) === next.charCodeAt(start)) start++;
1107
+ let end = 0;
1108
+ while (end < max - start && prev.charCodeAt(prev.length - 1 - end) === next.charCodeAt(next.length - 1 - end)) end++;
1109
+ const edit = new vscode.WorkspaceEdit();
1110
+ edit.replace(
1111
+ document.uri,
1112
+ new vscode.Range(document.positionAt(start), document.positionAt(prev.length - end)),
1113
+ next.slice(start, next.length - end)
1114
+ );
1115
+ return vscode.workspace.applyEdit(edit);
1116
+ }
1117
+ function targetUri(arg) {
1118
+ if (arg instanceof vscode.Uri) return arg;
1119
+ const editor = vscode.window.activeTextEditor;
1120
+ if (editor) return editor.document.uri;
1121
+ const input = vscode.window.tabGroups.activeTabGroup.activeTab?.input;
1122
+ if (input instanceof vscode.TabInputCustom || input instanceof vscode.TabInputText) return input.uri;
1123
+ return void 0;
1124
+ }
1125
+ var ADD_SELECTION_COMMAND = "composer.addsymbolstocomposer";
1126
+ var CHAT_COMMAND = "aichat.newchataction";
1127
+ async function chatAvailable() {
1128
+ const commands4 = await vscode.commands.getCommands(true);
1129
+ return commands4.includes(ADD_SELECTION_COMMAND) || commands4.includes(CHAT_COMMAND);
1130
+ }
1131
+ var openChat = () => vscode.commands.executeCommand(CHAT_COMMAND);
1132
+ async function addLinesToChat(document, startLine, endLine, text) {
1133
+ const last = document.lineCount - 1;
1134
+ const start = Math.max(0, Math.min(startLine, last));
1135
+ const end = Math.max(start, Math.min(endLine, last));
1136
+ let range = new vscode.Range(start, 0, end, document.lineAt(end).text.length);
1137
+ if (text) {
1138
+ const at = document.getText(range).indexOf(text);
1139
+ if (at >= 0) range = new vscode.Range(document.positionAt(document.offsetAt(range.start) + at), document.positionAt(document.offsetAt(range.start) + at + text.length));
1140
+ }
1141
+ const picked = text || document.getText(range);
1142
+ try {
1143
+ await vscode.commands.executeCommand(ADD_SELECTION_COMMAND, {
1144
+ codeSelections: [
1145
+ {
1146
+ uri: document.uri,
1147
+ range: {
1148
+ selectionStartLineNumber: range.start.line + 1,
1149
+ selectionStartColumn: range.start.character + 1,
1150
+ positionLineNumber: range.end.line + 1,
1151
+ positionColumn: range.end.character + 1
1152
+ },
1153
+ text: "```markdown\n" + picked + "\n```",
1154
+ rawText: picked
1155
+ }
1156
+ ]
1157
+ });
1158
+ return;
1159
+ } catch {
1160
+ }
1161
+ await viaTextEditor(document, range);
1162
+ }
1163
+ async function viaTextEditor(document, range) {
1164
+ const open = vscode.window.visibleTextEditors.find((e) => e.document === document);
1165
+ const layout = open ? void 0 : await vscode.commands.executeCommand("vscode.getEditorLayout");
1166
+ const before = new Set(vscode.window.tabGroups.all.flatMap((g) => g.tabs));
1167
+ await vscode.window.showTextDocument(document, {
1168
+ viewColumn: open?.viewColumn ?? vscode.ViewColumn.Beside,
1169
+ selection: range,
1170
+ preview: false
1171
+ });
1172
+ await openChat();
1173
+ if (open) return;
1174
+ const opened = vscode.window.tabGroups.all.flatMap((g) => g.tabs).find((tab) => !before.has(tab) && tab.input instanceof vscode.TabInputText && tab.input.uri.toString() === document.uri.toString());
1175
+ if (opened) await vscode.window.tabGroups.close(opened);
1176
+ if (layout) await vscode.commands.executeCommand("vscode.setEditorLayout", layout);
1177
+ }
1178
+
1179
+ // packages/vscode/src/i18n.ts
1180
+ var vscode2 = __toESM(require("vscode"));
1181
+ var zh = {
1182
+ openMarkdownFirst: "\u8BF7\u5148\u6253\u5F00\u4E00\u4E2A Markdown \u6587\u4EF6",
1183
+ browserOpened: "\u601D\u7EF4\u5BFC\u56FE\u5DF2\u5728\u6D4F\u89C8\u5668\u6253\u5F00\uFF1A{url}",
1184
+ copyLink: "\u590D\u5236\u94FE\u63A5",
1185
+ browserFailed: "\u65E0\u6CD5\u5728\u6D4F\u89C8\u5668\u6253\u5F00\u601D\u7EF4\u5BFC\u56FE\uFF1A{error}",
1186
+ readOnly: "\u6587\u6863\u65E0\u6CD5\u4FEE\u6539\uFF08\u53EF\u80FD\u662F\u53EA\u8BFB\u6587\u4EF6\uFF09",
1187
+ buyPro: "\u8D2D\u4E70 Pro",
1188
+ signIn: "\u767B\u5F55",
1189
+ switchAccount: "\u5207\u6362\u8D26\u53F7",
1190
+ proActiveDetail: "\u7EC8\u8EAB\u4F1A\u5458\u6743\u76CA\u5DF2\u5F00\u901A\u3002",
1191
+ accountLine: "\u5F53\u524D\u8D26\u53F7\uFF1A{account}",
1192
+ accountConnected: "\u5F53\u524D\u8D26\u53F7\uFF1A\u5DF2\u767B\u5F55",
1193
+ trialExpired: "7 \u5929\u8BD5\u7528\u5DF2\u7ED3\u675F\u3002\u8BF7\u8D2D\u4E70 Pro\uFF0C\u6216\u767B\u5F55\u5DF2\u8D2D\u4E70 Pro \u7684\u8D26\u53F7\u3002",
1194
+ checkoutHint: "\u5728\u6D4F\u89C8\u5668\u5B8C\u6210\u64CD\u4F5C\uFF0C\u5DF2\u6709 Pro \u6743\u76CA\u4F1A\u81EA\u52A8\u540C\u6B65\u3002",
1195
+ checkoutFailed: "\u65E0\u6CD5\u6253\u5F00\u8D2D\u4E70\u9875\u9762\u3002",
1196
+ removed: "\u5DF2\u9000\u51FA\u767B\u5F55\u3002",
1197
+ removeConfirm: "\u9000\u51FA\u5F53\u524D\u8D26\u53F7\uFF1F\u4E0B\u6B21\u767B\u5F55\u65F6\u4F1A\u81EA\u52A8\u540C\u6B65 Pro \u6743\u76CA\u3002",
1198
+ remove: "\u9000\u51FA\u767B\u5F55",
1199
+ saveExport: "\u5BFC\u51FA"
1200
+ };
1201
+ var en = {
1202
+ openMarkdownFirst: "Open a Markdown file first",
1203
+ browserOpened: "Mind map opened in the browser: {url}",
1204
+ copyLink: "Copy link",
1205
+ browserFailed: "Could not open the mind map in the browser: {error}",
1206
+ readOnly: "The document cannot be modified (it may be read-only)",
1207
+ buyPro: "Buy Pro",
1208
+ signIn: "Sign In",
1209
+ switchAccount: "Switch Account",
1210
+ proActiveDetail: "Lifetime Pro membership is active.",
1211
+ accountLine: "Account: {account}",
1212
+ accountConnected: "Account: Signed in",
1213
+ trialExpired: "Your 7-day trial has ended. Buy Pro or sign in to an account that has Pro.",
1214
+ checkoutHint: "Continue in your browser. Any existing Pro access will sync automatically.",
1215
+ checkoutFailed: "Could not open checkout.",
1216
+ removed: "Signed out.",
1217
+ removeConfirm: "Sign out? Your Pro access will sync the next time you sign in.",
1218
+ remove: "Sign Out",
1219
+ saveExport: "Export"
1220
+ };
1221
+ var isChinese = () => {
1222
+ if (/^zh/i.test(vscode2.env.language)) return true;
1223
+ try {
1224
+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
1225
+ if (/^Asia\/(Shanghai|Chongqing|Harbin|Urumqi)$/i.test(tz)) return true;
1226
+ } catch {
1227
+ }
1228
+ return false;
1229
+ };
1230
+ function t(key, vars = {}) {
1231
+ return (isChinese() ? zh : en)[key].replace(/\{(\w+)\}/g, (_, k) => vars[k] ?? "");
1232
+ }
1233
+
1234
+ // packages/vscode/src/browser.ts
1235
+ var VIEW_STATE_PREFIX = "inkmap.viewState:";
1236
+ var BrowserServers = class {
1237
+ constructor(context, webRoot, log, license, ads) {
1238
+ this.context = context;
1239
+ this.webRoot = webRoot;
1240
+ this.log = log;
1241
+ this.license = license;
1242
+ this.ads = ads;
1243
+ }
1244
+ servers = /* @__PURE__ */ new Map();
1245
+ async open(uri) {
1246
+ const key = uri.toString();
1247
+ let served = this.servers.get(key);
1248
+ if (!served) {
1249
+ served = serve({
1250
+ source: documentSource(uri, this.context),
1251
+ webRoot: this.webRoot,
1252
+ port: 0,
1253
+ log: (msg) => this.log.appendLine(`[${docName2(uri)}] ${msg}`),
1254
+ license: this.license,
1255
+ ads: this.ads
1256
+ });
1257
+ this.servers.set(key, served);
1258
+ served.catch(() => this.servers.delete(key));
1259
+ }
1260
+ const { url } = await served;
1261
+ this.log.appendLine(`[${docName2(uri)}] ${url}`);
1262
+ await openUrl(url);
1263
+ return url;
1264
+ }
1265
+ dispose() {
1266
+ for (const served of this.servers.values()) served.then((s) => s.close(), () => {
1267
+ });
1268
+ this.servers.clear();
1269
+ }
1270
+ };
1271
+ function documentSource(uri, context) {
1272
+ const document = () => vscode3.workspace.openTextDocument(uri);
1273
+ const viewKey = VIEW_STATE_PREFIX + uri.toString();
1274
+ return {
1275
+ name: docName2(uri),
1276
+ dir: docDir(uri)?.fsPath ?? "",
1277
+ read: async () => (await document()).getText(),
1278
+ async write(md) {
1279
+ const doc = await document();
1280
+ if (!await replaceText(doc, md)) throw new Error(t("readOnly"));
1281
+ if (vscode3.workspace.getConfiguration("inkmap").get("browserAutoSave", true) && !doc.isUntitled) await doc.save();
1282
+ },
1283
+ watch(onChange) {
1284
+ const sub = vscode3.workspace.onDidChangeTextDocument((e) => {
1285
+ if (e.document.uri.toString() === uri.toString() && e.contentChanges.length) onChange();
1286
+ });
1287
+ return () => sub.dispose();
1288
+ },
1289
+ readView: async () => uri.scheme === "untitled" ? void 0 : sanitizeViewState(context.workspaceState.get(viewKey)),
1290
+ writeView: async (state) => {
1291
+ if (uri.scheme !== "untitled") await context.workspaceState.update(viewKey, state);
1292
+ }
1293
+ };
1294
+ }
1295
+ async function openUrl(url) {
1296
+ const fallback = () => vscode3.env.openExternal(vscode3.Uri.parse(url));
1297
+ if (vscode3.workspace.getConfiguration("inkmap").get("browser", "chrome") !== "chrome") return fallback();
1298
+ const [cmd, args] = process.platform === "darwin" ? ["open", ["-a", "Google Chrome", url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", "chrome", url]] : ["google-chrome", [url]];
1299
+ const ok = await new Promise((done) => {
1300
+ const child = (0, import_node_child_process.spawn)(cmd, args, { stdio: "ignore", detached: true });
1301
+ child.on("error", () => done(false));
1302
+ child.on("exit", (code) => done(code === 0));
1303
+ child.unref();
1304
+ });
1305
+ if (!ok) await fallback();
1306
+ }
1307
+
1308
+ // packages/vscode/src/license.ts
1309
+ var vscode4 = __toESM(require("vscode"));
1310
+ var KEY = "inkmap.billing.session";
1311
+ function extensionLicense(context) {
1312
+ return licenseService({
1313
+ read: () => Promise.resolve(context.secrets.get(KEY)),
1314
+ write: async (token) => {
1315
+ if (token) await context.secrets.store(KEY, token);
1316
+ else await context.secrets.delete(KEY);
1317
+ }
1318
+ }, () => vscode4.workspace.getConfiguration("inkmap").get("billingOrigin") || process.env.INKMAP_BILLING_ORIGIN || "" || YUNFAN_BILLING_ORIGIN);
1319
+ }
1320
+ async function openCheckout(license, mode) {
1321
+ const url = await license.connect(mode);
1322
+ if (!await vscode4.env.openExternal(vscode4.Uri.parse(url))) throw new Error(t("checkoutFailed"));
1323
+ }
1324
+ async function offerPro(license) {
1325
+ const state = await license.state();
1326
+ const accountDetail = state.account ? t("accountLine", { account: state.account }) : state.connected ? t("accountConnected") : "";
1327
+ if (state.pro) {
1328
+ const signOut = t("remove");
1329
+ const detail2 = [t("proActiveDetail"), accountDetail || t("accountConnected")].join("\n");
1330
+ const pick2 = await vscode4.window.showInformationMessage("Inkmap Pro", { modal: true, detail: detail2 }, signOut);
1331
+ if (pick2 === signOut) {
1332
+ await license.deactivate();
1333
+ vscode4.window.showInformationMessage(t("removed"));
1334
+ }
1335
+ return true;
1336
+ }
1337
+ const buy = t("buyPro");
1338
+ const signIn = t(state.connected ? "switchAccount" : "signIn");
1339
+ const detail = accountDetail ? `${accountDetail}
1340
+ ${t("checkoutHint")}` : t("checkoutHint");
1341
+ const pick = await vscode4.window.showInformationMessage("Inkmap Pro", { modal: true, detail }, buy, signIn);
1342
+ if (pick) {
1343
+ try {
1344
+ await openCheckout(license, pick === buy ? "buy" : "restore");
1345
+ } catch (error) {
1346
+ vscode4.window.showErrorMessage(error instanceof Error ? error.message : t("checkoutFailed"));
1347
+ }
1348
+ }
1349
+ return false;
1350
+ }
1351
+
1352
+ // packages/vscode/src/mindmapEditor.ts
1353
+ var import_node_crypto3 = require("node:crypto");
1354
+ var import_promises3 = require("node:fs/promises");
1355
+ var vscode5 = __toESM(require("vscode"));
1356
+
1357
+ // packages/vscode/src/html.ts
1358
+ function webviewHtml(html, { webBase, assetBase, cspSource, nonce, locale }) {
1359
+ const csp = [
1360
+ "default-src 'none'",
1361
+ `img-src ${cspSource} https: data: blob:`,
1362
+ `style-src ${cspSource} 'unsafe-inline'`,
1363
+ `font-src ${cspSource} data:`,
1364
+ `script-src 'nonce-${nonce}' ${cspSource}`,
1365
+ "form-action 'none'"
1366
+ ].join("; ");
1367
+ const head = `<meta http-equiv="Content-Security-Policy" content="${csp}">
1368
+ <script nonce="${nonce}">window.INKMAP_ASSET_BASE = ${JSON.stringify(assetBase)}; window.INKMAP_LOCALE = ${JSON.stringify(locale)};</script>`;
1369
+ return html.replace(/ crossorigin/g, "").replace(/(src|href)="\.\/assets\//g, `$1="${webBase}/assets/`).replace(/(src|href)="\.\/(app\.(?:js|css))"/g, `$1="${webBase}/$2"`).replace(/<script /g, `<script nonce="${nonce}" `).replace("<head>", `<head>
1370
+ ${head}`);
1371
+ }
1372
+
1373
+ // packages/vscode/src/mindmapEditor.ts
1374
+ var VIEW_STATE_PREFIX2 = "inkmap.viewState:";
1375
+ var CHANGE_DELAY = 120;
1376
+ var REVEAL_DELAY = 150;
1377
+ var MindmapEditorProvider = class {
1378
+ constructor(context, license, ads) {
1379
+ this.context = context;
1380
+ this.license = license;
1381
+ this.ads = ads;
1382
+ }
1383
+ static viewType = "inkmap.mindmap";
1384
+ panels = /* @__PURE__ */ new Set();
1385
+ /** The chat shortcut was pressed: the focused mind map says what is selected. Anywhere else it just opens the chat. */
1386
+ requestChat() {
1387
+ const panel = [...this.panels].find((p) => p.active);
1388
+ return panel ? panel.webview.postMessage({ type: "requestChat" }) : openChat();
1389
+ }
1390
+ async resolveCustomTextEditor(document, panel) {
1391
+ const webview = panel.webview;
1392
+ this.panels.add(panel);
1393
+ const webRoot = vscode5.Uri.joinPath(this.context.extensionUri, "dist", "web");
1394
+ const assets = docDir(document.uri);
1395
+ webview.options = {
1396
+ enableScripts: true,
1397
+ localResourceRoots: [webRoot, ...assets ? [assets] : [], ...(vscode5.workspace.workspaceFolders ?? []).map((f) => f.uri)]
1398
+ };
1399
+ webview.html = await editorHtml(webview, webRoot, assets);
1400
+ const viewKey = VIEW_STATE_PREFIX2 + document.uri.toString();
1401
+ const state = () => {
1402
+ const viewState = document.uri.scheme === "untitled" ? void 0 : sanitizeViewState(this.context.workspaceState.get(viewKey));
1403
+ return {
1404
+ name: docName2(document.uri),
1405
+ md: document.getText(),
1406
+ version: String(document.version),
1407
+ ...viewState && { viewState }
1408
+ };
1409
+ };
1410
+ const post = (msg) => webview.postMessage(msg);
1411
+ const syncLicense = async () => {
1412
+ const state2 = await this.license.state();
1413
+ if (panel.visible && this.panels.has(panel)) await post({ type: "license", state: state2 });
1414
+ };
1415
+ const disposables = [];
1416
+ let applying = false;
1417
+ let changeTimer;
1418
+ let revealTimer;
1419
+ const unlisten = this.license.onChange((license) => post({ type: "license", state: license }));
1420
+ disposables.push(
1421
+ { dispose: unlisten },
1422
+ // A hidden panel can miss a license update. Send the latest state when it becomes visible again.
1423
+ panel.onDidChangeViewState(({ webviewPanel }) => {
1424
+ if (webviewPanel.visible) void syncLicense();
1425
+ }),
1426
+ vscode5.window.onDidChangeWindowState(({ focused }) => {
1427
+ if (focused && panel.visible) void syncLicense();
1428
+ }),
1429
+ vscode5.workspace.onDidChangeTextDocument((e) => {
1430
+ if (applying || e.document !== document || !e.contentChanges.length) return;
1431
+ clearTimeout(changeTimer);
1432
+ changeTimer = setTimeout(() => post({ type: "change", doc: state() }), CHANGE_DELAY);
1433
+ }),
1434
+ vscode5.window.onDidChangeTextEditorSelection((e) => {
1435
+ const userMoved = e.kind === vscode5.TextEditorSelectionChangeKind.Keyboard || e.kind === vscode5.TextEditorSelectionChangeKind.Mouse;
1436
+ if (!userMoved || e.textEditor.document !== document) return;
1437
+ clearTimeout(revealTimer);
1438
+ revealTimer = setTimeout(() => post({ type: "reveal", line: e.selections[0].active.line }), REVEAL_DELAY);
1439
+ }),
1440
+ webview.onDidReceiveMessage(async (msg) => {
1441
+ const accountAction = msg.type === "checkout" || msg.type === "orderPro" || msg.type === "signOut" || msg.type === "sendPhoneCode" || msg.type === "signInByPhone";
1442
+ if (!accountAction && msg.type !== "ready" && msg.type !== "viewState" && !hasAccess(await this.license.state())) {
1443
+ if ("id" in msg) return post({ type: "error", id: msg.id, message: t("trialExpired") });
1444
+ return;
1445
+ }
1446
+ switch (msg.type) {
1447
+ case "ready": {
1448
+ const [license, ads] = await Promise.all([this.license.state(), this.ads()]);
1449
+ return post({ type: "doc", doc: state(), license, ads, chat: await chatAvailable() });
1450
+ }
1451
+ case "viewState": {
1452
+ if (document.uri.scheme === "untitled") return;
1453
+ const cleaned = sanitizeViewState(msg.state);
1454
+ if (cleaned) await this.context.workspaceState.update(viewKey, cleaned);
1455
+ return;
1456
+ }
1457
+ case "save": {
1458
+ if (msg.baseVersion !== String(document.version)) return post({ type: "conflict", id: msg.id, doc: state() });
1459
+ applying = true;
1460
+ try {
1461
+ const ok = await replaceText(document, msg.md);
1462
+ if (!ok) return post({ type: "error", id: msg.id, message: t("readOnly") });
1463
+ } finally {
1464
+ applying = false;
1465
+ }
1466
+ return post({ type: "saved", id: msg.id, version: String(document.version) });
1467
+ }
1468
+ case "undo":
1469
+ case "redo":
1470
+ return vscode5.commands.executeCommand(msg.type);
1471
+ case "select": {
1472
+ const editor = vscode5.window.visibleTextEditors.find((e) => e.document === document);
1473
+ if (!editor) return;
1474
+ const pos = new vscode5.Position(Math.min(msg.line, document.lineCount - 1), 0);
1475
+ editor.selection = new vscode5.Selection(pos, pos);
1476
+ editor.revealRange(new vscode5.Range(pos, pos), vscode5.TextEditorRevealType.InCenterIfOutsideViewport);
1477
+ return;
1478
+ }
1479
+ case "addToChat":
1480
+ return msg.startLine === void 0 || msg.endLine === void 0 ? openChat() : addLinesToChat(document, msg.startLine, msg.endLine, msg.text);
1481
+ case "checkout":
1482
+ try {
1483
+ if (msg.mode !== "buy" && msg.mode !== "restore") throw new Error("Invalid checkout mode");
1484
+ await openCheckout(this.license, msg.mode);
1485
+ return post({ type: "checkout", id: msg.id });
1486
+ } catch (error) {
1487
+ return post({ type: "error", id: msg.id, message: error instanceof Error ? error.message : t("checkoutFailed") });
1488
+ }
1489
+ case "orderPro":
1490
+ try {
1491
+ const result = await this.license.orderPro();
1492
+ if (result.status === "redirect" && !await vscode5.env.openExternal(vscode5.Uri.parse(result.url))) {
1493
+ throw new Error(t("checkoutFailed"));
1494
+ }
1495
+ return post({ type: "proOrder", id: msg.id, result });
1496
+ } catch (error) {
1497
+ return post({ type: "error", id: msg.id, message: error instanceof Error ? error.message : t("checkoutFailed") });
1498
+ }
1499
+ case "signOut":
1500
+ await this.license.deactivate();
1501
+ return post({ type: "signedOut", id: msg.id });
1502
+ case "sendPhoneCode":
1503
+ return post({ type: "phoneCodeSent", id: msg.id, result: await this.license.sendPhoneCode(msg.phone) });
1504
+ case "signInByPhone":
1505
+ return post({ type: "phoneSignIn", id: msg.id, result: await this.license.signInByPhone(msg.phone, msg.code) });
1506
+ case "saveFile":
1507
+ return post({ type: "fileSaved", id: msg.id, saved: await saveDataUrl(msg.name, msg.dataUrl, assets) });
1508
+ }
1509
+ })
1510
+ );
1511
+ panel.onDidDispose(() => {
1512
+ this.panels.delete(panel);
1513
+ clearTimeout(changeTimer);
1514
+ clearTimeout(revealTimer);
1515
+ disposables.forEach((d) => d.dispose());
1516
+ });
1517
+ }
1518
+ };
1519
+ async function saveDataUrl(name, dataUrl, dir) {
1520
+ const match = dataUrl.match(/^data:([^;,]+)?(;base64)?,(.*)$/s);
1521
+ if (!match) return false;
1522
+ const ext = name.split(".").pop() ?? "";
1523
+ const target = await vscode5.window.showSaveDialog({
1524
+ defaultUri: dir ? vscode5.Uri.joinPath(dir, name) : void 0,
1525
+ filters: { [ext.toUpperCase()]: [ext] },
1526
+ saveLabel: t("saveExport")
1527
+ });
1528
+ if (!target) return false;
1529
+ const body = match[2] ? Buffer.from(match[3], "base64") : Buffer.from(decodeURIComponent(match[3]), "utf8");
1530
+ await (0, import_promises3.writeFile)(target.fsPath, body);
1531
+ return true;
1532
+ }
1533
+ async function editorHtml(webview, webRoot, assets) {
1534
+ return webviewHtml(await (0, import_promises3.readFile)(vscode5.Uri.joinPath(webRoot, "index.html").fsPath, "utf8"), {
1535
+ webBase: webview.asWebviewUri(webRoot).toString(),
1536
+ assetBase: assets ? webview.asWebviewUri(assets).toString() + "/" : "",
1537
+ cspSource: webview.cspSource,
1538
+ nonce: (0, import_node_crypto3.randomBytes)(16).toString("base64"),
1539
+ locale: isChinese() ? "zh-cn" : vscode5.env.language
1540
+ });
1541
+ }
1542
+
1543
+ // packages/vscode/src/extension.ts
1544
+ function insideOrEqual(root, target) {
1545
+ if (root === target) return true;
1546
+ const rel = (0, import_node_path3.relative)(root, target);
1547
+ return Boolean(rel && !(0, import_node_path3.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(".." + import_node_path3.sep));
1548
+ }
1549
+ function resolveEditorUri(filePath) {
1550
+ for (const folder of vscode6.workspace.workspaceFolders ?? []) {
1551
+ const folderPath = folder.uri.fsPath || folder.uri.path;
1552
+ if (folderPath && insideOrEqual(folderPath, filePath)) {
1553
+ const rel = (0, import_node_path3.relative)(folderPath, filePath).split(import_node_path3.sep).join("/");
1554
+ return rel ? vscode6.Uri.joinPath(folder.uri, rel) : folder.uri;
1555
+ }
1556
+ }
1557
+ const first = vscode6.workspace.workspaceFolders?.[0];
1558
+ if (first && first.uri.scheme !== "file") {
1559
+ return first.uri.with({ path: filePath });
1560
+ }
1561
+ return vscode6.Uri.file(filePath);
1562
+ }
1563
+ function findColumnForFile(fileUri) {
1564
+ const targetFs = fileUri.fsPath || fileUri.path;
1565
+ for (const group of vscode6.window.tabGroups.all) {
1566
+ for (const tab of group.tabs) {
1567
+ const input = tab.input;
1568
+ if (input?.uri && (input.uri.fsPath === targetFs || input.uri.path === targetFs)) {
1569
+ return group.viewColumn;
1570
+ }
1571
+ if (tab.label && targetFs.endsWith(import_node_path3.sep + tab.label.replace(/^Preview\s+/i, ""))) {
1572
+ return group.viewColumn;
1573
+ }
1574
+ }
1575
+ }
1576
+ return vscode6.window.activeTextEditor?.viewColumn ?? vscode6.ViewColumn.Active;
1577
+ }
1578
+ async function openFileInEditorPane(filePath) {
1579
+ const fileUri = resolveEditorUri(filePath);
1580
+ const viewColumn = findColumnForFile(fileUri);
1581
+ await vscode6.commands.executeCommand("vscode.openWith", fileUri, MindmapEditorProvider.viewType, {
1582
+ viewColumn,
1583
+ preserveFocus: false
1584
+ });
1585
+ }
1586
+ function startMcpTargetBridge() {
1587
+ const inkmapDir = process.env.INKMAP_HOME || (0, import_node_path3.join)((0, import_node_os3.homedir)(), ".inkmap");
1588
+ const targetPath = (0, import_node_path3.join)(inkmapDir, "antigravity-target.json");
1589
+ const ackPath = (0, import_node_path3.join)(inkmapDir, "antigravity-target-ack.json");
1590
+ const statusPath = (0, import_node_path3.join)(inkmapDir, "vscode-bridge-status.json");
1591
+ let lastSeq = Date.now() - 1e4;
1592
+ let debounceTimer;
1593
+ let disposed = false;
1594
+ const writeBridgeStatus = async () => {
1595
+ try {
1596
+ if (!(0, import_node_fs2.existsSync)(inkmapDir)) (0, import_node_fs2.mkdirSync)(inkmapDir, { recursive: true, mode: 448 });
1597
+ await (0, import_promises4.writeFile)(statusPath, JSON.stringify({
1598
+ pid: process.pid,
1599
+ activatedAt: Date.now(),
1600
+ appName: vscode6.env.appName,
1601
+ remoteName: vscode6.env.remoteName,
1602
+ focused: vscode6.window.state.focused,
1603
+ folders: (vscode6.workspace.workspaceFolders ?? []).map((f) => f.uri.toString())
1604
+ }, null, 2), { mode: 384 });
1605
+ } catch {
1606
+ }
1607
+ };
1608
+ const syncInitialSeq = async () => {
1609
+ try {
1610
+ const raw = JSON.parse(await (0, import_promises4.readFile)(targetPath, "utf8"));
1611
+ if (typeof raw?.seq === "number" && raw.seq < Date.now() - 8e3) {
1612
+ lastSeq = raw.seq;
1613
+ }
1614
+ } catch {
1615
+ }
1616
+ await checkTarget();
1617
+ };
1618
+ const checkTarget = async () => {
1619
+ if (disposed) return;
1620
+ try {
1621
+ const raw = JSON.parse(await (0, import_promises4.readFile)(targetPath, "utf8"));
1622
+ if (!raw || raw.openInEditorPane !== true) return;
1623
+ const seq = Number(raw.seq) || 0;
1624
+ if (seq <= lastSeq || typeof raw.file !== "string") return;
1625
+ const realTarget = await (0, import_promises4.realpath)(raw.file).catch(() => raw.file);
1626
+ const folders = vscode6.workspace.workspaceFolders ?? [];
1627
+ let matchesWindow = false;
1628
+ for (const folder of folders) {
1629
+ const folderPath = folder.uri.fsPath || folder.uri.path;
1630
+ if (!folderPath) continue;
1631
+ const realFolder = await (0, import_promises4.realpath)(folderPath).catch(() => folderPath);
1632
+ if (insideOrEqual(realFolder, realTarget)) {
1633
+ matchesWindow = true;
1634
+ break;
1635
+ }
1636
+ }
1637
+ if (!matchesWindow && vscode6.window.state.focused) {
1638
+ matchesWindow = true;
1639
+ }
1640
+ if (!matchesWindow) return;
1641
+ lastSeq = seq;
1642
+ await openFileInEditorPane(realTarget);
1643
+ await (0, import_promises4.writeFile)(ackPath, JSON.stringify({
1644
+ seq,
1645
+ file: realTarget,
1646
+ ok: true,
1647
+ handledAt: Date.now()
1648
+ }, null, 2), { mode: 384 }).catch(() => {
1649
+ });
1650
+ } catch (err) {
1651
+ await (0, import_promises4.writeFile)(ackPath, JSON.stringify({
1652
+ seq: lastSeq,
1653
+ ok: false,
1654
+ error: String(err instanceof Error ? err.message : err),
1655
+ handledAt: Date.now()
1656
+ }, null, 2), { mode: 384 }).catch(() => {
1657
+ });
1658
+ }
1659
+ };
1660
+ void writeBridgeStatus();
1661
+ void syncInitialSeq();
1662
+ try {
1663
+ if (!(0, import_node_fs2.existsSync)(inkmapDir)) (0, import_node_fs2.mkdirSync)(inkmapDir, { recursive: true, mode: 448 });
1664
+ const watcher = (0, import_node_fs2.watch)(inkmapDir, (_event, filename) => {
1665
+ if (filename && filename !== "antigravity-target.json") return;
1666
+ clearTimeout(debounceTimer);
1667
+ debounceTimer = setTimeout(() => {
1668
+ void checkTarget();
1669
+ }, 60);
1670
+ });
1671
+ const pollFallback = setInterval(() => {
1672
+ void checkTarget();
1673
+ }, 1200);
1674
+ return {
1675
+ dispose() {
1676
+ disposed = true;
1677
+ clearTimeout(debounceTimer);
1678
+ clearInterval(pollFallback);
1679
+ watcher.close();
1680
+ }
1681
+ };
1682
+ } catch {
1683
+ return { dispose() {
1684
+ disposed = true;
1685
+ } };
1686
+ }
1687
+ }
1688
+ function activate(context) {
1689
+ const log = vscode6.window.createOutputChannel("Inkmap");
1690
+ const license = extensionLicense(context);
1691
+ const ads = adFeed(PRODUCT.adFeedUrl);
1692
+ const browsers = new BrowserServers(context, vscode6.Uri.joinPath(context.extensionUri, "dist", "web").fsPath, log, license, ads);
1693
+ const withUri = (run) => (arg) => {
1694
+ const uri = targetUri(arg);
1695
+ if (!uri) return vscode6.window.showWarningMessage(t("openMarkdownFirst"));
1696
+ return run(uri);
1697
+ };
1698
+ const openToSide = withUri(
1699
+ (uri) => vscode6.commands.executeCommand("vscode.openWith", uri, MindmapEditorProvider.viewType, {
1700
+ viewColumn: vscode6.ViewColumn.Beside,
1701
+ preserveFocus: true
1702
+ })
1703
+ );
1704
+ const editors = new MindmapEditorProvider(context, license, ads);
1705
+ chatAvailable().then((available) => vscode6.commands.executeCommand("setContext", "inkmap.chatAvailable", available));
1706
+ context.subscriptions.push(
1707
+ log,
1708
+ license,
1709
+ browsers,
1710
+ startMcpTargetBridge(),
1711
+ vscode6.window.registerUriHandler({
1712
+ handleUri(uri) {
1713
+ if (uri.path === "/open") {
1714
+ const target = new URLSearchParams(uri.query).get("path");
1715
+ if (target) void openFileInEditorPane(target);
1716
+ }
1717
+ }
1718
+ }),
1719
+ vscode6.window.registerCustomEditorProvider(MindmapEditorProvider.viewType, editors, {
1720
+ webviewOptions: { retainContextWhenHidden: true }
1721
+ }),
1722
+ vscode6.commands.registerCommand("inkmap.addToChat", () => editors.requestChat()),
1723
+ vscode6.commands.registerCommand("inkmap.open", openToSide),
1724
+ vscode6.commands.registerCommand("inkmap.openToSide", openToSide),
1725
+ vscode6.commands.registerCommand(
1726
+ "inkmap.showSource",
1727
+ withUri((uri) => vscode6.window.showTextDocument(uri, { viewColumn: vscode6.ViewColumn.Beside, preview: false }))
1728
+ ),
1729
+ vscode6.commands.registerCommand(
1730
+ "inkmap.openInBrowser",
1731
+ withUri(async (uri) => {
1732
+ if (!hasAccess(await license.state()) && !await offerPro(license)) return;
1733
+ try {
1734
+ const url = await browsers.open(uri);
1735
+ const pick = await vscode6.window.showInformationMessage(t("browserOpened", { url }), t("copyLink"));
1736
+ if (pick) await vscode6.env.clipboard.writeText(url);
1737
+ } catch (err) {
1738
+ vscode6.window.showErrorMessage(t("browserFailed", { error: err instanceof Error ? err.message : String(err) }));
1739
+ }
1740
+ })
1741
+ ),
1742
+ vscode6.commands.registerCommand("inkmap.upgrade", () => offerPro(license)),
1743
+ vscode6.commands.registerCommand("inkmap.restorePro", async () => {
1744
+ try {
1745
+ await openCheckout(license, "restore");
1746
+ } catch (error) {
1747
+ vscode6.window.showErrorMessage(error instanceof Error ? error.message : t("checkoutFailed"));
1748
+ }
1749
+ }),
1750
+ vscode6.commands.registerCommand("inkmap.signOut", async () => {
1751
+ const remove = t("remove");
1752
+ if (await vscode6.window.showWarningMessage(t("removeConfirm"), { modal: true }, remove) !== remove) return;
1753
+ await license.deactivate();
1754
+ vscode6.window.showInformationMessage(t("removed"));
1755
+ })
1756
+ );
1757
+ }
1758
+ function deactivate() {
1759
+ }
1760
+ // Annotate the CommonJS export names for ESM import in node:
1761
+ 0 && (module.exports = {
1762
+ activate,
1763
+ deactivate
1764
+ });