Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

graphql-codegen-visitor-plugin-common

Package Overview
Dependencies
Maintainers
1
Versions
123
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

graphql-codegen-visitor-plugin-common - npm Package Compare versions

Comparing version 0.19.0-alpha.3f859ab8 to 0.19.0-alpha.52db8d29

cjs/index.js

132

dist/base-documents-visitor.js

@@ -1,19 +0,6 @@

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var autoBind = require("auto-bind");
var scalars_1 = require("./scalars");
var utils_1 = require("./utils");
var variables_to_object_1 = require("./variables-to-object");
var naming_1 = require("./naming");
import autoBind from 'auto-bind';
import { DEFAULT_SCALARS } from './scalars';
import { toPascalCase, DeclarationBlock } from './utils';
import { OperationVariablesToObject } from './variables-to-object';
import { convertFactory } from './naming';
function getRootType(operation, schema) {

@@ -29,55 +16,38 @@ switch (operation) {

}
var BaseDocumentsVisitor = /** @class */ (function () {
function BaseDocumentsVisitor(rawConfig, additionalConfig, _schema, defaultScalars) {
if (defaultScalars === void 0) { defaultScalars = scalars_1.DEFAULT_SCALARS; }
export class BaseDocumentsVisitor {
constructor(rawConfig, additionalConfig, _schema, defaultScalars = DEFAULT_SCALARS) {
this._schema = _schema;
this._declarationBlockConfig = {};
this._unnamedCounter = 1;
this._parsedConfig = __assign({ addTypename: !rawConfig.skipTypename, scalars: __assign({}, (defaultScalars || scalars_1.DEFAULT_SCALARS), (rawConfig.scalars || {})), convert: naming_1.convertFactory(rawConfig), typesPrefix: rawConfig.typesPrefix || '' }, (additionalConfig || {}));
this._parsedConfig = Object.assign({ addTypename: !rawConfig.skipTypename, scalars: Object.assign({}, (defaultScalars || DEFAULT_SCALARS), (rawConfig.scalars || {})), convert: convertFactory(rawConfig), typesPrefix: rawConfig.typesPrefix || '' }, (additionalConfig || {}));
autoBind(this);
this._variablesTransfomer = new variables_to_object_1.OperationVariablesToObject(this.scalars, this.convertName);
this._variablesTransfomer = new OperationVariablesToObject(this.scalars, this.convertName);
}
BaseDocumentsVisitor.prototype.setSelectionSetHandler = function (handler) {
setSelectionSetHandler(handler) {
this._selectionSetToObject = handler;
};
BaseDocumentsVisitor.prototype.setDeclarationBlockConfig = function (config) {
}
setDeclarationBlockConfig(config) {
this._declarationBlockConfig = config;
};
BaseDocumentsVisitor.prototype.setVariablesTransformer = function (variablesTransfomer) {
}
setVariablesTransformer(variablesTransfomer) {
this._variablesTransfomer = variablesTransfomer;
};
BaseDocumentsVisitor.prototype.convertName = function (node, options) {
var useTypesPrefix = options && typeof options.useTypesPrefix === 'boolean' ? options.useTypesPrefix : true;
}
convertName(node, options) {
const useTypesPrefix = options && typeof options.useTypesPrefix === 'boolean' ? options.useTypesPrefix : true;
return (useTypesPrefix ? this._parsedConfig.typesPrefix : '') + this._parsedConfig.convert(node, options);
};
Object.defineProperty(BaseDocumentsVisitor.prototype, "config", {
get: function () {
return this._parsedConfig;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseDocumentsVisitor.prototype, "schema", {
get: function () {
return this._schema;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseDocumentsVisitor.prototype, "scalars", {
get: function () {
return this.config.scalars;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseDocumentsVisitor.prototype, "addTypename", {
get: function () {
return this._parsedConfig.addTypename;
},
enumerable: true,
configurable: true
});
BaseDocumentsVisitor.prototype.handleAnonymouseOperation = function (node) {
var name = node.name && node.name.value;
}
get config() {
return this._parsedConfig;
}
get schema() {
return this._schema;
}
get scalars() {
return this.config.scalars;
}
get addTypename() {
return this._parsedConfig.addTypename;
}
handleAnonymouseOperation(node) {
const name = node.name && node.name.value;
if (name) {

@@ -93,7 +63,7 @@ return this.convertName(node, {

});
};
BaseDocumentsVisitor.prototype.FragmentDefinition = function (node) {
var fragmentRootType = this._schema.getType(node.typeCondition.name.value);
var selectionSet = this._selectionSetToObject.createNext(fragmentRootType, node.selectionSet);
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
}
FragmentDefinition(node) {
const fragmentRootType = this._schema.getType(node.typeCondition.name.value);
const selectionSet = this._selectionSetToObject.createNext(fragmentRootType, node.selectionSet);
return new DeclarationBlock(this._declarationBlockConfig)
.export()

@@ -106,27 +76,25 @@ .asKind('type')

.withContent(selectionSet.string).string;
};
BaseDocumentsVisitor.prototype.OperationDefinition = function (node) {
var name = this.handleAnonymouseOperation(node);
var operationRootType = getRootType(node.operation, this._schema);
var selectionSet = this._selectionSetToObject.createNext(operationRootType, node.selectionSet);
var visitedOperationVariables = this._variablesTransfomer.transform(node.variableDefinitions);
var operationResult = new utils_1.DeclarationBlock(this._declarationBlockConfig)
}
OperationDefinition(node) {
const name = this.handleAnonymouseOperation(node);
const operationRootType = getRootType(node.operation, this._schema);
const selectionSet = this._selectionSetToObject.createNext(operationRootType, node.selectionSet);
const visitedOperationVariables = this._variablesTransfomer.transform(node.variableDefinitions);
const operationResult = new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(this.convertName(name, {
suffix: utils_1.toPascalCase(node.operation)
suffix: toPascalCase(node.operation)
}))
.withContent(selectionSet.string).string;
var operationVariables = new utils_1.DeclarationBlock(this._declarationBlockConfig)
const operationVariables = new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(this.convertName(name, {
suffix: utils_1.toPascalCase(node.operation) + 'Variables'
suffix: toPascalCase(node.operation) + 'Variables'
}))
.withBlock(visitedOperationVariables).string;
return [operationVariables, operationResult].filter(function (r) { return r; }).join('\n\n');
};
return BaseDocumentsVisitor;
}());
exports.BaseDocumentsVisitor = BaseDocumentsVisitor;
return [operationVariables, operationResult].filter(r => r).join('\n\n');
}
}
//# sourceMappingURL=base-documents-visitor.js.map

@@ -1,23 +0,9 @@

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var autoBind = require("auto-bind");
var scalars_1 = require("./scalars");
var utils_1 = require("./utils");
var graphql_1 = require("graphql");
var variables_to_object_1 = require("./variables-to-object");
var naming_1 = require("./naming");
var BaseResolversVisitor = /** @class */ (function () {
function BaseResolversVisitor(rawConfig, additionalConfig, _schema, defaultScalars) {
if (defaultScalars === void 0) { defaultScalars = scalars_1.DEFAULT_SCALARS; }
import autoBind from 'auto-bind';
import { DEFAULT_SCALARS } from './scalars';
import { DeclarationBlock, indent, getBaseTypeNode } from './utils';
import { GraphQLObjectType } from 'graphql';
import { OperationVariablesToObject } from './variables-to-object';
import { convertFactory } from './naming';
export class BaseResolversVisitor {
constructor(rawConfig, additionalConfig, _schema, defaultScalars = DEFAULT_SCALARS) {
this._schema = _schema;

@@ -27,16 +13,16 @@ this._declarationBlockConfig = {};

this._collectedDirectiveResolvers = {};
this._parsedConfig = __assign({ scalars: __assign({}, (defaultScalars || scalars_1.DEFAULT_SCALARS), (rawConfig.scalars || {})), convert: naming_1.convertFactory(rawConfig), typesPrefix: rawConfig.typesPrefix || '', contextType: rawConfig.contextType || 'any', mappers: this.transformMappers(rawConfig.mappers || {}) }, (additionalConfig || {}));
this._parsedConfig = Object.assign({ scalars: Object.assign({}, (defaultScalars || DEFAULT_SCALARS), (rawConfig.scalars || {})), convert: convertFactory(rawConfig), typesPrefix: rawConfig.typesPrefix || '', contextType: rawConfig.contextType || 'any', mappers: this.transformMappers(rawConfig.mappers || {}) }, (additionalConfig || {}));
autoBind(this);
this._variablesTransfomer = new variables_to_object_1.OperationVariablesToObject(this.scalars, this.convertName);
this._variablesTransfomer = new OperationVariablesToObject(this.scalars, this.convertName);
}
BaseResolversVisitor.prototype.isExternalMapper = function (value) {
isExternalMapper(value) {
return value.includes('#');
};
BaseResolversVisitor.prototype.parseMapper = function (mapper) {
}
parseMapper(mapper) {
if (this.isExternalMapper(mapper)) {
var _a = mapper.split('#'), source = _a[0], type = _a[1];
const [source, type] = mapper.split('#');
return {
isExternal: true,
source: source,
type: type
source,
type
};

@@ -48,136 +34,115 @@ }

};
};
BaseResolversVisitor.prototype.transformMappers = function (rawMappers) {
var _this = this;
var result = {};
Object.keys(rawMappers).forEach(function (gqlTypeName) {
var mapperDef = rawMappers[gqlTypeName];
var parsedMapper = _this.parseMapper(mapperDef);
}
transformMappers(rawMappers) {
const result = {};
Object.keys(rawMappers).forEach(gqlTypeName => {
const mapperDef = rawMappers[gqlTypeName];
const parsedMapper = this.parseMapper(mapperDef);
result[gqlTypeName] = parsedMapper;
});
return result;
};
Object.defineProperty(BaseResolversVisitor.prototype, "config", {
get: function () {
return this._parsedConfig;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseResolversVisitor.prototype, "schema", {
get: function () {
return this._schema;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseResolversVisitor.prototype, "scalars", {
get: function () {
return this.config.scalars;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseResolversVisitor.prototype, "mappersImports", {
get: function () {
var _this = this;
var groupedMappers = {};
Object.keys(this.config.mappers)
.filter(function (gqlTypeName) { return _this.config.mappers[gqlTypeName].isExternal; })
.forEach(function (gqlTypeName) {
var mapper = _this.config.mappers[gqlTypeName];
if (!groupedMappers[mapper.source]) {
groupedMappers[mapper.source] = [];
}
groupedMappers[mapper.source].push(mapper.type);
});
return Object.keys(groupedMappers).map(function (source) { return _this.buildMapperImport(source, groupedMappers[source]); });
},
enumerable: true,
configurable: true
});
BaseResolversVisitor.prototype.buildMapperImport = function (source, types) {
return "import { " + types.join(', ') + " } from '" + source + "';";
};
BaseResolversVisitor.prototype.convertName = function (name, options) {
var useTypesPrefix = options && typeof options.useTypesPrefix === 'boolean' ? options.useTypesPrefix : true;
}
get config() {
return this._parsedConfig;
}
get schema() {
return this._schema;
}
get scalars() {
return this.config.scalars;
}
get mappersImports() {
const groupedMappers = {};
Object.keys(this.config.mappers)
.filter(gqlTypeName => this.config.mappers[gqlTypeName].isExternal)
.forEach(gqlTypeName => {
const mapper = this.config.mappers[gqlTypeName];
if (!groupedMappers[mapper.source]) {
groupedMappers[mapper.source] = [];
}
groupedMappers[mapper.source].push(mapper.type);
});
return Object.keys(groupedMappers).map(source => this.buildMapperImport(source, groupedMappers[source]));
}
buildMapperImport(source, types) {
return `import { ${types.join(', ')} } from '${source}';`;
}
convertName(name, options) {
const useTypesPrefix = options && typeof options.useTypesPrefix === 'boolean' ? options.useTypesPrefix : true;
return (useTypesPrefix ? this.config.typesPrefix : '') + this.config.convert(name, options);
};
BaseResolversVisitor.prototype.setDeclarationBlockConfig = function (config) {
}
setDeclarationBlockConfig(config) {
this._declarationBlockConfig = config;
};
BaseResolversVisitor.prototype.setVariablesTransformer = function (variablesTransfomer) {
}
setVariablesTransformer(variablesTransfomer) {
this._variablesTransfomer = variablesTransfomer;
};
BaseResolversVisitor.prototype.getRootResolver = function () {
var _this = this;
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
}
getRootResolver() {
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(this.convertName('IResolvers'), "<Context = " + this.config.contextType + ">")
.withName(this.convertName('IResolvers'), `<Context = ${this.config.contextType}>`)
.withBlock(Object.keys(this._collectedResolvers)
.map(function (schemaTypeName) {
var resolverType = _this._collectedResolvers[schemaTypeName];
return utils_1.indent(_this.formatRootResolver(schemaTypeName, resolverType));
.map(schemaTypeName => {
const resolverType = this._collectedResolvers[schemaTypeName];
return indent(this.formatRootResolver(schemaTypeName, resolverType));
})
.join('\n')).string;
};
BaseResolversVisitor.prototype.formatRootResolver = function (schemaTypeName, resolverType) {
return schemaTypeName + "?: " + resolverType + ",";
};
BaseResolversVisitor.prototype.getAllDirectiveResolvers = function () {
var _this = this;
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
}
formatRootResolver(schemaTypeName, resolverType) {
return `${schemaTypeName}?: ${resolverType},`;
}
getAllDirectiveResolvers() {
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(this.convertName('IDirectiveResolvers'), "<Context = " + this.config.contextType + ">")
.withName(this.convertName('IDirectiveResolvers'), `<Context = ${this.config.contextType}>`)
.withBlock(Object.keys(this._collectedDirectiveResolvers)
.map(function (schemaTypeName) {
var resolverType = _this._collectedDirectiveResolvers[schemaTypeName];
return utils_1.indent(_this.formatRootResolver(schemaTypeName, resolverType));
.map(schemaTypeName => {
const resolverType = this._collectedDirectiveResolvers[schemaTypeName];
return indent(this.formatRootResolver(schemaTypeName, resolverType));
})
.join('\n')).string;
};
BaseResolversVisitor.prototype.Name = function (node) {
}
Name(node) {
return node.value;
};
BaseResolversVisitor.prototype.ListType = function (node) {
var asString = node.type;
return "Array<" + asString + ">";
};
BaseResolversVisitor.prototype.NamedType = function (node) {
var type = this.config.scalars[node.name] || this.convertName(node);
return "" + type;
};
BaseResolversVisitor.prototype.NonNullType = function (node) {
var asString = node.type;
}
ListType(node) {
const asString = node.type;
return `Array<${asString}>`;
}
NamedType(node) {
const type = this.config.scalars[node.name] || this.convertName(node);
return `${type}`;
}
NonNullType(node) {
const asString = node.type;
return asString;
};
BaseResolversVisitor.prototype.FieldDefinition = function (node, key, parent) {
var _this = this;
var hasArguments = node.arguments && node.arguments.length > 0;
return function (parentName) {
var original = parent[key];
var realType = utils_1.getBaseTypeNode(original.type).name.value;
var mappedType = _this.config.mappers[realType]
? _this._variablesTransfomer.wrapAstTypeWithModifiers(_this.config.mappers[realType].type, original.type)
}
FieldDefinition(node, key, parent) {
const hasArguments = node.arguments && node.arguments.length > 0;
return (parentName) => {
const original = parent[key];
const realType = getBaseTypeNode(original.type).name.value;
const mappedType = this.config.mappers[realType]
? this._variablesTransfomer.wrapAstTypeWithModifiers(this.config.mappers[realType].type, original.type)
: node.type;
var subscriptionType = _this._schema.getSubscriptionType();
var isSubscriptionType = subscriptionType && subscriptionType.name === parentName;
return utils_1.indent(node.name + "?: " + (isSubscriptionType ? 'SubscriptionResolver' : 'Resolver') + "<" + mappedType + ", ParentType, Context" + (hasArguments
? ", " + (_this.convertName(parentName, {
const subscriptionType = this._schema.getSubscriptionType();
const isSubscriptionType = subscriptionType && subscriptionType.name === parentName;
return indent(`${node.name}?: ${isSubscriptionType ? 'SubscriptionResolver' : 'Resolver'}<${mappedType}, ParentType, Context${hasArguments
? `, ${this.convertName(parentName, {
useTypesPrefix: true
}) +
_this.convertName(node.name, {
this.convertName(node.name, {
useTypesPrefix: false
}) +
'Args')
: '') + ">,");
'Args'}`
: ''}>,`);
};
};
BaseResolversVisitor.prototype.ObjectTypeDefinition = function (node) {
var name = this.convertName(node, {
}
ObjectTypeDefinition(node) {
const name = this.convertName(node, {
suffix: 'Resolvers'
});
var type = null;
let type = null;
if (this.config.mappers[node.name]) {

@@ -189,31 +154,30 @@ type = this.config.mappers[node.name].type;

}
var block = new utils_1.DeclarationBlock(this._declarationBlockConfig)
const block = new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('interface')
.withName(name, "<Context = " + this.config.contextType + ", ParentType = " + type + ">")
.withBlock(node.fields.map(function (f) { return f(node.name); }).join('\n'));
.withName(name, `<Context = ${this.config.contextType}, ParentType = ${type}>`)
.withBlock(node.fields.map((f) => f(node.name)).join('\n'));
this._collectedResolvers[node.name] = name + '<Context>';
return block.string;
};
BaseResolversVisitor.prototype.UnionTypeDefinition = function (node, key, parent) {
var _this = this;
var name = this.convertName(node, {
}
UnionTypeDefinition(node, key, parent) {
const name = this.convertName(node, {
suffix: 'Resolvers'
});
var originalNode = parent[key];
var possibleTypes = originalNode.types
.map(function (node) { return _this.convertName(node); })
.map(function (f) { return "'" + f + "'"; })
const originalNode = parent[key];
const possibleTypes = originalNode.types
.map(node => this.convertName(node))
.map(f => `'${f}'`)
.join(' | ');
this._collectedResolvers[node.name] = name;
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('interface')
.withName(name, "<Context = " + this.config.contextType + ", ParentType = " + node.name + ">")
.withBlock(utils_1.indent("__resolveType: TypeResolveFn<" + possibleTypes + ">")).string;
};
BaseResolversVisitor.prototype.ScalarTypeDefinition = function (node) {
var baseName = this.convertName(node);
.withName(name, `<Context = ${this.config.contextType}, ParentType = ${node.name}>`)
.withBlock(indent(`__resolveType: TypeResolveFn<${possibleTypes}>`)).string;
}
ScalarTypeDefinition(node) {
const baseName = this.convertName(node);
this._collectedResolvers[node.name] = 'GraphQLScalarType';
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
return new DeclarationBlock(this._declarationBlockConfig)
.export()

@@ -223,32 +187,31 @@ .asKind('interface')

suffix: 'ScalarConfig'
}), " extends GraphQLScalarTypeConfig<" + baseName + ", any>")
.withBlock(utils_1.indent("name: '" + node.name + "'")).string;
};
BaseResolversVisitor.prototype.DirectiveDefinition = function (node) {
var directiveName = this.convertName(node, {
}), ` extends GraphQLScalarTypeConfig<${baseName}, any>`)
.withBlock(indent(`name: '${node.name}'`)).string;
}
DirectiveDefinition(node) {
const directiveName = this.convertName(node, {
suffix: 'DirectiveResolver'
});
var hasArguments = node.arguments && node.arguments.length > 0;
var directiveArgs = hasArguments
const hasArguments = node.arguments && node.arguments.length > 0;
const directiveArgs = hasArguments
? this._variablesTransfomer.transform(node.arguments)
: '';
this._collectedDirectiveResolvers[node.name] = directiveName + '<any, any, Context>';
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(directiveName, "<Result, Parent, Context = " + this.config.contextType + ", Args = { " + directiveArgs + " }>")
.withContent("DirectiveResolverFn<Result, Parent, Context, Args>").string;
};
BaseResolversVisitor.prototype.InterfaceTypeDefinition = function (node) {
var name = this.convertName(node, {
.withName(directiveName, `<Result, Parent, Context = ${this.config.contextType}, Args = { ${directiveArgs} }>`)
.withContent(`DirectiveResolverFn<Result, Parent, Context, Args>`).string;
}
InterfaceTypeDefinition(node) {
const name = this.convertName(node, {
suffix: 'Resolvers'
});
var allTypesMap = this._schema.getTypeMap();
var implementingTypes = [];
const allTypesMap = this._schema.getTypeMap();
const implementingTypes = [];
this._collectedResolvers[node.name] = name;
for (var _i = 0, _a = Object.values(allTypesMap); _i < _a.length; _i++) {
var graphqlType = _a[_i];
if (graphqlType instanceof graphql_1.GraphQLObjectType) {
var allInterfaces = graphqlType.getInterfaces();
if (allInterfaces.find(function (int) { return int.name === node.name; })) {
for (const graphqlType of Object.values(allTypesMap)) {
if (graphqlType instanceof GraphQLObjectType) {
const allInterfaces = graphqlType.getInterfaces();
if (allInterfaces.find(int => int.name === node.name)) {
implementingTypes.push(graphqlType.name);

@@ -258,15 +221,13 @@ }

}
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('interface')
.withName(name, "<Context = " + this.config.contextType + ", ParentType = " + node.name + ">")
.withBlock(utils_1.indent("__resolveType: TypeResolveFn<" + implementingTypes.map(function (name) { return "'" + name + "'"; }).join(' | ') + ">"))
.withName(name, `<Context = ${this.config.contextType}, ParentType = ${node.name}>`)
.withBlock(indent(`__resolveType: TypeResolveFn<${implementingTypes.map(name => `'${name}'`).join(' | ')}>`))
.string;
};
BaseResolversVisitor.prototype.SchemaDefinition = function () {
}
SchemaDefinition() {
return null;
};
return BaseResolversVisitor;
}());
exports.BaseResolversVisitor = BaseResolversVisitor;
}
}
//# sourceMappingURL=base-resolvers-visitor.js.map

@@ -1,51 +0,22 @@

"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var base_visitor_1 = require("./base-visitor");
var variables_to_object_1 = require("./variables-to-object");
var utils_1 = require("./utils");
var scalars_1 = require("./scalars");
var BaseTypesVisitor = /** @class */ (function (_super) {
__extends(BaseTypesVisitor, _super);
function BaseTypesVisitor(rawConfig, additionalConfig, defaultScalars) {
if (defaultScalars === void 0) { defaultScalars = scalars_1.DEFAULT_SCALARS; }
var _this = _super.call(this, rawConfig, __assign({ enumValues: rawConfig.enumValues || {} }, additionalConfig), defaultScalars) || this;
_this._argumentsTransformer = new variables_to_object_1.OperationVariablesToObject(_this.scalars, _this.convertName);
return _this;
import { BaseVisitor } from './base-visitor';
import { OperationVariablesToObject } from './variables-to-object';
import { DeclarationBlock, indent, wrapWithSingleQuotes } from './utils';
import { DEFAULT_SCALARS } from './scalars';
export class BaseTypesVisitor extends BaseVisitor {
constructor(rawConfig, additionalConfig, defaultScalars = DEFAULT_SCALARS) {
super(rawConfig, Object.assign({ enumValues: rawConfig.enumValues || {} }, additionalConfig), defaultScalars);
this._argumentsTransformer = new OperationVariablesToObject(this.scalars, this.convertName);
}
BaseTypesVisitor.prototype.setDeclarationBlockConfig = function (config) {
setDeclarationBlockConfig(config) {
this._declarationBlockConfig = config;
};
BaseTypesVisitor.prototype.setArgumentsTransformer = function (argumentsTransfomer) {
}
setArgumentsTransformer(argumentsTransfomer) {
this._argumentsTransformer = argumentsTransfomer;
};
BaseTypesVisitor.prototype.NonNullType = function (node) {
var asString = node.type;
}
NonNullType(node) {
const asString = node.type;
return asString;
};
BaseTypesVisitor.prototype.InputObjectTypeDefinition = function (node) {
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
}
InputObjectTypeDefinition(node) {
return new DeclarationBlock(this._declarationBlockConfig)
.export()

@@ -55,18 +26,17 @@ .asKind('type')

.withBlock(node.fields.join('\n')).string;
};
BaseTypesVisitor.prototype.InputValueDefinition = function (node) {
return utils_1.indent(node.name + ": " + node.type + ",");
};
BaseTypesVisitor.prototype.Name = function (node) {
}
InputValueDefinition(node) {
return indent(`${node.name}: ${node.type},`);
}
Name(node) {
return node.value;
};
BaseTypesVisitor.prototype.FieldDefinition = function (node) {
var typeString = node.type;
return utils_1.indent(node.name + ": " + typeString + ",");
};
BaseTypesVisitor.prototype.UnionTypeDefinition = function (node, key, parent) {
var _this = this;
var originalNode = parent[key];
var possibleTypes = originalNode.types.map(function (t) { return _this.convertName(t); }).join(' | ');
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
}
FieldDefinition(node) {
const typeString = node.type;
return indent(`${node.name}: ${typeString},`);
}
UnionTypeDefinition(node, key, parent) {
const originalNode = parent[key];
const possibleTypes = originalNode.types.map(t => this.convertName(t)).join(' | ');
return new DeclarationBlock(this._declarationBlockConfig)
.export()

@@ -76,10 +46,9 @@ .asKind('type')

.withContent(possibleTypes).string;
};
BaseTypesVisitor.prototype.ObjectTypeDefinition = function (node, key, parent) {
var _this = this;
var originalNode = parent[key];
var interfaces = originalNode.interfaces && node.interfaces.length > 0
? originalNode.interfaces.map(function (i) { return _this.convertName(i); }).join(' & ') + ' & '
}
ObjectTypeDefinition(node, key, parent) {
const originalNode = parent[key];
const interfaces = originalNode.interfaces && node.interfaces.length > 0
? originalNode.interfaces.map(i => this.convertName(i)).join(' & ') + ' & '
: '';
var typeDefinition = new utils_1.DeclarationBlock(this._declarationBlockConfig)
const typeDefinition = new DeclarationBlock(this._declarationBlockConfig)
.export()

@@ -90,20 +59,20 @@ .asKind('type')

.withBlock(node.fields.join('\n')).string;
var original = parent[key];
var fieldsWithArguments = original.fields.filter(function (field) { return field.arguments && field.arguments.length > 0; });
var fieldsArguments = fieldsWithArguments.map(function (field) {
var name = original.name.value +
_this.convertName(field, {
const original = parent[key];
const fieldsWithArguments = original.fields.filter(field => field.arguments && field.arguments.length > 0);
const fieldsArguments = fieldsWithArguments.map(field => {
const name = original.name.value +
this.convertName(field, {
useTypesPrefix: false
}) +
'Args';
return new utils_1.DeclarationBlock(_this._declarationBlockConfig)
return new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(_this.convertName(name))
.withBlock(_this._argumentsTransformer.transform(field.arguments)).string;
.withName(this.convertName(name))
.withBlock(this._argumentsTransformer.transform(field.arguments)).string;
});
return [typeDefinition].concat(fieldsArguments).filter(function (f) { return f; }).join('\n\n');
};
BaseTypesVisitor.prototype.InterfaceTypeDefinition = function (node) {
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
return [typeDefinition, ...fieldsArguments].filter(f => f).join('\n\n');
}
InterfaceTypeDefinition(node) {
return new DeclarationBlock(this._declarationBlockConfig)
.export()

@@ -113,5 +82,5 @@ .asKind('type')

.withBlock(node.fields.join('\n')).string;
};
BaseTypesVisitor.prototype.ScalarTypeDefinition = function (node) {
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
}
ScalarTypeDefinition(node) {
return new DeclarationBlock(this._declarationBlockConfig)
.export()

@@ -121,5 +90,5 @@ .asKind('type')

.withContent(this.config.scalars[node.name] || 'any').string;
};
BaseTypesVisitor.prototype.EnumTypeDefinition = function (node) {
return new utils_1.DeclarationBlock(this._declarationBlockConfig)
}
EnumTypeDefinition(node) {
return new DeclarationBlock(this._declarationBlockConfig)
.export()

@@ -129,33 +98,28 @@ .asKind('enum')

.withBlock(this.buildEnumValuesBlock(node.values)).string;
};
BaseTypesVisitor.prototype.buildEnumValuesBlock = function (values) {
var _this = this;
}
buildEnumValuesBlock(values) {
return values
.map(function (enumOption) {
return utils_1.indent("" + _this.convertName(enumOption) + _this._declarationBlockConfig.enumNameValueSeparator + " " + utils_1.wrapWithSingleQuotes(_this.config.enumValues[enumOption.name] || enumOption.name));
})
.map(enumOption => indent(`${this.convertName(enumOption)}${this._declarationBlockConfig.enumNameValueSeparator} ${wrapWithSingleQuotes(this.config.enumValues[enumOption.name] || enumOption.name)}`))
.join(', \n');
};
BaseTypesVisitor.prototype.DirectiveDefinition = function (node) {
}
DirectiveDefinition(node) {
return '';
};
BaseTypesVisitor.prototype._getTypeForNode = function (node) {
}
_getTypeForNode(node) {
return this.scalars[node.name] || this.convertName(node);
};
BaseTypesVisitor.prototype.NamedType = function (node) {
}
NamedType(node) {
return this._getTypeForNode(node);
};
BaseTypesVisitor.prototype.ListType = function (node) {
var asString = node.type;
}
ListType(node) {
const asString = node.type;
return this.wrapWithListType(asString);
};
BaseTypesVisitor.prototype.SchemaDefinition = function () {
}
SchemaDefinition() {
return null;
};
BaseTypesVisitor.prototype.wrapWithListType = function (str) {
return "Array<" + str + ">";
};
return BaseTypesVisitor;
}(base_visitor_1.BaseVisitor));
exports.BaseTypesVisitor = BaseTypesVisitor;
}
wrapWithListType(str) {
return `Array<${str}>`;
}
}
//# sourceMappingURL=base-types-visitor.js.map

@@ -1,45 +0,21 @@

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var autoBind = require("auto-bind");
var scalars_1 = require("./scalars");
var naming_1 = require("./naming");
var BaseVisitor = /** @class */ (function () {
function BaseVisitor(rawConfig, additionalConfig, defaultScalars) {
if (defaultScalars === void 0) { defaultScalars = scalars_1.DEFAULT_SCALARS; }
import autoBind from 'auto-bind';
import { DEFAULT_SCALARS } from './scalars';
import { convertFactory } from './naming';
export class BaseVisitor {
constructor(rawConfig, additionalConfig, defaultScalars = DEFAULT_SCALARS) {
this._declarationBlockConfig = {};
this._parsedConfig = __assign({ scalars: __assign({}, (defaultScalars || scalars_1.DEFAULT_SCALARS), (rawConfig.scalars || {})), convert: naming_1.convertFactory(rawConfig), typesPrefix: rawConfig.typesPrefix || '' }, (additionalConfig || {}));
this._parsedConfig = Object.assign({ scalars: Object.assign({}, (defaultScalars || DEFAULT_SCALARS), (rawConfig.scalars || {})), convert: convertFactory(rawConfig), typesPrefix: rawConfig.typesPrefix || '' }, (additionalConfig || {}));
autoBind(this);
}
Object.defineProperty(BaseVisitor.prototype, "config", {
get: function () {
return this._parsedConfig;
},
enumerable: true,
configurable: true
});
Object.defineProperty(BaseVisitor.prototype, "scalars", {
get: function () {
return this.config.scalars;
},
enumerable: true,
configurable: true
});
BaseVisitor.prototype.convertName = function (node, options) {
var useTypesPrefix = typeof (options && options.useTypesPrefix) === 'boolean' ? options.useTypesPrefix : true;
get config() {
return this._parsedConfig;
}
get scalars() {
return this.config.scalars;
}
convertName(node, options) {
const useTypesPrefix = typeof (options && options.useTypesPrefix) === 'boolean' ? options.useTypesPrefix : true;
return (useTypesPrefix ? this.config.typesPrefix : '') + this.config.convert(node, options);
};
return BaseVisitor;
}());
exports.BaseVisitor = BaseVisitor;
}
}
//# sourceMappingURL=base-visitor.js.map

@@ -1,151 +0,117 @@

"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var index_1 = require("./index");
var autoBind = require("auto-bind");
var graphql_1 = require("graphql");
var dependency_graph_1 = require("dependency-graph");
var graphql_tag_1 = require("graphql-tag");
var graphql_codegen_core_1 = require("graphql-codegen-core");
var utils_1 = require("./utils");
var ClientSideBaseVisitor = /** @class */ (function (_super) {
__extends(ClientSideBaseVisitor, _super);
function ClientSideBaseVisitor(_fragments, rawConfig, additionalConfig) {
var _this = _super.call(this, rawConfig, __assign({ noGraphQLTag: utils_1.getConfigValue(rawConfig.noGraphQLTag, false), gqlImport: rawConfig.gqlImport || null }, additionalConfig)) || this;
_this._fragments = _fragments;
autoBind(_this);
return _this;
import { BaseVisitor } from './index';
import autoBind from 'auto-bind';
import { print } from 'graphql';
import { DepGraph } from 'dependency-graph';
import gqlTag from 'graphql-tag';
import { toPascalCase } from 'graphql-codegen-plugin-helpers';
import { getConfigValue } from './utils';
export class ClientSideBaseVisitor extends BaseVisitor {
constructor(_fragments, rawConfig, additionalConfig) {
super(rawConfig, Object.assign({ noGraphQLTag: getConfigValue(rawConfig.noGraphQLTag, false), gqlImport: rawConfig.gqlImport || null }, additionalConfig));
this._fragments = _fragments;
autoBind(this);
}
ClientSideBaseVisitor.prototype._getFragmentName = function (fragment) {
_getFragmentName(fragment) {
return (typeof fragment === 'string' ? fragment : fragment.name.value) + 'FragmentDoc';
};
ClientSideBaseVisitor.prototype._extractFragments = function (document) {
return (graphql_1.print(document).match(/\.\.\.[a-z0-9\_]+/gi) || []).map(function (name) { return name.replace('...', ''); });
};
ClientSideBaseVisitor.prototype._transformFragments = function (document) {
var _this = this;
return this._extractFragments(document).map(function (document) { return _this._getFragmentName(document); });
};
ClientSideBaseVisitor.prototype._includeFragments = function (fragments) {
}
_extractFragments(document) {
return (print(document).match(/\.\.\.[a-z0-9\_]+/gi) || []).map(name => name.replace('...', ''));
}
_transformFragments(document) {
return this._extractFragments(document).map(document => this._getFragmentName(document));
}
_includeFragments(fragments) {
if (fragments) {
return "" + fragments
.filter(function (name, i, all) { return all.indexOf(name) === i; })
.map(function (name) { return '${' + name + '}'; })
.join('\n');
return `${fragments
.filter((name, i, all) => all.indexOf(name) === i)
.map(name => '${' + name + '}')
.join('\n')}`;
}
return '';
};
ClientSideBaseVisitor.prototype._prepareDocument = function (documentStr) {
}
_prepareDocument(documentStr) {
return documentStr;
};
ClientSideBaseVisitor.prototype._gql = function (node) {
var doc = this._prepareDocument("\n " + graphql_1.print(node) + "\n " + this._includeFragments(this._transformFragments(node)));
}
_gql(node) {
const doc = this._prepareDocument(`
${print(node)}
${this._includeFragments(this._transformFragments(node))}`);
if (this.config.noGraphQLTag) {
return JSON.stringify(graphql_tag_1.default(doc));
return JSON.stringify(gqlTag(doc));
}
return 'gql`' + doc + '`';
};
ClientSideBaseVisitor.prototype._generateFragment = function (fragmentDocument) {
var name = this._getFragmentName(fragmentDocument);
return "export const " + name + (this.config.noGraphQLTag ? ': DocumentNode' : '') + " = " + this._gql(fragmentDocument) + ";";
};
Object.defineProperty(ClientSideBaseVisitor.prototype, "fragments", {
get: function () {
var _this = this;
if (this._fragments.length === 0) {
return '';
}
var graph = new dependency_graph_1.DepGraph({ circular: true });
for (var _i = 0, _a = this._fragments; _i < _a.length; _i++) {
var fragment = _a[_i];
if (graph.hasNode(fragment.name.value)) {
var cachedAsString = graphql_1.print(graph.getNodeData(fragment.name.value));
var asString = graphql_1.print(fragment);
if (cachedAsString !== asString) {
throw new Error("Duplicated fragment called '" + fragment.name + "'!");
}
}
_generateFragment(fragmentDocument) {
const name = this._getFragmentName(fragmentDocument);
return `export const ${name}${this.config.noGraphQLTag ? ': DocumentNode' : ''} = ${this._gql(fragmentDocument)};`;
}
get fragments() {
if (this._fragments.length === 0) {
return '';
}
const graph = new DepGraph({ circular: true });
for (const fragment of this._fragments) {
if (graph.hasNode(fragment.name.value)) {
const cachedAsString = print(graph.getNodeData(fragment.name.value));
const asString = print(fragment);
if (cachedAsString !== asString) {
throw new Error(`Duplicated fragment called '${fragment.name}'!`);
}
graph.addNode(fragment.name.value, fragment);
}
this._fragments.forEach(function (fragment) {
var depends = _this._extractFragments(fragment);
if (depends) {
depends.forEach(function (name) {
graph.addDependency(fragment.name.value, name);
});
}
});
return graph
.overallOrder()
.map(function (name) { return _this._generateFragment(graph.getNodeData(name)); })
.join('\n');
},
enumerable: true,
configurable: true
});
ClientSideBaseVisitor.prototype._parseImport = function (importStr) {
var _a = importStr.split('#'), moduleName = _a[0], propName = _a[1];
graph.addNode(fragment.name.value, fragment);
}
this._fragments.forEach(fragment => {
const depends = this._extractFragments(fragment);
if (depends) {
depends.forEach(name => {
graph.addDependency(fragment.name.value, name);
});
}
});
return graph
.overallOrder()
.map(name => this._generateFragment(graph.getNodeData(name)))
.join('\n');
}
_parseImport(importStr) {
const [moduleName, propName] = importStr.split('#');
return {
moduleName: moduleName,
propName: propName
moduleName,
propName
};
};
ClientSideBaseVisitor.prototype.getImports = function () {
var gqlImport = this._parseImport(this.config.gqlImport || 'graphql-tag');
var imports = [];
}
getImports() {
const gqlImport = this._parseImport(this.config.gqlImport || 'graphql-tag');
let imports = [];
if (!this.config.noGraphQLTag) {
imports.push("\nimport " + (gqlImport.propName ? "{ " + (gqlImport.propName === 'gql' ? 'gql' : gqlImport.propName + " as gql") + " }" : 'gql') + " from '" + gqlImport.moduleName + "';");
imports.push(`
import ${gqlImport.propName ? `{ ${gqlImport.propName === 'gql' ? 'gql' : `${gqlImport.propName} as gql`} }` : 'gql'} from '${gqlImport.moduleName}';`);
}
else {
imports.push("import { DocumentNode } from 'graphql';");
imports.push(`import { DocumentNode } from 'graphql';`);
}
return imports.join('\n');
};
ClientSideBaseVisitor.prototype.buildOperation = function (node, documentVariableName, operationType, operationResultType, operationVariablesTypes) {
}
buildOperation(node, documentVariableName, operationType, operationResultType, operationVariablesTypes) {
return null;
};
ClientSideBaseVisitor.prototype.OperationDefinition = function (node) {
}
OperationDefinition(node) {
if (!node.name || !node.name.value) {
return null;
}
var documentVariableName = this.convertName(node, {
const documentVariableName = this.convertName(node, {
suffix: 'Document'
});
var documentString = "export const " + documentVariableName + (this.config.noGraphQLTag ? ': DocumentNode' : '') + " = " + this._gql(node) + ";";
var operationType = graphql_codegen_core_1.toPascalCase(node.operation);
var operationResultType = this.convertName(node, {
const documentString = `export const ${documentVariableName}${this.config.noGraphQLTag ? ': DocumentNode' : ''} = ${this._gql(node)};`;
const operationType = toPascalCase(node.operation);
const operationResultType = this.convertName(node, {
suffix: operationType
});
var operationVariablesTypes = this.convertName(node, {
const operationVariablesTypes = this.convertName(node, {
suffix: operationType + 'Variables'
});
var additional = this.buildOperation(node, documentVariableName, operationType, operationResultType, operationVariablesTypes);
return [documentString, additional].filter(function (a) { return a; }).join('\n');
};
return ClientSideBaseVisitor;
}(index_1.BaseVisitor));
exports.ClientSideBaseVisitor = ClientSideBaseVisitor;
const additional = this.buildOperation(node, documentVariableName, operationType, operationResultType, operationVariablesTypes);
return [documentString, additional].filter(a => a).join('\n');
}
}
//# sourceMappingURL=client-side-base-visitor.js.map

@@ -1,15 +0,10 @@

"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("./utils"));
__export(require("./scalars"));
__export(require("./base-visitor"));
__export(require("./base-types-visitor"));
__export(require("./base-documents-visitor"));
__export(require("./base-resolvers-visitor"));
__export(require("./client-side-base-visitor"));
__export(require("./variables-to-object"));
__export(require("./selection-set-to-object"));
export * from './utils';
export * from './scalars';
export * from './base-visitor';
export * from './base-types-visitor';
export * from './base-documents-visitor';
export * from './base-resolvers-visitor';
export * from './client-side-base-visitor';
export * from './variables-to-object';
export * from './selection-set-to-object';
//# sourceMappingURL=index.js.map

@@ -1,5 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var graphql_codegen_plugin_helpers_1 = require("graphql-codegen-plugin-helpers");
var utils_1 = require("./utils");
import { resolveExternalModuleAndFn } from 'graphql-codegen-plugin-helpers';
import { toPascalCase } from './utils';
function getKind(node) {

@@ -51,27 +49,26 @@ if (typeof node === 'string') {

}
function convertFactory(config) {
export function convertFactory(config) {
function resolveConventionName(type) {
if (!config.namingConvention) {
return utils_1.toPascalCase;
return toPascalCase;
}
if (typeof config.namingConvention === 'string') {
return graphql_codegen_plugin_helpers_1.resolveExternalModuleAndFn(config.namingConvention);
return resolveExternalModuleAndFn(config.namingConvention);
}
if (config.namingConvention[type] === 'keep') {
return function (str) { return str; };
return str => str;
}
if (typeof config.namingConvention[type] === 'string') {
return graphql_codegen_plugin_helpers_1.resolveExternalModuleAndFn(config.namingConvention[type]);
return resolveExternalModuleAndFn(config.namingConvention[type]);
}
return config.namingConvention[type];
}
return function (node, opts) {
var prefix = opts && opts.prefix;
var suffix = opts && opts.suffix;
var kind = getKind(node);
var str = [prefix || '', getName(node), suffix || ''].join('');
return (node, opts) => {
const prefix = opts && opts.prefix;
const suffix = opts && opts.suffix;
const kind = getKind(node);
const str = [prefix || '', getName(node), suffix || ''].join('');
return resolveConventionName(kind)(str);
};
}
exports.convertFactory = convertFactory;
//# sourceMappingURL=naming.js.map

@@ -1,4 +0,2 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DEFAULT_SCALARS = {
export const DEFAULT_SCALARS = {
ID: 'string',

@@ -5,0 +3,0 @@ String: 'string',

@@ -1,5 +0,3 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var graphql_1 = require("graphql");
var utils_1 = require("./utils");
import { Kind, isObjectType, isUnionType, isInterfaceType, isEnumType, isEqualType, SchemaMetaFieldDef, TypeMetaFieldDef } from 'graphql';
import { getBaseType, quoteIfNeeded } from './utils';
function isMetadataFieldName(name) {

@@ -9,12 +7,12 @@ return ['__schema', '__type'].includes(name);

function isRootType(type, schema) {
return (graphql_1.isEqualType(type, schema.getQueryType()) ||
graphql_1.isEqualType(type, schema.getMutationType()) ||
graphql_1.isEqualType(type, schema.getSubscriptionType()));
return (isEqualType(type, schema.getQueryType()) ||
isEqualType(type, schema.getMutationType()) ||
isEqualType(type, schema.getSubscriptionType()));
}
var metadataFieldMap = {
__schema: graphql_1.SchemaMetaFieldDef,
__type: graphql_1.TypeMetaFieldDef
const metadataFieldMap = {
__schema: SchemaMetaFieldDef,
__type: TypeMetaFieldDef
};
var SelectionSetToObject = /** @class */ (function () {
function SelectionSetToObject(_scalars, _schema, _convertName, _addTypename, _parentSchemaType, _selectionSet) {
export class SelectionSetToObject {
constructor(_scalars, _schema, _convertName, _addTypename, _parentSchemaType, _selectionSet) {
this._scalars = _scalars;

@@ -33,9 +31,9 @@ this._schema = _schema;

}
SelectionSetToObject.prototype.createNext = function (parentSchemaType, selectionSet) {
throw new Error("You must override createNext in your SelectionSetToObject implementation!");
};
SelectionSetToObject.prototype.wrapTypeWithModifiers = function (baseType, type) {
throw new Error("You must override wrapTypeWithModifiers in your SelectionSetToObject implementation!");
};
SelectionSetToObject.prototype._collectField = function (field) {
createNext(parentSchemaType, selectionSet) {
throw new Error(`You must override createNext in your SelectionSetToObject implementation!`);
}
wrapTypeWithModifiers(baseType, type) {
throw new Error(`You must override wrapTypeWithModifiers in your SelectionSetToObject implementation!`);
}
_collectField(field) {
if (field.name.value === '__typename') {

@@ -45,4 +43,4 @@ this._queriedForTypename = true;

}
if (graphql_1.isObjectType(this._parentSchemaType) || graphql_1.isInterfaceType(this._parentSchemaType)) {
var schemaField = void 0;
if (isObjectType(this._parentSchemaType) || isInterfaceType(this._parentSchemaType)) {
let schemaField;
if (isRootType(this._parentSchemaType, this._schema) && isMetadataFieldName(field.name.value)) {

@@ -54,6 +52,6 @@ schemaField = metadataFieldMap[field.name.value];

}
var rawType = schemaField.type;
var baseType = utils_1.getBaseType(rawType);
var typeName = baseType.name;
if (this._scalars[typeName] || graphql_1.isEnumType(baseType)) {
const rawType = schemaField.type;
const baseType = getBaseType(rawType);
const typeName = baseType.name;
if (this._scalars[typeName] || isEnumType(baseType)) {
if (field.alias && field.alias.value) {

@@ -70,3 +68,3 @@ this._primitiveAliasedFields.push({

else {
var selectionSetToObject = this.createNext(baseType, field.selectionSet);
const selectionSetToObject = this.createNext(baseType, field.selectionSet);
this._linksFields.push({

@@ -80,10 +78,10 @@ alias: field.alias ? field.alias.value : null,

}
};
SelectionSetToObject.prototype._collectFragmentSpread = function (node) {
}
_collectFragmentSpread(node) {
this._fragmentSpreads.push(node.name.value);
};
SelectionSetToObject.prototype._collectInlineFragment = function (node) {
var onType = node.typeCondition.name.value;
var schemaType = this._schema.getType(onType);
var selectionSet = this.createNext(schemaType, node.selectionSet);
}
_collectInlineFragment(node) {
const onType = node.typeCondition.name.value;
const schemaType = this._schema.getType(onType);
const selectionSet = this.createNext(schemaType, node.selectionSet);
if (!this._inlineFragments[onType]) {

@@ -93,44 +91,39 @@ this._inlineFragments[onType] = [];

this._inlineFragments[onType].push(selectionSet.string);
};
Object.defineProperty(SelectionSetToObject.prototype, "string", {
get: function () {
if (!this._selectionSet || !this._selectionSet.selections || this._selectionSet.selections.length === 0) {
return '';
}
get string() {
if (!this._selectionSet || !this._selectionSet.selections || this._selectionSet.selections.length === 0) {
return '';
}
const { selections } = this._selectionSet;
for (const selection of selections) {
switch (selection.kind) {
case Kind.FIELD:
this._collectField(selection);
break;
case Kind.FRAGMENT_SPREAD:
this._collectFragmentSpread(selection);
break;
case Kind.INLINE_FRAGMENT:
this._collectInlineFragment(selection);
break;
}
var selections = this._selectionSet.selections;
for (var _i = 0, selections_1 = selections; _i < selections_1.length; _i++) {
var selection = selections_1[_i];
switch (selection.kind) {
case graphql_1.Kind.FIELD:
this._collectField(selection);
break;
case graphql_1.Kind.FRAGMENT_SPREAD:
this._collectFragmentSpread(selection);
break;
case graphql_1.Kind.INLINE_FRAGMENT:
this._collectInlineFragment(selection);
break;
}
}
var parentName = this._convertName(this._parentSchemaType.name, {
useTypesPrefix: true
});
var typeName = this._addTypename || this._queriedForTypename ? this.buildTypeNameField() : null;
var baseFields = this.buildPrimitiveFields(parentName, this._primitiveFields);
var aliasBaseFields = this.buildAliasedPrimitiveFields(parentName, this._primitiveAliasedFields);
var linksFields = this.buildLinkFields(this._linksFields);
var inlineFragments = this.buildInlineFragments(this._inlineFragments);
var fragmentSpreads = this.buildFragmentSpread(this._fragmentSpreads);
var fieldsSet = [typeName, baseFields, aliasBaseFields, linksFields, fragmentSpreads, inlineFragments].filter(function (f) { return f && f !== ''; });
return this.mergeAllFields(fieldsSet);
},
enumerable: true,
configurable: true
});
SelectionSetToObject.prototype.mergeAllFields = function (fieldsSet) {
return utils_1.quoteIfNeeded(fieldsSet, ' & ');
};
SelectionSetToObject.prototype.buildTypeNameField = function () {
var possibleTypes = [];
if (!graphql_1.isUnionType(this._parentSchemaType) && !graphql_1.isInterfaceType(this._parentSchemaType)) {
}
const parentName = this._convertName(this._parentSchemaType.name, {
useTypesPrefix: true
});
const typeName = this._addTypename || this._queriedForTypename ? this.buildTypeNameField() : null;
const baseFields = this.buildPrimitiveFields(parentName, this._primitiveFields);
const aliasBaseFields = this.buildAliasedPrimitiveFields(parentName, this._primitiveAliasedFields);
const linksFields = this.buildLinkFields(this._linksFields);
const inlineFragments = this.buildInlineFragments(this._inlineFragments);
const fragmentSpreads = this.buildFragmentSpread(this._fragmentSpreads);
const fieldsSet = [typeName, baseFields, aliasBaseFields, linksFields, fragmentSpreads, inlineFragments].filter(f => f && f !== '');
return this.mergeAllFields(fieldsSet);
}
mergeAllFields(fieldsSet) {
return quoteIfNeeded(fieldsSet, ' & ');
}
buildTypeNameField() {
const possibleTypes = [];
if (!isUnionType(this._parentSchemaType) && !isInterfaceType(this._parentSchemaType)) {
possibleTypes.push(this._parentSchemaType.name);

@@ -141,52 +134,45 @@ }

}
return "{ " + this.formatNamedField('__typename') + (this._queriedForTypename ? '' : '?') + ": " + possibleTypes
.map(function (t) { return "'" + t + "'"; })
.join(' | ') + " }";
};
SelectionSetToObject.prototype.buildPrimitiveFields = function (parentName, fields) {
return `{ ${this.formatNamedField('__typename')}${this._queriedForTypename ? '' : '?'}: ${possibleTypes
.map(t => `'${t}'`)
.join(' | ')} }`;
}
buildPrimitiveFields(parentName, fields) {
if (fields.length === 0) {
return null;
}
return "Pick<" + parentName + ", " + fields.map(function (field) { return "'" + field + "'"; }).join(' | ') + ">";
};
SelectionSetToObject.prototype.buildAliasedPrimitiveFields = function (parentName, fields) {
var _this = this;
return `Pick<${parentName}, ${fields.map(field => `'${field}'`).join(' | ')}>`;
}
buildAliasedPrimitiveFields(parentName, fields) {
if (fields.length === 0) {
return null;
}
return "{ " + fields
.map(function (aliasedField) { return _this.formatNamedField(aliasedField.alias) + ": " + parentName + "['" + aliasedField.fieldName + "']"; })
.join(', ') + " }";
};
SelectionSetToObject.prototype.formatNamedField = function (name) {
return `{ ${fields
.map(aliasedField => `${this.formatNamedField(aliasedField.alias)}: ${parentName}['${aliasedField.fieldName}']`)
.join(', ')} }`;
}
formatNamedField(name) {
return name;
};
SelectionSetToObject.prototype.buildLinkFields = function (fields) {
var _this = this;
}
buildLinkFields(fields) {
if (fields.length === 0) {
return null;
}
return "{ " + fields
.map(function (field) { return _this.formatNamedField(field.alias || field.name) + ": " + field.selectionSet; })
.join(', ') + " }";
};
SelectionSetToObject.prototype.buildInlineFragments = function (inlineFragments) {
var allPossibleTypes = Object.keys(inlineFragments).map(function (typeName) { return inlineFragments[typeName].join(' & '); });
return allPossibleTypes.length === 0 ? null : "(" + allPossibleTypes.join(' | ') + ")";
};
SelectionSetToObject.prototype.buildFragmentSpread = function (fragmentsSpread) {
var _this = this;
return `{ ${fields
.map(field => `${this.formatNamedField(field.alias || field.name)}: ${field.selectionSet}`)
.join(', ')} }`;
}
buildInlineFragments(inlineFragments) {
const allPossibleTypes = Object.keys(inlineFragments).map(typeName => inlineFragments[typeName].join(' & '));
return allPossibleTypes.length === 0 ? null : `(${allPossibleTypes.join(' | ')})`;
}
buildFragmentSpread(fragmentsSpread) {
if (fragmentsSpread.length === 0) {
return null;
}
return utils_1.quoteIfNeeded(fragmentsSpread.map(function (fragmentName) {
return _this._convertName(fragmentName, {
suffix: 'Fragment',
useTypesPrefix: true
});
}), ' & ');
};
return SelectionSetToObject;
}());
exports.SelectionSetToObject = SelectionSetToObject;
return quoteIfNeeded(fragmentsSpread.map(fragmentName => this._convertName(fragmentName, {
suffix: 'Fragment',
useTypesPrefix: true
})), ' & ');
}
}
//# sourceMappingURL=selection-set-to-object.js.map

@@ -1,3 +0,1 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types.js.map

@@ -8,3 +8,3 @@ import { NameNode, TypeNode, NamedTypeNode, GraphQLObjectType, GraphQLNonNull, GraphQLList, GraphQLOutputType, GraphQLNamedType } from 'graphql';

export declare function breakLine(str: string): string;
export declare function indent(str: string): string;
export declare function indent(str: string, count?: number): string;
export interface DeclarationBlockConfig {

@@ -11,0 +11,0 @@ blockWrapper?: string;

@@ -1,20 +0,7 @@

"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var change_case_1 = require("change-case");
var graphql_1 = require("graphql");
import { pascalCase } from 'change-case';
import { Kind, isNonNullType, isListType } from 'graphql';
function isWrapperType(t) {
return graphql_1.isListType(t) || graphql_1.isNonNullType(t);
return isListType(t) || isNonNullType(t);
}
exports.getConfigValue = function (value, defaultValue) {
export const getConfigValue = (value, defaultValue) => {
if (value === null || value === undefined) {

@@ -25,3 +12,3 @@ return defaultValue;

};
function getBaseType(type) {
export function getBaseType(type) {
if (isWrapperType(type)) {

@@ -34,5 +21,3 @@ return getBaseType(type.ofType);

}
exports.getBaseType = getBaseType;
function quoteIfNeeded(array, joinWith) {
if (joinWith === void 0) { joinWith = ' & '; }
export function quoteIfNeeded(array, joinWith = ' & ') {
if (array.length === 0) {

@@ -45,24 +30,19 @@ return '';

else {
return "(" + array.join(joinWith) + ")";
return `(${array.join(joinWith)})`;
}
}
exports.quoteIfNeeded = quoteIfNeeded;
function block(array) {
export function block(array) {
return array && array.length !== 0 ? '{\n' + array.join('\n') + '\n}' : '';
}
exports.block = block;
function wrapWithSingleQuotes(str) {
return "'" + str + "'";
export function wrapWithSingleQuotes(str) {
return `'${str}'`;
}
exports.wrapWithSingleQuotes = wrapWithSingleQuotes;
function breakLine(str) {
export function breakLine(str) {
return str + '\n';
}
exports.breakLine = breakLine;
function indent(str) {
return ' ' + str;
export function indent(str, count = 1) {
return new Array(count).fill(' ').join('') + str;
}
exports.indent = indent;
var DeclarationBlock = /** @class */ (function () {
function DeclarationBlock(_config) {
export class DeclarationBlock {
constructor(_config) {
this._config = _config;

@@ -76,75 +56,71 @@ this._export = false;

this._nameGenerics = null;
this._config = __assign({ blockWrapper: '', enumNameValueSeparator: ':' }, this._config);
this._config = Object.assign({ blockWrapper: '', enumNameValueSeparator: ':' }, this._config);
}
DeclarationBlock.prototype.export = function (exp) {
if (exp === void 0) { exp = true; }
export(exp = true) {
this._export = exp;
return this;
};
DeclarationBlock.prototype.asKind = function (kind) {
}
asKind(kind) {
this._kind = kind;
return this;
};
DeclarationBlock.prototype.withMethodCall = function (methodName) {
}
withMethodCall(methodName) {
this._methodName = methodName;
return this;
};
DeclarationBlock.prototype.withBlock = function (block) {
}
withBlock(block) {
this._block = block;
return this;
};
DeclarationBlock.prototype.withContent = function (content) {
}
withContent(content) {
this._content = content;
return this;
};
DeclarationBlock.prototype.withName = function (name, generics) {
if (generics === void 0) { generics = null; }
}
withName(name, generics = null) {
this._name = name;
this._nameGenerics = generics;
return this;
};
Object.defineProperty(DeclarationBlock.prototype, "string", {
get: function () {
var result = '';
if (this._export) {
result += 'export ';
}
get string() {
let result = '';
if (this._export) {
result += 'export ';
}
if (this._kind) {
let extra = '';
let name = '';
if (['type', 'const', 'var', 'let'].includes(this._kind)) {
extra = '= ';
}
if (this._kind) {
var extra = '';
var name = '';
if (['type', 'const', 'var', 'let'].includes(this._kind)) {
extra = '= ';
}
if (this._name) {
name = this._name + (this._nameGenerics || '') + ' ';
}
result += this._kind + ' ' + name + extra;
if (this._name) {
name = this._name + (this._nameGenerics || '') + ' ';
}
if (this._block) {
if (this._content) {
result += this._content;
}
if (this._methodName) {
result += this._methodName + "({" + this._config.blockWrapper + "\n" + this._block + "\n" + this._config.blockWrapper + "})";
}
else {
result += "{" + this._config.blockWrapper + "\n" + this._block + "\n" + this._config.blockWrapper + "}";
}
}
else if (this._content) {
result += this._kind + ' ' + name + extra;
}
if (this._block) {
if (this._content) {
result += this._content;
}
else if (this._kind) {
result += '{}';
if (this._methodName) {
result += `${this._methodName}({${this._config.blockWrapper}
${this._block}
${this._config.blockWrapper}})`;
}
return result + (this._kind === 'interface' ? '' : ';') + '\n';
},
enumerable: true,
configurable: true
});
return DeclarationBlock;
}());
exports.DeclarationBlock = DeclarationBlock;
function getBaseTypeNode(typeNode) {
if (typeNode.kind === graphql_1.Kind.LIST_TYPE || typeNode.kind === graphql_1.Kind.NON_NULL_TYPE) {
else {
result += `{${this._config.blockWrapper}
${this._block}
${this._config.blockWrapper}}`;
}
}
else if (this._content) {
result += this._content;
}
else if (this._kind) {
result += '{}';
}
return result + (this._kind === 'interface' ? '' : ';') + '\n';
}
}
export function getBaseTypeNode(typeNode) {
if (typeNode.kind === Kind.LIST_TYPE || typeNode.kind === Kind.NON_NULL_TYPE) {
return getBaseTypeNode(typeNode.type);

@@ -154,25 +130,20 @@ }

}
exports.getBaseTypeNode = getBaseTypeNode;
function toPascalCase(str) {
export function toPascalCase(str) {
return str
.split('_')
.map(function (s) { return change_case_1.pascalCase(s); })
.map(s => pascalCase(s))
.join('_');
}
exports.toPascalCase = toPascalCase;
exports.wrapTypeWithModifiers = function (prefix) {
if (prefix === void 0) { prefix = ''; }
return function (baseType, type) {
if (graphql_1.isNonNullType(type)) {
return exports.wrapTypeWithModifiers(prefix)(baseType, type.ofType).substr(1);
}
else if (graphql_1.isListType(type)) {
var innerType = exports.wrapTypeWithModifiers(prefix)(baseType, type.ofType);
return prefix + "Array<" + innerType + ">";
}
else {
return "" + prefix + baseType;
}
};
export const wrapTypeWithModifiers = (prefix = '') => (baseType, type) => {
if (isNonNullType(type)) {
return wrapTypeWithModifiers(prefix)(baseType, type.ofType).substr(1);
}
else if (isListType(type)) {
const innerType = wrapTypeWithModifiers(prefix)(baseType, type.ofType);
return `${prefix}Array<${innerType}>`;
}
else {
return `${prefix}${baseType}`;
}
};
//# sourceMappingURL=utils.js.map

@@ -1,8 +0,6 @@

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var graphql_1 = require("graphql");
var utils_1 = require("./utils");
var autoBind = require("auto-bind");
var OperationVariablesToObject = /** @class */ (function () {
function OperationVariablesToObject(_scalars, _convertName) {
import { Kind } from 'graphql';
import { indent, getBaseTypeNode } from './utils';
import autoBind from 'auto-bind';
export class OperationVariablesToObject {
constructor(_scalars, _convertName) {
this._scalars = _scalars;

@@ -12,3 +10,3 @@ this._convertName = _convertName;

}
OperationVariablesToObject.prototype.getName = function (node) {
getName(node) {
if (node.name) {

@@ -24,37 +22,34 @@ if (typeof node.name === 'string') {

return null;
};
OperationVariablesToObject.prototype.transform = function (variablesNode) {
var _this = this;
}
transform(variablesNode) {
if (!variablesNode || variablesNode.length === 0) {
return null;
}
return variablesNode.map(function (variable) { return utils_1.indent(_this.transformVariable(variable)); }).join(',\n');
};
OperationVariablesToObject.prototype.transformVariable = function (variable) {
var baseType = typeof variable.type === 'string' ? variable.type : utils_1.getBaseTypeNode(variable.type);
var typeName = typeof baseType === 'string' ? baseType : baseType.name.value;
var typeValue = this._scalars[typeName] ||
return variablesNode.map(variable => indent(this.transformVariable(variable))).join(',\n');
}
transformVariable(variable) {
const baseType = typeof variable.type === 'string' ? variable.type : getBaseTypeNode(variable.type);
const typeName = typeof baseType === 'string' ? baseType : baseType.name.value;
const typeValue = this._scalars[typeName] ||
this._convertName(baseType, {
useTypesPrefix: true
});
var fieldName = this.getName(variable);
var fieldType = this.wrapAstTypeWithModifiers(typeValue, variable.type);
var hasDefaultValue = variable.defaultValue != null && typeof variable.defaultValue !== 'undefined';
var isNonNullType = variable.type.kind === graphql_1.Kind.NON_NULL_TYPE;
var formattedFieldString = this.formatFieldString(fieldName, isNonNullType, hasDefaultValue);
var formattedTypeString = this.formatTypeString(fieldType, isNonNullType, hasDefaultValue);
return formattedFieldString + ": " + formattedTypeString;
};
OperationVariablesToObject.prototype.wrapAstTypeWithModifiers = function (baseType, typeNode) {
throw new Error("You must override \"wrapAstTypeWithModifiers\" of OperationVariablesToObject!");
};
OperationVariablesToObject.prototype.formatFieldString = function (fieldName, isNonNullType, hasDefaultValue) {
const fieldName = this.getName(variable);
const fieldType = this.wrapAstTypeWithModifiers(typeValue, variable.type);
const hasDefaultValue = variable.defaultValue != null && typeof variable.defaultValue !== 'undefined';
const isNonNullType = variable.type.kind === Kind.NON_NULL_TYPE;
const formattedFieldString = this.formatFieldString(fieldName, isNonNullType, hasDefaultValue);
const formattedTypeString = this.formatTypeString(fieldType, isNonNullType, hasDefaultValue);
return `${formattedFieldString}: ${formattedTypeString}`;
}
wrapAstTypeWithModifiers(baseType, typeNode) {
throw new Error(`You must override "wrapAstTypeWithModifiers" of OperationVariablesToObject!`);
}
formatFieldString(fieldName, isNonNullType, hasDefaultValue) {
return fieldName;
};
OperationVariablesToObject.prototype.formatTypeString = function (fieldType, isNonNullType, hasDefaultValue) {
}
formatTypeString(fieldType, isNonNullType, hasDefaultValue) {
return fieldType;
};
return OperationVariablesToObject;
}());
exports.OperationVariablesToObject = OperationVariablesToObject;
}
}
//# sourceMappingURL=variables-to-object.js.map
{
"name": "graphql-codegen-visitor-plugin-common",
"version": "0.19.0-alpha.3f859ab8",
"version": "0.19.0-alpha.52db8d29",
"license": "MIT",

@@ -11,4 +11,6 @@ "scripts": {

"dependency-graph": "0.8.0",
"graphql-codegen-core": "0.19.0-alpha.3f859ab8",
"graphql-tag": "2.10.1"
"esm": "3.2.11",
"graphql-codegen-plugin-helpers": "0.19.0-alpha.52db8d29",
"graphql-tag": "2.10.1",
"tslib": "1.9.3"
},

@@ -21,5 +23,7 @@ "peerDependencies": {

"graphql": "14.1.1",
"graphql-codegen-testing": "0.19.0-alpha.52db8d29",
"typescript": "3.3.3333"
},
"main": "./dist/index.js",
"main": "cjs/index.js",
"module": "dist/index.js",
"typings": "dist/index.d.ts",

@@ -32,3 +36,6 @@ "typescript": {

"ts-jest": {
"enableTsDiagnostics": false
"enableTsDiagnostics": false,
"tsConfig": {
"esModuleInterop": true
}
}

@@ -35,0 +42,0 @@ },

{
"compilerOptions": {
"importHelpers": true,
"experimentalDecorators": true,
"module": "commonjs",
"target": "es5",
"module": "esnext",
"target": "es2018",
"lib": ["es6", "esnext", "es2015"],

@@ -7,0 +8,0 @@ "suppressImplicitAnyIndexErrors": true,

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc