@dedot/codegen 0.0.1-next.2d39ff2d.5 → 0.0.1-next.324f6c64.55

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 (76) hide show
  1. package/cjs/generator/ConstsGen.js +7 -8
  2. package/cjs/generator/ErrorsGen.js +7 -8
  3. package/cjs/generator/EventsGen.js +7 -8
  4. package/cjs/generator/IndexGen.js +6 -7
  5. package/cjs/generator/JsonRpcGen.js +59 -0
  6. package/cjs/generator/QueryGen.js +23 -15
  7. package/cjs/generator/RuntimeApisGen.js +101 -27
  8. package/cjs/generator/TxGen.js +16 -14
  9. package/cjs/generator/TypeImports.js +13 -3
  10. package/cjs/generator/TypesGen.js +12 -19
  11. package/cjs/generator/index.js +1 -1
  12. package/cjs/generator/known-codecs.js +8 -8
  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/ConstsGen.d.ts +2 -2
  24. package/generator/ConstsGen.js +6 -7
  25. package/generator/ErrorsGen.d.ts +1 -1
  26. package/generator/ErrorsGen.js +6 -7
  27. package/generator/EventsGen.d.ts +1 -1
  28. package/generator/EventsGen.js +6 -7
  29. package/generator/IndexGen.d.ts +3 -4
  30. package/generator/IndexGen.js +6 -7
  31. package/generator/JsonRpcGen.d.ts +7 -0
  32. package/generator/JsonRpcGen.js +55 -0
  33. package/generator/QueryGen.d.ts +2 -2
  34. package/generator/QueryGen.js +22 -14
  35. package/generator/RuntimeApisGen.d.ts +5 -5
  36. package/generator/RuntimeApisGen.js +97 -23
  37. package/generator/TxGen.d.ts +1 -1
  38. package/generator/TxGen.js +11 -9
  39. package/generator/TypeImports.d.ts +8 -1
  40. package/generator/TypeImports.js +13 -3
  41. package/generator/TypesGen.d.ts +2 -2
  42. package/generator/TypesGen.js +6 -13
  43. package/generator/index.d.ts +1 -1
  44. package/generator/index.js +1 -1
  45. package/generator/known-codecs.d.ts +2 -2
  46. package/generator/known-codecs.js +4 -4
  47. package/generator/utils.d.ts +5 -0
  48. package/generator/utils.js +28 -0
  49. package/index.d.ts +3 -4
  50. package/index.js +32 -32
  51. package/package.json +9 -18
  52. package/templates/consts.hbs +1 -1
  53. package/templates/errors.hbs +1 -1
  54. package/templates/events.hbs +1 -1
  55. package/templates/index.hbs +15 -10
  56. package/templates/json-rpc.hbs +5 -0
  57. package/templates/query.hbs +1 -1
  58. package/templates/runtime.hbs +1 -1
  59. package/templates/tx.hbs +1 -1
  60. package/cjs/genSupportedChainTypes.js +0 -83
  61. package/cjs/generator/RpcGen.js +0 -176
  62. package/cjs/generator/known-types.js +0 -33
  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 -78
  68. package/generator/RpcGen.d.ts +0 -10
  69. package/generator/RpcGen.js +0 -172
  70. package/generator/known-types.d.ts +0 -6
  71. package/generator/known-types.js +0 -30
  72. package/packageInfo.d.ts +0 -4
  73. package/packageInfo.js +0 -2
  74. package/templates/rpc.hbs +0 -7
  75. package/types.d.ts +0 -6
  76. package/types.js +0 -1
@@ -1,39 +1,46 @@
1
- import { stringLowerFirst } from '@polkadot/util';
2
- import { normalizeName } from '@dedot/utils';
3
- import { ApiGen } from '../generator/index.js';
1
+ import { normalizeName, stringCamelCase } from 'dedot/utils';
2
+ import { ApiGen } from './ApiGen.js';
4
3
  import { beautifySourceCode, commentBlock, compileTemplate } from './utils.js';
5
4
  export class QueryGen extends ApiGen {
6
- generate() {
5
+ generate(useSubPaths = false) {
7
6
  const { pallets } = this.metadata;
8
7
  this.typesGen.clearCache();
9
- this.typesGen.typeImports.addKnownType('GenericChainStorage', 'GenericStorageQuery', 'Callback');
8
+ this.typesGen.typeImports.addKnownType('GenericChainStorage', 'GenericStorageQuery', 'Callback', 'RpcVersion');
10
9
  let defTypeOut = '';
11
10
  for (let pallet of pallets) {
12
11
  const storage = pallet.storage;
13
12
  if (!storage)
14
13
  continue;
15
14
  const queries = storage.entries.map((one) => this.#generateEntry(one));
16
- const queryDefs = queries.map(({ name, valueType, keyType, docs }) => `${commentBlock(docs)}${name}: GenericStorageQuery<(${keyType}) => ${valueType}>`);
15
+ const queryDefs = queries.map(({ name, valueType, keyType, docs, keyTypeOut }) => {
16
+ if (keyTypeOut) {
17
+ return `${commentBlock(docs)}${name}: GenericStorageQuery<Rv, (${keyType}) => ${valueType}, ${keyTypeOut}>`;
18
+ }
19
+ else {
20
+ return `${commentBlock(docs)}${name}: GenericStorageQuery<Rv, (${keyType}) => ${valueType}>`;
21
+ }
22
+ });
17
23
  defTypeOut += commentBlock(`Pallet \`${pallet.name}\`'s storage queries`);
18
- defTypeOut += `${stringLowerFirst(pallet.name)}: {
24
+ defTypeOut += `${stringCamelCase(pallet.name)}: {
19
25
  ${queryDefs.join(',\n')}
20
26
 
21
- ${commentBlock('Generic pallet storage query')}[storage: string]: GenericStorageQuery;
27
+ ${commentBlock('Generic pallet storage query')}[storage: string]: GenericStorageQuery<Rv>;
22
28
  },`;
23
29
  }
24
- const importTypes = this.typesGen.typeImports.toImports();
30
+ const importTypes = this.typesGen.typeImports.toImports({ useSubPaths });
25
31
  const template = compileTemplate('query.hbs');
26
32
  return beautifySourceCode(template({ importTypes, defTypeOut }));
27
33
  }
28
34
  #generateEntry(entry) {
29
35
  const { name, type, docs, modifier } = entry;
30
- let valueType, keyType;
36
+ let valueType, keyTypeOut, keyTypeIn;
31
37
  if (type.tag === 'Plain') {
32
38
  valueType = this.typesGen.generateType(type.value.valueTypeId, 1, true);
33
39
  }
34
40
  else if (type.tag === 'Map') {
35
41
  valueType = this.typesGen.generateType(type.value.valueTypeId, 1, true);
36
- keyType = this.typesGen.generateType(type.value.keyTypeId, 1);
42
+ keyTypeOut = this.typesGen.generateType(type.value.keyTypeId, 1, true);
43
+ keyTypeIn = this.typesGen.generateType(type.value.keyTypeId, 1);
37
44
  }
38
45
  else {
39
46
  throw Error('Invalid entry type!');
@@ -41,14 +48,15 @@ export class QueryGen extends ApiGen {
41
48
  const isOptional = modifier === 'Optional';
42
49
  valueType = `${valueType}${isOptional ? ' | undefined' : ''}`;
43
50
  docs.push('\n');
44
- if (keyType) {
45
- docs.push(`@param {${keyType}} arg`);
51
+ if (keyTypeIn) {
52
+ docs.push(`@param {${keyTypeIn}} arg`);
46
53
  }
47
54
  docs.push(`@param {Callback<${valueType}> =} callback`);
48
55
  return {
49
56
  name: normalizeName(name),
50
57
  valueType,
51
- keyType: keyType ? `arg: ${keyType}` : '',
58
+ keyType: keyTypeIn ? `arg: ${keyTypeIn}` : '',
59
+ keyTypeOut,
52
60
  docs,
53
61
  };
54
62
  }
@@ -1,9 +1,9 @@
1
+ import { ApiGen } from './ApiGen.js';
1
2
  import { TypesGen } from './TypesGen.js';
2
- import { RpcGen } from './RpcGen.js';
3
- export declare class RuntimeApisGen extends RpcGen {
3
+ export declare class RuntimeApisGen extends ApiGen {
4
4
  #private;
5
5
  readonly typesGen: TypesGen;
6
- readonly runtimeApis: [string, number][];
7
- constructor(typesGen: TypesGen, runtimeApis: [string, number][]);
8
- generate(): Promise<string>;
6
+ readonly runtimeApis: Record<string, number>;
7
+ constructor(typesGen: TypesGen, runtimeApis: Record<string, number>);
8
+ generate(useSubPaths?: boolean): Promise<string>;
9
9
  }
@@ -1,28 +1,28 @@
1
- import { getRuntimeApiNames, getRuntimeApiSpecs } from '@dedot/specs';
2
- import { beautifySourceCode, commentBlock, compileTemplate } from './utils.js';
3
- import { calculateRuntimeApiHash, stringSnakeCase } from '@dedot/utils';
4
- import { RpcGen } from './RpcGen.js';
5
- import { stringCamelCase } from '@polkadot/util';
6
- export class RuntimeApisGen extends RpcGen {
1
+ import { getRuntimeApiNames, getRuntimeApiSpecs } from 'dedot/runtime-specs';
2
+ import { calcRuntimeApiHash, stringSnakeCase, stringCamelCase } from 'dedot/utils';
3
+ import { ApiGen } from './ApiGen.js';
4
+ import { findKnownCodecType } from './known-codecs.js';
5
+ import { beautifySourceCode, commentBlock, compileTemplate, isNativeType, TUPLE_TYPE_REGEX, WRAPPER_TYPE_REGEX, } from './utils.js';
6
+ export class RuntimeApisGen extends ApiGen {
7
7
  typesGen;
8
8
  runtimeApis;
9
9
  constructor(typesGen, runtimeApis) {
10
- super(typesGen, []);
10
+ super(typesGen);
11
11
  this.typesGen = typesGen;
12
12
  this.runtimeApis = runtimeApis;
13
13
  }
14
- generate() {
14
+ generate(useSubPaths = false) {
15
15
  this.typesGen.clearCache();
16
- this.typesGen.typeImports.addKnownType('GenericRuntimeApis', 'GenericRuntimeApiMethod');
16
+ this.typesGen.typeImports.addKnownType('GenericRuntimeApis', 'GenericRuntimeApiMethod', 'RpcVersion');
17
17
  let runtimeCallsOut = '';
18
18
  if (this.metadata.apis.length > 0) {
19
19
  this.metadata.apis.forEach((runtimeApi) => {
20
20
  const { name: runtimeApiName, methods } = runtimeApi;
21
- runtimeCallsOut += commentBlock(`@runtimeapi: ${runtimeApiName} - ${calculateRuntimeApiHash(runtimeApiName)}`);
21
+ runtimeCallsOut += commentBlock(`@runtimeapi: ${runtimeApiName} - ${calcRuntimeApiHash(runtimeApiName)}`);
22
22
  runtimeCallsOut += `${stringCamelCase(runtimeApiName)}: {
23
23
  ${methods.map((method) => this.#generateMethodDef(runtimeApiName, method)).join('\n')}
24
24
 
25
- ${commentBlock('Generic runtime api call')}[method: string]: GenericRuntimeApiMethod
25
+ ${commentBlock('Generic runtime api call')}[method: string]: GenericRuntimeApiMethod<Rv>
26
26
  }`;
27
27
  });
28
28
  }
@@ -39,11 +39,11 @@ export class RuntimeApisGen extends RpcGen {
39
39
  }))
40
40
  .join('\n')}
41
41
 
42
- ${commentBlock('Generic runtime api call')}[method: string]: GenericRuntimeApiMethod
42
+ ${commentBlock('Generic runtime api call')}[method: string]: GenericRuntimeApiMethod<Rv>
43
43
  }`;
44
44
  });
45
45
  }
46
- const importTypes = this.typesGen.typeImports.toImports();
46
+ const importTypes = this.typesGen.typeImports.toImports({ useSubPaths });
47
47
  const template = compileTemplate('runtime.hbs');
48
48
  return beautifySourceCode(template({ importTypes, runtimeCallsOut }));
49
49
  }
@@ -57,25 +57,25 @@ export class RuntimeApisGen extends RpcGen {
57
57
  const { docs = [], params, type, runtimeApiName, methodName } = spec;
58
58
  const callName = `${runtimeApiName}_${stringSnakeCase(methodName)}`;
59
59
  const defaultDocs = [`@callname: ${callName}`];
60
- this.addTypeImport(type, false);
61
- params.forEach(({ type }) => this.addTypeImport(type));
60
+ this.#addTypeImport(type, false);
61
+ params.forEach(({ type }) => this.#addTypeImport(type));
62
62
  const typedParams = params.map((param, idx) => ({
63
63
  ...param,
64
64
  isOptional: this.#isOptionalParam(params, param.type, idx),
65
- plainType: this.getGeneratedTypeName(param.type),
65
+ plainType: this.#getGeneratedTypeName(param.type),
66
66
  }));
67
67
  const paramsOut = typedParams
68
68
  .map(({ name, isOptional, plainType }) => `${stringCamelCase(name)}${isOptional ? '?' : ''}: ${plainType}`)
69
69
  .join(', ');
70
- const typeOut = this.getGeneratedTypeName(type, false);
71
- return `${commentBlock(docs, '\n', defaultDocs, typedParams.map(({ plainType, name }) => `@param {${plainType}} ${name}`))}${methodName}: GenericRuntimeApiMethod<(${paramsOut}) => Promise<${typeOut}>>`;
70
+ const typeOut = this.#getGeneratedTypeName(type, false);
71
+ return `${commentBlock(docs, '\n', defaultDocs, typedParams.map(({ plainType, name }) => `@param {${plainType}} ${name}`))}${methodName}: GenericRuntimeApiMethod<Rv, (${paramsOut}) => Promise<${typeOut}>>`;
72
72
  }
73
73
  #generateMethodDef(runtimeApiName, methodDef) {
74
74
  const { name: methodName, inputs, output, docs } = methodDef;
75
75
  const callName = `${runtimeApiName}_${stringSnakeCase(methodName)}`;
76
76
  const defaultDocs = [`@callname: ${callName}`];
77
77
  const typeOut = this.typesGen.generateType(output, 1, true);
78
- this.addTypeImport(typeOut, false);
78
+ this.#addTypeImport(typeOut, false);
79
79
  const typedInputs = inputs
80
80
  .map((input, idx) => ({
81
81
  ...input,
@@ -85,14 +85,14 @@ export class RuntimeApisGen extends RpcGen {
85
85
  ...input,
86
86
  isOptional: this.#isOptionalParam(inputs, input.type, idx),
87
87
  }));
88
- this.addTypeImport(typedInputs.map((t) => t.type));
88
+ this.#addTypeImport(typedInputs.map((t) => t.type));
89
89
  const paramsOut = typedInputs
90
90
  .map(({ name, type, isOptional }) => `${stringCamelCase(name)}${isOptional ? '?' : ''}: ${type}`)
91
91
  .join(', ');
92
- return `${commentBlock(docs, '\n', defaultDocs, typedInputs.map(({ type, name }) => `@param {${type}} ${name}`))}${stringCamelCase(methodName)}: GenericRuntimeApiMethod<(${paramsOut}) => Promise<${typeOut}>>`;
92
+ return `${commentBlock(docs, '\n', defaultDocs, typedInputs.map(({ type, name }) => `@param {${type}} ${name}`))}${stringCamelCase(methodName)}: GenericRuntimeApiMethod<Rv, (${paramsOut}) => Promise<${typeOut}>>`;
93
93
  }
94
94
  #targetRuntimeApiSpecs() {
95
- const specs = this.runtimeApis.map(([runtimeApiHash, version]) => {
95
+ const specs = Object.entries(this.runtimeApis).map(([runtimeApiHash, version]) => {
96
96
  const runtimeApiSpec = this.#findRuntimeApiSpec(runtimeApiHash, version);
97
97
  if (!runtimeApiSpec)
98
98
  return;
@@ -109,7 +109,81 @@ export class RuntimeApisGen extends RpcGen {
109
109
  }, []);
110
110
  }
111
111
  #findRuntimeApiSpec = (runtimeApiHash, version) => {
112
- const runtimeApiName = getRuntimeApiNames().find((one) => calculateRuntimeApiHash(one) === runtimeApiHash);
112
+ const runtimeApiName = getRuntimeApiNames().find((one) => calcRuntimeApiHash(one) === runtimeApiHash);
113
113
  return getRuntimeApiSpecs().find((one) => one.runtimeApiName === runtimeApiName && one.version === version);
114
114
  };
115
+ // TODO check typeIn, typeOut if param type, or rpc type isScale
116
+ #addTypeImport(type, toTypeIn = true) {
117
+ if (Array.isArray(type)) {
118
+ type.forEach((one) => this.#addTypeImport(one, toTypeIn));
119
+ return;
120
+ }
121
+ type = type.trim();
122
+ if (isNativeType(type)) {
123
+ return;
124
+ }
125
+ // Handle generic wrapper types
126
+ const matchArray = type.match(WRAPPER_TYPE_REGEX);
127
+ if (matchArray) {
128
+ const [_, $1, $2] = matchArray;
129
+ this.#addTypeImport($1, toTypeIn);
130
+ if ($2.match(WRAPPER_TYPE_REGEX) || $2.match(TUPLE_TYPE_REGEX)) {
131
+ this.#addTypeImport($2, toTypeIn);
132
+ }
133
+ else {
134
+ this.#addTypeImport($2.split(','), toTypeIn);
135
+ }
136
+ return;
137
+ }
138
+ // Check tuple type
139
+ if (type.match(TUPLE_TYPE_REGEX)) {
140
+ this.#addTypeImport(type.slice(1, -1).split(','), toTypeIn);
141
+ return;
142
+ }
143
+ if (type.includes(' | ')) {
144
+ this.#addTypeImport(type.split(' | ').map((one) => one.trim()), toTypeIn);
145
+ return;
146
+ }
147
+ try {
148
+ const codecType = this.#getCodecType(type, toTypeIn);
149
+ if (isNativeType(codecType))
150
+ return;
151
+ this.typesGen.typeImports.addCodecType(codecType);
152
+ return;
153
+ }
154
+ catch (e) { }
155
+ this.typesGen.addTypeImport(type);
156
+ }
157
+ #getGeneratedTypeName(type, toTypeIn = true) {
158
+ try {
159
+ const matchArray = type.match(WRAPPER_TYPE_REGEX);
160
+ if (matchArray) {
161
+ const [_, $1, $2] = matchArray;
162
+ const wrapperTypeName = this.#getCodecType($1, toTypeIn);
163
+ if ($2.match(WRAPPER_TYPE_REGEX) || $2.match(TUPLE_TYPE_REGEX)) {
164
+ return `${wrapperTypeName}<${this.#getGeneratedTypeName($2, toTypeIn)}>`;
165
+ }
166
+ const innerTypeNames = $2
167
+ .split(',')
168
+ .map((one) => this.#getGeneratedTypeName(one.trim(), toTypeIn))
169
+ .join(', ');
170
+ return `${wrapperTypeName}<${innerTypeNames}>`;
171
+ }
172
+ else if (type.match(TUPLE_TYPE_REGEX)) {
173
+ const innerTypeNames = type
174
+ .slice(1, -1)
175
+ .split(',')
176
+ .map((one) => this.#getGeneratedTypeName(one.trim(), toTypeIn))
177
+ .join(', ');
178
+ return `[${innerTypeNames}]`;
179
+ }
180
+ return this.#getCodecType(type, toTypeIn);
181
+ }
182
+ catch (e) { }
183
+ return type;
184
+ }
185
+ #getCodecType(type, toTypeIn = true) {
186
+ const { typeIn, typeOut } = findKnownCodecType(type);
187
+ return toTypeIn ? typeIn : typeOut;
188
+ }
115
189
  }
@@ -1,5 +1,5 @@
1
1
  import { ApiGen } from '../generator/index.js';
2
2
  export declare class TxGen extends ApiGen {
3
3
  #private;
4
- generate(): Promise<string>;
4
+ generate(useSubPaths?: boolean): Promise<string>;
5
5
  }
@@ -1,11 +1,11 @@
1
+ import { stringCamelCase, stringPascalCase } from 'dedot/utils';
1
2
  import { ApiGen } from '../generator/index.js';
2
- import { stringCamelCase, stringPascalCase } from '@polkadot/util';
3
3
  import { beautifySourceCode, commentBlock, compileTemplate, isReservedWord } from './utils.js';
4
4
  export class TxGen extends ApiGen {
5
- generate() {
5
+ generate(useSubPaths = false) {
6
6
  const { pallets, types } = this.metadata;
7
7
  this.typesGen.clearCache();
8
- this.typesGen.typeImports.addKnownType('GenericChainTx', 'GenericTxCall', 'ISubmittableExtrinsic', 'ISubmittableResult', 'IRuntimeTxCall');
8
+ this.typesGen.typeImports.addKnownType('GenericChainTx', 'GenericTxCall', 'ISubmittableExtrinsic', 'ISubmittableResult', 'IRuntimeTxCall', 'RpcVersion', 'RpcV2', 'ISubmittableExtrinsicLegacy', 'TransactionStatusLegacy', 'TransactionStatusV2');
9
9
  const { callTypeId, addressTypeId, signatureTypeId } = this.metadata.extrinsic;
10
10
  const callTypeIn = this.typesGen.generateType(callTypeId, 1);
11
11
  const addressTypeIn = this.typesGen.generateType(addressTypeId, 1);
@@ -41,20 +41,22 @@ export class TxGen extends ApiGen {
41
41
  txDefsOut += commentBlock(`Pallet \`${pallet.name}\`'s transaction calls`);
42
42
  txDefsOut += `${stringCamelCase(pallet.name)}: {
43
43
  ${typedTxs
44
- .map(({ functionName, params, docs, callInput }) => `${commentBlock(docs, '\n', params.map((p) => `@param {${p.type}} ${p.normalizedName} ${p.docs}`))}${functionName}: GenericTxCall<(${params.map((p) => `${p.normalizedName}: ${p.type}`).join(', ')}) => ChainSubmittableExtrinsic<${callInput}>>`)
44
+ .map(({ functionName, params, docs, callInput }) => `${commentBlock(docs, '\n', params.map((p) => `@param {${p.type}} ${p.normalizedName} ${p.docs}`))}${functionName}: GenericTxCall<Rv, (${params.map((p) => `${p.normalizedName}: ${p.type}`).join(', ')}) => ChainSubmittableExtrinsic<Rv, ${callInput}>>`)
45
45
  .join(',\n')}
46
46
 
47
- ${commentBlock('Generic pallet tx call')}[callName: string]: GenericTxCall<TxCall>,
47
+ ${commentBlock('Generic pallet tx call')}[callName: string]: GenericTxCall<Rv, TxCall<Rv>>,
48
48
  },`;
49
49
  }
50
- const importTypes = this.typesGen.typeImports.toImports();
50
+ const importTypes = this.typesGen.typeImports.toImports({ useSubPaths });
51
51
  // TODO make explicit separate type for Extra
52
52
  const defTypes = `
53
- export type ChainSubmittableExtrinsic<T extends IRuntimeTxCall = ${callTypeIn}> =
53
+ export type ChainSubmittableExtrinsic<Rv extends RpcVersion, T extends IRuntimeTxCall = ${callTypeIn}> =
54
54
  Extrinsic<${addressTypeIn}, T, ${signatureTypeIn}, any[]> &
55
- ISubmittableExtrinsic<ISubmittableResult<FrameSystemEventRecord>>
55
+ (Rv extends RpcV2
56
+ ? ISubmittableExtrinsic<ISubmittableResult<FrameSystemEventRecord, TransactionStatusV2>>
57
+ : ISubmittableExtrinsicLegacy<ISubmittableResult<FrameSystemEventRecord, TransactionStatusLegacy>>)
56
58
 
57
- export type TxCall = (...args: any[]) => ChainSubmittableExtrinsic;
59
+ export type TxCall<Rv extends RpcVersion> = (...args: any[]) => ChainSubmittableExtrinsic<Rv>;
58
60
  `;
59
61
  const template = compileTemplate('tx.hbs');
60
62
  return beautifySourceCode(template({ importTypes, defTypes, txDefsOut }));
@@ -1,14 +1,21 @@
1
+ type ImportConfig = {
2
+ excludeModules?: string[];
3
+ useSubPaths?: boolean;
4
+ };
1
5
  export declare class TypeImports {
2
6
  #private;
3
7
  portableTypes: Set<string>;
4
8
  codecTypes: Set<string>;
5
9
  knownTypes: Set<string>;
10
+ knownJsonRpcTypes: Set<string>;
6
11
  outTypes: Set<string>;
7
12
  constructor();
8
13
  clear(): void;
9
- toImports(...excludeModules: string[]): string;
14
+ toImports(config?: ImportConfig): string;
10
15
  addPortableType(...types: string[]): void;
11
16
  addCodecType(...types: string[]): void;
12
17
  addKnownType(...types: string[]): void;
18
+ addKnownJsonRpcType(...types: string[]): void;
13
19
  addOutType(...types: string[]): void;
14
20
  }
21
+ export {};
@@ -5,30 +5,37 @@ export class TypeImports {
5
5
  codecTypes;
6
6
  // Known types that're not codecs or chain/portable types defined in @dedot/types
7
7
  knownTypes;
8
+ knownJsonRpcTypes;
8
9
  // External types to define explicitly
9
10
  outTypes;
10
11
  constructor() {
11
12
  this.portableTypes = new Set();
12
13
  this.codecTypes = new Set();
13
14
  this.knownTypes = new Set();
15
+ this.knownJsonRpcTypes = new Set();
14
16
  this.outTypes = new Set();
15
17
  }
16
18
  clear() {
17
19
  this.portableTypes.clear();
18
20
  this.codecTypes.clear();
19
21
  this.knownTypes.clear();
22
+ this.knownJsonRpcTypes.clear();
20
23
  this.outTypes.clear();
21
24
  }
22
- toImports(...excludeModules) {
25
+ toImports(config) {
26
+ const { excludeModules = [], useSubPaths = false } = config || {};
23
27
  // TODO generate outTypes!
28
+ const prefix = useSubPaths ? '' : '@';
24
29
  const toImports = [
25
- [this.knownTypes, '@dedot/types'],
26
- [this.codecTypes, '@dedot/codecs'],
30
+ [this.knownTypes, `${prefix}dedot/types`],
31
+ [this.knownJsonRpcTypes, `${prefix}dedot/types/json-rpc`],
32
+ [this.codecTypes, `${prefix}dedot/codecs`],
27
33
  [this.portableTypes, './types'],
28
34
  ];
29
35
  return toImports
30
36
  .filter(([_, module]) => !excludeModules.includes(module))
31
37
  .map(([types, module]) => this.#toImportLine(types, module))
38
+ .filter((line) => line.length > 0)
32
39
  .join('\n');
33
40
  }
34
41
  #toImportLine(types, module) {
@@ -46,6 +53,9 @@ export class TypeImports {
46
53
  addKnownType(...types) {
47
54
  types.forEach((one) => this.knownTypes.add(one));
48
55
  }
56
+ addKnownJsonRpcType(...types) {
57
+ types.forEach((one) => this.knownJsonRpcTypes.add(one));
58
+ }
49
59
  addOutType(...types) {
50
60
  types.forEach((one) => this.outTypes.add(one));
51
61
  }
@@ -1,4 +1,4 @@
1
- import { PortableRegistry, Field, MetadataLatest, PortableType, TypeId } from '@dedot/codecs';
1
+ import { Field, MetadataLatest, PortableRegistry, PortableType, TypeId } from 'dedot/codecs';
2
2
  import { TypeImports } from './TypeImports.js';
3
3
  interface NamedType extends PortableType {
4
4
  name: string;
@@ -18,7 +18,7 @@ export declare class TypesGen {
18
18
  registry: PortableRegistry;
19
19
  typeImports: TypeImports;
20
20
  constructor(metadata: MetadataLatest);
21
- generate(): Promise<string>;
21
+ generate(useSubPaths?: boolean): Promise<string>;
22
22
  typeCache: Record<string, string>;
23
23
  clearCache(): void;
24
24
  generateType(typeId: TypeId, nestedLevel?: number, typeOut?: boolean): string;
@@ -1,10 +1,8 @@
1
- import { stringPascalCase } from '@polkadot/util';
2
- import { PortableRegistry } from '@dedot/codecs';
3
- import { isNativeType, normalizeName } from '@dedot/utils';
4
- import { beautifySourceCode, commentBlock, compileTemplate } from './utils.js';
5
- import { knownTypes } from './known-types.js';
1
+ import { PortableRegistry } from 'dedot/codecs';
2
+ import { normalizeName, stringPascalCase } from 'dedot/utils';
6
3
  import { TypeImports } from './TypeImports.js';
7
4
  import { findKnownCodec, findKnownCodecType, isKnownCodecType } from './known-codecs.js';
5
+ import { beautifySourceCode, commentBlock, compileTemplate, isNativeType } from './utils.js';
8
6
  // Skip generate types for these
9
7
  // as we do have native types for them
10
8
  const SKIP_TYPES = [
@@ -42,7 +40,7 @@ export class TypesGen {
42
40
  this.includedTypes = this.#includedTypes();
43
41
  this.typeImports = new TypeImports();
44
42
  }
45
- generate() {
43
+ generate(useSubPaths = false) {
46
44
  this.clearCache();
47
45
  let defTypeOut = '';
48
46
  Object.values(this.includedTypes)
@@ -53,7 +51,7 @@ export class TypesGen {
53
51
  defTypeOut += `export type ${name} = ${this.generateType(id)};\n\n`;
54
52
  }
55
53
  });
56
- const importTypes = this.typeImports.toImports('./types');
54
+ const importTypes = this.typeImports.toImports({ useSubPaths, excludeModules: ['./types'] });
57
55
  const template = compileTemplate('types.hbs');
58
56
  return beautifySourceCode(template({ importTypes, defTypeOut }));
59
57
  }
@@ -423,11 +421,6 @@ export class TypesGen {
423
421
  this.typeImports.addCodecType(typeName);
424
422
  return;
425
423
  }
426
- if (knownTypes.includes(typeName)) {
427
- this.typeImports.addKnownType(typeName);
428
- }
429
- else {
430
- this.typeImports.addOutType(typeName);
431
- }
424
+ this.typeImports.addOutType(typeName);
432
425
  }
433
426
  }
@@ -2,7 +2,7 @@ export * from './TypesGen.js';
2
2
  export * from './ApiGen.js';
3
3
  export * from './ConstsGen.js';
4
4
  export * from './QueryGen.js';
5
- export * from './RpcGen.js';
5
+ export * from './JsonRpcGen.js';
6
6
  export * from './IndexGen.js';
7
7
  export * from './ErrorsGen.js';
8
8
  export * from './EventsGen.js';
@@ -2,7 +2,7 @@ export * from './TypesGen.js';
2
2
  export * from './ApiGen.js';
3
3
  export * from './ConstsGen.js';
4
4
  export * from './QueryGen.js';
5
- export * from './RpcGen.js';
5
+ export * from './JsonRpcGen.js';
6
6
  export * from './IndexGen.js';
7
7
  export * from './ErrorsGen.js';
8
8
  export * from './EventsGen.js';
@@ -1,5 +1,5 @@
1
- import * as $ from '@dedot/shape';
2
- import { AnyShape } from '@dedot/shape';
1
+ import { $ } from 'dedot';
2
+ import { AnyShape } from 'dedot/shape';
3
3
  export type CodecName = `$${string}`;
4
4
  export interface CodecType {
5
5
  name: CodecName;
@@ -1,7 +1,7 @@
1
- import * as $ from '@dedot/shape';
2
- import * as Codecs from '@dedot/codecs';
3
- import { $AccountId20, $AccountId32, $Bytes, $ConsensusEngineId, $Era, $EthereumAddress, $MultiAddress, $OpaqueExtrinsic, $PrefixedStorageKey, $RawBytes, $StorageData, $StorageKey, $UncheckedExtrinsic, } from '@dedot/codecs';
4
- import { assert } from '@dedot/utils';
1
+ import { $ } from 'dedot';
2
+ import * as Codecs from 'dedot/codecs';
3
+ import { $AccountId20, $AccountId32, $Bytes, $ConsensusEngineId, $Era, $EthereumAddress, $MultiAddress, $OpaqueExtrinsic, $PrefixedStorageKey, $RawBytes, $StorageData, $StorageKey, $UncheckedExtrinsic, } from 'dedot/codecs';
4
+ import { assert } from 'dedot/utils';
5
5
  export const normalizeCodecName = (name) => {
6
6
  return name.startsWith('$') ? name : `$${name}`;
7
7
  };
@@ -8,3 +8,8 @@ export declare const compileTemplate: (templateFileName: string) => HandlebarsTe
8
8
  * @param word
9
9
  */
10
10
  export declare const isReservedWord: (word: string) => boolean;
11
+ /**
12
+ * Check if a type is native JS/TS type
13
+ * @param type
14
+ */
15
+ export declare const isNativeType: (type: string) => boolean;
@@ -33,3 +33,31 @@ const TS_RESERVED_WORDS = ['new', 'class'];
33
33
  * @param word
34
34
  */
35
35
  export const isReservedWord = (word) => TS_RESERVED_WORDS.includes(word);
36
+ const TS_PRIMITIVE_TYPES = [
37
+ 'void',
38
+ 'undefined',
39
+ 'null',
40
+ 'number',
41
+ 'boolean',
42
+ 'bigint',
43
+ 'Map',
44
+ 'Set',
45
+ 'string',
46
+ 'any',
47
+ 'Array',
48
+ 'Record',
49
+ ];
50
+ /**
51
+ * Check if a type is native JS/TS type
52
+ * @param type
53
+ */
54
+ export const isNativeType = (type) => {
55
+ return TS_PRIMITIVE_TYPES.some((one) => {
56
+ if (typeof one === 'string') {
57
+ return one === type;
58
+ }
59
+ else {
60
+ return type.match(one);
61
+ }
62
+ });
63
+ };
package/index.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { MetadataLatest } from '@dedot/codecs';
2
- import { NetworkInfo } from './types.js';
3
- export declare function generateTypesFromChain(network: NetworkInfo, endpoint: string, outDir: string): Promise<void>;
4
- export declare function generateTypes(network: NetworkInfo, metadata: MetadataLatest, rpcMethods: string[], runtimeApis: any[], outDir?: string): Promise<void>;
1
+ import { MetadataLatest } from 'dedot/codecs';
2
+ export declare function generateTypesFromEndpoint(chain: string, endpoint: string, outDir?: string, extension?: string, useSubPaths?: boolean): Promise<void>;
3
+ export declare function generateTypes(chain: string, metadata: MetadataLatest, rpcMethods: string[], runtimeApis: Record<string, number>, outDir?: string, extension?: string, useSubPaths?: boolean): Promise<void>;
package/index.js CHANGED
@@ -1,48 +1,48 @@
1
- import { Dedot } from 'dedot';
1
+ import { Dedot, WsProvider } from 'dedot';
2
+ import { stringCamelCase } from 'dedot/utils';
2
3
  import * as fs from 'fs';
3
4
  import * as path from 'path';
4
- import { ConstsGen, ErrorsGen, EventsGen, IndexGen, QueryGen, RpcGen, RuntimeApisGen, TxGen, TypesGen, } from './generator/index.js';
5
- import { stringCamelCase } from '@polkadot/util';
6
- export async function generateTypesFromChain(network, endpoint, outDir) {
7
- const api = await Dedot.create(endpoint);
8
- const { methods } = await api.rpc.rpc.methods();
9
- const apis = api.runtimeVersion?.apis || [];
10
- if (!network.chain) {
11
- network.chain = stringCamelCase(api.runtimeVersion?.specName || api.runtimeChain || 'local');
5
+ import { ConstsGen, ErrorsGen, EventsGen, IndexGen, JsonRpcGen, QueryGen, RuntimeApisGen, TxGen, TypesGen, } from './generator/index.js';
6
+ export async function generateTypesFromEndpoint(chain, endpoint, outDir, extension = 'd.ts', useSubPaths = false) {
7
+ const api = await Dedot.new(new WsProvider(endpoint));
8
+ const { methods } = await api.rpc.rpc_methods();
9
+ const apis = api.runtimeVersion.apis || {};
10
+ if (!chain) {
11
+ chain = stringCamelCase(api.runtimeVersion.specName || 'local');
12
12
  }
13
- await generateTypes(network, api.metadataLatest, methods, apis, outDir);
13
+ await generateTypes(chain, api.metadata.latest, methods, apis, outDir, extension, useSubPaths);
14
14
  await api.disconnect();
15
15
  }
16
- export async function generateTypes(network, metadata, rpcMethods, runtimeApis, outDir = '.') {
17
- const dirPath = path.resolve(outDir, network.chain);
18
- const defTypesFileName = path.join(dirPath, `types.d.ts`);
19
- const constsTypesFileName = path.join(dirPath, `consts.d.ts`);
20
- const queryTypesFileName = path.join(dirPath, `query.d.ts`);
21
- const rpcCallsFileName = path.join(dirPath, `rpc.d.ts`);
22
- const indexFileName = path.join(dirPath, `index.d.ts`);
23
- const errorsFileName = path.join(dirPath, `errors.d.ts`);
24
- const eventsFileName = path.join(dirPath, `events.d.ts`);
25
- const runtimeApisFileName = path.join(dirPath, `runtime.d.ts`);
26
- const txFileName = path.join(dirPath, `tx.d.ts`);
16
+ export async function generateTypes(chain, metadata, rpcMethods, runtimeApis, outDir = '.', extension = 'd.ts', useSubPaths = false) {
17
+ const dirPath = path.resolve(outDir, chain);
18
+ const defTypesFileName = path.join(dirPath, `types.${extension}`);
19
+ const constsTypesFileName = path.join(dirPath, `consts.${extension}`);
20
+ const queryTypesFileName = path.join(dirPath, `query.${extension}`);
21
+ const jsonRpcFileName = path.join(dirPath, `json-rpc.${extension}`);
22
+ const indexFileName = path.join(dirPath, `index.${extension}`);
23
+ const errorsFileName = path.join(dirPath, `errors.${extension}`);
24
+ const eventsFileName = path.join(dirPath, `events.${extension}`);
25
+ const runtimeApisFileName = path.join(dirPath, `runtime.${extension}`);
26
+ const txFileName = path.join(dirPath, `tx.${extension}`);
27
27
  if (!fs.existsSync(dirPath)) {
28
28
  fs.mkdirSync(dirPath, { recursive: true });
29
29
  }
30
30
  const typesGen = new TypesGen(metadata);
31
31
  const constsGen = new ConstsGen(typesGen);
32
32
  const queryGen = new QueryGen(typesGen);
33
- const rpcGen = new RpcGen(typesGen, rpcMethods);
34
- const indexGen = new IndexGen(network);
33
+ const jsonRpcGen = new JsonRpcGen(typesGen, rpcMethods);
34
+ const indexGen = new IndexGen(chain);
35
35
  const errorsGen = new ErrorsGen(typesGen);
36
36
  const eventsGen = new EventsGen(typesGen);
37
37
  const runtimeApisGen = new RuntimeApisGen(typesGen, runtimeApis);
38
38
  const txGen = new TxGen(typesGen);
39
- fs.writeFileSync(defTypesFileName, await typesGen.generate());
40
- fs.writeFileSync(errorsFileName, await errorsGen.generate());
41
- fs.writeFileSync(eventsFileName, await eventsGen.generate());
42
- fs.writeFileSync(rpcCallsFileName, await rpcGen.generate());
43
- fs.writeFileSync(queryTypesFileName, await queryGen.generate());
44
- fs.writeFileSync(constsTypesFileName, await constsGen.generate());
45
- fs.writeFileSync(txFileName, await txGen.generate());
46
- fs.writeFileSync(indexFileName, await indexGen.generate());
47
- fs.writeFileSync(runtimeApisFileName, await runtimeApisGen.generate());
39
+ fs.writeFileSync(defTypesFileName, await typesGen.generate(useSubPaths));
40
+ fs.writeFileSync(errorsFileName, await errorsGen.generate(useSubPaths));
41
+ fs.writeFileSync(eventsFileName, await eventsGen.generate(useSubPaths));
42
+ fs.writeFileSync(jsonRpcFileName, await jsonRpcGen.generate(useSubPaths));
43
+ fs.writeFileSync(queryTypesFileName, await queryGen.generate(useSubPaths));
44
+ fs.writeFileSync(constsTypesFileName, await constsGen.generate(useSubPaths));
45
+ fs.writeFileSync(txFileName, await txGen.generate(useSubPaths));
46
+ fs.writeFileSync(indexFileName, await indexGen.generate(useSubPaths));
47
+ fs.writeFileSync(runtimeApisFileName, await runtimeApisGen.generate(useSubPaths));
48
48
  }