inkmap-mcp 0.3.10 → 0.3.13

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.
@@ -1,15 +1,13 @@
1
1
  // packages/harness/src/host.mjs
2
2
  import { randomUUID as randomUUID2 } from "node:crypto";
3
- import { lstat as lstat2, realpath as realpath2 } from "node:fs/promises";
4
- import { isAbsolute as isAbsolute2, relative as relative2, sep as sep2 } from "node:path";
3
+ import { lstat as lstat3, realpath as realpath3 } from "node:fs/promises";
4
+ import { isAbsolute as isAbsolute2, relative as relative3, sep as sep4 } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
 
7
7
  // packages/core/dist/product.js
8
8
  var PRODUCT = {
9
9
  id: "inkmap-pro",
10
- entitlement: "inkmap.pro",
11
- /** JSON list of sponsor ads shown in the free edition; empty means house ads only. */
12
- adFeedUrl: ""
10
+ entitlement: "inkmap.pro"
13
11
  };
14
12
  var YUNFAN_BILLING_ORIGIN = "https://zhiyuanv.com";
15
13
  function billingFlowUrl(raw, origin, mode, legacy = false) {
@@ -57,56 +55,83 @@ function sanitizeViewState(raw) {
57
55
  import { execFileSync } from "node:child_process";
58
56
  import { link, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
59
57
  import { randomUUID } from "node:crypto";
60
- import { homedir } from "node:os";
61
- import { dirname, join } from "node:path";
58
+ import { homedir, tmpdir } from "node:os";
59
+ import { dirname, join, sep } from "node:path";
60
+
61
+ // packages/cli/dist/version.js
62
+ var INKMAP_VERSION = "0.3.13";
63
+
64
+ // packages/cli/dist/license.js
65
+ var ZH_LOCALE_RE = /^zh(?:[-_.]|$)/i;
66
+ var EN_LOCALE_RE = /^en(?:[-_.]|$)/i;
62
67
  var cachedOsLocale;
63
- function detectOsLocale() {
64
- const explicit = (process.env.INKMAP_LOCALE || "").trim();
65
- if (/^zh\b/i.test(explicit))
68
+ var WAIT_FAST_MS = 2500;
69
+ var WAIT_SLOW_MS = 3e4;
70
+ var WAIT_FAST_FOR_MS = 30 * 6e4;
71
+ var WAIT_MAX_MS = 3 * 24 * 60 * 6e4;
72
+ var MAX_WAITING = 5;
73
+ function isWaitingToken(value) {
74
+ const w = value;
75
+ 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";
76
+ }
77
+ var DOMESTIC_TIME_ZONE = /^(Asia\/(Shanghai|Chongqing|Chungking|Harbin|Urumqi|Beijing)|PRC)$/i;
78
+ function parseAppleLanguages(output) {
79
+ const match = /^\(\s*(?:"([^"]+)"|([^\s,)]+))/m.exec(output);
80
+ return match?.[1] ?? match?.[2] ?? "";
81
+ }
82
+ var posixLocale = (env) => (env.LC_ALL || env.LC_MESSAGES || env.LANG || "").trim();
83
+ function resolveOsLocale(probe) {
84
+ const explicit = (probe.env.INKMAP_LOCALE || "").trim();
85
+ if (ZH_LOCALE_RE.test(explicit))
66
86
  return "zh";
67
- if (/^en\b/i.test(explicit))
87
+ if (EN_LOCALE_RE.test(explicit))
68
88
  return "en";
69
- if (cachedOsLocale)
70
- return cachedOsLocale;
71
- let domestic = false;
72
- try {
73
- const tz = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
74
- if (/^(Asia\/(Shanghai|Chongqing|Chungking|Harbin|Urumqi|Beijing)|PRC)$/i.test(tz)) {
75
- domestic = true;
89
+ if (DOMESTIC_TIME_ZONE.test(probe.timeZone))
90
+ return "zh";
91
+ let language = "";
92
+ if (probe.platform === "darwin") {
93
+ try {
94
+ language = parseAppleLanguages(probe.run("defaults", ["read", "-g", "AppleLanguages"]));
95
+ } catch {
96
+ language = posixLocale(probe.env);
76
97
  }
77
- } catch {
78
- }
79
- if (!domestic) {
80
- if (process.platform === "darwin") {
81
- try {
82
- const out = execFileSync("defaults", ["read", "-g", "AppleLanguages"], {
83
- encoding: "utf8",
84
- timeout: 800,
85
- stdio: ["ignore", "pipe", "ignore"]
86
- });
87
- const firstLang = /"([^"]+)"/.exec(out)?.[1] ?? "";
88
- if (/^zh\b/i.test(firstLang))
89
- domestic = true;
90
- } catch {
91
- const raw = (process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || "").trim();
92
- if (/^zh\b/i.test(raw))
93
- domestic = true;
94
- }
95
- } else if (process.platform === "win32") {
96
- try {
97
- const loc = Intl.DateTimeFormat().resolvedOptions().locale || "";
98
- if (/^zh\b/i.test(loc))
99
- domestic = true;
100
- } catch {
101
- }
102
- } else {
103
- const raw = (process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || "").trim();
104
- if (/^zh\b/i.test(raw))
105
- domestic = true;
98
+ } else if (probe.platform === "win32") {
99
+ try {
100
+ const output = probe.run("reg", ["query", "HKCU\\Control Panel\\International", "/v", "LocaleName"]);
101
+ language = /LocaleName\s+REG_\w+\s+(\S+)/i.exec(output)?.[1] ?? "";
102
+ } catch {
106
103
  }
104
+ if (!language)
105
+ language = probe.intlLocale;
106
+ } else {
107
+ language = posixLocale(probe.env);
108
+ }
109
+ return ZH_LOCALE_RE.test(language) ? "zh" : "en";
110
+ }
111
+ function systemLocaleProbe() {
112
+ let timeZone = "";
113
+ let intlLocale = "";
114
+ try {
115
+ const options = Intl.DateTimeFormat().resolvedOptions();
116
+ timeZone = options.timeZone || "";
117
+ intlLocale = options.locale || "";
118
+ } catch {
107
119
  }
108
- cachedOsLocale = domestic ? "zh" : "en";
109
- return cachedOsLocale;
120
+ return {
121
+ platform: process.platform,
122
+ env: process.env,
123
+ timeZone,
124
+ intlLocale,
125
+ run: (command, args) => execFileSync(command, args, { encoding: "utf8", timeout: 800, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] })
126
+ };
127
+ }
128
+ function detectOsLocale() {
129
+ const explicit = (process.env.INKMAP_LOCALE || "").trim();
130
+ if (ZH_LOCALE_RE.test(explicit))
131
+ return "zh";
132
+ if (EN_LOCALE_RE.test(explicit))
133
+ return "en";
134
+ return cachedOsLocale ??= resolveOsLocale(systemLocaleProbe());
110
135
  }
111
136
  function billingOrigin(raw) {
112
137
  if (!raw)
@@ -117,7 +142,7 @@ function billingOrigin(raw) {
117
142
  }
118
143
  return url.origin;
119
144
  }
120
- function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHost = "" } = {}) {
145
+ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHost = "", waitPollMs = WAIT_FAST_MS } = {}) {
121
146
  const listeners = /* @__PURE__ */ new Set();
122
147
  let current = { pro: false };
123
148
  let trial;
@@ -129,6 +154,9 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
129
154
  let detectedHost = defaultHost;
130
155
  const pendingEvents = /* @__PURE__ */ new Map();
131
156
  let lastCheck = 0;
157
+ let fastPollUntil = 0;
158
+ const expectPurchase = () => void (fastPollUntil = Date.now() + 15 * 6e4);
159
+ let flowCreation;
132
160
  let disposed = false;
133
161
  let generation = 0;
134
162
  let connection;
@@ -136,12 +164,33 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
136
164
  let pendingWrite = Promise.resolve();
137
165
  let pendingCheckout;
138
166
  let cachedOrder;
139
- let magicPollTimer;
140
- let magicSession = 0;
141
- function stopMagicPoll() {
142
- ++magicSession;
143
- clearTimeout(magicPollTimer);
144
- magicPollTimer = void 0;
167
+ let waiting = [];
168
+ let waitTimer;
169
+ let waitRound = 0;
170
+ let lastSignIn;
171
+ const sessionRecord = (fields) => JSON.stringify({ ...fields, ...lastSignIn && { lastSignIn } });
172
+ const signedOutRecord = () => lastSignIn || waiting.length ? JSON.stringify({ ...lastSignIn && { lastSignIn }, ...waiting.length && { waiting } }) : void 0;
173
+ async function rememberSignIn(id) {
174
+ const clean = id.trim().slice(0, 254);
175
+ if (!clean || clean === lastSignIn)
176
+ return;
177
+ lastSignIn = clean;
178
+ current = { ...current, lastSignIn };
179
+ await writeSession(async () => {
180
+ let record = {};
181
+ try {
182
+ record = JSON.parse(await storage.read() || "{}");
183
+ } catch {
184
+ }
185
+ await storage.write(JSON.stringify({ ...record, lastSignIn }));
186
+ }).catch(() => {
187
+ });
188
+ }
189
+ function clearWaiting() {
190
+ waiting = [];
191
+ ++waitRound;
192
+ clearTimeout(waitTimer);
193
+ waitTimer = void 0;
145
194
  }
146
195
  function mergeCookies(existing, response) {
147
196
  const map = /* @__PURE__ */ new Map();
@@ -172,12 +221,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
172
221
  }
173
222
  return /^1\d{10}$/.test(clean) ? `${clean.slice(0, 3)}****${clean.slice(7)}` : clean.slice(0, 32);
174
223
  }
175
- function clientLocale(hint) {
176
- const h = (hint || "").trim();
177
- if (/^zh\b/i.test(h))
178
- return "zh";
179
- if (/^en\b/i.test(h))
180
- return "en";
224
+ function clientLocale(_uiLocaleHint) {
181
225
  return detectOsLocale();
182
226
  }
183
227
  function writeSession(operation) {
@@ -209,7 +253,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
209
253
  if (typeof data.token !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(data.token)) {
210
254
  throw new Error("Invalid Inkmap checkout response.");
211
255
  }
212
- return { origin, url, token: data.token, ...cookie && { cookie } };
256
+ return { origin, url, token: data.token, locale: loc, ...cookie && { cookie } };
213
257
  }
214
258
  function checkoutPost(checkoutUrl, action, origin, body, token, cookie, localeHint) {
215
259
  const loc = clientLocale(localeHint);
@@ -271,12 +315,26 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
271
315
  pro,
272
316
  ...current.trialUntil !== void 0 && { trialUntil: current.trialUntil },
273
317
  ...connected && { connected: true },
274
- ...cleanAccount && { account: cleanAccount }
318
+ ...cleanAccount && { account: cleanAccount },
319
+ ...lastSignIn && { lastSignIn }
275
320
  };
276
321
  for (const listener of listeners)
277
322
  listener(current);
278
323
  }
279
324
  async function startTrial() {
325
+ try {
326
+ const record = JSON.parse(await storage.read() || "{}");
327
+ const remembered = record.lastSignIn;
328
+ if (typeof remembered === "string" && remembered.trim() && !lastSignIn) {
329
+ lastSignIn = remembered.trim().slice(0, 254);
330
+ current = { ...current, lastSignIn };
331
+ }
332
+ if (typeof record.token !== "string" && Array.isArray(record.waiting) && !waiting.length) {
333
+ waiting = record.waiting.filter(isWaitingToken).slice(-MAX_WAITING);
334
+ scheduleWait(waitPollMs);
335
+ }
336
+ } catch {
337
+ }
280
338
  const trialUntil = await localTrialDeadline().catch(() => void 0);
281
339
  if (disposed || trialUntil === void 0)
282
340
  return;
@@ -328,7 +386,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
328
386
  return await writeSession(async () => {
329
387
  if (version !== generation || disposed)
330
388
  return;
331
- await storage.write(void 0).catch(() => {
389
+ await storage.write(signedOutRecord()).catch(() => {
332
390
  });
333
391
  update(false);
334
392
  });
@@ -352,48 +410,134 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
352
410
  });
353
411
  return connection;
354
412
  }
355
- function startMagicPoll(origin, pendingToken) {
356
- stopMagicPoll();
357
- const id = magicSession;
358
- const deadline = Date.now() + 10 * 6e4;
359
- const poll = () => {
360
- if (disposed || id !== magicSession || Date.now() >= deadline)
413
+ async function mustPayFirst() {
414
+ if (!loginOnly)
415
+ return false;
416
+ await (trial ??= startTrial());
417
+ return current.trialUntil !== void 0 && current.trialUntil <= Date.now();
418
+ }
419
+ async function waitFor(origin, token, email) {
420
+ const now = Date.now();
421
+ const same = (other) => !other || !email || other.toLowerCase() === email.toLowerCase();
422
+ waiting = waiting.filter((w) => w.token !== token && same(w.email)).map((w) => ({ ...w, fastUntil: now + WAIT_FAST_FOR_MS }));
423
+ waiting.push({ origin, token, email, since: now, fastUntil: now + WAIT_FAST_FOR_MS });
424
+ waiting = waiting.slice(-MAX_WAITING);
425
+ scheduleWait(waitPollMs);
426
+ await writeSession(async () => {
427
+ let record = {};
428
+ try {
429
+ record = JSON.parse(await storage.read() || "{}");
430
+ } catch {
431
+ }
432
+ if (typeof record.token !== "string")
433
+ await storage.write(signedOutRecord());
434
+ }).catch(() => {
435
+ });
436
+ }
437
+ function scheduleWait(delay) {
438
+ clearTimeout(waitTimer);
439
+ if (disposed || !waiting.length)
440
+ return;
441
+ waitTimer = setTimeout(() => void checkWaiting(), delay);
442
+ waitTimer.unref();
443
+ }
444
+ async function checkWaiting() {
445
+ const round = ++waitRound;
446
+ const now = Date.now();
447
+ const before = waiting.length;
448
+ let origin;
449
+ try {
450
+ origin = billingOrigin(getOrigin());
451
+ } catch {
452
+ return scheduleWait(WAIT_SLOW_MS);
453
+ }
454
+ waiting = waiting.filter((w) => w.origin === origin && now - w.since < WAIT_MAX_MS);
455
+ for (const w of [...waiting]) {
456
+ let response;
457
+ try {
458
+ response = await entitlement(w.origin, w.token);
459
+ } catch {
460
+ continue;
461
+ }
462
+ if (disposed || round !== waitRound)
463
+ return;
464
+ if (response.status === 401) {
465
+ waiting = waiting.filter((other) => other !== w);
466
+ continue;
467
+ }
468
+ if (!response.ok)
469
+ continue;
470
+ const body = await response.json().catch(() => null);
471
+ if (disposed || round !== waitRound)
361
472
  return;
362
- magicPollTimer = setTimeout(async () => {
363
- if (disposed || id !== magicSession)
473
+ if (body?.connected !== true || body.entitlement !== PRODUCT.entitlement)
474
+ continue;
475
+ if (body.active !== true && await mustPayFirst())
476
+ continue;
477
+ if (disposed || round !== waitRound)
478
+ return;
479
+ await writeSession(async () => {
480
+ if (disposed || round !== waitRound || w.origin !== billingOrigin(getOrigin()))
364
481
  return;
482
+ clearWaiting();
483
+ await storage.write(sessionRecord({ origin: w.origin, token: w.token }));
484
+ ++generation;
485
+ activeOrigin = w.origin;
486
+ applyEntitlement(body);
487
+ schedule(body.active === true ? 6e4 : 2500);
488
+ });
489
+ return;
490
+ }
491
+ if (disposed || round !== waitRound)
492
+ return;
493
+ if (waiting.length !== before) {
494
+ await writeSession(async () => {
495
+ let record = {};
365
496
  try {
366
- const res = await entitlement(origin, pendingToken);
367
- if (disposed || id !== magicSession)
368
- return;
369
- if (res.status === 401) {
370
- stopMagicPoll();
371
- return;
372
- }
373
- if (res.ok) {
374
- const body = await res.json();
375
- if (body?.connected === true && body.entitlement === PRODUCT.entitlement) {
376
- stopMagicPoll();
377
- await writeSession(async () => {
378
- if (disposed || origin !== billingOrigin(getOrigin()))
379
- return;
380
- await storage.write(JSON.stringify({ origin, token: pendingToken }));
381
- ++generation;
382
- activeOrigin = origin;
383
- applyEntitlement(body);
384
- schedule(body.active === true ? 6e4 : 2500);
385
- });
386
- return;
387
- }
388
- }
497
+ record = JSON.parse(await storage.read() || "{}");
389
498
  } catch {
390
499
  }
391
- if (!disposed && id === magicSession && Date.now() < deadline)
392
- poll();
393
- }, 2e3);
394
- magicPollTimer.unref();
395
- };
396
- poll();
500
+ if (typeof record.token !== "string")
501
+ await storage.write(signedOutRecord());
502
+ }).catch(() => {
503
+ });
504
+ }
505
+ scheduleWait(waiting.some((w) => Date.now() < w.fastUntil) ? waitPollMs : WAIT_SLOW_MS);
506
+ }
507
+ async function parkUnpaidSession() {
508
+ if (current.pro || !current.connected || !await mustPayFirst())
509
+ return;
510
+ await writeSession(async () => {
511
+ if (current.pro || !current.connected)
512
+ return;
513
+ let record = {};
514
+ try {
515
+ record = JSON.parse(await storage.read() || "{}");
516
+ } catch {
517
+ }
518
+ if (typeof record.token !== "string" || typeof record.origin !== "string")
519
+ return;
520
+ const response = await entitlement(record.origin, record.token).catch(() => null);
521
+ if (!response?.ok)
522
+ return;
523
+ const latest = await response.json().catch(() => null);
524
+ if (!latest || latest.active === true || latest.connected !== true) {
525
+ if (latest)
526
+ applyEntitlement(latest);
527
+ return;
528
+ }
529
+ ++generation;
530
+ clearTimeout(timer);
531
+ lastCheck = 0;
532
+ const now = Date.now();
533
+ waiting = [
534
+ ...waiting.filter((w) => w.token !== record.token),
535
+ { origin: record.origin, token: record.token, email: lastSignIn ?? "", since: now, fastUntil: now + WAIT_FAST_FOR_MS }
536
+ ].slice(-MAX_WAITING);
537
+ await storage.write(signedOutRecord());
538
+ update(false);
539
+ });
540
+ scheduleWait(waitPollMs);
397
541
  }
398
542
  async function sendPendingTelemetry() {
399
543
  if (disposed || !pendingEvents.size)
@@ -408,7 +552,8 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
408
552
  if (origin === "https://billing.example.com" || process.env.INKMAP_DISABLE_TELEMETRY === "1" || process.env.NODE_TEST_CONTEXT)
409
553
  return;
410
554
  const customHome = process.env.INKMAP_HOME || "";
411
- 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-"))) {
555
+ const sysTmp = tmpdir();
556
+ if (customHome && (customHome === sysTmp || customHome.startsWith(sysTmp + 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-"))) {
412
557
  return;
413
558
  }
414
559
  }
@@ -432,7 +577,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
432
577
  installId: id,
433
578
  host: hostName,
434
579
  os,
435
- version: "0.3.10",
580
+ version: INKMAP_VERSION,
436
581
  locale: clientLocale(),
437
582
  tier,
438
583
  events
@@ -444,13 +589,16 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
444
589
  return {
445
590
  async state() {
446
591
  await (trial ??= startTrial());
447
- if (Date.now() - lastCheck >= 4e3)
592
+ const interval = !current.pro && Date.now() < fastPollUntil ? 4e3 : 6e4;
593
+ if (Date.now() - lastCheck >= interval)
448
594
  await refresh();
595
+ await parkUnpaidSession();
449
596
  return current;
450
597
  },
451
598
  async connect(mode, localeHint) {
452
599
  if (loginOnly && mode !== "restore")
453
600
  throw new Error("Only Yunfan account sign-in is available.");
601
+ expectPurchase();
454
602
  const origin = billingOrigin(getOrigin());
455
603
  const loc = clientLocale(localeHint);
456
604
  const version = generation;
@@ -492,7 +640,8 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
492
640
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin())) {
493
641
  throw new Error("The Yunfan account session changed. Please try again.");
494
642
  }
495
- await storage.write(JSON.stringify({ origin, token: data.token, ...mode === "buy" && { checkoutUrl: url } }));
643
+ clearWaiting();
644
+ await storage.write(sessionRecord({ origin, token: data.token, ...mode === "buy" && { checkoutUrl: url } }));
496
645
  ++generation;
497
646
  lastCheck = 0;
498
647
  if (mode !== "buy" || !current.connected)
@@ -504,8 +653,10 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
504
653
  async orderPro(localeHint) {
505
654
  if (loginOnly)
506
655
  throw new Error("Only Yunfan account sign-in is available.");
656
+ expectPurchase();
507
657
  const origin = billingOrigin(getOrigin());
508
- if (cachedOrder && cachedOrder.origin === origin && Date.now() - cachedOrder.at < 8e3) {
658
+ const loc = clientLocale(localeHint);
659
+ if (cachedOrder && cachedOrder.origin === origin && cachedOrder.locale === loc && Date.now() - cachedOrder.at < 8e3) {
509
660
  const hit = cachedOrder.result;
510
661
  cachedOrder = void 0;
511
662
  schedule(hit.status === "qr" || hit.status === "redirect" ? 4e3 : 6e4);
@@ -531,7 +682,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
531
682
  await writeSession(async () => {
532
683
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin()))
533
684
  return;
534
- await storage.write(JSON.stringify({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
685
+ await storage.write(sessionRecord({ origin, token, checkoutUrl, ...nextCookie && { cookie: nextCookie } }));
535
686
  if (persist) {
536
687
  ++generation;
537
688
  lastCheck = 0;
@@ -580,34 +731,44 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
580
731
  async sendPhoneCode(phone, localeHint) {
581
732
  if (typeof phone !== "string" || !phone.trim() || phone.length > 254)
582
733
  return phoneFailure(400);
734
+ expectPurchase();
583
735
  const isEmail = phone.includes("@");
584
736
  const locale = clientLocale(localeHint);
585
737
  try {
586
738
  const origin = billingOrigin(getOrigin());
587
739
  if (!loginOnly) {
588
740
  try {
589
- if (!pendingCheckout || pendingCheckout.origin !== origin) {
590
- pendingCheckout = await createCheckoutFlow(origin, void 0, void 0, locale);
741
+ const newFlow = () => flowCreation ??= createCheckoutFlow(origin, void 0, void 0, locale).finally(() => {
742
+ flowCreation = void 0;
743
+ });
744
+ let flow = pendingCheckout;
745
+ if (!flow || flow.origin !== origin || flow.locale !== locale) {
746
+ flow = await newFlow();
747
+ pendingCheckout = flow;
591
748
  }
592
749
  const sendAction = isEmail ? "email/send" : "sms";
593
750
  const sendBody = isEmail ? { email: phone, locale } : { phone };
594
- let smsRes = await checkoutPost(pendingCheckout.url, sendAction, origin, sendBody, pendingCheckout.token, pendingCheckout.cookie, locale);
595
- if (smsRes.status === 410 || smsRes.status === 404) {
596
- pendingCheckout = await createCheckoutFlow(origin, void 0, void 0, locale);
597
- smsRes = await checkoutPost(pendingCheckout.url, sendAction, origin, sendBody, pendingCheckout.token, pendingCheckout.cookie, locale);
751
+ let smsRes = await checkoutPost(flow.url, sendAction, origin, sendBody, flow.token, flow.cookie, locale);
752
+ if (smsRes.status === 401 || smsRes.status === 403 || smsRes.status === 404 || smsRes.status === 410) {
753
+ flow = await newFlow();
754
+ pendingCheckout = flow;
755
+ smsRes = await checkoutPost(flow.url, sendAction, origin, sendBody, flow.token, flow.cookie, locale);
598
756
  }
599
- pendingCheckout.cookie = mergeCookies(pendingCheckout.cookie, smsRes);
600
- return smsRes.status === 204 ? { ok: true, value: void 0 } : phoneFailure(smsRes.status);
757
+ flow.cookie = mergeCookies(flow.cookie, smsRes);
758
+ if (smsRes.status !== 204)
759
+ return phoneFailure(smsRes.status);
760
+ await rememberSignIn(phone);
761
+ return { ok: true, value: void 0 };
601
762
  } catch {
602
763
  pendingCheckout = void 0;
603
764
  }
604
765
  }
605
766
  const response = await phoneRequest(origin, "send", phone, void 0, locale);
606
767
  if (response.status === 204) {
768
+ await rememberSignIn(phone);
607
769
  const pendingToken = response.headers.get("x-inkmap-pending-token")?.trim();
608
- if (pendingToken && /^[A-Za-z0-9_-]{43}$/.test(pendingToken)) {
609
- startMagicPoll(origin, pendingToken);
610
- }
770
+ if (pendingToken && /^[A-Za-z0-9_-]{43}$/.test(pendingToken))
771
+ await waitFor(origin, pendingToken, phone);
611
772
  return { ok: true, value: void 0 };
612
773
  }
613
774
  return phoneFailure(response.status);
@@ -615,41 +776,47 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
615
776
  return phoneFailure();
616
777
  }
617
778
  },
618
- async signInByPhone(phone, code) {
779
+ async signInByPhone(phone, code, localeHint) {
619
780
  if (typeof phone !== "string" || !phone.trim() || phone.length > 254 || typeof code !== "string" || !/^\d{6}$/.test(code))
620
781
  return phoneFailure(400);
621
782
  const isEmail = phone.includes("@");
783
+ const locale = clientLocale(localeHint);
622
784
  const version = generation;
623
785
  try {
624
786
  const origin = billingOrigin(getOrigin());
625
787
  let token;
626
788
  let checkoutUrl;
627
789
  let cookie;
628
- if (pendingCheckout && pendingCheckout.origin === origin && !loginOnly) {
790
+ const flow = pendingCheckout;
791
+ if (!loginOnly && flow && flow.origin === origin) {
629
792
  const verifyAction = isEmail ? "email/verify" : "login";
630
793
  const verifyBody = isEmail ? { email: phone, code } : { phone, code };
631
- const loginRes = await checkoutPost(pendingCheckout.url, verifyAction, origin, verifyBody, pendingCheckout.token, pendingCheckout.cookie);
794
+ const loginRes = await checkoutPost(flow.url, verifyAction, origin, verifyBody, flow.token, flow.cookie, locale);
632
795
  if (!loginRes.ok) {
633
- if (loginRes.status === 410 || loginRes.status === 404)
634
- pendingCheckout = void 0;
796
+ if (loginRes.status === 401 || loginRes.status === 403 || loginRes.status === 404 || loginRes.status === 410) {
797
+ if (pendingCheckout === flow)
798
+ pendingCheckout = void 0;
799
+ }
635
800
  return phoneFailure(loginRes.status);
636
801
  }
637
- cookie = mergeCookies(pendingCheckout.cookie, loginRes);
638
- token = pendingCheckout.token;
639
- checkoutUrl = pendingCheckout.url;
640
- pendingCheckout = void 0;
641
- const orderRes = await checkoutPost(checkoutUrl, "order", origin, {}, token, cookie).catch(() => null);
802
+ cookie = mergeCookies(flow.cookie, loginRes);
803
+ token = flow.token;
804
+ checkoutUrl = flow.url;
805
+ if (pendingCheckout === flow)
806
+ pendingCheckout = void 0;
807
+ const orderRes = await checkoutPost(checkoutUrl, "order", origin, {}, token, cookie, locale).catch(() => null);
642
808
  if (orderRes?.ok) {
643
809
  cookie = mergeCookies(cookie, orderRes);
644
810
  const orderData = await orderRes.json().catch(() => null);
645
811
  if (orderData && typeof orderData === "object") {
646
812
  if (orderData.active === true) {
647
- cachedOrder = { at: Date.now(), origin, result: { status: "active", state: current } };
813
+ cachedOrder = { at: Date.now(), origin, locale, result: { status: "active", state: current } };
648
814
  } else if (typeof orderData.qr === "string" && orderData.qr) {
649
815
  const qr = orderData.qr.startsWith("data:image/") ? orderData.qr : "data:image/png;base64," + orderData.qr;
650
816
  cachedOrder = {
651
817
  at: Date.now(),
652
818
  origin,
819
+ locale,
653
820
  result: {
654
821
  status: "qr",
655
822
  qr,
@@ -658,12 +825,12 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
658
825
  }
659
826
  };
660
827
  } else if (typeof orderData.checkoutUrl === "string" && /^https:\/\//.test(orderData.checkoutUrl)) {
661
- cachedOrder = { at: Date.now(), origin, result: { status: "redirect", url: orderData.checkoutUrl } };
828
+ cachedOrder = { at: Date.now(), origin, locale, result: { status: "redirect", url: orderData.checkoutUrl } };
662
829
  }
663
830
  }
664
831
  }
665
832
  } else {
666
- const response = await phoneRequest(origin, "verify", phone, code);
833
+ const response = await phoneRequest(origin, "verify", phone, code, locale);
667
834
  if (response.status !== 201)
668
835
  return phoneFailure(response.status);
669
836
  cookie = mergeCookies(void 0, response);
@@ -691,11 +858,16 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
691
858
  }
692
859
  if (cachedOrder?.result.status === "active")
693
860
  state.active = true;
861
+ if (!checkoutUrl && state.active !== true && await mustPayFirst()) {
862
+ await rememberSignIn(phone);
863
+ await waitFor(origin, token, phone);
864
+ return { ok: false, reason: "notPro" };
865
+ }
694
866
  return await writeSession(async () => {
695
867
  if (version !== generation || disposed || origin !== billingOrigin(getOrigin()))
696
868
  return phoneFailure();
697
- stopMagicPoll();
698
- await storage.write(JSON.stringify({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
869
+ clearWaiting();
870
+ await storage.write(sessionRecord({ origin, token, ...checkoutUrl && { checkoutUrl }, ...cookie && { cookie } }));
699
871
  ++generation;
700
872
  activeOrigin = origin;
701
873
  applyEntitlement(state);
@@ -709,12 +881,12 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
709
881
  }
710
882
  },
711
883
  async deactivate() {
712
- stopMagicPoll();
884
+ clearWaiting();
713
885
  pendingCheckout = void 0;
714
886
  cachedOrder = void 0;
715
887
  const saved = await writeSession(async () => {
716
888
  const previous = await storage.read();
717
- await storage.write(void 0);
889
+ await storage.write(signedOutRecord());
718
890
  ++generation;
719
891
  clearTimeout(timer);
720
892
  lastCheck = 0;
@@ -725,7 +897,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
725
897
  return;
726
898
  try {
727
899
  const { origin, token } = JSON.parse(saved);
728
- if (origin !== billingOrigin(getOrigin()))
900
+ if (origin !== billingOrigin(getOrigin()) || typeof token !== "string")
729
901
  return;
730
902
  await fetch(origin + "/billing/v1/entitlement", {
731
903
  method: "DELETE",
@@ -745,7 +917,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
745
917
  return;
746
918
  if (hostHint)
747
919
  detectedHost = hostHint;
748
- if (!sentAppOpen) {
920
+ if (!sentAppOpen && !PASSIVE_TELEMETRY_EVENTS.has(event)) {
749
921
  sentAppOpen = true;
750
922
  pendingEvents.set("app_open", (pendingEvents.get("app_open") ?? 0) + 1);
751
923
  }
@@ -769,7 +941,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
769
941
  },
770
942
  dispose() {
771
943
  disposed = true;
772
- stopMagicPoll();
944
+ clearWaiting();
773
945
  clearTimeout(trialTimer);
774
946
  clearTimeout(timer);
775
947
  clearTimeout(telemetryTimer);
@@ -778,6 +950,7 @@ function licenseService(storage, getOrigin, { loginOnly = false, host: defaultHo
778
950
  }
779
951
  };
780
952
  }
953
+ var PASSIVE_TELEMETRY_EVENTS = /* @__PURE__ */ new Set(["plugin_activate", "plugin_install", "onboarding_view"]);
781
954
  function inferNodeHost() {
782
955
  if (process.env.INKMAP_HOST)
783
956
  return process.env.INKMAP_HOST;
@@ -797,31 +970,39 @@ function inferNodeHost() {
797
970
  }
798
971
  return "cli";
799
972
  }
800
- async function localInstallId() {
801
- const path = join(process.env.INKMAP_HOME ?? join(homedir(), ".inkmap"), "install-id");
802
- let value;
973
+ async function atomicCreateIfMissing(path, initialContent) {
803
974
  try {
804
- value = (await readFile(path, "utf8")).trim();
975
+ return await readFile(path, "utf8");
805
976
  } catch (error) {
806
977
  if (error.code !== "ENOENT")
807
978
  throw error;
808
979
  await mkdir(dirname(path), { recursive: true, mode: 448 });
809
- const generated = "inst_" + randomUUID().replace(/-/g, "").slice(0, 24);
810
980
  const temporary = path + "." + randomUUID();
811
981
  try {
812
- await writeFile(temporary, generated, { mode: 384, flag: "wx" });
813
- await link(temporary, path).catch((err) => {
814
- if (err.code !== "EEXIST")
815
- throw err;
982
+ await writeFile(temporary, initialContent, { mode: 384, flag: "wx" });
983
+ await link(temporary, path).catch(async (err) => {
984
+ if (err.code === "EEXIST")
985
+ return;
986
+ if (err.code === "EPERM" || err.code === "ENOSYS" || err.code === "EXDEV") {
987
+ await rename(temporary, path);
988
+ return;
989
+ }
990
+ throw err;
816
991
  });
817
992
  } finally {
818
- await rm(temporary, { force: true });
993
+ await rm(temporary, { force: true }).catch(() => {
994
+ });
819
995
  }
820
- value = (await readFile(path, "utf8")).trim();
996
+ return await readFile(path, "utf8");
821
997
  }
998
+ }
999
+ async function localInstallId() {
1000
+ const path = join(process.env.INKMAP_HOME || join(homedir(), ".inkmap"), "install-id");
1001
+ const generated = "inst_" + randomUUID().replace(/-/g, "").slice(0, 24);
1002
+ const value = (await atomicCreateIfMissing(path, generated)).trim();
822
1003
  return /^[A-Za-z0-9_:-]{8,64}$/.test(value) ? value : void 0;
823
1004
  }
824
- function fileSessionStorage(path = join(process.env.INKMAP_HOME ?? join(homedir(), ".inkmap"), "billing-session")) {
1005
+ function fileSessionStorage(path = join(process.env.INKMAP_HOME || join(homedir(), ".inkmap"), "billing-session")) {
825
1006
  return {
826
1007
  read: () => readFile(path, "utf8").then((s) => s.trim() || void 0, () => void 0),
827
1008
  async write(token) {
@@ -839,40 +1020,26 @@ function fileSessionStorage(path = join(process.env.INKMAP_HOME ?? join(homedir(
839
1020
  };
840
1021
  }
841
1022
  async function localTrialDeadline() {
842
- const path = join(homedir(), ".inkmap", "trial-start");
843
- const now = Date.now();
844
- let value;
845
- try {
846
- value = await readFile(path, "utf8");
847
- } catch (error) {
848
- if (error.code !== "ENOENT")
849
- throw error;
850
- await mkdir(dirname(path), { recursive: true, mode: 448 });
851
- const temporary = path + "." + randomUUID();
852
- try {
853
- await writeFile(temporary, String(now), { mode: 384, flag: "wx" });
854
- await link(temporary, path).catch((error2) => {
855
- if (error2.code !== "EEXIST")
856
- throw error2;
857
- });
858
- } finally {
859
- await rm(temporary, { force: true });
860
- }
861
- value = await readFile(path, "utf8");
862
- }
1023
+ const path = join(process.env.INKMAP_HOME || join(homedir(), ".inkmap"), "trial-start");
1024
+ const value = await atomicCreateIfMissing(path, String(Date.now()));
863
1025
  const started = Number(value);
864
1026
  return Number.isSafeInteger(started) && started > 0 && started <= Date.now() ? started + TRIAL_MS : void 0;
865
1027
  }
866
- var AD_TTL = 6 * 60 * 60 * 1e3;
867
1028
 
868
1029
  // packages/cli/dist/server.js
869
1030
  import { spawn } from "node:child_process";
870
1031
  import { createHash, randomBytes } from "node:crypto";
871
1032
  import { watch } from "node:fs";
872
- import { lstat, mkdir as mkdir2, readdir, readFile as readFile2, realpath, rename as rename2, rm as rm2, stat, writeFile as writeFile2 } from "node:fs/promises";
1033
+ import { lstat as lstat2, mkdir as mkdir2, readFile as readFile3, realpath as realpath2, rename as rename2, rm as rm2, stat, writeFile as writeFile2 } from "node:fs/promises";
873
1034
  import { createServer } from "node:http";
1035
+ import { homedir as homedir3 } from "node:os";
1036
+ import { basename as basename2, delimiter as delimiter2, dirname as dirname3, extname, join as join3, normalize, relative as relative2, resolve as resolve2, sep as sep3 } from "node:path";
1037
+
1038
+ // packages/cli/dist/workspace-fs.js
1039
+ import { lstat, readdir, readFile as readFile2, realpath } from "node:fs/promises";
874
1040
  import { homedir as homedir2 } from "node:os";
875
- import { basename, delimiter, dirname as dirname2, extname, isAbsolute, join as join2, normalize, relative, resolve, sep } from "node:path";
1041
+ import { basename, delimiter, dirname as dirname2, isAbsolute, join as join2, posix, relative, resolve, sep as sep2, win32 } from "node:path";
1042
+ var MAX_MARKDOWN_BYTES = 5 * 1024 * 1024;
876
1043
  var SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
877
1044
  ".git",
878
1045
  ".hg",
@@ -895,15 +1062,22 @@ var SKIP_SCAN_DIRS = /* @__PURE__ */ new Set([
895
1062
  "coverage",
896
1063
  ".tmp"
897
1064
  ]);
898
- function insideRoot(root, target) {
1065
+ var MARKMAP_RE = /\.markmap\.md$/i;
1066
+ function insideOrEqual(root, target) {
899
1067
  if (root === target)
900
1068
  return true;
901
1069
  const rel = relative(root, target);
902
- return Boolean(rel && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(".." + sep));
1070
+ return Boolean(rel && !isAbsolute(rel) && rel !== ".." && !rel.startsWith(".." + sep2));
1071
+ }
1072
+ function hasHiddenSegment(root, target) {
1073
+ const rel = relative(root, target);
1074
+ if (!rel || rel === ".")
1075
+ return false;
1076
+ return rel.split(sep2).some((part) => part.startsWith("."));
903
1077
  }
904
1078
  async function findProjectRoot(filePath) {
905
- let cur = dirname2(filePath);
906
1079
  const home = await realpath(homedir2()).catch(() => homedir2());
1080
+ let cur = dirname2(filePath);
907
1081
  while (cur && cur !== dirname2(cur) && cur !== home) {
908
1082
  try {
909
1083
  await lstat(join2(cur, ".git"));
@@ -914,7 +1088,7 @@ async function findProjectRoot(filePath) {
914
1088
  }
915
1089
  return dirname2(filePath);
916
1090
  }
917
- async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
1091
+ async function scanMarkdownFiles(rootDir, { maxFiles = 200, maxDepth = 4, byRecent = false } = {}) {
918
1092
  const found = [];
919
1093
  async function walk(dir, depth) {
920
1094
  if (depth > maxDepth || found.length >= maxFiles)
@@ -936,12 +1110,12 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
936
1110
  await walk(full, depth + 1);
937
1111
  } else if (entry.isFile() && /\.md$/i.test(entry.name)) {
938
1112
  try {
939
- const st = await lstat(full);
940
- if (st.isFile() && st.size <= 5 * 1024 * 1024) {
941
- const real = await realpath(full);
942
- if (real === full && insideRoot(rootDir, real))
943
- found.push(real);
944
- }
1113
+ const info = await lstat(full);
1114
+ if (!info.isFile() || info.size > MAX_MARKDOWN_BYTES)
1115
+ continue;
1116
+ const real = await realpath(full);
1117
+ if (real === full && insideOrEqual(rootDir, real))
1118
+ found.push({ path: real, mtimeMs: info.mtimeMs });
945
1119
  } catch {
946
1120
  }
947
1121
  }
@@ -949,14 +1123,18 @@ async function scanProjectMarkdownFiles(rootDir, maxFiles = 200, maxDepth = 4) {
949
1123
  }
950
1124
  await walk(rootDir, 0);
951
1125
  found.sort((a, b) => {
952
- const aM = /\.markmap\.md$/i.test(a) ? 0 : 1;
953
- const bM = /\.markmap\.md$/i.test(b) ? 0 : 1;
954
- if (aM !== bM)
955
- return aM - bM;
956
- return a.localeCompare(b);
1126
+ const am = MARKMAP_RE.test(a.path) ? 0 : 1;
1127
+ const bm = MARKMAP_RE.test(b.path) ? 0 : 1;
1128
+ if (am !== bm)
1129
+ return am - bm;
1130
+ if (byRecent && Math.abs(b.mtimeMs - a.mtimeMs) > 1e3)
1131
+ return b.mtimeMs - a.mtimeMs;
1132
+ return a.path.localeCompare(b.path);
957
1133
  });
958
1134
  return found;
959
1135
  }
1136
+
1137
+ // packages/cli/dist/server.js
960
1138
  var MAX_BODY = 20 * 1024 * 1024;
961
1139
  var TYPES = {
962
1140
  ".html": "text/html; charset=utf-8",
@@ -968,29 +1146,40 @@ var TYPES = {
968
1146
  ".jpeg": "image/jpeg",
969
1147
  ".gif": "image/gif",
970
1148
  ".webp": "image/webp",
1149
+ ".avif": "image/avif",
1150
+ ".bmp": "image/bmp",
1151
+ ".ico": "image/x-icon",
971
1152
  ".woff2": "font/woff2",
972
1153
  ".woff": "font/woff",
973
1154
  ".ttf": "font/ttf",
974
1155
  ".json": "application/json"
975
1156
  };
1157
+ var HttpError = class extends Error {
1158
+ status;
1159
+ constructor(status, message) {
1160
+ super(message);
1161
+ this.status = status;
1162
+ }
1163
+ };
1164
+ var LOOPBACK_HOST = /^(?:127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/i;
976
1165
  var hash = (s) => createHash("sha1").update(s).digest("hex");
977
1166
  function docName(path) {
978
- return basename(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
1167
+ return basename2(path).replace(/\.md$/i, "").replace(/\.markmap$/i, "");
979
1168
  }
980
1169
  function viewStateFile(key) {
981
- const base = process.env.INKMAP_HOME ?? join2(homedir2(), ".inkmap");
982
- return join2(base, "view-state", hash(key) + ".json");
1170
+ const base = process.env.INKMAP_HOME || join3(homedir3(), ".inkmap");
1171
+ return join3(base, "view-state", hash(key) + ".json");
983
1172
  }
984
1173
  async function readDiskViewState(key) {
985
1174
  try {
986
- return sanitizeViewState(JSON.parse(await readFile2(viewStateFile(key), "utf8")));
1175
+ return sanitizeViewState(JSON.parse(await readFile3(viewStateFile(key), "utf8")));
987
1176
  } catch {
988
1177
  return void 0;
989
1178
  }
990
1179
  }
991
1180
  async function writeDiskViewState(key, state) {
992
1181
  const target = viewStateFile(key);
993
- await mkdir2(dirname2(target), { recursive: true, mode: 448 });
1182
+ await mkdir2(dirname3(target), { recursive: true, mode: 448 });
994
1183
  const temp = `${target}.${process.pid}.${Date.now()}`;
995
1184
  try {
996
1185
  await writeFile2(temp, JSON.stringify(state), { mode: 384 });
@@ -1002,24 +1191,26 @@ async function writeDiskViewState(key, state) {
1002
1191
  }
1003
1192
  async function fileSource(file, log = () => {
1004
1193
  }) {
1005
- const path = await realpath(resolve(file)).catch(() => resolve(file));
1194
+ const path = await realpath2(resolve2(file)).catch(() => resolve2(file));
1006
1195
  if (!(await stat(path)).isFile())
1007
1196
  throw new Error(`\u4E0D\u662F\u6587\u4EF6\uFF1A${path}`);
1008
- const dir = dirname2(path);
1197
+ const dir = dirname3(path);
1009
1198
  return {
1010
1199
  name: docName(path),
1011
1200
  key: path,
1012
1201
  dir,
1013
- read: () => readFile2(path, "utf8"),
1202
+ read: () => readFile3(path, "utf8"),
1014
1203
  async write(md) {
1015
1204
  await writeFile2(path, md, "utf8");
1016
1205
  log(`\u5DF2\u5199\u56DE ${path}`);
1017
1206
  },
1018
1207
  watch(onChange) {
1019
1208
  const watcher = watch(dir, (_, changed) => {
1020
- if (!changed || changed === basename(path))
1209
+ if (!changed || changed === basename2(path))
1021
1210
  onChange();
1022
1211
  });
1212
+ watcher.on("error", () => {
1213
+ });
1023
1214
  return () => watcher.close();
1024
1215
  },
1025
1216
  readView: () => readDiskViewState(path),
@@ -1027,8 +1218,15 @@ async function fileSource(file, log = () => {
1027
1218
  };
1028
1219
  }
1029
1220
  function within(root, rel) {
1030
- const base = root.endsWith(sep) ? root : root + sep;
1031
- const full = normalize(join2(root, decodeURIComponent(rel)));
1221
+ let decoded;
1222
+ try {
1223
+ decoded = decodeURIComponent(rel);
1224
+ } catch {
1225
+ return null;
1226
+ }
1227
+ const resolvedRoot = resolve2(root);
1228
+ const base = resolvedRoot.endsWith(sep3) ? resolvedRoot : resolvedRoot + sep3;
1229
+ const full = normalize(join3(resolvedRoot, decoded));
1032
1230
  return full.startsWith(base) ? full : null;
1033
1231
  }
1034
1232
  async function openBrowserWindow(url) {
@@ -1057,7 +1255,7 @@ async function openBrowserWindow(url) {
1057
1255
  await run("xdg-open", [url]);
1058
1256
  }
1059
1257
  async function serve({ source: initialSource, webRoot: webRoot2, port = 4377, host = "127.0.0.1", log = () => {
1060
- }, license, ads, sidebar = false, sidebarPurchase = false, sidebarAccountNavigation = false, loginOnly = false, ideWorkspace = false, workspaceRoots = [] }) {
1258
+ }, license, sidebar = false, sidebarPurchase = false, sidebarAccountNavigation = false, ideWorkspace = false, workspaceRoots = [], confineToWorkspaceRoots = false, openSource = (path) => fileSource(path, log), allowPurchase = true }) {
1061
1259
  if (sidebar && host !== "127.0.0.1")
1062
1260
  throw new Error("The sidebar bridge requires loopback.");
1063
1261
  const prefix2 = sidebar ? `/s/${randomBytes(24).toString("hex")}/` : "/";
@@ -1068,7 +1266,9 @@ async function serve({ source: initialSource, webRoot: webRoot2, port = 4377, ho
1068
1266
  let version = hash(current);
1069
1267
  let viewState = await activeSource.readView?.();
1070
1268
  const clients = /* @__PURE__ */ new Set();
1071
- const canPurchase = !loginOnly && (!sidebar || sidebarPurchase);
1269
+ const canPurchase = sidebar ? sidebarPurchase : allowPurchase;
1270
+ const allowedHosts = /* @__PURE__ */ new Set();
1271
+ const urlHost = host.includes(":") ? `[${host}]` : host;
1072
1272
  const docState = () => ({
1073
1273
  name: activeSource.name,
1074
1274
  md: current,
@@ -1103,36 +1303,36 @@ data: ${JSON.stringify(data)}
1103
1303
  broadcast();
1104
1304
  }
1105
1305
  let pending;
1106
- let unwatch = activeSource.watch(() => {
1306
+ const scheduleRefresh = () => {
1107
1307
  clearTimeout(pending);
1108
- pending = setTimeout(async () => {
1109
- void serialized(refresh).catch(() => {
1110
- });
1111
- }, 80);
1112
- });
1308
+ pending = setTimeout(() => void serialized(refresh).catch(() => {
1309
+ }), 80);
1310
+ };
1311
+ let unwatch = activeSource.watch(scheduleRefresh);
1312
+ const canonicalActiveKey = async () => activeSource.key ? await realpath2(activeSource.key).catch(() => activeSource.key) : void 0;
1113
1313
  async function collectWorkspaceFiles() {
1114
1314
  const roots = /* @__PURE__ */ new Map();
1115
- if (activeSource.key) {
1116
- const realKey = await realpath(activeSource.key).catch(() => activeSource.key);
1117
- const projRoot = await realpath(await findProjectRoot(realKey)).catch(() => dirname2(realKey));
1118
- roots.set(projRoot, { path: projRoot, name: basename(projRoot), active: true });
1315
+ if (activeSource.key && !confineToWorkspaceRoots) {
1316
+ const realKey = await realpath2(activeSource.key).catch(() => activeSource.key);
1317
+ const projRoot = await realpath2(await findProjectRoot(realKey)).catch(() => dirname3(realKey));
1318
+ roots.set(projRoot, { path: projRoot, name: basename2(projRoot), active: true });
1119
1319
  }
1120
- const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(delimiter)].filter(Boolean);
1320
+ const envRoots = [...workspaceRoots, ...(process.env.INKMAP_WORKSPACES || "").split(delimiter2)].filter(Boolean);
1121
1321
  for (const raw of envRoots) {
1122
- const real = await realpath(resolve(raw)).catch(() => null);
1322
+ const real = await realpath2(resolve2(raw)).catch(() => null);
1123
1323
  if (real && !roots.has(real)) {
1124
- roots.set(real, { path: real, name: basename(real), active: roots.size === 0 });
1324
+ roots.set(real, { path: real, name: basename2(real), active: roots.size === 0 });
1125
1325
  }
1126
1326
  }
1127
1327
  const items = [];
1128
1328
  const seen = /* @__PURE__ */ new Set();
1129
1329
  for (const root of roots.values()) {
1130
- const files = await scanProjectMarkdownFiles(root.path);
1330
+ const files = (await scanMarkdownFiles(root.path)).map((entry) => entry.path);
1131
1331
  for (const f of files) {
1132
1332
  if (seen.has(f))
1133
1333
  continue;
1134
1334
  seen.add(f);
1135
- const rel = relative(root.path, f);
1335
+ const rel = relative2(root.path, f);
1136
1336
  items.push({
1137
1337
  path: f,
1138
1338
  label: `${root.name} / ${rel}`,
@@ -1140,43 +1340,52 @@ data: ${JSON.stringify(data)}
1140
1340
  });
1141
1341
  }
1142
1342
  }
1143
- if (activeSource.key && !seen.has(activeSource.key)) {
1343
+ const activeReal = await canonicalActiveKey();
1344
+ if (activeSource.key && activeReal && !seen.has(activeReal)) {
1144
1345
  items.unshift({
1145
1346
  path: activeSource.key,
1146
- label: `${basename(activeSource.dir)} / ${basename(activeSource.key)}`,
1347
+ label: `${basename2(activeSource.dir)} / ${basename2(activeSource.key)}`,
1147
1348
  group: "active"
1148
1349
  });
1149
1350
  }
1150
1351
  return { roots: [...roots.values()], files: items };
1151
1352
  }
1152
- async function switchSourceToFile(candidatePath) {
1153
- if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath)) {
1154
- throw new Error("\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002");
1353
+ const zh = () => detectOsLocale() === "zh";
1354
+ async function switchSourceToFile(candidatePath, trustCaller = false) {
1355
+ const notMarkdown = () => new HttpError(400, zh() ? "\u8BF7\u9009\u62E9 .md \u6216 .markmap.md \u6587\u4EF6\u3002" : "Choose a .md or .markmap.md file.");
1356
+ if (!candidatePath || typeof candidatePath !== "string" || !/\.md$/i.test(candidatePath))
1357
+ throw notMarkdown();
1358
+ const resolvedCandidate = resolve2(candidatePath);
1359
+ const rawStat = await lstat2(resolvedCandidate).catch(() => null);
1360
+ const realTarget = await realpath2(resolvedCandidate).catch(() => null);
1361
+ const targetStat = realTarget ? await stat(realTarget).catch(() => null) : null;
1362
+ if (!rawStat || rawStat.isSymbolicLink() && !trustCaller || !realTarget || !targetStat?.isFile() || targetStat.size > MAX_MARKDOWN_BYTES) {
1363
+ throw new HttpError(403, zh() ? "\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684\u666E\u901A Markdown \u6587\u4EF6\u3002" : "Choose a regular Markdown file up to 5 MiB.");
1155
1364
  }
1156
- const realTarget = await realpath(resolve(candidatePath));
1157
- const st = await lstat(realTarget);
1158
- if (!st.isFile() || st.size > 5 * 1024 * 1024) {
1159
- throw new Error("\u8BF7\u9009\u62E9 5 MiB \u4EE5\u5185\u7684 Markdown \u6587\u4EF6\u3002");
1160
- }
1161
- const { roots } = await collectWorkspaceFiles();
1162
- if (roots.length > 0 && !roots.some((r) => insideRoot(r.path, realTarget))) {
1163
- throw new Error("\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u9879\u76EE\u5DE5\u4F5C\u533A\u5185\u3002");
1365
+ if (!/\.md$/i.test(realTarget))
1366
+ throw notMarkdown();
1367
+ if (!trustCaller) {
1368
+ const { roots } = await collectWorkspaceFiles();
1369
+ const matchedRoot = roots.find((r) => insideOrEqual(r.path, realTarget));
1370
+ if (!matchedRoot) {
1371
+ throw new HttpError(403, zh() ? "\u8BE5\u6587\u4EF6\u4E0D\u5728\u5F53\u524D\u9879\u76EE\u5DE5\u4F5C\u533A\u5185\u3002" : "This file is outside the current workspace.");
1372
+ }
1373
+ if (hasHiddenSegment(matchedRoot.path, realTarget)) {
1374
+ throw new HttpError(403, zh() ? "\u4E0D\u652F\u6301\u8BBF\u95EE\u9690\u85CF\u76EE\u5F55\u4E2D\u7684\u6587\u4EF6\u3002" : "Files in hidden folders are not allowed.");
1375
+ }
1164
1376
  }
1165
- if (activeSource.key === realTarget)
1377
+ if (await canonicalActiveKey() === realTarget)
1166
1378
  return;
1379
+ const next = await openSource(trustCaller ? resolvedCandidate : realTarget);
1380
+ const text = await next.read();
1381
+ const nextView = await next.readView?.();
1167
1382
  clearTimeout(pending);
1168
1383
  unwatch();
1169
- activeSource = await fileSource(realTarget, log);
1170
- current = await activeSource.read();
1171
- version = hash(current);
1172
- viewState = await activeSource.readView?.();
1173
- unwatch = activeSource.watch(() => {
1174
- clearTimeout(pending);
1175
- pending = setTimeout(async () => {
1176
- void serialized(refresh).catch(() => {
1177
- });
1178
- }, 80);
1179
- });
1384
+ activeSource = next;
1385
+ current = text;
1386
+ version = hash(text);
1387
+ viewState = nextView;
1388
+ unwatch = activeSource.watch(scheduleRefresh);
1180
1389
  broadcast();
1181
1390
  }
1182
1391
  const json2 = (res, status, body) => {
@@ -1189,7 +1398,7 @@ data: ${JSON.stringify(data)}
1189
1398
  req.on("data", (c) => {
1190
1399
  size += c.length;
1191
1400
  if (size > MAX_BODY) {
1192
- fail(new Error("\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927"));
1401
+ fail(new HttpError(413, zh() ? "\u8BF7\u6C42\u5185\u5BB9\u8FC7\u5927\u3002" : "The request is too large."));
1193
1402
  req.destroy();
1194
1403
  } else
1195
1404
  chunks.push(c);
@@ -1204,13 +1413,20 @@ data: ${JSON.stringify(data)}
1204
1413
  const ext = extname(full).toLowerCase();
1205
1414
  if (ext === ".html") {
1206
1415
  const osLoc = detectOsLocale();
1207
- const htmlText = (await readFile2(full, "utf8")).replace(/<html\b([^>]*)>/i, `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
1416
+ const htmlText = (await readFile3(full, "utf8")).replace(/<html\b([^>]*)>/i, () => `<html lang="${osLoc === "zh" ? "zh-CN" : "en"}" data-os-locale="${osLoc}">`);
1208
1417
  res.writeHead(200, { "content-type": TYPES[".html"], "cache-control": "no-store" });
1209
1418
  res.end(htmlText, "utf8");
1210
1419
  return;
1211
1420
  }
1212
- const body = await readFile2(full);
1213
- res.writeHead(200, { "content-type": TYPES[ext] ?? "application/octet-stream", "cache-control": sidebar ? "no-store" : "no-cache" });
1421
+ const body = await readFile3(full);
1422
+ const headers = {
1423
+ "content-type": TYPES[ext] ?? "application/octet-stream",
1424
+ "cache-control": sidebar ? "no-store" : "no-cache"
1425
+ };
1426
+ if (ext === ".svg") {
1427
+ headers["content-security-policy"] = "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox";
1428
+ }
1429
+ res.writeHead(200, headers);
1214
1430
  res.end(body);
1215
1431
  } catch {
1216
1432
  json2(res, 404, { error: "not found" });
@@ -1219,18 +1435,27 @@ data: ${JSON.stringify(data)}
1219
1435
  const server = createServer(async (req, res) => {
1220
1436
  try {
1221
1437
  const url = new URL(req.url ?? "/", "http://localhost");
1438
+ const reqHost = req.headers.host ?? "";
1439
+ const hostAllowed = LOOPBACK_HOST.test(reqHost) || allowedHosts.has(reqHost.toLowerCase());
1222
1440
  if (sidebar) {
1223
1441
  res.setHeader("Referrer-Policy", "no-referrer");
1224
1442
  res.setHeader("X-Content-Type-Options", "nosniff");
1225
1443
  res.setHeader("Cache-Control", "no-store");
1226
1444
  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'");
1227
- if (req.headers.host !== `127.0.0.1:${bound}` || !url.pathname.startsWith(prefix2))
1445
+ if (reqHost !== `127.0.0.1:${bound}` || !url.pathname.startsWith(prefix2))
1228
1446
  return json2(res, 404, { error: "not found" });
1229
1447
  if ((req.method === "PUT" || req.method === "POST") && (req.headers.origin !== `http://127.0.0.1:${bound}` || req.headers["content-type"] !== "application/json")) {
1230
1448
  return json2(res, 403, { error: "forbidden" });
1231
1449
  }
1232
1450
  url.pathname = "/" + url.pathname.slice(prefix2.length);
1451
+ } else if (!hostAllowed) {
1452
+ return json2(res, 403, { error: "forbidden" });
1233
1453
  }
1454
+ const sameOriginWrite = () => {
1455
+ const origin = req.headers.origin;
1456
+ const sameOrigin = origin === "http://" + reqHost || allowedHosts.has(reqHost.toLowerCase()) && origin === "https://" + reqHost;
1457
+ return hostAllowed && sameOrigin && req.headers["content-type"] === "application/json";
1458
+ };
1234
1459
  if (!sidebar && req.method === "GET" && /^\/(?:%E3%80%82|%EF%BC%8C|[。,.,;;::!?!?])+$/i.test(url.pathname)) {
1235
1460
  res.writeHead(302, { Location: "/" + url.search });
1236
1461
  return res.end();
@@ -1254,6 +1479,8 @@ data: ${JSON.stringify(data)}
1254
1479
  });
1255
1480
  }
1256
1481
  if (url.pathname === "/api/view" && req.method === "PUT") {
1482
+ if (!sameOriginWrite())
1483
+ return json2(res, 403, { error: "forbidden" });
1257
1484
  const cleaned = sanitizeViewState(JSON.parse(await readBody2(req)));
1258
1485
  if (cleaned) {
1259
1486
  viewState = cleaned;
@@ -1263,9 +1490,11 @@ data: ${JSON.stringify(data)}
1263
1490
  return json2(res, 200, { ok: true });
1264
1491
  }
1265
1492
  if (url.pathname === "/api/doc" && req.method === "PUT") {
1493
+ if (!sameOriginWrite())
1494
+ return json2(res, 403, { error: "forbidden" });
1266
1495
  const { md, baseVersion } = JSON.parse(await readBody2(req));
1267
1496
  if (typeof md !== "string")
1268
- return json2(res, 400, { error: "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32" });
1497
+ return json2(res, 400, { error: zh() ? "md \u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u3002" : "md must be a string." });
1269
1498
  if (!hasAccess(await license?.state() ?? { pro: false }))
1270
1499
  return json2(res, 403, { error: "Inkmap trial expired" });
1271
1500
  return await serialized(async () => {
@@ -1277,31 +1506,24 @@ data: ${JSON.stringify(data)}
1277
1506
  current = md;
1278
1507
  version = hash(md);
1279
1508
  license?.track?.("doc_edit");
1280
- if (sidebar)
1281
- broadcast();
1509
+ broadcast();
1282
1510
  }
1283
1511
  return json2(res, 200, { version });
1284
1512
  });
1285
1513
  }
1286
1514
  if (url.pathname === "/api/license" && req.method === "GET")
1287
1515
  return json2(res, 200, await license?.state() ?? { pro: false });
1288
- const sameOriginPost = () => {
1289
- const origin = req.headers.origin;
1290
- const reqHost = req.headers.host;
1291
- const local = reqHost && /^(127\.0\.0\.1|localhost|\[::1\]):[0-9]+$/.test(reqHost);
1292
- return Boolean(local && origin === "http://" + reqHost && req.headers["content-type"] === "application/json");
1293
- };
1294
1516
  if (url.pathname === "/api/open" && req.method === "POST") {
1295
- if (!sameOriginPost())
1517
+ if (!sameOriginWrite())
1296
1518
  return json2(res, 403, { error: "forbidden" });
1297
1519
  const { file } = JSON.parse(await readBody2(req));
1298
- await serialized(() => switchSourceToFile(String(file ?? "")));
1520
+ await serialized(() => switchSourceToFile(String(file ?? ""), false));
1299
1521
  license?.track?.("doc_open");
1300
1522
  const { files } = await collectWorkspaceFiles();
1301
1523
  return json2(res, 200, { currentFile: activeSource.key ?? null, files, doc: docState() });
1302
1524
  }
1303
1525
  if (url.pathname === "/api/telemetry" && req.method === "POST") {
1304
- if (!sameOriginPost())
1526
+ if (!sameOriginWrite())
1305
1527
  return json2(res, 403, { error: "forbidden" });
1306
1528
  const { event } = JSON.parse(await readBody2(req));
1307
1529
  if (typeof event === "string" && event)
@@ -1309,45 +1531,43 @@ data: ${JSON.stringify(data)}
1309
1531
  return json2(res, 200, { ok: true });
1310
1532
  }
1311
1533
  if (url.pathname === "/api/open-browser" && req.method === "POST") {
1312
- if (!sameOriginPost())
1534
+ if (!sameOriginWrite())
1313
1535
  return json2(res, 403, { error: "forbidden" });
1314
1536
  if (license && !hasAccess(await license.state())) {
1315
1537
  return json2(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." });
1316
1538
  }
1317
1539
  license?.track?.("feature_browser");
1318
1540
  if (!sidebar) {
1319
- const directUrl = `http://${host}:${bound}/`;
1541
+ const directUrl = `http://${urlHost}:${bound}/`;
1320
1542
  await openBrowserWindow(directUrl);
1321
1543
  return json2(res, 200, { ok: true, url: directUrl });
1322
1544
  }
1323
1545
  if (!browserCompanion) {
1324
- browserCompanion = (async () => {
1325
- const src = activeSource.key ? await fileSource(activeSource.key) : activeSource;
1326
- return serve({
1327
- source: src,
1328
- webRoot: webRoot2,
1329
- host: "127.0.0.1",
1330
- port: 0,
1331
- license,
1332
- ads,
1333
- sidebar: false,
1334
- loginOnly: false,
1335
- workspaceRoots
1336
- });
1337
- })();
1546
+ browserCompanion = serve({
1547
+ source: activeSource,
1548
+ webRoot: webRoot2,
1549
+ host: "127.0.0.1",
1550
+ port: 0,
1551
+ license,
1552
+ sidebar: false,
1553
+ workspaceRoots,
1554
+ confineToWorkspaceRoots,
1555
+ openSource,
1556
+ allowPurchase: canPurchase
1557
+ });
1338
1558
  browserCompanion.catch(() => {
1339
1559
  browserCompanion = null;
1340
1560
  });
1341
1561
  }
1342
1562
  const companion = await browserCompanion;
1343
1563
  if (activeSource.key)
1344
- await companion.switchToFile?.(activeSource.key).catch(() => {
1564
+ await companion.switchToFile?.(activeSource.key, { trustCaller: true }).catch(() => {
1345
1565
  });
1346
1566
  await openBrowserWindow(companion.url);
1347
1567
  return json2(res, 200, { ok: true, url: companion.url });
1348
1568
  }
1349
1569
  if (url.pathname === "/api/checkout" && req.method === "POST") {
1350
- if (!sameOriginPost())
1570
+ if (!sameOriginWrite())
1351
1571
  return json2(res, 403, { error: "forbidden" });
1352
1572
  const { mode, locale } = JSON.parse(await readBody2(req));
1353
1573
  if (mode !== "buy" && mode !== "restore")
@@ -1359,7 +1579,7 @@ data: ${JSON.stringify(data)}
1359
1579
  return json2(res, 200, { url: await (typeof locale === "string" ? license.connect(mode, locale) : license.connect(mode)) });
1360
1580
  }
1361
1581
  if (url.pathname === "/api/order-pro" && req.method === "POST") {
1362
- if (!sameOriginPost())
1582
+ if (!sameOriginWrite())
1363
1583
  return json2(res, 403, { error: "forbidden" });
1364
1584
  if (!canPurchase)
1365
1585
  return json2(res, 403, { error: "forbidden" });
@@ -1371,7 +1591,7 @@ data: ${JSON.stringify(data)}
1371
1591
  return json2(res, 200, { result: await (typeof locale === "string" ? license.orderPro(locale) : license.orderPro()) });
1372
1592
  }
1373
1593
  if (url.pathname === "/api/phone-send" && req.method === "POST") {
1374
- if (!sameOriginPost())
1594
+ if (!sameOriginWrite())
1375
1595
  return json2(res, 403, { error: "forbidden" });
1376
1596
  if (!license || typeof license.sendPhoneCode !== "function")
1377
1597
  return json2(res, 501, { fallback: true });
@@ -1379,21 +1599,21 @@ data: ${JSON.stringify(data)}
1379
1599
  return json2(res, 200, { result: await (typeof locale === "string" ? license.sendPhoneCode(String(phone ?? ""), locale) : license.sendPhoneCode(String(phone ?? ""))) });
1380
1600
  }
1381
1601
  if (url.pathname === "/api/phone-verify" && req.method === "POST") {
1382
- if (!sameOriginPost())
1602
+ if (!sameOriginWrite())
1383
1603
  return json2(res, 403, { error: "forbidden" });
1384
1604
  if (!license || typeof license.signInByPhone !== "function")
1385
1605
  return json2(res, 501, { fallback: true });
1386
- const { phone, code } = JSON.parse(await readBody2(req));
1387
- return json2(res, 200, { result: await license.signInByPhone(String(phone ?? ""), String(code ?? "")) });
1606
+ const { phone, code, locale } = JSON.parse(await readBody2(req));
1607
+ return json2(res, 200, {
1608
+ result: await (typeof locale === "string" ? license.signInByPhone(String(phone ?? ""), String(code ?? ""), locale) : license.signInByPhone(String(phone ?? ""), String(code ?? "")))
1609
+ });
1388
1610
  }
1389
1611
  if (url.pathname === "/api/signout" && req.method === "POST") {
1390
- if (!sameOriginPost())
1612
+ if (!sameOriginWrite())
1391
1613
  return json2(res, 403, { error: "forbidden" });
1392
1614
  await license?.deactivate();
1393
1615
  return json2(res, 200, await license?.state() ?? { pro: false });
1394
1616
  }
1395
- if (url.pathname === "/api/ads")
1396
- return json2(res, 200, sidebar ? [] : await ads?.() ?? []);
1397
1617
  if (url.pathname === "/api/events") {
1398
1618
  res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
1399
1619
  res.write(": connected\n\n");
@@ -1405,17 +1625,21 @@ data: ${JSON.stringify(data)}
1405
1625
  return void res.writeHead(204).end();
1406
1626
  if (url.pathname.startsWith("/doc-assets/")) {
1407
1627
  let asset = within(activeSource.dir, url.pathname.slice("/doc-assets/".length));
1408
- if (sidebar && asset) {
1409
- const root = await realpath(activeSource.dir);
1410
- asset = await realpath(asset).catch(() => null);
1411
- if (asset && (!asset.startsWith(root + sep) || !/\.(?:png|jpe?g|gif|webp)$/i.test(asset)))
1628
+ if (asset) {
1629
+ const root = await realpath2(activeSource.dir).catch(() => null);
1630
+ asset = await realpath2(asset).catch(() => null);
1631
+ const allowedExt = sidebar ? /\.(?:png|jpe?g|gif|webp|avif|bmp|ico)$/i : /\.(?:png|jpe?g|gif|webp|avif|bmp|ico|svg)$/i;
1632
+ if (!root || !asset || !insideOrEqual(root, asset) || !allowedExt.test(asset))
1412
1633
  asset = null;
1413
1634
  }
1414
1635
  return sendFile(res, asset);
1415
1636
  }
1416
1637
  return sendFile(res, within(webRoot2, url.pathname === "/" ? "index.html" : url.pathname.slice(1)));
1417
1638
  } catch (err) {
1418
- json2(res, 500, { error: err instanceof Error ? err.message : String(err) });
1639
+ if (res.headersSent)
1640
+ return void res.end();
1641
+ const status = err instanceof HttpError ? err.status : err instanceof SyntaxError ? 400 : 500;
1642
+ json2(res, status, { error: err instanceof Error ? err.message : String(err) });
1419
1643
  }
1420
1644
  });
1421
1645
  const listen = (p) => new Promise((ok, fail) => {
@@ -1426,15 +1650,26 @@ data: ${JSON.stringify(data)}
1426
1650
  });
1427
1651
  });
1428
1652
  try {
1429
- bound = await listen(port);
1653
+ try {
1654
+ bound = await listen(port);
1655
+ } catch (err) {
1656
+ if (err.code !== "EADDRINUSE")
1657
+ throw err;
1658
+ bound = await listen(0);
1659
+ }
1430
1660
  } catch (err) {
1431
- if (err.code !== "EADDRINUSE")
1432
- throw err;
1433
- bound = await listen(0);
1661
+ clearTimeout(pending);
1662
+ unwatch();
1663
+ unlisten();
1664
+ throw err;
1434
1665
  }
1435
1666
  return {
1436
- url: `http://${host}:${bound}${prefix2}`,
1437
- switchToFile: (filePath) => serialized(() => switchSourceToFile(filePath)),
1667
+ url: `http://${urlHost}:${bound}${prefix2}`,
1668
+ switchToFile: (filePath, options) => serialized(() => switchSourceToFile(filePath, Boolean(options?.trustCaller))),
1669
+ allowHost: (extraHost) => {
1670
+ if (extraHost)
1671
+ allowedHosts.add(extraHost.toLowerCase());
1672
+ },
1438
1673
  close: () => new Promise((done) => {
1439
1674
  clearTimeout(pending);
1440
1675
  unwatch();
@@ -1485,18 +1720,33 @@ async function workspaceFile(ctx, address) {
1485
1720
  if (typeof hostPath !== "string") throw new FileUnavailable();
1486
1721
  const roundTrip = fs.processPathFromHostPath(hostPath);
1487
1722
  if (roundTrip === void 0 || (await fs.resolve(roundTrip)).targetKey !== target.targetKey) throw new FileUnavailable();
1488
- return realpath2(hostPath);
1723
+ return realpath3(hostPath);
1489
1724
  };
1490
1725
  const [root, path] = await Promise.all([local(header.cwd), local(file.path)]);
1491
- const child = relative2(root, path);
1492
- if (!child || isAbsolute2(child) || child === ".." || child.startsWith(".." + sep2) || !/\.md$/i.test(path)) {
1726
+ const child = relative3(root, path);
1727
+ if (!child || isAbsolute2(child) || child === ".." || child.startsWith(".." + sep4) || !/\.md$/i.test(path)) {
1493
1728
  throw new FileUnavailable();
1494
1729
  }
1495
1730
  return { root, path };
1496
1731
  }
1497
1732
  async function assertFile(path) {
1498
- const info = await lstat2(path);
1499
- if (!info.isFile() || info.size > maxBytes || await realpath2(path) !== path) throw new FileUnavailable();
1733
+ const info = await lstat3(path);
1734
+ if (!info.isFile() || info.size > maxBytes || await realpath3(path) !== path) throw new FileUnavailable();
1735
+ }
1736
+ async function confinedSource(path) {
1737
+ const source = await fileSource(path);
1738
+ return {
1739
+ ...source,
1740
+ read: async () => {
1741
+ await assertFile(path);
1742
+ return source.read();
1743
+ },
1744
+ write: async (md) => {
1745
+ if (Buffer.byteLength(md) > maxBytes) throw new FileUnavailable();
1746
+ await assertFile(path);
1747
+ return source.write(md);
1748
+ }
1749
+ };
1500
1750
  }
1501
1751
  function json(res, status, body) {
1502
1752
  res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
@@ -1516,8 +1766,10 @@ async function readBody(req) {
1516
1766
  return null;
1517
1767
  }
1518
1768
  }
1769
+ var LEASE_TIMEOUT_MS = 15 * 6e4;
1770
+ var LEASE_SWEEP_MS = 5 * 6e4;
1519
1771
  function apply(ctx) {
1520
- const license = licenseService(fileSessionStorage(), () => YUNFAN_BILLING_ORIGIN, { host: "deepseek" });
1772
+ const license = licenseService(fileSessionStorage(), () => process.env.INKMAP_BILLING_ORIGIN || YUNFAN_BILLING_ORIGIN, { host: "deepseek" });
1521
1773
  license.track?.("plugin_activate", 1, "deepseek");
1522
1774
  const editors = /* @__PURE__ */ new Map();
1523
1775
  const leases = /* @__PURE__ */ new Map();
@@ -1527,6 +1779,18 @@ function apply(ctx) {
1527
1779
  return editor.server.then((server) => server.close(), () => {
1528
1780
  });
1529
1781
  }
1782
+ function releaseLease(id) {
1783
+ const lease = leases.get(id);
1784
+ if (!lease) return;
1785
+ leases.delete(id);
1786
+ const editor = editors.get(lease.path);
1787
+ if (editor && --editor.users === 0) return closeEditor(lease.path, editor);
1788
+ }
1789
+ const sweep = setInterval(() => {
1790
+ const cutoff = Date.now() - LEASE_TIMEOUT_MS;
1791
+ for (const [id, lease] of leases) if (lease.seen < cutoff) void releaseLease(id);
1792
+ }, LEASE_SWEEP_MS);
1793
+ sweep.unref?.();
1530
1794
  ctx.effect(() => {
1531
1795
  const unregister = ctx.webServer.register({
1532
1796
  kind: "exact",
@@ -1542,18 +1806,21 @@ function apply(ctx) {
1542
1806
  const body = await readBody(req).catch(() => null);
1543
1807
  if (!body || typeof body !== "object") return json(res, 400, {});
1544
1808
  if (req.method === "DELETE") {
1545
- const path = leases.get(body?.lease);
1546
- if (path === void 0) return json(res, 200, {});
1547
- leases.delete(body.lease);
1548
- const editor = editors.get(path);
1549
- if (editor && --editor.users === 0) await closeEditor(path, editor);
1809
+ await releaseLease(body?.lease);
1810
+ return json(res, 200, {});
1811
+ }
1812
+ if (body.action === "renew") {
1813
+ const lease = leases.get(body.lease);
1814
+ if (disposed || !lease) return json(res, 404, {});
1815
+ lease.seen = Date.now();
1550
1816
  return json(res, 200, {});
1551
1817
  }
1552
1818
  if (body.action === "sign-in" || body.action === "buy") {
1553
1819
  if (disposed || !leases.has(body.lease)) return json(res, 404, {});
1554
1820
  try {
1555
1821
  const mode = body.action === "buy" ? "buy" : "restore";
1556
- return json(res, 200, { url: await license.connect(mode) });
1822
+ const locale = typeof body.locale === "string" ? body.locale : void 0;
1823
+ return json(res, 200, { url: await license.connect(mode, locale) });
1557
1824
  } catch {
1558
1825
  return json(res, 502, {});
1559
1826
  }
@@ -1564,27 +1831,21 @@ function apply(ctx) {
1564
1831
  if (disposed) return json(res, 503, {});
1565
1832
  let editor = editors.get(path);
1566
1833
  if (!editor) {
1567
- const server2 = fileSource(path).then((source) => serve({
1568
- source: {
1569
- ...source,
1570
- workspaceRoot: root,
1571
- read: async () => {
1572
- await assertFile(path);
1573
- return source.read();
1574
- },
1575
- write: async (md) => {
1576
- if (Buffer.byteLength(md) > maxBytes) throw new FileUnavailable();
1577
- await assertFile(path);
1578
- return source.write(md);
1579
- }
1580
- },
1834
+ const server2 = confinedSource(path).then((source) => serve({
1835
+ source,
1581
1836
  webRoot,
1582
1837
  license,
1583
1838
  port: 0,
1584
1839
  sidebar: true,
1585
1840
  sidebarPurchase: true,
1586
1841
  sidebarAccountNavigation: true,
1587
- workspaceRoots: [root]
1842
+ // Stay inside the session's working directory, even when a .git folder sits above it.
1843
+ workspaceRoots: [root],
1844
+ confineToWorkspaceRoots: true,
1845
+ openSource: async (next) => {
1846
+ await assertFile(next);
1847
+ return confinedSource(next);
1848
+ }
1588
1849
  }));
1589
1850
  editor = { users: 0, server: server2 };
1590
1851
  editors.set(path, editor);
@@ -1592,11 +1853,20 @@ function apply(ctx) {
1592
1853
  if (editors.get(path)?.server === server2) editors.delete(path);
1593
1854
  });
1594
1855
  }
1595
- const server = await editor.server;
1596
- if (disposed) return json(res, 503, {});
1597
- const lease = randomUUID2();
1598
- leases.set(lease, path);
1599
1856
  editor.users++;
1857
+ let server;
1858
+ try {
1859
+ server = await editor.server;
1860
+ } catch (err) {
1861
+ if (--editor.users === 0) void closeEditor(path, editor);
1862
+ throw err;
1863
+ }
1864
+ if (disposed) {
1865
+ if (--editor.users === 0) void closeEditor(path, editor);
1866
+ return json(res, 503, {});
1867
+ }
1868
+ const lease = randomUUID2();
1869
+ leases.set(lease, { path, seen: Date.now() });
1600
1870
  return json(res, 200, { url: server.url, lease });
1601
1871
  } catch (error) {
1602
1872
  const unavailable = error instanceof FileUnavailable || ["ENOENT", "EACCES", "EPERM"].includes(error?.code);
@@ -1606,6 +1876,7 @@ function apply(ctx) {
1606
1876
  });
1607
1877
  return () => {
1608
1878
  disposed = true;
1879
+ clearInterval(sweep);
1609
1880
  unregister();
1610
1881
  license.dispose();
1611
1882
  leases.clear();