@inferencebureau/apps-sdk 0.12.0 → 0.14.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/dist/react.js ADDED
@@ -0,0 +1,488 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ /**
4
+ * React for an app's pages: hooks that read and change records, and AutoTable and AutoForm, which draw a model's list
5
+ * and its create and edit forms from its schema. They call the app's records route (`serveRecords`, at
6
+ * /api/records unless the provider names another), which answers as whoever the request is from: the merchant in the
7
+ * Shopify admin (its session token goes with every request) or a signed-in user (their cookie does).
8
+ *
9
+ * The components here are the plain ones: standard elements with the starters' classes (`.btn`, `.auto-*` in
10
+ * globals.css) and their CSS variables, so they look like the rest of the app. `@inferencebureau/apps-sdk/polaris`
11
+ * draws the same tables and forms in Polaris web components. Both draw what `useAutoTable` and `useAutoForm` work out,
12
+ * which a page can use to draw its own.
13
+ */
14
+ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
15
+ import { ApiError } from "./index.js";
16
+ import { sessionFetch } from "./browser.js";
17
+ import { choicesOf, columnsOf, display, formFieldsOf, initialValue, problemField, selectFor, sortOptions, toRecordValue, unchanged, } from "./auto.js";
18
+ export { labelOf, recordLabel } from "./auto.js";
19
+ /** A client for the app's records route, for a page's own scripts. Most pages use the hooks, which make one. */
20
+ export function createRecordsClient(o = {}) {
21
+ const endpoint = o.endpoint ?? "/api/records";
22
+ const send = o.fetch ?? sessionFetch;
23
+ const listeners = new Set();
24
+ const changed = (model) => { for (const l of listeners)
25
+ l(model); };
26
+ 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) });
29
+ const text = await res.text();
30
+ let json = {};
31
+ try {
32
+ json = text ? JSON.parse(text) : {};
33
+ }
34
+ catch { /* reported below */ }
35
+ if (!res.ok) {
36
+ const fallback = res.status === 404 ? `There's no records route at ${endpoint}.` : `The records route answered ${res.status}.`;
37
+ throw new ApiError(json.error?.message ?? fallback, res.status, json.error?.code ?? null, json.error?.problems ?? []);
38
+ }
39
+ return json;
40
+ }
41
+ const writes = (model, p) => p.then((v) => { changed(model); return v; });
42
+ const model = (name) => ({
43
+ describe() {
44
+ if (!descriptions.has(name))
45
+ descriptions.set(name, call({ op: "describe", model: name }).catch((e) => { descriptions.delete(name); throw e; }));
46
+ return descriptions.get(name);
47
+ },
48
+ findMany: (options = {}) => call({ op: "findMany", model: name, options }),
49
+ findOne: async (id, q = {}) => {
50
+ try {
51
+ return await call({ op: "findOne", model: name, id, ...(q.select ? { select: q.select } : {}) });
52
+ }
53
+ catch (e) {
54
+ if (e instanceof ApiError && e.status === 404)
55
+ return null;
56
+ throw e;
57
+ }
58
+ },
59
+ create: (values) => writes(name, call({ op: "create", model: name, values })),
60
+ update: (id, values) => writes(name, call({ op: "update", model: name, id, values })),
61
+ delete: (id) => writes(name, call({ op: "delete", model: name, id })).then(() => undefined),
62
+ bulkDelete: (ids) => writes(name, call({ op: "bulkDelete", model: name, ids })),
63
+ run: (action, q = {}) => writes(name, call({ op: "run", model: name, action, ...(q.id ? { id: q.id } : {}), params: q.params ?? {} })),
64
+ async upload(field, file, q = {}) {
65
+ const fileName = q.fileName ?? (typeof File !== "undefined" && file instanceof File ? file.name : undefined);
66
+ const up = await call({ op: "createUpload", model: name, field, size: file.size, ...(fileName ? { fileName } : {}), ...(file.type ? { mimeType: file.type } : {}) });
67
+ // Straight to storage: not the app's route, so no session token.
68
+ const res = await fetch(up.url, { method: "PUT", headers: up.headers, body: file });
69
+ if (!res.ok)
70
+ throw new ApiError(`The upload was refused (${res.status}).`, res.status, "upload_failed");
71
+ return { directUploadToken: up.token };
72
+ },
73
+ });
74
+ const models = new Map();
75
+ 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 }),
79
+ subscribe: (l) => { listeners.add(l); return () => { listeners.delete(l); }; },
80
+ };
81
+ }
82
+ const Context = createContext(null);
83
+ let fallback = null;
84
+ /** Gives the hooks and components below it a client: one for another route, or with another fetch. Optional. */
85
+ export function RecordsProvider({ client, endpoint, children }) {
86
+ const value = useMemo(() => client ?? createRecordsClient(endpoint ? { endpoint } : {}), [client, endpoint]);
87
+ return _jsx(Context.Provider, { value: value, children: children });
88
+ }
89
+ /** The provider's client, or one for /api/records. */
90
+ export function useRecordsClient() {
91
+ const c = useContext(Context);
92
+ if (c)
93
+ return c;
94
+ fallback ??= createRecordsClient();
95
+ return fallback;
96
+ }
97
+ 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) {
100
+ const client = useRecordsClient();
101
+ const [state, setState] = useState({ key, data: undefined, error: null, fetching: !!read });
102
+ const [nonce, setNonce] = useState(0);
103
+ const readRef = useRef(read);
104
+ readRef.current = read;
105
+ useEffect(() => {
106
+ const r = readRef.current;
107
+ if (!r) {
108
+ setState((s) => ({ ...s, key, fetching: false }));
109
+ return;
110
+ }
111
+ let live = true;
112
+ // A new key forgets the old answer; a refetch keeps it showing until the new one comes.
113
+ setState((s) => ({ key, data: s.key === key ? s.data : undefined, error: null, fetching: true }));
114
+ r().then((data) => { if (live)
115
+ setState({ key, data, error: null, fetching: false }); }, (e) => { if (live)
116
+ setState((s) => ({ ...s, key, error: asApiError(e), fetching: false })); });
117
+ return () => { live = false; };
118
+ }, [key, nonce, !!read]);
119
+ useEffect(() => client.subscribe((m) => { if (m === model)
120
+ setNonce((n) => n + 1); }), [client, model]);
121
+ const refetch = useCallback(() => setNonce((n) => n + 1), []);
122
+ return { data: state.key === key ? state.data : undefined, fetching: state.fetching, error: state.error, refetch };
123
+ }
124
+ /** A page of a model's records. Pass `pause` to hold off (until an id is known, say). */
125
+ export function useFindMany(model, options = {}, o = {}) {
126
+ const client = useRecordsClient();
127
+ return useQuery(model, `${model}:many:${JSON.stringify(options)}`, o.pause ? null : () => client.model(model).findMany(options));
128
+ }
129
+ /** One record by id, or null when there's none the caller can read. */
130
+ export function useFindOne(model, id, o = {}) {
131
+ 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 } : {}));
133
+ }
134
+ /** The first record matching, or null. */
135
+ export function useFindFirst(model, options = {}, o = {}) {
136
+ 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);
138
+ }
139
+ /** A model's description: its fields, which AutoTable and AutoForm draw from. */
140
+ export function useModel(model) {
141
+ const client = useRecordsClient();
142
+ return useQuery(model, `${model}:describe`, () => client.model(model).describe());
143
+ }
144
+ function useMutation(send) {
145
+ const [state, setState] = useState({ data: undefined, running: false, error: null });
146
+ const sendRef = useRef(send);
147
+ sendRef.current = send;
148
+ const run = useCallback(async (args) => {
149
+ setState((s) => ({ ...s, running: true, error: null }));
150
+ try {
151
+ const data = await sendRef.current(args);
152
+ setState({ data, running: false, error: null });
153
+ return data;
154
+ }
155
+ catch (e) {
156
+ const error = asApiError(e);
157
+ setState((s) => ({ ...s, running: false, error }));
158
+ throw error;
159
+ }
160
+ }, []);
161
+ return { ...state, run };
162
+ }
163
+ /**
164
+ * 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.
166
+ *
167
+ * const publish = useAction("post", "publish");
168
+ * await publish.run({ id: post.id });
169
+ */
170
+ export function useAction(model, action) {
171
+ const client = useRecordsClient();
172
+ return useMutation(async ({ id, params = {} }) => {
173
+ const m = client.model(model);
174
+ if (action === "create" && !id)
175
+ return { record: await m.create(params) };
176
+ if (action === "update" && id)
177
+ return { record: await m.update(id, params) };
178
+ if (action === "delete" && id) {
179
+ await m.delete(id);
180
+ return { record: null };
181
+ }
182
+ return m.run(action, { ...(id ? { id } : {}), params });
183
+ });
184
+ }
185
+ /** A global action the records route allows (`serveRecords`'s `globalActions`). */
186
+ export function useGlobalAction(action) {
187
+ const client = useRecordsClient();
188
+ return useMutation((params) => client.global(action, params ?? {}));
189
+ }
190
+ const SEARCH_WAIT = 250;
191
+ /** What a table of the model shows and does, for a renderer to draw. */
192
+ export function useAutoTable(model, o = {}) {
193
+ const client = useRecordsClient();
194
+ const described = useModel(model);
195
+ const columns = useMemo(() => (described.data ? columnsOf(described.data, o.columns) : []), [described.data, JSON.stringify(o.columns ?? null)]);
196
+ const [search, setSearchNow] = useState("");
197
+ const [query, setQuery] = useState("");
198
+ const [sort, setSortValue] = useState("");
199
+ const [cursors, setCursors] = useState([null]);
200
+ const [selected, setSelected] = useState(new Set());
201
+ const [deleting, setDeleting] = useState(false);
202
+ const [deleteError, setDeleteError] = useState(null);
203
+ // Typing waits a moment before reading, and starts from the first page.
204
+ useEffect(() => {
205
+ const t = setTimeout(() => { setQuery(search.trim()); setCursors([null]); }, SEARCH_WAIT);
206
+ return () => clearTimeout(t);
207
+ }, [search]);
208
+ const options = sortOptions(columns);
209
+ const chosen = options.find((s) => s.value === sort && s.field);
210
+ const order = chosen ? { [chosen.field]: chosen.direction } : o.sort;
211
+ const findOptions = {
212
+ first: Math.min(o.pageSize ?? 25, 250),
213
+ after: cursors[cursors.length - 1] ?? null,
214
+ ...(columns.length ? { select: selectFor(columns) } : {}),
215
+ ...(o.filter ? { filter: o.filter } : {}),
216
+ ...(order ? { sort: order } : {}),
217
+ ...(query ? { search: query } : {}),
218
+ };
219
+ const page = useFindMany(model, findOptions, { pause: !described.data });
220
+ const records = page.data?.records ?? [];
221
+ 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]);
224
+ const allSelected = rows.length > 0 && rows.every((r) => selected.has(r.id));
225
+ return {
226
+ description: described.data,
227
+ columns,
228
+ rows,
229
+ fetching: described.fetching || page.fetching || (!!described.data && !page.data && !page.error),
230
+ error: deleteError ?? described.error ?? page.error,
231
+ search,
232
+ setSearch: setSearchNow,
233
+ sortOptions: options,
234
+ sort,
235
+ setSort: (v) => { setSortValue(v); setCursors([null]); },
236
+ toggleSort: (name) => {
237
+ const asc = `${name}:Ascending`, desc = `${name}:Descending`;
238
+ setSortValue(sort === asc ? desc : asc);
239
+ setCursors([null]);
240
+ },
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)),
247
+ selected,
248
+ toggle: (id) => setSelected((s) => { const n = new Set(s); if (n.has(id))
249
+ n.delete(id);
250
+ else
251
+ n.add(id); return n; }),
252
+ toggleAll: () => setSelected(allSelected ? new Set() : new Set(rows.map((r) => r.id))),
253
+ allSelected,
254
+ async deleteSelected() {
255
+ if (!selected.size)
256
+ return;
257
+ setDeleting(true);
258
+ setDeleteError(null);
259
+ try {
260
+ const r = await client.model(model).bulkDelete([...selected]);
261
+ if (r.failed.length)
262
+ 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
+ // The page may now be short or empty; start again from the first.
264
+ setCursors([null]);
265
+ }
266
+ catch (e) {
267
+ setDeleteError(asApiError(e));
268
+ }
269
+ finally {
270
+ setDeleting(false);
271
+ }
272
+ },
273
+ deleting,
274
+ refetch: page.refetch,
275
+ };
276
+ }
277
+ /** What a form for the model shows and does, for a renderer to draw. */
278
+ export function useAutoForm(model, o = {}) {
279
+ const client = useRecordsClient();
280
+ const described = useModel(model);
281
+ 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
+ const select = useMemo(() => {
283
+ const s = {};
284
+ for (const f of specs)
285
+ if (f.kind !== "password")
286
+ s[f.name] = true;
287
+ return s;
288
+ }, [specs]);
289
+ const existing = useFindOne(model, o.id, { select, pause: !specs.length });
290
+ const record = o.id ? existing.data : undefined;
291
+ const initial = useMemo(() => {
292
+ const out = {};
293
+ for (const s of specs) {
294
+ const from = record ? record[s.name] : o.defaultValues && s.name in o.defaultValues ? o.defaultValues[s.name] : s.field.default;
295
+ out[s.name] = initialValue(s, from);
296
+ }
297
+ return out;
298
+ }, [specs, record, JSON.stringify(o.defaultValues ?? null)]);
299
+ const [values, setValues] = useState({});
300
+ const [errors, setErrors] = useState({});
301
+ const [error, setError] = useState(null);
302
+ const [submitting, setSubmitting] = useState(false);
303
+ const [saved, setSaved] = useState(false);
304
+ const [choices, setChoices] = useState({});
305
+ // The form starts again whenever what it starts from changes (the record loads, or is saved).
306
+ useEffect(() => { setValues(initial); setErrors({}); }, [initial]);
307
+ // Each belongsTo's records, for its picker.
308
+ useEffect(() => {
309
+ let live = true;
310
+ for (const s of specs) {
311
+ if (s.kind !== "record" || !s.parent)
312
+ continue;
313
+ client.model(s.parent).findMany({ first: 100 }).then((p) => { if (live)
314
+ setChoices((c) => ({ ...c, [s.name]: choicesOf(p.records) })); }, () => { });
315
+ }
316
+ return () => { live = false; };
317
+ }, [client, specs]);
318
+ const value = (name) => (name in values ? values[name] : initial[name] ?? null);
319
+ const fields = specs.map((s) => {
320
+ const current = s.kind === "file" && record && record[s.name] && typeof record[s.name] === "object" ? record[s.name] : null;
321
+ const own = choices[s.name] ?? [];
322
+ const v = value(s.name);
323
+ // The record's own parent, when it isn't among the first hundred.
324
+ const withCurrent = s.kind === "record" && typeof v === "string" && v && !own.some((c) => c.value === v) ? [{ value: v, label: v }, ...own] : own;
325
+ return {
326
+ ...s, value: v, error: errors[s.name] ?? null, choices: withCurrent, current,
327
+ set: (next) => {
328
+ setValues((vs) => ({ ...vs, [s.name]: next }));
329
+ setErrors((es) => { if (!(s.name in es))
330
+ return es; const { [s.name]: _gone, ...rest } = es; return rest; });
331
+ setSaved(false);
332
+ },
333
+ };
334
+ });
335
+ const dirty = specs.some((s) => !unchanged(value(s.name), initial[s.name] ?? null));
336
+ async function submit(event) {
337
+ event?.preventDefault();
338
+ if (submitting || !described.data)
339
+ return;
340
+ const out = {};
341
+ const problems = {};
342
+ for (const s of specs) {
343
+ const v = value(s.name);
344
+ // An edit sends what changed; a new record what's filled in, so the rest take their defaults.
345
+ if (o.id && !o.action && unchanged(v, initial[s.name] ?? null))
346
+ continue;
347
+ const r = toRecordValue(s, v);
348
+ if (!r.ok) {
349
+ problems[s.name] = r.message;
350
+ continue;
351
+ }
352
+ if (r.value === undefined)
353
+ continue;
354
+ if (!o.id && !o.action && (r.value === null || (Array.isArray(r.value) && !r.value.length)) && s.kind !== "boolean")
355
+ continue;
356
+ out[s.name] = r.value;
357
+ }
358
+ setErrors(problems);
359
+ if (Object.keys(problems).length) {
360
+ setError(null);
361
+ return;
362
+ }
363
+ setSubmitting(true);
364
+ setError(null);
365
+ try {
366
+ const m = client.model(model);
367
+ for (const s of specs) {
368
+ const v = value(s.name);
369
+ if (s.kind === "file" && typeof File !== "undefined" && v instanceof File)
370
+ out[s.name] = await m.upload(s.name, v);
371
+ }
372
+ let written;
373
+ let result;
374
+ if (o.action)
375
+ ({ record: written, result } = await m.run(o.action, { ...(o.id ? { id: o.id } : {}), params: out }));
376
+ else
377
+ written = o.id ? await m.update(o.id, out) : await m.create(out);
378
+ setSaved(true);
379
+ // A new record's form empties for the next one; an edit's starts again from what was saved (the refetch).
380
+ if (!o.id) {
381
+ setValues(initial);
382
+ setErrors({});
383
+ }
384
+ o.onSuccess?.(written, result);
385
+ }
386
+ catch (e) {
387
+ const err = asApiError(e);
388
+ const byField = {};
389
+ const other = [];
390
+ for (const p of err.problems) {
391
+ const name = problemField(p.field);
392
+ // The API words a problem to follow the field's name ("must be at most 5"); under its label it starts a sentence.
393
+ if (specs.some((s) => s.name === name))
394
+ byField[name] = byField[name] ?? p.message.charAt(0).toUpperCase() + p.message.slice(1);
395
+ else
396
+ other.push(`${p.field} ${p.message}`);
397
+ }
398
+ setErrors(byField);
399
+ setError(other.length ? other.join("; ") : Object.keys(byField).length ? null : err.message);
400
+ }
401
+ finally {
402
+ setSubmitting(false);
403
+ }
404
+ }
405
+ return {
406
+ description: described.data,
407
+ fields,
408
+ // An edit waits for its record, so the fields never show empty first.
409
+ loading: described.fetching || (!!o.id && existing.data === undefined && !existing.error),
410
+ submitting,
411
+ error: error ?? described.error?.message ?? existing.error?.message ?? (o.id && !existing.fetching && specs.length && existing.data === null ? "There's no such record, or it can't be read here." : null),
412
+ saved,
413
+ dirty,
414
+ submit,
415
+ reset: () => { setValues(initial); setErrors({}); setError(null); setSaved(false); },
416
+ isNew: !o.id,
417
+ };
418
+ }
419
+ // ---- the plain renderer ----
420
+ const cx = (...xs) => xs.filter(Boolean).join(" ");
421
+ /** A cell as standard elements, for the plain table. */
422
+ export function PlainCell({ value }) {
423
+ switch (value.kind) {
424
+ case "empty": return _jsx("span", { className: "auto-empty", children: "\u2014" });
425
+ case "boolean": return _jsx("span", { className: cx("auto-tag", value.value && "on"), children: value.text });
426
+ case "tags": return _jsx("span", { className: "auto-tags", children: value.tags.map((t) => _jsx("span", { className: "auto-tag", children: t }, t)) });
427
+ case "link": return _jsx("a", { className: "auto-link", href: value.href, target: value.href.startsWith("mailto:") ? undefined : "_blank", rel: "noreferrer", onClick: (e) => e.stopPropagation(), children: value.text });
428
+ case "color": return _jsxs("span", { className: "auto-color", children: [_jsx("i", { style: { background: value.color } }), value.color] });
429
+ case "file": return value.href
430
+ ? _jsxs("a", { className: "auto-file", href: value.href, target: "_blank", rel: "noreferrer", onClick: (e) => e.stopPropagation(), children: [value.image && _jsx("img", { src: value.image, alt: "" }), value.text] })
431
+ : _jsx("span", { className: "auto-file", children: value.text });
432
+ default: return _jsx("span", { className: cx(value.mono && "auto-mono"), children: value.text });
433
+ }
434
+ }
435
+ /** A model's records as a table: search, sort by a column's heading, pages, and bulk delete when `selectable`. */
436
+ export function AutoTable({ model, rowHref, onRowClick, emptyText, searchable = true, ...o }) {
437
+ const t = useAutoTable(model, o);
438
+ const [confirming, setConfirming] = useState(false);
439
+ useEffect(() => { if (!t.selected.size)
440
+ setConfirming(false); }, [t.selected.size]);
441
+ const open = (r) => { if (onRowClick)
442
+ onRowClick(r);
443
+ else if (rowHref)
444
+ window.location.assign(rowHref(r)); };
445
+ const clickable = !!(onRowClick || rowHref);
446
+ const sortedBy = t.sortOptions.find((s) => s.value === t.sort && s.field);
447
+ const span = t.columns.length + (o.selectable ? 1 : 0);
448
+ return (_jsxs("div", { className: "auto-table", children: [(searchable || t.selected.size > 0) && (_jsx("div", { className: "auto-toolbar", children: t.selected.size > 0 ? (_jsxs(_Fragment, { children: [_jsxs("span", { className: "auto-count", children: [t.selected.size, " selected"] }), confirming ? (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", className: "btn sm danger", disabled: t.deleting, onClick: () => void t.deleteSelected(), children: t.deleting ? "Deleting…" : `Delete ${t.selected.size}` }), _jsx("button", { type: "button", className: "btn sm ghost", disabled: t.deleting, onClick: () => setConfirming(false), children: "Cancel" })] })) : (_jsx("button", { type: "button", className: "btn sm ghost", onClick: () => setConfirming(true), children: "Delete" }))] })) : (_jsx("input", { className: "auto-search", type: "search", placeholder: "Search", "aria-label": `Search ${model}`, value: t.search, onChange: (e) => t.setSearch(e.target.value) })) })), t.error && _jsx("p", { className: "auto-banner", role: "alert", children: t.error.message }), _jsx("div", { className: "auto-scroll", children: _jsxs("table", { "aria-busy": t.fetching, children: [_jsx("thead", { children: _jsxs("tr", { children: [o.selectable && _jsx("th", { className: "auto-check", children: _jsx("input", { type: "checkbox", "aria-label": "Choose every row", checked: t.allSelected, onChange: t.toggleAll }) }), t.columns.map((c) => {
449
+ const dir = sortedBy?.field === c.name ? sortedBy.direction : null;
450
+ return (_jsx("th", { className: cx(c.numeric && "num"), "aria-sort": dir === "Ascending" ? "ascending" : dir === "Descending" ? "descending" : undefined, children: c.sortable ? _jsxs("button", { type: "button", onClick: () => t.toggleSort(c.name), children: [c.label, dir && _jsx("span", { "aria-hidden": "true", children: dir === "Ascending" ? " ↑" : " ↓" })] }) : c.label }, c.name));
451
+ })] }) }), _jsxs("tbody", { children: [t.rows.map((r) => (_jsxs("tr", { className: cx(clickable && "clickable", t.selected.has(r.id) && "selected"), onClick: clickable ? () => open(r.record) : undefined, children: [o.selectable && _jsx("td", { className: "auto-check", onClick: (e) => e.stopPropagation(), children: _jsx("input", { type: "checkbox", "aria-label": "Choose this row", checked: t.selected.has(r.id), onChange: () => t.toggle(r.id) }) }), r.cells.map((cell, i) => (_jsx("td", { className: cx(t.columns[i].numeric && "num"), children: i === 0 && rowHref ? _jsx("a", { href: rowHref(r.record), onClick: (e) => { e.stopPropagation(); if (onRowClick) {
452
+ e.preventDefault();
453
+ onRowClick(r.record);
454
+ } }, children: _jsx(PlainCell, { value: cell }) }) : _jsx(PlainCell, { value: cell }) }, t.columns[i].name)))] }, r.id))), !t.rows.length && (_jsx("tr", { className: "auto-none", children: _jsx("td", { colSpan: span || 1, children: t.fetching ? "Loading…" : t.search ? "No records match." : emptyText ?? "No records yet." }) }))] })] }) }), (t.hasNextPage || t.hasPreviousPage) && (_jsxs("div", { className: "auto-pager", children: [_jsx("button", { type: "button", className: "btn sm ghost", disabled: !t.hasPreviousPage || t.fetching, onClick: t.previousPage, children: "Previous" }), _jsxs("span", { children: ["Page ", t.page] }), _jsx("button", { type: "button", className: "btn sm ghost", disabled: !t.hasNextPage || t.fetching, onClick: t.nextPage, children: "Next" })] }))] }));
455
+ }
456
+ /** One field's control as standard elements, for the plain form. */
457
+ export function PlainInput({ field: f }) {
458
+ const id = `auto-${f.name}`;
459
+ const text = typeof f.value === "string" ? f.value : "";
460
+ const common = { id, name: f.name, "aria-invalid": f.error ? true : undefined, "aria-describedby": f.error ? `${id}-error` : undefined };
461
+ switch (f.kind) {
462
+ case "boolean": return _jsx("input", { ...common, type: "checkbox", checked: f.value === true, onChange: (e) => f.set(e.target.checked) });
463
+ case "textarea":
464
+ case "json": return _jsx("textarea", { ...common, rows: f.kind === "json" ? 6 : 4, className: cx(f.kind === "json" && "auto-mono"), value: text, onChange: (e) => f.set(e.target.value) });
465
+ case "select": return (_jsxs("select", { ...common, value: text, onChange: (e) => f.set(e.target.value), children: [_jsx("option", { value: "", children: f.required ? "Choose…" : "None" }), f.options.map((x) => _jsx("option", { value: x, children: x }, x))] }));
466
+ case "record": return (_jsxs("select", { ...common, value: text, onChange: (e) => f.set(e.target.value), children: [_jsx("option", { value: "", children: f.required ? "Choose…" : "None" }), f.choices.map((x) => _jsx("option", { value: x.value, children: x.label }, x.value))] }));
467
+ case "multiselect": {
468
+ const chosen = Array.isArray(f.value) ? f.value : [];
469
+ return (_jsx("span", { className: "auto-choices", role: "group", "aria-labelledby": `${id}-label`, children: f.options.map((x) => (_jsxs("label", { children: [_jsx("input", { type: "checkbox", checked: chosen.includes(x), onChange: (e) => f.set(e.target.checked ? [...chosen, x] : chosen.filter((c) => c !== x)) }), x] }, x))) }));
470
+ }
471
+ case "file": return (_jsxs("span", { className: "auto-filefield", children: [f.current && _jsx("span", { className: "auto-current", children: f.current.url ? _jsx("a", { href: f.current.url, target: "_blank", rel: "noreferrer", children: f.current.fileName }) : f.current.fileName }), _jsx("input", { ...common, type: "file", onChange: (e) => f.set(e.target.files?.[0] ?? null) })] }));
472
+ case "dateTime": return _jsx("input", { ...common, type: "datetime-local", value: text, onChange: (e) => f.set(e.target.value) });
473
+ case "number": return _jsx("input", { ...common, type: "text", inputMode: "decimal", value: text, onChange: (e) => f.set(e.target.value) });
474
+ case "color": return _jsxs("span", { className: "auto-colorfield", children: [_jsx("input", { type: "color", "aria-label": `${f.label} picker`, value: /^#[0-9a-f]{6}$/i.test(text) ? text : "#000000", onChange: (e) => f.set(e.target.value) }), _jsx("input", { ...common, type: "text", value: text, onChange: (e) => f.set(e.target.value) })] });
475
+ case "password": return _jsx("input", { ...common, type: "password", autoComplete: "new-password", value: text, onChange: (e) => f.set(e.target.value) });
476
+ case "email":
477
+ case "url": return _jsx("input", { ...common, type: f.kind, value: text, onChange: (e) => f.set(e.target.value) });
478
+ case "list": return _jsx("input", { ...common, type: "text", value: text, placeholder: "Separate with commas", onChange: (e) => f.set(e.target.value) });
479
+ default: return _jsx("input", { ...common, type: "text", value: text, onChange: (e) => f.set(e.target.value) });
480
+ }
481
+ }
482
+ /** A form for a model's record: its fields from the schema, the API's refusals shown on the fields they're about. */
483
+ export function AutoForm({ model, submitLabel, ...o }) {
484
+ const f = useAutoForm(model, o);
485
+ if (f.loading)
486
+ return _jsx("p", { className: "auto-loading", children: "Loading\u2026" });
487
+ return (_jsxs("form", { className: "auto-form", onSubmit: (e) => void f.submit(e), noValidate: true, children: [f.error && _jsx("p", { className: "auto-banner", role: "alert", children: f.error }), f.fields.map((field) => (_jsxs("div", { className: cx("auto-field", field.kind === "boolean" && "inline", field.error && "invalid"), children: [_jsxs("label", { id: `auto-${field.name}-label`, htmlFor: field.kind === "multiselect" ? undefined : `auto-${field.name}`, children: [field.label, field.required && _jsx("span", { className: "auto-required", "aria-hidden": "true", children: " *" })] }), _jsx(PlainInput, { field: field }), field.error && _jsx("span", { id: `auto-${field.name}-error`, className: "auto-error", children: field.error })] }, field.name))), _jsxs("div", { className: "auto-actions", children: [_jsx("button", { type: "submit", className: "btn sm primary", disabled: f.submitting, children: f.submitting ? "Saving…" : submitLabel ?? (f.isNew && !o.action ? "Create" : "Save") }), f.saved && !f.dirty && _jsx("span", { className: "auto-saved", role: "status", children: "Saved" })] })] }));
488
+ }
package/dist/test.js CHANGED
@@ -18,12 +18,13 @@
18
18
  * File fields keep their files in memory: `base64` reads back as a `data:` URL, `copyURL` as the URL itself (not
19
19
  * fetched, size 0), and `upload`/`createUpload` tokens as the upload (a `createUpload` needs no PUT here).
20
20
  */
21
- import { ApiError, MAX_BULK, ShopifyError, createAiClient, newRecordId } from "./index.js";
21
+ import { ApiError, MAX_BULK, ShopifyError, createAiClient, describeSchema, newRecordId } from "./index.js";
22
22
  import { runAction as runPhase } from "./runtime.js";
23
23
  /** Kept in `data`; the rest are a vector, the other side of a relationship, or worked out (computed). */
24
24
  const STORED = new Set(["string", "richText", "email", "url", "color", "number", "dateTime", "enum", "boolean", "roleList", "json", "belongsTo", "password", "encryptedString", "file"]);
25
25
  const SYSTEM = ["id", "createdAt", "updatedAt"];
26
26
  const MAX_PAGE = 250;
27
+ const MAX_SKIP = 10_000;
27
28
  const MAX_RECORD_BYTES = 256 * 1024;
28
29
  const invalid = (problems) => new ApiError(problems.map((p) => `${p.field}: ${p.message}`).join("; "), 400, "invalid_request", problems);
29
30
  /** A related filter's or sort's problems, named from the relationship: `product.vendor`. */
@@ -46,7 +47,11 @@ function modelOf(name, schema) {
46
47
  const dup = fields.find((f, i) => fields.findIndex((g) => g.key === f.key) !== i);
47
48
  if (dup)
48
49
  throw new Error(`${name}: two fields store their values under ${dup.key}; give ${dup.name} its own storageKey`);
49
- return { name, fields, byName: new Map(fields.map((f) => [f.name, f])) };
50
+ const byName = new Map(fields.map((f) => [f.name, f]));
51
+ // Unique indexes (records.ts indexesOf) hold their fields' values unique together; the other kinds only speed reads.
52
+ const unique = (Array.isArray(schema.indexes) ? schema.indexes : []).filter((ix) => ix.unique === true && Array.isArray(ix.fields) && ix.fields.length)
53
+ .map((ix) => ix.fields.map((n) => byName.get(n)).filter((f) => !!f && STORED.has(f.type)));
54
+ return { name, fields, byName, unique };
50
55
  }
51
56
  const RELATIONSHIPS = new Set(["belongsTo", "hasOne", "hasMany", "hasManyThrough"]);
52
57
  const LIST_OPS = ["some", "every", "none"];
@@ -989,7 +994,7 @@ class Records {
989
994
  const m = this.model(model);
990
995
  const plan = this.plan(m, o.select);
991
996
  const first = Math.min(Math.max(1, Math.floor(o.first ?? 50)), MAX_PAGE);
992
- const offset = offsetOf(o.after);
997
+ const offset = startOf(o);
993
998
  const ctx = { ...CTX, readable: o.readable };
994
999
  let rows = [...this.table(m).values()].filter((r) => this.matches(m, r, o.filter, ctx));
995
1000
  let distances = null;
@@ -1255,6 +1260,18 @@ class Records {
1255
1260
  problems.push({ field: f.name, message: "is already taken by another record" });
1256
1261
  }
1257
1262
  }
1263
+ // A unique index refuses the write as the database does (records.ts indexViolation): empty values don't count.
1264
+ for (const fields of m.unique) {
1265
+ if (!fields.length || fields.some((f) => data[f.key] === null || data[f.key] === undefined))
1266
+ continue;
1267
+ const dup = [...this.table(m).values()].some((r) => r.id !== current?.id && fields.every((f) => contains(r.data, { [f.key]: data[f.key] })));
1268
+ if (!dup)
1269
+ continue;
1270
+ const field = fields[fields.length - 1];
1271
+ const others = fields.slice(0, -1).map((f) => f.name);
1272
+ if (!problems.some((p) => p.field === field.name))
1273
+ problems.push({ field: field.name, message: others.length ? `is already taken by another record with the same ${others.join(", ")}` : "is already taken by another record" });
1274
+ }
1258
1275
  if (problems.length)
1259
1276
  throw invalid(problems);
1260
1277
  if (JSON.stringify(data).length > MAX_RECORD_BYTES)
@@ -1361,6 +1378,18 @@ function offsetOf(cursor) {
1361
1378
  throw invalid([{ field: "after", message: "isn't a cursor from this API" }]);
1362
1379
  return Number(m[1]);
1363
1380
  }
1381
+ /** As the API's: `after`'s cursor or `skip`, one or the other, and `skip` at most MAX_SKIP. */
1382
+ function startOf(o) {
1383
+ if (o.skip === undefined)
1384
+ return offsetOf(o.after);
1385
+ if (o.after)
1386
+ throw invalid([{ field: "skip", message: "can't be given with after; use one or the other" }]);
1387
+ if (typeof o.skip !== "number" || !Number.isInteger(o.skip) || o.skip < 0)
1388
+ throw invalid([{ field: "skip", message: "must be a whole number, 0 or more" }]);
1389
+ if (o.skip > MAX_SKIP)
1390
+ throw invalid([{ field: "skip", message: `must be at most ${MAX_SKIP}; page further with after, the endCursor of the page before` }]);
1391
+ return o.skip;
1392
+ }
1364
1393
  // ---- Shopify ----
1365
1394
  /** The store a test app installs on and runs as, unless a test names another. */
1366
1395
  export const TEST_SHOP = "test-shop.myshopify.com";
@@ -2190,6 +2219,7 @@ export function createTestApp(o = {}) {
2190
2219
  return { records, failed, counts };
2191
2220
  };
2192
2221
  const client = {
2222
+ describe: async () => { const m = store.model(name); return describeSchema(m.name, { type: "ib/model-schema/v1", fields: Object.fromEntries(m.fields.map((f) => [f.name, f.def])) }); },
2193
2223
  build: () => { throw new Error("build() makes a record for an action's run to save(); outside an action, use create()."); },
2194
2224
  findOne: async (id, o = {}) => findVisible(name, id, readOf(), wire(o.select), readable),
2195
2225
  findMany: async (q = {}) => store.findMany(name, narrow(wire(q))),
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@inferencebureau/apps-sdk",
3
- "version": "0.12.0",
4
- "description": "The SDK an Inference Bureau app's code imports: action helpers, metadata types, the records API client and a test harness for its actions.",
3
+ "version": "0.14.0",
4
+ "description": "The SDK an Inference Bureau app's code imports: action helpers, metadata types, the records API client, React hooks with AutoTable and AutoForm, and a test harness for its actions.",
5
5
  "license": "UNLICENSED",
6
6
  "keywords": [
7
7
  "inferencebureau",
@@ -33,6 +33,16 @@
33
33
  "import": "./dist/browser.js",
34
34
  "default": "./dist/browser.js"
35
35
  },
36
+ "./react": {
37
+ "types": "./dist/react.d.ts",
38
+ "import": "./dist/react.js",
39
+ "default": "./dist/react.js"
40
+ },
41
+ "./polaris": {
42
+ "types": "./dist/polaris.d.ts",
43
+ "import": "./dist/polaris.js",
44
+ "default": "./dist/polaris.js"
45
+ },
36
46
  "./test": {
37
47
  "types": "./dist/test.d.ts",
38
48
  "import": "./dist/test.js",
@@ -60,7 +70,20 @@
60
70
  "embed": "node scripts/embed.mjs"
61
71
  },
62
72
  "devDependencies": {
73
+ "@types/react": "^19.1.0",
74
+ "@types/react-dom": "^19.1.0",
75
+ "happy-dom": "^20.14.6",
76
+ "react": "^19.1.0",
77
+ "react-dom": "^19.1.0",
63
78
  "typescript": "^5.8.0",
64
79
  "vitest": "^3.2.0"
80
+ },
81
+ "peerDependencies": {
82
+ "react": ">=18"
83
+ },
84
+ "peerDependenciesMeta": {
85
+ "react": {
86
+ "optional": true
87
+ }
65
88
  }
66
89
  }