npm package: @salesforce/metadata-core-sdk
Description: Core SDK with shared contracts and platform abstractions for visualization plugins
Author: salesforce
Latest version: 1.0.0

# @salesforce/metadata-core-sdk

Core SDK with shared contracts and platform abstractions for visualization plugins.

## Overview

This package provides the foundational contracts used by visualization plugins. It contains:

- Plugin contracts (`IVisualizationPlugin`, `IMetadataParser`)
- Platform abstractions (`IPlatformContext`, `IFileSystem`, `ILogger`, `ITelemetry`)
- Shared types (`MetadataPluginInfo`, `ValidationResult`, `PluginContext`, `PluginError`, `PluginConfig`, `VersionInfo`)
- Webview messaging (`WebviewMessageType`, `VALID_MESSAGE_TYPES`)
- Common utilities (`SalesforceXMLParser`, `Logger`)
- Error handling (`ErrorBuilder`, `setupErrorHandlers`, `ErrorBoundary`)
- Design system tokens (colors, spacing, typography) via `@salesforce/metadata-core-sdk/design-system`
- Constants (`PLUGINS_DIR`, `PLUGINS_DIST_DIR`, `REACT_UI_DIR_NAME`)

**Note**: Rendering is handled automatically by the framework package (`@salesforce/metadata-visualizer-core`). The framework auto-detects React builds by checking for `ui/` directory in plugin build outputs.

## Installation

```bash
npm install @salesforce/metadata-core-sdk
```

## Usage

### Plugin Contracts

```typescript
import {
  IVisualizationPlugin,
  MetadataPluginInfo,
  IMetadataParser,
  IPlatformContext,
} from '@salesforce/metadata-core-sdk';
import type { VersionInfo } from '@salesforce/metadata-core-sdk';

export class MyVisualizer implements IVisualizationPlugin<MyData> {
  // 1. Cache metadata for efficiency (return same instance)
  private readonly pluginMetadata: MetadataPluginInfo = {
    id: 'myplugin', // Must match folder name!
    name: 'My Visualizer',
    description: 'Visualizes my metadata type', // optional
    author: 'My Team',
    filePatterns: ['.my-meta.xml'],
    priority: 0, // optional, higher = preferred when multiple plugins match
  };

  // 2. Required: Parser instance
  readonly parser: IMetadataParser<MyData>;

  constructor() {
    this.parser = new MyParser();
  }

  // 3. Required: Return metadata (mandatory hook)
  getMetadataPluginInfo(): MetadataPluginInfo {
    return this.pluginMetadata; // Return cached instance
  }

  // 4. Required: Check if plugin can handle file
  canHandle(filePath: string): boolean {
    return filePath.endsWith('.my-meta.xml');
  }

  // 5. Required: Initialize with platform context
  async initialize(context: IPlatformContext): Promise<void> {
    // Initialize parser, logger, etc.
  }

  // 6. Optional: Cleanup resources
  dispose?(): void {
    // Cleanup
  }
}
```

### Platform Abstractions

Platform abstractions are provided by core-sdk. Plugins receive these at runtime through the `initialize()` method:

```typescript
import type {
  IPlatformContext,
  IFileSystem,
  ILogger,
  ITelemetry,
} from '@salesforce/metadata-core-sdk';

interface IPlatformContext {
  readonly fileSystem: IFileSystem; // Platform-agnostic file operations
  readonly logger: ILogger; // Platform-agnostic logging
  readonly telemetry: ITelemetry; // Telemetry (metrics/events)
  readonly reactBuildsBasePath: string; // Base path for React builds
  readonly pluginSettings?: Record<string, unknown>; // Optional plugin feature flags
}
```

Platforms (like the VS Code extension) implement these interfaces to provide platform-specific functionality.

### Design System

Design tokens for building consistent plugin UIs:

```typescript
import {
  colorTokens,
  spacingTokens,
  fontSizeTokens,
} from '@salesforce/metadata-core-sdk/design-system';
import {
  getCSSVariableValue,
  resolveTokens,
  cssVar,
} from '@salesforce/metadata-core-sdk/design-system';
```

## API

### Plugin Contracts

- **`IVisualizationPlugin<TData>`** - Main plugin interface (`getMetadataPluginInfo`, `parser`, `canHandle`, `initialize`, `dispose?`)
- **`IMetadataParser<TData>`** - Parser contract (`parse(filePath, versionInfo)`, `validate?(data)`, `getVizDependentFilePaths?(filePath)`)

### Types

- **`MetadataPluginInfo`** - Plugin metadata (id, name, author, filePatterns, description?, priority?, trustedSources?)
- **`PluginContext`** - Context passed to renderers
- **`ValidationResult`** - Validation result with errors and warnings
- **`PluginError`** - Structured error type with category, message, and context
- **`PluginConfig`** - Plugin configuration with settings
- **`VersionInfo`** - Version information resolved by the framework
- **`FileMetadata`** - File metadata structure
- **`Result<T>`** - Result type for operations

### Platform Abstractions

- **`IPlatformContext`** - Core platform context (fileSystem, logger, telemetry, reactBuildsBasePath, pluginSettings?)
- **`IFileSystem`** - Platform-agnostic file operations
- **`ILogger`** - Platform-agnostic logging interface
- **`ITelemetry`** - Platform-agnostic telemetry interface

### Utilities

- **`ErrorBuilder`** - Fluent API for constructing and reporting errors; `send()` posts to extension via postMessage
- **`setupErrorHandlers`** - Global handlers for uncaught errors and unhandled promise rejections (call at app start)
- **`ErrorBoundary`** - React error boundary for catching rendering errors
- **`SalesforceXMLParser`** - Utility class for parsing Salesforce XML files with sensible defaults
- **`Logger`** - Simple console-based logger utility (plugins can also use platform logger from `IPlatformContext`)

### Webview Messaging

- **`WebviewMessageType`** - Message type constants for webview ↔ extension host communication (`PLUGIN_ERROR`, `RETRY_VISUALIZATION`, `COPY_STACK_TRACE`, `OPEN_SETTINGS`)
- **`VALID_MESSAGE_TYPES`** - Set of all valid message types for whitelist validation
- **`WebviewMessageTypeValue`** - Union type of all message type values

### Constants

- **`PLUGINS_DIR`** - Directory name for plugins (`'plugins'`)
- **`PLUGINS_DIST_DIR`** - Build output directory name (`'dist'`)
- **`REACT_UI_DIR_NAME`** - React UI directory name (`'ui'`)

## Package Exports

```typescript
// Main exports
import {
  IVisualizationPlugin,
  IMetadataParser,
  MetadataPluginInfo,
  IPlatformContext,
  IFileSystem,
  ILogger,
  SalesforceXMLParser,
  Logger,
  ErrorBuilder,
  ErrorCategory,
  setupErrorHandlers,
  ErrorBoundary,
  WebviewMessageType,
  VALID_MESSAGE_TYPES,
  PLUGINS_DIR,
  PLUGINS_DIST_DIR,
  REACT_UI_DIR_NAME,
} from '@salesforce/metadata-core-sdk';

// Types
import type {
  ValidationResult,
  PluginContext,
  PluginError,
  PluginConfig,
  VersionInfo,
  WebviewMessageTypeValue,
} from '@salesforce/metadata-core-sdk';

// Design system tokens and utilities (separate export)
import {
  colorTokens,
  spacingTokens,
  fontSizeTokens,
  getCSSVariableValue,
  resolveTokens,
  cssVar,
} from '@salesforce/metadata-core-sdk/design-system';

// Test helpers (separate export)
import {} from /* test utilities */ '@salesforce/metadata-core-sdk/test-helpers';
```

## License

BSD-3-Clause

## Support

For issues or questions, please file an issue at:
https://github.com/forcedotcom/salesforce-metadata-visualizer-support/issues