@dedot/codegen 0.0.1-next.9dacef43.1 → 0.0.1-next.a5b1d2fb.22

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 (154) hide show
  1. package/{generator → chaintypes/generator}/ApiGen.d.ts +2 -2
  2. package/chaintypes/generator/ConstsGen.d.ts +4 -0
  3. package/{generator → chaintypes/generator}/ConstsGen.js +8 -9
  4. package/chaintypes/generator/ErrorsGen.d.ts +5 -0
  5. package/{generator → chaintypes/generator}/ErrorsGen.js +9 -10
  6. package/chaintypes/generator/EventsGen.d.ts +5 -0
  7. package/{generator → chaintypes/generator}/EventsGen.js +9 -10
  8. package/chaintypes/generator/IndexGen.d.ts +5 -0
  9. package/chaintypes/generator/IndexGen.js +17 -0
  10. package/chaintypes/generator/JsonRpcGen.d.ts +8 -0
  11. package/chaintypes/generator/JsonRpcGen.js +55 -0
  12. package/chaintypes/generator/QueryGen.d.ts +5 -0
  13. package/{generator → chaintypes/generator}/QueryGen.js +24 -16
  14. package/chaintypes/generator/RuntimeApisGen.d.ts +9 -0
  15. package/chaintypes/generator/RuntimeApisGen.js +189 -0
  16. package/chaintypes/generator/TxGen.d.ts +5 -0
  17. package/{generator → chaintypes/generator}/TxGen.js +14 -12
  18. package/chaintypes/generator/TypesGen.d.ts +11 -0
  19. package/chaintypes/generator/TypesGen.js +55 -0
  20. package/chaintypes/generator/index.d.ts +10 -0
  21. package/chaintypes/generator/index.js +10 -0
  22. package/chaintypes/index.d.ts +3 -0
  23. package/chaintypes/index.js +49 -0
  24. package/chaintypes/templates/consts.hbs +7 -0
  25. package/chaintypes/templates/errors.hbs +7 -0
  26. package/chaintypes/templates/events.hbs +7 -0
  27. package/chaintypes/templates/index.hbs +27 -0
  28. package/chaintypes/templates/json-rpc.hbs +5 -0
  29. package/chaintypes/templates/query.hbs +7 -0
  30. package/chaintypes/templates/runtime.hbs +8 -0
  31. package/chaintypes/templates/tx.hbs +9 -0
  32. package/{cjs → chaintypes}/templates/types.hbs +1 -1
  33. package/cjs/{generator → chaintypes/generator}/ConstsGen.js +12 -13
  34. package/cjs/chaintypes/generator/ErrorsGen.js +40 -0
  35. package/cjs/{generator → chaintypes/generator}/EventsGen.js +16 -17
  36. package/cjs/chaintypes/generator/IndexGen.js +21 -0
  37. package/cjs/chaintypes/generator/JsonRpcGen.js +59 -0
  38. package/cjs/{generator → chaintypes/generator}/QueryGen.js +26 -18
  39. package/cjs/chaintypes/generator/RuntimeApisGen.js +193 -0
  40. package/cjs/{generator → chaintypes/generator}/TxGen.js +23 -21
  41. package/cjs/chaintypes/generator/TypesGen.js +59 -0
  42. package/cjs/chaintypes/generator/index.js +26 -0
  43. package/cjs/chaintypes/index.js +76 -0
  44. package/cjs/chaintypes/templates/consts.hbs +7 -0
  45. package/cjs/chaintypes/templates/errors.hbs +7 -0
  46. package/cjs/chaintypes/templates/events.hbs +7 -0
  47. package/cjs/chaintypes/templates/index.hbs +27 -0
  48. package/cjs/chaintypes/templates/json-rpc.hbs +5 -0
  49. package/cjs/chaintypes/templates/query.hbs +7 -0
  50. package/cjs/chaintypes/templates/runtime.hbs +8 -0
  51. package/cjs/chaintypes/templates/tx.hbs +9 -0
  52. package/{templates → cjs/chaintypes/templates}/types.hbs +1 -1
  53. package/cjs/{generator/dirname.js → dirname.js} +0 -1
  54. package/cjs/index.js +4 -62
  55. package/cjs/{generator/TypesGen.js → shared/BaseTypesGen.js} +102 -160
  56. package/cjs/{generator → shared}/TypeImports.js +29 -3
  57. package/cjs/{generator → shared}/index.js +3 -10
  58. package/cjs/shared/known-codecs.js +170 -0
  59. package/cjs/typink/generator/ConstructorQueryGen.js +24 -0
  60. package/cjs/typink/generator/ConstructorTxGen.js +24 -0
  61. package/cjs/typink/generator/IndexGen.js +24 -0
  62. package/cjs/typink/generator/QueryGen.js +72 -0
  63. package/cjs/typink/generator/TxGen.js +25 -0
  64. package/cjs/typink/generator/TypesGen.js +35 -0
  65. package/cjs/typink/generator/index.js +22 -0
  66. package/cjs/typink/index.js +36 -0
  67. package/cjs/typink/templates/constructor-query.hbs +7 -0
  68. package/cjs/typink/templates/constructor-tx.hbs +7 -0
  69. package/cjs/typink/templates/index.hbs +14 -0
  70. package/cjs/typink/templates/query.hbs +7 -0
  71. package/cjs/typink/templates/tx.hbs +7 -0
  72. package/cjs/typink/templates/types.hbs +5 -0
  73. package/cjs/{generator/utils.js → utils.js} +34 -5
  74. package/index.d.ts +2 -4
  75. package/index.js +2 -48
  76. package/package.json +16 -18
  77. package/{generator/TypesGen.d.ts → shared/BaseTypesGen.d.ts} +13 -12
  78. package/{generator/TypesGen.js → shared/BaseTypesGen.js} +89 -147
  79. package/{generator → shared}/TypeImports.d.ts +12 -1
  80. package/{generator → shared}/TypeImports.js +29 -3
  81. package/shared/index.d.ts +3 -0
  82. package/shared/index.js +3 -0
  83. package/shared/known-codecs.d.ts +23 -0
  84. package/shared/known-codecs.js +139 -0
  85. package/typink/generator/ConstructorQueryGen.d.ts +6 -0
  86. package/typink/generator/ConstructorQueryGen.js +20 -0
  87. package/typink/generator/ConstructorTxGen.d.ts +6 -0
  88. package/typink/generator/ConstructorTxGen.js +20 -0
  89. package/typink/generator/IndexGen.d.ts +6 -0
  90. package/typink/generator/IndexGen.js +20 -0
  91. package/typink/generator/QueryGen.d.ts +12 -0
  92. package/typink/generator/QueryGen.js +68 -0
  93. package/typink/generator/TxGen.d.ts +6 -0
  94. package/typink/generator/TxGen.js +21 -0
  95. package/typink/generator/TypesGen.d.ts +8 -0
  96. package/typink/generator/TypesGen.js +31 -0
  97. package/typink/generator/index.d.ts +6 -0
  98. package/typink/generator/index.js +6 -0
  99. package/typink/index.d.ts +2 -0
  100. package/typink/index.js +30 -0
  101. package/typink/templates/constructor-query.hbs +7 -0
  102. package/typink/templates/constructor-tx.hbs +7 -0
  103. package/typink/templates/index.hbs +14 -0
  104. package/typink/templates/query.hbs +7 -0
  105. package/typink/templates/tx.hbs +7 -0
  106. package/typink/templates/types.hbs +5 -0
  107. package/{generator/utils.d.ts → utils.d.ts} +6 -1
  108. package/{generator/utils.js → utils.js} +32 -4
  109. package/cjs/genSupportedChainTypes.js +0 -79
  110. package/cjs/generator/ErrorsGen.js +0 -41
  111. package/cjs/generator/IndexGen.js +0 -18
  112. package/cjs/generator/RpcGen.js +0 -175
  113. package/cjs/generator/RuntimeApisGen.js +0 -115
  114. package/cjs/packageInfo.js +0 -5
  115. package/cjs/templates/consts.hbs +0 -7
  116. package/cjs/templates/errors.hbs +0 -7
  117. package/cjs/templates/events.hbs +0 -7
  118. package/cjs/templates/index.hbs +0 -22
  119. package/cjs/templates/query.hbs +0 -7
  120. package/cjs/templates/rpc.hbs +0 -7
  121. package/cjs/templates/runtime.hbs +0 -8
  122. package/cjs/templates/tx.hbs +0 -9
  123. package/cjs/types.js +0 -2
  124. package/genSupportedChainTypes.d.ts +0 -1
  125. package/genSupportedChainTypes.js +0 -74
  126. package/generator/ConstsGen.d.ts +0 -4
  127. package/generator/ErrorsGen.d.ts +0 -5
  128. package/generator/EventsGen.d.ts +0 -5
  129. package/generator/IndexGen.d.ts +0 -6
  130. package/generator/IndexGen.js +0 -14
  131. package/generator/QueryGen.d.ts +0 -5
  132. package/generator/RpcGen.d.ts +0 -10
  133. package/generator/RpcGen.js +0 -171
  134. package/generator/RuntimeApisGen.d.ts +0 -9
  135. package/generator/RuntimeApisGen.js +0 -111
  136. package/generator/TxGen.d.ts +0 -5
  137. package/generator/index.d.ts +0 -10
  138. package/generator/index.js +0 -10
  139. package/packageInfo.d.ts +0 -4
  140. package/packageInfo.js +0 -2
  141. package/templates/consts.hbs +0 -7
  142. package/templates/errors.hbs +0 -7
  143. package/templates/events.hbs +0 -7
  144. package/templates/index.hbs +0 -22
  145. package/templates/query.hbs +0 -7
  146. package/templates/rpc.hbs +0 -7
  147. package/templates/runtime.hbs +0 -8
  148. package/templates/tx.hbs +0 -9
  149. package/types.d.ts +0 -6
  150. package/types.js +0 -1
  151. /package/{generator → chaintypes/generator}/ApiGen.js +0 -0
  152. /package/cjs/{generator → chaintypes/generator}/ApiGen.js +0 -0
  153. /package/{generator/dirname.d.ts → dirname.d.ts} +0 -0
  154. /package/{generator/dirname.js → dirname.js} +0 -0
@@ -1,69 +1,93 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TypesGen = exports.BASIC_KNOWN_TYPES = void 0;
4
- const util_1 = require("@polkadot/util");
5
- const codecs_1 = require("@dedot/codecs");
3
+ exports.BaseTypesGen = exports.BASIC_KNOWN_TYPES = void 0;
6
4
  const utils_1 = require("@dedot/utils");
7
- const utils_2 = require("./utils");
8
- const types_1 = require("@dedot/types");
9
- const TypeImports_1 = require("./TypeImports");
10
- // Skip generate types for these
11
- // as we do have native types for them
12
- const SKIP_TYPES = [
13
- 'BoundedBTreeMap',
14
- 'BoundedBTreeSet',
15
- 'BoundedVec',
16
- 'Box',
17
- 'BTreeMap',
18
- 'BTreeSet',
19
- 'Cow',
20
- 'Option',
21
- 'Range',
22
- 'RangeInclusive',
23
- 'Result',
24
- 'WeakBoundedVec',
25
- 'WrapperKeepOpaque',
26
- 'WrapperOpaque',
27
- ];
5
+ const utils_js_1 = require("../utils.js");
6
+ const TypeImports_js_1 = require("./TypeImports.js");
7
+ const known_codecs_js_1 = require("./known-codecs.js");
28
8
  // These are common & generic types, so we'll remove these from all paths at index 1
29
9
  // This helps make the type name shorter
30
10
  const PATH_RM_INDEX_1 = ['generic', 'misc', 'pallet', 'traits', 'types'];
31
11
  exports.BASIC_KNOWN_TYPES = ['BitSequence', 'Bytes', 'BytesLike', 'FixedBytes', 'FixedArray', 'Result'];
32
- const WRAPPER_TYPE_REGEX = /^(\w+)(<.*>)$/g;
33
- class TypesGen {
34
- metadata;
35
- /**
36
- * Types will be generated its definition out.
37
- */
12
+ class BaseTypesGen {
13
+ types;
38
14
  includedTypes;
39
- registry;
40
15
  typeImports;
41
- constructor(metadata) {
42
- this.metadata = metadata;
43
- this.registry = new codecs_1.CodecRegistry(this.metadata);
44
- this.includedTypes = this.#includedTypes();
45
- this.typeImports = new TypeImports_1.TypeImports();
46
- }
47
- generate() {
48
- this.clearCache();
49
- let defTypeOut = '';
50
- Object.values(this.includedTypes)
51
- .filter(({ skip, knownType }) => !(skip || knownType))
52
- .forEach(({ name, nameOut, id, docs }) => {
53
- defTypeOut += `${(0, utils_2.commentBlock)(docs)}export type ${nameOut} = ${this.generateType(id, 0, true)};\n\n`;
54
- if (this.#shouldGenerateTypeIn(id)) {
55
- defTypeOut += `export type ${name} = ${this.generateType(id)};\n\n`;
56
- }
57
- });
58
- const importTypes = this.typeImports.toImports('./types');
59
- const template = (0, utils_2.compileTemplate)('types.hbs');
60
- return (0, utils_2.beautifySourceCode)(template({ importTypes, defTypeOut }));
16
+ skipTypes;
17
+ constructor(types) {
18
+ this.types = types;
19
+ this.includedTypes = {};
20
+ this.typeImports = new TypeImports_js_1.TypeImports();
21
+ this.skipTypes = [];
61
22
  }
62
23
  typeCache = {};
63
24
  clearCache() {
64
25
  this.typeCache = {};
65
26
  this.typeImports.clear();
66
27
  }
28
+ includeTypes() {
29
+ const pathsCount = new Map();
30
+ const typesWithPath = this.types.filter((one) => one.path.length > 0);
31
+ const skipIds = [];
32
+ const typeSuffixes = new Map();
33
+ typesWithPath.forEach(({ path, id }) => {
34
+ const joinedPath = path.join('::');
35
+ if (pathsCount.has(joinedPath)) {
36
+ // We compare 2 types with the same path here,
37
+ // if they are the same type -> skip the current one, keep the first occurrence
38
+ // 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
39
+ const firstOccurrenceTypeId = pathsCount.get(joinedPath)[0];
40
+ const sameType = this.typeEql(firstOccurrenceTypeId, id);
41
+ if (sameType) {
42
+ skipIds.push(id);
43
+ }
44
+ else {
45
+ pathsCount.get(joinedPath).push(id);
46
+ typeSuffixes.set(id, this.extractDupTypeSuffix(id, firstOccurrenceTypeId, pathsCount.get(joinedPath).length));
47
+ }
48
+ }
49
+ else {
50
+ pathsCount.set(joinedPath, [id]);
51
+ }
52
+ });
53
+ return typesWithPath.reduce((o, type) => {
54
+ const { path, id } = type;
55
+ const joinedPath = path.join('::');
56
+ if (this.skipTypes.includes(joinedPath) || this.skipTypes.includes(path.at(-1))) {
57
+ return o;
58
+ }
59
+ const suffix = typeSuffixes.get(id) || '';
60
+ let knownType = false;
61
+ let name, nameOut;
62
+ const [isKnownCodecType, codecName] = (0, known_codecs_js_1.checkKnownCodecType)(joinedPath);
63
+ if (isKnownCodecType) {
64
+ const codecType = (0, known_codecs_js_1.findKnownCodecType)(codecName);
65
+ name = codecType.typeIn;
66
+ nameOut = codecType.typeOut;
67
+ knownType = true;
68
+ }
69
+ else if (PATH_RM_INDEX_1.includes(path[1])) {
70
+ const newPath = path.slice();
71
+ newPath.splice(1, 1);
72
+ name = this.cleanPath(newPath);
73
+ }
74
+ else {
75
+ name = this.cleanPath(path);
76
+ }
77
+ if (this.shouldGenerateTypeIn(id)) {
78
+ nameOut = name;
79
+ name = name.endsWith('Like') ? name : `${name}Like`;
80
+ }
81
+ o[id] = {
82
+ name: `${name}${suffix}`,
83
+ nameOut: nameOut ? `${nameOut}${suffix}` : `${name}${suffix}`,
84
+ knownType,
85
+ skip: skipIds.includes(id),
86
+ ...type,
87
+ };
88
+ return o;
89
+ }, {});
90
+ }
67
91
  generateType(typeId, nestedLevel = 0, typeOut = false) {
68
92
  if (nestedLevel > 0) {
69
93
  const includedDef = this.includedTypes[typeId];
@@ -94,7 +118,7 @@ class TypesGen {
94
118
  return type;
95
119
  }
96
120
  #generateType(typeId, nestedLevel = 0, typeOut = false) {
97
- const def = this.metadata.types[typeId];
121
+ const def = this.types[typeId];
98
122
  if (!def) {
99
123
  throw new Error(`Type def not found ${JSON.stringify(def)}`);
100
124
  }
@@ -102,7 +126,7 @@ class TypesGen {
102
126
  const { tag, value } = type;
103
127
  switch (tag) {
104
128
  case 'Primitive':
105
- const $codec = this.registry.findCodec(value.kind);
129
+ const $codec = (0, known_codecs_js_1.findKnownCodec)(value.kind);
106
130
  if ($codec.nativeType) {
107
131
  return $codec.nativeType;
108
132
  }
@@ -150,12 +174,12 @@ class TypesGen {
150
174
  return 'null';
151
175
  }
152
176
  else if (members.every((x) => x.fields.length === 0)) {
153
- return members.map(({ name, docs }) => `${(0, utils_2.commentBlock)(docs)}'${(0, util_1.stringPascalCase)(name)}'`).join(' | ');
177
+ return members.map(({ name, docs }) => `${(0, utils_js_1.commentBlock)(docs)}'${(0, utils_1.stringPascalCase)(name)}'`).join(' | ');
154
178
  }
155
179
  else {
156
180
  const membersType = [];
157
181
  for (const { fields, name, docs } of members) {
158
- const keyName = (0, util_1.stringPascalCase)(name);
182
+ const keyName = (0, utils_1.stringPascalCase)(name);
159
183
  if (fields.length === 0) {
160
184
  membersType.push([keyName, null, docs]);
161
185
  }
@@ -163,7 +187,7 @@ class TypesGen {
163
187
  const valueType = fields.length === 1
164
188
  ? this.generateType(fields[0].typeId, nestedLevel + 1, typeOut)
165
189
  : `[${fields
166
- .map(({ typeId, docs }) => `${(0, utils_2.commentBlock)(docs)}${this.generateType(typeId, nestedLevel + 1, typeOut)}`)
190
+ .map(({ typeId, docs }) => `${(0, utils_js_1.commentBlock)(docs)}${this.generateType(typeId, nestedLevel + 1, typeOut)}`)
167
191
  .join(', ')}]`;
168
192
  membersType.push([keyName, valueType, docs]);
169
193
  }
@@ -171,14 +195,14 @@ class TypesGen {
171
195
  membersType.push([keyName, this.generateObjectType(fields, nestedLevel + 1, typeOut), docs]);
172
196
  }
173
197
  }
174
- const { tagKey, valueKey } = this.registry.portableRegistry.getEnumOptions(typeId);
198
+ const { tagKey, valueKey } = this.getEnumOptions(typeId);
175
199
  return membersType
176
200
  .map(([keyName, valueType, docs]) => ({
177
201
  tag: `${tagKey}: '${keyName}'`,
178
202
  value: valueType ? `, ${valueKey}${this.#isOptionalType(valueType) ? '?' : ''}: ${valueType} ` : '',
179
203
  docs,
180
204
  }))
181
- .map(({ tag, value, docs }) => `${(0, utils_2.commentBlock)(docs)}{ ${tag}${value} }`)
205
+ .map(({ tag, value, docs }) => `${(0, utils_js_1.commentBlock)(docs)}{ ${tag}${value} }`)
182
206
  .join(' | ');
183
207
  }
184
208
  }
@@ -201,7 +225,7 @@ class TypesGen {
201
225
  case 'Sequence':
202
226
  case 'SizedVec': {
203
227
  const fixedSize = tag === 'SizedVec' ? `${value.len}` : null;
204
- const $innerType = this.metadata.types[value.typeParam].type;
228
+ const $innerType = this.types[value.typeParam].type;
205
229
  if ($innerType.tag === 'Primitive' && $innerType.value.kind === 'u8') {
206
230
  return fixedSize ? `FixedBytes<${fixedSize}>` : typeOut ? 'Bytes' : 'BytesLike';
207
231
  }
@@ -225,104 +249,26 @@ class TypesGen {
225
249
  };
226
250
  });
227
251
  return `{${props
228
- .map(({ name, type, optional, docs }) => `${(0, utils_2.commentBlock)(docs)}${name}${optional ? '?' : ''}: ${type}`)
252
+ .map(({ name, type, optional, docs }) => `${(0, utils_js_1.commentBlock)(docs)}${name}${optional ? '?' : ''}: ${type}`)
229
253
  .join(',\n')}}`;
230
254
  }
231
255
  #isOptionalType(type) {
232
256
  return type.endsWith('| undefined');
233
257
  }
234
- #includedTypes() {
235
- const { types } = this.metadata;
236
- const pathsCount = new Map();
237
- const typesWithPath = types.filter((one) => one.path.length > 0);
238
- const skipIds = [];
239
- const typeSuffixes = new Map();
240
- typesWithPath.forEach(({ path, id }) => {
241
- const joinedPath = path.join('::');
242
- if (pathsCount.has(joinedPath)) {
243
- // We compare 2 types with the same path here,
244
- // if they are the same type -> skip the current one, keep the first occurrence
245
- // 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
246
- const firstOccurrenceTypeId = pathsCount.get(joinedPath)[0];
247
- const sameType = this.typeEql(firstOccurrenceTypeId, id);
248
- if (sameType) {
249
- skipIds.push(id);
250
- }
251
- else {
252
- pathsCount.get(joinedPath).push(id);
253
- typeSuffixes.set(id, this.#extractDupTypeSuffix(id, firstOccurrenceTypeId, pathsCount.get(joinedPath).length));
254
- }
255
- }
256
- else {
257
- pathsCount.set(joinedPath, [id]);
258
- }
259
- });
260
- return typesWithPath.reduce((o, type) => {
261
- const { path, id } = type;
262
- const joinedPath = path.join('::');
263
- if (SKIP_TYPES.includes(joinedPath) || SKIP_TYPES.includes(path.at(-1))) {
264
- return o;
265
- }
266
- const suffix = typeSuffixes.get(id) || '';
267
- let knownType = false;
268
- let name, nameOut;
269
- if (this.registry.isKnownType(joinedPath)) {
270
- const codecType = this.registry.findCodecType(path.at(-1));
271
- name = codecType.typeIn;
272
- nameOut = codecType.typeOut;
273
- knownType = true;
274
- }
275
- else if (PATH_RM_INDEX_1.includes(path[1])) {
276
- const newPath = path.slice();
277
- newPath.splice(1, 1);
278
- name = this.#cleanPath(newPath);
279
- }
280
- else {
281
- name = this.#cleanPath(path);
282
- }
283
- if (this.#shouldGenerateTypeIn(id)) {
284
- nameOut = name;
285
- name = name.endsWith('Like') ? name : `${name}Like`;
286
- }
287
- o[id] = {
288
- name: `${name}${suffix}`,
289
- nameOut: nameOut ? `${nameOut}${suffix}` : `${name}${suffix}`,
290
- knownType,
291
- skip: skipIds.includes(id),
292
- ...type,
293
- };
294
- return o;
295
- }, {});
296
- }
297
258
  #removeGenericPart(typeName) {
298
- if (typeName.match(WRAPPER_TYPE_REGEX)) {
299
- return typeName.replace(WRAPPER_TYPE_REGEX, (_, $1) => $1);
259
+ if (typeName.match(utils_js_1.WRAPPER_TYPE_REGEX)) {
260
+ return typeName.replace(utils_js_1.WRAPPER_TYPE_REGEX, (_, $1) => $1);
300
261
  }
301
262
  else {
302
263
  return typeName;
303
264
  }
304
265
  }
305
- /**
306
- * @description Remove duplicated part of the path
307
- *
308
- * Example:
309
- * ["pallet_staking", "pallet", "pallet", "Event"]
310
- * => ["pallet_staking", "pallet", "Event"]
311
- *
312
- * @param path
313
- * @private
314
- */
315
- #cleanPath(path) {
266
+ cleanPath(path) {
316
267
  return path
317
- .map((one) => (0, util_1.stringPascalCase)(one))
268
+ .map((one) => (0, utils_1.stringPascalCase)(one))
318
269
  .filter((one, idx, currentPath) => idx === 0 || one !== currentPath[idx - 1])
319
270
  .join('');
320
271
  }
321
- #shouldGenerateTypeIn(id) {
322
- const { callTypeId } = this.metadata.extrinsic;
323
- const palletCallTypeIds = this.registry.portableRegistry.getPalletCallTypeIds();
324
- return callTypeId === id || palletCallTypeIds.includes(id);
325
- }
326
272
  eqlCache = new Map();
327
273
  typeEql(idA, idB, level = 0) {
328
274
  const cacheKey = `${idA}==${idB}`;
@@ -335,9 +281,8 @@ class TypesGen {
335
281
  #typeEql(idA, idB, lvl = 0) {
336
282
  if (idA === idB)
337
283
  return true;
338
- const { types } = this.metadata;
339
- const typeA = types[idA];
340
- const typeB = types[idB];
284
+ const typeA = this.types[idA];
285
+ const typeB = this.types[idB];
341
286
  if (typeA.path.join('::') !== typeB.path.join('::'))
342
287
  return false;
343
288
  const { type: defA, params: paramsA } = typeA;
@@ -380,19 +325,18 @@ class TypesGen {
380
325
  (param1.typeId === undefined) === (param2.typeId === undefined) &&
381
326
  (param1.typeId === undefined || this.#typeEql(param1.typeId, param2.typeId)));
382
327
  }
383
- #extractDupTypeSuffix(dupTypeId, originalTypeId, dupCount) {
384
- const { types } = this.metadata;
385
- const originalTypeParams = types[originalTypeId].params;
386
- const dupTypeParams = types[dupTypeId].params;
328
+ extractDupTypeSuffix(dupTypeId, originalTypeId, dupCount) {
329
+ const originalTypeParams = this.types[originalTypeId].params;
330
+ const dupTypeParams = this.types[dupTypeId].params;
387
331
  const diffParam = dupTypeParams.find((one, idx) => !this.#eqlTypeParam(one, originalTypeParams[idx]));
388
332
  // TODO make sure these suffix is unique if a type is duplicated more than 2 times
389
333
  if (diffParam?.typeId) {
390
- const diffType = types[diffParam.typeId];
334
+ const diffType = this.types[diffParam.typeId];
391
335
  if (diffType.path.length > 0) {
392
- return (0, util_1.stringPascalCase)(diffType.path.at(-1));
336
+ return (0, utils_1.stringPascalCase)(diffType.path.at(-1));
393
337
  }
394
338
  else if (diffType.type.tag === 'Primitive') {
395
- return (0, util_1.stringPascalCase)(diffType.type.value.kind);
339
+ return (0, utils_1.stringPascalCase)(diffType.type.value.kind);
396
340
  }
397
341
  }
398
342
  // Last resort!
@@ -403,7 +347,7 @@ class TypesGen {
403
347
  typeName.forEach((one) => this.addTypeImport(one));
404
348
  return;
405
349
  }
406
- if ((0, utils_1.isNativeType)(typeName)) {
350
+ if ((0, utils_js_1.isNativeType)(typeName)) {
407
351
  return;
408
352
  }
409
353
  for (let type of Object.values(this.includedTypes)) {
@@ -425,12 +369,10 @@ class TypesGen {
425
369
  this.typeImports.addCodecType(typeName);
426
370
  return;
427
371
  }
428
- if (types_1.registry.has(typeName)) {
429
- this.typeImports.addKnownType(typeName);
430
- }
431
- else {
432
- this.typeImports.addOutType(typeName);
433
- }
372
+ this.typeImports.addOutType(typeName);
373
+ }
374
+ getEnumOptions(_typeId) {
375
+ return { tagKey: 'tag', valueKey: 'value' };
434
376
  }
435
377
  }
436
- exports.TypesGen = TypesGen;
378
+ exports.BaseTypesGen = BaseTypesGen;
@@ -8,30 +8,47 @@ class TypeImports {
8
8
  codecTypes;
9
9
  // Known types that're not codecs or chain/portable types defined in @dedot/types
10
10
  knownTypes;
11
+ knownJsonRpcTypes;
11
12
  // External types to define explicitly
12
13
  outTypes;
14
+ // Know types defined in @dedot/contracts
15
+ contractTypes;
16
+ // Know types defined in @dedot/api/chaintypes or dedot/chaintypes
17
+ chainTypes;
13
18
  constructor() {
14
19
  this.portableTypes = new Set();
15
20
  this.codecTypes = new Set();
16
21
  this.knownTypes = new Set();
22
+ this.knownJsonRpcTypes = new Set();
17
23
  this.outTypes = new Set();
24
+ this.contractTypes = new Set();
25
+ this.chainTypes = new Set();
18
26
  }
19
27
  clear() {
20
28
  this.portableTypes.clear();
21
29
  this.codecTypes.clear();
22
30
  this.knownTypes.clear();
31
+ this.knownJsonRpcTypes.clear();
23
32
  this.outTypes.clear();
33
+ this.contractTypes.clear();
34
+ this.chainTypes.clear();
24
35
  }
25
- toImports(...excludeModules) {
36
+ toImports(config) {
37
+ const { excludeModules = [], useSubPaths = false } = config || {};
26
38
  // TODO generate outTypes!
39
+ const prefix = useSubPaths ? '' : '@';
27
40
  const toImports = [
28
- [this.knownTypes, '@dedot/types'],
29
- [this.codecTypes, '@dedot/codecs'],
41
+ [this.knownTypes, `${prefix}dedot/types`],
42
+ [this.knownJsonRpcTypes, `${prefix}dedot/types/json-rpc`],
43
+ [this.codecTypes, `${prefix}dedot/codecs`],
44
+ [this.contractTypes, `${prefix}dedot/contracts`],
45
+ [this.chainTypes, prefix ? '@dedot/api/chaintypes' : 'dedot/chaintypes'],
30
46
  [this.portableTypes, './types'],
31
47
  ];
32
48
  return toImports
33
49
  .filter(([_, module]) => !excludeModules.includes(module))
34
50
  .map(([types, module]) => this.#toImportLine(types, module))
51
+ .filter((line) => line.length > 0)
35
52
  .join('\n');
36
53
  }
37
54
  #toImportLine(types, module) {
@@ -49,8 +66,17 @@ class TypeImports {
49
66
  addKnownType(...types) {
50
67
  types.forEach((one) => this.knownTypes.add(one));
51
68
  }
69
+ addKnownJsonRpcType(...types) {
70
+ types.forEach((one) => this.knownJsonRpcTypes.add(one));
71
+ }
52
72
  addOutType(...types) {
53
73
  types.forEach((one) => this.outTypes.add(one));
54
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
+ }
55
81
  }
56
82
  exports.TypeImports = TypeImports;
@@ -14,13 +14,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./TypesGen"), exports);
18
- __exportStar(require("./ApiGen"), exports);
19
- __exportStar(require("./ConstsGen"), exports);
20
- __exportStar(require("./QueryGen"), exports);
21
- __exportStar(require("./RpcGen"), exports);
22
- __exportStar(require("./IndexGen"), exports);
23
- __exportStar(require("./ErrorsGen"), exports);
24
- __exportStar(require("./EventsGen"), exports);
25
- __exportStar(require("./TxGen"), exports);
26
- __exportStar(require("./RuntimeApisGen"), exports);
17
+ __exportStar(require("./BaseTypesGen.js"), exports);
18
+ __exportStar(require("./known-codecs.js"), exports);
19
+ __exportStar(require("./TypeImports.js"), exports);
@@ -0,0 +1,170 @@
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.looseTypeCodecs = exports.normalizeCodecName = void 0;
27
+ exports.findKnownCodecType = findKnownCodecType;
28
+ exports.findKnownCodec = findKnownCodec;
29
+ exports.findKnownWrapperCodec = findKnownWrapperCodec;
30
+ exports.checkKnownCodecType = checkKnownCodecType;
31
+ const Codecs = __importStar(require("@dedot/codecs"));
32
+ const codecs_1 = require("@dedot/codecs");
33
+ const $ = __importStar(require("@dedot/shape"));
34
+ const utils_1 = require("@dedot/utils");
35
+ const normalizeCodecName = (name) => {
36
+ return name.startsWith('$') ? name : `$${name}`;
37
+ };
38
+ exports.normalizeCodecName = normalizeCodecName;
39
+ // Known paths for codecs (primitives) that are shared between
40
+ // different substrate-based blockchains
41
+ const KNOWN_PATHS = [
42
+ 'sp_core::crypto::AccountId32',
43
+ 'sp_runtime::generic::era::Era',
44
+ 'sp_runtime::multiaddress::MultiAddress',
45
+ /^sp_runtime::DispatchError$/,
46
+ 'sp_runtime::ModuleError',
47
+ 'sp_runtime::TokenError',
48
+ 'sp_arithmetic::ArithmeticError',
49
+ 'sp_runtime::TransactionalError',
50
+ 'frame_support::dispatch::DispatchInfo',
51
+ 'frame_system::Phase',
52
+ 'sp_version::RuntimeVersion',
53
+ 'fp_account::AccountId20',
54
+ 'account::AccountId20',
55
+ 'polkadot_runtime_common::claims::EthereumAddress',
56
+ 'pallet_identity::types::Data',
57
+ 'sp_runtime::generic::digest::Digest',
58
+ 'sp_runtime::generic::digest::DigestItem',
59
+ 'sp_runtime::generic::header::Header',
60
+ 'sp_runtime::generic::unchecked_extrinsic::UncheckedExtrinsic',
61
+ /^primitive_types::\w+$/,
62
+ /^sp_arithmetic::per_things::\w+$/,
63
+ /^sp_arithmetic::fixed_point::\w+$/,
64
+ 'ink_primitives::types::Hash',
65
+ { path: 'ink_primitives::types::AccountId', codec: 'AccountId32' },
66
+ ];
67
+ const WRAPPER_TYPE_REGEX = /^(\w+)<(.*)>$/;
68
+ const TUPLE_TYPE_REGEX = /^\[(.*)]$/;
69
+ const KNOWN_WRAPPER_TYPES = ['Option', 'Vec', 'Result', 'Array'];
70
+ /**
71
+ * Collection of codec types with loose input types
72
+ *
73
+ * Loose codecs are codecs with different typeIn & typeOut,
74
+ * E.g: Codec `$AccountId32`, we have its typeIn is `AccountId32Like` & typeOut is `AccountId32`
75
+ *
76
+ * This registry keep track the list of codecs which follow this convention
77
+ */
78
+ exports.looseTypeCodecs = {
79
+ $AccountId20: codecs_1.$AccountId20,
80
+ $EthereumAddress: codecs_1.$EthereumAddress,
81
+ $AccountId32: codecs_1.$AccountId32,
82
+ $ConsensusEngineId: codecs_1.$ConsensusEngineId,
83
+ $StorageKey: codecs_1.$StorageKey,
84
+ $StorageData: codecs_1.$StorageData,
85
+ $PrefixedStorageKey: codecs_1.$PrefixedStorageKey,
86
+ $Bytes: codecs_1.$Bytes,
87
+ $RawBytes: codecs_1.$RawBytes,
88
+ $MultiAddress: codecs_1.$MultiAddress,
89
+ $OpaqueExtrinsic: codecs_1.$OpaqueExtrinsic,
90
+ $UncheckedExtrinsic: codecs_1.$UncheckedExtrinsic,
91
+ $Era: codecs_1.$Era,
92
+ };
93
+ function findKnownCodecType(name) {
94
+ const normalizedName = (0, exports.normalizeCodecName)(name);
95
+ const $knownCodec = exports.looseTypeCodecs[normalizedName];
96
+ if ($knownCodec) {
97
+ return {
98
+ name: normalizedName,
99
+ $codec: $knownCodec,
100
+ typeIn: `${name}Like`,
101
+ typeOut: name,
102
+ };
103
+ }
104
+ const $codec = findKnownCodec(name);
105
+ if ($codec.nativeType && $[name]) {
106
+ return {
107
+ name: normalizedName,
108
+ $codec,
109
+ typeIn: $codec.nativeType,
110
+ typeOut: $codec.nativeType,
111
+ };
112
+ }
113
+ return {
114
+ name: normalizedName,
115
+ $codec,
116
+ typeIn: name,
117
+ typeOut: name,
118
+ };
119
+ }
120
+ function findKnownCodec(typeName) {
121
+ // @ts-ignore
122
+ const $codec = findKnownWrapperCodec(typeName) || Codecs[(0, exports.normalizeCodecName)(typeName)] || $[typeName];
123
+ (0, utils_1.assert)($codec, `Known codec not found - ${typeName}`);
124
+ return $codec;
125
+ }
126
+ function findKnownWrapperCodec(typeName) {
127
+ const matchNames = typeName.match(WRAPPER_TYPE_REGEX);
128
+ if (matchNames) {
129
+ const [_, wrapper, inner] = matchNames;
130
+ if (KNOWN_WRAPPER_TYPES.includes(wrapper)) {
131
+ // @ts-ignore
132
+ const $Wrapper = $[wrapper];
133
+ if (inner.match(TUPLE_TYPE_REGEX) || inner.match(WRAPPER_TYPE_REGEX)) {
134
+ return $Wrapper(findKnownWrapperCodec(inner));
135
+ }
136
+ const $inners = inner.split(',').map((one) => findKnownCodec(one.trim()));
137
+ return $Wrapper(...$inners);
138
+ }
139
+ throw new Error(`Unknown wrapper type ${wrapper} from ${typeName}`);
140
+ }
141
+ else if (typeName.match(TUPLE_TYPE_REGEX)) {
142
+ const $inner = typeName
143
+ .slice(1, -1)
144
+ .split(',')
145
+ .filter((x) => x)
146
+ .map((one) => findKnownCodec(one.trim()));
147
+ return $.Tuple(...$inner);
148
+ }
149
+ }
150
+ function checkKnownCodecType(path) {
151
+ const joinedPath = Array.isArray(path) ? path.join('::') : path;
152
+ const knownPath = KNOWN_PATHS.find((one) => {
153
+ if (typeof one === 'string') {
154
+ return one === joinedPath;
155
+ }
156
+ else if (one instanceof RegExp) {
157
+ return one.test(joinedPath);
158
+ }
159
+ else {
160
+ return one.path === joinedPath;
161
+ }
162
+ });
163
+ if (!knownPath) {
164
+ return [false, ''];
165
+ }
166
+ if (typeof knownPath === 'string' || knownPath instanceof RegExp) {
167
+ return [true, joinedPath.split('::').at(-1)];
168
+ }
169
+ return [true, knownPath.codec];
170
+ }
@@ -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;