New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

grats

Package Overview
Dependencies
Maintainers
1
Versions
240
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

grats - npm Package Compare versions

Comparing version 0.0.25 to 0.0.26

dist/src/CodeActions.d.ts

2

dist/package.json
{
"name": "grats",
"version": "0.0.24",
"version": "0.0.25",
"main": "dist/src/index.js",

@@ -5,0 +5,0 @@ "bin": "dist/src/cli.js",

@@ -127,9 +127,9 @@ #!/usr/bin/env node

var schema = schemaAndDoc.schema, doc = schemaAndDoc.doc;
var gratsOptions = config.raw.grats;
var dest = (0, path_1.resolve)((0, path_1.dirname)(configPath), gratsOptions.tsSchema);
var code = (0, printSchema_1.printExecutableSchema)(schema, gratsOptions, dest);
var gratsConfig = config.raw.grats;
var dest = (0, path_1.resolve)((0, path_1.dirname)(configPath), gratsConfig.tsSchema);
var code = (0, printSchema_1.printExecutableSchema)(schema, gratsConfig, dest);
(0, fs_1.writeFileSync)(dest, code);
console.error("Grats: Wrote TypeScript schema to `".concat(dest, "`."));
var schemaStr = (0, printSchema_1.printGratsSDL)(doc, gratsOptions);
var absOutput = (0, path_1.resolve)((0, path_1.dirname)(configPath), gratsOptions.graphqlSchema);
var schemaStr = (0, printSchema_1.printGratsSDL)(doc, gratsConfig);
var absOutput = (0, path_1.resolve)((0, path_1.dirname)(configPath), gratsConfig.graphqlSchema);
(0, fs_1.writeFileSync)(absOutput, schemaStr);

@@ -136,0 +136,0 @@ console.error("Grats: Wrote schema to `".concat(absOutput, "`."));

import { GraphQLSchema } from "graphql";
export declare function codegen(schema: GraphQLSchema, destination: string): string;
import { GratsConfig } from "./gratsConfig.js";
export declare function codegen(schema: GraphQLSchema, config: GratsConfig, destination: string): string;

@@ -52,4 +52,4 @@ "use strict";

// GraphQLSchema implementing that schema.
function codegen(schema, destination) {
var codegen = new Codegen(schema, destination);
function codegen(schema, config, destination) {
var codegen = new Codegen(schema, config, destination);
codegen.schemaDeclarationExport();

@@ -60,3 +60,6 @@ return codegen.print();

var Codegen = /** @class */ (function () {
function Codegen(schema, destination) {
function Codegen(_schema, _config, _destination) {
this._schema = _schema;
this._config = _config;
this._destination = _destination;
this._imports = [];

@@ -67,4 +70,2 @@ this._helpers = new Map();

this._statements = [];
this._schema = schema;
this._destination = destination;
}

@@ -168,26 +169,29 @@ Codegen.prototype.createBlockWithScope = function (closure) {

var _this = this;
var metadataDirective = fieldDirective(field, metadataDirectives_1.FIELD_METADATA_DIRECTIVE);
if (metadataDirective == null) {
throw new Error("Expected to find metadata directive.");
}
var metadataDirective = (0, helpers_1.nullThrows)(fieldDirective(field, metadataDirectives_1.FIELD_METADATA_DIRECTIVE));
var metadata = (0, metadataDirectives_1.parseFieldMetadataDirective)(metadataDirective);
if (metadata.tsModulePath != null) {
var module_1 = metadata.tsModulePath;
var funcName = metadata.name;
if (funcName == null) {
throw new Error("Expected to find name in metadata directive.");
var exportName = metadata.exportName;
var argCount = (0, helpers_1.nullThrows)(metadata.argCount);
var abs = (0, gratsRoot_1.resolveRelativePath)(module_1);
var relative = replaceExt(path.relative(path.dirname(this._destination), abs), this._config.importModuleSpecifierEnding);
// Note: This name is guaranteed to be unique, but for static methods, it
// means we import the same class multiple times with multiple names.
var resolverName = formatResolverFunctionVarName(parentTypeName, field.name);
var modulePath = "./".concat(normalizeRelativePathToPosix(relative));
if (exportName == null) {
this.importDefault(modulePath, resolverName);
}
var argCount = metadata.argCount;
if (argCount == null) {
throw new Error("Expected to find argCount in metadata directive.");
else {
this.import(modulePath, [{ name: exportName, as: resolverName }]);
}
var abs = (0, gratsRoot_1.resolveRelativePath)(module_1);
var relative = stripExt(path.relative(path.dirname(this._destination), abs));
var resolverName = formatResolverFunctionVarName(parentTypeName, funcName);
this.import("./".concat(relative), [{ name: funcName, as: resolverName }]);
var usedArgs = RESOLVER_ARGS.slice(0, argCount);
var resolverAccess = F.createIdentifier(resolverName);
if (metadata.name != null) {
resolverAccess = F.createPropertyAccessExpression(resolverAccess, F.createIdentifier(metadata.name));
}
return this.method(methodName, usedArgs.map(function (name) {
return _this.param(name);
}), [
F.createReturnStatement(F.createCallExpression(F.createIdentifier(resolverName), undefined, usedArgs.map(function (name) {
F.createReturnStatement(F.createCallExpression(resolverAccess, undefined, usedArgs.map(function (name) {
return F.createIdentifier(name);

@@ -201,3 +205,3 @@ }))),

if (metadata.argCount != null) {
valueExpression = F.createCallExpression(prop, undefined, RESOLVER_ARGS.map(function (name) {
valueExpression = F.createCallExpression(prop, undefined, RESOLVER_ARGS.slice(1).map(function (name) {
return F.createIdentifier(name);

@@ -231,8 +235,5 @@ }));

if (ts.isReturnStatement(statement)) {
if (statement.expression == null) {
throw new Error("Expected return statement to have an expression");
}
foundReturn = true;
// We need to wrap the return statement in a call to the runtime check
return F.createReturnStatement(F.createCallExpression(F.createIdentifier(codegenHelpers_1.ASSERT_NON_NULL_HELPER), [], [statement.expression]));
return F.createReturnStatement(F.createCallExpression(F.createIdentifier(codegenHelpers_1.ASSERT_NON_NULL_HELPER), [], [(0, helpers_1.nullThrows)(statement.expression)]));
}

@@ -376,6 +377,2 @@ return statement;

Codegen.prototype.fieldMethods = function (field, parentTypeName) {
var metadataDirective = fieldDirective(field, metadataDirectives_1.FIELD_METADATA_DIRECTIVE);
if (metadataDirective == null) {
throw new Error("Expected to find metadata directive.");
}
// Note: We assume the default name is used here. When custom operation types are supported

@@ -549,2 +546,5 @@ // we'll need to update this.

};
Codegen.prototype.importDefault = function (from, as) {
this._imports.push(F.createImportDeclaration(undefined, F.createImportClause(false, F.createIdentifier(as), undefined), F.createStringLiteral(from)));
};
Codegen.prototype.print = function () {

@@ -562,5 +562,5 @@ var printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });

}
function stripExt(filePath) {
function replaceExt(filePath, newSuffix) {
var ext = path.extname(filePath);
return filePath.slice(0, -ext.length);
return filePath.slice(0, -ext.length) + newSuffix;
}

@@ -577,1 +577,5 @@ // Predicate function for filtering out null values

}
// https://github.com/sindresorhus/slash/blob/98b618f5a3bfcb5dd374b204868818845b87bb2f/index.js#L8C9-L8C33
function normalizeRelativePathToPosix(unknownPath) {
return unknownPath.replace(/\\/g, "/");
}

@@ -34,2 +34,3 @@ "use strict";

var E = require("./Errors");
var Act = require("./CodeActions");
var Extractor_1 = require("./Extractor");

@@ -62,7 +63,15 @@ // A line that starts with optional *s followed by @gql or @killsParentOnException

if (isLine) {
errors.push((0, DiagnosticError_1.rangeErr)(sourceFile, range, E.gqlTagInLineComment()));
errors.push((0, DiagnosticError_1.rangeErr)(sourceFile, range, E.gqlTagInLineComment(), [], {
fixName: "convert-line-comment-to-docblock-comment",
description: "Convert to a docblock comment",
changes: [Act.convertLineCommentToDocblock(sourceFile, comment)],
}));
}
else {
if (textSlice[0] !== "*") {
errors.push((0, DiagnosticError_1.rangeErr)(sourceFile, range, E.gqlTagInNonJSDocBlockComment()));
errors.push((0, DiagnosticError_1.rangeErr)(sourceFile, range, E.gqlTagInNonJSDocBlockComment(), [], {
fixName: "convert-block-comment-to-docblock-comment",
description: "Convert to a docblock comment",
changes: [Act.convertBlockCommentToDocblock(sourceFile, comment)],
}));
}

@@ -69,0 +78,0 @@ else {

@@ -27,6 +27,7 @@ export declare const ISSUE_URL = "https://github.com/captbaritone/grats/issues";

export declare function functionFieldNotTopLevel(): string;
export declare function staticMethodClassNotTopLevel(): string;
export declare function staticMethodFieldClassNotExported(): string;
export declare function functionFieldParentTypeMissing(): string;
export declare function functionFieldParentTypeNotValid(): string;
export declare function functionFieldNotNamed(): string;
export declare function functionFieldDefaultExport(): string;
export declare function functionFieldNotNamedExport(): string;

@@ -41,3 +42,7 @@ export declare function inputTypeNotLiteral(): string;

export declare function typeNameMissingInitializer(): string;
export declare function typeNameInitializeNotString(): string;
export declare function typeNameInitializeNotString(expectedName: string): string;
export declare function typeNameInitializeNotExpression(expectedName: string): string;
export declare function typeNameTypeNotReferenceNode(expectedName: string): string;
export declare function typeNameTypeNameNotIdentifier(expectedName: string): string;
export declare function typeNameTypeNameNotConst(expectedName: string): string;
export declare function typeNameInitializerWrong(expected: string, actual: string): string;

@@ -108,1 +113,5 @@ export declare function typeNameMissingTypeAnnotation(expected: string): string;

export declare function concreteTypeMissingTypename(implementor: string): string;
export declare function invalidFieldNonPublicAccessModifier(): string;
export declare function invalidStaticModifier(): string;
export declare function staticMethodOnNonClass(): string;
export declare function staticMethodClassWithNamedExportNotNamed(): string;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ambiguousNumberType = exports.expectedOneNonNullishType = exports.propertyFieldMissingType = exports.cannotResolveSymbolForDescription = exports.invalidWrapperOnInputType = exports.wrapperMissingTypeArg = exports.methodMissingType = exports.gqlEntityMissingName = exports.enumVariantMissingInitializer = exports.enumVariantNotStringLiteral = exports.enumTagOnInvalidNode = exports.argNotTyped = exports.argNameNotLiteral = exports.argIsNotProperty = exports.argumentParamIsNotObject = exports.argumentParamIsMissingType = exports.typeNameDoesNotMatchExpected = exports.typeNameTypeNotStringLiteral = exports.typeNameMissingTypeAnnotation = exports.typeNameInitializerWrong = exports.typeNameInitializeNotString = exports.typeNameMissingInitializer = exports.typeNameNotDeclaration = exports.typeTagOnAliasOfNonObjectOrUnknown = exports.typeTagOnUnnamedClass = exports.inputFieldUntyped = exports.inputInterfaceFieldNotProperty = exports.inputTypeFieldNotProperty = exports.inputTypeNotLiteral = exports.functionFieldNotNamedExport = exports.functionFieldDefaultExport = exports.functionFieldNotNamed = exports.functionFieldParentTypeNotValid = exports.functionFieldParentTypeMissing = exports.functionFieldNotTopLevel = exports.invalidReturnTypeForFunctionField = exports.invalidParentArgForFunctionField = exports.expectedUnionTypeReference = exports.expectedUnionTypeNode = exports.invalidUnionTagUsage = exports.invalidInputTagUsage = exports.invalidEnumTagUsage = exports.invalidInterfaceTagUsage = exports.invalidScalarTagUsage = exports.invalidTypeTagUsage = exports.invalidGratsTag = exports.wrongCasingForGratsTag = exports.killsParentOnExceptionOnWrongNode = exports.fieldTagOnWrongNode = exports.ISSUE_URL = void 0;
exports.concreteTypeMissingTypename = exports.genericTypeImplementsInterface = exports.genericTypeUsedAsUnionMember = exports.nonGraphQLGenericType = exports.missingGenericType = exports.specifiedByOnWrongNode = exports.missingSpecifiedByUrl = exports.gqlFieldParentMissingTag = exports.gqlFieldTagOnInputType = exports.gqlTagInDetachedJSDocBlockComment = exports.gqlTagInNonJSDocBlockComment = exports.gqlTagInLineComment = exports.expectedNullableArgumentToBeOptional = exports.operationTypeNotUnknown = exports.subscriptionFieldNotAsyncIterable = exports.graphQLTagNameHasWhitespace = exports.graphQLNameHasLeadingNewlines = exports.multipleContextTypes = exports.unexpectedParamSpreadForContextParam = exports.expectedTypeAnnotationOnContextToHaveDeclaration = exports.expectedTypeAnnotationOnContextToBeResolvable = exports.expectedTypeAnnotationOfReferenceOnContext = exports.expectedTypeAnnotationOnContext = exports.unresolvedTypeReference = exports.invalidTypePassedToFieldFunction = exports.parameterPropertyMissingType = exports.parameterPropertyNotPublic = exports.parameterWithoutModifiers = exports.duplicateInterfaceTag = exports.duplicateTag = exports.implementsTagOnTypeAlias = exports.implementsTagOnInterface = exports.implementsTagOnClass = exports.mergedInterfaces = exports.nonNullTypeCannotBeOptional = exports.killsParentOnExceptionOnNullable = exports.killsParentOnExceptionWithWrongConfig = exports.expectedNameIdentifier = exports.pluralTypeMissingParameter = exports.unknownGraphQLType = exports.unsupportedTypeLiteral = exports.defaultArgPropertyMissingInitializer = exports.defaultArgPropertyMissingName = exports.defaultArgElementIsNotAssignment = exports.defaultValueIsNotLiteral = void 0;
exports.wrapperMissingTypeArg = exports.methodMissingType = exports.gqlEntityMissingName = exports.enumVariantMissingInitializer = exports.enumVariantNotStringLiteral = exports.enumTagOnInvalidNode = exports.argNotTyped = exports.argNameNotLiteral = exports.argIsNotProperty = exports.argumentParamIsNotObject = exports.argumentParamIsMissingType = exports.typeNameDoesNotMatchExpected = exports.typeNameTypeNotStringLiteral = exports.typeNameMissingTypeAnnotation = exports.typeNameInitializerWrong = exports.typeNameTypeNameNotConst = exports.typeNameTypeNameNotIdentifier = exports.typeNameTypeNotReferenceNode = exports.typeNameInitializeNotExpression = exports.typeNameInitializeNotString = exports.typeNameMissingInitializer = exports.typeNameNotDeclaration = exports.typeTagOnAliasOfNonObjectOrUnknown = exports.typeTagOnUnnamedClass = exports.inputFieldUntyped = exports.inputInterfaceFieldNotProperty = exports.inputTypeFieldNotProperty = exports.inputTypeNotLiteral = exports.functionFieldNotNamedExport = exports.functionFieldNotNamed = exports.functionFieldParentTypeNotValid = exports.functionFieldParentTypeMissing = exports.staticMethodFieldClassNotExported = exports.staticMethodClassNotTopLevel = exports.functionFieldNotTopLevel = exports.invalidReturnTypeForFunctionField = exports.invalidParentArgForFunctionField = exports.expectedUnionTypeReference = exports.expectedUnionTypeNode = exports.invalidUnionTagUsage = exports.invalidInputTagUsage = exports.invalidEnumTagUsage = exports.invalidInterfaceTagUsage = exports.invalidScalarTagUsage = exports.invalidTypeTagUsage = exports.invalidGratsTag = exports.wrongCasingForGratsTag = exports.killsParentOnExceptionOnWrongNode = exports.fieldTagOnWrongNode = exports.ISSUE_URL = void 0;
exports.concreteTypeMissingTypename = exports.genericTypeImplementsInterface = exports.genericTypeUsedAsUnionMember = exports.nonGraphQLGenericType = exports.missingGenericType = exports.specifiedByOnWrongNode = exports.missingSpecifiedByUrl = exports.gqlFieldParentMissingTag = exports.gqlFieldTagOnInputType = exports.gqlTagInDetachedJSDocBlockComment = exports.gqlTagInNonJSDocBlockComment = exports.gqlTagInLineComment = exports.expectedNullableArgumentToBeOptional = exports.operationTypeNotUnknown = exports.subscriptionFieldNotAsyncIterable = exports.graphQLTagNameHasWhitespace = exports.graphQLNameHasLeadingNewlines = exports.multipleContextTypes = exports.unexpectedParamSpreadForContextParam = exports.expectedTypeAnnotationOnContextToHaveDeclaration = exports.expectedTypeAnnotationOnContextToBeResolvable = exports.expectedTypeAnnotationOfReferenceOnContext = exports.expectedTypeAnnotationOnContext = exports.unresolvedTypeReference = exports.invalidTypePassedToFieldFunction = exports.parameterPropertyMissingType = exports.parameterPropertyNotPublic = exports.parameterWithoutModifiers = exports.duplicateInterfaceTag = exports.duplicateTag = exports.implementsTagOnTypeAlias = exports.implementsTagOnInterface = exports.implementsTagOnClass = exports.mergedInterfaces = exports.nonNullTypeCannotBeOptional = exports.killsParentOnExceptionOnNullable = exports.killsParentOnExceptionWithWrongConfig = exports.expectedNameIdentifier = exports.pluralTypeMissingParameter = exports.unknownGraphQLType = exports.unsupportedTypeLiteral = exports.defaultArgPropertyMissingInitializer = exports.defaultArgPropertyMissingName = exports.defaultArgElementIsNotAssignment = exports.defaultValueIsNotLiteral = exports.ambiguousNumberType = exports.expectedOneNonNullishType = exports.propertyFieldMissingType = exports.cannotResolveSymbolForDescription = exports.invalidWrapperOnInputType = void 0;
exports.staticMethodClassWithNamedExportNotNamed = exports.staticMethodOnNonClass = exports.invalidStaticModifier = exports.invalidFieldNonPublicAccessModifier = void 0;
var Extractor_1 = require("./Extractor");

@@ -35,2 +36,3 @@ exports.ISSUE_URL = "https://github.com/captbaritone/grats/issues";

exports.wrongCasingForGratsTag = wrongCasingForGratsTag;
// TODO: Add code action
function invalidGratsTag(actual) {

@@ -85,2 +87,10 @@ var validTagList = Extractor_1.ALL_TAGS.map(function (t) { return "`@".concat(t, "`"); }).join(", ");

exports.functionFieldNotTopLevel = functionFieldNotTopLevel;
function staticMethodClassNotTopLevel() {
return "Expected class with a static `@".concat(Extractor_1.FIELD_TAG, "` method to be a top-level declaration. Grats needs to import resolver methods into it's generated schema module, so the resolver's class must be an exported.");
}
exports.staticMethodClassNotTopLevel = staticMethodClassNotTopLevel;
function staticMethodFieldClassNotExported() {
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` static method's class to be exported. Grats needs to import resolvers into it's generated schema module, so the resolver class must be an exported.");
}
exports.staticMethodFieldClassNotExported = staticMethodFieldClassNotExported;
var FUNCTION_PARENT_TYPE_CONTEXT = "Grats treats the first argument as the parent object of the field. Therefore Grats needs to see the _type_ of the first argument in order to know to which type/interface this field should be added.";

@@ -99,6 +109,2 @@ function functionFieldParentTypeMissing() {

exports.functionFieldNotNamed = functionFieldNotNamed;
function functionFieldDefaultExport() {
return "Expected a `@".concat(Extractor_1.FIELD_TAG, "` function to be a named export, not a default export. Grats needs to import resolver functions into it's generated schema module, so the resolver function must be a named export.");
}
exports.functionFieldDefaultExport = functionFieldDefaultExport;
function functionFieldNotNamedExport() {

@@ -132,2 +138,3 @@ return "Expected a `@".concat(Extractor_1.FIELD_TAG, "` function to be a named export. Grats needs to import resolver functions into it's generated schema module, so the resolver function must be a named export.");

exports.typeTagOnAliasOfNonObjectOrUnknown = typeTagOnAliasOfNonObjectOrUnknown;
// TODO: Add code action
function typeNameNotDeclaration() {

@@ -137,11 +144,30 @@ return "Expected `__typename` to be a property declaration. For example: `__typename: \"MyType\"`.";

exports.typeNameNotDeclaration = typeNameNotDeclaration;
var TYPENAME_CONTEXT = "This lets Grats know that the GraphQL executor will be able to derive the type of the object at runtime.";
var TYPENAME_CONTEXT = "This is needed to ensure Grats can determine the type of this object during GraphQL execution.";
function _typeNamePropertyExample(expectedName) {
return "For example: `__typename = \"".concat(expectedName, "\" as const` or `__typename: \"").concat(expectedName, "\";`.");
}
function typeNameMissingInitializer() {
return "Expected `__typename` property to have an initializer or a string literal type. For example: `__typename = \"MyType\"` or `__typename: \"MyType\";`. ".concat(TYPENAME_CONTEXT);
return "Expected `__typename` property to have an initializer or a string literal type. ".concat(TYPENAME_CONTEXT);
}
exports.typeNameMissingInitializer = typeNameMissingInitializer;
function typeNameInitializeNotString() {
return "Expected `__typename` property initializer to be a string literal. For example: `__typename = \"MyType\"` or `__typename: \"MyType\";`. ".concat(TYPENAME_CONTEXT);
function typeNameInitializeNotString(expectedName) {
return "Expected `__typename` property initializer to be a string literal. ".concat(_typeNamePropertyExample(expectedName), " ").concat(TYPENAME_CONTEXT);
}
exports.typeNameInitializeNotString = typeNameInitializeNotString;
function typeNameInitializeNotExpression(expectedName) {
return "Expected `__typename` property initializer to be an expression with a const assertion. ".concat(_typeNamePropertyExample(expectedName), " ").concat(TYPENAME_CONTEXT);
}
exports.typeNameInitializeNotExpression = typeNameInitializeNotExpression;
function typeNameTypeNotReferenceNode(expectedName) {
return "Expected `__typename` property must be correctly defined. ".concat(_typeNamePropertyExample(expectedName), " ").concat(TYPENAME_CONTEXT);
}
exports.typeNameTypeNotReferenceNode = typeNameTypeNotReferenceNode;
function typeNameTypeNameNotIdentifier(expectedName) {
return "Expected `__typename` property name must be correctly specified. ".concat(_typeNamePropertyExample(expectedName), " ").concat(TYPENAME_CONTEXT);
}
exports.typeNameTypeNameNotIdentifier = typeNameTypeNameNotIdentifier;
function typeNameTypeNameNotConst(expectedName) {
return "Expected `__typename` property type name to be \"const\". ".concat(_typeNamePropertyExample(expectedName), " ").concat(TYPENAME_CONTEXT);
}
exports.typeNameTypeNameNotConst = typeNameTypeNameNotConst;
function typeNameInitializerWrong(expected, actual) {

@@ -163,2 +189,3 @@ return "Expected `__typename` property initializer to be `\"".concat(expected, "\"`, found `\"").concat(actual, "\"`. ").concat(TYPENAME_CONTEXT);

exports.typeNameDoesNotMatchExpected = typeNameDoesNotMatchExpected;
// TODO: Add code action
function argumentParamIsMissingType() {

@@ -224,2 +251,3 @@ return "Expected GraphQL field arguments to have an explicit type annotation. If there are no arguments, you can use `args: unknown`. Grats needs to be able to see the type of the arguments to generate a GraphQL schema.";

exports.expectedOneNonNullishType = expectedOneNonNullishType;
// TODO: Add code action
function ambiguousNumberType() {

@@ -261,2 +289,3 @@ return "Unexpected number type. GraphQL supports both Int and Float, making `number` ambiguous. Instead, import the `Int` or `Float` type from `".concat(Extractor_1.LIBRARY_IMPORT_NAME, "` and use that. e.g. `import { Int, Float } from \"").concat(Extractor_1.LIBRARY_IMPORT_NAME, "\";`.");

exports.expectedNameIdentifier = expectedNameIdentifier;
// TODO: Add code action
function killsParentOnExceptionWithWrongConfig() {

@@ -266,2 +295,3 @@ return "Unexpected `@".concat(Extractor_1.KILLS_PARENT_ON_EXCEPTION_TAG, "` tag. `@").concat(Extractor_1.KILLS_PARENT_ON_EXCEPTION_TAG, "` is only supported when the Grats config option `nullableByDefault` is enabled in your `tsconfig.json`.");

exports.killsParentOnExceptionWithWrongConfig = killsParentOnExceptionWithWrongConfig;
// TODO: Add code action
function killsParentOnExceptionOnNullable() {

@@ -271,2 +301,3 @@ return "Unexpected `@".concat(Extractor_1.KILLS_PARENT_ON_EXCEPTION_TAG, "` tag on field typed as nullable. `@").concat(Extractor_1.KILLS_PARENT_ON_EXCEPTION_TAG, "` will force a field to appear as non-nullable in the schema, so it's implementation must also be non-nullable. .");

exports.killsParentOnExceptionOnNullable = killsParentOnExceptionOnNullable;
// TODO: Add code action
function nonNullTypeCannotBeOptional() {

@@ -286,2 +317,3 @@ return "Unexpected optional argument that does not also accept `null`. Optional arguments in GraphQL may get passed an explicit `null` value by the GraphQL executor. This means optional arguments must be typed to also accept `null`. Consider adding `| null` to the end of the argument type.";

exports.mergedInterfaces = mergedInterfaces;
// TODO: Add code action
function implementsTagOnClass() {

@@ -291,2 +323,3 @@ return "`@".concat(Extractor_1.IMPLEMENTS_TAG_DEPRECATED, "` has been deprecated. Instead use `class MyType implements MyInterface`.");

exports.implementsTagOnClass = implementsTagOnClass;
// TODO: Add code action
function implementsTagOnInterface() {

@@ -300,2 +333,3 @@ return "`@".concat(Extractor_1.IMPLEMENTS_TAG_DEPRECATED, "` has been deprecated. Instead use `interface MyType extends MyInterface`.");

exports.implementsTagOnTypeAlias = implementsTagOnTypeAlias;
// TODO: Add code action
function duplicateTag(tagName) {

@@ -309,2 +343,3 @@ return "Unexpected duplicate `@".concat(tagName, "` tag. Grats does not accept multiple instances of the same tag.");

exports.duplicateInterfaceTag = duplicateInterfaceTag;
// TODO: Add code action
function parameterWithoutModifiers() {

@@ -398,2 +433,3 @@ return [

exports.gqlFieldTagOnInputType = gqlFieldTagOnInputType;
// TODO: Add code action
function gqlFieldParentMissingTag() {

@@ -407,2 +443,3 @@ return "Unexpected `@".concat(Extractor_1.FIELD_TAG, "`. The parent construct must be either a `@").concat(Extractor_1.TYPE_TAG, "` or `@").concat(Extractor_1.INTERFACE_TAG, "` tag. Are you missing one of these tags?");

exports.missingSpecifiedByUrl = missingSpecifiedByUrl;
// TODO: Add code action
function specifiedByOnWrongNode() {

@@ -421,3 +458,3 @@ return "Unexpected `@".concat(Extractor_1.SPECIFIED_BY_TAG, "` tag on non-scalar declaration. `@").concat(Extractor_1.SPECIFIED_BY_TAG, "` can only be used on custom scalar declarations. Are you missing a `@").concat(Extractor_1.SCALAR_TAG, "` tag?");

function genericTypeUsedAsUnionMember() {
return "Unexpected generic type used sa union member. Generic type may not currently be used as members of a union. Grats requires that all union members define a `__typename` field typed as a string literal matching the type's name. Since generic types are synthesized into multiple types with different names, Grats cannot ensure they have a correct `__typename` property and thus cannot be used as members of a union.";
return "Unexpected generic type used as union member. Generic type may not currently be used as members of a union. Grats requires that all union members define a `__typename` field typed as a string literal matching the type's name. Since generic types are synthesized into multiple types with different names, Grats cannot ensure they have a correct `__typename` property and thus cannot be used as members of a union.";
}

@@ -433,1 +470,18 @@ exports.genericTypeUsedAsUnionMember = genericTypeUsedAsUnionMember;

exports.concreteTypeMissingTypename = concreteTypeMissingTypename;
// TODO: Add code action
function invalidFieldNonPublicAccessModifier() {
return "Unexpected access modifier on `@".concat(Extractor_1.FIELD_TAG, "` method. GraphQL fields must be able to be called by the GraphQL executor.");
}
exports.invalidFieldNonPublicAccessModifier = invalidFieldNonPublicAccessModifier;
function invalidStaticModifier() {
return "Unexpected `static` modifier on non-method `@".concat(Extractor_1.FIELD_TAG, "`. `static` is only valid on method signatures.");
}
exports.invalidStaticModifier = invalidStaticModifier;
function staticMethodOnNonClass() {
return "Unexpected `@".concat(Extractor_1.FIELD_TAG, "` `static` method on non-class declaration. Static method fields may only be declared on exported class declarations.");
}
exports.staticMethodOnNonClass = staticMethodOnNonClass;
function staticMethodClassWithNamedExportNotNamed() {
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` static method's class to be named if exported without the `default` keyword.");
}
exports.staticMethodClassWithNamedExportNotNamed = staticMethodClassWithNamedExportNotNamed;

@@ -8,2 +8,3 @@ import { ListTypeNode, NamedTypeNode, Location as GraphQLLocation, NameNode, TypeNode, NonNullTypeNode, StringValueNode, ConstValueNode, ConstDirectiveNode, ConstArgumentNode, UnionTypeDefinitionNode, FieldDefinitionNode, InputValueDefinitionNode, FloatValueNode, IntValueNode, NullValueNode, BooleanValueNode, ConstListValueNode, ConstObjectValueNode, ConstObjectFieldNode, ObjectTypeDefinitionNode, EnumValueDefinitionNode, ScalarTypeDefinitionNode, InputObjectTypeDefinitionNode, EnumTypeDefinitionNode, InterfaceTypeDefinitionNode, ASTNode, ObjectTypeExtensionNode } from "graphql";

name: string | null;
exportName: string | null;
argCount: number | null;

@@ -10,0 +11,0 @@ }): ConstDirectiveNode;

@@ -29,2 +29,5 @@ "use strict";

}
if (metadata.exportName != null) {
args.push(this.constArgument(node, this.name(node, metadataDirectives_1.EXPORT_NAME_ARG), this.string(node, metadata.exportName)));
}
if (metadata.argCount != null) {

@@ -31,0 +34,0 @@ args.push(this.constArgument(node, this.name(node, metadataDirectives_1.ARG_COUNT), this.int(node, metadata.argCount.toString())));

import * as ts from "typescript";
export type ConfigOptions = {
export type GratsConfig = {
graphqlSchema: string;

@@ -10,8 +10,9 @@ tsSchema: string;

tsSchemaHeader: string | null;
importModuleSpecifierEnding: string;
};
export type ParsedCommandLineGrats = Omit<ts.ParsedCommandLine, "raw"> & {
raw: {
grats: ConfigOptions;
grats: GratsConfig;
};
};
export declare function validateGratsOptions(options: ts.ParsedCommandLine): ParsedCommandLineGrats;

@@ -36,2 +36,3 @@ "use strict";

"tsSchemaHeader",
"importModuleSpecifierEnding",
]);

@@ -121,4 +122,10 @@ // TODO: Make this return diagnostics

}
if (gratsOptions.importModuleSpecifierEnding === undefined) {
gratsOptions.importModuleSpecifierEnding = "";
}
else if (typeof gratsOptions.importModuleSpecifierEnding !== "string") {
throw new Error("Grats: The Grats config option `importModuleSpecifierEnding` must be a string if provided.");
}
return __assign(__assign({}, options), { raw: __assign(__assign({}, options.raw), { grats: gratsOptions }) });
}
exports.validateGratsOptions = validateGratsOptions;

@@ -6,2 +6,4 @@ import { DocumentNode, GraphQLSchema } from "graphql";

import { ParsedCommandLineGrats } from "./gratsConfig";
export { initTsPlugin } from "./tsPlugin/initTsPlugin";
export { GratsConfig } from "./gratsConfig";
export type SchemaAndDoc = {

@@ -8,0 +10,0 @@ schema: GraphQLSchema;

@@ -30,3 +30,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.extractSchemaAndDoc = exports.buildSchemaAndDocResultWithHost = exports.buildSchemaAndDocResult = void 0;
exports.extractSchemaAndDoc = exports.buildSchemaAndDocResultWithHost = exports.buildSchemaAndDocResult = exports.initTsPlugin = void 0;
var graphql_1 = require("graphql");

@@ -52,2 +52,6 @@ var DiagnosticError_1 = require("./utils/DiagnosticError");

var resolveTypes_1 = require("./transforms/resolveTypes");
// Export the TypeScript plugin implementation used by
// grats-ts-plugin
var initTsPlugin_1 = require("./tsPlugin/initTsPlugin");
Object.defineProperty(exports, "initTsPlugin", { enumerable: true, get: function () { return initTsPlugin_1.initTsPlugin; } });
// Construct a schema, using GraphQL schema language

@@ -54,0 +58,0 @@ // Exported for tests that want to intercept diagnostic errors.

@@ -58,2 +58,3 @@ import { ConstDirectiveNode, DefinitionNode, DocumentNode, Location } from "graphql";

export declare const FIELD_METADATA_DIRECTIVE = "metadata";
export declare const EXPORT_NAME_ARG = "exportName";
export declare const FIELD_NAME_ARG = "name";

@@ -70,2 +71,3 @@ export declare const TS_MODULE_PATH_ARG = "tsModulePath";

name: string | null;
exportName: string | null;
argCount: number | null;

@@ -72,0 +74,0 @@ };

@@ -28,6 +28,7 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.parseFieldMetadataDirective = exports.makeKillsParentOnExceptionDirective = exports.addMetadataDirectives = exports.DIRECTIVES_AST = exports.METADATA_DIRECTIVE_NAMES = exports.KILLS_PARENT_ON_EXCEPTION_DIRECTIVE = exports.ASYNC_ITERABLE_ARG = exports.ARG_COUNT = exports.TS_MODULE_PATH_ARG = exports.FIELD_NAME_ARG = exports.FIELD_METADATA_DIRECTIVE = void 0;
exports.parseFieldMetadataDirective = exports.makeKillsParentOnExceptionDirective = exports.addMetadataDirectives = exports.DIRECTIVES_AST = exports.METADATA_DIRECTIVE_NAMES = exports.KILLS_PARENT_ON_EXCEPTION_DIRECTIVE = exports.ASYNC_ITERABLE_ARG = exports.ARG_COUNT = exports.TS_MODULE_PATH_ARG = exports.FIELD_NAME_ARG = exports.EXPORT_NAME_ARG = exports.FIELD_METADATA_DIRECTIVE = void 0;
var graphql_1 = require("graphql");
var helpers_1 = require("./utils/helpers");
exports.FIELD_METADATA_DIRECTIVE = "metadata";
exports.EXPORT_NAME_ARG = "exportName";
exports.FIELD_NAME_ARG = "name";

@@ -42,3 +43,3 @@ exports.TS_MODULE_PATH_ARG = "tsModulePath";

]);
exports.DIRECTIVES_AST = (0, graphql_1.parse)("\n directive @".concat(exports.FIELD_METADATA_DIRECTIVE, "(\n \"\"\"\n Name of property/method/function. Defaults to field name. For\n function-backed fields, this is the function's export name.\n \"\"\"\n ").concat(exports.FIELD_NAME_ARG, ": String\n \"\"\"\n Path of the TypeScript module to import if the field is a function.\n \"\"\"\n ").concat(exports.TS_MODULE_PATH_ARG, ": String\n \"\"\"\n Number of arguments. No value means property access\n \"\"\"\n ").concat(exports.ARG_COUNT, ": Int\n ) on FIELD_DEFINITION\n directive @").concat(exports.KILLS_PARENT_ON_EXCEPTION_DIRECTIVE, " on FIELD_DEFINITION\n"));
exports.DIRECTIVES_AST = (0, graphql_1.parse)("\n directive @".concat(exports.FIELD_METADATA_DIRECTIVE, "(\n \"\"\"\n Name of property/method/function. Defaults to field name.\n \"\"\"\n ").concat(exports.FIELD_NAME_ARG, ": String\n \"\"\"\n Path of the TypeScript module to import if the field is a function.\n \"\"\"\n ").concat(exports.TS_MODULE_PATH_ARG, ": String\n \"\"\"\n Export name of the field. For function fields this is the exported function name,\n for static method fields, this is the exported class name.\n \"\"\"\n ").concat(exports.EXPORT_NAME_ARG, ": String\n \"\"\"\n Number of arguments. No value means property access\n \"\"\"\n ").concat(exports.ARG_COUNT, ": Int\n ) on FIELD_DEFINITION\n directive @").concat(exports.KILLS_PARENT_ON_EXCEPTION_DIRECTIVE, " on FIELD_DEFINITION\n"));
function addMetadataDirectives(definitions) {

@@ -69,2 +70,3 @@ return __spreadArray(__spreadArray([], __read(exports.DIRECTIVES_AST.definitions), false), __read(definitions), false);

tsModulePath: getStringArg(directive, exports.TS_MODULE_PATH_ARG),
exportName: getStringArg(directive, exports.EXPORT_NAME_ARG),
argCount: getIntArg(directive, exports.ARG_COUNT),

@@ -71,0 +73,0 @@ };

import { DocumentNode, GraphQLSchema } from "graphql";
import { ConfigOptions } from "./gratsConfig";
import { GratsConfig } from "./gratsConfig";
/**

@@ -7,4 +7,4 @@ * Prints code for a TypeScript module that exports a GraphQLSchema.

*/
export declare function printExecutableSchema(schema: GraphQLSchema, config: ConfigOptions, destination: string): string;
export declare function applyTypeScriptHeader(config: ConfigOptions, code: string): string;
export declare function printExecutableSchema(schema: GraphQLSchema, config: GratsConfig, destination: string): string;
export declare function applyTypeScriptHeader(config: GratsConfig, code: string): string;
/**

@@ -14,4 +14,4 @@ * Prints SDL, potentially omitting directives depending upon the config.

*/
export declare function printGratsSDL(doc: DocumentNode, config: ConfigOptions): string;
export declare function applySDLHeader(config: ConfigOptions, sdl: string): string;
export declare function printGratsSDL(doc: DocumentNode, config: GratsConfig): string;
export declare function applySDLHeader(config: GratsConfig, sdl: string): string;
export declare function printSDLWithoutMetadata(doc: DocumentNode): string;

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

function printExecutableSchema(schema, config, destination) {
var code = (0, codegen_1.codegen)(schema, destination);
var code = (0, codegen_1.codegen)(schema, config, destination);
return applyTypeScriptHeader(config, code);

@@ -15,0 +15,0 @@ }

import { DocumentNode } from "graphql";
import { DiagnosticsResult } from "../utils/DiagnosticError";
import { ConfigOptions } from "../gratsConfig";
import { GratsConfig } from "../gratsConfig";
/**

@@ -8,2 +8,2 @@ * Grats has options to make all fields nullable by default to conform to

*/
export declare function applyDefaultNullability(doc: DocumentNode, { nullableByDefault, strictSemanticNullability }: ConfigOptions): DiagnosticsResult<DocumentNode>;
export declare function applyDefaultNullability(doc: DocumentNode, { nullableByDefault, strictSemanticNullability }: GratsConfig): DiagnosticsResult<DocumentNode>;

@@ -400,4 +400,4 @@ "use strict";

function renameDefinition(original, newName, loc) {
var name = __assign(__assign({}, original.name), { value: newName });
var name = __assign(__assign({}, original.name), { value: newName, loc: loc });
return __assign(__assign({}, original), { loc: loc, name: name, wasSynthesized: true });
}

@@ -41,2 +41,4 @@ "use strict";

var Extractor_1 = require("../Extractor");
var DiagnosticError_1 = require("../utils/DiagnosticError");
var helpers_1 = require("../utils/helpers");
// An experimental plugin for TypeScript that adds a new language service

@@ -89,2 +91,32 @@ // which reports diagnostics for the current file. Currently it only reports

};
proxy.getSupportedCodeFixes = function (fileName) {
info.project.projectService.logger.info("Grats: getSupportedCodeFixes called with ".concat(fileName));
return __spreadArray(__spreadArray([], __read(info.languageService.getSupportedCodeFixes(fileName)), false), [
String(DiagnosticError_1.FAKE_ERROR_CODE),
], false);
};
proxy.getCodeFixesAtPosition = function (fileName, start, end, errorCodes, formatOptions, preferences) {
var _a;
info.project.projectService.logger.info("Grats: getCodeFixesAtPosition called with ".concat(fileName, " and ").concat(errorCodes));
var prior = info.languageService.getCodeFixesAtPosition(fileName, start, end, errorCodes, formatOptions, preferences);
var doc = (_a = info.languageService.getProgram()) === null || _a === void 0 ? void 0 : _a.getSourceFile(fileName);
if (doc == null)
return prior;
var result = (0, Extractor_1.extract)(doc);
if (result.kind === "OK")
return prior;
info.project.projectService.logger.info("Grats: getCodeFixesAtPosition got ".concat(result.err.length, " errors in ").concat(fileName));
var relatedDiagnostics = result.err.filter(function (err) {
return (err.fix != null &&
err.start === start &&
err.length === end - start &&
err.file.fileName === doc.fileName &&
errorCodes.includes(err.code));
});
info.project.projectService.logger.info("Grats: getCodeFixesAtPosition matched ".concat(relatedDiagnostics.length, " errors in ").concat(fileName));
var fixes = relatedDiagnostics.map(function (err) {
return (0, helpers_1.nullThrows)(err.fix);
});
return __spreadArray(__spreadArray([], __read(prior), false), __read(fixes), false);
};
return proxy;

@@ -91,0 +123,0 @@ }

import { GraphQLError, Location, Source } from "graphql";
import * as ts from "typescript";
import { Result } from "./Result";
export type DiagnosticResult<T> = Result<T, ts.DiagnosticWithLocation>;
export type DiagnosticsResult<T> = Result<T, ts.DiagnosticWithLocation[]>;
type FixableDiagnostic = ts.Diagnostic & {
fix?: ts.CodeFixAction;
};
export type FixableDiagnosticWithLocation = ts.DiagnosticWithLocation & {
fix?: ts.CodeFixAction;
};
export type DiagnosticResult<T> = Result<T, FixableDiagnosticWithLocation>;
export type DiagnosticsResult<T> = Result<T, FixableDiagnosticWithLocation[]>;
export type DiagnosticsWithoutLocationResult<T> = Result<T, ts.Diagnostic[]>;
export declare class ReportableDiagnostics {
_host: ts.FormatDiagnosticsHost;
_diagnostics: ts.Diagnostic[];
constructor(host: ts.FormatDiagnosticsHost, diagnostics: ts.Diagnostic[]);
_diagnostics: FixableDiagnostic[];
constructor(host: ts.FormatDiagnosticsHost, diagnostics: FixableDiagnostic[]);
static fromDiagnostics(diagnostics: ts.Diagnostic[]): ReportableDiagnostics;

@@ -15,7 +21,7 @@ formatDiagnosticsWithColorAndContext(): string;

}
export declare const FAKE_ERROR_CODE = 349389149282;
export declare const FAKE_ERROR_CODE = 1038;
export declare function graphQlErrorToDiagnostic(error: GraphQLError): ts.Diagnostic;
export declare function gqlErr(loc: Location, message: string, relatedInformation?: ts.DiagnosticRelatedInformation[]): ts.DiagnosticWithLocation;
export declare function gqlRelated(loc: Location, message: string): ts.DiagnosticRelatedInformation;
export declare function rangeErr(file: ts.SourceFile, commentRange: ts.CommentRange, message: string, relatedInformation?: ts.DiagnosticRelatedInformation[]): ts.DiagnosticWithLocation;
export declare function rangeErr(file: ts.SourceFile, commentRange: ts.CommentRange, message: string, relatedInformation?: ts.DiagnosticRelatedInformation[], fix?: ts.CodeFixAction): FixableDiagnosticWithLocation;
/**

@@ -33,4 +39,5 @@ * A generic version of the methods on ts.Node that we need

}
export declare function tsErr(node: TsLocatableNode, message: string, relatedInformation?: ts.DiagnosticRelatedInformation[]): ts.DiagnosticWithLocation;
export declare function tsErr(node: TsLocatableNode, message: string, relatedInformation?: ts.DiagnosticRelatedInformation[], fix?: ts.CodeFixAction): FixableDiagnosticWithLocation;
export declare function tsRelated(node: ts.Node, message: string): ts.DiagnosticRelatedInformation;
export declare function graphqlSourceToSourceFile(source: Source): ts.SourceFile;
export {};

@@ -62,3 +62,3 @@ "use strict";

// We pick a very random number to avoid collisions with real error messages.
exports.FAKE_ERROR_CODE = 349389149282;
exports.FAKE_ERROR_CODE = 1038;
function stripColor(str) {

@@ -149,3 +149,3 @@ // eslint-disable-next-line no-control-regex

exports.gqlRelated = gqlRelated;
function rangeErr(file, commentRange, message, relatedInformation) {
function rangeErr(file, commentRange, message, relatedInformation, fix) {
var start = commentRange.pos;

@@ -162,6 +162,7 @@ var length = commentRange.end - commentRange.pos;

source: "Grats",
fix: fix,
};
}
exports.rangeErr = rangeErr;
function tsErr(node, message, relatedInformation) {
function tsErr(node, message, relatedInformation, fix) {
var start = node.getStart();

@@ -179,2 +180,3 @@ var length = node.getEnd() - start;

source: "Grats",
fix: fix,
};

@@ -181,0 +183,0 @@ }

import { GraphQLSchema } from "graphql";
import { DiagnosticsWithoutLocationResult } from "../utils/DiagnosticError";
import { ConfigOptions } from "../gratsConfig";
import { GratsConfig } from "../gratsConfig";
/**

@@ -8,2 +8,2 @@ * Ensure that all semantically non-nullable fields on an interface are also

*/
export declare function validateSemanticNullability(schema: GraphQLSchema, config: ConfigOptions): DiagnosticsWithoutLocationResult<GraphQLSchema>;
export declare function validateSemanticNullability(schema: GraphQLSchema, config: GratsConfig): DiagnosticsWithoutLocationResult<GraphQLSchema>;
{
"name": "grats",
"version": "0.0.25",
"version": "0.0.26",
"main": "dist/src/index.js",

@@ -5,0 +5,0 @@ "bin": "dist/src/cli.js",

@@ -7,3 +7,3 @@ # Grats: Implementation-First GraphQL for TypeScript

**What if building a GraphQL server were as simple as just writing functions?**
**The simplest way to build a GraphQL server in TypeScript**

@@ -19,2 +19,4 @@ When you write your GraphQL server in TypeScript, your fields and resolvers

Read the [blog post](https://jordaneldredge.com/blog/grats).
## Example

@@ -21,0 +23,0 @@

Sorry, the diff of this file is too big to display

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