From f5924c20c6666b5d38c24e19363361e3609e061d Mon Sep 17 00:00:00 2001 From: clover caruso Date: Wed, 11 Nov 2026 10:38:09 -0800 Subject: [PATCH] feat!: make Mutation the class define returns `Mutation` was an interface left over from when two classes implemented it; only `BlockingMutation` remains. The class is now `Mutation` itself and every type position uses it, so `useMutate` and mutation buttons only accept mutations created by `define` (or `bindAsyncCallback`). The class keeps the interface's two type parameters. It no longer carries the client's `Auth` and `Config`: `define` erases the typed options once, where it pairs them with the client whose context runs them, which drops the casts `bindAsyncCallback` needed and the now-unused `MutationClientFromConfig`. The class's private options make `Args` invariant, so mutation buttons infer `Args` from `mutation` alone and `args={[]}` still fits a zero-argument mutation. Also drops the duplicate private client field and comments naming `defineBlocking`, `DebouncedMutation` and `runAndReturn`, and bumps the version to 4.0.0. Assisted-by: claude-opus-5.5 --- jsr.json | 2 +- readme.changes.md | 6 + src/client.ts | 25 +--- src/mod.ts | 11 +- src/mutation.ts | 339 +++++++++++++++++++++++----------------------- src/react.ts | 34 ++--- src/types.ts | 39 +----- 7 files changed, 199 insertions(+), 257 deletions(-) diff --git a/jsr.json b/jsr.json index 1fa797aa97da3152cc2ba78ca7fe36686157153c..3622dccac4771a31c5d0cc2133d4ee137f0c6f48 100644 --- a/jsr.json +++ b/jsr.json @@ -1,6 +1,6 @@ { "name": "@clo/react-mutation", - "version": "3.0.4", + "version": "4.0.0", "exports": { ".": "./src/mod.ts", "./tanstack-query": "./src/tanstack-query.ts", diff --git a/readme.changes.md b/readme.changes.md index 4a1c9d44b766dff6b6cf616f397bca537e058f0f..253067227659c3fa7f738b42ef0d5ab44850bf87 100644 --- a/readme.changes.md +++ b/readme.changes.md @@ -1,5 +1,11 @@ # notable changes in React Mutation +## v4 + +### breaking + +- rewrite the api types to be cleaner. likely does not break most users. + ## v3.0.4 ### bugfixes diff --git a/src/client.ts b/src/client.ts index 46c9bf6fae16475cf89520177366206c7e571681..eb225bc54855f21c0c7c6740385453f161ef0ab0 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1,5 +1,5 @@ -import { BlockingMutation, type MutationOptions } from "./mutation.ts"; -import type { Mutation, MutationAction, Serializable, SerializableValue } from "./types.ts"; +import { Mutation, type MutationOptions } from "./mutation.ts"; +import type { MutationAction, Serializable, SerializableValue } from "./types.ts"; /** * Every element of a fixed argument tuple passes the {@link Serializable} check. @@ -37,13 +37,6 @@ export interface MutationClientConfig { authScopes: string; } -export type MutationClientFromConfig = MutationClient< - Config["context"], - Config["optimisticHelpers"], - Config["userContext"], - Config["authScopes"] ->; - const defaultDeepEquals = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b); // Declared locally to avoid depending on node types. @@ -62,8 +55,8 @@ export interface MutationClientOptions< reportError: (message: string, error: unknown) => void; reportSuccess?: (message: string) => void; /** - * Compare two values for deep equality. Used by DebouncedMutation to determine - * if the optimistic state has changed from the initial snapshot. + * Compare two values for deep equality. Used with a mutation's `snapshot` to + * determine if the optimistic state has changed from the initial snapshot. * @default JSON.stringify based comparison */ deepEquals?: (a: unknown, b: unknown) => boolean; @@ -171,14 +164,10 @@ export class MutationClient< } console.error(`Mutation id "${options.id}" registered twice; assuming hot reload and replacing it.`); } - const mutation = new BlockingMutation< - Args, - Result, - Auth, - { context: Context; optimisticHelpers: OptimisticHelpers; userContext: UserContext; authScopes: AuthScopes } - >( + const mutation = new Mutation( this, - options, + // `Mutation` runs these with this client's context and helpers. + options as MutationOptions, ); this.#mutations.set(options.id, mutation as unknown as Mutation); return mutation; diff --git a/src/mod.ts b/src/mod.ts index 33159dff52687a8c579a405eb8a27eed5ebee34a..53cb5613d8ce48e57b9cd873b21e2758c46c7769 100644 --- a/src/mod.ts +++ b/src/mod.ts @@ -1,11 +1,5 @@ -export { - MutationClient, - type MutationClientConfig, - type MutationClientFromConfig, - type MutationClientOptions, - type Reactive, -} from "./client.ts"; -export type { MutationOptions, OptimisticContext } from "./mutation.ts"; +export { MutationClient, type MutationClientConfig, type MutationClientOptions, type Reactive } from "./client.ts"; +export type { Mutation, MutationOptions, OptimisticContext } from "./mutation.ts"; export { type AsyncCallbackOptions, bindAsyncCallback, @@ -21,7 +15,6 @@ export { } from "./react.ts"; export type { Json, - Mutation, MutationAction, MutationEvent, Serializable, diff --git a/src/mutation.ts b/src/mutation.ts index 1b14c1bd4bcdf0adba6a7d3ff3d1f0593ecca605..cbe0a34eb019aaeecde74f296064fe64c05c58e2 100644 --- a/src/mutation.ts +++ b/src/mutation.ts @@ -1,13 +1,12 @@ import { message as errMessage } from "@clo/lib/error.ts"; -import type { MutationClientFromConfig, Reactive } from "./client.ts"; -import type { MutationClientConfig } from "./client.ts"; -import type { Mutation, MutationEvent, RunOptions, SerializableValue } from "./types.ts"; +import type { MutationClient, MutationClientConfig, Reactive } from "./client.ts"; +import type { MutationEvent, RunOptions, SerializableValue } from "./types.ts"; /** - * Argument to `defineBlocking`. + * Argument to `MutationClient.define`. * @template Args - the parameters to the mutation * @template Result - the result of the API call - * @template Config - global values and helpers from `MutationContext` + * @template Config - global values and helpers from `MutationClient` */ export interface MutationOptions< Args extends unknown[], @@ -119,11 +118,11 @@ export type OptimisticContext< onRefetch: (cb: () => Promise) => void; }; -interface PendingDebouncedState { +interface PendingDebouncedState { /** Arguments from the most recent call */ args: Args; /** Context captured when the most recent call was allowed */ - context: Context; + context: object; /** Restores registered by the most recent call */ rollbacks: Array<() => void>; /** All pending promises from all superseded calls */ @@ -159,20 +158,20 @@ function unwrapMutationError(caught: unknown) { return { error: caught, description: null }; } -interface Channel { +interface Channel { listeners: Set<(update: MutationEvent) => void>; status: "idle" | "waiting" | "mutating" | "refetching" | "skipped"; - queue: Array>; + queue: Array>; // Debounce state (only used if debounce option is set) debounceTimer: ReturnType | null; - pendingDebounced: PendingDebouncedState | null; + pendingDebounced: PendingDebouncedState | null; // Track when last debounced mutation executed (for debounceImmediate) lastDebouncedExecutionTime: number | null; } -interface Item { +interface Item { args: Args; - context: Context; + context: object; rollbacks: Array<() => void>; refetches: Array<() => Promise>; onSuccess: Array<(result: Result) => void>; @@ -180,59 +179,37 @@ interface Item { reject: (error: unknown) => void; } -export class BlockingMutation< - Args extends unknown[], - Result, - Auth extends boolean | string, - Config extends MutationClientConfig, -> implements Mutation { - #options: MutationOptions; - #client: MutationClientFromConfig; - #channels: Map< - string, - Channel> - > = new Map(); - client: MutationClientFromConfig; +/** A mutation defined with `MutationClient.define`. */ +export class Mutation { + readonly client: MutationClient; + #options: MutationOptions; + #channels: Map> = new Map(); constructor( - client: MutationClientFromConfig, - options: MutationOptions, + client: MutationClient, + options: MutationOptions, ) { - this.#options = options; - this.#client = client; this.client = client; + this.#options = options; } + /** Unique identifier passed to `define`. */ get id(): string { return this.#options.id; } - #context(): Context { - return { - ...this.#client.context, - ...(this.#client.userContext?.get() ?? {}), - } as Context; - } - - #reportUnauthenticated(options: RunOptions, args: Args) { - const handler = options.onUnauthenticated ?? this.#client.handleUnauthenticated; - handler?.call( - this.#client, - // Reached only for `auth: true`, whose arguments the define-time guard - // constrains to be serializable. - { id: this.#options.id, description: this.describe(...args), args: args as SerializableValue[] }, - this as unknown as Mutation, - ); - } - + /** + * `true` when an `auth: true` mutation has no user available. Scoped + * mutations are excluded; they disable instead of routing to the sign-in flow. + */ isUnauthenticated(): boolean { - return this.#options.auth === true && this.#client.userContext?.get() == null; + return this.#options.auth === true && this.client.userContext?.get() == null; } isAllowed(): boolean { const { auth } = this.#options; - if (auth !== undefined && auth !== false && this.#client.userContext?.get() == null) return false; - if (typeof auth === "string" && !(this.#client.authScopes?.[auth]?.get() ?? false)) return false; + if (auth !== undefined && auth !== false && this.client.userContext?.get() == null) return false; + if (typeof auth === "string" && !(this.client.authScopes?.[auth]?.get() ?? false)) return false; return this.#options.isAllowed?.get() ?? true; } @@ -240,33 +217,19 @@ export class BlockingMutation< const { auth } = this.#options; const unsubscribes = [ this.#options.isAllowed?.sub(cb), - typeof auth === "string" ? this.#client.authScopes?.[auth]?.sub(cb) : undefined, + typeof auth === "string" ? this.client.authScopes?.[auth]?.sub(cb) : undefined, ]; return () => unsubscribes.forEach((unsubscribe) => unsubscribe?.()); } - key(args: Args) { + /** Returns the concurrency key used for a given set of arguments */ + key(args: Args): string { const k = this.#options.key?.({ ...this.#context(), args }) ?? "shared"; return JSON.stringify(k); } - #getOrPutChannel(key: string) { - let channel = this.#channels.get(key); - if (!channel) { - channel = { - listeners: new Set(), - status: "idle", - queue: [], - debounceTimer: null, - pendingDebounced: null, - lastDebouncedExecutionTime: null, - }; - this.#channels.set(key, channel); - } - return channel; - } - + /** Subscribe to status changes using the key from `key()` */ subscribe( key: string, cb: (update: MutationEvent) => void, @@ -276,41 +239,6 @@ export class BlockingMutation< return () => channel?.listeners.delete(cb); } - #notify( - channel: Channel>, - status: MutationEvent["status"], - result: Result | null = null, - error: unknown = null, - ) { - const event: MutationEvent = { status, result, error, debounced: this.#options.debounceMs !== undefined }; - channel.listeners.forEach((cb) => cb(event)); - } - - #setIdle( - key: string, - channel: Channel>, - ) { - // Check if there are pending debounced calls waiting - if (channel.pendingDebounced !== null) { - // Stay in waiting state - channel.status = "waiting"; - this.#notify(channel, "waiting", null, null); - } else { - // Normal idle transition - channel.status = "idle"; - this.#notify(channel, "idle", null, null); - // Clean up the channel if there are no listeners - if (channel.listeners.size === 0) { - // Clear any pending timers before deleting the channel - if (channel.debounceTimer !== null) { - clearTimeout(channel.debounceTimer); - channel.debounceTimer = null; - } - this.#channels.delete(key); - } - } - } - describe(...args: Args): string { const { describe } = this.#options; return typeof describe === "function" @@ -327,58 +255,13 @@ export class BlockingMutation< } /** Calling the mutation in a global scope. Errors are turned into UI toasts. */ - run(...args: Args) { + run(...args: Args): void { this.runWithOptions(...args, {}); } - /** - * Using this in any situation is likely incorrect. Use {@linkcode runWithOptions} - * to handle success and error. - * - * By using this, you must handle the success and error conditions of the - * promise, or else the user will never see the result on screen. If the - * mutation has snapshots, be aware that cancelled mutations are implemented - * with promises that never resolve. - */ - runAsHeadlessPromise(...array: [...Args, RunOptions]): Promise { - if (!this.#client.enabled) { - throw new Error( - "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?", - ); - } - - const args = array.slice() as Args; - const options = args.pop() as RunOptions; - const { onSuccessUi: onSuccess, onSuccessData, onError, onSettled, onRestore } = options; - - if (!this.isAllowed()) { - if (this.isUnauthenticated()) { - this.#reportUnauthenticated(options, args); - return Promise.reject(new Error("Mutation requires authentication.")); - } - return Promise.reject(new Error("Mutation is not allowed.")); - } - - const promise = this.#runWithOptions(args, onRestore, true); - return promise.then((result) => { - // Call user handlers - onSuccess?.(result); - onSuccessData?.(result); - onSettled?.({ status: "success", result }); - return result; - }).catch((caught: unknown) => { - const { error } = unwrapMutationError(caught); - - onError?.(error); - onSettled?.({ status: "error", error }); - - throw error; - }); - } - /** Calls the mutation with custom handlers that can suppress global handlers. */ - runWithOptions(...array: [...Args, RunOptions]): void { - if (!this.#client.enabled) { + runWithOptions(...array: [...args: Args, options: RunOptions]): void { + if (!this.client.enabled) { throw new Error( "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?", ); @@ -396,7 +279,7 @@ export class BlockingMutation< onError?.(error); onSettled?.({ status: "error", error }); if (!onError) { - this.#client.reportError(formatFriendlyError(this.describe(...args), error), error); + this.client.reportError(formatFriendlyError(this.describe(...args), error), error); } return; } @@ -415,8 +298,8 @@ export class BlockingMutation< // Call global handler unless suppressed if (!suppressGlobalSuccess) { const message = this.describeResult(args, result); - if (message && this.#client.reportSuccess) { - this.#client.reportSuccess(message); + if (message && this.client.reportSuccess) { + this.client.reportSuccess(message); } } }).catch((caught: unknown) => { @@ -427,17 +310,62 @@ export class BlockingMutation< // Call global handler unless suppressed if (!suppressGlobalError) { - this.#client.reportError(formatFriendlyError(description, error), error); + this.client.reportError(formatFriendlyError(description, error), error); } }); } + /** + * Using this in any situation is likely incorrect. Use {@linkcode runWithOptions} + * to handle success and error. + * + * By using this, you must handle the success and error conditions of the + * promise, or else the user will never see the result on screen. If the + * mutation has snapshots, be aware that cancelled mutations are implemented + * with promises that never resolve. + */ + runAsHeadlessPromise(...array: [...args: Args, options: RunOptions]): Promise { + if (!this.client.enabled) { + throw new Error( + "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?", + ); + } + + const args = array.slice() as Args; + const options = args.pop() as RunOptions; + const { onSuccessUi: onSuccess, onSuccessData, onError, onSettled, onRestore } = options; + + if (!this.isAllowed()) { + if (this.isUnauthenticated()) { + this.#reportUnauthenticated(options, args); + return Promise.reject(new Error("Mutation requires authentication.")); + } + return Promise.reject(new Error("Mutation is not allowed.")); + } + + const promise = this.#runWithOptions(args, onRestore, true); + return promise.then((result) => { + // Call user handlers + onSuccess?.(result); + onSuccessData?.(result); + onSettled?.({ status: "success", result }); + return result; + }).catch((caught: unknown) => { + const { error } = unwrapMutationError(caught); + + onError?.(error); + onSettled?.({ status: "error", error }); + + throw error; + }); + } + #runWithOptions( args: Args, userOnRestore: RunOptions["onRestore"], suppressGlobalHandlers: boolean, ): Promise { - if (!this.#client.enabled) { + if (!this.client.enabled) { throw new Error( "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?", ); @@ -489,7 +417,7 @@ export class BlockingMutation< } // Per call, so restores, refetches and refetch dedupe belong to this call - const helpers = this.#client.getOptimisticHelpers({ + const helpers = this.client.getOptimisticHelpers({ onRestore: (cb) => { rollbacks.push(cb); }, @@ -535,7 +463,7 @@ export class BlockingMutation< context, { ...context, args }, ); - const isNoOp = this.#client.deepEquals(beforeSnapshot, afterSnapshot); + const isNoOp = this.client.deepEquals(beforeSnapshot, afterSnapshot); if (isNoOp) { let next; @@ -566,9 +494,44 @@ export class BlockingMutation< return promise; } + #notify( + channel: Channel, + status: MutationEvent["status"], + result: Result | null = null, + error: unknown = null, + ) { + const event: MutationEvent = { status, result, error, debounced: this.#options.debounceMs !== undefined }; + channel.listeners.forEach((cb) => cb(event)); + } + + #setIdle( + key: string, + channel: Channel, + ) { + // Check if there are pending debounced calls waiting + if (channel.pendingDebounced !== null) { + // Stay in waiting state + channel.status = "waiting"; + this.#notify(channel, "waiting", null, null); + } else { + // Normal idle transition + channel.status = "idle"; + this.#notify(channel, "idle", null, null); + // Clean up the channel if there are no listeners + if (channel.listeners.size === 0) { + // Clear any pending timers before deleting the channel + if (channel.debounceTimer !== null) { + clearTimeout(channel.debounceTimer); + channel.debounceTimer = null; + } + this.#channels.delete(key); + } + } + } + #executeNext( key: string, - channel: Channel>, + channel: Channel, ) { const item = channel.queue.shift(); if (!item) { @@ -594,7 +557,7 @@ export class BlockingMutation< results.forEach((result) => { if (result.status === "rejected") { const message = `Failed to refetch data: ${errMessage(result.reason)}`; - this.#client.reportError(message, result.reason); + this.client.reportError(message, result.reason); } }); }, @@ -637,7 +600,7 @@ export class BlockingMutation< results.forEach((result) => { if (result.status === "rejected") { const message = `Failed to refetch data: ${errMessage(result.reason)}`; - this.#client.reportError(message, result.reason); + this.client.reportError(message, result.reason); } }); }).finally(() => { @@ -651,8 +614,8 @@ export class BlockingMutation< #runDebouncedAndReturn( args: Args, key: string, - channel: Channel>, - context: Context, + channel: Channel, + context: object, userOnRestore: (() => void) | undefined, shouldExecuteImmediate: boolean, shouldCallGlobalHandler: boolean, @@ -672,7 +635,6 @@ export class BlockingMutation< this.#rollbackPendingDebounced(channel); } - // Apply optimistic update (same logic as current runAndReturn) const onSuccess: Array<(result: Result) => void> = []; let expired = false; const rollbacks: Array<() => void> = []; @@ -692,7 +654,7 @@ export class BlockingMutation< } // Per call, so restores, refetches and refetch dedupe belong to this call - const helpers = this.#client.getOptimisticHelpers({ + const helpers = this.client.getOptimisticHelpers({ onRestore: (cb) => { rollbacks.push(cb); }, @@ -745,7 +707,7 @@ export class BlockingMutation< if ( snapshotToCompare !== undefined - && this.#client.deepEquals(snapshotToCompare, currentSnapshot) + && this.client.deepEquals(snapshotToCompare, currentSnapshot) ) { // No-op detected - rollback optimistic update let next; @@ -818,7 +780,7 @@ export class BlockingMutation< } #rollbackPendingDebounced( - channel: Channel>, + channel: Channel, ) { if (!channel.pendingDebounced) return; @@ -834,7 +796,7 @@ export class BlockingMutation< #enqueueDebouncedCall( key: string, - channel: Channel>, + channel: Channel, ) { // Clear timer channel.debounceTimer = null; @@ -870,8 +832,8 @@ export class BlockingMutation< // Call global handler if needed (based on whether component is watching success) if (shouldCallGlobalHandler) { const message = this.describeResult(args, result); - if (message && this.#client.reportSuccess) { - this.#client.reportSuccess(message); + if (message && this.client.reportSuccess) { + this.client.reportSuccess(message); } } }, @@ -883,7 +845,7 @@ export class BlockingMutation< // Call global handler if needed (based on whether component is watching errors) if (shouldCallGlobalHandler) { - this.#client.reportError( + this.client.reportError( formatFriendlyError(description, error), error, ); @@ -891,7 +853,6 @@ export class BlockingMutation< }, ); - // Add to queue (same structure as regular blocking mutation) channel.queue.push({ args, context, @@ -908,6 +869,40 @@ export class BlockingMutation< } // Otherwise, it will execute when the current item finishes } + + #context(): object { + return { + ...this.client.context, + ...this.client.userContext?.get(), + }; + } + + #reportUnauthenticated(options: RunOptions, args: Args) { + const handler = options.onUnauthenticated ?? this.client.handleUnauthenticated; + handler?.call( + this.client, + // Reached only for `auth: true`, whose arguments the define-time guard + // constrains to be serializable. + { id: this.#options.id, description: this.describe(...args), args: args as SerializableValue[] }, + this as unknown as Mutation, + ); + } + + #getOrPutChannel(key: string) { + let channel = this.#channels.get(key); + if (!channel) { + channel = { + listeners: new Set(), + status: "idle", + queue: [], + debounceTimer: null, + pendingDebounced: null, + lastDebouncedExecutionTime: null, + }; + this.#channels.set(key, channel); + } + return channel; + } } export function formatFriendlyError( diff --git a/src/react.ts b/src/react.ts index d4cc1317b5b590af53b96a78843e2bb7d613b209..90f26fea5f62570f059d98a4f297ef9bbd0fe1cd 100644 --- a/src/react.ts +++ b/src/react.ts @@ -13,9 +13,9 @@ import { useSyncExternalStore, } from "react"; import { jsx } from "react/jsx-runtime"; -import type { MutationClient, MutationClientConfig, MutationClientFromConfig } from "./client.ts"; -import { BlockingMutation, formatFriendlyError } from "./mutation.ts"; -import type { Mutation, RunOptions, SerializableValue } from "./types.ts"; +import type { MutationClient } from "./client.ts"; +import { formatFriendlyError, Mutation } from "./mutation.ts"; +import type { RunOptions } from "./types.ts"; /** * Subscribe to a mutation's status, as well as accessing a local `run` method. @@ -77,22 +77,18 @@ export function bindAsyncCallback( const live = useRef({ callback, options }); live.current = { callback, options }; // A stable, unregistered mutation with no optimistic state; every field - // reads the ref so it tracks the latest callback and options. Args are - // never serialized here (no id, no auth replay), so the serializable bound - // is cast away locally. Empty describe/describeResult fall through to the - // generic error message and no success toast, respectively. + // reads the ref so it tracks the latest callback and options. Empty + // describe/describeResult fall through to the generic error message and no + // success toast, respectively. const [mutation] = useState(() => - new BlockingMutation( - client as unknown as MutationClientFromConfig, - { - id: "", - mutate: (...args) => live.current.callback(...(args as unknown as Args)), - optimistic: () => {}, - describe: () => live.current.options?.describe ?? "", - describeResult: () => live.current.options?.describeResult ?? "", - refetchOnSuccess: false, - }, - ) as unknown as Mutation + new Mutation(client, { + id: "", + mutate: (...args) => live.current.callback(...args), + optimistic: () => {}, + describe: () => live.current.options?.describe ?? "", + describeResult: () => live.current.options?.describeResult ?? "", + refetchOnSuccess: false, + }) ); return useMutate(mutation); }; @@ -494,7 +490,7 @@ export interface MutationButtonProps { | Mutation | UseMutateResult; /** Preventing default will interrupt the mutation */ - args: Args | null | ((e: MouseEvent) => Args | null); + args: NoInfer | null | ((e: MouseEvent) => NoInfer | null); /** Preventing default will interrupt the mutation */ onClick?: (e: MouseEvent) => void; disabled?: boolean; diff --git a/src/types.ts b/src/types.ts index 62a14ec45731b7c5c5ea7437dba9777d3b7f9d42..4181e4e302bb9c9306dfa3ba24c6b3ab70271832 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,4 +1,4 @@ -import type { MutationClient } from "./client.ts"; +import type { Mutation } from "./mutation.ts"; /** * Plain JSON value. The default serializable leaf set, still exported for @@ -61,43 +61,6 @@ export interface MutationAction { args: SerializableValue[]; } -export interface Mutation { - /** Unique identifier passed to `define`. */ - readonly id: string; - /** Calling the mutation. Errors are turned into UI toasts. */ - run(...args: Args): void; - /** Calls the mutation with custom handlers that can suppress global handlers. */ - runWithOptions(...args: [...args: Args, options: RunOptions]): void; - /** - * Using this in any situation is likely incorrect, even internally. - * Use {@linkcode runWithOptions} to handle success and error. - * - * By using this, you must handle the success and error conditions of the - * promise, or else the user will never see the result on screen. If the - * mutation has snapshots, be aware that cancelled mutations are implemented - * with promises that never resolve. - */ - runAsHeadlessPromise(...array: [...Args, RunOptions]): Promise; - - /** Returns the concurrency key used for a given set of arguments */ - key(args: Args): string; - /** Subscribe to status changes using the key from `key()` */ - subscribe( - key: string, - cb: (update: MutationEvent) => void, - ): () => void; - describe(...args: Args): string; - describeResult: ((args: Args, result: Result) => string | undefined) | null; - /** - * `true` when an `auth: true` mutation has no user available. Scoped - * mutations are excluded; they disable instead of routing to the sign-in flow. - */ - isUnauthenticated(): boolean; - isAllowed(): boolean; - subscribeAllowed(cb: () => void): () => void; - client: MutationClient; -} - export interface RunOptions { /** Called to show the success UI. Passing this suppresses the global success handler. */ onSuccessUi?: (result: Result) => void; -- 2.54.1