@inferencebureau/apps-sdk 0.12.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -2
- package/dist/auto.d.ts +113 -0
- package/dist/auto.js +197 -0
- package/dist/index.d.ts +127 -0
- package/dist/index.js +113 -0
- package/dist/polaris.d.ts +30 -0
- package/dist/polaris.js +104 -0
- package/dist/react.d.ts +242 -0
- package/dist/react.js +488 -0
- package/dist/test.js +33 -3
- package/package.json +25 -2
package/README.md
CHANGED
|
@@ -2,8 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
What an Inference Bureau app's code imports: types for the metadata files (`schema.ib.ts`, `permissions.ib.ts`,
|
|
4
4
|
`settings.ib.ts`), the helpers an action's `run` uses (`applyParams`, `save`, `deleteRecord`), the records API client,
|
|
5
|
-
request checks for Shopify session tokens and app proxies, and a harness for testing actions.
|
|
6
|
-
now.
|
|
5
|
+
request checks for Shopify session tokens and app proxies, and a harness for testing actions.
|
|
7
6
|
|
|
8
7
|
```sh
|
|
9
8
|
npm install @inferencebureau/apps-sdk
|
package/dist/auto.d.ts
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What AutoTable and AutoForm work out from a model's description (ModelDescription), with no React and no look:
|
|
3
|
+
* which fields are columns and which are inputs, how a value reads in a cell, and how a form's typed text becomes a
|
|
4
|
+
* record's value. Both renderers (react.tsx's plain one, polaris.tsx's) draw the same answers.
|
|
5
|
+
*/
|
|
6
|
+
import type { AppRecord, FieldDescription, ModelDescription, SortDirection } from "./index.js";
|
|
7
|
+
/** "emailVerified" → "Email verified", "shopifyId" → "Shopify ID". */
|
|
8
|
+
export declare function labelOf(name: string): string;
|
|
9
|
+
/** What a record is called where it's shown in a cell or a picker: its title, name, email and so on, else its id. */
|
|
10
|
+
export declare function recordLabel(record: Record<string, unknown> | null | undefined): string;
|
|
11
|
+
export interface Column {
|
|
12
|
+
field: FieldDescription;
|
|
13
|
+
name: string;
|
|
14
|
+
label: string;
|
|
15
|
+
sortable: boolean;
|
|
16
|
+
/** Right-aligned with tabular figures. */
|
|
17
|
+
numeric: boolean;
|
|
18
|
+
}
|
|
19
|
+
/** A column the app names: the field, or the field with its own heading. */
|
|
20
|
+
export type ColumnOption = string | {
|
|
21
|
+
field: string;
|
|
22
|
+
label: string;
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* A table's columns: the ones named, in order, else the first six fields that read well in a cell (no long text,
|
|
26
|
+
* json, secrets or relationship lists), then when each record was last changed.
|
|
27
|
+
*/
|
|
28
|
+
export declare function columnsOf(d: ModelDescription, named?: ColumnOption[]): Column[];
|
|
29
|
+
/** What a read selects for these columns: each field, and a belongsTo's whole record so it can be named. */
|
|
30
|
+
export declare function selectFor(columns: Column[]): Record<string, unknown>;
|
|
31
|
+
export type Tone = "neutral" | "success" | "info" | "warning" | "critical";
|
|
32
|
+
/** One cell, as both renderers draw it. */
|
|
33
|
+
export type Display = {
|
|
34
|
+
kind: "empty";
|
|
35
|
+
} | {
|
|
36
|
+
kind: "text";
|
|
37
|
+
text: string;
|
|
38
|
+
mono?: boolean;
|
|
39
|
+
} | {
|
|
40
|
+
kind: "boolean";
|
|
41
|
+
value: boolean;
|
|
42
|
+
text: string;
|
|
43
|
+
} | {
|
|
44
|
+
kind: "tags";
|
|
45
|
+
tags: string[];
|
|
46
|
+
} | {
|
|
47
|
+
kind: "link";
|
|
48
|
+
href: string;
|
|
49
|
+
text: string;
|
|
50
|
+
} | {
|
|
51
|
+
kind: "color";
|
|
52
|
+
color: string;
|
|
53
|
+
} | {
|
|
54
|
+
kind: "file";
|
|
55
|
+
text: string;
|
|
56
|
+
href: string | null;
|
|
57
|
+
image: string | null;
|
|
58
|
+
};
|
|
59
|
+
export declare function formatDate(iso: string): string;
|
|
60
|
+
/** How a field's value reads in a cell. */
|
|
61
|
+
export declare function display(f: FieldDescription, value: unknown): Display;
|
|
62
|
+
/** A sort a list can be put in, worded for its field's type. */
|
|
63
|
+
export interface SortOption {
|
|
64
|
+
value: string;
|
|
65
|
+
label: string;
|
|
66
|
+
field: string | null;
|
|
67
|
+
direction: SortDirection;
|
|
68
|
+
}
|
|
69
|
+
/** The sorts a table offers: newest first (the API's own order), then each sortable column both ways. */
|
|
70
|
+
export declare function sortOptions(columns: Column[]): SortOption[];
|
|
71
|
+
/** Which control a field's input is. */
|
|
72
|
+
export type InputKind = "text" | "textarea" | "email" | "url" | "color" | "number" | "password" | "dateTime" | "boolean" | "select" | "multiselect" | "list" | "json" | "file" | "record";
|
|
73
|
+
/** What a form keeps for a field while it's being typed in. */
|
|
74
|
+
export type FormValue = string | boolean | string[] | File | null;
|
|
75
|
+
export interface FormFieldSpec {
|
|
76
|
+
field: FieldDescription;
|
|
77
|
+
name: string;
|
|
78
|
+
label: string;
|
|
79
|
+
kind: InputKind;
|
|
80
|
+
required: boolean;
|
|
81
|
+
options: string[];
|
|
82
|
+
/** A belongsTo's model, whose records the picker lists. */
|
|
83
|
+
parent: string | null;
|
|
84
|
+
}
|
|
85
|
+
export declare function inputKind(f: FieldDescription): InputKind | null;
|
|
86
|
+
/** A field a form takes, the app may name it or label it its own way. */
|
|
87
|
+
export type FieldOption = string | {
|
|
88
|
+
field: string;
|
|
89
|
+
label: string;
|
|
90
|
+
};
|
|
91
|
+
/** A form's fields: the ones named, else every field a value can be written to except secrets' hashes and vectors. */
|
|
92
|
+
export declare function formFieldsOf(d: ModelDescription, named?: FieldOption[], exclude?: string[]): FormFieldSpec[];
|
|
93
|
+
/** An ISO time as a local `YYYY-MM-DDTHH:mm`, what a date and time input holds. */
|
|
94
|
+
export declare function toLocalInput(iso: string): string;
|
|
95
|
+
/** What a form starts a field at, from a record's value (or the field's default for a new one). */
|
|
96
|
+
export declare function initialValue(s: FormFieldSpec, value: unknown): FormValue;
|
|
97
|
+
/** A form value as the record's value, or why it can't be one. `undefined` leaves the field out of the write. */
|
|
98
|
+
export declare function toRecordValue(s: FormFieldSpec, v: FormValue): {
|
|
99
|
+
ok: true;
|
|
100
|
+
value: unknown;
|
|
101
|
+
} | {
|
|
102
|
+
ok: false;
|
|
103
|
+
message: string;
|
|
104
|
+
};
|
|
105
|
+
/** Whether a form value is still what it started as. */
|
|
106
|
+
export declare function unchanged(a: FormValue, b: FormValue): boolean;
|
|
107
|
+
/** The field a refusal's problem is about: `rating` for `rating`, and for `address.city`. */
|
|
108
|
+
export declare const problemField: (field: string) => string;
|
|
109
|
+
/** Records as their id and name, for a belongsTo picker. */
|
|
110
|
+
export declare const choicesOf: (records: AppRecord[]) => {
|
|
111
|
+
value: string;
|
|
112
|
+
label: string;
|
|
113
|
+
}[];
|
package/dist/auto.js
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/** "emailVerified" → "Email verified", "shopifyId" → "Shopify ID". */
|
|
2
|
+
export function labelOf(name) {
|
|
3
|
+
const words = name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").replace(/[_-]+/g, " ").trim().split(/\s+/);
|
|
4
|
+
const out = words.map((w, i) => {
|
|
5
|
+
const lower = w.toLowerCase();
|
|
6
|
+
if (lower === "id" || lower === "url" || lower === "sku" || lower === "gid")
|
|
7
|
+
return lower.toUpperCase();
|
|
8
|
+
return i === 0 ? lower.charAt(0).toUpperCase() + lower.slice(1) : lower;
|
|
9
|
+
});
|
|
10
|
+
return out.join(" ");
|
|
11
|
+
}
|
|
12
|
+
const NAMING = ["title", "name", "displayName", "label", "email", "handle", "sku", "subject", "myshopifyDomain"];
|
|
13
|
+
/** What a record is called where it's shown in a cell or a picker: its title, name, email and so on, else its id. */
|
|
14
|
+
export function recordLabel(record) {
|
|
15
|
+
if (!record)
|
|
16
|
+
return "";
|
|
17
|
+
for (const k of NAMING) {
|
|
18
|
+
const v = record[k];
|
|
19
|
+
if (typeof v === "string" && v.trim())
|
|
20
|
+
return v;
|
|
21
|
+
}
|
|
22
|
+
const first = ["firstName", "lastName"].map((k) => record[k]).filter((v) => typeof v === "string" && v).join(" ");
|
|
23
|
+
return first || String(record.id ?? "");
|
|
24
|
+
}
|
|
25
|
+
/** Fields no list or form shows unless named: secrets, and the hashes and tokens that stand in for them. */
|
|
26
|
+
const HIDDEN = /(hash|token|secret)$/i;
|
|
27
|
+
const COLUMN_TYPES = new Set(["string", "email", "url", "color", "number", "dateTime", "enum", "boolean", "belongsTo", "file", "computed", "roleList"]);
|
|
28
|
+
const SORTABLE_TYPES = new Set(["string", "email", "url", "color", "number", "dateTime", "enum", "boolean", "computed"]);
|
|
29
|
+
const MAX_COLUMNS = 6;
|
|
30
|
+
const isNumeric = (f) => f.type === "number" || (f.type === "computed" && f.valueType === "number");
|
|
31
|
+
const column = (f, label) => ({
|
|
32
|
+
field: f, name: f.name, label: label ?? labelOf(f.name),
|
|
33
|
+
sortable: SORTABLE_TYPES.has(f.type) && !(f.type === "enum" && f.allowMultiple) && !(f.type === "computed" && !f.valueType),
|
|
34
|
+
numeric: isNumeric(f),
|
|
35
|
+
});
|
|
36
|
+
/**
|
|
37
|
+
* A table's columns: the ones named, in order, else the first six fields that read well in a cell (no long text,
|
|
38
|
+
* json, secrets or relationship lists), then when each record was last changed.
|
|
39
|
+
*/
|
|
40
|
+
export function columnsOf(d, named) {
|
|
41
|
+
const byName = new Map(d.fields.map((f) => [f.name, f]));
|
|
42
|
+
if (named?.length) {
|
|
43
|
+
return named.flatMap((c) => {
|
|
44
|
+
const name = typeof c === "string" ? c : c.field;
|
|
45
|
+
const f = byName.get(name);
|
|
46
|
+
return f ? [column(f, typeof c === "string" ? undefined : c.label)] : [];
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
const picked = d.fields.filter((f) => !f.system && COLUMN_TYPES.has(f.type) && !HIDDEN.test(f.name)).slice(0, MAX_COLUMNS).map((f) => column(f));
|
|
50
|
+
const updated = byName.get("updatedAt");
|
|
51
|
+
return updated ? [...picked, column(updated, "Updated")] : picked;
|
|
52
|
+
}
|
|
53
|
+
/** What a read selects for these columns: each field, and a belongsTo's whole record so it can be named. */
|
|
54
|
+
export function selectFor(columns) {
|
|
55
|
+
return Object.fromEntries(columns.map((c) => [c.name, true]));
|
|
56
|
+
}
|
|
57
|
+
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
58
|
+
export function formatDate(iso) {
|
|
59
|
+
const d = new Date(iso);
|
|
60
|
+
if (Number.isNaN(d.getTime()))
|
|
61
|
+
return iso;
|
|
62
|
+
return d.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" });
|
|
63
|
+
}
|
|
64
|
+
const truncate = (s, n = 80) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
|
|
65
|
+
/** How a field's value reads in a cell. */
|
|
66
|
+
export function display(f, value) {
|
|
67
|
+
if (value === null || value === undefined || value === "")
|
|
68
|
+
return { kind: "empty" };
|
|
69
|
+
const type = f.type === "computed" ? (f.valueType ?? "string") : f.type;
|
|
70
|
+
switch (type) {
|
|
71
|
+
case "boolean": return { kind: "boolean", value: value === true, text: value === true ? "Yes" : "No" };
|
|
72
|
+
case "dateTime": return { kind: "text", text: formatDate(String(value)) };
|
|
73
|
+
case "number": return { kind: "text", text: typeof value === "number" ? value.toLocaleString() : String(value) };
|
|
74
|
+
case "enum":
|
|
75
|
+
case "roleList": return { kind: "tags", tags: (Array.isArray(value) ? value : [value]).map(String) };
|
|
76
|
+
case "url": return { kind: "link", href: String(value), text: truncate(String(value).replace(/^https?:\/\//, ""), 48) };
|
|
77
|
+
case "email": return { kind: "link", href: `mailto:${String(value)}`, text: String(value) };
|
|
78
|
+
case "color": return { kind: "color", color: String(value) };
|
|
79
|
+
case "id": return { kind: "text", text: String(value), mono: true };
|
|
80
|
+
case "file": {
|
|
81
|
+
if (!isObj(value))
|
|
82
|
+
return { kind: "empty" };
|
|
83
|
+
const file = value;
|
|
84
|
+
return { kind: "file", text: file.fileName, href: file.url, image: file.url && /^image\//.test(file.mimeType) ? file.url : null };
|
|
85
|
+
}
|
|
86
|
+
case "belongsTo": return isObj(value) ? { kind: "text", text: recordLabel(value) } : { kind: "text", text: String(value), mono: true };
|
|
87
|
+
case "json": return { kind: "text", text: truncate(JSON.stringify(value)), mono: true };
|
|
88
|
+
default: return { kind: "text", text: truncate(String(value), 120) };
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** The sorts a table offers: newest first (the API's own order), then each sortable column both ways. */
|
|
92
|
+
export function sortOptions(columns) {
|
|
93
|
+
const out = [{ value: "", label: "Newest first", field: null, direction: "Descending" }];
|
|
94
|
+
for (const c of columns) {
|
|
95
|
+
if (!c.sortable || c.name === "updatedAt" || c.name === "createdAt")
|
|
96
|
+
continue;
|
|
97
|
+
const type = c.field.type === "computed" ? c.field.valueType : c.field.type;
|
|
98
|
+
const [up, down] = type === "number" ? ["lowest first", "highest first"] : type === "dateTime" ? ["oldest first", "newest first"] : type === "boolean" ? ["no first", "yes first"] : ["A–Z", "Z–A"];
|
|
99
|
+
out.push({ value: `${c.name}:Ascending`, label: `${c.label}, ${up}`, field: c.name, direction: "Ascending" });
|
|
100
|
+
out.push({ value: `${c.name}:Descending`, label: `${c.label}, ${down}`, field: c.name, direction: "Descending" });
|
|
101
|
+
}
|
|
102
|
+
const updated = columns.find((c) => c.name === "updatedAt");
|
|
103
|
+
if (updated)
|
|
104
|
+
out.push({ value: "updatedAt:Descending", label: "Recently updated", field: "updatedAt", direction: "Descending" });
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
const KIND = {
|
|
108
|
+
string: "text", richText: "textarea", email: "email", url: "url", color: "color", number: "number", password: "password", encryptedString: "password",
|
|
109
|
+
dateTime: "dateTime", boolean: "boolean", roleList: "list", json: "json", file: "file", belongsTo: "record",
|
|
110
|
+
};
|
|
111
|
+
export function inputKind(f) {
|
|
112
|
+
if (f.type === "enum")
|
|
113
|
+
return f.allowMultiple ? "multiselect" : "select";
|
|
114
|
+
return KIND[f.type] ?? null;
|
|
115
|
+
}
|
|
116
|
+
/** A form's fields: the ones named, else every field a value can be written to except secrets' hashes and vectors. */
|
|
117
|
+
export function formFieldsOf(d, named, exclude = []) {
|
|
118
|
+
const byName = new Map(d.fields.map((f) => [f.name, f]));
|
|
119
|
+
const spec = (f, label) => {
|
|
120
|
+
const kind = inputKind(f);
|
|
121
|
+
return kind ? [{ field: f, name: f.name, label: label ?? labelOf(f.name), kind, required: f.required === true, options: f.options ?? [], parent: f.parent ?? null }] : [];
|
|
122
|
+
};
|
|
123
|
+
if (named?.length) {
|
|
124
|
+
return named.flatMap((c) => {
|
|
125
|
+
const f = byName.get(typeof c === "string" ? c : c.field);
|
|
126
|
+
return f ? spec(f, typeof c === "string" ? undefined : c.label) : [];
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
return d.fields.filter((f) => f.writable && !f.system && f.type !== "vector" && !HIDDEN.test(f.name) && !exclude.includes(f.name)).flatMap((f) => spec(f));
|
|
130
|
+
}
|
|
131
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
132
|
+
/** An ISO time as a local `YYYY-MM-DDTHH:mm`, what a date and time input holds. */
|
|
133
|
+
export function toLocalInput(iso) {
|
|
134
|
+
const d = new Date(iso);
|
|
135
|
+
if (Number.isNaN(d.getTime()))
|
|
136
|
+
return "";
|
|
137
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
|
138
|
+
}
|
|
139
|
+
/** What a form starts a field at, from a record's value (or the field's default for a new one). */
|
|
140
|
+
export function initialValue(s, value) {
|
|
141
|
+
switch (s.kind) {
|
|
142
|
+
case "boolean": return value === true;
|
|
143
|
+
case "multiselect": return Array.isArray(value) ? value.map(String) : [];
|
|
144
|
+
case "list": return Array.isArray(value) ? value.map(String).join(", ") : "";
|
|
145
|
+
case "json": return value === null || value === undefined ? "" : JSON.stringify(value, null, 2);
|
|
146
|
+
case "dateTime": return typeof value === "string" ? toLocalInput(value) : "";
|
|
147
|
+
// Never shown again once set; typing one replaces it.
|
|
148
|
+
case "password": return "";
|
|
149
|
+
// A file is kept as it is unless another is chosen.
|
|
150
|
+
case "file": return null;
|
|
151
|
+
case "record": return isObj(value) ? String(value.id ?? "") : value === null || value === undefined ? "" : String(value);
|
|
152
|
+
case "number": return typeof value === "number" ? String(value) : "";
|
|
153
|
+
default: return typeof value === "string" ? value : value === null || value === undefined ? "" : String(value);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/** A form value as the record's value, or why it can't be one. `undefined` leaves the field out of the write. */
|
|
157
|
+
export function toRecordValue(s, v) {
|
|
158
|
+
const blank = v === null || v === "" || (Array.isArray(v) && v.length === 0);
|
|
159
|
+
if (s.required && blank && s.kind !== "boolean" && s.kind !== "password" && s.kind !== "file")
|
|
160
|
+
return { ok: false, message: "Required" };
|
|
161
|
+
if (blank)
|
|
162
|
+
return { ok: true, value: s.kind === "password" || s.kind === "file" ? undefined : s.kind === "multiselect" || s.kind === "list" ? [] : null };
|
|
163
|
+
switch (s.kind) {
|
|
164
|
+
case "boolean": return { ok: true, value: v === true };
|
|
165
|
+
case "number": {
|
|
166
|
+
const n = Number(String(v).replace(/,/g, ""));
|
|
167
|
+
return Number.isFinite(n) ? { ok: true, value: n } : { ok: false, message: "Enter a number" };
|
|
168
|
+
}
|
|
169
|
+
case "dateTime": {
|
|
170
|
+
const d = new Date(String(v));
|
|
171
|
+
return Number.isNaN(d.getTime()) ? { ok: false, message: "Enter a date and time" } : { ok: true, value: d.toISOString() };
|
|
172
|
+
}
|
|
173
|
+
case "json": {
|
|
174
|
+
try {
|
|
175
|
+
return { ok: true, value: JSON.parse(String(v)) };
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
return { ok: false, message: "Enter valid JSON" };
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
case "list": return { ok: true, value: String(v).split(",").map((x) => x.trim()).filter(Boolean) };
|
|
182
|
+
case "multiselect": return { ok: true, value: v };
|
|
183
|
+
// Uploaded by the form before the write; it puts the upload's token here.
|
|
184
|
+
case "file": return { ok: true, value: undefined };
|
|
185
|
+
default: return { ok: true, value: String(v) };
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/** Whether a form value is still what it started as. */
|
|
189
|
+
export function unchanged(a, b) {
|
|
190
|
+
if (Array.isArray(a) && Array.isArray(b))
|
|
191
|
+
return a.length === b.length && a.every((x, i) => x === b[i]);
|
|
192
|
+
return a === b;
|
|
193
|
+
}
|
|
194
|
+
/** The field a refusal's problem is about: `rating` for `rating`, and for `address.city`. */
|
|
195
|
+
export const problemField = (field) => field.split(/[.[]/)[0] ?? field;
|
|
196
|
+
/** Records as their id and name, for a belongsTo picker. */
|
|
197
|
+
export const choicesOf = (records) => records.map((r) => ({ value: r.id, label: recordLabel(r) }));
|
package/dist/index.d.ts
CHANGED
|
@@ -99,10 +99,24 @@ export type ComputedAggregate = ({
|
|
|
99
99
|
}) & {
|
|
100
100
|
filter?: Filter;
|
|
101
101
|
};
|
|
102
|
+
/**
|
|
103
|
+
* An index on a model's records, kept as metadata like the rest of the schema and built in the background after a
|
|
104
|
+
* save or deploy (nothing blocks on it). `{ fields: ["shop", "createdAt"] }` serves equality on its first field with
|
|
105
|
+
* ranges and sorting on the rest; `unique: true` makes the fields' values unique together, checked by the database;
|
|
106
|
+
* `search: true` with fields serves `startsWith` and `contains` on each of them, and alone serves the model's text
|
|
107
|
+
* search. Fields are string, email, url, color, enum (one option), number, boolean, dateTime, belongsTo, or `id`,
|
|
108
|
+
* `createdAt`, `updatedAt`; `search` takes the text types (and rich text).
|
|
109
|
+
*/
|
|
110
|
+
export interface IndexDef {
|
|
111
|
+
fields?: string[];
|
|
112
|
+
unique?: boolean;
|
|
113
|
+
search?: boolean;
|
|
114
|
+
}
|
|
102
115
|
export interface ModelSchema {
|
|
103
116
|
type: "ib/model-schema/v1";
|
|
104
117
|
storageKey?: string;
|
|
105
118
|
fields: Record<string, FieldDef>;
|
|
119
|
+
indexes?: IndexDef[];
|
|
106
120
|
}
|
|
107
121
|
/**
|
|
108
122
|
* `settings.ib.ts`. Keep it a plain object literal: Inference Bureau reads `webhooks` and `schedules` from the file.
|
|
@@ -119,8 +133,15 @@ export interface AppSettings {
|
|
|
119
133
|
shopify?: ShopifyInstallSettings;
|
|
120
134
|
/** Other sites' pages that may call the app's routes from the browser. */
|
|
121
135
|
cors?: CorsSetting;
|
|
136
|
+
/**
|
|
137
|
+
* The integrations the app's code needs set up in Settings · Integrations: Problems warns while production has
|
|
138
|
+
* no credentials for one. Inference Bureau's `ai` client is always on and needs no entry.
|
|
139
|
+
*/
|
|
140
|
+
integrations?: IntegrationSetting[];
|
|
122
141
|
[key: string]: unknown;
|
|
123
142
|
}
|
|
143
|
+
/** `resend`: the app's email through the team's own Resend account, as RESEND_API_KEY and EMAIL_FROM. */
|
|
144
|
+
export type IntegrationSetting = "resend";
|
|
124
145
|
/**
|
|
125
146
|
* Which other sites' pages may call the app's routes from the browser. Inference Bureau answers for the app: it
|
|
126
147
|
* answers preflights itself and puts the CORS headers on every response, including the page shown while a development
|
|
@@ -218,7 +239,13 @@ export interface FindManyOptions<M extends ModelTypes = UntypedModel, S extends
|
|
|
218
239
|
filter?: Filter<M["filter"]>;
|
|
219
240
|
sort?: SortOf<M> | SortOf<M>[];
|
|
220
241
|
first?: number;
|
|
242
|
+
/** The `endCursor` of the page before: the fast way to page on. */
|
|
221
243
|
after?: string | null;
|
|
244
|
+
/**
|
|
245
|
+
* Records to pass over first, after the filter and sort, for a page by number (`skip: (page - 1) * first`) or a
|
|
246
|
+
* library that asks for an offset; at most 10,000, and not with `after`. Cursors are faster for reading every page.
|
|
247
|
+
*/
|
|
248
|
+
skip?: number;
|
|
222
249
|
/** Words to find in the model's text fields: records holding every one (any case, part of a word counts), those holding the whole phrase first unless sorted. */
|
|
223
250
|
search?: string;
|
|
224
251
|
/** Which fields to read, and which related records with them (SelectOf); every field and no related records when left out. */
|
|
@@ -402,6 +429,35 @@ export interface RecordPage<T = AppRecord> {
|
|
|
402
429
|
hasNextPage: boolean;
|
|
403
430
|
endCursor: string | null;
|
|
404
431
|
}
|
|
432
|
+
/**
|
|
433
|
+
* A model as the API describes it (`describe()`): its fields in schema order between `id` and the timestamps, which
|
|
434
|
+
* AutoTable and AutoForm draw from. `writable` fields take a value; `stored` ones filter and sort.
|
|
435
|
+
*/
|
|
436
|
+
export interface ModelDescription {
|
|
437
|
+
name: string;
|
|
438
|
+
fields: FieldDescription[];
|
|
439
|
+
}
|
|
440
|
+
export interface FieldDescription {
|
|
441
|
+
name: string;
|
|
442
|
+
type: FieldType | "id";
|
|
443
|
+
/** id, createdAt and updatedAt. */
|
|
444
|
+
system?: boolean;
|
|
445
|
+
stored?: boolean;
|
|
446
|
+
writable?: boolean;
|
|
447
|
+
required?: boolean;
|
|
448
|
+
options?: string[];
|
|
449
|
+
allowMultiple?: boolean;
|
|
450
|
+
allowPublicAccess?: boolean;
|
|
451
|
+
/** A belongsTo's model. */
|
|
452
|
+
parent?: string;
|
|
453
|
+
/** A hasOne's, hasMany's or hasManyThrough's model. */
|
|
454
|
+
related?: string;
|
|
455
|
+
/** A computed field's value type. */
|
|
456
|
+
valueType?: "string" | "number" | "boolean" | "dateTime" | null;
|
|
457
|
+
default?: unknown;
|
|
458
|
+
}
|
|
459
|
+
/** A schema's description, as the API gives it for a model, for code that has the schema and no API (the test harness). */
|
|
460
|
+
export declare function describeSchema(name: string, schema: ModelSchema): ModelDescription;
|
|
405
461
|
/**
|
|
406
462
|
* A record being worked on in an action: its fields, plus what the action has asked to happen to it. Its fields read
|
|
407
463
|
* as `any`, since one action file doesn't say which model's it is, so they pass to the generated client's typed calls.
|
|
@@ -536,6 +592,8 @@ export interface BulkDeleteResult {
|
|
|
536
592
|
/** The field (or fields) an upsert finds its record by: a stored field with a value in `values`, or `id`. */
|
|
537
593
|
export type UpsertOn<M extends ModelTypes = UntypedModel> = (keyof M["input"] & string) | "id";
|
|
538
594
|
export interface ModelClient<M extends ModelTypes = UntypedModel> {
|
|
595
|
+
/** The model's fields as the API describes them (ModelDescription): what AutoTable and AutoForm draw from. */
|
|
596
|
+
describe(): Promise<ModelDescription>;
|
|
539
597
|
findOne<S extends SelectOf<M> | undefined = undefined>(id: string, o?: {
|
|
540
598
|
select?: S;
|
|
541
599
|
}): Promise<ReadOf<M, S> | null>;
|
|
@@ -758,6 +816,75 @@ export interface ClientOptions {
|
|
|
758
816
|
}
|
|
759
817
|
/** The app's API. In an app's deployment every option comes from its environment variables. */
|
|
760
818
|
export declare function createClient(o?: ClientOptions): Api;
|
|
819
|
+
/** What the browser's records client (`@inferencebureau/apps-sdk/react`) sends the app's records route. */
|
|
820
|
+
export type RecordsRequest = {
|
|
821
|
+
op: "describe";
|
|
822
|
+
model: string;
|
|
823
|
+
} | {
|
|
824
|
+
op: "findMany";
|
|
825
|
+
model: string;
|
|
826
|
+
options?: Omit<FindManyOptions, "select"> & {
|
|
827
|
+
select?: Record<string, unknown>;
|
|
828
|
+
};
|
|
829
|
+
} | {
|
|
830
|
+
op: "findOne";
|
|
831
|
+
model: string;
|
|
832
|
+
id: string;
|
|
833
|
+
select?: Record<string, unknown>;
|
|
834
|
+
} | {
|
|
835
|
+
op: "create";
|
|
836
|
+
model: string;
|
|
837
|
+
values: Record<string, unknown>;
|
|
838
|
+
} | {
|
|
839
|
+
op: "update";
|
|
840
|
+
model: string;
|
|
841
|
+
id: string;
|
|
842
|
+
values: Record<string, unknown>;
|
|
843
|
+
} | {
|
|
844
|
+
op: "delete";
|
|
845
|
+
model: string;
|
|
846
|
+
id: string;
|
|
847
|
+
} | {
|
|
848
|
+
op: "bulkDelete";
|
|
849
|
+
model: string;
|
|
850
|
+
ids: string[];
|
|
851
|
+
} | {
|
|
852
|
+
op: "run";
|
|
853
|
+
model: string;
|
|
854
|
+
action: string;
|
|
855
|
+
id?: string;
|
|
856
|
+
params?: Record<string, unknown>;
|
|
857
|
+
} | {
|
|
858
|
+
op: "createUpload";
|
|
859
|
+
model: string;
|
|
860
|
+
field: string;
|
|
861
|
+
fileName?: string;
|
|
862
|
+
mimeType?: string;
|
|
863
|
+
size?: number;
|
|
864
|
+
} | {
|
|
865
|
+
op: "global";
|
|
866
|
+
action: string;
|
|
867
|
+
params?: Record<string, unknown>;
|
|
868
|
+
};
|
|
869
|
+
export interface ServeRecordsOptions {
|
|
870
|
+
/** The models the route answers for; every model when unset. */
|
|
871
|
+
models?: string[];
|
|
872
|
+
/** The global actions it runs; none when unset. */
|
|
873
|
+
globalActions?: string[];
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* The app's records route, for its pages' own scripts: the hooks and AutoTable/AutoForm in
|
|
877
|
+
* `@inferencebureau/apps-sdk/react` and `/polaris` call it. `api` is whoever the request is from: a Shopify session's
|
|
878
|
+
* (`verifyShopifySession`), or a signed-in user's role (`createClient().asRole(...)`); null answers 401. Every call
|
|
879
|
+
* goes through that api, so permissions.ib.ts decides what a page may read and change, never the browser.
|
|
880
|
+
*
|
|
881
|
+
* // web/app/api/records/route.ts
|
|
882
|
+
* export async function POST(request: Request) {
|
|
883
|
+
* const session = await verifyShopifySession(request);
|
|
884
|
+
* return serveRecords(request, session?.api ?? null);
|
|
885
|
+
* }
|
|
886
|
+
*/
|
|
887
|
+
export declare function serveRecords(request: Request, api: Api | null, o?: ServeRecordsOptions): Promise<Response>;
|
|
761
888
|
/**
|
|
762
889
|
* The Shopify Admin API for one store the app is installed on, through Inference Bureau: the store's token stays
|
|
763
890
|
* with us, and each call is checked against the environment's install.
|
package/dist/index.js
CHANGED
|
@@ -8,6 +8,33 @@
|
|
|
8
8
|
* then calls `onSuccess`. The code uses
|
|
9
9
|
* only fetch and Web Crypto, so it runs on any JavaScript runtime the app is hosted on.
|
|
10
10
|
*/
|
|
11
|
+
const STORED_TYPES = new Set(["string", "richText", "email", "url", "color", "number", "dateTime", "enum", "boolean", "roleList", "json", "belongsTo", "password", "encryptedString", "file"]);
|
|
12
|
+
/** A schema's description, as the API gives it for a model, for code that has the schema and no API (the test harness). */
|
|
13
|
+
export function describeSchema(name, schema) {
|
|
14
|
+
return {
|
|
15
|
+
name,
|
|
16
|
+
fields: [
|
|
17
|
+
{ name: "id", type: "id", system: true },
|
|
18
|
+
...Object.entries(schema.fields).map(([field, def]) => {
|
|
19
|
+
const stored = STORED_TYPES.has(def.type) || def.type === "vector";
|
|
20
|
+
return {
|
|
21
|
+
name: field, type: def.type, stored,
|
|
22
|
+
writable: stored && !(def.type === "vector" && Array.isArray(def.source) && def.source.length > 0),
|
|
23
|
+
required: def.validations?.required === true,
|
|
24
|
+
...(def.type === "enum" ? { options: def.options ?? [], allowMultiple: def.allowMultiple === true } : {}),
|
|
25
|
+
...(def.type === "file" ? { allowPublicAccess: def.allowPublicAccess === true } : {}),
|
|
26
|
+
...(def.type === "belongsTo" && def.parent ? { parent: def.parent.model } : {}),
|
|
27
|
+
...(def.type === "hasOne" && def.child ? { related: def.child.model } : {}),
|
|
28
|
+
...(def.type === "hasMany" && def.children ? { related: def.children.model } : {}),
|
|
29
|
+
...(def.type === "hasManyThrough" && def.children ? { related: def.children.model } : {}),
|
|
30
|
+
...(def.default !== undefined ? { default: def.default } : {}),
|
|
31
|
+
};
|
|
32
|
+
}),
|
|
33
|
+
{ name: "createdAt", type: "dateTime", system: true },
|
|
34
|
+
{ name: "updatedAt", type: "dateTime", system: true },
|
|
35
|
+
],
|
|
36
|
+
};
|
|
37
|
+
}
|
|
11
38
|
/** Shared by every copy of this module that loads, so `save` works whichever copy an action imported. */
|
|
12
39
|
const STATE = Symbol.for("inferencebureau.apps.record");
|
|
13
40
|
/** The order records were saved in, across copies too: they're written in that order. */
|
|
@@ -138,6 +165,8 @@ export function createClient(o = {}) {
|
|
|
138
165
|
const query = (o) => call("POST", `${m}/records/query`, o);
|
|
139
166
|
// Reads answer what `select` picked; the types say so (ReadOf), the wire doesn't.
|
|
140
167
|
return {
|
|
168
|
+
// The API's answer carries the record count too; the description is what's promised.
|
|
169
|
+
describe: async () => { const { name, fields } = await call("GET", m); return { name, fields }; },
|
|
141
170
|
async findOne(id, o = {}) {
|
|
142
171
|
const q = o.select ? `?select=${encodeURIComponent(JSON.stringify(o.select))}` : "";
|
|
143
172
|
try {
|
|
@@ -236,6 +265,90 @@ export function createClient(o = {}) {
|
|
|
236
265
|
},
|
|
237
266
|
});
|
|
238
267
|
}
|
|
268
|
+
const errorBody = (status, code, message, problems = []) => Response.json({ error: { code, message, ...(problems.length ? { problems } : {}) } }, { status });
|
|
269
|
+
/**
|
|
270
|
+
* The app's records route, for its pages' own scripts: the hooks and AutoTable/AutoForm in
|
|
271
|
+
* `@inferencebureau/apps-sdk/react` and `/polaris` call it. `api` is whoever the request is from: a Shopify session's
|
|
272
|
+
* (`verifyShopifySession`), or a signed-in user's role (`createClient().asRole(...)`); null answers 401. Every call
|
|
273
|
+
* goes through that api, so permissions.ib.ts decides what a page may read and change, never the browser.
|
|
274
|
+
*
|
|
275
|
+
* // web/app/api/records/route.ts
|
|
276
|
+
* export async function POST(request: Request) {
|
|
277
|
+
* const session = await verifyShopifySession(request);
|
|
278
|
+
* return serveRecords(request, session?.api ?? null);
|
|
279
|
+
* }
|
|
280
|
+
*/
|
|
281
|
+
export async function serveRecords(request, api, o = {}) {
|
|
282
|
+
if (!api)
|
|
283
|
+
return errorBody(401, "unauthorized", "Sign in to see this.");
|
|
284
|
+
if (request.method !== "POST")
|
|
285
|
+
return errorBody(405, "method_not_allowed", "The records route takes POST.");
|
|
286
|
+
let body;
|
|
287
|
+
try {
|
|
288
|
+
body = (await request.json());
|
|
289
|
+
}
|
|
290
|
+
catch {
|
|
291
|
+
return errorBody(400, "invalid_request", "The body must be JSON.");
|
|
292
|
+
}
|
|
293
|
+
if (!body || typeof body !== "object" || typeof body.op !== "string")
|
|
294
|
+
return errorBody(400, "invalid_request", "The body names no op.");
|
|
295
|
+
const str = (v) => typeof v === "string" && v.length > 0;
|
|
296
|
+
const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {});
|
|
297
|
+
try {
|
|
298
|
+
if (body.op === "global") {
|
|
299
|
+
if (!str(body.action) || !(o.globalActions ?? []).includes(body.action))
|
|
300
|
+
return errorBody(403, "forbidden", `This route doesn't run ${String(body.action)}.`);
|
|
301
|
+
return Response.json(await api.$global(body.action, obj(body.params)));
|
|
302
|
+
}
|
|
303
|
+
if (!str(body.model))
|
|
304
|
+
return errorBody(400, "invalid_request", "The body names no model.");
|
|
305
|
+
if (o.models && !o.models.includes(body.model))
|
|
306
|
+
return errorBody(403, "forbidden", `This route doesn't answer for ${body.model}.`);
|
|
307
|
+
const m = api.$model(body.model);
|
|
308
|
+
const b = body;
|
|
309
|
+
switch (body.op) {
|
|
310
|
+
case "describe": return Response.json(await m.describe());
|
|
311
|
+
case "findMany": return Response.json(await m.findMany(obj(b.options)));
|
|
312
|
+
case "findOne": {
|
|
313
|
+
if (!str(b.id))
|
|
314
|
+
break;
|
|
315
|
+
const record = await m.findOne(b.id, b.select ? { select: obj(b.select) } : {});
|
|
316
|
+
return record ? Response.json(record) : errorBody(404, "not_found", "There's no such record.");
|
|
317
|
+
}
|
|
318
|
+
case "create": return Response.json(await m.create(obj(b.values)));
|
|
319
|
+
case "update":
|
|
320
|
+
if (!str(b.id))
|
|
321
|
+
break;
|
|
322
|
+
return Response.json(await m.update(b.id, obj(b.values)));
|
|
323
|
+
case "delete":
|
|
324
|
+
if (!str(b.id))
|
|
325
|
+
break;
|
|
326
|
+
await m.delete(b.id);
|
|
327
|
+
return Response.json({ deleted: b.id });
|
|
328
|
+
case "bulkDelete":
|
|
329
|
+
if (!Array.isArray(b.ids) || !b.ids.every(str))
|
|
330
|
+
break;
|
|
331
|
+
return Response.json(await m.bulkDelete(b.ids));
|
|
332
|
+
case "run":
|
|
333
|
+
if (!str(b.action))
|
|
334
|
+
break;
|
|
335
|
+
return Response.json(await m.run(b.action, { ...(str(b.id) ? { id: b.id } : {}), params: obj(b.params) }));
|
|
336
|
+
case "createUpload": {
|
|
337
|
+
if (!str(b.field))
|
|
338
|
+
break;
|
|
339
|
+
const up = { ...(str(b.fileName) ? { fileName: b.fileName } : {}), ...(str(b.mimeType) ? { mimeType: b.mimeType } : {}), ...(typeof b.size === "number" ? { size: b.size } : {}) };
|
|
340
|
+
return Response.json(await m.createUpload(b.field, up));
|
|
341
|
+
}
|
|
342
|
+
default: return errorBody(400, "invalid_request", `Unknown op ${String(body.op)}.`);
|
|
343
|
+
}
|
|
344
|
+
return errorBody(400, "invalid_request", `The ${body.op} op is missing what it needs.`);
|
|
345
|
+
}
|
|
346
|
+
catch (e) {
|
|
347
|
+
if (e instanceof ApiError)
|
|
348
|
+
return errorBody(e.status, e.code ?? "error", e.message, e.problems);
|
|
349
|
+
throw e;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
239
352
|
export class ShopifyError extends Error {
|
|
240
353
|
errors;
|
|
241
354
|
constructor(message, errors) {
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Display } from "./auto.js";
|
|
2
|
+
import { type AutoFormField, type AutoFormProps, type AutoTableProps } from "./react.js";
|
|
3
|
+
/** A cell in Polaris: badges for yes/no and choices, links for URLs and emails, a thumbnail for an image. */
|
|
4
|
+
export declare function PolarisCell({ value }: {
|
|
5
|
+
value: Display;
|
|
6
|
+
}): import("react").JSX.Element;
|
|
7
|
+
export interface PolarisAutoTableProps extends AutoTableProps {
|
|
8
|
+
/** The section's heading above the table; none unless given. */
|
|
9
|
+
heading?: string;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* A model's records as the admin's index table: search and sort in its filters, pages, a row opening its record
|
|
13
|
+
* (`rowHref` or `onRowClick`), and bulk delete when `selectable`.
|
|
14
|
+
*/
|
|
15
|
+
export declare function AutoTable({ model, rowHref, onRowClick, emptyText, searchable, heading, ...o }: PolarisAutoTableProps): import("react").JSX.Element;
|
|
16
|
+
/** One field's control in Polaris. */
|
|
17
|
+
export declare function PolarisInput({ field: f }: {
|
|
18
|
+
field: AutoFormField;
|
|
19
|
+
}): import("react").JSX.Element;
|
|
20
|
+
export interface PolarisAutoFormProps extends AutoFormProps {
|
|
21
|
+
/** The section's heading; none unless given. */
|
|
22
|
+
heading?: string;
|
|
23
|
+
/**
|
|
24
|
+
* Shopify's contextual save bar instead of a Save button: App Bridge shows it once a field changes, and its Save
|
|
25
|
+
* and Discard submit and reset the form.
|
|
26
|
+
*/
|
|
27
|
+
saveBar?: boolean;
|
|
28
|
+
}
|
|
29
|
+
/** A form for a model's record in Polaris fields, the API's refusals shown on the fields they're about. */
|
|
30
|
+
export declare function AutoForm({ model, submitLabel, heading, saveBar, ...o }: PolarisAutoFormProps): import("react").JSX.Element;
|