Bump deps w/ eslint (#2302)
* Bump deps w/ eslint * Additional cleanups * Additional * @polkadot/types done * Additional * @polkadot/typegen done * Additional * @polkadot/rpc-core done * Additional * Additional * Additional * docs * @polkadot/api-derive done * @polkadot/api done * @polkadot/api-contracts done * Update tests
This commit is contained in:
@@ -19,7 +19,7 @@ async function run (ws: string): Promise<void> {
|
||||
]);
|
||||
|
||||
// output the chain info, for easy re-use
|
||||
console.error(`// Generated via 'yarn run chain:info ${ws}'\n\nexport default {\n chain: '${chain.toString()}',\n genesisHash: '${api.genesisHash.toHex()}',\n specVersion: ${api.runtimeVersion.specVersion.toNumber()},\n ss58Format: ${props.ss58Format.unwrapOr(42)},\n tokenDecimals: ${props.tokenDecimals.unwrapOr(0)},\n tokenSymbol: '${props.tokenSymbol.unwrapOr('UNIT')}',\n metaCalls: '${Buffer.from(api.runtimeMetadata.asCallsOnly.toU8a()).toString('base64')}'\n};`);
|
||||
console.error(`// Generated via 'yarn run chain:info ${ws}'\n\nexport default {\n chain: '${chain.toString()}',\n genesisHash: '${api.genesisHash.toHex()}',\n specVersion: ${api.runtimeVersion.specVersion.toNumber()},\n ss58Format: ${props.ss58Format.unwrapOr(42).toString()},\n tokenDecimals: ${props.tokenDecimals.unwrapOr(0).toString()},\n tokenSymbol: '${props.tokenSymbol.unwrapOr('UNIT').toString()}',\n metaCalls: '${Buffer.from(api.runtimeMetadata.asCallsOnly.toU8a()).toString('base64')}'\n};`);
|
||||
|
||||
// show any missing types
|
||||
api.runtimeMetadata.getUniqTypes(false);
|
||||
|
||||
@@ -12,13 +12,13 @@ import generateQuery from './generate/query';
|
||||
import generateTx from './generate/tx';
|
||||
import { HEADER, writeFile } from './util';
|
||||
|
||||
let websocket: any = null;
|
||||
let websocket: WebSocket;
|
||||
|
||||
function generate (metaHex: string, pkg: string | undefined, output: string, isStrict?: boolean): void {
|
||||
console.log(`Generating from metadata, ${formatNumber((metaHex.length - 2) / 2)} bytes`);
|
||||
|
||||
const extraTypes = pkg
|
||||
? { [pkg]: require(path.join(process.cwd(), output, 'definitions')) }
|
||||
? { [pkg]: require(path.join(process.cwd(), output, 'definitions')) as Record<string, any> }
|
||||
: {};
|
||||
|
||||
generateConst(path.join(process.cwd(), output, 'augment-api-consts.ts'), metaHex, extraTypes, isStrict);
|
||||
@@ -38,7 +38,7 @@ function generate (metaHex: string, pkg: string | undefined, output: string, isS
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
function onSocketClose (event: any): void {
|
||||
function onSocketClose (event: { code: number; reason: string }): void {
|
||||
console.error(`disconnected, code: '${event.code}' reason: '${event.reason}'`);
|
||||
|
||||
process.exit(1);
|
||||
@@ -89,6 +89,7 @@ export default function main (): void {
|
||||
websocket.onopen = onSocketOpen;
|
||||
|
||||
websocket.onmessage = (message: any): void => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
generate(JSON.parse(message.data).result, pkg, output, isStrict);
|
||||
};
|
||||
})
|
||||
@@ -96,6 +97,7 @@ export default function main (): void {
|
||||
process.exit(1);
|
||||
});
|
||||
} else {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
generate(require(path.join(process.cwd(), endpoint)).result, pkg, output, isStrict);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,10 +24,10 @@ export default function main (): void {
|
||||
}).argv;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const userDefs = require(path.join(process.cwd(), input, 'definitions.ts'));
|
||||
const userDefs = require(path.join(process.cwd(), input, 'definitions.ts')) as Record<string, any>;
|
||||
const userKeys = Object.keys(userDefs);
|
||||
const filteredBase = Object
|
||||
.entries(substrateDefs)
|
||||
.entries(substrateDefs as Record<string, unknown>)
|
||||
.filter(([key]) => {
|
||||
if (userKeys.includes(key)) {
|
||||
console.warn(`Override found for ${key} in user types, ignoring in @polkadot/types`);
|
||||
@@ -37,7 +37,7 @@ export default function main (): void {
|
||||
|
||||
return true;
|
||||
})
|
||||
.reduce((defs: any, [key, value]) => {
|
||||
.reduce((defs: Record<string, any>, [key, value]) => {
|
||||
defs[key] = value;
|
||||
|
||||
return defs;
|
||||
|
||||
@@ -18,7 +18,7 @@ const generateForMetaTemplate = Handlebars.compile(template);
|
||||
/** @internal */
|
||||
function generateForMeta (meta: Metadata, dest: string, extraTypes: Record<string, Record<string, { types: Record<string, any> }>>, isStrict: boolean): void {
|
||||
writeFile(dest, (): string => {
|
||||
const allTypes: Record<string, Record<string, { types: Record<string, any> }>> = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes };
|
||||
const allTypes: Record<string, Record<string, { types: Record<string, unknown> }>> = { '@polkadot/types/interfaces': defaultDefs, ...extraTypes };
|
||||
const imports = createImports(allTypes);
|
||||
const allDefs = Object.entries(allTypes).reduce((defs, [path, obj]) => {
|
||||
return Object.entries(obj).reduce((defs, [key, value]) => ({ ...defs, [`${path}/${key}`]: value }), defs);
|
||||
|
||||
@@ -9,6 +9,7 @@ import * as defaultDefinitions from '@polkadot/types/interfaces/definitions';
|
||||
import * as defaultPrimitives from '@polkadot/types/primitive';
|
||||
|
||||
import { createImports, getDerivedTypes, readTemplate, setImports, writeFile } from '../util';
|
||||
import { ModuleTypes } from '../util/imports';
|
||||
|
||||
const primitiveClasses = {
|
||||
...defaultPrimitives,
|
||||
@@ -19,9 +20,9 @@ const template = readTemplate('interfaceRegistry');
|
||||
const generateInterfaceTypesTemplate = Handlebars.compile(template);
|
||||
|
||||
/** @internal */
|
||||
export function generateInterfaceTypes (importDefinitions: { [importPath: string]: object }, dest: string): void {
|
||||
export function generateInterfaceTypes (importDefinitions: { [importPath: string]: Record<string, ModuleTypes> }, dest: string): void {
|
||||
writeFile(dest, (): string => {
|
||||
Object.entries(importDefinitions).reduce((acc, def) => Object.assign(acc, def), {} as object);
|
||||
Object.entries(importDefinitions).reduce((acc, def) => Object.assign(acc, def), {});
|
||||
|
||||
const imports = createImports(importDefinitions);
|
||||
const definitions = imports.definitions;
|
||||
@@ -46,7 +47,8 @@ export function generateInterfaceTypes (importDefinitions: { [importPath: string
|
||||
|
||||
uniqueTypes.forEach((type) => {
|
||||
existingTypes[type] = true;
|
||||
items.push(...getDerivedTypes(definitions, type, types[type], imports));
|
||||
|
||||
items.push(...getDerivedTypes(definitions, type, types[type] as string, imports));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -15,10 +15,11 @@ import { TypeRegistry } from '@polkadot/types/create';
|
||||
import { stringCamelCase } from '@polkadot/util';
|
||||
|
||||
import { TypeImports, createImports, compareName, formatType, getSimilarTypes, readTemplate, registerDefinitions, setImports, writeFile } from '../util';
|
||||
import { ModuleTypes } from '../util/imports';
|
||||
|
||||
// From a storage entry metadata, we return [args, returnType]
|
||||
/** @internal */
|
||||
function entrySignature (allDefs: object, registry: Registry, storageEntry: StorageEntryMetadataLatest, imports: TypeImports): [string, string] {
|
||||
function entrySignature (allDefs: Record<string, ModuleTypes>, registry: Registry, storageEntry: StorageEntryMetadataLatest, imports: TypeImports): [string, string] {
|
||||
const format = (type: string): string => formatType(allDefs, type, imports);
|
||||
const outputType = unwrapStorageType(storageEntry.type, storageEntry.modifier.isOptional);
|
||||
|
||||
@@ -59,7 +60,7 @@ function entrySignature (allDefs: object, registry: Registry, storageEntry: Stor
|
||||
];
|
||||
}
|
||||
|
||||
throw new Error(`entryArgs: Cannot parse args of entry ${storageEntry.name}`);
|
||||
throw new Error(`entryArgs: Cannot parse args of entry ${storageEntry.name.toString()}`);
|
||||
}
|
||||
|
||||
const template = readTemplate('query');
|
||||
|
||||
@@ -60,7 +60,8 @@ export default function generateRpcTypes (dest = 'packages/api/src/augment/rpc.t
|
||||
|
||||
if (args === undefined) {
|
||||
setImports(allDefs, imports, [def.type]);
|
||||
args = def.params.map((param: any) => {
|
||||
|
||||
args = def.params.map((param) => {
|
||||
const similarTypes = getSimilarTypes(definitions, registry, param.type, imports);
|
||||
|
||||
setImports(allDefs, imports, [param.type, ...similarTypes]);
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
// This software may be modified and distributed under the terms
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import Handlebars from 'handlebars';
|
||||
|
||||
import { TypeDef, TypeDefInfo } from '@polkadot/types/create/types';
|
||||
import { ModuleTypes } from '../util/imports';
|
||||
|
||||
import Handlebars from 'handlebars';
|
||||
import path from 'path';
|
||||
import { getTypeDef } from '@polkadot/types/create';
|
||||
import * as defaultDefinitions from '@polkadot/types/interfaces/definitions';
|
||||
import { isString, stringCamelCase, stringUpperFirst } from '@polkadot/util';
|
||||
import { isString, stringCamelCase, stringUpperFirst, assert } from '@polkadot/util';
|
||||
|
||||
import { TypeImports, createImports, exportInterface, exportType, readTemplate, formatType, setImports, writeFile } from '../util';
|
||||
|
||||
@@ -19,7 +19,7 @@ interface Imports extends TypeImports {
|
||||
|
||||
// helper to generate a `readonly <Name>: <Type>;` getter
|
||||
/** @internal */
|
||||
export function createGetter (definitions: object, name = '', type: string, imports: TypeImports): string {
|
||||
export function createGetter (definitions: Record<string, ModuleTypes>, name = '', type: string, imports: TypeImports): string {
|
||||
setImports(definitions, imports, [type]);
|
||||
|
||||
return ` readonly ${name}: ${type};\n`;
|
||||
@@ -27,12 +27,12 @@ export function createGetter (definitions: object, name = '', type: string, impo
|
||||
|
||||
/** @internal */
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
function errorUnhandled (definitions: object, def: TypeDef, imports: TypeImports): string {
|
||||
throw new Error(`Generate: ${name}: Unhandled type ${TypeDefInfo[def.info]}`);
|
||||
function errorUnhandled (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
|
||||
throw new Error(`Generate: ${def.name || ''}: Unhandled type ${TypeDefInfo[def.info]}`);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function tsExport (definitions: object, def: TypeDef, imports: TypeImports): string {
|
||||
function tsExport (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
|
||||
return exportInterface(def.name, formatType(definitions, def, imports));
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ const tsPlain = tsExport;
|
||||
const tsTuple = tsExport;
|
||||
|
||||
/** @internal */
|
||||
function tsEnum (definitions: object, { name: enumName, sub }: TypeDef, imports: TypeImports): string {
|
||||
function tsEnum (definitions: Record<string, ModuleTypes>, { name: enumName, sub }: TypeDef, imports: TypeImports): string {
|
||||
setImports(definitions, imports, ['Enum']);
|
||||
|
||||
const keys = (sub as TypeDef[]).map(({ info, name = '', type }): string => {
|
||||
@@ -64,21 +64,21 @@ function tsEnum (definitions: object, { name: enumName, sub }: TypeDef, imports:
|
||||
return `${isGetter}${asGetter}`;
|
||||
|
||||
default:
|
||||
throw new Error(`Enum: ${enumName}: Unhandled type ${TypeDefInfo[info]}`);
|
||||
throw new Error(`Enum: ${enumName || 'undefined'}: Unhandled type ${TypeDefInfo[info]}`);
|
||||
}
|
||||
});
|
||||
|
||||
return exportInterface(enumName, 'Enum', keys.join(''));
|
||||
}
|
||||
|
||||
function tsInt (definitions: object, def: TypeDef, imports: TypeImports, type: 'Int' | 'UInt' = 'Int'): string {
|
||||
function tsInt (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports, type: 'Int' | 'UInt' = 'Int'): string {
|
||||
setImports(definitions, imports, [type]);
|
||||
|
||||
return exportInterface(def.name, type);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function tsResultGetter (definitions: object, resultName = '', getter: 'Ok' | 'Error', def: TypeDef, imports: TypeImports): string {
|
||||
function tsResultGetter (definitions: Record<string, ModuleTypes>, resultName = '', getter: 'Ok' | 'Error', def: TypeDef, imports: TypeImports): string {
|
||||
const { info, type } = def;
|
||||
const asGetter = type === 'Null'
|
||||
? ''
|
||||
@@ -97,7 +97,7 @@ function tsResultGetter (definitions: object, resultName = '', getter: 'Ok' | 'E
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function tsResult (definitions: object, def: TypeDef, imports: TypeImports): string {
|
||||
function tsResult (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
|
||||
const [okDef, errorDef] = (def.sub as TypeDef[]);
|
||||
const inner = [
|
||||
tsResultGetter(definitions, def.name, 'Error', errorDef, imports),
|
||||
@@ -110,18 +110,20 @@ function tsResult (definitions: object, def: TypeDef, imports: TypeImports): str
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function tsSet (definitions: object, { name: setName, sub }: TypeDef, imports: TypeImports): string {
|
||||
function tsSet (definitions: Record<string, ModuleTypes>, { name: setName, sub }: TypeDef, imports: TypeImports): string {
|
||||
setImports(definitions, imports, ['Set']);
|
||||
|
||||
const types = (sub as TypeDef[]).map(({ name }): string =>
|
||||
createGetter(definitions, `is${name}`, 'boolean', imports)
|
||||
);
|
||||
const types = (sub as TypeDef[]).map(({ name }): string => {
|
||||
assert(!!name, 'Invalid TypeDef found, no name specified');
|
||||
|
||||
return createGetter(definitions, `is${name}`, 'boolean', imports);
|
||||
});
|
||||
|
||||
return exportInterface(setName, 'Set', types.join(''));
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function tsStruct (definitions: object, { name: structName, sub }: TypeDef, imports: TypeImports): string {
|
||||
function tsStruct (definitions: Record<string, ModuleTypes>, { name: structName, sub }: TypeDef, imports: TypeImports): string {
|
||||
setImports(definitions, imports, ['Struct']);
|
||||
|
||||
const keys = (sub as TypeDef[]).map((typedef): string => {
|
||||
@@ -134,12 +136,12 @@ function tsStruct (definitions: object, { name: structName, sub }: TypeDef, impo
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function tsUInt (definitions: object, def: TypeDef, imports: TypeImports): string {
|
||||
function tsUInt (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
|
||||
return tsInt(definitions, def, imports, 'UInt');
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function tsVec (definitions: object, def: TypeDef, imports: TypeImports): string {
|
||||
function tsVec (definitions: Record<string, ModuleTypes>, def: TypeDef, imports: TypeImports): string {
|
||||
const type = (def.sub as TypeDef).type;
|
||||
|
||||
if (def.info === TypeDefInfo.VecFixed && type === 'u8') {
|
||||
@@ -152,7 +154,7 @@ function tsVec (definitions: object, def: TypeDef, imports: TypeImports): string
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function generateInterfaces (definitions: object, { types }: { types: Record<string, any> }, imports: Imports): [string, string][] {
|
||||
function generateInterfaces (definitions: Record<string, ModuleTypes>, { types }: { types: Record<string, any> }, imports: Imports): [string, string][] {
|
||||
// handlers are defined externally to use - this means that when we do a
|
||||
// `generators[typedef.info](...)` TS will show any unhandled types. Rather
|
||||
// we are being explicit in having no handlers where we do not support (yet)
|
||||
@@ -194,7 +196,7 @@ const templateTypes = readTemplate('tsDef/types');
|
||||
const generateTsDefTypesTemplate = Handlebars.compile(templateTypes);
|
||||
|
||||
/** @internal */
|
||||
function generateTsDefFor (importDefinitions: { [importPath: string]: object }, defName: string, { types }: { types: Record<string, any> }, outputDir: string): void {
|
||||
function generateTsDefFor (importDefinitions: { [importPath: string]: Record<string, ModuleTypes> }, defName: string, { types }: { types: Record<string, any> }, outputDir: string): void {
|
||||
const imports = { ...createImports(importDefinitions, { types }), interfaces: [] } as Imports;
|
||||
const definitions = imports.definitions;
|
||||
const interfaces = generateInterfaces(definitions, { types }, imports);
|
||||
@@ -218,7 +220,7 @@ function generateTsDefFor (importDefinitions: { [importPath: string]: object },
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export function generateTsDef (importDefinitions: { [importPath: string]: object }, outputDir: string, generatingPackage: string): void {
|
||||
export function generateTsDef (importDefinitions: { [importPath: string]: Record<string, ModuleTypes> }, outputDir: string, generatingPackage: string): void {
|
||||
writeFile(path.join(outputDir, 'types.ts'), (): string => {
|
||||
const definitions = importDefinitions[generatingPackage];
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ function generateForMeta (registry: Registry, meta: Metadata, dest: string, extr
|
||||
|
||||
const modules = meta.asLatest.modules
|
||||
.sort(compareName)
|
||||
.filter(({ calls }) => calls.unwrapOr([]).length)
|
||||
.filter(({ calls }) => calls.unwrapOr([]).length !== 0)
|
||||
.map(({ calls, name }) => {
|
||||
setImports(allDefs, imports, ['Call', 'Extrinsic', 'SubmittableExtrinsic']);
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
// of the Apache-2.0 license. See the LICENSE file for details.
|
||||
|
||||
import { MetadataLatest } from '@polkadot/types/interfaces/metadata';
|
||||
import { Codec } from '@polkadot/types/types';
|
||||
|
||||
import fs from 'fs';
|
||||
import Decorated from '@polkadot/metadata/Decorated';
|
||||
@@ -81,8 +82,9 @@ function renderPage (page: Page): string {
|
||||
|
||||
Object.keys(item).filter((i) => i !== 'name').forEach((bullet) => {
|
||||
md += `\n- **${bullet}**: ${
|
||||
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
||||
item[bullet] instanceof Vec
|
||||
? documentationVecToMarkdown(item[bullet] as Vec<Text>, 2)
|
||||
? documentationVecToMarkdown(item[bullet] as Vec<Text>, 2).toString()
|
||||
: item[bullet]
|
||||
}`;
|
||||
});
|
||||
@@ -94,8 +96,9 @@ function renderPage (page: Page): string {
|
||||
return md;
|
||||
}
|
||||
|
||||
function sortByName<T extends { name: any }> (a: T, b: T): number {
|
||||
function sortByName<T extends { name: Codec | string }> (a: T, b: T): number {
|
||||
// case insensitive (all-uppercase) sorting
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return,@typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
|
||||
return a.name.toString().toUpperCase().localeCompare(b.name.toString().toUpperCase());
|
||||
}
|
||||
|
||||
@@ -119,6 +122,7 @@ function addRpc (): string {
|
||||
.map((methodName) => {
|
||||
const method = section.rpc[methodName];
|
||||
const args = method.params.map(({ isOptional, name, type }: any): string => {
|
||||
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
|
||||
return name + (isOptional ? '?' : '') + ': `' + type + '`';
|
||||
}).join(', ');
|
||||
const type = '`' + method.type + '`';
|
||||
@@ -155,7 +159,7 @@ function addConstants (metadata: MetadataLatest): string {
|
||||
|
||||
return {
|
||||
interface: '`' + `api.consts.${sectionName}.${methodName}` + '`',
|
||||
name: `${methodName}: ` + '`' + func.type + '`',
|
||||
name: `${methodName}: ` + '`' + func.type.toString() + '`',
|
||||
...(func.documentation.length && { summary: func.documentation })
|
||||
};
|
||||
}),
|
||||
@@ -196,7 +200,8 @@ function addStorage (metadata: MetadataLatest): string {
|
||||
};
|
||||
});
|
||||
|
||||
const knownSection = JSON.parse(fs.readFileSync('docs/substrate/storage-known-section.json', 'utf8'));
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const knownSection: any = JSON.parse(fs.readFileSync('docs/substrate/storage-known-section.json', 'utf8'));
|
||||
|
||||
return renderPage({
|
||||
description: DESC_STORAGE,
|
||||
@@ -211,7 +216,7 @@ function addExtrinsics (metadata: MetadataLatest): string {
|
||||
description: DESC_EXTRINSICS,
|
||||
sections: metadata.modules
|
||||
.sort(sortByName)
|
||||
.filter((meta) => !meta.calls.isNone && meta.calls.unwrap().length)
|
||||
.filter((meta) => !meta.calls.isNone && meta.calls.unwrap().length !== 0)
|
||||
.map((meta) => {
|
||||
const sectionName = stringCamelCase(meta.name.toString());
|
||||
|
||||
@@ -220,7 +225,7 @@ function addExtrinsics (metadata: MetadataLatest): string {
|
||||
.sort(sortByName)
|
||||
.map((func) => {
|
||||
const methodName = stringCamelCase(func.name.toString());
|
||||
const args = Call.filterOrigin(func).map(({ name, type }): string => `${name}: ` + '`' + type + '`').join(', ');
|
||||
const args = Call.filterOrigin(func).map(({ name, type }) => `${name.toString()}: ` + '`' + type.toString() + '`').join(', ');
|
||||
|
||||
return {
|
||||
interface: '`' + `api.tx.${sectionName}.${methodName}` + '`',
|
||||
@@ -241,13 +246,13 @@ function addEvents (metadata: MetadataLatest): string {
|
||||
description: DESC_EVENTS,
|
||||
sections: metadata.modules
|
||||
.sort(sortByName)
|
||||
.filter((meta) => !meta.events.isNone && meta.events.unwrap().length)
|
||||
.filter((meta) => !meta.events.isNone && meta.events.unwrap().length !== 0)
|
||||
.map((meta) => ({
|
||||
items: meta.events.unwrap()
|
||||
.sort(sortByName)
|
||||
.map((func) => {
|
||||
const methodName = func.name.toString();
|
||||
const args = func.args.map((type): string => '`' + type + '`').join(', ');
|
||||
const args = func.args.map((type): string => '`' + type.toString() + '`').join(', ');
|
||||
|
||||
return {
|
||||
name: `${methodName}(${args})`,
|
||||
|
||||
@@ -24,7 +24,7 @@ import { isChildClass } from '@polkadot/util';
|
||||
|
||||
import { isCompactEncodable } from './class';
|
||||
import { formatType } from './formatting';
|
||||
import { setImports, TypeImports } from './imports';
|
||||
import { setImports, ModuleTypes, TypeImports } from './imports';
|
||||
|
||||
function arrayToStrType (arr: string[]): string {
|
||||
return `${arr.map((c): string => `'${c}'`).join(' | ')}`;
|
||||
@@ -34,9 +34,9 @@ const voteConvictions = arrayToStrType(AllConvictions);
|
||||
|
||||
// From `T`, generate `Compact<T>, Option<T>, Vec<T>`
|
||||
/** @internal */
|
||||
export function getDerivedTypes (definitions: object, type: string, primitiveName: string, imports: TypeImports): string[] {
|
||||
export function getDerivedTypes (definitions: Record<string, ModuleTypes>, type: string, primitiveName: string, imports: TypeImports): string[] {
|
||||
// `primitiveName` represents the actual primitive type our type is mapped to
|
||||
const isCompact = isCompactEncodable((primitiveClasses as any)[primitiveName]);
|
||||
const isCompact = isCompactEncodable((primitiveClasses as Record<string, any>)[primitiveName]);
|
||||
const def = getTypeDef(type);
|
||||
|
||||
setImports(definitions, imports, ['Option', 'Vec', isCompact ? 'Compact' : '']);
|
||||
@@ -73,7 +73,7 @@ export function getDerivedTypes (definitions: object, type: string, primitiveNam
|
||||
// - if param instanceof AbstractInt, then param: u64 | Uint8array | AnyNumber
|
||||
// etc
|
||||
/** @internal */
|
||||
export function getSimilarTypes (definitions: object, registry: Registry, _type: string, imports: TypeImports): string[] {
|
||||
export function getSimilarTypes (definitions: Record<string, ModuleTypes>, registry: Registry, _type: string, imports: TypeImports): string[] {
|
||||
const typeParts = _type.split('::');
|
||||
const type = typeParts[typeParts.length - 1];
|
||||
const possibleTypes = [type];
|
||||
|
||||
@@ -9,9 +9,17 @@ import { TypeDef, TypeDefInfo } from '@polkadot/types/create/types';
|
||||
import { getTypeDef } from '@polkadot/types/create';
|
||||
import { paramsNotation } from '@polkadot/types/codec/utils';
|
||||
|
||||
import { setImports, TypeImports } from './imports';
|
||||
import { setImports, ModuleTypes, TypeImports } from './imports';
|
||||
import { readTemplate } from './file';
|
||||
|
||||
interface This {
|
||||
imports: TypeImports;
|
||||
types: {
|
||||
file: string;
|
||||
types: string[];
|
||||
}[]
|
||||
}
|
||||
|
||||
const TYPES_NON_PRIMITIVE = ['Metadata'];
|
||||
|
||||
export const HEADER = (type: 'chain' | 'defs'): string => `// Auto-generated via \`yarn polkadot-types-from-${type}\`, do not edit\n/* eslint-disable */\n\n`;
|
||||
@@ -23,9 +31,8 @@ Handlebars.registerPartial({
|
||||
|
||||
Handlebars.registerHelper({
|
||||
imports () {
|
||||
const { imports, types } = this as any;
|
||||
|
||||
return [
|
||||
const { imports, types } = this as unknown as This;
|
||||
const defs = [
|
||||
{
|
||||
file: '@polkadot/types/types',
|
||||
types: Object.keys(imports.typesTypes)
|
||||
@@ -34,7 +41,7 @@ Handlebars.registerHelper({
|
||||
file: '@polkadot/types/codec',
|
||||
types: Object
|
||||
.keys(imports.codecTypes)
|
||||
.filter((name): boolean => name !== 'Tuple')
|
||||
.filter((name) => name !== 'Tuple')
|
||||
},
|
||||
{
|
||||
file: '@polkadot/types/extrinsic',
|
||||
@@ -48,25 +55,27 @@ Handlebars.registerHelper({
|
||||
file: '@polkadot/types/primitive',
|
||||
types: Object
|
||||
.keys(imports.primitiveTypes)
|
||||
.filter((name): boolean => !TYPES_NON_PRIMITIVE.includes(name))
|
||||
.filter((name) => !TYPES_NON_PRIMITIVE.includes(name))
|
||||
},
|
||||
{
|
||||
file: '@polkadot/types',
|
||||
types: Object
|
||||
.keys(imports.primitiveTypes)
|
||||
.filter((name): boolean => TYPES_NON_PRIMITIVE.includes(name))
|
||||
.filter((name) => TYPES_NON_PRIMITIVE.includes(name))
|
||||
},
|
||||
...types
|
||||
].reduce((result, { file, types }): string => {
|
||||
];
|
||||
|
||||
return defs.reduce((result, { file, types }): string => {
|
||||
return types.length
|
||||
? `${result}import { ${types.sort().join(', ')} } from '${file}';\n`
|
||||
: result;
|
||||
}, '');
|
||||
},
|
||||
trim (options) {
|
||||
trim (options: { fn: (self: unknown) => string }) {
|
||||
return options.fn(this).trim();
|
||||
},
|
||||
upper (options) {
|
||||
upper (options: { fn: (self: unknown) => string }) {
|
||||
return options.fn(this).toUpperCase();
|
||||
}
|
||||
});
|
||||
@@ -172,7 +181,7 @@ function formatVec (inner: string): string {
|
||||
* Correctly format a given type
|
||||
*/
|
||||
/** @internal */
|
||||
export function formatType (definitions: object, type: string | TypeDef, imports: TypeImports): string {
|
||||
export function formatType (definitions: Record<string, ModuleTypes>, type: string | TypeDef, imports: TypeImports): string {
|
||||
let typeDef: TypeDef;
|
||||
|
||||
if (typeof type === 'string') {
|
||||
|
||||
@@ -10,6 +10,10 @@ import * as extrinsicClasses from '@polkadot/types/extrinsic';
|
||||
import * as genericClasses from '@polkadot/types/generic';
|
||||
import * as primitiveClasses from '@polkadot/types/primitive';
|
||||
|
||||
export interface ModuleTypes {
|
||||
types: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// these map all the codec and primitive types for import, see the TypeImports below. If
|
||||
// we have an unseen type, it is `undefined`/`false`, if we need to import it, it is `true`
|
||||
type TypeExist = Record<string, boolean>;
|
||||
@@ -26,14 +30,14 @@ export interface TypeImports {
|
||||
localTypes: TypeExistMap; // `import {} from '../something'`
|
||||
primitiveTypes: TypeExist; // `import {} from '@polkadot/types/primitive`
|
||||
typesTypes: TypeExist; // `import {} from '@polkadot/types/types`
|
||||
definitions: object; // all definitions
|
||||
definitions: Record<string, ModuleTypes>; // all definitions
|
||||
typeToModule: Record<string, string>;
|
||||
}
|
||||
|
||||
// Maps the types as found to the source location. This is used to generate the
|
||||
// imports in the output file, dep-duped and sorted
|
||||
/** @internal */
|
||||
export function setImports (allDefs: object, imports: TypeImports, types: string[]): void {
|
||||
export function setImports (allDefs: Record<string, ModuleTypes>, imports: TypeImports, types: string[]): void {
|
||||
const { codecTypes, extrinsicTypes, genericTypes, ignoredTypes, localTypes, primitiveTypes, typesTypes } = imports;
|
||||
|
||||
types.forEach((type): void => {
|
||||
@@ -41,13 +45,13 @@ export function setImports (allDefs: object, imports: TypeImports, types: string
|
||||
// do nothing
|
||||
} else if (['AnyNumber', 'CallFunction', 'Codec', 'IExtrinsic', 'ITuple'].includes(type)) {
|
||||
typesTypes[type] = true;
|
||||
} else if ((codecClasses as any)[type]) {
|
||||
} else if ((codecClasses as Record<string, unknown>)[type]) {
|
||||
codecTypes[type] = true;
|
||||
} else if ((extrinsicClasses as any)[type]) {
|
||||
} else if ((extrinsicClasses as Record<string, unknown>)[type]) {
|
||||
extrinsicTypes[type] = true;
|
||||
} else if ((genericClasses as any)[type]) {
|
||||
} else if ((genericClasses as Record<string, unknown>)[type]) {
|
||||
genericTypes[type] = true;
|
||||
} else if ((primitiveClasses as any)[type] || type === 'Metadata') {
|
||||
} else if ((primitiveClasses as Record<string, unknown>)[type] || type === 'Metadata') {
|
||||
primitiveTypes[type] = true;
|
||||
} else if (type.includes('<') || type.includes('(') || (type.includes('[') && !type.includes('|'))) {
|
||||
// If the type is a bit special (tuple, fixed u8, nested type...), then we
|
||||
@@ -84,8 +88,8 @@ export function setImports (allDefs: object, imports: TypeImports, types: string
|
||||
|
||||
// Create an Imports object, can be pre-filled with `ignoredTypes`
|
||||
/** @internal */
|
||||
export function createImports (importDefinitions: Record<string, object>, { types }: { types: Record<string, any> } = { types: {} }): TypeImports {
|
||||
const definitions = {} as Record<string, object>;
|
||||
export function createImports (importDefinitions: Record<string, Record<string, ModuleTypes>>, { types }: ModuleTypes = { types: {} }): TypeImports {
|
||||
const definitions = {} as Record<string, ModuleTypes>;
|
||||
const typeToModule = {} as Record<string, string>;
|
||||
|
||||
Object.entries(importDefinitions).forEach(([packagePath, packageDef]): void => {
|
||||
|
||||
Reference in New Issue
Block a user