inkmap-mcp 0.3.8 → 0.3.11

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.
@@ -38,9 +38,7 @@ module.exports = __toCommonJS(extension_exports);
38
38
  // packages/core/dist/product.js
39
39
  var PRODUCT = {
40
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: ""
41
+ entitlement: "inkmap.pro"
44
42
  };
45
43
  var YUNFAN_BILLING_ORIGIN = "https://zhiyuanv.com";
46
44
  function billingFlowUrl(raw, origin, mode, legacy = false) {
@@ -58,24 +56,6 @@ var TRIAL_MS = 7 * DAY_MS;
58
56
  function hasAccess(state, now = Date.now()) {
59
57
  return state.pro || (state.trialUntil ?? 0) > now;
60
58
  }
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
59
 
80
60
  // packages/core/dist/index.js
81
61
  function sanitizeViewState(raw) {
@@ -103,12 +83,25 @@ function sanitizeViewState(raw) {
103
83
  }
104
84
 
105
85
  // packages/vscode/src/extension.ts
106
- var import_node_child_process3 = require("node:child_process");
86
+ var import_node_child_process4 = require("node:child_process");
107
87
  var import_node_fs2 = require("node:fs");
108
- var import_promises4 = require("node:fs/promises");
88
+ var import_promises5 = require("node:fs/promises");
89
+ var import_node_os4 = require("node:os");
90
+ var import_node_path4 = require("node:path");
91
+ var vscode5 = __toESM(require("vscode"));
92
+
93
+ // packages/vscode/src/browser.ts
94
+ var import_node_child_process3 = require("node:child_process");
95
+ var vscode2 = __toESM(require("vscode"));
96
+
97
+ // packages/cli/src/server.ts
98
+ var import_node_child_process2 = require("node:child_process");
99
+ var import_node_crypto2 = require("node:crypto");
100
+ var import_node_fs = require("node:fs");
101
+ var import_promises3 = require("node:fs/promises");
102
+ var import_node_http = require("node:http");
109
103
  var import_node_os3 = require("node:os");
110
104
  var import_node_path3 = require("node:path");
111
- var vscode5 = __toESM(require("vscode"));
112
105
 
113
106
  // packages/cli/src/license.ts
114
107
  var import_node_child_process = require("node:child_process");
@@ -116,47 +109,75 @@ var import_promises = require("node:fs/promises");
116
109
  var import_node_crypto = require("node:crypto");
117
110
  var import_node_os = require("node:os");
118
111
  var import_node_path = require("node:path");
112
+
113
+ // packages/cli/src/version.ts
114
+ var INKMAP_VERSION = "0.3.11";
115
+
116
+ // packages/cli/src/license.ts
117
+ var ZH_LOCALE_RE = /^zh(?:[-_.]|$)/i;
118
+ var EN_LOCALE_RE = /^en(?:[-_.]|$)/i;
119
119
  var cachedOsLocale;
120
- function detectOsLocale() {
121
- const explicit = (process.env.INKMAP_LOCALE || "").trim();
122
- if (/^zh\b/i.test(explicit)) return "zh";
123
- if (/^en\b/i.test(explicit)) return "en";
124
- if (cachedOsLocale) return cachedOsLocale;
125
- let domestic = false;
126
- try {
127
- const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
128
- if (/^(Asia\/(Shanghai|Chongqing|Chungking|Harbin|Urumqi|Beijing)|PRC)$/i.test(tz)) {
129
- domestic = true;
120
+ var WAIT_FAST_MS = 2500;
121
+ var WAIT_SLOW_MS = 3e4;
122
+ var WAIT_FAST_FOR_MS = 30 * 6e4;
123
+ var WAIT_MAX_MS = 3 * 24 * 60 * 6e4;
124
+ var MAX_WAITING = 5;
125
+ function isWaitingToken(value) {
126
+ const w = value;
127
+ return Boolean(w) && typeof w.origin === "string" && typeof w.token === "string" && /^[A-Za-z0-9_-]{43}$/.test(w.token) && typeof w.email === "string" && typeof w.since === "number" && typeof w.fastUntil === "number";
128
+ }
129
+ var DOMESTIC_TIME_ZONE = /^(Asia\/(Shanghai|Chongqing|Chungking|Harbin|Urumqi|Beijing)|PRC)$/i;
130
+ function parseAppleLanguages(output) {
131
+ const match = /^\(\s*(?:"([^"]+)"|([^\s,)]+))/m.exec(output);
132
+ return match?.[1] ?? match?.[2] ?? "";
133
+ }
134
+ var posixLocale = (env5) => (env5.LC_ALL || env5.LC_MESSAGES || env5.LANG || "").trim();
135
+ function resolveOsLocale(probe) {
136
+ const explicit = (probe.env.INKMAP_LOCALE || "").trim();
137
+ if (ZH_LOCALE_RE.test(explicit)) return "zh";
138
+ if (EN_LOCALE_RE.test(explicit)) return "en";
139
+ if (DOMESTIC_TIME_ZONE.test(probe.timeZone)) return "zh";
140
+ let language = "";
141
+ if (probe.platform === "darwin") {
142
+ try {
143
+ language = parseAppleLanguages(probe.run("defaults", ["read", "-g", "AppleLanguages"]));
144
+ } catch {
145
+ language = posixLocale(probe.env);
130
146
  }
131
- } catch {
132
- }
133
- if (!domestic) {
134
- if (process.platform === "darwin") {
135
- try {
136
- const out = (0, import_node_child_process.execFileSync)("defaults", ["read", "-g", "AppleLanguages"], {
137
- encoding: "utf8",
138
- timeout: 800,
139
- stdio: ["ignore", "pipe", "ignore"]
140
- });
141
- const firstLang = /"([^"]+)"/.exec(out)?.[1] ?? "";
142
- if (/^zh\b/i.test(firstLang)) domestic = true;
143
- } catch {
144
- const raw = (process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || "").trim();
145
- if (/^zh\b/i.test(raw)) domestic = true;
146
- }
147
- } else if (process.platform === "win32") {
148
- try {
149
- const loc = Intl.DateTimeFormat().resolvedOptions().locale || "";
150
- if (/^zh\b/i.test(loc)) domestic = true;
151
- } catch {
152
- }
153
- } else {
154
- const raw = (process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || "").trim();
155
- if (/^zh\b/i.test(raw)) domestic = true;
147
+ } else if (probe.platform === "win32") {
148
+ try {
149
+ const output = probe.run("reg", ["query", "HKCU\\Control Panel\\International", "/v", "LocaleName"]);
150
+ language = /LocaleName\s+REG_\w+\s+(\S+)/i.exec(output)?.[1] ?? "";
151
+ } catch {
156
152
  }
153
+ if (!language) language = probe.intlLocale;
154
+ } else {
155
+ language = posixLocale(probe.env);
157
156
  }
158
- cachedOsLocale = domestic ? "zh" : "en";
159
- return cachedOsLocale;
157
+ return ZH_LOCALE_RE.test(language) ? "zh" : "en";
158
+ }
159
+ function systemLocaleProbe() {
160
+ let timeZone = "";
161
+ let intlLocale = "";
162
+ try {
163
+ const options = Intl.DateTimeFormat().resolvedOptions();
164
+ timeZone = options.timeZone || "";
165
+ intlLocale = options.locale || "";
166
+ } catch {
167
+ }
168
+ return {
169
+ platform: process.platform,
170
+ env: process.env,
171
+ timeZone,
172
+ intlLocale,
173
+ run: (command, args) => (0, import_node_child_process.execFileSync)(command, args, { encoding: "utf8", timeout: 800, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] })
174
+ };
175
+ }
176
+ function detectOsLocale() {
177
+ const explicit = (process.env.INKMAP_LOCALE || "").trim();
178
+ if (ZH_LOCALE_RE.test(explicit)) return "zh";
179
+ if (EN_LOCALE_RE.test(explicit)) return "en";
180
+ return cachedOsLocale ??= resolveOsLocale(systemLocaleProbe());
160
181
  }
161
182
  function billingOrigin(raw) {
162
183
  if (!raw) throw new Error("Inkmap checkout is not configured.");
@@ -166,7 +187,7 @@ function billingOrigin(raw) {
166
187
  }
167
188
  return url.origin;
168
189
  }
169
- function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHost = "" } = {}) {
190
+ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHost = "", waitPollMs = WAIT_FAST_MS } = {}) {
170
191
  const listeners = /* @__PURE__ */ new Set();
171
192
  let current = { pro: false };
172
193
  let trial;
@@ -178,6 +199,9 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
178
199
  let detectedHost = defaultHost;
179
200
  const pendingEvents = /* @__PURE__ */ new Map();
180
201
  let lastCheck = 0;
202
+ let fastPollUntil = 0;
203
+ const expectPurchase = () => void (fastPollUntil = Date.now() + 15 * 6e4);
204
+ let flowCreation;
181
205
  let disposed = false;
182
206
  let generation = 0;
183
207
  let connection;
@@ -185,12 +209,32 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
185
209
  let pendingWrite = Promise.resolve();
186
210
  let pendingCheckout;
187
211
  let cachedOrder;
188
- let magicPollTimer;
189
- let magicSession = 0;
190
- function stopMagicPoll() {
191
- ++magicSession;
192
- clearTimeout(magicPollTimer);
193
- magicPollTimer = void 0;
212
+ let waiting = [];
213
+ let waitTimer;
214
+ let waitRound = 0;
215
+ let lastSignIn;
216
+ const sessionRecord = (fields) => JSON.stringify({ ...fields, ...lastSignIn && { lastSignIn } });
217
+ const signedOutRecord = () => lastSignIn || waiting.length ? JSON.stringify({ ...lastSignIn && { lastSignIn }, ...waiting.length && { waiting } }) : void 0;
218
+ async function rememberSignIn(id) {
219
+ const clean = id.trim().slice(0, 254);
220
+ if (!clean || clean === lastSignIn) return;
221
+ lastSignIn = clean;
222
+ current = { ...current, lastSignIn };
223
+ await writeSession(async () => {
224
+ let record = {};
225
+ try {
226
+ record = JSON.parse(await storage.read() || "{}");
227
+ } catch {
228
+ }
229
+ await storage.write(JSON.stringify({ ...record, lastSignIn }));
230
+ }).catch(() => {
231
+ });
232
+ }
233
+ function clearWaiting() {
234
+ waiting = [];
235
+ ++waitRound;
236
+ clearTimeout(waitTimer);
237
+ waitTimer = void 0;
194
238
  }
195
239
  function mergeCookies(existing, response) {
196
240
  const map = /* @__PURE__ */ new Map();
@@ -219,10 +263,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
219
263
  }
220
264
  return /^1\d{10}$/.test(clean) ? `${clean.slice(0, 3)}****${clean.slice(7)}` : clean.slice(0, 32);
221
265
  }
222
- function clientLocale(hint) {
223
- const h = (hint || "").trim();
224
- if (/^zh\b/i.test(h)) return "zh";
225
- if (/^en\b/i.test(h)) return "en";
266
+ function clientLocale(_uiLocaleHint) {
226
267
  return detectOsLocale();
227
268
  }
228
269
  function writeSession(operation) {
@@ -253,7 +294,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
253
294
  if (typeof data.token !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(data.token)) {
254
295
  throw new Error("Invalid Inkmap checkout response.");
255
296
  }
256
- return { origin, url, token: data.token, ...cookie && { cookie } };
297
+ return { origin, url, token: data.token, locale: loc, ...cookie && { cookie } };
257
298
  }
258
299
  function checkoutPost(checkoutUrl, action, origin, body, token, cookie, localeHint) {
259
300
  const loc = clientLocale(localeHint);
@@ -312,11 +353,25 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
312
353
  pro,
313
354
  ...current.trialUntil !== void 0 && { trialUntil: current.trialUntil },
314
355
  ...connected && { connected: true },
315
- ...cleanAccount && { account: cleanAccount }
356
+ ...cleanAccount && { account: cleanAccount },
357
+ ...lastSignIn && { lastSignIn }
316
358
  };
317
359
  for (const listener of listeners) listener(current);
318
360
  }
319
361
  async function startTrial() {
362
+ try {
363
+ const record = JSON.parse(await storage.read() || "{}");
364
+ const remembered = record.lastSignIn;
365
+ if (typeof remembered === "string" && remembered.trim() && !lastSignIn) {
366
+ lastSignIn = remembered.trim().slice(0, 254);
367
+ current = { ...current, lastSignIn };
368
+ }
369
+ if (typeof record.token !== "string" && Array.isArray(record.waiting) && !waiting.length) {
370
+ waiting = record.waiting.filter(isWaitingToken).slice(-MAX_WAITING);
371
+ scheduleWait(waitPollMs);
372
+ }
373
+ } catch {
374
+ }
320
375
  const trialUntil = await localTrialDeadline().catch(() => void 0);
321
376
  if (disposed || trialUntil === void 0) return;
322
377
  current = { ...current, trialUntil };
@@ -359,7 +414,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
359
414
  token = void 0;
360
415
  return await writeSession(async () => {
361
416
  if (version !== generation || disposed) return;
362
- await storage.write(void 0).catch(() => {
417
+ await storage.write(signedOutRecord()).catch(() => {
363
418
  });
364
419
  update(false);
365
420
  });
@@ -379,52 +434,172 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
379
434
  });
380
435
  return connection;
381
436
  }
382
- function startMagicPoll(origin, pendingToken) {
383
- stopMagicPoll();
384
- const id = magicSession;
385
- const deadline = Date.now() + 10 * 6e4;
386
- const poll = () => {
387
- if (disposed || id !== magicSession || Date.now() >= deadline) return;
388
- magicPollTimer = setTimeout(async () => {
389
- if (disposed || id !== magicSession) return;
437
+ async function mustPayFirst() {
438
+ if (!loginOnly) return false;
439
+ await (trial ??= startTrial());
440
+ return current.trialUntil !== void 0 && current.trialUntil <= Date.now();
441
+ }
442
+ async function waitFor(origin, token, email) {
443
+ const now = Date.now();
444
+ const same = (other) => !other || !email || other.toLowerCase() === email.toLowerCase();
445
+ waiting = waiting.filter((w) => w.token !== token && same(w.email)).map((w) => ({ ...w, fastUntil: now + WAIT_FAST_FOR_MS }));
446
+ waiting.push({ origin, token, email, since: now, fastUntil: now + WAIT_FAST_FOR_MS });
447
+ waiting = waiting.slice(-MAX_WAITING);
448
+ scheduleWait(waitPollMs);
449
+ await writeSession(async () => {
450
+ let record = {};
451
+ try {
452
+ record = JSON.parse(await storage.read() || "{}");
453
+ } catch {
454
+ }
455
+ if (typeof record.token !== "string") await storage.write(signedOutRecord());
456
+ }).catch(() => {
457
+ });
458
+ }
459
+ function scheduleWait(delay) {
460
+ clearTimeout(waitTimer);
461
+ if (disposed || !waiting.length) return;
462
+ waitTimer = setTimeout(() => void checkWaiting(), delay);
463
+ waitTimer.unref();
464
+ }
465
+ async function checkWaiting() {
466
+ const round = ++waitRound;
467
+ const now = Date.now();
468
+ const before = waiting.length;
469
+ let origin;
470
+ try {
471
+ origin = billingOrigin(getOrigin());
472
+ } catch {
473
+ return scheduleWait(WAIT_SLOW_MS);
474
+ }
475
+ waiting = waiting.filter((w) => w.origin === origin && now - w.since < WAIT_MAX_MS);
476
+ for (const w of [...waiting]) {
477
+ let response;
478
+ try {
479
+ response = await entitlement(w.origin, w.token);
480
+ } catch {
481
+ continue;
482
+ }
483
+ if (disposed || round !== waitRound) return;
484
+ if (response.status === 401) {
485
+ waiting = waiting.filter((other) => other !== w);
486
+ continue;
487
+ }
488
+ if (!response.ok) continue;
489
+ const body = await response.json().catch(() => null);
490
+ if (disposed || round !== waitRound) return;
491
+ if (body?.connected !== true || body.entitlement !== PRODUCT.entitlement) continue;
492
+ if (body.active !== true && await mustPayFirst()) continue;
493
+ if (disposed || round !== waitRound) return;
494
+ await writeSession(async () => {
495
+ if (disposed || round !== waitRound || w.origin !== billingOrigin(getOrigin())) return;
496
+ clearWaiting();
497
+ await storage.write(sessionRecord({ origin: w.origin, token: w.token }));
498
+ ++generation;
499
+ activeOrigin = w.origin;
500
+ applyEntitlement(body);
501
+ schedule(body.active === true ? 6e4 : 2500);
502
+ });
503
+ return;
504
+ }
505
+ if (disposed || round !== waitRound) return;
506
+ if (waiting.length !== before) {
507
+ await writeSession(async () => {
508
+ let record = {};
390
509
  try {
391
- const res = await entitlement(origin, pendingToken);
392
- if (disposed || id !== magicSession) return;
393
- if (res.status === 401) {
394
- stopMagicPoll();
395
- return;
396
- }
397
- if (res.ok) {
398
- const body = await res.json();
399
- if (body?.connected === true && body.entitlement === PRODUCT.entitlement) {
400
- stopMagicPoll();
401
- await writeSession(async () => {
402
- if (disposed || origin !== billingOrigin(getOrigin())) return;
403
- await storage.write(JSON.stringify({ origin, token: pendingToken }));
404
- ++generation;
405
- activeOrigin = origin;
406
- applyEntitlement(body);
407
- schedule(body.active === true ? 6e4 : 2500);
408
- });
409
- return;
410
- }
411
- }
510
+ record = JSON.parse(await storage.read() || "{}");
412
511
  } catch {
413
512
  }
414
- if (!disposed && id === magicSession && Date.now() < deadline) poll();
415
- }, 2e3);
416
- magicPollTimer.unref();
417
- };
418
- poll();
513
+ if (typeof record.token !== "string") await storage.write(signedOutRecord());
514
+ }).catch(() => {
515
+ });
516
+ }
517
+ scheduleWait(waiting.some((w) => Date.now() < w.fastUntil) ? waitPollMs : WAIT_SLOW_MS);
518
+ }
519
+ async function parkUnpaidSession() {
520
+ if (current.pro || !current.connected || !await mustPayFirst()) return;
521
+ await writeSession(async () => {
522
+ if (current.pro || !current.connected) return;
523
+ let record = {};
524
+ try {
525
+ record = JSON.parse(await storage.read() || "{}");
526
+ } catch {
527
+ }
528
+ if (typeof record.token !== "string" || typeof record.origin !== "string") return;
529
+ const response = await entitlement(record.origin, record.token).catch(() => null);
530
+ if (!response?.ok) return;
531
+ const latest = await response.json().catch(() => null);
532
+ if (!latest || latest.active === true || latest.connected !== true) {
533
+ if (latest) applyEntitlement(latest);
534
+ return;
535
+ }
536
+ ++generation;
537
+ clearTimeout(timer);
538
+ lastCheck = 0;
539
+ const now = Date.now();
540
+ waiting = [
541
+ ...waiting.filter((w) => w.token !== record.token),
542
+ { origin: record.origin, token: record.token, email: lastSignIn ?? "", since: now, fastUntil: now + WAIT_FAST_FOR_MS }
543
+ ].slice(-MAX_WAITING);
544
+ await storage.write(signedOutRecord());
545
+ update(false);
546
+ });
547
+ scheduleWait(waitPollMs);
548
+ }
549
+ async function sendPendingTelemetry() {
550
+ if (disposed || !pendingEvents.size) return;
551
+ let origin;
552
+ try {
553
+ origin = billingOrigin(getOrigin());
554
+ } catch {
555
+ return;
556
+ }
557
+ if (process.env.INKMAP_ALLOW_TEST_TELEMETRY !== "1") {
558
+ if (origin === "https://billing.example.com" || process.env.INKMAP_DISABLE_TELEMETRY === "1" || process.env.NODE_TEST_CONTEXT) return;
559
+ const customHome = process.env.INKMAP_HOME || "";
560
+ const sysTmp = (0, import_node_os.tmpdir)();
561
+ if (customHome && (customHome === sysTmp || customHome.startsWith(sysTmp + import_node_path.sep) || customHome.startsWith("/tmp/") || customHome.startsWith("/private/tmp/") || customHome.includes("/var/folders/") || customHome.includes("inkmap-npm-isolated-") || customHome.includes("inkmap-antigravity-mcp-") || customHome.includes("inkmap-local-editor-") || customHome.includes("inkmap-harness-"))) {
562
+ return;
563
+ }
564
+ }
565
+ const id = await (installIdPromise ??= localInstallId().catch(() => void 0));
566
+ if (disposed || !id || !pendingEvents.size) return;
567
+ await (trial ??= startTrial());
568
+ const events = {};
569
+ for (const [k, v] of pendingEvents.entries()) events[k] = v;
570
+ pendingEvents.clear();
571
+ const tier = current.pro ? "pro" : (current.trialUntil ?? 0) > Date.now() ? "trial" : "expired";
572
+ const os = process.platform === "darwin" ? "mac" : process.platform === "win32" ? "win" : process.platform === "linux" ? "linux" : "other";
573
+ const hostName = detectedHost || inferNodeHost();
574
+ await fetch(origin + "/billing/v1/telemetry", {
575
+ method: "POST",
576
+ headers: { "content-type": "application/json" },
577
+ redirect: "error",
578
+ body: JSON.stringify({
579
+ product: PRODUCT.id,
580
+ installId: id,
581
+ host: hostName,
582
+ os,
583
+ version: INKMAP_VERSION,
584
+ locale: clientLocale(),
585
+ tier,
586
+ events
587
+ }),
588
+ signal: AbortSignal.timeout(5e3)
589
+ }).catch(() => {
590
+ });
419
591
  }
420
592
  return {
421
593
  async state() {
422
594
  await (trial ??= startTrial());
423
- if (Date.now() - lastCheck >= 4e3) await refresh();
595
+ const interval = !current.pro && Date.now() < fastPollUntil ? 4e3 : 6e4;
596
+ if (Date.now() - lastCheck >= interval) await refresh();
597
+ await parkUnpaidSession();
424
598
  return current;
425
599
  },
426
600
  async connect(mode, localeHint) {
427
601
  if (loginOnly && mode !== "restore") throw new Error("Only Yunfan account sign-in is available.");
602
+ expectPurchase();
428
603
  const origin = billingOrigin(getOrigin());
429
604
  const loc = clientLocale(localeHint);
430
605
  const version = generation;
@@ -464,7 +639,8 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
464
639
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin())) {
465
640
  throw new Error("The Yunfan account session changed. Please try again.");
466
641
  }
467
- await storage.write(JSON.stringify({ origin, token: data.token, ...mode === "buy" && { checkoutUrl: url } }));
642
+ clearWaiting();
643
+ await storage.write(sessionRecord({ origin, token: data.token, ...mode === "buy" && { checkoutUrl: url } }));
468
644
  ++generation;
469
645
  lastCheck = 0;
470
646
  if (mode !== "buy" || !current.connected) update(false);
@@ -474,8 +650,10 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
474
650
  },
475
651
  async orderPro(localeHint) {
476
652
  if (loginOnly) throw new Error("Only Yunfan account sign-in is available.");
653
+ expectPurchase();
477
654
  const origin = billingOrigin(getOrigin());
478
- if (cachedOrder && cachedOrder.origin === origin && Date.now() - cachedOrder.at < 8e3) {
655
+ const loc = clientLocale(localeHint);
656
+ if (cachedOrder && cachedOrder.origin === origin && cachedOrder.locale === loc && Date.now() - cachedOrder.at < 8e3) {
479
657
  const hit = cachedOrder.result;
480
658
  cachedOrder = void 0;
481
659
  schedule(hit.status === "qr" || hit.status === "redirect" ? 4e3 : 6e4);
@@ -497,7 +675,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
497
675
  if (persist || nextCookie !== cookie) {
498
676
  await writeSession(async () => {
499
677
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin())) return;
500
- await storage.write(JSON.stringify({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
678
+ await storage.write(sessionRecord({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
501
679
  if (persist) {
502
680
  ++generation;
503
681
  lastCheck = 0;
@@ -541,34 +719,42 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
541
719
  },
542
720
  async sendPhoneCode(phone, localeHint) {
543
721
  if (typeof phone !== "string" || !phone.trim() || phone.length > 254) return phoneFailure(400);
722
+ expectPurchase();
544
723
  const isEmail = phone.includes("@");
545
724
  const locale = clientLocale(localeHint);
546
725
  try {
547
726
  const origin = billingOrigin(getOrigin());
548
727
  if (!loginOnly) {
549
728
  try {
550
- if (!pendingCheckout || pendingCheckout.origin !== origin) {
551
- pendingCheckout = await createCheckoutFlow(origin, void 0, void 0, locale);
729
+ const newFlow = () => flowCreation ??= createCheckoutFlow(origin, void 0, void 0, locale).finally(() => {
730
+ flowCreation = void 0;
731
+ });
732
+ let flow = pendingCheckout;
733
+ if (!flow || flow.origin !== origin || flow.locale !== locale) {
734
+ flow = await newFlow();
735
+ pendingCheckout = flow;
552
736
  }
553
737
  const sendAction = isEmail ? "email/send" : "sms";
554
738
  const sendBody = isEmail ? { email: phone, locale } : { phone };
555
- let smsRes = await checkoutPost(pendingCheckout.url, sendAction, origin, sendBody, pendingCheckout.token, pendingCheckout.cookie, locale);
556
- if (smsRes.status === 410 || smsRes.status === 404) {
557
- pendingCheckout = await createCheckoutFlow(origin, void 0, void 0, locale);
558
- smsRes = await checkoutPost(pendingCheckout.url, sendAction, origin, sendBody, pendingCheckout.token, pendingCheckout.cookie, locale);
739
+ let smsRes = await checkoutPost(flow.url, sendAction, origin, sendBody, flow.token, flow.cookie, locale);
740
+ if (smsRes.status === 401 || smsRes.status === 403 || smsRes.status === 404 || smsRes.status === 410) {
741
+ flow = await newFlow();
742
+ pendingCheckout = flow;
743
+ smsRes = await checkoutPost(flow.url, sendAction, origin, sendBody, flow.token, flow.cookie, locale);
559
744
  }
560
- pendingCheckout.cookie = mergeCookies(pendingCheckout.cookie, smsRes);
561
- return smsRes.status === 204 ? { ok: true, value: void 0 } : phoneFailure(smsRes.status);
745
+ flow.cookie = mergeCookies(flow.cookie, smsRes);
746
+ if (smsRes.status !== 204) return phoneFailure(smsRes.status);
747
+ await rememberSignIn(phone);
748
+ return { ok: true, value: void 0 };
562
749
  } catch {
563
750
  pendingCheckout = void 0;
564
751
  }
565
752
  }
566
753
  const response = await phoneRequest(origin, "send", phone, void 0, locale);
567
754
  if (response.status === 204) {
755
+ await rememberSignIn(phone);
568
756
  const pendingToken = response.headers.get("x-inkmap-pending-token")?.trim();
569
- if (pendingToken && /^[A-Za-z0-9_-]{43}$/.test(pendingToken)) {
570
- startMagicPoll(origin, pendingToken);
571
- }
757
+ if (pendingToken && /^[A-Za-z0-9_-]{43}$/.test(pendingToken)) await waitFor(origin, pendingToken, phone);
572
758
  return { ok: true, value: void 0 };
573
759
  }
574
760
  return phoneFailure(response.status);
@@ -576,39 +762,44 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
576
762
  return phoneFailure();
577
763
  }
578
764
  },
579
- async signInByPhone(phone, code) {
765
+ async signInByPhone(phone, code, localeHint) {
580
766
  if (typeof phone !== "string" || !phone.trim() || phone.length > 254 || typeof code !== "string" || !/^\d{6}$/.test(code)) return phoneFailure(400);
581
767
  const isEmail = phone.includes("@");
768
+ const locale = clientLocale(localeHint);
582
769
  const version = generation;
583
770
  try {
584
771
  const origin = billingOrigin(getOrigin());
585
772
  let token;
586
773
  let checkoutUrl;
587
774
  let cookie;
588
- if (pendingCheckout && pendingCheckout.origin === origin && !loginOnly) {
775
+ const flow = pendingCheckout;
776
+ if (!loginOnly && flow && flow.origin === origin) {
589
777
  const verifyAction = isEmail ? "email/verify" : "login";
590
778
  const verifyBody = isEmail ? { email: phone, code } : { phone, code };
591
- const loginRes = await checkoutPost(pendingCheckout.url, verifyAction, origin, verifyBody, pendingCheckout.token, pendingCheckout.cookie);
779
+ const loginRes = await checkoutPost(flow.url, verifyAction, origin, verifyBody, flow.token, flow.cookie, locale);
592
780
  if (!loginRes.ok) {
593
- if (loginRes.status === 410 || loginRes.status === 404) pendingCheckout = void 0;
781
+ if (loginRes.status === 401 || loginRes.status === 403 || loginRes.status === 404 || loginRes.status === 410) {
782
+ if (pendingCheckout === flow) pendingCheckout = void 0;
783
+ }
594
784
  return phoneFailure(loginRes.status);
595
785
  }
596
- cookie = mergeCookies(pendingCheckout.cookie, loginRes);
597
- token = pendingCheckout.token;
598
- checkoutUrl = pendingCheckout.url;
599
- pendingCheckout = void 0;
600
- const orderRes = await checkoutPost(checkoutUrl, "order", origin, {}, token, cookie).catch(() => null);
786
+ cookie = mergeCookies(flow.cookie, loginRes);
787
+ token = flow.token;
788
+ checkoutUrl = flow.url;
789
+ if (pendingCheckout === flow) pendingCheckout = void 0;
790
+ const orderRes = await checkoutPost(checkoutUrl, "order", origin, {}, token, cookie, locale).catch(() => null);
601
791
  if (orderRes?.ok) {
602
792
  cookie = mergeCookies(cookie, orderRes);
603
793
  const orderData = await orderRes.json().catch(() => null);
604
794
  if (orderData && typeof orderData === "object") {
605
795
  if (orderData.active === true) {
606
- cachedOrder = { at: Date.now(), origin, result: { status: "active", state: current } };
796
+ cachedOrder = { at: Date.now(), origin, locale, result: { status: "active", state: current } };
607
797
  } else if (typeof orderData.qr === "string" && orderData.qr) {
608
798
  const qr = orderData.qr.startsWith("data:image/") ? orderData.qr : "data:image/png;base64," + orderData.qr;
609
799
  cachedOrder = {
610
800
  at: Date.now(),
611
801
  origin,
802
+ locale,
612
803
  result: {
613
804
  status: "qr",
614
805
  qr,
@@ -617,12 +808,12 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
617
808
  }
618
809
  };
619
810
  } else if (typeof orderData.checkoutUrl === "string" && /^https:\/\//.test(orderData.checkoutUrl)) {
620
- cachedOrder = { at: Date.now(), origin, result: { status: "redirect", url: orderData.checkoutUrl } };
811
+ cachedOrder = { at: Date.now(), origin, locale, result: { status: "redirect", url: orderData.checkoutUrl } };
621
812
  }
622
813
  }
623
814
  }
624
815
  } else {
625
- const response = await phoneRequest(origin, "verify", phone, code);
816
+ const response = await phoneRequest(origin, "verify", phone, code, locale);
626
817
  if (response.status !== 201) return phoneFailure(response.status);
627
818
  cookie = mergeCookies(void 0, response);
628
819
  const body = await response.json();
@@ -645,10 +836,15 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
645
836
  return phoneFailure();
646
837
  }
647
838
  if (cachedOrder?.result.status === "active") state.active = true;
839
+ if (!checkoutUrl && state.active !== true && await mustPayFirst()) {
840
+ await rememberSignIn(phone);
841
+ await waitFor(origin, token, phone);
842
+ return { ok: false, reason: "notPro" };
843
+ }
648
844
  return await writeSession(async () => {
649
845
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin())) return phoneFailure();
650
- stopMagicPoll();
651
- await storage.write(JSON.stringify({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
846
+ clearWaiting();
847
+ await storage.write(sessionRecord({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
652
848
  ++generation;
653
849
  activeOrigin = origin;
654
850
  applyEntitlement(state);
@@ -661,12 +857,12 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
661
857
  }
662
858
  },
663
859
  async deactivate() {
664
- stopMagicPoll();
860
+ clearWaiting();
665
861
  pendingCheckout = void 0;
666
862
  cachedOrder = void 0;
667
863
  const saved = await writeSession(async () => {
668
864
  const previous = await storage.read();
669
- await storage.write(void 0);
865
+ await storage.write(signedOutRecord());
670
866
  ++generation;
671
867
  clearTimeout(timer);
672
868
  lastCheck = 0;
@@ -676,7 +872,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
676
872
  if (!saved) return;
677
873
  try {
678
874
  const { origin, token } = JSON.parse(saved);
679
- if (origin !== billingOrigin(getOrigin())) return;
875
+ if (origin !== billingOrigin(getOrigin()) || typeof token !== "string") return;
680
876
  await fetch(origin + "/billing/v1/entitlement", {
681
877
  method: "DELETE",
682
878
  headers: { authorization: "Bearer " + token },
@@ -703,54 +899,20 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
703
899
  if (telemetryTimer) return;
704
900
  telemetryTimer = setTimeout(() => {
705
901
  telemetryTimer = void 0;
706
- void (async () => {
707
- if (disposed || !pendingEvents.size) return;
708
- let origin;
709
- try {
710
- origin = billingOrigin(getOrigin());
711
- } catch {
712
- return;
713
- }
714
- if (process.env.INKMAP_ALLOW_TEST_TELEMETRY !== "1") {
715
- if (origin === "https://billing.example.com" || process.env.INKMAP_DISABLE_TELEMETRY === "1" || process.env.NODE_TEST_CONTEXT) return;
716
- const customHome = process.env.INKMAP_HOME || "";
717
- if (customHome && (customHome.startsWith("/tmp/") || customHome.startsWith("/private/tmp/") || customHome.includes("/var/folders/") || customHome.includes("inkmap-npm-isolated-") || customHome.includes("inkmap-antigravity-mcp-") || customHome.includes("inkmap-local-editor-") || customHome.includes("inkmap-harness-"))) {
718
- return;
719
- }
720
- }
721
- const id = await (installIdPromise ??= localInstallId().catch(() => void 0));
722
- if (disposed || !id || !pendingEvents.size) return;
723
- await (trial ??= startTrial());
724
- const events = {};
725
- for (const [k, v] of pendingEvents.entries()) events[k] = v;
726
- pendingEvents.clear();
727
- const tier = current.pro ? "pro" : (current.trialUntil ?? 0) > Date.now() ? "trial" : "expired";
728
- const os = process.platform === "darwin" ? "mac" : process.platform === "win32" ? "win" : process.platform === "linux" ? "linux" : "other";
729
- const hostName = detectedHost || inferNodeHost();
730
- await fetch(origin + "/billing/v1/telemetry", {
731
- method: "POST",
732
- headers: { "content-type": "application/json" },
733
- redirect: "error",
734
- body: JSON.stringify({
735
- product: PRODUCT.id,
736
- installId: id,
737
- host: hostName,
738
- os,
739
- version: "0.3.8",
740
- locale: clientLocale(),
741
- tier,
742
- events
743
- }),
744
- signal: AbortSignal.timeout(5e3)
745
- }).catch(() => {
746
- });
747
- })();
902
+ void sendPendingTelemetry();
748
903
  }, 800);
749
904
  telemetryTimer.unref();
750
905
  },
906
+ async flushTelemetry() {
907
+ if (telemetryTimer) {
908
+ clearTimeout(telemetryTimer);
909
+ telemetryTimer = void 0;
910
+ }
911
+ await sendPendingTelemetry();
912
+ },
751
913
  dispose() {
752
914
  disposed = true;
753
- stopMagicPoll();
915
+ clearWaiting();
754
916
  clearTimeout(trialTimer);
755
917
  clearTimeout(timer);
756
918
  clearTimeout(telemetryTimer);
@@ -766,84 +928,54 @@ function inferNodeHost() {
766
928
  const app = (process.env.VSCODE_NLS_CONFIG || process.execPath || "").toLowerCase();
767
929
  if (app.includes("cursor")) return "cursor";
768
930
  if (app.includes("windsurf")) return "windsurf";
931
+ if (app.includes("trae")) return "trae";
932
+ if (app.includes("qoder")) return "qoder";
769
933
  return "vscode";
770
934
  }
771
935
  return "cli";
772
936
  }
773
- async function localInstallId() {
774
- const path2 = (0, import_node_path.join)(process.env.INKMAP_HOME ?? (0, import_node_path.join)((0, import_node_os.homedir)(), ".inkmap"), "install-id");
775
- let value;
937
+ async function atomicCreateIfMissing(path2, initialContent) {
776
938
  try {
777
- value = (await (0, import_promises.readFile)(path2, "utf8")).trim();
939
+ return await (0, import_promises.readFile)(path2, "utf8");
778
940
  } catch (error) {
779
941
  if (error.code !== "ENOENT") throw error;
780
942
  await (0, import_promises.mkdir)((0, import_node_path.dirname)(path2), { recursive: true, mode: 448 });
781
- const generated = "inst_" + (0, import_node_crypto.randomUUID)().replace(/-/g, "").slice(0, 24);
782
943
  const temporary = path2 + "." + (0, import_node_crypto.randomUUID)();
783
944
  try {
784
- await (0, import_promises.writeFile)(temporary, generated, { mode: 384, flag: "wx" });
785
- await (0, import_promises.link)(temporary, path2).catch((err) => {
786
- if (err.code !== "EEXIST") throw err;
945
+ await (0, import_promises.writeFile)(temporary, initialContent, { mode: 384, flag: "wx" });
946
+ await (0, import_promises.link)(temporary, path2).catch(async (err) => {
947
+ if (err.code === "EEXIST") return;
948
+ if (err.code === "EPERM" || err.code === "ENOSYS" || err.code === "EXDEV") {
949
+ await (0, import_promises.rename)(temporary, path2);
950
+ return;
951
+ }
952
+ throw err;
787
953
  });
788
954
  } finally {
789
- await (0, import_promises.rm)(temporary, { force: true });
955
+ await (0, import_promises.rm)(temporary, { force: true }).catch(() => {
956
+ });
790
957
  }
791
- value = (await (0, import_promises.readFile)(path2, "utf8")).trim();
958
+ return await (0, import_promises.readFile)(path2, "utf8");
792
959
  }
960
+ }
961
+ async function localInstallId() {
962
+ const path2 = (0, import_node_path.join)(process.env.INKMAP_HOME || (0, import_node_path.join)((0, import_node_os.homedir)(), ".inkmap"), "install-id");
963
+ const generated = "inst_" + (0, import_node_crypto.randomUUID)().replace(/-/g, "").slice(0, 24);
964
+ const value = (await atomicCreateIfMissing(path2, generated)).trim();
793
965
  return /^[A-Za-z0-9_:-]{8,64}$/.test(value) ? value : void 0;
794
966
  }
795
967
  async function localTrialDeadline() {
796
- const path2 = (0, import_node_path.join)((0, import_node_os.homedir)(), ".inkmap", "trial-start");
797
- const now = Date.now();
798
- let value;
799
- try {
800
- value = await (0, import_promises.readFile)(path2, "utf8");
801
- } catch (error) {
802
- if (error.code !== "ENOENT") throw error;
803
- await (0, import_promises.mkdir)((0, import_node_path.dirname)(path2), { recursive: true, mode: 448 });
804
- const temporary = path2 + "." + (0, import_node_crypto.randomUUID)();
805
- try {
806
- await (0, import_promises.writeFile)(temporary, String(now), { mode: 384, flag: "wx" });
807
- await (0, import_promises.link)(temporary, path2).catch((error2) => {
808
- if (error2.code !== "EEXIST") throw error2;
809
- });
810
- } finally {
811
- await (0, import_promises.rm)(temporary, { force: true });
812
- }
813
- value = await (0, import_promises.readFile)(path2, "utf8");
814
- }
968
+ const path2 = (0, import_node_path.join)(process.env.INKMAP_HOME || (0, import_node_path.join)((0, import_node_os.homedir)(), ".inkmap"), "trial-start");
969
+ const value = await atomicCreateIfMissing(path2, String(Date.now()));
815
970
  const started = Number(value);
816
971
  return Number.isSafeInteger(started) && started > 0 && started <= Date.now() ? started + TRIAL_MS : void 0;
817
972
  }
818
- var AD_TTL = 6 * 60 * 60 * 1e3;
819
- function adFeed(url) {
820
- let cache;
821
- return async () => {
822
- if (!url) return [];
823
- if (cache && Date.now() - cache.at < AD_TTL) return cache.ads;
824
- try {
825
- const res = await fetch(url, { signal: AbortSignal.timeout(5e3), headers: { accept: "application/json" } });
826
- const ads = res.ok ? sanitizeAds(await res.json()) : [];
827
- cache = { at: Date.now(), ads };
828
- return ads;
829
- } catch {
830
- cache = { at: Date.now(), ads: [] };
831
- return [];
832
- }
833
- };
834
- }
835
-
836
- // packages/vscode/src/browser.ts
837
- var import_node_child_process2 = require("node:child_process");
838
- var vscode2 = __toESM(require("vscode"));
839
973
 
840
- // packages/cli/src/server.ts
841
- var import_node_crypto2 = require("node:crypto");
842
- var import_node_fs = require("node:fs");
974
+ // packages/cli/src/workspace-fs.ts
843
975
  var import_promises2 = require("node:fs/promises");
844
- var import_node_http = require("node:http");
845
976
  var import_node_os2 = require("node:os");
846
977
  var import_node_path2 = require("node:path");
978
+ var MAX_MARKDOWN_BYTES = 5 * 1024 * 1024;
847
979
  var SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
848
980
  ".git",
849
981
  ".hg",
@@ -866,14 +998,20 @@ var SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
866
998
  "coverage",
867
999
  ".tmp"
868
1000
  ]);
869
- function insideRoot(root, target) {
1001
+ var MARKMAP_RE = /\.markmap\.md$/i;
1002
+ function insideOrEqual(root, target) {
870
1003
  if (root === target) return true;
871
1004
  const rel = (0, import_node_path2.relative)(root, target);
872
1005
  return Boolean(rel && !(0, import_node_path2.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(".." + import_node_path2.sep));
873
1006
  }
1007
+ function hasHiddenSegment(root, target) {
1008
+ const rel = (0, import_node_path2.relative)(root, target);
1009
+ if (!rel || rel === ".") return false;
1010
+ return rel.split(import_node_path2.sep).some((part) => part.startsWith("."));
1011
+ }
874
1012
  async function findProjectRoot(filePath) {
875
- let cur = (0, import_node_path2.dirname)(filePath);
876
1013
  const home = await (0, import_promises2.realpath)((0, import_node_os2.homedir)()).catch(() => (0, import_node_os2.homedir)());
1014
+ let cur = (0, import_node_path2.dirname)(filePath);
877
1015
  while (cur && cur !== (0, import_node_path2.dirname)(cur) && cur !== home) {
878
1016
  try {
879
1017
  await (0, import_promises2.lstat)((0, import_node_path2.join)(cur, ".git"));
@@ -884,7 +1022,7 @@ async function findProjectRoot(filePath) {
884
1022
  }
885
1023
  return (0, import_node_path2.dirname)(filePath);
886
1024
  }
887
- async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
1025
+ async function scanMarkdownFiles(rootDir, { maxFiles = 200, maxDepth = 4, byRecent = false } = {}) {
888
1026
  const found = [];
889
1027
  async function walk(dir, depth) {
890
1028
  if (depth > maxDepth || found.length >= maxFiles) return;
@@ -902,11 +1040,10 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
902
1040
  if (!SKIP_SCAN_DIRS.has(entry.name)) await walk(full, depth + 1);
903
1041
  } else if (entry.isFile() && /\.md$/i.test(entry.name)) {
904
1042
  try {
905
- const st = await (0, import_promises2.lstat)(full);
906
- if (st.isFile() && st.size <= 5 * 1024 * 1024) {
907
- const real = await (0, import_promises2.realpath)(full);
908
- if (real === full && insideRoot(rootDir, real)) found.push(real);
909
- }
1043
+ const info = await (0, import_promises2.lstat)(full);
1044
+ if (!info.isFile() || info.size > MAX_MARKDOWN_BYTES) continue;
1045
+ const real = await (0, import_promises2.realpath)(full);
1046
+ if (real === full && insideOrEqual(rootDir, real)) found.push({ path: real, mtimeMs: info.mtimeMs });
910
1047
  } catch {
911
1048
  }
912
1049
  }
@@ -914,13 +1051,16 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
914
1051
  }
915
1052
  await walk(rootDir, 0);
916
1053
  found.sort((a, b) => {
917
- const aM = /\.markmap\.md$/i.test(a) ? 0 : 1;
918
- const bM = /\.markmap\.md$/i.test(b) ? 0 : 1;
919
- if (aM !== bM) return aM - bM;
920
- return a.localeCompare(b);
1054
+ const am = MARKMAP_RE.test(a.path) ? 0 : 1;
1055
+ const bm = MARKMAP_RE.test(b.path) ? 0 : 1;
1056
+ if (am !== bm) return am - bm;
1057
+ if (byRecent && Math.abs(b.mtimeMs - a.mtimeMs) > 1e3) return b.mtimeMs - a.mtimeMs;
1058
+ return a.path.localeCompare(b.path);
921
1059
  });
922
1060
  return found;
923
1061
  }
1062
+
1063
+ // packages/cli/src/server.ts
924
1064
  var MAX_BODY = 20 * 1024 * 1024;
925
1065
  var TYPES = {
926
1066
  ".html": "text/html; charset=utf-8",
@@ -932,55 +1072,67 @@ var TYPES = {
932
1072
  ".jpeg": "image/jpeg",
933
1073
  ".gif": "image/gif",
934
1074
  ".webp": "image/webp",
1075
+ ".avif": "image/avif",
1076
+ ".bmp": "image/bmp",
1077
+ ".ico": "image/x-icon",
935
1078
  ".woff2": "font/woff2",
936
1079
  ".woff": "font/woff",
937
1080
  ".ttf": "font/ttf",
938
1081
  ".json": "application/json"
939
1082
  };
1083
+ var HttpError = class extends Error {
1084
+ constructor(status, message) {
1085
+ super(message);
1086
+ this.status = status;
1087
+ }
1088
+ };
1089
+ var LOOPBACK_HOST = /^(?:127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/i;
940
1090
  var hash = (s) => (0, import_node_crypto2.createHash)("sha1").update(s).digest("hex");
941
1091
  function docName(path2) {
942
- return (0, import_node_path2.basename)(path2).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
1092
+ return (0, import_node_path3.basename)(path2).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
943
1093
  }
944
1094
  function viewStateFile(key) {
945
- const base = process.env.INKMAP_HOME ?? (0, import_node_path2.join)((0, import_node_os2.homedir)(), ".inkmap");
946
- return (0, import_node_path2.join)(base, "view-state", hash(key) + ".json");
1095
+ const base = process.env.INKMAP_HOME || (0, import_node_path3.join)((0, import_node_os3.homedir)(), ".inkmap");
1096
+ return (0, import_node_path3.join)(base, "view-state", hash(key) + ".json");
947
1097
  }
948
1098
  async function readDiskViewState(key) {
949
1099
  try {
950
- return sanitizeViewState(JSON.parse(await (0, import_promises2.readFile)(viewStateFile(key), "utf8")));
1100
+ return sanitizeViewState(JSON.parse(await (0, import_promises3.readFile)(viewStateFile(key), "utf8")));
951
1101
  } catch {
952
1102
  return void 0;
953
1103
  }
954
1104
  }
955
1105
  async function writeDiskViewState(key, state) {
956
1106
  const target = viewStateFile(key);
957
- await (0, import_promises2.mkdir)((0, import_node_path2.dirname)(target), { recursive: true, mode: 448 });
1107
+ await (0, import_promises3.mkdir)((0, import_node_path3.dirname)(target), { recursive: true, mode: 448 });
958
1108
  const temp = `${target}.${process.pid}.${Date.now()}`;
959
1109
  try {
960
- await (0, import_promises2.writeFile)(temp, JSON.stringify(state), { mode: 384 });
961
- await (0, import_promises2.rename)(temp, target);
1110
+ await (0, import_promises3.writeFile)(temp, JSON.stringify(state), { mode: 384 });
1111
+ await (0, import_promises3.rename)(temp, target);
962
1112
  } finally {
963
- await (0, import_promises2.rm)(temp, { force: true }).catch(() => {
1113
+ await (0, import_promises3.rm)(temp, { force: true }).catch(() => {
964
1114
  });
965
1115
  }
966
1116
  }
967
1117
  async function fileSource(file, log = () => {
968
1118
  }) {
969
- const path2 = await (0, import_promises2.realpath)((0, import_node_path2.resolve)(file)).catch(() => (0, import_node_path2.resolve)(file));
970
- if (!(await (0, import_promises2.stat)(path2)).isFile()) throw new Error(`\u4E0D\u662F\u6587\u4EF6\uFF1A${path2}`);
971
- const dir = (0, import_node_path2.dirname)(path2);
1119
+ const path2 = await (0, import_promises3.realpath)((0, import_node_path3.resolve)(file)).catch(() => (0, import_node_path3.resolve)(file));
1120
+ if (!(await (0, import_promises3.stat)(path2)).isFile()) throw new Error(`\u4E0D\u662F\u6587\u4EF6\uFF1A${path2}`);
1121
+ const dir = (0, import_node_path3.dirname)(path2);
972
1122
  return {
973
1123
  name: docName(path2),
974
1124
  key: path2,
975
1125
  dir,
976
- read: () => (0, import_promises2.readFile)(path2, "utf8"),
1126
+ read: () => (0, import_promises3.readFile)(path2, "utf8"),
977
1127
  async write(md) {
978
- await (0, import_promises2.writeFile)(path2, md, "utf8");
1128
+ await (0, import_promises3.writeFile)(path2, md, "utf8");
979
1129
  log(`\u5DF2\u5199\u56DE ${path2}`);
980
1130
  },
981
1131
  watch(onChange) {
982
1132
  const watcher = (0, import_node_fs.watch)(dir, (_, changed) => {
983
- if (!changed || changed === (0, import_node_path2.basename)(path2)) onChange();
1133
+ if (!changed || changed === (0, import_node_path3.basename)(path2)) onChange();
1134
+ });
1135
+ watcher.on("error", () => {
984
1136
  });
985
1137
  return () => watcher.close();
986
1138
  },
@@ -989,21 +1141,67 @@ async function fileSource(file, log = () => {
989
1141
  };
990
1142
  }
991
1143
  function within(root, rel) {
992
- const base = root.endsWith(import_node_path2.sep) ? root : root + import_node_path2.sep;
993
- const full = (0, import_node_path2.normalize)((0, import_node_path2.join)(root, decodeURIComponent(rel)));
1144
+ let decoded;
1145
+ try {
1146
+ decoded = decodeURIComponent(rel);
1147
+ } catch {
1148
+ return null;
1149
+ }
1150
+ const resolvedRoot = (0, import_node_path3.resolve)(root);
1151
+ const base = resolvedRoot.endsWith(import_node_path3.sep) ? resolvedRoot : resolvedRoot + import_node_path3.sep;
1152
+ const full = (0, import_node_path3.normalize)((0, import_node_path3.join)(resolvedRoot, decoded));
994
1153
  return full.startsWith(base) ? full : null;
995
1154
  }
996
- async function serve({ source: initialSource, webRoot, port = 4377, host = "127.0.0.1", log = () => {
997
- }, license, ads, sidebar = false, sidebarPurchase = false, sidebarAccountNavigation = false, loginOnly = false, ideWorkspace = false, workspaceRoots = [] }) {
1155
+ async function openBrowserWindow(url) {
1156
+ if (process.env.INKMAP_NO_OPEN === "1" || !/^http:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):[0-9]+\//.test(url)) return;
1157
+ const run = (cmd, args) => new Promise((done) => {
1158
+ const child = (0, import_node_child_process2.spawn)(cmd, args, { stdio: "ignore", detached: true });
1159
+ child.on("error", () => done(false));
1160
+ child.on("exit", (code) => done(code === 0));
1161
+ child.unref();
1162
+ });
1163
+ if (process.platform === "darwin") {
1164
+ if (await run("open", ["-a", "Google Chrome", url])) return;
1165
+ await run("open", [url]);
1166
+ return;
1167
+ }
1168
+ if (process.platform === "win32") {
1169
+ if (await run("cmd", ["/c", "start", "", "chrome", url])) return;
1170
+ await run("cmd", ["/c", "start", "", url]);
1171
+ return;
1172
+ }
1173
+ if (await run("google-chrome", [url])) return;
1174
+ await run("xdg-open", [url]);
1175
+ }
1176
+ async function serve({
1177
+ source: initialSource,
1178
+ webRoot,
1179
+ port = 4377,
1180
+ host = "127.0.0.1",
1181
+ log = () => {
1182
+ },
1183
+ license,
1184
+ sidebar = false,
1185
+ sidebarPurchase = false,
1186
+ sidebarAccountNavigation = false,
1187
+ ideWorkspace = false,
1188
+ workspaceRoots = [],
1189
+ confineToWorkspaceRoots = false,
1190
+ openSource = (path2) => fileSource(path2, log),
1191
+ allowPurchase = true
1192
+ }) {
998
1193
  if (sidebar && host !== "127.0.0.1") throw new Error("The sidebar bridge requires loopback.");
999
1194
  const prefix = sidebar ? `/s/${(0, import_node_crypto2.randomBytes)(24).toString("hex")}/` : "/";
1000
1195
  let activeSource = initialSource;
1196
+ let browserCompanion = null;
1001
1197
  let bound;
1002
1198
  let current = await activeSource.read();
1003
1199
  let version = hash(current);
1004
1200
  let viewState = await activeSource.readView?.();
1005
1201
  const clients = /* @__PURE__ */ new Set();
1006
- const canPurchase = !loginOnly && (!sidebar || sidebarPurchase);
1202
+ const canPurchase = sidebar ? sidebarPurchase : allowPurchase;
1203
+ const allowedHosts = /* @__PURE__ */ new Set();
1204
+ const urlHost = host.includes(":") ? `[${host}]` : host;
1007
1205
  const docState = () => ({
1008
1206
  name: activeSource.name,
1009
1207
  md: current,
@@ -1036,35 +1234,35 @@ data: ${JSON.stringify(data)}
1036
1234
  broadcast();
1037
1235
  }
1038
1236
  let pending;
1039
- let unwatch = activeSource.watch(() => {
1237
+ const scheduleRefresh = () => {
1040
1238
  clearTimeout(pending);
1041
- pending = setTimeout(async () => {
1042
- void serialized(refresh).catch(() => {
1043
- });
1044
- }, 80);
1045
- });
1239
+ pending = setTimeout(() => void serialized(refresh).catch(() => {
1240
+ }), 80);
1241
+ };
1242
+ let unwatch = activeSource.watch(scheduleRefresh);
1243
+ const canonicalActiveKey = async () => activeSource.key ? await (0, import_promises3.realpath)(activeSource.key).catch(() => activeSource.key) : void 0;
1046
1244
  async function collectWorkspaceFiles() {
1047
1245
  const roots = /* @__PURE__ */ new Map();
1048
- if (activeSource.key) {
1049
- const realKey = await (0, import_promises2.realpath)(activeSource.key).catch(() => activeSource.key);
1050
- const projRoot = await (0, import_promises2.realpath)(await findProjectRoot(realKey)).catch(() => (0, import_node_path2.dirname)(realKey));
1051
- roots.set(projRoot, { path: projRoot, name: (0, import_node_path2.basename)(projRoot), active: true });
1246
+ if (activeSource.key && !confineToWorkspaceRoots) {
1247
+ const realKey = await (0, import_promises3.realpath)(activeSource.key).catch(() => activeSource.key);
1248
+ const projRoot = await (0, import_promises3.realpath)(await findProjectRoot(realKey)).catch(() => (0, import_node_path3.dirname)(realKey));
1249
+ roots.set(projRoot, { path: projRoot, name: (0, import_node_path3.basename)(projRoot), active: true });
1052
1250
  }
1053
- const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(import_node_path2.delimiter)].filter(Boolean);
1251
+ const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(import_node_path3.delimiter)].filter(Boolean);
1054
1252
  for (const raw of envRoots) {
1055
- const real = await (0, import_promises2.realpath)((0, import_node_path2.resolve)(raw)).catch(() => null);
1253
+ const real = await (0, import_promises3.realpath)((0, import_node_path3.resolve)(raw)).catch(() => null);
1056
1254
  if (real && !roots.has(real)) {
1057
- roots.set(real, { path: real, name: (0, import_node_path2.basename)(real), active: roots.size === 0 });
1255
+ roots.set(real, { path: real, name: (0, import_node_path3.basename)(real), active: roots.size === 0 });
1058
1256
  }
1059
1257
  }
1060
1258
  const items = [];
1061
1259
  const seen = /* @__PURE__ */ new Set();
1062
1260
  for (const root of roots.values()) {
1063
- const files = await scanProjectMarkdownFiles(root.path);
1261
+ const files = (await scanMarkdownFiles(root.path)).map((entry) => entry.path);
1064
1262
  for (const f of files) {
1065
1263
  if (seen.has(f)) continue;
1066
1264
  seen.add(f);
1067
- const rel = (0, import_node_path2.relative)(root.path, f);
1265
+ const rel = (0, import_node_path3.relative)(root.path, f);
1068
1266
  items.push({
1069
1267
  path: f,
1070
1268
  label: `${root.name} / ${rel}`,
@@ -1072,42 +1270,49 @@ data: ${JSON.stringify(data)}
1072
1270
  });
1073
1271
  }
1074
1272
  }
1075
- if (activeSource.key && !seen.has(activeSource.key)) {
1273
+ const activeReal = await canonicalActiveKey();
1274
+ if (activeSource.key && activeReal && !seen.has(activeReal)) {
1076
1275
  items.unshift({
1077
1276
  path: activeSource.key,
1078
- label: `${(0, import_node_path2.basename)(activeSource.dir)} / ${(0, import_node_path2.basename)(activeSource.key)}`,
1277
+ label: `${(0, import_node_path3.basename)(activeSource.dir)} / ${(0, import_node_path3.basename)(activeSource.key)}`,
1079
1278
  group: "active"
1080
1279
  });
1081
1280
  }
1082
1281
  return { roots: [...roots.values()], files: items };
1083
1282
  }
1084
- async function switchSourceToFile(candidatePath) {
1085
- if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath)) {
1086
- throw new Error("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002");
1283
+ const zh2 = () => detectOsLocale() === "zh";
1284
+ async function switchSourceToFile(candidatePath, trustCaller = false) {
1285
+ const notMarkdown = () => new HttpError(400, zh2() ? "\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002" : "Choose a .md or .markmap.md file.");
1286
+ if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath)) throw notMarkdown();
1287
+ const resolvedCandidate = (0, import_node_path3.resolve)(candidatePath);
1288
+ const rawStat = await (0, import_promises3.lstat)(resolvedCandidate).catch(() => null);
1289
+ const realTarget = await (0, import_promises3.realpath)(resolvedCandidate).catch(() => null);
1290
+ const targetStat = realTarget ? await (0, import_promises3.stat)(realTarget).catch(() => null) : null;
1291
+ if (!rawStat || rawStat.isSymbolicLink() && !trustCaller || !realTarget || !targetStat?.isFile() || targetStat.size > MAX_MARKDOWN_BYTES) {
1292
+ throw new HttpError(403, zh2() ? "\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684\u666E\u901A Markdown \u6587\u4EF6\u3002" : "Choose a regular Markdown file up to 5 MiB.");
1087
1293
  }
1088
- const realTarget = await (0, import_promises2.realpath)((0, import_node_path2.resolve)(candidatePath));
1089
- const st = await (0, import_promises2.lstat)(realTarget);
1090
- if (!st.isFile() || st.size > 5 * 1024 * 1024) {
1091
- throw new Error("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684 Markdown \u6587\u4EF6\u3002");
1092
- }
1093
- const { roots } = await collectWorkspaceFiles();
1094
- if (roots.length > 0 && !roots.some((r) => insideRoot(r.path, realTarget))) {
1095
- throw new Error("\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u9879\u76EE\u5DE5\u4F5C\u533A\u5185\u3002");
1294
+ if (!/\.md$/i.test(realTarget)) throw notMarkdown();
1295
+ if (!trustCaller) {
1296
+ const { roots } = await collectWorkspaceFiles();
1297
+ const matchedRoot = roots.find((r) => insideOrEqual(r.path, realTarget));
1298
+ if (!matchedRoot) {
1299
+ throw new HttpError(403, zh2() ? "\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u9879\u76EE\u5DE5\u4F5C\u533A\u5185\u3002" : "This file is outside the current workspace.");
1300
+ }
1301
+ if (hasHiddenSegment(matchedRoot.path, realTarget)) {
1302
+ throw new HttpError(403, zh2() ? "\u4E0D\u652F\u6301\u8BBF\u95EE\u9690\u85CF\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002" : "Files in hidden folders are not allowed.");
1303
+ }
1096
1304
  }
1097
- if (activeSource.key === realTarget) return;
1305
+ if (await canonicalActiveKey() === realTarget) return;
1306
+ const next = await openSource(trustCaller ? resolvedCandidate : realTarget);
1307
+ const text = await next.read();
1308
+ const nextView = await next.readView?.();
1098
1309
  clearTimeout(pending);
1099
1310
  unwatch();
1100
- activeSource = await fileSource(realTarget, log);
1101
- current = await activeSource.read();
1102
- version = hash(current);
1103
- viewState = await activeSource.readView?.();
1104
- unwatch = activeSource.watch(() => {
1105
- clearTimeout(pending);
1106
- pending = setTimeout(async () => {
1107
- void serialized(refresh).catch(() => {
1108
- });
1109
- }, 80);
1110
- });
1311
+ activeSource = next;
1312
+ current = text;
1313
+ version = hash(text);
1314
+ viewState = nextView;
1315
+ unwatch = activeSource.watch(scheduleRefresh);
1111
1316
  broadcast();
1112
1317
  }
1113
1318
  const json = (res, status, body) => {
@@ -1120,7 +1325,7 @@ data: ${JSON.stringify(data)}
1120
1325
  req.on("data", (c) => {
1121
1326
  size += c.length;
1122
1327
  if (size > MAX_BODY) {
1123
- fail(new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"));
1328
+ fail(new HttpError(413, zh2() ? "\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927\u3002" : "The request is too large."));
1124
1329
  req.destroy();
1125
1330
  } else chunks.push(c);
1126
1331
  });
@@ -1130,19 +1335,26 @@ data: ${JSON.stringify(data)}
1130
1335
  const sendFile = async (res, full) => {
1131
1336
  if (!full) return json(res, 403, { error: "forbidden" });
1132
1337
  try {
1133
- const ext = (0, import_node_path2.extname)(full).toLowerCase();
1338
+ const ext = (0, import_node_path3.extname)(full).toLowerCase();
1134
1339
  if (ext === ".html") {
1135
1340
  const osLoc = detectOsLocale();
1136
- const htmlText = (await (0, import_promises2.readFile)(full, "utf8")).replace(
1341
+ const htmlText = (await (0, import_promises3.readFile)(full, "utf8")).replace(
1137
1342
  /<html\b([^>]*)>/i,
1138
- `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`
1343
+ () => `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`
1139
1344
  );
1140
1345
  res.writeHead(200, { "content-type": TYPES[".html"], "cache-control": "no-store" });
1141
1346
  res.end(htmlText, "utf8");
1142
1347
  return;
1143
1348
  }
1144
- const body = await (0, import_promises2.readFile)(full);
1145
- res.writeHead(200, { "content-type": TYPES[ext] ?? "application/octet-stream", "cache-control": sidebar ? "no-store" : "no-cache" });
1349
+ const body = await (0, import_promises3.readFile)(full);
1350
+ const headers = {
1351
+ "content-type": TYPES[ext] ?? "application/octet-stream",
1352
+ "cache-control": sidebar ? "no-store" : "no-cache"
1353
+ };
1354
+ if (ext === ".svg") {
1355
+ headers["content-security-policy"] = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox";
1356
+ }
1357
+ res.writeHead(200, headers);
1146
1358
  res.end(body);
1147
1359
  } catch {
1148
1360
  json(res, 404, { error: "not found" });
@@ -1151,17 +1363,26 @@ data: ${JSON.stringify(data)}
1151
1363
  const server = (0, import_node_http.createServer)(async (req, res) => {
1152
1364
  try {
1153
1365
  const url = new URL(req.url ?? "/", "http://localhost");
1366
+ const reqHost = req.headers.host ?? "";
1367
+ const hostAllowed = LOOPBACK_HOST.test(reqHost) || allowedHosts.has(reqHost.toLowerCase());
1154
1368
  if (sidebar) {
1155
1369
  res.setHeader("Referrer-Policy", "no-referrer");
1156
1370
  res.setHeader("X-Content-Type-Options", "nosniff");
1157
1371
  res.setHeader("Cache-Control", "no-store");
1158
1372
  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'");
1159
- if (req.headers.host !== `127.0.0.1:${bound}` || !url.pathname.startsWith(prefix)) return json(res, 404, { error: "not found" });
1373
+ if (reqHost !== `127.0.0.1:${bound}` || !url.pathname.startsWith(prefix)) return json(res, 404, { error: "not found" });
1160
1374
  if ((req.method === "PUT" || req.method === "POST") && (req.headers.origin !== `http://127.0.0.1:${bound}` || req.headers["content-type"] !== "application/json")) {
1161
1375
  return json(res, 403, { error: "forbidden" });
1162
1376
  }
1163
1377
  url.pathname = "/" + url.pathname.slice(prefix.length);
1378
+ } else if (!hostAllowed) {
1379
+ return json(res, 403, { error: "forbidden" });
1164
1380
  }
1381
+ const sameOriginWrite = () => {
1382
+ const origin = req.headers.origin;
1383
+ const sameOrigin = origin === "http://" + reqHost || allowedHosts.has(reqHost.toLowerCase()) && origin === "https://" + reqHost;
1384
+ return hostAllowed && sameOrigin && req.headers["content-type"] === "application/json";
1385
+ };
1165
1386
  if (!sidebar && req.method === "GET" && /^\/(?:%E3%80%82|%EF%BC%8C|[。,.,;;::!?!?])+$/i.test(url.pathname)) {
1166
1387
  res.writeHead(302, { Location: "/" + url.search });
1167
1388
  return res.end();
@@ -1184,6 +1405,7 @@ data: ${JSON.stringify(data)}
1184
1405
  });
1185
1406
  }
1186
1407
  if (url.pathname === "/api/view" && req.method === "PUT") {
1408
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1187
1409
  const cleaned = sanitizeViewState(JSON.parse(await readBody(req)));
1188
1410
  if (cleaned) {
1189
1411
  viewState = cleaned;
@@ -1193,8 +1415,9 @@ data: ${JSON.stringify(data)}
1193
1415
  return json(res, 200, { ok: true });
1194
1416
  }
1195
1417
  if (url.pathname === "/api/doc" && req.method === "PUT") {
1418
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1196
1419
  const { md, baseVersion } = JSON.parse(await readBody(req));
1197
- if (typeof md !== "string") return json(res, 400, { error: "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32" });
1420
+ if (typeof md !== "string") return json(res, 400, { error: zh2() ? "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u3002" : "md must be a string." });
1198
1421
  if (!hasAccess(await license?.state() ?? { pro: false })) return json(res, 403, { error: "Inkmap trial expired" });
1199
1422
  return await serialized(async () => {
1200
1423
  await refresh();
@@ -1204,34 +1427,62 @@ data: ${JSON.stringify(data)}
1204
1427
  current = md;
1205
1428
  version = hash(md);
1206
1429
  license?.track?.("doc_edit");
1207
- if (sidebar) broadcast();
1430
+ broadcast();
1208
1431
  }
1209
1432
  return json(res, 200, { version });
1210
1433
  });
1211
1434
  }
1212
1435
  if (url.pathname === "/api/license" && req.method === "GET") return json(res, 200, await license?.state() ?? { pro: false });
1213
- const sameOriginPost = () => {
1214
- const origin = req.headers.origin;
1215
- const reqHost = req.headers.host;
1216
- const local = reqHost && /^(127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/.test(reqHost);
1217
- return Boolean(local && origin === "http://" + reqHost && req.headers["content-type"] === "application/json");
1218
- };
1219
1436
  if (url.pathname === "/api/open" && req.method === "POST") {
1220
- if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1437
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1221
1438
  const { file } = JSON.parse(await readBody(req));
1222
- await serialized(() => switchSourceToFile(String(file ?? "")));
1439
+ await serialized(() => switchSourceToFile(String(file ?? ""), false));
1223
1440
  license?.track?.("doc_open");
1224
1441
  const { files } = await collectWorkspaceFiles();
1225
1442
  return json(res, 200, { currentFile: activeSource.key ?? null, files, doc: docState() });
1226
1443
  }
1227
1444
  if (url.pathname === "/api/telemetry" && req.method === "POST") {
1228
- if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1445
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1229
1446
  const { event } = JSON.parse(await readBody(req));
1230
1447
  if (typeof event === "string" && event) license?.track?.(event);
1231
1448
  return json(res, 200, { ok: true });
1232
1449
  }
1450
+ if (url.pathname === "/api/open-browser" && req.method === "POST") {
1451
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1452
+ if (license && !hasAccess(await license.state())) {
1453
+ return json(res, 402, { error: detectOsLocale() === "zh" ? "\u514D\u8D39\u8BD5\u7528\u5DF2\u5230\u671F\uFF0C\u8BF7\u5148\u89E3\u9501\u6216\u6062\u590D Pro\u3002" : "Trial expired. Unlock or restore Pro first." });
1454
+ }
1455
+ license?.track?.("feature_browser");
1456
+ if (!sidebar) {
1457
+ const directUrl = `http://${urlHost}:${bound}/`;
1458
+ await openBrowserWindow(directUrl);
1459
+ return json(res, 200, { ok: true, url: directUrl });
1460
+ }
1461
+ if (!browserCompanion) {
1462
+ browserCompanion = serve({
1463
+ source: activeSource,
1464
+ webRoot,
1465
+ host: "127.0.0.1",
1466
+ port: 0,
1467
+ license,
1468
+ sidebar: false,
1469
+ workspaceRoots,
1470
+ confineToWorkspaceRoots,
1471
+ openSource,
1472
+ allowPurchase: canPurchase
1473
+ });
1474
+ browserCompanion.catch(() => {
1475
+ browserCompanion = null;
1476
+ });
1477
+ }
1478
+ const companion = await browserCompanion;
1479
+ if (activeSource.key) await companion.switchToFile?.(activeSource.key, { trustCaller: true }).catch(() => {
1480
+ });
1481
+ await openBrowserWindow(companion.url);
1482
+ return json(res, 200, { ok: true, url: companion.url });
1483
+ }
1233
1484
  if (url.pathname === "/api/checkout" && req.method === "POST") {
1234
- if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1485
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1235
1486
  const { mode, locale } = JSON.parse(await readBody(req));
1236
1487
  if (mode !== "buy" && mode !== "restore") return json(res, 400, { error: "invalid checkout mode" });
1237
1488
  if (!canPurchase && mode === "buy") return json(res, 403, { error: "forbidden" });
@@ -1239,7 +1490,7 @@ data: ${JSON.stringify(data)}
1239
1490
  return json(res, 200, { url: await (typeof locale === "string" ? license.connect(mode, locale) : license.connect(mode)) });
1240
1491
  }
1241
1492
  if (url.pathname === "/api/order-pro" && req.method === "POST") {
1242
- if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1493
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1243
1494
  if (!canPurchase) return json(res, 403, { error: "forbidden" });
1244
1495
  if (!license) return json(res, 503, { error: "Inkmap checkout is unavailable." });
1245
1496
  if (typeof license.orderPro !== "function") return json(res, 501, { fallback: true });
@@ -1247,23 +1498,24 @@ data: ${JSON.stringify(data)}
1247
1498
  return json(res, 200, { result: await (typeof locale === "string" ? license.orderPro(locale) : license.orderPro()) });
1248
1499
  }
1249
1500
  if (url.pathname === "/api/phone-send" && req.method === "POST") {
1250
- if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1501
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1251
1502
  if (!license || typeof license.sendPhoneCode !== "function") return json(res, 501, { fallback: true });
1252
1503
  const { phone, locale } = JSON.parse(await readBody(req));
1253
1504
  return json(res, 200, { result: await (typeof locale === "string" ? license.sendPhoneCode(String(phone ?? ""), locale) : license.sendPhoneCode(String(phone ?? ""))) });
1254
1505
  }
1255
1506
  if (url.pathname === "/api/phone-verify" && req.method === "POST") {
1256
- if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1507
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1257
1508
  if (!license || typeof license.signInByPhone !== "function") return json(res, 501, { fallback: true });
1258
- const { phone, code } = JSON.parse(await readBody(req));
1259
- return json(res, 200, { result: await license.signInByPhone(String(phone ?? ""), String(code ?? "")) });
1509
+ const { phone, code, locale } = JSON.parse(await readBody(req));
1510
+ return json(res, 200, {
1511
+ result: await (typeof locale === "string" ? license.signInByPhone(String(phone ?? ""), String(code ?? ""), locale) : license.signInByPhone(String(phone ?? ""), String(code ?? "")))
1512
+ });
1260
1513
  }
1261
1514
  if (url.pathname === "/api/signout" && req.method === "POST") {
1262
- if (!sameOriginPost()) return json(res, 403, { error: "forbidden" });
1515
+ if (!sameOriginWrite()) return json(res, 403, { error: "forbidden" });
1263
1516
  await license?.deactivate();
1264
1517
  return json(res, 200, await license?.state() ?? { pro: false });
1265
1518
  }
1266
- if (url.pathname === "/api/ads") return json(res, 200, sidebar ? [] : await ads?.() ?? []);
1267
1519
  if (url.pathname === "/api/events") {
1268
1520
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
1269
1521
  res.write(": connected\n\n");
@@ -1274,16 +1526,19 @@ data: ${JSON.stringify(data)}
1274
1526
  if (url.pathname === "/favicon.ico") return void res.writeHead(204).end();
1275
1527
  if (url.pathname.startsWith("/doc-assets/")) {
1276
1528
  let asset = within(activeSource.dir, url.pathname.slice("/doc-assets/".length));
1277
- if (sidebar && asset) {
1278
- const root = await (0, import_promises2.realpath)(activeSource.dir);
1279
- asset = await (0, import_promises2.realpath)(asset).catch(() => null);
1280
- if (asset && (!asset.startsWith(root + import_node_path2.sep) || !/\.(?:png|jpe?g|gif|webp)$/i.test(asset))) asset = null;
1529
+ if (asset) {
1530
+ const root = await (0, import_promises3.realpath)(activeSource.dir).catch(() => null);
1531
+ asset = await (0, import_promises3.realpath)(asset).catch(() => null);
1532
+ const allowedExt = sidebar ? /\.(?:png|jpe?g|gif|webp|avif|bmp|ico)$/i : /\.(?:png|jpe?g|gif|webp|avif|bmp|ico|svg)$/i;
1533
+ if (!root || !asset || !insideOrEqual(root, asset) || !allowedExt.test(asset)) asset = null;
1281
1534
  }
1282
1535
  return sendFile(res, asset);
1283
1536
  }
1284
1537
  return sendFile(res, within(webRoot, url.pathname === "/" ? "index.html" : url.pathname.slice(1)));
1285
1538
  } catch (err) {
1286
- json(res, 500, { error: err instanceof Error ? err.message : String(err) });
1539
+ if (res.headersSent) return void res.end();
1540
+ const status = err instanceof HttpError ? err.status : err instanceof SyntaxError ? 400 : 500;
1541
+ json(res, status, { error: err instanceof Error ? err.message : String(err) });
1287
1542
  }
1288
1543
  });
1289
1544
  const listen = (p) => new Promise((ok, fail) => {
@@ -1294,18 +1549,30 @@ data: ${JSON.stringify(data)}
1294
1549
  });
1295
1550
  });
1296
1551
  try {
1297
- bound = await listen(port);
1552
+ try {
1553
+ bound = await listen(port);
1554
+ } catch (err) {
1555
+ if (err.code !== "EADDRINUSE") throw err;
1556
+ bound = await listen(0);
1557
+ }
1298
1558
  } catch (err) {
1299
- if (err.code !== "EADDRINUSE") throw err;
1300
- bound = await listen(0);
1559
+ clearTimeout(pending);
1560
+ unwatch();
1561
+ unlisten();
1562
+ throw err;
1301
1563
  }
1302
1564
  return {
1303
- url: `http://${host}:${bound}${prefix}`,
1304
- switchToFile: (filePath) => serialized(() => switchSourceToFile(filePath)),
1565
+ url: `http://${urlHost}:${bound}${prefix}`,
1566
+ switchToFile: (filePath, options) => serialized(() => switchSourceToFile(filePath, Boolean(options?.trustCaller))),
1567
+ allowHost: (extraHost) => {
1568
+ if (extraHost) allowedHosts.add(extraHost.toLowerCase());
1569
+ },
1305
1570
  close: () => new Promise((done) => {
1306
1571
  clearTimeout(pending);
1307
1572
  unwatch();
1308
1573
  unlisten();
1574
+ if (browserCompanion) void browserCompanion.then((s) => s.close()).catch(() => {
1575
+ });
1309
1576
  for (const res of clients) res.end();
1310
1577
  server.close(() => done());
1311
1578
  })
@@ -1407,19 +1674,20 @@ var zh = {
1407
1674
  copyLink: "\u590D\u5236\u94FE\u63A5",
1408
1675
  browserFailed: "\u65E0\u6CD5\u5728\u6D4F\u89C8\u5668\u6253\u5F00\u601D\u7EF4\u5BFC\u56FE\uFF1A{error}",
1409
1676
  readOnly: "\u6587\u6863\u65E0\u6CD5\u4FEE\u6539\uFF08\u53EF\u80FD\u662F\u53EA\u8BFB\u6587\u4EF6\uFF09",
1410
- buyPro: "\u8D2D\u4E70 Pro",
1411
- signIn: "\u767B\u5F55",
1412
- switchAccount: "\u5207\u6362\u8D26\u53F7",
1413
- proActiveDetail: "\u7EC8\u8EAB\u4F1A\u5458\u6743\u76CA\u5DF2\u5F00\u901A\u3002",
1414
- accountLine: "\u5F53\u524D\u8D26\u53F7\uFF1A{account}",
1415
- accountConnected: "\u5F53\u524D\u8D26\u53F7\uFF1A\u5DF2\u767B\u5F55",
1416
1677
  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",
1417
- checkoutHint: "\u5728\u6D4F\u89C8\u5668\u5B8C\u6210\u64CD\u4F5C\uFF0C\u5DF2\u6709 Pro \u6743\u76CA\u4F1A\u81EA\u52A8\u540C\u6B65\u3002",
1418
1678
  checkoutFailed: "\u65E0\u6CD5\u6253\u5F00\u8D2D\u4E70\u9875\u9762\u3002",
1419
- removed: "\u5DF2\u9000\u51FA\u767B\u5F55\u3002",
1420
- removeConfirm: "\u9000\u51FA\u5F53\u524D\u8D26\u53F7\uFF1F\u4E0B\u6B21\u767B\u5F55\u65F6\u4F1A\u81EA\u52A8\u540C\u6B65 Pro \u6743\u76CA\u3002",
1421
- remove: "\u9000\u51FA\u767B\u5F55",
1422
- saveExport: "\u5BFC\u51FA"
1679
+ saveExport: "\u5BFC\u51FA",
1680
+ onboardingTip: "\u{1F4A1} Inkmap \u601D\u7EF4\u5BFC\u56FE\u5DF2\u5C31\u7EEA\uFF1A\u70B9\u51FB\u5373\u53EF\u5728\u53F3\u4FA7\u5E76\u6392\u6253\u5F00\u53EF\u53CC\u5411\u7F16\u8F91\u7684\u8111\u56FE\u4E0E\u6D41\u7A0B\u56FE",
1681
+ onboardingAction: "\u7ACB\u5373\u6253\u5F00\u601D\u7EF4\u5BFC\u56FE",
1682
+ harnessOffer: "\u68C0\u6D4B\u5230 DeepSeek Harness\u3002\u8981\u628A Inkmap \u601D\u7EF4\u5BFC\u56FE\u63D2\u4EF6\u5B89\u88C5\u5230 DeepSeek Harness \u5417\uFF1F\u8FD9\u4F1A\u5728\u5B83\u7684\u684C\u9762\u914D\u7F6E\u4E2D\u52A0\u5165 Inkmap \u63D2\u4EF6\u7D22\u5F15\u5E76\u5B89\u88C5\u63D2\u4EF6\u3002",
1683
+ harnessInstall: "\u5B89\u88C5",
1684
+ harnessNoThanks: "\u4E0D\u7528\u4E86",
1685
+ harnessInstalling: "\u6B63\u5728\u628A Inkmap \u5B89\u88C5\u5230 DeepSeek Harness\u2026",
1686
+ harnessInstalled: "\u5DF2\u628A Inkmap \u5B89\u88C5\u5230 DeepSeek Harness\uFF0C\u91CD\u542F DeepSeek Harness \u540E\u5373\u53EF\u4F7F\u7528\u3002",
1687
+ harnessConfigured: "\u5DF2\u5728 DeepSeek Harness \u4E2D\u52A0\u5165 Inkmap \u63D2\u4EF6\u7D22\u5F15\uFF1B\u672A\u627E\u5230 dsh \u547D\u4EE4\uFF0C\u8BF7\u5728 DeepSeek Harness \u7684\u300C\u63D2\u4EF6\u300D\u9875\u5B89\u88C5 Inkmap\u3002",
1688
+ harnessAlready: "DeepSeek Harness \u4E2D\u5DF2\u5B89\u88C5 Inkmap\u3002",
1689
+ harnessNotFound: "\u672A\u627E\u5230 DeepSeek Harness \u684C\u9762\u7248\u3002",
1690
+ harnessFailed: "\u5B89\u88C5\u5230 DeepSeek Harness \u5931\u8D25\uFF1A{error}"
1423
1691
  };
1424
1692
  var en = {
1425
1693
  openMarkdownFirst: "Open a Markdown file first",
@@ -1427,19 +1695,20 @@ var en = {
1427
1695
  copyLink: "Copy link",
1428
1696
  browserFailed: "Could not open the mind map in the browser: {error}",
1429
1697
  readOnly: "The document cannot be modified (it may be read-only)",
1430
- buyPro: "Buy Pro",
1431
- signIn: "Sign In",
1432
- switchAccount: "Switch Account",
1433
- proActiveDetail: "Lifetime Pro membership is active.",
1434
- accountLine: "Account: {account}",
1435
- accountConnected: "Account: Signed in",
1436
1698
  trialExpired: "Your 7-day trial has ended. Buy Pro or sign in to an account that has Pro.",
1437
- checkoutHint: "Continue in your browser. Any existing Pro access will sync automatically.",
1438
1699
  checkoutFailed: "Could not open checkout.",
1439
- removed: "Signed out.",
1440
- removeConfirm: "Sign out? Your Pro access will sync the next time you sign in.",
1441
- remove: "Sign Out",
1442
- saveExport: "Export"
1700
+ saveExport: "Export",
1701
+ onboardingTip: "\u{1F4A1} Inkmap is ready: Open this Markdown file side-by-side as an interactive two-way mind map",
1702
+ onboardingAction: "Open Mind Map",
1703
+ harnessOffer: "DeepSeek Harness is installed. Add the Inkmap mind map plugin to it? This adds the Inkmap plugin index to its desktop profile and installs the plugin.",
1704
+ harnessInstall: "Install",
1705
+ harnessNoThanks: "No thanks",
1706
+ harnessInstalling: "Installing Inkmap in DeepSeek Harness\u2026",
1707
+ harnessInstalled: "Inkmap was installed in DeepSeek Harness. Restart DeepSeek Harness to use it.",
1708
+ harnessConfigured: "The Inkmap plugin index was added to DeepSeek Harness, but the dsh command was not found. Install Inkmap from the Plugins page in DeepSeek Harness.",
1709
+ harnessAlready: "Inkmap is already installed in DeepSeek Harness.",
1710
+ harnessNotFound: "DeepSeek Harness desktop was not found.",
1711
+ harnessFailed: "Could not install Inkmap in DeepSeek Harness: {error}"
1443
1712
  };
1444
1713
  var isChinese = () => detectOsLocale() === "zh";
1445
1714
  function t(key, vars = {}) {
@@ -1449,30 +1718,37 @@ function t(key, vars = {}) {
1449
1718
  // packages/vscode/src/browser.ts
1450
1719
  var VIEW_STATE_PREFIX = "inkmap.viewState:";
1451
1720
  var BrowserServers = class {
1452
- constructor(context, webRoot, log, license, ads) {
1721
+ constructor(context, webRoot, log, license) {
1453
1722
  this.context = context;
1454
1723
  this.webRoot = webRoot;
1455
1724
  this.log = log;
1456
1725
  this.license = license;
1457
- this.ads = ads;
1458
1726
  }
1459
1727
  servers = /* @__PURE__ */ new Map();
1460
1728
  async open(uri) {
1461
1729
  const key = uri.toString();
1462
1730
  let served = this.servers.get(key);
1463
1731
  if (!served) {
1732
+ const workspaceRoots = (vscode2.workspace.workspaceFolders ?? []).filter((f) => f.uri.scheme === "file").map((f) => f.uri.fsPath);
1464
1733
  served = serve({
1465
1734
  source: documentSource(uri, this.context),
1466
1735
  webRoot: this.webRoot,
1467
1736
  port: 0,
1468
1737
  log: (msg) => this.log.appendLine(`[${docName2(uri)}] ${msg}`),
1469
1738
  license: this.license,
1470
- ads: this.ads
1739
+ workspaceRoots,
1740
+ // Files picked in the browser tree still go through VS Code's document model (dirty buffers, save hooks).
1741
+ openSource: async (path2) => documentSource(vscode2.Uri.file(path2), this.context)
1471
1742
  });
1472
1743
  this.servers.set(key, served);
1473
1744
  served.catch(() => this.servers.delete(key));
1474
1745
  }
1475
- const { url } = await served;
1746
+ const server = await served;
1747
+ if (uri.scheme === "file") await server.switchToFile?.(uri.fsPath, { trustCaller: true }).catch(() => {
1748
+ });
1749
+ const external = await vscode2.env.asExternalUri(vscode2.Uri.parse(server.url));
1750
+ if (external.authority && external.authority.toLowerCase() !== new URL(server.url).host) server.allowHost(external.authority);
1751
+ const url = external.toString(true);
1476
1752
  this.log.appendLine(`[${docName2(uri)}] ${url}`);
1477
1753
  await openUrl(url);
1478
1754
  return url;
@@ -1488,6 +1764,7 @@ function documentSource(uri, context) {
1488
1764
  const viewKey = VIEW_STATE_PREFIX + uri.toString();
1489
1765
  return {
1490
1766
  name: docName2(uri),
1767
+ ...uri.scheme === "file" && { key: uri.fsPath },
1491
1768
  dir: docDir(uri)?.fsPath ?? "",
1492
1769
  read: async () => (await document()).getText(),
1493
1770
  async write(md) {
@@ -1512,7 +1789,7 @@ async function openUrl(url) {
1512
1789
  if (vscode2.workspace.getConfiguration("inkmap").get("browser", "chrome") !== "chrome") return fallback();
1513
1790
  const [cmd, args] = process.platform === "darwin" ? ["open", ["-a", "Google Chrome", url]] : process.platform === "win32" ? ["cmd", ["/c", "start", "", "chrome", url]] : ["google-chrome", [url]];
1514
1791
  const ok = await new Promise((done) => {
1515
- const child = (0, import_node_child_process2.spawn)(cmd, args, { stdio: "ignore", detached: true });
1792
+ const child = (0, import_node_child_process3.spawn)(cmd, args, { stdio: "ignore", detached: true });
1516
1793
  child.on("error", () => done(false));
1517
1794
  child.on("exit", (code) => done(code === 0));
1518
1795
  child.unref();
@@ -1525,7 +1802,7 @@ var vscode3 = __toESM(require("vscode"));
1525
1802
  var KEY = "inkmap.billing.session";
1526
1803
  function extensionLicense(context) {
1527
1804
  const app = (vscode3.env.appName || "").toLowerCase();
1528
- const host = app.includes("cursor") ? "cursor" : app.includes("windsurf") ? "windsurf" : app.includes("antigravity") ? "antigravity" : "vscode";
1805
+ const host = app.includes("cursor") ? "cursor" : app.includes("windsurf") ? "windsurf" : app.includes("trae") ? "trae" : app.includes("qoder") ? "qoder" : app.includes("antigravity") ? "antigravity" : "vscode";
1529
1806
  return licenseService({
1530
1807
  read: () => Promise.resolve(context.secrets.get(KEY)),
1531
1808
  write: async (token) => {
@@ -1541,12 +1818,12 @@ async function openCheckout(license, mode, localeHint) {
1541
1818
 
1542
1819
  // packages/vscode/src/mindmapEditor.ts
1543
1820
  var import_node_crypto3 = require("node:crypto");
1544
- var import_promises3 = require("node:fs/promises");
1821
+ var import_promises4 = require("node:fs/promises");
1545
1822
  var vscode4 = __toESM(require("vscode"));
1546
1823
 
1547
1824
  // packages/vscode/src/html.ts
1548
1825
  function webviewHtml(html, { webBase, assetBase, cspSource, nonce, locale }) {
1549
- const osLoc = locale === "auto" ? "" : /^zh\b/i.test(locale) ? "zh" : "en";
1826
+ const osLoc = locale === "auto" ? "" : /^zh(?:[-_.]|$)/i.test(locale) ? "zh" : "en";
1550
1827
  const csp = [
1551
1828
  "default-src 'none'",
1552
1829
  `img-src ${cspSource} https: data: blob:`,
@@ -1557,7 +1834,7 @@ function webviewHtml(html, { webBase, assetBase, cspSource, nonce, locale }) {
1557
1834
  ].join("; ");
1558
1835
  const head = `<meta http-equiv="Content-Security-Policy" content="${csp}">
1559
1836
  <script nonce="${nonce}">window.INKMAP_ASSET_BASE = ${JSON.stringify(assetBase)}; window.INKMAP_LOCALE = ${JSON.stringify(osLoc || locale)};</script>`;
1560
- return html.replace(/<html\b([^>]*)>/i, osLoc ? `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">` : "<html$1>").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>
1837
+ return html.replace(/<html\b([^>]*)>/i, (_m, attrs) => osLoc ? `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">` : `<html${attrs}>`).replace(/ crossorigin/g, "").replace(/(src|href)="\.\/assets\//g, (_m, attr) => `${attr}="${webBase}/assets/`).replace(/(src|href)="\.\/(app\.(?:js|css))"/g, (_m, attr, file) => `${attr}="${webBase}/${file}"`).replace(/<script /g, () => `<script nonce="${nonce}" `).replace("<head>", () => `<head>
1561
1838
  ${head}`);
1562
1839
  }
1563
1840
 
@@ -1566,28 +1843,42 @@ var VIEW_STATE_PREFIX2 = "inkmap.viewState:";
1566
1843
  var CHANGE_DELAY = 120;
1567
1844
  var REVEAL_DELAY = 150;
1568
1845
  var MindmapEditorProvider = class {
1569
- constructor(context, license, ads) {
1846
+ constructor(context, license) {
1570
1847
  this.context = context;
1571
1848
  this.license = license;
1572
- this.ads = ads;
1573
1849
  }
1574
1850
  static viewType = "inkmap.mindmap";
1575
1851
  panels = /* @__PURE__ */ new Set();
1852
+ readyPanels = /* @__PURE__ */ new WeakSet();
1853
+ panelDocuments = /* @__PURE__ */ new WeakMap();
1854
+ /** An account dialog requested for a document whose editor is still opening; expires so it never pops up later. */
1855
+ pendingAccount;
1576
1856
  /** The chat shortcut was pressed: the focused mind map says what is selected. Anywhere else it just opens the chat. */
1577
1857
  requestChat() {
1578
1858
  const panel = [...this.panels].find((p) => p.active);
1579
1859
  return panel ? panel.webview.postMessage({ type: "requestChat" }) : openChat();
1580
1860
  }
1581
- /** Opens the inline Category 1 account & payment panel directly inside the active Inkmap editor tab. */
1582
- openAccount() {
1583
- const panel = [...this.panels].find((p) => p.active) ?? [...this.panels].find((p) => p.visible);
1584
- if (!panel) return false;
1585
- void panel.webview.postMessage({ type: "openAccount" });
1861
+ /**
1862
+ * Opens the inline Category 1 account & payment panel: in the editor for `document` when given (waiting for it to
1863
+ * finish loading), otherwise in the active or visible Inkmap editor tab.
1864
+ */
1865
+ openAccount(document) {
1866
+ const panels = [...this.panels];
1867
+ const target = document?.toString();
1868
+ const panel = target ? panels.find((p) => this.panelDocuments.get(p) === target) : panels.find((p) => p.active) ?? panels.find((p) => p.visible);
1869
+ if (panel && this.readyPanels.has(panel)) {
1870
+ void panel.webview.postMessage({ type: "openAccount" });
1871
+ return true;
1872
+ }
1873
+ const uri = target ?? (panel && this.panelDocuments.get(panel));
1874
+ if (!uri) return false;
1875
+ this.pendingAccount = { uri, until: Date.now() + 1e4 };
1586
1876
  return true;
1587
1877
  }
1588
1878
  async resolveCustomTextEditor(document, panel) {
1589
1879
  const webview = panel.webview;
1590
1880
  this.panels.add(panel);
1881
+ this.panelDocuments.set(panel, document.uri.toString());
1591
1882
  const webRoot = vscode4.Uri.joinPath(this.context.extensionUri, "dist", "web");
1592
1883
  const assets = docDir(document.uri);
1593
1884
  webview.options = {
@@ -1639,17 +1930,28 @@ var MindmapEditorProvider = class {
1639
1930
  revealTimer = setTimeout(() => post({ type: "reveal", line: e.selections[0].active.line }), REVEAL_DELAY);
1640
1931
  }),
1641
1932
  webview.onDidReceiveMessage(async (msg) => {
1642
- const accountAction = msg.type === "checkout" || msg.type === "orderPro" || msg.type === "openExternal" || msg.type === "signOut" || msg.type === "sendPhoneCode" || msg.type === "signInByPhone" || msg.type === "telemetry";
1933
+ if (msg.type === "mapMarkdownChange") return;
1934
+ const accountAction = msg.type === "checkout" || msg.type === "orderPro" || msg.type === "openExternal" || msg.type === "signOut" || msg.type === "sendPhoneCode" || msg.type === "signInByPhone" || msg.type === "openInBrowser" || msg.type === "telemetry";
1643
1935
  if (!accountAction && msg.type !== "ready" && msg.type !== "viewState" && msg.type !== "select" && !hasAccess(await this.license.state())) {
1644
1936
  if ("id" in msg) return post({ type: "error", id: msg.id, message: t("trialExpired") });
1645
1937
  return;
1646
1938
  }
1647
1939
  switch (msg.type) {
1648
1940
  case "ready": {
1941
+ this.readyPanels.add(panel);
1942
+ void this.context.globalState?.update("inkmap.hasOpenedMap", true);
1649
1943
  this.license.track?.("doc_open");
1650
- const [license, ads] = await Promise.all([this.license.state(), this.ads()]);
1651
- return post({ type: "doc", doc: state(), license, ads, chat: await chatAvailable() });
1944
+ const [license, chat] = await Promise.all([this.license.state(), chatAvailable()]);
1945
+ await post({ type: "doc", doc: state(), license, chat });
1946
+ const pending = this.pendingAccount;
1947
+ if (pending?.uri === document.uri.toString()) {
1948
+ this.pendingAccount = void 0;
1949
+ if (Date.now() < pending.until) await post({ type: "openAccount" });
1950
+ }
1951
+ return;
1652
1952
  }
1953
+ case "openInBrowser":
1954
+ return vscode4.commands.executeCommand("inkmap.openInBrowser", document.uri);
1653
1955
  case "telemetry": {
1654
1956
  this.license.track?.(msg.event);
1655
1957
  return;
@@ -1728,7 +2030,7 @@ var MindmapEditorProvider = class {
1728
2030
  case "sendPhoneCode":
1729
2031
  return post({ type: "phoneCodeSent", id: msg.id, result: await this.license.sendPhoneCode(msg.phone, msg.locale) });
1730
2032
  case "signInByPhone":
1731
- return post({ type: "phoneSignIn", id: msg.id, result: await this.license.signInByPhone(msg.phone, msg.code) });
2033
+ return post({ type: "phoneSignIn", id: msg.id, result: await this.license.signInByPhone(msg.phone, msg.code, msg.locale) });
1732
2034
  case "saveFile":
1733
2035
  return post({ type: "fileSaved", id: msg.id, saved: await saveDataUrl(msg.name, msg.dataUrl, assets) });
1734
2036
  }
@@ -1753,11 +2055,11 @@ async function saveDataUrl(name, dataUrl, dir) {
1753
2055
  });
1754
2056
  if (!target) return false;
1755
2057
  const body = match[2] ? Buffer.from(match[3], "base64") : Buffer.from(decodeURIComponent(match[3]), "utf8");
1756
- await (0, import_promises3.writeFile)(target.fsPath, body);
2058
+ await vscode4.workspace.fs.writeFile(target, body);
1757
2059
  return true;
1758
2060
  }
1759
2061
  async function editorHtml(webview, webRoot, assets) {
1760
- return webviewHtml(await (0, import_promises3.readFile)(vscode4.Uri.joinPath(webRoot, "index.html").fsPath, "utf8"), {
2062
+ return webviewHtml(await (0, import_promises4.readFile)(vscode4.Uri.joinPath(webRoot, "index.html").fsPath, "utf8"), {
1761
2063
  webBase: webview.asWebviewUri(webRoot).toString(),
1762
2064
  assetBase: assets ? webview.asWebviewUri(assets).toString() + "/" : "",
1763
2065
  cspSource: webview.cspSource,
@@ -1767,16 +2069,16 @@ async function editorHtml(webview, webRoot, assets) {
1767
2069
  }
1768
2070
 
1769
2071
  // packages/vscode/src/extension.ts
1770
- function insideOrEqual(root, target) {
2072
+ function insideOrEqual2(root, target) {
1771
2073
  if (root === target) return true;
1772
- const rel = (0, import_node_path3.relative)(root, target);
1773
- return Boolean(rel && !(0, import_node_path3.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(".." + import_node_path3.sep));
2074
+ const rel = (0, import_node_path4.relative)(root, target);
2075
+ return Boolean(rel && !(0, import_node_path4.isAbsolute)(rel) && rel !== ".." && !rel.startsWith(".." + import_node_path4.sep));
1774
2076
  }
1775
2077
  function resolveEditorUri(filePath) {
1776
2078
  for (const folder of vscode5.workspace.workspaceFolders ?? []) {
1777
2079
  const folderPath = folder.uri.fsPath || folder.uri.path;
1778
- if (folderPath && insideOrEqual(folderPath, filePath)) {
1779
- const rel = (0, import_node_path3.relative)(folderPath, filePath).split(import_node_path3.sep).join("/");
2080
+ if (folderPath && insideOrEqual2(folderPath, filePath)) {
2081
+ const rel = (0, import_node_path4.relative)(folderPath, filePath).split(import_node_path4.sep).join("/");
1780
2082
  return rel ? vscode5.Uri.joinPath(folder.uri, rel) : folder.uri;
1781
2083
  }
1782
2084
  }
@@ -1794,7 +2096,7 @@ function findColumnForFile(fileUri) {
1794
2096
  if (input?.uri && (input.uri.fsPath === targetFs || input.uri.path === targetFs)) {
1795
2097
  return group.viewColumn;
1796
2098
  }
1797
- if (tab.label && targetFs.endsWith(import_node_path3.sep + tab.label.replace(/^Preview\s+/i, ""))) {
2099
+ if (tab.label && targetFs.endsWith(import_node_path4.sep + tab.label.replace(/^Preview\s+/i, ""))) {
1798
2100
  return group.viewColumn;
1799
2101
  }
1800
2102
  }
@@ -1830,30 +2132,15 @@ async function openFileInEditorPane(filePath) {
1830
2132
  });
1831
2133
  }
1832
2134
  function startMcpTargetBridge() {
1833
- const inkmapDir = process.env.INKMAP_HOME || (0, import_node_path3.join)((0, import_node_os3.homedir)(), ".inkmap");
1834
- const targetPath = (0, import_node_path3.join)(inkmapDir, "antigravity-target.json");
1835
- const ackPath = (0, import_node_path3.join)(inkmapDir, "antigravity-target-ack.json");
1836
- const statusPath = (0, import_node_path3.join)(inkmapDir, "vscode-bridge-status.json");
2135
+ const inkmapDir = process.env.INKMAP_HOME || (0, import_node_path4.join)((0, import_node_os4.homedir)(), ".inkmap");
2136
+ const targetPath = (0, import_node_path4.join)(inkmapDir, "antigravity-target.json");
2137
+ const ackPath = (0, import_node_path4.join)(inkmapDir, "antigravity-target-ack.json");
1837
2138
  let lastSeq = Date.now() - 1e4;
1838
2139
  let debounceTimer;
1839
2140
  let disposed = false;
1840
- const writeBridgeStatus = async () => {
1841
- try {
1842
- if (!(0, import_node_fs2.existsSync)(inkmapDir)) (0, import_node_fs2.mkdirSync)(inkmapDir, { recursive: true, mode: 448 });
1843
- await (0, import_promises4.writeFile)(statusPath, JSON.stringify({
1844
- pid: process.pid,
1845
- activatedAt: Date.now(),
1846
- appName: vscode5.env.appName,
1847
- remoteName: vscode5.env.remoteName,
1848
- focused: vscode5.window.state.focused,
1849
- folders: (vscode5.workspace.workspaceFolders ?? []).map((f) => f.uri.toString())
1850
- }, null, 2), { mode: 384 });
1851
- } catch {
1852
- }
1853
- };
1854
2141
  const syncInitialSeq = async () => {
1855
2142
  try {
1856
- const raw = JSON.parse(await (0, import_promises4.readFile)(targetPath, "utf8"));
2143
+ const raw = JSON.parse(await (0, import_promises5.readFile)(targetPath, "utf8"));
1857
2144
  if (typeof raw?.seq === "number" && raw.seq < Date.now() - 8e3) {
1858
2145
  lastSeq = raw.seq;
1859
2146
  }
@@ -1861,34 +2148,55 @@ function startMcpTargetBridge() {
1861
2148
  }
1862
2149
  await checkTarget();
1863
2150
  };
2151
+ const alreadyAcked = async (seq) => {
2152
+ try {
2153
+ const ack = JSON.parse(await (0, import_promises5.readFile)(ackPath, "utf8"));
2154
+ return Boolean(ack && ack.ok === true && Number(ack.seq) >= seq);
2155
+ } catch {
2156
+ return false;
2157
+ }
2158
+ };
1864
2159
  const checkTarget = async () => {
1865
2160
  if (disposed) return;
2161
+ let claimedSeq = 0;
1866
2162
  try {
1867
- const raw = JSON.parse(await (0, import_promises4.readFile)(targetPath, "utf8"));
2163
+ const raw = JSON.parse(await (0, import_promises5.readFile)(targetPath, "utf8"));
1868
2164
  if (!raw || raw.openInEditorPane !== true) return;
1869
2165
  const seq = Number(raw.seq) || 0;
1870
- if (seq <= lastSeq || typeof raw.file !== "string") return;
1871
- const realTarget = await (0, import_promises4.realpath)(raw.file).catch(() => raw.file);
2166
+ if (seq <= lastSeq || typeof raw.file !== "string" || !/\.md$/i.test(raw.file)) return;
2167
+ if (await alreadyAcked(seq)) {
2168
+ lastSeq = seq;
2169
+ return;
2170
+ }
2171
+ const info = await (0, import_promises5.lstat)(raw.file).catch(() => null);
2172
+ if (!info || info.isSymbolicLink() || !info.isFile() || info.size > 5 * 1024 * 1024) return;
2173
+ const realTarget = await (0, import_promises5.realpath)(raw.file).catch(() => raw.file);
2174
+ if (!/\.md$/i.test(realTarget)) return;
1872
2175
  const folders = vscode5.workspace.workspaceFolders ?? [];
1873
- let matchesWindow = false;
2176
+ let matchesFolder = false;
1874
2177
  for (const folder of folders) {
1875
2178
  const folderPath = folder.uri.fsPath || folder.uri.path;
1876
2179
  if (!folderPath) continue;
1877
- const realFolder = await (0, import_promises4.realpath)(folderPath).catch(() => folderPath);
1878
- if (insideOrEqual(realFolder, realTarget)) {
1879
- matchesWindow = true;
2180
+ const realFolder = await (0, import_promises5.realpath)(folderPath).catch(() => folderPath);
2181
+ if (insideOrEqual2(realFolder, realTarget)) {
2182
+ matchesFolder = true;
1880
2183
  break;
1881
2184
  }
1882
2185
  }
1883
- if (!matchesWindow && vscode5.window.state.focused) {
1884
- matchesWindow = true;
2186
+ if (!matchesFolder) {
2187
+ if (!vscode5.window.state.focused) return;
2188
+ await new Promise((r) => setTimeout(r, 70));
2189
+ if (disposed || await alreadyAcked(seq)) {
2190
+ lastSeq = seq;
2191
+ return;
2192
+ }
1885
2193
  }
1886
- if (!matchesWindow) return;
1887
2194
  lastSeq = seq;
2195
+ claimedSeq = seq;
1888
2196
  const editorUrl = localEditorUrl(raw.editorUrl);
1889
2197
  if (editorUrl) await openUrlInEditorPane(editorUrl);
1890
2198
  else await openFileInEditorPane(realTarget);
1891
- await (0, import_promises4.writeFile)(ackPath, JSON.stringify({
2199
+ await (0, import_promises5.writeFile)(ackPath, JSON.stringify({
1892
2200
  seq,
1893
2201
  file: realTarget,
1894
2202
  ok: true,
@@ -1896,8 +2204,9 @@ function startMcpTargetBridge() {
1896
2204
  }, null, 2), { mode: 384 }).catch(() => {
1897
2205
  });
1898
2206
  } catch (err) {
1899
- await (0, import_promises4.writeFile)(ackPath, JSON.stringify({
1900
- seq: lastSeq,
2207
+ if (!claimedSeq) return;
2208
+ await (0, import_promises5.writeFile)(ackPath, JSON.stringify({
2209
+ seq: claimedSeq,
1901
2210
  ok: false,
1902
2211
  error: String(err instanceof Error ? err.message : err),
1903
2212
  handledAt: Date.now()
@@ -1905,7 +2214,6 @@ function startMcpTargetBridge() {
1905
2214
  });
1906
2215
  }
1907
2216
  };
1908
- void writeBridgeStatus();
1909
2217
  void syncInitialSeq();
1910
2218
  try {
1911
2219
  if (!(0, import_node_fs2.existsSync)(inkmapDir)) (0, import_node_fs2.mkdirSync)(inkmapDir, { recursive: true, mode: 448 });
@@ -1916,6 +2224,8 @@ function startMcpTargetBridge() {
1916
2224
  void checkTarget();
1917
2225
  }, 60);
1918
2226
  });
2227
+ watcher.on("error", () => {
2228
+ });
1919
2229
  const pollFallback = setInterval(() => {
1920
2230
  void checkTarget();
1921
2231
  }, 1200);
@@ -1933,56 +2243,115 @@ function startMcpTargetBridge() {
1933
2243
  } };
1934
2244
  }
1935
2245
  }
1936
- async function syncDeepSeekHarnessIfInstalled() {
2246
+ var HARNESS_INDEX_URL = "https://zhiyuanv.com/dsh-index.json";
2247
+ var HARNESS_MARKET_BUNDLE = "@deepseek-ai/dsh-experimental-plugin-market-bundle";
2248
+ var HARNESS_PROMPTED = "inkmap.deepseekHarnessPrompted";
2249
+ var harnessProfileDir = () => (0, import_node_path4.join)(process.env.DSH_HOME || (0, import_node_path4.join)((0, import_node_os4.homedir)(), ".dsh"), "profiles", "desktop");
2250
+ async function readHarnessProfile(dir) {
2251
+ const patchPath = (0, import_node_path4.join)(dir, "cordis.patch.yml");
2252
+ const patch = (0, import_node_fs2.existsSync)(patchPath) ? await (0, import_promises5.readFile)(patchPath, "utf8").catch(() => "") : "";
2253
+ let pkg;
1937
2254
  try {
1938
- const dshHome = process.env.DSH_HOME || (0, import_node_path3.join)((0, import_node_os3.homedir)(), ".dsh");
1939
- const profileDir = (0, import_node_path3.join)(dshHome, "profiles", "desktop");
1940
- if (!(0, import_node_fs2.existsSync)(profileDir)) return;
1941
- const indexUrl = "https://zhiyuanv.com/dsh-index.json";
1942
- const patchPath = (0, import_node_path3.join)(profileDir, "cordis.patch.yml");
1943
- const existingPatch = (0, import_node_fs2.existsSync)(patchPath) ? await (0, import_promises4.readFile)(patchPath, "utf8").catch(() => "") : "";
1944
- if (!existingPatch.includes(indexUrl)) {
1945
- const snippet = `
1946
- - id: plugin-market
2255
+ pkg = JSON.parse(await (0, import_promises5.readFile)((0, import_node_path4.join)(dir, "package.json"), "utf8"));
2256
+ } catch {
2257
+ }
2258
+ const bundles = pkg?.dsh?.profile?.bundles;
2259
+ return {
2260
+ dir,
2261
+ patch,
2262
+ pkg,
2263
+ needsIndex: !patch.includes(HARNESS_INDEX_URL) && !/^\s*-\s*id:\s*plugin-market\b/m.test(patch),
2264
+ needsBundle: Array.isArray(bundles) && !bundles.includes(HARNESS_MARKET_BUNDLE),
2265
+ needsPlugin: Boolean(pkg) && !pkg?.dependencies?.["dsh-inkmap"]
2266
+ };
2267
+ }
2268
+ var harnessSetUp = (profile) => !profile.needsIndex && !profile.needsBundle && !profile.needsPlugin;
2269
+ function harnessCli() {
2270
+ return [
2271
+ process.platform === "darwin" ? "/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh" : "",
2272
+ process.platform === "darwin" ? (0, import_node_path4.join)((0, import_node_os4.homedir)(), "Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh") : "",
2273
+ process.platform === "win32" ? (0, import_node_path4.join)(process.env.LOCALAPPDATA || (0, import_node_path4.join)((0, import_node_os4.homedir)(), "AppData", "Local"), "Programs", "DeepSeek Harness", "resources", "runtime", "cli", "bin", "dsh.cmd") : ""
2274
+ ].find((candidate) => candidate && (0, import_node_fs2.existsSync)(candidate));
2275
+ }
2276
+ function runHarnessCli(cli, args) {
2277
+ return new Promise((resolve3, reject) => {
2278
+ const q = (s) => `"${s.replace(/"/g, '""').replace(/%/g, '"^%"')}"`;
2279
+ const child = process.platform === "win32" && !cli.toLowerCase().endsWith(".exe") ? (0, import_node_child_process4.spawn)("cmd.exe", ["/d", "/s", "/c", `"${[cli, ...args].map(q).join(" ")}"`], {
2280
+ stdio: "ignore",
2281
+ windowsVerbatimArguments: true,
2282
+ windowsHide: true
2283
+ }) : (0, import_node_child_process4.spawn)(cli, args, { stdio: "ignore" });
2284
+ const timer = setTimeout(() => {
2285
+ child.kill();
2286
+ reject(new Error("dsh did not finish in time"));
2287
+ }, 18e4);
2288
+ child.on("error", (err) => {
2289
+ clearTimeout(timer);
2290
+ reject(err);
2291
+ });
2292
+ child.on("exit", (code) => {
2293
+ clearTimeout(timer);
2294
+ if (code === 0) resolve3();
2295
+ else reject(new Error(`dsh exited with code ${code}`));
2296
+ });
2297
+ });
2298
+ }
2299
+ async function installIntoHarness(profile) {
2300
+ if (profile.needsIndex) {
2301
+ const snippet = `- id: plugin-market
1947
2302
  name: "@deepseek-ai/dsh-plugin-market"
1948
2303
  config:
1949
2304
  indexes:
1950
- - ${indexUrl}
2305
+ - ${HARNESS_INDEX_URL}
1951
2306
  `;
1952
- await (0, import_promises4.writeFile)(patchPath, existingPatch.replace(/\n*$/, "") + snippet, "utf8").catch(() => {
1953
- });
1954
- }
1955
- const pkgPath = (0, import_node_path3.join)(profileDir, "package.json");
1956
- if (!(0, import_node_fs2.existsSync)(pkgPath)) return;
1957
- const pkg = JSON.parse(await (0, import_promises4.readFile)(pkgPath, "utf8"));
1958
- const bundles = pkg.dsh?.profile?.bundles;
1959
- if (Array.isArray(bundles) && !bundles.includes("@deepseek-ai/dsh-experimental-plugin-market-bundle")) {
1960
- bundles.push("@deepseek-ai/dsh-experimental-plugin-market-bundle");
1961
- await (0, import_promises4.writeFile)(pkgPath, JSON.stringify(pkg, null, 2) + "\n", "utf8").catch(() => {
1962
- });
1963
- }
1964
- if (pkg.dependencies?.["dsh-inkmap"]) return;
1965
- const stagedDsh = (0, import_node_path3.join)(process.env.INKMAP_HOME || (0, import_node_path3.join)((0, import_node_os3.homedir)(), ".inkmap"), "dsh-inkmap");
1966
- const spec = (0, import_node_fs2.existsSync)((0, import_node_path3.join)(stagedDsh, "package.json")) ? stagedDsh : "dsh-inkmap";
1967
- const candidates = [
1968
- process.platform === "darwin" ? "/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh" : "",
1969
- process.platform === "darwin" ? (0, import_node_path3.join)((0, import_node_os3.homedir)(), "Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh") : "",
1970
- process.platform === "win32" ? (0, import_node_path3.join)(process.env.LOCALAPPDATA || (0, import_node_path3.join)((0, import_node_os3.homedir)(), "AppData", "Local"), "Programs", "DeepSeek Harness", "resources", "runtime", "cli", "bin", "dsh.cmd") : ""
1971
- ].filter(Boolean);
1972
- const dshBin = candidates.find((c) => (0, import_node_fs2.existsSync)(c));
1973
- if (dshBin) {
1974
- const child = (0, import_node_child_process3.spawn)(dshBin, ["plugin", "--profile", "desktop", "add", spec], { stdio: "ignore", detached: true });
1975
- child.unref();
1976
- }
2307
+ const trimmed = profile.patch.trim();
2308
+ const next = !trimmed || trimmed === "[]" ? snippet : profile.patch.replace(/\n*$/, "\n\n") + snippet;
2309
+ await (0, import_promises5.writeFile)((0, import_node_path4.join)(profile.dir, "cordis.patch.yml"), next, "utf8");
2310
+ }
2311
+ if (profile.needsBundle && profile.pkg?.dsh?.profile?.bundles) {
2312
+ profile.pkg.dsh.profile.bundles.push(HARNESS_MARKET_BUNDLE);
2313
+ await (0, import_promises5.writeFile)((0, import_node_path4.join)(profile.dir, "package.json"), JSON.stringify(profile.pkg, null, 2) + "\n", "utf8");
2314
+ }
2315
+ if (!profile.needsPlugin) return "installed";
2316
+ const cli = harnessCli();
2317
+ if (!cli) return "configured";
2318
+ const staged = (0, import_node_path4.join)(process.env.INKMAP_HOME || (0, import_node_path4.join)((0, import_node_os4.homedir)(), ".inkmap"), "dsh-inkmap");
2319
+ await runHarnessCli(cli, ["plugin", "--profile", "desktop", "add", (0, import_node_fs2.existsSync)((0, import_node_path4.join)(staged, "package.json")) ? staged : "dsh-inkmap"]);
2320
+ return "installed";
2321
+ }
2322
+ async function installInDeepSeekHarness() {
2323
+ const dir = harnessProfileDir();
2324
+ if (!(0, import_node_fs2.existsSync)(dir)) return void vscode5.window.showWarningMessage(t("harnessNotFound"));
2325
+ try {
2326
+ const profile = await readHarnessProfile(dir);
2327
+ if (harnessSetUp(profile)) return void vscode5.window.showInformationMessage(t("harnessAlready"));
2328
+ const result = await vscode5.window.withProgress(
2329
+ { location: vscode5.ProgressLocation.Notification, title: t("harnessInstalling") },
2330
+ () => installIntoHarness(profile)
2331
+ );
2332
+ void vscode5.window.showInformationMessage(t(result === "installed" ? "harnessInstalled" : "harnessConfigured"));
2333
+ } catch (err) {
2334
+ void vscode5.window.showErrorMessage(t("harnessFailed", { error: err instanceof Error ? err.message : String(err) }));
2335
+ }
2336
+ }
2337
+ async function offerDeepSeekHarnessSetup(context) {
2338
+ try {
2339
+ if (context.globalState.get(HARNESS_PROMPTED)) return;
2340
+ const dir = harnessProfileDir();
2341
+ if (!(0, import_node_fs2.existsSync)(dir) || harnessSetUp(await readHarnessProfile(dir))) return;
2342
+ await context.globalState.update(HARNESS_PROMPTED, true);
2343
+ const install = t("harnessInstall");
2344
+ const pick = await vscode5.window.showInformationMessage(t("harnessOffer"), install, t("harnessNoThanks"));
2345
+ if (pick === install) await installInDeepSeekHarness();
1977
2346
  } catch {
1978
2347
  }
1979
2348
  }
1980
2349
  function activate(context) {
1981
- void syncDeepSeekHarnessIfInstalled();
2350
+ void offerDeepSeekHarnessSetup(context);
1982
2351
  const log = vscode5.window.createOutputChannel("Inkmap");
1983
2352
  const license = extensionLicense(context);
1984
- const ads = adFeed(PRODUCT.adFeedUrl);
1985
- const browsers = new BrowserServers(context, vscode5.Uri.joinPath(context.extensionUri, "dist", "web").fsPath, log, license, ads);
2353
+ license.track?.("plugin_activate");
2354
+ const browsers = new BrowserServers(context, vscode5.Uri.joinPath(context.extensionUri, "dist", "web").fsPath, log, license);
1986
2355
  const withUri = (run) => (arg) => {
1987
2356
  const uri = targetUri(arg);
1988
2357
  if (!uri) return vscode5.window.showWarningMessage(t("openMarkdownFirst"));
@@ -1994,18 +2363,36 @@ function activate(context) {
1994
2363
  preserveFocus: true
1995
2364
  })
1996
2365
  );
1997
- const editors = new MindmapEditorProvider(context, license, ads);
2366
+ const maybeOfferOnboarding = (editor) => {
2367
+ if (!editor || editor.document.languageId !== "markdown" || editor.document.uri.scheme !== "file") return;
2368
+ if (context.globalState.get("inkmap.hasOpenedMap") || context.globalState.get("inkmap.onboardingPrompted")) return;
2369
+ void context.globalState.update("inkmap.onboardingPrompted", true);
2370
+ license.track?.("onboarding_view");
2371
+ const docUri = editor.document.uri;
2372
+ void vscode5.window.showInformationMessage(t("onboardingTip"), t("onboardingAction")).then((pick) => {
2373
+ if (pick) {
2374
+ license.track?.("onboarding_open");
2375
+ void openToSide(docUri);
2376
+ }
2377
+ });
2378
+ };
2379
+ const editors = new MindmapEditorProvider(context, license);
1998
2380
  chatAvailable().then((available) => vscode5.commands.executeCommand("setContext", "inkmap.chatAvailable", available));
2381
+ maybeOfferOnboarding(vscode5.window.activeTextEditor);
1999
2382
  context.subscriptions.push(
2000
2383
  log,
2001
2384
  license,
2002
2385
  browsers,
2003
2386
  startMcpTargetBridge(),
2387
+ vscode5.window.onDidChangeActiveTextEditor(maybeOfferOnboarding),
2004
2388
  vscode5.window.registerUriHandler({
2005
- handleUri(uri) {
2389
+ async handleUri(uri) {
2006
2390
  if (uri.path === "/open") {
2007
- const target = new URLSearchParams(uri.query).get("path");
2008
- if (target) void openFileInEditorPane(target);
2391
+ const target = new URLSearchParams(uri.query).get("path")?.trim();
2392
+ if (!target || !(0, import_node_path4.isAbsolute)(target) || !/\.md$/i.test(target)) return;
2393
+ const info = await (0, import_promises5.lstat)(target).catch(() => null);
2394
+ if (!info || info.isSymbolicLink() || !info.isFile() || info.size > 5 * 1024 * 1024) return;
2395
+ void openFileInEditorPane(target);
2009
2396
  }
2010
2397
  }
2011
2398
  }),
@@ -2024,7 +2411,7 @@ function activate(context) {
2024
2411
  withUri(async (uri) => {
2025
2412
  if (!hasAccess(await license.state())) {
2026
2413
  await openToSide(uri);
2027
- setTimeout(() => editors.openAccount(), 250);
2414
+ editors.openAccount(uri);
2028
2415
  return;
2029
2416
  }
2030
2417
  try {
@@ -2037,12 +2424,13 @@ function activate(context) {
2037
2424
  }
2038
2425
  })
2039
2426
  ),
2427
+ vscode5.commands.registerCommand("inkmap.installDeepSeekHarness", installInDeepSeekHarness),
2040
2428
  vscode5.commands.registerCommand("inkmap.upgrade", async (arg) => {
2041
2429
  if (editors.openAccount()) return;
2042
2430
  const uri = targetUri(arg);
2043
2431
  if (!uri) return vscode5.window.showWarningMessage(t("openMarkdownFirst"));
2044
2432
  await openToSide(uri);
2045
- setTimeout(() => editors.openAccount(), 280);
2433
+ editors.openAccount(uri);
2046
2434
  })
2047
2435
  );
2048
2436
  }