@code-yeongyu/senpi 2026.5.21-2 → 2026.5.23-2

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 (258) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +1 -1
  3. package/dist/cli/file-processor.d.ts.map +1 -1
  4. package/dist/cli/file-processor.js +2 -3
  5. package/dist/cli/file-processor.js.map +1 -1
  6. package/dist/config.d.ts.map +1 -1
  7. package/dist/config.js +3 -10
  8. package/dist/config.js.map +1 -1
  9. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  10. package/dist/core/agent-session-runtime.js +2 -1
  11. package/dist/core/agent-session-runtime.js.map +1 -1
  12. package/dist/core/agent-session-services.d.ts.map +1 -1
  13. package/dist/core/agent-session-services.js +3 -2
  14. package/dist/core/agent-session-services.js.map +1 -1
  15. package/dist/core/agent-session.d.ts +2 -0
  16. package/dist/core/agent-session.d.ts.map +1 -1
  17. package/dist/core/agent-session.js +28 -4
  18. package/dist/core/agent-session.js.map +1 -1
  19. package/dist/core/auth-storage.d.ts.map +1 -1
  20. package/dist/core/auth-storage.js +2 -1
  21. package/dist/core/auth-storage.js.map +1 -1
  22. package/dist/core/export-html/index.d.ts.map +1 -1
  23. package/dist/core/export-html/index.js +8 -7
  24. package/dist/core/export-html/index.js.map +1 -1
  25. package/dist/core/export-html/template.js +6 -3
  26. package/dist/core/extensions/builtin/compaction/index.d.ts.map +1 -1
  27. package/dist/core/extensions/builtin/compaction/index.js +9 -0
  28. package/dist/core/extensions/builtin/compaction/index.js.map +1 -1
  29. package/dist/core/extensions/builtin/history-search/filter.d.ts +3 -0
  30. package/dist/core/extensions/builtin/history-search/filter.d.ts.map +1 -0
  31. package/dist/core/extensions/builtin/history-search/filter.js +22 -0
  32. package/dist/core/extensions/builtin/history-search/filter.js.map +1 -0
  33. package/dist/core/extensions/builtin/history-search/index.d.ts +7 -0
  34. package/dist/core/extensions/builtin/history-search/index.d.ts.map +1 -0
  35. package/dist/core/extensions/builtin/history-search/index.js +45 -0
  36. package/dist/core/extensions/builtin/history-search/index.js.map +1 -0
  37. package/dist/core/extensions/builtin/history-search/indexer.d.ts +3 -0
  38. package/dist/core/extensions/builtin/history-search/indexer.d.ts.map +1 -0
  39. package/dist/core/extensions/builtin/history-search/indexer.js +161 -0
  40. package/dist/core/extensions/builtin/history-search/indexer.js.map +1 -0
  41. package/dist/core/extensions/builtin/history-search/overlay.d.ts +30 -0
  42. package/dist/core/extensions/builtin/history-search/overlay.d.ts.map +1 -0
  43. package/dist/core/extensions/builtin/history-search/overlay.js +115 -0
  44. package/dist/core/extensions/builtin/history-search/overlay.js.map +1 -0
  45. package/dist/core/extensions/builtin/history-search/types.d.ts +8 -0
  46. package/dist/core/extensions/builtin/history-search/types.d.ts.map +1 -0
  47. package/dist/core/extensions/builtin/history-search/types.js +2 -0
  48. package/dist/core/extensions/builtin/history-search/types.js.map +1 -0
  49. package/dist/core/extensions/builtin/index.d.ts.map +1 -1
  50. package/dist/core/extensions/builtin/index.js +4 -0
  51. package/dist/core/extensions/builtin/index.js.map +1 -1
  52. package/dist/core/extensions/builtin/session-observer/index.d.ts +5 -0
  53. package/dist/core/extensions/builtin/session-observer/index.d.ts.map +1 -0
  54. package/dist/core/extensions/builtin/session-observer/index.js +36 -0
  55. package/dist/core/extensions/builtin/session-observer/index.js.map +1 -0
  56. package/dist/core/extensions/builtin/session-observer/loader.d.ts +3 -0
  57. package/dist/core/extensions/builtin/session-observer/loader.d.ts.map +1 -0
  58. package/dist/core/extensions/builtin/session-observer/loader.js +20 -0
  59. package/dist/core/extensions/builtin/session-observer/loader.js.map +1 -0
  60. package/dist/core/extensions/builtin/session-observer/overlay-format.d.ts +7 -0
  61. package/dist/core/extensions/builtin/session-observer/overlay-format.d.ts.map +1 -0
  62. package/dist/core/extensions/builtin/session-observer/overlay-format.js +30 -0
  63. package/dist/core/extensions/builtin/session-observer/overlay-format.js.map +1 -0
  64. package/dist/core/extensions/builtin/session-observer/overlay.d.ts +51 -0
  65. package/dist/core/extensions/builtin/session-observer/overlay.d.ts.map +1 -0
  66. package/dist/core/extensions/builtin/session-observer/overlay.js +239 -0
  67. package/dist/core/extensions/builtin/session-observer/overlay.js.map +1 -0
  68. package/dist/core/extensions/builtin/session-observer/scanner.d.ts +10 -0
  69. package/dist/core/extensions/builtin/session-observer/scanner.d.ts.map +1 -0
  70. package/dist/core/extensions/builtin/session-observer/scanner.js +140 -0
  71. package/dist/core/extensions/builtin/session-observer/scanner.js.map +1 -0
  72. package/dist/core/extensions/builtin/session-observer/text.d.ts +7 -0
  73. package/dist/core/extensions/builtin/session-observer/text.d.ts.map +1 -0
  74. package/dist/core/extensions/builtin/session-observer/text.js +37 -0
  75. package/dist/core/extensions/builtin/session-observer/text.js.map +1 -0
  76. package/dist/core/extensions/builtin/session-observer/transcript-entries.d.ts +7 -0
  77. package/dist/core/extensions/builtin/session-observer/transcript-entries.d.ts.map +1 -0
  78. package/dist/core/extensions/builtin/session-observer/transcript-entries.js +71 -0
  79. package/dist/core/extensions/builtin/session-observer/transcript-entries.js.map +1 -0
  80. package/dist/core/extensions/builtin/session-observer/transcript-format.d.ts +11 -0
  81. package/dist/core/extensions/builtin/session-observer/transcript-format.d.ts.map +1 -0
  82. package/dist/core/extensions/builtin/session-observer/transcript-format.js +65 -0
  83. package/dist/core/extensions/builtin/session-observer/transcript-format.js.map +1 -0
  84. package/dist/core/extensions/builtin/session-observer/transcript.d.ts +4 -0
  85. package/dist/core/extensions/builtin/session-observer/transcript.d.ts.map +1 -0
  86. package/dist/core/extensions/builtin/session-observer/transcript.js +81 -0
  87. package/dist/core/extensions/builtin/session-observer/transcript.js.map +1 -0
  88. package/dist/core/extensions/builtin/session-observer/types.d.ts +33 -0
  89. package/dist/core/extensions/builtin/session-observer/types.d.ts.map +1 -0
  90. package/dist/core/extensions/builtin/session-observer/types.js +2 -0
  91. package/dist/core/extensions/builtin/session-observer/types.js.map +1 -0
  92. package/dist/core/extensions/loader.d.ts.map +1 -1
  93. package/dist/core/extensions/loader.js +13 -30
  94. package/dist/core/extensions/loader.js.map +1 -1
  95. package/dist/core/extensions/runner.d.ts.map +1 -1
  96. package/dist/core/extensions/runner.js +1 -0
  97. package/dist/core/extensions/runner.js.map +1 -1
  98. package/dist/core/keybindings.d.ts +10 -0
  99. package/dist/core/keybindings.d.ts.map +1 -1
  100. package/dist/core/keybindings.js +3 -0
  101. package/dist/core/keybindings.js.map +1 -1
  102. package/dist/core/model-registry.d.ts.map +1 -1
  103. package/dist/core/model-registry.js +5 -1
  104. package/dist/core/model-registry.js.map +1 -1
  105. package/dist/core/package-manager.d.ts +1 -0
  106. package/dist/core/package-manager.d.ts.map +1 -1
  107. package/dist/core/package-manager.js +47 -32
  108. package/dist/core/package-manager.js.map +1 -1
  109. package/dist/core/prompt-templates.d.ts.map +1 -1
  110. package/dist/core/prompt-templates.js +6 -20
  111. package/dist/core/prompt-templates.js.map +1 -1
  112. package/dist/core/resource-loader.d.ts.map +1 -1
  113. package/dist/core/resource-loader.js +38 -31
  114. package/dist/core/resource-loader.js.map +1 -1
  115. package/dist/core/sdk.d.ts.map +1 -1
  116. package/dist/core/sdk.js +9 -4
  117. package/dist/core/sdk.js.map +1 -1
  118. package/dist/core/session-manager.d.ts.map +1 -1
  119. package/dist/core/session-manager.js +32 -24
  120. package/dist/core/session-manager.js.map +1 -1
  121. package/dist/core/settings-manager.d.ts.map +1 -1
  122. package/dist/core/settings-manager.js +6 -13
  123. package/dist/core/settings-manager.js.map +1 -1
  124. package/dist/core/skills.d.ts.map +1 -1
  125. package/dist/core/skills.js +8 -22
  126. package/dist/core/skills.js.map +1 -1
  127. package/dist/core/tools/bash.d.ts.map +1 -1
  128. package/dist/core/tools/bash.js +54 -53
  129. package/dist/core/tools/bash.js.map +1 -1
  130. package/dist/core/tools/edit-diff.d.ts +3 -1
  131. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  132. package/dist/core/tools/edit-diff.js +8 -1
  133. package/dist/core/tools/edit-diff.js.map +1 -1
  134. package/dist/core/tools/edit.d.ts +3 -1
  135. package/dist/core/tools/edit.d.ts.map +1 -1
  136. package/dist/core/tools/edit.js +44 -81
  137. package/dist/core/tools/edit.js.map +1 -1
  138. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
  139. package/dist/core/tools/file-mutation-queue.js +27 -12
  140. package/dist/core/tools/file-mutation-queue.js.map +1 -1
  141. package/dist/core/tools/find.d.ts.map +1 -1
  142. package/dist/core/tools/find.js +2 -3
  143. package/dist/core/tools/find.js.map +1 -1
  144. package/dist/core/tools/grep.d.ts.map +1 -1
  145. package/dist/core/tools/grep.js +3 -3
  146. package/dist/core/tools/grep.js.map +1 -1
  147. package/dist/core/tools/ls.d.ts.map +1 -1
  148. package/dist/core/tools/ls.js +5 -5
  149. package/dist/core/tools/ls.js.map +1 -1
  150. package/dist/core/tools/output-accumulator.d.ts +2 -0
  151. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  152. package/dist/core/tools/output-accumulator.js +9 -3
  153. package/dist/core/tools/output-accumulator.js.map +1 -1
  154. package/dist/core/tools/path-utils.d.ts +2 -0
  155. package/dist/core/tools/path-utils.d.ts.map +1 -1
  156. package/dist/core/tools/path-utils.js +39 -21
  157. package/dist/core/tools/path-utils.js.map +1 -1
  158. package/dist/core/tools/read.d.ts.map +1 -1
  159. package/dist/core/tools/read.js +9 -8
  160. package/dist/core/tools/read.js.map +1 -1
  161. package/dist/core/tools/truncate.d.ts.map +1 -1
  162. package/dist/core/tools/truncate.js +12 -2
  163. package/dist/core/tools/truncate.js.map +1 -1
  164. package/dist/core/tools/write.d.ts.map +1 -1
  165. package/dist/core/tools/write.js +20 -35
  166. package/dist/core/tools/write.js.map +1 -1
  167. package/dist/main.d.ts.map +1 -1
  168. package/dist/main.js +5 -6
  169. package/dist/main.js.map +1 -1
  170. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  171. package/dist/modes/interactive/components/config-selector.js +1 -1
  172. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  173. package/dist/modes/interactive/components/footer.d.ts +1 -0
  174. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  175. package/dist/modes/interactive/components/footer.js +87 -67
  176. package/dist/modes/interactive/components/footer.js.map +1 -1
  177. package/dist/modes/interactive/components/login-dialog.d.ts +9 -1
  178. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  179. package/dist/modes/interactive/components/login-dialog.js +29 -4
  180. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  181. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  182. package/dist/modes/interactive/interactive-mode.js +22 -4
  183. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  184. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  185. package/dist/modes/interactive/theme/theme.js +37 -28
  186. package/dist/modes/interactive/theme/theme.js.map +1 -1
  187. package/dist/utils/clipboard-native.d.ts +3 -1
  188. package/dist/utils/clipboard-native.d.ts.map +1 -1
  189. package/dist/utils/clipboard-native.js +14 -8
  190. package/dist/utils/clipboard-native.js.map +1 -1
  191. package/dist/utils/image-resize-core.d.ts +30 -0
  192. package/dist/utils/image-resize-core.d.ts.map +1 -0
  193. package/dist/utils/image-resize-core.js +124 -0
  194. package/dist/utils/image-resize-core.js.map +1 -0
  195. package/dist/utils/image-resize-worker.d.ts +2 -0
  196. package/dist/utils/image-resize-worker.d.ts.map +1 -0
  197. package/dist/utils/image-resize-worker.js +31 -0
  198. package/dist/utils/image-resize-worker.js.map +1 -0
  199. package/dist/utils/image-resize.d.ts +7 -27
  200. package/dist/utils/image-resize.d.ts.map +1 -1
  201. package/dist/utils/image-resize.js +75 -115
  202. package/dist/utils/image-resize.js.map +1 -1
  203. package/dist/utils/paths.d.ts +16 -1
  204. package/dist/utils/paths.d.ts.map +1 -1
  205. package/dist/utils/paths.js +41 -7
  206. package/dist/utils/paths.js.map +1 -1
  207. package/docs/custom-provider.md +44 -12
  208. package/docs/models.md +8 -2
  209. package/docs/packages.md +5 -4
  210. package/docs/sdk.md +2 -0
  211. package/docs/usage.md +2 -2
  212. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  213. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  214. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  215. package/examples/extensions/sandbox/package-lock.json +2 -2
  216. package/examples/extensions/sandbox/package.json +1 -1
  217. package/examples/extensions/with-deps/package-lock.json +2 -2
  218. package/examples/extensions/with-deps/package.json +1 -1
  219. package/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
  220. package/node_modules/@earendil-works/pi-ai/dist/cli.d.ts.map +1 -1
  221. package/node_modules/@earendil-works/pi-ai/dist/cli.js +14 -0
  222. package/node_modules/@earendil-works/pi-ai/dist/cli.js.map +1 -1
  223. package/node_modules/@earendil-works/pi-ai/dist/index.d.ts +1 -1
  224. package/node_modules/@earendil-works/pi-ai/dist/index.d.ts.map +1 -1
  225. package/node_modules/@earendil-works/pi-ai/dist/index.js.map +1 -1
  226. package/node_modules/@earendil-works/pi-ai/dist/models.generated.d.ts +145 -225
  227. package/node_modules/@earendil-works/pi-ai/dist/models.generated.d.ts.map +1 -1
  228. package/node_modules/@earendil-works/pi-ai/dist/models.generated.js +134 -225
  229. package/node_modules/@earendil-works/pi-ai/dist/models.generated.js.map +1 -1
  230. package/node_modules/@earendil-works/pi-ai/dist/providers/amazon-bedrock.d.ts.map +1 -1
  231. package/node_modules/@earendil-works/pi-ai/dist/providers/amazon-bedrock.js +2 -1
  232. package/node_modules/@earendil-works/pi-ai/dist/providers/amazon-bedrock.js.map +1 -1
  233. package/node_modules/@earendil-works/pi-ai/dist/providers/anthropic.d.ts +27 -8
  234. package/node_modules/@earendil-works/pi-ai/dist/providers/anthropic.d.ts.map +1 -1
  235. package/node_modules/@earendil-works/pi-ai/dist/providers/anthropic.js +35 -22
  236. package/node_modules/@earendil-works/pi-ai/dist/providers/anthropic.js.map +1 -1
  237. package/node_modules/@earendil-works/pi-ai/dist/types.d.ts +10 -0
  238. package/node_modules/@earendil-works/pi-ai/dist/types.d.ts.map +1 -1
  239. package/node_modules/@earendil-works/pi-ai/dist/types.js.map +1 -1
  240. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/device-code.d.ts +19 -0
  241. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/device-code.d.ts.map +1 -0
  242. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/device-code.js +55 -0
  243. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/device-code.js.map +1 -0
  244. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/github-copilot.d.ts +3 -3
  245. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/github-copilot.d.ts.map +1 -1
  246. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/github-copilot.js +45 -69
  247. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/github-copilot.js.map +1 -1
  248. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/index.d.ts +1 -0
  249. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/index.d.ts.map +1 -1
  250. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/index.js +1 -0
  251. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/index.js.map +1 -1
  252. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/types.d.ts +8 -1
  253. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/types.d.ts.map +1 -1
  254. package/node_modules/@earendil-works/pi-ai/dist/utils/oauth/types.js.map +1 -1
  255. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  256. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  257. package/npm-shrinkwrap.json +13 -13
  258. package/package.json +5 -5
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image-resize-core.js","sourceRoot":"","sources":["../../src/utils/image-resize-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAA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AC/C,MAAM;YACP,CAAC;YAED,MAAM,SAAS,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,YAAY,GAAG,IAAI,CAAC,CAAC,CAAC;YACxF,MAAM,UAAU,GAAG,aAAa,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,aAAa,GAAG,IAAI,CAAC,CAAC,CAAC;YAC3F,IAAI,SAAS,KAAK,YAAY,IAAI,UAAU,KAAK,aAAa,EAAE,CAAC;gBAChE,MAAM;YACP,CAAC;YAED,YAAY,GAAG,SAAS,CAAC;YACzB,aAAa,GAAG,UAAU,CAAC;QAC5B,CAAC;QAED,OAAO,IAAI,CAAC;IACb,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,IAAI,CAAC;IACb,CAAC;YAAS,CAAC;QACV,IAAI,KAAK,EAAE,CAAC;YACX,KAAK,CAAC,IAAI,EAAE,CAAC;QACd,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import { applyExifOrientation } from \"./exif-orientation.ts\";\nimport { loadPhoton } from \"./photon.ts\";\n\nexport interface ImageResizeOptions {\n\tmaxWidth?: number; // Default: 2000\n\tmaxHeight?: number; // Default: 2000\n\tmaxBytes?: number; // Default: 4.5MB of base64 payload (below Anthropic's 5MB limit)\n\tjpegQuality?: number; // Default: 80\n}\n\nexport interface ResizedImage {\n\tdata: string; // base64\n\tmimeType: string;\n\toriginalWidth: number;\n\toriginalHeight: number;\n\twidth: number;\n\theight: number;\n\twasResized: boolean;\n}\n\n// 4.5MB of base64 payload. Provides headroom below Anthropic's 5MB limit.\nconst DEFAULT_MAX_BYTES = 4.5 * 1024 * 1024;\n\nconst DEFAULT_OPTIONS: Required<ImageResizeOptions> = {\n\tmaxWidth: 2000,\n\tmaxHeight: 2000,\n\tmaxBytes: DEFAULT_MAX_BYTES,\n\tjpegQuality: 80,\n};\n\ninterface EncodedCandidate {\n\tdata: string;\n\tencodedSize: number;\n\tmimeType: string;\n}\n\nfunction encodeCandidate(buffer: Uint8Array, mimeType: string): EncodedCandidate {\n\tconst data = Buffer.from(buffer).toString(\"base64\");\n\treturn {\n\t\tdata,\n\t\tencodedSize: Buffer.byteLength(data, \"utf-8\"),\n\t\tmimeType,\n\t};\n}\n\n/**\n * Resize an image to fit within the specified max dimensions and encoded file size.\n * Returns null if the image cannot be resized below maxBytes.\n *\n * Uses Photon (Rust/WASM) for image processing. If Photon is not available,\n * returns null.\n *\n * Strategy for staying under maxBytes:\n * 1. First resize to maxWidth/maxHeight\n * 2. Try both PNG and JPEG formats, pick the smaller one\n * 3. If still too large, try JPEG with decreasing quality\n * 4. If still too large, progressively reduce dimensions until 1x1\n */\nexport async function resizeImageInProcess(\n\tinputBytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ImageResizeOptions,\n): Promise<ResizedImage | null> {\n\tconst opts = { ...DEFAULT_OPTIONS, ...options };\n\tconst inputBase64Size = Math.ceil(inputBytes.byteLength / 3) * 4;\n\n\tconst photon = await loadPhoton();\n\tif (!photon) {\n\t\treturn null;\n\t}\n\n\tlet image: ReturnType<typeof photon.PhotonImage.new_from_byteslice> | undefined;\n\ttry {\n\t\tconst rawImage = photon.PhotonImage.new_from_byteslice(inputBytes);\n\t\timage = applyExifOrientation(photon, rawImage, inputBytes);\n\t\tif (image !== rawImage) rawImage.free();\n\n\t\tconst originalWidth = image.get_width();\n\t\tconst originalHeight = image.get_height();\n\t\tconst format = mimeType.split(\"/\")[1] ?? \"png\";\n\n\t\t// Check if already within all limits (dimensions AND encoded size)\n\t\tif (originalWidth <= opts.maxWidth && originalHeight <= opts.maxHeight && inputBase64Size < opts.maxBytes) {\n\t\t\treturn {\n\t\t\t\tdata: Buffer.from(inputBytes).toString(\"base64\"),\n\t\t\t\tmimeType: mimeType || `image/${format}`,\n\t\t\t\toriginalWidth,\n\t\t\t\toriginalHeight,\n\t\t\t\twidth: originalWidth,\n\t\t\t\theight: originalHeight,\n\t\t\t\twasResized: false,\n\t\t\t};\n\t\t}\n\n\t\t// Calculate initial dimensions respecting max limits\n\t\tlet targetWidth = originalWidth;\n\t\tlet targetHeight = originalHeight;\n\n\t\tif (targetWidth > opts.maxWidth) {\n\t\t\ttargetHeight = Math.round((targetHeight * opts.maxWidth) / targetWidth);\n\t\t\ttargetWidth = opts.maxWidth;\n\t\t}\n\t\tif (targetHeight > opts.maxHeight) {\n\t\t\ttargetWidth = Math.round((targetWidth * opts.maxHeight) / targetHeight);\n\t\t\ttargetHeight = opts.maxHeight;\n\t\t}\n\n\t\tfunction tryEncodings(width: number, height: number, jpegQualities: number[]): EncodedCandidate[] {\n\t\t\tconst resized = photon!.resize(image!, width, height, photon!.SamplingFilter.Lanczos3);\n\n\t\t\ttry {\n\t\t\t\tconst candidates: EncodedCandidate[] = [encodeCandidate(resized.get_bytes(), \"image/png\")];\n\t\t\t\tfor (const quality of jpegQualities) {\n\t\t\t\t\tcandidates.push(encodeCandidate(resized.get_bytes_jpeg(quality), \"image/jpeg\"));\n\t\t\t\t}\n\t\t\t\treturn candidates;\n\t\t\t} finally {\n\t\t\t\tresized.free();\n\t\t\t}\n\t\t}\n\n\t\tconst qualitySteps = Array.from(new Set([opts.jpegQuality, 85, 70, 55, 40]));\n\t\tlet currentWidth = targetWidth;\n\t\tlet currentHeight = targetHeight;\n\n\t\twhile (true) {\n\t\t\tconst candidates = tryEncodings(currentWidth, currentHeight, qualitySteps);\n\t\t\tfor (const candidate of candidates) {\n\t\t\t\tif (candidate.encodedSize < opts.maxBytes) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdata: candidate.data,\n\t\t\t\t\t\tmimeType: candidate.mimeType,\n\t\t\t\t\t\toriginalWidth,\n\t\t\t\t\t\toriginalHeight,\n\t\t\t\t\t\twidth: currentWidth,\n\t\t\t\t\t\theight: currentHeight,\n\t\t\t\t\t\twasResized: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (currentWidth === 1 && currentHeight === 1) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst nextWidth = currentWidth === 1 ? 1 : Math.max(1, Math.floor(currentWidth * 0.75));\n\t\t\tconst nextHeight = currentHeight === 1 ? 1 : Math.max(1, Math.floor(currentHeight * 0.75));\n\t\t\tif (nextWidth === currentWidth && nextHeight === currentHeight) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcurrentWidth = nextWidth;\n\t\t\tcurrentHeight = nextHeight;\n\t\t}\n\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t} finally {\n\t\tif (image) {\n\t\t\timage.free();\n\t\t}\n\t}\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=image-resize-worker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image-resize-worker.d.ts","sourceRoot":"","sources":["../../src/utils/image-resize-worker.ts"],"names":[],"mappings":"","sourcesContent":["import { parentPort } from \"node:worker_threads\";\nimport { type ImageResizeOptions, type ResizedImage, resizeImageInProcess } from \"./image-resize-core.ts\";\n\ninterface ResizeImageWorkerRequest {\n\tinputBytes: Uint8Array;\n\tmimeType: string;\n\toptions?: ImageResizeOptions;\n}\n\ninterface ResizeImageWorkerResponse {\n\tresult?: ResizedImage | null;\n\terror?: string;\n}\n\nfunction isResizeImageWorkerRequest(value: unknown): value is ResizeImageWorkerRequest {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst record = value as Record<string, unknown>;\n\treturn record.inputBytes instanceof Uint8Array && typeof record.mimeType === \"string\";\n}\n\nconst port = parentPort;\nif (!port) {\n\tthrow new Error(\"image resize worker requires parentPort\");\n}\n\nport.once(\"message\", (message: unknown) => {\n\tvoid (async () => {\n\t\ttry {\n\t\t\tif (!isResizeImageWorkerRequest(message)) {\n\t\t\t\tthrow new Error(\"Invalid image resize worker request\");\n\t\t\t}\n\t\t\tconst result = await resizeImageInProcess(message.inputBytes, message.mimeType, message.options);\n\t\t\tconst response: ResizeImageWorkerResponse = { result };\n\t\t\tport.postMessage(response);\n\t\t} catch (error) {\n\t\t\tconst response: ResizeImageWorkerResponse = {\n\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t};\n\t\t\tport.postMessage(response);\n\t\t}\n\t})();\n});\n"]}
@@ -0,0 +1,31 @@
1
+ import { parentPort } from "node:worker_threads";
2
+ import { resizeImageInProcess } from "./image-resize-core.js";
3
+ function isResizeImageWorkerRequest(value) {
4
+ if (!value || typeof value !== "object")
5
+ return false;
6
+ const record = value;
7
+ return record.inputBytes instanceof Uint8Array && typeof record.mimeType === "string";
8
+ }
9
+ const port = parentPort;
10
+ if (!port) {
11
+ throw new Error("image resize worker requires parentPort");
12
+ }
13
+ port.once("message", (message) => {
14
+ void (async () => {
15
+ try {
16
+ if (!isResizeImageWorkerRequest(message)) {
17
+ throw new Error("Invalid image resize worker request");
18
+ }
19
+ const result = await resizeImageInProcess(message.inputBytes, message.mimeType, message.options);
20
+ const response = { result };
21
+ port.postMessage(response);
22
+ }
23
+ catch (error) {
24
+ const response = {
25
+ error: error instanceof Error ? error.message : String(error),
26
+ };
27
+ port.postMessage(response);
28
+ }
29
+ })();
30
+ });
31
+ //# sourceMappingURL=image-resize-worker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image-resize-worker.js","sourceRoot":"","sources":["../../src/utils/image-resize-worker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAA8C,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAa1G,SAAS,0BAA0B,CAAC,KAAc,EAAqC;IACtF,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACtD,MAAM,MAAM,GAAG,KAAgC,CAAC;IAChD,OAAO,MAAM,CAAC,UAAU,YAAY,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ,CAAC;AAAA,CACtF;AAED,MAAM,IAAI,GAAG,UAAU,CAAC;AACxB,IAAI,CAAC,IAAI,EAAE,CAAC;IACX,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;AAC5D,CAAC;AAED,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC,OAAgB,EAAE,EAAE,CAAC;IAC1C,KAAK,CAAC,KAAK,IAAI,EAAE,CAAC;QACjB,IAAI,CAAC;YACJ,IAAI,CAAC,0BAA0B,CAAC,OAAO,CAAC,EAAE,CAAC;gBAC1C,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;YACxD,CAAC;YACD,MAAM,MAAM,GAAG,MAAM,oBAAoB,CAAC,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;YACjG,MAAM,QAAQ,GAA8B,EAAE,MAAM,EAAE,CAAC;YACvD,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QAC5B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,MAAM,QAAQ,GAA8B;gBAC3C,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;aAC7D,CAAC;YACF,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QAC5B,CAAC;IAAA,CACD,CAAC,EAAE,CAAC;AAAA,CACL,CAAC,CAAC","sourcesContent":["import { parentPort } from \"node:worker_threads\";\nimport { type ImageResizeOptions, type ResizedImage, resizeImageInProcess } from \"./image-resize-core.ts\";\n\ninterface ResizeImageWorkerRequest {\n\tinputBytes: Uint8Array;\n\tmimeType: string;\n\toptions?: ImageResizeOptions;\n}\n\ninterface ResizeImageWorkerResponse {\n\tresult?: ResizedImage | null;\n\terror?: string;\n}\n\nfunction isResizeImageWorkerRequest(value: unknown): value is ResizeImageWorkerRequest {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst record = value as Record<string, unknown>;\n\treturn record.inputBytes instanceof Uint8Array && typeof record.mimeType === \"string\";\n}\n\nconst port = parentPort;\nif (!port) {\n\tthrow new Error(\"image resize worker requires parentPort\");\n}\n\nport.once(\"message\", (message: unknown) => {\n\tvoid (async () => {\n\t\ttry {\n\t\t\tif (!isResizeImageWorkerRequest(message)) {\n\t\t\t\tthrow new Error(\"Invalid image resize worker request\");\n\t\t\t}\n\t\t\tconst result = await resizeImageInProcess(message.inputBytes, message.mimeType, message.options);\n\t\t\tconst response: ResizeImageWorkerResponse = { result };\n\t\t\tport.postMessage(response);\n\t\t} catch (error) {\n\t\t\tconst response: ResizeImageWorkerResponse = {\n\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t};\n\t\t\tport.postMessage(response);\n\t\t}\n\t})();\n});\n"]}
@@ -1,33 +1,13 @@
1
- import type { ImageContent } from "@earendil-works/pi-ai";
2
- export interface ImageResizeOptions {
3
- maxWidth?: number;
4
- maxHeight?: number;
5
- maxBytes?: number;
6
- jpegQuality?: number;
7
- }
8
- export interface ResizedImage {
9
- data: string;
10
- mimeType: string;
11
- originalWidth: number;
12
- originalHeight: number;
13
- width: number;
14
- height: number;
15
- wasResized: boolean;
16
- }
1
+ import { type ImageResizeOptions, type ResizedImage } from "./image-resize-core.ts";
2
+ export type { ImageResizeOptions, ResizedImage } from "./image-resize-core.ts";
17
3
  /**
18
4
  * Resize an image to fit within the specified max dimensions and encoded file size.
19
- * Returns null if the image cannot be resized below maxBytes.
20
- *
21
- * Uses Photon (Rust/WASM) for image processing. If Photon is not available,
22
- * returns null.
23
- *
24
- * Strategy for staying under maxBytes:
25
- * 1. First resize to maxWidth/maxHeight
26
- * 2. Try both PNG and JPEG formats, pick the smaller one
27
- * 3. If still too large, try JPEG with decreasing quality
28
- * 4. If still too large, progressively reduce dimensions until 1x1
5
+ * Runs Photon in a worker thread so WASM decoding, resizing, and encoding do not
6
+ * block the TUI event loop. If the worker cannot be loaded (for example in some
7
+ * Bun compiled executable layouts), fall back to in-process resizing so image
8
+ * reads still work.
29
9
  */
30
- export declare function resizeImage(img: ImageContent, options?: ImageResizeOptions): Promise<ResizedImage | null>;
10
+ export declare function resizeImage(inputBytes: Uint8Array, mimeType: string, options?: ImageResizeOptions): Promise<ResizedImage | null>;
31
11
  /**
32
12
  * Format a dimension note for resized images.
33
13
  * This helps the model understand the coordinate mapping.
@@ -1 +1 @@
1
- {"version":3,"file":"image-resize.d.ts","sourceRoot":"","sources":["../../src/utils/image-resize.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAI1D,MAAM,WAAW,kBAAkB;IAClC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,YAAY;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;IACtB,cAAc,EAAE,MAAM,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,OAAO,CAAC;CACpB;AA2BD;;;;;;;;;;;;GAYG;AACH,wBAAsB,WAAW,CAAC,GAAG,EAAE,YAAY,EAAE,OAAO,CAAC,EAAE,kBAAkB,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAuG/G;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,CAO5E","sourcesContent":["import type { ImageContent } from \"@earendil-works/pi-ai\";\nimport { applyExifOrientation } from \"./exif-orientation.ts\";\nimport { loadPhoton } from \"./photon.ts\";\n\nexport interface ImageResizeOptions {\n\tmaxWidth?: number; // Default: 2000\n\tmaxHeight?: number; // Default: 2000\n\tmaxBytes?: number; // Default: 4.5MB of base64 payload (below Anthropic's 5MB limit)\n\tjpegQuality?: number; // Default: 80\n}\n\nexport interface ResizedImage {\n\tdata: string; // base64\n\tmimeType: string;\n\toriginalWidth: number;\n\toriginalHeight: number;\n\twidth: number;\n\theight: number;\n\twasResized: boolean;\n}\n\n// 4.5MB of base64 payload. Provides headroom below Anthropic's 5MB limit.\nconst DEFAULT_MAX_BYTES = 4.5 * 1024 * 1024;\n\nconst DEFAULT_OPTIONS: Required<ImageResizeOptions> = {\n\tmaxWidth: 2000,\n\tmaxHeight: 2000,\n\tmaxBytes: DEFAULT_MAX_BYTES,\n\tjpegQuality: 80,\n};\n\ninterface EncodedCandidate {\n\tdata: string;\n\tencodedSize: number;\n\tmimeType: string;\n}\n\nfunction encodeCandidate(buffer: Uint8Array, mimeType: string): EncodedCandidate {\n\tconst data = Buffer.from(buffer).toString(\"base64\");\n\treturn {\n\t\tdata,\n\t\tencodedSize: Buffer.byteLength(data, \"utf-8\"),\n\t\tmimeType,\n\t};\n}\n\n/**\n * Resize an image to fit within the specified max dimensions and encoded file size.\n * Returns null if the image cannot be resized below maxBytes.\n *\n * Uses Photon (Rust/WASM) for image processing. If Photon is not available,\n * returns null.\n *\n * Strategy for staying under maxBytes:\n * 1. First resize to maxWidth/maxHeight\n * 2. Try both PNG and JPEG formats, pick the smaller one\n * 3. If still too large, try JPEG with decreasing quality\n * 4. If still too large, progressively reduce dimensions until 1x1\n */\nexport async function resizeImage(img: ImageContent, options?: ImageResizeOptions): Promise<ResizedImage | null> {\n\tconst opts = { ...DEFAULT_OPTIONS, ...options };\n\tconst inputBuffer = Buffer.from(img.data, \"base64\");\n\tconst inputBase64Size = Buffer.byteLength(img.data, \"utf-8\");\n\n\tconst photon = await loadPhoton();\n\tif (!photon) {\n\t\treturn null;\n\t}\n\n\tlet image: ReturnType<typeof photon.PhotonImage.new_from_byteslice> | undefined;\n\ttry {\n\t\tconst inputBytes = new Uint8Array(inputBuffer);\n\t\tconst rawImage = photon.PhotonImage.new_from_byteslice(inputBytes);\n\t\timage = applyExifOrientation(photon, rawImage, inputBytes);\n\t\tif (image !== rawImage) rawImage.free();\n\n\t\tconst originalWidth = image.get_width();\n\t\tconst originalHeight = image.get_height();\n\t\tconst format = img.mimeType?.split(\"/\")[1] ?? \"png\";\n\n\t\t// Check if already within all limits (dimensions AND encoded size)\n\t\tif (originalWidth <= opts.maxWidth && originalHeight <= opts.maxHeight && inputBase64Size < opts.maxBytes) {\n\t\t\treturn {\n\t\t\t\tdata: img.data,\n\t\t\t\tmimeType: img.mimeType ?? `image/${format}`,\n\t\t\t\toriginalWidth,\n\t\t\t\toriginalHeight,\n\t\t\t\twidth: originalWidth,\n\t\t\t\theight: originalHeight,\n\t\t\t\twasResized: false,\n\t\t\t};\n\t\t}\n\n\t\t// Calculate initial dimensions respecting max limits\n\t\tlet targetWidth = originalWidth;\n\t\tlet targetHeight = originalHeight;\n\n\t\tif (targetWidth > opts.maxWidth) {\n\t\t\ttargetHeight = Math.round((targetHeight * opts.maxWidth) / targetWidth);\n\t\t\ttargetWidth = opts.maxWidth;\n\t\t}\n\t\tif (targetHeight > opts.maxHeight) {\n\t\t\ttargetWidth = Math.round((targetWidth * opts.maxHeight) / targetHeight);\n\t\t\ttargetHeight = opts.maxHeight;\n\t\t}\n\n\t\tfunction tryEncodings(width: number, height: number, jpegQualities: number[]): EncodedCandidate[] {\n\t\t\tconst resized = photon!.resize(image!, width, height, photon!.SamplingFilter.Lanczos3);\n\n\t\t\ttry {\n\t\t\t\tconst candidates: EncodedCandidate[] = [encodeCandidate(resized.get_bytes(), \"image/png\")];\n\t\t\t\tfor (const quality of jpegQualities) {\n\t\t\t\t\tcandidates.push(encodeCandidate(resized.get_bytes_jpeg(quality), \"image/jpeg\"));\n\t\t\t\t}\n\t\t\t\treturn candidates;\n\t\t\t} finally {\n\t\t\t\tresized.free();\n\t\t\t}\n\t\t}\n\n\t\tconst qualitySteps = Array.from(new Set([opts.jpegQuality, 85, 70, 55, 40]));\n\t\tlet currentWidth = targetWidth;\n\t\tlet currentHeight = targetHeight;\n\n\t\twhile (true) {\n\t\t\tconst candidates = tryEncodings(currentWidth, currentHeight, qualitySteps);\n\t\t\tfor (const candidate of candidates) {\n\t\t\t\tif (candidate.encodedSize < opts.maxBytes) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdata: candidate.data,\n\t\t\t\t\t\tmimeType: candidate.mimeType,\n\t\t\t\t\t\toriginalWidth,\n\t\t\t\t\t\toriginalHeight,\n\t\t\t\t\t\twidth: currentWidth,\n\t\t\t\t\t\theight: currentHeight,\n\t\t\t\t\t\twasResized: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (currentWidth === 1 && currentHeight === 1) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst nextWidth = currentWidth === 1 ? 1 : Math.max(1, Math.floor(currentWidth * 0.75));\n\t\t\tconst nextHeight = currentHeight === 1 ? 1 : Math.max(1, Math.floor(currentHeight * 0.75));\n\t\t\tif (nextWidth === currentWidth && nextHeight === currentHeight) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcurrentWidth = nextWidth;\n\t\t\tcurrentHeight = nextHeight;\n\t\t}\n\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t} finally {\n\t\tif (image) {\n\t\t\timage.free();\n\t\t}\n\t}\n}\n\n/**\n * Format a dimension note for resized images.\n * This helps the model understand the coordinate mapping.\n */\nexport function formatDimensionNote(result: ResizedImage): string | undefined {\n\tif (!result.wasResized) {\n\t\treturn undefined;\n\t}\n\n\tconst scale = result.originalWidth / result.width;\n\treturn `[Image: original ${result.originalWidth}x${result.originalHeight}, displayed at ${result.width}x${result.height}. Multiply coordinates by ${scale.toFixed(2)} to map to original image.]`;\n}\n"]}
1
+ {"version":3,"file":"image-resize.d.ts","sourceRoot":"","sources":["../../src/utils/image-resize.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,kBAAkB,EAAE,KAAK,YAAY,EAAwB,MAAM,wBAAwB,CAAC;AAE1G,YAAY,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AA0E/E;;;;;;GAMG;AACH,wBAAsB,WAAW,CAChC,UAAU,EAAE,UAAU,EACtB,QAAQ,EAAE,MAAM,EAChB,OAAO,CAAC,EAAE,kBAAkB,GAC1B,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAqB9B;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,GAAG,SAAS,CAO5E","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { type ImageResizeOptions, type ResizedImage, resizeImageInProcess } from \"./image-resize-core.ts\";\n\nexport type { ImageResizeOptions, ResizedImage } from \"./image-resize-core.ts\";\n\ninterface ResizeImageWorkerResponse {\n\tresult?: ResizedImage | null;\n\terror?: string;\n}\n\nfunction toTransferableBytes(input: Uint8Array): Uint8Array<ArrayBuffer> {\n\t// Transfer detaches the buffer, so transfer a worker-owned copy and leave the\n\t// caller's bytes intact.\n\treturn new Uint8Array(input);\n}\n\nfunction isResizeImageWorkerResponse(value: unknown): value is ResizeImageWorkerResponse {\n\treturn value !== null && typeof value === \"object\";\n}\n\nfunction createResizeWorker(workerSpecifier: string | URL): Worker {\n\treturn new Worker(workerSpecifier);\n}\n\nasync function resizeImageInWorker(\n\tworkerSpecifier: string | URL,\n\tinputBytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ImageResizeOptions,\n): Promise<ResizedImage | null> {\n\tconst worker = createResizeWorker(workerSpecifier);\n\ttry {\n\t\tconst inputBytesForWorker = toTransferableBytes(inputBytes);\n\t\treturn await new Promise<ResizedImage | null>((resolve, reject) => {\n\t\t\tlet settled = false;\n\t\t\tconst settle = (result: ResizedImage | null): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tresolve(result);\n\t\t\t};\n\t\t\tconst fail = (error: Error): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\treject(error);\n\t\t\t};\n\n\t\t\tworker.once(\"message\", (message: unknown) => {\n\t\t\t\tif (!isResizeImageWorkerResponse(message)) {\n\t\t\t\t\tfail(new Error(\"Invalid image resize worker response\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (message.error) {\n\t\t\t\t\tfail(new Error(message.error));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettle(message.result ?? null);\n\t\t\t});\n\t\t\tworker.once(\"error\", fail);\n\t\t\tworker.once(\"exit\", (code) => {\n\t\t\t\tif (!settled) {\n\t\t\t\t\tfail(new Error(`Image resize worker exited with code ${code}`));\n\t\t\t\t}\n\t\t\t});\n\t\t\tworker.postMessage(\n\t\t\t\t{\n\t\t\t\t\tinputBytes: inputBytesForWorker,\n\t\t\t\t\tmimeType,\n\t\t\t\t\toptions,\n\t\t\t\t},\n\t\t\t\t[inputBytesForWorker.buffer],\n\t\t\t);\n\t\t});\n\t} finally {\n\t\tvoid worker.terminate().catch(() => undefined);\n\t}\n}\n\n/**\n * Resize an image to fit within the specified max dimensions and encoded file size.\n * Runs Photon in a worker thread so WASM decoding, resizing, and encoding do not\n * block the TUI event loop. If the worker cannot be loaded (for example in some\n * Bun compiled executable layouts), fall back to in-process resizing so image\n * reads still work.\n */\nexport async function resizeImage(\n\tinputBytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ImageResizeOptions,\n): Promise<ResizedImage | null> {\n\tconst isTypeScriptRuntime = import.meta.url.endsWith(\".ts\");\n\tconst workerUrl = new URL(\n\t\tisTypeScriptRuntime ? \"./image-resize-worker.ts\" : \"./image-resize-worker.js\",\n\t\timport.meta.url,\n\t);\n\n\t// Bun compiled executables resolve worker entrypoints by string path, not via\n\t// new URL(..., import.meta.url). Try the string path first under Bun so the\n\t// release binary uses the embedded worker instead of falling back in-process.\n\tif (typeof process.versions.bun === \"string\") {\n\t\ttry {\n\t\t\treturn await resizeImageInWorker(\"./src/utils/image-resize-worker.ts\", inputBytes, mimeType, options);\n\t\t} catch {}\n\t}\n\n\ttry {\n\t\treturn await resizeImageInWorker(workerUrl, inputBytes, mimeType, options);\n\t} catch {\n\t\treturn resizeImageInProcess(inputBytes, mimeType, options);\n\t}\n}\n\n/**\n * Format a dimension note for resized images.\n * This helps the model understand the coordinate mapping.\n */\nexport function formatDimensionNote(result: ResizedImage): string | undefined {\n\tif (!result.wasResized) {\n\t\treturn undefined;\n\t}\n\n\tconst scale = result.originalWidth / result.width;\n\treturn `[Image: original ${result.originalWidth}x${result.originalHeight}, displayed at ${result.width}x${result.height}. Multiply coordinates by ${scale.toFixed(2)} to map to original image.]`;\n}\n"]}
@@ -1,126 +1,86 @@
1
- import { applyExifOrientation } from "./exif-orientation.js";
2
- import { loadPhoton } from "./photon.js";
3
- // 4.5MB of base64 payload. Provides headroom below Anthropic's 5MB limit.
4
- const DEFAULT_MAX_BYTES = 4.5 * 1024 * 1024;
5
- const DEFAULT_OPTIONS = {
6
- maxWidth: 2000,
7
- maxHeight: 2000,
8
- maxBytes: DEFAULT_MAX_BYTES,
9
- jpegQuality: 80,
10
- };
11
- function encodeCandidate(buffer, mimeType) {
12
- const data = Buffer.from(buffer).toString("base64");
13
- return {
14
- data,
15
- encodedSize: Buffer.byteLength(data, "utf-8"),
16
- mimeType,
17
- };
1
+ import { Worker } from "node:worker_threads";
2
+ import { resizeImageInProcess } from "./image-resize-core.js";
3
+ function toTransferableBytes(input) {
4
+ // Transfer detaches the buffer, so transfer a worker-owned copy and leave the
5
+ // caller's bytes intact.
6
+ return new Uint8Array(input);
18
7
  }
19
- /**
20
- * Resize an image to fit within the specified max dimensions and encoded file size.
21
- * Returns null if the image cannot be resized below maxBytes.
22
- *
23
- * Uses Photon (Rust/WASM) for image processing. If Photon is not available,
24
- * returns null.
25
- *
26
- * Strategy for staying under maxBytes:
27
- * 1. First resize to maxWidth/maxHeight
28
- * 2. Try both PNG and JPEG formats, pick the smaller one
29
- * 3. If still too large, try JPEG with decreasing quality
30
- * 4. If still too large, progressively reduce dimensions until 1x1
31
- */
32
- export async function resizeImage(img, options) {
33
- const opts = { ...DEFAULT_OPTIONS, ...options };
34
- const inputBuffer = Buffer.from(img.data, "base64");
35
- const inputBase64Size = Buffer.byteLength(img.data, "utf-8");
36
- const photon = await loadPhoton();
37
- if (!photon) {
38
- return null;
39
- }
40
- let image;
8
+ function isResizeImageWorkerResponse(value) {
9
+ return value !== null && typeof value === "object";
10
+ }
11
+ function createResizeWorker(workerSpecifier) {
12
+ return new Worker(workerSpecifier);
13
+ }
14
+ async function resizeImageInWorker(workerSpecifier, inputBytes, mimeType, options) {
15
+ const worker = createResizeWorker(workerSpecifier);
41
16
  try {
42
- const inputBytes = new Uint8Array(inputBuffer);
43
- const rawImage = photon.PhotonImage.new_from_byteslice(inputBytes);
44
- image = applyExifOrientation(photon, rawImage, inputBytes);
45
- if (image !== rawImage)
46
- rawImage.free();
47
- const originalWidth = image.get_width();
48
- const originalHeight = image.get_height();
49
- const format = img.mimeType?.split("/")[1] ?? "png";
50
- // Check if already within all limits (dimensions AND encoded size)
51
- if (originalWidth <= opts.maxWidth && originalHeight <= opts.maxHeight && inputBase64Size < opts.maxBytes) {
52
- return {
53
- data: img.data,
54
- mimeType: img.mimeType ?? `image/${format}`,
55
- originalWidth,
56
- originalHeight,
57
- width: originalWidth,
58
- height: originalHeight,
59
- wasResized: false,
17
+ const inputBytesForWorker = toTransferableBytes(inputBytes);
18
+ return await new Promise((resolve, reject) => {
19
+ let settled = false;
20
+ const settle = (result) => {
21
+ if (settled)
22
+ return;
23
+ settled = true;
24
+ resolve(result);
60
25
  };
61
- }
62
- // Calculate initial dimensions respecting max limits
63
- let targetWidth = originalWidth;
64
- let targetHeight = originalHeight;
65
- if (targetWidth > opts.maxWidth) {
66
- targetHeight = Math.round((targetHeight * opts.maxWidth) / targetWidth);
67
- targetWidth = opts.maxWidth;
68
- }
69
- if (targetHeight > opts.maxHeight) {
70
- targetWidth = Math.round((targetWidth * opts.maxHeight) / targetHeight);
71
- targetHeight = opts.maxHeight;
72
- }
73
- function tryEncodings(width, height, jpegQualities) {
74
- const resized = photon.resize(image, width, height, photon.SamplingFilter.Lanczos3);
75
- try {
76
- const candidates = [encodeCandidate(resized.get_bytes(), "image/png")];
77
- for (const quality of jpegQualities) {
78
- candidates.push(encodeCandidate(resized.get_bytes_jpeg(quality), "image/jpeg"));
26
+ const fail = (error) => {
27
+ if (settled)
28
+ return;
29
+ settled = true;
30
+ reject(error);
31
+ };
32
+ worker.once("message", (message) => {
33
+ if (!isResizeImageWorkerResponse(message)) {
34
+ fail(new Error("Invalid image resize worker response"));
35
+ return;
79
36
  }
80
- return candidates;
81
- }
82
- finally {
83
- resized.free();
84
- }
85
- }
86
- const qualitySteps = Array.from(new Set([opts.jpegQuality, 85, 70, 55, 40]));
87
- let currentWidth = targetWidth;
88
- let currentHeight = targetHeight;
89
- while (true) {
90
- const candidates = tryEncodings(currentWidth, currentHeight, qualitySteps);
91
- for (const candidate of candidates) {
92
- if (candidate.encodedSize < opts.maxBytes) {
93
- return {
94
- data: candidate.data,
95
- mimeType: candidate.mimeType,
96
- originalWidth,
97
- originalHeight,
98
- width: currentWidth,
99
- height: currentHeight,
100
- wasResized: true,
101
- };
37
+ if (message.error) {
38
+ fail(new Error(message.error));
39
+ return;
102
40
  }
103
- }
104
- if (currentWidth === 1 && currentHeight === 1) {
105
- break;
106
- }
107
- const nextWidth = currentWidth === 1 ? 1 : Math.max(1, Math.floor(currentWidth * 0.75));
108
- const nextHeight = currentHeight === 1 ? 1 : Math.max(1, Math.floor(currentHeight * 0.75));
109
- if (nextWidth === currentWidth && nextHeight === currentHeight) {
110
- break;
111
- }
112
- currentWidth = nextWidth;
113
- currentHeight = nextHeight;
114
- }
115
- return null;
116
- }
117
- catch {
118
- return null;
41
+ settle(message.result ?? null);
42
+ });
43
+ worker.once("error", fail);
44
+ worker.once("exit", (code) => {
45
+ if (!settled) {
46
+ fail(new Error(`Image resize worker exited with code ${code}`));
47
+ }
48
+ });
49
+ worker.postMessage({
50
+ inputBytes: inputBytesForWorker,
51
+ mimeType,
52
+ options,
53
+ }, [inputBytesForWorker.buffer]);
54
+ });
119
55
  }
120
56
  finally {
121
- if (image) {
122
- image.free();
57
+ void worker.terminate().catch(() => undefined);
58
+ }
59
+ }
60
+ /**
61
+ * Resize an image to fit within the specified max dimensions and encoded file size.
62
+ * Runs Photon in a worker thread so WASM decoding, resizing, and encoding do not
63
+ * block the TUI event loop. If the worker cannot be loaded (for example in some
64
+ * Bun compiled executable layouts), fall back to in-process resizing so image
65
+ * reads still work.
66
+ */
67
+ export async function resizeImage(inputBytes, mimeType, options) {
68
+ const isTypeScriptRuntime = import.meta.url.endsWith(".ts");
69
+ const workerUrl = new URL(isTypeScriptRuntime ? "./image-resize-worker.ts" : "./image-resize-worker.js", import.meta.url);
70
+ // Bun compiled executables resolve worker entrypoints by string path, not via
71
+ // new URL(..., import.meta.url). Try the string path first under Bun so the
72
+ // release binary uses the embedded worker instead of falling back in-process.
73
+ if (typeof process.versions.bun === "string") {
74
+ try {
75
+ return await resizeImageInWorker("./src/utils/image-resize-worker.ts", inputBytes, mimeType, options);
123
76
  }
77
+ catch { }
78
+ }
79
+ try {
80
+ return await resizeImageInWorker(workerUrl, inputBytes, mimeType, options);
81
+ }
82
+ catch {
83
+ return resizeImageInProcess(inputBytes, mimeType, options);
124
84
  }
125
85
  }
126
86
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"image-resize.js","sourceRoot":"","sources":["../../src/utils/image-resize.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAmBzC,0EAA0E;AAC1E,MAAM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"./exif-orientation.ts\";\nimport { loadPhoton } from \"./photon.ts\";\n\nexport interface ImageResizeOptions {\n\tmaxWidth?: number; // Default: 2000\n\tmaxHeight?: number; // Default: 2000\n\tmaxBytes?: number; // Default: 4.5MB of base64 payload (below Anthropic's 5MB limit)\n\tjpegQuality?: number; // Default: 80\n}\n\nexport interface ResizedImage {\n\tdata: string; // base64\n\tmimeType: string;\n\toriginalWidth: number;\n\toriginalHeight: number;\n\twidth: number;\n\theight: number;\n\twasResized: boolean;\n}\n\n// 4.5MB of base64 payload. Provides headroom below Anthropic's 5MB limit.\nconst DEFAULT_MAX_BYTES = 4.5 * 1024 * 1024;\n\nconst DEFAULT_OPTIONS: Required<ImageResizeOptions> = {\n\tmaxWidth: 2000,\n\tmaxHeight: 2000,\n\tmaxBytes: DEFAULT_MAX_BYTES,\n\tjpegQuality: 80,\n};\n\ninterface EncodedCandidate {\n\tdata: string;\n\tencodedSize: number;\n\tmimeType: string;\n}\n\nfunction encodeCandidate(buffer: Uint8Array, mimeType: string): EncodedCandidate {\n\tconst data = Buffer.from(buffer).toString(\"base64\");\n\treturn {\n\t\tdata,\n\t\tencodedSize: Buffer.byteLength(data, \"utf-8\"),\n\t\tmimeType,\n\t};\n}\n\n/**\n * Resize an image to fit within the specified max dimensions and encoded file size.\n * Returns null if the image cannot be resized below maxBytes.\n *\n * Uses Photon (Rust/WASM) for image processing. If Photon is not available,\n * returns null.\n *\n * Strategy for staying under maxBytes:\n * 1. First resize to maxWidth/maxHeight\n * 2. Try both PNG and JPEG formats, pick the smaller one\n * 3. If still too large, try JPEG with decreasing quality\n * 4. If still too large, progressively reduce dimensions until 1x1\n */\nexport async function resizeImage(img: ImageContent, options?: ImageResizeOptions): Promise<ResizedImage | null> {\n\tconst opts = { ...DEFAULT_OPTIONS, ...options };\n\tconst inputBuffer = Buffer.from(img.data, \"base64\");\n\tconst inputBase64Size = Buffer.byteLength(img.data, \"utf-8\");\n\n\tconst photon = await loadPhoton();\n\tif (!photon) {\n\t\treturn null;\n\t}\n\n\tlet image: ReturnType<typeof photon.PhotonImage.new_from_byteslice> | undefined;\n\ttry {\n\t\tconst inputBytes = new Uint8Array(inputBuffer);\n\t\tconst rawImage = photon.PhotonImage.new_from_byteslice(inputBytes);\n\t\timage = applyExifOrientation(photon, rawImage, inputBytes);\n\t\tif (image !== rawImage) rawImage.free();\n\n\t\tconst originalWidth = image.get_width();\n\t\tconst originalHeight = image.get_height();\n\t\tconst format = img.mimeType?.split(\"/\")[1] ?? \"png\";\n\n\t\t// Check if already within all limits (dimensions AND encoded size)\n\t\tif (originalWidth <= opts.maxWidth && originalHeight <= opts.maxHeight && inputBase64Size < opts.maxBytes) {\n\t\t\treturn {\n\t\t\t\tdata: img.data,\n\t\t\t\tmimeType: img.mimeType ?? `image/${format}`,\n\t\t\t\toriginalWidth,\n\t\t\t\toriginalHeight,\n\t\t\t\twidth: originalWidth,\n\t\t\t\theight: originalHeight,\n\t\t\t\twasResized: false,\n\t\t\t};\n\t\t}\n\n\t\t// Calculate initial dimensions respecting max limits\n\t\tlet targetWidth = originalWidth;\n\t\tlet targetHeight = originalHeight;\n\n\t\tif (targetWidth > opts.maxWidth) {\n\t\t\ttargetHeight = Math.round((targetHeight * opts.maxWidth) / targetWidth);\n\t\t\ttargetWidth = opts.maxWidth;\n\t\t}\n\t\tif (targetHeight > opts.maxHeight) {\n\t\t\ttargetWidth = Math.round((targetWidth * opts.maxHeight) / targetHeight);\n\t\t\ttargetHeight = opts.maxHeight;\n\t\t}\n\n\t\tfunction tryEncodings(width: number, height: number, jpegQualities: number[]): EncodedCandidate[] {\n\t\t\tconst resized = photon!.resize(image!, width, height, photon!.SamplingFilter.Lanczos3);\n\n\t\t\ttry {\n\t\t\t\tconst candidates: EncodedCandidate[] = [encodeCandidate(resized.get_bytes(), \"image/png\")];\n\t\t\t\tfor (const quality of jpegQualities) {\n\t\t\t\t\tcandidates.push(encodeCandidate(resized.get_bytes_jpeg(quality), \"image/jpeg\"));\n\t\t\t\t}\n\t\t\t\treturn candidates;\n\t\t\t} finally {\n\t\t\t\tresized.free();\n\t\t\t}\n\t\t}\n\n\t\tconst qualitySteps = Array.from(new Set([opts.jpegQuality, 85, 70, 55, 40]));\n\t\tlet currentWidth = targetWidth;\n\t\tlet currentHeight = targetHeight;\n\n\t\twhile (true) {\n\t\t\tconst candidates = tryEncodings(currentWidth, currentHeight, qualitySteps);\n\t\t\tfor (const candidate of candidates) {\n\t\t\t\tif (candidate.encodedSize < opts.maxBytes) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdata: candidate.data,\n\t\t\t\t\t\tmimeType: candidate.mimeType,\n\t\t\t\t\t\toriginalWidth,\n\t\t\t\t\t\toriginalHeight,\n\t\t\t\t\t\twidth: currentWidth,\n\t\t\t\t\t\theight: currentHeight,\n\t\t\t\t\t\twasResized: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (currentWidth === 1 && currentHeight === 1) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst nextWidth = currentWidth === 1 ? 1 : Math.max(1, Math.floor(currentWidth * 0.75));\n\t\t\tconst nextHeight = currentHeight === 1 ? 1 : Math.max(1, Math.floor(currentHeight * 0.75));\n\t\t\tif (nextWidth === currentWidth && nextHeight === currentHeight) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcurrentWidth = nextWidth;\n\t\t\tcurrentHeight = nextHeight;\n\t\t}\n\n\t\treturn null;\n\t} catch {\n\t\treturn null;\n\t} finally {\n\t\tif (image) {\n\t\t\timage.free();\n\t\t}\n\t}\n}\n\n/**\n * Format a dimension note for resized images.\n * This helps the model understand the coordinate mapping.\n */\nexport function formatDimensionNote(result: ResizedImage): string | undefined {\n\tif (!result.wasResized) {\n\t\treturn undefined;\n\t}\n\n\tconst scale = result.originalWidth / result.width;\n\treturn `[Image: original ${result.originalWidth}x${result.originalHeight}, displayed at ${result.width}x${result.height}. Multiply coordinates by ${scale.toFixed(2)} to map to original image.]`;\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,GAAG,CACxB,mBAAmB,CAAC,CAAC,CAAC,0BAA0B,CAAC,CAAC,CAAC,0BAA0B,EAC7E,OAAO,IAAI,CAAC,GAAG,CACf,CAAC;IAEF,8EAA8E;IAC9E,4EAA4E;IAC5E,8EAA8E;IAC9E,IAAI,OAAO,OAAO,CAAC,QAAQ,CAAC,GAAG,KAAK,QAAQ,EAAE,CAAC;QAC9C,IAAI,CAAC;YACJ,OAAO,MAAM,mBAAmB,CAAC,oCAAoC,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;QACvG,CAAC;QAAC,MAAM,CAAC,CAAA,CAAC;IACX,CAAC;IAED,IAAI,CAAC;QACJ,OAAO,MAAM,mBAAmB,CAAC,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC5E,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,oBAAoB,CAAC,UAAU,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC5D,CAAC;AAAA,CACD;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAAoB,EAAsB;IAC7E,IAAI,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC;QACxB,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,MAAM,KAAK,GAAG,MAAM,CAAC,aAAa,GAAG,MAAM,CAAC,KAAK,CAAC;IAClD,OAAO,oBAAoB,MAAM,CAAC,aAAa,IAAI,MAAM,CAAC,cAAc,kBAAkB,MAAM,CAAC,KAAK,IAAI,MAAM,CAAC,MAAM,6BAA6B,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,6BAA6B,CAAC;AAAA,CAClM","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { type ImageResizeOptions, type ResizedImage, resizeImageInProcess } from \"./image-resize-core.ts\";\n\nexport type { ImageResizeOptions, ResizedImage } from \"./image-resize-core.ts\";\n\ninterface ResizeImageWorkerResponse {\n\tresult?: ResizedImage | null;\n\terror?: string;\n}\n\nfunction toTransferableBytes(input: Uint8Array): Uint8Array<ArrayBuffer> {\n\t// Transfer detaches the buffer, so transfer a worker-owned copy and leave the\n\t// caller's bytes intact.\n\treturn new Uint8Array(input);\n}\n\nfunction isResizeImageWorkerResponse(value: unknown): value is ResizeImageWorkerResponse {\n\treturn value !== null && typeof value === \"object\";\n}\n\nfunction createResizeWorker(workerSpecifier: string | URL): Worker {\n\treturn new Worker(workerSpecifier);\n}\n\nasync function resizeImageInWorker(\n\tworkerSpecifier: string | URL,\n\tinputBytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ImageResizeOptions,\n): Promise<ResizedImage | null> {\n\tconst worker = createResizeWorker(workerSpecifier);\n\ttry {\n\t\tconst inputBytesForWorker = toTransferableBytes(inputBytes);\n\t\treturn await new Promise<ResizedImage | null>((resolve, reject) => {\n\t\t\tlet settled = false;\n\t\t\tconst settle = (result: ResizedImage | null): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tresolve(result);\n\t\t\t};\n\t\t\tconst fail = (error: Error): void => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\treject(error);\n\t\t\t};\n\n\t\t\tworker.once(\"message\", (message: unknown) => {\n\t\t\t\tif (!isResizeImageWorkerResponse(message)) {\n\t\t\t\t\tfail(new Error(\"Invalid image resize worker response\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (message.error) {\n\t\t\t\t\tfail(new Error(message.error));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettle(message.result ?? null);\n\t\t\t});\n\t\t\tworker.once(\"error\", fail);\n\t\t\tworker.once(\"exit\", (code) => {\n\t\t\t\tif (!settled) {\n\t\t\t\t\tfail(new Error(`Image resize worker exited with code ${code}`));\n\t\t\t\t}\n\t\t\t});\n\t\t\tworker.postMessage(\n\t\t\t\t{\n\t\t\t\t\tinputBytes: inputBytesForWorker,\n\t\t\t\t\tmimeType,\n\t\t\t\t\toptions,\n\t\t\t\t},\n\t\t\t\t[inputBytesForWorker.buffer],\n\t\t\t);\n\t\t});\n\t} finally {\n\t\tvoid worker.terminate().catch(() => undefined);\n\t}\n}\n\n/**\n * Resize an image to fit within the specified max dimensions and encoded file size.\n * Runs Photon in a worker thread so WASM decoding, resizing, and encoding do not\n * block the TUI event loop. If the worker cannot be loaded (for example in some\n * Bun compiled executable layouts), fall back to in-process resizing so image\n * reads still work.\n */\nexport async function resizeImage(\n\tinputBytes: Uint8Array,\n\tmimeType: string,\n\toptions?: ImageResizeOptions,\n): Promise<ResizedImage | null> {\n\tconst isTypeScriptRuntime = import.meta.url.endsWith(\".ts\");\n\tconst workerUrl = new URL(\n\t\tisTypeScriptRuntime ? \"./image-resize-worker.ts\" : \"./image-resize-worker.js\",\n\t\timport.meta.url,\n\t);\n\n\t// Bun compiled executables resolve worker entrypoints by string path, not via\n\t// new URL(..., import.meta.url). Try the string path first under Bun so the\n\t// release binary uses the embedded worker instead of falling back in-process.\n\tif (typeof process.versions.bun === \"string\") {\n\t\ttry {\n\t\t\treturn await resizeImageInWorker(\"./src/utils/image-resize-worker.ts\", inputBytes, mimeType, options);\n\t\t} catch {}\n\t}\n\n\ttry {\n\t\treturn await resizeImageInWorker(workerUrl, inputBytes, mimeType, options);\n\t} catch {\n\t\treturn resizeImageInProcess(inputBytes, mimeType, options);\n\t}\n}\n\n/**\n * Format a dimension note for resized images.\n * This helps the model understand the coordinate mapping.\n */\nexport function formatDimensionNote(result: ResizedImage): string | undefined {\n\tif (!result.wasResized) {\n\t\treturn undefined;\n\t}\n\n\tconst scale = result.originalWidth / result.width;\n\treturn `[Image: original ${result.originalWidth}x${result.originalHeight}, displayed at ${result.width}x${result.height}. Multiply coordinates by ${scale.toFixed(2)} to map to original image.]`;\n}\n"]}
@@ -1,3 +1,15 @@
1
+ export interface PathInputOptions {
2
+ /** Trim leading/trailing whitespace before normalization. */
3
+ trim?: boolean;
4
+ /** Expand leading `~` to a home directory. Defaults to true. */
5
+ expandTilde?: boolean;
6
+ /** Home directory used for `~` expansion. Defaults to `os.homedir()`. */
7
+ homeDir?: string;
8
+ /** Strip a leading `@`, used for CLI @file paths. */
9
+ stripAtPrefix?: boolean;
10
+ /** Normalize unicode space variants to regular spaces. */
11
+ normalizeUnicodeSpaces?: boolean;
12
+ }
1
13
  /**
2
14
  * Resolve a path to its canonical (real) form, following symlinks.
3
15
  * Falls back to the raw path if resolution fails (e.g. the target does
@@ -7,11 +19,14 @@
7
19
  export declare function canonicalizePath(path: string): string;
8
20
  /**
9
21
  * Returns true if the value is NOT a package source (npm:, git:, etc.)
10
- * or a URL protocol. Bare names and relative paths without ./ prefix
22
+ * or a remote URL protocol. Bare names, relative paths, and file: URLs
11
23
  * are considered local.
12
24
  */
13
25
  export declare function isLocalPath(value: string): boolean;
26
+ export declare function normalizePath(input: string, options?: PathInputOptions): string;
27
+ export declare function resolvePath(input: string, baseDir?: string, options?: PathInputOptions): string;
14
28
  export declare function getCwdRelativePath(filePath: string, cwd: string): string | undefined;
15
29
  export declare function formatPathRelativeToCwdOrAbsolute(filePath: string, cwd: string): string;
30
+ export declare function shortenPath(path: string): string;
16
31
  export declare function markPathIgnoredByCloudSync(path: string): void;
17
32
  //# sourceMappingURL=paths.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"paths.d.ts","sourceRoot":"","sources":["../../src/utils/paths.ts"],"names":[],"mappings":"AAIA;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAMrD;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAclD;AAMD,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CASpF;AAED,wBAAgB,iCAAiC,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAGvF;AAED,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAe7D","sourcesContent":["import { realpathSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve as resolvePath, sep } from \"node:path\";\nimport { spawnProcessSync } from \"./child-process.ts\";\n\n/**\n * Resolve a path to its canonical (real) form, following symlinks.\n * Falls back to the raw path if resolution fails (e.g. the target does\n * not exist yet), so that callers never crash on missing filesystem\n * entries.\n */\nexport function canonicalizePath(path: string): string {\n\ttry {\n\t\treturn realpathSync(path);\n\t} catch {\n\t\treturn path;\n\t}\n}\n\n/**\n * Returns true if the value is NOT a package source (npm:, git:, etc.)\n * or a URL protocol. Bare names and relative paths without ./ prefix\n * are considered local.\n */\nexport function isLocalPath(value: string): boolean {\n\tconst trimmed = value.trim();\n\t// Known non-local prefixes\n\tif (\n\t\ttrimmed.startsWith(\"npm:\") ||\n\t\ttrimmed.startsWith(\"git:\") ||\n\t\ttrimmed.startsWith(\"github:\") ||\n\t\ttrimmed.startsWith(\"http:\") ||\n\t\ttrimmed.startsWith(\"https:\") ||\n\t\ttrimmed.startsWith(\"ssh:\")\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nfunction resolveAgainstCwd(filePath: string, cwd: string): string {\n\treturn isAbsolute(filePath) ? resolvePath(filePath) : resolvePath(cwd, filePath);\n}\n\nexport function getCwdRelativePath(filePath: string, cwd: string): string | undefined {\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedPath = resolveAgainstCwd(filePath, resolvedCwd);\n\tconst relativePath = relative(resolvedCwd, resolvedPath);\n\tconst isInsideCwd =\n\t\trelativePath === \"\" ||\n\t\t(relativePath !== \"..\" && !relativePath.startsWith(`..${sep}`) && !isAbsolute(relativePath));\n\n\treturn isInsideCwd ? relativePath || \".\" : undefined;\n}\n\nexport function formatPathRelativeToCwdOrAbsolute(filePath: string, cwd: string): string {\n\tconst absolutePath = resolveAgainstCwd(filePath, cwd);\n\treturn (getCwdRelativePath(absolutePath, cwd) ?? absolutePath).split(sep).join(\"/\");\n}\n\nexport function markPathIgnoredByCloudSync(path: string): void {\n\tconst attrs =\n\t\tprocess.platform === \"darwin\"\n\t\t\t? [\"com.dropbox.ignored\", \"com.apple.fileprovider.ignore#P\"]\n\t\t\t: process.platform === \"linux\"\n\t\t\t\t? [\"user.com.dropbox.ignored\"]\n\t\t\t\t: [];\n\n\tfor (const attr of attrs) {\n\t\tif (process.platform === \"darwin\") {\n\t\t\tspawnProcessSync(\"xattr\", [\"-w\", attr, \"1\", path], { encoding: \"utf-8\", stdio: \"ignore\" });\n\t\t} else {\n\t\t\tspawnProcessSync(\"setfattr\", [\"-n\", attr, \"-v\", \"1\", path], { encoding: \"utf-8\", stdio: \"ignore\" });\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"paths.d.ts","sourceRoot":"","sources":["../../src/utils/paths.ts"],"names":[],"mappings":"AAQA,MAAM,WAAW,gBAAgB;IAChC,6DAA6D;IAC7D,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,gEAAgE;IAChE,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,yEAAyE;IACzE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,qDAAqD;IACrD,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,0DAA0D;IAC1D,sBAAsB,CAAC,EAAE,OAAO,CAAC;CACjC;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAMrD;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAclD;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB,GAAG,MAAM,CAsBnF;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,MAAsB,EAAE,OAAO,GAAE,gBAAqB,GAAG,MAAM,CAIlH;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CASpF;AAED,wBAAgB,iCAAiC,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAGvF;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAKhD;AAED,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAe7D","sourcesContent":["import { realpathSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { isAbsolute, join, resolve as nodeResolvePath, relative, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { spawnProcessSync } from \"./child-process.ts\";\n\nconst UNICODE_SPACES = /[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g;\n\nexport interface PathInputOptions {\n\t/** Trim leading/trailing whitespace before normalization. */\n\ttrim?: boolean;\n\t/** Expand leading `~` to a home directory. Defaults to true. */\n\texpandTilde?: boolean;\n\t/** Home directory used for `~` expansion. Defaults to `os.homedir()`. */\n\thomeDir?: string;\n\t/** Strip a leading `@`, used for CLI @file paths. */\n\tstripAtPrefix?: boolean;\n\t/** Normalize unicode space variants to regular spaces. */\n\tnormalizeUnicodeSpaces?: boolean;\n}\n\n/**\n * Resolve a path to its canonical (real) form, following symlinks.\n * Falls back to the raw path if resolution fails (e.g. the target does\n * not exist yet), so that callers never crash on missing filesystem\n * entries.\n */\nexport function canonicalizePath(path: string): string {\n\ttry {\n\t\treturn realpathSync(path);\n\t} catch {\n\t\treturn path;\n\t}\n}\n\n/**\n * Returns true if the value is NOT a package source (npm:, git:, etc.)\n * or a remote URL protocol. Bare names, relative paths, and file: URLs\n * are considered local.\n */\nexport function isLocalPath(value: string): boolean {\n\tconst trimmed = value.trim();\n\t// Known non-local prefixes. file: URLs are local paths and are intentionally resolved by resolvePath().\n\tif (\n\t\ttrimmed.startsWith(\"npm:\") ||\n\t\ttrimmed.startsWith(\"git:\") ||\n\t\ttrimmed.startsWith(\"github:\") ||\n\t\ttrimmed.startsWith(\"http:\") ||\n\t\ttrimmed.startsWith(\"https:\") ||\n\t\ttrimmed.startsWith(\"ssh:\")\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nexport function normalizePath(input: string, options: PathInputOptions = {}): string {\n\tlet normalized = options.trim ? input.trim() : input;\n\tif (options.normalizeUnicodeSpaces) {\n\t\tnormalized = normalized.replace(UNICODE_SPACES, \" \");\n\t}\n\tif (options.stripAtPrefix && normalized.startsWith(\"@\")) {\n\t\tnormalized = normalized.slice(1);\n\t}\n\n\tif (options.expandTilde ?? true) {\n\t\tconst home = options.homeDir ?? homedir();\n\t\tif (normalized === \"~\") return home;\n\t\tif (normalized.startsWith(\"~/\") || (process.platform === \"win32\" && normalized.startsWith(\"~\\\\\"))) {\n\t\t\treturn join(home, normalized.slice(2));\n\t\t}\n\t}\n\n\tif (/^file:\\/\\//.test(normalized)) {\n\t\treturn fileURLToPath(normalized);\n\t}\n\n\treturn normalized;\n}\n\nexport function resolvePath(input: string, baseDir: string = process.cwd(), options: PathInputOptions = {}): string {\n\tconst normalized = normalizePath(input, options);\n\tconst normalizedBaseDir = normalizePath(baseDir);\n\treturn isAbsolute(normalized) ? nodeResolvePath(normalized) : nodeResolvePath(normalizedBaseDir, normalized);\n}\n\nexport function getCwdRelativePath(filePath: string, cwd: string): string | undefined {\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedPath = resolvePath(filePath, resolvedCwd);\n\tconst relativePath = relative(resolvedCwd, resolvedPath);\n\tconst isInsideCwd =\n\t\trelativePath === \"\" ||\n\t\t(relativePath !== \"..\" && !relativePath.startsWith(`..${sep}`) && !isAbsolute(relativePath));\n\n\treturn isInsideCwd ? relativePath || \".\" : undefined;\n}\n\nexport function formatPathRelativeToCwdOrAbsolute(filePath: string, cwd: string): string {\n\tconst absolutePath = resolvePath(filePath, cwd);\n\treturn (getCwdRelativePath(absolutePath, cwd) ?? absolutePath).split(sep).join(\"/\");\n}\n\nexport function shortenPath(path: string): string {\n\tif (!path) return path;\n\tconst home = homedir();\n\tif (path.startsWith(home)) return `~${path.slice(home.length)}`;\n\treturn path;\n}\n\nexport function markPathIgnoredByCloudSync(path: string): void {\n\tconst attrs =\n\t\tprocess.platform === \"darwin\"\n\t\t\t? [\"com.dropbox.ignored\", \"com.apple.fileprovider.ignore#P\"]\n\t\t\t: process.platform === \"linux\"\n\t\t\t\t? [\"user.com.dropbox.ignored\"]\n\t\t\t\t: [];\n\n\tfor (const attr of attrs) {\n\t\tif (process.platform === \"darwin\") {\n\t\t\tspawnProcessSync(\"xattr\", [\"-w\", attr, \"1\", path], { encoding: \"utf-8\", stdio: \"ignore\" });\n\t\t} else {\n\t\t\tspawnProcessSync(\"setfattr\", [\"-n\", attr, \"-v\", \"1\", path], { encoding: \"utf-8\", stdio: \"ignore\" });\n\t\t}\n\t}\n}\n"]}
@@ -1,6 +1,9 @@
1
1
  import { realpathSync } from "node:fs";
2
- import { isAbsolute, relative, resolve as resolvePath, sep } from "node:path";
2
+ import { homedir } from "node:os";
3
+ import { isAbsolute, join, resolve as nodeResolvePath, relative, sep } from "node:path";
4
+ import { fileURLToPath } from "node:url";
3
5
  import { spawnProcessSync } from "./child-process.js";
6
+ const UNICODE_SPACES = /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g;
4
7
  /**
5
8
  * Resolve a path to its canonical (real) form, following symlinks.
6
9
  * Falls back to the raw path if resolution fails (e.g. the target does
@@ -17,12 +20,12 @@ export function canonicalizePath(path) {
17
20
  }
18
21
  /**
19
22
  * Returns true if the value is NOT a package source (npm:, git:, etc.)
20
- * or a URL protocol. Bare names and relative paths without ./ prefix
23
+ * or a remote URL protocol. Bare names, relative paths, and file: URLs
21
24
  * are considered local.
22
25
  */
23
26
  export function isLocalPath(value) {
24
27
  const trimmed = value.trim();
25
- // Known non-local prefixes
28
+ // Known non-local prefixes. file: URLs are local paths and are intentionally resolved by resolvePath().
26
29
  if (trimmed.startsWith("npm:") ||
27
30
  trimmed.startsWith("git:") ||
28
31
  trimmed.startsWith("github:") ||
@@ -33,21 +36,52 @@ export function isLocalPath(value) {
33
36
  }
34
37
  return true;
35
38
  }
36
- function resolveAgainstCwd(filePath, cwd) {
37
- return isAbsolute(filePath) ? resolvePath(filePath) : resolvePath(cwd, filePath);
39
+ export function normalizePath(input, options = {}) {
40
+ let normalized = options.trim ? input.trim() : input;
41
+ if (options.normalizeUnicodeSpaces) {
42
+ normalized = normalized.replace(UNICODE_SPACES, " ");
43
+ }
44
+ if (options.stripAtPrefix && normalized.startsWith("@")) {
45
+ normalized = normalized.slice(1);
46
+ }
47
+ if (options.expandTilde ?? true) {
48
+ const home = options.homeDir ?? homedir();
49
+ if (normalized === "~")
50
+ return home;
51
+ if (normalized.startsWith("~/") || (process.platform === "win32" && normalized.startsWith("~\\"))) {
52
+ return join(home, normalized.slice(2));
53
+ }
54
+ }
55
+ if (/^file:\/\//.test(normalized)) {
56
+ return fileURLToPath(normalized);
57
+ }
58
+ return normalized;
59
+ }
60
+ export function resolvePath(input, baseDir = process.cwd(), options = {}) {
61
+ const normalized = normalizePath(input, options);
62
+ const normalizedBaseDir = normalizePath(baseDir);
63
+ return isAbsolute(normalized) ? nodeResolvePath(normalized) : nodeResolvePath(normalizedBaseDir, normalized);
38
64
  }
39
65
  export function getCwdRelativePath(filePath, cwd) {
40
66
  const resolvedCwd = resolvePath(cwd);
41
- const resolvedPath = resolveAgainstCwd(filePath, resolvedCwd);
67
+ const resolvedPath = resolvePath(filePath, resolvedCwd);
42
68
  const relativePath = relative(resolvedCwd, resolvedPath);
43
69
  const isInsideCwd = relativePath === "" ||
44
70
  (relativePath !== ".." && !relativePath.startsWith(`..${sep}`) && !isAbsolute(relativePath));
45
71
  return isInsideCwd ? relativePath || "." : undefined;
46
72
  }
47
73
  export function formatPathRelativeToCwdOrAbsolute(filePath, cwd) {
48
- const absolutePath = resolveAgainstCwd(filePath, cwd);
74
+ const absolutePath = resolvePath(filePath, cwd);
49
75
  return (getCwdRelativePath(absolutePath, cwd) ?? absolutePath).split(sep).join("/");
50
76
  }
77
+ export function shortenPath(path) {
78
+ if (!path)
79
+ return path;
80
+ const home = homedir();
81
+ if (path.startsWith(home))
82
+ return `~${path.slice(home.length)}`;
83
+ return path;
84
+ }
51
85
  export function markPathIgnoredByCloudSync(path) {
52
86
  const attrs = process.platform === "darwin"
53
87
  ? ["com.dropbox.ignored", "com.apple.fileprovider.ignore#P"]
@@ -1 +1 @@
1
- {"version":3,"file":"paths.js","sourceRoot":"","sources":["../../src/utils/paths.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,IAAI,WAAW,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAC9E,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB,CAAC,IAAY,EAAU;IACtD,IAAI,CAAC;QACJ,OAAO,YAAY,CAAC,IAAI,CAAC,CAAC;IAC3B,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,IAAI,CAAC;IACb,CAAC;AAAA,CACD;AAED;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,KAAa,EAAW;IACnD,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,EAAE,CAAC;IAC7B,2BAA2B;IAC3B,IACC,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC;QAC1B,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC;QAC1B,OAAO,CAAC,UAAU,CAAC,SAAS,CAAC;QAC7B,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC;QAC3B,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC;QAC5B,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,EACzB,CAAC;QACF,OAAO,KAAK,CAAC;IACd,CAAC;IACD,OAAO,IAAI,CAAC;AAAA,CACZ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,CAAC,CAAC,0BAA0B,CAAC;YAC9B,CAAC,CAAC,EAAE,CAAC;IAER,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QAC1B,IAAI,OAAO,CAAC,QAAQ,KAAK,QAAQ,EAAE,CAAC;YACnC,gBAAgB,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC;QAC5F,CAAC;aAAM,CAAC;YACP,gBAAgB,CAAC,UAAU,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC;QACrG,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import { realpathSync } from \"node:fs\";\nimport { isAbsolute, relative, resolve as resolvePath, sep } from \"node:path\";\nimport { spawnProcessSync } from \"./child-process.ts\";\n\n/**\n * Resolve a path to its canonical (real) form, following symlinks.\n * Falls back to the raw path if resolution fails (e.g. the target does\n * not exist yet), so that callers never crash on missing filesystem\n * entries.\n */\nexport function canonicalizePath(path: string): string {\n\ttry {\n\t\treturn realpathSync(path);\n\t} catch {\n\t\treturn path;\n\t}\n}\n\n/**\n * Returns true if the value is NOT a package source (npm:, git:, etc.)\n * or a URL protocol. Bare names and relative paths without ./ prefix\n * are considered local.\n */\nexport function isLocalPath(value: string): boolean {\n\tconst trimmed = value.trim();\n\t// Known non-local prefixes\n\tif (\n\t\ttrimmed.startsWith(\"npm:\") ||\n\t\ttrimmed.startsWith(\"git:\") ||\n\t\ttrimmed.startsWith(\"github:\") ||\n\t\ttrimmed.startsWith(\"http:\") ||\n\t\ttrimmed.startsWith(\"https:\") ||\n\t\ttrimmed.startsWith(\"ssh:\")\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nfunction resolveAgainstCwd(filePath: string, cwd: string): string {\n\treturn isAbsolute(filePath) ? resolvePath(filePath) : resolvePath(cwd, filePath);\n}\n\nexport function getCwdRelativePath(filePath: string, cwd: string): string | undefined {\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedPath = resolveAgainstCwd(filePath, resolvedCwd);\n\tconst relativePath = relative(resolvedCwd, resolvedPath);\n\tconst isInsideCwd =\n\t\trelativePath === \"\" ||\n\t\t(relativePath !== \"..\" && !relativePath.startsWith(`..${sep}`) && !isAbsolute(relativePath));\n\n\treturn isInsideCwd ? relativePath || \".\" : undefined;\n}\n\nexport function formatPathRelativeToCwdOrAbsolute(filePath: string, cwd: string): string {\n\tconst absolutePath = resolveAgainstCwd(filePath, cwd);\n\treturn (getCwdRelativePath(absolutePath, cwd) ?? absolutePath).split(sep).join(\"/\");\n}\n\nexport function markPathIgnoredByCloudSync(path: string): void {\n\tconst attrs =\n\t\tprocess.platform === \"darwin\"\n\t\t\t? [\"com.dropbox.ignored\", \"com.apple.fileprovider.ignore#P\"]\n\t\t\t: process.platform === \"linux\"\n\t\t\t\t? [\"user.com.dropbox.ignored\"]\n\t\t\t\t: [];\n\n\tfor (const attr of attrs) {\n\t\tif (process.platform === \"darwin\") {\n\t\t\tspawnProcessSync(\"xattr\", [\"-w\", attr, \"1\", path], { encoding: \"utf-8\", stdio: \"ignore\" });\n\t\t} else {\n\t\t\tspawnProcessSync(\"setfattr\", [\"-n\", attr, \"-v\", \"1\", path], { encoding: \"utf-8\", stdio: \"ignore\" });\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"paths.js","sourceRoot":"","sources":["../../src/utils/paths.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,IAAI,eAAe,EAAE,QAAQ,EAAE,GAAG,EAAE,M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C,QAAQ,KAAK,QAAQ,EAAE,CAAC;YACnC,gBAAgB,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC;QAC5F,CAAC;aAAM,CAAC;YACP,gBAAgB,CAAC,UAAU,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC;QACrG,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import { realpathSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { isAbsolute, join, resolve as nodeResolvePath, relative, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { spawnProcessSync } from \"./child-process.ts\";\n\nconst UNICODE_SPACES = /[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]/g;\n\nexport interface PathInputOptions {\n\t/** Trim leading/trailing whitespace before normalization. */\n\ttrim?: boolean;\n\t/** Expand leading `~` to a home directory. Defaults to true. */\n\texpandTilde?: boolean;\n\t/** Home directory used for `~` expansion. Defaults to `os.homedir()`. */\n\thomeDir?: string;\n\t/** Strip a leading `@`, used for CLI @file paths. */\n\tstripAtPrefix?: boolean;\n\t/** Normalize unicode space variants to regular spaces. */\n\tnormalizeUnicodeSpaces?: boolean;\n}\n\n/**\n * Resolve a path to its canonical (real) form, following symlinks.\n * Falls back to the raw path if resolution fails (e.g. the target does\n * not exist yet), so that callers never crash on missing filesystem\n * entries.\n */\nexport function canonicalizePath(path: string): string {\n\ttry {\n\t\treturn realpathSync(path);\n\t} catch {\n\t\treturn path;\n\t}\n}\n\n/**\n * Returns true if the value is NOT a package source (npm:, git:, etc.)\n * or a remote URL protocol. Bare names, relative paths, and file: URLs\n * are considered local.\n */\nexport function isLocalPath(value: string): boolean {\n\tconst trimmed = value.trim();\n\t// Known non-local prefixes. file: URLs are local paths and are intentionally resolved by resolvePath().\n\tif (\n\t\ttrimmed.startsWith(\"npm:\") ||\n\t\ttrimmed.startsWith(\"git:\") ||\n\t\ttrimmed.startsWith(\"github:\") ||\n\t\ttrimmed.startsWith(\"http:\") ||\n\t\ttrimmed.startsWith(\"https:\") ||\n\t\ttrimmed.startsWith(\"ssh:\")\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nexport function normalizePath(input: string, options: PathInputOptions = {}): string {\n\tlet normalized = options.trim ? input.trim() : input;\n\tif (options.normalizeUnicodeSpaces) {\n\t\tnormalized = normalized.replace(UNICODE_SPACES, \" \");\n\t}\n\tif (options.stripAtPrefix && normalized.startsWith(\"@\")) {\n\t\tnormalized = normalized.slice(1);\n\t}\n\n\tif (options.expandTilde ?? true) {\n\t\tconst home = options.homeDir ?? homedir();\n\t\tif (normalized === \"~\") return home;\n\t\tif (normalized.startsWith(\"~/\") || (process.platform === \"win32\" && normalized.startsWith(\"~\\\\\"))) {\n\t\t\treturn join(home, normalized.slice(2));\n\t\t}\n\t}\n\n\tif (/^file:\\/\\//.test(normalized)) {\n\t\treturn fileURLToPath(normalized);\n\t}\n\n\treturn normalized;\n}\n\nexport function resolvePath(input: string, baseDir: string = process.cwd(), options: PathInputOptions = {}): string {\n\tconst normalized = normalizePath(input, options);\n\tconst normalizedBaseDir = normalizePath(baseDir);\n\treturn isAbsolute(normalized) ? nodeResolvePath(normalized) : nodeResolvePath(normalizedBaseDir, normalized);\n}\n\nexport function getCwdRelativePath(filePath: string, cwd: string): string | undefined {\n\tconst resolvedCwd = resolvePath(cwd);\n\tconst resolvedPath = resolvePath(filePath, resolvedCwd);\n\tconst relativePath = relative(resolvedCwd, resolvedPath);\n\tconst isInsideCwd =\n\t\trelativePath === \"\" ||\n\t\t(relativePath !== \"..\" && !relativePath.startsWith(`..${sep}`) && !isAbsolute(relativePath));\n\n\treturn isInsideCwd ? relativePath || \".\" : undefined;\n}\n\nexport function formatPathRelativeToCwdOrAbsolute(filePath: string, cwd: string): string {\n\tconst absolutePath = resolvePath(filePath, cwd);\n\treturn (getCwdRelativePath(absolutePath, cwd) ?? absolutePath).split(sep).join(\"/\");\n}\n\nexport function shortenPath(path: string): string {\n\tif (!path) return path;\n\tconst home = homedir();\n\tif (path.startsWith(home)) return `~${path.slice(home.length)}`;\n\treturn path;\n}\n\nexport function markPathIgnoredByCloudSync(path: string): void {\n\tconst attrs =\n\t\tprocess.platform === \"darwin\"\n\t\t\t? [\"com.dropbox.ignored\", \"com.apple.fileprovider.ignore#P\"]\n\t\t\t: process.platform === \"linux\"\n\t\t\t\t? [\"user.com.dropbox.ignored\"]\n\t\t\t\t: [];\n\n\tfor (const attr of attrs) {\n\t\tif (process.platform === \"darwin\") {\n\t\t\tspawnProcessSync(\"xattr\", [\"-w\", attr, \"1\", path], { encoding: \"utf-8\", stdio: \"ignore\" });\n\t\t} else {\n\t\t\tspawnProcessSync(\"setfattr\", [\"-n\", attr, \"-v\", \"1\", path], { encoding: \"utf-8\", stdio: \"ignore\" });\n\t\t}\n\t}\n}\n"]}