@getchomp/cli 0.2.43 → 0.2.44

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.
@@ -17,7 +17,7 @@ import { runAllChompPlugins } from "@getchomp/mcp";
17
17
  import { getGitInfo, resolveRepoName } from "../utils/git.js";
18
18
  import { hydrateRepositoryPortValves } from "../ports/portHydrator.js";
19
19
  import { seedRefGraphDiskCache } from "../server/graphLayoutState.js";
20
- import { ansi, loadExcludeWorkspaces, runChompExtractionWithAnimation, } from "../utils/branding.js";
20
+ import { ansi, countAnalyzableFiles, loadExcludeWorkspaces, runChompExtractionWithAnimation, } from "../utils/branding.js";
21
21
  import { ensureGitExcludeHasChomp, resolveDefaultCliTarget, setActiveChompTarget, } from "../utils/masterContext.js";
22
22
  /**
23
23
  * Runs deterministic AST extraction on `targetPath` and persists the RepresentationGraph to `.chomp/graph.db`.
@@ -74,9 +74,16 @@ export async function runAnalyze(targetPath, options = {}) {
74
74
  return { workingTreeDirty: false, dirtyFiles: [] };
75
75
  }
76
76
  };
77
- const executeExtractionAndSave = async () => {
77
+ const preFlightFileCount = !options.quiet
78
+ ? countAnalyzableFiles(targetPath, excludeWorkspaces)
79
+ : undefined;
80
+ const executeExtractionAndSave = async (onProgress) => {
78
81
  const t0 = Date.now();
79
82
  const graph = analyzeTarget(targetPath, CORE_EXTRACTOR_VERSION, commitSha, excludeWorkspaces);
83
+ if (onProgress) {
84
+ onProgress(`Saving ${graph.nodes.length.toLocaleString()} nodes & ${graph.edges.length.toLocaleString()} connections to SQLite...`);
85
+ await new Promise((r) => setImmediate(r));
86
+ }
80
87
  const storage = createSQLiteStorage(dbPath);
81
88
  const repoInfo = {
82
89
  id: repoId,
@@ -117,6 +124,10 @@ export async function runAnalyze(targetPath, options = {}) {
117
124
  const pluginFailures = [];
118
125
  const pluginWarnings = [];
119
126
  if (options.plugins !== false && !options.noPlugins) {
127
+ if (onProgress) {
128
+ onProgress("Running analysis-time overlay plugins...");
129
+ await new Promise((r) => setImmediate(r));
130
+ }
120
131
  try {
121
132
  const pluginResults = await runAllChompPlugins({
122
133
  repoPath,
@@ -154,6 +165,10 @@ export async function runAnalyze(targetPath, options = {}) {
154
165
  let portHydratedCount = 0;
155
166
  let portDiagnosticCount = 0;
156
167
  if (options.verifyPorts) {
168
+ if (onProgress) {
169
+ onProgress("Verifying TypeScript port schemas...");
170
+ await new Promise((r) => setImmediate(r));
171
+ }
157
172
  try {
158
173
  const portRes = await hydrateRepositoryPortValves({
159
174
  repoPath,
@@ -191,6 +206,8 @@ export async function runAnalyze(targetPath, options = {}) {
191
206
  const res = await runChompExtractionWithAnimation({
192
207
  repoName,
193
208
  repoPath,
209
+ targetPath,
210
+ preFlightFileCount,
194
211
  dbPath,
195
212
  excludeWorkspaces,
196
213
  commitSha,
@@ -16,5 +16,6 @@ export interface StartUiServerOptions {
16
16
  remote?: boolean;
17
17
  targetMode?: ResolvedCliTargetMode;
18
18
  }
19
+ export declare function resolveAvailableUiPort(preferredPort: number, host: string, maxFallbackAttempts?: number): Promise<number>;
19
20
  export declare function startUiServer(targetPath: string, options?: StartUiServerOptions): Promise<void>;
20
21
  export declare function registerUiCommand(program: Command): void;
@@ -1,9 +1,11 @@
1
1
  import { existsSync, statSync, watch, writeFileSync } from "node:fs";
2
+ import { createServer as createNetServer } from "node:net";
2
3
  import { dirname, join, resolve, sep } from "node:path";
3
4
  import express from "express";
4
5
  import { attachTtyBuildProgressSpinner, createBuildStatusTracker, LAYOUT_BUILD_STAGES, } from "../server/buildStatusTracker.js";
5
6
  import { buildLayout, cancelActivePortHydration, createUiServerState, getActiveUiTarget, invalidateAllServerCaches, scheduleBackgroundPortHydration, } from "../server/graphLayoutState.js";
6
7
  import { isAllowedLocalhostOrigin, isLoopbackHostHeader, registerLoopbackSecurityMiddleware, } from "../server/loopbackSecurity.js";
8
+ import { createHostedUiProxyMiddleware } from "../server/hostedUiProxy.js";
7
9
  import { buildAuthStatusPayload, registerAuthAndSourceRoutes, } from "../server/routes/authSourceRoutes.js";
8
10
  import { registerLayoutRoutes } from "../server/routes/layoutRoutes.js";
9
11
  import { registerPluginRoutes } from "../server/routes/pluginRoutes.js";
@@ -15,8 +17,34 @@ import { resolveDefaultCliTarget, setActiveChompTarget, } from "../utils/masterC
15
17
  import { DEFAULT_CLOUD_API_URL, DEFAULT_HOSTED_UI_URL, hasLocalMasterLayoutEngine, resolveLocalMasterWebDir, } from "../visualizer/localEngineBridge.js";
16
18
  import { runAnalyze } from "./analyze.js";
17
19
  export { LAYOUT_BUILD_STAGES, buildLayout, createBuildStatusTracker, getActiveUiTarget, isAllowedLocalhostOrigin, isLoopbackHostHeader, };
20
+ export async function resolveAvailableUiPort(preferredPort, host, maxFallbackAttempts = 15) {
21
+ for (let offset = 0; offset <= maxFallbackAttempts; offset++) {
22
+ const candidate = preferredPort + offset;
23
+ if (candidate > 65535)
24
+ break;
25
+ const isFree = await new Promise((resolvePort) => {
26
+ const probe = createNetServer();
27
+ probe.once("error", (err) => {
28
+ if (err.code === "EADDRINUSE" || err.code === "EACCES") {
29
+ resolvePort(false);
30
+ }
31
+ else {
32
+ resolvePort(false);
33
+ }
34
+ });
35
+ probe.once("listening", () => {
36
+ probe.close(() => resolvePort(true));
37
+ });
38
+ probe.listen(candidate, host);
39
+ });
40
+ if (isFree) {
41
+ return candidate;
42
+ }
43
+ }
44
+ return preferredPort;
45
+ }
18
46
  export async function startUiServer(targetPath, options = {}) {
19
- const port = typeof options.port === "number"
47
+ const requestedPort = typeof options.port === "number"
20
48
  ? options.port
21
49
  : parseInt(options.port ?? "5555", 10);
22
50
  const baseDir = process.env.INIT_CWD ?? process.cwd();
@@ -43,6 +71,10 @@ export async function startUiServer(targetPath, options = {}) {
43
71
  const app = express();
44
72
  const defaultHost = existsSync("/.dockerenv") ? "0.0.0.0" : "127.0.0.1";
45
73
  const host = options.host ?? process.env.CHOMP_UI_HOST ?? defaultHost;
74
+ const port = await resolveAvailableUiPort(requestedPort, host);
75
+ if (port !== requestedPort) {
76
+ console.log(`\n ${ansi.yellowBold("◆")} Port ${ansi.bold(String(requestedPort))} is already in use — binding to ${ansi.yellowBold(String(port))} instead`);
77
+ }
46
78
  registerLoopbackSecurityMiddleware(app);
47
79
  // Serve the local Next.js static export when running inside the master monorepo
48
80
  const localWebDir = options.remote ? null : resolveLocalMasterWebDir();
@@ -110,11 +142,20 @@ export async function startUiServer(targetPath, options = {}) {
110
142
  registerLayoutRoutes(app, state);
111
143
  registerViewAndRulesRoutes(app, state);
112
144
  registerPluginRoutes(app, state);
113
- // SPA fallback (or redirect to hosted UI in published NPM mode)
114
- app.use((_req, res) => {
145
+ // SPA fallback (local static export in master monorepo, or same-origin reverse proxy in NPM mode for Safari)
146
+ const hostedProxyMiddleware = !localWebDir
147
+ ? createHostedUiProxyMiddleware(rawHostedUi || DEFAULT_HOSTED_UI_URL)
148
+ : null;
149
+ app.use((req, res, next) => {
150
+ if (req.path === "/api" || req.path.startsWith("/api/")) {
151
+ return res.status(404).json({ error: "Not Found" });
152
+ }
115
153
  if (localWebDir) {
116
154
  return res.sendFile(join(localWebDir, "index.html"));
117
155
  }
156
+ if (hostedProxyMiddleware) {
157
+ return hostedProxyMiddleware(req, res, next);
158
+ }
118
159
  return res.redirect(302, url);
119
160
  });
120
161
  const printServerBannerAndShortcuts = () => {
@@ -196,19 +196,25 @@ export function runUninstall(inputPath, options) {
196
196
  pruneEmptyDir(resolve(cwd, relDir));
197
197
  }
198
198
  // 5. Clean up Chomp block in .gitignore and .git/info/exclude
199
+ const exactTrailingBlockRegex = /\r?\n# --- BEGIN CHOMP IGNORE ---\r?\n[\s\S]*?# --- END CHOMP IGNORE ---\r?\n?$/;
199
200
  const ignoreRegex = /\n?# --- BEGIN CHOMP IGNORE ---\r?\n[\s\S]*?# --- END CHOMP IGNORE ---\r?\n?/g;
200
201
  const gitignorePath = resolve(cwd, ".gitignore");
201
202
  if (existsSync(gitignorePath)) {
202
203
  const gitignoreContent = readFileSync(gitignorePath, "utf8");
203
204
  if (gitignoreContent.includes("# --- BEGIN CHOMP IGNORE ---")) {
204
- const cleaned = gitignoreContent.replace(ignoreRegex, "\n").trimEnd();
205
+ const cleaned = exactTrailingBlockRegex.test(gitignoreContent)
206
+ ? gitignoreContent.replace(exactTrailingBlockRegex, "")
207
+ : gitignoreContent.replace(ignoreRegex, "\n").trimEnd();
205
208
  if (cleaned.trim().length === 0) {
206
209
  unlinkSync(gitignorePath);
207
210
  removed.push(".gitignore");
208
211
  log(` ${ansi.green("✓")} Removed empty ${ansi.cyan(".gitignore")}`);
209
212
  }
210
213
  else {
211
- writeFileSync(gitignorePath, cleaned + "\n", "utf8");
214
+ const out = exactTrailingBlockRegex.test(gitignoreContent)
215
+ ? cleaned
216
+ : cleaned + "\n";
217
+ writeFileSync(gitignorePath, out, "utf8");
212
218
  updated.push(".gitignore");
213
219
  log(` ${ansi.green("✓")} Cleaned up ${ansi.cyan(".gitignore")}`);
214
220
  }
@@ -30,6 +30,11 @@ export interface HydratePortValvesResult {
30
30
  diagnosticCount: number;
31
31
  durationMs: number;
32
32
  }
33
+ /**
34
+ * Returns true when `<repoPath>/package.json` declares external `dependencies` or
35
+ * `devDependencies` while `<repoPath>/node_modules` is not installed on disk.
36
+ */
37
+ export declare function hasUninstalledExternalDependencies(repoPath: string): boolean;
33
38
  /**
34
39
  * Runs Speed 2 incremental TypeScript Port Valve verification on `graph` and persists
35
40
  * `L1_PORTS` (`source: "chomp-ports"`) cache rows to `storage`.
@@ -363,6 +363,123 @@ function isInsideReturnOrConciseBody(pos, ownerAstNode, sigNode) {
363
363
  walk(ownerAstNode);
364
364
  return insideReturn;
365
365
  }
366
+ const STDLIB_STATIC_RECEIVERS = new Set([
367
+ 'Object',
368
+ 'Array',
369
+ 'JSON',
370
+ 'Math',
371
+ 'Number',
372
+ 'String',
373
+ 'Boolean',
374
+ 'Promise',
375
+ 'Reflect',
376
+ 'Symbol',
377
+ 'RegExp',
378
+ 'Date',
379
+ 'Error',
380
+ 'Buffer',
381
+ 'Map',
382
+ 'Set',
383
+ 'WeakMap',
384
+ 'WeakSet',
385
+ 'Intl',
386
+ 'Atomics',
387
+ 'WebAssembly',
388
+ 'console',
389
+ ]);
390
+ const STDLIB_GLOBAL_FUNCTIONS = new Set([
391
+ 'parseInt',
392
+ 'parseFloat',
393
+ 'isNaN',
394
+ 'isFinite',
395
+ 'encodeURI',
396
+ 'decodeURI',
397
+ 'encodeURIComponent',
398
+ 'decodeURIComponent',
399
+ 'setTimeout',
400
+ 'clearTimeout',
401
+ 'setInterval',
402
+ 'clearInterval',
403
+ 'setImmediate',
404
+ 'clearImmediate',
405
+ 'queueMicrotask',
406
+ 'structuredClone',
407
+ ]);
408
+ function findInnermostCallOrJsxNode(pos, ownerAstNode, sf) {
409
+ let best = null;
410
+ const walk = (n) => {
411
+ if (pos < n.getFullStart() || pos > n.getEnd())
412
+ return;
413
+ if (ts.isCallExpression(n) ||
414
+ ts.isNewExpression(n) ||
415
+ ts.isJsxOpeningElement(n) ||
416
+ ts.isJsxSelfClosingElement(n)) {
417
+ const start = n.getStart(sf);
418
+ const end = n.getEnd();
419
+ if (pos >= start && pos <= end) {
420
+ if (!best || end - start <= best.getEnd() - best.getStart(sf)) {
421
+ best = n;
422
+ }
423
+ }
424
+ }
425
+ ts.forEachChild(n, walk);
426
+ };
427
+ walk(ownerAstNode);
428
+ return best;
429
+ }
430
+ function isStdlibOrGlobalCallNode(callNode) {
431
+ if (ts.isJsxOpeningElement(callNode) || ts.isJsxSelfClosingElement(callNode)) {
432
+ return false;
433
+ }
434
+ const expr = callNode.expression;
435
+ if (ts.isIdentifier(expr)) {
436
+ return STDLIB_GLOBAL_FUNCTIONS.has(expr.text);
437
+ }
438
+ if (ts.isPropertyAccessExpression(expr) && ts.isIdentifier(expr.expression)) {
439
+ return STDLIB_STATIC_RECEIVERS.has(expr.expression.text);
440
+ }
441
+ return false;
442
+ }
443
+ function extractCalleeShortName(callNode, sf) {
444
+ if (ts.isJsxOpeningElement(callNode) || ts.isJsxSelfClosingElement(callNode)) {
445
+ const raw = callNode.tagName.getText(sf).trim();
446
+ const parts = raw.split('.');
447
+ return parts[parts.length - 1] || null;
448
+ }
449
+ const expr = callNode.expression;
450
+ if (ts.isIdentifier(expr)) {
451
+ return expr.text;
452
+ }
453
+ if (ts.isPropertyAccessExpression(expr)) {
454
+ return expr.name.text;
455
+ }
456
+ return null;
457
+ }
458
+ /**
459
+ * Returns true when `<repoPath>/package.json` declares external `dependencies` or
460
+ * `devDependencies` while `<repoPath>/node_modules` is not installed on disk.
461
+ */
462
+ export function hasUninstalledExternalDependencies(repoPath) {
463
+ const absRepo = resolve(repoPath);
464
+ if (existsSync(resolve(absRepo, 'node_modules'))) {
465
+ return false;
466
+ }
467
+ const pkgJsonPath = resolve(absRepo, 'package.json');
468
+ if (!existsSync(pkgJsonPath)) {
469
+ return false;
470
+ }
471
+ try {
472
+ const parsed = JSON.parse(readFileSync(pkgJsonPath, 'utf8'));
473
+ const entries = [
474
+ ...Object.entries(parsed?.dependencies ?? {}),
475
+ ...Object.entries(parsed?.devDependencies ?? {}),
476
+ ];
477
+ return entries.some(([, ver]) => typeof ver === 'string' && !ver.trim().startsWith('workspace:'));
478
+ }
479
+ catch {
480
+ return false;
481
+ }
482
+ }
366
483
  function isInsideCallOrJsxExpression(pos, ownerAstNode) {
367
484
  let matched = false;
368
485
  const walk = (n) => {
@@ -489,6 +606,12 @@ export async function hydrateRepositoryPortValves(options) {
489
606
  durationMs: Date.now() - t0,
490
607
  };
491
608
  }
609
+ const contractNodeById = new Map();
610
+ for (const n of graph.nodes) {
611
+ if (n.type === 'CONTRACT') {
612
+ contractNodeById.set(n.id, n);
613
+ }
614
+ }
492
615
  const outEdgesBySource = new Map();
493
616
  for (const edge of graph.edges) {
494
617
  if (!edge.sourceId)
@@ -500,6 +623,7 @@ export async function hydrateRepositoryPortValves(options) {
500
623
  }
501
624
  list.push(edge);
502
625
  }
626
+ const suppressDiagnosticsForMissingDeps = hasUninstalledExternalDependencies(repoPath);
503
627
  const tsconfigCache = new Map();
504
628
  const fileHashCache = new Map();
505
629
  const contractsByGroup = new Map();
@@ -558,9 +682,13 @@ export async function hydrateRepositoryPortValves(options) {
558
682
  spanEnd: found.ownerAstNode.getEnd(),
559
683
  });
560
684
  }
561
- // Collect semantic diagnostics for this dirty file and bind port mismatches to their owning contract
685
+ // Collect semantic diagnostics for this dirty file and bind port mismatches to their owning contract.
686
+ // When external npm dependencies are declared in package.json without an installed node_modules/
687
+ // directory, skip semantic mismatch diagnostics to avoid unresolved external unknown/any cascades.
562
688
  const diagsByContractId = new Map();
563
- const fileDiagnostics = builder.getSemanticDiagnostics(sf);
689
+ const fileDiagnostics = suppressDiagnosticsForMissingDeps
690
+ ? []
691
+ : builder.getSemanticDiagnostics(sf);
564
692
  for (const d of fileDiagnostics) {
565
693
  if (d.start === undefined)
566
694
  continue;
@@ -601,17 +729,55 @@ export async function hydrateRepositoryPortValves(options) {
601
729
  .trim();
602
730
  let peerEntityId;
603
731
  if (kind === 'TS_CALL_MISMATCH') {
732
+ const callNode = findInnermostCallOrJsxNode(d.start, bestOwner.ownerAstNode, sf);
733
+ if (!callNode || isStdlibOrGlobalCallNode(callNode)) {
734
+ continue;
735
+ }
736
+ const callStartLine = sf.getLineAndCharacterOfPosition(callNode.getStart(sf)).line + 1;
737
+ const callEndLine = sf.getLineAndCharacterOfPosition(callNode.getEnd()).line + 1;
738
+ const calleeName = extractCalleeShortName(callNode, sf);
604
739
  const outEdges = outEdgesBySource.get(bestOwner.contract.id) ?? [];
605
- const matchingEdge = outEdges.find((e) => {
606
- if (!e.targetId)
740
+ const edgeMentionsCallee = (e) => {
741
+ if (!calleeName)
742
+ return true;
743
+ if (e.name.includes(calleeName))
744
+ return true;
745
+ const targetContract = e.targetId
746
+ ? contractNodeById.get(e.targetId)
747
+ : undefined;
748
+ return Boolean(targetContract?.name.includes(calleeName));
749
+ };
750
+ const contractEdgesInFile = outEdges.filter((e) => {
751
+ if (!e.targetId || !contractNodeById.has(e.targetId))
607
752
  return false;
608
753
  const eEvs = Array.isArray(e.evidence) ? e.evidence : [e.evidence];
609
- return eEvs.some((ev) => ev &&
610
- typeof ev.lineNumber === 'number' &&
611
- Math.abs(ev.lineNumber - diagLine) <= 2);
754
+ return eEvs.some((ev) => {
755
+ if (!ev || typeof ev.lineNumber !== 'number')
756
+ return false;
757
+ if (ev.filePath &&
758
+ normalizeSlash(ev.filePath.trim()) !== relFilePath) {
759
+ return false;
760
+ }
761
+ return (ev.lineNumber >= callStartLine - 1 &&
762
+ ev.lineNumber <= callEndLine + 1);
763
+ });
612
764
  });
613
- if (matchingEdge?.targetId) {
614
- peerEntityId = matchingEdge.targetId;
765
+ const exactLineMatch = contractEdgesInFile.find((e) => {
766
+ const eEvs = Array.isArray(e.evidence) ? e.evidence : [e.evidence];
767
+ return (eEvs.some((ev) => ev?.lineNumber === callStartLine) &&
768
+ edgeMentionsCallee(e));
769
+ }) ??
770
+ contractEdgesInFile.find((e) => {
771
+ const eEvs = Array.isArray(e.evidence) ? e.evidence : [e.evidence];
772
+ return eEvs.some((ev) => ev?.lineNumber === callStartLine);
773
+ }) ??
774
+ contractEdgesInFile.find((e) => edgeMentionsCallee(e));
775
+ if (exactLineMatch?.targetId) {
776
+ peerEntityId = exactLineMatch.targetId;
777
+ }
778
+ // Restrict TS_CALL_MISMATCH strictly to calls resolving to an extracted repository CONTRACT
779
+ if (!peerEntityId) {
780
+ continue;
615
781
  }
616
782
  }
617
783
  let bucket = diagsByContractId.get(bestOwner.contract.id);
@@ -79,7 +79,6 @@ export function cancelActivePortHydration(state) {
79
79
  }
80
80
  export function invalidateAllServerCaches(state) {
81
81
  state.layoutCache.clear();
82
- state.layoutInFlight.clear();
83
82
  state.loggedBoardRevisions.clear();
84
83
  state.baseGraphCache = null;
85
84
  state.baseGraphInFlight = null;
@@ -92,7 +91,6 @@ export function invalidateAllServerCaches(state) {
92
91
  export function invalidateAuthCachesOnly(state, activeDbPath) {
93
92
  clearDiskLayoutCache(activeDbPath);
94
93
  state.layoutCache.clear();
95
- state.layoutInFlight.clear();
96
94
  state.loggedBoardRevisions.clear();
97
95
  }
98
96
  export function getCurrentDbMtime(targetDbPath) {
@@ -0,0 +1,13 @@
1
+ import type { RequestHandler } from "express";
2
+ /**
3
+ * Proxies static Visualizer UI assets (`index.html`, `/_next/static/*`, icons, fonts)
4
+ * from `https://app.getchomp.dev` when running the published `@getchomp/cli` package
5
+ * (where `apps/web/out` is not bundled in the NPM tarball).
6
+ *
7
+ * Why this exists:
8
+ * WebKit / Safari strictly blocks `https://app.getchomp.dev` from calling `fetch()`
9
+ * against `http://127.0.0.1:<port>` as Mixed Content with no user setting to override it.
10
+ * Serving the hosted static UI transparently on `http://localhost:<port>` (`127.0.0.1:<port>`)
11
+ * lets Safari run 100% same-origin over HTTP while adding 0 KB to the `@getchomp/cli` tarball.
12
+ */
13
+ export declare function createHostedUiProxyMiddleware(hostedUiBaseUrl: string, fetchImpl?: typeof fetch): RequestHandler;
@@ -0,0 +1,137 @@
1
+ const MAX_CACHE_ENTRIES = 160;
2
+ const MUTABLE_TTL_MS = 60_000;
3
+ const PROXY_TIMEOUT_MS = 10_000;
4
+ /**
5
+ * Proxies static Visualizer UI assets (`index.html`, `/_next/static/*`, icons, fonts)
6
+ * from `https://app.getchomp.dev` when running the published `@getchomp/cli` package
7
+ * (where `apps/web/out` is not bundled in the NPM tarball).
8
+ *
9
+ * Why this exists:
10
+ * WebKit / Safari strictly blocks `https://app.getchomp.dev` from calling `fetch()`
11
+ * against `http://127.0.0.1:<port>` as Mixed Content with no user setting to override it.
12
+ * Serving the hosted static UI transparently on `http://localhost:<port>` (`127.0.0.1:<port>`)
13
+ * lets Safari run 100% same-origin over HTTP while adding 0 KB to the `@getchomp/cli` tarball.
14
+ */
15
+ export function createHostedUiProxyMiddleware(hostedUiBaseUrl, fetchImpl = fetch) {
16
+ let upstreamOrigin;
17
+ try {
18
+ upstreamOrigin = new URL(hostedUiBaseUrl.trim()).origin;
19
+ }
20
+ catch {
21
+ upstreamOrigin = "https://app.getchomp.dev";
22
+ }
23
+ const assetCache = new Map();
24
+ const setBoundedCache = (key, entry) => {
25
+ if (assetCache.has(key)) {
26
+ assetCache.delete(key);
27
+ }
28
+ else if (assetCache.size >= MAX_CACHE_ENTRIES) {
29
+ const oldestKey = assetCache.keys().next().value;
30
+ if (oldestKey !== undefined) {
31
+ assetCache.delete(oldestKey);
32
+ }
33
+ }
34
+ assetCache.set(key, entry);
35
+ };
36
+ const fetchUpstreamAsset = async (pathname) => {
37
+ const normalizedPath = pathname.startsWith("/") ? pathname : `/${pathname}`;
38
+ const immutable = normalizedPath.startsWith("/_next/static/");
39
+ const now = Date.now();
40
+ const cached = assetCache.get(normalizedPath);
41
+ if (cached &&
42
+ (cached.immutable || now - cached.cachedAt < MUTABLE_TTL_MS)) {
43
+ return cached;
44
+ }
45
+ let targetUrl;
46
+ try {
47
+ targetUrl = new URL(normalizedPath, `${upstreamOrigin}/`);
48
+ if (targetUrl.origin !== upstreamOrigin) {
49
+ return null;
50
+ }
51
+ }
52
+ catch {
53
+ return null;
54
+ }
55
+ const controller = new AbortController();
56
+ const timer = setTimeout(() => controller.abort(), PROXY_TIMEOUT_MS);
57
+ try {
58
+ const upstreamRes = await fetchImpl(targetUrl.toString(), {
59
+ method: "GET",
60
+ headers: {
61
+ "User-Agent": "chomp-cli-ui-proxy",
62
+ Accept: "*/*",
63
+ },
64
+ signal: controller.signal,
65
+ });
66
+ if (!upstreamRes.ok) {
67
+ if (upstreamRes.status === 404) {
68
+ return {
69
+ status: 404,
70
+ contentType: upstreamRes.headers.get("content-type") ||
71
+ "text/plain; charset=utf-8",
72
+ body: Buffer.from("Not Found", "utf-8"),
73
+ cachedAt: now,
74
+ immutable: false,
75
+ };
76
+ }
77
+ return cached ?? null;
78
+ }
79
+ const arrayBuf = await upstreamRes.arrayBuffer();
80
+ const entry = {
81
+ status: upstreamRes.status,
82
+ contentType: upstreamRes.headers.get("content-type") ||
83
+ "application/octet-stream",
84
+ body: Buffer.from(arrayBuf),
85
+ cachedAt: now,
86
+ immutable,
87
+ };
88
+ setBoundedCache(normalizedPath, entry);
89
+ return entry;
90
+ }
91
+ catch {
92
+ // Serve stale cached copy when briefly offline
93
+ return cached ?? null;
94
+ }
95
+ finally {
96
+ clearTimeout(timer);
97
+ }
98
+ };
99
+ return async (req, res) => {
100
+ const rawPath = req.path || "/";
101
+ if (rawPath === "/api" ||
102
+ rawPath.startsWith("/api/") ||
103
+ (req.method !== "GET" && req.method !== "HEAD")) {
104
+ return res.status(404).json({ error: "Not Found" });
105
+ }
106
+ if (rawPath.includes("..")) {
107
+ return res.status(400).send("Bad Request");
108
+ }
109
+ const normalizedPath = rawPath === "" ? "/" : rawPath;
110
+ let entry = await fetchUpstreamAsset(normalizedPath);
111
+ const hasExtension = /\/[^/]+\.[a-z0-9]{1,8}$/i.test(normalizedPath);
112
+ const acceptsHtml = (req.headers.accept ?? "").includes("text/html");
113
+ if (entry &&
114
+ entry.status === 404 &&
115
+ normalizedPath !== "/" &&
116
+ !hasExtension &&
117
+ acceptsHtml) {
118
+ entry = await fetchUpstreamAsset("/");
119
+ }
120
+ if (!entry) {
121
+ return res
122
+ .status(502)
123
+ .type("text/plain; charset=utf-8")
124
+ .send(`Unable to reach hosted Chomp Map assets at ${upstreamOrigin}. Check your internet connection and reload.`);
125
+ }
126
+ res.status(entry.status);
127
+ res.setHeader("Content-Type", entry.contentType);
128
+ res.setHeader("X-Content-Type-Options", "nosniff");
129
+ res.setHeader("Cache-Control", entry.immutable
130
+ ? "public, max-age=31536000, immutable"
131
+ : "no-cache");
132
+ if (req.method === "HEAD") {
133
+ return res.end();
134
+ }
135
+ return res.send(entry.body);
136
+ };
137
+ }
@@ -101,6 +101,17 @@ export function registerAuthAndSourceRoutes(app, state) {
101
101
  const { dbPath: activeDbPath } = getActiveUiTarget(state);
102
102
  invalidateAuthCachesOnly(state, activeDbPath);
103
103
  const redirectTarget = resolveSafeAuthReturnUrl(state, rawReturnTo, githubHandle);
104
+ if (req.query.mode === "popup") {
105
+ const safePayload = JSON.stringify({
106
+ type: "chomp:auth-success",
107
+ githubHandle: githubHandle ?? "",
108
+ redirectTarget,
109
+ }).replace(/</g, "\\u003c");
110
+ return res
111
+ .status(200)
112
+ .type("text/html; charset=utf-8")
113
+ .send(`<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Chomp — Signed In</title></head><body style="background:#0b0f15;color:#e8eef5;font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0"><p>Signed in — returning to Chomp Map…</p><script>(function(){var d=${safePayload};try{if(window.opener&&!window.opener.closed){window.opener.postMessage({type:d.type,githubHandle:d.githubHandle},"*");}}catch(_e){}try{window.close();}catch(_e){}setTimeout(function(){if(!document.hidden){window.location.replace(d.redirectTarget);}},350);})();</script></body></html>`);
114
+ }
104
115
  return res.redirect(302, redirectTarget);
105
116
  }
106
117
  catch (err) {
@@ -1,3 +1,8 @@
1
1
  import type { Express } from "express";
2
2
  import { type UiServerState } from "../graphLayoutState.js";
3
+ /**
4
+ * Coalesces concurrent layout computations for the same `cacheKey` onto a single
5
+ * in-flight Promise and removes the entry inside `finally` once settled.
6
+ */
7
+ export declare function runSingleFlightLayoutBuild<T>(inFlightMap: Map<string, Promise<T>>, cacheKey: string, factory: () => Promise<T>): Promise<T>;
3
8
  export declare function registerLayoutRoutes(app: Express, state: UiServerState): void;