@taqueria/plugin-contract-types 0.0.0-pr-91-a8fa7172

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/Readme.md +212 -0
  2. package/example/contracts/example-contract-1.tz +1409 -0
  3. package/example/contracts/example-contract-2.tz +798 -0
  4. package/example/contracts/example-contract-3.json +7080 -0
  5. package/example/contracts/example-contract-4.tz +1374 -0
  6. package/example/contracts/example-contract-5.tz +1424 -0
  7. package/example/contracts/example-contract-6.tz +675 -0
  8. package/example/contracts/example-contract-7.tz +384 -0
  9. package/example/contracts/example-contract-8.tz +28 -0
  10. package/example/contracts/example-contract-9.tz +1010 -0
  11. package/example/example-usage-type-utilities.ts +35 -0
  12. package/example/example-usage.ts +410 -0
  13. package/example/types-file/example-contract-1.code.ts +6 -0
  14. package/example/types-file/example-contract-1.types.ts +87 -0
  15. package/example/types-file/example-contract-2.code.ts +6 -0
  16. package/example/types-file/example-contract-2.types.ts +122 -0
  17. package/example/types-file/example-contract-4.code.ts +6 -0
  18. package/example/types-file/example-contract-4.types.ts +97 -0
  19. package/example/types-file/example-contract-5.code.ts +6 -0
  20. package/example/types-file/example-contract-5.types.ts +173 -0
  21. package/example/types-file/example-contract-6.code.ts +6 -0
  22. package/example/types-file/example-contract-6.types.ts +122 -0
  23. package/example/types-file/example-contract-7.code.ts +6 -0
  24. package/example/types-file/example-contract-7.types.ts +78 -0
  25. package/example/types-file/example-contract-8.code.ts +6 -0
  26. package/example/types-file/example-contract-8.types.ts +86 -0
  27. package/example/types-file/example-contract-9.code.ts +6 -0
  28. package/example/types-file/example-contract-9.types.ts +29 -0
  29. package/example/types-file/type-aliases.ts +81 -0
  30. package/example/types-file/type-utils.ts +36 -0
  31. package/index.js +969 -0
  32. package/index.js.map +1 -0
  33. package/index.ts +32 -0
  34. package/package.json +55 -0
  35. package/run.ts +3 -0
  36. package/src/cli-process.ts +111 -0
  37. package/src/cli.ts +34 -0
  38. package/src/generator/common.ts +21 -0
  39. package/src/generator/contract-name.ts +6 -0
  40. package/src/generator/contract-parser.ts +358 -0
  41. package/src/generator/process.ts +66 -0
  42. package/src/generator/schema-output.ts +54 -0
  43. package/src/generator/typescript-output.ts +239 -0
  44. package/src/taquito-contract-type-generator.ts +4 -0
  45. package/src/type-aliases-file-content.ts +83 -0
  46. package/src/type-aliases.ts +80 -0
  47. package/src/type-utils-file-content.ts +38 -0
  48. package/src/type-utils.ts +35 -0
  49. package/tasks.ts +127 -0
  50. package/test/generator.spec.ts +69 -0
  51. package/tsconfig.json +13 -0
package/index.js ADDED
@@ -0,0 +1,969 @@
1
+ var $3ymtt$taquerianodesdk = require("@taqueria/node-sdk");
2
+ var $3ymtt$fastglob = require("fast-glob");
3
+ var $3ymtt$path = require("path");
4
+ var $3ymtt$fs = require("fs");
5
+ var $3ymtt$util = require("util");
6
+ var $3ymtt$taquitomichelcodec = require("@taquito/michel-codec");
7
+
8
+ function $parcel$interopDefault(a) {
9
+ return a && a.__esModule ? a.default : a;
10
+ }
11
+
12
+
13
+
14
+
15
+
16
+
17
+ const $3f5c875567479895$export$bd8d1d28710832a7 = (text)=>text.replace(/[^A-Za-z0-9]/g, '_').split("_").filter((x)=>x
18
+ ).map((x)=>x[0].toUpperCase() + x.substring(1)
19
+ ).join('')
20
+ ;
21
+
22
+
23
+
24
+ class $901f5cf476ef87a5$export$d214d56e7a53a664 {
25
+ constructor(message, data){
26
+ this.message = message;
27
+ this.data = data;
28
+ this.name = `GenerateApiError`;
29
+ console.error(`❌ GenerateApiError: ${message}`, data);
30
+ }
31
+ }
32
+ const $901f5cf476ef87a5$export$16bf6fe03653420f = (value, message)=>{
33
+ console.error(message, {
34
+ value: value
35
+ });
36
+ };
37
+ const $901f5cf476ef87a5$export$37679993c4e6bc41 = (out, x)=>{
38
+ out.push(...x);
39
+ return out;
40
+ } // const reduceFlatMapTest = () => {
41
+ // const items = [['a'], ['b']];
42
+ // const itemsFlat = items.reduce(reduceFlatMap);
43
+ // };
44
+ ;
45
+
46
+
47
+
48
+ const $b95e97a0bb3bf047$var$toDebugSource = (node)=>{
49
+ return JSON.stringify(node);
50
+ };
51
+ const $b95e97a0bb3bf047$export$cc65da7b09dcddd7 = (storage)=>{
52
+ const fields = storage.args.map((x)=>$b95e97a0bb3bf047$var$visitVar(x)
53
+ ).reduce($901f5cf476ef87a5$export$37679993c4e6bc41, []);
54
+ const fieldsSimple = fields.length === 1 && !fields[0].name && fields[0].type.kind === 'object' ? fields[0].type.fields : fields;
55
+ return {
56
+ storage: {
57
+ kind: `object`,
58
+ raw: storage,
59
+ fields: fieldsSimple
60
+ }
61
+ };
62
+ };
63
+ const $b95e97a0bb3bf047$export$5c00959a6ba200c1 = (parameter)=>{
64
+ return {
65
+ methods: parameter.args.map((x)=>$b95e97a0bb3bf047$var$visitContractParameterEndpoint(x)
66
+ ).reduce($901f5cf476ef87a5$export$37679993c4e6bc41, [])
67
+ };
68
+ };
69
+ const $b95e97a0bb3bf047$var$visitContractParameterEndpoint = (node)=>{
70
+ // console.log('visitContractParameterEndpoint', { node });
71
+ // Sub endpoints (i.e. admin endpoints that are imported)
72
+ if (node.prim === `or`) return node.args.map((x)=>$b95e97a0bb3bf047$var$visitContractParameterEndpoint(x)
73
+ ).reduce($901f5cf476ef87a5$export$37679993c4e6bc41, []);
74
+ // Sub endpoints as a list with a single or (i.e. admin endpoints that are imported)
75
+ if (node.prim === `list` && node.args.length === 1 && node.args[0]?.prim === `or`) return node.args.map((x)=>$b95e97a0bb3bf047$var$visitContractParameterEndpoint(x)
76
+ ).reduce($901f5cf476ef87a5$export$37679993c4e6bc41, []);
77
+ const nameRaw = node.annots?.[0];
78
+ const name = nameRaw?.startsWith('%') ? nameRaw.substr(1) : null;
79
+ if (!name) {
80
+ console.warn(`Unknown method: ${node.prim}`, {
81
+ node: node,
82
+ args: node.args
83
+ });
84
+ return [];
85
+ }
86
+ const nodeType = $b95e97a0bb3bf047$var$visitType(node, {
87
+ ignorePairName: node.prim === 'pair'
88
+ });
89
+ // Method args are usually objects
90
+ if (nodeType.kind === 'object') return [
91
+ {
92
+ name: name,
93
+ args: nodeType.fields
94
+ }
95
+ ];
96
+ // Simple methods can have a single unnamed argument
97
+ return [
98
+ {
99
+ name: name,
100
+ args: [
101
+ {
102
+ type: nodeType
103
+ }
104
+ ]
105
+ }
106
+ ];
107
+ };
108
+ const $b95e97a0bb3bf047$var$visitVar = (node)=>{
109
+ const name = `annots` in node && node.annots?.length === 1 ? node.annots[0].substr(1) : undefined;
110
+ const type = $b95e97a0bb3bf047$var$visitType(node);
111
+ return [
112
+ {
113
+ name: name,
114
+ type: type
115
+ }
116
+ ];
117
+ };
118
+ const $b95e97a0bb3bf047$var$visitType = (node, options)=>{
119
+ // console.log('visitType', { node });
120
+ // const debug_source = toDebugSource(node);
121
+ // if (typeof node === `string`) {
122
+ // return { kind: `value`, raw: node, value: node, typescriptType: `string` };
123
+ // }
124
+ if (!(`prim` in node)) {
125
+ // Unknown
126
+ console.error(`visitType no prim`, {
127
+ node: node
128
+ });
129
+ return {
130
+ kind: `unknown`,
131
+ raw: node
132
+ };
133
+ }
134
+ // Union
135
+ if (node.prim === `or`) {
136
+ const unionVars = node.args.map((x)=>$b95e97a0bb3bf047$var$visitVar(x)
137
+ ).reduce($901f5cf476ef87a5$export$37679993c4e6bc41, []).map((x)=>x
138
+ );
139
+ // Flatten with child unions
140
+ const union = unionVars.map((x)=>!x.name && x.type.kind === 'union' ? x.type.union : [
141
+ x
142
+ ]
143
+ ).reduce($901f5cf476ef87a5$export$37679993c4e6bc41, []);
144
+ // const union = unionVars.map(x=>x.type);
145
+ // const union = unionVars.map(x => x.type);
146
+ // Flatten with child unions
147
+ // const rightSide = union[1];
148
+ // if (rightSide.kind === `union`) {
149
+ // union.pop();
150
+ // union.push(...rightSide.union);
151
+ // }
152
+ if (union.some((x)=>!x
153
+ )) throw new $901f5cf476ef87a5$export$d214d56e7a53a664(`or: Some fields are null`, {
154
+ node: node
155
+ });
156
+ return {
157
+ kind: `union`,
158
+ raw: node,
159
+ union: union
160
+ };
161
+ }
162
+ // Intersect
163
+ if (node.prim === `pair`) {
164
+ const fields = node.args.map((x)=>$b95e97a0bb3bf047$var$visitVar(x)
165
+ ).reduce($901f5cf476ef87a5$export$37679993c4e6bc41, []);
166
+ if (fields.some((x)=>!x
167
+ )) throw new $901f5cf476ef87a5$export$d214d56e7a53a664(`pair: Some fields are null`, {
168
+ node: node,
169
+ args: node.args,
170
+ fields: fields
171
+ });
172
+ if (fields.length !== 2) throw new $901f5cf476ef87a5$export$d214d56e7a53a664(`pair: Expected 2 items`, {
173
+ node: node,
174
+ length: fields.length,
175
+ fields: fields
176
+ });
177
+ // Flatten with unnamed child pairs
178
+ const fieldsFlat = fields.map((x)=>(!x.name || options?.ignorePairName) && x.type.kind === 'object' ? x.type.fields : [
179
+ x
180
+ ]
181
+ ).reduce($901f5cf476ef87a5$export$37679993c4e6bc41, []);
182
+ return {
183
+ kind: `object`,
184
+ raw: node,
185
+ fields: fieldsFlat
186
+ };
187
+ }
188
+ // list
189
+ if (node.prim === `list` || node.prim === `set`) {
190
+ if (node.args.length !== 1) throw new $901f5cf476ef87a5$export$d214d56e7a53a664(`list does not have 1 arg`, {
191
+ node: node,
192
+ args: node.args
193
+ });
194
+ const arrayItem = $b95e97a0bb3bf047$var$visitType(node.args[0]);
195
+ if (!arrayItem) throw new $901f5cf476ef87a5$export$d214d56e7a53a664(`arrayItem are null`, {
196
+ node: node,
197
+ args: node.args,
198
+ arrayItem: arrayItem
199
+ });
200
+ return {
201
+ kind: `array`,
202
+ raw: node,
203
+ array: {
204
+ item: arrayItem
205
+ }
206
+ };
207
+ }
208
+ // map
209
+ if (node.prim === `map` || node.prim === `big_map`) {
210
+ if (node.args.length !== 2) throw new $901f5cf476ef87a5$export$d214d56e7a53a664(`map does not have 2 args`, {
211
+ node: node,
212
+ args: node.args
213
+ });
214
+ const mapKey = $b95e97a0bb3bf047$var$visitType(node.args[0]);
215
+ const mapValue = $b95e97a0bb3bf047$var$visitType(node.args[1]);
216
+ if (!mapKey || !mapValue) throw new $901f5cf476ef87a5$export$d214d56e7a53a664(`map is missing key or value`, {
217
+ node: node,
218
+ args: node.args,
219
+ mapKey: mapKey,
220
+ mapValue: mapValue
221
+ });
222
+ return {
223
+ kind: `map`,
224
+ raw: node,
225
+ map: {
226
+ key: mapKey,
227
+ value: mapValue,
228
+ isBigMap: node.prim === `big_map`
229
+ }
230
+ };
231
+ }
232
+ // option
233
+ if (node.prim === `option`) return {
234
+ ...$b95e97a0bb3bf047$var$visitType(node.args[0]),
235
+ optional: true
236
+ };
237
+ // boolean
238
+ if (node.prim === `bool`) return {
239
+ kind: `value`,
240
+ raw: node,
241
+ value: node.prim,
242
+ typescriptType: `boolean`
243
+ };
244
+ // numbers
245
+ if (node.prim === `nat` || node.prim === `int` || node.prim === `mutez`) return {
246
+ kind: `value`,
247
+ raw: node,
248
+ value: node.prim,
249
+ typescriptType: `number`
250
+ };
251
+ // Date
252
+ if (node.prim === `timestamp`) return {
253
+ kind: `value`,
254
+ raw: node,
255
+ value: node.prim,
256
+ typescriptType: `Date`
257
+ };
258
+ // strings
259
+ if (node.prim === `address` || node.prim === `key` || node.prim === `key_hash` || node.prim === `chain_id` || node.prim === `string` || node.prim === `signature` || node.prim === `ticket` || node.prim === `bls12_381_fr` || node.prim === `bls12_381_g1` || node.prim === `bls12_381_g2` || node.prim === `sapling_state` || node.prim === `sapling_transaction` || node.prim === `contract`) return {
260
+ kind: `value`,
261
+ raw: node,
262
+ value: node.prim,
263
+ typescriptType: `string`
264
+ };
265
+ // void
266
+ if (node.prim === `unit`) return {
267
+ kind: `unit`,
268
+ raw: node
269
+ };
270
+ // bytes?
271
+ if (node.prim === `bytes`) return {
272
+ kind: `value`,
273
+ raw: node,
274
+ value: node.prim,
275
+ typescriptType: `string`
276
+ };
277
+ // misc?
278
+ if (node.prim === `lambda` || node.prim === `operation`) return {
279
+ kind: `value`,
280
+ raw: node,
281
+ value: node.prim,
282
+ typescriptType: `string`
283
+ };
284
+ // chest
285
+ if (node.prim === 'chest') throw new Error('Not Implemented: chest');
286
+ if (node.prim === 'chest_key') throw new Error('Not Implemented: chest_key');
287
+ // never
288
+ if (node.prim === `never`) return {
289
+ kind: `never`,
290
+ raw: node
291
+ };
292
+ // Unknown
293
+ $901f5cf476ef87a5$export$16bf6fe03653420f(node, `Unknown type`);
294
+ throw new $901f5cf476ef87a5$export$d214d56e7a53a664(`Unknown type`, {
295
+ node: node
296
+ });
297
+ };
298
+
299
+
300
+
301
+ const $4e7cd4eb63db9934$export$eb0413f5ee90780 = (methods)=>{
302
+ const getSchemaObjectType = (vars)=>{
303
+ // console.log('getSchemaObjectType', { vars });
304
+ if (vars.some((x)=>!x
305
+ )) throw new $901f5cf476ef87a5$export$d214d56e7a53a664(`getSchemaObjectType has null vars`, {
306
+ vars: vars
307
+ });
308
+ return vars.reduce((out, x, i)=>{
309
+ out[x.name ?? i] = getSchemaType(x.type);
310
+ return out;
311
+ }, {
312
+ });
313
+ };
314
+ const getSchemaType = (t)=>{
315
+ // console.log('getSchemaType', { t });
316
+ return ((((((t.kind === `value` && t.value ? t.value : null) ?? (t.kind === `array` && t.array ? [
317
+ getSchemaType(t.array.item)
318
+ ] : null)) ?? (t.kind === `map` && t.map ? [
319
+ `map`,
320
+ getSchemaType(t.map.key),
321
+ getSchemaType(t.map.value)
322
+ ] : null)) ?? (t.kind === `object` && t.fields ? getSchemaObjectType(t.fields) : null)) ?? (t.kind === `unit` ? `unit` : null)) ?? (t.kind === `never` ? `never` : null)) ?? `${t.raw}`;
323
+ };
324
+ const schemaMethods = methods.reduce((out, x)=>{
325
+ // console.log('schemaMethods', { x });
326
+ out[x.name] = {
327
+ params: x.args.length === 1 && !x.args[0].name ? getSchemaType(x.args[0].type) : getSchemaObjectType(x.args ?? [])
328
+ };
329
+ return out;
330
+ }, {
331
+ });
332
+ return {
333
+ schemaMethods: schemaMethods
334
+ };
335
+ };
336
+
337
+
338
+
339
+ const $8fdd19ff0013f28e$export$d355209543d39bc0 = (storage, methods, contractName, parsedContract, protocol, typeAliasData, typeUtilsData)=>{
340
+ const usedStrictTypes = [];
341
+ const addTypeAlias = (strictType)=>{
342
+ if (!usedStrictTypes.some((x)=>x.aliasType === strictType.aliasType
343
+ )) usedStrictTypes.push(strictType);
344
+ };
345
+ // Not really tabs :)
346
+ const tabs = (indent)=>Array(indent).fill(` `).join(``)
347
+ ;
348
+ const toIndentedItems = (indent, delimeters, items)=>{
349
+ return `
350
+ ${tabs(indent + 1)}${items.join(`${delimeters.afterItem ?? ``}
351
+ ${tabs(indent + 1)}${delimeters.beforeItem ?? ``}`)}
352
+ ${tabs(indent)}`;
353
+ };
354
+ const typeToCode = (t, indent)=>{
355
+ if (t.kind === `value`) {
356
+ // return `${t.typescriptType}`;
357
+ const prim = `prim` in t.raw ? t.raw.prim : `unknown`;
358
+ // Strict mode
359
+ if (t.typescriptType === `boolean` || t.typescriptType === `string` && prim === `string`) return `${t.typescriptType}`;
360
+ if (t.typescriptType === 'number') {
361
+ const simpleBaseType = `string | BigNumber | number`;
362
+ const typeAlias = {
363
+ aliasType: prim,
364
+ simpleTypeDefinition: `type ${prim} = ${simpleBaseType};`,
365
+ simpleTypeImports: [
366
+ {
367
+ name: 'BigNumber',
368
+ isDefault: true,
369
+ from: 'bignumber.js'
370
+ }
371
+ ]
372
+ };
373
+ addTypeAlias(typeAlias);
374
+ return typeAlias.aliasType;
375
+ }
376
+ const simpleBaseType = t.typescriptType === 'Date' ? 'Date | string' : t.typescriptType;
377
+ const typeAlias = {
378
+ aliasType: prim,
379
+ simpleTypeDefinition: `type ${prim} = ${simpleBaseType};`
380
+ };
381
+ addTypeAlias(typeAlias);
382
+ return typeAlias.aliasType;
383
+ }
384
+ if (t.kind === `array`) return `Array<${typeToCode(t.array.item, indent)}>`;
385
+ if (t.kind === `map`) {
386
+ const typeAlias = t.map.isBigMap ? {
387
+ aliasType: `BigMap`,
388
+ simpleTypeDefinition: 'type BigMap<K, T> = MichelsonMap<K, T>;',
389
+ simpleTypeImports: [
390
+ {
391
+ name: 'MichelsonMap',
392
+ from: '@taquito/taquito'
393
+ }
394
+ ]
395
+ } : {
396
+ aliasType: `MMap`,
397
+ simpleTypeDefinition: 'type MMap<K, T> = MichelsonMap<K, T>;',
398
+ simpleTypeImports: [
399
+ {
400
+ name: 'MichelsonMap',
401
+ from: '@taquito/taquito'
402
+ }
403
+ ]
404
+ };
405
+ addTypeAlias(typeAlias);
406
+ return `${typeAlias.aliasType}<${typeToCode(t.map.key, indent)}, ${typeToCode(t.map.value, indent)}>`;
407
+ }
408
+ if (t.kind === `object`) return `{${toIndentedItems(indent, {
409
+ }, t.fields.map((a, i)=>varToCode(a, i, indent + 1) + `;`
410
+ ))}}`;
411
+ if (t.kind === `union`) {
412
+ const getUnionItem = (a, i)=>{
413
+ const itemCode = `${varToCode(a, i, indent + 1)}`;
414
+ // Keep on single line if already on single line
415
+ if (!itemCode.includes(`\n`)) return `{ ${itemCode} }`;
416
+ // Indent if multi-line (and remake with extra indent)
417
+ return `{${toIndentedItems(indent + 1, {
418
+ }, [
419
+ `${varToCode(a, i, indent + 2)}`
420
+ ])}}`;
421
+ };
422
+ return `(${toIndentedItems(indent, {
423
+ beforeItem: `| `
424
+ }, t.union.map(getUnionItem))})`;
425
+ }
426
+ if (t.kind === `unit`) {
427
+ const typeAlias = {
428
+ aliasType: `unit`,
429
+ simpleTypeDefinition: `type unit = (true | undefined);`
430
+ };
431
+ addTypeAlias(typeAlias);
432
+ return typeAlias.aliasType;
433
+ }
434
+ if (t.kind === `never`) return `never`;
435
+ if (t.kind === `unknown`) return `unknown`;
436
+ $901f5cf476ef87a5$export$16bf6fe03653420f(t, `Unknown type`);
437
+ throw new $901f5cf476ef87a5$export$d214d56e7a53a664(`Unknown type node`, {
438
+ t: t
439
+ });
440
+ };
441
+ const varToCode = (t, i, indent)=>{
442
+ return `${t.name ?? i}${t.type.optional ? `?` : ``}: ${typeToCode(t.type, indent)}`;
443
+ };
444
+ const argsToCode = (args, indent, asObject)=>{
445
+ if (args.length === 1) {
446
+ if (args[0].type.kind === `unit`) return ``;
447
+ return `${args[0].name ?? `param`}: ${typeToCode(args[0].type, indent + 1)}`;
448
+ }
449
+ const result = `${toIndentedItems(indent, {
450
+ }, args.filter((x)=>x.name || x.type.kind !== `unit`
451
+ ).map((a, i)=>varToCode(a, i, indent + 1) + `,`
452
+ ))}`;
453
+ if (asObject) return `params: {${result}}`;
454
+ return result;
455
+ };
456
+ const methodsToCode = (indent)=>{
457
+ const methodFields = methods.map((x)=>{
458
+ const methodCode = `${x.name}: (${argsToCode(x.args, indent + 1, false)}) => Promise<void>;`;
459
+ return methodCode;
460
+ });
461
+ const methodsTypeCode = `type Methods = {${toIndentedItems(indent, {
462
+ }, methodFields)}};`;
463
+ return methodsTypeCode;
464
+ };
465
+ const methodsObjectToCode = (indent)=>{
466
+ const methodFields = methods.map((x)=>{
467
+ const methodCode = `${x.name}: (${argsToCode(x.args, indent + 1, true)}) => Promise<void>;`;
468
+ return methodCode;
469
+ });
470
+ const methodsTypeCode = `type MethodsObject = {${toIndentedItems(indent, {
471
+ }, methodFields)}};`;
472
+ return methodsTypeCode;
473
+ };
474
+ const storageToCode = (indent)=>{
475
+ const storageTypeCode = `type Storage = ${typeToCode(storage.storage, indent)};`;
476
+ return storageTypeCode;
477
+ };
478
+ const methodsCode = methodsToCode(0);
479
+ const methodsObjectCode = methodsObjectToCode(0);
480
+ const storageCode = storageToCode(0);
481
+ // Simple type aliases
482
+ const simpleTypeMappingImportsAll = new Map(usedStrictTypes.map((x)=>x.simpleTypeImports ?? []
483
+ ).reduce($901f5cf476ef87a5$export$37679993c4e6bc41, []).map((x)=>[
484
+ `${x?.from}:${x?.name}:${x?.isDefault}`,
485
+ x
486
+ ]
487
+ ));
488
+ const simpleTypeMappingImportsFrom = [
489
+ ...simpleTypeMappingImportsAll.values()
490
+ ].reduce((out, x)=>{
491
+ const entry = out[x.from] ?? (out[x.from] = {
492
+ names: []
493
+ });
494
+ if (x.isDefault) entry.default = x.name;
495
+ else entry.names.push(x.name);
496
+ entry.names.sort((a, b)=>a.localeCompare(b)
497
+ );
498
+ return out;
499
+ }, {
500
+ });
501
+ const simpleTypeMappingImportsText = Object.keys(simpleTypeMappingImportsFrom).map((k)=>{
502
+ const entry = simpleTypeMappingImportsFrom[k];
503
+ const items = [
504
+ entry.default,
505
+ entry.names.length ? `{ ${entry.names.join(', ')} }` : ''
506
+ ].filter((x)=>x
507
+ );
508
+ return `import ${items.join(', ')} from '${k}';\n`;
509
+ }).join('');
510
+ const simpleTypeMapping = usedStrictTypes.sort((a, b)=>a.aliasType.localeCompare(b.aliasType)
511
+ ).map((x)=>x.simpleTypeDefinition
512
+ ).join(`\n`);
513
+ const typeUtilsDefinitions = `import { ContractAbstractionFromContractType, WalletContractAbstractionFromContractType } from '${typeUtilsData.importPath}';`;
514
+ const typeAliasesDefinitions = typeAliasData.mode === 'simple' ? `${simpleTypeMappingImportsText}${simpleTypeMapping}` : typeAliasData.mode === 'local' ? typeAliasData.fileContent : `import { ${usedStrictTypes.map((x)=>x.aliasType
515
+ ).join(`, `)} } from '${typeAliasData.importPath}';`;
516
+ const contractTypeName = `${contractName}ContractType`;
517
+ const walletTypeName = `${contractName}WalletType`;
518
+ const codeName = `${contractName}Code`;
519
+ const typesFileContent = `
520
+ ${typeUtilsDefinitions}
521
+ ${typeAliasesDefinitions}
522
+
523
+ ${storageCode}
524
+
525
+ ${methodsCode}
526
+
527
+ ${methodsObjectCode}
528
+
529
+ type contractTypes = { methods: Methods, methodsObject: MethodsObject, storage: Storage, code: { __type: '${codeName}', protocol: string, code: object[] } };
530
+ export type ${contractTypeName} = ContractAbstractionFromContractType<contractTypes>;
531
+ export type ${walletTypeName} = WalletContractAbstractionFromContractType<contractTypes>;
532
+ `;
533
+ const contractCodeFileContent = `
534
+ export const ${codeName}: { __type: '${codeName}', protocol: string, code: object[] } = {
535
+ __type: '${codeName}',
536
+ protocol: '${protocol.key}',
537
+ code: JSON.parse(\`${JSON.stringify(parsedContract)}\`)
538
+ };
539
+ `;
540
+ return {
541
+ typesFileContent: typesFileContent,
542
+ contractCodeFileContent: contractCodeFileContent,
543
+ storage: storageCode,
544
+ methods: methodsCode,
545
+ methodsObject: methodsObjectCode
546
+ };
547
+ };
548
+
549
+
550
+ const $38088c948e5b4cf5$var$parseContractWithMinimalProtocolLevel = (contractScript, format, contractLevelIndex)=>{
551
+ const contractLevels = [
552
+ {
553
+ name: 'PsDELPH1',
554
+ key: $3ymtt$taquitomichelcodec.Protocol.PsDELPH1
555
+ },
556
+ {
557
+ name: 'PtEdo2Zk',
558
+ key: $3ymtt$taquitomichelcodec.Protocol.PtEdo2Zk
559
+ },
560
+ {
561
+ name: 'PsFLorena',
562
+ key: $3ymtt$taquitomichelcodec.Protocol.PsFLorena
563
+ },
564
+ ];
565
+ const protocol = contractLevels[contractLevelIndex];
566
+ if (!protocol) throw new $901f5cf476ef87a5$export$d214d56e7a53a664(`Could not parse contract script`, contractScript);
567
+ const p = new $3ymtt$taquitomichelcodec.Parser({
568
+ protocol: protocol.key
569
+ });
570
+ try {
571
+ const contract = format === 'tz' ? p.parseScript(contractScript) : p.parseJSON(JSON.parse(contractScript));
572
+ if (contract) return {
573
+ contract: contract,
574
+ protocol: protocol
575
+ };
576
+ } catch {
577
+ // Ignore parse errors
578
+ }
579
+ // Try again with next level
580
+ return $38088c948e5b4cf5$var$parseContractWithMinimalProtocolLevel(contractScript, format, contractLevelIndex + 1);
581
+ };
582
+ const $38088c948e5b4cf5$export$adc4e820bbd3332 = (contractScript, contractName, format, typeAliasData, typeUtilsData)=>{
583
+ const p = new $3ymtt$taquitomichelcodec.Parser({
584
+ protocol: $3ymtt$taquitomichelcodec.Protocol.PsFLorena
585
+ });
586
+ const { contract: contract , protocol: protocol } = $38088c948e5b4cf5$var$parseContractWithMinimalProtocolLevel(contractScript, format, 0);
587
+ const contractStorage = contract.find((x)=>x.prim === `storage`
588
+ );
589
+ const contractParameter = contract.find((x)=>x.prim === `parameter`
590
+ );
591
+ const storageResult = contractStorage && $b95e97a0bb3bf047$export$cc65da7b09dcddd7(contractStorage);
592
+ const storage = storageResult ?? {
593
+ storage: {
594
+ kind: `object`,
595
+ raw: {
596
+ prim: `never`
597
+ },
598
+ fields: []
599
+ }
600
+ };
601
+ const parameterResult = contractParameter && $b95e97a0bb3bf047$export$5c00959a6ba200c1(contractParameter);
602
+ const methods = parameterResult?.methods ?? [];
603
+ const schemaOutput = $4e7cd4eb63db9934$export$eb0413f5ee90780(methods);
604
+ const typescriptCode = $8fdd19ff0013f28e$export$d355209543d39bc0(storage, methods, contractName, contract, protocol, typeAliasData, typeUtilsData);
605
+ return {
606
+ schema: schemaOutput,
607
+ typescriptCodeOutput: typescriptCode,
608
+ parsedContract: contract,
609
+ minimalProtocol: protocol.key
610
+ };
611
+ };
612
+
613
+
614
+ const $7d27ec5ea3b0470e$export$4bf5db15180664ad = `
615
+ import { BigNumber } from 'bignumber.js';
616
+ import { MichelsonMap } from '@taquito/taquito';
617
+
618
+ export type unit = (true | undefined) & { __type: 'unit' };
619
+
620
+ export type address = string & { __type: 'address' };
621
+ export type bytes = string & { __type: 'bytes' };
622
+ export type contract = string & { __type: 'contract' };
623
+ export type operation = string & { __type: 'operation' };
624
+ export type key = string & { __type: 'key' };
625
+ export type key_hash = string & { __type: 'key_hash' };
626
+ export type signature = string & { __type: 'signature' };
627
+ export type ticket = string & { __type: 'ticket' };
628
+
629
+ export type timestamp = string & { __type: 'timestamp' };
630
+
631
+ export type int = BigNumber & { __type: 'int' };
632
+ export type nat = BigNumber & { __type: 'nat' };
633
+
634
+ export type mutez = BigNumber & { __type: 'mutez' };
635
+ export type tez = BigNumber & { __type: 'tez' };
636
+
637
+ export type MMap<K, V> = Omit<MichelsonMap<K, V>, 'get'> & { get: (key: K) => V };
638
+ export type BigMap<K, V> = Omit<MichelsonMap<K, V>, 'get'> & { get: (key: K) => Promise<V> };
639
+
640
+
641
+ const createStringTypeTas = <T extends string>() => {
642
+ return (value: string): T => value as T;
643
+ };
644
+
645
+ const createBigNumberTypeTas = <T extends BigNumber>() => {
646
+ return (value: number | BigNumber | string): T => new BigNumber(value) as T;
647
+ };
648
+
649
+ type asMapParamOf<K, V> = K extends string ? { [key: string]: V } | Array<{ key: K, value: V }>
650
+ : K extends number ? { [key: number]: V } | Array<{ key: K, value: V }>
651
+ : Array<{ key: K, value: V }>;
652
+
653
+ function asMap<K, V>(value: asMapParamOf<K, V>): MMap<K, V> {
654
+ const m = new MichelsonMap<K, V>();
655
+ if (Array.isArray(value)) {
656
+ const vArray = value as Array<{ key: K, value: V }>;
657
+ vArray.forEach(x => m.set(x.key, x.value));
658
+ } else {
659
+ const vObject = value as { [key: string]: V };
660
+ Object.keys(vObject).forEach(key => m.set(key as unknown as K, vObject[key]));
661
+ }
662
+ return m as MMap<K, V>;
663
+ }
664
+ const asBigMap = <K, V>(value: asMapParamOf<K, V>) => asMap(value) as unknown as BigMap<K, V>;
665
+
666
+ function add<T extends BigNumber>(a: T, b: T): T {
667
+ return a.plus(b) as T;
668
+ }
669
+ function subtract<T extends BigNumber>(a: T, b: T): T {
670
+ return a.minus(b) as T;
671
+ }
672
+
673
+ /** tas: Tezos 'as' casting for strict types */
674
+ export const tas = {
675
+ address: createStringTypeTas<address>(),
676
+ bytes: createStringTypeTas<bytes>(),
677
+ contract: createStringTypeTas<contract>(),
678
+ timestamp: (value: string | Date): timestamp => new Date(value).toISOString() as timestamp,
679
+
680
+ int: createBigNumberTypeTas<int>(),
681
+ nat: createBigNumberTypeTas<nat>(),
682
+ mutez: createBigNumberTypeTas<mutez>(),
683
+ tez: createBigNumberTypeTas<tez>(),
684
+
685
+ map: asMap,
686
+ bigMap: asBigMap,
687
+
688
+ // Operations
689
+ add,
690
+ subtract,
691
+
692
+ // To number
693
+ number: (value: string | BigNumber) => Number(value + ''),
694
+ };
695
+ `;
696
+
697
+
698
+ const $d6317276dd27d471$export$e9cf70f604100ab7 = `
699
+ import { ContractAbstraction, ContractMethod, ContractMethodObject, ContractProvider, Wallet } from '@taquito/taquito';
700
+
701
+ type BaseContractType = { methods: unknown, methodsObject: unknown, storage: unknown };
702
+
703
+ type ContractMethodsOf<T extends ContractProvider | Wallet, TContract extends BaseContractType> = {
704
+ [M in keyof TContract['methods']]:
705
+ TContract['methods'][M] extends (...args: infer A) => unknown
706
+ ? (...args: A) => ContractMethod<T>
707
+ : never
708
+ };
709
+ type ContractMethodsObjectsOf<T extends ContractProvider | Wallet, TContract extends BaseContractType> = {
710
+ [M in keyof TContract['methodsObject']]:
711
+ TContract['methodsObject'][M] extends (...args: infer A) => unknown
712
+ ? (...args: A) => ContractMethodObject<T>
713
+ : never
714
+ };
715
+ type ContractStorageOf<TContract extends BaseContractType> = TContract['storage'];
716
+
717
+ export type ContractAbstractionFromContractType<TContract extends BaseContractType> =
718
+ ContractAbstraction<ContractProvider,
719
+ ContractMethodsOf<ContractProvider, TContract>,
720
+ ContractMethodsObjectsOf<ContractProvider, TContract>,
721
+ {},
722
+ {},
723
+ ContractStorageOf<TContract>
724
+ >;
725
+
726
+ export type WalletContractAbstractionFromContractType<TContract extends BaseContractType> =
727
+ ContractAbstraction<Wallet,
728
+ ContractMethodsOf<Wallet, TContract>,
729
+ ContractMethodsObjectsOf<Wallet, TContract>,
730
+ {},
731
+ {},
732
+ ContractStorageOf<TContract>
733
+ >;
734
+ `;
735
+
736
+
737
+ const $ce33c3ba360b60b0$var$fs = {
738
+ mkdir: $3ymtt$util.promisify(($parcel$interopDefault($3ymtt$fs)).mkdir),
739
+ copyFile: $3ymtt$util.promisify(($parcel$interopDefault($3ymtt$fs)).copyFile),
740
+ readdir: $3ymtt$util.promisify(($parcel$interopDefault($3ymtt$fs)).readdir),
741
+ readFile: $3ymtt$util.promisify(($parcel$interopDefault($3ymtt$fs)).readFile),
742
+ writeFile: $3ymtt$util.promisify(($parcel$interopDefault($3ymtt$fs)).writeFile),
743
+ stat: $3ymtt$util.promisify(($parcel$interopDefault($3ymtt$fs)).stat),
744
+ exists: ($parcel$interopDefault($3ymtt$fs)).existsSync
745
+ };
746
+ const $ce33c3ba360b60b0$var$getAllFiles = async (rootPath, filter)=>{
747
+ const allFiles = [];
748
+ const getAllFilesRecursive = async (dirPath)=>{
749
+ let files = await $ce33c3ba360b60b0$var$fs.readdir(dirPath, {
750
+ withFileTypes: true
751
+ });
752
+ for (const f of files){
753
+ const subPath = ($parcel$interopDefault($3ymtt$path)).resolve(dirPath, f.name);
754
+ if (f.isDirectory()) {
755
+ await getAllFilesRecursive(subPath);
756
+ continue;
757
+ }
758
+ if (!filter(subPath)) continue;
759
+ allFiles.push(subPath);
760
+ }
761
+ };
762
+ await getAllFilesRecursive(rootPath);
763
+ return allFiles;
764
+ };
765
+ const $ce33c3ba360b60b0$export$2ab4539ae1119673 = async ({ inputTzContractDirectory: inputTzContractDirectory , inputFiles: inputFiles , outputTypescriptDirectory: outputTypescriptDirectory , format: format , typeAliasMode: typeAliasMode , })=>{
766
+ console.log(`Generating Types: ${($parcel$interopDefault($3ymtt$path)).resolve(inputTzContractDirectory)} => ${($parcel$interopDefault($3ymtt$path)).resolve(outputTypescriptDirectory)}`);
767
+ const ext = '.' + format;
768
+ const filesAll = await $ce33c3ba360b60b0$var$getAllFiles(inputTzContractDirectory, (x)=>x.endsWith(ext)
769
+ );
770
+ const files = inputFiles ? filesAll.filter((f)=>inputFiles.some((inputFile)=>f.endsWith(inputFile)
771
+ )
772
+ ) : filesAll;
773
+ console.log(`Contracts Found: ${[
774
+ ``,
775
+ ...files
776
+ ].join(`\n\t- `)}`);
777
+ const typeAliasImportPath = `@taquito/contract-type-generator`;
778
+ const typeAliasData = typeAliasMode === 'local' ? {
779
+ mode: typeAliasMode,
780
+ fileContent: $7d27ec5ea3b0470e$export$4bf5db15180664ad
781
+ } : typeAliasMode === 'file' ? {
782
+ mode: typeAliasMode,
783
+ importPath: `./type-aliases`
784
+ } : typeAliasMode === 'library' ? {
785
+ mode: typeAliasMode,
786
+ importPath: typeAliasImportPath
787
+ } : {
788
+ mode: 'simple'
789
+ };
790
+ if (typeAliasMode === 'file') {
791
+ // Copy the type alias file
792
+ await $ce33c3ba360b60b0$var$fs.mkdir(outputTypescriptDirectory, {
793
+ recursive: true
794
+ });
795
+ await $ce33c3ba360b60b0$var$fs.writeFile(($parcel$interopDefault($3ymtt$path)).join(outputTypescriptDirectory, './type-aliases.ts'), $7d27ec5ea3b0470e$export$4bf5db15180664ad);
796
+ }
797
+ // Copy the type utils file
798
+ const typeUtilsData = {
799
+ importPath: `./type-utils`
800
+ };
801
+ await $ce33c3ba360b60b0$var$fs.mkdir(outputTypescriptDirectory, {
802
+ recursive: true
803
+ });
804
+ await $ce33c3ba360b60b0$var$fs.writeFile(($parcel$interopDefault($3ymtt$path)).join(outputTypescriptDirectory, './type-utils.ts'), $d6317276dd27d471$export$e9cf70f604100ab7);
805
+ for (const fullPath of files){
806
+ const fileRelativePath = fullPath.replace(($parcel$interopDefault($3ymtt$path)).resolve(inputTzContractDirectory), '');
807
+ const fileName = fileRelativePath.replace(ext, '');
808
+ const inputFilePath = ($parcel$interopDefault($3ymtt$path)).join(inputTzContractDirectory, fileRelativePath);
809
+ const typesOutputFilePath = ($parcel$interopDefault($3ymtt$path)).join(outputTypescriptDirectory, fileRelativePath.replace(ext, `.types.ts`));
810
+ const codeContentOutputFilePath = ($parcel$interopDefault($3ymtt$path)).join(outputTypescriptDirectory, fileRelativePath.replace(ext, `.code.ts`));
811
+ console.log(`Processing ${fileRelativePath}...`);
812
+ try {
813
+ const contractTypeName = $3f5c875567479895$export$bd8d1d28710832a7(fileName);
814
+ const michelsonCode = await $ce33c3ba360b60b0$var$fs.readFile(inputFilePath, {
815
+ encoding: `utf8`
816
+ });
817
+ const { typescriptCodeOutput: { typesFileContent: typesFileContent , contractCodeFileContent: contractCodeFileContent } } = $38088c948e5b4cf5$export$adc4e820bbd3332(michelsonCode, contractTypeName, format, typeAliasData, typeUtilsData);
818
+ // Write output (ensure dir exists)
819
+ await $ce33c3ba360b60b0$var$fs.mkdir(($parcel$interopDefault($3ymtt$path)).dirname(typesOutputFilePath), {
820
+ recursive: true
821
+ });
822
+ await $ce33c3ba360b60b0$var$fs.writeFile(typesOutputFilePath, typesFileContent);
823
+ await $ce33c3ba360b60b0$var$fs.writeFile(codeContentOutputFilePath, contractCodeFileContent);
824
+ } catch (err) {
825
+ console.error(`❌ Could not process ${fileRelativePath}`, {
826
+ err: err
827
+ });
828
+ }
829
+ }
830
+ };
831
+
832
+
833
+ const $3beaa6d78a95a243$var$getContractAbspath = (contractFilename, parsedArgs)=>$3ymtt$path.join(parsedArgs.artifactsDir, /\.tz$/.test(contractFilename) ? contractFilename : `${contractFilename}.tz`)
834
+ ;
835
+ const $3beaa6d78a95a243$var$generateContractTypes = (parsedArgs)=>async (contractFilename)=>{
836
+ const contractAbspath = $3beaa6d78a95a243$var$getContractAbspath(contractFilename, parsedArgs);
837
+ await $ce33c3ba360b60b0$export$2ab4539ae1119673({
838
+ inputTzContractDirectory: parsedArgs.artifactsDir,
839
+ inputFiles: [
840
+ contractAbspath
841
+ ],
842
+ outputTypescriptDirectory: parsedArgs.typescriptDir,
843
+ format: 'tz',
844
+ typeAliasMode: parsedArgs.typeAliasMode ?? 'file'
845
+ });
846
+ return `${contractFilename}: Types generated`;
847
+ // TODO: Generate contract michelson
848
+ // TODO: Generate types from michelson
849
+ // throw new Error('Not Implemented');
850
+ // // TODO: Should getting the default environment be provided by the SDK or the framework?
851
+ // const currentEnv = parsedArgs.env
852
+ // ? (parsedArgs.env as string)
853
+ // : (
854
+ // parsedArgs.config.environment
855
+ // ? parsedArgs.config.environment.default
856
+ // : 'development'
857
+ // )
858
+ // const env = parsedArgs.config.environment && parsedArgs.config.environment[currentEnv]
859
+ // ? parsedArgs.config.environment[currentEnv]
860
+ // : undefined
861
+ // // Has storage been provided for this contract?
862
+ // if (env && env.storage) {
863
+ // try {
864
+ // const tezos = new TezosToolkit(env.rpcUrl)
865
+ // const contractData = await readFile(contractAbspath, "utf-8")
866
+ // // TODO: Generate contract michelson
867
+ // // TODO: Generate types from michelson
868
+ // throw new Error('Not Implemented');
869
+ // // await importKey(tezos, env.faucet.email, env.faucet.password, env.faucet.mnemonic.join(' '), env.faucet.activation_code)
870
+ // // return tezos.contract.originate({
871
+ // // code: contractData,
872
+ // // storage: env.storage[contractFilename]
873
+ // // })
874
+ // // .then(operation => `${contractFilename}: ${operation.contractAddress}`)
875
+ // }
876
+ // catch (err) {
877
+ // return Promise.reject({
878
+ // status: 'failed',
879
+ // stdout: "",
880
+ // stderr: err
881
+ // })
882
+ // }
883
+ // }
884
+ // return Promise.reject({
885
+ // status: 'failed',
886
+ // stderr: `No storage configured in your configuration file for ${contractFilename}`,
887
+ // stdout: ""
888
+ // })
889
+ }
890
+ ;
891
+ const $3beaa6d78a95a243$var$generateContractTypesAll = (parsedArgs)=>($parcel$interopDefault($3ymtt$fastglob))("**/*.tz", {
892
+ cwd: parsedArgs.artifactsDir
893
+ }).then((files)=>Promise.all(files.map($3beaa6d78a95a243$var$generateContractTypes(parsedArgs)))
894
+ )
895
+ ;
896
+ const $3beaa6d78a95a243$export$3350b7b754d5c00c = (parsedArgs)=>{
897
+ if (!parsedArgs.typescriptDir) return Promise.reject({
898
+ status: 'failed',
899
+ stderr: `No typescriptDir configured`,
900
+ stdout: ""
901
+ });
902
+ // WORKAROUND: Redirect console.log
903
+ const strOutLog = [];
904
+ const consoleLogOrig = console.log;
905
+ console.log = (message, data)=>{
906
+ strOutLog.push(`${message}${data ? `\n${JSON.stringify(data, null, 2)}` : ''}`);
907
+ };
908
+ console.log('generateTypes', {
909
+ typescriptDir: parsedArgs.typescriptDir
910
+ });
911
+ // console.log = consoleLogOrig;
912
+ // return Promise.resolve({
913
+ // status: 'success',
914
+ // stdout: `${strOutLog.join('\n')}`,
915
+ // stderr: ""
916
+ // });
917
+ const argsTyped = parsedArgs;
918
+ const p = argsTyped.contract ? $3beaa6d78a95a243$var$generateContractTypes(argsTyped)(argsTyped.contract) : $3beaa6d78a95a243$var$generateContractTypesAll(argsTyped);
919
+ return p.then((data)=>{
920
+ console.log = consoleLogOrig;
921
+ return {
922
+ status: 'success',
923
+ stdout: `${strOutLog.join('\n')}${Array.isArray(data) ? data.join("\n") : data}`,
924
+ stderr: ""
925
+ };
926
+ });
927
+ };
928
+ const $3beaa6d78a95a243$export$7191f9b9098a3ea4 = {
929
+ generateTypes: $3beaa6d78a95a243$export$3350b7b754d5c00c
930
+ };
931
+
932
+
933
+ $3ymtt$taquerianodesdk.Plugin.create((i18n)=>({
934
+ name: "contract-types",
935
+ schema: "1.0",
936
+ version: "0.1",
937
+ tasks: [
938
+ $3ymtt$taquerianodesdk.Task.create({
939
+ task: "types",
940
+ command: "typegen [contract]",
941
+ description: "Generate types for a contract to be used with taquito",
942
+ options: [
943
+ $3ymtt$taquerianodesdk.Option.create({
944
+ shortFlag: "o",
945
+ flag: "typescriptDir",
946
+ description: "The entry point that will be compiled"
947
+ }),
948
+ $3ymtt$taquerianodesdk.Option.create({
949
+ shortFlag: "t",
950
+ flag: "typeAliasMode",
951
+ choices: [
952
+ 'file',
953
+ 'simple'
954
+ ],
955
+ description: "The type aliases used in the generated types"
956
+ }),
957
+ ],
958
+ aliases: [
959
+ "types"
960
+ ],
961
+ handler: "proxy"
962
+ }),
963
+ ],
964
+ proxy: $3beaa6d78a95a243$export$7191f9b9098a3ea4.generateTypes
965
+ })
966
+ , process.argv);
967
+
968
+
969
+ //# sourceMappingURL=index.js.map