bitbadges 0.35.6 → 0.36.0

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 (214) hide show
  1. package/README.md +43 -1
  2. package/dist/cjs/cli/commands/address.d.ts +3 -0
  3. package/dist/cjs/cli/commands/address.d.ts.map +1 -0
  4. package/dist/cjs/cli/commands/address.js +66 -0
  5. package/dist/cjs/cli/commands/address.js.map +1 -0
  6. package/dist/cjs/cli/commands/alias.d.ts +3 -0
  7. package/dist/cjs/cli/commands/alias.d.ts.map +1 -0
  8. package/dist/cjs/cli/commands/alias.js +62 -0
  9. package/dist/cjs/cli/commands/alias.js.map +1 -0
  10. package/dist/cjs/cli/commands/api.d.ts.map +1 -1
  11. package/dist/cjs/cli/commands/api.js +23 -1
  12. package/dist/cjs/cli/commands/api.js.map +1 -1
  13. package/dist/cjs/cli/commands/auth.d.ts +3 -0
  14. package/dist/cjs/cli/commands/auth.d.ts.map +1 -0
  15. package/dist/cjs/cli/commands/auth.js +344 -0
  16. package/dist/cjs/cli/commands/auth.js.map +1 -0
  17. package/dist/cjs/cli/commands/build.d.ts +3 -0
  18. package/dist/cjs/cli/commands/build.d.ts.map +1 -0
  19. package/dist/cjs/cli/commands/{templates.js → build.js} +22 -22
  20. package/dist/cjs/cli/commands/build.js.map +1 -0
  21. package/dist/cjs/cli/commands/burner.js +2 -2
  22. package/dist/cjs/cli/commands/burner.js.map +1 -1
  23. package/dist/cjs/cli/commands/check.d.ts +3 -0
  24. package/dist/cjs/cli/commands/check.d.ts.map +1 -0
  25. package/dist/cjs/cli/commands/check.js +251 -0
  26. package/dist/cjs/cli/commands/check.js.map +1 -0
  27. package/dist/cjs/cli/commands/completion.d.ts +3 -0
  28. package/dist/cjs/cli/commands/completion.d.ts.map +1 -0
  29. package/dist/cjs/cli/commands/completion.js +46 -0
  30. package/dist/cjs/cli/commands/completion.js.map +1 -0
  31. package/dist/cjs/cli/commands/deploy.d.ts +3 -0
  32. package/dist/cjs/cli/commands/deploy.d.ts.map +1 -0
  33. package/dist/cjs/cli/commands/{createWithBurner.js → deploy.js} +15 -14
  34. package/dist/cjs/cli/commands/deploy.js.map +1 -0
  35. package/dist/cjs/cli/commands/docs.d.ts +3 -0
  36. package/dist/cjs/cli/commands/docs.d.ts.map +1 -0
  37. package/dist/cjs/cli/commands/docs.js +173 -0
  38. package/dist/cjs/cli/commands/docs.js.map +1 -0
  39. package/dist/cjs/cli/commands/doctor.d.ts +3 -0
  40. package/dist/cjs/cli/commands/doctor.d.ts.map +1 -0
  41. package/dist/cjs/cli/commands/doctor.js +355 -0
  42. package/dist/cjs/cli/commands/doctor.js.map +1 -0
  43. package/dist/cjs/cli/commands/explain.d.ts +3 -0
  44. package/dist/cjs/cli/commands/explain.d.ts.map +1 -0
  45. package/dist/cjs/cli/commands/explain.js +112 -0
  46. package/dist/cjs/cli/commands/explain.js.map +1 -0
  47. package/dist/cjs/cli/commands/gen-list-id.d.ts +3 -0
  48. package/dist/cjs/cli/commands/gen-list-id.d.ts.map +1 -0
  49. package/dist/cjs/cli/commands/gen-list-id.js +54 -0
  50. package/dist/cjs/cli/commands/gen-list-id.js.map +1 -0
  51. package/dist/cjs/cli/commands/lookup.d.ts +3 -0
  52. package/dist/cjs/cli/commands/lookup.d.ts.map +1 -0
  53. package/dist/cjs/cli/commands/lookup.js +111 -0
  54. package/dist/cjs/cli/commands/lookup.js.map +1 -0
  55. package/dist/cjs/cli/commands/preview.d.ts +3 -0
  56. package/dist/cjs/cli/commands/preview.d.ts.map +1 -0
  57. package/dist/cjs/cli/commands/preview.js +100 -0
  58. package/dist/cjs/cli/commands/preview.js.map +1 -0
  59. package/dist/cjs/cli/commands/resources.d.ts +3 -0
  60. package/dist/cjs/cli/commands/resources.d.ts.map +1 -0
  61. package/dist/cjs/cli/commands/resources.js +31 -0
  62. package/dist/cjs/cli/commands/resources.js.map +1 -0
  63. package/dist/cjs/cli/commands/session.d.ts +3 -0
  64. package/dist/cjs/cli/commands/session.d.ts.map +1 -0
  65. package/dist/cjs/cli/commands/session.js +34 -0
  66. package/dist/cjs/cli/commands/session.js.map +1 -0
  67. package/dist/cjs/cli/commands/simulate.d.ts +3 -0
  68. package/dist/cjs/cli/commands/simulate.d.ts.map +1 -0
  69. package/dist/cjs/cli/commands/simulate.js +108 -0
  70. package/dist/cjs/cli/commands/simulate.js.map +1 -0
  71. package/dist/cjs/cli/commands/skills.d.ts +3 -0
  72. package/dist/cjs/cli/commands/skills.d.ts.map +1 -0
  73. package/dist/cjs/cli/commands/skills.js +14 -0
  74. package/dist/cjs/cli/commands/skills.js.map +1 -0
  75. package/dist/cjs/cli/commands/tool.d.ts +3 -0
  76. package/dist/cjs/cli/commands/tool.d.ts.map +1 -0
  77. package/dist/cjs/cli/commands/tool.js +92 -0
  78. package/dist/cjs/cli/commands/tool.js.map +1 -0
  79. package/dist/cjs/cli/commands/tools.d.ts +3 -0
  80. package/dist/cjs/cli/commands/tools.d.ts.map +1 -0
  81. package/dist/cjs/cli/commands/tools.js +18 -0
  82. package/dist/cjs/cli/commands/tools.js.map +1 -0
  83. package/dist/cjs/cli/index.js +118 -49
  84. package/dist/cjs/cli/index.js.map +1 -1
  85. package/dist/cjs/cli/utils/api-client.d.ts +6 -0
  86. package/dist/cjs/cli/utils/api-client.d.ts.map +1 -1
  87. package/dist/cjs/cli/utils/api-client.js +14 -1
  88. package/dist/cjs/cli/utils/api-client.js.map +1 -1
  89. package/dist/cjs/cli/utils/auth-store.d.ts +59 -0
  90. package/dist/cjs/cli/utils/auth-store.d.ts.map +1 -0
  91. package/dist/cjs/cli/utils/auth-store.js +249 -0
  92. package/dist/cjs/cli/utils/auth-store.js.map +1 -0
  93. package/dist/cjs/tsconfig.build.tsbuildinfo +1 -1
  94. package/dist/esm/cli/commands/address.d.ts +3 -0
  95. package/dist/esm/cli/commands/address.d.ts.map +1 -0
  96. package/dist/esm/cli/commands/address.js +30 -0
  97. package/dist/esm/cli/commands/address.js.map +1 -0
  98. package/dist/esm/cli/commands/alias.d.ts +3 -0
  99. package/dist/esm/cli/commands/alias.d.ts.map +1 -0
  100. package/dist/esm/cli/commands/alias.js +26 -0
  101. package/dist/esm/cli/commands/alias.js.map +1 -0
  102. package/dist/esm/cli/commands/api.d.ts.map +1 -1
  103. package/dist/esm/cli/commands/api.js +23 -1
  104. package/dist/esm/cli/commands/api.js.map +1 -1
  105. package/dist/esm/cli/commands/auth.d.ts +3 -0
  106. package/dist/esm/cli/commands/auth.d.ts.map +1 -0
  107. package/dist/esm/cli/commands/auth.js +308 -0
  108. package/dist/esm/cli/commands/auth.js.map +1 -0
  109. package/dist/esm/cli/commands/build.d.ts +3 -0
  110. package/dist/esm/cli/commands/build.d.ts.map +1 -0
  111. package/dist/esm/cli/commands/{templates.js → build.js} +21 -21
  112. package/dist/esm/cli/commands/build.js.map +1 -0
  113. package/dist/esm/cli/commands/burner.js +2 -2
  114. package/dist/esm/cli/commands/burner.js.map +1 -1
  115. package/dist/esm/cli/commands/check.d.ts +3 -0
  116. package/dist/esm/cli/commands/check.d.ts.map +1 -0
  117. package/dist/esm/cli/commands/check.js +215 -0
  118. package/dist/esm/cli/commands/check.js.map +1 -0
  119. package/dist/esm/cli/commands/completion.d.ts +3 -0
  120. package/dist/esm/cli/commands/completion.d.ts.map +1 -0
  121. package/dist/esm/cli/commands/completion.js +43 -0
  122. package/dist/esm/cli/commands/completion.js.map +1 -0
  123. package/dist/esm/cli/commands/deploy.d.ts +3 -0
  124. package/dist/esm/cli/commands/deploy.d.ts.map +1 -0
  125. package/dist/esm/cli/commands/{createWithBurner.js → deploy.js} +14 -13
  126. package/dist/esm/cli/commands/deploy.js.map +1 -0
  127. package/dist/esm/cli/commands/docs.d.ts +3 -0
  128. package/dist/esm/cli/commands/docs.d.ts.map +1 -0
  129. package/dist/esm/cli/commands/docs.js +137 -0
  130. package/dist/esm/cli/commands/docs.js.map +1 -0
  131. package/dist/esm/cli/commands/doctor.d.ts +3 -0
  132. package/dist/esm/cli/commands/doctor.d.ts.map +1 -0
  133. package/dist/esm/cli/commands/doctor.js +319 -0
  134. package/dist/esm/cli/commands/doctor.js.map +1 -0
  135. package/dist/esm/cli/commands/explain.d.ts +3 -0
  136. package/dist/esm/cli/commands/explain.d.ts.map +1 -0
  137. package/dist/esm/cli/commands/explain.js +76 -0
  138. package/dist/esm/cli/commands/explain.js.map +1 -0
  139. package/dist/esm/cli/commands/gen-list-id.d.ts +3 -0
  140. package/dist/esm/cli/commands/gen-list-id.d.ts.map +1 -0
  141. package/dist/esm/cli/commands/gen-list-id.js +18 -0
  142. package/dist/esm/cli/commands/gen-list-id.js.map +1 -0
  143. package/dist/esm/cli/commands/lookup.d.ts +3 -0
  144. package/dist/esm/cli/commands/lookup.d.ts.map +1 -0
  145. package/dist/esm/cli/commands/lookup.js +75 -0
  146. package/dist/esm/cli/commands/lookup.js.map +1 -0
  147. package/dist/esm/cli/commands/preview.d.ts +3 -0
  148. package/dist/esm/cli/commands/preview.d.ts.map +1 -0
  149. package/dist/esm/cli/commands/preview.js +64 -0
  150. package/dist/esm/cli/commands/preview.js.map +1 -0
  151. package/dist/esm/cli/commands/resources.d.ts +3 -0
  152. package/dist/esm/cli/commands/resources.d.ts.map +1 -0
  153. package/dist/esm/cli/commands/resources.js +28 -0
  154. package/dist/esm/cli/commands/resources.js.map +1 -0
  155. package/dist/esm/cli/commands/session.d.ts +3 -0
  156. package/dist/esm/cli/commands/session.d.ts.map +1 -0
  157. package/dist/esm/cli/commands/session.js +31 -0
  158. package/dist/esm/cli/commands/session.js.map +1 -0
  159. package/dist/esm/cli/commands/simulate.d.ts +3 -0
  160. package/dist/esm/cli/commands/simulate.d.ts.map +1 -0
  161. package/dist/esm/cli/commands/simulate.js +72 -0
  162. package/dist/esm/cli/commands/simulate.js.map +1 -0
  163. package/dist/esm/cli/commands/skills.d.ts +3 -0
  164. package/dist/esm/cli/commands/skills.d.ts.map +1 -0
  165. package/dist/esm/cli/commands/skills.js +11 -0
  166. package/dist/esm/cli/commands/skills.js.map +1 -0
  167. package/dist/esm/cli/commands/tool.d.ts +3 -0
  168. package/dist/esm/cli/commands/tool.d.ts.map +1 -0
  169. package/dist/esm/cli/commands/tool.js +86 -0
  170. package/dist/esm/cli/commands/tool.js.map +1 -0
  171. package/dist/esm/cli/commands/tools.d.ts +3 -0
  172. package/dist/esm/cli/commands/tools.d.ts.map +1 -0
  173. package/dist/esm/cli/commands/tools.js +15 -0
  174. package/dist/esm/cli/commands/tools.js.map +1 -0
  175. package/dist/esm/cli/index.js +118 -49
  176. package/dist/esm/cli/index.js.map +1 -1
  177. package/dist/esm/cli/utils/api-client.d.ts +6 -0
  178. package/dist/esm/cli/utils/api-client.d.ts.map +1 -1
  179. package/dist/esm/cli/utils/api-client.js +14 -1
  180. package/dist/esm/cli/utils/api-client.js.map +1 -1
  181. package/dist/esm/cli/utils/auth-store.d.ts +59 -0
  182. package/dist/esm/cli/utils/auth-store.d.ts.map +1 -0
  183. package/dist/esm/cli/utils/auth-store.js +195 -0
  184. package/dist/esm/cli/utils/auth-store.js.map +1 -0
  185. package/dist/esm/tsconfig-esm.build.tsbuildinfo +1 -1
  186. package/package.json +1 -1
  187. package/dist/cjs/cli/commands/builder.d.ts +0 -3
  188. package/dist/cjs/cli/commands/builder.d.ts.map +0 -1
  189. package/dist/cjs/cli/commands/builder.js +0 -975
  190. package/dist/cjs/cli/commands/builder.js.map +0 -1
  191. package/dist/cjs/cli/commands/createWithBurner.d.ts +0 -3
  192. package/dist/cjs/cli/commands/createWithBurner.d.ts.map +0 -1
  193. package/dist/cjs/cli/commands/createWithBurner.js.map +0 -1
  194. package/dist/cjs/cli/commands/sdk.d.ts +0 -3
  195. package/dist/cjs/cli/commands/sdk.d.ts.map +0 -1
  196. package/dist/cjs/cli/commands/sdk.js +0 -514
  197. package/dist/cjs/cli/commands/sdk.js.map +0 -1
  198. package/dist/cjs/cli/commands/templates.d.ts +0 -3
  199. package/dist/cjs/cli/commands/templates.d.ts.map +0 -1
  200. package/dist/cjs/cli/commands/templates.js.map +0 -1
  201. package/dist/esm/cli/commands/builder.d.ts +0 -3
  202. package/dist/esm/cli/commands/builder.d.ts.map +0 -1
  203. package/dist/esm/cli/commands/builder.js +0 -936
  204. package/dist/esm/cli/commands/builder.js.map +0 -1
  205. package/dist/esm/cli/commands/createWithBurner.d.ts +0 -3
  206. package/dist/esm/cli/commands/createWithBurner.d.ts.map +0 -1
  207. package/dist/esm/cli/commands/createWithBurner.js.map +0 -1
  208. package/dist/esm/cli/commands/sdk.d.ts +0 -3
  209. package/dist/esm/cli/commands/sdk.d.ts.map +0 -1
  210. package/dist/esm/cli/commands/sdk.js +0 -478
  211. package/dist/esm/cli/commands/sdk.js.map +0 -1
  212. package/dist/esm/cli/commands/templates.d.ts +0 -3
  213. package/dist/esm/cli/commands/templates.d.ts.map +0 -1
  214. package/dist/esm/cli/commands/templates.js.map +0 -1
@@ -1,936 +0,0 @@
1
- import { Command } from 'commander';
2
- import fs from 'fs';
3
- import { toolRegistry, listTools, callTool, resourceRegistry, listResources, readResource } from '../../builder/tools/registry.js';
4
- import { loadSessionFromDisk, saveSessionToDisk, listSessionFilesOnDisk, readSessionFileRaw, resetSessionFile, sessionFilePath } from '../../builder/session/fileStore.js';
5
- import { templatesCommand } from './templates.js';
6
- import { createWithBurnerCommand } from './createWithBurner.js';
7
- import { burnerCommand } from './burner.js';
8
- import { addNetworkOptions } from '../utils/io.js';
9
- function ensureTxWrapper(input) {
10
- if (!input || typeof input !== 'object')
11
- return input;
12
- if (Array.isArray(input.messages))
13
- return input;
14
- if (typeof input.typeUrl === 'string' && input.value)
15
- return { messages: [input] };
16
- return input;
17
- }
18
- function parseArgs(argsJson, argsFile) {
19
- if (argsJson && argsFile) {
20
- throw new Error('Pass either --args or --args-file, not both');
21
- }
22
- if (argsFile) {
23
- const raw = fs.readFileSync(argsFile, 'utf-8');
24
- return JSON.parse(raw);
25
- }
26
- if (argsJson) {
27
- try {
28
- return JSON.parse(argsJson);
29
- }
30
- catch (err) {
31
- throw new Error(`--args is not valid JSON: ${err.message}`);
32
- }
33
- }
34
- return {};
35
- }
36
- function resolveSessionId(parsedArgs, sessionFlag) {
37
- if (sessionFlag)
38
- return sessionFlag;
39
- if (parsedArgs && typeof parsedArgs.sessionId === 'string')
40
- return parsedArgs.sessionId;
41
- return undefined;
42
- }
43
- export const builderCommand = new Command('builder')
44
- .description('BitBadges Builder — deterministic templates, fine-grained tools, docs resources, and session state for composing token transactions.')
45
- .showHelpAfterError('(see `bitbadges-cli builder --help` for the full subcommand list)');
46
- builderCommand.addCommand(templatesCommand);
47
- builderCommand.addCommand(createWithBurnerCommand);
48
- builderCommand.addCommand(burnerCommand);
49
- const toolsCommand = builderCommand
50
- .command('tools')
51
- .description('Fine-grained builder tool registry (session builders, queries, reviews, utilities).');
52
- toolsCommand
53
- .command('list')
54
- .description('List every builder tool with its schema as JSON.')
55
- .option('--names', 'Print only tool names, one per line')
56
- .action((opts) => {
57
- if (opts.names) {
58
- for (const name of Object.keys(toolRegistry)) {
59
- process.stdout.write(`${name}\n`);
60
- }
61
- return;
62
- }
63
- process.stdout.write(JSON.stringify(listTools(), null, 2) + '\n');
64
- });
65
- toolsCommand
66
- .command('call <tool>')
67
- .description('Call a builder tool by name. Args come from --args (JSON) or --args-file.')
68
- .option('--args <json>', 'Tool arguments as a JSON string')
69
- .option('--args-file <path>', 'Tool arguments read from a JSON file')
70
- .option('--session <id>', 'Session id for stateful tools. Stored under ~/.bitbadges/sessions/<id>.json. Defaults to the id inside --args.sessionId, or the builtin default session.')
71
- .option('--raw', 'Print the structured result instead of the formatted text block')
72
- .action(async (toolName, opts) => {
73
- if (!toolRegistry[toolName]) {
74
- const available = Object.keys(toolRegistry).sort().join(', ');
75
- process.stderr.write(`Unknown tool: ${toolName}\nAvailable tools: ${available}\n`);
76
- process.exitCode = 1;
77
- return;
78
- }
79
- let parsedArgs;
80
- try {
81
- parsedArgs = parseArgs(opts.args, opts.argsFile);
82
- }
83
- catch (err) {
84
- process.stderr.write(`${err.message}\n`);
85
- process.exitCode = 1;
86
- return;
87
- }
88
- const sessionId = resolveSessionId(parsedArgs, opts.session);
89
- if (sessionId) {
90
- try {
91
- loadSessionFromDisk(sessionId);
92
- }
93
- catch (err) {
94
- process.stderr.write(`${err.message}\n`);
95
- process.exitCode = 1;
96
- return;
97
- }
98
- if (parsedArgs && typeof parsedArgs === 'object' && parsedArgs.sessionId === undefined) {
99
- parsedArgs.sessionId = sessionId;
100
- }
101
- }
102
- const result = await callTool(toolName, parsedArgs);
103
- if (sessionId) {
104
- try {
105
- saveSessionToDisk(sessionId);
106
- }
107
- catch (err) {
108
- process.stderr.write(`Warning: failed to save session "${sessionId}": ${err.message}\n`);
109
- }
110
- }
111
- if (opts.raw) {
112
- process.stdout.write(JSON.stringify(result.result, null, 2) + '\n');
113
- }
114
- else {
115
- process.stdout.write(result.text + '\n');
116
- }
117
- if (result.isError) {
118
- process.exitCode = 1;
119
- }
120
- });
121
- addNetworkOptions(builderCommand
122
- .command('review <input>')
123
- .description('Review a built transaction or collection for issues. Input: JSON file, inline JSON, numeric collection ID, or - for stdin.')
124
- .option('--json', 'Output the full ReviewResult as JSON')
125
- .option('--strict', 'Exit 1 on warnings (critical always exits 2)')
126
- .option('--output-file <path>', 'Write output to file instead of stdout'))
127
- .action(async (input, opts) => {
128
- const { readJsonInput, output, getApiUrl, getApiKeyForNetwork } = await import('../utils/io.js');
129
- let data;
130
- if (/^\d+$/.test(input)) {
131
- const baseUrl = getApiUrl(opts);
132
- const apiKey = getApiKeyForNetwork(opts) || '';
133
- try {
134
- const response = await fetch(`${baseUrl}/api/v0/collection/${input}`, {
135
- headers: { 'x-api-key': apiKey }
136
- });
137
- if (!response.ok) {
138
- process.stderr.write(`Could not fetch collection ${input} from ${baseUrl} — HTTP ${response.status}.\n` +
139
- `Hint: --network local may not have a wired collection-by-id endpoint.\n` +
140
- `Try passing the collection JSON directly instead of a numeric id.\n`);
141
- process.exit(2);
142
- }
143
- data = await response.json();
144
- }
145
- catch (err) {
146
- process.stderr.write(`Could not reach ${baseUrl}/api/v0/collection/${input}: ${err?.message || err}\n`);
147
- process.exit(2);
148
- }
149
- }
150
- else {
151
- try {
152
- data = readJsonInput(input);
153
- }
154
- catch (err) {
155
- process.stderr.write(`Failed to parse input JSON: ${err?.message || err}\n` +
156
- `Accepts: file path, @file.json, inline JSON, numeric collection id, or - for stdin.\n`);
157
- process.exit(2);
158
- }
159
- }
160
- const { reviewCollection } = await import('../../core/review.js');
161
- let result;
162
- try {
163
- result = reviewCollection(ensureTxWrapper(data));
164
- }
165
- catch (err) {
166
- process.stderr.write(`Could not review input: ${err?.message || err}\n` +
167
- `\`builder review\` expects a transaction (with messages[]), a single Msg ({typeUrl,value}), ` +
168
- `or a complete on-chain collection document.\n`);
169
- process.exit(2);
170
- }
171
- if (opts.json) {
172
- output(result, { ...opts, human: false });
173
- }
174
- else {
175
- const { renderReview } = await import('../utils/terminal.js');
176
- const text = renderReview(result, { stream: process.stdout });
177
- if (opts.outputFile) {
178
- const fsMod = await import('fs');
179
- const plain = text.replace(/\x1b\[[0-9;]*m/g, '');
180
- fsMod.writeFileSync(opts.outputFile, plain + '\n', 'utf-8');
181
- process.stderr.write(`Written to ${opts.outputFile}\n`);
182
- }
183
- else {
184
- console.log(text);
185
- }
186
- }
187
- if (result.summary.critical > 0)
188
- process.exit(2);
189
- if (opts.strict && result.summary.warning > 0)
190
- process.exit(1);
191
- });
192
- addNetworkOptions(builderCommand
193
- .command('verify <input>')
194
- .description('Aggregate validate + review + metadata coverage check. Input: JSON file, inline JSON, or - for stdin.')
195
- .option('--json', 'Output a structured aggregate JSON instead of rendered sections')
196
- .option('--strict', 'Exit 1 on warnings (criticals always exit 2)')
197
- .option('--no-validate', 'Skip the structural validation section')
198
- .option('--no-review', 'Skip the design review section')
199
- .option('--no-metadata', 'Skip the metadata coverage section')
200
- .option('--design', 'Include the design decisions (informational ✓/✗) section. Hidden by default while the surface is being iterated on; the underlying decisions still appear in --json output.')
201
- .option('--output-file <path>', 'Write the rendered sections to a file instead of stdout'))
202
- .action(async (input, opts) => {
203
- const { readJsonInput, output } = await import('../utils/io.js');
204
- const { renderValidate, renderReview, renderDesignDecisions, renderMetadataPlaceholders, collectMetadataPlaceholders } = await import('../utils/terminal.js');
205
- let raw;
206
- try {
207
- raw = readJsonInput(input);
208
- }
209
- catch (err) {
210
- process.stderr.write(`Failed to parse input JSON: ${err?.message || err}\n` +
211
- `Accepts: file path, @file.json, inline JSON, or - for stdin.\n`);
212
- process.exit(2);
213
- }
214
- const wrapped = ensureTxWrapper(raw);
215
- const { isCollectionMsg } = await import('../utils/normalizeMsg.js');
216
- const firstMsg = Array.isArray(wrapped?.messages) && wrapped.messages.length > 0
217
- ? wrapped.messages.find((m) => isCollectionMsg(m)) ?? wrapped.messages[0]
218
- : wrapped;
219
- const firstIsCollection = isCollectionMsg(firstMsg);
220
- let validation = null;
221
- if (opts.validate !== false) {
222
- const { validateTransaction } = await import('../../core/validate.js');
223
- validation = validateTransaction(wrapped);
224
- }
225
- let review = null;
226
- if (opts.review !== false && firstIsCollection) {
227
- const { reviewCollection } = await import('../../core/review.js');
228
- review = reviewCollection(wrapped);
229
- }
230
- let design = null;
231
- if (firstIsCollection) {
232
- const { runDesignChecks } = await import('../../core/design-decisions/index.js');
233
- design = runDesignChecks(wrapped);
234
- }
235
- let placeholders = [];
236
- if (opts.metadata !== false && firstIsCollection) {
237
- placeholders = collectMetadataPlaceholders(firstMsg);
238
- }
239
- if (opts.json) {
240
- output({
241
- validate: validation,
242
- review,
243
- design,
244
- metadata: {
245
- placeholders,
246
- filled: firstMsg?.value?._meta?.metadataPlaceholders || {}
247
- }
248
- }, { ...opts, human: false });
249
- }
250
- else {
251
- const lines = [];
252
- if (validation) {
253
- lines.push(renderValidate(validation, { stream: process.stdout }));
254
- lines.push('');
255
- }
256
- if (review) {
257
- lines.push(renderReview(review, { stream: process.stdout }));
258
- lines.push('');
259
- }
260
- if (design && opts.design === true) {
261
- lines.push(renderDesignDecisions(design, { stream: process.stdout }));
262
- lines.push('');
263
- }
264
- if (placeholders.length > 0) {
265
- lines.push(renderMetadataPlaceholders(placeholders, firstMsg?.value?._meta?.metadataPlaceholders, {
266
- stream: process.stdout
267
- }));
268
- }
269
- const text = lines.join('\n');
270
- if (opts.outputFile) {
271
- const fsMod = await import('fs');
272
- const plain = text.replace(/\x1b\[[0-9;]*m/g, '');
273
- fsMod.writeFileSync(opts.outputFile, plain + '\n', 'utf-8');
274
- process.stderr.write(`Written to ${opts.outputFile}\n`);
275
- }
276
- else {
277
- console.log(text);
278
- }
279
- }
280
- const hasValidationErrors = validation && validation.issues?.some((i) => i.severity === 'error');
281
- const hasCritical = review && review.summary?.critical > 0;
282
- if (hasValidationErrors || hasCritical) {
283
- process.exit(2);
284
- }
285
- const hasValidationWarnings = validation && validation.issues?.some((i) => i.severity === 'warning');
286
- const hasReviewWarnings = review && review.summary?.warning > 0;
287
- if (opts.strict && (hasValidationWarnings || hasReviewWarnings)) {
288
- process.exit(1);
289
- }
290
- });
291
- addNetworkOptions(builderCommand
292
- .command('doctor')
293
- .description('Environment + session health check. Verifies Node/SDK/config/API key/MCP bin/session integrity. Pass --with-preview to also probe the indexer\'s shareable-preview upload + fetch roundtrip.')
294
- .option('--json', 'Output the full DoctorReport as JSON')
295
- .option('--with-preview', 'Add a preview-roundtrip probe: builds a minimal tx, POSTs it to /api/v0/builder/preview, GETs it back by code, and asserts the round trip is byte-equivalent. Catches indexer / Redis / preview-route regressions.')).action(async (opts) => {
296
- const checks = [];
297
- const nodeVersion = process.versions.node;
298
- const nodeMajor = parseInt(nodeVersion.split('.')[0], 10);
299
- if (nodeMajor >= 18) {
300
- checks.push({ name: 'Node version', status: 'pass', detail: `v${nodeVersion}` });
301
- }
302
- else {
303
- checks.push({
304
- name: 'Node version',
305
- status: 'fail',
306
- detail: `v${nodeVersion} — bitbadges requires Node 18+`
307
- });
308
- }
309
- const sdkPackageNames = ['bitbadges', 'bitbadgesjs-sdk'];
310
- try {
311
- const pathMod = await import('path');
312
- const fsMod = await import('fs');
313
- const startFrom = pathMod.dirname(process.argv[1] || process.cwd());
314
- let dir = startFrom;
315
- let pkgPath = null;
316
- for (let i = 0; i < 8; i++) {
317
- const candidate = pathMod.join(dir, 'package.json');
318
- if (fsMod.existsSync(candidate)) {
319
- try {
320
- const pkg = JSON.parse(fsMod.readFileSync(candidate, 'utf-8'));
321
- if (sdkPackageNames.includes(pkg.name)) {
322
- pkgPath = candidate;
323
- break;
324
- }
325
- }
326
- catch {
327
- }
328
- }
329
- const parent = pathMod.dirname(dir);
330
- if (parent === dir)
331
- break;
332
- dir = parent;
333
- }
334
- if (pkgPath) {
335
- const pkg = JSON.parse(fsMod.readFileSync(pkgPath, 'utf-8'));
336
- checks.push({ name: 'SDK package', status: 'pass', detail: `${pkg.name}@${pkg.version}` });
337
- }
338
- else {
339
- checks.push({
340
- name: 'SDK package',
341
- status: 'warn',
342
- detail: 'Could not locate bitbadges package.json from CLI entry'
343
- });
344
- }
345
- }
346
- catch (err) {
347
- checks.push({ name: 'SDK package', status: 'warn', detail: err.message });
348
- }
349
- try {
350
- const fsMod = await import('fs');
351
- const pathMod = await import('path');
352
- const osMod = await import('os');
353
- const configPath = pathMod.join(osMod.homedir(), '.bitbadges', 'config.json');
354
- if (fsMod.existsSync(configPath)) {
355
- try {
356
- JSON.parse(fsMod.readFileSync(configPath, 'utf-8'));
357
- checks.push({ name: 'Config file', status: 'pass', detail: configPath });
358
- }
359
- catch {
360
- checks.push({ name: 'Config file', status: 'fail', detail: `${configPath} exists but is not valid JSON` });
361
- }
362
- }
363
- else {
364
- checks.push({ name: 'Config file', status: 'skip', detail: 'no ~/.bitbadges/config.json (env vars also OK)' });
365
- }
366
- }
367
- catch (err) {
368
- checks.push({ name: 'Config file', status: 'fail', detail: err.message });
369
- }
370
- try {
371
- const { getApiUrl, getApiKeyForNetwork, resolveNetwork } = await import('../utils/io.js');
372
- const key = getApiKeyForNetwork(opts);
373
- const network = resolveNetwork(opts);
374
- if (!key) {
375
- checks.push({
376
- name: `API key (${network})`,
377
- status: 'skip',
378
- detail: `no key set (BITBADGES_API_KEY or config.apiKey${network !== 'mainnet' ? `/apiKey${network[0].toUpperCase() + network.slice(1)}` : ''})`
379
- });
380
- }
381
- else {
382
- const url = `${getApiUrl(opts)}/api/v0/simulate`;
383
- try {
384
- const response = await fetch(url, {
385
- method: 'POST',
386
- headers: { 'Content-Type': 'application/json', 'x-api-key': key },
387
- body: JSON.stringify({ txs: [] })
388
- });
389
- if (response.status >= 200 && response.status < 500) {
390
- checks.push({
391
- name: `API key (${network})`,
392
- status: 'pass',
393
- detail: `${url} responded with HTTP ${response.status}`
394
- });
395
- }
396
- else {
397
- checks.push({ name: `API key (${network})`, status: 'warn', detail: `HTTP ${response.status} from ${url}` });
398
- }
399
- }
400
- catch (err) {
401
- checks.push({
402
- name: `API key (${network})`,
403
- status: 'warn',
404
- detail: `network error pinging ${url}: ${err.message}`
405
- });
406
- }
407
- }
408
- }
409
- catch (err) {
410
- checks.push({ name: 'API key', status: 'fail', detail: err.message });
411
- }
412
- try {
413
- const fsMod = await import('fs');
414
- const pathMod = await import('path');
415
- const startFrom = pathMod.dirname(process.argv[1] || process.cwd());
416
- let dir = startFrom;
417
- let pkgRoot = null;
418
- for (let i = 0; i < 8; i++) {
419
- const candidate = pathMod.join(dir, 'package.json');
420
- if (fsMod.existsSync(candidate)) {
421
- try {
422
- const pkg = JSON.parse(fsMod.readFileSync(candidate, 'utf-8'));
423
- if (sdkPackageNames.includes(pkg.name)) {
424
- pkgRoot = dir;
425
- break;
426
- }
427
- }
428
- catch {
429
- }
430
- }
431
- const parent = pathMod.dirname(dir);
432
- if (parent === dir)
433
- break;
434
- dir = parent;
435
- }
436
- if (!pkgRoot) {
437
- checks.push({
438
- name: 'MCP stdio bin',
439
- status: 'warn',
440
- detail: 'Could not locate SDK root from CLI entry'
441
- });
442
- }
443
- else {
444
- const binCandidates = [
445
- pathMod.join(pkgRoot, 'dist', 'cjs', 'builder', 'index.js'),
446
- pathMod.join(pkgRoot, 'dist', 'esm', 'builder', 'index.js')
447
- ];
448
- const found = binCandidates.find((p) => fsMod.existsSync(p));
449
- if (found) {
450
- checks.push({ name: 'MCP stdio bin', status: 'pass', detail: found });
451
- }
452
- else {
453
- checks.push({
454
- name: 'MCP stdio bin',
455
- status: 'warn',
456
- detail: 'dist/cjs/builder/index.js not found — run `npm run build` in the bitbadges package'
457
- });
458
- }
459
- }
460
- }
461
- catch (err) {
462
- checks.push({ name: 'MCP stdio bin', status: 'fail', detail: err.message });
463
- }
464
- try {
465
- const { listSessionFilesOnDisk, readSessionFileRaw } = await import('../../builder/session/fileStore.js');
466
- const ids = listSessionFilesOnDisk();
467
- let parseable = 0;
468
- let corrupt = 0;
469
- for (const id of ids) {
470
- const raw = readSessionFileRaw(id);
471
- if (!raw)
472
- continue;
473
- try {
474
- JSON.parse(raw);
475
- parseable++;
476
- }
477
- catch {
478
- corrupt++;
479
- }
480
- }
481
- if (corrupt > 0) {
482
- checks.push({
483
- name: 'Sessions',
484
- status: 'warn',
485
- detail: `${parseable} parseable, ${corrupt} corrupt — run \`bitbadges-cli builder session reset <id>\` on broken ones`
486
- });
487
- }
488
- else {
489
- checks.push({ name: 'Sessions', status: 'pass', detail: `${parseable} session(s) on disk` });
490
- }
491
- }
492
- catch (err) {
493
- checks.push({ name: 'Sessions', status: 'fail', detail: err.message });
494
- }
495
- if (opts.withPreview) {
496
- try {
497
- const { getApiUrl: gAU, resolveNetwork: rN } = await import('../utils/io.js');
498
- const network = rN(opts);
499
- const baseUrl = gAU(opts);
500
- const probeTx = {
501
- transaction: {
502
- messages: [
503
- {
504
- typeUrl: '/tokenization.MsgCreateCollection',
505
- value: {
506
- creator: 'bb1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqpdguex7',
507
- validTokenIds: [],
508
- standards: [],
509
- collectionApprovals: [],
510
- tokenMetadata: [],
511
- aliasPathsToAdd: [],
512
- cosmosCoinWrapperPathsToAdd: [],
513
- mintEscrowCoinsToTransfer: [],
514
- _meta: {
515
- metadataPlaceholders: {
516
- 'ipfs://METADATA_DOCTOR_PROBE': { name: 'doctor probe', description: '', image: '' }
517
- }
518
- }
519
- }
520
- }
521
- ]
522
- }
523
- };
524
- const postRes = await fetch(`${baseUrl}/api/v0/builder/preview`, {
525
- method: 'POST',
526
- headers: { 'Content-Type': 'application/json' },
527
- body: JSON.stringify(probeTx)
528
- });
529
- if (!postRes.ok) {
530
- checks.push({
531
- name: `Preview roundtrip (${network})`,
532
- status: 'fail',
533
- detail: `POST /api/v0/builder/preview returned HTTP ${postRes.status}`
534
- });
535
- }
536
- else {
537
- const { code } = (await postRes.json());
538
- const getRes = await fetch(`${baseUrl}/api/v0/builder/preview?code=${encodeURIComponent(code)}`);
539
- if (!getRes.ok) {
540
- checks.push({
541
- name: `Preview roundtrip (${network})`,
542
- status: 'fail',
543
- detail: `GET /api/v0/builder/preview returned HTTP ${getRes.status} for the code we just uploaded (${code})`
544
- });
545
- }
546
- else {
547
- const fetched = (await getRes.json());
548
- const echoedTypeUrl = fetched?.transaction?.messages?.[0]?.typeUrl;
549
- const sidecarKey = fetched?.transaction?.messages?.[0]?.value?._meta?.metadataPlaceholders?.['ipfs://METADATA_DOCTOR_PROBE']?.name;
550
- if (echoedTypeUrl !== '/tokenization.MsgCreateCollection' || sidecarKey !== 'doctor probe') {
551
- checks.push({
552
- name: `Preview roundtrip (${network})`,
553
- status: 'fail',
554
- detail: `Round trip mutated the payload — got typeUrl=${echoedTypeUrl}, sidecarName=${sidecarKey}`
555
- });
556
- }
557
- else {
558
- checks.push({
559
- name: `Preview roundtrip (${network})`,
560
- status: 'pass',
561
- detail: `${baseUrl}/api/v0/builder/preview · uploaded ${code} · fetched and verified`
562
- });
563
- }
564
- }
565
- }
566
- }
567
- catch (err) {
568
- checks.push({
569
- name: 'Preview roundtrip',
570
- status: 'fail',
571
- detail: `network error: ${err?.message || err}`
572
- });
573
- }
574
- }
575
- if (opts.json) {
576
- const { output: outputFn } = await import('../utils/io.js');
577
- outputFn(checks, { ...opts, human: false });
578
- }
579
- else {
580
- const { makeColor, rule } = await import('../utils/terminal.js');
581
- const { c } = makeColor(process.stdout);
582
- const width = Math.min(80, process.stdout.columns || 80);
583
- const lines = [];
584
- lines.push(c('gray', rule('━', width, 'Doctor')));
585
- lines.push('');
586
- const sigil = { pass: '✓', fail: '■', warn: '▲', skip: '·' };
587
- const colorFor = { pass: 'green', fail: 'red', warn: 'yellow', skip: 'gray' };
588
- const labelFor = { pass: 'PASS', fail: 'FAIL', warn: 'WARN', skip: 'SKIP' };
589
- for (const ch of checks) {
590
- const badge = `${sigil[ch.status]} ${labelFor[ch.status]}`;
591
- lines.push(` ${c(colorFor[ch.status], c('bold', badge))} ${c('bold', ch.name)}`);
592
- if (ch.detail) {
593
- lines.push(` ${c('dim', ch.detail)}`);
594
- }
595
- }
596
- lines.push('');
597
- const counts = checks.reduce((acc, ch) => ({ ...acc, [ch.status]: (acc[ch.status] || 0) + 1 }), {});
598
- lines.push(c('gray', rule('━', width)));
599
- lines.push(` ${c('bold', 'Summary')} ${counts.pass || 0} pass · ${counts.fail
600
- ? c('red', `${counts.fail} fail`)
601
- : c('gray', '0 fail')} · ${counts.warn ? c('yellow', `${counts.warn} warn`) : c('gray', '0 warn')} · ${counts.skip || 0} skip`);
602
- lines.push(c('gray', rule('━', width)));
603
- console.log(lines.join('\n'));
604
- }
605
- if (checks.some((ch) => ch.status === 'fail'))
606
- process.exit(2);
607
- });
608
- addNetworkOptions(builderCommand
609
- .command('preview <input>')
610
- .description('Upload a tx to the indexer and print a shareable bitbadges.io preview URL. Input: JSON file, inline JSON, or - for stdin.')
611
- .option('--frontend-url <url>', 'Override the bitbadges.io frontend base for the printed preview URL', 'https://bitbadges.io')
612
- .option('--json', 'Output the structured upload result as JSON instead of just the URL')).action(async (input, opts) => {
613
- const { readJsonInput, getApiUrl } = await import('../utils/io.js');
614
- const raw = readJsonInput(input);
615
- const wrapped = ensureTxWrapper(raw);
616
- const { normalizeToCreateOrUpdate: _normalize } = await import('../utils/normalizeMsg.js');
617
- const cleanedMessages = (wrapped.messages || []).map((m) => _normalize(m));
618
- const payload = {
619
- transaction: {
620
- messages: cleanedMessages,
621
- ...(wrapped.memo ? { memo: wrapped.memo } : {}),
622
- ...(wrapped.fee ? { fee: wrapped.fee } : {})
623
- }
624
- };
625
- const apiUrl = getApiUrl(opts);
626
- const url = `${apiUrl}/api/v0/builder/preview`;
627
- let response;
628
- try {
629
- response = await fetch(url, {
630
- method: 'POST',
631
- headers: { 'Content-Type': 'application/json' },
632
- body: JSON.stringify(payload)
633
- });
634
- }
635
- catch (err) {
636
- process.stderr.write(`Preview upload failed: ${err instanceof Error ? err.message : String(err)}\n`);
637
- process.exit(2);
638
- }
639
- if (!response.ok) {
640
- const text = await response.text().catch(() => '');
641
- process.stderr.write(`Preview upload failed: HTTP ${response.status} ${text}\n`);
642
- process.exit(2);
643
- }
644
- const result = (await response.json());
645
- const frontendBase = opts.frontendUrl || 'https://bitbadges.io';
646
- const previewUrl = `${frontendBase.replace(/\/$/, '')}/builder/preview?code=${encodeURIComponent(result.code)}`;
647
- if (opts.json) {
648
- process.stdout.write(JSON.stringify({
649
- code: result.code,
650
- url: previewUrl,
651
- expiresAt: result.expiresAt,
652
- expiresIn: result.expiresIn
653
- }, null, 2) + '\n');
654
- }
655
- else {
656
- process.stdout.write(previewUrl + '\n');
657
- process.stderr.write(`Expires in ${result.expiresIn}.\n`);
658
- }
659
- });
660
- addNetworkOptions(builderCommand
661
- .command('simulate <input>')
662
- .description('Dry-run a built tx against the BitBadges API simulate endpoint. Returns gas + per-address net balance changes. Input: JSON file, inline JSON, or - for stdin.')
663
- .option('--json', 'Output the structured SimulateResult as JSON instead of a rendered section')
664
- .option('--creator <address>', 'Override the simulation context address (default: bb1simulation)')
665
- .option('--events', 'Dump the full raw chain events array in the rendered output (default: just the count)')).action(async (input, opts) => {
666
- const { readJsonInput, output, getApiUrl, getApiKeyForNetwork } = await import('../utils/io.js');
667
- const { simulateMessages } = await import('../../builder/tools/queries/simulateTransaction.js');
668
- const { renderSimulate } = await import('../utils/terminal.js');
669
- const { prefetchSimulateCollections } = await import('../utils/simulateSymbols.js');
670
- const apiKey = getApiKeyForNetwork(opts);
671
- if (!apiKey) {
672
- process.stderr.write(renderSimulate({
673
- success: false,
674
- error: 'No API key. Set BITBADGES_API_KEY, run `bitbadges-cli config set apiKey <key>`, or pass --network local against a key-less local indexer.'
675
- }, { stream: process.stderr }) + '\n');
676
- process.exit(2);
677
- }
678
- const raw = readJsonInput(input);
679
- const wrapped = ensureTxWrapper(raw);
680
- const messages = Array.isArray(wrapped?.messages) ? wrapped.messages : [];
681
- if (messages.length === 0) {
682
- process.stderr.write(renderSimulate({ success: false, error: 'No messages found in input. Expected `{messages: [...]}` or a single Msg.' }, { stream: process.stderr }) + '\n');
683
- process.exit(2);
684
- }
685
- const APPROVAL_RE = /\.(MsgUpdateUserApprovals|MsgSetIncomingApproval|MsgSetOutgoingApproval|MsgDeleteIncomingApproval|MsgDeleteOutgoingApproval|MsgPurgeApprovals)$/;
686
- const firstApprovalMsg = messages.find((m) => typeof m?.typeUrl === 'string' && APPROVAL_RE.test(m.typeUrl));
687
- if (firstApprovalMsg) {
688
- process.stderr.write(renderSimulate({
689
- success: false,
690
- error: `Cannot simulate user-level approval message (${firstApprovalMsg.typeUrl}). ` +
691
- 'Use `builder validate` and `builder review` to check it, or include it inside an ' +
692
- 'alternative approval message that wraps a full collection transaction.'
693
- }, { stream: process.stderr }) + '\n');
694
- process.exit(2);
695
- }
696
- const result = await simulateMessages({
697
- messages,
698
- memo: wrapped.memo,
699
- fee: wrapped.fee,
700
- creatorAddress: opts.creator,
701
- apiKey,
702
- apiUrl: getApiUrl(opts)
703
- });
704
- if (opts.json) {
705
- output(result, { ...opts, human: false });
706
- }
707
- else {
708
- const collectionCache = await prefetchSimulateCollections(result, {
709
- apiKey,
710
- apiUrl: getApiUrl(opts)
711
- });
712
- console.log(renderSimulate(result, {
713
- stream: process.stdout,
714
- events: opts.events ? 'full' : 'count',
715
- collectionCache
716
- }));
717
- }
718
- if (!result.success || result.valid === false)
719
- process.exit(2);
720
- });
721
- addNetworkOptions(builderCommand
722
- .command('explain <input>')
723
- .description('Explain a transaction or collection in plain English. Input: JSON file, inline JSON, numeric collection ID, or - for stdin.')
724
- .option('--output-file <path>', 'Write output to file instead of stdout')).action(async (input, opts) => {
725
- const { readJsonInput, getApiUrl, getApiKeyForNetwork } = await import('../utils/io.js');
726
- let data;
727
- let fetchedCollection = false;
728
- if (/^\d+$/.test(input)) {
729
- const baseUrl = getApiUrl(opts);
730
- const apiKey = getApiKeyForNetwork(opts) || '';
731
- try {
732
- const response = await fetch(`${baseUrl}/api/v0/collection/${input}`, {
733
- headers: { 'x-api-key': apiKey }
734
- });
735
- if (!response.ok) {
736
- process.stderr.write(`Could not fetch collection ${input} from ${baseUrl} — HTTP ${response.status}.\n` +
737
- `Hint: the indexer's collection-by-id endpoint may not be wired on --network local.\n` +
738
- `Try passing the collection JSON directly (file or inline) instead of a numeric id.\n`);
739
- process.exit(2);
740
- }
741
- data = await response.json();
742
- fetchedCollection = true;
743
- }
744
- catch (err) {
745
- process.stderr.write(`Could not reach ${baseUrl}/api/v0/collection/${input}: ${err?.message || err}.\n` +
746
- `Check that the network is reachable, or pass the collection JSON directly.\n`);
747
- process.exit(2);
748
- }
749
- }
750
- else {
751
- try {
752
- data = readJsonInput(input);
753
- }
754
- catch (err) {
755
- process.stderr.write(`Failed to parse input JSON: ${err?.message || err}.\n` +
756
- `Accepts: file path, @file.json, inline JSON, numeric collection id, or - for stdin.\n`);
757
- process.exit(2);
758
- }
759
- }
760
- let text;
761
- const { isCollectionMsg } = await import('../utils/normalizeMsg.js');
762
- const hasMessages = Array.isArray(data?.messages);
763
- const firstCollectionMsg = hasMessages ? data.messages.find((m) => isCollectionMsg(m)) : null;
764
- try {
765
- if (fetchedCollection ||
766
- (data && typeof data === 'object' && !data.typeUrl && !hasMessages && !data.value)) {
767
- const { interpretCollection } = await import('../../api-indexer/interpret.js');
768
- text = interpretCollection(data);
769
- }
770
- else {
771
- const txBody = firstCollectionMsg?.value ?? data.value ?? data;
772
- const { interpretTransaction } = await import('../../core/interpret-transaction.js');
773
- text = interpretTransaction(txBody);
774
- }
775
- }
776
- catch (err) {
777
- process.stderr.write(`Could not interpret input: ${err?.message || err}.\n` +
778
- `Hint: \`builder explain\` expects either a full transaction (with messages[]),\n` +
779
- `a single Msg ({typeUrl, value}), a complete on-chain collection document\n` +
780
- `(returned by query_collection), or a numeric collection id. Minimal ad-hoc\n` +
781
- `JSON like {collectionId:"1"} is not a valid input — it lacks the fields the\n` +
782
- `interpreter needs (collectionMetadata.uri, validTokenIds, etc).\n`);
783
- process.exit(2);
784
- }
785
- if (opts.outputFile) {
786
- const fsMod = await import('fs');
787
- fsMod.writeFileSync(opts.outputFile, text + '\n', 'utf-8');
788
- process.stderr.write(`Written to ${opts.outputFile}\n`);
789
- }
790
- else {
791
- console.log(text);
792
- }
793
- });
794
- addNetworkOptions(builderCommand
795
- .command('validate <input>')
796
- .description('Run static validation over a transaction JSON (structure, uint ranges, approval criteria, …). Offline — no API calls. Input: JSON file, inline JSON, or - for stdin. Exits 1 on validation failure, 2 on parse failure.'))
797
- .option('--json', 'Output the full ValidationResult as JSON')
798
- .option('--output-file <path>', 'Write output to file instead of stdout')
799
- .action(async (input, opts) => {
800
- const { readJsonInput, output } = await import('../utils/io.js');
801
- let data;
802
- try {
803
- data = ensureTxWrapper(readJsonInput(input));
804
- }
805
- catch (err) {
806
- const friendly = err?.message || String(err);
807
- if (opts.json) {
808
- const { output: outFn } = await import('../utils/io.js');
809
- outFn({ valid: false, issues: [{ severity: 'error', path: '(input)', message: friendly }] }, { ...opts, human: false });
810
- }
811
- else {
812
- process.stderr.write(`✗ Could not parse input: ${friendly}\n`);
813
- }
814
- process.exit(2);
815
- }
816
- if (Array.isArray(data?.messages) && data.messages.length === 0) {
817
- const result = {
818
- valid: true,
819
- issues: [
820
- {
821
- severity: 'warning',
822
- path: 'messages',
823
- message: 'Transaction has an empty messages array. Did you forget to add any messages?'
824
- }
825
- ]
826
- };
827
- if (opts.json) {
828
- output(result, { ...opts, human: false });
829
- }
830
- else {
831
- process.stderr.write('▲ WARNING messages: Transaction has an empty messages array.\n');
832
- }
833
- process.exitCode = 1;
834
- return;
835
- }
836
- const { validateTransaction } = await import('../../core/validate.js');
837
- const result = validateTransaction(data);
838
- if (opts.json) {
839
- output(result, { ...opts, human: false });
840
- }
841
- else {
842
- const { makeColor, rule } = await import('../utils/terminal.js');
843
- const { c } = makeColor(process.stdout);
844
- const width = Math.min(80, process.stdout.columns || 80);
845
- const lines = [];
846
- lines.push(c('gray', rule('━', width, 'Validate')));
847
- if (result.issues.length === 0) {
848
- lines.push('');
849
- lines.push(` ${c('green', '✓')} ${c('bold', 'Clean')} — no structural issues`);
850
- lines.push('');
851
- }
852
- else {
853
- lines.push('');
854
- for (const issue of result.issues) {
855
- const levelColor = issue.severity === 'error' ? 'red' : 'yellow';
856
- const badge = issue.severity === 'error' ? '■ ERROR ' : '▲ WARNING';
857
- lines.push(` ${c(levelColor, c('bold', badge))} ${c('dim', issue.path || '(root)')}`);
858
- lines.push(` ${issue.message}`);
859
- lines.push('');
860
- }
861
- }
862
- lines.push(c('gray', rule('━', width)));
863
- const errCount = result.issues.filter((i) => i.severity === 'error').length;
864
- const warnCount = result.issues.filter((i) => i.severity === 'warning').length;
865
- lines.push(` ${c('bold', 'Summary')} ${errCount > 0 ? c('red', `${errCount} error`) : c('gray', `${errCount} error`)} · ${warnCount > 0 ? c('yellow', `${warnCount} warning`) : c('gray', `${warnCount} warning`)}`);
866
- lines.push(c('gray', rule('━', width)));
867
- const text = lines.join('\n');
868
- if (opts.outputFile) {
869
- const fsMod = await import('fs');
870
- const plain = text.replace(/\x1b\[[0-9;]*m/g, '');
871
- fsMod.writeFileSync(opts.outputFile, plain + '\n', 'utf-8');
872
- process.stderr.write(`Written to ${opts.outputFile}\n`);
873
- }
874
- else {
875
- console.log(text);
876
- }
877
- }
878
- if (!result.valid)
879
- process.exitCode = 1;
880
- });
881
- const sessionCommand = builderCommand
882
- .command('session')
883
- .description('Inspect, dump, or reset persisted builder sessions.');
884
- sessionCommand
885
- .command('list')
886
- .description('List persisted session ids under ~/.bitbadges/sessions/.')
887
- .action(() => {
888
- for (const id of listSessionFilesOnDisk()) {
889
- process.stdout.write(id + '\n');
890
- }
891
- });
892
- sessionCommand
893
- .command('show <id>')
894
- .description('Print a session snapshot as JSON.')
895
- .action((id) => {
896
- const raw = readSessionFileRaw(id);
897
- if (raw === null) {
898
- process.stderr.write(`No session file at ${sessionFilePath(id)}\n`);
899
- process.exitCode = 1;
900
- return;
901
- }
902
- process.stdout.write(raw);
903
- });
904
- sessionCommand
905
- .command('reset <id>')
906
- .description('Delete a persisted session file.')
907
- .action((id) => {
908
- resetSessionFile(id);
909
- });
910
- const resourcesCommand = builderCommand
911
- .command('resources')
912
- .description('Read static builder resources (token registry, recipes, skills, docs, error patterns, ...).');
913
- resourcesCommand
914
- .command('list')
915
- .description('List every resource with its metadata as JSON.')
916
- .option('--uris', 'Print only resource URIs, one per line')
917
- .action((opts) => {
918
- if (opts.uris) {
919
- for (const uri of Object.keys(resourceRegistry)) {
920
- process.stdout.write(`${uri}\n`);
921
- }
922
- return;
923
- }
924
- process.stdout.write(JSON.stringify(listResources(), null, 2) + '\n');
925
- });
926
- resourcesCommand
927
- .command('read <uri>')
928
- .description('Read a resource body by URI (e.g. bitbadges://recipes/all).')
929
- .action((uri) => {
930
- const result = readResource(uri);
931
- process.stdout.write(result.text + '\n');
932
- if (result.isError) {
933
- process.exitCode = 1;
934
- }
935
- });
936
- //# sourceMappingURL=builder.js.map