@clarigen/cli 1.0.0-next.9 → 2.0.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.
@@ -0,0 +1,1442 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __objRest = (source, exclude) => {
25
+ var target = {};
26
+ for (var prop in source)
27
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
28
+ target[prop] = source[prop];
29
+ if (source != null && __getOwnPropSymbols)
30
+ for (var prop of __getOwnPropSymbols(source)) {
31
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
32
+ target[prop] = source[prop];
33
+ }
34
+ return target;
35
+ };
36
+ var __copyProps = (to, from, except, desc) => {
37
+ if (from && typeof from === "object" || typeof from === "function") {
38
+ for (let key of __getOwnPropNames(from))
39
+ if (!__hasOwnProp.call(to, key) && key !== except)
40
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
41
+ }
42
+ return to;
43
+ };
44
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod));
45
+ var __publicField = (obj, key, value) => {
46
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
47
+ return value;
48
+ };
49
+
50
+ // src/run-cli.ts
51
+ var import_clipanion6 = require("clipanion");
52
+
53
+ // src/commands/session-info.ts
54
+ var import_clipanion2 = require("clipanion");
55
+
56
+ // src/config.ts
57
+ var import_zod2 = require("zod");
58
+
59
+ // src/logger.ts
60
+ var import_pino = require("pino");
61
+ var import_pino_pretty = __toESM(require("pino-pretty"), 1);
62
+ var colorizedClarigen = `\x1B[33m[Clarigen]\x1B[0m`;
63
+ var logger = (0, import_pino.pino)((0, import_pino_pretty.default)({
64
+ colorize: true,
65
+ ignore: "pid,hostname,time",
66
+ messageFormat: `${colorizedClarigen} {msg}`,
67
+ minimumLevel: "debug"
68
+ }));
69
+ logger.level = "info";
70
+ var log = logger;
71
+
72
+ // src/utils.ts
73
+ var import_core = require("@clarigen/core");
74
+ var import_promises = require("fs/promises");
75
+ var import_path = require("path");
76
+ function encodeVariableName(name) {
77
+ if (/^[A-Z\-_]*$/.test(name))
78
+ return name.replaceAll("-", "_");
79
+ return (0, import_core.toCamelCase)(name);
80
+ }
81
+ async function fileExists(filename) {
82
+ try {
83
+ await (0, import_promises.stat)(filename);
84
+ return true;
85
+ } catch (error) {
86
+ return false;
87
+ }
88
+ }
89
+ async function writeFile(path, contents) {
90
+ const dir = (0, import_path.dirname)(path);
91
+ await (0, import_promises.mkdir)(dir, { recursive: true });
92
+ await (0, import_promises.writeFile)(path, contents, "utf-8");
93
+ return path;
94
+ }
95
+ function sortContracts(contracts) {
96
+ const nameSorted = [...contracts].sort((a, b) => {
97
+ if ((0, import_core.getContractName)(a.contract_id, false) < (0, import_core.getContractName)(b.contract_id, false)) {
98
+ return -1;
99
+ }
100
+ return 1;
101
+ });
102
+ return nameSorted;
103
+ }
104
+
105
+ // src/clarinet-config.ts
106
+ var import_zod = require("zod");
107
+ var import_promises2 = require("fs/promises");
108
+ var import_toml = require("@iarna/toml");
109
+ var ClarinetConfigSchema = import_zod.z.object({
110
+ project: import_zod.z.object({
111
+ requirements: import_zod.z.array(import_zod.z.object({ contract_id: import_zod.z.string() })).optional(),
112
+ cache_location: import_zod.z.object({ path: import_zod.z.string() }).optional()
113
+ }),
114
+ contracts: import_zod.z.record(import_zod.z.string(), import_zod.z.object({ path: import_zod.z.string() })).optional()
115
+ });
116
+ async function getClarinetConfig(path) {
117
+ const file = await (0, import_promises2.readFile)(path, "utf-8");
118
+ const config = ClarinetConfigSchema.parse((0, import_toml.parse)(file));
119
+ return config;
120
+ }
121
+
122
+ // src/config.ts
123
+ var import_path2 = require("path");
124
+ var import_toml2 = require("@iarna/toml");
125
+ var import_promises3 = require("fs/promises");
126
+ var CONFIG_FILE = "Clarigen.toml";
127
+ var typesSchema = import_zod2.z.object({
128
+ output: import_zod2.z.string().optional(),
129
+ outputs: import_zod2.z.array(import_zod2.z.string()).optional(),
130
+ include_accounts: import_zod2.z.boolean().optional(),
131
+ after: import_zod2.z.string().optional()
132
+ }).optional();
133
+ var ConfigFileSchema = import_zod2.z.object({
134
+ clarinet: import_zod2.z.string(),
135
+ ["types" /* ESM */]: typesSchema,
136
+ ["esm" /* ESM_OLD */]: typesSchema,
137
+ ["docs" /* Docs */]: import_zod2.z.object({
138
+ output: import_zod2.z.string().optional(),
139
+ outputs: import_zod2.z.array(import_zod2.z.string()).optional(),
140
+ exclude: import_zod2.z.array(import_zod2.z.string()).optional(),
141
+ after: import_zod2.z.string().optional()
142
+ }).optional()
143
+ });
144
+ var defaultConfigFile = {
145
+ clarinet: "./Clarinet.toml"
146
+ };
147
+ var Config = class {
148
+ configFile;
149
+ clarinet;
150
+ cwd;
151
+ constructor(config, clarinet, cwd) {
152
+ this.configFile = config;
153
+ this.clarinet = clarinet;
154
+ this.cwd = cwd ?? process.cwd();
155
+ }
156
+ static async load(cwd) {
157
+ const config = await getConfig(cwd);
158
+ if (config["esm" /* ESM_OLD */]) {
159
+ config["types" /* ESM */] = config["esm" /* ESM_OLD */];
160
+ delete config["esm" /* ESM_OLD */];
161
+ }
162
+ const clarinet = await getClarinetConfig((0, import_path2.resolve)(cwd ?? "", config.clarinet));
163
+ return new this(config, clarinet, cwd);
164
+ }
165
+ getOutputs(type) {
166
+ var _a, _b;
167
+ const singlePath = (_a = this.configFile[type]) == null ? void 0 : _a.output;
168
+ const multiPath = ((_b = this.configFile[type]) == null ? void 0 : _b.outputs) || [];
169
+ if (singlePath !== void 0)
170
+ return [singlePath];
171
+ return multiPath;
172
+ }
173
+ outputResolve(type, filePath) {
174
+ const outputs = this.getOutputs(type);
175
+ if (!this.supports(type))
176
+ return null;
177
+ return outputs.map((path) => {
178
+ return (0, import_path2.resolve)(this.cwd, path, filePath || "");
179
+ });
180
+ }
181
+ async writeOutput(type, contents, filePath) {
182
+ const paths = this.outputResolve(type, filePath);
183
+ if (paths === null)
184
+ return null;
185
+ await Promise.all(paths.map(async (path) => {
186
+ await writeFile(path, contents);
187
+ log.debug(`Generated ${type} file at ${(0, import_path2.relative)(this.cwd, path)}`);
188
+ }));
189
+ return paths;
190
+ }
191
+ supports(type) {
192
+ return this.getOutputs(type).length > 0;
193
+ }
194
+ type(type) {
195
+ return this.configFile[type];
196
+ }
197
+ get esm() {
198
+ return this.configFile["types" /* ESM */];
199
+ }
200
+ get docs() {
201
+ return this.configFile["docs" /* Docs */];
202
+ }
203
+ clarinetFile() {
204
+ return (0, import_path2.resolve)(this.cwd, this.configFile.clarinet);
205
+ }
206
+ joinFromClarinet(filePath) {
207
+ const baseDir = (0, import_path2.dirname)(this.clarinetFile());
208
+ return (0, import_path2.join)(baseDir, filePath);
209
+ }
210
+ };
211
+ function configFilePath(cwd) {
212
+ return (0, import_path2.resolve)(cwd ?? process.cwd(), CONFIG_FILE);
213
+ }
214
+ var sessionConfig;
215
+ async function getConfig(cwd) {
216
+ if (typeof sessionConfig !== "undefined")
217
+ return sessionConfig;
218
+ const path = configFilePath(cwd);
219
+ if (await fileExists(path)) {
220
+ const toml = await (0, import_promises3.readFile)(path, "utf-8");
221
+ const parsedToml = (0, import_toml2.parse)(toml);
222
+ sessionConfig = ConfigFileSchema.parse(parsedToml);
223
+ } else {
224
+ sessionConfig = defaultConfigFile;
225
+ }
226
+ return sessionConfig;
227
+ }
228
+
229
+ // src/commands/base-command.ts
230
+ var import_clipanion = require("clipanion");
231
+ var import_zod3 = require("zod");
232
+ var BaseCommand = class extends import_clipanion.Command {
233
+ verbose = import_clipanion.Option.Boolean("-v,--verbose", false, {
234
+ description: "Enable verbose logging"
235
+ });
236
+ preexecute() {
237
+ if (this.verbose) {
238
+ logger.level = "debug";
239
+ }
240
+ }
241
+ async catch(error) {
242
+ if (error instanceof import_zod3.ZodError) {
243
+ logger.error(error.issues, "Your configuration file is invalid.");
244
+ return;
245
+ }
246
+ logger.error(error);
247
+ if (error instanceof Error) {
248
+ logger.error(error.stack);
249
+ }
250
+ throw error;
251
+ }
252
+ };
253
+
254
+ // src/commands/session-info.ts
255
+ var SessionInfoCommand = class extends BaseCommand {
256
+ cwd = import_clipanion2.Option.String({ required: false });
257
+ async execute() {
258
+ this.preexecute();
259
+ const config = await Config.load(this.cwd);
260
+ logger.info(config);
261
+ }
262
+ };
263
+ __publicField(SessionInfoCommand, "paths", [["session-info"]]);
264
+ __publicField(SessionInfoCommand, "usage", import_clipanion2.Command.Usage({
265
+ description: "Log info about this project's Clarinet session"
266
+ }));
267
+
268
+ // src/commands/default-command.ts
269
+ var import_clipanion3 = require("clipanion");
270
+
271
+ // src/clarinet-sdk.ts
272
+ var import_clarinet_sdk = require("@hirosystems/clarinet-sdk");
273
+ var import_core7 = require("@clarigen/core");
274
+ var import_transactions = require("@stacks/transactions");
275
+ var import_promises4 = require("fs/promises");
276
+
277
+ // src/files/variables.ts
278
+ var import_core6 = require("@clarigen/core");
279
+
280
+ // src/declaration.ts
281
+ var import_core2 = require("@clarigen/core");
282
+ var import_core3 = require("@clarigen/core");
283
+ var jsTypeFromAbiType = (val, isArgument = false) => {
284
+ if ((0, import_core2.isClarityAbiPrimitive)(val)) {
285
+ if (val === "uint128") {
286
+ if (isArgument)
287
+ return "number | bigint";
288
+ return "bigint";
289
+ } else if (val === "int128") {
290
+ if (isArgument)
291
+ return "number | bigint";
292
+ return "bigint";
293
+ } else if (val === "bool") {
294
+ return "boolean";
295
+ } else if (val === "principal") {
296
+ return "string";
297
+ } else if (val === "none") {
298
+ return "null";
299
+ } else if (val === "trait_reference") {
300
+ return "string";
301
+ } else {
302
+ throw new Error(`Unexpected Clarity ABI type primitive: ${JSON.stringify(val)}`);
303
+ }
304
+ } else if ((0, import_core2.isClarityAbiBuffer)(val)) {
305
+ return "Uint8Array";
306
+ } else if ((0, import_core2.isClarityAbiResponse)(val)) {
307
+ const ok = jsTypeFromAbiType(val.response.ok, isArgument);
308
+ const err = jsTypeFromAbiType(val.response.error, isArgument);
309
+ return `Response<${ok}, ${err}>`;
310
+ } else if ((0, import_core2.isClarityAbiOptional)(val)) {
311
+ const innerType = jsTypeFromAbiType(val.optional, isArgument);
312
+ return `${innerType} | null`;
313
+ } else if ((0, import_core2.isClarityAbiTuple)(val)) {
314
+ const tupleDefs = [];
315
+ val.tuple.forEach(({ name, type }) => {
316
+ const camelName = (0, import_core3.toCamelCase)(name);
317
+ const innerType = jsTypeFromAbiType(type, isArgument);
318
+ tupleDefs.push(`"${camelName}": ${innerType};`);
319
+ });
320
+ return `{
321
+ ${tupleDefs.join("\n ")}
322
+ }`;
323
+ } else if ((0, import_core2.isClarityAbiList)(val)) {
324
+ const innerType = jsTypeFromAbiType(val.list.type, isArgument);
325
+ return `${innerType}[]`;
326
+ } else if ((0, import_core2.isClarityAbiStringAscii)(val)) {
327
+ return "string";
328
+ } else if ((0, import_core2.isClarityAbiStringUtf8)(val)) {
329
+ return "string";
330
+ } else if ((0, import_core2.isClarityAbiTraitReference)(val)) {
331
+ return "string";
332
+ } else {
333
+ throw new Error(`Unexpected Clarity ABI type: ${JSON.stringify(val)}`);
334
+ }
335
+ };
336
+ function abiArgType(arg) {
337
+ const nativeType = jsTypeFromAbiType(arg.type, true);
338
+ const argName = getArgName(arg.name);
339
+ return `${argName}: TypedAbiArg<${nativeType}, "${argName}">`;
340
+ }
341
+ function abiFunctionType(abiFunction) {
342
+ const args2 = abiFunction.args.map(abiArgType);
343
+ const retType = jsTypeFromAbiType(abiFunction.outputs.type);
344
+ const argsTuple = `[${args2.join(", ")}]`;
345
+ return `TypedAbiFunction<${argsTuple}, ${retType}>`;
346
+ }
347
+ function getArgName(name) {
348
+ const camel = (0, import_core3.toCamelCase)(name);
349
+ const prefix = RESERVED[camel] ? "_" : "";
350
+ return `${prefix}${camel}`;
351
+ }
352
+ function _hash(...words) {
353
+ const h = {};
354
+ for (const word of words) {
355
+ h[word] = true;
356
+ }
357
+ return h;
358
+ }
359
+ var RESERVED = _hash("break", "do", "in", "typeof", "case", "else", "instanceof", "var", "catch", "export", "new", "void", "class", "extends", "return", "while", "const", "finally", "super", "with", "continue", "for", "switch", "yield", "debugger", "function", "this", "default", "if", "throw", "delete", "import", "try", "enum", "await", "null", "true", "false");
360
+
361
+ // src/files/base.ts
362
+ var import_core5 = require("@clarigen/core");
363
+
364
+ // src/files/accounts.ts
365
+ function generateAccountsCode(session) {
366
+ const accounts = Object.fromEntries(session.accounts.map((account) => {
367
+ const _a = account, { name } = _a, rest = __objRest(_a, ["name"]);
368
+ return [name, rest];
369
+ }));
370
+ return `export const accounts = ${JSON.stringify(accounts)} as const;`;
371
+ }
372
+
373
+ // src/files/identifiers.ts
374
+ var import_core4 = require("@clarigen/core");
375
+ function generateIdentifiers(session) {
376
+ const identifiers = Object.fromEntries(sortContracts(session.contracts).map((c) => {
377
+ const contractName = (0, import_core4.getContractName)(c.contract_id);
378
+ return [contractName, c.contract_id];
379
+ }));
380
+ return identifiers;
381
+ }
382
+ function generateIdentifiersCode(session) {
383
+ const identifiers = generateIdentifiers(session);
384
+ return `export const identifiers = ${JSON.stringify(identifiers)} as const`;
385
+ }
386
+
387
+ // src/files/base.ts
388
+ var import_util = require("util");
389
+ function generateContractMeta(contract, constants) {
390
+ const abi = contract.contract_interface;
391
+ const functionLines = [];
392
+ const _a = abi, { functions, maps, variables, non_fungible_tokens } = _a, rest = __objRest(_a, ["functions", "maps", "variables", "non_fungible_tokens"]);
393
+ functions.forEach((func) => {
394
+ let functionLine = `${(0, import_core5.toCamelCase)(func.name)}: `;
395
+ const funcDef = JSON.stringify(func);
396
+ functionLine += funcDef;
397
+ const functionType = abiFunctionType(func);
398
+ functionLine += ` as ${functionType}`;
399
+ functionLines.push(functionLine);
400
+ });
401
+ const mapLines = maps.map((map) => {
402
+ let mapLine = `${(0, import_core5.toCamelCase)(map.name)}: `;
403
+ const keyType = jsTypeFromAbiType(map.key, true);
404
+ const valType = jsTypeFromAbiType(map.value);
405
+ mapLine += JSON.stringify(map);
406
+ mapLine += ` as TypedAbiMap<${keyType}, ${valType}>`;
407
+ return mapLine;
408
+ });
409
+ const otherAbi = JSON.stringify(rest);
410
+ const contractName = contract.contract_id.split(".")[1];
411
+ const variableLines = encodeVariables(variables);
412
+ const nftLines = non_fungible_tokens.map((nft) => {
413
+ return JSON.stringify(nft);
414
+ });
415
+ return `{
416
+ ${serializeLines("functions", functionLines)}
417
+ ${serializeLines("maps", mapLines)}
418
+ ${serializeLines("variables", variableLines)}
419
+ constants: ${constants},
420
+ ${serializeArray("non_fungible_tokens", nftLines)}
421
+ ${otherAbi.slice(1, -1)},
422
+ contractName: '${contractName}',
423
+ }`;
424
+ }
425
+ var TYPE_IMPORTS = `import type { TypedAbiArg, TypedAbiFunction, TypedAbiMap, TypedAbiVariable, Response } from '@clarigen/core';`;
426
+ function generateBaseFile(session) {
427
+ const combined = session.contracts.map((c, i) => __spreadProps(__spreadValues({}, c), {
428
+ constants: session.variables[i]
429
+ }));
430
+ const contractDefs = sortContracts(combined).map((contract) => {
431
+ const meta = generateContractMeta(contract, contract.constants);
432
+ const id = contract.contract_id.split(".")[1];
433
+ const keyName = (0, import_core5.toCamelCase)(id);
434
+ return `${keyName}: ${meta}`;
435
+ });
436
+ const file = `
437
+ ${TYPE_IMPORTS}
438
+
439
+ export const contracts = {
440
+ ${contractDefs.join(",\n")}
441
+ } as const;
442
+
443
+ ${generateAccountsCode(session)}
444
+
445
+ ${generateIdentifiersCode(session)}
446
+
447
+ export const simnet = {
448
+ accounts,
449
+ contracts,
450
+ identifiers,
451
+ } as const;
452
+
453
+ `;
454
+ return file;
455
+ }
456
+ function encodeVariables(variables) {
457
+ return variables.map((v) => {
458
+ let varLine = `${encodeVariableName(v.name)}: `;
459
+ const type = jsTypeFromAbiType(v.type);
460
+ const varJSON = serialize(v);
461
+ varLine += `${varJSON} as TypedAbiVariable<${type}>`;
462
+ return varLine;
463
+ });
464
+ }
465
+ Uint8Array.prototype[import_util.inspect.custom] = function(depth, options) {
466
+ return `Uint8Array.from([${this.join(",")}])`;
467
+ };
468
+ function serialize(obj) {
469
+ return (0, import_util.inspect)(obj, {
470
+ showHidden: false,
471
+ compact: false,
472
+ depth: 100,
473
+ colors: false,
474
+ maxArrayLength: Infinity,
475
+ maxStringLength: Infinity,
476
+ breakLength: Infinity,
477
+ numericSeparator: true
478
+ });
479
+ }
480
+ function serializeLines(key, lines) {
481
+ return `"${key}": {
482
+ ${lines.join(",\n ")}
483
+ },`;
484
+ }
485
+ function serializeArray(key, lines) {
486
+ return `"${key}": [
487
+ ${lines.join(",\n ")}
488
+ ],`;
489
+ }
490
+
491
+ // src/files/variables.ts
492
+ function getVariablesV2(contract, simnet, verbose) {
493
+ const [deployer] = contract.contract_id.split(".");
494
+ const fakeId = `${(0, import_core6.getContractName)(contract.contract_id)}-vars`;
495
+ logger.debug(`Deploying ${contract.contract_id} for variables.`);
496
+ if (!contract.source) {
497
+ logger.debug(`Contract ${(0, import_core6.getContractName)(contract.contract_id)} has no source. Skipping variables.`);
498
+ return {};
499
+ }
500
+ if (contract.contract_interface.variables.length === 0) {
501
+ logger.info(`Contract ${(0, import_core6.getContractName)(contract.contract_id, false)} has no variables`);
502
+ return {};
503
+ }
504
+ let varFn = `{
505
+ `;
506
+ const varLines = contract.contract_interface.variables.map((variable) => {
507
+ let varLine = `${variable.name}: `;
508
+ if (variable.access === "constant") {
509
+ varLine += `${variable.name}`;
510
+ } else {
511
+ varLine += `(var-get ${variable.name})`;
512
+ }
513
+ return varLine;
514
+ });
515
+ varFn += varLines.map((l) => ` ${l},`).join("\n");
516
+ varFn += "\n}";
517
+ const fullSrc = contract.source + `
518
+
519
+ ${varFn}`;
520
+ try {
521
+ const receipt = simnet.deployContract(fakeId, fullSrc, {
522
+ clarityVersion: 2
523
+ }, deployer);
524
+ const result = receipt.result;
525
+ const varsAbi = {
526
+ tuple: []
527
+ };
528
+ contract.contract_interface.variables.forEach((v) => {
529
+ const _v = v;
530
+ varsAbi.tuple.push({
531
+ type: _v.type,
532
+ name: _v.name
533
+ });
534
+ });
535
+ if (verbose) {
536
+ logger.info((0, import_core6.cvToValue)(result, true));
537
+ }
538
+ return (0, import_core6.cvToValue)(result, true);
539
+ } catch (error) {
540
+ logger.error(`Error getting variables for ${(0, import_core6.getContractName)(contract.contract_id, false)}`);
541
+ logger.error(`Source code: ${contract.source} with type ${String(typeof contract.source)}`);
542
+ logger.error(error);
543
+ logger.error(fullSrc);
544
+ return {};
545
+ }
546
+ }
547
+ function mapVariables(session, simnet) {
548
+ return session.contracts.map((contract) => {
549
+ const vars = getVariablesV2(contract, simnet);
550
+ return serialize(vars);
551
+ });
552
+ }
553
+
554
+ // src/clarinet-sdk.ts
555
+ async function getSession(config) {
556
+ const simnet = await (0, import_clarinet_sdk.initSimnet)(config.clarinetFile());
557
+ const interfaces = simnet.getContractsInterfaces();
558
+ const accounts = simnet.getAccounts();
559
+ const allAccounts = [...accounts.entries()].map(([name, address]) => {
560
+ const result = simnet.runSnippet(`(stx-get-balance '${address})`);
561
+ if (result.type !== import_transactions.ClarityType.UInt) {
562
+ throw new Error(`Unexpected result type for \`(stx-get-balance \``);
563
+ }
564
+ return {
565
+ name,
566
+ address,
567
+ balance: result.value.toString()
568
+ };
569
+ });
570
+ const contracts = (await Promise.all([...interfaces.entries()].map(async ([contract_id, contract_interface]) => {
571
+ var _a, _b;
572
+ if (contract_id.startsWith(import_core7.MAINNET_BURN_ADDRESS) || contract_id.startsWith(import_core7.TESTNET_BURN_ADDRESS)) {
573
+ return void 0;
574
+ }
575
+ const name = (0, import_core7.getContractName)(contract_id, false);
576
+ const contractPathDef = (_b = (_a = config.clarinet.contracts) == null ? void 0 : _a[name]) == null ? void 0 : _b.path;
577
+ let source;
578
+ if (contractPathDef) {
579
+ const contractPathFull = config.joinFromClarinet(contractPathDef);
580
+ source = await (0, import_promises4.readFile)(contractPathFull, "utf-8");
581
+ }
582
+ return {
583
+ contract_id,
584
+ contract_interface,
585
+ source: source ?? ""
586
+ };
587
+ }))).filter((x) => x !== void 0);
588
+ const session = {
589
+ session_id: 0,
590
+ accounts: allAccounts,
591
+ contracts
592
+ };
593
+ const variables = mapVariables(session, simnet);
594
+ return {
595
+ session_id: 0,
596
+ accounts: allAccounts,
597
+ contracts,
598
+ variables
599
+ };
600
+ }
601
+
602
+ // src/files/esm.ts
603
+ var import_promises5 = require("fs/promises");
604
+ var import_path3 = require("path");
605
+ var import_yaml = require("yaml");
606
+
607
+ // src/deployments.ts
608
+ function flatBatch(batches) {
609
+ const txs = [];
610
+ batches.forEach((batch) => txs.push(...batch.transactions));
611
+ return txs;
612
+ }
613
+ function getContractTxs(batches) {
614
+ const txs = flatBatch(batches);
615
+ return txs.filter(isContractTx);
616
+ }
617
+ function getDeploymentContract(contractName, deployment) {
618
+ const txs = flatBatch(deployment.plan.batches);
619
+ for (const tx of txs) {
620
+ if (!isContractTx(tx))
621
+ continue;
622
+ if ("requirement-publish" in tx) {
623
+ const [_, name] = tx["requirement-publish"]["contract-id"].split(".");
624
+ if (name === contractName) {
625
+ return tx;
626
+ }
627
+ } else if ("emulated-contract-publish" in tx) {
628
+ if (tx["emulated-contract-publish"]["contract-name"] === contractName) {
629
+ return tx;
630
+ }
631
+ } else if ("contract-publish" in tx) {
632
+ const contract = tx["contract-publish"];
633
+ if (contract["contract-name"] === contractName) {
634
+ return tx;
635
+ }
636
+ }
637
+ }
638
+ throw new Error(`Unable to find deployment tx for contract '${contractName}'`);
639
+ }
640
+ function getDeploymentTxPath(tx) {
641
+ if (!isContractTx(tx)) {
642
+ throw new Error("Unable to get path for tx type.");
643
+ }
644
+ if ("requirement-publish" in tx) {
645
+ return tx["requirement-publish"].path;
646
+ } else if ("emulated-contract-publish" in tx) {
647
+ const contract = tx["emulated-contract-publish"];
648
+ return contract.path;
649
+ } else if ("contract-publish" in tx) {
650
+ const contract = tx["contract-publish"];
651
+ return contract.path;
652
+ }
653
+ throw new Error("Couldnt get path for deployment tx.");
654
+ }
655
+ function getIdentifier(tx) {
656
+ if (!isContractTx(tx)) {
657
+ throw new Error("Unable to get ID for tx type.");
658
+ }
659
+ if ("requirement-publish" in tx) {
660
+ const spec = tx["requirement-publish"];
661
+ const [_, name] = spec["contract-id"].split(".");
662
+ return `${spec["remap-sender"]}.${name}`;
663
+ } else if ("emulated-contract-publish" in tx) {
664
+ const contract = tx["emulated-contract-publish"];
665
+ return `${contract["emulated-sender"]}.${contract["contract-name"]}`;
666
+ } else if ("contract-publish" in tx) {
667
+ const contract = tx["contract-publish"];
668
+ return `${contract["expected-sender"]}.${contract["contract-name"]}`;
669
+ }
670
+ throw new Error(`Unable to find ID for contract.`);
671
+ }
672
+ function isContractTx(tx) {
673
+ if ("contract-call" in tx)
674
+ return false;
675
+ if ("btc-transfer" in tx)
676
+ return false;
677
+ if ("emulated-contract-call" in tx)
678
+ return false;
679
+ return true;
680
+ }
681
+
682
+ // src/files/esm.ts
683
+ var import_core8 = require("@clarigen/core");
684
+ var import_child_process = require("child_process");
685
+ async function parseDeployment(path) {
686
+ const contents = await (0, import_promises5.readFile)(path, "utf-8");
687
+ const parsed = (0, import_yaml.parse)(contents);
688
+ return parsed;
689
+ }
690
+ var DEPLOYMENT_NETWORKS = ["devnet", "simnet", "testnet", "mainnet"];
691
+ async function getDeployments(config) {
692
+ const entries = await Promise.all(DEPLOYMENT_NETWORKS.map(async (network) => {
693
+ const file = `default.${network}-plan.yaml`;
694
+ const path = (0, import_path3.join)((0, import_path3.dirname)(config.clarinetFile()), "deployments", file);
695
+ let plan;
696
+ try {
697
+ plan = await parseDeployment(path);
698
+ } catch (_) {
699
+ }
700
+ return [network, plan];
701
+ }));
702
+ return Object.fromEntries(entries);
703
+ }
704
+ async function generateESMFile({
705
+ baseFile,
706
+ session,
707
+ config
708
+ }) {
709
+ const deployments = await getDeployments(config);
710
+ const contractDeployments = collectContractDeployments(session, deployments, config);
711
+ const simnet = generateSimnetCode(config, deployments, session);
712
+ return `${baseFile}
713
+ export const deployments = ${JSON.stringify(contractDeployments)} as const;
714
+ ${simnet}
715
+ export const project = {
716
+ contracts,
717
+ deployments,
718
+ } as const;
719
+ `;
720
+ }
721
+ function insertNetworkId(deployments, identifier, network) {
722
+ const name = (0, import_core8.getContractName)(identifier);
723
+ if (!deployments[name]) {
724
+ return;
725
+ }
726
+ if (deployments[name][network] === null) {
727
+ deployments[name][network] = identifier;
728
+ }
729
+ }
730
+ function collectContractDeployments(session, deployments, config) {
731
+ var _a;
732
+ const full = Object.fromEntries(sortContracts(session.contracts).map((contract) => {
733
+ const contractName = (0, import_core8.getContractName)(contract.contract_id);
734
+ const contractDeployments = Object.fromEntries(DEPLOYMENT_NETWORKS.map((network) => {
735
+ const deployment = deployments[network];
736
+ if (typeof deployment === "undefined") {
737
+ return [network, null];
738
+ }
739
+ try {
740
+ const contractName2 = contract.contract_id.split(".")[1];
741
+ const tx = getDeploymentContract(contractName2, deployment);
742
+ const id = getIdentifier(tx);
743
+ return [network, id];
744
+ } catch (_) {
745
+ return [network, null];
746
+ }
747
+ }));
748
+ return [contractName, contractDeployments];
749
+ }));
750
+ const deployer = session.accounts.find((a) => a.name === "deployer");
751
+ (_a = config.clarinet.project.requirements) == null ? void 0 : _a.forEach(({ contract_id }) => {
752
+ insertNetworkId(full, contract_id, "mainnet");
753
+ const contractName = contract_id.split(".")[1];
754
+ if (deployer) {
755
+ const devnetId = `${deployer.address}.${contractName}`;
756
+ insertNetworkId(full, devnetId, "devnet");
757
+ }
758
+ });
759
+ session.contracts.forEach((contract) => {
760
+ insertNetworkId(full, contract.contract_id, "devnet");
761
+ insertNetworkId(full, contract.contract_id, "simnet");
762
+ });
763
+ return full;
764
+ }
765
+ function collectDeploymentFiles(deployments, clarinetFolder, cwd) {
766
+ if (!deployments.simnet)
767
+ return [];
768
+ const simnet = deployments.simnet;
769
+ const txs = getContractTxs(simnet.plan.batches);
770
+ const entries = txs.map((tx) => {
771
+ const id = getIdentifier(tx);
772
+ const contractFile = getDeploymentTxPath(tx);
773
+ return {
774
+ identifier: id,
775
+ file: (0, import_path3.relative)(cwd, (0, import_path3.join)(clarinetFolder, contractFile))
776
+ };
777
+ });
778
+ return entries;
779
+ }
780
+ function generateSimnetCode(config, deployments, _session) {
781
+ var _a;
782
+ if (!((_a = config.esm) == null ? void 0 : _a.include_accounts))
783
+ return "";
784
+ const clarinetFolder = (0, import_path3.dirname)(config.clarinetFile());
785
+ const files = collectDeploymentFiles(deployments, clarinetFolder, config.cwd);
786
+ return `
787
+ export const simnetDeployment = ${JSON.stringify(files)};
788
+ `;
789
+ }
790
+ async function afterESM(config) {
791
+ var _a;
792
+ const command = (_a = config.esm) == null ? void 0 : _a.after;
793
+ if (!command)
794
+ return;
795
+ logger.debug(`Running after ESM command: ${command}`);
796
+ const parts = command.split(" ");
797
+ const [cmd, ...args2] = parts;
798
+ return new Promise((resolve3, reject) => {
799
+ const child = (0, import_child_process.spawn)(cmd, args2, {
800
+ cwd: config.cwd,
801
+ stdio: "inherit"
802
+ });
803
+ child.on("error", reject);
804
+ child.on("exit", (code) => {
805
+ if (code === 0) {
806
+ resolve3();
807
+ } else {
808
+ reject(new Error(`Command failed with code ${code ?? "unknown"}`));
809
+ }
810
+ });
811
+ });
812
+ }
813
+
814
+ // src/commands/default-command.ts
815
+ var import_chokidar = __toESM(require("chokidar"), 1);
816
+ var import_path4 = require("path");
817
+ async function generate(config) {
818
+ const session = await getSession(config);
819
+ const baseFile = generateBaseFile(session);
820
+ if (config.supports("types" /* ESM */)) {
821
+ const esmFile = await generateESMFile({
822
+ baseFile,
823
+ session,
824
+ config
825
+ });
826
+ await config.writeOutput("types" /* ESM */, esmFile);
827
+ await afterESM(config);
828
+ }
829
+ if (!config.supports("types" /* ESM */)) {
830
+ logger.warn("no config for ESM outputs. Not outputting any generated types.");
831
+ }
832
+ logger.info("Types generated!");
833
+ }
834
+ async function watch(config, cwd) {
835
+ return new Promise((resolve3, reject) => {
836
+ const clarinetFolder = (0, import_path4.dirname)(config.clarinetFile());
837
+ const contractsFolder = (0, import_path4.join)(clarinetFolder, "/contracts/**/*.clar");
838
+ const relativeFolder = (0, import_path4.relative)(cwd || process.cwd(), contractsFolder);
839
+ logger.info(`Watching for changes in ${relativeFolder}`);
840
+ const watcher = import_chokidar.default.watch(contractsFolder, { persistent: true, cwd: clarinetFolder });
841
+ let running = false;
842
+ let start = 0;
843
+ const isVerbose = logger.level !== "info";
844
+ watcher.on("change", (path) => {
845
+ if (!running) {
846
+ start = Date.now();
847
+ logger.info(`File ${path} has been changed. Generating types.`);
848
+ running = true;
849
+ void generate(config).then(() => {
850
+ setTimeout(() => {
851
+ process.stdout.moveCursor(0, -1);
852
+ process.stdout.clearLine(1);
853
+ const elapsed = Date.now() - start;
854
+ logger.info(`Types generated (${(elapsed / 1e3).toFixed(2)}s). Watching for changes...`);
855
+ running = false;
856
+ });
857
+ });
858
+ }
859
+ });
860
+ });
861
+ }
862
+ var DefaultCommand = class extends BaseCommand {
863
+ cwd = import_clipanion3.Option.String({
864
+ required: false
865
+ });
866
+ watch = import_clipanion3.Option.Boolean("-w,--watch", {
867
+ description: "Watch for changes and regenerate types",
868
+ required: false
869
+ });
870
+ async execute() {
871
+ this.preexecute();
872
+ const config = await Config.load(this.cwd);
873
+ if (this.watch) {
874
+ await watch(config, this.cwd);
875
+ } else {
876
+ await generate(config);
877
+ }
878
+ }
879
+ };
880
+ __publicField(DefaultCommand, "paths", [import_clipanion3.Command.Default, ["generate"]]);
881
+ __publicField(DefaultCommand, "usage", import_clipanion3.Command.Usage({
882
+ description: "Generate types for your Clarity contracts",
883
+ examples: [
884
+ ["Basic usage:", "clarigen"],
885
+ ["When your `Clarigen.toml` is in a different directory:", "clarigen /path/to/your/project"],
886
+ ["Watch for changes and regenerate types:", "clarigen --watch"]
887
+ ]
888
+ }));
889
+
890
+ // src/commands/docs-command.ts
891
+ var import_clipanion4 = require("clipanion");
892
+
893
+ // src/files/docs.ts
894
+ var import_core10 = require("@clarigen/core");
895
+ var import_path6 = require("path");
896
+
897
+ // src/docs/markdown.ts
898
+ var import_core9 = require("@clarigen/core");
899
+
900
+ // src/docs/index.ts
901
+ var import_child_process2 = require("child_process");
902
+ var FN_TYPES = ["read-only", "public", "private"];
903
+ var VAR_TYPES = ["map", "data-var", "constant"];
904
+ function createContractDocInfo({
905
+ contractSrc,
906
+ abi
907
+ }) {
908
+ const lines = contractSrc.split("\n");
909
+ let comments = [];
910
+ let parensCount = 0;
911
+ let currentFn;
912
+ const contract = {
913
+ comments: [],
914
+ functions: [],
915
+ variables: [],
916
+ maps: []
917
+ };
918
+ lines.forEach((line, lineNumber) => {
919
+ if (currentFn) {
920
+ currentFn.source.push(line);
921
+ parensCount = traceParens(line, parensCount);
922
+ if (parensCount === 0) {
923
+ pushItem(contract, currentFn);
924
+ currentFn = void 0;
925
+ }
926
+ return;
927
+ }
928
+ if (isComment(line)) {
929
+ const comment = line.replace(/^\s*;;\s*/g, "");
930
+ if (contract.comments.length === lineNumber) {
931
+ contract.comments.push(comment);
932
+ } else {
933
+ comments.push(comment);
934
+ }
935
+ return;
936
+ }
937
+ const name = findItemNameFromLine(line);
938
+ if (typeof name === "undefined") {
939
+ comments = [];
940
+ } else {
941
+ const abiFn = findAbiItemByName(abi, name);
942
+ if (!abiFn) {
943
+ console.debug(`[claridoc]: Unable to find ABI for function \`${name}\`. Probably a bug.`);
944
+ return;
945
+ }
946
+ parensCount = traceParens(line, 0);
947
+ const metaComments = parseComments(comments, abiFn);
948
+ currentFn = {
949
+ abi: abiFn,
950
+ comments: metaComments,
951
+ startLine: lineNumber,
952
+ source: [line]
953
+ };
954
+ if (parensCount === 0) {
955
+ pushItem(contract, currentFn);
956
+ currentFn = void 0;
957
+ }
958
+ comments = [];
959
+ }
960
+ });
961
+ return contract;
962
+ }
963
+ function pushItem(contract, item) {
964
+ if ("args" in item.abi) {
965
+ contract.functions.push(item);
966
+ } else if ("key" in item.abi) {
967
+ contract.maps.push(item);
968
+ } else if ("access" in item.abi) {
969
+ contract.variables.push(item);
970
+ }
971
+ }
972
+ function clarityNameMatcher(line) {
973
+ return /[\w|\-|\?|\!]+/.exec(line);
974
+ }
975
+ function findItemNameFromLine(line) {
976
+ const fnType = FN_TYPES.find((type) => {
977
+ return line.startsWith(`(define-${type}`);
978
+ });
979
+ if (fnType) {
980
+ const prefix = `(define-${fnType} (`;
981
+ const startString = line.slice(prefix.length);
982
+ const match = clarityNameMatcher(startString);
983
+ if (!match) {
984
+ console.debug(`[claridocs]: Unable to determine function name from line:
985
+ \`${line}\``);
986
+ return;
987
+ }
988
+ return match[0];
989
+ }
990
+ for (const type of VAR_TYPES) {
991
+ const prefix = `(define-${type} `;
992
+ if (!line.startsWith(prefix))
993
+ continue;
994
+ const startString = line.slice(prefix.length);
995
+ const match = clarityNameMatcher(startString);
996
+ if (!match) {
997
+ console.debug(`[claridocs]: Unable to determine ${type} name from line:
998
+ \`${line}\``);
999
+ return;
1000
+ }
1001
+ return match[0];
1002
+ }
1003
+ return void 0;
1004
+ }
1005
+ function findAbiItemByName(abi, name) {
1006
+ const fn = abi.functions.find((fn2) => {
1007
+ return fn2.name === name;
1008
+ });
1009
+ if (fn)
1010
+ return fn;
1011
+ const map = abi.maps.find((m) => m.name === name);
1012
+ if (map)
1013
+ return map;
1014
+ const v = abi.variables.find((v2) => v2.name === name);
1015
+ return v;
1016
+ }
1017
+ function isComment(line) {
1018
+ return line.startsWith(";;");
1019
+ }
1020
+ function traceParens(line, count) {
1021
+ let newCount = count;
1022
+ line.split("").forEach((char) => {
1023
+ if (char === "(")
1024
+ newCount++;
1025
+ if (char === ")")
1026
+ newCount--;
1027
+ });
1028
+ return newCount;
1029
+ }
1030
+ function parseComments(comments, abi) {
1031
+ let curParam;
1032
+ const parsed = {
1033
+ text: [],
1034
+ params: {}
1035
+ };
1036
+ comments.forEach((line) => {
1037
+ const paramMatches = /\s*@param\s([\w|\-]+)([;|-|\s]*)(.*)/.exec(line);
1038
+ if (paramMatches === null) {
1039
+ if (!curParam || line.trim() === "") {
1040
+ curParam = void 0;
1041
+ parsed.text.push(line);
1042
+ } else {
1043
+ parsed.params[curParam].comments.push(line);
1044
+ }
1045
+ return;
1046
+ }
1047
+ if (!("args" in abi))
1048
+ return;
1049
+ const [_full, name, _separator, rest] = paramMatches;
1050
+ const arg = abi.args.find((arg2) => arg2.name === name);
1051
+ if (!arg) {
1052
+ console.debug(`[claridocs]: Unable to find ABI for @param ${name}`);
1053
+ return;
1054
+ }
1055
+ curParam = name;
1056
+ parsed.params[curParam] = {
1057
+ abi: arg,
1058
+ comments: [rest]
1059
+ };
1060
+ });
1061
+ if ("args" in abi) {
1062
+ abi.args.forEach((arg) => {
1063
+ if (!parsed.params[arg.name]) {
1064
+ parsed.params[arg.name] = {
1065
+ abi: arg,
1066
+ comments: []
1067
+ };
1068
+ }
1069
+ });
1070
+ }
1071
+ return parsed;
1072
+ }
1073
+ async function afterDocs(config) {
1074
+ var _a;
1075
+ const command = (_a = config.docs) == null ? void 0 : _a.after;
1076
+ if (!command)
1077
+ return;
1078
+ logger.debug(`Running after docs command: ${command}`);
1079
+ const parts = command.split(" ");
1080
+ const [cmd, ...args2] = parts;
1081
+ return new Promise((resolve3, reject) => {
1082
+ const child = (0, import_child_process2.spawn)(cmd, args2, {
1083
+ cwd: config.cwd,
1084
+ stdio: "inherit"
1085
+ });
1086
+ child.on("error", reject);
1087
+ child.on("exit", (code) => {
1088
+ if (code === 0) {
1089
+ resolve3();
1090
+ } else {
1091
+ reject(new Error(`Command failed with code ${code ?? "unknown"}`));
1092
+ }
1093
+ });
1094
+ });
1095
+ }
1096
+
1097
+ // src/docs/markdown.ts
1098
+ var import_path5 = require("path");
1099
+ var import_transactions2 = require("@stacks/transactions");
1100
+ function generateMarkdown({
1101
+ contract,
1102
+ contractFile,
1103
+ withToc = true
1104
+ }) {
1105
+ const contractName = (0, import_core9.getContractName)(contract.contract_id, false);
1106
+ const doc = createContractDocInfo({
1107
+ contractSrc: contract.source,
1108
+ abi: contract.contract_interface
1109
+ });
1110
+ const functions = doc.functions.map((fn) => markdownFunction(fn, contractFile));
1111
+ const maps = doc.maps.map((map) => markdownMap(map, contractFile));
1112
+ const vars = doc.variables.filter((v) => v.abi.access === "variable").map((v) => markdownVar(v, contractFile));
1113
+ const constants = doc.variables.filter((v) => v.abi.access === "constant").map((v) => markdownVar(v, contractFile));
1114
+ let fileLine = "";
1115
+ if (contractFile) {
1116
+ const fileName = (0, import_path5.basename)(contractFile);
1117
+ fileLine = `
1118
+ [\`${fileName}\`](${contractFile})`;
1119
+ }
1120
+ return `
1121
+ # ${contractName}
1122
+ ${fileLine}
1123
+
1124
+ ${doc.comments.join("\n\n")}
1125
+
1126
+ ${withToc ? markdownTOC(doc) : ""}
1127
+
1128
+ ## Functions
1129
+
1130
+ ${functions.join("\n\n")}
1131
+
1132
+ ## Maps
1133
+
1134
+ ${maps.join("\n\n")}
1135
+
1136
+ ## Variables
1137
+
1138
+ ${vars.join("\n\n")}
1139
+
1140
+ ## Constants
1141
+
1142
+ ${constants.join("\n\n")}
1143
+ `;
1144
+ }
1145
+ function markdownFunction(fn, contractFile) {
1146
+ const params = mdParams(fn);
1147
+ const returnType = (0, import_transactions2.getTypeString)(fn.abi.outputs.type);
1148
+ const paramSigs = fn.abi.args.map((arg) => {
1149
+ return `(${arg.name} ${(0, import_transactions2.getTypeString)(arg.type)})`;
1150
+ });
1151
+ const startLine = fn.startLine + 1;
1152
+ let link = "";
1153
+ if (contractFile) {
1154
+ link = `[View in file](${contractFile}#L${startLine})`;
1155
+ }
1156
+ const source = `<details>
1157
+ <summary>Source code:</summary>
1158
+
1159
+ \`\`\`clarity
1160
+ ${fn.source.join("\n")}
1161
+ \`\`\`
1162
+ </details>
1163
+ `;
1164
+ const sig = `(define-${fn.abi.access.replace("_", "-")} (${fn.abi.name} (${paramSigs.join(" ")}) ${returnType})`;
1165
+ return `### ${fn.abi.name}
1166
+
1167
+ ${link}
1168
+
1169
+ \`${sig}\`
1170
+
1171
+ ${fn.comments.text.join("\n")}
1172
+
1173
+ ${source}
1174
+
1175
+ ${params}`;
1176
+ }
1177
+ function mdParams(fn) {
1178
+ if (fn.abi.args.length === 0)
1179
+ return "";
1180
+ const hasDescription = Object.values(fn.comments.params).some((p) => p.comments.length > 0);
1181
+ const params = Object.values(fn.comments.params).map((p) => markdownParam(p, hasDescription));
1182
+ return `**Parameters:**
1183
+
1184
+ | Name | Type | ${hasDescription ? "Description |" : ""}
1185
+ | --- | --- | ${hasDescription ? "--- |" : ""}
1186
+ ${params.join("\n")}`;
1187
+ }
1188
+ function markdownParam(param, withDescription) {
1189
+ const typeString = (0, import_transactions2.getTypeString)(param.abi.type);
1190
+ const base = `| ${param.abi.name} | ${typeString} |`;
1191
+ if (!withDescription)
1192
+ return base;
1193
+ return `${base} ${param.comments.join(" ")} |`;
1194
+ }
1195
+ function markdownMap(map, contractFile) {
1196
+ const startLine = map.startLine + 1;
1197
+ let link = "";
1198
+ if (contractFile) {
1199
+ link = `[View in file](${contractFile}#L${startLine})`;
1200
+ }
1201
+ return `### ${map.abi.name}
1202
+
1203
+ ${map.comments.text.join("\n")}
1204
+
1205
+ \`\`\`clarity
1206
+ ${map.source.join("\n")}
1207
+ \`\`\`
1208
+
1209
+ ${link}`;
1210
+ }
1211
+ function markdownVar(variable, contractFile) {
1212
+ const startLine = variable.startLine + 1;
1213
+ let link = "";
1214
+ if (contractFile) {
1215
+ link = `[View in file](${contractFile}#L${startLine})`;
1216
+ }
1217
+ const sig = variable.abi.access === "variable" ? (0, import_transactions2.getTypeString)(variable.abi.type) : "";
1218
+ return `### ${variable.abi.name}
1219
+
1220
+ ${sig}
1221
+
1222
+ ${variable.comments.text.join("\n")}
1223
+
1224
+ \`\`\`clarity
1225
+ ${variable.source.join("\n")}
1226
+ \`\`\`
1227
+
1228
+ ${link}`;
1229
+ }
1230
+ function markdownTOC(contract) {
1231
+ const publics = contract.functions.filter((fn) => fn.abi.access === "public");
1232
+ const readOnly = contract.functions.filter((fn) => fn.abi.access === "read_only");
1233
+ const privates = contract.functions.filter((fn) => fn.abi.access === "private");
1234
+ const maps = contract.maps;
1235
+ const constants = contract.variables.filter((v) => v.abi.access === "constant");
1236
+ const vars = contract.variables.filter((v) => v.abi.access === "variable");
1237
+ function tocLine(fn) {
1238
+ const name = fn.abi.name;
1239
+ return `- [\`${name}\`](#${name.toLowerCase().replaceAll("?", "")})`;
1240
+ }
1241
+ return `**Public functions:**
1242
+
1243
+ ${publics.map(tocLine).join("\n")}
1244
+
1245
+ **Read-only functions:**
1246
+
1247
+ ${readOnly.map(tocLine).join("\n")}
1248
+
1249
+ **Private functions:**
1250
+
1251
+ ${privates.map(tocLine).join("\n")}
1252
+
1253
+ **Maps**
1254
+
1255
+ ${maps.map(tocLine).join("\n")}
1256
+
1257
+ **Variables**
1258
+
1259
+ ${vars.map(tocLine).join("\n")}
1260
+
1261
+ **Constants**
1262
+
1263
+ ${constants.map(tocLine).join("\n")}
1264
+ `;
1265
+ }
1266
+ function generateReadme(session, excluded) {
1267
+ const contractLines = [];
1268
+ sortContracts(session.contracts).forEach((contract) => {
1269
+ const name = (0, import_core9.getContractName)(contract.contract_id, false);
1270
+ if (excluded[name])
1271
+ return;
1272
+ const fileName = `${name}.md`;
1273
+ const line = `- [\`${name}\`](${fileName})`;
1274
+ contractLines.push(line);
1275
+ });
1276
+ const fileContents = `# Contracts
1277
+
1278
+ ${contractLines.join("\n")}
1279
+ `;
1280
+ return fileContents;
1281
+ }
1282
+
1283
+ // src/files/docs.ts
1284
+ async function generateDocs({
1285
+ session,
1286
+ config
1287
+ }) {
1288
+ const docs = config.configFile["docs" /* Docs */];
1289
+ const docsBase = docs == null ? void 0 : docs.output;
1290
+ if (!docsBase) {
1291
+ warnNoDocs();
1292
+ return;
1293
+ }
1294
+ const docsPathExt = (0, import_path6.extname)(docsBase);
1295
+ if (docsPathExt) {
1296
+ log.warn(`Docs output path ('${docsBase}') looks like a file - it needs to be a directory.`);
1297
+ }
1298
+ const excluded = Object.fromEntries((docs.exclude || []).map((e) => {
1299
+ return [e, true];
1300
+ }));
1301
+ log.debug(`Generating docs at path \`${docsBase}\``);
1302
+ const docsBaseFolder = config.outputResolve("docs" /* Docs */, "./")[0];
1303
+ const paths = await Promise.all(session.contracts.map(async (contract) => {
1304
+ var _a, _b;
1305
+ const name = (0, import_core10.getContractName)(contract.contract_id, false);
1306
+ if (excluded[name])
1307
+ return null;
1308
+ const docFile = `${name}.md`;
1309
+ const contractPathDef = (_b = (_a = config.clarinet.contracts) == null ? void 0 : _a[name]) == null ? void 0 : _b.path;
1310
+ let contractFile;
1311
+ if (contractPathDef) {
1312
+ const contractPathFull = config.joinFromClarinet(contractPathDef);
1313
+ contractFile = (0, import_path6.relative)(docsBaseFolder, contractPathFull);
1314
+ } else {
1315
+ log.debug(`Couldn't find contract file from Clarinet.toml for contract ${name}`);
1316
+ }
1317
+ const md = generateMarkdown({ contract, contractFile });
1318
+ const path = await config.writeOutput("docs" /* Docs */, md, docFile);
1319
+ return path[0];
1320
+ }));
1321
+ const readme = generateReadme(session, excluded);
1322
+ paths.push((await config.writeOutput("docs" /* Docs */, readme, "README.md"))[0]);
1323
+ await afterDocs(config);
1324
+ }
1325
+ function warnNoDocs() {
1326
+ log.warn(`
1327
+ Clarigen config file doesn't include an output directory for docs.
1328
+
1329
+ To generate docs, specify 'docs.output' in your config file:
1330
+
1331
+ [docs]
1332
+ output = "docs/"
1333
+ `.trimEnd());
1334
+ }
1335
+
1336
+ // src/commands/docs-command.ts
1337
+ var DocsCommand = class extends BaseCommand {
1338
+ cwd = import_clipanion4.Option.String({ required: false });
1339
+ async execute() {
1340
+ this.preexecute();
1341
+ const config = await Config.load(this.cwd);
1342
+ const session = await getSession(config);
1343
+ await generateDocs({
1344
+ session: __spreadProps(__spreadValues({}, session), {
1345
+ variables: []
1346
+ }),
1347
+ config
1348
+ });
1349
+ }
1350
+ };
1351
+ __publicField(DocsCommand, "paths", [["docs"]]);
1352
+ __publicField(DocsCommand, "usage", BaseCommand.Usage({
1353
+ description: "Generate markdown documentation for your Clarity contracts"
1354
+ }));
1355
+
1356
+ // src/commands/init-config-command.ts
1357
+ var import_clipanion5 = require("clipanion");
1358
+ var import_promises6 = require("fs/promises");
1359
+
1360
+ // src/generated/init-config.ts
1361
+ var tomlInit = `
1362
+ # Set to your project's Clarinet config file
1363
+ clarinet = "./Clarinet.toml"
1364
+
1365
+ # Set where you'd like TypeScript types output.
1366
+ # Comment or remove section to skip TypeScript types
1367
+ [types]
1368
+ # \`output\` should be a path to a single file
1369
+ output = "src/clarigen-types.ts"
1370
+
1371
+ # You can also specify multiple output paths:
1372
+ # outputs = [
1373
+ # "src/clarigen-types.ts",
1374
+ # "test/clarigen-types.ts"
1375
+ # ]
1376
+
1377
+ # \`types.after\` - script to run after TypeScript types are generated.
1378
+ # examples:
1379
+ # after = "npm run prettier -w ./src/clarigen-types.ts"
1380
+ # after = "echo 'yay'"
1381
+
1382
+ # Set where you'd like generated contract docs
1383
+ # Generate docs by running \`clarigen docs\`
1384
+ [docs]
1385
+ # \`output\` should be a folder
1386
+ output = "docs"
1387
+
1388
+ # \`docs.after\` - script to run after docs are generated.
1389
+ # examples:
1390
+ # after = "npm run prettier -w ./docs"
1391
+ `;
1392
+
1393
+ // src/commands/init-config-command.ts
1394
+ var InitConfigCommand = class extends BaseCommand {
1395
+ cwd = import_clipanion5.Option.String({ required: false });
1396
+ overwrite = import_clipanion5.Option.Boolean("--overwrite", false, {
1397
+ description: "Overwrite the configuration file if it already exists"
1398
+ });
1399
+ async execute() {
1400
+ this.preexecute();
1401
+ const path = configFilePath(this.cwd);
1402
+ const configExists = await fileExists(path);
1403
+ if (configExists && !this.overwrite) {
1404
+ logger.warn("Configuration file already exists. Use --overwrite to overwrite it.");
1405
+ return 1;
1406
+ }
1407
+ logger.debug(`Writing configuration file to ${path}`);
1408
+ await (0, import_promises6.writeFile)(path, tomlInit, "utf-8");
1409
+ }
1410
+ };
1411
+ __publicField(InitConfigCommand, "paths", [["init-config"]]);
1412
+ __publicField(InitConfigCommand, "usage", {
1413
+ description: "Initialize a Clarigen configuration file"
1414
+ });
1415
+
1416
+ // src/generated/version.ts
1417
+ var version = "2.0.0";
1418
+
1419
+ // src/run-cli.ts
1420
+ var [node, script, ...args] = process.argv;
1421
+ var cli = new import_clipanion6.Cli({
1422
+ binaryLabel: "Clarigen",
1423
+ binaryName: "clarigen",
1424
+ binaryVersion: version
1425
+ });
1426
+ cli.register(import_clipanion6.Builtins.HelpCommand);
1427
+ cli.register(import_clipanion6.Builtins.VersionCommand);
1428
+ cli.register(DefaultCommand);
1429
+ cli.register(DocsCommand);
1430
+ cli.register(InitConfigCommand);
1431
+ cli.register(SessionInfoCommand);
1432
+ async function run() {
1433
+ await cli.runExit(args, import_clipanion6.Cli.defaultContext);
1434
+ }
1435
+ process.on("SIGINT", () => {
1436
+ logger.info("Bye! \u{1F44B}");
1437
+ process.exit();
1438
+ });
1439
+ run().catch(console.error).finally(() => {
1440
+ process.exit();
1441
+ });
1442
+ //# sourceMappingURL=run-cli.cjs.map