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

[@graphiql/toolkit] do not include require statements in ESM build, include import in esm and require in cjs builds #3747

Merged
merged 3 commits into from
Aug 23, 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
7 changes: 7 additions & 0 deletions .changeset/gold-ears-knock.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@graphiql/toolkit': minor
---

do not include `require` statements in ESM build, include `import` in esm and `require` in cjs builds

make `getWsFetcher`, `createWebsocketsFetcherFromUrl` async
26 changes: 14 additions & 12 deletions packages/graphiql-toolkit/src/create-fetcher/__tests__/lib.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { createClient } from 'graphql-ws';

import { SubscriptionClient } from 'subscriptions-transport-ws';

const exampleWithSubscription = /* GraphQL */ parse(`
const exampleWithSubscription = parse(/* GraphQL */ `
subscription Example {
example
}
Expand Down Expand Up @@ -47,9 +47,9 @@ describe('createWebsocketsFetcherFromUrl', () => {
jest.resetAllMocks();
});

it('creates a websockets client using provided url', () => {
it('creates a websockets client using provided url', async () => {
createClient.mockReturnValue(true);
createWebsocketsFetcherFromUrl('wss://example.com');
await createWebsocketsFetcherFromUrl('wss://example.com');
// @ts-ignore
expect(createClient.mock.calls[0][0]).toEqual({ url: 'wss://example.com' });
});
Expand All @@ -66,39 +66,41 @@ describe('getWsFetcher', () => {
afterEach(() => {
jest.resetAllMocks();
});
it('provides an observable wsClient when custom wsClient option is provided', () => {
it('provides an observable wsClient when custom wsClient option is provided', async () => {
createClient.mockReturnValue(true);
getWsFetcher({ url: '', wsClient: true });
await getWsFetcher({ url: '', wsClient: true });
// @ts-ignore
expect(createClient.mock.calls).toHaveLength(0);
});
it('creates a subscriptions-transports-ws observable when custom legacyClient option is provided', () => {
it('creates a subscriptions-transports-ws observable when custom legacyClient option is provided', async () => {
createClient.mockReturnValue(true);
getWsFetcher({ url: '', legacyClient: true });
await getWsFetcher({ url: '', legacyClient: true });
// @ts-ignore
expect(createClient.mock.calls).toHaveLength(0);
expect(SubscriptionClient.mock.calls).toHaveLength(0);
});

it('if subscriptionsUrl is provided, create a client on the fly', () => {
it('if subscriptionsUrl is provided, create a client on the fly', async () => {
createClient.mockReturnValue(true);
getWsFetcher({ url: '', subscriptionUrl: 'wss://example' });
await getWsFetcher({ url: '', subscriptionUrl: 'wss://example' });
expect(createClient.mock.calls[0]).toEqual([
{ connectionParams: {}, url: 'wss://example' },
]);
expect(SubscriptionClient.mock.calls).toHaveLength(0);
});
});

describe('missing graphql-ws dependency', () => {
it('should throw a nice error', () => {
describe('missing `graphql-ws` dependency', () => {
it('should throw a nice error', async () => {
jest.resetModules();
jest.doMock('graphql-ws', () => {
// eslint-disable-next-line no-throw-literal
throw { code: 'MODULE_NOT_FOUND' };
});

expect(() => createWebsocketsFetcherFromUrl('wss://example.com')).toThrow(
await expect(
createWebsocketsFetcherFromUrl('wss://example.com'),
).rejects.toThrow(
/You need to install the 'graphql-ws' package to use websockets when passing a 'subscriptionUrl'/,
);
});
Expand Down
4 changes: 2 additions & 2 deletions packages/graphiql-toolkit/src/create-fetcher/createFetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
? createMultipartFetcher(options, httpFetch)
: simpleFetcher;

return (graphQLParams, fetcherOpts) => {
return async (graphQLParams, fetcherOpts) => {
if (graphQLParams.operationName === 'IntrospectionQuery') {
return (options.schemaFetcher || simpleFetcher)(
graphQLParams,
Expand All @@ -41,7 +41,7 @@
)
: false;
if (isSubscription) {
const wsFetcher = getWsFetcher(options, fetcherOpts);
const wsFetcher = await getWsFetcher(options, fetcherOpts);

Check warning on line 44 in packages/graphiql-toolkit/src/create-fetcher/createFetcher.ts

View check run for this annotation

Codecov / codecov/patch

packages/graphiql-toolkit/src/create-fetcher/createFetcher.ts#L44

Added line #L44 was not covered by tests

if (!wsFetcher) {
throw new Error(
Expand Down
19 changes: 10 additions & 9 deletions packages/graphiql-toolkit/src/create-fetcher/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,16 @@
return data.json();
};

export const createWebsocketsFetcherFromUrl = (
export async function createWebsocketsFetcherFromUrl(
url: string,
connectionParams?: ClientOptions['connectionParams'],
) => {
): Promise<Fetcher | void> {
let wsClient;
try {
const { createClient } = require('graphql-ws') as {
createClient: typeof createClientType;
};
const { createClient } =
process.env.USE_IMPORT === 'false'
? (require('graphql-ws') as { createClient: typeof createClientType })

Check warning on line 79 in packages/graphiql-toolkit/src/create-fetcher/lib.ts

View check run for this annotation

Codecov / codecov/patch

packages/graphiql-toolkit/src/create-fetcher/lib.ts#L79

Added line #L79 was not covered by tests
: await import('graphql-ws');

// TODO: defaults?
wsClient = createClient({ url, connectionParams });
Expand All @@ -90,7 +91,7 @@
// eslint-disable-next-line no-console
console.error(`Error creating websocket client for ${url}`, err);
}
};
}

/**
* Create ws/s fetcher using provided wsClient implementation
Expand Down Expand Up @@ -177,10 +178,10 @@
/**
* If `wsClient` or `legacyClient` are provided, then `subscriptionUrl` is overridden.
*/
export const getWsFetcher = (
export async function getWsFetcher(
options: CreateFetcherOptions,
fetcherOpts?: FetcherOpts,
): Fetcher | void => {
): Promise<Fetcher | void> {
if (options.wsClient) {
return createWebsocketsFetcherFromClient(options.wsClient);
}
Expand All @@ -194,4 +195,4 @@
if (legacyWebsocketsClient) {
return createLegacyWebsocketsFetcher(legacyWebsocketsClient);
}
};
}
2 changes: 1 addition & 1 deletion packages/graphiql-toolkit/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"compilerOptions": {
"target": "es2016",
"target": "es2017",
"module": "ESNext",
"declaration": true,
"noEmit": true,
Expand Down
7 changes: 7 additions & 0 deletions packages/graphiql-toolkit/tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const opts: Options = {
bundle: false,
clean: true,
dts: true,
minifySyntax: true,
};

export default defineConfig([
Expand All @@ -13,10 +14,16 @@ export default defineConfig([
format: 'esm',
outDir: 'dist/esm',
outExtension: () => ({ js: '.js' }),
env: {
USE_IMPORT: 'true',
},
},
{
...opts,
format: 'cjs',
outDir: 'dist/cjs',
env: {
USE_IMPORT: 'false',
},
},
]);
2 changes: 1 addition & 1 deletion packages/monaco-graphql/test/monaco-editor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ describe('monaco-editor', () => {
// expect(lines[1]).toMatch(' building for production...');
// expect(lines[2]).toBe('transforming...');
expect(lines[3]).toMatch(
`✓ ${parseInt(version, 10) > 16 ? 857 : 843} modules transformed.`,
`✓ ${parseInt(version, 10) > 16 ? 862 : 843} modules transformed.`,
);
// expect(lines[4]).toBe('rendering chunks...');
// expect(lines[5]).toBe('computing gzip size...');
Expand Down
Loading