Skip to content

Commit

Permalink
fix: Compile ES6 to ES5 to add support for both 'scalar' and 'union' …
Browse files Browse the repository at this point in the history
…keywords
  • Loading branch information
nicolasdao committed Nov 27, 2017
1 parent e89358e commit 3bb4992
Show file tree
Hide file tree
Showing 3 changed files with 155 additions and 82 deletions.
233 changes: 153 additions & 80 deletions lib/graphqls2s.js
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,13 @@ var log = function log(msg, name) {
return msg;
};
/*eslint-enable */
/**
* Removes all multi-spaces with a single space + replace carriage returns with 'cr' and tabs with 't'
* @param {String} sch Text input
* @param {String} cr Carriage return replacement
* @param {String} t Tab replacement
* @return {String} Escaped text
*/
var escapeGraphQlSchema = function escapeGraphQlSchema(sch, cr, t) {
return sch.replace(/[\n\r]+/g, cr).replace(/[\t\r]+/g, t).replace(/\s+/g, ' ');
};
Expand Down Expand Up @@ -17254,57 +17261,89 @@ var propertyParamsRegEx = /\((.*?)\)/;
var carrReturnEsc = '_cr_';
var tabEsc = '_t_';

var s = null;
var _s = {};
var escapeGraphQlSchemaPlus = function escapeGraphQlSchemaPlus(sch, cr, t) {
return s || function () {
s = escapeGraphQlSchema(sch, cr, t);return s;
}
if (!sch) return sch;

/**
* Gets a first rough break down of the string schema
* @param {String} sch Original GraphQl Schema
* @return {Array} Using regex, the interfaces, types, inputs, enums and abstracts entities are isolated
* e.g. [{
* property: 'type Query { bars: [Bar]! }',
* block: [ 'bars: [Bar]!' ],
* extend: false
* },{
* property: 'type Bar { id: ID }',
* block: [ 'id: ID' ],
* extend: false
* }]
*/
();
};var typeRegex = /(extend type|type)\s(.*?){(.*?)_cr_([^#]*?)}/mg;
var inputRegex = /(extend input|input)\s(.*?){(.*?)_cr_([^#]*?)}/mg;
var enumRegex = /enum\s(.*?){(.*?)_cr_([^#]*?)}/mg;
var interfaceRegex = /(extend interface|interface)\s(.*?){(.*?)_cr_([^#]*?)}/mg;
var abstractRegex = /(extend abstract|abstract)\s(.*?){(.*?)_cr_([^#]*?)}/mg;
if (!_s[sch]) _s[sch] = escapeGraphQlSchema(sch, cr, t);

return _s[sch];
};

/**
* Gets a first rough breakdown of the string schema
* @param {String} sch Original GraphQl Schema
* @return {Array} Using regex, the interfaces, types, inputs, enums and abstracts entities are isolated
* e.g. [{
* property: 'type Query { bars: [Bar]! }',
* block: [ 'bars: [Bar]!' ],
* extend: false
* },{
* property: 'type Bar { id: ID }',
* block: [ 'id: ID' ],
* extend: false
* }]
*/
var typeRegex = { regex: /(extend type|type)\s(.*?){(.*?)_cr_([^#]*?)}/mg, type: 'type' };
var inputRegex = { regex: /(extend input|input)\s(.*?){(.*?)_cr_([^#]*?)}/mg, type: 'input' };
var enumRegex = { regex: /enum\s(.*?){(.*?)_cr_([^#]*?)}/mg, type: 'enum' };
var interfaceRegex = { regex: /(extend interface|interface)\s(.*?){(.*?)_cr_([^#]*?)}/mg, type: 'interface' };
var abstractRegex = { regex: /(extend abstract|abstract)\s(.*?){(.*?)_cr_([^#]*?)}/mg, type: 'abstract' };
var scalarRegex = { regex: /(.{1}|.{0})scalar\s(.*?)([^\s]*?)(?![a-zA-Z0-9])/mg, type: 'scalar' };
var unionRegex = { regex: /(.{1}|.{0})union([^\n]*?)\n/gm, type: 'union' };
var getSchemaBits = function getSchemaBits() {
var sch = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
return _.flatten(_.toArray(_([typeRegex, inputRegex, enumRegex, interfaceRegex, abstractRegex]).map(function (rx) {
return _.toArray(_(escapeGraphQlSchemaPlus(sch, carrReturnEsc, tabEsc).match(rx)).map(function (str) {
var blockMatch = str.match(/{(.*?)_cr_([^#]*?)}/);
if (!blockMatch) {
var msg = 'Schema error: Missing block';
log(msg);
throw new Error(msg);
}

var block = _.toArray(_(blockMatch[0].replace(/_t_/g, '').replace(/^{/, '').replace(/}$/, '').split(carrReturnEsc).map(function (x) {
return x.trim();
})).filter(function (x) {
return x != '';
}));
var rawProperty = str.split(carrReturnEsc).join(' ').split(tabEsc).join(' ').replace(/ +(?= )/g, '').trim();
var escapedSchemaWithComments = escapeGraphQlSchemaPlus(sch, carrReturnEsc, tabEsc
// We append '\n' to help isolating the 'union'
);var schemaWithoutComments = ' ' + sch.replace(/#(.*?)\n/g, '') + '\n';
var escapedSchemaWithoutComments = escapeGraphQlSchemaPlus(schemaWithoutComments, carrReturnEsc, tabEsc);
return _.flatten([typeRegex, inputRegex, enumRegex, interfaceRegex, abstractRegex, scalarRegex, unionRegex].map(function (rx) {
return chain((rx.type == 'scalar' ? escapedSchemaWithoutComments : rx.type == 'union' ? schemaWithoutComments : escapedSchemaWithComments).match(rx.regex) || []).next(function (regexMatches) {
return rx.type == 'scalar' ? regexMatches.filter(function (m) {
return m.indexOf('scalar') == 0 || m.match(/^(?![a-zA-Z0-9])/);
}) : rx.type == 'union' ? regexMatches.filter(function (m) {
return m.indexOf('union') == 0 || m.match(/^(?![a-zA-Z0-9])/);
}) : regexMatches;
}).next(function (regexMatches) {
var transform = rx.type == 'scalar' ? breakdownScalarBit : rx.type == 'union' ? breakdownUnionBit : breakdownSchemabBit;
return regexMatches.map(function (str) {
return transform(str);
});
}).val();
}));
};

var _ref = rawProperty.indexOf('extend') == 0 ? { property: rawProperty.replace('extend ', ''), extend: true } : { property: rawProperty, extend: false },
property = _ref.property,
extend = _ref.extend;
var breakdownSchemabBit = function breakdownSchemabBit(str) {
var blockMatch = str.match(/{(.*?)_cr_([^#]*?)}/);
if (!blockMatch) {
var msg = 'Schema error: Missing block';
log(msg);
throw new Error(msg);
}

return { property: property, block: block, extend: extend };
}));
})));
var block = _.toArray(_(blockMatch[0].replace(/_t_/g, '').replace(/^{/, '').replace(/}$/, '').split(carrReturnEsc).map(function (x) {
return x.trim();
})).filter(function (x) {
return x != '';
}));
var rawProperty = str.split(carrReturnEsc).join(' ').split(tabEsc).join(' ').replace(/ +(?= )/g, '').trim();

var _ref = rawProperty.indexOf('extend') == 0 ? { property: rawProperty.replace('extend ', ''), extend: true } : { property: rawProperty, extend: false },
property = _ref.property,
extend = _ref.extend;

return { property: property, block: block, extend: extend };
};

var breakdownScalarBit = function breakdownScalarBit(str) {
var block = (str.split(' ').slice(-1) || [])[0];
return { property: 'scalar ' + block, block: block, extend: false };
};

var breakdownUnionBit = function breakdownUnionBit(str) {
var block = str.replace(/(^union\s|\sunion\s|\n)/g, '').trim();
return { property: 'union ' + block, block: block, extend: false };
};

var getSchemaEntity = function getSchemaEntity(firstLine) {
Expand Down Expand Up @@ -17498,38 +17537,58 @@ var getBlockProperties = function getBlockProperties(blockParts, baseObj, metada
return _.toArray(_(definitions).filter(function (d) {
return d.property.indexOf(typeName) == 0;
}).map(function (d) {
var typeDefMatch = d.property.match(/(.*?){/);
if (!typeDefMatch || typeDefMatch[0].indexOf('#') >= 0) throw new Error('Schema error: Syntax error in \'' + d.property + '\'. Cannot any find schema type definition.');
var typeDef = typeDefMatch[0];
var nameMatch = typeDef.match(nameRegEx);
if (!nameMatch) throw new Error('Schema error: ' + typeName + ' with missing name.');
var name = nameMatch[1].trim().split(' ')[0];
var genericTypeMatch = name.match(genericTypeRegEx);
var isGenericType = genericTypeMatch ? genericTypeMatch[1] : null;
var inheritsMatch = typeDef.match(inheritsRegex);
var superClass = inheritsMatch ? inheritsMatch[0].replace('inherits ', '').replace(',', '').trim() : null;
var implementsMatch = typeDef.match(implementsRegex);
var _interface = implementsMatch ? implementsMatch[0].replace('implements ', '').replace('{', '').split(',').map(function (x) {
return x.trim().split(' ')[0];
}) : null;

var objectType = typeName.toUpperCase();
var metadat = metadata ? _(metadata).filter(function (m) {
return m.schemaType == objectType && m.schemaName == name;
}).first() || null : null;

var baseObj = { type: objectType, name: name };
var result = {
type: objectType,
extend: d.extend,
name: name,
metadata: metadat,
genericType: isGenericType,
blockProps: getBlockProperties(d.block, baseObj, metadata),
inherits: superClass,
implements: _interface
};
return result;
if (typeName == 'scalar') return {
type: 'SCALAR',
extend: false,
name: d.block,
metadata: null,
genericType: false,
blockProps: [],
inherits: null,
implements: null
};else if (typeName == 'union') return {
type: 'UNION',
extend: false,
name: d.block,
metadata: null,
genericType: false,
blockProps: [],
inherits: null,
implements: null
};else {
var typeDefMatch = d.property.match(/(.*?){/);
if (!typeDefMatch || typeDefMatch[0].indexOf('#') >= 0) throw new Error('Schema error: Syntax error in \'' + d.property + '\'. Cannot any find schema type definition.');
var typeDef = typeDefMatch[0];
var nameMatch = typeDef.match(nameRegEx);
if (!nameMatch) throw new Error('Schema error: ' + typeName + ' with missing name.');
var name = nameMatch[1].trim().split(' ')[0];
var genericTypeMatch = name.match(genericTypeRegEx);
var isGenericType = genericTypeMatch ? genericTypeMatch[1] : null;
var inheritsMatch = typeDef.match(inheritsRegex);
var superClass = inheritsMatch ? inheritsMatch[0].replace('inherits ', '').replace(',', '').trim() : null;
var implementsMatch = typeDef.match(implementsRegex);
var _interface = implementsMatch ? implementsMatch[0].replace('implements ', '').replace('{', '').split(',').map(function (x) {
return x.trim().split(' ')[0];
}) : null;

var objectType = typeName.toUpperCase();
var metadat = metadata ? _(metadata).filter(function (m) {
return m.schemaType == objectType && m.schemaName == name;
}).first() || null : null;

var baseObj = { type: objectType, name: name };
var result = {
type: objectType,
extend: d.extend,
name: name,
metadata: metadat,
genericType: isGenericType,
blockProps: getBlockProperties(d.block, baseObj, metadata),
inherits: superClass,
implements: _interface
};
return result;
}
}));
};

Expand Down Expand Up @@ -17565,6 +17624,14 @@ var getEnums = function getEnums(definitions, metadata) {
return getSchemaObject(definitions, 'enum', enumNameRegEx, metadata);
};

var getScalars = function getScalars(definitions, metadata) {
return getSchemaObject(definitions, 'scalar', null, metadata);
};

var getUnions = function getUnions(definitions, metadata) {
return getSchemaObject(definitions, 'union', null, metadata);
};

var memoizedExtendedObject = {};
var getObjWithExtensions = function getObjWithExtensions(obj, schemaObjects) {
if (obj && schemaObjects && obj.inherits) {
Expand Down Expand Up @@ -17643,9 +17710,15 @@ var addComments = function addComments(obj, comments) {

var parseSchemaObjToString = function parseSchemaObjToString(comments, type, name, _implements, blockProps) {
var extend = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
return ['' + (comments && comments != '' ? '\n' + comments : ''), '' + (extend ? 'extend ' : '') + type.toLowerCase() + ' ' + name + (_implements && _implements.length > 0 ? ' implements ' + _implements.join(', ') : '') + ' { ', blockProps.map(function (prop) {
return ['' + (comments && comments != '' ? '\n' + comments : ''), '' + (extend ? 'extend ' : '') + type.toLowerCase() + ' ' + name + (_implements && _implements.length > 0 ? ' implements ' + _implements.join(', ') : '') + ' ' + (blockProps.some(function (x) {
return x;
}) ? '{' : '') + ' ', blockProps.map(function (prop) {
return ' ' + (prop.comments != '' ? prop.comments + '\n ' : '') + prop.value;
}).join('\n'), '}'].join('\n');
}).join('\n'), blockProps.some(function (x) {
return x;
}) ? '}' : ''].filter(function (x) {
return x;
}).join('\n');
};

var isTypeGeneric = function isTypeGeneric(type, genericLetter) {
Expand Down Expand Up @@ -17715,7 +17788,7 @@ var buildSchemaString = function buildSchemaString(schemaObjs) {

var getSchemaParts = function getSchemaParts(graphQlSchema, metadata, includeNewGenTypes) {
return chain(getSchemaBits(graphQlSchema)).next(function (schemaBits) {
return _([getInterfaces, getAbstracts, getTypes, getInputs, getEnums].reduce(function (objects, getObjects) {
return _([getInterfaces, getAbstracts, getTypes, getInputs, getEnums, getScalars, getUnions].reduce(function (objects, getObjects) {
return objects.concat(getObjects(schemaBits, metadata));
}, []));
}).next(function (firstSchemaBreakDown) {
Expand All @@ -17732,7 +17805,7 @@ var getSchemaParts = function getSchemaParts(graphQlSchema, metadata, includeNew
};

var resetMemory = function resetMemory() {
s = null;
_s = {};
memoizedGenericSchemaObjects = {};
memoizedExtendedObject = {};
memoizedInterfaceWithAncestors = {};
Expand Down
2 changes: 1 addition & 1 deletion lib/graphqls2s.js.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion lib/graphqls2s.min.js

Large diffs are not rendered by default.

0 comments on commit 3bb4992

Please sign in to comment.