@inferencebureau/apps-sdk 0.16.3 → 0.16.5

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/index.d.ts CHANGED
@@ -260,8 +260,15 @@ export interface FindManyOptions<M extends ModelTypes = UntypedModel, S extends
260
260
  filter?: Filter<M["filter"]>;
261
261
  sort?: SortOf<M> | SortOf<M>[];
262
262
  first?: number;
263
- /** The `endCursor` of the page before: the fast way to page on. */
263
+ /**
264
+ * The `endCursor` of the page before: the records after its last one in the order, so a page never repeats or skips
265
+ * records written meanwhile. The way to read every page, past the 10,000 records `skip` reaches.
266
+ */
264
267
  after?: string | null;
268
+ /** Paging back: the page size, the last `last` records before `before` (or the last of all without it). */
269
+ last?: number;
270
+ /** The `startCursor` of the page after, with `last`. */
271
+ before?: string | null;
265
272
  /**
266
273
  * Records to pass over first, after the filter and sort, for a page by number (`skip: (page - 1) * first`) or a
267
274
  * library that asks for an offset; at most 10,000, and not with `after`. Cursors are faster for reading every page.
@@ -520,10 +527,16 @@ export type ModelRecord<N extends string> = ModelOf<N>["record"];
520
527
  export type ModelInput<N extends string> = ModelOf<N>["input"];
521
528
  /** What `enqueue` passes an action (ActionName) as its params. */
522
529
  export type ParamsOf<A extends string> = A extends `${infer M}.${infer N}` ? M extends keyof AppModels ? AppModels[M] extends ModelTypes ? N extends keyof AppModels[M]["actions"] ? AppModels[M]["actions"][N]["params"] : never : never : GlobalOf<A>["params"] : GlobalOf<A>["params"];
530
+ /**
531
+ * A page of records. `endCursor` (for `after`) and `startCursor` (for `before`) are its last and first records' places
532
+ * in the order. `hasPreviousPage` says whether the read started past the beginning.
533
+ */
523
534
  export interface RecordPage<T = AppRecord> {
524
535
  records: T[];
525
536
  hasNextPage: boolean;
526
537
  endCursor: string | null;
538
+ hasPreviousPage: boolean;
539
+ startCursor: string | null;
527
540
  }
528
541
  /**
529
542
  * A model as the API describes it (`describe()`): its fields in schema order between `id` and the timestamps, which
@@ -717,7 +730,7 @@ export interface ModelClient<M extends ModelTypes = UntypedModel> {
717
730
  select?: S;
718
731
  }): Promise<ReadOf<M, S> | null>;
719
732
  findMany<S extends SelectOf<M> | undefined = undefined>(o?: FindManyOptions<M, S>): Promise<RecordPage<ReadOf<M, S>>>;
720
- findFirst<S extends SelectOf<M> | undefined = undefined>(o?: Omit<FindManyOptions<M, S>, "first" | "after">): Promise<ReadOf<M, S> | null>;
733
+ findFirst<S extends SelectOf<M> | undefined = undefined>(o?: Omit<FindManyOptions<M, S>, "first" | "after" | "last" | "before">): Promise<ReadOf<M, S> | null>;
721
734
  /** Counts, sums, averages, least and most over the records, in groups or all together (AggregateOptions). */
722
735
  aggregate<A extends {
723
736
  [name: string]: AggregateSpec<M["sortable"]>;
@@ -1601,15 +1614,19 @@ export interface ActionOptions {
1601
1614
  */
1602
1615
  timeoutMS?: number;
1603
1616
  }
1617
+ /** `params` is unknown here: a file's literal without `ActionParams` widens its types to string. */
1604
1618
  export interface ActionModule {
1605
1619
  run?: ActionRun;
1606
1620
  onSuccess?: ActionOnSuccess;
1607
1621
  options?: ActionOptions;
1622
+ params?: unknown;
1608
1623
  }
1609
1624
  /**
1610
1625
  * `export const params` in an action file: what callers pass it, for the app's generated client types
1611
- * (`web/ib-client.d.ts`) to check calls by. Keep it a plain object literal: Inference Bureau reads it from the file.
1612
- * It isn't checked at run time. A create or update action takes the model's fields as well.
1626
+ * (`web/ib-client.d.ts`) to check calls by, and for every run to be checked against before the action runs: a call
1627
+ * whose params don't match is refused with 400 invalid_request, its `problems` naming each param (`note`,
1628
+ * `address.zip`, `lines[2].qty`). Keep it a plain object literal: Inference Bureau reads it from the file. Keys it
1629
+ * doesn't name pass; a create or update action takes the model's fields as well.
1613
1630
  *
1614
1631
  * export const params: ActionParams = { note: { type: "string" }, notify: { type: "boolean", required: true } };
1615
1632
  */
@@ -1633,7 +1650,7 @@ export interface ParamDef {
1633
1650
  * export const params = { note: { type: "string" }, notify: { type: "boolean", required: true } } as const satisfies ActionParams;
1634
1651
  * export const run: ActionRun<DeclaredParams<typeof params>> = async ({ params }) => { params.note; // string | undefined
1635
1652
  *
1636
- * Nothing checks them at run time: a caller can still send anything.
1653
+ * A call whose params don't match is refused before `run` (see ActionParams).
1637
1654
  */
1638
1655
  export type DeclaredParams<D> = Flat<{
1639
1656
  -readonly [K in keyof D as D[K] extends {
package/dist/react.d.ts CHANGED
@@ -135,7 +135,7 @@ export declare function useFindOne<N extends ModelName, S extends SelectOf<Model
135
135
  select?: S;
136
136
  }): Query<ReadOf<ModelOf<N>, S> | null>;
137
137
  /** The first record matching, or null. */
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>;
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" | "last" | "before">, o?: ReadHookOptions): Query<ReadOf<ModelOf<N>, S> | null>;
139
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
140
  export declare function useAggregate<N extends ModelName, A extends {
141
141
  [name: string]: AggregateSpec<ModelOf<N>["sortable"]>;
package/dist/test.js CHANGED
@@ -28,6 +28,38 @@ const MAX_PAGE = 250;
28
28
  const MAX_SKIP = 10_000;
29
29
  const MAX_RECORD_BYTES = 256 * 1024;
30
30
  const invalid = (problems) => new ApiError(problems.map((p) => `${p.field}: ${p.message}`).join("; "), 400, "invalid_request", problems);
31
+ const PARAM_WORD = { string: "text", dateTime: "text", enum: "text", number: "a number", boolean: "true or false", object: "an object", array: "a list" };
32
+ /** What's wrong with a run's params against the action's `export const params`, as the platform checks them (#206). */
33
+ function paramProblems(def, v, at) {
34
+ const field = at || "params";
35
+ const ok = def.type === "string" || def.type === "dateTime" || def.type === "enum" ? typeof v === "string"
36
+ : def.type === "number" ? typeof v === "number" && Number.isFinite(v)
37
+ : def.type === "boolean" ? typeof v === "boolean"
38
+ : def.type === "object" ? isObj(v)
39
+ : def.type === "array" ? Array.isArray(v)
40
+ : true;
41
+ if (!ok)
42
+ return [{ field, message: `must be ${PARAM_WORD[def.type]}` }];
43
+ if (def.type === "enum" && Array.isArray(def.options) && !def.options.includes(v))
44
+ return [{ field, message: `must be one of ${def.options.join(", ")}` }];
45
+ if (def.type === "dateTime" && Number.isNaN(Date.parse(v)))
46
+ return [{ field, message: "must be a date and time (ISO 8601)" }];
47
+ const out = [];
48
+ if (def.type === "object" && def.properties && isObj(v)) {
49
+ for (const [k, d] of Object.entries(def.properties)) {
50
+ const path = at ? `${at}.${k}` : k;
51
+ if (v[k] === undefined) {
52
+ if (d.required === true)
53
+ out.push({ field: path, message: "is required" });
54
+ }
55
+ else
56
+ out.push(...paramProblems(d, v[k], path));
57
+ }
58
+ }
59
+ if (def.type === "array" && def.items && Array.isArray(v))
60
+ v.forEach((x, i) => out.push(...paramProblems(def.items, x, `${field}[${i}]`)));
61
+ return out;
62
+ }
31
63
  /** A related filter's or sort's problems, named from the relationship: `product.vendor`. */
32
64
  function under(at, f) {
33
65
  try {
@@ -1035,14 +1067,23 @@ class Records {
1035
1067
  return ok;
1036
1068
  }
1037
1069
  sorted(m, rows, sort, readable) {
1070
+ const { tuple, compare } = this.order(m, sort, readable);
1071
+ return [...rows].sort((a, b) => compare(tuple(a), tuple(b)));
1072
+ }
1073
+ /**
1074
+ * A list's order as the API's (records.ts orderTerms): the sort's values, else the best text matches (`rank`) and the
1075
+ * newest, then the id. `tuple` is a row's values in turn, which a keyset cursor carries; `compare` orders two.
1076
+ */
1077
+ order(m, sort, readable, rank) {
1038
1078
  const ctx = { ...CTX, readable };
1039
1079
  const keys = (Array.isArray(sort) ? sort : sort ? [sort] : []).flatMap((s) => this.sortKeys(m, s, ctx));
1040
1080
  if (!keys.length)
1041
- keys.push({ at: (r) => r.createdAt, desc: true });
1081
+ keys.push(...(rank ? [{ at: rank, desc: true }] : []), { at: (r) => r.createdAt, desc: true });
1042
1082
  keys.push({ at: (r) => r.id, desc: true });
1043
- return [...rows].sort((a, b) => {
1044
- for (const k of keys) {
1045
- const x = k.at(a), y = k.at(b);
1083
+ const tuple = (r) => keys.map((k) => k.at(r) ?? null);
1084
+ const compare = (a, b) => {
1085
+ for (let i = 0; i < keys.length; i++) {
1086
+ const x = a[i], y = b[i];
1046
1087
  if (x === y)
1047
1088
  continue;
1048
1089
  // Nulls last, either way.
@@ -1051,10 +1092,11 @@ class Records {
1051
1092
  if (y === null)
1052
1093
  return -1;
1053
1094
  const c = (typeof x === "boolean" ? Number(x) : x) < (typeof y === "boolean" ? Number(y) : y) ? -1 : 1;
1054
- return k.desc ? -c : c;
1095
+ return keys[i].desc ? -c : c;
1055
1096
  }
1056
1097
  return 0;
1057
- });
1098
+ };
1099
+ return { tuple, compare };
1058
1100
  }
1059
1101
  /** A sort's values to order by, in turn (records.ts: sortTerms); a belongsTo's are read from its record, null without one the caller can read. */
1060
1102
  sortKeys(m, sort, ctx) {
@@ -1097,17 +1139,18 @@ class Records {
1097
1139
  async findMany(model, o = {}) {
1098
1140
  const m = this.model(model);
1099
1141
  const plan = this.plan(m, o.select);
1100
- const first = Math.min(Math.max(1, Math.floor(o.first ?? 50)), MAX_PAGE);
1101
- const offset = startOf(o);
1142
+ const nearest = !!o.search && typeof o.search === "object";
1143
+ const print = orderPrint(o.sort, typeof o.search === "string" ? o.search : null);
1144
+ const p = pagingOf(o, print, !nearest);
1102
1145
  const ctx = { ...CTX, readable: o.readable };
1103
1146
  let rows = [...this.table(m).values()].filter((r) => this.matches(m, r, o.filter, ctx));
1104
1147
  let distances = null;
1148
+ let order = null;
1105
1149
  const text = typeof o.search === "string" ? this.textSearch(m, rows, o.search) : null;
1106
1150
  if (text) {
1107
- rows = this.sorted(m, text.rows, o.sort, o.readable);
1108
- // Unsorted, the best matches come first (a stable sort keeps the default order within a score).
1109
- if (!o.sort)
1110
- rows.sort((a, b) => text.score.get(b.id) - text.score.get(a.id));
1151
+ // Unsorted, the best matches come first.
1152
+ order = this.order(m, o.sort, o.readable, (r) => text.score.get(r.id));
1153
+ rows = [...text.rows].sort((a, b) => order.compare(order.tuple(a), order.tuple(b)));
1111
1154
  }
1112
1155
  else if (o.search && typeof o.search === "object") {
1113
1156
  const f = m.byName.get(o.search.field);
@@ -1131,15 +1174,31 @@ class Records {
1131
1174
  }
1132
1175
  rows = rows.filter((r) => distances.has(r.id)).sort((a, b) => distances.get(a.id) - distances.get(b.id) || (a.id < b.id ? -1 : 1));
1133
1176
  }
1134
- else
1135
- rows = this.sorted(m, rows, o.sort, o.readable);
1136
- const page = rows.slice(offset, offset + first);
1177
+ else {
1178
+ order = this.order(m, o.sort, o.readable);
1179
+ rows = [...rows].sort((a, b) => order.compare(order.tuple(a), order.tuple(b)));
1180
+ }
1181
+ // Where the page sits: past a keyset cursor's values (before them, walking back), else from the offset.
1182
+ const at = (v, from) => { const i = rows.findIndex((r) => order.compare(order.tuple(r), v) >= from); return i < 0 ? rows.length : i; };
1183
+ let start = p.offset, end = p.offset + p.size;
1184
+ if (p.backward) {
1185
+ end = p.values ? at(p.values, 0) : rows.length;
1186
+ start = Math.max(0, end - p.size);
1187
+ }
1188
+ else if (p.values) {
1189
+ start = at(p.values, 1);
1190
+ end = start + p.size;
1191
+ }
1192
+ const page = rows.slice(start, end);
1137
1193
  const budget = { left: 5000 };
1138
1194
  const read = (r) => (plan ? this.selected(m, r, plan, o.readable, budget, false) : this.present(m, r, false));
1195
+ const cursor = (r, i) => (!r ? null : order ? keysetCursor(order.tuple(r), print) : cursorOf(i));
1139
1196
  return {
1140
1197
  records: page.map((r) => (distances ? { ...read(r), _distance: distances.get(r.id) } : read(r))),
1141
- hasNextPage: rows.length > offset + first,
1142
- endCursor: page.length ? cursorOf(offset + page.length) : null,
1198
+ hasNextPage: p.backward ? !!o.before : p.endsAt || rows.length > end,
1199
+ endCursor: cursor(page.at(-1), start + page.length),
1200
+ hasPreviousPage: start > 0,
1201
+ startCursor: cursor(page[0], start),
1143
1202
  };
1144
1203
  }
1145
1204
  count(model, filter, readable) {
@@ -1668,31 +1727,80 @@ function cosineDistance(a, b) {
1668
1727
  return na && nb ? 1 - dot / Math.sqrt(na * nb) : 1;
1669
1728
  }
1670
1729
  const base64url = (s) => btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1730
+ const unbase64url = (s) => { try {
1731
+ return decodeURIComponent(escape(atob(s.replace(/-/g, "+").replace(/_/g, "/"))));
1732
+ }
1733
+ catch {
1734
+ return "";
1735
+ } };
1671
1736
  const cursorOf = (offset) => base64url(`o:${offset}`);
1672
- function offsetOf(cursor) {
1673
- if (!cursor)
1674
- return 0;
1675
- let text = "";
1676
- try {
1677
- text = atob(cursor.replace(/-/g, "+").replace(/_/g, "/"));
1678
- }
1679
- catch { /* reported below */ }
1737
+ /** As the API's keyset cursor (records.ts keysetCursor): a record's place in the order, with the order's print. */
1738
+ const keysetCursor = (values, print) => base64url(unescape(encodeURIComponent(`k:${JSON.stringify({ v: values, s: print })}`)));
1739
+ /** The sort and search a keyset cursor belongs to (FNV-1a over them; the API hashes them too). */
1740
+ function orderPrint(sort, search) {
1741
+ let h = 0x811c9dc5;
1742
+ for (const ch of JSON.stringify([sort ?? null, search]))
1743
+ h = Math.imul(h ^ ch.charCodeAt(0), 0x01000193) >>> 0;
1744
+ return h.toString(36);
1745
+ }
1746
+ function readCursor(cursor, field) {
1747
+ const text = unbase64url(cursor);
1680
1748
  const m = /^o:(\d+)$/.exec(text);
1681
- if (!m)
1682
- throw invalid([{ field: "after", message: "isn't a cursor from this API" }]);
1683
- return Number(m[1]);
1749
+ if (m)
1750
+ return { offset: Number(m[1]) };
1751
+ if (text.startsWith("k:")) {
1752
+ try {
1753
+ const j = JSON.parse(text.slice(2));
1754
+ if (Array.isArray(j.v) && j.v.length && typeof j.s === "string")
1755
+ return { values: j.v, print: j.s };
1756
+ }
1757
+ catch { /* reported below */ }
1758
+ }
1759
+ throw invalid([{ field, message: "isn't a cursor from this API" }]);
1684
1760
  }
1685
- /** As the API's: `after`'s cursor or `skip`, one or the other, and `skip` at most MAX_SKIP. */
1686
- function startOf(o) {
1687
- if (o.skip === undefined)
1688
- return offsetOf(o.after);
1689
- if (o.after)
1690
- throw invalid([{ field: "skip", message: "can't be given with after; use one or the other" }]);
1691
- if (typeof o.skip !== "number" || !Number.isInteger(o.skip) || o.skip < 0)
1692
- throw invalid([{ field: "skip", message: "must be a whole number, 0 or more" }]);
1693
- if (o.skip > MAX_SKIP)
1694
- throw invalid([{ field: "skip", message: `must be at most ${MAX_SKIP}; page further with after, the endCursor of the page before` }]);
1695
- return o.skip;
1761
+ /**
1762
+ * As the API's (records.ts pagingOf): `after` and `skip` page forward, `before` and `last` back; an offset `before` is
1763
+ * the forward page that ends there. `keyset`: whether the read takes keyset cursors (a nearest search's doesn't).
1764
+ */
1765
+ function pagingOf(o, print, keyset) {
1766
+ const bad = (field, message) => invalid([{ field, message }]);
1767
+ const sizeOf = (n) => Math.min(Math.max(1, Math.floor(n ?? 50)), MAX_PAGE);
1768
+ const keysOf = (c, field) => {
1769
+ if ("offset" in c)
1770
+ return null;
1771
+ if (!keyset)
1772
+ throw bad(field, "is a cursor from a sorted read; a nearest search pages by its own cursors");
1773
+ if (c.print !== print)
1774
+ throw bad(field, "is a cursor from a read with another sort or search: start again without it");
1775
+ return c.values;
1776
+ };
1777
+ if (o.after && o.before)
1778
+ throw bad("before", "can't be given with after; use one or the other");
1779
+ if (o.before || o.last !== undefined) {
1780
+ if (o.first !== undefined)
1781
+ throw bad("first", "goes with after; paging back with before, use last");
1782
+ if (o.skip !== undefined)
1783
+ throw bad("skip", "can't be given with before or last");
1784
+ const size = sizeOf(o.last);
1785
+ const c = o.before ? readCursor(o.before, "before") : null;
1786
+ if (c && "offset" in c)
1787
+ return { size: Math.min(size, c.offset), offset: Math.max(0, c.offset - size), values: null, backward: false, endsAt: true };
1788
+ if (!keyset)
1789
+ throw bad("last", "a nearest search pages forward: use first and after");
1790
+ return { size, offset: 0, values: c ? keysOf(c, "before") : null, backward: true, endsAt: false };
1791
+ }
1792
+ const size = sizeOf(o.first);
1793
+ if (o.skip !== undefined) {
1794
+ if (o.after)
1795
+ throw bad("skip", "can't be given with after; use one or the other");
1796
+ if (typeof o.skip !== "number" || !Number.isInteger(o.skip) || o.skip < 0)
1797
+ throw bad("skip", "must be a whole number, 0 or more");
1798
+ if (o.skip > MAX_SKIP)
1799
+ throw bad("skip", `must be at most ${MAX_SKIP}; page further with after, the endCursor of the page before`);
1800
+ return { size, offset: o.skip, values: null, backward: false, endsAt: false };
1801
+ }
1802
+ const c = o.after ? readCursor(o.after, "after") : null;
1803
+ return c && "offset" in c ? { size, offset: c.offset, values: null, backward: false, endsAt: false } : { size, offset: 0, values: c ? keysOf(c, "after") : null, backward: false, endsAt: false };
1696
1804
  }
1697
1805
  // ---- Shopify ----
1698
1806
  /** The store a test app installs on and runs as, unless a test names another. */
@@ -2372,6 +2480,10 @@ export function createTestApp(o = {}) {
2372
2480
  }
2373
2481
  }
2374
2482
  const params = wire(input.params ?? {});
2483
+ // Checked against the file's `export const params` before anything runs, as the platform does; an obligation's payload is Shopify's.
2484
+ const wrong = isObj(mod.params) && !how.obligation ? paramProblems({ type: "object", properties: mod.params }, params, "") : [];
2485
+ if (wrong.length)
2486
+ throw invalid(wrong);
2375
2487
  const shop = input.shop ?? null;
2376
2488
  const given = mod.options?.timeoutMS;
2377
2489
  const total = Math.min(MAX_TIMEOUT_MS, Math.max(1000, typeof given === "number" ? given : how.background ? JOB_TIMEOUT_MS : DEFAULT_CALL_TIMEOUT_MS));
@@ -2901,7 +3013,7 @@ export function createTestApp(o = {}) {
2901
3013
  if (privacy) {
2902
3014
  handled = true;
2903
3015
  if (registry[`$global/${privacy}`])
2904
- runs.push(await run(null, privacy, { params: payload, shop }));
3016
+ runs.push(await run(null, privacy, { params: payload, shop }, { obligation: true }));
2905
3017
  }
2906
3018
  for (const s of o.settings?.webhooks ?? []) {
2907
3019
  if (s.topic !== topic)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inferencebureau/apps-sdk",
3
- "version": "0.16.3",
3
+ "version": "0.16.5",
4
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": [