@mmstack/resource 19.6.5 → 19.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -279,6 +279,22 @@ mutationResource(
279
279
 
280
280
  The `TCTX` returned from `onMutate` flows into `onError` / `onSuccess` / `onSettled`. The optional `initialCtx` second arg to `.mutate(value, initialCtx)` flows into `onMutate` as its second argument.
281
281
 
282
+ ### Awaiting a mutation (`mutateAsync`)
283
+
284
+ `.mutate()` is fire-and-forget. When you need to `await` the outcome — a form submit handler, an async validator — use `.mutateAsync()`, which returns a `Promise` that resolves with the result or rejects with the error. The lifecycle hooks still run exactly as with `.mutate()`.
285
+
286
+ ```typescript
287
+ try {
288
+ const saved = await createPost.mutateAsync(post);
289
+ router.navigate(['/posts', saved.id]);
290
+ } catch (e) {
291
+ if (e instanceof MutationCancelledError) return; // never ran — see below
292
+ toast.error('Failed to save');
293
+ }
294
+ ```
295
+
296
+ If the mutation never completes — superseded by a newer one (latest-wins), dropped from the queue (`clearQueue()` / a `key` change), abandoned on `destroy()`, or its `request()` returned `undefined` — the promise rejects with a `MutationCancelledError` whose `.type` (`MutationCancellationReason`) tells you which. Awaiters that don't expect cancellation should rethrow it. (Plain `.mutate()` has no promise, so it never produces an unhandled rejection.)
297
+
282
298
  ### Queuing
283
299
 
284
300
  By default, calling `.mutate()` while another mutation is in flight starts immediately — concurrent mutations run in parallel. With `queue: true`, mutations are serialized:
@@ -316,13 +332,42 @@ mutationResource(request, { triggerOnSameRequest: true });
316
332
 
317
333
  A mutation also honours the `register` option — but it registers the **mutation ref itself** into the transition scope (its internal query is never registered), so a `<mm-suspense>`/transition reacts to the mutation's own `pending` state. See [transitions & Suspense](#transitions--suspense).
318
334
 
335
+ ### File uploads & progress (`multipart/form-data`)
336
+
337
+ There's no special upload API — return a `FormData` body and `HttpClient` sets the `multipart/form-data` boundary for you. Opt into upload progress with `reportProgress: true` and read the `progress` signal (an `HttpProgressEvent`).
338
+
339
+ ```typescript
340
+ const upload = mutationResource<UploadResult, UploadResult, FormData>((form) => ({
341
+ url: '/api/upload',
342
+ method: 'POST',
343
+ body: form,
344
+ reportProgress: true, // opt in to progress events
345
+ }));
346
+
347
+ // trigger it:
348
+ const form = new FormData();
349
+ form.append('file', file);
350
+ upload.mutate(form);
351
+
352
+ // derive a percentage in a computed / template:
353
+ readonly pct = computed(() => {
354
+ const p = upload.progress();
355
+ return p?.total ? Math.round((p.loaded / p.total) * 100) : null;
356
+ });
357
+ ```
358
+
359
+ `FormData`, `File`, and `Blob` bodies are hashed structurally for dedup/cache keys (a `File` by name + type + size + lastModified), so distinct files never collide. To re-upload the **same** file while one is already in flight, pair it with `triggerOnSameRequest: true`.
360
+
319
361
  ### Return shape (`MutationResourceRef<T, TMutation>`)
320
362
 
321
- | Member | Type | Notes |
322
- | --------------------------------------------- | --------------------------- | ------------------------------------------------------ |
323
- | `mutate` | `(value, ctx?) => void` | Trigger the mutation. |
324
- | `current` | `Signal<TMutation \| null>` | The value currently being mutated (or `null` if idle). |
325
- | `status` / `error` / `isLoading` / `disabled` | as in `QueryResourceRef` | |
363
+ | Member | Type | Notes |
364
+ | --------------------------------------------- | ------------------------------------------ | ------------------------------------------------------ |
365
+ | `mutate` | `(value, ctx?) => void` | Trigger the mutation (fire-and-forget). |
366
+ | `mutateAsync` | `(value, ctx?) => Promise<TResult>` | Trigger and `await` the result; rejects with the error or a `MutationCancelledError`. |
367
+ | `current` | `Signal<TMutation \| null>` | The value currently being mutated (or `null` if idle). |
368
+ | `progress` | `Signal<HttpProgressEvent \| undefined>` | Upload/download progress when `reportProgress: true`. |
369
+ | `status` / `error` / `isLoading` / `disabled` | as in `QueryResourceRef` | – |
370
+ | `headers` / `statusCode` | as in `QueryResourceRef` | Response metadata, when available. |
326
371
 
327
372
  (Mutations deliberately don't expose `value`, `hasValue`, `set`, `update`, or `prefetch` — those don't make sense for one-off writes.)
328
373
 
@@ -2359,6 +2359,23 @@ function manualQueryResource(request, options) {
2359
2359
  }
2360
2360
 
2361
2361
  const NULL_VALUE = Symbol('@mmstack/resource:null');
2362
+ /**
2363
+ * Rejection reason for a {@link MutationResourceRef.mutateAsync} promise whose
2364
+ * mutation never completed. The {@link MutationCancelledError.type} discriminant
2365
+ * carries the cause ({@link MutationCancellationReason}); the message is a
2366
+ * human-readable elaboration of it.
2367
+ *
2368
+ * Only `mutateAsync` promises reject with this; plain `mutate()` calls have no
2369
+ * promise and so produce no (potentially unhandled) rejection.
2370
+ */
2371
+ class MutationCancelledError extends Error {
2372
+ type;
2373
+ constructor(type, message) {
2374
+ super(message);
2375
+ this.type = type;
2376
+ this.name = 'MutationCancelledError';
2377
+ }
2378
+ }
2362
2379
  const MUTATION_RESOURCE_OPTIONS = new InjectionToken('@mmstack/resource:mutation-resource-options', { factory: () => ({}) });
2363
2380
  /**
2364
2381
  * Layer 2 (mutation): default options for every `mutationResource`, inheriting + overriding the
@@ -2372,55 +2389,6 @@ function injectMutationResourceOptions(injector) {
2372
2389
  ? injector.get(MUTATION_RESOURCE_OPTIONS)
2373
2390
  : inject(MUTATION_RESOURCE_OPTIONS);
2374
2391
  }
2375
- /**
2376
- * Creates a resource for performing mutations (e.g., POST, PUT, PATCH, DELETE requests).
2377
- * Unlike `queryResource`, `mutationResource` is designed for one-off operations that change data.
2378
- * It does *not* cache responses and does not provide a `value` signal. Instead, it focuses on
2379
- * managing the mutation lifecycle (pending, error, success) and provides callbacks for handling
2380
- * these states.
2381
- *
2382
- * @param request A function that returns the base `HttpResourceRequest` to be made. This function is called reactively. The parameter is the mutation value provided by the `mutate` method.
2383
- * @param options Configuration options for the mutation resource. This includes callbacks
2384
- * for `onMutate`, `onError`, `onSuccess`, and `onSettled`.
2385
- * @typeParam TResult - The type of the expected result from the mutation.
2386
- * @typeParam TRaw - The raw response type from the HTTP request (defaults to TResult).
2387
- * @typeParam TMutation - The type of the mutation value (the request body).
2388
- * @typeParam TICTX - The type of the initial context value passed to `onMutate`.
2389
- * @typeParam TCTX - The type of the context value returned by `onMutate`.
2390
- * @typeParam TMethod - The HTTP method to be used for the mutation (defaults to `HttpResourceRequest['method']`).
2391
- * @returns A `MutationResourceRef` instance, which provides methods for triggering the mutation
2392
- * and observing its status.
2393
- *
2394
- * @example
2395
- * ```ts
2396
- * // Basic PATCH mutation
2397
- * const updateUser = mutationResource<User, User, Partial<User>>(
2398
- * (body) => ({ url: `/api/users/${userId()}`, method: 'PATCH', body }),
2399
- * {
2400
- * onSuccess: (saved) => toast.success(`Updated ${saved.name}`),
2401
- * onError: (err) => toast.error(err),
2402
- * },
2403
- * );
2404
- *
2405
- * updateUser.mutate({ name: 'Alice' });
2406
- * ```
2407
- *
2408
- * @example
2409
- * ```ts
2410
- * // Optimistic update with rollback via the `ctx` returned from `onMutate`
2411
- * const updateUser = mutationResource<User, User, Partial<User>, { prev: User | null }>(
2412
- * (body) => ({ url: `/api/users/${userId()}`, method: 'PATCH', body }),
2413
- * {
2414
- * onMutate: (patch) => {
2415
- * const prev = current();
2416
- * current.update((u) => (u ? { ...u, ...patch } : u));
2417
- * return { prev };
2418
- * },
2419
- * onError: (_err, { prev }) => current.set(prev),
2420
- * },
2421
- * );
2422
- * ```
2423
- */
2424
2392
  function mutationResource(request, options0 = {}) {
2425
2393
  // Two-layer option injection: per-call > provideMutationResourceOptions > provideResourceOptions.
2426
2394
  const globalOpts = injectResourceOptions(options0.injector);
@@ -2437,11 +2405,6 @@ function mutationResource(request, options0 = {}) {
2437
2405
  const { onMutate, onError, onSuccess, onSettled, equal, register, equalRequest, invalidates, ...rest } = options;
2438
2406
  const cache = invalidates ? injectQueryCache(options.injector) : undefined;
2439
2407
  const requestEqual = equalRequest ?? createEqualRequest(equal);
2440
- // A mutation is an imperative command, so `triggerOnSameRequest` means "fire on EVERY mutate(),
2441
- // even with an identical body". By default we dedup an identical value/request while one is in
2442
- // flight (double-click protection); when this is set, both the `next` and `req` dedup are bypassed
2443
- // so a repeat click isn't silently swallowed mid-flight. (Otherwise it'd be dropped until `next`
2444
- // resets to NULL on settle — the "every other click" symptom.)
2445
2408
  const triggerOnSame = options.triggerOnSameRequest ?? false;
2446
2409
  const eq = equal ?? Object.is;
2447
2410
  const next = signal(NULL_VALUE, {
@@ -2459,27 +2422,15 @@ function mutationResource(request, options0 = {}) {
2459
2422
  const queueKeyFn = typeof options.queue === 'object' ? options.queue.key : undefined;
2460
2423
  const queue = linkedSignal({
2461
2424
  source: () => queueKeyFn?.(),
2462
- computation: () => signal([]),
2425
+ computation: (_key, prev) => {
2426
+ // On a queue key change the previous pending entries are dropped — reject any
2427
+ // mutateAsync promises waiting on them so awaiters don't hang.
2428
+ if (prev)
2429
+ for (const [, , deferred] of untracked(prev.value))
2430
+ deferred?.reject(new MutationCancelledError('queue-key-changed', 'mutation dropped: queue key changed before it ran'));
2431
+ return signal([]);
2432
+ },
2463
2433
  });
2464
- let ctx = undefined;
2465
- const queueRef = effect(() => {
2466
- const q = queue(); // subscribe to swaps (key change / clearQueue)
2467
- const nextInQueue = q().at(0); // subscribe to contents
2468
- if (nextInQueue === undefined || next() !== NULL_VALUE)
2469
- return;
2470
- q.update((arr) => arr.slice(1));
2471
- const [value, ictx] = nextInQueue;
2472
- try {
2473
- ctx = onMutate?.(value, ictx);
2474
- next.set(value);
2475
- }
2476
- catch (mutationErr) {
2477
- ctx = undefined;
2478
- next.set(NULL_VALUE);
2479
- if (isDevMode())
2480
- console.error('[@mmstack/resource]: error thrown in onMutate hook, mutation was not applied', mutationErr);
2481
- }
2482
- }, { injector: options.injector });
2483
2434
  const req = computed(() => {
2484
2435
  const nr = next();
2485
2436
  if (nr === NULL_VALUE)
@@ -2496,6 +2447,57 @@ function mutationResource(request, options0 = {}) {
2496
2447
  return requestEqual(a, b);
2497
2448
  },
2498
2449
  });
2450
+ let ctx = undefined;
2451
+ let currentDeferred;
2452
+ const begin = (value, ictx, deferred) => {
2453
+ let nextCtx;
2454
+ try {
2455
+ nextCtx = onMutate?.(value, ictx);
2456
+ }
2457
+ catch (mutationErr) {
2458
+ // match legacy mutate(): the throw aborts the mutation and resets state
2459
+ ctx = undefined;
2460
+ next.set(NULL_VALUE);
2461
+ deferred?.reject(mutationErr);
2462
+ if (isDevMode())
2463
+ console.error('[@mmstack/resource]: error thrown in onMutate hook, mutation was not applied', mutationErr);
2464
+ return;
2465
+ }
2466
+ ctx = nextCtx;
2467
+ currentDeferred = deferred;
2468
+ next.set(value);
2469
+ if (deferred && untracked(req) === undefined) {
2470
+ ctx = undefined;
2471
+ currentDeferred = undefined;
2472
+ next.set(NULL_VALUE);
2473
+ deferred.reject(new MutationCancelledError('no-request', 'mutation not sent: request() returned undefined'));
2474
+ }
2475
+ };
2476
+ const supersedeInFlight = () => {
2477
+ if (untracked(next) === NULL_VALUE)
2478
+ return;
2479
+ if (isDevMode())
2480
+ console.warn('[@mmstack/resource]: mutate() called while another mutation was in flight — the previous mutation was superseded (latest-wins) and its onSettled was invoked. Use `queue: true` for sequential mutations.');
2481
+ try {
2482
+ onSettled?.(ctx);
2483
+ }
2484
+ catch (settleErr) {
2485
+ if (isDevMode())
2486
+ console.error('[@mmstack/resource]: error thrown in onSettled hook for a superseded mutation', settleErr);
2487
+ }
2488
+ currentDeferred?.reject(new MutationCancelledError('superseded', 'mutation superseded by a newer mutation (latest-wins)'));
2489
+ currentDeferred = undefined;
2490
+ ctx = undefined;
2491
+ };
2492
+ const queueRef = effect(() => {
2493
+ const q = queue(); // subscribe to swaps (key change / clearQueue)
2494
+ const nextInQueue = q().at(0); // subscribe to contents
2495
+ if (nextInQueue === undefined || next() !== NULL_VALUE)
2496
+ return;
2497
+ q.update((arr) => arr.slice(1));
2498
+ const [value, ictx, deferred] = nextInQueue;
2499
+ begin(value, ictx, deferred);
2500
+ }, { injector: options.injector });
2499
2501
  const lastValue = linkedSignal({
2500
2502
  source: next,
2501
2503
  computation: (next, prev) => {
@@ -2554,8 +2556,12 @@ function mutationResource(request, options0 = {}) {
2554
2556
  return NULL_VALUE;
2555
2557
  }), filter((v) => v !== NULL_VALUE), takeUntilDestroyed(destroyRef))
2556
2558
  .subscribe((result) => {
2557
- if (result.status === 'error')
2559
+ const deferred = currentDeferred;
2560
+ currentDeferred = undefined;
2561
+ if (result.status === 'error') {
2558
2562
  onError?.(result.error, ctx);
2563
+ deferred?.reject(result.error);
2564
+ }
2559
2565
  else {
2560
2566
  onSuccess?.(result.value, ctx);
2561
2567
  if (cache && invalidates) {
@@ -2563,11 +2569,10 @@ function mutationResource(request, options0 = {}) {
2563
2569
  const prefixes = typeof invalidates === 'function'
2564
2570
  ? invalidates(result.value, (mutation === NULL_VALUE ? undefined : mutation))
2565
2571
  : invalidates;
2566
- // auto-keys are `${method}:${url}:...` — a `GET:`-prefixed url prefix hits
2567
- // the url with any params/subpaths and every varyHeaders variant
2568
2572
  for (const prefix of prefixes)
2569
2573
  cache.invalidatePrefix(`GET:${prefix}`);
2570
2574
  }
2575
+ deferred?.resolve(result.value);
2571
2576
  }
2572
2577
  onSettled?.(ctx);
2573
2578
  ctx = undefined;
@@ -2579,39 +2584,32 @@ function mutationResource(request, options0 = {}) {
2579
2584
  // queue first — a late queue flush must not poke an already-destroyed resource
2580
2585
  queueRef.destroy();
2581
2586
  statusSub.unsubscribe();
2587
+ // reject any outstanding mutateAsync promises so awaiters don't hang
2588
+ const cancelled = new MutationCancelledError('destroyed', 'mutation abandoned: resource destroyed');
2589
+ currentDeferred?.reject(cancelled);
2590
+ currentDeferred = undefined;
2591
+ for (const [, , deferred] of untracked(queue)())
2592
+ deferred?.reject(cancelled);
2582
2593
  resource.destroy();
2583
2594
  },
2584
2595
  mutate: (value, ictx) => {
2585
2596
  if (queueEnabled) {
2586
- return queue().update((arr) => [...arr, [value, ictx]]);
2597
+ queue().update((arr) => [...arr, [value, ictx, undefined]]);
2598
+ return;
2599
+ }
2600
+ supersedeInFlight();
2601
+ begin(value, ictx, undefined);
2602
+ },
2603
+ mutateAsync: (value, ictx) => {
2604
+ const deferred = Promise.withResolvers();
2605
+ if (queueEnabled) {
2606
+ queue().update((arr) => [...arr, [value, ictx, deferred]]);
2587
2607
  }
2588
2608
  else {
2589
- // latest-wins: a mutation already in flight gets superseded (its request is
2590
- // aborted by the request change), so its onSuccess/onError will never fire —
2591
- // settle its context NOW so optimistic state can be rolled back/cleaned up
2592
- if (untracked(next) !== NULL_VALUE) {
2593
- if (isDevMode())
2594
- console.warn('[@mmstack/resource]: mutate() called while another mutation was in flight — the previous mutation was superseded (latest-wins) and its onSettled was invoked. Use `queue: true` for sequential mutations.');
2595
- try {
2596
- onSettled?.(ctx);
2597
- }
2598
- catch (settleErr) {
2599
- if (isDevMode())
2600
- console.error('[@mmstack/resource]: error thrown in onSettled hook for a superseded mutation', settleErr);
2601
- }
2602
- ctx = undefined;
2603
- }
2604
- try {
2605
- ctx = onMutate?.(value, ictx);
2606
- next.set(value);
2607
- }
2608
- catch (mutationErr) {
2609
- ctx = undefined;
2610
- next.set(NULL_VALUE);
2611
- if (isDevMode())
2612
- console.error('[@mmstack/resource]: error thrown in onMutate hook, mutation was not applied', mutationErr);
2613
- }
2609
+ supersedeInFlight();
2610
+ begin(value, ictx, deferred);
2614
2611
  }
2612
+ return deferred.promise;
2615
2613
  },
2616
2614
  current: computed(() => {
2617
2615
  const nv = next();
@@ -2620,7 +2618,11 @@ function mutationResource(request, options0 = {}) {
2620
2618
  clearQueue: () => {
2621
2619
  if (!queueEnabled)
2622
2620
  return;
2621
+ const dropped = untracked(queue)();
2623
2622
  queue.set(signal([]));
2623
+ // reject mutateAsync promises whose entries we just dropped
2624
+ for (const [, , deferred] of dropped)
2625
+ deferred?.reject(new MutationCancelledError('queue-cleared', 'mutation dropped: queue cleared before it ran'));
2624
2626
  },
2625
2627
  // redeclare disabled with last value so that it is not affected by the resource's internal disablement logic
2626
2628
  disabled: computed(() => cb.isOpen() || lastValueRequest() === undefined),
@@ -2633,5 +2635,5 @@ function mutationResource(request, options0 = {}) {
2633
2635
  * Generated bundle index. Do not edit.
2634
2636
  */
2635
2637
 
2636
- export { Cache, PAUSED, applyResourceRegistration, createCacheInterceptor, createCircuitBreaker, createDedupeRequestsInterceptor, hashRequest, infiniteQueryResource, injectQueryCache, injectResourceOptions, manualQueryResource, mutationResource, noDedupe, provideCircuitBreakerDefaultOptions, provideMutationResourceOptions, provideQueryCache, provideQueryResourceOptions, provideResourceOptions, provideTypedResourceOptions, queryResource };
2638
+ export { Cache, MutationCancelledError, PAUSED, applyResourceRegistration, createCacheInterceptor, createCircuitBreaker, createDedupeRequestsInterceptor, hashRequest, infiniteQueryResource, injectQueryCache, injectResourceOptions, manualQueryResource, mutationResource, noDedupe, provideCircuitBreakerDefaultOptions, provideMutationResourceOptions, provideQueryCache, provideQueryResourceOptions, provideResourceOptions, provideTypedResourceOptions, queryResource };
2637
2639
  //# sourceMappingURL=mmstack-resource.mjs.map