Skip to content

Commit

Permalink
move cosmiconfig-typescript-loader in peerDependencyMeta (#1171)
Browse files Browse the repository at this point in the history
* should be good

add cosmiconfig-typescript-loader to devdeps

fix

set node 14 in ci, clean eslint errors

* add friendly error

* clean peerDeps

* simplify

* Update .changeset/four-frogs-flash.md

* just spread args
  • Loading branch information
dimaMachina committed Dec 23, 2022
1 parent d01b878 commit b52dc1b
Show file tree
Hide file tree
Showing 11 changed files with 118 additions and 92 deletions.
5 changes: 5 additions & 0 deletions .changeset/four-frogs-flash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'graphql-config': minor
---

move `cosmiconfig-typescript-loader` in `peerDependencyMeta`
11 changes: 9 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"prepublishOnly": "yarn build",
"clean": "rimraf dist",
"prebuild": "yarn clean && yarn json-schema",
"postbuild": "tsx scripts/postbuild.ts",
"build": "bob build",
"prettier": "prettier --cache --write --list-different .",
"prettier:check": "prettier --cache --check .",
Expand All @@ -47,8 +48,14 @@
"json-schema": "typescript-json-schema src/types.ts IGraphQLConfig --out config-schema.json --ignoreErrors --required --titles && prettier --write config-schema.json"
},
"peerDependencies": {
"cosmiconfig-typescript-loader": "^4.0.0",
"graphql": "^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0"
},
"peerDependenciesMeta": {
"cosmiconfig-typescript-loader": {
"optional": true
}
},
"dependencies": {
"@graphql-tools/graphql-file-loader": "^7.3.7",
"@graphql-tools/json-file-loader": "^7.3.7",
Expand All @@ -58,10 +65,8 @@
"@graphql-tools/utils": "^8.6.5",
"cosmiconfig": "7.0.1",
"cosmiconfig-toml-loader": "1.0.0",
"cosmiconfig-typescript-loader": "^4.0.0",
"minimatch": "4.2.1",
"string-env-interpolation": "1.0.1",
"ts-node": "^10.8.1",
"tslib": "^2.4.0"
},
"devDependencies": {
Expand All @@ -71,6 +76,7 @@
"@typescript-eslint/eslint-plugin": "5.47.0",
"@typescript-eslint/parser": "5.47.0",
"bob-the-bundler": "4.2.0-alpha-20221222140753-fcf5286",
"cosmiconfig-typescript-loader": "4.3.0",
"del": "6.1.1",
"eslint": "8.25.0",
"eslint-config-prettier": "8.5.0",
Expand All @@ -81,6 +87,7 @@
"parent-module": "2.0.0",
"prettier": "2.7.1",
"rimraf": "3.0.2",
"ts-node": "10.9.1",
"tsx": "3.12.1",
"typescript": "4.8.4",
"typescript-json-schema": "0.54.0",
Expand Down
17 changes: 17 additions & 0 deletions scripts/postbuild.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/* eslint-disable no-console */
import { writeFile, readFile } from 'node:fs/promises';
import path from 'node:path';

const filePath = path.resolve(process.cwd(), 'dist/esm/helpers/cosmiconfig.js');

console.time('done');
const content = await readFile(filePath, 'utf8');

await writeFile(
filePath,
`
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
${content}`.trimStart(),
);
console.timeEnd('done');
28 changes: 6 additions & 22 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { GraphQLExtensionDeclaration, GraphQLExtensionsRegistry } from './extens
import { EndpointsExtension } from './extensions/endpoints.js';
import { isLegacyConfig } from './helpers/cosmiconfig.js';

const cwd = typeof process !== 'undefined' ? process.cwd() : undefined;
const CWD = process.cwd();
const defaultConfigName = 'graphql';

interface LoadConfigOptions {
Expand All @@ -29,7 +29,7 @@ interface LoadConfigOptions {
}

const defaultLoadConfigOptions: LoadConfigOptions = {
rootDir: cwd,
rootDir: CWD,
extensions: [],
throwOnMissing: true,
throwOnEmpty: true,
Expand All @@ -45,16 +45,8 @@ export async function loadConfig(options: LoadConfigOptions): Promise<GraphQLCon

try {
const found = filepath
? await getConfig({
filepath,
configName,
legacy,
})
: await findConfig({
rootDir,
configName,
legacy,
});
? await getConfig({ filepath, configName, legacy })
: await findConfig({ rootDir, configName, legacy });

return new GraphQLConfig(found, extensions);
} catch (error) {
Expand All @@ -70,16 +62,8 @@ export function loadConfigSync(options: LoadConfigOptions) {

try {
const found = filepath
? getConfigSync({
filepath,
configName,
legacy,
})
: findConfigSync({
rootDir,
configName,
legacy,
});
? getConfigSync({ filepath, configName, legacy })
: findConfigSync({ rootDir, configName, legacy });

return new GraphQLConfig(found, extensions);
} catch (error) {
Expand Down
6 changes: 6 additions & 0 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,41 +20,47 @@ export class ConfigNotFoundError extends ExtendableBuiltin(Error) {
this.message = message;
}
}

export class ConfigEmptyError extends ExtendableBuiltin(Error) {
constructor(message: string) {
super(message);
this.name = this.constructor.name;
this.message = message;
}
}
// TODO: remove in v5
export class ConfigInvalidError extends ExtendableBuiltin(Error) {
constructor(message: string) {
super(message);
this.name = this.constructor.name;
this.message = message;
}
}

export class ProjectNotFoundError extends ExtendableBuiltin(Error) {
constructor(message: string) {
super(message);
this.name = this.constructor.name;
this.message = message;
}
}
// TODO: remove in v5
export class LoadersMissingError extends ExtendableBuiltin(Error) {
constructor(message: string) {
super(message);
this.name = this.constructor.name;
this.message = message;
}
}
// TODO: remove in v5
export class LoaderNoResultError extends ExtendableBuiltin(Error) {
constructor(message: string) {
super(message);
this.name = this.constructor.name;
this.message = message;
}
}

export class ExtensionMissingError extends ExtendableBuiltin(Error) {
constructor(message: string) {
super(message);
Expand Down
57 changes: 27 additions & 30 deletions src/helpers/cosmiconfig.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { cosmiconfig, cosmiconfigSync, Loader, defaultLoaders } from 'cosmiconfig';
import { TypeScriptLoader } from 'cosmiconfig-typescript-loader';
import { loadToml } from 'cosmiconfig-toml-loader';
import { env } from 'string-env-interpolation';

Expand All @@ -9,49 +8,47 @@ export interface ConfigSearchResult {
isEmpty?: boolean;
}

const legacySearchPlaces = ['.graphqlconfig', '.graphqlconfig.json', '.graphqlconfig.yaml', '.graphqlconfig.yml'];
const legacySearchPlaces = [
'.graphqlconfig',
'.graphqlconfig.json',
'.graphqlconfig.yaml',
'.graphqlconfig.yml',
] as const;

export function isLegacyConfig(filepath: string): boolean {
filepath = filepath.toLowerCase();

return legacySearchPlaces.some((name) => filepath.endsWith(name));
export function isLegacyConfig(filePath: string): boolean {
filePath = filePath.toLowerCase();
return legacySearchPlaces.some((name) => filePath.endsWith(name));
}

function transformContent(content: string): string {
return env(content);
}

const createCustomLoader = (loader: Loader): Loader => {
return (filepath, content) => {
return loader(filepath, transformContent(content));
};
};
function createCustomLoader(loader: Loader): Loader {
return (filePath, content) => loader(filePath, transformContent(content));
}

export function createCosmiConfig(
moduleName: string,
{
legacy,
}: {
legacy: boolean;
},
) {
const options = prepareCosmiconfig(moduleName, {
legacy,
});
export function createCosmiConfig(moduleName: string, legacy: boolean) {
const options = prepareCosmiconfig(moduleName, legacy);

return cosmiconfig(moduleName, options);
}

export function createCosmiConfigSync(moduleName: string, { legacy }: { legacy: boolean }) {
const options = prepareCosmiconfig(moduleName, { legacy });
export function createCosmiConfigSync(moduleName: string, legacy: boolean) {
const options = prepareCosmiconfig(moduleName, legacy);

return cosmiconfigSync(moduleName, options);
}

function prepareCosmiconfig(moduleName: string, { legacy }: { legacy: boolean }) {
const loadTypeScript: Loader = (...args) => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { TypeScriptLoader } = require('cosmiconfig-typescript-loader');

return TypeScriptLoader({ transpileOnly: true })(...args);
};

function prepareCosmiconfig(moduleName: string, legacy: boolean) {
const loadYaml = createCustomLoader(defaultLoaders['.yaml']);
const loadTomlCustom = createCustomLoader(loadToml);
const loadJson = createCustomLoader(defaultLoaders['.json']);

const searchPlaces = [
'#.config.ts',
Expand Down Expand Up @@ -81,12 +78,12 @@ function prepareCosmiconfig(moduleName: string, { legacy }: { legacy: boolean })
return {
searchPlaces: searchPlaces.map((place) => place.replace('#', moduleName)),
loaders: {
'.ts': TypeScriptLoader({ transpileOnly: true }),
'.ts': loadTypeScript,
'.js': defaultLoaders['.js'],
'.json': loadJson,
'.json': createCustomLoader(defaultLoaders['.json']),
'.yaml': loadYaml,
'.yml': loadYaml,
'.toml': loadTomlCustom,
'.toml': createCustomLoader(loadToml),
noExt: loadYaml,
},
};
Expand Down
38 changes: 15 additions & 23 deletions src/helpers/find-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,45 +2,37 @@ import { ConfigNotFoundError, ConfigEmptyError, composeMessage } from '../errors
import { GraphQLConfigResult } from '../types.js';
import { createCosmiConfig, createCosmiConfigSync, ConfigSearchResult } from './cosmiconfig.js';

const cwd = typeof process !== 'undefined' ? process.cwd() : undefined;
const CWD = process.cwd();

export async function findConfig({
rootDir = cwd,
legacy = true,
configName,
}: {
type FindConfigOptions = {
rootDir: string;
configName: string;
legacy?: boolean;
}): Promise<GraphQLConfigResult> {
validate({ rootDir });
};

export async function findConfig({
rootDir = CWD,
legacy = true,
configName,
}: FindConfigOptions): Promise<GraphQLConfigResult> {
validate(rootDir);

return resolve({
rootDir,
result: await createCosmiConfig(configName, { legacy }).search(rootDir),
result: await createCosmiConfig(configName, legacy).search(rootDir),
});
}

export function findConfigSync({
rootDir = cwd,
legacy = true,
configName,
}: {
rootDir: string;
configName: string;
legacy?: boolean;
}): GraphQLConfigResult {
validate({ rootDir });
export function findConfigSync({ rootDir = CWD, legacy = true, configName }: FindConfigOptions): GraphQLConfigResult {
validate(rootDir);

return resolve({
rootDir,
result: createCosmiConfigSync(configName, { legacy }).search(rootDir),
result: createCosmiConfigSync(configName, legacy).search(rootDir),
});
}

//

function validate({ rootDir }: { rootDir: string }) {
function validate(rootDir: string): void {
if (!rootDir) {
throw new Error(`Defining a root directory is required`);
}
Expand Down
10 changes: 5 additions & 5 deletions src/helpers/get-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ export async function getConfig({
configName: string;
legacy?: boolean;
}): Promise<GraphQLConfigResult> {
validate({ filepath });
validate(filepath);

return resolve({
result: await createCosmiConfig(configName, { legacy }).load(filepath),
result: await createCosmiConfig(configName, legacy).load(filepath),
filepath,
});
}
Expand All @@ -28,10 +28,10 @@ export function getConfigSync({
configName: string;
legacy?: boolean;
}): GraphQLConfigResult {
validate({ filepath });
validate(filepath);

return resolve({
result: createCosmiConfigSync(configName, { legacy }).load(filepath),
result: createCosmiConfigSync(configName, legacy).load(filepath),
filepath,
});
}
Expand All @@ -55,7 +55,7 @@ function resolve({ result, filepath }: { result?: ConfigSearchResult; filepath:
};
}

function validate({ filepath }: { filepath?: string }) {
function validate(filepath: string): void {
if (!filepath) {
throw new Error(`Defining a file path is required`);
}
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export { Source, Loader } from '@graphql-tools/utils';
export { GraphQLConfig, loadConfig, loadConfigSync } from './config.js';
export { GraphQLProjectConfig } from './project-config.js';
export { GraphQLExtensionDeclaration } from './extension.js';
export { Source, Loader } from '@graphql-tools/utils';
export * from './types.js';
export * from './errors.js';
export { LoadersRegistry } from './loaders.js';
7 changes: 3 additions & 4 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
{
"compilerOptions": {
"jsx": "react",
"module": "esnext",
"target": "es2018",
"lib": ["es2017", "dom", "esnext.asynciterable"],
"lib": ["es2018"],
"outDir": "dist",
"declaration": true,
"declarationMap": true,
Expand All @@ -17,6 +16,6 @@
"graphql-config": ["./src/index.ts"]
}
},
"exclude": ["node_modules", "dist", "website"],
"include": ["src", "website/src/components"]
"exclude": [],
"include": ["src"]
}

0 comments on commit b52dc1b

Please sign in to comment.