@pezkuwi/typegen 16.5.5 → 16.5.6

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 (193) hide show
  1. package/LICENSE +201 -0
  2. package/augment.js +2 -0
  3. package/bundle.js +2 -0
  4. package/cjs/augment.d.ts +2 -0
  5. package/cjs/augment.js +4 -0
  6. package/cjs/bundle.d.ts +2 -0
  7. package/cjs/bundle.js +7 -0
  8. package/cjs/extractChain.js +44 -0
  9. package/cjs/fromChain.js +95 -0
  10. package/cjs/fromDefs.js +82 -0
  11. package/cjs/generate/consts.js +91 -0
  12. package/cjs/generate/errors.js +59 -0
  13. package/cjs/generate/events.js +139 -0
  14. package/cjs/generate/index.js +23 -0
  15. package/cjs/generate/interfaceRegistry.js +64 -0
  16. package/cjs/generate/lookup.js +240 -0
  17. package/cjs/generate/query.js +140 -0
  18. package/cjs/generate/rpc.js +115 -0
  19. package/cjs/generate/runtime.js +233 -0
  20. package/{build → cjs}/generate/tsDef.d.ts +1 -1
  21. package/cjs/generate/tsDef.js +254 -0
  22. package/cjs/generate/tx.js +121 -0
  23. package/cjs/generate/types.js +16 -0
  24. package/cjs/index.js +5 -0
  25. package/cjs/interfacesTs.js +28 -0
  26. package/cjs/metadataMd.js +652 -0
  27. package/cjs/package.json +3 -0
  28. package/cjs/packageDetect.js +8 -0
  29. package/cjs/packageInfo.js +4 -0
  30. package/cjs/util/assert.js +15 -0
  31. package/cjs/util/derived.js +128 -0
  32. package/cjs/util/docs.js +10 -0
  33. package/cjs/util/file.js +33 -0
  34. package/{build → cjs}/util/formatting.d.ts +1 -1
  35. package/cjs/util/formatting.js +237 -0
  36. package/cjs/util/imports.js +126 -0
  37. package/{build → cjs}/util/index.d.ts +1 -0
  38. package/cjs/util/index.js +39 -0
  39. package/cjs/util/initMeta.js +22 -0
  40. package/cjs/util/register.js +10 -0
  41. package/cjs/util/wsMeta.js +60 -0
  42. package/extractChain.d.ts +1 -0
  43. package/extractChain.js +40 -0
  44. package/fromChain.d.ts +1 -0
  45. package/fromChain.js +91 -0
  46. package/fromDefs.d.ts +1 -0
  47. package/fromDefs.js +78 -0
  48. package/generate/consts.d.ts +5 -0
  49. package/generate/consts.js +87 -0
  50. package/generate/errors.d.ts +4 -0
  51. package/generate/errors.js +55 -0
  52. package/generate/events.d.ts +5 -0
  53. package/generate/events.js +135 -0
  54. package/{src/generate/index.ts → generate/index.d.ts} +0 -3
  55. package/generate/index.js +10 -0
  56. package/generate/interfaceRegistry.d.ts +4 -0
  57. package/generate/interfaceRegistry.js +59 -0
  58. package/generate/lookup.d.ts +4 -0
  59. package/generate/lookup.js +235 -0
  60. package/generate/query.d.ts +5 -0
  61. package/generate/query.js +136 -0
  62. package/generate/rpc.d.ts +6 -0
  63. package/generate/rpc.js +110 -0
  64. package/generate/runtime.d.ts +7 -0
  65. package/generate/runtime.js +228 -0
  66. package/generate/tsDef.d.ts +16 -0
  67. package/generate/tsDef.js +246 -0
  68. package/generate/tx.d.ts +5 -0
  69. package/generate/tx.js +117 -0
  70. package/generate/types.d.ts +12 -0
  71. package/generate/types.js +13 -0
  72. package/index.d.ts +2 -0
  73. package/index.js +2 -0
  74. package/interfacesTs.d.ts +1 -0
  75. package/interfacesTs.js +24 -0
  76. package/metadataMd.d.ts +1 -0
  77. package/metadataMd.js +648 -0
  78. package/package.json +520 -24
  79. package/packageDetect.d.ts +1 -0
  80. package/{src/packageDetect.ts → packageDetect.js} +0 -8
  81. package/packageInfo.d.ts +6 -0
  82. package/packageInfo.js +1 -0
  83. package/scripts/{polkadot-types-chain-info.mjs → pezkuwi-types-chain-info.mjs} +1 -1
  84. package/scripts/{polkadot-types-from-chain.mjs → pezkuwi-types-from-chain.mjs} +1 -1
  85. package/scripts/{polkadot-types-from-defs.mjs → pezkuwi-types-from-defs.mjs} +1 -1
  86. package/{build/scripts/polkadot-types-internal-interfaces.mjs → scripts/pezkuwi-types-internal-interfaces.mjs} +1 -1
  87. package/{build/scripts/polkadot-types-internal-metadata.mjs → scripts/pezkuwi-types-internal-metadata.mjs} +1 -1
  88. package/{src/templates → templates}/calls.hbs +2 -2
  89. package/{src/templates → templates}/consts.hbs +2 -2
  90. package/{src/templates → templates}/errors.hbs +2 -2
  91. package/{src/templates → templates}/events.hbs +2 -2
  92. package/{src/templates → templates}/interfaceRegistry.hbs +2 -2
  93. package/{src/templates → templates}/lookup/types.hbs +2 -2
  94. package/{src/templates → templates}/query.hbs +2 -2
  95. package/{src/templates → templates}/rpc.hbs +2 -2
  96. package/{src/templates → templates}/tx.hbs +2 -2
  97. package/util/assert.d.ts +2 -0
  98. package/util/assert.js +10 -0
  99. package/util/derived.d.ts +4 -0
  100. package/util/derived.js +125 -0
  101. package/util/docs.d.ts +1 -0
  102. package/util/docs.js +6 -0
  103. package/util/file.d.ts +2 -0
  104. package/util/file.js +28 -0
  105. package/util/formatting.d.ts +11 -0
  106. package/util/formatting.js +230 -0
  107. package/util/imports.d.ts +23 -0
  108. package/util/imports.js +121 -0
  109. package/{src/util/index.ts → util/index.d.ts} +6 -8
  110. package/util/index.js +34 -0
  111. package/util/initMeta.d.ts +12 -0
  112. package/util/initMeta.js +19 -0
  113. package/util/register.d.ts +4 -0
  114. package/util/register.js +7 -0
  115. package/util/wsMeta.d.ts +4 -0
  116. package/util/wsMeta.js +55 -0
  117. package/build/scripts/polkadot-types-chain-info.mjs +0 -7
  118. package/build/scripts/polkadot-types-from-chain.mjs +0 -7
  119. package/build/scripts/polkadot-types-from-defs.mjs +0 -7
  120. package/scripts/polkadot-types-internal-interfaces.mjs +0 -7
  121. package/scripts/polkadot-types-internal-metadata.mjs +0 -7
  122. package/src/augment.ts +0 -5
  123. package/src/bundle.ts +0 -5
  124. package/src/extractChain.ts +0 -54
  125. package/src/fromChain.ts +0 -123
  126. package/src/fromDefs.ts +0 -106
  127. package/src/generate/consts.ts +0 -112
  128. package/src/generate/errors.ts +0 -75
  129. package/src/generate/events.ts +0 -165
  130. package/src/generate/interfaceRegistry.ts +0 -85
  131. package/src/generate/lookup.ts +0 -294
  132. package/src/generate/query.ts +0 -169
  133. package/src/generate/rpc.ts +0 -158
  134. package/src/generate/runtime.ts +0 -284
  135. package/src/generate/tsDef.ts +0 -321
  136. package/src/generate/tx.ts +0 -152
  137. package/src/generate/types.ts +0 -26
  138. package/src/index.ts +0 -6
  139. package/src/interfacesTs.ts +0 -35
  140. package/src/metadataMd.ts +0 -844
  141. package/src/packageInfo.ts +0 -6
  142. package/src/util/assert.ts +0 -18
  143. package/src/util/derived.spec.ts +0 -58
  144. package/src/util/derived.ts +0 -133
  145. package/src/util/docs.ts +0 -13
  146. package/src/util/file.ts +0 -42
  147. package/src/util/formatting.spec.ts +0 -30
  148. package/src/util/formatting.ts +0 -295
  149. package/src/util/imports.ts +0 -164
  150. package/src/util/initMeta.ts +0 -37
  151. package/src/util/register.ts +0 -12
  152. package/src/util/wsMeta.ts +0 -70
  153. package/tsconfig.build.json +0 -28
  154. package/tsconfig.build.tsbuildinfo +0 -1
  155. package/tsconfig.scripts.json +0 -19
  156. package/tsconfig.spec.json +0 -17
  157. /package/{build/augment.d.ts → augment.d.ts} +0 -0
  158. /package/{build/bundle.d.ts → bundle.d.ts} +0 -0
  159. /package/{build → cjs}/extractChain.d.ts +0 -0
  160. /package/{build → cjs}/fromChain.d.ts +0 -0
  161. /package/{build → cjs}/fromDefs.d.ts +0 -0
  162. /package/{build → cjs}/generate/consts.d.ts +0 -0
  163. /package/{build → cjs}/generate/errors.d.ts +0 -0
  164. /package/{build → cjs}/generate/events.d.ts +0 -0
  165. /package/{build → cjs}/generate/index.d.ts +0 -0
  166. /package/{build → cjs}/generate/interfaceRegistry.d.ts +0 -0
  167. /package/{build → cjs}/generate/lookup.d.ts +0 -0
  168. /package/{build → cjs}/generate/query.d.ts +0 -0
  169. /package/{build → cjs}/generate/rpc.d.ts +0 -0
  170. /package/{build → cjs}/generate/runtime.d.ts +0 -0
  171. /package/{build → cjs}/generate/tx.d.ts +0 -0
  172. /package/{build → cjs}/generate/types.d.ts +0 -0
  173. /package/{build → cjs}/index.d.ts +0 -0
  174. /package/{build → cjs}/interfacesTs.d.ts +0 -0
  175. /package/{build → cjs}/metadataMd.d.ts +0 -0
  176. /package/{build → cjs}/packageDetect.d.ts +0 -0
  177. /package/{build → cjs}/packageInfo.d.ts +0 -0
  178. /package/{build → cjs}/util/assert.d.ts +0 -0
  179. /package/{build → cjs}/util/derived.d.ts +0 -0
  180. /package/{build → cjs}/util/docs.d.ts +0 -0
  181. /package/{build → cjs}/util/file.d.ts +0 -0
  182. /package/{build → cjs}/util/imports.d.ts +0 -0
  183. /package/{build → cjs}/util/initMeta.d.ts +0 -0
  184. /package/{build → cjs}/util/register.d.ts +0 -0
  185. /package/{build → cjs}/util/wsMeta.d.ts +0 -0
  186. /package/{src/templates → templates}/docs.hbs +0 -0
  187. /package/{src/templates → templates}/header.hbs +0 -0
  188. /package/{src/templates → templates}/lookup/defs-named.hbs +0 -0
  189. /package/{src/templates → templates}/lookup/defs.hbs +0 -0
  190. /package/{src/templates → templates}/lookup/index.hbs +0 -0
  191. /package/{src/templates → templates}/tsDef/index.hbs +0 -0
  192. /package/{src/templates → templates}/tsDef/moduleTypes.hbs +0 -0
  193. /package/{src/templates → templates}/tsDef/types.hbs +0 -0
@@ -0,0 +1,228 @@
1
+ import Handlebars from 'handlebars';
2
+ import * as defaultDefs from '@pezkuwi/types/interfaces/definitions';
3
+ import lookupDefinitions from '@pezkuwi/types-augment/lookup/definitions';
4
+ import { objectSpread, stringCamelCase } from '@pezkuwi/util';
5
+ import { blake2AsHex } from '@pezkuwi/util-crypto';
6
+ import { createImports, formatType, getSimilarTypes, initMeta, readTemplate, rebrandTypeName, setImports, writeFile } from '../util/index.js';
7
+ import { getDeprecationNotice } from './types.js';
8
+ const generateCallsTypesTemplate = Handlebars.compile(readTemplate('calls'));
9
+ const aliases = {
10
+ AssetHubZagrosRuntimeRuntimeCall: 'RuntimeCall',
11
+ AssetHubPezkuwiRuntimeRuntimeCall: 'RuntimeCall',
12
+ AssetHubDicleRuntimeOriginCaller: 'OriginCaller',
13
+ AssetHubDicleRuntimeRuntimeCall: 'RuntimeCall',
14
+ DicleRuntimeConstantsProxyProxyType: 'ProxyType',
15
+ KitchensinkRuntimeRuntimeCall: 'RuntimeCall',
16
+ KitchensinkRuntimeRuntimeParametersKey: 'RuntimeParametersKey',
17
+ OpaqueValue: 'Bytes',
18
+ PezkuwiTeyrchainPrimitivesPrimitivesId: 'ParaId',
19
+ PezkuwiTeyrchainPrimitivesPrimitivesValidationCodeHash: 'ValidationCodeHash',
20
+ PezkuwiPrimitivesV7SlashingOpaqueKeyOwnershipProof: 'OpaqueKeyOwnershipProof',
21
+ PezkuwiPrimitivesV8SlashingOpaqueKeyOwnershipProof: 'OpaqueKeyOwnershipProof',
22
+ PezkuwiRuntimeRuntimeCall: 'RuntimeCall',
23
+ PrimitiveTypesH160: 'H160',
24
+ PrimitiveTypesH256: 'H256',
25
+ PrimitiveTypesU256: 'U256',
26
+ PezspConsensusBabeOpaqueKeyOwnershipProof: 'OpaqueKeyOwnershipProof',
27
+ PezspConsensusSlotsSlot: 'Slot',
28
+ PezspConsensusSlotsSlotDuration: 'SlotDuration',
29
+ PezspCoreCryptoAccountId32: 'AccountId32',
30
+ PezspCoreOpaqueMetadata: 'OpaqueMetadata',
31
+ PezspRuntimeOpaqueValue: 'Bytes',
32
+ PezspRuntimeUncheckedExtrinsic: 'Extrinsic',
33
+ StagingDicleRuntimeOriginCaller: 'OriginCaller',
34
+ StagingDicleRuntimeRuntimeCall: 'RuntimeCall',
35
+ StagingDicleRuntimeRuntimeParameters: 'RuntimeParameters',
36
+ StagingDicleRuntimeRuntimeParametersKey: 'RuntimeParametersKey',
37
+ StagingZagrosRuntimeRuntimeCall: 'RuntimeCall'
38
+ };
39
+ const getTypesViaAlias = (registry, id) => {
40
+ const rawTypeName = registry.lookup.getName(id) || registry.lookup.getTypeDef(id).type;
41
+ const typeName = rebrandTypeName(rawTypeName);
42
+ if (aliases[typeName]) {
43
+ return aliases[typeName];
44
+ }
45
+ return typeName;
46
+ };
47
+ /** @internal */
48
+ function getMethods(registry, methods) {
49
+ const result = {};
50
+ methods.forEach((m) => {
51
+ const { deprecationInfo, docs, inputs, name, output } = m;
52
+ let description = docs.map((d) => d.toString()).join();
53
+ if (!deprecationInfo.isNotDeprecated) {
54
+ const deprecationNotice = getDeprecationNotice(deprecationInfo, stringCamelCase(name));
55
+ const notice = description.length ? `\n * ${deprecationNotice}` : ` * ${deprecationNotice}`;
56
+ description += notice;
57
+ }
58
+ result[name.toString()] = {
59
+ description,
60
+ params: inputs.map(({ name, type }) => {
61
+ return { name: name.toString(), type: getTypesViaAlias(registry, type) };
62
+ }),
63
+ type: getTypesViaAlias(registry, output)
64
+ };
65
+ });
66
+ return result;
67
+ }
68
+ /** @internal */
69
+ function getRuntimeDefViaMetadata(registry) {
70
+ const result = {};
71
+ const { apis } = registry.metadata;
72
+ for (let i = 0, count = apis.length; i < count; i++) {
73
+ const { methods, name } = apis[i];
74
+ result[name.toString()] = [{
75
+ methods: getMethods(registry, methods),
76
+ // We set the version to 0 here since it will not be relevant when we are grabbing the runtime apis
77
+ // from the Metadata.
78
+ version: 0
79
+ }];
80
+ }
81
+ return Object.entries(result);
82
+ }
83
+ /** @internal */
84
+ function getDefs(apis, defs, registry) {
85
+ const named = {};
86
+ const all = Object.values(defs);
87
+ const isApiInMetadata = registry.metadata.apis.length > 0;
88
+ if (isApiInMetadata) {
89
+ const sections = getRuntimeDefViaMetadata(registry);
90
+ for (let j = 0, jcount = sections.length; j < jcount; j++) {
91
+ const [_section, secs] = sections[j];
92
+ const sec = secs[0];
93
+ const sectionHash = blake2AsHex(_section, 64);
94
+ const section = stringCamelCase(_section);
95
+ const methods = Object.entries(sec.methods);
96
+ if (!named[section]) {
97
+ named[section] = {};
98
+ }
99
+ for (let m = 0, mcount = methods.length; m < mcount; m++) {
100
+ const [_method, def] = methods[m];
101
+ const method = stringCamelCase(_method);
102
+ named[section][method] = objectSpread({ method, name: `${_section}_${_method}`, section, sectionHash }, def);
103
+ }
104
+ }
105
+ }
106
+ else {
107
+ for (let j = 0, jcount = all.length; j < jcount; j++) {
108
+ const set = all[j].runtime;
109
+ if (set) {
110
+ const sections = Object.entries(set);
111
+ for (let i = 0, scount = sections.length; i < scount; i++) {
112
+ const [_section, sec] = sections[i];
113
+ const sectionHash = blake2AsHex(_section, 64);
114
+ const api = apis?.find(([h]) => h === sectionHash);
115
+ if (api) {
116
+ const ver = sec.find(({ version }) => version === api[1]);
117
+ if (ver) {
118
+ const methods = Object.entries(ver.methods);
119
+ const mcount = methods.length;
120
+ if (mcount) {
121
+ const section = stringCamelCase(_section);
122
+ if (!named[section]) {
123
+ named[section] = {};
124
+ }
125
+ for (let m = 0; m < mcount; m++) {
126
+ const [_method, def] = methods[m];
127
+ const method = stringCamelCase(_method);
128
+ named[section][method] = objectSpread({ method, name: `${_section}_${method}`, section, sectionHash, version: ver.version }, def);
129
+ }
130
+ }
131
+ }
132
+ else {
133
+ console.warn(`Unable to find matching version for runtime ${_section}, expected ${api[1]}`);
134
+ }
135
+ }
136
+ }
137
+ }
138
+ }
139
+ }
140
+ return named;
141
+ }
142
+ /** @internal */
143
+ export function generateCallTypes(registry, meta, dest, extraTypes, isStrict, customLookupDefinitions) {
144
+ writeFile(dest, () => {
145
+ const allTypes = {
146
+ '@pezkuwi/types-augment': {
147
+ lookup: {
148
+ ...lookupDefinitions,
149
+ ...customLookupDefinitions
150
+ }
151
+ },
152
+ '@pezkuwi/types/interfaces': defaultDefs,
153
+ ...extraTypes
154
+ };
155
+ const imports = createImports(allTypes);
156
+ // find the system.Version in metadata
157
+ let apis = null;
158
+ const sysp = meta.asLatest.pallets.find(({ name }) => name.eq('System'));
159
+ if (sysp) {
160
+ const verc = sysp.constants.find(({ name }) => name.eq('Version'));
161
+ if (verc) {
162
+ apis = registry.createType('RuntimeVersion', verc.value).apis.map(([k, v]) => [k.toHex(), v.toNumber()]);
163
+ }
164
+ else {
165
+ console.error('Unable to find System.Version pallet, skipping API extraction');
166
+ }
167
+ }
168
+ else {
169
+ console.error('Unable to find System pallet, skipping API extraction');
170
+ }
171
+ const allDefs = Object.entries(allTypes).reduce((defs, [path, obj]) => {
172
+ return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [`${path}/${key}`]: value }), defs);
173
+ }, {});
174
+ const definitions = getDefs(apis, imports.definitions, registry);
175
+ const callKeys = Object.keys(definitions);
176
+ const modules = callKeys.map((section) => {
177
+ const calls = definitions[section];
178
+ const allMethods = Object.keys(calls).sort().map((methodName) => {
179
+ const def = calls[methodName];
180
+ setImports(allDefs, imports, [def.type]);
181
+ const args = def.params.map((param) => {
182
+ const similarTypes = getSimilarTypes(registry, imports.definitions, param.type, imports);
183
+ setImports(allDefs, imports, [param.type, ...similarTypes]);
184
+ return `${param.name}: ${similarTypes.join(' | ')}`;
185
+ });
186
+ return {
187
+ args: args.join(', '),
188
+ docs: [def.description],
189
+ name: methodName,
190
+ sectionHash: def.sectionHash,
191
+ sectionName: def.section,
192
+ sectionVersion: def.version,
193
+ type: formatType(registry, allDefs, def.type, imports)
194
+ };
195
+ }).sort((a, b) => a.name.localeCompare(b.name));
196
+ return {
197
+ items: allMethods,
198
+ name: section || 'unknown',
199
+ sectionHash: allMethods.length && allMethods[0].sectionHash,
200
+ sectionName: allMethods.length && allMethods[0].sectionName,
201
+ sectionVersion: allMethods.length && allMethods[0].sectionVersion
202
+ };
203
+ }).filter(({ items }) => items.length).sort((a, b) => a.name.localeCompare(b.name));
204
+ if (modules.length) {
205
+ imports.typesTypes['Observable'] = true;
206
+ }
207
+ return generateCallsTypesTemplate({
208
+ headerType: 'chain',
209
+ imports,
210
+ isStrict,
211
+ modules,
212
+ types: [
213
+ ...Object.keys(imports.localTypes).sort().map((packagePath) => ({
214
+ file: packagePath.replace('@pezkuwi/types-augment', '@pezkuwi/types'),
215
+ types: Object.keys(imports.localTypes[packagePath])
216
+ })),
217
+ {
218
+ file: '@pezkuwi/api-base/types',
219
+ types: ['ApiTypes', 'AugmentedCall', 'DecoratedCallBase']
220
+ }
221
+ ]
222
+ });
223
+ });
224
+ }
225
+ export function generateDefaultRuntime(dest, data, extraTypes = {}, isStrict = false, customLookupDefinitions) {
226
+ const { metadata, registry } = initMeta(data, extraTypes);
227
+ generateCallTypes(registry, metadata, dest, extraTypes, isStrict, customLookupDefinitions);
228
+ }
@@ -0,0 +1,16 @@
1
+ import type { Registry } from '@pezkuwi/types/types';
2
+ import type { TypeDef } from '@pezkuwi/types-create/types';
3
+ import type { ModuleTypes } from '../util/imports.js';
4
+ import type { TypeImports } from '../util/index.js';
5
+ import { TypeDefInfo } from '@pezkuwi/types-create';
6
+ /** @internal */
7
+ export declare function createGetter(definitions: Record<string, ModuleTypes>, name: string | undefined, type: string, imports: TypeImports): string;
8
+ export declare const typeEncoders: Record<TypeDefInfo, (registry: Registry, definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports) => string>;
9
+ /** @internal */
10
+ export declare function generateTsDefFor(registry: Registry, importDefinitions: Record<string, Record<string, ModuleTypes>>, defName: string, { types }: {
11
+ types: Record<string, any>;
12
+ }, outputDir: string): void;
13
+ /** @internal */
14
+ export declare function generateTsDef(importDefinitions: Record<string, Record<string, ModuleTypes>>, outputDir: string, generatingPackage: string): void;
15
+ /** @internal */
16
+ export declare function generateDefaultTsDef(): void;
@@ -0,0 +1,246 @@
1
+ import Handlebars from 'handlebars';
2
+ import path from 'node:path';
3
+ import { TypeRegistry } from '@pezkuwi/types/create';
4
+ import * as defaultDefinitions from '@pezkuwi/types/interfaces/definitions';
5
+ import { getTypeDef, TypeDefInfo } from '@pezkuwi/types-create';
6
+ import { assert, isString, stringify, stringPascalCase } from '@pezkuwi/util';
7
+ import { createImports, exportInterface, formatType, readTemplate, setImports, writeFile } from '../util/index.js';
8
+ const generateTsDefIndexTemplate = Handlebars.compile(readTemplate('tsDef/index'));
9
+ const generateTsDefModuleTypesTemplate = Handlebars.compile(readTemplate('tsDef/moduleTypes'));
10
+ const generateTsDefTypesTemplate = Handlebars.compile(readTemplate('tsDef/types'));
11
+ /** @internal */
12
+ export function createGetter(definitions, name = '', type, imports) {
13
+ setImports(definitions, imports, [type]);
14
+ return ` readonly ${name}: ${type};\n`;
15
+ }
16
+ /** @internal */
17
+ function errorUnhandled(_, _definitions, def, _imports) {
18
+ throw new Error(`Generate: ${def.name || ''}: Unhandled type ${TypeDefInfo[def.info]}`);
19
+ }
20
+ /** @internal */
21
+ function tsExport(registry, definitions, def, imports) {
22
+ return exportInterface(def.lookupIndex, def.name, formatType(registry, definitions, def, imports, false));
23
+ }
24
+ /** @internal */
25
+ function tsEnum(registry, definitions, { lookupIndex, name: enumName, sub }, imports, withShortcut = false) {
26
+ setImports(definitions, imports, ['Enum']);
27
+ const indent = withShortcut ? ' ' : '';
28
+ const named = sub.filter(({ name }) => !!name && !name.startsWith('__Unused'));
29
+ const keys = named.map((def) => {
30
+ const { info, lookupName, name = '', sub, type } = def;
31
+ const getter = stringPascalCase(name.replace(' ', '_'));
32
+ const isComplex = [TypeDefInfo.Option, TypeDefInfo.Range, TypeDefInfo.RangeInclusive, TypeDefInfo.Result, TypeDefInfo.Struct, TypeDefInfo.Tuple, TypeDefInfo.Vec, TypeDefInfo.VecFixed].includes(info);
33
+ let extractedLookupName;
34
+ // When the parent type does not have a lookupName, and the sub type is the same
35
+ // type as the parent we can take the lookupName from the sub.
36
+ // This is specific to `StagingXcmV4Junction`.
37
+ // see: https://github.com/pezkuwichain/pezkuwi-api/pull/5812
38
+ if (sub && !Array.isArray(sub) && type.includes(`${sub.type};`)) {
39
+ if (sub.lookupName === 'StagingXcmV4Junction') {
40
+ extractedLookupName = sub.lookupName;
41
+ }
42
+ else if (sub.lookupName === 'StagingXcmV5Junction') {
43
+ extractedLookupName = `Vec<${sub.lookupName}>`;
44
+ }
45
+ }
46
+ const asGetter = type === 'Null' || info === TypeDefInfo.DoNotConstruct
47
+ ? ''
48
+ : createGetter(definitions, `as${getter}`, lookupName || extractedLookupName || (isComplex ? formatType(registry, definitions, info === TypeDefInfo.Struct ? def : type, imports, withShortcut) : type), imports);
49
+ const isGetter = info === TypeDefInfo.DoNotConstruct
50
+ ? ''
51
+ : createGetter(definitions, `is${getter}`, 'boolean', imports);
52
+ switch (info) {
53
+ case TypeDefInfo.Compact:
54
+ case TypeDefInfo.Plain:
55
+ case TypeDefInfo.Range:
56
+ case TypeDefInfo.RangeInclusive:
57
+ case TypeDefInfo.Result:
58
+ case TypeDefInfo.Si:
59
+ case TypeDefInfo.Struct:
60
+ case TypeDefInfo.Tuple:
61
+ case TypeDefInfo.Vec:
62
+ case TypeDefInfo.BTreeMap:
63
+ case TypeDefInfo.BTreeSet:
64
+ case TypeDefInfo.Option:
65
+ case TypeDefInfo.VecFixed:
66
+ case TypeDefInfo.WrapperKeepOpaque:
67
+ case TypeDefInfo.WrapperOpaque:
68
+ return `${indent}${isGetter}${indent}${asGetter}`;
69
+ case TypeDefInfo.DoNotConstruct:
70
+ case TypeDefInfo.Null:
71
+ return `${indent}${isGetter}`;
72
+ default:
73
+ throw new Error(`Enum: ${enumName || 'undefined'}: Unhandled type ${TypeDefInfo[info]}, ${stringify(def)}`);
74
+ }
75
+ });
76
+ return exportInterface(lookupIndex, enumName, 'Enum', `${keys.join('')} ${indent}readonly type: ${named.map(({ name = '' }) => `'${stringPascalCase(name.replace(' ', '_'))}'`).join(' | ')};\n`, withShortcut);
77
+ }
78
+ function tsInt(_, definitions, def, imports, type = 'Int') {
79
+ setImports(definitions, imports, [type]);
80
+ return exportInterface(def.lookupIndex, def.name, type);
81
+ }
82
+ /** @internal */
83
+ function tsNull(_registry, definitions, { lookupIndex = -1, name }, imports) {
84
+ setImports(definitions, imports, ['Null']);
85
+ // * @description extends [[${base}]]
86
+ const doc = `/** @name ${name || ''}${lookupIndex !== -1 ? ` (${lookupIndex})` : ''} */\n`;
87
+ return `${doc}export type ${name || ''} = Null;`;
88
+ }
89
+ /** @internal */
90
+ function tsResultGetter(registry, definitions, resultName = '', getter, def, imports) {
91
+ const { info, lookupName, type } = def;
92
+ const asGetter = type === 'Null'
93
+ ? ''
94
+ : createGetter(definitions, `as${getter}`, lookupName || (info === TypeDefInfo.Tuple ? formatType(registry, definitions, def, imports, false) : type), imports);
95
+ const isGetter = createGetter(definitions, `is${getter}`, 'boolean', imports);
96
+ switch (info) {
97
+ case TypeDefInfo.Option:
98
+ case TypeDefInfo.Plain:
99
+ case TypeDefInfo.Si:
100
+ case TypeDefInfo.Tuple:
101
+ case TypeDefInfo.Vec:
102
+ case TypeDefInfo.BTreeMap:
103
+ case TypeDefInfo.BTreeSet:
104
+ case TypeDefInfo.WrapperKeepOpaque:
105
+ case TypeDefInfo.WrapperOpaque:
106
+ return `${isGetter}${asGetter}`;
107
+ case TypeDefInfo.Null:
108
+ return `${isGetter}`;
109
+ default:
110
+ throw new Error(`Result: ${resultName}: Unhandled type ${TypeDefInfo[info]}, ${stringify(def)}`);
111
+ }
112
+ }
113
+ /** @internal */
114
+ function tsResult(registry, definitions, def, imports) {
115
+ const [okDef, errorDef] = def.sub;
116
+ const inner = [
117
+ tsResultGetter(registry, definitions, def.name, 'Err', errorDef, imports),
118
+ tsResultGetter(registry, definitions, def.name, 'Ok', okDef, imports)
119
+ ].join('');
120
+ setImports(definitions, imports, [def.type]);
121
+ const fmtType = def.lookupName && def.name !== def.lookupName
122
+ ? def.lookupName
123
+ : formatType(registry, definitions, def, imports, false);
124
+ return exportInterface(def.lookupIndex, def.name, fmtType, inner);
125
+ }
126
+ /** @internal */
127
+ function tsSi(_registry, _definitions, typeDef, _imports) {
128
+ // FIXME
129
+ return `// SI: ${stringify(typeDef)}`;
130
+ }
131
+ /** @internal */
132
+ function tsSet(_, definitions, { lookupIndex, name: setName, sub }, imports) {
133
+ setImports(definitions, imports, ['Set']);
134
+ const types = sub.map(({ name }) => {
135
+ assert(name, 'Invalid TypeDef found, no name specified');
136
+ return createGetter(definitions, `is${name}`, 'boolean', imports);
137
+ });
138
+ return exportInterface(lookupIndex, setName, 'Set', types.join(''));
139
+ }
140
+ /** @internal */
141
+ function tsStruct(registry, definitions, { lookupIndex, name: structName, sub }, imports) {
142
+ setImports(definitions, imports, ['Struct']);
143
+ const keys = sub.map((def) => {
144
+ const fmtType = def.lookupName && def.name !== def.lookupName
145
+ ? def.lookupName
146
+ : def.info === TypeDefInfo.Enum
147
+ ? `${tsEnum(registry, definitions, def, imports, true)} & Enum`
148
+ : formatType(registry, definitions, def, imports, false);
149
+ return createGetter(definitions, def.name, fmtType, imports);
150
+ });
151
+ return exportInterface(lookupIndex, structName, 'Struct', keys.join(''));
152
+ }
153
+ /** @internal */
154
+ function tsUInt(registry, definitions, def, imports) {
155
+ return tsInt(registry, definitions, def, imports, 'UInt');
156
+ }
157
+ /** @internal */
158
+ function tsVec(registry, definitions, def, imports) {
159
+ const type = def.sub.type;
160
+ if (type === 'u8') {
161
+ if (def.info === TypeDefInfo.VecFixed) {
162
+ setImports(definitions, imports, ['U8aFixed']);
163
+ return exportInterface(def.lookupIndex, def.name, 'U8aFixed');
164
+ }
165
+ else {
166
+ setImports(definitions, imports, ['Bytes']);
167
+ return exportInterface(def.lookupIndex, def.name, 'Bytes');
168
+ }
169
+ }
170
+ const fmtType = def.lookupName && def.name !== def.lookupName
171
+ ? def.lookupName
172
+ : formatType(registry, definitions, def, imports, false);
173
+ return exportInterface(def.lookupIndex, def.name, fmtType);
174
+ }
175
+ export const typeEncoders = {
176
+ [TypeDefInfo.BTreeMap]: tsExport,
177
+ [TypeDefInfo.BTreeSet]: tsExport,
178
+ [TypeDefInfo.Compact]: tsExport,
179
+ [TypeDefInfo.DoNotConstruct]: tsExport,
180
+ [TypeDefInfo.Enum]: tsEnum,
181
+ [TypeDefInfo.HashMap]: tsExport,
182
+ [TypeDefInfo.Int]: tsInt,
183
+ [TypeDefInfo.Linkage]: errorUnhandled,
184
+ [TypeDefInfo.Null]: tsNull,
185
+ [TypeDefInfo.Option]: tsExport,
186
+ [TypeDefInfo.Plain]: tsExport,
187
+ [TypeDefInfo.Range]: tsExport,
188
+ [TypeDefInfo.RangeInclusive]: tsExport,
189
+ [TypeDefInfo.Result]: tsResult,
190
+ [TypeDefInfo.Set]: tsSet,
191
+ [TypeDefInfo.Si]: tsSi,
192
+ [TypeDefInfo.Struct]: tsStruct,
193
+ [TypeDefInfo.Tuple]: tsExport,
194
+ [TypeDefInfo.UInt]: tsUInt,
195
+ [TypeDefInfo.Vec]: tsVec,
196
+ [TypeDefInfo.VecFixed]: tsVec,
197
+ [TypeDefInfo.WrapperKeepOpaque]: tsExport,
198
+ [TypeDefInfo.WrapperOpaque]: tsExport
199
+ };
200
+ /** @internal */
201
+ function generateInterfaces(registry, definitions, { types }, imports) {
202
+ return Object.entries(types).map(([name, type]) => {
203
+ const def = getTypeDef(isString(type) ? type : stringify(type), { name });
204
+ return [name, typeEncoders[def.info](registry, definitions, def, imports)];
205
+ });
206
+ }
207
+ /** @internal */
208
+ export function generateTsDefFor(registry, importDefinitions, defName, { types }, outputDir) {
209
+ const imports = { ...createImports(importDefinitions, { types }), interfaces: [] };
210
+ const definitions = imports.definitions;
211
+ const interfaces = generateInterfaces(registry, definitions, { types }, imports);
212
+ const items = interfaces.sort((a, b) => a[0].localeCompare(b[0])).map(([, definition]) => definition);
213
+ writeFile(path.join(outputDir, defName, 'types.ts'), () => generateTsDefModuleTypesTemplate({
214
+ headerType: 'defs',
215
+ imports,
216
+ items,
217
+ name: defName,
218
+ types: [
219
+ ...Object.keys(imports.localTypes).sort().map((packagePath) => ({
220
+ file: packagePath.replace('@pezkuwi/types/augment', '@pezkuwi/types'),
221
+ types: Object.keys(imports.localTypes[packagePath])
222
+ }))
223
+ ]
224
+ }), true);
225
+ writeFile(path.join(outputDir, defName, 'index.ts'), () => generateTsDefIndexTemplate({ headerType: 'defs' }), true);
226
+ }
227
+ /** @internal */
228
+ export function generateTsDef(importDefinitions, outputDir, generatingPackage) {
229
+ const registry = new TypeRegistry();
230
+ writeFile(path.join(outputDir, 'types.ts'), () => {
231
+ const definitions = importDefinitions[generatingPackage];
232
+ Object.entries(definitions).forEach(([defName, obj]) => {
233
+ console.log(`\tExtracting interfaces for ${defName}`);
234
+ generateTsDefFor(registry, importDefinitions, defName, obj, outputDir);
235
+ });
236
+ return generateTsDefTypesTemplate({
237
+ headerType: 'defs',
238
+ items: Object.keys(definitions)
239
+ });
240
+ });
241
+ writeFile(path.join(outputDir, 'index.ts'), () => generateTsDefIndexTemplate({ headerType: 'defs' }), true);
242
+ }
243
+ /** @internal */
244
+ export function generateDefaultTsDef() {
245
+ generateTsDef({ '@pezkuwi/types/interfaces': defaultDefinitions }, 'packages/types/src/interfaces', '@pezkuwi/types/interfaces');
246
+ }
@@ -0,0 +1,5 @@
1
+ import type { Definitions } from '@pezkuwi/types/types';
2
+ import type { HexString } from '@pezkuwi/util/types';
3
+ import { type ExtraTypes } from './types.js';
4
+ /** @internal */
5
+ export declare function generateDefaultTx(dest: string, data: HexString, extraTypes?: ExtraTypes, isStrict?: boolean, customLookupDefinitions?: Definitions): void;
package/generate/tx.js ADDED
@@ -0,0 +1,117 @@
1
+ import Handlebars from 'handlebars';
2
+ import * as defaultDefs from '@pezkuwi/types/interfaces/definitions';
3
+ import lookupDefinitions from '@pezkuwi/types-augment/lookup/definitions';
4
+ import { stringCamelCase } from '@pezkuwi/util';
5
+ import { compareName, createImports, formatType, getSimilarTypes, initMeta, readTemplate, rebrandTypeName, setImports, writeFile } from '../util/index.js';
6
+ import { ignoreUnusedLookups } from './lookup.js';
7
+ import { getDeprecationNotice } from './types.js';
8
+ const MAPPED_NAMES = {
9
+ class: 'clazz',
10
+ new: 'updated'
11
+ };
12
+ const generateForMetaTemplate = Handlebars.compile(readTemplate('tx'));
13
+ function mapName(_name) {
14
+ const name = stringCamelCase(_name);
15
+ return MAPPED_NAMES[name] || name;
16
+ }
17
+ /** @internal */
18
+ function generateForMeta(registry, meta, dest, extraTypes, isStrict, customLookupDefinitions) {
19
+ writeFile(dest, () => {
20
+ const allTypes = {
21
+ '@pezkuwi/types-augment': {
22
+ lookup: {
23
+ ...lookupDefinitions,
24
+ ...customLookupDefinitions
25
+ }
26
+ },
27
+ '@pezkuwi/types/interfaces': defaultDefs,
28
+ ...extraTypes
29
+ };
30
+ const imports = createImports(allTypes);
31
+ const allDefs = Object.entries(allTypes).reduce((defs, [path, obj]) => {
32
+ return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [`${path}/${key}`]: value }), defs);
33
+ }, {});
34
+ const { lookup, pallets } = meta.asLatest;
35
+ const usedTypes = new Set([]);
36
+ const modules = pallets
37
+ .sort(compareName)
38
+ .filter(({ calls }) => calls.isSome)
39
+ .map((data) => {
40
+ const name = data.name;
41
+ const calls = data.calls.unwrap();
42
+ const deprecationInfo = calls.deprecationInfo.toJSON();
43
+ setImports(allDefs, imports, ['SubmittableExtrinsic']);
44
+ const sectionName = stringCamelCase(name);
45
+ const items = lookup.getSiType(calls.type).def.asVariant.variants
46
+ .map(({ docs, fields, index, name }) => {
47
+ const rawStatus = deprecationInfo?.[index.toNumber()];
48
+ if (rawStatus) {
49
+ const deprecationVariantInfo = meta.registry.createTypeUnsafe('VariantDeprecationInfoV16', [rawStatus]);
50
+ const deprecationNotice = getDeprecationNotice(deprecationVariantInfo, name.toString(), 'Call');
51
+ const notice = docs.length ? ['', deprecationNotice] : [deprecationNotice];
52
+ docs.push(...notice.map((text) => meta.registry.createType('Text', text)));
53
+ }
54
+ const typesInfo = fields.map(({ name, type, typeName }, index) => {
55
+ const typeDef = registry.lookup.getTypeDef(type);
56
+ return [
57
+ name.isSome
58
+ ? mapName(name.unwrap())
59
+ : `param${index}`,
60
+ rebrandTypeName(typeName.isSome
61
+ ? typeName.toString()
62
+ : typeDef.type),
63
+ rebrandTypeName(typeDef.isFromSi
64
+ ? typeDef.type
65
+ : typeDef.lookupName || typeDef.type)
66
+ ];
67
+ });
68
+ const params = typesInfo
69
+ .map(([name, , typeStr]) => {
70
+ const similarTypes = getSimilarTypes(registry, allDefs, typeStr, imports);
71
+ setImports(allDefs, imports, [typeStr, ...similarTypes]);
72
+ // Add the type to the list of used types
73
+ if (!(imports.primitiveTypes[typeStr])) {
74
+ usedTypes.add(typeStr);
75
+ }
76
+ return `${name}: ${similarTypes.join(' | ')}`;
77
+ })
78
+ .join(', ');
79
+ return {
80
+ args: typesInfo.map(([, , typeStr]) => formatType(registry, allDefs, typeStr, imports)).join(', '),
81
+ docs,
82
+ name: stringCamelCase(name),
83
+ params
84
+ };
85
+ })
86
+ .sort(compareName);
87
+ return {
88
+ items,
89
+ name: sectionName
90
+ };
91
+ })
92
+ .sort(compareName);
93
+ // filter out the unused lookup types from imports
94
+ ignoreUnusedLookups([...usedTypes], imports);
95
+ return generateForMetaTemplate({
96
+ headerType: 'chain',
97
+ imports,
98
+ isStrict,
99
+ modules,
100
+ types: [
101
+ ...Object.keys(imports.localTypes).sort().map((packagePath) => ({
102
+ file: packagePath.replace('@pezkuwi/types-augment', '@pezkuwi/types'),
103
+ types: Object.keys(imports.localTypes[packagePath])
104
+ })),
105
+ {
106
+ file: '@pezkuwi/api-base/types',
107
+ types: ['ApiTypes', 'AugmentedSubmittable', 'SubmittableExtrinsic', 'SubmittableExtrinsicFunction']
108
+ }
109
+ ]
110
+ });
111
+ });
112
+ }
113
+ /** @internal */
114
+ export function generateDefaultTx(dest, data, extraTypes = {}, isStrict = false, customLookupDefinitions) {
115
+ const { metadata, registry } = initMeta(data, extraTypes);
116
+ return generateForMeta(registry, metadata, dest, extraTypes, isStrict, customLookupDefinitions);
117
+ }
@@ -0,0 +1,12 @@
1
+ import type { Option, Text } from '@pezkuwi/types-codec';
2
+ export type ExtraTypes = Record<string, Record<string, {
3
+ runtime?: Record<string, any>;
4
+ types: Record<string, any>;
5
+ }>>;
6
+ export declare function getDeprecationNotice<T extends {
7
+ isDeprecated: boolean;
8
+ asDeprecated: {
9
+ note: Text;
10
+ since: Option<Text>;
11
+ };
12
+ }>(deprecationInfo: T, name: string, label?: string): string;
@@ -0,0 +1,13 @@
1
+ export function getDeprecationNotice(deprecationInfo, name, label) {
2
+ let deprecationNotice = '@deprecated';
3
+ if (deprecationInfo.isDeprecated) {
4
+ const { note, since } = deprecationInfo.asDeprecated;
5
+ const sinceText = since.isSome ? ` Since ${since.unwrap().toString()}.` : '';
6
+ deprecationNotice += ` ${note.toString()}${sinceText}`;
7
+ }
8
+ else {
9
+ const labelText = label ? `${label} ` : '';
10
+ deprecationNotice += ` ${labelText}${name} has been deprecated`;
11
+ }
12
+ return deprecationNotice;
13
+ }
package/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import './packageDetect.js';
2
+ export * from './bundle.js';
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import './packageDetect.js';
2
+ export * from './bundle.js';
@@ -0,0 +1 @@
1
+ export declare function main(): void;