@getspot/spot-widget

中文文档
4.8.0发布于 2026/10/30TypeScriptESM + CJS零依赖近 30 天下载 8193

Core JavaScript/TypeScript library for integrating Spot's refund guarantee widget into your applications.

原始使用文档
文档目录31 节
  1. Installation
  2. Quick Start
  3. TypeScript Support
  4. Configuration
  5. SpotWidgetOptions
  6. ApiConfig
  7. QuoteRequestData
  8. Widget Methods
  9. updateQuote(newQuoteRequestData)
  10. getSelection()
  11. validateSelection()
  12. destroy()
  13. Callbacks
  14. onOptIn(data: SelectionData)
  15. onOptOut(data: SelectionData)
  16. onQuoteRetrieved(quote: Quote)
  17. onError(error: ErrorData)
  18. noMatchingQuote(data)
  19. Styling
  20. Error Handling
  21. Environments
  22. Sandbox (Development)
  23. Production
  24. API Reference
  25. Interfaces
  26. Enums
  27. Type Aliases
  28. Framework Integration
  29. Browser Support
  30. License
  31. Support

@getspot/spot-widget

Core JavaScript/TypeScript library for integrating Spot's refund guarantee widget into your applications.

Installation

npm install @getspot/spot-widget

Quick Start

import SpotWidget from '@getspot/spot-widget';

// Create widget instance
const widget = new SpotWidget({
  location: '#spot-widget-container', // CSS selector or DOM element
  apiConfig: {
    environment: 'production', // 'sandbox' for testing
    partnerId: 'your-partner-id'
  },
  quoteRequestData: {
    startDate: '2024-01-01T00:00:00Z',
    endDate: '2024-01-07T23:59:59Z',
    currencyCode: 'USD',
    eventType: 'Ski Trip',
    productType: 'Trip',
    productDuration: 'Trip',
    productPrice: 500,
    productId: 'ski-trip-2024',
    cartId: 'cart-123',
    productName: 'Aspen Ski Trip 2024'
  },
  callbacks: {
    onOptIn: (data) => {
      console.log('User opted in:', data);
      // Handle opt-in logic
    },
    onOptOut: (data) => {
      console.log('User opted out:', data);
      // Handle opt-out logic
    },
    onQuoteRetrieved: (quote) => {
      console.log('Quote retrieved:', quote);
    },
    onError: (error) => {
      console.error('Widget error:', error);
    }
  }
});

TypeScript Support

This package is written in TypeScript and includes full type definitions.

import SpotWidget, { SpotWidgetOptions, SelectionData, Quote } from '@getspot/spot-widget';

const options: SpotWidgetOptions = {
  // ... your configuration
};

const widget = new SpotWidget(options);

Configuration

SpotWidgetOptions

OptionTypeRequiredDefaultDescription
locationstring | HTMLElementNo"body"Target element for the widget
apiConfigApiConfigYes-API configuration
quoteRequestDataQuoteRequestDataYes-Quote request information
showTablebooleanNotrueWhether to show payout table
selectionSelectionEnumNoSelectionEnum.UNSELECTEDInitial selection state for the widget
themeThemeNo-Custom styling
callbacksCallbacksNo{}Event callbacks
statestringNo-Customer's 2-letter US state code (e.g. "TX"). Only applies to Pass/Trip offers — ignored for Registration. When provided, hides the state selector and passes the value through to downstream calls. When omitted, the selector is shown automatically.

ApiConfig

{
  environment: 'production' | 'sandbox' | 'local';
  partnerId: string;
  customEndpoint?: string; // Optional custom API endpoint
}

QuoteRequestData

Single Product Quote

{
  startDate: string;        // ISO 8601 date
  endDate: string;          // ISO 8601 date
  currencyCode: 'USD' | 'CAD' | 'AUD' | 'NZD' | 'EUR' | 'MXN' | 'AED' | 'GBP' | 'MAD' | 'SAR' | 'BGN' | 'BRL' | 'CHF' | 'DKK' | 'INR' | 'JPY' | 'MYR' | 'NOK' | 'PLN' | 'SEK' | 'SGD' | 'THB' | 'ZAR';
  eventType: string;        // Event description
  productType: 'Pass' | 'Trip' | 'Registration';
  productDuration: 'Daily' | 'Seasonal' | 'Trip' | 'Event';
  productPrice: number;     // Price in specified currency
  productId: string;        // Unique product identifier
  cartId: string;           // Shopping cart identifier
  productName: string;      // Human-readable product name
  participantDescription?: string; // Optional participant info
}

Batch Quote (Multiple Products)

{
  cartId: string;
  cartName: string;
  currencyCode: 'USD' | 'CAD' | 'AUD' | 'NZD' | 'EUR' | 'MXN' | 'AED' | 'GBP' | 'MAD' | 'SAR' | 'BGN' | 'BRL' | 'CHF' | 'DKK' | 'INR' | 'JPY' | 'MYR' | 'NOK' | 'PLN' | 'SEK' | 'SGD' | 'THB' | 'ZAR';
  items: Array<{
    // All single product fields except cartId and currencyCode
    cartItemId?: string; // Optional item identifier
  }>;
}

Widget Methods

updateQuote(newQuoteRequestData)

Update the widget with new quote data.

const success = await widget.updateQuote({
  // new quote request data
});
console.log('Update successful:', success);

Returns: Promise<boolean>

getSelection()

Get the current user selection.

const selection = widget.getSelection();
console.log('User selection:', selection);

Returns: SelectionData | null

validateSelection()

Check if the user has made a selection.

const isValid = widget.validateSelection();
if (!isValid) {
  console.log('Please make a selection');
}

Returns: boolean

destroy()

Clean up the widget instance.

widget.destroy();

Callbacks

onOptIn(data: SelectionData)

Called when user opts into the refund guarantee.

{
  onOptIn: (data) => {
    console.log('Opt-in data:', data);
    // data.status === 'QUOTE_ACCEPTED'
    // data.quoteId - unique quote identifier
    // data.spotPrice - refund guarantee price
  }
}

onOptOut(data: SelectionData)

Called when user opts out of the refund guarantee.

{
  onOptOut: (data) => {
    console.log('Opt-out data:', data);
    // data.status === 'QUOTE_DECLINED'
    // data.quoteId - unique quote identifier
  }
}

onQuoteRetrieved(quote: Quote)

Called when a quote is successfully retrieved.

{
  onQuoteRetrieved: (quote) => {
    console.log('Quote:', quote);
    // quote.id - quote identifier
    // quote.spotPrice - refund guarantee price
    // quote.communication - display text and labels
  }
}

onError(error: ErrorData)

Called when an error occurs.

{
  onError: (error) => {
    console.error('Error:', error);
    // error.message - error description
    // error.status - HTTP status code (if applicable)
    // error.responseBody - API response (if applicable)
  }
}

noMatchingQuote(data)

Called when no quote is available for the request.

{
  noMatchingQuote: (data) => {
    console.log('No quote available:', data);
    // Handle case where product isn't eligible
  }
}

Styling

Customize the widget appearance using the theme option:

const widget = new SpotWidget({
  // ... other options
  theme: {
    primaryColor: '#007bff',
    secondaryColor: '#6c757d',
    borderRadius: '8px',
    fontFamily: 'Arial, sans-serif',
    fontSize: '14px'
    // Any CSS custom properties (without -- prefix)
  }
});

Error Handling

Always implement comprehensive error handling:

const widget = new SpotWidget({
  // ... configuration
  callbacks: {
    onError: (error) => {
      // Log for debugging
      console.error('Spot Widget Error:', error);
      
      // Handle different error types
      if (error.status === 404) {
        console.log('Product not eligible for refund guarantee');
      } else if (error.status >= 500) {
        console.log('Service temporarily unavailable');
      }
      
      // Track in analytics
      if (window.analytics) {
        window.analytics.track('spot_widget_error', {
          message: error.message,
          status: error.status
        });
      }
    },
    noMatchingQuote: (data) => {
      console.log('No refund guarantee available');
      // Hide widget or show alternative messaging
    }
  }
});

Environments

Sandbox (Development)

Use the sandbox environment for testing:

{
  apiConfig: {
    environment: 'sandbox',
    partnerId: 'your-sandbox-partner-id'
  }
}

Production

Use the production environment for live applications:

{
  apiConfig: {
    environment: 'production',
    partnerId: 'your-production-partner-id'
  }
}

API Reference

This package exports the following types and interfaces:

Interfaces

ApiConfig

export interface ApiConfig {
  environment: "sandbox" | "production" | "local";
  partnerId: string;
  customEndpoint?: string;
}

QuoteMetadata

export interface QuoteMetadata {
  segment?: string;
  operator?: string;
  channel?: string;
  consumerId?: string;
}

QuoteItem

export interface QuoteItem {
  productPrice: number;
  productType: "Pass" | "Trip" | "Registration";
  productDuration: "Daily" | "Seasonal" | "Trip" | "Event";
  productId: string;
  cartId: string;
  cartItemId?: string;
  cartName: string;
  productName: string;
  participantDescription?: string;
  eventType: string;
  eventId?: string;
  currencyCode:
    | "USD"
    | "CAD"
    | "AUD"
    | "NZD"
    | "EUR"
    | "MXN"
    | "AED"
    | "GBP"
    | "MAD"
    | "SAR"
    | "BGN"
    | "BRL"
    | "CHF"
    | "DKK"
    | "INR"
    | "JPY"
    | "MYR"
    | "NOK"
    | "PLN"
    | "SEK"
    | "SGD"
    | "THB"
    | "ZAR";
  startDate: string;
  endDate: string;
  partnerRiskEnd?: Date;
  metadata?: QuoteMetadata;
  isPartialPayment?: boolean;
  hostCountry?: string;
  hostCountryState?: string;
  destinations?: string[];
  dob?: string;
  roundTo?: number;
}

BatchQuoteRequest

export interface BatchQuoteRequest {
  cartId: string;
  cartName: string;
  currencyCode:
    | "USD"
    | "CAD"
    | "AUD"
    | "NZD"
    | "EUR"
    | "MXN"
    | "AED"
    | "GBP"
    | "MAD"
    | "SAR"
    | "BGN"
    | "BRL"
    | "CHF"
    | "DKK"
    | "INR"
    | "JPY"
    | "MYR"
    | "NOK"
    | "PLN"
    | "SEK"
    | "SGD"
    | "THB"
    | "ZAR";
  metadata?: QuoteMetadata;
  isPartialPayment?: boolean;
  roundTo?: number;
  items: BatchQuoteItem[];
}

QualifyingReason

export interface QualifyingReason {
  rank: number;
  name?: string;
  benefitType?: {
    name: string;
  };
}

PayoutScheduleItem

export interface PayoutScheduleItem {
  text: string;
  percent: string | number;
  amount: number;
}

Communication

export interface Communication {
  name: string;
  description: string;
  bulletPoints: string[];
  yesOptionText: string;
  noOptionText: string;
  legalDisclaimer: string;
  termsAndConditionsUrl: string;
  paymentTerms?: string;
}

Quote

export interface Quote {
  id: string;
  cartItemId?: string;
  spotPrice: number;
  currencyCode: string;
  communication: Communication;
  payoutSchedule: PayoutScheduleItem[];
  qualifyingReasons?: QualifyingReason[];
  coveredItems?: string[];
  originalQuotes?: Quote[];
}

QuoteUpdates

export interface QuoteUpdates {
  spotPriceWithFees?: number;
}

ApiResponse

export interface ApiResponse {
  status: "QUOTE_AVAILABLE" | "QUOTES_AVAILABLE" | "NO_MATCHING_QUOTE";
  data?: Quote;
  quotes?: Quote[];
  totalSpotPrice?: number;
  spotPrice?: number;
  currencyCode?: string;
  communication?: Communication;
  payoutSchedule?: PayoutScheduleItem[];
  coveredItems?: string[];
}

SelectionData

export interface SelectionData {
  status: "QUOTE_ACCEPTED" | "QUOTE_DECLINED";
  spotPrice?: number;
  quoteId?: string;
  selection?: string;
  /**
   * Customer's US state code (e.g. "TX"). Set when:
   * - The partner passes a `state` prop (captured at their checkout), or
   * - The user selects a US state from the selector shown on Pass/Trip offers.
   * Undefined when neither applies.
   */
  state?: string;
  batchQuoteDetails?: Array<{
    quoteId: string;
    productPrice: number;
    cartItemId: string;
  }>;
}

Callbacks

export interface Callbacks {
  onOptIn?: (data: SelectionData) => void;
  onOptOut?: (data: SelectionData) => void;
  onQuoteRetrieved?: (quote: Quote) => QuoteUpdates | void;
  onError?: (error: { message: string; status?: number; responseBody?: any }) => void;
  noMatchingQuote?: (data: { status: string; data: QuoteRequestData }) => void;
}

Theme

export interface Theme {
  [key: string]: string;
}

SpotWidgetOptions

export interface SpotWidgetOptions {
  location?: string | HTMLElement;
  showTable?: boolean;
  selection?: SelectionEnum;
  logoPosition?: "bottom-right" | "top-right";
  apiConfig: ApiConfig;
  quoteRequestData: QuoteRequestData;
  callbacks?: Callbacks;
  theme?: Theme;
  isPartialPayment?: boolean;
  useMockData?: boolean;
  mockData?: ApiResponse;
  // Response the widget should return from the residency re-fetch when useMockData is true.
  // Pass a function to vary the response by residency (e.g. return NO_MATCHING_QUOTE only when
  // isUSResident === false). Used by Storybook to exercise ST-5408 flows without a backend.
  // When omitted, re-fetch reuses `mockData`.
  // Accepts a Promise or an async function so Storybook can simulate a slow backend and show
  // the radios locking the instant the re-fetch starts (independent of when it resolves).
  mockRefetchData?:
    | ApiResponse
    | Promise<ApiResponse>
    | ((isUSResident: boolean | undefined) => ApiResponse | Promise<ApiResponse>);
  state?: string;
}

ElementOptions

export interface ElementOptions {
  text?: string;
  className?: string;
  parent?: HTMLElement;
  innerHTML?: string;
  href?: string;
  target?: string;
}

Enums

SelectionEnum

export enum SelectionEnum {
  YES = 'yes',
  NO = 'no',
  UNSELECTED = 'unselected',
}

Type Aliases

QuoteRequestData

export type QuoteRequestData = QuoteItem | BatchQuoteRequest | QuoteItem[];

Framework Integration

This is the core library. For framework-specific wrappers:

Browser Support

  • Modern browsers (ES2020+)
  • Chrome 80+
  • Firefox 74+
  • Safari 13+
  • Edge 80+

License

See the main package for license information.

Support

For support, please contact [email protected].

版本与发布记录

@getspot/spot-widget 共发布 54 个版本,首次发布于 2025/04/25;过去 12 个月发布了 31 个版本。

版本发布日期距今
4.8.0latest2026/10/3017 天前
4.7.02026/09/221 个月前
4.6.02026/08/123 个月前
4.5.02026/08/063 个月前
4.4.22026/08/053 个月前
4.4.12026/07/233 个月前

关于 @getspot/spot-widget 的常见问题

@getspot/spot-widget 是什么?

Core JavaScript/TypeScript library for integrating Spot's refund guarantee widget into your applications.

如何安装 @getspot/spot-widget?

在项目目录运行 npm install @getspot/spot-widget,或使用 pnpm add / yarn add / bun add。

@getspot/spot-widget 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@getspot/spot-widget 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@getspot/spot-widget 可以商用吗?

@getspot/spot-widget 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@getspot/spot-widget 的下载量有多少?

根据 npm 官方下载统计,@getspot/spot-widget 在 2026/10/17 – 2026/11/15 这 30 天内被下载 8,193 次,日均约 273 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@getspot/spot-widget 还在维护吗?

最新版本 4.8.0 发布于 2026/10/30(17 天前);至今共发布 54 个版本,其中过去 12 个月发布了 31 个;首次发布于 2025/04/25。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。