@mulmoclaude/core 7.0.0 → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_rolldown_runtime = require("../rolldown-runtime-CmQyd0Gu.cjs");
3
3
  const require_root = require("../root-9lRFeXbm.cjs");
4
- const require_safe = require("../safe-D79sHxq1.cjs");
4
+ const require_withinRoot = require("../withinRoot-FLjxC8oP.cjs");
5
5
  const require_relPath = require("../relPath-CZiP2S_a.cjs");
6
6
  const require_artifacts_paths = require("../artifacts/paths.cjs");
7
7
  let node_fs = require("node:fs");
@@ -25,7 +25,7 @@ async function realpathIfPresent(absPath) {
25
25
  try {
26
26
  return await node_fs.promises.realpath(absPath);
27
27
  } catch (err) {
28
- if (require_safe.isEnoent(err)) return null;
28
+ if (require_withinRoot.isEnoent(err)) return null;
29
29
  throw err;
30
30
  }
31
31
  }
@@ -40,7 +40,7 @@ async function lstatIfPresent(absPath) {
40
40
  try {
41
41
  return await node_fs.promises.lstat(absPath, { bigint: true });
42
42
  } catch (err) {
43
- if (require_safe.isEnoent(err)) return null;
43
+ if (require_withinRoot.isEnoent(err)) return null;
44
44
  throw err;
45
45
  }
46
46
  }
@@ -48,7 +48,7 @@ async function openIfPresent(absPath, flags) {
48
48
  try {
49
49
  return await node_fs.promises.open(absPath, flags);
50
50
  } catch (err) {
51
- if (require_safe.isEnoent(err)) return null;
51
+ if (require_withinRoot.isEnoent(err)) return null;
52
52
  throw err;
53
53
  }
54
54
  }
@@ -266,14 +266,18 @@ exports.canonicalRoot = require_root.canonicalRoot;
266
266
  exports.createByPathFileOps = createByPathFileOps;
267
267
  exports.createFileVerifiedInScope = createFileVerifiedInScope;
268
268
  exports.existsAsFile = existsAsFile;
269
- exports.isEnoent = require_safe.isEnoent;
269
+ exports.isEnoent = require_withinRoot.isEnoent;
270
+ exports.isWithinRoot = require_withinRoot.isWithinRoot;
270
271
  exports.joinPosixRelPath = require_relPath.joinPosixRelPath;
271
272
  exports.openVerifiedWithinScope = openVerifiedWithinScope;
273
+ exports.readTextWithinRoot = require_withinRoot.readTextWithinRoot;
274
+ exports.readTextWithinRootSync = require_withinRoot.readTextWithinRootSync;
272
275
  exports.realpathIfPresent = realpathIfPresent;
276
+ exports.realpathSyncOrNull = require_withinRoot.realpathSyncOrNull;
273
277
  exports.resolveByPath = resolveByPath;
274
278
  exports.resolveExistingWithinRoot = resolveExistingWithinRoot;
275
279
  exports.resolveHtmlFileRequestPath = resolveHtmlFileRequestPath;
276
- exports.resolveWithinRoot = require_safe.resolveWithinRoot;
280
+ exports.resolveWithinRoot = require_withinRoot.resolveWithinRoot;
277
281
  exports.scopeRealpath = scopeRealpath;
278
282
  exports.toPosixRelPath = require_relPath.toPosixRelPath;
279
283
  exports.writeFileAtomic = require_root.writeFileAtomic;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["writeFileAtomic","constants","promises","isEnoent","path","randomBytes","renameWithWindowsRetry","classifyFilePath","path","realpath","fsStat","readFile","writeFileAtomic","path"],"sources":["../../src/files/json.ts","../../src/files/verified.ts","../../src/files/byPath.ts","../../src/files/htmlFileRequest.ts"],"sourcesContent":["import { writeFileAtomic, type WriteAtomicOptions } from \"./atomic.js\";\n\nconst JSON_INDENT = 2;\n\n/** Atomic JSON write (2-space indent) — serialize then write through the atomic\n * tmp-file + rename seam so a reader never sees a half-written document. */\nexport async function writeJsonAtomic(filePath: string, data: unknown, opts: WriteAtomicOptions = {}): Promise<void> {\n await writeFileAtomic(filePath, JSON.stringify(data, null, JSON_INDENT), opts);\n}\n","// Containment that survives a path swapped between the check and the use (#3573). Node fs has no\n// openat, so a read opens first and then proves the handle is the in-root file, and a write\n// verifies its staging file before renaming within that same directory. See\n// plans/fix-3573-verified-open.md for what is closed and what stays best-effort.\n\nimport { constants, promises, type BigIntStats } from \"node:fs\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\nimport { renameWithWindowsRetry } from \"./atomic.js\";\nimport { isEnoent } from \"./safe.js\";\n\n// O_NOFOLLOW / O_NONBLOCK are undefined on Windows; a FIFO planted in the workspace must not block the read.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);\nconst CREATE_FLAGS = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0);\nconst STAGING_SUFFIX_BYTES = 6;\n\n/** Test seams at the points where a real race would swap a path. */\nexport interface VerifiedFileHooks {\n beforeOpen?: () => Promise<void>;\n afterOpen?: () => Promise<void>;\n beforeRename?: () => Promise<void>;\n}\n\n/** Only a missing path reads as null; EACCES, ELOOP, ENOTDIR … propagate. */\nexport async function realpathIfPresent(absPath: string): Promise<string | null> {\n try {\n return await promises.realpath(absPath);\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\nconst isWithin = (rootReal: string, candidateReal: string): boolean => candidateReal === rootReal || candidateReal.startsWith(rootReal + path.sep);\n\n/** Real location of `relative` (host-native) if it exists inside `rootReal`; null when missing or outside. `rootReal` MUST be a realpath. */\nexport async function resolveExistingWithinRoot(rootReal: string, relative: string): Promise<string | null> {\n const candidateReal = await realpathIfPresent(path.resolve(rootReal, relative));\n return candidateReal !== null && isWithin(rootReal, candidateReal) ? candidateReal : null;\n}\n\nconst sameFile = (onDisk: BigIntStats, opened: BigIntStats): boolean => onDisk.dev === opened.dev && onDisk.ino === opened.ino;\n\nasync function lstatIfPresent(absPath: string): Promise<BigIntStats | null> {\n try {\n return await promises.lstat(absPath, { bigint: true });\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\nasync function openIfPresent(absPath: string, flags: number): Promise<FileHandle | null> {\n try {\n return await promises.open(absPath, flags);\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\n/** A scope folder under a trusted anchor. `trustedReal` MUST be a realpath that the party being defended\n * against cannot replace (the workspace: in Docker it is the mount root). The scope is re-resolved under\n * it at every check, so a scope replaced by a link out is refused; a real directory moved into the\n * scope's place from inside the anchor is simply the scope from then on. */\nexport interface VerifiedScope {\n trustedReal: string;\n scopeWithinTrusted: string;\n}\n\n/** The scope's realpath if it exists inside the anchor now; null when absent or led outside. */\nexport const scopeRealpath = async (scope: VerifiedScope): Promise<string | null> => resolveExistingWithinRoot(scope.trustedReal, scope.scopeWithinTrusted);\n\ninterface BoundScope {\n scope: VerifiedScope;\n anchorIdentity: BigIntStats;\n}\n\nasync function bindScope(scope: VerifiedScope): Promise<BoundScope | null> {\n const anchorIdentity = await lstatIfPresent(scope.trustedReal);\n return anchorIdentity === null ? null : { scope, anchorIdentity };\n}\n\n/** The scope's realpath at this moment, provided the anchor is still the directory bound at the start. */\nasync function scopeRealNow(bound: BoundScope): Promise<string | null> {\n const anchorNow = await lstatIfPresent(bound.scope.trustedReal);\n return anchorNow !== null && sameFile(anchorNow, bound.anchorIdentity) ? scopeRealpath(bound.scope) : null;\n}\n\nasync function isInScopeFile(bound: BoundScope, candidateReal: string, handle: FileHandle): Promise<boolean> {\n const scopeReal = await scopeRealNow(bound);\n const again = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, candidateReal);\n if (again === null) return false;\n const onDisk = await lstatIfPresent(again);\n return onDisk !== null && sameFile(onDisk, await handle.stat({ bigint: true }));\n}\n\n/** Opens `relative` under the scope for reading and proves, after opening, that the handle is the file\n * the scope holds now. Null when missing, outside, or swapped during the call. The caller owns the handle. */\nexport async function openVerifiedWithinScope(scope: VerifiedScope, relative: string, hooks: VerifiedFileHooks = {}): Promise<FileHandle | null> {\n const bound = await bindScope(scope);\n const scopeReal = bound === null ? null : await scopeRealNow(bound);\n const candidateReal = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, relative);\n if (bound === null || candidateReal === null) return null;\n await hooks.beforeOpen?.();\n const handle = await openIfPresent(candidateReal, READ_FLAGS);\n if (handle === null) return null;\n try {\n await hooks.afterOpen?.();\n if (await isInScopeFile(bound, candidateReal, handle)) return handle;\n } catch (err) {\n await handle.close();\n throw err;\n }\n await handle.close();\n return null;\n}\n\n/** The directory of a file this call created, re-resolved, if it is inside the scope now and holds exactly the opened file. */\nasync function verifiedCreatedFileDir(bound: BoundScope, dirReal: string, staging: string, handle: FileHandle): Promise<string | null> {\n const scopeReal = await scopeRealNow(bound);\n const dirAgain = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, dirReal);\n if (dirAgain === null) return null;\n const entry = await lstatIfPresent(path.join(dirAgain, staging));\n return entry !== null && sameFile(entry, await handle.stat({ bigint: true })) ? dirAgain : null;\n}\n\nasync function writeStaging(bound: BoundScope, dirReal: string, staging: string, content: string | Uint8Array, hooks: VerifiedFileHooks): Promise<string> {\n await hooks.beforeOpen?.();\n const handle = await promises.open(path.join(dirReal, staging), CREATE_FLAGS);\n try {\n await hooks.afterOpen?.();\n const stagingDir = await verifiedCreatedFileDir(bound, dirReal, staging, handle);\n if (stagingDir === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);\n await handle.writeFile(content);\n return stagingDir;\n } finally {\n await handle.close();\n }\n}\n\n// `leaf` is joined to a verified directory, so a separator or `..` in it would step out of what was verified.\nconst assertSingleName = (leaf: string): void => {\n if (leaf === \"\" || leaf === \".\" || leaf === \"..\" || path.basename(leaf) !== leaf || leaf.includes(\"/\")) {\n throw new Error(`refusing to write: ${JSON.stringify(leaf)} is not a single file name`);\n }\n};\n\nconst stagingNameFor = (leaf: string): string => `${leaf}.${randomBytes(STAGING_SUFFIX_BYTES).toString(\"hex\")}.tmp`;\n\nconst removeQuietly = async (absPath: string): Promise<void> => {\n await promises.unlink(absPath).catch(() => {});\n};\n\n// The rename's source is the verified staging file under its random name, so it succeeds only where that\n// name reaches it: the verified directory (wherever moved since), or a directory the actor could already\n// write and planted the name in. No renameat in Node fs; see plans/fix-3573-verified-open.md.\nasync function renameIntoPlace(stagingDir: string, staging: string, leaf: string, hooks: VerifiedFileHooks): Promise<void> {\n try {\n await hooks.beforeRename?.();\n await renameWithWindowsRetry(path.join(stagingDir, staging), path.join(stagingDir, leaf));\n } catch (err) {\n await removeQuietly(path.join(stagingDir, staging));\n throw err;\n }\n}\n\n/** Atomic write of `leaf` into `dirReal` (an already-confined directory of the scope). The staging file is\n * verified to sit inside the scope before any byte is written, and a parent swapped for a link mid-call\n * makes the write fail — unless the link's target is a directory the actor could already write. */\nexport async function writeFileVerifiedInScope(\n scope: VerifiedScope,\n dirReal: string,\n leaf: string,\n content: string | Uint8Array,\n hooks: VerifiedFileHooks = {},\n): Promise<void> {\n assertSingleName(leaf);\n const bound = await bindScope(scope);\n if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);\n const staging = stagingNameFor(leaf);\n const stagingDir = await writeStaging(bound, dirReal, staging, content, hooks).catch(async (err: unknown) => {\n await removeQuietly(path.join(dirReal, staging));\n throw err;\n });\n await renameIntoPlace(stagingDir, staging, leaf, hooks);\n}\n\n/** Exclusive create of `leaf` in `dirReal` (an already-confined directory of the scope): throws EEXIST when `leaf`\n * exists, as `writeFile(…, { flag: \"wx\" })` does. The new file is verified to sit inside the scope before any byte is\n * written, and the bytes go through its handle. A parent swapped for a link before the create leaves an empty file\n * in the link's target and makes the call fail; it is not removed, because by then the name may be someone else's. */\nexport async function createFileVerifiedInScope(\n scope: VerifiedScope,\n dirReal: string,\n leaf: string,\n content: string | Uint8Array,\n hooks: VerifiedFileHooks = {},\n): Promise<void> {\n assertSingleName(leaf);\n const bound = await bindScope(scope);\n if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);\n await hooks.beforeOpen?.();\n const handle = await promises.open(path.join(dirReal, leaf), CREATE_FLAGS);\n try {\n await hooks.afterOpen?.();\n if ((await verifiedCreatedFileDir(bound, dirReal, leaf, handle)) === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);\n await handle.writeFile(content);\n } finally {\n await handle.close();\n }\n}\n","// Read / overwrite files the TOOL CALL named, rather than files the app minted.\n// `presentDocument(path)` / `presentHtml(path)` open a document that already\n// exists — a repo's `README.md`, `docs/report.html`, an absolute path — and the\n// user's edits in the view overwrite it in place.\n//\n// Shared by both hosts (MulmoClaude's `server/utils/files/by-path.ts` and\n// MulmoTerminal's backend bind their own workspace root to it), because the\n// judgement of what a `path` argument may reach is exactly the thing that must\n// not drift between them: a host that accepts what the other refuses turns one\n// tool call into two different behaviours.\n//\n// The rules:\n// - `classifyFilePath` (also what the plugins' `path` gate calls) decides the\n// shape: right extension, no NUL, no `.` / `..` / empty segment. That\n// lexical guard is what stops a vetted path from being re-pointed later.\n// - relative paths resolve against the injected root; absolute paths are taken\n// as given. There is deliberately NO containment check — opening a file\n// outside the workspace is the documented purpose of the `path` form. The\n// agent can already read and write those files directly; what is new is that\n// the view can too.\n// - a value that is absolute only under ANOTHER platform's rules is refused:\n// `classifyFilePath` recognises `C:\\proj\\x.md` everywhere (the value may\n// come from a remote host), but on POSIX `path.resolve(\"C:/proj/x.md\")`\n// lands under the process cwd — a file nobody named.\n// - reads and writes require a REGULAR FILE, judged through `realpath` so a\n// symlink is assessed by what it points at and a directory named `x.md`\n// cannot masquerade as a document.\n// - `write` overwrites only. Neither tool creates a file at a caller-supplied\n// path, so a write to a path that does not exist means the view is stale or\n// the path was wrong — refusing keeps a typo from scattering files.\n// - `readDir` and `unlink` are refused outright: this capability exists to\n// read and re-save ONE named document, not to browse or delete.\n\nimport { readFile, realpath, stat as fsStat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { classifyFilePath } from \"../artifacts/paths.js\";\nimport { writeFileAtomic } from \"./atomic.js\";\n\nexport const MARKDOWN_EXTENSIONS = [\".md\"] as const;\nexport const HTML_EXTENSIONS = [\".html\", \".htm\"] as const;\n\n/** Minimal structural echo of gui-chat-protocol's `FileOps`. Declared here\n * rather than imported so core keeps no dependency on the protocol package;\n * a host assigns the result straight to a `FileOps`-typed capability. */\nexport interface ByPathFileOps {\n read: (rel: string) => Promise<string>;\n readBytes: (rel: string) => Promise<Uint8Array>;\n write: (rel: string, content: string | Uint8Array) => Promise<void>;\n readDir: (rel: string) => Promise<string[]>;\n stat: (rel: string) => Promise<{ mtimeMs: number; size: number }>;\n exists: (rel: string) => Promise<boolean>;\n unlink: (rel: string) => Promise<void>;\n}\n\n/** Absolute on-disk path for a caller-supplied path with one of `extensions`,\n * or null when the value is not usable on this platform. */\nexport function resolveByPath(root: string, value: string, extensions: readonly string[]): string | null {\n const kind = classifyFilePath(value, extensions);\n if (kind === null) return null;\n if (kind === \"relative\") return path.resolve(root, value);\n return path.isAbsolute(value) ? path.resolve(value) : null;\n}\n\n/** True when the path names an existing regular file. */\nexport async function existsAsFile(root: string, value: string, extensions: readonly string[]): Promise<boolean> {\n const absPath = resolveByPath(root, value, extensions);\n return absPath === null ? false : (await regularFileTarget(absPath)) !== null;\n}\n\nexport interface ByPathOptions {\n /** The root relative values resolve against, read PER CALL — hosts inject the\n * workspace after these ops are already bound into plugin closures. */\n rootFor: () => string;\n extensions: readonly string[];\n}\n\nfunction resolveOrThrow({ rootFor, extensions }: ByPathOptions, value: string): string {\n const absPath = resolveByPath(rootFor(), value, extensions);\n if (absPath === null) throw new Error(`invalid path: ${value}`);\n return absPath;\n}\n\n/** The canonical REGULAR FILE a path names, or null when it is missing, is a\n * directory, or is anything else (a FIFO would block a read forever).\n * Resolved through `realpath` so a symlink is judged — and later written — by\n * what it points at: `writeFileAtomic` renames a temp file into place, which\n * through a link would replace the link itself and leave the real document\n * untouched. */\nasync function regularFileTarget(absPath: string): Promise<string | null> {\n try {\n const target = await realpath(absPath);\n return (await fsStat(target)).isFile() ? target : null;\n } catch {\n return null;\n }\n}\n\n/** The file to read or overwrite. Throws rather than creating: neither tool\n * ever writes to a path that does not already hold a document. */\nasync function existingFileFor(options: ByPathOptions, rel: string): Promise<string> {\n const target = await regularFileTarget(resolveOrThrow(options, rel));\n if (target === null) throw new Error(`no file exists at ${rel}`);\n return target;\n}\n\n/** Browsing and deleting are NOT part of this capability: it exists so a view\n * can read and re-save the ONE document the tool call named, not to enumerate\n * a directory it was never pointed at or remove a file. */\nfunction unsupported(operation: string): () => Promise<never> {\n return () => Promise.reject(new Error(`byPath FileOps does not support ${operation}`));\n}\n\n/** FileOps over caller-supplied paths — what a host injects as `files.byPath`\n * for plugins whose `path` argument may leave their artifact directory. Every\n * method takes the same value the tool call carried, not a scope-relative one. */\nexport function createByPathFileOps(options: ByPathOptions): ByPathFileOps {\n return {\n read: async (rel) => readFile(await existingFileFor(options, rel), \"utf-8\"),\n readBytes: async (rel) => {\n const buf = await readFile(await existingFileFor(options, rel));\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n },\n write: async (rel, content) => writeFileAtomic(await existingFileFor(options, rel), content),\n readDir: unsupported(\"readDir\"),\n stat: async (rel) => {\n const { mtimeMs, size } = await fsStat(resolveOrThrow(options, rel));\n return { mtimeMs, size };\n },\n exists: (rel) => existsAsFile(options.rootFor(), rel, options.extensions),\n unlink: unsupported(\"unlink\"),\n };\n}\n","// Server half of the `/htmlfile` scheme (client half: `src/config/htmlFileUrl.ts`).\n// Turns a request path into the absolute file to serve, or null.\n//\n// Shared by both hosts so the URL the View asks for and the file a host resolves\n// cannot drift apart.\n//\n// This mount is deliberately NOT contained to a root: presentHtml's `path` form\n// may name any HTML page on disk, and serving it is the point. What still holds:\n//\n// - only `ws` (workspace-relative) and `abs` (absolute) scopes exist; anything\n// else 404s, so a bare `/htmlfile/etc/passwd` is not a path at all.\n// - no `.` / `..` / empty segment survives, so a vetted URL cannot be\n// re-pointed by traversal, and no dotfile segment is reachable (same policy\n// as `resolveArtifactRequestPath`, which the artifact mounts share).\n// - extension allowlist, realpath and regular-file checks stay with the host's\n// mount, which is also where the CSP header and rate limit are applied.\n//\n// The trust boundary is whatever the host applies to its `/artifacts/html`\n// mount — in MulmoClaude, the loopback-only listener plus `requireSameOrigin`\n// (bearer auth does not apply outside `/api`, and an iframe `src` request cannot\n// carry an Authorization header anyway).\n\nimport path from \"node:path\";\n// The scope constants are re-declared rather than imported: core must not\n// depend on a plugin (dependencies flow the other way). `html-plugin`'s\n// `htmlFileUrl` builds the URLs these parse, and the round-trip test in the host\n// is what keeps the two halves honest.\nconst HTML_FILE_SCOPE_WORKSPACE = \"ws\";\nconst HTML_FILE_SCOPE_ABSOLUTE = \"abs\";\n\nconst WINDOWS_DRIVE_ONLY_RE = /^[a-zA-Z]:$/;\n\nfunction decodeSegments(reqPath: string): string[] | null {\n let decoded: string[];\n try {\n decoded = reqPath\n .replace(/^\\//, \"\")\n .split(\"/\")\n .map((segment) => decodeURIComponent(segment));\n } catch {\n // Malformed escape (`%ZZ`) — fail closed rather than bubbling a URIError.\n return null;\n }\n // Segmentation happens on the ENCODED path, so a `%2F` (or `%5C`) becomes a\n // separator only after this decode — `a%2F..%2F..%2Ftmp%2Fx.html` would arrive\n // as one segment that the `..` check below never sees, and then split apart\n // inside `path.resolve`. A decoded segment that still contains a separator is\n // never legitimate here, so refuse it.\n return decoded.some((segment) => segment.includes(\"/\") || segment.includes(\"\\\\\")) ? null : decoded;\n}\n\n/** Absolute path for a `/htmlfile/<scope>/<segments…>` request, or null when\n * the URL is malformed, uses an unknown scope, or touches a `.` / `..` /\n * dotfile segment. `workspaceRoot` should already be a realpath. */\nexport function resolveHtmlFileRequestPath(workspaceRoot: string, reqPath: string): string | null {\n const decoded = decodeSegments(reqPath);\n if (decoded === null || decoded.length < 2) return null;\n const [scope, ...rest] = decoded;\n if (scope !== HTML_FILE_SCOPE_WORKSPACE && scope !== HTML_FILE_SCOPE_ABSOLUTE) return null;\n const [firstRest] = rest;\n if (firstRest === undefined) return null;\n if (rest.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\" || segment.startsWith(\".\") || segment.includes(\"\\0\"))) {\n return null;\n }\n if (scope === HTML_FILE_SCOPE_WORKSPACE) return path.resolve(workspaceRoot, ...rest);\n // `abs/C:/proj/page.html` — the drive letter arrives as its own segment, so\n // rejoin it before resolving; everything else is rooted at `/`.\n const candidate = WINDOWS_DRIVE_ONLY_RE.test(firstRest) ? rest.join(\"/\") : `/${rest.join(\"/\")}`;\n // Only THIS platform's `path` can say whether that is really absolute: on\n // POSIX, `path.resolve(\"C:/proj/page.html\")` would land under the process cwd\n // rather than at any drive, silently serving the wrong file. Refuse instead.\n return path.isAbsolute(candidate) ? path.resolve(candidate) : null;\n}\n"],"mappings":";;;;;;;;;;;;AAEA,IAAM,cAAc;;;AAIpB,eAAsB,gBAAgB,UAAkB,MAAe,OAA2B,CAAC,GAAkB;CACnH,MAAMA,aAAAA,gBAAgB,UAAU,KAAK,UAAU,MAAM,MAAM,WAAW,GAAG,IAAI;AAC/E;;ACKA,IAAM,aAAaC,QAAAA,UAAU,YAAYA,QAAAA,UAAU,cAAc,MAAMA,QAAAA,UAAU,cAAc;AAC/F,IAAM,eAAeA,QAAAA,UAAU,WAAWA,QAAAA,UAAU,UAAUA,QAAAA,UAAU,UAAUA,QAAAA,UAAU,cAAc;AAC1G,IAAM,uBAAuB;;AAU7B,eAAsB,kBAAkB,SAAyC;CAC/E,IAAI;EACF,OAAO,MAAMC,QAAAA,SAAS,SAAS,OAAO;CACxC,SAAS,KAAK;EACZ,IAAIC,aAAAA,SAAS,GAAG,GAAG,OAAO;EAC1B,MAAM;CACR;AACF;AAEA,IAAM,YAAY,UAAkB,kBAAmC,kBAAkB,YAAY,cAAc,WAAW,WAAWC,UAAAA,QAAK,GAAG;;AAGjJ,eAAsB,0BAA0B,UAAkB,UAA0C;CAC1G,MAAM,gBAAgB,MAAM,kBAAkBA,UAAAA,QAAK,QAAQ,UAAU,QAAQ,CAAC;CAC9E,OAAO,kBAAkB,QAAQ,SAAS,UAAU,aAAa,IAAI,gBAAgB;AACvF;AAEA,IAAM,YAAY,QAAqB,WAAiC,OAAO,QAAQ,OAAO,OAAO,OAAO,QAAQ,OAAO;AAE3H,eAAe,eAAe,SAA8C;CA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AAC7F;;;;AAKA,SAAgB,2BAA2B,eAAuB,SAAgC;CAChG,MAAM,UAAU,eAAe,OAAO;CACtC,IAAI,YAAY,QAAQ,QAAQ,SAAS,GAAG,OAAO;CACnD,MAAM,CAAC,OAAO,GAAG,QAAQ;CACzB,IAAI,UAAU,6BAA6B,UAAU,0BAA0B,OAAO;CACtF,MAAM,CAAC,aAAa;CACpB,IAAI,cAAc,KAAA,GAAW,OAAO;CACpC,IAAI,KAAK,MAAM,YAAY,YAAY,MAAM,YAAY,OAAO,YAAY,QAAQ,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,IAAI,CAAC,GACnI,OAAO;CAET,IAAI,UAAU,2BAA2B,OAAOG,UAAAA,QAAK,QAAQ,eAAe,GAAG,IAAI;CAGnF,MAAM,YAAY,sBAAsB,KAAK,SAAS,IAAI,KAAK,KAAK,GAAG,IAAI,IAAI,KAAK,KAAK,GAAG;CAI5F,OAAOA,UAAAA,QAAK,WAAW,SAAS,IAAIA,UAAAA,QAAK,QAAQ,SAAS,IAAI;AAChE"}
1
+ {"version":3,"file":"index.cjs","names":["writeFileAtomic","constants","promises","isEnoent","path","randomBytes","renameWithWindowsRetry","classifyFilePath","path","realpath","fsStat","readFile","writeFileAtomic","path"],"sources":["../../src/files/json.ts","../../src/files/verified.ts","../../src/files/byPath.ts","../../src/files/htmlFileRequest.ts"],"sourcesContent":["import { writeFileAtomic, type WriteAtomicOptions } from \"./atomic.js\";\n\nconst JSON_INDENT = 2;\n\n/** Atomic JSON write (2-space indent) — serialize then write through the atomic\n * tmp-file + rename seam so a reader never sees a half-written document. */\nexport async function writeJsonAtomic(filePath: string, data: unknown, opts: WriteAtomicOptions = {}): Promise<void> {\n await writeFileAtomic(filePath, JSON.stringify(data, null, JSON_INDENT), opts);\n}\n","// Containment that survives a path swapped between the check and the use (#3573). Node fs has no\n// openat, so a read opens first and then proves the handle is the in-root file, and a write\n// verifies its staging file before renaming within that same directory. See\n// plans/fix-3573-verified-open.md for what is closed and what stays best-effort.\n\nimport { constants, promises, type BigIntStats } from \"node:fs\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\nimport { renameWithWindowsRetry } from \"./atomic.js\";\nimport { isEnoent } from \"./safe.js\";\n\n// O_NOFOLLOW / O_NONBLOCK are undefined on Windows; a FIFO planted in the workspace must not block the read.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);\nconst CREATE_FLAGS = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0);\nconst STAGING_SUFFIX_BYTES = 6;\n\n/** Test seams at the points where a real race would swap a path. */\nexport interface VerifiedFileHooks {\n beforeOpen?: () => Promise<void>;\n afterOpen?: () => Promise<void>;\n beforeRename?: () => Promise<void>;\n}\n\n/** Only a missing path reads as null; EACCES, ELOOP, ENOTDIR … propagate. */\nexport async function realpathIfPresent(absPath: string): Promise<string | null> {\n try {\n return await promises.realpath(absPath);\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\nconst isWithin = (rootReal: string, candidateReal: string): boolean => candidateReal === rootReal || candidateReal.startsWith(rootReal + path.sep);\n\n/** Real location of `relative` (host-native) if it exists inside `rootReal`; null when missing or outside. `rootReal` MUST be a realpath. */\nexport async function resolveExistingWithinRoot(rootReal: string, relative: string): Promise<string | null> {\n const candidateReal = await realpathIfPresent(path.resolve(rootReal, relative));\n return candidateReal !== null && isWithin(rootReal, candidateReal) ? candidateReal : null;\n}\n\nconst sameFile = (onDisk: BigIntStats, opened: BigIntStats): boolean => onDisk.dev === opened.dev && onDisk.ino === opened.ino;\n\nasync function lstatIfPresent(absPath: string): Promise<BigIntStats | null> {\n try {\n return await promises.lstat(absPath, { bigint: true });\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\nasync function openIfPresent(absPath: string, flags: number): Promise<FileHandle | null> {\n try {\n return await promises.open(absPath, flags);\n } catch (err) {\n if (isEnoent(err)) return null;\n throw err;\n }\n}\n\n/** A scope folder under a trusted anchor. `trustedReal` MUST be a realpath that the party being defended\n * against cannot replace (the workspace: in Docker it is the mount root). The scope is re-resolved under\n * it at every check, so a scope replaced by a link out is refused; a real directory moved into the\n * scope's place from inside the anchor is simply the scope from then on. */\nexport interface VerifiedScope {\n trustedReal: string;\n scopeWithinTrusted: string;\n}\n\n/** The scope's realpath if it exists inside the anchor now; null when absent or led outside. */\nexport const scopeRealpath = async (scope: VerifiedScope): Promise<string | null> => resolveExistingWithinRoot(scope.trustedReal, scope.scopeWithinTrusted);\n\ninterface BoundScope {\n scope: VerifiedScope;\n anchorIdentity: BigIntStats;\n}\n\nasync function bindScope(scope: VerifiedScope): Promise<BoundScope | null> {\n const anchorIdentity = await lstatIfPresent(scope.trustedReal);\n return anchorIdentity === null ? null : { scope, anchorIdentity };\n}\n\n/** The scope's realpath at this moment, provided the anchor is still the directory bound at the start. */\nasync function scopeRealNow(bound: BoundScope): Promise<string | null> {\n const anchorNow = await lstatIfPresent(bound.scope.trustedReal);\n return anchorNow !== null && sameFile(anchorNow, bound.anchorIdentity) ? scopeRealpath(bound.scope) : null;\n}\n\nasync function isInScopeFile(bound: BoundScope, candidateReal: string, handle: FileHandle): Promise<boolean> {\n const scopeReal = await scopeRealNow(bound);\n const again = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, candidateReal);\n if (again === null) return false;\n const onDisk = await lstatIfPresent(again);\n return onDisk !== null && sameFile(onDisk, await handle.stat({ bigint: true }));\n}\n\n/** Opens `relative` under the scope for reading and proves, after opening, that the handle is the file\n * the scope holds now. Null when missing, outside, or swapped during the call. The caller owns the handle. */\nexport async function openVerifiedWithinScope(scope: VerifiedScope, relative: string, hooks: VerifiedFileHooks = {}): Promise<FileHandle | null> {\n const bound = await bindScope(scope);\n const scopeReal = bound === null ? null : await scopeRealNow(bound);\n const candidateReal = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, relative);\n if (bound === null || candidateReal === null) return null;\n await hooks.beforeOpen?.();\n const handle = await openIfPresent(candidateReal, READ_FLAGS);\n if (handle === null) return null;\n try {\n await hooks.afterOpen?.();\n if (await isInScopeFile(bound, candidateReal, handle)) return handle;\n } catch (err) {\n await handle.close();\n throw err;\n }\n await handle.close();\n return null;\n}\n\n/** The directory of a file this call created, re-resolved, if it is inside the scope now and holds exactly the opened file. */\nasync function verifiedCreatedFileDir(bound: BoundScope, dirReal: string, staging: string, handle: FileHandle): Promise<string | null> {\n const scopeReal = await scopeRealNow(bound);\n const dirAgain = scopeReal === null ? null : await resolveExistingWithinRoot(scopeReal, dirReal);\n if (dirAgain === null) return null;\n const entry = await lstatIfPresent(path.join(dirAgain, staging));\n return entry !== null && sameFile(entry, await handle.stat({ bigint: true })) ? dirAgain : null;\n}\n\nasync function writeStaging(bound: BoundScope, dirReal: string, staging: string, content: string | Uint8Array, hooks: VerifiedFileHooks): Promise<string> {\n await hooks.beforeOpen?.();\n const handle = await promises.open(path.join(dirReal, staging), CREATE_FLAGS);\n try {\n await hooks.afterOpen?.();\n const stagingDir = await verifiedCreatedFileDir(bound, dirReal, staging, handle);\n if (stagingDir === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);\n await handle.writeFile(content);\n return stagingDir;\n } finally {\n await handle.close();\n }\n}\n\n// `leaf` is joined to a verified directory, so a separator or `..` in it would step out of what was verified.\nconst assertSingleName = (leaf: string): void => {\n if (leaf === \"\" || leaf === \".\" || leaf === \"..\" || path.basename(leaf) !== leaf || leaf.includes(\"/\")) {\n throw new Error(`refusing to write: ${JSON.stringify(leaf)} is not a single file name`);\n }\n};\n\nconst stagingNameFor = (leaf: string): string => `${leaf}.${randomBytes(STAGING_SUFFIX_BYTES).toString(\"hex\")}.tmp`;\n\nconst removeQuietly = async (absPath: string): Promise<void> => {\n await promises.unlink(absPath).catch(() => {});\n};\n\n// The rename's source is the verified staging file under its random name, so it succeeds only where that\n// name reaches it: the verified directory (wherever moved since), or a directory the actor could already\n// write and planted the name in. No renameat in Node fs; see plans/fix-3573-verified-open.md.\nasync function renameIntoPlace(stagingDir: string, staging: string, leaf: string, hooks: VerifiedFileHooks): Promise<void> {\n try {\n await hooks.beforeRename?.();\n await renameWithWindowsRetry(path.join(stagingDir, staging), path.join(stagingDir, leaf));\n } catch (err) {\n await removeQuietly(path.join(stagingDir, staging));\n throw err;\n }\n}\n\n/** Atomic write of `leaf` into `dirReal` (an already-confined directory of the scope). The staging file is\n * verified to sit inside the scope before any byte is written, and a parent swapped for a link mid-call\n * makes the write fail — unless the link's target is a directory the actor could already write. */\nexport async function writeFileVerifiedInScope(\n scope: VerifiedScope,\n dirReal: string,\n leaf: string,\n content: string | Uint8Array,\n hooks: VerifiedFileHooks = {},\n): Promise<void> {\n assertSingleName(leaf);\n const bound = await bindScope(scope);\n if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);\n const staging = stagingNameFor(leaf);\n const stagingDir = await writeStaging(bound, dirReal, staging, content, hooks).catch(async (err: unknown) => {\n await removeQuietly(path.join(dirReal, staging));\n throw err;\n });\n await renameIntoPlace(stagingDir, staging, leaf, hooks);\n}\n\n/** Exclusive create of `leaf` in `dirReal` (an already-confined directory of the scope): throws EEXIST when `leaf`\n * exists, as `writeFile(…, { flag: \"wx\" })` does. The new file is verified to sit inside the scope before any byte is\n * written, and the bytes go through its handle. A parent swapped for a link before the create leaves an empty file\n * in the link's target and makes the call fail; it is not removed, because by then the name may be someone else's. */\nexport async function createFileVerifiedInScope(\n scope: VerifiedScope,\n dirReal: string,\n leaf: string,\n content: string | Uint8Array,\n hooks: VerifiedFileHooks = {},\n): Promise<void> {\n assertSingleName(leaf);\n const bound = await bindScope(scope);\n if (bound === null) throw new Error(`refusing to write: the trusted root ${scope.trustedReal} is gone`);\n await hooks.beforeOpen?.();\n const handle = await promises.open(path.join(dirReal, leaf), CREATE_FLAGS);\n try {\n await hooks.afterOpen?.();\n if ((await verifiedCreatedFileDir(bound, dirReal, leaf, handle)) === null) throw new Error(`refusing to write: ${dirReal} left the scope during the write`);\n await handle.writeFile(content);\n } finally {\n await handle.close();\n }\n}\n","// Read / overwrite files the TOOL CALL named, rather than files the app minted.\n// `presentDocument(path)` / `presentHtml(path)` open a document that already\n// exists — a repo's `README.md`, `docs/report.html`, an absolute path — and the\n// user's edits in the view overwrite it in place.\n//\n// Shared by both hosts (MulmoClaude's `server/utils/files/by-path.ts` and\n// MulmoTerminal's backend bind their own workspace root to it), because the\n// judgement of what a `path` argument may reach is exactly the thing that must\n// not drift between them: a host that accepts what the other refuses turns one\n// tool call into two different behaviours.\n//\n// The rules:\n// - `classifyFilePath` (also what the plugins' `path` gate calls) decides the\n// shape: right extension, no NUL, no `.` / `..` / empty segment. That\n// lexical guard is what stops a vetted path from being re-pointed later.\n// - relative paths resolve against the injected root; absolute paths are taken\n// as given. There is deliberately NO containment check — opening a file\n// outside the workspace is the documented purpose of the `path` form. The\n// agent can already read and write those files directly; what is new is that\n// the view can too.\n// - a value that is absolute only under ANOTHER platform's rules is refused:\n// `classifyFilePath` recognises `C:\\proj\\x.md` everywhere (the value may\n// come from a remote host), but on POSIX `path.resolve(\"C:/proj/x.md\")`\n// lands under the process cwd — a file nobody named.\n// - reads and writes require a REGULAR FILE, judged through `realpath` so a\n// symlink is assessed by what it points at and a directory named `x.md`\n// cannot masquerade as a document.\n// - `write` overwrites only. Neither tool creates a file at a caller-supplied\n// path, so a write to a path that does not exist means the view is stale or\n// the path was wrong — refusing keeps a typo from scattering files.\n// - `readDir` and `unlink` are refused outright: this capability exists to\n// read and re-save ONE named document, not to browse or delete.\n\nimport { readFile, realpath, stat as fsStat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { classifyFilePath } from \"../artifacts/paths.js\";\nimport { writeFileAtomic } from \"./atomic.js\";\n\nexport const MARKDOWN_EXTENSIONS = [\".md\"] as const;\nexport const HTML_EXTENSIONS = [\".html\", \".htm\"] as const;\n\n/** Minimal structural echo of gui-chat-protocol's `FileOps`. Declared here\n * rather than imported so core keeps no dependency on the protocol package;\n * a host assigns the result straight to a `FileOps`-typed capability. */\nexport interface ByPathFileOps {\n read: (rel: string) => Promise<string>;\n readBytes: (rel: string) => Promise<Uint8Array>;\n write: (rel: string, content: string | Uint8Array) => Promise<void>;\n readDir: (rel: string) => Promise<string[]>;\n stat: (rel: string) => Promise<{ mtimeMs: number; size: number }>;\n exists: (rel: string) => Promise<boolean>;\n unlink: (rel: string) => Promise<void>;\n}\n\n/** Absolute on-disk path for a caller-supplied path with one of `extensions`,\n * or null when the value is not usable on this platform. */\nexport function resolveByPath(root: string, value: string, extensions: readonly string[]): string | null {\n const kind = classifyFilePath(value, extensions);\n if (kind === null) return null;\n if (kind === \"relative\") return path.resolve(root, value);\n return path.isAbsolute(value) ? path.resolve(value) : null;\n}\n\n/** True when the path names an existing regular file. */\nexport async function existsAsFile(root: string, value: string, extensions: readonly string[]): Promise<boolean> {\n const absPath = resolveByPath(root, value, extensions);\n return absPath === null ? false : (await regularFileTarget(absPath)) !== null;\n}\n\nexport interface ByPathOptions {\n /** The root relative values resolve against, read PER CALL — hosts inject the\n * workspace after these ops are already bound into plugin closures. */\n rootFor: () => string;\n extensions: readonly string[];\n}\n\nfunction resolveOrThrow({ rootFor, extensions }: ByPathOptions, value: string): string {\n const absPath = resolveByPath(rootFor(), value, extensions);\n if (absPath === null) throw new Error(`invalid path: ${value}`);\n return absPath;\n}\n\n/** The canonical REGULAR FILE a path names, or null when it is missing, is a\n * directory, or is anything else (a FIFO would block a read forever).\n * Resolved through `realpath` so a symlink is judged — and later written — by\n * what it points at: `writeFileAtomic` renames a temp file into place, which\n * through a link would replace the link itself and leave the real document\n * untouched. */\nasync function regularFileTarget(absPath: string): Promise<string | null> {\n try {\n const target = await realpath(absPath);\n return (await fsStat(target)).isFile() ? target : null;\n } catch {\n return null;\n }\n}\n\n/** The file to read or overwrite. Throws rather than creating: neither tool\n * ever writes to a path that does not already hold a document. */\nasync function existingFileFor(options: ByPathOptions, rel: string): Promise<string> {\n const target = await regularFileTarget(resolveOrThrow(options, rel));\n if (target === null) throw new Error(`no file exists at ${rel}`);\n return target;\n}\n\n/** Browsing and deleting are NOT part of this capability: it exists so a view\n * can read and re-save the ONE document the tool call named, not to enumerate\n * a directory it was never pointed at or remove a file. */\nfunction unsupported(operation: string): () => Promise<never> {\n return () => Promise.reject(new Error(`byPath FileOps does not support ${operation}`));\n}\n\n/** FileOps over caller-supplied paths — what a host injects as `files.byPath`\n * for plugins whose `path` argument may leave their artifact directory. Every\n * method takes the same value the tool call carried, not a scope-relative one. */\nexport function createByPathFileOps(options: ByPathOptions): ByPathFileOps {\n return {\n read: async (rel) => readFile(await existingFileFor(options, rel), \"utf-8\"),\n readBytes: async (rel) => {\n const buf = await readFile(await existingFileFor(options, rel));\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n },\n write: async (rel, content) => writeFileAtomic(await existingFileFor(options, rel), content),\n readDir: unsupported(\"readDir\"),\n stat: async (rel) => {\n const { mtimeMs, size } = await fsStat(resolveOrThrow(options, rel));\n return { mtimeMs, size };\n },\n exists: (rel) => existsAsFile(options.rootFor(), rel, options.extensions),\n unlink: unsupported(\"unlink\"),\n };\n}\n","// Server half of the `/htmlfile` scheme (client half: `src/config/htmlFileUrl.ts`).\n// Turns a request path into the absolute file to serve, or null.\n//\n// Shared by both hosts so the URL the View asks for and the file a host resolves\n// cannot drift apart.\n//\n// This mount is deliberately NOT contained to a root: presentHtml's `path` form\n// may name any HTML page on disk, and serving it is the point. What still holds:\n//\n// - only `ws` (workspace-relative) and `abs` (absolute) scopes exist; anything\n// else 404s, so a bare `/htmlfile/etc/passwd` is not a path at all.\n// - no `.` / `..` / empty segment survives, so a vetted URL cannot be\n// re-pointed by traversal, and no dotfile segment is reachable (same policy\n// as `resolveArtifactRequestPath`, which the artifact mounts share).\n// - extension allowlist, realpath and regular-file checks stay with the host's\n// mount, which is also where the CSP header and rate limit are applied.\n//\n// The trust boundary is whatever the host applies to its `/artifacts/html`\n// mount — in MulmoClaude, the loopback-only listener plus `requireSameOrigin`\n// (bearer auth does not apply outside `/api`, and an iframe `src` request cannot\n// carry an Authorization header anyway).\n\nimport path from \"node:path\";\n// The scope constants are re-declared rather than imported: core must not\n// depend on a plugin (dependencies flow the other way). `html-plugin`'s\n// `htmlFileUrl` builds the URLs these parse, and the round-trip test in the host\n// is what keeps the two halves honest.\nconst HTML_FILE_SCOPE_WORKSPACE = \"ws\";\nconst HTML_FILE_SCOPE_ABSOLUTE = \"abs\";\n\nconst WINDOWS_DRIVE_ONLY_RE = /^[a-zA-Z]:$/;\n\nfunction decodeSegments(reqPath: string): string[] | null {\n let decoded: string[];\n try {\n decoded = reqPath\n .replace(/^\\//, \"\")\n .split(\"/\")\n .map((segment) => decodeURIComponent(segment));\n } catch {\n // Malformed escape (`%ZZ`) — fail closed rather than bubbling a URIError.\n return null;\n }\n // Segmentation happens on the ENCODED path, so a `%2F` (or `%5C`) becomes a\n // separator only after this decode — `a%2F..%2F..%2Ftmp%2Fx.html` would arrive\n // as one segment that the `..` check below never sees, and then split apart\n // inside `path.resolve`. A decoded segment that still contains a separator is\n // never legitimate here, so refuse it.\n return decoded.some((segment) => segment.includes(\"/\") || segment.includes(\"\\\\\")) ? null : decoded;\n}\n\n/** Absolute path for a `/htmlfile/<scope>/<segments…>` request, or null when\n * the URL is malformed, uses an unknown scope, or touches a `.` / `..` /\n * dotfile segment. `workspaceRoot` should already be a realpath. */\nexport function resolveHtmlFileRequestPath(workspaceRoot: string, reqPath: string): string | null {\n const decoded = decodeSegments(reqPath);\n if (decoded === null || decoded.length < 2) return null;\n const [scope, ...rest] = decoded;\n if (scope !== HTML_FILE_SCOPE_WORKSPACE && scope !== HTML_FILE_SCOPE_ABSOLUTE) return null;\n const [firstRest] = rest;\n if (firstRest === undefined) return null;\n if (rest.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\" || segment.startsWith(\".\") || segment.includes(\"\\0\"))) {\n return null;\n }\n if (scope === HTML_FILE_SCOPE_WORKSPACE) return path.resolve(workspaceRoot, ...rest);\n // `abs/C:/proj/page.html` — the drive letter arrives as its own segment, so\n // rejoin it before resolving; everything else is rooted at `/`.\n const candidate = WINDOWS_DRIVE_ONLY_RE.test(firstRest) ? rest.join(\"/\") : `/${rest.join(\"/\")}`;\n // Only THIS platform's `path` can say whether that is really absolute: on\n // POSIX, `path.resolve(\"C:/proj/page.html\")` would land under the process cwd\n // rather than at any drive, silently serving the wrong file. Refuse instead.\n return path.isAbsolute(candidate) ? path.resolve(candidate) : null;\n}\n"],"mappings":";;;;;;;;;;;;AAEA,IAAM,cAAc;;;AAIpB,eAAsB,gBAAgB,UAAkB,MAAe,OAA2B,CAAC,GAAkB;CACnH,MAAMA,aAAAA,gBAAgB,UAAU,KAAK,UAAU,MAAM,MAAM,WAAW,GAAG,IAAI;AAC/E;;ACKA,IAAM,aAAaC,QAAAA,UAAU,YAAYA,QAAAA,UAAU,cAAc,MAAMA,QAAAA,UAAU,cAAc;AAC/F,IAAM,eAAeA,QAAAA,UAAU,WAAWA,QAAAA,UAAU,UAAUA,QAAAA,UAAU,UAAUA,QAAAA,UAAU,cAAc;AAC1G,IAAM,uBAAuB;;AAU7B,eAAsB,kBAAkB,SAAyC;CAC/E,IAAI;EACF,OAAO,MAAMC,QAAAA,SAAS,SAAS,OAAO;CACxC,SAAS,KAAK;EACZ,IAAIC,mBAAAA,SAAS,GAAG,GAAG,OAAO;EAC1B,MAAM;CACR;AACF;AAEA,IAAM,YAAY,UAAkB,kBAAmC,kBAAkB,YAAY,cAAc,WAAW,WAAWC,UAAAA,QAAK,GAAG;;AAGjJ,eAAsB,0BAA0B,UAAkB,UAA0C;CAC1G,MAAM,gBAAgB,MAAM,kBAAkBA,UAAAA,QAAK,QAAQ,UAAU,QAAQ,CAAC;CAC9E,OAAO,kBAAkB,QAAQ,SAAS,UAAU,aAAa,IAAI,gBAAgB;AACvF;AAEA,IAAM,YAAY,QAAqB,WAAiC,OAAO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M,YAAY,QAAQ,SAAS,GAAG,KAAK,QAAQ,SAAS,IAAI,CAAC,IAAI,OAAO;AAC7F;;;;AAKA,SAAgB,2BAA2B,eAAuB,SAAgC;CAChG,MAAM,UAAU,eAAe,OAAO;CACtC,IAAI,YAAY,QAAQ,QAAQ,SAAS,GAAG,OAAO;CACnD,MAAM,CAAC,OAAO,GAAG,QAAQ;CACzB,IAAI,UAAU,6BAA6B,UAAU,0BAA0B,OAAO;CACtF,MAAM,CAAC,aAAa;CACpB,IAAI,cAAc,KAAA,GAAW,OAAO;CACpC,IAAI,KAAK,MAAM,YAAY,YAAY,MAAM,YAAY,OAAO,YAAY,QAAQ,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,IAAI,CAAC,GACnI,OAAO;CAET,IAAI,UAAU,2BAA2B,OAAOG,UAAAA,QAAK,QAAQ,eAAe,GAAG,IAAI;CAGnF,MAAM,YAAY,sBAAsB,KAAK,SAAS,IAAI,KAAK,KAAK,GAAG,IAAI,IAAI,KAAK,KAAK,GAAG;CAI5F,OAAOA,UAAAA,QAAK,WAAW,SAAS,IAAIA,UAAAA,QAAK,QAAQ,SAAS,IAAI;AAChE"}
@@ -2,6 +2,7 @@ export { writeFileAtomic, writeFileAtomicSync, type WriteAtomicOptions } from '.
2
2
  export { writeJsonAtomic } from './json.js';
3
3
  export { isEnoent, resolveWithinRoot } from './safe.js';
4
4
  export { openVerifiedWithinScope, writeFileVerifiedInScope, createFileVerifiedInScope, scopeRealpath, resolveExistingWithinRoot, realpathIfPresent, type VerifiedScope, type VerifiedFileHooks, } from './verified.js';
5
+ export { isWithinRoot, realpathSyncOrNull, readTextWithinRoot, readTextWithinRootSync } from './withinRoot.js';
5
6
  export { toPosixRelPath, joinPosixRelPath } from './relPath.js';
6
7
  export { canonicalRoot } from './root.js';
7
8
  export { resolveByPath, existsAsFile, createByPathFileOps, MARKDOWN_EXTENSIONS, HTML_EXTENSIONS, type ByPathFileOps, type ByPathOptions } from './byPath.js';
@@ -1,5 +1,5 @@
1
1
  import { i as writeFileAtomicSync, n as renameWithWindowsRetry, r as writeFileAtomic, t as canonicalRoot } from "../root-CqxPNSyK.js";
2
- import { n as resolveWithinRoot, t as isEnoent } from "../safe-DRNa8UBp.js";
2
+ import { a as isEnoent, i as realpathSyncOrNull, n as readTextWithinRoot, o as resolveWithinRoot, r as readTextWithinRootSync, t as isWithinRoot } from "../withinRoot-Bbj6E-Lf.js";
3
3
  import { n as toPosixRelPath, t as joinPosixRelPath } from "../relPath-BkKmqiiF.js";
4
4
  import { classifyFilePath } from "../artifacts/paths.js";
5
5
  import { constants, promises } from "node:fs";
@@ -257,6 +257,6 @@ function resolveHtmlFileRequestPath(workspaceRoot, reqPath) {
257
257
  const candidate = WINDOWS_DRIVE_ONLY_RE.test(firstRest) ? rest.join("/") : `/${rest.join("/")}`;
258
258
  return path.isAbsolute(candidate) ? path.resolve(candidate) : null;
259
259
  }
260
- export { HTML_EXTENSIONS, MARKDOWN_EXTENSIONS, canonicalRoot, createByPathFileOps, createFileVerifiedInScope, existsAsFile, isEnoent, joinPosixRelPath, openVerifiedWithinScope, realpathIfPresent, resolveByPath, resolveExistingWithinRoot, resolveHtmlFileRequestPath, resolveWithinRoot, scopeRealpath, toPosixRelPath, writeFileAtomic, writeFileAtomicSync, writeFileVerifiedInScope, writeJsonAtomic };
260
+ export { HTML_EXTENSIONS, MARKDOWN_EXTENSIONS, canonicalRoot, createByPathFileOps, createFileVerifiedInScope, existsAsFile, isEnoent, isWithinRoot, joinPosixRelPath, openVerifiedWithinScope, readTextWithinRoot, readTextWithinRootSync, realpathIfPresent, realpathSyncOrNull, resolveByPath, resolveExistingWithinRoot, resolveHtmlFileRequestPath, resolveWithinRoot, scopeRealpath, toPosixRelPath, writeFileAtomic, writeFileAtomicSync, writeFileVerifiedInScope, writeJsonAtomic };
261
261
 
262
262
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ export declare function isWithinRoot(rootReal: string, candidateReal: string): boolean;
2
+ export declare function realpathSyncOrNull(absPath: string): string | null;
3
+ /** Text of a regular file inside `rootReal` (a realpath), or null when it is missing, leads outside, is a FIFO or
4
+ * other non-file, or is unreadable. */
5
+ export declare function readTextWithinRoot(rootReal: string, absPath: string): Promise<string | null>;
6
+ /** Sync twin of `readTextWithinRoot`. */
7
+ export declare function readTextWithinRootSync(rootReal: string, absPath: string): string | null;
@@ -1,10 +1,3 @@
1
1
  import { Dirent, Stats } from 'node:fs';
2
- export declare function isWithin(rootReal: string, candidateReal: string): boolean;
3
- export declare function realpathOrNull(absPath: string): string | null;
4
- /** Text of a regular file inside `rootReal`, or null when it is missing, leads outside, is a FIFO or other non-file,
5
- * or is unreadable. */
6
- export declare function readTextSafe(absPath: string, rootReal: string): Promise<string | null>;
7
- /** Sync twin of `readTextSafe`. */
8
- export declare function readTextSafeSync(absPath: string, rootReal: string): string | null;
9
2
  export declare function statSafeAsync(absPath: string): Promise<Stats | null>;
10
3
  export declare function readDirSafeAsync(absPath: string): Promise<Dirent[]>;
@@ -1,67 +1,14 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_rolldown_runtime = require("../../rolldown-runtime-CmQyd0Gu.cjs");
3
3
  const require_wiki_paths = require("../paths.cjs");
4
- const require_safe = require("../../safe-D79sHxq1.cjs");
5
4
  const require_graph = require("../../graph-BvVMZfDV.cjs");
6
5
  const require_slug = require("../../slug-DVkuPjIv.cjs");
7
- let node_fs = require("node:fs");
6
+ const require_withinRoot = require("../../withinRoot-FLjxC8oP.cjs");
8
7
  let node_path = require("node:path");
9
8
  node_path = require_rolldown_runtime.__toESM(node_path, 1);
10
9
  let node_fs_promises = require("node:fs/promises");
11
10
  let _mulmoclaude_markdown_utils_markdown_frontmatter = require("@mulmoclaude/markdown-utils/markdown/frontmatter");
12
11
  // src/wiki/server/fs.ts
13
- var READ_FLAGS = node_fs.constants.O_RDONLY | (node_fs.constants.O_NOFOLLOW ?? 0) | (node_fs.constants.O_NONBLOCK ?? 0);
14
- function isWithin(rootReal, candidateReal) {
15
- const rel = node_path.default.relative(rootReal, candidateReal);
16
- return rel !== ".." && !rel.startsWith(`..${node_path.default.sep}`) && !node_path.default.isAbsolute(rel);
17
- }
18
- function realpathOrNull(absPath) {
19
- try {
20
- return node_fs.realpathSync.native(absPath);
21
- } catch (err) {
22
- return require_safe.isEnoent(err) ? null : jsRealpathOrNull(absPath);
23
- }
24
- }
25
- function jsRealpathOrNull(absPath) {
26
- try {
27
- return (0, node_fs.realpathSync)(absPath);
28
- } catch {
29
- return null;
30
- }
31
- }
32
- function isOpenedFileInside(absPath, rootReal, opened) {
33
- const real = realpathOrNull(absPath);
34
- if (real === null || !isWithin(rootReal, real) || !opened.isFile()) return false;
35
- const onDisk = (0, node_fs.lstatSync)(real, { bigint: true });
36
- return onDisk.isFile() && onDisk.dev === opened.dev && onDisk.ino === opened.ino;
37
- }
38
- /** Text of a regular file inside `rootReal`, or null when it is missing, leads outside, is a FIFO or other non-file,
39
- * or is unreadable. */
40
- async function readTextSafe(absPath, rootReal) {
41
- try {
42
- const handle = await (0, node_fs_promises.open)(absPath, READ_FLAGS);
43
- try {
44
- return isOpenedFileInside(absPath, rootReal, await handle.stat({ bigint: true })) ? await handle.readFile("utf-8") : null;
45
- } finally {
46
- await handle.close();
47
- }
48
- } catch {
49
- return null;
50
- }
51
- }
52
- /** Sync twin of `readTextSafe`. */
53
- function readTextSafeSync(absPath, rootReal) {
54
- try {
55
- const descriptor = (0, node_fs.openSync)(absPath, READ_FLAGS);
56
- try {
57
- return isOpenedFileInside(absPath, rootReal, (0, node_fs.fstatSync)(descriptor, { bigint: true })) ? (0, node_fs.readFileSync)(descriptor, "utf-8") : null;
58
- } finally {
59
- (0, node_fs.closeSync)(descriptor);
60
- }
61
- } catch {
62
- return null;
63
- }
64
- }
65
12
  async function statSafeAsync(absPath) {
66
13
  try {
67
14
  return await (0, node_fs_promises.stat)(absPath);
@@ -126,10 +73,10 @@ function parseFrontmatterTags(content) {
126
73
  // src/wiki/server/locations.ts
127
74
  function wikiReadLocations(workspace) {
128
75
  const dirs = require_wiki_paths.wikiDirs(workspace);
129
- const workspaceReal = realpathOrNull(workspace);
76
+ const workspaceReal = require_withinRoot.realpathSyncOrNull(workspace);
130
77
  const insideWorkspace = (absPath) => {
131
- const candidateReal = workspaceReal === null ? null : realpathOrNull(node_path.default.resolve(workspaceReal, node_path.default.relative(workspace, absPath)));
132
- return workspaceReal !== null && candidateReal !== null && isWithin(workspaceReal, candidateReal) ? candidateReal : null;
78
+ const candidateReal = workspaceReal === null ? null : require_withinRoot.realpathSyncOrNull(node_path.default.resolve(workspaceReal, node_path.default.relative(workspace, absPath)));
79
+ return workspaceReal !== null && candidateReal !== null && require_withinRoot.isWithinRoot(workspaceReal, candidateReal) ? candidateReal : null;
133
80
  };
134
81
  return {
135
82
  pagesDir: dirs.pagesDir,
@@ -142,7 +89,7 @@ function wikiReadLocations(workspace) {
142
89
  // src/wiki/server/engine.ts
143
90
  var MIN_FUZZY_SLUG_LEN = 6;
144
91
  function readFileOrEmpty(absPath, workspaceReal) {
145
- return absPath === null || workspaceReal === null ? "" : readTextSafeSync(absPath, workspaceReal) ?? "";
92
+ return absPath === null || workspaceReal === null ? "" : require_withinRoot.readTextWithinRootSync(workspaceReal, absPath) ?? "";
146
93
  }
147
94
  async function pageSlugs(locations) {
148
95
  return locations.pagesReal === null ? /* @__PURE__ */ new Map() : (await getPageIndex(locations.pagesReal)).slugs;
@@ -233,7 +180,7 @@ async function readWikiPage(workspace, pageName) {
233
180
  /** Page body, or "" when the file vanished between indexing and reading. */
234
181
  async function readPageBody(locations, fileName) {
235
182
  const { pagesReal, workspaceReal } = locations;
236
- return pagesReal === null || workspaceReal === null ? "" : await readTextSafe(node_path.default.join(pagesReal, fileName), workspaceReal) ?? "";
183
+ return pagesReal === null || workspaceReal === null ? "" : await require_withinRoot.readTextWithinRoot(workspaceReal, node_path.default.join(pagesReal, fileName)) ?? "";
237
184
  }
238
185
  /** Read every page + the index and build the page→page link graph.
239
186
  * No cache: the graph is requested explicitly and a content edit does
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["constants","path","realpathSync","isEnoent","lstatSync","open","openSync","fstatSync","readFileSync","stat","readdir","parseFrontmatter","wikiDirs","path","parseIndexEntries","path","parseWikiLink","matchWikiSlug","wikiSlugify","buildWikiGraph","slugByIndexTitle","findOrphanPages","findMissingFiles","findBrokenLinksInPage","findTagDrift"],"sources":["../../../src/wiki/server/fs.ts","../../../src/wiki/server/pageIndex.ts","../../../src/wiki/server/frontmatter.ts","../../../src/wiki/server/locations.ts","../../../src/wiki/server/engine.ts"],"sourcesContent":["// Minimal ENOENT-swallowing fs wrappers for the wiki read-engine.\n// Self-contained (core can't reach the host's `server/utils/files/safe.ts`);\n// only the handful of helpers the wiki engine needs. Same \"return\n// null / [] on any error\" contract so callers branch on the value\n// instead of try/catch.\n\nimport type { BigIntStats, Dirent, Stats } from \"node:fs\";\nimport { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, realpathSync } from \"node:fs\";\nimport { open, readdir, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { isEnoent } from \"../../files/safe.js\";\n\n// A FIFO must not block the server, and a link is refused at open where the OS can; both flags are undefined on\n// Windows, where the check after the open is what refuses a link out.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);\n\n// `path.relative` rather than a `rootReal + sep` prefix, which a workspace at a filesystem root (`/`, `C:\\`) would fail.\nexport function isWithin(rootReal: string, candidateReal: string): boolean {\n const rel = path.relative(rootReal, candidateReal);\n return rel !== \"..\" && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);\n}\n\n// Native first: the JS realpath keeps a link's letter case, so on a case-insensitive disk an inside link looks outside.\n// The JS one is the fallback for drives where the native call throws (EISDIR on some Windows RAM disks).\nexport function realpathOrNull(absPath: string): string | null {\n try {\n return realpathSync.native(absPath);\n } catch (err) {\n return isEnoent(err) ? null : jsRealpathOrNull(absPath);\n }\n}\n\nfunction jsRealpathOrNull(absPath: string): string | null {\n try {\n return realpathSync(absPath);\n } catch {\n return null;\n }\n}\n\n// Checked after the open, so a folder or file swapped for a link out between the caller's check and the open, or\n// swapped back before this check, is refused: where the path leads now must be inside and be the opened file.\nfunction isOpenedFileInside(absPath: string, rootReal: string, opened: BigIntStats): boolean {\n const real = realpathOrNull(absPath);\n if (real === null || !isWithin(rootReal, real) || !opened.isFile()) return false;\n const onDisk = lstatSync(real, { bigint: true });\n return onDisk.isFile() && onDisk.dev === opened.dev && onDisk.ino === opened.ino;\n}\n\n/** Text of a regular file inside `rootReal`, or null when it is missing, leads outside, is a FIFO or other non-file,\n * or is unreadable. */\nexport async function readTextSafe(absPath: string, rootReal: string): Promise<string | null> {\n try {\n const handle = await open(absPath, READ_FLAGS);\n try {\n return isOpenedFileInside(absPath, rootReal, await handle.stat({ bigint: true })) ? await handle.readFile(\"utf-8\") : null;\n } finally {\n await handle.close();\n }\n } catch {\n return null;\n }\n}\n\n/** Sync twin of `readTextSafe`. */\nexport function readTextSafeSync(absPath: string, rootReal: string): string | null {\n try {\n const descriptor = openSync(absPath, READ_FLAGS);\n try {\n return isOpenedFileInside(absPath, rootReal, fstatSync(descriptor, { bigint: true })) ? readFileSync(descriptor, \"utf-8\") : null;\n } finally {\n closeSync(descriptor);\n }\n } catch {\n return null;\n }\n}\n\nexport async function statSafeAsync(absPath: string): Promise<Stats | null> {\n try {\n return await stat(absPath);\n } catch {\n return null;\n }\n}\n\nexport async function readDirSafeAsync(absPath: string): Promise<Dirent[]> {\n try {\n return await readdir(absPath, { withFileTypes: true });\n } catch {\n return [];\n }\n}\n","// In-memory index of `<pagesDir>/*.md` keyed by slug (= filename\n// without the `.md` extension). Kept fresh via `pagesDir` mtime —\n// adding, removing, or renaming a file under `pagesDir` advances the\n// directory's mtime on every major filesystem we target (macOS APFS,\n// Linux ext4, Windows NTFS), so one cheap `stat()` per request is\n// enough to decide whether to rebuild.\n\nimport { readDirSafeAsync, statSafeAsync } from \"./fs.js\";\n\nexport interface PageIndex {\n mtimeMs: number;\n /** slug → filename (e.g. \"sakura-internet\" → \"sakura-internet.md\"). */\n slugs: Map<string, string>;\n}\n\n// Keyed by `pagesDir`: the engine is workspace-injected and may be\n// called with more than one pages directory in a single process. A\n// single global slot would let one workspace's slug map be returned\n// for another whenever their mtimes happen to tie (Codex P2 on #1876).\nconst cache = new Map<string, PageIndex>();\n\n/**\n * Get the page index for `pagesDir`. Returns a cached value as long as\n * THAT directory's mtime hasn't advanced; otherwise rebuilds. Safe to\n * call concurrently — racing builds produce the same result.\n */\nexport async function getPageIndex(pagesDir: string): Promise<PageIndex> {\n const stat = await statSafeAsync(pagesDir);\n if (!stat) {\n // Dir doesn't exist yet (never ingested). Return empty but don't\n // cache a stale-forever value — the next call re-stats.\n return { mtimeMs: 0, slugs: new Map() };\n }\n const cached = cache.get(pagesDir);\n if (cached && cached.mtimeMs >= stat.mtimeMs) return cached;\n const entries = await readDirSafeAsync(pagesDir);\n const slugs = new Map<string, string>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const { name } = entry;\n if (!name.endsWith(\".md\")) continue;\n slugs.set(name.slice(0, -\".md\".length), name);\n }\n const built: PageIndex = { mtimeMs: stat.mtimeMs, slugs };\n cache.set(pagesDir, built);\n return built;\n}\n\n/** Test-only: drop the module-level cache (all directories). */\nexport function __resetPageIndexCache(): void {\n cache.clear();\n}\n","// Read-side frontmatter helpers for the wiki engine. The generic\n// `---\\n…\\n---\\n` envelope parsing is the canonical value-preserving\n// (FAILSAFE_SCHEMA) parser in `@mulmoclaude/markdown-utils`; only the\n// wiki-specific `tags:` reader stays here. Re-exporting `parseFrontmatter`\n// keeps the `@mulmoclaude/core/wiki/server` barrel surface stable — it now\n// returns the richer `{ meta, body, hasHeader }` shape.\n\nimport { parseFrontmatter } from \"@mulmoclaude/markdown-utils/markdown/frontmatter\";\n\nexport { parseFrontmatter };\n\nfunction cleanTagToken(token: string): string {\n return token\n .trim()\n .replace(/^['\"]|['\"]$/g, \"\")\n .replace(/^#/, \"\")\n .toLowerCase();\n}\n\n/** Narrow `tags:` reader. Handles flow (`tags: [a, b]`) and block-list\n * style; anything unparseable returns `[]` (best-effort, never throws). */\nexport function parseFrontmatterTags(content: string): string[] {\n const parsed = parseFrontmatter(content);\n if (!parsed.hasHeader) return [];\n const tagsValue = parsed.meta.tags;\n if (!Array.isArray(tagsValue)) return [];\n return tagsValue\n .filter((item): item is string => typeof item === \"string\")\n .map(cleanTagToken)\n .filter((token) => token.length > 0);\n}\n","// A wiki folder or file that leads out of the workspace counts as absent, so nothing outside is listed or read.\n\nimport path from \"node:path\";\nimport { isWithin, realpathOrNull } from \"./fs.js\";\nimport { wikiDirs } from \"./paths.js\";\n\nexport interface WikiReadLocations {\n /** `<workspace>/data/wiki/pages` as the caller spelled it: resolved page paths handed back are joined onto this. */\n pagesDir: string;\n /** The workspace's realpath: every read re-checks against it after opening. */\n workspaceReal: string | null;\n pagesReal: string | null;\n indexReal: string | null;\n logReal: string | null;\n}\n\nexport function wikiReadLocations(workspace: string): WikiReadLocations {\n const dirs = wikiDirs(workspace);\n const workspaceReal = realpathOrNull(workspace);\n const insideWorkspace = (absPath: string): string | null => {\n const candidateReal = workspaceReal === null ? null : realpathOrNull(path.resolve(workspaceReal, path.relative(workspace, absPath)));\n return workspaceReal !== null && candidateReal !== null && isWithin(workspaceReal, candidateReal) ? candidateReal : null;\n };\n return {\n pagesDir: dirs.pagesDir,\n workspaceReal,\n pagesReal: insideWorkspace(dirs.pagesDir),\n indexReal: insideWorkspace(dirs.indexFile),\n logReal: insideWorkspace(dirs.logFile),\n };\n}\n","// Workspace-injected wiki read-engine — the filesystem layer that feeds\n// the pure helpers in `@mulmoclaude/core/wiki`. Shared by every host so\n// the two apps reading the same `data/wiki/` can't disagree on slug\n// resolution, graph edges, or lint findings. Mirrors the bodies that\n// previously lived in MulmoClaude's `server/api/routes/wiki.ts`; the\n// hosts keep only their HTTP response shaping on top.\n//\n// The read/write WRITE side (writeWikiPage / snapshots) stays host-side\n// until a host needs it shared.\n\nimport path from \"node:path\";\nimport { parseWikiLink } from \"../link.js\";\nimport { wikiSlugify } from \"../slug.js\";\nimport { matchWikiSlug, slugByIndexTitle } from \"../resolve.js\";\nimport { type WikiPageEntry, parseIndexEntries } from \"../index-parse.js\";\nimport { findBrokenLinksInPage, findMissingFiles, findOrphanPages, findTagDrift } from \"../lint.js\";\nimport { type WikiGraph, buildWikiGraph } from \"../graph.js\";\nimport { readTextSafe, readTextSafeSync } from \"./fs.js\";\nimport { getPageIndex } from \"./pageIndex.js\";\nimport { parseFrontmatterTags } from \"./frontmatter.js\";\nimport { type WikiReadLocations, wikiReadLocations } from \"./locations.js\";\n\n// Below this length the fuzzy `includes` step is skipped — CJK /\n// emoji-only / very-short page names slugify down to a short noise\n// tail that partial-matches almost anything; the index.md title-match\n// fallback still handles the legitimate non-ASCII case (#1194).\nconst MIN_FUZZY_SLUG_LEN = 6;\n\nfunction readFileOrEmpty(absPath: string | null, workspaceReal: string | null): string {\n return absPath === null || workspaceReal === null ? \"\" : (readTextSafeSync(absPath, workspaceReal) ?? \"\");\n}\n\nasync function pageSlugs(locations: WikiReadLocations): Promise<Map<string, string>> {\n return locations.pagesReal === null ? new Map() : (await getPageIndex(locations.pagesReal)).slugs;\n}\n\n/** Walk every indexed slug for an `includes`-style match. Returns the\n * single best candidate, or null when the slug is too short OR several\n * candidates tie at the top score (ambiguous → defer to the caller's\n * title-match fallback). Score = min/max length, decoupled from Map\n * iteration order so resolution is deterministic across hosts. */\nexport function pickFuzzyMatch(slug: string, slugs: ReadonlyMap<string, string>): string | null {\n if (slug.length < MIN_FUZZY_SLUG_LEN) return null;\n let bestFile: string | null = null;\n let bestScore = 0;\n let bestIsTied = false;\n for (const [key, file] of slugs) {\n if (!slug.includes(key) && !key.includes(slug)) continue;\n const shorter = Math.min(slug.length, key.length);\n const longer = Math.max(slug.length, key.length);\n const score = shorter / longer;\n if (score > bestScore) {\n bestScore = score;\n bestFile = file;\n bestIsTied = false;\n } else if (score === bestScore) {\n bestIsTied = true;\n }\n }\n return bestIsTied ? null : bestFile;\n}\n\n/** File matching an index.md entry whose title equals `target` — the\n * last resort for a link written as the display title rather than\n * the page's own name. */\nfunction fileByIndexTitle(locations: WikiReadLocations, target: string, slugs: ReadonlyMap<string, string>): string | undefined {\n const entries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n const trimmed = target.trim();\n const titleMatch = entries.find((entry) => entry.title === trimmed);\n return titleMatch ? slugs.get(titleMatch.slug) : undefined;\n}\n\n/** Resolve a page name to an absolute `.md` path: known slug (literal\n * or slugified) → fuzzy → index-title fallback. `pageName` may carry\n * the `[[target|display]]` form; `parseWikiLink` strips the display\n * half so the lookup uses just the target. */\nexport async function resolvePagePath(workspace: string, pageName: string): Promise<string | null> {\n const locations = wikiReadLocations(workspace);\n const fileName = await resolvePageFile(locations, pageName);\n return fileName === null ? null : path.join(locations.pagesDir, fileName);\n}\n\nasync function resolvePageFile(locations: WikiReadLocations, pageName: string): Promise<string | null> {\n const slugs = await pageSlugs(locations);\n if (slugs.size === 0) return null;\n\n const { target } = parseWikiLink(pageName);\n const matched = matchWikiSlug(target, slugs);\n const matchedFile = matched === null ? undefined : slugs.get(matched);\n if (matchedFile) return matchedFile;\n\n const fuzzy = pickFuzzyMatch(wikiSlugify(target), slugs);\n if (fuzzy) return fuzzy;\n\n return fileByIndexTitle(locations, target, slugs) ?? null;\n}\n\n/** Raw `index.md` content + its parsed entries. */\nexport function readWikiIndex(workspace: string): { content: string; entries: WikiPageEntry[] } {\n const locations = wikiReadLocations(workspace);\n const content = readFileOrEmpty(locations.indexReal, locations.workspaceReal);\n return { content, entries: parseIndexEntries(content) };\n}\n\n/** Raw `log.md` content (empty string if absent). */\nexport function readWikiLog(workspace: string): string {\n const locations = wikiReadLocations(workspace);\n return readFileOrEmpty(locations.logReal, locations.workspaceReal);\n}\n\nexport interface WikiPageRead {\n /** Absolute path of the resolved file, or null when nothing matched. */\n filePath: string | null;\n /** File body (empty when missing OR when the file is an empty placeholder). */\n content: string;\n /** True iff a page file resolved (distinct from empty content). */\n exists: boolean;\n /** Title to display — the resolved filename stem, or the raw pageName. */\n resolvedTitle: string;\n}\n\n/** Resolve + read a page. Distinguishes missing (`exists: false`) from\n * empty-but-present (`exists: true`, `content: \"\"`). */\nexport async function readWikiPage(workspace: string, pageName: string): Promise<WikiPageRead> {\n const locations = wikiReadLocations(workspace);\n const fileName = await resolvePageFile(locations, pageName);\n if (fileName === null || locations.pagesReal === null) return { filePath: null, content: \"\", exists: false, resolvedTitle: pageName };\n const content = readFileOrEmpty(path.join(locations.pagesReal, fileName), locations.workspaceReal);\n return { filePath: path.join(locations.pagesDir, fileName), content, exists: true, resolvedTitle: path.basename(fileName, \".md\") };\n}\n\n/** Page body, or \"\" when the file vanished between indexing and reading. */\nasync function readPageBody(locations: WikiReadLocations, fileName: string): Promise<string> {\n const { pagesReal, workspaceReal } = locations;\n return pagesReal === null || workspaceReal === null ? \"\" : ((await readTextSafe(path.join(pagesReal, fileName), workspaceReal)) ?? \"\");\n}\n\n/** Read every page + the index and build the page→page link graph.\n * No cache: the graph is requested explicitly and a content edit does\n * not advance the pagesDir mtime the page index caches on. */\nexport async function loadWikiGraph(workspace: string): Promise<WikiGraph> {\n const locations = wikiReadLocations(workspace);\n const slugs = await pageSlugs(locations);\n const pages = await Promise.all([...slugs.entries()].map(async ([slug, fileName]) => ({ slug, content: await readPageBody(locations, fileName) })));\n const indexEntries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n return buildWikiGraph(pages, indexEntries);\n}\n\nexport interface PageBody {\n fileName: string;\n content: string;\n}\n\nasync function readPageBodies(locations: WikiReadLocations, fileNames: readonly string[]): Promise<PageBody[]> {\n return Promise.all(fileNames.map(async (fileName) => ({ fileName, content: await readPageBody(locations, fileName) })));\n}\n\n/** Frontmatter `tags:` per page, keyed for `findTagDrift`. Lowercased so\n * a `MyPage.md` filename matches an `entry.slug` of `mypage`, which is\n * what the drift rule looks up. */\nexport function frontmatterTagIndex(bodies: readonly PageBody[]): Map<string, string[]> {\n const tagsBySlug = new Map<string, string[]>();\n bodies.forEach(({ fileName, content }) => {\n tagsBySlug.set(fileName.replace(/\\.md$/i, \"\").toLowerCase(), parseFrontmatterTags(content));\n });\n return tagsBySlug;\n}\n\n/** Run every lint rule over the on-disk wiki, returning issue strings. */\nexport async function collectLintIssues(workspace: string): Promise<string[]> {\n const locations = wikiReadLocations(workspace);\n const slugs = await pageSlugs(locations);\n if (slugs.size === 0 || locations.pagesReal === null) {\n return [\"- Wiki `pages/` directory does not exist yet. Start ingesting sources.\"];\n }\n const pageEntries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n const fileSlugs = new Set(slugs.keys());\n const slugByTitle = slugByIndexTitle(pageEntries);\n const bodies = await readPageBodies(locations, [...slugs.values()]);\n return [\n ...findOrphanPages(fileSlugs, new Set(pageEntries.map((entry) => entry.slug))),\n ...findMissingFiles(pageEntries, fileSlugs),\n ...bodies.flatMap(({ fileName, content }) => findBrokenLinksInPage(fileName, content, fileSlugs, slugByTitle)),\n ...findTagDrift(pageEntries, frontmatterTagIndex(bodies)),\n ];\n}\n"],"mappings":";;;;;;;;;;;;AAcA,IAAM,aAAaA,QAAAA,UAAU,YAAYA,QAAAA,UAAU,cAAc,MAAMA,QAAAA,UAAU,cAAc;AAG/F,SAAgB,SAAS,UAAkB,eAAgC;CACzE,MAAM,MAAMC,UAAAA,QAAK,SAAS,UAAU,aAAa;CACjD,OAAO,QAAQ,QAAQ,CAAC,IAAI,WAAW,KAAKA,UAAAA,QAAK,KAAK,KAAK,CAACA,UAAAA,QAAK,WAAW,GAAG;AACjF;AAIA,SAAgB,eAAe,SAAgC;CAC7D,IAAI;EACF,OAAOC,QAAAA,aAAa,OAAO,OAAO;CACpC,SAAS,KAAK;EACZ,OAAOC,aAAAA,SAAS,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AC;AACxH;;;;AAKA,SAAgB,oBAAoB,QAAoD;CACtF,MAAM,6BAAa,IAAI,IAAsB;CAC7C,OAAO,SAAS,EAAE,UAAU,cAAc;EACxC,WAAW,IAAI,SAAS,QAAQ,UAAU,EAAE,CAAC,CAAC,YAAY,GAAG,qBAAqB,OAAO,CAAC;CAC5F,CAAC;CACD,OAAO;AACT;;AAGA,eAAsB,kBAAkB,WAAsC;CAC5E,MAAM,YAAY,kBAAkB,SAAS;CAC7C,MAAM,QAAQ,MAAM,UAAU,SAAS;CACvC,IAAI,MAAM,SAAS,KAAK,UAAU,cAAc,MAC9C,OAAO,CAAC,wEAAwE;CAElF,MAAM,cAAcL,cAAAA,kBAAkB,gBAAgB,UAAU,WAAW,UAAU,aAAa,CAAC;CACnG,MAAM,YAAY,IAAI,IAAI,MAAM,KAAK,CAAC;CACtC,MAAM,cAAcM,cAAAA,iBAAiB,WAAW;CAChD,MAAM,SAAS,MAAM,eAAe,WAAW,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC;CAClE,OAAO;EACL,GAAGC,cAAAA,gBAAgB,WAAW,IAAI,IAAI,YAAY,KAAK,UAAU,MAAM,IAAI,CAAC,CAAC;EAC7E,GAAGC,cAAAA,iBAAiB,aAAa,SAAS;EAC1C,GAAG,OAAO,SAAS,EAAE,UAAU,cAAcC,cAAAA,sBAAsB,UAAU,SAAS,WAAW,WAAW,CAAC;EAC7G,GAAGC,cAAAA,aAAa,aAAa,oBAAoB,MAAM,CAAC;CAC1D;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["stat","readdir","parseFrontmatter","wikiDirs","realpathSyncOrNull","path","isWithinRoot","readTextWithinRootSync","parseIndexEntries","path","parseWikiLink","matchWikiSlug","wikiSlugify","readTextWithinRoot","buildWikiGraph","slugByIndexTitle","findOrphanPages","findMissingFiles","findBrokenLinksInPage","findTagDrift"],"sources":["../../../src/wiki/server/fs.ts","../../../src/wiki/server/pageIndex.ts","../../../src/wiki/server/frontmatter.ts","../../../src/wiki/server/locations.ts","../../../src/wiki/server/engine.ts"],"sourcesContent":["// Minimal ENOENT-swallowing fs wrappers for the wiki read-engine.\n// Self-contained (core can't reach the host's `server/utils/files/safe.ts`);\n// only the handful of helpers the wiki engine needs. Same \"return\n// null / [] on any error\" contract so callers branch on the value\n// instead of try/catch.\n\nimport type { Dirent, Stats } from \"node:fs\";\nimport { readdir, stat } from \"node:fs/promises\";\n\nexport async function statSafeAsync(absPath: string): Promise<Stats | null> {\n try {\n return await stat(absPath);\n } catch {\n return null;\n }\n}\n\nexport async function readDirSafeAsync(absPath: string): Promise<Dirent[]> {\n try {\n return await readdir(absPath, { withFileTypes: true });\n } catch {\n return [];\n }\n}\n","// In-memory index of `<pagesDir>/*.md` keyed by slug (= filename\n// without the `.md` extension). Kept fresh via `pagesDir` mtime —\n// adding, removing, or renaming a file under `pagesDir` advances the\n// directory's mtime on every major filesystem we target (macOS APFS,\n// Linux ext4, Windows NTFS), so one cheap `stat()` per request is\n// enough to decide whether to rebuild.\n\nimport { readDirSafeAsync, statSafeAsync } from \"./fs.js\";\n\nexport interface PageIndex {\n mtimeMs: number;\n /** slug → filename (e.g. \"sakura-internet\" → \"sakura-internet.md\"). */\n slugs: Map<string, string>;\n}\n\n// Keyed by `pagesDir`: the engine is workspace-injected and may be\n// called with more than one pages directory in a single process. A\n// single global slot would let one workspace's slug map be returned\n// for another whenever their mtimes happen to tie (Codex P2 on #1876).\nconst cache = new Map<string, PageIndex>();\n\n/**\n * Get the page index for `pagesDir`. Returns a cached value as long as\n * THAT directory's mtime hasn't advanced; otherwise rebuilds. Safe to\n * call concurrently — racing builds produce the same result.\n */\nexport async function getPageIndex(pagesDir: string): Promise<PageIndex> {\n const stat = await statSafeAsync(pagesDir);\n if (!stat) {\n // Dir doesn't exist yet (never ingested). Return empty but don't\n // cache a stale-forever value — the next call re-stats.\n return { mtimeMs: 0, slugs: new Map() };\n }\n const cached = cache.get(pagesDir);\n if (cached && cached.mtimeMs >= stat.mtimeMs) return cached;\n const entries = await readDirSafeAsync(pagesDir);\n const slugs = new Map<string, string>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const { name } = entry;\n if (!name.endsWith(\".md\")) continue;\n slugs.set(name.slice(0, -\".md\".length), name);\n }\n const built: PageIndex = { mtimeMs: stat.mtimeMs, slugs };\n cache.set(pagesDir, built);\n return built;\n}\n\n/** Test-only: drop the module-level cache (all directories). */\nexport function __resetPageIndexCache(): void {\n cache.clear();\n}\n","// Read-side frontmatter helpers for the wiki engine. The generic\n// `---\\n…\\n---\\n` envelope parsing is the canonical value-preserving\n// (FAILSAFE_SCHEMA) parser in `@mulmoclaude/markdown-utils`; only the\n// wiki-specific `tags:` reader stays here. Re-exporting `parseFrontmatter`\n// keeps the `@mulmoclaude/core/wiki/server` barrel surface stable — it now\n// returns the richer `{ meta, body, hasHeader }` shape.\n\nimport { parseFrontmatter } from \"@mulmoclaude/markdown-utils/markdown/frontmatter\";\n\nexport { parseFrontmatter };\n\nfunction cleanTagToken(token: string): string {\n return token\n .trim()\n .replace(/^['\"]|['\"]$/g, \"\")\n .replace(/^#/, \"\")\n .toLowerCase();\n}\n\n/** Narrow `tags:` reader. Handles flow (`tags: [a, b]`) and block-list\n * style; anything unparseable returns `[]` (best-effort, never throws). */\nexport function parseFrontmatterTags(content: string): string[] {\n const parsed = parseFrontmatter(content);\n if (!parsed.hasHeader) return [];\n const tagsValue = parsed.meta.tags;\n if (!Array.isArray(tagsValue)) return [];\n return tagsValue\n .filter((item): item is string => typeof item === \"string\")\n .map(cleanTagToken)\n .filter((token) => token.length > 0);\n}\n","// A wiki folder or file that leads out of the workspace counts as absent, so nothing outside is listed or read.\n\nimport path from \"node:path\";\nimport { isWithinRoot, realpathSyncOrNull } from \"../../files/withinRoot.js\";\nimport { wikiDirs } from \"./paths.js\";\n\nexport interface WikiReadLocations {\n /** `<workspace>/data/wiki/pages` as the caller spelled it: resolved page paths handed back are joined onto this. */\n pagesDir: string;\n /** The workspace's realpath: every read re-checks against it after opening. */\n workspaceReal: string | null;\n pagesReal: string | null;\n indexReal: string | null;\n logReal: string | null;\n}\n\nexport function wikiReadLocations(workspace: string): WikiReadLocations {\n const dirs = wikiDirs(workspace);\n const workspaceReal = realpathSyncOrNull(workspace);\n const insideWorkspace = (absPath: string): string | null => {\n const candidateReal = workspaceReal === null ? null : realpathSyncOrNull(path.resolve(workspaceReal, path.relative(workspace, absPath)));\n return workspaceReal !== null && candidateReal !== null && isWithinRoot(workspaceReal, candidateReal) ? candidateReal : null;\n };\n return {\n pagesDir: dirs.pagesDir,\n workspaceReal,\n pagesReal: insideWorkspace(dirs.pagesDir),\n indexReal: insideWorkspace(dirs.indexFile),\n logReal: insideWorkspace(dirs.logFile),\n };\n}\n","// Workspace-injected wiki read-engine — the filesystem layer that feeds\n// the pure helpers in `@mulmoclaude/core/wiki`. Shared by every host so\n// the two apps reading the same `data/wiki/` can't disagree on slug\n// resolution, graph edges, or lint findings. Mirrors the bodies that\n// previously lived in MulmoClaude's `server/api/routes/wiki.ts`; the\n// hosts keep only their HTTP response shaping on top.\n//\n// The read/write WRITE side (writeWikiPage / snapshots) stays host-side\n// until a host needs it shared.\n\nimport path from \"node:path\";\nimport { parseWikiLink } from \"../link.js\";\nimport { wikiSlugify } from \"../slug.js\";\nimport { matchWikiSlug, slugByIndexTitle } from \"../resolve.js\";\nimport { type WikiPageEntry, parseIndexEntries } from \"../index-parse.js\";\nimport { findBrokenLinksInPage, findMissingFiles, findOrphanPages, findTagDrift } from \"../lint.js\";\nimport { type WikiGraph, buildWikiGraph } from \"../graph.js\";\nimport { readTextWithinRoot, readTextWithinRootSync } from \"../../files/withinRoot.js\";\nimport { getPageIndex } from \"./pageIndex.js\";\nimport { parseFrontmatterTags } from \"./frontmatter.js\";\nimport { type WikiReadLocations, wikiReadLocations } from \"./locations.js\";\n\n// Below this length the fuzzy `includes` step is skipped — CJK /\n// emoji-only / very-short page names slugify down to a short noise\n// tail that partial-matches almost anything; the index.md title-match\n// fallback still handles the legitimate non-ASCII case (#1194).\nconst MIN_FUZZY_SLUG_LEN = 6;\n\nfunction readFileOrEmpty(absPath: string | null, workspaceReal: string | null): string {\n return absPath === null || workspaceReal === null ? \"\" : (readTextWithinRootSync(workspaceReal, absPath) ?? \"\");\n}\n\nasync function pageSlugs(locations: WikiReadLocations): Promise<Map<string, string>> {\n return locations.pagesReal === null ? new Map() : (await getPageIndex(locations.pagesReal)).slugs;\n}\n\n/** Walk every indexed slug for an `includes`-style match. Returns the\n * single best candidate, or null when the slug is too short OR several\n * candidates tie at the top score (ambiguous → defer to the caller's\n * title-match fallback). Score = min/max length, decoupled from Map\n * iteration order so resolution is deterministic across hosts. */\nexport function pickFuzzyMatch(slug: string, slugs: ReadonlyMap<string, string>): string | null {\n if (slug.length < MIN_FUZZY_SLUG_LEN) return null;\n let bestFile: string | null = null;\n let bestScore = 0;\n let bestIsTied = false;\n for (const [key, file] of slugs) {\n if (!slug.includes(key) && !key.includes(slug)) continue;\n const shorter = Math.min(slug.length, key.length);\n const longer = Math.max(slug.length, key.length);\n const score = shorter / longer;\n if (score > bestScore) {\n bestScore = score;\n bestFile = file;\n bestIsTied = false;\n } else if (score === bestScore) {\n bestIsTied = true;\n }\n }\n return bestIsTied ? null : bestFile;\n}\n\n/** File matching an index.md entry whose title equals `target` — the\n * last resort for a link written as the display title rather than\n * the page's own name. */\nfunction fileByIndexTitle(locations: WikiReadLocations, target: string, slugs: ReadonlyMap<string, string>): string | undefined {\n const entries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n const trimmed = target.trim();\n const titleMatch = entries.find((entry) => entry.title === trimmed);\n return titleMatch ? slugs.get(titleMatch.slug) : undefined;\n}\n\n/** Resolve a page name to an absolute `.md` path: known slug (literal\n * or slugified) → fuzzy → index-title fallback. `pageName` may carry\n * the `[[target|display]]` form; `parseWikiLink` strips the display\n * half so the lookup uses just the target. */\nexport async function resolvePagePath(workspace: string, pageName: string): Promise<string | null> {\n const locations = wikiReadLocations(workspace);\n const fileName = await resolvePageFile(locations, pageName);\n return fileName === null ? null : path.join(locations.pagesDir, fileName);\n}\n\nasync function resolvePageFile(locations: WikiReadLocations, pageName: string): Promise<string | null> {\n const slugs = await pageSlugs(locations);\n if (slugs.size === 0) return null;\n\n const { target } = parseWikiLink(pageName);\n const matched = matchWikiSlug(target, slugs);\n const matchedFile = matched === null ? undefined : slugs.get(matched);\n if (matchedFile) return matchedFile;\n\n const fuzzy = pickFuzzyMatch(wikiSlugify(target), slugs);\n if (fuzzy) return fuzzy;\n\n return fileByIndexTitle(locations, target, slugs) ?? null;\n}\n\n/** Raw `index.md` content + its parsed entries. */\nexport function readWikiIndex(workspace: string): { content: string; entries: WikiPageEntry[] } {\n const locations = wikiReadLocations(workspace);\n const content = readFileOrEmpty(locations.indexReal, locations.workspaceReal);\n return { content, entries: parseIndexEntries(content) };\n}\n\n/** Raw `log.md` content (empty string if absent). */\nexport function readWikiLog(workspace: string): string {\n const locations = wikiReadLocations(workspace);\n return readFileOrEmpty(locations.logReal, locations.workspaceReal);\n}\n\nexport interface WikiPageRead {\n /** Absolute path of the resolved file, or null when nothing matched. */\n filePath: string | null;\n /** File body (empty when missing OR when the file is an empty placeholder). */\n content: string;\n /** True iff a page file resolved (distinct from empty content). */\n exists: boolean;\n /** Title to display — the resolved filename stem, or the raw pageName. */\n resolvedTitle: string;\n}\n\n/** Resolve + read a page. Distinguishes missing (`exists: false`) from\n * empty-but-present (`exists: true`, `content: \"\"`). */\nexport async function readWikiPage(workspace: string, pageName: string): Promise<WikiPageRead> {\n const locations = wikiReadLocations(workspace);\n const fileName = await resolvePageFile(locations, pageName);\n if (fileName === null || locations.pagesReal === null) return { filePath: null, content: \"\", exists: false, resolvedTitle: pageName };\n const content = readFileOrEmpty(path.join(locations.pagesReal, fileName), locations.workspaceReal);\n return { filePath: path.join(locations.pagesDir, fileName), content, exists: true, resolvedTitle: path.basename(fileName, \".md\") };\n}\n\n/** Page body, or \"\" when the file vanished between indexing and reading. */\nasync function readPageBody(locations: WikiReadLocations, fileName: string): Promise<string> {\n const { pagesReal, workspaceReal } = locations;\n return pagesReal === null || workspaceReal === null ? \"\" : ((await readTextWithinRoot(workspaceReal, path.join(pagesReal, fileName))) ?? \"\");\n}\n\n/** Read every page + the index and build the page→page link graph.\n * No cache: the graph is requested explicitly and a content edit does\n * not advance the pagesDir mtime the page index caches on. */\nexport async function loadWikiGraph(workspace: string): Promise<WikiGraph> {\n const locations = wikiReadLocations(workspace);\n const slugs = await pageSlugs(locations);\n const pages = await Promise.all([...slugs.entries()].map(async ([slug, fileName]) => ({ slug, content: await readPageBody(locations, fileName) })));\n const indexEntries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n return buildWikiGraph(pages, indexEntries);\n}\n\nexport interface PageBody {\n fileName: string;\n content: string;\n}\n\nasync function readPageBodies(locations: WikiReadLocations, fileNames: readonly string[]): Promise<PageBody[]> {\n return Promise.all(fileNames.map(async (fileName) => ({ fileName, content: await readPageBody(locations, fileName) })));\n}\n\n/** Frontmatter `tags:` per page, keyed for `findTagDrift`. Lowercased so\n * a `MyPage.md` filename matches an `entry.slug` of `mypage`, which is\n * what the drift rule looks up. */\nexport function frontmatterTagIndex(bodies: readonly PageBody[]): Map<string, string[]> {\n const tagsBySlug = new Map<string, string[]>();\n bodies.forEach(({ fileName, content }) => {\n tagsBySlug.set(fileName.replace(/\\.md$/i, \"\").toLowerCase(), parseFrontmatterTags(content));\n });\n return tagsBySlug;\n}\n\n/** Run every lint rule over the on-disk wiki, returning issue strings. */\nexport async function collectLintIssues(workspace: string): Promise<string[]> {\n const locations = wikiReadLocations(workspace);\n const slugs = await pageSlugs(locations);\n if (slugs.size === 0 || locations.pagesReal === null) {\n return [\"- Wiki `pages/` directory does not exist yet. Start ingesting sources.\"];\n }\n const pageEntries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n const fileSlugs = new Set(slugs.keys());\n const slugByTitle = slugByIndexTitle(pageEntries);\n const bodies = await readPageBodies(locations, [...slugs.values()]);\n return [\n ...findOrphanPages(fileSlugs, new Set(pageEntries.map((entry) => entry.slug))),\n ...findMissingFiles(pageEntries, fileSlugs),\n ...bodies.flatMap(({ fileName, content }) => findBrokenLinksInPage(fileName, content, fileSlugs, slugByTitle)),\n ...findTagDrift(pageEntries, frontmatterTagIndex(bodies)),\n ];\n}\n"],"mappings":";;;;;;;;;;;AASA,eAAsB,cAAc,SAAwC;CAC1E,IAAI;EACF,OAAO,OAAA,GAAMA,iBAAAA,KAAAA,CAAK,OAAO;CAC3B,QAAQ;EACN,OAAO;CACT;AACF;AAEA,eAAsB,iBAAiB,SAAoC;CACzE,IAAI;EACF,OAAO,OAAA,GAAMC,iBAAAA,QAAAA,CAAQ,SAAS,EAAE,eAAe,KAAK,CAAC;CACvD,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;ACJA,IAAM,wBAAQ,IAAI,IAAuB;;;;;;AAOzC,eAAsB,aAAa,UAAsC;CACvE,MAAM,OAAO,MAAM,cAAc,QAAQ;CACzC,IAAI,CAAC,MAGH,OAAO;EAAE,SAAS;EAAG,uBAAO,IAAI,IAAI;CAAE;CAExC,MAAM,SAAS,MAAM,IAAI,QAAQ;CACjC,IAAI,UAAU,OAAO,WAAW,KAAK,SAAS,OAAO;CACrD,MAAM,UAAU,MAAM,iBAAiB,QAAQ;CAC/C,MAAM,wBAAQ,IAAI,IAAoB;CACtC,KAAK,MAAM,SAAS,SAAS;EAC3B,IAAI,CAAC,MAAM,OAAO,GAAG;EACrB,MAAM,EAAE,SAAS;EACjB,IAAI,CAAC,KAAK,SAAS,KAAK,GAAG;EAC3B,MAAM,IAAI,KAAK,MAAM,GAAG,EAAa,GAAG,IAAI;CAC9C;CACA,MAAM,QAAmB;EAAE,SAAS,KAAK;EAAS;CAAM;CACxD,MAAM,IAAI,UAAU,KAAK;CACzB,OAAO;AACT;;AAGA,SAAgB,wBAA8B;CAC5C,MAAM,MAAM;AACd;;ACxCA,SAAS,cAAc,O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AW,WAAW,CAAC;EAC7G,GAAGC,cAAAA,aAAa,aAAa,oBAAoB,MAAM,CAAC;CAC1D;AACF"}
@@ -1,64 +1,11 @@
1
1
  import { wikiDirs, wikiSlugFromAbsPath } from "../paths.js";
2
- import { t as isEnoent } from "../../safe-DRNa8UBp.js";
3
2
  import { a as findMissingFiles, b as parseWikiLink, g as matchWikiSlug, i as findBrokenLinksInPage, m as parseIndexEntries, o as findOrphanPages, s as findTagDrift, t as buildWikiGraph, v as slugByIndexTitle } from "../../graph-DBbzemby.js";
4
3
  import { r as wikiSlugify } from "../../slug-D24AYqCZ.js";
5
- import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, realpathSync } from "node:fs";
4
+ import { i as realpathSyncOrNull, n as readTextWithinRoot, r as readTextWithinRootSync, t as isWithinRoot } from "../../withinRoot-Bbj6E-Lf.js";
6
5
  import path from "node:path";
7
- import { open, readdir, stat } from "node:fs/promises";
6
+ import { readdir, stat } from "node:fs/promises";
8
7
  import { parseFrontmatter } from "@mulmoclaude/markdown-utils/markdown/frontmatter";
9
8
  // src/wiki/server/fs.ts
10
- var READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
11
- function isWithin(rootReal, candidateReal) {
12
- const rel = path.relative(rootReal, candidateReal);
13
- return rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
14
- }
15
- function realpathOrNull(absPath) {
16
- try {
17
- return realpathSync.native(absPath);
18
- } catch (err) {
19
- return isEnoent(err) ? null : jsRealpathOrNull(absPath);
20
- }
21
- }
22
- function jsRealpathOrNull(absPath) {
23
- try {
24
- return realpathSync(absPath);
25
- } catch {
26
- return null;
27
- }
28
- }
29
- function isOpenedFileInside(absPath, rootReal, opened) {
30
- const real = realpathOrNull(absPath);
31
- if (real === null || !isWithin(rootReal, real) || !opened.isFile()) return false;
32
- const onDisk = lstatSync(real, { bigint: true });
33
- return onDisk.isFile() && onDisk.dev === opened.dev && onDisk.ino === opened.ino;
34
- }
35
- /** Text of a regular file inside `rootReal`, or null when it is missing, leads outside, is a FIFO or other non-file,
36
- * or is unreadable. */
37
- async function readTextSafe(absPath, rootReal) {
38
- try {
39
- const handle = await open(absPath, READ_FLAGS);
40
- try {
41
- return isOpenedFileInside(absPath, rootReal, await handle.stat({ bigint: true })) ? await handle.readFile("utf-8") : null;
42
- } finally {
43
- await handle.close();
44
- }
45
- } catch {
46
- return null;
47
- }
48
- }
49
- /** Sync twin of `readTextSafe`. */
50
- function readTextSafeSync(absPath, rootReal) {
51
- try {
52
- const descriptor = openSync(absPath, READ_FLAGS);
53
- try {
54
- return isOpenedFileInside(absPath, rootReal, fstatSync(descriptor, { bigint: true })) ? readFileSync(descriptor, "utf-8") : null;
55
- } finally {
56
- closeSync(descriptor);
57
- }
58
- } catch {
59
- return null;
60
- }
61
- }
62
9
  async function statSafeAsync(absPath) {
63
10
  try {
64
11
  return await stat(absPath);
@@ -123,10 +70,10 @@ function parseFrontmatterTags(content) {
123
70
  // src/wiki/server/locations.ts
124
71
  function wikiReadLocations(workspace) {
125
72
  const dirs = wikiDirs(workspace);
126
- const workspaceReal = realpathOrNull(workspace);
73
+ const workspaceReal = realpathSyncOrNull(workspace);
127
74
  const insideWorkspace = (absPath) => {
128
- const candidateReal = workspaceReal === null ? null : realpathOrNull(path.resolve(workspaceReal, path.relative(workspace, absPath)));
129
- return workspaceReal !== null && candidateReal !== null && isWithin(workspaceReal, candidateReal) ? candidateReal : null;
75
+ const candidateReal = workspaceReal === null ? null : realpathSyncOrNull(path.resolve(workspaceReal, path.relative(workspace, absPath)));
76
+ return workspaceReal !== null && candidateReal !== null && isWithinRoot(workspaceReal, candidateReal) ? candidateReal : null;
130
77
  };
131
78
  return {
132
79
  pagesDir: dirs.pagesDir,
@@ -139,7 +86,7 @@ function wikiReadLocations(workspace) {
139
86
  // src/wiki/server/engine.ts
140
87
  var MIN_FUZZY_SLUG_LEN = 6;
141
88
  function readFileOrEmpty(absPath, workspaceReal) {
142
- return absPath === null || workspaceReal === null ? "" : readTextSafeSync(absPath, workspaceReal) ?? "";
89
+ return absPath === null || workspaceReal === null ? "" : readTextWithinRootSync(workspaceReal, absPath) ?? "";
143
90
  }
144
91
  async function pageSlugs(locations) {
145
92
  return locations.pagesReal === null ? /* @__PURE__ */ new Map() : (await getPageIndex(locations.pagesReal)).slugs;
@@ -230,7 +177,7 @@ async function readWikiPage(workspace, pageName) {
230
177
  /** Page body, or "" when the file vanished between indexing and reading. */
231
178
  async function readPageBody(locations, fileName) {
232
179
  const { pagesReal, workspaceReal } = locations;
233
- return pagesReal === null || workspaceReal === null ? "" : await readTextSafe(path.join(pagesReal, fileName), workspaceReal) ?? "";
180
+ return pagesReal === null || workspaceReal === null ? "" : await readTextWithinRoot(workspaceReal, path.join(pagesReal, fileName)) ?? "";
234
181
  }
235
182
  /** Read every page + the index and build the page→page link graph.
236
183
  * No cache: the graph is requested explicitly and a content edit does
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/wiki/server/fs.ts","../../../src/wiki/server/pageIndex.ts","../../../src/wiki/server/frontmatter.ts","../../../src/wiki/server/locations.ts","../../../src/wiki/server/engine.ts"],"sourcesContent":["// Minimal ENOENT-swallowing fs wrappers for the wiki read-engine.\n// Self-contained (core can't reach the host's `server/utils/files/safe.ts`);\n// only the handful of helpers the wiki engine needs. Same \"return\n// null / [] on any error\" contract so callers branch on the value\n// instead of try/catch.\n\nimport type { BigIntStats, Dirent, Stats } from \"node:fs\";\nimport { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, realpathSync } from \"node:fs\";\nimport { open, readdir, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { isEnoent } from \"../../files/safe.js\";\n\n// A FIFO must not block the server, and a link is refused at open where the OS can; both flags are undefined on\n// Windows, where the check after the open is what refuses a link out.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);\n\n// `path.relative` rather than a `rootReal + sep` prefix, which a workspace at a filesystem root (`/`, `C:\\`) would fail.\nexport function isWithin(rootReal: string, candidateReal: string): boolean {\n const rel = path.relative(rootReal, candidateReal);\n return rel !== \"..\" && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);\n}\n\n// Native first: the JS realpath keeps a link's letter case, so on a case-insensitive disk an inside link looks outside.\n// The JS one is the fallback for drives where the native call throws (EISDIR on some Windows RAM disks).\nexport function realpathOrNull(absPath: string): string | null {\n try {\n return realpathSync.native(absPath);\n } catch (err) {\n return isEnoent(err) ? null : jsRealpathOrNull(absPath);\n }\n}\n\nfunction jsRealpathOrNull(absPath: string): string | null {\n try {\n return realpathSync(absPath);\n } catch {\n return null;\n }\n}\n\n// Checked after the open, so a folder or file swapped for a link out between the caller's check and the open, or\n// swapped back before this check, is refused: where the path leads now must be inside and be the opened file.\nfunction isOpenedFileInside(absPath: string, rootReal: string, opened: BigIntStats): boolean {\n const real = realpathOrNull(absPath);\n if (real === null || !isWithin(rootReal, real) || !opened.isFile()) return false;\n const onDisk = lstatSync(real, { bigint: true });\n return onDisk.isFile() && onDisk.dev === opened.dev && onDisk.ino === opened.ino;\n}\n\n/** Text of a regular file inside `rootReal`, or null when it is missing, leads outside, is a FIFO or other non-file,\n * or is unreadable. */\nexport async function readTextSafe(absPath: string, rootReal: string): Promise<string | null> {\n try {\n const handle = await open(absPath, READ_FLAGS);\n try {\n return isOpenedFileInside(absPath, rootReal, await handle.stat({ bigint: true })) ? await handle.readFile(\"utf-8\") : null;\n } finally {\n await handle.close();\n }\n } catch {\n return null;\n }\n}\n\n/** Sync twin of `readTextSafe`. */\nexport function readTextSafeSync(absPath: string, rootReal: string): string | null {\n try {\n const descriptor = openSync(absPath, READ_FLAGS);\n try {\n return isOpenedFileInside(absPath, rootReal, fstatSync(descriptor, { bigint: true })) ? readFileSync(descriptor, \"utf-8\") : null;\n } finally {\n closeSync(descriptor);\n }\n } catch {\n return null;\n }\n}\n\nexport async function statSafeAsync(absPath: string): Promise<Stats | null> {\n try {\n return await stat(absPath);\n } catch {\n return null;\n }\n}\n\nexport async function readDirSafeAsync(absPath: string): Promise<Dirent[]> {\n try {\n return await readdir(absPath, { withFileTypes: true });\n } catch {\n return [];\n }\n}\n","// In-memory index of `<pagesDir>/*.md` keyed by slug (= filename\n// without the `.md` extension). Kept fresh via `pagesDir` mtime —\n// adding, removing, or renaming a file under `pagesDir` advances the\n// directory's mtime on every major filesystem we target (macOS APFS,\n// Linux ext4, Windows NTFS), so one cheap `stat()` per request is\n// enough to decide whether to rebuild.\n\nimport { readDirSafeAsync, statSafeAsync } from \"./fs.js\";\n\nexport interface PageIndex {\n mtimeMs: number;\n /** slug → filename (e.g. \"sakura-internet\" → \"sakura-internet.md\"). */\n slugs: Map<string, string>;\n}\n\n// Keyed by `pagesDir`: the engine is workspace-injected and may be\n// called with more than one pages directory in a single process. A\n// single global slot would let one workspace's slug map be returned\n// for another whenever their mtimes happen to tie (Codex P2 on #1876).\nconst cache = new Map<string, PageIndex>();\n\n/**\n * Get the page index for `pagesDir`. Returns a cached value as long as\n * THAT directory's mtime hasn't advanced; otherwise rebuilds. Safe to\n * call concurrently — racing builds produce the same result.\n */\nexport async function getPageIndex(pagesDir: string): Promise<PageIndex> {\n const stat = await statSafeAsync(pagesDir);\n if (!stat) {\n // Dir doesn't exist yet (never ingested). Return empty but don't\n // cache a stale-forever value — the next call re-stats.\n return { mtimeMs: 0, slugs: new Map() };\n }\n const cached = cache.get(pagesDir);\n if (cached && cached.mtimeMs >= stat.mtimeMs) return cached;\n const entries = await readDirSafeAsync(pagesDir);\n const slugs = new Map<string, string>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const { name } = entry;\n if (!name.endsWith(\".md\")) continue;\n slugs.set(name.slice(0, -\".md\".length), name);\n }\n const built: PageIndex = { mtimeMs: stat.mtimeMs, slugs };\n cache.set(pagesDir, built);\n return built;\n}\n\n/** Test-only: drop the module-level cache (all directories). */\nexport function __resetPageIndexCache(): void {\n cache.clear();\n}\n","// Read-side frontmatter helpers for the wiki engine. The generic\n// `---\\n…\\n---\\n` envelope parsing is the canonical value-preserving\n// (FAILSAFE_SCHEMA) parser in `@mulmoclaude/markdown-utils`; only the\n// wiki-specific `tags:` reader stays here. Re-exporting `parseFrontmatter`\n// keeps the `@mulmoclaude/core/wiki/server` barrel surface stable — it now\n// returns the richer `{ meta, body, hasHeader }` shape.\n\nimport { parseFrontmatter } from \"@mulmoclaude/markdown-utils/markdown/frontmatter\";\n\nexport { parseFrontmatter };\n\nfunction cleanTagToken(token: string): string {\n return token\n .trim()\n .replace(/^['\"]|['\"]$/g, \"\")\n .replace(/^#/, \"\")\n .toLowerCase();\n}\n\n/** Narrow `tags:` reader. Handles flow (`tags: [a, b]`) and block-list\n * style; anything unparseable returns `[]` (best-effort, never throws). */\nexport function parseFrontmatterTags(content: string): string[] {\n const parsed = parseFrontmatter(content);\n if (!parsed.hasHeader) return [];\n const tagsValue = parsed.meta.tags;\n if (!Array.isArray(tagsValue)) return [];\n return tagsValue\n .filter((item): item is string => typeof item === \"string\")\n .map(cleanTagToken)\n .filter((token) => token.length > 0);\n}\n","// A wiki folder or file that leads out of the workspace counts as absent, so nothing outside is listed or read.\n\nimport path from \"node:path\";\nimport { isWithin, realpathOrNull } from \"./fs.js\";\nimport { wikiDirs } from \"./paths.js\";\n\nexport interface WikiReadLocations {\n /** `<workspace>/data/wiki/pages` as the caller spelled it: resolved page paths handed back are joined onto this. */\n pagesDir: string;\n /** The workspace's realpath: every read re-checks against it after opening. */\n workspaceReal: string | null;\n pagesReal: string | null;\n indexReal: string | null;\n logReal: string | null;\n}\n\nexport function wikiReadLocations(workspace: string): WikiReadLocations {\n const dirs = wikiDirs(workspace);\n const workspaceReal = realpathOrNull(workspace);\n const insideWorkspace = (absPath: string): string | null => {\n const candidateReal = workspaceReal === null ? null : realpathOrNull(path.resolve(workspaceReal, path.relative(workspace, absPath)));\n return workspaceReal !== null && candidateReal !== null && isWithin(workspaceReal, candidateReal) ? candidateReal : null;\n };\n return {\n pagesDir: dirs.pagesDir,\n workspaceReal,\n pagesReal: insideWorkspace(dirs.pagesDir),\n indexReal: insideWorkspace(dirs.indexFile),\n logReal: insideWorkspace(dirs.logFile),\n };\n}\n","// Workspace-injected wiki read-engine — the filesystem layer that feeds\n// the pure helpers in `@mulmoclaude/core/wiki`. Shared by every host so\n// the two apps reading the same `data/wiki/` can't disagree on slug\n// resolution, graph edges, or lint findings. Mirrors the bodies that\n// previously lived in MulmoClaude's `server/api/routes/wiki.ts`; the\n// hosts keep only their HTTP response shaping on top.\n//\n// The read/write WRITE side (writeWikiPage / snapshots) stays host-side\n// until a host needs it shared.\n\nimport path from \"node:path\";\nimport { parseWikiLink } from \"../link.js\";\nimport { wikiSlugify } from \"../slug.js\";\nimport { matchWikiSlug, slugByIndexTitle } from \"../resolve.js\";\nimport { type WikiPageEntry, parseIndexEntries } from \"../index-parse.js\";\nimport { findBrokenLinksInPage, findMissingFiles, findOrphanPages, findTagDrift } from \"../lint.js\";\nimport { type WikiGraph, buildWikiGraph } from \"../graph.js\";\nimport { readTextSafe, readTextSafeSync } from \"./fs.js\";\nimport { getPageIndex } from \"./pageIndex.js\";\nimport { parseFrontmatterTags } from \"./frontmatter.js\";\nimport { type WikiReadLocations, wikiReadLocations } from \"./locations.js\";\n\n// Below this length the fuzzy `includes` step is skipped — CJK /\n// emoji-only / very-short page names slugify down to a short noise\n// tail that partial-matches almost anything; the index.md title-match\n// fallback still handles the legitimate non-ASCII case (#1194).\nconst MIN_FUZZY_SLUG_LEN = 6;\n\nfunction readFileOrEmpty(absPath: string | null, workspaceReal: string | null): string {\n return absPath === null || workspaceReal === null ? \"\" : (readTextSafeSync(absPath, workspaceReal) ?? \"\");\n}\n\nasync function pageSlugs(locations: WikiReadLocations): Promise<Map<string, string>> {\n return locations.pagesReal === null ? new Map() : (await getPageIndex(locations.pagesReal)).slugs;\n}\n\n/** Walk every indexed slug for an `includes`-style match. Returns the\n * single best candidate, or null when the slug is too short OR several\n * candidates tie at the top score (ambiguous → defer to the caller's\n * title-match fallback). Score = min/max length, decoupled from Map\n * iteration order so resolution is deterministic across hosts. */\nexport function pickFuzzyMatch(slug: string, slugs: ReadonlyMap<string, string>): string | null {\n if (slug.length < MIN_FUZZY_SLUG_LEN) return null;\n let bestFile: string | null = null;\n let bestScore = 0;\n let bestIsTied = false;\n for (const [key, file] of slugs) {\n if (!slug.includes(key) && !key.includes(slug)) continue;\n const shorter = Math.min(slug.length, key.length);\n const longer = Math.max(slug.length, key.length);\n const score = shorter / longer;\n if (score > bestScore) {\n bestScore = score;\n bestFile = file;\n bestIsTied = false;\n } else if (score === bestScore) {\n bestIsTied = true;\n }\n }\n return bestIsTied ? null : bestFile;\n}\n\n/** File matching an index.md entry whose title equals `target` — the\n * last resort for a link written as the display title rather than\n * the page's own name. */\nfunction fileByIndexTitle(locations: WikiReadLocations, target: string, slugs: ReadonlyMap<string, string>): string | undefined {\n const entries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n const trimmed = target.trim();\n const titleMatch = entries.find((entry) => entry.title === trimmed);\n return titleMatch ? slugs.get(titleMatch.slug) : undefined;\n}\n\n/** Resolve a page name to an absolute `.md` path: known slug (literal\n * or slugified) → fuzzy → index-title fallback. `pageName` may carry\n * the `[[target|display]]` form; `parseWikiLink` strips the display\n * half so the lookup uses just the target. */\nexport async function resolvePagePath(workspace: string, pageName: string): Promise<string | null> {\n const locations = wikiReadLocations(workspace);\n const fileName = await resolvePageFile(locations, pageName);\n return fileName === null ? null : path.join(locations.pagesDir, fileName);\n}\n\nasync function resolvePageFile(locations: WikiReadLocations, pageName: string): Promise<string | null> {\n const slugs = await pageSlugs(locations);\n if (slugs.size === 0) return null;\n\n const { target } = parseWikiLink(pageName);\n const matched = matchWikiSlug(target, slugs);\n const matchedFile = matched === null ? undefined : slugs.get(matched);\n if (matchedFile) return matchedFile;\n\n const fuzzy = pickFuzzyMatch(wikiSlugify(target), slugs);\n if (fuzzy) return fuzzy;\n\n return fileByIndexTitle(locations, target, slugs) ?? null;\n}\n\n/** Raw `index.md` content + its parsed entries. */\nexport function readWikiIndex(workspace: string): { content: string; entries: WikiPageEntry[] } {\n const locations = wikiReadLocations(workspace);\n const content = readFileOrEmpty(locations.indexReal, locations.workspaceReal);\n return { content, entries: parseIndexEntries(content) };\n}\n\n/** Raw `log.md` content (empty string if absent). */\nexport function readWikiLog(workspace: string): string {\n const locations = wikiReadLocations(workspace);\n return readFileOrEmpty(locations.logReal, locations.workspaceReal);\n}\n\nexport interface WikiPageRead {\n /** Absolute path of the resolved file, or null when nothing matched. */\n filePath: string | null;\n /** File body (empty when missing OR when the file is an empty placeholder). */\n content: string;\n /** True iff a page file resolved (distinct from empty content). */\n exists: boolean;\n /** Title to display — the resolved filename stem, or the raw pageName. */\n resolvedTitle: string;\n}\n\n/** Resolve + read a page. Distinguishes missing (`exists: false`) from\n * empty-but-present (`exists: true`, `content: \"\"`). */\nexport async function readWikiPage(workspace: string, pageName: string): Promise<WikiPageRead> {\n const locations = wikiReadLocations(workspace);\n const fileName = await resolvePageFile(locations, pageName);\n if (fileName === null || locations.pagesReal === null) return { filePath: null, content: \"\", exists: false, resolvedTitle: pageName };\n const content = readFileOrEmpty(path.join(locations.pagesReal, fileName), locations.workspaceReal);\n return { filePath: path.join(locations.pagesDir, fileName), content, exists: true, resolvedTitle: path.basename(fileName, \".md\") };\n}\n\n/** Page body, or \"\" when the file vanished between indexing and reading. */\nasync function readPageBody(locations: WikiReadLocations, fileName: string): Promise<string> {\n const { pagesReal, workspaceReal } = locations;\n return pagesReal === null || workspaceReal === null ? \"\" : ((await readTextSafe(path.join(pagesReal, fileName), workspaceReal)) ?? \"\");\n}\n\n/** Read every page + the index and build the page→page link graph.\n * No cache: the graph is requested explicitly and a content edit does\n * not advance the pagesDir mtime the page index caches on. */\nexport async function loadWikiGraph(workspace: string): Promise<WikiGraph> {\n const locations = wikiReadLocations(workspace);\n const slugs = await pageSlugs(locations);\n const pages = await Promise.all([...slugs.entries()].map(async ([slug, fileName]) => ({ slug, content: await readPageBody(locations, fileName) })));\n const indexEntries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n return buildWikiGraph(pages, indexEntries);\n}\n\nexport interface PageBody {\n fileName: string;\n content: string;\n}\n\nasync function readPageBodies(locations: WikiReadLocations, fileNames: readonly string[]): Promise<PageBody[]> {\n return Promise.all(fileNames.map(async (fileName) => ({ fileName, content: await readPageBody(locations, fileName) })));\n}\n\n/** Frontmatter `tags:` per page, keyed for `findTagDrift`. Lowercased so\n * a `MyPage.md` filename matches an `entry.slug` of `mypage`, which is\n * what the drift rule looks up. */\nexport function frontmatterTagIndex(bodies: readonly PageBody[]): Map<string, string[]> {\n const tagsBySlug = new Map<string, string[]>();\n bodies.forEach(({ fileName, content }) => {\n tagsBySlug.set(fileName.replace(/\\.md$/i, \"\").toLowerCase(), parseFrontmatterTags(content));\n });\n return tagsBySlug;\n}\n\n/** Run every lint rule over the on-disk wiki, returning issue strings. */\nexport async function collectLintIssues(workspace: string): Promise<string[]> {\n const locations = wikiReadLocations(workspace);\n const slugs = await pageSlugs(locations);\n if (slugs.size === 0 || locations.pagesReal === null) {\n return [\"- Wiki `pages/` directory does not exist yet. Start ingesting sources.\"];\n }\n const pageEntries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n const fileSlugs = new Set(slugs.keys());\n const slugByTitle = slugByIndexTitle(pageEntries);\n const bodies = await readPageBodies(locations, [...slugs.values()]);\n return [\n ...findOrphanPages(fileSlugs, new Set(pageEntries.map((entry) => entry.slug))),\n ...findMissingFiles(pageEntries, fileSlugs),\n ...bodies.flatMap(({ fileName, content }) => findBrokenLinksInPage(fileName, content, fileSlugs, slugByTitle)),\n ...findTagDrift(pageEntries, frontmatterTagIndex(bodies)),\n ];\n}\n"],"mappings":";;;;;;;;;AAcA,IAAM,aAAa,UAAU,YAAY,UAAU,cAAc,MAAM,UAAU,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AAI,IAAsB;CAC7C,OAAO,SAAS,EAAE,UAAU,cAAc;EACxC,WAAW,IAAI,SAAS,QAAQ,UAAU,EAAE,CAAC,CAAC,YAAY,GAAG,qBAAqB,OAAO,CAAC;CAC5F,CAAC;CACD,OAAO;AACT;;AAGA,eAAsB,kBAAkB,WAAsC;CAC5E,MAAM,YAAY,kBAAkB,SAAS;CAC7C,MAAM,QAAQ,MAAM,UAAU,SAAS;CACvC,IAAI,MAAM,SAAS,KAAK,UAAU,cAAc,MAC9C,OAAO,CAAC,wEAAwE;CAElF,MAAM,cAAc,kBAAkB,gBAAgB,UAAU,WAAW,UAAU,aAAa,CAAC;CACnG,MAAM,YAAY,IAAI,IAAI,MAAM,KAAK,CAAC;CACtC,MAAM,cAAc,iBAAiB,WAAW;CAChD,MAAM,SAAS,MAAM,eAAe,WAAW,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC;CAClE,OAAO;EACL,GAAG,gBAAgB,WAAW,IAAI,IAAI,YAAY,KAAK,UAAU,MAAM,IAAI,CAAC,CAAC;EAC7E,GAAG,iBAAiB,aAAa,SAAS;EAC1C,GAAG,OAAO,SAAS,EAAE,UAAU,cAAc,sBAAsB,UAAU,SAAS,WAAW,WAAW,CAAC;EAC7G,GAAG,aAAa,aAAa,oBAAoB,MAAM,CAAC;CAC1D;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/wiki/server/fs.ts","../../../src/wiki/server/pageIndex.ts","../../../src/wiki/server/frontmatter.ts","../../../src/wiki/server/locations.ts","../../../src/wiki/server/engine.ts"],"sourcesContent":["// Minimal ENOENT-swallowing fs wrappers for the wiki read-engine.\n// Self-contained (core can't reach the host's `server/utils/files/safe.ts`);\n// only the handful of helpers the wiki engine needs. Same \"return\n// null / [] on any error\" contract so callers branch on the value\n// instead of try/catch.\n\nimport type { Dirent, Stats } from \"node:fs\";\nimport { readdir, stat } from \"node:fs/promises\";\n\nexport async function statSafeAsync(absPath: string): Promise<Stats | null> {\n try {\n return await stat(absPath);\n } catch {\n return null;\n }\n}\n\nexport async function readDirSafeAsync(absPath: string): Promise<Dirent[]> {\n try {\n return await readdir(absPath, { withFileTypes: true });\n } catch {\n return [];\n }\n}\n","// In-memory index of `<pagesDir>/*.md` keyed by slug (= filename\n// without the `.md` extension). Kept fresh via `pagesDir` mtime —\n// adding, removing, or renaming a file under `pagesDir` advances the\n// directory's mtime on every major filesystem we target (macOS APFS,\n// Linux ext4, Windows NTFS), so one cheap `stat()` per request is\n// enough to decide whether to rebuild.\n\nimport { readDirSafeAsync, statSafeAsync } from \"./fs.js\";\n\nexport interface PageIndex {\n mtimeMs: number;\n /** slug → filename (e.g. \"sakura-internet\" → \"sakura-internet.md\"). */\n slugs: Map<string, string>;\n}\n\n// Keyed by `pagesDir`: the engine is workspace-injected and may be\n// called with more than one pages directory in a single process. A\n// single global slot would let one workspace's slug map be returned\n// for another whenever their mtimes happen to tie (Codex P2 on #1876).\nconst cache = new Map<string, PageIndex>();\n\n/**\n * Get the page index for `pagesDir`. Returns a cached value as long as\n * THAT directory's mtime hasn't advanced; otherwise rebuilds. Safe to\n * call concurrently — racing builds produce the same result.\n */\nexport async function getPageIndex(pagesDir: string): Promise<PageIndex> {\n const stat = await statSafeAsync(pagesDir);\n if (!stat) {\n // Dir doesn't exist yet (never ingested). Return empty but don't\n // cache a stale-forever value — the next call re-stats.\n return { mtimeMs: 0, slugs: new Map() };\n }\n const cached = cache.get(pagesDir);\n if (cached && cached.mtimeMs >= stat.mtimeMs) return cached;\n const entries = await readDirSafeAsync(pagesDir);\n const slugs = new Map<string, string>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const { name } = entry;\n if (!name.endsWith(\".md\")) continue;\n slugs.set(name.slice(0, -\".md\".length), name);\n }\n const built: PageIndex = { mtimeMs: stat.mtimeMs, slugs };\n cache.set(pagesDir, built);\n return built;\n}\n\n/** Test-only: drop the module-level cache (all directories). */\nexport function __resetPageIndexCache(): void {\n cache.clear();\n}\n","// Read-side frontmatter helpers for the wiki engine. The generic\n// `---\\n…\\n---\\n` envelope parsing is the canonical value-preserving\n// (FAILSAFE_SCHEMA) parser in `@mulmoclaude/markdown-utils`; only the\n// wiki-specific `tags:` reader stays here. Re-exporting `parseFrontmatter`\n// keeps the `@mulmoclaude/core/wiki/server` barrel surface stable — it now\n// returns the richer `{ meta, body, hasHeader }` shape.\n\nimport { parseFrontmatter } from \"@mulmoclaude/markdown-utils/markdown/frontmatter\";\n\nexport { parseFrontmatter };\n\nfunction cleanTagToken(token: string): string {\n return token\n .trim()\n .replace(/^['\"]|['\"]$/g, \"\")\n .replace(/^#/, \"\")\n .toLowerCase();\n}\n\n/** Narrow `tags:` reader. Handles flow (`tags: [a, b]`) and block-list\n * style; anything unparseable returns `[]` (best-effort, never throws). */\nexport function parseFrontmatterTags(content: string): string[] {\n const parsed = parseFrontmatter(content);\n if (!parsed.hasHeader) return [];\n const tagsValue = parsed.meta.tags;\n if (!Array.isArray(tagsValue)) return [];\n return tagsValue\n .filter((item): item is string => typeof item === \"string\")\n .map(cleanTagToken)\n .filter((token) => token.length > 0);\n}\n","// A wiki folder or file that leads out of the workspace counts as absent, so nothing outside is listed or read.\n\nimport path from \"node:path\";\nimport { isWithinRoot, realpathSyncOrNull } from \"../../files/withinRoot.js\";\nimport { wikiDirs } from \"./paths.js\";\n\nexport interface WikiReadLocations {\n /** `<workspace>/data/wiki/pages` as the caller spelled it: resolved page paths handed back are joined onto this. */\n pagesDir: string;\n /** The workspace's realpath: every read re-checks against it after opening. */\n workspaceReal: string | null;\n pagesReal: string | null;\n indexReal: string | null;\n logReal: string | null;\n}\n\nexport function wikiReadLocations(workspace: string): WikiReadLocations {\n const dirs = wikiDirs(workspace);\n const workspaceReal = realpathSyncOrNull(workspace);\n const insideWorkspace = (absPath: string): string | null => {\n const candidateReal = workspaceReal === null ? null : realpathSyncOrNull(path.resolve(workspaceReal, path.relative(workspace, absPath)));\n return workspaceReal !== null && candidateReal !== null && isWithinRoot(workspaceReal, candidateReal) ? candidateReal : null;\n };\n return {\n pagesDir: dirs.pagesDir,\n workspaceReal,\n pagesReal: insideWorkspace(dirs.pagesDir),\n indexReal: insideWorkspace(dirs.indexFile),\n logReal: insideWorkspace(dirs.logFile),\n };\n}\n","// Workspace-injected wiki read-engine — the filesystem layer that feeds\n// the pure helpers in `@mulmoclaude/core/wiki`. Shared by every host so\n// the two apps reading the same `data/wiki/` can't disagree on slug\n// resolution, graph edges, or lint findings. Mirrors the bodies that\n// previously lived in MulmoClaude's `server/api/routes/wiki.ts`; the\n// hosts keep only their HTTP response shaping on top.\n//\n// The read/write WRITE side (writeWikiPage / snapshots) stays host-side\n// until a host needs it shared.\n\nimport path from \"node:path\";\nimport { parseWikiLink } from \"../link.js\";\nimport { wikiSlugify } from \"../slug.js\";\nimport { matchWikiSlug, slugByIndexTitle } from \"../resolve.js\";\nimport { type WikiPageEntry, parseIndexEntries } from \"../index-parse.js\";\nimport { findBrokenLinksInPage, findMissingFiles, findOrphanPages, findTagDrift } from \"../lint.js\";\nimport { type WikiGraph, buildWikiGraph } from \"../graph.js\";\nimport { readTextWithinRoot, readTextWithinRootSync } from \"../../files/withinRoot.js\";\nimport { getPageIndex } from \"./pageIndex.js\";\nimport { parseFrontmatterTags } from \"./frontmatter.js\";\nimport { type WikiReadLocations, wikiReadLocations } from \"./locations.js\";\n\n// Below this length the fuzzy `includes` step is skipped — CJK /\n// emoji-only / very-short page names slugify down to a short noise\n// tail that partial-matches almost anything; the index.md title-match\n// fallback still handles the legitimate non-ASCII case (#1194).\nconst MIN_FUZZY_SLUG_LEN = 6;\n\nfunction readFileOrEmpty(absPath: string | null, workspaceReal: string | null): string {\n return absPath === null || workspaceReal === null ? \"\" : (readTextWithinRootSync(workspaceReal, absPath) ?? \"\");\n}\n\nasync function pageSlugs(locations: WikiReadLocations): Promise<Map<string, string>> {\n return locations.pagesReal === null ? new Map() : (await getPageIndex(locations.pagesReal)).slugs;\n}\n\n/** Walk every indexed slug for an `includes`-style match. Returns the\n * single best candidate, or null when the slug is too short OR several\n * candidates tie at the top score (ambiguous → defer to the caller's\n * title-match fallback). Score = min/max length, decoupled from Map\n * iteration order so resolution is deterministic across hosts. */\nexport function pickFuzzyMatch(slug: string, slugs: ReadonlyMap<string, string>): string | null {\n if (slug.length < MIN_FUZZY_SLUG_LEN) return null;\n let bestFile: string | null = null;\n let bestScore = 0;\n let bestIsTied = false;\n for (const [key, file] of slugs) {\n if (!slug.includes(key) && !key.includes(slug)) continue;\n const shorter = Math.min(slug.length, key.length);\n const longer = Math.max(slug.length, key.length);\n const score = shorter / longer;\n if (score > bestScore) {\n bestScore = score;\n bestFile = file;\n bestIsTied = false;\n } else if (score === bestScore) {\n bestIsTied = true;\n }\n }\n return bestIsTied ? null : bestFile;\n}\n\n/** File matching an index.md entry whose title equals `target` — the\n * last resort for a link written as the display title rather than\n * the page's own name. */\nfunction fileByIndexTitle(locations: WikiReadLocations, target: string, slugs: ReadonlyMap<string, string>): string | undefined {\n const entries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n const trimmed = target.trim();\n const titleMatch = entries.find((entry) => entry.title === trimmed);\n return titleMatch ? slugs.get(titleMatch.slug) : undefined;\n}\n\n/** Resolve a page name to an absolute `.md` path: known slug (literal\n * or slugified) → fuzzy → index-title fallback. `pageName` may carry\n * the `[[target|display]]` form; `parseWikiLink` strips the display\n * half so the lookup uses just the target. */\nexport async function resolvePagePath(workspace: string, pageName: string): Promise<string | null> {\n const locations = wikiReadLocations(workspace);\n const fileName = await resolvePageFile(locations, pageName);\n return fileName === null ? null : path.join(locations.pagesDir, fileName);\n}\n\nasync function resolvePageFile(locations: WikiReadLocations, pageName: string): Promise<string | null> {\n const slugs = await pageSlugs(locations);\n if (slugs.size === 0) return null;\n\n const { target } = parseWikiLink(pageName);\n const matched = matchWikiSlug(target, slugs);\n const matchedFile = matched === null ? undefined : slugs.get(matched);\n if (matchedFile) return matchedFile;\n\n const fuzzy = pickFuzzyMatch(wikiSlugify(target), slugs);\n if (fuzzy) return fuzzy;\n\n return fileByIndexTitle(locations, target, slugs) ?? null;\n}\n\n/** Raw `index.md` content + its parsed entries. */\nexport function readWikiIndex(workspace: string): { content: string; entries: WikiPageEntry[] } {\n const locations = wikiReadLocations(workspace);\n const content = readFileOrEmpty(locations.indexReal, locations.workspaceReal);\n return { content, entries: parseIndexEntries(content) };\n}\n\n/** Raw `log.md` content (empty string if absent). */\nexport function readWikiLog(workspace: string): string {\n const locations = wikiReadLocations(workspace);\n return readFileOrEmpty(locations.logReal, locations.workspaceReal);\n}\n\nexport interface WikiPageRead {\n /** Absolute path of the resolved file, or null when nothing matched. */\n filePath: string | null;\n /** File body (empty when missing OR when the file is an empty placeholder). */\n content: string;\n /** True iff a page file resolved (distinct from empty content). */\n exists: boolean;\n /** Title to display — the resolved filename stem, or the raw pageName. */\n resolvedTitle: string;\n}\n\n/** Resolve + read a page. Distinguishes missing (`exists: false`) from\n * empty-but-present (`exists: true`, `content: \"\"`). */\nexport async function readWikiPage(workspace: string, pageName: string): Promise<WikiPageRead> {\n const locations = wikiReadLocations(workspace);\n const fileName = await resolvePageFile(locations, pageName);\n if (fileName === null || locations.pagesReal === null) return { filePath: null, content: \"\", exists: false, resolvedTitle: pageName };\n const content = readFileOrEmpty(path.join(locations.pagesReal, fileName), locations.workspaceReal);\n return { filePath: path.join(locations.pagesDir, fileName), content, exists: true, resolvedTitle: path.basename(fileName, \".md\") };\n}\n\n/** Page body, or \"\" when the file vanished between indexing and reading. */\nasync function readPageBody(locations: WikiReadLocations, fileName: string): Promise<string> {\n const { pagesReal, workspaceReal } = locations;\n return pagesReal === null || workspaceReal === null ? \"\" : ((await readTextWithinRoot(workspaceReal, path.join(pagesReal, fileName))) ?? \"\");\n}\n\n/** Read every page + the index and build the page→page link graph.\n * No cache: the graph is requested explicitly and a content edit does\n * not advance the pagesDir mtime the page index caches on. */\nexport async function loadWikiGraph(workspace: string): Promise<WikiGraph> {\n const locations = wikiReadLocations(workspace);\n const slugs = await pageSlugs(locations);\n const pages = await Promise.all([...slugs.entries()].map(async ([slug, fileName]) => ({ slug, content: await readPageBody(locations, fileName) })));\n const indexEntries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n return buildWikiGraph(pages, indexEntries);\n}\n\nexport interface PageBody {\n fileName: string;\n content: string;\n}\n\nasync function readPageBodies(locations: WikiReadLocations, fileNames: readonly string[]): Promise<PageBody[]> {\n return Promise.all(fileNames.map(async (fileName) => ({ fileName, content: await readPageBody(locations, fileName) })));\n}\n\n/** Frontmatter `tags:` per page, keyed for `findTagDrift`. Lowercased so\n * a `MyPage.md` filename matches an `entry.slug` of `mypage`, which is\n * what the drift rule looks up. */\nexport function frontmatterTagIndex(bodies: readonly PageBody[]): Map<string, string[]> {\n const tagsBySlug = new Map<string, string[]>();\n bodies.forEach(({ fileName, content }) => {\n tagsBySlug.set(fileName.replace(/\\.md$/i, \"\").toLowerCase(), parseFrontmatterTags(content));\n });\n return tagsBySlug;\n}\n\n/** Run every lint rule over the on-disk wiki, returning issue strings. */\nexport async function collectLintIssues(workspace: string): Promise<string[]> {\n const locations = wikiReadLocations(workspace);\n const slugs = await pageSlugs(locations);\n if (slugs.size === 0 || locations.pagesReal === null) {\n return [\"- Wiki `pages/` directory does not exist yet. Start ingesting sources.\"];\n }\n const pageEntries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n const fileSlugs = new Set(slugs.keys());\n const slugByTitle = slugByIndexTitle(pageEntries);\n const bodies = await readPageBodies(locations, [...slugs.values()]);\n return [\n ...findOrphanPages(fileSlugs, new Set(pageEntries.map((entry) => entry.slug))),\n ...findMissingFiles(pageEntries, fileSlugs),\n ...bodies.flatMap(({ fileName, content }) => findBrokenLinksInPage(fileName, content, fileSlugs, slugByTitle)),\n ...findTagDrift(pageEntries, frontmatterTagIndex(bodies)),\n ];\n}\n"],"mappings":";;;;;;;;AASA,eAAsB,cAAc,SAAwC;CAC1E,IAAI;EACF,OAAO,MAAM,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AAY,GAAG,qBAAqB,OAAO,CAAC;CAC5F,CAAC;CACD,OAAO;AACT;;AAGA,eAAsB,kBAAkB,WAAsC;CAC5E,MAAM,YAAY,kBAAkB,SAAS;CAC7C,MAAM,QAAQ,MAAM,UAAU,SAAS;CACvC,IAAI,MAAM,SAAS,KAAK,UAAU,cAAc,MAC9C,OAAO,CAAC,wEAAwE;CAElF,MAAM,cAAc,kBAAkB,gBAAgB,UAAU,WAAW,UAAU,aAAa,CAAC;CACnG,MAAM,YAAY,IAAI,IAAI,MAAM,KAAK,CAAC;CACtC,MAAM,cAAc,iBAAiB,WAAW;CAChD,MAAM,SAAS,MAAM,eAAe,WAAW,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC;CAClE,OAAO;EACL,GAAG,gBAAgB,WAAW,IAAI,IAAI,YAAY,KAAK,UAAU,MAAM,IAAI,CAAC,CAAC;EAC7E,GAAG,iBAAiB,aAAa,SAAS;EAC1C,GAAG,OAAO,SAAS,EAAE,UAAU,cAAc,sBAAsB,UAAU,SAAS,WAAW,WAAW,CAAC;EAC7G,GAAG,aAAa,aAAa,oBAAoB,MAAM,CAAC;CAC1D;AACF"}
@@ -0,0 +1,84 @@
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, realpathSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { open } from "node:fs/promises";
4
+ // src/files/safe.ts
5
+ /** True for a `not found` filesystem error (ENOENT) — lets callers treat a
6
+ * missing file as an empty/default result instead of a thrown error. */
7
+ function isEnoent(err) {
8
+ return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
9
+ }
10
+ /** Realpath-based read-time containment: resolve `relPath` against the root's
11
+ * realpath and require the target's realpath to stay inside it. Returns null
12
+ * on ENOENT or traversal (symlink escapes included). `rootReal` MUST already
13
+ * be a realpath. The one implementation for host and plugins (#2461) — this
14
+ * security-critical primitive must not drift per consumer. */
15
+ function resolveWithinRoot(rootReal, relPath) {
16
+ const normalized = path.normalize(relPath || "");
17
+ const resolvedReal = realpathOrNull(path.resolve(rootReal, normalized));
18
+ if (resolvedReal === null) return null;
19
+ if (resolvedReal !== rootReal && !resolvedReal.startsWith(rootReal + path.sep)) return null;
20
+ return resolvedReal;
21
+ }
22
+ function realpathOrNull(absPath) {
23
+ try {
24
+ return realpathSync(absPath);
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+ // src/files/withinRoot.ts
30
+ var READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
31
+ function isWithinRoot(rootReal, candidateReal) {
32
+ const rel = path.relative(rootReal, candidateReal);
33
+ return rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
34
+ }
35
+ function realpathSyncOrNull(absPath) {
36
+ try {
37
+ return realpathSync.native(absPath);
38
+ } catch (err) {
39
+ return isEnoent(err) ? null : jsRealpathOrNull(absPath);
40
+ }
41
+ }
42
+ function jsRealpathOrNull(absPath) {
43
+ try {
44
+ return realpathSync(absPath);
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+ function isOpenedFileInside(rootReal, absPath, opened) {
50
+ const real = realpathSyncOrNull(absPath);
51
+ if (real === null || !isWithinRoot(rootReal, real) || !opened.isFile()) return false;
52
+ const onDisk = lstatSync(real, { bigint: true });
53
+ return onDisk.isFile() && onDisk.dev === opened.dev && onDisk.ino === opened.ino;
54
+ }
55
+ /** Text of a regular file inside `rootReal` (a realpath), or null when it is missing, leads outside, is a FIFO or
56
+ * other non-file, or is unreadable. */
57
+ async function readTextWithinRoot(rootReal, absPath) {
58
+ try {
59
+ const handle = await open(absPath, READ_FLAGS);
60
+ try {
61
+ return isOpenedFileInside(rootReal, absPath, await handle.stat({ bigint: true })) ? await handle.readFile("utf-8") : null;
62
+ } finally {
63
+ await handle.close();
64
+ }
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+ /** Sync twin of `readTextWithinRoot`. */
70
+ function readTextWithinRootSync(rootReal, absPath) {
71
+ try {
72
+ const descriptor = openSync(absPath, READ_FLAGS);
73
+ try {
74
+ return isOpenedFileInside(rootReal, absPath, fstatSync(descriptor, { bigint: true })) ? readFileSync(descriptor, "utf-8") : null;
75
+ } finally {
76
+ closeSync(descriptor);
77
+ }
78
+ } catch {
79
+ return null;
80
+ }
81
+ }
82
+ export { isEnoent as a, realpathSyncOrNull as i, readTextWithinRoot as n, resolveWithinRoot as o, readTextWithinRootSync as r, isWithinRoot as t };
83
+
84
+ //# sourceMappingURL=withinRoot-Bbj6E-Lf.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"withinRoot-Bbj6E-Lf.js","names":[],"sources":["../src/files/safe.ts","../src/files/withinRoot.ts"],"sourcesContent":["import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/** True for a `not found` filesystem error (ENOENT) — lets callers treat a\n * missing file as an empty/default result instead of a thrown error. */\nexport function isEnoent(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && \"code\" in err && err.code === \"ENOENT\";\n}\n\n/** Realpath-based read-time containment: resolve `relPath` against the root's\n * realpath and require the target's realpath to stay inside it. Returns null\n * on ENOENT or traversal (symlink escapes included). `rootReal` MUST already\n * be a realpath. The one implementation for host and plugins (#2461) — this\n * security-critical primitive must not drift per consumer. */\nexport function resolveWithinRoot(rootReal: string, relPath: string): string | null {\n const normalized = path.normalize(relPath || \"\");\n const resolved = path.resolve(rootReal, normalized);\n const resolvedReal = realpathOrNull(resolved);\n if (resolvedReal === null) return null;\n if (resolvedReal !== rootReal && !resolvedReal.startsWith(rootReal + path.sep)) {\n return null;\n }\n return resolvedReal;\n}\n\nfunction realpathOrNull(absPath: string): string | null {\n try {\n return realpathSync(absPath);\n } catch {\n return null;\n }\n}\n","// Synchronous containment and whole-file reads for callers that cannot await (prompt assembly, the wiki engine's\n// sync readers). The read opens first and then proves where the path leads, like `openVerifiedWithinScope`.\n\nimport type { BigIntStats } from \"node:fs\";\nimport { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, realpathSync } from \"node:fs\";\nimport { open } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { isEnoent } from \"./safe.js\";\n\n// A FIFO must not block the server, and a link is refused at open where the OS can; both flags are undefined on\n// Windows, where the check after the open is what refuses a link out.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);\n\n// `path.relative` rather than a `rootReal + sep` prefix, which a root at a filesystem root (`/`, `C:\\`) would fail.\nexport function isWithinRoot(rootReal: string, candidateReal: string): boolean {\n const rel = path.relative(rootReal, candidateReal);\n return rel !== \"..\" && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);\n}\n\n// Native first: the JS realpath keeps a link's letter case, so on a case-insensitive disk an inside link looks outside.\n// The JS one is the fallback for drives where the native call throws (EISDIR on some Windows RAM disks).\nexport function realpathSyncOrNull(absPath: string): string | null {\n try {\n return realpathSync.native(absPath);\n } catch (err) {\n return isEnoent(err) ? null : jsRealpathOrNull(absPath);\n }\n}\n\nfunction jsRealpathOrNull(absPath: string): string | null {\n try {\n return realpathSync(absPath);\n } catch {\n return null;\n }\n}\n\n// Checked after the open, so a folder or file swapped for a link out between the caller's check and the open, or\n// swapped back before this check, is refused: where the path leads now must be inside and be the opened file.\nfunction isOpenedFileInside(rootReal: string, absPath: string, opened: BigIntStats): boolean {\n const real = realpathSyncOrNull(absPath);\n if (real === null || !isWithinRoot(rootReal, real) || !opened.isFile()) return false;\n const onDisk = lstatSync(real, { bigint: true });\n return onDisk.isFile() && onDisk.dev === opened.dev && onDisk.ino === opened.ino;\n}\n\n/** Text of a regular file inside `rootReal` (a realpath), or null when it is missing, leads outside, is a FIFO or\n * other non-file, or is unreadable. */\nexport async function readTextWithinRoot(rootReal: string, absPath: string): Promise<string | null> {\n try {\n const handle = await open(absPath, READ_FLAGS);\n try {\n return isOpenedFileInside(rootReal, absPath, await handle.stat({ bigint: true })) ? await handle.readFile(\"utf-8\") : null;\n } finally {\n await handle.close();\n }\n } catch {\n return null;\n }\n}\n\n/** Sync twin of `readTextWithinRoot`. */\nexport function readTextWithinRootSync(rootReal: string, absPath: string): string | null {\n try {\n const descriptor = openSync(absPath, READ_FLAGS);\n try {\n return isOpenedFileInside(rootReal, absPath, fstatSync(descriptor, { bigint: true })) ? readFileSync(descriptor, \"utf-8\") : null;\n } finally {\n closeSync(descriptor);\n }\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;;AAKA,SAAgB,SAAS,KAAuB;CAC9C,OAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,UAAU,OAAO,IAAI,SAAS;AAClF;;;;;;AAOA,SAAgB,kBAAkB,UAAkB,SAAgC;CAClF,MAAM,aAAa,KAAK,UAAU,WAAW,EAAE;CAE/C,MAAM,eAAe,eADJ,KAAK,QAAQ,UAAU,UACJ,CAAQ;CAC5C,IAAI,iBAAiB,MAAM,OAAO;CAClC,IAAI,iBAAiB,YAAY,CAAC,aAAa,WAAW,WAAW,KAAK,GAAG,GAC3E,OAAO;CAET,OAAO;AACT;AAEA,SAAS,eAAe,SAAgC;CACtD,IAAI;EACF,OAAO,aAAa,OAAO;CAC7B,QAAQ;EACN,OAAO;CACT;AACF;;ACpBA,IAAM,aAAa,UAAU,YAAY,UAAU,cAAc,MAAM,UAAU,cAAc;AAG/F,SAAgB,aAAa,UAAkB,eAAgC;CAC7E,MAAM,MAAM,KAAK,SAAS,UAAU,aAAa;CACjD,OAAO,QAAQ,QAAQ,CAAC,IAAI,WAAW,KAAK,KAAK,KAAK,KAAK,CAAC,KAAK,WAAW,GAAG;AACjF;AAIA,SAAgB,mBAAmB,SAAgC;CACjE,IAAI;EACF,OAAO,aAAa,OAAO,OAAO;CACpC,SAAS,KAAK;EACZ,OAAO,SAAS,GAAG,IAAI,OAAO,iBAAiB,OAAO;CACxD;AACF;AAEA,SAAS,iBAAiB,SAAgC;CACxD,IAAI;EACF,OAAO,aAAa,OAAO;CAC7B,QAAQ;EACN,OAAO;CACT;AACF;AAIA,SAAS,mBAAmB,UAAkB,SAAiB,QAA8B;CAC3F,MAAM,OAAO,mBAAmB,OAAO;CACvC,IAAI,SAAS,QAAQ,CAAC,aAAa,UAAU,IAAI,KAAK,CAAC,OAAO,OAAO,GAAG,OAAO;CAC/E,MAAM,SAAS,UAAU,MAAM,EAAE,QAAQ,KAAK,CAAC;CAC/C,OAAO,OAAO,OAAO,KAAK,OAAO,QAAQ,OAAO,OAAO,OAAO,QAAQ,OAAO;AAC/E;;;AAIA,eAAsB,mBAAmB,UAAkB,SAAyC;CAClG,IAAI;EACF,MAAM,SAAS,MAAM,KAAK,SAAS,UAAU;EAC7C,IAAI;GACF,OAAO,mBAAmB,UAAU,SAAS,MAAM,OAAO,KAAK,EAAE,QAAQ,KAAK,CAAC,CAAC,IAAI,MAAM,OAAO,SAAS,OAAO,IAAI;EACvH,UAAU;GACR,MAAM,OAAO,MAAM;EACrB;CACF,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,SAAgB,uBAAuB,UAAkB,SAAgC;CACvF,IAAI;EACF,MAAM,aAAa,SAAS,SAAS,UAAU;EAC/C,IAAI;GACF,OAAO,mBAAmB,UAAU,SAAS,UAAU,YAAY,EAAE,QAAQ,KAAK,CAAC,CAAC,IAAI,aAAa,YAAY,OAAO,IAAI;EAC9H,UAAU;GACR,UAAU,UAAU;EACtB;CACF,QAAQ;EACN,OAAO;CACT;AACF"}
@@ -0,0 +1,121 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-CmQyd0Gu.cjs");
2
+ let node_fs = require("node:fs");
3
+ let node_path = require("node:path");
4
+ node_path = require_rolldown_runtime.__toESM(node_path, 1);
5
+ let node_fs_promises = require("node:fs/promises");
6
+ // src/files/safe.ts
7
+ /** True for a `not found` filesystem error (ENOENT) — lets callers treat a
8
+ * missing file as an empty/default result instead of a thrown error. */
9
+ function isEnoent(err) {
10
+ return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
11
+ }
12
+ /** Realpath-based read-time containment: resolve `relPath` against the root's
13
+ * realpath and require the target's realpath to stay inside it. Returns null
14
+ * on ENOENT or traversal (symlink escapes included). `rootReal` MUST already
15
+ * be a realpath. The one implementation for host and plugins (#2461) — this
16
+ * security-critical primitive must not drift per consumer. */
17
+ function resolveWithinRoot(rootReal, relPath) {
18
+ const normalized = node_path.default.normalize(relPath || "");
19
+ const resolvedReal = realpathOrNull(node_path.default.resolve(rootReal, normalized));
20
+ if (resolvedReal === null) return null;
21
+ if (resolvedReal !== rootReal && !resolvedReal.startsWith(rootReal + node_path.default.sep)) return null;
22
+ return resolvedReal;
23
+ }
24
+ function realpathOrNull(absPath) {
25
+ try {
26
+ return (0, node_fs.realpathSync)(absPath);
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+ // src/files/withinRoot.ts
32
+ var READ_FLAGS = node_fs.constants.O_RDONLY | (node_fs.constants.O_NOFOLLOW ?? 0) | (node_fs.constants.O_NONBLOCK ?? 0);
33
+ function isWithinRoot(rootReal, candidateReal) {
34
+ const rel = node_path.default.relative(rootReal, candidateReal);
35
+ return rel !== ".." && !rel.startsWith(`..${node_path.default.sep}`) && !node_path.default.isAbsolute(rel);
36
+ }
37
+ function realpathSyncOrNull(absPath) {
38
+ try {
39
+ return node_fs.realpathSync.native(absPath);
40
+ } catch (err) {
41
+ return isEnoent(err) ? null : jsRealpathOrNull(absPath);
42
+ }
43
+ }
44
+ function jsRealpathOrNull(absPath) {
45
+ try {
46
+ return (0, node_fs.realpathSync)(absPath);
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+ function isOpenedFileInside(rootReal, absPath, opened) {
52
+ const real = realpathSyncOrNull(absPath);
53
+ if (real === null || !isWithinRoot(rootReal, real) || !opened.isFile()) return false;
54
+ const onDisk = (0, node_fs.lstatSync)(real, { bigint: true });
55
+ return onDisk.isFile() && onDisk.dev === opened.dev && onDisk.ino === opened.ino;
56
+ }
57
+ /** Text of a regular file inside `rootReal` (a realpath), or null when it is missing, leads outside, is a FIFO or
58
+ * other non-file, or is unreadable. */
59
+ async function readTextWithinRoot(rootReal, absPath) {
60
+ try {
61
+ const handle = await (0, node_fs_promises.open)(absPath, READ_FLAGS);
62
+ try {
63
+ return isOpenedFileInside(rootReal, absPath, await handle.stat({ bigint: true })) ? await handle.readFile("utf-8") : null;
64
+ } finally {
65
+ await handle.close();
66
+ }
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+ /** Sync twin of `readTextWithinRoot`. */
72
+ function readTextWithinRootSync(rootReal, absPath) {
73
+ try {
74
+ const descriptor = (0, node_fs.openSync)(absPath, READ_FLAGS);
75
+ try {
76
+ return isOpenedFileInside(rootReal, absPath, (0, node_fs.fstatSync)(descriptor, { bigint: true })) ? (0, node_fs.readFileSync)(descriptor, "utf-8") : null;
77
+ } finally {
78
+ (0, node_fs.closeSync)(descriptor);
79
+ }
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+ Object.defineProperty(exports, "isEnoent", {
85
+ enumerable: true,
86
+ get: function() {
87
+ return isEnoent;
88
+ }
89
+ });
90
+ Object.defineProperty(exports, "isWithinRoot", {
91
+ enumerable: true,
92
+ get: function() {
93
+ return isWithinRoot;
94
+ }
95
+ });
96
+ Object.defineProperty(exports, "readTextWithinRoot", {
97
+ enumerable: true,
98
+ get: function() {
99
+ return readTextWithinRoot;
100
+ }
101
+ });
102
+ Object.defineProperty(exports, "readTextWithinRootSync", {
103
+ enumerable: true,
104
+ get: function() {
105
+ return readTextWithinRootSync;
106
+ }
107
+ });
108
+ Object.defineProperty(exports, "realpathSyncOrNull", {
109
+ enumerable: true,
110
+ get: function() {
111
+ return realpathSyncOrNull;
112
+ }
113
+ });
114
+ Object.defineProperty(exports, "resolveWithinRoot", {
115
+ enumerable: true,
116
+ get: function() {
117
+ return resolveWithinRoot;
118
+ }
119
+ });
120
+
121
+ //# sourceMappingURL=withinRoot-FLjxC8oP.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"withinRoot-FLjxC8oP.cjs","names":["path","realpathSync","constants","path","realpathSync","lstatSync","open","openSync","fstatSync","readFileSync"],"sources":["../src/files/safe.ts","../src/files/withinRoot.ts"],"sourcesContent":["import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/** True for a `not found` filesystem error (ENOENT) — lets callers treat a\n * missing file as an empty/default result instead of a thrown error. */\nexport function isEnoent(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && \"code\" in err && err.code === \"ENOENT\";\n}\n\n/** Realpath-based read-time containment: resolve `relPath` against the root's\n * realpath and require the target's realpath to stay inside it. Returns null\n * on ENOENT or traversal (symlink escapes included). `rootReal` MUST already\n * be a realpath. The one implementation for host and plugins (#2461) — this\n * security-critical primitive must not drift per consumer. */\nexport function resolveWithinRoot(rootReal: string, relPath: string): string | null {\n const normalized = path.normalize(relPath || \"\");\n const resolved = path.resolve(rootReal, normalized);\n const resolvedReal = realpathOrNull(resolved);\n if (resolvedReal === null) return null;\n if (resolvedReal !== rootReal && !resolvedReal.startsWith(rootReal + path.sep)) {\n return null;\n }\n return resolvedReal;\n}\n\nfunction realpathOrNull(absPath: string): string | null {\n try {\n return realpathSync(absPath);\n } catch {\n return null;\n }\n}\n","// Synchronous containment and whole-file reads for callers that cannot await (prompt assembly, the wiki engine's\n// sync readers). The read opens first and then proves where the path leads, like `openVerifiedWithinScope`.\n\nimport type { BigIntStats } from \"node:fs\";\nimport { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, realpathSync } from \"node:fs\";\nimport { open } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { isEnoent } from \"./safe.js\";\n\n// A FIFO must not block the server, and a link is refused at open where the OS can; both flags are undefined on\n// Windows, where the check after the open is what refuses a link out.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);\n\n// `path.relative` rather than a `rootReal + sep` prefix, which a root at a filesystem root (`/`, `C:\\`) would fail.\nexport function isWithinRoot(rootReal: string, candidateReal: string): boolean {\n const rel = path.relative(rootReal, candidateReal);\n return rel !== \"..\" && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);\n}\n\n// Native first: the JS realpath keeps a link's letter case, so on a case-insensitive disk an inside link looks outside.\n// The JS one is the fallback for drives where the native call throws (EISDIR on some Windows RAM disks).\nexport function realpathSyncOrNull(absPath: string): string | null {\n try {\n return realpathSync.native(absPath);\n } catch (err) {\n return isEnoent(err) ? null : jsRealpathOrNull(absPath);\n }\n}\n\nfunction jsRealpathOrNull(absPath: string): string | null {\n try {\n return realpathSync(absPath);\n } catch {\n return null;\n }\n}\n\n// Checked after the open, so a folder or file swapped for a link out between the caller's check and the open, or\n// swapped back before this check, is refused: where the path leads now must be inside and be the opened file.\nfunction isOpenedFileInside(rootReal: string, absPath: string, opened: BigIntStats): boolean {\n const real = realpathSyncOrNull(absPath);\n if (real === null || !isWithinRoot(rootReal, real) || !opened.isFile()) return false;\n const onDisk = lstatSync(real, { bigint: true });\n return onDisk.isFile() && onDisk.dev === opened.dev && onDisk.ino === opened.ino;\n}\n\n/** Text of a regular file inside `rootReal` (a realpath), or null when it is missing, leads outside, is a FIFO or\n * other non-file, or is unreadable. */\nexport async function readTextWithinRoot(rootReal: string, absPath: string): Promise<string | null> {\n try {\n const handle = await open(absPath, READ_FLAGS);\n try {\n return isOpenedFileInside(rootReal, absPath, await handle.stat({ bigint: true })) ? await handle.readFile(\"utf-8\") : null;\n } finally {\n await handle.close();\n }\n } catch {\n return null;\n }\n}\n\n/** Sync twin of `readTextWithinRoot`. */\nexport function readTextWithinRootSync(rootReal: string, absPath: string): string | null {\n try {\n const descriptor = openSync(absPath, READ_FLAGS);\n try {\n return isOpenedFileInside(rootReal, absPath, fstatSync(descriptor, { bigint: true })) ? readFileSync(descriptor, \"utf-8\") : null;\n } finally {\n closeSync(descriptor);\n }\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;;;;AAKA,SAAgB,SAAS,KAAuB;CAC9C,OAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,UA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,CAAC;CAC/C,OAAO,OAAO,OAAO,KAAK,OAAO,QAAQ,OAAO,OAAO,OAAO,QAAQ,OAAO;AAC/E;;;AAIA,eAAsB,mBAAmB,UAAkB,SAAyC;CAClG,IAAI;EACF,MAAM,SAAS,OAAA,GAAMC,iBAAAA,KAAAA,CAAK,SAAS,UAAU;EAC7C,IAAI;GACF,OAAO,mBAAmB,UAAU,SAAS,MAAM,OAAO,KAAK,EAAE,QAAQ,KAAK,CAAC,CAAC,IAAI,MAAM,OAAO,SAAS,OAAO,IAAI;EACvH,UAAU;GACR,MAAM,OAAO,MAAM;EACrB;CACF,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,SAAgB,uBAAuB,UAAkB,SAAgC;CACvF,IAAI;EACF,MAAM,cAAA,GAAaC,QAAAA,SAAAA,CAAS,SAAS,UAAU;EAC/C,IAAI;GACF,OAAO,mBAAmB,UAAU,UAAA,GAASC,QAAAA,UAAAA,CAAU,YAAY,EAAE,QAAQ,KAAK,CAAC,CAAC,KAAA,GAAIC,QAAAA,aAAAA,CAAa,YAAY,OAAO,IAAI;EAC9H,UAAU;GACR,CAAA,GAAA,QAAA,UAAA,CAAU,UAAU;EACtB;CACF,QAAQ;EACN,OAAO;CACT;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mulmoclaude/core",
3
- "version": "7.0.0",
3
+ "version": "7.1.0",
4
4
  "description": "Shared server-side core for MulmoClaude and MulmoTerminal — the always-shipped-together subsystems consolidated behind subpath exports so the two hosts can't drift. Server-only except the browser-safe ./artifacts, ./whisper/client, ./workspace-setup/slug, ./translation/client, ./remote-view, ./remote-host and ./plugin-vue entries. All host specifics are injected.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,43 +0,0 @@
1
- const require_rolldown_runtime = require("./rolldown-runtime-CmQyd0Gu.cjs");
2
- let node_fs = require("node:fs");
3
- let node_path = require("node:path");
4
- node_path = require_rolldown_runtime.__toESM(node_path, 1);
5
- // src/files/safe.ts
6
- /** True for a `not found` filesystem error (ENOENT) — lets callers treat a
7
- * missing file as an empty/default result instead of a thrown error. */
8
- function isEnoent(err) {
9
- return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
10
- }
11
- /** Realpath-based read-time containment: resolve `relPath` against the root's
12
- * realpath and require the target's realpath to stay inside it. Returns null
13
- * on ENOENT or traversal (symlink escapes included). `rootReal` MUST already
14
- * be a realpath. The one implementation for host and plugins (#2461) — this
15
- * security-critical primitive must not drift per consumer. */
16
- function resolveWithinRoot(rootReal, relPath) {
17
- const normalized = node_path.default.normalize(relPath || "");
18
- const resolvedReal = realpathOrNull(node_path.default.resolve(rootReal, normalized));
19
- if (resolvedReal === null) return null;
20
- if (resolvedReal !== rootReal && !resolvedReal.startsWith(rootReal + node_path.default.sep)) return null;
21
- return resolvedReal;
22
- }
23
- function realpathOrNull(absPath) {
24
- try {
25
- return (0, node_fs.realpathSync)(absPath);
26
- } catch {
27
- return null;
28
- }
29
- }
30
- Object.defineProperty(exports, "isEnoent", {
31
- enumerable: true,
32
- get: function() {
33
- return isEnoent;
34
- }
35
- });
36
- Object.defineProperty(exports, "resolveWithinRoot", {
37
- enumerable: true,
38
- get: function() {
39
- return resolveWithinRoot;
40
- }
41
- });
42
-
43
- //# sourceMappingURL=safe-D79sHxq1.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"safe-D79sHxq1.cjs","names":["path","realpathSync"],"sources":["../src/files/safe.ts"],"sourcesContent":["import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/** True for a `not found` filesystem error (ENOENT) — lets callers treat a\n * missing file as an empty/default result instead of a thrown error. */\nexport function isEnoent(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && \"code\" in err && err.code === \"ENOENT\";\n}\n\n/** Realpath-based read-time containment: resolve `relPath` against the root's\n * realpath and require the target's realpath to stay inside it. Returns null\n * on ENOENT or traversal (symlink escapes included). `rootReal` MUST already\n * be a realpath. The one implementation for host and plugins (#2461) — this\n * security-critical primitive must not drift per consumer. */\nexport function resolveWithinRoot(rootReal: string, relPath: string): string | null {\n const normalized = path.normalize(relPath || \"\");\n const resolved = path.resolve(rootReal, normalized);\n const resolvedReal = realpathOrNull(resolved);\n if (resolvedReal === null) return null;\n if (resolvedReal !== rootReal && !resolvedReal.startsWith(rootReal + path.sep)) {\n return null;\n }\n return resolvedReal;\n}\n\nfunction realpathOrNull(absPath: string): string | null {\n try {\n return realpathSync(absPath);\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;;;AAKA,SAAgB,SAAS,KAAuB;CAC9C,OAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,UAAU,OAAO,IAAI,SAAS;AAClF;;;;;;AAOA,SAAgB,kBAAkB,UAAkB,SAAgC;CAClF,MAAM,aAAaA,UAAAA,QAAK,UAAU,WAAW,EAAE;CAE/C,MAAM,eAAe,eADJA,UAAAA,QAAK,QAAQ,UAAU,UACJ,CAAQ;CAC5C,IAAI,iBAAiB,MAAM,OAAO;CAClC,IAAI,iBAAiB,YAAY,CAAC,aAAa,WAAW,WAAWA,UAAAA,QAAK,GAAG,GAC3E,OAAO;CAET,OAAO;AACT;AAEA,SAAS,eAAe,SAAgC;CACtD,IAAI;EACF,QAAA,GAAOC,QAAAA,aAAAA,CAAa,OAAO;CAC7B,QAAQ;EACN,OAAO;CACT;AACF"}
@@ -1,30 +0,0 @@
1
- import { realpathSync } from "node:fs";
2
- import path from "node:path";
3
- // src/files/safe.ts
4
- /** True for a `not found` filesystem error (ENOENT) — lets callers treat a
5
- * missing file as an empty/default result instead of a thrown error. */
6
- function isEnoent(err) {
7
- return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
8
- }
9
- /** Realpath-based read-time containment: resolve `relPath` against the root's
10
- * realpath and require the target's realpath to stay inside it. Returns null
11
- * on ENOENT or traversal (symlink escapes included). `rootReal` MUST already
12
- * be a realpath. The one implementation for host and plugins (#2461) — this
13
- * security-critical primitive must not drift per consumer. */
14
- function resolveWithinRoot(rootReal, relPath) {
15
- const normalized = path.normalize(relPath || "");
16
- const resolvedReal = realpathOrNull(path.resolve(rootReal, normalized));
17
- if (resolvedReal === null) return null;
18
- if (resolvedReal !== rootReal && !resolvedReal.startsWith(rootReal + path.sep)) return null;
19
- return resolvedReal;
20
- }
21
- function realpathOrNull(absPath) {
22
- try {
23
- return realpathSync(absPath);
24
- } catch {
25
- return null;
26
- }
27
- }
28
- export { resolveWithinRoot as n, isEnoent as t };
29
-
30
- //# sourceMappingURL=safe-DRNa8UBp.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"safe-DRNa8UBp.js","names":[],"sources":["../src/files/safe.ts"],"sourcesContent":["import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/** True for a `not found` filesystem error (ENOENT) — lets callers treat a\n * missing file as an empty/default result instead of a thrown error. */\nexport function isEnoent(err: unknown): boolean {\n return typeof err === \"object\" && err !== null && \"code\" in err && err.code === \"ENOENT\";\n}\n\n/** Realpath-based read-time containment: resolve `relPath` against the root's\n * realpath and require the target's realpath to stay inside it. Returns null\n * on ENOENT or traversal (symlink escapes included). `rootReal` MUST already\n * be a realpath. The one implementation for host and plugins (#2461) — this\n * security-critical primitive must not drift per consumer. */\nexport function resolveWithinRoot(rootReal: string, relPath: string): string | null {\n const normalized = path.normalize(relPath || \"\");\n const resolved = path.resolve(rootReal, normalized);\n const resolvedReal = realpathOrNull(resolved);\n if (resolvedReal === null) return null;\n if (resolvedReal !== rootReal && !resolvedReal.startsWith(rootReal + path.sep)) {\n return null;\n }\n return resolvedReal;\n}\n\nfunction realpathOrNull(absPath: string): string | null {\n try {\n return realpathSync(absPath);\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;AAKA,SAAgB,SAAS,KAAuB;CAC9C,OAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,UAAU,OAAO,IAAI,SAAS;AAClF;;;;;;AAOA,SAAgB,kBAAkB,UAAkB,SAAgC;CAClF,MAAM,aAAa,KAAK,UAAU,WAAW,EAAE;CAE/C,MAAM,eAAe,eADJ,KAAK,QAAQ,UAAU,UACJ,CAAQ;CAC5C,IAAI,iBAAiB,MAAM,OAAO;CAClC,IAAI,iBAAiB,YAAY,CAAC,aAAa,WAAW,WAAW,KAAK,GAAG,GAC3E,OAAO;CAET,OAAO;AACT;AAEA,SAAS,eAAe,SAAgC;CACtD,IAAI;EACF,OAAO,aAAa,OAAO;CAC7B,QAAQ;EACN,OAAO;CACT;AACF"}