🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@chargebee/code-samples

Package Overview
Dependencies
Maintainers
1
Versions
25
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install
Package was removed
Sorry, it seems this package was removed from the registry

@chargebee/code-samples

A self-contained, reusable React component for generating and displaying API code samples from OpenAPI specifications

Source
npmnpm
Version
0.1.2
Version published
Weekly downloads
0
Maintainers
1
Weekly downloads
 
Created
Source

@chargebee/code-samples

A self-contained, reusable React component for displaying API code samples with syntax highlighting, language switching, and copy functionality.

Features

  • Display Component: Renders pre-generated code samples with beautiful syntax highlighting
  • Multi-Language: Supports 12+ languages (cURL, Node.js, Python, PHP, Ruby, Java, .NET, Go, TypeScript)
  • Syntax Highlighting: Powered by Shiki
  • Feature-Rich: Carousel, copy button, animations, language switcher
  • Module Federation: Consumable across multiple apps via Vite Module Federation
  • Themeable: Configurable themes and styling

Installation

pnpm add @chargebee/code-samples

Usage

Simple Usage (Code String)

import { CodeSamples } from '@chargebee/code-samples';
import '@chargebee/code-samples/styles';

function MyPage() {
  return (
    <CodeSamples
      codeString={`curl https://your-site.chargebee.com/api/v2/customers \\
  -u test_api_key: \\
  -X POST \\
  -d "first_name=John&last_name=Doe"`}
      language="curl"
      theme="github-light"
      features={{
        copyButton: true,
        showLineNumbers: true,
      }}
    />
  );
}

Multiple Pre-generated Samples

import { CodeSamples } from '@chargebee/code-samples';
import '@chargebee/code-samples/styles';

function MyPage() {
  // Pre-generate samples using generateCodeSamples (see Pure Function API below)
  const samples = {
    'curl': 'curl https://...',
    'node-v3': 'const chargebee = new Chargebee({...})',
    'python-v3': 'import chargebee\nchargebee.configure(...)',
  };

  return (
    <CodeSamples
      samples={samples}
      initialLanguage="node-v3"
      theme="github-light"
      features={{
        carousel: true,
        copyButton: true,
        showLanguageSwitcher: true,
      }}
    />
  );
}

Props

PropTypeRequiredDescription
codeStringstringRaw code string to display (simplest usage)
languagestringLanguage identifier (required if codeString is provided)
samplesRecord<string, string> | Array<{languageSnippets: Record<string, string>}>Pre-generated code samples object or array
responseDataanySample response JSON to display
initialLanguagestringInitial language selection (default: first language)
themestring | ThemeConfigShiki theme name or custom config (default: "github-dark")
highlighterHighlighterConfigShiki highlighter configuration
featuresFeaturesConfigFeature toggles (see below)
classNamestringAdditional CSS classes
styleReact.CSSPropertiesInline styles
replacementsRecord<string, string>String replacements (e.g., {"{site}": "acme"})
onLanguageChange(lang: string) => voidLanguage change callback
onCopy(code: string) => voidCopy callback
onSampleChange(index: number) => voidSample change callback (for carousel)

Features Config

FeatureTypeDefaultDescription
carouselbooleanfalseEnable carousel for multiple samples
copyButtonbooleantrueShow copy-to-clipboard button
animationsbooleantrueEnable fade transitions
showHeaderbooleantrueShow/hide entire header
showLanguageSwitcherbooleantrueShow/hide language dropdown
showApiExplorerbooleanfalseShow "Try in API Explorer" button
showLineNumbersbooleantrueShow line numbers in code blocks
titlestring"Sample Request"Header title
languageFilterstring[]undefinedShow only specific languages
onApiExplorerClick() => voidundefinedCallback for API Explorer button

Module Federation

This package is configured for Vite Module Federation, allowing it to be consumed by multiple applications without bundling duplication.

Host Configuration (api-docs example)

// vite.config.ts
import federation from '@originjs/vite-plugin-federation';

export default defineConfig({
  plugins: [
    federation({
      name: 'apiDocs',
      remotes: {
        codeSamples: 'http://localhost:5001/assets/remoteEntry.js',
      },
      shared: {
        react: { singleton: true },
        'react-dom': { singleton: true },
      },
    }),
  ],
});

Development

# Install dependencies
pnpm install

# Start dev server (port 5001)
pnpm dev

# Build for production
pnpm build

Code Sample Reporting Tools

This package includes tools to analyze and report on code sample generation across all OpenAPI operations.

Generate Operations Report

Generate a comprehensive report of all operations, their code sample status, and generation success/failure:

# Generate report for v2-pcv2 (default)
pnpm report:operations

# Generate report for specific version
pnpm report:operations --version v2-pcv2
pnpm report:operations --version v2-pcv1
pnpm report:operations --version v1

# Generate only JSON or Markdown
pnpm report:operations --format json
pnpm report:operations --format markdown

# Test with specific language
pnpm report:operations --test-lang java

Output: Reports are saved to reports/operations-report-{version}.{json|md}

View Reports

Open the interactive HTML viewer to filter and explore reports:

# Open the report viewer in your browser
open reports/report-viewer.html

# Or manually navigate to:
# packages/code-samples/reports/report-viewer.html

The viewer allows you to:

  • Select version (v1, v2-pcv1, v2-pcv2) from dropdown
  • Filter by resource, HTTP method, or status
  • Search operations by name, path, or operationId
  • Export filtered results as CSV
  • View detailed error messages for failed operations

Report Structure

Each report includes:

  • Summary: Total operations, with samples, successful, failed, missing samples
  • Operations: Detailed list with:
    • Resource and operation name
    • HTTP method and path
    • Operation ID
    • Sample file status
    • Code generation status (success/failed/no_samples)
    • Error messages and categories

See README-REPORT.md for detailed documentation.

Architecture

  • generators/: Language-specific code generators (Go, Node.js, Python, etc.)
  • metadata/: OpenAPI metadata extraction
  • components/: React UI components
  • styles/: CSS themes and animations

Code Generation vs Display

Important: The CodeSamples component is a display component - it renders pre-generated code strings. It does NOT generate code from OpenAPI specs.

To generate code from OpenAPI specs, use the generateCodeSample or generateCodeSamples functions (see Pure Function API below), then pass the result to the component:

import { CodeSamples } from '@chargebee/code-samples';
import { generateCodeSamples } from '@chargebee/code-samples';

// In your loader/server component (SSG/SSR)
export async function loader() {
  const samples = await generateCodeSamples({
    languages: ['curl', 'node-v3', 'python-v3'],
    resource: 'customer',
    operation: 'create_a_customer',
    apiVersion: 'v2',
    openapi: openapiSpec,
    site: 'acme-test',
    apiKey: 'test_api_key'
  });

  return { samples };
}

// In your React component
function MyPage({ samples }) {
  return <CodeSamples samples={samples} />;
}

Pure Function API (Non-React)

For non-React environments (Node.js, LLMs, Deno, Bun) or server-side generation (SSG/SSR), use the pure function API:

import { generateCodeSample, generateCodeSamples } from '@chargebee/code-samples';

// Generate code for a specific language
const result = await generateCodeSample({
  language: 'node-v3',
  resource: 'customer',
  operation: 'create_a_customer',
  apiVersion: 'v2',
  pcVersion: 'v2',
  openapi: openapiSpec,
  site: 'acme-test',
  apiKey: 'test_api_key'
});

console.log(result.code); // Generated Node.js code string
console.log(result.language); // 'node-v3'

// Generate code for multiple languages
const allSamples = await generateCodeSamples({
  languages: ['curl', 'node-v3', 'python-v3', 'java'],
  resource: 'customer',
  operation: 'create_a_customer',
  apiVersion: 'v2',
  openapi: openapiSpec
});

console.log(allSamples['node-v3']); // Node.js code
console.log(allSamples['python-v3']); // Python code

// Or use pre-generated samples
const result = await generateCodeSample({
  language: 'python-v3',
  samples: {
    'python-v3': 'import chargebee\nchargebee.configure(...)'
  }
});

Use Cases:

  • LLM/AI code generation tools
  • Server-side code generation (SSG/SSR)
  • CLI tools and scripts
  • Non-React applications
  • Testing and validation

Code Generators (Server-Side)

The code generators (getGenerator, extractOperationMetadataFromOpenAPI) are server-side only and require @cb-docs-platform/openapi-utils to be installed. If you're only using the React components (CodeSamples, CodeBlock), you don't need this dependency.

# If using generators (SSG/SSR)
pnpm add @cb-docs-platform/openapi-utils

Note: @cb-docs-platform/openapi-utils is currently a private package. If you need to use generators, ensure you have access to the Chargebee internal npm registry or install it from the monorepo.

License

MIT

Keywords

code-samples

FAQs

Package last updated on 05 Feb 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts