@inferencebureau/apps-sdk 0.2.2 → 0.4.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 CHANGED
@@ -37,6 +37,15 @@ 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;
42
+ /**
43
+ * A synced Shopify field's: `"later"` isn't written from webhooks, only by sync passes (the hourly reconcile, a
44
+ * run), which fill it even when nothing else changed; `"onWebhook"` has the record fetched from the Admin API when
45
+ * a webhook's payload doesn't carry the field (products, collections, customers, orders, draft orders). Unset, a
46
+ * webhook writes what its payload carries.
47
+ */
48
+ fetch?: "onWebhook" | "later";
40
49
  parent?: {
41
50
  model: string;
42
51
  };
@@ -150,6 +159,37 @@ export declare class ApiError extends Error {
150
159
  message: string;
151
160
  }[]);
152
161
  }
162
+ /** A file field's value as a record reads it. `url` is signed for an hour unless the field has `allowPublicAccess`. */
163
+ export interface FileValue {
164
+ url: string | null;
165
+ fileName: string;
166
+ mimeType: string;
167
+ size: number;
168
+ }
169
+ /**
170
+ * What a write gives a file field: the bytes as base64 (small files), a public https URL to copy, or the token of a
171
+ * direct upload (`createUpload` or `upload`). `null` clears it.
172
+ */
173
+ export type FileInput = {
174
+ base64: string;
175
+ fileName?: string;
176
+ mimeType?: string;
177
+ } | {
178
+ copyURL: string;
179
+ fileName?: string;
180
+ mimeType?: string;
181
+ } | {
182
+ directUploadToken: string;
183
+ fileName?: string;
184
+ };
185
+ /** A direct upload: PUT the file to `url` with `headers` within the hour, then write `{ directUploadToken: token }` within a day. */
186
+ export interface Upload {
187
+ url: string;
188
+ method: "PUT";
189
+ headers: Record<string, string>;
190
+ token: string;
191
+ expiresAt: string;
192
+ }
153
193
  export interface ModelClient {
154
194
  findOne(id: string): Promise<AppRecord | null>;
155
195
  findMany(o?: FindManyOptions): Promise<RecordPage>;
@@ -172,6 +212,22 @@ export interface ModelClient {
172
212
  record: AppRecord | null;
173
213
  result?: unknown;
174
214
  }>;
215
+ /**
216
+ * 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.
217
+ * Give `size` and the upload takes at most that many bytes.
218
+ */
219
+ createUpload(field: string, o?: {
220
+ fileName?: string;
221
+ mimeType?: string;
222
+ size?: number;
223
+ }): Promise<Upload>;
224
+ /** Uploads a file for a file field, straight to storage, and answers the value to write to the field. */
225
+ upload(field: string, body: Blob | ArrayBuffer | Uint8Array, o?: {
226
+ fileName?: string;
227
+ mimeType?: string;
228
+ }): Promise<{
229
+ directUploadToken: string;
230
+ }>;
175
231
  }
176
232
  export type Api = {
177
233
  [model: string]: ModelClient;
@@ -185,7 +241,82 @@ export type Api = {
185
241
  * `id` for the record). It gets up to five minutes, and is retried when it fails.
186
242
  */
187
243
  enqueue(action: string, params?: Record<string, unknown>, options?: EnqueueOptions): Promise<Job>;
244
+ /**
245
+ * The same API for one store: store-owned models (Shopify's, and any with a text field named `shop`) show only that
246
+ * 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.
247
+ */
248
+ forShop(shop: string): Api;
249
+ /**
250
+ * The same API held to a role in accessControl/permissions.ib.ts: only what the role is granted, through its
251
+ * filters, with `session` standing in for `{ $session: "userId" | "customerId" }`. A Shopify session's and a proxy
252
+ * request's `api` already are.
253
+ */
254
+ asRole(role: string, session?: CallerSession): Api;
255
+ /** Shopify sync on demand: one store, some or all of its synced models, everything or what changed since a date. */
256
+ shopifySync: ShopifySync;
188
257
  };
258
+ export interface SyncRunOptions {
259
+ /** The store (x.myshopify.com); an `api.forShop(shop)` client's own store when left out. */
260
+ shop?: string;
261
+ /** Synced models by name (a child brings its parent: shopifyProductVariant syncs products); all of them when unset. */
262
+ models?: string[];
263
+ /** Only records Shopify changed after this; everything when unset. */
264
+ since?: string | Date;
265
+ /** Run each model's create, update and delete actions for what the run writes (default true). */
266
+ runActions?: boolean;
267
+ /** Write every record, even ones Shopify hasn't changed since the stored copy (default false). */
268
+ force?: boolean;
269
+ }
270
+ export interface SyncCounts {
271
+ created: number;
272
+ updated: number;
273
+ deleted: number;
274
+ skipped: number;
275
+ failed: number;
276
+ errors: string[];
277
+ }
278
+ export interface SyncRun {
279
+ id: string;
280
+ shop: string;
281
+ models: string[] | null;
282
+ since: string | null;
283
+ runActions: boolean;
284
+ force: boolean;
285
+ /** A run whose function stopped without finishing reads as failed. */
286
+ state: "running" | "succeeded" | "failed" | "aborted";
287
+ abortRequested: boolean;
288
+ /** What it wrote, by model, once it's done. */
289
+ counts: Record<string, SyncCounts> | null;
290
+ error: string | null;
291
+ actor: string;
292
+ source: string;
293
+ createdAt: string;
294
+ heartbeatAt: string;
295
+ finishedAt: string | null;
296
+ }
297
+ export interface ShopifySync {
298
+ /** Starts a run and returns it at once, `running`; one store runs one at a time. Pass `wait` to resolve once it's done. */
299
+ run(o: SyncRunOptions & {
300
+ wait?: boolean | {
301
+ timeoutMs?: number;
302
+ intervalMs?: number;
303
+ };
304
+ }): Promise<SyncRun>;
305
+ get(id: string): Promise<SyncRun | null>;
306
+ /** Runs, newest first; one store's with `shop`. */
307
+ list(o?: {
308
+ shop?: string;
309
+ limit?: number;
310
+ }): Promise<SyncRun[]>;
311
+ /** Stops a running run before its next page; what it wrote stays. */
312
+ abort(id: string): Promise<SyncRun>;
313
+ }
314
+ /** Who a role-scoped call is for, filling `{ $session: … }` in permissions.ib.ts filters. */
315
+ export interface CallerSession {
316
+ userId?: string | null;
317
+ customerId?: string | null;
318
+ customerRecordId?: string | null;
319
+ }
189
320
  export interface EnqueueOptions {
190
321
  /** The record a model's action works on. */
191
322
  id?: string;
@@ -221,6 +352,11 @@ export interface ClientOptions {
221
352
  app?: string;
222
353
  environment?: string;
223
354
  fetch?: typeof fetch;
355
+ /** Narrows every call to one store (see `Api.forShop`). */
356
+ shop?: string;
357
+ /** Holds every call to a role in permissions.ib.ts (see `Api.asRole`). */
358
+ role?: string;
359
+ session?: CallerSession;
224
360
  }
225
361
  /** The app's API. In an app's deployment every option comes from its environment variables. */
226
362
  export declare function createClient(o?: ClientOptions): Api;
@@ -234,13 +370,44 @@ export interface ShopifyClient {
234
370
  environment?: string;
235
371
  /** Runs an Admin GraphQL query or mutation and returns its `data`; GraphQL errors throw ShopifyError. */
236
372
  graphql<T = any>(query: string, variables?: Record<string, unknown>): Promise<T>;
373
+ /**
374
+ * The store's free trial as Inference Bureau keeps it, so it survives a reinstall (Billing's helpers use it).
375
+ * `createShopifyClient` and an action's `shopify` have it; a client of your own may leave it out.
376
+ */
377
+ trial?: {
378
+ get(): Promise<TrialRecord | null>;
379
+ /** Records the trial as started (the first start is kept). */
380
+ start(o: {
381
+ days: number;
382
+ startedAt?: string;
383
+ subscriptionId?: string;
384
+ }): Promise<TrialRecord>;
385
+ };
386
+ }
387
+ /** When a store's first trial started, and how long it was. */
388
+ export interface TrialRecord {
389
+ shop: string;
390
+ startedAt: string;
391
+ days: number;
392
+ subscriptionId: string | null;
237
393
  }
238
394
  export declare class ShopifyError extends Error {
239
395
  readonly errors: unknown[];
240
396
  constructor(message: string, errors: unknown[]);
397
+ /** Shopify was still throttling the store after Inference Bureau waited and tried again. */
398
+ get throttled(): boolean;
399
+ }
400
+ export interface ShopifyClientOptions extends ClientOptions {
401
+ /**
402
+ * `"background"` for work nobody is waiting on: its calls wait until half the store's GraphQL bucket is free, so
403
+ * the embedded admin's requests keep theirs. Actions run by jobs, webhooks and schedules get it on their own.
404
+ */
405
+ priority?: "background" | "request";
406
+ /** Throttled calls Inference Bureau tries again before answering (default 5). */
407
+ maxRetries?: number;
241
408
  }
242
409
  /** The Admin API for `shop`, as the environment (the same options as createClient). */
243
- export declare function createShopifyClient(shop: string, o?: ClientOptions): ShopifyClient;
410
+ export declare function createShopifyClient(shop: string, o?: ShopifyClientOptions): ShopifyClient;
244
411
  export interface Money {
245
412
  amount: number | string;
246
413
  currencyCode: string;
@@ -265,6 +432,11 @@ export interface SubscriptionRequest {
265
432
  replacementBehavior?: "APPLY_IMMEDIATELY" | "APPLY_ON_NEXT_BILLING_CYCLE" | "STANDARD";
266
433
  /** Force a test charge, or (in production on a real store only) a real one. */
267
434
  test?: boolean;
435
+ /**
436
+ * With `trialDays`: offer only what's left of the store's first trial, so uninstalling and reinstalling doesn't
437
+ * start another (default true). The trial runs from when it first started, installed or not.
438
+ */
439
+ trackTrial?: boolean;
268
440
  }
269
441
  export interface AppSubscription {
270
442
  id: string;
@@ -310,7 +482,13 @@ export declare function requestSubscription(shopify: ShopifyClient, plan: Subscr
310
482
  confirmationUrl: string;
311
483
  subscriptionId: string;
312
484
  test: boolean;
485
+ trialDays?: number;
313
486
  }>;
487
+ /**
488
+ * Days left of a `days`-day trial for the client's store: all of them before its first trial, else what's left of
489
+ * the window since that one started (reinstalling doesn't reset it). `days` when the client can't say.
490
+ */
491
+ export declare function trialDaysLeft(shopify: ShopifyClient, days: number, now?: number): Promise<number>;
314
492
  /** The store's active subscriptions to this app (usually one), with each line's price or usage cap and balance. */
315
493
  export declare function activeSubscriptions(shopify: ShopifyClient): Promise<AppSubscription[]>;
316
494
  /**
@@ -338,6 +516,91 @@ export declare function cancelSubscription(shopify: ShopifyClient, id: string, o
338
516
  * to pick or change their plan. `appHandle` is the app's handle in the Partner Dashboard.
339
517
  */
340
518
  export declare function managedPricingUrl(shop: string, appHandle: string): string;
519
+ /** The plan a store is on: its active subscription's name, and whether it's still in its trial. */
520
+ export interface CurrentPlan {
521
+ name: string;
522
+ /** ACTIVE, or another of Shopify's statuses only when asked for (`statuses`). */
523
+ status: string;
524
+ subscriptionId: string;
525
+ test: boolean;
526
+ inTrial: boolean;
527
+ /** When the trial ends, or null without one. */
528
+ trialEndsAt: string | null;
529
+ currentPeriodEnd: string | null;
530
+ /** Read from the synced shopifyAppSubscription model, or asked of Shopify. */
531
+ source: "synced" | "shopify";
532
+ }
533
+ /**
534
+ * The store's current plan, or null when it has no active subscription. With `api`, read from the synced
535
+ * shopifyAppSubscription model when the app syncs it (no Admin API call); otherwise, or when it isn't synced, asked
536
+ * of Shopify. A trial is measured from the store's first one (see `trialDaysLeft`), which this records when it sees
537
+ * one running that Inference Bureau hadn't.
538
+ */
539
+ export declare function currentPlan(shopify: ShopifyClient, o?: {
540
+ api?: Api;
541
+ now?: number;
542
+ }): Promise<CurrentPlan | null>;
543
+ /** A store without the plan a route or action needs. `status` is 402; `toResponse()` answers it as JSON. */
544
+ export declare class PlanRequiredError extends Error {
545
+ readonly plans: string[];
546
+ readonly current: CurrentPlan | null;
547
+ readonly status = 402;
548
+ constructor(message: string, plans: string[], current: CurrentPlan | null);
549
+ toResponse(): Response;
550
+ }
551
+ /**
552
+ * The store's plan when it's one of `plans` (by name, any case), or any active plan when `plans` is empty; else
553
+ * throws PlanRequiredError. `allowTrial: false` refuses a plan still in its trial. In an action, pass its `shopify`;
554
+ * in a route, `createShopifyClient(session.shop)`.
555
+ *
556
+ * const plan = await requirePlan(shopify, ["Pro", "Plus"], { api });
557
+ */
558
+ export declare function requirePlan(shopify: ShopifyClient | null, plans?: string | string[], o?: {
559
+ api?: Api;
560
+ allowTrial?: boolean;
561
+ now?: number;
562
+ }): Promise<CurrentPlan>;
563
+ export interface PurchaseRequest {
564
+ /** What the merchant sees on Shopify's approval page and their bill. */
565
+ name: string;
566
+ price: Money;
567
+ /** Where Shopify sends the merchant after they approve or decline. */
568
+ returnUrl: string;
569
+ test?: boolean;
570
+ }
571
+ export interface OneTimePurchase {
572
+ id: string;
573
+ name: string;
574
+ status: string;
575
+ test: boolean;
576
+ createdAt: string;
577
+ price: Money;
578
+ }
579
+ /**
580
+ * A one-time charge (a setup fee, a pack of credits, a lifetime unlock): returns Shopify's `confirmationUrl` for the
581
+ * merchant to approve, as `requestSubscription` does. It's paid once its status is ACTIVE (`oneTimePurchases`).
582
+ */
583
+ export declare function requestPurchase(shopify: ShopifyClient, p: PurchaseRequest): Promise<{
584
+ confirmationUrl: string;
585
+ purchaseId: string;
586
+ test: boolean;
587
+ }>;
588
+ /** The store's one-time purchases of this app, newest first (the latest 50). */
589
+ export declare function oneTimePurchases(shopify: ShopifyClient): Promise<OneTimePurchase[]>;
590
+ /** Whether the store has paid for the one-time purchase of this name (status ACTIVE). */
591
+ export declare function hasPurchased(shopify: ShopifyClient, name: string): Promise<boolean>;
592
+ /**
593
+ * Credits the store against its future app charges (a refund, a goodwill gesture). Shopify takes it off what the
594
+ * store next owes the app; it's never paid out. A test credit outside production or on a development store.
595
+ */
596
+ export declare function grantCredit(shopify: ShopifyClient, c: {
597
+ description: string;
598
+ amount: Money;
599
+ test?: boolean;
600
+ }): Promise<{
601
+ id: string;
602
+ test: boolean;
603
+ }>;
341
604
  export interface ShopifySession {
342
605
  /** The store the admin page is open in (x.myshopify.com). */
343
606
  shop: string;
@@ -348,6 +611,8 @@ export interface ShopifySession {
348
611
  preview?: {
349
612
  actor: string;
350
613
  };
614
+ /** The app's API for this staff member: the store's records only, as the `shopify-app-users` role. */
615
+ api: Api;
351
616
  }
352
617
  /**
353
618
  * The store and staff member behind a request from one of the app's pages in the Shopify admin, or null when it
@@ -363,16 +628,51 @@ export interface ProxyRequest {
363
628
  customerId: string | null;
364
629
  /** Where the storefront reached the app, e.g. /apps/wholesale. */
365
630
  pathPrefix: string;
631
+ /** The app's API for this shopper: the store's records only, as the `storefront-shoppers` role. */
632
+ api: Api;
366
633
  }
367
634
  /**
368
- * A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or null for
369
- * anything else. Shopify's own signature was checked before it was passed on; this checks ours, so only a real
370
- * storefront request is trusted with a shop and customer.
635
+ * A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or from a
636
+ * customer account extension (web/app/extension/, `pathPrefix` "/extension"), or null for anything else. Shopify's
637
+ * own signature (the extension's session token) was checked before it was passed on; this checks ours, so only a
638
+ * real storefront request is trusted with a shop and customer.
371
639
  */
372
640
  export declare function verifyProxyRequest(request: Request, o?: {
373
641
  token?: string;
374
642
  now?: () => number;
375
- }): Promise<ProxyRequest | null>;
643
+ } & Omit<ClientOptions, "token" | "shop" | "role" | "session">): Promise<ProxyRequest | null>;
644
+ /** A signed-in storefront customer, from the app proxy or a customer account extension. */
645
+ export interface StorefrontCustomer {
646
+ shop: string;
647
+ /** Their Shopify id, as the app proxy gives it (numeric), and as a gid. */
648
+ customerId: string;
649
+ customerGid: string;
650
+ /**
651
+ * Their synced shopifyCustomer record, made now if the sync hadn't brought it yet (a customer who just signed up).
652
+ * Null when the app doesn't sync customers or the store hasn't granted read_customers.
653
+ */
654
+ customer: AppRecord | null;
655
+ /** The app proxy (web/app/proxy/) or a customer account extension (web/app/extension/). */
656
+ source: "proxy" | "extension";
657
+ /**
658
+ * The app's API for this customer, as the `storefront-customers` role: the store's records only, what the role is
659
+ * granted in permissions.ib.ts, and of models that belong to a customer (a `belongsTo` shopifyCustomer, the
660
+ * customer record itself, synced orders), only theirs; new ones are made as theirs. Actions it runs see `caller`.
661
+ */
662
+ api: Api;
663
+ }
664
+ /**
665
+ * The signed-in customer behind a storefront request (the app proxy, or a customer account extension), or null for a
666
+ * guest or anything that isn't a storefront request. Their shopifyCustomer record comes with them.
667
+ *
668
+ * const me = await verifyCustomerRequest(request);
669
+ * if (!me) return Response.json({ error: "Sign in to see your wishlist." }, { status: 401 });
670
+ * const items = await me.api.wishlistItem.findMany(); // theirs only
671
+ */
672
+ export declare function verifyCustomerRequest(request: Request, o?: {
673
+ token?: string;
674
+ now?: () => number;
675
+ } & Omit<ClientOptions, "token" | "shop" | "role" | "session">): Promise<StorefrontCustomer | null>;
376
676
  export interface LogLine {
377
677
  level: "debug" | "info" | "warn" | "error";
378
678
  message: string;
@@ -400,6 +700,18 @@ export interface ActionContext {
400
700
  /** The store this run is about (an install, a webhook, or the caller's `shop`), and the Admin API for it. */
401
701
  shop: string | null;
402
702
  shopify: ShopifyClient | null;
703
+ /**
704
+ * Who called, when the call was held to a role: a signed-in storefront customer (verifyCustomerRequest's `api`),
705
+ * staff in the store's admin (verifyShopifySession's), a shopper. Null for the app's own calls, webhooks and jobs.
706
+ */
707
+ caller: ActionCaller | null;
708
+ }
709
+ export interface ActionCaller {
710
+ role: string;
711
+ userId?: string | null;
712
+ /** A storefront customer's Shopify id (numeric), and their shopifyCustomer record's id when the app syncs customers. */
713
+ customerId?: string | null;
714
+ customerRecordId?: string | null;
403
715
  }
404
716
  export type ActionRun = (ctx: ActionContext) => unknown | Promise<unknown>;
405
717
  export type ActionOnSuccess = (ctx: ActionContext) => void | Promise<void>;
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, ...(o.session.customerRecordId ? { customerRecordId: o.session.customerRecordId } : {}) }) } : {}),
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,63 @@ 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 sync = "/shopify/sync";
142
+ const getRun = async (id) => {
143
+ try {
144
+ return await call("GET", `${sync}/${encodeURIComponent(id)}`);
145
+ }
146
+ catch (e) {
147
+ if (e instanceof ApiError && e.status === 404)
148
+ return null;
149
+ throw e;
150
+ }
151
+ };
152
+ const shopifySync = {
153
+ async run({ wait, since, ...r }) {
154
+ let run = await call("POST", sync, { ...r, ...(since !== undefined ? { since: since instanceof Date ? since.toISOString() : since } : {}) });
155
+ if (!wait)
156
+ return run;
157
+ const { timeoutMs = 10 * 60_000, intervalMs = 2_000 } = wait === true ? {} : wait;
158
+ for (const end = Date.now() + timeoutMs; run.state === "running" && Date.now() < end;) {
159
+ await new Promise((done) => setTimeout(done, intervalMs));
160
+ run = (await getRun(run.id)) ?? run;
161
+ }
162
+ return run;
163
+ },
164
+ get: getRun,
165
+ list: async (q = {}) => (await call("GET", `${sync}?${new URLSearchParams({ ...(q.shop ? { shop: q.shop } : {}), ...(q.limit ? { limit: String(q.limit) } : {}) })}`)).data,
166
+ abort: (id) => call("POST", `${sync}/${encodeURIComponent(id)}/abort`),
167
+ };
168
+ const forShop = (shop) => createClient({ ...o, url, token, app, environment, fetch: f, shop });
169
+ const asRole = (role, session) => createClient({ ...o, url, token, app, environment, fetch: f, role, ...(session ? { session } : {}) });
125
170
  return new Proxy({}, {
126
171
  get(_t, prop) {
127
172
  if (prop === "$global")
128
173
  return $global;
129
174
  if (prop === "enqueue")
130
175
  return enqueue;
176
+ if (prop === "forShop")
177
+ return forShop;
178
+ if (prop === "asRole")
179
+ return asRole;
180
+ if (prop === "shopifySync")
181
+ return shopifySync;
131
182
  if (typeof prop !== "string" || prop === "then")
132
183
  return undefined;
133
184
  if (!cache.has(prop))
@@ -142,6 +193,8 @@ export class ShopifyError extends Error {
142
193
  super(message);
143
194
  this.errors = errors;
144
195
  }
196
+ /** Shopify was still throttling the store after Inference Bureau waited and tried again. */
197
+ get throttled() { return this.errors.some((e) => e?.extensions?.code === "THROTTLED"); }
145
198
  }
146
199
  /** The Admin API for `shop`, as the environment (the same options as createClient). */
147
200
  export function createShopifyClient(shop, o = {}) {
@@ -150,12 +203,24 @@ export function createShopifyClient(shop, o = {}) {
150
203
  const app = o.app ?? envVar("IB_APP") ?? "";
151
204
  const environment = o.environment ?? envVar("IB_ENVIRONMENT") ?? "development";
152
205
  const f = o.fetch ?? fetch;
206
+ const base = `${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/shopify`;
207
+ const trialCall = async (init) => {
208
+ const res = await f(`${base}/billing/trial${init.query ?? ""}`, { ...init, headers: { authorization: `Bearer ${token}`, "content-type": "application/json" } });
209
+ const json = (await res.json().catch(() => ({})));
210
+ if (!res.ok)
211
+ throw new ApiError(json.error?.message ?? `The API answered ${res.status}.`, res.status, json.error?.code ?? null);
212
+ return json.trial ?? null;
213
+ };
153
214
  return {
154
215
  shop,
155
216
  environment,
217
+ trial: {
218
+ get: () => trialCall({ method: "GET", query: `?shop=${encodeURIComponent(shop)}` }),
219
+ start: async (t) => (await trialCall({ method: "POST", body: JSON.stringify({ shop, ...t }) })),
220
+ },
156
221
  async graphql(query, variables = {}) {
157
- 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 }),
222
+ const res = await f(`${base}/graphql`, {
223
+ 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
224
  });
160
225
  const json = (await res.json().catch(() => ({})));
161
226
  if (!res.ok)
@@ -202,16 +267,27 @@ export async function requestSubscription(shopify, plan) {
202
267
  ...(plan.usage ? [{ plan: { appUsagePricingDetails: { cappedAmount: money(plan.usage.cappedAmount), terms: plan.usage.terms } } }] : []),
203
268
  ];
204
269
  const test = await isTestCharge(shopify, plan.test);
270
+ const trialDays = plan.trialDays && plan.trackTrial !== false ? await trialDaysLeft(shopify, plan.trialDays) : plan.trialDays;
205
271
  const data = await shopify.graphql(`
206
272
  mutation BillingSubscribe($name: String!, $lineItems: [AppSubscriptionLineItemInput!]!, $returnUrl: URL!, $trialDays: Int, $test: Boolean, $replacementBehavior: AppSubscriptionReplacementBehavior) {
207
273
  appSubscriptionCreate(name: $name, lineItems: $lineItems, returnUrl: $returnUrl, trialDays: $trialDays, test: $test, replacementBehavior: $replacementBehavior) {
208
274
  confirmationUrl appSubscription { id } userErrors { field message }
209
275
  }
210
- }`, { name: plan.name, lineItems, returnUrl: plan.returnUrl, trialDays: plan.trialDays ?? null, test, replacementBehavior: plan.replacementBehavior ?? null });
276
+ }`, { name: plan.name, lineItems, returnUrl: plan.returnUrl, trialDays: trialDays || null, test, replacementBehavior: plan.replacementBehavior ?? null });
211
277
  userErrorsOf("start the subscription", data.appSubscriptionCreate.userErrors);
212
278
  if (!data.appSubscriptionCreate.confirmationUrl || !data.appSubscriptionCreate.appSubscription)
213
279
  throw new ShopifyBillingError("Shopify didn't return a confirmation URL.");
214
- return { confirmationUrl: data.appSubscriptionCreate.confirmationUrl, subscriptionId: data.appSubscriptionCreate.appSubscription.id, test };
280
+ return { confirmationUrl: data.appSubscriptionCreate.confirmationUrl, subscriptionId: data.appSubscriptionCreate.appSubscription.id, test, ...(plan.trialDays ? { trialDays: trialDays ?? 0 } : {}) };
281
+ }
282
+ /**
283
+ * Days left of a `days`-day trial for the client's store: all of them before its first trial, else what's left of
284
+ * the window since that one started (reinstalling doesn't reset it). `days` when the client can't say.
285
+ */
286
+ export async function trialDaysLeft(shopify, days, now = Date.now()) {
287
+ const t = shopify.trial ? await shopify.trial.get() : null;
288
+ if (!t)
289
+ return days;
290
+ return Math.max(0, days - Math.floor((now - Date.parse(t.startedAt)) / 86_400_000));
215
291
  }
216
292
  const SUBSCRIPTION = `id name status test trialDays currentPeriodEnd createdAt
217
293
  lineItems { id plan { pricingDetails { __typename
@@ -262,6 +338,123 @@ export async function cancelSubscription(shopify, id, o = {}) {
262
338
  export function managedPricingUrl(shop, appHandle) {
263
339
  return `https://admin.shopify.com/store/${shop.replace(/\.myshopify\.com$/, "")}/charges/${encodeURIComponent(appHandle)}/pricing_plans`;
264
340
  }
341
+ const DAY = 86_400_000;
342
+ const isoPlus = (at, days) => new Date(Date.parse(at) + days * DAY).toISOString();
343
+ /**
344
+ * The store's current plan, or null when it has no active subscription. With `api`, read from the synced
345
+ * shopifyAppSubscription model when the app syncs it (no Admin API call); otherwise, or when it isn't synced, asked
346
+ * of Shopify. A trial is measured from the store's first one (see `trialDaysLeft`), which this records when it sees
347
+ * one running that Inference Bureau hadn't.
348
+ */
349
+ export async function currentPlan(shopify, o = {}) {
350
+ const now = o.now ?? Date.now();
351
+ let sub = null;
352
+ let read = false;
353
+ if (o.api) {
354
+ try {
355
+ const r = await o.api.shopifyAppSubscription.findFirst({ filter: { shop: { equals: shopify.shop }, status: { equals: "active" } }, sort: { shopifyCreatedAt: "Descending" } });
356
+ read = true;
357
+ if (r)
358
+ sub = { name: String(r.name ?? ""), status: "ACTIVE", subscriptionId: String(r.shopifyId), test: r.test === true, currentPeriodEnd: r.currentPeriodEnd ?? null, trialDays: Number(r.trialDays ?? 0), createdAt: String(r.shopifyCreatedAt ?? r.createdAt), source: "synced" };
359
+ }
360
+ catch (e) {
361
+ // Not synced: the model doesn't exist. Anything else is a real failure.
362
+ if (!(e instanceof ApiError && (e.status === 404 || e.code === "not_found")))
363
+ throw e;
364
+ }
365
+ }
366
+ if (!read) {
367
+ const [a] = await activeSubscriptions(shopify);
368
+ if (a)
369
+ sub = { name: a.name, status: a.status, subscriptionId: a.id, test: a.test, currentPeriodEnd: a.currentPeriodEnd, trialDays: a.trialDays, createdAt: a.createdAt, source: "shopify" };
370
+ }
371
+ if (!sub)
372
+ return null;
373
+ const { trialDays, createdAt, ...plan } = sub;
374
+ let trialEndsAt = null;
375
+ if (trialDays > 0) {
376
+ const t = shopify.trial ? await shopify.trial.get().catch(() => null) : null;
377
+ trialEndsAt = t ? isoPlus(t.startedAt, Math.min(t.days, trialDays)) : isoPlus(createdAt, trialDays);
378
+ if (!t && shopify.trial && Date.parse(trialEndsAt) > now)
379
+ await shopify.trial.start({ days: trialDays, startedAt: createdAt, subscriptionId: sub.subscriptionId }).catch(() => undefined);
380
+ }
381
+ return { ...plan, inTrial: !!trialEndsAt && Date.parse(trialEndsAt) > now, trialEndsAt };
382
+ }
383
+ /** A store without the plan a route or action needs. `status` is 402; `toResponse()` answers it as JSON. */
384
+ export class PlanRequiredError extends Error {
385
+ plans;
386
+ current;
387
+ status = 402;
388
+ constructor(message, plans, current) {
389
+ super(message);
390
+ this.plans = plans;
391
+ this.current = current;
392
+ }
393
+ toResponse() {
394
+ return Response.json({ error: { code: "plan_required", message: this.message, plans: this.plans, current: this.current?.name ?? null } }, { status: 402 });
395
+ }
396
+ }
397
+ /**
398
+ * The store's plan when it's one of `plans` (by name, any case), or any active plan when `plans` is empty; else
399
+ * throws PlanRequiredError. `allowTrial: false` refuses a plan still in its trial. In an action, pass its `shopify`;
400
+ * in a route, `createShopifyClient(session.shop)`.
401
+ *
402
+ * const plan = await requirePlan(shopify, ["Pro", "Plus"], { api });
403
+ */
404
+ export async function requirePlan(shopify, plans = [], o = {}) {
405
+ const want = (Array.isArray(plans) ? plans : [plans]).filter(Boolean);
406
+ if (!shopify)
407
+ throw new PlanRequiredError("This needs a store: the run has no shop.", want, null);
408
+ const plan = await currentPlan(shopify, o);
409
+ const named = want.length ? want.join(" or ") : "a plan";
410
+ if (!plan)
411
+ throw new PlanRequiredError(`${shopify.shop} needs ${named} for this.`, want, null);
412
+ if (want.length && !want.some((p) => p.toLowerCase() === plan.name.toLowerCase()))
413
+ throw new PlanRequiredError(`${shopify.shop} is on ${plan.name}; this needs ${named}.`, want, plan);
414
+ if (o.allowTrial === false && plan.inTrial)
415
+ throw new PlanRequiredError(`${shopify.shop} is still in its ${plan.name} trial; this needs a paid plan.`, want, plan);
416
+ return plan;
417
+ }
418
+ /**
419
+ * A one-time charge (a setup fee, a pack of credits, a lifetime unlock): returns Shopify's `confirmationUrl` for the
420
+ * merchant to approve, as `requestSubscription` does. It's paid once its status is ACTIVE (`oneTimePurchases`).
421
+ */
422
+ export async function requestPurchase(shopify, p) {
423
+ const test = await isTestCharge(shopify, p.test);
424
+ const data = await shopify.graphql(`
425
+ mutation BillingPurchase($name: String!, $price: MoneyInput!, $returnUrl: URL!, $test: Boolean) {
426
+ appPurchaseOneTimeCreate(name: $name, price: $price, returnUrl: $returnUrl, test: $test) { confirmationUrl appPurchaseOneTime { id } userErrors { field message } }
427
+ }`, { name: p.name, price: money(p.price), returnUrl: p.returnUrl, test });
428
+ userErrorsOf("start the purchase", data.appPurchaseOneTimeCreate.userErrors);
429
+ if (!data.appPurchaseOneTimeCreate.confirmationUrl || !data.appPurchaseOneTimeCreate.appPurchaseOneTime)
430
+ throw new ShopifyBillingError("Shopify didn't return a confirmation URL.");
431
+ return { confirmationUrl: data.appPurchaseOneTimeCreate.confirmationUrl, purchaseId: data.appPurchaseOneTimeCreate.appPurchaseOneTime.id, test };
432
+ }
433
+ /** The store's one-time purchases of this app, newest first (the latest 50). */
434
+ export async function oneTimePurchases(shopify) {
435
+ const data = await shopify.graphql(`query BillingPurchases {
436
+ currentAppInstallation { oneTimePurchases(first: 50, sortKey: CREATED_AT, reverse: true) { nodes { id name status test createdAt price { amount currencyCode } } } } }`);
437
+ return data.currentAppInstallation.oneTimePurchases.nodes;
438
+ }
439
+ /** Whether the store has paid for the one-time purchase of this name (status ACTIVE). */
440
+ export async function hasPurchased(shopify, name) {
441
+ return (await oneTimePurchases(shopify)).some((p) => p.status === "ACTIVE" && p.name === name);
442
+ }
443
+ /**
444
+ * Credits the store against its future app charges (a refund, a goodwill gesture). Shopify takes it off what the
445
+ * store next owes the app; it's never paid out. A test credit outside production or on a development store.
446
+ */
447
+ export async function grantCredit(shopify, c) {
448
+ const test = await isTestCharge(shopify, c.test);
449
+ const data = await shopify.graphql(`
450
+ mutation BillingCredit($description: String!, $amount: MoneyInput!, $test: Boolean) {
451
+ appCreditCreate(description: $description, amount: $amount, test: $test) { appCredit { id } userErrors { field message } }
452
+ }`, { description: c.description, amount: money(c.amount), test });
453
+ userErrorsOf("grant the credit", data.appCreditCreate.userErrors);
454
+ if (!data.appCreditCreate.appCredit)
455
+ throw new ShopifyBillingError("Shopify didn't create the credit.");
456
+ return { id: data.appCreditCreate.appCredit.id, test };
457
+ }
265
458
  /**
266
459
  * The store and staff member behind a request from one of the app's pages in the Shopify admin, or null when it
267
460
  * carries no valid session token. App Bridge's `shopify.idToken()` gives the page its token; send it as
@@ -284,13 +477,15 @@ export async function verifyShopifySession(request, o = {}) {
284
477
  return null;
285
478
  if (!res.ok)
286
479
  throw new ApiError(json.error?.message ?? `Checking the session failed (${res.status}).`, res.status, json.error?.code ?? null);
287
- return { shop: json.shop, userId: json.userId, sessionId: json.sessionId, ...(json.preview ? { preview: json.preview } : {}) };
480
+ const api = createClient({ ...o, shop: json.shop, role: "shopify-app-users", session: { userId: json.userId } });
481
+ return { shop: json.shop, userId: json.userId, sessionId: json.sessionId, ...(json.preview ? { preview: json.preview } : {}), api };
288
482
  }
289
483
  const hex = (b) => Array.from(new Uint8Array(b), (x) => x.toString(16).padStart(2, "0")).join("");
290
484
  /**
291
- * A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or null for
292
- * anything else. Shopify's own signature was checked before it was passed on; this checks ours, so only a real
293
- * storefront request is trusted with a shop and customer.
485
+ * A storefront request Inference Bureau passed on from Shopify's app proxy (routes under web/app/proxy/), or from a
486
+ * customer account extension (web/app/extension/, `pathPrefix` "/extension"), or null for anything else. Shopify's
487
+ * own signature (the extension's session token) was checked before it was passed on; this checks ours, so only a
488
+ * real storefront request is trusted with a shop and customer.
294
489
  */
295
490
  export async function verifyProxyRequest(request, o = {}) {
296
491
  const token = o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? "";
@@ -304,5 +499,38 @@ export async function verifyProxyRequest(request, o = {}) {
304
499
  let d = got.length ^ want.length;
305
500
  for (let i = 0; i < Math.min(got.length, want.length); i++)
306
501
  d |= got.charCodeAt(i) ^ want.charCodeAt(i);
307
- return d === 0 ? { shop, customerId: customer || null, pathPrefix: prefix } : null;
502
+ if (d !== 0)
503
+ return null;
504
+ const { now: _now, ...client } = o;
505
+ const api = createClient({ ...client, token, shop, role: "storefront-shoppers", session: { customerId: customer || null } });
506
+ return { shop, customerId: customer || null, pathPrefix: prefix, api };
507
+ }
508
+ /**
509
+ * The signed-in customer behind a storefront request (the app proxy, or a customer account extension), or null for a
510
+ * guest or anything that isn't a storefront request. Their shopifyCustomer record comes with them.
511
+ *
512
+ * const me = await verifyCustomerRequest(request);
513
+ * if (!me) return Response.json({ error: "Sign in to see your wishlist." }, { status: 401 });
514
+ * const items = await me.api.wishlistItem.findMany(); // theirs only
515
+ */
516
+ export async function verifyCustomerRequest(request, o = {}) {
517
+ const proxied = await verifyProxyRequest(request, o);
518
+ if (!proxied?.customerId)
519
+ return null;
520
+ const token = o.token ?? envVar("IB_ENVIRONMENT_TOKEN") ?? "";
521
+ const { now: _now, ...client } = o;
522
+ const url = (o.url ?? envVar("IB_API_URL") ?? "https://api.inferencebureau.com").replace(/\/$/, "");
523
+ const app = o.app ?? envVar("IB_APP") ?? "", environment = o.environment ?? envVar("IB_ENVIRONMENT") ?? "development";
524
+ const res = await (o.fetch ?? fetch)(`${url}/v1/apps/${encodeURIComponent(app)}/environments/${encodeURIComponent(environment)}/shopify/customer`, {
525
+ method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ shop: proxied.shop, customerId: proxied.customerId }),
526
+ });
527
+ const json = (await res.json().catch(() => ({})));
528
+ if (!res.ok)
529
+ throw new ApiError(json.error?.message ?? `Looking up the customer failed (${res.status}).`, res.status, json.error?.code ?? null);
530
+ const customer = json.customer ?? null;
531
+ const api = createClient({ ...client, token, shop: proxied.shop, role: "storefront-customers", session: { customerId: proxied.customerId, customerRecordId: customer?.id ?? null } });
532
+ return {
533
+ shop: proxied.shop, customerId: proxied.customerId, customerGid: json.customerGid ?? `gid://shopify/Customer/${proxied.customerId}`, customer,
534
+ source: proxied.pathPrefix === "/extension" ? "extension" : "proxy", api,
535
+ };
308
536
  }
package/dist/runtime.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * signature, runs the action file, and answers with what `run` asked to happen to the record. Inference Bureau
5
5
  * applies that in one transaction, then calls again for `onSuccess` with the saved record.
6
6
  */
7
- import { type ActionModule, type Api, type AppRecord, type LogLine, type ShopifyClient } from "./index.js";
7
+ import { type ActionCaller, type ActionModule, type Api, type AppRecord, type LogLine, type ShopifyClient } from "./index.js";
8
8
  /** Action modules by key: `<model>/<action>` for model actions, `$global/<action>` for global ones. */
9
9
  export type ActionRegistry = Record<string, () => Promise<ActionModule>>;
10
10
  export interface ActionRequest {
@@ -18,6 +18,10 @@ 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;
23
+ /** Who called, when the call was held to a role. */
24
+ caller?: ActionCaller | null;
21
25
  }
22
26
  export type ActionResponse = {
23
27
  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
+ 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,
51
53
  };
52
54
  if (req.phase === "onSuccess") {
53
55
  await mod.onSuccess?.(ctx);
package/dist/test.d.ts CHANGED
@@ -11,8 +11,11 @@
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
- import { ApiError, type ActionModule, type Api, type AppRecord, type AppSettings, type Job, type LogLine, type ModelSchema } from "./index.js";
18
+ import { ApiError, type ActionModule, type Api, type AppRecord, type AppSettings, type Job, type LogLine, type ModelSchema, type SyncRun } from "./index.js";
16
19
  type Embed = (model: string, input: string[]) => Promise<number[][]>;
17
20
  /** The store a test app installs on and runs as, unless a test names another. */
18
21
  export declare const TEST_SHOP = "test-shop.myshopify.com";
@@ -230,6 +233,8 @@ export interface TestApp {
230
233
  }): Promise<TestRun[]>;
231
234
  /** Jobs `api.enqueue` queued, in order. */
232
235
  jobs: Job[];
236
+ /** Shopify sync runs `api.shopifySync.run` started, in order (each succeeds at once, writing nothing). */
237
+ syncRuns: SyncRun[];
233
238
  /** Runs every queued job once (and the ones they queue), whatever its delay. A failed job stays queued while it has tries left. */
234
239
  runJobs(): Promise<Job[]>;
235
240
  shopify: ShopifyMock;
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: f.type === "file" ? "file fields can't be written yet" : `a ${f.type} field isn't stored on this record` });
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
- const modelClient = (name) => ({
765
- findOne: async (id) => store.findOne(name, id),
766
- findMany: async (q = {}) => store.findMany(name, wire(q)),
767
- findFirst: async (q = {}) => (await store.findMany(name, { ...wire(q), first: 1 })).records[0] ?? null,
768
- search: async (field, near, q = {}) => (await store.findMany(name, { ...wire(q), search: { field, near } })),
769
- // As through the API: the model's create, update or delete action when it has one, else a direct write.
770
- create: async (values) => (registry[`${name}/create`] ? (await run(name, "create", { params: values })).record : store.create(name, wire(values))),
771
- update: async (id, values) => (registry[`${name}/update`] ? (await run(name, "update", { id, params: values })).record : store.update(name, id, wire(values))),
772
- delete: async (id) => { if (registry[`${name}/delete`])
773
- await run(name, "delete", { id });
774
- else
775
- store.delete(name, id); },
776
- checkPassword: async (id, password, field) => store.checkPassword(name, id, password, field),
777
- run: async (action, q = {}) => {
778
- const r = await run(name, action, q);
779
- return { record: r.record, ...(r.result !== undefined ? { result: r.result } : {}) };
780
- },
781
- });
782
- const clients = new Map();
783
- const $global = async (action, params = {}) => {
784
- const r = await run(null, action, { params });
785
- return r.result !== undefined ? { result: r.result } : {};
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,70 @@ export function createTestApp(o = {}) {
794
892
  jobs.push(job);
795
893
  return wire(job);
796
894
  };
797
- const api = new Proxy({}, {
798
- get(_t, prop) {
799
- if (prop === "$global")
800
- return $global;
801
- if (prop === "enqueue")
802
- return enqueue;
803
- if (typeof prop !== "string" || prop === "then")
804
- return undefined;
805
- if (!clients.has(prop))
806
- clients.set(prop, modelClient(prop));
807
- return clients.get(prop);
808
- },
809
- });
895
+ // Runs succeed at once and write nothing: a test sees what was asked for in `syncRuns`.
896
+ const shopifySync = (shop) => {
897
+ const find = (id) => syncRuns.find((r) => r.id === id) ?? null;
898
+ return {
899
+ run: async ({ wait: _wait, since, ...q }) => {
900
+ const target = q.shop ?? shop;
901
+ if (!target)
902
+ throw new ApiError("Name the store: shop.", 400, "invalid_request");
903
+ if (shop && target !== shop)
904
+ throw otherStore(shop);
905
+ const at = new Date((o.now ?? Date.now)()).toISOString();
906
+ const r = {
907
+ id: `syn_${String(syncRuns.length + 1).padStart(6, "0")}`, shop: target, models: q.models?.length ? q.models : null, since: since === undefined ? null : new Date(since).toISOString(),
908
+ runActions: q.runActions ?? true, force: q.force ?? false, state: "succeeded", abortRequested: false, counts: {}, error: null, actor: "test", source: "api", createdAt: at, heartbeatAt: at, finishedAt: at,
909
+ };
910
+ syncRuns.push(r);
911
+ return r;
912
+ },
913
+ get: async (id) => find(id),
914
+ list: async (q = {}) => syncRuns.filter((r) => !(q.shop ?? shop) || r.shop === (q.shop ?? shop)).reverse().slice(0, q.limit ?? 50),
915
+ abort: async (id) => { const r = find(id); if (!r)
916
+ throw notFound(`There's no sync run ${id}.`); return r; },
917
+ };
918
+ };
919
+ const syncRuns = [];
920
+ const apis = new Map();
921
+ /** The API, for every store or one (`forShop`). Roles aren't applied here: `asRole` gives the same API. */
922
+ const apiFor = (shop) => {
923
+ const key = shop ?? "";
924
+ if (apis.has(key))
925
+ return apis.get(key);
926
+ const clients = new Map();
927
+ const $global = async (action, params = {}) => {
928
+ const r = await run(null, action, { params, ...(shop ? { shop } : {}) });
929
+ return r.result !== undefined ? { result: r.result } : {};
930
+ };
931
+ const queue = (action, params = {}, q = {}) => {
932
+ if (shop && q.shop && q.shop !== shop)
933
+ throw otherStore(shop);
934
+ return enqueue(action, params, shop ? { ...q, shop } : q);
935
+ };
936
+ const made = new Proxy({}, {
937
+ get(_t, prop) {
938
+ if (prop === "$global")
939
+ return $global;
940
+ if (prop === "enqueue")
941
+ return queue;
942
+ if (prop === "forShop")
943
+ return (s) => apiFor(s);
944
+ if (prop === "asRole")
945
+ return () => made;
946
+ if (prop === "shopifySync")
947
+ return shopifySync(shop);
948
+ if (typeof prop !== "string" || prop === "then")
949
+ return undefined;
950
+ if (!clients.has(prop))
951
+ clients.set(prop, modelClient(prop, shop));
952
+ return clients.get(prop);
953
+ },
954
+ });
955
+ apis.set(key, made);
956
+ return made;
957
+ };
958
+ const api = apiFor(null);
810
959
  // ---- Shopify's side ----
811
960
  const shopModel = () => models.get("shopifyShop");
812
961
  const shopRecord = async (shop) => (shopModel()?.byName.has("myshopifyDomain") ? (await store.findMany("shopifyShop", { filter: { myshopifyDomain: { equals: shop } }, first: 1 })).records[0] ?? null : null);
@@ -960,10 +1109,11 @@ export function createTestApp(o = {}) {
960
1109
  uninstall: (shop = TEST_SHOP) => shopHook(shop, "uninstall", { state: "uninstalled", uninstalledAt: iso((o.now ?? Date.now)()) }),
961
1110
  webhook,
962
1111
  jobs,
1112
+ syncRuns,
963
1113
  runJobs,
964
1114
  shopify,
965
1115
  logs,
966
- reset() { store.clear(); jobs.length = 0; logs.length = 0; shopify.calls.length = 0; },
1116
+ reset() { store.clear(); jobs.length = 0; syncRuns.length = 0; logs.length = 0; shopify.calls.length = 0; },
967
1117
  };
968
1118
  }
969
1119
  // ---- loading an app's folder ----
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@inferencebureau/apps-sdk",
3
- "version": "0.2.2",
3
+ "version": "0.4.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": [