Skip to content

Commit

Permalink
feat: add a CLI capable of generating the base gql.tada files (#58)
Browse files Browse the repository at this point in the history
Co-authored-by: Phil Pluckthun <phil@kitten.sh>
  • Loading branch information
JoviDeCroock and kitten authored Feb 21, 2024
1 parent 5f06be0 commit 11e1aae
Show file tree
Hide file tree
Showing 16 changed files with 382 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/blue-boats-dance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'gql.tada': minor
---

Add CLI entrypoint `gql-tada` capable of generating the types file without the LSP running
5 changes: 5 additions & 0 deletions .changeset/nice-worms-deny.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@gql.tada/cli': minor
---

Add `tada` CLI capable of generating the introspection types file
6 changes: 3 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ jobs:
run: pnpm run lint

- name: Unit Tests
run: pnpm run test --run
run: pnpm multi --include-workspace-root run test --run

- name: benchmarks
run: pnpm run bench --run
run: pnpm multi --include-workspace-root run bench --run

- name: Build
run: pnpm run build
run: pnpm multi --include-workspace-root run build
2 changes: 1 addition & 1 deletion .github/workflows/site.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ jobs:

- name: Build Website
working-directory: website
run: pnpm run build
run: pnpm run export

- name: Deploy to Cloudflare Pages
uses: cloudflare/pages-action@v1
Expand Down
17 changes: 17 additions & 0 deletions cli/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "gql-tada-cli",
"private": true,
"version": "0.0.0",
"main": "../dist/gql-tada-cli.js",
"module": "../dist/gql-tada-cli.mjs",
"types": "../dist/gql-tada-cli.d.ts",
"source": "../src/cli/index.ts",
"exports": {
".": {
"types": "../dist/gql-tada-cli.d.ts",
"import": "../dist/gql-tada-cli.mjs",
"require": "../dist/gql-tada-cli.js",
"source": "../src/cli/index.ts"
}
}
}
13 changes: 12 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
"module": "./dist/gql-tada.mjs",
"types": "./dist/gql-tada.d.ts",
"sideEffects": false,
"bin": {
"gql.tada": "./dist/gql-tada-cli.js",
"gql-tada": "./dist/gql-tada-cli.js"
},
"files": [
"LICENSE.md",
"README.md",
Expand All @@ -20,10 +24,17 @@
"require": "./dist/gql-tada.js",
"source": "./src/index.ts"
},
"./cli": {
"types": "./dist/gql-tada-cli.d.ts",
"import": "./dist/gql-tada-cli.mjs",
"require": "./dist/gql-tada-cli.js",
"source": "./src/cli/index.ts"
},
"./package.json": "./package.json"
},
"dependencies": {
"@0no-co/graphql.web": "^1.0.4"
"@0no-co/graphql.web": "^1.0.4",
"@gql.tada/cli-utils": "workspace:*"
},
"public": true,
"keywords": [
Expand Down
21 changes: 21 additions & 0 deletions packages/cli-utils/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 0no.co

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Empty file added packages/cli-utils/README.md
Empty file.
42 changes: 42 additions & 0 deletions packages/cli-utils/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"name": "@gql.tada/cli-utils",
"version": "0.0.0",
"description": "Main logic for gql.tada’s CLI tool.",
"author": "0no.co <hi@0no.co>",
"sideEffects": false,
"source": "./src/index.ts",
"exports": {
".": {
"types": "./dist/gql-tada-cli.d.ts",
"import": "./dist/gql-tada-cli.mjs",
"require": "./dist/gql-tada-cli.js",
"source": "./src/index.ts"
},
"./package.json": "./package.json"
},
"files": [
"CHANGELOG.md",
"LICENSE.md",
"README.md",
"dist/"
],
"license": "MIT",
"scripts": {
"build": "rollup -c ../../scripts/rollup.config.mjs"
},
"devDependencies": {
"@types/node": "^20.11.0",
"comment-json": "^4.2.3",
"rollup": "^4.9.4",
"sade": "^1.8.1",
"type-fest": "^4.10.2",
"typescript": "^5.3.3"
},
"dependencies": {
"@urql/introspection": "^1.0.3"
},
"publishConfig": {
"access": "public",
"provenance": true
}
}
88 changes: 88 additions & 0 deletions packages/cli-utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import sade from 'sade';
import { promises as fs, existsSync } from 'node:fs';
import path from 'node:path';
// We use comment-json to parse the tsconfig as the default ones
// have comment annotations in JSON.
import { parse } from 'comment-json';
import type { TsConfigJson } from 'type-fest';
import { ensureTadaIntrospection } from './tada';

const prog = sade('fuse');

prog.version(process.env.npm_package_version || '0.0.0');

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

function hasGraphQLSP(tsconfig: TsConfigJson): boolean {
if (!tsconfig.compilerOptions) {
// Warn
return false;
}

if (!tsconfig.compilerOptions.plugins) {
// Warn
return false;
}

const foundPlugin = tsconfig.compilerOptions.plugins.find(
(plugin) => plugin.name === '@0no-co/graphqlsp'
) as GraphQLSPConfig | undefined;
if (!foundPlugin) {
// Warn
return false;
}

if (!foundPlugin.schema) {
// Warn
return false;
}

if (!foundPlugin.tadaOutputLocation) {
// Warn
return false;
}

return true;
}

async function main() {
prog
.command('generate')
.describe(
'Generate the gql.tada types file, this will look for your "tsconfig.json" and use the "@0no-co/graphqlsp" configuration to generate the file.'
)
.action(async () => {
const cwd = process.cwd();
const tsconfigpath = path.resolve(cwd, 'tsconfig.json');
const hasTsConfig = existsSync(tsconfigpath);
if (!hasTsConfig) {
// Error
}

const tsconfigContents = await fs.readFile(tsconfigpath, 'utf-8');
let tsConfig: TsConfigJson;
try {
tsConfig = parse(tsconfigContents) as TsConfigJson;
} catch (err) {
// report error and bail
return;
}

if (!hasGraphQLSP(tsConfig)) {
// Error
}

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

await ensureTadaIntrospection(foundPlugin.schema, false);
// Generate the file
});
}

export default main;
92 changes: 92 additions & 0 deletions packages/cli-utils/src/tada.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { promises as fs, watch, existsSync } from 'node:fs';
import path from 'node:path';
import { buildSchema, introspectionFromSchema } from 'graphql';
import { minifyIntrospectionQuery } from '@urql/introspection';

export const tadaGqlContents = `import { initGraphQLTada } from 'gql.tada';
import type { introspection } from './introspection';
export const graphql = initGraphQLTada<{
introspection: typeof introspection;
}>();
export type { FragmentOf, ResultOf, VariablesOf } from 'gql.tada';
export type { FragmentOf as FragmentType } from 'gql.tada';
export { readFragment } from 'gql.tada';
export { readFragment as useFragment } from 'gql.tada';
`;

/**
* This function mimics the behavior of the LSP, this so we can ensure
* that gql.tada will work in any environment. The JetBrains IDE's do not
* implement the tsserver plugin protocol hence in those and editors where
* we are not able to leverage the workspace TS version we will rely on
* this function.
*/
export async function ensureTadaIntrospection(location: string, shouldWatch: boolean) {
const schemaLocation = path.resolve(location, 'schema.graphql');

const writeTada = async () => {
try {
const content = await fs.readFile(schemaLocation, 'utf-8');
const schema = buildSchema(content);
const introspection = introspectionFromSchema(schema, {
descriptions: false,
});
const minified = minifyIntrospectionQuery(introspection, {
includeDirectives: false,
includeEnums: true,
includeInputs: true,
includeScalars: true,
});

const json = JSON.stringify(minified, null, 2);
const hasSrcDir = existsSync(path.resolve(location, 'src'));
const base = hasSrcDir ? path.resolve(location, 'src') : location;

const outputLocation = path.resolve(base, 'fuse', 'introspection.ts');
const contents = [
preambleComments,
tsAnnotationComment,
`const introspection = ${json} as const;\n`,
'export { introspection };',
].join('\n');

await fs.writeFile(outputLocation, contents);
} catch (e) {}
};

await writeTada();

if (shouldWatch) {
watch(schemaLocation, async () => {
await writeTada();
});
}
}

const preambleComments = ['/* eslint-disable */', '/* prettier-ignore */'].join('\n') + '\n';

const tsAnnotationComment = [
'/** An IntrospectionQuery representation of your schema.',
' *',
' * @remarks',
' * This is an introspection of your schema saved as a file by GraphQLSP.',
' * You may import it to create a `graphql()` tag function with `gql.tada`',
' * by importing it and passing it to `initGraphQLTada<>()`.',
' *',
' * @example',
' * ```',
" * import { initGraphQLTada } from 'gql.tada';",
" * import type { introspection } from './introspection';",
' *',
' * export const graphql = initGraphQLTada<{',
' * introspection: typeof introspection;',
' * scalars: {',
' * DateTime: string;',
' * Json: any;',
' * };',
' * }>();',
' * ```',
' */',
].join('\n');
4 changes: 4 additions & 0 deletions packages/cli-utils/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.json",
"include": ["src"]
}
Loading

0 comments on commit 11e1aae

Please sign in to comment.