tenjin-cli 0.1.0-alpha.0 → 0.1.0-alpha.10

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 (191) hide show
  1. package/NOTICE.md +33 -0
  2. package/README.md +575 -50
  3. package/dist/{_esm-ZH2J4QEH.js → _esm-C5CRWCYU.js} +2 -2
  4. package/dist/_esm-N4KAVXQR.js +881 -0
  5. package/dist/buy-FMDBZ4NY.js +44 -0
  6. package/dist/candidate-7LAELUQD.js +23 -0
  7. package/dist/ccip-RPPPKTJR.js +19 -0
  8. package/dist/{ccip-FXWZDDF5.js → ccip-ZGGWQN4X.js} +6 -5
  9. package/dist/chunk-2GSRYTZS.js +127 -0
  10. package/dist/chunk-2GSRYTZS.js.map +1 -0
  11. package/dist/chunk-2I4QTOLB.js +11 -0
  12. package/dist/chunk-2I4QTOLB.js.map +1 -0
  13. package/dist/chunk-36X2CA3N.js +311 -0
  14. package/dist/chunk-36X2CA3N.js.map +1 -0
  15. package/dist/{chunk-F5DZJLU3.js → chunk-47PP7TAG.js} +1441 -634
  16. package/dist/chunk-47PP7TAG.js.map +1 -0
  17. package/dist/chunk-5JMKIDMM.js +316 -0
  18. package/dist/chunk-5JMKIDMM.js.map +1 -0
  19. package/dist/chunk-5JXAZP7H.js +206 -0
  20. package/dist/chunk-5JXAZP7H.js.map +1 -0
  21. package/dist/chunk-5SE6BJRP.js +135 -0
  22. package/dist/chunk-5SE6BJRP.js.map +1 -0
  23. package/dist/chunk-6BZLSRNU.js +149 -0
  24. package/dist/chunk-6BZLSRNU.js.map +1 -0
  25. package/dist/{chunk-PAAL45FJ.js → chunk-7FK2UN2T.js} +3410 -412
  26. package/dist/chunk-7FK2UN2T.js.map +1 -0
  27. package/dist/chunk-7WDY4AXV.js +14620 -0
  28. package/dist/chunk-7WDY4AXV.js.map +1 -0
  29. package/dist/chunk-A6KCZPNQ.js +83 -0
  30. package/dist/chunk-A6KCZPNQ.js.map +1 -0
  31. package/dist/chunk-AWQ6A4CI.js +341 -0
  32. package/dist/chunk-AWQ6A4CI.js.map +1 -0
  33. package/dist/chunk-BJJ5BQO6.js +162 -0
  34. package/dist/chunk-BJJ5BQO6.js.map +1 -0
  35. package/dist/chunk-BUDHTDKL.js +612 -0
  36. package/dist/chunk-BUDHTDKL.js.map +1 -0
  37. package/dist/chunk-DKQMJTG7.js +188 -0
  38. package/dist/chunk-DKQMJTG7.js.map +1 -0
  39. package/dist/chunk-FKSAUOJU.js +137 -0
  40. package/dist/chunk-FKSAUOJU.js.map +1 -0
  41. package/dist/chunk-GECSWJ7O.js +1645 -0
  42. package/dist/chunk-GECSWJ7O.js.map +1 -0
  43. package/dist/chunk-GSDZRCGF.js +105 -0
  44. package/dist/chunk-GSDZRCGF.js.map +1 -0
  45. package/dist/chunk-JSSIMGQT.js +174 -0
  46. package/dist/chunk-JSSIMGQT.js.map +1 -0
  47. package/dist/chunk-KYH4KPE5.js +1357 -0
  48. package/dist/chunk-KYH4KPE5.js.map +1 -0
  49. package/dist/chunk-KYQVEKP5.js +209 -0
  50. package/dist/chunk-KYQVEKP5.js.map +1 -0
  51. package/dist/chunk-KZAAWQNP.js +6199 -0
  52. package/dist/chunk-KZAAWQNP.js.map +1 -0
  53. package/dist/{chunk-SXQQ2ZSR.js → chunk-M2O56UK7.js} +243 -75
  54. package/dist/chunk-M2O56UK7.js.map +1 -0
  55. package/dist/chunk-MD7WGYYI.js +125 -0
  56. package/dist/chunk-MD7WGYYI.js.map +1 -0
  57. package/dist/chunk-MJZZTKCC.js +323 -0
  58. package/dist/chunk-MJZZTKCC.js.map +1 -0
  59. package/dist/chunk-O6CAUZGY.js +317 -0
  60. package/dist/chunk-O6CAUZGY.js.map +1 -0
  61. package/dist/chunk-P74I3WH4.js +204 -0
  62. package/dist/chunk-P74I3WH4.js.map +1 -0
  63. package/dist/chunk-POF7HPRV.js +145 -0
  64. package/dist/chunk-POF7HPRV.js.map +1 -0
  65. package/dist/chunk-POJRB2AE.js +83 -0
  66. package/dist/chunk-POJRB2AE.js.map +1 -0
  67. package/dist/{chunk-FIYZLITH.js → chunk-PZRAAAY2.js} +107 -18
  68. package/dist/chunk-PZRAAAY2.js.map +1 -0
  69. package/dist/chunk-PZSUWDF2.js +35 -0
  70. package/dist/chunk-PZSUWDF2.js.map +1 -0
  71. package/dist/chunk-QW2Q2KAH.js +27 -0
  72. package/dist/chunk-QW2Q2KAH.js.map +1 -0
  73. package/dist/chunk-R2VLGNFD.js +181 -0
  74. package/dist/chunk-R2VLGNFD.js.map +1 -0
  75. package/dist/{chunk-CPUZRZ2A.js → chunk-RBJPAZFI.js} +25 -170
  76. package/dist/chunk-RBJPAZFI.js.map +1 -0
  77. package/dist/chunk-S5RYMCV6.js +70 -0
  78. package/dist/chunk-S5RYMCV6.js.map +1 -0
  79. package/dist/chunk-SGK2B724.js +67 -0
  80. package/dist/chunk-SGK2B724.js.map +1 -0
  81. package/dist/chunk-STND72DS.js +242 -0
  82. package/dist/chunk-STND72DS.js.map +1 -0
  83. package/dist/chunk-TEL27PR5.js +124 -0
  84. package/dist/chunk-TEL27PR5.js.map +1 -0
  85. package/dist/chunk-TWRYSGAW.js +134 -0
  86. package/dist/chunk-TWRYSGAW.js.map +1 -0
  87. package/dist/{chunk-WOHCAMDQ.js → chunk-U5S527PP.js} +1887 -1029
  88. package/dist/chunk-U5S527PP.js.map +1 -0
  89. package/dist/chunk-UHTVXQ2O.js +140 -0
  90. package/dist/chunk-UHTVXQ2O.js.map +1 -0
  91. package/dist/chunk-UOJRKQTZ.js +213 -0
  92. package/dist/chunk-UOJRKQTZ.js.map +1 -0
  93. package/dist/chunk-V4WWTZHZ.js +233 -0
  94. package/dist/chunk-V4WWTZHZ.js.map +1 -0
  95. package/dist/chunk-VRRLTZ2Q.js +651 -0
  96. package/dist/chunk-VRRLTZ2Q.js.map +1 -0
  97. package/dist/{chunk-TX5T3LKJ.js → chunk-W6R3HAAG.js} +21 -17
  98. package/dist/{chunk-TX5T3LKJ.js.map → chunk-W6R3HAAG.js.map} +1 -1
  99. package/dist/chunk-X3OOVSPX.js +154 -0
  100. package/dist/chunk-X3OOVSPX.js.map +1 -0
  101. package/dist/chunk-XJN5WUKL.js +204 -0
  102. package/dist/chunk-XJN5WUKL.js.map +1 -0
  103. package/dist/chunk-Y7ERTA7D.js +146 -0
  104. package/dist/chunk-Y7ERTA7D.js.map +1 -0
  105. package/dist/chunk-YLYINX2H.js +7806 -0
  106. package/dist/chunk-YLYINX2H.js.map +1 -0
  107. package/dist/chunk-ZQIQ55KK.js +51 -0
  108. package/dist/chunk-ZQIQ55KK.js.map +1 -0
  109. package/dist/chunk-ZUAQRIVP.js +1369 -0
  110. package/dist/chunk-ZUAQRIVP.js.map +1 -0
  111. package/dist/{chunk-3IMLRUZE.js → chunk-ZXTAQYNA.js} +6 -2
  112. package/dist/chunk-ZXTAQYNA.js.map +1 -0
  113. package/dist/{cli-LMHGCZ5S.js → cli-HK2XAWNW.js} +438 -177
  114. package/dist/cli-HK2XAWNW.js.map +1 -0
  115. package/dist/config-LYCHHNAJ.js +26 -0
  116. package/dist/config-LYCHHNAJ.js.map +1 -0
  117. package/dist/dist-U4M6QCKE.js +2842 -0
  118. package/dist/dist-U4M6QCKE.js.map +1 -0
  119. package/dist/doctor-2KPUQURC.js +27 -0
  120. package/dist/doctor-2KPUQURC.js.map +1 -0
  121. package/dist/edit-TST3OCKQ.js +38 -0
  122. package/dist/edit-TST3OCKQ.js.map +1 -0
  123. package/dist/ethersCompat-Df4a6QIZ-WHYKB6HA.js +18 -0
  124. package/dist/ethersCompat-Df4a6QIZ-WHYKB6HA.js.map +1 -0
  125. package/dist/index.js +1 -1
  126. package/dist/inspect-TPTHVPBB.js +35 -0
  127. package/dist/inspect-TPTHVPBB.js.map +1 -0
  128. package/dist/install-PT3XEDJ6.js +1869 -0
  129. package/dist/install-PT3XEDJ6.js.map +1 -0
  130. package/dist/{mine.wasm-GQECMSGN.js → mine.wasm-6PIT3DK6.js} +2 -2
  131. package/dist/outcome-NPNSF2Q7.js +22 -0
  132. package/dist/outcome-NPNSF2Q7.js.map +1 -0
  133. package/dist/publish-XP5SEWST.js +41 -0
  134. package/dist/publish-XP5SEWST.js.map +1 -0
  135. package/dist/read-D4VXRWOG.js +158 -0
  136. package/dist/read-D4VXRWOG.js.map +1 -0
  137. package/dist/run-3IPGEXW7.js +16902 -0
  138. package/dist/run-3IPGEXW7.js.map +1 -0
  139. package/dist/search-YOBD6VDI.js +24 -0
  140. package/dist/search-YOBD6VDI.js.map +1 -0
  141. package/dist/{secp256k1-35YNNB6F.js → secp256k1-XRPVBC6V.js} +5 -4
  142. package/dist/secp256k1-XRPVBC6V.js.map +1 -0
  143. package/dist/send-BWNP6WN4.js +223 -0
  144. package/dist/send-BWNP6WN4.js.map +1 -0
  145. package/dist/session-GZEZBOMI.js +88 -0
  146. package/dist/session-GZEZBOMI.js.map +1 -0
  147. package/dist/skill-heal-OK6YALW6.js +85 -0
  148. package/dist/skill-heal-OK6YALW6.js.map +1 -0
  149. package/dist/usdc-4VCDHFWX.js +38 -0
  150. package/dist/usdc-4VCDHFWX.js.map +1 -0
  151. package/dist/viemAdapter-By13KInL-TUQJBMHM.js +14 -0
  152. package/dist/viemAdapter-By13KInL-TUQJBMHM.js.map +1 -0
  153. package/dist/wallet-5RHDFPN2.js +32 -0
  154. package/dist/wallet-5RHDFPN2.js.map +1 -0
  155. package/dist/wallet-YEGQBWWL.js +42 -0
  156. package/dist/wallet-YEGQBWWL.js.map +1 -0
  157. package/docs/agent-permissions.md +281 -0
  158. package/package.json +26 -17
  159. package/skills/tenjin/SKILL.md +364 -0
  160. package/skills/tenjin-publish/SKILL.md +219 -0
  161. package/skills/tenjin-search/SKILL.md +335 -0
  162. package/dist/chunk-376LHMK2.js +0 -100
  163. package/dist/chunk-376LHMK2.js.map +0 -1
  164. package/dist/chunk-CPUZRZ2A.js.map +0 -1
  165. package/dist/chunk-F5DZJLU3.js.map +0 -1
  166. package/dist/chunk-FIYZLITH.js.map +0 -1
  167. package/dist/chunk-LTTRND4A.js +0 -135
  168. package/dist/chunk-LTTRND4A.js.map +0 -1
  169. package/dist/chunk-PAAL45FJ.js.map +0 -1
  170. package/dist/chunk-QHIEYBLV.js +0 -320
  171. package/dist/chunk-QHIEYBLV.js.map +0 -1
  172. package/dist/chunk-SXQQ2ZSR.js.map +0 -1
  173. package/dist/chunk-WOHCAMDQ.js.map +0 -1
  174. package/dist/chunk-ZPZFPVDN.js +0 -67
  175. package/dist/chunk-ZPZFPVDN.js.map +0 -1
  176. package/dist/cli-LMHGCZ5S.js.map +0 -1
  177. package/dist/config-XVXZ3V2Q.js +0 -206
  178. package/dist/config-XVXZ3V2Q.js.map +0 -1
  179. package/dist/doctor-MVLZRVPU.js +0 -338
  180. package/dist/doctor-MVLZRVPU.js.map +0 -1
  181. package/dist/usdc-OQUOFF6R.js +0 -18
  182. package/dist/wallet-NRKWLKHX.js +0 -153
  183. package/dist/wallet-NRKWLKHX.js.map +0 -1
  184. package/dist/wallet-QUWK2PA4.js +0 -22
  185. /package/dist/{_esm-ZH2J4QEH.js.map → _esm-C5CRWCYU.js.map} +0 -0
  186. /package/dist/{ccip-FXWZDDF5.js.map → _esm-N4KAVXQR.js.map} +0 -0
  187. /package/dist/{chunk-3IMLRUZE.js.map → buy-FMDBZ4NY.js.map} +0 -0
  188. /package/dist/{secp256k1-35YNNB6F.js.map → candidate-7LAELUQD.js.map} +0 -0
  189. /package/dist/{usdc-OQUOFF6R.js.map → ccip-RPPPKTJR.js.map} +0 -0
  190. /package/dist/{wallet-QUWK2PA4.js.map → ccip-ZGGWQN4X.js.map} +0 -0
  191. /package/dist/{mine.wasm-GQECMSGN.js.map → mine.wasm-6PIT3DK6.js.map} +0 -0
@@ -0,0 +1,154 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ HOSTED_SKILL_NAME,
4
+ readSkillFile
5
+ } from "./chunk-P74I3WH4.js";
6
+ import {
7
+ hasCode
8
+ } from "./chunk-2I4QTOLB.js";
9
+ import {
10
+ CliError,
11
+ writeFileAtomic
12
+ } from "./chunk-PZRAAAY2.js";
13
+
14
+ // src/lib/skill-writer.ts
15
+ import { existsSync } from "fs";
16
+ import { lstat, readFile, readdir, realpath, stat } from "fs/promises";
17
+ import { dirname, join, relative } from "path";
18
+ async function installSkill(srcDir, destDir, dryRun, name, opts = {}) {
19
+ const src = await readTree(srcDir);
20
+ if (src === null) {
21
+ throw new CliError("INTERNAL", `Packaged skill source ${srcDir} is empty`);
22
+ }
23
+ const writeTo = /* @__PURE__ */ new Map();
24
+ await assertReachable(destDir, name);
25
+ await assertNoCaseCollision(destDir, name);
26
+ for (const rel of src.keys()) {
27
+ const declared = join(destDir, rel);
28
+ writeTo.set(
29
+ rel,
30
+ opts.followSymlinks === false ? declared : await resolveThroughLink(declared, name)
31
+ );
32
+ }
33
+ let differs = false;
34
+ let preexisting = false;
35
+ for (const [rel, content] of src) {
36
+ const current = await readShippedFile(writeTo.get(rel), name, destDir);
37
+ if (rel === "SKILL.md") preexisting = current !== null;
38
+ if (current === null || !current.equals(content)) differs = true;
39
+ }
40
+ const change = !preexisting ? "create" : differs ? "update" : "none";
41
+ if (!dryRun && change !== "none") {
42
+ for (const [rel, content] of src) {
43
+ const target = writeTo.get(rel);
44
+ try {
45
+ const current = await stat(target).catch(() => null);
46
+ await writeFileAtomic(
47
+ target,
48
+ content,
49
+ current === null ? {} : { mode: current.mode & 511 }
50
+ );
51
+ } catch (err) {
52
+ throw wrapWriteError(
53
+ err,
54
+ destDir,
55
+ `the ${name} skill`,
56
+ await deepestExisting(dirname(target)),
57
+ { expected: ": a skill is a directory holding SKILL.md" }
58
+ );
59
+ }
60
+ }
61
+ }
62
+ if (change === "create") return { status: dryRun ? "would-install" : "installed", preexisting };
63
+ if (change === "none") return { status: "up-to-date", preexisting };
64
+ return {
65
+ status: dryRun ? "would-update" : "updated",
66
+ preexisting,
67
+ // The hosted skill is a MIRROR of tenjin.blog/skills.md (roadmap G4), so a
68
+ // differing local copy is a replacement, not the drift warning the CLI skills
69
+ // get. Neither side carries a version or date, so the wording claims no
70
+ // direction: the local file may well be a newer fetch than this package's copy.
71
+ warning: name === HOSTED_SKILL_NAME ? `${destDir}: the hosted Tenjin skill differed and ${dryRun ? "would be" : "was"} replaced by this package's mirror of tenjin.blog/skills.md, which may be older; it stays as the zero-install fallback. Re-fetch it from tenjin.blog/skills.md if you need the current one.` : `${destDir}: local edits to ${name}'s SKILL.md ${dryRun ? "would be" : "were"} overwritten (the packaged copy is canonical).`
72
+ };
73
+ }
74
+ async function readShippedFile(path, name, destDir) {
75
+ const read = await readSkillFile(path);
76
+ if (read.kind === "absent") return null;
77
+ if (read.kind === "ok") return read.bytes;
78
+ if (read.kind === "not-regular") {
79
+ throw new CliError("INTERNAL", `${path} is not a regular file, so ${name} was not written.`, {
80
+ fix: `A skill file must be a regular file. Check what is there (\`ls -l ${path}\`) and remove or replace it, then re-run \`tenjin install\`.`
81
+ });
82
+ }
83
+ throw wrapWriteError(read.err, destDir, `the ${name} skill`, path, { verb: "read" });
84
+ }
85
+ async function resolveThroughLink(path, name) {
86
+ const entry = await lstat(path).catch(() => null);
87
+ if (entry === null || !entry.isSymbolicLink()) return path;
88
+ const target = await realpath(path).catch(() => null);
89
+ if (target !== null) return target;
90
+ throw new CliError("INTERNAL", `${path} is a broken symlink, so ${name} was not written.`, {
91
+ fix: `Point it at a path that exists, or remove it (\`ls -ld ${path}\`), then re-run \`tenjin install\`.`
92
+ });
93
+ }
94
+ async function assertNoCaseCollision(destDir, name) {
95
+ if (!existsSync(destDir)) return;
96
+ const entries = await readdir(dirname(destDir)).catch(() => null);
97
+ if (entries === null || entries.includes(name)) return;
98
+ const variant = entries.find((e) => e.toLowerCase() === name.toLowerCase());
99
+ if (variant === void 0) return;
100
+ const actual = join(dirname(destDir), variant);
101
+ throw new CliError(
102
+ "INTERNAL",
103
+ `${actual} is a case variant of the ${name} skill and this filesystem treats them as the same directory, so ${name} was not written.`,
104
+ {
105
+ fix: `Rename or remove ${actual}, then re-run \`tenjin install\`.`
106
+ }
107
+ );
108
+ }
109
+ async function assertReachable(destDir, name) {
110
+ const entry = await lstat(destDir).catch(() => null);
111
+ if (entry?.isSymbolicLink() !== true) return;
112
+ if (await realpath(destDir).catch(() => null) !== null) return;
113
+ throw new CliError("INTERNAL", `${destDir} is a broken symlink, so ${name} was not written.`, {
114
+ fix: `Point it at a directory that exists, or remove it (\`ls -ld ${destDir}\`), then re-run \`tenjin install\`.`
115
+ });
116
+ }
117
+ async function deepestExisting(dir) {
118
+ for (let cur = dir; ; cur = dirname(cur)) {
119
+ if (existsSync(cur)) return realpath(cur).catch(() => cur);
120
+ if (dirname(cur) === cur) return cur;
121
+ }
122
+ }
123
+ function wrapWriteError(err, dest, subject, culprit, opts = {}) {
124
+ const verb = opts.verb ?? "write";
125
+ const denied = hasCode(err, "EACCES") || hasCode(err, "EPERM");
126
+ const missing = hasCode(err, "ENOENT");
127
+ const wrongKind = hasCode(err, "ENOTDIR") || hasCode(err, "EISDIR");
128
+ if (!denied && !missing && !wrongKind) return err;
129
+ const fix = denied ? `Permission denied on ${culprit}. Check it (\`ls -ld ${culprit}\`), then re-run \`tenjin install\`.` : wrongKind ? `${dest} (or a path inside it) is not the kind of thing it needs to be${opts.expected ?? ""}. Check it (\`ls -ld ${dest}\`), then re-run \`tenjin install\`.` : `${dest} could not be created; if it is a symlink, check that its target exists (\`ls -ld ${dest}\`), then re-run \`tenjin install\`.`;
130
+ return new CliError(
131
+ "INTERNAL",
132
+ `Could not ${verb} ${subject} ${verb === "read" ? "at" : "to"} ${dest}.`,
133
+ { fix, cause: err }
134
+ );
135
+ }
136
+ async function readTree(dir) {
137
+ if (!existsSync(dir)) return null;
138
+ const entries = await readdir(dir, { recursive: true, withFileTypes: true });
139
+ const files = /* @__PURE__ */ new Map();
140
+ for (const entry of entries) {
141
+ if (!entry.isFile()) continue;
142
+ const full = join(entry.parentPath, entry.name);
143
+ files.set(relative(dir, full), await readFile(full));
144
+ }
145
+ return files;
146
+ }
147
+
148
+ export {
149
+ installSkill,
150
+ resolveThroughLink,
151
+ deepestExisting,
152
+ wrapWriteError
153
+ };
154
+ //# sourceMappingURL=chunk-X3OOVSPX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/skill-writer.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { lstat, readFile, readdir, realpath, stat } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { writeFileAtomic } from './atomic-json';\nimport { hasCode } from './errno';\nimport { CliError } from './errors';\nimport { HOSTED_SKILL_NAME, readSkillFile } from './skill-wiring';\n\n/**\n * Writing one packaged skill into one harness directory, and the path guards that\n * write needs. Its own module, free of the command layer's dependencies, because\n * `install` and the post-command self-heal both write skills and the heal runs on\n * every command: reaching into commands/install would parse the wallet's viem\n * chunk on a `tenjin config`.\n */\n\nexport type SkillInstallStatus =\n 'installed' | 'updated' | 'up-to-date' | 'would-install' | 'would-update';\n\nexport interface SkillInstallResult {\n status: SkillInstallStatus;\n warning?: string;\n /** Was a real copy (a SKILL.md, not just the directory) already on disk before this run? */\n preexisting: boolean;\n}\n\nexport interface SkillWriteOptions {\n /**\n * Write THROUGH a symlinked destination (default), or replace it. `install`\n * follows the link, because the operator pointed it somewhere on purpose. The\n * unattended self-heal does not, and passes false: it has already refused every\n * link it could see, and this closes the gap between that look and this write,\n * where a link appearing in between would otherwise be followed. `rename` never\n * follows its final component, so the worst a race can now do is leave our\n * regular file where the new link was.\n */\n followSymlinks?: boolean;\n}\n\nexport async function installSkill(\n srcDir: string,\n destDir: string,\n dryRun: boolean,\n name: string,\n opts: SkillWriteOptions = {},\n): Promise<SkillInstallResult> {\n const src = await readTree(srcDir);\n if (src === null) {\n // assertSkillsSource already guards SKILL.md; this is defensive for an empty dir.\n throw new CliError('INTERNAL', `Packaged skill source ${srcDir} is empty`);\n }\n\n // Only the files this package SHIPS are read and written. Everything else in the\n // directory belongs to the operator: never inspected, listed, or removed. That is\n // what package managers do (npm, dpkg, Homebrew all own their files, not the\n // directory), and wholesale replacement was the single cause behind a run of\n // data-loss, symlink and enumeration bugs.\n //\n // Resolved on BOTH paths, dry run included, so a dry run cannot promise a write\n // the real run refuses.\n const writeTo = new Map<string, string>();\n await assertReachable(destDir, name);\n await assertNoCaseCollision(destDir, name);\n for (const rel of src.keys()) {\n const declared = join(destDir, rel);\n writeTo.set(\n rel,\n opts.followSymlinks === false ? declared : await resolveThroughLink(declared, name),\n );\n }\n\n let differs = false;\n let preexisting = false;\n for (const [rel, content] of src) {\n const current = await readShippedFile(writeTo.get(rel)!, name, destDir);\n if (rel === 'SKILL.md') preexisting = current !== null;\n if (current === null || !current.equals(content)) differs = true;\n }\n const change = !preexisting ? 'create' : differs ? 'update' : 'none';\n\n if (!dryRun && change !== 'none') {\n for (const [rel, content] of src) {\n const target = writeTo.get(rel)!;\n try {\n // An existing file keeps the mode it has. A skill an operator (or their\n // dotfiles) made group-readable or read-only is theirs to have set that\n // way, and an update is no reason to hand it back at the default 0644.\n const current = await stat(target).catch(() => null);\n await writeFileAtomic(\n target,\n content,\n current === null ? {} : { mode: current.mode & 0o777 },\n );\n } catch (err) {\n // Culprit is derived from the file that FAILED, not assumed to be the\n // skills root: an existing skill directory that refuses the temp file is\n // itself the thing to chmod, and a symlinked SKILL.md fails in the link's\n // TARGET directory, which no path under destDir names.\n throw wrapWriteError(\n err,\n destDir,\n `the ${name} skill`,\n await deepestExisting(dirname(target)),\n { expected: ': a skill is a directory holding SKILL.md' },\n );\n }\n }\n }\n\n if (change === 'create') return { status: dryRun ? 'would-install' : 'installed', preexisting };\n if (change === 'none') return { status: 'up-to-date', preexisting };\n return {\n status: dryRun ? 'would-update' : 'updated',\n preexisting,\n // The hosted skill is a MIRROR of tenjin.blog/skills.md (roadmap G4), so a\n // differing local copy is a replacement, not the drift warning the CLI skills\n // get. Neither side carries a version or date, so the wording claims no\n // direction: the local file may well be a newer fetch than this package's copy.\n warning:\n name === HOSTED_SKILL_NAME\n ? `${destDir}: the hosted Tenjin skill differed and ${dryRun ? 'would be' : 'was'} replaced by this package's mirror of tenjin.blog/skills.md, which may be older; it stays as the zero-install fallback. Re-fetch it from tenjin.blog/skills.md if you need the current one.`\n : `${destDir}: local edits to ${name}'s SKILL.md ${dryRun ? 'would be' : 'were'} overwritten (the packaged copy is canonical).`,\n };\n}\n\n/**\n * Read a shipped file, or null when it is not there.\n *\n * The node-type guard lives in `readSkillFile`, shared with the wiring check and\n * the staleness check, because all three read the same operator-controlled paths\n * and a pipe at one of them used to hang whichever command got there first.\n */\nasync function readShippedFile(\n path: string,\n name: string,\n destDir: string,\n): Promise<Buffer | null> {\n const read = await readSkillFile(path);\n if (read.kind === 'absent') return null;\n if (read.kind === 'ok') return read.bytes;\n if (read.kind === 'not-regular') {\n throw new CliError('INTERNAL', `${path} is not a regular file, so ${name} was not written.`, {\n fix: `A skill file must be a regular file. Check what is there (\\`ls -l ${path}\\`) and remove or replace it, then re-run \\`tenjin install\\`.`,\n });\n }\n // Names the FILE, not its directory: this is a read failure, and pointing at a\n // perfectly writable parent is what sent operators to chmod the wrong thing.\n throw wrapWriteError(read.err, destDir, `the ${name} skill`, path, { verb: 'read' });\n}\n\n/**\n * A destination the operator manages through a symlink is written THROUGH it, so\n * their link survives and their target is what actually changes. Same call the\n * settings.json writer makes, and the same reason: committing with `rename` over a\n * link would replace it with a regular file and strand the target.\n */\nexport async function resolveThroughLink(path: string, name: string): Promise<string> {\n const entry = await lstat(path).catch(() => null);\n if (entry === null || !entry.isSymbolicLink()) return path;\n const target = await realpath(path).catch(() => null);\n if (target !== null) return target;\n throw new CliError('INTERNAL', `${path} is a broken symlink, so ${name} was not written.`, {\n fix: `Point it at a path that exists, or remove it (\\`ls -ld ${path}\\`), then re-run \\`tenjin install\\`.`,\n });\n}\n\n/**\n * On a case-insensitive filesystem (the macOS default), a user directory named a\n * case variant of a shipped skill ALIASES the skill's path, so the write would\n * replace the user's own SKILL.md under a warning naming a path that is not on\n * disk. Detected by the alias itself: the destination resolves but the parent\n * lists only a differently-cased entry, which also means a case-SENSITIVE\n * filesystem (where both names can coexist) never trips this. Dry runs too.\n */\nasync function assertNoCaseCollision(destDir: string, name: string): Promise<void> {\n if (!existsSync(destDir)) return;\n const entries = await readdir(dirname(destDir)).catch(() => null);\n if (entries === null || entries.includes(name)) return;\n const variant = entries.find((e) => e.toLowerCase() === name.toLowerCase());\n if (variant === undefined) return;\n const actual = join(dirname(destDir), variant);\n throw new CliError(\n 'INTERNAL',\n `${actual} is a case variant of the ${name} skill and this filesystem treats them as the same directory, so ${name} was not written.`,\n {\n fix: `Rename or remove ${actual}, then re-run \\`tenjin install\\`.`,\n },\n );\n}\n\n/**\n * Fail a destination directory that is a BROKEN SYMLINK, on dry runs too, so a dry\n * run cannot report `would-install` where the real run cannot write. It checks only\n * that: an unwritable but real directory passes here and fails at the write, with\n * the permission-denied error.\n */\nasync function assertReachable(destDir: string, name: string): Promise<void> {\n const entry = await lstat(destDir).catch(() => null);\n if (entry?.isSymbolicLink() !== true) return;\n if ((await realpath(destDir).catch(() => null)) !== null) return;\n throw new CliError('INTERNAL', `${destDir} is a broken symlink, so ${name} was not written.`, {\n fix: `Point it at a directory that exists, or remove it (\\`ls -ld ${destDir}\\`), then re-run \\`tenjin install\\`.`,\n });\n}\n\n/**\n * The directory a denied WRITE should point the operator at: the deepest existing\n * ancestor of the failed target's directory, RESOLVED. An existing skill directory\n * that refuses the temp file names itself; a directory that could not be created\n * names the ancestor that refused to create it, because `ls -ld` on a path that is\n * not there says nothing. Resolved because a destination managed through a symlink\n * denies the write in the link's TARGET, and telling the operator to chmod the\n * link's path leaves them staring at a healthy link.\n */\nexport async function deepestExisting(dir: string): Promise<string> {\n for (let cur = dir; ; cur = dirname(cur)) {\n if (existsSync(cur)) return realpath(cur).catch(() => cur);\n if (dirname(cur) === cur) return cur;\n }\n}\n\n/** A raw errno under INTERNAL reads as a CLI bug and carries no fix. */\nexport function wrapWriteError(\n err: unknown,\n /** The destination as the operator knows it (the declared path, pre-resolution). */\n dest: string,\n /** What could not be written, e.g. `the tenjin-search skill` or `the Tenjin pointer`. */\n subject: string,\n /**\n * The path to point the operator at. A READ failure names the file itself, which\n * is the thing whose mode is wrong. A WRITE failure names the deepest existing\n * directory on the failed target's resolved path.\n */\n culprit: string,\n opts: {\n /** Which side failed; a read error reported as \"could not write\" misleads. */\n verb?: 'read' | 'write';\n /** Sentence tail for the wrong-kind fix, telling the operator the expected shape. */\n expected?: string;\n } = {},\n): unknown {\n const verb = opts.verb ?? 'write';\n const denied = hasCode(err, 'EACCES') || hasCode(err, 'EPERM');\n const missing = hasCode(err, 'ENOENT');\n // A skills directory that resolves to a regular file, or a SKILL.md that resolves\n // to a directory. Pathological, but a raw ENOTDIR/EISDIR says nothing about which\n // path is the wrong kind of thing.\n const wrongKind = hasCode(err, 'ENOTDIR') || hasCode(err, 'EISDIR');\n if (!denied && !missing && !wrongKind) return err;\n const fix = denied\n ? `Permission denied on ${culprit}. Check it (\\`ls -ld ${culprit}\\`), then re-run \\`tenjin install\\`.`\n : wrongKind\n ? `${dest} (or a path inside it) is not the kind of thing it needs to be${opts.expected ?? ''}. Check it (\\`ls -ld ${dest}\\`), then re-run \\`tenjin install\\`.`\n : `${dest} could not be created; if it is a symlink, check that its target exists (\\`ls -ld ${dest}\\`), then re-run \\`tenjin install\\`.`;\n return new CliError(\n 'INTERNAL',\n `Could not ${verb} ${subject} ${verb === 'read' ? 'at' : 'to'} ${dest}.`,\n { fix, cause: err },\n );\n}\n\n/**\n * Read a directory tree into a rel-path -> content map, or null when it does not\n * exist. Reads as raw `Buffer`, not `utf8`: today's skills are markdown-only, but\n * this is a general recursive dir-copy, and decoding to a string here would\n * silently corrupt a future non-text asset (an image, a font) on write, or worse,\n * make two different corrupted binaries both decode to U+FFFD and compare equal.\n */\nasync function readTree(dir: string): Promise<Map<string, Buffer> | null> {\n if (!existsSync(dir)) return null;\n const entries = await readdir(dir, { recursive: true, withFileTypes: true });\n const files = new Map<string, Buffer>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const full = join(entry.parentPath, entry.name);\n files.set(relative(dir, full), await readFile(full));\n }\n return files;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,UAAU,SAAS,UAAU,YAAY;AACzD,SAAS,SAAS,MAAM,gBAAgB;AAqCxC,eAAsB,aACpB,QACA,SACA,QACA,MACA,OAA0B,CAAC,GACE;AAC7B,QAAM,MAAM,MAAM,SAAS,MAAM;AACjC,MAAI,QAAQ,MAAM;AAEhB,UAAM,IAAI,SAAS,YAAY,yBAAyB,MAAM,WAAW;AAAA,EAC3E;AAUA,QAAM,UAAU,oBAAI,IAAoB;AACxC,QAAM,gBAAgB,SAAS,IAAI;AACnC,QAAM,sBAAsB,SAAS,IAAI;AACzC,aAAW,OAAO,IAAI,KAAK,GAAG;AAC5B,UAAM,WAAW,KAAK,SAAS,GAAG;AAClC,YAAQ;AAAA,MACN;AAAA,MACA,KAAK,mBAAmB,QAAQ,WAAW,MAAM,mBAAmB,UAAU,IAAI;AAAA,IACpF;AAAA,EACF;AAEA,MAAI,UAAU;AACd,MAAI,cAAc;AAClB,aAAW,CAAC,KAAK,OAAO,KAAK,KAAK;AAChC,UAAM,UAAU,MAAM,gBAAgB,QAAQ,IAAI,GAAG,GAAI,MAAM,OAAO;AACtE,QAAI,QAAQ,WAAY,eAAc,YAAY;AAClD,QAAI,YAAY,QAAQ,CAAC,QAAQ,OAAO,OAAO,EAAG,WAAU;AAAA,EAC9D;AACA,QAAM,SAAS,CAAC,cAAc,WAAW,UAAU,WAAW;AAE9D,MAAI,CAAC,UAAU,WAAW,QAAQ;AAChC,eAAW,CAAC,KAAK,OAAO,KAAK,KAAK;AAChC,YAAM,SAAS,QAAQ,IAAI,GAAG;AAC9B,UAAI;AAIF,cAAM,UAAU,MAAM,KAAK,MAAM,EAAE,MAAM,M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AA,EACnC;AACF;AAGO,SAAS,eACd,KAEA,MAEA,SAMA,SACA,OAKI,CAAC,GACI;AACT,QAAM,OAAO,KAAK,QAAQ;AAC1B,QAAM,SAAS,QAAQ,KAAK,QAAQ,KAAK,QAAQ,KAAK,OAAO;AAC7D,QAAM,UAAU,QAAQ,KAAK,QAAQ;AAIrC,QAAM,YAAY,QAAQ,KAAK,SAAS,KAAK,QAAQ,KAAK,QAAQ;AAClE,MAAI,CAAC,UAAU,CAAC,WAAW,CAAC,UAAW,QAAO;AAC9C,QAAM,MAAM,SACR,wBAAwB,OAAO,wBAAwB,OAAO,yCAC9D,YACE,GAAG,IAAI,iEAAiE,KAAK,YAAY,EAAE,wBAAwB,IAAI,yCACvH,GAAG,IAAI,qFAAqF,IAAI;AACtG,SAAO,IAAI;AAAA,IACT;AAAA,IACA,aAAa,IAAI,IAAI,OAAO,IAAI,SAAS,SAAS,OAAO,IAAI,IAAI,IAAI;AAAA,IACrE,EAAE,KAAK,OAAO,IAAI;AAAA,EACpB;AACF;AASA,eAAe,SAAS,KAAkD;AACxE,MAAI,CAAC,WAAW,GAAG,EAAG,QAAO;AAC7B,QAAM,UAAU,MAAM,QAAQ,KAAK,EAAE,WAAW,MAAM,eAAe,KAAK,CAAC;AAC3E,QAAM,QAAQ,oBAAI,IAAoB;AACtC,aAAW,SAAS,SAAS;AAC3B,QAAI,CAAC,MAAM,OAAO,EAAG;AACrB,UAAM,OAAO,KAAK,MAAM,YAAY,MAAM,IAAI;AAC9C,UAAM,IAAI,SAAS,KAAK,IAAI,GAAG,MAAM,SAAS,IAAI,CAAC;AAAA,EACrD;AACA,SAAO;AACT;","names":[]}
@@ -0,0 +1,204 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ Hash,
4
+ abytes,
5
+ aexists,
6
+ anumber,
7
+ aoutput,
8
+ clean,
9
+ createHasher,
10
+ rotlBH,
11
+ rotlBL,
12
+ rotlSH,
13
+ rotlSL,
14
+ split,
15
+ swap32IfBE,
16
+ toBytes,
17
+ u32
18
+ } from "./chunk-KYQVEKP5.js";
19
+
20
+ // node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha3.js
21
+ var _0n = BigInt(0);
22
+ var _1n = BigInt(1);
23
+ var _2n = BigInt(2);
24
+ var _7n = BigInt(7);
25
+ var _256n = BigInt(256);
26
+ var _0x71n = BigInt(113);
27
+ var SHA3_PI = [];
28
+ var SHA3_ROTL = [];
29
+ var _SHA3_IOTA = [];
30
+ for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
31
+ [x, y] = [y, (2 * x + 3 * y) % 5];
32
+ SHA3_PI.push(2 * (5 * y + x));
33
+ SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64);
34
+ let t = _0n;
35
+ for (let j = 0; j < 7; j++) {
36
+ R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n;
37
+ if (R & _2n)
38
+ t ^= _1n << (_1n << /* @__PURE__ */ BigInt(j)) - _1n;
39
+ }
40
+ _SHA3_IOTA.push(t);
41
+ }
42
+ var IOTAS = split(_SHA3_IOTA, true);
43
+ var SHA3_IOTA_H = IOTAS[0];
44
+ var SHA3_IOTA_L = IOTAS[1];
45
+ var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s);
46
+ var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s);
47
+ function keccakP(s, rounds = 24) {
48
+ const B = new Uint32Array(5 * 2);
49
+ for (let round = 24 - rounds; round < 24; round++) {
50
+ for (let x = 0; x < 10; x++)
51
+ B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
52
+ for (let x = 0; x < 10; x += 2) {
53
+ const idx1 = (x + 8) % 10;
54
+ const idx0 = (x + 2) % 10;
55
+ const B0 = B[idx0];
56
+ const B1 = B[idx0 + 1];
57
+ const Th = rotlH(B0, B1, 1) ^ B[idx1];
58
+ const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
59
+ for (let y = 0; y < 50; y += 10) {
60
+ s[x + y] ^= Th;
61
+ s[x + y + 1] ^= Tl;
62
+ }
63
+ }
64
+ let curH = s[2];
65
+ let curL = s[3];
66
+ for (let t = 0; t < 24; t++) {
67
+ const shift = SHA3_ROTL[t];
68
+ const Th = rotlH(curH, curL, shift);
69
+ const Tl = rotlL(curH, curL, shift);
70
+ const PI = SHA3_PI[t];
71
+ curH = s[PI];
72
+ curL = s[PI + 1];
73
+ s[PI] = Th;
74
+ s[PI + 1] = Tl;
75
+ }
76
+ for (let y = 0; y < 50; y += 10) {
77
+ for (let x = 0; x < 10; x++)
78
+ B[x] = s[y + x];
79
+ for (let x = 0; x < 10; x++)
80
+ s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
81
+ }
82
+ s[0] ^= SHA3_IOTA_H[round];
83
+ s[1] ^= SHA3_IOTA_L[round];
84
+ }
85
+ clean(B);
86
+ }
87
+ var Keccak = class _Keccak extends Hash {
88
+ // NOTE: we accept arguments in bytes instead of bits here.
89
+ constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
90
+ super();
91
+ this.pos = 0;
92
+ this.posOut = 0;
93
+ this.finished = false;
94
+ this.destroyed = false;
95
+ this.enableXOF = false;
96
+ this.blockLen = blockLen;
97
+ this.suffix = suffix;
98
+ this.outputLen = outputLen;
99
+ this.enableXOF = enableXOF;
100
+ this.rounds = rounds;
101
+ anumber(outputLen);
102
+ if (!(0 < blockLen && blockLen < 200))
103
+ throw new Error("only keccak-f1600 function is supported");
104
+ this.state = new Uint8Array(200);
105
+ this.state32 = u32(this.state);
106
+ }
107
+ clone() {
108
+ return this._cloneInto();
109
+ }
110
+ keccak() {
111
+ swap32IfBE(this.state32);
112
+ keccakP(this.state32, this.rounds);
113
+ swap32IfBE(this.state32);
114
+ this.posOut = 0;
115
+ this.pos = 0;
116
+ }
117
+ update(data) {
118
+ aexists(this);
119
+ data = toBytes(data);
120
+ abytes(data);
121
+ const { blockLen, state } = this;
122
+ const len = data.length;
123
+ for (let pos = 0; pos < len; ) {
124
+ const take = Math.min(blockLen - this.pos, len - pos);
125
+ for (let i = 0; i < take; i++)
126
+ state[this.pos++] ^= data[pos++];
127
+ if (this.pos === blockLen)
128
+ this.keccak();
129
+ }
130
+ return this;
131
+ }
132
+ finish() {
133
+ if (this.finished)
134
+ return;
135
+ this.finished = true;
136
+ const { state, suffix, pos, blockLen } = this;
137
+ state[pos] ^= suffix;
138
+ if ((suffix & 128) !== 0 && pos === blockLen - 1)
139
+ this.keccak();
140
+ state[blockLen - 1] ^= 128;
141
+ this.keccak();
142
+ }
143
+ writeInto(out) {
144
+ aexists(this, false);
145
+ abytes(out);
146
+ this.finish();
147
+ const bufferOut = this.state;
148
+ const { blockLen } = this;
149
+ for (let pos = 0, len = out.length; pos < len; ) {
150
+ if (this.posOut >= blockLen)
151
+ this.keccak();
152
+ const take = Math.min(blockLen - this.posOut, len - pos);
153
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
154
+ this.posOut += take;
155
+ pos += take;
156
+ }
157
+ return out;
158
+ }
159
+ xofInto(out) {
160
+ if (!this.enableXOF)
161
+ throw new Error("XOF is not possible for this instance");
162
+ return this.writeInto(out);
163
+ }
164
+ xof(bytes) {
165
+ anumber(bytes);
166
+ return this.xofInto(new Uint8Array(bytes));
167
+ }
168
+ digestInto(out) {
169
+ aoutput(out, this);
170
+ if (this.finished)
171
+ throw new Error("digest() was already called");
172
+ this.writeInto(out);
173
+ this.destroy();
174
+ return out;
175
+ }
176
+ digest() {
177
+ return this.digestInto(new Uint8Array(this.outputLen));
178
+ }
179
+ destroy() {
180
+ this.destroyed = true;
181
+ clean(this.state);
182
+ }
183
+ _cloneInto(to) {
184
+ const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
185
+ to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
186
+ to.state32.set(this.state32);
187
+ to.pos = this.pos;
188
+ to.posOut = this.posOut;
189
+ to.finished = this.finished;
190
+ to.rounds = rounds;
191
+ to.suffix = suffix;
192
+ to.outputLen = outputLen;
193
+ to.enableXOF = enableXOF;
194
+ to.destroyed = this.destroyed;
195
+ return to;
196
+ }
197
+ };
198
+ var gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));
199
+ var keccak_256 = /* @__PURE__ */ (() => gen(1, 136, 256 / 8))();
200
+
201
+ export {
202
+ keccak_256
203
+ };
204
+ //# sourceMappingURL=chunk-XJN5WUKL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/src/sha3.ts"],"sourcesContent":["/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.ts';\n// prettier-ignore\nimport {\n abytes, aexists, anumber, aoutput,\n clean, createHasher, createXOFer, Hash,\n swap32IfBE,\n toBytes, u32,\n type CHash, type CHashXO, type HashXOF, type Input\n} from './utils.ts';\n\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI: number[] = [];\nconst SHA3_ROTL: number[] = [];\nconst _SHA3_IOTA: bigint[] = [];\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n) t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h: number, l: number, s: number) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h: number, l: number, s: number) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s: Uint32Array, rounds: number = 24): void {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++) B[x] = s[y + x];\n for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n\n/** Keccak sponge function. */\nexport class Keccak extends Hash<Keccak> implements HashXOF<Keccak> {\n protected state: Uint8Array;\n protected pos = 0;\n protected posOut = 0;\n protected finished = false;\n protected state32: Uint32Array;\n protected destroyed = false;\n\n public blockLen: number;\n public suffix: number;\n public outputLen: number;\n protected enableXOF = false;\n protected rounds: number;\n\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(\n blockLen: number,\n suffix: number,\n outputLen: number,\n enableXOF = false,\n rounds: number = 24\n ) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone(): Keccak {\n return this._cloneInto();\n }\n protected keccak(): void {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data: Input): this {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen) this.keccak();\n }\n return this;\n }\n protected finish(): void {\n if (this.finished) return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n protected writeInto(out: Uint8Array): Uint8Array {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len; ) {\n if (this.posOut >= blockLen) this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out: Uint8Array): Uint8Array {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF) throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes: number): Uint8Array {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out: Uint8Array): Uint8Array {\n aoutput(out, this);\n if (this.finished) throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest(): Uint8Array {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to?: Keccak): Keccak {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds);\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\n\nconst gen = (suffix: number, blockLen: number, outputLen: number) =>\n createHasher(() => new Keccak(blockLen, suffix, outputLen));\n\n/** SHA3-224 hash function. */\nexport const sha3_224: CHash = /* @__PURE__ */ (() => gen(0x06, 144, 224 / 8))();\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256: CHash = /* @__PURE__ */ (() => gen(0x06, 136, 256 / 8))();\n/** SHA3-384 hash function. */\nexport const sha3_384: CHash = /* @__PURE__ */ (() => gen(0x06, 104, 384 / 8))();\n/** SHA3-512 hash function. */\nexport const sha3_512: CHash = /* @__PURE__ */ (() => gen(0x06, 72, 512 / 8))();\n\n/** keccak-224 hash function. */\nexport const keccak_224: CHash = /* @__PURE__ */ (() => gen(0x01, 144, 224 / 8))();\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256: CHash = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();\n/** keccak-384 hash function. */\nexport const keccak_384: CHash = /* @__PURE__ */ (() => gen(0x01, 104, 384 / 8))();\n/** keccak-512 hash function. */\nexport const keccak_512: CHash = /* @__PURE__ */ (() => gen(0x01, 72, 512 / 8))();\n\nexport type ShakeOpts = { dkLen?: number };\n\nconst genShake = (suffix: number, blockLen: number, outputLen: number) =>\n createXOFer<HashXOF<Keccak>, ShakeOpts>(\n (opts: ShakeOpts = {}) =>\n new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true)\n );\n\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128: CHashXO = /* @__PURE__ */ (() => genShake(0x1f, 168, 128 / 8))();\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256: CHashXO = /* @__PURE__ */ (() => genShake(0x1f, 136, 256 / 8))();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAwBA,IAAM,MAAM,OAAO,CAAC;AACpB,IAAM,MAAM,OAAO,CAAC;AACpB,IAAM,MAAM,OAAO,CAAC;AACpB,IAAM,MAAM,OAAO,CAAC;AACpB,IAAM,QAAQ,OAAO,GAAG;AACxB,IAAM,SAAS,OAAO,GAAI;AAC1B,IAAM,UAAoB,CAAA;AAC1B,IAAM,YAAsB,CAAA;AAC5B,IAAM,aAAuB,CAAA;AAC7B,SAAS,QAAQ,GAAG,IAAI,KAAK,IAAI,GAAG,I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Require(import.meta.url);
2
+ import {
3
+ walletPath
4
+ } from "./chunk-ZQIQ55KK.js";
5
+ import {
6
+ hasCode
7
+ } from "./chunk-2I4QTOLB.js";
8
+ import {
9
+ CliError,
10
+ external_exports,
11
+ writeFileAtomicExclusive
12
+ } from "./chunk-PZRAAAY2.js";
13
+
14
+ // src/lib/wallet/store.ts
15
+ import { readFile, stat } from "fs/promises";
16
+ var PRIVATE_KEY_RE = /^0x[0-9a-f]{64}$/i;
17
+ var ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
18
+ var KeystoreV3Schema = external_exports.object({
19
+ crypto: external_exports.object({
20
+ cipher: external_exports.literal("aes-128-ctr"),
21
+ ciphertext: external_exports.string(),
22
+ cipherparams: external_exports.object({ iv: external_exports.string() }),
23
+ kdf: external_exports.enum(["scrypt", "pbkdf2"]),
24
+ kdfparams: external_exports.record(external_exports.string(), external_exports.unknown()),
25
+ mac: external_exports.string()
26
+ }),
27
+ id: external_exports.string(),
28
+ version: external_exports.literal(3)
29
+ });
30
+ var WALLET_SCHEMA_VERSION = 2;
31
+ var WalletRecordSchema = external_exports.object({
32
+ schemaVersion: external_exports.literal(WALLET_SCHEMA_VERSION),
33
+ provider: external_exports.literal("local"),
34
+ address: external_exports.string().regex(ADDRESS_RE, "expected a 0x-prefixed 20-byte address"),
35
+ keystore: KeystoreV3Schema,
36
+ createdAt: external_exports.string()
37
+ });
38
+ async function walletFileExists(dir) {
39
+ return await walletFileMode(dir) !== null;
40
+ }
41
+ async function walletFileMode(dir) {
42
+ try {
43
+ return (await stat(walletPath(dir))).mode & 511;
44
+ } catch (err) {
45
+ if (isNotFound(err)) return null;
46
+ throw err;
47
+ }
48
+ }
49
+ async function readWalletRecord(dir) {
50
+ const path = walletPath(dir);
51
+ let raw;
52
+ try {
53
+ raw = await readFile(path, "utf8");
54
+ } catch (err) {
55
+ if (isNotFound(err)) return null;
56
+ throw new CliError("WALLET_INVALID_KEY", `Could not read the wallet file at ${path}.`, {
57
+ fix: `Check file permissions on ${path}.`,
58
+ cause: err
59
+ });
60
+ }
61
+ let json;
62
+ try {
63
+ json = JSON.parse(raw);
64
+ } catch (err) {
65
+ throw new CliError("WALLET_INVALID_KEY", `The wallet file at ${path} is not valid JSON.`, {
66
+ fix: `Move ${path} aside, then run \`tenjin wallet create\`.`,
67
+ cause: err
68
+ });
69
+ }
70
+ if (isPreEncryptionRecord(json)) {
71
+ throw new CliError(
72
+ "WALLET_INVALID_KEY",
73
+ `The wallet file at ${path} predates encrypted storage.`,
74
+ {
75
+ fix: `Move ${path} aside and run \`tenjin wallet create\`; sweep any funds from the old address first.`
76
+ }
77
+ );
78
+ }
79
+ const newer = newerSchemaVersion(json);
80
+ if (newer !== null) {
81
+ throw new CliError(
82
+ "CONTRACT_MISMATCH",
83
+ `The wallet file at ${path} was written by a newer tenjin-cli (wallet schema v${newer}; this build reads v${WALLET_SCHEMA_VERSION}).`,
84
+ {
85
+ fix: "Upgrade with `npm i -g tenjin-cli`. Do not delete or recreate the wallet: the newer CLI still reads this one, and the funds are on the address it holds."
86
+ }
87
+ );
88
+ }
89
+ const parsed = WalletRecordSchema.safeParse(json);
90
+ if (!parsed.success) {
91
+ throw new CliError(
92
+ "WALLET_INVALID_KEY",
93
+ `The wallet file at ${path} is not a valid wallet record.`,
94
+ {
95
+ fix: `Move ${path} aside, then run \`tenjin wallet create\`.`,
96
+ details: parsed.error.issues
97
+ }
98
+ );
99
+ }
100
+ return parsed.data;
101
+ }
102
+ function walletExistsError(dir, cause) {
103
+ const path = walletPath(dir);
104
+ return new CliError("WALLET_EXISTS", `A wallet already exists at ${path}.`, {
105
+ fix: `Run \`tenjin wallet create --replace\` to archive it and create a new one: its keystore is parked beside the new wallet and its passphrase stays preserved in the OS credential store (service tenjin-cli, account = its address), so its funds remain reachable. That passphrase is unrecoverable \u2014 never delete the credential-store entry, or the wallet's funds are stranded.`,
106
+ ...cause !== void 0 ? { cause } : {}
107
+ });
108
+ }
109
+ async function writeWalletRecord(dir, record) {
110
+ const validated = WalletRecordSchema.parse(record);
111
+ const path = walletPath(dir);
112
+ try {
113
+ await writeFileAtomicExclusive(path, `${JSON.stringify(validated, null, 2)}
114
+ `, {
115
+ mode: 384,
116
+ dirMode: 448
117
+ });
118
+ } catch (err) {
119
+ if (hasCode(err, "EEXIST")) throw walletExistsError(dir, err);
120
+ throw err;
121
+ }
122
+ }
123
+ function newerSchemaVersion(json) {
124
+ if (typeof json !== "object" || json === null) return null;
125
+ const v = json.schemaVersion;
126
+ return typeof v === "number" && Number.isInteger(v) && v > WALLET_SCHEMA_VERSION ? v : null;
127
+ }
128
+ function isPreEncryptionRecord(json) {
129
+ if (typeof json !== "object" || json === null) return false;
130
+ const rec = json;
131
+ return rec.schemaVersion === 1 || "privateKey" in rec;
132
+ }
133
+ function isNotFound(err) {
134
+ return hasCode(err, "ENOENT");
135
+ }
136
+
137
+ export {
138
+ PRIVATE_KEY_RE,
139
+ WALLET_SCHEMA_VERSION,
140
+ walletFileExists,
141
+ walletFileMode,
142
+ readWalletRecord,
143
+ walletExistsError,
144
+ writeWalletRecord
145
+ };
146
+ //# sourceMappingURL=chunk-Y7ERTA7D.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/wallet/store.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport * as Keystore from 'ox/Keystore';\nimport { CliError } from '../errors';\nimport { writeFileAtomicExclusive } from '../atomic-json';\nimport { hasCode } from '../errno';\nimport { walletPath } from '../paths';\n\n/** A 0x-prefixed 32-byte hex private key (case-insensitive). */\nexport const PRIVATE_KEY_RE = /^0x[0-9a-f]{64}$/i;\nconst ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;\n\n/**\n * The at-rest shape of a Keystore v3 document (Web3 Secret Storage). Validated\n * structurally on read so an obviously-corrupt keystore fails as\n * WALLET_INVALID_KEY before we ever ask for a passphrase; the real integrity\n * check is the keystore's own MAC, verified by ox at decrypt time. `kdfparams`\n * stays an open object because scrypt and pbkdf2 carry different fields and only\n * ox needs to interpret them.\n */\nconst KeystoreV3Schema = z.object({\n crypto: z.object({\n cipher: z.literal('aes-128-ctr'),\n ciphertext: z.string(),\n cipherparams: z.object({ iv: z.string() }),\n kdf: z.enum(['scrypt', 'pbkdf2']),\n kdfparams: z.record(z.string(), z.unknown()),\n mac: z.string(),\n }),\n id: z.string(),\n version: z.literal(3),\n});\n\n/** The wallet-record schema this build writes and reads. Anything higher on disk\n * was written by a newer CLI; see `readWalletRecord`. */\nexport const WALLET_SCHEMA_VERSION = 2;\n\n/**\n * The persisted wallet record (schema v2). The private key is NEVER stored in\n * cleartext: `keystore` is a Keystore v3 document (scrypt + AES-128-CTR) and the\n * key is recovered only by decrypting it with the wallet passphrase. `address`\n * stays top-level in cleartext ON PURPOSE so `show`/`balance` keep working\n * without a passphrase; signing decrypts, and so does `doctor` when it can reach\n * a passphrase without prompting. The `provider`\n * discriminator keeps the schema from implying every future wallet embeds a\n * keystore. Validated on read (a corrupt file is WALLET_INVALID_KEY, never a\n * silent partial parse).\n */\nexport const WalletRecordSchema = z.object({\n schemaVersion: z.literal(WALLET_SCHEMA_VERSION),\n provider: z.literal('local'),\n address: z.string().regex(ADDRESS_RE, 'expected a 0x-prefixed 20-byte address'),\n keystore: KeystoreV3Schema,\n createdAt: z.string(),\n});\nexport type WalletRecord = Omit<z.infer<typeof WalletRecordSchema>, 'keystore'> & {\n keystore: Keystore.Keystore;\n};\n\nexport async function walletFileExists(dir: string): Promise<boolean> {\n return (await walletFileMode(dir)) !== null;\n}\n\n/** File permission bits (`mode & 0o777`), or null when the wallet file is absent. */\nexport async function walletFileMode(dir: string): Promise<number | null> {\n try {\n return (await stat(walletPath(dir))).mode & 0o777;\n } catch (err) {\n if (isNotFound(err)) return null;\n throw err;\n }\n}\n\n/** Read + validate the wallet record; null when absent, WALLET_INVALID_KEY when corrupt. */\nexport async function readWalletRecord(dir: string): Promise<WalletRecord | null> {\n const path = walletPath(dir);\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (isNotFound(err)) return null;\n throw new CliError('WALLET_INVALID_KEY', `Could not read the wallet file at ${path}.`, {\n fix: `Check file permissions on ${path}.`,\n cause: err,\n });\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw new CliError('WALLET_INVALID_KEY', `The wallet file at ${path} is not valid JSON.`, {\n fix: `Move ${path} aside, then run \\`tenjin wallet create\\`.`,\n cause: err,\n });\n }\n // A pre-encryption record (schema v1 stored the raw key). There is no in-place\n // migration: the old key must be swept and a fresh encrypted wallet created.\n if (isPreEncryptionRecord(json)) {\n throw new CliError(\n 'WALLET_INVALID_KEY',\n `The wallet file at ${path} predates encrypted storage.`,\n {\n fix: `Move ${path} aside and run \\`tenjin wallet create\\`; sweep any funds from the old address first.`,\n },\n );\n }\n // A NEWER CLI's record is a downgrade, not a corruption, and must be caught\n // BEFORE the generic parse failure below: that failure says to move the file\n // aside and run `wallet create`, which on a downgrade abandons a funded wallet.\n // CONTRACT_MISMATCH is the API layer's code for a schema version skew.\n const newer = newerSchemaVersion(json);\n if (newer !== null) {\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The wallet file at ${path} was written by a newer tenjin-cli (wallet schema v${newer}; this build reads v${WALLET_SCHEMA_VERSION}).`,\n {\n fix: 'Upgrade with `npm i -g tenjin-cli`. Do not delete or recreate the wallet: the newer CLI still reads this one, and the funds are on the address it holds.',\n },\n );\n }\n const parsed = WalletRecordSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError(\n 'WALLET_INVALID_KEY',\n `The wallet file at ${path} is not a valid wallet record.`,\n {\n fix: `Move ${path} aside, then run \\`tenjin wallet create\\`.`,\n details: parsed.error.issues,\n },\n );\n }\n return parsed.data as WalletRecord;\n}\n\n/**\n * The one WALLET_EXISTS error, shared by the create pre-check and the exclusive\n * write's race loser so the two surfaces can never drift apart.\n */\nexport function walletExistsError(dir: string, cause?: unknown): CliError {\n const path = walletPath(dir);\n return new CliError('WALLET_EXISTS', `A wallet already exists at ${path}.`, {\n fix: `Run \\`tenjin wallet create --replace\\` to archive it and create a new one: its keystore is parked beside the new wallet and its passphrase stays preserved in the OS credential store (service tenjin-cli, account = its address), so its funds remain reachable. That passphrase is unrecoverable — never delete the credential-store entry, or the wallet's funds are stranded.`,\n ...(cause !== undefined ? { cause } : {}),\n });\n}\n\n/**\n * Persist a validated record at 0600 in a 0700 dir, NO-CLOBBER. The exclusive\n * write — not an earlier existence check — is the authority: two concurrent\n * `create` runs can both pass a pre-check, but only one can win the atomic\n * commit; the loser surfaces as WALLET_EXISTS instead of silently overwriting\n * (and losing) a non-recoverable key.\n */\nexport async function writeWalletRecord(dir: string, record: WalletRecord): Promise<void> {\n const validated = WalletRecordSchema.parse(record);\n const path = walletPath(dir);\n try {\n await writeFileAtomicExclusive(path, `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n } catch (err) {\n if (hasCode(err, 'EEXIST')) throw walletExistsError(dir, err);\n throw err;\n }\n}\n\n/** The schema version of a record from a future CLI, or null when this build reads it. */\nfunction newerSchemaVersion(json: unknown): number | null {\n if (typeof json !== 'object' || json === null) return null;\n const v = (json as Record<string, unknown>).schemaVersion;\n // Integral only: `2.5` is not a schema we will ship, and calling it \"from the\n // future\" would send the operator into an upgrade loop. Integrality rather than\n // SAFE integrality, because an absurd-but-whole version is still a version, and\n // the alternative branch tells them to move the wallet aside and recreate it.\n return typeof v === 'number' && Number.isInteger(v) && v > WALLET_SCHEMA_VERSION ? v : null;\n}\n\n/** A cleartext-key record from before encrypted storage: schema v1 or a bare `privateKey`. */\nfunction isPreEncryptionRecord(json: unknown): boolean {\n if (typeof json !== 'object' || json === null) return false;\n const rec = json as Record<string, unknown>;\n return rec.schemaVersion === 1 || 'privateKey' in rec;\n}\n\nfunction isNotFound(err: unknown): boolean {\n return hasCode(err, 'ENOENT');\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,UAAU,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