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.

latest
npmnpm
Version
0.1.100
Version published
Weekly downloads
2.5K
128.93%
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().

Audit Module

  • copaApi.audit.createAuditLog(): Records an audit log entry
  • copaApi.audit.getAuditLogs(): Retrieves audit log entries

See: audit/createAuditLog.ts, audit/getAuditLogs.ts

Chat Module

  • copaApi.chat.checkSubscriptionStatus(): Checks whether the user is subscribed to chat updates
  • copaApi.chat.createThread(): Creates a new chat thread
  • copaApi.chat.getCommentsByThreadId(): Lists comments in a thread
  • copaApi.chat.postComment(): Posts a comment to a thread
  • copaApi.chat.updateComment(): Updates an existing comment
  • copaApi.chat.deleteComment(): Deletes a comment
  • copaApi.chat.subscribeUser(): Subscribes a user to chat updates
  • copaApi.chat.unsubscribeUser(): Unsubscribes a user from chat updates

See: chat/

ClientIp Module

  • copaApi.clientIp.getClientIp(): Returns the caller's client IP

See: clientIp/getClientIp.ts

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

EmailEngine Module

  • copaApi.emailEngine.getAllConversations(): Lists email conversations (paginated)
  • copaApi.emailEngine.getConversation(): Fetches a single conversation
  • copaApi.emailEngine.createConversation(): Creates a new conversation
  • copaApi.emailEngine.replyToConversation(): Sends a reply on a conversation
  • copaApi.emailEngine.getMessageBySenderId(): Retrieves messages filtered by sender id

See: emailEngine/

File Module

  • copaApi.files.getFileUrlByFileId(fileId: string): Generates a URL for a file by its ID
  • copaApi.files.fileUpload({ data, contentType, method, uploadType }): Uploads data and returns a file id/path
  • copaApi.files.fileDownload({ fileId }): Downloads a file by id
  • copaApi.files.getFileByFolderIdAndName({ folderId, name }): Fetches a filebox file by its parent folder and name

See: file/getFileUrlByFileId.ts, file/fileUpload.ts, file/fileDownload.ts, file/getFileByFolderIdAndName.ts

Form Module

  • copaApi.form.getFormById(): Fetches a form by id
  • copaApi.form.getFormSchema(): Retrieves a form's schema
  • copaApi.form.getFormData(): Retrieves submitted form data
  • copaApi.form.createOrUpdateForm(): Creates or updates a form definition

See: form/

InboxItems Module

  • copaApi.inboxItems.getAllInboxItems(): Lists inbox items
  • copaApi.inboxItems.createInboxItemPerUser(): Creates an inbox item for a specific user
  • copaApi.inboxItems.markItemAsRead(): Marks an inbox item as read
  • copaApi.inboxItems.markItemAsUnread(): Marks an inbox item as unread

See: inboxItems/

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
  • copaApi.inputTable.getRows(options): Reads rows from an input table view (filters, paging, sorting)
  • copaApi.inputTable.insertRow(options): Inserts a new row
  • copaApi.inputTable.updateRow(options): Updates an existing row
  • copaApi.inputTable.deleteRow(options): Deletes a row

See: inputTable/getData.ts, inputTable/getInputTables.ts, inputTable/getTableById.ts, inputTable/getRows.ts, inputTable/insertRow.ts, inputTable/updateRow.ts, inputTable/deleteRow.ts

Metric Module

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

See: metric/getData.ts

Permissions Module

  • copaApi.permissions.getPermissions(): Retrieves permissions for the current user / context

See: permissions/getPermissions.ts

Process Module

  • copaApi.process.markTaskDone(): Marks a process task as done
  • copaApi.process.reassignTask(): Reassigns a process task to a different user
  • copaApi.process.getTriggersBySheet(): Lists triggers associated with a sheet
  • copaApi.process.registerProcessTrigger(): Registers a new process trigger
  • copaApi.process.deleteProcessTrigger(): Deletes a process trigger

See: process/

Recon Module

  • copaApi.recon.runRecon(): Triggers a recon workflow run
  • copaApi.recon.getAllReconWorkflows(): Lists all recon workflows

See: recon/runRecon.ts, recon/getAllReconWorkflows.ts

Statement Module

  • copaApi.statement.getData(): Retrieves statement data
  • copaApi.statement.getViewsBySheetId(): Lists statement views for a sheet
  • copaApi.statement.getViewById(): Fetches a single statement view
  • copaApi.statement.getRunsByViewId(): Lists runs for a given view
  • copaApi.statement.createNewRun(): Creates a new statement run
  • copaApi.statement.getRunResultById(): Fetches the result of a given run

See: statement/

Task Module

  • copaApi.task.getTaskDetails(): Fetches detailed information about a task

See: task/getTaskDetails.ts

TemplatedPipeline Module

  • copaApi.templatedPipeline.getAllTemplatedPipelines(): Lists all templated pipelines

See: templatedPipeline/getAllTemplatedPipelines.ts

Templates Module

  • copaApi.templates.renderTemplate(): Renders a template with provided variables

See: templates/render.ts

Tcn Module

  • copaApi.tcn.getAuthUrl(): Returns the TCN OAuth authorization URL
  • copaApi.tcn.exchangeCode(): Exchanges an OAuth code for TCN tokens
  • copaApi.tcn.refreshToken(): Refreshes a TCN access token
  • copaApi.tcn.getCurrentAgent(): Fetches the currently signed-in TCN agent
  • copaApi.tcn.getAgentSkills(): Lists skills available to the agent
  • copaApi.tcn.createSession(): Creates a new TCN agent session
  • copaApi.tcn.keepAlive(): Pings the TCN session to keep it alive
  • copaApi.tcn.agentGetStatus(): Returns the current agent status
  • copaApi.tcn.agentSetReady(): Marks the agent as ready
  • copaApi.tcn.agentPause(): Pauses the agent
  • copaApi.tcn.agentDisconnect(): Disconnects the agent
  • copaApi.tcn.agentGetConnectedParty(): Returns the currently connected party for the agent
  • copaApi.tcn.agentPutCallOnHold(): Puts the agent's current call on hold
  • copaApi.tcn.agentGetCallFromHold(): Resumes the agent's held call
  • copaApi.tcn.getHuntGroupAgentSettings(): Fetches hunt-group settings for the agent
  • copaApi.tcn.getCallData(): Retrieves data for an active call
  • copaApi.tcn.dialManualPrepare(): Prepares a manual dial
  • copaApi.tcn.manualDialStart(): Starts a prepared manual dial
  • copaApi.tcn.processManualDial(): Processes the result of a manual dial

See: tcn/

User Module

  • copaApi.user.getLoggedInUserDetails(): Retrieves details of the currently logged-in user
  • copaApi.user.getAllUsers(): Lists all users in the workspace

See: user/getLoggedInUserDetails.ts, user/getAllUsers.ts

Workbook Module

  • copaApi.workbook.getPublishedWorkbookById(id: string): Fetches a published workbook by ID
  • copaApi.workbook.getWorkbooksByType(type: string): Retrieves workbooks filtered by type
  • copaApi.workbook.getWorkbookDetails(): Retrieves workbook metadata/details
  • copaApi.workbook.saveWorkbook(): Saves a workbook draft
  • copaApi.workbook.publishWorkbook(): Publishes a workbook

See: workbook/getPublishedWorkbookById.ts, workbook/getWorkbooksByType.ts, workbook/getWorkbookDetails.ts, workbook/saveWorkbook.ts, workbook/publishWorkbook.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
  • copaApi.workflow.getAllHttpTriggers(): Lists all HTTP triggers

See: workflow/triggerHttpWorkflowById.ts, workflow/triggerWorkflowById.ts, workflow/getWorkflowInstanceStatusById.ts, workflow/getAllHttpTriggers.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 10 Jun 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