tenjin-cli 0.1.0-alpha.1 → 0.1.0-alpha.11

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 (193) hide show
  1. package/NOTICE.md +33 -0
  2. package/README.md +596 -79
  3. package/dist/{_esm-ZH2J4QEH.js → _esm-C5CRWCYU.js} +2 -2
  4. package/dist/_esm-N4KAVXQR.js +881 -0
  5. package/dist/buy-THMVOPUH.js +44 -0
  6. package/dist/ccip-RPPPKTJR.js +19 -0
  7. package/dist/{ccip-UCLT5VOW.js → ccip-ZGGWQN4X.js} +6 -5
  8. package/dist/chunk-2I4QTOLB.js +11 -0
  9. package/dist/chunk-2I4QTOLB.js.map +1 -0
  10. package/dist/chunk-2SDUV6MQ.js +352 -0
  11. package/dist/chunk-2SDUV6MQ.js.map +1 -0
  12. package/dist/chunk-3GSZUADW.js +199 -0
  13. package/dist/chunk-3GSZUADW.js.map +1 -0
  14. package/dist/{chunk-BRJHUQSY.js → chunk-47PP7TAG.js} +908 -812
  15. package/dist/chunk-47PP7TAG.js.map +1 -0
  16. package/dist/chunk-4NTZETIL.js +158 -0
  17. package/dist/chunk-4NTZETIL.js.map +1 -0
  18. package/dist/chunk-4TCU3YRD.js +130 -0
  19. package/dist/chunk-4TCU3YRD.js.map +1 -0
  20. package/dist/chunk-6BGYHARE.js +14620 -0
  21. package/dist/chunk-6BGYHARE.js.map +1 -0
  22. package/dist/chunk-6UY2UQMY.js +213 -0
  23. package/dist/chunk-6UY2UQMY.js.map +1 -0
  24. package/dist/{chunk-IPOWB3G3.js → chunk-7FK2UN2T.js} +3515 -507
  25. package/dist/chunk-7FK2UN2T.js.map +1 -0
  26. package/dist/chunk-ALUNME53.js +306 -0
  27. package/dist/chunk-ALUNME53.js.map +1 -0
  28. package/dist/{chunk-EXBMF5X7.js → chunk-CNUXRXI2.js} +526 -79
  29. package/dist/chunk-CNUXRXI2.js.map +1 -0
  30. package/dist/chunk-E6YOODH7.js +913 -0
  31. package/dist/chunk-E6YOODH7.js.map +1 -0
  32. package/dist/chunk-EDVI7RRD.js +317 -0
  33. package/dist/chunk-EDVI7RRD.js.map +1 -0
  34. package/dist/chunk-FKSAUOJU.js +137 -0
  35. package/dist/chunk-FKSAUOJU.js.map +1 -0
  36. package/dist/chunk-GKV6VZSZ.js +125 -0
  37. package/dist/chunk-GKV6VZSZ.js.map +1 -0
  38. package/dist/chunk-GUUAYR3K.js +175 -0
  39. package/dist/chunk-GUUAYR3K.js.map +1 -0
  40. package/dist/chunk-IAFYUFIC.js +1408 -0
  41. package/dist/chunk-IAFYUFIC.js.map +1 -0
  42. package/dist/chunk-IB63U6BM.js +185 -0
  43. package/dist/chunk-IB63U6BM.js.map +1 -0
  44. package/dist/chunk-IXTENA2H.js +235 -0
  45. package/dist/chunk-IXTENA2H.js.map +1 -0
  46. package/dist/chunk-JTYIX6OD.js +161 -0
  47. package/dist/chunk-JTYIX6OD.js.map +1 -0
  48. package/dist/chunk-KYQVEKP5.js +209 -0
  49. package/dist/chunk-KYQVEKP5.js.map +1 -0
  50. package/dist/chunk-KZAAWQNP.js +6199 -0
  51. package/dist/chunk-KZAAWQNP.js.map +1 -0
  52. package/dist/{chunk-T4LKNY7T.js → chunk-M2O56UK7.js} +225 -70
  53. package/dist/chunk-M2O56UK7.js.map +1 -0
  54. package/dist/chunk-MJZZTKCC.js +323 -0
  55. package/dist/chunk-MJZZTKCC.js.map +1 -0
  56. package/dist/chunk-NUF2PKJO.js +207 -0
  57. package/dist/chunk-NUF2PKJO.js.map +1 -0
  58. package/dist/chunk-O25VWJCG.js +1357 -0
  59. package/dist/chunk-O25VWJCG.js.map +1 -0
  60. package/dist/chunk-OCN27NJV.js +612 -0
  61. package/dist/chunk-OCN27NJV.js.map +1 -0
  62. package/dist/chunk-OZHJ3FLR.js +105 -0
  63. package/dist/chunk-OZHJ3FLR.js.map +1 -0
  64. package/dist/chunk-P74I3WH4.js +204 -0
  65. package/dist/chunk-P74I3WH4.js.map +1 -0
  66. package/dist/chunk-POJRB2AE.js +83 -0
  67. package/dist/chunk-POJRB2AE.js.map +1 -0
  68. package/dist/{chunk-YG2DO46P.js → chunk-PZRAAAY2.js} +107 -22
  69. package/dist/chunk-PZRAAAY2.js.map +1 -0
  70. package/dist/chunk-PZSUWDF2.js +35 -0
  71. package/dist/chunk-PZSUWDF2.js.map +1 -0
  72. package/dist/chunk-QW2Q2KAH.js +27 -0
  73. package/dist/chunk-QW2Q2KAH.js.map +1 -0
  74. package/dist/{chunk-CUWUHTIL.js → chunk-RBJPAZFI.js} +16 -202
  75. package/dist/chunk-RBJPAZFI.js.map +1 -0
  76. package/dist/chunk-RSBN67PA.js +152 -0
  77. package/dist/chunk-RSBN67PA.js.map +1 -0
  78. package/dist/chunk-S5RYMCV6.js +70 -0
  79. package/dist/chunk-S5RYMCV6.js.map +1 -0
  80. package/dist/chunk-SFGXAZ3M.js +316 -0
  81. package/dist/chunk-SFGXAZ3M.js.map +1 -0
  82. package/dist/chunk-SGK2B724.js +67 -0
  83. package/dist/chunk-SGK2B724.js.map +1 -0
  84. package/dist/chunk-TDDN5GXR.js +145 -0
  85. package/dist/chunk-TDDN5GXR.js.map +1 -0
  86. package/dist/{chunk-LPRVHM7P.js → chunk-U5S527PP.js} +1655 -114
  87. package/dist/chunk-U5S527PP.js.map +1 -0
  88. package/dist/chunk-UFPJBS4C.js +242 -0
  89. package/dist/chunk-UFPJBS4C.js.map +1 -0
  90. package/dist/chunk-UHTVXQ2O.js +140 -0
  91. package/dist/chunk-UHTVXQ2O.js.map +1 -0
  92. package/dist/chunk-UY6CGULW.js +83 -0
  93. package/dist/chunk-UY6CGULW.js.map +1 -0
  94. package/dist/chunk-VWY3U732.js +674 -0
  95. package/dist/chunk-VWY3U732.js.map +1 -0
  96. package/dist/{chunk-Q53IYV2G.js → chunk-W6R3HAAG.js} +20 -17
  97. package/dist/{chunk-Q53IYV2G.js.map → chunk-W6R3HAAG.js.map} +1 -1
  98. package/dist/chunk-XJN5WUKL.js +204 -0
  99. package/dist/chunk-XJN5WUKL.js.map +1 -0
  100. package/dist/chunk-XWHXX2BI.js +149 -0
  101. package/dist/chunk-XWHXX2BI.js.map +1 -0
  102. package/dist/{chunk-DXPYFVKG.js → chunk-Y7ERTA7D.js} +35 -15
  103. package/dist/chunk-Y7ERTA7D.js.map +1 -0
  104. package/dist/chunk-YLYINX2H.js +7806 -0
  105. package/dist/chunk-YLYINX2H.js.map +1 -0
  106. package/dist/chunk-ZE7KOO7A.js +233 -0
  107. package/dist/chunk-ZE7KOO7A.js.map +1 -0
  108. package/dist/chunk-ZQIQ55KK.js +51 -0
  109. package/dist/chunk-ZQIQ55KK.js.map +1 -0
  110. package/dist/{chunk-3IMLRUZE.js → chunk-ZXTAQYNA.js} +6 -2
  111. package/dist/{cli-WA65NP4Y.js → cli-Y2HBOSGK.js} +437 -175
  112. package/dist/cli-Y2HBOSGK.js.map +1 -0
  113. package/dist/config-WDGMZKHU.js +26 -0
  114. package/dist/config-WDGMZKHU.js.map +1 -0
  115. package/dist/dist-U4M6QCKE.js +2842 -0
  116. package/dist/dist-U4M6QCKE.js.map +1 -0
  117. package/dist/doctor-CSIWKWM2.js +27 -0
  118. package/dist/doctor-CSIWKWM2.js.map +1 -0
  119. package/dist/edit-E7N6F3OY.js +38 -0
  120. package/dist/edit-E7N6F3OY.js.map +1 -0
  121. package/dist/ethersCompat-Df4a6QIZ-WHYKB6HA.js +18 -0
  122. package/dist/ethersCompat-Df4a6QIZ-WHYKB6HA.js.map +1 -0
  123. package/dist/fund-OKK627GL.js +38 -0
  124. package/dist/fund-OKK627GL.js.map +1 -0
  125. package/dist/index.js +1 -1
  126. package/dist/inspect-573WHEV4.js +35 -0
  127. package/dist/inspect-573WHEV4.js.map +1 -0
  128. package/dist/install-SQAYMNQC.js +1134 -0
  129. package/dist/install-SQAYMNQC.js.map +1 -0
  130. package/dist/{mine.wasm-GQECMSGN.js → mine.wasm-6PIT3DK6.js} +2 -2
  131. package/dist/outcome-W3KYGF23.js +22 -0
  132. package/dist/outcome-W3KYGF23.js.map +1 -0
  133. package/dist/publish-N5U4XYVA.js +40 -0
  134. package/dist/publish-N5U4XYVA.js.map +1 -0
  135. package/dist/read-PJ7Z6UGF.js +158 -0
  136. package/dist/read-PJ7Z6UGF.js.map +1 -0
  137. package/dist/run-FSO3MMXN.js +16883 -0
  138. package/dist/run-FSO3MMXN.js.map +1 -0
  139. package/dist/search-ZWOP4EGK.js +23 -0
  140. package/dist/search-ZWOP4EGK.js.map +1 -0
  141. package/dist/{secp256k1-BEZS642W.js → secp256k1-XRPVBC6V.js} +5 -4
  142. package/dist/secp256k1-XRPVBC6V.js.map +1 -0
  143. package/dist/send-F34ZDXDZ.js +223 -0
  144. package/dist/send-F34ZDXDZ.js.map +1 -0
  145. package/dist/session-4N4ZT3AH.js +88 -0
  146. package/dist/session-4N4ZT3AH.js.map +1 -0
  147. package/dist/skill-heal-XBEK272G.js +85 -0
  148. package/dist/skill-heal-XBEK272G.js.map +1 -0
  149. package/dist/uninstall-BTKPHPDL.js +68 -0
  150. package/dist/uninstall-BTKPHPDL.js.map +1 -0
  151. package/dist/usdc-4VCDHFWX.js +38 -0
  152. package/dist/usdc-4VCDHFWX.js.map +1 -0
  153. package/dist/viemAdapter-By13KInL-TUQJBMHM.js +14 -0
  154. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +1 -0
  155. package/dist/wallet-UL4P2JRO.js +42 -0
  156. package/dist/wallet-UL4P2JRO.js.map +1 -0
  157. package/dist/wallet-WJ6UP5OU.js +32 -0
  158. package/dist/wallet-WJ6UP5OU.js.map +1 -0
  159. package/docs/agent-permissions.md +294 -0
  160. package/package.json +25 -18
  161. package/skills/tenjin/SKILL.md +364 -0
  162. package/skills/tenjin-publish/SKILL.md +232 -0
  163. package/skills/tenjin-search/SKILL.md +341 -0
  164. package/dist/chunk-BRJHUQSY.js.map +0 -1
  165. package/dist/chunk-CUWUHTIL.js.map +0 -1
  166. package/dist/chunk-DXPYFVKG.js.map +0 -1
  167. package/dist/chunk-EXBMF5X7.js.map +0 -1
  168. package/dist/chunk-EZROUI5U.js +0 -135
  169. package/dist/chunk-EZROUI5U.js.map +0 -1
  170. package/dist/chunk-IPOWB3G3.js.map +0 -1
  171. package/dist/chunk-LPRVHM7P.js.map +0 -1
  172. package/dist/chunk-T4LKNY7T.js.map +0 -1
  173. package/dist/chunk-YBMMV4Y4.js +0 -51
  174. package/dist/chunk-YBMMV4Y4.js.map +0 -1
  175. package/dist/chunk-YG2DO46P.js.map +0 -1
  176. package/dist/chunk-ZPZFPVDN.js +0 -67
  177. package/dist/chunk-ZPZFPVDN.js.map +0 -1
  178. package/dist/cli-WA65NP4Y.js.map +0 -1
  179. package/dist/config-CEFTL5ZL.js +0 -164
  180. package/dist/config-CEFTL5ZL.js.map +0 -1
  181. package/dist/doctor-3QBYN46N.js +0 -338
  182. package/dist/doctor-3QBYN46N.js.map +0 -1
  183. package/dist/usdc-44R6XZF2.js +0 -18
  184. package/dist/wallet-ELBTBMXO.js +0 -20
  185. package/dist/wallet-XD576HF3.js +0 -173
  186. package/dist/wallet-XD576HF3.js.map +0 -1
  187. /package/dist/{_esm-ZH2J4QEH.js.map → _esm-C5CRWCYU.js.map} +0 -0
  188. /package/dist/{ccip-UCLT5VOW.js.map → _esm-N4KAVXQR.js.map} +0 -0
  189. /package/dist/{chunk-3IMLRUZE.js.map → buy-THMVOPUH.js.map} +0 -0
  190. /package/dist/{secp256k1-BEZS642W.js.map → ccip-RPPPKTJR.js.map} +0 -0
  191. /package/dist/{usdc-44R6XZF2.js.map → ccip-ZGGWQN4X.js.map} +0 -0
  192. /package/dist/{wallet-ELBTBMXO.js.map → chunk-ZXTAQYNA.js.map} +0 -0
  193. /package/dist/{mine.wasm-GQECMSGN.js.map → mine.wasm-6PIT3DK6.js.map} +0 -0
@@ -0,0 +1,233 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ rateLimitError
4
+ } from "./chunk-EDVI7RRD.js";
5
+ import {
6
+ SIWX_HEADER,
7
+ decodePaymentRequiredHeader,
8
+ decodePaymentResponseHeader
9
+ } from "./chunk-6BGYHARE.js";
10
+ import {
11
+ httpRequest
12
+ } from "./chunk-3GSZUADW.js";
13
+ import {
14
+ SLUG_RE,
15
+ UUID_RE
16
+ } from "./chunk-ALUNME53.js";
17
+ import {
18
+ CliError,
19
+ external_exports
20
+ } from "./chunk-PZRAAAY2.js";
21
+
22
+ // src/lib/read-client.ts
23
+ var PAYMENT_REQUIRED_HEADER = "PAYMENT-REQUIRED";
24
+ var PAYMENT_RESPONSE_HEADER = "PAYMENT-RESPONSE";
25
+ var readBodySchema = external_exports.object({
26
+ id: external_exports.string().regex(UUID_RE, "resource id must be a uuid"),
27
+ slug: external_exports.string().regex(SLUG_RE, "unsafe slug").max(80),
28
+ title: external_exports.string(),
29
+ bodyMd: external_exports.string(),
30
+ price: external_exports.string(),
31
+ creator: external_exports.object({
32
+ handle: external_exports.string().nullish(),
33
+ walletAddress: external_exports.string().nullish()
34
+ }).passthrough()
35
+ }).passthrough();
36
+ var previewCardSchema = external_exports.object({
37
+ artifactType: external_exports.string(),
38
+ temporalMode: external_exports.string(),
39
+ asOf: external_exports.string().nullable(),
40
+ validUntil: external_exports.string().nullable(),
41
+ questionsAnswered: external_exports.array(external_exports.string()),
42
+ tasksSupported: external_exports.array(external_exports.string()),
43
+ appliesTo: external_exports.record(external_exports.string(), external_exports.array(external_exports.string())),
44
+ scope: external_exports.string().nullable(),
45
+ exclusions: external_exports.string().nullable(),
46
+ provenanceSummary: external_exports.string().nullable(),
47
+ methodologySummary: external_exports.string().nullable(),
48
+ maintenanceCadence: external_exports.string().nullable()
49
+ }).passthrough();
50
+ var previewSchema = external_exports.object({
51
+ id: external_exports.string().optional(),
52
+ title: external_exports.string().optional(),
53
+ price: external_exports.string().optional(),
54
+ creator: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
55
+ // `.catch` keeps a botched card from taking the rest of the preview with it:
56
+ // every other preview field is optional, so before the card existed a parse
57
+ // failure here was near-impossible, and a server that half-fills the card
58
+ // should still not cost the caller the title and the price it came for.
59
+ // The drop is NOT silent: see `cardError` on the result below.
60
+ card: previewCardSchema.optional().catch(void 0),
61
+ // Set by the SERVER when the piece has a card it could not load, so an absent
62
+ // card is never ambiguous: no flag means uncarded, this flag means temporarily
63
+ // unreadable. Never false and never sent beside `card` (tenjin#500), and the
64
+ // same fail-soft as above so a bogus `false` drops the flag rather than the
65
+ // whole preview.
66
+ cardUnavailable: external_exports.literal(true).optional().catch(void 0)
67
+ }).passthrough();
68
+ var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
69
+ var paymentRequiredSchema = external_exports.object({
70
+ x402Version: external_exports.literal(2),
71
+ accepts: external_exports.array(
72
+ external_exports.object({
73
+ scheme: external_exports.string(),
74
+ network: external_exports.string().regex(/^eip155:\d+$/, "network must be CAIP-2 eip155"),
75
+ asset: external_exports.string().regex(ADDRESS_RE, "asset must be a 0x address"),
76
+ amount: external_exports.string().regex(/^\d{1,39}$/, "amount must be an atomic integer string"),
77
+ payTo: external_exports.string().regex(ADDRESS_RE, "payTo must be a 0x address")
78
+ }).passthrough()
79
+ )
80
+ }).passthrough();
81
+ async function fetchRead(url, opts) {
82
+ const headers = { accept: "application/json" };
83
+ if (opts.searchId !== void 0) headers["x-tenjin-search-id"] = opts.searchId;
84
+ if (opts.siwxHeader !== void 0) headers[SIWX_HEADER] = opts.siwxHeader;
85
+ if (opts.sessionHeaders !== void 0) Object.assign(headers, opts.sessionHeaders);
86
+ if (opts.paymentHeaders !== void 0) Object.assign(headers, opts.paymentHeaders);
87
+ const res = await httpRequest(url, {
88
+ method: "GET",
89
+ timeoutMs: opts.timeoutMs,
90
+ headers,
91
+ fetchImpl: opts.fetchImpl,
92
+ // Pinned even when UNSIGNED (the first probe): a 200 from this route is
93
+ // written to the library by `deliverFresh` as an entitlement record under
94
+ // the server-chosen id/slug, and `findDeliveredByUrl` later matches saved
95
+ // receipts by handle+slug alone — so a followed cross-origin redirect
96
+ // would let another host's bytes short-circuit future buys as owned.
97
+ // `assertOnBaseOrigin` cannot catch this; it checks only the URL asked for.
98
+ //
99
+ // Refused for ANY 3xx, same-origin hops included. The transport failing closed
100
+ // on the whole class is the point: an exemption for "benign" redirects is a
101
+ // second origin check living in the one place that already proved it cannot see
102
+ // enough to make one. Keeping a canonical URL is the CALLER's job instead, and
103
+ // `resolveResourceRef` does it for every verb that gets here.
104
+ blockRedirects: true
105
+ });
106
+ if (!res.ok) {
107
+ if (res.kind === "blocked-redirect") {
108
+ throw new CliError("CONTRACT_MISMATCH", `${url}: ${res.message}`, {
109
+ // The origin half of this hint deliberately does NOT name the base-URL
110
+ // flag. `read` is meant to be allowlistable, the skill tells the agent
111
+ // never to pass that flag on an allowlisted verb, and a `fix:` naming it
112
+ // would coach exactly the move the skill forbids. `doctor` is the
113
+ // allowlisted verb that owns the question — its `checkReadPath` probes
114
+ // this route and its own copy names the config command when it should.
115
+ fix: "Ask for the URL in the spelling `tenjin search` or `tenjin inspect` reports. If every read hops, `tenjin doctor` checks the configured origin."
116
+ });
117
+ }
118
+ const code = res.kind === "network" || res.kind === "timeout" ? "NETWORK_ERROR" : "API_UNREACHABLE";
119
+ throw new CliError(code, `${url}: ${res.message}`, {
120
+ fix: "Check the resource URL and your network, then retry."
121
+ });
122
+ }
123
+ if (res.status === 200) {
124
+ const parsed = readBodySchema.safeParse(res.json);
125
+ if (!parsed.success) {
126
+ throw new CliError(
127
+ "CONTRACT_MISMATCH",
128
+ "The read response did not match the expected contract",
129
+ {
130
+ fix: "Update tenjin-cli; the read contract may have changed.",
131
+ details: parsed.error.issues
132
+ }
133
+ );
134
+ }
135
+ const settlement = decodeSettlement(res.header(PAYMENT_RESPONSE_HEADER));
136
+ return {
137
+ kind: "entitled",
138
+ body: parsed.data,
139
+ ...settlement !== void 0 ? { settlementTxHash: settlement } : {}
140
+ };
141
+ }
142
+ if (res.status === 402) {
143
+ const encoded = res.header(PAYMENT_REQUIRED_HEADER);
144
+ if (encoded === void 0) {
145
+ throw new CliError("CONTRACT_MISMATCH", "The 402 carried no PAYMENT-REQUIRED header", {
146
+ fix: "The server may be misconfigured; try another resource or update tenjin-cli."
147
+ });
148
+ }
149
+ let decoded;
150
+ try {
151
+ decoded = decodePaymentRequiredHeader(encoded);
152
+ } catch (err) {
153
+ throw new CliError("CONTRACT_MISMATCH", "Could not decode the PAYMENT-REQUIRED header", {
154
+ fix: "Update tenjin-cli; the x402 header format may have changed.",
155
+ cause: err
156
+ });
157
+ }
158
+ const validated = paymentRequiredSchema.safeParse(decoded);
159
+ if (!validated.success) {
160
+ throw new CliError(
161
+ "CONTRACT_MISMATCH",
162
+ "The 402 challenge is not a valid x402 v2 payment declaration.",
163
+ {
164
+ fix: "Update tenjin-cli, or check the configured base URL (`tenjin config get baseUrl`) points at a Tenjin deployment.",
165
+ details: validated.error.issues
166
+ }
167
+ );
168
+ }
169
+ const paymentRequired = decoded;
170
+ const parsed = previewSchema.safeParse(res.json);
171
+ const preview = parsed.success ? parsed.data : {};
172
+ return {
173
+ kind: "payment_required",
174
+ paymentRequired,
175
+ preview,
176
+ ...sentUnparsableCard(res.json, preview) ? { cardError: true } : {}
177
+ };
178
+ }
179
+ if (res.status === 401 && opts.sessionHeaders !== void 0) {
180
+ const code = readCode(res.json);
181
+ return { kind: "session_rejected", ...code !== void 0 ? { code } : {} };
182
+ }
183
+ if (res.status === 409) {
184
+ return { kind: "already_purchased", message: readMessage(res.json) ?? "Already purchased." };
185
+ }
186
+ if (res.status === 404) {
187
+ throw new CliError("RESOURCE_NOT_FOUND", `No resource at ${url}`, {
188
+ fix: "Check the handle/slug or resource id."
189
+ });
190
+ }
191
+ if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));
192
+ throw new CliError(
193
+ "API_UNREACHABLE",
194
+ readMessage(res.json) ?? `Unexpected status ${res.status} from ${url}`,
195
+ {
196
+ fix: "Retry; if it persists the resource may be unavailable.",
197
+ details: res.json
198
+ }
199
+ );
200
+ }
201
+ function sentUnparsableCard(json, preview) {
202
+ if (typeof json !== "object" || json === null) return false;
203
+ return "card" in json && preview.card === void 0;
204
+ }
205
+ function decodeSettlement(header) {
206
+ if (header === void 0) return void 0;
207
+ try {
208
+ const settle = decodePaymentResponseHeader(header);
209
+ const tx = settle.transaction;
210
+ return typeof tx === "string" ? tx : void 0;
211
+ } catch {
212
+ return void 0;
213
+ }
214
+ }
215
+ function readCode(json) {
216
+ if (typeof json !== "object" || json === null) return void 0;
217
+ const code = json.code;
218
+ return typeof code === "string" ? code : void 0;
219
+ }
220
+ function readMessage(json) {
221
+ if (typeof json === "object" && json !== null) {
222
+ const rec = json;
223
+ if (typeof rec.message === "string") return rec.message;
224
+ if (typeof rec.error === "string") return rec.error;
225
+ if (typeof rec.code === "string") return rec.code;
226
+ }
227
+ return void 0;
228
+ }
229
+
230
+ export {
231
+ fetchRead
232
+ };
233
+ //# sourceMappingURL=chunk-ZE7KOO7A.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/read-client.ts"],"sourcesContent":["import { z } from 'zod';\nimport { decodePaymentRequiredHeader, decodePaymentResponseHeader } from '@x402/core/http';\nimport type { PaymentRequired } from '@x402/core/types';\nimport { CliError } from './errors';\nimport { rateLimitError } from './agent-api';\nimport { httpRequest } from './http';\nimport { SIWX_HEADER } from './siwx';\n\n/**\n * The read-route (`GET /api/read/<handle>/<slug>`) client, always JSON/x402, so\n * it is the robust agent target (llms-full). It surfaces the three outcomes the\n * buy flow branches on: `entitled` (200 with the full body, free post, SIWX\n * re-read, or freshly paid), `payment_required` (402 with the decoded\n * PAYMENT-REQUIRED header + the leak-safe preview body), and `already_purchased`\n * (409 owned-re-pay gate, nothing charged). Purchase attribution rides the\n * shared transport's User-Agent always and `X-Tenjin-Search-Id` when a search\n * preceded the buy.\n */\n\nconst PAYMENT_REQUIRED_HEADER = 'PAYMENT-REQUIRED';\nconst PAYMENT_RESPONSE_HEADER = 'PAYMENT-RESPONSE';\n\n// id/slug become filesystem path segments (the local library), so they are\n// validated as a uuid + the server's slug charset HERE, at the trust boundary, so\n// a hostile id='../../evil' or slug fails as CONTRACT_MISMATCH before delivery.\nimport { SLUG_RE, UUID_RE as RESOURCE_ID_RE } from './ids';\n\n/** The full essay body a 200 returns (loose: require what the CLI reads, keep the rest). */\nconst readBodySchema = z\n .object({\n id: z.string().regex(RESOURCE_ID_RE, 'resource id must be a uuid'),\n slug: z.string().regex(SLUG_RE, 'unsafe slug').max(80),\n title: z.string(),\n bodyMd: z.string(),\n price: z.string(),\n creator: z\n .object({\n handle: z.string().nullish(),\n walletAddress: z.string().nullish(),\n })\n .passthrough(),\n })\n .passthrough();\n\nexport type ReadBody = z.infer<typeof readBodySchema>;\n\n/**\n * The public half of the piece's answer card, carried on the 402 body when the\n * piece has one. The key is ABSENT (never null) on an uncarded piece, so callers\n * branch on presence; the projection emits every field whenever it emits the card\n * at all, so a present card is never partial. Nullable fields carry null.\n *\n * This is the depth half of the search/inspect split: the card left the search\n * candidate in search v2 and lives here, one free unpaid GET away.\n */\nexport const previewCardSchema = z\n .object({\n artifactType: z.string(),\n temporalMode: z.string(),\n asOf: z.string().nullable(),\n validUntil: z.string().nullable(),\n questionsAnswered: z.array(z.string()),\n tasksSupported: z.array(z.string()),\n appliesTo: z.record(z.string(), z.array(z.string())),\n scope: z.string().nullable(),\n exclusions: z.string().nullable(),\n provenanceSummary: z.string().nullable(),\n methodologySummary: z.string().nullable(),\n maintenanceCadence: z.string().nullable(),\n })\n .passthrough();\n\nexport type PreviewCard = z.infer<typeof previewCardSchema>;\n\n/** The leak-safe 402 preview body, never the paid content. */\nconst previewSchema = z\n .object({\n id: z.string().optional(),\n title: z.string().optional(),\n price: z.string().optional(),\n creator: z.record(z.string(), z.unknown()).optional(),\n // `.catch` keeps a botched card from taking the rest of the preview with it:\n // every other preview field is optional, so before the card existed a parse\n // failure here was near-impossible, and a server that half-fills the card\n // should still not cost the caller the title and the price it came for.\n // The drop is NOT silent: see `cardError` on the result below.\n card: previewCardSchema.optional().catch(undefined),\n // Set by the SERVER when the piece has a card it could not load, so an absent\n // card is never ambiguous: no flag means uncarded, this flag means temporarily\n // unreadable. Never false and never sent beside `card` (tenjin#500), and the\n // same fail-soft as above so a bogus `false` drops the flag rather than the\n // whole preview.\n cardUnavailable: z.literal(true).optional().catch(undefined),\n })\n .passthrough();\n\nexport type Preview = z.infer<typeof previewSchema>;\n\n// The decoded PAYMENT-REQUIRED is money-path input: validate the fields the pay\n// path consumes (amount as an atomic integer, CAIP-2 network, 0x asset/payTo)\n// at THIS boundary instead of trusting raw base64 JSON. Loose otherwise so new\n// server fields never break an older CLI.\nconst ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\nconst paymentRequiredSchema = z\n .object({\n x402Version: z.literal(2),\n accepts: z.array(\n z\n .object({\n scheme: z.string(),\n network: z.string().regex(/^eip155:\\d+$/, 'network must be CAIP-2 eip155'),\n asset: z.string().regex(ADDRESS_RE, 'asset must be a 0x address'),\n amount: z.string().regex(/^\\d{1,39}$/, 'amount must be an atomic integer string'),\n payTo: z.string().regex(ADDRESS_RE, 'payTo must be a 0x address'),\n })\n .passthrough(),\n ),\n })\n .passthrough();\n\nexport type ReadResult =\n | { kind: 'entitled'; body: ReadBody; settlementTxHash?: string }\n | {\n kind: 'payment_required';\n paymentRequired: PaymentRequired;\n preview: Preview;\n /** The 402 carried a `card` this CLI could not parse, so `preview.card` is\n * absent for a reason that is NOT \"the piece is uncarded\". The two must\n * stay distinguishable: an uncarded piece is a real signal a buyer acts\n * on, and this 402 is the only pre-purchase depth there is. */\n cardError?: true;\n }\n | { kind: 'already_purchased'; message: string };\n\n/**\n * The extra outcome a SESSION-SIGNED read can have: a 401 saying the delegation is\n * expired, revoked, or bound to a key this server will not accept.\n *\n * It is a value rather than a thrown API_UNREACHABLE because the caller has a\n * defined answer for it — `read` falls to its ordinary exit-3 refusal, never a\n * retry loop, because re-establishing needs a wallet it cannot reach. And it is\n * kept OUT of `ReadResult` because an unsigned or SIWX 401 has no such contract:\n * widening the shared union would make `buy` and `inspect` branch on a state they\n * can never produce, and a \"cannot happen\" branch is where wrong handling hides.\n */\nexport type SessionReadResult = ReadResult | { kind: 'session_rejected'; code?: string };\n\nexport interface ReadRequestOptions {\n timeoutMs: number;\n fetchImpl?: typeof fetch;\n /** A `SIGN-IN-WITH-X` header for the entitled free re-read. */\n siwxHeader?: string;\n /** The `PAYMENT-SIGNATURE` header(s) for a paid request. */\n paymentHeaders?: Record<string, string>;\n /**\n * RFC 9421 session-key headers (`Tenjin-Session-Delegation`, `Signature-Input`,\n * `Signature`) proving an entitlement without a wallet and without paying. A\n * bodyless GET carries no `Content-Digest`, so the covered set is method+URI.\n */\n sessionHeaders?: Record<string, string>;\n /** Attribute a following purchase to the search that surfaced it. */\n searchId?: string;\n}\n\n/**\n * One transport, two result types, selected by whether the caller actually\n * presented a session key. The `session_rejected` arm is reachable only when\n * `sessionHeaders` were sent, so the overloads say exactly that instead of\n * leaving every caller to prove it by inspection.\n */\nexport async function fetchRead(\n url: string,\n opts: ReadRequestOptions & { sessionHeaders: Record<string, string> },\n): Promise<SessionReadResult>;\nexport async function fetchRead(url: string, opts: ReadRequestOptions): Promise<ReadResult>;\nexport async function fetchRead(url: string, opts: ReadRequestOptions): Promise<SessionReadResult> {\n const headers: Record<string, string> = { accept: 'application/json' };\n if (opts.searchId !== undefined) headers['x-tenjin-search-id'] = opts.searchId;\n if (opts.siwxHeader !== undefined) headers[SIWX_HEADER] = opts.siwxHeader;\n if (opts.sessionHeaders !== undefined) Object.assign(headers, opts.sessionHeaders);\n if (opts.paymentHeaders !== undefined) Object.assign(headers, opts.paymentHeaders);\n\n const res = await httpRequest(url, {\n method: 'GET',\n timeoutMs: opts.timeoutMs,\n headers,\n fetchImpl: opts.fetchImpl,\n // Pinned even when UNSIGNED (the first probe): a 200 from this route is\n // written to the library by `deliverFresh` as an entitlement record under\n // the server-chosen id/slug, and `findDeliveredByUrl` later matches saved\n // receipts by handle+slug alone — so a followed cross-origin redirect\n // would let another host's bytes short-circuit future buys as owned.\n // `assertOnBaseOrigin` cannot catch this; it checks only the URL asked for.\n //\n // Refused for ANY 3xx, same-origin hops included. The transport failing closed\n // on the whole class is the point: an exemption for \"benign\" redirects is a\n // second origin check living in the one place that already proved it cannot see\n // enough to make one. Keeping a canonical URL is the CALLER's job instead, and\n // `resolveResourceRef` does it for every verb that gets here.\n blockRedirects: true,\n });\n if (!res.ok) {\n // A redirect refused mid-flight is a URL-shape problem, not a flaky network:\n // retrying a signed request re-sends the same signature into the same\n // redirect, and retrying the unsigned probe re-fetches bytes the library must\n // never record as this origin's. The `fix` names the URL, not the route: the\n // route is allowed to redirect (canonicalizing a path is what a redirect is\n // FOR), and pointing an agent at the base URL for a hop the base URL did not\n // cause spends two useless steps and still does not read the piece.\n // `resolveResourceRef` canonicalizes what it can (the trailing slash); what\n // reaches here is a spelling it could not.\n if (res.kind === 'blocked-redirect') {\n throw new CliError('CONTRACT_MISMATCH', `${url}: ${res.message}`, {\n // The origin half of this hint deliberately does NOT name the base-URL\n // flag. `read` is meant to be allowlistable, the skill tells the agent\n // never to pass that flag on an allowlisted verb, and a `fix:` naming it\n // would coach exactly the move the skill forbids. `doctor` is the\n // allowlisted verb that owns the question — its `checkReadPath` probes\n // this route and its own copy names the config command when it should.\n fix:\n 'Ask for the URL in the spelling `tenjin search` or `tenjin inspect` ' +\n 'reports. If every read hops, `tenjin doctor` checks the configured origin.',\n });\n }\n const code =\n res.kind === 'network' || res.kind === 'timeout' ? 'NETWORK_ERROR' : 'API_UNREACHABLE';\n throw new CliError(code, `${url}: ${res.message}`, {\n fix: 'Check the resource URL and your network, then retry.',\n });\n }\n\n if (res.status === 200) {\n const parsed = readBodySchema.safeParse(res.json);\n if (!parsed.success) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n 'The read response did not match the expected contract',\n {\n fix: 'Update tenjin-cli; the read contract may have changed.',\n details: parsed.error.issues,\n },\n );\n }\n const settlement = decodeSettlement(res.header(PAYMENT_RESPONSE_HEADER));\n return {\n kind: 'entitled',\n body: parsed.data,\n ...(settlement !== undefined ? { settlementTxHash: settlement } : {}),\n };\n }\n\n if (res.status === 402) {\n const encoded = res.header(PAYMENT_REQUIRED_HEADER);\n if (encoded === undefined) {\n throw new CliError('CONTRACT_MISMATCH', 'The 402 carried no PAYMENT-REQUIRED header', {\n fix: 'The server may be misconfigured; try another resource or update tenjin-cli.',\n });\n }\n let decoded: PaymentRequired;\n try {\n decoded = decodePaymentRequiredHeader(encoded);\n } catch (err) {\n throw new CliError('CONTRACT_MISMATCH', 'Could not decode the PAYMENT-REQUIRED header', {\n fix: 'Update tenjin-cli; the x402 header format may have changed.',\n cause: err,\n });\n }\n const validated = paymentRequiredSchema.safeParse(decoded);\n if (!validated.success) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n 'The 402 challenge is not a valid x402 v2 payment declaration.',\n {\n fix: 'Update tenjin-cli, or check the configured base URL (`tenjin config get baseUrl`) points at a Tenjin deployment.',\n details: validated.error.issues,\n },\n );\n }\n const paymentRequired = decoded;\n const parsed = previewSchema.safeParse(res.json);\n const preview = parsed.success ? parsed.data : {};\n return {\n kind: 'payment_required',\n paymentRequired,\n preview,\n ...(sentUnparsableCard(res.json, preview) ? { cardError: true as const } : {}),\n };\n }\n\n // Narrow on purpose: only a request that actually presented a session key gets\n // the soft outcome. Widening this to every 401 would quietly turn buy's SIWX\n // re-check failure into a value the caller has to remember to branch on.\n if (res.status === 401 && opts.sessionHeaders !== undefined) {\n const code = readCode(res.json);\n return { kind: 'session_rejected', ...(code !== undefined ? { code } : {}) };\n }\n\n if (res.status === 409) {\n // The owned-re-pay gate: a payment for a post this wallet already bought is\n // refused, nothing charged. The caller falls back to a SIWX free re-read.\n return { kind: 'already_purchased', message: readMessage(res.json) ?? 'Already purchased.' };\n }\n\n if (res.status === 404) {\n throw new CliError('RESOURCE_NOT_FOUND', `No resource at ${url}`, {\n fix: 'Check the handle/slug or resource id.',\n });\n }\n\n // 429 on the paid-read path is a recoverable pause, not an outage: surface\n // RATE_LIMITED + retryAfterSeconds like postSearch/postOutcomes do, so a looping\n // agent (the caller most likely to hit this) can back off instead of treating it\n // as API_UNREACHABLE.\n if (res.status === 429) throw rateLimitError(url, (n) => res.header(n));\n\n throw new CliError(\n 'API_UNREACHABLE',\n readMessage(res.json) ?? `Unexpected status ${res.status} from ${url}`,\n {\n fix: 'Retry; if it persists the resource may be unavailable.',\n details: res.json,\n },\n );\n}\n\n/** The server sent a `card` key but nothing survived the parse. Distinguishes a\n * DROPPED card from an absent one, which the `.catch` above otherwise makes\n * look identical. */\nfunction sentUnparsableCard(json: unknown, preview: Preview): boolean {\n if (typeof json !== 'object' || json === null) return false;\n return 'card' in json && preview.card === undefined;\n}\n\nfunction decodeSettlement(header: string | undefined): string | undefined {\n if (header === undefined) return undefined;\n try {\n const settle = decodePaymentResponseHeader(header);\n const tx = (settle as { transaction?: unknown }).transaction;\n return typeof tx === 'string' ? tx : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The server's machine `code` on an auth failure (`session_expired`, …), if any. */\nfunction readCode(json: unknown): string | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const code = (json as Record<string, unknown>).code;\n return typeof code === 'string' ? code : undefined;\n}\n\nfunction readMessage(json: unknown): string | undefined {\n if (typeof json === 'object' && json !== null) {\n const rec = json as Record<string, unknown>;\n if (typeof rec.message === 'string') return rec.message;\n if (typeof rec.error === 'string') return rec.error;\n if (typeof rec.code === 'string') return rec.code;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAmBA,IAAM,0BAA0B;AAChC,IAAM,0BAA0B;AAQhC,IAAM,iBAAiB,iBACpB,OAAO;AAAA,EACN,IAAI,iBAAE,OAAO,EAAE,MAAM,SAAgB,4BAA4B;AAAA,EACjE,MAAM,iBAAE,OAAO,EAAE,MAAM,SAAS,aAAa,EAAE,IAAI,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qC;AACjD,WAAO,OAAO,OAAO,WAAW,KAAK;AAAA,EACvC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,SAAS,SAAS,MAAmC;AACnD,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AACtD,QAAM,OAAQ,KAAiC;AAC/C,SAAO,OAAO,SAAS,WAAW,OAAO;AAC3C;AAEA,SAAS,YAAY,MAAmC;AACtD,MAAI,OAAO,SAAS,YAAY,SAAS,MAAM;AAC7C,UAAM,MAAM;AACZ,QAAI,OAAO,IAAI,YAAY,SAAU,QAAO,IAAI;AAChD,QAAI,OAAO,IAAI,UAAU,SAAU,QAAO,IAAI;AAC9C,QAAI,OAAO,IAAI,SAAS,SAAU,QAAO,IAAI;AAAA,EAC/C;AACA,SAAO;AACT;","names":[]}
@@ -0,0 +1,51 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+
3
+ // src/lib/paths.ts
4
+ import { homedir } from "os";
5
+ import { join } from "path";
6
+ function dataDir(env = process.env) {
7
+ const override = env.TENJIN_DATA_DIR;
8
+ if (override !== void 0 && override.length > 0) return override;
9
+ return join(homedir(), ".tenjin");
10
+ }
11
+ function configPath(dir = dataDir()) {
12
+ return join(dir, "config.json");
13
+ }
14
+ function walletPath(dir = dataDir()) {
15
+ return join(dir, "wallet.json");
16
+ }
17
+ function sessionPath(dir = dataDir()) {
18
+ return join(dir, "session.json");
19
+ }
20
+ function spendLedgerPath(dir = dataDir()) {
21
+ return join(dir, "spend.json");
22
+ }
23
+ function updateCheckPath(dir = dataDir()) {
24
+ return join(dir, "update-check.json");
25
+ }
26
+ function hooksDir(dir = dataDir()) {
27
+ return join(dir, "hooks");
28
+ }
29
+ function passphraseBlobPath(dir = dataDir()) {
30
+ return join(dir, "passphrase.dpapi");
31
+ }
32
+ function passphraseBlobPathFor(account, dir = dataDir()) {
33
+ return join(dir, `passphrase.${account}.dpapi`);
34
+ }
35
+ function archivedWalletPath(account, dir = dataDir()) {
36
+ return join(dir, `wallet.${account}.json.bak`);
37
+ }
38
+
39
+ export {
40
+ dataDir,
41
+ configPath,
42
+ walletPath,
43
+ sessionPath,
44
+ spendLedgerPath,
45
+ updateCheckPath,
46
+ hooksDir,
47
+ passphraseBlobPath,
48
+ passphraseBlobPathFor,
49
+ archivedWalletPath
50
+ };
51
+ //# sourceMappingURL=chunk-ZQIQ55KK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/paths.ts"],"sourcesContent":["import { homedir } from 'node:os';\nimport { join } from 'node:path';\n\n/**\n * Where the CLI keeps its config and wallet. Defaults to ~/.tenjin, overridable\n * via TENJIN_DATA_DIR (CI, ephemeral agents, and every test — which point it at\n * a temp dir so the real home is never touched).\n */\nexport function dataDir(env: NodeJS.ProcessEnv = process.env): string {\n const override = env.TENJIN_DATA_DIR;\n if (override !== undefined && override.length > 0) return override;\n return join(homedir(), '.tenjin');\n}\n\nexport function configPath(dir: string = dataDir()): string {\n return join(dir, 'config.json');\n}\n\nexport function walletPath(dir: string = dataDir()): string {\n return join(dir, 'wallet.json');\n}\n\n/**\n * Where the delegated P-256 session key + its wallet-signed SIWX delegation are\n * cached (B3, D35). A short-lived (≤24h) hot key: lower stakes than wallet.json,\n * but still written 0600 and address-bound so a wallet change invalidates it.\n */\nexport function sessionPath(dir: string = dataDir()): string {\n return join(dir, 'session.json');\n}\n\n/**\n * Where the client-side rolling spend ledger lives (lib/wallet/spend.ts).\n *\n * Its own file, NOT session.json: the two schemas are incompatible and both\n * readers treat a parse failure as \"absent\", so a shared path meant each writer\n * silently destroyed the other's file — a session key wiped the spend window, and\n * the next spend wiped the session key.\n */\nexport function spendLedgerPath(dir: string = dataDir()): string {\n return join(dir, 'spend.json');\n}\n\n/**\n * Where the once-a-day \"a newer tenjin-cli exists\" check caches the registry\n * answer. A pure cache: nothing here is authoritative, so an unreadable file is\n * simply re-fetched.\n */\nexport function updateCheckPath(dir: string = dataDir()): string {\n return join(dir, 'update-check.json');\n}\n\n/**\n * Where `install` writes the standalone harness hook scripts. Under the data dir\n * rather than the harness's own config directory: the scripts are ours, a harness\n * only ever holds the path to them, and one location serves every harness.\n */\nexport function hooksDir(dir: string = dataDir()): string {\n return join(dir, 'hooks');\n}\n\n/**\n * Which searchIds the Stop hook has already nagged about, so each open loop is\n * raised once per turn-end rather than every turn.\n *\n * Not atomic, deliberately: two sessions ending at the same instant can both read\n * this file before either writes, and one loop is then named twice. The cost is a\n * duplicate line, and taking the search store's lock here would put a\n * cross-process wait at the end of every turn to buy nothing but tidiness.\n *\n * Its own file, NOT a field in searches.json, and that separation is the whole\n * point: the hook runs outside the CLI with no access to the lock `recordSearch`\n * takes, so a hook writing searches.json could erase a search landing at the same\n * moment. Nothing but the hook writes this file, and losing it costs one repeated\n * nag rather than a lost search.\n */\nexport function nagStatePath(dir: string = dataDir()): string {\n return join(dir, 'hook-nags.json');\n}\n\n/**\n * Where the LEGACY (pre-per-wallet) Windows DPAPI passphrase blob lives. The\n * file holds a DPAPI CurrentUser ciphertext, not the passphrase in plaintext.\n * New writes go to the per-wallet path below; this one is only read as a\n * migration fallback and removed after a verified per-wallet copy exists.\n */\nexport function passphraseBlobPath(dir: string = dataDir()): string {\n return join(dir, 'passphrase.dpapi');\n}\n\n/**\n * The per-wallet Windows DPAPI passphrase blob: one file per wallet address\n * (lowercase), so creating a new wallet never clobbers an old wallet's blob.\n * Only ever written on win32; other platforms use their own OS store.\n */\nexport function passphraseBlobPathFor(account: string, dir: string = dataDir()): string {\n return join(dir, `passphrase.${account}.dpapi`);\n}\n\n/**\n * Where `wallet create --replace` parks the outgoing wallet's keystore, keyed by\n * its lowercase address so successive replaces can never collide. Together with\n * the wallet's per-address passphrase entry in the OS store, this file keeps the\n * replaced wallet's funds recoverable; it is never read by the active-wallet\n * path.\n */\nexport function archivedWalletPath(account: string, dir: string = dataDir()): string {\n return join(dir, `wallet.${account}.json.bak`);\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;AACxB,SAAS,YAAY;AAOd,SAAS,QAAQ,MAAyB,QAAQ,KAAa;AACpE,QAAM,WAAW,IAAI;AACrB,MAAI,aAAa,UAAa,SAAS,SAAS,EAAG,QAAO;AAC1D,SAAO,KAAK,QAAQ,GAAG,SAAS;AAClC;AAEO,SAAS,WAAW,MAAc,QAAQ,GAAW;AAC1D,SAAO,KAAK,KAAK,aAAa;AAChC;AAEO,SAAS,WAAW,MAAc,QAAQ,GAAW;AAC1D,SAAO,KAAK,KAAK,aAAa;AAChC;AAOO,SAAS,YAAY,MAAc,QAAQ,GAAW;AAC3D,SAAO,KAAK,KAAK,cAAc;AACjC;AAUO,SAAS,gBAAgB,MAAc,QAAQ,GAAW;AAC/D,SAAO,KAAK,KAAK,YAAY;AAC/B;AAOO,SAAS,gBAAgB,MAAc,QAAQ,GAAW;AAC/D,SAAO,KAAK,KAAK,mBAAmB;AACtC;AAOO,SAAS,SAAS,MAAc,QAAQ,GAAW;AACxD,SAAO,KAAK,KAAK,OAAO;AAC1B;AA2BO,SAAS,mBAAmB,MAAc,QAAQ,GAAW;AAClE,SAAO,KAAK,KAAK,kBAAkB;AACrC;AAOO,SAAS,sBAAsB,SAAiB,MAAc,QAAQ,GAAW;AACtF,SAAO,KAAK,KAAK,cAAc,OAAO,QAAQ;AAChD;AASO,SAAS,mBAAmB,SAAiB,MAAc,QAAQ,GAAW;AACnF,SAAO,KAAK,KAAK,UAAU,OAAO,WAAW;AAC/C;","names":[]}
@@ -12,7 +12,11 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
12
12
  throw Error('Dynamic require of "' + x + '" is not supported');
13
13
  });
14
14
  var __commonJS = (cb, mod) => function __require2() {
15
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15
+ try {
16
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
17
+ } catch (e) {
18
+ throw mod = 0, e;
19
+ }
16
20
  };
17
21
  var __export = (target, all) => {
18
22
  for (var name in all)
@@ -41,4 +45,4 @@ export {
41
45
  __export,
42
46
  __toESM
43
47
  };
44
- //# sourceMappingURL=chunk-3IMLRUZE.js.map
48
+ //# sourceMappingURL=chunk-ZXTAQYNA.js.map