tenjin-cli 0.1.0-alpha.3 → 0.1.0-alpha.30

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 (246) hide show
  1. package/NOTICE.md +54 -7
  2. package/README.md +149 -264
  3. package/dist/{_esm-FEASBWRP.js → _esm-CE7KNONL.js} +9 -10
  4. package/dist/alive-3J3CHOQP.js +21 -0
  5. package/dist/{ccip-NQXCEK2U.js → ccip-7RMRLAGV.js} +4 -4
  6. package/dist/{ccip-XR5NE5QK.js → ccip-NLCSCHKI.js} +5 -5
  7. package/dist/chunk-2SNUOHAT.js +75 -0
  8. package/dist/chunk-2SNUOHAT.js.map +1 -0
  9. package/dist/chunk-3O2BQIF6.js +2227 -0
  10. package/dist/chunk-3O2BQIF6.js.map +1 -0
  11. package/dist/{chunk-ZMHYXMO6.js → chunk-5IEP5EGE.js} +3 -3
  12. package/dist/chunk-5LJCEMFD.js +12700 -0
  13. package/dist/chunk-5LJCEMFD.js.map +1 -0
  14. package/dist/chunk-6W5GYG3W.js +128 -0
  15. package/dist/chunk-6W5GYG3W.js.map +1 -0
  16. package/dist/chunk-7EKYXMUO.js +7536 -0
  17. package/dist/chunk-7EKYXMUO.js.map +1 -0
  18. package/dist/chunk-7QKHZQKW.js +1680 -0
  19. package/dist/chunk-7QKHZQKW.js.map +1 -0
  20. package/dist/chunk-A36LQPHV.js +29 -0
  21. package/dist/chunk-A36LQPHV.js.map +1 -0
  22. package/dist/chunk-AEG2PXBP.js +192 -0
  23. package/dist/chunk-AEG2PXBP.js.map +1 -0
  24. package/dist/chunk-AKWGE6JQ.js +49 -0
  25. package/dist/chunk-AKWGE6JQ.js.map +1 -0
  26. package/dist/chunk-AWFUPKTM.js +238 -0
  27. package/dist/chunk-AWFUPKTM.js.map +1 -0
  28. package/dist/{chunk-UGX7YPX2.js → chunk-AWQPGIR6.js} +7 -9
  29. package/dist/{chunk-UGX7YPX2.js.map → chunk-AWQPGIR6.js.map} +1 -1
  30. package/dist/{chunk-5CLSD5YN.js → chunk-BPMWXTFX.js} +2 -2
  31. package/dist/chunk-EBVIKMCH.js +108 -0
  32. package/dist/chunk-EBVIKMCH.js.map +1 -0
  33. package/dist/{chunk-YALGASEU.js → chunk-EGELTSPU.js} +2 -2
  34. package/dist/{chunk-S3IGX57D.js → chunk-EL56RW2J.js} +166 -7237
  35. package/dist/chunk-EL56RW2J.js.map +1 -0
  36. package/dist/chunk-HE2MS4QO.js +256 -0
  37. package/dist/chunk-HE2MS4QO.js.map +1 -0
  38. package/dist/{chunk-CYOF7ROH.js → chunk-HPWO4O6S.js} +3 -3
  39. package/dist/chunk-IOODYAXL.js +324 -0
  40. package/dist/chunk-IOODYAXL.js.map +1 -0
  41. package/dist/chunk-JMM6YE7J.js +2174 -0
  42. package/dist/chunk-JMM6YE7J.js.map +1 -0
  43. package/dist/{chunk-QVX5MWJZ.js → chunk-JRGFKVAZ.js} +2 -2
  44. package/dist/{chunk-HIVZG55D.js → chunk-KG3D7FIF.js} +2 -2
  45. package/dist/chunk-KHE6L6TD.js +416 -0
  46. package/dist/chunk-KHE6L6TD.js.map +1 -0
  47. package/dist/chunk-KOGZDMHO.js +21 -0
  48. package/dist/chunk-KOGZDMHO.js.map +1 -0
  49. package/dist/chunk-KYFZTGMC.js +237 -0
  50. package/dist/chunk-KYFZTGMC.js.map +1 -0
  51. package/dist/chunk-LFZJM56J.js +159 -0
  52. package/dist/chunk-LFZJM56J.js.map +1 -0
  53. package/dist/chunk-LHHMV4GU.js +27 -0
  54. package/dist/chunk-LHHMV4GU.js.map +1 -0
  55. package/dist/{chunk-YBMMV4Y4.js → chunk-MEFB5KHA.js} +13 -5
  56. package/dist/chunk-MEFB5KHA.js.map +1 -0
  57. package/dist/{chunk-NCE5NSN6.js → chunk-N35E6CM2.js} +140 -10
  58. package/dist/chunk-N35E6CM2.js.map +1 -0
  59. package/dist/chunk-NZIP4PA2.js +114 -0
  60. package/dist/chunk-NZIP4PA2.js.map +1 -0
  61. package/dist/chunk-O2FRQ2L2.js +168 -0
  62. package/dist/chunk-O2FRQ2L2.js.map +1 -0
  63. package/dist/chunk-OK2TDZQU.js +404 -0
  64. package/dist/chunk-OK2TDZQU.js.map +1 -0
  65. package/dist/chunk-ORWL5BSN.js +269 -0
  66. package/dist/chunk-ORWL5BSN.js.map +1 -0
  67. package/dist/{chunk-Z6MFJV5Z.js → chunk-OSYTBCUC.js} +850 -499
  68. package/dist/chunk-OSYTBCUC.js.map +1 -0
  69. package/dist/chunk-P7LABKCW.js +90 -0
  70. package/dist/chunk-P7LABKCW.js.map +1 -0
  71. package/dist/chunk-PAYV4XUA.js +151 -0
  72. package/dist/chunk-PAYV4XUA.js.map +1 -0
  73. package/dist/{chunk-ZABPQJ3M.js → chunk-POUWHWID.js} +2 -2
  74. package/dist/chunk-QUVVWYJW.js +112 -0
  75. package/dist/chunk-QUVVWYJW.js.map +1 -0
  76. package/dist/chunk-RAULEAZ6.js +228 -0
  77. package/dist/chunk-RAULEAZ6.js.map +1 -0
  78. package/dist/chunk-S4SAZ7OD.js +30 -0
  79. package/dist/chunk-S4SAZ7OD.js.map +1 -0
  80. package/dist/chunk-SJLTEINJ.js +117 -0
  81. package/dist/chunk-SJLTEINJ.js.map +1 -0
  82. package/dist/chunk-SPAVAYSW.js +125 -0
  83. package/dist/chunk-SPAVAYSW.js.map +1 -0
  84. package/dist/chunk-TTBKWWTV.js +1605 -0
  85. package/dist/chunk-TTBKWWTV.js.map +1 -0
  86. package/dist/{chunk-RRN3YTK7.js → chunk-TTNESUPQ.js} +3 -3
  87. package/dist/chunk-U6YQ6FRI.js +378 -0
  88. package/dist/chunk-U6YQ6FRI.js.map +1 -0
  89. package/dist/chunk-VFMQTSXG.js +29 -0
  90. package/dist/chunk-VFMQTSXG.js.map +1 -0
  91. package/dist/chunk-VUFAK2LW.js +115 -0
  92. package/dist/chunk-VUFAK2LW.js.map +1 -0
  93. package/dist/chunk-VZGAONSJ.js +194 -0
  94. package/dist/chunk-VZGAONSJ.js.map +1 -0
  95. package/dist/{chunk-OYMYCW7J.js → chunk-WO5BJNIB.js} +682 -53
  96. package/dist/chunk-WO5BJNIB.js.map +1 -0
  97. package/dist/chunk-WVUSXNIE.js +39 -0
  98. package/dist/chunk-WVUSXNIE.js.map +1 -0
  99. package/dist/chunk-XKESD27X.js +10 -0
  100. package/dist/chunk-XKESD27X.js.map +1 -0
  101. package/dist/{chunk-HSDCI7OV.js → chunk-XZKD7DIF.js} +3 -3
  102. package/dist/{chunk-XJIW7USF.js → chunk-YFQOA5AU.js} +118 -9
  103. package/dist/chunk-YFQOA5AU.js.map +1 -0
  104. package/dist/chunk-YHKXNYTB.js +105 -0
  105. package/dist/chunk-YHKXNYTB.js.map +1 -0
  106. package/dist/{cli-SBXI5AMS.js → cli-O5SN7ZJ4.js} +382 -214
  107. package/dist/cli-O5SN7ZJ4.js.map +1 -0
  108. package/dist/config-OJQI27LT.js +45 -0
  109. package/dist/dist-3LOO6M4U.js +2842 -0
  110. package/dist/dist-3LOO6M4U.js.map +1 -0
  111. package/dist/doctor-IQQJHGGM.js +590 -0
  112. package/dist/doctor-IQQJHGGM.js.map +1 -0
  113. package/dist/env-proxy-XL4P73MZ.js +15 -0
  114. package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
  115. package/dist/fund-WEV6DMTD.js +365 -0
  116. package/dist/fund-WEV6DMTD.js.map +1 -0
  117. package/dist/hook-command-D2P3ILRV.js +32 -0
  118. package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
  119. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +14 -0
  120. package/dist/hosts/claude/tenjin/.mcp.json +12 -0
  121. package/dist/hosts/claude/tenjin/hooks/hooks.json +221 -0
  122. package/dist/index.js +21 -2
  123. package/dist/index.js.map +1 -1
  124. package/dist/install-TUCRF32I.js +60 -0
  125. package/dist/install-identity-WHPNMNMQ.js +26 -0
  126. package/dist/install-wallet-MA27FTQ5.js +113 -0
  127. package/dist/install-wallet-MA27FTQ5.js.map +1 -0
  128. package/dist/mcp-QML7ZMPH.js +13427 -0
  129. package/dist/mcp-QML7ZMPH.js.map +1 -0
  130. package/dist/package-LGKYOEPV.js +37 -0
  131. package/dist/package-LGKYOEPV.js.map +1 -0
  132. package/dist/paths-POPTXJO6.js +61 -0
  133. package/dist/paths-POPTXJO6.js.map +1 -0
  134. package/dist/pay-2C2UBBXJ.js +51 -0
  135. package/dist/pay-2C2UBBXJ.js.map +1 -0
  136. package/dist/payments-C44QUFXU.js +106 -0
  137. package/dist/payments-C44QUFXU.js.map +1 -0
  138. package/dist/redact-6W23GGJC.js +15 -0
  139. package/dist/redact-6W23GGJC.js.map +1 -0
  140. package/dist/{secp256k1-N3ZHU7LB.js → secp256k1-ZZZT2CAX.js} +3 -3
  141. package/dist/secp256k1-ZZZT2CAX.js.map +1 -0
  142. package/dist/send-KVJX4XIR.js +222 -0
  143. package/dist/send-KVJX4XIR.js.map +1 -0
  144. package/dist/status-S7C3WMSH.js +115 -0
  145. package/dist/status-S7C3WMSH.js.map +1 -0
  146. package/dist/status-line-YR2T5HC4.js +86 -0
  147. package/dist/status-line-YR2T5HC4.js.map +1 -0
  148. package/dist/uninstall-HY6LKIIT.js +149 -0
  149. package/dist/uninstall-HY6LKIIT.js.map +1 -0
  150. package/dist/update-OJV22LR3.js +36 -0
  151. package/dist/update-OJV22LR3.js.map +1 -0
  152. package/dist/usdc-JK4RRFFQ.js +39 -0
  153. package/dist/usdc-JK4RRFFQ.js.map +1 -0
  154. package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
  155. package/dist/viemAdapter-By13KInL-X2VY6CY3.js.map +1 -0
  156. package/dist/wallet-PD2IMZDU.js +39 -0
  157. package/dist/wallet-PD2IMZDU.js.map +1 -0
  158. package/dist/wallet-kdf-worker.mjs +980 -0
  159. package/docs/agent-permissions.md +180 -0
  160. package/docs/safety-model.md +59 -0
  161. package/docs/troubleshooting.md +13 -0
  162. package/package.json +28 -19
  163. package/LICENSE +0 -21
  164. package/dist/buy-EE6SEXP6.js +0 -1598
  165. package/dist/buy-EE6SEXP6.js.map +0 -1
  166. package/dist/candidate-ERMSYYQZ.js +0 -127
  167. package/dist/candidate-ERMSYYQZ.js.map +0 -1
  168. package/dist/chunk-3OV7E5G5.js +0 -18
  169. package/dist/chunk-3OV7E5G5.js.map +0 -1
  170. package/dist/chunk-4ONXEEQL.js +0 -152
  171. package/dist/chunk-4ONXEEQL.js.map +0 -1
  172. package/dist/chunk-662MSGZB.js +0 -286
  173. package/dist/chunk-662MSGZB.js.map +0 -1
  174. package/dist/chunk-7KUW4MJD.js +0 -59
  175. package/dist/chunk-7KUW4MJD.js.map +0 -1
  176. package/dist/chunk-AWPAWHNX.js +0 -333
  177. package/dist/chunk-AWPAWHNX.js.map +0 -1
  178. package/dist/chunk-DXTQ3CSI.js +0 -171
  179. package/dist/chunk-DXTQ3CSI.js.map +0 -1
  180. package/dist/chunk-ESPNTPQ2.js +0 -207
  181. package/dist/chunk-ESPNTPQ2.js.map +0 -1
  182. package/dist/chunk-FJPLRISB.js +0 -79
  183. package/dist/chunk-FJPLRISB.js.map +0 -1
  184. package/dist/chunk-GO75V3NZ.js +0 -160
  185. package/dist/chunk-GO75V3NZ.js.map +0 -1
  186. package/dist/chunk-JPHG2JW3.js +0 -96
  187. package/dist/chunk-JPHG2JW3.js.map +0 -1
  188. package/dist/chunk-MUBUQVC3.js +0 -67
  189. package/dist/chunk-MUBUQVC3.js.map +0 -1
  190. package/dist/chunk-NCE5NSN6.js.map +0 -1
  191. package/dist/chunk-OYMYCW7J.js.map +0 -1
  192. package/dist/chunk-RY4XKNV3.js +0 -140
  193. package/dist/chunk-RY4XKNV3.js.map +0 -1
  194. package/dist/chunk-S3IGX57D.js.map +0 -1
  195. package/dist/chunk-TLCMMYLY.js +0 -126
  196. package/dist/chunk-TLCMMYLY.js.map +0 -1
  197. package/dist/chunk-UO22YNY4.js +0 -69
  198. package/dist/chunk-UO22YNY4.js.map +0 -1
  199. package/dist/chunk-XHC6FCGZ.js +0 -261
  200. package/dist/chunk-XHC6FCGZ.js.map +0 -1
  201. package/dist/chunk-XJIW7USF.js.map +0 -1
  202. package/dist/chunk-YBMMV4Y4.js.map +0 -1
  203. package/dist/chunk-YN5SHIXQ.js +0 -126
  204. package/dist/chunk-YN5SHIXQ.js.map +0 -1
  205. package/dist/chunk-Z52RA3NC.js +0 -137
  206. package/dist/chunk-Z52RA3NC.js.map +0 -1
  207. package/dist/chunk-Z6MFJV5Z.js.map +0 -1
  208. package/dist/cli-SBXI5AMS.js.map +0 -1
  209. package/dist/config-VELDKLHY.js +0 -21
  210. package/dist/doctor-T3KWNNP2.js +0 -20
  211. package/dist/inspect-LMKOXE4Y.js +0 -96
  212. package/dist/inspect-LMKOXE4Y.js.map +0 -1
  213. package/dist/install-LEX3ENQ6.js +0 -387
  214. package/dist/install-LEX3ENQ6.js.map +0 -1
  215. package/dist/lookup-ZPN2Q67N.js +0 -129
  216. package/dist/lookup-ZPN2Q67N.js.map +0 -1
  217. package/dist/outcome-N7TAK6WR.js +0 -66
  218. package/dist/outcome-N7TAK6WR.js.map +0 -1
  219. package/dist/publish-BKBQQAW4.js +0 -1478
  220. package/dist/publish-BKBQQAW4.js.map +0 -1
  221. package/dist/usdc-JIAJW4SV.js +0 -22
  222. package/dist/wallet-CWEMYVIH.js +0 -179
  223. package/dist/wallet-CWEMYVIH.js.map +0 -1
  224. package/dist/wallet-PA54CRBL.js +0 -30
  225. package/skills/tenjin/SKILL.md +0 -199
  226. package/skills/tenjin-publish/SKILL.md +0 -111
  227. package/skills/tenjin-search/SKILL.md +0 -133
  228. /package/dist/{_esm-FEASBWRP.js.map → _esm-CE7KNONL.js.map} +0 -0
  229. /package/dist/{ccip-NQXCEK2U.js.map → alive-3J3CHOQP.js.map} +0 -0
  230. /package/dist/{ccip-XR5NE5QK.js.map → ccip-7RMRLAGV.js.map} +0 -0
  231. /package/dist/{config-VELDKLHY.js.map → ccip-NLCSCHKI.js.map} +0 -0
  232. /package/dist/{chunk-ZMHYXMO6.js.map → chunk-5IEP5EGE.js.map} +0 -0
  233. /package/dist/{chunk-5CLSD5YN.js.map → chunk-BPMWXTFX.js.map} +0 -0
  234. /package/dist/{chunk-YALGASEU.js.map → chunk-EGELTSPU.js.map} +0 -0
  235. /package/dist/{chunk-CYOF7ROH.js.map → chunk-HPWO4O6S.js.map} +0 -0
  236. /package/dist/{chunk-QVX5MWJZ.js.map → chunk-JRGFKVAZ.js.map} +0 -0
  237. /package/dist/{chunk-HIVZG55D.js.map → chunk-KG3D7FIF.js.map} +0 -0
  238. /package/dist/{chunk-ZABPQJ3M.js.map → chunk-POUWHWID.js.map} +0 -0
  239. /package/dist/{chunk-RRN3YTK7.js.map → chunk-TTNESUPQ.js.map} +0 -0
  240. /package/dist/{chunk-HSDCI7OV.js.map → chunk-XZKD7DIF.js.map} +0 -0
  241. /package/dist/{doctor-T3KWNNP2.js.map → config-OJQI27LT.js.map} +0 -0
  242. /package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js.map → env-proxy-XL4P73MZ.js.map} +0 -0
  243. /package/dist/{secp256k1-N3ZHU7LB.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
  244. /package/dist/{usdc-JIAJW4SV.js.map → hook-command-D2P3ILRV.js.map} +0 -0
  245. /package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js.map → install-TUCRF32I.js.map} +0 -0
  246. /package/dist/{wallet-PA54CRBL.js.map → install-identity-WHPNMNMQ.js.map} +0 -0
@@ -0,0 +1,237 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ CliError,
4
+ external_exports
5
+ } from "./chunk-WO5BJNIB.js";
6
+
7
+ // src/lib/output.ts
8
+ import { WriteStream } from "node:tty";
9
+ import { styleText } from "node:util";
10
+
11
+ // src/schemas.ts
12
+ var SCHEMA_VERSION = 1;
13
+ var ErrorCodeSchema = external_exports.enum([
14
+ "NODE_UNSUPPORTED",
15
+ "USAGE",
16
+ "CONFIG_INVALID",
17
+ "WALLET_EXISTS",
18
+ "WALLET_MISSING",
19
+ "WALLET_INVALID_KEY",
20
+ "PROVIDER_ERROR",
21
+ "RPC_ERROR",
22
+ "API_UNREACHABLE",
23
+ "CONTRACT_MISMATCH",
24
+ "REFUSED",
25
+ "NETWORK_ERROR",
26
+ "INTERNAL",
27
+ "NOT_IMPLEMENTED",
28
+ // B2 (search/inspect/buy/outcome): a policy refusal (exit 3) has its own code
29
+ // so an agent can distinguish a spend-cap block from a generic REFUSED; a
30
+ // payment that failed after approval (exit 4) is PAYMENT_FAILED; the read
31
+ // route's own coded failures (402 preview parse, 409 gate) surface as these.
32
+ "POLICY_REFUSED",
33
+ "PAYMENT_FAILED",
34
+ "RESOURCE_NOT_FOUND",
35
+ "SEARCH_NOT_FOUND",
36
+ // A 429 from the anonymous search/outcome/read limits; error.details carries
37
+ // retryAfterSeconds so a looping agent can back off instead of hammering.
38
+ "RATE_LIMITED",
39
+ // B3 (publish): a publish that needs the human's yes (exit 3) — soft scan
40
+ // findings, or `review` mode always. NEEDS_CONFIRMATION clears with --yes;
41
+ // PUBLISH_BLOCKED is a hard-block finding (a live secret) that no mode or --yes
42
+ // ever clears. PUBLISH_FAILED (exit 4) is a write that failed AFTER approval,
43
+ // mirroring PAYMENT_FAILED's post-decision failure class.
44
+ "NEEDS_CONFIRMATION",
45
+ "PUBLISH_BLOCKED",
46
+ "PUBLISH_FAILED",
47
+ // A send that reverted or produced no receipt AFTER the human approved it and
48
+ // it was broadcast (exit 4), same post-decision class as PAYMENT_FAILED.
49
+ "SEND_FAILED",
50
+ // `tenjin delete`: the soft-delete failed AFTER the human confirmed it (exit
51
+ // 4). Its own code rather than PUBLISH_FAILED because the two say opposite
52
+ // things about what is now live, and an agent reporting the outcome to a user
53
+ // must not read "the piece is still up" as "the piece went up".
54
+ "DELETE_FAILED",
55
+ // `tenjin update`: the npm install it spawned exited nonzero or never started.
56
+ // Exit 1, not the post-decision class: nothing is half-written that the
57
+ // operator must reconcile, and the old build keeps running.
58
+ "UPDATE_FAILED",
59
+ // `tenjin pay` Bazaar lane: the live 402 does not match what a configured
60
+ // registry publicly advertises for this resource (understood-but-refused, 3);
61
+ // nothing was signed and nothing was spent.
62
+ "REGISTRY_MISMATCH",
63
+ // The seller's 402 challenge exceeds this process's response-header limit, so
64
+ // its terms could never be read (understood-but-refused, 3). Nothing was
65
+ // signed and nothing was sent; a retry changes nothing without an operator
66
+ // raising `--max-http-header-size` on the process that runs the CLI.
67
+ "CHALLENGE_TOO_LARGE"
68
+ ]);
69
+ var MoneySchema = external_exports.object({
70
+ atomic: external_exports.string(),
71
+ usd: external_exports.string()
72
+ });
73
+ var OutputErrorSchema = external_exports.object({
74
+ code: ErrorCodeSchema,
75
+ message: external_exports.string(),
76
+ fix: external_exports.string().optional(),
77
+ details: external_exports.unknown().optional()
78
+ });
79
+ var UpdateAvailableSchema = external_exports.object({
80
+ current: external_exports.string(),
81
+ latest: external_exports.string()
82
+ });
83
+ var SuccessEnvelopeSchema = external_exports.object({
84
+ schemaVersion: external_exports.literal(SCHEMA_VERSION),
85
+ command: external_exports.string(),
86
+ ok: external_exports.literal(true),
87
+ data: external_exports.unknown(),
88
+ /** Present only when a newer version is known and update.mode is not `off`. */
89
+ updateAvailable: UpdateAvailableSchema.optional()
90
+ });
91
+ var FailureEnvelopeSchema = external_exports.object({
92
+ schemaVersion: external_exports.literal(SCHEMA_VERSION),
93
+ command: external_exports.string(),
94
+ ok: external_exports.literal(false),
95
+ error: OutputErrorSchema,
96
+ updateAvailable: UpdateAvailableSchema.optional()
97
+ });
98
+ var OutputEnvelopeSchema = external_exports.discriminatedUnion("ok", [
99
+ SuccessEnvelopeSchema,
100
+ FailureEnvelopeSchema
101
+ ]);
102
+
103
+ // src/lib/output.ts
104
+ function defaultIo() {
105
+ return {
106
+ stdin: { stream: process.stdin, isTTY: Boolean(process.stdin.isTTY) },
107
+ stdout: process.stdout,
108
+ stderr: process.stderr,
109
+ isTTY: Boolean(process.stdout.isTTY)
110
+ };
111
+ }
112
+ function buildSuccessEnvelope(command, data, updateAvailable) {
113
+ return {
114
+ schemaVersion: SCHEMA_VERSION,
115
+ command,
116
+ ok: true,
117
+ data,
118
+ ...updateAvailable != null ? { updateAvailable } : {}
119
+ };
120
+ }
121
+ function buildFailureEnvelope(command, err, updateAvailable) {
122
+ const error = {
123
+ code: err.code,
124
+ message: err.message,
125
+ ...err.fix !== void 0 ? { fix: err.fix } : {},
126
+ ...err.details !== void 0 ? { details: err.details } : {}
127
+ };
128
+ return {
129
+ schemaVersion: SCHEMA_VERSION,
130
+ command,
131
+ ok: false,
132
+ error,
133
+ ...updateAvailable != null ? { updateAvailable } : {}
134
+ };
135
+ }
136
+ function emitSuccess(io, command, data, humanLines = [], opts = {}) {
137
+ if (humanMode(io, opts)) {
138
+ writeLines(io.stdout, humanLines);
139
+ return;
140
+ }
141
+ writeJson(io.stdout, buildSuccessEnvelope(command, data, opts.updateAvailable));
142
+ }
143
+ function emitFailure(io, command, err, opts = {}) {
144
+ const cliErr = normalizeError(err);
145
+ if (humanMode(io, opts)) {
146
+ const lines = [paint(io, "red", `error: ${sanitizeForTerminal(cliErr.message)}`)];
147
+ if (cliErr.fix !== void 0) {
148
+ lines.push(paint(io, "dim", `fix: ${sanitizeForTerminal(cliErr.fix)}`));
149
+ }
150
+ lines.push(...findingLines(io, cliErr.details));
151
+ writeLines(io.stdout, lines);
152
+ return cliErr;
153
+ }
154
+ writeJson(io.stdout, buildFailureEnvelope(command, cliErr, opts.updateAvailable));
155
+ return cliErr;
156
+ }
157
+ function emitNotice(io, text, opts = {}) {
158
+ if (!humanMode(io, opts)) return;
159
+ io.stderr.write(`${paint(io, "dim", sanitizeForTerminal(text))}
160
+ `);
161
+ }
162
+ function emitWriteNotice(io, text) {
163
+ io.stderr.write(`${paint(io, "dim", sanitizeForTerminal(text))}
164
+ `);
165
+ }
166
+ var ANSI_ESCAPE_RE = (
167
+ // eslint-disable-next-line no-control-regex
168
+ /\x1b(?:\[[0-9;?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-Z\\-_])/g
169
+ );
170
+ function sanitizeForTerminal(text) {
171
+ return text.replace(ANSI_ESCAPE_RE, "").replace(/[\x00-\x08\x0a-\x1f\x7f-\x9f]/g, "").replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, "").replace(
172
+ /(\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F})|[\u{E0000}-\u{E007F}\u{FEFF}]/gu,
173
+ (_match, rgiFlag) => rgiFlag ?? ""
174
+ );
175
+ }
176
+ function normalizeError(err) {
177
+ if (err instanceof CliError) return err;
178
+ if (err instanceof Error) return new CliError("INTERNAL", err.message, { cause: err });
179
+ return new CliError("INTERNAL", "Unexpected error", { details: err });
180
+ }
181
+ function humanMode(io, opts) {
182
+ return io.isTTY && opts.json !== true;
183
+ }
184
+ function findingLines(io, details) {
185
+ if (typeof details !== "object" || details === null || !("findings" in details)) return [];
186
+ const { findings } = details;
187
+ if (!Array.isArray(findings) || findings.length === 0) return [];
188
+ const rendered = [];
189
+ for (const f of findings) {
190
+ if (typeof f !== "object" || f === null) continue;
191
+ const { check, line, excerpt, source, severity } = f;
192
+ if (typeof check !== "string" || typeof line !== "number" || typeof excerpt !== "string") {
193
+ continue;
194
+ }
195
+ const from = source === "server" ? " [server]" : source === "both" ? " [local+server]" : "";
196
+ const tier = typeof severity === "string" && severity.length > 0 ? `${severity}, ` : "";
197
+ rendered.push(
198
+ paint(
199
+ io,
200
+ "dim",
201
+ ` ${sanitizeForTerminal(check)}${from} (${sanitizeForTerminal(tier)}line ${line}): ${sanitizeForTerminal(excerpt)}`
202
+ )
203
+ );
204
+ }
205
+ return rendered;
206
+ }
207
+ function writeJson(stream, value) {
208
+ stream.write(`${JSON.stringify(value, null, 2)}
209
+ `);
210
+ }
211
+ function writeLines(stream, lines) {
212
+ if (lines.length > 0) stream.write(`${lines.join("\n")}
213
+ `);
214
+ }
215
+ function colorCapable(stream, env = process.env) {
216
+ const force = env.FORCE_COLOR;
217
+ if (force !== void 0) return ["", "1", "true", "2", "3"].includes(force);
218
+ return stream instanceof WriteStream && stream.isTTY && stream.getColorDepth(env) > 2;
219
+ }
220
+ function style(format, text, stream = process.stdout) {
221
+ return colorCapable(stream) ? styleText(format, text, { validateStream: false }) : text;
222
+ }
223
+ function paint(io, format, text) {
224
+ return style(format, text, io.stdout);
225
+ }
226
+
227
+ export {
228
+ defaultIo,
229
+ emitSuccess,
230
+ emitFailure,
231
+ emitNotice,
232
+ emitWriteNotice,
233
+ sanitizeForTerminal,
234
+ style,
235
+ paint
236
+ };
237
+ //# sourceMappingURL=chunk-KYFZTGMC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/output.ts","../src/schemas.ts"],"sourcesContent":["import { WriteStream } from 'node:tty';\nimport { styleText } from 'node:util';\nimport { CliError } from './errors';\nimport type { StdinInput } from './stdin';\nimport { SCHEMA_VERSION } from '../schemas';\nimport type { UpdateAvailable } from '../schemas';\nimport type { FailureEnvelope, OutputError, SuccessEnvelope } from '../schemas';\n\n/**\n * Injected streams + TTY facts. Every command receives one via CommandContext,\n * so tests drive the CLI in-process with memory buffers and no child process.\n * `isTTY` describes stdout; the separate `--json` flag (passed to the emit\n * functions) is what suppresses human rendering — the two are ANDed, never\n * conflated, so `--json` on a TTY still yields pure machine output. `stdin` is\n * optional for compatibility with command-core contexts that never read it;\n * defaultIo supplies the real stream, and only the CLI forwards that capability\n * to commands that accept Markdown on stdin.\n */\nexport interface Io {\n stdin?: StdinInput;\n stdout: NodeJS.WritableStream;\n stderr: NodeJS.WritableStream;\n isTTY: boolean;\n}\n\nexport function defaultIo(): Io {\n return {\n stdin: { stream: process.stdin, isTTY: Boolean(process.stdin.isTTY) },\n stdout: process.stdout,\n stderr: process.stderr,\n isTTY: Boolean(process.stdout.isTTY),\n };\n}\n\nexport interface EmitOptions {\n /** The global --json flag. When true, the JSON envelope is emitted even at a TTY. */\n json?: boolean;\n /**\n * \"A newer tenjin-cli exists\", from the daily check's cache. Rides the\n * envelope so the AGENT running the command learns it; the human at a TTY\n * gets the dim stderr line instead, and neither path fetches anything.\n */\n updateAvailable?: UpdateAvailable | null;\n}\n\n/**\n * The two pure envelope builders, shared by the CLI's emit functions and the MCP\n * adapter so both surfaces produce the identical wire object by construction. They\n * hold no I/O and no --json branching: they turn a (command, data) or a normalized\n * CliError into the exact object that goes to stdout / structuredContent.\n */\nexport function buildSuccessEnvelope(\n command: string,\n data: unknown,\n updateAvailable?: UpdateAvailable | null,\n): SuccessEnvelope {\n return {\n schemaVersion: SCHEMA_VERSION,\n command,\n ok: true,\n data,\n ...(updateAvailable != null ? { updateAvailable: updateAvailable } : {}),\n };\n}\n\nexport function buildFailureEnvelope(\n command: string,\n err: CliError,\n updateAvailable?: UpdateAvailable | null,\n): FailureEnvelope {\n const error: OutputError = {\n code: err.code,\n message: err.message,\n ...(err.fix !== undefined ? { fix: err.fix } : {}),\n ...(err.details !== undefined ? { details: err.details } : {}),\n };\n return {\n schemaVersion: SCHEMA_VERSION,\n command,\n ok: false,\n error,\n ...(updateAvailable != null ? { updateAvailable: updateAvailable } : {}),\n };\n}\n\n/**\n * Output contract (human-first): at a TTY without `--json`, print ONLY the human\n * rendering to stdout, no JSON envelope. With `--json`, or when stdout is not a\n * TTY (a pipe, an agent), print exactly one JSON envelope to stdout and nothing\n * else. Exit codes are identical on both paths; only the stdout shape differs.\n */\nexport function emitSuccess(\n io: Io,\n command: string,\n data: unknown,\n humanLines: string[] = [],\n opts: EmitOptions = {},\n): void {\n if (humanMode(io, opts)) {\n writeLines(io.stdout, humanLines);\n return;\n }\n writeJson(io.stdout, buildSuccessEnvelope(command, data, opts.updateAvailable));\n}\n\n/**\n * The failure half of the same contract: at a TTY without `--json`, a red error\n * line plus a `fix` line to stdout and no envelope; otherwise exactly one failure\n * envelope to stdout. Accepts a CliError or any thrown value (non-CliError\n * normalizes to INTERNAL). Returns the normalized CliError so the caller reads its\n * `exitCode`.\n */\nexport function emitFailure(\n io: Io,\n command: string,\n err: unknown,\n opts: EmitOptions = {},\n): CliError {\n const cliErr = normalizeError(err);\n if (humanMode(io, opts)) {\n // Error messages can embed server-sourced text (api error passthrough) and\n // never carry intentional ANSI, so sanitize before painting.\n const lines = [paint(io, 'red', `error: ${sanitizeForTerminal(cliErr.message)}`)];\n if (cliErr.fix !== undefined) {\n lines.push(paint(io, 'dim', `fix: ${sanitizeForTerminal(cliErr.fix)}`));\n }\n // Scan findings are the one detail shape a human needs inline: without them\n // an interactive publish hitting NEEDS_CONFIRMATION / PUBLISH_BLOCKED sees\n // the count but not WHICH lines tripped. Every other shape is machine-only.\n lines.push(...findingLines(io, cliErr.details));\n writeLines(io.stdout, lines);\n return cliErr;\n }\n writeJson(io.stdout, buildFailureEnvelope(command, cliErr, opts.updateAvailable));\n return cliErr;\n}\n\n/**\n * One dim advisory line on stderr, human mode only. This is for facts that belong\n * to NO command's result — an unreadable spend ledger, a newer release on npm —\n * so they can never join the envelope on stdout or reach a machine consumer at\n * all. Sanitized here rather than by each caller: what these lines quote (a\n * registry version string, a parse error) is not the command's own prose.\n */\nexport function emitNotice(io: Io, text: string, opts: EmitOptions = {}): void {\n if (!humanMode(io, opts)) return;\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * The same dim stderr line, delivered whatever the surface is: no TTY gate and no\n * `--json` gate. Only for an advisory a piped or agent-driven run must not miss,\n * which today is two things: a WRITE to the operator's own files, and `fund`'s\n * checkout link, which expires long before the stdout envelope that also carries\n * it is written. Anything a piped run can simply do without belongs in\n * {@link emitNotice} instead. stdout is untouched either way, so the exactly-one\n * JSON object contract is unaffected.\n */\nexport function emitWriteNotice(io: Io, text: string): void {\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * Every escape sequence a terminal writes: CSI (colour, cursor), OSC — which\n * covers the OSC-8 hyperlinks pnpm wraps package names in, terminated by BEL\n * or ST — charset selection, and a stray ESC with a single final byte.\n *\n * ONE COPY, because the other reader is the failure lane: `stripAnsi`\n * (`hooks/text.ts`) takes colour off a runner's output before the arm scans it\n * for a diagnostic, and a pattern that misses OSC-8 leaves `]8;;https://…`\n * sitting in front of the very line the start-anchored markers must match.\n * That reader CANNOT call {@link sanitizeForTerminal}: this is only its first\n * clause, and the second strips `\\n`, which would flatten the output it is\n * about to split into lines.\n *\n * Safe to share despite the `g` flag: both callers use it through\n * `String.replace`, which starts at 0 and resets `lastIndex`. Do not `test()`\n * or `exec()` it.\n */\nexport const ANSI_ESCAPE_RE =\n // eslint-disable-next-line no-control-regex\n /\\x1b(?:\\[[0-9;?]*[ -/]*[@-~]|\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)|[@-Z\\\\-_])/g;\n\n/**\n * Strip ANSI escape sequences, C0/C1 control characters, Unicode bidirectional\n * formatting, and invisible tag/BOM characters from a string headed for a\n * terminal. Commands apply this to every SERVER-sourced string (titles,\n * handles) they put into human lines or the buy confirm prompt; without it a\n * malicious deployment could use cursor-movement escapes to overwrite the very\n * price a human is being asked to confirm, a right-to-left override to reorder\n * that same line on screen into one that reads as a different price, or tag\n * characters to carry a payload that draws as nothing at all. It is not\n * applied to whole human lines here because trusted callers (doctor) paint\n * their own ANSI colors. JSON stdout is untouched: JSON.stringify escapes C0\n * controls itself, but the bidi and tag/BOM sets ride through it raw, and that\n * is deliberate rather than covered — the envelope is machine-read data whose\n * bytes must be what the server said, and a consumer reading codepoints is not\n * deceived by rendering order the way a human reading a drawn line is.\n */\nexport function sanitizeForTerminal(text: string): string {\n return (\n text\n // CSI/OSC/charset escape sequences first, then any stray ESC and the rest\n // of C0 (except \\t) plus DEL and the C1 range.\n .replace(ANSI_ESCAPE_RE, '')\n // eslint-disable-next-line no-control-regex\n .replace(/[\\x00-\\x08\\x0a-\\x1f\\x7f-\\x9f]/g, '')\n // The UAX#9 directional formatting set: the marks (LRM/RLM/ALM), the\n // embeddings and overrides (U+202A-U+202E), and the isolates\n // (U+2066-U+2069). Removed, not escaped, so what a human reads is the\n // order the bytes are in. Deliberately this set and NOT all of category\n // Cf: U+200D (ZWJ) joins legitimate emoji sequences, and dropping it\n // would corrupt honest titles to defend against dishonest ones.\n .replace(/[\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g, '')\n // The Unicode tag block (U+E0000-U+E007F) and the BOM/ZWNBSP, neither of\n // which has a legitimate mid-title use. Tag characters render as nothing\n // at all, so a payload spelled in them is invisible in the line a human\n // is reading and in the line they would paste back to report it.\n //\n // The three RGI subdivision flags are the exception and survive\n // byte-identical: they are ordinary title content. The whitelist is those\n // three sequences and NOT \"any well-formed tag sequence\", because a\n // non-RGI sequence draws as a bare black flag with the payload hidden\n // behind it, which is the exact channel this closes.\n //\n // Kept for the same reason as ZWJ above: U+200B (ZWSP) hints line breaks\n // in CJK and U+200C (ZWNJ) is orthographically required in Persian, so\n // stripping them would corrupt honest titles to defend against dishonest\n // ones.\n .replace(\n /(\\u{1F3F4}\\u{E0067}\\u{E0062}(?:\\u{E0065}\\u{E006E}\\u{E0067}|\\u{E0073}\\u{E0063}\\u{E0074}|\\u{E0077}\\u{E006C}\\u{E0073})\\u{E007F})|[\\u{E0000}-\\u{E007F}\\u{FEFF}]/gu,\n (_match, rgiFlag: string | undefined) => rgiFlag ?? '',\n )\n );\n}\n\n/**\n * The same strip, for text that ships to OTHER PEOPLE rather than to this\n * terminal: a post's title, its public excerpt, and every free-text field of the\n * answer card a buyer reads before paying.\n *\n * The threat is the same one {@link sanitizeForTerminal} closes, one hop further\n * out. None of this text is necessarily typed by the person publishing: a card\n * question can be prefilled from a stored search, and every field can arrive over\n * MCP from an agent that read them off a fetched page. `trim()` removes neither a\n * CSI sequence nor a right-to-left override, so without this a payload rides into\n * the marketplace and renders in every future reader's terminal.\n *\n * Newlines and tabs fold to a single space FIRST, because these are all\n * single-line display fields and a bare strip would join the words on either side\n * of a line break into one. NOT for the post BODY: that is the author's document,\n * markdown and all, and rewriting it is not this function's business.\n */\nexport function sanitizeWireText(text: string): string {\n return sanitizeForTerminal(text.replace(/[\\r\\n\\t]+/g, ' ')).trim();\n}\n\n/** CliError passes through; every other thrown value becomes an INTERNAL CliError. */\nexport function normalizeError(err: unknown): CliError {\n if (err instanceof CliError) return err;\n if (err instanceof Error) return new CliError('INTERNAL', err.message, { cause: err });\n return new CliError('INTERNAL', 'Unexpected error', { details: err });\n}\n\n/** True in human-first mode: a TTY without --json. Otherwise the JSON envelope wins. */\nfunction humanMode(io: Io, opts: EmitOptions): boolean {\n return io.isTTY && opts.json !== true;\n}\n\n/**\n * Render `details.findings` (the scan-finding projection publish attaches to\n * NEEDS_CONFIRMATION / PUBLISH_BLOCKED) as one dim line per finding:\n * ` <check> (line N): <excerpt>`. The excerpt is already masked for secret\n * findings at the source; sanitize it anyway since it can echo file content.\n * Returns [] for any other details shape, so no other error leaks a detail dump.\n *\n * A finding the SERVER gate contributed carries a `source`, and the marker is\n * printed because it is the difference between \"fix your file\" and \"the\n * marketplace refused this\": the detector may be one this release predates, so\n * the line has to stand on the server's own words rather than on recognition.\n * The tier rides the same line, for the payloads that mix block and warn.\n */\nfunction findingLines(io: Io, details: unknown): string[] {\n if (typeof details !== 'object' || details === null || !('findings' in details)) return [];\n const { findings } = details as { findings: unknown };\n if (!Array.isArray(findings) || findings.length === 0) return [];\n const rendered: string[] = [];\n for (const f of findings) {\n if (typeof f !== 'object' || f === null) continue;\n const { check, line, excerpt, source, severity } = f as {\n check?: unknown;\n line?: unknown;\n excerpt?: unknown;\n source?: unknown;\n severity?: unknown;\n };\n if (typeof check !== 'string' || typeof line !== 'number' || typeof excerpt !== 'string') {\n continue;\n }\n const from = source === 'server' ? ' [server]' : source === 'both' ? ' [local+server]' : '';\n // THE TIER IS PRINTED because one payload can mix them: a `scan_blocked`\n // envelope ships the block finding alongside the warns the same pass found,\n // and without the tier nothing on the page says which one is the refusal.\n // An open string, sanitized like the rest: the server owns its own tier names.\n const tier = typeof severity === 'string' && severity.length > 0 ? `${severity}, ` : '';\n // The detector id is sanitized too: on a server finding it is a name this\n // release may never have seen, so it is untrusted text like the excerpt.\n rendered.push(\n paint(\n io,\n 'dim',\n ` ${sanitizeForTerminal(check)}${from} (${sanitizeForTerminal(tier)}line ${line}): ${sanitizeForTerminal(excerpt)}`,\n ),\n );\n }\n return rendered;\n}\n\nfunction writeJson(stream: NodeJS.WritableStream, value: unknown): void {\n stream.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nfunction writeLines(stream: NodeJS.WritableStream, lines: string[]): void {\n if (lines.length > 0) stream.write(`${lines.join('\\n')}\\n`);\n}\n\nexport type StyleFormat = Parameters<typeof styleText>[0];\n\n/**\n * Does `stream` take ANSI color? Node's own rule (`shouldColorize`): FORCE_COLOR\n * wins when set, otherwise a TTY whose color depth is above 2 (which reads\n * NO_COLOR, NODE_DISABLE_COLORS and TERM). Decided here because styleText only\n * checks the stream from Node 22.13 and colors unconditionally before it.\n */\nexport function colorCapable(stream: unknown, env: NodeJS.ProcessEnv = process.env): boolean {\n const force = env.FORCE_COLOR;\n if (force !== undefined) return ['', '1', 'true', '2', '3'].includes(force);\n return stream instanceof WriteStream && stream.isTTY && stream.getColorDepth(env) > 2;\n}\n\n/** `text` in `format` when `stream` takes color, else plain. */\nexport function style(format: StyleFormat, text: string, stream: unknown = process.stdout): string {\n return colorCapable(stream) ? styleText(format, text, { validateStream: false }) : text;\n}\n\n/** Color a human line for stdout. A test or redirected sink is no TTY, so it comes out plain. */\nexport function paint(io: Io, format: StyleFormat, text: string): string {\n return style(format, text, io.stdout);\n}\n","import { z } from 'zod';\n\n/**\n * Bumped only on a breaking change to any stdout envelope shape. Agents pin on\n * this: a consumer that sees an unexpected value should refuse to parse rather\n * than guess. Every envelope carries it, success or failure.\n */\nexport const SCHEMA_VERSION = 1;\n\n/**\n * The closed set of machine error codes. `error.code` in a failure envelope is\n * always one of these; agents branch on it, humans read `message`/`fix`. The\n * exit-code mapping lives in lib/errors.ts (this enum is the single source of\n * the code names both sides agree on).\n */\nexport const ErrorCodeSchema = z.enum([\n 'NODE_UNSUPPORTED',\n 'USAGE',\n 'CONFIG_INVALID',\n 'WALLET_EXISTS',\n 'WALLET_MISSING',\n 'WALLET_INVALID_KEY',\n 'PROVIDER_ERROR',\n 'RPC_ERROR',\n 'API_UNREACHABLE',\n 'CONTRACT_MISMATCH',\n 'REFUSED',\n 'NETWORK_ERROR',\n 'INTERNAL',\n 'NOT_IMPLEMENTED',\n // B2 (search/inspect/buy/outcome): a policy refusal (exit 3) has its own code\n // so an agent can distinguish a spend-cap block from a generic REFUSED; a\n // payment that failed after approval (exit 4) is PAYMENT_FAILED; the read\n // route's own coded failures (402 preview parse, 409 gate) surface as these.\n 'POLICY_REFUSED',\n 'PAYMENT_FAILED',\n 'RESOURCE_NOT_FOUND',\n 'SEARCH_NOT_FOUND',\n // A 429 from the anonymous search/outcome/read limits; error.details carries\n // retryAfterSeconds so a looping agent can back off instead of hammering.\n 'RATE_LIMITED',\n // B3 (publish): a publish that needs the human's yes (exit 3) — soft scan\n // findings, or `review` mode always. NEEDS_CONFIRMATION clears with --yes;\n // PUBLISH_BLOCKED is a hard-block finding (a live secret) that no mode or --yes\n // ever clears. PUBLISH_FAILED (exit 4) is a write that failed AFTER approval,\n // mirroring PAYMENT_FAILED's post-decision failure class.\n 'NEEDS_CONFIRMATION',\n 'PUBLISH_BLOCKED',\n 'PUBLISH_FAILED',\n // A send that reverted or produced no receipt AFTER the human approved it and\n // it was broadcast (exit 4), same post-decision class as PAYMENT_FAILED.\n 'SEND_FAILED',\n // `tenjin delete`: the soft-delete failed AFTER the human confirmed it (exit\n // 4). Its own code rather than PUBLISH_FAILED because the two say opposite\n // things about what is now live, and an agent reporting the outcome to a user\n // must not read \"the piece is still up\" as \"the piece went up\".\n 'DELETE_FAILED',\n // `tenjin update`: the npm install it spawned exited nonzero or never started.\n // Exit 1, not the post-decision class: nothing is half-written that the\n // operator must reconcile, and the old build keeps running.\n 'UPDATE_FAILED',\n // `tenjin pay` Bazaar lane: the live 402 does not match what a configured\n // registry publicly advertises for this resource (understood-but-refused, 3);\n // nothing was signed and nothing was spent.\n 'REGISTRY_MISMATCH',\n // The seller's 402 challenge exceeds this process's response-header limit, so\n // its terms could never be read (understood-but-refused, 3). Nothing was\n // signed and nothing was sent; a retry changes nothing without an operator\n // raising `--max-http-header-size` on the process that runs the CLI.\n 'CHALLENGE_TOO_LARGE',\n]);\nexport type ErrorCode = z.infer<typeof ErrorCodeSchema>;\n\n/**\n * All money in machine output is dual-form: `atomic` is the 6-decimal USDC base\n * unit as a decimal string (never a JS number — precision), `usd` is the same\n * value formatted as decimal dollars. Emit both so agents compute on `atomic`\n * and humans read `usd` without either side re-deriving the other.\n */\nexport const MoneySchema = z.object({\n atomic: z.string(),\n usd: z.string(),\n});\nexport type Money = z.infer<typeof MoneySchema>;\n\nexport const OutputErrorSchema = z.object({\n code: ErrorCodeSchema,\n message: z.string(),\n fix: z.string().optional(),\n details: z.unknown().optional(),\n});\nexport type OutputError = z.infer<typeof OutputErrorSchema>;\n\n/**\n * \"A newer tenjin-cli exists\", carried on the envelope so an AGENT learns it.\n *\n * The daily check's other surface is one dim stderr line, which only a human at\n * a terminal ever sees; on the machines that run this CLI most, nobody does.\n * This field is how the agent driving the command finds out it can run\n * `tenjin update` itself. Read from the check's cache, never fetched here: the\n * envelope must not wait on a network call it did not need.\n */\nexport const UpdateAvailableSchema = z.object({\n current: z.string(),\n latest: z.string(),\n});\nexport type UpdateAvailable = z.infer<typeof UpdateAvailableSchema>;\n\nexport const SuccessEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(true),\n data: z.unknown(),\n /** Present only when a newer version is known and update.mode is not `off`. */\n updateAvailable: UpdateAvailableSchema.optional(),\n});\nexport type SuccessEnvelope = z.infer<typeof SuccessEnvelopeSchema>;\n\nexport const FailureEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(false),\n error: OutputErrorSchema,\n updateAvailable: UpdateAvailableSchema.optional(),\n});\nexport type FailureEnvelope = z.infer<typeof FailureEnvelopeSchema>;\n\n/** The one thing every invocation prints to stdout, discriminated on `ok`. */\nexport const OutputEnvelopeSchema = z.discriminatedUnion('ok', [\n SuccessEnvelopeSchema,\n FailureEnvelopeSchema,\n]);\nexport type OutputEnvelope = z.infer<typeof OutputEnvelopeSchema>;\n"],"mappings":";;;;;;;AAAA,SAAS,mBAAmB;AAC5B,SAAS,iBAAiB;;;ACMnB,IAAM,iBAAiB;AAQvB,IAAM,kBAAkB,iBAAE,KAAK;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA,EAGA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA,EAGA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AACF,CAAC;AASM,IAAM,cAAc,iBAAE,OAAO;AAAA,EAClC,QAAQ,iBAAE,OAAO;AAAA,EACjB,KAAK,iBAAE,OAAO;AAChB,CAAC;AAGM,IAAM,oBAAoB,iBAA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AAa,YAAY,SAAS,SAAS,IAAI,GAAG,QAAQ,OAAO;AAGrF,aAAS;AAAA,MACP;AAAA,QACE;AAAA,QACA;AAAA,QACA,KAAK,oBAAoB,KAAK,CAAC,GAAG,IAAI,KAAK,oBAAoB,IAAI,CAAC,QAAQ,IAAI,MAAM,oBAAoB,OAAO,CAAC;AAAA,MACpH;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,UAAU,QAA+B,OAAsB;AACtE,SAAO,MAAM,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC;AAAA,CAAI;AACpD;AAEA,SAAS,WAAW,QAA+B,OAAuB;AACxE,MAAI,MAAM,SAAS,EAAG,QAAO,MAAM,GAAG,MAAM,KAAK,IAAI,CAAC;AAAA,CAAI;AAC5D;AAUO,SAAS,aAAa,QAAiB,MAAyB,QAAQ,KAAc;AAC3F,QAAM,QAAQ,IAAI;AAClB,MAAI,UAAU,OAAW,QAAO,CAAC,IAAI,KAAK,QAAQ,KAAK,GAAG,EAAE,SAAS,KAAK;AAC1E,SAAO,kBAAkB,eAAe,OAAO,SAAS,OAAO,cAAc,GAAG,IAAI;AACtF;AAGO,SAAS,MAAM,QAAqB,MAAc,SAAkB,QAAQ,QAAgB;AACjG,SAAO,aAAa,MAAM,IAAI,UAAU,QAAQ,MAAM,EAAE,gBAAgB,MAAM,CAAC,IAAI;AACrF;AAGO,SAAS,MAAM,IAAQ,QAAqB,MAAsB;AACvE,SAAO,MAAM,QAAQ,MAAM,GAAG,MAAM;AACtC;","names":[]}
@@ -0,0 +1,159 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ hashTypedData
4
+ } from "./chunk-EL56RW2J.js";
5
+ import {
6
+ getAddress,
7
+ keccak256,
8
+ toBytes,
9
+ toHex
10
+ } from "./chunk-TTNESUPQ.js";
11
+
12
+ // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-EKCH75YB.mjs
13
+ var EIP155_NETWORK_REGEX = /^eip155:(\d+)$/;
14
+ function getEvmChainId(network) {
15
+ if (!network.startsWith("eip155:")) {
16
+ throw new Error(`Unsupported network format: ${network} (expected eip155:CHAIN_ID)`);
17
+ }
18
+ const match = EIP155_NETWORK_REGEX.exec(network);
19
+ if (!match) {
20
+ throw new Error(`Invalid CAIP-2 chain ID: ${network}`);
21
+ }
22
+ const chainId = Number(match[1]);
23
+ if (!Number.isSafeInteger(chainId)) {
24
+ throw new Error(`Invalid CAIP-2 chain ID: ${network}`);
25
+ }
26
+ return chainId;
27
+ }
28
+ function getCrypto() {
29
+ const cryptoObj = globalThis.crypto;
30
+ if (!cryptoObj) {
31
+ throw new Error("Crypto API not available");
32
+ }
33
+ return cryptoObj;
34
+ }
35
+ function createNonce() {
36
+ return toHex(getCrypto().getRandomValues(new Uint8Array(32)));
37
+ }
38
+ function createPermit2Nonce() {
39
+ const randomBytes = getCrypto().getRandomValues(new Uint8Array(32));
40
+ return BigInt(toHex(randomBytes)).toString();
41
+ }
42
+
43
+ // node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/dist/esm/chunk-5XX3PMSD.mjs
44
+ var BATCH_SETTLEMENT_SCHEME = "batch-settlement";
45
+ var BATCH_SETTLEMENT_ADDRESS = "0x4020074e9dF2ce1deE5A9C1b5c3f541D02a10003";
46
+ var ERC3009_DEPOSIT_COLLECTOR_ADDRESS = "0x4020806089470a89826cB9fB1f4059150b550004";
47
+ var PERMIT2_DEPOSIT_COLLECTOR_ADDRESS = "0x4020425FAf3B746C082C2f942b4E5159887B0005";
48
+ var MIN_WITHDRAW_DELAY = 900;
49
+ var BATCH_SETTLEMENT_DOMAIN = {
50
+ name: "x402 Batch Settlement",
51
+ version: "1"
52
+ };
53
+ var CHANNEL_CONFIG_TYPEHASH = keccak256(
54
+ toBytes(
55
+ "ChannelConfig(address payer,address payerAuthorizer,address receiver,address receiverAuthorizer,address token,uint40 withdrawDelay,bytes32 salt)"
56
+ )
57
+ );
58
+ var channelConfigTypes = {
59
+ ChannelConfig: [
60
+ { name: "payer", type: "address" },
61
+ { name: "payerAuthorizer", type: "address" },
62
+ { name: "receiver", type: "address" },
63
+ { name: "receiverAuthorizer", type: "address" },
64
+ { name: "token", type: "address" },
65
+ { name: "withdrawDelay", type: "uint40" },
66
+ { name: "salt", type: "bytes32" }
67
+ ]
68
+ };
69
+ var voucherTypes = {
70
+ Voucher: [
71
+ { name: "channelId", type: "bytes32" },
72
+ { name: "maxClaimableAmount", type: "uint128" }
73
+ ]
74
+ };
75
+ var receiveAuthorizationTypes = {
76
+ ReceiveWithAuthorization: [
77
+ { name: "from", type: "address" },
78
+ { name: "to", type: "address" },
79
+ { name: "value", type: "uint256" },
80
+ { name: "validAfter", type: "uint256" },
81
+ { name: "validBefore", type: "uint256" },
82
+ { name: "nonce", type: "bytes32" }
83
+ ]
84
+ };
85
+ var batchPermit2WitnessTypes = {
86
+ PermitWitnessTransferFrom: [
87
+ { name: "permitted", type: "TokenPermissions" },
88
+ { name: "spender", type: "address" },
89
+ { name: "nonce", type: "uint256" },
90
+ { name: "deadline", type: "uint256" },
91
+ { name: "witness", type: "DepositWitness" }
92
+ ],
93
+ TokenPermissions: [
94
+ { name: "token", type: "address" },
95
+ { name: "amount", type: "uint256" }
96
+ ],
97
+ DepositWitness: [{ name: "channelId", type: "bytes32" }]
98
+ };
99
+ var ErrCumulativeAmountBelowClaimed = "invalid_batch_settlement_evm_cumulative_below_claimed";
100
+ var ErrInvalidChannelId = "invalid_batch_settlement_evm_channel_id_invalid";
101
+ var ErrCumulativeAmountMismatch = "invalid_batch_settlement_evm_cumulative_amount_mismatch";
102
+ var ErrRefundNoBalance = "invalid_batch_settlement_evm_refund_no_balance";
103
+ var ErrRefundAmountInvalid = "invalid_batch_settlement_evm_refund_amount_invalid";
104
+ var CHANNEL_ID_RE = /^0x[0-9a-fA-F]{64}$/;
105
+ function isCanonicalChannelId(value) {
106
+ return typeof value === "string" && CHANNEL_ID_RE.test(value);
107
+ }
108
+ function normalizeChannelId(channelId) {
109
+ if (!isCanonicalChannelId(channelId)) {
110
+ throw new Error(ErrInvalidChannelId);
111
+ }
112
+ return channelId.toLowerCase();
113
+ }
114
+ function computeChannelId(config, networkOrChainId) {
115
+ const chainId = typeof networkOrChainId === "number" ? networkOrChainId : getEvmChainId(networkOrChainId);
116
+ return hashTypedData({
117
+ domain: getBatchSettlementEip712Domain(chainId),
118
+ types: channelConfigTypes,
119
+ primaryType: "ChannelConfig",
120
+ message: {
121
+ payer: config.payer,
122
+ payerAuthorizer: config.payerAuthorizer,
123
+ receiver: config.receiver,
124
+ receiverAuthorizer: config.receiverAuthorizer,
125
+ token: config.token,
126
+ withdrawDelay: config.withdrawDelay,
127
+ salt: config.salt
128
+ }
129
+ });
130
+ }
131
+ function getBatchSettlementEip712Domain(chainId) {
132
+ return {
133
+ ...BATCH_SETTLEMENT_DOMAIN,
134
+ chainId,
135
+ verifyingContract: getAddress(BATCH_SETTLEMENT_ADDRESS)
136
+ };
137
+ }
138
+
139
+ export {
140
+ getEvmChainId,
141
+ createNonce,
142
+ createPermit2Nonce,
143
+ BATCH_SETTLEMENT_SCHEME,
144
+ BATCH_SETTLEMENT_ADDRESS,
145
+ ERC3009_DEPOSIT_COLLECTOR_ADDRESS,
146
+ PERMIT2_DEPOSIT_COLLECTOR_ADDRESS,
147
+ MIN_WITHDRAW_DELAY,
148
+ voucherTypes,
149
+ receiveAuthorizationTypes,
150
+ batchPermit2WitnessTypes,
151
+ ErrCumulativeAmountBelowClaimed,
152
+ ErrCumulativeAmountMismatch,
153
+ ErrRefundNoBalance,
154
+ ErrRefundAmountInvalid,
155
+ normalizeChannelId,
156
+ computeChannelId,
157
+ getBatchSettlementEip712Domain
158
+ };
159
+ //# sourceMappingURL=chunk-LFZJM56J.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/src/utils.ts","../node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/src/batch-settlement/constants.ts","../node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/src/batch-settlement/errors.ts","../node_modules/.pnpm/@x402+evm@2.28.0_typescript@6.0.3/node_modules/@x402/evm/src/batch-settlement/utils.ts"],"sourcesContent":["import type { Network, SettleResponse } from \"@x402/core/types\";\nimport { isHash, toHex } from \"viem\";\n\n/** CAIP-2 `eip155` reference: a bare decimal chain ID, matching the Go and Python SDKs. */\nconst EIP155_NETWORK_REGEX = /^eip155:(\\d+)$/;\n\n/**\n * Extract chain ID from a CAIP-2 network identifier (eip155:CHAIN_ID).\n *\n * @param network - The network identifier in CAIP-2 format (e.g., \"eip155:8453\")\n * @returns The numeric chain ID\n * @throws Error if the network format is invalid\n */\nexport function getEvmChainId(network: string): number {\n if (!network.startsWith(\"eip155:\")) {\n throw new Error(`Unsupported network format: ${network} (expected eip155:CHAIN_ID)`);\n }\n\n const match = EIP155_NETWORK_REGEX.exec(network);\n if (!match) {\n throw new Error(`Invalid CAIP-2 chain ID: ${network}`);\n }\n\n const chainId = Number(match[1]);\n if (!Number.isSafeInteger(chainId)) {\n throw new Error(`Invalid CAIP-2 chain ID: ${network}`);\n }\n\n return chainId;\n}\n\n/**\n * Get the crypto object from the global scope.\n *\n * @returns The crypto object\n * @throws Error if crypto API is not available\n */\nfunction getCrypto(): Crypto {\n const cryptoObj = globalThis.crypto as Crypto | undefined;\n if (!cryptoObj) {\n throw new Error(\"Crypto API not available\");\n }\n return cryptoObj;\n}\n\n/**\n * Create a random 32-byte nonce for EIP-3009 authorization.\n *\n * @returns A hex-encoded 32-byte nonce\n */\nexport function createNonce(): `0x${string}` {\n return toHex(getCrypto().getRandomValues(new Uint8Array(32)));\n}\n\n/**\n * Creates a random 256-bit nonce for Permit2.\n * Permit2 uses uint256 nonces (not bytes32 like EIP-3009).\n *\n * @returns A string representation of the random nonce\n */\nexport function createPermit2Nonce(): string {\n const randomBytes = getCrypto().getRandomValues(new Uint8Array(32));\n return BigInt(toHex(randomBytes)).toString();\n}\n\n/** Matches the truncation length used by the Go and Python SDKs. */\nexport const MAX_ERROR_MESSAGE_LENGTH = 500;\n\n/**\n * Bounds raw error text (e.g. from an RPC client) before it is placed in a settle/verify\n * errorMessage. RPC/transport errors can carry node URLs, request bodies, or other verbose\n * data that should not be echoed to callers unbounded.\n *\n * @param message - Raw error text to bound.\n * @returns `message`, truncated to {@link MAX_ERROR_MESSAGE_LENGTH} characters.\n */\nexport function truncateErrorMessage(message: string): string {\n return message.slice(0, MAX_ERROR_MESSAGE_LENGTH);\n}\n\n/**\n * Last hash from a two-request extension-signer broadcast (e.g. approve + settle/deposit).\n * Conforming signers return one hash (atomic bundle) or two (sequential); any other\n * count means a partial execution.\n *\n * @param txHashes - Hashes returned by the signer for the two-request broadcast\n * @returns The final transaction hash, or undefined if the hash count is invalid\n */\nexport function finalHashFromTwoRequestSend<T extends string>(\n txHashes: readonly T[],\n): T | undefined {\n if (txHashes.length !== 1 && txHashes.length !== 2) {\n return undefined;\n }\n return txHashes[txHashes.length - 1];\n}\n\n/**\n * Checks that a signer-supplied transaction hash is usable for a receipt wait. The all-zero\n * hash is rejected because it reconciles to nothing, so a signer reporting success with a\n * placeholder fails terminally instead of as settlement_pending.\n *\n * @param hash - Transaction hash returned by the signer\n * @returns True if the hash is a well-formed, non-zero 32-byte hash\n */\nexport function isValidTxHash(hash: string): boolean {\n return isHash(hash) && !/^0x0+$/.test(hash);\n}\n\n/**\n * Terminal failure when a signer reports success without a usable transaction hash.\n *\n * @param tx - Value returned in place of a valid transaction hash\n * @param errorReason - Scheme/action-specific terminal error reason\n * @param network - Network the transaction was broadcast to\n * @param payer - Payer address, when known\n * @returns Failed {@link SettleResponse} with no transaction hash\n */\nexport function invalidBroadcastHashResponse(\n tx: unknown,\n errorReason: string,\n network: Network,\n payer?: string,\n): SettleResponse {\n return {\n success: false,\n errorReason,\n errorMessage: `signer returned an invalid transaction hash: ${typeof tx === \"string\" ? tx : JSON.stringify(tx)}`,\n transaction: \"\",\n network,\n payer,\n };\n}\n","import { keccak256, toBytes } from \"viem\";\n\n/** Scheme identifier for the batch-settlement payment scheme. */\nexport const BATCH_SETTLEMENT_SCHEME = \"batch-settlement\" as const;\n\n/** Deployed address of the x402BatchSettlement contract. */\nexport const BATCH_SETTLEMENT_ADDRESS = \"0x4020074e9dF2ce1deE5A9C1b5c3f541D02a10003\" as const;\n\n/** Deployed address of the ERC3009DepositCollector contract. */\nexport const ERC3009_DEPOSIT_COLLECTOR_ADDRESS =\n \"0x4020806089470a89826cB9fB1f4059150b550004\" as const;\n\n/** Deployed address of the Permit2DepositCollector contract. */\nexport const PERMIT2_DEPOSIT_COLLECTOR_ADDRESS =\n \"0x4020425FAf3B746C082C2f942b4E5159887B0005\" as const;\n\n/**\n * Bounds for the post-transaction channel-state polling loops in refund.ts and\n * deposit.ts, which re-read onchain state until it reflects a just-confirmed\n * change (a pending-withdrawal cancellation or a deposit balance increase).\n * Shared so both call sites stay in lockstep.\n */\nexport const CHANNEL_STATE_POLL_MS = 2_000;\nexport const CHANNEL_STATE_POLL_INTERVAL_MS = 150;\n\n/** Default server SDK multiplier for `extra.minDeposit` when no floor is configured. */\nexport const DEFAULT_SERVER_MIN_DEPOSIT_MULTIPLIER = 10;\n\n/** Minimum withdraw delay in seconds (15 minutes), matching the onchain constant. */\nexport const MIN_WITHDRAW_DELAY = 900;\n\n/** Maximum withdraw delay in seconds (30 days), matching the onchain constant. */\nexport const MAX_WITHDRAW_DELAY = 2_592_000;\n\n/** EIP-712 domain fields shared across all batch-settlement typed-data signatures. */\nexport const BATCH_SETTLEMENT_DOMAIN = {\n name: \"x402 Batch Settlement\",\n version: \"1\",\n} as const;\n\n/** EIP-712 type hash for channel identity. */\nexport const CHANNEL_CONFIG_TYPEHASH = keccak256(\n toBytes(\n \"ChannelConfig(address payer,address payerAuthorizer,address receiver,address receiverAuthorizer,address token,uint40 withdrawDelay,bytes32 salt)\",\n ),\n);\n\n/** EIP-712 type definition for a channel configuration. */\nexport const channelConfigTypes = {\n ChannelConfig: [\n { name: \"payer\", type: \"address\" },\n { name: \"payerAuthorizer\", type: \"address\" },\n { name: \"receiver\", type: \"address\" },\n { name: \"receiverAuthorizer\", type: \"address\" },\n { name: \"token\", type: \"address\" },\n { name: \"withdrawDelay\", type: \"uint40\" },\n { name: \"salt\", type: \"bytes32\" },\n ],\n} as const;\n\n/** EIP-712 type definition for a cumulative voucher: `Voucher(bytes32 channelId, uint128 maxClaimableAmount)`. */\nexport const voucherTypes = {\n Voucher: [\n { name: \"channelId\", type: \"bytes32\" },\n { name: \"maxClaimableAmount\", type: \"uint128\" },\n ],\n} as const;\n\n/** EIP-712 type definition for cooperative refund: `Refund(bytes32 channelId, uint256 nonce, uint128 amount)`. */\nexport const refundTypes = {\n Refund: [\n { name: \"channelId\", type: \"bytes32\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"amount\", type: \"uint128\" },\n ],\n} as const;\n\n/** EIP-712 type definitions for a receiver-authorizer claim batch (nested ClaimEntry). */\nexport const claimBatchTypes = {\n ClaimBatch: [{ name: \"claims\", type: \"ClaimEntry[]\" }],\n ClaimEntry: [\n { name: \"channelId\", type: \"bytes32\" },\n { name: \"maxClaimableAmount\", type: \"uint128\" },\n { name: \"totalClaimed\", type: \"uint128\" },\n ],\n} as const;\n\n/** EIP-712 type definition for ERC-3009 `ReceiveWithAuthorization` (used for gasless deposits). */\nexport const receiveAuthorizationTypes = {\n ReceiveWithAuthorization: [\n { name: \"from\", type: \"address\" },\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"validAfter\", type: \"uint256\" },\n { name: \"validBefore\", type: \"uint256\" },\n { name: \"nonce\", type: \"bytes32\" },\n ],\n} as const;\n\n/** Permit2 typed data for channel-bound batch deposits. */\nexport const batchPermit2WitnessTypes = {\n PermitWitnessTransferFrom: [\n { name: \"permitted\", type: \"TokenPermissions\" },\n { name: \"spender\", type: \"address\" },\n { name: \"nonce\", type: \"uint256\" },\n { name: \"deadline\", type: \"uint256\" },\n { name: \"witness\", type: \"DepositWitness\" },\n ],\n TokenPermissions: [\n { name: \"token\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n DepositWitness: [{ name: \"channelId\", type: \"bytes32\" }],\n} as const;\n","/** Error codes for the batch-settlement EVM scheme (see scheme_batch_settlement_evm2.md). */\n\nexport const ErrChannelNotFound = \"invalid_batch_settlement_evm_channel_not_found\";\nexport const ErrTokenMismatch = \"invalid_batch_settlement_evm_token_mismatch\";\nexport const ErrInvalidVoucherSignature = \"invalid_batch_settlement_evm_voucher_signature\";\nexport const ErrCumulativeExceedsBalance =\n \"invalid_batch_settlement_evm_cumulative_exceeds_balance\";\nexport const ErrCumulativeAmountBelowClaimed =\n \"invalid_batch_settlement_evm_cumulative_below_claimed\";\nexport const ErrInsufficientBalance = \"invalid_batch_settlement_evm_insufficient_balance\";\nexport const ErrDepositTransactionFailed =\n \"invalid_batch_settlement_evm_deposit_transaction_failed\";\nexport const ErrClaimTransactionFailed = \"invalid_batch_settlement_evm_claim_transaction_failed\";\nexport const ErrSettleTransactionFailed = \"invalid_batch_settlement_evm_settle_transaction_failed\";\nexport const ErrInvalidScheme = \"invalid_batch_settlement_evm_scheme\";\nexport const ErrNetworkMismatch = \"invalid_batch_settlement_evm_network_mismatch\";\nexport const ErrMissingEip712Domain = \"invalid_batch_settlement_evm_missing_eip712_domain\";\nexport const ErrValidBeforeExpired =\n \"invalid_batch_settlement_evm_payload_authorization_valid_before\";\nexport const ErrValidAfterInFuture =\n \"invalid_batch_settlement_evm_payload_authorization_valid_after\";\nexport const ErrInvalidReceiveAuthorizationSignature =\n \"invalid_batch_settlement_evm_receive_authorization_signature\";\nexport const ErrErc3009AuthorizationRequired =\n \"invalid_batch_settlement_evm_erc3009_authorization_required\";\nexport const ErrRefundTransactionFailed = \"invalid_batch_settlement_evm_refund_transaction_failed\";\nexport const ErrInvalidPayloadType = \"invalid_batch_settlement_evm_payload_type\";\nexport const ErrWithdrawDelayOutOfRange =\n \"invalid_batch_settlement_evm_withdraw_delay_out_of_range\";\nexport const ErrChannelIdMismatch = \"invalid_batch_settlement_evm_channel_id_mismatch\";\nexport const ErrInvalidChannelId = \"invalid_batch_settlement_evm_channel_id_invalid\";\nexport const ErrReceiverMismatch = \"invalid_batch_settlement_evm_receiver_mismatch\";\nexport const ErrReceiverAuthorizerMismatch =\n \"invalid_batch_settlement_evm_receiver_authorizer_mismatch\";\nexport const ErrWithdrawDelayMismatch = \"invalid_batch_settlement_evm_withdraw_delay_mismatch\";\nexport const ErrAuthorizerAddressMismatch =\n \"invalid_batch_settlement_evm_authorizer_address_mismatch\";\nexport const ErrAuthorizerNotConfigured = \"invalid_batch_settlement_evm_authorizer_not_configured\";\nexport const ErrDepositSimulationFailed = \"invalid_batch_settlement_evm_deposit_simulation_failed\";\nexport const ErrDepositBelowMinDeposit = \"invalid_batch_settlement_evm_deposit_below_min_deposit\";\n\n// ERC-6492 counterfactual deployment errors (ERC-3009 deposit path). Wire values keep the\n// scheme prefix to match the rest of this module's contract.\nexport const ErrFactoryNotAllowed = \"invalid_batch_settlement_evm_eip6492_factory_not_allowed\";\nexport const ErrSmartWalletDeploymentFailed =\n \"invalid_batch_settlement_evm_smart_wallet_deployment_failed\";\nexport const ErrClaimSimulationFailed = \"invalid_batch_settlement_evm_claim_simulation_failed\";\nexport const ErrSettleSimulationFailed = \"invalid_batch_settlement_evm_settle_simulation_failed\";\nexport const ErrNothingToSettle = \"invalid_batch_settlement_evm_nothing_to_settle\";\nexport const ErrRefundPayload = \"invalid_batch_settlement_evm_refund_payload\";\nexport const ErrRefundSimulationFailed = \"invalid_batch_settlement_evm_refund_simulation_failed\";\nexport const ErrRpcReadFailed = \"invalid_batch_settlement_evm_rpc_read_failed\";\nexport const ErrPermit2AuthorizationRequired =\n \"invalid_batch_settlement_evm_permit2_authorization_required\";\nexport const ErrPermit2InvalidSpender = \"invalid_batch_settlement_evm_permit2_invalid_spender\";\nexport const ErrPermit2AmountMismatch = \"invalid_batch_settlement_evm_permit2_amount_mismatch\";\nexport const ErrPermit2DeadlineExpired = \"invalid_batch_settlement_evm_permit2_deadline_expired\";\nexport const ErrPermit2InvalidSignature = \"invalid_batch_settlement_evm_permit2_invalid_signature\";\nexport const ErrPermit2AllowanceRequired =\n \"invalid_batch_settlement_evm_permit2_allowance_required\";\nexport const ErrEip2612AmountMismatch = \"invalid_batch_settlement_evm_eip2612_amount_mismatch\";\nexport const ErrEip2612OwnerMismatch = \"invalid_batch_settlement_evm_eip2612_owner_mismatch\";\nexport const ErrEip2612AssetMismatch = \"invalid_batch_settlement_evm_eip2612_asset_mismatch\";\nexport const ErrEip2612SpenderMismatch = \"invalid_batch_settlement_evm_eip2612_spender_mismatch\";\nexport const ErrEip2612DeadlineExpired = \"invalid_batch_settlement_evm_eip2612_deadline_expired\";\nexport const ErrErc20ApprovalUnavailable =\n \"invalid_batch_settlement_evm_erc20_approval_unavailable\";\n\n/** Resource server: 402 `error` and lifecycle `reason` (same strings as the spec). */\nexport const ErrCumulativeAmountMismatch =\n \"invalid_batch_settlement_evm_cumulative_amount_mismatch\";\nexport const ErrChannelBusy = \"invalid_batch_settlement_evm_channel_busy\";\nexport const ErrVerificationStateUnavailable =\n \"invalid_batch_settlement_evm_verification_state_unavailable\";\nexport const ErrChargeExceedsSignedCumulative =\n \"invalid_batch_settlement_evm_charge_exceeds_signed_cumulative\";\nexport const ErrMissingChannel = \"invalid_batch_settlement_evm_missing_channel\";\nexport const ErrRefundNoBalance = \"invalid_batch_settlement_evm_refund_no_balance\";\nexport const ErrRefundAmountInvalid = \"invalid_batch_settlement_evm_refund_amount_invalid\";\n","import { getAddress, hashTypedData } from \"viem\";\nimport { BATCH_SETTLEMENT_ADDRESS, BATCH_SETTLEMENT_DOMAIN, channelConfigTypes } from \"./constants\";\nimport { ErrChannelIdMismatch, ErrInvalidChannelId } from \"./errors\";\nimport type { ChannelConfig } from \"./types\";\nimport { getEvmChainId } from \"../utils\";\n\n/** Canonical `bytes32` channel id: `0x` followed by exactly 64 hex digits. */\nconst CHANNEL_ID_RE = /^0x[0-9a-fA-F]{64}$/;\n\n/**\n * Narrows an untrusted value to a canonical `bytes32` channel id string.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a `0x`-prefixed 64-hex-digit string.\n */\nexport function isCanonicalChannelId(value: unknown): value is `0x${string}` {\n return typeof value === \"string\" && CHANNEL_ID_RE.test(value);\n}\n\n/**\n * Validates canonical `bytes32` form and normalizes to lowercase.\n *\n * @param channelId - Untrusted channel identifier from a request payload.\n * @returns The lowercased channel id.\n * @throws When `channelId` is not a canonical `bytes32` string. The message is generic\n * so untrusted input is never echoed into logs.\n */\nexport function normalizeChannelId(channelId: string): `0x${string}` {\n if (!isCanonicalChannelId(channelId)) {\n throw new Error(ErrInvalidChannelId);\n }\n return channelId.toLowerCase() as `0x${string}`;\n}\n\n/**\n * Binds a claimed channel id to a channel config and network.\n *\n * @param config - The immutable channel configuration from the payload.\n * @param claimedChannelId - The channel id the client claims the config resolves to.\n * @param networkOrChainId - CAIP-2 network identifier or numeric EVM chain id.\n * @returns An error code when the id is malformed or does not match the config, else `undefined`.\n */\nexport function channelIdBindingError(\n config: ChannelConfig,\n claimedChannelId: string,\n networkOrChainId: string | number,\n): string | undefined {\n if (!isCanonicalChannelId(claimedChannelId)) return ErrInvalidChannelId;\n if (computeChannelId(config, networkOrChainId).toLowerCase() !== claimedChannelId.toLowerCase()) {\n return ErrChannelIdMismatch;\n }\n return undefined;\n}\n\n/**\n * Computes the chain-bound channel id from a {@link ChannelConfig} struct.\n *\n * @param config - The immutable channel configuration.\n * @param networkOrChainId - CAIP-2 network identifier or numeric EVM chain id.\n * @returns The `bytes32` channel id as a hex string.\n */\nexport function computeChannelId(\n config: ChannelConfig,\n networkOrChainId: string | number,\n): `0x${string}` {\n const chainId =\n typeof networkOrChainId === \"number\" ? networkOrChainId : getEvmChainId(networkOrChainId);\n return hashTypedData({\n domain: getBatchSettlementEip712Domain(chainId),\n types: channelConfigTypes,\n primaryType: \"ChannelConfig\",\n message: {\n payer: config.payer,\n payerAuthorizer: config.payerAuthorizer,\n receiver: config.receiver,\n receiverAuthorizer: config.receiverAuthorizer,\n token: config.token,\n withdrawDelay: config.withdrawDelay,\n salt: config.salt,\n },\n });\n}\n\n/**\n * Returns the full EIP-712 domain for the batch-settlement contract on the given chain.\n *\n * @param chainId - Numeric EVM chain id.\n * @returns EIP-712 domain with `name`, `version`, `chainId`, and checksummed `verifyingContract`.\n */\nexport function getBatchSettlementEip712Domain(chainId: number) {\n return {\n ...BATCH_SETTLEMENT_DOMAIN,\n chainId,\n verifyingContract: getAddress(BATCH_SETTLEMENT_ADDRESS),\n } as const;\n}\n"],"mappings":";;;;;;;;;;;;AAIA,IAAM,uBAAuB;AAStB,SAAS,cAAc,SAAyB;AACrD,MAAI,CAAC,QAAQ,WAAW,SAAS,GAAG;AAClC,UAAM,IAAI,MAAM,+BAA+B,OAAO,6BAA6B;EACrF;AAEA,QAAM,QAAQ,qBAAqB,KAAK,OAAO;AAC/C,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,4BAA4B,OAAO,EAAE;EACvD;AAEA,QAAM,UAAU,OAAO,MAAM,CAAC,CAAC;AAC/B,MAAI,CAAC,OAAO,cAAc,OAAO,GAAG;AAClC,UAAM,IAAI,MAAM,4BAA4B,OAAO,EAAE;EACvD;AAEA,SAAO;AACT;AAQA,SAAS,YAAoB;AAC3B,QAAM,YAAY,WAAW;AAC7B,MAAI,CAAC,WAAW;AACd,UAAM,IAAI,MAAM,0BAA0B;EAC5C;AACA,SAAO;AACT;AAOO,SAAS,cAA6B;AAC3C,SAAO,MAAM,UAAU,EAAE,gBAAgB,IAAI,WAAW,EAAE,CAAC,CAAC;AAC9D;AAQO,SAAS,qBAA6B;AAC3C,QAAM,cAAc,U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,MAAM,SAAS,MAAM,UAAU;IACjC,EAAE,MAAM,UAAU,MAAM,UAAU;EACpC;EACA,gBAAgB,CAAC,EAAE,MAAM,aAAa,MAAM,UAAU,CAAC;AACzD;AC1GO,IAAM,kCACX;AAsBK,IAAM,sBAAsB;AAuC5B,IAAM,8BACX;AAOK,IAAM,qBAAqB;AAC3B,IAAM,yBAAyB;ACvEtC,IAAM,gBAAgB;AAQf,SAAS,qBAAqB,OAAwC;AAC3E,SAAO,OAAO,UAAU,YAAY,cAAc,KAAK,KAAK;AAC9D;AAUO,SAAS,mBAAmB,WAAkC;AACnE,MAAI,CAAC,qBAAqB,SAAS,GAAG;AACpC,UAAM,IAAI,MAAM,mBAAmB;EACrC;AACA,SAAO,UAAU,YAAY;AAC/B;AA6BO,SAAS,iBACd,QACA,kBACe;AACf,QAAM,UACJ,OAAO,qBAAqB,WAAW,mBAAmB,cAAc,gBAAgB;AAC1F,SAAO,cAAc;IACnB,QAAQ,+BAA+B,OAAO;IAC9C,OAAO;IACP,aAAa;IACb,SAAS;MACP,OAAO,OAAO;MACd,iBAAiB,OAAO;MACxB,UAAU,OAAO;MACjB,oBAAoB,OAAO;MAC3B,OAAO,OAAO;MACd,eAAe,OAAO;MACtB,MAAM,OAAO;IACf;EACF,CAAC;AACH;AAQO,SAAS,+BAA+B,SAAiB;AAC9D,SAAO;IACL,GAAG;IACH;IACA,mBAAmB,WAAW,wBAAwB;EACxD;AACF;","names":[]}
@@ -0,0 +1,27 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+
3
+ // src/lib/prompt.ts
4
+ import { createInterface } from "node:readline";
5
+ function promptYesNo(prompt, opts = {}) {
6
+ const { defaultYes = false, input = process.stdin, output = process.stderr } = opts;
7
+ return new Promise((resolve) => {
8
+ const rl = createInterface({ input, output });
9
+ let settled = false;
10
+ const settle = (value) => {
11
+ if (settled) return;
12
+ settled = true;
13
+ rl.close();
14
+ resolve(value);
15
+ };
16
+ rl.once("close", () => settle(false));
17
+ rl.question(prompt, (answer) => {
18
+ const a = answer.trim().toLowerCase();
19
+ settle(a === "" ? defaultYes : a === "y" || a === "yes");
20
+ });
21
+ });
22
+ }
23
+
24
+ export {
25
+ promptYesNo
26
+ };
27
+ //# sourceMappingURL=chunk-LHHMV4GU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/prompt.ts"],"sourcesContent":["import { createInterface } from 'node:readline';\n\nexport interface PromptYesNoOptions {\n /** What an EMPTY answer means; the closing of stdin (ctrl-D) is always false. */\n defaultYes?: boolean;\n /** Injectable streams for tests; label/echo go to stderr, never stdout. */\n input?: NodeJS.ReadableStream;\n output?: NodeJS.WritableStream;\n}\n\n/**\n * The one y/n reader every confirm gate shares (buy, send, install). \"y\"/\"yes\"\n * (any case) is true, an empty answer follows `defaultYes` (explicit at each\n * call site), anything else is false, and stdin closing mid-prompt resolves\n * false rather than hanging. The prompt writes to stderr so stdout stays a\n * single JSON envelope.\n */\nexport function promptYesNo(prompt: string, opts: PromptYesNoOptions = {}): Promise<boolean> {\n const { defaultYes = false, input = process.stdin, output = process.stderr } = opts;\n return new Promise((resolve) => {\n const rl = createInterface({ input, output });\n let settled = false;\n const settle = (value: boolean): void => {\n if (settled) return;\n settled = true;\n rl.close();\n resolve(value);\n };\n rl.once('close', () => settle(false));\n rl.question(prompt, (answer) => {\n const a = answer.trim().toLowerCase();\n settle(a === '' ? defaultYes : a === 'y' || a === 'yes');\n });\n });\n}\n"],"mappings":";;;AAAA,SAAS,uBAAuB;AAiBzB,SAAS,YAAY,QAAgB,OAA2B,CAAC,GAAqB;AAC3F,QAAM,EAAE,aAAa,OAAO,QAAQ,QAAQ,OAAO,SAAS,QAAQ,OAAO,IAAI;AAC/E,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,KAAK,gBAAgB,EAAE,OAAO,OAAO,CAAC;AAC5C,QAAI,UAAU;AACd,UAAM,SAAS,CAAC,UAAyB;AACvC,UAAI,QAAS;AACb,gBAAU;AACV,SAAG,MAAM;AACT,cAAQ,KAAK;AAAA,IACf;AACA,OAAG,KAAK,SAAS,MAAM,OAAO,KAAK,CAAC;AACpC,OAAG,SAAS,QAAQ,CAAC,WAAW;AAC9B,YAAM,IAAI,OAAO,KAAK,EAAE,YAAY;AACpC,aAAO,MAAM,KAAK,aAAa,MAAM,OAAO,MAAM,KAAK;AAAA,IACzD,CAAC;AAAA,EACH,CAAC;AACH;","names":[]}
@@ -1,8 +1,10 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
 
3
3
  // src/lib/lock.ts
4
- import { mkdir, rm, writeFile } from "fs/promises";
5
- import { join } from "path";
4
+ import { mkdirSync, rmSync } from "node:fs";
5
+ import { writeFile } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ var owned = /* @__PURE__ */ new Set();
6
8
  var DEFAULTS = { timeoutMs: 5e3, retryMs: 25 };
7
9
  var LockTimeoutError = class extends Error {
8
10
  lockPath;
@@ -20,7 +22,8 @@ async function withFileLock(lockPath, fn, opts = {}) {
20
22
  const deadline = Date.now() + timeoutMs;
21
23
  for (; ; ) {
22
24
  try {
23
- await mkdir(lockPath);
25
+ mkdirSync(lockPath);
26
+ owned.add(lockPath);
24
27
  break;
25
28
  } catch (err) {
26
29
  if (!isEexist(err)) throw err;
@@ -34,7 +37,12 @@ async function withFileLock(lockPath, fn, opts = {}) {
34
37
  try {
35
38
  return await fn();
36
39
  } finally {
37
- await rm(lockPath, { recursive: true, force: true }).catch(() => void 0);
40
+ try {
41
+ rmSync(lockPath, { recursive: true, force: true });
42
+ owned.delete(lockPath);
43
+ } catch (err) {
44
+ opts.onReleaseError?.(lockPath, err);
45
+ }
38
46
  }
39
47
  }
40
48
  function isEexist(err) {
@@ -48,4 +56,4 @@ export {
48
56
  LockTimeoutError,
49
57
  withFileLock
50
58
  };
51
- //# sourceMappingURL=chunk-YBMMV4Y4.js.map
59
+ //# sourceMappingURL=chunk-MEFB5KHA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/lock.ts"],"sourcesContent":["import { mkdirSync, rmSync } from 'node:fs';\nimport { writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\n\n/**\n * Locks this process currently holds. Ownership starts the instant `mkdir`\n * succeeds and ends when the release has removed the directory, so there is no\n * window where a lock is on disk and unaccounted for. A removal that FAILS keeps\n * the lock owned: the directory is still on disk, no successor can claim the path\n * while it exists, and a signal-time release gets another attempt. The one place\n * ownership is dropped without a successful removal is `releaseOwnedLocks`, which\n * runs only as the process exits, where a claim held by a dying process helps\n * nobody.\n *\n * It exists because the default signal action terminates WITHOUT running\n * `finally`: without this, one Ctrl-C leaves a lock nothing will ever clean and\n * every later run of the same command times out on it.\n */\nconst owned = new Set<string>();\n\n/** Does this process hold any lock right now? */\nexport function ownsAnyLock(): boolean {\n return owned.size > 0;\n}\n\n/**\n * Synchronously attempt to release every lock this process holds. BEST EFFORT: a\n * path that refuses to be removed is left on disk and the next run's timeout names\n * it. Safe to call from a signal handler, and a no-op when this process holds\n * none, so a run merely QUEUED behind another cannot remove that other run's lock.\n */\nexport function releaseOwnedLocks(): void {\n for (const path of owned) {\n // NEVER throws. This runs inside a signal handler, and a throw there is an\n // uncaught exception: the process dies with code 1 and a stack trace instead\n // of the diagnostic and exit 130 the handler promises. One lock we could not\n // remove must not cost the report, or the exit code, or the other locks.\n try {\n rmSync(path, { recursive: true, force: true });\n } catch {\n // Left behind; the next run's timeout names the path.\n }\n }\n owned.clear();\n}\n\nexport interface FileLockOptions {\n /** Give up acquiring after this long (ms). */\n timeoutMs?: number;\n /** Poll interval between acquisition attempts (ms). */\n retryMs?: number;\n /**\n * Called when the lock could not be removed on release. The protected work\n * succeeded, so this is not a failure of the command; it is a leftover that will\n * block later runs, and the caller is the only one able to say so.\n */\n onReleaseError?: (lockPath: string, err: unknown) => void;\n}\n\nconst DEFAULTS = { timeoutMs: 5000, retryMs: 25 };\n\n/** Thrown when the lock cannot be acquired within `timeoutMs`. Carries the lock\n * path so a caller can surface the manual-recovery step in its own error contract. */\nexport class LockTimeoutError extends Error {\n readonly lockPath: string;\n constructor(lockPath: string, timeoutMs: number) {\n super(\n `Timed out waiting for lock at ${lockPath} after ${timeoutMs}ms; if no other tenjin process is running, remove that directory and retry.`,\n );\n this.name = 'LockTimeoutError';\n this.lockPath = lockPath;\n }\n}\n\n/**\n * Minimal cross-process mutex: the lock IS a directory, and mkdir is atomic, so a\n * second holder gets EEXIST and retries with backoff until `timeoutMs`, then\n * throws LockTimeoutError. There is deliberately NO auto-steal of a \"stale\" lock:\n * concurrent waiters each judging a lock stale could remove a fresh holder's\n * directory and lose its update. A crashed holder's lock is recovered by hand (the\n * timeout error names the path); the pid+acquiredAt meta exists only to make that\n * manual call diagnosable. Always released in the finally.\n *\n * NO LONGER MIRRORED IN THE HOOKS. The generated scripts used to reimplement\n * this protocol byte for byte — they run as standalone .mjs files outside the\n * CLI and cannot import this module, yet wrote the same searches.json, and two\n * writers of one file that disagree about the mutex have no mutex. That file is\n * gone (tenjin-agent#209): hook state is one SQLite database and WAL serializes\n * the writers, so nothing outside this module implements this protocol any more.\n */\nexport async function withFileLock<T>(\n lockPath: string,\n fn: () => Promise<T>,\n opts: FileLockOptions = {},\n): Promise<T> {\n const { timeoutMs, retryMs } = { ...DEFAULTS, ...opts };\n const metaPath = join(lockPath, 'meta');\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n try {\n // SYNCHRONOUS, for the same reason the release is: `await mkdir` finishes the\n // syscall before the continuation records ownership, so between the two the\n // directory is on disk and unclaimed. A signal there exits without removing\n // it and, with no stale recovery, nothing ever will. mkdirSync and the add\n // are one uninterruptible step.\n mkdirSync(lockPath);\n owned.add(lockPath); // owned from here, released only in the finally below\n break; // acquired\n } catch (err) {\n if (!isEexist(err)) throw err;\n if (Date.now() >= deadline) throw new LockTimeoutError(lockPath, timeoutMs);\n await delay(retryMs);\n }\n }\n await writeFile(metaPath, JSON.stringify({ pid: process.pid, acquiredAt: Date.now() })).catch(\n () => undefined,\n );\n try {\n return await fn();\n } finally {\n // SYNCHRONOUS, and in this order, because both are load-bearing. A signal\n // handler cannot run between two synchronous statements, so there is no instant\n // where the lock is on disk but unclaimed (a signal would exit without removing\n // it, and with no stale recovery nothing ever would) nor one where it is\n // claimed after release (a signal would remove whatever SUCCESSOR had since\n // acquired the path). An `await` here reopens the first window: `rm` yields, the\n // handler runs, sees no ownership, and leaves the directory behind.\n //\n // With no stealing, nothing else ever removes or replaces this directory, so\n // the lock here is provably the one we created — the unconditional rm is sound.\n try {\n rmSync(lockPath, { recursive: true, force: true });\n owned.delete(lockPath);\n } catch (err) {\n // KEEP ownership when the removal fails: the successor-steal risk only\n // exists once the directory is gone and someone else can take the path, so a\n // removal that failed leaves it on disk and still ours, and a signal-time\n // release gets another attempt. That only helps while THIS process lives,\n // though; once it exits normally the leftover blocks every later run, so the\n // caller is told rather than left to discover it as a timeout.\n opts.onReleaseError?.(lockPath, err);\n }\n }\n}\n\nfunction isEexist(err: unknown): boolean {\n return typeof err === 'object' && err !== null && (err as { code?: unknown }).code === 'EEXIST';\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"],"mappings":";;;AAAA,SAAS,WAAW,cAAc;AAClC,SAAS,iBAAiB;AAC1B,SAAS,YAAY;AAgBrB,IAAM,QAAQ,oBAAI,IAAY;AAyC9B,IAAM,WAAW,EAAE,WAAW,KAAM,SAAS,GAAG;AAIzC,IAAM,mBAAN,cAA+B,MAAM;AAAA,EACjC;AAAA,EACT,YAAY,UAAkB,WAAmB;AAC/C;AAAA,MACE,iCAAiC,QAAQ,UAAU,SAAS;AAAA,IAC9D;AACA,SAAK,OAAO;AACZ,SAAK,WAAW;AAAA,EAClB;AACF;AAkBA,eAAsB,aACpB,UACA,IACA,OAAwB,CAAC,GACb;AACZ,QAAM,EAAE,WAAW,QAAQ,IAAI,EAAE,G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