@supacloud/js 0.15.1 → 0.16.1

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
@@ -8,6 +8,7 @@ It does **not** replace [`@supabase/supabase-js`](https://www.npmjs.com/package/
8
8
  - task detail and list APIs
9
9
  - cancel / retry helpers
10
10
  - Realtime subscription with polling fallback
11
+ - queue send / receive / ack / release / fail / retry / delete / list / listFailed / stats / settings helpers
11
12
  - project OAuth/OIDC migration and OAuth client management
12
13
 
13
14
  ## Install
@@ -33,6 +34,12 @@ const supacloud = createSupaCloudClient({
33
34
  const task = await supacloud.tasks.submit("aorist-ai/generate/crop", {
34
35
  body: { image_id: "img_123" },
35
36
  idempotencyKey: "crop-img_123-v1",
37
+ correlationId: "workflow-run-123",
38
+ businessTaskId: "aorist-task-123",
39
+ metadata: {
40
+ workflow_id: "workflow-123",
41
+ billing_subject: "user-123",
42
+ },
36
43
  });
37
44
 
38
45
  const finalState = await task.wait();
@@ -49,6 +56,8 @@ This SDK is intentionally thin:
49
56
  `tasks.submit()` expects the target function path to be configured in `background_routes`.
50
57
  That keeps frontend calls compatible with strict CORS deployments while preserving the same task receipt API.
51
58
 
59
+ Use `correlationId`, `businessTaskId`, and `metadata` when the application already has its own task, workflow, or billing records. SupaCloud stores these fields but does not interpret them; lifecycle webhooks echo them back so the application can update its own tables.
60
+
52
61
  The current package focuses on:
53
62
 
54
63
  - `tasks.submit`
@@ -59,6 +68,18 @@ The current package focuses on:
59
68
  - `tasks.retry`
60
69
  - `tasks.wait`
61
70
  - `tasks.subscribe`
71
+ - `queue(name).send`
72
+ - `queue(name).receive`
73
+ - `queue(name).ack`
74
+ - `queue(name).release`
75
+ - `queue(name).fail`
76
+ - `queue(name).retry`
77
+ - `queue(name).delete`
78
+ - `queue(name).list`
79
+ - `queue(name).listFailed`
80
+ - `queue(name).stats`
81
+ - `queue(name).getSettings`
82
+ - `queue(name).updateSettings`
62
83
  - `auth.oauthServer.getStatus`
63
84
  - `auth.oauthServer.migrateToOidc`
64
85
  - `auth.oauthServer.getDiscovery`
@@ -75,6 +96,97 @@ The current package focuses on:
75
96
 
76
97
  This lets apps degrade gracefully when websocket or channel health is transient.
77
98
 
99
+ ## Task Lifecycle Webhook
100
+
101
+ Applications that already own a business task table should keep it. SupaCloud emits lifecycle events so the app can sync `public.tasks`, billing, Realtime, and workflow rows without adopting platform-internal mirror tables.
102
+
103
+ Register a webhook from a trusted backend:
104
+
105
+ ```http
106
+ POST /v1/projects/:ref/task-events/webhook
107
+ Authorization: Bearer <management-token>
108
+ Content-Type: application/json
109
+
110
+ {
111
+ "url": "https://app.example.com/supacloud/task-events",
112
+ "secret": "shared-hmac-secret"
113
+ }
114
+ ```
115
+
116
+ Events are delivered as `{ events: [...] }`. Each event includes `event_type`, `task_id`, `status`, `attempt`, `correlation_id`, `business_task_id`, and `metadata`.
117
+
118
+ Supported lifecycle events:
119
+
120
+ - `task.created`
121
+ - `task.running`
122
+ - `task.succeeded`
123
+ - `task.failed`
124
+ - `task.retry_scheduled`
125
+ - `task.dead_lettered`
126
+ - `task.cancelled`
127
+
128
+ If `secret` is set, verify `X-SupaCloud-Signature: sha256=<hmac>` against the raw JSON body.
129
+
130
+ ## Queue Helpers
131
+
132
+ ```ts
133
+ const queue = supacloud.queue("emails");
134
+
135
+ const message = await queue.send(
136
+ { to: "user@example.com", template: "welcome" },
137
+ {
138
+ idempotencyKey: "welcome-user-123",
139
+ delayMs: 10_000,
140
+ maxAttempts: 5,
141
+ traceId: "trace-123",
142
+ correlationId: "signup-123",
143
+ businessTaskId: "email-job-123",
144
+ metadata: {
145
+ source: "signup",
146
+ billing_subject: "user-123",
147
+ },
148
+ },
149
+ );
150
+
151
+ const leased = await queue.receive({ visibilityTimeoutSec: 60 });
152
+ if (leased) {
153
+ try {
154
+ await sendEmail(leased.payload);
155
+ await queue.ack(leased.id, { delivered: true });
156
+ } catch (error) {
157
+ await queue.release(leased.id, { delayMs: 30_000, error: String(error) });
158
+ }
159
+ }
160
+
161
+ const stats = await queue.stats();
162
+ console.log(stats.inFlight, stats.deadLettered);
163
+ ```
164
+
165
+ Queue API surface:
166
+
167
+ - `queue.send(payload, options)`: enqueue a message, optionally delayed and idempotent
168
+ - `queue.receive({ visibilityTimeoutSec })`: lease the next message, or return `null`
169
+ - `queue.ack(messageId, result)`: mark the leased message succeeded
170
+ - `queue.release(messageId, { delayMs, error })`: return the message to the queue later
171
+ - `queue.fail(messageId, { error, deadLetter })`: mark failed or dead-lettered
172
+ - `queue.retry(messageId)`: replay a dead-lettered message
173
+ - `queue.delete(messageId)`: cancel/delete a message
174
+ - `queue.list(filters)`: list messages by status, DLQ flag, and limit
175
+ - `queue.listFailed(limit)`: shortcut for DLQ messages
176
+ - `queue.get(messageId)`: read message detail, attempts, and latest logs
177
+ - `queue.stats()`: inspect queue depth and recent success/failure counts
178
+ - `queue.getSettings()`: read concurrency, lease, retry, and rate-limit settings
179
+ - `queue.updateSettings(settings)`: patch queue settings
180
+
181
+ Queue settings:
182
+
183
+ - `max_in_flight`: max concurrently leased/running messages for this queue
184
+ - `default_visibility_timeout_sec`: lease timeout used by `receive()`
185
+ - `max_attempts`: default retry budget for new messages
186
+ - `rate_limit_per_minute`: producer enqueue limit
187
+
188
+ Queue conflicts such as replaying a non-DLQ message are surfaced as `SupaCloudApiError` with `status`, `code`, and `responseBody`, so callers do not need to parse raw `fetch` responses.
189
+
78
190
  ## OAuth/OIDC Helpers
79
191
 
80
192
  `client.auth.oauthServer` is the SupaCloud SDK surface for project-scoped OAuth 2.1 / OIDC migration and discovery.
package/dist/index.d.ts CHANGED
@@ -30,6 +30,9 @@ export type SupaCloudTaskDetail = {
30
30
  payload?: Record<string, unknown>;
31
31
  attempts?: SupaCloudTaskAttempt[];
32
32
  latest_logs?: SupaCloudTaskLogEntry[];
33
+ correlation_id?: string | null;
34
+ business_task_id?: string | null;
35
+ metadata?: Record<string, unknown> | null;
33
36
  updated_at?: string | null;
34
37
  created_at?: string | null;
35
38
  [key: string]: unknown;
@@ -56,12 +59,21 @@ export type SupaCloudTaskSubmitOptions = {
56
59
  timeoutSec?: number;
57
60
  idempotencyKey?: string;
58
61
  method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
62
+ /** Opaque correlation ID — the platform stores it but does not interpret it */
63
+ correlationId?: string;
64
+ /** Business-layer task ID for mapping back to the caller's own task table */
65
+ businessTaskId?: string;
66
+ /** Arbitrary JSON metadata — the platform stores it but does not interpret it */
67
+ metadata?: Record<string, unknown>;
59
68
  };
60
69
  export type SupaCloudQueueSendOptions = {
61
70
  delayMs?: number;
62
71
  maxAttempts?: number;
63
72
  idempotencyKey?: string;
64
73
  traceId?: string;
74
+ correlationId?: string;
75
+ businessTaskId?: string;
76
+ metadata?: Record<string, unknown>;
65
77
  };
66
78
  export type SupaCloudQueueReceiveOptions = {
67
79
  visibilityTimeoutSec?: number;
@@ -82,6 +94,24 @@ export type SupaCloudQueueListFilters = {
82
94
  export type SupaCloudQueueMessage = SupaCloudTaskDetail & {
83
95
  payload: Record<string, unknown>;
84
96
  };
97
+ export type SupaCloudQueueStats = {
98
+ pending: number;
99
+ leased: number;
100
+ running: number;
101
+ retryScheduled: number;
102
+ succeededLast24h: number;
103
+ failedLast24h: number;
104
+ deadLettered: number;
105
+ oldestPendingAgeSec: number | null;
106
+ inFlight: number;
107
+ };
108
+ export type SupaCloudQueueSettings = {
109
+ max_in_flight: number;
110
+ default_visibility_timeout_sec: number;
111
+ max_attempts: number;
112
+ rate_limit_per_minute: number;
113
+ };
114
+ export type SupaCloudQueueSettingsUpdate = Partial<SupaCloudQueueSettings>;
85
115
  export type SupaCloudTaskWaitOptions = {
86
116
  intervalMs?: number;
87
117
  signal?: AbortSignal;
@@ -183,7 +213,13 @@ export declare class SupaCloudTaskSubmitError extends Error {
183
213
  readonly responseBody: unknown;
184
214
  constructor(message: string, responseBody: unknown);
185
215
  }
186
- type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
216
+ export declare class SupaCloudApiError extends Error {
217
+ readonly status: number;
218
+ readonly code: string | null;
219
+ readonly responseBody: unknown;
220
+ constructor(message: string, status: number, responseBody: unknown);
221
+ }
222
+ type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
187
223
  declare class SupaCloudManagementClient<TClient extends SupabaseClient = SupabaseClient> {
188
224
  protected readonly options: Required<SupaCloudClientOptions<TClient>>;
189
225
  constructor(options: Required<SupaCloudClientOptions<TClient>>);
@@ -212,11 +248,15 @@ declare class SupaCloudQueueClient<TClient extends SupabaseClient = SupabaseClie
212
248
  receive(options?: SupaCloudQueueReceiveOptions): Promise<SupaCloudQueueMessage | null>;
213
249
  list(filters?: SupaCloudQueueListFilters): Promise<SupaCloudQueueMessage[]>;
214
250
  listFailed(limit?: number): Promise<SupaCloudQueueMessage[]>;
251
+ stats(): Promise<SupaCloudQueueStats>;
252
+ getSettings(): Promise<SupaCloudQueueSettings>;
253
+ updateSettings(settings: SupaCloudQueueSettingsUpdate): Promise<SupaCloudQueueSettings>;
215
254
  get(messageId: string): Promise<SupaCloudQueueMessage>;
216
255
  ack(messageId: string, result?: Record<string, unknown>): Promise<SupaCloudQueueMessage>;
217
256
  delete(messageId: string): Promise<void>;
218
257
  release(messageId: string, options?: SupaCloudQueueReleaseOptions): Promise<SupaCloudQueueMessage>;
219
258
  fail(messageId: string, options?: SupaCloudQueueFailOptions): Promise<SupaCloudQueueMessage>;
259
+ retry(messageId: string): Promise<SupaCloudQueueMessage>;
220
260
  }
221
261
  declare class SupaCloudOAuthServerClient<TClient extends SupabaseClient = SupabaseClient> extends SupaCloudManagementClient<TClient> {
222
262
  getStatus(): Promise<SupaCloudOAuthServerStatus>;
package/dist/index.js CHANGED
@@ -7,6 +7,19 @@ class SupaCloudTaskSubmitError extends Error {
7
7
  this.responseBody = responseBody;
8
8
  }
9
9
  }
10
+
11
+ class SupaCloudApiError extends Error {
12
+ status;
13
+ code;
14
+ responseBody;
15
+ constructor(message, status, responseBody) {
16
+ super(message);
17
+ this.name = "SupaCloudApiError";
18
+ this.status = status;
19
+ this.responseBody = responseBody;
20
+ this.code = extractErrorCode(responseBody);
21
+ }
22
+ }
10
23
  var TERMINAL_STATUSES = new Set([
11
24
  "succeeded",
12
25
  "failed",
@@ -51,6 +64,22 @@ function createQueueQueryString(filters = {}) {
51
64
  const query = params.toString();
52
65
  return query.length > 0 ? `?${query}` : "";
53
66
  }
67
+ function extractErrorCode(body) {
68
+ if (!body || typeof body !== "object")
69
+ return null;
70
+ const code = body.code;
71
+ return typeof code === "string" ? code : null;
72
+ }
73
+ async function readResponseBody(response) {
74
+ const text = await response.text();
75
+ if (!text)
76
+ return;
77
+ try {
78
+ return JSON.parse(text);
79
+ } catch {
80
+ return text;
81
+ }
82
+ }
54
83
  async function defaultAccessTokenResolver(supabase) {
55
84
  const { data, error } = await supabase.auth.getSession();
56
85
  if (error)
@@ -91,12 +120,14 @@ class SupaCloudManagementClient {
91
120
  },
92
121
  ...body !== undefined ? { body: JSON.stringify(body) } : {}
93
122
  });
94
- if (!response.ok) {
95
- throw new Error(`SupaCloud request failed (${response.status})`);
96
- }
97
123
  if (response.status === 204)
98
124
  return;
99
- return await response.json();
125
+ const responseBody = await readResponseBody(response);
126
+ if (!response.ok) {
127
+ const message = responseBody && typeof responseBody === "object" && typeof responseBody.message === "string" ? String(responseBody.message) : `SupaCloud request failed (${response.status})`;
128
+ throw new SupaCloudApiError(message, response.status, responseBody);
129
+ }
130
+ return responseBody;
100
131
  }
101
132
  }
102
133
 
@@ -116,7 +147,10 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
116
147
  const { body, headers = {}, retries: _retries, timeoutSec: _timeoutSec, idempotencyKey, method } = options;
117
148
  const invokeHeaders = {
118
149
  ...headers,
119
- ...idempotencyKey ? { "x-supacloud-idempotency-key": idempotencyKey } : {}
150
+ ...idempotencyKey ? { "x-supacloud-idempotency-key": idempotencyKey } : {},
151
+ ...options.correlationId ? { "x-supacloud-correlation-id": options.correlationId } : {},
152
+ ...options.businessTaskId ? { "x-supacloud-business-task-id": options.businessTaskId } : {},
153
+ ...options.metadata ? { "x-supacloud-task-metadata": JSON.stringify(options.metadata) } : {}
120
154
  };
121
155
  const { data, error } = await this.options.supabase.functions.invoke(functionName, {
122
156
  body,
@@ -341,7 +375,10 @@ class SupaCloudQueueClient extends SupaCloudManagementClient {
341
375
  delayMs: options.delayMs,
342
376
  maxAttempts: options.maxAttempts,
343
377
  idempotencyKey: options.idempotencyKey,
344
- traceId: options.traceId
378
+ traceId: options.traceId,
379
+ correlationId: options.correlationId,
380
+ businessTaskId: options.businessTaskId,
381
+ metadata: options.metadata
345
382
  });
346
383
  }
347
384
  async receive(options = {}) {
@@ -354,6 +391,15 @@ class SupaCloudQueueClient extends SupaCloudManagementClient {
354
391
  async listFailed(limit = 100) {
355
392
  return this.list({ dlq: true, limit });
356
393
  }
394
+ async stats() {
395
+ return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/stats`, "GET");
396
+ }
397
+ async getSettings() {
398
+ return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/settings`, "GET");
399
+ }
400
+ async updateSettings(settings) {
401
+ return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/settings`, "PATCH", settings);
402
+ }
357
403
  async get(messageId) {
358
404
  return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/${messageId}`, "GET");
359
405
  }
@@ -369,6 +415,9 @@ class SupaCloudQueueClient extends SupaCloudManagementClient {
369
415
  async fail(messageId, options = {}) {
370
416
  return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/${messageId}/fail`, "POST", options);
371
417
  }
418
+ async retry(messageId) {
419
+ return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/${messageId}/retry`, "POST");
420
+ }
372
421
  }
373
422
 
374
423
  class SupaCloudOAuthServerClient extends SupaCloudManagementClient {
@@ -462,5 +511,6 @@ function createSupaCloudClient(options) {
462
511
  }
463
512
  export {
464
513
  createSupaCloudClient,
465
- SupaCloudTaskSubmitError
514
+ SupaCloudTaskSubmitError,
515
+ SupaCloudApiError
466
516
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supacloud/js",
3
- "version": "0.15.1",
3
+ "version": "0.16.1",
4
4
  "description": "Platform SDK for SupaCloud, built on top of supabase-js",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",