@supacloud/js 0.25.0 → 0.29.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
@@ -186,6 +186,44 @@ The current package focuses on:
186
186
  - `artifacts.get`
187
187
  - `artifacts.link`
188
188
 
189
+ ### Typed task results
190
+
191
+ Task receipts are transport-safe by default: ordinary task methods return an
192
+ unknown result payload. Use an explicit decoder when the application owns the
193
+ result contract; the decoder is retained by the receipt for `get`, `wait`,
194
+ `cancel`, `retry`, and `subscribe`.
195
+
196
+ ```ts
197
+ type InvoiceResult = { invoiceId: string; accepted: boolean };
198
+
199
+ const decodeInvoiceResult = (value: unknown): InvoiceResult => {
200
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
201
+ throw new Error("Invalid invoice result");
202
+ }
203
+ const result = value as Record<string, unknown>;
204
+ if (typeof result.invoiceId !== "string" || typeof result.accepted !== "boolean") {
205
+ throw new Error("Invalid invoice result");
206
+ }
207
+ return { invoiceId: result.invoiceId, accepted: result.accepted };
208
+ };
209
+
210
+ const receipt = await supacloud.tasks.submitTyped(
211
+ "issue-invoice",
212
+ decodeInvoiceResult,
213
+ { body: { invoiceId: "inv-123" } },
214
+ );
215
+ const result = await receipt.wait();
216
+ console.log(result.result?.invoiceId, result.result?.accepted);
217
+ ```
218
+
219
+ The same decoder-first API is available as `getTyped`, `listTyped`,
220
+ `listDlqTyped`, `waitTyped`, `cancelTyped`, `retryTyped`, and `subscribeTyped`.
221
+ Decoder failures throw the sanitized `SupaCloudTaskDecoderError`; its
222
+ `mutationMayHaveApplied` flag is `true` for `cancelTyped` and `retryTyped`, so a
223
+ caller must reconcile the task state instead of blindly repeating the mutation.
224
+ This is runtime validation supplied by the application, not an unchecked
225
+ generic cast or a second platform task schema.
226
+
189
227
  ## Status Subscription
190
228
 
191
229
  `tasks.subscribe()` uses this strategy:
@@ -292,6 +330,30 @@ Queue settings:
292
330
 
293
331
  Management extension conflicts are surfaced as `SupaCloudApiError` with `status`, `code`, and `responseBody`, so callers do not need to parse raw `fetch` responses.
294
332
 
333
+ ## Command Status
334
+
335
+ `commands.submit` and `commands.get` share a runtime-validated status contract:
336
+ `kind: "submission"` means accepted work, with `execution: null`; `kind: "execution"`
337
+ includes the durable execution receipt. Workflow status remains a separate field.
338
+ A completed workflow by itself never proves that an external business effect
339
+ occurred. Use `workflows.get(commandId)` for the full workflow details.
340
+
341
+ `commands.get(commandId)` also accepts `{ tenantId, actorId, command, operationId }`
342
+ for direct executions. The returned commandId is the global dispatch/workflow ID.
343
+ These RPCs remain service-role-only and are not browser authorization boundaries.
344
+
345
+ For submitted work, supply verified `tenantId` and `actorId` on submission, then
346
+ bind the claimed execute step with `createPostgresCommandStore(database, { submission })`.
347
+ The executor preserves the submitted ID and atomically completes or advances the
348
+ same Workflow; it does not create a second command. See
349
+ [migration and worker wiring](../../docs/command-workflow-convergence.md).
350
+
351
+ This is a breaking SDK return-shape change: old top-level `idempotent`, target and
352
+ full-workflow fields are no longer the public command status contract. Identical
353
+ submission replay still deduplicates in SQL. Legacy low-level SQL snapshot/submit
354
+ functions retain their stored submission data; older records are not reclassified
355
+ as confirmed executions.
356
+
295
357
  ## Durable Workflows
296
358
 
297
359
  `supacloud.workflows` coordinates code-defined, linear steps on the project's PostgreSQL and PGMQ runtime. Every workflow RPC is restricted to `service_role`; create this client only in a trusted worker or server process.
@@ -1,33 +1,34 @@
1
- import type { SupabaseClient } from "@supabase/supabase-js";
2
- import type { SupaCloudWorkflowJson, SupaCloudWorkflowRun } from "./workflows.js";
1
+ import { type CommandLookup, type CommandStatus } from "@supacloud/contracts";
2
+ /** Narrow, validated boundary compatible with the Supabase RPC client. */
3
+ export interface CommandRpcClient {
4
+ rpc(functionName: string, args: {
5
+ request: object;
6
+ }): PromiseLike<{
7
+ data: unknown;
8
+ error: unknown;
9
+ }>;
10
+ }
3
11
  export interface SupaCloudCommandSubmitRequest {
4
12
  commandId: string;
5
13
  commandType: string;
6
14
  targetType: string;
7
15
  targetId: string;
8
16
  actorId?: string;
9
- payload?: SupaCloudWorkflowJson;
17
+ /** Required, together with actorId, when binding a submission to a durable executor. */
18
+ tenantId?: string;
19
+ payload?: Record<string, unknown>;
10
20
  maxAttempts?: number;
11
21
  }
12
- export interface SupaCloudCommandReceipt {
13
- commandId: string;
14
- commandType: string;
15
- targetType: string;
16
- targetId: string;
17
- actorId: string | null;
18
- payloadFingerprint: string;
19
- createdAt: string;
20
- idempotent: boolean;
21
- workflow: SupaCloudWorkflowRun;
22
- }
22
+ export type SupaCloudCommandReceipt = CommandStatus;
23
23
  /**
24
24
  * Service-role-only transactional command receipt client. Application-owned
25
25
  * database RPCs can call `supacloud_commands.submit` directly inside a larger
26
26
  * transaction when the domain write and durable enqueue must commit together.
27
27
  */
28
- export declare class SupaCloudCommandsClient<TClient extends SupabaseClient = SupabaseClient> {
28
+ export declare class SupaCloudCommandsClient<TClient extends CommandRpcClient = CommandRpcClient> {
29
29
  private readonly supabase;
30
30
  constructor(supabase: TClient);
31
31
  submit(request: SupaCloudCommandSubmitRequest): Promise<SupaCloudCommandReceipt>;
32
- get(commandId: string): Promise<SupaCloudCommandReceipt | null>;
32
+ get(lookup: string | CommandLookup): Promise<SupaCloudCommandReceipt | null>;
33
+ private request;
33
34
  }
package/dist/index.d.ts CHANGED
@@ -6,6 +6,52 @@ export { createSupaCloudOAuthFetch, type SupaCloudOAuthFetchOptions, } from "./a
6
6
  export * from "./workflows.js";
7
7
  export * from "./commands.js";
8
8
  export * from "./artifacts.js";
9
+ export declare const SUPACLOUD_JS_VERSION = "0.27.1";
10
+ export type SupaCloudCapability = {
11
+ available: boolean;
12
+ source: string;
13
+ version: string | null;
14
+ reason_code: string | null;
15
+ authority_project_ref?: string;
16
+ managed_by_owner?: boolean;
17
+ [key: string]: unknown;
18
+ };
19
+ export type SupaCloudProjectCapabilities = {
20
+ project_ref: string;
21
+ auth_runtime: string;
22
+ schema_version: number;
23
+ platform_version?: string;
24
+ environment?: string;
25
+ storage_backend?: string;
26
+ capabilities: Record<string, SupaCloudCapability>;
27
+ [key: string]: unknown;
28
+ };
29
+ export type SupaCloudEnvironmentInfo = {
30
+ projectRef: string;
31
+ platformVersion: string;
32
+ environment: string;
33
+ schemaVersion: number;
34
+ authRuntime: string;
35
+ storageBackend?: string;
36
+ capabilities: Record<string, SupaCloudCapability>;
37
+ [key: string]: unknown;
38
+ };
39
+ export type SupaCloudStoragePlatformConstraints = {
40
+ max_upload_size_bytes: number;
41
+ max_upload_size_mb: number;
42
+ tus_max_size_bytes: number;
43
+ tus_chunk_max_size_bytes: number;
44
+ streaming_upload_supported: boolean;
45
+ };
46
+ export type SupaCloudStorageUploadConstraints = {
47
+ bucketId: string;
48
+ fileSizeLimit: number | null;
49
+ allowedMimeTypes: string[] | null;
50
+ };
51
+ export type SupaCloudUploadValidationResult = {
52
+ valid: boolean;
53
+ error?: string;
54
+ };
9
55
  export type SupaCloudTaskStatus = "pending" | "leased" | "running" | "retry_scheduled" | "succeeded" | "failed" | "dead_lettered" | "cancelled" | "queued" | "processing" | "completed";
10
56
  export type SupaCloudTaskLogEntry = {
11
57
  timestamp: string;
@@ -23,7 +69,10 @@ export type SupaCloudTaskAttempt = {
23
69
  error: string | null;
24
70
  logs: SupaCloudTaskLogEntry[];
25
71
  };
26
- export type SupaCloudTaskDetail = {
72
+ export type SupaCloudTaskResultDecoder<TResult> = (value: unknown) => TResult;
73
+ /** Alias kept short for consumers that already use decoder terminology. */
74
+ export type SupaCloudTaskDecoder<TResult> = SupaCloudTaskResultDecoder<TResult>;
75
+ export type SupaCloudTaskDetail<TResult = unknown> = {
27
76
  id: string;
28
77
  status: SupaCloudTaskStatus | string;
29
78
  function_slug?: string | null;
@@ -33,7 +82,7 @@ export type SupaCloudTaskDetail = {
33
82
  progress?: number | null;
34
83
  error?: string | null;
35
84
  error_message?: string | null;
36
- result?: unknown;
85
+ result?: TResult;
37
86
  payload?: Record<string, unknown>;
38
87
  attempts?: SupaCloudTaskAttempt[];
39
88
  latest_logs?: SupaCloudTaskLogEntry[];
@@ -44,13 +93,13 @@ export type SupaCloudTaskDetail = {
44
93
  created_at?: string | null;
45
94
  [key: string]: unknown;
46
95
  };
47
- export type SupaCloudTaskSnapshot = {
96
+ export type SupaCloudTaskSnapshot<TResult = unknown> = {
48
97
  id: string;
49
98
  status: SupaCloudTaskStatus | string;
50
99
  progress?: number | null;
51
100
  error?: string | null;
52
101
  updatedAt?: string | null;
53
- raw: unknown;
102
+ raw: SupaCloudTaskDetail<TResult>;
54
103
  };
55
104
  export type SupaCloudTaskListFilters = {
56
105
  status?: string | string[];
@@ -249,28 +298,29 @@ export type SupaCloudTaskWaitOptions = {
249
298
  signal?: AbortSignal;
250
299
  };
251
300
  export type SupaCloudTaskSubscribeState = "connecting" | "realtime" | "polling" | "closed";
252
- export type SupaCloudTaskSubscribeOptions = {
301
+ export type SupaCloudTaskSubscribeOptions<TResult = unknown> = {
253
302
  pollingIntervalMs?: number;
254
303
  realtimeTimeoutMs?: number;
255
304
  reconcileIntervalMs?: number;
256
- onUpdate: (task: SupaCloudTaskSnapshot) => void;
305
+ onUpdate: (task: SupaCloudTaskSnapshot<TResult>) => void;
257
306
  onStateChange?: (state: SupaCloudTaskSubscribeState, details?: {
258
307
  error?: unknown;
259
308
  }) => void;
260
309
  onError?: (error: unknown) => void;
261
310
  stopOnTerminal?: boolean;
262
311
  };
263
- export type SupaCloudTaskReceipt = {
312
+ export type SupaCloudTaskSubscription = {
313
+ readonly connectionState: SupaCloudTaskSubscribeState;
314
+ unsubscribe: () => void;
315
+ };
316
+ export type SupaCloudTaskReceipt<TResult = unknown> = {
264
317
  taskId: string;
265
318
  status: string;
266
- get: () => Promise<SupaCloudTaskDetail>;
267
- wait: (options?: SupaCloudTaskWaitOptions) => Promise<SupaCloudTaskDetail>;
268
- cancel: () => Promise<SupaCloudTaskDetail>;
269
- retry: () => Promise<SupaCloudTaskDetail>;
270
- subscribe: (options: SupaCloudTaskSubscribeOptions) => {
271
- connectionState: SupaCloudTaskSubscribeState;
272
- unsubscribe: () => void;
273
- };
319
+ get: () => Promise<SupaCloudTaskDetail<TResult>>;
320
+ wait: (options?: SupaCloudTaskWaitOptions) => Promise<SupaCloudTaskDetail<TResult>>;
321
+ cancel: () => Promise<SupaCloudTaskDetail<TResult>>;
322
+ retry: () => Promise<SupaCloudTaskDetail<TResult>>;
323
+ subscribe: (options: SupaCloudTaskSubscribeOptions<TResult>) => SupaCloudTaskSubscription;
274
324
  };
275
325
  export type SupaCloudClientOptions<TClient extends SupabaseClient = SupabaseClient> = {
276
326
  supabase: TClient;
@@ -352,6 +402,19 @@ export declare class SupaCloudApiError extends Error {
352
402
  readonly responseBody: unknown;
353
403
  constructor(message: string, status: number, responseBody: unknown);
354
404
  }
405
+ export type SupaCloudTaskDecodeOperation = "get" | "list" | "wait" | "cancel" | "retry" | "subscribe";
406
+ /**
407
+ * A caller-supplied result decoder failed. Decoder errors are sanitized so
408
+ * application result values and decoder implementation details are not leaked.
409
+ */
410
+ export declare class SupaCloudTaskDecoderError extends SupaCloudApiError {
411
+ readonly operation: SupaCloudTaskDecodeOperation;
412
+ readonly code: "TASK_RESULT_INVALID";
413
+ readonly mutationMayHaveApplied: boolean;
414
+ constructor(operation: SupaCloudTaskDecodeOperation);
415
+ }
416
+ /** Compatibility spelling for callers that use the shorter decode term. */
417
+ export { SupaCloudTaskDecoderError as SupaCloudTaskDecodeError };
355
418
  type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
356
419
  type ResponseDecoder<T> = (value: unknown) => T;
357
420
  declare class SupaCloudManagementClient<TClient extends SupabaseClient = SupabaseClient> {
@@ -362,17 +425,28 @@ declare class SupaCloudManagementClient<TClient extends SupabaseClient = Supabas
362
425
  }
363
426
  declare class SupaCloudTasksClient<TClient extends SupabaseClient = SupabaseClient> extends SupaCloudManagementClient<TClient> {
364
427
  private createReceipt;
365
- submit(functionName: string, options?: SupaCloudTaskSubmitOptions): Promise<SupaCloudTaskReceipt>;
428
+ private createTypedReceipt;
429
+ submit(functionName: string, options?: SupaCloudTaskSubmitOptions): Promise<SupaCloudTaskReceipt<unknown>>;
430
+ submitTyped<TResult>(functionName: string, decoder: SupaCloudTaskResultDecoder<TResult>, options?: SupaCloudTaskSubmitOptions): Promise<SupaCloudTaskReceipt<TResult>>;
431
+ submitTyped<TResult>(functionName: string, options: SupaCloudTaskSubmitOptions, decoder: SupaCloudTaskResultDecoder<TResult>): Promise<SupaCloudTaskReceipt<TResult>>;
366
432
  get(taskId: string): Promise<SupaCloudTaskDetail>;
433
+ getTyped<TResult>(taskId: string, decoder: SupaCloudTaskResultDecoder<TResult>): Promise<SupaCloudTaskDetail<TResult>>;
367
434
  list(filters?: SupaCloudTaskListFilters): Promise<SupaCloudTaskDetail[]>;
435
+ listTyped<TResult>(decoder: SupaCloudTaskResultDecoder<TResult>, filters?: SupaCloudTaskListFilters): Promise<SupaCloudTaskDetail<TResult>[]>;
436
+ listTyped<TResult>(filters: SupaCloudTaskListFilters, decoder: SupaCloudTaskResultDecoder<TResult>): Promise<SupaCloudTaskDetail<TResult>[]>;
368
437
  cancel(taskId: string): Promise<SupaCloudTaskDetail>;
438
+ cancelTyped<TResult>(taskId: string, decoder: SupaCloudTaskResultDecoder<TResult>): Promise<SupaCloudTaskDetail<TResult>>;
369
439
  retry(taskId: string): Promise<SupaCloudTaskDetail>;
440
+ retryTyped<TResult>(taskId: string, decoder: SupaCloudTaskResultDecoder<TResult>): Promise<SupaCloudTaskDetail<TResult>>;
370
441
  listDlq(limit?: number): Promise<SupaCloudTaskDetail[]>;
442
+ listDlqTyped<TResult>(decoder: SupaCloudTaskResultDecoder<TResult>, limit?: number): Promise<SupaCloudTaskDetail<TResult>[]>;
371
443
  wait(taskId: string, options?: SupaCloudTaskWaitOptions): Promise<SupaCloudTaskDetail>;
372
- subscribe(taskId: string, options: SupaCloudTaskSubscribeOptions): {
373
- readonly connectionState: SupaCloudTaskSubscribeState;
374
- unsubscribe(): void;
375
- };
444
+ waitTyped<TResult>(taskId: string, decoder: SupaCloudTaskResultDecoder<TResult>, options?: SupaCloudTaskWaitOptions): Promise<SupaCloudTaskDetail<TResult>>;
445
+ waitTyped<TResult>(taskId: string, options: SupaCloudTaskWaitOptions, decoder: SupaCloudTaskResultDecoder<TResult>): Promise<SupaCloudTaskDetail<TResult>>;
446
+ subscribe(taskId: string, options: SupaCloudTaskSubscribeOptions): SupaCloudTaskSubscription;
447
+ subscribeTyped<TResult>(taskId: string, decoder: SupaCloudTaskResultDecoder<TResult>, options: SupaCloudTaskSubscribeOptions<TResult>): SupaCloudTaskSubscription;
448
+ subscribeTyped<TResult>(taskId: string, options: SupaCloudTaskSubscribeOptions<TResult>, decoder: SupaCloudTaskResultDecoder<TResult>): SupaCloudTaskSubscription;
449
+ private subscribeInternal;
376
450
  }
377
451
  declare class SupaCloudQueueClient<TClient extends SupabaseClient = SupabaseClient> extends SupaCloudManagementClient<TClient> {
378
452
  private readonly name;
@@ -443,6 +517,20 @@ declare class SupaCloudSupAuthClient<TClient extends SupabaseClient = SupabaseCl
443
517
  getClientConfig(): Promise<SupaCloudSupAuthClientConfig>;
444
518
  verify(): Promise<SupaCloudSupAuthVerification>;
445
519
  }
520
+ export declare class SupaCloudCapabilitiesClient<TClient extends SupabaseClient = SupabaseClient> extends SupaCloudManagementClient<TClient> {
521
+ get(): Promise<SupaCloudProjectCapabilities>;
522
+ isAvailable(capabilityKey: string): Promise<boolean>;
523
+ getVersion(): Promise<string>;
524
+ getEnvironment(): Promise<SupaCloudEnvironmentInfo>;
525
+ }
526
+ export declare class SupaCloudStorageClient<TClient extends SupabaseClient = SupabaseClient> extends SupaCloudManagementClient<TClient> {
527
+ getPlatformConstraints(): Promise<SupaCloudStoragePlatformConstraints>;
528
+ getUploadConstraints(bucketId: string): Promise<SupaCloudStorageUploadConstraints>;
529
+ validateUpload(bucketId: string, file: {
530
+ size: number;
531
+ type?: string;
532
+ }): Promise<SupaCloudUploadValidationResult>;
533
+ }
446
534
  export declare function createSupaCloudClient<TClient extends SupabaseClient = SupabaseClient>(options: SupaCloudClientOptions<TClient>): {
447
535
  supabase: TClient;
448
536
  projectRef: string;
@@ -457,8 +545,12 @@ export declare function createSupaCloudClient<TClient extends SupabaseClient = S
457
545
  artifacts: SupaCloudArtifactsClient<TClient>;
458
546
  supauth: SupaCloudSupAuthClient<TClient>;
459
547
  queues: SupaCloudQueuesClient<TClient>;
548
+ capabilities: SupaCloudCapabilitiesClient<TClient>;
549
+ storage: SupaCloudStorageClient<TClient>;
550
+ getEnvironment: () => Promise<SupaCloudEnvironmentInfo>;
551
+ getVersion: () => Promise<string>;
460
552
  queue: (name: string) => SupaCloudQueueClient<TClient>;
461
553
  functions: {
462
- invokeBackground: (functionName: string, submitOptions?: SupaCloudTaskSubmitOptions) => Promise<SupaCloudTaskReceipt>;
554
+ invokeBackground: (functionName: string, submitOptions?: SupaCloudTaskSubmitOptions) => Promise<SupaCloudTaskReceipt<unknown>>;
463
555
  };
464
556
  };
package/dist/index.js CHANGED
@@ -49,18 +49,44 @@ class SupaCloudWorkflowsClient {
49
49
  }
50
50
 
51
51
  // src/commands.ts
52
+ import { decodeCommandStatus } from "@supacloud/contracts";
53
+
52
54
  class SupaCloudCommandsClient {
53
55
  supabase;
54
56
  constructor(supabase) {
55
57
  this.supabase = supabase;
56
58
  }
57
- submit(request) {
58
- return invokeServiceRoleRpc(this.supabase, "supacloud_command_submit", request);
59
+ async submit(request) {
60
+ const raw = await this.request("supacloud_command_submit", request);
61
+ const status = decodeCommandStatus(raw);
62
+ if (status.commandId !== request.commandId.toLowerCase())
63
+ throw new TypeError("Invalid command submission");
64
+ return status;
65
+ }
66
+ async get(lookup) {
67
+ const request = typeof lookup === "string" ? { commandId: lookup } : { ...lookup };
68
+ const raw = await this.request("supacloud_command_get", request);
69
+ if (raw === null)
70
+ return null;
71
+ const status = decodeCommandStatus(raw);
72
+ if ("commandId" in request) {
73
+ if (status.commandId !== request.commandId.toLowerCase())
74
+ throw new TypeError("Mismatched command status");
75
+ } else {
76
+ if (status.kind !== "execution")
77
+ throw new TypeError("Missing command execution");
78
+ for (const key of ["tenantId", "actorId", "command", "operationId"]) {
79
+ if (status.execution[key] !== request[key])
80
+ throw new TypeError("Mismatched command reference");
81
+ }
82
+ }
83
+ return status;
59
84
  }
60
- get(commandId) {
61
- return invokeServiceRoleRpc(this.supabase, "supacloud_command_get", {
62
- commandId
63
- });
85
+ async request(functionName, request) {
86
+ const result = await this.supabase.rpc(functionName, { request });
87
+ if (result.error)
88
+ throw result.error;
89
+ return result.data;
64
90
  }
65
91
  }
66
92
 
@@ -106,12 +132,12 @@ function parseRefreshBody(body, contentType) {
106
132
  const refreshToken = typeof record.refresh_token === "string" ? record.refresh_token.trim() : "";
107
133
  if (!refreshToken)
108
134
  return null;
109
- const params2 = new URLSearchParams;
135
+ const params = new URLSearchParams;
110
136
  for (const [key, item] of Object.entries(record)) {
111
137
  if (typeof item === "string")
112
- params2.set(key, item);
138
+ params.set(key, item);
113
139
  }
114
- return params2;
140
+ return params;
115
141
  }
116
142
  const params = new URLSearchParams(body);
117
143
  return params.get("refresh_token")?.trim() ? params : null;
@@ -172,6 +198,8 @@ function createSupaCloudOAuthFetch(options = {}) {
172
198
  }
173
199
 
174
200
  // src/index.ts
201
+ var SUPACLOUD_JS_VERSION = "0.27.1";
202
+
175
203
  class SupaCloudTaskSubmitError extends Error {
176
204
  responseBody;
177
205
  constructor(message, responseBody) {
@@ -193,6 +221,22 @@ class SupaCloudApiError extends Error {
193
221
  this.code = extractErrorCode(responseBody);
194
222
  }
195
223
  }
224
+
225
+ class SupaCloudTaskDecoderError extends SupaCloudApiError {
226
+ operation;
227
+ code = "TASK_RESULT_INVALID";
228
+ mutationMayHaveApplied;
229
+ constructor(operation) {
230
+ const mutation = operation === "cancel" || operation === "retry";
231
+ super("Task result could not be decoded", 0, {
232
+ code: "TASK_RESULT_INVALID",
233
+ mutation_may_have_applied: mutation
234
+ });
235
+ this.operation = operation;
236
+ this.name = "SupaCloudTaskDecoderError";
237
+ this.mutationMayHaveApplied = mutation;
238
+ }
239
+ }
196
240
  var TERMINAL_STATUSES = new Set([
197
241
  "succeeded",
198
242
  "failed",
@@ -332,6 +376,20 @@ function decodeTaskDetails(value) {
332
376
  throw new Error("Invalid task list response");
333
377
  return value.map(decodeTaskDetail);
334
378
  }
379
+ function captureTaskDecoder(value) {
380
+ if (typeof value !== "function")
381
+ throw new TypeError("Invalid task result decoder");
382
+ return value;
383
+ }
384
+ function decodeTaskResult(task, decoder, operation) {
385
+ if (!Object.hasOwn(task, "result"))
386
+ return task;
387
+ try {
388
+ return { ...task, result: decoder(task.result) };
389
+ } catch {
390
+ throw new SupaCloudTaskDecoderError(operation);
391
+ }
392
+ }
335
393
  function decodeQueueMessage(value) {
336
394
  const record = responseRecord(value, "queue message");
337
395
  const messageValue = record.message ?? record.payload;
@@ -483,11 +541,11 @@ function decodeSupAuthVerification(value) {
483
541
  projectRef: responseString(record, "projectRef", "SupAuth verification"),
484
542
  healthy: responseBoolean(record, "healthy", "SupAuth verification"),
485
543
  checks: checks.map((check) => {
486
- const record2 = responseRecord(check, "SupAuth check");
544
+ const record = responseRecord(check, "SupAuth check");
487
545
  return {
488
- ...record2,
489
- name: responseString(record2, "name", "SupAuth check"),
490
- status: responseString(record2, "status", "SupAuth check")
546
+ ...record,
547
+ name: responseString(record, "name", "SupAuth check"),
548
+ status: responseString(record, "status", "SupAuth check")
491
549
  };
492
550
  })
493
551
  };
@@ -499,6 +557,42 @@ function decodePurgeResult(value) {
499
557
  purged: responseNumber(record, "purged", "queue purge")
500
558
  };
501
559
  }
560
+ function decodeProjectCapabilities(value) {
561
+ const record = responseRecord(value, "project capabilities");
562
+ const rawCapabilities = valueRecord2(record.capabilities);
563
+ const capabilities = {};
564
+ for (const [key, item] of Object.entries(rawCapabilities)) {
565
+ const capRecord = valueRecord2(item);
566
+ capabilities[key] = {
567
+ available: typeof capRecord.available === "boolean" ? capRecord.available : false,
568
+ source: typeof capRecord.source === "string" ? capRecord.source : "unknown",
569
+ version: typeof capRecord.version === "string" ? capRecord.version : null,
570
+ reason_code: typeof capRecord.reason_code === "string" ? capRecord.reason_code : null,
571
+ ...typeof capRecord.authority_project_ref === "string" ? { authority_project_ref: capRecord.authority_project_ref } : {},
572
+ ...typeof capRecord.managed_by_owner === "boolean" ? { managed_by_owner: capRecord.managed_by_owner } : {}
573
+ };
574
+ }
575
+ return {
576
+ ...record,
577
+ project_ref: responseString(record, "project_ref", "project capabilities"),
578
+ auth_runtime: typeof record.auth_runtime === "string" ? record.auth_runtime : "unknown",
579
+ schema_version: typeof record.schema_version === "number" ? record.schema_version : 1,
580
+ platform_version: typeof record.platform_version === "string" ? record.platform_version : undefined,
581
+ environment: typeof record.environment === "string" ? record.environment : undefined,
582
+ storage_backend: typeof record.storage_backend === "string" ? record.storage_backend : undefined,
583
+ capabilities
584
+ };
585
+ }
586
+ function decodeStoragePlatformConstraints(value) {
587
+ const record = responseRecord(value, "storage constraints");
588
+ return {
589
+ max_upload_size_bytes: responseNumber(record, "max_upload_size_bytes", "storage constraints"),
590
+ max_upload_size_mb: responseNumber(record, "max_upload_size_mb", "storage constraints"),
591
+ tus_max_size_bytes: responseNumber(record, "tus_max_size_bytes", "storage constraints"),
592
+ tus_chunk_max_size_bytes: responseNumber(record, "tus_chunk_max_size_bytes", "storage constraints"),
593
+ streaming_upload_supported: responseBoolean(record, "streaming_upload_supported", "storage constraints")
594
+ };
595
+ }
502
596
  function normalizeRpcMessage(queueName, value, status) {
503
597
  const row = firstRpcValue(value);
504
598
  if (!row || typeof row !== "object")
@@ -556,15 +650,16 @@ async function defaultAccessTokenResolver(supabase) {
556
650
  throw error;
557
651
  return data.session?.access_token ?? null;
558
652
  }
559
- function normalizeTaskSnapshot(task) {
560
- const value = valueRecord2(task ?? {});
653
+ function normalizeTaskSnapshot(task, decoder) {
654
+ const raw = decoder ? decodeTaskResult(decodeTaskDetail(task), decoder, "subscribe") : task;
655
+ const value = valueRecord2(raw);
561
656
  return {
562
657
  id: String(value.id ?? ""),
563
658
  status: String(value.status ?? "unknown"),
564
659
  progress: typeof value.progress === "number" ? value.progress : null,
565
660
  error: typeof value.error === "string" ? value.error : typeof value.error_message === "string" ? value.error_message : null,
566
661
  updatedAt: typeof value.updated_at === "string" ? value.updated_at : typeof value.updatedAt === "string" ? value.updatedAt : null,
567
- raw: task
662
+ raw
568
663
  };
569
664
  }
570
665
 
@@ -586,6 +681,7 @@ class SupaCloudManagementClient {
586
681
  method,
587
682
  headers: {
588
683
  authorization: `Bearer ${accessToken}`,
684
+ "x-client-info": `supacloud-js/${SUPACLOUD_JS_VERSION}`,
589
685
  ...body !== undefined ? { "content-type": "application/json" } : {}
590
686
  },
591
687
  ...body !== undefined ? { body: JSON.stringify(body) } : {}
@@ -594,8 +690,8 @@ class SupaCloudManagementClient {
594
690
  return decode(undefined);
595
691
  const responseBody = await readResponseBody(response);
596
692
  if (!response.ok) {
597
- const responseRecord2 = valueRecord2(responseBody);
598
- const message = typeof responseRecord2.message === "string" ? responseRecord2.message : `SupaCloud request failed (${response.status})`;
693
+ const responseRecord = valueRecord2(responseBody);
694
+ const message = typeof responseRecord.message === "string" ? responseRecord.message : `SupaCloud request failed (${response.status})`;
599
695
  throw new SupaCloudApiError(message, response.status, responseBody);
600
696
  }
601
697
  return decode(responseBody);
@@ -611,7 +707,18 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
611
707
  wait: (options) => this.wait(taskId, options),
612
708
  cancel: () => this.cancel(taskId),
613
709
  retry: () => this.retry(taskId),
614
- subscribe: (options) => this.subscribe(taskId, options)
710
+ subscribe: (options) => this.subscribeInternal(taskId, options)
711
+ };
712
+ }
713
+ createTypedReceipt(taskId, status, decoder) {
714
+ return {
715
+ taskId,
716
+ status,
717
+ get: () => this.getTyped(taskId, decoder),
718
+ wait: (options) => this.waitTyped(taskId, decoder, options),
719
+ cancel: () => this.cancelTyped(taskId, decoder),
720
+ retry: () => this.retryTyped(taskId, decoder),
721
+ subscribe: (options) => this.subscribeTyped(taskId, decoder, options)
615
722
  };
616
723
  }
617
724
  async submit(functionName, options = {}) {
@@ -638,21 +745,52 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
638
745
  }
639
746
  return this.createReceipt(taskId, String(payload.status ?? "enqueued"));
640
747
  }
748
+ async submitTyped(functionName, decoderOrOptions, optionsOrDecoder) {
749
+ let decoder;
750
+ let options;
751
+ if (typeof decoderOrOptions === "function") {
752
+ decoder = captureTaskDecoder(decoderOrOptions);
753
+ options = typeof optionsOrDecoder === "function" ? undefined : optionsOrDecoder;
754
+ } else {
755
+ options = decoderOrOptions;
756
+ decoder = captureTaskDecoder(optionsOrDecoder);
757
+ }
758
+ const receipt = await this.submit(functionName, options);
759
+ return this.createTypedReceipt(receipt.taskId, receipt.status, decoder);
760
+ }
641
761
  async get(taskId) {
642
762
  return this.request(`/v1/projects/${this.options.projectRef}/tasks/${taskId}`, "GET", undefined, decodeTaskDetail);
643
763
  }
764
+ async getTyped(taskId, decoder) {
765
+ const resultDecoder = captureTaskDecoder(decoder);
766
+ return decodeTaskResult(await this.get(taskId), resultDecoder, "get");
767
+ }
644
768
  async list(filters = {}) {
645
769
  return this.request(`/v1/projects/${this.options.projectRef}/tasks${createQueryString(filters)}`, "GET", undefined, decodeTaskDetails);
646
770
  }
771
+ async listTyped(decoderOrFilters, filtersOrDecoder) {
772
+ const decoder = typeof decoderOrFilters === "function" ? captureTaskDecoder(decoderOrFilters) : captureTaskDecoder(filtersOrDecoder);
773
+ const filters = typeof decoderOrFilters === "function" ? filtersOrDecoder : decoderOrFilters;
774
+ return (await this.list(filters)).map((task) => decodeTaskResult(task, decoder, "list"));
775
+ }
647
776
  async cancel(taskId) {
648
777
  return this.request(`/v1/projects/${this.options.projectRef}/tasks/${taskId}/cancel`, "POST", undefined, decodeTaskDetail);
649
778
  }
779
+ async cancelTyped(taskId, decoder) {
780
+ return decodeTaskResult(await this.cancel(taskId), captureTaskDecoder(decoder), "cancel");
781
+ }
650
782
  async retry(taskId) {
651
783
  return this.request(`/v1/projects/${this.options.projectRef}/tasks/${taskId}/retry`, "POST", undefined, decodeTaskDetail);
652
784
  }
785
+ async retryTyped(taskId, decoder) {
786
+ return decodeTaskResult(await this.retry(taskId), captureTaskDecoder(decoder), "retry");
787
+ }
653
788
  async listDlq(limit = 100) {
654
789
  return this.request(`/v1/projects/${this.options.projectRef}/tasks/dlq?limit=${limit}`, "GET", undefined, decodeTaskDetails);
655
790
  }
791
+ async listDlqTyped(decoder, limit = 100) {
792
+ return this.listTyped({ dlq: true, limit }, captureTaskDecoder(decoder));
793
+ }
656
794
  async wait(taskId, options = {}) {
657
795
  const intervalMs = options.intervalMs ?? this.options.pollingIntervalMs;
658
796
  while (true) {
@@ -665,7 +803,20 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
665
803
  await waitForPollingInterval(intervalMs, options.signal);
666
804
  }
667
805
  }
806
+ async waitTyped(taskId, decoderOrOptions, optionsOrDecoder) {
807
+ const decoder = typeof decoderOrOptions === "function" ? captureTaskDecoder(decoderOrOptions) : captureTaskDecoder(optionsOrDecoder);
808
+ const options = typeof decoderOrOptions === "function" ? optionsOrDecoder : decoderOrOptions;
809
+ return decodeTaskResult(await this.wait(taskId, options), decoder, "wait");
810
+ }
668
811
  subscribe(taskId, options) {
812
+ return this.subscribeInternal(taskId, options);
813
+ }
814
+ subscribeTyped(taskId, decoderOrOptions, optionsOrDecoder) {
815
+ const decoder = typeof decoderOrOptions === "function" ? captureTaskDecoder(decoderOrOptions) : captureTaskDecoder(optionsOrDecoder);
816
+ const options = typeof decoderOrOptions === "function" ? optionsOrDecoder : decoderOrOptions;
817
+ return this.subscribeInternal(taskId, options, decoder);
818
+ }
819
+ subscribeInternal(taskId, options, decoder) {
669
820
  let closed = false;
670
821
  let channel = null;
671
822
  let pollTimer = null;
@@ -718,7 +869,7 @@ class SupaCloudTasksClient extends SupaCloudManagementClient {
718
869
  closed = true;
719
870
  };
720
871
  const emitTask = (task) => {
721
- const snapshot = normalizeTaskSnapshot(task);
872
+ const snapshot = normalizeTaskSnapshot(task, decoder);
722
873
  options.onUpdate(snapshot);
723
874
  if (stopOnTerminal && TERMINAL_STATUSES.has(snapshot.status)) {
724
875
  close();
@@ -1040,6 +1191,83 @@ class SupaCloudSupAuthClient extends SupaCloudManagementClient {
1040
1191
  return this.request(`${this.basePath}/verify`, "GET", undefined, decodeSupAuthVerification);
1041
1192
  }
1042
1193
  }
1194
+
1195
+ class SupaCloudCapabilitiesClient extends SupaCloudManagementClient {
1196
+ async get() {
1197
+ return this.request(`/v1/projects/${this.options.projectRef}/capabilities`, "GET", undefined, decodeProjectCapabilities);
1198
+ }
1199
+ async isAvailable(capabilityKey) {
1200
+ const res = await this.get();
1201
+ return res.capabilities?.[capabilityKey]?.available === true;
1202
+ }
1203
+ async getVersion() {
1204
+ const res = await this.get();
1205
+ return res.platform_version ?? "unknown";
1206
+ }
1207
+ async getEnvironment() {
1208
+ const res = await this.get();
1209
+ return {
1210
+ projectRef: res.project_ref,
1211
+ platformVersion: res.platform_version ?? "unknown",
1212
+ environment: res.environment ?? "production",
1213
+ schemaVersion: res.schema_version,
1214
+ authRuntime: res.auth_runtime,
1215
+ storageBackend: res.storage_backend,
1216
+ capabilities: res.capabilities
1217
+ };
1218
+ }
1219
+ }
1220
+
1221
+ class SupaCloudStorageClient extends SupaCloudManagementClient {
1222
+ async getPlatformConstraints() {
1223
+ return this.request(`/storage/v1/constraints`, "GET", undefined, decodeStoragePlatformConstraints);
1224
+ }
1225
+ async getUploadConstraints(bucketId) {
1226
+ try {
1227
+ const { data, error } = await this.options.supabase.storage.getBucket(bucketId);
1228
+ if (!error && data) {
1229
+ return {
1230
+ bucketId,
1231
+ fileSizeLimit: typeof data.file_size_limit === "number" ? data.file_size_limit : data.file_size_limit ? Number(data.file_size_limit) : null,
1232
+ allowedMimeTypes: Array.isArray(data.allowed_mime_types) ? data.allowed_mime_types : null
1233
+ };
1234
+ }
1235
+ } catch {}
1236
+ try {
1237
+ const bucket = await this.request(`/v1/projects/${this.options.projectRef}/storage/buckets/${encodeURIComponent(bucketId)}`, "GET", undefined, (val) => responseRecord(val, "storage bucket"));
1238
+ const rawLimit = bucket.file_size_limit;
1239
+ const fileSizeLimit = typeof rawLimit === "number" ? rawLimit : rawLimit ? Number(rawLimit) : null;
1240
+ const allowedMimeTypes = Array.isArray(bucket.allowed_mime_types) ? bucket.allowed_mime_types : null;
1241
+ return {
1242
+ bucketId,
1243
+ fileSizeLimit,
1244
+ allowedMimeTypes
1245
+ };
1246
+ } catch {
1247
+ return {
1248
+ bucketId,
1249
+ fileSizeLimit: null,
1250
+ allowedMimeTypes: null
1251
+ };
1252
+ }
1253
+ }
1254
+ async validateUpload(bucketId, file) {
1255
+ const constraints = await this.getUploadConstraints(bucketId);
1256
+ if (constraints.fileSizeLimit !== null && file.size > constraints.fileSizeLimit) {
1257
+ return {
1258
+ valid: false,
1259
+ error: `File size ${file.size} bytes exceeds bucket limit of ${constraints.fileSizeLimit} bytes`
1260
+ };
1261
+ }
1262
+ if (constraints.allowedMimeTypes && constraints.allowedMimeTypes.length > 0 && file.type && !constraints.allowedMimeTypes.includes(file.type)) {
1263
+ return {
1264
+ valid: false,
1265
+ error: `MIME type "${file.type}" is not in the allowed list: ${constraints.allowedMimeTypes.join(", ")}`
1266
+ };
1267
+ }
1268
+ return { valid: true };
1269
+ }
1270
+ }
1043
1271
  function createSupaCloudClient(options) {
1044
1272
  const normalized = {
1045
1273
  ...options,
@@ -1052,6 +1280,8 @@ function createSupaCloudClient(options) {
1052
1280
  const oauthClients = new SupaCloudOAuthClientsClient(normalized);
1053
1281
  const supauth = new SupaCloudSupAuthClient(normalized);
1054
1282
  const queues = new SupaCloudQueuesClient(normalized);
1283
+ const capabilities = new SupaCloudCapabilitiesClient(normalized);
1284
+ const storage = new SupaCloudStorageClient(normalized);
1055
1285
  const workflows2 = new SupaCloudWorkflowsClient(options.supabase);
1056
1286
  const commands2 = new SupaCloudCommandsClient(options.supabase);
1057
1287
  const artifacts2 = new SupaCloudArtifactsClient(options.supabase);
@@ -1069,6 +1299,10 @@ function createSupaCloudClient(options) {
1069
1299
  artifacts: artifacts2,
1070
1300
  supauth,
1071
1301
  queues,
1302
+ capabilities,
1303
+ storage,
1304
+ getEnvironment: () => capabilities.getEnvironment(),
1305
+ getVersion: () => capabilities.getVersion(),
1072
1306
  queue: (name) => new SupaCloudQueueClient(normalized, name),
1073
1307
  functions: {
1074
1308
  invokeBackground: (functionName, submitOptions) => tasks.submit(functionName, submitOptions)
@@ -1076,9 +1310,14 @@ function createSupaCloudClient(options) {
1076
1310
  };
1077
1311
  }
1078
1312
  export {
1313
+ SUPACLOUD_JS_VERSION,
1079
1314
  SupaCloudApiError,
1080
1315
  SupaCloudArtifactsClient,
1316
+ SupaCloudCapabilitiesClient,
1081
1317
  SupaCloudCommandsClient,
1318
+ SupaCloudStorageClient,
1319
+ SupaCloudTaskDecoderError as SupaCloudTaskDecodeError,
1320
+ SupaCloudTaskDecoderError,
1082
1321
  SupaCloudTaskSubmitError,
1083
1322
  SupaCloudWorkflowsClient,
1084
1323
  createSupaCloudClient,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supacloud/js",
3
- "version": "0.25.0",
3
+ "version": "0.29.0",
4
4
  "description": "Platform SDK for SupaCloud, built on top of supabase-js",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -20,7 +20,7 @@
20
20
  "scripts": {
21
21
  "test": "bun test",
22
22
  "build": "bun run clean && bun run build:js && bun run build:types",
23
- "build:js": "bun build src/index.ts --outdir dist --target node",
23
+ "build:js": "bun build src/index.ts --outdir dist --target node --external @supacloud/contracts",
24
24
  "build:types": "tsc -p tsconfig.json --emitDeclarationOnly",
25
25
  "clean": "rm -rf dist",
26
26
  "prepublishOnly": "bun run build",
@@ -44,8 +44,11 @@
44
44
  "peerDependencies": {
45
45
  "@supabase/supabase-js": "^2.115.0"
46
46
  },
47
+ "dependencies": {
48
+ "@supacloud/contracts": "0.3.1"
49
+ },
47
50
  "devDependencies": {
48
- "@types/bun": "^1.4.0",
51
+ "@types/bun": "^1.4.2",
49
52
  "@supabase/supabase-js": "^2.115.0",
50
53
  "typescript": "^7.0.2"
51
54
  }