@inferencebureau/apps-sdk 0.15.0 → 0.15.2
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 +121 -16
- package/dist/index.js +112 -17
- 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 +37 -23
- 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;
|
|
@@ -783,10 +803,11 @@ export type Api = ModelClients & {
|
|
|
783
803
|
forShop(shop: string): Api;
|
|
784
804
|
/**
|
|
785
805
|
* The same API held to a role in accessControl/permissions.ib.ts: only what the role is granted, through its
|
|
786
|
-
* filters, with `session` standing in for `{ $session: "userId" | "customerId" }`.
|
|
806
|
+
* filters, with `session` standing in for `{ $session: "userId" | "customerId" | "accountId" }`. Several roles
|
|
807
|
+
* (`["signed-in", "account-admin"]`) are held to the union of their grants. A Shopify session's and a proxy
|
|
787
808
|
* request's `api` already are.
|
|
788
809
|
*/
|
|
789
|
-
asRole(role: string, session?: CallerSession): Api;
|
|
810
|
+
asRole(role: string | string[], session?: CallerSession): Api;
|
|
790
811
|
/** Shopify sync on demand: one store, some or all of its synced models, everything or what changed since a date. */
|
|
791
812
|
shopifySync: ShopifySync;
|
|
792
813
|
/**
|
|
@@ -916,7 +937,8 @@ export interface Changes {
|
|
|
916
937
|
export interface CallerSession {
|
|
917
938
|
userId?: string | null;
|
|
918
939
|
customerId?: string | null;
|
|
919
|
-
customerRecordId?: string | null;
|
|
940
|
+
customerRecordId?: string | null; /** The account the user acts in (a web app's `$session: "accountId"`). */
|
|
941
|
+
accountId?: string | null;
|
|
920
942
|
}
|
|
921
943
|
export interface EnqueueOptions {
|
|
922
944
|
/** The record a model's action works on. */
|
|
@@ -955,8 +977,8 @@ export interface ClientOptions {
|
|
|
955
977
|
fetch?: typeof fetch;
|
|
956
978
|
/** Narrows every call to one store (see `Api.forShop`). */
|
|
957
979
|
shop?: string;
|
|
958
|
-
/** Holds every call to a role in permissions.ib.ts (see `Api.asRole`). */
|
|
959
|
-
role?: string;
|
|
980
|
+
/** Holds every call to a role in permissions.ib.ts, or to several roles' grants together (see `Api.asRole`). */
|
|
981
|
+
role?: string | string[];
|
|
960
982
|
session?: CallerSession;
|
|
961
983
|
}
|
|
962
984
|
/** The app's API. In an app's deployment every option comes from its environment variables. */
|
|
@@ -1014,6 +1036,13 @@ export type RecordsRequest = {
|
|
|
1014
1036
|
op: "global";
|
|
1015
1037
|
action: string;
|
|
1016
1038
|
params?: Record<string, unknown>;
|
|
1039
|
+
} | {
|
|
1040
|
+
op: "enqueue";
|
|
1041
|
+
action: string;
|
|
1042
|
+
params?: Record<string, unknown>;
|
|
1043
|
+
options?: Omit<EnqueueOptions, "shop" | "runAt"> & {
|
|
1044
|
+
runAt?: string;
|
|
1045
|
+
};
|
|
1017
1046
|
} | {
|
|
1018
1047
|
op: "changes";
|
|
1019
1048
|
models: string[];
|
|
@@ -1024,6 +1053,11 @@ export interface ServeRecordsOptions {
|
|
|
1024
1053
|
models?: string[];
|
|
1025
1054
|
/** The global actions it runs; none when unset. */
|
|
1026
1055
|
globalActions?: string[];
|
|
1056
|
+
/**
|
|
1057
|
+
* The actions it queues as background jobs (`useEnqueue`): global actions' names and `<model>.<action>`; none when
|
|
1058
|
+
* unset. A job runs for the request's store and is held to its role, the way `api.enqueue` is.
|
|
1059
|
+
*/
|
|
1060
|
+
enqueueActions?: string[];
|
|
1027
1061
|
/**
|
|
1028
1062
|
* Seconds a live query's watch waits for a change before the route answers that none came (25 unless given, 0 to
|
|
1029
1063
|
* 25). The route's function must be allowed to run that long; a shorter wait just means more requests.
|
|
@@ -1444,9 +1478,12 @@ export interface Logger {
|
|
|
1444
1478
|
warn(message: string, data?: unknown): void;
|
|
1445
1479
|
error(message: string, data?: unknown): void;
|
|
1446
1480
|
}
|
|
1447
|
-
export interface ActionContext {
|
|
1448
|
-
/**
|
|
1449
|
-
|
|
1481
|
+
export interface ActionContext<P = Record<string, unknown>> {
|
|
1482
|
+
/**
|
|
1483
|
+
* What the caller passed. A model action's fields may be at the top level or under the model's name. Typed from the
|
|
1484
|
+
* file's `export const params` with `ActionRun<DeclaredParams<typeof params>>` (the declaration `as const`).
|
|
1485
|
+
*/
|
|
1486
|
+
params: P;
|
|
1450
1487
|
/** The record the action works on: the stored one, or a new, empty one for a create. Null in a global action. */
|
|
1451
1488
|
record: ActionRecord;
|
|
1452
1489
|
/**
|
|
@@ -1486,14 +1523,19 @@ export interface ActionCaller {
|
|
|
1486
1523
|
customerId?: string | null;
|
|
1487
1524
|
customerRecordId?: string | null;
|
|
1488
1525
|
}
|
|
1489
|
-
export type ActionRun = (ctx: ActionContext) => unknown | Promise<unknown>;
|
|
1490
|
-
export type ActionOnSuccess = (ctx: ActionContext) => void | Promise<void>;
|
|
1491
|
-
export type GlobalActionRun = (ctx: Omit<ActionContext
|
|
1526
|
+
export type ActionRun<P = Record<string, unknown>> = (ctx: ActionContext<P>) => unknown | Promise<unknown>;
|
|
1527
|
+
export type ActionOnSuccess<P = Record<string, unknown>> = (ctx: ActionContext<P>) => void | Promise<void>;
|
|
1528
|
+
export type GlobalActionRun<P = Record<string, unknown>> = (ctx: Omit<ActionContext<P>, "record"> & {
|
|
1492
1529
|
record: null;
|
|
1493
1530
|
}) => unknown | Promise<unknown>;
|
|
1494
1531
|
export interface ActionOptions {
|
|
1495
1532
|
/** create: works on a new record; update and custom: on the record named by id; delete: removes it. */
|
|
1496
1533
|
actionType?: "create" | "update" | "delete" | "custom";
|
|
1534
|
+
/**
|
|
1535
|
+
* A line on what the action does, for the app's API reference, its generated types and its MCP server. Inference
|
|
1536
|
+
* Bureau reads it from the file, like `params`: keep `options` a plain object literal.
|
|
1537
|
+
*/
|
|
1538
|
+
description?: string;
|
|
1497
1539
|
/** Whether what `run` returns goes back to the caller (it's dropped otherwise). */
|
|
1498
1540
|
returnType?: boolean;
|
|
1499
1541
|
/**
|
|
@@ -1519,6 +1561,8 @@ export interface ParamDef {
|
|
|
1519
1561
|
type: "string" | "number" | "boolean" | "dateTime" | "enum" | "json" | "object" | "array";
|
|
1520
1562
|
/** Callers must pass it. */
|
|
1521
1563
|
required?: boolean;
|
|
1564
|
+
/** A line on what the param is, for the app's API reference, its generated types and its MCP server. */
|
|
1565
|
+
description?: string;
|
|
1522
1566
|
/** enum: the values it takes. */
|
|
1523
1567
|
options?: string[];
|
|
1524
1568
|
/** object: its keys. */
|
|
@@ -1526,6 +1570,67 @@ export interface ParamDef {
|
|
|
1526
1570
|
/** array: each item. */
|
|
1527
1571
|
items?: ParamDef;
|
|
1528
1572
|
}
|
|
1573
|
+
/**
|
|
1574
|
+
* What an action's `export const params` declares, as types, for `run` to read them typed:
|
|
1575
|
+
*
|
|
1576
|
+
* export const params = { note: { type: "string" }, notify: { type: "boolean", required: true } } as const satisfies ActionParams;
|
|
1577
|
+
* export const run: ActionRun<DeclaredParams<typeof params>> = async ({ params }) => { params.note; // string | undefined
|
|
1578
|
+
*
|
|
1579
|
+
* Nothing checks them at run time: a caller can still send anything.
|
|
1580
|
+
*/
|
|
1581
|
+
export type DeclaredParams<D> = Flat<{
|
|
1582
|
+
-readonly [K in keyof D as D[K] extends {
|
|
1583
|
+
required: true;
|
|
1584
|
+
} ? K : never]: DeclaredValue<D[K]>;
|
|
1585
|
+
} & {
|
|
1586
|
+
-readonly [K in keyof D as D[K] extends {
|
|
1587
|
+
required: true;
|
|
1588
|
+
} ? never : K]?: DeclaredValue<D[K]>;
|
|
1589
|
+
}>;
|
|
1590
|
+
type DeclaredValue<P> = P extends {
|
|
1591
|
+
type: "string" | "dateTime";
|
|
1592
|
+
} ? string : P extends {
|
|
1593
|
+
type: "number";
|
|
1594
|
+
} ? number : P extends {
|
|
1595
|
+
type: "boolean";
|
|
1596
|
+
} ? boolean : P extends {
|
|
1597
|
+
type: "enum";
|
|
1598
|
+
options: readonly (infer O)[];
|
|
1599
|
+
} ? O : P extends {
|
|
1600
|
+
type: "enum";
|
|
1601
|
+
} ? string : P extends {
|
|
1602
|
+
type: "object";
|
|
1603
|
+
properties: infer Q;
|
|
1604
|
+
} ? DeclaredParams<Q> : P extends {
|
|
1605
|
+
type: "array";
|
|
1606
|
+
items: infer I;
|
|
1607
|
+
} ? DeclaredValue<I>[] : P extends {
|
|
1608
|
+
type: "array";
|
|
1609
|
+
} ? unknown[] : any;
|
|
1610
|
+
export interface CaptureOptions {
|
|
1611
|
+
/** Searchable in Sentry. Values are cut to 200 characters. */
|
|
1612
|
+
tags?: Record<string, string | number | boolean | null | undefined>;
|
|
1613
|
+
/** Shown on the event, not searchable. */
|
|
1614
|
+
extra?: Record<string, unknown>;
|
|
1615
|
+
level?: "fatal" | "error" | "warning" | "info";
|
|
1616
|
+
/** The runtime's own reports: thrown out of an action, not caught by the app. */
|
|
1617
|
+
handled?: boolean;
|
|
1618
|
+
/** Defaults to SENTRY_DSN. */
|
|
1619
|
+
dsn?: string;
|
|
1620
|
+
/** Defaults to IB_ENVIRONMENT: development or production. */
|
|
1621
|
+
environment?: string;
|
|
1622
|
+
fetch?: typeof fetch;
|
|
1623
|
+
}
|
|
1624
|
+
/** A DSN's parts, or null when it isn't one: `https://<key>@<host>[/<path>]/<project>`. */
|
|
1625
|
+
export declare function parseDsn(dsn: string): {
|
|
1626
|
+
key: string;
|
|
1627
|
+
envelope: string;
|
|
1628
|
+
} | null;
|
|
1629
|
+
/**
|
|
1630
|
+
* 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
|
|
1631
|
+
* take it. Never throws, and gives up after three seconds.
|
|
1632
|
+
*/
|
|
1633
|
+
export declare function captureException(error: unknown, o?: CaptureOptions): Promise<string | null>;
|
|
1529
1634
|
export interface ShopifyPrivacyCustomer {
|
|
1530
1635
|
id: number;
|
|
1531
1636
|
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;
|
|
@@ -141,27 +143,41 @@ export function createClient(o = {}) {
|
|
|
141
143
|
const f = o.fetch ?? fetch;
|
|
142
144
|
const base = `${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}`;
|
|
143
145
|
// The scope only narrows what the token may do; Inference Bureau applies it (and refuses a malformed one).
|
|
146
|
+
const role = Array.isArray(o.role) ? o.role.join(",") : o.role;
|
|
144
147
|
const scope = {
|
|
145
|
-
...(o.shop ? { "x-ib-shop": o.shop } : {}), ...(
|
|
146
|
-
...(
|
|
148
|
+
...(o.shop ? { "x-ib-shop": o.shop } : {}), ...(role ? { "x-ib-role": role } : {}),
|
|
149
|
+
...(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 } : {}), ...(o.session.accountId ? { accountId: o.session.accountId } : {}) }) } : {}),
|
|
147
150
|
};
|
|
148
|
-
/**
|
|
151
|
+
/**
|
|
152
|
+
* A call with a JSON body (or none); `raw` sends bytes as they are, with their type when known. A call turned away
|
|
153
|
+
* before it did anything is tried again, up to CALL_RETRIES times after Retry-After: the environment's calls all
|
|
154
|
+
* running (429 concurrency_limit_exceeded), or, for a read, the database's connections busy (503 reason busy).
|
|
155
|
+
*/
|
|
149
156
|
async function call(method, path, body, raw) {
|
|
150
|
-
const
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
json =
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
157
|
+
const read = method === "GET" || /\/records\/(query|aggregate)$/.test(path);
|
|
158
|
+
for (let tries = 0;; tries++) {
|
|
159
|
+
const res = await f(`${base}${path}`, {
|
|
160
|
+
method, headers: { authorization: `Bearer ${token}`, ...scope, ...(raw ? (raw.type ? { "content-type": raw.type } : {}) : body === undefined ? {} : { "content-type": "application/json" }) },
|
|
161
|
+
...(raw ? { body: raw.body } : body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
162
|
+
});
|
|
163
|
+
if (res.status === 204)
|
|
164
|
+
return undefined;
|
|
165
|
+
const text = await res.text();
|
|
166
|
+
let json = {};
|
|
167
|
+
try {
|
|
168
|
+
json = text ? JSON.parse(text) : {};
|
|
169
|
+
}
|
|
170
|
+
catch { /* reported below */ }
|
|
171
|
+
if (res.ok)
|
|
172
|
+
return json;
|
|
173
|
+
const turnedAway = (res.status === 429 && json.error?.code === "concurrency_limit_exceeded") || (read && res.status === 503 && json.error?.reason === "busy");
|
|
174
|
+
if (turnedAway && tries < CALL_RETRIES) {
|
|
175
|
+
const after = Math.min(5, Number(res.headers.get("retry-after")) || 1);
|
|
176
|
+
await new Promise((done) => setTimeout(done, after * 1000 * (0.75 + Math.random() * 0.5)));
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
163
179
|
throw new ApiError(json.error?.message ?? `The API answered ${res.status}.`, res.status, json.error?.code ?? null, json.error?.problems ?? []);
|
|
164
|
-
|
|
180
|
+
}
|
|
165
181
|
}
|
|
166
182
|
const model = (name) => {
|
|
167
183
|
const m = `/models/${encodeURIComponent(name)}`;
|
|
@@ -336,6 +352,13 @@ export async function serveRecords(request, api, o = {}) {
|
|
|
336
352
|
return errorBody(403, "forbidden", `This route doesn't run ${String(body.action)}.`);
|
|
337
353
|
return Response.json(await api.$global(body.action, obj(body.params)));
|
|
338
354
|
}
|
|
355
|
+
if (body.op === "enqueue") {
|
|
356
|
+
if (!str(body.action) || !(o.enqueueActions ?? []).includes(body.action))
|
|
357
|
+
return errorBody(403, "forbidden", `This route doesn't queue ${String(body.action)}.`);
|
|
358
|
+
// The store is the request's own (its api is already that store's), never one the browser names.
|
|
359
|
+
const { shop: _, ...options } = obj(body.options);
|
|
360
|
+
return Response.json(await api.enqueue(body.action, obj(body.params), options));
|
|
361
|
+
}
|
|
339
362
|
// A live query's watch: which of its models changed, waiting for one to (#125).
|
|
340
363
|
if (body.op === "changes") {
|
|
341
364
|
const names = Array.isArray(body.models) ? body.models : [];
|
|
@@ -819,3 +842,75 @@ export async function verifyCustomerRequest(request, o = {}) {
|
|
|
819
842
|
source: proxied.pathPrefix === "/extension" ? "extension" : "proxy", api,
|
|
820
843
|
};
|
|
821
844
|
}
|
|
845
|
+
/** A DSN's parts, or null when it isn't one: `https://<key>@<host>[/<path>]/<project>`. */
|
|
846
|
+
export function parseDsn(dsn) {
|
|
847
|
+
let u;
|
|
848
|
+
try {
|
|
849
|
+
u = new URL(dsn.trim());
|
|
850
|
+
}
|
|
851
|
+
catch {
|
|
852
|
+
return null;
|
|
853
|
+
}
|
|
854
|
+
const m = /^(.*)\/(\d+)\/?$/.exec(u.pathname);
|
|
855
|
+
if (!u.username || !m || (u.protocol !== "https:" && u.protocol !== "http:"))
|
|
856
|
+
return null;
|
|
857
|
+
return { key: decodeURIComponent(u.username), envelope: `${u.protocol}//${u.host}${m[1]}/api/${m[2]}/envelope/` };
|
|
858
|
+
}
|
|
859
|
+
const FRAME = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?$/;
|
|
860
|
+
/** A V8 stack's frames as Sentry wants them: the outermost call first. Ours and dependencies' aren't the app's code. */
|
|
861
|
+
function stackFrames(stack) {
|
|
862
|
+
const frames = [];
|
|
863
|
+
for (const line of (stack ?? "").split("\n").slice(1, 51)) {
|
|
864
|
+
const m = FRAME.exec(line);
|
|
865
|
+
if (!m)
|
|
866
|
+
continue;
|
|
867
|
+
const filename = m[2].replace(/^file:\/\//, "");
|
|
868
|
+
const inApp = !/node_modules|^node:|^internal\/|\/ib\/sdk\//.test(filename);
|
|
869
|
+
frames.push({ function: m[1] ?? "?", filename, lineno: Number(m[3]), colno: Number(m[4]), in_app: inApp });
|
|
870
|
+
}
|
|
871
|
+
return frames.reverse();
|
|
872
|
+
}
|
|
873
|
+
/** The error and what caused it, the deepest cause first, as Sentry orders an exception chain. */
|
|
874
|
+
function exceptionChain(error, handled) {
|
|
875
|
+
const out = [];
|
|
876
|
+
let e = error;
|
|
877
|
+
for (let i = 0; i < 5 && e != null; i++) {
|
|
878
|
+
const err = e instanceof Error ? e : new Error(typeof e === "string" ? e : JSON.stringify(e));
|
|
879
|
+
out.unshift({ type: err.name || "Error", value: err.message.slice(0, 8000), stacktrace: { frames: stackFrames(err.stack) }, ...(i === 0 ? { mechanism: { type: "inferencebureau", handled } } : {}) });
|
|
880
|
+
e = err.cause;
|
|
881
|
+
}
|
|
882
|
+
return out;
|
|
883
|
+
}
|
|
884
|
+
/**
|
|
885
|
+
* 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
|
|
886
|
+
* take it. Never throws, and gives up after three seconds.
|
|
887
|
+
*/
|
|
888
|
+
export async function captureException(error, o = {}) {
|
|
889
|
+
const dsn = parseDsn(o.dsn ?? envVar("SENTRY_DSN") ?? "");
|
|
890
|
+
if (!dsn)
|
|
891
|
+
return null;
|
|
892
|
+
try {
|
|
893
|
+
const id = crypto.randomUUID().replace(/-/g, "");
|
|
894
|
+
const app = envVar("IB_APP");
|
|
895
|
+
const version = envVar("IB_FILE_VERSION");
|
|
896
|
+
const tags = Object.fromEntries(Object.entries({ ...(app ? { app } : {}), ...o.tags }).filter(([, v]) => v != null && v !== "").map(([k, v]) => [k, String(v).slice(0, 200)]));
|
|
897
|
+
const event = {
|
|
898
|
+
event_id: id, timestamp: Date.now() / 1000, platform: "node", level: o.level ?? "error",
|
|
899
|
+
environment: o.environment ?? envVar("IB_ENVIRONMENT") ?? "production",
|
|
900
|
+
...(app && version ? { release: `${app}@${version}` } : {}),
|
|
901
|
+
tags, ...(o.extra ? { extra: o.extra } : {}),
|
|
902
|
+
exception: { values: exceptionChain(error, o.handled ?? true) },
|
|
903
|
+
sdk: { name: "inferencebureau.apps-sdk", version: "1" },
|
|
904
|
+
};
|
|
905
|
+
const body = `${JSON.stringify({ event_id: id, sent_at: new Date().toISOString() })}\n${JSON.stringify({ type: "event" })}\n${JSON.stringify(event)}\n`;
|
|
906
|
+
const res = await (o.fetch ?? fetch)(dsn.envelope, {
|
|
907
|
+
method: "POST", body,
|
|
908
|
+
headers: { "content-type": "application/x-sentry-envelope", "x-sentry-auth": `Sentry sentry_version=7, sentry_client=inferencebureau.apps-sdk/1, sentry_key=${dsn.key}` },
|
|
909
|
+
...(typeof AbortSignal.timeout === "function" ? { signal: AbortSignal.timeout(3000) } : {}),
|
|
910
|
+
});
|
|
911
|
+
return res.ok ? id : null;
|
|
912
|
+
}
|
|
913
|
+
catch {
|
|
914
|
+
return null;
|
|
915
|
+
}
|
|
916
|
+
}
|
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
|
}
|
|
@@ -1821,12 +1823,14 @@ function syncItem(model, o, shop) {
|
|
|
1821
1823
|
const fields = Array.isArray(o.fields) ? Object.fromEntries(o.fields.map((x) => [x.key, x.value])) : isObj(o.fields) ? o.fields : {};
|
|
1822
1824
|
return { model, shopifyId: id, updatedAt, values: { sh_id: id, sh_shop: shop, sh_type: str(o.type), sh_handle: str(o.handle), sh_display_name: str(o.display_name), sh_fields: fields, sh_updated_at: updatedAt } };
|
|
1823
1825
|
}
|
|
1824
|
-
const FULL_ACCESS = { shop: null, role: null, session: { userId: null, customerId: null, customerRecordId: null } };
|
|
1826
|
+
const FULL_ACCESS = { shop: null, role: null, session: { userId: null, customerId: null, customerRecordId: null, accountId: null } };
|
|
1827
|
+
/** The roles a scope is held to: `role` holds several comma-separated, as the API's x-ib-role does. */
|
|
1828
|
+
const rolesOf = (s) => (s.role ? s.role.split(",") : []);
|
|
1825
1829
|
const isScoped = (s) => !!s.shop || !!s.role;
|
|
1826
1830
|
const CUSTOMER_ROLE = "storefront-customers";
|
|
1827
1831
|
const PERMISSIONS_PATH = "accessControl/permissions.ib.ts";
|
|
1828
1832
|
const ROLE = /^[a-z][a-z0-9-]{0,63}$/;
|
|
1829
|
-
const sessionOf = (s = {}) => ({ userId: s.userId ?? null, customerId: s.customerId ?? null, customerRecordId: s.customerRecordId ?? null });
|
|
1833
|
+
const sessionOf = (s = {}) => ({ userId: s.userId ?? null, customerId: s.customerId ?? null, customerRecordId: s.customerRecordId ?? null, accountId: s.accountId ?? null });
|
|
1830
1834
|
const denied = (message) => new ApiError(message, 403, "policy_denied");
|
|
1831
1835
|
/** The field holding a record's store, or null when the model isn't store-owned. */
|
|
1832
1836
|
function storeField(m) {
|
|
@@ -1860,7 +1864,7 @@ const customerGid = (id) => (id.startsWith("gid://") ? id : `gid://shopify/Custo
|
|
|
1860
1864
|
/** A condition no record meets. */
|
|
1861
1865
|
const NOTHING = { id: { in: [] } };
|
|
1862
1866
|
function customerFilter(m, scope) {
|
|
1863
|
-
if (scope.
|
|
1867
|
+
if (!rolesOf(scope).includes(CUSTOMER_ROLE))
|
|
1864
1868
|
return undefined;
|
|
1865
1869
|
const f = customerField(m);
|
|
1866
1870
|
if (!f)
|
|
@@ -1920,7 +1924,7 @@ function fillValue(v, scope, missing) {
|
|
|
1920
1924
|
const keys = Object.keys(v);
|
|
1921
1925
|
if (keys.length === 1 && keys[0] === "$session") {
|
|
1922
1926
|
const name = v.$session;
|
|
1923
|
-
const value = name === "shop" ? scope.shop : name === "userId" || name === "customerId" || name === "customerRecordId" ? scope.session[name] : null;
|
|
1927
|
+
const value = name === "shop" ? scope.shop : name === "userId" || name === "customerId" || name === "customerRecordId" || name === "accountId" ? scope.session[name] : null;
|
|
1924
1928
|
if (value === null || value === undefined)
|
|
1925
1929
|
missing();
|
|
1926
1930
|
return value ?? null;
|
|
@@ -1945,19 +1949,28 @@ function fill(f, scope) {
|
|
|
1945
1949
|
function roleFilter(perms, scope, model, op, what) {
|
|
1946
1950
|
if (!scope.role)
|
|
1947
1951
|
return {};
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1952
|
+
// Several roles are held to the union of their grants: everything when any grants it outright, else the OR of their filters.
|
|
1953
|
+
const filters = [];
|
|
1954
|
+
const roles = rolesOf(scope);
|
|
1955
|
+
for (const role of roles) {
|
|
1956
|
+
const r = perms.roles.get(role);
|
|
1957
|
+
let g;
|
|
1958
|
+
if (r) {
|
|
1959
|
+
if (model === null)
|
|
1960
|
+
g = "action" in op && r.globalActions[op.action] === true;
|
|
1961
|
+
else {
|
|
1962
|
+
const m = r.models[model];
|
|
1963
|
+
g = "read" in op ? (m?.read ?? r.default.read) : (m?.actions[op.action] ?? r.default.action);
|
|
1964
|
+
}
|
|
1956
1965
|
}
|
|
1966
|
+
if (g === true)
|
|
1967
|
+
return {};
|
|
1968
|
+
if (g)
|
|
1969
|
+
filters.push(fill(g.filter, scope));
|
|
1957
1970
|
}
|
|
1958
|
-
if (!
|
|
1959
|
-
throw denied(`The ${
|
|
1960
|
-
return
|
|
1971
|
+
if (!filters.length)
|
|
1972
|
+
throw denied(`The ${roles.join(", ")} role${roles.length === 1 ? "" : "s"} can't ${what}.${perms.problem ? ` (${perms.problem})` : ` Grant it in ${PERMISSIONS_PATH}.`}`);
|
|
1973
|
+
return filters.length === 1 ? filters[0] : { OR: filters };
|
|
1961
1974
|
}
|
|
1962
1975
|
const combine = (...fs) => {
|
|
1963
1976
|
const list = fs.filter((f) => !!f && Object.keys(f).length > 0);
|
|
@@ -1988,7 +2001,7 @@ function scopedValues(scope, m, values) {
|
|
|
1988
2001
|
throw denied(`This call is for ${scope.shop}; it can't write ${m.name} records of another store.`);
|
|
1989
2002
|
out = { ...out, [f]: scope.shop };
|
|
1990
2003
|
}
|
|
1991
|
-
const c = scope.
|
|
2004
|
+
const c = rolesOf(scope).includes(CUSTOMER_ROLE) ? customerField(m) : null;
|
|
1992
2005
|
if (c && c.field !== "id") {
|
|
1993
2006
|
const mine = c.by === "record" ? scope.session.customerRecordId : scope.session.customerId ? customerGid(scope.session.customerId) : null;
|
|
1994
2007
|
if (!mine)
|
|
@@ -2002,7 +2015,7 @@ function scopedValues(scope, m, values) {
|
|
|
2002
2015
|
/** An update's values: the store field may stay as it is, never become another store, and a customer's record stays theirs. */
|
|
2003
2016
|
function scopedUpdate(scope, m, values) {
|
|
2004
2017
|
const f = scope.shop ? storeField(m) : null;
|
|
2005
|
-
const c = scope.
|
|
2018
|
+
const c = rolesOf(scope).includes(CUSTOMER_ROLE) ? customerField(m)?.field : null;
|
|
2006
2019
|
if (!(f && f in values) && !(c && c !== "id" && c in values))
|
|
2007
2020
|
return values;
|
|
2008
2021
|
return scopedValues(scope, m, values);
|
|
@@ -2341,7 +2354,7 @@ export function createTestApp(o = {}) {
|
|
|
2341
2354
|
});
|
|
2342
2355
|
const req = { phase: p, model, action, params, record: rec, isNew, environment, shop, caller: how.caller ?? null, ...(how.background ? { background: true } : {}) };
|
|
2343
2356
|
try {
|
|
2344
|
-
return await Promise.race([runPhase(wire(req), registry, { api, shopify: shopify.client, ai: ai.client(), echo: o.echo ?? false }), late]);
|
|
2357
|
+
return await Promise.race([runPhase(wire(req), registry, { api, shopify: shopify.client, ai: ai.client(), echo: o.echo ?? false, sentry: false }), late]);
|
|
2345
2358
|
}
|
|
2346
2359
|
finally {
|
|
2347
2360
|
clearTimeout(timer);
|
|
@@ -2373,7 +2386,7 @@ export function createTestApp(o = {}) {
|
|
|
2373
2386
|
const m = store.model(w.model);
|
|
2374
2387
|
// A run about one store writes that store's records of a store-owned model, as through the API.
|
|
2375
2388
|
const f = shop ? storeField(m) : null;
|
|
2376
|
-
const own = { shop, role: null, session: { userId: null, customerId: null, customerRecordId: null } };
|
|
2389
|
+
const own = { shop, role: null, session: { userId: null, customerId: null, customerRecordId: null, accountId: null } };
|
|
2377
2390
|
if (w.op !== "create" && f && !(await findVisible(m.name, w.id, { [f]: { equals: shop } })))
|
|
2378
2391
|
throw notFound(`There's no ${m.name} with id ${w.id}.`);
|
|
2379
2392
|
if (w.op === "delete")
|
|
@@ -2615,9 +2628,10 @@ export function createTestApp(o = {}) {
|
|
|
2615
2628
|
const apis = new Map();
|
|
2616
2629
|
/** A role's name as the API takes it; a malformed one is refused, never ignored (ignoring it would widen the call). */
|
|
2617
2630
|
const roleOf = (role) => {
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
|
|
2631
|
+
const names = [...new Set((Array.isArray(role) ? role : role.split(",")).map((r) => r.trim()).filter(Boolean))];
|
|
2632
|
+
if (!names.length || names.some((r) => !ROLE.test(r)))
|
|
2633
|
+
throw new ApiError("x-ib-role must be a role's name, or several separated by commas.", 400, "invalid_request");
|
|
2634
|
+
return names.join(",");
|
|
2621
2635
|
};
|
|
2622
2636
|
/** The API for a scope: every store or one (`forShop`), as the environment or held to a role (`asRole`). */
|
|
2623
2637
|
const apiFor = (scope) => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inferencebureau/apps-sdk",
|
|
3
|
-
"version": "0.15.
|
|
3
|
+
"version": "0.15.2",
|
|
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
|
},
|