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

@newcoretech/widget-react

v2.1.1

Published

A React library for building widgets that communicate with the Newcore platform through an event-driven architecture. This library provides seamless integration between React components and the Newcore host application using WebEventBus for cross-frame co

Readme

@newcoretech/widget-react

A React library for building widgets that communicate with the Newcore platform through an event-driven architecture. This library provides seamless integration between React components and the Newcore host application using WebEventBus for cross-frame communication.

Features

  • 🚀 Event-driven widget communication with host applications
  • 📱 Two client types: standard widgets and background processing
  • 🔄 Async data operations with Promise-based API
  • 🌍 Cross-frame communication using WebEventBus
  • 🛡️ Request interceptors for background widgets
  • 📦 Full TypeScript support with complete type definitions
  • 🎯 React hooks for automatic lifecycle management
  • 🔒 Secure event namespacing and message handling
  • 📊 Singleton pattern for global client management
  • ⚡ Automatic cleanup and resource management

Installation

npm install @newcoretech/widget-react
# or
yarn add @newcoretech/widget-react
# or
pnpm add @newcoretech/widget-react

Peer Dependencies

npm install react@>=17 react-dom@>=17

Quick Start

Basic Widget Usage

import React from 'react';
import { useClient } from '@newcoretech/widget-react';

function MyWidget() {
  const client = useClient();

  const handleGetData = async () => {
    const result = await client.get('user.profile');
    console.log('User profile:', result.data);
  };

  const handleSetData = async () => {
    const result = await client.set('user.preferences.theme', 'dark');
    console.log('Theme updated:', result.success);
  };

  return (
    <div>
      <button onClick={handleGetData}>Get User Profile</button>
      <button onClick={handleSetData}>Set Dark Theme</button>
    </div>
  );
}

Background Widget Usage

For widgets that need to intercept and handle background operations:

import React from 'react';
import { useBackgroundClient } from '@newcoretech/widget-react';

function BackgroundWidget() {
  const client = useBackgroundClient();

  React.useEffect(() => {
    // Add interceptor for API requests
    client.addInterceptor('api.request', async (data) => {
      console.log('Intercepting API request:', data);
      // Perform validation or modification
      return { success: true, message: 'Request approved' };
    });

    return () => {
      client.removeInterceptor('api.request');
    };
  }, [client]);

  return <div>Background widget running...</div>;
}

API Reference

Client Methods

| Method | Parameters | Returns | Description | |--------|------------|---------|-------------| | get | path: string | Promise<EventResponse> | Retrieve data from host application | | set | path: string, value: unknown | Promise<EventResponse> | Update data in host application | | invoke | path: string, ...args: unknown[] | Promise<EventResponse> | Call methods in host application | | on | eventName: string, callback: Function | void | Subscribe to events | | off | eventName: string, callback?: Function | void | Unsubscribe from events | | has | eventName: string, callback?: Function | boolean | Check if event is subscribed | | trigger | eventName: string, data: unknown | void | Trigger custom events | | requestProxy | url: string, { method, headers, body,}: {method: "GET" \| "POST" \| "PUT" \| "DELETE" \| "HEAD" \| "OPTIONS" \| "TRACE"; headers?: Record<string, string>; body?: string \| Record<string, unknown>; } | Promise<{headers: Record<string, string>; status: number; body: { code: number; message: string; data: unknown };} | Make HTTP requests with proxy support |

BackgroundClient Additional Methods

| Method | Parameters | Returns | Description | |--------|------------|---------|-------------| | addInterceptor | name: string, interceptor: Function | void | Add request interceptor | | removeInterceptor | name: string | void | Remove request interceptor |

React Hooks

| Hook | Returns | Description | |------|---------|-------------| | useClient() | Client | Creates and manages a Client instance with automatic cleanup | | useBackgroundClient() | BackgroundClient | Creates and manages a BackgroundClient instance with automatic cleanup |

Types

interface EventResponse {
  success: boolean;
  message?: string;
  data?: unknown; // Only for get() and invoke() operations
}

type LocationType = 'NavBar' | 'TopBar' | 'SideBar' | 'Background';
type LanguageType = 'zh-CN' | 'en-US' | 'vi-VN' | 'ja-JP';

Event System

The library uses a sophisticated event system with different namespaces:

  • Widget Events: Prefixed with widget-event: for standard widget communication
  • Background Events: Prefixed with background-event: for background operations
  • System Events: Used internally for lifecycle management

Event Flow

  1. Widget → Host: Events are published to the parent frame like set(), invoke() or trigger();
  2. Host → Widget: Events are received through subscriptions to specific event names like on();
  3. Async Operations: Request-response patterns using unique event names with path/operation identifiers;

Error Handling

All async operations return standardized response objects:

interface Response {
  success: boolean;
  message?: string;
  data?: unknown; // Only for get() and invoke() operations
}

Handle errors appropriately:

const result = await client.get('user.profile');
if (!result.success) {
  console.error('Failed to get profile:', result.message);
  return;
}
// Use result.data safely

Widget Communication Protocol

Event Namespaces

The library uses structured event namespaces for secure communication:

  • Widget Events: Prefixed with widget-event: for standard widget operations
  • Background Events: Prefixed with background-event: for background processing
  • System Events: Internal events for lifecycle management (web-event-bus:)

Supported Operations

| Operation | Event Pattern | Description | |-----------|---------------|-------------| | #get | {prefix}#get{prefix}#get-response:{path} | Data retrieval with response | | #set | {prefix}#set{prefix}#set-result:{path} | Data storage with acknowledgment | | #invoke | {prefix}#invoke{prefix}#invoke-result:{path} | Method invocation with response | | #trigger | {prefix}#trigger | Fire-and-forget event triggering | | #onChange | {prefix}#onChange | Event change notifications | | #onIntercept | background-event:#onIntercept | Background interceptor events |

Security Features

  • Event Namespacing: Prevents event collision with prefixed event names
  • Cross-Frame Communication: Secure parent-child window message passing
  • Origin Validation: Built-in support for origin checking (configurable)
  • Resource Cleanup: Automatic cleanup of event listeners and timeouts

Development

Prerequisites

  • Node.js 18+
  • pnpm (recommended)

Setup

# Install dependencies
pnpm install

# Development mode
pnpm dev

# Build library
pnpm build

# Lint code
pnpm lint

Project Structure

src/
├── client.ts              # Main widget client implementation
├── background-client.ts   # Background client with interceptors
├── hooks.ts              # React hooks for client management
├── index.ts              # Main library exports
├── common/
│   └── index.ts          # XHYClient singleton factory
└── __test__/             # Test directory

Build Configuration

The library is built using Rollup with the following outputs:

  • ES Modules: dist/index.js
  • TypeScript Declarations: dist/index.d.ts
  • External Dependencies: React and ReactDOM (peer dependencies)
  • CSS Processing: PostCSS with Sass/Less support
  • Asset Handling: Images and URLs with size limits

Build Features

  • TypeScript compilation with strict mode
  • Babel transpilation for ES compatibility
  • CSS extraction and minification
  • Source maps in development mode
  • Tree-shaking optimization

Browser Support

  • Modern browsers with ES2020+ support
  • React 17+ compatibility
  • WebEventBus cross-frame communication support
  • PostMessage API support

Changelog

v2.0.1-beta11

  • 🚀 Event-driven architecture with WebEventBus
  • 📱 Dual client types (standard and background)
  • 🔄 Promise-based async operations
  • 🛡️ Request interceptor support
  • 📦 Full TypeScript support
  • 🎯 React hooks integration
  • 🔒 Secure event namespacing

2.0.2 - 2025-10-11

  • Addressed type import reference to avoid missing src/type.ts and ensure type declarations resolve correctly.
  • Minor build and lint adjustments to improve development stability.

2.0.3 - 2025-10-15

  • Modify class BackgroundClient to extends class Client.
  • Add method requestProxy in Client class to support proxy requests.

2.0.5 - 2025-10-16

  • Change response of requestProxy method to return a Promise.

License

See the repository for license information.

Support

For issues and questions, please use the project's issue tracker at the GitHub repository.