@inferencebureau/apps-sdk 0.15.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/README.md +1 -1
- package/dist/index.d.ts +68 -5
- package/dist/index.js +109 -15
- package/dist/react.d.ts +88 -39
- package/dist/react.js +86 -39
- package/dist/runtime.d.ts +5 -1
- package/dist/runtime.js +9 -2
- package/dist/test.js +4 -2
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@ npm install @inferencebureau/apps-sdk
|
|
|
9
9
|
```
|
|
10
10
|
|
|
11
11
|
Apps built on Inference Bureau get the SDK in every build already; install it to have the types in your editor, or to
|
|
12
|
-
use the client from your own code. It's ESM, uses only `fetch` and Web Crypto, and runs on Node
|
|
12
|
+
use the client from your own code. It's ESM, uses only `fetch` and Web Crypto, and runs on Node 22+, edge runtimes and
|
|
13
13
|
Next.js without `transpilePackages`.
|
|
14
14
|
|
|
15
15
|
```ts
|
package/dist/index.d.ts
CHANGED
|
@@ -30,6 +30,8 @@ export interface FieldDef {
|
|
|
30
30
|
type: FieldType;
|
|
31
31
|
/** Where the field's values are kept. The schema editor sets it; keep it when renaming the field so its values follow. */
|
|
32
32
|
storageKey?: string;
|
|
33
|
+
/** A line on what the field holds, for the app's API reference, its generated types and its MCP server. */
|
|
34
|
+
description?: string;
|
|
33
35
|
default?: unknown;
|
|
34
36
|
validations?: FieldValidations;
|
|
35
37
|
options?: string[];
|
|
@@ -115,6 +117,8 @@ export interface IndexDef {
|
|
|
115
117
|
export interface ModelSchema {
|
|
116
118
|
type: "ib/model-schema/v1";
|
|
117
119
|
storageKey?: string;
|
|
120
|
+
/** A line on what a record of the model is, for the app's API reference, its generated types and its MCP server. */
|
|
121
|
+
description?: string;
|
|
118
122
|
fields: Record<string, FieldDef>;
|
|
119
123
|
indexes?: IndexDef[];
|
|
120
124
|
}
|
|
@@ -138,8 +142,18 @@ export interface AppSettings {
|
|
|
138
142
|
* no credentials for one. Inference Bureau's `ai` client is always on and needs no entry.
|
|
139
143
|
*/
|
|
140
144
|
integrations?: IntegrationSetting[];
|
|
145
|
+
/** Whether the team is emailed when production fails. On unless `{ failures: false }`. */
|
|
146
|
+
alerts?: AlertSetting;
|
|
141
147
|
[key: string]: unknown;
|
|
142
148
|
}
|
|
149
|
+
/**
|
|
150
|
+
* Failure emails: when an action, job, deploy, release or request fails in production, the team's owners, admins and
|
|
151
|
+
* the members who can see the app get an email naming what failed, at most one every 12 hours per app (failures in
|
|
152
|
+
* the meantime are sent together when the 12 hours are up). Development's failures are never emailed.
|
|
153
|
+
*/
|
|
154
|
+
export interface AlertSetting {
|
|
155
|
+
failures?: boolean;
|
|
156
|
+
}
|
|
143
157
|
/** `resend`: the app's email through the team's own Resend account, as RESEND_API_KEY and EMAIL_FROM. */
|
|
144
158
|
export type IntegrationSetting = "resend";
|
|
145
159
|
/**
|
|
@@ -149,7 +163,7 @@ export type IntegrationSetting = "resend";
|
|
|
149
163
|
* Shopify's extensions (https://extensions.shopifycdn.com, where Sidekick tools run) are always allowed.
|
|
150
164
|
*/
|
|
151
165
|
export interface CorsSetting {
|
|
152
|
-
/** `https://shop.example.com`, `https://*.example.com` for its subdomains, `http://localhost:3000`, or `*`. */
|
|
166
|
+
/** `https://shop.example.com`, `https://*.example.com` for its subdomains, `http://localhost:3000`, `http://localhost:*` for any local port, or `*`. */
|
|
153
167
|
origins?: string[];
|
|
154
168
|
/** The paths it covers, e.g. `/api/*` for everything under /api. Every path unless named. */
|
|
155
169
|
paths?: string[];
|
|
@@ -478,21 +492,27 @@ export type ModelClients = Typed<AppModels> extends true ? {
|
|
|
478
492
|
} : {
|
|
479
493
|
[model: string]: ModelClient;
|
|
480
494
|
};
|
|
495
|
+
/** A model's name: one the generated file lists, or any before there is one. */
|
|
496
|
+
export type ModelName = Typed<AppModels> extends true ? keyof AppModels & string : string;
|
|
481
497
|
type Globals = Typed<AppGlobalActions> extends true ? AppGlobalActions : {
|
|
482
498
|
[action: string]: ActionTypes;
|
|
483
499
|
};
|
|
484
|
-
|
|
485
|
-
type
|
|
500
|
+
/** A global action's name, the same way. */
|
|
501
|
+
export type GlobalName = keyof Globals & string;
|
|
502
|
+
/** A global action's params and result, by name. */
|
|
503
|
+
export type GlobalOf<A extends string> = A extends keyof Globals ? (Globals[A] extends ActionTypes ? Globals[A] : ActionTypes) : ActionTypes;
|
|
486
504
|
/** What `enqueue` takes: a global action, or `<model>.<action>`. */
|
|
487
505
|
export type ActionName = Typed<AppModels> extends true ? GlobalName | {
|
|
488
506
|
[K in keyof AppModels & string]: AppModels[K] extends ModelTypes ? `${K}.${keyof AppModels[K]["actions"] & string}` : never;
|
|
489
507
|
}[keyof AppModels & string] : string;
|
|
490
|
-
|
|
508
|
+
/** A model's types by name (ModelTypes): the generated file's, or UntypedModel. */
|
|
509
|
+
export type ModelOf<N extends string> = N extends keyof AppModels ? (AppModels[N] extends ModelTypes ? AppModels[N] : UntypedModel) : UntypedModel;
|
|
491
510
|
/** A model's record as the API reads it, by name: `ModelRecord<"review">`. Any record before the app has generated types. */
|
|
492
511
|
export type ModelRecord<N extends string> = ModelOf<N>["record"];
|
|
493
512
|
/** What creating or updating a model's record takes, by name. */
|
|
494
513
|
export type ModelInput<N extends string> = ModelOf<N>["input"];
|
|
495
|
-
|
|
514
|
+
/** What `enqueue` passes an action (ActionName) as its params. */
|
|
515
|
+
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"];
|
|
496
516
|
export interface RecordPage<T = AppRecord> {
|
|
497
517
|
records: T[];
|
|
498
518
|
hasNextPage: boolean;
|
|
@@ -1014,6 +1034,13 @@ export type RecordsRequest = {
|
|
|
1014
1034
|
op: "global";
|
|
1015
1035
|
action: string;
|
|
1016
1036
|
params?: Record<string, unknown>;
|
|
1037
|
+
} | {
|
|
1038
|
+
op: "enqueue";
|
|
1039
|
+
action: string;
|
|
1040
|
+
params?: Record<string, unknown>;
|
|
1041
|
+
options?: Omit<EnqueueOptions, "shop" | "runAt"> & {
|
|
1042
|
+
runAt?: string;
|
|
1043
|
+
};
|
|
1017
1044
|
} | {
|
|
1018
1045
|
op: "changes";
|
|
1019
1046
|
models: string[];
|
|
@@ -1024,6 +1051,11 @@ export interface ServeRecordsOptions {
|
|
|
1024
1051
|
models?: string[];
|
|
1025
1052
|
/** The global actions it runs; none when unset. */
|
|
1026
1053
|
globalActions?: string[];
|
|
1054
|
+
/**
|
|
1055
|
+
* The actions it queues as background jobs (`useEnqueue`): global actions' names and `<model>.<action>`; none when
|
|
1056
|
+
* unset. A job runs for the request's store and is held to its role, the way `api.enqueue` is.
|
|
1057
|
+
*/
|
|
1058
|
+
enqueueActions?: string[];
|
|
1027
1059
|
/**
|
|
1028
1060
|
* Seconds a live query's watch waits for a change before the route answers that none came (25 unless given, 0 to
|
|
1029
1061
|
* 25). The route's function must be allowed to run that long; a shorter wait just means more requests.
|
|
@@ -1494,6 +1526,11 @@ export type GlobalActionRun = (ctx: Omit<ActionContext, "record"> & {
|
|
|
1494
1526
|
export interface ActionOptions {
|
|
1495
1527
|
/** create: works on a new record; update and custom: on the record named by id; delete: removes it. */
|
|
1496
1528
|
actionType?: "create" | "update" | "delete" | "custom";
|
|
1529
|
+
/**
|
|
1530
|
+
* A line on what the action does, for the app's API reference, its generated types and its MCP server. Inference
|
|
1531
|
+
* Bureau reads it from the file, like `params`: keep `options` a plain object literal.
|
|
1532
|
+
*/
|
|
1533
|
+
description?: string;
|
|
1497
1534
|
/** Whether what `run` returns goes back to the caller (it's dropped otherwise). */
|
|
1498
1535
|
returnType?: boolean;
|
|
1499
1536
|
/**
|
|
@@ -1519,6 +1556,8 @@ export interface ParamDef {
|
|
|
1519
1556
|
type: "string" | "number" | "boolean" | "dateTime" | "enum" | "json" | "object" | "array";
|
|
1520
1557
|
/** Callers must pass it. */
|
|
1521
1558
|
required?: boolean;
|
|
1559
|
+
/** A line on what the param is, for the app's API reference, its generated types and its MCP server. */
|
|
1560
|
+
description?: string;
|
|
1522
1561
|
/** enum: the values it takes. */
|
|
1523
1562
|
options?: string[];
|
|
1524
1563
|
/** object: its keys. */
|
|
@@ -1526,6 +1565,30 @@ export interface ParamDef {
|
|
|
1526
1565
|
/** array: each item. */
|
|
1527
1566
|
items?: ParamDef;
|
|
1528
1567
|
}
|
|
1568
|
+
export interface CaptureOptions {
|
|
1569
|
+
/** Searchable in Sentry. Values are cut to 200 characters. */
|
|
1570
|
+
tags?: Record<string, string | number | boolean | null | undefined>;
|
|
1571
|
+
/** Shown on the event, not searchable. */
|
|
1572
|
+
extra?: Record<string, unknown>;
|
|
1573
|
+
level?: "fatal" | "error" | "warning" | "info";
|
|
1574
|
+
/** The runtime's own reports: thrown out of an action, not caught by the app. */
|
|
1575
|
+
handled?: boolean;
|
|
1576
|
+
/** Defaults to SENTRY_DSN. */
|
|
1577
|
+
dsn?: string;
|
|
1578
|
+
/** Defaults to IB_ENVIRONMENT: development or production. */
|
|
1579
|
+
environment?: string;
|
|
1580
|
+
fetch?: typeof fetch;
|
|
1581
|
+
}
|
|
1582
|
+
/** A DSN's parts, or null when it isn't one: `https://<key>@<host>[/<path>]/<project>`. */
|
|
1583
|
+
export declare function parseDsn(dsn: string): {
|
|
1584
|
+
key: string;
|
|
1585
|
+
envelope: string;
|
|
1586
|
+
} | null;
|
|
1587
|
+
/**
|
|
1588
|
+
* Reports an error to the app's Sentry project. Answers the event's id, or null when there's no DSN or Sentry didn't
|
|
1589
|
+
* take it. Never throws, and gives up after three seconds.
|
|
1590
|
+
*/
|
|
1591
|
+
export declare function captureException(error: unknown, o?: CaptureOptions): Promise<string | null>;
|
|
1529
1592
|
export interface ShopifyPrivacyCustomer {
|
|
1530
1593
|
id: number;
|
|
1531
1594
|
email?: string | null;
|
package/dist/index.js
CHANGED
|
@@ -116,6 +116,8 @@ export function newRecordId() {
|
|
|
116
116
|
return `rec_${Date.now().toString(36)}${Array.from(bytes, (b) => ID_CHARS[b % 36]).join("")}`;
|
|
117
117
|
}
|
|
118
118
|
// ---- the API ----
|
|
119
|
+
/** Tries again of a call the API turned away before doing anything (all the environment's calls running, or busy). */
|
|
120
|
+
const CALL_RETRIES = 2;
|
|
119
121
|
export class ApiError extends Error {
|
|
120
122
|
status;
|
|
121
123
|
code;
|
|
@@ -145,23 +147,36 @@ export function createClient(o = {}) {
|
|
|
145
147
|
...(o.shop ? { "x-ib-shop": o.shop } : {}), ...(o.role ? { "x-ib-role": o.role } : {}),
|
|
146
148
|
...(o.role && o.session ? { "x-ib-session": JSON.stringify({ userId: o.session.userId ?? null, customerId: o.session.customerId ?? null, ...(o.session.customerRecordId ? { customerRecordId: o.session.customerRecordId } : {}) }) } : {}),
|
|
147
149
|
};
|
|
148
|
-
/**
|
|
150
|
+
/**
|
|
151
|
+
* A call with a JSON body (or none); `raw` sends bytes as they are, with their type when known. A call turned away
|
|
152
|
+
* before it did anything is tried again, up to CALL_RETRIES times after Retry-After: the environment's calls all
|
|
153
|
+
* running (429 concurrency_limit_exceeded), or, for a read, the database's connections busy (503 reason busy).
|
|
154
|
+
*/
|
|
149
155
|
async function call(method, path, body, raw) {
|
|
150
|
-
const
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
json =
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
156
|
+
const read = method === "GET" || /\/records\/(query|aggregate)$/.test(path);
|
|
157
|
+
for (let tries = 0;; tries++) {
|
|
158
|
+
const res = await f(`${base}${path}`, {
|
|
159
|
+
method, headers: { authorization: `Bearer ${token}`, ...scope, ...(raw ? (raw.type ? { "content-type": raw.type } : {}) : body === undefined ? {} : { "content-type": "application/json" }) },
|
|
160
|
+
...(raw ? { body: raw.body } : body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
161
|
+
});
|
|
162
|
+
if (res.status === 204)
|
|
163
|
+
return undefined;
|
|
164
|
+
const text = await res.text();
|
|
165
|
+
let json = {};
|
|
166
|
+
try {
|
|
167
|
+
json = text ? JSON.parse(text) : {};
|
|
168
|
+
}
|
|
169
|
+
catch { /* reported below */ }
|
|
170
|
+
if (res.ok)
|
|
171
|
+
return json;
|
|
172
|
+
const turnedAway = (res.status === 429 && json.error?.code === "concurrency_limit_exceeded") || (read && res.status === 503 && json.error?.reason === "busy");
|
|
173
|
+
if (turnedAway && tries < CALL_RETRIES) {
|
|
174
|
+
const after = Math.min(5, Number(res.headers.get("retry-after")) || 1);
|
|
175
|
+
await new Promise((done) => setTimeout(done, after * 1000 * (0.75 + Math.random() * 0.5)));
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
163
178
|
throw new ApiError(json.error?.message ?? `The API answered ${res.status}.`, res.status, json.error?.code ?? null, json.error?.problems ?? []);
|
|
164
|
-
|
|
179
|
+
}
|
|
165
180
|
}
|
|
166
181
|
const model = (name) => {
|
|
167
182
|
const m = `/models/${encodeURIComponent(name)}`;
|
|
@@ -336,6 +351,13 @@ export async function serveRecords(request, api, o = {}) {
|
|
|
336
351
|
return errorBody(403, "forbidden", `This route doesn't run ${String(body.action)}.`);
|
|
337
352
|
return Response.json(await api.$global(body.action, obj(body.params)));
|
|
338
353
|
}
|
|
354
|
+
if (body.op === "enqueue") {
|
|
355
|
+
if (!str(body.action) || !(o.enqueueActions ?? []).includes(body.action))
|
|
356
|
+
return errorBody(403, "forbidden", `This route doesn't queue ${String(body.action)}.`);
|
|
357
|
+
// The store is the request's own (its api is already that store's), never one the browser names.
|
|
358
|
+
const { shop: _, ...options } = obj(body.options);
|
|
359
|
+
return Response.json(await api.enqueue(body.action, obj(body.params), options));
|
|
360
|
+
}
|
|
339
361
|
// A live query's watch: which of its models changed, waiting for one to (#125).
|
|
340
362
|
if (body.op === "changes") {
|
|
341
363
|
const names = Array.isArray(body.models) ? body.models : [];
|
|
@@ -819,3 +841,75 @@ export async function verifyCustomerRequest(request, o = {}) {
|
|
|
819
841
|
source: proxied.pathPrefix === "/extension" ? "extension" : "proxy", api,
|
|
820
842
|
};
|
|
821
843
|
}
|
|
844
|
+
/** A DSN's parts, or null when it isn't one: `https://<key>@<host>[/<path>]/<project>`. */
|
|
845
|
+
export function parseDsn(dsn) {
|
|
846
|
+
let u;
|
|
847
|
+
try {
|
|
848
|
+
u = new URL(dsn.trim());
|
|
849
|
+
}
|
|
850
|
+
catch {
|
|
851
|
+
return null;
|
|
852
|
+
}
|
|
853
|
+
const m = /^(.*)\/(\d+)\/?$/.exec(u.pathname);
|
|
854
|
+
if (!u.username || !m || (u.protocol !== "https:" && u.protocol !== "http:"))
|
|
855
|
+
return null;
|
|
856
|
+
return { key: decodeURIComponent(u.username), envelope: `${u.protocol}//${u.host}${m[1]}/api/${m[2]}/envelope/` };
|
|
857
|
+
}
|
|
858
|
+
const FRAME = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/;
|
|
859
|
+
/** A V8 stack's frames as Sentry wants them: the outermost call first. Ours and dependencies' aren't the app's code. */
|
|
860
|
+
function stackFrames(stack) {
|
|
861
|
+
const frames = [];
|
|
862
|
+
for (const line of (stack ?? "").split("\n").slice(1, 51)) {
|
|
863
|
+
const m = FRAME.exec(line);
|
|
864
|
+
if (!m)
|
|
865
|
+
continue;
|
|
866
|
+
const filename = m[2].replace(/^file:\/\//, "");
|
|
867
|
+
const inApp = !/node_modules|^node:|^internal\/|\/ib\/sdk\//.test(filename);
|
|
868
|
+
frames.push({ function: m[1] ?? "?", filename, lineno: Number(m[3]), colno: Number(m[4]), in_app: inApp });
|
|
869
|
+
}
|
|
870
|
+
return frames.reverse();
|
|
871
|
+
}
|
|
872
|
+
/** The error and what caused it, the deepest cause first, as Sentry orders an exception chain. */
|
|
873
|
+
function exceptionChain(error, handled) {
|
|
874
|
+
const out = [];
|
|
875
|
+
let e = error;
|
|
876
|
+
for (let i = 0; i < 5 && e != null; i++) {
|
|
877
|
+
const err = e instanceof Error ? e : new Error(typeof e === "string" ? e : JSON.stringify(e));
|
|
878
|
+
out.unshift({ type: err.name || "Error", value: err.message.slice(0, 8000), stacktrace: { frames: stackFrames(err.stack) }, ...(i === 0 ? { mechanism: { type: "inferencebureau", handled } } : {}) });
|
|
879
|
+
e = err.cause;
|
|
880
|
+
}
|
|
881
|
+
return out;
|
|
882
|
+
}
|
|
883
|
+
/**
|
|
884
|
+
* Reports an error to the app's Sentry project. Answers the event's id, or null when there's no DSN or Sentry didn't
|
|
885
|
+
* take it. Never throws, and gives up after three seconds.
|
|
886
|
+
*/
|
|
887
|
+
export async function captureException(error, o = {}) {
|
|
888
|
+
const dsn = parseDsn(o.dsn ?? envVar("SENTRY_DSN") ?? "");
|
|
889
|
+
if (!dsn)
|
|
890
|
+
return null;
|
|
891
|
+
try {
|
|
892
|
+
const id = crypto.randomUUID().replace(/-/g, "");
|
|
893
|
+
const app = envVar("IB_APP");
|
|
894
|
+
const version = envVar("IB_FILE_VERSION");
|
|
895
|
+
const tags = Object.fromEntries(Object.entries({ ...(app ? { app } : {}), ...o.tags }).filter(([, v]) => v != null && v !== "").map(([k, v]) => [k, String(v).slice(0, 200)]));
|
|
896
|
+
const event = {
|
|
897
|
+
event_id: id, timestamp: Date.now() / 1000, platform: "node", level: o.level ?? "error",
|
|
898
|
+
environment: o.environment ?? envVar("IB_ENVIRONMENT") ?? "production",
|
|
899
|
+
...(app && version ? { release: `${app}@${version}` } : {}),
|
|
900
|
+
tags, ...(o.extra ? { extra: o.extra } : {}),
|
|
901
|
+
exception: { values: exceptionChain(error, o.handled ?? true) },
|
|
902
|
+
sdk: { name: "inferencebureau.apps-sdk", version: "1" },
|
|
903
|
+
};
|
|
904
|
+
const body = `${JSON.stringify({ event_id: id, sent_at: new Date().toISOString() })}\n${JSON.stringify({ type: "event" })}\n${JSON.stringify(event)}\n`;
|
|
905
|
+
const res = await (o.fetch ?? fetch)(dsn.envelope, {
|
|
906
|
+
method: "POST", body,
|
|
907
|
+
headers: { "content-type": "application/x-sentry-envelope", "x-sentry-auth": `Sentry sentry_version=7, sentry_client=inferencebureau.apps-sdk/1, sentry_key=${dsn.key}` },
|
|
908
|
+
...(typeof AbortSignal.timeout === "function" ? { signal: AbortSignal.timeout(3000) } : {}),
|
|
909
|
+
});
|
|
910
|
+
return res.ok ? id : null;
|
|
911
|
+
}
|
|
912
|
+
catch {
|
|
913
|
+
return null;
|
|
914
|
+
}
|
|
915
|
+
}
|
package/dist/react.d.ts
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* goes through the route like any other, so it sees only what the viewer may.
|
|
16
16
|
*/
|
|
17
17
|
import { type FormEvent, type ReactNode } from "react";
|
|
18
|
-
import { ApiError, type AggregateOptions, type AggregateResult, 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";
|
|
19
19
|
import { type Column, type ColumnOption, type Display, type FieldOption, type FormFieldSpec, type FormValue, type SortOption } from "./auto.js";
|
|
20
20
|
export { labelOf, recordLabel } from "./auto.js";
|
|
21
21
|
export type { Column, ColumnOption, Display, FieldOption, FormFieldSpec, FormValue, InputKind, SortOption } from "./auto.js";
|
|
@@ -23,39 +23,52 @@ export type { Column, ColumnOption, Display, FieldOption, FormFieldSpec, FormVal
|
|
|
23
23
|
export type ReadOptions = Omit<FindManyOptions, "select"> & {
|
|
24
24
|
select?: Record<string, unknown>;
|
|
25
25
|
};
|
|
26
|
-
|
|
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> {
|
|
27
31
|
describe(): Promise<ModelDescription>;
|
|
28
|
-
findMany(options?:
|
|
29
|
-
findOne(id: string, o?: {
|
|
30
|
-
select?:
|
|
31
|
-
}): Promise<
|
|
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>;
|
|
32
36
|
/** Counts, sums, averages, least and most over the records, in groups or all together. */
|
|
33
|
-
aggregate
|
|
34
|
-
|
|
35
|
-
|
|
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"]>;
|
|
36
42
|
delete(id: string): Promise<void>;
|
|
37
43
|
bulkDelete(ids: string[]): Promise<BulkDeleteResult>;
|
|
38
44
|
/** Runs one of the model's actions: on a record when `id` is given. */
|
|
39
|
-
run(action:
|
|
45
|
+
run<A extends keyof M["actions"] & string>(action: A, o?: {
|
|
40
46
|
id?: string;
|
|
41
|
-
params?:
|
|
47
|
+
params?: M["actions"][A]["params"];
|
|
42
48
|
}): Promise<{
|
|
43
|
-
record:
|
|
44
|
-
result?:
|
|
49
|
+
record: M["record"] | null;
|
|
50
|
+
result?: M["actions"][A]["result"];
|
|
45
51
|
}>;
|
|
46
52
|
/** Uploads a file for a file field straight to storage; write the answer to the field. */
|
|
47
|
-
upload(field:
|
|
53
|
+
upload(field: M["files"], file: Blob, o?: {
|
|
48
54
|
fileName?: string;
|
|
49
55
|
}): Promise<{
|
|
50
56
|
directUploadToken: string;
|
|
51
57
|
}>;
|
|
52
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">;
|
|
53
61
|
export interface RecordsClient {
|
|
54
|
-
model(name:
|
|
62
|
+
model<N extends ModelName>(name: N): RecordsModel<ModelOf<N>>;
|
|
55
63
|
/** Runs a global action the route allows (`serveRecords`'s `globalActions`). */
|
|
56
|
-
global(action:
|
|
57
|
-
result?:
|
|
64
|
+
global<A extends GlobalName>(action: A, params?: GlobalOf<A>["params"]): Promise<{
|
|
65
|
+
result?: GlobalOf<A>["result"];
|
|
58
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>;
|
|
59
72
|
/** Called with a model's name whenever a write through this client changed its records; returns the unsubscribe. */
|
|
60
73
|
subscribe(listener: (model: string) => void): () => void;
|
|
61
74
|
/**
|
|
@@ -96,47 +109,83 @@ export interface ReadHookOptions {
|
|
|
96
109
|
/** Read again whenever the model's records change, whoever changes them. */
|
|
97
110
|
live?: boolean;
|
|
98
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
|
+
}
|
|
99
123
|
/**
|
|
100
|
-
* A page of a model's records
|
|
101
|
-
*
|
|
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;
|
|
102
131
|
*/
|
|
103
|
-
export declare function useFindMany(model:
|
|
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>>;
|
|
104
133
|
/** One record by id, or null when there's none the caller can read. */
|
|
105
|
-
export declare function useFindOne(model:
|
|
106
|
-
select?:
|
|
107
|
-
}): Query<
|
|
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>;
|
|
108
137
|
/** The first record matching, or null. */
|
|
109
|
-
export declare function useFindFirst(model:
|
|
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>;
|
|
110
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. */
|
|
111
|
-
export declare function useAggregate
|
|
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?: {
|
|
112
143
|
pause?: boolean;
|
|
113
|
-
}): Query<AggregateResult
|
|
144
|
+
}): Query<AggregateResult<A>>;
|
|
114
145
|
/** A model's description: its fields, which AutoTable and AutoForm draw from. */
|
|
115
|
-
export declare function useModel(model:
|
|
146
|
+
export declare function useModel(model: ModelName): Query<ModelDescription>;
|
|
116
147
|
export interface Mutation<T, A> {
|
|
117
148
|
data: T | undefined;
|
|
118
149
|
running: boolean;
|
|
119
150
|
error: ApiError | null;
|
|
120
151
|
run(args: A): Promise<T>;
|
|
121
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;
|
|
122
158
|
/**
|
|
123
159
|
* One of a model's actions: `create`, `update` and `delete` write the way the API does (the model's action when it has
|
|
124
|
-
* one), any other runs by name.
|
|
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.
|
|
125
162
|
*
|
|
126
163
|
* const publish = useAction("post", "publish");
|
|
127
164
|
* await publish.run({ id: post.id });
|
|
128
165
|
*/
|
|
129
|
-
export declare function useAction(model:
|
|
130
|
-
record:
|
|
131
|
-
result?:
|
|
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>;
|
|
132
169
|
}, {
|
|
133
170
|
id?: string;
|
|
134
|
-
params?:
|
|
171
|
+
params?: ActionParams<N, A>;
|
|
135
172
|
}>;
|
|
136
173
|
/** A global action the records route allows (`serveRecords`'s `globalActions`). */
|
|
137
|
-
export declare function useGlobalAction(action:
|
|
138
|
-
result?:
|
|
139
|
-
},
|
|
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>;
|
|
140
189
|
export interface AutoTableOptions {
|
|
141
190
|
/** Which columns, in order; the first six that read well in a cell, then Updated, when unset. */
|
|
142
191
|
columns?: ColumnOption[];
|
|
@@ -186,7 +235,7 @@ export interface AutoTable {
|
|
|
186
235
|
refetch(): void;
|
|
187
236
|
}
|
|
188
237
|
/** What a table of the model shows and does, for a renderer to draw. */
|
|
189
|
-
export declare function useAutoTable(model:
|
|
238
|
+
export declare function useAutoTable(model: ModelName, o?: AutoTableOptions): AutoTable;
|
|
190
239
|
export interface AutoFormOptions {
|
|
191
240
|
/** The record to edit; a new one is made without it. */
|
|
192
241
|
id?: string;
|
|
@@ -235,13 +284,13 @@ export interface AutoForm {
|
|
|
235
284
|
isNew: boolean;
|
|
236
285
|
}
|
|
237
286
|
/** What a form for the model shows and does, for a renderer to draw. */
|
|
238
|
-
export declare function useAutoForm(model:
|
|
287
|
+
export declare function useAutoForm(model: ModelName, o?: AutoFormOptions): AutoForm;
|
|
239
288
|
/** A cell as standard elements, for the plain table. */
|
|
240
289
|
export declare function PlainCell({ value }: {
|
|
241
290
|
value: Display;
|
|
242
291
|
}): import("react").JSX.Element;
|
|
243
292
|
export interface AutoTableProps extends AutoTableOptions {
|
|
244
|
-
model:
|
|
293
|
+
model: ModelName;
|
|
245
294
|
/** What a row opens: a link to the record's page, say. */
|
|
246
295
|
rowHref?(record: AppRecord): string;
|
|
247
296
|
onRowClick?(record: AppRecord): void;
|
|
@@ -257,7 +306,7 @@ export declare function PlainInput({ field: f }: {
|
|
|
257
306
|
field: AutoFormField;
|
|
258
307
|
}): import("react").JSX.Element;
|
|
259
308
|
export interface AutoFormProps extends AutoFormOptions {
|
|
260
|
-
model:
|
|
309
|
+
model: ModelName;
|
|
261
310
|
/** The submit button's words; Save, or Create for a new record, unless given. */
|
|
262
311
|
submitLabel?: string;
|
|
263
312
|
}
|
package/dist/react.js
CHANGED
|
@@ -17,7 +17,7 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
|
|
|
17
17
|
* goes through the route like any other, so it sees only what the viewer may.
|
|
18
18
|
*/
|
|
19
19
|
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
|
|
20
|
-
import { ApiError } from "./index.js";
|
|
20
|
+
import { ApiError, } from "./index.js";
|
|
21
21
|
import { sessionFetch } from "./browser.js";
|
|
22
22
|
import { choicesOf, columnsOf, display, formFieldsOf, initialValue, problemField, selectFor, sortOptions, toRecordValue, unchanged, } from "./auto.js";
|
|
23
23
|
export { labelOf, recordLabel } from "./auto.js";
|
|
@@ -50,7 +50,7 @@ export function createRecordsClient(o = {}) {
|
|
|
50
50
|
descriptions.set(name, call({ op: "describe", model: name }).catch((e) => { descriptions.delete(name); throw e; }));
|
|
51
51
|
return descriptions.get(name);
|
|
52
52
|
},
|
|
53
|
-
findMany: (options = {}) => call({ op: "findMany", model: name, options }),
|
|
53
|
+
findMany: (options = {}) => call({ op: "findMany", model: name, options: options }),
|
|
54
54
|
aggregate: (options) => call({ op: "aggregate", model: name, options }),
|
|
55
55
|
findOne: async (id, q = {}) => {
|
|
56
56
|
try {
|
|
@@ -127,9 +127,10 @@ export function createRecordsClient(o = {}) {
|
|
|
127
127
|
}
|
|
128
128
|
const models = new Map();
|
|
129
129
|
return {
|
|
130
|
-
model: (name) => { if (!models.has(name))
|
|
131
|
-
models.set(name, model(name)); return models.get(name); },
|
|
132
|
-
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 } : {}) } }),
|
|
133
134
|
subscribe: (l) => { listeners.add(l); return () => { listeners.delete(l); }; },
|
|
134
135
|
watch(names, l) {
|
|
135
136
|
const fn = (m) => l(m);
|
|
@@ -193,33 +194,60 @@ function useQuery(model, key, read, live = false) {
|
|
|
193
194
|
const refetch = useCallback(() => setNonce((n) => n + 1), []);
|
|
194
195
|
return { data: state.key === key ? state.data : undefined, fetching: state.fetching, error: state.error, refetch };
|
|
195
196
|
}
|
|
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);
|
|
196
199
|
/**
|
|
197
|
-
* A page of a model's records
|
|
198
|
-
*
|
|
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;
|
|
199
207
|
*/
|
|
200
208
|
export function useFindMany(model, options = {}, o = {}) {
|
|
201
209
|
const client = useRecordsClient();
|
|
202
|
-
|
|
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
|
+
};
|
|
203
230
|
}
|
|
204
231
|
/** One record by id, or null when there's none the caller can read. */
|
|
205
232
|
export function useFindOne(model, id, o = {}) {
|
|
206
233
|
const client = useRecordsClient();
|
|
207
|
-
|
|
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);
|
|
208
236
|
}
|
|
209
237
|
/** The first record matching, or null. */
|
|
210
238
|
export function useFindFirst(model, options = {}, o = {}) {
|
|
211
239
|
const client = useRecordsClient();
|
|
212
|
-
return useQuery(model, `${model}:first:${JSON.stringify(options)}`, o.pause ? null : async () => (await client
|
|
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);
|
|
213
241
|
}
|
|
214
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. */
|
|
215
243
|
export function useAggregate(model, options, o = {}) {
|
|
216
244
|
const client = useRecordsClient();
|
|
217
|
-
return useQuery(model, `${model}:aggregate:${JSON.stringify(options)}`, o.pause ? null : () => client
|
|
245
|
+
return useQuery(model, `${model}:aggregate:${JSON.stringify(options)}`, o.pause ? null : () => untyped(client, model).aggregate(options));
|
|
218
246
|
}
|
|
219
247
|
/** A model's description: its fields, which AutoTable and AutoForm draw from. */
|
|
220
248
|
export function useModel(model) {
|
|
221
249
|
const client = useRecordsClient();
|
|
222
|
-
return useQuery(model, `${model}:describe`, () => client
|
|
250
|
+
return useQuery(model, `${model}:describe`, () => untyped(client, model).describe());
|
|
223
251
|
}
|
|
224
252
|
function useMutation(send) {
|
|
225
253
|
const [state, setState] = useState({ data: undefined, running: false, error: null });
|
|
@@ -242,47 +270,69 @@ function useMutation(send) {
|
|
|
242
270
|
}
|
|
243
271
|
/**
|
|
244
272
|
* One of a model's actions: `create`, `update` and `delete` write the way the API does (the model's action when it has
|
|
245
|
-
* one), any other runs by name.
|
|
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.
|
|
246
275
|
*
|
|
247
276
|
* const publish = useAction("post", "publish");
|
|
248
277
|
* await publish.run({ id: post.id });
|
|
249
278
|
*/
|
|
250
279
|
export function useAction(model, action) {
|
|
251
280
|
const client = useRecordsClient();
|
|
252
|
-
return useMutation(async ({ id, params
|
|
253
|
-
const m = client
|
|
281
|
+
return useMutation(async ({ id, params }) => {
|
|
282
|
+
const m = untyped(client, model);
|
|
283
|
+
const values = (params ?? {});
|
|
254
284
|
if (action === "create" && !id)
|
|
255
|
-
return { record: await m.create(
|
|
285
|
+
return { record: await m.create(values) };
|
|
256
286
|
if (action === "update" && id)
|
|
257
|
-
return { record: await m.update(id,
|
|
287
|
+
return { record: await m.update(id, values) };
|
|
258
288
|
if (action === "delete" && id) {
|
|
259
289
|
await m.delete(id);
|
|
260
290
|
return { record: null };
|
|
261
291
|
}
|
|
262
|
-
return m.run(action, { ...(id ? { id } : {}), params });
|
|
292
|
+
return m.run(action, { ...(id ? { id } : {}), params: values });
|
|
263
293
|
});
|
|
264
294
|
}
|
|
265
295
|
/** A global action the records route allows (`serveRecords`'s `globalActions`). */
|
|
266
296
|
export function useGlobalAction(action) {
|
|
267
297
|
const client = useRecordsClient();
|
|
268
|
-
return useMutation((params) => client.global(action, params
|
|
298
|
+
return useMutation((params) => client.global(action, params));
|
|
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
|
+
});
|
|
269
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;
|
|
270
321
|
const SEARCH_WAIT = 250;
|
|
271
322
|
/** What a table of the model shows and does, for a renderer to draw. */
|
|
272
323
|
export function useAutoTable(model, o = {}) {
|
|
273
324
|
const client = useRecordsClient();
|
|
274
|
-
const described =
|
|
325
|
+
const described = useAnyModel(model);
|
|
275
326
|
const columns = useMemo(() => (described.data ? columnsOf(described.data, o.columns) : []), [described.data, JSON.stringify(o.columns ?? null)]);
|
|
276
327
|
const [search, setSearchNow] = useState("");
|
|
277
328
|
const [query, setQuery] = useState("");
|
|
278
329
|
const [sort, setSortValue] = useState("");
|
|
279
|
-
const [cursors, setCursors] = useState([null]);
|
|
280
330
|
const [selected, setSelected] = useState(new Set());
|
|
281
331
|
const [deleting, setDeleting] = useState(false);
|
|
282
332
|
const [deleteError, setDeleteError] = useState(null);
|
|
283
|
-
// Typing waits a moment before reading
|
|
333
|
+
// Typing waits a moment before reading (a new search starts from the first page, as any new options do).
|
|
284
334
|
useEffect(() => {
|
|
285
|
-
const t = setTimeout(() =>
|
|
335
|
+
const t = setTimeout(() => setQuery(search.trim()), SEARCH_WAIT);
|
|
286
336
|
return () => clearTimeout(t);
|
|
287
337
|
}, [search]);
|
|
288
338
|
const options = sortOptions(columns);
|
|
@@ -290,13 +340,12 @@ export function useAutoTable(model, o = {}) {
|
|
|
290
340
|
const order = chosen ? { [chosen.field]: chosen.direction } : o.sort;
|
|
291
341
|
const findOptions = {
|
|
292
342
|
first: Math.min(o.pageSize ?? 25, 250),
|
|
293
|
-
after: cursors[cursors.length - 1] ?? null,
|
|
294
343
|
...(columns.length ? { select: selectFor(columns) } : {}),
|
|
295
344
|
...(o.filter ? { filter: o.filter } : {}),
|
|
296
345
|
...(order ? { sort: order } : {}),
|
|
297
346
|
...(query ? { search: query } : {}),
|
|
298
347
|
};
|
|
299
|
-
const page =
|
|
348
|
+
const page = useAnyMany(model, findOptions, { pause: !described.data, live: !!o.live });
|
|
300
349
|
const records = page.data?.records ?? [];
|
|
301
350
|
const rows = records.map((record) => ({ id: record.id, record, cells: columns.map((c) => display(c.field, record[c.name])) }));
|
|
302
351
|
// A new page chooses nothing; the same page read again keeps the rows still on it chosen.
|
|
@@ -315,18 +364,16 @@ export function useAutoTable(model, o = {}) {
|
|
|
315
364
|
setSearch: setSearchNow,
|
|
316
365
|
sortOptions: options,
|
|
317
366
|
sort,
|
|
318
|
-
setSort:
|
|
367
|
+
setSort: setSortValue,
|
|
319
368
|
toggleSort: (name) => {
|
|
320
369
|
const asc = `${name}:Ascending`, desc = `${name}:Descending`;
|
|
321
370
|
setSortValue(sort === asc ? desc : asc);
|
|
322
|
-
setCursors([null]);
|
|
323
371
|
},
|
|
324
|
-
page:
|
|
325
|
-
hasNextPage:
|
|
326
|
-
hasPreviousPage:
|
|
327
|
-
nextPage:
|
|
328
|
-
|
|
329
|
-
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,
|
|
330
377
|
selected,
|
|
331
378
|
toggle: (id) => setSelected((s) => { const n = new Set(s); if (n.has(id))
|
|
332
379
|
n.delete(id);
|
|
@@ -340,11 +387,11 @@ export function useAutoTable(model, o = {}) {
|
|
|
340
387
|
setDeleting(true);
|
|
341
388
|
setDeleteError(null);
|
|
342
389
|
try {
|
|
343
|
-
const r = await client
|
|
390
|
+
const r = await untyped(client, model).bulkDelete([...selected]);
|
|
344
391
|
if (r.failed.length)
|
|
345
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"));
|
|
346
393
|
// The page may now be short or empty; start again from the first.
|
|
347
|
-
|
|
394
|
+
page.resetPages();
|
|
348
395
|
}
|
|
349
396
|
catch (e) {
|
|
350
397
|
setDeleteError(asApiError(e));
|
|
@@ -360,7 +407,7 @@ export function useAutoTable(model, o = {}) {
|
|
|
360
407
|
/** What a form for the model shows and does, for a renderer to draw. */
|
|
361
408
|
export function useAutoForm(model, o = {}) {
|
|
362
409
|
const client = useRecordsClient();
|
|
363
|
-
const described =
|
|
410
|
+
const described = useAnyModel(model);
|
|
364
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)]);
|
|
365
412
|
const select = useMemo(() => {
|
|
366
413
|
const s = {};
|
|
@@ -369,7 +416,7 @@ export function useAutoForm(model, o = {}) {
|
|
|
369
416
|
s[f.name] = true;
|
|
370
417
|
return s;
|
|
371
418
|
}, [specs]);
|
|
372
|
-
const existing =
|
|
419
|
+
const existing = useAnyOne(model, o.id, { select: select, pause: !specs.length });
|
|
373
420
|
const record = o.id ? existing.data : undefined;
|
|
374
421
|
const initial = useMemo(() => {
|
|
375
422
|
const out = {};
|
|
@@ -393,7 +440,7 @@ export function useAutoForm(model, o = {}) {
|
|
|
393
440
|
for (const s of specs) {
|
|
394
441
|
if (s.kind !== "record" || !s.parent)
|
|
395
442
|
continue;
|
|
396
|
-
client
|
|
443
|
+
untyped(client, s.parent).findMany({ first: 100 }).then((p) => { if (live)
|
|
397
444
|
setChoices((c) => ({ ...c, [s.name]: choicesOf(p.records) })); }, () => { });
|
|
398
445
|
}
|
|
399
446
|
return () => { live = false; };
|
|
@@ -446,7 +493,7 @@ export function useAutoForm(model, o = {}) {
|
|
|
446
493
|
setSubmitting(true);
|
|
447
494
|
setError(null);
|
|
448
495
|
try {
|
|
449
|
-
const m = client
|
|
496
|
+
const m = untyped(client, model);
|
|
450
497
|
for (const s of specs) {
|
|
451
498
|
const v = value(s.name);
|
|
452
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?: {
|
package/dist/runtime.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* `api` read or built. Inference Bureau applies all of it in one transaction, then calls again for `onSuccess` with
|
|
6
6
|
* the saved record.
|
|
7
7
|
*/
|
|
8
|
-
import { createAiClient, createClient, createShopifyClient, newRecordId, pendingWrite, stagedWrites, trackRecord } from "./index.js";
|
|
8
|
+
import { captureException, createAiClient, createClient, createShopifyClient, newRecordId, pendingWrite, stagedWrites, trackRecord } from "./index.js";
|
|
9
9
|
/** The most spans a phase reports; past it they're counted, not kept. */
|
|
10
10
|
export const MAX_SPANS = 200;
|
|
11
11
|
const clock = () => globalThis.performance?.now?.() ?? Date.now();
|
|
@@ -189,7 +189,7 @@ function stagingApi(api, handed) {
|
|
|
189
189
|
/**
|
|
190
190
|
* Runs one phase of an action, without checking where the request came from (handleAction does). `api`, `shopify`
|
|
191
191
|
* and `ai` stand in for the environment's clients (the test app's in-memory ones); `echo: false` keeps the logger's
|
|
192
|
-
* lines off the console.
|
|
192
|
+
* lines off the console; `sentry` stands in for SENTRY_DSN, and false (the test app's) reports nothing.
|
|
193
193
|
*/
|
|
194
194
|
export async function runAction(req, registry, o = {}) {
|
|
195
195
|
const logs = [];
|
|
@@ -233,6 +233,13 @@ export async function runAction(req, registry, o = {}) {
|
|
|
233
233
|
}
|
|
234
234
|
catch (e) {
|
|
235
235
|
const err = e instanceof Error ? e : new Error(String(e));
|
|
236
|
+
// With the Sentry integration, what the action threw goes to the app's Sentry project too, before the answer.
|
|
237
|
+
if (o.sentry !== false && (o.sentry ?? envVar("SENTRY_DSN"))) {
|
|
238
|
+
await captureException(e, {
|
|
239
|
+
handled: false, environment: req.environment, ...(o.sentry ? { dsn: o.sentry.dsn, ...(o.sentry.fetch ? { fetch: o.sentry.fetch } : {}) } : {}),
|
|
240
|
+
tags: { action: req.model ? `${req.model}.${req.action}` : req.action, phase: req.phase, shop: req.shop, "ib.event": req.event, "ib.background": req.background ? "true" : null },
|
|
241
|
+
});
|
|
242
|
+
}
|
|
236
243
|
return { ok: false, error: { message: err.message, ...(err.stack ? { stack: err.stack.split("\n").slice(0, 8).join("\n") } : {}) }, logs, ...traced() };
|
|
237
244
|
}
|
|
238
245
|
}
|
package/dist/test.js
CHANGED
|
@@ -1551,8 +1551,10 @@ class Records {
|
|
|
1551
1551
|
const p = this.prepare(m, values, null);
|
|
1552
1552
|
const at = this.stamp();
|
|
1553
1553
|
const row = { id: id ?? `rec_${String(++this.seq).padStart(6, "0")}`, createdAt: at, updatedAt: at, data: p.data, vectors: new Map() };
|
|
1554
|
-
|
|
1554
|
+
// In the table before anything is awaited, as the API's lock holds a unique value: two creates at once can't both
|
|
1555
|
+
// pass the checks above.
|
|
1555
1556
|
this.table(m).set(row.id, row);
|
|
1557
|
+
await this.vectorize(m, row, p.vectors, null);
|
|
1556
1558
|
this.log(m, row.data);
|
|
1557
1559
|
return this.present(m, row, true);
|
|
1558
1560
|
}
|
|
@@ -2341,7 +2343,7 @@ export function createTestApp(o = {}) {
|
|
|
2341
2343
|
});
|
|
2342
2344
|
const req = { phase: p, model, action, params, record: rec, isNew, environment, shop, caller: how.caller ?? null, ...(how.background ? { background: true } : {}) };
|
|
2343
2345
|
try {
|
|
2344
|
-
return await Promise.race([runPhase(wire(req), registry, { api, shopify: shopify.client, ai: ai.client(), echo: o.echo ?? false }), late]);
|
|
2346
|
+
return await Promise.race([runPhase(wire(req), registry, { api, shopify: shopify.client, ai: ai.client(), echo: o.echo ?? false, sentry: false }), late]);
|
|
2345
2347
|
}
|
|
2346
2348
|
finally {
|
|
2347
2349
|
clearTimeout(timer);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inferencebureau/apps-sdk",
|
|
3
|
-
"version": "0.15.
|
|
3
|
+
"version": "0.15.1",
|
|
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": [
|
|
@@ -57,7 +57,7 @@
|
|
|
57
57
|
"README.md"
|
|
58
58
|
],
|
|
59
59
|
"engines": {
|
|
60
|
-
"node": ">=
|
|
60
|
+
"node": ">=22"
|
|
61
61
|
},
|
|
62
62
|
"publishConfig": {
|
|
63
63
|
"access": "public"
|
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
"scripts": {
|
|
66
66
|
"build": "rm -rf dist && tsc -p tsconfig.build.json && node scripts/fix-dist.mjs",
|
|
67
67
|
"prepublishOnly": "npm run build",
|
|
68
|
-
"typecheck": "tsc --noEmit",
|
|
68
|
+
"typecheck": "tsc --noEmit && tsc -p test/types",
|
|
69
69
|
"test": "vitest run",
|
|
70
70
|
"embed": "node scripts/embed.mjs"
|
|
71
71
|
},
|