| ... | @@ -1,13 +1,12 @@ | ... | @@ -1,13 +1,12 @@ |
| 1 | import { message as errMessage } from "@clo/lib/error.ts"; | 1 | import { message as errMessage } from "@clo/lib/error.ts"; |
| 2 | import type { MutationClientFromConfig, Reactive } from "./client.ts"; | 2 | import type { MutationClient, MutationClientConfig, Reactive } from "./client.ts"; |
| 3 | import type { MutationClientConfig } from "./client.ts"; | 3 | import type { MutationEvent, RunOptions, SerializableValue } from "./types.ts"; |
| 4 | import type { Mutation, MutationEvent, RunOptions, SerializableValue } from "./types.ts"; | | |
| 5 | | 4 | |
| 6 | /** | 5 | /** |
| 7 | * Argument to `defineBlocking`. | 6 | * Argument to `MutationClient.define`. |
| 8 | * @template Args - the parameters to the mutation | 7 | * @template Args - the parameters to the mutation |
| 9 | * @template Result - the result of the API call | 8 | * @template Result - the result of the API call |
| 10 | * @template Config - global values and helpers from `MutationContext` | 9 | * @template Config - global values and helpers from `MutationClient` |
| 11 | */ | 10 | */ |
| 12 | export interface MutationOptions< | 11 | export interface MutationOptions< |
| 13 | Args extends unknown[], | 12 | Args extends unknown[], |
| ... | @@ -119,11 +118,11 @@ export type OptimisticContext< | ... | @@ -119,11 +118,11 @@ export type OptimisticContext< |
| 119 | onRefetch: (cb: () => Promise<void>) => void; | 118 | onRefetch: (cb: () => Promise<void>) => void; |
| 120 | }; | 119 | }; |
| 121 | | 120 | |
| 122 | interface PendingDebouncedState<Args extends unknown[], Result, Context> { | 121 | interface PendingDebouncedState<Args extends unknown[], Result> { |
| 123 | /** Arguments from the most recent call */ | 122 | /** Arguments from the most recent call */ |
| 124 | args: Args; | 123 | args: Args; |
| 125 | /** Context captured when the most recent call was allowed */ | 124 | /** Context captured when the most recent call was allowed */ |
| 126 | context: Context; | 125 | context: object; |
| 127 | /** Restores registered by the most recent call */ | 126 | /** Restores registered by the most recent call */ |
| 128 | rollbacks: Array<() => void>; | 127 | rollbacks: Array<() => void>; |
| 129 | /** All pending promises from all superseded calls */ | 128 | /** All pending promises from all superseded calls */ |
| ... | @@ -159,20 +158,20 @@ function unwrapMutationError(caught: unknown) { | ... | @@ -159,20 +158,20 @@ function unwrapMutationError(caught: unknown) { |
| 159 | return { error: caught, description: null }; | 158 | return { error: caught, description: null }; |
| 160 | } | 159 | } |
| 161 | | 160 | |
| 162 | interface Channel<Args extends unknown[], Result, Context> { | 161 | interface Channel<Args extends unknown[], Result> { |
| 163 | listeners: Set<(update: MutationEvent<Result>) => void>; | 162 | listeners: Set<(update: MutationEvent<Result>) => void>; |
| 164 | status: "idle" | "waiting" | "mutating" | "refetching" | "skipped"; | 163 | status: "idle" | "waiting" | "mutating" | "refetching" | "skipped"; |
| 165 | queue: Array<Item<Args, Result, Context>>; | 164 | queue: Array<Item<Args, Result>>; |
| 166 | // Debounce state (only used if debounce option is set) | 165 | // Debounce state (only used if debounce option is set) |
| 167 | debounceTimer: ReturnType<typeof setTimeout> | null; | 166 | debounceTimer: ReturnType<typeof setTimeout> | null; |
| 168 | pendingDebounced: PendingDebouncedState<Args, Result, Context> | null; | 167 | pendingDebounced: PendingDebouncedState<Args, Result> | null; |
| 169 | // Track when last debounced mutation executed (for debounceImmediate) | 168 | // Track when last debounced mutation executed (for debounceImmediate) |
| 170 | lastDebouncedExecutionTime: number | null; | 169 | lastDebouncedExecutionTime: number | null; |
| 171 | } | 170 | } |
| 172 | | 171 | |
| 173 | interface Item<Args extends unknown[], Result, Context> { | 172 | interface Item<Args extends unknown[], Result> { |
| 174 | args: Args; | 173 | args: Args; |
| 175 | context: Context; | 174 | context: object; |
| 176 | rollbacks: Array<() => void>; | 175 | rollbacks: Array<() => void>; |
| 177 | refetches: Array<() => Promise<void>>; | 176 | refetches: Array<() => Promise<void>>; |
| 178 | onSuccess: Array<(result: Result) => void>; | 177 | onSuccess: Array<(result: Result) => void>; |
| ... | @@ -180,59 +179,37 @@ interface Item<Args extends unknown[], Result, Context> { | ... | @@ -180,59 +179,37 @@ interface Item<Args extends unknown[], Result, Context> { |
| 180 | reject: (error: unknown) => void; | 179 | reject: (error: unknown) => void; |
| 181 | } | 180 | } |
| 182 | | 181 | |
| 183 | export class BlockingMutation< | 182 | /** A mutation defined with `MutationClient.define`. */ |
| 184 | Args extends unknown[], | 183 | export class Mutation<Args extends unknown[], Result> { |
| 185 | Result, | 184 | readonly client: MutationClient<object, object, object, string>; |
| 186 | Auth extends boolean | string, | 185 | #options: MutationOptions<Args, Result, boolean | string, MutationClientConfig>; |
| 187 | Config extends MutationClientConfig, | 186 | #channels: Map<string, Channel<Args, Result>> = new Map(); |
| 188 | > implements Mutation<Args, Result> { | | |
| 189 | #options: MutationOptions<Args, Result, Auth, Config>; | | |
| 190 | #client: MutationClientFromConfig<Config>; | | |
| 191 | #channels: Map< | | |
| 192 | string, | | |
| 193 | Channel<Args, Result, Context<Config, Auth>> | | |
| 194 | > = new Map(); | | |
| 195 | client: MutationClientFromConfig<Config>; | | |
| 196 | | 187 | |
| 197 | constructor( | 188 | constructor( |
| 198 | client: MutationClientFromConfig<Config>, | 189 | client: MutationClient<object, object, object, string>, |
| 199 | options: MutationOptions<Args, Result, Auth, Config>, | 190 | options: MutationOptions<Args, Result, boolean | string, MutationClientConfig>, |
| 200 | ) { | 191 | ) { |
| 201 | this.#options = options; | | |
| 202 | this.#client = client; | | |
| 203 | this.client = client; | 192 | this.client = client; |
| | 193 | this.#options = options; |
| 204 | } | 194 | } |
| 205 | | 195 | |
| | 196 | /** Unique identifier passed to `define`. */ |
| 206 | get id(): string { | 197 | get id(): string { |
| 207 | return this.#options.id; | 198 | return this.#options.id; |
| 208 | } | 199 | } |
| 209 | | 200 | |
| 210 | #context(): Context<Config, Auth> { | 201 | /** |
| 211 | return { | 202 | * `true` when an `auth: true` mutation has no user available. Scoped |
| 212 | ...this.#client.context, | 203 | * mutations are excluded; they disable instead of routing to the sign-in flow. |
| 213 | ...(this.#client.userContext?.get() ?? {}), | 204 | */ |
| 214 | } as Context<Config, Auth>; | | |
| 215 | } | | |
| 216 | | | |
| 217 | #reportUnauthenticated(options: RunOptions<Result>, args: Args) { | | |
| 218 | const handler = options.onUnauthenticated ?? this.#client.handleUnauthenticated; | | |
| 219 | handler?.call( | | |
| 220 | this.#client, | | |
| 221 | // Reached only for `auth: true`, whose arguments the define-time guard | | |
| 222 | // constrains to be serializable. | | |
| 223 | { id: this.#options.id, description: this.describe(...args), args: args as SerializableValue[] }, | | |
| 224 | this as unknown as Mutation<SerializableValue[], unknown>, | | |
| 225 | ); | | |
| 226 | } | | |
| 227 | | | |
| 228 | isUnauthenticated(): boolean { | 205 | isUnauthenticated(): boolean { |
| 229 | return this.#options.auth === true && this.#client.userContext?.get() == null; | 206 | return this.#options.auth === true && this.client.userContext?.get() == null; |
| 230 | } | 207 | } |
| 231 | | 208 | |
| 232 | isAllowed(): boolean { | 209 | isAllowed(): boolean { |
| 233 | const { auth } = this.#options; | 210 | const { auth } = this.#options; |
| 234 | if (auth !== undefined && auth !== false && this.#client.userContext?.get() == null) return false; | 211 | if (auth !== undefined && auth !== false && this.client.userContext?.get() == null) return false; |
| 235 | if (typeof auth === "string" && !(this.#client.authScopes?.[auth]?.get() ?? false)) return false; | 212 | if (typeof auth === "string" && !(this.client.authScopes?.[auth]?.get() ?? false)) return false; |
| 236 | return this.#options.isAllowed?.get() ?? true; | 213 | return this.#options.isAllowed?.get() ?? true; |
| 237 | } | 214 | } |
| 238 | | 215 | |
| ... | @@ -240,33 +217,19 @@ export class BlockingMutation< | ... | @@ -240,33 +217,19 @@ export class BlockingMutation< |
| 240 | const { auth } = this.#options; | 217 | const { auth } = this.#options; |
| 241 | const unsubscribes = [ | 218 | const unsubscribes = [ |
| 242 | this.#options.isAllowed?.sub(cb), | 219 | this.#options.isAllowed?.sub(cb), |
| 243 | typeof auth === "string" ? this.#client.authScopes?.[auth]?.sub(cb) : undefined, | 220 | typeof auth === "string" ? this.client.authScopes?.[auth]?.sub(cb) : undefined, |
| 244 | ]; | 221 | ]; |
| 245 | return () => unsubscribes.forEach((unsubscribe) => unsubscribe?.()); | 222 | return () => unsubscribes.forEach((unsubscribe) => unsubscribe?.()); |
| 246 | } | 223 | } |
| 247 | | 224 | |
| 248 | key(args: Args) { | 225 | /** Returns the concurrency key used for a given set of arguments */ |
| | 226 | key(args: Args): string { |
| 249 | const k = this.#options.key?.({ ...this.#context(), args }) | 227 | const k = this.#options.key?.({ ...this.#context(), args }) |
| 250 | ?? "shared"; | 228 | ?? "shared"; |
| 251 | return JSON.stringify(k); | 229 | return JSON.stringify(k); |
| 252 | } | 230 | } |
| 253 | | 231 | |
| 254 | #getOrPutChannel(key: string) { | 232 | /** Subscribe to status changes using the key from `key()` */ |
| 255 | let channel = this.#channels.get(key); | | |
| 256 | if (!channel) { | | |
| 257 | channel = { | | |
| 258 | listeners: new Set(), | | |
| 259 | status: "idle", | | |
| 260 | queue: [], | | |
| 261 | debounceTimer: null, | | |
| 262 | pendingDebounced: null, | | |
| 263 | lastDebouncedExecutionTime: null, | | |
| 264 | }; | | |
| 265 | this.#channels.set(key, channel); | | |
| 266 | } | | |
| 267 | return channel; | | |
| 268 | } | | |
| 269 | | | |
| 270 | subscribe( | 233 | subscribe( |
| 271 | key: string, | 234 | key: string, |
| 272 | cb: (update: MutationEvent<Result>) => void, | 235 | cb: (update: MutationEvent<Result>) => void, |
| ... | @@ -276,41 +239,6 @@ export class BlockingMutation< | ... | @@ -276,41 +239,6 @@ export class BlockingMutation< |
| 276 | return () => channel?.listeners.delete(cb); | 239 | return () => channel?.listeners.delete(cb); |
| 277 | } | 240 | } |
| 278 | | 241 | |
| 279 | #notify( | | |
| 280 | channel: Channel<Args, Result, Context<Config, Auth>>, | | |
| 281 | status: MutationEvent<Result>["status"], | | |
| 282 | result: Result | null = null, | | |
| 283 | error: unknown = null, | | |
| 284 | ) { | | |
| 285 | const event: MutationEvent<Result> = { status, result, error, debounced: this.#options.debounceMs !== undefined }; | | |
| 286 | channel.listeners.forEach((cb) => cb(event)); | | |
| 287 | } | | |
| 288 | | | |
| 289 | #setIdle( | | |
| 290 | key: string, | | |
| 291 | channel: Channel<Args, Result, Context<Config, Auth>>, | | |
| 292 | ) { | | |
| 293 | // Check if there are pending debounced calls waiting | | |
| 294 | if (channel.pendingDebounced !== null) { | | |
| 295 | // Stay in waiting state | | |
| 296 | channel.status = "waiting"; | | |
| 297 | this.#notify(channel, "waiting", null, null); | | |
| 298 | } else { | | |
| 299 | // Normal idle transition | | |
| 300 | channel.status = "idle"; | | |
| 301 | this.#notify(channel, "idle", null, null); | | |
| 302 | // Clean up the channel if there are no listeners | | |
| 303 | if (channel.listeners.size === 0) { | | |
| 304 | // Clear any pending timers before deleting the channel | | |
| 305 | if (channel.debounceTimer !== null) { | | |
| 306 | clearTimeout(channel.debounceTimer); | | |
| 307 | channel.debounceTimer = null; | | |
| 308 | } | | |
| 309 | this.#channels.delete(key); | | |
| 310 | } | | |
| 311 | } | | |
| 312 | } | | |
| 313 | | | |
| 314 | describe(...args: Args): string { | 242 | describe(...args: Args): string { |
| 315 | const { describe } = this.#options; | 243 | const { describe } = this.#options; |
| 316 | return typeof describe === "function" | 244 | return typeof describe === "function" |
| ... | @@ -327,58 +255,13 @@ export class BlockingMutation< | ... | @@ -327,58 +255,13 @@ export class BlockingMutation< |
| 327 | } | 255 | } |
| 328 | | 256 | |
| 329 | /** Calling the mutation in a global scope. Errors are turned into UI toasts. */ | 257 | /** Calling the mutation in a global scope. Errors are turned into UI toasts. */ |
| 330 | run(...args: Args) { | 258 | run(...args: Args): void { |
| 331 | this.runWithOptions(...args, {}); | 259 | this.runWithOptions(...args, {}); |
| 332 | } | 260 | } |
| 333 | | 261 | |
| 334 | /** | | |
| 335 | * Using this in any situation is likely incorrect. Use {@linkcode runWithOptions} | | |
| 336 | * to handle success and error. | | |
| 337 | * | | |
| 338 | * By using this, you must handle the success and error conditions of the | | |
| 339 | * promise, or else the user will never see the result on screen. If the | | |
| 340 | * mutation has snapshots, be aware that cancelled mutations are implemented | | |
| 341 | * with promises that never resolve. | | |
| 342 | */ | | |
| 343 | runAsHeadlessPromise(...array: [...Args, RunOptions<Result>]): Promise<Result> { | | |
| 344 | if (!this.#client.enabled) { | | |
| 345 | throw new Error( | | |
| 346 | "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?", | | |
| 347 | ); | | |
| 348 | } | | |
| 349 | | | |
| 350 | const args = array.slice() as Args; | | |
| 351 | const options = args.pop() as RunOptions<Result>; | | |
| 352 | const { onSuccessUi: onSuccess, onSuccessData, onError, onSettled, onRestore } = options; | | |
| 353 | | | |
| 354 | if (!this.isAllowed()) { | | |
| 355 | if (this.isUnauthenticated()) { | | |
| 356 | this.#reportUnauthenticated(options, args); | | |
| 357 | return Promise.reject(new Error("Mutation requires authentication.")); | | |
| 358 | } | | |
| 359 | return Promise.reject(new Error("Mutation is not allowed.")); | | |
| 360 | } | | |
| 361 | | | |
| 362 | const promise = this.#runWithOptions(args, onRestore, true); | | |
| 363 | return promise.then((result) => { | | |
| 364 | // Call user handlers | | |
| 365 | onSuccess?.(result); | | |
| 366 | onSuccessData?.(result); | | |
| 367 | onSettled?.({ status: "success", result }); | | |
| 368 | return result; | | |
| 369 | }).catch((caught: unknown) => { | | |
| 370 | const { error } = unwrapMutationError(caught); | | |
| 371 | | | |
| 372 | onError?.(error); | | |
| 373 | onSettled?.({ status: "error", error }); | | |
| 374 | | | |
| 375 | throw error; | | |
| 376 | }); | | |
| 377 | } | | |
| 378 | | | |
| 379 | /** Calls the mutation with custom handlers that can suppress global handlers. */ | 262 | /** Calls the mutation with custom handlers that can suppress global handlers. */ |
| 380 | runWithOptions(...array: [...Args, RunOptions<Result>]): void { | 263 | runWithOptions(...array: [...args: Args, options: RunOptions<Result>]): void { |
| 381 | if (!this.#client.enabled) { | 264 | if (!this.client.enabled) { |
| 382 | throw new Error( | 265 | throw new Error( |
| 383 | "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?", | 266 | "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?", |
| 384 | ); | 267 | ); |
| ... | @@ -396,7 +279,7 @@ export class BlockingMutation< | ... | @@ -396,7 +279,7 @@ export class BlockingMutation< |
| 396 | onError?.(error); | 279 | onError?.(error); |
| 397 | onSettled?.({ status: "error", error }); | 280 | onSettled?.({ status: "error", error }); |
| 398 | if (!onError) { | 281 | if (!onError) { |
| 399 | this.#client.reportError(formatFriendlyError(this.describe(...args), error), error); | 282 | this.client.reportError(formatFriendlyError(this.describe(...args), error), error); |
| 400 | } | 283 | } |
| 401 | return; | 284 | return; |
| 402 | } | 285 | } |
| ... | @@ -415,8 +298,8 @@ export class BlockingMutation< | ... | @@ -415,8 +298,8 @@ export class BlockingMutation< |
| 415 | // Call global handler unless suppressed | 298 | // Call global handler unless suppressed |
| 416 | if (!suppressGlobalSuccess) { | 299 | if (!suppressGlobalSuccess) { |
| 417 | const message = this.describeResult(args, result); | 300 | const message = this.describeResult(args, result); |
| 418 | if (message && this.#client.reportSuccess) { | 301 | if (message && this.client.reportSuccess) { |
| 419 | this.#client.reportSuccess(message); | 302 | this.client.reportSuccess(message); |
| 420 | } | 303 | } |
| 421 | } | 304 | } |
| 422 | }).catch((caught: unknown) => { | 305 | }).catch((caught: unknown) => { |
| ... | @@ -427,8 +310,53 @@ export class BlockingMutation< | ... | @@ -427,8 +310,53 @@ export class BlockingMutation< |
| 427 | | 310 | |
| 428 | // Call global handler unless suppressed | 311 | // Call global handler unless suppressed |
| 429 | if (!suppressGlobalError) { | 312 | if (!suppressGlobalError) { |
| 430 | this.#client.reportError(formatFriendlyError(description, error), error); | 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.")); |
| 431 | } | 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; |
| 432 | }); | 360 | }); |
| 433 | } | 361 | } |
| 434 | | 362 | |
| ... | @@ -437,7 +365,7 @@ export class BlockingMutation< | ... | @@ -437,7 +365,7 @@ export class BlockingMutation< |
| 437 | userOnRestore: RunOptions<Result>["onRestore"], | 365 | userOnRestore: RunOptions<Result>["onRestore"], |
| 438 | suppressGlobalHandlers: boolean, | 366 | suppressGlobalHandlers: boolean, |
| 439 | ): Promise<Result> { | 367 | ): Promise<Result> { |
| 440 | if (!this.#client.enabled) { | 368 | if (!this.client.enabled) { |
| 441 | throw new Error( | 369 | throw new Error( |
| 442 | "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?", | 370 | "MutationClient was passed enabled: false. Are you trying to perform a mutation from SSR?", |
| 443 | ); | 371 | ); |
| ... | @@ -489,7 +417,7 @@ export class BlockingMutation< | ... | @@ -489,7 +417,7 @@ export class BlockingMutation< |
| 489 | } | 417 | } |
| 490 | | 418 | |
| 491 | // Per call, so restores, refetches and refetch dedupe belong to this call | 419 | // Per call, so restores, refetches and refetch dedupe belong to this call |
| 492 | const helpers = this.#client.getOptimisticHelpers({ | 420 | const helpers = this.client.getOptimisticHelpers({ |
| 493 | onRestore: (cb) => { | 421 | onRestore: (cb) => { |
| 494 | rollbacks.push(cb); | 422 | rollbacks.push(cb); |
| 495 | }, | 423 | }, |
| ... | @@ -535,7 +463,7 @@ export class BlockingMutation< | ... | @@ -535,7 +463,7 @@ export class BlockingMutation< |
| 535 | context, | 463 | context, |
| 536 | { ...context, args }, | 464 | { ...context, args }, |
| 537 | ); | 465 | ); |
| 538 | const isNoOp = this.#client.deepEquals(beforeSnapshot, afterSnapshot); | 466 | const isNoOp = this.client.deepEquals(beforeSnapshot, afterSnapshot); |
| 539 | | 467 | |
| 540 | if (isNoOp) { | 468 | if (isNoOp) { |
| 541 | let next; | 469 | let next; |
| ... | @@ -566,9 +494,44 @@ export class BlockingMutation< | ... | @@ -566,9 +494,44 @@ export class BlockingMutation< |
| 566 | return promise; | 494 | return promise; |
| 567 | } | 495 | } |
| 568 | | 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 | |
| 569 | #executeNext( | 532 | #executeNext( |
| 570 | key: string, | 533 | key: string, |
| 571 | channel: Channel<Args, Result, Context<Config, Auth>>, | 534 | channel: Channel<Args, Result>, |
| 572 | ) { | 535 | ) { |
| 573 | const item = channel.queue.shift(); | 536 | const item = channel.queue.shift(); |
| 574 | if (!item) { | 537 | if (!item) { |
| ... | @@ -594,7 +557,7 @@ export class BlockingMutation< | ... | @@ -594,7 +557,7 @@ export class BlockingMutation< |
| 594 | results.forEach((result) => { | 557 | results.forEach((result) => { |
| 595 | if (result.status === "rejected") { | 558 | if (result.status === "rejected") { |
| 596 | const message = `Failed to refetch data: ${errMessage(result.reason)}`; | 559 | const message = `Failed to refetch data: ${errMessage(result.reason)}`; |
| 597 | this.#client.reportError(message, result.reason); | 560 | this.client.reportError(message, result.reason); |
| 598 | } | 561 | } |
| 599 | }); | 562 | }); |
| 600 | }, | 563 | }, |
| ... | @@ -637,7 +600,7 @@ export class BlockingMutation< | ... | @@ -637,7 +600,7 @@ export class BlockingMutation< |
| 637 | results.forEach((result) => { | 600 | results.forEach((result) => { |
| 638 | if (result.status === "rejected") { | 601 | if (result.status === "rejected") { |
| 639 | const message = `Failed to refetch data: ${errMessage(result.reason)}`; | 602 | const message = `Failed to refetch data: ${errMessage(result.reason)}`; |
| 640 | this.#client.reportError(message, result.reason); | 603 | this.client.reportError(message, result.reason); |
| 641 | } | 604 | } |
| 642 | }); | 605 | }); |
| 643 | }).finally(() => { | 606 | }).finally(() => { |
| ... | @@ -651,8 +614,8 @@ export class BlockingMutation< | ... | @@ -651,8 +614,8 @@ export class BlockingMutation< |
| 651 | #runDebouncedAndReturn( | 614 | #runDebouncedAndReturn( |
| 652 | args: Args, | 615 | args: Args, |
| 653 | key: string, | 616 | key: string, |
| 654 | channel: Channel<Args, Result, Context<Config, Auth>>, | 617 | channel: Channel<Args, Result>, |
| 655 | context: Context<Config, Auth>, | 618 | context: object, |
| 656 | userOnRestore: (() => void) | undefined, | 619 | userOnRestore: (() => void) | undefined, |
| 657 | shouldExecuteImmediate: boolean, | 620 | shouldExecuteImmediate: boolean, |
| 658 | shouldCallGlobalHandler: boolean, | 621 | shouldCallGlobalHandler: boolean, |
| ... | @@ -672,7 +635,6 @@ export class BlockingMutation< | ... | @@ -672,7 +635,6 @@ export class BlockingMutation< |
| 672 | this.#rollbackPendingDebounced(channel); | 635 | this.#rollbackPendingDebounced(channel); |
| 673 | } | 636 | } |
| 674 | | 637 | |
| 675 | // Apply optimistic update (same logic as current runAndReturn) | | |
| 676 | const onSuccess: Array<(result: Result) => void> = []; | 638 | const onSuccess: Array<(result: Result) => void> = []; |
| 677 | let expired = false; | 639 | let expired = false; |
| 678 | const rollbacks: Array<() => void> = []; | 640 | const rollbacks: Array<() => void> = []; |
| ... | @@ -692,7 +654,7 @@ export class BlockingMutation< | ... | @@ -692,7 +654,7 @@ export class BlockingMutation< |
| 692 | } | 654 | } |
| 693 | | 655 | |
| 694 | // Per call, so restores, refetches and refetch dedupe belong to this call | 656 | // Per call, so restores, refetches and refetch dedupe belong to this call |
| 695 | const helpers = this.#client.getOptimisticHelpers({ | 657 | const helpers = this.client.getOptimisticHelpers({ |
| 696 | onRestore: (cb) => { | 658 | onRestore: (cb) => { |
| 697 | rollbacks.push(cb); | 659 | rollbacks.push(cb); |
| 698 | }, | 660 | }, |
| ... | @@ -745,7 +707,7 @@ export class BlockingMutation< | ... | @@ -745,7 +707,7 @@ export class BlockingMutation< |
| 745 | | 707 | |
| 746 | if ( | 708 | if ( |
| 747 | snapshotToCompare !== undefined | 709 | snapshotToCompare !== undefined |
| 748 | && this.#client.deepEquals(snapshotToCompare, currentSnapshot) | 710 | && this.client.deepEquals(snapshotToCompare, currentSnapshot) |
| 749 | ) { | 711 | ) { |
| 750 | // No-op detected - rollback optimistic update | 712 | // No-op detected - rollback optimistic update |
| 751 | let next; | 713 | let next; |
| ... | @@ -818,7 +780,7 @@ export class BlockingMutation< | ... | @@ -818,7 +780,7 @@ export class BlockingMutation< |
| 818 | } | 780 | } |
| 819 | | 781 | |
| 820 | #rollbackPendingDebounced( | 782 | #rollbackPendingDebounced( |
| 821 | channel: Channel<Args, Result, Context<Config, Auth>>, | 783 | channel: Channel<Args, Result>, |
| 822 | ) { | 784 | ) { |
| 823 | if (!channel.pendingDebounced) return; | 785 | if (!channel.pendingDebounced) return; |
| 824 | | 786 | |
| ... | @@ -834,7 +796,7 @@ export class BlockingMutation< | ... | @@ -834,7 +796,7 @@ export class BlockingMutation< |
| 834 | | 796 | |
| 835 | #enqueueDebouncedCall( | 797 | #enqueueDebouncedCall( |
| 836 | key: string, | 798 | key: string, |
| 837 | channel: Channel<Args, Result, Context<Config, Auth>>, | 799 | channel: Channel<Args, Result>, |
| 838 | ) { | 800 | ) { |
| 839 | // Clear timer | 801 | // Clear timer |
| 840 | channel.debounceTimer = null; | 802 | channel.debounceTimer = null; |
| ... | @@ -870,8 +832,8 @@ export class BlockingMutation< | ... | @@ -870,8 +832,8 @@ export class BlockingMutation< |
| 870 | // Call global handler if needed (based on whether component is watching success) | 832 | // Call global handler if needed (based on whether component is watching success) |
| 871 | if (shouldCallGlobalHandler) { | 833 | if (shouldCallGlobalHandler) { |
| 872 | const message = this.describeResult(args, result); | 834 | const message = this.describeResult(args, result); |
| 873 | if (message && this.#client.reportSuccess) { | 835 | if (message && this.client.reportSuccess) { |
| 874 | this.#client.reportSuccess(message); | 836 | this.client.reportSuccess(message); |
| 875 | } | 837 | } |
| 876 | } | 838 | } |
| 877 | }, | 839 | }, |
| ... | @@ -883,7 +845,7 @@ export class BlockingMutation< | ... | @@ -883,7 +845,7 @@ export class BlockingMutation< |
| 883 | | 845 | |
| 884 | // Call global handler if needed (based on whether component is watching errors) | 846 | // Call global handler if needed (based on whether component is watching errors) |
| 885 | if (shouldCallGlobalHandler) { | 847 | if (shouldCallGlobalHandler) { |
| 886 | this.#client.reportError( | 848 | this.client.reportError( |
| 887 | formatFriendlyError(description, error), | 849 | formatFriendlyError(description, error), |
| 888 | error, | 850 | error, |
| 889 | ); | 851 | ); |
| ... | @@ -891,7 +853,6 @@ export class BlockingMutation< | ... | @@ -891,7 +853,6 @@ export class BlockingMutation< |
| 891 | }, | 853 | }, |
| 892 | ); | 854 | ); |
| 893 | | 855 | |
| 894 | // Add to queue (same structure as regular blocking mutation) | | |
| 895 | channel.queue.push({ | 856 | channel.queue.push({ |
| 896 | args, | 857 | args, |
| 897 | context, | 858 | context, |
| ... | @@ -908,6 +869,40 @@ export class BlockingMutation< | ... | @@ -908,6 +869,40 @@ export class BlockingMutation< |
| 908 | } | 869 | } |
| 909 | // Otherwise, it will execute when the current item finishes | 870 | // Otherwise, it will execute when the current item finishes |
| 910 | } | 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 | } |
| 911 | } | 906 | } |
| 912 | | 907 | |
| 913 | export function formatFriendlyError( | 908 | export function formatFriendlyError( |