@inferencebureau/apps-sdk 0.2.2 → 0.3.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/dist/index.d.ts +87 -2
- package/dist/index.js +33 -4
- package/dist/runtime.d.ts +2 -0
- package/dist/runtime.js +4 -2
- package/dist/test.d.ts +3 -0
- package/dist/test.js +161 -39
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -37,6 +37,8 @@ export interface FieldDef {
|
|
|
37
37
|
source?: string[];
|
|
38
38
|
embeddingModel?: string;
|
|
39
39
|
dimensions?: number;
|
|
40
|
+
/** File fields: keep the files on a public CDN, read as a plain URL. Otherwise they read through a URL signed for an hour. */
|
|
41
|
+
allowPublicAccess?: boolean;
|
|
40
42
|
parent?: {
|
|
41
43
|
model: string;
|
|
42
44
|
};
|
|
@@ -150,6 +152,37 @@ export declare class ApiError extends Error {
|
|
|
150
152
|
message: string;
|
|
151
153
|
}[]);
|
|
152
154
|
}
|
|
155
|
+
/** A file field's value as a record reads it. `url` is signed for an hour unless the field has `allowPublicAccess`. */
|
|
156
|
+
export interface FileValue {
|
|
157
|
+
url: string | null;
|
|
158
|
+
fileName: string;
|
|
159
|
+
mimeType: string;
|
|
160
|
+
size: number;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* What a write gives a file field: the bytes as base64 (small files), a public https URL to copy, or the token of a
|
|
164
|
+
* direct upload (`createUpload` or `upload`). `null` clears it.
|
|
165
|
+
*/
|
|
166
|
+
export type FileInput = {
|
|
167
|
+
base64: string;
|
|
168
|
+
fileName?: string;
|
|
169
|
+
mimeType?: string;
|
|
170
|
+
} | {
|
|
171
|
+
copyURL: string;
|
|
172
|
+
fileName?: string;
|
|
173
|
+
mimeType?: string;
|
|
174
|
+
} | {
|
|
175
|
+
directUploadToken: string;
|
|
176
|
+
fileName?: string;
|
|
177
|
+
};
|
|
178
|
+
/** A direct upload: PUT the file to `url` with `headers` within the hour, then write `{ directUploadToken: token }` within a day. */
|
|
179
|
+
export interface Upload {
|
|
180
|
+
url: string;
|
|
181
|
+
method: "PUT";
|
|
182
|
+
headers: Record<string, string>;
|
|
183
|
+
token: string;
|
|
184
|
+
expiresAt: string;
|
|
185
|
+
}
|
|
153
186
|
export interface ModelClient {
|
|
154
187
|
findOne(id: string): Promise<AppRecord | null>;
|
|
155
188
|
findMany(o?: FindManyOptions): Promise<RecordPage>;
|
|
@@ -172,6 +205,22 @@ export interface ModelClient {
|
|
|
172
205
|
record: AppRecord | null;
|
|
173
206
|
result?: unknown;
|
|
174
207
|
}>;
|
|
208
|
+
/**
|
|
209
|
+
* A direct upload for a file field, for a browser to PUT a file to (up to 1 GiB) without it passing through the app.
|
|
210
|
+
* Give `size` and the upload takes at most that many bytes.
|
|
211
|
+
*/
|
|
212
|
+
createUpload(field: string, o?: {
|
|
213
|
+
fileName?: string;
|
|
214
|
+
mimeType?: string;
|
|
215
|
+
size?: number;
|
|
216
|
+
}): Promise<Upload>;
|
|
217
|
+
/** Uploads a file for a file field, straight to storage, and answers the value to write to the field. */
|
|
218
|
+
upload(field: string, body: Blob | ArrayBuffer | Uint8Array, o?: {
|
|
219
|
+
fileName?: string;
|
|
220
|
+
mimeType?: string;
|
|
221
|
+
}): Promise<{
|
|
222
|
+
directUploadToken: string;
|
|
223
|
+
}>;
|
|
175
224
|
}
|
|
176
225
|
export type Api = {
|
|
177
226
|
[model: string]: ModelClient;
|
|
@@ -185,7 +234,23 @@ export type Api = {
|
|
|
185
234
|
* `id` for the record). It gets up to five minutes, and is retried when it fails.
|
|
186
235
|
*/
|
|
187
236
|
enqueue(action: string, params?: Record<string, unknown>, options?: EnqueueOptions): Promise<Job>;
|
|
237
|
+
/**
|
|
238
|
+
* The same API for one store: store-owned models (Shopify's, and any with a text field named `shop`) show only that
|
|
239
|
+
* store's records, new ones are made as its, and actions run for it. An action's `api` is already its run's store's.
|
|
240
|
+
*/
|
|
241
|
+
forShop(shop: string): Api;
|
|
242
|
+
/**
|
|
243
|
+
* The same API held to a role in accessControl/permissions.ib.ts: only what the role is granted, through its
|
|
244
|
+
* filters, with `session` standing in for `{ $session: "userId" | "customerId" }`. A Shopify session's and a proxy
|
|
245
|
+
* request's `api` already are.
|
|
246
|
+
*/
|
|
247
|
+
asRole(role: string, session?: CallerSession): Api;
|
|
188
248
|
};
|
|
249
|
+
/** Who a role-scoped call is for, filling `{ $session: … }` in permissions.ib.ts filters. */
|
|
250
|
+
export interface CallerSession {
|
|
251
|
+
userId?: string | null;
|
|
252
|
+
customerId?: string | null;
|
|
253
|
+
}
|
|
189
254
|
export interface EnqueueOptions {
|
|
190
255
|
/** The record a model's action works on. */
|
|
191
256
|
id?: string;
|
|
@@ -221,6 +286,11 @@ export interface ClientOptions {
|
|
|
221
286
|
app?: string;
|
|
222
287
|
environment?: string;
|
|
223
288
|
fetch?: typeof fetch;
|
|
289
|
+
/** Narrows every call to one store (see `Api.forShop`). */
|
|
290
|
+
shop?: string;
|
|
291
|
+
/** Holds every call to a role in permissions.ib.ts (see `Api.asRole`). */
|
|
292
|
+
role?: string;
|
|
293
|
+
session?: CallerSession;
|
|
224
294
|
}
|
|
225
295
|
/** The app's API. In an app's deployment every option comes from its environment variables. */
|
|
226
296
|
export declare function createClient(o?: ClientOptions): Api;
|
|
@@ -238,9 +308,20 @@ export interface ShopifyClient {
|
|
|
238
308
|
export declare class ShopifyError extends Error {
|
|
239
309
|
readonly errors: unknown[];
|
|
240
310
|
constructor(message: string, errors: unknown[]);
|
|
311
|
+
/** Shopify was still throttling the store after Inference Bureau waited and tried again. */
|
|
312
|
+
get throttled(): boolean;
|
|
313
|
+
}
|
|
314
|
+
export interface ShopifyClientOptions extends ClientOptions {
|
|
315
|
+
/**
|
|
316
|
+
* `"background"` for work nobody is waiting on: its calls wait until half the store's GraphQL bucket is free, so
|
|
317
|
+
* the embedded admin's requests keep theirs. Actions run by jobs, webhooks and schedules get it on their own.
|
|
318
|
+
*/
|
|
319
|
+
priority?: "background" | "request";
|
|
320
|
+
/** Throttled calls Inference Bureau tries again before answering (default 5). */
|
|
321
|
+
maxRetries?: number;
|
|
241
322
|
}
|
|
242
323
|
/** The Admin API for `shop`, as the environment (the same options as createClient). */
|
|
243
|
-
export declare function createShopifyClient(shop: string, o?:
|
|
324
|
+
export declare function createShopifyClient(shop: string, o?: ShopifyClientOptions): ShopifyClient;
|
|
244
325
|
export interface Money {
|
|
245
326
|
amount: number | string;
|
|
246
327
|
currencyCode: string;
|
|
@@ -348,6 +429,8 @@ export interface ShopifySession {
|
|
|
348
429
|
preview?: {
|
|
349
430
|
actor: string;
|
|
350
431
|
};
|
|
432
|
+
/** The app's API for this staff member: the store's records only, as the `shopify-app-users` role. */
|
|
433
|
+
api: Api;
|
|
351
434
|
}
|
|
352
435
|
/**
|
|
353
436
|
* The store and staff member behind a request from one of the app's pages in the Shopify admin, or null when it
|
|
@@ -363,6 +446,8 @@ export interface ProxyRequest {
|
|
|
363
446
|
customerId: string | null;
|
|
364
447
|
/** Where the storefront reached the app, e.g. /apps/wholesale. */
|
|
365
448
|
pathPrefix: string;
|
|
449
|
+
/** The app's API for this shopper: the store's records only, as the `storefront-shoppers` role. */
|
|
450
|
+
api: Api;
|
|
366
451
|
}
|
|
367
452
|
/**
|
|
368
453
|
* A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or null for
|
|
@@ -372,7 +457,7 @@ export interface ProxyRequest {
|
|
|
372
457
|
export declare function verifyProxyRequest(request: Request, o?: {
|
|
373
458
|
token?: string;
|
|
374
459
|
now?: () => number;
|
|
375
|
-
}): Promise<ProxyRequest | null>;
|
|
460
|
+
} & Omit<ClientOptions, "token" | "shop" | "role" | "session">): Promise<ProxyRequest | null>;
|
|
376
461
|
export interface LogLine {
|
|
377
462
|
level: "debug" | "info" | "warn" | "error";
|
|
378
463
|
message: string;
|
package/dist/index.js
CHANGED
|
@@ -78,9 +78,14 @@ export function createClient(o = {}) {
|
|
|
78
78
|
const environment = o.environment ?? envVar("IB_ENVIRONMENT") ?? "development";
|
|
79
79
|
const f = o.fetch ?? fetch;
|
|
80
80
|
const base = `${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}`;
|
|
81
|
+
// The scope only narrows what the token may do; Inference Bureau applies it (and refuses a malformed one).
|
|
82
|
+
const scope = {
|
|
83
|
+
...(o.shop ? { "x-ib-shop": o.shop } : {}), ...(o.role ? { "x-ib-role": o.role } : {}),
|
|
84
|
+
...(o.role && o.session ? { "x-ib-session": JSON.stringify({ userId: o.session.userId ?? null, customerId: o.session.customerId ?? null }) } : {}),
|
|
85
|
+
};
|
|
81
86
|
async function call(method, path, body) {
|
|
82
87
|
const res = await f(`${base}${path}`, {
|
|
83
|
-
method, headers: { authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "content-type": "application/json" }) },
|
|
88
|
+
method, headers: { authorization: `Bearer ${token}`, ...scope, ...(body === undefined ? {} : { "content-type": "application/json" }) },
|
|
84
89
|
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
85
90
|
});
|
|
86
91
|
if (res.status === 204)
|
|
@@ -117,17 +122,34 @@ export function createClient(o = {}) {
|
|
|
117
122
|
delete: (id) => call("DELETE", `${m}/records/${encodeURIComponent(id)}`),
|
|
118
123
|
checkPassword: async (id, password, field) => (await call("POST", `${m}/records/${encodeURIComponent(id)}/check-password`, { password, ...(field ? { field } : {}) })).valid,
|
|
119
124
|
run: (action, o = {}) => call("POST", `${m}/actions/${encodeURIComponent(action)}`, { ...(o.id ? { id: o.id } : {}), params: o.params ?? {}, ...(o.shop ? { shop: o.shop } : {}) }),
|
|
125
|
+
createUpload: (field, o = {}) => call("POST", `${m}/uploads`, { field, ...o }),
|
|
126
|
+
async upload(field, body, o = {}) {
|
|
127
|
+
const blob = body instanceof Blob ? body : new Blob([body]);
|
|
128
|
+
const fileName = o.fileName ?? (typeof File !== "undefined" && body instanceof File ? body.name : undefined);
|
|
129
|
+
const mimeType = o.mimeType ?? (blob.type || undefined);
|
|
130
|
+
const up = await call("POST", `${m}/uploads`, { field, size: blob.size, ...(fileName ? { fileName } : {}), ...(mimeType ? { mimeType } : {}) });
|
|
131
|
+
const res = await f(up.url, { method: "PUT", headers: up.headers, body: blob });
|
|
132
|
+
if (!res.ok)
|
|
133
|
+
throw new ApiError(`The upload was refused (${res.status}): ${(await res.text()).slice(0, 300)}`, res.status, "upload_failed");
|
|
134
|
+
return { directUploadToken: up.token };
|
|
135
|
+
},
|
|
120
136
|
};
|
|
121
137
|
};
|
|
122
138
|
const cache = new Map();
|
|
123
139
|
const $global = (action, params = {}) => call("POST", `/actions/${encodeURIComponent(action)}`, { params });
|
|
124
140
|
const enqueue = (action, params = {}, o = {}) => call("POST", "/jobs", { action, params, ...o, ...(o.runAt instanceof Date ? { runAt: o.runAt.toISOString() } : {}) });
|
|
141
|
+
const forShop = (shop) => createClient({ ...o, url, token, app, environment, fetch: f, shop });
|
|
142
|
+
const asRole = (role, session) => createClient({ ...o, url, token, app, environment, fetch: f, role, ...(session ? { session } : {}) });
|
|
125
143
|
return new Proxy({}, {
|
|
126
144
|
get(_t, prop) {
|
|
127
145
|
if (prop === "$global")
|
|
128
146
|
return $global;
|
|
129
147
|
if (prop === "enqueue")
|
|
130
148
|
return enqueue;
|
|
149
|
+
if (prop === "forShop")
|
|
150
|
+
return forShop;
|
|
151
|
+
if (prop === "asRole")
|
|
152
|
+
return asRole;
|
|
131
153
|
if (typeof prop !== "string" || prop === "then")
|
|
132
154
|
return undefined;
|
|
133
155
|
if (!cache.has(prop))
|
|
@@ -142,6 +164,8 @@ export class ShopifyError extends Error {
|
|
|
142
164
|
super(message);
|
|
143
165
|
this.errors = errors;
|
|
144
166
|
}
|
|
167
|
+
/** Shopify was still throttling the store after Inference Bureau waited and tried again. */
|
|
168
|
+
get throttled() { return this.errors.some((e) => e?.extensions?.code === "THROTTLED"); }
|
|
145
169
|
}
|
|
146
170
|
/** The Admin API for `shop`, as the environment (the same options as createClient). */
|
|
147
171
|
export function createShopifyClient(shop, o = {}) {
|
|
@@ -155,7 +179,7 @@ export function createShopifyClient(shop, o = {}) {
|
|
|
155
179
|
environment,
|
|
156
180
|
async graphql(query, variables = {}) {
|
|
157
181
|
const res = await f(`${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/shopify/graphql`, {
|
|
158
|
-
method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ shop, query, variables }),
|
|
182
|
+
method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ shop, query, variables, ...(o.priority ? { priority: o.priority } : {}), ...(o.maxRetries !== undefined ? { maxRetries: o.maxRetries } : {}) }),
|
|
159
183
|
});
|
|
160
184
|
const json = (await res.json().catch(() => ({})));
|
|
161
185
|
if (!res.ok)
|
|
@@ -284,7 +308,8 @@ export async function verifyShopifySession(request, o = {}) {
|
|
|
284
308
|
return null;
|
|
285
309
|
if (!res.ok)
|
|
286
310
|
throw new ApiError(json.error?.message ?? `Checking the session failed (${res.status}).`, res.status, json.error?.code ?? null);
|
|
287
|
-
|
|
311
|
+
const api = createClient({ ...o, shop: json.shop, role: "shopify-app-users", session: { userId: json.userId } });
|
|
312
|
+
return { shop: json.shop, userId: json.userId, sessionId: json.sessionId, ...(json.preview ? { preview: json.preview } : {}), api };
|
|
288
313
|
}
|
|
289
314
|
const hex = (b) => Array.from(new Uint8Array(b), (x) => x.toString(16).padStart(2, "0")).join("");
|
|
290
315
|
/**
|
|
@@ -304,5 +329,9 @@ export async function verifyProxyRequest(request, o = {}) {
|
|
|
304
329
|
let d = got.length ^ want.length;
|
|
305
330
|
for (let i = 0; i < Math.min(got.length, want.length); i++)
|
|
306
331
|
d |= got.charCodeAt(i) ^ want.charCodeAt(i);
|
|
307
|
-
|
|
332
|
+
if (d !== 0)
|
|
333
|
+
return null;
|
|
334
|
+
const { now: _now, ...client } = o;
|
|
335
|
+
const api = createClient({ ...client, token, shop, role: "storefront-shoppers", session: { customerId: customer || null } });
|
|
336
|
+
return { shop, customerId: customer || null, pathPrefix: prefix, api };
|
|
308
337
|
}
|
package/dist/runtime.d.ts
CHANGED
|
@@ -18,6 +18,8 @@ export interface ActionRequest {
|
|
|
18
18
|
environment: "development" | "production";
|
|
19
19
|
/** The store the run is about, when there is one. */
|
|
20
20
|
shop?: string | null;
|
|
21
|
+
/** Nobody is waiting on the run (a job, a webhook, a schedule): its Shopify calls give way to requests. */
|
|
22
|
+
background?: boolean;
|
|
21
23
|
}
|
|
22
24
|
export type ActionResponse = {
|
|
23
25
|
ok: true;
|
package/dist/runtime.js
CHANGED
|
@@ -30,6 +30,8 @@ function collector(lines, echo) {
|
|
|
30
30
|
};
|
|
31
31
|
return { debug: at("debug"), info: at("info"), warn: at("warn"), error: at("error") };
|
|
32
32
|
}
|
|
33
|
+
/** An action's `api`: its run's store's records only, when the run is for a store (`createClient()` reaches every store). */
|
|
34
|
+
const scopedApi = (api, shop) => (shop && typeof api.forShop === "function" ? api.forShop(shop) : api);
|
|
33
35
|
/**
|
|
34
36
|
* Runs one phase of an action, without checking where the request came from (handleAction does). `api` and
|
|
35
37
|
* `shopify` stand in for the environment's clients (the test app's in-memory ones); `echo: false` keeps the logger's
|
|
@@ -45,9 +47,9 @@ export async function runAction(req, registry, o = {}) {
|
|
|
45
47
|
const mod = await load();
|
|
46
48
|
const record = req.record ? trackRecord({ ...req.record }, req.model) : null;
|
|
47
49
|
const ctx = {
|
|
48
|
-
params: req.params ?? {}, record, api: o.api ?? createClient(o.token ? { token: o.token } : {}), logger: collector(logs, o.echo ?? true),
|
|
50
|
+
params: req.params ?? {}, record, api: scopedApi(o.api ?? createClient(o.token ? { token: o.token } : {}), req.shop), logger: collector(logs, o.echo ?? true),
|
|
49
51
|
model: req.model, action: req.action, environment: req.environment,
|
|
50
|
-
shop: req.shop ?? null, shopify: req.shop ? (o.shopify?.(req.shop) ?? createShopifyClient(req.shop, o.token ? { token: o.token } : {})) : null,
|
|
52
|
+
shop: req.shop ?? null, shopify: req.shop ? (o.shopify?.(req.shop) ?? createShopifyClient(req.shop, { ...(o.token ? { token: o.token } : {}), ...(req.background ? { priority: "background" } : {}) })) : null,
|
|
51
53
|
};
|
|
52
54
|
if (req.phase === "onSuccess") {
|
|
53
55
|
await mod.onSuccess?.(ctx);
|
package/dist/test.d.ts
CHANGED
|
@@ -11,6 +11,9 @@
|
|
|
11
11
|
* as JSON, its writes are applied when `run` returns, then `onSuccess` runs with the saved record. Not covered:
|
|
12
12
|
* permissions (actions run as the system), `timeoutMS`, webhook `filter`s (Shopify applies them), schedules' timing
|
|
13
13
|
* and computed or relationship fields other than belongsTo.
|
|
14
|
+
*
|
|
15
|
+
* File fields keep their files in memory: `base64` reads back as a `data:` URL, `copyURL` as the URL itself (not
|
|
16
|
+
* fetched, size 0), and `upload`/`createUpload` tokens as the upload (a `createUpload` needs no PUT here).
|
|
14
17
|
*/
|
|
15
18
|
import { ApiError, type ActionModule, type Api, type AppRecord, type AppSettings, type Job, type LogLine, type ModelSchema } from "./index.js";
|
|
16
19
|
type Embed = (model: string, input: string[]) => Promise<number[][]>;
|
package/dist/test.js
CHANGED
|
@@ -11,11 +11,14 @@
|
|
|
11
11
|
* as JSON, its writes are applied when `run` returns, then `onSuccess` runs with the saved record. Not covered:
|
|
12
12
|
* permissions (actions run as the system), `timeoutMS`, webhook `filter`s (Shopify applies them), schedules' timing
|
|
13
13
|
* and computed or relationship fields other than belongsTo.
|
|
14
|
+
*
|
|
15
|
+
* File fields keep their files in memory: `base64` reads back as a `data:` URL, `copyURL` as the URL itself (not
|
|
16
|
+
* fetched, size 0), and `upload`/`createUpload` tokens as the upload (a `createUpload` needs no PUT here).
|
|
14
17
|
*/
|
|
15
18
|
import { ApiError, ShopifyError } from "./index.js";
|
|
16
19
|
import { runAction as runPhase } from "./runtime.js";
|
|
17
20
|
/** Kept in `data`; the rest are a vector, the other side of a relationship, or worked out (computed). */
|
|
18
|
-
const STORED = new Set(["string", "richText", "email", "url", "color", "number", "dateTime", "enum", "boolean", "roleList", "json", "belongsTo", "password", "encryptedString"]);
|
|
21
|
+
const STORED = new Set(["string", "richText", "email", "url", "color", "number", "dateTime", "enum", "boolean", "roleList", "json", "belongsTo", "password", "encryptedString", "file"]);
|
|
19
22
|
const SYSTEM = ["id", "createdAt", "updatedAt"];
|
|
20
23
|
const MAX_PAGE = 250;
|
|
21
24
|
const MAX_RECORD_BYTES = 256 * 1024;
|
|
@@ -110,6 +113,8 @@ function convert(f, v, mode) {
|
|
|
110
113
|
}
|
|
111
114
|
case "password":
|
|
112
115
|
return typeof v === "string" ? ok(v) : read ? ok(null) : bad("must be text");
|
|
116
|
+
case "file":
|
|
117
|
+
return read ? ok(isObj(v) && "url" in v ? v : null) : fileOf(v);
|
|
113
118
|
case "vector": {
|
|
114
119
|
if (!Array.isArray(v) || !v.length || !v.every((x) => typeof x === "number" && Number.isFinite(x)))
|
|
115
120
|
return read ? ok(null) : bad("must be a list of numbers");
|
|
@@ -124,6 +129,50 @@ function convert(f, v, mode) {
|
|
|
124
129
|
return read ? ok(null) : bad(`${f.type} fields can't be written yet`);
|
|
125
130
|
}
|
|
126
131
|
}
|
|
132
|
+
// ---- files (record-files.ts), in memory ----
|
|
133
|
+
/** Uploads by token: `upload`'s, and `createUpload`'s as if their PUT had happened. */
|
|
134
|
+
const UPLOADS = new Map();
|
|
135
|
+
let uploadSeq = 0;
|
|
136
|
+
const baseName = (name, fallback = "file") => (typeof name === "string" ? name.split(/[\\/]/).pop()?.trim() : "") || fallback;
|
|
137
|
+
const MIME = /^[\w.+-]+\/[\w.+-]+$/;
|
|
138
|
+
const mimeOf = (given) => (typeof given === "string" && MIME.test(given.trim()) ? given.trim().toLowerCase() : "application/octet-stream");
|
|
139
|
+
function fileOf(v) {
|
|
140
|
+
if (!isObj(v))
|
|
141
|
+
return bad("must be { base64, fileName }, { copyURL } or { directUploadToken }");
|
|
142
|
+
const given = ["base64", "copyURL", "directUploadToken"].filter((k) => v[k] !== undefined);
|
|
143
|
+
if (given.length !== 1)
|
|
144
|
+
return bad(typeof v.url === "string" && !given.length ? "a file is written as { copyURL }, { base64 } or { directUploadToken }, not as it reads" : "must have one of base64, copyURL or directUploadToken");
|
|
145
|
+
if (typeof v.directUploadToken === "string") {
|
|
146
|
+
const up = UPLOADS.get(v.directUploadToken);
|
|
147
|
+
return up ? ok({ ...up, ...(typeof v.fileName === "string" ? { fileName: baseName(v.fileName) } : {}) }) : bad("isn't an upload token for this environment");
|
|
148
|
+
}
|
|
149
|
+
if (typeof v.base64 === "string") {
|
|
150
|
+
const b64 = v.base64.replace(/^data:[^;,]*;base64,/, "").replace(/\s+/g, "");
|
|
151
|
+
if (!/^[A-Za-z0-9+/_-]*={0,2}$/.test(b64))
|
|
152
|
+
return bad("has base64 that isn't base64");
|
|
153
|
+
const mimeType = mimeOf(v.mimeType ?? /^data:([^;,]+)/.exec(v.base64)?.[1]);
|
|
154
|
+
return ok({ url: `data:${mimeType};base64,${b64}`, fileName: baseName(v.fileName), mimeType, size: Math.floor((b64.replace(/=+$/, "").length * 3) / 4) });
|
|
155
|
+
}
|
|
156
|
+
if (typeof v.copyURL === "string") {
|
|
157
|
+
let url;
|
|
158
|
+
try {
|
|
159
|
+
url = new URL(v.copyURL);
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return bad("couldn't be copied: That is not a URL.");
|
|
163
|
+
}
|
|
164
|
+
if (url.protocol !== "https:")
|
|
165
|
+
return bad("couldn't be copied: Only https:// URLs are fetched.");
|
|
166
|
+
return ok({ url: url.toString(), fileName: baseName(v.fileName ?? decodeURIComponent(url.pathname.split("/").pop() ?? "")), mimeType: mimeOf(v.mimeType), size: 0 });
|
|
167
|
+
}
|
|
168
|
+
return bad("must have one of base64, copyURL or directUploadToken");
|
|
169
|
+
}
|
|
170
|
+
function fileFieldOf(m, field) {
|
|
171
|
+
const f = m.byName.get(field);
|
|
172
|
+
if (!f || f.type !== "file")
|
|
173
|
+
throw new ApiError(`${m.name} has no file field named ${field}`, 400, "invalid_request");
|
|
174
|
+
return f;
|
|
175
|
+
}
|
|
127
176
|
function defaultOf(f) {
|
|
128
177
|
if (f.def.default === undefined)
|
|
129
178
|
return null;
|
|
@@ -201,7 +250,7 @@ class Records {
|
|
|
201
250
|
const f = m.byName.get(name);
|
|
202
251
|
if (!f)
|
|
203
252
|
throw invalid([{ field: name, message: `${m.name} has no field named ${name}` }]);
|
|
204
|
-
if (!STORED.has(f.type) || f.type === "password" || f.type === "encryptedString")
|
|
253
|
+
if (!STORED.has(f.type) || f.type === "password" || f.type === "encryptedString" || f.type === "file")
|
|
205
254
|
throw invalid([{ field: name, message: `${f.type} fields can't be filtered or sorted on` }]);
|
|
206
255
|
return { f };
|
|
207
256
|
}
|
|
@@ -403,7 +452,7 @@ class Records {
|
|
|
403
452
|
continue;
|
|
404
453
|
}
|
|
405
454
|
if (!STORED.has(f.type) && f.type !== "vector") {
|
|
406
|
-
problems.push({ field: name, message:
|
|
455
|
+
problems.push({ field: name, message: `a ${f.type} field isn't stored on this record` });
|
|
407
456
|
continue;
|
|
408
457
|
}
|
|
409
458
|
if (f.type === "vector" && Array.isArray(f.def.source) && f.def.source.length) {
|
|
@@ -552,7 +601,7 @@ const OPS = ["equals", "notEquals", "in", "notIn", "lessThan", "lessThanOrEqual"
|
|
|
552
601
|
const embeddingModelOf = (f) => (typeof f.def.embeddingModel === "string" && f.def.embeddingModel ? f.def.embeddingModel : DEFAULT_EMBEDDING_MODEL);
|
|
553
602
|
function sourceText(m, f, data) {
|
|
554
603
|
const names = Array.isArray(f.def.source) ? f.def.source.map(String) : [];
|
|
555
|
-
return names.map((n) => m.byName.get(n)).filter((s) => !!s && STORED.has(s.type) && s.type !== "password" && s.type !== "encryptedString")
|
|
604
|
+
return names.map((n) => m.byName.get(n)).filter((s) => !!s && STORED.has(s.type) && s.type !== "password" && s.type !== "encryptedString" && s.type !== "file")
|
|
556
605
|
.map((s) => { const v = data[s.key]; return v === null || v === undefined ? "" : typeof v === "string" ? v : JSON.stringify(v); })
|
|
557
606
|
.filter(Boolean).join("\n");
|
|
558
607
|
}
|
|
@@ -761,28 +810,77 @@ export function createTestApp(o = {}) {
|
|
|
761
810
|
const dot = action.indexOf(".");
|
|
762
811
|
return dot < 0 ? { model: null, action } : { model: action.slice(0, dot), action: action.slice(dot + 1) };
|
|
763
812
|
};
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
813
|
+
/** The field holding a record's store (access.ts storeField), or null when the model isn't store-owned. */
|
|
814
|
+
const storeFieldOf = (name) => {
|
|
815
|
+
const m = models.get(name);
|
|
816
|
+
if (!m)
|
|
817
|
+
return null;
|
|
818
|
+
if (name === "shopifyShop" && m.byName.has("myshopifyDomain"))
|
|
819
|
+
return "myshopifyDomain";
|
|
820
|
+
const synced = m.fields.find((f) => f.key === "sh_shop");
|
|
821
|
+
if (synced)
|
|
822
|
+
return synced.name;
|
|
823
|
+
const own = m.byName.get("shop");
|
|
824
|
+
return own && ["string", "email", "enum"].includes(own.type) ? "shop" : null;
|
|
825
|
+
};
|
|
826
|
+
const otherStore = (shop) => new ApiError(`This call is for ${shop}; it can't reach another store's records.`, 403, "policy_denied");
|
|
827
|
+
// As through the API, `shop` narrows store-owned models to that store's records (api.forShop, an action's api).
|
|
828
|
+
const modelClient = (name, shop) => {
|
|
829
|
+
const f = shop ? storeFieldOf(name) : null;
|
|
830
|
+
const narrow = (q) => (f ? { ...q, filter: q.filter ? { AND: [q.filter, { [f]: { equals: shop } }] } : { [f]: { equals: shop } } } : q);
|
|
831
|
+
const visible = (id) => { const r = store.findOne(name, id); return r && (!f || r[f] === shop) ? r : null; };
|
|
832
|
+
const reach = (id) => { if (!visible(id))
|
|
833
|
+
throw notFound(`There's no ${name} with id ${id}.`); };
|
|
834
|
+
const owned = (values, isNew) => {
|
|
835
|
+
if (!f)
|
|
836
|
+
return values;
|
|
837
|
+
if (f in values && values[f] !== shop)
|
|
838
|
+
throw otherStore(shop);
|
|
839
|
+
return isNew ? { ...values, [f]: shop } : values;
|
|
840
|
+
};
|
|
841
|
+
const runFor = (q) => {
|
|
842
|
+
if (shop && q.shop && q.shop !== shop)
|
|
843
|
+
throw otherStore(shop);
|
|
844
|
+
return shop ? { ...q, shop } : q;
|
|
845
|
+
};
|
|
846
|
+
return {
|
|
847
|
+
findOne: async (id) => visible(id),
|
|
848
|
+
findMany: async (q = {}) => store.findMany(name, narrow(wire(q))),
|
|
849
|
+
findFirst: async (q = {}) => (await store.findMany(name, { ...narrow(wire(q)), first: 1 })).records[0] ?? null,
|
|
850
|
+
search: async (field, near, q = {}) => (await store.findMany(name, { ...narrow(wire(q)), search: { field, near } })),
|
|
851
|
+
// As through the API: the model's create, update or delete action when it has one, else a direct write.
|
|
852
|
+
create: async (values) => { const v = owned(wire(values), true); return registry[`${name}/create`] ? (await run(name, "create", runFor({ params: v }))).record : store.create(name, v); },
|
|
853
|
+
update: async (id, values) => { reach(id); const v = owned(wire(values), false); return registry[`${name}/update`] ? (await run(name, "update", runFor({ id, params: v }))).record : store.update(name, id, v); },
|
|
854
|
+
delete: async (id) => { reach(id); if (registry[`${name}/delete`])
|
|
855
|
+
await run(name, "delete", runFor({ id }));
|
|
856
|
+
else
|
|
857
|
+
store.delete(name, id); },
|
|
858
|
+
checkPassword: async (id, password, field) => (visible(id) ? store.checkPassword(name, id, password, field) : false),
|
|
859
|
+
run: async (action, q = {}) => {
|
|
860
|
+
if (q.id)
|
|
861
|
+
reach(q.id);
|
|
862
|
+
const r = await run(name, action, runFor(q));
|
|
863
|
+
return { record: r.record, ...(r.result !== undefined ? { result: r.result } : {}) };
|
|
864
|
+
},
|
|
865
|
+
createUpload: async (field, q = {}) => {
|
|
866
|
+
fileFieldOf(store.model(name), field);
|
|
867
|
+
const token = `upload_${String(++uploadSeq).padStart(6, "0")}`, fileName = baseName(q.fileName);
|
|
868
|
+
const mimeType = q.mimeType === undefined ? null : mimeOf(q.mimeType);
|
|
869
|
+
UPLOADS.set(token, { url: `https://uploads.test/${token}/${encodeURIComponent(fileName)}`, fileName, mimeType: mimeType ?? "application/octet-stream", size: q.size ?? 0 });
|
|
870
|
+
return { url: `https://uploads.test/${token}`, method: "PUT", headers: mimeType ? { "content-type": mimeType } : {}, token, expiresAt: new Date((o.now ?? Date.now)() + 3_600_000).toISOString() };
|
|
871
|
+
},
|
|
872
|
+
upload: async (field, body, q = {}) => {
|
|
873
|
+
fileFieldOf(store.model(name), field);
|
|
874
|
+
const blob = body instanceof Blob ? body : new Blob([body]);
|
|
875
|
+
const bytes = new Uint8Array(await blob.arrayBuffer());
|
|
876
|
+
let bin = "";
|
|
877
|
+
for (const b of bytes)
|
|
878
|
+
bin += String.fromCharCode(b);
|
|
879
|
+
const mimeType = mimeOf(q.mimeType ?? blob.type), token = `upload_${String(++uploadSeq).padStart(6, "0")}`;
|
|
880
|
+
UPLOADS.set(token, { url: `data:${mimeType};base64,${btoa(bin)}`, fileName: baseName(q.fileName ?? (typeof File !== "undefined" && body instanceof File ? body.name : undefined)), mimeType, size: bytes.length });
|
|
881
|
+
return { directUploadToken: token };
|
|
882
|
+
},
|
|
883
|
+
};
|
|
786
884
|
};
|
|
787
885
|
const enqueue = async (action, params = {}, q = {}) => {
|
|
788
886
|
const t = (o.now ?? Date.now)();
|
|
@@ -794,19 +892,43 @@ export function createTestApp(o = {}) {
|
|
|
794
892
|
jobs.push(job);
|
|
795
893
|
return wire(job);
|
|
796
894
|
};
|
|
797
|
-
const
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
},
|
|
809
|
-
|
|
895
|
+
const apis = new Map();
|
|
896
|
+
/** The API, for every store or one (`forShop`). Roles aren't applied here: `asRole` gives the same API. */
|
|
897
|
+
const apiFor = (shop) => {
|
|
898
|
+
const key = shop ?? "";
|
|
899
|
+
if (apis.has(key))
|
|
900
|
+
return apis.get(key);
|
|
901
|
+
const clients = new Map();
|
|
902
|
+
const $global = async (action, params = {}) => {
|
|
903
|
+
const r = await run(null, action, { params, ...(shop ? { shop } : {}) });
|
|
904
|
+
return r.result !== undefined ? { result: r.result } : {};
|
|
905
|
+
};
|
|
906
|
+
const queue = (action, params = {}, q = {}) => {
|
|
907
|
+
if (shop && q.shop && q.shop !== shop)
|
|
908
|
+
throw otherStore(shop);
|
|
909
|
+
return enqueue(action, params, shop ? { ...q, shop } : q);
|
|
910
|
+
};
|
|
911
|
+
const made = new Proxy({}, {
|
|
912
|
+
get(_t, prop) {
|
|
913
|
+
if (prop === "$global")
|
|
914
|
+
return $global;
|
|
915
|
+
if (prop === "enqueue")
|
|
916
|
+
return queue;
|
|
917
|
+
if (prop === "forShop")
|
|
918
|
+
return (s) => apiFor(s);
|
|
919
|
+
if (prop === "asRole")
|
|
920
|
+
return () => made;
|
|
921
|
+
if (typeof prop !== "string" || prop === "then")
|
|
922
|
+
return undefined;
|
|
923
|
+
if (!clients.has(prop))
|
|
924
|
+
clients.set(prop, modelClient(prop, shop));
|
|
925
|
+
return clients.get(prop);
|
|
926
|
+
},
|
|
927
|
+
});
|
|
928
|
+
apis.set(key, made);
|
|
929
|
+
return made;
|
|
930
|
+
};
|
|
931
|
+
const api = apiFor(null);
|
|
810
932
|
// ---- Shopify's side ----
|
|
811
933
|
const shopModel = () => models.get("shopifyShop");
|
|
812
934
|
const shopRecord = async (shop) => (shopModel()?.byName.has("myshopifyDomain") ? (await store.findMany("shopifyShop", { filter: { myshopifyDomain: { equals: shop } }, first: 1 })).records[0] ?? null : null);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inferencebureau/apps-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "The SDK an Inference Bureau app's code imports: action helpers, metadata types, the records API client and a test harness for its actions.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"keywords": [
|