@supacloud/js 0.16.1 → 0.18.0

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,8 +8,9 @@ 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
+ - Supabase Queues helpers backed by the official `pgmq_public` RPC API, plus SupaCloud management extensions for queue administration and diagnostics
12
12
  - project OAuth/OIDC migration and OAuth client management
13
+ - SupAuth provisioning and runtime verification helpers
13
14
 
14
15
  ## Install
15
16
 
@@ -46,6 +47,51 @@ const finalState = await task.wait();
46
47
  console.log(finalState.status);
47
48
  ```
48
49
 
50
+ ## SupAuth Management
51
+
52
+ `supacloud.supauth` is a management-plane helper for provisioning and verifying a SupAuth/SupaOAuth runtime on SupaCloud. It is intended for trusted server-side tools, CI jobs, or admin backends that can call the SupaCloud Management API.
53
+
54
+ ```ts
55
+ const supacloud = createSupaCloudClient({
56
+ supabase,
57
+ managementApiUrl: "https://admin.example.com",
58
+ projectRef: "abcd1234",
59
+ getAccessToken: () => process.env.SUPACLOUD_MANAGEMENT_TOKEN ?? null,
60
+ });
61
+
62
+ await supacloud.supauth.provision({
63
+ authDomain: "auth.example.com",
64
+ apiDomain: "api.example.com",
65
+ adminMode: "sso",
66
+ storageBuckets: [{ id: "avatars", public: true }],
67
+ });
68
+
69
+ await supacloud.supauth.reconcile({ dryRun: false });
70
+
71
+ const health = await supacloud.supauth.verify();
72
+ if (!health.healthy) {
73
+ throw new Error("SupAuth runtime is not healthy");
74
+ }
75
+
76
+ const config = await supacloud.supauth.getClientConfig();
77
+ console.log(config.authUrl);
78
+ ```
79
+
80
+ The helper maps to these SupaCloud Management API routes:
81
+
82
+ - `POST /v1/projects/:projectRef/supauth/provision`
83
+ - `POST /v1/projects/:projectRef/supauth/reconcile`
84
+ - `POST /v1/projects/:projectRef/supauth/rollback`
85
+ - `GET /v1/projects/:projectRef/supauth/client-config`
86
+ - `GET /v1/projects/:projectRef/supauth/verify`
87
+
88
+ Boundary:
89
+
90
+ - Use `@supacloud/js` for SupaCloud-owned infrastructure orchestration: GoTrue env injection, restart/reconcile, Kong route setup, runtime health checks, and public client config discovery.
91
+ - Use `@supabase/supabase-js` for normal application runtime calls: auth session, database, storage, realtime, and edge functions.
92
+ - Use the SupaOAuth product SDK or Management API for SupaOAuth-owned resources: applications, connectors, organizations, roles, permissions, audit logs, and webhooks.
93
+ - Do not expose SupaCloud Management API credentials in browser code.
94
+
49
95
  ## Design
50
96
 
51
97
  This SDK is intentionally thin:
@@ -68,16 +114,22 @@ The current package focuses on:
68
114
  - `tasks.retry`
69
115
  - `tasks.wait`
70
116
  - `tasks.subscribe`
117
+ - `queues.list`
118
+ - `queues.create`
119
+ - `queues.drop`
71
120
  - `queue(name).send`
121
+ - `queue(name).sendBatch`
122
+ - `queue(name).read`
72
123
  - `queue(name).receive`
124
+ - `queue(name).pop`
125
+ - `queue(name).archive`
73
126
  - `queue(name).ack`
74
- - `queue(name).release`
75
- - `queue(name).fail`
76
- - `queue(name).retry`
77
127
  - `queue(name).delete`
128
+ - `queue(name).release`
78
129
  - `queue(name).list`
79
- - `queue(name).listFailed`
130
+ - `queue(name).listArchived`
80
131
  - `queue(name).stats`
132
+ - `queue(name).purge`
81
133
  - `queue(name).getSettings`
82
134
  - `queue(name).updateSettings`
83
135
  - `auth.oauthServer.getStatus`
@@ -86,6 +138,11 @@ The current package focuses on:
86
138
  - `auth.oauthServer.getJwks`
87
139
  - `auth.oauthServer.buildAuthorizeUrl`
88
140
  - `auth.oauthClients.list/create/get/update/delete/regenerateSecret`
141
+ - `supauth.provision`
142
+ - `supauth.reconcile`
143
+ - `supauth.rollback`
144
+ - `supauth.getClientConfig`
145
+ - `supauth.verify`
89
146
 
90
147
  ## Status Subscription
91
148
 
@@ -129,22 +186,24 @@ If `secret` is set, verify `X-SupaCloud-Signature: sha256=<hmac>` against the ra
129
186
 
130
187
  ## Queue Helpers
131
188
 
189
+ The core message operations use the official Supabase Queues API exposed through `pgmq_public`:
190
+
191
+ - `pgmq_public.send(queue_name, message, sleep_seconds)`
192
+ - `pgmq_public.send_batch(queue_name, messages, sleep_seconds)`
193
+ - `pgmq_public.read(queue_name, sleep_seconds, n)`
194
+ - `pgmq_public.pop(queue_name)`
195
+ - `pgmq_public.archive(queue_name, message_id)`
196
+ - `pgmq_public.delete(queue_name, message_id)`
197
+
198
+ These calls go through your wrapped `supabase` client as `supabase.schema('pgmq_public').rpc(...)`. Queue creation/drop, queue listing, metrics, purge, settings, diagnostics, and visibility-timeout adjustment are SupaCloud management extensions because Supabase's public Queue API intentionally does not expose those as client-side RPCs.
199
+
132
200
  ```ts
133
201
  const queue = supacloud.queue("emails");
134
202
 
135
203
  const message = await queue.send(
136
204
  { to: "user@example.com", template: "welcome" },
137
205
  {
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
- },
206
+ sleepSeconds: 10,
148
207
  },
149
208
  );
150
209
 
@@ -152,40 +211,44 @@ const leased = await queue.receive({ visibilityTimeoutSec: 60 });
152
211
  if (leased) {
153
212
  try {
154
213
  await sendEmail(leased.payload);
155
- await queue.ack(leased.id, { delivered: true });
214
+ await queue.ack(leased.msg_id);
156
215
  } catch (error) {
157
- await queue.release(leased.id, { delayMs: 30_000, error: String(error) });
216
+ await queue.release(leased.msg_id, { delayMs: 30_000, error: String(error) });
158
217
  }
159
218
  }
160
219
 
161
220
  const stats = await queue.stats();
162
- console.log(stats.inFlight, stats.deadLettered);
221
+ console.log(stats.queue_length, stats.oldest_msg_age_sec);
163
222
  ```
164
223
 
165
224
  Queue API surface:
166
225
 
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
226
+ - `queue.send(payload, { sleepSeconds })`: enqueue one message through `pgmq_public.send`
227
+ - `queue.sendBatch(messages, { sleepSeconds })`: enqueue messages through `pgmq_public.send_batch`
228
+ - `queue.read({ sleepSeconds, n })`: read up to `n` messages through `pgmq_public.read`
229
+ - `queue.receive({ visibilityTimeoutSec })`: compatibility shortcut for `read({ n: 1 })`
230
+ - `queue.pop()`: read and delete the next message through `pgmq_public.pop`
231
+ - `queue.archive(messageId)` / `queue.ack(messageId)`: archive a message through `pgmq_public.archive`
232
+ - `queue.delete(messageId)`: delete a message through `pgmq_public.delete`
233
+ - `queue.release(messageId, { sleepSeconds | delayMs })`: SupaCloud extension for `pgmq.set_vt`
234
+ - `queue.list(filters)`: SupaCloud diagnostic extension for queue/archive table inspection
235
+ - `queue.listArchived(limit)`: SupaCloud diagnostic shortcut for archived messages
236
+ - `queue.stats()`: SupaCloud extension for `pgmq.metrics`
237
+ - `queue.purge()`: SupaCloud extension for `pgmq.purge_queue`
178
238
  - `queue.getSettings()`: read concurrency, lease, retry, and rate-limit settings
179
239
  - `queue.updateSettings(settings)`: patch queue settings
240
+ - `supacloud.queues.list()`: list queues with `pgmq.list_queues`
241
+ - `supacloud.queues.create(name, { unlogged })`: create a basic or unlogged queue
242
+ - `supacloud.queues.drop(name)`: drop a queue
180
243
 
181
244
  Queue settings:
182
245
 
183
246
  - `max_in_flight`: max concurrently leased/running messages for this queue
184
247
  - `default_visibility_timeout_sec`: lease timeout used by `receive()`
185
- - `max_attempts`: default retry budget for new messages
248
+ - `max_attempts`: application-level retry budget for SupaCloud consumers; PGMQ itself stores plain JSON messages
186
249
  - `rate_limit_per_minute`: producer enqueue limit
187
250
 
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.
251
+ Management extension conflicts are surfaced as `SupaCloudApiError` with `status`, `code`, and `responseBody`, so callers do not need to parse raw `fetch` responses.
189
252
 
190
253
  ## OAuth/OIDC Helpers
191
254
 
package/dist/index.d.ts CHANGED
@@ -67,18 +67,40 @@ export type SupaCloudTaskSubmitOptions = {
67
67
  metadata?: Record<string, unknown>;
68
68
  };
69
69
  export type SupaCloudQueueSendOptions = {
70
+ /** Official Supabase Queues visibility delay, in seconds. */
71
+ sleepSeconds?: number;
72
+ /** Official Supabase Queues visibility delay, in seconds. */
73
+ sleep_seconds?: number;
74
+ /** Convenience alias converted to sleep_seconds for compatibility with older SupaCloud callers. */
70
75
  delayMs?: number;
76
+ /** @deprecated PGMQ does not store per-message retry budgets. Keep retry policy at the consumer layer. */
71
77
  maxAttempts?: number;
78
+ /** @deprecated PGMQ does not provide enqueue idempotency keys. Deduplicate in your payload or application table. */
72
79
  idempotencyKey?: string;
80
+ /** @deprecated PGMQ messages are plain JSON payloads. Put trace data inside message if needed. */
73
81
  traceId?: string;
82
+ /** @deprecated PGMQ messages are plain JSON payloads. Put correlation data inside message if needed. */
74
83
  correlationId?: string;
84
+ /** @deprecated PGMQ messages are plain JSON payloads. Put business IDs inside message if needed. */
75
85
  businessTaskId?: string;
86
+ /** @deprecated PGMQ messages are plain JSON payloads. Put metadata inside message if needed. */
76
87
  metadata?: Record<string, unknown>;
77
88
  };
78
89
  export type SupaCloudQueueReceiveOptions = {
90
+ /** Official Supabase Queues visibility timeout, in seconds. */
91
+ sleepSeconds?: number;
92
+ /** Official Supabase Queues visibility timeout, in seconds. */
93
+ sleep_seconds?: number;
94
+ /** Number of messages to read when using read(). receive() always reads one. */
95
+ n?: number;
96
+ /** Alias for n. */
97
+ count?: number;
98
+ /** Convenience alias converted to sleep_seconds for older SupaCloud callers. */
79
99
  visibilityTimeoutSec?: number;
80
100
  };
81
101
  export type SupaCloudQueueReleaseOptions = {
102
+ sleepSeconds?: number;
103
+ sleep_seconds?: number;
82
104
  delayMs?: number;
83
105
  error?: string;
84
106
  };
@@ -88,22 +110,55 @@ export type SupaCloudQueueFailOptions = {
88
110
  };
89
111
  export type SupaCloudQueueListFilters = {
90
112
  status?: string | string[];
113
+ archived?: boolean;
91
114
  dlq?: boolean;
92
115
  limit?: number;
93
116
  };
94
- export type SupaCloudQueueMessage = SupaCloudTaskDetail & {
117
+ export type SupaCloudQueueMessage = {
118
+ id: string;
119
+ msg_id: number;
120
+ read_ct?: number;
121
+ enqueued_at?: string | null;
122
+ vt?: string | null;
123
+ message?: Record<string, unknown>;
124
+ payload: Record<string, unknown>;
125
+ status?: string;
126
+ queue_name?: string;
127
+ task_type?: string;
128
+ [key: string]: unknown;
129
+ };
130
+ export type SupaCloudQueueSendResult = {
131
+ id: string;
132
+ msg_id: number;
133
+ queue_name: string;
134
+ status: "pending";
95
135
  payload: Record<string, unknown>;
96
136
  };
137
+ export type SupaCloudQueueMutationResult = {
138
+ id: string;
139
+ msg_id: number;
140
+ queue_name: string;
141
+ status: "archived" | "deleted" | "released";
142
+ success: boolean;
143
+ };
97
144
  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;
145
+ queue_name: string;
146
+ queue_length: number;
147
+ newest_msg_age_sec: number | null;
148
+ oldest_msg_age_sec: number | null;
149
+ total_messages: number;
150
+ scrape_time: string;
151
+ [key: string]: unknown;
152
+ };
153
+ export type SupaCloudQueueInfo = {
154
+ queue_name: string;
155
+ created_at?: string | null;
156
+ is_partitioned?: boolean;
157
+ is_unlogged?: boolean;
158
+ type?: string;
159
+ };
160
+ export type SupaCloudQueueCreateOptions = {
161
+ unlogged?: boolean;
107
162
  };
108
163
  export type SupaCloudQueueSettings = {
109
164
  max_in_flight: number;
@@ -112,6 +167,76 @@ export type SupaCloudQueueSettings = {
112
167
  rate_limit_per_minute: number;
113
168
  };
114
169
  export type SupaCloudQueueSettingsUpdate = Partial<SupaCloudQueueSettings>;
170
+ export type SupaCloudSupAuthAdminMode = "sso" | "token" | "auto";
171
+ export type SupaCloudSupAuthStorageBucket = {
172
+ id: string;
173
+ public?: boolean;
174
+ fileSizeLimit?: number;
175
+ allowedMimeTypes?: string[];
176
+ };
177
+ export type SupaCloudSupAuthProvisionOptions = {
178
+ authDomain?: string;
179
+ apiDomain?: string;
180
+ adminMode?: SupaCloudSupAuthAdminMode;
181
+ adminSsoClientId?: string;
182
+ runtimeUrl?: string;
183
+ supaOAuthUrl?: string;
184
+ storageBuckets?: SupaCloudSupAuthStorageBucket[];
185
+ metadata?: Record<string, unknown>;
186
+ };
187
+ export type SupaCloudSupAuthReconcileOptions = {
188
+ dryRun?: boolean;
189
+ force?: boolean;
190
+ };
191
+ export type SupaCloudSupAuthStepResult = {
192
+ step: string;
193
+ status: "pending" | "running" | "succeeded" | "failed" | "skipped" | string;
194
+ message?: string;
195
+ details?: Record<string, unknown>;
196
+ };
197
+ export type SupaCloudSupAuthProvisionResult = {
198
+ projectRef: string;
199
+ status: "pending" | "running" | "succeeded" | "failed" | string;
200
+ steps?: SupaCloudSupAuthStepResult[];
201
+ raw?: unknown;
202
+ };
203
+ export type SupaCloudSupAuthReconcileResult = {
204
+ projectRef: string;
205
+ changed: boolean;
206
+ dryRun?: boolean;
207
+ steps?: SupaCloudSupAuthStepResult[];
208
+ raw?: unknown;
209
+ };
210
+ export type SupaCloudSupAuthRollbackResult = {
211
+ projectRef: string;
212
+ status: "succeeded" | "failed" | string;
213
+ steps?: SupaCloudSupAuthStepResult[];
214
+ raw?: unknown;
215
+ };
216
+ export type SupaCloudSupAuthClientConfig = {
217
+ projectRef: string;
218
+ supabaseUrl: string;
219
+ anonKey?: string | null;
220
+ authUrl: string;
221
+ restUrl: string;
222
+ storageUrl: string;
223
+ realtimeUrl: string;
224
+ functionsUrl: string;
225
+ issuer?: string | null;
226
+ jwksUrl?: string | null;
227
+ metadata?: Record<string, unknown>;
228
+ };
229
+ export type SupaCloudSupAuthVerificationCheck = {
230
+ name: string;
231
+ status: "pass" | "fail" | "warn" | string;
232
+ message?: string;
233
+ details?: Record<string, unknown>;
234
+ };
235
+ export type SupaCloudSupAuthVerification = {
236
+ projectRef: string;
237
+ healthy: boolean;
238
+ checks: SupaCloudSupAuthVerificationCheck[];
239
+ };
115
240
  export type SupaCloudTaskWaitOptions = {
116
241
  intervalMs?: number;
117
242
  signal?: AbortSignal;
@@ -244,20 +369,45 @@ declare class SupaCloudQueueClient<TClient extends SupabaseClient = SupabaseClie
244
369
  private readonly name;
245
370
  constructor(options: Required<SupaCloudClientOptions<TClient>>, name: string);
246
371
  private get encodedName();
247
- send(payload?: Record<string, unknown>, options?: SupaCloudQueueSendOptions): Promise<SupaCloudQueueMessage>;
372
+ private rpc;
373
+ send(payload?: Record<string, unknown>, options?: SupaCloudQueueSendOptions): Promise<SupaCloudQueueSendResult>;
374
+ sendBatch(messages: Record<string, unknown>[], options?: SupaCloudQueueSendOptions): Promise<SupaCloudQueueSendResult[]>;
375
+ read(options?: SupaCloudQueueReceiveOptions): Promise<SupaCloudQueueMessage[]>;
248
376
  receive(options?: SupaCloudQueueReceiveOptions): Promise<SupaCloudQueueMessage | null>;
377
+ pop(): Promise<SupaCloudQueueMessage | null>;
249
378
  list(filters?: SupaCloudQueueListFilters): Promise<SupaCloudQueueMessage[]>;
250
379
  listFailed(limit?: number): Promise<SupaCloudQueueMessage[]>;
380
+ listArchived(limit?: number): Promise<SupaCloudQueueMessage[]>;
251
381
  stats(): Promise<SupaCloudQueueStats>;
252
382
  getSettings(): Promise<SupaCloudQueueSettings>;
253
383
  updateSettings(settings: SupaCloudQueueSettingsUpdate): Promise<SupaCloudQueueSettings>;
384
+ archive(messageId: string | number): Promise<SupaCloudQueueMutationResult>;
385
+ ack(messageId: string | number): Promise<SupaCloudQueueMutationResult>;
386
+ delete(messageId: string | number): Promise<SupaCloudQueueMutationResult>;
387
+ release(messageId: string | number, options?: SupaCloudQueueReleaseOptions): Promise<SupaCloudQueueMessage>;
388
+ purge(): Promise<{
389
+ queue_name: string;
390
+ purged: number;
391
+ }>;
392
+ /**
393
+ * SupaCloud extension alias: PGMQ has archive/delete but no failed state.
394
+ * This archives the message, matching the management API's compatibility behavior.
395
+ */
396
+ fail(messageId: string | number, _options?: SupaCloudQueueFailOptions): Promise<SupaCloudQueueMutationResult>;
397
+ /**
398
+ * @deprecated Direct random lookup is not part of Supabase Queues' official API.
399
+ */
254
400
  get(messageId: string): Promise<SupaCloudQueueMessage>;
255
- ack(messageId: string, result?: Record<string, unknown>): Promise<SupaCloudQueueMessage>;
256
- delete(messageId: string): Promise<void>;
257
- release(messageId: string, options?: SupaCloudQueueReleaseOptions): Promise<SupaCloudQueueMessage>;
258
- fail(messageId: string, options?: SupaCloudQueueFailOptions): Promise<SupaCloudQueueMessage>;
401
+ /**
402
+ * @deprecated PGMQ archived messages are replayed with SQL/application workflows, not an official Queue API call.
403
+ */
259
404
  retry(messageId: string): Promise<SupaCloudQueueMessage>;
260
405
  }
406
+ declare class SupaCloudQueuesClient<TClient extends SupabaseClient = SupabaseClient> extends SupaCloudManagementClient<TClient> {
407
+ list(): Promise<SupaCloudQueueInfo[]>;
408
+ create(queueName: string, options?: SupaCloudQueueCreateOptions): Promise<SupaCloudQueueInfo>;
409
+ drop(queueName: string): Promise<void>;
410
+ }
261
411
  declare class SupaCloudOAuthServerClient<TClient extends SupabaseClient = SupabaseClient> extends SupaCloudManagementClient<TClient> {
262
412
  getStatus(): Promise<SupaCloudOAuthServerStatus>;
263
413
  migrateToOidc(options?: {
@@ -275,6 +425,14 @@ declare class SupaCloudOAuthClientsClient<TClient extends SupabaseClient = Supab
275
425
  delete(clientId: string): Promise<void>;
276
426
  regenerateSecret(clientId: string): Promise<SupaCloudOAuthClient>;
277
427
  }
428
+ declare class SupaCloudSupAuthClient<TClient extends SupabaseClient = SupabaseClient> extends SupaCloudManagementClient<TClient> {
429
+ private get basePath();
430
+ provision(options?: SupaCloudSupAuthProvisionOptions): Promise<SupaCloudSupAuthProvisionResult>;
431
+ reconcile(options?: SupaCloudSupAuthReconcileOptions): Promise<SupaCloudSupAuthReconcileResult>;
432
+ rollback(): Promise<SupaCloudSupAuthRollbackResult>;
433
+ getClientConfig(): Promise<SupaCloudSupAuthClientConfig>;
434
+ verify(): Promise<SupaCloudSupAuthVerification>;
435
+ }
278
436
  export declare function createSupaCloudClient<TClient extends SupabaseClient = SupabaseClient>(options: SupaCloudClientOptions<TClient>): {
279
437
  supabase: TClient;
280
438
  projectRef: string;
@@ -284,6 +442,8 @@ export declare function createSupaCloudClient<TClient extends SupabaseClient = S
284
442
  oauthClients: SupaCloudOAuthClientsClient<TClient>;
285
443
  };
286
444
  tasks: SupaCloudTasksClient<TClient>;
445
+ supauth: SupaCloudSupAuthClient<TClient>;
446
+ queues: SupaCloudQueuesClient<TClient>;
287
447
  queue: (name: string) => SupaCloudQueueClient<TClient>;
288
448
  functions: {
289
449
  invokeBackground: (functionName: string, submitOptions?: SupaCloudTaskSubmitOptions) => Promise<SupaCloudTaskReceipt>;
package/dist/index.js CHANGED
@@ -57,6 +57,8 @@ function createQueueQueryString(filters = {}) {
57
57
  const statuses = toArray(filters.status);
58
58
  if (statuses?.length)
59
59
  params.set("status", statuses.join(","));
60
+ if (filters.archived)
61
+ params.set("archived", "true");
60
62
  if (filters.dlq)
61
63
  params.set("dlq", "true");
62
64
  if (filters.limit !== undefined)
@@ -64,6 +66,58 @@ function createQueueQueryString(filters = {}) {
64
66
  const query = params.toString();
65
67
  return query.length > 0 ? `?${query}` : "";
66
68
  }
69
+ function normalizeSecondsFromOptions(options = {}) {
70
+ if (typeof options.sleepSeconds === "number")
71
+ return Math.max(0, Math.floor(options.sleepSeconds));
72
+ if (typeof options.sleep_seconds === "number")
73
+ return Math.max(0, Math.floor(options.sleep_seconds));
74
+ if (typeof options.visibilityTimeoutSec === "number")
75
+ return Math.max(0, Math.floor(options.visibilityTimeoutSec));
76
+ if (typeof options.delayMs === "number")
77
+ return Math.max(0, Math.floor(options.delayMs / 1000));
78
+ return 0;
79
+ }
80
+ function normalizeMessageId(value) {
81
+ const parsed = Number(value);
82
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : 0;
83
+ }
84
+ function firstRpcValue(value) {
85
+ return Array.isArray(value) ? value[0] : value;
86
+ }
87
+ function normalizeRpcMessage(queueName, value, status) {
88
+ const row = firstRpcValue(value);
89
+ if (!row || typeof row !== "object")
90
+ return null;
91
+ const record = row;
92
+ const message = record.message && typeof record.message === "object" && !Array.isArray(record.message) ? record.message : {};
93
+ const msgId = normalizeMessageId(record.msg_id ?? record.id);
94
+ return {
95
+ ...record,
96
+ id: String(msgId),
97
+ msg_id: msgId,
98
+ message,
99
+ payload: message,
100
+ status,
101
+ queue_name: queueName,
102
+ task_type: `queue:${queueName}`
103
+ };
104
+ }
105
+ function normalizeRpcMessages(queueName, value, status) {
106
+ const rows = Array.isArray(value) ? value : value == null ? [] : [value];
107
+ return rows.map((row) => normalizeRpcMessage(queueName, row, status)).filter((row) => Boolean(row));
108
+ }
109
+ function normalizeRpcMessageId(value) {
110
+ const row = firstRpcValue(value);
111
+ if (row && typeof row === "object") {
112
+ const record = row;
113
+ return normalizeMessageId(record.msg_id ?? record.send ?? record.send_batch ?? record.id);
114
+ }
115
+ return normalizeMessageId(row);
116
+ }
117
+ function normalizeRpcMessageIds(value) {
118
+ const rows = Array.isArray(value) ? value : value == null ? [] : [value];
119
+ return rows.map((row) => normalizeRpcMessageId(row)).filter((id) => id > 0);
120
+ }
67
121
  function extractErrorCode(body) {
68
122
  if (!body || typeof body !== "object")
69
123
  return null;
@@ -369,27 +423,63 @@ class SupaCloudQueueClient extends SupaCloudManagementClient {
369
423
  get encodedName() {
370
424
  return encodeURIComponent(this.name);
371
425
  }
426
+ async rpc(fn, params) {
427
+ const scopedClient = this.options.supabase.schema("pgmq_public");
428
+ const { data, error } = await scopedClient.rpc(fn, params);
429
+ if (error)
430
+ throw error;
431
+ return data;
432
+ }
372
433
  async send(payload = {}, options = {}) {
373
- return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages`, "POST", {
374
- payload,
375
- delayMs: options.delayMs,
376
- maxAttempts: options.maxAttempts,
377
- idempotencyKey: options.idempotencyKey,
378
- traceId: options.traceId,
379
- correlationId: options.correlationId,
380
- businessTaskId: options.businessTaskId,
381
- metadata: options.metadata
382
- });
434
+ const msgId = normalizeRpcMessageId(await this.rpc("send", {
435
+ queue_name: this.name,
436
+ message: payload,
437
+ sleep_seconds: normalizeSecondsFromOptions(options)
438
+ }));
439
+ return {
440
+ id: String(msgId),
441
+ msg_id: msgId,
442
+ queue_name: this.name,
443
+ status: "pending",
444
+ payload
445
+ };
446
+ }
447
+ async sendBatch(messages, options = {}) {
448
+ const ids = normalizeRpcMessageIds(await this.rpc("send_batch", {
449
+ queue_name: this.name,
450
+ messages,
451
+ sleep_seconds: normalizeSecondsFromOptions(options)
452
+ }));
453
+ return ids.map((msgId, index) => ({
454
+ id: String(msgId),
455
+ msg_id: msgId,
456
+ queue_name: this.name,
457
+ status: "pending",
458
+ payload: messages[index] ?? {}
459
+ }));
460
+ }
461
+ async read(options = {}) {
462
+ return normalizeRpcMessages(this.name, await this.rpc("read", {
463
+ queue_name: this.name,
464
+ sleep_seconds: normalizeSecondsFromOptions(options),
465
+ n: Math.max(1, Math.floor(options.n ?? options.count ?? 1))
466
+ }), "leased");
383
467
  }
384
468
  async receive(options = {}) {
385
- const message = await this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/receive`, "POST", options);
386
- return message ?? null;
469
+ const messages = await this.read({ ...options, n: 1 });
470
+ return messages[0] ?? null;
471
+ }
472
+ async pop() {
473
+ return normalizeRpcMessage(this.name, await this.rpc("pop", { queue_name: this.name }), "deleted");
387
474
  }
388
475
  async list(filters = {}) {
389
476
  return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages${createQueueQueryString(filters)}`, "GET");
390
477
  }
391
478
  async listFailed(limit = 100) {
392
- return this.list({ dlq: true, limit });
479
+ return this.list({ archived: true, dlq: true, limit });
480
+ }
481
+ async listArchived(limit = 100) {
482
+ return this.list({ archived: true, limit });
393
483
  }
394
484
  async stats() {
395
485
  return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/stats`, "GET");
@@ -400,26 +490,57 @@ class SupaCloudQueueClient extends SupaCloudManagementClient {
400
490
  async updateSettings(settings) {
401
491
  return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/settings`, "PATCH", settings);
402
492
  }
403
- async get(messageId) {
404
- return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/${messageId}`, "GET");
493
+ async archive(messageId) {
494
+ const msgId = normalizeMessageId(messageId);
495
+ const success = Boolean(firstRpcValue(await this.rpc("archive", {
496
+ queue_name: this.name,
497
+ message_id: msgId
498
+ })));
499
+ return { id: String(msgId), msg_id: msgId, queue_name: this.name, status: "archived", success };
405
500
  }
406
- async ack(messageId, result) {
407
- return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/${messageId}/ack`, "POST", result ? { result } : {});
501
+ async ack(messageId) {
502
+ return this.archive(messageId);
408
503
  }
409
504
  async delete(messageId) {
410
- await this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/${messageId}`, "DELETE");
505
+ const msgId = normalizeMessageId(messageId);
506
+ const success = Boolean(firstRpcValue(await this.rpc("delete", {
507
+ queue_name: this.name,
508
+ message_id: msgId
509
+ })));
510
+ return { id: String(msgId), msg_id: msgId, queue_name: this.name, status: "deleted", success };
411
511
  }
412
512
  async release(messageId, options = {}) {
413
- return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/${messageId}/release`, "POST", options);
513
+ return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/${messageId}/release`, "POST", {
514
+ sleep_seconds: normalizeSecondsFromOptions(options),
515
+ ...options.error ? { error: options.error } : {}
516
+ });
517
+ }
518
+ async purge() {
519
+ return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/purge`, "POST");
414
520
  }
415
- async fail(messageId, options = {}) {
416
- return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/${messageId}/fail`, "POST", options);
521
+ async fail(messageId, _options = {}) {
522
+ return this.archive(messageId);
523
+ }
524
+ async get(messageId) {
525
+ return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/${messageId}`, "GET");
417
526
  }
418
527
  async retry(messageId) {
419
528
  return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${this.encodedName}/messages/${messageId}/retry`, "POST");
420
529
  }
421
530
  }
422
531
 
532
+ class SupaCloudQueuesClient extends SupaCloudManagementClient {
533
+ async list() {
534
+ return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues`, "GET");
535
+ }
536
+ async create(queueName, options = {}) {
537
+ return this.request(`/v1/projects/${this.options.projectRef}/tasks/queues`, "POST", { queue_name: queueName, unlogged: options.unlogged });
538
+ }
539
+ async drop(queueName) {
540
+ await this.request(`/v1/projects/${this.options.projectRef}/tasks/queues/${encodeURIComponent(queueName)}`, "DELETE");
541
+ }
542
+ }
543
+
423
544
  class SupaCloudOAuthServerClient extends SupaCloudManagementClient {
424
545
  async getStatus() {
425
546
  return this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-server`, "GET");
@@ -484,6 +605,27 @@ class SupaCloudOAuthClientsClient extends SupaCloudManagementClient {
484
605
  return this.request(`/v1/projects/${this.options.projectRef}/auth/oauth-clients/${encodeURIComponent(clientId)}/regenerate-secret`, "POST");
485
606
  }
486
607
  }
608
+
609
+ class SupaCloudSupAuthClient extends SupaCloudManagementClient {
610
+ get basePath() {
611
+ return `/v1/projects/${this.options.projectRef}/supauth`;
612
+ }
613
+ async provision(options = {}) {
614
+ return this.request(`${this.basePath}/provision`, "POST", options);
615
+ }
616
+ async reconcile(options = {}) {
617
+ return this.request(`${this.basePath}/reconcile`, "POST", options);
618
+ }
619
+ async rollback() {
620
+ return this.request(`${this.basePath}/rollback`, "POST");
621
+ }
622
+ async getClientConfig() {
623
+ return this.request(`${this.basePath}/client-config`, "GET");
624
+ }
625
+ async verify() {
626
+ return this.request(`${this.basePath}/verify`, "GET");
627
+ }
628
+ }
487
629
  function createSupaCloudClient(options) {
488
630
  const normalized = {
489
631
  ...options,
@@ -494,6 +636,8 @@ function createSupaCloudClient(options) {
494
636
  const tasks = new SupaCloudTasksClient(normalized);
495
637
  const oauthServer = new SupaCloudOAuthServerClient(normalized);
496
638
  const oauthClients = new SupaCloudOAuthClientsClient(normalized);
639
+ const supauth = new SupaCloudSupAuthClient(normalized);
640
+ const queues = new SupaCloudQueuesClient(normalized);
497
641
  return {
498
642
  supabase: options.supabase,
499
643
  projectRef: normalized.projectRef,
@@ -503,6 +647,8 @@ function createSupaCloudClient(options) {
503
647
  oauthClients
504
648
  },
505
649
  tasks,
650
+ supauth,
651
+ queues,
506
652
  queue: (name) => new SupaCloudQueueClient(normalized, name),
507
653
  functions: {
508
654
  invokeBackground: (functionName, submitOptions) => tasks.submit(functionName, submitOptions)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supacloud/js",
3
- "version": "0.16.1",
3
+ "version": "0.18.0",
4
4
  "description": "Platform SDK for SupaCloud, built on top of supabase-js",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",