@classytic/arc-next 0.5.0 → 0.7.0

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
@@ -85,31 +85,49 @@ function Products() {
85
85
  ## Core Hooks (from `createCrudHooks`)
86
86
 
87
87
  ```ts
88
- const { items, pagination, isLoading, refetch } = useList(token, params, options);
89
- const { item, isLoading } = useDetail(id, token, options);
88
+ const { items, pagination, isLoading, refetch } = useList(params, options);
89
+ const { item, isLoading, isPlaceholderData } = useDetail(id, options);
90
90
  const { create, update, remove, isMutating } = useActions();
91
- const { items, hasNextPage, fetchNextPage } = useInfiniteList(token, params);
91
+ const { items, hasNextPage, fetchNextPage } = useInfiniteList(params);
92
92
 
93
93
  await create({ data, organizationId }, { onSuccess: (item) => navigate(...) });
94
94
  ```
95
95
 
96
- All mutations are optimistic with automatic rollback on error. Lists prefill the detail cache. Cache keys auto-scope by `organizationId` when present.
96
+ - All mutations are optimistic with automatic rollback on error.
97
+ - Cache keys auto-scope by `organizationId` when present.
98
+ - **List → detail handoff:** when a parent `useList` has the entity in cache,
99
+ `useDetail` reads it via TanStack's `placeholderData` factory — instant
100
+ preview, but the real detail GET still fires (rich payload swap, no
101
+ cache pollution). Use `isPlaceholderData` to dim the preview while it
102
+ resolves. See [CHANGELOG 0.7](./CHANGELOG.md#070) for why this replaced
103
+ the old setQueryData-based prefill.
104
+ - **Detail → list pseudo-normalization:** after a `useDetail` GET resolves,
105
+ arc-next shallow-merges the fresh fields into every list cache holding
106
+ this id. The list view stays in sync without a refetch. Direction is
107
+ one-way (detail → list, never the reverse) — see
108
+ [CHANGELOG → "pseudo-normalization"](./CHANGELOG.md#070) for the
109
+ rationale. For true entity-level normalization (one copy per id, field-
110
+ level invalidation), use Apollo Client or Relay; arc-next stays in the
111
+ REST + React Query niche.
112
+
113
+ `useList(token, params, options)` (legacy 3-arg form) still compiles —
114
+ both signatures are kept stable across the 0.x line.
97
115
 
98
116
  ### `useApiQuery` — non-CRUD reads
99
117
 
100
- For reports, aggregates, RPC-style endpoints. Auto-unwraps `{ success, data }`:
118
+ For reports, aggregates, RPC-style endpoints. Response IS the data — arc 2.13+ has no envelope:
101
119
 
102
120
  ```ts
103
121
  import { useApiQuery } from "@classytic/arc-next/query";
104
122
 
105
- const { data, isLoading } = useApiQuery<ApiResponse<DashboardStats>>({
123
+ const { data, isLoading } = useApiQuery<DashboardStats>({
106
124
  queryKey: ["dashboard", "stats"],
107
125
  queryFn: ({ signal }) => api.request("GET", "/dashboard/stats", { options: { signal } }),
108
126
  freshness: "realtime", // 'realtime' | 'frequent' | 'stable' | 'static'
109
127
  });
110
128
  ```
111
129
 
112
- Pass a custom `select` to override auto-unwrap.
130
+ Pass a custom `select` to project a sub-field from the response.
113
131
 
114
132
  ## Actions & Custom Routes
115
133
 
@@ -126,14 +144,16 @@ const stats = await api.invokeRoute<{ data: { total: number } }>({
126
144
  method: "GET",
127
145
  path: "/stats",
128
146
  });
129
- const recent = await api.invokeRoute<PaginatedResponse<Todo>>({
147
+ import type { OffsetPaginationResult } from "@classytic/repo-core/pagination";
148
+
149
+ const recent = await api.invokeRoute<OffsetPaginationResult<Todo>>({
130
150
  method: "GET",
131
151
  path: "/recent",
132
152
  params: { limit: 5 },
133
153
  });
134
154
  ```
135
155
 
136
- The `useAction` hook (returned from `createCrudHooks`) wraps `api.dispatchAction()` with toast + invalidation. For custom GETs, compose `api.invokeRoute()` with `useApiQuery` — it auto-unwraps the `{ success, data }` envelope:
156
+ The `useAction` hook (returned from `createCrudHooks`) wraps `api.dispatchAction()` with toast + invalidation. For custom GETs, compose `api.invokeRoute()` with `useApiQuery` — the response IS the data (no envelope since arc 2.13):
137
157
 
138
158
  ```ts
139
159
  const { data } = useApiQuery({
@@ -411,13 +431,132 @@ configureClient({
411
431
 
412
432
  Interceptors are async-supported and compose with retry — `beforeRequest` re-runs each attempt (so a refreshed token mid-flight is picked up). Aborting via `AbortSignal` cancels both the pending fetch AND any in-flight backoff sleep.
413
433
 
434
+ ## `arcFetch` — one-line authenticated fetch for non-hook contexts (0.7+)
435
+
436
+ When you need to hit an arc endpoint from outside a hook — event handler, service worker, server action, custom MDX submit, background poll — `arcFetch` collapses the auth/org/content-type/error/parse boilerplate into one call:
437
+
438
+ ```ts
439
+ import { arc } from "@classytic/arc-next/client";
440
+
441
+ // Before — 15 lines of header dance + error parse + JSON parse:
442
+ // const { token } = getAuthContext();
443
+ // if (!token) throw ...
444
+ // const res = await fetch(`${apiBaseUrl()}/api/statements`, {
445
+ // method: "POST",
446
+ // headers: { "content-type": "application/json", authorization: `Bearer ${token}`, ... },
447
+ // body: JSON.stringify(statements),
448
+ // });
449
+ // if (!res.ok) throw ...
450
+ // return await res.json();
451
+ //
452
+ // After:
453
+ const result = await arc.post<{ ok: boolean }>("/api/statements", statements);
454
+ ```
455
+
456
+ Auto-injects `Authorization` (or your `headerName` for `authMode: "header"`), `x-organization-id`, `x-internal-api-key`, `Idempotency-Key`, `x-arc-scope`, and `Content-Type: application/json` (only for plain object/array bodies). Composes with everything else — `retry`, `onAuthError`, `beforeRequest`, `afterResponse`.
457
+
458
+ **Method shorthands:**
459
+
460
+ ```ts
461
+ arc.get<T>(path, opts?)
462
+ arc.post<T>(path, body?, opts?)
463
+ arc.put<T>(path, body?, opts?)
464
+ arc.patch<T>(path, body?, opts?)
465
+ arc.delete<T>(path, opts?)
466
+
467
+ // Or call arcFetch directly for full RequestInit control:
468
+ arcFetch<T>(path, { method, body, headers, signal, elevated, idempotencyKey, revalidate, tags, cache, client })
469
+ ```
470
+
471
+ **Body sniffing.** `FormData`, `Blob`, `URLSearchParams`, `ArrayBuffer`, `ReadableStream`, and `string` pass through unchanged — caller controls `Content-Type` for those. Plain objects and arrays get `JSON.stringify`d and the JSON content-type header.
472
+
473
+ **Protected headers.** `Authorization`, `x-organization-id`, `x-internal-api-key`, and the custom header for `authMode: "header"` cannot be overridden by `options.headers`. A caller can't accidentally strip the bearer token by spreading their own header map. Non-auth headers (`X-Trace-Id`, `Accept-Version`, etc.) pass through normally.
474
+
475
+ **Error handling.** Non-2xx throws `ArcApiError` with parsed body, status, endpoint, method — same contract as the CRUD hooks. Use `isArcApiError(err)` + `err.code` to discriminate.
476
+
477
+ **Escape hatch.** When you need full `Response` control (rare — streaming downloads, custom redirect logic), use plain `fetch` with `arcAuthHeaders()`:
478
+
479
+ ```ts
480
+ import { arcAuthHeaders, getAuthMode } from "@classytic/arc-next/client";
481
+
482
+ const res = await fetch(url, {
483
+ headers: { ...arcAuthHeaders(), "X-Custom": "1" },
484
+ credentials: getAuthMode() === "cookie" ? "include" : "same-origin",
485
+ });
486
+ ```
487
+
488
+ ## Auth Recovery (0.7+) — 401 → refresh → retry
489
+
490
+ When a session token expires mid-page, the SDK transparently refreshes and retries — no flash of unauthenticated UI, no manual reload. Wire it once at app boot:
491
+
492
+ ```ts
493
+ import { configureAuth, createAuthRefreshHandler } from "@classytic/arc-next/client";
494
+ import { authClient } from "@/lib/auth-client";
495
+
496
+ configureAuth({
497
+ getToken: () => authClient.getSession().data?.session.token ?? null,
498
+ onAuthError: createAuthRefreshHandler({
499
+ refresh: async () => {
500
+ // Whatever your auth lib calls to mint a fresh access token.
501
+ const { data } = await authClient.getSession({ disableCookieCache: true });
502
+ return data?.session.token ?? null; // null → session truly expired; original 401 surfaces
503
+ },
504
+ }),
505
+ });
506
+ ```
507
+
508
+ Every `useList`, `useDetail`, `useActions`, and any code path going through `createAuthAwareClient()` or `createClient(...)` now survives token expiry transparently. Apps that don't wire `onAuthError` see the original behavior (401 surfaces immediately).
509
+
510
+ **Concurrent-refresh dedup.** When N requests hit 401 at the same time, the handler fires **once**. All N concurrent callers await the same refresh promise and retry with the token it produces — no stampeding the refresh endpoint under burst auth-expiry.
511
+
512
+ **Tuning knobs.**
513
+
514
+ ```ts
515
+ configureAuth({
516
+ // ...
517
+ onAuthError,
518
+ retryOn403: true, // also recover from 403 (default: 401 only)
519
+ maxAuthRetries: 1, // cap per individual request (default: 1; prevents loops)
520
+ });
521
+ ```
522
+
523
+ **Custom handler.** Bypass `createAuthRefreshHandler` if you need full control over the recovery cycle:
524
+
525
+ ```ts
526
+ configureAuth({
527
+ onAuthError: async ({ error, request, attempt, setToken }) => {
528
+ if (error.code === "session.revoked") return "skip"; // route to /login
529
+ const fresh = await myRefreshFn();
530
+ if (!fresh) return "skip";
531
+ setToken(fresh);
532
+ return "retry";
533
+ },
534
+ });
535
+ ```
536
+
537
+ The handler receives the full `ArcApiError`, the failing request descriptor, the 1-indexed attempt counter, and a `setToken(value)` callback that supplies the refreshed token for the retry. Throwing from the handler short-circuits — the thrown error propagates instead of the 401.
538
+
539
+ **Transport coverage.** Auth recovery fires across every transport arc-next exposes:
540
+
541
+ | Transport | Trigger | Mechanism |
542
+ |---|---|---|
543
+ | Fetch (CRUD hooks, `arcFetch`, `handleApiRequest`) | 401 / 403 response | Inline retry in `executeRequest` |
544
+ | XHR upload (`uploadWithProgress`, `useUploadWithProgress`) | 401 / 403 response | Outer retry loop in `upload.ts` |
545
+ | WebSocket | close code `1008` / `3401` / `4001` / `4401` | `ws.onclose` handler routes through recovery, reconnect with refreshed token |
546
+ | SSE (`subscribeToEvents`, `useEventStream`) | `EventSource` error | Pre-flight `fetch` probe classifies as auth-failure → recovery → reopen |
547
+
548
+ All four transports share **one** dedup'd refresh promise — concurrent failures across mixed transports (5 in-flight uploads + 3 WebSocket reconnects + 10 fetch calls, all 401 at once) collapse to a single `onAuthError` call.
549
+
414
550
  ## Cache & Keys
415
551
 
416
552
  ```ts
417
553
  KEYS.detail(id); // ["products", "detail", id]
418
554
  KEYS.scopedDetail(id, orgId); // tenant-scoped variant
419
555
 
556
+ // Writes/reads the raw doc — no `{ data: TDoc }` envelope (0.7+). Matches
557
+ // what useDetail, prefetchDetail, and useNavigation all produce.
420
558
  cache.setDetail(qc, id, data);
559
+ cache.getDetail(qc, id); // TDoc | undefined
421
560
  cache.invalidateDetail(qc, id); // matches all scoped variants
422
561
  cache.invalidateLists(qc);
423
562
  ```
package/dist/api.d.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  import { ArcClient } from "./client.js";
2
+ import { AggregatePaginationResult, KeysetPaginationResult, OffsetPaginationResult, PaginatedResult } from "@classytic/repo-core/pagination";
3
+ import { AggResult, AggRow, BulkCreateResult, DeleteManyResult, DeleteResult, UpdateManyResult } from "@classytic/repo-core/repository";
4
+ import { BracketOperator, BracketOperator as BracketOperator$1 } from "@classytic/repo-core/query-parser";
2
5
 
3
6
  //#region src/api.d.ts
4
7
  interface PopulateOption {
@@ -6,68 +9,24 @@ interface PopulateOption {
6
9
  select?: string;
7
10
  match?: Record<string, unknown>;
8
11
  }
9
- interface ApiResponse<T = unknown> {
10
- success: boolean;
11
- data?: T;
12
- message?: string;
13
- }
14
- interface OffsetPaginationResponse<T = unknown> {
15
- success: boolean;
16
- method: 'offset';
17
- docs: T[];
18
- page: number;
19
- limit: number;
20
- total: number;
21
- pages: number;
22
- hasNext: boolean;
23
- hasPrev: boolean;
24
- warning?: string;
25
- }
26
- interface KeysetPaginationResponse<T = unknown> {
27
- success: boolean;
28
- method: 'keyset';
29
- docs: T[];
30
- limit: number;
31
- hasMore: boolean;
32
- next: string | null;
33
- }
34
- interface AggregatePaginationResponse<T = unknown> {
35
- success: boolean;
36
- method: 'aggregate';
37
- docs: T[];
38
- page: number;
39
- limit: number;
40
- total: number;
41
- pages: number;
42
- hasNext: boolean;
43
- hasPrev: boolean;
44
- warning?: string;
45
- }
46
- type PaginatedResponse<T = unknown> = OffsetPaginationResponse<T> | KeysetPaginationResponse<T> | AggregatePaginationResponse<T>;
47
- interface DeleteResponse {
48
- success: boolean;
49
- data?: {
50
- message?: string;
51
- id?: string;
52
- soft?: boolean;
53
- };
54
- }
55
- interface BulkCreateResponse<T = unknown> {
56
- success: boolean;
57
- data?: T[];
58
- count?: number;
59
- }
60
- interface BulkUpdateResponse {
61
- success: boolean;
62
- modifiedCount?: number;
63
- }
64
- interface BulkDeleteResponse {
65
- success: boolean;
66
- deletedCount?: number;
67
- }
68
12
  type SortDirection = 1 | -1 | 'asc' | 'desc';
69
13
  type SortSpec = Record<string, SortDirection> | string;
70
- type FilterOperator = 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'nin' | 'contains' | 'startsWith' | 'endsWith' | 'regex' | 'like' | 'exists' | 'size' | 'type' | 'between' | 'near' | 'nearSphere' | 'geoWithin' | 'withinRadius';
14
+ /**
15
+ * Filter operators supported by arc-next URL emission.
16
+ *
17
+ * Composes:
18
+ * - **Canonical** ({@link BracketOperator}) — every operator repo-core's
19
+ * `parseUrl` reverses. Cross-kit portable: mongokit, sqlitekit, prismakit,
20
+ * and any future kit that consumes the canonical Filter IR all support
21
+ * these out of the box.
22
+ * - **Driver-specific extensions** — operators that require kit-native
23
+ * support. Geo (`near`, `nearSphere`, `geoWithin`, `withinRadius`) is
24
+ * mongokit + sqlitekit-spatialite. `size` / `type` are mongokit
25
+ * array/BSON helpers. Hosts using kits without these features just
26
+ * don't emit them; the union stays open with `(string & {})` so custom
27
+ * domain operators still satisfy the type.
28
+ */
29
+ type FilterOperator = BracketOperator$1 | 'size' | 'type' | 'near' | 'nearSphere' | 'geoWithin' | 'withinRadius' | (string & {});
71
30
  interface QueryParams {
72
31
  page?: number;
73
32
  limit?: number;
@@ -140,7 +99,7 @@ declare class BaseApi<TDoc = Record<string, unknown>, TCreate = Partial<TDoc>, T
140
99
  organizationId?: string | null;
141
100
  params?: QueryParams;
142
101
  options?: Omit<RequestOptions, 'token' | 'organizationId'>;
143
- }): Promise<PaginatedResponse<TDoc>>;
102
+ }): Promise<PaginatedResult<TDoc>>;
144
103
  getById({
145
104
  token,
146
105
  organizationId,
@@ -156,7 +115,7 @@ declare class BaseApi<TDoc = Record<string, unknown>, TCreate = Partial<TDoc>, T
156
115
  populate?: string | string[];
157
116
  };
158
117
  options?: Omit<RequestOptions, 'token' | 'organizationId'>;
159
- }): Promise<ApiResponse<TDoc>>;
118
+ }): Promise<TDoc>;
160
119
  create({
161
120
  token,
162
121
  organizationId,
@@ -167,7 +126,7 @@ declare class BaseApi<TDoc = Record<string, unknown>, TCreate = Partial<TDoc>, T
167
126
  organizationId?: string | null;
168
127
  data: TCreate;
169
128
  options?: Omit<RequestOptions, 'token' | 'organizationId'>;
170
- }): Promise<ApiResponse<TDoc>>;
129
+ }): Promise<TDoc>;
171
130
  update({
172
131
  token,
173
132
  organizationId,
@@ -180,7 +139,7 @@ declare class BaseApi<TDoc = Record<string, unknown>, TCreate = Partial<TDoc>, T
180
139
  id: string;
181
140
  data: TUpdate;
182
141
  options?: Omit<RequestOptions, 'token' | 'organizationId'>;
183
- }): Promise<ApiResponse<TDoc>>;
142
+ }): Promise<TDoc>;
184
143
  delete({
185
144
  token,
186
145
  organizationId,
@@ -191,7 +150,7 @@ declare class BaseApi<TDoc = Record<string, unknown>, TCreate = Partial<TDoc>, T
191
150
  organizationId?: string | null;
192
151
  id: string;
193
152
  options?: Omit<RequestOptions, 'token' | 'organizationId'>;
194
- }): Promise<DeleteResponse>;
153
+ }): Promise<DeleteResult>;
195
154
  upload({
196
155
  token,
197
156
  organizationId,
@@ -203,7 +162,7 @@ declare class BaseApi<TDoc = Record<string, unknown>, TCreate = Partial<TDoc>, T
203
162
  data: FormData; /** Resource ID — shorthand for path, appended as `baseUrl/{id}/upload` */
204
163
  id?: string; /** Custom sub-path appended as `baseUrl/{path}`. Takes precedence over `id`. */
205
164
  path?: string;
206
- }): Promise<ApiResponse<TDoc>>;
165
+ }): Promise<TDoc>;
207
166
  request<TResponse = unknown>(method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE', endpoint: string, {
208
167
  token,
209
168
  organizationId,
@@ -223,17 +182,18 @@ declare class BaseApi<TDoc = Record<string, unknown>, TCreate = Partial<TDoc>, T
223
182
  * Arc's escape hatch for endpoints that don't fit CRUD or actions.
224
183
  *
225
184
  * For aggregates / reports, prefer the response-aware {@link useApiQuery} hook
226
- * (which auto-unwraps `{ success, data }`) and pass `invokeRoute` as the queryFn.
185
+ * and pass `invokeRoute` as the queryFn — arc 2.13+ emits raw payloads, so
186
+ * the response IS the data.
227
187
  *
228
188
  * @example
229
- * // GET /todos/stats → { success, data: { total, byStatus } }
189
+ * // GET /todos/stats → { total, byStatus }
230
190
  * const stats = await api.invokeRoute<{ total: number; byStatus: Record<string, number> }>({
231
191
  * method: 'GET',
232
192
  * path: '/stats',
233
193
  * });
234
194
  *
235
195
  * // GET /todos/recent?limit=5 → paginated shape spread to root
236
- * const recent = await api.invokeRoute<PaginatedResponse<Todo>>({
196
+ * const recent = await api.invokeRoute<PaginatedResult<Todo>>({
237
197
  * method: 'GET',
238
198
  * path: '/recent',
239
199
  * params: { limit: 5 },
@@ -260,6 +220,30 @@ declare class BaseApi<TDoc = Record<string, unknown>, TCreate = Partial<TDoc>, T
260
220
  data?: unknown;
261
221
  params?: QueryParams;
262
222
  }): Promise<TResponse>;
223
+ /**
224
+ * Fetch a declared aggregation by name.
225
+ *
226
+ * @example
227
+ * const { rows } = await api.aggregate<{ day: string; total: number }>({
228
+ * name: 'salesByDay',
229
+ * filter: { from: '2025-01-01', to: '2025-12-31' },
230
+ * });
231
+ */
232
+ aggregate<TRow extends AggRow = AggRow>({
233
+ token,
234
+ organizationId,
235
+ name,
236
+ filter,
237
+ options
238
+ }: ScopedArgs & {
239
+ /** Aggregation name as declared on the resource. */name: string;
240
+ /**
241
+ * URL-encoded filter narrows + dimension args. Reserved keys (`page`,
242
+ * `limit`, etc.) are stripped server-side; everything else flows into
243
+ * the AggRequest filter via shallow merge with the host's base filter.
244
+ */
245
+ filter?: Record<string, unknown>;
246
+ }): Promise<AggResult<TRow>>;
263
247
  dispatchAction<TResult = unknown, TBody extends Record<string, unknown> = Record<string, unknown>>({
264
248
  token,
265
249
  organizationId,
@@ -271,12 +255,12 @@ declare class BaseApi<TDoc = Record<string, unknown>, TCreate = Partial<TDoc>, T
271
255
  id: string;
272
256
  action: string;
273
257
  data?: TBody;
274
- }): Promise<ApiResponse<TResult>>;
258
+ }): Promise<TResult>;
275
259
  }
276
260
  declare function createCrudApi<TDoc = Record<string, unknown>, TCreate = Partial<TDoc>, TUpdate = Partial<TDoc>>(entity: string, config?: BaseApiConfig): BaseApi<TDoc, TCreate, TUpdate>;
277
- type ExtractDoc<T> = T extends PaginatedResponse<infer D> ? D : never;
278
- declare function isOffsetPagination<T>(response: PaginatedResponse<T>): response is OffsetPaginationResponse<T>;
279
- declare function isKeysetPagination<T>(response: PaginatedResponse<T>): response is KeysetPaginationResponse<T>;
280
- declare function isAggregatePagination<T>(response: PaginatedResponse<T>): response is AggregatePaginationResponse<T>;
261
+ type ExtractDoc<T> = T extends PaginatedResult<infer D> ? D : never;
262
+ declare function isOffsetPagination<T>(response: PaginatedResult<T>): response is OffsetPaginationResult<T>;
263
+ declare function isKeysetPagination<T>(response: PaginatedResult<T>): response is KeysetPaginationResult<T>;
264
+ declare function isAggregatePagination<T>(response: PaginatedResult<T>): response is AggregatePaginationResult<T>;
281
265
  //#endregion
282
- export { AggregatePaginationResponse, ApiResponse, BaseApi, BaseApiConfig, BulkCreateResponse, BulkDeleteResponse, BulkUpdateResponse, DeleteResponse, ExtractDoc, FilterOperator, KeysetPaginationResponse, OffsetPaginationResponse, PaginatedResponse, PopulateOption, QueryParams, RequestOptions, ScopedArgs, SortDirection, SortSpec, createCrudApi, isAggregatePagination, isKeysetPagination, isOffsetPagination };
266
+ export { type AggResult, type AggRow, BaseApi, BaseApiConfig, type BracketOperator, type BulkCreateResult, type DeleteManyResult, type DeleteResult, ExtractDoc, FilterOperator, PopulateOption, QueryParams, RequestOptions, ScopedArgs, SortDirection, SortSpec, type UpdateManyResult, createCrudApi, isAggregatePagination, isKeysetPagination, isOffsetPagination };
package/dist/api.js CHANGED
@@ -158,17 +158,18 @@ var BaseApi = class {
158
158
  * Arc's escape hatch for endpoints that don't fit CRUD or actions.
159
159
  *
160
160
  * For aggregates / reports, prefer the response-aware {@link useApiQuery} hook
161
- * (which auto-unwraps `{ success, data }`) and pass `invokeRoute` as the queryFn.
161
+ * and pass `invokeRoute` as the queryFn — arc 2.13+ emits raw payloads, so
162
+ * the response IS the data.
162
163
  *
163
164
  * @example
164
- * // GET /todos/stats → { success, data: { total, byStatus } }
165
+ * // GET /todos/stats → { total, byStatus }
165
166
  * const stats = await api.invokeRoute<{ total: number; byStatus: Record<string, number> }>({
166
167
  * method: 'GET',
167
168
  * path: '/stats',
168
169
  * });
169
170
  *
170
171
  * // GET /todos/recent?limit=5 → paginated shape spread to root
171
- * const recent = await api.invokeRoute<PaginatedResponse<Todo>>({
172
+ * const recent = await api.invokeRoute<PaginatedResult<Todo>>({
172
173
  * method: 'GET',
173
174
  * path: '/recent',
174
175
  * params: { limit: 5 },
@@ -193,6 +194,24 @@ var BaseApi = class {
193
194
  options
194
195
  });
195
196
  }
197
+ /**
198
+ * Fetch a declared aggregation by name.
199
+ *
200
+ * @example
201
+ * const { rows } = await api.aggregate<{ day: string; total: number }>({
202
+ * name: 'salesByDay',
203
+ * filter: { from: '2025-01-01', to: '2025-12-31' },
204
+ * });
205
+ */
206
+ async aggregate({ token = null, organizationId = null, name, filter, options = {} }) {
207
+ if (!name) throw new Error("Aggregation name is required");
208
+ const queryString = filter ? this.createQueryString(filter) : "";
209
+ const endpoint = `${this.baseUrl}/aggregations/${name}${queryString ? `?${queryString}` : ""}`;
210
+ const requestOptions = { ...options };
211
+ if (token) requestOptions.token = token;
212
+ if (organizationId) requestOptions.organizationId = organizationId;
213
+ return this.requestFn("GET", endpoint, this.withHeaders(requestOptions));
214
+ }
196
215
  async dispatchAction({ token = null, organizationId = null, id, action, data, options = {} }) {
197
216
  if (!id) throw new Error("ID is required");
198
217
  if (!action) throw new Error("Action name is required");
@@ -212,13 +231,13 @@ function createCrudApi(entity, config = {}) {
212
231
  return new BaseApi(entity, config);
213
232
  }
214
233
  function isOffsetPagination(response) {
215
- return response.method === "offset";
234
+ return "method" in response && response.method === "offset";
216
235
  }
217
236
  function isKeysetPagination(response) {
218
- return response.method === "keyset";
237
+ return "method" in response && response.method === "keyset";
219
238
  }
220
239
  function isAggregatePagination(response) {
221
- return response.method === "aggregate";
240
+ return "method" in response && response.method === "aggregate";
222
241
  }
223
242
 
224
243
  //#endregion
package/dist/cache.d.ts CHANGED
@@ -53,9 +53,10 @@ declare function normalizePagination(data: unknown): PaginationData | null;
53
53
  */
54
54
  declare function extractItems<T>(data: unknown): T[];
55
55
  /**
56
- * Strict detail extractor. Checks well-known keys (`data`, `doc`, `item`,
57
- * `result`); falls back to returning the response as-is. Primitive responses
58
- * (string/number/boolean) pass through.
56
+ * Detail extractor. Arc emits the doc directly (no envelope wrapper) — this
57
+ * function is identity-with-null-guard. Kept as a named helper so callers
58
+ * have a stable seam if a future backend ever ships an envelope, and so
59
+ * `null` / `undefined` responses normalize to `null` consistently.
59
60
  */
60
61
  declare function extractItem<T>(data: unknown): T | null;
61
62
  /**
@@ -64,6 +65,27 @@ declare function extractItem<T>(data: unknown): T | null;
64
65
  * the array length changes.
65
66
  */
66
67
  declare function updateListCache<T>(listData: unknown, updater: (items: T[]) => T[]): unknown;
68
+ /**
69
+ * After a detail fetch lands, propagate the fresh values into every cached
70
+ * list entry that contains this item. The item's ID is resolved via
71
+ * `idField`, falling back to `_id` / `id`. Handles both flat list payloads
72
+ * and infinite-query page arrays.
73
+ *
74
+ * Only updates EXISTING list entries — never creates new caches or new items
75
+ * in lists. If the item moved between filter buckets (e.g. status changed),
76
+ * the relevant lists will refetch on their own; we don't try to predict
77
+ * filter membership.
78
+ *
79
+ * Returns the number of cache entries updated (useful for tests + telemetry).
80
+ *
81
+ * @param qc TanStack QueryClient
82
+ * @param listsKey Prefix key for this entity's lists (typically `KEYS.lists()`)
83
+ * @param item Fresh entity to merge into matching list items
84
+ * @param opts.idField Custom ID field name (defaults to `_id` / `id` lookup)
85
+ */
86
+ declare function syncDetailToLists<TItem extends Record<string, unknown>>(qc: QueryClient, listsKey: QueryKey, item: TItem, opts?: {
87
+ idField?: string;
88
+ }): number;
67
89
  interface QueryKeys {
68
90
  all: string[];
69
91
  lists: () => QueryKey;
@@ -74,6 +96,14 @@ interface QueryKeys {
74
96
  scopedDetail: (id: string, organizationId: string | null) => QueryKey;
75
97
  custom: (key: string, ...args: unknown[]) => QueryKey;
76
98
  scopedList: (scope: string, params?: unknown) => QueryKey;
99
+ /** Prefix for every aggregation on this resource — invalidate all at once. */
100
+ aggregations: () => QueryKey;
101
+ /**
102
+ * Aggregation key (`arc 2.13+ /aggregations/:name`). The `filter` arg is
103
+ * structurally hashed by TanStack — pass the same object identity (or
104
+ * structurally identical) you pass to `useAggregation` so the cache hits.
105
+ */
106
+ aggregation: (name: string, filter?: unknown) => QueryKey;
77
107
  }
78
108
  /**
79
109
  * Build a hierarchical query-key factory for a resource. The returned shape
@@ -97,12 +127,26 @@ interface CacheUtils<T> {
97
127
  getScopedDetail: (client: QueryClient, id: string, organizationId: string | null) => T | undefined;
98
128
  /** Remove tenant-scoped detail from cache. */
99
129
  removeScopedDetail: (client: QueryClient, id: string, organizationId: string | null) => void;
130
+ /**
131
+ * Invalidate every aggregation for this resource. Call from mutation
132
+ * `onSuccess` so dashboards refresh after CRUD writes.
133
+ *
134
+ * For targeted invalidation of a single aggregation pass the name —
135
+ * prefix-matches every parameterized variant.
136
+ */
137
+ invalidateAggregations: (client: QueryClient, name?: string) => Promise<void>;
100
138
  }
101
139
  /**
102
140
  * Build cache read/write/invalidate helpers bound to the given key factory.
103
141
  * Server-safe — operates on a `QueryClient` instance which can be a per-request
104
142
  * server client (during prefetch) or the browser singleton.
143
+ *
144
+ * **Wire shape:** Arc 2.13+ emits raw documents on `GET /:resource/:id` — no
145
+ * `{ data: ... }` envelope. `setDetail` / `getDetail` write and read the raw
146
+ * doc directly so the cache shape matches `useDetail`'s `queryFn` output,
147
+ * `useNavigation`'s pre-populated entries, and `prefetchDetail`'s server seed.
148
+ * All four paths converge on the same shape: TDoc, not `{ data: TDoc }`.
105
149
  */
106
150
  declare function createCacheUtils<T>(KEYS: QueryKeys): CacheUtils<T>;
107
151
  //#endregion
108
- export { CacheUtils, DEFAULT_QUERY_CONFIG, PaginationData, QUERY_CONFIGS, QueryKeys, createCacheUtils, createQueryKeys, extractItem, extractItems, getItemId, normalizePagination, updateListCache };
152
+ export { CacheUtils, DEFAULT_QUERY_CONFIG, PaginationData, QUERY_CONFIGS, QueryKeys, createCacheUtils, createQueryKeys, extractItem, extractItems, getItemId, normalizePagination, syncDetailToLists, updateListCache };