npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

sp-net-core

v0.1.2

Published

Reusable networking core utilities for SP projects.

Readme

sp-net-core

SP 제품군에서 재사용 가능한 네트워크 코어 유틸리티를 모듈화한 실험 프로젝트입니다. 클라이언트 앱에서 HTTP 요청 흐름과 서버 설정을 일관되게 구성할 수 있도록 하는 것을 목표로 하며, 기존 앱 코드와 직접 연결되어 있지는 않습니다.

  • ServerRegistry: 서버 템플릿을 등록하고 환경별 설정을 해석하는 경량 레지스트리.
  • ApiClient: Axios 기반 HTTP 클라이언트. 토큰 공급자와 세션 만료 훅, URL 변환 함수를 외부에서 주입합니다.
  • SessionManager: access/refresh 토큰을 관리하고 만료 전에 자동 갱신하는 OIDC 지향 세션 매니저.
  • OidcTokenRefresher: refresh token으로 새로운 access token을 발급받는 HTTP 유틸리티.
  • Interceptors: 인증 토큰 주입, 오류 매핑을 담당하는 인터셉터 유틸리티.
  • ApiError 계열 클래스: 다양한 HTTP 오류 상황을 구조화된 에러 객체로 변환합니다.
  • Logger: 모듈 단위 로그 출력을 위한 간단한 래퍼.

설치 및 빌드

현재는 예제와 테스트를 위한 개발용 패키지입니다.

pnpm install
pnpm --filter sp-net-core test

Vitest 설정(vitest.config.ts)이 포함되어 있으며, 필요 시 pnpm --filter sp-net-core test --watch로 자동 실행을 유지할 수 있습니다.

핵심 개념

1. ServerRegistry

서버별 공통 설정을 중앙에서 관리합니다. 템플릿 등록 후 resolve를 호출하면 ServerConfig가 반환됩니다.

import { ServerRegistry } from 'sp-net-core';

const registry = new ServerRegistry([
  { id: 'app', name: 'App API', baseURL: 'https://api.example.com', timeout: 5000 },
]);

const config = registry.resolve('app');

resolve에 두 번째 인자로 덮어쓰기 옵션을 전달하면 일회성 override가 가능합니다.

2. ApiClient + AccessTokenProvider

ApiClient는 서버 설정과 토큰 공급자를 입력받아 요청 시점에 Authorization 헤더를 주입합니다. 토큰 공급자는 getAccessTokenonTokenInvalid 인터페이스를 충족하면 됩니다.

import { ApiClient, defaultServerRegistry } from 'sp-net-core';

defaultServerRegistry.registerTemplate({
  id: 'math',
  name: 'Math API',
  baseURL: 'https://math.example.com',
});

const client = new ApiClient({
  serverConfig: defaultServerRegistry.resolve('math'),
  tokenProvider: {
    async getAccessToken() {
      return { token: 'mock-token', expiresAt: Date.now() + 60_000 };
    },
    onTokenInvalid() {
      console.log('token expired → trigger sign-out');
    },
  },
});

const response = await client.get('/status');

3. Interceptors & 오류 매핑

applyInterceptors는 Axios 인스턴스에 요청/응답 훅을 등록합니다. 커스텀 오류 매핑 함수를 전달하면 각 서비스 규격에 맞는 ApiError 하위 클래스를 직접 생성할 수도 있습니다.

4. SessionManager + OIDC Refresh

SessionManager는 access/refresh 토큰을 캐싱하고 만료 전에 자동 갱신까지 수행합니다. refresh 로직은 TokenRefresher 인터페이스로 주입하며, 기본 제공되는 OidcTokenRefresher를 활용하면 OIDC 서버와 바로 연동할 수 있습니다.

import { SessionManager, InMemoryTokenStore, OidcTokenRefresher } from 'sp-net-core';

const sessionManager = new SessionManager({
  tokenStore: new InMemoryTokenStore(),
  tokenRefresher: new OidcTokenRefresher({
    tokenEndpoint: 'https://auth.example.com/oauth2/token',
    clientId: 'web-client',
    clientSecret: process.env.OIDC_CLIENT_SECRET,
  }),
});

sessionManager.addListener((session) => {
  console.log('session updated', session?.accessToken);
});

await sessionManager.setSession({
  accessToken: 'init-access-token',
  refreshToken: 'init-refresh-token',
});

5. 에러 클래스 사용

ApiError, AuthenticationError 등의 클래스는 HTTP 오류를 유형별로 다룰 수 있게 도와줍니다.

import { createErrorFromStatus } from 'sp-net-core';

try {
  await client.get('/forbidden');
} catch (error) {
  const apiError = createErrorFromStatus(error.status, error.message, error.details);
  if (apiError.name === 'AuthorizationError') {
    // 접근 권한 없음 처리
  }
}

예제

  • examples/basic-usage.ts: 템플릿 등록 후 간단한 GET 요청 흐름.
  • examples/custom-token-provider.ts: 커스텀 토큰 공급자, 세션 만료 처리 예제.

테스트

  • tests/ServerRegistry.test.ts: 템플릿 등록과 override 동작 확인.
  • tests/ApiClient.test.ts: 토큰 헤더 주입 및 URL 변환 동작 확인.

Vitest를 사용하며 루트 프로젝트에서 pnpm --filter sp-net-core test로 실행할 수 있습니다.

제한 사항 및 TODO

  • NextAuth/React Query 연동은 포함되어 있지 않습니다. 기존 프로젝트에서는 어댑터를 별도로 구현해야 합니다.
  • Axios 이외의 HTTP 클라이언트는 지원하지 않습니다.
  • 토큰 공급자/세션 관리 전략은 애플리케이션에서 직접 구현해야 합니다.

향후 작업으로는 React Query 연동 헬퍼, NextAuth 통합 샘플, 브라우저 포커스 감지 유틸을 추가로 제공할 예정입니다.

배포

새 버전을 게시하기 전에 package.json의 버전을 업데이트하세요.

npm install
npm run publish:release

스크립트는 루트에서 빌드를 수행한 뒤 npm publish --access public을 실행합니다. 2단계 배포(빌드 → 검증 → 퍼블리시)를 직접 처리하고 싶다면 scripts/publish.sh를 참고하세요.