Comparing version
# Changelog | ||
### 0.12.0 (next) | ||
#### beta.14 | ||
- feat(plugins): onInstall hook (#236) | ||
- feat(deps): add support for TypeScript 3.6 (#255) | ||
#### beta.13 | ||
- fix(typegen): explicitly await removeFile before write (#254) | ||
#### beta.12 | ||
- feat(config): env var for should-generate-artifacts (#244) | ||
You can now set the `shouldGenerateArtifacts` config option by env var | ||
`NEXUS_SHOULD_GENERATE_ARTIFACTS=true|false`. | ||
- fix(typegen): delete prev file before writing next (#252) | ||
Before, sometimes, you would have to open the typegen file to make VSCode pick | ||
up its changed version. This change should reduce/remove the need for this | ||
workaround. | ||
* feat: by default typegen as an @types package (#230) | ||
BREAKING CHANGE | ||
You should not have to configure typegen manually anymore. We | ||
generate by default into `node_modules/@types/nexus-typegen` which TypeScript | ||
will automatically pick up. If you use the `types` `tsc` compiler option | ||
however, make sure to include `nexus-typegen`. | ||
This is a breaking change because typegen is enabled even when config | ||
`outputs` have not been configured (before, they were required). The | ||
heuristics of `shouldGenerateArtifacts` remain unchanged. | ||
### 0.11.7 | ||
@@ -4,0 +41,0 @@ |
@@ -16,7 +16,6 @@ import { GraphQLEnumType, GraphQLFieldConfig, GraphQLFieldConfigArgumentMap, GraphQLFieldConfigMap, GraphQLFieldResolver, GraphQLInputFieldConfig, GraphQLInputFieldConfigMap, GraphQLInputObjectType, GraphQLInputType, GraphQLInterfaceType, GraphQLNamedType, GraphQLObjectType, GraphQLOutputType, GraphQLScalarType, GraphQLSchema, GraphQLUnionType, GraphQLField } from "graphql"; | ||
import { GetGen, AuthorizeResolver } from "./typegenTypeHelpers"; | ||
import { Index } from "./utils"; | ||
import { NexusExtendInputTypeDef, NexusExtendInputTypeConfig } from "./definitions/extendInputType"; | ||
import { DynamicInputMethodDef, DynamicOutputMethodDef } from "./dynamicMethod"; | ||
import { DynamicOutputPropertyDef } from "./dynamicProperty"; | ||
import { Plugin } from "./plugins"; | ||
import * as Plugins from "./plugins"; | ||
export declare type Maybe<T> = T | null; | ||
@@ -36,18 +35,35 @@ export declare type NexusAcceptedTypeDef = AllNexusNamedTypeDefs | NexusExtendInputTypeDef<string> | NexusExtendTypeDef<string> | GraphQLNamedType | DynamicInputMethodDef<string> | DynamicOutputMethodDef<string> | DynamicOutputPropertyDef<string>; | ||
export interface BuilderConfig { | ||
plugins?: Plugin[]; | ||
plugins?: Plugins.PluginDef[]; | ||
/** | ||
* When the schema starts and `process.env.NODE_ENV !== "production"`, | ||
* artifact files are auto-generated containing the .graphql definitions of | ||
* the schema | ||
* Generated artifact settings. Set to false to disable all. | ||
* Set to true to enable all and use default paths. Leave | ||
* undefined for default behaviour of each artifact. | ||
*/ | ||
outputs: { | ||
outputs?: boolean | { | ||
/** | ||
* Absolute path where the GraphQL IDL file should be written | ||
* TypeScript declaration file generation settings. This file | ||
* contains types reflected off your source code. It is how | ||
* Nexus imbues dynamic code with static guarnatees. | ||
* | ||
* Defaults to being enabled when `process.env.NODE_ENV !== "production"`. | ||
* Set to true to enable and emit into default path (see below). | ||
* Set to false to disable. Set to a string to specify absolute path. | ||
* | ||
* The default path is node_modules/@types/nexus-typegen/index.d.ts. | ||
* This is chosen becuase TypeScript will pick it up without | ||
* any configuration needed by you. For more details about the @types | ||
* system refer to https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types | ||
*/ | ||
schema: string | false; | ||
typegen?: boolean | string; | ||
/** | ||
* File path where generated types should be saved | ||
* GraphQL SDL generation settings. This file is not necessary but | ||
* may be nice for teams wishing to review SDL in pull-requests or | ||
* just generally transitioning from a schema-first workflow. | ||
* | ||
* Defaults to false (disabled). Set to true to enable and emit into | ||
* default path (current working directory). Set to a string to specify | ||
* absolute path. | ||
*/ | ||
typegen: string | false; | ||
} | false; | ||
schema?: boolean | string; | ||
}; | ||
/** | ||
@@ -86,2 +102,10 @@ * Whether the schema & types are generated when the server | ||
} | ||
export interface SchemaConfig extends BuilderConfig { | ||
/** | ||
* All of the GraphQL types. This is an any for simplicity of developer experience, | ||
* if it's an object we get the values, if it's an array we flatten out the | ||
* valid types, ignoring invalid ones. | ||
*/ | ||
types: any; | ||
} | ||
export interface TypegenInfo { | ||
@@ -108,8 +132,14 @@ /** | ||
} | ||
export interface SchemaConfig extends BuilderConfig { | ||
/** | ||
* All of the GraphQL types. This is an any for simplicity of developer experience, | ||
* if it's an object we get the values, if it's an array we flatten out the | ||
* valid types, ignoring invalid ones. | ||
*/ | ||
/** | ||
* The resolved builder config wherein optional fields have been | ||
* given their fallbacks, etc. | ||
*/ | ||
export interface InternalBuilderConfig extends BuilderConfig { | ||
outputs: { | ||
schema: false | string; | ||
typegen: false | string; | ||
}; | ||
} | ||
export declare function resolveBuilderConfig(config: BuilderConfig): InternalBuilderConfig; | ||
export interface InternalSchemaConfig extends InternalBuilderConfig { | ||
types: any; | ||
@@ -141,5 +171,7 @@ } | ||
/** | ||
* Used to track all types that have been added to the builder. | ||
* Used to track all _GraphQL_ types that have been added to the builder. | ||
* This supports hasType method which permits asking the question "Will | ||
* the GraphQL schema have _this_ type (name)". | ||
*/ | ||
protected allTypes: Index<NexusAcceptedTypeDef>; | ||
protected allTypeDefs: Record<string, NexusAcceptedTypeDef>; | ||
/** | ||
@@ -152,3 +184,3 @@ * Used to check for circular references. | ||
*/ | ||
protected finalTypeMap: Index<GraphQLNamedType>; | ||
protected finalTypeMap: Record<string, GraphQLNamedType>; | ||
/** | ||
@@ -159,3 +191,3 @@ * The "defined type" map keeps track of all of the types that were | ||
*/ | ||
protected definedTypeMap: Index<GraphQLNamedType>; | ||
protected definedTypeMap: Record<string, GraphQLNamedType>; | ||
/** | ||
@@ -165,11 +197,11 @@ * The "pending type" map keeps track of all types that were defined w/ | ||
*/ | ||
protected pendingTypeMap: Index<AllNexusNamedTypeDefs>; | ||
protected pendingTypeMap: Record<string, AllNexusNamedTypeDefs>; | ||
/** | ||
* All "extensions" to types (adding fields on types from many locations) | ||
*/ | ||
protected typeExtensionMap: Index<NexusExtendTypeConfig<string>[] | null>; | ||
protected typeExtensionMap: Record<string, NexusExtendTypeConfig<string>[] | null>; | ||
/** | ||
* All "extensions" to input types (adding fields on types from many locations) | ||
*/ | ||
protected inputTypeExtensionMap: Index<NexusExtendInputTypeConfig<string>[] | null>; | ||
protected inputTypeExtensionMap: Record<string, NexusExtendInputTypeConfig<string>[] | null>; | ||
/** | ||
@@ -202,3 +234,3 @@ * Configures the root-level nonNullDefaults defaults | ||
*/ | ||
protected missingTypes: Index<MissingType>; | ||
protected missingTypes: Record<string, MissingType>; | ||
/** | ||
@@ -283,2 +315,6 @@ * Whether we've called `getFinalTypeMap` or not | ||
export declare function buildTypes<TypeMapDefs extends Record<string, GraphQLNamedType> = any>(types: any, config?: BuilderConfig, schemaBuilder?: SchemaBuilder): BuildTypes<TypeMapDefs>; | ||
/** | ||
* Internal build types woring with config rather than options. | ||
*/ | ||
export declare function buildTypesInternal<TypeMapDefs extends Record<string, GraphQLNamedType> = any>(types: any, config: InternalBuilderConfig, schemaBuilder?: SchemaBuilder): BuildTypes<TypeMapDefs>; | ||
export declare type NexusSchemaExtensions = { | ||
@@ -297,3 +333,3 @@ rootTypings: RootTypings; | ||
*/ | ||
export declare function makeSchemaInternal(options: SchemaConfig, schemaBuilder?: SchemaBuilder): { | ||
export declare function makeSchemaInternal(config: InternalSchemaConfig, schemaBuilder?: SchemaBuilder): { | ||
schema: NexusSchema; | ||
@@ -309,3 +345,3 @@ missingTypes: Record<string, MissingType>; | ||
*/ | ||
export declare function makeSchema(options: SchemaConfig): GraphQLSchema; | ||
export declare function makeSchema(config: SchemaConfig): GraphQLSchema; | ||
/** | ||
@@ -315,3 +351,3 @@ * Like makeSchema except that typegen is always run | ||
*/ | ||
export declare function generateSchema(options: SchemaConfig): Promise<NexusSchema>; | ||
export declare function generateSchema(config: SchemaConfig): Promise<NexusSchema>; | ||
export {}; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
var graphql_1 = require("graphql"); | ||
var args_1 = require("./definitions/args"); | ||
var definitionBlocks_1 = require("./definitions/definitionBlocks"); | ||
var interfaceType_1 = require("./definitions/interfaceType"); | ||
var objectType_1 = require("./definitions/objectType"); | ||
var unionType_1 = require("./definitions/unionType"); | ||
var wrapping_1 = require("./definitions/wrapping"); | ||
var typegenMetadata_1 = require("./typegenMetadata"); | ||
var utils_1 = require("./utils"); | ||
var decorateType_1 = require("./definitions/decorateType"); | ||
var plugins_1 = require("./plugins"); | ||
var SCALARS = { | ||
const tslib_1 = require("tslib"); | ||
const path = tslib_1.__importStar(require("path")); | ||
const graphql_1 = require("graphql"); | ||
const args_1 = require("./definitions/args"); | ||
const definitionBlocks_1 = require("./definitions/definitionBlocks"); | ||
const interfaceType_1 = require("./definitions/interfaceType"); | ||
const objectType_1 = require("./definitions/objectType"); | ||
const unionType_1 = require("./definitions/unionType"); | ||
const wrapping_1 = require("./definitions/wrapping"); | ||
const typegenMetadata_1 = require("./typegenMetadata"); | ||
const utils_1 = require("./utils"); | ||
const decorateType_1 = require("./definitions/decorateType"); | ||
const Plugins = tslib_1.__importStar(require("./plugins")); | ||
const SCALARS = { | ||
String: graphql_1.GraphQLString, | ||
@@ -24,10 +25,14 @@ Int: graphql_1.GraphQLInt, | ||
name: "NEXUS__UNKNOWN__TYPE", | ||
description: "\n This scalar should never make it into production. It is used as a placeholder for situations\n where GraphQL Nexus encounters a missing type. We don't want to error immedately, otherwise\n the TypeScript definitions will not be updated.\n ", | ||
parseValue: function (value) { | ||
description: ` | ||
This scalar should never make it into production. It is used as a placeholder for situations | ||
where GraphQL Nexus encounters a missing type. We don't want to error immedately, otherwise | ||
the TypeScript definitions will not be updated. | ||
`, | ||
parseValue(value) { | ||
throw new Error("Error: NEXUS__UNKNOWN__TYPE is not a valid scalar."); | ||
}, | ||
parseLiteral: function (value) { | ||
parseLiteral(value) { | ||
throw new Error("Error: NEXUS__UNKNOWN__TYPE is not a valid scalar."); | ||
}, | ||
serialize: function (value) { | ||
serialize(value) { | ||
throw new Error("Error: NEXUS__UNKNOWN__TYPE is not a valid scalar."); | ||
@@ -38,2 +43,67 @@ }, | ||
}); | ||
function resolveBuilderConfig(config) { | ||
// For JS | ||
if (config.outputs === null) { | ||
throw new Error("config.outputs cannot be of type `null`."); | ||
} | ||
if (typeof config.outputs === "object" && | ||
typeof config.outputs.schema === "string") { | ||
utils_1.assertAbsolutePath(config.outputs.schema, "outputs.schema"); | ||
} | ||
// Setup defaults | ||
const defaultSchemaPath = path.join(process.cwd(), "schema.graphql"); | ||
const defaultTypesPath = path.join(__dirname, "../../@types/nexus-typegen/index.d.ts"); | ||
const defaults = { | ||
outputs: { | ||
schema: defaultSchemaPath, | ||
typegen: defaultTypesPath, | ||
}, | ||
outputsUndefined: { | ||
schema: false, | ||
typegen: defaultTypesPath, | ||
}, | ||
}; | ||
// Build internal config | ||
const internalConfig = Object.assign(Object.assign({}, config), { outputs: {} }); | ||
const shouldGenerateArtifacts = config.shouldGenerateArtifacts !== undefined | ||
? config.shouldGenerateArtifacts | ||
: process.env.NEXUS_SHOULD_GENERATE_ARTIFACTS === "true" | ||
? true | ||
: process.env.NEXUS_SHOULD_GENERATE_ARTIFACTS === "false" | ||
? false | ||
: Boolean(!process.env.NODE_ENV || process.env.NODE_ENV === "development"); | ||
if (shouldGenerateArtifacts === false || config.outputs === false) { | ||
internalConfig.outputs = { schema: false, typegen: false }; | ||
} | ||
else if (config.outputs === true) { | ||
internalConfig.outputs = defaults.outputs; | ||
} | ||
else if (config.outputs === undefined) { | ||
internalConfig.outputs = defaults.outputsUndefined; | ||
} | ||
else { | ||
if (config.outputs.schema === undefined) { | ||
internalConfig.outputs.schema = false; | ||
} | ||
else if (config.outputs.schema === true) { | ||
internalConfig.outputs.schema = defaults.outputs.schema; | ||
} | ||
else { | ||
internalConfig.outputs.schema = config.outputs.schema; | ||
} | ||
if (config.outputs.typegen === undefined || | ||
config.outputs.typegen === true) { | ||
internalConfig.outputs.typegen = defaults.outputs.typegen; | ||
} | ||
else { | ||
internalConfig.outputs.typegen = config.outputs.typegen; | ||
} | ||
} | ||
return internalConfig; | ||
} | ||
exports.resolveBuilderConfig = resolveBuilderConfig; | ||
function resolveSchemaConfig(config) { | ||
// There is no additional processing for schema config | ||
return resolveBuilderConfig(config); | ||
} | ||
/** | ||
@@ -44,10 +114,11 @@ * Builds all of the types, properly accounts for any using "mix". | ||
*/ | ||
var SchemaBuilder = /** @class */ (function () { | ||
function SchemaBuilder(config) { | ||
var _this = this; | ||
class SchemaBuilder { | ||
constructor(config) { | ||
this.config = config; | ||
/** | ||
* Used to track all types that have been added to the builder. | ||
* Used to track all _GraphQL_ types that have been added to the builder. | ||
* This supports hasType method which permits asking the question "Will | ||
* the GraphQL schema have _this_ type (name)". | ||
*/ | ||
this.allTypes = {}; | ||
this.allTypeDefs = {}; | ||
/** | ||
@@ -112,4 +183,4 @@ * Used to check for circular references. | ||
this.finalized = false; | ||
this.hasType = function (typeName) { | ||
return Boolean(_this.allTypes[typeName]); | ||
this.hasType = (typeName) => { | ||
return Boolean(this.allTypeDefs[typeName]); | ||
}; | ||
@@ -122,31 +193,28 @@ /** | ||
*/ | ||
this.addType = function (typeDef) { | ||
if (!_this.allTypes[typeDef.name]) { | ||
_this.allTypes[typeDef.name] = typeDef; | ||
} | ||
this.addType = (typeDef) => { | ||
if (wrapping_1.isNexusDynamicInputMethod(typeDef)) { | ||
_this.dynamicInputFields[typeDef.name] = typeDef; | ||
this.dynamicInputFields[typeDef.name] = typeDef; | ||
return; | ||
} | ||
if (wrapping_1.isNexusDynamicOutputMethod(typeDef)) { | ||
_this.dynamicOutputFields[typeDef.name] = typeDef; | ||
this.dynamicOutputFields[typeDef.name] = typeDef; | ||
return; | ||
} | ||
if (wrapping_1.isNexusDynamicOutputProperty(typeDef)) { | ||
_this.dynamicOutputProperties[typeDef.name] = typeDef; | ||
this.dynamicOutputProperties[typeDef.name] = typeDef; | ||
return; | ||
} | ||
var existingType = _this.finalTypeMap[typeDef.name] || _this.pendingTypeMap[typeDef.name]; | ||
const existingType = this.finalTypeMap[typeDef.name] || this.pendingTypeMap[typeDef.name]; | ||
if (wrapping_1.isNexusExtendTypeDef(typeDef)) { | ||
var typeExtensions = (_this.typeExtensionMap[typeDef.name] = | ||
_this.typeExtensionMap[typeDef.name] || []); | ||
const typeExtensions = (this.typeExtensionMap[typeDef.name] = | ||
this.typeExtensionMap[typeDef.name] || []); | ||
typeExtensions.push(typeDef.value); | ||
_this.typesToWalk.push({ type: "object", value: typeDef.value }); | ||
this.typesToWalk.push({ type: "object", value: typeDef.value }); | ||
return; | ||
} | ||
if (wrapping_1.isNexusExtendInputTypeDef(typeDef)) { | ||
var typeExtensions = (_this.inputTypeExtensionMap[typeDef.name] = | ||
_this.inputTypeExtensionMap[typeDef.name] || []); | ||
const typeExtensions = (this.inputTypeExtensionMap[typeDef.name] = | ||
this.inputTypeExtensionMap[typeDef.name] || []); | ||
typeExtensions.push(typeDef.value); | ||
_this.typesToWalk.push({ type: "input", value: typeDef.value }); | ||
this.typesToWalk.push({ type: "input", value: typeDef.value }); | ||
return; | ||
@@ -161,19 +229,22 @@ } | ||
} | ||
if (!this.allTypeDefs[typeDef.name]) { | ||
this.allTypeDefs[typeDef.name] = typeDef; | ||
} | ||
if (wrapping_1.isNexusScalarTypeDef(typeDef) && typeDef.value.asNexusMethod) { | ||
_this.dynamicInputFields[typeDef.value.asNexusMethod] = typeDef.name; | ||
_this.dynamicOutputFields[typeDef.value.asNexusMethod] = typeDef.name; | ||
this.dynamicInputFields[typeDef.value.asNexusMethod] = typeDef.name; | ||
this.dynamicOutputFields[typeDef.value.asNexusMethod] = typeDef.name; | ||
if (typeDef.value.rootTyping) { | ||
_this.rootTypings[typeDef.name] = typeDef.value.rootTyping; | ||
this.rootTypings[typeDef.name] = typeDef.value.rootTyping; | ||
} | ||
} | ||
else if (graphql_1.isScalarType(typeDef)) { | ||
var scalarDef = typeDef; | ||
const scalarDef = typeDef; | ||
if (scalarDef.extensions && scalarDef.extensions.nexus) { | ||
var _a = scalarDef.extensions.nexus, asNexusMethod = _a.asNexusMethod, rootTyping = _a.rootTyping; | ||
const { asNexusMethod, rootTyping } = scalarDef.extensions.nexus; | ||
if (asNexusMethod) { | ||
_this.dynamicInputFields[asNexusMethod] = scalarDef.name; | ||
_this.dynamicOutputFields[asNexusMethod] = typeDef.name; | ||
this.dynamicInputFields[asNexusMethod] = scalarDef.name; | ||
this.dynamicOutputFields[asNexusMethod] = typeDef.name; | ||
} | ||
if (rootTyping) { | ||
_this.rootTypings[scalarDef.name] = rootTyping; | ||
this.rootTypings[scalarDef.name] = rootTyping; | ||
} | ||
@@ -183,26 +254,26 @@ } | ||
if (graphql_1.isNamedType(typeDef)) { | ||
_this.finalTypeMap[typeDef.name] = typeDef; | ||
_this.definedTypeMap[typeDef.name] = typeDef; | ||
_this.typesToWalk.push({ type: "named", value: typeDef }); | ||
this.finalTypeMap[typeDef.name] = typeDef; | ||
this.definedTypeMap[typeDef.name] = typeDef; | ||
this.typesToWalk.push({ type: "named", value: typeDef }); | ||
} | ||
else { | ||
_this.pendingTypeMap[typeDef.name] = typeDef; | ||
this.pendingTypeMap[typeDef.name] = typeDef; | ||
} | ||
if (wrapping_1.isNexusInputObjectTypeDef(typeDef)) { | ||
_this.typesToWalk.push({ type: "input", value: typeDef.value }); | ||
this.typesToWalk.push({ type: "input", value: typeDef.value }); | ||
} | ||
if (wrapping_1.isNexusObjectTypeDef(typeDef)) { | ||
_this.typesToWalk.push({ type: "object", value: typeDef.value }); | ||
this.typesToWalk.push({ type: "object", value: typeDef.value }); | ||
} | ||
if (wrapping_1.isNexusInterfaceTypeDef(typeDef)) { | ||
_this.typesToWalk.push({ type: "interface", value: typeDef.value }); | ||
this.typesToWalk.push({ type: "interface", value: typeDef.value }); | ||
} | ||
}; | ||
this.nonNullDefaults = tslib_1.__assign({ input: false, output: true }, config.nonNullDefaults); | ||
this.nonNullDefaults = Object.assign({ input: false, output: true }, config.nonNullDefaults); | ||
} | ||
SchemaBuilder.prototype.getConfig = function () { | ||
getConfig() { | ||
return this.config; | ||
}; | ||
SchemaBuilder.prototype.walkTypes = function () { | ||
var obj; | ||
} | ||
walkTypes() { | ||
let obj; | ||
while ((obj = this.typesToWalk.shift())) { | ||
@@ -224,5 +295,4 @@ switch (obj.type) { | ||
} | ||
}; | ||
SchemaBuilder.prototype.getFinalTypeMap = function () { | ||
var _this = this; | ||
} | ||
getFinalTypeMap() { | ||
this.finalized = true; | ||
@@ -234,29 +304,29 @@ this.walkTypes(); | ||
} | ||
Object.keys(this.pendingTypeMap).forEach(function (key) { | ||
Object.keys(this.pendingTypeMap).forEach((key) => { | ||
// If we've already constructed the type by this point, | ||
// via circular dependency resolution don't worry about building it. | ||
if (_this.finalTypeMap[key]) { | ||
if (this.finalTypeMap[key]) { | ||
return; | ||
} | ||
if (_this.definedTypeMap[key]) { | ||
if (this.definedTypeMap[key]) { | ||
throw extendError(key); | ||
} | ||
_this.finalTypeMap[key] = _this.getOrBuildType(key); | ||
_this.buildingTypes.clear(); | ||
this.finalTypeMap[key] = this.getOrBuildType(key); | ||
this.buildingTypes.clear(); | ||
}); | ||
Object.keys(this.typeExtensionMap).forEach(function (key) { | ||
Object.keys(this.typeExtensionMap).forEach((key) => { | ||
// If we haven't defined the type, assume it's an object type | ||
if (_this.typeExtensionMap[key] !== null) { | ||
_this.buildObjectType({ | ||
if (this.typeExtensionMap[key] !== null) { | ||
this.buildObjectType({ | ||
name: key, | ||
definition: function () { }, | ||
definition() { }, | ||
}); | ||
} | ||
}); | ||
Object.keys(this.inputTypeExtensionMap).forEach(function (key) { | ||
Object.keys(this.inputTypeExtensionMap).forEach((key) => { | ||
// If we haven't defined the type, assume it's an object type | ||
if (_this.inputTypeExtensionMap[key] !== null) { | ||
_this.buildInputObjectType({ | ||
if (this.inputTypeExtensionMap[key] !== null) { | ||
this.buildInputObjectType({ | ||
name: key, | ||
definition: function () { }, | ||
definition() { }, | ||
}); | ||
@@ -275,18 +345,15 @@ } | ||
}; | ||
}; | ||
SchemaBuilder.prototype.buildInputObjectType = function (config) { | ||
var _this = this; | ||
var fields = []; | ||
var definitionBlock = new definitionBlocks_1.InputDefinitionBlock({ | ||
} | ||
buildInputObjectType(config) { | ||
const fields = []; | ||
const definitionBlock = new definitionBlocks_1.InputDefinitionBlock({ | ||
typeName: config.name, | ||
addField: function (field) { return fields.push(field); }, | ||
addDynamicInputFields: function (block, isList) { | ||
return _this.addDynamicInputFields(block, isList); | ||
}, | ||
addField: (field) => fields.push(field), | ||
addDynamicInputFields: (block, isList) => this.addDynamicInputFields(block, isList), | ||
warn: consoleWarn, | ||
}); | ||
config.definition(definitionBlock); | ||
var extensions = this.inputTypeExtensionMap[config.name]; | ||
const extensions = this.inputTypeExtensionMap[config.name]; | ||
if (extensions) { | ||
extensions.forEach(function (extension) { | ||
extensions.forEach((extension) => { | ||
extension.definition(definitionBlock); | ||
@@ -298,10 +365,9 @@ }); | ||
name: config.name, | ||
fields: function () { return _this.buildInputObjectFields(fields, config); }, | ||
fields: () => this.buildInputObjectFields(fields, config), | ||
description: config.description, | ||
})); | ||
}; | ||
SchemaBuilder.prototype.buildObjectType = function (config) { | ||
var _this = this; | ||
var fields = []; | ||
var interfaces = []; | ||
} | ||
buildObjectType(config) { | ||
const fields = []; | ||
const interfaces = []; | ||
// FIXME | ||
@@ -313,20 +379,18 @@ // We use `any` because otherwise TypeScript fails to compile. It states: | ||
// visibility is limited to the implementation of buildObjectType. | ||
var modifications = {}; | ||
var definitionBlock = new objectType_1.ObjectDefinitionBlock({ | ||
const modifications = {}; | ||
const definitionBlock = new objectType_1.ObjectDefinitionBlock({ | ||
typeName: config.name, | ||
addField: function (fieldDef) { return fields.push(fieldDef); }, | ||
addInterfaces: function (interfaceDefs) { return interfaces.push.apply(interfaces, interfaceDefs); }, | ||
addFieldModifications: function (mods) { | ||
addField: (fieldDef) => fields.push(fieldDef), | ||
addInterfaces: (interfaceDefs) => interfaces.push(...interfaceDefs), | ||
addFieldModifications: (mods) => { | ||
modifications[mods.field] = modifications[mods.field] || []; | ||
modifications[mods.field].push(mods); | ||
}, | ||
addDynamicOutputMembers: function (block, isList) { | ||
return _this.addDynamicOutputMembers(block, isList); | ||
}, | ||
addDynamicOutputMembers: (block, isList) => this.addDynamicOutputMembers(block, isList), | ||
warn: consoleWarn, | ||
}); | ||
config.definition(definitionBlock); | ||
var extensions = this.typeExtensionMap[config.name]; | ||
const extensions = this.typeExtensionMap[config.name]; | ||
if (extensions) { | ||
extensions.forEach(function (extension) { | ||
extensions.forEach((extension) => { | ||
extension.definition(definitionBlock); | ||
@@ -341,22 +405,22 @@ }); | ||
name: config.name, | ||
interfaces: function () { return interfaces.map(function (i) { return _this.getInterface(i); }); }, | ||
interfaces: () => interfaces.map((i) => this.getInterface(i)), | ||
description: config.description, | ||
fields: function () { | ||
var allFieldsMap = {}; | ||
var allInterfaces = interfaces.map(function (i) { return _this.getInterface(i); }); | ||
allInterfaces.forEach(function (i) { | ||
var interfaceFields = i.getFields(); | ||
fields: () => { | ||
const allFieldsMap = {}; | ||
const allInterfaces = interfaces.map((i) => this.getInterface(i)); | ||
allInterfaces.forEach((i) => { | ||
const interfaceFields = i.getFields(); | ||
// We need to take the interface fields and reconstruct them | ||
// this actually simplifies things becuase if we've modified | ||
// the field at all it needs to happen here. | ||
Object.keys(interfaceFields).forEach(function (iFieldName) { | ||
var _a = interfaceFields[iFieldName], isDeprecated = _a.isDeprecated, args = _a.args, rest = tslib_1.__rest(_a, ["isDeprecated", "args"]); | ||
allFieldsMap[iFieldName] = tslib_1.__assign({}, rest, { args: args.reduce(function (result, a) { | ||
var name = a.name, argRest = tslib_1.__rest(a, ["name"]); | ||
Object.keys(interfaceFields).forEach((iFieldName) => { | ||
const _a = interfaceFields[iFieldName], { isDeprecated, args } = _a, rest = tslib_1.__rest(_a, ["isDeprecated", "args"]); | ||
allFieldsMap[iFieldName] = Object.assign(Object.assign({}, rest), { args: args.reduce((result, a) => { | ||
const { name } = a, argRest = tslib_1.__rest(a, ["name"]); | ||
result[name] = argRest; | ||
return result; | ||
}, {}) }); | ||
var mods = modifications[iFieldName]; | ||
const mods = modifications[iFieldName]; | ||
if (mods) { | ||
mods.map(function (mod) { | ||
mods.map((mod) => { | ||
if (typeof mod.description !== "undefined") { | ||
@@ -372,24 +436,21 @@ allFieldsMap[iFieldName].description = mod.description; | ||
}); | ||
return _this.buildObjectFields(fields, config, allFieldsMap); | ||
return this.buildObjectFields(fields, config, allFieldsMap); | ||
}, | ||
})); | ||
}; | ||
SchemaBuilder.prototype.buildInterfaceType = function (config) { | ||
var _this = this; | ||
var name = config.name, description = config.description; | ||
var resolveType; | ||
var fields = []; | ||
var definitionBlock = new interfaceType_1.InterfaceDefinitionBlock({ | ||
} | ||
buildInterfaceType(config) { | ||
const { name, description } = config; | ||
let resolveType; | ||
const fields = []; | ||
const definitionBlock = new interfaceType_1.InterfaceDefinitionBlock({ | ||
typeName: config.name, | ||
addField: function (field) { return fields.push(field); }, | ||
setResolveType: function (fn) { return (resolveType = fn); }, | ||
addDynamicOutputMembers: function (block, isList) { | ||
return _this.addDynamicOutputMembers(block, isList); | ||
}, | ||
addField: (field) => fields.push(field), | ||
setResolveType: (fn) => (resolveType = fn), | ||
addDynamicOutputMembers: (block, isList) => this.addDynamicOutputMembers(block, isList), | ||
warn: consoleWarn, | ||
}); | ||
config.definition(definitionBlock); | ||
var extensions = this.typeExtensionMap[config.name]; | ||
const extensions = this.typeExtensionMap[config.name]; | ||
if (extensions) { | ||
extensions.forEach(function (extension) { | ||
extensions.forEach((extension) => { | ||
extension.definition(definitionBlock); | ||
@@ -405,13 +466,13 @@ }); | ||
return this.finalize(new graphql_1.GraphQLInterfaceType({ | ||
name: name, | ||
fields: function () { return _this.buildObjectFields(fields, config, {}, true); }, | ||
resolveType: resolveType, | ||
description: description, | ||
name, | ||
fields: () => this.buildObjectFields(fields, config, {}, true), | ||
resolveType, | ||
description, | ||
})); | ||
}; | ||
SchemaBuilder.prototype.buildEnumType = function (config) { | ||
var members = config.members; | ||
var values = {}; | ||
} | ||
buildEnumType(config) { | ||
const { members } = config; | ||
const values = {}; | ||
if (Array.isArray(members)) { | ||
members.forEach(function (m) { | ||
members.forEach((m) => { | ||
if (typeof m === "string") { | ||
@@ -436,4 +497,4 @@ values[m] = { value: m }; | ||
// See: https://www.typescriptlang.org/docs/handbook/enums.html | ||
.filter(function (key) { return isNaN(+key); }) | ||
.forEach(function (key) { | ||
.filter((key) => isNaN(+key)) | ||
.forEach((key) => { | ||
graphql_1.assertValidName(key); | ||
@@ -446,3 +507,3 @@ values[key] = { | ||
if (!Object.keys(values).length) { | ||
throw new Error("GraphQL Nexus: Enum " + config.name + " must have at least one member"); | ||
throw new Error(`GraphQL Nexus: Enum ${config.name} must have at least one member`); | ||
} | ||
@@ -457,10 +518,9 @@ if (config.rootTyping) { | ||
})); | ||
}; | ||
SchemaBuilder.prototype.buildUnionType = function (config) { | ||
var _this = this; | ||
var members; | ||
var resolveType; | ||
} | ||
buildUnionType(config) { | ||
let members; | ||
let resolveType; | ||
config.definition(new unionType_1.UnionDefinitionBlock({ | ||
setResolveType: function (fn) { return (resolveType = fn); }, | ||
addUnionMembers: function (unionMembers) { return (members = unionMembers); }, | ||
setResolveType: (fn) => (resolveType = fn), | ||
addUnionMembers: (unionMembers) => (members = unionMembers), | ||
})); | ||
@@ -475,8 +535,8 @@ if (!resolveType) { | ||
name: config.name, | ||
resolveType: resolveType, | ||
resolveType, | ||
description: config.description, | ||
types: function () { return _this.buildUnionMembers(config.name, members); }, | ||
types: () => this.buildUnionMembers(config.name, members), | ||
})); | ||
}; | ||
SchemaBuilder.prototype.buildScalarType = function (config) { | ||
} | ||
buildScalarType(config) { | ||
if (config.rootTyping) { | ||
@@ -486,9 +546,8 @@ this.rootTypings[config.name] = config.rootTyping; | ||
return this.finalize(new graphql_1.GraphQLScalarType(config)); | ||
}; | ||
SchemaBuilder.prototype.finalize = function (type) { | ||
} | ||
finalize(type) { | ||
this.finalTypeMap[type.name] = type; | ||
return type; | ||
}; | ||
SchemaBuilder.prototype.missingType = function (typeName, fromObject) { | ||
if (fromObject === void 0) { fromObject = false; } | ||
} | ||
missingType(typeName, fromObject = false) { | ||
invariantGuard(typeName); | ||
@@ -501,3 +560,3 @@ if (typeName === "Query") { | ||
type: graphql_1.GraphQLNonNull(graphql_1.GraphQLBoolean), | ||
resolve: function () { return true; }, | ||
resolve: () => true, | ||
}, | ||
@@ -508,41 +567,36 @@ }, | ||
if (!this.missingTypes[typeName]) { | ||
this.missingTypes[typeName] = { fromObject: fromObject }; | ||
this.missingTypes[typeName] = { fromObject }; | ||
} | ||
return exports.UNKNOWN_TYPE_SCALAR; | ||
}; | ||
SchemaBuilder.prototype.buildUnionMembers = function (unionName, members) { | ||
var _this = this; | ||
var unionMembers = []; | ||
} | ||
buildUnionMembers(unionName, members) { | ||
const unionMembers = []; | ||
if (!members) { | ||
throw new Error("Missing Union members for " + unionName + "." + | ||
"Make sure to call the t.members(...) method in the union blocks"); | ||
throw new Error(`Missing Union members for ${unionName}.` + | ||
`Make sure to call the t.members(...) method in the union blocks`); | ||
} | ||
members.forEach(function (member) { | ||
unionMembers.push(_this.getObjectType(member)); | ||
members.forEach((member) => { | ||
unionMembers.push(this.getObjectType(member)); | ||
}); | ||
if (!unionMembers.length) { | ||
throw new Error("GraphQL Nexus: Union " + unionName + " must have at least one member type"); | ||
throw new Error(`GraphQL Nexus: Union ${unionName} must have at least one member type`); | ||
} | ||
return unionMembers; | ||
}; | ||
SchemaBuilder.prototype.buildObjectFields = function (fields, typeConfig, intoObject, forInterface) { | ||
var _this = this; | ||
if (forInterface === void 0) { forInterface = false; } | ||
fields.forEach(function (field) { | ||
intoObject[field.name] = _this.buildObjectField(field, typeConfig, forInterface); | ||
} | ||
buildObjectFields(fields, typeConfig, intoObject, forInterface = false) { | ||
fields.forEach((field) => { | ||
intoObject[field.name] = this.buildObjectField(field, typeConfig, forInterface); | ||
}); | ||
return intoObject; | ||
}; | ||
SchemaBuilder.prototype.buildInputObjectFields = function (fields, typeConfig) { | ||
var _this = this; | ||
var fieldMap = {}; | ||
fields.forEach(function (field) { | ||
fieldMap[field.name] = _this.buildInputObjectField(field, typeConfig); | ||
} | ||
buildInputObjectFields(fields, typeConfig) { | ||
const fieldMap = {}; | ||
fields.forEach((field) => { | ||
fieldMap[field.name] = this.buildInputObjectField(field, typeConfig); | ||
}); | ||
return fieldMap; | ||
}; | ||
SchemaBuilder.prototype.buildObjectField = function (fieldConfig, typeConfig, forInterface) { | ||
if (forInterface === void 0) { forInterface = false; } | ||
} | ||
buildObjectField(fieldConfig, typeConfig, forInterface = false) { | ||
if (!fieldConfig.type) { | ||
throw new Error("Missing required \"type\" field for " + typeConfig.name + "." + fieldConfig.name); | ||
throw new Error(`Missing required "type" field for ${typeConfig.name}.${fieldConfig.name}`); | ||
} | ||
@@ -557,4 +611,4 @@ return { | ||
}; | ||
}; | ||
SchemaBuilder.prototype.buildInputObjectField = function (field, typeConfig) { | ||
} | ||
buildInputObjectField(field, typeConfig) { | ||
return { | ||
@@ -565,10 +619,9 @@ type: this.decorateType(this.getInputType(field.type), field.list, this.inputNonNull(typeConfig, field)), | ||
}; | ||
}; | ||
SchemaBuilder.prototype.buildArgs = function (args, typeConfig) { | ||
var _this = this; | ||
var allArgs = {}; | ||
Object.keys(args).forEach(function (argName) { | ||
var argDef = normalizeArg(args[argName]).value; | ||
} | ||
buildArgs(args, typeConfig) { | ||
const allArgs = {}; | ||
Object.keys(args).forEach((argName) => { | ||
const argDef = normalizeArg(args[argName]).value; | ||
allArgs[argName] = { | ||
type: _this.decorateType(_this.getInputType(argDef.type), argDef.list, _this.inputNonNull(typeConfig, argDef)), | ||
type: this.decorateType(this.getInputType(argDef.type), argDef.list, this.inputNonNull(typeConfig, argDef)), | ||
description: argDef.description, | ||
@@ -579,8 +632,8 @@ defaultValue: argDef.default, | ||
return allArgs; | ||
}; | ||
SchemaBuilder.prototype.inputNonNull = function (typeDef, field) { | ||
var nullable = field.nullable, required = field.required; | ||
var name = typeDef.name, _a = typeDef.nonNullDefaults, nonNullDefaults = _a === void 0 ? {} : _a; | ||
} | ||
inputNonNull(typeDef, field) { | ||
const { nullable, required } = field; | ||
const { name, nonNullDefaults = {} } = typeDef; | ||
if (typeof nullable !== "undefined" && typeof required !== "undefined") { | ||
throw new Error("Cannot set both nullable & required on " + name); | ||
throw new Error(`Cannot set both nullable & required on ${name}`); | ||
} | ||
@@ -595,6 +648,6 @@ if (typeof nullable !== "undefined") { | ||
return utils_1.firstDefined(nonNullDefaults.input, this.nonNullDefaults.input, false); | ||
}; | ||
SchemaBuilder.prototype.outputNonNull = function (typeDef, field) { | ||
var nullable = field.nullable; | ||
var _a = typeDef.nonNullDefaults, nonNullDefaults = _a === void 0 ? {} : _a; | ||
} | ||
outputNonNull(typeDef, field) { | ||
const { nullable } = field; | ||
const { nonNullDefaults = {} } = typeDef; | ||
if (typeof nullable !== "undefined") { | ||
@@ -605,4 +658,4 @@ return !nullable; | ||
return utils_1.firstDefined(nonNullDefaults.output, this.nonNullDefaults.output, true); | ||
}; | ||
SchemaBuilder.prototype.decorateType = function (type, list, isNonNull) { | ||
} | ||
decorateType(type, list, isNonNull) { | ||
if (list) { | ||
@@ -612,5 +665,5 @@ type = this.decorateList(type, list); | ||
return (isNonNull ? graphql_1.GraphQLNonNull(type) : type); | ||
}; | ||
SchemaBuilder.prototype.decorateList = function (type, list) { | ||
var finalType = type; | ||
} | ||
decorateList(type, list) { | ||
let finalType = type; | ||
if (!Array.isArray(list)) { | ||
@@ -620,4 +673,4 @@ return graphql_1.GraphQLList(graphql_1.GraphQLNonNull(type)); | ||
if (Array.isArray(list)) { | ||
for (var i = 0; i < list.length; i++) { | ||
var isNull = !list[i]; | ||
for (let i = 0; i < list.length; i++) { | ||
const isNull = !list[i]; | ||
if (!isNull) { | ||
@@ -630,36 +683,35 @@ finalType = graphql_1.GraphQLNonNull(finalType); | ||
return finalType; | ||
}; | ||
SchemaBuilder.prototype.getInterface = function (name) { | ||
var type = this.getOrBuildType(name); | ||
} | ||
getInterface(name) { | ||
const type = this.getOrBuildType(name); | ||
if (!graphql_1.isInterfaceType(type)) { | ||
throw new Error("Expected " + name + " to be an interfaceType, saw " + type.constructor.name); | ||
throw new Error(`Expected ${name} to be an interfaceType, saw ${type.constructor.name}`); | ||
} | ||
return type; | ||
}; | ||
SchemaBuilder.prototype.getInputType = function (name) { | ||
var type = this.getOrBuildType(name); | ||
} | ||
getInputType(name) { | ||
const type = this.getOrBuildType(name); | ||
if (!graphql_1.isInputObjectType(type) && !graphql_1.isLeafType(type)) { | ||
throw new Error("Expected " + name + " to be a possible input type, saw " + type.constructor.name); | ||
throw new Error(`Expected ${name} to be a possible input type, saw ${type.constructor.name}`); | ||
} | ||
return type; | ||
}; | ||
SchemaBuilder.prototype.getOutputType = function (name) { | ||
var type = this.getOrBuildType(name); | ||
} | ||
getOutputType(name) { | ||
const type = this.getOrBuildType(name); | ||
if (!graphql_1.isOutputType(type)) { | ||
throw new Error("Expected " + name + " to be a valid output type, saw " + type.constructor.name); | ||
throw new Error(`Expected ${name} to be a valid output type, saw ${type.constructor.name}`); | ||
} | ||
return type; | ||
}; | ||
SchemaBuilder.prototype.getObjectType = function (name) { | ||
} | ||
getObjectType(name) { | ||
if (wrapping_1.isNexusNamedTypeDef(name)) { | ||
return this.getObjectType(name.name); | ||
} | ||
var type = this.getOrBuildType(name); | ||
const type = this.getOrBuildType(name); | ||
if (!graphql_1.isObjectType(type)) { | ||
throw new Error("Expected " + name + " to be a objectType, saw " + type.constructor.name); | ||
throw new Error(`Expected ${name} to be a objectType, saw ${type.constructor.name}`); | ||
} | ||
return type; | ||
}; | ||
SchemaBuilder.prototype.getOrBuildType = function (name, fromObject) { | ||
if (fromObject === void 0) { fromObject = false; } | ||
} | ||
getOrBuildType(name, fromObject = false) { | ||
invariantGuard(name); | ||
@@ -676,5 +728,5 @@ if (wrapping_1.isNexusNamedTypeDef(name) || wrapping_1.isNexusWrappedType(name)) { | ||
if (this.buildingTypes.has(name)) { | ||
throw new Error("GraphQL Nexus: Circular dependency detected, while building types " + Array.from(this.buildingTypes)); | ||
throw new Error(`GraphQL Nexus: Circular dependency detected, while building types ${Array.from(this.buildingTypes)}`); | ||
} | ||
var pendingType = this.pendingTypeMap[name]; | ||
const pendingType = this.pendingTypeMap[name]; | ||
if (wrapping_1.isNexusNamedTypeDef(pendingType)) { | ||
@@ -702,5 +754,5 @@ this.buildingTypes.add(pendingType.name); | ||
return this.missingType(name, fromObject); | ||
}; | ||
SchemaBuilder.prototype.getSubscribe = function (fieldConfig) { | ||
var subscribe; | ||
} | ||
getSubscribe(fieldConfig) { | ||
let subscribe; | ||
if (fieldConfig.subscribe) { | ||
@@ -713,6 +765,5 @@ subscribe = fieldConfig.subscribe; | ||
return subscribe; | ||
}; | ||
SchemaBuilder.prototype.getResolver = function (fieldConfig, typeConfig, forInterface) { | ||
if (forInterface === void 0) { forInterface = false; } | ||
var resolver; | ||
} | ||
getResolver(fieldConfig, typeConfig, forInterface = false) { | ||
let resolver; | ||
if (fieldConfig.resolve) { | ||
@@ -728,39 +779,31 @@ resolver = fieldConfig.resolve; | ||
return resolver; | ||
}; | ||
SchemaBuilder.prototype.missingResolveType = function (name, location) { | ||
console.error(new Error("Missing resolveType for the " + name + " " + location + ". " + | ||
"Be sure to add one in the definition block for the type, " + | ||
"or t.resolveType(() => null) if you don't want or need to implement.")); | ||
return function () { return null; }; | ||
}; | ||
SchemaBuilder.prototype.walkInputType = function (obj) { | ||
var _this = this; | ||
var definitionBlock = new definitionBlocks_1.InputDefinitionBlock({ | ||
} | ||
missingResolveType(name, location) { | ||
console.error(new Error(`Missing resolveType for the ${name} ${location}. ` + | ||
`Be sure to add one in the definition block for the type, ` + | ||
`or t.resolveType(() => null) if you don't want or need to implement.`)); | ||
return () => null; | ||
} | ||
walkInputType(obj) { | ||
const definitionBlock = new definitionBlocks_1.InputDefinitionBlock({ | ||
typeName: obj.name, | ||
addField: function (f) { return _this.maybeTraverseInputType(f); }, | ||
addDynamicInputFields: function (block, isList) { | ||
return _this.addDynamicInputFields(block, isList); | ||
}, | ||
warn: function () { }, | ||
addField: (f) => this.maybeTraverseInputType(f), | ||
addDynamicInputFields: (block, isList) => this.addDynamicInputFields(block, isList), | ||
warn: () => { }, | ||
}); | ||
obj.definition(definitionBlock); | ||
return obj; | ||
}; | ||
SchemaBuilder.prototype.addDynamicInputFields = function (block, isList) { | ||
var _this = this; | ||
utils_1.eachObj(this.dynamicInputFields, function (val, methodName) { | ||
} | ||
addDynamicInputFields(block, isList) { | ||
utils_1.eachObj(this.dynamicInputFields, (val, methodName) => { | ||
if (typeof val === "string") { | ||
return _this.addDynamicScalar(methodName, val, block); | ||
return this.addDynamicScalar(methodName, val, block); | ||
} | ||
// @ts-ignore | ||
block[methodName] = function () { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
var config = isList ? [args[0], tslib_1.__assign({ list: isList }, args[1])] : args; | ||
block[methodName] = (...args) => { | ||
const config = isList ? [args[0], Object.assign({ list: isList }, args[1])] : args; | ||
return val.value.factory({ | ||
args: config, | ||
typeDef: block, | ||
builder: _this, | ||
builder: this, | ||
typeName: block.typeName, | ||
@@ -770,20 +813,15 @@ }); | ||
}); | ||
}; | ||
SchemaBuilder.prototype.addDynamicOutputMembers = function (block, isList) { | ||
var _this = this; | ||
utils_1.eachObj(this.dynamicOutputFields, function (val, methodName) { | ||
} | ||
addDynamicOutputMembers(block, isList) { | ||
utils_1.eachObj(this.dynamicOutputFields, (val, methodName) => { | ||
if (typeof val === "string") { | ||
return _this.addDynamicScalar(methodName, val, block); | ||
return this.addDynamicScalar(methodName, val, block); | ||
} | ||
// @ts-ignore | ||
block[methodName] = function () { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
var config = isList ? [args[0], tslib_1.__assign({ list: isList }, args[1])] : args; | ||
block[methodName] = (...args) => { | ||
const config = isList ? [args[0], Object.assign({ list: isList }, args[1])] : args; | ||
return val.value.factory({ | ||
args: config, | ||
typeDef: block, | ||
builder: _this, | ||
builder: this, | ||
typeName: block.typeName, | ||
@@ -793,5 +831,5 @@ }); | ||
}); | ||
utils_1.eachObj(this.dynamicOutputProperties, function (val, propertyName) { | ||
utils_1.eachObj(this.dynamicOutputProperties, (val, propertyName) => { | ||
Object.defineProperty(block, propertyName, { | ||
get: function () { | ||
get() { | ||
return val.value.factory({ | ||
@@ -806,7 +844,7 @@ typeDef: block, | ||
}); | ||
}; | ||
SchemaBuilder.prototype.addDynamicScalar = function (methodName, typeName, block) { | ||
} | ||
addDynamicScalar(methodName, typeName, block) { | ||
// @ts-ignore | ||
block[methodName] = function (fieldName, opts) { | ||
var fieldConfig = { | ||
block[methodName] = (fieldName, opts) => { | ||
let fieldConfig = { | ||
type: typeName, | ||
@@ -819,3 +857,3 @@ }; | ||
else { | ||
fieldConfig = tslib_1.__assign({}, fieldConfig, opts); | ||
fieldConfig = Object.assign(Object.assign({}, fieldConfig), opts); | ||
} | ||
@@ -825,35 +863,28 @@ // @ts-ignore | ||
}; | ||
}; | ||
SchemaBuilder.prototype.walkOutputType = function (obj) { | ||
var _this = this; | ||
var definitionBlock = new objectType_1.ObjectDefinitionBlock({ | ||
} | ||
walkOutputType(obj) { | ||
const definitionBlock = new objectType_1.ObjectDefinitionBlock({ | ||
typeName: obj.name, | ||
addFieldModifications: function () { }, | ||
addInterfaces: function () { }, | ||
addField: function (f) { return _this.maybeTraverseOutputType(f); }, | ||
addDynamicOutputMembers: function (block, isList) { | ||
return _this.addDynamicOutputMembers(block, isList); | ||
}, | ||
warn: function () { }, | ||
addFieldModifications: () => { }, | ||
addInterfaces: () => { }, | ||
addField: (f) => this.maybeTraverseOutputType(f), | ||
addDynamicOutputMembers: (block, isList) => this.addDynamicOutputMembers(block, isList), | ||
warn: () => { }, | ||
}); | ||
obj.definition(definitionBlock); | ||
return obj; | ||
}; | ||
SchemaBuilder.prototype.walkInterfaceType = function (obj) { | ||
var _this = this; | ||
var definitionBlock = new interfaceType_1.InterfaceDefinitionBlock({ | ||
} | ||
walkInterfaceType(obj) { | ||
const definitionBlock = new interfaceType_1.InterfaceDefinitionBlock({ | ||
typeName: obj.name, | ||
setResolveType: function () { }, | ||
addField: function (f) { return _this.maybeTraverseOutputType(f); }, | ||
addDynamicOutputMembers: function (block, isList) { | ||
return _this.addDynamicOutputMembers(block, isList); | ||
}, | ||
warn: function () { }, | ||
setResolveType: () => { }, | ||
addField: (f) => this.maybeTraverseOutputType(f), | ||
addDynamicOutputMembers: (block, isList) => this.addDynamicOutputMembers(block, isList), | ||
warn: () => { }, | ||
}); | ||
obj.definition(definitionBlock); | ||
return obj; | ||
}; | ||
SchemaBuilder.prototype.maybeTraverseOutputType = function (type) { | ||
var _this = this; | ||
var args = type.args, fieldType = type.type; | ||
} | ||
maybeTraverseOutputType(type) { | ||
const { args, type: fieldType } = type; | ||
if (typeof fieldType !== "string" && !wrapping_1.isNexusWrappedType(fieldType)) { | ||
@@ -863,66 +894,53 @@ this.addType(fieldType); | ||
if (args) { | ||
utils_1.eachObj(args, function (val) { | ||
var t = wrapping_1.isNexusArgDef(val) ? val.value.type : val; | ||
utils_1.eachObj(args, (val) => { | ||
const t = wrapping_1.isNexusArgDef(val) ? val.value.type : val; | ||
if (typeof t !== "string" && !wrapping_1.isNexusWrappedType(t)) { | ||
_this.addType(t); | ||
this.addType(t); | ||
} | ||
}); | ||
} | ||
}; | ||
SchemaBuilder.prototype.maybeTraverseInputType = function (type) { | ||
var fieldType = type.type; | ||
} | ||
maybeTraverseInputType(type) { | ||
const { type: fieldType } = type; | ||
if (typeof fieldType !== "string" && !wrapping_1.isNexusWrappedType(fieldType)) { | ||
this.addType(fieldType); | ||
} | ||
}; | ||
SchemaBuilder.prototype.walkNamedTypes = function (namedType) { | ||
var _this = this; | ||
} | ||
walkNamedTypes(namedType) { | ||
if (graphql_1.isObjectType(namedType)) { | ||
utils_1.eachObj(namedType.getFields(), function (val) { return _this.addObjectField(val); }); | ||
utils_1.eachObj(namedType.getFields(), (val) => this.addObjectField(val)); | ||
} | ||
if (graphql_1.isInterfaceType(namedType)) { | ||
utils_1.eachObj(namedType.getFields(), function (val) { return _this.addObjectField(val); }); | ||
utils_1.eachObj(namedType.getFields(), (val) => this.addObjectField(val)); | ||
} | ||
if (graphql_1.isInputObjectType(namedType)) { | ||
utils_1.eachObj(namedType.getFields(), function (val) { | ||
return _this.addType(graphql_1.getNamedType(val.type)); | ||
}); | ||
utils_1.eachObj(namedType.getFields(), (val) => this.addType(graphql_1.getNamedType(val.type))); | ||
} | ||
}; | ||
SchemaBuilder.prototype.addObjectField = function (obj) { | ||
var _this = this; | ||
} | ||
addObjectField(obj) { | ||
this.addType(graphql_1.getNamedType(obj.type)); | ||
if (obj.args) { | ||
obj.args.forEach(function (val) { return _this.addType(graphql_1.getNamedType(val.type)); }); | ||
obj.args.forEach((val) => this.addType(graphql_1.getNamedType(val.type))); | ||
} | ||
}; | ||
return SchemaBuilder; | ||
}()); | ||
} | ||
} | ||
exports.SchemaBuilder = SchemaBuilder; | ||
function extendError(name) { | ||
return new Error(name + " was already defined and imported as a type, check the docs for extending types"); | ||
return new Error(`${name} was already defined and imported as a type, check the docs for extending types`); | ||
} | ||
function wrapAuthorize(resolver, authorize) { | ||
var _this = this; | ||
var nexusAuthWrapped = function (root, args, ctx, info) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var authResult, fieldName, parentTypeName; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4 /*yield*/, authorize(root, args, ctx, info)]; | ||
case 1: | ||
authResult = _a.sent(); | ||
if (authResult === true) { | ||
return [2 /*return*/, resolver(root, args, ctx, info)]; | ||
} | ||
if (authResult === false) { | ||
throw new Error("Not authorized"); | ||
} | ||
if (authResult instanceof Error) { | ||
throw authResult; | ||
} | ||
fieldName = info.fieldName, parentTypeName = info.parentType.name; | ||
throw new Error("Nexus authorize for " + parentTypeName + "." + fieldName + " Expected a boolean or Error, saw " + authResult); | ||
} | ||
}); | ||
}); }; | ||
const nexusAuthWrapped = (root, args, ctx, info) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const authResult = yield authorize(root, args, ctx, info); | ||
if (authResult === true) { | ||
return resolver(root, args, ctx, info); | ||
} | ||
if (authResult === false) { | ||
throw new Error("Not authorized"); | ||
} | ||
if (authResult instanceof Error) { | ||
throw authResult; | ||
} | ||
const { fieldName, parentType: { name: parentTypeName }, } = info; | ||
throw new Error(`Nexus authorize for ${parentTypeName}.${fieldName} Expected a boolean or Error, saw ${authResult}`); | ||
}); | ||
nexusAuthWrapped.nexusWrappedResolver = resolver; | ||
@@ -937,16 +955,19 @@ return nexusAuthWrapped; | ||
*/ | ||
function buildTypes(types, config, schemaBuilder) { | ||
if (config === void 0) { config = { outputs: false }; } | ||
var builder = schemaBuilder || new SchemaBuilder(config); | ||
var plugins = config.plugins || []; | ||
var pluginControllers = plugins.map(function (plugin) { | ||
return plugins_1.initializePlugin(builder, plugin); | ||
}); | ||
function buildTypes(types, config = { outputs: false }, schemaBuilder) { | ||
const internalConfig = resolveBuilderConfig(config || {}); | ||
return buildTypesInternal(types, internalConfig, schemaBuilder); | ||
} | ||
exports.buildTypes = buildTypes; | ||
/** | ||
* Internal build types woring with config rather than options. | ||
*/ | ||
function buildTypesInternal(types, config, schemaBuilder) { | ||
const builder = schemaBuilder || new SchemaBuilder(config); | ||
const plugins = config.plugins || []; | ||
const pluginControllers = plugins.map((plugin) => Plugins.initialize(builder, plugin)); | ||
addTypes(builder, types); | ||
pluginControllers.forEach(function (pluginController) { | ||
return pluginController.triggerOnInstall(); | ||
}); | ||
pluginControllers.forEach((pluginController) => pluginController.triggerOnInstall()); | ||
return builder.getFinalTypeMap(); | ||
} | ||
exports.buildTypes = buildTypes; | ||
exports.buildTypesInternal = buildTypesInternal; | ||
function addTypes(builder, types) { | ||
@@ -970,6 +991,6 @@ if (!types) { | ||
else if (Array.isArray(types)) { | ||
types.forEach(function (typeDef) { return addTypes(builder, typeDef); }); | ||
types.forEach((typeDef) => addTypes(builder, typeDef)); | ||
} | ||
else if (utils_1.isObject(types)) { | ||
Object.keys(types).forEach(function (key) { return addTypes(builder, types[key]); }); | ||
Object.keys(types).forEach((key) => addTypes(builder, types[key])); | ||
} | ||
@@ -981,15 +1002,15 @@ } | ||
*/ | ||
function makeSchemaInternal(options, schemaBuilder) { | ||
var _a = buildTypes(options.types, options, schemaBuilder), typeMap = _a.typeMap, dynamicFields = _a.dynamicFields, rootTypings = _a.rootTypings, missingTypes = _a.missingTypes; | ||
var Query = typeMap.Query, Mutation = typeMap.Mutation, Subscription = typeMap.Subscription; | ||
function makeSchemaInternal(config, schemaBuilder) { | ||
const { typeMap, dynamicFields, rootTypings, missingTypes, } = buildTypesInternal(config.types, config, schemaBuilder); | ||
const { Query, Mutation, Subscription } = typeMap; | ||
if (!graphql_1.isObjectType(Query)) { | ||
throw new Error("Expected Query to be a objectType, saw " + Query.constructor.name); | ||
throw new Error(`Expected Query to be a objectType, saw ${Query.constructor.name}`); | ||
} | ||
if (Mutation && !graphql_1.isObjectType(Mutation)) { | ||
throw new Error("Expected Mutation to be a objectType, saw " + Mutation.constructor.name); | ||
throw new Error(`Expected Mutation to be a objectType, saw ${Mutation.constructor.name}`); | ||
} | ||
if (Subscription && !graphql_1.isObjectType(Subscription)) { | ||
throw new Error("Expected Subscription to be a objectType, saw " + Subscription.constructor.name); | ||
throw new Error(`Expected Subscription to be a objectType, saw ${Subscription.constructor.name}`); | ||
} | ||
var schema = new graphql_1.GraphQLSchema({ | ||
const schema = new graphql_1.GraphQLSchema({ | ||
query: Query, | ||
@@ -1001,7 +1022,7 @@ mutation: Mutation, | ||
// Loosely related to https://github.com/graphql/graphql-js/issues/1527#issuecomment-457828990 | ||
schema.extensions = tslib_1.__assign({}, schema.extensions, { nexus: { | ||
rootTypings: rootTypings, | ||
dynamicFields: dynamicFields, | ||
schema.extensions = Object.assign(Object.assign({}, schema.extensions), { nexus: { | ||
rootTypings, | ||
dynamicFields, | ||
} }); | ||
return { schema: schema, missingTypes: missingTypes }; | ||
return { schema, missingTypes }; | ||
} | ||
@@ -1016,11 +1037,9 @@ exports.makeSchemaInternal = makeSchemaInternal; | ||
*/ | ||
function makeSchema(options) { | ||
var _a = makeSchemaInternal(options), schema = _a.schema, missingTypes = _a.missingTypes; | ||
// Only in development envs do we want to worry about regenerating the | ||
// schema definition and/or generated types. | ||
var _b = options.shouldGenerateArtifacts, shouldGenerateArtifacts = _b === void 0 ? Boolean(!process.env.NODE_ENV || process.env.NODE_ENV === "development") : _b; | ||
if (shouldGenerateArtifacts) { | ||
function makeSchema(config) { | ||
const internalConfig = resolveSchemaConfig(config); | ||
const { schema, missingTypes } = makeSchemaInternal(internalConfig); | ||
if (internalConfig.outputs.schema || internalConfig.outputs.typegen) { | ||
// Generating in the next tick allows us to use the schema | ||
// in the optional thunk for the typegen config | ||
new typegenMetadata_1.TypegenMetadata(options).generateArtifacts(schema).catch(function (e) { | ||
new typegenMetadata_1.TypegenMetadata(internalConfig).generateArtifacts(schema).catch((e) => { | ||
console.error(e); | ||
@@ -1037,16 +1056,9 @@ }); | ||
*/ | ||
function generateSchema(options) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var _a, schema, missingTypes; | ||
return tslib_1.__generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
_a = makeSchemaInternal(options), schema = _a.schema, missingTypes = _a.missingTypes; | ||
assertNoMissingTypes(schema, missingTypes); | ||
return [4 /*yield*/, new typegenMetadata_1.TypegenMetadata(options).generateArtifacts(schema)]; | ||
case 1: | ||
_b.sent(); | ||
return [2 /*return*/, schema]; | ||
} | ||
}); | ||
function generateSchema(config) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const internalConfig = resolveSchemaConfig(config); | ||
const { schema, missingTypes } = makeSchemaInternal(internalConfig); | ||
assertNoMissingTypes(schema, missingTypes); | ||
yield new typegenMetadata_1.TypegenMetadata(internalConfig).generateArtifacts(schema); | ||
return schema; | ||
}); | ||
@@ -1071,18 +1083,18 @@ } | ||
function assertNoMissingTypes(schema, missingTypes) { | ||
var missingTypesNames = Object.keys(missingTypes); | ||
var schemaTypeMap = schema.getTypeMap(); | ||
var schemaTypeNames = Object.keys(schemaTypeMap).filter(function (typeName) { return !utils_1.isUnknownType(schemaTypeMap[typeName]); }); | ||
const missingTypesNames = Object.keys(missingTypes); | ||
const schemaTypeMap = schema.getTypeMap(); | ||
const schemaTypeNames = Object.keys(schemaTypeMap).filter((typeName) => !utils_1.isUnknownType(schemaTypeMap[typeName])); | ||
if (missingTypesNames.length > 0) { | ||
var errors = missingTypesNames | ||
.map(function (typeName) { | ||
var fromObject = missingTypes[typeName].fromObject; | ||
const errors = missingTypesNames | ||
.map((typeName) => { | ||
const { fromObject } = missingTypes[typeName]; | ||
if (fromObject) { | ||
return "- Looks like you forgot to import " + typeName + " in the root \"types\" passed to Nexus makeSchema"; | ||
return `- Looks like you forgot to import ${typeName} in the root "types" passed to Nexus makeSchema`; | ||
} | ||
var suggestions = utils_1.suggestionList(typeName, schemaTypeNames); | ||
var suggestionsString = ""; | ||
const suggestions = utils_1.suggestionList(typeName, schemaTypeNames); | ||
let suggestionsString = ""; | ||
if (suggestions.length > 0) { | ||
suggestionsString = " or mean " + suggestions.join(", "); | ||
suggestionsString = ` or mean ${suggestions.join(", ")}`; | ||
} | ||
return "- Missing type " + typeName + ", did you forget to import a type to the root query" + suggestionsString + "?"; | ||
return `- Missing type ${typeName}, did you forget to import a type to the root query${suggestionsString}?`; | ||
}) | ||
@@ -1089,0 +1101,0 @@ .join("\n"); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
const tslib_1 = require("tslib"); | ||
// The "core" is used as a namespace to re-export everything, | ||
@@ -5,0 +5,0 @@ // For anyone who wants to use the internals |
@@ -22,3 +22,4 @@ import { GraphQLLeafType, GraphQLCompositeType, GraphQLInputObjectType, GraphQLFieldResolver } from "graphql"; | ||
DynamicOutputMethod = "DynamicOutputMethod", | ||
DynamicOutputProperty = "DynamicOutputProperty" | ||
DynamicOutputProperty = "DynamicOutputProperty", | ||
Plugin = "Plugin" | ||
} | ||
@@ -25,0 +26,0 @@ export interface DeprecationInfo { |
@@ -20,2 +20,3 @@ "use strict"; | ||
NexusTypes["DynamicOutputProperty"] = "DynamicOutputProperty"; | ||
NexusTypes["Plugin"] = "Plugin"; | ||
})(NexusTypes = exports.NexusTypes || (exports.NexusTypes = {})); | ||
@@ -22,0 +23,0 @@ exports.NexusWrappedSymbol = Symbol.for("@nexus/wrapped"); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
var _types_1 = require("./_types"); | ||
var NexusArgDef = /** @class */ (function () { | ||
function NexusArgDef(name, config) { | ||
const _types_1 = require("./_types"); | ||
class NexusArgDef { | ||
constructor(name, config) { | ||
this.name = name; | ||
this.config = config; | ||
} | ||
Object.defineProperty(NexusArgDef.prototype, "value", { | ||
get: function () { | ||
return this.config; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
return NexusArgDef; | ||
}()); | ||
get value() { | ||
return this.config; | ||
} | ||
} | ||
exports.NexusArgDef = NexusArgDef; | ||
@@ -40,21 +34,21 @@ _types_1.withNexusSymbol(NexusArgDef, _types_1.NexusTypes.Arg); | ||
function stringArg(options) { | ||
return arg(tslib_1.__assign({ type: "String" }, options)); | ||
return arg(Object.assign({ type: "String" }, options)); | ||
} | ||
exports.stringArg = stringArg; | ||
function intArg(options) { | ||
return arg(tslib_1.__assign({ type: "Int" }, options)); | ||
return arg(Object.assign({ type: "Int" }, options)); | ||
} | ||
exports.intArg = intArg; | ||
function floatArg(options) { | ||
return arg(tslib_1.__assign({ type: "Float" }, options)); | ||
return arg(Object.assign({ type: "Float" }, options)); | ||
} | ||
exports.floatArg = floatArg; | ||
function idArg(options) { | ||
return arg(tslib_1.__assign({ type: "ID" }, options)); | ||
return arg(Object.assign({ type: "ID" }, options)); | ||
} | ||
exports.idArg = idArg; | ||
function booleanArg(options) { | ||
return arg(tslib_1.__assign({ type: "Boolean" }, options)); | ||
return arg(Object.assign({ type: "Boolean" }, options)); | ||
} | ||
exports.booleanArg = booleanArg; | ||
//# sourceMappingURL=args.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
function decorateType(type, config) { | ||
type.extensions = tslib_1.__assign({}, type.extensions, { nexus: { | ||
type.extensions = Object.assign(Object.assign({}, type.extensions), { nexus: { | ||
asNexusMethod: config.asNexusMethod, | ||
@@ -7,0 +6,0 @@ rootTyping: config.rootTyping, |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
/** | ||
@@ -8,5 +7,4 @@ * The output definition block is passed to the "definition" | ||
*/ | ||
var OutputDefinitionBlock = /** @class */ (function () { | ||
function OutputDefinitionBlock(typeBuilder, isList) { | ||
if (isList === void 0) { isList = false; } | ||
class OutputDefinitionBlock { | ||
constructor(typeBuilder, isList = false) { | ||
this.typeBuilder = typeBuilder; | ||
@@ -17,48 +15,24 @@ this.isList = isList; | ||
} | ||
Object.defineProperty(OutputDefinitionBlock.prototype, "list", { | ||
get: function () { | ||
if (this.isList) { | ||
throw new Error("Cannot chain list.list, in the definition block. Use `list: []` config value"); | ||
} | ||
return new OutputDefinitionBlock(this.typeBuilder, true); | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
OutputDefinitionBlock.prototype.string = function (fieldName) { | ||
var opts = []; | ||
for (var _i = 1; _i < arguments.length; _i++) { | ||
opts[_i - 1] = arguments[_i]; | ||
get list() { | ||
if (this.isList) { | ||
throw new Error("Cannot chain list.list, in the definition block. Use `list: []` config value"); | ||
} | ||
return new OutputDefinitionBlock(this.typeBuilder, true); | ||
} | ||
string(fieldName, ...opts) { | ||
this.addScalarField(fieldName, "String", opts); | ||
}; | ||
OutputDefinitionBlock.prototype.int = function (fieldName) { | ||
var opts = []; | ||
for (var _i = 1; _i < arguments.length; _i++) { | ||
opts[_i - 1] = arguments[_i]; | ||
} | ||
} | ||
int(fieldName, ...opts) { | ||
this.addScalarField(fieldName, "Int", opts); | ||
}; | ||
OutputDefinitionBlock.prototype.boolean = function (fieldName) { | ||
var opts = []; | ||
for (var _i = 1; _i < arguments.length; _i++) { | ||
opts[_i - 1] = arguments[_i]; | ||
} | ||
} | ||
boolean(fieldName, ...opts) { | ||
this.addScalarField(fieldName, "Boolean", opts); | ||
}; | ||
OutputDefinitionBlock.prototype.id = function (fieldName) { | ||
var opts = []; | ||
for (var _i = 1; _i < arguments.length; _i++) { | ||
opts[_i - 1] = arguments[_i]; | ||
} | ||
} | ||
id(fieldName, ...opts) { | ||
this.addScalarField(fieldName, "ID", opts); | ||
}; | ||
OutputDefinitionBlock.prototype.float = function (fieldName) { | ||
var opts = []; | ||
for (var _i = 1; _i < arguments.length; _i++) { | ||
opts[_i - 1] = arguments[_i]; | ||
} | ||
} | ||
float(fieldName, ...opts) { | ||
this.addScalarField(fieldName, "Float", opts); | ||
}; | ||
OutputDefinitionBlock.prototype.field = function (name, fieldConfig) { | ||
} | ||
field(name, fieldConfig) { | ||
// FIXME | ||
@@ -69,7 +43,7 @@ // 1. FieldOutConfig<TypeName is constrained to any string subtype | ||
// 4. and changing FieldOutConfig to FieldOutConfig<string breaks types in other places | ||
var field = tslib_1.__assign({ name: name }, fieldConfig); | ||
const field = Object.assign({ name }, fieldConfig); | ||
this.typeBuilder.addField(this.decorateField(field)); | ||
}; | ||
OutputDefinitionBlock.prototype.addScalarField = function (fieldName, typeName, opts) { | ||
var config = { | ||
} | ||
addScalarField(fieldName, typeName, opts) { | ||
let config = { | ||
name: fieldName, | ||
@@ -83,10 +57,10 @@ type: typeName, | ||
else { | ||
config = tslib_1.__assign({}, config, opts[0]); | ||
config = Object.assign(Object.assign({}, config), opts[0]); | ||
} | ||
this.typeBuilder.addField(this.decorateField(config)); | ||
}; | ||
OutputDefinitionBlock.prototype.decorateField = function (config) { | ||
} | ||
decorateField(config) { | ||
if (this.isList) { | ||
if (config.list) { | ||
this.typeBuilder.warn("It looks like you chained .list and set list for " + config.name + ". " + | ||
this.typeBuilder.warn(`It looks like you chained .list and set list for ${config.name}. ` + | ||
"You should only do one or the other"); | ||
@@ -99,9 +73,7 @@ } | ||
return config; | ||
}; | ||
return OutputDefinitionBlock; | ||
}()); | ||
} | ||
} | ||
exports.OutputDefinitionBlock = OutputDefinitionBlock; | ||
var InputDefinitionBlock = /** @class */ (function () { | ||
function InputDefinitionBlock(typeBuilder, isList) { | ||
if (isList === void 0) { isList = false; } | ||
class InputDefinitionBlock { | ||
constructor(typeBuilder, isList = false) { | ||
this.typeBuilder = typeBuilder; | ||
@@ -112,38 +84,33 @@ this.isList = isList; | ||
} | ||
Object.defineProperty(InputDefinitionBlock.prototype, "list", { | ||
get: function () { | ||
if (this.isList) { | ||
throw new Error("Cannot chain list.list, in the definition block. Use `list: []` config value"); | ||
} | ||
return new InputDefinitionBlock(this.typeBuilder, true); | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
InputDefinitionBlock.prototype.string = function (fieldName, opts) { | ||
get list() { | ||
if (this.isList) { | ||
throw new Error("Cannot chain list.list, in the definition block. Use `list: []` config value"); | ||
} | ||
return new InputDefinitionBlock(this.typeBuilder, true); | ||
} | ||
string(fieldName, opts) { | ||
this.addScalarField(fieldName, "String", opts); | ||
}; | ||
InputDefinitionBlock.prototype.int = function (fieldName, opts) { | ||
} | ||
int(fieldName, opts) { | ||
this.addScalarField(fieldName, "Int", opts); | ||
}; | ||
InputDefinitionBlock.prototype.boolean = function (fieldName, opts) { | ||
} | ||
boolean(fieldName, opts) { | ||
this.addScalarField(fieldName, "Boolean", opts); | ||
}; | ||
InputDefinitionBlock.prototype.id = function (fieldName, opts) { | ||
} | ||
id(fieldName, opts) { | ||
this.addScalarField(fieldName, "ID", opts); | ||
}; | ||
InputDefinitionBlock.prototype.float = function (fieldName, opts) { | ||
} | ||
float(fieldName, opts) { | ||
this.addScalarField(fieldName, "Float", opts); | ||
}; | ||
InputDefinitionBlock.prototype.field = function (fieldName, fieldConfig) { | ||
this.typeBuilder.addField(this.decorateField(tslib_1.__assign({ name: fieldName }, fieldConfig))); | ||
}; | ||
InputDefinitionBlock.prototype.addScalarField = function (fieldName, typeName, opts) { | ||
if (opts === void 0) { opts = {}; } | ||
this.typeBuilder.addField(this.decorateField(tslib_1.__assign({ name: fieldName, type: typeName }, opts))); | ||
}; | ||
InputDefinitionBlock.prototype.decorateField = function (config) { | ||
} | ||
field(fieldName, fieldConfig) { | ||
this.typeBuilder.addField(this.decorateField(Object.assign({ name: fieldName }, fieldConfig))); | ||
} | ||
addScalarField(fieldName, typeName, opts = {}) { | ||
this.typeBuilder.addField(this.decorateField(Object.assign({ name: fieldName, type: typeName }, opts))); | ||
} | ||
decorateField(config) { | ||
if (this.isList) { | ||
if (config.list) { | ||
this.typeBuilder.warn("It looks like you chained .list and set list for " + config.name + | ||
this.typeBuilder.warn(`It looks like you chained .list and set list for ${config.name}` + | ||
"You should only do one or the other"); | ||
@@ -156,6 +123,5 @@ } | ||
return config; | ||
}; | ||
return InputDefinitionBlock; | ||
}()); | ||
} | ||
} | ||
exports.InputDefinitionBlock = InputDefinitionBlock; | ||
//# sourceMappingURL=definitionBlocks.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var _types_1 = require("./_types"); | ||
var graphql_1 = require("graphql"); | ||
var NexusEnumTypeDef = /** @class */ (function () { | ||
function NexusEnumTypeDef(name, config) { | ||
const _types_1 = require("./_types"); | ||
const graphql_1 = require("graphql"); | ||
class NexusEnumTypeDef { | ||
constructor(name, config) { | ||
this.name = name; | ||
@@ -11,11 +11,6 @@ this.config = config; | ||
} | ||
Object.defineProperty(NexusEnumTypeDef.prototype, "value", { | ||
get: function () { | ||
return this.config; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
return NexusEnumTypeDef; | ||
}()); | ||
get value() { | ||
return this.config; | ||
} | ||
} | ||
exports.NexusEnumTypeDef = NexusEnumTypeDef; | ||
@@ -22,0 +17,0 @@ _types_1.withNexusSymbol(NexusEnumTypeDef, _types_1.NexusTypes.Enum); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
var _types_1 = require("./_types"); | ||
var graphql_1 = require("graphql"); | ||
var NexusExtendInputTypeDef = /** @class */ (function () { | ||
function NexusExtendInputTypeDef(name, config) { | ||
const _types_1 = require("./_types"); | ||
const graphql_1 = require("graphql"); | ||
class NexusExtendInputTypeDef { | ||
constructor(name, config) { | ||
this.name = name; | ||
@@ -12,11 +11,6 @@ this.config = config; | ||
} | ||
Object.defineProperty(NexusExtendInputTypeDef.prototype, "value", { | ||
get: function () { | ||
return this.config; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
return NexusExtendInputTypeDef; | ||
}()); | ||
get value() { | ||
return this.config; | ||
} | ||
} | ||
exports.NexusExtendInputTypeDef = NexusExtendInputTypeDef; | ||
@@ -31,5 +25,5 @@ _types_1.withNexusSymbol(NexusExtendInputTypeDef, _types_1.NexusTypes.ExtendInputObject); | ||
function extendInputType(config) { | ||
return new NexusExtendInputTypeDef(config.type, tslib_1.__assign({}, config, { name: config.type })); | ||
return new NexusExtendInputTypeDef(config.type, Object.assign(Object.assign({}, config), { name: config.type })); | ||
} | ||
exports.extendInputType = extendInputType; | ||
//# sourceMappingURL=extendInputType.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
var _types_1 = require("./_types"); | ||
var graphql_1 = require("graphql"); | ||
var NexusExtendTypeDef = /** @class */ (function () { | ||
function NexusExtendTypeDef(name, config) { | ||
const _types_1 = require("./_types"); | ||
const graphql_1 = require("graphql"); | ||
class NexusExtendTypeDef { | ||
constructor(name, config) { | ||
this.name = name; | ||
@@ -12,11 +11,6 @@ this.config = config; | ||
} | ||
Object.defineProperty(NexusExtendTypeDef.prototype, "value", { | ||
get: function () { | ||
return this.config; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
return NexusExtendTypeDef; | ||
}()); | ||
get value() { | ||
return this.config; | ||
} | ||
} | ||
exports.NexusExtendTypeDef = NexusExtendTypeDef; | ||
@@ -31,5 +25,5 @@ _types_1.withNexusSymbol(NexusExtendTypeDef, _types_1.NexusTypes.ExtendObject); | ||
function extendType(config) { | ||
return new NexusExtendTypeDef(config.type, tslib_1.__assign({}, config, { name: config.type })); | ||
return new NexusExtendTypeDef(config.type, Object.assign(Object.assign({}, config), { name: config.type })); | ||
} | ||
exports.extendType = extendType; | ||
//# sourceMappingURL=extendType.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
var _types_1 = require("./_types"); | ||
var graphql_1 = require("graphql"); | ||
var args_1 = require("./args"); | ||
var NexusInputObjectTypeDef = /** @class */ (function () { | ||
function NexusInputObjectTypeDef(name, config) { | ||
const _types_1 = require("./_types"); | ||
const graphql_1 = require("graphql"); | ||
const args_1 = require("./args"); | ||
class NexusInputObjectTypeDef { | ||
constructor(name, config) { | ||
this.name = name; | ||
@@ -13,9 +12,5 @@ this.config = config; | ||
} | ||
Object.defineProperty(NexusInputObjectTypeDef.prototype, "value", { | ||
get: function () { | ||
return this.config; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
get value() { | ||
return this.config; | ||
} | ||
// FIXME | ||
@@ -25,8 +20,7 @@ // Instead of `any` we want to pass the name of this type... | ||
// from the typegen. | ||
NexusInputObjectTypeDef.prototype.asArg = function (cfg) { | ||
asArg(cfg) { | ||
// FIXME | ||
return args_1.arg(tslib_1.__assign({}, cfg, { type: this })); | ||
}; | ||
return NexusInputObjectTypeDef; | ||
}()); | ||
return args_1.arg(Object.assign(Object.assign({}, cfg), { type: this })); | ||
} | ||
} | ||
exports.NexusInputObjectTypeDef = NexusInputObjectTypeDef; | ||
@@ -33,0 +27,0 @@ _types_1.withNexusSymbol(NexusInputObjectTypeDef, _types_1.NexusTypes.InputObject); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
var definitionBlocks_1 = require("./definitionBlocks"); | ||
var _types_1 = require("./_types"); | ||
var graphql_1 = require("graphql"); | ||
var InterfaceDefinitionBlock = /** @class */ (function (_super) { | ||
tslib_1.__extends(InterfaceDefinitionBlock, _super); | ||
function InterfaceDefinitionBlock(typeBuilder) { | ||
var _this = _super.call(this, typeBuilder) || this; | ||
_this.typeBuilder = typeBuilder; | ||
return _this; | ||
const definitionBlocks_1 = require("./definitionBlocks"); | ||
const _types_1 = require("./_types"); | ||
const graphql_1 = require("graphql"); | ||
class InterfaceDefinitionBlock extends definitionBlocks_1.OutputDefinitionBlock { | ||
constructor(typeBuilder) { | ||
super(typeBuilder); | ||
this.typeBuilder = typeBuilder; | ||
} | ||
@@ -17,10 +14,9 @@ /** | ||
*/ | ||
InterfaceDefinitionBlock.prototype.resolveType = function (fn) { | ||
resolveType(fn) { | ||
this.typeBuilder.setResolveType(fn); | ||
}; | ||
return InterfaceDefinitionBlock; | ||
}(definitionBlocks_1.OutputDefinitionBlock)); | ||
} | ||
} | ||
exports.InterfaceDefinitionBlock = InterfaceDefinitionBlock; | ||
var NexusInterfaceTypeDef = /** @class */ (function () { | ||
function NexusInterfaceTypeDef(name, config) { | ||
class NexusInterfaceTypeDef { | ||
constructor(name, config) { | ||
this.name = name; | ||
@@ -30,11 +26,6 @@ this.config = config; | ||
} | ||
Object.defineProperty(NexusInterfaceTypeDef.prototype, "value", { | ||
get: function () { | ||
return this.config; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
return NexusInterfaceTypeDef; | ||
}()); | ||
get value() { | ||
return this.config; | ||
} | ||
} | ||
exports.NexusInterfaceTypeDef = NexusInterfaceTypeDef; | ||
@@ -41,0 +32,0 @@ _types_1.withNexusSymbol(NexusInterfaceTypeDef, _types_1.NexusTypes.Interface); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var extendType_1 = require("./extendType"); | ||
const extendType_1 = require("./extendType"); | ||
function mutationField(fieldName, config) { | ||
return extendType_1.extendType({ | ||
type: "Mutation", | ||
definition: function (t) { | ||
var finalConfig = typeof config === "function" ? config() : config; | ||
definition(t) { | ||
const finalConfig = typeof config === "function" ? config() : config; | ||
t.field(fieldName, finalConfig); | ||
@@ -10,0 +10,0 @@ }, |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
var definitionBlocks_1 = require("./definitionBlocks"); | ||
var _types_1 = require("./_types"); | ||
var graphql_1 = require("graphql"); | ||
var ObjectDefinitionBlock = /** @class */ (function (_super) { | ||
tslib_1.__extends(ObjectDefinitionBlock, _super); | ||
function ObjectDefinitionBlock(typeBuilder) { | ||
var _this = _super.call(this, typeBuilder) || this; | ||
_this.typeBuilder = typeBuilder; | ||
return _this; | ||
const definitionBlocks_1 = require("./definitionBlocks"); | ||
const _types_1 = require("./_types"); | ||
const graphql_1 = require("graphql"); | ||
class ObjectDefinitionBlock extends definitionBlocks_1.OutputDefinitionBlock { | ||
constructor(typeBuilder) { | ||
super(typeBuilder); | ||
this.typeBuilder = typeBuilder; | ||
} | ||
@@ -17,20 +14,15 @@ /** | ||
*/ | ||
ObjectDefinitionBlock.prototype.implements = function () { | ||
var interfaceName = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
interfaceName[_i] = arguments[_i]; | ||
} | ||
implements(...interfaceName) { | ||
this.typeBuilder.addInterfaces(interfaceName); | ||
}; | ||
} | ||
/** | ||
* Modifies a field added via an interface | ||
*/ | ||
ObjectDefinitionBlock.prototype.modify = function (field, modifications) { | ||
this.typeBuilder.addFieldModifications(tslib_1.__assign({}, modifications, { field: field })); | ||
}; | ||
return ObjectDefinitionBlock; | ||
}(definitionBlocks_1.OutputDefinitionBlock)); | ||
modify(field, modifications) { | ||
this.typeBuilder.addFieldModifications(Object.assign(Object.assign({}, modifications), { field })); | ||
} | ||
} | ||
exports.ObjectDefinitionBlock = ObjectDefinitionBlock; | ||
var NexusObjectTypeDef = /** @class */ (function () { | ||
function NexusObjectTypeDef(name, config) { | ||
class NexusObjectTypeDef { | ||
constructor(name, config) { | ||
this.name = name; | ||
@@ -40,11 +32,6 @@ this.config = config; | ||
} | ||
Object.defineProperty(NexusObjectTypeDef.prototype, "value", { | ||
get: function () { | ||
return this.config; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
return NexusObjectTypeDef; | ||
}()); | ||
get value() { | ||
return this.config; | ||
} | ||
} | ||
exports.NexusObjectTypeDef = NexusObjectTypeDef; | ||
@@ -57,9 +44,9 @@ _types_1.withNexusSymbol(NexusObjectTypeDef, _types_1.NexusTypes.Object); | ||
function queryType(config) { | ||
return objectType(tslib_1.__assign({}, config, { name: "Query" })); | ||
return objectType(Object.assign(Object.assign({}, config), { name: "Query" })); | ||
} | ||
exports.queryType = queryType; | ||
function mutationType(config) { | ||
return objectType(tslib_1.__assign({}, config, { name: "Mutation" })); | ||
return objectType(Object.assign(Object.assign({}, config), { name: "Mutation" })); | ||
} | ||
exports.mutationType = mutationType; | ||
//# sourceMappingURL=objectType.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var extendType_1 = require("./extendType"); | ||
const extendType_1 = require("./extendType"); | ||
function queryField(fieldName, config) { | ||
return extendType_1.extendType({ | ||
type: "Query", | ||
definition: function (t) { | ||
var finalConfig = typeof config === "function" ? config() : config; | ||
definition(t) { | ||
const finalConfig = typeof config === "function" ? config() : config; | ||
t.field(fieldName, finalConfig); | ||
@@ -10,0 +10,0 @@ }, |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var graphql_1 = require("graphql"); | ||
var _types_1 = require("./_types"); | ||
var decorateType_1 = require("./decorateType"); | ||
var NexusScalarTypeDef = /** @class */ (function () { | ||
function NexusScalarTypeDef(name, config) { | ||
const graphql_1 = require("graphql"); | ||
const _types_1 = require("./_types"); | ||
const decorateType_1 = require("./decorateType"); | ||
class NexusScalarTypeDef { | ||
constructor(name, config) { | ||
this.name = name; | ||
@@ -12,11 +12,6 @@ this.config = config; | ||
} | ||
Object.defineProperty(NexusScalarTypeDef.prototype, "value", { | ||
get: function () { | ||
return this.config; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
return NexusScalarTypeDef; | ||
}()); | ||
get value() { | ||
return this.config; | ||
} | ||
} | ||
exports.NexusScalarTypeDef = NexusScalarTypeDef; | ||
@@ -23,0 +18,0 @@ _types_1.withNexusSymbol(NexusScalarTypeDef, _types_1.NexusTypes.Scalar); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var extendType_1 = require("./extendType"); | ||
const extendType_1 = require("./extendType"); | ||
function subscriptionField(fieldName, config) { | ||
return extendType_1.extendType({ | ||
type: "Subscription", | ||
definition: function (t) { | ||
var finalConfig = typeof config === "function" ? config() : config; | ||
definition(t) { | ||
const finalConfig = typeof config === "function" ? config() : config; | ||
t.field(fieldName, finalConfig); | ||
@@ -10,0 +10,0 @@ }, |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var _types_1 = require("./_types"); | ||
var graphql_1 = require("graphql"); | ||
var UnionDefinitionBlock = /** @class */ (function () { | ||
function UnionDefinitionBlock(typeBuilder) { | ||
const _types_1 = require("./_types"); | ||
const graphql_1 = require("graphql"); | ||
class UnionDefinitionBlock { | ||
constructor(typeBuilder) { | ||
this.typeBuilder = typeBuilder; | ||
@@ -13,20 +13,15 @@ } | ||
*/ | ||
UnionDefinitionBlock.prototype.members = function () { | ||
var unionMembers = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
unionMembers[_i] = arguments[_i]; | ||
} | ||
members(...unionMembers) { | ||
this.typeBuilder.addUnionMembers(unionMembers); | ||
}; | ||
} | ||
/** | ||
* Sets the "resolveType" method for the current union | ||
*/ | ||
UnionDefinitionBlock.prototype.resolveType = function (fn) { | ||
resolveType(fn) { | ||
this.typeBuilder.setResolveType(fn); | ||
}; | ||
return UnionDefinitionBlock; | ||
}()); | ||
} | ||
} | ||
exports.UnionDefinitionBlock = UnionDefinitionBlock; | ||
var NexusUnionTypeDef = /** @class */ (function () { | ||
function NexusUnionTypeDef(name, config) { | ||
class NexusUnionTypeDef { | ||
constructor(name, config) { | ||
this.name = name; | ||
@@ -36,11 +31,6 @@ this.config = config; | ||
} | ||
Object.defineProperty(NexusUnionTypeDef.prototype, "value", { | ||
get: function () { | ||
return this.config; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
return NexusUnionTypeDef; | ||
}()); | ||
get value() { | ||
return this.config; | ||
} | ||
} | ||
exports.NexusUnionTypeDef = NexusUnionTypeDef; | ||
@@ -47,0 +37,0 @@ _types_1.withNexusSymbol(NexusUnionTypeDef, _types_1.NexusTypes.Union); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var _types_1 = require("./_types"); | ||
const _types_1 = require("./_types"); | ||
/** | ||
* Container object for a "wrapped function" | ||
*/ | ||
var NexusWrappedType = /** @class */ (function () { | ||
function NexusWrappedType(name, wrappedFn) { | ||
class NexusWrappedType { | ||
constructor(name, wrappedFn) { | ||
this.name = name; | ||
this.wrappedFn = wrappedFn; | ||
} | ||
Object.defineProperty(NexusWrappedType.prototype, "fn", { | ||
get: function () { | ||
return this.wrappedFn; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
return NexusWrappedType; | ||
}()); | ||
get fn() { | ||
return this.wrappedFn; | ||
} | ||
} | ||
exports.NexusWrappedType = NexusWrappedType; | ||
@@ -33,3 +28,3 @@ _types_1.withNexusSymbol(NexusWrappedType, _types_1.NexusTypes.WrappedType); | ||
exports.nexusWrappedType = nexusWrappedType; | ||
var NamedTypeDefs = new Set([ | ||
const NamedTypeDefs = new Set([ | ||
_types_1.NexusTypes.Enum, | ||
@@ -36,0 +31,0 @@ _types_1.NexusTypes.Object, |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var _types_1 = require("./definitions/_types"); | ||
var DynamicInputMethodDef = /** @class */ (function () { | ||
function DynamicInputMethodDef(name, config) { | ||
const _types_1 = require("./definitions/_types"); | ||
class DynamicInputMethodDef { | ||
constructor(name, config) { | ||
this.name = name; | ||
this.config = config; | ||
} | ||
Object.defineProperty(DynamicInputMethodDef.prototype, "value", { | ||
get: function () { | ||
return this.config; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
return DynamicInputMethodDef; | ||
}()); | ||
get value() { | ||
return this.config; | ||
} | ||
} | ||
exports.DynamicInputMethodDef = DynamicInputMethodDef; | ||
_types_1.withNexusSymbol(DynamicInputMethodDef, _types_1.NexusTypes.DynamicInput); | ||
var DynamicOutputMethodDef = /** @class */ (function () { | ||
function DynamicOutputMethodDef(name, config) { | ||
class DynamicOutputMethodDef { | ||
constructor(name, config) { | ||
this.name = name; | ||
this.config = config; | ||
} | ||
Object.defineProperty(DynamicOutputMethodDef.prototype, "value", { | ||
get: function () { | ||
return this.config; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
return DynamicOutputMethodDef; | ||
}()); | ||
get value() { | ||
return this.config; | ||
} | ||
} | ||
exports.DynamicOutputMethodDef = DynamicOutputMethodDef; | ||
@@ -35,0 +25,0 @@ _types_1.withNexusSymbol(DynamicOutputMethodDef, _types_1.NexusTypes.DynamicOutputMethod); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var _types_1 = require("./definitions/_types"); | ||
var DynamicOutputPropertyDef = /** @class */ (function () { | ||
function DynamicOutputPropertyDef(name, config) { | ||
const _types_1 = require("./definitions/_types"); | ||
class DynamicOutputPropertyDef { | ||
constructor(name, config) { | ||
this.name = name; | ||
this.config = config; | ||
} | ||
Object.defineProperty(DynamicOutputPropertyDef.prototype, "value", { | ||
get: function () { | ||
return this.config; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
return DynamicOutputPropertyDef; | ||
}()); | ||
get value() { | ||
return this.config; | ||
} | ||
} | ||
exports.DynamicOutputPropertyDef = DynamicOutputPropertyDef; | ||
@@ -19,0 +14,0 @@ _types_1.withNexusSymbol(DynamicOutputPropertyDef, _types_1.NexusTypes.DynamicOutputProperty); |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var dynamicMethod_1 = require("../dynamicMethod"); | ||
var objectType_1 = require("../definitions/objectType"); | ||
var args_1 = require("../definitions/args"); | ||
var basicCollectionMap = new Map(); | ||
const dynamicMethod_1 = require("../dynamicMethod"); | ||
const objectType_1 = require("../definitions/objectType"); | ||
const args_1 = require("../definitions/args"); | ||
const basicCollectionMap = new Map(); | ||
exports.CollectionFieldMethod = dynamicMethod_1.dynamicOutputMethod({ | ||
name: "collectionField", | ||
typeDefinition: "<FieldName extends string>(fieldName: FieldName, opts: {\n type: NexusGenObjectNames | NexusGenInterfaceNames | core.NexusObjectTypeDef<string> | core.NexusInterfaceTypeDef<string>,\n nodes: core.SubFieldResolver<TypeName, FieldName, \"nodes\">,\n totalCount: core.SubFieldResolver<TypeName, FieldName, \"totalCount\">,\n args?: core.ArgsRecord,\n nullable?: boolean,\n description?: string\n }): void;", | ||
factory: function (_a) { | ||
var t = _a.typeDef, _b = _a.args, fieldName = _b[0], config = _b[1]; | ||
typeDefinition: `<FieldName extends string>(fieldName: FieldName, opts: { | ||
type: NexusGenObjectNames | NexusGenInterfaceNames | core.NexusObjectTypeDef<string> | core.NexusInterfaceTypeDef<string>, | ||
nodes: core.SubFieldResolver<TypeName, FieldName, "nodes">, | ||
totalCount: core.SubFieldResolver<TypeName, FieldName, "totalCount">, | ||
args?: core.ArgsRecord, | ||
nullable?: boolean, | ||
description?: string | ||
}): void;`, | ||
factory({ typeDef: t, args: [fieldName, config] }) { | ||
if (!config.type) { | ||
throw new Error("Missing required property \"type\" from collectionField " + fieldName); | ||
throw new Error(`Missing required property "type" from collectionField ${fieldName}`); | ||
} | ||
var typeName = typeof config.type === "string" ? config.type : config.type.name; | ||
const typeName = typeof config.type === "string" ? config.type : config.type.name; | ||
if (config.list) { | ||
throw new Error("Collection field " + fieldName + "." + typeName + " cannot be used as a list."); | ||
throw new Error(`Collection field ${fieldName}.${typeName} cannot be used as a list.`); | ||
} | ||
if (!basicCollectionMap.has(typeName)) { | ||
basicCollectionMap.set(typeName, objectType_1.objectType({ | ||
name: typeName + "Collection", | ||
definition: function (c) { | ||
name: `${typeName}Collection`, | ||
definition(c) { | ||
c.int("totalCount"); | ||
@@ -36,17 +42,5 @@ c.list.field("nodes", { type: config.type }); | ||
description: config.description, | ||
resolve: function (root, args, ctx, info) { | ||
var nodesResolver = function () { | ||
var fArgs = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
fArgs[_i] = arguments[_i]; | ||
} | ||
return config.nodes(root, args, ctx, fArgs[3]); | ||
}; | ||
var totalCountResolver = function () { | ||
var fArgs = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
fArgs[_i] = arguments[_i]; | ||
} | ||
return config.totalCount(root, args, ctx, fArgs[3]); | ||
}; | ||
resolve(root, args, ctx, info) { | ||
const nodesResolver = (...fArgs) => config.nodes(root, args, ctx, fArgs[3]); | ||
const totalCountResolver = (...fArgs) => config.totalCount(root, args, ctx, fArgs[3]); | ||
return { | ||
@@ -53,0 +47,0 @@ nodes: nodesResolver, |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
const tslib_1 = require("tslib"); | ||
tslib_1.__exportStar(require("./collection"), exports); | ||
tslib_1.__exportStar(require("./relayConnection"), exports); | ||
//# sourceMappingURL=index.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
var dynamicMethod_1 = require("../dynamicMethod"); | ||
var objectType_1 = require("../definitions/objectType"); | ||
var args_1 = require("../definitions/args"); | ||
var relayConnectionMap = new Map(); | ||
var pageInfo; | ||
const dynamicMethod_1 = require("../dynamicMethod"); | ||
const objectType_1 = require("../definitions/objectType"); | ||
const args_1 = require("../definitions/args"); | ||
const relayConnectionMap = new Map(); | ||
let pageInfo; | ||
exports.RelayConnectionFieldMethod = dynamicMethod_1.dynamicOutputMethod({ | ||
name: "relayConnectionField", | ||
typeDefinition: "\n <FieldName extends string>(fieldName: FieldName, opts: {\n type: NexusGenObjectNames | NexusGenInterfaceNames | core.NexusObjectTypeDef<string> | core.NexusInterfaceTypeDef<string>,\n edges: core.SubFieldResolver<TypeName, FieldName, \"edges\">,\n pageInfo: core.SubFieldResolver<TypeName, FieldName, \"pageInfo\">,\n args?: Record<string, core.NexusArgDef<string>>,\n nullable?: boolean,\n description?: string\n }): void\n ", | ||
factory: function (_a) { | ||
var t = _a.typeDef, _b = _a.args, fieldName = _b[0], config = _b[1]; | ||
typeDefinition: ` | ||
<FieldName extends string>(fieldName: FieldName, opts: { | ||
type: NexusGenObjectNames | NexusGenInterfaceNames | core.NexusObjectTypeDef<string> | core.NexusInterfaceTypeDef<string>, | ||
edges: core.SubFieldResolver<TypeName, FieldName, "edges">, | ||
pageInfo: core.SubFieldResolver<TypeName, FieldName, "pageInfo">, | ||
args?: Record<string, core.NexusArgDef<string>>, | ||
nullable?: boolean, | ||
description?: string | ||
}): void | ||
`, | ||
factory({ typeDef: t, args: [fieldName, config] }) { | ||
if (!config.type) { | ||
throw new Error("Missing required property \"type\" from relayConnection field " + fieldName); | ||
throw new Error(`Missing required property "type" from relayConnection field ${fieldName}`); | ||
} | ||
var typeName = typeof config.type === "string" ? config.type : config.type.name; | ||
const typeName = typeof config.type === "string" ? config.type : config.type.name; | ||
pageInfo = | ||
pageInfo || | ||
objectType_1.objectType({ | ||
name: "ConnectionPageInfo", | ||
definition: function (p) { | ||
name: `ConnectionPageInfo`, | ||
definition(p) { | ||
p.boolean("hasNextPage"); | ||
@@ -28,12 +35,12 @@ p.boolean("hasPreviousPage"); | ||
if (config.list) { | ||
throw new Error("Collection field " + fieldName + "." + typeName + " cannot be used as a list."); | ||
throw new Error(`Collection field ${fieldName}.${typeName} cannot be used as a list.`); | ||
} | ||
if (!relayConnectionMap.has(typeName)) { | ||
relayConnectionMap.set(typeName, objectType_1.objectType({ | ||
name: typeName + "RelayConnection", | ||
definition: function (c) { | ||
name: `${typeName}RelayConnection`, | ||
definition(c) { | ||
c.list.field("edges", { | ||
type: objectType_1.objectType({ | ||
name: typeName + "Edge", | ||
definition: function (e) { | ||
name: `${typeName}Edge`, | ||
definition(e) { | ||
e.id("cursor"); | ||
@@ -50,20 +57,8 @@ e.field("node", { type: config.type }); | ||
type: relayConnectionMap.get(typeName), | ||
args: tslib_1.__assign({ first: args_1.intArg(), after: args_1.stringArg(), last: args_1.intArg(), before: args_1.stringArg() }, config.args), | ||
args: Object.assign({ first: args_1.intArg(), after: args_1.stringArg(), last: args_1.intArg(), before: args_1.stringArg() }, config.args), | ||
nullable: config.nullable, | ||
description: config.description, | ||
resolve: function (root, args, ctx, info) { | ||
var edgeResolver = function () { | ||
var fArgs = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
fArgs[_i] = arguments[_i]; | ||
} | ||
return config.edges(root, args, ctx, fArgs[3]); | ||
}; | ||
var pageInfoResolver = function () { | ||
var fArgs = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
fArgs[_i] = arguments[_i]; | ||
} | ||
return config.pageInfo(root, args, ctx, fArgs[3]); | ||
}; | ||
resolve(root, args, ctx, info) { | ||
const edgeResolver = (...fArgs) => config.edges(root, args, ctx, fArgs[3]); | ||
const pageInfoResolver = (...fArgs) => config.pageInfo(root, args, ctx, fArgs[3]); | ||
return { | ||
@@ -70,0 +65,0 @@ edges: edgeResolver, |
@@ -1,2 +0,2 @@ | ||
export { Plugin, create as createPlugin } from "./plugins"; | ||
export { createPlugin, PluginConfig, PluginBuilderLens, PluginOnInstallHandler, } from "./plugins"; | ||
export { buildTypes, makeSchema } from "./builder"; | ||
@@ -3,0 +3,0 @@ export { arg, booleanArg, floatArg, idArg, intArg, stringArg, } from "./definitions/args"; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
const tslib_1 = require("tslib"); | ||
// All of the Public API definitions | ||
var plugins_1 = require("./plugins"); | ||
exports.createPlugin = plugins_1.create; | ||
exports.createPlugin = plugins_1.createPlugin; | ||
var builder_1 = require("./builder"); | ||
@@ -55,8 +55,8 @@ exports.buildTypes = builder_1.buildTypes; | ||
exports.dynamicOutputProperty = dynamicProperty_1.dynamicOutputProperty; | ||
var core = tslib_1.__importStar(require("./core")); | ||
const core = tslib_1.__importStar(require("./core")); | ||
exports.core = core; | ||
var blocks = tslib_1.__importStar(require("./blocks")); | ||
const blocks = tslib_1.__importStar(require("./blocks")); | ||
exports.blocks = blocks; | ||
var ext = tslib_1.__importStar(require("./extensions")); | ||
const ext = tslib_1.__importStar(require("./extensions")); | ||
exports.ext = ext; | ||
//# sourceMappingURL=index.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.SDL_HEADER = "### This file was autogenerated by GraphQL Nexus\n### Do not make changes to this file directly\n"; | ||
exports.TYPEGEN_HEADER = "/**\n * This file was automatically generated by GraphQL Nexus\n * Do not make changes to this file directly\n */\n"; | ||
exports.TYPEGEN_CONFIG_WARNING = "/**\n * For better typings, you should provide configuration for how to lookup \n * the types. See the documentation for \"typegenAutoConfig\"\n */\n"; | ||
exports.SDL_HEADER = `### This file was autogenerated by GraphQL Nexus | ||
### Do not make changes to this file directly | ||
`; | ||
exports.TYPEGEN_HEADER = `/** | ||
* This file was automatically generated by GraphQL Nexus | ||
* Do not make changes to this file directly | ||
*/ | ||
`; | ||
exports.TYPEGEN_CONFIG_WARNING = `/** | ||
* For better typings, you should provide configuration for how to lookup | ||
* the types. See the documentation for "typegenAutoConfig" | ||
*/ | ||
`; | ||
//# sourceMappingURL=lang.js.map |
import { SchemaBuilder, NexusAcceptedTypeDef } from "./builder"; | ||
/** | ||
* This is a read-only builder-like api exposed to plugins in the onInstall | ||
* hook. It proxies the Nexus Builder which is a much bigger beast that we do | ||
* not want to directly expose to plugins. | ||
* A read-only builder api exposed to plugins in the onInstall hook which | ||
* proxies very limited functionality into the internal Nexus Builder. | ||
*/ | ||
declare type BuilderFacade = { | ||
export declare type PluginBuilderLens = { | ||
hasType: (typeName: string) => boolean; | ||
@@ -15,12 +14,47 @@ }; | ||
*/ | ||
export declare type Plugin = { | ||
onInstall: OnInstallHandler; | ||
export declare type PluginConfig = { | ||
name: string; | ||
onInstall?: PluginOnInstallHandler; | ||
}; | ||
declare type OnInstallHandler = (builder: BuilderFacade) => { | ||
/** | ||
* The plugin callback to execute when onInstall lifecycle event occurs. | ||
* OnInstall event occurs before type walking which means inline types are not | ||
* visible at this point yet. `builderLens.hasType` will only return true | ||
* for types the user has defined top level in their app, and any types added by | ||
* upstream plugins. | ||
*/ | ||
export declare type PluginOnInstallHandler = (builder: PluginBuilderLens) => { | ||
types: NexusAcceptedTypeDef[]; | ||
}; | ||
/** | ||
* This is the interface that Nexus uses to drive plugins meaning triggering the | ||
* lifecycle events that plugins have registered for. | ||
* The processed version of a plugin config. This lower level version has | ||
* defaults provided for optionals etc. | ||
*/ | ||
export declare type InternalPluginConfig = Required<PluginConfig>; | ||
/** | ||
* A plugin defines configuration which can document additional metadata options | ||
* for a type definition. This metadata can be used to decorate the "resolve" function | ||
* to provide custom functionality, such as logging, error handling, additional type | ||
* validation. | ||
* | ||
* You can specify options which can be defined on the schema, | ||
* the type or the plugin. The config from each of these will be | ||
* passed in during schema construction time, and used to augment the field as necessary. | ||
* | ||
* You can either return a function, with the new defintion of a resolver implementation, | ||
* or you can return an "enter" / "leave" pairing which will wrap the pre-execution of the | ||
* resolver and the "result" of the resolver, respectively. | ||
*/ | ||
export declare function createPlugin(config: PluginConfig): PluginDef; | ||
/** | ||
* A definition for a plugin. Should be passed to the `plugins: []` option | ||
* on makeSchema. Refer to `createPlugin` factory for full doc. | ||
*/ | ||
export declare class PluginDef { | ||
readonly config: InternalPluginConfig; | ||
constructor(config: InternalPluginConfig); | ||
} | ||
/** | ||
* The interface used to drive plugin execution via lifecycle event triggering. | ||
*/ | ||
declare type PluginController = { | ||
@@ -30,16 +64,7 @@ triggerOnInstall: () => void; | ||
/** | ||
* Initialize a plugin. This will gather the hook handlers (aka. callbacks, | ||
* event handlers) that the plugin has registered for. A controller is returned | ||
* that permits Nexus to trigger the hooks so executing the hook handlers. | ||
* This will gather the hook handlers (aka. callbacks, event handlers) a the | ||
* plugin has registered for and return a controller to trigger said hooks, | ||
* thus controlling execution of the plugins' hook handlers. | ||
*/ | ||
export declare const initializePlugin: (builder: SchemaBuilder, plugin: Plugin) => PluginController; | ||
/** | ||
* Create a Nexus Plugin. This function is just a convenience for not having to | ||
* import the Plugin type. Feel free to do this instead: | ||
* | ||
* import { Plugin } from "nexus" | ||
* export default { ... } as Plugin | ||
* | ||
*/ | ||
export declare const create: (plugin: Plugin) => Plugin; | ||
export declare function initialize(builder: SchemaBuilder, plugin: PluginDef): PluginController; | ||
export {}; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const _types_1 = require("./definitions/_types"); | ||
const utils_1 = require("./utils"); | ||
/** | ||
* Initialize a plugin. This will gather the hook handlers (aka. callbacks, | ||
* event handlers) that the plugin has registered for. A controller is returned | ||
* that permits Nexus to trigger the hooks so executing the hook handlers. | ||
* A plugin defines configuration which can document additional metadata options | ||
* for a type definition. This metadata can be used to decorate the "resolve" function | ||
* to provide custom functionality, such as logging, error handling, additional type | ||
* validation. | ||
* | ||
* You can specify options which can be defined on the schema, | ||
* the type or the plugin. The config from each of these will be | ||
* passed in during schema construction time, and used to augment the field as necessary. | ||
* | ||
* You can either return a function, with the new defintion of a resolver implementation, | ||
* or you can return an "enter" / "leave" pairing which will wrap the pre-execution of the | ||
* resolver and the "result" of the resolver, respectively. | ||
*/ | ||
exports.initializePlugin = function (builder, plugin) { | ||
function createPlugin(config) { | ||
validatePluginConfig(config); | ||
const internalConfig = Object.assign(Object.assign({}, configDefaults), config); | ||
return new PluginDef(internalConfig); | ||
} | ||
exports.createPlugin = createPlugin; | ||
const configDefaults = { | ||
onInstall: () => ({ types: [] }), | ||
}; | ||
/** | ||
* A definition for a plugin. Should be passed to the `plugins: []` option | ||
* on makeSchema. Refer to `createPlugin` factory for full doc. | ||
*/ | ||
class PluginDef { | ||
constructor(config) { | ||
this.config = config; | ||
} | ||
} | ||
exports.PluginDef = PluginDef; | ||
_types_1.withNexusSymbol(PluginDef, _types_1.NexusTypes.Plugin); | ||
/** | ||
* This will gather the hook handlers (aka. callbacks, event handlers) a the | ||
* plugin has registered for and return a controller to trigger said hooks, | ||
* thus controlling execution of the plugins' hook handlers. | ||
*/ | ||
function initialize(builder, plugin) { | ||
const state = { | ||
onInstallTriggered: false, | ||
}; | ||
const builderLens = { | ||
hasType: builder.hasType, | ||
}; | ||
return { | ||
triggerOnInstall: function () { | ||
if (plugin.onInstall) { | ||
var types = plugin.onInstall({ | ||
hasType: builder.hasType, | ||
}).types; | ||
types.forEach(builder.addType); | ||
triggerOnInstall: () => { | ||
// Enforce the invariant that a lifecycle hook will only ever be called once. | ||
if (state.onInstallTriggered) { | ||
throw new Error("Multiple triggers of onInstall hook detected. This should never happen. This is an internal error."); | ||
} | ||
else { | ||
state.onInstallTriggered = true; | ||
} | ||
// By doing addType on the types returned by a plugin right after it has | ||
// done so we make it possible for downstream plugins to see types added | ||
// by upstream plugins. | ||
let hookResult; | ||
try { | ||
hookResult = plugin.config.onInstall(builderLens); | ||
} | ||
catch (error) { | ||
throw new Error(`Plugin ${plugin.config.name} failed on "onInstall" hook:\n\n${error.stack}`); | ||
} | ||
validateOnInstallHookResult(plugin, hookResult); | ||
hookResult.types.forEach(builder.addType); | ||
}, | ||
}; | ||
}; | ||
} | ||
exports.initialize = initialize; | ||
/** | ||
* Create a Nexus Plugin. This function is just a convenience for not having to | ||
* import the Plugin type. Feel free to do this instead: | ||
* | ||
* import { Plugin } from "nexus" | ||
* export default { ... } as Plugin | ||
* | ||
* Validate that the configuration given by a plugin is valid. | ||
*/ | ||
exports.create = function (plugin) { return plugin; }; | ||
function validatePluginConfig(plugin) { | ||
const validRequiredProps = ["name"]; | ||
const validOptionalProps = ["onInstall"]; | ||
const validProps = [...validRequiredProps, ...validOptionalProps]; | ||
const givenProps = Object.keys(plugin); | ||
const printProps = (props) => { | ||
return [...props].join(", "); | ||
}; | ||
const [missingRequiredProps, ,] = utils_1.venn(validRequiredProps, givenProps); | ||
if (missingRequiredProps.size > 0) { | ||
throw new Error(`Plugin "${plugin.name}" is missing required properties: ${printProps(missingRequiredProps)}`); | ||
} | ||
const nameType = typeof plugin.name; | ||
if (nameType !== "string") { | ||
throw new Error(`Plugin "${plugin.name}" is giving an invalid value for property name: expected "string" type, got ${nameType} type`); | ||
} | ||
if (plugin.name === "") { | ||
throw new Error(`Plugin "${plugin.name}" is giving an invalid value for property name: empty string`); | ||
} | ||
const [, , invalidGivenProps] = utils_1.venn(validProps, givenProps); | ||
if (invalidGivenProps.size > 0) { | ||
throw new Error(`Plugin "${plugin.name}" is giving unexpected properties: ${printProps(invalidGivenProps)}`); | ||
} | ||
if (plugin.onInstall) { | ||
const onInstallType = typeof plugin.onInstall; | ||
if (onInstallType !== "function") { | ||
throw new Error(`Plugin "${plugin.name}" is giving an invalid value for onInstall hook: expected "function" type, got ${onInstallType} type`); | ||
} | ||
} | ||
} | ||
/** | ||
* Validate that the data returned from a plugin from the `onInstall` hook is valid. | ||
*/ | ||
function validateOnInstallHookResult(plugin, hookResult) { | ||
if (hookResult === null || | ||
typeof hookResult !== "object" || | ||
!Array.isArray(hookResult.types)) { | ||
throw new Error(`Plugin "${plugin.config.name}" returned invalid data for "onInstall" hook:\n\nexpected structure:\n\n { types: NexusAcceptedTypeDef[] }\n\ngot:\n\n ${hookResult}`); | ||
} | ||
// TODO we should validate that the array members all fall under NexusAcceptedTypeDef | ||
} | ||
//# sourceMappingURL=plugins.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var graphql_1 = require("graphql"); | ||
var utils_1 = require("./utils"); | ||
function convertSDL(sdl, commonjs, json) { | ||
if (commonjs === void 0) { commonjs = false; } | ||
if (json === void 0) { json = JSON; } | ||
const graphql_1 = require("graphql"); | ||
const utils_1 = require("./utils"); | ||
function convertSDL(sdl, commonjs = false, json = JSON) { | ||
try { | ||
@@ -12,3 +10,3 @@ return new SDLConverter(sdl, commonjs, json).print(); | ||
catch (e) { | ||
return "Error Parsing SDL into Schema: " + e.stack; | ||
return `Error Parsing SDL into Schema: ${e.stack}`; | ||
} | ||
@@ -20,6 +18,4 @@ } | ||
*/ | ||
var SDLConverter = /** @class */ (function () { | ||
function SDLConverter(sdl, commonjs, json) { | ||
if (commonjs === void 0) { commonjs = false; } | ||
if (json === void 0) { json = JSON; } | ||
class SDLConverter { | ||
constructor(sdl, commonjs = false, json = JSON) { | ||
this.commonjs = commonjs; | ||
@@ -33,4 +29,4 @@ this.json = json; | ||
} | ||
SDLConverter.prototype.print = function () { | ||
var body = [ | ||
print() { | ||
const body = [ | ||
this.printObjectTypes(), | ||
@@ -46,72 +42,68 @@ this.printInterfaceTypes(), | ||
.concat(body) | ||
.filter(function (f) { return f; }) | ||
.filter((f) => f) | ||
.join("\n\n"); | ||
}; | ||
SDLConverter.prototype.printUsedImports = function () { | ||
} | ||
printUsedImports() { | ||
if (this.commonjs) { | ||
return "const { " + Array.from(this.usedImports).join(", ") + " } = require('nexus');"; | ||
return `const { ${Array.from(this.usedImports).join(", ")} } = require('nexus');`; | ||
} | ||
return "import { " + Array.from(this.usedImports).join(", ") + " } from 'nexus';"; | ||
}; | ||
SDLConverter.prototype.printObjectTypes = function () { | ||
var _this = this; | ||
return `import { ${Array.from(this.usedImports).join(", ")} } from 'nexus';`; | ||
} | ||
printObjectTypes() { | ||
if (this.groupedTypes.object.length > 0) { | ||
this.usedImports.add("objectType"); | ||
return this.groupedTypes.object | ||
.map(function (t) { return _this.printObjectType(t); }) | ||
.map((t) => this.printObjectType(t)) | ||
.join("\n"); | ||
} | ||
return ""; | ||
}; | ||
SDLConverter.prototype.printObjectType = function (type) { | ||
var implementing = type.getInterfaces().map(function (i) { return i.name; }); | ||
var implementsInterfaces = implementing.length > 0 | ||
? " t.implements(" + implementing.join(", ") + ")" | ||
} | ||
printObjectType(type) { | ||
const implementing = type.getInterfaces().map((i) => i.name); | ||
const implementsInterfaces = implementing.length > 0 | ||
? ` t.implements(${implementing.join(", ")})` | ||
: ""; | ||
this.exports.add(type.name); | ||
return this.printBlock([ | ||
"" + this.export + type.name + " = objectType({", | ||
" name: \"" + type.name + "\",", | ||
`${this.export}${type.name} = objectType({`, | ||
` name: "${type.name}",`, | ||
this.maybeDescription(type), | ||
" definition(t) {", | ||
` definition(t) {`, | ||
implementsInterfaces, | ||
this.printObjectFields(type), | ||
" }", | ||
"})", | ||
` }`, | ||
`})`, | ||
]); | ||
}; | ||
SDLConverter.prototype.printObjectFields = function (type) { | ||
var _this = this; | ||
} | ||
printObjectFields(type) { | ||
return utils_1.objValues(type.getFields()) | ||
.map(function (field) { | ||
.map((field) => { | ||
if (graphql_1.isObjectType(type) && utils_1.isInterfaceField(type, field.name)) { | ||
return; | ||
} | ||
return _this.printField("output", field); | ||
return this.printField("output", field); | ||
}) | ||
.filter(function (f) { return f; }) | ||
.filter((f) => f) | ||
.join("\n"); | ||
}; | ||
SDLConverter.prototype.printInputObjectFields = function (type) { | ||
var _this = this; | ||
} | ||
printInputObjectFields(type) { | ||
return utils_1.objValues(type.getFields()) | ||
.map(function (field) { return _this.printField("input", field); }) | ||
.filter(function (f) { return f; }) | ||
.map((field) => this.printField("input", field)) | ||
.filter((f) => f) | ||
.join("\n"); | ||
}; | ||
SDLConverter.prototype.printField = function (source, field) { | ||
var _a = unwrapType(field.type), list = _a.list, fieldType = _a.type, isNonNull = _a.isNonNull; | ||
var prefix = list.length === 1 && list[0] === true ? "t.list." : "t."; | ||
return " " + prefix + this.printFieldMethod(source, field, fieldType, list, isNonNull); | ||
}; | ||
SDLConverter.prototype.printFieldMethod = function (source, field, type, list, isNonNull) { | ||
var _this = this; | ||
var objectMeta = {}; | ||
var str = ""; | ||
} | ||
printField(source, field) { | ||
const { list, type: fieldType, isNonNull } = unwrapType(field.type); | ||
const prefix = list.length === 1 && list[0] === true ? `t.list.` : `t.`; | ||
return ` ${prefix}${this.printFieldMethod(source, field, fieldType, list, isNonNull)}`; | ||
} | ||
printFieldMethod(source, field, type, list, isNonNull) { | ||
const objectMeta = {}; | ||
let str = ""; | ||
if (isCommonScalar(type)) { | ||
str += type.name.toLowerCase() + "(\"" + field.name + "\""; | ||
str += `${type.name.toLowerCase()}("${field.name}"`; | ||
} | ||
else { | ||
objectMeta.type = type; | ||
str += "field(\"" + field.name + "\""; | ||
str += `field("${field.name}"`; | ||
} | ||
@@ -134,3 +126,3 @@ if ("deprecationReason" in field && field.deprecationReason) { | ||
if (source === "output") { | ||
var outputField = field; | ||
const outputField = field; | ||
if (outputField.args.length) { | ||
@@ -141,3 +133,3 @@ objectMeta.args = outputField.args; | ||
else { | ||
var inputField = field; | ||
const inputField = field; | ||
if (inputField.defaultValue !== undefined) { | ||
@@ -147,20 +139,19 @@ objectMeta.default = inputField.defaultValue; | ||
} | ||
var metaKeys = Object.keys(objectMeta); | ||
const metaKeys = Object.keys(objectMeta); | ||
if (metaKeys.length > 0) { | ||
if (metaKeys.length === 1 && !objectMeta.args) { | ||
var key = metaKeys[0]; | ||
str += ", { " + key + ": " + this.printMeta(objectMeta[key], key) + " }"; | ||
const key = metaKeys[0]; | ||
str += `, { ${key}: ${this.printMeta(objectMeta[key], key)} }`; | ||
} | ||
else { | ||
str += ", {\n"; | ||
utils_1.eachObj(objectMeta, function (val, key) { | ||
str += " " + key + ": " + _this.printMeta(val, key) + ",\n"; | ||
str += `, {\n`; | ||
utils_1.eachObj(objectMeta, (val, key) => { | ||
str += ` ${key}: ${this.printMeta(val, key)},\n`; | ||
}); | ||
str += " }"; | ||
str += ` }`; | ||
} | ||
} | ||
return str + ")"; | ||
}; | ||
SDLConverter.prototype.printMeta = function (val, key) { | ||
var _this = this; | ||
return `${str})`; | ||
} | ||
printMeta(val, key) { | ||
if (key === "type") { | ||
@@ -171,42 +162,42 @@ return val; | ||
return Array.isArray(val) | ||
? "[" + val.join(", ") + "]" | ||
? `[${val.join(", ")}]` | ||
: this.json.stringify(val); | ||
} | ||
if (key === "args") { | ||
var str_1 = "{\n"; | ||
val.forEach(function (arg) { | ||
str_1 += " " + arg.name + ": " + _this.printArg(arg) + "\n"; | ||
let str = `{\n`; | ||
val.forEach((arg) => { | ||
str += ` ${arg.name}: ${this.printArg(arg)}\n`; | ||
}); | ||
str_1 += " }"; | ||
return str_1; | ||
str += ` }`; | ||
return str; | ||
} | ||
return this.json.stringify(val); | ||
}; | ||
SDLConverter.prototype.printArg = function (arg) { | ||
var description = arg.description; | ||
var _a = unwrapType(arg.type), list = _a.list, isNonNull = _a.isNonNull, type = _a.type; | ||
var isArg = !isCommonScalar(type); | ||
var str = ""; | ||
} | ||
printArg(arg) { | ||
const description = arg.description; | ||
const { list, isNonNull, type } = unwrapType(arg.type); | ||
const isArg = !isCommonScalar(type); | ||
let str = ""; | ||
if (isArg) { | ||
this.usedImports.add("arg"); | ||
str += "arg("; | ||
str += `arg(`; | ||
} | ||
else { | ||
this.usedImports.add(type.toString().toLowerCase() + "Arg"); | ||
str += type.toString().toLowerCase() + "Arg("; | ||
this.usedImports.add(`${type.toString().toLowerCase()}Arg`); | ||
str += `${type.toString().toLowerCase()}Arg(`; | ||
} | ||
var metaToAdd = []; | ||
const metaToAdd = []; | ||
if (isArg) { | ||
metaToAdd.push("type: " + type.name); | ||
metaToAdd.push(`type: ${type.name}`); | ||
} | ||
if (description) { | ||
metaToAdd.push("description: " + JSON.stringify(description)); | ||
metaToAdd.push(`description: ${JSON.stringify(description)}`); | ||
} | ||
if (list.length) { | ||
metaToAdd.push(list.length === 1 && list[0] === true | ||
? "list: true" | ||
: "list: [" + list.join(", ") + "]"); | ||
? `list: true` | ||
: `list: [${list.join(", ")}]`); | ||
} | ||
if (arg.defaultValue !== undefined) { | ||
metaToAdd.push("default: " + this.json.stringify(arg.defaultValue)); | ||
metaToAdd.push(`default: ${this.json.stringify(arg.defaultValue)}`); | ||
} | ||
@@ -218,155 +209,149 @@ if (isNonNull) { | ||
metaToAdd.length > 1 | ||
? "{\n " + metaToAdd.join(",\n ") + "\n }" | ||
? `{\n ${metaToAdd.join(",\n ")}\n }` | ||
: metaToAdd.length | ||
? "{ " + metaToAdd[0] + " }" | ||
? `{ ${metaToAdd[0]} }` | ||
: ""; | ||
return str + "),"; | ||
}; | ||
SDLConverter.prototype.printInterfaceTypes = function () { | ||
var _this = this; | ||
return `${str}),`; | ||
} | ||
printInterfaceTypes() { | ||
if (this.groupedTypes.interface.length) { | ||
this.usedImports.add("interfaceType"); | ||
return this.groupedTypes.interface | ||
.map(function (t) { return _this.printInterfaceType(t); }) | ||
.map((t) => this.printInterfaceType(t)) | ||
.join("\n"); | ||
} | ||
return ""; | ||
}; | ||
SDLConverter.prototype.printInterfaceType = function (type) { | ||
} | ||
printInterfaceType(type) { | ||
this.exports.add(type.name); | ||
return this.printBlock([ | ||
"" + this.export + type.name + " = interfaceType({", | ||
" name: \"" + type.name + "\",", | ||
`${this.export}${type.name} = interfaceType({`, | ||
` name: "${type.name}",`, | ||
this.maybeDescription(type), | ||
" definition(t) {", | ||
` definition(t) {`, | ||
this.printObjectFields(type), | ||
" t.resolveType(() => null)", | ||
" }", | ||
"});", | ||
` t.resolveType(() => null)`, | ||
` }`, | ||
`});`, | ||
]); | ||
}; | ||
SDLConverter.prototype.printEnumTypes = function () { | ||
var _this = this; | ||
} | ||
printEnumTypes() { | ||
if (this.groupedTypes.enum.length) { | ||
this.usedImports.add("enumType"); | ||
return this.groupedTypes.enum | ||
.map(function (t) { return _this.printEnumType(t); }) | ||
.map((t) => this.printEnumType(t)) | ||
.join("\n"); | ||
} | ||
return ""; | ||
}; | ||
SDLConverter.prototype.printEnumType = function (type) { | ||
var members = type.getValues().map(function (val) { | ||
var description = val.description, name = val.name, deprecationReason = val.deprecationReason, value = val.value; | ||
} | ||
printEnumType(type) { | ||
const members = type.getValues().map((val) => { | ||
const { description, name, deprecationReason, value } = val; | ||
if (!description && !deprecationReason && name === value) { | ||
return val.name; | ||
} | ||
return { description: description, name: name, deprecation: deprecationReason, value: value }; | ||
return { description, name, deprecation: deprecationReason, value }; | ||
}); | ||
this.exports.add(type.name); | ||
return this.printBlock([ | ||
"" + this.export + type.name + " = enumType({", | ||
" name: \"" + type.name + "\",", | ||
`${this.export}${type.name} = enumType({`, | ||
` name: "${type.name}",`, | ||
this.maybeDescription(type), | ||
" members: " + this.json.stringify(members) + ",", | ||
"});", | ||
` members: ${this.json.stringify(members)},`, | ||
`});`, | ||
]); | ||
}; | ||
SDLConverter.prototype.printInputObjectTypes = function () { | ||
var _this = this; | ||
} | ||
printInputObjectTypes() { | ||
if (this.groupedTypes.input.length) { | ||
this.usedImports.add("inputObjectType"); | ||
return this.groupedTypes.input | ||
.map(function (t) { return _this.printInputObjectType(t); }) | ||
.map((t) => this.printInputObjectType(t)) | ||
.join("\n"); | ||
} | ||
return ""; | ||
}; | ||
SDLConverter.prototype.printInputObjectType = function (type) { | ||
} | ||
printInputObjectType(type) { | ||
this.exports.add(type.name); | ||
return this.printBlock([ | ||
"" + this.export + type.name + " = inputObjectType({", | ||
" name: \"" + type.name + "\",", | ||
`${this.export}${type.name} = inputObjectType({`, | ||
` name: "${type.name}",`, | ||
this.maybeDescription(type), | ||
" definition(t) {", | ||
` definition(t) {`, | ||
this.printInputObjectFields(type), | ||
" }", | ||
"});", | ||
` }`, | ||
`});`, | ||
]); | ||
}; | ||
SDLConverter.prototype.printUnionTypes = function () { | ||
var _this = this; | ||
} | ||
printUnionTypes() { | ||
if (this.groupedTypes.union.length) { | ||
this.usedImports.add("unionType"); | ||
return this.groupedTypes.union | ||
.map(function (t) { return _this.printUnionType(t); }) | ||
.map((t) => this.printUnionType(t)) | ||
.join("\n"); | ||
} | ||
return ""; | ||
}; | ||
SDLConverter.prototype.printUnionType = function (type) { | ||
} | ||
printUnionType(type) { | ||
this.exports.add(type.name); | ||
return this.printBlock([ | ||
"" + this.export + type.name + " = unionType({", | ||
" name: \"" + type.name + "\",", | ||
`${this.export}${type.name} = unionType({`, | ||
` name: "${type.name}",`, | ||
this.maybeDescription(type), | ||
" definition(t) {", | ||
" t.members(" + type.getTypes().join(", ") + ")", | ||
" }", | ||
"});", | ||
` definition(t) {`, | ||
` t.members(${type.getTypes().join(", ")})`, | ||
` }`, | ||
`});`, | ||
]); | ||
}; | ||
SDLConverter.prototype.printScalarTypes = function () { | ||
var _this = this; | ||
} | ||
printScalarTypes() { | ||
if (this.groupedTypes.scalar.length) { | ||
this.usedImports.add("scalarType"); | ||
return this.groupedTypes.scalar | ||
.filter(function (s) { return !graphql_1.isSpecifiedScalarType(s); }) | ||
.map(function (t) { return _this.printScalarType(t); }) | ||
.filter((s) => !graphql_1.isSpecifiedScalarType(s)) | ||
.map((t) => this.printScalarType(t)) | ||
.join("\n"); | ||
} | ||
return ""; | ||
}; | ||
SDLConverter.prototype.printScalarType = function (type) { | ||
} | ||
printScalarType(type) { | ||
this.exports.add(type.name); | ||
return this.printBlock([ | ||
"" + this.export + type.name + " = scalarType({", | ||
" name: \"" + type.name + "\",", | ||
`${this.export}${type.name} = scalarType({`, | ||
` name: "${type.name}",`, | ||
this.maybeDescription(type), | ||
this.maybeAsNexusType(type), | ||
" serialize() { /* Todo */ },", | ||
" parseValue() { /* Todo */ },", | ||
" parseLiteral() { /* Todo */ }", | ||
"});", | ||
` serialize() { /* Todo */ },`, | ||
` parseValue() { /* Todo */ },`, | ||
` parseLiteral() { /* Todo */ }`, | ||
`});`, | ||
]); | ||
}; | ||
SDLConverter.prototype.printExports = function () { | ||
} | ||
printExports() { | ||
if (!this.commonjs || this.exports.size === 0) { | ||
return ""; | ||
} | ||
var exports = Array.from(this.exports); | ||
return this.printBlock(exports.map(function (exp) { return "exports." + exp + " = " + exp + ";"; })); | ||
}; | ||
SDLConverter.prototype.maybeAsNexusType = function (type) { | ||
const exports = Array.from(this.exports); | ||
return this.printBlock(exports.map((exp) => `exports.${exp} = ${exp};`)); | ||
} | ||
maybeAsNexusType(type) { | ||
if (isCommonScalar(type)) { | ||
return " asNexusMethod: \"" + type.name.toLowerCase() + "\","; | ||
return ` asNexusMethod: "${type.name.toLowerCase()}",`; | ||
} | ||
return null; | ||
}; | ||
SDLConverter.prototype.maybeDescription = function (type) { | ||
} | ||
maybeDescription(type) { | ||
if (type.description) { | ||
return " description: " + this.json.stringify(type.description) + ","; | ||
return ` description: ${this.json.stringify(type.description)},`; | ||
} | ||
return null; | ||
}; | ||
SDLConverter.prototype.printBlock = function (block) { | ||
return block.filter(function (t) { return t !== null && t !== ""; }).join("\n"); | ||
}; | ||
return SDLConverter; | ||
}()); | ||
} | ||
printBlock(block) { | ||
return block.filter((t) => t !== null && t !== "").join("\n"); | ||
} | ||
} | ||
exports.SDLConverter = SDLConverter; | ||
function unwrapType(type) { | ||
var finalType = type; | ||
var isNonNull = false; | ||
var list = []; | ||
let finalType = type; | ||
let isNonNull = false; | ||
const list = []; | ||
while (graphql_1.isWrappingType(finalType)) { | ||
@@ -388,3 +373,3 @@ while (graphql_1.isListType(finalType)) { | ||
} | ||
return { type: finalType, isNonNull: isNonNull, list: list }; | ||
return { type: finalType, isNonNull, list }; | ||
} | ||
@@ -391,0 +376,0 @@ function isCommonScalar(field) { |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
var graphql_1 = require("graphql"); | ||
var path_1 = tslib_1.__importDefault(require("path")); | ||
var utils_1 = require("./utils"); | ||
var SpecifiedScalars = { | ||
const tslib_1 = require("tslib"); | ||
const graphql_1 = require("graphql"); | ||
const path_1 = tslib_1.__importDefault(require("path")); | ||
const utils_1 = require("./utils"); | ||
const SpecifiedScalars = { | ||
ID: "string", | ||
@@ -29,18 +29,18 @@ String: "string", | ||
*/ | ||
var Typegen = /** @class */ (function () { | ||
function Typegen(schema, typegenInfo, extensions) { | ||
class Typegen { | ||
constructor(schema, typegenInfo, extensions) { | ||
this.schema = schema; | ||
this.typegenInfo = typegenInfo; | ||
this.extensions = extensions; | ||
this.printObj = function (space, source) { return function (val, key) { | ||
return ["" + space + key + ": { // " + source] | ||
.concat(utils_1.mapObj(val, function (v2, k2) { | ||
return space + " " + k2 + v2[0] + " " + v2[1]; | ||
this.printObj = (space, source) => (val, key) => { | ||
return [`${space}${key}: { // ${source}`] | ||
.concat(utils_1.mapObj(val, (v2, k2) => { | ||
return `${space} ${k2}${v2[0]} ${v2[1]}`; | ||
})) | ||
.concat(space + "}") | ||
.concat(`${space}}`) | ||
.join("\n"); | ||
}; }; | ||
}; | ||
this.groupedTypes = utils_1.groupTypes(schema); | ||
} | ||
Typegen.prototype.print = function () { | ||
print() { | ||
return [ | ||
@@ -64,4 +64,4 @@ this.printHeaders(), | ||
].join("\n\n"); | ||
}; | ||
Typegen.prototype.printHeaders = function () { | ||
} | ||
printHeaders() { | ||
return [ | ||
@@ -76,52 +76,52 @@ this.typegenInfo.headers.join("\n"), | ||
].join("\n"); | ||
}; | ||
Typegen.prototype.printGenTypeMap = function () { | ||
return ["export interface NexusGenTypes {"] | ||
} | ||
printGenTypeMap() { | ||
return [`export interface NexusGenTypes {`] | ||
.concat([ | ||
" context: " + this.printContext() + ";", | ||
" inputTypes: NexusGenInputs;", | ||
" rootTypes: NexusGenRootTypes;", | ||
" argTypes: NexusGenArgTypes;", | ||
" fieldTypes: NexusGenFieldTypes;", | ||
" allTypes: NexusGenAllTypes;", | ||
" inheritedFields: NexusGenInheritedFields;", | ||
" objectNames: NexusGenObjectNames;", | ||
" inputNames: NexusGenInputNames;", | ||
" enumNames: NexusGenEnumNames;", | ||
" interfaceNames: NexusGenInterfaceNames;", | ||
" scalarNames: NexusGenScalarNames;", | ||
" unionNames: NexusGenUnionNames;", | ||
" allInputTypes: NexusGenTypes['inputNames'] | NexusGenTypes['enumNames'] | NexusGenTypes['scalarNames'];", | ||
" allOutputTypes: NexusGenTypes['objectNames'] | NexusGenTypes['enumNames'] | NexusGenTypes['unionNames'] | NexusGenTypes['interfaceNames'] | NexusGenTypes['scalarNames'];", | ||
" allNamedTypes: NexusGenTypes['allInputTypes'] | NexusGenTypes['allOutputTypes']", | ||
" abstractTypes: NexusGenTypes['interfaceNames'] | NexusGenTypes['unionNames'];", | ||
" abstractResolveReturn: NexusGenAbstractResolveReturnTypes;", | ||
` context: ${this.printContext()};`, | ||
` inputTypes: NexusGenInputs;`, | ||
` rootTypes: NexusGenRootTypes;`, | ||
` argTypes: NexusGenArgTypes;`, | ||
` fieldTypes: NexusGenFieldTypes;`, | ||
` allTypes: NexusGenAllTypes;`, | ||
` inheritedFields: NexusGenInheritedFields;`, | ||
` objectNames: NexusGenObjectNames;`, | ||
` inputNames: NexusGenInputNames;`, | ||
` enumNames: NexusGenEnumNames;`, | ||
` interfaceNames: NexusGenInterfaceNames;`, | ||
` scalarNames: NexusGenScalarNames;`, | ||
` unionNames: NexusGenUnionNames;`, | ||
` allInputTypes: NexusGenTypes['inputNames'] | NexusGenTypes['enumNames'] | NexusGenTypes['scalarNames'];`, | ||
` allOutputTypes: NexusGenTypes['objectNames'] | NexusGenTypes['enumNames'] | NexusGenTypes['unionNames'] | NexusGenTypes['interfaceNames'] | NexusGenTypes['scalarNames'];`, | ||
` allNamedTypes: NexusGenTypes['allInputTypes'] | NexusGenTypes['allOutputTypes']`, | ||
` abstractTypes: NexusGenTypes['interfaceNames'] | NexusGenTypes['unionNames'];`, | ||
` abstractResolveReturn: NexusGenAbstractResolveReturnTypes;`, | ||
]) | ||
.concat("}") | ||
.join("\n"); | ||
}; | ||
Typegen.prototype.printDynamicImport = function () { | ||
var _a = this.extensions, _b = _a.dynamicFields, dynamicInputFields = _b.dynamicInputFields, dynamicOutputFields = _b.dynamicOutputFields, rootTypings = _a.rootTypings; | ||
var imports = []; | ||
if ([dynamicInputFields, dynamicOutputFields].some(function (o) { return Object.keys(o).length > 0; })) { | ||
imports.push("import { core } from \"nexus\""); | ||
} | ||
printDynamicImport() { | ||
const { dynamicFields: { dynamicInputFields, dynamicOutputFields }, rootTypings, } = this.extensions; | ||
const imports = []; | ||
if ([dynamicInputFields, dynamicOutputFields].some((o) => Object.keys(o).length > 0)) { | ||
imports.push(`import { core } from "nexus"`); | ||
} | ||
var importMap = {}; | ||
var outputPath = this.typegenInfo.typegenFile; | ||
utils_1.eachObj(rootTypings, function (val, key) { | ||
const importMap = {}; | ||
const outputPath = this.typegenInfo.typegenFile; | ||
utils_1.eachObj(rootTypings, (val, key) => { | ||
if (typeof val !== "string") { | ||
var importPath = (path_1.default.isAbsolute(val.path) | ||
const importPath = (path_1.default.isAbsolute(val.path) | ||
? utils_1.relativePathTo(val.path, outputPath) | ||
: val.path).replace(/(\.d)?\.ts/, ""); | ||
importMap[importPath] = importMap[importPath] || new Set(); | ||
importMap[importPath].add(val.alias ? val.name + " as " + val.alias : val.name); | ||
importMap[importPath].add(val.alias ? `${val.name} as ${val.alias}` : val.name); | ||
} | ||
}); | ||
utils_1.eachObj(importMap, function (val, key) { | ||
imports.push("import { " + Array.from(val).join(", ") + " } from " + JSON.stringify(key)); | ||
utils_1.eachObj(importMap, (val, key) => { | ||
imports.push(`import { ${Array.from(val).join(", ")} } from ${JSON.stringify(key)}`); | ||
}); | ||
return imports.join("\n"); | ||
}; | ||
Typegen.prototype.printDynamicInputFieldDefinitions = function () { | ||
var dynamicInputFields = this.extensions.dynamicFields.dynamicInputFields; | ||
} | ||
printDynamicInputFieldDefinitions() { | ||
const { dynamicInputFields } = this.extensions.dynamicFields; | ||
// If there is nothing custom... exit | ||
@@ -132,17 +132,17 @@ if (!Object.keys(dynamicInputFields).length) { | ||
return [ | ||
"declare global {", | ||
" interface NexusGenCustomInputMethods<TypeName extends string> {", | ||
`declare global {`, | ||
` interface NexusGenCustomInputMethods<TypeName extends string> {`, | ||
] | ||
.concat(utils_1.mapObj(dynamicInputFields, function (val, key) { | ||
.concat(utils_1.mapObj(dynamicInputFields, (val, key) => { | ||
if (typeof val === "string") { | ||
return " " + key + "<FieldName extends string>(fieldName: FieldName, opts?: core.ScalarInputFieldConfig<core.GetGen3<\"inputTypes\", TypeName, FieldName>>): void // " + JSON.stringify(val) + ";"; | ||
return ` ${key}<FieldName extends string>(fieldName: FieldName, opts?: core.ScalarInputFieldConfig<core.GetGen3<"inputTypes", TypeName, FieldName>>): void // ${JSON.stringify(val)};`; | ||
} | ||
return " " + key + (val.value.typeDefinition || | ||
"(...args: any): void"); | ||
return ` ${key}${val.value.typeDefinition || | ||
`(...args: any): void`}`; | ||
})) | ||
.concat([" }", "}"]) | ||
.concat([` }`, `}`]) | ||
.join("\n"); | ||
}; | ||
Typegen.prototype.printDynamicOutputFieldDefinitions = function () { | ||
var dynamicOutputFields = this.extensions.dynamicFields.dynamicOutputFields; | ||
} | ||
printDynamicOutputFieldDefinitions() { | ||
const { dynamicOutputFields } = this.extensions.dynamicFields; | ||
// If there is nothing custom... exit | ||
@@ -153,17 +153,17 @@ if (!Object.keys(dynamicOutputFields).length) { | ||
return [ | ||
"declare global {", | ||
" interface NexusGenCustomOutputMethods<TypeName extends string> {", | ||
`declare global {`, | ||
` interface NexusGenCustomOutputMethods<TypeName extends string> {`, | ||
] | ||
.concat(utils_1.mapObj(dynamicOutputFields, function (val, key) { | ||
.concat(utils_1.mapObj(dynamicOutputFields, (val, key) => { | ||
if (typeof val === "string") { | ||
return " " + key + "<FieldName extends string>(fieldName: FieldName, ...opts: core.ScalarOutSpread<TypeName, FieldName>): void // " + JSON.stringify(val) + ";"; | ||
return ` ${key}<FieldName extends string>(fieldName: FieldName, ...opts: core.ScalarOutSpread<TypeName, FieldName>): void // ${JSON.stringify(val)};`; | ||
} | ||
return " " + key + (val.value.typeDefinition || | ||
"(...args: any): void"); | ||
return ` ${key}${val.value.typeDefinition || | ||
`(...args: any): void`}`; | ||
})) | ||
.concat([" }", "}"]) | ||
.concat([` }`, `}`]) | ||
.join("\n"); | ||
}; | ||
Typegen.prototype.printDynamicOutputPropertyDefinitions = function () { | ||
var dynamicOutputProperties = this.extensions.dynamicFields.dynamicOutputProperties; | ||
} | ||
printDynamicOutputPropertyDefinitions() { | ||
const { dynamicOutputProperties } = this.extensions.dynamicFields; | ||
// If there is nothing custom... exit | ||
@@ -174,33 +174,32 @@ if (!Object.keys(dynamicOutputProperties).length) { | ||
return [ | ||
"declare global {", | ||
" interface NexusGenCustomOutputProperties<TypeName extends string> {", | ||
`declare global {`, | ||
` interface NexusGenCustomOutputProperties<TypeName extends string> {`, | ||
] | ||
.concat(utils_1.mapObj(dynamicOutputProperties, function (val, key) { | ||
return " " + key + (val.value.typeDefinition || ": any"); | ||
.concat(utils_1.mapObj(dynamicOutputProperties, (val, key) => { | ||
return ` ${key}${val.value.typeDefinition || `: any`}`; | ||
})) | ||
.concat([" }", "}"]) | ||
.concat([` }`, `}`]) | ||
.join("\n"); | ||
}; | ||
Typegen.prototype.printInheritedFieldMap = function () { | ||
} | ||
printInheritedFieldMap() { | ||
// TODO: | ||
return "export interface NexusGenInheritedFields {}"; | ||
}; | ||
Typegen.prototype.printContext = function () { | ||
} | ||
printContext() { | ||
return this.typegenInfo.contextType || "{}"; | ||
}; | ||
Typegen.prototype.buildResolveSourceTypeMap = function () { | ||
var _this = this; | ||
var sourceMap = {}; | ||
var abstractTypes = []; | ||
} | ||
buildResolveSourceTypeMap() { | ||
const sourceMap = {}; | ||
const abstractTypes = []; | ||
abstractTypes | ||
.concat(this.groupedTypes.union) | ||
.concat(this.groupedTypes.interface) | ||
.forEach(function (type) { | ||
.forEach((type) => { | ||
if (graphql_1.isInterfaceType(type)) { | ||
var possibleNames = _this.schema | ||
const possibleNames = this.schema | ||
.getPossibleTypes(type) | ||
.map(function (t) { return t.name; }); | ||
.map((t) => t.name); | ||
if (possibleNames.length > 0) { | ||
sourceMap[type.name] = possibleNames | ||
.map(function (val) { return "NexusGenRootTypes['" + val + "']"; }) | ||
.map((val) => `NexusGenRootTypes['${val}']`) | ||
.join(" | "); | ||
@@ -212,3 +211,3 @@ } | ||
.getTypes() | ||
.map(function (t) { return "NexusGenRootTypes['" + t.name + "']"; }) | ||
.map((t) => `NexusGenRootTypes['${t.name}']`) | ||
.join(" | "); | ||
@@ -218,21 +217,20 @@ } | ||
return sourceMap; | ||
}; | ||
Typegen.prototype.printAbstractResolveReturnTypeMap = function () { | ||
} | ||
printAbstractResolveReturnTypeMap() { | ||
return this.printTypeInterface("NexusGenAbstractResolveReturnTypes", this.buildResolveReturnTypesMap()); | ||
}; | ||
Typegen.prototype.buildResolveReturnTypesMap = function () { | ||
var _this = this; | ||
var sourceMap = {}; | ||
var abstractTypes = []; | ||
} | ||
buildResolveReturnTypesMap() { | ||
const sourceMap = {}; | ||
const abstractTypes = []; | ||
abstractTypes | ||
.concat(this.groupedTypes.union) | ||
.concat(this.groupedTypes.interface) | ||
.forEach(function (type) { | ||
.forEach((type) => { | ||
if (graphql_1.isInterfaceType(type)) { | ||
var possibleNames = _this.schema | ||
const possibleNames = this.schema | ||
.getPossibleTypes(type) | ||
.map(function (t) { return t.name; }); | ||
.map((t) => t.name); | ||
if (possibleNames.length > 0) { | ||
sourceMap[type.name] = possibleNames | ||
.map(function (val) { return JSON.stringify(val); }) | ||
.map((val) => JSON.stringify(val)) | ||
.join(" | "); | ||
@@ -244,3 +242,3 @@ } | ||
.getTypes() | ||
.map(function (t) { return JSON.stringify(t.name); }) | ||
.map((t) => JSON.stringify(t.name)) | ||
.join(" | "); | ||
@@ -250,18 +248,17 @@ } | ||
return sourceMap; | ||
}; | ||
Typegen.prototype.printTypeNames = function (name, exportName) { | ||
var obj = this.groupedTypes[name]; | ||
var typeDef = obj.length === 0 | ||
} | ||
printTypeNames(name, exportName) { | ||
const obj = this.groupedTypes[name]; | ||
const typeDef = obj.length === 0 | ||
? "never" | ||
: obj | ||
.map(function (o) { return JSON.stringify(o.name); }) | ||
.map((o) => JSON.stringify(o.name)) | ||
.sort() | ||
.join(" | "); | ||
return "export type " + exportName + " = " + typeDef + ";"; | ||
}; | ||
Typegen.prototype.buildEnumTypeMap = function () { | ||
var _this = this; | ||
var enumMap = {}; | ||
this.groupedTypes.enum.forEach(function (e) { | ||
var backingType = _this.resolveBackingType(e.name); | ||
return `export type ${exportName} = ${typeDef};`; | ||
} | ||
buildEnumTypeMap() { | ||
const enumMap = {}; | ||
this.groupedTypes.enum.forEach((e) => { | ||
const backingType = this.resolveBackingType(e.name); | ||
if (backingType) { | ||
@@ -271,3 +268,3 @@ enumMap[e.name] = backingType; | ||
else { | ||
var values = e.getValues().map(function (val) { return JSON.stringify(val.value); }); | ||
const values = e.getValues().map((val) => JSON.stringify(val.value)); | ||
enumMap[e.name] = values.join(" | "); | ||
@@ -277,24 +274,22 @@ } | ||
return enumMap; | ||
}; | ||
Typegen.prototype.buildInputTypeMap = function () { | ||
var _this = this; | ||
var inputObjMap = {}; | ||
this.groupedTypes.input.forEach(function (input) { | ||
utils_1.eachObj(input.getFields(), function (field) { | ||
} | ||
buildInputTypeMap() { | ||
const inputObjMap = {}; | ||
this.groupedTypes.input.forEach((input) => { | ||
utils_1.eachObj(input.getFields(), (field) => { | ||
inputObjMap[input.name] = inputObjMap[input.name] || {}; | ||
inputObjMap[input.name][field.name] = _this.normalizeArg(field); | ||
inputObjMap[input.name][field.name] = this.normalizeArg(field); | ||
}); | ||
}); | ||
return inputObjMap; | ||
}; | ||
Typegen.prototype.printInputTypeMap = function () { | ||
} | ||
printInputTypeMap() { | ||
return this.printTypeFieldInterface("NexusGenInputs", this.buildInputTypeMap(), "input type"); | ||
}; | ||
Typegen.prototype.printEnumTypeMap = function () { | ||
} | ||
printEnumTypeMap() { | ||
return this.printTypeInterface("NexusGenEnums", this.buildEnumTypeMap()); | ||
}; | ||
Typegen.prototype.buildRootTypeMap = function () { | ||
var _this = this; | ||
var rootTypeMap = {}; | ||
var hasFields = []; | ||
} | ||
buildRootTypeMap() { | ||
const rootTypeMap = {}; | ||
const hasFields = []; | ||
hasFields | ||
@@ -305,4 +300,4 @@ .concat(this.groupedTypes.object) | ||
.concat(this.groupedTypes.union) | ||
.forEach(function (type) { | ||
var rootTyping = _this.resolveBackingType(type.name); | ||
.forEach((type) => { | ||
const rootTyping = this.resolveBackingType(type.name); | ||
if (rootTyping) { | ||
@@ -324,9 +319,9 @@ rootTypeMap[type.name] = rootTyping; | ||
.getTypes() | ||
.map(function (t) { return "NexusGenRootTypes['" + t.name + "']"; }) | ||
.map((t) => `NexusGenRootTypes['${t.name}']`) | ||
.join(" | "); | ||
} | ||
else if (graphql_1.isInterfaceType(type)) { | ||
var possibleRoots = _this.schema | ||
const possibleRoots = this.schema | ||
.getPossibleTypes(type) | ||
.map(function (t) { return "NexusGenRootTypes['" + t.name + "']"; }); | ||
.map((t) => `NexusGenRootTypes['${t.name}']`); | ||
if (possibleRoots.length > 0) { | ||
@@ -343,9 +338,9 @@ rootTypeMap[type.name] = possibleRoots.join(" | "); | ||
else { | ||
utils_1.eachObj(type.getFields(), function (field) { | ||
var obj = (rootTypeMap[type.name] = rootTypeMap[type.name] || {}); | ||
if (!_this.hasResolver(field, type)) { | ||
utils_1.eachObj(type.getFields(), (field) => { | ||
const obj = (rootTypeMap[type.name] = rootTypeMap[type.name] || {}); | ||
if (!this.hasResolver(field, type)) { | ||
if (typeof obj !== "string") { | ||
obj[field.name] = [ | ||
_this.argSeparator(field.type), | ||
_this.printOutputType(field.type), | ||
this.argSeparator(field.type), | ||
this.printOutputType(field.type), | ||
]; | ||
@@ -358,5 +353,5 @@ } | ||
return rootTypeMap; | ||
}; | ||
Typegen.prototype.resolveBackingType = function (typeName) { | ||
var rootTyping = this.extensions.rootTypings[typeName]; | ||
} | ||
resolveBackingType(typeName) { | ||
const rootTyping = this.extensions.rootTypings[typeName]; | ||
if (rootTyping) { | ||
@@ -366,20 +361,20 @@ return typeof rootTyping === "string" ? rootTyping : rootTyping.name; | ||
return this.typegenInfo.backingTypeMap[typeName]; | ||
}; | ||
Typegen.prototype.buildAllTypesMap = function () { | ||
var typeMap = {}; | ||
var toCheck = []; | ||
} | ||
buildAllTypesMap() { | ||
const typeMap = {}; | ||
const toCheck = []; | ||
toCheck | ||
.concat(this.groupedTypes.input) | ||
.concat(this.groupedTypes.enum) | ||
.forEach(function (type) { | ||
.forEach((type) => { | ||
if (graphql_1.isInputObjectType(type)) { | ||
typeMap[type.name] = "NexusGenInputs['" + type.name + "']"; | ||
typeMap[type.name] = `NexusGenInputs['${type.name}']`; | ||
} | ||
else if (graphql_1.isEnumType(type)) { | ||
typeMap[type.name] = "NexusGenEnums['" + type.name + "']"; | ||
typeMap[type.name] = `NexusGenEnums['${type.name}']`; | ||
} | ||
}); | ||
return typeMap; | ||
}; | ||
Typegen.prototype.hasResolver = function (field, _type // Used in tests | ||
} | ||
hasResolver(field, _type // Used in tests | ||
) { | ||
@@ -392,28 +387,27 @@ if (field.resolve) { | ||
return false; | ||
}; | ||
Typegen.prototype.printRootTypeMap = function () { | ||
} | ||
printRootTypeMap() { | ||
return this.printRootTypeFieldInterface("NexusGenRootTypes", this.buildRootTypeMap()); | ||
}; | ||
Typegen.prototype.printAllTypesMap = function () { | ||
var typeMapping = this.buildAllTypesMap(); | ||
return ["export interface NexusGenAllTypes extends NexusGenRootTypes {"] | ||
.concat(utils_1.mapObj(typeMapping, function (val, key) { | ||
return " " + key + ": " + val + ";"; | ||
} | ||
printAllTypesMap() { | ||
const typeMapping = this.buildAllTypesMap(); | ||
return [`export interface NexusGenAllTypes extends NexusGenRootTypes {`] | ||
.concat(utils_1.mapObj(typeMapping, (val, key) => { | ||
return ` ${key}: ${val};`; | ||
})) | ||
.concat("}") | ||
.join("\n"); | ||
}; | ||
Typegen.prototype.buildArgTypeMap = function () { | ||
var _this = this; | ||
var argTypeMap = {}; | ||
var hasFields = []; | ||
} | ||
buildArgTypeMap() { | ||
const argTypeMap = {}; | ||
const hasFields = []; | ||
hasFields | ||
.concat(this.groupedTypes.object) | ||
.concat(this.groupedTypes.interface) | ||
.forEach(function (type) { | ||
utils_1.eachObj(type.getFields(), function (field) { | ||
.forEach((type) => { | ||
utils_1.eachObj(type.getFields(), (field) => { | ||
if (field.args.length > 0) { | ||
argTypeMap[type.name] = argTypeMap[type.name] || {}; | ||
argTypeMap[type.name][field.name] = field.args.reduce(function (obj, arg) { | ||
obj[arg.name] = _this.normalizeArg(arg); | ||
argTypeMap[type.name][field.name] = field.args.reduce((obj, arg) => { | ||
obj[arg.name] = this.normalizeArg(arg); | ||
return obj; | ||
@@ -425,19 +419,18 @@ }, {}); | ||
return argTypeMap; | ||
}; | ||
Typegen.prototype.printArgTypeMap = function () { | ||
} | ||
printArgTypeMap() { | ||
return this.printArgTypeFieldInterface(this.buildArgTypeMap()); | ||
}; | ||
Typegen.prototype.buildReturnTypeMap = function () { | ||
var _this = this; | ||
var returnTypeMap = {}; | ||
var hasFields = []; | ||
} | ||
buildReturnTypeMap() { | ||
const returnTypeMap = {}; | ||
const hasFields = []; | ||
hasFields | ||
.concat(this.groupedTypes.object) | ||
.concat(this.groupedTypes.interface) | ||
.forEach(function (type) { | ||
utils_1.eachObj(type.getFields(), function (field) { | ||
.forEach((type) => { | ||
utils_1.eachObj(type.getFields(), (field) => { | ||
returnTypeMap[type.name] = returnTypeMap[type.name] || {}; | ||
returnTypeMap[type.name][field.name] = [ | ||
":", | ||
_this.printOutputType(field.type), | ||
this.printOutputType(field.type), | ||
]; | ||
@@ -447,12 +440,12 @@ }); | ||
return returnTypeMap; | ||
}; | ||
Typegen.prototype.printOutputType = function (type) { | ||
var returnType = this.typeToArr(type); | ||
} | ||
printOutputType(type) { | ||
const returnType = this.typeToArr(type); | ||
function combine(item) { | ||
if (item.length === 1) { | ||
if (Array.isArray(item[0])) { | ||
var toPrint = combine(item[0]); | ||
const toPrint = combine(item[0]); | ||
return toPrint.indexOf("null") === -1 | ||
? toPrint + "[]" | ||
: "Array<" + toPrint + ">"; | ||
? `${toPrint}[]` | ||
: `Array<${toPrint}>`; | ||
} | ||
@@ -462,13 +455,13 @@ return item[0]; | ||
if (Array.isArray(item[1])) { | ||
var toPrint = combine(item[1]); | ||
const toPrint = combine(item[1]); | ||
return toPrint.indexOf("null") === -1 | ||
? toPrint + "[] | null" | ||
: "Array<" + toPrint + "> | null"; | ||
? `${toPrint}[] | null` | ||
: `Array<${toPrint}> | null`; | ||
} | ||
return item[1] + " | null"; | ||
return `${item[1]} | null`; | ||
} | ||
return combine(returnType) + "; // " + type; | ||
}; | ||
Typegen.prototype.typeToArr = function (type) { | ||
var typing = []; | ||
return `${combine(returnType)}; // ${type}`; | ||
} | ||
typeToArr(type) { | ||
const typing = []; | ||
if (graphql_1.isNonNullType(type)) { | ||
@@ -487,3 +480,3 @@ type = type.ofType; | ||
else if (graphql_1.isEnumType(type)) { | ||
typing.push("NexusGenEnums['" + type.name + "']"); | ||
typing.push(`NexusGenEnums['${type.name}']`); | ||
} | ||
@@ -493,13 +486,13 @@ else if (graphql_1.isObjectType(type) || | ||
graphql_1.isUnionType(type)) { | ||
typing.push("NexusGenRootTypes['" + type.name + "']"); | ||
typing.push(`NexusGenRootTypes['${type.name}']`); | ||
} | ||
return typing; | ||
}; | ||
Typegen.prototype.printReturnTypeMap = function () { | ||
} | ||
printReturnTypeMap() { | ||
return this.printTypeFieldInterface("NexusGenFieldTypes", this.buildReturnTypeMap(), "field return type"); | ||
}; | ||
Typegen.prototype.normalizeArg = function (arg) { | ||
} | ||
normalizeArg(arg) { | ||
return [this.argSeparator(arg.type), this.argTypeRepresentation(arg.type)]; | ||
}; | ||
Typegen.prototype.argSeparator = function (type) { | ||
} | ||
argSeparator(type) { | ||
if (graphql_1.isNonNullType(type)) { | ||
@@ -509,12 +502,12 @@ return ":"; | ||
return "?:"; | ||
}; | ||
Typegen.prototype.argTypeRepresentation = function (arg) { | ||
var argType = this.argTypeArr(arg); | ||
} | ||
argTypeRepresentation(arg) { | ||
const argType = this.argTypeArr(arg); | ||
function combine(item) { | ||
if (item.length === 1) { | ||
if (Array.isArray(item[0])) { | ||
var toPrint = combine(item[0]); | ||
const toPrint = combine(item[0]); | ||
return toPrint.indexOf("null") === -1 | ||
? toPrint + "[]" | ||
: "Array<" + toPrint + ">"; | ||
? `${toPrint}[]` | ||
: `Array<${toPrint}>`; | ||
} | ||
@@ -524,13 +517,13 @@ return item[0]; | ||
if (Array.isArray(item[1])) { | ||
var toPrint = combine(item[1]); | ||
const toPrint = combine(item[1]); | ||
return toPrint.indexOf("null") === -1 | ||
? toPrint + "[] | null" | ||
: "Array<" + toPrint + "> | null"; | ||
? `${toPrint}[] | null` | ||
: `Array<${toPrint}> | null`; | ||
} | ||
return item[1] + " | null"; | ||
return `${item[1]} | null`; | ||
} | ||
return combine(argType) + "; // " + arg; | ||
}; | ||
Typegen.prototype.argTypeArr = function (arg) { | ||
var typing = []; | ||
return `${combine(argType)}; // ${arg}`; | ||
} | ||
argTypeArr(arg) { | ||
const typing = []; | ||
if (graphql_1.isNonNullType(arg)) { | ||
@@ -549,42 +542,40 @@ arg = arg.ofType; | ||
else if (graphql_1.isEnumType(arg)) { | ||
typing.push("NexusGenEnums['" + arg.name + "']"); | ||
typing.push(`NexusGenEnums['${arg.name}']`); | ||
} | ||
else if (graphql_1.isInputObjectType(arg)) { | ||
typing.push("NexusGenInputs['" + arg.name + "']"); | ||
typing.push(`NexusGenInputs['${arg.name}']`); | ||
} | ||
return typing; | ||
}; | ||
Typegen.prototype.printTypeInterface = function (interfaceName, typeMapping) { | ||
return ["export interface " + interfaceName + " {"] | ||
.concat(utils_1.mapObj(typeMapping, function (val, key) { return " " + key + ": " + val; })) | ||
} | ||
printTypeInterface(interfaceName, typeMapping) { | ||
return [`export interface ${interfaceName} {`] | ||
.concat(utils_1.mapObj(typeMapping, (val, key) => ` ${key}: ${val}`)) | ||
.concat("}") | ||
.join("\n"); | ||
}; | ||
Typegen.prototype.printRootTypeFieldInterface = function (interfaceName, typeMapping) { | ||
var _this = this; | ||
return ["export interface " + interfaceName + " {"] | ||
.concat(utils_1.mapObj(typeMapping, function (val, key) { | ||
} | ||
printRootTypeFieldInterface(interfaceName, typeMapping) { | ||
return [`export interface ${interfaceName} {`] | ||
.concat(utils_1.mapObj(typeMapping, (val, key) => { | ||
if (typeof val === "string") { | ||
return " " + key + ": " + val + ";"; | ||
return ` ${key}: ${val};`; | ||
} | ||
if (Object.keys(val).length === 0) { | ||
return " " + key + ": {};"; | ||
return ` ${key}: {};`; | ||
} | ||
return _this.printObj(" ", "root type")(val, key); | ||
return this.printObj(" ", "root type")(val, key); | ||
})) | ||
.concat("}") | ||
.join("\n"); | ||
}; | ||
Typegen.prototype.printTypeFieldInterface = function (interfaceName, typeMapping, source) { | ||
return ["export interface " + interfaceName + " {"] | ||
} | ||
printTypeFieldInterface(interfaceName, typeMapping, source) { | ||
return [`export interface ${interfaceName} {`] | ||
.concat(utils_1.mapObj(typeMapping, this.printObj(" ", source))) | ||
.concat("}") | ||
.join("\n"); | ||
}; | ||
Typegen.prototype.printArgTypeFieldInterface = function (typeMapping) { | ||
var _this = this; | ||
return ["export interface NexusGenArgTypes {"] | ||
.concat(utils_1.mapObj(typeMapping, function (val, key) { | ||
return [" " + key + ": {"] | ||
.concat(utils_1.mapObj(val, _this.printObj(" ", "args"))) | ||
} | ||
printArgTypeFieldInterface(typeMapping) { | ||
return [`export interface NexusGenArgTypes {`] | ||
.concat(utils_1.mapObj(typeMapping, (val, key) => { | ||
return [` ${key}: {`] | ||
.concat(utils_1.mapObj(val, this.printObj(" ", "args"))) | ||
.concat(" }") | ||
@@ -595,8 +586,8 @@ .join("\n"); | ||
.join("\n"); | ||
}; | ||
Typegen.prototype.printScalar = function (type) { | ||
} | ||
printScalar(type) { | ||
if (graphql_1.isSpecifiedScalarType(type)) { | ||
return SpecifiedScalars[type.name]; | ||
} | ||
var backingType = this.typegenInfo.backingTypeMap[type.name]; | ||
const backingType = this.typegenInfo.backingTypeMap[type.name]; | ||
if (typeof backingType === "string") { | ||
@@ -608,7 +599,9 @@ return backingType; | ||
} | ||
}; | ||
return Typegen; | ||
}()); | ||
} | ||
} | ||
exports.Typegen = Typegen; | ||
var GLOBAL_DECLARATION = "\ndeclare global {\n interface NexusGen extends NexusGenTypes {}\n}"; | ||
const GLOBAL_DECLARATION = ` | ||
declare global { | ||
interface NexusGen extends NexusGenTypes {} | ||
}`; | ||
//# sourceMappingURL=typegen.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
var graphql_1 = require("graphql"); | ||
var path_1 = tslib_1.__importDefault(require("path")); | ||
var lang_1 = require("./lang"); | ||
var utils_1 = require("./utils"); | ||
const tslib_1 = require("tslib"); | ||
const graphql_1 = require("graphql"); | ||
const path_1 = tslib_1.__importDefault(require("path")); | ||
const lang_1 = require("./lang"); | ||
const utils_1 = require("./utils"); | ||
/** | ||
@@ -30,168 +30,153 @@ * Any common types / constants that would otherwise be circular-imported | ||
function typegenAutoConfig(options) { | ||
var _this = this; | ||
return function (schema, outputPath) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var headers, contextType, _a, skipTypes, _backingTypeMap, debug, typeMap, typesToIgnore, typesToIgnoreRegex, allImportsMap, importsMap, backingTypeMap, forceImports, typeSources, builtinScalars, imports, typegenInfo; | ||
var _this = this; | ||
return tslib_1.__generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
headers = options.headers, contextType = options.contextType, _a = options.skipTypes, skipTypes = _a === void 0 ? ["Query", "Mutation", "Subscription"] : _a, _backingTypeMap = options.backingTypeMap, debug = options.debug; | ||
typeMap = schema.getTypeMap(); | ||
typesToIgnore = new Set(); | ||
typesToIgnoreRegex = []; | ||
allImportsMap = {}; | ||
importsMap = {}; | ||
backingTypeMap = tslib_1.__assign({}, exports.SCALAR_TYPES, _backingTypeMap); | ||
forceImports = new Set(utils_1.objValues(backingTypeMap) | ||
.concat(contextType || "") | ||
.map(function (t) { | ||
var match = t.match(/^(\w+)\./); | ||
return match ? match[1] : null; | ||
}) | ||
.filter(function (f) { return f; })); | ||
skipTypes.forEach(function (skip) { | ||
if (typeof skip === "string") { | ||
typesToIgnore.add(skip); | ||
return (schema, outputPath) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const { headers, contextType, skipTypes = ["Query", "Mutation", "Subscription"], backingTypeMap: _backingTypeMap, debug, } = options; | ||
const typeMap = schema.getTypeMap(); | ||
const typesToIgnore = new Set(); | ||
const typesToIgnoreRegex = []; | ||
const allImportsMap = {}; | ||
const importsMap = {}; | ||
const backingTypeMap = Object.assign(Object.assign({}, exports.SCALAR_TYPES), _backingTypeMap); | ||
const forceImports = new Set(utils_1.objValues(backingTypeMap) | ||
.concat(contextType || "") | ||
.map((t) => { | ||
const match = t.match(/^(\w+)\./); | ||
return match ? match[1] : null; | ||
}) | ||
.filter((f) => f)); | ||
skipTypes.forEach((skip) => { | ||
if (typeof skip === "string") { | ||
typesToIgnore.add(skip); | ||
} | ||
else if (skip instanceof RegExp) { | ||
typesToIgnoreRegex.push(skip); | ||
} | ||
else { | ||
throw new Error("Invalid type for options.skipTypes, expected string or RegExp"); | ||
} | ||
}); | ||
const typeSources = yield Promise.all(options.sources.map((source) => tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
// Keeping all of this in here so if we don't have any sources | ||
// e.g. in the Playground, it doesn't break things. | ||
// Yeah, this doesn't exist in Node 6, but since this is a new | ||
// lib and Node 6 is close to EOL so if you really need it, open a PR :) | ||
const fs = require("fs"); | ||
const util = require("util"); | ||
const readFile = util.promisify(fs.readFile); | ||
const { source: pathOrModule, glob = true, onlyTypes, alias, typeMatch, } = source; | ||
if (path_1.default.isAbsolute(pathOrModule) && | ||
path_1.default.extname(pathOrModule) !== ".ts") { | ||
return console.warn(`GraphQL Nexus Typegen: Expected module ${pathOrModule} to be an absolute path to a TypeScript module, skipping.`); | ||
} | ||
let resolvedPath; | ||
let fileContents; | ||
try { | ||
resolvedPath = require.resolve(pathOrModule, { | ||
paths: [process.cwd()], | ||
}); | ||
if (path_1.default.extname(resolvedPath) !== ".ts") { | ||
resolvedPath = findTypingForFile(resolvedPath, pathOrModule); | ||
} | ||
fileContents = yield readFile(resolvedPath, "utf-8"); | ||
} | ||
catch (e) { | ||
if (e instanceof Error && | ||
e.message.indexOf("Cannot find module") !== -1) { | ||
console.error(`GraphQL Nexus: Unable to find file or module ${pathOrModule}, skipping`); | ||
} | ||
else { | ||
console.error(e.message); | ||
} | ||
return null; | ||
} | ||
const importPath = (path_1.default.isAbsolute(pathOrModule) | ||
? utils_1.relativePathTo(resolvedPath, outputPath) | ||
: pathOrModule).replace(/(\.d)?\.ts/, ""); | ||
if (allImportsMap[alias] && allImportsMap[alias] !== importPath) { | ||
return console.warn(`GraphQL Nexus Typegen: Cannot have multiple type sources ${importsMap[alias]} and ${pathOrModule} with the same alias ${alias}, skipping`); | ||
} | ||
allImportsMap[alias] = importPath; | ||
if (forceImports.has(alias)) { | ||
importsMap[alias] = [importPath, glob]; | ||
forceImports.delete(alias); | ||
} | ||
return { | ||
alias, | ||
glob, | ||
importPath, | ||
fileContents, | ||
onlyTypes, | ||
typeMatch: typeMatch || defaultTypeMatcher, | ||
}; | ||
}))); | ||
const builtinScalars = new Set(Object.keys(exports.SCALAR_TYPES)); | ||
Object.keys(typeMap).forEach((typeName) => { | ||
if (typeName.indexOf("__") === 0) { | ||
return; | ||
} | ||
if (typesToIgnore.has(typeName)) { | ||
return; | ||
} | ||
if (typesToIgnoreRegex.some((r) => r.test(typeName))) { | ||
return; | ||
} | ||
if (backingTypeMap[typeName]) { | ||
return; | ||
} | ||
if (builtinScalars.has(typeName)) { | ||
return; | ||
} | ||
const type = schema.getType(typeName); | ||
// For now we'll say that if it's output type it can be backed | ||
if (graphql_1.isOutputType(type)) { | ||
for (let i = 0; i < typeSources.length; i++) { | ||
const typeSource = typeSources[i]; | ||
if (!typeSource) { | ||
continue; | ||
} | ||
// If we've specified an array of "onlyTypes" to match ensure the | ||
// `typeName` falls within that list. | ||
if (typeSource.onlyTypes) { | ||
if (!typeSource.onlyTypes.some((t) => { | ||
return t instanceof RegExp ? t.test(typeName) : t === typeName; | ||
})) { | ||
continue; | ||
} | ||
else if (skip instanceof RegExp) { | ||
typesToIgnoreRegex.push(skip); | ||
} | ||
const { fileContents, importPath, glob, alias, typeMatch, } = typeSource; | ||
const typeRegex = typeMatch(type, defaultTypeMatcher(type)[0]); | ||
const matched = firstMatch(fileContents, Array.isArray(typeRegex) ? typeRegex : [typeRegex]); | ||
if (matched) { | ||
if (debug) { | ||
utils_1.log(`Matched type - ${typeName} in "${importPath}" - ${alias}.${matched[1]}`); | ||
} | ||
else { | ||
throw new Error("Invalid type for options.skipTypes, expected string or RegExp"); | ||
importsMap[alias] = [importPath, glob]; | ||
backingTypeMap[typeName] = `${alias}.${matched[1]}`; | ||
} | ||
else { | ||
if (debug) { | ||
utils_1.log(`No match for ${typeName} in "${importPath}" using ${typeRegex}`); | ||
} | ||
}); | ||
return [4 /*yield*/, Promise.all(options.sources.map(function (source) { return tslib_1.__awaiter(_this, void 0, void 0, function () { | ||
var fs, util, readFile, pathOrModule, _a, glob, onlyTypes, alias, typeMatch, resolvedPath, fileContents, e_1, importPath; | ||
return tslib_1.__generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
fs = require("fs"); | ||
util = require("util"); | ||
readFile = util.promisify(fs.readFile); | ||
pathOrModule = source.source, _a = source.glob, glob = _a === void 0 ? true : _a, onlyTypes = source.onlyTypes, alias = source.alias, typeMatch = source.typeMatch; | ||
if (path_1.default.isAbsolute(pathOrModule) && | ||
path_1.default.extname(pathOrModule) !== ".ts") { | ||
return [2 /*return*/, console.warn("GraphQL Nexus Typegen: Expected module " + pathOrModule + " to be an absolute path to a TypeScript module, skipping.")]; | ||
} | ||
_b.label = 1; | ||
case 1: | ||
_b.trys.push([1, 3, , 4]); | ||
resolvedPath = require.resolve(pathOrModule, { | ||
paths: [process.cwd()], | ||
}); | ||
if (path_1.default.extname(resolvedPath) !== ".ts") { | ||
resolvedPath = findTypingForFile(resolvedPath, pathOrModule); | ||
} | ||
return [4 /*yield*/, readFile(resolvedPath, "utf-8")]; | ||
case 2: | ||
fileContents = _b.sent(); | ||
return [3 /*break*/, 4]; | ||
case 3: | ||
e_1 = _b.sent(); | ||
if (e_1 instanceof Error && | ||
e_1.message.indexOf("Cannot find module") !== -1) { | ||
console.error("GraphQL Nexus: Unable to find file or module " + pathOrModule + ", skipping"); | ||
} | ||
else { | ||
console.error(e_1.message); | ||
} | ||
return [2 /*return*/, null]; | ||
case 4: | ||
importPath = (path_1.default.isAbsolute(pathOrModule) | ||
? utils_1.relativePathTo(resolvedPath, outputPath) | ||
: pathOrModule).replace(/(\.d)?\.ts/, ""); | ||
if (allImportsMap[alias] && allImportsMap[alias] !== importPath) { | ||
return [2 /*return*/, console.warn("GraphQL Nexus Typegen: Cannot have multiple type sources " + importsMap[alias] + " and " + pathOrModule + " with the same alias " + alias + ", skipping")]; | ||
} | ||
allImportsMap[alias] = importPath; | ||
if (forceImports.has(alias)) { | ||
importsMap[alias] = [importPath, glob]; | ||
forceImports.delete(alias); | ||
} | ||
return [2 /*return*/, { | ||
alias: alias, | ||
glob: glob, | ||
importPath: importPath, | ||
fileContents: fileContents, | ||
onlyTypes: onlyTypes, | ||
typeMatch: typeMatch || defaultTypeMatcher, | ||
}]; | ||
} | ||
}); | ||
}); }))]; | ||
case 1: | ||
typeSources = _b.sent(); | ||
builtinScalars = new Set(Object.keys(exports.SCALAR_TYPES)); | ||
Object.keys(typeMap).forEach(function (typeName) { | ||
if (typeName.indexOf("__") === 0) { | ||
return; | ||
} | ||
if (typesToIgnore.has(typeName)) { | ||
return; | ||
} | ||
if (typesToIgnoreRegex.some(function (r) { return r.test(typeName); })) { | ||
return; | ||
} | ||
if (backingTypeMap[typeName]) { | ||
return; | ||
} | ||
if (builtinScalars.has(typeName)) { | ||
return; | ||
} | ||
var type = schema.getType(typeName); | ||
// For now we'll say that if it's output type it can be backed | ||
if (graphql_1.isOutputType(type)) { | ||
for (var i = 0; i < typeSources.length; i++) { | ||
var typeSource = typeSources[i]; | ||
if (!typeSource) { | ||
continue; | ||
} | ||
// If we've specified an array of "onlyTypes" to match ensure the | ||
// `typeName` falls within that list. | ||
if (typeSource.onlyTypes) { | ||
if (!typeSource.onlyTypes.some(function (t) { | ||
return t instanceof RegExp ? t.test(typeName) : t === typeName; | ||
})) { | ||
continue; | ||
} | ||
} | ||
var fileContents = typeSource.fileContents, importPath = typeSource.importPath, glob = typeSource.glob, alias = typeSource.alias, typeMatch = typeSource.typeMatch; | ||
var typeRegex = typeMatch(type, defaultTypeMatcher(type)[0]); | ||
var matched = firstMatch(fileContents, Array.isArray(typeRegex) ? typeRegex : [typeRegex]); | ||
if (matched) { | ||
if (debug) { | ||
utils_1.log("Matched type - " + typeName + " in \"" + importPath + "\" - " + alias + "." + matched[1]); | ||
} | ||
importsMap[alias] = [importPath, glob]; | ||
backingTypeMap[typeName] = alias + "." + matched[1]; | ||
} | ||
else { | ||
if (debug) { | ||
utils_1.log("No match for " + typeName + " in \"" + importPath + "\" using " + typeRegex); | ||
} | ||
} | ||
} | ||
} | ||
}); | ||
if (forceImports.size > 0) { | ||
console.error("Missing required typegen import: " + Array.from(forceImports)); | ||
} | ||
imports = []; | ||
Object.keys(importsMap) | ||
.sort() | ||
.forEach(function (alias) { | ||
var _a = importsMap[alias], importPath = _a[0], glob = _a[1]; | ||
var safeImportPath = importPath.replace(/\\+/g, "/"); | ||
imports.push("import " + (glob ? "* as " : "") + alias + " from \"" + safeImportPath + "\""); | ||
}); | ||
typegenInfo = { | ||
headers: headers || [lang_1.TYPEGEN_HEADER], | ||
backingTypeMap: backingTypeMap, | ||
imports: imports, | ||
contextType: contextType, | ||
}; | ||
return [2 /*return*/, typegenInfo]; | ||
} | ||
} | ||
}); | ||
}); }; | ||
if (forceImports.size > 0) { | ||
console.error(`Missing required typegen import: ${Array.from(forceImports)}`); | ||
} | ||
const imports = []; | ||
Object.keys(importsMap) | ||
.sort() | ||
.forEach((alias) => { | ||
const [importPath, glob] = importsMap[alias]; | ||
const safeImportPath = importPath.replace(/\\+/g, "/"); | ||
imports.push(`import ${glob ? "* as " : ""}${alias} from "${safeImportPath}"`); | ||
}); | ||
const typegenInfo = { | ||
headers: headers || [lang_1.TYPEGEN_HEADER], | ||
backingTypeMap, | ||
imports, | ||
contextType, | ||
}; | ||
return typegenInfo; | ||
}); | ||
} | ||
@@ -202,3 +187,3 @@ exports.typegenAutoConfig = typegenAutoConfig; | ||
try { | ||
var typeDefPath = absolutePath.replace(path_1.default.extname(absolutePath), ".d.ts"); | ||
const typeDefPath = absolutePath.replace(path_1.default.extname(absolutePath), ".d.ts"); | ||
require.resolve(typeDefPath); | ||
@@ -212,8 +197,8 @@ return typeDefPath; | ||
// and "typings" is set in the package.json | ||
throw new Error("Unable to find typings associated with " + pathOrModule + ", skipping"); | ||
throw new Error(`Unable to find typings associated with ${pathOrModule}, skipping`); | ||
} | ||
var firstMatch = function (fileContents, typeRegex) { | ||
for (var i = 0; i < typeRegex.length; i++) { | ||
var regex = typeRegex[i]; | ||
var match = regex.exec(fileContents); | ||
const firstMatch = (fileContents, typeRegex) => { | ||
for (let i = 0; i < typeRegex.length; i++) { | ||
const regex = typeRegex[i]; | ||
const match = regex.exec(fileContents); | ||
if (match) { | ||
@@ -225,7 +210,7 @@ return match; | ||
}; | ||
var defaultTypeMatcher = function (type) { | ||
const defaultTypeMatcher = (type) => { | ||
return [ | ||
new RegExp("(?:interface|type|class|enum)\\s+(" + type.name + ")\\W", "g"), | ||
new RegExp(`(?:interface|type|class|enum)\\s+(${type.name})\\W`, "g"), | ||
]; | ||
}; | ||
//# sourceMappingURL=typegenAutoConfig.js.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
var path_1 = tslib_1.__importDefault(require("path")); | ||
const tslib_1 = require("tslib"); | ||
const path_1 = tslib_1.__importDefault(require("path")); | ||
function typegenFormatPrettier(prettierConfig) { | ||
return function formatTypegen(content, type) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var prettier, fs, util, readFile, _a, _b, e_1; | ||
return tslib_1.__generator(this, function (_c) { | ||
switch (_c.label) { | ||
case 0: | ||
_c.trys.push([0, 3, , 4]); | ||
prettier = require("prettier"); | ||
if (!(typeof prettierConfig === "string")) return [3 /*break*/, 2]; | ||
if (!path_1.default.isAbsolute(prettierConfig)) { | ||
throw new Error("Expected prettierrc path to be absolute, saw " + prettierConfig); | ||
} | ||
fs = require("fs"); | ||
util = require("util"); | ||
readFile = util.promisify(fs.readFile); | ||
_b = (_a = JSON).parse; | ||
return [4 /*yield*/, readFile(prettierConfig, "utf8")]; | ||
case 1: | ||
prettierConfig = _b.apply(_a, [_c.sent()]); | ||
_c.label = 2; | ||
case 2: return [2 /*return*/, prettier.format(content, tslib_1.__assign({}, prettierConfig, { parser: type === "types" ? "typescript" : "graphql" }))]; | ||
case 3: | ||
e_1 = _c.sent(); | ||
console.error(e_1); | ||
return [3 /*break*/, 4]; | ||
case 4: return [2 /*return*/, content]; | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
try { | ||
const prettier = require("prettier"); | ||
if (typeof prettierConfig === "string") { | ||
if (!path_1.default.isAbsolute(prettierConfig)) { | ||
throw new Error(`Expected prettierrc path to be absolute, saw ${prettierConfig}`); | ||
} | ||
const fs = require("fs"); | ||
const util = require("util"); | ||
const readFile = util.promisify(fs.readFile); | ||
prettierConfig = JSON.parse(yield readFile(prettierConfig, "utf8")); | ||
} | ||
}); | ||
return prettier.format(content, Object.assign(Object.assign({}, prettierConfig), { parser: type === "types" ? "typescript" : "graphql" })); | ||
} | ||
catch (e) { | ||
console.error(e); | ||
} | ||
return content; | ||
}); | ||
@@ -35,0 +26,0 @@ }; |
import { GraphQLSchema } from "graphql"; | ||
import { BuilderConfig, TypegenInfo, NexusSchema, NexusSchemaExtensions } from "./builder"; | ||
import { TypegenInfo, InternalBuilderConfig, NexusSchemaExtensions, NexusSchema } from "./builder"; | ||
/** | ||
@@ -9,7 +9,6 @@ * Passed into the SchemaBuilder, this keeps track of any necessary | ||
export declare class TypegenMetadata { | ||
protected config: BuilderConfig; | ||
protected typegenFile: string; | ||
constructor(config: BuilderConfig); | ||
protected config: InternalBuilderConfig; | ||
constructor(config: InternalBuilderConfig); | ||
/** | ||
* Generates the artifacts of the build based on what we | ||
* Generates the artifacts of the buid based on what we | ||
* know about the schema and how it was defined. | ||
@@ -27,4 +26,4 @@ */ | ||
*/ | ||
generateTypesFile(schema: GraphQLSchema, extensions: NexusSchemaExtensions): Promise<string>; | ||
generateTypesFile(schema: GraphQLSchema, extensions: NexusSchemaExtensions, typegenFile: string): Promise<string>; | ||
getTypegenInfo(schema: GraphQLSchema): Promise<TypegenInfo>; | ||
} |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
var graphql_1 = require("graphql"); | ||
var path_1 = tslib_1.__importDefault(require("path")); | ||
var typegen_1 = require("./typegen"); | ||
var utils_1 = require("./utils"); | ||
var lang_1 = require("./lang"); | ||
var typegenAutoConfig_1 = require("./typegenAutoConfig"); | ||
var typegenFormatPrettier_1 = require("./typegenFormatPrettier"); | ||
const tslib_1 = require("tslib"); | ||
const graphql_1 = require("graphql"); | ||
const path_1 = tslib_1.__importDefault(require("path")); | ||
const typegen_1 = require("./typegen"); | ||
const lang_1 = require("./lang"); | ||
const typegenAutoConfig_1 = require("./typegenAutoConfig"); | ||
const typegenFormatPrettier_1 = require("./typegenFormatPrettier"); | ||
/** | ||
@@ -16,45 +15,24 @@ * Passed into the SchemaBuilder, this keeps track of any necessary | ||
*/ | ||
var TypegenMetadata = /** @class */ (function () { | ||
function TypegenMetadata(config) { | ||
class TypegenMetadata { | ||
constructor(config) { | ||
this.config = config; | ||
this.typegenFile = ""; | ||
if (config.outputs !== false && config.shouldGenerateArtifacts !== false) { | ||
if (config.outputs.typegen) { | ||
this.typegenFile = utils_1.assertAbsolutePath(config.outputs.typegen, "outputs.typegen"); | ||
} | ||
} | ||
} | ||
/** | ||
* Generates the artifacts of the build based on what we | ||
* Generates the artifacts of the buid based on what we | ||
* know about the schema and how it was defined. | ||
*/ | ||
TypegenMetadata.prototype.generateArtifacts = function (schema) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var sortedSchema, value; | ||
return tslib_1.__generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
sortedSchema = this.sortSchema(schema); | ||
if (!this.config.outputs) return [3 /*break*/, 5]; | ||
if (!this.config.outputs.schema) return [3 /*break*/, 2]; | ||
return [4 /*yield*/, this.writeFile("schema", this.generateSchemaFile(sortedSchema), this.config.outputs.schema)]; | ||
case 1: | ||
_a.sent(); | ||
_a.label = 2; | ||
case 2: | ||
if (!this.typegenFile) return [3 /*break*/, 5]; | ||
return [4 /*yield*/, this.generateTypesFile(sortedSchema, schema.extensions.nexus)]; | ||
case 3: | ||
value = _a.sent(); | ||
return [4 /*yield*/, this.writeFile("types", value, this.typegenFile)]; | ||
case 4: | ||
_a.sent(); | ||
_a.label = 5; | ||
case 5: return [2 /*return*/]; | ||
} | ||
}); | ||
generateArtifacts(schema) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
const sortedSchema = this.sortSchema(schema); | ||
if (this.config.outputs.schema) { | ||
yield this.writeFile("schema", this.generateSchemaFile(sortedSchema), this.config.outputs.schema); | ||
} | ||
if (this.config.outputs.typegen) { | ||
const value = yield this.generateTypesFile(sortedSchema, schema.extensions.nexus, this.config.outputs.typegen); | ||
yield this.writeFile("types", value, this.config.outputs.typegen); | ||
} | ||
}); | ||
}; | ||
TypegenMetadata.prototype.sortSchema = function (schema) { | ||
var sortedSchema = schema; | ||
} | ||
sortSchema(schema) { | ||
let sortedSchema = schema; | ||
if (typeof graphql_1.lexicographicSortSchema !== "undefined") { | ||
@@ -64,112 +42,91 @@ sortedSchema = graphql_1.lexicographicSortSchema(schema); | ||
return sortedSchema; | ||
}; | ||
TypegenMetadata.prototype.writeFile = function (type, output, filePath) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var fs, util, _a, readFile, writeFile, mkdir, formatTypegen, content, _b, _c, toSave, existing, dirPath, e_1; | ||
return tslib_1.__generator(this, function (_d) { | ||
switch (_d.label) { | ||
case 0: | ||
if (typeof filePath !== "string" || !path_1.default.isAbsolute(filePath)) { | ||
return [2 /*return*/, Promise.reject(new Error("Expected an absolute path to output the GraphQL Nexus " + type + ", saw " + filePath))]; | ||
} | ||
fs = require("fs"); | ||
util = require("util"); | ||
_a = [ | ||
util.promisify(fs.readFile), | ||
util.promisify(fs.writeFile), | ||
util.promisify(fs.mkdir), | ||
], readFile = _a[0], writeFile = _a[1], mkdir = _a[2]; | ||
formatTypegen = null; | ||
if (typeof this.config.formatTypegen === "function") { | ||
formatTypegen = this.config.formatTypegen; | ||
} | ||
else if (this.config.prettierConfig) { | ||
formatTypegen = typegenFormatPrettier_1.typegenFormatPrettier(this.config.prettierConfig); | ||
} | ||
if (!(typeof formatTypegen === "function")) return [3 /*break*/, 2]; | ||
return [4 /*yield*/, formatTypegen(output, type)]; | ||
case 1: | ||
_b = _d.sent(); | ||
return [3 /*break*/, 3]; | ||
case 2: | ||
_b = output; | ||
_d.label = 3; | ||
case 3: | ||
content = _b; | ||
return [4 /*yield*/, Promise.all([ | ||
content, | ||
readFile(filePath, "utf8").catch(function () { return ""; }), | ||
])]; | ||
case 4: | ||
_c = _d.sent(), toSave = _c[0], existing = _c[1]; | ||
if (!(toSave !== existing)) return [3 /*break*/, 9]; | ||
dirPath = path_1.default.dirname(filePath); | ||
_d.label = 5; | ||
case 5: | ||
_d.trys.push([5, 7, , 8]); | ||
return [4 /*yield*/, mkdir(dirPath, { recursive: true })]; | ||
case 6: | ||
_d.sent(); | ||
return [3 /*break*/, 8]; | ||
case 7: | ||
e_1 = _d.sent(); | ||
if (e_1.code !== "EEXIST") { | ||
throw e_1; | ||
} | ||
return [3 /*break*/, 8]; | ||
case 8: return [2 /*return*/, writeFile(filePath, toSave)]; | ||
case 9: return [2 /*return*/]; | ||
} | ||
writeFile(type, output, filePath) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (typeof filePath !== "string" || !path_1.default.isAbsolute(filePath)) { | ||
return Promise.reject(new Error(`Expected an absolute path to output the GraphQL Nexus ${type}, saw ${filePath}`)); | ||
} | ||
const fs = require("fs"); | ||
const util = require("util"); | ||
const [readFile, writeFile, removeFile, mkdir] = [ | ||
util.promisify(fs.readFile), | ||
util.promisify(fs.writeFile), | ||
util.promisify(fs.unlink), | ||
util.promisify(fs.mkdir), | ||
]; | ||
let formatTypegen = null; | ||
if (typeof this.config.formatTypegen === "function") { | ||
formatTypegen = this.config.formatTypegen; | ||
} | ||
else if (this.config.prettierConfig) { | ||
formatTypegen = typegenFormatPrettier_1.typegenFormatPrettier(this.config.prettierConfig); | ||
} | ||
const content = typeof formatTypegen === "function" | ||
? yield formatTypegen(output, type) | ||
: output; | ||
const [toSave, existing] = yield Promise.all([ | ||
content, | ||
readFile(filePath, "utf8").catch(() => ""), | ||
]); | ||
if (toSave !== existing) { | ||
const dirPath = path_1.default.dirname(filePath); | ||
try { | ||
yield mkdir(dirPath, { recursive: true }); | ||
} | ||
}); | ||
catch (e) { | ||
if (e.code !== "EEXIST") { | ||
throw e; | ||
} | ||
} | ||
// VSCode reacts to file changes better if a file is first deleted, | ||
// apparently. See issue motivating this logic here: | ||
// https://github.com/prisma-labs/nexus/issues/247. | ||
try { | ||
yield removeFile(filePath); | ||
} | ||
catch (e) { | ||
if (e.code !== "ENOENT") { | ||
throw e; | ||
} | ||
} | ||
return writeFile(filePath, toSave); | ||
} | ||
}); | ||
}; | ||
} | ||
/** | ||
* Generates the schema, adding any directives as necessary | ||
*/ | ||
TypegenMetadata.prototype.generateSchemaFile = function (schema) { | ||
var printedSchema = graphql_1.printSchema(schema); | ||
generateSchemaFile(schema) { | ||
let printedSchema = graphql_1.printSchema(schema); | ||
return [lang_1.SDL_HEADER, printedSchema].join("\n\n"); | ||
}; | ||
} | ||
/** | ||
* Generates the type definitions | ||
*/ | ||
TypegenMetadata.prototype.generateTypesFile = function (schema, extensions) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
var _a, _b, _c; | ||
return tslib_1.__generator(this, function (_d) { | ||
switch (_d.label) { | ||
case 0: | ||
_a = typegen_1.Typegen.bind; | ||
_b = [void 0, schema]; | ||
_c = [{}]; | ||
return [4 /*yield*/, this.getTypegenInfo(schema)]; | ||
case 1: return [2 /*return*/, new (_a.apply(typegen_1.Typegen, _b.concat([tslib_1.__assign.apply(void 0, _c.concat([(_d.sent()), { typegenFile: this.typegenFile }])), extensions])))().print()]; | ||
} | ||
}); | ||
generateTypesFile(schema, extensions, typegenFile) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
return new typegen_1.Typegen(schema, Object.assign(Object.assign({}, (yield this.getTypegenInfo(schema))), { typegenFile }), extensions).print(); | ||
}); | ||
}; | ||
TypegenMetadata.prototype.getTypegenInfo = function (schema) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function () { | ||
return tslib_1.__generator(this, function (_a) { | ||
if (this.config.typegenConfig) { | ||
if (this.config.typegenAutoConfig) { | ||
console.warn("Only one of typegenConfig and typegenAutoConfig should be specified, ignoring typegenConfig"); | ||
} | ||
return [2 /*return*/, this.config.typegenConfig(schema, this.typegenFile)]; | ||
} | ||
} | ||
getTypegenInfo(schema) { | ||
return tslib_1.__awaiter(this, void 0, void 0, function* () { | ||
if (this.config.typegenConfig) { | ||
if (this.config.typegenAutoConfig) { | ||
return [2 /*return*/, typegenAutoConfig_1.typegenAutoConfig(this.config.typegenAutoConfig)(schema, this.typegenFile)]; | ||
console.warn(`Only one of typegenConfig and typegenAutoConfig should be specified, ignoring typegenConfig`); | ||
} | ||
return [2 /*return*/, { | ||
headers: [lang_1.TYPEGEN_HEADER], | ||
imports: [], | ||
contextType: "any", | ||
backingTypeMap: {}, | ||
}]; | ||
}); | ||
return this.config.typegenConfig(schema, this.config.outputs.typegen || ""); | ||
} | ||
if (this.config.typegenAutoConfig) { | ||
return typegenAutoConfig_1.typegenAutoConfig(this.config.typegenAutoConfig)(schema, this.config.outputs.typegen || ""); | ||
} | ||
return { | ||
headers: [lang_1.TYPEGEN_HEADER], | ||
imports: [], | ||
contextType: "any", | ||
backingTypeMap: {}, | ||
}; | ||
}); | ||
}; | ||
return TypegenMetadata; | ||
}()); | ||
} | ||
} | ||
exports.TypegenMetadata = TypegenMetadata; | ||
//# sourceMappingURL=typegenMetadata.js.map |
@@ -37,12 +37,10 @@ import { GraphQLObjectType, GraphQLInterfaceType, GraphQLSchema, GraphQLInputObjectType, GraphQLUnionType, GraphQLEnumType, GraphQLScalarType, GraphQLNamedType } from "graphql"; | ||
/** | ||
* Index types are just an alias for Records whose keys are of type `string`. | ||
* The name of this type, `Index`, signifies its canonical use-case for data | ||
* indexed by some property, e.g. a list of users indexed by email. | ||
*/ | ||
export declare type Index<T> = Record<string, T>; | ||
/** | ||
* Returns its input. For example: | ||
* Calculate the venn diagram between two iterables based on reference equality | ||
* checks. The returned tripple contains items thusly: | ||
* | ||
* id(1) // -> 1 | ||
* * items only in arg 1 --> first tripple slot | ||
* * items in args 1 & 2 --> second tripple slot | ||
* * items only in arg 2 --> third tripple slot | ||
*/ | ||
export declare const id: <T extends unknown>(x: T) => T; | ||
export declare function venn<T>(xs: Iterable<T>, ys: Iterable<T>): [Set<T>, Set<T>, Set<T>]; | ||
export declare function indentBlock(size: number, block: string): string; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var tslib_1 = require("tslib"); | ||
var graphql_1 = require("graphql"); | ||
var path_1 = tslib_1.__importDefault(require("path")); | ||
var builder_1 = require("./builder"); | ||
const tslib_1 = require("tslib"); | ||
const graphql_1 = require("graphql"); | ||
const path_1 = tslib_1.__importDefault(require("path")); | ||
const builder_1 = require("./builder"); | ||
function log(msg) { | ||
console.log("GraphQL Nexus: " + msg); | ||
console.log(`GraphQL Nexus: ${msg}`); | ||
} | ||
exports.log = log; | ||
exports.isInterfaceField = function (type, fieldName) { | ||
return type.getInterfaces().some(function (i) { return Boolean(i.getFields()[fieldName]); }); | ||
exports.isInterfaceField = (type, fieldName) => { | ||
return type.getInterfaces().some((i) => Boolean(i.getFields()[fieldName])); | ||
}; | ||
@@ -24,5 +24,3 @@ // ---------------------------- | ||
*/ | ||
function suggestionList(input, options) { | ||
if (input === void 0) { input = ""; } | ||
if (options === void 0) { options = []; } | ||
function suggestionList(input = "", options = []) { | ||
var optionsByDistance = Object.create(null); | ||
@@ -61,9 +59,9 @@ var oLength = options.length; | ||
} | ||
var i; | ||
var j; | ||
var d = []; | ||
var a = aStr.toLowerCase(); | ||
var b = bStr.toLowerCase(); | ||
var aLength = a.length; | ||
var bLength = b.length; // Any case change counts as a single edit | ||
let i; | ||
let j; | ||
const d = []; | ||
const a = aStr.toLowerCase(); | ||
const b = bStr.toLowerCase(); | ||
const aLength = a.length; | ||
const bLength = b.length; // Any case change counts as a single edit | ||
if (a === b) { | ||
@@ -91,3 +89,3 @@ return 1; | ||
function objValues(obj) { | ||
return Object.keys(obj).reduce(function (result, key) { | ||
return Object.keys(obj).reduce((result, key) => { | ||
result.push(obj[key]); | ||
@@ -99,15 +97,13 @@ return result; | ||
function mapObj(obj, mapper) { | ||
return Object.keys(obj).map(function (key, index) { return mapper(obj[key], key, index); }); | ||
return Object.keys(obj).map((key, index) => mapper(obj[key], key, index)); | ||
} | ||
exports.mapObj = mapObj; | ||
function eachObj(obj, iter) { | ||
Object.keys(obj).forEach(function (name, i) { return iter(obj[name], name, i); }); | ||
Object.keys(obj).forEach((name, i) => iter(obj[name], name, i)); | ||
} | ||
exports.eachObj = eachObj; | ||
exports.isObject = function (obj) { | ||
return obj !== null && typeof obj === "object"; | ||
}; | ||
exports.assertAbsolutePath = function (pathName, property) { | ||
exports.isObject = (obj) => obj !== null && typeof obj === "object"; | ||
exports.assertAbsolutePath = (pathName, property) => { | ||
if (!path_1.default.isAbsolute(pathName)) { | ||
throw new Error("Expected path for " + property + " to be an absolute path, saw " + pathName); | ||
throw new Error(`Expected path for ${property} to be an absolute path, saw ${pathName}`); | ||
} | ||
@@ -117,3 +113,3 @@ return pathName; | ||
function groupTypes(schema) { | ||
var groupedTypes = { | ||
const groupedTypes = { | ||
input: [], | ||
@@ -126,10 +122,10 @@ interface: [], | ||
}; | ||
var schemaTypeMap = schema.getTypeMap(); | ||
const schemaTypeMap = schema.getTypeMap(); | ||
Object.keys(schemaTypeMap) | ||
.sort() | ||
.forEach(function (typeName) { | ||
.forEach((typeName) => { | ||
if (typeName.indexOf("__") === 0) { | ||
return; | ||
} | ||
var type = schema.getType(typeName); | ||
const type = schema.getType(typeName); | ||
if (graphql_1.isObjectType(type)) { | ||
@@ -163,9 +159,5 @@ groupedTypes.object.push(type); | ||
exports.isUnknownType = isUnknownType; | ||
function firstDefined() { | ||
var args = []; | ||
for (var _i = 0; _i < arguments.length; _i++) { | ||
args[_i] = arguments[_i]; | ||
} | ||
for (var i = 0; i < args.length; i++) { | ||
var arg = args[i]; | ||
function firstDefined(...args) { | ||
for (let i = 0; i < args.length; i++) { | ||
const arg = args[i]; | ||
if (typeof arg !== "undefined") { | ||
@@ -185,6 +177,6 @@ return arg; | ||
function relativePathTo(absolutePath, outputPath) { | ||
var filename = path_1.default.basename(absolutePath).replace(/(\.d)?\.ts/, ""); | ||
var relative = path_1.default.relative(path_1.default.dirname(outputPath), path_1.default.dirname(absolutePath)); | ||
const filename = path_1.default.basename(absolutePath).replace(/(\.d)?\.ts/, ""); | ||
const relative = path_1.default.relative(path_1.default.dirname(outputPath), path_1.default.dirname(absolutePath)); | ||
if (relative.indexOf(".") !== 0) { | ||
return "./" + path_1.default.join(relative, filename); | ||
return `./${path_1.default.join(relative, filename)}`; | ||
} | ||
@@ -195,7 +187,51 @@ return path_1.default.join(relative, filename); | ||
/** | ||
* Returns its input. For example: | ||
* Calculate the venn diagram between two iterables based on reference equality | ||
* checks. The returned tripple contains items thusly: | ||
* | ||
* id(1) // -> 1 | ||
* * items only in arg 1 --> first tripple slot | ||
* * items in args 1 & 2 --> second tripple slot | ||
* * items only in arg 2 --> third tripple slot | ||
*/ | ||
exports.id = function (x) { return x; }; | ||
function venn(xs, ys) { | ||
const lefts = new Set(xs); | ||
const boths = new Set(); | ||
const rights = new Set(ys); | ||
for (const l of lefts) { | ||
if (rights.has(l)) { | ||
boths.add(l); | ||
lefts.delete(l); | ||
rights.delete(l); | ||
} | ||
} | ||
for (const r of rights) { | ||
if (lefts.has(r)) { | ||
boths.add(r); | ||
lefts.delete(r); | ||
rights.delete(r); | ||
} | ||
} | ||
return [lefts, boths, rights]; | ||
} | ||
exports.venn = venn; | ||
function indentBlock(size, block) { | ||
return block | ||
.split("\n") | ||
.map((line) => range(size) | ||
.map(constant(" ")) | ||
.join("") + line) | ||
.join("\n"); | ||
} | ||
exports.indentBlock = indentBlock; | ||
function constant(x) { | ||
return function () { | ||
return x; | ||
}; | ||
} | ||
function range(times) { | ||
const list = []; | ||
while (list.length < times) { | ||
list.push(list.length + 1); | ||
} | ||
return list; | ||
} | ||
//# sourceMappingURL=utils.js.map |
{ | ||
"name": "nexus", | ||
"version": "0.0.0-pr.236.5bdf659", | ||
"version": "0.0.0-pr.275.004e62d", | ||
"main": "dist", | ||
@@ -9,2 +9,3 @@ "types": "dist/index.d.ts", | ||
"homepage": "https://nexus.js.org", | ||
"bin": "bin/run", | ||
"scripts": { | ||
@@ -15,2 +16,3 @@ "test": "jest", | ||
"dev": "tsc -w", | ||
"dev:test": "jest --watch", | ||
"dev:examples": "yarn -s link-examples && tsc -w", | ||
@@ -33,2 +35,3 @@ "lint": "tslint -p tsconfig.json", | ||
"dist", | ||
"bin", | ||
"LICENSE.md", | ||
@@ -43,2 +46,3 @@ "README.md", | ||
"dependencies": { | ||
"@oclif/command": "^1.5.19", | ||
"tslib": "^1.9.3" | ||
@@ -52,2 +56,4 @@ }, | ||
"@types/prettier": "^1.15.2", | ||
"codecov": "^3.6.1", | ||
"globby": "^10.0.1", | ||
"graphql": "^14.0.2", | ||
@@ -61,3 +67,3 @@ "graphql-iso-date": "^3.6.1", | ||
"ts-jest": "^24", | ||
"ts-node": "^7.0.1", | ||
"ts-node": "^8.4.1", | ||
"tslint": "^5.11.0", | ||
@@ -75,2 +81,6 @@ "tslint-config-prettier": "^1.15.0", | ||
}, | ||
"oclif": { | ||
"commands": "./dist/cli/commands", | ||
"bin": "nexus" | ||
}, | ||
"lint-staged": { | ||
@@ -77,0 +87,0 @@ "*.{js,json,css,md}": [ |
@@ -1,13 +0,13 @@ | ||
<p align="center"><a href="https://nexus.js.org"><img src="https://i.imgur.com/Y5BgDGl.png" width="150" /><a></p> | ||
<p align="center"> | ||
<a href="https://nexus.js.org"><img src="https://i.imgur.com/Y5BgDGl.png" width="150" /><a> | ||
<h1 align="center">Nexus</h1> | ||
</p> | ||
# GraphQL Nexus | ||
[](https://circleci.com/gh/prisma/nexus) | ||
[](https://badge.fury.io/js/nexus) | ||
[](https://spectrum.chat/nexus) | ||
[](https://badge.fury.io/js/nexus) | ||
[](https://slack.prisma.io/) | ||
Declarative, code-first and strongly typed GraphQL schema construction for TypeScript & JavaScript | ||
> GraphQL Nexus is independent from Prisma. To learn how it can best be combined with Prisma, check out the [`nexus-prisma`](https://github.com/prisma/nexus-prisma) plugin. | ||
> GraphQL Nexus can be used independently from [Prisma](https://www.prisma.io). To learn how it can best be combined with Prisma, check out the [`nexus-prisma`](https://github.com/prisma-labs/nexus-prisma) plugin. | ||
@@ -14,0 +14,0 @@ ## Overview |
@@ -0,1 +1,2 @@ | ||
import * as path from "path"; | ||
import { | ||
@@ -121,3 +122,3 @@ GraphQLBoolean, | ||
isUnknownType, | ||
Index, | ||
assertAbsolutePath, | ||
} from "./utils"; | ||
@@ -131,3 +132,3 @@ import { | ||
import { decorateType } from "./definitions/decorateType"; | ||
import { Plugin, initializePlugin } from "./plugins"; | ||
import * as Plugins from "./plugins"; | ||
@@ -187,20 +188,37 @@ export type Maybe<T> = T | null; | ||
export interface BuilderConfig { | ||
plugins?: Plugin[]; | ||
plugins?: Plugins.PluginDef[]; | ||
/** | ||
* When the schema starts and `process.env.NODE_ENV !== "production"`, | ||
* artifact files are auto-generated containing the .graphql definitions of | ||
* the schema | ||
* Generated artifact settings. Set to false to disable all. | ||
* Set to true to enable all and use default paths. Leave | ||
* undefined for default behaviour of each artifact. | ||
*/ | ||
outputs: | ||
outputs?: | ||
| boolean | ||
| { | ||
/** | ||
* Absolute path where the GraphQL IDL file should be written | ||
* TypeScript declaration file generation settings. This file | ||
* contains types reflected off your source code. It is how | ||
* Nexus imbues dynamic code with static guarnatees. | ||
* | ||
* Defaults to being enabled when `process.env.NODE_ENV !== "production"`. | ||
* Set to true to enable and emit into default path (see below). | ||
* Set to false to disable. Set to a string to specify absolute path. | ||
* | ||
* The default path is node_modules/@types/nexus-typegen/index.d.ts. | ||
* This is chosen becuase TypeScript will pick it up without | ||
* any configuration needed by you. For more details about the @types | ||
* system refer to https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types | ||
*/ | ||
schema: string | false; | ||
typegen?: boolean | string; | ||
/** | ||
* File path where generated types should be saved | ||
* GraphQL SDL generation settings. This file is not necessary but | ||
* may be nice for teams wishing to review SDL in pull-requests or | ||
* just generally transitioning from a schema-first workflow. | ||
* | ||
* Defaults to false (disabled). Set to true to enable and emit into | ||
* default path (current working directory). Set to a string to specify | ||
* absolute path. | ||
*/ | ||
typegen: string | false; | ||
} | ||
| false; | ||
schema?: boolean | string; | ||
}; | ||
/** | ||
@@ -243,2 +261,11 @@ * Whether the schema & types are generated when the server | ||
export interface SchemaConfig extends BuilderConfig { | ||
/** | ||
* All of the GraphQL types. This is an any for simplicity of developer experience, | ||
* if it's an object we get the values, if it's an array we flatten out the | ||
* valid types, ignoring invalid ones. | ||
*/ | ||
types: any; | ||
} | ||
export interface TypegenInfo { | ||
@@ -264,11 +291,98 @@ /** | ||
export interface SchemaConfig extends BuilderConfig { | ||
/** | ||
* All of the GraphQL types. This is an any for simplicity of developer experience, | ||
* if it's an object we get the values, if it's an array we flatten out the | ||
* valid types, ignoring invalid ones. | ||
*/ | ||
/** | ||
* The resolved builder config wherein optional fields have been | ||
* given their fallbacks, etc. | ||
*/ | ||
export interface InternalBuilderConfig extends BuilderConfig { | ||
outputs: { | ||
schema: false | string; | ||
typegen: false | string; | ||
}; | ||
} | ||
export function resolveBuilderConfig( | ||
config: BuilderConfig | ||
): InternalBuilderConfig { | ||
// For JS | ||
if (config.outputs === null) { | ||
throw new Error("config.outputs cannot be of type `null`."); | ||
} | ||
if ( | ||
typeof config.outputs === "object" && | ||
typeof config.outputs.schema === "string" | ||
) { | ||
assertAbsolutePath(config.outputs.schema, "outputs.schema"); | ||
} | ||
// Setup defaults | ||
const defaultSchemaPath = path.join(process.cwd(), "schema.graphql"); | ||
const defaultTypesPath = path.join( | ||
__dirname, | ||
"../../@types/nexus-typegen/index.d.ts" | ||
); | ||
const defaults = { | ||
outputs: { | ||
schema: defaultSchemaPath, | ||
typegen: defaultTypesPath, | ||
}, | ||
outputsUndefined: { | ||
schema: false, | ||
typegen: defaultTypesPath, | ||
}, | ||
} as const; | ||
// Build internal config | ||
const internalConfig = { | ||
...config, | ||
outputs: {}, | ||
} as InternalBuilderConfig; | ||
const shouldGenerateArtifacts = | ||
config.shouldGenerateArtifacts !== undefined | ||
? config.shouldGenerateArtifacts | ||
: process.env.NEXUS_SHOULD_GENERATE_ARTIFACTS === "true" | ||
? true | ||
: process.env.NEXUS_SHOULD_GENERATE_ARTIFACTS === "false" | ||
? false | ||
: Boolean( | ||
!process.env.NODE_ENV || process.env.NODE_ENV === "development" | ||
); | ||
if (shouldGenerateArtifacts === false || config.outputs === false) { | ||
internalConfig.outputs = { schema: false, typegen: false }; | ||
} else if (config.outputs === true) { | ||
internalConfig.outputs = defaults.outputs; | ||
} else if (config.outputs === undefined) { | ||
internalConfig.outputs = defaults.outputsUndefined; | ||
} else { | ||
if (config.outputs.schema === undefined) { | ||
internalConfig.outputs.schema = false; | ||
} else if (config.outputs.schema === true) { | ||
internalConfig.outputs.schema = defaults.outputs.schema; | ||
} else { | ||
internalConfig.outputs.schema = config.outputs.schema; | ||
} | ||
if ( | ||
config.outputs.typegen === undefined || | ||
config.outputs.typegen === true | ||
) { | ||
internalConfig.outputs.typegen = defaults.outputs.typegen; | ||
} else { | ||
internalConfig.outputs.typegen = config.outputs.typegen; | ||
} | ||
} | ||
return internalConfig; | ||
} | ||
export interface InternalSchemaConfig extends InternalBuilderConfig { | ||
types: any; | ||
} | ||
function resolveSchemaConfig(config: SchemaConfig): InternalSchemaConfig { | ||
// There is no additional processing for schema config | ||
return resolveBuilderConfig(config) as InternalSchemaConfig; | ||
} | ||
export type TypeToWalk = | ||
@@ -302,5 +416,7 @@ | { type: "named"; value: GraphQLNamedType } | ||
/** | ||
* Used to track all types that have been added to the builder. | ||
* Used to track all _GraphQL_ types that have been added to the builder. | ||
* This supports hasType method which permits asking the question "Will | ||
* the GraphQL schema have _this_ type (name)". | ||
*/ | ||
protected allTypes: Index<NexusAcceptedTypeDef> = {}; | ||
protected allTypeDefs: Record<string, NexusAcceptedTypeDef> = {}; | ||
/** | ||
@@ -313,3 +429,3 @@ * Used to check for circular references. | ||
*/ | ||
protected finalTypeMap: Index<GraphQLNamedType> = {}; | ||
protected finalTypeMap: Record<string, GraphQLNamedType> = {}; | ||
/** | ||
@@ -320,3 +436,3 @@ * The "defined type" map keeps track of all of the types that were | ||
*/ | ||
protected definedTypeMap: Index<GraphQLNamedType> = {}; | ||
protected definedTypeMap: Record<string, GraphQLNamedType> = {}; | ||
/** | ||
@@ -326,7 +442,8 @@ * The "pending type" map keeps track of all types that were defined w/ | ||
*/ | ||
protected pendingTypeMap: Index<AllNexusNamedTypeDefs> = {}; | ||
protected pendingTypeMap: Record<string, AllNexusNamedTypeDefs> = {}; | ||
/** | ||
* All "extensions" to types (adding fields on types from many locations) | ||
*/ | ||
protected typeExtensionMap: Index< | ||
protected typeExtensionMap: Record< | ||
string, | ||
NexusExtendTypeConfig<string>[] | null | ||
@@ -337,3 +454,4 @@ > = {}; | ||
*/ | ||
protected inputTypeExtensionMap: Index< | ||
protected inputTypeExtensionMap: Record< | ||
string, | ||
NexusExtendInputTypeConfig<string>[] | null | ||
@@ -374,3 +492,3 @@ > = {}; | ||
*/ | ||
protected missingTypes: Index<MissingType> = {}; | ||
protected missingTypes: Record<string, MissingType> = {}; | ||
@@ -395,3 +513,3 @@ /** | ||
hasType = (typeName: string): boolean => { | ||
return Boolean(this.allTypes[typeName]); | ||
return Boolean(this.allTypeDefs[typeName]); | ||
}; | ||
@@ -406,6 +524,2 @@ | ||
addType = (typeDef: NexusAcceptedTypeDef) => { | ||
if (!this.allTypes[typeDef.name]) { | ||
this.allTypes[typeDef.name] = typeDef; | ||
} | ||
if (isNexusDynamicInputMethod(typeDef)) { | ||
@@ -451,2 +565,6 @@ this.dynamicInputFields[typeDef.name] = typeDef; | ||
if (!this.allTypeDefs[typeDef.name]) { | ||
this.allTypeDefs[typeDef.name] = typeDef; | ||
} | ||
if (isNexusScalarTypeDef(typeDef) && typeDef.value.asNexusMethod) { | ||
@@ -1356,6 +1474,20 @@ this.dynamicInputFields[typeDef.value.asNexusMethod] = typeDef.name; | ||
): BuildTypes<TypeMapDefs> { | ||
const internalConfig = resolveBuilderConfig(config || {}); | ||
return buildTypesInternal<TypeMapDefs>(types, internalConfig, schemaBuilder); | ||
} | ||
/** | ||
* Internal build types woring with config rather than options. | ||
*/ | ||
export function buildTypesInternal< | ||
TypeMapDefs extends Record<string, GraphQLNamedType> = any | ||
>( | ||
types: any, | ||
config: InternalBuilderConfig, | ||
schemaBuilder?: SchemaBuilder | ||
): BuildTypes<TypeMapDefs> { | ||
const builder = schemaBuilder || new SchemaBuilder(config); | ||
const plugins = config.plugins || []; | ||
const pluginControllers = plugins.map((plugin) => | ||
initializePlugin(builder, plugin) | ||
Plugins.initialize(builder, plugin) | ||
); | ||
@@ -1408,11 +1540,12 @@ addTypes(builder, types); | ||
export function makeSchemaInternal( | ||
options: SchemaConfig, | ||
config: InternalSchemaConfig, | ||
schemaBuilder?: SchemaBuilder | ||
): { schema: NexusSchema; missingTypes: Record<string, MissingType> } { | ||
const { typeMap, dynamicFields, rootTypings, missingTypes } = buildTypes( | ||
options.types, | ||
options, | ||
schemaBuilder | ||
); | ||
let { Query, Mutation, Subscription } = typeMap; | ||
const { | ||
typeMap, | ||
dynamicFields, | ||
rootTypings, | ||
missingTypes, | ||
} = buildTypesInternal(config.types, config, schemaBuilder); | ||
const { Query, Mutation, Subscription } = typeMap; | ||
@@ -1460,17 +1593,10 @@ if (!isObjectType(Query)) { | ||
*/ | ||
export function makeSchema(options: SchemaConfig): GraphQLSchema { | ||
const { schema, missingTypes } = makeSchemaInternal(options); | ||
export function makeSchema(config: SchemaConfig): GraphQLSchema { | ||
const internalConfig = resolveSchemaConfig(config); | ||
const { schema, missingTypes } = makeSchemaInternal(internalConfig); | ||
// Only in development envs do we want to worry about regenerating the | ||
// schema definition and/or generated types. | ||
const { | ||
shouldGenerateArtifacts = Boolean( | ||
!process.env.NODE_ENV || process.env.NODE_ENV === "development" | ||
), | ||
} = options; | ||
if (shouldGenerateArtifacts) { | ||
if (internalConfig.outputs.schema || internalConfig.outputs.typegen) { | ||
// Generating in the next tick allows us to use the schema | ||
// in the optional thunk for the typegen config | ||
new TypegenMetadata(options).generateArtifacts(schema).catch((e) => { | ||
new TypegenMetadata(internalConfig).generateArtifacts(schema).catch((e) => { | ||
console.error(e); | ||
@@ -1490,7 +1616,8 @@ }); | ||
export async function generateSchema( | ||
options: SchemaConfig | ||
config: SchemaConfig | ||
): Promise<NexusSchema> { | ||
const { schema, missingTypes } = makeSchemaInternal(options); | ||
const internalConfig = resolveSchemaConfig(config); | ||
const { schema, missingTypes } = makeSchemaInternal(internalConfig); | ||
assertNoMissingTypes(schema, missingTypes); | ||
await new TypegenMetadata(options).generateArtifacts(schema); | ||
await new TypegenMetadata(internalConfig).generateArtifacts(schema); | ||
return schema; | ||
@@ -1497,0 +1624,0 @@ } |
@@ -32,2 +32,3 @@ import { | ||
DynamicOutputProperty = "DynamicOutputProperty", | ||
Plugin = "Plugin", | ||
} | ||
@@ -34,0 +35,0 @@ |
// All of the Public API definitions | ||
export { Plugin, create as createPlugin } from "./plugins"; | ||
export { | ||
createPlugin, | ||
PluginConfig, | ||
PluginBuilderLens, | ||
PluginOnInstallHandler, | ||
} from "./plugins"; | ||
export { buildTypes, makeSchema } from "./builder"; | ||
@@ -4,0 +9,0 @@ export { |
import { SchemaBuilder, NexusAcceptedTypeDef } from "./builder"; | ||
import { withNexusSymbol, NexusTypes } from "./definitions/_types"; | ||
import { venn } from "./utils"; | ||
/** | ||
* This is a read-only builder-like api exposed to plugins in the onInstall | ||
* hook. It proxies the Nexus Builder which is a much bigger beast that we do | ||
* not want to directly expose to plugins. | ||
* A read-only builder api exposed to plugins in the onInstall hook which | ||
* proxies very limited functionality into the internal Nexus Builder. | ||
*/ | ||
type BuilderFacade = { | ||
export type PluginBuilderLens = { | ||
hasType: (typeName: string) => boolean; | ||
@@ -17,14 +18,60 @@ }; | ||
*/ | ||
export type Plugin = { | ||
onInstall: OnInstallHandler; | ||
export type PluginConfig = { | ||
name: string; | ||
onInstall?: PluginOnInstallHandler; | ||
}; | ||
type OnInstallHandler = ( | ||
builder: BuilderFacade | ||
/** | ||
* The plugin callback to execute when onInstall lifecycle event occurs. | ||
* OnInstall event occurs before type walking which means inline types are not | ||
* visible at this point yet. `builderLens.hasType` will only return true | ||
* for types the user has defined top level in their app, and any types added by | ||
* upstream plugins. | ||
*/ | ||
export type PluginOnInstallHandler = ( | ||
builder: PluginBuilderLens | ||
) => { types: NexusAcceptedTypeDef[] }; | ||
/** | ||
* This is the interface that Nexus uses to drive plugins meaning triggering the | ||
* lifecycle events that plugins have registered for. | ||
* The processed version of a plugin config. This lower level version has | ||
* defaults provided for optionals etc. | ||
*/ | ||
export type InternalPluginConfig = Required<PluginConfig>; | ||
/** | ||
* A plugin defines configuration which can document additional metadata options | ||
* for a type definition. This metadata can be used to decorate the "resolve" function | ||
* to provide custom functionality, such as logging, error handling, additional type | ||
* validation. | ||
* | ||
* You can specify options which can be defined on the schema, | ||
* the type or the plugin. The config from each of these will be | ||
* passed in during schema construction time, and used to augment the field as necessary. | ||
* | ||
* You can either return a function, with the new defintion of a resolver implementation, | ||
* or you can return an "enter" / "leave" pairing which will wrap the pre-execution of the | ||
* resolver and the "result" of the resolver, respectively. | ||
*/ | ||
export function createPlugin(config: PluginConfig): PluginDef { | ||
validatePluginConfig(config); | ||
const internalConfig = { ...configDefaults, ...config }; | ||
return new PluginDef(internalConfig); | ||
} | ||
const configDefaults = { | ||
onInstall: () => ({ types: [] }), | ||
}; | ||
/** | ||
* A definition for a plugin. Should be passed to the `plugins: []` option | ||
* on makeSchema. Refer to `createPlugin` factory for full doc. | ||
*/ | ||
export class PluginDef { | ||
constructor(readonly config: InternalPluginConfig) {} | ||
} | ||
withNexusSymbol(PluginDef, NexusTypes.Plugin); | ||
/** | ||
* The interface used to drive plugin execution via lifecycle event triggering. | ||
*/ | ||
type PluginController = { | ||
@@ -35,30 +82,118 @@ triggerOnInstall: () => void; | ||
/** | ||
* Initialize a plugin. This will gather the hook handlers (aka. callbacks, | ||
* event handlers) that the plugin has registered for. A controller is returned | ||
* that permits Nexus to trigger the hooks so executing the hook handlers. | ||
* This will gather the hook handlers (aka. callbacks, event handlers) a the | ||
* plugin has registered for and return a controller to trigger said hooks, | ||
* thus controlling execution of the plugins' hook handlers. | ||
*/ | ||
export const initializePlugin = ( | ||
export function initialize( | ||
builder: SchemaBuilder, | ||
plugin: Plugin | ||
): PluginController => { | ||
plugin: PluginDef | ||
): PluginController { | ||
const state = { | ||
onInstallTriggered: false, | ||
}; | ||
const builderLens: PluginBuilderLens = { | ||
hasType: builder.hasType, | ||
}; | ||
return { | ||
triggerOnInstall: () => { | ||
if (plugin.onInstall) { | ||
const { types } = plugin.onInstall({ | ||
hasType: builder.hasType, | ||
}); | ||
types.forEach(builder.addType); | ||
// Enforce the invariant that a lifecycle hook will only ever be called once. | ||
if (state.onInstallTriggered) { | ||
throw new Error( | ||
"Multiple triggers of onInstall hook detected. This should never happen. This is an internal error." | ||
); | ||
} else { | ||
state.onInstallTriggered = true; | ||
} | ||
// By doing addType on the types returned by a plugin right after it has | ||
// done so we make it possible for downstream plugins to see types added | ||
// by upstream plugins. | ||
let hookResult: ReturnType<PluginOnInstallHandler>; | ||
try { | ||
hookResult = plugin.config.onInstall(builderLens); | ||
} catch (error) { | ||
throw new Error( | ||
`Plugin ${plugin.config.name} failed on "onInstall" hook:\n\n${error.stack}` | ||
); | ||
} | ||
validateOnInstallHookResult(plugin, hookResult); | ||
hookResult.types.forEach(builder.addType); | ||
}, | ||
}; | ||
}; | ||
} | ||
/** | ||
* Create a Nexus Plugin. This function is just a convenience for not having to | ||
* import the Plugin type. Feel free to do this instead: | ||
* | ||
* import { Plugin } from "nexus" | ||
* export default { ... } as Plugin | ||
* | ||
* Validate that the configuration given by a plugin is valid. | ||
*/ | ||
export const create = (plugin: Plugin): Plugin => plugin; | ||
function validatePluginConfig(plugin: PluginConfig): void { | ||
const validRequiredProps = ["name"]; | ||
const validOptionalProps = ["onInstall"]; | ||
const validProps = [...validRequiredProps, ...validOptionalProps]; | ||
const givenProps = Object.keys(plugin); | ||
const printProps = (props: Iterable<string>): string => { | ||
return [...props].join(", "); | ||
}; | ||
const [missingRequiredProps, ,] = venn(validRequiredProps, givenProps); | ||
if (missingRequiredProps.size > 0) { | ||
throw new Error( | ||
`Plugin "${plugin.name}" is missing required properties: ${printProps( | ||
missingRequiredProps | ||
)}` | ||
); | ||
} | ||
const nameType = typeof plugin.name; | ||
if (nameType !== "string") { | ||
throw new Error( | ||
`Plugin "${plugin.name}" is giving an invalid value for property name: expected "string" type, got ${nameType} type` | ||
); | ||
} | ||
if (plugin.name === "") { | ||
throw new Error( | ||
`Plugin "${plugin.name}" is giving an invalid value for property name: empty string` | ||
); | ||
} | ||
const [, , invalidGivenProps] = venn(validProps, givenProps); | ||
if (invalidGivenProps.size > 0) { | ||
throw new Error( | ||
`Plugin "${plugin.name}" is giving unexpected properties: ${printProps( | ||
invalidGivenProps | ||
)}` | ||
); | ||
} | ||
if (plugin.onInstall) { | ||
const onInstallType = typeof plugin.onInstall; | ||
if (onInstallType !== "function") { | ||
throw new Error( | ||
`Plugin "${plugin.name}" is giving an invalid value for onInstall hook: expected "function" type, got ${onInstallType} type` | ||
); | ||
} | ||
} | ||
} | ||
/** | ||
* Validate that the data returned from a plugin from the `onInstall` hook is valid. | ||
*/ | ||
function validateOnInstallHookResult( | ||
plugin: PluginDef, | ||
hookResult: ReturnType<PluginOnInstallHandler> | ||
): void { | ||
if ( | ||
hookResult === null || | ||
typeof hookResult !== "object" || | ||
!Array.isArray(hookResult.types) | ||
) { | ||
throw new Error( | ||
`Plugin "${plugin.config.name}" returned invalid data for "onInstall" hook:\n\nexpected structure:\n\n { types: NexusAcceptedTypeDef[] }\n\ngot:\n\n ${hookResult}` | ||
); | ||
} | ||
// TODO we should validate that the array members all fall under NexusAcceptedTypeDef | ||
} |
@@ -483,3 +483,3 @@ import { | ||
argTypeMap[type.name][field.name] = field.args.reduce( | ||
(obj: Record<string, string[]>, arg) => { | ||
(obj: Record<string, [string, string]>, arg) => { | ||
obj[arg.name] = this.normalizeArg(arg); | ||
@@ -486,0 +486,0 @@ return obj; |
import { GraphQLSchema, lexicographicSortSchema, printSchema } from "graphql"; | ||
import path from "path"; | ||
import { Typegen } from "./typegen"; | ||
import { assertAbsolutePath } from "./utils"; | ||
import { SDL_HEADER, TYPEGEN_HEADER } from "./lang"; | ||
@@ -12,6 +11,6 @@ import { typegenAutoConfig } from "./typegenAutoConfig"; | ||
import { | ||
BuilderConfig, | ||
TypegenInfo, | ||
InternalBuilderConfig, | ||
NexusSchemaExtensions, | ||
NexusSchema, | ||
NexusSchemaExtensions, | ||
} from "./builder"; | ||
@@ -25,17 +24,6 @@ | ||
export class TypegenMetadata { | ||
protected typegenFile: string = ""; | ||
constructor(protected config: InternalBuilderConfig) {} | ||
constructor(protected config: BuilderConfig) { | ||
if (config.outputs !== false && config.shouldGenerateArtifacts !== false) { | ||
if (config.outputs.typegen) { | ||
this.typegenFile = assertAbsolutePath( | ||
config.outputs.typegen, | ||
"outputs.typegen" | ||
); | ||
} | ||
} | ||
} | ||
/** | ||
* Generates the artifacts of the build based on what we | ||
* Generates the artifacts of the buid based on what we | ||
* know about the schema and how it was defined. | ||
@@ -45,18 +33,17 @@ */ | ||
const sortedSchema = this.sortSchema(schema); | ||
if (this.config.outputs) { | ||
if (this.config.outputs.schema) { | ||
await this.writeFile( | ||
"schema", | ||
this.generateSchemaFile(sortedSchema), | ||
this.config.outputs.schema | ||
); | ||
} | ||
if (this.typegenFile) { | ||
const value = await this.generateTypesFile( | ||
sortedSchema, | ||
schema.extensions.nexus | ||
); | ||
await this.writeFile("types", value, this.typegenFile); | ||
} | ||
if (this.config.outputs.schema) { | ||
await this.writeFile( | ||
"schema", | ||
this.generateSchemaFile(sortedSchema), | ||
this.config.outputs.schema | ||
); | ||
} | ||
if (this.config.outputs.typegen) { | ||
const value = await this.generateTypesFile( | ||
sortedSchema, | ||
schema.extensions.nexus, | ||
this.config.outputs.typegen | ||
); | ||
await this.writeFile("types", value, this.config.outputs.typegen); | ||
} | ||
} | ||
@@ -82,5 +69,6 @@ | ||
const util = require("util") as typeof import("util"); | ||
const [readFile, writeFile, mkdir] = [ | ||
const [readFile, writeFile, removeFile, mkdir] = [ | ||
util.promisify(fs.readFile), | ||
util.promisify(fs.writeFile), | ||
util.promisify(fs.unlink), | ||
util.promisify(fs.mkdir), | ||
@@ -111,2 +99,12 @@ ]; | ||
} | ||
// VSCode reacts to file changes better if a file is first deleted, | ||
// apparently. See issue motivating this logic here: | ||
// https://github.com/prisma-labs/nexus/issues/247. | ||
try { | ||
await removeFile(filePath); | ||
} catch (e) { | ||
if (e.code !== "ENOENT") { | ||
throw e; | ||
} | ||
} | ||
return writeFile(filePath, toSave); | ||
@@ -129,3 +127,4 @@ } | ||
schema: GraphQLSchema, | ||
extensions: NexusSchemaExtensions | ||
extensions: NexusSchemaExtensions, | ||
typegenFile: string | ||
): Promise<string> { | ||
@@ -136,3 +135,3 @@ return new Typegen( | ||
...(await this.getTypegenInfo(schema)), | ||
typegenFile: this.typegenFile, | ||
typegenFile, | ||
}, | ||
@@ -150,10 +149,15 @@ extensions | ||
} | ||
return this.config.typegenConfig(schema, this.typegenFile); | ||
return this.config.typegenConfig( | ||
schema, | ||
this.config.outputs.typegen || "" | ||
); | ||
} | ||
if (this.config.typegenAutoConfig) { | ||
return typegenAutoConfig(this.config.typegenAutoConfig)( | ||
schema, | ||
this.typegenFile | ||
this.config.outputs.typegen || "" | ||
); | ||
} | ||
return { | ||
@@ -160,0 +164,0 @@ headers: [TYPEGEN_HEADER], |
@@ -241,13 +241,59 @@ import { | ||
/** | ||
* Index types are just an alias for Records whose keys are of type `string`. | ||
* The name of this type, `Index`, signifies its canonical use-case for data | ||
* indexed by some property, e.g. a list of users indexed by email. | ||
* Calculate the venn diagram between two iterables based on reference equality | ||
* checks. The returned tripple contains items thusly: | ||
* | ||
* * items only in arg 1 --> first tripple slot | ||
* * items in args 1 & 2 --> second tripple slot | ||
* * items only in arg 2 --> third tripple slot | ||
*/ | ||
export type Index<T> = Record<string, T>; | ||
export function venn<T>( | ||
xs: Iterable<T>, | ||
ys: Iterable<T> | ||
): [Set<T>, Set<T>, Set<T>] { | ||
const lefts: Set<T> = new Set(xs); | ||
const boths: Set<T> = new Set(); | ||
const rights: Set<T> = new Set(ys); | ||
/** | ||
* Returns its input. For example: | ||
* | ||
* id(1) // -> 1 | ||
*/ | ||
export const id = <T extends unknown>(x: T): T => x; | ||
for (const l of lefts) { | ||
if (rights.has(l)) { | ||
boths.add(l); | ||
lefts.delete(l); | ||
rights.delete(l); | ||
} | ||
} | ||
for (const r of rights) { | ||
if (lefts.has(r)) { | ||
boths.add(r); | ||
lefts.delete(r); | ||
rights.delete(r); | ||
} | ||
} | ||
return [lefts, boths, rights]; | ||
} | ||
export function indentBlock(size: number, block: string): string { | ||
return block | ||
.split("\n") | ||
.map( | ||
(line) => | ||
range(size) | ||
.map(constant(" ")) | ||
.join("") + line | ||
) | ||
.join("\n"); | ||
} | ||
function constant<T>(x: T): () => T { | ||
return function() { | ||
return x; | ||
}; | ||
} | ||
function range(times: number): number[] { | ||
const list: number[] = []; | ||
while (list.length < times) { | ||
list.push(list.length + 1); | ||
} | ||
return list; | ||
} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Shell access
Supply chain riskThis module accesses the system shell. Accessing the system shell increases the risk of executing arbitrary code.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 2 instances in 1 package
710221
3.89%151
7.09%11001
3.92%3
50%19
11.76%10
42.86%1
Infinity%+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added