@supacloud/js 0.39.1 → 0.41.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/dist/index.cjs CHANGED
@@ -69,6 +69,9 @@ __export(exports_src, {
69
69
  SupaCloudWorkflowRetryError: () => SupaCloudWorkflowRetryError,
70
70
  SupaCloudWorkflowStartError: () => SupaCloudWorkflowStartError,
71
71
  SupaCloudWorkflowsClient: () => SupaCloudWorkflowsClient,
72
+ createProcedureClient: () => createProcedureClient,
73
+ createQueryAdapter: () => createQueryAdapter,
74
+ createQueryKey: () => createQueryKey,
72
75
  createSupaCloudApiFetch: () => createSupaCloudApiFetch,
73
76
  createSupaCloudArtifactFetch: () => createSupaCloudArtifactFetch,
74
77
  createSupaCloudClient: () => createSupaCloudClient,
@@ -77,6 +80,7 @@ __export(exports_src, {
77
80
  createSupaCloudProcedureClient: () => createSupaCloudProcedureClient,
78
81
  createSupaCloudTaskFetch: () => createSupaCloudTaskFetch,
79
82
  createSupaCloudWorkflowFetch: () => createSupaCloudWorkflowFetch,
83
+ invalidateByTags: () => invalidateByTags,
80
84
  isSupaCloudProcedureError: () => isSupaCloudProcedureError,
81
85
  isSupaCloudProcedureErrorCode: () => isSupaCloudProcedureErrorCode,
82
86
  isSupaCloudProcedureHttpError: () => isSupaCloudProcedureHttpError,
@@ -2392,6 +2396,142 @@ class SupaCloudOAuthServerClient {
2392
2396
  });
2393
2397
  }
2394
2398
  }
2399
+
2400
+ // node_modules/@supacloud/query/dist/index.js
2401
+ async function invalidateByTags(queryClient, tags, keyPrefix) {
2402
+ const targetTags = Array.isArray(tags) ? tags : [tags];
2403
+ if (targetTags.length === 0)
2404
+ return;
2405
+ await queryClient.invalidateQueries({
2406
+ ...keyPrefix ? { queryKey: keyPrefix } : {},
2407
+ predicate: (query) => {
2408
+ const queryTags = query.meta?.tags;
2409
+ if (!Array.isArray(queryTags))
2410
+ return false;
2411
+ return targetTags.some((tag) => queryTags.includes(tag));
2412
+ }
2413
+ });
2414
+ }
2415
+ function snapshot(value, ancestors = new Set) {
2416
+ if (value === null || value === undefined || typeof value === "string" || typeof value === "boolean")
2417
+ return value;
2418
+ if (typeof value === "number" && Number.isFinite(value))
2419
+ return value;
2420
+ if (typeof value !== "object" || ancestors.has(value))
2421
+ throw new TypeError("Input must be acyclic JSON data");
2422
+ const prototype = Object.getPrototypeOf(value);
2423
+ if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null)
2424
+ throw new TypeError("Input must be JSON data");
2425
+ ancestors.add(value);
2426
+ try {
2427
+ if (Array.isArray(value))
2428
+ return Object.freeze(value.map((item) => snapshot(item, ancestors) ?? null));
2429
+ return Object.freeze(Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, snapshot(item, ancestors)])));
2430
+ } finally {
2431
+ ancestors.delete(value);
2432
+ }
2433
+ }
2434
+ function identityPrefix(prefix) {
2435
+ if (!Array.isArray(prefix) || prefix.length === 0 || prefix.some((part) => typeof part !== "string" || !part.trim())) {
2436
+ throw new TypeError("keyPrefix must contain nonempty identity values");
2437
+ }
2438
+ return Object.freeze(["supacloud", ...prefix]);
2439
+ }
2440
+ function createQueryKey(operationId, input, keyPrefix) {
2441
+ return Object.freeze([...identityPrefix(keyPrefix), operationId, snapshot(input)]);
2442
+ }
2443
+ function createProcedureClient(client) {
2444
+ const candidate = Object.hasOwn(client, "procedureClient") ? client.procedureClient : undefined;
2445
+ return candidate !== undefined ? candidate : client;
2446
+ }
2447
+ function call(procedure, input, execution) {
2448
+ if (!execution || typeof execution !== "object" || Array.isArray(execution))
2449
+ throw new TypeError("Invalid execution options");
2450
+ const { signal, idempotencyKey } = execution;
2451
+ if (signal !== undefined && !(signal instanceof AbortSignal))
2452
+ throw new TypeError("Invalid AbortSignal");
2453
+ if (procedure.__supacloudProcedure.idempotency === "required" && idempotencyKey === undefined || idempotencyKey !== undefined && (typeof idempotencyKey !== "string" || !/^[A-Za-z0-9._:-]{1,512}$/.test(idempotencyKey))) {
2454
+ throw new TypeError("A valid idempotencyKey is required");
2455
+ }
2456
+ const captured = Object.freeze({ ...execution });
2457
+ const invoke = procedure;
2458
+ return new Promise((resolve, reject) => {
2459
+ const abort = () => reject(signal?.reason ?? new DOMException("Procedure cancelled", "AbortError"));
2460
+ if (signal?.aborted) {
2461
+ abort();
2462
+ return;
2463
+ }
2464
+ signal?.addEventListener("abort", abort, { once: true });
2465
+ Promise.resolve().then(() => {
2466
+ signal?.throwIfAborted();
2467
+ return invoke(input, captured);
2468
+ }).then(resolve, reject).finally(() => signal?.removeEventListener("abort", abort));
2469
+ });
2470
+ }
2471
+ function createQueryAdapter(client, options) {
2472
+ const prefix = identityPrefix(options.keyPrefix);
2473
+ const source = createProcedureClient(client);
2474
+ const result = Object.create(null);
2475
+ for (const [controller, handlers] of Object.entries(source)) {
2476
+ if (controller === "invalidateByTags")
2477
+ throw new TypeError("Reserved controller name: invalidateByTags");
2478
+ const mapped = Object.create(null);
2479
+ result[controller] = mapped;
2480
+ for (const [name, member] of Object.entries(handlers)) {
2481
+ const procedure = "query" in member ? member.query : member.mutate;
2482
+ if (procedure === undefined)
2483
+ throw new TypeError("Expected a generated procedure");
2484
+ const metadata = procedure.__supacloudProcedure;
2485
+ if (typeof procedure !== "function" || !metadata || metadata.kind !== ("query" in member ? "query" : "mutation") || typeof metadata.key !== "string" || typeof metadata.method !== "string" || typeof metadata.path !== "string" || !["none", "required"].includes(metadata.idempotency)) {
2486
+ throw new TypeError("Expected a generated procedure");
2487
+ }
2488
+ const key = Object.freeze([...prefix, metadata.kind, metadata.method, metadata.path]);
2489
+ if ("query" in member) {
2490
+ const proc = member.query;
2491
+ mapped[name] = {
2492
+ queryKey: (...args) => args.length ? Object.freeze([...key, snapshot(args[0] ?? {})]) : key,
2493
+ queryOptions: (input, opts) => {
2494
+ const captured = snapshot(input ?? {});
2495
+ return {
2496
+ queryKey: Object.freeze([...key, captured]),
2497
+ queryFn: async ({ signal }) => await call(proc, captured, { signal }) ?? null,
2498
+ meta: { ...opts?.meta, tags: Object.freeze([...opts?.tags ?? []]) }
2499
+ };
2500
+ }
2501
+ };
2502
+ } else {
2503
+ const proc = member.mutate;
2504
+ if (proc === undefined)
2505
+ throw new TypeError("Expected a generated mutation");
2506
+ mapped[name] = {
2507
+ mutationKey: () => key,
2508
+ mutationOptions: (opts) => ({
2509
+ mutationKey: key,
2510
+ retry: false,
2511
+ mutationFn: async (variables) => call(proc, variables.input, variables.execution === undefined ? {} : variables.execution),
2512
+ meta: { ...opts?.meta },
2513
+ onSuccess: async (data, variables, context) => {
2514
+ const target = opts?.queryClient ?? options.queryClient;
2515
+ if (opts?.invalidateTags?.length && target === undefined)
2516
+ throw new Error("No QueryClient provided for invalidation");
2517
+ if (target !== undefined && opts?.invalidateTags?.length)
2518
+ await invalidateByTags(target, opts.invalidateTags, prefix);
2519
+ return opts?.onSuccess?.(data, variables, context);
2520
+ }
2521
+ })
2522
+ };
2523
+ }
2524
+ }
2525
+ }
2526
+ return Object.assign(result, {
2527
+ invalidateByTags: (tags, clientForInvalidation) => {
2528
+ const target = clientForInvalidation ?? options.queryClient;
2529
+ if (target === undefined)
2530
+ throw new Error("No QueryClient provided for invalidateByTags");
2531
+ return invalidateByTags(target, tags, prefix);
2532
+ }
2533
+ });
2534
+ }
2395
2535
  // src/auth-fetch.ts
2396
2536
  function requestMethod(input, init) {
2397
2537
  return (init?.method || (input instanceof Request ? input.method : "GET")).toUpperCase();
@@ -3899,6 +4039,34 @@ class SupaCloudQueueClient extends SupaCloudManagementClient {
3899
4039
  payload: captured
3900
4040
  };
3901
4041
  }
4042
+ async sendIdempotent(payload = {}, jobKey, options = {}) {
4043
+ const captured = queueJsonSnapshot(payload);
4044
+ if (typeof jobKey !== "string" || jobKey.trim() !== jobKey || !/^[A-Za-z0-9_.:@/-]{1,200}$/.test(jobKey)) {
4045
+ throw new SupaCloudQueueError(false, "QUEUE_JOB_KEY_INVALID");
4046
+ }
4047
+ const result = await this.rpc("send_idempotent", {
4048
+ queue_name: this.name,
4049
+ message: captured,
4050
+ p_job_key: jobKey,
4051
+ sleep_seconds: normalizeSecondsFromOptions(options)
4052
+ }, (value) => {
4053
+ if (!Array.isArray(value) || value.length !== 1 || !value[0] || Array.isArray(value[0]) || typeof value[0] !== "object") {
4054
+ throw new SupaCloudQueueError;
4055
+ }
4056
+ const row = value[0];
4057
+ if (typeof row.created !== "boolean")
4058
+ throw new SupaCloudQueueError;
4059
+ return { msgId: queueMessageId(row.msg_id), created: row.created === true };
4060
+ });
4061
+ return {
4062
+ id: result.msgId,
4063
+ msg_id: result.msgId,
4064
+ queue_name: this.name,
4065
+ status: result.created ? "pending" : "deduplicated",
4066
+ payload: captured,
4067
+ deduplicated: !result.created
4068
+ };
4069
+ }
3902
4070
  async sendBatch(messages, options = {}) {
3903
4071
  if (!Array.isArray(messages) || messages.length === 0 || messages.length > 1e4)
3904
4072
  throw new SupaCloudQueueError;
@@ -4029,7 +4197,7 @@ function createSupaCloudClient(options) {
4029
4197
  const workflows2 = new SupaCloudWorkflowsClient(options.supabase);
4030
4198
  const commands2 = new SupaCloudCommandsClient(options.supabase);
4031
4199
  const artifacts2 = new SupaCloudArtifactsClient(options.supabase);
4032
- return {
4200
+ const instance = {
4033
4201
  supabase: options.supabase,
4034
4202
  projectRef: normalized.projectRef,
4035
4203
  managementApiUrl: normalized.managementApiUrl,
@@ -4047,4 +4215,22 @@ function createSupaCloudClient(options) {
4047
4215
  invokeBackground: (functionName, submitOptions) => tasks.submit(functionName, submitOptions)
4048
4216
  }
4049
4217
  };
4218
+ function withClient(apiClient) {
4219
+ return {
4220
+ ...instance,
4221
+ procedures: createProcedureClient(apiClient),
4222
+ queryAdapter: (adapterOptions) => createQueryAdapter(apiClient, adapterOptions),
4223
+ withClient
4224
+ };
4225
+ }
4226
+ return {
4227
+ ...instance,
4228
+ procedures: options.apiClient === undefined ? undefined : createProcedureClient(options.apiClient),
4229
+ queryAdapter: (adapterOptions) => {
4230
+ if (options.apiClient === undefined)
4231
+ throw new Error("No procedure client attached");
4232
+ return createQueryAdapter(options.apiClient, adapterOptions);
4233
+ },
4234
+ withClient
4235
+ };
4050
4236
  }
package/dist/index.d.cts CHANGED
@@ -6,9 +6,11 @@ import { SupaCloudApiError } from "./api-error.cjs";
6
6
  import { type FetchTransport } from "./bounded-rpc-fetch.cjs";
7
7
  import { SupaCloudOAuthClientsClient } from "./oauth-clients.cjs";
8
8
  import { SupaCloudOAuthServerClient } from "./oauth-server.cjs";
9
- import { type SupaCloudQueueJson, type SupaCloudQueueMessage, type SupaCloudQueueSendResult, type SupaCloudQueueMutationResult } from "./queue-rpc.cjs";
9
+ import { type ProcedureSource, type ProceduresOf, type QueryAdapterOptions } from "@supacloud/query";
10
+ export { createProcedureClient, createQueryAdapter, createQueryKey, invalidateByTags, type QueryAdapter, type QueryAdapterOptions, } from "@supacloud/query";
11
+ import { type SupaCloudQueueJson, type SupaCloudQueueMessage, type SupaCloudQueueSendResult, type SupaCloudQueueIdempotentSendResult, type SupaCloudQueueMutationResult } from "./queue-rpc.cjs";
10
12
  export { SupaCloudApiError } from "./api-error.cjs";
11
- export { SupaCloudQueueError, type SupaCloudQueueJson, type SupaCloudQueueMessage, type SupaCloudQueueSendResult, type SupaCloudQueueMutationResult, } from "./queue-rpc.cjs";
13
+ export { SupaCloudQueueError, type SupaCloudQueueJson, type SupaCloudQueueMessage, type SupaCloudQueueSendResult, type SupaCloudQueueIdempotentSendResult, type SupaCloudQueueMutationResult, } from "./queue-rpc.cjs";
12
14
  export * from "./oauth-clients.cjs";
13
15
  export * from "./oauth-server.cjs";
14
16
  export { createSupaCloudOAuthFetch, type SupaCloudOAuthFetchOptions, } from "./auth-fetch.cjs";
@@ -305,6 +307,11 @@ declare class SupaCloudQueueClient<TClient extends SupabaseClient = SupabaseClie
305
307
  private get encodedName();
306
308
  private rpc;
307
309
  send(payload?: SupaCloudQueueJson, options?: SupaCloudQueueSendOptions): Promise<SupaCloudQueueSendResult>;
310
+ /**
311
+ * Additive SupaCloud extension backed by a tenant-local unique job key.
312
+ * The official pgmq_public.send contract remains unchanged.
313
+ */
314
+ sendIdempotent(payload: SupaCloudQueueJson | undefined, jobKey: string, options?: SupaCloudQueueSendOptions): Promise<SupaCloudQueueIdempotentSendResult>;
308
315
  sendBatch(messages: SupaCloudQueueJson[], options?: SupaCloudQueueSendOptions): Promise<SupaCloudQueueSendResult[]>;
309
316
  read(options?: SupaCloudQueueReceiveOptions): Promise<SupaCloudQueueMessage[]>;
310
317
  receive(options?: SupaCloudQueueReceiveOptions): Promise<SupaCloudQueueMessage | null>;
@@ -342,7 +349,9 @@ declare class SupaCloudQueuesClient<TClient extends SupabaseClient = SupabaseCli
342
349
  create(queueName: string, options?: SupaCloudQueueCreateOptions): Promise<SupaCloudQueueInfo>;
343
350
  drop(queueName: string): Promise<void>;
344
351
  }
345
- export declare function createSupaCloudClient<TClient extends SupabaseClient = SupabaseClient>(options: SupaCloudClientOptions<TClient>): {
352
+ export declare function createSupaCloudClient<TClient extends SupabaseClient = SupabaseClient, TApiClient extends ProcedureSource | undefined = undefined>(options: SupaCloudClientOptions<TClient> & {
353
+ apiClient?: TApiClient;
354
+ }): {
346
355
  supabase: TClient;
347
356
  projectRef: string;
348
357
  managementApiUrl: string;
@@ -359,4 +368,27 @@ export declare function createSupaCloudClient<TClient extends SupabaseClient = S
359
368
  functions: {
360
369
  invokeBackground: (functionName: string, submitOptions?: SupaCloudTaskSubmitOptions) => Promise<SupaCloudTaskReceipt<unknown>>;
361
370
  };
371
+ procedures: TApiClient extends ProcedureSource ? ProceduresOf<TApiClient> : undefined;
372
+ queryAdapter: (adapterOptions: QueryAdapterOptions) => import("@supacloud/query").QueryAdapter<TApiClient & {}>;
373
+ withClient: <T extends ProcedureSource>(apiClient: T) => {
374
+ supabase: TClient;
375
+ projectRef: string;
376
+ managementApiUrl: string;
377
+ auth: {
378
+ oauthServer: SupaCloudOAuthServerClient;
379
+ oauthClients: SupaCloudOAuthClientsClient;
380
+ };
381
+ tasks: SupaCloudTasksClient<TClient>;
382
+ workflows: SupaCloudWorkflowsClient<TClient>;
383
+ commands: SupaCloudCommandsClient<TClient>;
384
+ artifacts: SupaCloudArtifactsClient<TClient>;
385
+ queues: SupaCloudQueuesClient<TClient>;
386
+ queue: (name: string) => SupaCloudQueueClient<TClient>;
387
+ functions: {
388
+ invokeBackground: (functionName: string, submitOptions?: SupaCloudTaskSubmitOptions) => Promise<SupaCloudTaskReceipt<unknown>>;
389
+ };
390
+ procedures: ProceduresOf<T>;
391
+ queryAdapter: (adapterOptions: QueryAdapterOptions) => import("@supacloud/query").QueryAdapter<T>;
392
+ withClient: /*elided*/ any;
393
+ };
362
394
  };
package/dist/index.d.mts CHANGED
@@ -6,9 +6,11 @@ import { SupaCloudApiError } from "./api-error.mjs";
6
6
  import { type FetchTransport } from "./bounded-rpc-fetch.mjs";
7
7
  import { SupaCloudOAuthClientsClient } from "./oauth-clients.mjs";
8
8
  import { SupaCloudOAuthServerClient } from "./oauth-server.mjs";
9
- import { type SupaCloudQueueJson, type SupaCloudQueueMessage, type SupaCloudQueueSendResult, type SupaCloudQueueMutationResult } from "./queue-rpc.mjs";
9
+ import { type ProcedureSource, type ProceduresOf, type QueryAdapterOptions } from "@supacloud/query";
10
+ export { createProcedureClient, createQueryAdapter, createQueryKey, invalidateByTags, type QueryAdapter, type QueryAdapterOptions, } from "@supacloud/query";
11
+ import { type SupaCloudQueueJson, type SupaCloudQueueMessage, type SupaCloudQueueSendResult, type SupaCloudQueueIdempotentSendResult, type SupaCloudQueueMutationResult } from "./queue-rpc.mjs";
10
12
  export { SupaCloudApiError } from "./api-error.mjs";
11
- export { SupaCloudQueueError, type SupaCloudQueueJson, type SupaCloudQueueMessage, type SupaCloudQueueSendResult, type SupaCloudQueueMutationResult, } from "./queue-rpc.mjs";
13
+ export { SupaCloudQueueError, type SupaCloudQueueJson, type SupaCloudQueueMessage, type SupaCloudQueueSendResult, type SupaCloudQueueIdempotentSendResult, type SupaCloudQueueMutationResult, } from "./queue-rpc.mjs";
12
14
  export * from "./oauth-clients.mjs";
13
15
  export * from "./oauth-server.mjs";
14
16
  export { createSupaCloudOAuthFetch, type SupaCloudOAuthFetchOptions, } from "./auth-fetch.mjs";
@@ -305,6 +307,11 @@ declare class SupaCloudQueueClient<TClient extends SupabaseClient = SupabaseClie
305
307
  private get encodedName();
306
308
  private rpc;
307
309
  send(payload?: SupaCloudQueueJson, options?: SupaCloudQueueSendOptions): Promise<SupaCloudQueueSendResult>;
310
+ /**
311
+ * Additive SupaCloud extension backed by a tenant-local unique job key.
312
+ * The official pgmq_public.send contract remains unchanged.
313
+ */
314
+ sendIdempotent(payload: SupaCloudQueueJson | undefined, jobKey: string, options?: SupaCloudQueueSendOptions): Promise<SupaCloudQueueIdempotentSendResult>;
308
315
  sendBatch(messages: SupaCloudQueueJson[], options?: SupaCloudQueueSendOptions): Promise<SupaCloudQueueSendResult[]>;
309
316
  read(options?: SupaCloudQueueReceiveOptions): Promise<SupaCloudQueueMessage[]>;
310
317
  receive(options?: SupaCloudQueueReceiveOptions): Promise<SupaCloudQueueMessage | null>;
@@ -342,7 +349,9 @@ declare class SupaCloudQueuesClient<TClient extends SupabaseClient = SupabaseCli
342
349
  create(queueName: string, options?: SupaCloudQueueCreateOptions): Promise<SupaCloudQueueInfo>;
343
350
  drop(queueName: string): Promise<void>;
344
351
  }
345
- export declare function createSupaCloudClient<TClient extends SupabaseClient = SupabaseClient>(options: SupaCloudClientOptions<TClient>): {
352
+ export declare function createSupaCloudClient<TClient extends SupabaseClient = SupabaseClient, TApiClient extends ProcedureSource | undefined = undefined>(options: SupaCloudClientOptions<TClient> & {
353
+ apiClient?: TApiClient;
354
+ }): {
346
355
  supabase: TClient;
347
356
  projectRef: string;
348
357
  managementApiUrl: string;
@@ -359,4 +368,27 @@ export declare function createSupaCloudClient<TClient extends SupabaseClient = S
359
368
  functions: {
360
369
  invokeBackground: (functionName: string, submitOptions?: SupaCloudTaskSubmitOptions) => Promise<SupaCloudTaskReceipt<unknown>>;
361
370
  };
371
+ procedures: TApiClient extends ProcedureSource ? ProceduresOf<TApiClient> : undefined;
372
+ queryAdapter: (adapterOptions: QueryAdapterOptions) => import("@supacloud/query").QueryAdapter<TApiClient & {}>;
373
+ withClient: <T extends ProcedureSource>(apiClient: T) => {
374
+ supabase: TClient;
375
+ projectRef: string;
376
+ managementApiUrl: string;
377
+ auth: {
378
+ oauthServer: SupaCloudOAuthServerClient;
379
+ oauthClients: SupaCloudOAuthClientsClient;
380
+ };
381
+ tasks: SupaCloudTasksClient<TClient>;
382
+ workflows: SupaCloudWorkflowsClient<TClient>;
383
+ commands: SupaCloudCommandsClient<TClient>;
384
+ artifacts: SupaCloudArtifactsClient<TClient>;
385
+ queues: SupaCloudQueuesClient<TClient>;
386
+ queue: (name: string) => SupaCloudQueueClient<TClient>;
387
+ functions: {
388
+ invokeBackground: (functionName: string, submitOptions?: SupaCloudTaskSubmitOptions) => Promise<SupaCloudTaskReceipt<unknown>>;
389
+ };
390
+ procedures: ProceduresOf<T>;
391
+ queryAdapter: (adapterOptions: QueryAdapterOptions) => import("@supacloud/query").QueryAdapter<T>;
392
+ withClient: /*elided*/ any;
393
+ };
362
394
  };
package/dist/index.mjs CHANGED
@@ -2308,6 +2308,142 @@ class SupaCloudOAuthServerClient {
2308
2308
  });
2309
2309
  }
2310
2310
  }
2311
+
2312
+ // node_modules/@supacloud/query/dist/index.js
2313
+ async function invalidateByTags(queryClient, tags, keyPrefix) {
2314
+ const targetTags = Array.isArray(tags) ? tags : [tags];
2315
+ if (targetTags.length === 0)
2316
+ return;
2317
+ await queryClient.invalidateQueries({
2318
+ ...keyPrefix ? { queryKey: keyPrefix } : {},
2319
+ predicate: (query) => {
2320
+ const queryTags = query.meta?.tags;
2321
+ if (!Array.isArray(queryTags))
2322
+ return false;
2323
+ return targetTags.some((tag) => queryTags.includes(tag));
2324
+ }
2325
+ });
2326
+ }
2327
+ function snapshot(value, ancestors = new Set) {
2328
+ if (value === null || value === undefined || typeof value === "string" || typeof value === "boolean")
2329
+ return value;
2330
+ if (typeof value === "number" && Number.isFinite(value))
2331
+ return value;
2332
+ if (typeof value !== "object" || ancestors.has(value))
2333
+ throw new TypeError("Input must be acyclic JSON data");
2334
+ const prototype = Object.getPrototypeOf(value);
2335
+ if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null)
2336
+ throw new TypeError("Input must be JSON data");
2337
+ ancestors.add(value);
2338
+ try {
2339
+ if (Array.isArray(value))
2340
+ return Object.freeze(value.map((item) => snapshot(item, ancestors) ?? null));
2341
+ return Object.freeze(Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => [key, snapshot(item, ancestors)])));
2342
+ } finally {
2343
+ ancestors.delete(value);
2344
+ }
2345
+ }
2346
+ function identityPrefix(prefix) {
2347
+ if (!Array.isArray(prefix) || prefix.length === 0 || prefix.some((part) => typeof part !== "string" || !part.trim())) {
2348
+ throw new TypeError("keyPrefix must contain nonempty identity values");
2349
+ }
2350
+ return Object.freeze(["supacloud", ...prefix]);
2351
+ }
2352
+ function createQueryKey(operationId, input, keyPrefix) {
2353
+ return Object.freeze([...identityPrefix(keyPrefix), operationId, snapshot(input)]);
2354
+ }
2355
+ function createProcedureClient(client) {
2356
+ const candidate = Object.hasOwn(client, "procedureClient") ? client.procedureClient : undefined;
2357
+ return candidate !== undefined ? candidate : client;
2358
+ }
2359
+ function call(procedure, input, execution) {
2360
+ if (!execution || typeof execution !== "object" || Array.isArray(execution))
2361
+ throw new TypeError("Invalid execution options");
2362
+ const { signal, idempotencyKey } = execution;
2363
+ if (signal !== undefined && !(signal instanceof AbortSignal))
2364
+ throw new TypeError("Invalid AbortSignal");
2365
+ if (procedure.__supacloudProcedure.idempotency === "required" && idempotencyKey === undefined || idempotencyKey !== undefined && (typeof idempotencyKey !== "string" || !/^[A-Za-z0-9._:-]{1,512}$/.test(idempotencyKey))) {
2366
+ throw new TypeError("A valid idempotencyKey is required");
2367
+ }
2368
+ const captured = Object.freeze({ ...execution });
2369
+ const invoke = procedure;
2370
+ return new Promise((resolve, reject) => {
2371
+ const abort = () => reject(signal?.reason ?? new DOMException("Procedure cancelled", "AbortError"));
2372
+ if (signal?.aborted) {
2373
+ abort();
2374
+ return;
2375
+ }
2376
+ signal?.addEventListener("abort", abort, { once: true });
2377
+ Promise.resolve().then(() => {
2378
+ signal?.throwIfAborted();
2379
+ return invoke(input, captured);
2380
+ }).then(resolve, reject).finally(() => signal?.removeEventListener("abort", abort));
2381
+ });
2382
+ }
2383
+ function createQueryAdapter(client, options) {
2384
+ const prefix = identityPrefix(options.keyPrefix);
2385
+ const source = createProcedureClient(client);
2386
+ const result = Object.create(null);
2387
+ for (const [controller, handlers] of Object.entries(source)) {
2388
+ if (controller === "invalidateByTags")
2389
+ throw new TypeError("Reserved controller name: invalidateByTags");
2390
+ const mapped = Object.create(null);
2391
+ result[controller] = mapped;
2392
+ for (const [name, member] of Object.entries(handlers)) {
2393
+ const procedure = "query" in member ? member.query : member.mutate;
2394
+ if (procedure === undefined)
2395
+ throw new TypeError("Expected a generated procedure");
2396
+ const metadata = procedure.__supacloudProcedure;
2397
+ if (typeof procedure !== "function" || !metadata || metadata.kind !== ("query" in member ? "query" : "mutation") || typeof metadata.key !== "string" || typeof metadata.method !== "string" || typeof metadata.path !== "string" || !["none", "required"].includes(metadata.idempotency)) {
2398
+ throw new TypeError("Expected a generated procedure");
2399
+ }
2400
+ const key = Object.freeze([...prefix, metadata.kind, metadata.method, metadata.path]);
2401
+ if ("query" in member) {
2402
+ const proc = member.query;
2403
+ mapped[name] = {
2404
+ queryKey: (...args) => args.length ? Object.freeze([...key, snapshot(args[0] ?? {})]) : key,
2405
+ queryOptions: (input, opts) => {
2406
+ const captured = snapshot(input ?? {});
2407
+ return {
2408
+ queryKey: Object.freeze([...key, captured]),
2409
+ queryFn: async ({ signal }) => await call(proc, captured, { signal }) ?? null,
2410
+ meta: { ...opts?.meta, tags: Object.freeze([...opts?.tags ?? []]) }
2411
+ };
2412
+ }
2413
+ };
2414
+ } else {
2415
+ const proc = member.mutate;
2416
+ if (proc === undefined)
2417
+ throw new TypeError("Expected a generated mutation");
2418
+ mapped[name] = {
2419
+ mutationKey: () => key,
2420
+ mutationOptions: (opts) => ({
2421
+ mutationKey: key,
2422
+ retry: false,
2423
+ mutationFn: async (variables) => call(proc, variables.input, variables.execution === undefined ? {} : variables.execution),
2424
+ meta: { ...opts?.meta },
2425
+ onSuccess: async (data, variables, context) => {
2426
+ const target = opts?.queryClient ?? options.queryClient;
2427
+ if (opts?.invalidateTags?.length && target === undefined)
2428
+ throw new Error("No QueryClient provided for invalidation");
2429
+ if (target !== undefined && opts?.invalidateTags?.length)
2430
+ await invalidateByTags(target, opts.invalidateTags, prefix);
2431
+ return opts?.onSuccess?.(data, variables, context);
2432
+ }
2433
+ })
2434
+ };
2435
+ }
2436
+ }
2437
+ }
2438
+ return Object.assign(result, {
2439
+ invalidateByTags: (tags, clientForInvalidation) => {
2440
+ const target = clientForInvalidation ?? options.queryClient;
2441
+ if (target === undefined)
2442
+ throw new Error("No QueryClient provided for invalidateByTags");
2443
+ return invalidateByTags(target, tags, prefix);
2444
+ }
2445
+ });
2446
+ }
2311
2447
  // src/auth-fetch.ts
2312
2448
  function requestMethod(input, init) {
2313
2449
  return (init?.method || (input instanceof Request ? input.method : "GET")).toUpperCase();
@@ -3815,6 +3951,34 @@ class SupaCloudQueueClient extends SupaCloudManagementClient {
3815
3951
  payload: captured
3816
3952
  };
3817
3953
  }
3954
+ async sendIdempotent(payload = {}, jobKey, options = {}) {
3955
+ const captured = queueJsonSnapshot(payload);
3956
+ if (typeof jobKey !== "string" || jobKey.trim() !== jobKey || !/^[A-Za-z0-9_.:@/-]{1,200}$/.test(jobKey)) {
3957
+ throw new SupaCloudQueueError(false, "QUEUE_JOB_KEY_INVALID");
3958
+ }
3959
+ const result = await this.rpc("send_idempotent", {
3960
+ queue_name: this.name,
3961
+ message: captured,
3962
+ p_job_key: jobKey,
3963
+ sleep_seconds: normalizeSecondsFromOptions(options)
3964
+ }, (value) => {
3965
+ if (!Array.isArray(value) || value.length !== 1 || !value[0] || Array.isArray(value[0]) || typeof value[0] !== "object") {
3966
+ throw new SupaCloudQueueError;
3967
+ }
3968
+ const row = value[0];
3969
+ if (typeof row.created !== "boolean")
3970
+ throw new SupaCloudQueueError;
3971
+ return { msgId: queueMessageId(row.msg_id), created: row.created === true };
3972
+ });
3973
+ return {
3974
+ id: result.msgId,
3975
+ msg_id: result.msgId,
3976
+ queue_name: this.name,
3977
+ status: result.created ? "pending" : "deduplicated",
3978
+ payload: captured,
3979
+ deduplicated: !result.created
3980
+ };
3981
+ }
3818
3982
  async sendBatch(messages, options = {}) {
3819
3983
  if (!Array.isArray(messages) || messages.length === 0 || messages.length > 1e4)
3820
3984
  throw new SupaCloudQueueError;
@@ -3945,7 +4109,7 @@ function createSupaCloudClient(options) {
3945
4109
  const workflows2 = new SupaCloudWorkflowsClient(options.supabase);
3946
4110
  const commands2 = new SupaCloudCommandsClient(options.supabase);
3947
4111
  const artifacts2 = new SupaCloudArtifactsClient(options.supabase);
3948
- return {
4112
+ const instance = {
3949
4113
  supabase: options.supabase,
3950
4114
  projectRef: normalized.projectRef,
3951
4115
  managementApiUrl: normalized.managementApiUrl,
@@ -3963,6 +4127,24 @@ function createSupaCloudClient(options) {
3963
4127
  invokeBackground: (functionName, submitOptions) => tasks.submit(functionName, submitOptions)
3964
4128
  }
3965
4129
  };
4130
+ function withClient(apiClient) {
4131
+ return {
4132
+ ...instance,
4133
+ procedures: createProcedureClient(apiClient),
4134
+ queryAdapter: (adapterOptions) => createQueryAdapter(apiClient, adapterOptions),
4135
+ withClient
4136
+ };
4137
+ }
4138
+ return {
4139
+ ...instance,
4140
+ procedures: options.apiClient === undefined ? undefined : createProcedureClient(options.apiClient),
4141
+ queryAdapter: (adapterOptions) => {
4142
+ if (options.apiClient === undefined)
4143
+ throw new Error("No procedure client attached");
4144
+ return createQueryAdapter(options.apiClient, adapterOptions);
4145
+ },
4146
+ withClient
4147
+ };
3966
4148
  }
3967
4149
  export {
3968
4150
  SupaCloudApiError,
@@ -3995,6 +4177,9 @@ export {
3995
4177
  SupaCloudWorkflowRetryError,
3996
4178
  SupaCloudWorkflowStartError,
3997
4179
  SupaCloudWorkflowsClient,
4180
+ createProcedureClient,
4181
+ createQueryAdapter,
4182
+ createQueryKey,
3998
4183
  createSupaCloudApiFetch,
3999
4184
  createSupaCloudArtifactFetch,
4000
4185
  createSupaCloudClient,
@@ -4003,6 +4188,7 @@ export {
4003
4188
  createSupaCloudProcedureClient,
4004
4189
  createSupaCloudTaskFetch,
4005
4190
  createSupaCloudWorkflowFetch,
4191
+ invalidateByTags,
4006
4192
  isSupaCloudProcedureError,
4007
4193
  isSupaCloudProcedureErrorCode,
4008
4194
  isSupaCloudProcedureHttpError,
@@ -21,6 +21,11 @@ export type SupaCloudQueueSendResult = {
21
21
  status: "pending";
22
22
  payload: SupaCloudQueueJson;
23
23
  };
24
+ /** Deduplication confirms the original enqueue, not current pending/execution state. */
25
+ export type SupaCloudQueueIdempotentSendResult = Omit<SupaCloudQueueSendResult, "status"> & {
26
+ status: "pending" | "deduplicated";
27
+ deduplicated: boolean;
28
+ };
24
29
  export type SupaCloudQueueMutationResult = {
25
30
  id: string;
26
31
  msg_id: string;
@@ -21,6 +21,11 @@ export type SupaCloudQueueSendResult = {
21
21
  status: "pending";
22
22
  payload: SupaCloudQueueJson;
23
23
  };
24
+ /** Deduplication confirms the original enqueue, not current pending/execution state. */
25
+ export type SupaCloudQueueIdempotentSendResult = Omit<SupaCloudQueueSendResult, "status"> & {
26
+ status: "pending" | "deduplicated";
27
+ deduplicated: boolean;
28
+ };
24
29
  export type SupaCloudQueueMutationResult = {
25
30
  id: string;
26
31
  msg_id: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@supacloud/js",
3
- "version": "0.39.1",
3
+ "version": "0.41.1",
4
4
  "description": "Platform SDK for SupaCloud, built on top of supabase-js",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -96,7 +96,7 @@
96
96
  "directory": "packages/supacloud-js"
97
97
  },
98
98
  "peerDependencies": {
99
- "@supabase/supabase-js": "^2.115.0",
99
+ "@supabase/supabase-js": "^2.117.3",
100
100
  "@tanstack/query-core": "^5.104.1"
101
101
  },
102
102
  "peerDependenciesMeta": {
@@ -106,11 +106,12 @@
106
106
  },
107
107
  "dependencies": {
108
108
  "@supacloud/contracts": "0.8.0",
109
+ "@supacloud/query": "0.2.0",
109
110
  "rxjs": "7.8.2"
110
111
  },
111
112
  "devDependencies": {
112
113
  "@types/bun": "^1.4.2",
113
- "@supabase/supabase-js": "^2.115.0",
114
+ "@supabase/supabase-js": "^2.117.3",
114
115
  "typescript": "^7.0.2",
115
116
  "@tanstack/query-core": "5.104.1",
116
117
  "@tanstack/svelte-query": "6.3.1",