@shop-on/theme-server 0.13.1 → 0.14.0-next.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.
@@ -0,0 +1,163 @@
1
+ import { BUYER_SESSION_HEADER } from "./api-contract/src/storefront/customer.js";
2
+ import { extractClientIp } from "./analytics-proxy.js";
3
+ import { checkSameOriginRequest } from "./csrf.js";
4
+ import { readCustomerSession } from "./customer-session.js";
5
+ import { readPasswordGate } from "./password.js";
6
+ import { storefrontApiUrl, storefrontKey } from "./storefront.js";
7
+ import { requestTraceHeaders } from "./trace.js";
8
+ import { shardBuyerHeaders } from "@shop-on/customer-runtime/relay";
9
+ // src/app-proxy.ts
10
+ /** The api mount's own body cap (`apps/api/src/server.ts`, APP_PROXY_PATH). */
11
+ const MAX_REQUEST_BYTES = 262144;
12
+ const TIMEOUT_MS = 7e3;
13
+ const FORWARDED_HEADERS = [
14
+ "Content-Type",
15
+ "Accept",
16
+ "Accept-Language",
17
+ "User-Agent"
18
+ ];
19
+ const BODY_METHODS = /* @__PURE__ */ new Set(["POST", "PUT"]);
20
+ /** What the api passes of an app's answer (`ALLOWED_RESPONSE_HEADERS` in its forward). */
21
+ const APP_RESPONSE_HEADERS = [
22
+ "content-type",
23
+ "cache-control",
24
+ "expires",
25
+ "etag",
26
+ "last-modified",
27
+ "vary",
28
+ "location",
29
+ "content-disposition",
30
+ "content-language"
31
+ ];
32
+ /** What a refusal needs beside its JSON: the 405's `Allow`, the 503's `Retry-After`. */
33
+ const REFUSAL_HEADERS = [
34
+ "content-type",
35
+ "allow",
36
+ "retry-after"
37
+ ];
38
+ const SANDBOX = {
39
+ "Content-Security-Policy": "sandbox",
40
+ "X-Content-Type-Options": "nosniff"
41
+ };
42
+ function refuse(status, error) {
43
+ return Response.json({ error }, {
44
+ status,
45
+ headers: {
46
+ "Cache-Control": "no-store",
47
+ ...SANDBOX
48
+ }
49
+ });
50
+ }
51
+ /** The storefront's public origin, as the buyer sees it (custom domain included). */
52
+ async function requestOrigin() {
53
+ const { getRequestUrl } = await import("@tanstack/react-start/server");
54
+ return getRequestUrl({
55
+ xForwardedHost: true,
56
+ xForwardedProto: true
57
+ }).origin;
58
+ }
59
+ async function readBoundedBody(request) {
60
+ if (Number(request.headers.get("content-length") ?? 0) > 262144) return null;
61
+ if (!request.body) return /* @__PURE__ */ new Uint8Array(0);
62
+ const reader = request.body.getReader();
63
+ const chunks = [];
64
+ let size = 0;
65
+ for (;;) {
66
+ const { done, value } = await reader.read();
67
+ if (done) break;
68
+ size += value.byteLength;
69
+ if (size > 262144) {
70
+ await reader.cancel().catch(() => {});
71
+ return null;
72
+ }
73
+ chunks.push(value);
74
+ }
75
+ const body = new Uint8Array(size);
76
+ let offset = 0;
77
+ for (const chunk of chunks) {
78
+ body.set(chunk, offset);
79
+ offset += chunk.byteLength;
80
+ }
81
+ return body;
82
+ }
83
+ function envelopeHeaders(input, key) {
84
+ const { request } = input;
85
+ const headers = {
86
+ Authorization: `Bearer ${key}`,
87
+ "Content-Type": "application/octet-stream",
88
+ "X-App-Proxy-Prefix": input.prefix,
89
+ "X-App-Proxy-Subpath": input.subpath,
90
+ "X-App-Proxy-Path": input.path,
91
+ "X-App-Proxy-Query": input.query,
92
+ "X-App-Proxy-Method": request.method,
93
+ ...requestTraceHeaders(),
94
+ ...input.clientIp ? { "X-Forwarded-For": input.clientIp } : {},
95
+ ...shardBuyerHeaders()
96
+ };
97
+ for (const name of FORWARDED_HEADERS) {
98
+ const value = request.headers.get(name);
99
+ if (value) headers[`X-App-Proxy-${name}`] = value;
100
+ }
101
+ if (input.customerSessionToken) headers[BUYER_SESSION_HEADER] = input.customerSessionToken;
102
+ return headers;
103
+ }
104
+ async function isRefusal(res) {
105
+ if (!res.headers.get("content-type")?.includes("application/json")) return false;
106
+ return typeof (await res.clone().json().catch(() => null))?.error === "string";
107
+ }
108
+ function cacheControl(input, upstream) {
109
+ if (input.customerSessionToken || input.request.method !== "GET") return "private, no-store";
110
+ return upstream ?? "no-store";
111
+ }
112
+ async function proxyAppRequest(input) {
113
+ let body;
114
+ if (BODY_METHODS.has(input.request.method)) {
115
+ const read = await readBoundedBody(input.request);
116
+ if (!read) return refuse(413, "request_too_large");
117
+ body = read;
118
+ }
119
+ const key = storefrontKey();
120
+ let res;
121
+ try {
122
+ res = await fetch(`${storefrontApiUrl()}/storefront/app_proxy`, {
123
+ method: "POST",
124
+ headers: envelopeHeaders(input, key),
125
+ body,
126
+ redirect: "manual",
127
+ signal: AbortSignal.timeout(TIMEOUT_MS)
128
+ });
129
+ } catch (err) {
130
+ console.warn(`[app-proxy] api unreachable: ${err instanceof Error ? err.name : "error"}`);
131
+ return refuse(502, "app_unreachable");
132
+ }
133
+ const app = res.headers.get("x-app-proxy-answer") === "app";
134
+ if (!app && !await isRefusal(res)) {
135
+ console.warn(`[app-proxy] api answered ${res.status} without an app answer or a refusal`);
136
+ await res.body?.cancel().catch(() => {});
137
+ return refuse(502, "app_unreachable");
138
+ }
139
+ const headers = new Headers();
140
+ for (const name of app ? APP_RESPONSE_HEADERS : REFUSAL_HEADERS) {
141
+ const value = res.headers.get(name);
142
+ if (value !== null) headers.set(name, value);
143
+ }
144
+ headers.set("Cache-Control", cacheControl(input, res.headers.get("cache-control")));
145
+ for (const [name, value] of Object.entries(SANDBOX)) headers.set(name, value);
146
+ return new Response(res.body, {
147
+ status: res.status,
148
+ headers
149
+ });
150
+ }
151
+ /** What `appProxyHandler` (`@shop-on/theme-routes`) takes. Only a theme's
152
+ * `/<prefix>/$` route files import it, and the client build deletes their
153
+ * `server` key and prunes them from the client route tree, so none of this
154
+ * reaches the browser. */
155
+ const appProxyDeps = {
156
+ proxyAppRequest,
157
+ readCustomerSession,
158
+ extractClientIp,
159
+ requestOrigin,
160
+ checkSameOriginRequest,
161
+ readPasswordGate
162
+ };
163
+ export { MAX_REQUEST_BYTES, appProxyDeps, proxyAppRequest, requestOrigin };
package/dist/card.js CHANGED
@@ -109,9 +109,18 @@ function cardFields(p, baseWidth) {
109
109
  rating: p.rating && {
110
110
  value: p.rating.value,
111
111
  count: p.rating.count
112
- }
112
+ },
113
+ ...buyButtonClaims(p)
113
114
  };
114
115
  }
116
+ /**
117
+ * The apps claiming a product's buy button, as every theme-side shape carries
118
+ * them: present only when one does. Absent from an api deployed before the
119
+ * claim, which reads as no app claiming it. The one read of the field.
120
+ */
121
+ function buyButtonClaims(p) {
122
+ return p.buyButtonAppIds?.length ? { buyButtonAppIds: p.buyButtonAppIds } : {};
123
+ }
115
124
  /** A card as every card surface and listing grid reads it. */
116
125
  function toCard(c) {
117
126
  return {
@@ -156,4 +165,4 @@ function readCard(ref, shape, locale) {
156
165
  })).items;
157
166
  });
158
167
  }
159
- export { cardFields, cardShape, compareAt, productRef, readCard, shapeKey, swatchImageUrl, toCard, toOption };
168
+ export { buyButtonClaims, cardFields, cardShape, compareAt, productRef, readCard, shapeKey, swatchImageUrl, toCard, toOption };
@@ -1,5 +1,5 @@
1
1
  import { CartData } from "./cart.js";
2
- import { CartFailure } from "./cart-mutations.js";
2
+ import { CartActionResult, CartFailure, CartLineInput } from "./cart-mutations.js";
3
3
  export type CartCustomerCookieSession = {
4
4
  data: {
5
5
  token?: string;
@@ -21,4 +21,13 @@ export declare function mintOrClaimCart(args: {
21
21
  }): Promise<{
22
22
  ok: true;
23
23
  token: string;
24
- } | CartFailure>;
24
+ } | CartFailure>;
25
+ /** Add several lines in one `cartLinesAdd`, to the cart in this request's
26
+ * cookie, opening (or claiming) one first as `mintOrClaimCart` does. Lines
27
+ * under quantity 1 are dropped; when none is left the add is refused as
28
+ * `INVALID_QUANTITY` with the theme's `emptyMessage`, and nothing is sent.
29
+ * Each line goes as its `variantId`, `quantity` and `customAttributes`. */
30
+ export declare function addLinesToSessionCart(args: {
31
+ lines: CartLineInput[];
32
+ emptyMessage: string;
33
+ }): Promise<CartActionResult>;
@@ -1,5 +1,7 @@
1
1
  import { isCartGone, toCart } from "./cart.js";
2
- import { mintCart } from "./cart-mutations.js";
2
+ import { addLines, mintCart } from "./cart-mutations.js";
3
+ import { useCartSession } from "./cart-session.js";
4
+ import { readCustomerSession } from "./customer-session.js";
3
5
  import { StorefrontConfigError, buyerStorefront, errorCode } from "./storefront.js";
4
6
  // src/cart-customer.ts
5
7
  /** What `cart.attach` answers about the carts themselves: the guest cart is
@@ -58,6 +60,40 @@ async function mintOrClaimCart(args) {
58
60
  token: minted.token
59
61
  };
60
62
  }
63
+ /** Add several lines in one `cartLinesAdd`, to the cart in this request's
64
+ * cookie, opening (or claiming) one first as `mintOrClaimCart` does. Lines
65
+ * under quantity 1 are dropped; when none is left the add is refused as
66
+ * `INVALID_QUANTITY` with the theme's `emptyMessage`, and nothing is sent.
67
+ * Each line goes as its `variantId`, `quantity` and `customAttributes`. */
68
+ async function addLinesToSessionCart(args) {
69
+ const lines = args.lines.filter((line) => line.quantity >= 1);
70
+ if (lines.length === 0) return {
71
+ ok: false,
72
+ code: "INVALID_QUANTITY",
73
+ resource: null,
74
+ message: args.emptyMessage
75
+ };
76
+ const session = await useCartSession();
77
+ const customerToken = (await readCustomerSession())?.token;
78
+ let token = session.data.token;
79
+ if (!token) {
80
+ const resolved = await mintOrClaimCart({
81
+ session,
82
+ customerToken
83
+ });
84
+ if (!resolved.ok) return resolved;
85
+ token = resolved.token;
86
+ }
87
+ return addLines({
88
+ session,
89
+ token,
90
+ lines: lines.map((line) => ({
91
+ variantId: line.variantId,
92
+ quantity: line.quantity,
93
+ customAttributes: line.customAttributes
94
+ }))
95
+ });
96
+ }
61
97
  async function claim(session, api) {
62
98
  let answer;
63
99
  try {
@@ -82,4 +118,4 @@ async function claim(session, api) {
82
118
  function claimed(result) {
83
119
  return result?.cart ?? null;
84
120
  }
85
- export { mintOrClaimCart, resolveCartForCustomer };
121
+ export { addLinesToSessionCart, mintOrClaimCart, resolveCartForCustomer };
package/dist/cart.d.ts CHANGED
@@ -22,6 +22,9 @@ export type CartLine = {
22
22
  available: boolean;
23
23
  /** Units the shop can sell; null when nothing bounds them. */
24
24
  quantityAvailable: number | null;
25
+ /** Until when an app holds the line (ISO time; docs/cart-holds.md), null when
26
+ * none does. Its quantity is the app's, and it leaves the cart at that time. */
27
+ holdExpiresAt: string | null;
25
28
  variant: {
26
29
  id: string;
27
30
  /** Its option values joined by " / "; empty without options. */
package/dist/cart.js CHANGED
@@ -41,6 +41,7 @@ function toCart(cart) {
41
41
  discount: toMoney(line.discount),
42
42
  available: line.available,
43
43
  quantityAvailable: line.quantityAvailable,
44
+ holdExpiresAt: line.holdExpiresAt ?? null,
44
45
  variant: {
45
46
  id: line.variant.id,
46
47
  title: line.variant.title,
@@ -5,6 +5,7 @@ import { Money } from "@shop-on/theme-runtime/money";
5
5
  import { ListingFilters } from "@shop-on/theme-runtime/listing-filters";
6
6
  import { ProductOption } from "@shop-on/theme-runtime/product-variants";
7
7
  export type CollectionProductData = {
8
+ buyButtonAppIds?: string[];
8
9
  id?: string;
9
10
  handle: string;
10
11
  title: string;
@@ -37,9 +37,11 @@ export type ProcedureAccess<TPermission extends string = string> = {
37
37
  * `mount` is the edge's own, never a procedure's: every request to a mount
38
38
  * counts against it before anything else runs. `mcp-write` is the MCP
39
39
  * mount's own too: each call of a writing tool, per connection;
40
- * `app-token-exchange` lite's `/oauth/app_token` mount's, per address.
40
+ * `app-token-exchange` lite's `/oauth/app_token` mount's, per address;
41
+ * `app-proxy` lite's `/storefront/app_proxy` mount's, per buyer address
42
+ * and per app in the shop.
41
43
  */
42
- export declare const RATE_LIMIT_CLASSES: readonly ["sign-in", "app-token-exchange", "code-send", "code-redeem", "link-write", "provider-callback", "courier-webhook", "billing-webhook", "provider-push", "promo-guess", "gift-card-guess", "register-gift-card-guess", "gift-card-reveal", "theme-submission", "payout-write", "public-read", "image-size", "read", "write", "storefront", "storefront-unlock", "register-pin", "driver-sign-in", "storefront-review", "storefront-contact", "storefront-newsletter", "storefront-sitemap", "storefront-analytics", "storefront-cart", "buyer-write", "buyer-email-change", "google-nonce", "expensive", "checkpoint", "editor-presence", "webhook-create", "webhook-update", "webhook-delete", "webhook-test", "webhook-redeliver", "webhook-rotate", "editor-bell", "feedback", "sticker", "mcp-write", "mount"];
44
+ export declare const RATE_LIMIT_CLASSES: readonly ["sign-in", "app-token-exchange", "app-proxy", "code-send", "code-redeem", "link-write", "provider-callback", "courier-webhook", "billing-webhook", "provider-push", "register-push", "promo-guess", "gift-card-guess", "register-gift-card-guess", "gift-card-reveal", "theme-submission", "payout-write", "public-read", "image-size", "read", "write", "storefront", "storefront-unlock", "register-pin", "driver-sign-in", "storefront-review", "storefront-contact", "storefront-newsletter", "storefront-sitemap", "storefront-analytics", "storefront-cart", "buyer-write", "buyer-email-change", "google-nonce", "expensive", "checkpoint", "editor-presence", "webhook-create", "webhook-update", "webhook-delete", "webhook-test", "webhook-redeliver", "webhook-rotate", "editor-bell", "feedback", "sticker", "mcp-write", "mount"];
43
45
  export type RateLimitClass = (typeof RATE_LIMIT_CLASSES)[number];
44
46
  /**
45
47
  * A procedure's class, or for a class counted per identifier (`sign-in`,
package/dist/csrf.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export type OriginCheck = {
2
+ ok: true;
3
+ } | {
4
+ ok: false;
5
+ reason: "missing_origin" | "malformed_origin" | "origin_mismatch" | "cross_site_fetch";
6
+ };
7
+ export declare function checkSameOriginRequest(headers: Headers, expectedOrigin: string): OriginCheck;
package/dist/csrf.js CHANGED
@@ -17,4 +17,14 @@ function checkOrigin(originHeader, expectedOrigin) {
17
17
  };
18
18
  }
19
19
  }
20
- export { checkOrigin };
20
+ function checkSameOriginRequest(headers, expectedOrigin) {
21
+ const origin = checkOrigin(headers.get("origin"), expectedOrigin);
22
+ if (!origin.ok) return origin;
23
+ const site = headers.get("sec-fetch-site");
24
+ if (site !== null && site !== "same-origin") return {
25
+ ok: false,
26
+ reason: "cross_site_fetch"
27
+ };
28
+ return { ok: true };
29
+ }
30
+ export { checkOrigin, checkSameOriginRequest };
package/dist/product.d.ts CHANGED
@@ -13,6 +13,7 @@ export type ProductRating = {
13
13
  }[];
14
14
  };
15
15
  export type ProductData = {
16
+ buyButtonAppIds?: string[];
16
17
  id?: string;
17
18
  handle: string;
18
19
  title: string;
package/dist/search.d.ts CHANGED
@@ -97,6 +97,9 @@ export type ProductSuggestion = {
97
97
  defaultVariantId?: string;
98
98
  available?: boolean;
99
99
  variantsCount?: number;
100
+ /** `ProductData.buyButtonAppIds`, with the add-or-choose fields: a claimed
101
+ * product's row opens its page. */
102
+ buyButtonAppIds?: string[];
100
103
  };
101
104
  /** The typeahead: product rows, the collection and content groups when the
102
105
  * caller asked for them (`resources`), and the term completions that go above
package/dist/search.js CHANGED
@@ -1,4 +1,4 @@
1
- import { cardShape, toCard } from "./card.js";
1
+ import { buyButtonClaims, cardShape, toCard } from "./card.js";
2
2
  import { imageFileInfo } from "./files.js";
3
3
  import { listingCard, listingInput, pageInput, toCollectionListItem, toFacets, toPriceBounds } from "./listing.js";
4
4
  import { toMoney } from "./money.js";
@@ -199,7 +199,8 @@ async function fetchSearchSuggestions(data) {
199
199
  ...quickAdd && {
200
200
  defaultVariantId: p.defaultVariant.id,
201
201
  available: p.defaultVariant.available,
202
- variantsCount: p.variantsCount
202
+ variantsCount: p.variantsCount,
203
+ ...buyButtonClaims(p)
203
204
  }
204
205
  };
205
206
  }),
@@ -22,6 +22,7 @@ function storefrontApiUrl() {
22
22
  assertServerOnly();
23
23
  return process.env.STOREFRONT_API_URL || "http://localhost:4000";
24
24
  }
25
+ /** The shop's storefront key, the credential of every api call a theme server makes. Never logged. */
25
26
  function storefrontKey() {
26
27
  const key = process.env.STOREFRONT_KEY || "";
27
28
  if (!key) throw new StorefrontConfigError("the storefront has no STOREFRONT_KEY");
@@ -196,4 +197,4 @@ function storefront(locale, headers = {}) {
196
197
  function buyerStorefront(session, locale) {
197
198
  return storefront(locale, { [BUYER_SESSION_HEADER]: session });
198
199
  }
199
- export { STOREFRONT_TIMEOUT_MS, StorefrontConfigError, assertServerOnly, buyerStorefront, errorCode, invalidField, lastSeenContentVersion, orFallback, orNotFound, shopUnavailableThisRequest, storefront, storefrontApiUrl };
200
+ export { STOREFRONT_TIMEOUT_MS, StorefrontConfigError, assertServerOnly, buyerStorefront, errorCode, invalidField, lastSeenContentVersion, orFallback, orNotFound, shopUnavailableThisRequest, storefront, storefrontApiUrl, storefrontKey };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shop-on/theme-server",
3
- "version": "0.13.1",
3
+ "version": "0.14.0-next.0",
4
4
  "license": "SEE LICENSE IN dist/LICENSE.md",
5
5
  "files": [
6
6
  "dist"
@@ -11,6 +11,7 @@
11
11
  "./activity": "./dist/activity.js",
12
12
  "./analytics-proxy": "./dist/analytics-proxy.js",
13
13
  "./analytics-script-proxy": "./dist/analytics-script-proxy.js",
14
+ "./app-proxy": "./dist/app-proxy.js",
14
15
  "./availability": "./dist/availability.js",
15
16
  "./blog": "./dist/blog.js",
16
17
  "./cache": "./dist/cache.js",
@@ -60,9 +61,9 @@
60
61
  "dependencies": {
61
62
  "@orpc/client": "1.16.2",
62
63
  "@orpc/contract": "1.16.2",
63
- "@shop-on/customer-runtime": "0.13.1",
64
- "@shop-on/theme-contract": "0.13.1",
65
- "@shop-on/theme-runtime": "0.13.1",
64
+ "@shop-on/customer-runtime": "0.14.0-next.0",
65
+ "@shop-on/theme-contract": "0.14.0-next.0",
66
+ "@shop-on/theme-runtime": "0.14.0-next.0",
66
67
  "liquidjs": "10.30.1",
67
68
  "zod": "4.6.7"
68
69
  },