From 192ce541762f0b02533ac16b4bd96bc204407a68 Mon Sep 17 00:00:00 2001 From: Ed Sungik Choi Date: Fri, 8 Sep 2023 11:43:42 +0900 Subject: [PATCH 1/3] feat(utils): add assert utils --- .../bezier-react/src/utils/assertUtils.ts | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 packages/bezier-react/src/utils/assertUtils.ts diff --git a/packages/bezier-react/src/utils/assertUtils.ts b/packages/bezier-react/src/utils/assertUtils.ts new file mode 100644 index 0000000000..e3ab109250 --- /dev/null +++ b/packages/bezier-react/src/utils/assertUtils.ts @@ -0,0 +1,32 @@ +export function isDev() { + return process.env.NODE_ENV !== 'production' +} + +export function warn(message: string) { + if (isDev()) { + // eslint-disable-next-line no-console + console.warn(message) + } +} + +class AssertionException extends Error { + constructor(message?: string) { + super() + + this.name = 'AssertionException' + this.message = message ?? 'assertion failed' + } +} + +export function assert( + predicate: boolean, + message?: string, +): asserts predicate { + if (predicate) { + return + } + + if (isDev()) { + throw new AssertionException(message) + } +} From 0a3bfc48c10b860c8bf74fb0a348ba8c1ee402af Mon Sep 17 00:00:00 2001 From: Ed Sungik Choi Date: Fri, 8 Sep 2023 12:11:32 +0900 Subject: [PATCH 2/3] feat(utils): apply assert to createContext util --- packages/bezier-react/src/utils/reactUtils.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/bezier-react/src/utils/reactUtils.ts b/packages/bezier-react/src/utils/reactUtils.ts index edf2119be7..02d2dd023f 100644 --- a/packages/bezier-react/src/utils/reactUtils.ts +++ b/packages/bezier-react/src/utils/reactUtils.ts @@ -1,5 +1,7 @@ import React from 'react' +import { assert } from './assertUtils' + export const getReactVersion = () => { const [major, minor, patch] = React.version.split('.').map(Number) return { major, minor, patch } @@ -33,9 +35,10 @@ export function createContext( function useContext(consumerName?: any) { const contextValue = React.useContext(Context) - if (contextValue === null) { - throw new Error(`'${consumerName}' must be used within '${providerName}'`) - } + assert( + contextValue !== null, + `'${consumerName}' must be used within '${providerName}'`, + ) return contextValue } From ae2b52b9103aa0e4f81e1ea3ef9c9cda56f9ea4d Mon Sep 17 00:00:00 2001 From: Ed Sungik Choi Date: Fri, 8 Sep 2023 12:17:45 +0900 Subject: [PATCH 3/3] feat(utils): rm export of isDev function --- packages/bezier-react/src/utils/assertUtils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/bezier-react/src/utils/assertUtils.ts b/packages/bezier-react/src/utils/assertUtils.ts index e3ab109250..686d5493b2 100644 --- a/packages/bezier-react/src/utils/assertUtils.ts +++ b/packages/bezier-react/src/utils/assertUtils.ts @@ -1,4 +1,4 @@ -export function isDev() { +function isDev() { return process.env.NODE_ENV !== 'production' }