@dedot/codegen 0.0.1-next.3 → 0.0.1-next.3662494a.39

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 (74) hide show
  1. package/cjs/generator/ConstsGen.js +10 -11
  2. package/cjs/generator/ErrorsGen.js +13 -14
  3. package/cjs/generator/EventsGen.js +14 -15
  4. package/cjs/generator/IndexGen.js +8 -9
  5. package/cjs/generator/JsonRpcGen.js +59 -0
  6. package/cjs/generator/QueryGen.js +24 -16
  7. package/cjs/generator/RuntimeApisGen.js +107 -29
  8. package/cjs/generator/TxGen.js +21 -19
  9. package/cjs/generator/TypeImports.js +8 -0
  10. package/cjs/generator/TypesGen.js +23 -29
  11. package/cjs/generator/index.js +10 -10
  12. package/cjs/generator/known-codecs.js +151 -0
  13. package/cjs/generator/utils.js +30 -1
  14. package/cjs/index.js +32 -32
  15. package/cjs/templates/consts.hbs +1 -1
  16. package/cjs/templates/errors.hbs +1 -1
  17. package/cjs/templates/events.hbs +1 -1
  18. package/cjs/templates/index.hbs +15 -10
  19. package/cjs/templates/json-rpc.hbs +5 -0
  20. package/cjs/templates/query.hbs +1 -1
  21. package/cjs/templates/runtime.hbs +1 -1
  22. package/cjs/templates/tx.hbs +1 -1
  23. package/generator/ApiGen.d.ts +5 -5
  24. package/generator/ConstsGen.d.ts +1 -1
  25. package/generator/ConstsGen.js +5 -6
  26. package/generator/ErrorsGen.d.ts +1 -1
  27. package/generator/ErrorsGen.js +6 -7
  28. package/generator/EventsGen.d.ts +1 -1
  29. package/generator/EventsGen.js +6 -7
  30. package/generator/IndexGen.d.ts +2 -3
  31. package/generator/IndexGen.js +6 -7
  32. package/generator/JsonRpcGen.d.ts +7 -0
  33. package/generator/JsonRpcGen.js +55 -0
  34. package/generator/QueryGen.d.ts +1 -1
  35. package/generator/QueryGen.js +21 -13
  36. package/generator/RuntimeApisGen.d.ts +5 -5
  37. package/generator/RuntimeApisGen.js +99 -21
  38. package/generator/TxGen.d.ts +1 -1
  39. package/generator/TxGen.js +11 -9
  40. package/generator/TypeImports.d.ts +2 -0
  41. package/generator/TypeImports.js +8 -0
  42. package/generator/TypesGen.d.ts +3 -3
  43. package/generator/TypesGen.js +12 -18
  44. package/generator/index.d.ts +10 -10
  45. package/generator/index.js +10 -10
  46. package/generator/known-codecs.d.ts +23 -0
  47. package/generator/known-codecs.js +120 -0
  48. package/generator/utils.d.ts +5 -0
  49. package/generator/utils.js +28 -0
  50. package/index.d.ts +2 -3
  51. package/index.js +24 -24
  52. package/package.json +14 -18
  53. package/templates/consts.hbs +1 -1
  54. package/templates/errors.hbs +1 -1
  55. package/templates/events.hbs +1 -1
  56. package/templates/index.hbs +15 -10
  57. package/templates/json-rpc.hbs +5 -0
  58. package/templates/query.hbs +1 -1
  59. package/templates/runtime.hbs +1 -1
  60. package/templates/tx.hbs +1 -1
  61. package/cjs/genSupportedChainTypes.js +0 -79
  62. package/cjs/generator/RpcGen.js +0 -175
  63. package/cjs/packageInfo.js +0 -5
  64. package/cjs/templates/rpc.hbs +0 -7
  65. package/cjs/types.js +0 -2
  66. package/genSupportedChainTypes.d.ts +0 -1
  67. package/genSupportedChainTypes.js +0 -74
  68. package/generator/RpcGen.d.ts +0 -10
  69. package/generator/RpcGen.js +0 -171
  70. package/packageInfo.d.ts +0 -4
  71. package/packageInfo.js +0 -2
  72. package/templates/rpc.hbs +0 -7
  73. package/types.d.ts +0 -6
  74. package/types.js +0 -1
@@ -8,30 +8,35 @@ 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
+ specTypes;
11
12
  // External types to define explicitly
12
13
  outTypes;
13
14
  constructor() {
14
15
  this.portableTypes = new Set();
15
16
  this.codecTypes = new Set();
16
17
  this.knownTypes = new Set();
18
+ this.specTypes = new Set();
17
19
  this.outTypes = new Set();
18
20
  }
19
21
  clear() {
20
22
  this.portableTypes.clear();
21
23
  this.codecTypes.clear();
22
24
  this.knownTypes.clear();
25
+ this.specTypes.clear();
23
26
  this.outTypes.clear();
24
27
  }
25
28
  toImports(...excludeModules) {
26
29
  // TODO generate outTypes!
27
30
  const toImports = [
28
31
  [this.knownTypes, '@dedot/types'],
32
+ [this.specTypes, '@dedot/specs'],
29
33
  [this.codecTypes, '@dedot/codecs'],
30
34
  [this.portableTypes, './types'],
31
35
  ];
32
36
  return toImports
33
37
  .filter(([_, module]) => !excludeModules.includes(module))
34
38
  .map(([types, module]) => this.#toImportLine(types, module))
39
+ .filter((line) => line.length > 0)
35
40
  .join('\n');
36
41
  }
37
42
  #toImportLine(types, module) {
@@ -49,6 +54,9 @@ class TypeImports {
49
54
  addKnownType(...types) {
50
55
  types.forEach((one) => this.knownTypes.add(one));
51
56
  }
57
+ addSpecType(...types) {
58
+ types.forEach((one) => this.specTypes.add(one));
59
+ }
52
60
  addOutType(...types) {
53
61
  types.forEach((one) => this.outTypes.add(one));
54
62
  }
@@ -1,12 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.TypesGen = exports.BASIC_KNOWN_TYPES = void 0;
4
- const util_1 = require("@polkadot/util");
5
4
  const codecs_1 = require("@dedot/codecs");
6
5
  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");
6
+ const TypeImports_js_1 = require("./TypeImports.js");
7
+ const known_codecs_js_1 = require("./known-codecs.js");
8
+ const utils_js_1 = require("./utils.js");
10
9
  // Skip generate types for these
11
10
  // as we do have native types for them
12
11
  const SKIP_TYPES = [
@@ -40,9 +39,9 @@ class TypesGen {
40
39
  typeImports;
41
40
  constructor(metadata) {
42
41
  this.metadata = metadata;
43
- this.registry = new codecs_1.CodecRegistry(this.metadata);
42
+ this.registry = new codecs_1.PortableRegistry(this.metadata);
44
43
  this.includedTypes = this.#includedTypes();
45
- this.typeImports = new TypeImports_1.TypeImports();
44
+ this.typeImports = new TypeImports_js_1.TypeImports();
46
45
  }
47
46
  generate() {
48
47
  this.clearCache();
@@ -50,14 +49,14 @@ class TypesGen {
50
49
  Object.values(this.includedTypes)
51
50
  .filter(({ skip, knownType }) => !(skip || knownType))
52
51
  .forEach(({ name, nameOut, id, docs }) => {
53
- defTypeOut += `${(0, utils_2.commentBlock)(docs)}export type ${nameOut} = ${this.generateType(id, 0, true)};\n\n`;
52
+ defTypeOut += `${(0, utils_js_1.commentBlock)(docs)}export type ${nameOut} = ${this.generateType(id, 0, true)};\n\n`;
54
53
  if (this.#shouldGenerateTypeIn(id)) {
55
54
  defTypeOut += `export type ${name} = ${this.generateType(id)};\n\n`;
56
55
  }
57
56
  });
58
57
  const importTypes = this.typeImports.toImports('./types');
59
- const template = (0, utils_2.compileTemplate)('types.hbs');
60
- return (0, utils_2.beautifySourceCode)(template({ importTypes, defTypeOut }));
58
+ const template = (0, utils_js_1.compileTemplate)('types.hbs');
59
+ return (0, utils_js_1.beautifySourceCode)(template({ importTypes, defTypeOut }));
61
60
  }
62
61
  typeCache = {};
63
62
  clearCache() {
@@ -102,7 +101,7 @@ class TypesGen {
102
101
  const { tag, value } = type;
103
102
  switch (tag) {
104
103
  case 'Primitive':
105
- const $codec = this.registry.findCodec(value.kind);
104
+ const $codec = (0, known_codecs_js_1.findKnownCodec)(value.kind);
106
105
  if ($codec.nativeType) {
107
106
  return $codec.nativeType;
108
107
  }
@@ -150,12 +149,12 @@ class TypesGen {
150
149
  return 'null';
151
150
  }
152
151
  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(' | ');
152
+ return members.map(({ name, docs }) => `${(0, utils_js_1.commentBlock)(docs)}'${(0, utils_1.stringPascalCase)(name)}'`).join(' | ');
154
153
  }
155
154
  else {
156
155
  const membersType = [];
157
156
  for (const { fields, name, docs } of members) {
158
- const keyName = (0, util_1.stringPascalCase)(name);
157
+ const keyName = (0, utils_1.stringPascalCase)(name);
159
158
  if (fields.length === 0) {
160
159
  membersType.push([keyName, null, docs]);
161
160
  }
@@ -163,7 +162,7 @@ class TypesGen {
163
162
  const valueType = fields.length === 1
164
163
  ? this.generateType(fields[0].typeId, nestedLevel + 1, typeOut)
165
164
  : `[${fields
166
- .map(({ typeId, docs }) => `${(0, utils_2.commentBlock)(docs)}${this.generateType(typeId, nestedLevel + 1, typeOut)}`)
165
+ .map(({ typeId, docs }) => `${(0, utils_js_1.commentBlock)(docs)}${this.generateType(typeId, nestedLevel + 1, typeOut)}`)
167
166
  .join(', ')}]`;
168
167
  membersType.push([keyName, valueType, docs]);
169
168
  }
@@ -171,14 +170,14 @@ class TypesGen {
171
170
  membersType.push([keyName, this.generateObjectType(fields, nestedLevel + 1, typeOut), docs]);
172
171
  }
173
172
  }
174
- const { tagKey, valueKey } = this.registry.portableRegistry.getEnumOptions(typeId);
173
+ const { tagKey, valueKey } = this.registry.getEnumOptions(typeId);
175
174
  return membersType
176
175
  .map(([keyName, valueType, docs]) => ({
177
176
  tag: `${tagKey}: '${keyName}'`,
178
177
  value: valueType ? `, ${valueKey}${this.#isOptionalType(valueType) ? '?' : ''}: ${valueType} ` : '',
179
178
  docs,
180
179
  }))
181
- .map(({ tag, value, docs }) => `${(0, utils_2.commentBlock)(docs)}{ ${tag}${value} }`)
180
+ .map(({ tag, value, docs }) => `${(0, utils_js_1.commentBlock)(docs)}{ ${tag}${value} }`)
182
181
  .join(' | ');
183
182
  }
184
183
  }
@@ -225,7 +224,7 @@ class TypesGen {
225
224
  };
226
225
  });
227
226
  return `{${props
228
- .map(({ name, type, optional, docs }) => `${(0, utils_2.commentBlock)(docs)}${name}${optional ? '?' : ''}: ${type}`)
227
+ .map(({ name, type, optional, docs }) => `${(0, utils_js_1.commentBlock)(docs)}${name}${optional ? '?' : ''}: ${type}`)
229
228
  .join(',\n')}}`;
230
229
  }
231
230
  #isOptionalType(type) {
@@ -266,8 +265,8 @@ class TypesGen {
266
265
  const suffix = typeSuffixes.get(id) || '';
267
266
  let knownType = false;
268
267
  let name, nameOut;
269
- if (this.registry.isKnownType(joinedPath)) {
270
- const codecType = this.registry.findCodecType(path.at(-1));
268
+ if ((0, known_codecs_js_1.isKnownCodecType)(joinedPath)) {
269
+ const codecType = (0, known_codecs_js_1.findKnownCodecType)(path.at(-1));
271
270
  name = codecType.typeIn;
272
271
  nameOut = codecType.typeOut;
273
272
  knownType = true;
@@ -314,13 +313,13 @@ class TypesGen {
314
313
  */
315
314
  #cleanPath(path) {
316
315
  return path
317
- .map((one) => (0, util_1.stringPascalCase)(one))
316
+ .map((one) => (0, utils_1.stringPascalCase)(one))
318
317
  .filter((one, idx, currentPath) => idx === 0 || one !== currentPath[idx - 1])
319
318
  .join('');
320
319
  }
321
320
  #shouldGenerateTypeIn(id) {
322
321
  const { callTypeId } = this.metadata.extrinsic;
323
- const palletCallTypeIds = this.registry.portableRegistry.getPalletCallTypeIds();
322
+ const palletCallTypeIds = this.registry.getPalletCallTypeIds();
324
323
  return callTypeId === id || palletCallTypeIds.includes(id);
325
324
  }
326
325
  eqlCache = new Map();
@@ -389,10 +388,10 @@ class TypesGen {
389
388
  if (diffParam?.typeId) {
390
389
  const diffType = types[diffParam.typeId];
391
390
  if (diffType.path.length > 0) {
392
- return (0, util_1.stringPascalCase)(diffType.path.at(-1));
391
+ return (0, utils_1.stringPascalCase)(diffType.path.at(-1));
393
392
  }
394
393
  else if (diffType.type.tag === 'Primitive') {
395
- return (0, util_1.stringPascalCase)(diffType.type.value.kind);
394
+ return (0, utils_1.stringPascalCase)(diffType.type.value.kind);
396
395
  }
397
396
  }
398
397
  // Last resort!
@@ -403,7 +402,7 @@ class TypesGen {
403
402
  typeName.forEach((one) => this.addTypeImport(one));
404
403
  return;
405
404
  }
406
- if ((0, utils_1.isNativeType)(typeName)) {
405
+ if ((0, utils_js_1.isNativeType)(typeName)) {
407
406
  return;
408
407
  }
409
408
  for (let type of Object.values(this.includedTypes)) {
@@ -425,12 +424,7 @@ class TypesGen {
425
424
  this.typeImports.addCodecType(typeName);
426
425
  return;
427
426
  }
428
- if (types_1.registry.has(typeName)) {
429
- this.typeImports.addKnownType(typeName);
430
- }
431
- else {
432
- this.typeImports.addOutType(typeName);
433
- }
427
+ this.typeImports.addOutType(typeName);
434
428
  }
435
429
  }
436
430
  exports.TypesGen = TypesGen;
@@ -14,13 +14,13 @@ 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("./TypesGen.js"), exports);
18
+ __exportStar(require("./ApiGen.js"), exports);
19
+ __exportStar(require("./ConstsGen.js"), exports);
20
+ __exportStar(require("./QueryGen.js"), exports);
21
+ __exportStar(require("./JsonRpcGen.js"), exports);
22
+ __exportStar(require("./IndexGen.js"), exports);
23
+ __exportStar(require("./ErrorsGen.js"), exports);
24
+ __exportStar(require("./EventsGen.js"), exports);
25
+ __exportStar(require("./TxGen.js"), exports);
26
+ __exportStar(require("./RuntimeApisGen.js"), exports);
@@ -0,0 +1,151 @@
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.isKnownCodecType = exports.findKnownWrapperCodec = exports.findKnownCodec = exports.findKnownCodecType = exports.looseTypeCodecs = exports.normalizeCodecName = void 0;
27
+ const Codecs = __importStar(require("@dedot/codecs"));
28
+ const codecs_1 = require("@dedot/codecs");
29
+ const $ = __importStar(require("@dedot/shape"));
30
+ const utils_1 = require("@dedot/utils");
31
+ const normalizeCodecName = (name) => {
32
+ return name.startsWith('$') ? name : `$${name}`;
33
+ };
34
+ exports.normalizeCodecName = normalizeCodecName;
35
+ // Known paths for codecs (primitives) that are shared between
36
+ // different substrate-based blockchains
37
+ const KNOWN_PATHS = [
38
+ 'sp_core::crypto::AccountId32',
39
+ 'sp_runtime::generic::era::Era',
40
+ 'sp_runtime::multiaddress::MultiAddress',
41
+ /^sp_runtime::DispatchError$/,
42
+ 'sp_runtime::ModuleError',
43
+ 'sp_runtime::TokenError',
44
+ 'sp_arithmetic::ArithmeticError',
45
+ 'sp_runtime::TransactionalError',
46
+ 'frame_support::dispatch::DispatchInfo',
47
+ 'frame_system::Phase',
48
+ 'sp_version::RuntimeVersion',
49
+ 'fp_account::AccountId20',
50
+ 'account::AccountId20',
51
+ 'polkadot_runtime_common::claims::EthereumAddress',
52
+ 'pallet_identity::types::Data',
53
+ 'sp_runtime::generic::digest::Digest',
54
+ 'sp_runtime::generic::digest::DigestItem',
55
+ 'sp_runtime::generic::header::Header',
56
+ 'sp_runtime::generic::unchecked_extrinsic::UncheckedExtrinsic',
57
+ /^primitive_types::\w+$/,
58
+ /^sp_arithmetic::per_things::\w+$/,
59
+ /^sp_arithmetic::fixed_point::\w+$/,
60
+ ];
61
+ const WRAPPER_TYPE_REGEX = /^(\w+)<(.*)>$/;
62
+ const TUPLE_TYPE_REGEX = /^\[(.*)]$/;
63
+ const KNOWN_WRAPPER_TYPES = ['Option', 'Vec', 'Result', 'Array'];
64
+ /**
65
+ * Collection of codec types with loose input types
66
+ *
67
+ * Loose codecs are codecs with different typeIn & typeOut,
68
+ * E.g: Codec `$AccountId32`, we have its typeIn is `AccountId32Like` & typeOut is `AccountId32`
69
+ *
70
+ * This registry keep track the list of codecs which follow this convention
71
+ */
72
+ exports.looseTypeCodecs = {
73
+ $AccountId20: codecs_1.$AccountId20,
74
+ $EthereumAddress: codecs_1.$EthereumAddress,
75
+ $AccountId32: codecs_1.$AccountId32,
76
+ $ConsensusEngineId: codecs_1.$ConsensusEngineId,
77
+ $StorageKey: codecs_1.$StorageKey,
78
+ $StorageData: codecs_1.$StorageData,
79
+ $PrefixedStorageKey: codecs_1.$PrefixedStorageKey,
80
+ $Bytes: codecs_1.$Bytes,
81
+ $RawBytes: codecs_1.$RawBytes,
82
+ $MultiAddress: codecs_1.$MultiAddress,
83
+ $OpaqueExtrinsic: codecs_1.$OpaqueExtrinsic,
84
+ $UncheckedExtrinsic: codecs_1.$UncheckedExtrinsic,
85
+ $Era: codecs_1.$Era,
86
+ };
87
+ function findKnownCodecType(name) {
88
+ const normalizedName = (0, exports.normalizeCodecName)(name);
89
+ const $knownCodec = exports.looseTypeCodecs[normalizedName];
90
+ if ($knownCodec) {
91
+ return {
92
+ name: normalizedName,
93
+ $codec: $knownCodec,
94
+ typeIn: `${name}Like`,
95
+ typeOut: name,
96
+ };
97
+ }
98
+ const $codec = findKnownCodec(name);
99
+ if ($codec.nativeType && $[name]) {
100
+ return {
101
+ name: normalizedName,
102
+ $codec,
103
+ typeIn: $codec.nativeType,
104
+ typeOut: $codec.nativeType,
105
+ };
106
+ }
107
+ return {
108
+ name: normalizedName,
109
+ $codec,
110
+ typeIn: name,
111
+ typeOut: name,
112
+ };
113
+ }
114
+ exports.findKnownCodecType = findKnownCodecType;
115
+ function findKnownCodec(typeName) {
116
+ // @ts-ignore
117
+ const $codec = findKnownWrapperCodec(typeName) || Codecs[(0, exports.normalizeCodecName)(typeName)] || $[typeName];
118
+ (0, utils_1.assert)($codec, `Known codec not found - ${typeName}`);
119
+ return $codec;
120
+ }
121
+ exports.findKnownCodec = findKnownCodec;
122
+ function findKnownWrapperCodec(typeName) {
123
+ const matchNames = typeName.match(WRAPPER_TYPE_REGEX);
124
+ if (matchNames) {
125
+ const [_, wrapper, inner] = matchNames;
126
+ if (KNOWN_WRAPPER_TYPES.includes(wrapper)) {
127
+ // @ts-ignore
128
+ const $Wrapper = $[wrapper];
129
+ if (inner.match(TUPLE_TYPE_REGEX) || inner.match(WRAPPER_TYPE_REGEX)) {
130
+ return $Wrapper(findKnownWrapperCodec(inner));
131
+ }
132
+ const $inners = inner.split(',').map((one) => findKnownCodec(one.trim()));
133
+ return $Wrapper(...$inners);
134
+ }
135
+ throw new Error(`Unknown wrapper type ${wrapper} from ${typeName}`);
136
+ }
137
+ else if (typeName.match(TUPLE_TYPE_REGEX)) {
138
+ const $inner = typeName
139
+ .slice(1, -1)
140
+ .split(',')
141
+ .filter((x) => x)
142
+ .map((one) => findKnownCodec(one.trim()));
143
+ return $.Tuple(...$inner);
144
+ }
145
+ }
146
+ exports.findKnownWrapperCodec = findKnownWrapperCodec;
147
+ function isKnownCodecType(path) {
148
+ const joinedPath = Array.isArray(path) ? path.join('::') : path;
149
+ return KNOWN_PATHS.some((one) => joinedPath.match(one));
150
+ }
151
+ exports.isKnownCodecType = isKnownCodecType;
@@ -26,7 +26,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
26
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.isReservedWord = exports.compileTemplate = exports.beautifySourceCode = exports.commentBlock = exports.TUPLE_TYPE_REGEX = exports.WRAPPER_TYPE_REGEX = void 0;
29
+ exports.isNativeType = exports.isReservedWord = exports.compileTemplate = exports.beautifySourceCode = exports.commentBlock = exports.TUPLE_TYPE_REGEX = exports.WRAPPER_TYPE_REGEX = void 0;
30
30
  const fs = __importStar(require("fs"));
31
31
  const handlebars_1 = __importDefault(require("handlebars"));
32
32
  const path = __importStar(require("path"));
@@ -66,3 +66,32 @@ const TS_RESERVED_WORDS = ['new', 'class'];
66
66
  */
67
67
  const isReservedWord = (word) => TS_RESERVED_WORDS.includes(word);
68
68
  exports.isReservedWord = isReservedWord;
69
+ const TS_PRIMITIVE_TYPES = [
70
+ 'void',
71
+ 'undefined',
72
+ 'null',
73
+ 'number',
74
+ 'boolean',
75
+ 'bigint',
76
+ 'Map',
77
+ 'Set',
78
+ 'string',
79
+ 'any',
80
+ 'Array',
81
+ 'Record',
82
+ ];
83
+ /**
84
+ * Check if a type is native JS/TS type
85
+ * @param type
86
+ */
87
+ const isNativeType = (type) => {
88
+ return TS_PRIMITIVE_TYPES.some((one) => {
89
+ if (typeof one === 'string') {
90
+ return one === type;
91
+ }
92
+ else {
93
+ return type.match(one);
94
+ }
95
+ });
96
+ };
97
+ exports.isNativeType = isNativeType;
package/cjs/index.js CHANGED
@@ -23,50 +23,50 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.generateTypes = exports.generateTypesFromChain = void 0;
26
+ exports.generateTypes = exports.generateTypesFromEndpoint = void 0;
27
+ const utils_1 = require("@dedot/utils");
27
28
  const dedot_1 = require("dedot");
28
29
  const fs = __importStar(require("fs"));
29
30
  const path = __importStar(require("path"));
30
- const generator_1 = require("./generator");
31
- const util_1 = require("@polkadot/util");
32
- async function generateTypesFromChain(network, endpoint, outDir) {
33
- const api = await dedot_1.Dedot.create(endpoint);
34
- const { methods } = await api.rpc.rpc.methods();
35
- const apis = api.runtimeVersion?.apis || [];
36
- if (!network.chain) {
37
- network.chain = (0, util_1.stringCamelCase)(api.runtimeVersion?.specName || api.runtimeChain || 'local');
31
+ const index_js_1 = require("./generator/index.js");
32
+ async function generateTypesFromEndpoint(chain, endpoint, outDir, extension = 'd.ts') {
33
+ const api = await dedot_1.Dedot.new(new dedot_1.WsProvider(endpoint));
34
+ const { methods } = await api.rpc.rpc_methods();
35
+ const apis = api.runtimeVersion.apis || {};
36
+ if (!chain) {
37
+ chain = (0, utils_1.stringCamelCase)(api.runtimeVersion.specName || 'local');
38
38
  }
39
- await generateTypes(network, api.metadataLatest, methods, apis, outDir);
39
+ await generateTypes(chain, api.metadata.latest, methods, apis, outDir, extension);
40
40
  await api.disconnect();
41
41
  }
42
- exports.generateTypesFromChain = generateTypesFromChain;
43
- async function generateTypes(network, metadata, rpcMethods, runtimeApis, outDir = '.') {
44
- const dirPath = path.resolve(outDir, network.chain);
45
- const defTypesFileName = path.join(dirPath, `types.d.ts`);
46
- const constsTypesFileName = path.join(dirPath, `consts.d.ts`);
47
- const queryTypesFileName = path.join(dirPath, `query.d.ts`);
48
- const rpcCallsFileName = path.join(dirPath, `rpc.d.ts`);
49
- const indexFileName = path.join(dirPath, `index.d.ts`);
50
- const errorsFileName = path.join(dirPath, `errors.d.ts`);
51
- const eventsFileName = path.join(dirPath, `events.d.ts`);
52
- const runtimeApisFileName = path.join(dirPath, `runtime.d.ts`);
53
- const txFileName = path.join(dirPath, `tx.d.ts`);
42
+ exports.generateTypesFromEndpoint = generateTypesFromEndpoint;
43
+ async function generateTypes(chain, metadata, rpcMethods, runtimeApis, outDir = '.', extension = 'd.ts') {
44
+ const dirPath = path.resolve(outDir, chain);
45
+ const defTypesFileName = path.join(dirPath, `types.${extension}`);
46
+ const constsTypesFileName = path.join(dirPath, `consts.${extension}`);
47
+ const queryTypesFileName = path.join(dirPath, `query.${extension}`);
48
+ const jsonRpcFileName = path.join(dirPath, `json-rpc.${extension}`);
49
+ const indexFileName = path.join(dirPath, `index.${extension}`);
50
+ const errorsFileName = path.join(dirPath, `errors.${extension}`);
51
+ const eventsFileName = path.join(dirPath, `events.${extension}`);
52
+ const runtimeApisFileName = path.join(dirPath, `runtime.${extension}`);
53
+ const txFileName = path.join(dirPath, `tx.${extension}`);
54
54
  if (!fs.existsSync(dirPath)) {
55
55
  fs.mkdirSync(dirPath, { recursive: true });
56
56
  }
57
- const typesGen = new generator_1.TypesGen(metadata);
58
- const constsGen = new generator_1.ConstsGen(typesGen);
59
- const queryGen = new generator_1.QueryGen(typesGen);
60
- const rpcGen = new generator_1.RpcGen(typesGen, rpcMethods);
61
- const indexGen = new generator_1.IndexGen(network);
62
- const errorsGen = new generator_1.ErrorsGen(typesGen);
63
- const eventsGen = new generator_1.EventsGen(typesGen);
64
- const runtimeApisGen = new generator_1.RuntimeApisGen(typesGen, runtimeApis);
65
- const txGen = new generator_1.TxGen(typesGen);
57
+ const typesGen = new index_js_1.TypesGen(metadata);
58
+ const constsGen = new index_js_1.ConstsGen(typesGen);
59
+ const queryGen = new index_js_1.QueryGen(typesGen);
60
+ const jsonRpcGen = new index_js_1.JsonRpcGen(typesGen, rpcMethods);
61
+ const indexGen = new index_js_1.IndexGen(chain);
62
+ const errorsGen = new index_js_1.ErrorsGen(typesGen);
63
+ const eventsGen = new index_js_1.EventsGen(typesGen);
64
+ const runtimeApisGen = new index_js_1.RuntimeApisGen(typesGen, runtimeApis);
65
+ const txGen = new index_js_1.TxGen(typesGen);
66
66
  fs.writeFileSync(defTypesFileName, await typesGen.generate());
67
67
  fs.writeFileSync(errorsFileName, await errorsGen.generate());
68
68
  fs.writeFileSync(eventsFileName, await eventsGen.generate());
69
- fs.writeFileSync(rpcCallsFileName, await rpcGen.generate());
69
+ fs.writeFileSync(jsonRpcFileName, await jsonRpcGen.generate());
70
70
  fs.writeFileSync(queryTypesFileName, await queryGen.generate());
71
71
  fs.writeFileSync(constsTypesFileName, await constsGen.generate());
72
72
  fs.writeFileSync(txFileName, await txGen.generate());
@@ -2,6 +2,6 @@
2
2
 
3
3
  {{{ importTypes }}}
4
4
 
5
- export interface ChainConsts extends GenericChainConsts {
5
+ export interface ChainConsts<Rv extends RpcVersion> extends GenericChainConsts<Rv> {
6
6
  {{{ defTypeOut }}}
7
7
  }
@@ -2,6 +2,6 @@
2
2
 
3
3
  {{{ importTypes }}}
4
4
 
5
- export interface ChainErrors extends GenericChainErrors {
5
+ export interface ChainErrors<Rv extends RpcVersion> extends GenericChainErrors<Rv> {
6
6
  {{{ defTypeOut }}}
7
7
  }
@@ -2,6 +2,6 @@
2
2
 
3
3
  {{{ importTypes }}}
4
4
 
5
- export interface ChainEvents extends GenericChainEvents {
5
+ export interface ChainEvents<Rv extends RpcVersion> extends GenericChainEvents<Rv> {
6
6
  {{{ defTypeOut }}}
7
7
  }
@@ -1,9 +1,9 @@
1
1
  // Generated by @dedot/codegen
2
2
 
3
- import { GenericSubstrateApi } from '@dedot/types';
3
+ import { GenericSubstrateApi, RpcLegacy, RpcV2, RpcVersion } from '@dedot/types';
4
4
  import { ChainConsts } from './consts';
5
5
  import { ChainStorage } from './query';
6
- import { RpcCalls } from './rpc';
6
+ import { ChainJsonRpcApis } from './json-rpc';
7
7
  import { ChainErrors } from './errors';
8
8
  import { ChainEvents } from './events';
9
9
  import { RuntimeApis } from './runtime';
@@ -11,12 +11,17 @@ import { ChainTx } from './tx';
11
11
 
12
12
  export * from './types';
13
13
 
14
- export interface {{{interfaceName}}}Api extends GenericSubstrateApi {
15
- rpc: RpcCalls;
16
- consts: ChainConsts;
17
- query: ChainStorage;
18
- errors: ChainErrors;
19
- events: ChainEvents;
20
- call: RuntimeApis;
21
- tx: ChainTx;
14
+ export interface Versioned{{{interfaceName}}}Api<Rv extends RpcVersion> extends GenericSubstrateApi<Rv> {
15
+ rpc: ChainJsonRpcApis<Rv>;
16
+ consts: ChainConsts<Rv>;
17
+ query: ChainStorage<Rv>;
18
+ errors: ChainErrors<Rv>;
19
+ events: ChainEvents<Rv>;
20
+ call: RuntimeApis<Rv>;
21
+ tx: ChainTx<Rv>;
22
+ }
23
+
24
+ export interface {{{interfaceName}}}Api {
25
+ legacy: Versioned{{{interfaceName}}}Api<RpcLegacy>;
26
+ v2: Versioned{{{interfaceName}}}Api<RpcV2>;
22
27
  }
@@ -0,0 +1,5 @@
1
+ // Generated by @dedot/codegen
2
+
3
+ {{{ importTypes }}}
4
+
5
+ export type ChainJsonRpcApis<Rv extends RpcVersion> = Pick<JsonRpcApis, {{{jsonRpcMethods}}}> & GenericJsonRpcApis<Rv>;
@@ -2,6 +2,6 @@
2
2
 
3
3
  {{{ importTypes }}}
4
4
 
5
- export interface ChainStorage extends GenericChainStorage {
5
+ export interface ChainStorage<Rv extends RpcVersion> extends GenericChainStorage<Rv> {
6
6
  {{{ defTypeOut }}}
7
7
  }
@@ -2,7 +2,7 @@
2
2
 
3
3
  {{{ importTypes }}}
4
4
 
5
- export interface RuntimeApis extends GenericRuntimeApis {
5
+ export interface RuntimeApis<Rv extends RpcVersion> extends GenericRuntimeApis<Rv> {
6
6
  {{{ runtimeCallsOut }}}
7
7
  }
8
8
 
@@ -4,6 +4,6 @@
4
4
 
5
5
  {{{ defTypes }}}
6
6
 
7
- export interface ChainTx extends GenericChainTx<TxCall> {
7
+ export interface ChainTx<Rv extends RpcVersion> extends GenericChainTx<Rv, TxCall<Rv>> {
8
8
  {{{ txDefsOut }}}
9
9
  }
@@ -1,4 +1,4 @@
1
- import { TypesGen } from '../generator';
1
+ import { TypesGen } from '../generator/index.js';
2
2
  export declare abstract class ApiGen {
3
3
  readonly typesGen: TypesGen;
4
4
  constructor(typesGen: TypesGen);
@@ -13,14 +13,14 @@ export declare abstract class ApiGen {
13
13
  type: {
14
14
  tag: "Struct";
15
15
  value: {
16
- fields: import("@dedot/codecs").Field[];
16
+ fields: import("dedot").Field[];
17
17
  };
18
18
  } | {
19
19
  tag: "Enum";
20
20
  value: {
21
21
  members: {
22
22
  name: string;
23
- fields: import("@dedot/codecs").Field[];
23
+ fields: import("dedot").Field[];
24
24
  index: number;
25
25
  docs: string[];
26
26
  }[];
@@ -44,7 +44,7 @@ export declare abstract class ApiGen {
44
44
  } | {
45
45
  tag: "Primitive";
46
46
  value: {
47
- kind: "bool" | "char" | "str" | "u8" | "u16" | "u32" | "u64" | "u128" | "u256" | "i8" | "i16" | "i32" | "i64" | "i128" | "i256";
47
+ kind: "bool" | "u8" | "i8" | "u16" | "i16" | "u32" | "i32" | "u64" | "i64" | "u128" | "i128" | "u256" | "i256" | "str" | "char";
48
48
  };
49
49
  } | {
50
50
  tag: "Compact";
@@ -134,5 +134,5 @@ export declare abstract class ApiGen {
134
134
  }>;
135
135
  };
136
136
  };
137
- get registry(): import("@dedot/codecs").CodecRegistry;
137
+ get registry(): import("dedot").PortableRegistry;
138
138
  }
@@ -1,4 +1,4 @@
1
- import { ApiGen } from '../generator';
1
+ import { ApiGen } from './ApiGen.js';
2
2
  export declare class ConstsGen extends ApiGen {
3
3
  generate(): Promise<string>;
4
4
  }