@dedot/codegen 0.0.1-alpha.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 (55) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +3 -0
  3. package/cjs/genSupportedChainTypes.js +76 -0
  4. package/cjs/generator/ApiGen.js +16 -0
  5. package/cjs/generator/ConstsGen.js +32 -0
  6. package/cjs/generator/ErrorsGen.js +41 -0
  7. package/cjs/generator/EventsGen.js +68 -0
  8. package/cjs/generator/IndexGen.js +18 -0
  9. package/cjs/generator/QueryGen.js +59 -0
  10. package/cjs/generator/RpcGen.js +175 -0
  11. package/cjs/generator/RuntimeApisGen.js +120 -0
  12. package/cjs/generator/TxGen.js +90 -0
  13. package/cjs/generator/TypeImports.js +56 -0
  14. package/cjs/generator/TypesGen.js +436 -0
  15. package/cjs/generator/index.js +26 -0
  16. package/cjs/generator/utils.js +47 -0
  17. package/cjs/index.js +50 -0
  18. package/cjs/package.json +1 -0
  19. package/cjs/packageInfo.js +5 -0
  20. package/cjs/types.js +2 -0
  21. package/genSupportedChainTypes.d.ts +1 -0
  22. package/genSupportedChainTypes.js +74 -0
  23. package/generator/ApiGen.d.ts +138 -0
  24. package/generator/ApiGen.js +12 -0
  25. package/generator/ConstsGen.d.ts +4 -0
  26. package/generator/ConstsGen.js +28 -0
  27. package/generator/ErrorsGen.d.ts +5 -0
  28. package/generator/ErrorsGen.js +37 -0
  29. package/generator/EventsGen.d.ts +5 -0
  30. package/generator/EventsGen.js +64 -0
  31. package/generator/IndexGen.d.ts +6 -0
  32. package/generator/IndexGen.js +14 -0
  33. package/generator/QueryGen.d.ts +5 -0
  34. package/generator/QueryGen.js +55 -0
  35. package/generator/RpcGen.d.ts +10 -0
  36. package/generator/RpcGen.js +171 -0
  37. package/generator/RuntimeApisGen.d.ts +9 -0
  38. package/generator/RuntimeApisGen.js +116 -0
  39. package/generator/TxGen.d.ts +5 -0
  40. package/generator/TxGen.js +86 -0
  41. package/generator/TypeImports.d.ts +14 -0
  42. package/generator/TypeImports.js +52 -0
  43. package/generator/TypesGen.d.ts +30 -0
  44. package/generator/TypesGen.js +432 -0
  45. package/generator/index.d.ts +10 -0
  46. package/generator/index.js +10 -0
  47. package/generator/utils.d.ts +11 -0
  48. package/generator/utils.js +39 -0
  49. package/index.d.ts +4 -0
  50. package/index.js +45 -0
  51. package/package.json +48 -0
  52. package/packageInfo.d.ts +4 -0
  53. package/packageInfo.js +3 -0
  54. package/types.d.ts +6 -0
  55. package/types.js +1 -0
@@ -0,0 +1,116 @@
1
+ import { findRuntimeApiSpec } from '@dedot/specs';
2
+ import { beautifySourceCode, commentBlock, compileTemplate } from './utils';
3
+ import { calculateRuntimeApiHash, stringSnakeCase } from '@dedot/utils';
4
+ import { RpcGen } from './RpcGen';
5
+ import { stringCamelCase } from '@polkadot/util';
6
+ export class RuntimeApisGen extends RpcGen {
7
+ typesGen;
8
+ runtimeApis;
9
+ constructor(typesGen, runtimeApis) {
10
+ super(typesGen, []);
11
+ this.typesGen = typesGen;
12
+ this.runtimeApis = runtimeApis;
13
+ }
14
+ generate() {
15
+ this.typesGen.clearCache();
16
+ this.typesGen.typeImports.addKnownType('GenericRuntimeApis', 'GenericRuntimeApiMethod');
17
+ let runtimeCallsOut = '';
18
+ if (this.metadata.apis.length > 0) {
19
+ this.metadata.apis.forEach((runtimeApi) => {
20
+ const { name: runtimeApiName, methods } = runtimeApi;
21
+ runtimeCallsOut += commentBlock(`@runtimeapi: ${runtimeApiName} - ${calculateRuntimeApiHash(runtimeApiName)}`);
22
+ runtimeCallsOut += `${stringCamelCase(runtimeApiName)}: {
23
+ ${methods.map((method) => this.#generateMethodDef(runtimeApiName, method)).join('\n')}
24
+
25
+ ${commentBlock('Generic runtime api call')}[method: string]: GenericRuntimeApiMethod
26
+ }`;
27
+ });
28
+ }
29
+ else {
30
+ const specsByModule = this.#runtimeApisSpecsByModule();
31
+ Object.values(specsByModule).forEach((specs) => {
32
+ specs.forEach(({ methods, runtimeApiName, runtimeApiHash, version }) => {
33
+ runtimeCallsOut += commentBlock(`@runtimeapi: ${runtimeApiName} - ${runtimeApiHash}`, `@version: ${version}`);
34
+ runtimeCallsOut += `${stringCamelCase(runtimeApiName)}: {
35
+ ${Object.keys(methods)
36
+ .map((methodName) => this.#generateMethodDefFromSpec({ ...methods[methodName], runtimeApiName, methodName }))
37
+ .join('\n')}
38
+
39
+ ${commentBlock('Generic runtime api call')}[method: string]: GenericRuntimeApiMethod
40
+ }`;
41
+ });
42
+ });
43
+ }
44
+ const importTypes = this.typesGen.typeImports.toImports();
45
+ const template = compileTemplate('runtime.hbs');
46
+ return beautifySourceCode(template({ importTypes, runtimeCallsOut }));
47
+ }
48
+ #isOptionalType(type) {
49
+ return type.startsWith('Option<') || type.endsWith('| undefined');
50
+ }
51
+ #isOptionalParam(params, type, idx) {
52
+ return this.#isOptionalType(type) && params.slice(idx + 1).every(({ type }) => this.#isOptionalType(type));
53
+ }
54
+ #generateMethodDefFromSpec(spec) {
55
+ const { docs = [], params, type, runtimeApiName, methodName } = spec;
56
+ const callName = `${runtimeApiName}_${stringSnakeCase(methodName)}`;
57
+ const defaultDocs = [`@callname: ${callName}`];
58
+ this.addTypeImport(type, false);
59
+ params.forEach(({ type }) => this.addTypeImport(type));
60
+ const typedParams = params.map((param, idx) => ({
61
+ ...param,
62
+ isOptional: this.#isOptionalParam(params, param.type, idx),
63
+ plainType: this.getGeneratedTypeName(param.type),
64
+ }));
65
+ const paramsOut = typedParams
66
+ .map(({ name, isOptional, plainType }) => `${stringCamelCase(name)}${isOptional ? '?' : ''}: ${plainType}`)
67
+ .join(', ');
68
+ const typeOut = this.getGeneratedTypeName(type, false);
69
+ return `${commentBlock(docs, '\n', defaultDocs, typedParams.map(({ plainType, name }) => `@param {${plainType}} ${name}`))}${methodName}: GenericRuntimeApiMethod<(${paramsOut}) => Promise<${typeOut}>>`;
70
+ }
71
+ #generateMethodDef(runtimeApiName, methodDef) {
72
+ const { name: methodName, inputs, output, docs } = methodDef;
73
+ const callName = `${runtimeApiName}_${stringSnakeCase(methodName)}`;
74
+ const defaultDocs = [`@callname: ${callName}`];
75
+ const typeOut = this.typesGen.generateType(output, 1, true);
76
+ this.addTypeImport(typeOut, false);
77
+ const typedInputs = inputs
78
+ .map((input, idx) => ({
79
+ ...input,
80
+ type: this.typesGen.generateType(input.typeId, 1),
81
+ }))
82
+ .map((input, idx, inputs) => ({
83
+ ...input,
84
+ isOptional: this.#isOptionalParam(inputs, input.type, idx),
85
+ }));
86
+ this.addTypeImport(typedInputs.map((t) => t.type));
87
+ const paramsOut = typedInputs
88
+ .map(({ name, type, isOptional }) => `${stringCamelCase(name)}${isOptional ? '?' : ''}: ${type}`)
89
+ .join(', ');
90
+ return `${commentBlock(docs, '\n', defaultDocs, typedInputs.map(({ type, name }) => `@param {${type}} ${name}`))}${stringCamelCase(methodName)}: GenericRuntimeApiMethod<(${paramsOut}) => Promise<${typeOut}>>`;
91
+ }
92
+ #runtimeApisSpecsByModule() {
93
+ const specs = this.runtimeApis.map(([runtimeApiHash, version]) => {
94
+ const runtimeApiSpec = findRuntimeApiSpec(runtimeApiHash, version);
95
+ if (!runtimeApiSpec)
96
+ return;
97
+ return {
98
+ ...runtimeApiSpec,
99
+ runtimeApiHash,
100
+ };
101
+ });
102
+ return specs.reduce((o, spec) => {
103
+ if (!spec) {
104
+ return o;
105
+ }
106
+ const { moduleName } = spec;
107
+ if (!moduleName) {
108
+ return o;
109
+ }
110
+ return {
111
+ ...o,
112
+ [moduleName]: o[moduleName] ? [...o[moduleName], spec] : [spec],
113
+ };
114
+ }, {});
115
+ }
116
+ }
@@ -0,0 +1,5 @@
1
+ import { ApiGen } from '../generator';
2
+ export declare class TxGen extends ApiGen {
3
+ #private;
4
+ generate(): Promise<string>;
5
+ }
@@ -0,0 +1,86 @@
1
+ import { ApiGen } from '../generator';
2
+ import { stringCamelCase, stringPascalCase } from '@polkadot/util';
3
+ import { beautifySourceCode, commentBlock, compileTemplate, isReservedWord } from './utils';
4
+ export class TxGen extends ApiGen {
5
+ generate() {
6
+ const { pallets, types } = this.metadata;
7
+ this.typesGen.clearCache();
8
+ this.typesGen.typeImports.addKnownType('GenericChainTx', 'GenericTxCall', 'ISubmittableExtrinsic', 'ISubmittableResult', 'IRuntimeTxCall');
9
+ const { callTypeId, addressTypeId, signatureTypeId } = this.metadata.extrinsic;
10
+ const callTypeIn = this.typesGen.generateType(callTypeId, 1);
11
+ const addressTypeIn = this.typesGen.generateType(addressTypeId, 1);
12
+ const signatureTypeIn = this.typesGen.generateType(signatureTypeId, 1);
13
+ this.typesGen.typeImports.addPortableType('FrameSystemEventRecord');
14
+ this.typesGen.typeImports.addCodecType('Extrinsic');
15
+ this.typesGen.addTypeImport([callTypeIn, addressTypeIn, signatureTypeIn]);
16
+ let txDefsOut = '';
17
+ for (let pallet of pallets) {
18
+ if (pallet.calls === undefined)
19
+ continue;
20
+ const { type } = types[pallet.calls];
21
+ if (type.tag !== 'Enum')
22
+ continue;
23
+ const isFlatEnum = type.value.members.every((m) => m.fields.length === 0);
24
+ const typedTxs = type.value.members
25
+ .map((one) => ({
26
+ functionName: stringCamelCase(one.name),
27
+ params: one.fields.map((f) => ({
28
+ name: stringCamelCase(f.name),
29
+ normalizedName: this.#normalizeParamName(f.name),
30
+ type: this.typesGen.generateType(f.typeId, 1),
31
+ docs: f.docs,
32
+ })),
33
+ docs: one.docs,
34
+ }))
35
+ .map((f) => {
36
+ return {
37
+ ...f,
38
+ callInput: this.#generateCallInput(stringPascalCase(pallet.name), stringPascalCase(f.functionName), !isFlatEnum ? f.params.map((p) => `${p.name}: ${p.type}`) : undefined),
39
+ };
40
+ });
41
+ txDefsOut += commentBlock(`Pallet \`${pallet.name}\`'s transaction calls`);
42
+ txDefsOut += `${stringCamelCase(pallet.name)}: {
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}>>`)
45
+ .join(',\n')}
46
+
47
+ ${commentBlock('Generic pallet tx call')}[callName: string]: GenericTxCall<TxCall>,
48
+ },`;
49
+ }
50
+ const importTypes = this.typesGen.typeImports.toImports();
51
+ // TODO make explicit separate type for Extra
52
+ const defTypes = `
53
+ export type ChainSubmittableExtrinsic<T extends IRuntimeTxCall = ${callTypeIn}> =
54
+ Extrinsic<${addressTypeIn}, T, ${signatureTypeIn}, any[]> &
55
+ ISubmittableExtrinsic<ISubmittableResult<FrameSystemEventRecord>>
56
+
57
+ export type TxCall = (...args: any[]) => ChainSubmittableExtrinsic;
58
+ `;
59
+ const template = compileTemplate('tx.hbs');
60
+ return beautifySourceCode(template({ importTypes, defTypes, txDefsOut }));
61
+ }
62
+ #normalizeParamName(name) {
63
+ name = stringCamelCase(name);
64
+ return isReservedWord(name) ? `${name}_` : name;
65
+ }
66
+ #generateCallInput(palletName, callName, params) {
67
+ if (!params) {
68
+ return `
69
+ {
70
+ pallet: '${palletName}',
71
+ palletCall: '${callName}'
72
+ }
73
+ `;
74
+ }
75
+ const paramsOut = params.length > 0 ? `params: { ${params.join(',')} }` : '';
76
+ return `
77
+ {
78
+ pallet: '${palletName}',
79
+ palletCall: {
80
+ name: '${callName}',
81
+ ${paramsOut}
82
+ }
83
+ }
84
+ `;
85
+ }
86
+ }
@@ -0,0 +1,14 @@
1
+ export declare class TypeImports {
2
+ #private;
3
+ portableTypes: Set<string>;
4
+ codecTypes: Set<string>;
5
+ knownTypes: Set<string>;
6
+ outTypes: Set<string>;
7
+ constructor();
8
+ clear(): void;
9
+ toImports(...excludeModules: string[]): string;
10
+ addPortableType(...types: string[]): void;
11
+ addCodecType(...types: string[]): void;
12
+ addKnownType(...types: string[]): void;
13
+ addOutType(...types: string[]): void;
14
+ }
@@ -0,0 +1,52 @@
1
+ export class TypeImports {
2
+ // Portable types from chain/metadata
3
+ portableTypes;
4
+ // Known types that has a corresponding codec defined in @dedot/codecs
5
+ codecTypes;
6
+ // Known types that're not codecs or chain/portable types defined in @dedot/types
7
+ knownTypes;
8
+ // External types to define explicitly
9
+ outTypes;
10
+ constructor() {
11
+ this.portableTypes = new Set();
12
+ this.codecTypes = new Set();
13
+ this.knownTypes = new Set();
14
+ this.outTypes = new Set();
15
+ }
16
+ clear() {
17
+ this.portableTypes.clear();
18
+ this.codecTypes.clear();
19
+ this.knownTypes.clear();
20
+ this.outTypes.clear();
21
+ }
22
+ toImports(...excludeModules) {
23
+ // TODO generate outTypes!
24
+ const toImports = [
25
+ [this.knownTypes, '@dedot/types'],
26
+ [this.codecTypes, '@dedot/codecs'],
27
+ [this.portableTypes, './types'],
28
+ ];
29
+ return toImports
30
+ .filter(([_, module]) => !excludeModules.includes(module))
31
+ .map(([types, module]) => this.#toImportLine(types, module))
32
+ .join('\n');
33
+ }
34
+ #toImportLine(types, module) {
35
+ const typesToImports = [...types];
36
+ if (typesToImports.length === 0)
37
+ return '';
38
+ return `import type {${typesToImports.join(', ')}} from "${module}"`;
39
+ }
40
+ addPortableType(...types) {
41
+ types.forEach((one) => this.portableTypes.add(one));
42
+ }
43
+ addCodecType(...types) {
44
+ types.forEach((one) => this.codecTypes.add(one));
45
+ }
46
+ addKnownType(...types) {
47
+ types.forEach((one) => this.knownTypes.add(one));
48
+ }
49
+ addOutType(...types) {
50
+ types.forEach((one) => this.outTypes.add(one));
51
+ }
52
+ }
@@ -0,0 +1,30 @@
1
+ import { CodecRegistry, Field, MetadataLatest, PortableType, TypeId } from '@dedot/codecs';
2
+ import { TypeImports } from './TypeImports';
3
+ interface NamedType extends PortableType {
4
+ name: string;
5
+ nameOut: string;
6
+ skip?: boolean;
7
+ knownType?: boolean;
8
+ suffix?: string;
9
+ }
10
+ export declare const BASIC_KNOWN_TYPES: string[];
11
+ export declare class TypesGen {
12
+ #private;
13
+ metadata: MetadataLatest;
14
+ /**
15
+ * Types will be generated its definition out.
16
+ */
17
+ includedTypes: Record<TypeId, NamedType>;
18
+ registry: CodecRegistry;
19
+ typeImports: TypeImports;
20
+ constructor(metadata: MetadataLatest);
21
+ generate(): Promise<string>;
22
+ typeCache: Record<string, string>;
23
+ clearCache(): void;
24
+ generateType(typeId: TypeId, nestedLevel?: number, typeOut?: boolean): string;
25
+ generateObjectType(fields: Field[], nestedLevel?: number, typeOut?: boolean): string;
26
+ eqlCache: Map<string, boolean>;
27
+ typeEql(idA: number, idB: number, level?: number): boolean;
28
+ addTypeImport(typeName: string | string[]): void;
29
+ }
30
+ export {};