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

feat(internal/cli): Implement schema loaders for URL/SDL inputs #163

Merged
merged 10 commits into from
Mar 27, 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
5 changes: 5 additions & 0 deletions .changeset/beige-tools-eat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@gql.tada/internal": patch
---

Add `loadFromSDL` and `loadFromURL` schema loader utilities.
5 changes: 5 additions & 0 deletions .changeset/swift-dolphins-join.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@gql.tada/cli-utils": patch
---

Update CLI with new schema loaders
141 changes: 47 additions & 94 deletions packages/cli-utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import sade from 'sade';
import { promises as fs, existsSync, readFileSync } from 'node:fs';
import path, { resolve } from 'node:path';
import fs from 'node:fs/promises';
import path from 'node:path';
import { parse } from 'json5';
import type { IntrospectionQuery } from 'graphql';
import { buildClientSchema, getIntrospectionQuery, printSchema } from 'graphql';
import { printSchema } from 'graphql';

import type { GraphQLSchema } from 'graphql';
import type { TsConfigJson } from 'type-fest';
import { resolveTypeScriptRootDir } from '@gql.tada/internal';

import type { GraphQLSPConfig } from './lsp';
import { hasGraphQLSP } from './lsp';
import { ensureTadaIntrospection } from './tada';
import { getGraphQLSPConfig } from './lsp';
import { ensureTadaIntrospection, makeLoader } from './tada';

interface GenerateSchemaOptions {
headers?: Record<string, string>;
Expand All @@ -21,74 +21,31 @@ export async function generateSchema(
target: string,
{ headers, output, cwd = process.cwd() }: GenerateSchemaOptions
) {
let url: URL | undefined;
const loader = makeLoader(cwd, headers ? { url: target, headers } : target);

let schema: GraphQLSchema | null;
try {
url = new URL(target);
} catch (e) {}

let introspection: IntrospectionQuery;
if (url) {
const response = await fetch(url!.toString(), {
method: 'POST',
headers: {
...headers,
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: getIntrospectionQuery({
descriptions: true,
schemaDescription: false,
inputValueDeprecation: false,
directiveIsRepeatable: false,
specifiedByUrl: false,
}),
}),
});

if (response.ok) {
const text = await response.text();

try {
const result = JSON.parse(text);
if (result.data) {
introspection = (result as { data: IntrospectionQuery }).data;
} else {
console.error(`Got invalid response ${JSON.stringify(result)}`);
return;
}
} catch (e) {
console.error(`Got invalid JSON ${text}`);
return;
}
} else {
console.error(`Got invalid response ${await response.text()}`);
return;
}
} else {
const path = resolve(cwd, target);
const fileContents = await fs.readFile(path, 'utf-8');

try {
introspection = JSON.parse(fileContents);
} catch (e) {
console.error(`Got invalid JSON ${fileContents}`);
return;
}
schema = await loader.loadSchema();
} catch (error) {
console.error('Something went wrong while trying to load the schema.', error);
return;
}

const schema = buildClientSchema(introspection!);
if (!schema) {
console.error('Could not load the schema.');
return;
}

let destination = output;
if (!destination) {
const tsconfigpath = path.resolve(cwd, 'tsconfig.json');
const hasTsConfig = existsSync(tsconfigpath);
if (!hasTsConfig) {
console.error(`Could not find a tsconfig in the working-directory.`);
let tsconfigContents: string;
try {
tsconfigContents = await fs.readFile('tsconfig.json', 'utf-8');
} catch (error) {
console.error('Failed to read tsconfig.json in current working directory.', error);
return;
}

const tsconfigContents = await fs.readFile(tsconfigpath, 'utf-8');
let tsConfig: TsConfigJson;
try {
tsConfig = parse(tsconfigContents) as TsConfigJson;
Expand All @@ -97,39 +54,37 @@ export async function generateSchema(
return;
}

if (!hasGraphQLSP(tsConfig)) {
const config = getGraphQLSPConfig(tsConfig);
if (!config) {
console.error(`Could not find a "@0no-co/graphqlsp" plugin in your tsconfig.`);
return;
}

const foundPlugin = tsConfig.compilerOptions!.plugins!.find(
(plugin) => plugin.name === '@0no-co/graphqlsp'
) as GraphQLSPConfig;

destination = foundPlugin.schema;

if (!foundPlugin.schema.endsWith('.graphql')) {
console.error(`Found "${foundPlugin.schema}" which is not a path to a GraphQL Schema.`);
} else if (typeof config.schema !== 'string' || !config.schema.endsWith('.graphql')) {
console.error(`Found "${config.schema}" which is not a path to a .graphql SDL file.`);
return;
} else {
destination = config.schema;
}
}

await fs.writeFile(resolve(cwd, destination), printSchema(schema), 'utf-8');
// TODO: Should the output be relative to the relevant `tsconfig.json` file?
await fs.writeFile(path.resolve(cwd, destination), printSchema(schema), 'utf-8');
}

export async function generateTadaTypes(shouldPreprocess = false, cwd: string = process.cwd()) {
const tsconfigpath = path.resolve(cwd, 'tsconfig.json');
const hasTsConfig = existsSync(tsconfigpath);
if (!hasTsConfig) {
console.error('Missing tsconfig.json');

// TODO: Remove redundant read and move tsconfig.json handling to internal package
const root = (await resolveTypeScriptRootDir(tsconfigpath)) || cwd;

let tsconfigContents: string;
try {
const file = path.resolve(root, 'tsconfig.json');
tsconfigContents = await fs.readFile(file, 'utf-8');
} catch (error) {
console.error('Failed to read tsconfig.json in current working directory.', error);
return;
}

// TODO: Remove redundant read and move tsconfig.json handling to internal package
const root =
resolveTypeScriptRootDir(readFileSync as (path: string) => string | undefined, tsconfigpath) ||
cwd;
const tsconfigContents = await fs.readFile(path.resolve(root, 'tsconfig.json'), 'utf-8');
let tsConfig: TsConfigJson;
try {
tsConfig = parse(tsconfigContents) as TsConfigJson;
Expand All @@ -138,17 +93,15 @@ export async function generateTadaTypes(shouldPreprocess = false, cwd: string =
return;
}

if (!hasGraphQLSP(tsConfig)) {
const config = getGraphQLSPConfig(tsConfig);
if (!config) {
console.error(`Could not find a "@0no-co/graphqlsp" plugin in your tsconfig.`);
return;
}

const foundPlugin = tsConfig.compilerOptions!.plugins!.find(
(plugin) => plugin.name === '@0no-co/graphqlsp' || plugin.name === 'gql.tda/cli'
) as GraphQLSPConfig;

await ensureTadaIntrospection(
foundPlugin.schema,
foundPlugin.tadaOutputLocation!,
return await ensureTadaIntrospection(
config.schema,
config.tadaOutputLocation,
cwd,
shouldPreprocess
);
Expand Down Expand Up @@ -185,7 +138,7 @@ async function main() {
}

return generateSchema(target, {
headers: parsedHeaders,
headers: Object.keys(parsedHeaders).length ? parsedHeaders : undefined,
output: options.output,
});
})
Expand Down
67 changes: 37 additions & 30 deletions packages/cli-utils/src/lsp.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,48 @@
import type { TsConfigJson } from 'type-fest';

export type SchemaOrigin =
| string
| {
url: string;
headers: HeadersInit;
};

export type GraphQLSPConfig = {
name: string;
schema: string;
tadaOutputLocation?: string;
schema: SchemaOrigin;
tadaOutputLocation: string;
};

export function hasGraphQLSP(tsconfig: TsConfigJson): boolean {
if (!tsconfig.compilerOptions) {
console.warn('Missing compilerOptions object in tsconfig.json.');
return false;
}
export function getGraphQLSPConfig(tsconfig: TsConfigJson): GraphQLSPConfig | null {
if (tsconfig.compilerOptions) {
if (tsconfig.compilerOptions.plugins) {
const foundPlugin = tsconfig.compilerOptions.plugins.find(
(plugin) => plugin.name === '@0no-co/graphqlsp' || plugin.name === 'gql.tada/lsp'
) as GraphQLSPConfig | undefined;
if (!foundPlugin) {
console.error('Missing @0no-co/graphqlsp plugin in tsconfig.json.');
return null;
}

if (!tsconfig.compilerOptions.plugins) {
console.warn('Missing plugins array in tsconfig.json.');
return false;
}
if (!foundPlugin.schema) {
console.warn('Missing schema property in @0no-co/graphqlsp plugin in tsconfig.json.');
return null;
}

const foundPlugin = tsconfig.compilerOptions.plugins.find(
(plugin) => plugin.name === '@0no-co/graphqlsp' || plugin.name === 'gql.tada/lsp'
) as GraphQLSPConfig | undefined;
if (!foundPlugin) {
console.warn('Missing @0no-co/graphqlsp plugin in tsconfig.json.');
return false;
}
if (!foundPlugin.tadaOutputLocation) {
console.warn(
'Missing tadaOutputLocation property in @0no-co/graphqlsp plugin in tsconfig.json.'
);
return null;
}

if (!foundPlugin.schema) {
console.warn('Missing schema property in @0no-co/graphqlsp plugin in tsconfig.json.');
return false;
}

if (!foundPlugin.tadaOutputLocation) {
console.warn(
'Missing tadaOutputLocation property in @0no-co/graphqlsp plugin in tsconfig.json.'
);
return false;
return foundPlugin;
} else {
console.warn('Missing plugins array in tsconfig.json.');
return null;
}
} else {
console.warn('Missing compilerOptions object in tsconfig.json.');
return null;
}

return true;
}
Loading
Loading