| 1 | import { message as errMessage } from "@clo/lib/error.ts"; |
| 2 | import type { MutationClient, MutationClientConfig, Reactive } from "./client.ts"; |
| 3 | import type { MutationEvent, RunOptions, SerializableValue } from "./types.ts"; |
| 4 | |
| 5 | /** |
| 6 | * Argument to `MutationClient.define`. |
| 7 | * @template Args - the parameters to the mutation |
| 8 | * @template Result - the result of the API call |
| 9 | * @template Config - global values and helpers from `MutationClient` |
| 10 | */ |
| 11 | export interface MutationOptions< |
| 12 | Args extends unknown[], |
| 13 | Result, |
| 14 | Auth extends boolean | string, |
| 15 | Config extends MutationClientConfig, |
| 16 | > { |
| 17 | /** |
| 18 | * Stable identifier, unique per client; duplicate registration throws in |
| 19 | * production and replaces the previous registration in development, where |
| 20 | * hot reload re-runs `define`. Identifies the mutation in a stored |
| 21 | * `MutationAction` so a call attempted while signed out can be restored |
| 22 | * with `MutationClient.run`. |
| 23 | */ |
| 24 | id: string; |
| 25 | /** |
| 26 | * Require a current user before the mutation can run. Passing one of the |
| 27 | * client's `authScopes` additionally requires that scope to read `true`. |
| 28 | */ |
| 29 | auth?: Auth; |
| 30 | /** Additional guard for fine-grained auth or domain-specific availability. */ |
| 31 | isAllowed?: Reactive<boolean>; |
| 32 | /** |
| 33 | * This function is only responsible for performing the underlying API call, |
| 34 | * syncronizing the optimistic state with reality. Throw on failure. A rest |
| 35 | * params type is used to allow type inference. Place this function first to |
| 36 | * ensure TypeScript correctly infers the argument type for the rest of the |
| 37 | * functions. |
| 38 | * |
| 39 | * In practice, optimistic context is never needed in this function, but it |
| 40 | * is provided as the `this` value if you truly desire it. |
| 41 | */ |
| 42 | mutate: (this: Context<Config, Auth>, ...args: Args) => Promise<Result>; |
| 43 | /** |
| 44 | * Specifying the optimistic strategy is required. To disable, pass an empty |
| 45 | * function with a comment to document why it isn't needed. |
| 46 | */ |
| 47 | optimistic: ( |
| 48 | context: OptimisticContext<Args, Result, Config, Auth>, |
| 49 | ) => void; |
| 50 | /** |
| 51 | * Used in error messages and debug tools. |
| 52 | * Phrase it considering the template `Could not ${describe(...)}` |
| 53 | * |
| 54 | * Unlike every other function, user context is nullable: this also runs |
| 55 | * while signed out to build the `MutationAction` description given to the |
| 56 | * sign-in flow. |
| 57 | */ |
| 58 | describe: string | ((context: Context<Config, false> & { args: Args }) => string); |
| 59 | /** |
| 60 | * Used in success messages. |
| 61 | * Phrase it as a complete success message: "Deleted Item" |
| 62 | */ |
| 63 | describeResult: |
| 64 | | string |
| 65 | | ((context: Context<Config, Auth> & { args: Args; result: Result }) => string) |
| 66 | | null; |
| 67 | /** |
| 68 | * If the optimistic updator function is perfect, then this may be set to false. |
| 69 | * @default true |
| 70 | */ |
| 71 | refetchOnSuccess?: boolean; |
| 72 | /** |
| 73 | * A key to associate related items. For example, returning a user ID. If |
| 74 | * specifying, then all mutations of the same key will evaluate in serial, |
| 75 | * but optimistic updates will apply instantly. |
| 76 | */ |
| 77 | key?: (context: Context<Config, Auth> & { args: Args }) => string | string[]; |
| 78 | /** |
| 79 | * Enable debouncing with "last call wins" behavior. When rapid calls arrive, |
| 80 | * the previous optimistic update is rolled back and the new one applied. |
| 81 | * |
| 82 | * All pending promises resolve with the final result. |
| 83 | */ |
| 84 | debounceMs?: number; |
| 85 | /** |
| 86 | * When true, the first call executes immediately (leading edge), then |
| 87 | * subsequent rapid calls are debounced (trailing edge). After the debounce |
| 88 | * period ends, the next call executes immediately again. |
| 89 | * |
| 90 | * Requires `debounceMs` to be set. |
| 91 | */ |
| 92 | debounceImmediate?: boolean; |
| 93 | /** |
| 94 | * Called before and after optimistic updates to detect no-op mutations. |
| 95 | * If the snapshots are equal (using deepEquals), the mutation is cancelled. |
| 96 | * Only `onSettled` callbacks fire, not `onSuccess` or global handlers. |
| 97 | */ |
| 98 | snapshot?: (context: Context<Config, Auth> & { args: Args }) => unknown; |
| 99 | } |
| 100 | |
| 101 | type Context<Config extends MutationClientConfig, Auth extends boolean | string> = |
| 102 | & Config["context"] |
| 103 | & (Auth extends false ? Partial<Config["userContext"]> : Config["userContext"]); |
| 104 | |
| 105 | export type OptimisticContext< |
| 106 | Args extends unknown[], |
| 107 | Result, |
| 108 | Config extends MutationClientConfig, |
| 109 | Auth extends boolean | string, |
| 110 | > = Context<Config, Auth> & { |
| 111 | args: Args; |
| 112 | helpers: Config["optimisticHelpers"]; |
| 113 | /** Add an event listener to roll back the update */ |
| 114 | onRestore: (cb: () => void) => void; |
| 115 | /** Add an event listener to apply `Result` to the store. */ |
| 116 | onSuccess: (cb: (result: Result) => void) => void; |
| 117 | /** Add an event listener to refetch data after mutation. */ |
| 118 | onRefetch: (cb: () => Promise<void>) => void; |
| 119 | }; |
| 120 | |
| 121 | interface PendingDebouncedState<Args extends unknown[], Result> { |
| 122 | /** Arguments from the most recent call */ |
| 123 | args: Args; |
| 124 | /** Context captured when the most recent call was allowed */ |
| 125 | context: object; |
| 126 | /** Restores registered by the most recent call */ |
| 127 | rollbacks: Array<() => void>; |
| 128 | /** All pending promises from all superseded calls */ |
| 129 | pending: Array<{ |
| 130 | resolve: (result: Result) => void; |
| 131 | reject: (error: unknown) => void; |
| 132 | }>; |
| 133 | /** Success callbacks from the most recent call */ |
| 134 | onSuccess: Array<(result: Result) => void>; |
| 135 | /** Refetch callbacks from the most recent call */ |
| 136 | refetches: Array<() => Promise<void>>; |
| 137 | /** Initial snapshot before any debounced calls (for no-op detection) */ |
| 138 | initialSnapshot?: unknown; |
| 139 | /** Whether the last call wanted global handlers to be called */ |
| 140 | shouldCallGlobalHandler: boolean; |
| 141 | } |
| 142 | |
| 143 | /** Internal wrapper that preserves the pre-rollback description for reporting. */ |
| 144 | class MutationError extends Error { |
| 145 | constructor( |
| 146 | readonly error: unknown, |
| 147 | readonly description: string, |
| 148 | ) { |
| 149 | super(errMessage(error), { cause: error }); |
| 150 | this.name = "MutationError"; |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | function unwrapMutationError(caught: unknown) { |
| 155 | if (caught instanceof MutationError) { |
| 156 | return { error: caught.error, description: caught.description }; |
| 157 | } |
| 158 | return { error: caught, description: null }; |
| 159 | } |
| 160 | |
| 161 | interface Channel<Args extends unknown[], Result> { |
| 162 | listeners: Set<(update: MutationEvent<Result>) => void>; |
| 163 | status: "idle" | "waiting" | "mutating" | "refetching" | "skipped"; |
| 164 | queue: Array<Item<Args, Result>>; |
| 165 | // Debounce state (only used if debounce option is set) |
| 166 | debounceTimer: ReturnType<typeof setTimeout> | null; |
| 167 | pendingDebounced: PendingDebouncedState<Args, Result> | null; |
| 168 | // Track when last debounced mutation executed (for debounceImmediate) |
| 169 | lastDebouncedExecutionTime: number | null; |
| 170 | } |
| 171 | |
| 172 | interface Item<Args extends unknown[], Result> { |
| 173 | args: Args; |
| 174 | context: object; |
| 175 | rollbacks: Array<() => void>; |
| 176 | refetches: Array<() => Promise<void>>; |
| 177 | onSuccess: Array<(result: Result) => void>; |
| 178 | resolve: (result: Result) => void; |
| 179 | reject: (error: unknown) => void; |
| 180 | } |
| 181 | |
| 182 | /** A mutation defined with `MutationClient.define`. */ |
| 183 | export class Mutation<Args extends unknown[], Result> { |
| 184 | readonly client: MutationClient<object, object, object, string>; |
| 185 | #options: MutationOptions<Args, Result, boolean | string, MutationClientConfig>; |
| 186 | #channels: Map<string, Channel<Args, Result>> = new Map(); |
| 187 | |
| 188 | constructor( |
| 189 | client: MutationClient<object, object, object, string>, |
| 190 | options: MutationOptions<Args, Result, boolean | string, MutationClientConfig>, |
| 191 | ) { |
| 192 | this.client = client; |
| 193 | this.#options = options; |
| 194 | } |
| 195 | |
| 196 | /** Unique identifier passed to `define`. */ |
| 197 | get id(): string { |
| 198 | return this.#options.id; |
| 199 | } |
| 200 | |
| 201 | /** |
| 202 | * `true` when an `auth: true` mutation has no user available. Scoped |
| 203 | * mutations are excluded; they disable instead of routing to the sign-in flow. |
| 204 | */ |
| 205 | isUnauthenticated(): boolean { |
| 206 | return this.#options.auth === true && this.client.userContext?.get() == null; |
| 207 | } |
| 208 | |
| 209 | isAllowed(): boolean { |
| 210 | const { auth } = this.#options; |
| 211 | if (auth !== undefined && auth !== false && this.client.userContext?.get() == null) return false; |
| 212 | if (typeof auth === "string" && !(this.client.authScopes?.[auth]?.get() ?? false)) return false; |
| 213 | return this.#options.isAllowed?.get() ?? true; |
| 214 | } |
| 215 | |
| 216 | subscribeAllowed(cb: () => void): () => void { |
| 217 | const { auth } = this.#options; |
| 218 | const unsubscribes = [ |
| 219 | this.#options.isAllowed?.sub(cb), |
| 220 | typeof auth === "string" ? this.client.authScopes?.[auth]?.sub(cb) : undefined, |
| 221 | ]; |
| 222 | return () => unsubscribes.forEach((unsubscribe) => unsubscribe?.()); |
| 223 | } |
| 224 | |
| 225 | /** Returns the concurrency key used for a given set of arguments */ |
| 226 | key(args: Args): string { |
| 227 | const k = this.#options.key?.({ ...this.#context(), args }) |
| 228 | ?? "shared"; |
| 229 | return JSON.stringify(k); |
| 230 | } |
| 231 | |
| 232 | /** Subscribe to status changes using the key from `key()` */ |
| 233 | subscribe( |
| 234 | key: string, |
| 235 | cb: (update: MutationEvent<Result>) => void, |
| 236 | ): () => void { |
| 237 | const channel = this.#getOrPutChannel(key); |
| 238 | channel.listeners.add(cb); |
| 239 | return () => channel?.listeners.delete(cb); |
| 240 | } |
| 241 | |
| 242 | describe(...args: Args): string { |
| 243 | const { describe } = this.#options; |
| 244 | return typeof describe === "function" |
| 245 | ? describe({ ...this.#context(), args }) |
| 246 | : describe; |
| 247 | } |
| 248 | |
| 249 | describeResult(args: Args, result: Result): string | undefined { |
| 250 | const { describeResult } = this.#options; |
| 251 | if (describeResult === null) return undefined; |
| 252 | return typeof describeResult === "function" |
| 253 | ? describeResult({ ...this.#context(), args, result }) |
| 254 | : describeResult; |
| 255 | } |
| 256 | |
| 257 | /** Calling the mutation in a global scope. Errors are turned into UI toasts. */ |
| 258 | run(...args: Args): void { |
| 259 | this.runWithOptions(...args, {}); |
| 260 | } |
| 261 | |
| 262 | /** Calls the mutation with custom handlers that can suppress global handlers. */ |
| 263 | runWithOptions(...array: [...args: Args, options: RunOptions<Result>]): void { |
| 264 | if (!this.client.enabled) { |
| 265 | throw new Error( |
| 266 | "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?", |
| 267 | ); |
| 268 | } |
| 269 | |
| 270 | const args = array.slice() as Args; |
| 271 | const options = args.pop() as RunOptions<Result>; |
| 272 | const { onSuccessUi, onSuccessData, onError, onSettled, onRestore } = options; |
| 273 | if (!this.isAllowed()) { |
| 274 | if (this.isUnauthenticated()) { |
| 275 | this.#reportUnauthenticated(options, args); |
| 276 | return; |
| 277 | } |
| 278 | const error = new Error("Mutation is not allowed."); |
| 279 | onError?.(error); |
| 280 | onSettled?.({ status: "error", error }); |
| 281 | if (!onError) { |
| 282 | this.client.reportError(formatFriendlyError(this.describe(...args), error), error); |
| 283 | } |
| 284 | return; |
| 285 | } |
| 286 | |
| 287 | const suppressAll = this.#options.debounceMs !== undefined && !onSuccessUi && !onError; |
| 288 | const suppressGlobalSuccess = onSuccessUi !== undefined || suppressAll; |
| 289 | const suppressGlobalError = onError !== undefined || suppressAll; |
| 290 | |
| 291 | const promise = this.#runWithOptions(args, onRestore, suppressAll); |
| 292 | promise.then((result) => { |
| 293 | // Call user handlers |
| 294 | onSuccessUi?.(result); |
| 295 | onSuccessData?.(result); |
| 296 | onSettled?.({ status: "success", result }); |
| 297 | |
| 298 | // Call global handler unless suppressed |
| 299 | if (!suppressGlobalSuccess) { |
| 300 | const message = this.describeResult(args, result); |
| 301 | if (message && this.client.reportSuccess) { |
| 302 | this.client.reportSuccess(message); |
| 303 | } |
| 304 | } |
| 305 | }).catch((caught: unknown) => { |
| 306 | const { error, description = this.describe(...args) } = unwrapMutationError(caught); |
| 307 | |
| 308 | onError?.(error); |
| 309 | onSettled?.({ status: "error", error }); |
| 310 | |
| 311 | // Call global handler unless suppressed |
| 312 | if (!suppressGlobalError) { |
| 313 | this.client.reportError(formatFriendlyError(description, error), error); |
| 314 | } |
| 315 | }); |
| 316 | } |
| 317 | |
| 318 | /** |
| 319 | * Using this in any situation is likely incorrect. Use {@linkcode runWithOptions} |
| 320 | * to handle success and error. |
| 321 | * |
| 322 | * By using this, you must handle the success and error conditions of the |
| 323 | * promise, or else the user will never see the result on screen. If the |
| 324 | * mutation has snapshots, be aware that cancelled mutations are implemented |
| 325 | * with promises that never resolve. |
| 326 | */ |
| 327 | runAsHeadlessPromise(...array: [...args: Args, options: RunOptions<Result>]): Promise<Result> { |
| 328 | if (!this.client.enabled) { |
| 329 | throw new Error( |
| 330 | "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?", |
| 331 | ); |
| 332 | } |
| 333 | |
| 334 | const args = array.slice() as Args; |
| 335 | const options = args.pop() as RunOptions<Result>; |
| 336 | const { onSuccessUi: onSuccess, onSuccessData, onError, onSettled, onRestore } = options; |
| 337 | |
| 338 | if (!this.isAllowed()) { |
| 339 | if (this.isUnauthenticated()) { |
| 340 | this.#reportUnauthenticated(options, args); |
| 341 | return Promise.reject(new Error("Mutation requires authentication.")); |
| 342 | } |
| 343 | return Promise.reject(new Error("Mutation is not allowed.")); |
| 344 | } |
| 345 | |
| 346 | const promise = this.#runWithOptions(args, onRestore, true); |
| 347 | return promise.then((result) => { |
| 348 | // Call user handlers |
| 349 | onSuccess?.(result); |
| 350 | onSuccessData?.(result); |
| 351 | onSettled?.({ status: "success", result }); |
| 352 | return result; |
| 353 | }).catch((caught: unknown) => { |
| 354 | const { error } = unwrapMutationError(caught); |
| 355 | |
| 356 | onError?.(error); |
| 357 | onSettled?.({ status: "error", error }); |
| 358 | |
| 359 | throw error; |
| 360 | }); |
| 361 | } |
| 362 | |
| 363 | #runWithOptions( |
| 364 | args: Args, |
| 365 | userOnRestore: RunOptions<Result>["onRestore"], |
| 366 | suppressGlobalHandlers: boolean, |
| 367 | ): Promise<Result> { |
| 368 | if (!this.client.enabled) { |
| 369 | throw new Error( |
| 370 | "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?", |
| 371 | ); |
| 372 | } |
| 373 | const key = this.key(args); |
| 374 | const channel = this.#getOrPutChannel(key); |
| 375 | const context = this.#context(); |
| 376 | |
| 377 | // Check if debouncing is enabled |
| 378 | if (this.#options.debounceMs !== undefined) { |
| 379 | // Check if we should execute immediately (leading edge) |
| 380 | const shouldExecuteImmediate = this.#options.debounceImmediate && ( |
| 381 | channel.lastDebouncedExecutionTime === null |
| 382 | || Date.now() - channel.lastDebouncedExecutionTime >= this.#options.debounceMs |
| 383 | ); |
| 384 | |
| 385 | return this.#runDebouncedAndReturn( |
| 386 | args, |
| 387 | key, |
| 388 | channel, |
| 389 | context, |
| 390 | userOnRestore, |
| 391 | !!shouldExecuteImmediate, |
| 392 | suppressGlobalHandlers, |
| 393 | ); |
| 394 | } |
| 395 | |
| 396 | // Take snapshot before optimistic update (if snapshot function defined) |
| 397 | const beforeSnapshot = this.#options.snapshot |
| 398 | ? this.#options.snapshot.call(context, { ...context, args }) |
| 399 | : undefined; |
| 400 | |
| 401 | const onSuccess: Array<(result: Result) => void> = []; |
| 402 | let expired = false; |
| 403 | const rollbacks: Array<() => void> = []; |
| 404 | const refetches: Array<() => Promise<void>> = []; |
| 405 | const onRestore = (cb: () => void) => { |
| 406 | if (expired) { |
| 407 | throw new Error( |
| 408 | "Can only call onRestore from within the optimistic update function.", |
| 409 | ); |
| 410 | } |
| 411 | rollbacks.push(cb); |
| 412 | }; |
| 413 | |
| 414 | // Register user's onRestore callback if provided |
| 415 | if (userOnRestore) { |
| 416 | rollbacks.push(userOnRestore); |
| 417 | } |
| 418 | |
| 419 | // Per call, so restores, refetches and refetch dedupe belong to this call |
| 420 | const helpers = this.client.getOptimisticHelpers({ |
| 421 | onRestore: (cb) => { |
| 422 | rollbacks.push(cb); |
| 423 | }, |
| 424 | onRefetch: (cb) => { |
| 425 | refetches.push(cb); |
| 426 | }, |
| 427 | }); |
| 428 | |
| 429 | try { |
| 430 | this.#options.optimistic({ |
| 431 | ...context, |
| 432 | args, |
| 433 | helpers, |
| 434 | onRestore, |
| 435 | onSuccess(cb) { |
| 436 | if (expired) { |
| 437 | throw new Error( |
| 438 | "Can only call onSuccess from within the optimistic update function.", |
| 439 | ); |
| 440 | } |
| 441 | onSuccess.push(cb); |
| 442 | }, |
| 443 | onRefetch(cb) { |
| 444 | if (expired) { |
| 445 | throw new Error( |
| 446 | "Can only call onRefetch from within the optimistic update function.", |
| 447 | ); |
| 448 | } |
| 449 | refetches.push(cb); |
| 450 | }, |
| 451 | }); |
| 452 | } catch (error) { |
| 453 | expired = true; |
| 454 | let next; |
| 455 | while (next = rollbacks.pop()) next(); |
| 456 | return Promise.reject(error); |
| 457 | } |
| 458 | expired = true; |
| 459 | |
| 460 | // Take snapshot after optimistic update and check for no-op |
| 461 | if (beforeSnapshot !== undefined) { |
| 462 | const afterSnapshot = this.#options.snapshot!.call( |
| 463 | context, |
| 464 | { ...context, args }, |
| 465 | ); |
| 466 | const isNoOp = this.client.deepEquals(beforeSnapshot, afterSnapshot); |
| 467 | |
| 468 | if (isNoOp) { |
| 469 | let next; |
| 470 | while (next = rollbacks.pop()) next(); |
| 471 | |
| 472 | // Notify listeners of skipped status |
| 473 | this.#notify(channel, "skipped"); |
| 474 | |
| 475 | return new Promise(() => {}); |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | const { promise, resolve, reject } = Promise.withResolvers<Result>(); |
| 480 | channel.queue.push({ |
| 481 | args, |
| 482 | context, |
| 483 | rollbacks, |
| 484 | refetches, |
| 485 | onSuccess, |
| 486 | resolve, |
| 487 | reject, |
| 488 | }); |
| 489 | |
| 490 | if (channel.status === "idle") { |
| 491 | this.#executeNext(key, channel); |
| 492 | } |
| 493 | |
| 494 | return promise; |
| 495 | } |
| 496 | |
| 497 | #notify( |
| 498 | channel: Channel<Args, Result>, |
| 499 | status: MutationEvent<Result>["status"], |
| 500 | result: Result | null = null, |
| 501 | error: unknown = null, |
| 502 | ) { |
| 503 | const event: MutationEvent<Result> = { status, result, error, debounced: this.#options.debounceMs !== undefined }; |
| 504 | channel.listeners.forEach((cb) => cb(event)); |
| 505 | } |
| 506 | |
| 507 | #setIdle( |
| 508 | key: string, |
| 509 | channel: Channel<Args, Result>, |
| 510 | ) { |
| 511 | // Check if there are pending debounced calls waiting |
| 512 | if (channel.pendingDebounced !== null) { |
| 513 | // Stay in waiting state |
| 514 | channel.status = "waiting"; |
| 515 | this.#notify(channel, "waiting", null, null); |
| 516 | } else { |
| 517 | // Normal idle transition |
| 518 | channel.status = "idle"; |
| 519 | this.#notify(channel, "idle", null, null); |
| 520 | // Clean up the channel if there are no listeners |
| 521 | if (channel.listeners.size === 0) { |
| 522 | // Clear any pending timers before deleting the channel |
| 523 | if (channel.debounceTimer !== null) { |
| 524 | clearTimeout(channel.debounceTimer); |
| 525 | channel.debounceTimer = null; |
| 526 | } |
| 527 | this.#channels.delete(key); |
| 528 | } |
| 529 | } |
| 530 | } |
| 531 | |
| 532 | #executeNext( |
| 533 | key: string, |
| 534 | channel: Channel<Args, Result>, |
| 535 | ) { |
| 536 | const item = channel.queue.shift(); |
| 537 | if (!item) { |
| 538 | this.#setIdle(key, channel); |
| 539 | return; |
| 540 | } |
| 541 | |
| 542 | const { args, context, refetches, onSuccess, resolve, reject } = item; |
| 543 | channel.status = "mutating"; |
| 544 | this.#notify(channel, "mutating"); |
| 545 | |
| 546 | new Promise<Result>((resolve) => resolve(this.#options.mutate.call(context, ...args))).then((result) => { |
| 547 | // the call's rollbacks retire with it; apply optimistic success handlers |
| 548 | onSuccess.forEach((cb) => cb(result)); |
| 549 | |
| 550 | if (this.#options.refetchOnSuccess !== false) { |
| 551 | channel.status = "refetching"; |
| 552 | this.#notify(channel, "refetching", result); |
| 553 | // Call refetch and all refetch callbacks in parallel |
| 554 | Promise.allSettled(refetches.map((cb) => cb())).then( |
| 555 | (results) => { |
| 556 | // Report any errors from refetch or callbacks |
| 557 | results.forEach((result) => { |
| 558 | if (result.status === "rejected") { |
| 559 | const message = `Failed to refetch data: ${errMessage(result.reason)}`; |
| 560 | this.client.reportError(message, result.reason); |
| 561 | } |
| 562 | }); |
| 563 | }, |
| 564 | ).finally(() => { |
| 565 | this.#executeNext(key, channel); |
| 566 | }); |
| 567 | } else { |
| 568 | // Notify listeners with success status and result before moving to next |
| 569 | this.#notify(channel, "mutating", result); |
| 570 | this.#executeNext(key, channel); |
| 571 | } |
| 572 | resolve(result); |
| 573 | }, (error) => { |
| 574 | // Capture description BEFORE rollback so it sees optimistic state |
| 575 | const description = this.describe(...args); |
| 576 | const wrappedError = new MutationError(error, description); |
| 577 | |
| 578 | // if an error happens, then every pending call's rollbacks are called in reverse order |
| 579 | const remainingItems = channel.queue.splice(0); |
| 580 | for (const call of [item, ...remainingItems, channel.pendingDebounced].reverse()) { |
| 581 | let next; |
| 582 | while (next = call?.rollbacks.pop()) next(); |
| 583 | } |
| 584 | |
| 585 | // Cancel all remaining items in the channel |
| 586 | remainingItems.forEach((queuedItem) => { |
| 587 | queuedItem.reject(wrappedError); |
| 588 | }); |
| 589 | |
| 590 | // Notify listeners of the error |
| 591 | this.#notify(channel, "mutating", null, error); |
| 592 | |
| 593 | // Refetch to restore correct state |
| 594 | channel.status = "refetching"; |
| 595 | this.#notify(channel, "refetching", null, error); |
| 596 | // Refetch for the failed and cancelled calls in parallel |
| 597 | const refetchCallbacks = [item, ...remainingItems].flatMap((call) => call.refetches); |
| 598 | Promise.allSettled(refetchCallbacks.map((cb) => cb())).then((results) => { |
| 599 | // Report any errors from refetch or callbacks |
| 600 | results.forEach((result) => { |
| 601 | if (result.status === "rejected") { |
| 602 | const message = `Failed to refetch data: ${errMessage(result.reason)}`; |
| 603 | this.client.reportError(message, result.reason); |
| 604 | } |
| 605 | }); |
| 606 | }).finally(() => { |
| 607 | this.#executeNext(key, channel); |
| 608 | }); |
| 609 | |
| 610 | reject(wrappedError); |
| 611 | }); |
| 612 | } |
| 613 | |
| 614 | #runDebouncedAndReturn( |
| 615 | args: Args, |
| 616 | key: string, |
| 617 | channel: Channel<Args, Result>, |
| 618 | context: object, |
| 619 | userOnRestore: (() => void) | undefined, |
| 620 | shouldExecuteImmediate: boolean, |
| 621 | shouldCallGlobalHandler: boolean, |
| 622 | ): Promise<Result> { |
| 623 | // Capture initial snapshot before first debounced call |
| 624 | const isFirstDebouncedCall = channel.pendingDebounced === null; |
| 625 | let initialSnapshot: unknown; |
| 626 | if (isFirstDebouncedCall && this.#options.snapshot) { |
| 627 | initialSnapshot = this.#options.snapshot.call( |
| 628 | context, |
| 629 | { ...context, args }, |
| 630 | ); |
| 631 | } |
| 632 | |
| 633 | // If there's a pending debounced call, roll it back |
| 634 | if (channel.pendingDebounced) { |
| 635 | this.#rollbackPendingDebounced(channel); |
| 636 | } |
| 637 | |
| 638 | const onSuccess: Array<(result: Result) => void> = []; |
| 639 | let expired = false; |
| 640 | const rollbacks: Array<() => void> = []; |
| 641 | const refetches: Array<() => Promise<void>> = []; |
| 642 | const onRestore = (cb: () => void) => { |
| 643 | if (expired) { |
| 644 | throw new Error( |
| 645 | "Can only call onRestore from within the optimistic update function.", |
| 646 | ); |
| 647 | } |
| 648 | rollbacks.push(cb); |
| 649 | }; |
| 650 | |
| 651 | // Register user's onRestore callback if provided |
| 652 | if (userOnRestore) { |
| 653 | rollbacks.push(userOnRestore); |
| 654 | } |
| 655 | |
| 656 | // Per call, so restores, refetches and refetch dedupe belong to this call |
| 657 | const helpers = this.client.getOptimisticHelpers({ |
| 658 | onRestore: (cb) => { |
| 659 | rollbacks.push(cb); |
| 660 | }, |
| 661 | onRefetch: (cb) => { |
| 662 | refetches.push(cb); |
| 663 | }, |
| 664 | }); |
| 665 | |
| 666 | try { |
| 667 | this.#options.optimistic({ |
| 668 | ...context, |
| 669 | args, |
| 670 | helpers, |
| 671 | onRestore, |
| 672 | onSuccess(cb) { |
| 673 | if (expired) { |
| 674 | throw new Error( |
| 675 | "Can only call onSuccess from within the optimistic update function.", |
| 676 | ); |
| 677 | } |
| 678 | onSuccess.push(cb); |
| 679 | }, |
| 680 | onRefetch(cb) { |
| 681 | if (expired) { |
| 682 | throw new Error( |
| 683 | "Can only call onRefetch from within the optimistic update function.", |
| 684 | ); |
| 685 | } |
| 686 | refetches.push(cb); |
| 687 | }, |
| 688 | }); |
| 689 | } catch (error) { |
| 690 | expired = true; |
| 691 | // Roll back the rollbacks we just added |
| 692 | let next; |
| 693 | while (next = rollbacks.pop()) next(); |
| 694 | return Promise.reject(error); |
| 695 | } |
| 696 | expired = true; |
| 697 | |
| 698 | // Check for no-op by comparing to initial snapshot |
| 699 | if (this.#options.snapshot) { |
| 700 | const currentSnapshot = this.#options.snapshot.call( |
| 701 | context, |
| 702 | { ...context, args }, |
| 703 | ); |
| 704 | const snapshotToCompare = isFirstDebouncedCall |
| 705 | ? initialSnapshot! |
| 706 | : channel.pendingDebounced?.initialSnapshot; |
| 707 | |
| 708 | if ( |
| 709 | snapshotToCompare !== undefined |
| 710 | && this.client.deepEquals(snapshotToCompare, currentSnapshot) |
| 711 | ) { |
| 712 | // No-op detected - rollback optimistic update |
| 713 | let next; |
| 714 | while (next = rollbacks.pop()) next(); |
| 715 | |
| 716 | // Clear debounce timer |
| 717 | if (channel.debounceTimer !== null) { |
| 718 | clearTimeout(channel.debounceTimer); |
| 719 | channel.debounceTimer = null; |
| 720 | } |
| 721 | |
| 722 | // Clear pending debounced state |
| 723 | channel.pendingDebounced = null; |
| 724 | |
| 725 | // Notify listeners of skipped status |
| 726 | this.#notify(channel, "skipped"); |
| 727 | |
| 728 | // Return resolved promise |
| 729 | return new Promise(() => {}); |
| 730 | } |
| 731 | } |
| 732 | |
| 733 | // Create promise for this call |
| 734 | const { promise, resolve, reject } = Promise.withResolvers<Result>(); |
| 735 | |
| 736 | // Store or update pending debounced state |
| 737 | if (channel.pendingDebounced === null) { |
| 738 | // First debounced call |
| 739 | channel.pendingDebounced = { |
| 740 | args, |
| 741 | context, |
| 742 | rollbacks, |
| 743 | pending: [{ resolve, reject }], |
| 744 | onSuccess, |
| 745 | refetches, |
| 746 | initialSnapshot: isFirstDebouncedCall ? initialSnapshot : undefined, |
| 747 | shouldCallGlobalHandler, |
| 748 | }; |
| 749 | |
| 750 | // An in-flight request picks the call up when it finishes |
| 751 | if (channel.status === "idle") { |
| 752 | channel.status = "waiting"; |
| 753 | this.#notify(channel, "waiting"); |
| 754 | } |
| 755 | } else { |
| 756 | // Subsequent debounced call - update state |
| 757 | channel.pendingDebounced.args = args; |
| 758 | channel.pendingDebounced.context = context; |
| 759 | channel.pendingDebounced.rollbacks = rollbacks; |
| 760 | channel.pendingDebounced.pending.push({ resolve, reject }); |
| 761 | channel.pendingDebounced.onSuccess = onSuccess; |
| 762 | channel.pendingDebounced.refetches = refetches; |
| 763 | channel.pendingDebounced.shouldCallGlobalHandler = shouldCallGlobalHandler; |
| 764 | // Keep the initial snapshot from the first call |
| 765 | // Status stays "waiting" |
| 766 | } |
| 767 | |
| 768 | // Clear existing timer |
| 769 | if (channel.debounceTimer !== null) { |
| 770 | clearTimeout(channel.debounceTimer); |
| 771 | } |
| 772 | |
| 773 | // Start new timer (0ms for immediate execution, debounceMs otherwise) |
| 774 | const delay = shouldExecuteImmediate ? 0 : this.#options.debounceMs!; |
| 775 | channel.debounceTimer = setTimeout(() => { |
| 776 | this.#enqueueDebouncedCall(key, channel); |
| 777 | }, delay); |
| 778 | |
| 779 | return promise; |
| 780 | } |
| 781 | |
| 782 | #rollbackPendingDebounced( |
| 783 | channel: Channel<Args, Result>, |
| 784 | ) { |
| 785 | if (!channel.pendingDebounced) return; |
| 786 | |
| 787 | const { rollbacks } = channel.pendingDebounced; |
| 788 | |
| 789 | // Roll back this call's optimistic updates (in reverse order) |
| 790 | let next; |
| 791 | while (next = rollbacks.pop()) next(); |
| 792 | |
| 793 | // Note: We do NOT reject the promises here |
| 794 | // They will all resolve when the final call completes |
| 795 | } |
| 796 | |
| 797 | #enqueueDebouncedCall( |
| 798 | key: string, |
| 799 | channel: Channel<Args, Result>, |
| 800 | ) { |
| 801 | // Clear timer |
| 802 | channel.debounceTimer = null; |
| 803 | |
| 804 | // Safety check |
| 805 | if (!channel.pendingDebounced) { |
| 806 | this.#setIdle(key, channel); |
| 807 | return; |
| 808 | } |
| 809 | |
| 810 | const { args, context, rollbacks, pending, onSuccess, refetches, shouldCallGlobalHandler } = |
| 811 | channel.pendingDebounced; |
| 812 | channel.pendingDebounced = null; |
| 813 | |
| 814 | // Track execution time for debounceImmediate |
| 815 | if (this.#options.debounceImmediate) { |
| 816 | channel.lastDebouncedExecutionTime = Date.now(); |
| 817 | } |
| 818 | |
| 819 | // Create wrapper resolve/reject that resolves ALL pending promises |
| 820 | const { |
| 821 | promise: wrapperPromise, |
| 822 | resolve: wrapperResolve, |
| 823 | reject: wrapperReject, |
| 824 | } = Promise.withResolvers<Result>(); |
| 825 | |
| 826 | // Resolve/reject pending promises and add global handler logic for execution-time checks |
| 827 | wrapperPromise.then( |
| 828 | (result) => { |
| 829 | // Resolve all pending promises |
| 830 | pending.forEach((p) => p.resolve(result)); |
| 831 | |
| 832 | // Call global handler if needed (based on whether component is watching success) |
| 833 | if (shouldCallGlobalHandler) { |
| 834 | const message = this.describeResult(args, result); |
| 835 | if (message && this.client.reportSuccess) { |
| 836 | this.client.reportSuccess(message); |
| 837 | } |
| 838 | } |
| 839 | }, |
| 840 | (caught) => { |
| 841 | const { error, description = this.describe(...args) } = unwrapMutationError(caught); |
| 842 | |
| 843 | // Reject all pending promises with unwrapped error |
| 844 | pending.forEach((p) => p.reject(error)); |
| 845 | |
| 846 | // Call global handler if needed (based on whether component is watching errors) |
| 847 | if (shouldCallGlobalHandler) { |
| 848 | this.client.reportError( |
| 849 | formatFriendlyError(description, error), |
| 850 | error, |
| 851 | ); |
| 852 | } |
| 853 | }, |
| 854 | ); |
| 855 | |
| 856 | channel.queue.push({ |
| 857 | args, |
| 858 | context, |
| 859 | rollbacks, |
| 860 | refetches, |
| 861 | onSuccess, |
| 862 | resolve: wrapperResolve, |
| 863 | reject: wrapperReject, |
| 864 | }); |
| 865 | |
| 866 | // If queue was idle/waiting, start execution |
| 867 | if (channel.status === "idle" || channel.status === "waiting") { |
| 868 | this.#executeNext(key, channel); |
| 869 | } |
| 870 | // Otherwise, it will execute when the current item finishes |
| 871 | } |
| 872 | |
| 873 | #context(): object { |
| 874 | return { |
| 875 | ...this.client.context, |
| 876 | ...this.client.userContext?.get(), |
| 877 | }; |
| 878 | } |
| 879 | |
| 880 | #reportUnauthenticated(options: RunOptions<Result>, args: Args) { |
| 881 | const handler = options.onUnauthenticated ?? this.client.handleUnauthenticated; |
| 882 | handler?.call( |
| 883 | this.client, |
| 884 | // Reached only for `auth: true`, whose arguments the define-time guard |
| 885 | // constrains to be serializable. |
| 886 | { id: this.#options.id, description: this.describe(...args), args: args as SerializableValue[] }, |
| 887 | this as unknown as Mutation<SerializableValue[], unknown>, |
| 888 | ); |
| 889 | } |
| 890 | |
| 891 | #getOrPutChannel(key: string) { |
| 892 | let channel = this.#channels.get(key); |
| 893 | if (!channel) { |
| 894 | channel = { |
| 895 | listeners: new Set(), |
| 896 | status: "idle", |
| 897 | queue: [], |
| 898 | debounceTimer: null, |
| 899 | pendingDebounced: null, |
| 900 | lastDebouncedExecutionTime: null, |
| 901 | }; |
| 902 | this.#channels.set(key, channel); |
| 903 | } |
| 904 | return channel; |
| 905 | } |
| 906 | } |
| 907 | |
| 908 | export function formatFriendlyError( |
| 909 | description: string | null, |
| 910 | error: unknown, |
| 911 | ) { |
| 912 | if (!description || !description[0]) return `Something went wrong: ${errMessage(error)}`; |
| 913 | description = description[0].toLowerCase() + description.slice(1); |
| 914 | return `Could not ${description}: ${errMessage(error)}`; |
| 915 | } |