npm package: @insuretax/widget-sdk
Description: A React-based widget SDK for integrating InsureTax quote generation functionality into any web application. The widget is fully isolated using Shadow DOM and can be used in both React and non-React applications.
Latest version: 0.0.5

# InsureTax Widget SDK

A React-based widget SDK for integrating InsureTax quote generation functionality into any web application. The widget is fully isolated using Shadow DOM and can be used in both React and non-React applications.

## Table of Contents

- [Installation](#installation)
- [Usage](#usage)
  - [React Component](#react-component)
  - [Mount Function (Non-React)](#mount-function-non-react)
- [API Reference](#api-reference)
- [Development](#development)
  - [Publishing to npm](#publishing-to-npm)
- [Building](#building)

## Installation

This package is published to a private npm registry. To install it, you need to configure npm to authenticate with the registry.

### Step 1: Create `.npmrc` file

Create an `.npmrc` file in your project root (or in your home directory at `~/.npmrc` for global configuration):

```ini
@insuretax:registry=https://registry.npmjs.org/
//registry.npmjs.org/:_authToken=YOUR_NPM_TOKEN_HERE
```

Replace `YOUR_NPM_TOKEN_HERE` with your npm authentication token. You can generate a token from your npm account settings.

**Note:** If you're using a different registry URL, replace `https://registry.npmjs.org/` with your registry URL.

### Step 2: Install the package

```bash
npm install @insuretax/widget-sdk
```

Or with yarn:

```bash
yarn add @insuretax/widget-sdk
```

Or with pnpm:

```bash
pnpm add @insuretax/widget-sdk
```

### Requirements

- **Node.js**: Version 18.x or higher
- **React**: Version 19.1.1 or higher (as peer dependency)
- **React DOM**: Version 19.1.1 or higher (as peer dependency)

**Important for TypeScript projects (Angular, Vue with TypeScript, etc.):** You need to install React type definitions even if you're not using React directly:

```bash
npm install --save-dev @types/react@^19.1.16 @types/react-dom@^19.1.9
```

This is required because the widget's TypeScript definitions use React types. The types are only used during compilation and won't affect your runtime bundle.
- **@types/react**: Version ^19.1.16 or higher (as peer dependency, required for TypeScript projects)
- **@types/react-dom**: Version ^19.1.9 or higher (as peer dependency, required for TypeScript projects)

**Note for Angular/Vue/TypeScript projects:** If you have React namespace mestake, you have to install `@types/react` and `@types/react-dom` as dev dependencies for TypeScript to resolve the React types used in the widget's type definitions:

```bash
npm install --save-dev @types/react@^19.1.16 @types/react-dom@^19.1.9
```

## Usage

### React Component

If you're using React in your application, you can import and use the `Widget` component directly.

#### Import the component

```typescript
import { InsureTaxWidget } from '@insuretax/widget-sdk';
```

**Important:** The widget automatically injects all its styles (including Tailwind CSS) into Shadow DOM when it renders. **You don't need to import any CSS files** - everything works out of the box with complete style isolation.

#### Use the component

```tsx
import React from 'react';
import { InsureTaxWidget } from '@insuretax/widget-sdk';

function App() {
  return (
    <InsureTaxWidget
      publishableApiKey="your-api-key-here"
      initialData={{ /* optional initial data */ }}
      onQuoteGenerated={(quote) => {
        console.log('Quote generated:', quote.quoteId);
      }}
      onError={(error) => {
        console.error('Error:', error);
      }}
    />
  );
}

export default App;
```

### Mount Function (Non-React)

For non-React applications (vanilla JavaScript, Vue, Angular, etc.), use the `mount` function to render the widget into a DOM element.

**Important for TypeScript projects (Angular, Vue with TypeScript, etc.):** You need to install React type definitions even though you're not using React:

```bash
npm install --save-dev @types/react@^19.1.16 @types/react-dom@^19.1.9
```

This is required because the widget's TypeScript definitions use React types (like `React.FC`). The types are only used during compilation and won't affect your runtime bundle.

#### Import the mount function

```typescript
import { mount } from '@insuretax/widget-sdk';
```

**Important:** The widget automatically injects all its styles into Shadow DOM when it renders. **You don't need to import any CSS files** - everything works automatically with complete style isolation.

#### Mount the widget

```typescript
// Mount to an element with ID 'insuretax-widget'
mount('insuretax-widget', {
  publishableApiKey: 'your-api-key-here',
  initialData: { /* optional initial data */ },
  onQuoteGenerated: (quote) => {
    console.log('Quote generated:', quote.quoteId);
  },
  onError: (error) => {
    console.error('Error:', error);
  }
});
```

**HTML Example:**

```html
<!DOCTYPE html>
<html>
<head>
  <!-- No need to import CSS - widget injects styles into Shadow DOM -->
</head>
<body>
  <div id="insuretax-widget"></div>
  
  <script type="module">
    import { mount } from '@insuretax/widget-sdk';
    
    mount('insuretax-widget', {
      publishableApiKey: 'your-api-key-here',
      initialData: {
        // Optional: Pre-populate form fields
        // Note: 'name' will be automatically mapped to 'fullName' for PersonalInformationStep
        name: 'John Doe',        // Maps to fullName
        email: 'john@example.com',
        phone: '80991234567',    // Will be automatically formatted for mask
        // Add more fields as needed
      },
      onQuoteGenerated: (quote) => {
        console.log('Quote ID:', quote.quoteId);
      },
      onError: (error) => {
        console.error('Error:', error);
      }
    });
  </script>
</body>
</html>
```

## API Reference

### `WidgetProps`

The widget accepts the following props:

| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `publishableApiKey` | `string` | Yes | Your InsureTax API key for authentication |
| `initialData` | `Record<string, any>` | No | Initial data to pre-populate the wizard |
| `onQuoteGenerated` | `(quote: QuoteModel) => void` | No | Callback function called when a quote is successfully generated |
| `onError` | `(error: any) => void` | No | Callback function called when an error occurs |

### `QuoteModel`

```typescript
interface QuoteModel {
  quoteId: string;
}
```

### `mount(elementId: string, options: WidgetProps)`

Mounts the widget into a DOM element.

- **`elementId`**: The ID of the DOM element where the widget should be rendered
- **`options`**: Same as `WidgetProps` above

**Throws:** `Error` if the element with the specified ID is not found.

## Development

This section is for developers who want to contribute to or modify the widget SDK.

### Prerequisites

- **Node.js**: Version 18.x or higher
- **npm**: Version 9.x or higher (or yarn/pnpm equivalent)

### Getting Started

1. Clone the repository:
```bash
git clone <repository-url>
cd insuretax-sdk-client
```

2. Install dependencies:
```bash
npm install
```

3. Start the development server:
```bash
npm run dev
```

The development server will start on `http://localhost:5173` (or the next available port).

### Project Structure

```
src/
├── features/          # Main feature modules
│   ├── Widget/        # Widget component
│   ├── QuoteWizard/   # Quote wizard flow
│   └── wizard/        # Wizard components and logic
├── components/        # Shared UI components
├── contexts/          # React contexts
├── hooks/             # Custom React hooks
├── api/               # API client and services
├── config/            # Configuration files
├── types/             # TypeScript type definitions
└── styles/            # Style definitions
```

### Available Scripts

- **`npm run dev`**: Start the development server with hot module replacement (HMR)
- **`npm run build`**: Build the production bundle
- **`npm run lint`**: Run ESLint to check code quality
- **`npm run preview`**: Preview the production build locally

### Building

To build the production bundle:

```bash
npm run build
```

This will generate:
- `dist/index.es.js` - ES module bundle
- `dist/index.umd.js` - UMD bundle (for browser `<script>` tags)
- `dist/index.d.ts` - TypeScript type definitions
- `dist/widget-sdk.css` - Compiled CSS with Tailwind styles
- Source maps (`.map` files) for debugging

The build output is optimized and minified for production use.

### Publishing to npm

This section covers how to publish and update the package in the npm registry.

#### Prerequisites for Publishing

1. **npm Account**: You need to be logged in to npm with appropriate permissions for the `@insuretax` scope.

2. **Authentication**: Ensure your `.npmrc` file is configured (see [Installation](#installation) section).

3. **Build the Package**: Always build the package before publishing:
   ```bash
   npm run build
   ```

#### First-Time Publishing

1. **Verify package.json**: Ensure the `version` field in `package.json` is set correctly (e.g., `"0.0.1"`).

2. **Check build output**: Verify that the `dist/` folder contains all necessary files:
   - `index.es.js`
   - `index.umd.js`
   - `index.d.ts`
   - `widget-sdk.css`
   - Source maps (`.map` files)

3. **Login to npm** (if not already logged in):
   ```bash
   npm login
   ```
   Enter your npm credentials when prompted.

4. **Publish the package**:
   ```bash
   npm publish
   ```
   
   For a scoped package with restricted access (as configured in `package.json`), npm will automatically publish it as a private package.

#### Updating the Package

1. **Update the version** in `package.json`:
   
   You can update the version manually or use npm version commands:
   
   ```bash
   # Patch version (0.0.1 -> 0.0.2) - for bug fixes
   npm version patch
   
   # Minor version (0.0.1 -> 0.1.0) - for new features
   npm version minor
   
   # Major version (0.0.1 -> 1.0.0) - for breaking changes
   npm version major
   ```
   
   These commands will automatically update the version in `package.json` and create a git tag.

2. **Build the updated package**:
   ```bash
   npm run build
   ```

3. **Publish the update**:
   ```bash
   npm publish
   ```

#### Version Management Best Practices

- **Semantic Versioning**: Follow [semver](https://semver.org/) guidelines:
  - **MAJOR** (1.0.0): Breaking changes
  - **MINOR** (0.1.0): New features (backward compatible)
  - **PATCH** (0.0.1): Bug fixes (backward compatible)

- **Pre-release versions**: For testing, you can publish pre-release versions:
  ```bash
  npm version prerelease --preid=beta
  npm publish --tag beta
  ```
  Users can then install with: `npm install @insuretax/widget-sdk@beta`

#### Verifying the Published Package

After publishing, you can verify the package was published correctly:

1. **Check on npm website**: Visit `https://www.npmjs.com/package/@insuretax/widget-sdk`

2. **Test installation** in a clean directory:
   ```bash
   mkdir test-install
   cd test-install
   npm init -y
   npm install @insuretax/widget-sdk
   ```

3. **Verify files**: Check that `node_modules/@insuretax/widget-sdk/dist/` contains all expected files.

#### Troubleshooting Publishing

- **Authentication errors**: Ensure your npm token is valid and has the correct permissions
- **Version already exists**: If you try to publish the same version twice, npm will reject it. Update the version first.
- **Build errors**: Always run `npm run build` and check for errors before publishing
- **Missing files**: Verify that the `files` field in `package.json` includes all necessary files

### Development Notes

- The widget uses **Shadow DOM** for style isolation, ensuring it won't conflict with your application's styles
- Styles are scoped using Tailwind CSS v4 with custom prefixes (`_19xxl_2`)
- The widget is built as a library, so React and React DOM are peer dependencies (not bundled)
- TypeScript is used throughout the codebase for type safety

### Testing

To test the widget in development:

1. The widget can be tested using the example in `src/App.tsx`
2. Update `src/App.tsx` with your test API key and data
3. Run `npm run dev` and open the application in your browser

## Style Isolation

The widget uses **Shadow DOM** to completely isolate its styles from your application. **You don't need to import or configure any CSS files** - everything is handled automatically.

### How it works:

1. **Automatic Style Injection**: When the widget renders, it automatically injects all its styles (including Tailwind CSS with `@layer base`, `@layer components`, and `@layer utilities`) into a Shadow DOM container.

2. **Complete Isolation**: 
   - ✅ The widget's styles (including `@layer base` reset styles) **will NOT** affect your application's global styles
   - ✅ Your application's styles **will NOT** affect the widget
   - ✅ All Tailwind classes are scoped with unique hashes (e.g., `_19xxl_2`) for additional isolation

3. **No Configuration Required**: 
   - ❌ **Do NOT** import `widget-sdk.css` in your application
   - ❌ **Do NOT** add any CSS links to your HTML
   - ✅ Just use the component or `mount()` function - styles are injected automatically

### Why this works:

The `@layer base` styles (which include CSS resets like `* { margin: 0; padding: 0; }`) are injected **inside** the Shadow DOM. Shadow DOM creates a completely isolated style scope, so these reset styles only apply to elements inside the widget, not to your document.

**Example:**
```tsx
import { InsureTaxWidget } from '@insuretax/widget-sdk';

<InsureTaxWidget publishableApiKey="..." />
```

## Troubleshooting

### Widget not rendering

- Check that the element ID exists in the DOM before calling `mount()`
- Verify that React and React DOM are installed (for React usage)
- Check the browser console for any error messages

### Authentication errors

- Verify your `publishableApiKey` is correct
- Check that your npm token is valid (for installation)
- Ensure the `.npmrc` file is in the correct location

## License

[Add your license information here]

## Support

For issues, questions, or contributions, please [add your support contact information here].