@inferencebureau/apps-sdk 0.16.4 → 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"]>;
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
@@ -1067,14 +1067,23 @@ class Records {
1067
1067
  return ok;
1068
1068
  }
1069
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) {
1070
1078
  const ctx = { ...CTX, readable };
1071
1079
  const keys = (Array.isArray(sort) ? sort : sort ? [sort] : []).flatMap((s) => this.sortKeys(m, s, ctx));
1072
1080
  if (!keys.length)
1073
- keys.push({ at: (r) => r.createdAt, desc: true });
1081
+ keys.push(...(rank ? [{ at: rank, desc: true }] : []), { at: (r) => r.createdAt, desc: true });
1074
1082
  keys.push({ at: (r) => r.id, desc: true });
1075
- return [...rows].sort((a, b) => {
1076
- for (const k of keys) {
1077
- 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];
1078
1087
  if (x === y)
1079
1088
  continue;
1080
1089
  // Nulls last, either way.
@@ -1083,10 +1092,11 @@ class Records {
1083
1092
  if (y === null)
1084
1093
  return -1;
1085
1094
  const c = (typeof x === "boolean" ? Number(x) : x) < (typeof y === "boolean" ? Number(y) : y) ? -1 : 1;
1086
- return k.desc ? -c : c;
1095
+ return keys[i].desc ? -c : c;
1087
1096
  }
1088
1097
  return 0;
1089
- });
1098
+ };
1099
+ return { tuple, compare };
1090
1100
  }
1091
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. */
1092
1102
  sortKeys(m, sort, ctx) {
@@ -1129,17 +1139,18 @@ class Records {
1129
1139
  async findMany(model, o = {}) {
1130
1140
  const m = this.model(model);
1131
1141
  const plan = this.plan(m, o.select);
1132
- const first = Math.min(Math.max(1, Math.floor(o.first ?? 50)), MAX_PAGE);
1133
- 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);
1134
1145
  const ctx = { ...CTX, readable: o.readable };
1135
1146
  let rows = [...this.table(m).values()].filter((r) => this.matches(m, r, o.filter, ctx));
1136
1147
  let distances = null;
1148
+ let order = null;
1137
1149
  const text = typeof o.search === "string" ? this.textSearch(m, rows, o.search) : null;
1138
1150
  if (text) {
1139
- rows = this.sorted(m, text.rows, o.sort, o.readable);
1140
- // Unsorted, the best matches come first (a stable sort keeps the default order within a score).
1141
- if (!o.sort)
1142
- 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)));
1143
1154
  }
1144
1155
  else if (o.search && typeof o.search === "object") {
1145
1156
  const f = m.byName.get(o.search.field);
@@ -1163,15 +1174,31 @@ class Records {
1163
1174
  }
1164
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));
1165
1176
  }
1166
- else
1167
- rows = this.sorted(m, rows, o.sort, o.readable);
1168
- 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);
1169
1193
  const budget = { left: 5000 };
1170
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));
1171
1196
  return {
1172
1197
  records: page.map((r) => (distances ? { ...read(r), _distance: distances.get(r.id) } : read(r))),
1173
- hasNextPage: rows.length > offset + first,
1174
- 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),
1175
1202
  };
1176
1203
  }
1177
1204
  count(model, filter, readable) {
@@ -1700,31 +1727,80 @@ function cosineDistance(a, b) {
1700
1727
  return na && nb ? 1 - dot / Math.sqrt(na * nb) : 1;
1701
1728
  }
1702
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
+ } };
1703
1736
  const cursorOf = (offset) => base64url(`o:${offset}`);
1704
- function offsetOf(cursor) {
1705
- if (!cursor)
1706
- return 0;
1707
- let text = "";
1708
- try {
1709
- text = atob(cursor.replace(/-/g, "+").replace(/_/g, "/"));
1710
- }
1711
- 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);
1712
1748
  const m = /^o:(\d+)$/.exec(text);
1713
- if (!m)
1714
- throw invalid([{ field: "after", message: "isn't a cursor from this API" }]);
1715
- 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" }]);
1716
1760
  }
1717
- /** As the API's: `after`'s cursor or `skip`, one or the other, and `skip` at most MAX_SKIP. */
1718
- function startOf(o) {
1719
- if (o.skip === undefined)
1720
- return offsetOf(o.after);
1721
- if (o.after)
1722
- throw invalid([{ field: "skip", message: "can't be given with after; use one or the other" }]);
1723
- if (typeof o.skip !== "number" || !Number.isInteger(o.skip) || o.skip < 0)
1724
- throw invalid([{ field: "skip", message: "must be a whole number, 0 or more" }]);
1725
- if (o.skip > MAX_SKIP)
1726
- throw invalid([{ field: "skip", message: `must be at most ${MAX_SKIP}; page further with after, the endCursor of the page before` }]);
1727
- 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 };
1728
1804
  }
1729
1805
  // ---- Shopify ----
1730
1806
  /** The store a test app installs on and runs as, unless a test names another. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inferencebureau/apps-sdk",
3
- "version": "0.16.4",
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": [