@mmstack/resource 21.4.5 → 21.4.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
 
@@ -2354,6 +2354,23 @@ function manualQueryResource(request, options) {
2354
2354
  }
2355
2355
 
2356
2356
  const NULL_VALUE = Symbol('@mmstack/resource:null');
2357
+ /**
2358
+ * Rejection reason for a {@link MutationResourceRef.mutateAsync} promise whose
2359
+ * mutation never completed. The {@link MutationCancelledError.type} discriminant
2360
+ * carries the cause ({@link MutationCancellationReason}); the message is a
2361
+ * human-readable elaboration of it.
2362
+ *
2363
+ * Only `mutateAsync` promises reject with this; plain `mutate()` calls have no
2364
+ * promise and so produce no (potentially unhandled) rejection.
2365
+ */
2366
+ class MutationCancelledError extends Error {
2367
+ type;
2368
+ constructor(type, message) {
2369
+ super(message);
2370
+ this.type = type;
2371
+ this.name = 'MutationCancelledError';
2372
+ }
2373
+ }
2357
2374
  const MUTATION_RESOURCE_OPTIONS = new InjectionToken('@mmstack/resource:mutation-resource-options', { factory: () => ({}) });
2358
2375
  /**
2359
2376
  * Layer 2 (mutation): default options for every `mutationResource`, inheriting + overriding the
@@ -2367,55 +2384,6 @@ function injectMutationResourceOptions(injector) {
2367
2384
  ? injector.get(MUTATION_RESOURCE_OPTIONS)
2368
2385
  : inject(MUTATION_RESOURCE_OPTIONS);
2369
2386
  }
2370
- /**
2371
- * Creates a resource for performing mutations (e.g., POST, PUT, PATCH, DELETE requests).
2372
- * Unlike `queryResource`, `mutationResource` is designed for one-off operations that change data.
2373
- * It does *not* cache responses and does not provide a `value` signal. Instead, it focuses on
2374
- * managing the mutation lifecycle (pending, error, success) and provides callbacks for handling
2375
- * these states.
2376
- *
2377
- * @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.
2378
- * @param options Configuration options for the mutation resource. This includes callbacks
2379
- * for `onMutate`, `onError`, `onSuccess`, and `onSettled`.
2380
- * @typeParam TResult - The type of the expected result from the mutation.
2381
- * @typeParam TRaw - The raw response type from the HTTP request (defaults to TResult).
2382
- * @typeParam TMutation - The type of the mutation value (the request body).
2383
- * @typeParam TICTX - The type of the initial context value passed to `onMutate`.
2384
- * @typeParam TCTX - The type of the context value returned by `onMutate`.
2385
- * @typeParam TMethod - The HTTP method to be used for the mutation (defaults to `HttpResourceRequest['method']`).
2386
- * @returns A `MutationResourceRef` instance, which provides methods for triggering the mutation
2387
- * and observing its status.
2388
- *
2389
- * @example
2390
- * ```ts
2391
- * // Basic PATCH mutation
2392
- * const updateUser = mutationResource<User, User, Partial<User>>(
2393
- * (body) => ({ url: `/api/users/${userId()}`, method: 'PATCH', body }),
2394
- * {
2395
- * onSuccess: (saved) => toast.success(`Updated ${saved.name}`),
2396
- * onError: (err) => toast.error(err),
2397
- * },
2398
- * );
2399
- *
2400
- * updateUser.mutate({ name: 'Alice' });
2401
- * ```
2402
- *
2403
- * @example
2404
- * ```ts
2405
- * // Optimistic update with rollback via the `ctx` returned from `onMutate`
2406
- * const updateUser = mutationResource<User, User, Partial<User>, { prev: User | null }>(
2407
- * (body) => ({ url: `/api/users/${userId()}`, method: 'PATCH', body }),
2408
- * {
2409
- * onMutate: (patch) => {
2410
- * const prev = current();
2411
- * current.update((u) => (u ? { ...u, ...patch } : u));
2412
- * return { prev };
2413
- * },
2414
- * onError: (_err, { prev }) => current.set(prev),
2415
- * },
2416
- * );
2417
- * ```
2418
- */
2419
2387
  function mutationResource(request, options0 = {}) {
2420
2388
  // Two-layer option injection: per-call > provideMutationResourceOptions > provideResourceOptions.
2421
2389
  const globalOpts = injectResourceOptions(options0.injector);
@@ -2432,11 +2400,6 @@ function mutationResource(request, options0 = {}) {
2432
2400
  const { onMutate, onError, onSuccess, onSettled, equal, register, equalRequest, invalidates, ...rest } = options;
2433
2401
  const cache = invalidates ? injectQueryCache(options.injector) : undefined;
2434
2402
  const requestEqual = equalRequest ?? createEqualRequest(equal);
2435
- // A mutation is an imperative command, so `triggerOnSameRequest` means "fire on EVERY mutate(),
2436
- // even with an identical body". By default we dedup an identical value/request while one is in
2437
- // flight (double-click protection); when this is set, both the `next` and `req` dedup are bypassed
2438
- // so a repeat click isn't silently swallowed mid-flight. (Otherwise it'd be dropped until `next`
2439
- // resets to NULL on settle — the "every other click" symptom.)
2440
2403
  const triggerOnSame = options.triggerOnSameRequest ?? false;
2441
2404
  const eq = equal ?? Object.is;
2442
2405
  const next = signal(NULL_VALUE, { ...(ngDevMode ? { debugName: "next" } : /* istanbul ignore next */ {}), equal: (a, b) => {
@@ -2451,26 +2414,14 @@ function mutationResource(request, options0 = {}) {
2451
2414
  const queueEnabled = !!options.queue;
2452
2415
  const queueKeyFn = typeof options.queue === 'object' ? options.queue.key : undefined;
2453
2416
  const queue = linkedSignal({ ...(ngDevMode ? { debugName: "queue" } : /* istanbul ignore next */ {}), source: () => queueKeyFn?.(),
2454
- computation: () => signal([]) });
2455
- let ctx = undefined;
2456
- const queueRef = effect(() => {
2457
- const q = queue(); // subscribe to swaps (key change / clearQueue)
2458
- const nextInQueue = q().at(0); // subscribe to contents
2459
- if (nextInQueue === undefined || next() !== NULL_VALUE)
2460
- return;
2461
- q.update((arr) => arr.slice(1));
2462
- const [value, ictx] = nextInQueue;
2463
- try {
2464
- ctx = onMutate?.(value, ictx);
2465
- next.set(value);
2466
- }
2467
- catch (mutationErr) {
2468
- ctx = undefined;
2469
- next.set(NULL_VALUE);
2470
- if (isDevMode())
2471
- console.error('[@mmstack/resource]: error thrown in onMutate hook, mutation was not applied', mutationErr);
2472
- }
2473
- }, { ...(ngDevMode ? { debugName: "queueRef" } : /* istanbul ignore next */ {}), injector: options.injector });
2417
+ computation: (_key, prev) => {
2418
+ // On a queue key change the previous pending entries are dropped — reject any
2419
+ // mutateAsync promises waiting on them so awaiters don't hang.
2420
+ if (prev)
2421
+ for (const [, , deferred] of untracked(prev.value))
2422
+ deferred?.reject(new MutationCancelledError('queue-key-changed', 'mutation dropped: queue key changed before it ran'));
2423
+ return signal([]);
2424
+ } });
2474
2425
  const req = computed(() => {
2475
2426
  const nr = next();
2476
2427
  if (nr === NULL_VALUE)
@@ -2485,6 +2436,57 @@ function mutationResource(request, options0 = {}) {
2485
2436
  return false;
2486
2437
  return requestEqual(a, b);
2487
2438
  } });
2439
+ let ctx = undefined;
2440
+ let currentDeferred;
2441
+ const begin = (value, ictx, deferred) => {
2442
+ let nextCtx;
2443
+ try {
2444
+ nextCtx = onMutate?.(value, ictx);
2445
+ }
2446
+ catch (mutationErr) {
2447
+ // match legacy mutate(): the throw aborts the mutation and resets state
2448
+ ctx = undefined;
2449
+ next.set(NULL_VALUE);
2450
+ deferred?.reject(mutationErr);
2451
+ if (isDevMode())
2452
+ console.error('[@mmstack/resource]: error thrown in onMutate hook, mutation was not applied', mutationErr);
2453
+ return;
2454
+ }
2455
+ ctx = nextCtx;
2456
+ currentDeferred = deferred;
2457
+ next.set(value);
2458
+ if (deferred && untracked(req) === undefined) {
2459
+ ctx = undefined;
2460
+ currentDeferred = undefined;
2461
+ next.set(NULL_VALUE);
2462
+ deferred.reject(new MutationCancelledError('no-request', 'mutation not sent: request() returned undefined'));
2463
+ }
2464
+ };
2465
+ const supersedeInFlight = () => {
2466
+ if (untracked(next) === NULL_VALUE)
2467
+ return;
2468
+ if (isDevMode())
2469
+ 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.');
2470
+ try {
2471
+ onSettled?.(ctx);
2472
+ }
2473
+ catch (settleErr) {
2474
+ if (isDevMode())
2475
+ console.error('[@mmstack/resource]: error thrown in onSettled hook for a superseded mutation', settleErr);
2476
+ }
2477
+ currentDeferred?.reject(new MutationCancelledError('superseded', 'mutation superseded by a newer mutation (latest-wins)'));
2478
+ currentDeferred = undefined;
2479
+ ctx = undefined;
2480
+ };
2481
+ const queueRef = effect(() => {
2482
+ const q = queue(); // subscribe to swaps (key change / clearQueue)
2483
+ const nextInQueue = q().at(0); // subscribe to contents
2484
+ if (nextInQueue === undefined || next() !== NULL_VALUE)
2485
+ return;
2486
+ q.update((arr) => arr.slice(1));
2487
+ const [value, ictx, deferred] = nextInQueue;
2488
+ begin(value, ictx, deferred);
2489
+ }, { ...(ngDevMode ? { debugName: "queueRef" } : /* istanbul ignore next */ {}), injector: options.injector });
2488
2490
  const lastValue = linkedSignal({ ...(ngDevMode ? { debugName: "lastValue" } : /* istanbul ignore next */ {}), source: next,
2489
2491
  computation: (next, prev) => {
2490
2492
  if (next === NULL_VALUE && !!prev)
@@ -2539,8 +2541,12 @@ function mutationResource(request, options0 = {}) {
2539
2541
  return NULL_VALUE;
2540
2542
  }), filter((v) => v !== NULL_VALUE), takeUntilDestroyed(destroyRef))
2541
2543
  .subscribe((result) => {
2542
- if (result.status === 'error')
2544
+ const deferred = currentDeferred;
2545
+ currentDeferred = undefined;
2546
+ if (result.status === 'error') {
2543
2547
  onError?.(result.error, ctx);
2548
+ deferred?.reject(result.error);
2549
+ }
2544
2550
  else {
2545
2551
  onSuccess?.(result.value, ctx);
2546
2552
  if (cache && invalidates) {
@@ -2548,11 +2554,10 @@ function mutationResource(request, options0 = {}) {
2548
2554
  const prefixes = typeof invalidates === 'function'
2549
2555
  ? invalidates(result.value, (mutation === NULL_VALUE ? undefined : mutation))
2550
2556
  : invalidates;
2551
- // auto-keys are `${method}:${url}:...` — a `GET:`-prefixed url prefix hits
2552
- // the url with any params/subpaths and every varyHeaders variant
2553
2557
  for (const prefix of prefixes)
2554
2558
  cache.invalidatePrefix(`GET:${prefix}`);
2555
2559
  }
2560
+ deferred?.resolve(result.value);
2556
2561
  }
2557
2562
  onSettled?.(ctx);
2558
2563
  ctx = undefined;
@@ -2564,39 +2569,32 @@ function mutationResource(request, options0 = {}) {
2564
2569
  // queue first — a late queue flush must not poke an already-destroyed resource
2565
2570
  queueRef.destroy();
2566
2571
  statusSub.unsubscribe();
2572
+ // reject any outstanding mutateAsync promises so awaiters don't hang
2573
+ const cancelled = new MutationCancelledError('destroyed', 'mutation abandoned: resource destroyed');
2574
+ currentDeferred?.reject(cancelled);
2575
+ currentDeferred = undefined;
2576
+ for (const [, , deferred] of untracked(queue)())
2577
+ deferred?.reject(cancelled);
2567
2578
  resource.destroy();
2568
2579
  },
2569
2580
  mutate: (value, ictx) => {
2570
2581
  if (queueEnabled) {
2571
- return queue().update((arr) => [...arr, [value, ictx]]);
2582
+ queue().update((arr) => [...arr, [value, ictx, undefined]]);
2583
+ return;
2584
+ }
2585
+ supersedeInFlight();
2586
+ begin(value, ictx, undefined);
2587
+ },
2588
+ mutateAsync: (value, ictx) => {
2589
+ const deferred = Promise.withResolvers();
2590
+ if (queueEnabled) {
2591
+ queue().update((arr) => [...arr, [value, ictx, deferred]]);
2572
2592
  }
2573
2593
  else {
2574
- // latest-wins: a mutation already in flight gets superseded (its request is
2575
- // aborted by the request change), so its onSuccess/onError will never fire —
2576
- // settle its context NOW so optimistic state can be rolled back/cleaned up
2577
- if (untracked(next) !== NULL_VALUE) {
2578
- if (isDevMode())
2579
- 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.');
2580
- try {
2581
- onSettled?.(ctx);
2582
- }
2583
- catch (settleErr) {
2584
- if (isDevMode())
2585
- console.error('[@mmstack/resource]: error thrown in onSettled hook for a superseded mutation', settleErr);
2586
- }
2587
- ctx = undefined;
2588
- }
2589
- try {
2590
- ctx = onMutate?.(value, ictx);
2591
- next.set(value);
2592
- }
2593
- catch (mutationErr) {
2594
- ctx = undefined;
2595
- next.set(NULL_VALUE);
2596
- if (isDevMode())
2597
- console.error('[@mmstack/resource]: error thrown in onMutate hook, mutation was not applied', mutationErr);
2598
- }
2594
+ supersedeInFlight();
2595
+ begin(value, ictx, deferred);
2599
2596
  }
2597
+ return deferred.promise;
2600
2598
  },
2601
2599
  current: computed(() => {
2602
2600
  const nv = next();
@@ -2605,7 +2603,11 @@ function mutationResource(request, options0 = {}) {
2605
2603
  clearQueue: () => {
2606
2604
  if (!queueEnabled)
2607
2605
  return;
2606
+ const dropped = untracked(queue)();
2608
2607
  queue.set(signal([]));
2608
+ // reject mutateAsync promises whose entries we just dropped
2609
+ for (const [, , deferred] of dropped)
2610
+ deferred?.reject(new MutationCancelledError('queue-cleared', 'mutation dropped: queue cleared before it ran'));
2609
2611
  },
2610
2612
  // redeclare disabled with last value so that it is not affected by the resource's internal disablement logic
2611
2613
  disabled: computed(() => cb.isOpen() || lastValueRequest() === undefined),
@@ -2618,5 +2620,5 @@ function mutationResource(request, options0 = {}) {
2618
2620
  * Generated bundle index. Do not edit.
2619
2621
  */
2620
2622
 
2621
- export { Cache, PAUSED, applyResourceRegistration, createCacheInterceptor, createCircuitBreaker, createDedupeRequestsInterceptor, hashRequest, infiniteQueryResource, injectQueryCache, injectResourceOptions, manualQueryResource, mutationResource, noDedupe, provideCircuitBreakerDefaultOptions, provideMutationResourceOptions, provideQueryCache, provideQueryResourceOptions, provideResourceOptions, provideTypedResourceOptions, queryResource };
2623
+ export { Cache, MutationCancelledError, PAUSED, applyResourceRegistration, createCacheInterceptor, createCircuitBreaker, createDedupeRequestsInterceptor, hashRequest, infiniteQueryResource, injectQueryCache, injectResourceOptions, manualQueryResource, mutationResource, noDedupe, provideCircuitBreakerDefaultOptions, provideMutationResourceOptions, provideQueryCache, provideQueryResourceOptions, provideResourceOptions, provideTypedResourceOptions, queryResource };
2622
2624
  //# sourceMappingURL=mmstack-resource.mjs.map