Socket
Socket
Sign inDemoInstall

graphql-import

Package Overview
Dependencies
Maintainers
1
Versions
431
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

graphql-import - npm Package Compare versions

Comparing version 0.1.5 to 0.1.6

11

dist/definition.d.ts

@@ -5,2 +5,11 @@ import { TypeDefinitionNode } from 'graphql';

}
export declare function completeDefinitionPool(allDefinitions: TypeDefinitionNode[], defintionPool: TypeDefinitionNode[], newTypeDefinitions: TypeDefinitionNode[], schemaPath: string): TypeDefinitionNode[];
/**
* Post processing of all imported type definitions. Loops over each of the
* imported type definitions, and processes it using collectNewTypeDefinitions.
*
* @param allDefinitions All definitions from all schemas
* @param definitionPool Current definitions (from first schema)
* @param newTypeDefinitions All imported definitions
* @returns Final collection of type definitions for the resulting schema
*/
export declare function completeDefinitionPool(allDefinitions: TypeDefinitionNode[], definitionPool: TypeDefinitionNode[], newTypeDefinitions: TypeDefinitionNode[]): TypeDefinitionNode[];

50

dist/definition.js

@@ -5,3 +5,12 @@ "use strict";

var builtinTypes = ['String', 'Float', 'Int', 'Boolean', 'ID'];
function completeDefinitionPool(allDefinitions, defintionPool, newTypeDefinitions, schemaPath) {
/**
* Post processing of all imported type definitions. Loops over each of the
* imported type definitions, and processes it using collectNewTypeDefinitions.
*
* @param allDefinitions All definitions from all schemas
* @param definitionPool Current definitions (from first schema)
* @param newTypeDefinitions All imported definitions
* @returns Final collection of type definitions for the resulting schema
*/
function completeDefinitionPool(allDefinitions, definitionPool, newTypeDefinitions) {
var visitedDefinitions = {};

@@ -14,11 +23,24 @@ while (newTypeDefinitions.length > 0) {

}
var collectedTypedDefinitions = collectNewTypeDefinitions(allDefinitions, defintionPool, newDefinition, schemaMap, schemaPath);
var collectedTypedDefinitions = collectNewTypeDefinitions(allDefinitions, definitionPool, newDefinition, schemaMap);
newTypeDefinitions.push.apply(newTypeDefinitions, collectedTypedDefinitions);
defintionPool.push.apply(defintionPool, collectedTypedDefinitions);
definitionPool.push.apply(definitionPool, collectedTypedDefinitions);
visitedDefinitions[newDefinition.name.value] = true;
}
return lodash_1.uniqBy(defintionPool, 'name.value');
return lodash_1.uniqBy(definitionPool, 'name.value');
}
exports.completeDefinitionPool = completeDefinitionPool;
function collectNewTypeDefinitions(allDefinitions, definitionPool, newDefinition, schemaMap, schemaPath) {
/**
* Processes a single type definition, and performs a number of checks:
* - Add missing interface implementations
* - Add missing referenced types
* - Remove unused type definitions
*
* @param allDefinitions All definitions from all schemas
* (only used to find missing interface implementations)
* @param definitionPool Resulting definitions
* @param newDefinition All imported definitions
* @param schemaMap Map of all definitions for easy lookup
* @returns All relevant type definitions to add to the final schema
*/
function collectNewTypeDefinitions(allDefinitions, definitionPool, newDefinition, schemaMap) {
var newTypeDefinitions = [];

@@ -34,3 +56,3 @@ if (newDefinition.kind === 'InputObjectTypeDefinition') {

if (!argTypeMatch) {
throw new Error("Field " + field.name.value + ": Couldn't find type " + typeName + " in " + schemaPath + ".");
throw new Error("Field " + field.name.value + ": Couldn't find type " + typeName + " in any of the schemas.");
}

@@ -50,3 +72,3 @@ newTypeDefinitions.push(argTypeMatch);

if (!schemaType) {
throw new Error("Field " + field.name.value + ": Couldn't find type " + typeName + " in " + schemaPath + ".");
throw new Error("Field " + field.name.value + ": Couldn't find type " + typeName + " in any of the schemas.");
}

@@ -68,3 +90,3 @@ newTypeDefinitions.push(schemaType);

if (!typeMatch) {
throw new Error("Couldn't find type " + typeName + " in " + schemaPath + ".");
throw new Error("Couldn't find type " + typeName + " in any of the schemas.");
}

@@ -82,3 +104,3 @@ newTypeDefinitions.push(schemaMap[type.name.value]);

if (!interfaceMatch) {
throw new Error("Couldn't find interface " + interfaceName + " in " + schemaPath + ".");
throw new Error("Couldn't find interface " + interfaceName + " in any of the schemas.");
}

@@ -100,3 +122,3 @@ newTypeDefinitions.push(schemaMap[int.name.value]);

if (!argTypeMatch) {
throw new Error("Field " + field.name.value + ": Couldn't find type " + argTypeName + " in " + schemaPath + ".");
throw new Error("Field " + field.name.value + ": Couldn't find type " + argTypeName + " in any of the schemas.");
}

@@ -111,3 +133,3 @@ newTypeDefinitions.push(argTypeMatch);

if (!schemaType) {
throw new Error("Field " + field.name.value + ": Couldn't find type " + typeName + " in " + schemaPath + ".");
throw new Error("Field " + field.name.value + ": Couldn't find type " + typeName + " in any of the schemas.");
}

@@ -120,2 +142,8 @@ newTypeDefinitions.push(schemaType);

}
/**
* Nested visitor for a type node to get to the final NamedType
*
* @param {TypeNode} type Type node to get NamedTypeNode for
* @returns {NamedTypeNode} The found NamedTypeNode
*/
function getNamedType(type) {

@@ -122,0 +150,0 @@ if (type.kind === 'NamedType') {

@@ -1,2 +0,5 @@

import { TypeDefinitionNode } from 'graphql';
/**
* Describes the information from a single import line
*
*/
export interface RawModule {

@@ -6,5 +9,22 @@ imports: string[];

}
/**
* Parse a single import line and extract imported types and schema filename
*
* @param importLine Import line
* @returns Processed import line
*/
export declare function parseImportLine(importLine: string): RawModule;
/**
* Parse a schema and analyze all import lines
*
* @param sdl Schema to parse
* @returns Array with collection of imports per import line (file)
*/
export declare function parseSDL(sdl: string): RawModule[];
/**
* Main entry point. Recursively process all import statement in a schema
*
* @param filePath File path to the initial schema file
* @returns Single bundled schema with all imported types
*/
export declare function importSchema(filePath: string): string;
export declare function collectDefinitions(imports: string[], sdl: string, filePath: string): TypeDefinitionNode[];
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var fs = require("fs");
var graphql_1 = require("graphql");
var lodash_1 = require("lodash");
var fs = require("fs");
var path = require("path");
var definition_1 = require("./definition");
/**
* Read a schema file from disk
*
* @param f Filename
* @returns File contents
*/
var read = function (f) { return fs.readFileSync(f, { encoding: 'utf8' }); };
/**
* Parse a single import line and extract imported types and schema filename
*
* @param importLine Import line
* @returns Processed import line
*/
function parseImportLine(importLine) {
// Apply regex to import line
var matches = importLine.match(/^import (\*|(.*)) from ('|")(.*)('|")$/);

@@ -14,7 +27,16 @@ if (matches.length !== 6) {

}
// Extract matches into named variables
var wildcard = matches[1], importsString = matches[2], from = matches[4];
// Extract imported types
var imports = wildcard === '*' ? ['*'] : importsString.split(',').map(function (d) { return d.trim(); });
// Return information about the import line
return { imports: imports, from: from };
}
exports.parseImportLine = parseImportLine;
/**
* Parse a schema and analyze all import lines
*
* @param sdl Schema to parse
* @returns Array with collection of imports per import line (file)
*/
function parseSDL(sdl) {

@@ -29,35 +51,84 @@ return sdl

exports.parseSDL = parseSDL;
/**
* Main entry point. Recursively process all import statement in a schema
*
* @param filePath File path to the initial schema file
* @returns Single bundled schema with all imported types
*/
function importSchema(filePath) {
var sdl = read(filePath);
var document = graphql_1.parse(sdl);
var allDefinitions = collectDefinitions(['*'], sdl, path.resolve(filePath));
document.definitions = allDefinitions;
var document = graphql_1.parse(sdl, { noLocation: true });
// Recursively process the imports, starting by importing all types from the initial schema
var _a = collectDefinitions(['*'], sdl, path.resolve(filePath)), allDefinitions = _a.allDefinitions, typeDefinitions = _a.typeDefinitions;
// Post processing of the final schema (missing types, unused types, etc.)
document.definitions = definition_1.completeDefinitionPool(lodash_1.flatten(allDefinitions), typeDefinitions[0], lodash_1.flatten(typeDefinitions));
// Return the schema as string
return graphql_1.print(document);
}
exports.importSchema = importSchema;
function collectDefinitions(imports, sdl, filePath) {
/**
* Recursively process all schema files. Keeps track of both the filtered
* type definitions, and all type definitions, because they might be needed
* in post-processing (to add missing types)
*
* @param imports Types specified in the import statement
* @param sdl Current schema
* @param filePath File location for current schema
* @param Tracking of processed schemas (for circular dependencies)
* @param Tracking of imported type definitions per schema
* @param Tracking of all type definitions per schema
* @returns Both the collection of all type definitions, and the collection of imported type definitions
*/
function collectDefinitions(imports, sdl, filePath, processedFiles, typeDefinitions, allDefinitions) {
if (processedFiles === void 0) { processedFiles = new Set(); }
if (typeDefinitions === void 0) { typeDefinitions = []; }
if (allDefinitions === void 0) { allDefinitions = []; }
var key = path.basename(filePath);
var dirname = path.dirname(filePath);
// Get TypeDefinitionNodes from current schema
var document = graphql_1.parse(sdl);
// Add all definitions to running total
allDefinitions.push(filterTypeDefinitions(document.definitions));
// Filter TypeDefinitionNodes by type and defined imports
var currentTypeDefinitions = filterImportedDefinitions(imports, document.definitions);
// Add typedefinitions to running total
typeDefinitions.push(currentTypeDefinitions);
// Mark file as processed (for circular dependency cases)
processedFiles.add(key);
// Read imports from current file
var rawModules = parseSDL(sdl);
var document = graphql_1.parse(sdl);
var currentTypeDefinitions = filterTypeDefinitions(document.definitions);
var importedTypeDefinitions = lodash_1.flatten(rawModules.map(function (m) {
var moduleFilePath = path.resolve(path.join(dirname, m.from));
return collectDefinitions(m.imports, read(moduleFilePath), moduleFilePath);
}));
var typeDefinitions = currentTypeDefinitions.concat(importedTypeDefinitions);
var filteredTypeDefinitions = importDefinitions(imports, typeDefinitions, filePath);
return definition_1.completeDefinitionPool(typeDefinitions, filteredTypeDefinitions.slice(0), filteredTypeDefinitions.slice(0), filePath);
// Process each file (recursively)
rawModules.forEach(function (m) {
// If it was not yet processed (in case of circular dependencies)
if (!processedFiles.has(path.basename(m.from))) {
var moduleFilePath = path.resolve(path.join(dirname, m.from));
collectDefinitions(m.imports, read(moduleFilePath), moduleFilePath, processedFiles, typeDefinitions, allDefinitions);
}
});
// Return the maps of type definitions from each file
return { allDefinitions: allDefinitions, typeDefinitions: typeDefinitions };
}
exports.collectDefinitions = collectDefinitions;
function importDefinitions(imports, typeDefinitions, schemaPath) {
/**
* Filter the types loaded from a schema, first by relevant types,
* then by the types specified in the import statement.
*
* @param imports Types specified in the import statement
* @param typeDefinitions All definitions from a schema
* @returns Filtered collection of type definitions
*/
function filterImportedDefinitions(imports, typeDefinitions) {
var filteredDefinitions = filterTypeDefinitions(typeDefinitions);
if (imports.includes('*')) {
return typeDefinitions;
return filteredDefinitions;
}
else {
var importedDefinitions = typeDefinitions.filter(function (d) {
return imports.includes(d.name.value);
});
return definition_1.completeDefinitionPool(typeDefinitions, importedDefinitions.slice(0), importedDefinitions.slice(0), schemaPath);
return filteredDefinitions.filter(function (d) { return imports.includes(d.name.value); });
}
}
/**
* Filter relevant definitions from schema
*
* @param definitions All definitions from a schema
* @returns Relevant type definitions
*/
function filterTypeDefinitions(definitions) {

@@ -70,3 +141,3 @@ var validKinds = [

'UnionTypeDefinition',
'InputObjectTypeDefinition',
'InputObjectTypeDefinition'
];

@@ -73,0 +144,0 @@ return definitions

@@ -79,2 +79,12 @@ "use strict";

});
ava_1.default('circular imports', function (t) {
var expectedSDL = "type A {\n first: String @first\n second: Float\n b: B\n}\n\ntype B {\n hello: String!\n c1: C1\n c2: C2\n a: A\n}\n\ntype C1 {\n id: ID!\n}\n\ntype C2 {\n id: ID!\n}\n";
var actualSDL = _1.importSchema('fixtures/circular/a.graphql');
t.is(actualSDL, expectedSDL);
});
ava_1.default('related types', function (t) {
var expectedSDL = "type A {\n first: String @first\n second: Float\n b: B\n}\n\ntype B {\n hello: String!\n c1: C\n}\n\ntype C {\n field: String\n}\n";
var actualSDL = _1.importSchema('fixtures/related-types/a.graphql');
t.is(actualSDL, expectedSDL);
});
//# sourceMappingURL=index.test.js.map
{
"name": "graphql-import",
"version": "0.1.5",
"version": "0.1.6",
"license": "MIT",

@@ -18,3 +18,5 @@ "repository": "git@github.com:graphcool/graphql-import.git",

"test-only": "npm run build && ava --verbose dist/**/*.test.js",
"test": "tslint src/**/*.ts && npm run test-only"
"test": "tslint src/**/*.ts && npm run test-only",
"docs": "typedoc --out docs src/index.ts --hideGenerator --exclude **/*.test.ts",
"docs:publish": "cp ./now.json ./docs && cd docs && now --public -f && now alias && now rm --yes --safe graphql-import & cd .."
},

@@ -26,6 +28,7 @@ "devDependencies": {

"tslint-config-standard": "^7.0.0",
"typedoc": "^0.9.0",
"typescript": "^2.6.1"
},
"dependencies": {
"@types/graphql": "^0.11.6",
"@types/graphql": "0.11.7",
"@types/lodash": "^4.14.85",

@@ -32,0 +35,0 @@ "graphql": "^0.11.7",

@@ -87,2 +87,6 @@ # graphql-import [![Build Status](https://travis-ci.org/graphcool/graphql-import.svg?branch=master)](https://travis-ci.org/graphcool/graphql-import) [![npm version](https://badge.fury.io/js/graphql-import.svg)](https://badge.fury.io/js/graphql-import) [![Greenkeeper badge](https://badges.greenkeeper.io/graphcool/graphql-import.svg)](https://greenkeeper.io/)

## Development
The [implemenentation documentation](https://graphql-import.now.sh/) documents how things are implemented under the hood. You can also use the VSCode test setup to debug your code/tests.
## Related topics & next steps

@@ -89,0 +93,0 @@

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