@centrali-io/centrali-sdk 4.4.4 → 4.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,6 +4,8 @@ Official Node.js SDK for Centrali - Build modern web applications without managi
4
4
 
5
5
  [![npm version](https://badge.fury.io/js/%40centrali-io%2Fcentrali-sdk.svg)](https://www.npmjs.com/package/@centrali-io/centrali-sdk)
6
6
 
7
+ > **Full documentation:** [docs.centrali.io](https://docs.centrali.io) — SDK guide, API reference, compute functions, orchestrations, and more.
8
+
7
9
  > **Try it now!** Explore the SDK in our [Live Playground on StackBlitz](https://stackblitz.com/~/github.com/centrali-demo/sdk-playground) - no setup required.
8
10
 
9
11
  ## Installation
@@ -20,7 +22,7 @@ import { CentraliSDK } from '@centrali-io/centrali-sdk';
20
22
  // Initialize the SDK
21
23
  const centrali = new CentraliSDK({
22
24
  baseUrl: 'https://centrali.io',
23
- workspaceId: 'your-workspace',
25
+ workspaceId: 'your-workspace-slug', // This is the workspace slug, not a UUID
24
26
  token: 'your-api-key'
25
27
  });
26
28
 
@@ -40,7 +42,16 @@ console.log('Found:', results.data.totalHits, 'results');
40
42
 
41
43
  ## Authentication
42
44
 
43
- The SDK supports three authentication methods. See the [full authentication guide](../docs/sdk/authentication.md) for details.
45
+ The SDK supports three authentication methods. See the [full authentication guide](https://docs.centrali.io/guides/centrali-sdk#authentication) for details.
46
+
47
+ ### Recommended Auth by Context
48
+
49
+ | Context | Method | Why |
50
+ |---------|--------|-----|
51
+ | **Browser / frontend app** | Publishable key | Safe to expose in client code, scoped to specific resources |
52
+ | **Server app / API route** | Service account | Server-to-server, automatic token refresh |
53
+ | **MCP agent** | Service account (env vars) | `CENTRALI_CLIENT_ID` + `CENTRALI_CLIENT_SECRET` + `CENTRALI_WORKSPACE_ID` |
54
+ | **App with its own auth (Clerk, Auth0)** | External token / BYOT | Dynamic token callback |
44
55
 
45
56
  ### Publishable Key (Frontend Apps)
46
57
 
@@ -49,7 +60,7 @@ Safe to use in browser code. Scoped to specific resources.
49
60
  ```typescript
50
61
  const centrali = new CentraliSDK({
51
62
  baseUrl: 'https://centrali.io',
52
- workspaceId: 'your-workspace',
63
+ workspaceId: 'your-workspace-slug',
53
64
  publishableKey: 'pk_live_your_key_here'
54
65
  });
55
66
  ```
@@ -61,7 +72,7 @@ Dynamic token callback for apps with their own auth.
61
72
  ```typescript
62
73
  const centrali = new CentraliSDK({
63
74
  baseUrl: 'https://centrali.io',
64
- workspaceId: 'your-workspace',
75
+ workspaceId: 'your-workspace-slug',
65
76
  getToken: async () => await clerk.session.getToken()
66
77
  });
67
78
  ```
@@ -73,12 +84,14 @@ Never use in browser code. Client secret must stay on the server.
73
84
  ```typescript
74
85
  const centrali = new CentraliSDK({
75
86
  baseUrl: 'https://centrali.io',
76
- workspaceId: 'your-workspace',
87
+ workspaceId: 'your-workspace-slug',
77
88
  clientId: process.env.CENTRALI_CLIENT_ID,
78
89
  clientSecret: process.env.CENTRALI_CLIENT_SECRET
79
90
  });
80
91
  ```
81
92
 
93
+ > **Note:** `workspaceId` is always the **workspace slug** (e.g., `"acme"`), not a UUID.
94
+
82
95
  ## Features
83
96
 
84
97
  - ✅ **Type-safe API** with full TypeScript support
@@ -403,17 +416,106 @@ const realtime = new RealtimeManager(
403
416
  );
404
417
  ```
405
418
 
406
- ### Compute Functions (via Triggers)
419
+ ### Compute Functions
420
+
421
+ Compute functions are JavaScript code blocks that execute in a sandboxed environment. Every function uses the same signature:
422
+
423
+ ```javascript
424
+ async function run() {
425
+ // Three variables are available:
426
+ // - api: SDK for records, HTTP, files, crypto, logging
427
+ // - triggerParams: static config from the trigger definition
428
+ // - executionParams: dynamic data from the current invocation
429
+
430
+ const result = await api.httpRequest({
431
+ url: 'https://api.example.com/data',
432
+ method: 'POST',
433
+ body: JSON.stringify(executionParams.payload)
434
+ });
435
+
436
+ return { success: true, data: result };
437
+ }
438
+ ```
439
+
440
+ > **Important:** Use `async function run() { ... }`. Do NOT use `module.exports`.
441
+
442
+ #### Compute Input Contract
443
+
444
+ What `triggerParams` and `executionParams` contain depends on how the function is invoked:
445
+
446
+ | Trigger type | `triggerParams` | `executionParams` |
447
+ |--------------|-----------------|-------------------|
448
+ | **HTTP trigger** | Static params from trigger definition | `{ payload }` — parsed request body |
449
+ | **Endpoint trigger** | Static params from trigger definition | `{ payload, method, headers, query }` — full HTTP context |
450
+ | **Scheduled trigger** | Static params from trigger definition (max 64KB) | `{}` — empty |
451
+ | **Pages action** | `{ input, token }` — from page action invocation | `{}` — empty |
452
+ | **Orchestration step** | Orchestration input + previous step outputs + decrypted encrypted params | Not used (all input arrives via `triggerParams`) |
453
+
454
+ #### The `api` Object
455
+
456
+ Every compute function has access to `api`, which provides:
457
+
458
+ | Category | Methods |
459
+ |----------|---------|
460
+ | **Records** | `queryRecords`, `fetchRecord`, `createRecord`, `updateRecord`, `deleteRecord`, `bulkCreateRecords`, `bulkUpdateRecords`, `bulkDeleteRecords` |
461
+ | **HTTP** | `httpRequest`, `httpFetch` (outbound calls to allowed domains) |
462
+ | **Files** | `storeFile`, `storeAsCSV`, `storeAsJSON` |
463
+ | **Crypto** | `crypto.sha256`, `crypto.hmacSha256`, `crypto.rsaSign`, `crypto.signJwt` |
464
+ | **Utilities** | `uuid`, `formatDate`, `chunk`, `merge`, `math`, `evaluate`, `renderTemplate`, `log`, `logError` |
465
+ | **Conversion** | `toCSV`, `toJSON` |
466
+
467
+ #### Secrets in Compute Functions
468
+
469
+ Compute functions have **no built-in environment variables or secrets field**. To pass secrets (API keys, credentials) to a compute function:
470
+
471
+ - **Recommended:** Wrap the function in an orchestration and use **encrypted params** on the compute step. Encrypted params are stored with AES-256-GCM at rest and decrypted at execution time — they arrive in `triggerParams`.
472
+ - **Alternative:** Pass secrets in the trigger invocation payload via `executionParams`. This works but means the calling app is the courier for the secret.
473
+
474
+ See [Orchestrations](#orchestrations) for encrypted params usage.
475
+
476
+ #### Invoking Triggers
477
+
478
+ Trigger invocation is **asynchronous** — it returns a job ID, not the execution result. Use the function runs API to poll for the result.
407
479
 
408
480
  ```typescript
409
- // Invoke an on-demand trigger to execute a compute function
481
+ // Invoke an on-demand trigger
410
482
  const job = await centrali.triggers.invoke('trigger-id', {
411
483
  payload: { data: 'your-input-data' }
412
484
  });
413
-
414
485
  console.log('Job queued:', job.data);
486
+
487
+ // Poll for the result using function runs
488
+ // (The job ID maps to a function run — query by trigger to find it)
489
+ const runs = await centrali.runs.listByTrigger('trigger-id', { limit: 1 });
490
+ const latestRun = runs.data.data[0];
491
+ console.log('Status:', latestRun.status); // pending | running | completed | failure | timeout
492
+ console.log('Result:', latestRun.runData); // execution output (once completed)
493
+ console.log('Error:', latestRun.errorMessage); // error details (if failed)
494
+ ```
495
+
496
+ #### Function Runs (Execution History)
497
+
498
+ Query execution history for debugging and observability:
499
+
500
+ ```typescript
501
+ // Get a specific run by ID
502
+ const run = await centrali.runs.get('run-uuid');
503
+ console.log('Status:', run.data.status);
504
+ console.log('Output:', run.data.runData);
505
+ console.log('Duration:', run.data.startedAt, '→', run.data.endedAt);
506
+
507
+ // List runs for a trigger (most recent first)
508
+ const triggerRuns = await centrali.runs.listByTrigger('trigger-uuid', {
509
+ status: 'failure', // Filter by status
510
+ limit: 10
511
+ });
512
+
513
+ // List runs for a function
514
+ const functionRuns = await centrali.runs.listByFunction('function-uuid');
415
515
  ```
416
516
 
517
+ Run statuses: `pending` → `running` → `completed` | `failure` | `timeout`
518
+
417
519
  ### File Uploads
418
520
 
419
521
  ```typescript
package/dist/index.js CHANGED
@@ -87,6 +87,7 @@ exports.getComputeFunctionTestApiPath = getComputeFunctionTestApiPath;
87
87
  exports.getFunctionRunsApiPath = getFunctionRunsApiPath;
88
88
  exports.getFunctionRunsByTriggerApiPath = getFunctionRunsByTriggerApiPath;
89
89
  exports.getFunctionRunsByFunctionApiPath = getFunctionRunsByFunctionApiPath;
90
+ exports.getComputeJobStatusApiPath = getComputeJobStatusApiPath;
90
91
  exports.getSmartQueryTestApiPath = getSmartQueryTestApiPath;
91
92
  exports.getValidationSuggestionsApiPath = getValidationSuggestionsApiPath;
92
93
  exports.getValidationSuggestionAcceptApiPath = getValidationSuggestionAcceptApiPath;
@@ -681,6 +682,15 @@ function getFunctionRunsByFunctionApiPath(workspaceId, functionId) {
681
682
  return `data/workspace/${workspaceId}/api/v1/function-runs/function/${functionId}`;
682
683
  }
683
684
  // =====================================================
685
+ // Compute Job Status API Path Helper
686
+ // =====================================================
687
+ /**
688
+ * Generate Compute Job Status API URL PATH.
689
+ */
690
+ function getComputeJobStatusApiPath(workspaceId, jobId) {
691
+ return `data/workspace/${workspaceId}/api/v1/jobs/compute/${jobId}`;
692
+ }
693
+ // =====================================================
684
694
  // Smart Query Test API Path Helper (Configuration-as-Code)
685
695
  // =====================================================
686
696
  /**
@@ -2407,12 +2417,12 @@ exports.CollectionsManager = CollectionsManager;
2407
2417
  * // Create a new function
2408
2418
  * const fn = await client.functions.create({
2409
2419
  * name: 'Process Order',
2410
- * code: 'module.exports = async (ctx) => { return { processed: true }; }'
2420
+ * code: 'async function run() { return { processed: true }; }'
2411
2421
  * });
2412
2422
  *
2413
2423
  * // Test execute code without saving
2414
2424
  * const result = await client.functions.testExecute({
2415
- * code: 'module.exports = async (ctx) => { return ctx.executionParams; }',
2425
+ * code: 'async function run() { return executionParams; }',
2416
2426
  * params: { orderId: '123' }
2417
2427
  * });
2418
2428
  * ```
@@ -2464,7 +2474,7 @@ class ComputeFunctionsManager {
2464
2474
  * ```ts
2465
2475
  * const fn = await client.functions.create({
2466
2476
  * name: 'Process Order',
2467
- * code: 'module.exports = async (ctx) => { return { processed: true }; }',
2477
+ * code: 'async function run() { return { processed: true }; }',
2468
2478
  * description: 'Processes incoming orders',
2469
2479
  * timeoutMs: 60000
2470
2480
  * });
@@ -2484,7 +2494,7 @@ class ComputeFunctionsManager {
2484
2494
  * @example
2485
2495
  * ```ts
2486
2496
  * const updated = await client.functions.update('function-uuid', {
2487
- * code: 'module.exports = async (ctx) => { return { v2: true }; }',
2497
+ * code: 'async function run() { return { v2: true }; }',
2488
2498
  * timeoutMs: 120000
2489
2499
  * });
2490
2500
  * ```
@@ -2517,7 +2527,7 @@ class ComputeFunctionsManager {
2517
2527
  * @example
2518
2528
  * ```ts
2519
2529
  * const result = await client.functions.testExecute({
2520
- * code: 'module.exports = async (ctx) => { return { sum: ctx.executionParams.a + ctx.executionParams.b }; }',
2530
+ * code: 'async function run() { return { sum: executionParams.a + executionParams.b }; }',
2521
2531
  * params: { a: 1, b: 2 }
2522
2532
  * });
2523
2533
  * console.log('Output:', result.data.output); // { sum: 3 }
@@ -2619,6 +2629,38 @@ class FunctionRunsManager {
2619
2629
  queryParams.status = options.status;
2620
2630
  return this.requestFn('GET', path, null, queryParams);
2621
2631
  }
2632
+ /**
2633
+ * Get the status of a compute job by job ID.
2634
+ *
2635
+ * This is the primary way to poll for the result of an async trigger
2636
+ * invocation. The job ID is returned by `client.triggers.invoke()`.
2637
+ *
2638
+ * @param jobId - The job ID returned by invoke
2639
+ * @returns Job status including returnValue (on success) or failedReason (on failure)
2640
+ *
2641
+ * @example
2642
+ * ```ts
2643
+ * // Invoke a trigger and poll for the result
2644
+ * const { data: jobId } = await client.triggers.invoke('trigger-uuid');
2645
+ *
2646
+ * // Poll until complete
2647
+ * let job;
2648
+ * do {
2649
+ * await new Promise(r => setTimeout(r, 1000));
2650
+ * job = await client.runs.getJobStatus(jobId);
2651
+ * } while (job.data.status === 'queued' || job.data.status === 'running');
2652
+ *
2653
+ * if (job.data.status === 'completed') {
2654
+ * console.log('Result:', job.data.returnValue);
2655
+ * } else {
2656
+ * console.error('Failed:', job.data.failedReason);
2657
+ * }
2658
+ * ```
2659
+ */
2660
+ getJobStatus(jobId) {
2661
+ const path = getComputeJobStatusApiPath(this.workspaceId, jobId);
2662
+ return this.requestFn('GET', path);
2663
+ }
2622
2664
  }
2623
2665
  exports.FunctionRunsManager = FunctionRunsManager;
2624
2666
  /**
@@ -3014,12 +3056,12 @@ class CentraliSDK {
3014
3056
  * // Create a function
3015
3057
  * const fn = await client.functions.create({
3016
3058
  * name: 'Process Order',
3017
- * code: 'module.exports = async (ctx) => { return { ok: true }; }'
3059
+ * code: 'async function run() { return { ok: true }; }'
3018
3060
  * });
3019
3061
  *
3020
3062
  * // Test execute without saving
3021
3063
  * const result = await client.functions.testExecute({
3022
- * code: 'module.exports = async (ctx) => { return ctx.executionParams; }',
3064
+ * code: 'async function run() { return executionParams; }',
3023
3065
  * params: { test: true }
3024
3066
  * });
3025
3067
  * ```
package/index.ts CHANGED
@@ -1840,6 +1840,22 @@ export interface ListFunctionRunsOptions {
1840
1840
  status?: FunctionRunStatus;
1841
1841
  }
1842
1842
 
1843
+ /**
1844
+ * Status of a compute job in the execution pipeline.
1845
+ */
1846
+ export type ComputeJobStatus = 'queued' | 'running' | 'completed' | 'failed';
1847
+
1848
+ /**
1849
+ * A compute job status response from the job status endpoint.
1850
+ * Represents the state of an async compute execution.
1851
+ */
1852
+ export interface ComputeJobStatusResponse {
1853
+ jobId: string;
1854
+ status: ComputeJobStatus;
1855
+ returnValue?: any;
1856
+ failedReason?: string | null;
1857
+ }
1858
+
1843
1859
  // =====================================================
1844
1860
  // Trigger CRUD Types (Configuration-as-Code)
1845
1861
  // =====================================================
@@ -2820,6 +2836,17 @@ export function getFunctionRunsByFunctionApiPath(workspaceId: string, functionId
2820
2836
  return `data/workspace/${workspaceId}/api/v1/function-runs/function/${functionId}`;
2821
2837
  }
2822
2838
 
2839
+ // =====================================================
2840
+ // Compute Job Status API Path Helper
2841
+ // =====================================================
2842
+
2843
+ /**
2844
+ * Generate Compute Job Status API URL PATH.
2845
+ */
2846
+ export function getComputeJobStatusApiPath(workspaceId: string, jobId: string): string {
2847
+ return `data/workspace/${workspaceId}/api/v1/jobs/compute/${jobId}`;
2848
+ }
2849
+
2823
2850
  // =====================================================
2824
2851
  // Smart Query Test API Path Helper (Configuration-as-Code)
2825
2852
  // =====================================================
@@ -4712,12 +4739,12 @@ export class CollectionsManager {
4712
4739
  * // Create a new function
4713
4740
  * const fn = await client.functions.create({
4714
4741
  * name: 'Process Order',
4715
- * code: 'module.exports = async (ctx) => { return { processed: true }; }'
4742
+ * code: 'async function run() { return { processed: true }; }'
4716
4743
  * });
4717
4744
  *
4718
4745
  * // Test execute code without saving
4719
4746
  * const result = await client.functions.testExecute({
4720
- * code: 'module.exports = async (ctx) => { return ctx.executionParams; }',
4747
+ * code: 'async function run() { return executionParams; }',
4721
4748
  * params: { orderId: '123' }
4722
4749
  * });
4723
4750
  * ```
@@ -4778,7 +4805,7 @@ export class ComputeFunctionsManager {
4778
4805
  * ```ts
4779
4806
  * const fn = await client.functions.create({
4780
4807
  * name: 'Process Order',
4781
- * code: 'module.exports = async (ctx) => { return { processed: true }; }',
4808
+ * code: 'async function run() { return { processed: true }; }',
4782
4809
  * description: 'Processes incoming orders',
4783
4810
  * timeoutMs: 60000
4784
4811
  * });
@@ -4799,7 +4826,7 @@ export class ComputeFunctionsManager {
4799
4826
  * @example
4800
4827
  * ```ts
4801
4828
  * const updated = await client.functions.update('function-uuid', {
4802
- * code: 'module.exports = async (ctx) => { return { v2: true }; }',
4829
+ * code: 'async function run() { return { v2: true }; }',
4803
4830
  * timeoutMs: 120000
4804
4831
  * });
4805
4832
  * ```
@@ -4834,7 +4861,7 @@ export class ComputeFunctionsManager {
4834
4861
  * @example
4835
4862
  * ```ts
4836
4863
  * const result = await client.functions.testExecute({
4837
- * code: 'module.exports = async (ctx) => { return { sum: ctx.executionParams.a + ctx.executionParams.b }; }',
4864
+ * code: 'async function run() { return { sum: executionParams.a + executionParams.b }; }',
4838
4865
  * params: { a: 1, b: 2 }
4839
4866
  * });
4840
4867
  * console.log('Output:', result.data.output); // { sum: 3 }
@@ -4939,6 +4966,39 @@ export class FunctionRunsManager {
4939
4966
  if (options?.status) queryParams.status = options.status;
4940
4967
  return this.requestFn<PaginatedResponse<FunctionRun>>('GET', path, null, queryParams);
4941
4968
  }
4969
+
4970
+ /**
4971
+ * Get the status of a compute job by job ID.
4972
+ *
4973
+ * This is the primary way to poll for the result of an async trigger
4974
+ * invocation. The job ID is returned by `client.triggers.invoke()`.
4975
+ *
4976
+ * @param jobId - The job ID returned by invoke
4977
+ * @returns Job status including returnValue (on success) or failedReason (on failure)
4978
+ *
4979
+ * @example
4980
+ * ```ts
4981
+ * // Invoke a trigger and poll for the result
4982
+ * const { data: jobId } = await client.triggers.invoke('trigger-uuid');
4983
+ *
4984
+ * // Poll until complete
4985
+ * let job;
4986
+ * do {
4987
+ * await new Promise(r => setTimeout(r, 1000));
4988
+ * job = await client.runs.getJobStatus(jobId);
4989
+ * } while (job.data.status === 'queued' || job.data.status === 'running');
4990
+ *
4991
+ * if (job.data.status === 'completed') {
4992
+ * console.log('Result:', job.data.returnValue);
4993
+ * } else {
4994
+ * console.error('Failed:', job.data.failedReason);
4995
+ * }
4996
+ * ```
4997
+ */
4998
+ public getJobStatus(jobId: string): Promise<ApiResponse<ComputeJobStatusResponse>> {
4999
+ const path = getComputeJobStatusApiPath(this.workspaceId, jobId);
5000
+ return this.requestFn<ComputeJobStatusResponse>('GET', path);
5001
+ }
4942
5002
  }
4943
5003
 
4944
5004
  /**
@@ -5409,12 +5469,12 @@ export class CentraliSDK {
5409
5469
  * // Create a function
5410
5470
  * const fn = await client.functions.create({
5411
5471
  * name: 'Process Order',
5412
- * code: 'module.exports = async (ctx) => { return { ok: true }; }'
5472
+ * code: 'async function run() { return { ok: true }; }'
5413
5473
  * });
5414
5474
  *
5415
5475
  * // Test execute without saving
5416
5476
  * const result = await client.functions.testExecute({
5417
- * code: 'module.exports = async (ctx) => { return ctx.executionParams; }',
5477
+ * code: 'async function run() { return executionParams; }',
5418
5478
  * params: { test: true }
5419
5479
  * });
5420
5480
  * ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@centrali-io/centrali-sdk",
3
- "version": "4.4.4",
3
+ "version": "4.4.6",
4
4
  "description": "Centrali Node SDK",
5
5
  "main": "dist/index.js",
6
6
  "type": "commonjs",