@inferencebureau/apps-sdk 0.9.0 → 0.10.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 +7 -0
- package/dist/index.d.ts +148 -5
- package/dist/index.js +61 -2
- package/dist/runtime.d.ts +6 -3
- package/dist/runtime.js +7 -5
- package/dist/test.d.ts +25 -3
- package/dist/test.js +206 -16
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -77,6 +77,13 @@ one changes (`ib-apps dev` and `ib-apps pull` bring it down), and it fills in th
|
|
|
77
77
|
request. `ModelRecord<"review">` and `ModelInput<"review">` name a model's types; `api.$model(name)` reaches a model
|
|
78
78
|
the app may not have. Without the file the client takes any name.
|
|
79
79
|
|
|
80
|
+
Reads take `select` to pick fields and follow relationships in one call, typed to what they pick:
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
const { records } = await api.review.findMany({ select: { rating: true, product: { select: { title: true } } } });
|
|
84
|
+
records[0]?.product?.title; // a belongsTo reads as its record; a hasMany as { records, hasNextPage }
|
|
85
|
+
```
|
|
86
|
+
|
|
80
87
|
Entry points:
|
|
81
88
|
|
|
82
89
|
- `@inferencebureau/apps-sdk`: metadata types, action helpers, `createClient`, `createShopifyClient`,
|
package/dist/index.d.ts
CHANGED
|
@@ -71,8 +71,14 @@ export interface FieldDef {
|
|
|
71
71
|
model: string;
|
|
72
72
|
belongsToField?: string;
|
|
73
73
|
};
|
|
74
|
+
/**
|
|
75
|
+
* A hasManyThrough's join model. Its belongsTo to this model and its belongsTo to the records reached are found when
|
|
76
|
+
* there's one of each; name them when there are more.
|
|
77
|
+
*/
|
|
74
78
|
through?: {
|
|
75
79
|
model: string;
|
|
80
|
+
belongsToSelfField?: string;
|
|
81
|
+
belongsToSiblingField?: string;
|
|
76
82
|
};
|
|
77
83
|
[key: string]: unknown;
|
|
78
84
|
}
|
|
@@ -196,14 +202,73 @@ export type Sort<K extends string = string> = string extends K ? Record<string,
|
|
|
196
202
|
[P in K]?: SortDirection;
|
|
197
203
|
};
|
|
198
204
|
export type SortDirection = "Ascending" | "Descending";
|
|
199
|
-
export interface FindManyOptions<M extends ModelTypes = UntypedModel> {
|
|
205
|
+
export interface FindManyOptions<M extends ModelTypes = UntypedModel, S extends SelectOf<M> | undefined = undefined> {
|
|
200
206
|
filter?: Filter<M["filter"]>;
|
|
201
207
|
sort?: Sort<M["sortable"]> | Sort<M["sortable"]>[];
|
|
202
208
|
first?: number;
|
|
203
209
|
after?: string | null;
|
|
204
210
|
/** 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. */
|
|
205
211
|
search?: string;
|
|
212
|
+
/** Which fields to read, and which related records with them (SelectOf); every field and no related records when left out. */
|
|
213
|
+
select?: S;
|
|
206
214
|
}
|
|
215
|
+
/**
|
|
216
|
+
* What a read's `select` names: fields as `true` (the id always comes), and relationships as `true` for their records
|
|
217
|
+
* with every field, or `{ select }` to choose theirs. A hasMany or hasManyThrough also takes `filter`, `sort` and
|
|
218
|
+
* `first` (50 unless given, at most 250 for each record). Up to 3 relationships deep, every related model read
|
|
219
|
+
* through the same store and role as the call itself.
|
|
220
|
+
*
|
|
221
|
+
* const reviews = await api.review.findMany({ select: { rating: true, product: { select: { title: true } } } });
|
|
222
|
+
* reviews.records[0].product?.title;
|
|
223
|
+
*
|
|
224
|
+
* A belongsTo then reads as its record (null when there's none, or the call can't read it) instead of its id; a
|
|
225
|
+
* hasOne as its record or null; a hasMany or hasManyThrough as `{ records, hasNextPage }`, newest first unless sorted.
|
|
226
|
+
*/
|
|
227
|
+
export type SelectOf<M extends ModelTypes = UntypedModel> = string extends keyof RelationsOf<M> ? {
|
|
228
|
+
[field: string]: true | {
|
|
229
|
+
select?: SelectOf;
|
|
230
|
+
filter?: Filter;
|
|
231
|
+
sort?: Sort | Sort[];
|
|
232
|
+
first?: number;
|
|
233
|
+
};
|
|
234
|
+
} : {
|
|
235
|
+
[K in Exclude<keyof M["record"], keyof RelationsOf<M>> & string]?: true;
|
|
236
|
+
} & {
|
|
237
|
+
[R in keyof RelationsOf<M> & string]?: true | RelatedSelectOf<RelationsOf<M>[R]>;
|
|
238
|
+
};
|
|
239
|
+
type RelatedSelectOf<R extends RelationTypes> = {
|
|
240
|
+
select?: SelectOf<ModelOf<R["model"]>>;
|
|
241
|
+
} & (R["many"] extends true ? {
|
|
242
|
+
filter?: Filter<ModelOf<R["model"]>["filter"]>;
|
|
243
|
+
sort?: Sort<ModelOf<R["model"]>["sortable"]> | Sort<ModelOf<R["model"]>["sortable"]>[];
|
|
244
|
+
first?: number;
|
|
245
|
+
} : {});
|
|
246
|
+
type RelationsOf<M extends ModelTypes> = M extends {
|
|
247
|
+
relations: infer R extends {
|
|
248
|
+
[field: string]: RelationTypes;
|
|
249
|
+
};
|
|
250
|
+
} ? R : {
|
|
251
|
+
[field: string]: RelationTypes;
|
|
252
|
+
};
|
|
253
|
+
/** A record as a read with `select` returns it: the fields it names, and the related records it reads. */
|
|
254
|
+
export type Selected<M extends ModelTypes, S> = string extends keyof RelationsOf<M> ? AppRecord : Flat<{
|
|
255
|
+
id: string;
|
|
256
|
+
} & {
|
|
257
|
+
[K in keyof S & Exclude<keyof M["record"], keyof RelationsOf<M>>]: M["record"][K];
|
|
258
|
+
} & {
|
|
259
|
+
[K in keyof S & keyof RelationsOf<M>]: RelatedOf<RelationsOf<M>[K], S[K]>;
|
|
260
|
+
}>;
|
|
261
|
+
type RelatedOf<R extends RelationTypes, V> = (V extends {
|
|
262
|
+
select: infer T;
|
|
263
|
+
} ? Selected<ModelOf<R["model"]>, T> : ModelOf<R["model"]>["record"]) extends infer T ? R["many"] extends true ? {
|
|
264
|
+
records: T[];
|
|
265
|
+
hasNextPage: boolean;
|
|
266
|
+
} : T | null : never;
|
|
267
|
+
type Flat<T> = {
|
|
268
|
+
[K in keyof T]: T[K];
|
|
269
|
+
} & {};
|
|
270
|
+
/** A read's records: the model's record, or what `select` picked of it. */
|
|
271
|
+
export type ReadOf<M extends ModelTypes, S> = [S] extends [undefined] ? M["record"] : Selected<M, S>;
|
|
207
272
|
/** A field's filter: `null` matches records without a value (or holding the field's default when that's null). */
|
|
208
273
|
export interface FieldFilter<V> {
|
|
209
274
|
equals?: V | null;
|
|
@@ -255,6 +320,14 @@ export interface ModelTypes {
|
|
|
255
320
|
actions: {
|
|
256
321
|
[action: string]: ActionTypes;
|
|
257
322
|
};
|
|
323
|
+
/** Its relationships (belongsTo, hasOne, hasMany, hasManyThrough), for `select`: the model each reads, and whether it's a list. */
|
|
324
|
+
relations?: {
|
|
325
|
+
[field: string]: RelationTypes;
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
export interface RelationTypes {
|
|
329
|
+
model: string;
|
|
330
|
+
many: boolean;
|
|
258
331
|
}
|
|
259
332
|
/** An action's `params` and what it returns: `unknown` when its options say `returnType: true`, else nothing. */
|
|
260
333
|
export interface ActionTypes {
|
|
@@ -401,11 +474,13 @@ export interface CheckPasswordOptions {
|
|
|
401
474
|
ip?: string;
|
|
402
475
|
}
|
|
403
476
|
export interface ModelClient<M extends ModelTypes = UntypedModel> {
|
|
404
|
-
findOne(id: string
|
|
405
|
-
|
|
406
|
-
|
|
477
|
+
findOne<S extends SelectOf<M> | undefined = undefined>(id: string, o?: {
|
|
478
|
+
select?: S;
|
|
479
|
+
}): Promise<ReadOf<M, S> | null>;
|
|
480
|
+
findMany<S extends SelectOf<M> | undefined = undefined>(o?: FindManyOptions<M, S>): Promise<RecordPage<ReadOf<M, S>>>;
|
|
481
|
+
findFirst<S extends SelectOf<M> | undefined = undefined>(o?: Omit<FindManyOptions<M, S>, "first" | "after">): Promise<ReadOf<M, S> | null>;
|
|
407
482
|
/** Nearest records to text (embedded with the field's model) or a vector, nearest first, with `_distance`. */
|
|
408
|
-
search(field: M["vectors"], near: string | number[], o?: Omit<FindManyOptions<M>, "sort" | "search">): Promise<RecordPage<M
|
|
483
|
+
search<S extends SelectOf<M> | undefined = undefined>(field: M["vectors"], near: string | number[], o?: Omit<FindManyOptions<M, S>, "sort" | "search">): Promise<RecordPage<ReadOf<M, S> & {
|
|
409
484
|
_distance: number;
|
|
410
485
|
}>>;
|
|
411
486
|
/** Writes at once. In an action, that's outside its transaction: to write with the run, `build` and `save` instead. */
|
|
@@ -634,6 +709,69 @@ export interface ShopifyClientOptions extends ClientOptions {
|
|
|
634
709
|
}
|
|
635
710
|
/** The Admin API for `shop`, as the environment (the same options as createClient). */
|
|
636
711
|
export declare function createShopifyClient(shop: string, o?: ShopifyClientOptions): ShopifyClient;
|
|
712
|
+
/**
|
|
713
|
+
* Models through Inference Bureau's gateway, billed to the team like the app's embeddings: no provider key to manage.
|
|
714
|
+
* Each call is an ordinary gateway request on the team's Apps AI key, so Directives, budgets and the balance apply, it
|
|
715
|
+
* shows in the gateway's Logs, and the app's Logs has it (model, tokens, cost) under the action that made it.
|
|
716
|
+
*
|
|
717
|
+
* The client is also the settings of an OpenAI-compatible provider: `createInferenceBureau(ai)` from
|
|
718
|
+
* `@inferencebureau/ai-sdk-provider` (or `createOpenAI({ baseURL: ai.baseURL, apiKey: ai.apiKey, headers: ai.headers })`)
|
|
719
|
+
* gives the AI SDK's `generateText`, `streamText`, `generateObject` and tools.
|
|
720
|
+
*/
|
|
721
|
+
export interface AiClient {
|
|
722
|
+
/** The gateway for this environment, with chat completions, Anthropic Messages and embeddings under it. */
|
|
723
|
+
baseURL: string;
|
|
724
|
+
/** What to send as the API key: the environment's token. */
|
|
725
|
+
apiKey: string;
|
|
726
|
+
/** Sent with every call: ties the call to the action's run in Logs. */
|
|
727
|
+
headers: Record<string, string>;
|
|
728
|
+
/** fetch with the token and headers added, for a client of your own. */
|
|
729
|
+
fetch: typeof fetch;
|
|
730
|
+
/** One answer from a chat model: `prompt` (with an optional `system`), or `messages`. */
|
|
731
|
+
generateText(o: GenerateTextOptions): Promise<GenerateTextResult>;
|
|
732
|
+
/** Vectors for the texts, in order (openai/text-embedding-3-small unless `model` names another). */
|
|
733
|
+
embed(input: string | string[], o?: {
|
|
734
|
+
model?: string;
|
|
735
|
+
signal?: AbortSignal;
|
|
736
|
+
}): Promise<number[][]>;
|
|
737
|
+
}
|
|
738
|
+
export interface AiMessage {
|
|
739
|
+
role: "system" | "user" | "assistant";
|
|
740
|
+
content: string;
|
|
741
|
+
}
|
|
742
|
+
export interface GenerateTextOptions {
|
|
743
|
+
/** A catalog id (`openai/gpt-5-mini`, `anthropic/claude-sonnet-4.5`) or a team alias, as Directives allow. */
|
|
744
|
+
model: string;
|
|
745
|
+
prompt?: string;
|
|
746
|
+
system?: string;
|
|
747
|
+
messages?: AiMessage[];
|
|
748
|
+
maxTokens?: number;
|
|
749
|
+
temperature?: number;
|
|
750
|
+
/** Answer with a JSON object (say what shape in the prompt); `text` is then the JSON. */
|
|
751
|
+
json?: boolean;
|
|
752
|
+
signal?: AbortSignal;
|
|
753
|
+
}
|
|
754
|
+
export interface GenerateTextResult {
|
|
755
|
+
text: string;
|
|
756
|
+
/** The model that answered (a fallback in Directives may differ from the one asked for). */
|
|
757
|
+
model: string;
|
|
758
|
+
finishReason: string | null;
|
|
759
|
+
usage: {
|
|
760
|
+
inputTokens: number;
|
|
761
|
+
outputTokens: number;
|
|
762
|
+
} | null;
|
|
763
|
+
/** The gateway request's id, as Logs shows it. */
|
|
764
|
+
requestId: string | null;
|
|
765
|
+
}
|
|
766
|
+
export interface AiClientOptions extends ClientOptions {
|
|
767
|
+
/** The action run's event, so its calls sit under it in Logs (an action's `ai` has it). */
|
|
768
|
+
event?: string;
|
|
769
|
+
/** Aborts every call (an action's `ai` stops with its run). */
|
|
770
|
+
signal?: AbortSignal;
|
|
771
|
+
}
|
|
772
|
+
export declare const DEFAULT_EMBEDDING_MODEL = "openai/text-embedding-3-small";
|
|
773
|
+
/** Models for the app's code, as the environment (the same options as createClient). */
|
|
774
|
+
export declare function createAiClient(o?: AiClientOptions): AiClient;
|
|
637
775
|
export interface Money {
|
|
638
776
|
amount: number | string;
|
|
639
777
|
currencyCode: string;
|
|
@@ -948,6 +1086,11 @@ export interface ActionContext {
|
|
|
948
1086
|
* staff in the store's admin (verifyShopifySession's), a shopper. Null for the app's own calls, webhooks and jobs.
|
|
949
1087
|
*/
|
|
950
1088
|
caller: ActionCaller | null;
|
|
1089
|
+
/**
|
|
1090
|
+
* Models through Inference Bureau's gateway, billed to the team: `ai.generateText({ model, prompt })`, `ai.embed`,
|
|
1091
|
+
* or `createInferenceBureau(ai)` for the AI SDK. Its calls appear under the run in Logs, and stop with it.
|
|
1092
|
+
*/
|
|
1093
|
+
ai: AiClient;
|
|
951
1094
|
/**
|
|
952
1095
|
* Fires when the run is stopped: its job canceled from the Queue or the API, or its time up. Pass it to `fetch` and
|
|
953
1096
|
* check it between steps of a long loop to stop early; what `run` returns after it fires is dropped.
|
package/dist/index.js
CHANGED
|
@@ -134,10 +134,12 @@ export function createClient(o = {}) {
|
|
|
134
134
|
const model = (name) => {
|
|
135
135
|
const m = `/models/${encodeURIComponent(name)}`;
|
|
136
136
|
const query = (o) => call("POST", `${m}/records/query`, o);
|
|
137
|
+
// Reads answer what `select` picked; the types say so (ReadOf), the wire doesn't.
|
|
137
138
|
return {
|
|
138
|
-
async findOne(id) {
|
|
139
|
+
async findOne(id, o = {}) {
|
|
140
|
+
const q = o.select ? `?select=${encodeURIComponent(JSON.stringify(o.select))}` : "";
|
|
139
141
|
try {
|
|
140
|
-
return await call("GET", `${m}/records/${encodeURIComponent(id)}`);
|
|
142
|
+
return await call("GET", `${m}/records/${encodeURIComponent(id)}${q}`);
|
|
141
143
|
}
|
|
142
144
|
catch (e) {
|
|
143
145
|
if (e instanceof ApiError && e.status === 404)
|
|
@@ -268,6 +270,63 @@ export function createShopifyClient(shop, o = {}) {
|
|
|
268
270
|
},
|
|
269
271
|
};
|
|
270
272
|
}
|
|
273
|
+
export const DEFAULT_EMBEDDING_MODEL = "openai/text-embedding-3-small";
|
|
274
|
+
/** Models for the app's code, as the environment (the same options as createClient). */
|
|
275
|
+
export function createAiClient(o = {}) {
|
|
276
|
+
const url = (o.url ?? envVar("IB_API_URL") ?? "https://api.inferencebureau.com").replace(/\/$/, "");
|
|
277
|
+
const token = o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? "";
|
|
278
|
+
const app = o.app ?? envVar("IB_APP") ?? "";
|
|
279
|
+
const environment = o.environment ?? envVar("IB_ENVIRONMENT") ?? "development";
|
|
280
|
+
const f = o.fetch ?? fetch;
|
|
281
|
+
const baseURL = `${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/ai`;
|
|
282
|
+
const headers = o.event ? { "x-ib-event": o.event } : {};
|
|
283
|
+
const withAuth = (input, init = {}) => {
|
|
284
|
+
const h = new Headers(init.headers);
|
|
285
|
+
if (!h.has("authorization"))
|
|
286
|
+
h.set("authorization", `Bearer ${token}`);
|
|
287
|
+
for (const [k, v] of Object.entries(headers))
|
|
288
|
+
if (!h.has(k))
|
|
289
|
+
h.set(k, v);
|
|
290
|
+
const signal = init.signal ?? o.signal;
|
|
291
|
+
return f(input, { ...init, headers: h, ...(signal ? { signal } : {}) });
|
|
292
|
+
};
|
|
293
|
+
async function post(path, body, signal) {
|
|
294
|
+
const res = await withAuth(`${baseURL}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), ...(signal ? { signal } : {}) });
|
|
295
|
+
const text = await res.text();
|
|
296
|
+
let json = {};
|
|
297
|
+
try {
|
|
298
|
+
json = text ? JSON.parse(text) : {};
|
|
299
|
+
}
|
|
300
|
+
catch { /* reported below */ }
|
|
301
|
+
if (!res.ok)
|
|
302
|
+
throw new ApiError(json.error?.message ?? `The gateway answered ${res.status}.`, res.status, json.error?.code ?? null);
|
|
303
|
+
return { json: json, requestId: res.headers.get("x-request-id") };
|
|
304
|
+
}
|
|
305
|
+
return {
|
|
306
|
+
baseURL, apiKey: token, headers, fetch: withAuth,
|
|
307
|
+
async generateText(g) {
|
|
308
|
+
if (!g.prompt && !g.messages?.length)
|
|
309
|
+
throw new Error("generateText needs a prompt or messages.");
|
|
310
|
+
const messages = [...(g.system ? [{ role: "system", content: g.system }] : []), ...(g.messages ?? []), ...(g.prompt ? [{ role: "user", content: g.prompt }] : [])];
|
|
311
|
+
const { json, requestId } = await post("/chat/completions", {
|
|
312
|
+
model: g.model, messages, ...(g.maxTokens !== undefined ? { max_tokens: g.maxTokens } : {}), ...(g.temperature !== undefined ? { temperature: g.temperature } : {}),
|
|
313
|
+
...(g.json ? { response_format: { type: "json_object" } } : {}),
|
|
314
|
+
}, g.signal);
|
|
315
|
+
const choice = json.choices?.[0];
|
|
316
|
+
return {
|
|
317
|
+
text: typeof choice?.message?.content === "string" ? choice.message.content : "", model: json.model ?? g.model, finishReason: choice?.finish_reason ?? null,
|
|
318
|
+
usage: json.usage ? { inputTokens: json.usage.prompt_tokens ?? 0, outputTokens: json.usage.completion_tokens ?? 0 } : null, requestId,
|
|
319
|
+
};
|
|
320
|
+
},
|
|
321
|
+
async embed(input, e = {}) {
|
|
322
|
+
const texts = typeof input === "string" ? [input] : input;
|
|
323
|
+
if (!texts.length)
|
|
324
|
+
return [];
|
|
325
|
+
const { json } = await post("/embeddings", { model: e.model ?? DEFAULT_EMBEDDING_MODEL, input: texts }, e.signal);
|
|
326
|
+
return [...(json.data ?? [])].sort((a, b) => (a.index ?? 0) - (b.index ?? 0)).map((d) => d.embedding);
|
|
327
|
+
},
|
|
328
|
+
};
|
|
329
|
+
}
|
|
271
330
|
export class ShopifyBillingError extends Error {
|
|
272
331
|
userErrors;
|
|
273
332
|
constructor(message, userErrors = []) {
|
package/dist/runtime.d.ts
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 { type ActionCaller, type ActionModule, type Api, type AppRecord, type LogLine, type ShopifyClient, type StagedWrite } from "./index.js";
|
|
8
|
+
import { type ActionCaller, type AiClient, type ActionModule, type Api, type AppRecord, type LogLine, type ShopifyClient, type StagedWrite } from "./index.js";
|
|
9
9
|
/** Action modules by key: `<model>/<action>` for model actions, `$global/<action>` for global ones. */
|
|
10
10
|
export type ActionRegistry = Record<string, () => Promise<ActionModule>>;
|
|
11
11
|
export interface ActionRequest {
|
|
@@ -23,6 +23,8 @@ export interface ActionRequest {
|
|
|
23
23
|
background?: boolean;
|
|
24
24
|
/** Who called, when the call was held to a role. */
|
|
25
25
|
caller?: ActionCaller | null;
|
|
26
|
+
/** The run's event in Logs: the action's `ai` calls sit under it. */
|
|
27
|
+
event?: string;
|
|
26
28
|
}
|
|
27
29
|
export type ActionResponse = {
|
|
28
30
|
ok: true;
|
|
@@ -46,14 +48,15 @@ export type ActionResponse = {
|
|
|
46
48
|
/** The signature Inference Bureau sends: HMAC-SHA256 of `<timestamp>.<body>` with the environment's token, hex. */
|
|
47
49
|
export declare function sign(token: string, timestamp: string, body: string): Promise<string>;
|
|
48
50
|
/**
|
|
49
|
-
* Runs one phase of an action, without checking where the request came from (handleAction does). `api`
|
|
50
|
-
* `
|
|
51
|
+
* Runs one phase of an action, without checking where the request came from (handleAction does). `api`, `shopify`
|
|
52
|
+
* and `ai` stand in for the environment's clients (the test app's in-memory ones); `echo: false` keeps the logger's
|
|
51
53
|
* lines off the console.
|
|
52
54
|
*/
|
|
53
55
|
export declare function runAction(req: ActionRequest, registry: ActionRegistry, o?: {
|
|
54
56
|
token?: string;
|
|
55
57
|
api?: Api;
|
|
56
58
|
shopify?: (shop: string) => ShopifyClient;
|
|
59
|
+
ai?: AiClient;
|
|
57
60
|
echo?: boolean;
|
|
58
61
|
signal?: AbortSignal;
|
|
59
62
|
}): Promise<ActionResponse>;
|
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 { createClient, createShopifyClient, newRecordId, pendingWrite, stagedWrites, trackRecord } from "./index.js";
|
|
8
|
+
import { createAiClient, createClient, createShopifyClient, newRecordId, pendingWrite, stagedWrites, trackRecord } from "./index.js";
|
|
9
9
|
const SKEW_MS = 5 * 60_000;
|
|
10
10
|
const encoder = new TextEncoder();
|
|
11
11
|
const envVar = (name) => globalThis.process?.env?.[name];
|
|
@@ -46,7 +46,7 @@ function stagingApi(api, handed) {
|
|
|
46
46
|
keep(model, r); return p; };
|
|
47
47
|
const wrap = (name, m) => ({
|
|
48
48
|
...m,
|
|
49
|
-
findOne: async (id) => keep(name, await m.findOne(id)),
|
|
49
|
+
findOne: async (id, o) => keep(name, await m.findOne(id, o)),
|
|
50
50
|
findFirst: async (o) => keep(name, await m.findFirst(o)),
|
|
51
51
|
findMany: async (o) => page(name, await m.findMany(o)),
|
|
52
52
|
search: async (field, near, o) => page(name, await m.search(field, near, o)),
|
|
@@ -72,8 +72,8 @@ function stagingApi(api, handed) {
|
|
|
72
72
|
});
|
|
73
73
|
}
|
|
74
74
|
/**
|
|
75
|
-
* Runs one phase of an action, without checking where the request came from (handleAction does). `api`
|
|
76
|
-
* `
|
|
75
|
+
* Runs one phase of an action, without checking where the request came from (handleAction does). `api`, `shopify`
|
|
76
|
+
* and `ai` stand in for the environment's clients (the test app's in-memory ones); `echo: false` keeps the logger's
|
|
77
77
|
* lines off the console.
|
|
78
78
|
*/
|
|
79
79
|
export async function runAction(req, registry, o = {}) {
|
|
@@ -87,10 +87,12 @@ export async function runAction(req, registry, o = {}) {
|
|
|
87
87
|
const record = req.record ? trackRecord({ ...req.record }, req.model) : null;
|
|
88
88
|
const handed = [];
|
|
89
89
|
const logger = collector(logs, o.echo ?? true);
|
|
90
|
+
const signal = o.signal ?? new AbortController().signal;
|
|
90
91
|
const ctx = {
|
|
91
92
|
params: req.params ?? {}, record, api: stagingApi(scopedApi(o.api ?? createClient(o.token ? { token: o.token } : {}), req.shop), handed), logger,
|
|
92
|
-
model: req.model, action: req.action, environment: req.environment, signal
|
|
93
|
+
model: req.model, action: req.action, environment: req.environment, signal,
|
|
93
94
|
caller: req.caller ?? null, shop: req.shop ?? null, shopify: req.shop ? (o.shopify?.(req.shop) ?? createShopifyClient(req.shop, { ...(o.token ? { token: o.token } : {}), ...(req.background ? { priority: "background" } : {}) })) : null,
|
|
95
|
+
ai: o.ai ?? createAiClient({ ...(o.token ? { token: o.token } : {}), ...(req.event ? { event: req.event } : {}), signal }),
|
|
94
96
|
};
|
|
95
97
|
if (req.phase === "onSuccess") {
|
|
96
98
|
await mod.onSuccess?.(ctx);
|
package/dist/test.d.ts
CHANGED
|
@@ -12,8 +12,8 @@
|
|
|
12
12
|
* `timeoutMS`. Calls run as the system unless a test says who they're for (`runAs`, `api.asRole`, `api.forShop`), and
|
|
13
13
|
* are then held to accessControl/permissions.ib.ts and the store as the API holds them (packages/apps/src/access.ts).
|
|
14
14
|
* Webhook entries' `filter`s are applied as Shopify applies them, and `queueSchedules` queues what settings.ib.ts's
|
|
15
|
-
* schedules owe in a window of time. Computed fields are worked out as records.ts's SQL works them out
|
|
16
|
-
*
|
|
15
|
+
* schedules owe in a window of time. Computed fields are worked out as records.ts's SQL works them out, and a read's
|
|
16
|
+
* `select` follows belongsTo, hasOne, hasMany and hasManyThrough as the API's does.
|
|
17
17
|
*
|
|
18
18
|
* File fields keep their files in memory: `base64` reads back as a `data:` URL, `copyURL` as the URL itself (not
|
|
19
19
|
* fetched, size 0), and `upload`/`createUpload` tokens as the upload (a `createUpload` needs no PUT here).
|
|
@@ -37,6 +37,26 @@ export interface ShopifyMock {
|
|
|
37
37
|
on(match: string | RegExp, answer: ShopifyAnswer): ShopifyMock;
|
|
38
38
|
calls: ShopifyCall[];
|
|
39
39
|
}
|
|
40
|
+
/** A chat call an action made through its `ai` client: the model, the messages, and the last user message's text. */
|
|
41
|
+
export interface AiCall {
|
|
42
|
+
model: string;
|
|
43
|
+
messages: {
|
|
44
|
+
role: string;
|
|
45
|
+
content: unknown;
|
|
46
|
+
}[];
|
|
47
|
+
prompt: string;
|
|
48
|
+
body: Record<string, unknown>;
|
|
49
|
+
}
|
|
50
|
+
/** The reply's text, or a function of the call returning it; a function that throws fails the call. */
|
|
51
|
+
export type AiAnswer = string | ((call: AiCall) => string | Promise<string>);
|
|
52
|
+
export interface AiMock {
|
|
53
|
+
/**
|
|
54
|
+
* Answers chat calls whose last user message contains `match` (or matches the RegExp) with `answer`, through
|
|
55
|
+
* `ai.generateText` and the AI SDK alike, streamed or not. The latest match wins. `ai.embed` uses the test app's `embed`.
|
|
56
|
+
*/
|
|
57
|
+
on(match: string | RegExp, answer: AiAnswer): AiMock;
|
|
58
|
+
calls: AiCall[];
|
|
59
|
+
}
|
|
40
60
|
/**
|
|
41
61
|
* Shopify's webhook payloads (REST-shaped, as deliveries arrive), filled with believable values. Pass what the test
|
|
42
62
|
* cares about; the rest is made up. Ids are unique within the test run.
|
|
@@ -287,11 +307,13 @@ export interface TestApp {
|
|
|
287
307
|
to?: Date | string | number;
|
|
288
308
|
}): Promise<Job[]>;
|
|
289
309
|
shopify: ShopifyMock;
|
|
310
|
+
/** The gateway, mocked: what an action's `ai` answers. */
|
|
311
|
+
ai: AiMock;
|
|
290
312
|
/** Everything every action logged, in order. */
|
|
291
313
|
logs: (LogLine & {
|
|
292
314
|
action: string;
|
|
293
315
|
})[];
|
|
294
|
-
/** Empties the records, jobs, logs and
|
|
316
|
+
/** Empties the records, jobs, logs, Shopify and AI calls (mocks stay), e.g. in beforeEach. */
|
|
295
317
|
reset(): void;
|
|
296
318
|
}
|
|
297
319
|
export declare function createTestApp(o?: TestAppOptions): TestApp;
|
package/dist/test.js
CHANGED
|
@@ -12,13 +12,13 @@
|
|
|
12
12
|
* `timeoutMS`. Calls run as the system unless a test says who they're for (`runAs`, `api.asRole`, `api.forShop`), and
|
|
13
13
|
* are then held to accessControl/permissions.ib.ts and the store as the API holds them (packages/apps/src/access.ts).
|
|
14
14
|
* Webhook entries' `filter`s are applied as Shopify applies them, and `queueSchedules` queues what settings.ib.ts's
|
|
15
|
-
* schedules owe in a window of time. Computed fields are worked out as records.ts's SQL works them out
|
|
16
|
-
*
|
|
15
|
+
* schedules owe in a window of time. Computed fields are worked out as records.ts's SQL works them out, and a read's
|
|
16
|
+
* `select` follows belongsTo, hasOne, hasMany and hasManyThrough as the API's does.
|
|
17
17
|
*
|
|
18
18
|
* File fields keep their files in memory: `base64` reads back as a `data:` URL, `copyURL` as the URL itself (not
|
|
19
19
|
* fetched, size 0), and `upload`/`createUpload` tokens as the upload (a `createUpload` needs no PUT here).
|
|
20
20
|
*/
|
|
21
|
-
import { ApiError, ShopifyError, newRecordId } from "./index.js";
|
|
21
|
+
import { ApiError, ShopifyError, createAiClient, newRecordId } from "./index.js";
|
|
22
22
|
import { runAction as runPhase } from "./runtime.js";
|
|
23
23
|
/** Kept in `data`; the rest are a vector, the other side of a relationship, or worked out (computed). */
|
|
24
24
|
const STORED = new Set(["string", "richText", "email", "url", "color", "number", "dateTime", "enum", "boolean", "roleList", "json", "belongsTo", "password", "encryptedString", "file"]);
|
|
@@ -37,6 +37,8 @@ function modelOf(name, schema) {
|
|
|
37
37
|
throw new Error(`${name}: two fields store their values under ${dup.key}; give ${dup.name} its own storageKey`);
|
|
38
38
|
return { name, fields, byName: new Map(fields.map((f) => [f.name, f])) };
|
|
39
39
|
}
|
|
40
|
+
const RELATIONSHIPS = new Set(["belongsTo", "hasOne", "hasMany", "hasManyThrough"]);
|
|
41
|
+
const both = (a, b) => (a && b ? { AND: [a, b] } : a ?? b);
|
|
40
42
|
const ok = (value) => ({ ok: true, value });
|
|
41
43
|
const bad = (message) => ({ ok: false, message });
|
|
42
44
|
const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
@@ -526,10 +528,14 @@ class Records {
|
|
|
526
528
|
return new Map([...this.rows].map(([m, t]) => [m, new Map([...t].map(([id, r]) => [id, { ...r, vectors: new Map(r.vectors) }]))]));
|
|
527
529
|
}
|
|
528
530
|
restore(rows) { this.rows = rows; }
|
|
529
|
-
present(m, row, vectors) {
|
|
530
|
-
const out = { id: row.id
|
|
531
|
+
present(m, row, vectors, only = null) {
|
|
532
|
+
const out = { id: row.id };
|
|
533
|
+
if (!only || only.has("createdAt"))
|
|
534
|
+
out.createdAt = row.createdAt;
|
|
535
|
+
if (!only || only.has("updatedAt"))
|
|
536
|
+
out.updatedAt = row.updatedAt;
|
|
531
537
|
for (const f of m.fields) {
|
|
532
|
-
if (f.type === "password")
|
|
538
|
+
if (f.type === "password" || (only && !only.has(f.name)))
|
|
533
539
|
continue;
|
|
534
540
|
if (f.type === "vector") {
|
|
535
541
|
const v = row.vectors.get(f.key);
|
|
@@ -554,10 +560,13 @@ class Records {
|
|
|
554
560
|
}
|
|
555
561
|
return out;
|
|
556
562
|
}
|
|
557
|
-
findOne(model, id) {
|
|
563
|
+
findOne(model, id, o = {}) {
|
|
558
564
|
const m = this.model(model);
|
|
565
|
+
const plan = this.plan(m, o.select);
|
|
559
566
|
const row = this.table(m).get(id);
|
|
560
|
-
|
|
567
|
+
if (!row)
|
|
568
|
+
return null;
|
|
569
|
+
return plan ? this.selected(m, row, plan, o.readable, { left: 5000 }, false) : this.present(m, row, true);
|
|
561
570
|
}
|
|
562
571
|
/** Every record, oldest first. */
|
|
563
572
|
all(model) {
|
|
@@ -618,7 +627,9 @@ class Records {
|
|
|
618
627
|
};
|
|
619
628
|
}
|
|
620
629
|
childrenOf(m, rel) {
|
|
621
|
-
const
|
|
630
|
+
const at = rel.type === "hasOne" ? "child" : "children";
|
|
631
|
+
const v = rel.def[at];
|
|
632
|
+
const to = isObj(v) ? v : {};
|
|
622
633
|
const cm = typeof to.model === "string" ? this.models.get(to.model) : undefined;
|
|
623
634
|
if (!cm)
|
|
624
635
|
throw new Error(`${rel.name} points at ${typeof to.model === "string" ? to.model : "no model"}, which doesn't exist`);
|
|
@@ -627,7 +638,7 @@ class Records {
|
|
|
627
638
|
const named = typeof to.belongsToField === "string" && to.belongsToField ? cm.byName.get(to.belongsToField) : undefined;
|
|
628
639
|
const link = named ?? (links.length === 1 ? links[0] : undefined);
|
|
629
640
|
if (!link || link.type !== "belongsTo") {
|
|
630
|
-
throw new Error(typeof to.belongsToField === "string" && to.belongsToField ? `${cm.name} has no belongsTo field named ${to.belongsToField}` : `${rel.name} needs
|
|
641
|
+
throw new Error(typeof to.belongsToField === "string" && to.belongsToField ? `${cm.name} has no belongsTo field named ${to.belongsToField}` : `${rel.name} needs ${at}.belongsToField: the field on ${cm.name} that points back`);
|
|
631
642
|
}
|
|
632
643
|
return { model: cm, link };
|
|
633
644
|
}
|
|
@@ -889,6 +900,7 @@ class Records {
|
|
|
889
900
|
}
|
|
890
901
|
async findMany(model, o = {}) {
|
|
891
902
|
const m = this.model(model);
|
|
903
|
+
const plan = this.plan(m, o.select);
|
|
892
904
|
const first = Math.min(Math.max(1, Math.floor(o.first ?? 50)), MAX_PAGE);
|
|
893
905
|
const offset = offsetOf(o.after);
|
|
894
906
|
let rows = [...this.table(m).values()].filter((r) => this.matches(m, r, o.filter));
|
|
@@ -925,8 +937,10 @@ class Records {
|
|
|
925
937
|
else
|
|
926
938
|
rows = this.sorted(m, rows, o.sort);
|
|
927
939
|
const page = rows.slice(offset, offset + first);
|
|
940
|
+
const budget = { left: 5000 };
|
|
941
|
+
const read = (r) => (plan ? this.selected(m, r, plan, o.readable, budget, false) : this.present(m, r, false));
|
|
928
942
|
return {
|
|
929
|
-
records: page.map((r) => (distances ? { ...
|
|
943
|
+
records: page.map((r) => (distances ? { ...read(r), _distance: distances.get(r.id) } : read(r))),
|
|
930
944
|
hasNextPage: rows.length > offset + first,
|
|
931
945
|
endCursor: page.length ? cursorOf(offset + page.length) : null,
|
|
932
946
|
};
|
|
@@ -935,6 +949,128 @@ class Records {
|
|
|
935
949
|
const m = this.model(model);
|
|
936
950
|
return [...this.table(m).values()].filter((r) => this.matches(m, r, filter)).length;
|
|
937
951
|
}
|
|
952
|
+
// ---- select (records.ts: planOf, attach) ----
|
|
953
|
+
/** A select checked against the model, as records.ts's planOf checks it; null when unset. */
|
|
954
|
+
plan(m, select, path = "select", depth = 0) {
|
|
955
|
+
if (select === undefined || select === null)
|
|
956
|
+
return null;
|
|
957
|
+
const wrong = (field, message) => invalid([{ field, message }]);
|
|
958
|
+
if (!isObj(select))
|
|
959
|
+
throw wrong(path, "must be an object of field names, like { title: true }");
|
|
960
|
+
const fields = new Set();
|
|
961
|
+
const relations = [];
|
|
962
|
+
for (const [name, v] of Object.entries(select)) {
|
|
963
|
+
const at = `${path}.${name}`;
|
|
964
|
+
const f = m.byName.get(name);
|
|
965
|
+
if (!f && !SYSTEM.includes(name))
|
|
966
|
+
throw wrong(at, `${m.name} has no field named ${name}`);
|
|
967
|
+
if (f?.type === "password")
|
|
968
|
+
throw wrong(at, "password fields are never read");
|
|
969
|
+
if (!f || !RELATIONSHIPS.has(f.type)) {
|
|
970
|
+
if (v !== true)
|
|
971
|
+
throw wrong(at, "takes true");
|
|
972
|
+
fields.add(name);
|
|
973
|
+
continue;
|
|
974
|
+
}
|
|
975
|
+
if (v !== true && !isObj(v))
|
|
976
|
+
throw wrong(at, "takes true, or { select } to choose its records' fields");
|
|
977
|
+
if (depth >= 3)
|
|
978
|
+
throw wrong(at, "related records can be read at most 3 relationships deep");
|
|
979
|
+
const o = v === true ? {} : v;
|
|
980
|
+
const many = f.type === "hasMany" || f.type === "hasManyThrough";
|
|
981
|
+
for (const k of Object.keys(o)) {
|
|
982
|
+
if (k === "select" || (many && (k === "filter" || k === "sort" || k === "first")))
|
|
983
|
+
continue;
|
|
984
|
+
throw wrong(`${at}.${k}`, many ? "isn't an option; use select, filter, sort or first" : `isn't an option; a ${f.type} takes select`);
|
|
985
|
+
}
|
|
986
|
+
if (o.first !== undefined && (typeof o.first !== "number" || !Number.isInteger(o.first) || o.first < 1 || o.first > MAX_PAGE))
|
|
987
|
+
throw wrong(`${at}.first`, `must be 1 to ${MAX_PAGE}`);
|
|
988
|
+
let rel;
|
|
989
|
+
try {
|
|
990
|
+
rel = this.relatedOf(m, f);
|
|
991
|
+
}
|
|
992
|
+
catch (e) {
|
|
993
|
+
throw wrong(at, e.message);
|
|
994
|
+
}
|
|
995
|
+
if (f.type === "belongsTo")
|
|
996
|
+
fields.add(name);
|
|
997
|
+
const probe = { id: "", createdAt: "", updatedAt: "", data: {}, vectors: new Map() };
|
|
998
|
+
try {
|
|
999
|
+
this.matches(rel.target, probe, o.filter);
|
|
1000
|
+
this.sorted(rel.target, [], o.sort);
|
|
1001
|
+
}
|
|
1002
|
+
catch (e) {
|
|
1003
|
+
if (e instanceof ApiError)
|
|
1004
|
+
throw invalid(e.problems.map((p) => ({ field: `${at}.${p.field}`, message: p.message })));
|
|
1005
|
+
throw e;
|
|
1006
|
+
}
|
|
1007
|
+
relations.push({
|
|
1008
|
+
field: f, ...rel, filter: o.filter, sort: o.sort,
|
|
1009
|
+
first: f.type === "hasOne" ? 1 : (o.first ?? 50), plan: this.plan(rel.target, o.select ?? undefined, `${at}.select`, depth + 1),
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
return { fields, relations };
|
|
1013
|
+
}
|
|
1014
|
+
relatedOf(m, f) {
|
|
1015
|
+
const parentOf = (x) => (isObj(x.def.parent) && typeof x.def.parent.model === "string" ? x.def.parent.model : null);
|
|
1016
|
+
if (f.type === "belongsTo") {
|
|
1017
|
+
const target = this.models.get(parentOf(f) ?? "");
|
|
1018
|
+
if (!target)
|
|
1019
|
+
throw new Error(`${f.name} points at ${parentOf(f) ?? "no model"}, which doesn't exist`);
|
|
1020
|
+
return { target, link: null, join: null };
|
|
1021
|
+
}
|
|
1022
|
+
if (f.type === "hasOne" || f.type === "hasMany") {
|
|
1023
|
+
const c = this.childrenOf(m, f);
|
|
1024
|
+
return { target: c.model, link: c.link, join: null };
|
|
1025
|
+
}
|
|
1026
|
+
const t = isObj(f.def.through) ? f.def.through : {};
|
|
1027
|
+
const jm = typeof t.model === "string" ? this.models.get(t.model) : undefined;
|
|
1028
|
+
if (!jm)
|
|
1029
|
+
throw new Error(`${f.name} goes through ${typeof t.model === "string" ? t.model : "no model"}, which doesn't exist`);
|
|
1030
|
+
const links = jm.fields.filter((x) => x.type === "belongsTo");
|
|
1031
|
+
const named = (k) => (typeof t[k] === "string" && t[k] ? jm.byName.get(t[k]) : undefined);
|
|
1032
|
+
const one = (xs) => (xs.length === 1 ? xs[0] : undefined);
|
|
1033
|
+
const self = named("belongsToSelfField") ?? one(links.filter((x) => parentOf(x) === m.name));
|
|
1034
|
+
if (!self || self.type !== "belongsTo")
|
|
1035
|
+
throw new Error(`${f.name} needs through.belongsToSelfField: the field on ${jm.name} that points at ${m.name}`);
|
|
1036
|
+
const sibling = named("belongsToSiblingField") ?? one(links.filter((x) => x !== self));
|
|
1037
|
+
if (!sibling || sibling.type !== "belongsTo")
|
|
1038
|
+
throw new Error(`${f.name} needs through.belongsToSiblingField: the field on ${jm.name} that points at the records it reaches`);
|
|
1039
|
+
const target = this.models.get(parentOf(sibling) ?? "");
|
|
1040
|
+
if (!target)
|
|
1041
|
+
throw new Error(`${jm.name}.${sibling.name} points at ${parentOf(sibling) ?? "no model"}, which doesn't exist`);
|
|
1042
|
+
return { target, link: null, join: { model: jm, self, sibling } };
|
|
1043
|
+
}
|
|
1044
|
+
/** A row as `plan` reads it, with its related records through `readable` (the caller's filter for each model). */
|
|
1045
|
+
selected(m, row, plan, readable, budget, vectors) {
|
|
1046
|
+
const out = this.present(m, row, vectors || m.fields.some((f) => f.type === "vector" && plan.fields.has(f.name)), plan.fields);
|
|
1047
|
+
for (const rel of plan.relations) {
|
|
1048
|
+
const filter = both(readable?.(rel.target), rel.filter);
|
|
1049
|
+
const t = rel.target;
|
|
1050
|
+
let rows;
|
|
1051
|
+
if (rel.link)
|
|
1052
|
+
rows = this.sorted(t, [...this.table(t).values()].filter((r) => r.data[rel.link.key] === row.id && this.matches(t, r, filter)), rel.sort);
|
|
1053
|
+
else if (rel.join) {
|
|
1054
|
+
const { model: jm, self, sibling } = rel.join;
|
|
1055
|
+
const jf = readable?.(jm);
|
|
1056
|
+
const reached = [...this.table(jm).values()].filter((j) => j.data[self.key] === row.id && this.matches(jm, j, jf))
|
|
1057
|
+
.map((j) => this.table(t).get(j.data[sibling.key])).filter((r) => !!r && this.matches(t, r, filter));
|
|
1058
|
+
rows = this.sorted(t, reached, rel.sort);
|
|
1059
|
+
}
|
|
1060
|
+
else {
|
|
1061
|
+
const id = out[rel.field.name];
|
|
1062
|
+
const r = typeof id === "string" ? this.table(t).get(id) : undefined;
|
|
1063
|
+
rows = r && this.matches(t, r, filter) ? [r] : [];
|
|
1064
|
+
}
|
|
1065
|
+
const kept = rows.slice(0, rel.first + 1);
|
|
1066
|
+
budget.left -= kept.length;
|
|
1067
|
+
if (budget.left < 0)
|
|
1068
|
+
throw invalid([{ field: `select.${rel.field.name}`, message: "reads more than 5000 related records in all; ask for fewer with first" }]);
|
|
1069
|
+
const read = kept.slice(0, rel.first).map((r) => (rel.plan ? this.selected(t, r, rel.plan, readable, budget, false) : this.present(t, r, false)));
|
|
1070
|
+
out[rel.field.name] = rel.field.type === "hasMany" || rel.field.type === "hasManyThrough" ? { records: read, hasNextPage: kept.length > rel.first } : read[0] ?? null;
|
|
1071
|
+
}
|
|
1072
|
+
return out;
|
|
1073
|
+
}
|
|
938
1074
|
// ---- writing ----
|
|
939
1075
|
prepare(m, params, current) {
|
|
940
1076
|
if (!isObj(params))
|
|
@@ -1160,6 +1296,56 @@ function shopifyMock() {
|
|
|
1160
1296
|
};
|
|
1161
1297
|
return mock;
|
|
1162
1298
|
}
|
|
1299
|
+
const textOf = (content) => typeof content === "string" ? content
|
|
1300
|
+
: Array.isArray(content) ? content.map((p) => (p && typeof p === "object" && typeof p.text === "string" ? p.text : "")).join("") : "";
|
|
1301
|
+
/** The gateway as the test app's `ai` sees it: chat completions answered from `on`'s handlers, embeddings by `embed`. */
|
|
1302
|
+
function aiMock(embed) {
|
|
1303
|
+
const handlers = [];
|
|
1304
|
+
const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "x-request-id": "req_test" } });
|
|
1305
|
+
const refuse = (status, message) => json(status, { error: { code: "invalid_request", message } });
|
|
1306
|
+
const serve = async (input, init = {}) => {
|
|
1307
|
+
const path = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url).pathname;
|
|
1308
|
+
const body = JSON.parse(typeof init.body === "string" ? init.body : "{}");
|
|
1309
|
+
const model = String(body.model ?? "");
|
|
1310
|
+
if (path.endsWith("/embeddings")) {
|
|
1311
|
+
if (!embed)
|
|
1312
|
+
return refuse(400, "The test app has no embed function: pass `embed` to createTestApp or loadApp.");
|
|
1313
|
+
const texts = typeof body.input === "string" ? [body.input] : body.input;
|
|
1314
|
+
const vectors = await embed(model, texts);
|
|
1315
|
+
return json(200, { object: "list", model, data: vectors.map((embedding, index) => ({ object: "embedding", index, embedding })), usage: { prompt_tokens: 0, total_tokens: 0 } });
|
|
1316
|
+
}
|
|
1317
|
+
if (!path.endsWith("/chat/completions"))
|
|
1318
|
+
return refuse(404, `The test app's ai answers chat completions and embeddings, not ${path.replace(/^.*\/ai/, "")}. Use the chat model (ib(model) or ib.chat).`);
|
|
1319
|
+
const messages = (Array.isArray(body.messages) ? body.messages : []);
|
|
1320
|
+
const prompt = textOf([...messages].reverse().find((m) => m.role === "user")?.content);
|
|
1321
|
+
const call = { model, messages, prompt, body };
|
|
1322
|
+
mock.calls.push(call);
|
|
1323
|
+
const h = handlers.find((x) => (typeof x.match === "string" ? prompt.includes(x.match) : x.match.test(prompt)));
|
|
1324
|
+
if (!h)
|
|
1325
|
+
return refuse(400, `No mock answers this prompt; add one with app.ai.on(…): ${prompt.replace(/\s+/g, " ").trim().slice(0, 120)}`);
|
|
1326
|
+
let text;
|
|
1327
|
+
try {
|
|
1328
|
+
text = typeof h.answer === "function" ? await h.answer(call) : h.answer;
|
|
1329
|
+
}
|
|
1330
|
+
catch (e) {
|
|
1331
|
+
return refuse(400, e.message);
|
|
1332
|
+
}
|
|
1333
|
+
const usage = { prompt_tokens: Math.ceil(prompt.length / 4), completion_tokens: Math.ceil(text.length / 4), total_tokens: 0 };
|
|
1334
|
+
usage.total_tokens = usage.prompt_tokens + usage.completion_tokens;
|
|
1335
|
+
const base = { id: "chatcmpl-test", created: Math.floor(Date.now() / 1000), model };
|
|
1336
|
+
if (!body.stream)
|
|
1337
|
+
return json(200, { ...base, object: "chat.completion", choices: [{ index: 0, message: { role: "assistant", content: text }, finish_reason: "stop" }], usage });
|
|
1338
|
+
const chunk = (delta, finish, extra = {}) => `data: ${JSON.stringify({ ...base, object: "chat.completion.chunk", choices: [{ index: 0, delta, finish_reason: finish }], ...extra })}\n\n`;
|
|
1339
|
+
const sse = chunk({ role: "assistant", content: text }, null) + chunk({}, "stop", { usage }) + "data: [DONE]\n\n";
|
|
1340
|
+
return new Response(sse, { status: 200, headers: { "content-type": "text/event-stream", "x-request-id": "req_test" } });
|
|
1341
|
+
};
|
|
1342
|
+
const mock = {
|
|
1343
|
+
calls: [],
|
|
1344
|
+
on(match, answer) { handlers.unshift({ match, answer }); return mock; },
|
|
1345
|
+
client: () => createAiClient({ url: "https://api.test.invalid", token: "ibenv_test", app: "test", fetch: serve }),
|
|
1346
|
+
};
|
|
1347
|
+
return mock;
|
|
1348
|
+
}
|
|
1163
1349
|
let fixtureSeq = 0;
|
|
1164
1350
|
const nextId = () => 1000 + ++fixtureSeq;
|
|
1165
1351
|
const iso = (t = Date.now()) => new Date(t).toISOString();
|
|
@@ -1712,6 +1898,7 @@ export function createTestApp(o = {}) {
|
|
|
1712
1898
|
const registry = Object.fromEntries(Object.entries(o.actions ?? {}).map(([k, m]) => [k, typeof m === "function" ? m : async () => m]));
|
|
1713
1899
|
const environment = o.environment ?? "development";
|
|
1714
1900
|
const shopify = shopifyMock();
|
|
1901
|
+
const ai = aiMock(o.embed);
|
|
1715
1902
|
const jobs = [];
|
|
1716
1903
|
const logs = [];
|
|
1717
1904
|
const perms = readPermissions(o.permissions);
|
|
@@ -1761,7 +1948,7 @@ export function createTestApp(o = {}) {
|
|
|
1761
1948
|
});
|
|
1762
1949
|
const req = { phase: p, model, action, params, record: rec, isNew, environment, shop, caller: how.caller ?? null, ...(how.background ? { background: true } : {}) };
|
|
1763
1950
|
try {
|
|
1764
|
-
return await Promise.race([runPhase(wire(req), registry, { api, shopify: shopify.client, echo: o.echo ?? false }), late]);
|
|
1951
|
+
return await Promise.race([runPhase(wire(req), registry, { api, shopify: shopify.client, ai: ai.client(), echo: o.echo ?? false }), late]);
|
|
1765
1952
|
}
|
|
1766
1953
|
finally {
|
|
1767
1954
|
clearTimeout(timer);
|
|
@@ -1821,7 +2008,7 @@ export function createTestApp(o = {}) {
|
|
|
1821
2008
|
};
|
|
1822
2009
|
const otherStore = (shop) => denied(`This call is for ${shop}; it can't reach another store's records.`);
|
|
1823
2010
|
/** The record by id when the filter lets the call see it (undefined: no narrowing), else null. */
|
|
1824
|
-
const findVisible = async (model, id, filter) => (filter ? (await store.findMany(model, { filter: { AND: [{ id: { equals: id } }, filter] }, first: 1 })).records[0] ?? null : store.findOne(model, id));
|
|
2011
|
+
const findVisible = async (model, id, filter, select, readable) => (filter ? (await store.findMany(model, { filter: { AND: [{ id: { equals: id } }, filter] }, first: 1, select, readable })).records[0] ?? null : store.findOne(model, id, { select, readable }));
|
|
1825
2012
|
/** Refuses a run the scope doesn't allow; a record its store or grant doesn't reach is answered as missing. */
|
|
1826
2013
|
async function canRun(scope, model, action, id) {
|
|
1827
2014
|
if (!isScoped(scope))
|
|
@@ -1843,7 +2030,9 @@ export function createTestApp(o = {}) {
|
|
|
1843
2030
|
const modelClient = (name, scope) => {
|
|
1844
2031
|
const scoped = isScoped(scope);
|
|
1845
2032
|
const readOf = (filter) => (scoped ? readFilter(perms, scope, store.model(name), filter) : filter);
|
|
1846
|
-
|
|
2033
|
+
// A select's related records are read through the same store and role, model by model.
|
|
2034
|
+
const readable = scoped ? (m) => readFilter(perms, scope, m) : undefined;
|
|
2035
|
+
const narrow = (q) => { const filter = readOf(q.filter); return { ...q, ...(filter ? { filter } : {}), ...(readable ? { readable } : {}) }; };
|
|
1847
2036
|
// A file goes to a record the role may make or change.
|
|
1848
2037
|
const uploadable = () => {
|
|
1849
2038
|
if (!scoped)
|
|
@@ -1857,7 +2046,7 @@ export function createTestApp(o = {}) {
|
|
|
1857
2046
|
};
|
|
1858
2047
|
return {
|
|
1859
2048
|
build: () => { throw new Error("build() makes a record for an action's run to save(); outside an action, use create()."); },
|
|
1860
|
-
findOne: async (id) => findVisible(name, id, readOf()),
|
|
2049
|
+
findOne: async (id, o = {}) => findVisible(name, id, readOf(), wire(o.select), readable),
|
|
1861
2050
|
findMany: async (q = {}) => store.findMany(name, narrow(wire(q))),
|
|
1862
2051
|
findFirst: async (q = {}) => (await store.findMany(name, { ...narrow(wire(q)), first: 1 })).records[0] ?? null,
|
|
1863
2052
|
search: async (field, near, q = {}) => (await store.findMany(name, { ...narrow(wire(q)), search: { field, near } })),
|
|
@@ -2183,8 +2372,9 @@ export function createTestApp(o = {}) {
|
|
|
2183
2372
|
return queued;
|
|
2184
2373
|
},
|
|
2185
2374
|
shopify,
|
|
2375
|
+
ai,
|
|
2186
2376
|
logs,
|
|
2187
|
-
reset() { store.clear(); jobs.length = 0; scheduled.clear(); syncRuns.length = 0; logs.length = 0; shopify.calls.length = 0; },
|
|
2377
|
+
reset() { store.clear(); jobs.length = 0; scheduled.clear(); syncRuns.length = 0; logs.length = 0; shopify.calls.length = 0; ai.calls.length = 0; },
|
|
2188
2378
|
};
|
|
2189
2379
|
}
|
|
2190
2380
|
// ---- loading an app's folder ----
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inferencebureau/apps-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.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": [
|