@mulmoclaude/core 5.12.1 → 5.14.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.
Files changed (186) hide show
  1. package/assets/helps/presenthtml.md +24 -0
  2. package/dist/artifacts/paths.cjs +1 -2
  3. package/dist/artifacts/paths.js +1 -2
  4. package/dist/collection/firestore.cjs +1 -2
  5. package/dist/collection/firestore.js +1 -2
  6. package/dist/collection/index.cjs +18 -30
  7. package/dist/collection/index.cjs.map +1 -1
  8. package/dist/collection/index.js +18 -30
  9. package/dist/collection/index.js.map +1 -1
  10. package/dist/collection/paths.cjs +1 -1
  11. package/dist/collection/paths.js +1 -1
  12. package/dist/collection/registry/index.cjs +1 -1
  13. package/dist/collection/registry/index.js +1 -1
  14. package/dist/collection/registry/server/index.cjs +17 -26
  15. package/dist/collection/registry/server/index.cjs.map +1 -1
  16. package/dist/collection/registry/server/index.js +16 -25
  17. package/dist/collection/registry/server/index.js.map +1 -1
  18. package/dist/collection/server/index.cjs +5 -5
  19. package/dist/collection/server/index.js +5 -5
  20. package/dist/collection-watchers/index.cjs +10 -14
  21. package/dist/collection-watchers/index.cjs.map +1 -1
  22. package/dist/collection-watchers/index.js +10 -14
  23. package/dist/collection-watchers/index.js.map +1 -1
  24. package/dist/{discovery-DgZRmO7F.cjs → discovery-CYIV1J5l.cjs} +25 -42
  25. package/dist/{discovery-DgZRmO7F.cjs.map → discovery-CYIV1J5l.cjs.map} +1 -1
  26. package/dist/{discovery-CbwHtcwk.js → discovery-duLlygnJ.js} +24 -41
  27. package/dist/{discovery-CbwHtcwk.js.map → discovery-duLlygnJ.js.map} +1 -1
  28. package/dist/{dist-BZ62pKuU.cjs → dist-734JaRYi.cjs} +2 -4
  29. package/dist/{dist-BZ62pKuU.cjs.map → dist-734JaRYi.cjs.map} +1 -1
  30. package/dist/{dist-MFUV9FYo.js → dist-BmO4oSQy.js} +2 -4
  31. package/dist/{dist-MFUV9FYo.js.map → dist-BmO4oSQy.js.map} +1 -1
  32. package/dist/errorMessage-D0kR547_.cjs +1 -0
  33. package/dist/errorMessage-TpKxrmeo.js +1 -0
  34. package/dist/{errors-zTAsW7dS.js → errors-0QwjDxsv.js} +3 -4
  35. package/dist/{errors-zTAsW7dS.js.map → errors-0QwjDxsv.js.map} +1 -1
  36. package/dist/{errors-B0xloJ3E.cjs → errors-B9mCEVG9.cjs} +3 -4
  37. package/dist/{errors-B0xloJ3E.cjs.map → errors-B9mCEVG9.cjs.map} +1 -1
  38. package/dist/feeds/index.cjs +2 -2
  39. package/dist/feeds/index.js +2 -2
  40. package/dist/feeds/paths.cjs +2 -3
  41. package/dist/feeds/paths.js +1 -2
  42. package/dist/feeds/server/index.cjs +23 -37
  43. package/dist/feeds/server/index.cjs.map +1 -1
  44. package/dist/feeds/server/index.js +22 -36
  45. package/dist/feeds/server/index.js.map +1 -1
  46. package/dist/file-change/index.cjs +2 -3
  47. package/dist/file-change/index.js +1 -2
  48. package/dist/files/index.cjs +159 -11
  49. package/dist/files/index.cjs.map +1 -1
  50. package/dist/files/index.d.ts +1 -0
  51. package/dist/files/index.js +154 -12
  52. package/dist/files/index.js.map +1 -1
  53. package/dist/files/verified.d.ts +33 -0
  54. package/dist/global-config/index.cjs +3 -5
  55. package/dist/global-config/index.cjs.map +1 -1
  56. package/dist/global-config/index.js +3 -5
  57. package/dist/global-config/index.js.map +1 -1
  58. package/dist/google/index.cjs +38 -67
  59. package/dist/google/index.cjs.map +1 -1
  60. package/dist/google/index.js +37 -66
  61. package/dist/google/index.js.map +1 -1
  62. package/dist/{graph-CURotEkH.cjs → graph-BvVMZfDV.cjs} +6 -11
  63. package/dist/{graph-CURotEkH.cjs.map → graph-BvVMZfDV.cjs.map} +1 -1
  64. package/dist/{graph-DBxSOx3v.js → graph-DBbzemby.js} +6 -11
  65. package/dist/{graph-DBxSOx3v.js.map → graph-DBbzemby.js.map} +1 -1
  66. package/dist/{iconGlyph-fSBp6k4J.cjs → iconGlyph-CFOiFsmq.cjs} +2 -3
  67. package/dist/{iconGlyph-fSBp6k4J.cjs.map → iconGlyph-CFOiFsmq.cjs.map} +1 -1
  68. package/dist/{iconGlyph-D8JeNg7R.js → iconGlyph-D9h__VaM.js} +2 -3
  69. package/dist/{iconGlyph-D8JeNg7R.js.map → iconGlyph-D9h__VaM.js.map} +1 -1
  70. package/dist/{ingestTypes-DS9HiR2I.cjs → ingestTypes-CLDvn7kw.cjs} +3 -4
  71. package/dist/{ingestTypes-DS9HiR2I.cjs.map → ingestTypes-CLDvn7kw.cjs.map} +1 -1
  72. package/dist/{ingestTypes-Bs31Xt5c.js → ingestTypes-DuXuSBSn.js} +3 -4
  73. package/dist/{ingestTypes-Bs31Xt5c.js.map → ingestTypes-DuXuSBSn.js.map} +1 -1
  74. package/dist/{itemId-CVrNibwT.cjs → itemId-D2XAQ8RU.cjs} +9 -17
  75. package/dist/{itemId-CVrNibwT.cjs.map → itemId-D2XAQ8RU.cjs.map} +1 -1
  76. package/dist/{itemId-C9s-Jd5s.js → itemId-D_pSpa3U.js} +9 -17
  77. package/dist/{itemId-C9s-Jd5s.js.map → itemId-D_pSpa3U.js.map} +1 -1
  78. package/dist/{listen-N_8XdKz_.cjs → listen-OmfLDX1l.cjs} +3 -4
  79. package/dist/{listen-N_8XdKz_.cjs.map → listen-OmfLDX1l.cjs.map} +1 -1
  80. package/dist/{listen-DUlzSOzX.js → listen-uiEnXcW9.js} +3 -4
  81. package/dist/{listen-DUlzSOzX.js.map → listen-uiEnXcW9.js.map} +1 -1
  82. package/dist/notifier/index.cjs +1 -1
  83. package/dist/notifier/index.js +1 -1
  84. package/dist/{notifier-CiemUClt.cjs → notifier-CRTk34EC.cjs} +6 -10
  85. package/dist/{notifier-CiemUClt.cjs.map → notifier-CRTk34EC.cjs.map} +1 -1
  86. package/dist/{notifier-dgkC-h80.js → notifier-htdf4ekH.js} +6 -10
  87. package/dist/{notifier-dgkC-h80.js.map → notifier-htdf4ekH.js.map} +1 -1
  88. package/dist/{paths-CkJxNZ7T.js → paths-BMQNHdaJ.js} +2 -3
  89. package/dist/{paths-CkJxNZ7T.js.map → paths-BMQNHdaJ.js.map} +1 -1
  90. package/dist/{paths-C8-jxR0s.cjs → paths-DUHAueEv.cjs} +2 -3
  91. package/dist/{paths-C8-jxR0s.cjs.map → paths-DUHAueEv.cjs.map} +1 -1
  92. package/dist/plugin-vue/i18n.cjs +1 -2
  93. package/dist/plugin-vue/i18n.js +1 -2
  94. package/dist/plugin-vue/index.cjs +9 -17
  95. package/dist/plugin-vue/index.cjs.map +1 -1
  96. package/dist/plugin-vue/index.js +9 -17
  97. package/dist/plugin-vue/index.js.map +1 -1
  98. package/dist/{project-C1ep9pvo.cjs → project-DDTIVEMU.cjs} +2 -3
  99. package/dist/{project-C1ep9pvo.cjs.map → project-DDTIVEMU.cjs.map} +1 -1
  100. package/dist/{project-B0j_Vf_Q.js → project-mU6-xLfy.js} +2 -3
  101. package/dist/{project-B0j_Vf_Q.js.map → project-mU6-xLfy.js.map} +1 -1
  102. package/dist/prompt-files/index.cjs +4 -6
  103. package/dist/prompt-files/index.cjs.map +1 -1
  104. package/dist/prompt-files/index.js +3 -5
  105. package/dist/prompt-files/index.js.map +1 -1
  106. package/dist/{promptSafety-DFaOnOWN.js → promptSafety-B8LECAkY.js} +14 -25
  107. package/dist/{promptSafety-DFaOnOWN.js.map → promptSafety-B8LECAkY.js.map} +1 -1
  108. package/dist/{promptSafety-yET9jLep.cjs → promptSafety-CjxafW2b.cjs} +14 -25
  109. package/dist/{promptSafety-yET9jLep.cjs.map → promptSafety-CjxafW2b.cjs.map} +1 -1
  110. package/dist/{relPath-DW8MC8VO.js → relPath-BkKmqiiF.js} +2 -3
  111. package/dist/{relPath-DW8MC8VO.js.map → relPath-BkKmqiiF.js.map} +1 -1
  112. package/dist/{relPath-CTAjGdCL.cjs → relPath-CZiP2S_a.cjs} +3 -4
  113. package/dist/{relPath-CTAjGdCL.cjs.map → relPath-CZiP2S_a.cjs.map} +1 -1
  114. package/dist/remote-host/index.cjs +1 -1
  115. package/dist/remote-host/index.js +1 -1
  116. package/dist/remote-host/server/index.cjs +14 -25
  117. package/dist/remote-host/server/index.cjs.map +1 -1
  118. package/dist/remote-host/server/index.js +14 -25
  119. package/dist/remote-host/server/index.js.map +1 -1
  120. package/dist/{remote-host-CR5W9uj4.cjs → remote-host-BW_eH-Nu.cjs} +4 -6
  121. package/dist/{remote-host-CR5W9uj4.cjs.map → remote-host-BW_eH-Nu.cjs.map} +1 -1
  122. package/dist/{remote-host-9NNAvUhU.js → remote-host-CSeDNbE6.js} +4 -6
  123. package/dist/{remote-host-9NNAvUhU.js.map → remote-host-CSeDNbE6.js.map} +1 -1
  124. package/dist/remote-view/index.cjs +3 -4
  125. package/dist/remote-view/index.js +3 -4
  126. package/dist/{rolldown-runtime-VH7oDXx4.cjs → rolldown-runtime-CmQyd0Gu.cjs} +1 -2
  127. package/dist/{root-BvwBUcol.cjs → root-9lRFeXbm.cjs} +10 -6
  128. package/dist/{root-BvwBUcol.cjs.map → root-9lRFeXbm.cjs.map} +1 -1
  129. package/dist/{root-BcS4-Kge.js → root-CqxPNSyK.js} +4 -6
  130. package/dist/{root-BcS4-Kge.js.map → root-CqxPNSyK.js.map} +1 -1
  131. package/dist/scheduler/index.cjs +6 -9
  132. package/dist/scheduler/index.cjs.map +1 -1
  133. package/dist/scheduler/index.js +5 -8
  134. package/dist/scheduler/index.js.map +1 -1
  135. package/dist/{server-CJek9Y3Q.cjs → server-ByKWGQn2.cjs} +25 -41
  136. package/dist/{server-CJek9Y3Q.cjs.map → server-ByKWGQn2.cjs.map} +1 -1
  137. package/dist/{server-BtbbQqBY.js → server-CA-alqqN.js} +24 -40
  138. package/dist/{server-BtbbQqBY.js.map → server-CA-alqqN.js.map} +1 -1
  139. package/dist/skill-bridge/index.cjs +3 -4
  140. package/dist/skill-bridge/index.js +2 -3
  141. package/dist/{slug-BpjumQfe.js → slug-D24AYqCZ.js} +2 -3
  142. package/dist/{slug-BpjumQfe.js.map → slug-D24AYqCZ.js.map} +1 -1
  143. package/dist/{slug-JxgB0ru9.cjs → slug-DVkuPjIv.cjs} +2 -3
  144. package/dist/{slug-JxgB0ru9.cjs.map → slug-DVkuPjIv.cjs.map} +1 -1
  145. package/dist/{templatePath-27vUZowm.cjs → templatePath-BIh7wqgS.cjs} +2 -3
  146. package/dist/{templatePath-27vUZowm.cjs.map → templatePath-BIh7wqgS.cjs.map} +1 -1
  147. package/dist/{templatePath-k_WNbL_Q.js → templatePath-CB3wtVpe.js} +2 -3
  148. package/dist/{templatePath-k_WNbL_Q.js.map → templatePath-CB3wtVpe.js.map} +1 -1
  149. package/dist/{text-CjDbP2O1.js → text-BQAuwKVj.js} +2 -3
  150. package/dist/{text-CjDbP2O1.js.map → text-BQAuwKVj.js.map} +1 -1
  151. package/dist/{text-CaAh9ZSO.cjs → text-BQiyo5R9.cjs} +2 -3
  152. package/dist/{text-CaAh9ZSO.cjs.map → text-BQiyo5R9.cjs.map} +1 -1
  153. package/dist/translation/client.cjs +1 -2
  154. package/dist/translation/client.js +1 -2
  155. package/dist/{types-BKVZrtyc.js → types-BLCZTGW2.js} +4 -7
  156. package/dist/{types-BKVZrtyc.js.map → types-BLCZTGW2.js.map} +1 -1
  157. package/dist/{types-CNqkLT4M.cjs → types-DPycxnDf.cjs} +4 -7
  158. package/dist/{types-CNqkLT4M.cjs.map → types-DPycxnDf.cjs.map} +1 -1
  159. package/dist/utils/fetch.cjs +0 -1
  160. package/dist/utils/fetch.js +0 -1
  161. package/dist/utils/index.cjs +3 -3
  162. package/dist/utils/index.js +3 -3
  163. package/dist/whisper/client.cjs +2 -4
  164. package/dist/whisper/client.cjs.map +1 -1
  165. package/dist/whisper/client.js +2 -4
  166. package/dist/whisper/client.js.map +1 -1
  167. package/dist/whisper/index.cjs +9 -15
  168. package/dist/whisper/index.cjs.map +1 -1
  169. package/dist/whisper/index.js +8 -14
  170. package/dist/whisper/index.js.map +1 -1
  171. package/dist/wiki/index.cjs +5 -7
  172. package/dist/wiki/index.cjs.map +1 -1
  173. package/dist/wiki/index.js +5 -7
  174. package/dist/wiki/index.js.map +1 -1
  175. package/dist/wiki/paths.cjs +3 -4
  176. package/dist/wiki/paths.js +2 -3
  177. package/dist/wiki/server/index.cjs +7 -11
  178. package/dist/wiki/server/index.cjs.map +1 -1
  179. package/dist/wiki/server/index.js +6 -10
  180. package/dist/wiki/server/index.js.map +1 -1
  181. package/dist/workspace-setup/index.js +4 -9
  182. package/dist/workspace-setup/index.js.map +1 -1
  183. package/dist/workspace-setup/slug.js +1 -2
  184. package/package.json +2 -2
  185. package/dist/errorMessage-OEQzRwsi.cjs +0 -1
  186. package/dist/errorMessage-VEiXHRnX.js +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["fsStat"],"sources":["../../src/files/json.ts","../../src/files/safe.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","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","// 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,MAAM,gBAAgB,UAAU,KAAK,UAAU,MAAM,MAAM,WAAW,GAAG,IAAI;AAC/E;;;;;ACHA,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;;;ACOA,IAAa,sBAAsB,CAAC,KAAK;AACzC,IAAa,kBAAkB,CAAC,SAAS,MAAM;;;AAiB/C,SAAgB,cAAc,MAAc,OAAe,YAA8C;CAC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O,KAAK,WAAW,SAAS,IAAI,KAAK,QAAQ,SAAS,IAAI;AAChE"}
1
+ {"version":3,"file":"index.js","names":["fsStat"],"sources":["../../src/files/json.ts","../../src/files/safe.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","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","// 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,MAAM,gBAAgB,UAAU,KAAK,UAAU,MAAM,MAAM,WAAW,GAAG,IAAI;AAC/E;;;;ACHA,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;;AClBA,IAAM,aAAa,UAAU,YAAY,UAAU,cAAc,MAAM,UAAU,cAAc;AAC/F,IAAM,eAAe,UAAU,WAAW,UAAU,UAAU,UAAU,UAAU,UAAU,cAAc;AAC1G,IAAM,uBAAuB;;AAU7B,eAAsB,kBAAkB,SAAyC;CAC/E,IAAI;EACF,OAAO,MAAM,SAAS,SAAS,OAAO;CACxC,SAAS,KAAK;EACZ,IAAI,SAAS,GAAG,GA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,QAAQ,MAAM,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,OAAO,KAAK,QAAQ,eAAe,GAAG,IAAI;CAGnF,MAAM,YAAY,sBAAsB,KAAK,SAAS,IAAI,KAAK,KAAK,GAAG,IAAI,IAAI,KAAK,KAAK,GAAG;CAI5F,OAAO,KAAK,WAAW,SAAS,IAAI,KAAK,QAAQ,SAAS,IAAI;AAChE"}
@@ -0,0 +1,33 @@
1
+ import { FileHandle } from 'node:fs/promises';
2
+ /** Test seams at the points where a real race would swap a path. */
3
+ export interface VerifiedFileHooks {
4
+ beforeOpen?: () => Promise<void>;
5
+ afterOpen?: () => Promise<void>;
6
+ beforeRename?: () => Promise<void>;
7
+ }
8
+ /** Only a missing path reads as null; EACCES, ELOOP, ENOTDIR … propagate. */
9
+ export declare function realpathIfPresent(absPath: string): Promise<string | null>;
10
+ /** Real location of `relative` (host-native) if it exists inside `rootReal`; null when missing or outside. `rootReal` MUST be a realpath. */
11
+ export declare function resolveExistingWithinRoot(rootReal: string, relative: string): Promise<string | null>;
12
+ /** A scope folder under a trusted anchor. `trustedReal` MUST be a realpath that the party being defended
13
+ * against cannot replace (the workspace: in Docker it is the mount root). The scope is re-resolved under
14
+ * it at every check, so a scope replaced by a link out is refused; a real directory moved into the
15
+ * scope's place from inside the anchor is simply the scope from then on. */
16
+ export interface VerifiedScope {
17
+ trustedReal: string;
18
+ scopeWithinTrusted: string;
19
+ }
20
+ /** The scope's realpath if it exists inside the anchor now; null when absent or led outside. */
21
+ export declare const scopeRealpath: (scope: VerifiedScope) => Promise<string | null>;
22
+ /** Opens `relative` under the scope for reading and proves, after opening, that the handle is the file
23
+ * the scope holds now. Null when missing, outside, or swapped during the call. The caller owns the handle. */
24
+ export declare function openVerifiedWithinScope(scope: VerifiedScope, relative: string, hooks?: VerifiedFileHooks): Promise<FileHandle | null>;
25
+ /** Atomic write of `leaf` into `dirReal` (an already-confined directory of the scope). The staging file is
26
+ * verified to sit inside the scope before any byte is written, and a parent swapped for a link mid-call
27
+ * makes the write fail — unless the link's target is a directory the actor could already write. */
28
+ export declare function writeFileVerifiedInScope(scope: VerifiedScope, dirReal: string, leaf: string, content: string | Uint8Array, hooks?: VerifiedFileHooks): Promise<void>;
29
+ /** Exclusive create of `leaf` in `dirReal` (an already-confined directory of the scope): throws EEXIST when `leaf`
30
+ * exists, as `writeFile(…, { flag: "wx" })` does. The new file is verified to sit inside the scope before any byte is
31
+ * written, and the bytes go through its handle. A parent swapped for a link before the create leaves an empty file
32
+ * in the link's target and makes the call fail; it is not removed, because by then the name may be someone else's. */
33
+ export declare function createFileVerifiedInScope(scope: VerifiedScope, dirReal: string, leaf: string, content: string | Uint8Array, hooks?: VerifiedFileHooks): Promise<void>;
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_paths = require("../paths-C8-jxR0s.cjs");
2
+ const require_paths = require("../paths-DUHAueEv.cjs");
3
3
  let node_fs_promises = require("node:fs/promises");
4
- //#region src/global-config/schema.ts
4
+ // src/global-config/schema.ts
5
5
  /** A user-supplied regular expression source is compiled and then run against
6
6
  * whole documents on every keystroke. Length is the cheap, honest guard: it
7
7
  * bounds how baroque — and so how catastrophically backtracking — the pattern
@@ -37,8 +37,7 @@ function readDocumentBookmarkPattern(config) {
37
37
  if (pattern.length === 0 || pattern.length > 200) return null;
38
38
  return compiles(pattern) ? pattern : null;
39
39
  }
40
- //#endregion
41
- //#region src/global-config/index.ts
40
+ // src/global-config/index.ts
42
41
  /**
43
42
  * Parse `~/.config/mulmo/config.json`. Returns `null` when the file is absent
44
43
  * or unparseable — both are ordinary states (there is no UI that creates it),
@@ -58,7 +57,6 @@ async function readMulmoGlobalConfig(home) {
58
57
  async function loadDocumentBookmarkPattern(home) {
59
58
  return readDocumentBookmarkPattern(await readMulmoGlobalConfig(home));
60
59
  }
61
- //#endregion
62
60
  exports.MAX_BOOKMARK_PATTERN_LENGTH = MAX_BOOKMARK_PATTERN_LENGTH;
63
61
  exports.loadDocumentBookmarkPattern = loadDocumentBookmarkPattern;
64
62
  exports.mulmoConfigDir = require_paths.mulmoConfigDir;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["readFile","mulmoGlobalConfigPath"],"sources":["../../src/global-config/schema.ts","../../src/global-config/index.ts"],"sourcesContent":["// Pure readers over the parsed `~/.config/mulmo/config.json` document. No IO\n// here so the validation rules are unit-testable without a filesystem, and so a\n// host that already has the document in memory can reuse them.\n//\n// Every reader is TOLERANT by design: this file is hand-edited (there is no UI\n// for it yet), and a typo in one key must not take out the app or the other\n// keys. An unusable value reads as \"not configured\" and the caller applies its\n// own default.\n\n/** A user-supplied regular expression source is compiled and then run against\n * whole documents on every keystroke. Length is the cheap, honest guard: it\n * bounds how baroque — and so how catastrophically backtracking — the pattern\n * can be, without pretending to be a ReDoS analyser. The file is machine-local\n * and hand-written, so the threat model is \"the user's own typo\", not attack. */\nexport const MAX_BOOKMARK_PATTERN_LENGTH = 200;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** True when `source` compiles as a regular expression. `new RegExp` is the\n * only real validator — there is no cheaper way to reject `\"^([a-z\"`. */\nfunction compiles(source: string): boolean {\n try {\n return RegExp(source) instanceof RegExp;\n } catch {\n return false;\n }\n}\n\n/**\n * `documentBookmarks.pattern` — the regex whose matches the markdown source\n * editor marks in its left-edge rail. Returns the raw SOURCE string (not a\n * compiled RegExp): the value crosses a JSON dispatch hop to the browser, which\n * compiles it there.\n *\n * Returns null — meaning \"not configured, use your default\" — for a missing\n * file, a missing key, a non-string, an empty string, an over-long string, or\n * one that does not compile.\n */\nexport function readDocumentBookmarkPattern(config: unknown): string | null {\n if (!isRecord(config)) return null;\n const { documentBookmarks } = config;\n if (!isRecord(documentBookmarks)) return null;\n const { pattern } = documentBookmarks;\n if (typeof pattern !== \"string\") return null;\n if (pattern.length === 0 || pattern.length > MAX_BOOKMARK_PATTERN_LENGTH) return null;\n return compiles(pattern) ? pattern : null;\n}\n","// Entry point for `@mulmoclaude/core/global-config` — the host-neutral\n// per-user config file (`~/.config/mulmo/config.json`) shared by MulmoClaude\n// and MulmoTerminal. Server-only (node:fs); the values it yields are plain\n// JSON, so they cross a dispatch hop to a plugin View unchanged.\nimport { readFile } from \"node:fs/promises\";\nimport { mulmoGlobalConfigPath } from \"./paths.js\";\nimport { readDocumentBookmarkPattern } from \"./schema.js\";\n\nexport { mulmoConfigDir, mulmoGlobalConfigPath } from \"./paths.js\";\nexport { readDocumentBookmarkPattern, MAX_BOOKMARK_PATTERN_LENGTH } from \"./schema.js\";\n\n/**\n * Parse `~/.config/mulmo/config.json`. Returns `null` when the file is absent\n * or unparseable — both are ordinary states (there is no UI that creates it),\n * and every reader in `./schema` treats `null` as \"nothing configured\".\n *\n * Not cached: the file is read at most once per view open, and caching would\n * mean a hand-edit needs an app restart to take effect.\n */\nexport async function readMulmoGlobalConfig(home?: string): Promise<unknown> {\n try {\n return JSON.parse(await readFile(mulmoGlobalConfigPath(home), \"utf-8\"));\n } catch {\n return null;\n }\n}\n\n/** Convenience: the configured document-bookmark regex source, or null. */\nexport async function loadDocumentBookmarkPattern(home?: string): Promise<string | null> {\n return readDocumentBookmarkPattern(await readMulmoGlobalConfig(home));\n}\n"],"mappings":";;;;;;;;;AAcA,IAAa,8BAA8B;AAE3C,IAAM,YAAY,UAAqD,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;;AAI1I,SAAS,SAAS,QAAyB;CACzC,IAAI;EACF,OAAO,OAAO,MAAM,aAAa;CACnC,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;;AAYA,SAAgB,4BAA4B,QAAgC;CAC1E,IAAI,CAAC,SAAS,MAAM,GAAG,OAAO;CAC9B,MAAM,EAAE,sBAAsB;CAC9B,IAAI,CAAC,SAAS,iBAAiB,GAAG,OAAO;CACzC,MAAM,EAAE,YAAY;CACpB,IAAI,OAAO,YAAY,UAAU,OAAO;CACxC,IAAI,QAAQ,WAAW,KAAK,QAAQ,SAAA,KAAsC,OAAO;CACjF,OAAO,SAAS,OAAO,IAAI,UAAU;AACvC;;;;;;;;;;;AC3BA,eAAsB,sBAAsB,MAAiC;CAC3E,IAAI;EACF,OAAO,KAAK,MAAM,OAAA,GAAMA,iBAAAA,SAAAA,CAASC,cAAAA,sBAAsB,IAAI,GAAG,OAAO,CAAC;CACxE,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,eAAsB,4BAA4B,MAAuC;CACvF,OAAO,4BAA4B,MAAM,sBAAsB,IAAI,CAAC;AACtE"}
1
+ {"version":3,"file":"index.cjs","names":["readFile","mulmoGlobalConfigPath"],"sources":["../../src/global-config/schema.ts","../../src/global-config/index.ts"],"sourcesContent":["// Pure readers over the parsed `~/.config/mulmo/config.json` document. No IO\n// here so the validation rules are unit-testable without a filesystem, and so a\n// host that already has the document in memory can reuse them.\n//\n// Every reader is TOLERANT by design: this file is hand-edited (there is no UI\n// for it yet), and a typo in one key must not take out the app or the other\n// keys. An unusable value reads as \"not configured\" and the caller applies its\n// own default.\n\n/** A user-supplied regular expression source is compiled and then run against\n * whole documents on every keystroke. Length is the cheap, honest guard: it\n * bounds how baroque — and so how catastrophically backtracking — the pattern\n * can be, without pretending to be a ReDoS analyser. The file is machine-local\n * and hand-written, so the threat model is \"the user's own typo\", not attack. */\nexport const MAX_BOOKMARK_PATTERN_LENGTH = 200;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** True when `source` compiles as a regular expression. `new RegExp` is the\n * only real validator — there is no cheaper way to reject `\"^([a-z\"`. */\nfunction compiles(source: string): boolean {\n try {\n return RegExp(source) instanceof RegExp;\n } catch {\n return false;\n }\n}\n\n/**\n * `documentBookmarks.pattern` — the regex whose matches the markdown source\n * editor marks in its left-edge rail. Returns the raw SOURCE string (not a\n * compiled RegExp): the value crosses a JSON dispatch hop to the browser, which\n * compiles it there.\n *\n * Returns null — meaning \"not configured, use your default\" — for a missing\n * file, a missing key, a non-string, an empty string, an over-long string, or\n * one that does not compile.\n */\nexport function readDocumentBookmarkPattern(config: unknown): string | null {\n if (!isRecord(config)) return null;\n const { documentBookmarks } = config;\n if (!isRecord(documentBookmarks)) return null;\n const { pattern } = documentBookmarks;\n if (typeof pattern !== \"string\") return null;\n if (pattern.length === 0 || pattern.length > MAX_BOOKMARK_PATTERN_LENGTH) return null;\n return compiles(pattern) ? pattern : null;\n}\n","// Entry point for `@mulmoclaude/core/global-config` — the host-neutral\n// per-user config file (`~/.config/mulmo/config.json`) shared by MulmoClaude\n// and MulmoTerminal. Server-only (node:fs); the values it yields are plain\n// JSON, so they cross a dispatch hop to a plugin View unchanged.\nimport { readFile } from \"node:fs/promises\";\nimport { mulmoGlobalConfigPath } from \"./paths.js\";\nimport { readDocumentBookmarkPattern } from \"./schema.js\";\n\nexport { mulmoConfigDir, mulmoGlobalConfigPath } from \"./paths.js\";\nexport { readDocumentBookmarkPattern, MAX_BOOKMARK_PATTERN_LENGTH } from \"./schema.js\";\n\n/**\n * Parse `~/.config/mulmo/config.json`. Returns `null` when the file is absent\n * or unparseable — both are ordinary states (there is no UI that creates it),\n * and every reader in `./schema` treats `null` as \"nothing configured\".\n *\n * Not cached: the file is read at most once per view open, and caching would\n * mean a hand-edit needs an app restart to take effect.\n */\nexport async function readMulmoGlobalConfig(home?: string): Promise<unknown> {\n try {\n return JSON.parse(await readFile(mulmoGlobalConfigPath(home), \"utf-8\"));\n } catch {\n return null;\n }\n}\n\n/** Convenience: the configured document-bookmark regex source, or null. */\nexport async function loadDocumentBookmarkPattern(home?: string): Promise<string | null> {\n return readDocumentBookmarkPattern(await readMulmoGlobalConfig(home));\n}\n"],"mappings":";;;;;;;;;AAcA,IAAa,8BAA8B;AAE3C,IAAM,YAAY,UAAqD,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;;AAI1I,SAAS,SAAS,QAAyB;CACzC,IAAI;EACF,OAAO,OAAO,MAAM,aAAa;CACnC,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;;AAYA,SAAgB,4BAA4B,QAAgC;CAC1E,IAAI,CAAC,SAAS,MAAM,GAAG,OAAO;CAC9B,MAAM,EAAE,sBAAsB;CAC9B,IAAI,CAAC,SAAS,iBAAiB,GAAG,OAAO;CACzC,MAAM,EAAE,YAAY;CACpB,IAAI,OAAO,YAAY,UAAU,OAAO;CACxC,IAAI,QAAQ,WAAW,KAAK,QAAQ,SAAA,KAAsC,OAAO;CACjF,OAAO,SAAS,OAAO,IAAI,UAAU;AACvC;;;;;;;;;;AC3BA,eAAsB,sBAAsB,MAAiC;CAC3E,IAAI;EACF,OAAO,KAAK,MAAM,OAAA,GAAMA,iBAAAA,SAAAA,CAASC,cAAAA,sBAAsB,IAAI,GAAG,OAAO,CAAC;CACxE,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,eAAsB,4BAA4B,MAAuC;CACvF,OAAO,4BAA4B,MAAM,sBAAsB,IAAI,CAAC;AACtE"}
@@ -1,6 +1,6 @@
1
- import { n as mulmoGlobalConfigPath, t as mulmoConfigDir } from "../paths-CkJxNZ7T.js";
1
+ import { n as mulmoGlobalConfigPath, t as mulmoConfigDir } from "../paths-BMQNHdaJ.js";
2
2
  import { readFile } from "node:fs/promises";
3
- //#region src/global-config/schema.ts
3
+ // src/global-config/schema.ts
4
4
  /** A user-supplied regular expression source is compiled and then run against
5
5
  * whole documents on every keystroke. Length is the cheap, honest guard: it
6
6
  * bounds how baroque — and so how catastrophically backtracking — the pattern
@@ -36,8 +36,7 @@ function readDocumentBookmarkPattern(config) {
36
36
  if (pattern.length === 0 || pattern.length > 200) return null;
37
37
  return compiles(pattern) ? pattern : null;
38
38
  }
39
- //#endregion
40
- //#region src/global-config/index.ts
39
+ // src/global-config/index.ts
41
40
  /**
42
41
  * Parse `~/.config/mulmo/config.json`. Returns `null` when the file is absent
43
42
  * or unparseable — both are ordinary states (there is no UI that creates it),
@@ -57,7 +56,6 @@ async function readMulmoGlobalConfig(home) {
57
56
  async function loadDocumentBookmarkPattern(home) {
58
57
  return readDocumentBookmarkPattern(await readMulmoGlobalConfig(home));
59
58
  }
60
- //#endregion
61
59
  export { MAX_BOOKMARK_PATTERN_LENGTH, loadDocumentBookmarkPattern, mulmoConfigDir, mulmoGlobalConfigPath, readDocumentBookmarkPattern, readMulmoGlobalConfig };
62
60
 
63
61
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/global-config/schema.ts","../../src/global-config/index.ts"],"sourcesContent":["// Pure readers over the parsed `~/.config/mulmo/config.json` document. No IO\n// here so the validation rules are unit-testable without a filesystem, and so a\n// host that already has the document in memory can reuse them.\n//\n// Every reader is TOLERANT by design: this file is hand-edited (there is no UI\n// for it yet), and a typo in one key must not take out the app or the other\n// keys. An unusable value reads as \"not configured\" and the caller applies its\n// own default.\n\n/** A user-supplied regular expression source is compiled and then run against\n * whole documents on every keystroke. Length is the cheap, honest guard: it\n * bounds how baroque — and so how catastrophically backtracking — the pattern\n * can be, without pretending to be a ReDoS analyser. The file is machine-local\n * and hand-written, so the threat model is \"the user's own typo\", not attack. */\nexport const MAX_BOOKMARK_PATTERN_LENGTH = 200;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** True when `source` compiles as a regular expression. `new RegExp` is the\n * only real validator — there is no cheaper way to reject `\"^([a-z\"`. */\nfunction compiles(source: string): boolean {\n try {\n return RegExp(source) instanceof RegExp;\n } catch {\n return false;\n }\n}\n\n/**\n * `documentBookmarks.pattern` — the regex whose matches the markdown source\n * editor marks in its left-edge rail. Returns the raw SOURCE string (not a\n * compiled RegExp): the value crosses a JSON dispatch hop to the browser, which\n * compiles it there.\n *\n * Returns null — meaning \"not configured, use your default\" — for a missing\n * file, a missing key, a non-string, an empty string, an over-long string, or\n * one that does not compile.\n */\nexport function readDocumentBookmarkPattern(config: unknown): string | null {\n if (!isRecord(config)) return null;\n const { documentBookmarks } = config;\n if (!isRecord(documentBookmarks)) return null;\n const { pattern } = documentBookmarks;\n if (typeof pattern !== \"string\") return null;\n if (pattern.length === 0 || pattern.length > MAX_BOOKMARK_PATTERN_LENGTH) return null;\n return compiles(pattern) ? pattern : null;\n}\n","// Entry point for `@mulmoclaude/core/global-config` — the host-neutral\n// per-user config file (`~/.config/mulmo/config.json`) shared by MulmoClaude\n// and MulmoTerminal. Server-only (node:fs); the values it yields are plain\n// JSON, so they cross a dispatch hop to a plugin View unchanged.\nimport { readFile } from \"node:fs/promises\";\nimport { mulmoGlobalConfigPath } from \"./paths.js\";\nimport { readDocumentBookmarkPattern } from \"./schema.js\";\n\nexport { mulmoConfigDir, mulmoGlobalConfigPath } from \"./paths.js\";\nexport { readDocumentBookmarkPattern, MAX_BOOKMARK_PATTERN_LENGTH } from \"./schema.js\";\n\n/**\n * Parse `~/.config/mulmo/config.json`. Returns `null` when the file is absent\n * or unparseable — both are ordinary states (there is no UI that creates it),\n * and every reader in `./schema` treats `null` as \"nothing configured\".\n *\n * Not cached: the file is read at most once per view open, and caching would\n * mean a hand-edit needs an app restart to take effect.\n */\nexport async function readMulmoGlobalConfig(home?: string): Promise<unknown> {\n try {\n return JSON.parse(await readFile(mulmoGlobalConfigPath(home), \"utf-8\"));\n } catch {\n return null;\n }\n}\n\n/** Convenience: the configured document-bookmark regex source, or null. */\nexport async function loadDocumentBookmarkPattern(home?: string): Promise<string | null> {\n return readDocumentBookmarkPattern(await readMulmoGlobalConfig(home));\n}\n"],"mappings":";;;;;;;;AAcA,IAAa,8BAA8B;AAE3C,IAAM,YAAY,UAAqD,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;;AAI1I,SAAS,SAAS,QAAyB;CACzC,IAAI;EACF,OAAO,OAAO,MAAM,aAAa;CACnC,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;;AAYA,SAAgB,4BAA4B,QAAgC;CAC1E,IAAI,CAAC,SAAS,MAAM,GAAG,OAAO;CAC9B,MAAM,EAAE,sBAAsB;CAC9B,IAAI,CAAC,SAAS,iBAAiB,GAAG,OAAO;CACzC,MAAM,EAAE,YAAY;CACpB,IAAI,OAAO,YAAY,UAAU,OAAO;CACxC,IAAI,QAAQ,WAAW,KAAK,QAAQ,SAAA,KAAsC,OAAO;CACjF,OAAO,SAAS,OAAO,IAAI,UAAU;AACvC;;;;;;;;;;;AC3BA,eAAsB,sBAAsB,MAAiC;CAC3E,IAAI;EACF,OAAO,KAAK,MAAM,MAAM,SAAS,sBAAsB,IAAI,GAAG,OAAO,CAAC;CACxE,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,eAAsB,4BAA4B,MAAuC;CACvF,OAAO,4BAA4B,MAAM,sBAAsB,IAAI,CAAC;AACtE"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/global-config/schema.ts","../../src/global-config/index.ts"],"sourcesContent":["// Pure readers over the parsed `~/.config/mulmo/config.json` document. No IO\n// here so the validation rules are unit-testable without a filesystem, and so a\n// host that already has the document in memory can reuse them.\n//\n// Every reader is TOLERANT by design: this file is hand-edited (there is no UI\n// for it yet), and a typo in one key must not take out the app or the other\n// keys. An unusable value reads as \"not configured\" and the caller applies its\n// own default.\n\n/** A user-supplied regular expression source is compiled and then run against\n * whole documents on every keystroke. Length is the cheap, honest guard: it\n * bounds how baroque — and so how catastrophically backtracking — the pattern\n * can be, without pretending to be a ReDoS analyser. The file is machine-local\n * and hand-written, so the threat model is \"the user's own typo\", not attack. */\nexport const MAX_BOOKMARK_PATTERN_LENGTH = 200;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** True when `source` compiles as a regular expression. `new RegExp` is the\n * only real validator — there is no cheaper way to reject `\"^([a-z\"`. */\nfunction compiles(source: string): boolean {\n try {\n return RegExp(source) instanceof RegExp;\n } catch {\n return false;\n }\n}\n\n/**\n * `documentBookmarks.pattern` — the regex whose matches the markdown source\n * editor marks in its left-edge rail. Returns the raw SOURCE string (not a\n * compiled RegExp): the value crosses a JSON dispatch hop to the browser, which\n * compiles it there.\n *\n * Returns null — meaning \"not configured, use your default\" — for a missing\n * file, a missing key, a non-string, an empty string, an over-long string, or\n * one that does not compile.\n */\nexport function readDocumentBookmarkPattern(config: unknown): string | null {\n if (!isRecord(config)) return null;\n const { documentBookmarks } = config;\n if (!isRecord(documentBookmarks)) return null;\n const { pattern } = documentBookmarks;\n if (typeof pattern !== \"string\") return null;\n if (pattern.length === 0 || pattern.length > MAX_BOOKMARK_PATTERN_LENGTH) return null;\n return compiles(pattern) ? pattern : null;\n}\n","// Entry point for `@mulmoclaude/core/global-config` — the host-neutral\n// per-user config file (`~/.config/mulmo/config.json`) shared by MulmoClaude\n// and MulmoTerminal. Server-only (node:fs); the values it yields are plain\n// JSON, so they cross a dispatch hop to a plugin View unchanged.\nimport { readFile } from \"node:fs/promises\";\nimport { mulmoGlobalConfigPath } from \"./paths.js\";\nimport { readDocumentBookmarkPattern } from \"./schema.js\";\n\nexport { mulmoConfigDir, mulmoGlobalConfigPath } from \"./paths.js\";\nexport { readDocumentBookmarkPattern, MAX_BOOKMARK_PATTERN_LENGTH } from \"./schema.js\";\n\n/**\n * Parse `~/.config/mulmo/config.json`. Returns `null` when the file is absent\n * or unparseable — both are ordinary states (there is no UI that creates it),\n * and every reader in `./schema` treats `null` as \"nothing configured\".\n *\n * Not cached: the file is read at most once per view open, and caching would\n * mean a hand-edit needs an app restart to take effect.\n */\nexport async function readMulmoGlobalConfig(home?: string): Promise<unknown> {\n try {\n return JSON.parse(await readFile(mulmoGlobalConfigPath(home), \"utf-8\"));\n } catch {\n return null;\n }\n}\n\n/** Convenience: the configured document-bookmark regex source, or null. */\nexport async function loadDocumentBookmarkPattern(home?: string): Promise<string | null> {\n return readDocumentBookmarkPattern(await readMulmoGlobalConfig(home));\n}\n"],"mappings":";;;;;;;;AAcA,IAAa,8BAA8B;AAE3C,IAAM,YAAY,UAAqD,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;;AAI1I,SAAS,SAAS,QAAyB;CACzC,IAAI;EACF,OAAO,OAAO,MAAM,aAAa;CACnC,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;;AAYA,SAAgB,4BAA4B,QAAgC;CAC1E,IAAI,CAAC,SAAS,MAAM,GAAG,OAAO;CAC9B,MAAM,EAAE,sBAAsB;CAC9B,IAAI,CAAC,SAAS,iBAAiB,GAAG,OAAO;CACzC,MAAM,EAAE,YAAY;CACpB,IAAI,OAAO,YAAY,UAAU,OAAO;CACxC,IAAI,QAAQ,WAAW,KAAK,QAAQ,SAAA,KAAsC,OAAO;CACjF,OAAO,SAAS,OAAO,IAAI,UAAU;AACvC;;;;;;;;;;AC3BA,eAAsB,sBAAsB,MAAiC;CAC3E,IAAI;EACF,OAAO,KAAK,MAAM,MAAM,SAAS,sBAAsB,IAAI,GAAG,OAAO,CAAC;CACxE,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,eAAsB,4BAA4B,MAAuC;CACvF,OAAO,4BAA4B,MAAM,sBAAsB,IAAI,CAAC;AACtE"}
@@ -1,14 +1,14 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_rolldown_runtime = require("../rolldown-runtime-VH7oDXx4.cjs");
3
- const require_dist = require("../dist-BZ62pKuU.cjs");
4
- require("../errors-B0xloJ3E.cjs");
5
- const require_text = require("../text-CaAh9ZSO.cjs");
6
- const require_root = require("../root-BvwBUcol.cjs");
2
+ const require_rolldown_runtime = require("../rolldown-runtime-CmQyd0Gu.cjs");
3
+ const require_dist = require("../dist-734JaRYi.cjs");
4
+ require("../errors-B9mCEVG9.cjs");
5
+ const require_text = require("../text-BQiyo5R9.cjs");
6
+ const require_root = require("../root-9lRFeXbm.cjs");
7
7
  const require_utils_fetch = require("../utils/fetch.cjs");
8
- const require_itemId = require("../itemId-CVrNibwT.cjs");
9
- const require_project = require("../project-C1ep9pvo.cjs");
10
- const require_discovery = require("../discovery-DgZRmO7F.cjs");
11
- const require_paths = require("../paths-C8-jxR0s.cjs");
8
+ const require_itemId = require("../itemId-D2XAQ8RU.cjs");
9
+ const require_project = require("../project-DDTIVEMU.cjs");
10
+ const require_discovery = require("../discovery-CYIV1J5l.cjs");
11
+ const require_paths = require("../paths-DUHAueEv.cjs");
12
12
  let node_fs = require("node:fs");
13
13
  let node_path = require("node:path");
14
14
  node_path = require_rolldown_runtime.__toESM(node_path, 1);
@@ -19,14 +19,13 @@ let _receptron_task_scheduler = require("@receptron/task-scheduler");
19
19
  let node_http = require("node:http");
20
20
  node_http = require_rolldown_runtime.__toESM(node_http, 1);
21
21
  let google_auth_library = require("google-auth-library");
22
- //#region src/google/host.ts
22
+ // src/google/host.ts
23
23
  var hostSlot = require_discovery.createHostSlot("@mulmoclaude/core/google: configureGoogleHost()");
24
24
  function configureGoogleHost(binding) {
25
25
  hostSlot.set(binding.log);
26
26
  }
27
27
  var log = require_discovery.createForwardingLogger(() => hostSlot.peek());
28
- //#endregion
29
- //#region src/google/datetime.ts
28
+ // src/google/datetime.ts
30
29
  var ISO_DATE_TIME_WITH_OFFSET_RE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:Z|[+-](\d{2}):(\d{2}))$/;
31
30
  var FRACTIONAL_SECONDS_RE$2 = /\.\d+(?=Z|[+-])/;
32
31
  var MAX_HOUR = 23;
@@ -44,8 +43,7 @@ var isIsoDateTimeWithOffset = (value) => {
44
43
  const offsetInRange = match[7] === void 0 || Number(match[7]) <= MAX_HOUR && Number(match[8]) <= MAX_MINUTE;
45
44
  return isRealCalendarDate(year, month, day) && timeInRange && offsetInRange;
46
45
  };
47
- //#endregion
48
- //#region src/google/deletePlan.ts
46
+ // src/google/deletePlan.ts
49
47
  var ATTENDEES_REASON = "it carries attendees — deleting an invited event withdraws it from their calendars too";
50
48
  var ALREADY_GONE_REASON = "it is no longer in Google";
51
49
  /** The message the push reports for a refusal, with the event named. */
@@ -74,15 +72,13 @@ function planDelete(fetched) {
74
72
  etag: fetched.etag
75
73
  };
76
74
  }
77
- //#endregion
78
- //#region src/google/util.ts
75
+ // src/google/util.ts
79
76
  var ONE_SECOND_MS = 1e3;
80
77
  var ONE_MINUTE_MS = 6e4;
81
78
  function isRecord(value) {
82
79
  return typeof value === "object" && value !== null && !Array.isArray(value);
83
80
  }
84
- //#endregion
85
- //#region src/google/eventDerived.ts
81
+ // src/google/eventDerived.ts
86
82
  var stringAt = (record, key) => typeof record[key] === "string" ? record[key] : "";
87
83
  var recordsIn = (value) => Array.isArray(value) ? value.filter(isRecord) : [];
88
84
  /** The signed-in user's own `responseStatus` on this event, `""` when Google
@@ -112,8 +108,7 @@ function conferenceVideoUri(conferenceData) {
112
108
  const video = recordsIn(conferenceData.entryPoints).find((entry) => entry.entryPointType === VIDEO_ENTRY_POINT);
113
109
  return video === void 0 ? "" : stringAt(video, "uri");
114
110
  }
115
- //#endregion
116
- //#region src/google/eventSpanInput.ts
111
+ // src/google/eventSpanInput.ts
117
112
  var DATE_ONLY_RE$1 = /^\d{4}-\d{2}-\d{2}$/;
118
113
  /** Whether `value` is a bare calendar day — the all-day spelling of an event
119
114
  * time, and the one shape `isIsoDateTimeWithOffset` is built to refuse.
@@ -210,8 +205,7 @@ function resolvePartialSpanInput(start, end) {
210
205
  times: {}
211
206
  };
212
207
  }
213
- //#endregion
214
- //#region src/google/paths.ts
208
+ // src/google/paths.ts
215
209
  /** Same directory as every other cross-app per-user file — see
216
210
  * `../global-config/paths.ts`, which owns the spelling. */
217
211
  function googleConfigDir(home) {
@@ -227,8 +221,7 @@ function googleTokenPath(home) {
227
221
  function googleSecretsDir(home) {
228
222
  return (0, node_path.join)(home ?? (0, node_os.homedir)(), ".secrets");
229
223
  }
230
- //#endregion
231
- //#region src/google/clientSecret.ts
224
+ // src/google/clientSecret.ts
232
225
  var isNonEmptyString = (value) => typeof value === "string" && value !== "";
233
226
  var isInstalledClientSecret = (value) => {
234
227
  if (!isRecord(value) || !isRecord(value.installed)) return false;
@@ -273,8 +266,7 @@ async function loadClientSecret(home) {
273
266
  client_secret: parsed.installed.client_secret
274
267
  };
275
268
  }
276
- //#endregion
277
- //#region src/google/fsJson.ts
269
+ // src/google/fsJson.ts
278
270
  var JSON_INDENT = 2;
279
271
  async function readJsonOrNull(filePath) {
280
272
  try {
@@ -293,8 +285,7 @@ async function writeJsonAtomicWithMode(filePath, data, mode) {
293
285
  uniqueTmp: false
294
286
  });
295
287
  }
296
- //#endregion
297
- //#region src/google/tokenStore.ts
288
+ // src/google/tokenStore.ts
298
289
  var TOKEN_FILE_MODE = 384;
299
290
  function mergeGoogleTokens(existing, incoming) {
300
291
  const merged = {
@@ -332,8 +323,7 @@ async function saveGoogleTokens(incoming, home) {
332
323
  async function deleteGoogleTokens(home) {
333
324
  await (0, node_fs_promises.rm)(googleTokenPath(home), { force: true });
334
325
  }
335
- //#endregion
336
- //#region src/google/broker.ts
326
+ // src/google/broker.ts
337
327
  var DEFAULT_BROKER_BASE_URL = "https://asia-northeast1-mulmoserver.cloudfunctions.net";
338
328
  var BROKER_TIMEOUT_MS = 20 * ONE_SECOND_MS;
339
329
  var withoutTrailingSlashes = (url) => {
@@ -439,8 +429,7 @@ async function brokerRefresh(refreshToken, baseUrl = brokerBaseUrl()) {
439
429
  body: JSON.stringify({ refresh_token: refreshToken })
440
430
  }), refreshToken);
441
431
  }
442
- //#endregion
443
- //#region src/google/auth.ts
432
+ // src/google/auth.ts
444
433
  var GOOGLE_CALENDAR_SCOPE = "https://www.googleapis.com/auth/calendar.events";
445
434
  /** Minimal read scope for the calendar list + per-calendar colours.
446
435
  * `calendar.events` already covers reading/writing events on any calendar, but
@@ -652,8 +641,7 @@ async function authorizeGoogle(opts = {}) {
652
641
  server.close();
653
642
  }
654
643
  }
655
- //#endregion
656
- //#region src/google/authFlow.ts
644
+ // src/google/authFlow.ts
657
645
  var createGoogleAuthFlow = (authorize) => {
658
646
  let flowRunning = false;
659
647
  let lastError = null;
@@ -699,8 +687,7 @@ var createGoogleAuthFlow = (authorize) => {
699
687
  };
700
688
  };
701
689
  var googleAuthFlow = createGoogleAuthFlow(authorizeGoogle);
702
- //#endregion
703
- //#region src/google/apiClient.ts
690
+ // src/google/apiClient.ts
704
691
  var GOOGLE_API_TIMEOUT_MS = 30 * ONE_SECOND_MS;
705
692
  var ERROR_BODY_MAX_CHARS = 300;
706
693
  var HTTP_FORBIDDEN = 403;
@@ -747,8 +734,7 @@ var itemsOf = (value) => {
747
734
  const record = asRecord(value);
748
735
  return Array.isArray(record.items) ? record.items : [];
749
736
  };
750
- //#endregion
751
- //#region src/google/calendar.ts
737
+ // src/google/calendar.ts
752
738
  var CALENDAR_BASE_URL = "https://www.googleapis.com/calendar/v3";
753
739
  var CALENDAR_API_LABEL = "Google Calendar API";
754
740
  var DEFAULT_CALENDAR_ID = "primary";
@@ -1046,8 +1032,7 @@ async function getCalendarColors(accessToken) {
1046
1032
  calendar: toColorMap(record.calendar)
1047
1033
  };
1048
1034
  }
1049
- //#endregion
1050
- //#region src/google/calendarStateLock.ts
1035
+ // src/google/calendarStateLock.ts
1051
1036
  var LOCK_MODE = 384;
1052
1037
  /** How long a lock may sit untouched before another process may reclaim it.
1053
1038
  *
@@ -1199,8 +1184,7 @@ async function acquireBefore(lockPath, holder, deadline, clock) {
1199
1184
  }
1200
1185
  /** `<state file>.lock`, so each state file is serialised on its own. */
1201
1186
  var stateLockPath = (statePath) => `${statePath}.lock`;
1202
- //#endregion
1203
- //#region src/google/calendarSyncStore.ts
1187
+ // src/google/calendarSyncStore.ts
1204
1188
  var SYNC_STATE_MODE = 384;
1205
1189
  /** `<workspace>/data/calendar/.sync-state.json` */
1206
1190
  function calendarSyncStatePath(workspaceRoot) {
@@ -1322,8 +1306,7 @@ async function clearCalendarLastSyncedAt(calendarId, workspaceRoot) {
1322
1306
  lastSyncedAt: withoutKey(state.lastSyncedAt, dropped)
1323
1307
  }), workspaceRoot);
1324
1308
  }
1325
- //#endregion
1326
- //#region src/google/calendarSyncDue.ts
1309
+ // src/google/calendarSyncDue.ts
1327
1310
  /** Slack between a tick and the marker it writes. Without it a lone host reads
1328
1311
  * its OWN marker as "not due yet" — elapsed lands a hair under the interval
1329
1312
  * every time — and syncs every other hour. */
@@ -1346,8 +1329,7 @@ function isCalendarSyncDue(lastSyncedAt, windowMs, now = Date.now()) {
1346
1329
  if (elapsed < -windowMs) return true;
1347
1330
  return elapsed >= windowMs;
1348
1331
  }
1349
- //#endregion
1350
- //#region src/google/calendarBackfillState.ts
1332
+ // src/google/calendarBackfillState.ts
1351
1333
  var BACKFILL_STATE_MODE = 384;
1352
1334
  var BACKFILL_FILE = ".calendar-sync.json";
1353
1335
  /** `<dataDir>/.calendar-sync.json` */
@@ -1386,8 +1368,7 @@ async function markCalendarBackfilled(dataDir, calendarId, walkedAt) {
1386
1368
  });
1387
1369
  }
1388
1370
  }
1389
- //#endregion
1390
- //#region src/google/calendarPushState.ts
1371
+ // src/google/calendarPushState.ts
1391
1372
  var PUSH_STATE_MODE = 384;
1392
1373
  /** `<workspace>/data/calendar/.push-state.json` */
1393
1374
  function calendarPushStatePath(workspaceRoot) {
@@ -1442,8 +1423,7 @@ async function clearCalendarShadow(calendarId, workspaceRoot) {
1442
1423
  const dropped = canonicalCalendarId(calendarId);
1443
1424
  await updateState((events) => Object.fromEntries(Object.entries(events).filter(([key]) => key !== dropped)), workspaceRoot);
1444
1425
  }
1445
- //#endregion
1446
- //#region src/google/calendarLock.ts
1426
+ // src/google/calendarLock.ts
1447
1427
  /** Serialise `run` against whatever is already running for `key`.
1448
1428
  *
1449
1429
  * `locks` is passed in so the queuing rule is testable without module state;
@@ -1475,8 +1455,7 @@ var calendarLocks = /* @__PURE__ */ new Map();
1475
1455
  async function withCalendarLock(calendarId, run) {
1476
1456
  return await withKeyedLock(calendarLocks, canonicalCalendarId(calendarId), run);
1477
1457
  }
1478
- //#endregion
1479
- //#region src/google/pushDateTime.ts
1458
+ // src/google/pushDateTime.ts
1480
1459
  /** RFC3339 zone designator: `Z`, `+09:00`, `-0500`. */
1481
1460
  var ZONE_SUFFIX_RE$1 = /(?:Z|[+-]\d{2}:?\d{2})$/;
1482
1461
  var FRACTIONAL_SECONDS_RE$1 = /\.\d+$/;
@@ -1571,8 +1550,7 @@ function toGoogleEventTime(local, previous, calendarTimeZone) {
1571
1550
  timeZone: calendarTimeZone
1572
1551
  } : { dateTime: `${dateTime}${zone}` };
1573
1552
  }
1574
- //#endregion
1575
- //#region src/google/collectionDateTime.ts
1553
+ // src/google/collectionDateTime.ts
1576
1554
  /** All-day events carry no clock; midnight is where the day view places them. */
1577
1555
  var ALL_DAY_CLOCK = "00:00";
1578
1556
  var DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
@@ -1591,8 +1569,7 @@ function toCollectionDateTime(value) {
1591
1569
  if (!trimmed.includes("T")) return value;
1592
1570
  return trimmed.replace(ZONE_SUFFIX_RE, "").replace(FRACTIONAL_SECONDS_RE, "");
1593
1571
  }
1594
- //#endregion
1595
- //#region src/google/collectionProjection.ts
1572
+ // src/google/collectionProjection.ts
1596
1573
  var DATETIME_FIELD_TYPE = "datetime";
1597
1574
  /** Own-property lookup, mirroring what the record lint reads: a spec reachable
1598
1575
  * only through the prototype chain is not a DECLARED field, so it must not
@@ -1617,8 +1594,7 @@ function toCollectionRecord(event, map, primaryKey, fields) {
1617
1594
  [primaryKey]: event.id
1618
1595
  };
1619
1596
  }
1620
- //#endregion
1621
- //#region src/google/pushPlan.ts
1597
+ // src/google/pushPlan.ts
1622
1598
  /** The event fields Google lets a caller write — a SUBSET of what the pull can
1623
1599
  * read (`GOOGLE_CALENDAR_SOURCE_FIELDS`). A column mapped to one of the
1624
1600
  * pull-only fields is ignored here rather than rejected: the mapping was
@@ -1766,8 +1742,7 @@ function locallyDeletedIds(shadow, presentIds) {
1766
1742
  const present = new Set(presentIds);
1767
1743
  return Object.keys(shadow).filter((eventId) => !present.has(eventId));
1768
1744
  }
1769
- //#endregion
1770
- //#region src/google/collectionPush.ts
1745
+ // src/google/collectionPush.ts
1771
1746
  /** Access roles that may write events. `reader` / `freeBusyReader` cannot, and a
1772
1747
  * push under them fails per event with an opaque 403 — checked once up front so
1773
1748
  * the user is told the real reason. */
@@ -2233,8 +2208,7 @@ async function pushCalendarForCollection(slug, workspaceRoot, deps = liveDeps) {
2233
2208
  };
2234
2209
  }
2235
2210
  }
2236
- //#endregion
2237
- //#region src/google/collectionSync.ts
2211
+ // src/google/collectionSync.ts
2238
2212
  var GOOGLE_CALENDAR_SYNC_TASK_ID = "system:google-calendar-sync";
2239
2213
  var DEFAULT_SYNC_INTERVAL_MS = 36e5;
2240
2214
  function classifyWrite(eventId, kind) {
@@ -2967,8 +2941,7 @@ function googleCalendarSyncTaskDef(opts) {
2967
2941
  };
2968
2942
  return def;
2969
2943
  }
2970
- //#endregion
2971
- //#region src/google/tasks.ts
2944
+ // src/google/tasks.ts
2972
2945
  var TASKS_BASE_URL = "https://tasks.googleapis.com/tasks/v1";
2973
2946
  var TASKS_API_LABEL = "Google Tasks API";
2974
2947
  var DEFAULT_TASK_LIST_ID = "@default";
@@ -3068,8 +3041,7 @@ async function uncompleteTask(accessToken, input) {
3068
3041
  async function deleteTask(accessToken, input) {
3069
3042
  await googleRequest(TASKS_API_LABEL, accessToken, tasksUrl(input.taskListId, `/${encodeURIComponent(input.taskId)}`), { method: "DELETE" });
3070
3043
  }
3071
- //#endregion
3072
- //#region src/google/driveFile.ts
3044
+ // src/google/driveFile.ts
3073
3045
  var DRIVE_FILES_URL = "https://www.googleapis.com/drive/v3/files";
3074
3046
  var DRIVE_UPLOAD_URL = "https://www.googleapis.com/upload/drive/v3/files";
3075
3047
  var DRIVE_API_LABEL = "Google Drive API";
@@ -3161,7 +3133,6 @@ async function readDriveFile(accessToken, input) {
3161
3133
  async function deleteDriveFile(accessToken, input) {
3162
3134
  await googleRequest(DRIVE_API_LABEL, accessToken, `${DRIVE_FILES_URL}/${encodeURIComponent(input.fileId)}`, { method: "DELETE" });
3163
3135
  }
3164
- //#endregion
3165
3136
  exports.ALL_DAY_END_HINT = ALL_DAY_END_HINT;
3166
3137
  exports.CANCELLED_EVENT_STATUS = CANCELLED_EVENT_STATUS;
3167
3138
  exports.DEFAULT_LIST_MAX_RESULTS = DEFAULT_LIST_MAX_RESULTS;