@supacloud/js 0.37.0 → 0.39.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/PROCEDURES.md ADDED
@@ -0,0 +1,100 @@
1
+ # Generated Procedure Facade
2
+
3
+ The root `@supacloud/js` entrypoint provides a framework-neutral facade for
4
+ compiler-generated application clients:
5
+
6
+ ```ts
7
+ import { createSupaCloudProcedureClient } from "@supacloud/js";
8
+ import { createApiClient } from "./generated/client";
9
+
10
+ const api = createSupaCloudProcedureClient({
11
+ supabase,
12
+ functionName: "app-api",
13
+ generated: createApiClient,
14
+ });
15
+
16
+ await api.cases.detail.query({ params: { id: "case-1" } });
17
+ await api.cases.accept.mutate(
18
+ { params: { id: "case-1" } },
19
+ { idempotencyKey: "case-1-accept-v1" },
20
+ );
21
+ ```
22
+
23
+ The facade creates no session, token store or second auth implementation.
24
+ `supabase-js` remains responsible for authentication, refresh, Functions,
25
+ Database, Storage and Realtime. The existing generated client transport and
26
+ callable route methods remain compatible, so migration can be incremental.
27
+
28
+ ## Migration
29
+
30
+ Upgrade the compiler and SDK together and regenerate the application `client.ts`.
31
+ Existing `createApiClient({ fetch: createSupaCloudApiFetch(...) })` initialization
32
+ remains supported and retains the original error classes. Switch initialization
33
+ to the facade when ready; successful values, route decoder overloads and
34
+ `.query/.mutate` argument types are unchanged. Existing `api.cases.detail(input)`
35
+ calls also work through the facade. The facade normalizes failures from routes,
36
+ procedures and `api.request`; `buildRouteUrl` stays synchronous.
37
+
38
+ Facade `.mutate` calls with required idempotency must supply an execution key.
39
+ Direct generated procedures may still satisfy the legacy runtime check with an
40
+ explicit `idempotency-key` request header. Legacy callable routes retain their old
41
+ header and argument conventions. Extra generated-client settings can still be applied with
42
+ `generated: config => createApiClient({ ...config, normalize: false })`.
43
+ Do not override `config.fetch` or introduce retrying interceptors in that factory.
44
+
45
+ The same procedures work with the optional
46
+ [`@supacloud/js/query`](./QUERY.md) adapter and ordinary Svelte/React Query bindings.
47
+ The facade does not create a cache or import a framework runtime.
48
+
49
+ ## Errors
50
+
51
+ `SupaCloudProcedureError` exposes:
52
+
53
+ - `code`: generated API or SupaCloud transport classification
54
+ - `status`: HTTP status, or `null` when no response was received
55
+ - `requestId`: bounded `x-request-id` (or the JSON body's `requestId`), or `null`
56
+ - `details`: the full JSON error body when available, including any domain `code`
57
+ - `response`: the original HTTP `Response` when available
58
+ - `cause`: the original Supabase `FunctionsHttpError`, fetch error or client error
59
+
60
+ ```ts
61
+ import { FunctionsHttpError } from "@supabase/supabase-js";
62
+ import { SupaCloudProcedureError } from "@supacloud/js";
63
+
64
+ try {
65
+ await api.cases.detail.query({ params: { id: "case-1" } });
66
+ } catch (error) {
67
+ if (!(error instanceof SupaCloudProcedureError)) throw error;
68
+ console.error(error.code, error.status, error.requestId);
69
+ if (error.cause instanceof FunctionsHttpError) {
70
+ // Identical to error.response; its body has not been consumed by the facade.
71
+ const body: unknown = await error.cause.context.json();
72
+ }
73
+ }
74
+ ```
75
+
76
+ HTTP failures use `API_HTTP_ERROR`; JSON/schema failures use
77
+ `API_RESPONSE_INVALID` and undeclared success statuses use
78
+ `API_RESPONSE_UNDECLARED`. Network and relay failures use
79
+ `SUPACLOUD_TRANSPORT_ERROR` and `SUPACLOUD_FUNCTIONS_ERROR`; other client failures
80
+ use `SUPACLOUD_CLIENT_ERROR`. Invalid idempotency uses `SUPACLOUD_EXECUTION_ERROR`.
81
+ Native `AbortError` cancellation remains unchanged.
82
+
83
+ Error-body inspection reads only a clone of JSON failures, at most 64 KiB and
84
+ 250 ms. Non-JSON, oversized, malformed or stalled bodies leave `details`
85
+ undefined without hiding the HTTP failure. Treat details as untrusted data.
86
+ `details`, `response` and `cause` are excluded from JSON serialization.
87
+ Successful response bodies may already be consumed when schema validation fails;
88
+ their status and headers remain available. If Supabase fails before returning a
89
+ response (including malformed success JSON), the original error is kept as
90
+ `cause`, but no HTTP status is fabricated.
91
+
92
+ ## Mutation Safety
93
+
94
+ Mutations are never retried by this facade. Commands that declare required
95
+ idempotency reject before dispatch unless an invocation supplies a valid
96
+ `idempotencyKey`. Declared non-2xx response schemas retain the generated
97
+ client's typed-value behavior instead of being reclassified as exceptions.
98
+ Reuse the key only for the same logical operation. A failed or cancelled request
99
+ does not prove that a write rolled back; resolve uncertain outcomes before retrying.
100
+ The facade does not implement server-side idempotency or durable command receipts.
package/QUERY.md ADDED
@@ -0,0 +1,173 @@
1
+ # TanStack Query Adapter
2
+
3
+ `@supacloud/js/query` adds framework-neutral options for compiler-generated
4
+ `.query` and `.mutate` procedures. Use the host's existing TanStack binding and
5
+ QueryClient; this entrypoint creates neither a cache nor an authentication store.
6
+ No Svelte-specific SDK entrypoint is needed.
7
+
8
+ ## Installation And Migration
9
+
10
+ ```sh
11
+ npm install @supacloud/js @supabase/supabase-js @tanstack/query-core
12
+ # Svelte applications also use their normal framework binding:
13
+ npm install @tanstack/svelte-query svelte
14
+ ```
15
+
16
+ The adapter targets Query Core `^5.104.1`; the integration tests use Svelte Query
17
+ `6.3.1`. Query Core is an optional peer. The root SDK does not import this adapter,
18
+ and the adapter has no runtime dependency on Supabase, Svelte or Query Core.
19
+
20
+ Regenerate `client.ts` with a compiler that emits `__supacloudProcedure` metadata.
21
+ Earlier generated clients remain usable directly, but cannot use these options
22
+ until regenerated. Existing route calls, response validation, interceptors,
23
+ `.query()` and `.mutate()` argument conventions are unchanged.
24
+
25
+ ```ts
26
+ import { createSupaCloudProcedureClient } from "@supacloud/js";
27
+ import { createSupaCloudQueryAdapter } from "@supacloud/js/query";
28
+ import { createApiClient } from "./generated/client";
29
+
30
+ // Reuse the application's existing user-scoped Supabase client.
31
+ const api = createSupaCloudProcedureClient({
32
+ supabase,
33
+ functionName: "app-api",
34
+ generated: createApiClient,
35
+ });
36
+ const queries = createSupaCloudQueryAdapter({
37
+ keyPrefix: [projectUrl, "app-api", tenantId, actorId],
38
+ });
39
+ ```
40
+
41
+ The Supabase client still owns session storage, refresh, auth headers, Database,
42
+ Storage, Realtime and Functions. No second token store or fetch/auth protocol is
43
+ introduced. This adapter works with other generated-client transports as well.
44
+ See [Procedure Facade](./PROCEDURES.md) for incremental migration and unified
45
+ errors. `createApiClient({ fetch: createSupaCloudApiFetch(...) })` remains supported.
46
+
47
+ ## Query Options
48
+
49
+ ```ts
50
+ const input = { params: { id: "item-1" } };
51
+ const options = queries.queryOptions(api.items.detail.query, input, {
52
+ staleTime: 30_000,
53
+ });
54
+
55
+ // Works with QueryClient and the host's framework query hook.
56
+ const item = await queryClient.fetchQuery(options);
57
+ const cached = queryClient.getQueryData(options.queryKey);
58
+
59
+ // One exact input, or every input for this procedure in the same identity scope.
60
+ await queryClient.invalidateQueries({ queryKey: queries.queryKey(api.items.detail.query, input), exact: true });
61
+ await queryClient.invalidateQueries({ queryKey: queries.queryKey(api.items.detail.query) });
62
+ ```
63
+
64
+ Keys include the explicit namespace, query/mutation kind, HTTP method, route
65
+ template, and query input. Query inputs are immutable JSON snapshots: mutating an
66
+ input after building options cannot change the request under an old key. Cycles,
67
+ binary objects, functions and non-finite numbers are rejected for cached queries.
68
+ Pass `undefined` for a query with no required input. `select`, `enabled`, staleness
69
+ and other observer options remain TanStack options. Keys and request functions
70
+ are adapter-owned.
71
+
72
+ Query cancellation forwards TanStack's signal into the generated client.
73
+ No-content query results are normalized from `undefined` to `null`, because
74
+ TanStack cannot cache `undefined`; direct procedure and mutation results remain
75
+ unchanged. With the facade, HTTP/validation failures use `SupaCloudProcedureError`;
76
+ direct generated clients retain their original error classes.
77
+ Schema-declared non-2xx responses retain the generated client's typed-data
78
+ semantics; this adapter does not reclassify them as exceptions.
79
+
80
+ The namespace is mandatory and must include all non-secret identities that
81
+ affect authorization and the target application/function. Recreate the adapter
82
+ on project, tenant or actor changes. Cancel/remove old scoped queries on logout;
83
+ do not preserve previous data across authorization boundaries. Use one QueryClient
84
+ per SSR request. Do not put tokens or session cookies in keys, request input,
85
+ metadata or persisted caches; use the existing Supabase session for auth.
86
+
87
+ ## Svelte
88
+
89
+ Call the normal Svelte Query hooks inside a component under its existing
90
+ `QueryClientProvider`. Build options in their reactive accessors:
91
+
92
+ ```svelte
93
+ <script lang="ts">
94
+ import { createQuery, createMutation, useQueryClient } from "@tanstack/svelte-query";
95
+ import { createSupaCloudQueryAdapter } from "@supacloud/js/query";
96
+ import { createSvelteCommandScope } from "@supacloud/app-svelte";
97
+ import { toStore } from "svelte/store";
98
+ import { api } from "./api";
99
+
100
+ let { projectUrl, tenantId, actorId, itemId } = $props<{
101
+ projectUrl: string; tenantId: string; actorId: string; itemId: string;
102
+ }>();
103
+ const queryClient = useQueryClient();
104
+ const queries = $derived(createSupaCloudQueryAdapter({
105
+ keyPrefix: [projectUrl, "app-api", tenantId, actorId],
106
+ }));
107
+ const scope = createSvelteCommandScope({
108
+ target: toStore(() => JSON.stringify([projectUrl, tenantId, actorId, itemId])),
109
+ });
110
+
111
+ const detail = createQuery(() => queries.queryOptions(
112
+ api.items.detail.query, { params: { id: itemId } },
113
+ ));
114
+ const save = createMutation(() => queries.mutationOptions(api.items.save.mutate));
115
+
116
+ async function submit(name: string, operationId: string) {
117
+ const capturedQueries = queries;
118
+ const input = { params: { id: itemId }, body: { name } };
119
+ const attempt = scope.begin(operationId);
120
+ try {
121
+ await save.mutateAsync({
122
+ input,
123
+ execution: { idempotencyKey: operationId, signal: attempt.signal },
124
+ });
125
+ if (attempt.isCurrent()) {
126
+ await queryClient.invalidateQueries({
127
+ queryKey: capturedQueries.queryKey(api.items.detail.query, { params: input.params }),
128
+ });
129
+ }
130
+ } catch (error) {
131
+ if (attempt.isCurrent()) throw error;
132
+ }
133
+ }
134
+ </script>
135
+ ```
136
+
137
+ `detail.data`, `detail.isPending`, `detail.error` and `save.mutateAsync` are typed
138
+ by the generated schemas. React and other bindings consume the same ordinary
139
+ options through their own query/mutation hooks; no framework runtime is imported
140
+ by this adapter. The focused tests cover Query Core runtime behavior and Svelte
141
+ type integration, not a browser-rendered application.
142
+
143
+ ## Mutation Safety
144
+
145
+ Each invocation supplies `{ input, execution }`. A required command idempotency
146
+ key is required both by TypeScript and at runtime. It belongs to the logical
147
+ operation, not to the component or mutation-options factory. Reuse it only when
148
+ reconciling/retrying the same operation, never for a different write.
149
+ The facade validates execution keys; direct generated procedures retain their
150
+ legacy header checks. With the facade, invalid mutation
151
+ execution settings reject with `SupaCloudProcedureError` and
152
+ `SUPACLOUD_EXECUTION_ERROR` before dispatch; direct generated clients retain their
153
+ original validation errors.
154
+
155
+ Mutations set `retry: false`, including when QueryClient defaults enable retry.
156
+ An unknown outcome is not permission to retry; first resolve the server outcome.
157
+ If the procedure has no required input or execution settings, use
158
+ `mutation.mutateAsync({})`. Mutation inputs are passed through, including binary
159
+ or multipart bodies supported by the generated client.
160
+
161
+ Capture `scope.begin(operationId).signal` when the user starts an operation and
162
+ pass it in `execution`. The existing `@supacloud/app-svelte` scope invalidates it
163
+ on target/navigation changes and destruction. An already-aborted signal prevents
164
+ dispatch; aborting in-flight work rejects waiting and ignores late completion.
165
+ This never proves a server write rolled back and never releases persistent locks.
166
+ Use `attempt.isCurrent()`/`attempt.commit()` for component effects and guard custom
167
+ error/settled callbacks, including callbacks already running at cancellation time.
168
+ TanStack's native mutation `scope` still means serial scheduling, not component
169
+ lifetime.
170
+
171
+ This first adapter does not add batching, subscriptions, infinite-query builders,
172
+ automatic mutation-to-query dependency inference or a new durable-command engine.
173
+ Invalidation and optimistic updates remain explicit TanStack behavior.
package/README.md CHANGED
@@ -60,6 +60,31 @@ peer range compatible with a newer SDK.
60
60
 
61
61
  ## Quick Start
62
62
 
63
+ Use [`createSupaCloudProcedureClient`](./PROCEDURES.md) to initialize a generated
64
+ application client with the existing Supabase session:
65
+
66
+ ```ts
67
+ import { createSupaCloudProcedureClient } from "@supacloud/js";
68
+ import { createApiClient } from "./generated/client";
69
+
70
+ const api = createSupaCloudProcedureClient({
71
+ supabase,
72
+ functionName: "app-api",
73
+ generated: createApiClient,
74
+ });
75
+
76
+ const detail = await api.cases.detail.query({ params: { id: "case-1" } });
77
+ ```
78
+
79
+ The facade preserves route overloads and adds `SupaCloudProcedureError`, original
80
+ Functions errors, and HTTP metadata. It does not replace Supabase JS or retry writes.
81
+
82
+ For compiler-generated application procedures, the optional
83
+ [`@supacloud/js/query`](./QUERY.md) entrypoint provides typed TanStack Query options,
84
+ identity-scoped cache keys, cancellation and per-invocation mutation idempotency.
85
+ Use the existing Svelte/React Query binding and Supabase session; no additional
86
+ framework-specific SupaCloud query package is required.
87
+
63
88
  ```ts
64
89
  import { createClient } from "@supabase/supabase-js";
65
90
  import { createSupaCloudClient, createSupaCloudTaskFetch } from "@supacloud/js";
@@ -6,6 +6,8 @@ export interface SupaCloudApiFetchOptions<TClient extends SupabaseClient = Supab
6
6
  /** The deployed Edge Function name that hosts the generated application routes. */
7
7
  functionName: string;
8
8
  }
9
+ /** Returns the original Supabase Functions error associated with a response. */
10
+ export declare function getSupaCloudApiFetchError(response: Response): unknown | undefined;
9
11
  /**
10
12
  * Adapts the generated application client to the official Supabase Function
11
13
  * transport without creating a second auth/session implementation.
@@ -6,6 +6,8 @@ export interface SupaCloudApiFetchOptions<TClient extends SupabaseClient = Supab
6
6
  /** The deployed Edge Function name that hosts the generated application routes. */
7
7
  functionName: string;
8
8
  }
9
+ /** Returns the original Supabase Functions error associated with a response. */
10
+ export declare function getSupaCloudApiFetchError(response: Response): unknown | undefined;
9
11
  /**
10
12
  * Adapts the generated application client to the official Supabase Function
11
13
  * transport without creating a second auth/session implementation.
package/dist/index.cjs CHANGED
@@ -51,6 +51,7 @@ __export(exports_src, {
51
51
  SupaCloudOAuthClientsClient: () => SupaCloudOAuthClientsClient,
52
52
  SupaCloudOAuthServerClient: () => SupaCloudOAuthServerClient,
53
53
  SupaCloudOAuthServerError: () => SupaCloudOAuthServerError,
54
+ SupaCloudProcedureError: () => SupaCloudProcedureError,
54
55
  SupaCloudQueueError: () => SupaCloudQueueError,
55
56
  SupaCloudTaskAuthenticationError: () => SupaCloudTaskAuthenticationError,
56
57
  SupaCloudTaskDecodeError: () => SupaCloudTaskDecoderError,
@@ -73,6 +74,7 @@ __export(exports_src, {
73
74
  createSupaCloudClient: () => createSupaCloudClient,
74
75
  createSupaCloudCommandFetch: () => createSupaCloudCommandFetch,
75
76
  createSupaCloudOAuthFetch: () => createSupaCloudOAuthFetch,
77
+ createSupaCloudProcedureClient: () => createSupaCloudProcedureClient,
76
78
  createSupaCloudTaskFetch: () => createSupaCloudTaskFetch,
77
79
  createSupaCloudWorkflowFetch: () => createSupaCloudWorkflowFetch
78
80
  });
@@ -2489,6 +2491,10 @@ function createSupaCloudArtifactFetch(options = {}) {
2489
2491
  return createBoundedRpcFetch(artifactPath2, () => new Error("Artifact HTTP response could not be validated"), options.fetch);
2490
2492
  }
2491
2493
  // src/api-fetch.ts
2494
+ var invocationErrors = new WeakMap;
2495
+ function getSupaCloudApiFetchError(response) {
2496
+ return invocationErrors.get(response);
2497
+ }
2492
2498
  function isRecord4(value) {
2493
2499
  return value !== null && typeof value === "object" && !Array.isArray(value);
2494
2500
  }
@@ -2569,6 +2575,7 @@ function createSupaCloudApiFetch(options) {
2569
2575
  delete headers[key];
2570
2576
  }
2571
2577
  }
2578
+ request.signal.throwIfAborted();
2572
2579
  const invocation = await invoke(`${functionName}${url.pathname}${url.search}`, {
2573
2580
  ...body === undefined ? {} : { body },
2574
2581
  ...Object.keys(headers).length === 0 ? {} : { headers },
@@ -2576,8 +2583,10 @@ function createSupaCloudApiFetch(options) {
2576
2583
  signal: request.signal
2577
2584
  });
2578
2585
  if (invocation.error !== null && invocation.error !== undefined) {
2579
- if (invocation.response instanceof Response)
2586
+ if (invocation.response instanceof Response) {
2587
+ invocationErrors.set(invocation.response, invocation.error);
2580
2588
  return invocation.response;
2589
+ }
2581
2590
  if (invocation.error instanceof Error)
2582
2591
  throw invocation.error;
2583
2592
  throw new Error(errorMessage(invocation.error));
@@ -2585,6 +2594,187 @@ function createSupaCloudApiFetch(options) {
2585
2594
  return responseFromData(invocation.data, invocation.response instanceof Response ? invocation.response : undefined);
2586
2595
  };
2587
2596
  }
2597
+ // src/procedure-error.ts
2598
+ function procedureErrorIdentifier(value) {
2599
+ return typeof value === "string" && /^[A-Za-z0-9._:-]{1,256}$/.test(value) ? value : undefined;
2600
+ }
2601
+
2602
+ class SupaCloudProcedureError extends Error {
2603
+ code;
2604
+ status;
2605
+ requestId;
2606
+ details;
2607
+ response;
2608
+ cause;
2609
+ constructor(message, options) {
2610
+ super(message, { cause: options.cause });
2611
+ this.name = "SupaCloudProcedureError";
2612
+ this.code = options.code;
2613
+ this.status = options.status ?? null;
2614
+ this.requestId = procedureErrorIdentifier(options.requestId) ?? null;
2615
+ this.details = options.details;
2616
+ this.response = options.response;
2617
+ this.cause = options.cause;
2618
+ Object.defineProperty(this, "response", { enumerable: false });
2619
+ Object.defineProperty(this, "cause", { enumerable: false });
2620
+ Object.defineProperty(this, "details", { enumerable: false });
2621
+ }
2622
+ }
2623
+
2624
+ // src/procedure-client.ts
2625
+ function isRecord5(value) {
2626
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2627
+ }
2628
+ function asGeneratedError(value) {
2629
+ if (!isRecord5(value))
2630
+ return;
2631
+ if (value.name !== "ApiClientError" || typeof value.code !== "string" || typeof value.status !== "number")
2632
+ return;
2633
+ return { code: value.code, status: value.status, requestId: value.requestId, response: value.response };
2634
+ }
2635
+ async function readErrorBody(response) {
2636
+ if (response === undefined || response.ok || response.bodyUsed || !response.body)
2637
+ return;
2638
+ const type = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
2639
+ if (type !== "application/json" && !type?.endsWith("+json"))
2640
+ return;
2641
+ const maxBytes = 64 * 1024;
2642
+ const length = response.headers.get("content-length");
2643
+ if (length !== null && (!/^\d+$/.test(length) || Number(length) > maxBytes))
2644
+ return;
2645
+ let reader;
2646
+ let timer;
2647
+ let finished = false;
2648
+ try {
2649
+ reader = response.clone().body?.getReader();
2650
+ if (!reader)
2651
+ return;
2652
+ const current = reader;
2653
+ const read = async () => {
2654
+ const decoder = new TextDecoder("utf-8", { fatal: true });
2655
+ let bytes = 0;
2656
+ let text = "";
2657
+ while (!finished) {
2658
+ const chunk = await current.read();
2659
+ if (finished)
2660
+ return;
2661
+ if (chunk.done) {
2662
+ const body = JSON.parse(text + decoder.decode());
2663
+ return isRecord5(body) ? body : undefined;
2664
+ }
2665
+ bytes += chunk.value.byteLength;
2666
+ if (bytes > maxBytes)
2667
+ return;
2668
+ text += decoder.decode(chunk.value, { stream: true });
2669
+ }
2670
+ return;
2671
+ };
2672
+ return await Promise.race([
2673
+ read(),
2674
+ new Promise((resolve) => {
2675
+ timer = setTimeout(() => resolve(undefined), 250);
2676
+ })
2677
+ ]);
2678
+ } catch {
2679
+ return;
2680
+ } finally {
2681
+ finished = true;
2682
+ clearTimeout(timer);
2683
+ reader?.cancel().catch(() => {});
2684
+ }
2685
+ }
2686
+ function errorName(error) {
2687
+ return isRecord5(error) && typeof error.name === "string" ? error.name : undefined;
2688
+ }
2689
+ async function normalizeProcedureError(error, transport = false) {
2690
+ if (error instanceof SupaCloudProcedureError)
2691
+ return error;
2692
+ if (errorName(error) === "AbortError")
2693
+ return error;
2694
+ if (errorName(error) === "FunctionsFetchError" && isRecord5(error) && errorName(error.context) === "AbortError")
2695
+ return error.context;
2696
+ const generated = asGeneratedError(error);
2697
+ const response = generated?.response instanceof Response ? generated.response : isRecord5(error) && error.context instanceof Response ? error.context : undefined;
2698
+ const original = response === undefined ? undefined : getSupaCloudApiFetchError(response);
2699
+ const cause = original ?? error;
2700
+ const responseBody = await readErrorBody(response);
2701
+ const name = errorName(cause);
2702
+ const message = error instanceof Error ? error.message : "SupaCloud procedure failed";
2703
+ const fallback = name === "FunctionsFetchError" ? "SUPACLOUD_TRANSPORT_ERROR" : name === "FunctionsRelayError" ? "SUPACLOUD_FUNCTIONS_ERROR" : name === "FunctionsHttpError" ? "API_HTTP_ERROR" : error instanceof SyntaxError ? "API_RESPONSE_INVALID" : transport ? "SUPACLOUD_TRANSPORT_ERROR" : "SUPACLOUD_CLIENT_ERROR";
2704
+ const code = name === "FunctionsRelayError" ? fallback : generated?.code ?? fallback;
2705
+ return new SupaCloudProcedureError(message, {
2706
+ code,
2707
+ status: generated?.status ?? response?.status ?? null,
2708
+ requestId: procedureErrorIdentifier(generated?.requestId) ?? procedureErrorIdentifier(response?.headers.get("x-request-id")) ?? procedureErrorIdentifier(responseBody?.requestId) ?? null,
2709
+ details: responseBody,
2710
+ response,
2711
+ cause
2712
+ });
2713
+ }
2714
+ function validateProcedureExecution(procedure, args) {
2715
+ const metadata = Reflect.get(procedure, "__supacloudProcedure");
2716
+ if (!isRecord5(metadata))
2717
+ return;
2718
+ const [first, second] = args;
2719
+ const execution = second ?? (isRecord5(first) && (Object.hasOwn(first, "idempotencyKey") || Object.hasOwn(first, "signal")) ? first : undefined);
2720
+ const key = isRecord5(execution) ? execution.idempotencyKey : undefined;
2721
+ if (metadata.idempotency === "required" && key === undefined || key !== undefined && (typeof key !== "string" || !/^[A-Za-z0-9._:-]{1,512}$/.test(key))) {
2722
+ throw new SupaCloudProcedureError("This procedure requires a valid idempotencyKey", {
2723
+ code: "SUPACLOUD_EXECUTION_ERROR"
2724
+ });
2725
+ }
2726
+ }
2727
+ function wrapGeneratedClient(client) {
2728
+ const cache = new WeakMap;
2729
+ const wrap = (value, level) => {
2730
+ const cached = cache.get(value);
2731
+ if (cached !== undefined)
2732
+ return cached;
2733
+ const proxy = new Proxy(value, {
2734
+ async apply(current, thisArg, args) {
2735
+ try {
2736
+ validateProcedureExecution(current, args);
2737
+ return await Reflect.apply(current, thisArg, args);
2738
+ } catch (failure) {
2739
+ throw await normalizeProcedureError(failure);
2740
+ }
2741
+ },
2742
+ get(current, key, receiver) {
2743
+ const member = Reflect.get(current, key, receiver);
2744
+ if (!Object.hasOwn(current, key))
2745
+ return member;
2746
+ if (typeof member === "function" && (level === "controller" || level === "client" && key === "request" || level === "call" && (key === "query" || key === "mutate"))) {
2747
+ return wrap(member, "call");
2748
+ }
2749
+ if (level === "client" && isRecord5(member) && Object.getPrototypeOf(member) === Object.prototype) {
2750
+ return wrap(member, "controller");
2751
+ }
2752
+ return member;
2753
+ }
2754
+ });
2755
+ cache.set(value, proxy);
2756
+ return proxy;
2757
+ };
2758
+ return wrap(client, "client");
2759
+ }
2760
+ function createSupaCloudProcedureClient(options) {
2761
+ const transport = createSupaCloudApiFetch({
2762
+ supabase: options.supabase,
2763
+ functionName: options.functionName
2764
+ });
2765
+ const fetch2 = async (input, init) => {
2766
+ try {
2767
+ const response = await transport(input, init);
2768
+ const error = getSupaCloudApiFetchError(response);
2769
+ if (error !== undefined && (response.ok || errorName(error) === "FunctionsRelayError"))
2770
+ throw error;
2771
+ return response;
2772
+ } catch (error) {
2773
+ throw await normalizeProcedureError(error, true);
2774
+ }
2775
+ };
2776
+ return wrapGeneratedClient(options.generated({ fetch: fetch2 }));
2777
+ }
2588
2778
 
2589
2779
  // src/index.ts
2590
2780
  class SupaCloudTaskSubmitError extends Error {
package/dist/index.d.cts CHANGED
@@ -16,7 +16,8 @@ export * from "./workflows.cjs";
16
16
  export { createSupaCloudWorkflowFetch, type SupaCloudWorkflowFetchOptions } from "./workflow-fetch.cjs";
17
17
  export { createSupaCloudCommandFetch, type SupaCloudCommandFetchOptions } from "./command-fetch.cjs";
18
18
  export { createSupaCloudArtifactFetch, type SupaCloudArtifactFetchOptions } from "./artifact-fetch.cjs";
19
- export { createSupaCloudApiFetch, type SupaCloudApiFetchOptions } from "./api-fetch.cjs";
19
+ export { createSupaCloudApiFetch, type SupaCloudApiFetchOptions, } from "./api-fetch.cjs";
20
+ export { createSupaCloudProcedureClient, SupaCloudProcedureError, type SupaCloudGeneratedClientConfig, type SupaCloudGeneratedClientFactory, type SupaCloudProcedureClient, type SupaCloudProcedureClientOptions, type SupaCloudProcedureErrorCode, type SupaCloudProcedureErrorOptions, } from "./procedure-client.cjs";
20
21
  export * from "./commands.cjs";
21
22
  export * from "./artifacts.cjs";
22
23
  export type SupaCloudTaskStatus = "pending" | "leased" | "running" | "retry_scheduled" | "succeeded" | "failed" | "dead_lettered" | "cancelled" | "queued" | "processing" | "completed";
package/dist/index.d.mts CHANGED
@@ -16,7 +16,8 @@ export * from "./workflows.mjs";
16
16
  export { createSupaCloudWorkflowFetch, type SupaCloudWorkflowFetchOptions } from "./workflow-fetch.mjs";
17
17
  export { createSupaCloudCommandFetch, type SupaCloudCommandFetchOptions } from "./command-fetch.mjs";
18
18
  export { createSupaCloudArtifactFetch, type SupaCloudArtifactFetchOptions } from "./artifact-fetch.mjs";
19
- export { createSupaCloudApiFetch, type SupaCloudApiFetchOptions } from "./api-fetch.mjs";
19
+ export { createSupaCloudApiFetch, type SupaCloudApiFetchOptions, } from "./api-fetch.mjs";
20
+ export { createSupaCloudProcedureClient, SupaCloudProcedureError, type SupaCloudGeneratedClientConfig, type SupaCloudGeneratedClientFactory, type SupaCloudProcedureClient, type SupaCloudProcedureClientOptions, type SupaCloudProcedureErrorCode, type SupaCloudProcedureErrorOptions, } from "./procedure-client.mjs";
20
21
  export * from "./commands.mjs";
21
22
  export * from "./artifacts.mjs";
22
23
  export type SupaCloudTaskStatus = "pending" | "leased" | "running" | "retry_scheduled" | "succeeded" | "failed" | "dead_lettered" | "cancelled" | "queued" | "processing" | "completed";