webextensions-api-mock
Version:
WebExtensions API as sinon stubs
111 lines (110 loc) • 3.52 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const helper_1 = require("./helper");
const walker_1 = require("../walker");
class Utils {
static typeIdWithSchemaId(schemaId) {
const nameParts = schemaId.name.split('.').map(name => helper_1.capitalize(name));
const lastName = nameParts.pop();
const firstName = nameParts.shift();
const middleName = nameParts.join('');
return {
shortName: `${lastName}`,
fullName: `${firstName}${middleName}["${lastName}"]`,
};
}
}
class NamespacesSchemaWalker {
constructor(outNamespaces, imports) {
this.outNamespaces = outNamespaces;
this.imports = imports;
}
walk(schemaNamespaces) {
new walker_1.SchemaWalker(this).walk(schemaNamespaces);
}
handleImport(schemaId, name) {
if (schemaId.type === walker_1.SchemaType.Namespace) {
this.imports.push({
name: helper_1.capitalize(schemaId.name),
import: helper_1.capitalize(name),
});
}
}
createNamespaceValue(schemaId) {
const nameParts = schemaId.name.split('.');
const interfaceName = nameParts.map(name => helper_1.capitalize(name)).join('');
const out = {
parent: [],
childTypes: [],
};
this.outNamespaces.set(interfaceName, out);
return out;
}
startObjectPropertyValue(schemaId, out) {
return {
parent: [],
childTypes: out.childTypes,
};
}
finishObjectPropertyValue(schemaId, out) {
const fields = out.parent.sort().join('\n');
return `{\n${fields}\n}`;
}
valueForInvalidRef() {
return 'any';
}
valueForCircularType(schemaId) {
return Utils.typeIdWithSchemaId(schemaId).fullName;
}
finishTypeValue(schemaId, value, out) {
const typeId = Utils.typeIdWithSchemaId(schemaId);
out.parent.push(`${typeId.shortName}: ${value};`);
return typeId.fullName;
}
createEnumValue(schemaId, type, choices, out) {
if (type === 'string') {
choices = choices.map(choice => `'${choice}'`);
}
const enumValue = choices.join('|');
if (schemaId.type !== walker_1.SchemaType.Type) {
return enumValue;
}
else {
const enumName = schemaId.name
.split('.')
.map(name => helper_1.capitalize(name))
.join('');
out.childTypes.push(`${enumName} = ${enumValue};`);
return enumName;
}
}
createPlainValue(schemaId, type, isArray) {
let typeName;
switch (type) {
case 'integer':
typeName = 'number';
break;
case 'choices':
typeName = 'any';
break;
default:
typeName = type;
}
return typeName + (isArray ? '[]' : '');
}
createEventValue() {
return 'Events["Event"]';
}
createFnValue(schemaId, returnValue) {
if (returnValue !== undefined) {
return `sinon.SinonStub<any[], ${returnValue}>`;
}
else {
return 'sinon.SinonStub';
}
}
handleField(schemaId, name, value, optional, out) {
out.parent.push(`${name}${optional ? '?' : ''}: ${value};`);
}
}
exports.NamespacesSchemaWalker = NamespacesSchemaWalker;