Skip to content

Use no-op for production instanceOf #4426

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

Open
wants to merge 3 commits into
base: next
Choose a base branch
from
Open
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
34 changes: 34 additions & 0 deletions src/__tests__/env-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { expect } from 'chai';
import { describe, it } from 'mocha';

const { getEnv: defaultGetEnv } = await import(`../env.js?ts${Date.now()}`);
const { getEnv: developmentGetEnv, setEnv: developmentSetEnv } = await import(
`../env.js?ts${Date.now()}`
);
const { getEnv: productionGetEnv, setEnv: productionSetEnv } = await import(
`../env.js?ts${Date.now()}`
);
const { setEnv: repetitiveSetEnv } = await import(`../env.js?ts${Date.now()}`);

describe('Env', () => {
it('should return undefined if environment is not set', () => {
expect(defaultGetEnv()).to.equal(undefined);
});

it('should set the environment to development', () => {
developmentSetEnv('development');
expect(developmentGetEnv()).to.equal('development');
});

it('should set the environment to production', () => {
productionSetEnv('production');
expect(productionGetEnv()).to.equal('production');
});

it('should throw if environment already set', () => {
repetitiveSetEnv('development');
expect(() => repetitiveSetEnv('production')).to.throw(
'Environment already set to "development", cannot be changed to "production".',
);
});
});
21 changes: 21 additions & 0 deletions src/env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useDevelopmentInstanceOfCheck } from './jsutils/instanceOf.js';

export type Env = 'production' | 'development';

let env: Env | undefined;

export function setEnv(newEnv: Env): void {
if (env !== undefined && env !== newEnv) {
throw new Error(
`Environment already set to "${env}", cannot be changed to "${newEnv}".`,
);
}
env = newEnv;
if (env === 'development') {
useDevelopmentInstanceOfCheck();
}
}

export function getEnv(): Env | undefined {
return env;
}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@

// The GraphQL.js version info.
export { version, versionInfo } from './version.js';
export { setEnv, getEnv } from './env.js';
export type { Env } from './env.js';

// The primary entry point into fulfilling a GraphQL request.
export type { GraphQLArgs } from './graphql.js';
Expand Down
36 changes: 34 additions & 2 deletions src/jsutils/__tests__/instanceOf-test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
import { expect } from 'chai';
import { describe, it } from 'mocha';
import { before, describe, it } from 'mocha';

import { setEnv } from '../../env.js';

import { instanceOf } from '../instanceOf.js';

// will pick up non-development version of instanceOf by default
const { instanceOf: defaultInstanceOf } = await import(
`../instanceOf.js?ts${Date.now()}`
);

describe('instanceOf', () => {
before(() => {
setEnv('development');
});

it('do not throw on values without prototype', () => {
class Foo {
get [Symbol.toStringTag]() {
Expand All @@ -16,7 +27,7 @@ describe('instanceOf', () => {
expect(instanceOf(Object.create(null), Foo)).to.equal(false);
});

it('detect name clashes with older versions of this lib', () => {
it('detect name clashes with older versions of this lib when set', () => {
function oldVersion() {
class Foo {}
return Foo;
Expand All @@ -37,6 +48,27 @@ describe('instanceOf', () => {
expect(() => instanceOf(new OldClass(), NewClass)).to.throw();
});

it('ignore name clashes with older versions of this lib by default', () => {
function oldVersion() {
class Foo {}
return Foo;
}

function newVersion() {
class Foo {
get [Symbol.toStringTag]() {
return 'Foo';
}
}
return Foo;
}

const NewClass = newVersion();
const OldClass = oldVersion();
expect(defaultInstanceOf(new NewClass(), NewClass)).to.equal(true);
expect(defaultInstanceOf(new OldClass(), NewClass)).to.equal(false);
});

it('allows instances to have share the same constructor name', () => {
function getMinifiedClass(tag: string) {
class SomeNameAfterMinification {
Expand Down
70 changes: 37 additions & 33 deletions src/jsutils/instanceOf.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,45 @@
import { inspect } from './inspect.js';

/* c8 ignore next 3 */
const isProduction =
globalThis.process != null &&
// eslint-disable-next-line no-undef
process.env.NODE_ENV === 'production';
const noOp = (_value: unknown, _constructor: Constructor): void => {
/* no-op */
};

let check = noOp;

export function useDevelopmentInstanceOfCheck(): void {
check = developmentInstanceOfCheck;
}

/**
* A replacement for instanceof which includes an error warning when multi-realm
* constructors are detected.
* See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production
* See: https://webpack.js.org/guides/production/
*/
export const instanceOf: (value: unknown, constructor: Constructor) => boolean =
/* c8 ignore next 6 */
// FIXME: https://github.com/graphql/graphql-js/issues/2317
isProduction
? function instanceOf(value: unknown, constructor: Constructor): boolean {
return value instanceof constructor;
}
: function instanceOf(value: unknown, constructor: Constructor): boolean {
if (value instanceof constructor) {
return true;
}
if (typeof value === 'object' && value !== null) {
// Prefer Symbol.toStringTag since it is immune to minification.
const className = constructor.prototype[Symbol.toStringTag];
const valueClassName =
// We still need to support constructor's name to detect conflicts with older versions of this library.
Symbol.toStringTag in value
? value[Symbol.toStringTag]
: value.constructor?.name;
if (className === valueClassName) {
const stringifiedValue = inspect(value);
throw new Error(
`Cannot use ${className} "${stringifiedValue}" from another module or realm.
export function instanceOf(value: unknown, constructor: Constructor): boolean {
if (value instanceof constructor) {
return true;
}
check(value, constructor);
return false;
}

function developmentInstanceOfCheck(
value: unknown,
constructor: Constructor,
): void {
if (typeof value === 'object' && value !== null) {
// Prefer Symbol.toStringTag since it is immune to minification.
const className = constructor.prototype[Symbol.toStringTag];
const valueClassName =
// We still need to support constructor's name to detect conflicts with older versions of this library.
Symbol.toStringTag in value
? value[Symbol.toStringTag]
: value.constructor?.name;
if (className === valueClassName) {
const stringifiedValue = inspect(value);
throw new Error(
`Cannot use ${className} "${stringifiedValue}" from another module or realm.

Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
Expand All @@ -46,11 +51,10 @@ Duplicate "graphql" modules cannot be used at the same time since different
versions may have different capabilities and behavior. The data from one
version used in the function from another could produce confusing and
spurious results.`,
);
}
}
return false;
};
);
}
}
}

interface Constructor {
prototype: {
Expand Down
Loading