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

sws-notification-center

v0.1.2

Published

مرکز اعلان‌های درون‌برنامه‌ای سرویس‌های SWS با جریان SSE، نوسازی خودکار توکن و اعلان‌های Tailwind.

Readme

sws-notification-center

Headless REST hooks (React Query v5)

Install in DRIVE, CALENDAR, MEET, or another host application:

npm install sws-notification-center @tanstack/react-query

Import from sws-notification-center/react-query. This entry point has no components, CSS, toast rendering, or SSE connection. Use your application's existing QueryClientProvider (or add one) and build your own UI around the returned query and mutation states.

import { useMemo } from 'react';
import {
  createNotificationClient,
  useNotifications,
  useMarkNotificationAsRead,
  useMarkAllNotificationsAsRead,
  useDeleteNotification,
  useDeleteAllNotifications,
} from 'sws-notification-center/react-query';

// Call this custom hook beneath your application's QueryClientProvider.
export function useDriveNotifications(userId: string) {
  const client = useMemo(() => createNotificationClient({
    baseUrl: 'https://your-api.example',
    userId,
    serviceName: 'DRIVE', // use CALENDAR, MEET, ADMIN, or SSO in those apps
    // Cookie auth is enabled by default (credentials: 'include').
    // For bearer auth, read your current token on every request:
    // getHeaders: () => ({ Authorization: `Bearer ${authStore.getAccessToken()}` }),
    // fetcher: authenticatedFetch, // optional host wrapper with token refresh
  }), [userId]);

  const list = useNotifications(client, { limit: 20, offset: 0 }, {
    staleTime: 30_000,
    // enabled, select, refetchInterval, and other React Query options are supported.
  });
  const read = useMarkNotificationAsRead(client);
  const readAll = useMarkAllNotificationsAsRead(client);
  const remove = useDeleteNotification(client);
  const removeAll = useDeleteAllNotifications(client);

  return { list, read, readAll, remove, removeAll };
}
  • List data: list.data?.results, count, next, previous. Use isPending, isFetching, and error for your own loading/error UI. Add status: 'UNREAD' or 'READ' to filter; change offset to paginate. created_at remains the API's Unix-seconds string (new Date(Number(item.created_at) * 1000)).
  • Read one: read.mutate(notificationId); read the entire service: readAll.mutate().
  • Delete one: remove.mutate(notificationId); delete the entire service: removeAll.mutate(). Bulk actions affect all stored notifications in that service, including items outside the current page/filter.
  • Mutations expose isPending, error, mutateAsync, and standard mutation callbacks. Successful mutations invalidate all pages and status filters for the same backend/user/service and refetch active lists. Consumer onSuccess callbacks run after invalidation. No optimistic updates are applied.
  • Query keys isolate backend, user, service, pagination, and status. Names are case-insensitive. Recreate the client when its backend/user/service changes. Clear private queries on logout with queryClient.removeQueries({ queryKey: notificationKeys.all }).
  • Bearer tokens are never stored in query keys. getHeaders may be asynchronous. REST requests do not refresh tokens themselves; pass your authenticated fetch wrapper if needed. NotificationApiError exposes HTTP status and parsed error body; network and abort errors propagate normally.
  • The documented backend currently accepts ADMIN, SSO, DRIVE, MEET, and CALENDAR. Custom service names require backend support.

The client also exposes list, markAsRead, markAllAsRead, deleteNotification, and deleteAllNotifications for use outside React. notificationListOptions(client, params) supports queryClient.fetchQuery and prefetchQuery; notificationKeys.scope(client) supports manual invalidation (for example, from your existing SSE onNotification callback).

The original SSE hooks and UI exports below remain available. Their local markAsRead, markAllAsRead, and clear actions only change the in-memory SSE store; use the REST hooks above for server persistence. React Query is an optional peer dependency for consumers using only those original exports.

مرکز اعلان‌های درون‌برنامه‌ای سرویس‌های SWS برای React. این کتابخانه به جریان Server-Sent Events (SSE) وصل می‌شود، در صورت رد شدن توکن دسترسی آن را از طریق SSO نوسازی می‌کند و هر رویداد دریافتی را به‌شکل اعلان نمایش می‌دهد. رابط و پیام‌های خود کتابخانه فارسی و راست‌به‌چپ هستند.

  • سازگار با React 18 و 19، TypeScript و خروجی‌های ESM، CJS و فایل‌های تعریف نوع
  • استایل‌های Tailwind CSS v4 با پیشوند sws: و بدون بازنشانی سراسری CSS
  • اتصال SSE بر پایهٔ fetch برای پشتیبانی از سربرگ Authorization
  • نوسازی خودکار توکن با POST /api/sso/v1/profile/refresh-token/ و یکی‌کردن درخواست‌های هم‌زمان
  • هوک بدون رابط و Provider برای ساخت صندوق اعلان سفارشی

نصب

npm install sws-notification-center

راه‌اندازی سریع

import { NotificationCenter } from 'sws-notification-center';
import 'sws-notification-center/style.css';

export function App() {
  return (
    <NotificationCenter
      baseUrl="https://sws-stage-edgemodule.mobintadbir.ir"
      userId={user.id}
      serviceName="DRIVE"
      accessToken={tokens.access}
      refreshToken={tokens.refresh}
      onTokensRefreshed={(next) => saveTokens(next)}
      position="top-right"
      theme="system"
    />
  );
}

کامپوننت هنگام نصب به جریان وصل می‌شود، اعلان‌ها را نشان می‌دهد، در صورت قطع اتصال با تأخیر افزایشی دوباره تلاش می‌کند و هنگام حذف شدن جریان را می‌بندد. وارد کردن style.css لازم است. این فایل فقط استایل‌های دارای پیشوند sws:، متغیرهای CSS محدود به کتابخانه و انیمیشن‌ها را اضافه می‌کند.

رفتار توکن‌ها

  1. اتصال: درخواست GET {baseUrl}/api/notification/v1/notification/{user_id}/stream/{service_name}/ با Accept: text/event-stream و Authorization: Bearer <accessToken> ارسال می‌شود. نام سرویس در نشانی با حروف کوچک می‌آید؛ برای نمونه /stream/drive/.
  2. رد شدن توکن: اگر پاسخ 401 یا 403 باشد، مقدار { "refresh": "<refreshToken>" } به {baseUrl}/api/sso/v1/profile/refresh-token/ فرستاده می‌شود. پاسخ { access, refresh, token_id, is_lock } جایگزین توکن‌های حافظه می‌شود و اتصال بی‌درنگ تکرار می‌شود.
  3. ادامهٔ نشست: توکن‌های تازه در طول عمر کامپوننت حفظ می‌شوند. اتصال‌های بعدی از آن‌ها استفاده می‌کنند و درخواست نوسازی فقط پس از رد شدن دوبارهٔ توکن انجام می‌شود.
  4. ذخیره‌سازی: onTokensRefreshed جفت توکن تازه را برمی‌گرداند. آن را در برنامهٔ میزبان ذخیره کنید و توکن قدیمی را دوباره به پراپ‌ها ندهید.
  5. خطا: نبودن توکن نوسازی یا is_lock: true جریان را با NotificationCenterError و فراخوانی onError متوقف می‌کند. خطاهای موقت نوسازی با تأخیر افزایشی دوباره امتحان می‌شوند. برای توکن قفل‌شده، کد خطا token-locked است.

رویدادهای اعلان

جریان طبق قالب استاندارد SSE شامل event:، data:، id:، retry: و دیدگاه‌های : پردازش می‌شود. نمونهٔ دادهٔ سرور:

{
  "id": "b0d1…",
  "created_at": 1731234567.12,
  "service_name": "DRIVE",
  "audience": "USER",
  "status": "UNREAD",
  "data": { "message": "فایل تازه‌ای با شما به اشتراک گذاشته شد: Q3-report.pdf" }
}

data.message یا data.text، data.body و data.title متن اعلان را می‌سازند. data.title عنوان اختیاری است. دادهٔ متنی ساده نیز نمایش داده می‌شود. رویدادهای ضربان قلب (ping، heartbeat، open، connected، ready) نادیده گرفته می‌شوند. متن ارسالی از سرور همان‌طور که دریافت شده نمایش داده می‌شود؛ برای اعلان‌های فارسی، متن پیام را در سرور فارسی ارسال کنید.

پراپ‌ها

NotificationCenter پراپ‌های اتصال و رابط زیر را می‌پذیرد. نام‌ها و مقادیر قراردادی API انگلیسی باقی می‌مانند.

| پراپ اتصال | نوع | پیش‌فرض | توضیح | | --- | --- | --- | --- | | baseUrl | string | — | نشانی پایهٔ API | | userId | string | — | شناسهٔ صاحب جریان در مسیر درخواست | | serviceName | 'ADMIN' \| 'SSO' \| 'DRIVE' \| 'MEET' \| 'CALENDAR' \| string | — | نام سرویس؛ در مسیر به حروف کوچک تبدیل می‌شود | | accessToken | string | — | توکن دسترسی فعلی | | refreshToken | string | — | توکن مورد استفاده برای نوسازی | | refreshUrl | string | {baseUrl}/api/sso/v1/profile/refresh-token/ | نشانی سفارشی نوسازی | | enabled | boolean | true | توقف یا ادامهٔ جریان | | authScheme | string | 'Bearer' | شیوهٔ احراز هویت | | getAuthHeaders | (ctx) => headers | — | سربرگ‌های احراز هویت سفارشی | | requestHeaders | Record<string, string> | — | سربرگ‌های اضافی | | onTokensRefreshed | (tokens) => void | — | جفت توکن تازه | | onNotification | (notification) => void | — | هر اعلان دریافتی | | onStatusChange | (status) => void | — | وضعیت اتصال: idle \| connecting \| refreshing \| open \| reconnecting \| error \| closed | | onError | (error) => void | — | خطای NotificationCenterError با code و status | | maxNotifications | number | 100 | ظرفیت صندوق در حافظه | | reconnect | { initialDelayMs, maxDelayMs, factor } | 1000 / 30000 / 1.8 | تنظیم تأخیر اتصال دوباره | | debug | boolean | false | ثبت جزئیات در کنسول |

| پراپ رابط | نوع | پیش‌فرض | | --- | --- | --- | | position | top-right \| top-left \| top-center \| bottom-right \| bottom-left \| bottom-center | top-right | | maxToasts | number | 4 | | toastDuration | number \| false | 6000 | | theme | 'light' \| 'dark' \| 'system' | system | | showToasts | boolean | true | | showProgress | boolean | true | | markAsReadOnClick | boolean | true | | onNotificationClick | (notification) => void | — | | className | string | —؛ برای ظرف اعلان |

صندوق اعلان سفارشی

اگر اعلان‌های شناور و صندوق در بخش‌های متفاوت درخت React هستند، از Provider استفاده کنید:

import {
  NotificationProvider,
  NotificationToastViewport,
  useNotificationCenter,
} from 'sws-notification-center';

function Inbox() {
  const { unreadCount, markAllAsRead } = useNotificationCenter();
  return (
    <button onClick={markAllAsRead}>
      {unreadCount} اعلان خوانده‌نشده
    </button>
  );
}

export function App() {
  return (
    <NotificationProvider
      baseUrl="https://sws-stage-edgemodule.mobintadbir.ir"
      userId={user.id}
      serviceName="CALENDAR"
      accessToken={tokens.access}
      refreshToken={tokens.refresh}
      onTokensRefreshed={(next) => saveTokens(next)}
    >
      <Inbox />
      <NotificationToastViewport position="bottom-right" theme="dark" />
    </NotificationProvider>
  );
}

useNotificationStream(config) نسخهٔ بدون رابط Provider است و همان وضعیت و کنترل‌ها، از جمله connect، disconnect، refreshTokens، markAsRead، markAllAsRead، clear و dismissToast را برمی‌گرداند.

استایل و پیشوند sws:

کلاس‌ها با prefix(sws) در Tailwind v4 ساخته می‌شوند؛ مانند sws:flex و sws:hover:bg-black. مصرف‌کننده نیازی به نصب Tailwind ندارد. متغیرهای پوسته در .sws-root تعریف شده‌اند:

.sws-root {
  --sws-surface: #0b1220;
  --sws-text: #e2e8f0;
  --sws-border: rgba(148, 163, 184, 0.2);
  --sws-accent: #38bdf8;
  --sws-radius: 12px;
  --sws-font: "Vazirmatn", sans-serif;
}

رنگ‌های اختصاصی سرویس‌های DRIVE، MEET، CALENDAR، SSO و ADMIN نیز در استایل تعریف شده و قابل بازنویسی هستند. اگر فونت فارسی دلخواه دارید، آن را در برنامهٔ خود بارگذاری کنید و مقدار --sws-font را تغییر دهید.

محیط آزمایش

مخزن شامل صفحهٔ پیش‌نمایش و API آزمایشی است. دمو فونت وزیرمتن را از فایل محلی خودش بارگذاری می‌کند. API آزمایشی توکن نخست را رد می‌کند تا روند نوسازی قابل مشاهده باشد.

npm install
npm run dev

برای اجرای جداگانه از npm run dev:app و npm run mock استفاده کنید. در دمو می‌توانید اعلان بفرستید، چند اعلان پیاپی بسازید، توکن‌ها را باطل کنید، جریان را متوقف یا ادامه دهید و پوسته و سرویس را تغییر دهید.

برای آزمایش استیج، «API استیج» را در بخش منبع انتخاب کنید، شناسهٔ کاربر و توکن دسترسی را وارد کنید و «اتصال پیش‌نمایش» را بزنید. نشانی دقیق GET پیش از اتصال نشان داده می‌شود. توکن نوسازی اختیاری است و فقط بعد از پاسخ 401 یا 403 به‌کار می‌رود. اطلاعات استیج فقط در فرم مرورگر وارد می‌شوند و در مخزن قرار ندارند.

برای ساخت اعلان استیج، در کارت «ارسال اعلان به استیج» شناسهٔ سازمان، مقدار auth-header، مخاطب و پیام را وارد کنید. شناسهٔ کاربر و سرویس از فرم اتصال گرفته می‌شوند و هر ارسال یک UUID تازه می‌سازد. در توسعهٔ محلی، درخواست‌های استیج از پراکسی‌های Vite عبور می‌کنند تا محدودیت CORS مرورگر مانع آزمایش نشود. کتابخانهٔ منتشرشده درخواست SSE را مستقیم به baseUrl تنظیم‌شده می‌فرستد. سرور آزمایشی تا زمانی که جریان باز باشد، هر ۲۰ ثانیه یک اعلان تصادفی هم می‌فرستد.

ساخت، آزمون و انتشار

npm run typecheck   # بررسی نوع‌ها
npm test            # ساخت و بررسی نشانی SSE، سربرگ‌ها و پردازشگر
npm run build       # تولید dist/index.js، dist/index.cjs، dist/style.css و dist/types
npm publish

dist/style.css با مسیر sws-notification-center/style.css در دسترس است.

مرجع کوتاه API

buildStreamUrl({ baseUrl, userId, serviceName })  // نشانی SSE
buildRefreshUrl(baseUrl)                          // نشانی نوسازی توکن
runSseStream(options)                             // حلقهٔ اتصال SSE بر پایهٔ fetch
SseParser                                         // پردازشگر تدریجی SSE
normalizeNotification(payload, fallbackService)   // تبدیل داده به NotificationItem
TokenManager                                      // مدیریت نوسازی توکن
NotificationStore                                 // مخزن وضعیت اعلان‌ها

مجوز

MIT