@inferencebureau/apps-sdk 0.14.0 → 0.15.1

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/dist/react.d.ts CHANGED
@@ -8,9 +8,14 @@
8
8
  * globals.css) and their CSS variables, so they look like the rest of the app. `@inferencebureau/apps-sdk/polaris`
9
9
  * draws the same tables and forms in Polaris web components. Both draw what `useAutoTable` and `useAutoForm` work out,
10
10
  * which a page can use to draw its own.
11
+ *
12
+ * A read given `live: true` reads again whenever its model's records change, whoever changes them: an action, a
13
+ * Shopify sync, another tab. The client keeps one watch open on the records route for every live read on the page
14
+ * (a long poll, paused while the tab is hidden), and the route answers which models changed; the read that follows
15
+ * goes through the route like any other, so it sees only what the viewer may.
11
16
  */
12
17
  import { type FormEvent, type ReactNode } from "react";
13
- import { ApiError, type AppRecord, type BulkDeleteResult, type Filter, type FindManyOptions, type ModelDescription, type RecordPage, type Sort } from "./index.js";
18
+ import { ApiError, type ActionName, type AggregateOptions, type AggregateResult, type AggregateSpec, type AppRecord, type BulkDeleteResult, type EnqueueOptions, type Filter, type FindManyOptions, type GlobalName, type GlobalOf, type Job, type ModelDescription, type ModelName, type ModelOf, type ModelTypes, type ParamsOf, type ReadOf, type RecordPage, type SelectOf, type Sort, type UntypedModel } from "./index.js";
14
19
  import { type Column, type ColumnOption, type Display, type FieldOption, type FormFieldSpec, type FormValue, type SortOption } from "./auto.js";
15
20
  export { labelOf, recordLabel } from "./auto.js";
16
21
  export type { Column, ColumnOption, Display, FieldOption, FormFieldSpec, FormValue, InputKind, SortOption } from "./auto.js";
@@ -18,39 +23,59 @@ export type { Column, ColumnOption, Display, FieldOption, FormFieldSpec, FormVal
18
23
  export type ReadOptions = Omit<FindManyOptions, "select"> & {
19
24
  select?: Record<string, unknown>;
20
25
  };
21
- export interface RecordsModel {
26
+ /**
27
+ * One model through the records route. Typed from the app's generated client types (`web/ib-client.d.ts`) the way
28
+ * `createClient()`'s models are: its records, filters, sorts, selects and actions; any field without them.
29
+ */
30
+ export interface RecordsModel<M extends ModelTypes = UntypedModel> {
22
31
  describe(): Promise<ModelDescription>;
23
- findMany(options?: ReadOptions): Promise<RecordPage>;
24
- findOne(id: string, o?: {
25
- select?: Record<string, unknown>;
26
- }): Promise<AppRecord | null>;
27
- create(values: Record<string, unknown>): Promise<AppRecord>;
28
- update(id: string, values: Record<string, unknown>): Promise<AppRecord>;
32
+ findMany<S extends SelectOf<M> | undefined = undefined>(options?: FindManyOptions<M, S>): Promise<RecordPage<ReadOf<M, S>>>;
33
+ findOne<S extends SelectOf<M> | undefined = undefined>(id: string, o?: {
34
+ select?: S;
35
+ }): Promise<ReadOf<M, S> | null>;
36
+ /** Counts, sums, averages, least and most over the records, in groups or all together. */
37
+ aggregate<A extends {
38
+ [name: string]: AggregateSpec<M["sortable"]>;
39
+ }>(options: AggregateOptions<M, A>): Promise<AggregateResult<A>>;
40
+ create(values: M["input"]): Promise<M["record"]>;
41
+ update(id: string, values: M["input"]): Promise<M["record"]>;
29
42
  delete(id: string): Promise<void>;
30
43
  bulkDelete(ids: string[]): Promise<BulkDeleteResult>;
31
44
  /** Runs one of the model's actions: on a record when `id` is given. */
32
- run(action: string, o?: {
45
+ run<A extends keyof M["actions"] & string>(action: A, o?: {
33
46
  id?: string;
34
- params?: Record<string, unknown>;
47
+ params?: M["actions"][A]["params"];
35
48
  }): Promise<{
36
- record: AppRecord | null;
37
- result?: unknown;
49
+ record: M["record"] | null;
50
+ result?: M["actions"][A]["result"];
38
51
  }>;
39
52
  /** Uploads a file for a file field straight to storage; write the answer to the field. */
40
- upload(field: string, file: Blob, o?: {
53
+ upload(field: M["files"], file: Blob, o?: {
41
54
  fileName?: string;
42
55
  }): Promise<{
43
56
  directUploadToken: string;
44
57
  }>;
45
58
  }
59
+ /** What a job queued from a page takes: everything `api.enqueue` does but the store, which is the request's own. */
60
+ export type RecordsEnqueueOptions = Omit<EnqueueOptions, "shop">;
46
61
  export interface RecordsClient {
47
- model(name: string): RecordsModel;
62
+ model<N extends ModelName>(name: N): RecordsModel<ModelOf<N>>;
48
63
  /** Runs a global action the route allows (`serveRecords`'s `globalActions`). */
49
- global(action: string, params?: Record<string, unknown>): Promise<{
50
- result?: unknown;
64
+ global<A extends GlobalName>(action: A, params?: GlobalOf<A>["params"]): Promise<{
65
+ result?: GlobalOf<A>["result"];
51
66
  }>;
67
+ /**
68
+ * Queues an action as a background job, a global action's name or `<model>.<action>` (with `id` for the record),
69
+ * when the route allows it (`serveRecords`'s `enqueueActions`).
70
+ */
71
+ enqueue?<A extends ActionName>(action: A, params?: ParamsOf<A>, options?: RecordsEnqueueOptions): Promise<Job>;
52
72
  /** Called with a model's name whenever a write through this client changed its records; returns the unsubscribe. */
53
73
  subscribe(listener: (model: string) => void): () => void;
74
+ /**
75
+ * Called with the models that changed whenever records of any of `models` do, by anyone (live queries); returns
76
+ * the unsubscribe. One watch on the route serves every listener.
77
+ */
78
+ watch?(models: string[], listener: (models: string[]) => void): () => void;
54
79
  }
55
80
  export interface RecordsClientOptions {
56
81
  /** The app's records route; /api/records unless the app put it elsewhere. */
@@ -77,45 +102,90 @@ export interface Query<T> {
77
102
  error: ApiError | null;
78
103
  refetch(): void;
79
104
  }
80
- /** A page of a model's records. Pass `pause` to hold off (until an id is known, say). */
81
- export declare function useFindMany(model: string, options?: ReadOptions, o?: {
105
+ /** Options every read takes. */
106
+ export interface ReadHookOptions {
107
+ /** Hold off (until an id is known, say). */
82
108
  pause?: boolean;
83
- }): Query<RecordPage>;
109
+ /** Read again whenever the model's records change, whoever changes them. */
110
+ live?: boolean;
111
+ }
112
+ /** A page of records, and the way to the pages either side of it. */
113
+ export interface PagedQuery<T> extends Query<RecordPage<T>> {
114
+ /** 1 for the page the options start from. */
115
+ page: number;
116
+ hasNextPage: boolean;
117
+ hasPreviousPage: boolean;
118
+ nextPage(): void;
119
+ previousPage(): void;
120
+ /** Back to the page the options start from. */
121
+ resetPages(): void;
122
+ }
123
+ /**
124
+ * A page of a model's records, typed by the app's generated client types: `filter`, `sort` and `select` name its
125
+ * fields, and the records are what `select` picks. `nextPage` and `previousPage` move through the list by cursor; a
126
+ * change to the options starts again from the first page. Pass `pause` to hold off (until an id is known, say), and
127
+ * `live` to read again whenever its records change.
128
+ *
129
+ * const reviews = useFindMany("review", { filter: { rating: { lessThan: 3 } }, select: { rating: true, product: { select: { title: true } } } });
130
+ * reviews.data?.records[0]?.product?.title;
131
+ */
132
+ export declare function useFindMany<N extends ModelName, S extends SelectOf<ModelOf<N>> | undefined = undefined>(model: N, options?: FindManyOptions<ModelOf<N>, S>, o?: ReadHookOptions): PagedQuery<ReadOf<ModelOf<N>, S>>;
84
133
  /** One record by id, or null when there's none the caller can read. */
85
- export declare function useFindOne(model: string, id: string | null | undefined, o?: {
86
- select?: Record<string, unknown>;
87
- pause?: boolean;
88
- }): Query<AppRecord | null>;
134
+ export declare function useFindOne<N extends ModelName, S extends SelectOf<ModelOf<N>> | undefined = undefined>(model: N, id: string | null | undefined, o?: ReadHookOptions & {
135
+ select?: S;
136
+ }): Query<ReadOf<ModelOf<N>, S> | null>;
89
137
  /** The first record matching, or null. */
90
- export declare function useFindFirst(model: string, options?: Omit<ReadOptions, "first" | "after">, o?: {
138
+ export declare function useFindFirst<N extends ModelName, S extends SelectOf<ModelOf<N>> | undefined = undefined>(model: N, options?: Omit<FindManyOptions<ModelOf<N>, S>, "first" | "after">, o?: ReadHookOptions): Query<ReadOf<ModelOf<N>, S> | null>;
139
+ /** Groups of a model's records with their counts, sums and averages, for a chart or a report; again after a write to it. */
140
+ export declare function useAggregate<N extends ModelName, A extends {
141
+ [name: string]: AggregateSpec<ModelOf<N>["sortable"]>;
142
+ }>(model: N, options: AggregateOptions<ModelOf<N>, A>, o?: {
91
143
  pause?: boolean;
92
- }): Query<AppRecord | null>;
144
+ }): Query<AggregateResult<A>>;
93
145
  /** A model's description: its fields, which AutoTable and AutoForm draw from. */
94
- export declare function useModel(model: string): Query<ModelDescription>;
146
+ export declare function useModel(model: ModelName): Query<ModelDescription>;
95
147
  export interface Mutation<T, A> {
96
148
  data: T | undefined;
97
149
  running: boolean;
98
150
  error: ApiError | null;
99
151
  run(args: A): Promise<T>;
100
152
  }
153
+ /** A model's actions by name: its own (api/models/<model>/actions), and the create, update and delete every model takes. */
154
+ export type ActionOf<N extends string> = (keyof ModelOf<N>["actions"] & string) | "create" | "update" | "delete";
155
+ /** What one of a model's actions takes: its `params`, or the model's fields for a create or update it doesn't have. */
156
+ export type ActionParams<N extends string, A extends string> = A extends keyof ModelOf<N>["actions"] ? ModelOf<N>["actions"][A]["params"] : A extends "delete" ? Record<string, never> : ModelOf<N>["input"];
157
+ type ActionResult<N extends string, A extends string> = A extends keyof ModelOf<N>["actions"] ? ModelOf<N>["actions"][A]["result"] : unknown;
101
158
  /**
102
159
  * One of a model's actions: `create`, `update` and `delete` write the way the API does (the model's action when it has
103
- * one), any other runs by name. Lists of the model refetch once it's done.
160
+ * one), any other runs by name. Its params and result are the action's, from the generated client types. Lists of
161
+ * the model refetch once it's done.
104
162
  *
105
163
  * const publish = useAction("post", "publish");
106
164
  * await publish.run({ id: post.id });
107
165
  */
108
- export declare function useAction(model: string, action: string): Mutation<{
109
- record: AppRecord | null;
110
- result?: unknown;
166
+ export declare function useAction<N extends ModelName, A extends ActionOf<N>>(model: N, action: A): Mutation<{
167
+ record: ModelOf<N>["record"] | null;
168
+ result?: ActionResult<N, A>;
111
169
  }, {
112
170
  id?: string;
113
- params?: Record<string, unknown>;
171
+ params?: ActionParams<N, A>;
114
172
  }>;
115
173
  /** A global action the records route allows (`serveRecords`'s `globalActions`). */
116
- export declare function useGlobalAction(action: string): Mutation<{
117
- result?: unknown;
118
- }, Record<string, unknown> | undefined>;
174
+ export declare function useGlobalAction<A extends GlobalName>(action: A): Mutation<{
175
+ result?: GlobalOf<A>["result"];
176
+ }, GlobalOf<A>["params"] | undefined>;
177
+ /** What `useEnqueue`'s `run` takes: the action's params, and the job's options (`id` for a model action's record). */
178
+ export type EnqueueArgs<A extends string> = {
179
+ params?: ParamsOf<A>;
180
+ } & RecordsEnqueueOptions;
181
+ /**
182
+ * Queues an action as a background job, a global action's name or `<model>.<action>`, when the records route allows
183
+ * it (`serveRecords`'s `enqueueActions`). `run` answers with the job once it's queued, not when it has run.
184
+ *
185
+ * const reindex = useEnqueue("post.reindex");
186
+ * await reindex.run({ id: post.id, delay: 60_000 });
187
+ */
188
+ export declare function useEnqueue<A extends ActionName>(action: A): Mutation<Job, EnqueueArgs<A> | undefined>;
119
189
  export interface AutoTableOptions {
120
190
  /** Which columns, in order; the first six that read well in a cell, then Updated, when unset. */
121
191
  columns?: ColumnOption[];
@@ -127,6 +197,8 @@ export interface AutoTableOptions {
127
197
  sort?: Sort;
128
198
  /** Whether rows can be chosen for a bulk delete. */
129
199
  selectable?: boolean;
200
+ /** Show changes to the records as they happen, whoever makes them. */
201
+ live?: boolean;
130
202
  }
131
203
  export interface AutoTableRow {
132
204
  id: string;
@@ -163,7 +235,7 @@ export interface AutoTable {
163
235
  refetch(): void;
164
236
  }
165
237
  /** What a table of the model shows and does, for a renderer to draw. */
166
- export declare function useAutoTable(model: string, o?: AutoTableOptions): AutoTable;
238
+ export declare function useAutoTable(model: ModelName, o?: AutoTableOptions): AutoTable;
167
239
  export interface AutoFormOptions {
168
240
  /** The record to edit; a new one is made without it. */
169
241
  id?: string;
@@ -212,13 +284,13 @@ export interface AutoForm {
212
284
  isNew: boolean;
213
285
  }
214
286
  /** What a form for the model shows and does, for a renderer to draw. */
215
- export declare function useAutoForm(model: string, o?: AutoFormOptions): AutoForm;
287
+ export declare function useAutoForm(model: ModelName, o?: AutoFormOptions): AutoForm;
216
288
  /** A cell as standard elements, for the plain table. */
217
289
  export declare function PlainCell({ value }: {
218
290
  value: Display;
219
291
  }): import("react").JSX.Element;
220
292
  export interface AutoTableProps extends AutoTableOptions {
221
- model: string;
293
+ model: ModelName;
222
294
  /** What a row opens: a link to the record's page, say. */
223
295
  rowHref?(record: AppRecord): string;
224
296
  onRowClick?(record: AppRecord): void;
@@ -234,7 +306,7 @@ export declare function PlainInput({ field: f }: {
234
306
  field: AutoFormField;
235
307
  }): import("react").JSX.Element;
236
308
  export interface AutoFormProps extends AutoFormOptions {
237
- model: string;
309
+ model: ModelName;
238
310
  /** The submit button's words; Save, or Create for a new record, unless given. */
239
311
  submitLabel?: string;
240
312
  }
package/dist/react.js CHANGED
@@ -10,9 +10,14 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
10
10
  * globals.css) and their CSS variables, so they look like the rest of the app. `@inferencebureau/apps-sdk/polaris`
11
11
  * draws the same tables and forms in Polaris web components. Both draw what `useAutoTable` and `useAutoForm` work out,
12
12
  * which a page can use to draw its own.
13
+ *
14
+ * A read given `live: true` reads again whenever its model's records change, whoever changes them: an action, a
15
+ * Shopify sync, another tab. The client keeps one watch open on the records route for every live read on the page
16
+ * (a long poll, paused while the tab is hidden), and the route answers which models changed; the read that follows
17
+ * goes through the route like any other, so it sees only what the viewer may.
13
18
  */
14
19
  import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
15
- import { ApiError } from "./index.js";
20
+ import { ApiError, } from "./index.js";
16
21
  import { sessionFetch } from "./browser.js";
17
22
  import { choicesOf, columnsOf, display, formFieldsOf, initialValue, problemField, selectFor, sortOptions, toRecordValue, unchanged, } from "./auto.js";
18
23
  export { labelOf, recordLabel } from "./auto.js";
@@ -24,8 +29,8 @@ export function createRecordsClient(o = {}) {
24
29
  const changed = (model) => { for (const l of listeners)
25
30
  l(model); };
26
31
  const descriptions = new Map();
27
- async function call(body) {
28
- const res = await send(endpoint, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
32
+ async function call(body, signal) {
33
+ const res = await send(endpoint, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), ...(signal ? { signal } : {}) });
29
34
  const text = await res.text();
30
35
  let json = {};
31
36
  try {
@@ -45,7 +50,8 @@ export function createRecordsClient(o = {}) {
45
50
  descriptions.set(name, call({ op: "describe", model: name }).catch((e) => { descriptions.delete(name); throw e; }));
46
51
  return descriptions.get(name);
47
52
  },
48
- findMany: (options = {}) => call({ op: "findMany", model: name, options }),
53
+ findMany: (options = {}) => call({ op: "findMany", model: name, options: options }),
54
+ aggregate: (options) => call({ op: "aggregate", model: name, options }),
49
55
  findOne: async (id, q = {}) => {
50
56
  try {
51
57
  return await call({ op: "findOne", model: name, id, ...(q.select ? { select: q.select } : {}) });
@@ -71,12 +77,74 @@ export function createRecordsClient(o = {}) {
71
77
  return { directUploadToken: up.token };
72
78
  },
73
79
  });
80
+ // Live queries: one watch for every model a listener names, asked again as soon as it answers. The cursor carries
81
+ // over when the models change, so nothing in between is missed (at worst a model is read once more).
82
+ const live = new Map();
83
+ let cursor = null;
84
+ let running = null;
85
+ // A set of models the route refused (an older SDK's route, a model it doesn't serve, a role that can't read one).
86
+ let refused = null;
87
+ const hidden = () => typeof document !== "undefined" && document.visibilityState === "hidden";
88
+ function rewatch() {
89
+ const key = [...new Set([...live.values()].flat())].sort().join(",");
90
+ if (running && running.key === key && !hidden())
91
+ return;
92
+ running?.abort.abort();
93
+ running = null;
94
+ if (!key || key === refused || hidden())
95
+ return;
96
+ const run = { key, abort: new AbortController() };
97
+ running = run;
98
+ void (async () => {
99
+ for (let failures = 0; running === run;) {
100
+ try {
101
+ const r = await call({ op: "changes", models: key.split(","), cursor }, run.abort.signal);
102
+ if (running !== run)
103
+ return;
104
+ cursor = r.cursor;
105
+ failures = 0;
106
+ if (r.models.length)
107
+ for (const [l, watched] of live) {
108
+ const hit = r.models.filter((m) => watched.includes(m));
109
+ if (hit.length)
110
+ l(hit);
111
+ }
112
+ }
113
+ catch (e) {
114
+ if (running !== run)
115
+ return;
116
+ if (e instanceof ApiError && [400, 403, 404, 405].includes(e.status)) {
117
+ refused = key;
118
+ running = null;
119
+ console.warn(`Live queries for ${key} are off: ${e.message}`);
120
+ return;
121
+ }
122
+ // Offline, or the route failed: try again, backing off to half a minute.
123
+ await new Promise((done) => setTimeout(done, Math.min(30_000, 1_000 * 2 ** ++failures)));
124
+ }
125
+ }
126
+ })();
127
+ }
74
128
  const models = new Map();
75
129
  return {
76
- model: (name) => { if (!models.has(name))
77
- models.set(name, model(name)); return models.get(name); },
78
- global: (action, params = {}) => call({ op: "global", action, params }),
130
+ model: ((name) => { if (!models.has(name))
131
+ models.set(name, model(name)); return models.get(name); }),
132
+ global: (action, params) => call({ op: "global", action, params: (params ?? {}) }),
133
+ enqueue: (action, params, { runAt, ...q } = {}) => call({ op: "enqueue", action, params: (params ?? {}), options: { ...q, ...(runAt ? { runAt: runAt instanceof Date ? runAt.toISOString() : runAt } : {}) } }),
79
134
  subscribe: (l) => { listeners.add(l); return () => { listeners.delete(l); }; },
135
+ watch(names, l) {
136
+ const fn = (m) => l(m);
137
+ if (!live.size && typeof document !== "undefined")
138
+ document.addEventListener("visibilitychange", rewatch);
139
+ live.set(fn, names);
140
+ rewatch();
141
+ return () => {
142
+ live.delete(fn);
143
+ if (!live.size && typeof document !== "undefined")
144
+ document.removeEventListener("visibilitychange", rewatch);
145
+ rewatch();
146
+ };
147
+ },
80
148
  };
81
149
  }
82
150
  const Context = createContext(null);
@@ -95,8 +163,11 @@ export function useRecordsClient() {
95
163
  return fallback;
96
164
  }
97
165
  const asApiError = (e) => (e instanceof ApiError ? e : new ApiError(e instanceof Error ? e.message : String(e), 0, null));
98
- /** A read that runs again when its key changes, when it's asked to, and when a write through the client changes its model. */
99
- function useQuery(model, key, read) {
166
+ /**
167
+ * A read that runs again when its key changes, when it's asked to, and when a write through the client changes its
168
+ * model; when `live`, also when anyone's does.
169
+ */
170
+ function useQuery(model, key, read, live = false) {
100
171
  const client = useRecordsClient();
101
172
  const [state, setState] = useState({ key, data: undefined, error: null, fetching: !!read });
102
173
  const [nonce, setNonce] = useState(0);
@@ -118,28 +189,65 @@ function useQuery(model, key, read) {
118
189
  }, [key, nonce, !!read]);
119
190
  useEffect(() => client.subscribe((m) => { if (m === model)
120
191
  setNonce((n) => n + 1); }), [client, model]);
192
+ const watching = live && !!read;
193
+ useEffect(() => (watching && client.watch ? client.watch([model], () => setNonce((n) => n + 1)) : undefined), [client, model, watching]);
121
194
  const refetch = useCallback(() => setNonce((n) => n + 1), []);
122
195
  return { data: state.key === key ? state.data : undefined, fetching: state.fetching, error: state.error, refetch };
123
196
  }
124
- /** A page of a model's records. Pass `pause` to hold off (until an id is known, say). */
197
+ /** The model through the client without its generated types, for the hooks' own calls (their signatures carry them). */
198
+ const untyped = (client, model) => client.model(model);
199
+ /**
200
+ * A page of a model's records, typed by the app's generated client types: `filter`, `sort` and `select` name its
201
+ * fields, and the records are what `select` picks. `nextPage` and `previousPage` move through the list by cursor; a
202
+ * change to the options starts again from the first page. Pass `pause` to hold off (until an id is known, say), and
203
+ * `live` to read again whenever its records change.
204
+ *
205
+ * const reviews = useFindMany("review", { filter: { rating: { lessThan: 3 } }, select: { rating: true, product: { select: { title: true } } } });
206
+ * reviews.data?.records[0]?.product?.title;
207
+ */
125
208
  export function useFindMany(model, options = {}, o = {}) {
126
209
  const client = useRecordsClient();
127
- return useQuery(model, `${model}:many:${JSON.stringify(options)}`, o.pause ? null : () => client.model(model).findMany(options));
210
+ const key = `${model}:many:${JSON.stringify(options)}`;
211
+ // The cursors of the pages past the first: kept for the options they were read with, so new ones start again.
212
+ const [pages, setPages] = useState({ key, cursors: [] });
213
+ const cursors = pages.key === key ? pages.cursors : [];
214
+ const after = cursors[cursors.length - 1];
215
+ // Past the first page the cursor says where to start, whatever `skip` the first one had.
216
+ const read = (after ? { ...options, skip: undefined, after } : options);
217
+ const q = useQuery(model, `${key}:${after ?? ""}`, o.pause ? null : () => untyped(client, model).findMany(read), o.live);
218
+ const end = q.data?.hasNextPage ? q.data.endCursor : null;
219
+ return {
220
+ ...q,
221
+ page: cursors.length + 1,
222
+ hasNextPage: !!end,
223
+ hasPreviousPage: cursors.length > 0,
224
+ nextPage: () => { if (end)
225
+ setPages({ key, cursors: [...cursors, end] }); },
226
+ previousPage: () => { if (cursors.length)
227
+ setPages({ key, cursors: cursors.slice(0, -1) }); },
228
+ resetPages: () => setPages({ key, cursors: [] }),
229
+ };
128
230
  }
129
231
  /** One record by id, or null when there's none the caller can read. */
130
232
  export function useFindOne(model, id, o = {}) {
131
233
  const client = useRecordsClient();
132
- return useQuery(model, `${model}:one:${id ?? ""}:${JSON.stringify(o.select ?? null)}`, !id || o.pause ? null : () => client.model(model).findOne(id, o.select ? { select: o.select } : {}));
234
+ const select = o.select;
235
+ return useQuery(model, `${model}:one:${id ?? ""}:${JSON.stringify(select ?? null)}`, !id || o.pause ? null : () => untyped(client, model).findOne(id, select ? { select: select } : {}), o.live);
133
236
  }
134
237
  /** The first record matching, or null. */
135
238
  export function useFindFirst(model, options = {}, o = {}) {
136
239
  const client = useRecordsClient();
137
- return useQuery(model, `${model}:first:${JSON.stringify(options)}`, o.pause ? null : async () => (await client.model(model).findMany({ ...options, first: 1 })).records[0] ?? null);
240
+ return useQuery(model, `${model}:first:${JSON.stringify(options)}`, o.pause ? null : async () => (await untyped(client, model).findMany({ ...options, first: 1 })).records[0] ?? null, o.live);
241
+ }
242
+ /** Groups of a model's records with their counts, sums and averages, for a chart or a report; again after a write to it. */
243
+ export function useAggregate(model, options, o = {}) {
244
+ const client = useRecordsClient();
245
+ return useQuery(model, `${model}:aggregate:${JSON.stringify(options)}`, o.pause ? null : () => untyped(client, model).aggregate(options));
138
246
  }
139
247
  /** A model's description: its fields, which AutoTable and AutoForm draw from. */
140
248
  export function useModel(model) {
141
249
  const client = useRecordsClient();
142
- return useQuery(model, `${model}:describe`, () => client.model(model).describe());
250
+ return useQuery(model, `${model}:describe`, () => untyped(client, model).describe());
143
251
  }
144
252
  function useMutation(send) {
145
253
  const [state, setState] = useState({ data: undefined, running: false, error: null });
@@ -162,47 +270,69 @@ function useMutation(send) {
162
270
  }
163
271
  /**
164
272
  * One of a model's actions: `create`, `update` and `delete` write the way the API does (the model's action when it has
165
- * one), any other runs by name. Lists of the model refetch once it's done.
273
+ * one), any other runs by name. Its params and result are the action's, from the generated client types. Lists of
274
+ * the model refetch once it's done.
166
275
  *
167
276
  * const publish = useAction("post", "publish");
168
277
  * await publish.run({ id: post.id });
169
278
  */
170
279
  export function useAction(model, action) {
171
280
  const client = useRecordsClient();
172
- return useMutation(async ({ id, params = {} }) => {
173
- const m = client.model(model);
281
+ return useMutation(async ({ id, params }) => {
282
+ const m = untyped(client, model);
283
+ const values = (params ?? {});
174
284
  if (action === "create" && !id)
175
- return { record: await m.create(params) };
285
+ return { record: await m.create(values) };
176
286
  if (action === "update" && id)
177
- return { record: await m.update(id, params) };
287
+ return { record: await m.update(id, values) };
178
288
  if (action === "delete" && id) {
179
289
  await m.delete(id);
180
290
  return { record: null };
181
291
  }
182
- return m.run(action, { ...(id ? { id } : {}), params });
292
+ return m.run(action, { ...(id ? { id } : {}), params: values });
183
293
  });
184
294
  }
185
295
  /** A global action the records route allows (`serveRecords`'s `globalActions`). */
186
296
  export function useGlobalAction(action) {
187
297
  const client = useRecordsClient();
188
- return useMutation((params) => client.global(action, params ?? {}));
298
+ return useMutation((params) => client.global(action, params));
189
299
  }
300
+ /**
301
+ * Queues an action as a background job, a global action's name or `<model>.<action>`, when the records route allows
302
+ * it (`serveRecords`'s `enqueueActions`). `run` answers with the job once it's queued, not when it has run.
303
+ *
304
+ * const reindex = useEnqueue("post.reindex");
305
+ * await reindex.run({ id: post.id, delay: 60_000 });
306
+ */
307
+ export function useEnqueue(action) {
308
+ const client = useRecordsClient();
309
+ return useMutation((args) => {
310
+ const { params, ...options } = args ?? {};
311
+ if (!client.enqueue)
312
+ throw new ApiError("This records client can't queue jobs.", 0, null);
313
+ return client.enqueue(action, params, options);
314
+ });
315
+ }
316
+ // ---- AutoTable's core ----
317
+ // AutoTable and AutoForm work from a model's description, whatever the generated types say of it: the hooks untyped.
318
+ const useAnyModel = useModel;
319
+ const useAnyMany = useFindMany;
320
+ const useAnyOne = useFindOne;
190
321
  const SEARCH_WAIT = 250;
191
322
  /** What a table of the model shows and does, for a renderer to draw. */
192
323
  export function useAutoTable(model, o = {}) {
193
324
  const client = useRecordsClient();
194
- const described = useModel(model);
325
+ const described = useAnyModel(model);
195
326
  const columns = useMemo(() => (described.data ? columnsOf(described.data, o.columns) : []), [described.data, JSON.stringify(o.columns ?? null)]);
196
327
  const [search, setSearchNow] = useState("");
197
328
  const [query, setQuery] = useState("");
198
329
  const [sort, setSortValue] = useState("");
199
- const [cursors, setCursors] = useState([null]);
200
330
  const [selected, setSelected] = useState(new Set());
201
331
  const [deleting, setDeleting] = useState(false);
202
332
  const [deleteError, setDeleteError] = useState(null);
203
- // Typing waits a moment before reading, and starts from the first page.
333
+ // Typing waits a moment before reading (a new search starts from the first page, as any new options do).
204
334
  useEffect(() => {
205
- const t = setTimeout(() => { setQuery(search.trim()); setCursors([null]); }, SEARCH_WAIT);
335
+ const t = setTimeout(() => setQuery(search.trim()), SEARCH_WAIT);
206
336
  return () => clearTimeout(t);
207
337
  }, [search]);
208
338
  const options = sortOptions(columns);
@@ -210,17 +340,19 @@ export function useAutoTable(model, o = {}) {
210
340
  const order = chosen ? { [chosen.field]: chosen.direction } : o.sort;
211
341
  const findOptions = {
212
342
  first: Math.min(o.pageSize ?? 25, 250),
213
- after: cursors[cursors.length - 1] ?? null,
214
343
  ...(columns.length ? { select: selectFor(columns) } : {}),
215
344
  ...(o.filter ? { filter: o.filter } : {}),
216
345
  ...(order ? { sort: order } : {}),
217
346
  ...(query ? { search: query } : {}),
218
347
  };
219
- const page = useFindMany(model, findOptions, { pause: !described.data });
348
+ const page = useAnyMany(model, findOptions, { pause: !described.data, live: !!o.live });
220
349
  const records = page.data?.records ?? [];
221
350
  const rows = records.map((record) => ({ id: record.id, record, cells: columns.map((c) => display(c.field, record[c.name])) }));
222
- // A new page chooses nothing.
223
- useEffect(() => { setSelected(new Set()); }, [page.data]);
351
+ // A new page chooses nothing; the same page read again keeps the rows still on it chosen.
352
+ useEffect(() => {
353
+ const ids = new Set((page.data?.records ?? []).map((r) => r.id));
354
+ setSelected((s) => (s.size && [...s].some((id) => !ids.has(id)) ? new Set([...s].filter((id) => ids.has(id))) : s));
355
+ }, [page.data]);
224
356
  const allSelected = rows.length > 0 && rows.every((r) => selected.has(r.id));
225
357
  return {
226
358
  description: described.data,
@@ -232,18 +364,16 @@ export function useAutoTable(model, o = {}) {
232
364
  setSearch: setSearchNow,
233
365
  sortOptions: options,
234
366
  sort,
235
- setSort: (v) => { setSortValue(v); setCursors([null]); },
367
+ setSort: setSortValue,
236
368
  toggleSort: (name) => {
237
369
  const asc = `${name}:Ascending`, desc = `${name}:Descending`;
238
370
  setSortValue(sort === asc ? desc : asc);
239
- setCursors([null]);
240
371
  },
241
- page: cursors.length,
242
- hasNextPage: !!page.data?.hasNextPage,
243
- hasPreviousPage: cursors.length > 1,
244
- nextPage: () => { if (page.data?.hasNextPage && page.data.endCursor)
245
- setCursors((c) => [...c, page.data.endCursor]); },
246
- previousPage: () => setCursors((c) => (c.length > 1 ? c.slice(0, -1) : c)),
372
+ page: page.page,
373
+ hasNextPage: page.hasNextPage,
374
+ hasPreviousPage: page.hasPreviousPage,
375
+ nextPage: page.nextPage,
376
+ previousPage: page.previousPage,
247
377
  selected,
248
378
  toggle: (id) => setSelected((s) => { const n = new Set(s); if (n.has(id))
249
379
  n.delete(id);
@@ -257,11 +387,11 @@ export function useAutoTable(model, o = {}) {
257
387
  setDeleting(true);
258
388
  setDeleteError(null);
259
389
  try {
260
- const r = await client.model(model).bulkDelete([...selected]);
390
+ const r = await untyped(client, model).bulkDelete([...selected]);
261
391
  if (r.failed.length)
262
392
  setDeleteError(new ApiError(r.failed.length === 1 ? r.failed[0].error.message : `${r.failed.length} records weren't deleted: ${r.failed[0].error.message}`, 400, "bulk_failed"));
263
393
  // The page may now be short or empty; start again from the first.
264
- setCursors([null]);
394
+ page.resetPages();
265
395
  }
266
396
  catch (e) {
267
397
  setDeleteError(asApiError(e));
@@ -277,7 +407,7 @@ export function useAutoTable(model, o = {}) {
277
407
  /** What a form for the model shows and does, for a renderer to draw. */
278
408
  export function useAutoForm(model, o = {}) {
279
409
  const client = useRecordsClient();
280
- const described = useModel(model);
410
+ const described = useAnyModel(model);
281
411
  const specs = useMemo(() => (described.data ? formFieldsOf(described.data, o.fields, o.exclude) : []), [described.data, JSON.stringify(o.fields ?? null), JSON.stringify(o.exclude ?? null)]);
282
412
  const select = useMemo(() => {
283
413
  const s = {};
@@ -286,7 +416,7 @@ export function useAutoForm(model, o = {}) {
286
416
  s[f.name] = true;
287
417
  return s;
288
418
  }, [specs]);
289
- const existing = useFindOne(model, o.id, { select, pause: !specs.length });
419
+ const existing = useAnyOne(model, o.id, { select: select, pause: !specs.length });
290
420
  const record = o.id ? existing.data : undefined;
291
421
  const initial = useMemo(() => {
292
422
  const out = {};
@@ -310,7 +440,7 @@ export function useAutoForm(model, o = {}) {
310
440
  for (const s of specs) {
311
441
  if (s.kind !== "record" || !s.parent)
312
442
  continue;
313
- client.model(s.parent).findMany({ first: 100 }).then((p) => { if (live)
443
+ untyped(client, s.parent).findMany({ first: 100 }).then((p) => { if (live)
314
444
  setChoices((c) => ({ ...c, [s.name]: choicesOf(p.records) })); }, () => { });
315
445
  }
316
446
  return () => { live = false; };
@@ -363,7 +493,7 @@ export function useAutoForm(model, o = {}) {
363
493
  setSubmitting(true);
364
494
  setError(null);
365
495
  try {
366
- const m = client.model(model);
496
+ const m = untyped(client, model);
367
497
  for (const s of specs) {
368
498
  const v = value(s.name);
369
499
  if (s.kind === "file" && typeof File !== "undefined" && v instanceof File)
package/dist/runtime.d.ts CHANGED
@@ -72,7 +72,7 @@ export declare function sign(token: string, timestamp: string, body: string): Pr
72
72
  /**
73
73
  * Runs one phase of an action, without checking where the request came from (handleAction does). `api`, `shopify`
74
74
  * and `ai` stand in for the environment's clients (the test app's in-memory ones); `echo: false` keeps the logger's
75
- * lines off the console.
75
+ * lines off the console; `sentry` stands in for SENTRY_DSN, and false (the test app's) reports nothing.
76
76
  */
77
77
  export declare function runAction(req: ActionRequest, registry: ActionRegistry, o?: {
78
78
  token?: string;
@@ -82,6 +82,10 @@ export declare function runAction(req: ActionRequest, registry: ActionRegistry,
82
82
  echo?: boolean;
83
83
  signal?: AbortSignal;
84
84
  trace?: boolean;
85
+ sentry?: {
86
+ dsn: string;
87
+ fetch?: typeof fetch;
88
+ } | false;
85
89
  }): Promise<ActionResponse>;
86
90
  /** The `/_ib/actions` route: a signed request from Inference Bureau, or 404 for anyone else. */
87
91
  export declare function handleAction(request: Request, registry: ActionRegistry, o?: {