@dedot/codegen 0.0.1-alpha.34 → 0.0.1-alpha.35

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 (112) hide show
  1. package/{generator → chaintypes/generator}/ApiGen.d.ts +12 -12
  2. package/{generator → chaintypes/generator}/ConstsGen.js +2 -2
  3. package/{generator → chaintypes/generator}/ErrorsGen.js +4 -4
  4. package/{generator → chaintypes/generator}/EventsGen.js +4 -4
  5. package/{generator → chaintypes/generator}/IndexGen.js +3 -3
  6. package/{generator → chaintypes/generator}/JsonRpcGen.js +2 -2
  7. package/{generator → chaintypes/generator}/QueryGen.js +9 -9
  8. package/{generator → chaintypes/generator}/RuntimeApisGen.js +3 -3
  9. package/{generator → chaintypes/generator}/TxGen.js +6 -6
  10. package/chaintypes/generator/TypesGen.d.ts +11 -0
  11. package/chaintypes/generator/TypesGen.js +55 -0
  12. package/chaintypes/index.d.ts +3 -0
  13. package/chaintypes/index.js +49 -0
  14. package/{cjs → chaintypes}/templates/consts.hbs +1 -1
  15. package/{templates → chaintypes/templates}/errors.hbs +1 -1
  16. package/{templates → chaintypes/templates}/events.hbs +1 -1
  17. package/{templates → chaintypes/templates}/index.hbs +1 -1
  18. package/{templates → chaintypes/templates}/json-rpc.hbs +1 -1
  19. package/{templates → chaintypes/templates}/query.hbs +1 -1
  20. package/{templates → chaintypes/templates}/runtime.hbs +1 -1
  21. package/{cjs → chaintypes}/templates/tx.hbs +1 -1
  22. package/{cjs → chaintypes}/templates/types.hbs +1 -1
  23. package/cjs/{generator → chaintypes/generator}/ConstsGen.js +2 -2
  24. package/cjs/{generator → chaintypes/generator}/ErrorsGen.js +4 -4
  25. package/cjs/{generator → chaintypes/generator}/EventsGen.js +4 -4
  26. package/cjs/{generator → chaintypes/generator}/IndexGen.js +4 -4
  27. package/cjs/{generator → chaintypes/generator}/JsonRpcGen.js +2 -2
  28. package/cjs/{generator → chaintypes/generator}/QueryGen.js +9 -9
  29. package/cjs/{generator → chaintypes/generator}/RuntimeApisGen.js +4 -4
  30. package/cjs/{generator → chaintypes/generator}/TxGen.js +6 -6
  31. package/cjs/chaintypes/generator/TypesGen.js +59 -0
  32. package/cjs/chaintypes/index.js +77 -0
  33. package/{templates → cjs/chaintypes/templates}/consts.hbs +1 -1
  34. package/cjs/{templates → chaintypes/templates}/errors.hbs +1 -1
  35. package/cjs/{templates → chaintypes/templates}/events.hbs +1 -1
  36. package/cjs/{templates → chaintypes/templates}/index.hbs +1 -1
  37. package/cjs/{templates → chaintypes/templates}/json-rpc.hbs +1 -1
  38. package/cjs/{templates → chaintypes/templates}/query.hbs +1 -1
  39. package/cjs/{templates → chaintypes/templates}/runtime.hbs +1 -1
  40. package/{templates → cjs/chaintypes/templates}/tx.hbs +1 -1
  41. package/{templates → cjs/chaintypes/templates}/types.hbs +1 -1
  42. package/cjs/index.js +4 -63
  43. package/cjs/{generator/TypesGen.js → shared/BaseTypesGen.js} +111 -159
  44. package/cjs/{generator → shared}/TypeImports.js +16 -0
  45. package/cjs/shared/index.js +19 -0
  46. package/cjs/{generator → shared}/known-codecs.js +23 -4
  47. package/cjs/typink/generator/ConstructorQueryGen.js +24 -0
  48. package/cjs/typink/generator/ConstructorTxGen.js +24 -0
  49. package/cjs/typink/generator/IndexGen.js +24 -0
  50. package/cjs/typink/generator/QueryGen.js +72 -0
  51. package/cjs/typink/generator/TxGen.js +25 -0
  52. package/cjs/typink/generator/TypesGen.js +28 -0
  53. package/cjs/typink/generator/index.js +22 -0
  54. package/cjs/typink/index.js +37 -0
  55. package/cjs/typink/templates/constructor-query.hbs +7 -0
  56. package/cjs/typink/templates/constructor-tx.hbs +7 -0
  57. package/cjs/typink/templates/index.hbs +14 -0
  58. package/cjs/typink/templates/query.hbs +7 -0
  59. package/cjs/typink/templates/tx.hbs +7 -0
  60. package/cjs/typink/templates/types.hbs +5 -0
  61. package/cjs/{generator/utils.js → utils.js} +4 -4
  62. package/index.d.ts +2 -3
  63. package/index.js +2 -49
  64. package/package.json +12 -12
  65. package/{generator/TypesGen.d.ts → shared/BaseTypesGen.d.ts} +12 -11
  66. package/{generator/TypesGen.js → shared/BaseTypesGen.js} +108 -156
  67. package/{generator → shared}/TypeImports.d.ts +4 -0
  68. package/{generator → shared}/TypeImports.js +16 -0
  69. package/shared/index.d.ts +3 -0
  70. package/shared/index.js +3 -0
  71. package/{generator → shared}/known-codecs.d.ts +2 -2
  72. package/{generator → shared}/known-codecs.js +21 -2
  73. package/typink/generator/ConstructorQueryGen.d.ts +6 -0
  74. package/typink/generator/ConstructorQueryGen.js +20 -0
  75. package/typink/generator/ConstructorTxGen.d.ts +6 -0
  76. package/typink/generator/ConstructorTxGen.js +20 -0
  77. package/typink/generator/IndexGen.d.ts +6 -0
  78. package/typink/generator/IndexGen.js +20 -0
  79. package/typink/generator/QueryGen.d.ts +12 -0
  80. package/typink/generator/QueryGen.js +68 -0
  81. package/typink/generator/TxGen.d.ts +6 -0
  82. package/typink/generator/TxGen.js +21 -0
  83. package/typink/generator/TypesGen.d.ts +7 -0
  84. package/typink/generator/TypesGen.js +24 -0
  85. package/typink/generator/index.d.ts +6 -0
  86. package/typink/generator/index.js +6 -0
  87. package/typink/index.d.ts +2 -0
  88. package/typink/index.js +30 -0
  89. package/typink/templates/constructor-query.hbs +7 -0
  90. package/typink/templates/constructor-tx.hbs +7 -0
  91. package/typink/templates/index.hbs +14 -0
  92. package/typink/templates/query.hbs +7 -0
  93. package/typink/templates/tx.hbs +7 -0
  94. package/typink/templates/types.hbs +5 -0
  95. package/{generator/utils.d.ts → utils.d.ts} +1 -1
  96. package/{generator/utils.js → utils.js} +4 -4
  97. /package/{generator → chaintypes/generator}/ApiGen.js +0 -0
  98. /package/{generator → chaintypes/generator}/ConstsGen.d.ts +0 -0
  99. /package/{generator → chaintypes/generator}/ErrorsGen.d.ts +0 -0
  100. /package/{generator → chaintypes/generator}/EventsGen.d.ts +0 -0
  101. /package/{generator → chaintypes/generator}/IndexGen.d.ts +0 -0
  102. /package/{generator → chaintypes/generator}/JsonRpcGen.d.ts +0 -0
  103. /package/{generator → chaintypes/generator}/QueryGen.d.ts +0 -0
  104. /package/{generator → chaintypes/generator}/RuntimeApisGen.d.ts +0 -0
  105. /package/{generator → chaintypes/generator}/TxGen.d.ts +0 -0
  106. /package/{generator → chaintypes/generator}/index.d.ts +0 -0
  107. /package/{generator → chaintypes/generator}/index.js +0 -0
  108. /package/cjs/{generator → chaintypes/generator}/ApiGen.js +0 -0
  109. /package/cjs/{generator → chaintypes/generator}/index.js +0 -0
  110. /package/cjs/{generator/dirname.js → dirname.js} +0 -0
  111. /package/{generator/dirname.d.ts → dirname.d.ts} +0 -0
  112. /package/{generator/dirname.js → dirname.js} +0 -0
@@ -1,68 +1,96 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TypesGen = exports.BASIC_KNOWN_TYPES = void 0;
4
- const codecs_1 = require("@dedot/codecs");
3
+ exports.BaseTypesGen = exports.BASIC_KNOWN_TYPES = void 0;
5
4
  const utils_1 = require("@dedot/utils");
5
+ const utils_js_1 = require("../utils.js");
6
6
  const TypeImports_js_1 = require("./TypeImports.js");
7
7
  const known_codecs_js_1 = require("./known-codecs.js");
8
- const utils_js_1 = require("./utils.js");
9
- // Skip generate types for these
10
- // as we do have native types for them
11
- const SKIP_TYPES = [
12
- 'BoundedBTreeMap',
13
- 'BoundedBTreeSet',
14
- 'BoundedVec',
15
- 'Box',
16
- 'BTreeMap',
17
- 'BTreeSet',
18
- 'Cow',
19
- 'Option',
20
- 'Range',
21
- 'RangeInclusive',
22
- 'Result',
23
- 'WeakBoundedVec',
24
- 'WrapperKeepOpaque',
25
- 'WrapperOpaque',
26
- ];
27
8
  // These are common & generic types, so we'll remove these from all paths at index 1
28
9
  // This helps make the type name shorter
29
10
  const PATH_RM_INDEX_1 = ['generic', 'misc', 'pallet', 'traits', 'types'];
30
11
  exports.BASIC_KNOWN_TYPES = ['BitSequence', 'Bytes', 'BytesLike', 'FixedBytes', 'FixedArray', 'Result'];
31
- const WRAPPER_TYPE_REGEX = /^(\w+)(<.*>)$/g;
32
- class TypesGen {
33
- metadata;
34
- /**
35
- * Types will be generated its definition out.
36
- */
12
+ class BaseTypesGen {
13
+ types;
37
14
  includedTypes;
38
- registry;
39
15
  typeImports;
40
- constructor(metadata) {
41
- this.metadata = metadata;
42
- this.registry = new codecs_1.PortableRegistry(this.metadata);
43
- this.includedTypes = this.#includedTypes();
16
+ skipTypes;
17
+ constructor(types) {
18
+ this.types = types;
19
+ this.includedTypes = {};
44
20
  this.typeImports = new TypeImports_js_1.TypeImports();
21
+ this.skipTypes = [];
45
22
  }
46
- generate(useSubPaths = false) {
47
- this.clearCache();
48
- let defTypeOut = '';
49
- Object.values(this.includedTypes)
50
- .filter(({ skip, knownType }) => !(skip || knownType))
51
- .forEach(({ name, nameOut, id, docs }) => {
52
- defTypeOut += `${(0, utils_js_1.commentBlock)(docs)}export type ${nameOut} = ${this.generateType(id, 0, true)};\n\n`;
53
- if (this.#shouldGenerateTypeIn(id)) {
54
- defTypeOut += `export type ${name} = ${this.generateType(id)};\n\n`;
55
- }
56
- });
57
- const importTypes = this.typeImports.toImports({ useSubPaths, excludeModules: ['./types'] });
58
- const template = (0, utils_js_1.compileTemplate)('types.hbs');
59
- return (0, utils_js_1.beautifySourceCode)(template({ importTypes, defTypeOut }));
23
+ shouldGenerateTypeIn(_id) {
24
+ return false;
60
25
  }
61
26
  typeCache = {};
62
27
  clearCache() {
63
28
  this.typeCache = {};
64
29
  this.typeImports.clear();
65
30
  }
31
+ includeTypes() {
32
+ const pathsCount = new Map();
33
+ const typesWithPath = this.types.filter((one) => one.path.length > 0);
34
+ const skipIds = [];
35
+ const typeSuffixes = new Map();
36
+ typesWithPath.forEach(({ path, id }) => {
37
+ const joinedPath = path.join('::');
38
+ if (pathsCount.has(joinedPath)) {
39
+ // We compare 2 types with the same path here,
40
+ // if they are the same type -> skip the current one, keep the first occurrence
41
+ // if they are not the same type but has the same path -> we'll try to calculate & add a suffix for the current type name
42
+ const firstOccurrenceTypeId = pathsCount.get(joinedPath)[0];
43
+ const sameType = this.typeEql(firstOccurrenceTypeId, id);
44
+ if (sameType) {
45
+ skipIds.push(id);
46
+ }
47
+ else {
48
+ pathsCount.get(joinedPath).push(id);
49
+ typeSuffixes.set(id, this.extractDupTypeSuffix(id, firstOccurrenceTypeId, pathsCount.get(joinedPath).length));
50
+ }
51
+ }
52
+ else {
53
+ pathsCount.set(joinedPath, [id]);
54
+ }
55
+ });
56
+ return typesWithPath.reduce((o, type) => {
57
+ const { path, id } = type;
58
+ const joinedPath = path.join('::');
59
+ if (this.skipTypes.includes(joinedPath) || this.skipTypes.includes(path.at(-1))) {
60
+ return o;
61
+ }
62
+ const suffix = typeSuffixes.get(id) || '';
63
+ let knownType = false;
64
+ let name, nameOut;
65
+ const [isKnownCodecType, codecName] = (0, known_codecs_js_1.checkKnownCodecType)(joinedPath);
66
+ if (isKnownCodecType) {
67
+ const codecType = (0, known_codecs_js_1.findKnownCodecType)(codecName);
68
+ name = codecType.typeIn;
69
+ nameOut = codecType.typeOut;
70
+ knownType = true;
71
+ }
72
+ else if (PATH_RM_INDEX_1.includes(path[1])) {
73
+ const newPath = path.slice();
74
+ newPath.splice(1, 1);
75
+ name = this.cleanPath(newPath);
76
+ }
77
+ else {
78
+ name = this.cleanPath(path);
79
+ }
80
+ if (this.shouldGenerateTypeIn(id)) {
81
+ nameOut = name;
82
+ name = name.endsWith('Like') ? name : `${name}Like`;
83
+ }
84
+ o[id] = {
85
+ name: `${name}${suffix}`,
86
+ nameOut: nameOut ? `${nameOut}${suffix}` : `${name}${suffix}`,
87
+ knownType,
88
+ skip: skipIds.includes(id),
89
+ ...type,
90
+ };
91
+ return o;
92
+ }, {});
93
+ }
66
94
  generateType(typeId, nestedLevel = 0, typeOut = false) {
67
95
  if (nestedLevel > 0) {
68
96
  const includedDef = this.includedTypes[typeId];
@@ -93,13 +121,13 @@ class TypesGen {
93
121
  return type;
94
122
  }
95
123
  #generateType(typeId, nestedLevel = 0, typeOut = false) {
96
- const def = this.metadata.types[typeId];
124
+ const def = this.types[typeId];
97
125
  if (!def) {
98
126
  throw new Error(`Type def not found ${JSON.stringify(def)}`);
99
127
  }
100
- const { type, path, docs } = def;
101
- const { tag, value } = type;
102
- switch (tag) {
128
+ const { typeDef, path, docs } = def;
129
+ const { type, value } = typeDef;
130
+ switch (type) {
103
131
  case 'Primitive':
104
132
  const $codec = (0, known_codecs_js_1.findKnownCodec)(value.kind);
105
133
  if ($codec.nativeType) {
@@ -170,14 +198,14 @@ class TypesGen {
170
198
  membersType.push([keyName, this.generateObjectType(fields, nestedLevel + 1, typeOut), docs]);
171
199
  }
172
200
  }
173
- const { tagKey, valueKey } = this.registry.getEnumOptions(typeId);
201
+ const { tagKey, valueKey } = this.getEnumOptions(typeId);
174
202
  return membersType
175
203
  .map(([keyName, valueType, docs]) => ({
176
- tag: `${tagKey}: '${keyName}'`,
204
+ type: `${tagKey}: '${keyName}'`,
177
205
  value: valueType ? `, ${valueKey}${this.#isOptionalType(valueType) ? '?' : ''}: ${valueType} ` : '',
178
206
  docs,
179
207
  }))
180
- .map(({ tag, value, docs }) => `${(0, utils_js_1.commentBlock)(docs)}{ ${tag}${value} }`)
208
+ .map(({ type, value, docs }) => `${(0, utils_js_1.commentBlock)(docs)}{ ${type}${value} }`)
181
209
  .join(' | ');
182
210
  }
183
211
  }
@@ -199,9 +227,9 @@ class TypesGen {
199
227
  return this.generateType(value.typeParam, nestedLevel + 1, typeOut);
200
228
  case 'Sequence':
201
229
  case 'SizedVec': {
202
- const fixedSize = tag === 'SizedVec' ? `${value.len}` : null;
203
- const $innerType = this.metadata.types[value.typeParam].type;
204
- if ($innerType.tag === 'Primitive' && $innerType.value.kind === 'u8') {
230
+ const fixedSize = type === 'SizedVec' ? `${value.len}` : null;
231
+ const $innerType = this.types[value.typeParam].typeDef;
232
+ if ($innerType.type === 'Primitive' && $innerType.value.kind === 'u8') {
205
233
  return fixedSize ? `FixedBytes<${fixedSize}>` : typeOut ? 'Bytes' : 'BytesLike';
206
234
  }
207
235
  else {
@@ -210,7 +238,7 @@ class TypesGen {
210
238
  }
211
239
  }
212
240
  default:
213
- throw new Error(`Invalid type! ${tag}`);
241
+ throw new Error(`Invalid type! ${type}`);
214
242
  }
215
243
  }
216
244
  generateObjectType(fields, nestedLevel = 0, typeOut = false) {
@@ -230,98 +258,20 @@ class TypesGen {
230
258
  #isOptionalType(type) {
231
259
  return type.endsWith('| undefined');
232
260
  }
233
- #includedTypes() {
234
- const { types } = this.metadata;
235
- const pathsCount = new Map();
236
- const typesWithPath = types.filter((one) => one.path.length > 0);
237
- const skipIds = [];
238
- const typeSuffixes = new Map();
239
- typesWithPath.forEach(({ path, id }) => {
240
- const joinedPath = path.join('::');
241
- if (pathsCount.has(joinedPath)) {
242
- // We compare 2 types with the same path here,
243
- // if they are the same type -> skip the current one, keep the first occurrence
244
- // if they are not the same type but has the same path -> we'll try to calculate & add a suffix for the current type name
245
- const firstOccurrenceTypeId = pathsCount.get(joinedPath)[0];
246
- const sameType = this.typeEql(firstOccurrenceTypeId, id);
247
- if (sameType) {
248
- skipIds.push(id);
249
- }
250
- else {
251
- pathsCount.get(joinedPath).push(id);
252
- typeSuffixes.set(id, this.#extractDupTypeSuffix(id, firstOccurrenceTypeId, pathsCount.get(joinedPath).length));
253
- }
254
- }
255
- else {
256
- pathsCount.set(joinedPath, [id]);
257
- }
258
- });
259
- return typesWithPath.reduce((o, type) => {
260
- const { path, id } = type;
261
- const joinedPath = path.join('::');
262
- if (SKIP_TYPES.includes(joinedPath) || SKIP_TYPES.includes(path.at(-1))) {
263
- return o;
264
- }
265
- const suffix = typeSuffixes.get(id) || '';
266
- let knownType = false;
267
- let name, nameOut;
268
- if ((0, known_codecs_js_1.isKnownCodecType)(joinedPath)) {
269
- const codecType = (0, known_codecs_js_1.findKnownCodecType)(path.at(-1));
270
- name = codecType.typeIn;
271
- nameOut = codecType.typeOut;
272
- knownType = true;
273
- }
274
- else if (PATH_RM_INDEX_1.includes(path[1])) {
275
- const newPath = path.slice();
276
- newPath.splice(1, 1);
277
- name = this.#cleanPath(newPath);
278
- }
279
- else {
280
- name = this.#cleanPath(path);
281
- }
282
- if (this.#shouldGenerateTypeIn(id)) {
283
- nameOut = name;
284
- name = name.endsWith('Like') ? name : `${name}Like`;
285
- }
286
- o[id] = {
287
- name: `${name}${suffix}`,
288
- nameOut: nameOut ? `${nameOut}${suffix}` : `${name}${suffix}`,
289
- knownType,
290
- skip: skipIds.includes(id),
291
- ...type,
292
- };
293
- return o;
294
- }, {});
295
- }
296
261
  #removeGenericPart(typeName) {
297
- if (typeName.match(WRAPPER_TYPE_REGEX)) {
298
- return typeName.replace(WRAPPER_TYPE_REGEX, (_, $1) => $1);
262
+ if (typeName.match(utils_js_1.WRAPPER_TYPE_REGEX)) {
263
+ return typeName.replace(utils_js_1.WRAPPER_TYPE_REGEX, (_, $1) => $1);
299
264
  }
300
265
  else {
301
266
  return typeName;
302
267
  }
303
268
  }
304
- /**
305
- * @description Remove duplicated part of the path
306
- *
307
- * Example:
308
- * ["pallet_staking", "pallet", "pallet", "Event"]
309
- * => ["pallet_staking", "pallet", "Event"]
310
- *
311
- * @param path
312
- * @private
313
- */
314
- #cleanPath(path) {
269
+ cleanPath(path) {
315
270
  return path
316
271
  .map((one) => (0, utils_1.stringPascalCase)(one))
317
272
  .filter((one, idx, currentPath) => idx === 0 || one !== currentPath[idx - 1])
318
273
  .join('');
319
274
  }
320
- #shouldGenerateTypeIn(id) {
321
- const { callTypeId } = this.metadata.extrinsic;
322
- const palletCallTypeIds = this.registry.getPalletCallTypeIds();
323
- return callTypeId === id || palletCallTypeIds.includes(id);
324
- }
325
275
  eqlCache = new Map();
326
276
  typeEql(idA, idB, level = 0) {
327
277
  const cacheKey = `${idA}==${idB}`;
@@ -334,36 +284,36 @@ class TypesGen {
334
284
  #typeEql(idA, idB, lvl = 0) {
335
285
  if (idA === idB)
336
286
  return true;
337
- const { types } = this.metadata;
338
- const typeA = types[idA];
339
- const typeB = types[idB];
287
+ const typeA = this.types[idA];
288
+ const typeB = this.types[idB];
340
289
  if (typeA.path.join('::') !== typeB.path.join('::'))
341
290
  return false;
342
- const { type: defA, params: paramsA } = typeA;
343
- const { type: defB, params: paramsB } = typeB;
291
+ const { typeDef: defA, params: paramsA } = typeA;
292
+ const { typeDef: defB, params: paramsB } = typeB;
344
293
  if (!this.#eqlArray(paramsA, paramsB, (valA, valB) => this.#eqlTypeParam(valA, valB))) {
345
294
  return false;
346
295
  }
347
- if (defA.tag !== defB.tag)
296
+ if (defA.type !== defB.type)
348
297
  return false;
349
- if (defA.tag === 'BitSequence')
298
+ if (defA.type === 'BitSequence')
350
299
  return true;
351
- if (defA.tag === 'Primitive' && defB.tag === 'Primitive') {
300
+ if (defA.type === 'Primitive' && defB.type === 'Primitive') {
352
301
  return defA.value.kind === defB.value.kind;
353
302
  }
354
- if ((defA.tag === 'Compact' && defB.tag === 'Compact') || (defA.tag === 'Sequence' && defB.tag === 'Sequence')) {
303
+ if ((defA.type === 'Compact' && defB.type === 'Compact') ||
304
+ (defA.type === 'Sequence' && defB.type === 'Sequence')) {
355
305
  return this.typeEql(defA.value.typeParam, defB.value.typeParam, lvl + 1);
356
306
  }
357
- if (defA.tag === 'SizedVec' && defB.tag === 'SizedVec') {
307
+ if (defA.type === 'SizedVec' && defB.type === 'SizedVec') {
358
308
  return defA.value.len === defB.value.len && this.typeEql(defA.value.typeParam, defB.value.typeParam, lvl + 1);
359
309
  }
360
- if (defA.tag === 'Tuple' && defB.tag === 'Tuple') {
310
+ if (defA.type === 'Tuple' && defB.type === 'Tuple') {
361
311
  return this.#eqlArray(defA.value.fields, defB.value.fields, (val1, val2) => this.typeEql(val1, val2, lvl + 1));
362
312
  }
363
- if (defA.tag === 'Struct' && defB.tag === 'Struct') {
313
+ if (defA.type === 'Struct' && defB.type === 'Struct') {
364
314
  return this.#eqlFields(defA.value.fields, defB.value.fields, lvl);
365
315
  }
366
- if (defA.tag === 'Enum' && defB.tag === 'Enum') {
316
+ if (defA.type === 'Enum' && defB.type === 'Enum') {
367
317
  return this.#eqlArray(defA.value.members, defB.value.members, (val1, val2) => val1.name === val2.name && val1.index === val2.index && this.#eqlFields(val1.fields, val2.fields, lvl));
368
318
  }
369
319
  return false;
@@ -379,19 +329,18 @@ class TypesGen {
379
329
  (param1.typeId === undefined) === (param2.typeId === undefined) &&
380
330
  (param1.typeId === undefined || this.#typeEql(param1.typeId, param2.typeId)));
381
331
  }
382
- #extractDupTypeSuffix(dupTypeId, originalTypeId, dupCount) {
383
- const { types } = this.metadata;
384
- const originalTypeParams = types[originalTypeId].params;
385
- const dupTypeParams = types[dupTypeId].params;
332
+ extractDupTypeSuffix(dupTypeId, originalTypeId, dupCount) {
333
+ const originalTypeParams = this.types[originalTypeId].params;
334
+ const dupTypeParams = this.types[dupTypeId].params;
386
335
  const diffParam = dupTypeParams.find((one, idx) => !this.#eqlTypeParam(one, originalTypeParams[idx]));
387
336
  // TODO make sure these suffix is unique if a type is duplicated more than 2 times
388
337
  if (diffParam?.typeId) {
389
- const diffType = types[diffParam.typeId];
338
+ const diffType = this.types[diffParam.typeId];
390
339
  if (diffType.path.length > 0) {
391
340
  return (0, utils_1.stringPascalCase)(diffType.path.at(-1));
392
341
  }
393
- else if (diffType.type.tag === 'Primitive') {
394
- return (0, utils_1.stringPascalCase)(diffType.type.value.kind);
342
+ else if (diffType.typeDef.type === 'Primitive') {
343
+ return (0, utils_1.stringPascalCase)(diffType.typeDef.value.kind);
395
344
  }
396
345
  }
397
346
  // Last resort!
@@ -426,5 +375,8 @@ class TypesGen {
426
375
  }
427
376
  this.typeImports.addOutType(typeName);
428
377
  }
378
+ getEnumOptions(_typeId) {
379
+ return { tagKey: 'type', valueKey: 'value' };
380
+ }
429
381
  }
430
- exports.TypesGen = TypesGen;
382
+ exports.BaseTypesGen = BaseTypesGen;
@@ -11,12 +11,18 @@ class TypeImports {
11
11
  knownJsonRpcTypes;
12
12
  // External types to define explicitly
13
13
  outTypes;
14
+ // Know types defined in @dedot/contracts
15
+ contractTypes;
16
+ // Know types defined in @dedot/api/chaintypes or dedot/chaintypes
17
+ chainTypes;
14
18
  constructor() {
15
19
  this.portableTypes = new Set();
16
20
  this.codecTypes = new Set();
17
21
  this.knownTypes = new Set();
18
22
  this.knownJsonRpcTypes = new Set();
19
23
  this.outTypes = new Set();
24
+ this.contractTypes = new Set();
25
+ this.chainTypes = new Set();
20
26
  }
21
27
  clear() {
22
28
  this.portableTypes.clear();
@@ -24,6 +30,8 @@ class TypeImports {
24
30
  this.knownTypes.clear();
25
31
  this.knownJsonRpcTypes.clear();
26
32
  this.outTypes.clear();
33
+ this.contractTypes.clear();
34
+ this.chainTypes.clear();
27
35
  }
28
36
  toImports(config) {
29
37
  const { excludeModules = [], useSubPaths = false } = config || {};
@@ -33,6 +41,8 @@ class TypeImports {
33
41
  [this.knownTypes, `${prefix}dedot/types`],
34
42
  [this.knownJsonRpcTypes, `${prefix}dedot/types/json-rpc`],
35
43
  [this.codecTypes, `${prefix}dedot/codecs`],
44
+ [this.contractTypes, `${prefix}dedot/contracts`],
45
+ [this.chainTypes, prefix ? '@dedot/api/chaintypes' : 'dedot/chaintypes'],
36
46
  [this.portableTypes, './types'],
37
47
  ];
38
48
  return toImports
@@ -62,5 +72,11 @@ class TypeImports {
62
72
  addOutType(...types) {
63
73
  types.forEach((one) => this.outTypes.add(one));
64
74
  }
75
+ addContractType(...types) {
76
+ types.forEach((one) => this.contractTypes.add(one));
77
+ }
78
+ addChainType(...types) {
79
+ types.forEach((one) => this.chainTypes.add(one));
80
+ }
65
81
  }
66
82
  exports.TypeImports = TypeImports;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./BaseTypesGen.js"), exports);
18
+ __exportStar(require("./known-codecs.js"), exports);
19
+ __exportStar(require("./TypeImports.js"), exports);
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.isKnownCodecType = exports.findKnownWrapperCodec = exports.findKnownCodec = exports.findKnownCodecType = exports.looseTypeCodecs = exports.normalizeCodecName = void 0;
26
+ exports.checkKnownCodecType = exports.findKnownWrapperCodec = exports.findKnownCodec = exports.findKnownCodecType = exports.looseTypeCodecs = exports.normalizeCodecName = void 0;
27
27
  const Codecs = __importStar(require("@dedot/codecs"));
28
28
  const codecs_1 = require("@dedot/codecs");
29
29
  const $ = __importStar(require("@dedot/shape"));
@@ -57,6 +57,8 @@ const KNOWN_PATHS = [
57
57
  /^primitive_types::\w+$/,
58
58
  /^sp_arithmetic::per_things::\w+$/,
59
59
  /^sp_arithmetic::fixed_point::\w+$/,
60
+ 'ink_primitives::types::Hash',
61
+ { path: 'ink_primitives::types::AccountId', codec: 'AccountId32' },
60
62
  ];
61
63
  const WRAPPER_TYPE_REGEX = /^(\w+)<(.*)>$/;
62
64
  const TUPLE_TYPE_REGEX = /^\[(.*)]$/;
@@ -144,8 +146,25 @@ function findKnownWrapperCodec(typeName) {
144
146
  }
145
147
  }
146
148
  exports.findKnownWrapperCodec = findKnownWrapperCodec;
147
- function isKnownCodecType(path) {
149
+ function checkKnownCodecType(path) {
148
150
  const joinedPath = Array.isArray(path) ? path.join('::') : path;
149
- return KNOWN_PATHS.some((one) => joinedPath.match(one));
151
+ const knownPath = KNOWN_PATHS.find((one) => {
152
+ if (typeof one === 'string') {
153
+ return one === joinedPath;
154
+ }
155
+ else if (one instanceof RegExp) {
156
+ return one.test(joinedPath);
157
+ }
158
+ else {
159
+ return one.path === joinedPath;
160
+ }
161
+ });
162
+ if (!knownPath) {
163
+ return [false, ''];
164
+ }
165
+ if (typeof knownPath === 'string' || knownPath instanceof RegExp) {
166
+ return [true, joinedPath.split('::').at(-1)];
167
+ }
168
+ return [true, knownPath.codec];
150
169
  }
151
- exports.isKnownCodecType = isKnownCodecType;
170
+ exports.checkKnownCodecType = checkKnownCodecType;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConstructorQueryGen = void 0;
4
+ const utils_js_1 = require("../../utils.js");
5
+ const QueryGen_js_1 = require("./QueryGen.js");
6
+ class ConstructorQueryGen extends QueryGen_js_1.QueryGen {
7
+ generate(useSubPaths = false) {
8
+ this.typesGen.clearCache();
9
+ this.typesGen.typeImports.addKnownType('GenericSubstrateApi');
10
+ this.typesGen.typeImports.addContractType('GenericConstructorQuery', 'GenericConstructorQueryCall', 'ConstructorCallOptions', 'ContractInstantiateResult');
11
+ const { constructors } = this.contractMetadata.spec;
12
+ const constructorsOut = this.doGenerate(constructors, 'ConstructorCallOptions');
13
+ const importTypes = this.typesGen.typeImports.toImports({ useSubPaths });
14
+ const template = (0, utils_js_1.compileTemplate)('typink/templates/constructor-query.hbs');
15
+ return (0, utils_js_1.beautifySourceCode)(template({ importTypes, constructorsOut }));
16
+ }
17
+ generateMethodDef(def) {
18
+ const { args } = def;
19
+ args.forEach(({ type: { type } }) => this.importType(type));
20
+ const paramsOut = this.generateParamsOut(args);
21
+ return `GenericConstructorQueryCall<ChainApi, (${paramsOut && `${paramsOut},`} options: ConstructorCallOptions) => Promise<ContractInstantiateResult<ChainApi>>>`;
22
+ }
23
+ }
24
+ exports.ConstructorQueryGen = ConstructorQueryGen;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConstructorTxGen = void 0;
4
+ const utils_js_1 = require("../../utils.js");
5
+ const QueryGen_js_1 = require("./QueryGen.js");
6
+ class ConstructorTxGen extends QueryGen_js_1.QueryGen {
7
+ generate(useSubPaths = false) {
8
+ this.typesGen.clearCache();
9
+ this.typesGen.typeImports.addKnownType('GenericSubstrateApi');
10
+ this.typesGen.typeImports.addContractType('GenericConstructorTx', 'GenericConstructorTxCall', 'ConstructorTxOptions', 'GenericInstantiateSubmittableExtrinsic');
11
+ const { constructors } = this.contractMetadata.spec;
12
+ const constructorsOut = this.doGenerate(constructors, 'ConstructorTxOptions');
13
+ const importTypes = this.typesGen.typeImports.toImports({ useSubPaths });
14
+ const template = (0, utils_js_1.compileTemplate)('typink/templates/constructor-tx.hbs');
15
+ return (0, utils_js_1.beautifySourceCode)(template({ importTypes, constructorsOut }));
16
+ }
17
+ generateMethodDef(def) {
18
+ const { args } = def;
19
+ args.forEach(({ type: { type } }) => this.importType(type));
20
+ const paramsOut = this.generateParamsOut(args);
21
+ return `GenericConstructorTxCall<ChainApi, (${paramsOut && `${paramsOut},`} options: ConstructorTxOptions) => GenericInstantiateSubmittableExtrinsic<ChainApi>>`;
22
+ }
23
+ }
24
+ exports.ConstructorTxGen = ConstructorTxGen;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.IndexGen = void 0;
4
+ const utils_1 = require("@dedot/utils");
5
+ const index_js_1 = require("../../shared/index.js");
6
+ const utils_js_1 = require("../../utils.js");
7
+ const SUFFIX = 'contract_api';
8
+ class IndexGen {
9
+ contractMetadata;
10
+ constructor(contractMetadata) {
11
+ this.contractMetadata = contractMetadata;
12
+ }
13
+ generate(useSubPaths = false) {
14
+ const contractName = (0, utils_1.stringPascalCase)(`${this.contractMetadata.contract.name}_${SUFFIX}`);
15
+ const typeImports = new index_js_1.TypeImports();
16
+ typeImports.addKnownType('VersionedGenericSubstrateApi', 'RpcVersion', 'RpcV2');
17
+ typeImports.addContractType('GenericContractApi');
18
+ typeImports.addChainType('SubstrateApi');
19
+ const importTypes = typeImports.toImports({ useSubPaths });
20
+ const template = (0, utils_js_1.compileTemplate)('typink/templates/index.hbs');
21
+ return (0, utils_js_1.beautifySourceCode)(template({ contractName, importTypes }));
22
+ }
23
+ }
24
+ exports.IndexGen = IndexGen;
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QueryGen = void 0;
4
+ const contracts_1 = require("@dedot/contracts");
5
+ const utils_1 = require("@dedot/utils");
6
+ const utils_js_1 = require("../../utils.js");
7
+ class QueryGen {
8
+ contractMetadata;
9
+ typesGen;
10
+ constructor(contractMetadata, typeGen) {
11
+ this.contractMetadata = contractMetadata;
12
+ this.typesGen = typeGen;
13
+ }
14
+ generate(useSubPaths = false) {
15
+ this.typesGen.clearCache();
16
+ this.typesGen.typeImports.addKnownType('GenericSubstrateApi');
17
+ this.typesGen.typeImports.addContractType('GenericContractQuery', 'GenericContractQueryCall', 'ContractCallOptions', 'GenericContractCallResult', 'ContractCallResult');
18
+ const { messages } = this.contractMetadata.spec;
19
+ const queryCallsOut = this.doGenerate(messages, 'ContractCallOptions');
20
+ const importTypes = this.typesGen.typeImports.toImports({ useSubPaths });
21
+ const template = (0, utils_js_1.compileTemplate)('typink/templates/query.hbs');
22
+ return (0, utils_js_1.beautifySourceCode)(template({ importTypes, queryCallsOut }));
23
+ }
24
+ doGenerate(messages, optionsTypeName) {
25
+ let callsOut = '';
26
+ messages.forEach((messageDef) => {
27
+ const { label, docs, selector, args } = messageDef;
28
+ callsOut += `${(0, utils_js_1.commentBlock)(docs, '\n', args.map((arg) => `@param {${this.typesGen.generateType(arg.type.type, 1)}} ${(0, utils_1.stringCamelCase)(arg.label)}`), optionsTypeName ? `@param {${optionsTypeName}} options` : '', '\n', `@selector ${selector}`)}`;
29
+ callsOut += `${(0, contracts_1.normalizeLabel)(label)}: ${this.generateMethodDef(messageDef)};\n\n`;
30
+ });
31
+ return callsOut;
32
+ }
33
+ generateMethodDef(def) {
34
+ const { args, returnType } = def;
35
+ this.importType(returnType.type);
36
+ args.forEach(({ type: { type } }) => this.importType(type));
37
+ const paramsOut = this.generateParamsOut(args);
38
+ const typeOut = this.typesGen.generateType(returnType.type, 0, true);
39
+ return `GenericContractQueryCall<ChainApi, (${paramsOut && `${paramsOut},`} options: ContractCallOptions) => Promise<GenericContractCallResult<${typeOut}, ContractCallResult<ChainApi>>>>`;
40
+ }
41
+ generateParamsOut(args) {
42
+ return args
43
+ .map(({ type: { type }, label }) => `${(0, utils_1.stringCamelCase)(label)}: ${this.typesGen.generateType(type, 1)}`)
44
+ .join(', ');
45
+ }
46
+ importType(typeId) {
47
+ const contractType = this.contractMetadata.types[typeId];
48
+ const typeDef = (0, contracts_1.normalizeContractTypeDef)(this.contractMetadata.types[typeId].type.def);
49
+ if (this.typesGen.includedTypes[contractType.id]) {
50
+ this.typesGen.addTypeImport(this.typesGen.includedTypes[contractType.id].name);
51
+ return;
52
+ }
53
+ const { type, value } = typeDef;
54
+ switch (type) {
55
+ case 'Compact':
56
+ case 'Primitive':
57
+ case 'BitSequence':
58
+ return;
59
+ case 'Struct':
60
+ return value.fields.forEach(({ typeId }) => this.importType(typeId));
61
+ case 'Enum':
62
+ return value.members.forEach(({ fields }) => fields.map(({ typeId }) => this.importType(typeId)).flat());
63
+ case 'Tuple':
64
+ return value.fields.forEach((typeId) => this.importType(typeId));
65
+ case 'SizedVec':
66
+ return this.importType(value.typeParam);
67
+ case 'Sequence':
68
+ return this.importType(value.typeParam);
69
+ }
70
+ }
71
+ }
72
+ exports.QueryGen = QueryGen;