Comparing version 0.0.0-main-957a70fd to 0.0.0-main-958caaeb
{ | ||
"name": "grats", | ||
"version": "0.0.25", | ||
"version": "0.0.32", | ||
"main": "dist/src/index.js", | ||
@@ -21,7 +21,7 @@ "bin": "dist/src/cli.js", | ||
"commander": "^10.0.0", | ||
"graphql": "^16.6.0", | ||
"typescript": "^5.0.2" | ||
"graphql": "^16.9.0", | ||
"typescript": "5.5.4", | ||
"semver": "^7.5.4" | ||
}, | ||
"devDependencies": { | ||
"@graphql-tools/utils": "^9.2.1", | ||
"@types/node": "^18.14.6", | ||
@@ -37,3 +37,2 @@ "@types/semver": "^7.5.6", | ||
"process": "^0.11.10", | ||
"semver": "^7.5.4", | ||
"ts-node": "^10.9.1" | ||
@@ -46,4 +45,3 @@ }, | ||
"engines": { | ||
"node": ">=16 <=21", | ||
"pnpm": "^8" | ||
"node": ">=16 <=21" | ||
}, | ||
@@ -50,0 +48,0 @@ "bugs": { |
@@ -40,3 +40,5 @@ #!/usr/bin/env node | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.formatLoc = void 0; | ||
exports.formatLoc = formatLoc; | ||
var E = require("./Errors"); | ||
var graphql_1 = require("graphql"); | ||
var _1 = require("./"); | ||
@@ -52,2 +54,3 @@ var lib_1 = require("./lib"); | ||
var DiagnosticError_1 = require("./utils/DiagnosticError"); | ||
var Result_1 = require("./utils/Result"); | ||
var program = new commander_1.Command(); | ||
@@ -60,16 +63,14 @@ program | ||
.option("--watch", "Watch for changes and rebuild schema files as needed") | ||
.action(function (_a) { | ||
var tsconfig = _a.tsconfig, watch = _a.watch; | ||
return __awaiter(void 0, void 0, void 0, function () { | ||
return __generator(this, function (_b) { | ||
if (watch) { | ||
startWatchMode(tsconfig); | ||
} | ||
else { | ||
runBuild(tsconfig); | ||
} | ||
return [2 /*return*/]; | ||
}); | ||
.action(function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) { | ||
var tsconfig = _b.tsconfig, watch = _b.watch; | ||
return __generator(this, function (_c) { | ||
if (watch) { | ||
startWatchMode(tsconfig); | ||
} | ||
else { | ||
runBuild(tsconfig); | ||
} | ||
return [2 /*return*/]; | ||
}); | ||
}); | ||
}); }); | ||
program | ||
@@ -81,9 +82,4 @@ .command("locate") | ||
var tsconfig = _a.tsconfig; | ||
var config = getTsConfigOrReportAndExit(tsconfig).config; | ||
var schemaAndDocResult = (0, lib_1.buildSchemaAndDocResult)(config); | ||
if (schemaAndDocResult.kind === "ERROR") { | ||
console.error(schemaAndDocResult.err.formatDiagnosticsWithColorAndContext()); | ||
process.exit(1); | ||
} | ||
var schema = schemaAndDocResult.value.schema; | ||
var config = handleDiagnostics(getTsConfig(tsconfig)).config; | ||
var schema = handleDiagnostics(buildSchemaAndDocResultForCli(config)).schema; | ||
var loc = (0, Locate_1.locate)(schema, entity); | ||
@@ -101,3 +97,3 @@ if (loc.kind === "ERROR") { | ||
function startWatchMode(tsconfig) { | ||
var _a = getTsConfigOrReportAndExit(tsconfig), config = _a.config, configPath = _a.configPath; | ||
var _a = handleDiagnostics(getTsConfig(tsconfig)), config = _a.config, configPath = _a.configPath; | ||
var watchHost = ts.createWatchCompilerHost(configPath, {}, ts.sys, ts.createSemanticDiagnosticsBuilderProgram, function (diagnostic) { return reportDiagnostics([diagnostic]); }, function (diagnostic) { return reportDiagnostics([diagnostic]); }); | ||
@@ -115,13 +111,29 @@ watchHost.afterProgramCreate = function (program) { | ||
} | ||
function isUserDefinedType(type) { | ||
return type instanceof graphql_1.GraphQLObjectType && !type.name.startsWith("__"); | ||
} | ||
/** | ||
* Like `buildSchemaAndDocResult` but applies a few additional validations that | ||
* are considered helpful for CLI usage, like warning if you have no types defined.. | ||
*/ | ||
function buildSchemaAndDocResultForCli(config) { | ||
var result = (0, lib_1.buildSchemaAndDocResult)(config); | ||
if (result.kind === "ERROR") { | ||
return result; | ||
} | ||
var types = Object.values(result.value.schema.getTypeMap()); | ||
if (!types.some(function (t) { return isUserDefinedType(t); })) { | ||
return (0, Result_1.err)(DiagnosticError_1.ReportableDiagnostics.fromDiagnostics([ | ||
(0, DiagnosticError_1.locationlessErr)(E.noTypesDefined()), | ||
])); | ||
} | ||
return result; | ||
} | ||
/** | ||
* Run the compiler performing a single build. | ||
*/ | ||
function runBuild(tsconfig) { | ||
var _a = getTsConfigOrReportAndExit(tsconfig), config = _a.config, configPath = _a.configPath; | ||
var schemaAndDocResult = (0, lib_1.buildSchemaAndDocResult)(config); | ||
if (schemaAndDocResult.kind === "ERROR") { | ||
console.error(schemaAndDocResult.err.formatDiagnosticsWithColorAndContext()); | ||
process.exit(1); | ||
} | ||
writeSchemaFilesAndReport(schemaAndDocResult.value, config, configPath); | ||
var _a = handleDiagnostics(getTsConfig(tsconfig)), config = _a.config, configPath = _a.configPath; | ||
var schemaAndDoc = handleDiagnostics(buildSchemaAndDocResultForCli(config)); | ||
writeSchemaFilesAndReport(schemaAndDoc, config, configPath); | ||
} | ||
@@ -132,12 +144,17 @@ /** | ||
function writeSchemaFilesAndReport(schemaAndDoc, config, configPath) { | ||
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 schema = schemaAndDoc.schema, doc = schemaAndDoc.doc, resolvers = schemaAndDoc.resolvers; | ||
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, resolvers, 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); | ||
console.error("Grats: Wrote schema to `".concat(absOutput, "`.")); | ||
if (config.raw.grats.EXPERIMENTAL__emitMetadata) { | ||
var absOutput_1 = (0, path_1.resolve)((0, path_1.dirname)(configPath), gratsConfig.graphqlSchema.replace(/\.graphql$/, ".json")); | ||
(0, fs_1.writeFileSync)(absOutput_1, JSON.stringify(resolvers, null, 2)); | ||
console.error("Grats: Wrote resolver signatures to `".concat(absOutput_1, "`.")); | ||
} | ||
} | ||
@@ -151,14 +168,26 @@ /** | ||
} | ||
/** | ||
* Utility function to report diagnostics to the console. | ||
*/ | ||
function handleDiagnostics(result) { | ||
if (result.kind === "ERROR") { | ||
console.error(result.err.formatDiagnosticsWithColorAndContext()); | ||
process.exit(1); | ||
} | ||
return result.value; | ||
} | ||
// Locate and read the tsconfig.json file | ||
function getTsConfigOrReportAndExit(tsconfig) { | ||
var configPath = tsconfig || ts.findConfigFile(process.cwd(), ts.sys.fileExists); | ||
function getTsConfig(tsconfig) { | ||
var cwd = process.cwd(); | ||
var configPath = tsconfig || ts.findConfigFile(cwd, ts.sys.fileExists); | ||
if (configPath == null) { | ||
throw new Error("Grats: Could not find tsconfig.json"); | ||
return (0, Result_1.err)(DiagnosticError_1.ReportableDiagnostics.fromDiagnostics([ | ||
(0, DiagnosticError_1.locationlessErr)(E.tsConfigNotFound(cwd)), | ||
])); | ||
} | ||
var optionsResult = (0, _1.getParsedTsConfig)(configPath); | ||
if (optionsResult.kind === "ERROR") { | ||
console.error(optionsResult.err.formatDiagnosticsWithColorAndContext()); | ||
process.exit(1); | ||
return (0, Result_1.err)(optionsResult.err); | ||
} | ||
return { configPath: configPath, config: optionsResult.value }; | ||
return (0, Result_1.ok)({ configPath: configPath, config: optionsResult.value }); | ||
} | ||
@@ -170,2 +199,1 @@ // Format a location for printing to the console. Tools like VS Code and iTerm | ||
} | ||
exports.formatLoc = formatLoc; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.createAssertNonNullHelper = exports.ASSERT_NON_NULL_HELPER = void 0; | ||
exports.ASSERT_NON_NULL_HELPER = void 0; | ||
exports.createAssertNonNullHelper = createAssertNonNullHelper; | ||
var ts = require("typescript"); | ||
@@ -34,2 +35,1 @@ exports.ASSERT_NON_NULL_HELPER = "assertNonNull"; | ||
} | ||
exports.createAssertNonNullHelper = createAssertNonNullHelper; |
@@ -30,6 +30,8 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.forEachComment = exports.detectInvalidComments = void 0; | ||
exports.detectInvalidComments = detectInvalidComments; | ||
exports.forEachComment = forEachComment; | ||
var ts = require("typescript"); | ||
var DiagnosticError_1 = require("./utils/DiagnosticError"); | ||
var E = require("./Errors"); | ||
var Act = require("./CodeActions"); | ||
var Extractor_1 = require("./Extractor"); | ||
@@ -62,7 +64,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)], | ||
})); | ||
} | ||
@@ -85,3 +95,2 @@ else { | ||
} | ||
exports.detectInvalidComments = detectInvalidComments; | ||
// Extract @gql or @killsParentOnException tags from a JSDoc block comment. | ||
@@ -149,3 +158,2 @@ // along with their positions. | ||
} | ||
exports.forEachComment = forEachComment; | ||
function forEachToken(sourceFile, callback) { | ||
@@ -152,0 +160,0 @@ var queue = []; |
@@ -13,2 +13,3 @@ export declare const ISSUE_URL = "https://github.com/captbaritone/grats/issues"; | ||
export declare function fieldTagOnWrongNode(): string; | ||
export declare function rootFieldTagOnWrongNode(typeName: string): string; | ||
export declare function killsParentOnExceptionOnWrongNode(): string; | ||
@@ -42,3 +43,7 @@ export declare function wrongCasingForGratsTag(actual: string, expected: string): 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; | ||
@@ -48,4 +53,4 @@ export declare function typeNameMissingTypeAnnotation(expected: string): string; | ||
export declare function typeNameDoesNotMatchExpected(expected: string): string; | ||
export declare function argumentParamIsMissingType(): string; | ||
export declare function argumentParamIsNotObject(): string; | ||
export declare function resolverParamIsMissingType(): string; | ||
export declare function multipleResolverTypeLiterals(): string; | ||
export declare function argIsNotProperty(): string; | ||
@@ -91,3 +96,6 @@ export declare function argNameNotLiteral(): string; | ||
export declare function expectedTypeAnnotationOnContextToHaveDeclaration(): string; | ||
export declare function unexpectedParamSpreadForContextParam(): string; | ||
export declare function unexpectedParamSpreadForResolverParam(): string; | ||
export declare function resolverParamIsUnknown(): string; | ||
export declare function resolverParamIsNever(): string; | ||
export declare function unexpectedResolverParamType(): string; | ||
export declare function multipleContextTypes(): string; | ||
@@ -104,4 +112,2 @@ export declare function graphQLNameHasLeadingNewlines(name: string, tagName: string): string; | ||
export declare function gqlFieldParentMissingTag(): string; | ||
export declare function missingSpecifiedByUrl(): string; | ||
export declare function specifiedByOnWrongNode(): string; | ||
export declare function missingGenericType(templateName: string, paramName: string): string; | ||
@@ -111,3 +117,4 @@ export declare function nonGraphQLGenericType(templateName: string, paramName: string): string; | ||
export declare function genericTypeImplementsInterface(): string; | ||
export declare function concreteTypeMissingTypename(implementor: string): string; | ||
export declare function concreteTypenameImplementingInterfaceCannotBeResolved(implementor: string, interfaceName: string): string; | ||
export declare function concreteTypenameInUnionCannotBeResolved(implementor: string, unionName: string): string; | ||
export declare function invalidFieldNonPublicAccessModifier(): string; | ||
@@ -117,1 +124,29 @@ export declare function invalidStaticModifier(): string; | ||
export declare function staticMethodClassWithNamedExportNotNamed(): string; | ||
export declare function oneOfNotSupportedGraphql(requiredVersion: string, foundVersion: string): string; | ||
export declare function oneOfNotOnUnion(): string; | ||
export declare function oneOfFieldNotTypeLiteralWithOneProperty(): string; | ||
export declare function oneOfPropertyMissingTypeAnnotation(): string; | ||
export declare function contextTagOnNonDeclaration(): string; | ||
export declare function duplicateContextTag(): string; | ||
export declare function userDefinedInfoTag(): string; | ||
export declare function invalidResolverParamType(): string; | ||
export declare function exportedArrowFunctionNotConst(): string; | ||
export declare function exportedFieldVariableMultipleDeclarations(n: number): string; | ||
export declare function fieldVariableNotTopLevelExported(): string; | ||
export declare function fieldVariableIsNotArrowFunction(): string; | ||
export declare function positionalResolverArgDoesNotHaveName(): string; | ||
export declare function positionalArgAndArgsObject(): string; | ||
export declare function contextOrInfoUsedInGraphQLPosition(kind: "CONTEXT" | "INFO"): string; | ||
export declare function typeWithNoFields(kind: string, typeName: string): string; | ||
export declare function noTypesDefined(): string; | ||
export declare function tsConfigNotFound(cwd: string): string; | ||
export declare function cyclicDerivedContext(): string; | ||
export declare function invalidDerivedContextArgType(): string; | ||
export declare function missingReturnTypeForDerivedResolver(): string; | ||
export declare function derivedResolverInvalidReturnType(): string; | ||
export declare function directiveTagOnWrongNode(): string; | ||
export declare function directiveTagCommentNotText(): string; | ||
export declare function specifiedByDeprecated(): string; | ||
export declare function directiveTagNoComment(): string; | ||
export declare function directiveFunctionNotNamed(): string; | ||
export declare function directiveArgumentNotObject(): string; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
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.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.staticMethodClassWithNamedExportNotNamed = exports.staticMethodOnNonClass = exports.invalidStaticModifier = exports.invalidFieldNonPublicAccessModifier = 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 = void 0; | ||
exports.ISSUE_URL = void 0; | ||
exports.fieldTagOnWrongNode = fieldTagOnWrongNode; | ||
exports.rootFieldTagOnWrongNode = rootFieldTagOnWrongNode; | ||
exports.killsParentOnExceptionOnWrongNode = killsParentOnExceptionOnWrongNode; | ||
exports.wrongCasingForGratsTag = wrongCasingForGratsTag; | ||
exports.invalidGratsTag = invalidGratsTag; | ||
exports.invalidTypeTagUsage = invalidTypeTagUsage; | ||
exports.invalidScalarTagUsage = invalidScalarTagUsage; | ||
exports.invalidInterfaceTagUsage = invalidInterfaceTagUsage; | ||
exports.invalidEnumTagUsage = invalidEnumTagUsage; | ||
exports.invalidInputTagUsage = invalidInputTagUsage; | ||
exports.invalidUnionTagUsage = invalidUnionTagUsage; | ||
exports.expectedUnionTypeNode = expectedUnionTypeNode; | ||
exports.expectedUnionTypeReference = expectedUnionTypeReference; | ||
exports.invalidParentArgForFunctionField = invalidParentArgForFunctionField; | ||
exports.invalidReturnTypeForFunctionField = invalidReturnTypeForFunctionField; | ||
exports.functionFieldNotTopLevel = functionFieldNotTopLevel; | ||
exports.staticMethodClassNotTopLevel = staticMethodClassNotTopLevel; | ||
exports.staticMethodFieldClassNotExported = staticMethodFieldClassNotExported; | ||
exports.functionFieldParentTypeMissing = functionFieldParentTypeMissing; | ||
exports.functionFieldParentTypeNotValid = functionFieldParentTypeNotValid; | ||
exports.functionFieldNotNamed = functionFieldNotNamed; | ||
exports.functionFieldNotNamedExport = functionFieldNotNamedExport; | ||
exports.inputTypeNotLiteral = inputTypeNotLiteral; | ||
exports.inputTypeFieldNotProperty = inputTypeFieldNotProperty; | ||
exports.inputInterfaceFieldNotProperty = inputInterfaceFieldNotProperty; | ||
exports.inputFieldUntyped = inputFieldUntyped; | ||
exports.typeTagOnUnnamedClass = typeTagOnUnnamedClass; | ||
exports.typeTagOnAliasOfNonObjectOrUnknown = typeTagOnAliasOfNonObjectOrUnknown; | ||
exports.typeNameNotDeclaration = typeNameNotDeclaration; | ||
exports.typeNameMissingInitializer = typeNameMissingInitializer; | ||
exports.typeNameInitializeNotString = typeNameInitializeNotString; | ||
exports.typeNameInitializeNotExpression = typeNameInitializeNotExpression; | ||
exports.typeNameTypeNotReferenceNode = typeNameTypeNotReferenceNode; | ||
exports.typeNameTypeNameNotIdentifier = typeNameTypeNameNotIdentifier; | ||
exports.typeNameTypeNameNotConst = typeNameTypeNameNotConst; | ||
exports.typeNameInitializerWrong = typeNameInitializerWrong; | ||
exports.typeNameMissingTypeAnnotation = typeNameMissingTypeAnnotation; | ||
exports.typeNameTypeNotStringLiteral = typeNameTypeNotStringLiteral; | ||
exports.typeNameDoesNotMatchExpected = typeNameDoesNotMatchExpected; | ||
exports.resolverParamIsMissingType = resolverParamIsMissingType; | ||
exports.multipleResolverTypeLiterals = multipleResolverTypeLiterals; | ||
exports.argIsNotProperty = argIsNotProperty; | ||
exports.argNameNotLiteral = argNameNotLiteral; | ||
exports.argNotTyped = argNotTyped; | ||
exports.enumTagOnInvalidNode = enumTagOnInvalidNode; | ||
exports.enumVariantNotStringLiteral = enumVariantNotStringLiteral; | ||
exports.enumVariantMissingInitializer = enumVariantMissingInitializer; | ||
exports.gqlEntityMissingName = gqlEntityMissingName; | ||
exports.methodMissingType = methodMissingType; | ||
exports.wrapperMissingTypeArg = wrapperMissingTypeArg; | ||
exports.invalidWrapperOnInputType = invalidWrapperOnInputType; | ||
exports.cannotResolveSymbolForDescription = cannotResolveSymbolForDescription; | ||
exports.propertyFieldMissingType = propertyFieldMissingType; | ||
exports.expectedOneNonNullishType = expectedOneNonNullishType; | ||
exports.ambiguousNumberType = ambiguousNumberType; | ||
exports.defaultValueIsNotLiteral = defaultValueIsNotLiteral; | ||
exports.defaultArgElementIsNotAssignment = defaultArgElementIsNotAssignment; | ||
exports.defaultArgPropertyMissingName = defaultArgPropertyMissingName; | ||
exports.defaultArgPropertyMissingInitializer = defaultArgPropertyMissingInitializer; | ||
exports.unsupportedTypeLiteral = unsupportedTypeLiteral; | ||
exports.unknownGraphQLType = unknownGraphQLType; | ||
exports.pluralTypeMissingParameter = pluralTypeMissingParameter; | ||
exports.expectedNameIdentifier = expectedNameIdentifier; | ||
exports.killsParentOnExceptionWithWrongConfig = killsParentOnExceptionWithWrongConfig; | ||
exports.killsParentOnExceptionOnNullable = killsParentOnExceptionOnNullable; | ||
exports.nonNullTypeCannotBeOptional = nonNullTypeCannotBeOptional; | ||
exports.mergedInterfaces = mergedInterfaces; | ||
exports.implementsTagOnClass = implementsTagOnClass; | ||
exports.implementsTagOnInterface = implementsTagOnInterface; | ||
exports.implementsTagOnTypeAlias = implementsTagOnTypeAlias; | ||
exports.duplicateTag = duplicateTag; | ||
exports.duplicateInterfaceTag = duplicateInterfaceTag; | ||
exports.parameterWithoutModifiers = parameterWithoutModifiers; | ||
exports.parameterPropertyNotPublic = parameterPropertyNotPublic; | ||
exports.parameterPropertyMissingType = parameterPropertyMissingType; | ||
exports.invalidTypePassedToFieldFunction = invalidTypePassedToFieldFunction; | ||
exports.unresolvedTypeReference = unresolvedTypeReference; | ||
exports.expectedTypeAnnotationOnContext = expectedTypeAnnotationOnContext; | ||
exports.expectedTypeAnnotationOfReferenceOnContext = expectedTypeAnnotationOfReferenceOnContext; | ||
exports.expectedTypeAnnotationOnContextToBeResolvable = expectedTypeAnnotationOnContextToBeResolvable; | ||
exports.expectedTypeAnnotationOnContextToHaveDeclaration = expectedTypeAnnotationOnContextToHaveDeclaration; | ||
exports.unexpectedParamSpreadForResolverParam = unexpectedParamSpreadForResolverParam; | ||
exports.resolverParamIsUnknown = resolverParamIsUnknown; | ||
exports.resolverParamIsNever = resolverParamIsNever; | ||
exports.unexpectedResolverParamType = unexpectedResolverParamType; | ||
exports.multipleContextTypes = multipleContextTypes; | ||
exports.graphQLNameHasLeadingNewlines = graphQLNameHasLeadingNewlines; | ||
exports.graphQLTagNameHasWhitespace = graphQLTagNameHasWhitespace; | ||
exports.subscriptionFieldNotAsyncIterable = subscriptionFieldNotAsyncIterable; | ||
exports.operationTypeNotUnknown = operationTypeNotUnknown; | ||
exports.expectedNullableArgumentToBeOptional = expectedNullableArgumentToBeOptional; | ||
exports.gqlTagInLineComment = gqlTagInLineComment; | ||
exports.gqlTagInNonJSDocBlockComment = gqlTagInNonJSDocBlockComment; | ||
exports.gqlTagInDetachedJSDocBlockComment = gqlTagInDetachedJSDocBlockComment; | ||
exports.gqlFieldTagOnInputType = gqlFieldTagOnInputType; | ||
exports.gqlFieldParentMissingTag = gqlFieldParentMissingTag; | ||
exports.missingGenericType = missingGenericType; | ||
exports.nonGraphQLGenericType = nonGraphQLGenericType; | ||
exports.genericTypeUsedAsUnionMember = genericTypeUsedAsUnionMember; | ||
exports.genericTypeImplementsInterface = genericTypeImplementsInterface; | ||
exports.concreteTypenameImplementingInterfaceCannotBeResolved = concreteTypenameImplementingInterfaceCannotBeResolved; | ||
exports.concreteTypenameInUnionCannotBeResolved = concreteTypenameInUnionCannotBeResolved; | ||
exports.invalidFieldNonPublicAccessModifier = invalidFieldNonPublicAccessModifier; | ||
exports.invalidStaticModifier = invalidStaticModifier; | ||
exports.staticMethodOnNonClass = staticMethodOnNonClass; | ||
exports.staticMethodClassWithNamedExportNotNamed = staticMethodClassWithNamedExportNotNamed; | ||
exports.oneOfNotSupportedGraphql = oneOfNotSupportedGraphql; | ||
exports.oneOfNotOnUnion = oneOfNotOnUnion; | ||
exports.oneOfFieldNotTypeLiteralWithOneProperty = oneOfFieldNotTypeLiteralWithOneProperty; | ||
exports.oneOfPropertyMissingTypeAnnotation = oneOfPropertyMissingTypeAnnotation; | ||
exports.contextTagOnNonDeclaration = contextTagOnNonDeclaration; | ||
exports.duplicateContextTag = duplicateContextTag; | ||
exports.userDefinedInfoTag = userDefinedInfoTag; | ||
exports.invalidResolverParamType = invalidResolverParamType; | ||
exports.exportedArrowFunctionNotConst = exportedArrowFunctionNotConst; | ||
exports.exportedFieldVariableMultipleDeclarations = exportedFieldVariableMultipleDeclarations; | ||
exports.fieldVariableNotTopLevelExported = fieldVariableNotTopLevelExported; | ||
exports.fieldVariableIsNotArrowFunction = fieldVariableIsNotArrowFunction; | ||
exports.positionalResolverArgDoesNotHaveName = positionalResolverArgDoesNotHaveName; | ||
exports.positionalArgAndArgsObject = positionalArgAndArgsObject; | ||
exports.contextOrInfoUsedInGraphQLPosition = contextOrInfoUsedInGraphQLPosition; | ||
exports.typeWithNoFields = typeWithNoFields; | ||
exports.noTypesDefined = noTypesDefined; | ||
exports.tsConfigNotFound = tsConfigNotFound; | ||
exports.cyclicDerivedContext = cyclicDerivedContext; | ||
exports.invalidDerivedContextArgType = invalidDerivedContextArgType; | ||
exports.missingReturnTypeForDerivedResolver = missingReturnTypeForDerivedResolver; | ||
exports.derivedResolverInvalidReturnType = derivedResolverInvalidReturnType; | ||
exports.directiveTagOnWrongNode = directiveTagOnWrongNode; | ||
exports.directiveTagCommentNotText = directiveTagCommentNotText; | ||
exports.specifiedByDeprecated = specifiedByDeprecated; | ||
exports.directiveTagNoComment = directiveTagNoComment; | ||
exports.directiveFunctionNotNamed = directiveFunctionNotNamed; | ||
exports.directiveArgumentNotObject = directiveArgumentNotObject; | ||
var Extractor_1 = require("./Extractor"); | ||
@@ -24,13 +157,14 @@ exports.ISSUE_URL = "https://github.com/captbaritone/grats/issues"; | ||
function fieldTagOnWrongNode() { | ||
return "`@".concat(Extractor_1.FIELD_TAG, "` can only be used on method/property declarations, signatures, or function declarations."); | ||
return "`@".concat(Extractor_1.FIELD_TAG, "` can only be used on method/property declarations, signatures, function or static method declarations."); | ||
} | ||
exports.fieldTagOnWrongNode = fieldTagOnWrongNode; | ||
function rootFieldTagOnWrongNode(typeName) { | ||
return "`@gql".concat(typeName, "Field` can only be used on function or static method declarations."); | ||
} | ||
function killsParentOnExceptionOnWrongNode() { | ||
return "Unexpected `@".concat(Extractor_1.KILLS_PARENT_ON_EXCEPTION_TAG, "`. `@").concat(Extractor_1.KILLS_PARENT_ON_EXCEPTION_TAG, "` can only be used in field annotation docblocks. Perhaps you are missing a `@").concat(Extractor_1.FIELD_TAG, "` tag?"); | ||
} | ||
exports.killsParentOnExceptionOnWrongNode = killsParentOnExceptionOnWrongNode; | ||
function wrongCasingForGratsTag(actual, expected) { | ||
return "Incorrect casing for Grats tag `@".concat(actual, "`. Use `@").concat(expected, "` instead."); | ||
} | ||
exports.wrongCasingForGratsTag = wrongCasingForGratsTag; | ||
// TODO: Add code action | ||
function invalidGratsTag(actual) { | ||
@@ -40,55 +174,41 @@ var validTagList = Extractor_1.ALL_TAGS.map(function (t) { return "`@".concat(t, "`"); }).join(", "); | ||
} | ||
exports.invalidGratsTag = invalidGratsTag; | ||
function invalidTypeTagUsage() { | ||
return "`@".concat(Extractor_1.TYPE_TAG, "` can only be used on class, interface or type declarations. e.g. `class MyType {}`"); | ||
} | ||
exports.invalidTypeTagUsage = invalidTypeTagUsage; | ||
function invalidScalarTagUsage() { | ||
return "`@".concat(Extractor_1.SCALAR_TAG, "` can only be used on type alias declarations. e.g. `type MyScalar = string`"); | ||
} | ||
exports.invalidScalarTagUsage = invalidScalarTagUsage; | ||
function invalidInterfaceTagUsage() { | ||
return "`@".concat(Extractor_1.INTERFACE_TAG, "` can only be used on interface declarations. e.g. `interface MyInterface {}`"); | ||
} | ||
exports.invalidInterfaceTagUsage = invalidInterfaceTagUsage; | ||
function invalidEnumTagUsage() { | ||
return "`@".concat(Extractor_1.ENUM_TAG, "` can only be used on enum declarations or TypeScript unions. e.g. `enum MyEnum {}` or `type MyEnum = \"foo\" | \"bar\"`"); | ||
} | ||
exports.invalidEnumTagUsage = invalidEnumTagUsage; | ||
function invalidInputTagUsage() { | ||
return "`@".concat(Extractor_1.INPUT_TAG, "` can only be used on type alias or interface declarations. e.g. `type MyInput = { foo: string }` or `interface MyInput { foo: string }`"); | ||
return "`@".concat(Extractor_1.INPUT_TAG, "` can only be used on type alias, interface declarations or type unions. e.g. `type MyInput = { foo: string }` or `interface MyInput { foo: string }`"); | ||
} | ||
exports.invalidInputTagUsage = invalidInputTagUsage; | ||
function invalidUnionTagUsage() { | ||
return "`@".concat(Extractor_1.UNION_TAG, "` can only be used on type alias declarations. e.g. `type MyUnion = TypeA | TypeB`"); | ||
} | ||
exports.invalidUnionTagUsage = invalidUnionTagUsage; | ||
function expectedUnionTypeNode() { | ||
return "Expected a TypeScript union. `@".concat(Extractor_1.UNION_TAG, "` can only be used on TypeScript unions. e.g. `type MyUnion = TypeA | TypeB`"); | ||
} | ||
exports.expectedUnionTypeNode = expectedUnionTypeNode; | ||
function expectedUnionTypeReference() { | ||
return "Expected `@".concat(Extractor_1.UNION_TAG, "` union members to be type references. Grats expects union members to be references to something annotated with `@gqlType`."); | ||
} | ||
exports.expectedUnionTypeReference = expectedUnionTypeReference; | ||
function invalidParentArgForFunctionField() { | ||
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` function to have a first argument representing the type to extend. If you don't need access to the parent object in the function, you can name the variable `_` to indicate that it is unused. e.g. `function myField(_: ParentType) {}`"); | ||
} | ||
exports.invalidParentArgForFunctionField = invalidParentArgForFunctionField; | ||
function invalidReturnTypeForFunctionField() { | ||
return 'Expected GraphQL field to have an explicit return type. This is needed to allow Grats to "see" the type of the field.'; | ||
} | ||
exports.invalidReturnTypeForFunctionField = invalidReturnTypeForFunctionField; | ||
function functionFieldNotTopLevel() { | ||
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` function to be a top-level declaration. Grats needs to import resolver functions into it's generated schema module, so the resolver function must be an exported."); | ||
} | ||
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."; | ||
@@ -98,176 +218,152 @@ function functionFieldParentTypeMissing() { | ||
} | ||
exports.functionFieldParentTypeMissing = functionFieldParentTypeMissing; | ||
function functionFieldParentTypeNotValid() { | ||
return "Expected first argument of a `@".concat(Extractor_1.FIELD_TAG, "` function to be typed as a type reference. ").concat(FUNCTION_PARENT_TYPE_CONTEXT); | ||
} | ||
exports.functionFieldParentTypeNotValid = functionFieldParentTypeNotValid; | ||
function functionFieldNotNamed() { | ||
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` function to be named. Grats uses the name of the function to derive the name of the GraphQL field. Additionally, Grats needs to import resolver functions into it's generated schema module, so the resolver function must be a named export."); | ||
} | ||
exports.functionFieldNotNamed = functionFieldNotNamed; | ||
function functionFieldNotNamedExport() { | ||
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.functionFieldNotNamedExport = functionFieldNotNamedExport; | ||
function inputTypeNotLiteral() { | ||
return "`@".concat(Extractor_1.INPUT_TAG, "` can only be used on type literals. e.g. `type MyInput = { foo: string }`"); | ||
} | ||
exports.inputTypeNotLiteral = inputTypeNotLiteral; | ||
function inputTypeFieldNotProperty() { | ||
return "`@".concat(Extractor_1.INPUT_TAG, "` types only support property signature members. e.g. `type MyInput = { foo: string }`"); | ||
} | ||
exports.inputTypeFieldNotProperty = inputTypeFieldNotProperty; | ||
function inputInterfaceFieldNotProperty() { | ||
return "`@".concat(Extractor_1.INPUT_TAG, "` interfaces only support property signature members. e.g. `interface MyInput { foo: string }`"); | ||
} | ||
exports.inputInterfaceFieldNotProperty = inputInterfaceFieldNotProperty; | ||
function inputFieldUntyped() { | ||
return 'Input field must have an explicit type annotation. Grats uses the type annotation to determine the type of the field, so it must be explicit in order for Grats to "see" the type.'; | ||
} | ||
exports.inputFieldUntyped = inputFieldUntyped; | ||
function typeTagOnUnnamedClass() { | ||
return "Unexpected `@".concat(Extractor_1.TYPE_TAG, "` annotation on unnamed class declaration. Grats uses the name of the class to derive the name of the GraphQL type. Consider naming the class."); | ||
} | ||
exports.typeTagOnUnnamedClass = typeTagOnUnnamedClass; | ||
function typeTagOnAliasOfNonObjectOrUnknown() { | ||
return "Expected `@".concat(Extractor_1.TYPE_TAG, "` type to be an object type literal (`{ }`) or `unknown`. For example: `type Foo = { bar: string }` or `type Query = unknown`."); | ||
} | ||
exports.typeTagOnAliasOfNonObjectOrUnknown = typeTagOnAliasOfNonObjectOrUnknown; | ||
// TODO: Add code action | ||
function typeNameNotDeclaration() { | ||
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); | ||
} | ||
function typeNameTypeNotReferenceNode(expectedName) { | ||
return "Expected `__typename` property must be correctly defined. ".concat(_typeNamePropertyExample(expectedName), " ").concat(TYPENAME_CONTEXT); | ||
} | ||
function typeNameTypeNameNotIdentifier(expectedName) { | ||
return "Expected `__typename` property name must be correctly specified. ".concat(_typeNamePropertyExample(expectedName), " ").concat(TYPENAME_CONTEXT); | ||
} | ||
function typeNameTypeNameNotConst(expectedName) { | ||
return "Expected `__typename` property type name to be \"const\". ".concat(_typeNamePropertyExample(expectedName), " ").concat(TYPENAME_CONTEXT); | ||
} | ||
function typeNameInitializerWrong(expected, actual) { | ||
return "Expected `__typename` property initializer to be `\"".concat(expected, "\"`, found `\"").concat(actual, "\"`. ").concat(TYPENAME_CONTEXT); | ||
} | ||
exports.typeNameInitializerWrong = typeNameInitializerWrong; | ||
function typeNameMissingTypeAnnotation(expected) { | ||
return "Expected `__typename` property signature to specify the typename as a string literal string type. For example `__typename: \"".concat(expected, "\";`. ").concat(TYPENAME_CONTEXT); | ||
} | ||
exports.typeNameMissingTypeAnnotation = typeNameMissingTypeAnnotation; | ||
function typeNameTypeNotStringLiteral(expected) { | ||
return "Expected `__typename` property signature to specify the typename as a string literal string type. For example `__typename: \"".concat(expected, "\";`. ").concat(TYPENAME_CONTEXT); | ||
} | ||
exports.typeNameTypeNotStringLiteral = typeNameTypeNotStringLiteral; | ||
function typeNameDoesNotMatchExpected(expected) { | ||
return "Expected `__typename` property to be `\"".concat(expected, "\"`. ").concat(TYPENAME_CONTEXT); | ||
} | ||
exports.typeNameDoesNotMatchExpected = typeNameDoesNotMatchExpected; | ||
function argumentParamIsMissingType() { | ||
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."; | ||
function resolverParamIsMissingType() { | ||
return "Missing type annotation for resolver argument. Expected all resolver arguments to have an explicit type annotation. Grats needs to be able to see the type of the arguments to generate an executable GraphQL schema."; | ||
} | ||
exports.argumentParamIsMissingType = argumentParamIsMissingType; | ||
function argumentParamIsNotObject() { | ||
return "Expected GraphQL field arguments to be typed using an inline literal object: `{someField: string}`. 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."; | ||
function multipleResolverTypeLiterals() { | ||
return "Unexpected multiple resolver parameters typed with an object literal. Grats assumes a resolver parameter typed with object literals describes the GraphQL arguments. Therefore only one such parameter is permitted."; | ||
} | ||
exports.argumentParamIsNotObject = argumentParamIsNotObject; | ||
function argIsNotProperty() { | ||
return "Expected GraphQL field argument type to be a property signature. For example: `{ someField: string }`. Grats needs to be able to see the type of the arguments to generate a GraphQL schema."; | ||
} | ||
exports.argIsNotProperty = argIsNotProperty; | ||
function argNameNotLiteral() { | ||
return "Expected GraphQL field argument names to be a literal. For example: `{ someField: string }`. Grats needs to be able to see the type of the arguments to generate a GraphQL schema."; | ||
} | ||
exports.argNameNotLiteral = argNameNotLiteral; | ||
function argNotTyped() { | ||
return "Expected GraphQL field argument to have an explicit type annotation. For example: `{ someField: string }`. Grats needs to be able to see the type of the arguments to generate a GraphQL schema."; | ||
} | ||
exports.argNotTyped = argNotTyped; | ||
function enumTagOnInvalidNode() { | ||
return "Expected `@".concat(Extractor_1.ENUM_TAG, "` to be a union type, or a string literal in the edge case of a single value enum. For example: `type MyEnum = \"foo\" | \"bar\"` or `type MyEnum = \"foo\"`."); | ||
} | ||
exports.enumTagOnInvalidNode = enumTagOnInvalidNode; | ||
function enumVariantNotStringLiteral() { | ||
return "Expected `@".concat(Extractor_1.ENUM_TAG, "` enum members to be string literal types. For example: `'foo'`. Grats needs to be able to see the concrete value of the enum member to generate the GraphQL schema."); | ||
} | ||
exports.enumVariantNotStringLiteral = enumVariantNotStringLiteral; | ||
function enumVariantMissingInitializer() { | ||
return "Expected `@".concat(Extractor_1.ENUM_TAG, "` enum members to have string literal initializers. For example: `FOO = 'foo'`. In GraphQL enum values are strings, and Grats needs to be able to see the concrete value of the enum member to generate the GraphQL schema."); | ||
} | ||
exports.enumVariantMissingInitializer = enumVariantMissingInitializer; | ||
function gqlEntityMissingName() { | ||
return "Expected GraphQL entity to have a name. Grats uses the name of the entity to derive the name of the GraphQL construct."; | ||
} | ||
exports.gqlEntityMissingName = gqlEntityMissingName; | ||
function methodMissingType() { | ||
return "Expected GraphQL field methods to have an explicitly defined return type. Grats needs to be able to see the type of the field to generate its type in the GraphQL schema."; | ||
} | ||
exports.methodMissingType = methodMissingType; | ||
function wrapperMissingTypeArg() { | ||
return "Expected wrapper type reference to have type arguments. Grats needs to be able to see the return type in order to generate a GraphQL schema."; | ||
} | ||
exports.wrapperMissingTypeArg = wrapperMissingTypeArg; | ||
function invalidWrapperOnInputType(wrapperName) { | ||
return "Invalid input type. `".concat(wrapperName, "` is not a valid type when used as a GraphQL input value."); | ||
} | ||
exports.invalidWrapperOnInputType = invalidWrapperOnInputType; | ||
function cannotResolveSymbolForDescription() { | ||
return "Expected TypeScript to be able to resolve this GraphQL entity to a symbol. Is it possible that this type is not defined in this file? Grats needs to follow type references to their declaration in order to determine which GraphQL name is being referenced."; | ||
} | ||
exports.cannotResolveSymbolForDescription = cannotResolveSymbolForDescription; | ||
function propertyFieldMissingType() { | ||
return "Expected GraphQL field to have an explicitly defined type annotation. Grats needs to be able to see the type of the field to generate a field's type in the GraphQL schema."; | ||
} | ||
exports.propertyFieldMissingType = propertyFieldMissingType; | ||
function expectedOneNonNullishType() { | ||
return "Expected exactly one non-nullish type. GraphQL does not support fields returning an arbitrary union of types. Consider defining an explicit `@".concat(Extractor_1.UNION_TAG, "` union type and returning that."); | ||
} | ||
exports.expectedOneNonNullishType = expectedOneNonNullishType; | ||
// TODO: Add code action | ||
function ambiguousNumberType() { | ||
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.ambiguousNumberType = ambiguousNumberType; | ||
function defaultValueIsNotLiteral() { | ||
return 'Expected GraphQL field argument default values to be a literal. Grats interprets argument defaults as GraphQL default values, which must be literals. For example: `10` or `"foo"`.'; | ||
} | ||
exports.defaultValueIsNotLiteral = defaultValueIsNotLiteral; | ||
function defaultArgElementIsNotAssignment() { | ||
return "Expected property to be a default assignment. For example: `{ first = 10}`. Grats needs to extract a literal GraphQL value here, and that requires Grats being able to see the literal value in the source code."; | ||
} | ||
exports.defaultArgElementIsNotAssignment = defaultArgElementIsNotAssignment; | ||
function defaultArgPropertyMissingName() { | ||
return "Expected object literal property to have a name. Grats needs to extract a literal value here, and that requires Grats being able to see the literal value and its field name in the source code."; | ||
} | ||
exports.defaultArgPropertyMissingName = defaultArgPropertyMissingName; | ||
function defaultArgPropertyMissingInitializer() { | ||
return "Expected object literal property to have an initializer. For example: `{ offset = 10}`. Grats needs to extract a literal GraphQL value here, and that requires Grats being able to see the literal value in the source code."; | ||
} | ||
exports.defaultArgPropertyMissingInitializer = defaultArgPropertyMissingInitializer; | ||
function unsupportedTypeLiteral() { | ||
return "Unexpected type literal. Grats expects types in GraphQL positions to be scalar types, or reference a named GraphQL type directly. You may want to define a named GraphQL type elsewhere and reference it here."; | ||
} | ||
exports.unsupportedTypeLiteral = unsupportedTypeLiteral; | ||
function unknownGraphQLType() { | ||
return "Unknown GraphQL type. Grats doe not know how to map this type to a GraphQL type. You may want to define a named GraphQL type elsewhere and reference it here. If you think Grats should be able to infer a GraphQL type from this type, please file an issue."; | ||
return "Unknown GraphQL type. Grats does not know how to map this type to a GraphQL type. You may want to define a named GraphQL type elsewhere and reference it here. If you think Grats should be able to infer a GraphQL type from this type, please file an issue."; | ||
} | ||
exports.unknownGraphQLType = unknownGraphQLType; | ||
function pluralTypeMissingParameter() { | ||
return "Expected wrapper type reference to have type arguments. Grats needs to be able to see the return type in order to generate a GraphQL schema."; | ||
} | ||
exports.pluralTypeMissingParameter = pluralTypeMissingParameter; | ||
function expectedNameIdentifier() { | ||
return "Expected an name identifier. Grats expected to find a name here which it could use to derive the GraphQL name."; | ||
return "Expected a name identifier. Grats expected to find a name here which it could use to derive the GraphQL name."; | ||
} | ||
exports.expectedNameIdentifier = expectedNameIdentifier; | ||
// TODO: Add code action | ||
function killsParentOnExceptionWithWrongConfig() { | ||
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() { | ||
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() { | ||
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.nonNullTypeCannotBeOptional = nonNullTypeCannotBeOptional; | ||
function mergedInterfaces() { | ||
@@ -282,23 +378,21 @@ return [ | ||
} | ||
exports.mergedInterfaces = mergedInterfaces; | ||
// TODO: Add code action | ||
function implementsTagOnClass() { | ||
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() { | ||
return "`@".concat(Extractor_1.IMPLEMENTS_TAG_DEPRECATED, "` has been deprecated. Instead use `interface MyType extends MyInterface`."); | ||
} | ||
exports.implementsTagOnInterface = implementsTagOnInterface; | ||
function implementsTagOnTypeAlias() { | ||
return "`@".concat(Extractor_1.IMPLEMENTS_TAG_DEPRECATED, "` has been deprecated. Types which implement GraphQL interfaces should be defined using TypeScript class or interface declarations."); | ||
} | ||
exports.implementsTagOnTypeAlias = implementsTagOnTypeAlias; | ||
// TODO: Add code action | ||
function duplicateTag(tagName) { | ||
return "Unexpected duplicate `@".concat(tagName, "` tag. Grats does not accept multiple instances of the same tag."); | ||
} | ||
exports.duplicateTag = duplicateTag; | ||
function duplicateInterfaceTag() { | ||
return "Unexpected duplicate `@".concat(Extractor_1.IMPLEMENTS_TAG_DEPRECATED, "` tag. To declare that a type or interface implements multiple interfaces list them as comma separated values: `@").concat(Extractor_1.IMPLEMENTS_TAG_DEPRECATED, " interfaceA, interfaceB`."); | ||
} | ||
exports.duplicateInterfaceTag = duplicateInterfaceTag; | ||
// TODO: Add code action | ||
function parameterWithoutModifiers() { | ||
@@ -310,3 +404,2 @@ return [ | ||
} | ||
exports.parameterWithoutModifiers = parameterWithoutModifiers; | ||
function parameterPropertyNotPublic() { | ||
@@ -318,23 +411,17 @@ return [ | ||
} | ||
exports.parameterPropertyNotPublic = parameterPropertyNotPublic; | ||
function parameterPropertyMissingType() { | ||
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` parameter property to have an explicit type annotation. Grats needs to be able to see the type of the parameter property to generate a GraphQL schema."); | ||
} | ||
exports.parameterPropertyMissingType = parameterPropertyMissingType; | ||
function invalidTypePassedToFieldFunction() { | ||
return "Unexpected type passed to `@".concat(Extractor_1.FIELD_TAG, "` function. `@").concat(Extractor_1.FIELD_TAG, "` functions can only be used to extend `@").concat(Extractor_1.TYPE_TAG, "` and `@").concat(Extractor_1.INTERFACE_TAG, "` types."); | ||
} | ||
exports.invalidTypePassedToFieldFunction = invalidTypePassedToFieldFunction; | ||
function unresolvedTypeReference() { | ||
return "Unable to resolve type reference. In order to generate a GraphQL schema, Grats needs to determine which GraphQL type is being referenced. This requires being able to resolve type references to their `@gql` annotated declaration. However this reference could not be resolved. Is it possible that this type is not defined in this file?"; | ||
} | ||
exports.unresolvedTypeReference = unresolvedTypeReference; | ||
function expectedTypeAnnotationOnContext() { | ||
return "Expected context parameter to have an explicit type annotation. Grats validates that your context parameter is type-safe by checking that all context values reference the same type declaration."; | ||
} | ||
exports.expectedTypeAnnotationOnContext = expectedTypeAnnotationOnContext; | ||
function expectedTypeAnnotationOfReferenceOnContext() { | ||
return "Expected context parameter's type to be a type reference. Grats validates that your context parameter is type-safe by checking that all context values reference the same type declaration."; | ||
} | ||
exports.expectedTypeAnnotationOfReferenceOnContext = expectedTypeAnnotationOfReferenceOnContext; | ||
function expectedTypeAnnotationOnContextToBeResolvable() { | ||
@@ -345,98 +432,168 @@ // TODO: Provide guidance? | ||
} | ||
exports.expectedTypeAnnotationOnContextToBeResolvable = expectedTypeAnnotationOnContextToBeResolvable; | ||
function expectedTypeAnnotationOnContextToHaveDeclaration() { | ||
return "Unable to locate the declaration of the context parameter's type. Grats validates that your context parameter is type-safe by checking all context values reference the same type declaration. Did you forget to import or define this type?"; | ||
} | ||
exports.expectedTypeAnnotationOnContextToHaveDeclaration = expectedTypeAnnotationOnContextToHaveDeclaration; | ||
function unexpectedParamSpreadForContextParam() { | ||
return "Unexpected spread parameter in context parameter position. Grats expects the context parameter to be a single, explicitly-typed argument."; | ||
function unexpectedParamSpreadForResolverParam() { | ||
return "Unexpected spread argument in resolver. Grats expects all resolver arguments to be a single, explicitly-typed argument."; | ||
} | ||
exports.unexpectedParamSpreadForContextParam = unexpectedParamSpreadForContextParam; | ||
function resolverParamIsUnknown() { | ||
// TODO: Give guidance that this is a change? | ||
return "Unexpected `unknown` type for resolver argument. If a resolver argument is not needed by the resolver, it may be omitted."; | ||
} | ||
function resolverParamIsNever() { | ||
// TODO: Give guidance that this is a change? | ||
return "Unexpected `never` type for resolver argument. If a resolver argument is not needed by the resolver, it may be omitted."; | ||
} | ||
function unexpectedResolverParamType() { | ||
return "Unexpected type for resolver argument. Resolver arguments must be typed with either an object literal (`{}`) or a reference to a named type."; | ||
} | ||
function multipleContextTypes() { | ||
return "Context argument's type does not match. Grats expects all resolvers that read the context argument to use the same type for that argument. Did you use the incorrect type in one of your resolvers?"; | ||
} | ||
exports.multipleContextTypes = multipleContextTypes; | ||
function graphQLNameHasLeadingNewlines(name, tagName) { | ||
return "Expected the GraphQL name `".concat(name, "` to be on the same line as it's `@").concat(tagName, "` tag."); | ||
} | ||
exports.graphQLNameHasLeadingNewlines = graphQLNameHasLeadingNewlines; | ||
function graphQLTagNameHasWhitespace(tagName) { | ||
return "Expected text following a `@".concat(tagName, "` tag to be a GraphQL name. If you intended this text to be a description, place it at the top of the docblock before any `@tags`."); | ||
} | ||
exports.graphQLTagNameHasWhitespace = graphQLTagNameHasWhitespace; | ||
function subscriptionFieldNotAsyncIterable() { | ||
return "Expected fields on `Subscription` to return an `AsyncIterable`. Fields on `Subscription` model a subscription, which is a stream of events. Grats expects fields on `Subscription` to return an `AsyncIterable` which can be used to model this stream."; | ||
} | ||
exports.subscriptionFieldNotAsyncIterable = subscriptionFieldNotAsyncIterable; | ||
function operationTypeNotUnknown() { | ||
return "Operation types `Query`, `Mutation`, and `Subscription` must be defined as type aliases of `unknown`. E.g. `type Query = unknown`. This is because GraphQL servers do not have an agreed upon way to produce root values, and Grats errs on the side of safety. If you are trying to implement dependency injection, consider using the `context` argument passed to each resolver instead. If you have a strong use case for a concrete root value, please file an issue."; | ||
} | ||
exports.operationTypeNotUnknown = operationTypeNotUnknown; | ||
function expectedNullableArgumentToBeOptional() { | ||
return "Expected nullable argument to _also_ be optional (`?`). graphql-js may omit properties on the argument object where an undefined GraphQL variable is passed, or if the argument is omitted in the operation text. To ensure your resolver is capable of handing this scenario, add a `?` to the end of the argument name to make it optional. e.g. `{greeting?: string | null}`"; | ||
} | ||
exports.expectedNullableArgumentToBeOptional = expectedNullableArgumentToBeOptional; | ||
function gqlTagInLineComment() { | ||
return "Unexpected Grats tag in line (`//`) comment. Grats looks for tags in JSDoc-style block comments. e.g. `/** @gqlType */`. For more information see: ".concat(DOC_URLS.commentSyntax); | ||
} | ||
exports.gqlTagInLineComment = gqlTagInLineComment; | ||
function gqlTagInNonJSDocBlockComment() { | ||
return "Unexpected Grats tag in non-JSDoc-style block comment. Grats only looks for tags in JSDoc-style block comments which start with `/**`. For more information see: ".concat(DOC_URLS.commentSyntax); | ||
} | ||
exports.gqlTagInNonJSDocBlockComment = gqlTagInNonJSDocBlockComment; | ||
function gqlTagInDetachedJSDocBlockComment() { | ||
return "Unexpected Grats tag in detached docblock. Grats was unable to determine which TypeScript declaration this docblock is associated with. Moving the docblock to a position with is unambiguously \"above\" the relevant declaration may help. For more information see: ".concat(DOC_URLS.commentSyntax); | ||
} | ||
exports.gqlTagInDetachedJSDocBlockComment = gqlTagInDetachedJSDocBlockComment; | ||
function gqlFieldTagOnInputType() { | ||
return "The tag `@".concat(Extractor_1.FIELD_TAG, "` is not needed on fields of input types. All fields are automatically included as part of the input type. This tag can be safely removed."); | ||
} | ||
exports.gqlFieldTagOnInputType = gqlFieldTagOnInputType; | ||
// TODO: Add code action | ||
function gqlFieldParentMissingTag() { | ||
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.gqlFieldParentMissingTag = gqlFieldParentMissingTag; | ||
function missingSpecifiedByUrl() { | ||
return "Expected `@".concat(Extractor_1.SPECIFIED_BY_TAG, "` tag to be followed by a URL. This URL will be used as the `url` argument to the `@specifiedBy` directive in the generated GraphQL schema. See https://spec.graphql.org/draft/#sec--specifiedBy for more information."); | ||
} | ||
exports.missingSpecifiedByUrl = missingSpecifiedByUrl; | ||
function specifiedByOnWrongNode() { | ||
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?"); | ||
} | ||
exports.specifiedByOnWrongNode = specifiedByOnWrongNode; | ||
function missingGenericType(templateName, paramName) { | ||
return "Missing type argument for generic GraphQL type. Expected `".concat(templateName, "` to be passed a GraphQL type argument for type parameter `").concat(paramName, "`."); | ||
} | ||
exports.missingGenericType = missingGenericType; | ||
function nonGraphQLGenericType(templateName, paramName) { | ||
return "Expected `".concat(templateName, "` to be passed a GraphQL type argument for type parameter `").concat(paramName, "`."); | ||
} | ||
exports.nonGraphQLGenericType = nonGraphQLGenericType; | ||
function genericTypeUsedAsUnionMember() { | ||
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."; | ||
} | ||
exports.genericTypeUsedAsUnionMember = genericTypeUsedAsUnionMember; | ||
function genericTypeImplementsInterface() { | ||
return "Unexpected `implements` on generic `".concat(Extractor_1.TYPE_TAG, "`. Generic types may not currently declare themselves as implementing interfaces. Grats requires that all types which implement an interface 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 declare themselves as interface implementors."); | ||
} | ||
exports.genericTypeImplementsInterface = genericTypeImplementsInterface; | ||
function concreteTypeMissingTypename(implementor) { | ||
return "Missing `__typename` on `".concat(implementor, "`. The type `").concat(implementor, "` is used in a union or interface, so it must have a `__typename` field."); | ||
function concreteTypenameImplementingInterfaceCannotBeResolved(implementor, interfaceName) { | ||
return "Cannot resolve typename. The type `".concat(implementor, "` implements `").concat(interfaceName, "`, so it must either have a `__typename` property or be an exported class."); | ||
} | ||
exports.concreteTypeMissingTypename = concreteTypeMissingTypename; | ||
function concreteTypenameInUnionCannotBeResolved(implementor, unionName) { | ||
return "Cannot resolve typename. The type `".concat(implementor, "` is a member of `").concat(unionName, "`, so it must either have a `__typename` property or be an exported class."); | ||
} | ||
// 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; | ||
function oneOfNotSupportedGraphql(requiredVersion, foundVersion) { | ||
return "OneOf input types are only supported in `graphql@".concat(requiredVersion, "` and later but Grats found `graphql@").concat(foundVersion, "`. Please upgrade your version of graphql-js in order to use this feature."); | ||
} | ||
function oneOfNotOnUnion() { | ||
return "Expected the type of a @gqlInput with @oneOf to be attached to a TypeScript union."; | ||
} | ||
function oneOfFieldNotTypeLiteralWithOneProperty() { | ||
return "Expected each member of a @oneOf @gqlInput to be a TypeScript object literal with exactly one property."; | ||
} | ||
function oneOfPropertyMissingTypeAnnotation() { | ||
return "Expected each property of a @oneOf @gqlInput to have a type annotation."; | ||
} | ||
function contextTagOnNonDeclaration() { | ||
return "Invalid `@".concat(Extractor_1.CONTEXT_TAG, "` tag annotation. Expected the `@").concat(Extractor_1.CONTEXT_TAG, "` tag to be attached to a type, interface or class declaration."); | ||
} | ||
function duplicateContextTag() { | ||
return "Unexpected duplicate `@".concat(Extractor_1.CONTEXT_TAG, "` tag. Only one type in a project may be annotated with the `@").concat(Extractor_1.CONTEXT_TAG, "`."); | ||
} | ||
function userDefinedInfoTag() { | ||
return "Unexpected user-defined `@".concat(Extractor_1.INFO_TAG, "` tag. Use the type `GqlInfo` exported from `grats`: `import { GqlInfo } from \"grats\";`."); | ||
} | ||
function invalidResolverParamType() { | ||
return "Unexpected GraphQL type used as resolver parameter. Resolver input arguments must be specified as a single `args` object literal: `args: {argName: ArgType}`."; | ||
} | ||
function exportedArrowFunctionNotConst() { | ||
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` arrow function to be declared as `const`."); | ||
} | ||
function exportedFieldVariableMultipleDeclarations(n) { | ||
return "Expected only one declaration when defining a `@".concat(Extractor_1.FIELD_TAG, "`, found ").concat(n, "."); | ||
} | ||
function fieldVariableNotTopLevelExported() { | ||
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` to be an exported top-level declaration. Grats needs to import resolver functions into it's generated schema module, so the resolver function must be exported from the module."); | ||
} | ||
function fieldVariableIsNotArrowFunction() { | ||
return "Expected `@".concat(Extractor_1.FIELD_TAG, "` on variable declaration to be attached to an arrow function."); | ||
} | ||
function positionalResolverArgDoesNotHaveName() { | ||
return "Expected resolver argument to have a name. Grats needs to be able to see the name of the argument in order to derive a GraphQL argument name."; | ||
} | ||
function positionalArgAndArgsObject() { | ||
return "Unexpected arguments object in resolver that is also using positional GraphQL arguments. Grats expects that either all GraphQL arguments will be defined in a single object, or that all GraphQL arguments will be defined using positional arguments. The two strategies may not be combined."; | ||
} | ||
function contextOrInfoUsedInGraphQLPosition(kind) { | ||
var tag = kind === "CONTEXT" ? Extractor_1.CONTEXT_TAG : Extractor_1.INFO_TAG; | ||
return "Cannot use `".concat(tag, "` as a type in GraphQL type position."); | ||
} | ||
function typeWithNoFields(kind, typeName) { | ||
return "".concat(kind, " `").concat(typeName, "` must define one or more fields.\n\nDefine a field by adding `/** @").concat(Extractor_1.FIELD_TAG, " */` above a field, property, attribute or method of this type, or above a function that has `").concat(typeName, "` as its first argument."); | ||
} | ||
function noTypesDefined() { | ||
return "Grats could not find any GraphQL types defined in this project.\n\nDeclare a type by adding a `/** @".concat(Extractor_1.TYPE_TAG, " */` docblock above a class, interface, or type alias declaration.\nGrats looks for docblock tags in any TypeScript file included in your TypeScript project."); | ||
} | ||
function tsConfigNotFound(cwd) { | ||
return "Grats: Could not find `tsconfig.json` searching in ".concat(cwd, ".\n\nSee https://www.typescriptlang.org/download/ for instructors on how to add TypeScript to your project. Then run `npx tsc --init` to create a `tsconfig.json` file."); | ||
} | ||
function cyclicDerivedContext() { | ||
return "Cyclic dependency detected in derived context. This derived context value depends upon itself."; | ||
} | ||
function invalidDerivedContextArgType() { | ||
return "Invalid type for derived context function argument. Derived context functions may only accept other `@gqlContext` types as arguments."; | ||
} | ||
function missingReturnTypeForDerivedResolver() { | ||
return 'Expected derived resolver to have an explicit return type. This is needed to allow Grats to "see" which type to treat as a derived context type.'; | ||
} | ||
function derivedResolverInvalidReturnType() { | ||
return "Expected derived resolver function's return type to be a type reference. Grats uses this type reference to determine which type to treat as a derived context type."; | ||
} | ||
function directiveTagOnWrongNode() { | ||
return "`@".concat(Extractor_1.DIRECTIVE_TAG, "` can only be used on function declarations."); | ||
} | ||
function directiveTagCommentNotText() { | ||
return "Expected Grats JSDoc tag value to be simple text."; | ||
} | ||
function specifiedByDeprecated() { | ||
return 'The `@specifiedBy` tag has been deprecated in favor of `@gqlAnnotate`. Use `@gqlAnnotate specified(url: "http://example.com")` instead.'; | ||
} | ||
function directiveTagNoComment() { | ||
return "Expected `@gqlDirective` tag to specify at least one location."; | ||
} | ||
function directiveFunctionNotNamed() { | ||
return "Expected `@gqlDirective` function to be named."; | ||
} | ||
function directiveArgumentNotObject() { | ||
return "Expected first argument of a `@gqlDirective` function to be typed using an inline object literal."; | ||
} |
import { NameNode, DefinitionNode } from "graphql"; | ||
import { DiagnosticsResult } from "./utils/DiagnosticError"; | ||
import * as ts from "typescript"; | ||
import { NameDefinition } from "./TypeContext"; | ||
import { DeclarationDefinition, NameDefinition } from "./TypeContext"; | ||
export declare const LIBRARY_IMPORT_NAME = "grats"; | ||
@@ -14,6 +14,14 @@ export declare const LIBRARY_NAME = "Grats"; | ||
export declare const INPUT_TAG = "gqlInput"; | ||
export declare const DIRECTIVE_TAG = "gqlDirective"; | ||
export declare const ANNOTATE_TAG = "gqlAnnotate"; | ||
export declare const QUERY_FIELD_TAG = "gqlQueryField"; | ||
export declare const MUTATION_FIELD_TAG = "gqlMutationField"; | ||
export declare const SUBSCRIPTION_FIELD_TAG = "gqlSubscriptionField"; | ||
export declare const CONTEXT_TAG = "gqlContext"; | ||
export declare const INFO_TAG = "gqlInfo"; | ||
export declare const IMPLEMENTS_TAG_DEPRECATED = "gqlImplements"; | ||
export declare const KILLS_PARENT_ON_EXCEPTION_TAG = "killsParentOnException"; | ||
export declare const ALL_TAGS: string[]; | ||
export declare const SPECIFIED_BY_TAG = "specifiedBy"; | ||
export declare const ONE_OF_TAG = "oneOf"; | ||
export declare const OPERATION_TYPES: Set<string>; | ||
export type ExtractionSnapshot = { | ||
@@ -23,3 +31,3 @@ readonly definitions: DefinitionNode[]; | ||
readonly nameDefinitions: Map<ts.DeclarationStatement, NameDefinition>; | ||
readonly contextReferences: Array<ts.Node>; | ||
readonly implicitNameDefinitions: Map<DeclarationDefinition, ts.TypeReferenceNode>; | ||
readonly typesWithTypename: Set<string>; | ||
@@ -26,0 +34,0 @@ readonly interfaceDeclarations: Array<ts.InterfaceDeclaration>; |
@@ -1,20 +0,19 @@ | ||
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"; | ||
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, DirectiveDefinitionNode } from "graphql"; | ||
import * as ts from "typescript"; | ||
import { TsLocatableNode } from "./utils/DiagnosticError"; | ||
import { DiagnosticResult, TsLocatableNode } from "./utils/DiagnosticError"; | ||
import { InputValueDefinitionNodeOrResolverArg, ResolverSignature } from "./resolverSignature"; | ||
export declare class GraphQLConstructor { | ||
fieldMetadataDirective(node: ts.Node, metadata: { | ||
tsModulePath: string | null; | ||
name: string | null; | ||
directiveDefinition(node: ts.Node, name: NameNode, args: readonly InputValueDefinitionNode[] | null, repeatable: boolean, locations: readonly NameNode[], description: StringValueNode | null): DirectiveDefinitionNode; | ||
unionTypeDefinition(node: ts.Node, name: NameNode, types: NamedTypeNode[], description: StringValueNode | null, directives: readonly ConstDirectiveNode[] | null): UnionTypeDefinitionNode; | ||
objectTypeDefinition(node: ts.Node, name: NameNode, fields: FieldDefinitionNode[], interfaces: NamedTypeNode[] | null, description: StringValueNode | null, directives: readonly ConstDirectiveNode[] | null, hasTypeNameField: boolean, exported: { | ||
tsModulePath: string; | ||
exportName: string | null; | ||
argCount: number | null; | ||
}): ConstDirectiveNode; | ||
killsParentOnExceptionDirective(node: ts.Node): ConstDirectiveNode; | ||
unionTypeDefinition(node: ts.Node, name: NameNode, types: NamedTypeNode[], description: StringValueNode | null): UnionTypeDefinitionNode; | ||
objectTypeDefinition(node: ts.Node, name: NameNode, fields: FieldDefinitionNode[], interfaces: NamedTypeNode[] | null, description: StringValueNode | null): ObjectTypeDefinitionNode; | ||
interfaceTypeDefinition(node: ts.Node, name: NameNode, fields: FieldDefinitionNode[], interfaces: NamedTypeNode[] | null, description: StringValueNode | null): InterfaceTypeDefinitionNode; | ||
enumTypeDefinition(node: ts.Node, name: NameNode, values: readonly EnumValueDefinitionNode[], description: StringValueNode | null): EnumTypeDefinitionNode; | ||
abstractFieldDefinition(node: ts.Node, onType: NameNode, field: FieldDefinitionNode): ObjectTypeExtensionNode; | ||
fieldDefinition(node: ts.Node, name: NameNode, type: TypeNode, args: readonly InputValueDefinitionNode[] | null, directives: readonly ConstDirectiveNode[], description: StringValueNode | null): FieldDefinitionNode; | ||
} | null): ObjectTypeDefinitionNode; | ||
interfaceTypeDefinition(node: ts.Node, name: NameNode, fields: FieldDefinitionNode[], interfaces: NamedTypeNode[] | null, description: StringValueNode | null, directives: readonly ConstDirectiveNode[] | null): InterfaceTypeDefinitionNode; | ||
enumTypeDefinition(node: ts.Node, name: NameNode, values: readonly EnumValueDefinitionNode[], description: StringValueNode | null, directives: readonly ConstDirectiveNode[] | null): EnumTypeDefinitionNode; | ||
abstractFieldDefinition(node: ts.Node, onType: NameNode, field: FieldDefinitionNode, mayBeInterface?: boolean): ObjectTypeExtensionNode; | ||
fieldDefinition(node: ts.Node, name: NameNode, type: TypeNode, args: readonly InputValueDefinitionNode[] | null, directives: readonly ConstDirectiveNode[], description: StringValueNode | null, killsParentOnException: NameNode | null, resolver: ResolverSignature): FieldDefinitionNode; | ||
constObjectField(node: ts.Node, name: NameNode, value: ConstValueNode): ConstObjectFieldNode; | ||
inputValueDefinition(node: ts.Node, name: NameNode, type: TypeNode, directives: readonly ConstDirectiveNode[] | null, defaultValue: ConstValueNode | null, description: StringValueNode | null): InputValueDefinitionNode; | ||
inputValueDefinitionOrResolverArg(node: ts.Node, name: DiagnosticResult<NameNode>, type: TypeNode, directives: readonly ConstDirectiveNode[] | null, defaultValue: ConstValueNode | null, description: StringValueNode | null): InputValueDefinitionNodeOrResolverArg; | ||
enumValueDefinition(node: ts.Node, name: NameNode, directives: readonly ConstDirectiveNode[] | undefined, description: StringValueNode | null): EnumValueDefinitionNode; | ||
@@ -32,3 +31,3 @@ scalarTypeDefinition(node: ts.Node, name: NameNode, directives: readonly ConstDirectiveNode[] | null, description: StringValueNode | null): ScalarTypeDefinitionNode; | ||
constArgument(node: ts.Node, name: NameNode, value: ConstValueNode): ConstArgumentNode; | ||
constDirective(node: ts.Node, name: NameNode, args: ReadonlyArray<ConstArgumentNode> | null): ConstDirectiveNode; | ||
constDirective(node: ts.Node, name: NameNode, args: ReadonlyArray<ConstArgumentNode> | null, isAmbiguous?: boolean): ConstDirectiveNode; | ||
string(node: ts.Node, value: string, block?: boolean): StringValueNode; | ||
@@ -35,0 +34,0 @@ float(node: ts.Node, value: string): FloatValueNode; |
@@ -14,5 +14,5 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.loc = exports.GraphQLConstructor = void 0; | ||
exports.GraphQLConstructor = void 0; | ||
exports.loc = loc; | ||
var graphql_1 = require("graphql"); | ||
var metadataDirectives_1 = require("./metadataDirectives"); | ||
var helpers_1 = require("./utils/helpers"); | ||
@@ -22,24 +22,18 @@ var GraphQLConstructor = /** @class */ (function () { | ||
} | ||
GraphQLConstructor.prototype.fieldMetadataDirective = function (node, metadata) { | ||
var args = []; | ||
if (metadata.tsModulePath != null) { | ||
args.push(this.constArgument(node, this.name(node, metadataDirectives_1.TS_MODULE_PATH_ARG), this.string(node, metadata.tsModulePath))); | ||
} | ||
if (metadata.name != null) { | ||
args.push(this.constArgument(node, this.name(node, metadataDirectives_1.FIELD_NAME_ARG), this.string(node, metadata.name))); | ||
} | ||
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) { | ||
args.push(this.constArgument(node, this.name(node, metadataDirectives_1.ARG_COUNT), this.int(node, metadata.argCount.toString()))); | ||
} | ||
return this.constDirective(node, this.name(node, metadataDirectives_1.FIELD_METADATA_DIRECTIVE), args); | ||
}; | ||
GraphQLConstructor.prototype.killsParentOnExceptionDirective = function (node) { | ||
return (0, metadataDirectives_1.makeKillsParentOnExceptionDirective)(loc(node)); | ||
}; | ||
/* Top Level Types */ | ||
GraphQLConstructor.prototype.unionTypeDefinition = function (node, name, types, description) { | ||
GraphQLConstructor.prototype.directiveDefinition = function (node, name, args, repeatable, locations, description) { | ||
return { | ||
kind: graphql_1.Kind.DIRECTIVE_DEFINITION, | ||
loc: loc(node), | ||
name: name, | ||
// "Real" arguments are undefined for now. Later they will be derived from | ||
// `resolverArgs`. | ||
arguments: this._optionalList(args), | ||
repeatable: repeatable, | ||
locations: locations, | ||
description: description !== null && description !== void 0 ? description : undefined, | ||
}; | ||
}; | ||
GraphQLConstructor.prototype.unionTypeDefinition = function (node, name, types, description, directives) { | ||
return { | ||
kind: graphql_1.Kind.UNION_TYPE_DEFINITION, | ||
@@ -50,5 +44,6 @@ loc: loc(node), | ||
types: types, | ||
directives: this._optionalList(directives), | ||
}; | ||
}; | ||
GraphQLConstructor.prototype.objectTypeDefinition = function (node, name, fields, interfaces, description) { | ||
GraphQLConstructor.prototype.objectTypeDefinition = function (node, name, fields, interfaces, description, directives, hasTypeNameField, exported) { | ||
return { | ||
@@ -58,9 +53,11 @@ kind: graphql_1.Kind.OBJECT_TYPE_DEFINITION, | ||
description: description !== null && description !== void 0 ? description : undefined, | ||
directives: undefined, | ||
name: name, | ||
fields: fields, | ||
interfaces: interfaces !== null && interfaces !== void 0 ? interfaces : undefined, | ||
hasTypeNameField: hasTypeNameField, | ||
exported: exported !== null && exported !== void 0 ? exported : undefined, | ||
directives: this._optionalList(directives), | ||
}; | ||
}; | ||
GraphQLConstructor.prototype.interfaceTypeDefinition = function (node, name, fields, interfaces, description) { | ||
GraphQLConstructor.prototype.interfaceTypeDefinition = function (node, name, fields, interfaces, description, directives) { | ||
return { | ||
@@ -70,9 +67,9 @@ kind: graphql_1.Kind.INTERFACE_TYPE_DEFINITION, | ||
description: description !== null && description !== void 0 ? description : undefined, | ||
directives: undefined, | ||
name: name, | ||
fields: fields, | ||
interfaces: interfaces !== null && interfaces !== void 0 ? interfaces : undefined, | ||
directives: this._optionalList(directives), | ||
}; | ||
}; | ||
GraphQLConstructor.prototype.enumTypeDefinition = function (node, name, values, description) { | ||
GraphQLConstructor.prototype.enumTypeDefinition = function (node, name, values, description, directives) { | ||
return { | ||
@@ -84,6 +81,8 @@ kind: graphql_1.Kind.ENUM_TYPE_DEFINITION, | ||
values: values, | ||
directives: this._optionalList(directives), | ||
}; | ||
}; | ||
/* Top Level Extensions */ | ||
GraphQLConstructor.prototype.abstractFieldDefinition = function (node, onType, field) { | ||
GraphQLConstructor.prototype.abstractFieldDefinition = function (node, onType, field, mayBeInterface) { | ||
if (mayBeInterface === void 0) { mayBeInterface = true; } | ||
return { | ||
@@ -94,7 +93,7 @@ kind: graphql_1.Kind.OBJECT_TYPE_EXTENSION, | ||
fields: [field], | ||
mayBeInterface: true, | ||
mayBeInterface: mayBeInterface, | ||
}; | ||
}; | ||
/* Field Definitions */ | ||
GraphQLConstructor.prototype.fieldDefinition = function (node, name, type, args, directives, description) { | ||
GraphQLConstructor.prototype.fieldDefinition = function (node, name, type, args, directives, description, killsParentOnException, resolver) { | ||
return { | ||
@@ -108,2 +107,4 @@ kind: graphql_1.Kind.FIELD_DEFINITION, | ||
directives: this._optionalList(directives), | ||
resolver: resolver, | ||
killsParentOnException: killsParentOnException !== null && killsParentOnException !== void 0 ? killsParentOnException : undefined, | ||
}; | ||
@@ -125,2 +126,13 @@ }; | ||
}; | ||
GraphQLConstructor.prototype.inputValueDefinitionOrResolverArg = function (node, name, type, directives, defaultValue, description) { | ||
return { | ||
kind: graphql_1.Kind.INPUT_VALUE_DEFINITION, | ||
loc: loc(node), | ||
description: description !== null && description !== void 0 ? description : undefined, | ||
name: name, | ||
type: type, | ||
defaultValue: defaultValue !== null && defaultValue !== void 0 ? defaultValue : undefined, | ||
directives: this._optionalList(directives), | ||
}; | ||
}; | ||
GraphQLConstructor.prototype.enumValueDefinition = function (node, name, directives, description) { | ||
@@ -199,3 +211,4 @@ return { | ||
}; | ||
GraphQLConstructor.prototype.constDirective = function (node, name, args) { | ||
GraphQLConstructor.prototype.constDirective = function (node, name, args, isAmbiguous) { | ||
if (isAmbiguous === void 0) { isAmbiguous = false; } | ||
return { | ||
@@ -206,2 +219,3 @@ kind: graphql_1.Kind.DIRECTIVE, | ||
arguments: this._optionalList(args), | ||
isAmbiguous: isAmbiguous, | ||
}; | ||
@@ -243,3 +257,2 @@ }; | ||
} | ||
exports.loc = loc; | ||
function _dummyToken(sourceFile, pos) { | ||
@@ -246,0 +259,0 @@ var _a = sourceFile.getLineAndCharacterOfPosition(pos), line = _a.line, character = _a.character; |
import * as ts from "typescript"; | ||
export type ConfigOptions = { | ||
export type GratsConfig = { | ||
graphqlSchema: string; | ||
@@ -10,8 +10,11 @@ tsSchema: string; | ||
tsSchemaHeader: string | null; | ||
importModuleSpecifierEnding: string; | ||
EXPERIMENTAL__emitMetadata: boolean; | ||
EXPERIMENTAL__emitResolverMap: boolean; | ||
}; | ||
export type ParsedCommandLineGrats = Omit<ts.ParsedCommandLine, "raw"> & { | ||
raw: { | ||
grats: ConfigOptions; | ||
grats: GratsConfig; | ||
}; | ||
}; | ||
export declare function validateGratsOptions(options: ts.ParsedCommandLine): ParsedCommandLineGrats; |
@@ -25,3 +25,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.validateGratsOptions = void 0; | ||
exports.validateGratsOptions = validateGratsOptions; | ||
var DEFAULT_SDL_HEADER = "# Schema generated by Grats (https://grats.capt.dev)\n# Do not manually edit. Regenerate by running `npx grats`."; | ||
@@ -37,2 +37,5 @@ var DEFAULT_TYPESCRIPT_HEADER = "/**\n * Executable schema generated by Grats (https://grats.capt.dev)\n * Do not manually edit. Regenerate by running `npx grats`.\n */"; | ||
"tsSchemaHeader", | ||
"importModuleSpecifierEnding", | ||
"EXPERIMENTAL__emitMetadata", | ||
"EXPERIMENTAL__emitResolverMap", | ||
]); | ||
@@ -122,4 +125,27 @@ // 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."); | ||
} | ||
if (gratsOptions.EXPERIMENTAL__emitMetadata === undefined) { | ||
gratsOptions.EXPERIMENTAL__emitMetadata = false; | ||
} | ||
else if (typeof gratsOptions.EXPERIMENTAL__emitMetadata !== "boolean") { | ||
throw new Error("Grats: The Grats config option `EXPERIMENTAL__emitMetadata` must be a boolean if provided."); | ||
} | ||
else { | ||
console.warn("Grats: The `EXPERIMENTAL__emitMetadata` option is experimental and will be renamed or removed in a future release."); | ||
} | ||
if (gratsOptions.EXPERIMENTAL__emitResolverMap === undefined) { | ||
gratsOptions.EXPERIMENTAL__emitResolverMap = false; | ||
} | ||
else if (typeof gratsOptions.EXPERIMENTAL__emitResolverMap !== "boolean") { | ||
throw new Error("Grats: The Grats config option `EXPERIMENTAL__emitResolverMap` must be a boolean if provided."); | ||
} | ||
else { | ||
console.warn("Grats: The `EXPERIMENTAL__emitResolverMap` option is experimental and will be renamed or removed in a future release."); | ||
} | ||
return __assign(__assign({}, options), { raw: __assign(__assign({}, options.raw), { grats: gratsOptions }) }); | ||
} | ||
exports.validateGratsOptions = validateGratsOptions; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.resolveRelativePath = exports.relativePath = void 0; | ||
exports.relativePath = relativePath; | ||
exports.resolveRelativePath = resolveRelativePath; | ||
var path_1 = require("path"); | ||
@@ -16,6 +17,4 @@ // Grats parses TypeScript files and finds resolvers. If the field resolver is a | ||
} | ||
exports.relativePath = relativePath; | ||
function resolveRelativePath(relativePath) { | ||
return (0, path_1.resolve)(gratsRoot, relativePath); | ||
} | ||
exports.resolveRelativePath = resolveRelativePath; |
@@ -8,3 +8,3 @@ import { ParsedCommandLineGrats } from "./gratsConfig"; | ||
export { extract } from "./Extractor"; | ||
export { codegen } from "./codegen"; | ||
export { codegen } from "./codegen/schemaCodegen"; | ||
export declare function getParsedTsConfig(configFile: string): Result<ParsedCommandLineGrats, ReportableDiagnostics>; |
@@ -17,3 +17,4 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.getParsedTsConfig = exports.codegen = exports.extract = exports.printSDLWithoutMetadata = void 0; | ||
exports.codegen = exports.extract = exports.printSDLWithoutMetadata = void 0; | ||
exports.getParsedTsConfig = getParsedTsConfig; | ||
var ts = require("typescript"); | ||
@@ -30,9 +31,6 @@ var gratsConfig_1 = require("./gratsConfig"); | ||
Object.defineProperty(exports, "extract", { enumerable: true, get: function () { return Extractor_1.extract; } }); | ||
var codegen_1 = require("./codegen"); | ||
Object.defineProperty(exports, "codegen", { enumerable: true, get: function () { return codegen_1.codegen; } }); | ||
var schemaCodegen_1 = require("./codegen/schemaCodegen"); | ||
Object.defineProperty(exports, "codegen", { enumerable: true, get: function () { return schemaCodegen_1.codegen; } }); | ||
// #FIXME: Report diagnostics instead of throwing! | ||
function getParsedTsConfig(configFile) { | ||
if (!configFile) { | ||
throw new Error("Grats: Could not find tsconfig.json"); | ||
} | ||
// https://github.com/microsoft/TypeScript/blob/46d70d79cd0dd00d19e4c617d6ebb25e9f3fc7de/src/compiler/watch.ts#L216 | ||
@@ -49,2 +47,1 @@ var configFileHost = ts.sys; | ||
} | ||
exports.getParsedTsConfig = getParsedTsConfig; |
@@ -14,3 +14,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.computeInterfaceMap = void 0; | ||
exports.computeInterfaceMap = computeInterfaceMap; | ||
var helpers_1 = require("./utils/helpers"); | ||
@@ -90,2 +90,1 @@ var graphql_1 = require("graphql"); | ||
} | ||
exports.computeInterfaceMap = computeInterfaceMap; |
@@ -6,5 +6,9 @@ import { DocumentNode, GraphQLSchema } from "graphql"; | ||
import { ParsedCommandLineGrats } from "./gratsConfig"; | ||
import { Metadata } from "./metadata"; | ||
export { initTsPlugin } from "./tsPlugin/initTsPlugin"; | ||
export { GratsConfig } from "./gratsConfig"; | ||
export type SchemaAndDoc = { | ||
schema: GraphQLSchema; | ||
doc: DocumentNode; | ||
resolvers: Metadata; | ||
}; | ||
@@ -11,0 +15,0 @@ export declare function buildSchemaAndDocResult(options: ParsedCommandLineGrats): Result<SchemaAndDoc, ReportableDiagnostics>; |
@@ -30,3 +30,6 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.extractSchemaAndDoc = exports.buildSchemaAndDocResultWithHost = exports.buildSchemaAndDocResult = void 0; | ||
exports.initTsPlugin = void 0; | ||
exports.buildSchemaAndDocResult = buildSchemaAndDocResult; | ||
exports.buildSchemaAndDocResultWithHost = buildSchemaAndDocResultWithHost; | ||
exports.extractSchemaAndDoc = extractSchemaAndDoc; | ||
var graphql_1 = require("graphql"); | ||
@@ -42,4 +45,2 @@ var DiagnosticError_1 = require("./utils/DiagnosticError"); | ||
var validateMergedInterfaces_1 = require("./validations/validateMergedInterfaces"); | ||
var validateContextReferences_1 = require("./validations/validateContextReferences"); | ||
var metadataDirectives_1 = require("./metadataDirectives"); | ||
var addInterfaceFields_1 = require("./transforms/addInterfaceFields"); | ||
@@ -51,4 +52,14 @@ var filterNonGqlInterfaces_1 = require("./transforms/filterNonGqlInterfaces"); | ||
var sortSchemaAst_1 = require("./transforms/sortSchemaAst"); | ||
var validateDuplicateContextOrInfo_1 = require("./validations/validateDuplicateContextOrInfo"); | ||
var validateSemanticNullability_1 = require("./validations/validateSemanticNullability"); | ||
var resolveTypes_1 = require("./transforms/resolveTypes"); | ||
var resolveResolverParams_1 = require("./transforms/resolveResolverParams"); | ||
var customSpecValidations_1 = require("./validations/customSpecValidations"); | ||
var makeResolverSignature_1 = require("./transforms/makeResolverSignature"); | ||
var addImplicitRootTypes_1 = require("./transforms/addImplicitRootTypes"); | ||
var validateDirectiveArguments_1 = require("./validations/validateDirectiveArguments"); | ||
// 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 | ||
@@ -63,3 +74,2 @@ // Exported for tests that want to intercept diagnostic errors. | ||
} | ||
exports.buildSchemaAndDocResult = buildSchemaAndDocResult; | ||
function buildSchemaAndDocResultWithHost(options, compilerHost) { | ||
@@ -71,3 +81,2 @@ var program = ts.createProgram(options.fileNames, options.options, compilerHost); | ||
} | ||
exports.buildSchemaAndDocResultWithHost = buildSchemaAndDocResultWithHost; | ||
/** | ||
@@ -83,11 +92,13 @@ * The core transformation pipeline of Grats. | ||
var checker = program.getTypeChecker(); | ||
var ctx = TypeContext_1.TypeContext.fromSnapshot(checker, snapshot); | ||
var ctxResult = TypeContext_1.TypeContext.fromSnapshot(checker, snapshot); | ||
if (ctxResult.kind === "ERROR") { | ||
return ctxResult; | ||
} | ||
var ctx = ctxResult.value; | ||
// Collect validation errors | ||
var validationResult = (0, Result_1.concatResults)((0, validateMergedInterfaces_1.validateMergedInterfaces)(checker, snapshot.interfaceDeclarations), (0, validateContextReferences_1.validateContextReferences)(ctx, snapshot.contextReferences)); | ||
var validationResult = (0, Result_1.concatResults)((0, validateMergedInterfaces_1.validateMergedInterfaces)(checker, snapshot.interfaceDeclarations), (0, validateDuplicateContextOrInfo_1.validateDuplicateContextOrInfo)(ctx)); | ||
var docResult = new Result_1.ResultPipe(validationResult) | ||
// Add the metadata directive definitions to definitions | ||
// found in the snapshot. | ||
.map(function () { return (0, metadataDirectives_1.addMetadataDirectives)(snapshot.definitions); }) | ||
// Filter out any `implements` clauses that are not GraphQL interfaces. | ||
.map(function (definitions) { return (0, filterNonGqlInterfaces_1.filterNonGqlInterfaces)(ctx, definitions); }) | ||
.map(function () { return (0, filterNonGqlInterfaces_1.filterNonGqlInterfaces)(ctx, snapshot.definitions); }) | ||
.andThen(function (definitions) { return (0, resolveResolverParams_1.resolveResolverParams)(ctx, definitions); }) | ||
.andThen(function (definitions) { return (0, resolveTypes_1.resolveTypes)(ctx, definitions); }) | ||
@@ -105,6 +116,13 @@ // If you define a field on an interface using the functional style, we need to add | ||
.andThen(function (doc) { return (0, applyDefaultNullability_1.applyDefaultNullability)(doc, config); }) | ||
// Ensure we have Query/Mutation/Subscription types if they've been extended with | ||
// `@gqlQueryField` and friends. | ||
.map(function (doc) { return (0, addImplicitRootTypes_1.addImplicitRootTypes)(doc); }) | ||
// Merge any `extend` definitions into their base definitions. | ||
.map(function (doc) { return (0, mergeExtensions_1.mergeExtensions)(doc); }) | ||
// Perform custom validations that reimplement spec validation rules | ||
// with more tailored error messages. | ||
.andThen(function (doc) { return (0, customSpecValidations_1.customSpecValidations)(doc); }) | ||
// Sort the definitions in the document to ensure a stable output. | ||
.map(function (doc) { return (0, sortSchemaAst_1.sortSchemaAst)(doc); }) | ||
.andThen(function (doc) { return specValidateSDL(doc); }) | ||
.result(); | ||
@@ -115,10 +133,19 @@ if (docResult.kind === "ERROR") { | ||
var doc = docResult.value; | ||
var resolvers = (0, makeResolverSignature_1.makeResolverSignature)(doc); | ||
// Build and validate the schema with regards to the GraphQL spec. | ||
return (new Result_1.ResultPipe(buildSchemaFromDoc(doc)) | ||
return (new Result_1.ResultPipe(buildSchema(doc)) | ||
// Apply the "Type Validation" sub-sections of the specification's | ||
// "Type System" section. | ||
.andThen(function (schema) { return specSchemaValidation(schema); }) | ||
// The above spec validation fails to catch type errors in directive | ||
// arguments, so Grats checks these manually. | ||
.andThen(function (schema) { return (0, validateDirectiveArguments_1.validateDirectiveArguments)(schema, doc); }) | ||
// Ensure that every type which implements an interface or is a member of a | ||
// union has a __typename field. | ||
.andThen(function (schema) { return (0, validateTypenames_1.validateTypenames)(schema, typesWithTypename); }) | ||
// Validate that semantic nullability directives are not in conflict | ||
// with type nullability. | ||
.andThen(function (schema) { return (0, validateSemanticNullability_1.validateSemanticNullability)(schema, config); }) | ||
// Combine the schema and document into a single result. | ||
.map(function (schema) { return ({ schema: schema, doc: doc }); }) | ||
.map(function (schema) { return ({ schema: schema, doc: doc, resolvers: resolvers }); }) | ||
.result()); | ||
@@ -128,5 +155,6 @@ }) | ||
} | ||
exports.extractSchemaAndDoc = extractSchemaAndDoc; | ||
// Given a SDL AST, build and validate a GraphQLSchema. | ||
function buildSchemaFromDoc(doc) { | ||
function buildSchema(doc) { | ||
return (0, Result_2.ok)((0, graphql_1.buildASTSchema)(doc, { assumeValidSDL: true })); | ||
} | ||
function specValidateSDL(doc) { | ||
// TODO: Currently this does not detect definitions that shadow builtins | ||
@@ -136,14 +164,16 @@ // (`String`, `Int`, etc). However, if we pass a second param (extending an | ||
// shadow builtins. | ||
var validationErrors = (0, validate_1.validateSDL)(doc); | ||
return asDiagnostics(doc, validate_1.validateSDL); | ||
} | ||
function specSchemaValidation(schema) { | ||
return asDiagnostics(schema, graphql_1.validateSchema); | ||
} | ||
// Utility to map GraphQL validation errors to a Result of | ||
function asDiagnostics(value, validate) { | ||
var validationErrors = validate(value).filter( | ||
// FIXME: Handle case where query is not defined (no location) | ||
function (e) { return e.source && e.locations && e.positions; }); | ||
if (validationErrors.length > 0) { | ||
return (0, Result_2.err)(validationErrors.map(DiagnosticError_1.graphQlErrorToDiagnostic)); | ||
} | ||
var schema = (0, graphql_1.buildASTSchema)(doc, { assumeValidSDL: true }); | ||
var diagnostics = (0, graphql_1.validateSchema)(schema) | ||
// FIXME: Handle case where query is not defined (no location) | ||
.filter(function (e) { return e.source && e.locations && e.positions; }); | ||
if (diagnostics.length > 0) { | ||
return (0, Result_2.err)(diagnostics.map(DiagnosticError_1.graphQlErrorToDiagnostic)); | ||
} | ||
return (0, Result_2.ok)(schema); | ||
return (0, Result_2.ok)(value); | ||
} | ||
@@ -156,4 +186,4 @@ // Given a list of snapshots, merge them into a single snapshot. | ||
nameDefinitions: new Map(), | ||
implicitNameDefinitions: new Map(), | ||
unresolvedNames: new Map(), | ||
contextReferences: [], | ||
typesWithTypename: new Set(), | ||
@@ -205,5 +235,5 @@ interfaceDeclarations: [], | ||
try { | ||
for (var _r = (e_5 = void 0, __values(snapshot.contextReferences)), _s = _r.next(); !_s.done; _s = _r.next()) { | ||
var contextReference = _s.value; | ||
result.contextReferences.push(contextReference); | ||
for (var _r = (e_5 = void 0, __values(snapshot.implicitNameDefinitions)), _s = _r.next(); !_s.done; _s = _r.next()) { | ||
var _t = __read(_s.value, 2), node = _t[0], definition = _t[1]; | ||
result.implicitNameDefinitions.set(node, definition); | ||
} | ||
@@ -219,4 +249,4 @@ } | ||
try { | ||
for (var _t = (e_6 = void 0, __values(snapshot.typesWithTypename)), _u = _t.next(); !_u.done; _u = _t.next()) { | ||
var typeName = _u.value; | ||
for (var _u = (e_6 = void 0, __values(snapshot.typesWithTypename)), _v = _u.next(); !_v.done; _v = _u.next()) { | ||
var typeName = _v.value; | ||
result.typesWithTypename.add(typeName); | ||
@@ -228,3 +258,3 @@ } | ||
try { | ||
if (_u && !_u.done && (_f = _t.return)) _f.call(_t); | ||
if (_v && !_v.done && (_f = _u.return)) _f.call(_u); | ||
} | ||
@@ -234,4 +264,4 @@ finally { if (e_6) throw e_6.error; } | ||
try { | ||
for (var _v = (e_7 = void 0, __values(snapshot.interfaceDeclarations)), _w = _v.next(); !_w.done; _w = _v.next()) { | ||
var interfaceDeclaration = _w.value; | ||
for (var _w = (e_7 = void 0, __values(snapshot.interfaceDeclarations)), _x = _w.next(); !_x.done; _x = _w.next()) { | ||
var interfaceDeclaration = _x.value; | ||
result.interfaceDeclarations.push(interfaceDeclaration); | ||
@@ -243,3 +273,3 @@ } | ||
try { | ||
if (_w && !_w.done && (_g = _v.return)) _g.call(_v); | ||
if (_x && !_x.done && (_g = _w.return)) _g.call(_w); | ||
} | ||
@@ -246,0 +276,0 @@ finally { if (e_7) throw e_7.error; } |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.locate = void 0; | ||
exports.locate = locate; | ||
var graphql_1 = require("graphql"); | ||
@@ -25,3 +25,3 @@ var Result_1 = require("./utils/Result"); | ||
} | ||
return (0, Result_1.ok)((0, helpers_1.loc)(type.astNode.name)); | ||
return (0, Result_1.ok)((0, helpers_1.nullThrows)(type.astNode.name.loc)); | ||
} | ||
@@ -40,5 +40,4 @@ if (!(type instanceof graphql_1.GraphQLObjectType || | ||
} | ||
return (0, Result_1.ok)((0, helpers_1.loc)(field.astNode.name)); | ||
return (0, Result_1.ok)((0, helpers_1.nullThrows)(field.astNode.name.loc)); | ||
} | ||
exports.locate = locate; | ||
var ENTITY_NAME_REGEX = /^([A-Za-z0-9_]+)(?:\.([A-Za-z0-9_]+))?$/; | ||
@@ -45,0 +44,0 @@ function parseEntityName(entityName) { |
import { DocumentNode, GraphQLSchema } from "graphql"; | ||
import { ConfigOptions } from "./gratsConfig"; | ||
import { GratsConfig } from "./gratsConfig"; | ||
import { Metadata } from "./metadata"; | ||
/** | ||
@@ -7,4 +8,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, resolvers: Metadata, config: GratsConfig, destination: string): string; | ||
export declare function applyTypeScriptHeader(config: GratsConfig, code: string): string; | ||
/** | ||
@@ -14,4 +15,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; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.printSDLWithoutMetadata = exports.applySDLHeader = exports.printGratsSDL = exports.applyTypeScriptHeader = exports.printExecutableSchema = void 0; | ||
exports.printExecutableSchema = printExecutableSchema; | ||
exports.applyTypeScriptHeader = applyTypeScriptHeader; | ||
exports.printGratsSDL = printGratsSDL; | ||
exports.applySDLHeader = applySDLHeader; | ||
exports.printSDLWithoutMetadata = printSDLWithoutMetadata; | ||
var graphql_1 = require("graphql"); | ||
var codegen_1 = require("./codegen"); | ||
var metadataDirectives_1 = require("./metadataDirectives"); | ||
var schemaCodegen_1 = require("./codegen/schemaCodegen"); | ||
var resolverMapCodegen_1 = require("./codegen/resolverMapCodegen"); | ||
/** | ||
@@ -11,11 +15,11 @@ * Prints code for a TypeScript module that exports a GraphQLSchema. | ||
*/ | ||
function printExecutableSchema(schema, config, destination) { | ||
var code = (0, codegen_1.codegen)(schema, destination); | ||
function printExecutableSchema(schema, resolvers, config, destination) { | ||
var code = config.EXPERIMENTAL__emitResolverMap | ||
? (0, resolverMapCodegen_1.resolverMapCodegen)(schema, resolvers, config, destination) | ||
: (0, schemaCodegen_1.codegen)(schema, resolvers, config, destination); | ||
return applyTypeScriptHeader(config, code); | ||
} | ||
exports.printExecutableSchema = printExecutableSchema; | ||
function applyTypeScriptHeader(config, code) { | ||
return formatHeader(config.tsSchemaHeader, code); | ||
} | ||
exports.applyTypeScriptHeader = applyTypeScriptHeader; | ||
/** | ||
@@ -29,15 +33,7 @@ * Prints SDL, potentially omitting directives depending upon the config. | ||
} | ||
exports.printGratsSDL = printGratsSDL; | ||
function applySDLHeader(config, sdl) { | ||
return formatHeader(config.schemaHeader, sdl); | ||
} | ||
exports.applySDLHeader = applySDLHeader; | ||
function printSDLWithoutMetadata(doc) { | ||
var trimmed = (0, graphql_1.visit)(doc, { | ||
DirectiveDefinition: function (t) { | ||
return metadataDirectives_1.METADATA_DIRECTIVE_NAMES.has(t.name.value) ? null : t; | ||
}, | ||
Directive: function (t) { | ||
return metadataDirectives_1.METADATA_DIRECTIVE_NAMES.has(t.name.value) ? null : t; | ||
}, | ||
ScalarTypeDefinition: function (t) { | ||
@@ -51,3 +47,2 @@ return graphql_1.specifiedScalarTypes.some(function (scalar) { return scalar.name === t.name.value; }) | ||
} | ||
exports.printSDLWithoutMetadata = printSDLWithoutMetadata; | ||
function formatHeader(header, code) { | ||
@@ -54,0 +49,0 @@ if (header !== null) { |
@@ -28,3 +28,5 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.makeSemanticNonNullDirective = exports.addSemanticNonNullDirective = exports.DIRECTIVES_AST = exports.SEMANTIC_NON_NULL_DIRECTIVE = void 0; | ||
exports.DIRECTIVES_AST = exports.SEMANTIC_NON_NULL_DIRECTIVE = void 0; | ||
exports.addSemanticNonNullDirective = addSemanticNonNullDirective; | ||
exports.makeSemanticNonNullDirective = makeSemanticNonNullDirective; | ||
var graphql_1 = require("graphql"); | ||
@@ -43,3 +45,2 @@ var helpers_1 = require("./utils/helpers"); | ||
} | ||
exports.addSemanticNonNullDirective = addSemanticNonNullDirective; | ||
function makeSemanticNonNullDirective(loc) { | ||
@@ -57,2 +58,1 @@ return { | ||
} | ||
exports.makeSemanticNonNullDirective = makeSemanticNonNullDirective; |
"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); | ||
}; | ||
var __values = (this && this.__values) || function(o) { | ||
@@ -25,3 +14,3 @@ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.addInterfaceFields = void 0; | ||
exports.addInterfaceFields = addInterfaceFields; | ||
var E = require("../Errors"); | ||
@@ -34,3 +23,2 @@ var graphql_1 = require("graphql"); | ||
var Extractor_1 = require("../Extractor"); | ||
var metadataDirectives_1 = require("../metadataDirectives"); | ||
/** | ||
@@ -78,3 +66,2 @@ * Grats allows you to define GraphQL fields on TypeScript interfaces using | ||
} | ||
exports.addInterfaceFields = addInterfaceFields; | ||
// A field definition may be on a concrete type, or on an interface. If it's on an interface, | ||
@@ -84,3 +71,3 @@ // we need to add it to each concrete type that implements the interface. | ||
var e_2, _a; | ||
var _b, _c; | ||
var _b; | ||
var newDocs = []; | ||
@@ -106,19 +93,14 @@ var definitionResult = ctx.gqlNameDefinitionForGqlName(doc.name); | ||
// to the interface, and to each type that implements the interface. | ||
// The interface field definition is not executable, so we don't | ||
// need to annotate it with the details of the implementation. | ||
var directives = (_c = field.directives) === null || _c === void 0 ? void 0 : _c.filter(function (directive) { | ||
return directive.name.value !== metadataDirectives_1.FIELD_METADATA_DIRECTIVE; | ||
}); | ||
newDocs.push({ | ||
kind: graphql_1.Kind.INTERFACE_TYPE_EXTENSION, | ||
name: doc.name, | ||
fields: [__assign(__assign({}, field), { directives: directives })], | ||
fields: [field], | ||
}); | ||
try { | ||
for (var _d = __values(interfaceGraph.get(nameDefinition.name.value)), _e = _d.next(); !_e.done; _e = _d.next()) { | ||
var implementor = _e.value; | ||
for (var _c = __values(interfaceGraph.get(nameDefinition.name.value)), _d = _c.next(); !_d.done; _d = _c.next()) { | ||
var implementor = _d.value; | ||
var name = { | ||
kind: graphql_1.Kind.NAME, | ||
value: implementor.name, | ||
loc: doc.loc, | ||
loc: doc.loc, // Bit of a lie, but I don't see a better option. | ||
tsIdentifier: (0, helpers_1.uniqueId)(), | ||
@@ -139,3 +121,3 @@ }; | ||
name: name, | ||
fields: [__assign(__assign({}, field), { directives: directives })], | ||
fields: [field], | ||
loc: doc.loc, | ||
@@ -150,3 +132,3 @@ }); | ||
try { | ||
if (_e && !_e.done && (_a = _d.return)) _a.call(_d); | ||
if (_d && !_d.done && (_a = _c.return)) _a.call(_c); | ||
} | ||
@@ -159,6 +141,4 @@ finally { if (e_2) throw e_2.error; } | ||
// Extending any other type of definition is not supported. | ||
var loc = (0, helpers_1.nullThrows)(doc.name.loc); | ||
var relatedLoc = (0, helpers_1.nullThrows)(nameDefinition.name.loc); | ||
return (0, Result_1.err)((0, DiagnosticError_1.gqlErr)(loc, E.invalidTypePassedToFieldFunction(), [ | ||
(0, DiagnosticError_1.gqlRelated)(relatedLoc, "This is the type that was passed to `@".concat(Extractor_1.FIELD_TAG, "`.")), | ||
return (0, Result_1.err)((0, DiagnosticError_1.gqlErr)(doc.name, E.invalidTypePassedToFieldFunction(), [ | ||
(0, DiagnosticError_1.gqlRelated)(nameDefinition.name, "This is the type that was passed to `@".concat(Extractor_1.FIELD_TAG, "`.")), | ||
])); | ||
@@ -165,0 +145,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>; |
@@ -39,3 +39,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.applyDefaultNullability = void 0; | ||
exports.applyDefaultNullability = applyDefaultNullability; | ||
var graphql_1 = require("graphql"); | ||
@@ -45,3 +45,2 @@ var DiagnosticError_1 = require("../utils/DiagnosticError"); | ||
var E = require("../Errors"); | ||
var metadataDirectives_1 = require("../metadataDirectives"); | ||
var publicDirectives_1 = require("../publicDirectives"); | ||
@@ -61,12 +60,12 @@ var GraphQLConstructor_1 = require("../GraphQLConstructor"); | ||
_b[graphql_1.Kind.FIELD_DEFINITION] = function (t) { | ||
var _a, _b; | ||
var killsParent = (_a = t.directives) === null || _a === void 0 ? void 0 : _a.find(function (d) { return d.name.value === metadataDirectives_1.KILLS_PARENT_ON_EXCEPTION_DIRECTIVE; }); | ||
var _a; | ||
var killsParent = t.killsParentOnException; | ||
if (killsParent) { | ||
// You can only use @killsParentOnException if nullableByDefault is on. | ||
if (!nullableByDefault) { | ||
errors.push((0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(killsParent), E.killsParentOnExceptionWithWrongConfig())); | ||
errors.push((0, DiagnosticError_1.gqlErr)(killsParent, E.killsParentOnExceptionWithWrongConfig())); | ||
} | ||
// You can't use @killsParentOnException if it's been typed as nullable | ||
if (t.type.kind !== graphql_1.Kind.NON_NULL_TYPE) { | ||
errors.push((0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(killsParent), E.killsParentOnExceptionOnNullable())); | ||
errors.push((0, DiagnosticError_1.gqlErr)(killsParent, E.killsParentOnExceptionOnNullable())); | ||
} | ||
@@ -80,5 +79,5 @@ // Set the location of the NON_NULL_TYPE wrapper to the location of the | ||
var type = gql.nullableType(t.type); | ||
var directives = (_b = t.directives) !== null && _b !== void 0 ? _b : []; | ||
var directives = (_a = t.directives) !== null && _a !== void 0 ? _a : []; | ||
if (strictSemanticNullability) { | ||
var semanticNullability = (0, publicDirectives_1.makeSemanticNonNullDirective)((0, helpers_1.loc)(t.type)); | ||
var semanticNullability = (0, publicDirectives_1.makeSemanticNonNullDirective)((0, helpers_1.nullThrows)(t.type.loc)); | ||
directives = __spreadArray(__spreadArray([], __read(directives), false), [semanticNullability], false); | ||
@@ -99,2 +98,1 @@ } | ||
} | ||
exports.applyDefaultNullability = applyDefaultNullability; |
@@ -14,3 +14,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.filterNonGqlInterfaces = void 0; | ||
exports.filterNonGqlInterfaces = filterNonGqlInterfaces; | ||
var graphql_1 = require("graphql"); | ||
@@ -34,3 +34,2 @@ /** | ||
} | ||
exports.filterNonGqlInterfaces = filterNonGqlInterfaces; | ||
function filterInterfaces(ctx, t) { | ||
@@ -37,0 +36,0 @@ if (t.interfaces == null || t.interfaces.length === 0) { |
@@ -39,3 +39,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.mergeExtensions = void 0; | ||
exports.mergeExtensions = mergeExtensions; | ||
var graphql_1 = require("graphql"); | ||
@@ -94,3 +94,2 @@ var helpers_1 = require("../utils/helpers"); | ||
} | ||
exports.mergeExtensions = mergeExtensions; | ||
// Map a key to an array of values. | ||
@@ -97,0 +96,0 @@ var MultiMap = /** @class */ (function () { |
@@ -41,3 +41,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.resolveTypes = void 0; | ||
exports.resolveTypes = resolveTypes; | ||
var graphql_1 = require("graphql"); | ||
@@ -60,3 +60,2 @@ var GraphQLConstructor_1 = require("../GraphQLConstructor"); | ||
} | ||
exports.resolveTypes = resolveTypes; | ||
/** | ||
@@ -291,4 +290,4 @@ * Template extraction happens in two phases and resolves named type references | ||
if (definition.interfaces && definition.interfaces.length > 0) { | ||
var loc_1 = (0, helpers_1.loc)(definition.interfaces[0].name); | ||
this._errors.push((0, DiagnosticError_1.gqlErr)(loc_1, E.genericTypeImplementsInterface())); | ||
var item = definition.interfaces[0].name; | ||
this._errors.push((0, DiagnosticError_1.gqlErr)(item, E.genericTypeImplementsInterface())); | ||
} | ||
@@ -335,4 +334,4 @@ } | ||
definition.kind === graphql_1.Kind.UNION_TYPE_DEFINITION || | ||
definition.kind === graphql_1.Kind.INPUT_OBJECT_TYPE_DEFINITION || | ||
definition.kind === graphql_1.Kind.INTERFACE_TYPE_DEFINITION); | ||
definition.kind === graphql_1.Kind.INTERFACE_TYPE_DEFINITION || | ||
definition.kind === graphql_1.Kind.INPUT_OBJECT_TYPE_DEFINITION); | ||
} | ||
@@ -339,0 +338,0 @@ function getTypeParameters(declaration) { |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.extractSnapshotsFromProgram = void 0; | ||
exports.extractSnapshotsFromProgram = extractSnapshotsFromProgram; | ||
var ts = require("typescript"); | ||
@@ -49,2 +49,1 @@ var Extractor_1 = require("../Extractor"); | ||
} | ||
exports.extractSnapshotsFromProgram = extractSnapshotsFromProgram; |
@@ -14,3 +14,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.sortSchemaAst = void 0; | ||
exports.sortSchemaAst = sortSchemaAst; | ||
var graphql_1 = require("graphql"); | ||
@@ -65,3 +65,2 @@ var naturalCompare_1 = require("../utils/naturalCompare"); | ||
} | ||
exports.sortSchemaAst = sortSchemaAst; | ||
// Given an optional array of AST nodes, sort them by name or kind. | ||
@@ -68,0 +67,0 @@ function sortNamed(arr) { |
@@ -39,4 +39,7 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.initTsPlugin = void 0; | ||
exports.initTsPlugin = initTsPlugin; | ||
var typescript_1 = require("typescript"); | ||
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 | ||
@@ -78,2 +81,18 @@ // which reports diagnostics for the current file. Currently it only reports | ||
} | ||
if (ts.version !== typescript_1.version) { | ||
proxy.getCompilerOptionsDiagnostics = function () { | ||
var prev = info.languageService.getCompilerOptionsDiagnostics(); | ||
return __spreadArray(__spreadArray([], __read(prev), false), [ | ||
{ | ||
category: ts.DiagnosticCategory.Error, | ||
code: 0, | ||
messageText: typeScriptVersionMismatch(ts.version), | ||
file: undefined, | ||
start: undefined, | ||
length: undefined, | ||
}, | ||
], false); | ||
}; | ||
return proxy; | ||
} | ||
proxy.getSyntacticDiagnostics = function (filename) { | ||
@@ -90,2 +109,32 @@ var _a; | ||
}; | ||
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; | ||
@@ -95,2 +144,4 @@ } | ||
} | ||
exports.initTsPlugin = initTsPlugin; | ||
function typeScriptVersionMismatch(extensionVersion) { | ||
return "grats-plugin-ts error: The version of TypeScript picked up by Grats does not match the version used by VSCode.\nGrats is using ".concat(typescript_1.version, " but VSCode is using ").concat(extensionVersion, ".\nThis may be caused by a yarn.lock or package-lock.json which is pinning a different version of TypeScript for Grats than the version used by the rest of your project.\nSee https://github.com/captbaritone/grats/issues/142> for more information."); | ||
} |
import { InputObjectTypeDefinitionNode, InterfaceTypeDefinitionNode, NameNode, ObjectTypeDefinitionNode, UnionTypeDefinitionNode } from "graphql"; | ||
import * as ts from "typescript"; | ||
import { DiagnosticResult } from "./utils/DiagnosticError"; | ||
import { DiagnosticResult, DiagnosticsResult } from "./utils/DiagnosticError"; | ||
import { ExtractionSnapshot } from "./Extractor"; | ||
import { ResolverArgument } from "./resolverSignature"; | ||
export declare const UNRESOLVED_REFERENCE_NAME = "__UNRESOLVED_REFERENCE__"; | ||
export type DerivedResolverDefinition = { | ||
name: NameNode; | ||
path: string; | ||
exportName: string | null; | ||
args: ResolverArgument[]; | ||
kind: "DERIVED_CONTEXT"; | ||
}; | ||
export type NameDefinition = { | ||
name: NameNode; | ||
kind: "TYPE" | "INTERFACE" | "UNION" | "SCALAR" | "INPUT_OBJECT" | "ENUM"; | ||
kind: "TYPE" | "INTERFACE" | "UNION" | "SCALAR" | "INPUT_OBJECT" | "ENUM" | "CONTEXT" | "INFO"; | ||
}; | ||
export type DeclarationDefinition = NameDefinition | DerivedResolverDefinition; | ||
type TsIdentifier = number; | ||
@@ -25,9 +34,10 @@ /** | ||
checker: ts.TypeChecker; | ||
_declarationToName: Map<ts.Declaration, NameDefinition>; | ||
_declarationToDefinition: Map<ts.Declaration, DeclarationDefinition>; | ||
_unresolvedNodes: Map<TsIdentifier, ts.EntityName>; | ||
_idToDeclaration: Map<TsIdentifier, ts.Declaration>; | ||
static fromSnapshot(checker: ts.TypeChecker, snapshot: ExtractionSnapshot): TypeContext; | ||
static fromSnapshot(checker: ts.TypeChecker, snapshot: ExtractionSnapshot): DiagnosticsResult<TypeContext>; | ||
constructor(checker: ts.TypeChecker); | ||
private _recordTypeName; | ||
private _recordDeclaration; | ||
private _markUnresolvedType; | ||
allDefinitions(): Iterable<DeclarationDefinition>; | ||
findSymbolDeclaration(startSymbol: ts.Symbol): ts.Declaration | null; | ||
@@ -37,3 +47,3 @@ private resolveSymbol; | ||
unresolvedNameIsGraphQL(unresolved: NameNode): boolean; | ||
gqlNameDefinitionForGqlName(nameNode: NameNode): DiagnosticResult<NameDefinition>; | ||
gqlNameDefinitionForGqlName(nameNode: NameNode): DiagnosticResult<DeclarationDefinition>; | ||
gqlNameForTsName(node: ts.EntityName): DiagnosticResult<string>; | ||
@@ -40,0 +50,0 @@ private maybeTsDeclarationForTsName; |
@@ -46,3 +46,2 @@ "use strict"; | ||
var E = require("./Errors"); | ||
var helpers_1 = require("./utils/helpers"); | ||
exports.UNRESOLVED_REFERENCE_NAME = "__UNRESOLVED_REFERENCE__"; | ||
@@ -63,3 +62,3 @@ /** | ||
function TypeContext(checker) { | ||
this._declarationToName = new Map(); | ||
this._declarationToDefinition = new Map(); | ||
this._unresolvedNodes = new Map(); | ||
@@ -70,7 +69,8 @@ this._idToDeclaration = new Map(); | ||
TypeContext.fromSnapshot = function (checker, snapshot) { | ||
var e_1, _a, e_2, _b; | ||
var e_1, _a, e_2, _b, e_3, _c; | ||
var errors = []; | ||
var self = new TypeContext(checker); | ||
try { | ||
for (var _c = __values(snapshot.unresolvedNames), _d = _c.next(); !_d.done; _d = _c.next()) { | ||
var _e = __read(_d.value, 2), node = _e[0], typeName = _e[1]; | ||
for (var _d = __values(snapshot.unresolvedNames), _e = _d.next(); !_e.done; _e = _d.next()) { | ||
var _f = __read(_e.value, 2), node = _f[0], typeName = _f[1]; | ||
self._markUnresolvedType(node, typeName); | ||
@@ -82,3 +82,3 @@ } | ||
try { | ||
if (_d && !_d.done && (_a = _c.return)) _a.call(_c); | ||
if (_e && !_e.done && (_a = _d.return)) _a.call(_d); | ||
} | ||
@@ -88,5 +88,5 @@ finally { if (e_1) throw e_1.error; } | ||
try { | ||
for (var _f = __values(snapshot.nameDefinitions), _g = _f.next(); !_g.done; _g = _f.next()) { | ||
var _h = __read(_g.value, 2), node = _h[0], definition = _h[1]; | ||
self._recordTypeName(node, definition.name, definition.kind); | ||
for (var _g = __values(snapshot.nameDefinitions), _h = _g.next(); !_h.done; _h = _g.next()) { | ||
var _j = __read(_h.value, 2), node = _j[0], definition = _j[1]; | ||
self._recordDeclaration(node, definition); | ||
} | ||
@@ -97,13 +97,42 @@ } | ||
try { | ||
if (_g && !_g.done && (_b = _f.return)) _b.call(_f); | ||
if (_h && !_h.done && (_b = _g.return)) _b.call(_g); | ||
} | ||
finally { if (e_2) throw e_2.error; } | ||
} | ||
return self; | ||
try { | ||
for (var _k = __values(snapshot.implicitNameDefinitions), _l = _k.next(); !_l.done; _l = _k.next()) { | ||
var _m = __read(_l.value, 2), definition = _m[0], reference = _m[1]; | ||
var declaration = self.maybeTsDeclarationForTsName(reference.typeName); | ||
if (declaration == null) { | ||
errors.push((0, DiagnosticError_1.tsErr)(reference.typeName, E.unresolvedTypeReference())); | ||
continue; | ||
} | ||
var existing = self._declarationToDefinition.get(declaration); | ||
if (existing != null) { | ||
errors.push((0, DiagnosticError_1.tsErr)(declaration, "Multiple derived contexts defined for given type", [ | ||
(0, DiagnosticError_1.gqlRelated)(definition.name, "One was defined here"), | ||
(0, DiagnosticError_1.gqlRelated)(existing.name, "Another here"), | ||
])); | ||
continue; | ||
} | ||
self._recordDeclaration(declaration, definition); | ||
} | ||
} | ||
catch (e_3_1) { e_3 = { error: e_3_1 }; } | ||
finally { | ||
try { | ||
if (_l && !_l.done && (_c = _k.return)) _c.call(_k); | ||
} | ||
finally { if (e_3) throw e_3.error; } | ||
} | ||
if (errors.length > 0) { | ||
return (0, Result_1.err)(errors); | ||
} | ||
return (0, Result_1.ok)(self); | ||
}; | ||
// Record that a GraphQL construct of type `kind` with the name `name` is | ||
// declared at `node`. | ||
TypeContext.prototype._recordTypeName = function (node, name, kind) { | ||
this._idToDeclaration.set(name.tsIdentifier, node); | ||
this._declarationToName.set(node, { name: name, kind: kind }); | ||
TypeContext.prototype._recordDeclaration = function (node, definition) { | ||
this._idToDeclaration.set(definition.name.tsIdentifier, node); | ||
this._declarationToDefinition.set(node, definition); | ||
}; | ||
@@ -114,2 +143,5 @@ // Record that a type references `node` | ||
}; | ||
TypeContext.prototype.allDefinitions = function () { | ||
return this._declarationToDefinition.values(); | ||
}; | ||
TypeContext.prototype.findSymbolDeclaration = function (startSymbol) { | ||
@@ -148,8 +180,11 @@ var _a; | ||
if (ts.isTypeParameterDeclaration(declarationResult.value)) { | ||
return (0, Result_1.err)((0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(unresolved), "Type parameters are not supported in this context.")); | ||
return (0, Result_1.err)((0, DiagnosticError_1.gqlErr)(unresolved, "Type parameters are not supported in this context.")); | ||
} | ||
var nameDefinition = this._declarationToName.get(declarationResult.value); | ||
var nameDefinition = this._declarationToDefinition.get(declarationResult.value); | ||
if (nameDefinition == null) { | ||
return (0, Result_1.err)((0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(unresolved), E.unresolvedTypeReference())); | ||
return (0, Result_1.err)((0, DiagnosticError_1.gqlErr)(unresolved, E.unresolvedTypeReference())); | ||
} | ||
if (nameDefinition.kind === "CONTEXT" || nameDefinition.kind === "INFO") { | ||
return (0, Result_1.err)((0, DiagnosticError_1.gqlErr)(unresolved, E.contextOrInfoUsedInGraphQLPosition(nameDefinition.kind), [(0, DiagnosticError_1.gqlRelated)(nameDefinition.name, "Defined here")])); | ||
} | ||
return (0, Result_1.ok)(__assign(__assign({}, unresolved), { value: nameDefinition.name.value })); | ||
@@ -164,3 +199,3 @@ }; | ||
return false; | ||
return this._declarationToName.has(declaration); | ||
return this._declarationToDefinition.has(declaration); | ||
}; | ||
@@ -174,7 +209,7 @@ TypeContext.prototype.gqlNameDefinitionForGqlName = function (nameNode) { | ||
if (declaration == null) { | ||
return (0, Result_1.err)((0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(nameNode), E.unresolvedTypeReference())); | ||
return (0, Result_1.err)((0, DiagnosticError_1.gqlErr)(nameNode, E.unresolvedTypeReference())); | ||
} | ||
var definition = this._declarationToName.get(declaration); | ||
var definition = this._declarationToDefinition.get(declaration); | ||
if (definition == null) { | ||
throw new Error("Expected to find name definition."); | ||
return (0, Result_1.err)((0, DiagnosticError_1.gqlErr)(nameNode, E.unresolvedTypeReference())); | ||
} | ||
@@ -194,6 +229,11 @@ return (0, Result_1.ok)(definition); | ||
} | ||
var nameDefinition = this._declarationToName.get(declarationResult.value); | ||
var nameDefinition = this._declarationToDefinition.get(declarationResult.value); | ||
if (nameDefinition == null) { | ||
return (0, Result_1.err)((0, DiagnosticError_1.tsErr)(node, E.unresolvedTypeReference())); | ||
} | ||
if (nameDefinition.kind === "CONTEXT" || nameDefinition.kind === "INFO") { | ||
return (0, Result_1.err)((0, DiagnosticError_1.tsErr)(node, E.contextOrInfoUsedInGraphQLPosition(nameDefinition.kind), [ | ||
(0, DiagnosticError_1.gqlRelated)(nameDefinition.name, "Defined here"), | ||
])); | ||
} | ||
return (0, Result_1.ok)(nameDefinition.name.value); | ||
@@ -219,2 +259,3 @@ }; | ||
if (!declaration) { | ||
console.log(definition); | ||
throw new Error("Could not find declaration for ".concat(name.value)); | ||
@@ -221,0 +262,0 @@ } |
@@ -0,1 +1,2 @@ | ||
import type { GraphQLResolveInfo } from "graphql"; | ||
/** @gqlScalar */ | ||
@@ -7,1 +8,3 @@ export type Float = number; | ||
export type ID = string; | ||
/** @gqlInfo */ | ||
export type GqlInfo = GraphQLResolveInfo; |
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,12 @@ 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 locationlessErr(message: string): ts.Diagnostic; | ||
export declare function gqlErr(item: { | ||
loc?: Location; | ||
}, message: string, relatedInformation?: ts.DiagnosticRelatedInformation[]): ts.DiagnosticWithLocation; | ||
export declare function gqlRelated(item: { | ||
loc?: Location; | ||
}, message: string): ts.DiagnosticRelatedInformation; | ||
export declare function rangeErr(file: ts.SourceFile, commentRange: ts.CommentRange, message: string, relatedInformation?: ts.DiagnosticRelatedInformation[], fix?: ts.CodeFixAction): FixableDiagnosticWithLocation; | ||
/** | ||
@@ -33,4 +44,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 {}; |
@@ -30,3 +30,11 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.graphqlSourceToSourceFile = exports.tsRelated = exports.tsErr = exports.rangeErr = exports.gqlRelated = exports.gqlErr = exports.graphQlErrorToDiagnostic = exports.FAKE_ERROR_CODE = exports.ReportableDiagnostics = void 0; | ||
exports.FAKE_ERROR_CODE = exports.ReportableDiagnostics = void 0; | ||
exports.graphQlErrorToDiagnostic = graphQlErrorToDiagnostic; | ||
exports.locationlessErr = locationlessErr; | ||
exports.gqlErr = gqlErr; | ||
exports.gqlRelated = gqlRelated; | ||
exports.rangeErr = rangeErr; | ||
exports.tsErr = tsErr; | ||
exports.tsRelated = tsRelated; | ||
exports.graphqlSourceToSourceFile = graphqlSourceToSourceFile; | ||
var ts = require("typescript"); | ||
@@ -63,3 +71,3 @@ var ReportableDiagnostics = /** @class */ (function () { | ||
// 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) { | ||
@@ -97,3 +105,3 @@ // eslint-disable-next-line no-control-regex | ||
} | ||
relatedInformation.push(gqlRelated(relatedNode.loc, "Related location")); | ||
relatedInformation.push(gqlRelated(relatedNode, "Related location")); | ||
} | ||
@@ -126,6 +134,20 @@ } | ||
} | ||
exports.graphQlErrorToDiagnostic = graphQlErrorToDiagnostic; | ||
function gqlErr(loc, message, relatedInformation) { | ||
function locationlessErr(message) { | ||
return { | ||
messageText: message, | ||
file: undefined, | ||
code: exports.FAKE_ERROR_CODE, | ||
category: ts.DiagnosticCategory.Error, | ||
start: undefined, | ||
length: undefined, | ||
source: "Grats", | ||
}; | ||
} | ||
function gqlErr(item, message, relatedInformation) { | ||
if (item.loc == null) { | ||
throw new Error("Expected item to have loc"); | ||
} | ||
var loc = item.loc; | ||
return { | ||
messageText: message, | ||
file: graphqlSourceToSourceFile(loc.source), | ||
@@ -140,4 +162,7 @@ code: exports.FAKE_ERROR_CODE, | ||
} | ||
exports.gqlErr = gqlErr; | ||
function gqlRelated(loc, message) { | ||
function gqlRelated(item, message) { | ||
if (item.loc == null) { | ||
throw new Error("Expected item to have loc"); | ||
} | ||
var loc = item.loc; | ||
return { | ||
@@ -152,4 +177,3 @@ category: ts.DiagnosticCategory.Message, | ||
} | ||
exports.gqlRelated = gqlRelated; | ||
function rangeErr(file, commentRange, message, relatedInformation) { | ||
function rangeErr(file, commentRange, message, relatedInformation, fix) { | ||
var start = commentRange.pos; | ||
@@ -166,6 +190,6 @@ 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(); | ||
@@ -183,5 +207,5 @@ var length = node.getEnd() - start; | ||
source: "Grats", | ||
fix: fix, | ||
}; | ||
} | ||
exports.tsErr = tsErr; | ||
function tsRelated(node, message) { | ||
@@ -197,6 +221,4 @@ return { | ||
} | ||
exports.tsRelated = tsRelated; | ||
function graphqlSourceToSourceFile(source) { | ||
return ts.createSourceFile(source.name, source.body, ts.ScriptTarget.Latest); | ||
} | ||
exports.graphqlSourceToSourceFile = graphqlSourceToSourceFile; |
@@ -1,2 +0,1 @@ | ||
import { Location } from "graphql"; | ||
export declare class DefaultMap<K, V> { | ||
@@ -9,5 +8,2 @@ private readonly getDefault; | ||
export declare function extend<T>(a: T[], b: readonly T[]): void; | ||
export declare function loc(item: { | ||
loc?: Location; | ||
}): Location; | ||
export declare function astNode<T>(item: { | ||
@@ -17,2 +13,4 @@ astNode?: T | undefined | null; | ||
export declare function uniqueId(): number; | ||
export declare function invariant(condition: unknown, message: string): asserts condition; | ||
export declare function nullThrows<T>(value: T | null | undefined): T; | ||
export declare function isNonNull<T>(value: T | null | undefined): value is T; |
@@ -14,3 +14,9 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.nullThrows = exports.uniqueId = exports.astNode = exports.loc = exports.extend = exports.DefaultMap = void 0; | ||
exports.DefaultMap = void 0; | ||
exports.extend = extend; | ||
exports.astNode = astNode; | ||
exports.uniqueId = uniqueId; | ||
exports.invariant = invariant; | ||
exports.nullThrows = nullThrows; | ||
exports.isNonNull = isNonNull; | ||
var DefaultMap = /** @class */ (function () { | ||
@@ -48,10 +54,2 @@ function DefaultMap(getDefault) { | ||
} | ||
exports.extend = extend; | ||
function loc(item) { | ||
if (item.loc == null) { | ||
throw new Error("Expected item to have loc"); | ||
} | ||
return item.loc; | ||
} | ||
exports.loc = loc; | ||
function astNode(item) { | ||
@@ -63,3 +61,2 @@ if (item.astNode == null) { | ||
} | ||
exports.astNode = astNode; | ||
var i = 0; | ||
@@ -69,3 +66,7 @@ function uniqueId() { | ||
} | ||
exports.uniqueId = uniqueId; | ||
function invariant(condition, message) { | ||
if (!condition) { | ||
throw new Error("Grats Error. Invariant failed: ".concat(message, ". This error represents an error in Grats. Please report it.")); | ||
} | ||
} | ||
function nullThrows(value) { | ||
@@ -77,2 +78,6 @@ if (value == null) { | ||
} | ||
exports.nullThrows = nullThrows; | ||
// Predicate function for filtering out null values | ||
// Includes TypeScript refinement for narrowing the type | ||
function isNonNull(value) { | ||
return value != null; | ||
} |
@@ -14,3 +14,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.traverseJSDocTags = void 0; | ||
exports.traverseJSDocTags = traverseJSDocTags; | ||
var ts = require("typescript"); | ||
@@ -51,2 +51,1 @@ // Recursively search for all JSDoc tags calling `cb` on each one with its | ||
} | ||
exports.traverseJSDocTags = traverseJSDocTags; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.naturalCompare = void 0; | ||
exports.naturalCompare = naturalCompare; | ||
/** | ||
@@ -52,3 +52,2 @@ * Returns a number indicating whether a reference string comes before, or after, | ||
} | ||
exports.naturalCompare = naturalCompare; | ||
var DIGIT_0 = 48; | ||
@@ -55,0 +54,0 @@ var DIGIT_9 = 57; |
@@ -39,3 +39,7 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.concatResults = exports.collectResults = exports.ResultPipe = exports.err = exports.ok = void 0; | ||
exports.ResultPipe = void 0; | ||
exports.ok = ok; | ||
exports.err = err; | ||
exports.collectResults = collectResults; | ||
exports.concatResults = concatResults; | ||
// Create a new `Result` in an OK state. | ||
@@ -45,3 +49,2 @@ function ok(value) { | ||
} | ||
exports.ok = ok; | ||
// Create a new `Result` in an ERROR state. | ||
@@ -51,3 +54,2 @@ function err(err) { | ||
} | ||
exports.err = err; | ||
/** | ||
@@ -117,3 +119,2 @@ * Helper class for chaining together a series of `Result` operations. | ||
} | ||
exports.collectResults = collectResults; | ||
function concatResults(result1, result2) { | ||
@@ -131,2 +132,1 @@ if (result1.kind === "ERROR" && result2.kind === "ERROR") { | ||
} | ||
exports.concatResults = concatResults; |
@@ -14,3 +14,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.validateAsyncIterable = void 0; | ||
exports.validateAsyncIterable = validateAsyncIterable; | ||
var graphql_1 = require("graphql"); | ||
@@ -20,3 +20,2 @@ var DiagnosticError_1 = require("../utils/DiagnosticError"); | ||
var E = require("../Errors"); | ||
var helpers_1 = require("../utils/helpers"); | ||
/** | ||
@@ -42,3 +41,3 @@ * Ensure that all fields on `Subscription` return an AsyncIterable and transform | ||
if (inner.kind !== graphql_1.Kind.LIST_TYPE || !inner.isAsyncIterable) { | ||
errors.push((0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(field.type), E.subscriptionFieldNotAsyncIterable())); | ||
errors.push((0, DiagnosticError_1.gqlErr)(field.type, E.subscriptionFieldNotAsyncIterable())); | ||
return field; | ||
@@ -67,3 +66,2 @@ } | ||
} | ||
exports.validateAsyncIterable = validateAsyncIterable; | ||
function innerType(type) { | ||
@@ -70,0 +68,0 @@ if (type.kind === graphql_1.Kind.NON_NULL_TYPE) { |
@@ -14,3 +14,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.validateMergedInterfaces = void 0; | ||
exports.validateMergedInterfaces = validateMergedInterfaces; | ||
var ts = require("typescript"); | ||
@@ -70,2 +70,1 @@ var E = require("../Errors"); | ||
} | ||
exports.validateMergedInterfaces = validateMergedInterfaces; |
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>; |
@@ -14,3 +14,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.validateSemanticNullability = void 0; | ||
exports.validateSemanticNullability = validateSemanticNullability; | ||
var graphql_1 = require("graphql"); | ||
@@ -61,5 +61,3 @@ var DiagnosticError_1 = require("../utils/DiagnosticError"); | ||
if (typeSemanticNonNull == null) { | ||
errors.push((0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(interfaceSemanticNonNull), "Interface field `".concat(implementor.name, ".").concat(implementorField.name, "` expects a non-nullable type but `").concat(interfaceType.name, ".").concat(interfaceField.name, "` is nullable."), [ | ||
(0, DiagnosticError_1.gqlRelated)((0, helpers_1.loc)((0, helpers_1.astNode)(implementorField).type), "Related location"), | ||
])); | ||
errors.push((0, DiagnosticError_1.gqlErr)(interfaceSemanticNonNull, "Interface field `".concat(implementor.name, ".").concat(implementorField.name, "` expects a non-nullable type but `").concat(interfaceType.name, ".").concat(interfaceField.name, "` is nullable."), [(0, DiagnosticError_1.gqlRelated)((0, helpers_1.astNode)(implementorField).type, "Related location")])); | ||
} | ||
@@ -98,3 +96,2 @@ } | ||
} | ||
exports.validateSemanticNullability = validateSemanticNullability; | ||
function findSemanticNonNull(field) { | ||
@@ -101,0 +98,0 @@ var _a, _b; |
@@ -14,3 +14,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.validateTypenames = void 0; | ||
exports.validateTypenames = validateTypenames; | ||
var graphql_1 = require("graphql"); | ||
@@ -32,3 +32,2 @@ var DiagnosticError_1 = require("../utils/DiagnosticError"); | ||
var type = abstractTypes_1_1.value; | ||
// TODO: If we already implement resolveType, we don't need to check implementors | ||
var typeImplementors = schema.getPossibleTypes(type).filter(graphql_1.isType); | ||
@@ -45,6 +44,11 @@ try { | ||
: E.genericTypeUsedAsUnionMember(); | ||
errors.push((0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(ast.name), message)); | ||
errors.push((0, DiagnosticError_1.gqlErr)(ast.name, message)); | ||
} | ||
else if (!hasTypename.has(implementor.name)) { | ||
var err_1 = (0, DiagnosticError_1.gqlErr)((0, helpers_1.loc)(ast.name), E.concreteTypeMissingTypename(implementor.name)); | ||
else if (!hasTypename.has(implementor.name) && ast.exported == null) { | ||
var message = type instanceof graphql_1.GraphQLInterfaceType | ||
? E.concreteTypenameImplementingInterfaceCannotBeResolved(implementor.name, type.name) | ||
: E.concreteTypenameInUnionCannotBeResolved(implementor.name, type.name); | ||
var err_1 = (0, DiagnosticError_1.gqlErr)(ast.name, message, [ | ||
(0, DiagnosticError_1.gqlRelated)((0, helpers_1.nullThrows)(type.astNode).name, "".concat(type.name, " is defined here:")), | ||
]); | ||
errors.push(err_1); | ||
@@ -75,2 +79,1 @@ } | ||
} | ||
exports.validateTypenames = validateTypenames; |
{ | ||
"name": "grats", | ||
"version": "0.0.0-main-957a70fd", | ||
"version": "0.0.0-main-958caaeb", | ||
"main": "dist/src/index.js", | ||
@@ -14,7 +14,7 @@ "bin": "dist/src/cli.js", | ||
"commander": "^10.0.0", | ||
"graphql": "^16.6.0", | ||
"typescript": "^5.0.2" | ||
"graphql": "^16.9.0", | ||
"typescript": "5.5.4", | ||
"semver": "^7.5.4" | ||
}, | ||
"devDependencies": { | ||
"@graphql-tools/utils": "^9.2.1", | ||
"@types/node": "^18.14.6", | ||
@@ -30,3 +30,2 @@ "@types/semver": "^7.5.6", | ||
"process": "^0.11.10", | ||
"semver": "^7.5.4", | ||
"ts-node": "^10.9.1" | ||
@@ -37,6 +36,4 @@ }, | ||
}, | ||
"packageManager": "pnpm@8.12.0", | ||
"engines": { | ||
"node": ">=16 <=21", | ||
"pnpm": "^8" | ||
"node": ">=16 <=21" | ||
}, | ||
@@ -43,0 +40,0 @@ "bugs": { |
# Grats: Implementation-First GraphQL for TypeScript | ||
[](https://capt.dev/grats-chat) | ||
**The simplest way to build a GraphQL server in TypeScript** | ||
_Beta Software: Grats is largely stable and being used in production in multiple places. If you encounter any issues, don't hesitate to let us know._ | ||
**What if building a GraphQL server were as simple as just writing functions?** | ||
When you write your GraphQL server in TypeScript, your fields and resolvers | ||
@@ -18,2 +14,4 @@ are _already_ annotated with type information. _Grats leverages your existing | ||
Read the [blog post](https://jordaneldredge.com/blog/grats). | ||
## Example | ||
@@ -47,2 +45,4 @@ | ||
[](https://capt.dev/grats-chat) | ||
## Contributing | ||
@@ -49,0 +49,0 @@ |
Sorry, the diff of this file is too big to display
441869
11
98
9247
4
+ Addedsemver@^7.5.4
+ Addedsemver@7.7.1(transitive)
+ Addedtypescript@5.5.4(transitive)
- Removedtypescript@5.7.3(transitive)
Updatedgraphql@^16.9.0
Updatedtypescript@5.5.4