diff --git a/package-lock.json b/package-lock.json index 79032eb..6cdee3c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,15 +1,158 @@ { "name": "@kri/common", - "version": "0.2.0", + "version": "0.11.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@kri/common", - "version": "0.2.0", + "version": "0.11.1", "license": "UNLICENSED", + "dependencies": { + "clsx": "^2.1.1", + "crypto-js": "^4.2.0", + "tailwind-merge": "^3.4.0" + }, "devDependencies": { + "@tanstack/react-query": "^5.90.21", + "@types/crypto-js": "^4.2.2", + "@types/react": "^19.2.17", + "jotai": "^2.20.1", + "react": "^19.2.7", "typescript": "^6.0.3" + }, + "peerDependencies": { + "@tanstack/react-query": ">=5 <6", + "jotai": ">=2", + "react": ">=18" + }, + "peerDependenciesMeta": { + "@tanstack/react-query": { + "optional": true + }, + "jotai": { + "optional": true + }, + "react": { + "optional": true + } + } + }, + "node_modules/@tanstack/query-core": { + "version": "5.90.20", + "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.90.20.tgz", + "integrity": "sha512-OMD2HLpNouXEfZJWcKeVKUgQ5n+n3A2JFmBaScpNDUqSrQSjiveC7dKMe53uJUg1nDG16ttFPz2xfilz6i2uVg==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + } + }, + "node_modules/@tanstack/react-query": { + "version": "5.90.21", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.90.21.tgz", + "integrity": "sha512-0Lu6y5t+tvlTJMTO7oh5NSpJfpg/5D41LlThfepTixPYkJ0sE2Jj0m0f6yYqujBwIXlId87e234+MxG3D3g7kg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@tanstack/query-core": "5.90.20" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/tannerlinsley" + }, + "peerDependencies": { + "react": "^18 || ^19" + } + }, + "node_modules/@types/crypto-js": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/@types/crypto-js/-/crypto-js-4.2.2.tgz", + "integrity": "sha512-sDOLlVbHhXpAUAL0YHDUUwDZf3iN4Bwi4W6a0W0b+QcAezUbRtH4FVb+9J4h+XFPW7l/gQ9F8qC7P+Ec4k8QVQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "19.2.17", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz", + "integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/crypto-js": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz", + "integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==", + "license": "MIT" + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jotai": { + "version": "2.20.1", + "resolved": "https://registry.npmjs.org/jotai/-/jotai-2.20.1.tgz", + "integrity": "sha512-dnuKfU/GLi8B28RRMjQ3AfoN7kfzP8o41+AX2FmITZqEMY8PHnjABq+VkEooomLwYaGjda+pgy0yFSjaHX/ZPg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.20.0" + }, + "peerDependencies": { + "@babel/core": ">=7.0.0", + "@babel/template": ">=7.0.0", + "@types/react": ">=17.0.0", + "react": ">=17.0.0" + }, + "peerDependenciesMeta": { + "@babel/core": { + "optional": true + }, + "@babel/template": { + "optional": true + }, + "@types/react": { + "optional": true + }, + "react": { + "optional": true + } + } + }, + "node_modules/react": { + "version": "19.2.7", + "resolved": "https://registry.npmjs.org/react/-/react-19.2.7.tgz", + "integrity": "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tailwind-merge": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.4.0.tgz", + "integrity": "sha512-uSaO4gnW+b3Y2aWoWfFpX62vn2sR3skfhbjsEnaBI81WD1wBLlHZe5sWf0AqjksNdYTbGBEd0UasQMT3SNV15g==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/dcastil" } }, "node_modules/typescript": { diff --git a/package.json b/package.json index 753c85a..80d5235 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@kri/common", - "version": "0.2.0", + "version": "0.11.1", "description": "KRI 프런트엔드 공통 유틸리티", "type": "module", "main": "./dist/index.js", @@ -10,6 +10,46 @@ "types": "./dist/index.d.ts", "import": "./dist/index.js", "default": "./dist/index.js" + }, + "./http": { + "types": "./dist/http/index.d.ts", + "import": "./dist/http/index.js", + "default": "./dist/http/index.js" + }, + "./browser": { + "types": "./dist/browser/index.d.ts", + "import": "./dist/browser/index.js", + "default": "./dist/browser/index.js" + }, + "./ui": { + "types": "./dist/ui/index.d.ts", + "import": "./dist/ui/index.js", + "default": "./dist/ui/index.js" + }, + "./server": { + "types": "./dist/server/index.d.ts", + "import": "./dist/server/index.js", + "default": "./dist/server/index.js" + }, + "./security": { + "types": "./dist/security/index.d.ts", + "import": "./dist/security/index.js", + "default": "./dist/security/index.js" + }, + "./hooks": { + "types": "./dist/hooks/index.d.ts", + "import": "./dist/hooks/index.js", + "default": "./dist/hooks/index.js" + }, + "./query": { + "types": "./dist/query/index.d.ts", + "import": "./dist/query/index.js", + "default": "./dist/query/index.js" + }, + "./config": { + "types": "./dist/config/index.d.ts", + "import": "./dist/config/index.js", + "default": "./dist/config/index.js" } }, "files": [ @@ -32,6 +72,32 @@ "registry": "https://gitea.kric.com/api/packages/KRi/npm/" }, "devDependencies": { + "@tanstack/react-query": "^5.90.21", + "@types/crypto-js": "^4.2.2", + "@types/react": "^19.2.17", + "jotai": "^2.20.1", + "react": "^19.2.7", "typescript": "^6.0.3" + }, + "peerDependencies": { + "@tanstack/react-query": ">=5 <6", + "jotai": ">=2", + "react": ">=18" + }, + "peerDependenciesMeta": { + "@tanstack/react-query": { + "optional": true + }, + "jotai": { + "optional": true + }, + "react": { + "optional": true + } + }, + "dependencies": { + "clsx": "^2.1.1", + "crypto-js": "^4.2.0", + "tailwind-merge": "^3.4.0" } } diff --git a/src/browser/file-download.ts b/src/browser/file-download.ts new file mode 100644 index 0000000..2755202 --- /dev/null +++ b/src/browser/file-download.ts @@ -0,0 +1,75 @@ +export const XLSX_MIME_TYPE = + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + +export const DEFAULT_BINARY_MIME_TYPE = "application/octet-stream"; + +const assertBrowserEnvironment = (): void => { + if (typeof window === "undefined" || typeof document === "undefined") { + throw new Error( + "파일 다운로드 기능은 브라우저 환경에서만 사용할 수 있습니다.", + ); + } +}; + +const stripBase64Prefix = (value: string): string => { + const commaIndex = value.indexOf(","); + + if (value.startsWith("data:") && commaIndex >= 0) { + return value.slice(commaIndex + 1); + } + + return value; +}; + +export const base64ToBlob = ( + base64: string, + contentType = DEFAULT_BINARY_MIME_TYPE, +): Blob => { + assertBrowserEnvironment(); + + const normalizedBase64 = stripBase64Prefix(base64); + + const byteString = window.atob(normalizedBase64); + + const bytes = new Uint8Array(byteString.length); + + for (let index = 0; index < byteString.length; index += 1) { + bytes[index] = byteString.charCodeAt(index); + } + + return new Blob([bytes], { type: contentType }); +}; + +export const downloadFile = (blob: Blob, filename: string): void => { + assertBrowserEnvironment(); + + const objectUrl = URL.createObjectURL(blob); + + const anchor = document.createElement("a"); + + anchor.href = objectUrl; + anchor.download = filename; + anchor.style.display = "none"; + + document.body.appendChild(anchor); + anchor.click(); + anchor.remove(); + + /* + * 클릭 직후 바로 해제하면 일부 브라우저에서 + * 다운로드가 취소될 가능성이 있어 다음 tick에서 해제한다. + */ + window.setTimeout(() => { + URL.revokeObjectURL(objectUrl); + }, 0); +}; + +export const downloadBase64File = ( + base64: string, + filename: string, + contentType = DEFAULT_BINARY_MIME_TYPE, +): void => { + const blob = base64ToBlob(base64, contentType); + + downloadFile(blob, filename); +}; diff --git a/src/browser/index.ts b/src/browser/index.ts new file mode 100644 index 0000000..8c0eebc --- /dev/null +++ b/src/browser/index.ts @@ -0,0 +1 @@ +export * from "./file-download.js"; diff --git a/src/config/env.ts b/src/config/env.ts new file mode 100644 index 0000000..5bf2a79 --- /dev/null +++ b/src/config/env.ts @@ -0,0 +1,207 @@ +export type EnvInput = string | null | undefined; + +export type EnvStringOptions = { + /** + * 앞뒤 공백을 제거할지 여부 + * + * @default true + */ + trim?: boolean; + + /** + * 빈 문자열을 유효한 값으로 허용할지 여부 + * + * @default false + */ + allowEmpty?: boolean; +}; + +export type NumberEnvOptions = EnvStringOptions & { + min?: number; + max?: number; +}; + +export type BooleanEnvOptions = EnvStringOptions & { + trueValues?: readonly string[]; + falseValues?: readonly string[]; +}; + +export class EnvValidationError extends Error { + readonly variableName: string; + readonly reason: string; + + constructor(variableName: string, reason: string) { + super(`Invalid environment variable "${variableName}": ${reason}`); + + this.name = "EnvValidationError"; + this.variableName = variableName; + this.reason = reason; + } +} + +const normalizeEnvValue = ( + value: EnvInput, + trim: boolean, +): string | undefined => { + if (value === undefined || value === null) { + return undefined; + } + + return trim ? value.trim() : value; +}; + +export const requiredEnv = ( + variableName: string, + value: EnvInput, + options: EnvStringOptions = {}, +): string => { + const { trim = true, allowEmpty = false } = options; + + const normalized = normalizeEnvValue(value, trim); + + if (normalized === undefined) { + throw new EnvValidationError(variableName, "required value is missing"); + } + + if (!allowEmpty && normalized.length === 0) { + throw new EnvValidationError(variableName, "empty value is not allowed"); + } + + return normalized; +}; + +export const optionalEnv = ( + variableName: string, + value: EnvInput, + options: EnvStringOptions = {}, +): string | undefined => { + const { trim = true, allowEmpty = false } = options; + + const normalized = normalizeEnvValue(value, trim); + + if (normalized === undefined) { + return undefined; + } + + if (!allowEmpty && normalized.length === 0) { + return undefined; + } + + return normalized; +}; + +export const enumEnv = ( + variableName: string, + value: EnvInput, + allowedValues: TAllowed, + options: EnvStringOptions = {}, +): TAllowed[number] => { + const normalized = requiredEnv(variableName, value, options); + + const matched = allowedValues.some((allowedValue) => { + return allowedValue === normalized; + }); + + if (!matched) { + throw new EnvValidationError( + variableName, + [ + `received "${normalized}"`, + `allowed values: ${allowedValues.join(", ")}`, + ].join("; "), + ); + } + + return normalized as TAllowed[number]; +}; + +export const booleanEnv = ( + variableName: string, + value: EnvInput, + options: BooleanEnvOptions = {}, +): boolean => { + const { + trueValues = ["true", "1", "yes", "on"], + falseValues = ["false", "0", "no", "off"], + } = options; + + const normalized = requiredEnv(variableName, value, options).toLowerCase(); + + if (trueValues.some((item) => item.toLowerCase() === normalized)) { + return true; + } + + if (falseValues.some((item) => item.toLowerCase() === normalized)) { + return false; + } + + throw new EnvValidationError( + variableName, + `cannot convert "${normalized}" to boolean`, + ); +}; + +export const numberEnv = ( + variableName: string, + value: EnvInput, + options: NumberEnvOptions = {}, +): number => { + const normalized = requiredEnv(variableName, value, options); + + const parsed = Number(normalized); + + if (!Number.isFinite(parsed)) { + throw new EnvValidationError( + variableName, + `cannot convert "${normalized}" to number`, + ); + } + + if (options.min !== undefined && parsed < options.min) { + throw new EnvValidationError( + variableName, + `must be greater than or equal to ${options.min}`, + ); + } + + if (options.max !== undefined && parsed > options.max) { + throw new EnvValidationError( + variableName, + `must be less than or equal to ${options.max}`, + ); + } + + return parsed; +}; + +export const integerEnv = ( + variableName: string, + value: EnvInput, + options: NumberEnvOptions = {}, +): number => { + const parsed = numberEnv(variableName, value, options); + + if (!Number.isInteger(parsed)) { + throw new EnvValidationError( + variableName, + `must be an integer; received "${parsed}"`, + ); + } + + return parsed; +}; + +export const createEnv = >( + values: TValues, +): Readonly => { + return Object.freeze(values); +}; + +export const env = Object.freeze({ + required: requiredEnv, + optional: optionalEnv, + oneOf: enumEnv, + boolean: booleanEnv, + number: numberEnv, + integer: integerEnv, +}); diff --git a/src/config/index.ts b/src/config/index.ts new file mode 100644 index 0000000..ab98ed6 --- /dev/null +++ b/src/config/index.ts @@ -0,0 +1,2 @@ +export * from "./env.js"; +export * from "./next-config.js"; diff --git a/src/config/next-config.ts b/src/config/next-config.ts new file mode 100644 index 0000000..38da235 --- /dev/null +++ b/src/config/next-config.ts @@ -0,0 +1,14 @@ +export const createKriNextConfig = ( + config: TConfig, +) => { + return { + output: "standalone" as const, + reactCompiler: true as const, + + /* + * 프로젝트 설정을 뒤에 병합해 + * 필요한 경우 기본값을 덮어쓸 수 있다. + */ + ...config, + }; +}; diff --git a/src/date.ts b/src/date.ts index b0c6274..75b8cb5 100644 --- a/src/date.ts +++ b/src/date.ts @@ -1,8 +1,5 @@ export type DateTimeFormatOption = - | "date" - | "dateHour" - | "dateHourMin" - | "dateTime"; + "date" | "dateHour" | "dateHourMin" | "dateTime"; const KST_OFFSET_MS = 9 * 60 * 60 * 1000; @@ -14,28 +11,20 @@ function pad2(value: number): string { * 날짜 값을 한국 표준시(KST) 문자열로 변환한다. */ export function formatKst( - input: string | number | Date | null | undefined, - option: DateTimeFormatOption = "dateTime", + input: string | number | Date | null | undefined, + option: DateTimeFormatOption = "dateTime", ): string { - if ( - input === null - || input === undefined - || input === "" - ) { + if (input === null || input === undefined || input === "") { return ""; } - const date = input instanceof Date - ? input - : new Date(input); + const date = input instanceof Date ? input : new Date(input); if (Number.isNaN(date.getTime())) { return ""; } - const kstDate = new Date( - date.getTime() + KST_OFFSET_MS, - ); + const kstDate = new Date(date.getTime() + KST_OFFSET_MS); const year = kstDate.getUTCFullYear(); const month = pad2(kstDate.getUTCMonth() + 1); @@ -59,4 +48,4 @@ export function formatKst( case "dateTime": return `${datePart} ${hour}:${minute}:${second}`; } -} \ No newline at end of file +} diff --git a/src/hooks/create/auth.ts b/src/hooks/create/auth.ts new file mode 100644 index 0000000..a607301 --- /dev/null +++ b/src/hooks/create/auth.ts @@ -0,0 +1,97 @@ +"use client"; + +import { atom, useAtom } from "jotai"; + +import { useCallback, useMemo } from "react"; + +export type EmptyAuthExtra = Record; + +export type AuthState = { + user: TUser | null; +} & TExtra; + +export type AuthStateAction = + | AuthState + | ((previous: AuthState) => AuthState); + +export type CreateAuthHookOptions = { + initialState: AuthState; +}; + +export const createAuthHook = ( + options: CreateAuthHookOptions, +) => { + const createInitialState = (): AuthState => { + return { + ...options.initialState, + }; + }; + + const authAtom = atom>(createInitialState()); + + const useAuth = () => { + const [auth, setAuthValue] = useAtom(authAtom); + + const setAuth = useCallback( + (next: AuthStateAction): void => { + if (typeof next === "function") { + setAuthValue((previous) => { + return next(previous); + }); + + return; + } + + setAuthValue(next); + }, + [setAuthValue], + ); + + const patchAuth = useCallback( + (patch: Partial>): void => { + setAuthValue((previous) => { + return { + ...previous, + ...patch, + }; + }); + }, + [setAuthValue], + ); + + const setUser = useCallback( + (user: TUser | null): void => { + setAuthValue((previous) => { + return { + ...previous, + user, + }; + }); + }, + [setAuthValue], + ); + + const resetAuth = useCallback((): void => { + setAuthValue(createInitialState()); + }, [setAuthValue]); + + return useMemo( + () => ({ + auth, + user: auth.user, + isAuthenticated: auth.user !== null, + + setAuth, + patchAuth, + setUser, + resetAuth, + }), + [auth, patchAuth, resetAuth, setAuth, setUser], + ); + }; + + return { + authAtom, + useAuth, + }; +}; diff --git a/src/hooks/create/dialog.ts b/src/hooks/create/dialog.ts new file mode 100644 index 0000000..8f1ec9a --- /dev/null +++ b/src/hooks/create/dialog.ts @@ -0,0 +1,87 @@ +"use client"; + +import { atom, useAtom } from "jotai"; + +import { useCallback } from "react"; + +export const createDialogHook = () => { + const openDialogIdsAtom = atom([]); + + const useDialog = () => { + const [openDialogIds, setOpenDialogIds] = useAtom(openDialogIdsAtom); + + const openDialog = useCallback( + (dialogId: TDialogId): void => { + setOpenDialogIds((previous) => { + if (previous.includes(dialogId)) { + return previous; + } + + return [...previous, dialogId]; + }); + }, + [setOpenDialogIds], + ); + + const closeDialog = useCallback( + (dialogId: TDialogId): void => { + setOpenDialogIds((previous) => { + return previous.filter((id) => id !== dialogId); + }); + }, + [setOpenDialogIds], + ); + + const setDialogOpen = useCallback( + (dialogId: TDialogId, open: boolean): void => { + if (open) { + openDialog(dialogId); + return; + } + + closeDialog(dialogId); + }, + [closeDialog, openDialog], + ); + + const toggleDialog = useCallback( + (dialogId: TDialogId): void => { + setOpenDialogIds((previous) => { + if (previous.includes(dialogId)) { + return previous.filter((id) => id !== dialogId); + } + + return [...previous, dialogId]; + }); + }, + [setOpenDialogIds], + ); + + const closeAllDialogs = useCallback((): void => { + setOpenDialogIds([]); + }, [setOpenDialogIds]); + + const isDialogOpen = useCallback( + (dialogId: TDialogId): boolean => { + return openDialogIds.includes(dialogId); + }, + [openDialogIds], + ); + + return { + openDialogIds, + + openDialog, + closeDialog, + setDialogOpen, + toggleDialog, + closeAllDialogs, + isDialogOpen, + }; + }; + + return { + openDialogIdsAtom, + useDialog, + }; +}; diff --git a/src/hooks/create/loading.ts b/src/hooks/create/loading.ts new file mode 100644 index 0000000..c5e147e --- /dev/null +++ b/src/hooks/create/loading.ts @@ -0,0 +1,79 @@ +"use client"; + +import { atom, useAtomValue, useSetAtom } from "jotai"; + +import { useCallback } from "react"; + +export const createLoadingHook = () => { + const loadingCountAtom = atom(0); + + const isLoadingAtom = atom((get) => { + return get(loadingCountAtom) > 0; + }); + + const useLoading = () => { + const loadingCount = useAtomValue(loadingCountAtom); + + const isLoading = useAtomValue(isLoadingAtom); + + const setLoadingCount = useSetAtom(loadingCountAtom); + + const showLoading = useCallback((): void => { + setLoadingCount((previous) => previous + 1); + }, [setLoadingCount]); + + const hideLoading = useCallback((): void => { + setLoadingCount((previous) => Math.max(0, previous - 1)); + }, [setLoadingCount]); + + const resetLoading = useCallback((): void => { + setLoadingCount(0); + }, [setLoadingCount]); + + const withLoading = useCallback( + function runWithLoading(task: () => T): T { + showLoading(); + + try { + return task(); + } finally { + hideLoading(); + } + }, + [hideLoading, showLoading], + ); + + const withLoadingAsync = useCallback( + async function runWithLoadingAsync( + task: () => Promise, + ): Promise { + showLoading(); + + try { + return await task(); + } finally { + hideLoading(); + } + }, + [hideLoading, showLoading], + ); + + return { + loadingCount, + isLoading, + + showLoading, + hideLoading, + resetLoading, + + withLoading, + withLoadingAsync, + }; + }; + + return { + loadingCountAtom, + isLoadingAtom, + useLoading, + }; +}; diff --git a/src/hooks/create/storage.ts b/src/hooks/create/storage.ts new file mode 100644 index 0000000..cb4cc6a --- /dev/null +++ b/src/hooks/create/storage.ts @@ -0,0 +1,68 @@ +"use client"; + +import { useMemo } from "react"; + +export type StorageScope = "local" | "session"; + +export type StorageAdapter = { + get: (key: string) => unknown | null; + + set: (key: string, value: unknown) => void; + + remove: (key: string) => void; +}; + +type StorageKey = Extract; + +export type StorageHandle = { + scope: StorageScope; + + get: () => TValue | null; + + set: (value: TValue) => void; + + remove: () => void; +}; + +export type CreateStorageHookOptions = { + resolveStorageScope: (key: StorageKey) => StorageScope; + + localStorageAdapter: StorageAdapter; + + sessionStorageAdapter: StorageAdapter; +}; + +export const createStorageHook = ( + options: CreateStorageHookOptions, +) => { + const useStorage = >( + key: TKey, + ): StorageHandle => { + const scope = options.resolveStorageScope(key); + + return useMemo(() => { + const adapter = + scope === "local" + ? options.localStorageAdapter + : options.sessionStorageAdapter; + + return { + scope, + + get: () => { + return adapter.get(key) as TSchema[TKey] | null; + }, + + set: (value: TSchema[TKey]): void => { + adapter.set(key, value); + }, + + remove: (): void => { + adapter.remove(key); + }, + }; + }, [key, scope]); + }; + + return useStorage; +}; diff --git a/src/hooks/index.ts b/src/hooks/index.ts new file mode 100644 index 0000000..8709531 --- /dev/null +++ b/src/hooks/index.ts @@ -0,0 +1,10 @@ +"use client"; + +export * from "./use/previous.js"; +export * from "./use/debounced-value.js"; +export * from "./use/mounted.js"; + +export * from "./create/auth.js"; +export * from "./create/loading.js"; +export * from "./create/storage.js"; +export * from "./create/dialog.js"; diff --git a/src/hooks/use/debounced-value.ts b/src/hooks/use/debounced-value.ts new file mode 100644 index 0000000..82aa854 --- /dev/null +++ b/src/hooks/use/debounced-value.ts @@ -0,0 +1,22 @@ +"use client"; + +import { useEffect, useState } from "react"; + +export const useDebouncedValue = (value: T, delayMs = 300): T => { + const [debouncedValue, setDebouncedValue] = useState(value); + + useEffect(() => { + const timeoutId = setTimeout( + () => { + setDebouncedValue(value); + }, + Math.max(0, delayMs), + ); + + return () => { + clearTimeout(timeoutId); + }; + }, [value, delayMs]); + + return debouncedValue; +}; diff --git a/src/hooks/use/mounted.ts b/src/hooks/use/mounted.ts new file mode 100644 index 0000000..7199b6a --- /dev/null +++ b/src/hooks/use/mounted.ts @@ -0,0 +1,13 @@ +"use client"; + +import { useEffect, useState } from "react"; + +export const useMounted = (): boolean => { + const [mounted, setMounted] = useState(false); + + useEffect(() => { + setMounted(true); + }, []); + + return mounted; +}; diff --git a/src/hooks/use/previous.ts b/src/hooks/use/previous.ts new file mode 100644 index 0000000..d0e0123 --- /dev/null +++ b/src/hooks/use/previous.ts @@ -0,0 +1,13 @@ +"use client"; + +import { useEffect, useRef } from "react"; + +export const usePrevious = (value: T): T | undefined => { + const previousRef = useRef(undefined); + + useEffect(() => { + previousRef.current = value; + }, [value]); + + return previousRef.current; +}; diff --git a/src/http/error-policy.ts b/src/http/error-policy.ts new file mode 100644 index 0000000..45fb2a5 --- /dev/null +++ b/src/http/error-policy.ts @@ -0,0 +1,100 @@ +import type { + ErrorMessageResolver, + ErrorNotifier, + HttpError, +} from "./http-client.js"; + +let logoutRedirectStarted = false; + +export type LogoutRedirectOptions = { + logoutPath?: string; + excludedPaths?: string[]; +}; + +export const getServerMessage = (payload: unknown): string | undefined => { + if (typeof payload === "string") { + return payload; + } + + if (typeof payload === "object" && payload !== null && "message" in payload) { + const message = (payload as { message?: unknown }).message; + + return typeof message === "string" ? message : undefined; + } + + return undefined; +}; + +export const redirectToLogout = (options: LogoutRedirectOptions = {}): void => { + if (typeof window === "undefined") { + return; + } + + if (logoutRedirectStarted) { + return; + } + + const logoutPath = options.logoutPath ?? "/logout"; + + const excludedPaths = options.excludedPaths ?? ["/login", logoutPath]; + + if (excludedPaths.includes(window.location.pathname)) { + return; + } + + logoutRedirectStarted = true; + window.location.replace(logoutPath); +}; + +export const defaultResolveErrorMessage: ErrorMessageResolver = ( + status, + serverMessage, +) => { + if (serverMessage) { + return serverMessage; + } + + switch (status) { + case 400: + return "잘못된 요청입니다."; + + case 404: + return "요청한 대상을 찾을 수 없습니다."; + + case 408: + return "요청 시간이 초과되었습니다."; + + case 500: + return "서버 오류가 발생했습니다."; + + default: + return "요청 처리 중 오류가 발생했습니다."; + } +}; + +export const defaultNotifyError: ErrorNotifier = (message, error) => { + if (typeof window === "undefined") { + return; + } + + window.alert(`[${error.status}] ${message}`); +}; + +export const showErrorMessage = ( + error: HttpError, + options?: { + resolveErrorMessage?: ErrorMessageResolver; + notifyError?: ErrorNotifier; + }, +): void => { + const serverMessage = getServerMessage(error.data); + + const resolveErrorMessage = + options?.resolveErrorMessage ?? defaultResolveErrorMessage; + + const notifyError = options?.notifyError ?? defaultNotifyError; + + const message = resolveErrorMessage(error.status, serverMessage); + + notifyError(message, error); +}; diff --git a/src/http/http-client.ts b/src/http/http-client.ts new file mode 100644 index 0000000..6f3dbf9 --- /dev/null +++ b/src/http/http-client.ts @@ -0,0 +1,766 @@ +import { redirectToLogout, showErrorMessage } from "./error-policy.js"; + +export const DEFAULT_HTTP_TIMEOUT_MS = 60_000; + +export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE"; + +export type HttpErrorHandler = (error: HttpError) => void; + +export type ErrorMessageResolver = ( + status: number, + serverMessage?: string, +) => string; + +export type ErrorNotifier = (message: string, error: HttpError) => void; + +export class HttpError extends Error { + public readonly status: number; + public readonly data: unknown; + public readonly url: string; + + private readonly headerMap: Record; + + public constructor( + status: number, + data: unknown, + url: string, + headers?: Headers, + ) { + super(`HTTP ${status}`); + + this.name = "HttpError"; + this.status = status; + this.data = data; + this.url = url; + + const headerMap: Record = {}; + + headers?.forEach((value, key) => { + headerMap[key.toLowerCase()] = value; + }); + + this.headerMap = headerMap; + } + + public get headers(): Readonly> { + return this.headerMap; + } + + public get traceId(): string | undefined { + return this.headerMap["x-trace-id"] ?? this.headerMap["x-request-id"]; + } +} + +export type QueryPrimitive = string | number | boolean; + +export type QueryValue = QueryPrimitive | QueryPrimitive[] | null | undefined; + +export type Query = Record; + +export type PathParams = Record; + +export type NextFetchOptions = { + revalidate?: number | false; + tags?: string[]; +}; + +export type RequestOptions = { + method?: HttpMethod; + + pathParams?: PathParams; + query?: Query; + + json?: unknown; + rawBody?: BodyInit; + form?: FormData; + + headers?: HeadersInit; + timeoutMs?: number; + + expectText?: boolean; + expectBinary?: boolean; + + cache?: RequestCache; + next?: NextFetchOptions; + + /** + * 401 기본 처리를 실행하지 않는다. + */ + skipUnauthorizedHandler?: boolean; + + /** + * 403 기본 처리를 실행하지 않는다. + */ + skipForbiddenHandler?: boolean; + + /** + * 401·403 이외의 오류에 대한 기본 처리를 실행하지 않는다. + */ + skipResponseErrorHandler?: boolean; + + /** + * @deprecated + * skipUnauthorizedHandler와 skipForbiddenHandler를 사용한다. + */ + skipAuthErrorHandler?: boolean; +}; + +export type HttpClientOptions = { + getToken?: () => string | null | undefined; + + defaultTimeoutMs?: number; + defaultHeaders?: HeadersInit; + + /** + * 401 처리. + * + * undefined: + * 기본 로그아웃 처리 + * + * 함수: + * 전달한 함수로 대체 + * + * false: + * 전역 401 처리 비활성화 + */ + onUnauthorized?: HttpErrorHandler | false; + + /** + * 403 처리. + * + * undefined: + * 기본 로그아웃 처리 + * + * 함수: + * 전달한 함수로 대체 + * + * false: + * 전역 403 처리 비활성화 + */ + onForbidden?: HttpErrorHandler | false; + + /** + * 401·403 이외의 HTTP 오류 처리. + * + * undefined: + * 기본 오류 메시지 표시 + * + * 함수: + * 전달한 함수로 대체 + * + * false: + * 전역 오류 표시 비활성화 + */ + onResponseError?: HttpErrorHandler | false; + + /** + * @deprecated + * onUnauthorized와 onForbidden을 사용한다. + * + * 두 옵션이 별도로 지정되지 않았을 때 + * 401과 403 모두에 적용된다. + */ + onAuthError?: HttpErrorHandler | false; + + logoutPath?: string; + authExcludedPaths?: string[]; + + resolveErrorMessage?: ErrorMessageResolver; + notifyError?: ErrorNotifier; +}; + +type RequestFactoryOptions = { + getToken: (() => string | null | undefined) | undefined; + + defaultTimeoutMs: number; + defaultHeaders: HeadersInit; + + onUnauthorized: HttpErrorHandler | undefined; + onForbidden: HttpErrorHandler | undefined; + onResponseError: HttpErrorHandler | undefined; +}; + +type NextRequestInit = RequestInit & { + next?: NextFetchOptions; +}; + +type RequestOptionBodyKeys = "method" | "json" | "rawBody" | "form"; + +export type RequestOptionsWithoutBody = Omit< + RequestOptions, + RequestOptionBodyKeys +>; + +export type DeleteRequestOptions = Omit; + +const replacePathParams = (path: string, params?: PathParams): string => { + if (!params) { + return path; + } + + let result = path; + + for (const [key, value] of Object.entries(params)) { + result = result.replaceAll(`:${key}`, encodeURIComponent(String(value))); + } + + return result; +}; + +const createBaseUrl = (baseUrl: string): URL => { + const result = new URL(baseUrl); + + if (!result.pathname.endsWith("/")) { + result.pathname = `${result.pathname}/`; + } + + return result; +}; + +const buildUrl = ( + baseUrl: string, + path: string, + options: RequestOptions, +): URL => { + const replacedPath = replacePathParams(path, options.pathParams); + + if (/^https?:\/\//i.test(replacedPath)) { + return new URL(replacedPath); + } + + const normalizedPath = replacedPath.replace(/^\/+/, ""); + + return new URL(normalizedPath, createBaseUrl(baseUrl)); +}; + +const appendQuery = (url: URL, query?: Query): void => { + if (!query) { + return; + } + + for (const [key, value] of Object.entries(query)) { + if (value === undefined || value === null) { + continue; + } + + if (Array.isArray(value)) { + for (const item of value) { + url.searchParams.append(key, String(item)); + } + + continue; + } + + url.searchParams.set(key, String(value)); + } +}; + +const buildHeaders = ( + defaultHeaders: HeadersInit, + getToken: (() => string | null | undefined) | undefined, + requestHeaders?: HeadersInit, +): Headers => { + const headers = new Headers(defaultHeaders); + + const token = getToken?.(); + + if (token) { + headers.set("authorization", `Bearer ${token}`); + } + + if (requestHeaders) { + const overrides = new Headers(requestHeaders); + + overrides.forEach((value, key) => { + headers.set(key, value); + }); + } + + return headers; +}; + +const buildBody = ( + options: RequestOptions, + headers: Headers, +): BodyInit | undefined => { + if (options.form !== undefined) { + /* + * FormData의 Content-Type과 boundary는 + * fetch가 자동으로 생성해야 한다. + */ + headers.delete("content-type"); + + return options.form; + } + + if (options.rawBody !== undefined) { + return options.rawBody; + } + + if (options.json === undefined) { + return undefined; + } + + if (!headers.has("content-type")) { + headers.set("content-type", "application/json"); + } + + return typeof options.json === "string" + ? options.json + : JSON.stringify(options.json); +}; + +const isJsonContentType = (contentType: string): boolean => { + const normalized = contentType.toLowerCase(); + + return ( + normalized.includes("application/json") || normalized.includes("+json") + ); +}; + +const parseSuccessBody = ( + rawText: string, + contentType: string, + expectText: boolean, +): unknown => { + if (expectText) { + return rawText; + } + + if (!rawText) { + return null; + } + + if (!isJsonContentType(contentType)) { + return rawText; + } + + return JSON.parse(rawText); +}; + +const parseErrorBody = (rawText: string, contentType: string): unknown => { + if (!rawText) { + return null; + } + + if (!isJsonContentType(contentType)) { + return rawText; + } + + try { + return JSON.parse(rawText); + } catch { + return rawText; + } +}; + +const isAbortError = (error: unknown): boolean => { + if (typeof error !== "object" || error === null) { + return false; + } + + const candidate = error as { + name?: unknown; + code?: unknown; + message?: unknown; + }; + + if (candidate.name === "AbortError" || candidate.code === "ABORT_ERR") { + return true; + } + + return ( + typeof candidate.message === "string" && + candidate.message.toLowerCase().includes("aborted") + ); +}; + +const extractErrorCode = (error: unknown): string | undefined => { + if (typeof error !== "object" || error === null) { + return undefined; + } + + const candidate = error as { + code?: unknown; + cause?: unknown; + }; + + if (typeof candidate.cause === "object" && candidate.cause !== null) { + const cause = candidate.cause as { + code?: unknown; + }; + + if (typeof cause.code === "string") { + return cause.code; + } + } + + return typeof candidate.code === "string" ? candidate.code : undefined; +}; + +const processHttpError = ( + error: HttpError, + requestOptions: RequestOptions, + clientOptions: RequestFactoryOptions, +): never => { + const skipAllAuthHandlers = requestOptions.skipAuthErrorHandler ?? false; + + if (error.status === 401) { + if (!skipAllAuthHandlers && !requestOptions.skipUnauthorizedHandler) { + clientOptions.onUnauthorized?.(error); + } + + throw error; + } + + if (error.status === 403) { + if (!skipAllAuthHandlers && !requestOptions.skipForbiddenHandler) { + clientOptions.onForbidden?.(error); + } + + throw error; + } + + if (!requestOptions.skipResponseErrorHandler) { + clientOptions.onResponseError?.(error); + } + + throw error; +}; + +const processErrorResponse = ( + response: Response, + data: unknown, + url: URL, + requestOptions: RequestOptions, + clientOptions: RequestFactoryOptions, +): never => { + const error = new HttpError( + response.status, + data, + url.toString(), + response.headers, + ); + + return processHttpError(error, requestOptions, clientOptions); +}; + +const resolveAuthHandler = ( + specificHandler: HttpErrorHandler | false | undefined, + legacyHandler: HttpErrorHandler | false | undefined, + defaultHandler: HttpErrorHandler, +): HttpErrorHandler | undefined => { + if (specificHandler === false) { + return undefined; + } + + if (typeof specificHandler === "function") { + return specificHandler; + } + + if (legacyHandler === false) { + return undefined; + } + + if (typeof legacyHandler === "function") { + return legacyHandler; + } + + return defaultHandler; +}; + +const resolveResponseHandler = ( + options: HttpClientOptions, +): HttpErrorHandler | undefined => { + if (options.onResponseError === false) { + return undefined; + } + + if (typeof options.onResponseError === "function") { + return options.onResponseError; + } + + return (error: HttpError): void => { + showErrorMessage(error, options); + }; +}; + +const createResolvedOptions = ( + options: HttpClientOptions, +): RequestFactoryOptions => { + const logoutPath = options.logoutPath ?? "/logout"; + + const authExcludedPaths = options.authExcludedPaths ?? ["/login", logoutPath]; + + const defaultLogoutHandler: HttpErrorHandler = () => { + redirectToLogout({ + logoutPath, + excludedPaths: authExcludedPaths, + }); + }; + + return { + getToken: options.getToken, + + defaultTimeoutMs: options.defaultTimeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS, + + defaultHeaders: options.defaultHeaders ?? { + "content-type": "application/json", + }, + + onUnauthorized: resolveAuthHandler( + options.onUnauthorized, + options.onAuthError, + defaultLogoutHandler, + ), + + onForbidden: resolveAuthHandler( + options.onForbidden, + options.onAuthError, + defaultLogoutHandler, + ), + + onResponseError: resolveResponseHandler(options), + }; +}; + +const createRequest = ( + baseUrl: string, + clientOptions: RequestFactoryOptions, +) => { + return async ( + path: string, + options: RequestOptions = {}, + ): Promise => { + const url = buildUrl(baseUrl, path, options); + + appendQuery(url, options.query); + + const headers = buildHeaders( + clientOptions.defaultHeaders, + clientOptions.getToken, + options.headers, + ); + + const body = buildBody(options, headers); + + const controller = new AbortController(); + + const timeoutMs = options.timeoutMs ?? clientOptions.defaultTimeoutMs; + + const timeoutId = setTimeout(() => controller.abort(), timeoutMs); + + const isServer = typeof window === "undefined"; + + const cache = + options.cache ?? (isServer && options.next ? "force-cache" : "no-store"); + + const init: NextRequestInit = { + method: options.method ?? (body === undefined ? "GET" : "POST"), + + headers, + signal: controller.signal, + cache, + }; + + if (body !== undefined) { + init.body = body; + } + + if (isServer && options.next !== undefined) { + init.next = options.next; + } + + try { + const response = await fetch(url.toString(), init); + + if (options.expectBinary) { + if (!response.ok) { + const rawText = await response.text().catch(() => ""); + + const contentType = response.headers.get("content-type") ?? ""; + + const errorData = parseErrorBody(rawText, contentType); + + processErrorResponse( + response, + errorData, + url, + options, + clientOptions, + ); + } + + return (await response.arrayBuffer()) as T; + } + + const contentType = response.headers.get("content-type") ?? ""; + + const rawText = await response.text().catch(() => ""); + + if (!response.ok) { + const errorData = parseErrorBody(rawText, contentType); + + processErrorResponse(response, errorData, url, options, clientOptions); + } + + const parsed = parseSuccessBody( + rawText, + contentType, + options.expectText ?? false, + ); + + return parsed as T; + } catch (error: unknown) { + if (error instanceof HttpError) { + throw error; + } + + if (isAbortError(error)) { + return processHttpError( + new HttpError( + 408, + { + message: "요청 시간이 초과되었습니다.", + + timeoutMs, + }, + url.toString(), + ), + options, + clientOptions, + ); + } + + if (extractErrorCode(error) === "ECONNREFUSED") { + return processHttpError( + new HttpError( + 503, + { + message: "백엔드 서버에 연결할 수 없습니다.", + }, + url.toString(), + ), + options, + clientOptions, + ); + } + + return processHttpError( + new HttpError( + 0, + { + message: "네트워크 요청을 처리하지 못했습니다.", + + cause: error, + }, + url.toString(), + ), + options, + clientOptions, + ); + } finally { + clearTimeout(timeoutId); + } + }; +}; + +export const createHttpClient = ( + baseUrl: string, + options: HttpClientOptions = {}, +) => { + const request = createRequest(baseUrl, createResolvedOptions(options)); + + const get = ( + path: string, + requestOptions?: RequestOptionsWithoutBody, + ): Promise => { + return request(path, { + ...(requestOptions ?? {}), + method: "GET", + }); + }; + + const post = ( + path: string, + json?: unknown, + requestOptions?: RequestOptionsWithoutBody, + ): Promise => { + return request(path, { + ...(requestOptions ?? {}), + method: "POST", + json, + }); + }; + + const put = ( + path: string, + json?: unknown, + requestOptions?: RequestOptionsWithoutBody, + ): Promise => { + return request(path, { + ...(requestOptions ?? {}), + method: "PUT", + json, + }); + }; + + const patch = ( + path: string, + json?: unknown, + requestOptions?: RequestOptionsWithoutBody, + ): Promise => { + return request(path, { + ...(requestOptions ?? {}), + method: "PATCH", + json, + }); + }; + + const del = ( + path: string, + requestOptions?: DeleteRequestOptions, + ): Promise => { + return request(path, { + ...(requestOptions ?? {}), + method: "DELETE", + }); + }; + + const postForm = ( + path: string, + form: FormData, + requestOptions?: RequestOptionsWithoutBody, + ): Promise => { + return request(path, { + ...(requestOptions ?? {}), + method: "POST", + form, + }); + }; + + const putForm = ( + path: string, + form: FormData, + requestOptions?: RequestOptionsWithoutBody, + ): Promise => { + return request(path, { + ...(requestOptions ?? {}), + method: "PUT", + form, + }); + }; + + return { + request, + get, + post, + put, + patch, + del, + postForm, + putForm, + }; +}; + +export type HttpClient = ReturnType; diff --git a/src/http/http-util.ts b/src/http/http-util.ts new file mode 100644 index 0000000..d001cc5 --- /dev/null +++ b/src/http/http-util.ts @@ -0,0 +1,92 @@ +import { HttpError } from "./http-client.js"; +import { getServerMessage } from "./error-policy.js"; + +export const UNKNOWN_HTTP_ERROR = "UNKNOWN_HTTP_ERROR"; + +export const NONE_HTTP_ERROR = "NONE_HTTP_ERROR"; + +export type ApiError = { + status: number; + code: string; + message: string; +}; + +export type ApiErrorOptions = { + fallbackMessage?: string; + debug?: boolean; +}; + +export const apiError = ( + error: unknown, + options: ApiErrorOptions = {}, +): ApiError => { + const { fallbackMessage = "요청 처리에 실패했습니다.", debug = false } = + options; + + if (error instanceof HttpError) { + const data = error.data as { + code?: unknown; + detail?: unknown; + message?: unknown; + errMessage?: unknown; + } | null; + + const code = + typeof data?.code === "string" ? data.code : UNKNOWN_HTTP_ERROR; + + const message = + (typeof data?.detail === "string" && data.detail) || + getServerMessage(error.data) || + (typeof data?.errMessage === "string" && data.errMessage) || + `HTTP ${error.status}`; + + if (debug) { + console.groupCollapsed(`[API ERROR] ${error.status} / ${code}`); + console.log("url:", error.url); + + if (error.traceId) { + console.log("traceId:", error.traceId); + } + + console.log("raw data:", error.data); + console.groupEnd(); + } + + return { + status: error.status, + code, + message, + }; + } + + if (debug) { + console.error("[NON-HTTP ERROR]", error); + } + + return { + status: 500, + code: NONE_HTTP_ERROR, + message: fallbackMessage, + }; +}; + +export const errorToResponse = (error: unknown): Response => { + if (error instanceof HttpError) { + const payload = error.data ?? { + message: "서버에서 오류 응답을 받았습니다.", + }; + + return Response.json(payload, { + status: error.status, + }); + } + + return Response.json( + { + message: "서버 내부 오류가 발생했습니다.", + }, + { + status: 500, + }, + ); +}; diff --git a/src/http/index.ts b/src/http/index.ts new file mode 100644 index 0000000..70bc759 --- /dev/null +++ b/src/http/index.ts @@ -0,0 +1,4 @@ +// src/http/index.ts +export * from "./http-client.js"; +export * from "./error-policy.js"; +export * from "./http-util.js"; diff --git a/src/index.ts b/src/index.ts index e050bc4..f397f5f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,4 +3,4 @@ export type * from "./types.js"; export * from "./object.js"; export * from "./url.js"; export * from "./date.js"; -export * from "./string.js"; \ No newline at end of file +export * from "./string.js"; diff --git a/src/object.ts b/src/object.ts index 9b30821..444aab6 100644 --- a/src/object.ts +++ b/src/object.ts @@ -1,27 +1,21 @@ -export function getKeyByValue< - const T extends Record, ->( - map: T, - value: T[keyof T], +export function getKeyByValue>( + map: T, + value: T[keyof T], ): keyof T | undefined { const entry = Object.entries(map).find( - ([, currentValue]) => currentValue === value, + ([, currentValue]) => currentValue === value, ); - return entry - ? (entry[0] as keyof T) - : undefined; + return entry ? (entry[0] as keyof T) : undefined; } export function getNumberKeyByValue( - map: Record, - value: string, + map: Record, + value: string, ): number | undefined { const entry = Object.entries(map).find( - ([, currentValue]) => currentValue === value, + ([, currentValue]) => currentValue === value, ); - return entry - ? Number(entry[0]) - : undefined; -} \ No newline at end of file + return entry ? Number(entry[0]) : undefined; +} diff --git a/src/query/index.ts b/src/query/index.ts new file mode 100644 index 0000000..6836eea --- /dev/null +++ b/src/query/index.ts @@ -0,0 +1,5 @@ +"use client"; + +export * from "./query-client.js"; +export * from "./query-provider.js"; +export * from "./query-loading.js"; diff --git a/src/query/query-client.ts b/src/query/query-client.ts new file mode 100644 index 0000000..883c2a7 --- /dev/null +++ b/src/query/query-client.ts @@ -0,0 +1,38 @@ +import { QueryClient, type QueryClientConfig } from "@tanstack/react-query"; + +export const DEFAULT_QUERY_RETRY_COUNT = 1; + +export const DEFAULT_QUERY_STALE_TIME_MS = 30_000; + +export const DEFAULT_QUERY_GC_TIME_MS = 5 * 60_000; + +export const createQueryClient = ( + config: QueryClientConfig = {}, +): QueryClient => { + const defaultOptions = config.defaultOptions; + + return new QueryClient({ + ...config, + + defaultOptions: { + ...defaultOptions, + + queries: { + retry: DEFAULT_QUERY_RETRY_COUNT, + + refetchOnWindowFocus: false, + refetchOnReconnect: false, + + staleTime: DEFAULT_QUERY_STALE_TIME_MS, + + gcTime: DEFAULT_QUERY_GC_TIME_MS, + + /* + * 프로젝트에서 전달한 설정을 + * 공통 기본값보다 우선한다. + */ + ...defaultOptions?.queries, + }, + }, + }); +}; diff --git a/src/query/query-loading.tsx b/src/query/query-loading.tsx new file mode 100644 index 0000000..f80ed1b --- /dev/null +++ b/src/query/query-loading.tsx @@ -0,0 +1,76 @@ +"use client"; + +import { useIsFetching, useIsMutating } from "@tanstack/react-query"; + +import { useEffect } from "react"; + +export interface QueryLoadingMeta extends Record { + /** + * true이면 해당 Query 또는 Mutation을 + * 전역 Loading에서 제외한다. + */ + ignoreGlobalLoading?: boolean; +} + +/** + * useQuery와 useMutation의 meta 타입을 + * 동일하게 적용한다. + */ +declare module "@tanstack/react-query" { + interface Register { + queryMeta: QueryLoadingMeta; + mutationMeta: QueryLoadingMeta; + } +} + +const shouldTrackGlobalLoading = ( + meta: QueryLoadingMeta | undefined, +): boolean => { + return meta?.ignoreGlobalLoading !== true; +}; + +export type QueryLoadingState = { + fetchingCount: number; + mutatingCount: number; + totalCount: number; + isLoading: boolean; +}; + +export const useQueryLoading = (): QueryLoadingState => { + const fetchingCount = useIsFetching({ + predicate: (query) => { + return shouldTrackGlobalLoading(query.options.meta); + }, + }); + + const mutatingCount = useIsMutating({ + predicate: (mutation) => { + return shouldTrackGlobalLoading(mutation.options.meta); + }, + }); + + const totalCount = fetchingCount + mutatingCount; + + return { + fetchingCount, + mutatingCount, + totalCount, + isLoading: totalCount > 0, + }; +}; + +export type QueryLoadingSyncProps = { + onLoadingChange: (isLoading: boolean) => void; +}; + +export const QueryLoadingSync = ({ + onLoadingChange, +}: QueryLoadingSyncProps) => { + const { isLoading } = useQueryLoading(); + + useEffect(() => { + onLoadingChange(isLoading); + }, [isLoading, onLoadingChange]); + + return null; +}; diff --git a/src/query/query-provider.tsx b/src/query/query-provider.tsx new file mode 100644 index 0000000..6812861 --- /dev/null +++ b/src/query/query-provider.tsx @@ -0,0 +1,39 @@ +"use client"; + +import { + QueryClientProvider, + type QueryClient, + type QueryClientConfig, +} from "@tanstack/react-query"; + +import { useState, type ReactNode } from "react"; + +import { createQueryClient } from "./query-client.js"; + +export type QueryProviderProps = { + children: ReactNode; + + /** + * 외부에서 생성한 QueryClient를 + * 직접 전달할 때 사용한다. + */ + client?: QueryClient; + + /** + * 내부 QueryClient 생성 설정이다. + * 최초 생성 시에만 사용한다. + */ + clientConfig?: QueryClientConfig; +}; + +export const QueryProvider = ({ + children, + client: providedClient, + clientConfig, +}: QueryProviderProps) => { + const [client] = useState(() => { + return providedClient ?? createQueryClient(clientConfig); + }); + + return {children}; +}; diff --git a/src/security/index.ts b/src/security/index.ts new file mode 100644 index 0000000..790d87a --- /dev/null +++ b/src/security/index.ts @@ -0,0 +1 @@ +export * from "./security.js"; diff --git a/src/security/security.ts b/src/security/security.ts new file mode 100644 index 0000000..3d6a3ec --- /dev/null +++ b/src/security/security.ts @@ -0,0 +1,315 @@ +import CryptoJS from "crypto-js"; + +export type WordArray = CryptoJS.lib.WordArray; + +export type SecurityConfigError = { + message: string; + + keyBytes: number; + ivBytes: number; + + validKeyBytes: readonly number[]; + requiredIvBytes: number; +}; + +export type SecurityDecryptError = { + error: unknown; + inputPreview: string; +}; + +export type CreateSecurityOptions = { + /** + * 기존 문자열을 그대로 UTF-8 WordArray로 변환한다. + */ + key: string; + + /** + * 기존 문자열을 그대로 UTF-8 WordArray로 변환한다. + */ + iv: string; + + onInvalidConfig?: (error: SecurityConfigError) => void; + + onDecryptError?: (error: SecurityDecryptError) => void; +}; + +const VALID_AES_KEY_BYTES = [16, 24, 32] as const; + +const AES_IV_BYTES = 16; + +const createConfigError = ( + keyBytes: number, + ivBytes: number, +): SecurityConfigError => { + const message = [ + "AES 설정이 올바르지 않습니다.", + `KEY: ${keyBytes} bytes (허용: ${VALID_AES_KEY_BYTES.join(", ")})`, + `IV: ${ivBytes} bytes (필수: ${AES_IV_BYTES})`, + ].join("\n"); + + return { + message, + keyBytes, + ivBytes, + validKeyBytes: VALID_AES_KEY_BYTES, + requiredIvBytes: AES_IV_BYTES, + }; +}; + +export const createSecurity = (options: CreateSecurityOptions) => { + const key = CryptoJS.enc.Utf8.parse(options.key); + + const iv = CryptoJS.enc.Utf8.parse(options.iv); + + const validKey = VALID_AES_KEY_BYTES.includes(key.sigBytes as 16 | 24 | 32); + + const validIv = iv.sigBytes === AES_IV_BYTES; + + if (!validKey || !validIv) { + const configError = createConfigError(key.sigBytes, iv.sigBytes); + + options.onInvalidConfig?.(configError); + + throw new Error(configError.message); + } + + const encodeUtf8 = (input: WordArray): string => { + return CryptoJS.enc.Utf8.stringify(input); + }; + + const decodeUtf8 = (input: string): WordArray => { + return CryptoJS.enc.Utf8.parse(input); + }; + + const encodeHex = (input: WordArray): string => { + return CryptoJS.enc.Hex.stringify(input); + }; + + const decodeHex = (input: string): WordArray => { + return CryptoJS.enc.Hex.parse(input); + }; + + const hasSpecialChars = (input: string): boolean => { + return input.includes("\u200b") || input.includes("\u200c"); + }; + + const convertFromSpecialChars = (input: string): string => { + return input + .split("ㅤ") + .map((binary) => { + return binary.replace(/\u200b/g, "0").replace(/\u200c/g, "1"); + }) + .map((binary) => { + return String.fromCharCode(Number.parseInt(binary, 2)); + }) + .join(""); + }; + + const encodeBase64 = (input: WordArray): string => { + return CryptoJS.enc.Base64.stringify(input); + }; + + const decodeBase64 = (input: string): WordArray => { + const normalized = hasSpecialChars(input) + ? convertFromSpecialChars(input) + : input; + + return CryptoJS.enc.Base64.parse(normalized); + }; + + const encodeBase64Url = (input: WordArray): string => { + return CryptoJS.enc.Base64url.stringify(input); + }; + + const decodeBase64Url = (input: string): WordArray => { + const normalized = hasSpecialChars(input) + ? convertFromSpecialChars(input) + : input; + + return CryptoJS.enc.Base64url.parse(normalized); + }; + + const encodeBase64Utf8 = (input: string): string => { + return encodeBase64(decodeUtf8(input)); + }; + + const decodeBase64Utf8 = (input: string): string => { + return encodeUtf8(decodeBase64(input)); + }; + + const encodeBase64UrlUtf8 = (input: string): string => { + return encodeBase64Url(decodeUtf8(input)); + }; + + const decodeBase64UrlUtf8 = (input: string): string => { + return encodeUtf8(decodeBase64Url(input)); + }; + + const encrypt = (input: WordArray): WordArray => { + const encrypted = CryptoJS.AES.encrypt(input, key, { + iv, + padding: CryptoJS.pad.Pkcs7, + mode: CryptoJS.mode.CBC, + }); + + return encrypted.ciphertext; + }; + + const decrypt = (input: WordArray): WordArray => { + const cipherParams = CryptoJS.lib.CipherParams.create({ + ciphertext: input, + }); + + return CryptoJS.AES.decrypt(cipherParams, key, { + iv, + padding: CryptoJS.pad.Pkcs7, + mode: CryptoJS.mode.CBC, + }); + }; + + const encryptBase64 = (input: string): string => { + return encodeBase64(encrypt(decodeUtf8(input))); + }; + + const decryptBase64 = (input: string): string => { + try { + return encodeUtf8(decrypt(decodeBase64(input))); + } catch (error: unknown) { + const inputPreview = `${input?.substring(0, 50) ?? ""}...`; + + if (options.onDecryptError) { + options.onDecryptError({ + error, + inputPreview, + }); + } else { + console.error("Security.decryptBase64 오류:", { + input: inputPreview, + error: error instanceof Error ? error.message : String(error), + }); + } + + throw error; + } + }; + + const encryptBase64Url = (input: string): string => { + return encodeBase64Url(encrypt(decodeUtf8(input))); + }; + + const decryptBase64Url = (input: string): string => { + return encodeUtf8(decrypt(decodeBase64Url(input))); + }; + + const encryptBase64Object = (input: unknown): string => { + return encryptBase64(JSON.stringify(input)); + }; + + const decryptBase64Object = (input: string): T => { + return JSON.parse(decryptBase64(input)) as T; + }; + + const encryptBase64UrlObject = (input: unknown): string => { + return encryptBase64Url(JSON.stringify(input)); + }; + + const decryptBase64UrlObject = (input: string): T => { + return JSON.parse(decryptBase64Url(input)) as T; + }; + + const convertUint8ArrayToWordArray = (input: Uint8Array): WordArray => { + const words: number[] = []; + + for (let index = 0; index < input.length; index += 1) { + const wordIndex = index >>> 2; + + const bitOffset = 24 - (index % 4) * 8; + + words[wordIndex] = (words[wordIndex] ?? 0) | (input[index]! << bitOffset); + } + + return CryptoJS.lib.WordArray.create(words, input.length); + }; + + const convertWordArrayToUint8Array = (input: WordArray): Uint8Array => { + const bytes = new Uint8Array(input.sigBytes); + + for (let index = 0; index < input.sigBytes; index += 1) { + const word = input.words[index >>> 2] ?? 0; + + const bitOffset = 24 - (index % 4) * 8; + + bytes[index] = (word >>> bitOffset) & 0xff; + } + + return bytes; + }; + + const computeSha256 = (input: WordArray): WordArray => { + return CryptoJS.SHA256(input); + }; + + const computeSha256Hex = (input: WordArray): string => { + return encodeHex(computeSha256(input)); + }; + + const computeHmacSha256 = ( + input: WordArray, + hmacKey: WordArray, + ): WordArray => { + return CryptoJS.HmacSHA256(input, hmacKey); + }; + + const computeHmacSha256Hex = ( + input: WordArray, + hmacKey: WordArray, + ): string => { + return encodeHex(computeHmacSha256(input, hmacKey)); + }; + + return Object.freeze({ + encryptBase64UrlObject, + decryptBase64UrlObject, + + encryptBase64Object, + decryptBase64Object, + + encryptBase64Url, + decryptBase64Url, + + encryptBase64, + decryptBase64, + + encrypt, + decrypt, + + convertUint8ArrayToWordArray, + convertWordArrayToUint8Array, + + computeHmacSha256Hex, + computeHmacSha256, + + computeSha256Hex, + computeSha256, + + encodeBase64UrlUtf8, + decodeBase64UrlUtf8, + + encodeBase64Url, + decodeBase64Url, + + encodeBase64Utf8, + decodeBase64Utf8, + + encodeBase64, + decodeBase64, + + encodeHex, + decodeHex, + + encodeUtf8, + decodeUtf8, + }); +}; + +export type SecurityApi = ReturnType; diff --git a/src/server/client-ip.ts b/src/server/client-ip.ts new file mode 100644 index 0000000..7b63739 --- /dev/null +++ b/src/server/client-ip.ts @@ -0,0 +1,57 @@ +export type HeaderReader = Pick; + +export type RequestWithHeaders = { + headers: HeaderReader; +}; + +export type ClientIpSource = HeaderReader | RequestWithHeaders; + +const resolveHeaders = (source: ClientIpSource): HeaderReader => { + return "headers" in source ? source.headers : source; +}; + +/** + * 신뢰할 수 있는 리버스 프록시가 전달한 헤더에서 + * 클라이언트 IP를 추출한다. + * + * x-forwarded-for는 첫 번째 값을 사용한다. + */ +export const getClientIp = (source: ClientIpSource): string | null => { + const headers = resolveHeaders(source); + + const forwardedFor = headers.get("x-forwarded-for"); + + if (forwardedFor) { + const firstAddress = forwardedFor.split(",")[0]?.trim(); + + if (firstAddress) { + return firstAddress; + } + } + + const realIp = headers.get("x-real-ip")?.trim(); + + if (realIp) { + return realIp; + } + + const cloudflareIp = headers.get("cf-connecting-ip")?.trim(); + + if (cloudflareIp) { + return cloudflareIp; + } + + const forwarded = headers.get("forwarded"); + + if (forwarded) { + const matched = forwarded.match(/for="?([^;,\s"]+)"?/i); + + const forwardedIp = matched?.[1]?.trim(); + + if (forwardedIp) { + return forwardedIp; + } + } + + return null; +}; diff --git a/src/server/index.ts b/src/server/index.ts new file mode 100644 index 0000000..9a3e538 --- /dev/null +++ b/src/server/index.ts @@ -0,0 +1 @@ +export * from "./client-ip.js"; diff --git a/src/string.ts b/src/string.ts index f54bb1c..60bb8e8 100644 --- a/src/string.ts +++ b/src/string.ts @@ -1,19 +1,13 @@ /** * 문자열이 null, undefined 또는 공백인지 확인한다. */ -export function isBlank( - value: string | null | undefined, -): boolean { - return value === null - || value === undefined - || value.trim().length === 0; +export function isBlank(value: string | null | undefined): boolean { + return value === null || value === undefined || value.trim().length === 0; } /** * 문자열에 공백이 아닌 문자가 있는지 확인한다. */ -export function isNotBlank( - value: string | null | undefined, -): boolean { +export function isNotBlank(value: string | null | undefined): boolean { return !isBlank(value); -} \ No newline at end of file +} diff --git a/src/types.ts b/src/types.ts index f924cd2..f14dd10 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,9 +1,5 @@ export type ValueOf = T[keyof T]; -export type EnumLikeKey< - T extends Record, -> = keyof T; +export type EnumLikeKey> = keyof T; -export type EnumLikeValue< - T extends Record, -> = ValueOf; \ No newline at end of file +export type EnumLikeValue> = ValueOf; diff --git a/src/ui/class-name.ts b/src/ui/class-name.ts new file mode 100644 index 0000000..b9109fd --- /dev/null +++ b/src/ui/class-name.ts @@ -0,0 +1,13 @@ +import { clsx, type ClassValue } from "clsx"; + +import { twMerge } from "tailwind-merge"; + +/** + * 조건부 className을 결합하고 + * 충돌하는 Tailwind CSS 클래스를 정리한다. + */ +export const cn = (...inputs: ClassValue[]): string => { + return twMerge(clsx(inputs)); +}; + +export type { ClassValue }; diff --git a/src/ui/index.ts b/src/ui/index.ts new file mode 100644 index 0000000..94a3337 --- /dev/null +++ b/src/ui/index.ts @@ -0,0 +1 @@ +export * from "./class-name.js"; diff --git a/src/url.ts b/src/url.ts index 90e244f..bd9989f 100644 --- a/src/url.ts +++ b/src/url.ts @@ -1,15 +1,11 @@ -export type QueryParameterValue = - | string - | string[] - | undefined; +export type QueryParameterValue = string | string[] | undefined; -export type QueryParameters = - Record; +export type QueryParameters = Record; export function buildUrlWithParams( - targetPath: string, - parameters: QueryParameters, - extra?: Record, + targetPath: string, + parameters: QueryParameters, + extra?: Record, ): string { const searchParams = new URLSearchParams(); @@ -33,7 +29,5 @@ export function buildUrlWithParams( const queryString = searchParams.toString(); - return queryString - ? `${targetPath}?${queryString}` - : targetPath; -} \ No newline at end of file + return queryString ? `${targetPath}?${queryString}` : targetPath; +} diff --git a/tsconfig.json b/tsconfig.json index 0ce3bf9..26c5099 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -4,6 +4,8 @@ "module": "NodeNext", "moduleResolution": "NodeNext", + "jsx": "react-jsx", + "rootDir": "./src", "outDir": "./dist", @@ -20,7 +22,8 @@ "forceConsistentCasingInFileNames": true }, "include": [ - "src/**/*.ts" + "src/**/*.ts", + "src/**/*.tsx" ], "exclude": [ "node_modules",