@clarigen/cli 1.0.0-next.18 → 1.0.0-next.21

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.
package/dist/index.js CHANGED
@@ -1,105 +1,792 @@
1
- var V=Object.defineProperty,Dt=Object.defineProperties,Vt=Object.getOwnPropertyDescriptor,Ot=Object.getOwnPropertyDescriptors,Lt=Object.getOwnPropertyNames,D=Object.getOwnPropertySymbols;var Q=Object.prototype.hasOwnProperty,ct=Object.prototype.propertyIsEnumerable;var at=(t,e,r)=>e in t?V(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,d=(t,e)=>{for(var r in e||(e={}))Q.call(e,r)&&at(t,r,e[r]);if(D)for(var r of D(e))ct.call(e,r)&&at(t,r,e[r]);return t},w=(t,e)=>Dt(t,Ot(e));var O=(t,e)=>{var r={};for(var n in t)Q.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&D)for(var n of D(t))e.indexOf(n)<0&&ct.call(t,n)&&(r[n]=t[n]);return r};var Mt=(t,e)=>{for(var r in e)V(t,r,{get:e[r],enumerable:!0})},_t=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Lt(e))!Q.call(t,o)&&o!==r&&V(t,o,{get:()=>e[o],enumerable:!(n=Vt(e,o))||n.enumerable});return t};var Bt=t=>_t(V({},"__esModule",{value:!0}),t);var ne={};Mt(ne,{Generate:()=>A,configFileExists:()=>Ct,configFilePath:()=>gt,defaultConfigFile:()=>G,generateIndexFile:()=>rt,generateInterface:()=>zt,generateInterfaceFile:()=>et,generateProjectIndexFile:()=>ot,generateTypesFile:()=>nt,getArgName:()=>B,getConfigFile:()=>yt,getProjectConfig:()=>E,jsTypeFromAbiType:()=>p,makePureTypes:()=>tt,run:()=>kt.run});module.exports=Bt(ne);var kt=require("@oclif/command");var h=require("path"),M=require("fs/promises"),ut=require("fs");var X=require("@ltd/j-toml"),Y=require("path"),Z=require("fs/promises"),L=require("micro-stacks/wallet-sdk"),lt=require("toposort"),ft=require("micro-stacks/crypto");async function Jt(t){let e=(0,Y.resolve)(t,"settings","Devnet.toml"),r=await(0,Z.readFile)(e,{encoding:"utf-8"});return(0,X.parse)(r,1,`
2
- `,!0,{longer:!0})}async function Rt(t){let e=(0,Y.resolve)(t,"Clarinet.toml"),r=await(0,Z.readFile)(e,{encoding:"utf-8"});return(0,X.parse)(r,1,`
3
- `,!0)}async function pt(t,e){let r=await Rt(t),n=e.deployer.address;return Ut(r.contracts).map(a=>({file:r.contracts[a].path.replace(/^contracts\//,""),address:n,name:a}))}function Ut(t){let e=[],r=[];return Object.entries(t).forEach(([o,i])=>{r.push(o),i.depends_on.forEach(a=>e.push([o,a]))}),(0,lt.array)(r,e).reverse()}async function mt(t){let e=await Jt(t),r=await Promise.all(Object.entries(e.accounts).map(async([o,i])=>{let a=await(0,L.generateWallet)(i.mnemonic,"password"),[s]=a.accounts,f=(0,L.getStxAddressFromAccount)(s,ft.StacksNetworkVersion.testnetP2PKH);return[o,w(d({},i),{address:f})]}));return Object.fromEntries(r)}var G={outputDir:"src/clarigen",clarinet:"."};function gt(t){return(0,h.resolve)(t,"clarigen.config.json")}async function Ct(t){try{return await(0,M.access)(t,ut.constants.R_OK),!0}catch{return!1}}async function yt(t){let e=gt(t);if(await Ct(e)){let n=await(0,M.readFile)(e,{encoding:"utf-8"}),o=JSON.parse(n);return d(d({},G),o)}return G}async function E(t){let e=await yt(t),r=(0,h.resolve)(t,e.clarinet||"."),n=await mt(r),o=await pt(r,n),i=(0,h.relative)(process.cwd(),(0,h.join)(e.clarinet,"contracts"));return w(d({},e),{contracts:o,contractsDir:i,accounts:n,clarinet:e.clarinet||"."})}var m=require("micro-stacks/transactions"),_=require("@clarigen/core"),dt=require("reserved-words"),p=(t,e=!1)=>{if((0,m.isClarityAbiPrimitive)(t)){if(t==="uint128")return e?"number | bigint":"bigint";if(t==="int128")return e?"number | bigint":"bigint";if(t==="bool")return"boolean";if(t==="principal")return"string";if(t==="none")return"null";if(t==="trait_reference")return"string";throw new Error(`Unexpected Clarity ABI type primitive: ${JSON.stringify(t)}`)}else{if((0,m.isClarityAbiBuffer)(t))return"Uint8Array";if((0,m.isClarityAbiResponse)(t)){let r=p(t.response.ok),n=p(t.response.error);return`Response<${r}, ${n}>`}else{if((0,m.isClarityAbiOptional)(t))return`${p(t.optional)} | null`;if((0,m.isClarityAbiTuple)(t)){let r=[];return t.tuple.forEach(({name:n,type:o})=>{let i=p(o);r.push(`"${n}": ${i}`)}),`{
4
- ${r.join(`;
5
- `)}
6
- }`}else{if((0,m.isClarityAbiList)(t))return`${p(t.list.type)}[]`;if((0,m.isClarityAbiStringAscii)(t))return"string";if((0,m.isClarityAbiStringUtf8)(t))return"string";if(t==="trait_reference")return"string";throw new Error(`Unexpected Clarity ABI type: ${JSON.stringify(t)}`)}}}};function B(t){let e=(0,_.toCamelCase)(t);return`${(0,dt.check)(e,6)?"_":""}${e}`}var Wt={public:"Public",read_only:"ReadOnly",private:"Private"};function tt(t){let e="";return t.functions.forEach((r,n)=>{let o=`${(0,_.toCamelCase)(r.name)}: `;if(o+=`(${r.args.map(s=>`${B(s.name)}: ${p(s.type,!0)}`).join(", ")}) => `,o+=`ContractCalls.${Wt[r.access]}<`,r.access==="public"){let{type:s}=r.outputs;if(!(0,m.isClarityAbiResponse)(s))throw new Error("Expected response type for public function");let f=p(s.response.ok),l=p(s.response.error);o+=`${f}, ${l}>;`}else o+=`${p(r.outputs.type)}>;`;e+=`${n===0?"":`
7
- `} ${o}`}),t.maps.forEach(r=>{let n=`${(0,_.toCamelCase)(r.name)}: `,o=p(r.key,!0),i=`key: ${o}`,a=p(r.value);n+=`(${i}) => ContractCalls.Map<${o}, ${a}>;`,e+=`
8
- ${n}`}),e}var $t=require("@clarigen/native-bin"),F=require("@clarigen/core"),J=require("path");var zt=async({provider:t,contractFile:e,contractAddress:r,contractName:n})=>{let o=await t.runCommand(["launch",`${r}.${n}`,e,t.dbFilePath,"--output_analysis","--costs","--assets"]);if((0,$t.hasStdErr)(o.stderr))throw new Error(`Error on ${e}:
9
- ${o.stderr}
10
- `);let i=JSON.parse(o.stdout);if(i.error){let{initialization:s}=i.error;if(s!=null&&s.includes(`
11
- Near:
12
- `)){let[f,l]=s.split(`
13
- Near:
14
- `),y="",C=/start_line: (\d+),/.exec(l);throw C&&(y=C[1]),new Error(`Error on ${e}:
15
- ${f}
16
- ${y?`Near line ${y}`:""}
17
- Raw trace:
18
- ${l}
19
- `)}throw new Error(`Error on ${e}:
20
- ${JSON.stringify(i.error,null,2)}
21
- `)}return i.analysis},et=({contractName:t,abi:e})=>{let r=(0,F.toCamelCase)(t,!0),s=e,{clarity_version:n}=s,o=O(s,["clarity_version"]),i=JSON.stringify(o,null,2);return`import { ClarityAbi } from '@clarigen/core';
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 __export = (target, all) => {
37
+ for (var name in all)
38
+ __defProp(target, name, { get: all[name], enumerable: true });
39
+ };
40
+ var __copyProps = (to, from, except, desc) => {
41
+ if (from && typeof from === "object" || typeof from === "function") {
42
+ for (let key of __getOwnPropNames(from))
43
+ if (!__hasOwnProp.call(to, key) && key !== except)
44
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
45
+ }
46
+ return to;
47
+ };
48
+ 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));
49
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
50
+
51
+ // src/index.ts
52
+ var src_exports = {};
53
+ __export(src_exports, {
54
+ Generate: () => Generate,
55
+ configFileExists: () => configFileExists,
56
+ configFilePath: () => configFilePath,
57
+ defaultConfigFile: () => defaultConfigFile,
58
+ generateIndexFile: () => generateIndexFile,
59
+ generateInterfaceFile: () => generateInterfaceFile,
60
+ generateProjectIndexFile: () => generateProjectIndexFile,
61
+ generateTypesFile: () => generateTypesFile,
62
+ getArgName: () => getArgName,
63
+ getConfigFile: () => getConfigFile,
64
+ getProjectConfig: () => getProjectConfig,
65
+ jsTypeFromAbiType: () => jsTypeFromAbiType,
66
+ makePureTypes: () => makePureTypes,
67
+ run: () => import_command2.run
68
+ });
69
+ module.exports = __toCommonJS(src_exports);
70
+ var import_command2 = require("@oclif/command");
71
+
72
+ // src/config.ts
73
+ var import_path2 = require("path");
74
+ var import_promises2 = require("fs/promises");
75
+ var import_fs = require("fs");
76
+
77
+ // src/clarinet-config.ts
78
+ var import_j_toml = require("@ltd/j-toml");
79
+ var import_path = require("path");
80
+ var import_promises = require("fs/promises");
81
+ var import_wallet_sdk = require("micro-stacks/wallet-sdk");
82
+ var import_toposort = require("toposort");
83
+ var import_crypto = require("micro-stacks/crypto");
84
+ async function getClarinetDevConfig(folder) {
85
+ const baseConfigPath = (0, import_path.resolve)(folder, "settings", "Devnet.toml");
86
+ const configContents = await (0, import_promises.readFile)(baseConfigPath, { encoding: "utf-8" });
87
+ const config = (0, import_j_toml.parse)(configContents, 1, "\n", true, {
88
+ longer: true
89
+ });
90
+ return config;
91
+ }
92
+ async function getClarinetConfig(folder) {
93
+ const baseConfigPath = (0, import_path.resolve)(folder, "Clarinet.toml");
94
+ const configContents = await (0, import_promises.readFile)(baseConfigPath, { encoding: "utf-8" });
95
+ const config = (0, import_j_toml.parse)(configContents, 1, "\n", true);
96
+ return config;
97
+ }
98
+ function getContractsFromClarinet(clarinetConfig, accounts) {
99
+ const deployerAddress = accounts.deployer.address;
100
+ const sortedContracts = sortClarinetContracts(clarinetConfig.contracts);
101
+ const contracts = sortedContracts.map((contractName) => {
102
+ const info = clarinetConfig.contracts[contractName];
103
+ const file = info.path.replace(/^contracts\//, "");
104
+ return {
105
+ file,
106
+ address: deployerAddress,
107
+ name: contractName
108
+ };
109
+ });
110
+ return contracts;
111
+ }
112
+ function sortClarinetContracts(contractsConfig) {
113
+ const edges = [];
114
+ const nodes = [];
115
+ Object.entries(contractsConfig).forEach(([contractName, info]) => {
116
+ nodes.push(contractName);
117
+ info.depends_on.forEach((dependency) => edges.push([contractName, dependency]));
118
+ });
119
+ const sorted = (0, import_toposort.array)(nodes, edges).reverse();
120
+ return sorted;
121
+ }
122
+ async function getClarinetAccounts(folder) {
123
+ const devConfig = await getClarinetDevConfig(folder);
124
+ const accountEntries = await Promise.all(Object.entries(devConfig.accounts).map(async ([key, info]) => {
125
+ const wallet = await (0, import_wallet_sdk.generateWallet)(info.mnemonic, "password");
126
+ const [account] = wallet.accounts;
127
+ const address = (0, import_wallet_sdk.getStxAddressFromAccount)(account, import_crypto.StacksNetworkVersion.testnetP2PKH);
128
+ return [
129
+ key,
130
+ __spreadProps(__spreadValues({}, info), {
131
+ address
132
+ })
133
+ ];
134
+ }));
135
+ const accounts = Object.fromEntries(accountEntries);
136
+ return accounts;
137
+ }
138
+
139
+ // src/config.ts
140
+ var defaultConfigFile = {
141
+ outputDir: "src/clarigen",
142
+ clarinet: "."
143
+ };
144
+ function configFilePath(rootPath) {
145
+ return (0, import_path2.resolve)(rootPath, "clarigen.config.json");
146
+ }
147
+ async function configFileExists(configPath) {
148
+ try {
149
+ await (0, import_promises2.access)(configPath, import_fs.constants.R_OK);
150
+ return true;
151
+ } catch (error) {
152
+ return false;
153
+ }
154
+ }
155
+ async function getConfigFile(rootPath) {
156
+ const fullPath = configFilePath(rootPath);
157
+ const exists = await configFileExists(fullPath);
158
+ if (exists) {
159
+ const configContents = await (0, import_promises2.readFile)(fullPath, { encoding: "utf-8" });
160
+ const configFile = JSON.parse(configContents);
161
+ return __spreadValues(__spreadValues({}, defaultConfigFile), configFile);
162
+ }
163
+ return defaultConfigFile;
164
+ }
165
+ async function getProjectConfig(rootPath) {
166
+ var _a, _b;
167
+ const configFile = await getConfigFile(rootPath);
168
+ const clarinetPath = (0, import_path2.resolve)(rootPath, configFile.clarinet);
169
+ const clarinet = await getClarinetConfig(clarinetPath);
170
+ const accounts = await getClarinetAccounts(clarinetPath);
171
+ const contracts = getContractsFromClarinet(clarinet, accounts);
172
+ const contractsDir = (0, import_path2.relative)(process.cwd(), (0, import_path2.join)(configFile.clarinet, "contracts"));
173
+ return __spreadProps(__spreadValues({}, configFile), {
174
+ outputDir: ((_a = clarinet.clarigen) == null ? void 0 : _a.output_dir) || configFile.outputDir,
175
+ docs: ((_b = clarinet.clarigen) == null ? void 0 : _b.docs) || configFile.docs,
176
+ contracts,
177
+ contractsDir,
178
+ accounts,
179
+ clarinet: configFile.clarinet
180
+ });
181
+ }
182
+
183
+ // src/generate/declaration.ts
184
+ var import_transactions = require("micro-stacks/transactions");
185
+ var import_core = require("@clarigen/core");
186
+ var import_reserved_words = require("reserved-words");
187
+ var jsTypeFromAbiType = (val, isArgument = false) => {
188
+ if ((0, import_transactions.isClarityAbiPrimitive)(val)) {
189
+ if (val === "uint128") {
190
+ if (isArgument)
191
+ return "number | bigint";
192
+ return "bigint";
193
+ } else if (val === "int128") {
194
+ if (isArgument)
195
+ return "number | bigint";
196
+ return "bigint";
197
+ } else if (val === "bool") {
198
+ return "boolean";
199
+ } else if (val === "principal") {
200
+ return "string";
201
+ } else if (val === "none") {
202
+ return "null";
203
+ } else if (val === "trait_reference") {
204
+ return "string";
205
+ } else {
206
+ throw new Error(`Unexpected Clarity ABI type primitive: ${JSON.stringify(val)}`);
207
+ }
208
+ } else if ((0, import_transactions.isClarityAbiBuffer)(val)) {
209
+ return "Uint8Array";
210
+ } else if ((0, import_transactions.isClarityAbiResponse)(val)) {
211
+ const ok = jsTypeFromAbiType(val.response.ok);
212
+ const err = jsTypeFromAbiType(val.response.error);
213
+ return `Response<${ok}, ${err}>`;
214
+ } else if ((0, import_transactions.isClarityAbiOptional)(val)) {
215
+ const innerType = jsTypeFromAbiType(val.optional);
216
+ return `${innerType} | null`;
217
+ } else if ((0, import_transactions.isClarityAbiTuple)(val)) {
218
+ const tupleDefs = [];
219
+ val.tuple.forEach(({ name, type }) => {
220
+ const innerType = jsTypeFromAbiType(type);
221
+ tupleDefs.push(`"${name}": ${innerType}`);
222
+ });
223
+ return `{
224
+ ${tupleDefs.join(";\n ")}
225
+ }`;
226
+ } else if ((0, import_transactions.isClarityAbiList)(val)) {
227
+ const innerType = jsTypeFromAbiType(val.list.type);
228
+ return `${innerType}[]`;
229
+ } else if ((0, import_transactions.isClarityAbiStringAscii)(val)) {
230
+ return "string";
231
+ } else if ((0, import_transactions.isClarityAbiStringUtf8)(val)) {
232
+ return "string";
233
+ } else if (val === "trait_reference") {
234
+ return "string";
235
+ } else {
236
+ throw new Error(`Unexpected Clarity ABI type: ${JSON.stringify(val)}`);
237
+ }
238
+ };
239
+ function getArgName(name) {
240
+ const camel = (0, import_core.toCamelCase)(name);
241
+ const prefix = (0, import_reserved_words.check)(camel, 6) ? "_" : "";
242
+ return `${prefix}${camel}`;
243
+ }
244
+ var accessToReturnType = {
245
+ public: "Public",
246
+ read_only: "ReadOnly",
247
+ private: "Private"
248
+ };
249
+ function makePureTypes(abi) {
250
+ let typings = "";
251
+ abi.functions.forEach((func, index) => {
252
+ let functionLine = `${(0, import_core.toCamelCase)(func.name)}: `;
253
+ const args = func.args.map((arg) => {
254
+ return `${getArgName(arg.name)}: ${jsTypeFromAbiType(arg.type, true)}`;
255
+ });
256
+ functionLine += `(${args.join(", ")}) => `;
257
+ const funcType = accessToReturnType[func.access];
258
+ functionLine += `ContractCalls.${funcType}<`;
259
+ if (func.access === "public") {
260
+ const { type } = func.outputs;
261
+ if (!(0, import_transactions.isClarityAbiResponse)(type))
262
+ throw new Error("Expected response type for public function");
263
+ const ok = jsTypeFromAbiType(type.response.ok);
264
+ const err = jsTypeFromAbiType(type.response.error);
265
+ functionLine += `${ok}, ${err}>;`;
266
+ } else {
267
+ const returnType = jsTypeFromAbiType(func.outputs.type);
268
+ functionLine += `${returnType}>;`;
269
+ }
270
+ typings += `${index === 0 ? "" : "\n"} ${functionLine}`;
271
+ });
272
+ abi.maps.forEach((map) => {
273
+ let functionLine = `${(0, import_core.toCamelCase)(map.name)}: `;
274
+ const keyType = jsTypeFromAbiType(map.key, true);
275
+ const arg = `key: ${keyType}`;
276
+ const valType = jsTypeFromAbiType(map.value);
277
+ functionLine += `(${arg}) => ContractCalls.Map<${keyType}, ${valType}>;`;
278
+ typings += `
279
+ ${functionLine}`;
280
+ });
281
+ return typings;
282
+ }
283
+
284
+ // src/generate/files.ts
285
+ var import_core2 = require("@clarigen/core");
286
+ var import_path3 = require("path");
287
+ var generateInterfaceFile = ({
288
+ contractName,
289
+ abi
290
+ }) => {
291
+ const variableName = (0, import_core2.toCamelCase)(contractName, true);
292
+ const _a = abi, { clarity_version } = _a, rest = __objRest(_a, ["clarity_version"]);
293
+ const abiString = JSON.stringify(rest, null, 2);
294
+ const fileContents = `import { ClarityAbi } from '@clarigen/core';
22
295
 
23
296
  // prettier-ignore
24
- export const ${r}Interface: ClarityAbi = ${i};
25
- `},rt=({contractFile:t,contractAddress:e,contractName:r})=>{let n=(0,F.toCamelCase)(r,!0),o=(0,F.toCamelCase)(r),i=`${n}Contract`,a=`${n}Interface`;return`import { pureProxy, Contract } from '@clarigen/core';
26
- import type { ${i} } from './types';
27
- import { ${a} } from './abi';
28
- export type { ${i} } from './types';
29
-
30
- export function ${o}Contract(contractAddress: string, contractName: string) {
31
- return pureProxy<${i}>({
32
- abi: ${a},
297
+ export const ${variableName}Interface: ClarityAbi = ${abiString};
298
+ `;
299
+ return fileContents;
300
+ };
301
+ var generateIndexFile = ({
302
+ contractFile,
303
+ contractAddress,
304
+ contractName
305
+ }) => {
306
+ const contractTitle = (0, import_core2.toCamelCase)(contractName, true);
307
+ const varName = (0, import_core2.toCamelCase)(contractName);
308
+ const contractType = `${contractTitle}Contract`;
309
+ const interfaceVar = `${contractTitle}Interface`;
310
+ const fileContents = `import { pureProxy, Contract } from '@clarigen/core';
311
+ import type { ${contractType} } from './types';
312
+ import { ${interfaceVar} } from './abi';
313
+ export type { ${contractType} } from './types';
314
+
315
+ export function ${varName}Contract(contractAddress: string, contractName: string) {
316
+ return pureProxy<${contractType}>({
317
+ abi: ${interfaceVar},
33
318
  contractAddress,
34
319
  contractName,
35
320
  });
36
321
  }
37
322
 
38
- export const ${o}Info: Contract<${i}> = {
39
- contract: ${o}Contract,
40
- address: '${e}',
41
- contractFile: '${t}',
42
- name: '${r}',
43
- abi: ${a},
323
+ export const ${varName}Info: Contract<${contractType}> = {
324
+ contract: ${varName}Contract,
325
+ address: '${contractAddress}',
326
+ contractFile: '${contractFile}',
327
+ name: '${contractName}',
328
+ abi: ${interfaceVar},
329
+ };
330
+ `;
331
+ return fileContents;
44
332
  };
45
- `},nt=(t,e)=>{let r=(0,F.toCamelCase)(e,!0),n=tt(t);return`import { Response, ContractCalls } from '@clarigen/core';
333
+ var generateTypesFile = (abi, contractName) => {
334
+ const name = (0, import_core2.toCamelCase)(contractName, true);
335
+ const typings = makePureTypes(abi);
336
+ const fileContents = `import { Response, ContractCalls } from '@clarigen/core';
46
337
 
47
338
  // prettier-ignore
48
- export interface ${r}Contract {
49
- ${n}
339
+ export interface ${name}Contract {
340
+ ${typings}
50
341
  }
51
- `},ot=t=>{let e=["import type { ContractInstances } from '@clarigen/core';"],r=[],n=[],o="";"accounts"in t&&(o=`
342
+ `;
343
+ return fileContents;
344
+ };
345
+ var generateProjectIndexFile = (config) => {
346
+ const imports = [
347
+ "import type { ContractInstances } from '@clarigen/core';"
348
+ ];
349
+ const exports = [];
350
+ const contractMap = [];
351
+ let accounts = "";
352
+ if ("accounts" in config) {
353
+ const accountLines = Object.keys(config.accounts).map((key) => {
354
+ const account = config.accounts[key];
355
+ return `"${key}": {
356
+ mnemonic: "${account.mnemonic}",
357
+ balance: ${account.balance.toString()}n,
358
+ address: "${account.address}",
359
+ },`;
360
+ });
361
+ accounts = `
52
362
 
53
363
  // prettier-ignore
54
364
  export const accounts = {
55
- ${Object.keys(t.accounts).map(f=>{let l=t.accounts[f];return`"${f}": {
56
- mnemonic: "${l.mnemonic}",
57
- balance: ${l.balance.toString()}n,
58
- address: "${l.address}",
59
- },`}).join(`
60
- `)}
61
- };`),t.contracts.forEach(s=>{let f=s.name,l=(0,F.toCamelCase)(f),y=`${l}Info`,x=`${(0,F.toCamelCase)(f,!0)}Contract`,C=(0,J.dirname)(s.file),b=`'./${(0,J.join)(C||".",f)}'`,c=`import { ${y} } from ${b};`;e.push(c);let u=`export type { ${x} } from ${b};`;r.push(u);let v=`${l}: ${y},`;n.push(v)});let i=`
365
+ ${accountLines.join("\n ")}
366
+ };`;
367
+ }
368
+ config.contracts.forEach((contract) => {
369
+ const contractName = contract.name;
370
+ const contractVar = (0, import_core2.toCamelCase)(contractName);
371
+ const contractInfo = `${contractVar}Info`;
372
+ const contractInterface = `${(0, import_core2.toCamelCase)(contractName, true)}Contract`;
373
+ const dirName = (0, import_path3.dirname)(contract.file);
374
+ const importPath = `'./${(0, import_path3.join)(dirName || ".", contractName)}'`;
375
+ const _import = `import { ${contractInfo} } from ${importPath};`;
376
+ imports.push(_import);
377
+ const _export = `export type { ${contractInterface} } from ${importPath};`;
378
+ exports.push(_export);
379
+ const map = `${contractVar}: ${contractInfo},`;
380
+ contractMap.push(map);
381
+ });
382
+ const contractsType = `
62
383
  export type Contracts = ContractInstances<typeof contracts>;
63
- `;return`${e.join(`
64
- `)}
65
- ${r.join(`
66
- `)}
67
- ${i}
384
+ `;
385
+ const file = `${imports.join("\n")}
386
+ ${exports.join("\n")}
387
+ ${contractsType}
68
388
  export const contracts = {
69
- ${n.join(`
70
- `)}
71
- };${o}
72
- `};var I=require("@oclif/command");var q=require("@clarigen/native-bin"),g=require("path"),jt=require("fs/promises");var R=require("@clarigen/claridocs"),T=require("fs/promises"),P=require("path");async function bt({contractFile:t,contractName:e,docsPath:r,abi:n,dirName:o}){let i=await(0,T.readFile)(t,{encoding:"utf-8"}),a=(0,R.createContractDocInfo)({contractSrc:i,abi:n}),s=(0,P.resolve)(process.cwd(),r,o||"."),f=(0,P.resolve)(s,`${e}.md`),l=(0,R.generateMarkdown)({contract:a,contractFile:(0,P.relative)(s,t),contractName:e,abi:n});await(0,T.mkdir)(s,{recursive:!0}),await(0,T.writeFile)(f,l)}async function xt(t){if(!t.docs)return;let r=`# Contracts
73
-
74
- ${t.contracts.map(o=>{let i=o.file.replace(".clar",".md");return`- [\`${o.name}\`](${i})`}).join(`
75
- `)}
76
- `,n=(0,P.resolve)(process.cwd(),t.docs,"README.md");await(0,T.writeFile)(n,r)}var N=require("@clarigen/core");var W=require("path"),wt=require("fs/promises"),z=require("util");function Kt(t){let{abi:e}=t,r=[],b=e,{functions:n,variables:o,maps:i}=b,a=O(b,["functions","variables","maps"]);n.forEach(c=>{let u=`${(0,N.toCamelCase)(c.name)}: `,S=`[${c.args.map(st=>`${B(st.name)}: ${p(st.type,!0)}`).join(", ")}]`;u+=JSON.stringify(c);let St=p(c.outputs.type);u+=` as TypedAbiFunction<${S}, ${St}>`,r.push(u)});let s=t.variables.map(c=>{let u=`${(0,N.toCamelCase)(c.name)}: `,v=p(c.type);return u+=`${(0,z.inspect)(c,!1,null,!1)} as TypedAbiVariable<${v}>`,u}),l=t.variables.filter(c=>c.access==="constant").map(c=>`"${(0,N.toCamelCase)(c.name)}": ${Ht(c.defaultValue)}`),y=i.map(c=>{let u=`${(0,N.toCamelCase)(c.name)}: `,v=p(c.key),S=p(c.value);return u+=JSON.stringify(c),u+=` as TypedAbiMap<${v}, ${S}>`,u}),x=JSON.stringify(a),C=(0,W.relative)(process.cwd(),t.contractFile);return`{
77
- ${U("functions",r)}
78
- ${U("variables",s)}
79
- ${U("maps",y)}
80
- ${U("constants",l)}
81
- ${x.slice(1,-1)},
82
- contractName: '${t.contractName}',
83
- contractFile: '${C}',
84
- }`}async function At(t,e){let r=e.map(a=>{let s=Kt(a);return`${(0,N.toCamelCase)(a.contractName)}: ${s}`}),n=await Qt(),o=qt(t);return`
85
- ${n}
86
-
87
- export const contracts: Record<string, TypedAbi> = {
88
- ${r.join(`,
89
- `)}
389
+ ${contractMap.join("\n ")}
390
+ };${accounts}
391
+ `;
392
+ return file;
393
+ };
394
+
395
+ // src/commands/index.ts
396
+ var import_command = require("@oclif/command");
397
+
398
+ // src/utils.ts
399
+ var import_native_bin2 = require("@clarigen/native-bin");
400
+ var import_path7 = require("path");
401
+ var import_promises6 = require("fs/promises");
402
+
403
+ // src/docs.ts
404
+ var import_claridocs = require("@clarigen/claridocs");
405
+ var import_promises3 = require("fs/promises");
406
+ var import_path4 = require("path");
407
+ async function generateMarkdownDoc({
408
+ contractFile,
409
+ contractName,
410
+ docsPath,
411
+ abi,
412
+ dirName
413
+ }) {
414
+ const contractSrc = await (0, import_promises3.readFile)(contractFile, { encoding: "utf-8" });
415
+ const docs = (0, import_claridocs.createContractDocInfo)({ contractSrc, abi });
416
+ const folder = (0, import_path4.resolve)(process.cwd(), docsPath, dirName || ".");
417
+ const filePath = (0, import_path4.resolve)(folder, `${contractName}.md`);
418
+ const md = (0, import_claridocs.generateMarkdown)({
419
+ contract: docs,
420
+ contractFile: (0, import_path4.relative)(folder, contractFile),
421
+ contractName,
422
+ abi
423
+ });
424
+ await (0, import_promises3.mkdir)(folder, { recursive: true });
425
+ await (0, import_promises3.writeFile)(filePath, md);
426
+ }
427
+ async function generateDocsIndex(configFile) {
428
+ if (!configFile.docs)
429
+ return;
430
+ const contractLines = configFile.contracts.map((contract) => {
431
+ const fileName = contract.file.replace(".clar", ".md");
432
+ return `- [\`${contract.name}\`](${fileName})`;
433
+ });
434
+ const fileContents = `# Contracts
435
+
436
+ ${contractLines.join("\n")}
437
+ `;
438
+ const filepath = (0, import_path4.resolve)(process.cwd(), configFile.docs, "README.md");
439
+ await (0, import_promises3.writeFile)(filepath, fileContents);
440
+ }
441
+
442
+ // src/generate/single.ts
443
+ var import_core3 = require("@clarigen/core");
444
+ var import_path5 = require("path");
445
+ var import_promises4 = require("fs/promises");
446
+ var import_util = require("util");
447
+ function generateContractMeta(contract) {
448
+ const { abi } = contract;
449
+ const functionLines = [];
450
+ const _a = abi, { functions, variables, maps } = _a, rest = __objRest(_a, ["functions", "variables", "maps"]);
451
+ functions.forEach((func) => {
452
+ let functionLine = `${(0, import_core3.toCamelCase)(func.name)}: `;
453
+ const args = func.args.map((arg) => {
454
+ return `${getArgName(arg.name)}: ${jsTypeFromAbiType(arg.type, true)}`;
455
+ });
456
+ const argsTuple = `[${args.join(", ")}]`;
457
+ const funcDef = JSON.stringify(func);
458
+ functionLine += funcDef;
459
+ const retType = jsTypeFromAbiType(func.outputs.type);
460
+ functionLine += ` as TypedAbiFunction<${argsTuple}, ${retType}>`;
461
+ functionLines.push(functionLine);
462
+ });
463
+ const variableLines = contract.variables.map((v) => {
464
+ let varLine = `${(0, import_core3.toCamelCase)(v.name)}: `;
465
+ const type = jsTypeFromAbiType(v.type);
466
+ const varJSON = serialize(v);
467
+ varLine += `${varJSON} as TypedAbiVariable<${type}>`;
468
+ return varLine;
469
+ });
470
+ const constants2 = contract.variables.filter((v) => v.access === "constant");
471
+ const constantLines = constants2.map((constant) => {
472
+ return `"${(0, import_core3.toCamelCase)(constant.name)}": ${serialize(constant.defaultValue)}`;
473
+ });
474
+ const mapLines = maps.map((map) => {
475
+ let mapLine = `${(0, import_core3.toCamelCase)(map.name)}: `;
476
+ const keyType = jsTypeFromAbiType(map.key);
477
+ const valType = jsTypeFromAbiType(map.value);
478
+ mapLine += JSON.stringify(map);
479
+ mapLine += ` as TypedAbiMap<${keyType}, ${valType}>`;
480
+ return mapLine;
481
+ });
482
+ const otherAbi = JSON.stringify(rest);
483
+ const contractFile = (0, import_path5.relative)(process.cwd(), contract.contractFile);
484
+ return `{
485
+ ${serializeLines("functions", functionLines)}
486
+ ${serializeLines("variables", variableLines)}
487
+ ${serializeLines("maps", mapLines)}
488
+ ${serializeLines("constants", constantLines)}
489
+ ${otherAbi.slice(1, -1)},
490
+ contractName: '${contract.contractName}',
491
+ contractFile: '${contractFile}',
492
+ }`;
493
+ }
494
+ async function generateSingleFile(config, contracts) {
495
+ const contractDefs = contracts.map((contract) => {
496
+ const meta = generateContractMeta(contract);
497
+ const keyName = (0, import_core3.toCamelCase)(contract.contractName);
498
+ return `${keyName}: ${meta}`;
499
+ });
500
+ const types = await getSingleTypes();
501
+ const accounts = generateAccounts(config);
502
+ const file = `
503
+ ${types}
504
+
505
+ export const contracts = {
506
+ ${contractDefs.join(",\n")}
90
507
  } as const;
91
508
 
92
- ${o}
93
- `}function qt(t){let e="";return"accounts"in t&&(e=`export const accounts = {
94
- ${Object.keys(t.accounts).map(n=>{let o=t.accounts[n];return`"${n}": {
95
- mnemonic: "${o.mnemonic}",
96
- balance: ${o.balance.toString()}n,
97
- address: "${o.address}",
98
- },`}).join(`
99
- `)}
100
- } as const;`),e}Uint8Array.prototype[z.inspect.custom]=function(){return`Uint8Array.from([${this.join(",")}])`};function Ht(t){return(0,z.inspect)(t,!1,null,!1)}function U(t,e){return`"${t}": {
101
- ${e.join(`,
102
- `)}
103
- },`}async function Qt(){let t=(0,W.resolve)(__dirname,"../../../core/src/abi-types.ts");return await(0,wt.readFile)(t,{encoding:"utf-8"})}var ht=require("fs/promises"),Ft=require("path"),K=require("prettier"),Xt={printWidth:80,semi:!0,singleQuote:!0,trailingComma:"es5"};async function Yt(){try{let t=await(0,K.resolveConfig)(process.cwd());if(t)return t}catch{}return Xt}async function Zt(t,e){try{let r=(0,Ft.basename)(e),n=await Yt();return(0,K.format)(t,w(d({},n),{filepath:r}))}catch{}return t}async function j(t,e){let r=await Zt(e,t);await(0,ht.writeFile)(t,r)}var Tt=require("@clarigen/core"),vt=require("@clarigen/native-bin"),Pt=require("micro-stacks/clarity");async function Nt({abi:t,contractIdentifier:e,provider:r}){let n=t.variables.map(i=>Gt({variable:i,provider:r,contractIdentifier:e}));return await Promise.all(n)}async function Gt({contractIdentifier:t,variable:e,provider:r}){let n=te(e),o=await(0,vt.evalRaw)({contractAddress:t,code:n,provider:r}),i=(0,Pt.hexToCV)(o.output_serialized),a=(0,Tt.cvToValue)(i,!0);return w(d({},e),{defaultValue:a})}function te(t){let{access:e}=t;return e==="variable"?`(var-get ${t.name})`:t.name}var ee=async({contractFile:t,outputFolder:e,provider:r,contractAddress:n,dirName:o,contractName:i,docsPath:a})=>{let s=(0,g.resolve)(process.cwd(),t),f=`${n}.${i}`,l=await(0,q.deployContract)({contractIdentifier:f,contractFilePath:s,provider:r}),y=await Nt({abi:l,contractIdentifier:f,provider:r}),x=nt(l,i),C=rt({contractFile:(0,g.relative)(process.cwd(),s),contractAddress:n,contractName:i}),b=et({contractName:i,abi:l});typeof a<"u"&&await bt({contractFile:s,contractName:i,abi:l,docsPath:a,dirName:o});let c=(0,g.resolve)(e,o||".",i);return await(0,jt.mkdir)(c,{recursive:!0}),await j((0,g.resolve)(c,"abi.ts"),b),await j((0,g.resolve)(c,"index.ts"),C),await j((0,g.resolve)(c,"types.ts"),x),{abi:l,contractFile:s,contractName:i,dirName:o,contractAddress:n,variables:y}},H=async t=>{let e=await E(t),{contractsDir:r,outputDir:n,contracts:o}=e,i=(0,g.resolve)(t,n),a=await(0,q.createClarityBin)(),s=[];for(let C of o){let b=(0,g.resolve)(t,r,C.file),c=(0,g.dirname)(C.file),u=await ee({contractFile:b,outputFolder:i,provider:a,contractAddress:C.address,dirName:c,contractName:C.name,docsPath:e.docs});s.push(u)}let f=ot(e);await xt(e);let l=(0,g.resolve)(i,"index.ts");await j(l,f);let y=await At(e,s),x=(0,g.resolve)(i,"single.ts");await j(x,y)};var Et=require("chokidar"),It=require("path"),k=require("chalk"),re=require("ora"),it=class extends I.Command{async run(){let{flags:e}=this.parse(it),r=process.cwd();if(e.watch){let n=re("Generating files").start(),{contractsDir:o}=await E(r),i=(0,Et.watch)([o],{cwd:r});try{await H(r),n.succeed("Finished generating files. Watching for changes.")}catch(a){n.fail(`Error generating files.
104
- ${a.message}`)}i.on("change",async a=>{let s=(0,It.basename)(a);n.clear(),n.start(`Change detected for ${(0,k.green)(s)}, generating.`);try{await H(r),n.succeed(`Finished generating files for ${(0,k.green)(s)}. Watching for changes.`)}catch(f){let l=f.message;n.fail(`Error after saving ${(0,k.red)(s)}.
105
- ${l}`)}}),process.on("SIGINT",async()=>{await i.close(),process.exit()})}else await H(r)}},A=it;A.description="Generate project files",A.strict=!0,A.hidden=!1,A.flags={help:I.flags.help({char:"h"}),watch:I.flags.boolean({char:"w",description:"Watch for changes to your contracts"})},A.args=[];0&&(module.exports={Generate,configFileExists,configFilePath,defaultConfigFile,generateIndexFile,generateInterface,generateInterfaceFile,generateProjectIndexFile,generateTypesFile,getArgName,getConfigFile,getProjectConfig,jsTypeFromAbiType,makePureTypes,run});
509
+ ${accounts}
510
+ `;
511
+ return file;
512
+ }
513
+ function generateAccounts(config) {
514
+ let accounts = "";
515
+ if ("accounts" in config) {
516
+ const accountLines = Object.keys(config.accounts).map((key) => {
517
+ const account = config.accounts[key];
518
+ return `"${key}": {
519
+ mnemonic: "${account.mnemonic}",
520
+ balance: ${account.balance.toString()}n,
521
+ address: "${account.address}",
522
+ },`;
523
+ });
524
+ accounts = `export const accounts = {
525
+ ${accountLines.join("\n ")}
526
+ } as const;`;
527
+ }
528
+ return accounts;
529
+ }
530
+ Uint8Array.prototype[import_util.inspect.custom] = function() {
531
+ return `Uint8Array.from([${this.join(",")}])`;
532
+ };
533
+ function serialize(obj) {
534
+ return (0, import_util.inspect)(obj, {
535
+ showHidden: false,
536
+ maxArrayLength: null,
537
+ maxStringLength: null,
538
+ depth: null,
539
+ colors: false
540
+ });
541
+ }
542
+ function serializeLines(key, lines) {
543
+ return `"${key}": {
544
+ ${lines.join(",\n ")}
545
+ },`;
546
+ }
547
+ async function getSingleTypes() {
548
+ const typesPath = (0, import_path5.resolve)(__dirname, "../../dist/abi-types.ts.txt");
549
+ const typesFile = await (0, import_promises4.readFile)(typesPath, { encoding: "utf-8" });
550
+ return typesFile;
551
+ }
552
+
553
+ // src/writer.ts
554
+ var import_promises5 = require("fs/promises");
555
+ var import_path6 = require("path");
556
+ var import_prettier = require("prettier");
557
+ var defaultPrettierConfig = {
558
+ printWidth: 80,
559
+ semi: true,
560
+ singleQuote: true,
561
+ trailingComma: "es5"
562
+ };
563
+ async function resolvePrettierConfig() {
564
+ try {
565
+ const local = await (0, import_prettier.resolveConfig)(process.cwd());
566
+ if (local)
567
+ return local;
568
+ } catch (error) {
569
+ }
570
+ return defaultPrettierConfig;
571
+ }
572
+ async function formatFile(contents, path) {
573
+ try {
574
+ const fileName = (0, import_path6.basename)(path);
575
+ const config = await resolvePrettierConfig();
576
+ const formatted = (0, import_prettier.format)(contents, __spreadProps(__spreadValues({}, config), {
577
+ filepath: fileName
578
+ }));
579
+ return formatted;
580
+ } catch (error) {
581
+ }
582
+ return contents;
583
+ }
584
+ async function writeFile2(path, contents) {
585
+ const formatted = await formatFile(contents, path);
586
+ await (0, import_promises5.writeFile)(path, formatted);
587
+ }
588
+
589
+ // src/generate/vars.ts
590
+ var import_core4 = require("@clarigen/core");
591
+ var import_native_bin = require("@clarigen/native-bin");
592
+ var import_clarity = require("micro-stacks/clarity");
593
+ async function getVariables({
594
+ abi,
595
+ contractIdentifier,
596
+ provider
597
+ }) {
598
+ const variableTransforms = abi.variables.map((variable) => {
599
+ return evalVariable({
600
+ variable,
601
+ provider,
602
+ contractIdentifier
603
+ });
604
+ });
605
+ const variables = await Promise.all(variableTransforms);
606
+ return variables;
607
+ }
608
+ async function evalVariable({
609
+ contractIdentifier,
610
+ variable,
611
+ provider
612
+ }) {
613
+ const code = getEvalCode(variable);
614
+ const result = await (0, import_native_bin.evalRaw)({
615
+ contractAddress: contractIdentifier,
616
+ code,
617
+ provider
618
+ });
619
+ const resultCV = (0, import_clarity.hexToCV)(result.output_serialized);
620
+ const value = (0, import_core4.cvToValue)(resultCV, true);
621
+ return __spreadProps(__spreadValues({}, variable), {
622
+ defaultValue: value
623
+ });
624
+ }
625
+ function getEvalCode(variable) {
626
+ const { access: access2 } = variable;
627
+ if (access2 === "variable") {
628
+ return `(var-get ${variable.name})`;
629
+ }
630
+ return variable.name;
631
+ }
632
+
633
+ // src/utils.ts
634
+ var generateFilesForContract = async ({
635
+ contractFile: _contractFile,
636
+ outputFolder,
637
+ provider,
638
+ contractAddress,
639
+ dirName,
640
+ contractName,
641
+ docsPath
642
+ }) => {
643
+ const contractFile = (0, import_path7.resolve)(process.cwd(), _contractFile);
644
+ const contractIdentifier = `${contractAddress}.${contractName}`;
645
+ const abi = await (0, import_native_bin2.deployContract)({
646
+ contractIdentifier,
647
+ contractFilePath: contractFile,
648
+ provider
649
+ });
650
+ const variables = await getVariables({
651
+ abi,
652
+ contractIdentifier,
653
+ provider
654
+ });
655
+ const typesFile = generateTypesFile(abi, contractName);
656
+ const indexFile = generateIndexFile({
657
+ contractFile: (0, import_path7.relative)(process.cwd(), contractFile),
658
+ contractAddress,
659
+ contractName
660
+ });
661
+ const abiFile = generateInterfaceFile({ contractName, abi });
662
+ if (typeof docsPath !== "undefined") {
663
+ await generateMarkdownDoc({
664
+ contractFile,
665
+ contractName,
666
+ abi,
667
+ docsPath,
668
+ dirName
669
+ });
670
+ }
671
+ const outputPath = (0, import_path7.resolve)(outputFolder, dirName || ".", contractName);
672
+ await (0, import_promises6.mkdir)(outputPath, { recursive: true });
673
+ await writeFile2((0, import_path7.resolve)(outputPath, "abi.ts"), abiFile);
674
+ await writeFile2((0, import_path7.resolve)(outputPath, "index.ts"), indexFile);
675
+ await writeFile2((0, import_path7.resolve)(outputPath, "types.ts"), typesFile);
676
+ return {
677
+ abi,
678
+ contractFile,
679
+ contractName,
680
+ dirName,
681
+ contractAddress,
682
+ variables
683
+ };
684
+ };
685
+ var generateProject = async (projectPath) => {
686
+ const configFile = await getProjectConfig(projectPath);
687
+ const { contractsDir, outputDir, contracts } = configFile;
688
+ const outputFolder = (0, import_path7.resolve)(projectPath, outputDir);
689
+ const provider = await (0, import_native_bin2.createClarityBin)();
690
+ const metas = [];
691
+ for (const contract of contracts) {
692
+ const contractFile = (0, import_path7.resolve)(projectPath, contractsDir, contract.file);
693
+ const dirName = (0, import_path7.dirname)(contract.file);
694
+ const meta = await generateFilesForContract({
695
+ contractFile,
696
+ outputFolder,
697
+ provider,
698
+ contractAddress: contract.address,
699
+ dirName,
700
+ contractName: contract.name,
701
+ docsPath: configFile.docs
702
+ });
703
+ metas.push(meta);
704
+ }
705
+ const indexFile = generateProjectIndexFile(configFile);
706
+ await generateDocsIndex(configFile);
707
+ const indexPath = (0, import_path7.resolve)(outputFolder, "index.ts");
708
+ await writeFile2(indexPath, indexFile);
709
+ const singleFile = await generateSingleFile(configFile, metas);
710
+ const singlePath = (0, import_path7.resolve)(outputFolder, "single.ts");
711
+ await writeFile2(singlePath, singleFile);
712
+ };
713
+
714
+ // src/commands/index.ts
715
+ var import_chokidar = require("chokidar");
716
+ var import_path8 = require("path");
717
+ var import_chalk = require("chalk");
718
+ var import_ora = __toESM(require("ora"));
719
+ var _Generate = class extends import_command.Command {
720
+ async run() {
721
+ const { flags: flags2 } = this.parse(_Generate);
722
+ const cwd = process.cwd();
723
+ if (flags2.watch) {
724
+ const spinner = (0, import_ora.default)("Generating files").start();
725
+ const { contractsDir } = await getProjectConfig(cwd);
726
+ const watcher = (0, import_chokidar.watch)([contractsDir], {
727
+ cwd
728
+ });
729
+ try {
730
+ await generateProject(cwd);
731
+ spinner.succeed(`Finished generating files. Watching for changes.`);
732
+ } catch (error) {
733
+ spinner.fail(`Error generating files.
734
+ ${String(error.message)}`);
735
+ }
736
+ watcher.on("change", (path) => {
737
+ const cb = async () => {
738
+ const file = (0, import_path8.basename)(path);
739
+ spinner.clear();
740
+ spinner.start(`Change detected for ${(0, import_chalk.green)(file)}, generating.`);
741
+ try {
742
+ await generateProject(cwd);
743
+ spinner.succeed(`Finished generating files for ${(0, import_chalk.green)(file)}. Watching for changes.`);
744
+ } catch (error) {
745
+ const msg = error.message;
746
+ spinner.fail(`Error after saving ${(0, import_chalk.red)(file)}.
747
+ ${msg}`);
748
+ }
749
+ };
750
+ void cb();
751
+ });
752
+ process.on("SIGINT", () => {
753
+ async function cb() {
754
+ await watcher.close();
755
+ process.exit();
756
+ }
757
+ void cb();
758
+ });
759
+ } else {
760
+ await generateProject(cwd);
761
+ }
762
+ }
763
+ };
764
+ var Generate = _Generate;
765
+ Generate.description = `Generate project files`;
766
+ Generate.strict = true;
767
+ Generate.hidden = false;
768
+ Generate.flags = {
769
+ help: import_command.flags.help({ char: "h" }),
770
+ watch: import_command.flags.boolean({
771
+ char: "w",
772
+ description: "Watch for changes to your contracts"
773
+ })
774
+ };
775
+ Generate.args = [];
776
+ // Annotate the CommonJS export names for ESM import in node:
777
+ 0 && (module.exports = {
778
+ Generate,
779
+ configFileExists,
780
+ configFilePath,
781
+ defaultConfigFile,
782
+ generateIndexFile,
783
+ generateInterfaceFile,
784
+ generateProjectIndexFile,
785
+ generateTypesFile,
786
+ getArgName,
787
+ getConfigFile,
788
+ getProjectConfig,
789
+ jsTypeFromAbiType,
790
+ makePureTypes,
791
+ run
792
+ });