Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

@bluecopa/core

Package Overview
Dependencies
Maintainers
3
Versions
95
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@bluecopa/core

The core package provides essential API utilities and functions for data management, workbook handling, dataset operations, and definition execution in the Bluecopa platform.

npmnpm
Version
0.1.70
Version published
Weekly downloads
2.5K
15.31%
Maintainers
3
Weekly downloads
 
Created
Source

@bluecopa/core

The core package provides essential API utilities and functions for data management, workbook handling, dataset operations, and definition execution in the Bluecopa platform.

Table of Contents

Version

Current version: 0.1.4

Installation

npm install @bluecopa/core

Requirements

  • Node.js >= 18.0.0
  • Dependencies:
    • axios (1.12.0) - For HTTP requests
    • lodash (4.17.21) - For utility functions
    • centrifuge (5.0.0) - For WebSocket connections

Configuration

The package uses a singleton-based configuration system to manage API settings. Configure it before making API calls.

Import and set the config:

import { copaSetConfig, copaApi } from "@bluecopa/core";

copaSetConfig({
  apiBaseUrl: "https://develop.bluecopa.com", // Base URL for API endpoints
  accessToken: "your-access-token", // Authentication token
  workspaceId: "your-workspace-id", // Current workspace identifier
  userId: "your-user-id", // User identifier for WebSocket connections
});

Getting User Details and Setting User ID

To automatically set the userId from the logged-in user:

import { copaSetConfig, copaApi } from "@bluecopa/core";

// First configure basic settings
copaSetConfig({
  apiBaseUrl: "https://develop.bluecopa.com",
  accessToken: "your-access-token",
  workspaceId: "your-workspace-id",
});

// Get user details and set userId
try {
  const userDetails = await copaApi.user.getLoggedInUserDetails();
  copaSetConfig({ userId: userDetails.id });
  console.log("User ID set:", userDetails.id);
} catch (error) {
  console.error("Failed to get user details:", error);
}
  • copaSetConfig(partialConfig: Partial<Config>): Updates the configuration.
  • copaGetConfig(): Retrieves the current configuration.
  • resetConfig(): Resets to default empty values.

The Config interface:

export interface Config {
  apiBaseUrl: string;
  accessToken: string;
  workspaceId: string;
  userId: string;
  solutionId?: string;                   // used by InputTableDB
  websocketProvider?: IWebsocketProvider; // enables realtime sync
}

API Reference

All API functions are asynchronous and use the shared apiClient for HTTP requests. They handle errors by throwing objects with message and status. Access via copaApi.moduleName.functionName().

Dataset Module

  • copaApi.dataset.getData(): Retrieves specific dataset data by ID or parameters
  • copaApi.dataset.getDatasets(): Fetches a list of datasets
  • copaApi.dataset.getSampleData(): Gets sample data for datasets

See: dataset/getData.ts, dataset/getSampleData.ts, dataset/getDatasets.ts

Definition Module

  • copaApi.definition.runDefinition(): Executes a custom definition
  • copaApi.definition.runPublishedDefinition(): Runs a published definition
  • copaApi.definition.runSampleDefinition(): Executes a sample definition for testing

See: definition/runPublishedDefinition.ts, definition/runSampleDefinition.ts, definition/runDefinition.ts

File Module

  • copaApi.files.getFileUrlByFileId(fileId: string): Generates a URL for a file by its ID

See: file/getFileUrlByFileId.ts

InputTable Module

  • copaApi.inputTable.getData(): Retrieves data from an input table
  • copaApi.inputTable.getInputTables(): Fetches all input tables
  • copaApi.inputTable.getTableById(id: string): Gets a specific input table by ID

See: inputTable/getData.ts, inputTable/getInputTables.ts, inputTable/getTableById.ts

Metric Module

  • copaApi.metric.getData(): Fetches metric data

See: metric/getData.ts

User Module

  • copaApi.user.getLoggedInUserDetails(): Retrieves details of the currently logged-in user

See: user/getLoggedInUserDetails.ts

Workbook Module

  • copaApi.workbook.getPublishedWorkbookById(id: string): Fetches a published workbook by ID
  • copaApi.workbook.getWorkbooksByType(type: string): Retrieves workbooks filtered by type

See: workbook/getPublishedWorkbookById.ts, workbook/getWorkbooksByType.ts

Workflow Module

  • copaApi.workflow.getWorkflowInstanceStatusById(id: string): Checks the status of a workflow instance
  • copaApi.workflow.triggerHttpWorkflowById(id: string): Triggers an HTTP-based workflow
  • copaApi.workflow.triggerWorkflowById(id: string): Triggers a workflow by ID

See: workflow/triggerHttpWorkflowById.ts, workflow/triggerWorkflowById.ts, workflow/getWorkflowInstanceStatusById.ts

Worksheet Module

  • copaApi.worksheet.getWorksheets(): Fetches all worksheets
  • copaApi.worksheet.getWorksheetsByType(type: string): Retrieves worksheets by type

See: worksheet/getWorksheets.ts, worksheet/getWorksheetsByType.ts

InputTableDB — Reactive Database Client

A Firebase-like client for querying and subscribing to Bluecopa Input Table V2 data. No init required — just import and use.

Full SDK Guide — comprehensive documentation with architecture details, error handling, framework integration (Svelte/React), and all available features.

Quick Start

import { copaSetConfig, copaInputTableDb } from "@bluecopa/core";

// Configure once at app startup
copaSetConfig({
  apiBaseUrl: "https://develop.bluecopa.com",
  accessToken: "your-token",
  workspaceId: "ws-123",
  solutionId: "sol-abc",           // optional — falls back to SOLUTION_ID cookie
  websocketProvider: ws,           // optional — enables realtime sync
});

// Subscribe (reactive — fires on every change)
const unsub = copaInputTableDb.collection("invoices")
  .where("status", "==", "pending")
  .orderBy("updated_at", "desc")
  .limit(50)
  .subscribe((rows) => console.log(rows));

// Cleanup
unsub();

CRUD

// One-time fetch
const rows = await copaInputTableDb.collection("invoices").get();
const inv  = await copaInputTableDb.collection("invoices").doc(id).get();

// Write
const newId = await copaInputTableDb.collection("invoices").add({ vendor: "Acme", amount: 100 });
await copaInputTableDb.collection("invoices").doc(id).update({ status: "approved" });
await copaInputTableDb.collection("invoices").doc(id).delete();

// Listen to a single doc
const unsub = copaInputTableDb.collection("invoices").doc(id).onSnapshot((doc) => {
  console.log(doc);
});

// Reactive count
const unsub = copaInputTableDb.collection("invoices").count((n) => console.log(n));

Query Operators

OperatorMeaning
==equals
!=not equals
<less than
<=less than or eq
>greater than
>=gte
inin array
not-innot in array

Aggregate Queries

Compute server-side aggregates (sum, avg, count, min, max) without fetching all rows. Combines with where(), limit(), and skip() filters.

// Column aggregates
const result = await copaInputTableDb
  .collection("invoices")
  .where("status", "==", "active")
  .aggregate({ amount: ["sum", "avg"], price: ["min", "max"] });
// => { amount: { sum: 1234.56, avg: 123.45 }, price: { min: 10, max: 999 } }

// Row count
const result = await copaInputTableDb
  .collection("invoices")
  .aggregate({ _count: true });
// => { _count: 42 }

// Column count (non-null values) + row count
const result = await copaInputTableDb
  .collection("invoices")
  .aggregate({ name: ["count"], _count: true });
// => { name: { count: 38 }, _count: 42 }

.aggregate() is a terminal method — it bypasses local RxDB and hits PostgREST directly. Errors throw InputTableError. An empty spec {} returns {} without calling the API.

Grouped Aggregates

Add a { groupBy: [...columns] } second argument to get per-group breakdowns. Returns an array instead of a single object.

// Sum per status group
const rows = await copaInputTableDb
  .collection("invoices")
  .aggregate({ amount: ["sum"] }, { groupBy: ["status"] });
// => [{ status: "active", amount: { sum: 1234 } }, { status: "draft", amount: { sum: 100 } }]

// Multi-column groupBy with filters and ordering
const rows = await copaInputTableDb
  .collection("invoices")
  .where("year", "==", 2024)
  .orderBy("order_date", "asc")
  .aggregate({ amount: ["sum", "avg"] }, { groupBy: ["order_date", "status"] });

// Count per group
const rows = await copaInputTableDb
  .collection("invoices")
  .aggregate({ _count: true }, { groupBy: ["status"] });
// => [{ status: "active", _count: 10 }, { status: "draft", _count: 4 }]

// Distinct values (no aggregate functions)
const rows = await copaInputTableDb
  .collection("invoices")
  .aggregate({}, { groupBy: ["status"] });
// => [{ status: "active" }, { status: "draft" }]

Notes:

  • orderBy() is forwarded to PostgREST when groupBy is present (ignored otherwise)
  • limit()/skip() apply to the number of groups, not input rows
  • A column cannot appear in both the aggregate spec and groupBy — throws InputTableError
  • Empty groupBy: [] behaves like no groupBy — returns a single object

Framework Integration

Svelte 5

<script>
  import { copaInputTableDb } from "@bluecopa/core";
  let rows = $state([]);

  $effect(() =>
    copaInputTableDb.collection("invoices")
      .where("status", "==", "pending")
      .subscribe((r) => { rows = r; })
  );
</script>

React

useEffect(() => {
  return copaInputTableDb.collection("invoices")
    .where("status", "==", "pending")
    .subscribe(setRows);
}, []);

Vanilla JS

const unsub = copaInputTableDb.collection("invoices").subscribe(setRows);
// later:
unsub();

WebSocket Provider (optional)

Enables realtime sync via push instead of polling:

import { copaSetConfig, copaInputTableDb, copaUtils } from "@bluecopa/core";

const ws = copaUtils.websocketUtils.WebsocketContextFactory.create("centrifugo", {
  connectionUrl: "wss://...",
  token: "jwt",
  userId: "user-123",
});

// Option A: via config
copaSetConfig({ websocketProvider: ws });

// Option B: set directly
copaInputTableDb.setWebsocketProvider(ws);

If no provider is set, the SDK still works via HTTP pull replication and logs a console warning.

Cleanup

await copaInputTableDb.destroy(); // closes all collections + WebSocket

WebSocket Connection

The core package provides WebSocket utilities for real-time communication using Centrifugo.

WebSocket Factory

Access WebSocket functionality through the utilities:

import { copaUtils } from "@bluecopa/core";

// Create a WebSocket connection
const websocket = copaUtils.websocketUtils.WebsocketContextFactory.create(
  "centrifugo",
  {
    connectionUrl: "wss://your-centrifugo-url",
  },
);

WebSocket Provider Interface

The IWebsocketProvider interface provides the following methods:

  • connect(): Establishes the WebSocket connection
  • bind(channel: string, event: string, callback: (data: any) => void): Subscribe to private user-specific channels
  • bindGlobal(event: string, callback: (data: any) => void): Subscribe to global channels
  • unbindAll(channel: string): Unsubscribe from all events on a channel
  • disconnect(): Close the WebSocket connection

WebSocket Usage Example

import { copaSetConfig, copaApi, copaUtils } from "@bluecopa/core";

// Configure with userId for WebSocket connections
copaSetConfig({
  apiBaseUrl: "https://develop.bluecopa.com",
  accessToken: "your-access-token",
  workspaceId: "your-workspace-id",
  userId: "your-user-id",
});

// Create WebSocket connection
const websocket = copaUtils.websocketUtils.WebsocketContextFactory.create(
  "centrifugo",
  {
    connectionUrl: "wss://centrifugo.your-domain.com/connection/websocket",
  },
);

// Subscribe to user-specific events
websocket.bind("notifications", "new_message", (data) => {
  console.log("New notification:", data);
});

// Subscribe to global events
websocket.bindGlobal("system_updates", (data) => {
  console.log("System update:", data);
});

// Clean up when done
websocket.disconnect();

WebSocket Requirements

  • userId: Required for private channel subscriptions (bind method)
  • accessToken: Required for authentication with Centrifugo
  • connectionUrl: WebSocket endpoint URL

The WebSocket connection automatically uses the configured accessToken and userId from the config for authentication and channel binding.

Examples

1. Complete Setup with User Details and WebSocket

Complete example showing configuration, user details retrieval, and WebSocket setup.

import { copaSetConfig, copaApi, copaUtils } from "@bluecopa/core";

// Initial configuration
copaSetConfig({
  apiBaseUrl: "https://develop.bluecopa.com",
  accessToken: "your-access-token",
  workspaceId: "your-workspace-id",
});

// Get user details and set userId
try {
  const userDetails = await copaApi.user.getLoggedInUserDetails();
  copaSetConfig({ userId: userDetails.id });
  console.log("User configured:", userDetails.name, userDetails.id);
} catch (error: any) {
  console.error("Failed to get user details:", error.message, error.status);
}

// Set up WebSocket connection
const websocket = copaUtils.websocketUtils.WebsocketContextFactory.create(
  "centrifugo",
  {
    connectionUrl: "wss://centrifugo.develop.bluecopa.com/connection/websocket",
  },
);

// Subscribe to notifications
websocket.bind("notifications", "new_message", (data) => {
  console.log("New notification received:", data);
});

2. Get Input Tables

Fetches all input tables from the API.

import { copaApi } from "@bluecopa/core";

// Configure first
copaSetConfig({
  apiBaseUrl: "https://api.example.com",
  accessToken: "token",
  workspaceId: "ws1",
  userId: "user123",
});

// Use API
const { getInputTables } = copaApi.inputTable;
const { getWorkbooksByType } = copaApi.workbook;

3. Get Workbooks by Type

Retrieves workbooks filtered by a specific type.

import { copaApi } from "@bluecopa/core";
import type { Worksheet } from "$models/gen/Api";

try {
  const workbooks = await copaApi.workbook.getWorkbooksByType(
    "dashboard" as Worksheet["type"],
  );
  console.log(workbooks); // Array of Worksheet
} catch (error: any) {
  console.error(error.message, error.status);
}

Development

  • Run the build: npm run build (in the root or package-specific script)
  • TypeScript configuration: See tsconfig.json
  • Vite configuration: See vite.config.ts

FAQs

Package last updated on 02 May 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