@nhtio/adk 0.1.0-master-e6c58205 → 0.1.0-master-89b47bec

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 (290) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/__vite-browser-external-CU7uua8b.mjs +9 -0
  3. package/__vite-browser-external-CU7uua8b.mjs.map +1 -0
  4. package/__vite-browser-external-DAHxjh-D.js +13 -0
  5. package/__vite-browser-external-DAHxjh-D.js.map +1 -0
  6. package/batteries/embeddings/openai/adapter.cjs +1 -1
  7. package/batteries/embeddings/openai/adapter.mjs +1 -1
  8. package/batteries/embeddings/webllm/adapter.cjs +1 -1
  9. package/batteries/embeddings/webllm/adapter.mjs +1 -1
  10. package/batteries/llm/ollama/adapter.cjs +5 -5
  11. package/batteries/llm/ollama/adapter.mjs +5 -5
  12. package/batteries/llm/ollama/helpers.cjs +2 -2
  13. package/batteries/llm/ollama/helpers.mjs +2 -2
  14. package/batteries/llm/ollama/validation.cjs +1 -1
  15. package/batteries/llm/ollama/validation.mjs +1 -1
  16. package/batteries/llm/openai_chat_completions/adapter.cjs +5 -5
  17. package/batteries/llm/openai_chat_completions/adapter.mjs +5 -5
  18. package/batteries/llm/openai_chat_completions/helpers.cjs +2 -2
  19. package/batteries/llm/openai_chat_completions/helpers.mjs +2 -2
  20. package/batteries/llm/openai_chat_completions/validation.cjs +1 -1
  21. package/batteries/llm/openai_chat_completions/validation.mjs +1 -1
  22. package/batteries/llm/webllm_chat_completions/adapter.cjs +5 -5
  23. package/batteries/llm/webllm_chat_completions/adapter.mjs +5 -5
  24. package/batteries/llm/webllm_chat_completions/validation.cjs +1 -1
  25. package/batteries/llm/webllm_chat_completions/validation.mjs +1 -1
  26. package/batteries/media/contracts.cjs +38 -8
  27. package/batteries/media/contracts.cjs.map +1 -1
  28. package/batteries/media/contracts.d.ts +86 -6
  29. package/batteries/media/contracts.mjs +37 -9
  30. package/batteries/media/contracts.mjs.map +1 -1
  31. package/batteries/media/engines/audio_decode.cjs +46 -6
  32. package/batteries/media/engines/audio_decode.cjs.map +1 -1
  33. package/batteries/media/engines/audio_decode.d.ts +9 -5
  34. package/batteries/media/engines/audio_decode.mjs +47 -7
  35. package/batteries/media/engines/audio_decode.mjs.map +1 -1
  36. package/batteries/media/engines/data.cjs +159 -0
  37. package/batteries/media/engines/data.cjs.map +1 -0
  38. package/batteries/media/engines/data.d.ts +36 -0
  39. package/batteries/media/engines/data.mjs +157 -0
  40. package/batteries/media/engines/data.mjs.map +1 -0
  41. package/batteries/media/engines/exceljs.cjs +290 -0
  42. package/batteries/media/engines/exceljs.cjs.map +1 -0
  43. package/batteries/media/engines/exceljs.d.ts +41 -0
  44. package/batteries/media/engines/exceljs.mjs +288 -0
  45. package/batteries/media/engines/exceljs.mjs.map +1 -0
  46. package/batteries/media/engines/execa_executor.cjs +1 -1
  47. package/batteries/media/engines/execa_executor.mjs +1 -1
  48. package/batteries/media/engines/fs_workspace.cjs +1 -1
  49. package/batteries/media/engines/fs_workspace.mjs +1 -1
  50. package/batteries/media/engines/jimp.cjs +24 -2
  51. package/batteries/media/engines/jimp.cjs.map +1 -1
  52. package/batteries/media/engines/jimp.d.ts +3 -1
  53. package/batteries/media/engines/jimp.mjs +24 -2
  54. package/batteries/media/engines/jimp.mjs.map +1 -1
  55. package/batteries/media/engines/sharp.cjs +37 -4
  56. package/batteries/media/engines/sharp.cjs.map +1 -1
  57. package/batteries/media/engines/sharp.d.ts +5 -3
  58. package/batteries/media/engines/sharp.mjs +37 -4
  59. package/batteries/media/engines/sharp.mjs.map +1 -1
  60. package/batteries/media/engines/sheetjs.cjs +438 -0
  61. package/batteries/media/engines/sheetjs.cjs.map +1 -0
  62. package/batteries/media/engines/sheetjs.d.ts +51 -0
  63. package/batteries/media/engines/sheetjs.mjs +436 -0
  64. package/batteries/media/engines/sheetjs.mjs.map +1 -0
  65. package/batteries/media/engines/soffice.cjs +37 -3
  66. package/batteries/media/engines/soffice.cjs.map +1 -1
  67. package/batteries/media/engines/soffice.mjs +38 -4
  68. package/batteries/media/engines/soffice.mjs.map +1 -1
  69. package/batteries/media/engines/tesseract_js.cjs +1 -1
  70. package/batteries/media/engines/tesseract_js.mjs +1 -1
  71. package/batteries/media/engines/transformers_asr.cjs +1 -1
  72. package/batteries/media/engines/transformers_asr.mjs +1 -1
  73. package/batteries/media/forge.cjs +89 -20
  74. package/batteries/media/forge.cjs.map +1 -1
  75. package/batteries/media/forge.mjs +89 -20
  76. package/batteries/media/forge.mjs.map +1 -1
  77. package/batteries/media/formats.d.ts +9 -0
  78. package/batteries/media/index.d.ts +8 -6
  79. package/batteries/media/lint.cjs +270 -58
  80. package/batteries/media/lint.cjs.map +1 -1
  81. package/batteries/media/lint.d.ts +45 -0
  82. package/batteries/media/lint.mjs +267 -58
  83. package/batteries/media/lint.mjs.map +1 -1
  84. package/batteries/media/registry.d.ts +11 -2
  85. package/batteries/media/steps/data.d.ts +26 -0
  86. package/batteries/media/steps/doc.d.ts +17 -7
  87. package/batteries/media/steps/patch.d.ts +90 -0
  88. package/batteries/media/steps/sheet.d.ts +10 -6
  89. package/batteries/media/steps/text.d.ts +4 -1
  90. package/batteries/media/validate.d.ts +5 -0
  91. package/batteries/media/verbs.d.ts +12 -1
  92. package/batteries/media.cjs +869 -448
  93. package/batteries/media.cjs.map +1 -1
  94. package/batteries/media.mjs +829 -409
  95. package/batteries/media.mjs.map +1 -1
  96. package/batteries/storage/flydrive.cjs +3 -6
  97. package/batteries/storage/flydrive.cjs.map +1 -1
  98. package/batteries/storage/flydrive.mjs +3 -6
  99. package/batteries/storage/flydrive.mjs.map +1 -1
  100. package/batteries/storage/in_memory.cjs +1 -1
  101. package/batteries/storage/in_memory.mjs +1 -1
  102. package/batteries/storage/opfs.cjs +1 -1
  103. package/batteries/storage/opfs.mjs +1 -1
  104. package/batteries/tools/_shared.cjs +2 -2
  105. package/batteries/tools/_shared.mjs +2 -2
  106. package/batteries/tools/color.cjs +2 -2
  107. package/batteries/tools/color.mjs +2 -2
  108. package/batteries/tools/comparison.cjs +3 -3
  109. package/batteries/tools/comparison.mjs +3 -3
  110. package/batteries/tools/data_structure.cjs +3 -3
  111. package/batteries/tools/data_structure.mjs +3 -3
  112. package/batteries/tools/datetime_extended.cjs +3 -3
  113. package/batteries/tools/datetime_extended.mjs +3 -3
  114. package/batteries/tools/datetime_math.cjs +3 -3
  115. package/batteries/tools/datetime_math.mjs +3 -3
  116. package/batteries/tools/encoding.cjs +3 -3
  117. package/batteries/tools/encoding.mjs +3 -3
  118. package/batteries/tools/formatting.cjs +3 -3
  119. package/batteries/tools/formatting.mjs +3 -3
  120. package/batteries/tools/geo_basics.cjs +2 -2
  121. package/batteries/tools/geo_basics.mjs +2 -2
  122. package/batteries/tools/math.cjs +3 -3
  123. package/batteries/tools/math.mjs +3 -3
  124. package/batteries/tools/memory.cjs +6 -6
  125. package/batteries/tools/memory.mjs +6 -6
  126. package/batteries/tools/parsing.cjs +4 -4
  127. package/batteries/tools/parsing.mjs +4 -4
  128. package/batteries/tools/retrievables.cjs +5 -5
  129. package/batteries/tools/retrievables.mjs +5 -5
  130. package/batteries/tools/scrapper.cjs +1 -1
  131. package/batteries/tools/scrapper.mjs +1 -1
  132. package/batteries/tools/searxng.cjs +1 -1
  133. package/batteries/tools/searxng.mjs +1 -1
  134. package/batteries/tools/standing_instructions.cjs +4 -4
  135. package/batteries/tools/standing_instructions.mjs +4 -4
  136. package/batteries/tools/statistics.cjs +4 -4
  137. package/batteries/tools/statistics.mjs +4 -4
  138. package/batteries/tools/string_processing.cjs +3 -3
  139. package/batteries/tools/string_processing.mjs +3 -3
  140. package/batteries/tools/structured_data.cjs +3 -3
  141. package/batteries/tools/structured_data.mjs +3 -3
  142. package/batteries/tools/text_analysis.cjs +3 -3
  143. package/batteries/tools/text_analysis.mjs +3 -3
  144. package/batteries/tools/text_comparison.cjs +2 -2
  145. package/batteries/tools/text_comparison.mjs +2 -2
  146. package/batteries/tools/time.cjs +3 -3
  147. package/batteries/tools/time.mjs +3 -3
  148. package/batteries/tools/unit_conversion.cjs +2 -2
  149. package/batteries/tools/unit_conversion.mjs +2 -2
  150. package/batteries/tools/web_retrieval.cjs +1 -1
  151. package/batteries/tools/web_retrieval.mjs +1 -1
  152. package/batteries/tools.cjs +2 -2
  153. package/batteries/tools.mjs +2 -2
  154. package/batteries/vector/arangodb.cjs +1 -1
  155. package/batteries/vector/arangodb.mjs +1 -1
  156. package/batteries/vector/clickhouse.cjs +1 -1
  157. package/batteries/vector/clickhouse.mjs +1 -1
  158. package/batteries/vector/cloudflare.cjs +1 -1
  159. package/batteries/vector/cloudflare.mjs +1 -1
  160. package/batteries/vector/couchbase.cjs +1 -1
  161. package/batteries/vector/couchbase.mjs +1 -1
  162. package/batteries/vector/duckdb.cjs +1 -1
  163. package/batteries/vector/duckdb.mjs +1 -1
  164. package/batteries/vector/elasticsearch.cjs +1 -1
  165. package/batteries/vector/elasticsearch.mjs +1 -1
  166. package/batteries/vector/filters.cjs +1 -1
  167. package/batteries/vector/filters.mjs +1 -1
  168. package/batteries/vector/hnswlib.cjs +1 -1
  169. package/batteries/vector/hnswlib.mjs +1 -1
  170. package/batteries/vector/lancedb.cjs +1 -1
  171. package/batteries/vector/lancedb.mjs +1 -1
  172. package/batteries/vector/mariadb.cjs +1 -1
  173. package/batteries/vector/mariadb.mjs +1 -1
  174. package/batteries/vector/meilisearch.cjs +1 -1
  175. package/batteries/vector/meilisearch.mjs +1 -1
  176. package/batteries/vector/migrate.cjs +1 -1
  177. package/batteries/vector/migrate.mjs +1 -1
  178. package/batteries/vector/mongodb.cjs +1 -1
  179. package/batteries/vector/mongodb.mjs +1 -1
  180. package/batteries/vector/neo4j.cjs +1 -1
  181. package/batteries/vector/neo4j.mjs +1 -1
  182. package/batteries/vector/opensearch.cjs +1 -1
  183. package/batteries/vector/opensearch.mjs +1 -1
  184. package/batteries/vector/oracle23ai.cjs +1 -1
  185. package/batteries/vector/oracle23ai.mjs +1 -1
  186. package/batteries/vector/pinecone.cjs +1 -1
  187. package/batteries/vector/pinecone.mjs +1 -1
  188. package/batteries/vector/redis.cjs +1 -1
  189. package/batteries/vector/redis.mjs +1 -1
  190. package/batteries/vector/retrievable.cjs +1 -1
  191. package/batteries/vector/retrievable.mjs +1 -1
  192. package/batteries/vector/s3vectors.cjs +1 -1
  193. package/batteries/vector/s3vectors.mjs +1 -1
  194. package/batteries/vector/solr.cjs +1 -1
  195. package/batteries/vector/solr.mjs +1 -1
  196. package/batteries/vector/surrealdb.cjs +1 -1
  197. package/batteries/vector/surrealdb.mjs +1 -1
  198. package/batteries/vector/typesense.cjs +1 -1
  199. package/batteries/vector/typesense.mjs +1 -1
  200. package/batteries/vector/vespa.cjs +1 -1
  201. package/batteries/vector/vespa.mjs +1 -1
  202. package/batteries/vector/weaviate.cjs +1 -1
  203. package/batteries/vector/weaviate.mjs +1 -1
  204. package/batteries.cjs +2 -2
  205. package/batteries.mjs +2 -2
  206. package/bundled_xlsx.d.ts +1075 -0
  207. package/{common-BxoznqbX.mjs → common-BQoFv108.mjs} +7 -7
  208. package/{common-BxoznqbX.mjs.map → common-BQoFv108.mjs.map} +1 -1
  209. package/{common-BBK2e5ro.js → common-DmDn4Gfl.js} +7 -7
  210. package/{common-BBK2e5ro.js.map → common-DmDn4Gfl.js.map} +1 -1
  211. package/common.cjs +7 -7
  212. package/common.mjs +7 -7
  213. package/{dispatch_runner-Hn5idJYx.js → dispatch_runner-BwplbCPr.js} +3 -3
  214. package/{dispatch_runner-Hn5idJYx.js.map → dispatch_runner-BwplbCPr.js.map} +1 -1
  215. package/{dispatch_runner-DUrpj0xR.mjs → dispatch_runner-C1ar_D7W.mjs} +3 -3
  216. package/{dispatch_runner-DUrpj0xR.mjs.map → dispatch_runner-C1ar_D7W.mjs.map} +1 -1
  217. package/dispatch_runner.cjs +1 -1
  218. package/dispatch_runner.mjs +1 -1
  219. package/eslint.cjs +1 -1
  220. package/eslint.mjs +1 -1
  221. package/forge.cjs +4 -4
  222. package/forge.mjs +4 -4
  223. package/formats-CCylUHZw.mjs +161 -0
  224. package/formats-CCylUHZw.mjs.map +1 -0
  225. package/formats-DZVuqZUN.js +196 -0
  226. package/formats-DZVuqZUN.js.map +1 -0
  227. package/guards.cjs +8 -8
  228. package/guards.mjs +8 -8
  229. package/index.cjs +11 -11
  230. package/index.mjs +11 -11
  231. package/mcp/adk-docs-corpus.json +1 -1
  232. package/package.json +198 -182
  233. package/{scrapper-DLj_KkxK.mjs → scrapper-Dn2wXu0Y.mjs} +5 -5
  234. package/{scrapper-DLj_KkxK.mjs.map → scrapper-Dn2wXu0Y.mjs.map} +1 -1
  235. package/{scrapper-Cmf1CSA-.js → scrapper-mBZ0Odq7.js} +5 -5
  236. package/{scrapper-Cmf1CSA-.js.map → scrapper-mBZ0Odq7.js.map} +1 -1
  237. package/{searxng-BKs5s8Su.js → searxng-Dj-iP_Vz.js} +5 -5
  238. package/{searxng-BKs5s8Su.js.map → searxng-Dj-iP_Vz.js.map} +1 -1
  239. package/{searxng-BJ-aZcMz.mjs → searxng-DjFxtFf6.mjs} +5 -5
  240. package/{searxng-BJ-aZcMz.mjs.map → searxng-DjFxtFf6.mjs.map} +1 -1
  241. package/server.json +21 -0
  242. package/skills/adk-assembly/SKILL.md +2 -2
  243. package/{spooled_artifact-BR0IhU9y.js → spooled_artifact-BCmPrxZS.js} +3 -3
  244. package/{spooled_artifact-BR0IhU9y.js.map → spooled_artifact-BCmPrxZS.js.map} +1 -1
  245. package/{spooled_artifact-nTE6ujM8.mjs → spooled_artifact-DL36jnqA.mjs} +3 -3
  246. package/{spooled_artifact-nTE6ujM8.mjs.map → spooled_artifact-DL36jnqA.mjs.map} +1 -1
  247. package/spooled_artifact.cjs +2 -2
  248. package/spooled_artifact.mjs +2 -2
  249. package/{spooled_markdown_artifact-Dj3fNowz.js → spooled_markdown_artifact-CD4PrrpV.js} +3 -3
  250. package/{spooled_markdown_artifact-Dj3fNowz.js.map → spooled_markdown_artifact-CD4PrrpV.js.map} +1 -1
  251. package/{spooled_markdown_artifact-DIYzbQv8.mjs → spooled_markdown_artifact-Da-Xnebh.mjs} +3 -3
  252. package/{spooled_markdown_artifact-DIYzbQv8.mjs.map → spooled_markdown_artifact-Da-Xnebh.mjs.map} +1 -1
  253. package/{thought-Cde2Y_GK.mjs → thought-CtOoZUSE.mjs} +3 -3
  254. package/{thought-Cde2Y_GK.mjs.map → thought-CtOoZUSE.mjs.map} +1 -1
  255. package/{thought-BFtsnUTU.js → thought-eka4iUHa.js} +3 -3
  256. package/{thought-BFtsnUTU.js.map → thought-eka4iUHa.js.map} +1 -1
  257. package/{tool-CcxYxA5X.mjs → tool-CITF20yJ.mjs} +3 -3
  258. package/{tool-CcxYxA5X.mjs.map → tool-CITF20yJ.mjs.map} +1 -1
  259. package/{tool-B2nnkwNU.js → tool-Dhjca7rC.js} +3 -3
  260. package/{tool-B2nnkwNU.js.map → tool-Dhjca7rC.js.map} +1 -1
  261. package/{tool_call-BxL3eU1k.js → tool_call-Cyi0hUUc.js} +4 -4
  262. package/{tool_call-BxL3eU1k.js.map → tool_call-Cyi0hUUc.js.map} +1 -1
  263. package/{tool_call-B3MOog2R.mjs → tool_call-D_k36aI4.mjs} +4 -4
  264. package/{tool_call-B3MOog2R.mjs.map → tool_call-D_k36aI4.mjs.map} +1 -1
  265. package/{tool_registry-BaLUIzWz.mjs → tool_registry-CZ55mIti.mjs} +152 -143
  266. package/tool_registry-CZ55mIti.mjs.map +1 -0
  267. package/{tool_registry-BdKlPuHS.js → tool_registry-DwZ6pzN4.js} +151 -142
  268. package/tool_registry-DwZ6pzN4.js.map +1 -0
  269. package/{turn_runner-M2I8G2ok.js → turn_runner-CCZcsoDU.js} +5 -5
  270. package/{turn_runner-M2I8G2ok.js.map → turn_runner-CCZcsoDU.js.map} +1 -1
  271. package/{turn_runner-BV4BaZK9.mjs → turn_runner-DRPpVvsd.mjs} +5 -5
  272. package/{turn_runner-BV4BaZK9.mjs.map → turn_runner-DRPpVvsd.mjs.map} +1 -1
  273. package/turn_runner.cjs +1 -1
  274. package/turn_runner.mjs +1 -1
  275. package/{validate-JOHfh-BB.mjs → validate-C_hTnDBE.mjs} +95 -8
  276. package/validate-C_hTnDBE.mjs.map +1 -0
  277. package/{validate-DgDZkUKs.js → validate-gaSa9bsk.js} +95 -8
  278. package/validate-gaSa9bsk.js.map +1 -0
  279. package/xlsx-B0sTpEC2.js +30615 -0
  280. package/xlsx-B0sTpEC2.js.map +1 -0
  281. package/xlsx-DiMpn_Xv.mjs +30596 -0
  282. package/xlsx-DiMpn_Xv.mjs.map +1 -0
  283. package/xlsx.zahl-D2_Q-Xs4.mjs +6 -0
  284. package/xlsx.zahl-D2_Q-Xs4.mjs.map +1 -0
  285. package/xlsx.zahl-ZIcUQVv8.js +7 -0
  286. package/xlsx.zahl-ZIcUQVv8.js.map +1 -0
  287. package/tool_registry-BaLUIzWz.mjs.map +0 -1
  288. package/tool_registry-BdKlPuHS.js.map +0 -1
  289. package/validate-DgDZkUKs.js.map +0 -1
  290. package/validate-JOHfh-BB.mjs.map +0 -1
@@ -1,8 +1,9 @@
1
- import { c as isObject, o as isError, s as isInstanceOf } from "../tool_registry-BaLUIzWz.mjs";
1
+ import { c as isObject, o as isError, s as isInstanceOf } from "../tool_registry-CZ55mIti.mjs";
2
2
  import "../guards.mjs";
3
- import { PCM_MIME, bytesToPcm, implementsMediaEngine, pcmToBytes } from "./media/contracts.mjs";
3
+ import { EMPTY_MIME, PCM_MIME, bytesToPcm, implementsMediaEngine, pcmToBytes } from "./media/contracts.mjs";
4
4
  import { a as E_MEDIA_NOT_PIPE_EXPRESSIBLE, c as E_MEDIA_STEP_UNAVAILABLE, d as E_MEDIA_UNSUPPORTED_OP, i as E_MEDIA_MISSING_ARG, l as E_MEDIA_UNKNOWN_ARG, n as E_MEDIA_BAD_ARG, o as E_MEDIA_PIPE_SYNTAX, r as E_MEDIA_ENGINE_REQUIRED, s as E_MEDIA_STEP_FAILED, t as E_INVALID_MEDIA_PIPELINE_CONFIG, u as E_MEDIA_UNKNOWN_VERB } from "../exceptions-BLTn4Ofs.mjs";
5
- import { a as VERBS, c as suggestVerbs, d as isMediaRef, f as isRegExpRef, i as FOLDED_VERBS, l as canonicalFlags, m as toPipe, n as validateOps, o as VERB_INDEX, p as toOps, r as validateSegments, s as foldVerb, t as availableVerbs, u as fromOps } from "../validate-JOHfh-BB.mjs";
5
+ import { a as VERBS, c as suggestVerbs, d as isMediaRef, f as isRegExpRef, i as FOLDED_VERBS, l as canonicalFlags, m as toPipe, n as validateOps, o as VERB_INDEX, p as toOps, r as validateSegments, s as foldVerb, t as availableVerbs, u as fromOps } from "../validate-C_hTnDBE.mjs";
6
+ import { a as replaceExtension, i as familyOf, n as MIME, o as unsupportedForMutationReason, r as SPREADSHEET_MIMES, t as EXT_TO_MIME } from "../formats-CCylUHZw.mjs";
6
7
  import { validator } from "@nhtio/validation";
7
8
  import { Middleware } from "@nhtio/middleware";
8
9
  import moo from "moo";
@@ -45,7 +46,7 @@ var lexer = moo.compile({
45
46
  pipe: "|",
46
47
  eq: "=",
47
48
  comma: ",",
48
- ref: /@[A-Za-z0-9_-]+/,
49
+ ref: /@[A-Za-z0-9:_-]+/,
49
50
  regex: /\/(?:\\.|\[(?:\\.|[^\]\\\n])*\]|[^/\\[\n])+\/[a-z]*/,
50
51
  dstring: /"(?:\\.|[^"\\\n])*"/,
51
52
  sstring: /'(?:\\.|[^'\\\n])*'/,
@@ -84,7 +85,7 @@ var spanOf = (tok, length) => ({
84
85
  length: length ?? tok.text.length
85
86
  });
86
87
  var unquote = (raw) => raw.slice(1, -1).replace(/\\n/g, "\n").replace(/\\t/g, " ").replace(/\\(["'\\/])/g, "$1");
87
- var fail$5 = (tok, message, exemplar) => {
88
+ var fail$6 = (tok, message, exemplar) => {
88
89
  throw new E_MEDIA_PIPE_SYNTAX([`${message}${tok ? ` at line ${tok.line}, col ${tok.col}` : " at end of input"}. Write it like: ${exemplar}`]);
89
90
  };
90
91
  var Parser = class {
@@ -101,19 +102,19 @@ var Parser = class {
101
102
  }
102
103
  parsePipeline() {
103
104
  const segments = [];
104
- if (this.#toks.length === 0) fail$5(void 0, "empty pipe expression", "extract text | chunk by=sentence");
105
+ if (this.#toks.length === 0) fail$6(void 0, "empty pipe expression", "extract text | chunk by=sentence");
105
106
  segments.push(this.#parseSegment());
106
107
  while (this.#peek()?.type === "pipe") {
107
108
  this.#next();
108
109
  segments.push(this.#parseSegment());
109
110
  }
110
111
  const trailing = this.#peek();
111
- if (trailing) fail$5(trailing, `unexpected "${trailing.text}" after a complete segment`, "segment | segment (segments are separated by |)");
112
+ if (trailing) fail$6(trailing, `unexpected "${trailing.text}" after a complete segment`, "segment | segment (segments are separated by |)");
112
113
  return segments;
113
114
  }
114
115
  #parseSegment() {
115
116
  const first = this.#peek();
116
- if (!first || first.type !== "ident") fail$5(first, "expected a verb to start the segment", "convert to=pdf");
117
+ if (!first || first.type !== "ident") fail$6(first, "expected a verb to start the segment", "convert to=pdf");
117
118
  const head = this.#next();
118
119
  const collected = [head.value];
119
120
  const posAfterWord = [this.#pos];
@@ -136,12 +137,12 @@ var Parser = class {
136
137
  for (;;) {
137
138
  const tok = this.#peek();
138
139
  if (!tok || tok.type === "pipe") break;
139
- if (tok.type === "dash") fail$5(tok, "unexpected \"-\" — values containing dashes must be quoted", `${verbText} name="value-with-dashes"`);
140
- if (tok.type !== "ident" || this.#peek(1)?.type !== "eq") fail$5(tok, `unexpected "${tok.text}" — args must be name=value`, `${verbText} name=value`);
140
+ if (tok.type === "dash") fail$6(tok, "unexpected \"-\" — values containing dashes must be quoted", `${verbText} name="value-with-dashes"`);
141
+ if (tok.type !== "ident" || this.#peek(1)?.type !== "eq") fail$6(tok, `unexpected "${tok.text}" — args must be name=value`, `${verbText} name=value`);
141
142
  const name = this.#next().value;
142
143
  this.#next();
143
144
  const value = this.#parseValue(verbText, name);
144
- if (args.has(name)) fail$5(tok, `duplicate arg "${name}"`, `${verbText} ${name}=value (give each arg once)`);
145
+ if (args.has(name)) fail$6(tok, `duplicate arg "${name}"`, `${verbText} ${name}=value (give each arg once)`);
145
146
  args.set(name, value);
146
147
  }
147
148
  return {
@@ -170,7 +171,7 @@ var Parser = class {
170
171
  }
171
172
  #parseScalar(verbText, argName) {
172
173
  const tok = this.#peek();
173
- if (!tok) fail$5(tok, `missing value for "${argName}"`, `${verbText} ${argName}=value`);
174
+ if (!tok) fail$6(tok, `missing value for "${argName}"`, `${verbText} ${argName}=value`);
174
175
  const t = tok;
175
176
  switch (t.type) {
176
177
  case "int":
@@ -190,7 +191,7 @@ var Parser = class {
190
191
  case "range": {
191
192
  this.#next();
192
193
  const [lo, hi] = t.value.split("-").map(Number);
193
- if (lo > hi) fail$5(t, `range ${t.value} is descending (start must be ≤ end)`, `${argName}=${hi}-${lo}`);
194
+ if (lo > hi) fail$6(t, `range ${t.value} is descending (start must be ≤ end)`, `${argName}=${hi}-${lo}`);
194
195
  const nums = [];
195
196
  for (let n = lo; n <= hi; n++) nums.push(n);
196
197
  return {
@@ -233,7 +234,7 @@ var Parser = class {
233
234
  new RegExp(source, flags);
234
235
  } catch (err) {
235
236
  const detail = isError(err) ? err.message : String(err);
236
- fail$5(t, `invalid regex ${t.text}: ${detail}`, `${argName}=/pattern/flags`);
237
+ fail$6(t, `invalid regex ${t.text}: ${detail}`, `${argName}=/pattern/flags`);
237
238
  }
238
239
  return {
239
240
  value: {
@@ -255,9 +256,9 @@ var Parser = class {
255
256
  span: spanOf(t)
256
257
  };
257
258
  case "dash":
258
- fail$5(t, "unexpected \"-\" in a bare value", `${argName}="value-with-dashes" (quote values containing dashes)`);
259
+ fail$6(t, "unexpected \"-\" in a bare value", `${argName}="value-with-dashes" (quote values containing dashes)`);
259
260
  break;
260
- default: fail$5(t, `unexpected "${t.text}"`, `${verbText} ${argName}=value`);
261
+ default: fail$6(t, `unexpected "${t.text}"`, `${verbText} ${argName}=value`);
261
262
  }
262
263
  throw new E_MEDIA_PIPE_SYNTAX(["internal parser error"]);
263
264
  }
@@ -795,137 +796,255 @@ var materializedName = (filename) => {
795
796
  /** Convenience: read a step arg with a typed cast (validation already ran). */
796
797
  var argOf = (step, name) => step.args[name];
797
798
  //#endregion
798
- //#region src/batteries/media/formats.ts
799
- /** Well-known MIME constants used across the battery. */
800
- var MIME = {
801
- DOCX: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
802
- XLSX: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
803
- PPTX: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
804
- ODT: "application/vnd.oasis.opendocument.text",
805
- ODS: "application/vnd.oasis.opendocument.spreadsheet",
806
- ODP: "application/vnd.oasis.opendocument.presentation",
807
- PDF: "application/pdf",
808
- DOC: "application/msword",
809
- XLS: "application/vnd.ms-excel",
810
- PPT: "application/vnd.ms-powerpoint",
811
- PAGES: "application/x-iwork-pages-sffpages",
812
- NUMBERS: "application/x-iwork-numbers-sffnumbers",
813
- KEYNOTE: "application/x-iwork-keynote-sffkey",
814
- TXT: "text/plain",
815
- MD: "text/markdown",
816
- CSV: "text/csv",
817
- HTML: "text/html",
818
- JSON: "application/json",
819
- PNG: "image/png",
820
- JPEG: "image/jpeg",
821
- WEBP: "image/webp",
822
- TIFF: "image/tiff",
823
- AVIF: "image/avif",
824
- WAV: "audio/wav",
825
- MP3: "audio/mpeg"
826
- };
827
- /** Legacy Office MIME types (extraction only — mutation is rejected). */
828
- var LEGACY_OFFICE_MIMES = new Set([
829
- MIME.DOC,
830
- MIME.XLS,
831
- MIME.PPT
832
- ]);
833
- /** Apple iWork MIME types (extraction only — mutation is rejected). */
834
- var IWORK_MIMES = new Set([
835
- MIME.PAGES,
836
- MIME.NUMBERS,
837
- MIME.KEYNOTE
838
- ]);
839
- var SPREADSHEET_MIMES = new Set([
840
- MIME.XLSX,
841
- MIME.ODS,
842
- MIME.XLS,
843
- MIME.CSV
844
- ]);
845
- var PRESENTATION_MIMES = new Set([
846
- MIME.PPTX,
847
- MIME.ODP,
848
- MIME.PPT,
849
- MIME.KEYNOTE
850
- ]);
851
- var DOCUMENT_MIMES = new Set([
852
- MIME.PDF,
853
- MIME.DOCX,
854
- MIME.ODT,
855
- MIME.DOC,
856
- MIME.PAGES,
857
- MIME.TXT,
858
- MIME.MD,
859
- MIME.HTML,
860
- MIME.JSON,
861
- "application/rtf",
862
- "text/rtf"
863
- ]);
799
+ //#region src/batteries/media/steps/patch.ts
800
+ var PATCH_PREFIX = "*** Begin Patch";
801
+ var PATCH_SUFFIX = "*** End Patch";
802
+ var ADD_FILE_PREFIX = "*** Add File:";
803
+ var DELETE_FILE_PREFIX = "*** Delete File:";
804
+ var UPDATE_FILE_PREFIX = "*** Update File:";
805
+ var MOVE_TO_PREFIX = "*** Move to:";
806
+ /** `true` when `patch` is the structured envelope rather than a unified diff. */
807
+ var isStructuredPatch = (patch) => patch.trimStart().startsWith(PATCH_PREFIX);
808
+ /** Normalize a workspace path: relative, no `.`/`..`/empty segments, forward slashes. */
809
+ var normalizeWorkspacePath = (path) => {
810
+ const normalized = path.replace(/\\/g, "/").trim();
811
+ if (!normalized) throw new Error("apply_patch path cannot be empty");
812
+ if (normalized.startsWith("/") || /^[A-Za-z]:/.test(normalized)) throw new Error(`apply_patch path "${path}" must be relative to the workspace root`);
813
+ const segments = normalized.split("/");
814
+ const sanitizedSegments = [];
815
+ for (const segment of segments) {
816
+ if (!segment || segment === "." || segment === "..") throw new Error(`apply_patch path "${path}" contains invalid segment "${segment || "(empty)"}"`);
817
+ sanitizedSegments.push(segment);
818
+ }
819
+ return sanitizedSegments.join("/");
820
+ };
864
821
  /**
865
- * Classify a MIME type into the verb table's broad format family.
822
+ * Parse a structured `*** Begin Patch` envelope.
866
823
  *
867
- * @param mimeType - The media MIME type.
868
- * @returns The family used by verb-applicability checks.
824
+ * @param patch - The raw patch text.
825
+ * @returns The parsed operations.
869
826
  */
870
- var familyOf = (mimeType) => {
871
- const mime = mimeType.toLowerCase().split(";")[0].trim();
872
- if (SPREADSHEET_MIMES.has(mime)) return "spreadsheet";
873
- if (PRESENTATION_MIMES.has(mime)) return "presentation";
874
- if (DOCUMENT_MIMES.has(mime)) return "document";
875
- if (mime.startsWith("image/")) return "image";
876
- if (mime.startsWith("audio/")) return "audio";
877
- if (mime.startsWith("text/")) return "document";
878
- return "document";
827
+ var parseStructuredPatch = (patch) => {
828
+ const lines = patch.replace(/\r\n/g, "\n").split("\n");
829
+ if (lines[0]?.trim() !== PATCH_PREFIX) throw new Error("a structured patch must start with \"*** Begin Patch\"");
830
+ const lastNonEmptyIndex = [...lines].reverse().findIndex((line) => line.trim() !== "");
831
+ const endIndex = lastNonEmptyIndex === -1 ? -1 : lines.length - 1 - lastNonEmptyIndex;
832
+ if (endIndex < 0 || lines[endIndex]?.trim() !== PATCH_SUFFIX) throw new Error("a structured patch must end with \"*** End Patch\"");
833
+ const body = lines.slice(1, endIndex);
834
+ const operations = [];
835
+ let totalAdded = 0;
836
+ let totalRemoved = 0;
837
+ let i = 0;
838
+ while (i < body.length) {
839
+ const line = body[i] ?? "";
840
+ if (line.trim() === "" || line.startsWith("*** End of File")) {
841
+ i += 1;
842
+ continue;
843
+ }
844
+ if (line.startsWith(ADD_FILE_PREFIX)) {
845
+ const path = normalizeWorkspacePath(line.slice(13).trim());
846
+ i += 1;
847
+ const contentLines = [];
848
+ while (i < body.length) {
849
+ const next = body[i] ?? "";
850
+ if (next.startsWith("*** ")) break;
851
+ if (!next.startsWith("+")) throw new Error(`apply_patch add-file line must start with "+": "${next}"`);
852
+ contentLines.push(next.slice(1));
853
+ i += 1;
854
+ }
855
+ operations.push({
856
+ type: "add",
857
+ path,
858
+ content: contentLines.join("\n"),
859
+ added: contentLines.length
860
+ });
861
+ totalAdded += contentLines.length;
862
+ continue;
863
+ }
864
+ if (line.startsWith(DELETE_FILE_PREFIX)) {
865
+ const path = normalizeWorkspacePath(line.slice(16).trim());
866
+ operations.push({
867
+ type: "delete",
868
+ path
869
+ });
870
+ i += 1;
871
+ continue;
872
+ }
873
+ if (!line.startsWith(UPDATE_FILE_PREFIX)) throw new Error(`apply_patch invalid structured patch header: "${line}"`);
874
+ const path = normalizeWorkspacePath(line.slice(16).trim());
875
+ i += 1;
876
+ let movePath;
877
+ if ((body[i] ?? "").startsWith(MOVE_TO_PREFIX)) {
878
+ movePath = normalizeWorkspacePath((body[i] ?? "").slice(12).trim());
879
+ i += 1;
880
+ }
881
+ const hunks = [];
882
+ let opAdded = 0;
883
+ let opRemoved = 0;
884
+ while (i < body.length && (body[i] ?? "").startsWith("@@")) {
885
+ i += 1;
886
+ const hunkLines = [];
887
+ while (i < body.length) {
888
+ const next = body[i] ?? "";
889
+ if (next.startsWith("@@") || next.startsWith("*** ")) break;
890
+ hunkLines.push(next);
891
+ i += 1;
892
+ }
893
+ if (hunkLines.length === 0) throw new Error("apply_patch contains an empty hunk");
894
+ const oldLines = [];
895
+ const newLines = [];
896
+ let added = 0;
897
+ let removed = 0;
898
+ for (const hunkLine of hunkLines) if (hunkLine.startsWith("+")) {
899
+ newLines.push(hunkLine.slice(1));
900
+ added += 1;
901
+ } else if (hunkLine.startsWith("-")) {
902
+ oldLines.push(hunkLine.slice(1));
903
+ removed += 1;
904
+ } else if (hunkLine.startsWith(" ")) {
905
+ const contextLine = hunkLine.slice(1);
906
+ oldLines.push(contextLine);
907
+ newLines.push(contextLine);
908
+ } else throw new Error(`apply_patch invalid hunk line (must start with +, -, or space): "${hunkLine}"`);
909
+ if (added === 0 && removed === 0) throw new Error("apply_patch hunk must contain at least one added or removed line");
910
+ opAdded += added;
911
+ opRemoved += removed;
912
+ hunks.push({
913
+ oldLines,
914
+ newLines,
915
+ added,
916
+ removed
917
+ });
918
+ }
919
+ if (hunks.length === 0) throw new Error(`apply_patch update operation for "${path}" must contain at least one hunk`);
920
+ operations.push({
921
+ type: "update",
922
+ path,
923
+ movePath,
924
+ hunks,
925
+ added: opAdded,
926
+ removed: opRemoved
927
+ });
928
+ totalAdded += opAdded;
929
+ totalRemoved += opRemoved;
930
+ }
931
+ if (operations.length === 0) throw new Error("apply_patch contains no operations");
932
+ return {
933
+ operations,
934
+ added: totalAdded,
935
+ removed: totalRemoved
936
+ };
937
+ };
938
+ var countSequenceMatches = (haystack, needle, start) => {
939
+ if (needle.length === 0) return 0;
940
+ let matches = 0;
941
+ let i = start;
942
+ while (i <= haystack.length - needle.length) {
943
+ let matched = true;
944
+ let j = 0;
945
+ while (j < needle.length) {
946
+ if (haystack[i + j] !== needle[j]) {
947
+ matched = false;
948
+ break;
949
+ }
950
+ j += 1;
951
+ }
952
+ if (matched) matches += 1;
953
+ i += 1;
954
+ }
955
+ return matches;
956
+ };
957
+ var findExactSequence = (haystack, needle, start) => {
958
+ if (needle.length === 0) return start;
959
+ let i = start;
960
+ while (i <= haystack.length - needle.length) {
961
+ let matched = true;
962
+ let j = 0;
963
+ while (j < needle.length) {
964
+ if (haystack[i + j] !== needle[j]) {
965
+ matched = false;
966
+ break;
967
+ }
968
+ j += 1;
969
+ }
970
+ if (matched) return i;
971
+ i += 1;
972
+ }
973
+ return -1;
879
974
  };
880
975
  /**
881
- * Reason a mutation verb cannot run against this MIME type, or `undefined` when mutation is
882
- * allowed. Returns a reason string (not a throw) so callers compose model-actionable failures.
976
+ * Apply an update operation's hunks to `inputText`. Context matching is exact and rejects
977
+ * ambiguity: a hunk whose old-lines match more than one location past the cursor fails
978
+ * rather than guessing.
883
979
  *
884
- * @param mimeType - The media MIME type.
885
- * @returns A human-readable reason, or `undefined` when mutation is supported.
980
+ * @param inputText - The file's current text.
981
+ * @param hunks - The parsed hunks, in order.
982
+ * @returns The patched text.
886
983
  */
887
- var unsupportedForMutationReason = (mimeType) => {
888
- const mime = mimeType.toLowerCase().split(";")[0].trim();
889
- if (LEGACY_OFFICE_MIMES.has(mime)) return `legacy Office format (${mime}) supports extraction only — convert it first (e.g. convert to=docx)`;
890
- if (IWORK_MIMES.has(mime)) return `Apple iWork format (${mime}) supports extraction only`;
891
- };
892
- /** A small extension → MIME lookup for filenames produced by transforms. */
893
- var EXT_TO_MIME = {
894
- pdf: MIME.PDF,
895
- docx: MIME.DOCX,
896
- xlsx: MIME.XLSX,
897
- pptx: MIME.PPTX,
898
- odt: MIME.ODT,
899
- ods: MIME.ODS,
900
- odp: MIME.ODP,
901
- doc: MIME.DOC,
902
- xls: MIME.XLS,
903
- ppt: MIME.PPT,
904
- txt: MIME.TXT,
905
- md: MIME.MD,
906
- csv: MIME.CSV,
907
- html: MIME.HTML,
908
- json: MIME.JSON,
909
- rtf: "application/rtf",
910
- png: MIME.PNG,
911
- jpg: MIME.JPEG,
912
- jpeg: MIME.JPEG,
913
- webp: MIME.WEBP,
914
- tiff: MIME.TIFF,
915
- avif: MIME.AVIF,
916
- wav: MIME.WAV,
917
- mp3: MIME.MP3
984
+ var applyUpdateHunks = (inputText, hunks) => {
985
+ const lines = inputText.replace(/\r\n/g, "\n").split("\n");
986
+ let cursor = 0;
987
+ for (const hunk of hunks) {
988
+ if (countSequenceMatches(lines, hunk.oldLines, cursor) > 1) throw new Error("patch context is ambiguous and matches multiple locations");
989
+ const start = findExactSequence(lines, hunk.oldLines, cursor);
990
+ if (start === -1) throw new Error("the patch could not be applied cleanly to the source text");
991
+ lines.splice(start, hunk.oldLines.length, ...hunk.newLines);
992
+ cursor = start + hunk.newLines.length;
993
+ }
994
+ return lines.join("\n");
918
995
  };
919
996
  /**
920
- * Replace (or add) a filename's extension.
997
+ * Apply a parsed structured patch to a virtual workspace of files keyed by normalized path.
921
998
  *
922
- * @param filename - The original filename.
923
- * @param ext - The new extension, without the dot.
924
- * @returns The filename with the new extension.
999
+ * @param files - The workspace (mutated in place).
1000
+ * @param patch - The parsed envelope.
1001
+ * @returns The workspace and the number of files touched.
925
1002
  */
926
- var replaceExtension = (filename, ext) => {
927
- const dot = filename.lastIndexOf(".");
928
- return `${dot > 0 ? filename.slice(0, dot) : filename}.${ext}`;
1003
+ var applyOperations = (files, patch) => {
1004
+ let modifiedFiles = 0;
1005
+ for (const operation of patch.operations) {
1006
+ if (operation.type === "add") {
1007
+ if (files.has(operation.path)) throw new Error(`cannot add file "${operation.path}": the path already exists`);
1008
+ files.set(operation.path, {
1009
+ text: operation.content,
1010
+ mimeType: inferTextMimeFromPath(operation.path)
1011
+ });
1012
+ modifiedFiles += 1;
1013
+ continue;
1014
+ }
1015
+ if (operation.type === "delete") {
1016
+ if (!files.has(operation.path)) throw new Error(`cannot delete file "${operation.path}": the path does not exist`);
1017
+ files.delete(operation.path);
1018
+ modifiedFiles += 1;
1019
+ continue;
1020
+ }
1021
+ const current = files.get(operation.path);
1022
+ if (!current) throw new Error(`cannot update file "${operation.path}": the path does not exist`);
1023
+ const updatedText = applyUpdateHunks(current.text, operation.hunks);
1024
+ const targetPath = operation.movePath ?? operation.path;
1025
+ if (operation.movePath && files.has(targetPath)) throw new Error(`cannot move file "${operation.path}" to "${targetPath}": the target already exists`);
1026
+ files.delete(operation.path);
1027
+ files.set(targetPath, {
1028
+ text: updatedText,
1029
+ mimeType: current.mimeType
1030
+ });
1031
+ modifiedFiles += 1;
1032
+ }
1033
+ return {
1034
+ files,
1035
+ modifiedFiles
1036
+ };
1037
+ };
1038
+ /** Infer a text MIME from a workspace path's extension (Add File outputs). */
1039
+ var inferTextMimeFromPath = (path) => {
1040
+ const dot = path.lastIndexOf(".");
1041
+ const ext = dot > 0 ? path.slice(dot + 1).toLowerCase() : "";
1042
+ if (ext === "json") return "application/json";
1043
+ if (ext === "md" || ext === "markdown") return "text/markdown";
1044
+ if (ext === "csv") return "text/csv";
1045
+ if (ext === "yaml" || ext === "yml") return "application/yaml";
1046
+ if (ext === "html" || ext === "htm") return "text/html";
1047
+ return "text/plain";
929
1048
  };
930
1049
  //#endregion
931
1050
  //#region src/batteries/media/steps/text.ts
@@ -996,18 +1115,18 @@ var splitFixed = (text, chunkSize, overlap) => {
996
1115
  }
997
1116
  return chunks;
998
1117
  };
999
- var decoder = new TextDecoder("utf-8", { fatal: false });
1000
- var encoder = new TextEncoder();
1118
+ var decoder$1 = new TextDecoder("utf-8", { fatal: false });
1119
+ var encoder$1 = new TextEncoder();
1001
1120
  /** Decode payload bytes as UTF-8 text (UTF-16 BOM aware). */
1002
1121
  var decodeText = (bytes) => {
1003
1122
  if (bytes.length >= 2) {
1004
1123
  if (bytes[0] === 255 && bytes[1] === 254) return new TextDecoder("utf-16le").decode(bytes.subarray(2));
1005
1124
  if (bytes[0] === 254 && bytes[1] === 255) return new TextDecoder("utf-16be").decode(bytes.subarray(2));
1006
1125
  }
1007
- return decoder.decode(bytes).replace(/\r\n?/g, "\n");
1126
+ return decoder$1.decode(bytes).replace(/\r\n?/g, "\n");
1008
1127
  };
1009
1128
  var textPayload = (source, text, suffix) => ({
1010
- bytes: encoder.encode(text),
1129
+ bytes: encoder$1.encode(text),
1011
1130
  mimeType: MIME.TXT,
1012
1131
  filename: replaceExtension(source.filename, suffix)
1013
1132
  });
@@ -1091,7 +1210,7 @@ var updateTextStep = async (ctx) => {
1091
1210
  kind: "media",
1092
1211
  payload: {
1093
1212
  ...ctx.payload,
1094
- bytes: encoder.encode(updated)
1213
+ bytes: encoder$1.encode(updated)
1095
1214
  }
1096
1215
  };
1097
1216
  };
@@ -1121,9 +1240,13 @@ var diffStep = async (ctx) => {
1121
1240
  asText: patch
1122
1241
  };
1123
1242
  };
1124
- /** `apply_patch` — apply a unified diff to the media text. */
1243
+ /**
1244
+ * `apply_patch` — apply a unified diff, or a structured `*** Begin Patch` envelope
1245
+ * (multi-file Add/Delete/Update/Move — the GitHub Copilot apply_patch dialect).
1246
+ */
1125
1247
  var applyPatchStep = async (ctx) => {
1126
1248
  const patch = argOf(ctx.step, "patch");
1249
+ if (isStructuredPatch(patch)) return applyStructuredPatch(ctx, patch);
1127
1250
  const text = decodeText(ctx.payload.bytes);
1128
1251
  const result = (await import("diff")).applyPatch(text, patch);
1129
1252
  if (result === false) throw new E_MEDIA_STEP_FAILED(["apply_patch", "the patch does not apply to this media content (context mismatch)"]);
@@ -1131,30 +1254,86 @@ var applyPatchStep = async (ctx) => {
1131
1254
  kind: "media",
1132
1255
  payload: {
1133
1256
  ...ctx.payload,
1134
- bytes: encoder.encode(result)
1257
+ bytes: encoder$1.encode(result)
1135
1258
  }
1136
1259
  };
1137
1260
  };
1261
+ /** The structured-envelope path: primary media + `with=@refs` form a virtual workspace. */
1262
+ var applyStructuredPatch = async (ctx, patch) => {
1263
+ const verb = "apply_patch";
1264
+ const fail = (message) => {
1265
+ throw new E_MEDIA_STEP_FAILED([verb, message]);
1266
+ };
1267
+ const files = /* @__PURE__ */ new Map();
1268
+ const addToWorkspace = (payload) => {
1269
+ let path;
1270
+ try {
1271
+ path = normalizeWorkspacePath(payload.filename);
1272
+ } catch (err) {
1273
+ fail(isError(err) ? err.message : String(err));
1274
+ throw err;
1275
+ }
1276
+ if (files.has(path)) fail(`duplicate workspace path in inputs: "${path}"`);
1277
+ files.set(path, {
1278
+ text: decodeText(payload.bytes),
1279
+ mimeType: payload.mimeType
1280
+ });
1281
+ };
1282
+ addToWorkspace(ctx.payload);
1283
+ const raw = ctx.step.args.with;
1284
+ if (raw !== void 0) {
1285
+ const refs = Array.isArray(raw) ? raw : [raw];
1286
+ for (const ref of refs) {
1287
+ if (ref.kind !== "id") fail("builder refs are not yet supported here");
1288
+ addToWorkspace(await ctx.resolveRef(ref.id));
1289
+ }
1290
+ }
1291
+ let parsed;
1292
+ let applied;
1293
+ try {
1294
+ parsed = parseStructuredPatch(patch);
1295
+ applied = applyOperations(files, parsed);
1296
+ } catch (err) {
1297
+ fail(isError(err) ? err.message : String(err));
1298
+ throw err;
1299
+ }
1300
+ const payloads = [...applied.files.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([path, file]) => ({
1301
+ bytes: encoder$1.encode(file.text),
1302
+ mimeType: file.mimeType,
1303
+ filename: path
1304
+ }));
1305
+ if (payloads.length === 0) fail("the patch deleted every file in the workspace");
1306
+ if (payloads.length === 1) return {
1307
+ kind: "media",
1308
+ payload: payloads[0]
1309
+ };
1310
+ return {
1311
+ kind: "media-list",
1312
+ payloads
1313
+ };
1314
+ };
1138
1315
  //#endregion
1139
1316
  //#region src/batteries/media/steps/doc.ts
1140
1317
  /**
1141
- * Doc-domain step extensions: format-preserving text mutation for DOCX/PPTX, asset
1142
- * extraction from OOXML/ODF archives and PDFs, and format conversion via the convert engine.
1318
+ * Doc-domain step extensions: format-preserving text mutation for DOCX/PPTX/ODF, PDF visual
1319
+ * redaction, asset extraction from OOXML/ODF archives and PDFs, and format conversion via the
1320
+ * convert engine.
1143
1321
  *
1144
1322
  * @remarks
1145
1323
  * Internal sibling of the `@nhtio/adk/batteries/media` entry. Ported from the source server's
1146
1324
  * doc adapters; the format-dispatch contract follows the server's green e2e suite: DOCX and
1147
1325
  * PPTX redact/sanitize/normalize/update_text mutate text in place inside the container
1148
- * (preserving the source format); text-like inputs mutate as text; PDF redact falls back to
1149
- * text extraction (the server's PDF "visual annotation" path is content-stream-preserving and
1150
- * out of scope here — the failure message says exactly that).
1326
+ * (preserving the source format); ODT/ODS/ODP redact/update_text mutate `content.xml` the
1327
+ * same way; text-like inputs mutate as text. PDF redact is VISUAL (pdf-lib draw-over +
1328
+ * metadata strip — content streams keep the text); the result carries that warning verbatim
1329
+ * because it is a trust boundary, not a footnote.
1151
1330
  */
1152
1331
  var zipPromise$2;
1153
1332
  var jszip$2 = () => {
1154
1333
  zipPromise$2 ??= import("jszip").then((m) => "default" in m ? m.default : m);
1155
1334
  return zipPromise$2;
1156
1335
  };
1157
- var fail$4 = (verb, message) => {
1336
+ var fail$5 = (verb, message) => {
1158
1337
  throw new E_MEDIA_STEP_FAILED([verb, message]);
1159
1338
  };
1160
1339
  var escapeXml$1 = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
@@ -1206,11 +1385,11 @@ var mutateOoxmlText = async (ctx, verb, mutateXml) => {
1206
1385
  try {
1207
1386
  zip = await JSZip.loadAsync(ctx.payload.bytes);
1208
1387
  } catch (err) {
1209
- fail$4(verb, `could not open the document container: ${isError(err) ? err.message : String(err)}`);
1388
+ fail$5(verb, `could not open the document container: ${isError(err) ? err.message : String(err)}`);
1210
1389
  throw err;
1211
1390
  }
1212
1391
  const parts = kind === "docx" ? Object.keys(zip.files).filter((n) => /^word\/(document|header\d*|footer\d*)\.xml$/.test(n)) : Object.keys(zip.files).filter((n) => /^ppt\/slides\/slide\d+\.xml$/.test(n));
1213
- if (parts.length === 0) fail$4(verb, "the container has no text parts to mutate (corrupt file?)");
1392
+ if (parts.length === 0) fail$5(verb, "the container has no text parts to mutate (corrupt file?)");
1214
1393
  for (const part of parts) {
1215
1394
  const xml = await zip.file(part).async("text");
1216
1395
  const next = mutateXml(xml, kind);
@@ -1236,21 +1415,170 @@ var toGlobalRegex = (value) => {
1236
1415
  const ref = value;
1237
1416
  return new RegExp(ref.source, ref.flags.includes("g") ? ref.flags : `${ref.flags}g`);
1238
1417
  };
1239
- /** `redact` — format dispatch: text media → text path; DOCX/PPTX → in-place container edit. */
1418
+ var ODF_MIMES = new Set([
1419
+ MIME.ODT,
1420
+ MIME.ODS,
1421
+ MIME.ODP
1422
+ ]);
1423
+ /**
1424
+ * Replace matches inside the text nodes of ODF `content.xml`, aggregating per paragraph so
1425
+ * patterns spanning `<text:span>` formatting splits still match.
1426
+ */
1427
+ var replaceTextInContentXml = (xml, pattern, replacement) => {
1428
+ let totalMatches = 0;
1429
+ return {
1430
+ xml: xml.replace(/<text:(?:p|h)\b[^>]*>[\s\S]*?<\/text:(?:p|h)>/g, (paragraphXml) => {
1431
+ const textNodes = [];
1432
+ const textRegex = />([^<]+)</g;
1433
+ let match;
1434
+ while (match = textRegex.exec(paragraphXml)) {
1435
+ const content = unescapeXml(match[1]);
1436
+ if (content.trim() === "") continue;
1437
+ textNodes.push({
1438
+ content,
1439
+ start: match.index,
1440
+ end: match.index + match[0].length
1441
+ });
1442
+ }
1443
+ if (textNodes.length === 0) return paragraphXml;
1444
+ const aggregated = textNodes.map((n) => n.content).join("");
1445
+ const p = new RegExp(pattern.source, pattern.flags);
1446
+ const replaced = aggregated.replace(p, replacement);
1447
+ if (replaced === aggregated) return paragraphXml;
1448
+ const counter = new RegExp(pattern.source, pattern.flags);
1449
+ while (counter.exec(aggregated)) {
1450
+ totalMatches += 1;
1451
+ if (!counter.global) break;
1452
+ }
1453
+ let out = paragraphXml;
1454
+ for (let i = textNodes.length - 1; i >= 0; i--) {
1455
+ const node = textNodes[i];
1456
+ const newContent = i === 0 ? escapeXml$1(replaced) : "";
1457
+ out = out.slice(0, node.start) + `>${newContent}<` + out.slice(node.end);
1458
+ }
1459
+ return out;
1460
+ }),
1461
+ matchCount: totalMatches
1462
+ };
1463
+ };
1464
+ /** Map a `content.xml` mutation over an ODF container (ODT/ODS/ODP). */
1465
+ var mutateOdfText = async (ctx, verb, mutateXml) => {
1466
+ const JSZip = await jszip$2();
1467
+ let zip;
1468
+ try {
1469
+ zip = await JSZip.loadAsync(ctx.payload.bytes);
1470
+ } catch (err) {
1471
+ fail$5(verb, `could not open the document container: ${isError(err) ? err.message : String(err)}`);
1472
+ throw err;
1473
+ }
1474
+ const part = zip.file("content.xml");
1475
+ if (!part) fail$5(verb, "the ODF container has no content.xml (corrupt file?)");
1476
+ const xml = await part.async("text");
1477
+ const next = mutateXml(xml);
1478
+ if (next !== xml) zip.file("content.xml", next);
1479
+ const bytes = await zip.generateAsync({
1480
+ type: "uint8array",
1481
+ compression: "DEFLATE"
1482
+ });
1483
+ return {
1484
+ kind: "media",
1485
+ payload: {
1486
+ ...ctx.payload,
1487
+ bytes
1488
+ }
1489
+ };
1490
+ };
1491
+ /** Visual page-level redaction: draw-over banner on matching pages + metadata strip. */
1492
+ var redactPdf = async (ctx, verb, patterns) => {
1493
+ const { PDFDocument, PDFName, PDFString, rgb, StandardFonts } = await import("pdf-lib");
1494
+ let doc;
1495
+ try {
1496
+ doc = await PDFDocument.load(ctx.payload.bytes, { ignoreEncryption: true });
1497
+ } catch (err) {
1498
+ fail$5(verb, `could not parse the PDF: ${isError(err) ? err.message : String(err)}`);
1499
+ throw err;
1500
+ }
1501
+ let pageTexts = [];
1502
+ try {
1503
+ const { PDFParse } = await import("pdf-parse");
1504
+ pageTexts = (await new PDFParse({ data: ctx.payload.bytes }).getText()).pages.map((p) => p.text ?? "");
1505
+ } catch {
1506
+ pageTexts = [];
1507
+ }
1508
+ const pages = doc.getPages();
1509
+ const font = await doc.embedFont(StandardFonts.Helvetica);
1510
+ let pagesRedacted = 0;
1511
+ for (const [i, page] of pages.entries()) {
1512
+ const pageText = pageTexts[i] ?? "";
1513
+ if (!patterns.some((pattern) => new RegExp(pattern.source, pattern.flags).test(pageText))) continue;
1514
+ const { width } = page.getSize();
1515
+ page.drawRectangle({
1516
+ x: 0,
1517
+ y: 0,
1518
+ width,
1519
+ height: 14,
1520
+ color: rgb(1, 1, .9)
1521
+ });
1522
+ page.drawText(`[Page ${i + 1}: content redacted]`, {
1523
+ x: 4,
1524
+ y: 2,
1525
+ size: 8,
1526
+ font,
1527
+ color: rgb(.5, 0, 0)
1528
+ });
1529
+ pagesRedacted += 1;
1530
+ }
1531
+ for (const field of [
1532
+ "Title",
1533
+ "Author",
1534
+ "Subject",
1535
+ "Keywords",
1536
+ "Creator",
1537
+ "Producer"
1538
+ ]) try {
1539
+ const infoDict = doc.context.lookup(doc.context.trailerInfo.Info);
1540
+ if (infoDict && typeof infoDict.get === "function" && typeof infoDict.set === "function") {
1541
+ if (infoDict.get(PDFName.of(field))) infoDict.set(PDFName.of(field), PDFString.of(""));
1542
+ }
1543
+ } catch {}
1544
+ try {
1545
+ const catalog = doc.context.lookup(doc.context.trailerInfo.Root);
1546
+ if (catalog && typeof catalog.get === "function" && typeof catalog.delete === "function") {
1547
+ if (catalog.get(PDFName.of("Metadata"))) catalog.delete(PDFName.of("Metadata"));
1548
+ }
1549
+ } catch {}
1550
+ if (pagesRedacted === 0) fail$5(verb, "no page text matched the redaction pattern(s) — nothing was redacted");
1551
+ const bytes = new Uint8Array(await doc.save());
1552
+ return {
1553
+ kind: "media",
1554
+ payload: {
1555
+ ...ctx.payload,
1556
+ bytes
1557
+ }
1558
+ };
1559
+ };
1560
+ /**
1561
+ * `redact` — format dispatch: text media → text path; DOCX/PPTX/ODF → in-place container
1562
+ * edit; PDF → visual redaction (draw-over + metadata strip — see {@link PDF_REDACTION_WARNING}).
1563
+ */
1240
1564
  var docRedactStep = async (ctx) => {
1241
1565
  const mime = ctx.payload.mimeType.toLowerCase().split(";")[0].trim();
1242
1566
  if (mime.startsWith("text/")) return redactStep(ctx);
1243
- if (mime === MIME.DOCX || mime === MIME.PPTX) {
1244
- const raw = ctx.step.args.match;
1245
- const patterns = Array.isArray(raw) ? raw : [raw];
1246
- const replacement = argOf(ctx.step, "replace") ?? "█";
1247
- return mutateOoxmlText(ctx, "redact", (xml, kind) => {
1248
- let out = xml;
1249
- for (const p of patterns) out = replaceInOoxml(out, kind === "docx" ? "w:p" : "a:p", kind === "docx" ? "w:t" : "a:t", toGlobalRegex(p), replacement).xml;
1250
- return out;
1251
- });
1252
- }
1253
- fail$4("redact", `redaction for ${mime} is not supported in this build (text, DOCX, and PPTX are). For PDF, extract the text first: extract text | redact …`);
1567
+ const raw = ctx.step.args.match;
1568
+ const patterns = Array.isArray(raw) ? raw : [raw];
1569
+ const replacement = argOf(ctx.step, "replace") ?? "█";
1570
+ if (mime === MIME.DOCX || mime === MIME.PPTX) return mutateOoxmlText(ctx, "redact", (xml, kind) => {
1571
+ let out = xml;
1572
+ for (const p of patterns) out = replaceInOoxml(out, kind === "docx" ? "w:p" : "a:p", kind === "docx" ? "w:t" : "a:t", toGlobalRegex(p), replacement).xml;
1573
+ return out;
1574
+ });
1575
+ if (ODF_MIMES.has(mime)) return mutateOdfText(ctx, "redact", (xml) => {
1576
+ let out = xml;
1577
+ for (const p of patterns) out = replaceTextInContentXml(out, toGlobalRegex(p), replacement).xml;
1578
+ return out;
1579
+ });
1580
+ if (mime === MIME.PDF) return redactPdf(ctx, "redact", patterns.map(toGlobalRegex));
1581
+ fail$5("redact", `redaction for ${mime} is not supported in this build (text, DOCX, PPTX, ODT/ODS/ODP, and PDF are).`);
1254
1582
  throw new Error("unreachable");
1255
1583
  };
1256
1584
  var BLOCKED_CONTROL = (code) => code >= 0 && code <= 8 || code === 11 || code === 12 || code >= 14 && code <= 31 || code === 127;
@@ -1281,7 +1609,7 @@ var docSanitizeStep = async (ctx) => {
1281
1609
  };
1282
1610
  }
1283
1611
  if (mime === MIME.DOCX || mime === MIME.PPTX) return mutateOoxmlText(ctx, "sanitize", (xml, kind) => sanitizeTextNodes(xml, kind === "docx" ? "w:t" : "a:t"));
1284
- fail$4("sanitize", `sanitize for ${mime} is not supported in this build (text, DOCX, PPTX are)`);
1612
+ fail$5("sanitize", `sanitize for ${mime} is not supported in this build (text, DOCX, PPTX are)`);
1285
1613
  throw new Error("unreachable");
1286
1614
  };
1287
1615
  var normalizeText = (text) => text.replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/[\t ]+$/gm, "");
@@ -1306,28 +1634,38 @@ var docNormalizeStep = async (ctx) => {
1306
1634
  return full.replace(content, escapeXml$1(normalized));
1307
1635
  });
1308
1636
  });
1309
- fail$4("normalize", `normalize for ${mime} is not supported in this build (text, DOCX, PPTX are)`);
1637
+ fail$5("normalize", `normalize for ${mime} is not supported in this build (text, DOCX, PPTX are)`);
1310
1638
  throw new Error("unreachable");
1311
1639
  };
1312
- /** `update_text` — anchor replacement; DOCX/PPTX in-place, TARGET_NOT_FOUND when absent. */
1640
+ /** `update_text` — anchor replacement; DOCX/PPTX/ODF in-place, TARGET_NOT_FOUND when absent. */
1313
1641
  var docUpdateTextStep = async (ctx) => {
1314
1642
  const mime = ctx.payload.mimeType.toLowerCase().split(";")[0].trim();
1315
1643
  if (mime.startsWith("text/")) return updateTextStep(ctx);
1644
+ const anchor = argOf(ctx.step, "anchor");
1645
+ const replace = argOf(ctx.step, "replace") ?? "";
1646
+ const escapedAnchor = anchor.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1316
1647
  if (mime === MIME.DOCX || mime === MIME.PPTX) {
1317
- const anchor = argOf(ctx.step, "anchor");
1318
- const replace = argOf(ctx.step, "replace") ?? "";
1319
1648
  let found = 0;
1320
1649
  const result = await mutateOoxmlText(ctx, "update_text", (xml, kind) => {
1321
1650
  if (found > 0) return xml;
1322
- const escaped = anchor.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1323
- const { xml: next, matchCount } = replaceInOoxml(xml, kind === "docx" ? "w:p" : "a:p", kind === "docx" ? "w:t" : "a:t", new RegExp(escaped), replace);
1651
+ const { xml: next, matchCount } = replaceInOoxml(xml, kind === "docx" ? "w:p" : "a:p", kind === "docx" ? "w:t" : "a:t", new RegExp(escapedAnchor), replace);
1652
+ found += matchCount;
1653
+ return next;
1654
+ });
1655
+ if (found === 0) fail$5("update_text", `anchor text not found: "${anchor.slice(0, 80)}"`);
1656
+ return result;
1657
+ }
1658
+ if (ODF_MIMES.has(mime)) {
1659
+ let found = 0;
1660
+ const result = await mutateOdfText(ctx, "update_text", (xml) => {
1661
+ const { xml: next, matchCount } = replaceTextInContentXml(xml, new RegExp(escapedAnchor), replace);
1324
1662
  found += matchCount;
1325
1663
  return next;
1326
1664
  });
1327
- if (found === 0) fail$4("update_text", `anchor text not found: "${anchor.slice(0, 80)}"`);
1665
+ if (found === 0) fail$5("update_text", `anchor text not found: "${anchor.slice(0, 80)}"`);
1328
1666
  return result;
1329
1667
  }
1330
- fail$4("update_text", `text update for ${mime} is not supported (text, DOCX, PPTX are; PDF text is not reliably editable)`);
1668
+ fail$5("update_text", `text update for ${mime} is not supported (text, DOCX, PPTX, ODT/ODS/ODP are; PDF text is not reliably editable)`);
1331
1669
  throw new Error("unreachable");
1332
1670
  };
1333
1671
  var ASSET_PATTERNS = {
@@ -1363,8 +1701,8 @@ var extractAssetsStep = async (ctx) => {
1363
1701
  const wantAll = requested.includes("all");
1364
1702
  const want = (kind) => wantAll || requested.includes(kind);
1365
1703
  if (mime === MIME.PDF) {
1366
- if (!want("image")) fail$4(verb, "PDF asset extraction currently supports images (types=image or all)");
1367
- if (!ctx.engines.hasConvert(mime, "images")) fail$4(verb, "PDF asset extraction requires an engine that converts application/pdf to \"images\", and none is configured. Do not retry this verb on PDFs in this deployment.");
1704
+ if (!want("image")) fail$5(verb, "PDF asset extraction currently supports images (types=image or all)");
1705
+ if (!ctx.engines.hasConvert(mime, "images")) fail$5(verb, "PDF asset extraction requires an engine that converts application/pdf to \"images\", and none is configured. Do not retry this verb on PDFs in this deployment.");
1368
1706
  const format = argOf(ctx.step, "format");
1369
1707
  const result = await ctx.engines.convert({
1370
1708
  bytes: ctx.payload.bytes,
@@ -1374,7 +1712,7 @@ var extractAssetsStep = async (ctx) => {
1374
1712
  options: format ? { format } : void 0,
1375
1713
  signal: ctx.signal
1376
1714
  });
1377
- if (result.outputs.length === 0) fail$4(verb, "no embedded images were found in the PDF");
1715
+ if (result.outputs.length === 0) fail$5(verb, "no embedded images were found in the PDF");
1378
1716
  const wantedMime = format ? EXT_MIME[format] ?? `image/${format}` : void 0;
1379
1717
  const payloads = [];
1380
1718
  for (const [i, img] of result.outputs.entries()) {
@@ -1408,7 +1746,7 @@ var extractAssetsStep = async (ctx) => {
1408
1746
  MIME.ODT,
1409
1747
  MIME.ODS,
1410
1748
  MIME.ODP
1411
- ].includes(mime)) fail$4(verb, `asset extraction for ${mime} is not supported (OOXML/ODF archives and PDF are)`);
1749
+ ].includes(mime)) fail$5(verb, `asset extraction for ${mime} is not supported (OOXML/ODF archives and PDF are)`);
1412
1750
  const zip = await (await jszip$2()).loadAsync(ctx.payload.bytes);
1413
1751
  const payloads = [];
1414
1752
  for (const [name, entry] of Object.entries(zip.files)) {
@@ -1424,7 +1762,7 @@ var extractAssetsStep = async (ctx) => {
1424
1762
  filename: basename
1425
1763
  });
1426
1764
  }
1427
- if (payloads.length === 0) fail$4(verb, "no embedded assets matched the requested types");
1765
+ if (payloads.length === 0) fail$5(verb, "no embedded assets matched the requested types");
1428
1766
  return {
1429
1767
  kind: "media-list",
1430
1768
  payloads
@@ -1435,7 +1773,7 @@ var convertStep = async (ctx) => {
1435
1773
  const verb = "convert";
1436
1774
  const to = argOf(ctx.step, "to");
1437
1775
  const supported = ctx.engines.convertTargets(ctx.payload.mimeType);
1438
- if (!supported.includes(to)) fail$4(verb, `no configured engine (or computed path) can produce "${to}" from ${ctx.payload.mimeType}; reachable targets: ${supported.join(", ") || "(none)"}`);
1776
+ if (!supported.includes(to)) fail$5(verb, `no configured engine (or computed path) can produce "${to}" from ${ctx.payload.mimeType}; reachable targets: ${supported.join(", ") || "(none)"}`);
1439
1777
  const output = (await ctx.engines.convert({
1440
1778
  bytes: ctx.payload.bytes,
1441
1779
  mimeType: ctx.payload.mimeType,
@@ -1443,7 +1781,7 @@ var convertStep = async (ctx) => {
1443
1781
  to,
1444
1782
  signal: ctx.signal
1445
1783
  })).outputs[0];
1446
- if (!output) fail$4(verb, "the conversion produced no output");
1784
+ if (!output) fail$5(verb, "the conversion produced no output");
1447
1785
  const dot = ctx.payload.filename.lastIndexOf(".");
1448
1786
  const base = dot > 0 ? ctx.payload.filename.slice(0, dot) : ctx.payload.filename;
1449
1787
  return {
@@ -1465,32 +1803,222 @@ var DOC_STEPS = [
1465
1803
  ["convert", convertStep]
1466
1804
  ];
1467
1805
  //#endregion
1468
- //#region src/batteries/media/steps/sheet.ts
1806
+ //#region src/batteries/media/steps/data.ts
1469
1807
  /**
1470
- * `sheet.*` step implementations: ExcelJS workbook mutations on in-memory bytes.
1808
+ * `append` and `data.*` step implementations: deterministic text/data mutations on in-memory
1809
+ * bytes — append a line, set/merge/delete at a JSON or YAML path.
1471
1810
  *
1472
1811
  * @remarks
1473
- * Internal sibling of the `@nhtio/adk/batteries/media` entry. Ported from the source server's
1474
- * sheet adapters (its green e2e suite informs the spec coverage). All ten mutations operate on
1475
- * xlsx natively via ExcelJS (optional peer, lazily imported); ODS and legacy-xls inputs are
1476
- * normalized to xlsx first through the configured `sheetNormalize` engine, degrading to a
1477
- * readable failure when none is configured. Output is always xlsx.
1812
+ * Internal sibling of the `@nhtio/adk/batteries/media` entry. Pure and cross-env: text ops
1813
+ * are string concatenation; structured ops parse (JSON natively, YAML via the `js-yaml`
1814
+ * dependency), mutate the value tree, and re-serialize **preserving the source format** —
1815
+ * `data.set` on a YAML file yields YAML, on a JSON file yields JSON. These are the verbs
1816
+ * that make the lossy text family first-class media: `empty:json | data set path=… value=…`
1817
+ * is a create-then-populate chain with no engine requirement at all.
1478
1818
  */
1479
- var excelPromise;
1480
- var excel = () => {
1481
- excelPromise ??= import("exceljs").then((m) => "default" in m ? m.default : m);
1482
- return excelPromise;
1819
+ var fail$4 = (verb, message) => {
1820
+ throw new E_MEDIA_STEP_FAILED([verb, message]);
1821
+ };
1822
+ var encoder = new TextEncoder();
1823
+ var decoder = new TextDecoder();
1824
+ /** MIME types the text-shaped verbs operate on. */
1825
+ var TEXTUAL = (mime) => mime.startsWith("text/") || mime === MIME.JSON || mime === MIME.YAML;
1826
+ /** `append` — append text to text-family media. */
1827
+ var appendStep = async (ctx) => {
1828
+ const verb = "append";
1829
+ const mime = ctx.payload.mimeType.toLowerCase().split(";")[0].trim();
1830
+ if (!TEXTUAL(mime)) fail$4(verb, `append expects text-family media (txt/md/csv/yaml/json-lines); the media is ${mime}`);
1831
+ const text = argOf(ctx.step, "text");
1832
+ const newline = argOf(ctx.step, "newline") ?? true;
1833
+ const current = decoder.decode(ctx.payload.bytes);
1834
+ const next = current + (newline && current.length > 0 && !current.endsWith("\n") ? "\n" : "") + text + (newline ? "\n" : "");
1835
+ return {
1836
+ kind: "media",
1837
+ payload: {
1838
+ ...ctx.payload,
1839
+ bytes: encoder.encode(next)
1840
+ }
1841
+ };
1842
+ };
1843
+ var parseDoc = async (verb, payload) => {
1844
+ const mime = payload.mimeType.toLowerCase().split(";")[0].trim();
1845
+ const text = decoder.decode(payload.bytes);
1846
+ if (mime === MIME.JSON) try {
1847
+ return {
1848
+ value: text.trim() === "" ? null : JSON.parse(text),
1849
+ format: "json"
1850
+ };
1851
+ } catch (err) {
1852
+ fail$4(verb, `the media is not valid JSON: ${isError(err) ? err.message : String(err)}`);
1853
+ }
1854
+ if (mime === MIME.YAML) try {
1855
+ const { load } = await import("js-yaml");
1856
+ return {
1857
+ value: load(text) ?? null,
1858
+ format: "yaml"
1859
+ };
1860
+ } catch (err) {
1861
+ fail$4(verb, `the media is not valid YAML: ${isError(err) ? err.message : String(err)}`);
1862
+ }
1863
+ fail$4(verb, `data operations expect JSON or YAML media; the media is ${mime}`);
1864
+ throw new Error("unreachable");
1483
1865
  };
1866
+ var serializeDoc = async (doc, payload) => {
1867
+ if (doc.format === "yaml") {
1868
+ const { dump } = await import("js-yaml");
1869
+ return {
1870
+ ...payload,
1871
+ bytes: encoder.encode(dump(doc.value))
1872
+ };
1873
+ }
1874
+ return {
1875
+ ...payload,
1876
+ bytes: encoder.encode(JSON.stringify(doc.value, null, 2))
1877
+ };
1878
+ };
1879
+ /** Parse a dot/bracket path (`a.b[2].c`) into segments. */
1880
+ var parsePath = (verb, raw) => {
1881
+ if (typeof raw !== "string" || raw.trim() === "") fail$4(verb, "path must be a non-empty string");
1882
+ const segments = [];
1883
+ const re = /([^.[\]]+)|\[(\d+)\]/g;
1884
+ let match;
1885
+ while (match = re.exec(raw)) if (match[2] !== void 0) segments.push(Number(match[2]));
1886
+ else segments.push(match[1]);
1887
+ if (segments.length === 0) fail$4(verb, `could not parse path "${raw}"`);
1888
+ return segments;
1889
+ };
1890
+ /** Walk to the parent of the path target, creating containers when `create` is set. */
1891
+ var walkToParent = (verb, root, segments, create) => {
1892
+ let node = root;
1893
+ for (let i = 0; i < segments.length - 1; i++) {
1894
+ const seg = segments[i];
1895
+ const isIndex = typeof seg === "number";
1896
+ if (node === null || typeof node !== "object") fail$4(verb, `path segment "${String(seg)}" walks through a non-container value`);
1897
+ const container = node;
1898
+ let next = isIndex ? container[seg] : container[seg];
1899
+ if (next === void 0 || next === null) {
1900
+ if (!create) fail$4(verb, `path segment "${String(seg)}" does not exist`);
1901
+ next = typeof segments[i + 1] === "number" ? [] : {};
1902
+ if (isIndex) container[seg] = next;
1903
+ else container[seg] = next;
1904
+ }
1905
+ node = next;
1906
+ }
1907
+ if (node === null || typeof node !== "object") fail$4(verb, "the path target parent is not an object or array");
1908
+ return {
1909
+ parent: node,
1910
+ key: segments[segments.length - 1]
1911
+ };
1912
+ };
1913
+ /** `data.set` — set a value at a JSON/YAML path, creating intermediate containers. */
1914
+ var dataSetStep = async (ctx) => {
1915
+ const verb = "data set";
1916
+ const path = argOf(ctx.step, "path");
1917
+ const rawValue = argOf(ctx.step, "value");
1918
+ if (rawValue === void 0) fail$4(verb, "value is required (JSON-encoded scalar or structure)");
1919
+ let value;
1920
+ try {
1921
+ value = JSON.parse(String(rawValue));
1922
+ } catch {
1923
+ value = String(rawValue);
1924
+ }
1925
+ const doc = await parseDoc(verb, ctx.payload);
1926
+ const segments = parsePath(verb, path);
1927
+ if (doc.value === null || typeof doc.value !== "object") doc.value = typeof segments[0] === "number" ? [] : {};
1928
+ const { parent, key } = walkToParent(verb, doc.value, segments, true);
1929
+ if (Array.isArray(parent)) parent[Number(key)] = value;
1930
+ else parent[String(key)] = value;
1931
+ return {
1932
+ kind: "media",
1933
+ payload: await serializeDoc(doc, ctx.payload)
1934
+ };
1935
+ };
1936
+ /** Deep merge `fragment` into `target` (objects merge recursively; everything else replaces). */
1937
+ var deepMerge = (target, fragment) => {
1938
+ if (target === null || fragment === null || typeof target !== "object" || typeof fragment !== "object" || Array.isArray(target) !== Array.isArray(fragment) || Array.isArray(fragment)) return fragment;
1939
+ const out = { ...target };
1940
+ for (const [k, v] of Object.entries(fragment)) out[k] = k in out ? deepMerge(out[k], v) : v;
1941
+ return out;
1942
+ };
1943
+ /** `data.merge` — merge a JSON fragment into the document (deep by default). */
1944
+ var dataMergeStep = async (ctx) => {
1945
+ const verb = "data merge";
1946
+ const rawFragment = argOf(ctx.step, "fragment");
1947
+ const strategy = argOf(ctx.step, "strategy") ?? "deep";
1948
+ let fragment;
1949
+ try {
1950
+ fragment = JSON.parse(String(rawFragment));
1951
+ } catch (err) {
1952
+ fail$4(verb, `fragment must be valid JSON: ${isError(err) ? err.message : String(err)}`);
1953
+ }
1954
+ if (fragment === null || typeof fragment !== "object" || Array.isArray(fragment)) fail$4(verb, "fragment must be a JSON object");
1955
+ const doc = await parseDoc(verb, ctx.payload);
1956
+ if (doc.value === null || typeof doc.value !== "object" || Array.isArray(doc.value)) fail$4(verb, "merge requires the document root to be an object");
1957
+ doc.value = strategy === "shallow" ? {
1958
+ ...doc.value,
1959
+ ...fragment
1960
+ } : deepMerge(doc.value, fragment);
1961
+ return {
1962
+ kind: "media",
1963
+ payload: await serializeDoc(doc, ctx.payload)
1964
+ };
1965
+ };
1966
+ /** `data.delete` — remove a key/index at a JSON/YAML path. */
1967
+ var dataDeleteStep = async (ctx) => {
1968
+ const verb = "data delete";
1969
+ const path = argOf(ctx.step, "path");
1970
+ const doc = await parseDoc(verb, ctx.payload);
1971
+ const segments = parsePath(verb, path);
1972
+ if (doc.value === null || typeof doc.value !== "object") fail$4(verb, "the document has no structure to delete from");
1973
+ const { parent, key } = walkToParent(verb, doc.value, segments, false);
1974
+ if (Array.isArray(parent)) {
1975
+ const idx = Number(key);
1976
+ if (idx < 0 || idx >= parent.length) fail$4(verb, `index ${idx} is out of range`);
1977
+ parent.splice(idx, 1);
1978
+ } else {
1979
+ if (!(String(key) in parent)) fail$4(verb, `key "${String(key)}" does not exist at that path`);
1980
+ delete parent[String(key)];
1981
+ }
1982
+ return {
1983
+ kind: "media",
1984
+ payload: await serializeDoc(doc, ctx.payload)
1985
+ };
1986
+ };
1987
+ /** The data step registry fragment, keyed by canonical verb id. */
1988
+ var DATA_STEPS = [
1989
+ ["append", appendStep],
1990
+ ["data.set", dataSetStep],
1991
+ ["data.merge", dataMergeStep],
1992
+ ["data.delete", dataDeleteStep]
1993
+ ];
1994
+ //#endregion
1995
+ //#region src/batteries/media/steps/sheet.ts
1996
+ /**
1997
+ * `sheet.*` step implementations: thin dispatchers into the engine registry's edit
1998
+ * capability.
1999
+ *
2000
+ * @remarks
2001
+ * Internal sibling of the `@nhtio/adk/batteries/media` entry. The actual workbook surgery
2002
+ * lives in edit-capable engines (`engines/exceljs` preserves styling; `engines/sheetjs`
2003
+ * covers the wider read matrix but strips styling — SheetJS CE limitation). Each step here:
2004
+ * normalizes non-xlsx spreadsheet inputs to xlsx when the selected edit coverage requires it
2005
+ * (any spreadsheet-family MIME with a declared `hasConvert(mime, 'xlsx')` edge qualifies —
2006
+ * ODS/XLS via soffice or sheetjs, XLSB/FODS/SYLK/DIF/DBF/NUMBERS via sheetjs), dispatches the
2007
+ * op through `ctx.engines.edit`, and degrades to a model-actionable failure when no edit
2008
+ * engine is configured.
2009
+ */
1484
2010
  var fail$3 = (verb, message) => {
1485
2011
  throw new E_MEDIA_STEP_FAILED([verb, message]);
1486
2012
  };
1487
- /** Acquire xlsx bytes for the step, converting ODS/xls to xlsx via the engine registry. */
1488
- var acquireXlsx = async (ctx, verb) => {
2013
+ /** Acquire bytes the edit dispatch can work on, normalizing to xlsx when necessary. */
2014
+ var acquireEditable = async (ctx, verb) => {
1489
2015
  const mime = ctx.payload.mimeType.toLowerCase().split(";")[0].trim();
1490
- if (mime === MIME.XLSX) return ctx.payload.bytes;
1491
- const mutationBlock = unsupportedForMutationReason(mime);
1492
- if (mime === MIME.ODS || mime === MIME.XLS) {
1493
- if (!ctx.engines.hasConvert(mime, "xlsx")) fail$3(verb, `this input is ${mime} — an engine that converts it to xlsx is required first, and none is configured. Do not retry this verb on this media in this deployment.`);
2016
+ if (ctx.engines.hasEdit?.(mime)) return {
2017
+ bytes: ctx.payload.bytes,
2018
+ mimeType: mime
2019
+ };
2020
+ if (SPREADSHEET_MIMES.has(mime) && mime !== MIME.XLSX) {
2021
+ if (!ctx.engines.hasConvert(mime, "xlsx")) fail$3(verb, unsupportedForMutationReason(mime) ?? `this input is ${mime} — an engine that converts it to xlsx is required first, and none is configured. Do not retry this verb on this media in this deployment.`);
1494
2022
  const output = (await ctx.engines.convert({
1495
2023
  bytes: ctx.payload.bytes,
1496
2024
  mimeType: mime,
@@ -1499,247 +2027,93 @@ var acquireXlsx = async (ctx, verb) => {
1499
2027
  signal: ctx.signal
1500
2028
  })).outputs[0];
1501
2029
  if (!output) fail$3(verb, "normalizing the workbook to xlsx produced no output");
1502
- return output.bytes;
2030
+ return {
2031
+ bytes: output.bytes,
2032
+ mimeType: MIME.XLSX
2033
+ };
1503
2034
  }
1504
- if (mutationBlock) fail$3(verb, mutationBlock);
1505
- fail$3(verb, `sheet operations expect a spreadsheet; the media is ${mime}`);
1506
- throw new Error("unreachable");
1507
- };
1508
- /** The shared open → mutate → write-back lifecycle every sheet verb uses. */
1509
- var withWorkbook = async (ctx, verb, mutate) => {
1510
- const xlsxBytes = await acquireXlsx(ctx, verb);
1511
- const wb = new (await (excel())).Workbook();
1512
- try {
1513
- await wb.xlsx.load(xlsxBytes.buffer.slice(xlsxBytes.byteOffset, xlsxBytes.byteOffset + xlsxBytes.byteLength));
1514
- } catch (err) {
1515
- fail$3(verb, `could not open the spreadsheet: ${isError(err) ? err.message : String(err)}`);
2035
+ if (mime !== MIME.XLSX) {
2036
+ const mutationBlock = unsupportedForMutationReason(mime);
2037
+ if (mutationBlock) fail$3(verb, mutationBlock);
2038
+ fail$3(verb, `sheet operations expect a spreadsheet; the media is ${mime}`);
1516
2039
  }
1517
- await mutate(wb);
1518
2040
  return {
1519
- kind: "media",
1520
- payload: {
1521
- bytes: new Uint8Array(await wb.xlsx.writeBuffer()),
1522
- mimeType: MIME.XLSX,
1523
- filename: replaceExtension(ctx.payload.filename, "xlsx")
1524
- }
2041
+ bytes: ctx.payload.bytes,
2042
+ mimeType: MIME.XLSX
1525
2043
  };
1526
2044
  };
1527
- /** Resolve the target worksheet from the frozen `sheet=` rule (bare number=index, string=name). */
1528
- var resolveSheet = (verb, wb, sheetArg) => {
1529
- if (sheetArg === void 0) {
1530
- const first = wb.worksheets[0];
1531
- if (!first) fail$3(verb, "the workbook has no worksheets");
1532
- return first;
2045
+ /** Dispatch one `sheet.*` op through the registry's edit capability. */
2046
+ var dispatchEdit = async (ctx, verb, op) => {
2047
+ const { bytes, mimeType } = await acquireEditable(ctx, verb);
2048
+ if (!ctx.engines.hasEdit?.(mimeType, op)) fail$3(verb, `no engine that edits spreadsheets is configured — add engines/exceljs (or engines/sheetjs) to the pipeline's engines array. Do not retry this verb in this deployment.`);
2049
+ try {
2050
+ const result = await ctx.engines.edit({
2051
+ bytes,
2052
+ mimeType,
2053
+ op,
2054
+ args: ctx.step.args,
2055
+ signal: ctx.signal
2056
+ });
2057
+ return {
2058
+ kind: "media",
2059
+ payload: {
2060
+ bytes: result.bytes,
2061
+ mimeType: result.mimeType,
2062
+ filename: replaceExtension(ctx.payload.filename, "xlsx")
2063
+ }
2064
+ };
2065
+ } catch (err) {
2066
+ if (isError(err) && err.name.startsWith("E_MEDIA_")) throw err;
2067
+ fail$3(verb, isError(err) ? err.message : String(err));
2068
+ throw err;
1533
2069
  }
1534
- if (typeof sheetArg === "number") {
1535
- const byIndex = wb.worksheets[sheetArg - 1];
1536
- if (byIndex) return byIndex;
1537
- if (wb.getWorksheet(String(sheetArg))) fail$3(verb, `no sheet at index ${sheetArg}, but a sheet NAMED "${sheetArg}" exists — quote it: sheet="${sheetArg}"`);
1538
- fail$3(verb, `sheet index ${sheetArg} is out of range (1-based; the workbook has ${wb.worksheets.length})`);
1539
- }
1540
- const ws = wb.getWorksheet(sheetArg);
1541
- if (!ws) fail$3(verb, `no sheet named "${sheetArg}". Sheets: ${wb.worksheets.map((w) => `"${w.name}"`).join(", ")}`);
1542
- return ws;
1543
- };
1544
- var columnLetterToNumber = (col) => {
1545
- let n = 0;
1546
- for (const ch of col.toUpperCase()) n = n * 26 + (ch.charCodeAt(0) - 64);
1547
- return n;
1548
- };
1549
- var asCellValue = (verb, value) => {
1550
- if (value === null) return null;
1551
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
1552
- fail$3(verb, `cell values must be string, number, boolean, or null; got ${typeof value}`);
1553
- throw new Error("unreachable");
2070
+ };
2071
+ /** Pre-dispatch arg validation: keep the historical readable failures for malformed args. */
2072
+ var requireJsonArray = (verb, value, message) => {
2073
+ if (!Array.isArray(value) || value.length === 0) fail$3(verb, message);
1554
2074
  };
1555
2075
  /** `sheet.add_rows` — insert rows before/after an index, or append. */
1556
2076
  var sheetAddRowsStep = async (ctx) => {
1557
2077
  const verb = "sheet add_rows";
1558
2078
  const rows = ctx.step.args.rows;
1559
2079
  if (!Array.isArray(rows) || rows.length === 0 || !rows.every(Array.isArray)) fail$3(verb, `rows must be a non-empty JSON array of arrays, e.g. rows='[["a",1]]'`);
1560
- const before = argOf(ctx.step, "before");
1561
- const after = argOf(ctx.step, "after");
1562
- return withWorkbook(ctx, verb, (wb) => {
1563
- const ws = resolveSheet(verb, wb, argOf(ctx.step, "sheet"));
1564
- const insertAt = before !== void 0 ? before : after !== void 0 ? after + 1 : ws.rowCount + 1;
1565
- const cellRows = rows.map((r) => r.map((v) => asCellValue(verb, v)));
1566
- ws.spliceRows(insertAt, 0, ...cellRows);
1567
- return { added: cellRows.length };
1568
- });
2080
+ return dispatchEdit(ctx, verb, "sheet.add_rows");
1569
2081
  };
1570
2082
  /** `sheet.add_columns` — insert columns with headers or full descriptors. */
1571
2083
  var sheetAddColumnsStep = async (ctx) => {
1572
2084
  const verb = "sheet add_columns";
1573
2085
  const headers = ctx.step.args.headers;
1574
- const columns = ctx.step.args.columns ?? headers?.map((header) => ({ header }));
1575
- if (!Array.isArray(columns) || columns.length === 0) fail$3(verb, `provide headers=a,b or columns='[{"header":"X","values":[1]}]'`);
1576
- const before = argOf(ctx.step, "before");
1577
- const after = argOf(ctx.step, "after");
1578
- return withWorkbook(ctx, verb, (wb) => {
1579
- const ws = resolveSheet(verb, wb, argOf(ctx.step, "sheet"));
1580
- const insertAt = before !== void 0 ? before : after !== void 0 ? after + 1 : ws.columnCount + 1;
1581
- for (const [i, col] of columns.entries()) {
1582
- if (typeof col?.header !== "string") fail$3(verb, "every column needs a string header");
1583
- ws.spliceColumns(insertAt + i, 0, [col.header, ...(col.values ?? []).map((v) => asCellValue(verb, v))]);
1584
- }
1585
- return { added: columns.length };
1586
- });
2086
+ requireJsonArray(verb, ctx.step.args.columns ?? headers, `provide headers=a,b or columns='[{"header":"X","values":[1]}]'`);
2087
+ return dispatchEdit(ctx, verb, "sheet.add_columns");
1587
2088
  };
1588
2089
  /** `sheet.update_cells` — set cells by A1 address or row/col. Leading `=` writes a formula. */
1589
2090
  var sheetUpdateCellsStep = async (ctx) => {
1590
2091
  const verb = "sheet update_cells";
1591
- const updates = ctx.step.args.updates;
1592
- if (!Array.isArray(updates) || updates.length === 0) fail$3(verb, `updates must be a non-empty JSON array, e.g. updates='[{"address":"B2","value":3}]'`);
1593
- return withWorkbook(ctx, verb, (wb) => {
1594
- const ws = resolveSheet(verb, wb, argOf(ctx.step, "sheet"));
1595
- let modified = 0;
1596
- for (const raw of updates) {
1597
- const address = raw.address;
1598
- const row = raw.row;
1599
- const col = raw.col;
1600
- let cell;
1601
- if (address) cell = ws.getCell(address);
1602
- else if (row !== void 0 && col !== void 0) cell = typeof col === "string" ? ws.getCell(row, columnLetterToNumber(col)) : ws.getCell(row, col);
1603
- else {
1604
- fail$3(verb, "each update needs address, or both row and col");
1605
- continue;
1606
- }
1607
- const value = raw.value;
1608
- if (typeof value === "string" && value.startsWith("=")) cell.value = { formula: value.slice(1) };
1609
- else cell.value = asCellValue(verb, value);
1610
- modified += 1;
1611
- }
1612
- return { modified };
1613
- });
2092
+ requireJsonArray(verb, ctx.step.args.updates, `updates must be a non-empty JSON array, e.g. updates='[{"address":"B2","value":3}]'`);
2093
+ return dispatchEdit(ctx, verb, "sheet.update_cells");
1614
2094
  };
1615
2095
  /** `sheet.delete_rows` — delete 1-based rows (bottom-up so indices stay valid). */
1616
- var sheetDeleteRowsStep = async (ctx) => {
1617
- const verb = "sheet delete_rows";
1618
- const rows = ctx.step.args.rows;
1619
- return withWorkbook(ctx, verb, (wb) => {
1620
- const ws = resolveSheet(verb, wb, argOf(ctx.step, "sheet"));
1621
- for (const r of [...rows].sort((a, b) => b - a)) ws.spliceRows(r, 1);
1622
- return { removed: rows.length };
1623
- });
1624
- };
2096
+ var sheetDeleteRowsStep = async (ctx) => dispatchEdit(ctx, "sheet delete_rows", "sheet.delete_rows");
1625
2097
  /** `sheet.delete_columns` — delete 1-based columns. */
1626
- var sheetDeleteColumnsStep = async (ctx) => {
1627
- const verb = "sheet delete_columns";
1628
- const columns = ctx.step.args.columns;
1629
- return withWorkbook(ctx, verb, (wb) => {
1630
- const ws = resolveSheet(verb, wb, argOf(ctx.step, "sheet"));
1631
- for (const c of [...columns].sort((a, b) => b - a)) ws.spliceColumns(c, 1);
1632
- return { removed: columns.length };
1633
- });
1634
- };
2098
+ var sheetDeleteColumnsStep = async (ctx) => dispatchEdit(ctx, "sheet delete_columns", "sheet.delete_columns");
1635
2099
  /** `sheet.rename_sheet` — rename by NAME (the server contract; index targeting is rejected). */
1636
- var sheetRenameSheetStep = async (ctx) => {
1637
- const verb = "sheet rename_sheet";
1638
- const sheet = argOf(ctx.step, "sheet");
1639
- const to = argOf(ctx.step, "to");
1640
- return withWorkbook(ctx, verb, (wb) => {
1641
- const ws = wb.getWorksheet(sheet);
1642
- if (!ws) fail$3(verb, `rename targets a sheet NAME; no sheet named "${sheet}". Sheets: ${wb.worksheets.map((w) => `"${w.name}"`).join(", ")}`);
1643
- ws.name = to;
1644
- return { modified: 1 };
1645
- });
1646
- };
2100
+ var sheetRenameSheetStep = async (ctx) => dispatchEdit(ctx, "sheet rename_sheet", "sheet.rename_sheet");
1647
2101
  /** `sheet.add_sheet` — add a worksheet, optionally at a 1-based position. */
1648
- var sheetAddSheetStep = async (ctx) => {
1649
- const verb = "sheet add_sheet";
1650
- const name = argOf(ctx.step, "name");
1651
- const at = argOf(ctx.step, "at");
1652
- return withWorkbook(ctx, verb, (wb) => {
1653
- if (wb.getWorksheet(name)) fail$3(verb, `a sheet named "${name}" already exists`);
1654
- const ws = wb.addWorksheet(name);
1655
- if (at !== void 0) {
1656
- const all = wb.worksheets;
1657
- const wsIdx = all.indexOf(ws);
1658
- if (wsIdx !== at - 1) all.forEach((w, i) => {
1659
- w.orderNo = w === ws ? at : i + 1 >= at && i < wsIdx ? i + 2 : i + 1;
1660
- });
1661
- }
1662
- return { added: 1 };
1663
- });
1664
- };
2102
+ var sheetAddSheetStep = async (ctx) => dispatchEdit(ctx, "sheet add_sheet", "sheet.add_sheet");
1665
2103
  /** `sheet.remove_sheet` — remove by NAME (the server contract). */
1666
- var sheetRemoveSheetStep = async (ctx) => {
1667
- const verb = "sheet remove_sheet";
1668
- const sheet = argOf(ctx.step, "sheet");
1669
- return withWorkbook(ctx, verb, (wb) => {
1670
- const ws = wb.getWorksheet(sheet);
1671
- if (!ws) fail$3(verb, `remove targets a sheet NAME; no sheet named "${sheet}". Sheets: ${wb.worksheets.map((w) => `"${w.name}"`).join(", ")}`);
1672
- wb.removeWorksheet(ws.id);
1673
- return { removed: 1 };
1674
- });
1675
- };
2104
+ var sheetRemoveSheetStep = async (ctx) => dispatchEdit(ctx, "sheet remove_sheet", "sheet.remove_sheet");
1676
2105
  /** `sheet.reorder_sheets` — every sheet exactly once, by name or 1-based index. */
1677
2106
  var sheetReorderSheetsStep = async (ctx) => {
1678
2107
  const verb = "sheet reorder_sheets";
1679
- const order = ctx.step.args.order;
1680
- if (!Array.isArray(order) || order.length === 0) fail$3(verb, `order must be a JSON array of names/indices, e.g. order='["Summary",2]'`);
1681
- return withWorkbook(ctx, verb, (wb) => {
1682
- const refs = order;
1683
- if (refs.length !== wb.worksheets.length) fail$3(verb, `order must include every worksheet exactly once (the workbook has ${wb.worksheets.length})`);
1684
- const reordered = [];
1685
- const seen = /* @__PURE__ */ new Set();
1686
- for (const ref of refs) {
1687
- const ws = typeof ref === "number" ? wb.worksheets[ref - 1] : wb.getWorksheet(ref);
1688
- if (!ws) fail$3(verb, `sheet not found: ${String(ref)}`);
1689
- if (seen.has(ws.id)) fail$3(verb, `duplicate sheet reference: ${String(ref)}`);
1690
- seen.add(ws.id);
1691
- reordered.push(ws);
1692
- }
1693
- reordered.forEach((ws, i) => {
1694
- ws.orderNo = i + 1;
1695
- });
1696
- return { modified: reordered.length };
1697
- });
2108
+ requireJsonArray(verb, ctx.step.args.order, `order must be a JSON array of names/indices, e.g. order='["Summary",2]'`);
2109
+ return dispatchEdit(ctx, verb, "sheet.reorder_sheets");
1698
2110
  };
1699
2111
  /** `sheet.transform_table` — rename/select/drop columns by header name. */
1700
2112
  var sheetTransformTableStep = async (ctx) => {
1701
2113
  const verb = "sheet transform_table";
1702
- const headerRow = argOf(ctx.step, "header_row") ?? 1;
1703
- const rename = ctx.step.args.rename;
1704
- const select = ctx.step.args.select;
1705
- const drop = ctx.step.args.drop;
1706
- return withWorkbook(ctx, verb, (wb) => {
1707
- const ws = resolveSheet(verb, wb, argOf(ctx.step, "sheet"));
1708
- let modified = 0;
1709
- const headerMap = /* @__PURE__ */ new Map();
1710
- ws.getRow(headerRow).eachCell({ includeEmpty: false }, (cell, colNumber) => {
1711
- if (typeof cell.value === "string") headerMap.set(cell.value, colNumber);
1712
- });
1713
- if (rename) for (const { from, to } of rename) {
1714
- const colNum = headerMap.get(from);
1715
- if (colNum !== void 0) {
1716
- ws.getRow(headerRow).getCell(colNum).value = to;
1717
- headerMap.delete(from);
1718
- headerMap.set(to, colNum);
1719
- modified += 1;
1720
- }
1721
- }
1722
- if (drop) {
1723
- const cols = drop.map((name) => headerMap.get(name)).filter((n) => n !== void 0).sort((a, b) => b - a);
1724
- for (const col of cols) {
1725
- ws.spliceColumns(col, 1);
1726
- modified += 1;
1727
- }
1728
- }
1729
- if (select) {
1730
- const keep = new Set(select);
1731
- const cols = [];
1732
- ws.getRow(headerRow).eachCell({ includeEmpty: false }, (cell, colNumber) => {
1733
- if (typeof cell.value === "string" && !keep.has(cell.value)) cols.push(colNumber);
1734
- });
1735
- cols.sort((a, b) => b - a);
1736
- for (const col of cols) {
1737
- ws.spliceColumns(col, 1);
1738
- modified += 1;
1739
- }
1740
- }
1741
- return { modified };
1742
- });
2114
+ const headerRow = argOf(ctx.step, "header_row");
2115
+ if (headerRow !== void 0 && (!Number.isFinite(headerRow) || headerRow < 1)) fail$3(verb, "header_row must be a 1-based row number");
2116
+ return dispatchEdit(ctx, verb, "sheet.transform_table");
1743
2117
  };
1744
2118
  /** The sheet step registry fragment, keyed by canonical verb id. */
1745
2119
  var SHEET_STEPS = [
@@ -2329,10 +2703,16 @@ var INGEST_STEPS = [["extract.text", extractTextDeepStep], ["extract.metadata",
2329
2703
  /** The maximum number of conversion hops a computed path may take. */
2330
2704
  var MAX_HOPS = 3;
2331
2705
  /**
2332
- * Format tokens that are valid conversion endpoints but never intermediate path nodes.
2333
- * Without this rule the pathfinder would happily route `docx → txt → …` (lossy garbage in,
2334
- * garbage out) or auto-chain `audio → pcm → txt` (skipping the resample the transcription
2335
- * step performs between those legs).
2706
+ * The no-lossy-intermediates ROUTING rule — and nothing else. These format tokens are valid
2707
+ * conversion endpoints but never intermediate path nodes: without this rule the pathfinder
2708
+ * would happily route `docx → txt → …` (lossy garbage in, garbage out) or auto-chain
2709
+ * `audio → pcm → txt` (skipping the resample the transcription step performs between those
2710
+ * legs).
2711
+ *
2712
+ * This set does NOT gate mutation, creation, or advertising. A lossy format as the *desired
2713
+ * output* is still valid media: `txt` can be created (`empty:txt`), appended to, patched,
2714
+ * diffed, and targeted by `convert to=txt` — terminality only forbids silently routing
2715
+ * *through* it on the way to somewhere else.
2336
2716
  */
2337
2717
  var TERMINAL_TOKENS = new Set([
2338
2718
  "txt",
@@ -2400,6 +2780,20 @@ var buildEngineRegistry = (engines, selection = []) => {
2400
2780
  }
2401
2781
  return out;
2402
2782
  };
2783
+ const editCandidates = (mimeType, op) => {
2784
+ const mime = normalizeMime(mimeType);
2785
+ const out = [];
2786
+ for (const engine of engines) for (const capability of engine.edits ?? []) {
2787
+ if (!matchesAny(capability.over, mime)) continue;
2788
+ if (!capability.ops.includes(op)) continue;
2789
+ out.push({
2790
+ engine,
2791
+ capability
2792
+ });
2793
+ break;
2794
+ }
2795
+ return out;
2796
+ };
2403
2797
  const arbitrate = async (kind, request, candidates) => {
2404
2798
  if (candidates.length === 0) return void 0;
2405
2799
  if (selection.length === 0 || candidates.length === 1) return candidates[0];
@@ -2543,13 +2937,38 @@ var buildEngineRegistry = (engines, selection = []) => {
2543
2937
  if (!chosen) throw new Error(`all engines capable of this mutate (${candidates.map((c) => c.engine.id).join(", ")}) were excluded by selection middleware`);
2544
2938
  return chosen.capability.mutate(request);
2545
2939
  };
2940
+ const edit = async (request) => {
2941
+ const candidates = editCandidates(request.mimeType, request.op);
2942
+ if (candidates.length === 0) {
2943
+ const allOps = /* @__PURE__ */ new Set();
2944
+ for (const engine of engines) for (const capability of engine.edits ?? []) for (const op of capability.ops) allOps.add(op);
2945
+ throw new Error(`no configured engine can apply "${request.op}" to ${request.mimeType}; declared edit ops: ${[...allOps].join(", ") || "(none)"} (engines: ${ids()})`);
2946
+ }
2947
+ const chosen = await arbitrate("edit", {
2948
+ mimeType: request.mimeType,
2949
+ filename: "",
2950
+ bytes: request.bytes,
2951
+ ops: [request.op]
2952
+ }, candidates);
2953
+ if (!chosen) throw new Error(`all engines capable of "${request.op}" (${candidates.map((c) => c.engine.id).join(", ")}) were excluded by selection middleware`);
2954
+ return chosen.capability.edit(request);
2955
+ };
2546
2956
  return {
2547
2957
  engines,
2548
2958
  hasConvert,
2549
2959
  hasMutate: () => engines.some((e) => (e.mutates ?? []).length > 0),
2960
+ hasEdit: (mime, op) => {
2961
+ for (const engine of engines) for (const capability of engine.edits ?? []) {
2962
+ if (mime !== void 0 && !matchesAny(capability.over, normalizeMime(mime))) continue;
2963
+ if (op !== void 0 && !capability.ops.includes(op)) continue;
2964
+ return true;
2965
+ }
2966
+ return false;
2967
+ },
2550
2968
  convertTargets,
2551
2969
  convert,
2552
- mutate
2970
+ mutate,
2971
+ edit
2553
2972
  };
2554
2973
  };
2555
2974
  //#endregion
@@ -2927,6 +3346,7 @@ var PURE_STEPS = [
2927
3346
  ["extract.text", extractTextStep],
2928
3347
  ["extract.metadata", extractMetadataStep],
2929
3348
  ["chunk", chunkStep],
3349
+ ...DATA_STEPS,
2930
3350
  ...SHEET_STEPS,
2931
3351
  ...SLIDES_STEPS,
2932
3352
  ...DOC_STEPS,
@@ -3004,6 +3424,6 @@ var createMediaPipeline = async (config = {}) => {
3004
3424
  return callable;
3005
3425
  };
3006
3426
  //#endregion
3007
- export { EXT_TO_MIME, E_INVALID_MEDIA_PIPELINE_CONFIG, E_MEDIA_BAD_ARG, E_MEDIA_ENGINE_REQUIRED, E_MEDIA_MISSING_ARG, E_MEDIA_NOT_PIPE_EXPRESSIBLE, E_MEDIA_PIPE_SYNTAX, E_MEDIA_STEP_FAILED, E_MEDIA_STEP_UNAVAILABLE, E_MEDIA_UNKNOWN_ARG, E_MEDIA_UNKNOWN_VERB, E_MEDIA_UNSUPPORTED_OP, FOLDED_VERBS, MIME, MediaChain, PCM_MIME, VERBS, VERB_INDEX, availableVerbs, buildEngineRegistry, bytesToPcm, createMediaPipeline, familyOf, foldVerb, fromOps, implementsMediaEngine, isMediaRef, isRegExpRef, lowerSegments, parsePipeRaw, pcmToBytes, replaceExtension, suggestVerbs, toOps, toPipe, unsupportedForMutationReason, validateOps, validateSegments };
3427
+ export { EMPTY_MIME, EXT_TO_MIME, E_INVALID_MEDIA_PIPELINE_CONFIG, E_MEDIA_BAD_ARG, E_MEDIA_ENGINE_REQUIRED, E_MEDIA_MISSING_ARG, E_MEDIA_NOT_PIPE_EXPRESSIBLE, E_MEDIA_PIPE_SYNTAX, E_MEDIA_STEP_FAILED, E_MEDIA_STEP_UNAVAILABLE, E_MEDIA_UNKNOWN_ARG, E_MEDIA_UNKNOWN_VERB, E_MEDIA_UNSUPPORTED_OP, FOLDED_VERBS, MIME, MediaChain, PCM_MIME, VERBS, VERB_INDEX, availableVerbs, buildEngineRegistry, bytesToPcm, createMediaPipeline, familyOf, foldVerb, fromOps, implementsMediaEngine, isMediaRef, isRegExpRef, lowerSegments, parsePipeRaw, pcmToBytes, replaceExtension, suggestVerbs, toOps, toPipe, unsupportedForMutationReason, validateOps, validateSegments };
3008
3428
 
3009
3429
  //# sourceMappingURL=media.mjs.map