@bluecopa/core

中文文档
0.1.127发布于 2026/10/13MITTypeScriptES Module近 30 天下载 9873

The core package is Bluecopa's TypeScript API SDK. It provides a configured Axios client, a namespaced API surface (copaApi.*) covering every platform domain, a curated api/hub client, a Firebase-like reactive Input Table DB, Centrifugo/Pusher WebSocket

原始使用文档
文档目录63 节
  1. Table of Contents
  2. Installation
  3. Requirements
  4. Configuration
  5. The Config interface
  6. Setting the user id from the logged-in user
  7. API Reference
  8. user
  9. team
  10. workflow
  11. files ( copaApi.files )
  12. definition
  13. metric
  14. chat
  15. dataset
  16. inputTable
  17. workbook
  18. worksheet
  19. statement
  20. task
  21. recon
  22. reconV2
  23. form
  24. audit
  25. templatedPipeline
  26. process
  27. processTree
  28. inboxItems
  29. inboxV2
  30. permissions
  31. customAuthz
  32. clientIp
  33. emailEngine
  34. periodManagement
  35. databox
  36. tcn
  37. templates
  38. pipeline
  39. workingPaper
  40. solutions
  41. versioning
  42. externalApps
  43. Curated hub modules ( /blui-api )
  44. Top-level exports
  45. InputTableDB — Reactive Database Client
  46. Quick Start
  47. CRUD
  48. Query Operators
  49. Aggregate Queries
  50. Grouped Aggregates
  51. Framework Integration
  52. WebSocket Provider (optional)
  53. Cleanup
  54. WebSocket Connection
  55. WebSocket Factory
  56. WebSocket Provider Interface
  57. WebSocket Usage Example
  58. WebSocket Requirements
  59. Examples
  60. Configure, then fetch input tables
  61. Get workbooks by type
  62. Development
  63. Related Packages

@bluecopa/core npm version License

The core package is Bluecopa's TypeScript API SDK. It provides a configured Axios client, a namespaced API surface (copaApi.*) covering every platform domain, a curated api/hub client, a Firebase-like reactive Input Table DB, Centrifugo/Pusher WebSocket utilities, and the shared Tailwind config.

Table of Contents

Installation

npm install @bluecopa/core
# or
pnpm add @bluecopa/core

Check the npm badge above for the current published version.

Requirements

  • Node.js ^20.19.0 || >=22.12.0
  • Runtime dependencies:
    • axios (1.16.0) — HTTP requests
    • centrifuge (5.2.2) — Centrifugo WebSocket connections
    • pusher-js (^8.3.0) — Pusher WebSocket connections
    • rxdb (^16.21.1) + rxjs (^7.5.4) — reactive Input Table DB
    • lodash (4.18.1) — utility functions

Configuration

The package uses a singleton config. Set it once before making API calls.

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

copaSetConfig({
    apiBaseUrl: 'https://develop.bluecopa.com/api/v1', // data-plane base URL
    accessToken: 'your-access-token', // auth token
    workspaceId: 'your-workspace-id', // active workspace
    userId: 'your-user-id' // used by WebSocket private channels
});
  • copaSetConfig(partialConfig: Partial<Config>) — merges into the current config.
  • copaGetConfig() — returns a copy of the current config.

The Config interface

export interface Config {
    apiBaseUrl: string;
    hubBaseUrl?: string; // curated /blui-api base; derived from apiBaseUrl when unset
    accessToken: string;
    workspaceId: string;
    userId: string;
    solutionId?: string; // solution-scoped requests + InputTableDB
    solutionBranch?: string; // solution branch name
    solutionBranchType?: string; // 'LOCAL' | 'REMOTE'
    deployedSolution?: boolean; // forwards x-bluecopa-deployed-solution: true
    websocketProvider?: IWebsocketProvider; // enables realtime sync
}

The SDK forwards workspace and solution context (branch, branch type, deployed flag) as request headers automatically. Set the solution fields (or a solutionId cookie) to make calls solution-aware.

Setting the user id from the logged-in user

copaSetConfig({
    apiBaseUrl: 'https://develop.bluecopa.com/api/v1',
    accessToken: 'your-access-token',
    workspaceId: 'your-workspace-id'
});

const userDetails = await copaApi.user.getLoggedInUserDetails();
copaSetConfig({ userId: userDetails.id });

API Reference

All API functions are asynchronous, use the shared apiClient, and normalise errors by throwing objects with { message, status }. Access them as copaApi.<module>.<function>(). Modules tagged (hub) target the curated /blui-api surface via hubClient rather than the data-plane apiClient.

user

  • copaApi.user.getLoggedInUserDetails(): Fetches the authenticated user's profile.
  • copaApi.user.getAllUsers(): Lists all users in the workspace.

team

  • copaApi.team.getAllTeams(): Lists all teams in the workspace.

workflow

  • copaApi.workflow.triggerHttpWorkflowById(): Triggers an HTTP workflow by id.
  • copaApi.workflow.triggerWorkflowById(): Triggers a workflow by id.
  • copaApi.workflow.getWorkflowInstanceStatusById(): Gets a workflow instance's status.
  • copaApi.workflow.getAllHttpTriggers(): Lists all HTTP workflow triggers.

files (copaApi.files)

  • copaApi.files.getFileUrlByFileId(): Returns a (presigned) URL for a file id.
  • copaApi.files.fileUpload(): Uploads a file and returns its metadata.
  • copaApi.files.fileDownload(): Downloads a file's contents.
  • copaApi.files.getFileByFolderIdAndName(): Looks up a filebox file by folder id + name.
  • copaApi.files.getFileById(): Fetches a file's metadata by id.

definition

  • copaApi.definition.runDefinition(): Runs a draft definition.
  • copaApi.definition.runPublishedDefinition(): Runs a published definition.
  • copaApi.definition.runSampleDefinition(): Runs a definition against sample data.
  • copaApi.definition.getDescription(): Retrieves a definition's description/metadata.

metric

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

chat

  • copaApi.chat.createThread(): Creates a comment thread.
  • copaApi.chat.getCommentsByThreadId(): Lists comments in a thread.
  • copaApi.chat.postComment(): Posts a comment to a thread.
  • copaApi.chat.updateComment(): Edits a comment.
  • copaApi.chat.deleteComment(): Deletes a comment.
  • copaApi.chat.subscribeUser(): Subscribes a user to a thread.
  • copaApi.chat.unsubscribeUser(): Unsubscribes a user from a thread.
  • copaApi.chat.checkSubscriptionStatus(): Checks a user's subscription to a thread.

dataset

  • copaApi.dataset.getData(): Fetches dataset row data.
  • copaApi.dataset.getSampleData(): Fetches a sample of dataset rows.
  • copaApi.dataset.getAllDatasets(): Lists all datasets.
  • copaApi.dataset.getVirtualDatasets(): Lists virtual datasets.
  • copaApi.dataset.getDatasetExceptions(): Fetches exception rows for a dataset.
  • copaApi.dataset.getDatasetDuplicates(): Fetches duplicate rows for a dataset.

inputTable

  • copaApi.inputTable.getData(): Fetches input table data.
  • copaApi.inputTable.getTableById(): Fetches an input table definition by id.
  • copaApi.inputTable.getInputTables(): Lists all input tables.
  • copaApi.inputTable.getRows(): Reads rows (filters, paging, sorting).
  • copaApi.inputTable.insertRow(): Inserts a row.
  • copaApi.inputTable.updateRow(): Updates a row.
  • copaApi.inputTable.deleteRow(): Deletes a row.

workbook

  • copaApi.workbook.getWorkbooksByType(): Lists workbooks of a given type.
  • copaApi.workbook.getPublishedWorkbookById(): Fetches a published workbook by id.
  • copaApi.workbook.getWorkbookDetails(): Fetches full workbook details.
  • copaApi.workbook.saveWorkbook(): Saves a workbook draft.
  • copaApi.workbook.publishWorkbook(): Publishes a workbook.
  • copaApi.workbook.deleteWorkbook(): Deletes a workbook.

worksheet

  • copaApi.worksheet.getWorksheets(): Fetches worksheets by id.
  • copaApi.worksheet.getWorksheetsByType(): Lists worksheets of a given type.
  • copaApi.worksheet.getWorksheetModel(): Fetches a worksheet's model JSON by sheet id.

statement

  • copaApi.statement.getData(): Fetches statement data.
  • copaApi.statement.getViewsBySheetId(): Lists statement views for a sheet.
  • copaApi.statement.getViewById(): Fetches a statement view by id.
  • copaApi.statement.getRunsByViewId(): Lists runs for a view.
  • copaApi.statement.createNewRun(): Starts a new statement run.
  • copaApi.statement.getRunResultById(): Fetches a statement run's result.

task

  • copaApi.task.getTaskDetails(): Fetches details of a task.

recon

  • copaApi.recon.runRecon(): Runs a (v1) reconciliation workflow.
  • copaApi.recon.getAllReconWorkflows(): Lists all (v1) recon workflows.

reconV2

  • copaApi.reconV2.createReconV2(): Creates a recon v2 workflow.
  • copaApi.reconV2.updateReconV2(): Updates a recon v2 workflow.
  • copaApi.reconV2.deleteReconV2(): Deletes a recon v2 workflow.
  • copaApi.reconV2.runReconV2(): Runs a recon v2 workflow.
  • copaApi.reconV2.getAllReconV2Workflows(): Lists all recon v2 workflows.
  • copaApi.reconV2.getReconV2Workflow(): Fetches a single recon v2 workflow.
  • copaApi.reconV2.getReconV2Runs(): Lists runs for a recon v2 workflow.
  • copaApi.reconV2.getReconV2RunResult(): Fetches a recon v2 run's result.
  • copaApi.reconV2.getReconV2SmartResult(): Fetches the AI-assisted result of a run.
  • copaApi.reconV2.startReconV2Profile(): Starts a data-profiling job.
  • copaApi.reconV2.getReconV2ProfileResult(): Fetches the profiling result.
  • copaApi.reconV2.startReconV2Clean(): Starts a data-cleaning job.
  • copaApi.reconV2.getReconV2CleanResult(): Fetches the cleaning result.
  • copaApi.reconV2.getReconV2Diff(): Fetches the diff between datasets/runs.
  • copaApi.reconV2.getReconV2Explanation(): Fetches an explanation for a match/result.
  • copaApi.reconV2.getReconV2Templates(): Fetches the recon v2 template catalog.

form

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

audit

  • copaApi.audit.getAuditLogs(): Fetches audit log entries.
  • copaApi.audit.createAuditLog(): Creates an audit log entry.

templatedPipeline

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

process

  • copaApi.process.markTaskDone(): Marks a process task as done.
  • copaApi.process.reassignTask(): Reassigns a process task.
  • copaApi.process.getTriggersBySheet(): Lists process triggers for a sheet.
  • copaApi.process.registerProcessTrigger(): Registers a process trigger.
  • copaApi.process.deleteProcessTrigger(): Deletes a process trigger.
  • copaApi.process.pauseSchedule(): Pauses a scheduled trigger.
  • copaApi.process.resumeSchedule(): Resumes a paused schedule.
  • copaApi.process.getScheduleStatus(): Gets a schedule's status.
  • copaApi.process.executeNow(): Executes a scheduled process immediately.

processTree

  • copaApi.processTree.createOrUpdateProcessTreeTrigger(): Creates/updates a process-tree trigger.
  • copaApi.processTree.executeProcessTreeTrigger(): Executes a process-tree trigger.
  • copaApi.processTree.terminatePipelines(): Terminates running pipelines for a process tree.
  • copaApi.processTree.logProcessTreeRun(): Records a process-tree run.
  • copaApi.processTree.updateProcessTreeRunContext(): Updates a run's context.
  • copaApi.processTree.getProcessTreeTrigger(): Fetches a trigger by id.
  • copaApi.processTree.deleteProcessTreeTrigger(): Deletes a trigger.
  • copaApi.processTree.getProcessTreeTriggersBySheetId(): Lists triggers for a sheet.
  • copaApi.processTree.getProcessTreeRunsBySheetId(): Lists runs for a sheet.
  • copaApi.processTree.getProcessTreeRunsBySheetIdPaginated(): Lists runs for a sheet (paged).
  • copaApi.processTree.getProcessTreeRunByInstanceId(): Fetches a run by instance id.

inboxItems

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

inboxV2

  • copaApi.inboxV2.listTypes() / createType() / getType() / updateType() / deleteType(): Manage inbox item types.
  • copaApi.inboxV2.listMyItems(): Lists the current user's inbox items.
  • copaApi.inboxV2.createItem() / getItem() / updateItem(): Manage inbox items.
  • copaApi.inboxV2.markRead() / markUnread(): Mark items read/unread.
  • copaApi.inboxV2.snoozeItem() / dismissItem(): Snooze or dismiss an item.
  • copaApi.inboxV2.claimItem() / completeItem() / releaseItem(): Claim, complete, or release an actionable item.
  • copaApi.inboxV2.cancelItem() / reassignItem(): Cancel or reassign an item.
  • copaApi.inboxV2.completeByKey() / cancelByKey(): Complete/cancel by business key.

permissions

  • copaApi.permissions.getPermissions(): Fetches permissions for the current user/object.

customAuthz

  • copaApi.customAuthz.getCustomAuthzModel(): Fetches the custom authorization model.
  • copaApi.customAuthz.registerCustomAuthzModel(): Registers/replaces the model.
  • copaApi.customAuthz.updateCustomObjectPermissions(): Updates permissions on an object.
  • copaApi.customAuthz.bulkUpdateCustomObjectPermissions(): Bulk-updates object permissions.
  • copaApi.customAuthz.checkCustomPermissions(): Checks a permission.
  • copaApi.customAuthz.bulkCheckCustomPermissions(): Bulk-checks permissions.

clientIp

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

emailEngine

  • copaApi.emailEngine.getAllConversations(): Lists email conversations (paged).
  • copaApi.emailEngine.getConversation(): Fetches a single conversation.
  • copaApi.emailEngine.createConversation(): Creates a conversation.
  • copaApi.emailEngine.replyToConversation(): Replies to a conversation.
  • copaApi.emailEngine.getMessageBySenderId(): Fetches messages by sender id.
  • copaApi.emailEngine.searchMessages(): Searches email messages.

periodManagement

  • copaApi.periodManagement.createFiscalCalendar() / listFiscalCalendars() / getFiscalCalendar() / updateFiscalCalendar() / deleteFiscalCalendar(): Manage fiscal calendars.
  • copaApi.periodManagement.createHolidayCalendar() / listHolidayCalendars() / getHolidayCalendar() / updateHolidayCalendar() / deleteHolidayCalendar(): Manage holiday calendars.
  • copaApi.periodManagement.listHolidays() / importHolidays(): List or bulk-import holidays.

databox

  • copaApi.databox.getDataboxFolder() / getDataboxFolderFiles() / getDataboxFolderDatasets() / getDataboxFolderDuplicates(): Read a databox folder and its contents.
  • copaApi.databox.getDataboxFolderSchema() / updateDataboxFolderSchema() / getDataboxSchemaHistory(): Manage a folder's schema.
  • copaApi.databox.dropFileToDatabox() / runDataboxFolder(): Upload a file / run folder processing.
  • copaApi.databox.getDataboxFile() / getDataboxFileStatus() / getDataboxFileRuns() / getDataboxFileDownloadUrl(): Read a databox file.
  • copaApi.databox.getDataboxTrashFiles() / trashDataboxFiles() / restoreDataboxFile() / permanentDeleteDataboxFiles(): Trash lifecycle.

tcn

TCN (contact-center) integration. Selected functions:

  • copaApi.tcn.getAuthUrl() / exchangeCode() / refreshToken(): OAuth flow.
  • copaApi.tcn.getCurrentAgent() / getAgentSkills() / createSession() / keepAlive(): Agent session lifecycle.
  • copaApi.tcn.agentGetStatus() / agentSetReady() / agentPause() / agentDisconnect(): Agent state.
  • copaApi.tcn.agentGetConnectedParty() / getCallData() / agentPutCallOnHold() / agentGetCallFromHold(): Active call control.
  • copaApi.tcn.getHuntGroupAgentSettings() / dialManualPrepare() / manualDialStart() / processManualDial() / ftpManualDialReport(): Manual dialing.

templates

  • copaApi.templates.renderTemplate(): Renders a template with the given engine and data.

pipeline

  • copaApi.pipeline.getPipelines() / getPipelineList(): List pipelines (full / lightweight).
  • copaApi.pipeline.getPipelineRuns() / getPipelineRunStatus(): Runs and run status.
  • copaApi.pipeline.getPipelineDefinition() / buildDatasetDefinition(): Read/build a definition.
  • copaApi.pipeline.getPipelineOverview(): Fetch inputs/outputs overview.
  • copaApi.pipeline.startOutputSample() / getOutputSampleResult(): Output-sample job.
  • copaApi.pipeline.savePipeline() / runPipeline(): Save / run (hub).

workingPaper

  • copaApi.workingPaper.getWorkingPapers() / getWorkingPaper() / createWorkingPaper() / updateWorkingPaper() / deleteWorkingPaper(): CRUD for working papers.
  • copaApi.workingPaper.createFxDatasetDefinition() / fxBaseTable() / addRuleFilter() / addSort() / addMetric() / addPivot() / addColumn(): Fx-definition composition helpers.

solutions

  • copaApi.solutions.getSolutionList(): Lists solutions.
  • copaApi.solutions.create(): Creates a solution.
  • copaApi.solutions.packagableComponents(): Lists packagable components.
  • copaApi.solutions.addObjects(): Adds objects to a solution.
  • copaApi.solutions.validate() / publish() / publishJob(): Validate, publish, and poll a publish job.
  • copaApi.solutions.setSolutionSeedData(): Sets deploy-time seed data.

versioning

  • copaApi.versioning.getBranches() / createBranch() / pushBranch() / mergeBranches(): Branch operations.
  • copaApi.versioning.listCommits() / commitChanges() / listTags(): Commits and tags.

externalApps

  • copaApi.externalApps.create(): Creates an external app.
  • copaApi.externalApps.setEnv() / setSchemaMap() / setAccessControl(): Configure env, schema map, and access control.
  • copaApi.externalApps.validateUrl(): Validates an external app URL.

Curated hub modules (/blui-api)

These target the curated api/hub via hubClient.

  • workbooks (hub): create(), listWorkbooks(), getWorkbook().
  • connections (hub): createSftpConnection(), createEmailConnection(), createBlobConnection(), testConnection(), listConnections().
  • ingestion (hub): createDatabox(), createFileboxFolder(), listDataboxes(), listFileboxFolders().
  • inputTableV2 (hub): listInputTables(), getInputTable(), createInputTable(), deleteInputTable(), getInputTableSchema(), readInputTableRows(), insertInputTableRows(), updateInputTableRows(), deleteInputTableRows().
  • workflowV2 (hub): listWorkflows(), getWorkflow(), saveWorkflow().
  • processHub (hub): registerTrigger(), deleteTrigger(), executeTriggerNow(), pauseTrigger(), resumeTrigger(), skipTrigger(), triggerScheduleStatus(), upcomingSchedules(), triggersBySheet(), sheetRuns(), sheetRunStatus().
  • datasetsHub (hub): getDatasetSchema(), searchDatasets(), getDatasetStats().
  • virtualDatasets (hub): listVirtualDatasets(), getVirtualDataset(), createVirtualDataset().
  • exportConfig (hub): listExportConfigs(), getExportConfig(), createExportConfig(), updateExportConfig(), runExportConfig().
  • dashboards (hub): listDashboards(), getDashboard(), createDashboard(), addDashboardWidget(), updateDashboardWidget(), removeDashboardWidget().
  • httpTriggersHub (hub): listHttpTriggers(), getHttpTrigger().

Top-level exports

Besides copaApi, the package root exports:

  • copaSetConfig / copaGetConfig — set/read the SDK config.
  • hubClient — Axios client for the curated /blui-api hub (same auth/workspace/solution headers as apiClient, targeting config.hubBaseUrl or a value derived from apiBaseUrl). Use it for hub endpoints not yet wrapped in a copaApi.* module.
  • copaUtils — utility helpers, including copaUtils.websocketUtils.WebsocketContextFactory (see WebSocket Connection).
  • copaInputTableDb — the reactive Input Table DB client, plus InputTableColumnType and InputTableError (see below).
  • copaTailwindConfig — the shared Bluecopa Tailwind config.

The root also re-exports a large set of TypeScript types (audit, recon v2, pipeline node catalogue, etc.) for SDK consumers.

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/api/v1',
    accessToken: 'your-token',
    workspaceId: 'ws-123',
    solutionId: 'sol-abc' // optional — falls back to SOLUTION_ID cookie
    // websocketProvider: ws — optional, enables realtime sync (see "WebSocket Provider" below)
});

// 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 unsubCount = 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 } }]

// 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 (and Pusher).

WebSocket Factory

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

const websocket = copaUtils.websocketUtils.WebsocketContextFactory.create('centrifugo', {
    connectionUrl: 'wss://your-centrifugo-url'
});

WebSocket Provider Interface

The IWebsocketProvider interface provides:

  • connect(): Establishes the connection
  • bind(channel, event, callback): Subscribe to a private user-specific channel
  • bindGlobal(event, callback): Subscribe to a global channel
  • unbindAll(channel): Unsubscribe from all events on a channel
  • disconnect(): Close the connection

WebSocket Usage Example

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

copaSetConfig({
    apiBaseUrl: 'https://develop.bluecopa.com/api/v1',
    accessToken: 'your-access-token',
    workspaceId: 'your-workspace-id',
    userId: 'your-user-id'
});

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

websocket.bind('notifications', 'new_message', (data) => {
    console.log('New notification:', data);
});

websocket.bindGlobal('system_updates', (data) => {
    console.log('System update:', data);
});

websocket.disconnect();

WebSocket Requirements

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

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

Examples

Configure, then fetch input tables

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

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

const inputTables = await copaApi.inputTable.getInputTables();

Get workbooks by type

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

try {
    const workbooks = await copaApi.workbook.getWorkbooksByType('dashboard');
    console.log(workbooks);
} catch (error: any) {
    console.error(error.message, error.status);
}

Development

  • Build: npm run build (Vite) — npm run build:umd for the UMD bundle
  • Watch: npm run dev
  • Test: npm run test / npm run test:watch / npm run test:coverage
  • TypeScript config: tsconfig.json; Vite config: vite.config.ts

版本与发布记录

@bluecopa/core 共发布 122 个版本,首次发布于 2025/09/05;过去 12 个月发布了 109 个版本。

版本发布日期距今
0.1.127latest2026/10/1325 天前
0.1.1262026/09/211 个月前
0.1.1252026/09/161 个月前
0.1.1242026/09/072 个月前
0.1.1232026/09/022 个月前
0.1.1222026/08/172 个月前

关于 @bluecopa/core 的常见问题

@bluecopa/core 是什么?

The core package is Bluecopa's TypeScript API SDK. It provides a configured Axios client, a namespaced API surface (copaApi.*) covering every platform domain, a curated api/hub client, a Firebase-like reactive Input Table DB, Centrifugo/Pusher WebSocket

如何安装 @bluecopa/core?

在项目目录运行 npm install @bluecopa/core,或使用 pnpm add / yarn add / bun add。

@bluecopa/core 支持 TypeScript 吗?

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

@bluecopa/core 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@bluecopa/core 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js ^20.19.0 || >=22.12.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@bluecopa/core 可以商用吗?

@bluecopa/core 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@bluecopa/core 的下载量有多少?

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

@bluecopa/core 还在维护吗?

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