@dedot/codegen 0.0.1-alpha.11

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/LICENSE +201 -0
  2. package/README.md +3 -0
  3. package/cjs/genSupportedChainTypes.js +79 -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/dirname.js +5 -0
  16. package/cjs/generator/index.js +26 -0
  17. package/cjs/generator/utils.js +68 -0
  18. package/cjs/index.js +76 -0
  19. package/cjs/package.json +1 -0
  20. package/cjs/packageInfo.js +5 -0
  21. package/cjs/templates/consts.hbs +7 -0
  22. package/cjs/templates/errors.hbs +7 -0
  23. package/cjs/templates/events.hbs +7 -0
  24. package/cjs/templates/index.hbs +22 -0
  25. package/cjs/templates/query.hbs +7 -0
  26. package/cjs/templates/rpc.hbs +7 -0
  27. package/cjs/templates/runtime.hbs +8 -0
  28. package/cjs/templates/tx.hbs +9 -0
  29. package/cjs/templates/types.hbs +5 -0
  30. package/cjs/types.js +2 -0
  31. package/genSupportedChainTypes.d.ts +1 -0
  32. package/genSupportedChainTypes.js +74 -0
  33. package/generator/ApiGen.d.ts +138 -0
  34. package/generator/ApiGen.js +12 -0
  35. package/generator/ConstsGen.d.ts +4 -0
  36. package/generator/ConstsGen.js +28 -0
  37. package/generator/ErrorsGen.d.ts +5 -0
  38. package/generator/ErrorsGen.js +37 -0
  39. package/generator/EventsGen.d.ts +5 -0
  40. package/generator/EventsGen.js +64 -0
  41. package/generator/IndexGen.d.ts +6 -0
  42. package/generator/IndexGen.js +14 -0
  43. package/generator/QueryGen.d.ts +5 -0
  44. package/generator/QueryGen.js +55 -0
  45. package/generator/RpcGen.d.ts +10 -0
  46. package/generator/RpcGen.js +171 -0
  47. package/generator/RuntimeApisGen.d.ts +9 -0
  48. package/generator/RuntimeApisGen.js +116 -0
  49. package/generator/TxGen.d.ts +5 -0
  50. package/generator/TxGen.js +86 -0
  51. package/generator/TypeImports.d.ts +14 -0
  52. package/generator/TypeImports.js +52 -0
  53. package/generator/TypesGen.d.ts +30 -0
  54. package/generator/TypesGen.js +432 -0
  55. package/generator/dirname.d.ts +1 -0
  56. package/generator/dirname.js +6 -0
  57. package/generator/index.d.ts +10 -0
  58. package/generator/index.js +10 -0
  59. package/generator/utils.d.ts +10 -0
  60. package/generator/utils.js +35 -0
  61. package/index.d.ts +4 -0
  62. package/index.js +48 -0
  63. package/package.json +49 -0
  64. package/packageInfo.d.ts +4 -0
  65. package/packageInfo.js +2 -0
  66. package/templates/consts.hbs +7 -0
  67. package/templates/errors.hbs +7 -0
  68. package/templates/events.hbs +7 -0
  69. package/templates/index.hbs +22 -0
  70. package/templates/query.hbs +7 -0
  71. package/templates/rpc.hbs +7 -0
  72. package/templates/runtime.hbs +8 -0
  73. package/templates/tx.hbs +9 -0
  74. package/templates/types.hbs +5 -0
  75. package/types.d.ts +6 -0
  76. package/types.js +1 -0
@@ -0,0 +1,175 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RpcGen = void 0;
4
+ const specs_1 = require("@dedot/specs");
5
+ const utils_1 = require("@dedot/utils");
6
+ const generator_1 = require("../generator");
7
+ const utils_2 = require("./utils");
8
+ const HIDDEN_RPCS = [
9
+ // Ref: https://github.com/paritytech/polkadot-sdk/blob/43415ef58c143b985e09015cd000dbd65f6d3997/substrate/client/rpc-servers/src/lib.rs#L152C9-L158
10
+ 'rpc_methods',
11
+ ];
12
+ class RpcGen extends generator_1.ApiGen {
13
+ typesGen;
14
+ rpcMethods;
15
+ constructor(typesGen, rpcMethods) {
16
+ super(typesGen);
17
+ this.typesGen = typesGen;
18
+ this.rpcMethods = rpcMethods;
19
+ HIDDEN_RPCS.filter((one) => !rpcMethods.includes(one)).forEach((one) => rpcMethods.push(one));
20
+ rpcMethods.sort();
21
+ }
22
+ generate() {
23
+ this.typesGen.clearCache();
24
+ this.typesGen.typeImports.addKnownType('GenericRpcCalls', 'Unsub', 'Callback', 'GenericRpcCall');
25
+ const specsByModule = this.rpcMethods
26
+ .filter((one) => !(0, specs_1.findAliasRpcSpec)(one)) // we'll ignore alias rpc for now if defined in the specs! TODO should we generate alias rpc as well?
27
+ .filter((one) => !(0, specs_1.isUnsubscribeMethod)(one)) // we'll ignore unsubscribe method as well
28
+ .map((one) => {
29
+ const spec = (0, specs_1.findRpcSpec)(one);
30
+ if (spec) {
31
+ return spec;
32
+ }
33
+ const [module, ...methodParts] = one.split('_');
34
+ const method = methodParts.join('_');
35
+ return {
36
+ params: [],
37
+ type: 'GenericRpcCall',
38
+ module,
39
+ method,
40
+ };
41
+ })
42
+ .reduce((o, spec) => {
43
+ const { module, method } = spec;
44
+ // ignore if rpc name does not confront with the general convention
45
+ if (!module || !method) {
46
+ return o;
47
+ }
48
+ return {
49
+ ...o,
50
+ [module]: o[module] ? [...o[module], spec] : [spec],
51
+ };
52
+ }, {});
53
+ let rpcCallsOut = '';
54
+ Object.keys(specsByModule).forEach((module) => {
55
+ const specs = specsByModule[module];
56
+ // TODO add alias info to docs block!
57
+ rpcCallsOut += `${module}: {
58
+ ${specs.map((spec) => this.#generateMethodDef(spec)).join(',\n')},
59
+
60
+ [method: string]: GenericRpcCall,
61
+ },`;
62
+ });
63
+ // TODO include & define external types
64
+ const importTypes = this.typesGen.typeImports.toImports();
65
+ const template = (0, utils_2.compileTemplate)('rpc.hbs');
66
+ return (0, utils_2.beautifySourceCode)(template({ importTypes, rpcCallsOut }));
67
+ }
68
+ #generateMethodDef(spec) {
69
+ const { name, type, module, method, docs = [], params, pubsub, deprecated } = spec;
70
+ const rpcName = name || `${module}_${method}`;
71
+ let defaultDocs = [`@rpcname: ${rpcName}`];
72
+ if (deprecated) {
73
+ defaultDocs.push(`@deprecated: ${deprecated}`);
74
+ }
75
+ if (type === 'GenericRpcCall' && params.length === 0) {
76
+ return `${(0, utils_2.commentBlock)(defaultDocs)}${method}: GenericRpcCall`;
77
+ }
78
+ this.addTypeImport(type, false);
79
+ params.forEach(({ type, isScale }) => {
80
+ this.addTypeImport(type, !!isScale);
81
+ });
82
+ const typedParams = params.map((param) => ({
83
+ ...param,
84
+ plainType: this.getGeneratedTypeName(param.type, !!param.isScale),
85
+ }));
86
+ const isSubscription = !!pubsub;
87
+ const paramsOut = typedParams.map(({ name, type, isOptional, isScale, plainType }) => `${name}${isOptional ? '?' : ''}: ${plainType}`);
88
+ const paramsDoc = typedParams.map(({ name, plainType }) => `@param {${plainType}} ${name}`);
89
+ const typeOut = this.getGeneratedTypeName(type, false);
90
+ if (isSubscription) {
91
+ defaultDocs.shift();
92
+ defaultDocs.unshift(`@pubsub: ${pubsub?.join(', ')}`);
93
+ paramsOut.push(`callback: Callback<${typeOut}>`);
94
+ return `${(0, utils_2.commentBlock)(docs, '\n', defaultDocs, paramsDoc)}${method}: GenericRpcCall<(${paramsOut.join(', ')}) => Promise<Unsub>>`;
95
+ }
96
+ else {
97
+ return `${(0, utils_2.commentBlock)(docs, '\n', defaultDocs, paramsDoc)}${method}: GenericRpcCall<(${paramsOut.join(', ')}) => Promise<${typeOut}>>`;
98
+ }
99
+ }
100
+ // TODO check typeIn, typeOut if param type, or rpc type isScale
101
+ addTypeImport(type, toTypeIn = true) {
102
+ if (Array.isArray(type)) {
103
+ type.forEach((one) => this.addTypeImport(one, toTypeIn));
104
+ return;
105
+ }
106
+ type = type.trim();
107
+ if ((0, utils_1.isNativeType)(type)) {
108
+ return;
109
+ }
110
+ // Handle generic wrapper types
111
+ const matchArray = type.match(utils_2.WRAPPER_TYPE_REGEX);
112
+ if (matchArray) {
113
+ const [_, $1, $2] = matchArray;
114
+ this.addTypeImport($1, toTypeIn);
115
+ if ($2.match(utils_2.WRAPPER_TYPE_REGEX) || $2.match(utils_2.TUPLE_TYPE_REGEX)) {
116
+ this.addTypeImport($2, toTypeIn);
117
+ }
118
+ else {
119
+ this.addTypeImport($2.split(','), toTypeIn);
120
+ }
121
+ return;
122
+ }
123
+ // Check tuple type
124
+ if (type.match(utils_2.TUPLE_TYPE_REGEX)) {
125
+ this.addTypeImport(type.slice(1, -1).split(','), toTypeIn);
126
+ return;
127
+ }
128
+ if (type.includes(' | ')) {
129
+ this.addTypeImport(type.split(' | ').map((one) => one.trim()), toTypeIn);
130
+ return;
131
+ }
132
+ try {
133
+ const codecType = this.#getCodecType(type, toTypeIn);
134
+ if ((0, utils_1.isNativeType)(codecType))
135
+ return;
136
+ this.typesGen.typeImports.addCodecType(codecType);
137
+ return;
138
+ }
139
+ catch (e) { }
140
+ this.typesGen.addTypeImport(type);
141
+ }
142
+ getGeneratedTypeName(type, toTypeIn = true) {
143
+ try {
144
+ const matchArray = type.match(utils_2.WRAPPER_TYPE_REGEX);
145
+ if (matchArray) {
146
+ const [_, $1, $2] = matchArray;
147
+ const wrapperTypeName = this.#getCodecType($1, toTypeIn);
148
+ if ($2.match(utils_2.WRAPPER_TYPE_REGEX) || $2.match(utils_2.TUPLE_TYPE_REGEX)) {
149
+ return `${wrapperTypeName}<${this.getGeneratedTypeName($2, toTypeIn)}>`;
150
+ }
151
+ const innerTypeNames = $2
152
+ .split(',')
153
+ .map((one) => this.getGeneratedTypeName(one.trim(), toTypeIn))
154
+ .join(', ');
155
+ return `${wrapperTypeName}<${innerTypeNames}>`;
156
+ }
157
+ else if (type.match(utils_2.TUPLE_TYPE_REGEX)) {
158
+ const innerTypeNames = type
159
+ .slice(1, -1)
160
+ .split(',')
161
+ .map((one) => this.getGeneratedTypeName(one.trim(), toTypeIn))
162
+ .join(', ');
163
+ return `[${innerTypeNames}]`;
164
+ }
165
+ return this.#getCodecType(type, toTypeIn);
166
+ }
167
+ catch (e) { }
168
+ return type;
169
+ }
170
+ #getCodecType(type, toTypeIn = true) {
171
+ const { typeIn, typeOut } = this.registry.findCodecType(type);
172
+ return toTypeIn ? typeIn : typeOut;
173
+ }
174
+ }
175
+ exports.RpcGen = RpcGen;
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RuntimeApisGen = void 0;
4
+ const specs_1 = require("@dedot/specs");
5
+ const utils_1 = require("./utils");
6
+ const utils_2 = require("@dedot/utils");
7
+ const RpcGen_1 = require("./RpcGen");
8
+ const util_1 = require("@polkadot/util");
9
+ class RuntimeApisGen extends RpcGen_1.RpcGen {
10
+ typesGen;
11
+ runtimeApis;
12
+ constructor(typesGen, runtimeApis) {
13
+ super(typesGen, []);
14
+ this.typesGen = typesGen;
15
+ this.runtimeApis = runtimeApis;
16
+ }
17
+ generate() {
18
+ this.typesGen.clearCache();
19
+ this.typesGen.typeImports.addKnownType('GenericRuntimeApis', 'GenericRuntimeApiMethod');
20
+ let runtimeCallsOut = '';
21
+ if (this.metadata.apis.length > 0) {
22
+ this.metadata.apis.forEach((runtimeApi) => {
23
+ const { name: runtimeApiName, methods } = runtimeApi;
24
+ runtimeCallsOut += (0, utils_1.commentBlock)(`@runtimeapi: ${runtimeApiName} - ${(0, utils_2.calculateRuntimeApiHash)(runtimeApiName)}`);
25
+ runtimeCallsOut += `${(0, util_1.stringCamelCase)(runtimeApiName)}: {
26
+ ${methods.map((method) => this.#generateMethodDef(runtimeApiName, method)).join('\n')}
27
+
28
+ ${(0, utils_1.commentBlock)('Generic runtime api call')}[method: string]: GenericRuntimeApiMethod
29
+ }`;
30
+ });
31
+ }
32
+ else {
33
+ const specsByModule = this.#runtimeApisSpecsByModule();
34
+ Object.values(specsByModule).forEach((specs) => {
35
+ specs.forEach(({ methods, runtimeApiName, runtimeApiHash, version }) => {
36
+ runtimeCallsOut += (0, utils_1.commentBlock)(`@runtimeapi: ${runtimeApiName} - ${runtimeApiHash}`, `@version: ${version}`);
37
+ runtimeCallsOut += `${(0, util_1.stringCamelCase)(runtimeApiName)}: {
38
+ ${Object.keys(methods)
39
+ .map((methodName) => this.#generateMethodDefFromSpec({ ...methods[methodName], runtimeApiName, methodName }))
40
+ .join('\n')}
41
+
42
+ ${(0, utils_1.commentBlock)('Generic runtime api call')}[method: string]: GenericRuntimeApiMethod
43
+ }`;
44
+ });
45
+ });
46
+ }
47
+ const importTypes = this.typesGen.typeImports.toImports();
48
+ const template = (0, utils_1.compileTemplate)('runtime.hbs');
49
+ return (0, utils_1.beautifySourceCode)(template({ importTypes, runtimeCallsOut }));
50
+ }
51
+ #isOptionalType(type) {
52
+ return type.startsWith('Option<') || type.endsWith('| undefined');
53
+ }
54
+ #isOptionalParam(params, type, idx) {
55
+ return this.#isOptionalType(type) && params.slice(idx + 1).every(({ type }) => this.#isOptionalType(type));
56
+ }
57
+ #generateMethodDefFromSpec(spec) {
58
+ const { docs = [], params, type, runtimeApiName, methodName } = spec;
59
+ const callName = `${runtimeApiName}_${(0, utils_2.stringSnakeCase)(methodName)}`;
60
+ const defaultDocs = [`@callname: ${callName}`];
61
+ this.addTypeImport(type, false);
62
+ params.forEach(({ type }) => this.addTypeImport(type));
63
+ const typedParams = params.map((param, idx) => ({
64
+ ...param,
65
+ isOptional: this.#isOptionalParam(params, param.type, idx),
66
+ plainType: this.getGeneratedTypeName(param.type),
67
+ }));
68
+ const paramsOut = typedParams
69
+ .map(({ name, isOptional, plainType }) => `${(0, util_1.stringCamelCase)(name)}${isOptional ? '?' : ''}: ${plainType}`)
70
+ .join(', ');
71
+ const typeOut = this.getGeneratedTypeName(type, false);
72
+ return `${(0, utils_1.commentBlock)(docs, '\n', defaultDocs, typedParams.map(({ plainType, name }) => `@param {${plainType}} ${name}`))}${methodName}: GenericRuntimeApiMethod<(${paramsOut}) => Promise<${typeOut}>>`;
73
+ }
74
+ #generateMethodDef(runtimeApiName, methodDef) {
75
+ const { name: methodName, inputs, output, docs } = methodDef;
76
+ const callName = `${runtimeApiName}_${(0, utils_2.stringSnakeCase)(methodName)}`;
77
+ const defaultDocs = [`@callname: ${callName}`];
78
+ const typeOut = this.typesGen.generateType(output, 1, true);
79
+ this.addTypeImport(typeOut, false);
80
+ const typedInputs = inputs
81
+ .map((input, idx) => ({
82
+ ...input,
83
+ type: this.typesGen.generateType(input.typeId, 1),
84
+ }))
85
+ .map((input, idx, inputs) => ({
86
+ ...input,
87
+ isOptional: this.#isOptionalParam(inputs, input.type, idx),
88
+ }));
89
+ this.addTypeImport(typedInputs.map((t) => t.type));
90
+ const paramsOut = typedInputs
91
+ .map(({ name, type, isOptional }) => `${(0, util_1.stringCamelCase)(name)}${isOptional ? '?' : ''}: ${type}`)
92
+ .join(', ');
93
+ return `${(0, utils_1.commentBlock)(docs, '\n', defaultDocs, typedInputs.map(({ type, name }) => `@param {${type}} ${name}`))}${(0, util_1.stringCamelCase)(methodName)}: GenericRuntimeApiMethod<(${paramsOut}) => Promise<${typeOut}>>`;
94
+ }
95
+ #runtimeApisSpecsByModule() {
96
+ const specs = this.runtimeApis.map(([runtimeApiHash, version]) => {
97
+ const runtimeApiSpec = (0, specs_1.findRuntimeApiSpec)(runtimeApiHash, version);
98
+ if (!runtimeApiSpec)
99
+ return;
100
+ return {
101
+ ...runtimeApiSpec,
102
+ runtimeApiHash,
103
+ };
104
+ });
105
+ return specs.reduce((o, spec) => {
106
+ if (!spec) {
107
+ return o;
108
+ }
109
+ const { moduleName } = spec;
110
+ if (!moduleName) {
111
+ return o;
112
+ }
113
+ return {
114
+ ...o,
115
+ [moduleName]: o[moduleName] ? [...o[moduleName], spec] : [spec],
116
+ };
117
+ }, {});
118
+ }
119
+ }
120
+ exports.RuntimeApisGen = RuntimeApisGen;
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TxGen = void 0;
4
+ const generator_1 = require("../generator");
5
+ const util_1 = require("@polkadot/util");
6
+ const utils_1 = require("./utils");
7
+ class TxGen extends generator_1.ApiGen {
8
+ generate() {
9
+ const { pallets, types } = this.metadata;
10
+ this.typesGen.clearCache();
11
+ this.typesGen.typeImports.addKnownType('GenericChainTx', 'GenericTxCall', 'ISubmittableExtrinsic', 'ISubmittableResult', 'IRuntimeTxCall');
12
+ const { callTypeId, addressTypeId, signatureTypeId } = this.metadata.extrinsic;
13
+ const callTypeIn = this.typesGen.generateType(callTypeId, 1);
14
+ const addressTypeIn = this.typesGen.generateType(addressTypeId, 1);
15
+ const signatureTypeIn = this.typesGen.generateType(signatureTypeId, 1);
16
+ this.typesGen.typeImports.addPortableType('FrameSystemEventRecord');
17
+ this.typesGen.typeImports.addCodecType('Extrinsic');
18
+ this.typesGen.addTypeImport([callTypeIn, addressTypeIn, signatureTypeIn]);
19
+ let txDefsOut = '';
20
+ for (let pallet of pallets) {
21
+ if (pallet.calls === undefined)
22
+ continue;
23
+ const { type } = types[pallet.calls];
24
+ if (type.tag !== 'Enum')
25
+ continue;
26
+ const isFlatEnum = type.value.members.every((m) => m.fields.length === 0);
27
+ const typedTxs = type.value.members
28
+ .map((one) => ({
29
+ functionName: (0, util_1.stringCamelCase)(one.name),
30
+ params: one.fields.map((f) => ({
31
+ name: (0, util_1.stringCamelCase)(f.name),
32
+ normalizedName: this.#normalizeParamName(f.name),
33
+ type: this.typesGen.generateType(f.typeId, 1),
34
+ docs: f.docs,
35
+ })),
36
+ docs: one.docs,
37
+ }))
38
+ .map((f) => {
39
+ return {
40
+ ...f,
41
+ callInput: this.#generateCallInput((0, util_1.stringPascalCase)(pallet.name), (0, util_1.stringPascalCase)(f.functionName), !isFlatEnum ? f.params.map((p) => `${p.name}: ${p.type}`) : undefined),
42
+ };
43
+ });
44
+ txDefsOut += (0, utils_1.commentBlock)(`Pallet \`${pallet.name}\`'s transaction calls`);
45
+ txDefsOut += `${(0, util_1.stringCamelCase)(pallet.name)}: {
46
+ ${typedTxs
47
+ .map(({ functionName, params, docs, callInput }) => `${(0, utils_1.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}>>`)
48
+ .join(',\n')}
49
+
50
+ ${(0, utils_1.commentBlock)('Generic pallet tx call')}[callName: string]: GenericTxCall<TxCall>,
51
+ },`;
52
+ }
53
+ const importTypes = this.typesGen.typeImports.toImports();
54
+ // TODO make explicit separate type for Extra
55
+ const defTypes = `
56
+ export type ChainSubmittableExtrinsic<T extends IRuntimeTxCall = ${callTypeIn}> =
57
+ Extrinsic<${addressTypeIn}, T, ${signatureTypeIn}, any[]> &
58
+ ISubmittableExtrinsic<ISubmittableResult<FrameSystemEventRecord>>
59
+
60
+ export type TxCall = (...args: any[]) => ChainSubmittableExtrinsic;
61
+ `;
62
+ const template = (0, utils_1.compileTemplate)('tx.hbs');
63
+ return (0, utils_1.beautifySourceCode)(template({ importTypes, defTypes, txDefsOut }));
64
+ }
65
+ #normalizeParamName(name) {
66
+ name = (0, util_1.stringCamelCase)(name);
67
+ return (0, utils_1.isReservedWord)(name) ? `${name}_` : name;
68
+ }
69
+ #generateCallInput(palletName, callName, params) {
70
+ if (!params) {
71
+ return `
72
+ {
73
+ pallet: '${palletName}',
74
+ palletCall: '${callName}'
75
+ }
76
+ `;
77
+ }
78
+ const paramsOut = params.length > 0 ? `params: { ${params.join(',')} }` : '';
79
+ return `
80
+ {
81
+ pallet: '${palletName}',
82
+ palletCall: {
83
+ name: '${callName}',
84
+ ${paramsOut}
85
+ }
86
+ }
87
+ `;
88
+ }
89
+ }
90
+ exports.TxGen = TxGen;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TypeImports = void 0;
4
+ class TypeImports {
5
+ // Portable types from chain/metadata
6
+ portableTypes;
7
+ // Known types that has a corresponding codec defined in @dedot/codecs
8
+ codecTypes;
9
+ // Known types that're not codecs or chain/portable types defined in @dedot/types
10
+ knownTypes;
11
+ // External types to define explicitly
12
+ outTypes;
13
+ constructor() {
14
+ this.portableTypes = new Set();
15
+ this.codecTypes = new Set();
16
+ this.knownTypes = new Set();
17
+ this.outTypes = new Set();
18
+ }
19
+ clear() {
20
+ this.portableTypes.clear();
21
+ this.codecTypes.clear();
22
+ this.knownTypes.clear();
23
+ this.outTypes.clear();
24
+ }
25
+ toImports(...excludeModules) {
26
+ // TODO generate outTypes!
27
+ const toImports = [
28
+ [this.knownTypes, '@dedot/types'],
29
+ [this.codecTypes, '@dedot/codecs'],
30
+ [this.portableTypes, './types'],
31
+ ];
32
+ return toImports
33
+ .filter(([_, module]) => !excludeModules.includes(module))
34
+ .map(([types, module]) => this.#toImportLine(types, module))
35
+ .join('\n');
36
+ }
37
+ #toImportLine(types, module) {
38
+ const typesToImports = [...types];
39
+ if (typesToImports.length === 0)
40
+ return '';
41
+ return `import type {${typesToImports.join(', ')}} from "${module}"`;
42
+ }
43
+ addPortableType(...types) {
44
+ types.forEach((one) => this.portableTypes.add(one));
45
+ }
46
+ addCodecType(...types) {
47
+ types.forEach((one) => this.codecTypes.add(one));
48
+ }
49
+ addKnownType(...types) {
50
+ types.forEach((one) => this.knownTypes.add(one));
51
+ }
52
+ addOutType(...types) {
53
+ types.forEach((one) => this.outTypes.add(one));
54
+ }
55
+ }
56
+ exports.TypeImports = TypeImports;