Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Fix preprocessed introspection being cut off by TS #152

Merged
merged 1 commit into from
Mar 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 56 additions & 45 deletions packages/internal/src/introspection.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { IntrospectionQuery } from 'graphql';
import { EmitHint, NodeBuilderFlags, NewLineKind, createPrinter } from 'typescript';

import { TypeFormatFlags } from 'typescript';
import { minifyIntrospectionQuery } from '@urql/introspection';

import { PREAMBLE_IGNORE, ANNOTATION_DTS, ANNOTATION_TS } from './constants';
Expand All @@ -13,24 +14,20 @@ import {
createProgram,
} from './vfs';

const builderFlags =
NodeBuilderFlags.NoTruncation |
NodeBuilderFlags.GenerateNamesForShadowedTypeParams |
NodeBuilderFlags.NoTypeReduction |
NodeBuilderFlags.AllowEmptyTuple |
NodeBuilderFlags.InObjectTypeLiteral |
NodeBuilderFlags.InTypeAlias |
NodeBuilderFlags.IgnoreErrors;

const boilerplateFile = `
import type { introspection } from './introspection.ts';
import type { mapIntrospection } from './gql-tada.ts';
type obj<T> = T extends { [key: string | number]: any } ? { [K in keyof T]: T[K] } : never;
export type output = obj<mapIntrospection<introspection>>;
`;
const ROOT_FILE = 'index.ts';
const ALIAS_PREFIX = '$__';

const BUILDER_FLAGS =
TypeFormatFlags.NoTruncation |
TypeFormatFlags.NoTypeReduction |
TypeFormatFlags.InTypeAlias |
TypeFormatFlags.UseFullyQualifiedType |
TypeFormatFlags.GenerateNamesForShadowedTypeParams;

const stringifyJson = (input: unknown | string): string =>
typeof input === 'string' ? input : JSON.stringify(input, null, 2);
const stringifyName = (input: string | undefined | null): string =>
input ? JSON.stringify(input) : 'never';

export function minifyIntrospection(introspection: IntrospectionQuery): IntrospectionQuery {
return minifyIntrospectionQuery(introspection, {
Expand All @@ -41,46 +38,60 @@ export function minifyIntrospection(introspection: IntrospectionQuery): Introspe
});
}

export async function preprocessIntrospection(introspection: IntrospectionQuery): Promise<string> {
const json = JSON.stringify(introspection, null, 2);
const introspectionFile = `export type introspection = ${json};`;

async function createHost(evaluateFile: string) {
const host = createVirtualHost();
await importLib(host);
await importModule(host, '@0no-co/graphql.web');
host.writeFile('gql-tada.ts', await resolveModuleFile('gql.tada/dist/gql-tada.d.ts'));
host.writeFile('introspection.ts', introspectionFile);
host.writeFile('index.ts', boilerplateFile);
host.writeFile(ROOT_FILE, evaluateFile);
return host;
}

const program = createProgram(['index.ts'], host);
const checker = program.getTypeChecker();
const diagnostics = program.getSemanticDiagnostics();
if (diagnostics.length) {
throw new TSError('TypeScript failed to evaluate introspection', diagnostics);
export async function preprocessIntrospection({
__schema: schema,
}: IntrospectionQuery): Promise<string> {
const queryName = stringifyName(schema.queryType.name);
const mutationName = stringifyName(schema.mutationType && schema.mutationType.name);
const subscriptionName = stringifyName(schema.subscriptionType && schema.subscriptionType.name);

// TODO: We'd love for this to be just evaluated from `mapIntrospection` instead
// However, currently TypeScript seems to have hard limits in both the printer and checker for how
// many types are evaluated inside large object types.
// A fix/hack to get TypeScript to output the entire type would be preferable to splitting printing
// up here.
let evaluateFile = 'import type { __mapType } from "./gql-tada.ts";\n';
for (const type of schema.types) {
evaluateFile += `export type ${ALIAS_PREFIX + type.name} = __mapType<${JSON.stringify(
type
)}>;\n`;
}

const root = program.getSourceFile('index.ts');
const host = await createHost(evaluateFile);
const program = createProgram([ROOT_FILE], host);
const checker = program.getTypeChecker();
const diagnostics = program.getSemanticDiagnostics();
const root = program.getSourceFile(ROOT_FILE);
const rootSymbol = root && checker.getSymbolAtLocation(root);
const outputSymbol = rootSymbol && checker.getExportsOfModule(rootSymbol)[0];
const declaration = outputSymbol && outputSymbol.declarations && outputSymbol.declarations[0];
const type = declaration && checker.getTypeAtLocation(declaration);
if (!type) {
throw new TSError('Something went wrong while evaluating introspection type.');
}

const printer = createPrinter({
newLine: NewLineKind.LineFeed,
removeComments: true,
omitTrailingSemicolon: true,
noEmitHelpers: true,
});
if (diagnostics.length || !rootSymbol)
throw new TSError('TypeScript failed to evaluate introspection', diagnostics);

const typeNode = checker.typeToTypeNode(type, declaration, builderFlags);
if (!typeNode) {
throw new TSError('Something went wrong while evaluating introspection type node.');
let evaluatedTypes = '';
for (const exportSymbol of checker.getExportsOfModule(rootSymbol)) {
const declaration = exportSymbol && exportSymbol.declarations && exportSymbol.declarations[0];
const type = declaration && checker.getTypeAtLocation(declaration);
if (!type) throw new TSError('Something went wrong while evaluating introspection type.');
const typeStr = checker.typeToString(type, undefined, BUILDER_FLAGS).trim();
const nameStr = exportSymbol.name.slice(ALIAS_PREFIX.length);
evaluatedTypes += ` ${stringifyName(nameStr)}: ${typeStr};\n`;
}

return printer.printNode(EmitHint.Unspecified, typeNode, root);
return (
'{\n' +
` query: ${queryName};\n` +
` mutation: ${mutationName};\n` +
` subscription: ${subscriptionName};\n` +
` types: {\n${evaluatedTypes} };\n}`
);
}

interface OutputIntrospectionFileOptions {
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@ export type { DocumentDecoration } from './utils';

// NOTE: This must be exported for `isolatedModules: true`
export type { $tada } from './namespace';
export type { mapIntrospection } from './introspection';
export type { mapType as __mapType } from './introspection';
5 changes: 4 additions & 1 deletion src/introspection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ type mapUnion<T extends IntrospectionUnionType> = {
possibleTypes: T['possibleTypes'][number]['name'];
};

/** @internal */
type mapType<Type> = Type extends IntrospectionEnumType
? mapEnum<Type>
: Type extends IntrospectionObjectType
Expand All @@ -182,6 +183,7 @@ type mapType<Type> = Type extends IntrospectionEnumType
? unknown
: never;

/** @internal */
type mapIntrospectionTypes<Query extends IntrospectionQuery> = obj<{
[P in Query['__schema']['types'][number]['name']]: Query['__schema']['types'][number] extends infer Type
? Type extends { readonly name: P }
Expand All @@ -190,6 +192,7 @@ type mapIntrospectionTypes<Query extends IntrospectionQuery> = obj<{
: never;
}>;

/** @internal */
type mapIntrospectionScalarTypes<Scalars extends ScalarsLike = DefaultScalars> = obj<{
[P in keyof Scalars | keyof DefaultScalars]: {
kind: 'SCALAR';
Expand Down Expand Up @@ -241,4 +244,4 @@ export type SchemaLike = {
types: { [name: string]: any };
};

export type { mapIntrospectionTypes, mapIntrospection, addIntrospectionScalars };
export type { mapType, mapIntrospectionTypes, mapIntrospection, addIntrospectionScalars };
Loading