awesome-cordova-plugins/scripts/build/transformers/plugin-class.ts

80 lines
2.1 KiB
TypeScript
Raw Normal View History

2017-12-28 20:28:44 +08:00
import * as ts from 'typescript';
2018-03-23 17:57:54 +08:00
2017-12-29 12:15:34 +08:00
import { Logger } from '../../logger';
2018-03-23 17:57:54 +08:00
import {
convertValueToLiteral,
getDecorator,
getDecoratorArgs,
getDecoratorName
} from '../helpers';
2017-12-28 20:28:44 +08:00
import { transformMembers } from './members';
function transformClass(cls: any, ngcBuild?: boolean) {
2017-12-29 12:43:29 +08:00
Logger.profile('transformClass: ' + cls.name.text);
2017-12-28 20:28:44 +08:00
2018-03-23 17:57:54 +08:00
const pluginStatics = [];
const dec: any = getDecorator(cls);
2017-12-28 20:28:44 +08:00
2018-03-23 17:57:54 +08:00
if (dec) {
const pluginDecoratorArgs = getDecoratorArgs(dec);
2017-12-28 20:28:44 +08:00
2018-03-23 17:57:54 +08:00
// add plugin decorator args as static properties of the plugin's class
for (const prop in pluginDecoratorArgs) {
pluginStatics.push(
ts.createProperty(
2017-12-28 20:28:44 +08:00
undefined,
[ts.createToken(ts.SyntaxKind.StaticKeyword)],
ts.createIdentifier(prop),
undefined,
undefined,
convertValueToLiteral(pluginDecoratorArgs[prop])
2018-03-23 17:57:54 +08:00
)
);
2017-12-28 20:28:44 +08:00
}
2018-03-23 17:57:54 +08:00
}
2017-12-28 20:28:44 +08:00
2018-03-23 17:57:54 +08:00
cls = ts.createClassDeclaration(
ngcBuild && cls.decorators && cls.decorators.length
? cls.decorators.filter(d => getDecoratorName(d) === 'Injectable')
: undefined, // remove Plugin and Injectable decorators
[ts.createToken(ts.SyntaxKind.ExportKeyword)],
cls.name,
cls.typeParameters,
cls.heritageClauses,
[...transformMembers(cls), ...pluginStatics]
);
Logger.profile('transformClass: ' + cls.name.text, { level: 'verbose' });
return cls;
2017-12-28 20:28:44 +08:00
}
2018-03-23 17:57:54 +08:00
function transformClasses(
file: ts.SourceFile,
ctx: ts.TransformationContext,
ngcBuild?: boolean
) {
2017-12-29 12:43:29 +08:00
Logger.silly('Transforming file: ' + file.fileName);
2018-03-23 17:57:54 +08:00
return ts.visitEachChild(
file,
node => {
if (node.kind !== ts.SyntaxKind.ClassDeclaration) {
return node;
}
return transformClass(node, ngcBuild);
},
ctx
);
2017-12-28 20:28:44 +08:00
}
2018-03-23 17:57:54 +08:00
export function pluginClassTransformer(
ngcBuild?: boolean
): ts.TransformerFactory<ts.SourceFile> {
2017-12-28 20:28:44 +08:00
return (ctx: ts.TransformationContext) => {
return tsSourceFile => {
2017-12-28 20:40:57 +08:00
if (tsSourceFile.fileName.indexOf('src/@ionic-native/plugins') > -1)
2017-12-28 20:28:44 +08:00
return transformClasses(tsSourceFile, ctx, ngcBuild);
return tsSourceFile;
2017-12-29 12:43:29 +08:00
};
2017-12-28 20:28:44 +08:00
};
}